cmdline.spec.ts 7.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198
  1. /**
  2. * The launcher-to-app command line over a REAL Loader tree, mounted the way a
  3. * profile boot mounts it: Loader holds each row until its injections are
  4. * active, then resolves that row's config against its injection-ready context.
  5. */
  6. import { mkdtempSync, writeFileSync } from 'node:fs'
  7. import { tmpdir } from 'node:os'
  8. import { join } from 'node:path'
  9. import { pathToFileURL } from 'node:url'
  10. import { Command } from 'commander'
  11. import { Context } from '@deepseek-ai/cordis'
  12. import Loader from '@deepseek-ai/cordis-plugin-loader'
  13. import Include from '@deepseek-ai/cordis-plugin-include'
  14. import type { PatchOptions } from '@deepseek-ai/cordis-plugin-include'
  15. import { afterEach, describe, expect, it } from 'vitest'
  16. import { internals, parseCmdline, provideCmdline, type CmdlinePlan } from '../src/index.ts'
  17. /** Every value one boot of the fixture tree observed. */
  18. interface Observed {
  19. /** Config the reading row started with; absent means it never started. */
  20. started?: Record<string, unknown>
  21. exits: number[]
  22. out: string
  23. }
  24. /** A booted fixture tree: what it observed, and its root for direct parser calls. */
  25. interface Fixture {
  26. observed: Observed
  27. ctx: Context
  28. }
  29. const disposers: (() => Promise<void>)[] = []
  30. afterEach(async () => {
  31. for (const dispose of disposers.splice(0)) await dispose()
  32. internals.stdout = process.stdout
  33. internals.stderr = process.stderr
  34. })
  35. /** The fixture app's flag family: one `--port` its rows read from the service. */
  36. function demoCommand(): Command {
  37. return new Command().name('demo').exitOverride().option('--port <port>', 'listen port')
  38. }
  39. /** The fixture app's plan: the resolved values its rows read. */
  40. const demoPlan: CmdlinePlan<{ port?: number }> = (program) => {
  41. const port = program.opts<{ port?: string }>().port
  42. if (port === undefined) return {}
  43. if (!/^\d+$/.test(port)) program.error(`error: --port must be a number, got ${JSON.stringify(port)}`)
  44. return { port: Number(port) }
  45. }
  46. /** A YAML `!!js` expression node, as the include parses one out of a patch file. */
  47. const expression = (source: string): unknown => ({ __jsExpr: source })
  48. /**
  49. * Mount a two-row composition the way a profile boot does: both rows at once,
  50. * with Loader ordering config resolution from their injections.
  51. * @param args - the invocation's inner arguments.
  52. * @param plan - the app's plan; defaults to the fixture's own.
  53. * @returns the booted fixture.
  54. */
  55. async function bootFixture(
  56. args: string[],
  57. plan: CmdlinePlan = demoPlan,
  58. options: { objectInject?: boolean; withoutProvider?: boolean } = {},
  59. ): Promise<Fixture> {
  60. const dir = mkdtempSync(join(tmpdir(), 'dsh-cmdline-'))
  61. const observed: Observed = { exits: [], out: '' }
  62. writeFileSync(join(dir, 'reader.mjs'), `
  63. export const name = 'reader'
  64. export const inject = ['demoStartup']
  65. export function apply(ctx, config) { globalThis.__observed.started = config }
  66. `)
  67. // The Loader imports a row through Node's own resolver, which cannot resolve
  68. // this workspace's sources; the row delegates to the real function the test
  69. // imported through the source-plane path mapping.
  70. writeFileSync(join(dir, 'startup.mjs'), `
  71. export const name = 'demo-startup'
  72. export const inject = ['cmdlineArgs']
  73. export function apply(ctx) { return globalThis.__provideDemoArgs(ctx) }
  74. `)
  75. writeFileSync(join(dir, 'cordis.yml'), '[]\n')
  76. const observing = { write: (chunk: string) => { observed.out += chunk; return true } }
  77. internals.stdout = observing
  78. internals.stderr = observing
  79. const globals = globalThis as unknown as { __observed: Observed; __provideDemoArgs: (ctx: Context) => void }
  80. globals.__observed = observed
  81. globals.__provideDemoArgs = (ctx: Context) => {
  82. const values = parseCmdline(ctx, demoCommand(), plan)
  83. if (values !== undefined) ctx.provide('demoStartup', values)
  84. }
  85. // The composition, exactly as a profile delivers one: include patches whose
  86. // config carries `!!js` expressions.
  87. const composition: PatchOptions[] = [{
  88. insert: [
  89. ...options.withoutProvider === true
  90. ? []
  91. : [{ id: 'demo-startup', name: pathToFileURL(join(dir, 'startup.mjs')).href }],
  92. {
  93. id: 'reader',
  94. name: pathToFileURL(join(dir, 'reader.mjs')).href,
  95. inject: options.objectInject === true ? { demoStartup: { required: true } } : ['demoStartup'],
  96. config: { port: expression('ctx.demoStartup.port ?? 3080') },
  97. },
  98. ],
  99. }]
  100. const ctx = new Context()
  101. await ctx.plugin(Loader)
  102. ctx.loader.builtins.include = Include
  103. provideCmdline(ctx, { args, exit: code => void observed.exits.push(code) })
  104. await ctx.loader.create({
  105. name: 'cordis:include',
  106. config: { path: pathToFileURL(join(dir, 'cordis.yml')).href, patches: structuredClone(composition) },
  107. })
  108. await ctx.loader.await()
  109. disposers.push(async () => { await ctx.fiber.dispose() })
  110. return { observed, ctx }
  111. }
  112. describe('parseCmdline', () => {
  113. it('lets a row read the flag value the app resolved', async () => {
  114. const { observed } = await bootFixture(['--port', '8080'])
  115. expect(observed.started).toEqual({ port: 8080 })
  116. expect(observed.exits).toEqual([])
  117. })
  118. it('leaves a row on the value written beside the expression when no flag names one', async () => {
  119. const { observed } = await bootFixture([])
  120. expect(observed.started).toEqual({ port: 3080 })
  121. })
  122. it('recognizes the Loader object form of a provider-service injection', async () => {
  123. const { observed } = await bootFixture(['--port', '8080'], demoPlan, { objectInject: true })
  124. expect(observed.started).toEqual({ port: 8080 })
  125. })
  126. it('prints the app help, starts no reading row, and requests exit 0', async () => {
  127. const { observed } = await bootFixture(['--help'])
  128. expect(observed.out).toContain('Usage: demo')
  129. expect(observed.started).toBeUndefined()
  130. expect(observed.exits).toEqual([0])
  131. })
  132. it('rejects the invocation from the plan without starting the app', async () => {
  133. const { observed } = await bootFixture(['--port', 'abc'])
  134. expect(observed.out).toContain('--port must be a number')
  135. expect(observed.started).toBeUndefined()
  136. expect(observed.exits).toEqual([1])
  137. })
  138. it('rethrows a plan failure that is not commander asking to exit', async () => {
  139. const { ctx } = await bootFixture([], demoPlan, { withoutProvider: true })
  140. const plan: CmdlinePlan = () => { throw new Error('plan exploded') }
  141. expect(() => { parseCmdline(ctx, demoCommand(), plan) }).toThrow('plan exploded')
  142. })
  143. it('rethrows a thrown value that is not an object at all', async () => {
  144. const { ctx } = await bootFixture([], demoPlan, { withoutProvider: true })
  145. const plan: CmdlinePlan = () => {
  146. const thrown: unknown = 'plan threw a string'
  147. throw thrown
  148. }
  149. expect(() => { parseCmdline(ctx, demoCommand(), plan) }).toThrow('plan threw a string')
  150. })
  151. it('returns values without inspecting Loader rows or owning a service', async () => {
  152. const { ctx } = await bootFixture([], demoPlan, { withoutProvider: true })
  153. expect(parseCmdline(ctx, demoCommand())).toEqual({})
  154. expect(ctx.get('demoStartup')).toBeUndefined()
  155. })
  156. })
  157. describe('provideCmdline', () => {
  158. it('hands the app a snapshot the caller cannot mutate afterwards', () => {
  159. const ctx = new Context()
  160. const args = ['--resume', 'abc']
  161. provideCmdline(ctx, { args, exit: () => {} })
  162. args.push('--tampered')
  163. expect(ctx.cmdlineArgs?.get()).toEqual(['--resume', 'abc'])
  164. })
  165. it('fails loud when a parser runs without the launcher values', () => {
  166. const ctx = new Context()
  167. expect(() => { parseCmdline(ctx, demoCommand()) })
  168. .toThrow('the launcher must provide ctx.cmdlineArgs and ctx.appExit')
  169. })
  170. it('lets multiple parsers read the same immutable snapshot', () => {
  171. const ctx = new Context()
  172. provideCmdline(ctx, { args: ['--port', '8080'], exit: () => {} })
  173. expect(parseCmdline(ctx, demoCommand(), demoPlan)).toEqual({ port: 8080 })
  174. expect(parseCmdline(ctx, demoCommand(), demoPlan)).toEqual({ port: 8080 })
  175. expect(Object.isFrozen(ctx.cmdlineArgs?.get())).toBe(true)
  176. })
  177. })