@znight/cli 0.6.2 → 0.6.4
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +58 -25
- package/dist/cli.mjs +1 -1
- package/dist/index.d.mts +17 -6
- package/dist/index.mjs +1 -1
- package/dist/{main-DUyElIVZ.mjs → main-CLoS12u4.mjs} +452 -75
- package/dist/main-CLoS12u4.mjs.map +1 -0
- package/package.json +7 -7
- package/src/commands/dev.ts +23 -6
- package/src/commands/generate.ts +36 -27
- package/src/commands/new.ts +41 -8
- package/src/commands/start.ts +7 -2
- package/src/dev/supervisor.ts +38 -14
- package/src/scaffold/options.ts +37 -5
- package/src/scaffold/templates.ts +379 -24
- package/src/scaffold/versions.ts +2 -0
- package/dist/main-DUyElIVZ.mjs.map +0 -1
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"main-DUyElIVZ.mjs","names":["nodeSpawn","constants","printDiagnostics","watch","printDiagnostics"],"sources":["../src/errors.ts","../src/names.ts","../src/output.ts","../src/command.ts","../src/integrations/resolve.ts","../src/integrations/compiler.ts","../src/integrations/openapi.ts","../src/integrations/process.ts","../src/integrations/prompts.ts","../src/integrations/vite.ts","../src/integrations/watch.ts","../src/runtime.ts","../src/version.ts","../src/context.ts","../src/dev/supervisor.ts","../src/commands/shared.ts","../src/commands/build.ts","../src/commands/dev.ts","../src/commands/generate.ts","../src/scaffold/options.ts","../src/scaffold/create.ts","../src/scaffold/versions.ts","../src/scaffold/templates.ts","../src/commands/new.ts","../src/commands/openapi.ts","../src/schematics/index.ts","../src/commands/schematic.ts","../src/commands/start.ts","../src/main.ts"],"sourcesContent":["/**\n * Errors thrown by commands. The dispatcher turns them into a message on stderr and an exit code;\n * any other error is reported as an unexpected failure (exit code 1, stack trace with `--debug`).\n */\n\n/** Exit codes of the `znight` binary. */\nexport const ExitCode = {\n /** The command succeeded. */\n Ok: 0,\n /** The command failed (compilation errors, failed build, stale generated file...). */\n Failure: 1,\n /** Invalid usage: unknown command or option, missing or invalid argument. */\n Usage: 2,\n /** The user cancelled an interactive prompt or interrupted the command. */\n Cancelled: 130,\n} as const\n\n/** One of the {@link ExitCode} values (or any process exit code). */\nexport type ExitCodeValue = number\n\n/** Options of a {@link CliError}. */\nexport interface CliErrorOptions {\n /** Exit code of the process. Default {@link ExitCode.Failure}. */\n readonly exitCode?: number\n /** Lines printed after the message (`= hint: ...`). */\n readonly hints?: readonly string[]\n /** Original error. */\n readonly cause?: unknown\n}\n\n/** An expected failure: printed without stack trace. */\nexport class CliError extends Error {\n readonly exitCode: number\n readonly hints: readonly string[]\n\n constructor(message: string, options: CliErrorOptions = {}) {\n super(message, options.cause === undefined ? undefined : { cause: options.cause })\n this.name = 'CliError'\n this.exitCode = options.exitCode ?? ExitCode.Failure\n this.hints = options.hints ?? []\n }\n}\n\n/** Invalid command line usage (exit code 2). The usage of the command is printed after the message. */\nexport class UsageError extends CliError {\n constructor(message: string, hints: readonly string[] = []) {\n super(message, { exitCode: ExitCode.Usage, hints })\n this.name = 'UsageError'\n }\n}\n\n/** The user cancelled a prompt (exit code 130). */\nexport class CancelledError extends CliError {\n constructor(message = 'Cancelled') {\n super(message, { exitCode: ExitCode.Cancelled })\n this.name = 'CancelledError'\n }\n}\n\n/** Message of an unknown thrown value. */\nexport function errorMessage(error: unknown): string {\n if (error instanceof Error) return error.message\n return String(error)\n}\n","/**\n * Naming helpers shared by `znight new` and `znight g`: case conversions, npm package names,\n * \"did you mean\" suggestions.\n */\n\n/** Splits an identifier into lower-case words: `UserProfile`, `user_profile`, `HTTPClient` → words. */\nexport function words(name: string): string[] {\n return name\n .replace(/([a-z0-9])([A-Z])/g, '$1 $2')\n .replace(/([A-Z]+)([A-Z][a-z])/g, '$1 $2')\n .split(/[^A-Za-z0-9]+/)\n .filter(word => word !== '')\n .map(word => word.toLowerCase())\n}\n\n/** `user-profile` */\nexport function kebabCase(name: string): string {\n return words(name).join('-')\n}\n\n/** `UserProfile` */\nexport function pascalCase(name: string): string {\n return words(name)\n .map(word => word.charAt(0).toUpperCase() + word.slice(1))\n .join('')\n}\n\n/** `userProfile` */\nexport function camelCase(name: string): string {\n const pascal = pascalCase(name)\n return pascal.charAt(0).toLowerCase() + pascal.slice(1)\n}\n\n/** `USER_PROFILE` */\nexport function constantCase(name: string): string {\n return words(name)\n .map(word => word.toUpperCase())\n .join('_')\n}\n\nconst PACKAGE_NAME = /^(?:@[a-z0-9][a-z0-9._~-]*\\/)?[a-z0-9][a-z0-9._~-]*$/\n\n/**\n * Validates an npm package name (lower case, URL-safe, at most 214 characters, optional scope).\n * Returns a problem description, or `undefined` when the name is valid.\n */\nexport function validatePackageName(name: string): string | undefined {\n if (name === '') return 'the name cannot be empty'\n if (name.length > 214) return 'the name cannot be longer than 214 characters'\n if (name !== name.trim()) return 'the name cannot start or end with spaces'\n if (name !== name.toLowerCase()) return 'the name must be lower case'\n if (name.startsWith('.') || name.startsWith('_')) return 'the name cannot start with \".\" or \"_\"'\n if (!PACKAGE_NAME.test(name)) {\n return 'the name may only contain lower-case letters, digits, \"-\", \".\", \"_\" and \"~\" (and an optional @scope/)'\n }\n return undefined\n}\n\n/** Turns any string into a valid package name candidate: `My App!` → `my-app`. */\nexport function toPackageName(name: string): string {\n return name\n .trim()\n .toLowerCase()\n .replace(/\\s+/g, '-')\n .replace(/^[._]+/, '')\n .replace(/[^a-z0-9@/._~-]+/g, '-')\n .replace(/-+/g, '-')\n .replace(/^-|-$/g, '')\n}\n\n/** The unscoped part of a package name: `@acme/api` → `api`. */\nexport function unscopedName(name: string): string {\n const slash = name.indexOf('/')\n return name.startsWith('@') && slash !== -1 ? name.slice(slash + 1) : name\n}\n\n/** Levenshtein distance (small strings only). */\nexport function editDistance(a: string, b: string): number {\n const previous = Array.from({ length: b.length + 1 }, (_, index) => index)\n for (let i = 1; i <= a.length; i++) {\n let diagonal = previous[0] ?? 0\n previous[0] = i\n for (let j = 1; j <= b.length; j++) {\n const above = previous[j] ?? 0\n const cost = a[i - 1] === b[j - 1] ? 0 : 1\n previous[j] = Math.min(above + 1, (previous[j - 1] ?? 0) + 1, diagonal + cost)\n diagonal = above\n }\n }\n return previous[b.length] ?? 0\n}\n\n/** The closest candidate within a distance of `max(2, length / 3)`, if any. */\nexport function suggest(input: string, candidates: Iterable<string>): string | undefined {\n let best: string | undefined\n let bestDistance = Number.POSITIVE_INFINITY\n const limit = Math.max(2, Math.floor(input.length / 3))\n for (const candidate of candidates) {\n const distance = editDistance(input.toLowerCase(), candidate.toLowerCase())\n if (distance < bestDistance && distance <= limit) {\n best = candidate\n bestDistance = distance\n }\n }\n return best\n}\n","/**\n * Terminal output: color detection (NO_COLOR, FORCE_COLOR, `--color` / `--no-color`, TTY), a small\n * reporter writing consistent status lines, and formatting helpers.\n */\nimport { stripVTControlCharacters } from 'node:util'\nimport picocolors from 'picocolors'\n\n/** picocolors formatters (`colors.red('x')`...). */\nexport type Colors = ReturnType<typeof picocolors.createColors>\n\n/** A writable text stream (`process.stdout`, or a test double). */\nexport interface OutputStream {\n write(chunk: string): unknown\n readonly isTTY?: boolean | undefined\n readonly columns?: number | undefined\n}\n\n/** Inputs of {@link shouldUseColor}. */\nexport interface ColorInputs {\n readonly env: Readonly<Record<string, string | undefined>>\n readonly stream: OutputStream\n /** `true` for `--color`, `false` for `--no-color`, `undefined` when neither was passed. */\n readonly flag?: boolean | undefined\n}\n\n/**\n * Whether colors should be written: `--no-color` and a non-empty `NO_COLOR` disable them,\n * `--color` and `FORCE_COLOR` (other than `0`/`false`) force them, otherwise a TTY that is not\n * `TERM=dumb` gets colors.\n */\nexport function shouldUseColor({ env, stream, flag }: ColorInputs): boolean {\n if (flag !== undefined) return flag\n if (env['NO_COLOR'] !== undefined && env['NO_COLOR'] !== '') return false\n const force = env['FORCE_COLOR']\n if (force !== undefined) return force !== '0' && force !== 'false'\n return stream.isTTY === true && env['TERM'] !== 'dumb'\n}\n\n/** picocolors formatters, enabled or not. */\nexport function createColors(enabled: boolean): Colors {\n return picocolors.createColors(enabled)\n}\n\n/** Removes ANSI escape sequences. */\nexport function stripAnsi(text: string): string {\n return stripVTControlCharacters(text)\n}\n\n/** Writes consistent status lines. Errors and warnings go to stderr, everything else to stdout. */\nexport interface Reporter {\n readonly colors: Colors\n /** A raw line on stdout. */\n log(message?: string): void\n /** `› message` */\n info(message: string): void\n /** `✓ message` */\n success(message: string): void\n /** `! message` (stderr) */\n warn(message: string, hints?: readonly string[]): void\n /** `✗ message` (stderr) */\n error(message: string, hints?: readonly string[]): void\n /** A raw line on stderr. */\n logError(message?: string): void\n}\n\n/** Creates a {@link Reporter} writing to the given streams. */\nexport function createReporter(stdout: OutputStream, stderr: OutputStream, colors: Colors): Reporter {\n const line = (stream: OutputStream, text: string): void => {\n stream.write(`${text}\\n`)\n }\n const withHints = (stream: OutputStream, hints: readonly string[] | undefined): void => {\n for (const hint of hints ?? []) line(stream, ` ${colors.dim('=')} ${colors.bold('hint:')} ${hint}`)\n }\n return {\n colors,\n log: (message = '') => line(stdout, message),\n info: message => line(stdout, `${colors.cyan('›')} ${message}`),\n success: message => line(stdout, `${colors.green('✓')} ${message}`),\n warn: (message, hints) => {\n line(stderr, `${colors.yellow('!')} ${message}`)\n withHints(stderr, hints)\n },\n error: (message, hints) => {\n line(stderr, `${colors.red('✗')} ${colors.red(message)}`)\n withHints(stderr, hints)\n },\n logError: (message = '') => line(stderr, message),\n }\n}\n\n/** `850ms`, `1.24s`, `2m 05s`. */\nexport function formatDuration(ms: number): string {\n if (ms < 1000) return `${Math.round(ms)}ms`\n if (ms < 60_000) return `${(ms / 1000).toFixed(2)}s`\n const minutes = Math.floor(ms / 60_000)\n const seconds = Math.round((ms % 60_000) / 1000)\n return `${minutes}m ${String(seconds).padStart(2, '0')}s`\n}\n\n/** `512 B`, `1.5 kB`, `2.31 MB` (SI units, like Vite). */\nexport function formatBytes(bytes: number): string {\n if (bytes < 1000) return `${bytes} B`\n if (bytes < 1_000_000) return `${(bytes / 1000).toFixed(2)} kB`\n return `${(bytes / 1_000_000).toFixed(2)} MB`\n}\n\n/** `1 provider`, `3 providers`. */\nexport function plural(count: number, singular: string, pluralForm = `${singular}s`): string {\n return `${count} ${count === 1 ? singular : pluralForm}`\n}\n","/**\n * A small command layer over citty's argument parser: strict options (unknown options and extra\n * arguments are usage errors, with suggestions), `--` pass-through arguments and help rendering\n * that honours the color settings.\n */\nimport type { ArgDef, ArgsDef, ParsedArgs } from 'citty'\nimport type { CliContext } from './context.ts'\nimport type { Colors } from './output.ts'\n\nimport { parseArgs } from 'citty'\n\nimport { UsageError } from './errors.ts'\nimport { camelCase, kebabCase, suggest } from './names.ts'\nimport { stripAnsi } from './output.ts'\n\n/** What a command receives. */\nexport interface CommandRunContext<A extends ArgsDef = ArgsDef> {\n readonly args: ParsedArgs<A>\n readonly cli: CliContext\n /** Arguments of the command as typed (before `--`). */\n readonly rawArgs: readonly string[]\n /** Arguments after `--` (forwarded to the application by `dev` and `start`). */\n readonly passthrough: readonly string[]\n}\n\n/** Whether an option was explicitly given (`--install`, `--no-install`, `--install=false`). */\nexport function hasFlag(rawArgs: readonly string[], name: string): boolean {\n return rawArgs.some(\n arg =>\n arg === `--${name}` || arg === `--no-${name}` || arg.startsWith(`--${name}=`) || arg.startsWith(`--no-${name}=`),\n )\n}\n\n/** Description of a command. */\nexport interface CommandMeta {\n readonly name: string\n readonly description: string\n readonly aliases?: readonly string[]\n /** Usage line after `znight <name>` (default: computed from the arguments). */\n readonly usage?: string\n readonly examples?: readonly string[]\n /** Extra help paragraph printed after the options. */\n readonly details?: string | ((colors: Colors) => string)\n}\n\n/** Definition of a command: typed arguments and the implementation. */\nexport interface CommandDefinition<A extends ArgsDef> {\n readonly meta: CommandMeta\n readonly args: A\n /** Runs the command; the returned number is the exit code (default 0). */\n run(context: CommandRunContext<A>): number | undefined | Promise<number | undefined>\n}\n\n/** A CLI command, ready to execute. */\nexport interface Command {\n readonly meta: CommandMeta\n readonly args: ArgsDef\n /**\n * Parses `argv` (the arguments after the command name, without `--` pass-through arguments) and\n * runs the command. Resolves with the exit code.\n */\n execute(argv: readonly string[], passthrough: readonly string[], cli: CliContext): Promise<number>\n}\n\n/** Creates a {@link Command}; `args` keep their literal types in `run`. */\nexport function defineCommand<const A extends ArgsDef>(definition: CommandDefinition<A>): Command {\n return {\n meta: definition.meta,\n args: definition.args,\n execute: async (argv, passthrough, cli) => {\n const args = parseCommandArgs(definition, argv)\n return (await definition.run({ args, cli, rawArgs: argv, passthrough })) ?? 0\n },\n }\n}\n\n/** Parses `argv` (without the command name and without `--` pass-through) for `command`. */\nexport function parseCommandArgs<A extends ArgsDef>(\n command: Pick<CommandDefinition<A>, 'args'>,\n argv: readonly string[],\n): ParsedArgs<A> {\n checkOptions(command, argv)\n let parsed: ParsedArgs<A>\n try {\n parsed = parseArgs<A>([...argv], command.args)\n } catch (error) {\n throw new UsageError(stripAnsi(error instanceof Error ? error.message : String(error)))\n }\n const positionals = Object.values(command.args).filter(arg => arg.type === 'positional').length\n const extra = parsed._.slice(positionals)\n if (extra.length > 0) {\n throw new UsageError(`Unexpected argument${extra.length > 1 ? 's' : ''}: ${extra.join(' ')}`)\n }\n return parsed\n}\n\ninterface OptionInfo {\n readonly type: ArgDef['type']\n}\n\nfunction optionTable(args: ArgsDef): Map<string, OptionInfo> {\n const table = new Map<string, OptionInfo>([\n ['help', { type: 'boolean' }],\n ['h', { type: 'boolean' }],\n ])\n for (const [name, def] of Object.entries(args)) {\n if (def.type === 'positional') continue\n const info: OptionInfo = { type: def.type }\n for (const key of [name, kebabCase(name), camelCase(name), ...aliasesOf(def)]) table.set(key, info)\n }\n return table\n}\n\nfunction aliasesOf(def: ArgDef): string[] {\n if (!('alias' in def) || def.alias === undefined) return []\n return Array.isArray(def.alias) ? [...def.alias] : [def.alias]\n}\n\nfunction checkOptions(command: Pick<Command, 'args'>, argv: readonly string[]): void {\n const table = optionTable(command.args)\n const longNames = [...table.keys()].filter(name => name.length > 1)\n for (let index = 0; index < argv.length; index++) {\n const token = argv[index] ?? ''\n if (!token.startsWith('-') || token === '-') continue\n if (token.startsWith('--')) {\n const [rawName = '', inlineValue] = token.slice(2).split(/=(.*)/s, 2)\n let info = table.get(rawName)\n if (info === undefined && rawName.startsWith('no-')) {\n const negated = table.get(rawName.slice(3))\n if (negated?.type === 'boolean') info = negated\n }\n if (info === undefined) {\n const candidate = suggest(rawName, longNames)\n throw new UsageError(\n `Unknown option --${rawName}`,\n candidate === undefined ? [] : [`did you mean --${candidate}?`],\n )\n }\n if ((info.type === 'string' || info.type === 'enum') && inlineValue === undefined) index++\n continue\n }\n // short options: -y, -f, or a group of boolean flags (-yf)\n const letters = token.slice(1)\n for (const [position, letter] of [...letters].entries()) {\n const info = table.get(letter)\n if (info === undefined) throw new UsageError(`Unknown option -${letter}`)\n if ((info.type === 'string' || info.type === 'enum') && position === letters.length - 1) index++\n }\n }\n}\n\n/** Formats the help of a command. */\nexport function renderCommandHelp(command: Pick<Command, 'meta' | 'args'>, colors: Colors): string {\n const { meta } = command\n const entries = Object.entries(command.args)\n const positionals = entries.filter(([, def]) => def.type === 'positional')\n const options = entries.filter(([, def]) => def.type !== 'positional')\n const usage =\n meta.usage ??\n [\n ...positionals.map(([name, def]) =>\n def.required === false || def.default !== undefined ? `[${name}]` : `<${name}>`,\n ),\n options.length > 0 ? '[options]' : '',\n ]\n .filter(Boolean)\n .join(' ')\n const lines = [`${colors.bold(`znight ${meta.name}`)} ${colors.dim('—')} ${meta.description}`, '']\n lines.push(colors.bold('Usage'), ` ${colors.cyan(`znight ${meta.name}${usage === '' ? '' : ` ${usage}`}`)}`, '')\n if (meta.aliases !== undefined && meta.aliases.length > 0) {\n lines.push(colors.bold('Aliases'), ` ${meta.aliases.join(', ')}`, '')\n }\n if (positionals.length > 0) {\n lines.push(colors.bold('Arguments'))\n lines.push(\n ...table(\n positionals.map(([name, def]) => [name, def.description ?? ''] as const),\n colors,\n ),\n )\n lines.push('')\n }\n const optionRows = options.map(([name, def]) => [optionLabel(name, def), describeOption(def)] as const)\n optionRows.push(['-h, --help', 'Show this help'])\n lines.push(colors.bold('Options'), ...table(optionRows, colors), '')\n if (meta.details !== undefined) {\n lines.push(typeof meta.details === 'function' ? meta.details(colors) : meta.details, '')\n }\n if (meta.examples !== undefined && meta.examples.length > 0) {\n lines.push(colors.bold('Examples'), ...meta.examples.map(example => ` ${colors.dim('$')} ${example}`), '')\n }\n return lines.join('\\n')\n}\n\nfunction optionLabel(name: string, def: ArgDef): string {\n const short = aliasesOf(def)\n .filter(alias => alias.length === 1)\n .map(alias => `-${alias}, `)\n .join('')\n const flag = def.type === 'boolean' && def.default === true ? `--no-${name}` : `--${name}`\n let value = ''\n if (def.type === 'enum') value = ` <${(def.options ?? []).join('|')}>`\n else if (def.type === 'string') value = ` <${def.valueHint ?? name}>`\n return `${short}${flag}${value}`\n}\n\nfunction describeOption(def: ArgDef): string {\n const description = def.description ?? ''\n if (def.type === 'boolean') return description\n return def.default === undefined || def.default === '' ? description : `${description} (default: ${def.default})`\n}\n\n/** Two aligned columns. */\nexport function table(rows: readonly (readonly [string, string])[], colors: Colors): string[] {\n const width = Math.max(0, ...rows.map(([left]) => left.length))\n return rows.map(([left, right]) => ` ${colors.cyan(left.padEnd(width))} ${right}`.trimEnd())\n}\n","import { createRequire } from 'node:module'\nimport { join } from 'node:path'\nimport { pathToFileURL } from 'node:url'\n\n/**\n * Imports `specifier` as resolved from the project `root` (the versions the project installed, like\n * `vite` and `tsc` do), or with `fallback` (resolved from the CLI) when the project does not have it.\n */\nexport async function importFromProject(\n specifier: string,\n root: string,\n fallback: () => Promise<unknown>,\n): Promise<unknown> {\n const resolved = resolveFromProject(specifier, root)\n if (resolved !== undefined) {\n try {\n return await import(pathToFileURL(resolved).href)\n } catch (error) {\n // a broken project install must not hide behind the fallback\n if (!isModuleNotFound(error)) throw error\n }\n }\n return fallback()\n}\n\n/** Absolute path of `specifier` resolved from `root`, or `undefined`. */\nexport function resolveFromProject(specifier: string, root: string): string | undefined {\n try {\n return createRequire(join(root, 'package.json')).resolve(specifier)\n } catch {\n return undefined\n }\n}\n\nfunction isModuleNotFound(error: unknown): boolean {\n const code = (error as { code?: unknown } | null)?.code\n return code === 'ERR_MODULE_NOT_FOUND' || code === 'MODULE_NOT_FOUND'\n}\n","/**\n * The `@znight/compiler` programmatic API (spec §6.2), loaded lazily: commands that do not compile\n * (`new`, `g`, `start`) never load it. Commands use {@link CompilerApi} so tests can inject a fake.\n *\n * The CLI only relies on the documented shapes below (structural types, no type import from the\n * compiler), so any `@znight/compiler` of the same major version works.\n */\nimport { existsSync, mkdirSync, readFileSync, writeFileSync } from 'node:fs'\nimport { dirname, relative, resolve } from 'node:path'\n\nimport { CliError } from '../errors.ts'\nimport { createColors } from '../output.ts'\nimport { importFromProject } from './resolve.ts'\n\n/** Location of a diagnostic (`Diagnostic.location`, §6.2). */\nexport interface DiagnosticLocation {\n readonly file: string\n readonly line: number\n readonly column: number\n}\n\n/** A compiler diagnostic (§6.2). */\nexport interface Diagnostic {\n readonly code: string\n readonly severity: 'error' | 'warning'\n readonly message: string\n readonly location?: DiagnosticLocation | undefined\n readonly hints?: readonly string[] | undefined\n readonly related?: readonly { readonly message: string; readonly location: DiagnosticLocation }[] | undefined\n}\n\n/** A string alias of Vite's `resolve.alias` (`CompileOptions.aliases` of the compiler). */\nexport interface StringAliasLike {\n readonly find: string\n readonly replacement: string\n}\n\n/**\n * Compiler options (`ZnightOptions`, §6.2, plus the `CompileOptions` the Vite plugin derives from the\n * Vite config). The CLI reads `root`, `include` and `outFile`; the others are passed through.\n */\nexport interface ZnightOptions {\n readonly root?: string | undefined\n readonly include?: readonly string[] | undefined\n readonly outFile?: string | undefined\n /** String aliases of the Vite config (`resolve.alias`). */\n readonly aliases?: readonly StringAliasLike[] | undefined\n readonly [option: string]: unknown\n}\n\n/** A file emitted by a compiler extension next to the generated module (`CompileResult.extraFiles`, §6.2). */\nexport interface ExtraFileLike {\n /** Absolute path. */\n readonly file: string\n readonly content: string\n}\n\n/** What the CLI reads from a compile result (`CompileResult`, §6.2). */\nexport interface CompileResultLike {\n /** Content of the generated module (with errors: a module throwing them, or empty). */\n readonly code: string\n /** Absolute path of the generated module. */\n readonly outFile: string\n readonly diagnostics: readonly Diagnostic[]\n readonly stats?: { readonly files?: number; readonly providers?: number; readonly durationMs?: number } | undefined\n /** Files the result depends on (`createCompiler()` results). */\n readonly watchFiles?: readonly string[] | undefined\n /** Files emitted by compiler extensions (an SDL schema...), absent from compilers without them. */\n readonly extraFiles?: readonly ExtraFileLike[] | undefined\n}\n\n/** Result of {@link CompilerApi.generate}. */\nexport interface GenerateResultLike extends CompileResultLike {\n /** Whether the generated module was written (its content changed). */\n readonly written: boolean\n}\n\n/** Result of {@link CompilerApi.check}. */\nexport interface CheckResultLike extends CompileResultLike {\n /** The generated files on disk are missing or differ from what would be generated. */\n readonly stale: boolean\n /**\n * The generated files that are missing or out of date (the module, the extra files of the\n * extensions, and `znight.providers.json` in library mode). Empty when `stale` is `false`; empty or\n * absent with `stale` when the compiler does not say which file is stale.\n */\n readonly staleFiles?: readonly string[] | undefined\n}\n\n/** Files changed since the previous compile of an {@link IncrementalCompiler}. */\nexport interface CompilerChanges {\n readonly changed?: readonly string[]\n readonly added?: readonly string[]\n readonly removed?: readonly string[]\n}\n\n/** Kind of a file system event (`ChangeKind` of the compiler). */\nexport type ChangeKind = 'changed' | 'added' | 'removed'\n\n/** A compiler keeping its parse cache between compiles (`createCompiler()`), for watch mode. */\nexport interface IncrementalCompiler {\n /** Compiles (only `changes` are re-read, everything without) and writes the module when it changed. */\n generate(changes?: CompilerChanges): Promise<GenerateResultLike>\n /** Whether `file` is the generated module (watchers ignore it). */\n isOutFile(file: string): boolean\n /**\n * Directories where a created or deleted source changes the scan (`includeRoots()` of the\n * compiler: the bases of the `include` globs in the project and in every source library, known once\n * compiled), to watch recursively. The project root when the compiler does not tell.\n */\n includeRoots(): readonly string[]\n /**\n * Whether a file event can change the next compile (`isRelevantChange()` of the compiler): `watched`\n * are the `watchFiles` of the last compile, `roots` its {@link includeRoots}. When the compiler does\n * not tell, every event but the generated module is.\n */\n isRelevantChange(kind: ChangeKind, file: string, watched: ReadonlySet<string>, roots: readonly string[]): boolean\n}\n\n/** Options of {@link CompilerApi.formatDiagnostics}. */\nexport interface FormatDiagnosticsOptions {\n readonly color?: boolean\n readonly cwd?: string\n /** Append the summary line (`Build failed with 2 errors`). */\n readonly summary?: boolean\n}\n\n/** Options read from `znight.config.*` (`loadZnightConfig()`, §6.3). */\nexport interface ZnightConfigLike {\n /** The config file, `undefined` when the project has none. */\n readonly file: string | undefined\n /** Its options, `root` resolved against the config file directory. */\n readonly options: ZnightOptions\n}\n\n/** The part of `@znight/compiler` used by the CLI. */\nexport interface CompilerApi {\n /** Compiles and writes the generated module when its content changed (`generate()`). */\n generate(options: ZnightOptions): Promise<GenerateResultLike>\n /** Compiles without writing and compares with the files on disk (`generate({ check: true })`). */\n check(options: ZnightOptions): Promise<CheckResultLike>\n /** An incremental compiler (`createCompiler()`). */\n createIncremental(options: ZnightOptions): IncrementalCompiler\n /** Code frames for diagnostics (`formatDiagnostics()`). */\n formatDiagnostics(diagnostics: readonly Diagnostic[], options?: FormatDiagnosticsOptions): string\n /**\n * The options of `znight.config.*` (or of the file named by `ZNIGHT_CONFIG`) in `root`\n * (`loadZnightConfig()`). Absent for compilers without it.\n */\n loadConfig?(root: string): Promise<ZnightConfigLike>\n}\n\n/**\n * Not a literal in `import()`: the CLI type-checks and bundles without the compiler (an optional\n * peer dependency), whose version is the project's.\n */\nconst COMPILER_PACKAGE: string = '@znight/compiler'\n\n/** A compile result as returned by any `@znight/compiler` version (extra fields are optional). */\ninterface ModuleResult extends CompileResultLike {\n /** The disk copy of the module (`code` before it existed; they differ in `build` mode only). */\n readonly diskCode?: string\n readonly written?: readonly string[]\n readonly stale?: boolean\n /** The stale generated files (check mode), when the compiler tells. */\n readonly staleFiles?: readonly string[]\n /** Library mode: `znight.providers.json` (`library` of a `CompileResult`). */\n readonly library?: { readonly file?: unknown; readonly content?: unknown } | undefined\n}\n\n/** The parts of a `ZnightCompiler` (`createCompiler()`) the CLI uses; all optional. */\nexport interface ModuleIncrementalCompiler {\n generate?: (changes?: CompilerChanges, options?: { check?: boolean }) => Promise<ModuleResult>\n isOutFile?: (file: string) => boolean\n}\n\n/** The shape of the `@znight/compiler` module (every export optional: partial versions are adapted). */\nexport interface CompilerModule {\n compile?: (options?: ZnightOptions) => Promise<ModuleResult>\n generate?: (options?: ZnightOptions & { check?: boolean }) => Promise<ModuleResult>\n createCompiler?: (options?: ZnightOptions) => ModuleIncrementalCompiler\n formatDiagnostics?: (diagnostics: readonly Diagnostic[], options?: FormatDiagnosticsOptions) => string\n loadZnightConfig?: (cwd?: string) => Promise<ZnightConfigLike>\n /** The watch roots of a compiler (`includeRoots(compiler)`). */\n includeRoots?: (compiler: ModuleIncrementalCompiler) => readonly string[]\n /** Whether a file event can change the next compile of a compiler (`isRelevantChange(compiler, ...)`). */\n isRelevantChange?: (\n compiler: ModuleIncrementalCompiler,\n kind: ChangeKind,\n file: string,\n watched: ReadonlySet<string>,\n roots: readonly string[],\n ) => boolean\n}\n\n/**\n * Loads `@znight/compiler` as installed in the project (falls back to the CLI's own peer) and adapts\n * it to {@link CompilerApi}.\n */\nexport async function loadCompiler(root: string): Promise<CompilerApi> {\n let module: CompilerModule\n try {\n module = (await importFromProject(COMPILER_PACKAGE, root, () => import(COMPILER_PACKAGE))) as CompilerModule\n } catch (error) {\n throw new CliError('Cannot load @znight/compiler', {\n cause: error,\n hints: ['install it in your project: npm install -D @znight/compiler vite'],\n })\n }\n return adaptCompilerModule(module)\n}\n\nfunction readText(file: string): string | undefined {\n try {\n return readFileSync(file, 'utf8')\n } catch {\n return undefined\n }\n}\n\n/**\n * Adapts a loaded compiler module: `generate()` / `generate({ check })` / `createCompiler()` when\n * available, otherwise the same behaviour built on `compile()`.\n */\nexport function adaptCompilerModule(module: CompilerModule): CompilerApi {\n const { compile, generate, createCompiler, loadZnightConfig } = module\n if (typeof compile !== 'function' && typeof generate !== 'function') {\n throw new CliError('This version of @znight/compiler exposes neither compile() nor generate()', {\n hints: ['upgrade @znight/compiler to the version of @znight/cli'],\n })\n }\n const format = module.formatDiagnostics ?? fallbackFormatDiagnostics\n\n /** Pure compile: `compile()`, else `generate({ check: true })` (never writes). */\n const compileOnly = (options: ZnightOptions): Promise<ModuleResult> =>\n typeof compile === 'function'\n ? compile(options)\n : (generate as NonNullable<CompilerModule['generate']>)({ ...options, check: true })\n\n /** Write-if-changed on top of a compile result, when the compiler did not write itself. */\n const written = (result: ModuleResult, before: string | undefined): GenerateResultLike => ({\n ...result,\n written: Array.isArray(result.written) ? result.written.length > 0 : before !== readText(result.outFile),\n })\n\n const generateOnce = async (options: ZnightOptions): Promise<GenerateResultLike> => {\n if (typeof generate === 'function') {\n const before = readText(resolveOutFile(options))\n return written(await generate(options), before)\n }\n const result = await compileOnly(options)\n let changed = false\n if (!hasErrors(result.diagnostics)) {\n for (const output of outputsOf(result, false)) changed = writeIfChanged(output.file, output.content) || changed\n }\n return { ...result, written: changed }\n }\n\n return {\n generate: generateOnce,\n check: async options => {\n const result =\n typeof generate === 'function' ? await generate({ ...options, check: true }) : await compileOnly(options)\n const staleFiles = Array.isArray(result.staleFiles) ? result.staleFiles : staleOutputs(result)\n const stale = typeof result.stale === 'boolean' ? result.stale : staleFiles.length > 0\n return { ...result, stale, staleFiles: stale ? staleFiles : [] }\n },\n createIncremental: options => {\n const compiler = typeof createCompiler === 'function' ? createCompiler(options) : undefined\n const incremental = compiler?.generate\n const outFile = resolveOutFile(options)\n const isOutFile = (file: string): boolean =>\n typeof compiler?.isOutFile === 'function' ? compiler.isOutFile(file) : resolve(file) === outFile\n const { includeRoots, isRelevantChange } = module\n return {\n generate: async changes => {\n if (compiler === undefined || typeof incremental !== 'function') return generateOnce(options)\n const before = readText(outFile)\n return written(await incremental.call(compiler, changes), before)\n },\n isOutFile,\n includeRoots: () =>\n compiler !== undefined && typeof includeRoots === 'function'\n ? includeRoots(compiler)\n : [resolve(options.root ?? '.')],\n isRelevantChange: (kind, file, watched, roots) =>\n compiler !== undefined && typeof isRelevantChange === 'function'\n ? isRelevantChange(compiler, kind, file, watched, roots)\n : !isOutFile(file),\n }\n },\n formatDiagnostics: (diagnostics, options) => format(diagnostics, options),\n ...(typeof loadZnightConfig === 'function'\n ? { loadConfig: (root: string): Promise<ZnightConfigLike> => loadZnightConfig(root) }\n : {}),\n }\n}\n\n/**\n * The generated files of a compile result: the module, the extra files of the extensions and, with\n * `library`, `znight.providers.json` in library mode (`generate()` of the compiler writes the module\n * and the extra files; library mode is a compiler feature).\n */\nfunction outputsOf(result: ModuleResult, library: boolean): { file: string; content: string }[] {\n const outputs: { file: string; content: string }[] = [\n { file: result.outFile, content: result.diskCode ?? result.code },\n ]\n for (const extra of result.extraFiles ?? []) outputs.push({ file: extra.file, content: extra.content })\n const { file, content } = result.library ?? {}\n if (library && typeof file === 'string' && typeof content === 'string') outputs.push({ file, content })\n return outputs\n}\n\n/**\n * The generated files of a compile result that differ from the disk: the module, the extra files of\n * the extensions and `znight.providers.json` in library mode. None with errors (nothing would be\n * written).\n */\nfunction staleOutputs(result: ModuleResult): string[] {\n if (hasErrors(result.diagnostics)) return []\n return outputsOf(result, true)\n .filter(output => readText(output.file) !== output.content)\n .map(output => output.file)\n}\n\n/** Default `outFile` of the compiler (§6.2). */\nexport const DEFAULT_OUT_FILE = 'src/.znight/container.generated.ts'\n\n/** Absolute path of the generated module for `options`. */\nexport function resolveOutFile(options: ZnightOptions): string {\n return resolve(options.root ?? '.', options.outFile ?? DEFAULT_OUT_FILE)\n}\n\n/** Whether a list of diagnostics contains an error. */\nexport function hasErrors(diagnostics: readonly Diagnostic[]): boolean {\n return diagnostics.some(diagnostic => diagnostic.severity === 'error')\n}\n\n/** Writes `content` to `file` unless it already has that exact content. Returns whether it wrote. */\nexport function writeIfChanged(file: string, content: string): boolean {\n if (existsSync(file) && readFileSync(file, 'utf8') === content) return false\n mkdirSync(dirname(file), { recursive: true })\n writeFileSync(file, content)\n return true\n}\n\n/**\n * Plain formatter used when the installed compiler has no `formatDiagnostics()`:\n *\n * ```\n * ✗ ZNIGHT001: Missing provider for 'EmailService' required by NotificationService\n * --> src/notification/notification.service.ts:12:5\n * = hint: Add @Injectable() to EmailService\n * ```\n */\nexport function fallbackFormatDiagnostics(\n diagnostics: readonly Diagnostic[],\n options: FormatDiagnosticsOptions = {},\n): string {\n const colors = createColors(options.color === true)\n const blocks: string[] = []\n for (const diagnostic of diagnostics) {\n const isError = diagnostic.severity === 'error'\n const head = isError\n ? colors.red(`✗ ${diagnostic.code}: ${diagnostic.message}`)\n : colors.yellow(`! ${diagnostic.code}: ${diagnostic.message}`)\n const lines = [colors.bold(head)]\n if (diagnostic.location !== undefined) {\n lines.push(` ${colors.cyan('-->')} ${formatLocation(diagnostic.location, options.cwd)}`)\n }\n for (const hint of diagnostic.hints ?? []) lines.push(` ${colors.dim('=')} ${colors.bold('hint:')} ${hint}`)\n for (const related of diagnostic.related ?? []) {\n lines.push(\n ` ${colors.dim('=')} ${colors.bold('note:')} ${related.message} (${formatLocation(related.location, options.cwd)})`,\n )\n }\n blocks.push(lines.join('\\n'))\n }\n return blocks.join('\\n\\n')\n}\n\nfunction formatLocation(location: { file: string; line: number; column: number }, cwd: string | undefined): string {\n const file = cwd === undefined ? location.file : relative(cwd, location.file).replaceAll('\\\\', '/')\n return `${file}:${location.line}:${location.column}`\n}\n","/**\n * `@znight/openapi`, loaded lazily from the project (an optional peer dependency): `znight openapi`\n * uses its emission API (`@znight/openapi/emit`), `znight build --openapi` its Vite plugin\n * (`@znight/openapi/vite`). Commands use the structural types below, so tests can inject fakes.\n */\nimport type { Plugin } from 'vite'\nimport type { Diagnostic, ZnightOptions } from './compiler.ts'\n\nimport { CliError } from '../errors.ts'\nimport { importFromProject } from './resolve.ts'\n\n/** Options of `emitOpenApi()` (`@znight/openapi/emit`). */\nexport interface OpenApiEmitOptionsLike {\n readonly root: string\n readonly output: readonly string[]\n readonly check?: boolean\n readonly prefix?: string\n readonly runtime?: 'auto' | 'node' | 'bun'\n readonly converters?: string\n readonly config?: string\n readonly configLoader?: string\n readonly compilerOptions?: ZnightOptions\n}\n\n/** A warning of the assembly. */\nexport interface OpenApiWarningLike {\n readonly code: string\n readonly message: string\n}\n\n/** What the CLI reads from the result of `emitOpenApi()`. */\nexport interface OpenApiEmitResultLike {\n readonly ok: boolean\n readonly written: readonly string[]\n readonly stale: boolean\n readonly staleFiles: readonly string[]\n readonly diagnostics: readonly Diagnostic[]\n readonly warnings: readonly OpenApiWarningLike[]\n readonly outputs: readonly string[]\n readonly runtime: 'node' | 'bun'\n readonly document?: { readonly paths?: Readonly<Record<string, object>> } | undefined\n}\n\n/** `@znight/openapi/emit`. */\nexport interface OpenApiEmitApi {\n emitOpenApi(options: OpenApiEmitOptionsLike): Promise<OpenApiEmitResultLike>\n}\n\n/** Options of the `openapi()` Vite plugin. */\nexport interface OpenApiVitePluginOptionsLike {\n readonly output?: string\n /** HTTP prefix (`servers` default when `@OpenApiDocument` declares none). */\n readonly prefix?: string\n}\n\n/** `@znight/openapi/vite`. */\nexport interface OpenApiViteApi {\n openapi(options?: OpenApiVitePluginOptionsLike): Plugin\n}\n\n/** Not literals in `import()`: the CLI builds without `@znight/openapi` (an optional peer). */\nconst EMIT_MODULE: string = '@znight/openapi/emit'\nconst VITE_MODULE: string = '@znight/openapi/vite'\n\nconst MISSING_HINTS = ['install it in your project: npm install @znight/openapi']\n\n/** Loads `@znight/openapi/emit` as installed in the project. */\nexport async function loadOpenApiEmit(root: string): Promise<OpenApiEmitApi> {\n let module: Partial<OpenApiEmitApi>\n try {\n module = (await importFromProject(EMIT_MODULE, root, () => import(EMIT_MODULE))) as Partial<OpenApiEmitApi>\n } catch (error) {\n throw new CliError('Cannot load @znight/openapi', { cause: error, hints: MISSING_HINTS })\n }\n if (typeof module.emitOpenApi !== 'function') {\n throw new CliError('This version of @znight/openapi has no emitOpenApi()', {\n hints: ['upgrade @znight/openapi to the version of @znight/cli'],\n })\n }\n return module as OpenApiEmitApi\n}\n\n/** Loads `@znight/openapi/vite` as installed in the project. */\nexport async function loadOpenApiVite(root: string): Promise<OpenApiViteApi> {\n let module: Partial<OpenApiViteApi>\n try {\n module = (await importFromProject(VITE_MODULE, root, () => import(VITE_MODULE))) as Partial<OpenApiViteApi>\n } catch (error) {\n throw new CliError('Cannot load @znight/openapi', { cause: error, hints: MISSING_HINTS })\n }\n if (typeof module.openapi !== 'function') {\n throw new CliError('This version of @znight/openapi has no openapi() Vite plugin', {\n hints: ['upgrade @znight/openapi to the version of @znight/cli'],\n })\n }\n return module as OpenApiViteApi\n}\n","/**\n * Child processes: the application (`znight dev` / `znight start`) and tools (`git`, package\n * managers). Behind {@link ProcessService} so that tests can use fake processes.\n */\nimport { type ChildProcess, spawn as nodeSpawn } from 'node:child_process'\nimport { constants } from 'node:os'\n\n/** How a child process ended. */\nexport interface ExitStatus {\n /** Exit code, `null` when killed by a signal or when the process could not start. */\n readonly code: number | null\n readonly signal: NodeJS.Signals | null\n /** Spawn failure (`ENOENT`...). */\n readonly error?: Error | undefined\n}\n\n/** A running child process. */\nexport interface ChildHandle {\n readonly pid: number | undefined\n /** Sends a signal (to its process group when it runs detached). Returns `false` when it already exited. */\n kill(signal: NodeJS.Signals): boolean\n /** Resolves once the process exited (never rejects). */\n readonly exited: Promise<ExitStatus>\n}\n\n/** Options of {@link ProcessService.spawn}. */\nexport interface SpawnOptions {\n readonly cwd: string\n readonly env: Readonly<Record<string, string | undefined>>\n /** Default `'inherit'`. */\n readonly stdio?: 'inherit' | 'ignore'\n /**\n * POSIX only: run the process in its own process group, so that a terminal Ctrl+C reaches the CLI\n * only (the CLI then forwards exactly one signal). The process is killed when the CLI exits.\n */\n readonly detached?: boolean\n}\n\n/** Result of {@link ProcessService.run}. */\nexport interface RunResult extends ExitStatus {\n readonly stdout: string\n readonly stderr: string\n}\n\n/** Options of {@link ProcessService.run}. */\nexport interface RunOptions {\n readonly cwd: string\n readonly env: Readonly<Record<string, string | undefined>>\n}\n\n/**\n * Replaces the current process image (`execve(2)`) after changing the working directory to `cwd`.\n * `args[0]` is the program name. Never returns on success.\n */\nexport type ExecveFunction = (\n file: string,\n args: readonly string[],\n env: Readonly<Record<string, string>>,\n cwd: string,\n) => void\n\n/** Process primitives used by the commands. */\nexport interface ProcessService {\n spawn(command: string, args: readonly string[], options: SpawnOptions): ChildHandle\n /** Runs a command to completion, capturing its output. */\n run(command: string, args: readonly string[], options: RunOptions): Promise<RunResult>\n /** `process.execve` when the runtime supports it (POSIX). */\n readonly execve?: ExecveFunction | undefined\n}\n\nconst detachedChildren = new Set<ChildProcess>()\nlet exitHookInstalled = false\n\nfunction killDetachedChildren(): void {\n for (const child of detachedChildren) {\n killTree(child, 'SIGKILL', true)\n }\n}\n\nfunction killTree(child: ChildProcess, signal: NodeJS.Signals, detached: boolean): boolean {\n if (child.exitCode !== null || child.signalCode !== null) return false\n if (detached && child.pid !== undefined && process.platform !== 'win32') {\n try {\n process.kill(-child.pid, signal)\n return true\n } catch {\n // the group is gone: fall back to the process itself\n }\n }\n return child.kill(signal)\n}\n\nfunction cleanEnv(env: Readonly<Record<string, string | undefined>>): Record<string, string> {\n const result: Record<string, string> = {}\n for (const [key, value] of Object.entries(env)) {\n if (value !== undefined) result[key] = value\n }\n return result\n}\n\n/** Starts a process with `node:child_process`. */\nexport function spawnProcess(command: string, args: readonly string[], options: SpawnOptions): ChildHandle {\n const detached = options.detached === true && process.platform !== 'win32'\n const child = nodeSpawn(command, [...args], {\n cwd: options.cwd,\n env: cleanEnv(options.env),\n stdio: options.stdio ?? 'inherit',\n detached,\n windowsHide: true,\n })\n if (detached) {\n detachedChildren.add(child)\n if (!exitHookInstalled) {\n exitHookInstalled = true\n process.on('exit', killDetachedChildren)\n }\n }\n const exited = new Promise<ExitStatus>(resolve => {\n child.once('error', error => {\n detachedChildren.delete(child)\n resolve({ code: null, signal: null, error })\n })\n child.once('exit', (code, signal) => {\n detachedChildren.delete(child)\n resolve({ code, signal })\n })\n })\n return {\n pid: child.pid,\n kill: signal => killTree(child, signal, detached),\n exited,\n }\n}\n\n/** Runs a command to completion with `node:child_process`, capturing stdout and stderr. */\nexport function runProcess(command: string, args: readonly string[], options: RunOptions): Promise<RunResult> {\n return new Promise<RunResult>(resolve => {\n const child = nodeSpawn(command, [...args], {\n cwd: options.cwd,\n env: cleanEnv(options.env),\n stdio: ['ignore', 'pipe', 'pipe'],\n windowsHide: true,\n // package managers are `.cmd` shims on Windows\n shell: process.platform === 'win32',\n })\n let stdout = ''\n let stderr = ''\n child.stdout?.setEncoding('utf8').on('data', (chunk: string) => {\n stdout += chunk\n })\n child.stderr?.setEncoding('utf8').on('data', (chunk: string) => {\n stderr += chunk\n })\n child.once('error', error => resolve({ code: null, signal: null, error, stdout, stderr }))\n child.once('close', (code, signal) => resolve({ code, signal, stdout, stderr }))\n })\n}\n\n/** The default {@link ProcessService}. */\nexport function createProcessService(): ProcessService {\n const execve = (process as { execve?: (file: string, args: string[], env: Record<string, string>) => void }).execve\n return {\n spawn: spawnProcess,\n run: runProcess,\n execve:\n typeof execve === 'function' && process.platform !== 'win32'\n ? (file, args, env, cwd) => {\n process.chdir(cwd)\n execve.call(process, file, [...args], { ...env })\n }\n : undefined,\n }\n}\n\n/** Exit code of the CLI mirroring a child's exit status (`128 + n` for signals, like shells). */\nexport function exitCodeOf(status: ExitStatus): number {\n if (status.code !== null) return status.code\n if (status.signal !== null) return 128 + (constants.signals[status.signal] ?? 1)\n return 1\n}\n","/**\n * Interactive prompts of `znight new`, backed by `@clack/prompts` (loaded lazily). A cancelled\n * prompt (Ctrl+C, Escape) throws a {@link CancelledError}.\n */\nimport { CancelledError } from '../errors.ts'\n\n/** A choice of a select / multiselect prompt. */\nexport interface PromptChoice<T extends string> {\n readonly value: T\n readonly label: string\n readonly hint?: string\n}\n\n/** Prompts used by the CLI. */\nexport interface Prompts {\n intro(title: string): void\n outro(message: string): void\n text(options: {\n message: string\n placeholder?: string\n initialValue?: string\n validate?: (value: string) => string | undefined\n }): Promise<string>\n select<T extends string>(options: {\n message: string\n choices: readonly PromptChoice<T>[]\n initialValue?: T\n }): Promise<T>\n multiselect<T extends string>(options: {\n message: string\n choices: readonly PromptChoice<T>[]\n initialValues?: readonly T[]\n }): Promise<T[]>\n confirm(options: { message: string; initialValue?: boolean }): Promise<boolean>\n /** A spinner; `stop` prints the final message. */\n spinner(): { start(message: string): void; stop(message: string, failed?: boolean): void }\n note(message: string, title?: string): void\n}\n\n/** Loads `@clack/prompts` and adapts it to {@link Prompts}. */\nexport async function loadPrompts(): Promise<Prompts> {\n const clack = await import('@clack/prompts')\n const unwrap = <T>(value: T): Exclude<T, symbol> => {\n if (clack.isCancel(value) || typeof value === 'symbol') throw new CancelledError('Operation cancelled')\n return value as Exclude<T, symbol>\n }\n const toOptions = (choices: readonly PromptChoice<string>[]): { value: string; label: string; hint?: string }[] =>\n choices.map(choice => ({\n value: choice.value,\n label: choice.label,\n ...(choice.hint === undefined ? {} : { hint: choice.hint }),\n }))\n return {\n intro: title => clack.intro(title),\n outro: message => clack.outro(message),\n text: async options =>\n unwrap(\n await clack.text({\n message: options.message,\n ...(options.placeholder === undefined ? {} : { placeholder: options.placeholder }),\n ...(options.initialValue === undefined ? {} : { initialValue: options.initialValue }),\n ...(options.validate === undefined\n ? {}\n : { validate: (value: string | undefined) => options.validate?.(value ?? '') }),\n }),\n ),\n select: async <T extends string>(options: {\n message: string\n choices: readonly PromptChoice<T>[]\n initialValue?: T\n }): Promise<T> => {\n const value = await clack.select<string>({\n message: options.message,\n options: toOptions(options.choices),\n ...(options.initialValue === undefined ? {} : { initialValue: options.initialValue }),\n })\n return unwrap(value) as T\n },\n multiselect: async <T extends string>(options: {\n message: string\n choices: readonly PromptChoice<T>[]\n initialValues?: readonly T[]\n }): Promise<T[]> => {\n const value = await clack.multiselect<string>({\n message: options.message,\n required: false,\n options: toOptions(options.choices),\n ...(options.initialValues === undefined ? {} : { initialValues: [...options.initialValues] }),\n })\n return unwrap(value) as T[]\n },\n confirm: async options =>\n unwrap(\n await clack.confirm({\n message: options.message,\n ...(options.initialValue === undefined ? {} : { initialValue: options.initialValue }),\n }),\n ),\n spinner: () => {\n const spinner = clack.spinner()\n return {\n start: message => spinner.start(message),\n stop: (message, failed = false) => (failed ? spinner.error(message) : spinner.stop(message)),\n }\n },\n note: (message, title) => clack.note(message, title),\n }\n}\n","/**\n * Vite, loaded lazily from the project (it is a peer dependency). `znight build` and `znight dev` run\n * `vite build` programmatically: the `znight()` plugin of the project's `vite.config.ts` compiles the\n * container and, with its `app` defaults, configures a server build (`src/main.ts` → `dist/`).\n *\n * The Vite root is resolved like the Vite CLI run in the project directory: the `root` of the config\n * file, relative to the project root (`--root`), else the project root ({@link projectRootPlugin}).\n */\nimport type { InlineConfig, Plugin } from 'vite'\nimport type { Diagnostic, StringAliasLike, ZnightOptions } from './compiler.ts'\n\nimport { existsSync } from 'node:fs'\nimport { join, resolve } from 'node:path'\n\nimport { CliError } from '../errors.ts'\nimport { importFromProject } from './resolve.ts'\n\n/** Vite log levels. */\nexport type ViteLogLevel = 'info' | 'warn' | 'error' | 'silent'\n\n/** How Vite loads its config file (`--configLoader` of the Vite CLI). */\nexport type ViteConfigLoader = 'bundle' | 'runner' | 'native'\n\n/** What the CLI reads from a config resolved by Vite (`ResolvedConfig`). */\nexport interface ResolvedConfigLike {\n /** Absolute root. */\n readonly root: string\n /** The config file that was loaded. */\n readonly configFile?: string | undefined\n /** Every plugin, flattened. */\n readonly plugins: readonly unknown[]\n readonly resolve?: { readonly alias?: unknown } | undefined\n}\n\n/** Subset of the `vite` module used by the CLI. */\nexport interface ViteApi {\n build(config: InlineConfig): Promise<unknown>\n /** Resolves the config as a build would, without building (absent: `znight generate` uses defaults). */\n resolveConfig?: (\n config: InlineConfig,\n command: 'build' | 'serve',\n defaultMode?: string,\n defaultNodeEnv?: string,\n ) => Promise<ResolvedConfigLike>\n}\n\n/** Events of a Vite build in watch mode (Rolldown/Rollup watcher events). */\nexport type WatcherEvent =\n | { readonly code: 'START' }\n | { readonly code: 'BUNDLE_START' }\n | { readonly code: 'BUNDLE_END'; readonly duration?: number; readonly result?: ClosableBuild }\n | { readonly code: 'END' }\n | { readonly code: 'ERROR'; readonly error: unknown; readonly result?: ClosableBuild }\n\ninterface ClosableBuild {\n close(): unknown\n}\n\n/** The watcher returned by `vite.build({ build: { watch } })`. */\nexport interface BuildWatcher {\n on(event: 'event', listener: (event: WatcherEvent) => void): unknown\n close(): Promise<void>\n}\n\n/** Loads `vite` as installed in the project. */\nexport async function loadVite(root: string): Promise<ViteApi> {\n try {\n return (await importFromProject('vite', root, () => import('vite'))) as ViteApi\n } catch (error) {\n throw new CliError('Cannot load vite', {\n cause: error,\n hints: ['install it in your project: npm install -D vite @znight/compiler'],\n })\n }\n}\n\n/** Options shared by {@link runBuild} and {@link watchBuild}. */\nexport interface BuildOptions {\n readonly root: string\n /** Vite config file; default: auto-detected `vite.config.*`. */\n readonly configFile?: string | undefined\n readonly mode: string\n readonly logLevel: ViteLogLevel\n /** How the config file is loaded (default: Vite's, `bundle`). */\n readonly configLoader?: ViteConfigLoader | undefined\n /** Plugins added to the config file's ones. */\n readonly plugins?: readonly Plugin[]\n}\n\n/** The outcome of the compile of the `znight()` plugin (`plugin.api.result`, @znight/compiler). */\nexport interface CompileOutcome {\n /** No error diagnostic. */\n readonly ok: boolean\n readonly diagnostics: readonly Diagnostic[]\n}\n\n/** What the CLI reads from the `plugin.api` of `znight()` (structural: any compiler version). */\ninterface ZnightPluginApiLike {\n /** The latest compile result. */\n readonly result?: unknown\n}\n\n/**\n * Captures what a build produced: the entry chunk written (the file `znight dev` runs) and the\n * compile result of the `znight()` plugin. In watch mode the plugin does not fail the build on\n * compile errors (the bundle contains a module throwing them): `znight dev` reads the result to keep\n * the last good process running.\n */\nexport interface OutputTracker {\n readonly plugin: Plugin\n /** Absolute path of the entry chunk written by the last build. */\n entry(): string | undefined\n /** `performance.now()` when the last build started (`undefined` before the first one). */\n startedAt(): number | undefined\n /**\n * The compile result the last written build was made of (`plugin.api.result` of `znight()`),\n * `undefined` when the Vite config has no `znight()` plugin exposing it.\n */\n compile(): CompileOutcome | undefined\n}\n\n/** Creates an {@link OutputTracker}; relative output paths are resolved against the Vite root. */\nexport function createOutputTracker(root: string): OutputTracker {\n let entry: string | undefined\n let started: number | undefined\n let api: ZnightPluginApiLike | undefined\n let compile: CompileOutcome | undefined\n let viteRoot = root\n const plugin: Plugin = {\n name: 'znight:cli-output',\n configResolved(config) {\n api = findZnightApi(config.plugins)\n if (typeof config.root === 'string') viteRoot = config.root\n },\n buildStart() {\n started = performance.now()\n compile = undefined\n },\n writeBundle(outputOptions, bundle) {\n // the plugin compiled in its buildStart: its latest result is the one this bundle contains\n compile = compileOutcome(api?.result)\n const chunks = Object.values(bundle).filter(\n (output): output is Extract<(typeof bundle)[string], { type: 'chunk' }> =>\n output.type === 'chunk' && output.isEntry,\n )\n const chunk = chunks.find(candidate => candidate.name === 'main') ?? chunks[0]\n if (chunk === undefined) return\n entry =\n outputOptions.file === undefined\n ? resolve(viteRoot, outputOptions.dir ?? 'dist', chunk.fileName)\n : resolve(viteRoot, outputOptions.file)\n },\n }\n return { plugin, entry: () => entry, startedAt: () => started, compile: () => compile }\n}\n\n/** The `plugin.api` of the `znight()` plugin among the resolved plugins. */\nfunction findZnightApi(plugins: readonly unknown[]): ZnightPluginApiLike | undefined {\n for (const plugin of plugins) {\n if (typeof plugin !== 'object' || plugin === null || (plugin as { name?: unknown }).name !== 'znight') continue\n const api = (plugin as { api?: unknown }).api\n if (typeof api === 'object' && api !== null && 'result' in api) return api as ZnightPluginApiLike\n }\n return undefined\n}\n\nfunction compileOutcome(result: unknown): CompileOutcome | undefined {\n if (typeof result !== 'object' || result === null) return undefined\n const { ok, diagnostics } = result as { ok?: unknown; diagnostics?: unknown }\n if (typeof ok !== 'boolean') return undefined\n return { ok, diagnostics: Array.isArray(diagnostics) ? (diagnostics as Diagnostic[]) : [] }\n}\n\n/** Name of {@link projectRootPlugin}. */\nconst ROOT_PLUGIN = 'znight:cli-root'\n\n/**\n * Resolves the Vite root like the Vite CLI run in the project directory: the `root` of the config\n * file against `projectRoot`, or `projectRoot` without one. An inline `root` would override the\n * config file's, so the CLI sets it from the first `config` hook instead.\n */\nexport function projectRootPlugin(projectRoot: string): Plugin {\n return {\n name: ROOT_PLUGIN,\n config: {\n order: 'pre',\n handler: config => ({ root: resolve(projectRoot, config.root ?? '.') }),\n },\n }\n}\n\nfunction inlineConfig(options: BuildOptions, watch: boolean): InlineConfig {\n return {\n // found in the project root (not the working directory); no config file: none is searched\n configFile: findViteConfig(options.root, options.configFile) ?? false,\n mode: options.mode,\n logLevel: options.logLevel,\n ...(options.configLoader === undefined ? {} : { configLoader: options.configLoader }),\n clearScreen: false,\n plugins: [projectRootPlugin(options.root), ...(options.plugins ?? [])],\n build: watch ? { watch: {} } : {},\n }\n}\n\n/** Runs `vite build` once. Throws the build error. */\nexport async function runBuild(vite: ViteApi, options: BuildOptions): Promise<void> {\n const result = await vite.build(inlineConfig(options, false))\n if (isWatcher(result)) await result.close()\n}\n\n/** Starts `vite build --watch`. */\nexport async function watchBuild(vite: ViteApi, options: BuildOptions): Promise<BuildWatcher> {\n const result = await vite.build(inlineConfig(options, true))\n if (!isWatcher(result)) {\n throw new CliError('vite build did not start in watch mode', {\n hints: ['check that your Vite config does not override \"build.watch\"'],\n })\n }\n return result\n}\n\nfunction isWatcher(value: unknown): value is BuildWatcher {\n return (\n typeof value === 'object' &&\n value !== null &&\n typeof (value as Partial<BuildWatcher>).on === 'function' &&\n typeof (value as Partial<BuildWatcher>).close === 'function'\n )\n}\n\n/** Vite's `DEFAULT_CONFIG_FILES`, in its order. */\nconst CONFIG_FILES = [\n 'vite.config.js',\n 'vite.config.mjs',\n 'vite.config.ts',\n 'vite.config.cjs',\n 'vite.config.mts',\n 'vite.config.cts',\n]\n\n/** The Vite config file of the project (the one Vite would load from `root`), if any. */\nexport function findViteConfig(root: string, configFile?: string): string | undefined {\n if (configFile !== undefined) return resolve(root, configFile)\n return CONFIG_FILES.map(file => join(root, file)).find(file => existsSync(file))\n}\n\n/** Result of {@link readZnightPluginOptions}. */\nexport interface ZnightPluginLookup {\n /** The Vite config file that was loaded. */\n readonly configFile: string\n /** Whether the config registers the `znight()` plugin. */\n readonly found: boolean\n /**\n * The options the `znight()` plugin compiles with: those given to it (`plugin.api.options`) with\n * the absolute `root` (resolved against the Vite root) and, as derived from the Vite config, the\n * string `aliases` of `resolve.alias` and the `runtimeConditions` (when the plugin exposes its\n * compiler).\n */\n readonly options?: ZnightOptions | undefined\n}\n\n/**\n * Resolves the project's Vite config as `znight build` does and reads the options the `znight()`\n * plugin compiles with, so that `znight generate` compiles exactly like the Vite build. Returns\n * `undefined` without a config file. `process.env.NODE_ENV`, which Vite sets, is left untouched.\n */\nexport async function readZnightPluginOptions(\n vite: ViteApi,\n root: string,\n configFile?: string,\n configLoader?: ViteConfigLoader,\n): Promise<ZnightPluginLookup | undefined> {\n const file = findViteConfig(root, configFile)\n const resolveConfig = vite.resolveConfig\n if (file === undefined || resolveConfig === undefined) return undefined\n const inline: InlineConfig = {\n configFile: file,\n mode: 'production',\n logLevel: 'silent',\n ...(configLoader === undefined ? {} : { configLoader }),\n plugins: [projectRootPlugin(root)],\n }\n const config = await preservingNodeEnv(() => resolveConfig.call(vite, inline, 'build', 'production', 'production'))\n const loaded = config.configFile ?? file\n for (const plugin of config.plugins) {\n if (typeof plugin !== 'object' || plugin === null) continue\n const name = (plugin as { name?: unknown }).name\n if (typeof name !== 'string' || !isZnightPluginName(name)) continue\n return { configFile: loaded, found: true, options: compileOptionsOf(plugin, config) }\n }\n return { configFile: loaded, found: false }\n}\n\n/** `znight` and its sub-plugins (`znight:*`), not the CLI's own plugins. */\nfunction isZnightPluginName(name: string): boolean {\n return name === 'znight' || (name.startsWith('znight:') && !name.startsWith('znight:cli-'))\n}\n\nasync function preservingNodeEnv<T>(run: () => Promise<T>): Promise<T> {\n const nodeEnv = process.env['NODE_ENV']\n try {\n return await run()\n } finally {\n if (nodeEnv === undefined) delete process.env['NODE_ENV']\n else process.env['NODE_ENV'] = nodeEnv\n }\n}\n\nconst isObject = (value: unknown): value is Record<string, unknown> => typeof value === 'object' && value !== null\n\n/** {@link ZnightPluginLookup.options}: the compiler's resolved options when exposed, else derived. */\nfunction compileOptionsOf(plugin: object, config: ResolvedConfigLike): ZnightOptions {\n const api = (plugin as { api?: unknown }).api\n let options: ZnightOptions = {}\n let resolved: Record<string, unknown> | undefined\n if (isObject(api)) {\n const value: unknown = typeof api['getOptions'] === 'function' ? api['getOptions'].call(api) : api['options']\n if (isObject(value)) options = value as ZnightOptions\n const compiler = api['compiler']\n if (isObject(compiler) && isObject(compiler['options'])) resolved = compiler['options']\n }\n const root = typeof resolved?.['root'] === 'string' ? resolved['root'] : resolve(config.root, options.root ?? '.')\n const aliases = Array.isArray(resolved?.['aliases'])\n ? (resolved['aliases'] as StringAliasLike[])\n : stringAliases(config.resolve?.alias)\n const conditions = resolved?.['runtimeConditions']\n return {\n ...options,\n root,\n ...(aliases.length > 0 ? { aliases } : {}),\n ...(Array.isArray(conditions) ? { runtimeConditions: conditions as string[] } : {}),\n }\n}\n\n/** The string entries of Vite's (resolved) `resolve.alias`: the compiler ignores RegExp aliases. */\nfunction stringAliases(alias: unknown): StringAliasLike[] {\n if (!Array.isArray(alias)) return []\n return alias.filter(\n (entry): entry is StringAliasLike =>\n isObject(entry) && typeof entry['find'] === 'string' && typeof entry['replacement'] === 'string',\n )\n}\n\n/** Message of a Vite/Rolldown build error, with its location and code frame when available. */\nexport function formatBuildError(error: unknown): string {\n if (!(error instanceof Error)) return String(error)\n const details = error as Error & {\n plugin?: string\n id?: string\n loc?: { file?: string; line: number; column: number }\n frame?: string\n }\n const lines = [details.plugin === undefined ? error.message : `[${details.plugin}] ${error.message}`]\n const file = details.loc?.file ?? details.id\n if (file !== undefined && !error.message.includes(file)) {\n lines.push(details.loc === undefined ? ` --> ${file}` : ` --> ${file}:${details.loc.line}:${details.loc.column}`)\n }\n if (details.frame !== undefined && details.frame !== '' && !error.message.includes(details.frame)) {\n lines.push(details.frame)\n }\n return lines.join('\\n')\n}\n","/**\n * File watching for `znight generate --watch` (`fs.watch`, recursive on macOS, Windows and Linux with\n * Node.js >= 20 / Bun). It covers what the Vite plugin and the Bun preload watch: the `include`\n * directories of the project and of its source libraries (recursively), the project root\n * (`package.json`, `tsconfig.json`, lockfiles) and the directories of the files the last compile\n * depends on (`watchFiles`: library manifests, compiled libraries...), refreshed after every compile.\n * Which events matter is the compiler's call (`includeRoots()`, `isRelevantChange()`); this module\n * only turns `fs.watch` events, which carry no kind and report a moved directory without its files,\n * into compiler changes.\n *\n * Paths handed to the compiler are absolute, real (symbolic links resolved) and POSIX-style, like the\n * paths of the compiler itself (`watchFiles`, `includeRoots()`).\n */\nimport type { ChangeKind, CompilerChanges } from './compiler.ts'\n\nimport { existsSync, type FSWatcher, realpathSync, statSync, watch } from 'node:fs'\nimport { join, posix, resolve } from 'node:path'\n\n/** A directory to watch. */\nexport interface WatchTarget {\n readonly path: string\n readonly recursive: boolean\n}\n\n/** A running watcher. */\nexport interface FileWatcher {\n close(): void\n}\n\n/**\n * Starts watching `targets`; `onChange` receives the absolute path of every changed file or\n * directory (created, modified, deleted or renamed), except in ignored directories\n * ({@link isIgnoredPath}).\n */\nexport type WatchFactory = (targets: readonly WatchTarget[], onChange: (file: string) => void) => FileWatcher\n\nconst IGNORED_SEGMENTS = new Set(['node_modules', 'dist', 'coverage'])\n\n/** Native separators to forward slashes (the compiler's path style, also on Windows). */\nexport function toPosixPath(path: string): string {\n return path.includes('\\\\') ? path.replaceAll('\\\\', '/') : path\n}\n\n/**\n * The absolute, POSIX-style real path of `path` (symbolic links resolved and the on-disk casing:\n * `/var` → `/private/var` on macOS), also when its last segments do not exist (anymore): the real\n * path of the deepest existing parent, then the rest. Makes watcher paths comparable with the\n * compiler's.\n */\nexport function realPath(path: string): string {\n const absolute = resolve(path)\n try {\n return toPosixPath(realpathSync.native(absolute))\n } catch {\n const parent = resolve(absolute, '..')\n if (parent === absolute) return toPosixPath(absolute)\n return `${realPath(parent).replace(/\\/$/, '')}/${posix.basename(toPosixPath(absolute))}`\n }\n}\n\n/**\n * Whether a path relative to a watched directory is never relevant: inside `node_modules`, `dist`,\n * `coverage` or a dot directory (`.git`, `.znight`...).\n */\nexport function isIgnoredPath(relativePath: string): boolean {\n return relativePath.split(/[\\\\/]/).some(segment => IGNORED_SEGMENTS.has(segment) || segment.startsWith('.'))\n}\n\n/** `true` when `file` is `directory` or inside it (absolute POSIX paths). */\nexport function isWithin(directory: string, file: string): boolean {\n return file === directory || file.startsWith(directory.endsWith('/') ? directory : `${directory}/`)\n}\n\n/** Drops the directories nested in another one; sorted, de-duplicated. */\nfunction outermost(directories: Iterable<string>): string[] {\n const sorted = [...new Set(directories)].sort()\n return sorted.filter(directory => !sorted.some(other => other !== directory && isWithin(other, directory)))\n}\n\n/**\n * Directories to watch: the include `roots` (`includeRoots()` of the compiler) recursively; the\n * project `root` and the directories of `files` (the `watchFiles` of the last compile) that are\n * outside them, non-recursively.\n */\nexport function watchTargets(root: string, roots: readonly string[], files: Iterable<string> = []): WatchTarget[] {\n const recursive = outermost(roots.map(toPosixPath))\n const covered = (directory: string): boolean => recursive.some(base => isWithin(base, directory))\n const flat = new Set<string>()\n const directories = [toPosixPath(resolve(root))]\n for (const file of files) directories.push(posix.dirname(toPosixPath(resolve(file))))\n for (const directory of directories) if (!covered(directory)) flat.add(directory)\n return [\n ...recursive.map(path => ({ path, recursive: true })),\n ...[...flat].sort().map(path => ({ path, recursive: false })),\n ]\n}\n\ntype PathKind = 'file' | 'directory' | 'missing'\n\nfunction kindOf(path: string): PathKind {\n try {\n return statSync(path).isDirectory() ? 'directory' : 'file'\n } catch {\n return 'missing'\n }\n}\n\n/** The known files inside `directory`. */\nfunction knownWithin(known: ReadonlySet<string>, directory: string): string[] {\n const prefix = directory.endsWith('/') ? directory : `${directory}/`\n return [...known].filter(file => file.startsWith(prefix))\n}\n\n/**\n * The kind of an `fs.watch` event on `file` (absolute, real, POSIX-style), which `fs.watch` does not\n * tell, from the disk and the files of the last compile (`known`): `removed` when it is gone,\n * `changed` for a known file, `added` otherwise (a new file, a directory created or moved there).\n */\nexport function changeKind(file: string, known: ReadonlySet<string>): ChangeKind {\n switch (kindOf(file)) {\n case 'missing':\n return 'removed'\n case 'directory':\n return 'added'\n default:\n return known.has(file) ? 'changed' : 'added'\n }\n}\n\n/**\n * Classifies relevant paths (`isRelevantChange()` of the compiler) for the incremental compiler,\n * given the files of the last compile: a deleted path is removed with the known files it contained\n * (a directory moved away), an existing directory is added (the compiler re-runs the scan) and the\n * known files it contains are re-read (or removed when gone), an existing file is changed when\n * known, added otherwise.\n */\nexport function classifyChanges(files: Iterable<string>, known: ReadonlySet<string>): CompilerChanges {\n const changed = new Set<string>()\n const added = new Set<string>()\n const removed = new Set<string>()\n for (const file of files) {\n switch (kindOf(file)) {\n case 'missing':\n removed.add(file)\n for (const inner of knownWithin(known, file)) removed.add(inner)\n break\n case 'directory':\n added.add(file)\n for (const inner of knownWithin(known, file)) (existsSync(inner) ? changed : removed).add(inner)\n break\n default:\n if (known.has(file)) changed.add(file)\n else added.add(file)\n }\n }\n return {\n changed: [...changed].filter(file => !removed.has(file)),\n added: [...added].filter(file => !removed.has(file)),\n removed: [...removed],\n }\n}\n\n/** The default {@link WatchFactory}, based on `fs.watch`. */\nexport const watchFiles: WatchFactory = (targets, onChange) => {\n const watchers: FSWatcher[] = []\n for (const target of targets) {\n if (!existsSync(target.path)) continue\n let watcher: FSWatcher\n try {\n watcher = watch(target.path, { recursive: target.recursive }, (_event, filename) => {\n // no file name (rare, Linux): something changed in the directory itself\n if (filename === null) {\n onChange(target.path)\n return\n }\n const name = filename.toString()\n if (!isIgnoredPath(name)) onChange(join(target.path, name))\n })\n } catch {\n // removed meanwhile (or not watchable): the next compile refreshes the targets\n continue\n }\n watcher.on('error', () => {\n // a watched directory was removed: keep the other watchers running\n })\n watchers.push(watcher)\n }\n return {\n close: () => {\n for (const watcher of watchers) watcher.close()\n },\n }\n}\n\nconst targetKey = (target: WatchTarget): string => `${target.recursive ? 'r' : 'f'}:${target.path}`\n\n/**\n * The watchers of a set of targets that changes after every compile: one watcher per target (started\n * with a {@link WatchFactory}), so that unchanged targets keep their watcher.\n */\nexport class TargetWatchers {\n readonly #factory: WatchFactory\n readonly #onChange: (file: string) => void\n readonly #watchers = new Map<string, { readonly watcher: FileWatcher; readonly existed: boolean }>()\n\n constructor(factory: WatchFactory, onChange: (file: string) => void) {\n this.#factory = factory\n this.#onChange = onChange\n }\n\n /** The watched targets. */\n get targets(): WatchTarget[] {\n return [...this.#watchers.keys()].map(key => ({ path: key.slice(2), recursive: key.startsWith('r') }))\n }\n\n /**\n * Watches exactly `targets`: stops the watchers of the targets that are gone, starts the new ones,\n * and restarts those whose directory was missing when they started, or was itself created, moved or\n * deleted since (`touched`: the paths of the last changes).\n */\n update(targets: readonly WatchTarget[], touched: ReadonlySet<string> = new Set()): void {\n const wanted = new Map(targets.map(target => [targetKey(target), target]))\n for (const [key, entry] of this.#watchers) {\n if (wanted.has(key)) continue\n entry.watcher.close()\n this.#watchers.delete(key)\n }\n for (const [key, target] of wanted) {\n const entry = this.#watchers.get(key)\n const exists = existsSync(target.path)\n if (entry !== undefined) {\n if (!exists || (entry.existed && !touched.has(target.path))) continue\n entry.watcher.close()\n }\n this.#watchers.set(key, { watcher: this.#factory([target], this.#onChange), existed: exists })\n }\n }\n\n close(): void {\n for (const entry of this.#watchers.values()) entry.watcher.close()\n this.#watchers.clear()\n }\n}\n","/**\n * JavaScript runtimes the application can run on (`znight dev`, `znight start`) and executable\n * lookup in `PATH`.\n */\nimport { accessSync, constants, statSync } from 'node:fs'\nimport { delimiter, isAbsolute, join } from 'node:path'\n\n/** Runtime of the application process. */\nexport type RuntimeName = 'node' | 'bun'\n\n/** `--runtime` values: `auto` picks Bun when the CLI itself runs on Bun, Node.js otherwise. */\nexport type RuntimeOption = RuntimeName | 'auto'\n\n/** The runtime executing the CLI. */\nexport interface HostRuntime {\n readonly name: RuntimeName\n /** Absolute path of the running executable (`process.execPath`). */\n readonly execPath: string\n readonly platform: NodeJS.Platform\n}\n\n/** Detects the runtime executing this process. */\nexport function detectHostRuntime(): HostRuntime {\n const isBun = typeof process.versions['bun'] === 'string'\n return { name: isBun ? 'bun' : 'node', execPath: process.execPath, platform: process.platform }\n}\n\n/** Resolves `auto`. */\nexport function resolveRuntime(option: RuntimeOption | undefined, host: HostRuntime): RuntimeName {\n return option === undefined || option === 'auto' ? host.name : option\n}\n\n/**\n * Finds an executable in `PATH` (`PATHEXT` extensions on Windows). Absolute paths are checked as is.\n * Returns `undefined` when not found.\n */\nexport function which(\n command: string,\n env: Readonly<Record<string, string | undefined>>,\n platform: NodeJS.Platform = process.platform,\n): string | undefined {\n const extensions =\n platform === 'win32' ? ['', ...(env['PATHEXT'] ?? '.EXE;.CMD;.BAT;.COM').split(';').filter(Boolean)] : ['']\n const candidates = isAbsolute(command)\n ? [command]\n : (env['PATH'] ?? env['Path'] ?? '')\n .split(platform === 'win32' ? ';' : delimiter)\n .filter(directory => directory !== '')\n .map(directory => join(directory, command))\n for (const candidate of candidates) {\n for (const extension of extensions) {\n const file = candidate + extension\n if (isExecutable(file, platform)) return file\n }\n }\n return undefined\n}\n\nfunction isExecutable(file: string, platform: NodeJS.Platform): boolean {\n try {\n if (!statSync(file).isFile()) return false\n if (platform !== 'win32') accessSync(file, constants.X_OK)\n return true\n } catch {\n return false\n }\n}\n\n/**\n * The executable of `runtime`: the running executable when it is that runtime, otherwise the one\n * found in `PATH`.\n */\nexport function runtimeExecutable(\n runtime: RuntimeName,\n host: HostRuntime,\n env: Readonly<Record<string, string | undefined>>,\n): string | undefined {\n if (runtime === host.name) return host.execPath\n return which(runtime, env, host.platform)\n}\n\n/** Runtime arguments placed before the entry file. */\nexport function runtimeArguments(runtime: RuntimeName, extra: readonly string[] = []): string[] {\n // Vite emits source maps for server builds: map stack traces to the TypeScript sources.\n return runtime === 'node' ? ['--enable-source-maps', ...extra] : [...extra]\n}\n","import { readFileSync } from 'node:fs'\n\nlet cached: string | undefined\n\n/**\n * Version of `@znight/cli`, read from its `package.json` (one level above both `src/` and `dist/`).\n * Projects created by `znight new` depend on `@znight/*` packages at `^<version>`.\n */\nexport function cliVersion(): string {\n if (cached === undefined) {\n try {\n const manifest: unknown = JSON.parse(readFileSync(new URL('../package.json', import.meta.url), 'utf8'))\n const version = (manifest as { version?: unknown }).version\n cached = typeof version === 'string' ? version : '0.0.0'\n } catch {\n cached = '0.0.0'\n }\n }\n return cached\n}\n","/**\n * Everything a command needs from the outside world: streams, environment, runtime and the\n * services (compiler, Vite, processes, prompts, file watching). Tests replace any of them.\n */\nimport type { CompilerApi } from './integrations/compiler.ts'\nimport type { OpenApiEmitApi, OpenApiViteApi } from './integrations/openapi.ts'\nimport type { ProcessService } from './integrations/process.ts'\nimport type { Prompts } from './integrations/prompts.ts'\nimport type { ViteApi } from './integrations/vite.ts'\nimport type { WatchFactory } from './integrations/watch.ts'\nimport type { Colors, OutputStream, Reporter } from './output.ts'\nimport type { HostRuntime } from './runtime.ts'\n\nimport { loadCompiler } from './integrations/compiler.ts'\nimport { loadOpenApiEmit, loadOpenApiVite } from './integrations/openapi.ts'\nimport { createProcessService } from './integrations/process.ts'\nimport { loadPrompts } from './integrations/prompts.ts'\nimport { loadVite } from './integrations/vite.ts'\nimport { watchFiles } from './integrations/watch.ts'\nimport { createColors, createReporter, shouldUseColor } from './output.ts'\nimport { detectHostRuntime } from './runtime.ts'\nimport { cliVersion } from './version.ts'\n\n/** A source of process signals (`process` by default). */\nexport interface SignalSource {\n on(signal: NodeJS.Signals, listener: () => void): void\n off(signal: NodeJS.Signals, listener: () => void): void\n}\n\n/** External services, lazily loaded. */\nexport interface CliServices {\n /** Loads `@znight/compiler` for the project at `root`. */\n loadCompiler(root: string): Promise<CompilerApi>\n /** Loads `vite` for the project at `root`. */\n loadVite(root: string): Promise<ViteApi>\n /** Loads the interactive prompts. */\n loadPrompts(): Promise<Prompts>\n /** Loads `@znight/openapi/emit` for the project at `root` (`znight openapi`). */\n loadOpenApi(root: string): Promise<OpenApiEmitApi>\n /** Loads `@znight/openapi/vite` for the project at `root` (`znight build --openapi`). */\n loadOpenApiVite(root: string): Promise<OpenApiViteApi>\n readonly processes: ProcessService\n readonly watch: WatchFactory\n}\n\n/** The execution context of a command. */\nexport interface CliContext {\n readonly cwd: string\n readonly env: Readonly<Record<string, string | undefined>>\n readonly stdout: OutputStream\n readonly stderr: OutputStream\n /** Whether prompts may be shown (stdin and stdout are TTYs, not in CI). */\n readonly interactive: boolean\n readonly colors: Colors\n readonly reporter: Reporter\n readonly runtime: HostRuntime\n /** Version of `@znight/cli`. */\n readonly version: string\n readonly signals: SignalSource\n readonly services: CliServices\n /** Print stack traces of unexpected errors. */\n readonly debug: boolean\n}\n\n/** Overrides accepted by {@link createContext}. */\nexport interface CliContextOptions {\n readonly cwd?: string\n readonly env?: Readonly<Record<string, string | undefined>>\n readonly stdout?: OutputStream\n readonly stderr?: OutputStream\n readonly interactive?: boolean\n /** `--color` / `--no-color`. */\n readonly color?: boolean | undefined\n readonly runtime?: HostRuntime\n readonly version?: string\n readonly signals?: SignalSource\n readonly services?: Partial<CliServices>\n readonly debug?: boolean\n}\n\nconst processSignals: SignalSource = {\n on: (signal, listener) => {\n process.on(signal, listener)\n },\n off: (signal, listener) => {\n process.off(signal, listener)\n },\n}\n\n/**\n * Creates a context from the current process, with optional overrides. The environment is a copy\n * of `process.env` taken now: tools running in the CLI process (Vite sets `NODE_ENV`) do not change\n * what the commands see and pass to the application.\n */\nexport function createContext(options: CliContextOptions = {}): CliContext {\n const env = options.env ?? { ...process.env }\n const stdout = options.stdout ?? process.stdout\n const stderr = options.stderr ?? process.stderr\n const colors = createColors(shouldUseColor({ env, stream: stdout, flag: options.color }))\n const interactive =\n options.interactive ??\n (process.stdin.isTTY === true && stdout.isTTY === true && env['CI'] === undefined && env['TERM'] !== 'dumb')\n return {\n cwd: options.cwd ?? process.cwd(),\n env,\n stdout,\n stderr,\n interactive,\n colors,\n reporter: createReporter(stdout, stderr, colors),\n runtime: options.runtime ?? detectHostRuntime(),\n version: options.version ?? cliVersion(),\n signals: options.signals ?? processSignals,\n debug:\n options.debug ?? (env['ZNIGHT_DEBUG'] !== undefined && env['ZNIGHT_DEBUG'] !== '' && env['ZNIGHT_DEBUG'] !== '0'),\n services: {\n loadCompiler: options.services?.loadCompiler ?? loadCompiler,\n loadVite: options.services?.loadVite ?? loadVite,\n loadPrompts: options.services?.loadPrompts ?? loadPrompts,\n loadOpenApi: options.services?.loadOpenApi ?? loadOpenApiEmit,\n loadOpenApiVite: options.services?.loadOpenApiVite ?? loadOpenApiVite,\n processes: options.services?.processes ?? createProcessService(),\n watch: options.services?.watch ?? watchFiles,\n },\n }\n}\n","/**\n * Restart orchestration of `znight dev`: one application process at a time, restarted (debounced)\n * after each successful build. Stopping sends SIGTERM, waits for the exit and sends SIGKILL after a\n * timeout. Restarts are serialised and coalesced: a burst of builds causes one restart with the\n * latest output. A failed build simply does not schedule a restart (and cancels a pending one when\n * its output is broken), so the last good process keeps running.\n */\nimport type { ChildHandle, ExitStatus } from '../integrations/process.ts'\n\n/** Notifications of an {@link AppSupervisor}. */\nexport interface SupervisorEvents {\n /** A process was started (`restart` is false for the first one). */\n onStart?(child: ChildHandle, restart: boolean): void\n /** A process stopped by the supervisor exited (`forced`: it needed SIGKILL). */\n onStop?(status: ExitStatus, forced: boolean): void\n /** The current process exited by itself (crash, or the application ended). */\n onExit?(status: ExitStatus): void\n /** Starting a process failed synchronously. */\n onError?(error: unknown): void\n}\n\n/** Options of {@link AppSupervisor}. */\nexport interface AppSupervisorOptions {\n /** Starts a new application process. */\n readonly spawn: () => ChildHandle\n /** Delay applied by {@link AppSupervisor.scheduleRestart}. Default 100 ms. */\n readonly debounceMs?: number\n /** Time a process gets to exit after SIGTERM before SIGKILL. Default 5000 ms. */\n readonly killTimeoutMs?: number\n readonly events?: SupervisorEvents\n}\n\n/** Keeps one application process running and restarts it on demand. */\nexport class AppSupervisor {\n readonly #spawn: () => ChildHandle\n readonly #debounceMs: number\n readonly #killTimeoutMs: number\n readonly #events: SupervisorEvents\n readonly #stopping = new Set<ChildHandle>()\n #current: ChildHandle | undefined\n #debounce: ReturnType<typeof setTimeout> | undefined\n #queue: Promise<void> = Promise.resolve()\n #queued = false\n #closed = false\n #started = 0\n\n constructor(options: AppSupervisorOptions) {\n this.#spawn = options.spawn\n this.#debounceMs = options.debounceMs ?? 100\n this.#killTimeoutMs = options.killTimeoutMs ?? 5000\n this.#events = options.events ?? {}\n }\n\n /** Whether an application process is running. */\n get running(): boolean {\n return this.#current !== undefined\n }\n\n /** The running process. */\n get current(): ChildHandle | undefined {\n return this.#current\n }\n\n /** Number of processes started so far. */\n get starts(): number {\n return this.#started\n }\n\n /** Restarts after `debounceMs`; calls in between postpone it. */\n scheduleRestart(): void {\n if (this.#closed) return\n if (this.#debounce !== undefined) clearTimeout(this.#debounce)\n this.#debounce = setTimeout(() => {\n this.#debounce = undefined\n void this.restart()\n }, this.#debounceMs)\n }\n\n /**\n * Cancels a restart scheduled by {@link scheduleRestart} and not started yet (the output it would\n * run turned out to be broken, e.g. a failed compilation). Returns whether one was pending.\n */\n cancelRestart(): boolean {\n if (this.#debounce === undefined) return false\n clearTimeout(this.#debounce)\n this.#debounce = undefined\n return true\n }\n\n /**\n * Stops the current process (if any) and starts a new one. Restarts never overlap; a restart\n * requested while another one is waiting to run is merged with it.\n */\n restart(): Promise<void> {\n if (this.#closed) return this.#queue\n if (this.#queued) return this.#queue\n this.#queued = true\n this.#queue = this.#queue\n .then(async () => {\n this.#queued = false\n if (this.#closed) return\n await this.#stopCurrent('SIGTERM')\n if (this.#closed) return\n this.#startNew()\n })\n .catch((error: unknown) => {\n // keep the queue usable: a failing listener must not block later restarts\n this.#queued = false\n this.#events.onError?.(error)\n })\n return this.#queue\n }\n\n /** Stops the current process with `signal` (SIGKILL after the timeout) and refuses new starts. */\n async stop(signal: NodeJS.Signals = 'SIGTERM'): Promise<void> {\n this.#closed = true\n if (this.#debounce !== undefined) {\n clearTimeout(this.#debounce)\n this.#debounce = undefined\n }\n await this.#queue\n await this.#stopCurrent(signal)\n }\n\n /** Immediately SIGKILLs every process (a second Ctrl+C). */\n kill(): void {\n this.#closed = true\n if (this.#debounce !== undefined) clearTimeout(this.#debounce)\n this.#current?.kill('SIGKILL')\n for (const child of this.#stopping) child.kill('SIGKILL')\n }\n\n #startNew(): void {\n let child: ChildHandle\n try {\n child = this.#spawn()\n } catch (error) {\n this.#events.onError?.(error)\n return\n }\n const restart = this.#started > 0\n this.#started++\n this.#current = child\n void child.exited.then(status => {\n if (this.#current !== child) return\n this.#current = undefined\n this.#events.onExit?.(status)\n })\n this.#events.onStart?.(child, restart)\n }\n\n async #stopCurrent(signal: NodeJS.Signals): Promise<void> {\n const child = this.#current\n if (child === undefined) return\n this.#current = undefined\n this.#stopping.add(child)\n try {\n child.kill(signal)\n let timer: ReturnType<typeof setTimeout> | undefined\n const timeout = new Promise<'timeout'>(resolve => {\n timer = setTimeout(() => resolve('timeout'), this.#killTimeoutMs)\n })\n const first = await Promise.race([child.exited, timeout])\n clearTimeout(timer)\n if (first === 'timeout') {\n child.kill('SIGKILL')\n this.#events.onStop?.(await child.exited, true)\n } else {\n this.#events.onStop?.(first, false)\n }\n } finally {\n this.#stopping.delete(child)\n }\n }\n}\n","/** Helpers shared by the commands. */\nimport type { CliContext } from '../context.ts'\n\nimport { existsSync, readFileSync, statSync } from 'node:fs'\nimport { dirname, isAbsolute, join, relative, resolve, sep } from 'node:path'\n\nimport { CliError, UsageError } from '../errors.ts'\n\n/** `--root`, resolved against the working directory. Must be an existing directory. */\nexport function resolveRoot(cli: CliContext, root: string | undefined): string {\n const directory = resolve(cli.cwd, root ?? '.')\n let isDirectory = false\n try {\n isDirectory = statSync(directory).isDirectory()\n } catch {\n isDirectory = false\n }\n if (!isDirectory) throw new CliError(`Project root not found: ${directory}`)\n return directory\n}\n\n/** The nearest directory containing a `package.json`, from `start` upwards (`start` when none). */\nexport function findProjectRoot(start: string): string {\n let directory = start\n for (;;) {\n if (existsSync(join(directory, 'package.json'))) return directory\n const parent = dirname(directory)\n if (parent === directory) return start\n directory = parent\n }\n}\n\n/** Reads `package.json` of `root` (an empty object when missing or invalid). */\nexport function readManifest(root: string): {\n dependencies?: Record<string, string>\n devDependencies?: Record<string, string>\n} {\n try {\n const manifest: unknown = JSON.parse(readFileSync(join(root, 'package.json'), 'utf8'))\n return typeof manifest === 'object' && manifest !== null ? manifest : {}\n } catch {\n return {}\n }\n}\n\n/** Parses a non-negative integer option (milliseconds...). */\nexport function parseNonNegativeInteger(value: string | undefined, option: string, fallback: number): number {\n if (value === undefined || value === '') return fallback\n const parsed = Number(value)\n if (!Number.isInteger(parsed) || parsed < 0) {\n throw new UsageError(`Invalid value for --${option}: expected a non-negative integer, got \"${value}\"`)\n }\n return parsed\n}\n\n/** An HTTP prefix option (`/api`, the `prefix` of `HttpPlugin`): `undefined` when not given. */\nexport function parseHttpPrefix(value: string | undefined, option: string): string | undefined {\n if (value === undefined) return undefined\n if (!value.startsWith('/')) {\n throw new UsageError(`Invalid --${option} \"${value}\": expected a path starting with \"/\"`)\n }\n return value\n}\n\n/** A path for messages: relative to `from`, or absolute when that is shorter. POSIX separators. */\nexport function displayPath(file: string, from: string): string {\n const path = relative(from, file)\n if (path === '') return '.'\n const shortest = isAbsolute(path) || (path.startsWith('..') && file.length < path.length) ? file : path\n return shortest.split(sep).join('/')\n}\n\n/**\n * Signals stopping a long-running command: Ctrl+C, `kill`, the terminal closed (`SIGHUP`) and, on\n * POSIX, `Ctrl+\\` (`SIGQUIT`). Without a listener the last two kill the CLI without running its exit\n * hooks, leaving the application of `znight dev` (in its own session) running.\n */\nexport const TERMINATION_SIGNALS: readonly NodeJS.Signals[] =\n process.platform === 'win32' ? ['SIGINT', 'SIGTERM', 'SIGHUP'] : ['SIGINT', 'SIGTERM', 'SIGHUP', 'SIGQUIT']\n\n/**\n * Calls `onFirst` on the first {@link TERMINATION_SIGNALS termination signal}; `onRepeat` runs on\n * any later one (force quit). Returns a function removing the listeners.\n */\nexport function onTermination(\n cli: CliContext,\n onFirst: (signal: NodeJS.Signals) => void,\n onRepeat: (signal: NodeJS.Signals) => void,\n): () => void {\n let received = false\n const listeners = TERMINATION_SIGNALS.map(signal => {\n const listener = (): void => {\n if (received) {\n onRepeat(signal)\n return\n }\n received = true\n onFirst(signal)\n }\n cli.signals.on(signal, listener)\n return [signal, listener] as const\n })\n return () => {\n for (const [signal, listener] of listeners) cli.signals.off(signal, listener)\n }\n}\n","/**\n * `znight build`: production build with Vite (the `znight()` plugin compiles the container).\n * `--openapi[=path]` adds the `openapi()` plugin of `@znight/openapi` when the Vite config has none:\n * the OpenAPI document is emitted after the bundle (`dist/openapi.json` by default), with the\n * `servers` of `--openapi-prefix` (the `prefix` of `HttpPlugin`) when `@OpenApiDocument` declares none.\n */\nimport type { Plugin } from 'vite'\nimport type { Command } from '../command.ts'\nimport type { CliContext } from '../context.ts'\nimport type { OpenApiVitePluginOptionsLike } from '../integrations/openapi.ts'\n\nimport { statSync } from 'node:fs'\n\nimport { defineCommand } from '../command.ts'\nimport { CliError, UsageError } from '../errors.ts'\nimport {\n createOutputTracker,\n formatBuildError,\n runBuild,\n type ViteConfigLoader,\n type ViteLogLevel,\n} from '../integrations/vite.ts'\nimport { formatBytes, formatDuration } from '../output.ts'\nimport { displayPath, parseHttpPrefix, resolveRoot } from './shared.ts'\n\n/** `znight build` */\nexport const buildCommand: Command = defineCommand({\n meta: {\n name: 'build',\n description: 'Build the application for production (vite build)',\n usage: '[options]',\n examples: [\n 'znight build',\n 'znight build --mode staging',\n 'znight build --openapi # also dist/openapi.json',\n 'znight build --openapi --openapi-prefix /api # HttpPlugin.configure({ prefix: \"/api\" })',\n ],\n details: [\n 'Fails on any compiler error. With the defaults of the znight() plugin, src/main.ts is built to dist/main.js.',\n '--openapi emits the OpenAPI document after the bundle (dist/openapi.json, or --openapi=<path>) with the',\n 'openapi() Vite plugin of @znight/openapi, unless the Vite config already registers it. When HttpPlugin',\n 'has a prefix, pass it with --openapi-prefix: it becomes the servers of the document (unless',\n '@OpenApiDocument declares servers), like the document the application serves in \"build\" mode.',\n ].join('\\n'),\n },\n args: {\n root: { type: 'string', valueHint: 'dir', description: 'Project root (default: the current directory)' },\n config: { type: 'string', valueHint: 'file', description: 'Vite config file (default: vite.config.*)' },\n mode: { type: 'string', default: 'production', description: 'Vite mode' },\n 'config-loader': {\n type: 'enum',\n options: ['bundle', 'runner', 'native'],\n description: 'How Vite loads the config file (default: bundle)',\n },\n 'log-level': {\n type: 'enum',\n options: ['info', 'warn', 'error', 'silent'],\n default: 'info',\n description: 'Vite log level',\n },\n openapi: {\n type: 'boolean',\n description: 'Also emit the OpenAPI document (dist/openapi.json, or --openapi=<path>; needs @znight/openapi)',\n },\n 'openapi-prefix': {\n type: 'string',\n valueHint: 'path',\n description: 'With --openapi: the HTTP prefix of HttpPlugin, the servers default of the document (/api)',\n },\n },\n async run({ args, cli, rawArgs }) {\n const root = resolveRoot(cli, args.root)\n const openapi = openapiOption(rawArgs, args.openapi)\n const prefix = parseHttpPrefix(args['openapi-prefix'], 'openapi-prefix')\n if (prefix !== undefined && openapi === undefined) {\n throw new UsageError('--openapi-prefix needs --openapi', [`znight build --openapi --openapi-prefix ${prefix}`])\n }\n const vite = await cli.services.loadVite(root)\n const tracker = createOutputTracker(root)\n const extra: Plugin[] = []\n if (openapi !== undefined) {\n const api = await cli.services.loadOpenApiVite(root)\n const options: OpenApiVitePluginOptionsLike = {\n ...(openapi === true ? {} : { output: openapi }),\n ...(prefix === undefined ? {} : { prefix }),\n }\n const plugin = api.openapi(options)\n extra.push(plugin)\n const given = [\n ...(options.output === undefined ? [] : [`--openapi=${options.output}`]),\n ...(options.prefix === undefined ? [] : [`--openapi-prefix ${options.prefix}`]),\n ]\n if (given.length > 0) extra.push(ignoredOpenApiOptions(cli, plugin, given))\n }\n const started = performance.now()\n try {\n await runBuild(vite, {\n root,\n configFile: args.config,\n configLoader: args['config-loader'] as ViteConfigLoader | undefined,\n mode: args.mode,\n logLevel: args['log-level'] as ViteLogLevel,\n plugins: [tracker.plugin, ...extra],\n })\n } catch (error) {\n // like the Vite CLI: the (enhanced) error message carries the location and the code frame\n cli.reporter.logError(formatBuildError(error))\n throw new CliError('Build failed', { cause: error })\n }\n const entry = tracker.entry()\n const duration = formatDuration(performance.now() - started)\n if (entry === undefined) {\n cli.reporter.success(`Built in ${duration}`)\n return 0\n }\n let size = ''\n try {\n size = ` ${cli.colors.dim(formatBytes(statSync(entry).size))}`\n } catch {\n size = ''\n }\n cli.reporter.success(`Built ${cli.colors.bold(displayPath(entry, cli.cwd))}${size} in ${duration}`)\n cli.reporter.log(` ${cli.colors.dim('run it with')} ${cli.colors.cyan('znight start')}`)\n return 0\n },\n})\n\n/** `--openapi` (`true`), `--openapi=<path>` (the path), or `undefined`. */\nfunction openapiOption(rawArgs: readonly string[], parsed: unknown): true | string | undefined {\n for (const token of rawArgs) {\n if (token.startsWith('--openapi=')) {\n const value = token.slice('--openapi='.length)\n if (value === 'false') return undefined\n return value === '' || value === 'true' ? true : value\n }\n if (token === '--no-openapi') return undefined\n }\n return parsed === true || rawArgs.includes('--openapi') ? true : undefined\n}\n\n/**\n * When the Vite config registers its own `openapi()`, that one emits the document and the copy of the\n * CLI stays inactive: the options given on the command line (`given`) do not apply. Says so, instead\n * of emitting a document without the requested output or prefix.\n */\nfunction ignoredOpenApiOptions(cli: CliContext, plugin: Plugin, given: readonly string[]): Plugin {\n return {\n name: 'znight:cli-openapi-options',\n apply: 'build',\n configResolved(config) {\n const active = config.plugins.find(candidate => candidate.name === plugin.name)\n if (active === undefined || active === plugin) return\n cli.reporter.warn(\n `${given.join(' and ')} ignored: the openapi() plugin of the Vite config emits the document with its own options`,\n ['set them on openapi() in the Vite config (openapi({ output, prefix })), or remove it from there'],\n )\n },\n }\n}\n","/**\n * `znight dev`: Vite build in watch mode (no Vite dev server) and a full restart of the application\n * process after every successful rebuild — no partial hot replacement of providers: a restart is\n * fast and always consistent. A failed build keeps the last good process running, and so does a\n * failed compilation: in watch mode the `znight()` plugin does not fail the build (the bundle\n * contains a module throwing the diagnostics), so its result (`plugin.api.result`) is checked\n * before restarting.\n */\nimport type { Command } from '../command.ts'\nimport type { CliContext } from '../context.ts'\nimport type { Diagnostic } from '../integrations/compiler.ts'\nimport type { BuildWatcher, ViteConfigLoader, ViteLogLevel, WatcherEvent } from '../integrations/vite.ts'\n\nimport { resolve } from 'node:path'\n\nimport { defineCommand } from '../command.ts'\nimport { ORPHAN_GUARD_POLL_MS, orphanGuard } from '../dev/orphan.ts'\nimport { AppSupervisor } from '../dev/supervisor.ts'\nimport { CliError } from '../errors.ts'\nimport { fallbackFormatDiagnostics } from '../integrations/compiler.ts'\nimport { exitCodeOf } from '../integrations/process.ts'\nimport { createOutputTracker, formatBuildError, watchBuild } from '../integrations/vite.ts'\nimport { formatDuration, plural } from '../output.ts'\nimport { type RuntimeOption, resolveRuntime, runtimeArguments, runtimeExecutable } from '../runtime.ts'\nimport { displayPath, onTermination, parseNonNegativeInteger, resolveRoot } from './shared.ts'\n\n/** Clears the terminal and its scrollback. */\nconst CLEAR_SCREEN = '\\x1b[2J\\x1b[3J\\x1b[H'\n\n/** `znight dev` */\nexport const devCommand: Command = defineCommand({\n meta: {\n name: 'dev',\n description: 'Build in watch mode and restart the application after every successful rebuild',\n usage: '[options] [-- <application arguments>]',\n examples: ['znight dev', 'znight dev --runtime bun --clear', 'znight dev --inspect -- --verbose'],\n details: [\n 'Uses \"vite build --watch\" with the project Vite config (the znight() plugin regenerates the container).',\n 'On every successful build the application receives SIGTERM, gets --kill-timeout ms to stop gracefully',\n '(then SIGKILL), and a new process starts. A failed build or compilation (ZNIGHT errors) keeps the',\n 'last good process running.',\n ].join('\\n'),\n },\n args: {\n root: { type: 'string', valueHint: 'dir', description: 'Project root (default: the current directory)' },\n config: { type: 'string', valueHint: 'file', description: 'Vite config file (default: vite.config.*)' },\n mode: { type: 'string', default: 'development', description: 'Vite mode' },\n 'config-loader': {\n type: 'enum',\n options: ['bundle', 'runner', 'native'],\n description: 'How Vite loads the config file (default: bundle)',\n },\n runtime: {\n type: 'enum',\n options: ['auto', 'node', 'bun'],\n default: 'auto',\n description: 'Runtime of the application (auto: the runtime running the CLI)',\n },\n entry: { type: 'string', valueHint: 'file', description: 'File to run (default: the entry chunk of the build)' },\n inspect: { type: 'boolean', description: 'Start the application with --inspect (debugger)' },\n clear: { type: 'boolean', description: 'Clear the screen before each rebuild' },\n debounce: { type: 'string', valueHint: 'ms', default: '100', description: 'Delay before restarting after a build' },\n 'kill-timeout': {\n type: 'string',\n valueHint: 'ms',\n default: '5000',\n description: 'Time the application gets to stop after SIGTERM before SIGKILL',\n },\n 'log-level': {\n type: 'enum',\n options: ['info', 'warn', 'error', 'silent'],\n default: 'warn',\n description: 'Vite log level',\n },\n },\n async run({ args, cli, passthrough }) {\n const root = resolveRoot(cli, args.root)\n const debounceMs = parseNonNegativeInteger(args.debounce, 'debounce', 100)\n const killTimeoutMs = parseNonNegativeInteger(args['kill-timeout'], 'kill-timeout', 5000)\n const runtime = resolveRuntime(args.runtime as RuntimeOption, cli.runtime)\n const executable = runtimeExecutable(runtime, cli.runtime, cli.env)\n if (executable === undefined) {\n throw new CliError(`Cannot find \"${runtime}\" in PATH`, { hints: ['install it, or choose another --runtime'] })\n }\n const logLevel = args['log-level'] as ViteLogLevel\n const { colors, reporter } = cli\n // before Vite runs: its build sets process.env.NODE_ENV (to \"production\") when it is not set\n const env = { ...cli.env }\n // the application runs detached: it stops by itself when the CLI dies without stopping it (kill -9)\n const guard = orphanGuard(runtime, { parentPid: process.pid, pollMs: ORPHAN_GUARD_POLL_MS, killTimeoutMs })\n const runtimeArgs = runtimeArguments(runtime, [\n ...(guard?.args ?? []),\n ...(args.inspect === true ? ['--inspect'] : []),\n ])\n const vite = await cli.services.loadVite(root)\n const tracker = createOutputTracker(root)\n let entry: string | undefined\n\n const supervisor = new AppSupervisor({\n debounceMs,\n killTimeoutMs,\n spawn: () => {\n const file = entry ?? resolve(root, 'dist/main.js')\n return cli.services.processes.spawn(executable, [...runtimeArgs, file, ...passthrough], {\n cwd: root,\n env: { ...env, ...guard?.env, NODE_ENV: env['NODE_ENV'] ?? 'development' },\n detached: true,\n })\n },\n events: {\n onStart: (child, restart) => {\n const file = displayPath(entry ?? resolve(root, 'dist/main.js'), cli.cwd)\n reporter.info(\n `${restart ? 'Restarted' : 'Started'} ${colors.bold(file)} ${colors.dim(`(${runtime}, pid ${child.pid ?? '?'})`)}`,\n )\n },\n onStop: (_status, forced) => {\n if (forced) reporter.warn(`The application did not stop within ${killTimeoutMs}ms: killed`)\n },\n onExit: status => {\n if (status.error !== undefined) {\n reporter.error(`Cannot start ${runtime}: ${status.error.message}`)\n return\n }\n const code = exitCodeOf(status)\n const message = `The application exited with code ${code}${status.signal === null ? '' : ` (${status.signal})`}`\n if (code === 0) reporter.info(`${message}. Waiting for changes...`)\n else reporter.error(`${message}. Waiting for changes...`)\n },\n onError: error =>\n reporter.error(`Cannot start the application: ${error instanceof Error ? error.message : String(error)}`),\n },\n })\n\n const state = { failed: false, first: true, started: 0 }\n const onEvent = (event: WatcherEvent): void => {\n switch (event.code) {\n case 'START':\n state.failed = false\n state.started = performance.now()\n if (!state.first) {\n if (args.clear === true && cli.stdout.isTTY === true) cli.stdout.write(CLEAR_SCREEN)\n reporter.info(colors.dim('Change detected, rebuilding...'))\n }\n break\n case 'ERROR':\n state.failed = true\n state.first = false\n // Vite closes the build of BUNDLE_END itself, not the one of ERROR\n void Promise.resolve()\n .then(() => event.result?.close())\n .catch(() => undefined)\n // Vite logs build errors itself, unless it is silenced\n if (logLevel === 'silent') reporter.logError(formatBuildError(event.error))\n reporter.error(\n `Build failed. ${supervisor.running ? 'The last good build keeps running. ' : ''}Waiting for changes...`,\n )\n break\n case 'END': {\n state.first = false\n if (state.failed) break\n // the bundle was written, but with a failed compile it throws the diagnostics at startup\n const compile = tracker.compile()\n if (compile !== undefined && !compile.ok) {\n // a restart still pending for a previous build would run this broken output\n supervisor.cancelRestart()\n const errors = compile.diagnostics.filter(diagnostic => diagnostic.severity === 'error').length\n // the znight() plugin prints the diagnostics through the Vite logger, unless it is silenced\n const printed = logLevel === 'silent' ? printDiagnostics(cli, root, compile.diagnostics) : Promise.resolve()\n void printed.then(() =>\n reporter.error(\n `Compilation failed with ${plural(errors, 'error')}. ${supervisor.running ? 'The last good build keeps running. ' : ''}Waiting for changes...`,\n ),\n )\n break\n }\n entry = args.entry === undefined ? (tracker.entry() ?? entry) : resolve(root, args.entry)\n reporter.success(`Built in ${formatDuration(performance.now() - (tracker.startedAt() ?? state.started))}`)\n supervisor.scheduleRestart()\n break\n }\n default:\n break\n }\n }\n\n reporter.info(\n `${colors.bold('znight dev')} ${colors.dim(`v${cli.version}`)} — vite build --watch, ${runtime} runtime`,\n )\n let watcher: BuildWatcher\n try {\n watcher = await watchBuild(vite, {\n root,\n configFile: args.config,\n configLoader: args['config-loader'] as ViteConfigLoader | undefined,\n mode: args.mode,\n logLevel,\n plugins: [tracker.plugin],\n })\n } catch (error) {\n if (error instanceof CliError) throw error\n // configuration errors (the config file does not load, invalid options...)\n reporter.logError(formatBuildError(error))\n throw new CliError('Cannot start the Vite build', { cause: error })\n }\n watcher.on('event', onEvent)\n return waitForTermination(cli, watcher, supervisor)\n },\n})\n\n/** Prints compiler diagnostics with the project's `formatDiagnostics()` (a built-in formatter otherwise). */\nasync function printDiagnostics(cli: CliContext, root: string, diagnostics: readonly Diagnostic[]): Promise<void> {\n if (diagnostics.length === 0) return\n const options = { color: cli.colors.isColorSupported, cwd: root, summary: false }\n let text: string\n try {\n text = (await cli.services.loadCompiler(root)).formatDiagnostics(diagnostics, options)\n } catch {\n text = fallbackFormatDiagnostics(diagnostics, options)\n }\n cli.reporter.logError(text.trimEnd())\n}\n\nfunction waitForTermination(cli: CliContext, watcher: BuildWatcher, supervisor: AppSupervisor): Promise<number> {\n return new Promise<number>(resolveExit => {\n const dispose = onTermination(\n cli,\n signal => {\n // SIGHUP: the terminal is gone, nothing can be printed\n if (signal !== 'SIGHUP') cli.reporter.info(cli.colors.dim('Stopping... (press Ctrl+C again to force)'))\n void (async () => {\n try {\n await watcher.close()\n } finally {\n // the application stops gracefully on SIGINT or SIGTERM\n await supervisor.stop(signal === 'SIGINT' ? 'SIGINT' : 'SIGTERM')\n dispose()\n resolveExit(0)\n }\n })()\n },\n () => {\n supervisor.kill()\n dispose()\n resolveExit(130)\n },\n )\n })\n}\n","/**\n * `znight generate`: writes the DI container module (`src/.znight/container.generated.ts`), and the\n * files compiler extensions emit with it, with the compiler, checks that they are up to date\n * (`--check`, for CI) or keeps them up to date (`--watch`, for `tsc --watch` and editors).\n */\nimport type { Command } from '../command.ts'\nimport type { CliContext } from '../context.ts'\nimport type {\n CheckResultLike,\n CompileResultLike,\n CompilerApi,\n GenerateResultLike,\n IncrementalCompiler,\n ZnightConfigLike,\n ZnightOptions,\n} from '../integrations/compiler.ts'\n\nimport { existsSync } from 'node:fs'\nimport { resolve } from 'node:path'\n\nimport { defineCommand } from '../command.ts'\nimport { CliError, errorMessage } from '../errors.ts'\nimport { hasErrors } from '../integrations/compiler.ts'\nimport { findViteConfig, readZnightPluginOptions, type ViteConfigLoader } from '../integrations/vite.ts'\nimport {\n changeKind,\n classifyChanges,\n realPath,\n TargetWatchers,\n toPosixPath,\n watchTargets,\n} from '../integrations/watch.ts'\nimport { formatDuration, plural } from '../output.ts'\nimport { displayPath, onTermination, resolveRoot } from './shared.ts'\n\n/** `znight generate` */\nexport const generateCommand: Command = defineCommand({\n meta: {\n name: 'generate',\n description: 'Generate the dependency injection container (src/.znight/container.generated.ts)',\n usage: '[options]',\n examples: ['znight generate', 'znight generate --check # in CI, before tsc', 'znight generate --watch'],\n details: [\n 'The compiler options are read from znight.config.* (or the file named by ZNIGHT_CONFIG), the file',\n 'shared with the Bun preload; without one, from the znight() plugin of vite.config.ts, so that the',\n 'generated file is the same as the one of the Vite build. --config reads the given Vite config.',\n '\"znight generate <schematic> <name>\" is an alias of \"znight g <schematic> <name>\".',\n ].join('\\n'),\n },\n args: {\n check: {\n type: 'boolean',\n description: 'Do not write: exit with code 1 when the generated file is missing or out of date',\n },\n watch: { type: 'boolean', alias: 'w', description: 'Regenerate on every change' },\n root: { type: 'string', valueHint: 'dir', description: 'Project root (default: the current directory)' },\n config: {\n type: 'string',\n valueHint: 'file',\n description: 'Vite config file to read the znight() options from (instead of znight.config.*)',\n },\n 'config-loader': {\n type: 'enum',\n options: ['bundle', 'runner', 'native'],\n description: 'How Vite loads the config file (default: bundle)',\n },\n },\n async run({ args, cli }) {\n const root = resolveRoot(cli, args.root)\n const compiler = await cli.services.loadCompiler(root)\n const configLoader = args['config-loader'] as ViteConfigLoader | undefined\n const options = await compilerOptions(cli, compiler, root, args.config, configLoader)\n if (args.check === true) return check(cli, compiler, options)\n if (args.watch === true) return watch(cli, compiler, options)\n const result = await generateOnce(cli, compiler, options)\n return hasErrors(result.diagnostics) ? 1 : 0\n },\n})\n\n/**\n * The compiler options, with `root`: those of `znight.config.*` when the project has one (unless a\n * Vite config is given with `--config`), else those of `znight()` in the Vite config (when exposed),\n * else the defaults.\n */\nexport async function compilerOptions(\n cli: CliContext,\n compiler: CompilerApi,\n root: string,\n configFile: string | undefined,\n configLoader: ViteConfigLoader | undefined,\n): Promise<ZnightOptions> {\n if (configFile === undefined) {\n const shared = await znightConfigOptions(compiler, root)\n if (shared !== undefined) return shared\n }\n let options: ZnightOptions | undefined\n // no Vite config: nothing to read, do not even load Vite\n if (findViteConfig(root, configFile) === undefined) return { root }\n try {\n const vite = await cli.services.loadVite(root)\n const lookup = await readZnightPluginOptions(vite, root, configFile, configLoader)\n if (lookup !== undefined && !lookup.found) {\n cli.reporter.warn(`${displayPath(lookup.configFile, cli.cwd)} does not register the znight() plugin`)\n }\n options = lookup?.options\n } catch (error) {\n if (configFile !== undefined) {\n throw new CliError(`Cannot load the Vite config ${configFile}`, { cause: error, hints: [errorMessage(error)] })\n }\n cli.reporter.warn(\n `Cannot read the znight() options from the Vite config, using the defaults: ${errorMessage(error)}`,\n )\n }\n return { ...options, root: resolve(root, options?.root ?? '.') }\n}\n\n/** Options of `znight.config.*` (`loadZnightConfig()` of the compiler), `undefined` without the file. */\nasync function znightConfigOptions(compiler: CompilerApi, root: string): Promise<ZnightOptions | undefined> {\n if (compiler.loadConfig === undefined) return undefined\n let config: ZnightConfigLike\n try {\n config = await compiler.loadConfig(root)\n } catch (error) {\n throw new CliError('Cannot load the Znight config (znight.config.*)', {\n cause: error,\n hints: [errorMessage(error)],\n })\n }\n if (config.file === undefined) return undefined\n // `logLevel` is an option of the Bun preload only\n const { logLevel: _preloadLogLevel, ...options } = config.options\n return { ...options, root: resolve(root, options.root ?? '.') }\n}\n\nfunction printDiagnostics(cli: CliContext, compiler: CompilerApi, result: CompileResultLike, root: string): void {\n if (result.diagnostics.length === 0) return\n const text = compiler.formatDiagnostics(result.diagnostics, {\n color: cli.colors.isColorSupported,\n cwd: root,\n summary: false,\n })\n cli.reporter.logError(text.trimEnd())\n cli.reporter.logError()\n}\n\nfunction statsOf(result: CompileResultLike, elapsedMs: number): string {\n const parts: string[] = []\n if (result.stats?.providers !== undefined) parts.push(plural(result.stats.providers, 'provider'))\n if (result.stats?.files !== undefined) parts.push(plural(result.stats.files, 'file'))\n parts.push(formatDuration(result.stats?.durationMs ?? elapsedMs))\n return parts.join(', ')\n}\n\nfunction failure(cli: CliContext, result: CompileResultLike): void {\n const errors = result.diagnostics.filter(diagnostic => diagnostic.severity === 'error').length\n cli.reporter.error(`Generation failed with ${plural(errors, 'error')}`)\n}\n\n/** Prints the outcome of a generation. */\nfunction report(\n cli: CliContext,\n compiler: CompilerApi,\n result: GenerateResultLike,\n root: string,\n elapsed: number,\n): void {\n printDiagnostics(cli, compiler, result, root)\n if (hasErrors(result.diagnostics)) {\n failure(cli, result)\n return\n }\n const file = displayPath(result.outFile, cli.cwd)\n cli.reporter.success(\n `${result.written ? 'Generated' : 'Up to date:'} ${cli.colors.bold(file)} ${cli.colors.dim(`(${statsOf(result, elapsed)})`)}`,\n )\n}\n\nasync function generateOnce(\n cli: CliContext,\n compiler: CompilerApi,\n options: ZnightOptions,\n): Promise<GenerateResultLike> {\n const started = performance.now()\n const result = await compiler.generate(options)\n report(cli, compiler, result, options.root ?? cli.cwd, performance.now() - started)\n return result\n}\n\n/**\n * The generated files `--check` reports, the module first: those the compiler says are stale (the\n * module when it does not say which), and the module when it is missing.\n */\nfunction staleFilesOf(result: CheckResultLike): string[] {\n const stale = new Set<string>()\n if (!existsSync(result.outFile)) stale.add(result.outFile)\n if (result.stale) {\n const files = result.staleFiles ?? []\n for (const file of files.length > 0 ? files : [result.outFile]) stale.add(file)\n }\n return [...stale].sort((a, b) => Number(b === result.outFile) - Number(a === result.outFile))\n}\n\n/**\n * The hint of a missing generated file: the module, an extra file of the compiler extensions (an SDL\n * schema...) or the library manifest (`dist/znight.providers.json`).\n */\nfunction missingHint(path: string, outFile: string, extraFiles: ReadonlySet<string>): string {\n if (path === outFile) return 'run \"znight generate\" (it is git-ignored: generate it before tsc and tests)'\n if (extraFiles.has(path)) return 'run \"znight generate\" (a compiler extension generates it from the sources)'\n return 'run \"znight generate\" after the build: a build cleaning dist/ (tsdown, tsc --build --clean...) deletes it'\n}\n\nasync function check(cli: CliContext, compiler: CompilerApi, options: ZnightOptions): Promise<number> {\n const root = options.root ?? cli.cwd\n const started = performance.now()\n const result = await compiler.check(options)\n printDiagnostics(cli, compiler, result, root)\n if (hasErrors(result.diagnostics)) {\n failure(cli, result)\n return 1\n }\n const file = displayPath(result.outFile, cli.cwd)\n const stale = staleFilesOf(result)\n const extraFiles = new Set(result.extraFiles?.map(extra => extra.file))\n for (const path of stale) {\n const shown = displayPath(path, cli.cwd)\n if (existsSync(path)) cli.reporter.error(`${shown} is out of date`, ['run \"znight generate\"'])\n else cli.reporter.error(`${shown} is missing`, [missingHint(path, result.outFile, extraFiles)])\n }\n if (stale.length > 0) return 1\n cli.reporter.success(\n `${cli.colors.bold(file)} is up to date ${cli.colors.dim(`(${statsOf(result, performance.now() - started)})`)}`,\n )\n return 0\n}\n\n/** What the watcher knows about the last compile. */\ninterface WatchState {\n /** Files the last compile depends on (`watchFiles`): absolute, real, POSIX-style. */\n readonly known: ReadonlySet<string>\n /** Directories where a created or deleted source changes the scan (`includeRoots()`). */\n readonly roots: readonly string[]\n}\n\nasync function watch(cli: CliContext, compiler: CompilerApi, options: ZnightOptions): Promise<number> {\n const root = options.root ?? cli.cwd\n const realRoot = realPath(root)\n const incremental: IncrementalCompiler = compiler.createIncremental(options)\n let state: WatchState = { known: new Set(), roots: [] }\n let pending = new Set<string>()\n let running = false\n let timer: ReturnType<typeof setTimeout> | undefined\n\n // which events matter is the compiler's call: the CLI only tells their kind, which fs.watch does not\n const watchers = new TargetWatchers(cli.services.watch, file => {\n const path = realPath(file)\n if (!incremental.isRelevantChange(changeKind(path, state.known), path, state.known, state.roots)) return\n pending.add(path)\n if (timer !== undefined) clearTimeout(timer)\n timer = setTimeout(() => {\n timer = undefined\n void run(false)\n }, 50)\n })\n\n const run = async (initial: boolean): Promise<void> => {\n if (running) return\n running = true\n let first = initial\n try {\n do {\n const files = pending\n pending = new Set()\n const started = performance.now()\n let known = state.known\n try {\n const result = await incremental.generate(first ? undefined : classifyChanges(files, state.known))\n if (result.watchFiles !== undefined) {\n known = new Set(result.watchFiles.map(file => toPosixPath(resolve(file))))\n }\n report(cli, compiler, result, root, performance.now() - started)\n } catch (error) {\n cli.reporter.error(`Generation failed: ${errorMessage(error)}`)\n }\n // the include directories of the source libraries are known once compiled\n state = { known, roots: incremental.includeRoots().map(realPath) }\n watchers.update(watchTargets(realRoot, state.roots, state.known), files)\n first = false\n } while (pending.size > 0)\n } finally {\n running = false\n }\n }\n\n await run(true)\n cli.reporter.info(cli.colors.dim('Watching for changes... (Ctrl+C to stop)'))\n\n return new Promise<number>(resolveExit => {\n const dispose = onTermination(\n cli,\n () => {\n if (timer !== undefined) clearTimeout(timer)\n watchers.close()\n dispose()\n resolveExit(0)\n },\n () => undefined,\n )\n })\n}\n","/** Choices of `znight new`. */\n\n/** Package managers supported by `znight new`. */\nexport type PackageManager = 'bun' | 'npm' | 'pnpm' | 'yarn'\n\n/** HTTP adapters of `@znight/http`. */\nexport type HttpAdapterName = 'node' | 'fastify' | 'express' | 'hono'\n\n/** Optional features of a new project. */\nexport type Feature = 'config' | 'observability' | 'messaging' | 'schedule' | 'openapi'\n\n/** Every package manager, in display order. */\nexport const PACKAGE_MANAGERS: readonly PackageManager[] = ['bun', 'npm', 'pnpm', 'yarn']\n\n/** Every HTTP adapter, in display order. */\nexport const HTTP_ADAPTERS: readonly HttpAdapterName[] = ['node', 'fastify', 'express', 'hono']\n\n/** Every feature, in display (and canonical) order. */\nexport const FEATURES: readonly Feature[] = ['config', 'observability', 'messaging', 'schedule', 'openapi']\n\n/** Features selected when none are given. */\nexport const DEFAULT_FEATURES: readonly Feature[] = ['config', 'observability']\n\n/** Labels shown by the prompts and the help. */\nexport const ADAPTER_LABELS: Readonly<Record<HttpAdapterName, string>> = {\n node: 'node:http (built-in, zero dependency)',\n fastify: 'Fastify',\n express: 'Express',\n hono: 'Hono',\n}\n\n/** Labels shown by the prompts. */\nexport const FEATURE_LABELS: Readonly<Record<Feature, string>> = {\n config: 'Config: type-safe configuration classes (@znight/config)',\n observability: 'Observability: structured logs, metrics, tracing (@znight/observability)',\n messaging: 'Messaging: message consumers and publishing (@znight/messaging)',\n schedule: 'Schedule: cron, interval and timeout jobs (@znight/schedule)',\n openapi: 'OpenAPI: openapi.json and an API reference at /docs (@znight/openapi)',\n}\n\n/** Everything that determines the files of a new project. */\nexport interface ProjectOptions {\n /** npm package name. */\n readonly name: string\n readonly packageManager: PackageManager\n readonly adapter: HttpAdapterName\n /** Selected features, in canonical order. */\n readonly features: readonly Feature[]\n /** Version range base of the `@znight/*` packages (the CLI version). */\n readonly znightVersion: string\n}\n\n/**\n * Parses `--features` (`config,observability`, `none`, `all`). Returns the features in canonical\n * order, or the unknown names.\n */\nexport function parseFeatures(value: string): { features: Feature[] } | { unknown: string[] } {\n const names = value\n .split(',')\n .map(name => name.trim().toLowerCase())\n .filter(name => name !== '')\n if (names.length === 1 && names[0] === 'none') return { features: [] }\n if (names.length === 1 && names[0] === 'all') return { features: [...FEATURES] }\n const unknown = names.filter(name => !FEATURES.includes(name as Feature))\n if (unknown.length > 0) return { unknown }\n return { features: FEATURES.filter(feature => names.includes(feature)) }\n}\n\n/**\n * Default package manager: the one that launched the CLI (`npm_config_user_agent`: `pnpm dlx`,\n * `yarn dlx`, `bunx`, `npx`), else Bun when running on Bun, else npm.\n */\nexport function detectPackageManager(\n env: Readonly<Record<string, string | undefined>>,\n runningOnBun: boolean,\n): PackageManager {\n const agent = env['npm_config_user_agent'] ?? ''\n const name = agent.split('/')[0]\n if (name === 'bun' || name === 'npm' || name === 'pnpm' || name === 'yarn') return name\n return runningOnBun ? 'bun' : 'npm'\n}\n\n/** `bun install`, `npm install`... */\nexport function installCommand(pm: PackageManager): readonly [string, ...string[]] {\n return [pm, 'install']\n}\n\n/** `bun run dev`, `npm run dev`, `pnpm dev`, `yarn dev`. */\nexport function runScript(pm: PackageManager, script: string): string {\n return pm === 'pnpm' || pm === 'yarn' ? `${pm} ${script}` : `${pm} run ${script}`\n}\n\n/** Runs a binary of the project: `npx znight`, `bunx znight`, `pnpm znight`, `yarn znight`. */\nexport function execBinary(pm: PackageManager, binary: string): string {\n switch (pm) {\n case 'npm':\n return `npx ${binary}`\n case 'bun':\n return `bunx ${binary}`\n default:\n return `${pm} ${binary}`\n }\n}\n","/** Writing a new project to disk, initialising git and installing dependencies. */\nimport type { ProcessService, RunResult } from '../integrations/process.ts'\nimport type { PackageManager } from './options.ts'\nimport type { ProjectFile } from './templates.ts'\n\nimport { mkdirSync, readdirSync, statSync, writeFileSync } from 'node:fs'\nimport { dirname, join } from 'node:path'\n\nimport { installCommand } from './options.ts'\n\n/** Entries tolerated in the target directory (a fresh clone, editor settings). */\nconst IGNORABLE_ENTRIES = new Set(['.git', '.DS_Store', 'Thumbs.db', '.idea', '.vscode'])\n\n/** State of the target directory of `znight new`. */\nexport type TargetState = 'missing' | 'empty' | 'not-empty' | 'file'\n\n/** Inspects the target directory. */\nexport function targetState(directory: string): TargetState {\n let stats: ReturnType<typeof statSync>\n try {\n stats = statSync(directory)\n } catch {\n return 'missing'\n }\n if (!stats.isDirectory()) return 'file'\n return readdirSync(directory).every(entry => IGNORABLE_ENTRIES.has(entry)) ? 'empty' : 'not-empty'\n}\n\n/** Writes `files` under `directory` (created when missing). Returns the written paths. */\nexport function writeProject(directory: string, files: readonly ProjectFile[]): string[] {\n mkdirSync(directory, { recursive: true })\n for (const file of files) {\n const target = join(directory, file.path)\n mkdirSync(dirname(target), { recursive: true })\n writeFileSync(target, file.content)\n }\n return files.map(file => file.path)\n}\n\n/** Outcome of {@link initGit}. */\nexport type GitOutcome = 'initialized' | 'inside-repository' | 'unavailable' | 'failed'\n\n/** `git init` in `directory`, unless it already is inside a git work tree (monorepos). */\nexport async function initGit(\n processes: ProcessService,\n directory: string,\n env: Readonly<Record<string, string | undefined>>,\n): Promise<GitOutcome> {\n const inside = await processes.run('git', ['rev-parse', '--is-inside-work-tree'], { cwd: directory, env })\n if (inside.error !== undefined) return 'unavailable'\n if (inside.code === 0 && inside.stdout.trim() === 'true') return 'inside-repository'\n const init = await processes.run('git', ['init', '--quiet'], { cwd: directory, env })\n return init.code === 0 ? 'initialized' : 'failed'\n}\n\n/** `<pm> install` in `directory`, output captured. */\nexport function installDependencies(\n processes: ProcessService,\n directory: string,\n packageManager: PackageManager,\n env: Readonly<Record<string, string | undefined>>,\n): Promise<RunResult> {\n const [command, ...args] = installCommand(packageManager)\n return processes.run(command, args, { cwd: directory, env })\n}\n","/**\n * Version ranges of the third-party dependencies of new projects. `@znight/*` packages use\n * `^<version of @znight/cli>` (they are released in lockstep).\n */\nexport const DEPENDENCY_VERSIONS: Readonly<Record<string, string>> = {\n '@hono/node-server': '^2.1.5',\n '@types/bun': '^1.3.0',\n '@types/express': '^5.0.6',\n '@types/node': '^24.0.0',\n express: '^5.3.0',\n fastify: '^5.12.7',\n hono: '^4.13.14',\n 'light-my-request': '^6.8.0',\n typescript: '^7.0.0',\n vite: '^8.0.0',\n vitest: '^4.1.0',\n zod: '^4.6.0',\n}\n\n/** Range of a third-party dependency. */\nexport function versionOf(name: string): string {\n const version = DEPENDENCY_VERSIONS[name]\n if (version === undefined) throw new Error(`[znight] no version declared for ${name}`)\n return version\n}\n","/**\n * Files of a project created by `znight new`. Pure: {@link renderProject} returns the files for a set\n * of options, `create.ts` writes them. The sample application uses the public APIs of the\n * `@znight/*` packages exactly as documented in their READMEs.\n */\nimport type { Feature, HttpAdapterName, PackageManager, ProjectOptions } from './options.ts'\n\nimport { execBinary, runScript } from './options.ts'\nimport { versionOf } from './versions.ts'\n\n/** A file of the new project. */\nexport interface ProjectFile {\n /** POSIX path relative to the project directory. */\n readonly path: string\n readonly content: string\n}\n\ninterface Flags {\n readonly config: boolean\n readonly observability: boolean\n readonly messaging: boolean\n readonly schedule: boolean\n readonly openapi: boolean\n readonly adapter: HttpAdapterName\n readonly pm: PackageManager\n readonly bun: boolean\n}\n\nfunction flagsOf(options: ProjectOptions): Flags {\n const has = (feature: Feature): boolean => options.features.includes(feature)\n return {\n config: has('config'),\n observability: has('observability'),\n messaging: has('messaging'),\n schedule: has('schedule'),\n openapi: has('openapi'),\n adapter: options.adapter,\n pm: options.packageManager,\n bun: options.packageManager === 'bun',\n }\n}\n\n/** Every file of a new project, sorted by path. */\nexport function renderProject(options: ProjectOptions): ProjectFile[] {\n const flags = flagsOf(options)\n const files: ProjectFile[] = [\n { path: 'package.json', content: packageJson(options, flags) },\n { path: 'tsconfig.json', content: tsconfigJson(flags) },\n { path: 'vite.config.ts', content: viteConfig() },\n { path: 'znight.config.ts', content: znightConfig(flags) },\n { path: '.gitignore', content: gitignore() },\n { path: 'README.md', content: readme(options, flags) },\n { path: 'src/main.ts', content: mainTs(flags) },\n { path: 'src/app/greeting.schemas.ts', content: greetingSchemas(flags) },\n { path: 'src/app/greeting.service.ts', content: greetingService(flags) },\n { path: 'src/app/greeting.controller.ts', content: greetingController(flags) },\n { path: 'src/app/health.controller.ts', content: healthController() },\n { path: 'test/greeting.service.test.ts', content: greetingServiceTest(flags) },\n { path: 'test/greeting.controller.test.ts', content: greetingControllerTest(flags) },\n ]\n if (flags.config) files.push({ path: 'src/app/app.config.ts', content: appConfig() })\n if (flags.messaging) files.push({ path: 'src/app/greeting.consumer.ts', content: greetingConsumer(flags) })\n if (flags.schedule) {\n files.push({ path: 'src/app/heartbeat.jobs.ts', content: heartbeatJobs() })\n files.push({ path: 'test/heartbeat.jobs.test.ts', content: heartbeatJobsTest(flags) })\n }\n if (flags.openapi) files.push({ path: 'src/api.ts', content: apiDocument(options) })\n if (flags.bun) files.push({ path: 'bunfig.toml', content: bunfig(flags) })\n if (flags.pm === 'yarn') files.push({ path: '.yarnrc.yml', content: 'nodeLinker: node-modules\\n' })\n return files.sort((a, b) => (a.path < b.path ? -1 : 1))\n}\n\n// ---------------------------------------------------------------------------------------------------\n// configuration files\n\nfunction sortRecord(record: Record<string, string>): Record<string, string> {\n return Object.fromEntries(Object.entries(record).sort(([a], [b]) => (a < b ? -1 : 1)))\n}\n\nfunction packageJson(options: ProjectOptions, flags: Flags): string {\n const znight = `^${options.znightVersion}`\n const dependencies: Record<string, string> = {\n '@znight/core': znight,\n '@znight/http': znight,\n zod: versionOf('zod'),\n }\n if (flags.config) dependencies['@znight/config'] = znight\n if (flags.observability) dependencies['@znight/observability'] = znight\n if (flags.messaging) dependencies['@znight/messaging'] = znight\n if (flags.schedule) dependencies['@znight/schedule'] = znight\n if (flags.openapi) dependencies['@znight/openapi'] = znight\n if (flags.adapter === 'fastify') dependencies['fastify'] = versionOf('fastify')\n if (flags.adapter === 'express') dependencies['express'] = versionOf('express')\n if (flags.adapter === 'hono') {\n dependencies['hono'] = versionOf('hono')\n dependencies['@hono/node-server'] = versionOf('@hono/node-server')\n }\n const devDependencies: Record<string, string> = {\n '@types/node': versionOf('@types/node'),\n '@znight/cli': znight,\n '@znight/compiler': znight,\n '@znight/testing': znight,\n typescript: versionOf('typescript'),\n vite: versionOf('vite'),\n }\n if (flags.bun) devDependencies['@types/bun'] = versionOf('@types/bun')\n else devDependencies['vitest'] = versionOf('vitest')\n if (flags.adapter === 'express') devDependencies['@types/express'] = versionOf('@types/express')\n // in-memory requests (TestApp.inject) with the node and express adapters\n if (flags.adapter === 'node' || flags.adapter === 'express') {\n devDependencies['light-my-request'] = versionOf('light-my-request')\n }\n const manifest = {\n name: options.name,\n version: '0.1.0',\n private: true,\n type: 'module',\n engines: { node: '>=24' },\n scripts: {\n // `bun run` honours the node shebang of the znight binary: the runtime has to be explicit\n dev: flags.bun ? 'znight dev --runtime bun' : 'znight dev',\n build: 'znight build',\n start: flags.bun ? 'znight start --runtime bun' : 'znight start',\n generate: 'znight generate',\n typecheck: 'znight generate && tsc --noEmit',\n test: flags.bun ? 'bun test' : 'vitest run',\n ...(flags.openapi ? { openapi: 'znight openapi', 'openapi:check': 'znight openapi --check' } : {}),\n },\n dependencies: sortRecord(dependencies),\n devDependencies: sortRecord(devDependencies),\n }\n return `${JSON.stringify(manifest, null, 2)}\\n`\n}\n\nfunction tsconfigJson(flags: Flags): string {\n return `{\n \"compilerOptions\": {\n \"target\": \"ES2024\",\n \"lib\": [\"ES2024\", \"ESNext.Disposable\"],\n \"module\": \"preserve\",\n \"moduleResolution\": \"bundler\",\n \"moduleDetection\": \"force\",\n \"types\": [\"${flags.bun ? 'bun' : 'node'}\"],\n \"strict\": true,\n \"noUncheckedIndexedAccess\": true,\n \"noImplicitOverride\": true,\n // Znight decorators are TypeScript decorators: no emitDecoratorMetadata nor reflect-metadata\n \"experimentalDecorators\": true,\n \"verbatimModuleSyntax\": true,\n \"isolatedModules\": true,\n \"resolveJsonModule\": true,\n \"skipLibCheck\": true,\n \"noEmit\": true,\n // vite.config.ts imports ./znight.config.ts (also loaded as is by Node.js and Bun)\n \"allowImportingTsExtensions\": true\n },\n \"include\": [\"src\", \"test\", \"vite.config.ts\", \"znight.config.ts\"]\n}\n`\n}\n\nfunction viteConfig(): string {\n return `import { znight } from '@znight/compiler'\nimport { defineConfig } from 'vite'\n\nimport options from './znight.config.ts'\n\n// znight() generates the dependency injection container at build time and configures a server\n// build: src/main.ts -> dist/main.js (Node.js 24 target, source maps).\nexport default defineConfig({\n plugins: [znight(options)],\n})\n`\n}\n\nfunction znightConfig(flags: Flags): string {\n const readers = flags.bun\n ? `// Options of the Znight compiler. The znight() Vite plugin (vite.config.ts), the Bun preload of the\n// tests (bunfig.toml) and \\`znight generate\\` read them, so they all generate the same container.`\n : `// Options of the Znight compiler. The znight() Vite plugin (vite.config.ts, also used by Vitest)\n// and \\`znight generate\\` read them, so they all generate the same container.`\n return `import type { ZnightOptions } from '@znight/compiler'\n\n${readers}\n// https://github.com/znight-org/znight/tree/main/packages/compiler#options\nexport default {\n // reportUnused: true, // warn about providers nothing uses (ZNIGHT019)\n} satisfies ZnightOptions\n`\n}\n\nfunction bunfig(flags: Flags): string {\n // Bun loads .env files into process.env with its own precedence, which then wins over dotenv()\n const env = flags.config\n ? `# @znight/config loads the .env files (dotenv()), the same way on Node.js and Bun: Bun's own\n# loading would put them in process.env first, with its own precedence\nenv = false\n\n`\n : ''\n return `${env}[test]\n# Regenerates the DI container (src/.znight/container.generated.ts) before the tests run\npreload = [\"@znight/compiler/bun\"]\n`\n}\n\nfunction gitignore(): string {\n return `node_modules\ndist\ncoverage\n*.log\n\n# generated by the Znight compiler (znight generate, vite build, bun test)\n.znight\n\n# local environment\n.env.local\n.env.*.local\n`\n}\n\n// ---------------------------------------------------------------------------------------------------\n// application\n\nfunction adapterImport(adapter: HttpAdapterName): string | undefined {\n switch (adapter) {\n case 'fastify':\n return \"import { fastifyAdapter } from '@znight/http/fastify'\"\n case 'express':\n return \"import { expressAdapter } from '@znight/http/express'\"\n case 'hono':\n return \"import { honoAdapter } from '@znight/http/hono'\"\n default:\n return undefined\n }\n}\n\nfunction adapterCall(adapter: HttpAdapterName): string | undefined {\n return adapter === 'node' ? undefined : `${adapter}Adapter()`\n}\n\nfunction mainTs(flags: Flags): string {\n const imports = [\n flags.config ? \"import { ConfigPlugin } from '@znight/config'\" : undefined,\n \"import { Application } from '@znight/core'\",\n \"import { HttpPlugin } from '@znight/http'\",\n adapterImport(flags.adapter),\n flags.messaging ? \"import { MessagingPlugin } from '@znight/messaging'\" : undefined,\n flags.messaging ? \"import { memory } from '@znight/messaging/memory'\" : undefined,\n flags.observability ? \"import { ObservabilityPlugin } from '@znight/observability'\" : undefined,\n flags.openapi ? \"import { OpenApiPlugin } from '@znight/openapi'\" : undefined,\n flags.schedule ? \"import { SchedulePlugin } from '@znight/schedule'\" : undefined,\n ].filter(line => line !== undefined)\n const localImports = [\n \"import { __ZNIGHT_METADATA__ } from './.znight/container.generated.js'\",\n flags.config ? \"import { AppConfig } from './app/app.config.js'\" : undefined,\n ].filter(line => line !== undefined)\n\n const plugins: string[] = []\n if (flags.observability) {\n plugins.push(\n ' // first, so that its hooks wrap everything: request logs, metrics (with prom-client), traces',\n ' ObservabilityPlugin.configure(),',\n )\n }\n if (flags.config) {\n plugins.push(\n ' // loads .env files and the environment, validates every @Config class before anything starts',\n ' ConfigPlugin.configure(),',\n )\n }\n if (flags.messaging) {\n plugins.push(\n ' // in-memory broker for development: use rabbitmq(), sqs() or kafka() in production',\n ' MessagingPlugin.configure({ driver: memory() }),',\n )\n }\n if (flags.schedule) {\n plugins.push(\n ' // before HttpPlugin: plugins stop in reverse order, so HTTP stops first, then running jobs drain',\n ' SchedulePlugin.configure(),',\n )\n }\n const adapter = adapterCall(flags.adapter)\n if (flags.config) {\n plugins.push(\n ' HttpPlugin.configure(container => ({',\n ...(adapter === undefined ? [] : [` adapter: ${adapter},`]),\n ' port: container.get(AppConfig).port,',\n ' })),',\n )\n } else {\n const port = 'port: Number(process.env.PORT ?? 3000)'\n plugins.push(\n adapter === undefined\n ? ` HttpPlugin.configure({ ${port} }),`\n : ` HttpPlugin.configure({ adapter: ${adapter}, ${port} }),`,\n )\n }\n if (flags.openapi) {\n plugins.push(\n ' // GET /openapi.json and the API reference at /docs (document options: src/api.ts)',\n ' OpenApiPlugin.configure(),',\n )\n }\n\n return `${imports.join('\\n')}\n\n${localImports.join('\\n')}\n\nconst app = await Application.create({\n metadata: __ZNIGHT_METADATA__,\n plugins: [\n${plugins.join('\\n')}\n ],\n})\n\n// SIGINT / SIGTERM stop the application gracefully (in-flight requests are drained)\nawait app.start()\n`\n}\n\nfunction appConfig(): string {\n return `import { Config, Env } from '@znight/config'\n\n/**\n * Settings of the application, validated at boot by ConfigPlugin. Each property is read from the\n * environment (or a .env file): APP_<PROPERTY> by default, or the name given to @Env. Properties\n * with an initializer are optional; their type selects the coercion (\"3000\" -> 3000).\n */\n@Config('app')\nexport class AppConfig {\n /** HTTP port (PORT). */\n @Env('PORT')\n port = 3000\n\n /** Greeting used by GreetingService (APP_GREETING). */\n greeting = 'Hello'\n}\n`\n}\n\nfunction greetingSchemas(flags: Flags): string {\n const usage = flags.messaging\n ? 'Body of POST /greetings and POST /greetings/async, payload of the \"greetings\" queue.'\n : 'Body of POST /greetings.'\n return `import { z } from 'zod'\n\n/** ${usage} */\nexport const CreateGreeting = z.object({\n name: z.string().trim().min(1).max(100),\n excited: z.boolean().default(false),\n})\nexport type CreateGreeting = z.output<typeof CreateGreeting>\n`\n}\n\nfunction greetingService(flags: Flags): string {\n const imports = [\"import { Injectable } from '@znight/core'\"]\n if (flags.observability) imports.push(\"import { Logger } from '@znight/observability'\")\n const local = flags.config ? \"\\nimport { AppConfig } from './app.config.js'\\n\" : ''\n const params: string[] = []\n if (flags.config) params.push(' private readonly config: AppConfig,')\n if (flags.observability) params.push(' private readonly logger: Logger,')\n let members = ''\n if (params.length > 0) {\n members = ` // dependencies are resolved at build time from the parameter types\n constructor(\n${params.join('\\n')}\n ) {}\n\n`\n }\n const greeting = flags.config ? 'this.config.greeting' : \"'Hello'\"\n const log = flags.observability ? \" this.logger.debug('Greeting', { name, excited })\\n\" : ''\n return `${imports.join('\\n')}\n${local}\n@Injectable()\nexport class GreetingService {\n${members} greet(name: string, excited = false): string {\n${log} return \\`\\${${greeting}}, \\${name}\\${excited ? '!' : '.'}\\`\n }\n}\n`\n}\n\nfunction greetingController(flags: Flags): string {\n const httpImports = flags.messaging\n ? 'Body, Controller, Get, HttpCode, Param, Post, Query'\n : 'Body, Controller, Get, Param, Post, Query'\n const imports = [`import { ${httpImports} } from '@znight/http'`]\n if (flags.messaging) imports.push(\"import { MessageBroker } from '@znight/messaging'\")\n const ctor = flags.messaging\n ? ` constructor(\n private readonly greetings: GreetingService,\n private readonly broker: MessageBroker,\n ) {}`\n : ' constructor(private readonly greetings: GreetingService) {}'\n const enqueue = flags.messaging\n ? `\n\n /** POST /greetings/async: published to the \"greetings\" queue, handled by GreetingConsumer. */\n @Post('/async')\n @HttpCode(202)\n async enqueue(@Body(CreateGreeting) input: CreateGreeting): Promise<{ id: string }> {\n const { id } = await this.broker.publish('greetings', input, { type: 'greeting.requested' })\n return { id }\n }`\n : ''\n return `${imports.join('\\n')}\n\nimport { CreateGreeting } from './greeting.schemas.js'\nimport { GreetingService } from './greeting.service.js'\n\n@Controller('/greetings')\nexport class GreetingController {\n${ctor}\n\n /** GET /greetings/Ada?excited=true: route and query parameters are coerced to their types. */\n @Get('/:name')\n greet(@Param('name') name: string, @Query('excited') excited?: boolean): { message: string } {\n return { message: this.greetings.greet(name, excited) }\n }\n\n /** POST /greetings {\"name\": \"Ada\"}: the body is validated by the schema (400 otherwise). */\n @Post()\n create(@Body(CreateGreeting) input: CreateGreeting): { message: string } {\n return { message: this.greetings.greet(input.name, input.excited) }\n }${enqueue}\n}\n`\n}\n\nfunction healthController(): string {\n return `import { Controller, Get } from '@znight/http'\n\n@Controller('/health')\nexport class HealthController {\n /** GET /health */\n @Get()\n check(): { status: 'ok'; uptime: number } {\n return { status: 'ok', uptime: Math.round(process.uptime()) }\n }\n}\n`\n}\n\nfunction greetingConsumer(flags: Flags): string {\n const imports = [\"import { Consumer, Message, OnMessage, Retry } from '@znight/messaging'\"]\n if (flags.observability) imports.push(\"import { Logger } from '@znight/observability'\")\n const ctor = flags.observability\n ? ` constructor(\n private readonly greetings: GreetingService,\n private readonly logger: Logger,\n ) {}`\n : ' constructor(private readonly greetings: GreetingService) {}'\n const output = flags.observability\n ? ' this.logger.info(this.greetings.greet(request.name, request.excited))'\n : ' console.log(this.greetings.greet(request.name, request.excited))'\n return `${imports.join('\\n')}\n\nimport { CreateGreeting } from './greeting.schemas.js'\nimport { GreetingService } from './greeting.service.js'\n\n/**\n * Consumes the \"greetings\" queue. Delivery is at-least-once: handlers must be idempotent. A failing\n * handler is retried, then the message goes to the dead-letter queue (greetings.dlq).\n */\n@Consumer('greetings')\nexport class GreetingConsumer {\n${ctor}\n\n @OnMessage('greeting.requested')\n @Retry({ attempts: 3, backoff: 'exponential', delay: 500 })\n handle(@Message(CreateGreeting) request: CreateGreeting): void {\n${output}\n }\n}\n`\n}\n\nfunction heartbeatJobs(): string {\n return `import { Cron, type JobContext } from '@znight/schedule'\n\n/**\n * Scheduled jobs. A class with @Cron, @Interval or @Timeout methods becomes a singleton provider\n * (no decorator needed): its dependencies are constructor parameters. Running several instances?\n * Give SchedulePlugin a lock store so that each occurrence runs on one of them.\n */\nexport class HeartbeatJobs {\n /** Number of runs. */\n beats = 0\n /** The occurrence of the last run. */\n last: Date | undefined\n\n /** Every minute (cron expressions run in UTC unless they set a timeZone). */\n @Cron('* * * * *', { name: 'heartbeat' })\n beat(ctx: JobContext): void {\n this.beats++\n this.last = ctx.scheduledAt\n }\n}\n`\n}\n\nfunction apiDocument(options: ProjectOptions): string {\n return `import { OpenApiDocument } from '@znight/openapi'\n\n/**\n * ${options.name}\n *\n * The HTTP API of ${options.name}. Title and description of the OpenAPI document come from this\n * comment, the version from package.json.\n */\n@OpenApiDocument({\n tags: [{ name: 'Greeting', description: 'Greetings' }],\n})\nexport class Api {}\n`\n}\n\n// ---------------------------------------------------------------------------------------------------\n// tests\n\nfunction heartbeatJobsTest(flags: Flags): string {\n return `${testImports(flags, 'describe, expect, test')}\nimport { SchedulePlugin, SchedulerRegistry } from '@znight/schedule'\nimport { createTestClock } from '@znight/schedule/testing'\nimport { TestApp } from '@znight/testing'\n\nimport { __ZNIGHT_METADATA__ as metadata } from '../src/.znight/container.generated.js'\nimport { HeartbeatJobs } from '../src/app/heartbeat.jobs.js'\n\n// virtual time: the clock only moves when the test advances it, and waits for the runs it starts\ndescribe('HeartbeatJobs', () => {\n test('beats every minute', async () => {\n const clock = createTestClock('2026-01-01T00:00:30Z')\n const app = await TestApp.create({\n metadata,\n plugins: [SchedulePlugin.configure({ clock })],\n only: [HeartbeatJobs],\n })\n try {\n await clock.advance('3m')\n\n expect(app.get(HeartbeatJobs).beats).toBe(3)\n expect(app.get(HeartbeatJobs).last?.toISOString()).toBe('2026-01-01T00:03:00.000Z')\n const heartbeat = app.get(SchedulerRegistry).get('heartbeat')\n expect(heartbeat?.nextRun?.toISOString()).toBe('2026-01-01T00:04:00.000Z')\n } finally {\n await app.close()\n }\n })\n})\n`\n}\n\nfunction testImports(flags: Flags, names: string): string {\n return flags.bun ? `import { ${names} } from 'bun:test'` : `import { ${names} } from 'vitest'`\n}\n\nfunction greetingServiceTest(flags: Flags): string {\n const imports = [testImports(flags, 'describe, expect, test')]\n if (flags.observability) imports.push(\"import { Logger } from '@znight/observability'\")\n imports.push(\"import { TestBed } from '@znight/testing'\")\n const configOption = flags.config ? \"\\n config: { app: { greeting: 'Hi' } }, // @Config('app') values\" : ''\n const greeting = flags.config ? 'Hi' : 'Hello'\n const loggerTest = flags.observability\n ? `\n\n test('logs every greeting', async () => {\n const { instance, mocks } = await TestBed.create(GreetingService, { metadata })\n\n instance.greet('Grace')\n\n // Logger is provided by ObservabilityPlugin at runtime: TestBed injects an auto-mock\n expect(mocks.get(Logger).debug).toHaveBeenCalledWith('Greeting', { name: 'Grace', excited: false })\n })`\n : ''\n return `${imports.join('\\n')}\n\nimport { __ZNIGHT_METADATA__ as metadata } from '../src/.znight/container.generated.js'\nimport { GreetingService } from '../src/app/greeting.service.js'\n\n// TestBed builds GreetingService with its generated factory and auto-mocks its dependencies\ndescribe('GreetingService', () => {\n test('greets', async () => {\n const { instance } = await TestBed.create(GreetingService, {\n metadata,${configOption}\n })\n\n expect(instance.greet('Ada')).toBe('${greeting}, Ada.')\n expect(instance.greet('Ada', true)).toBe('${greeting}, Ada!')\n })${loggerTest}\n})\n`\n}\n\nfunction greetingControllerTest(flags: Flags): string {\n const imports = [\n testImports(flags, 'afterEach, beforeEach, describe, expect, test'),\n \"import { HttpPlugin } from '@znight/http'\",\n ]\n if (flags.messaging) {\n imports.push(\"import { MessagingPlugin } from '@znight/messaging'\")\n imports.push(\"import { memory } from '@znight/messaging/memory'\")\n }\n if (flags.observability) imports.push(\"import { ObservabilityPlugin } from '@znight/observability'\")\n imports.push(\"import { TestApp } from '@znight/testing'\")\n const plugins: string[] = []\n // no metrics server (port 9464 once prom-client is installed): test files and `dev` run side by side\n if (flags.observability) {\n plugins.push(\"ObservabilityPlugin.configure({ logging: { level: 'silent' }, metrics: { server: false } })\")\n }\n if (flags.messaging) plugins.push('MessagingPlugin.configure({ driver: memory() })')\n // port 0: TestApp.inject() sends requests in memory, the server listens on a free port\n plugins.push('HttpPlugin.configure({ port: 0 })')\n const pluginList =\n plugins.length === 1 ? `[${plugins[0]}]` : `[\\n${plugins.map(plugin => ` ${plugin},`).join('\\n')}\\n ]`\n const greeting = 'Hello'\n return `${imports.join('\\n')}\n\nimport { __ZNIGHT_METADATA__ as metadata } from '../src/.znight/container.generated.js'\n\n// TestApp starts the application (without signal handlers) and sends requests in memory\ndescribe('GreetingController', () => {\n let app: TestApp\n\n beforeEach(async () => {\n app = await TestApp.create({\n metadata,\n plugins: ${pluginList},\n })\n })\n\n afterEach(async () => {\n await app.close()\n })\n\n test('GET /greetings/:name', async () => {\n const response = await app.inject({ method: 'GET', url: '/greetings/Ada?excited=true' })\n\n expect(response.status).toBe(200)\n expect(response.json()).toEqual({ message: '${greeting}, Ada!' })\n })\n\n test('POST /greetings validates the body', async () => {\n const created = await app.inject({ method: 'POST', url: '/greetings', body: { name: 'Grace' } })\n expect(created.status).toBe(201)\n expect(created.json()).toEqual({ message: '${greeting}, Grace.' })\n\n const invalid = await app.inject({ method: 'POST', url: '/greetings', body: { name: '' } })\n expect(invalid.status).toBe(400)\n })\n})\n`\n}\n\n// ---------------------------------------------------------------------------------------------------\n// README\n\nfunction readme(options: ProjectOptions, flags: Flags): string {\n const run = (script: string): string => runScript(flags.pm, script)\n const znight = execBinary(flags.pm, 'znight')\n const features = [\n `- **HTTP** with \\`@znight/http\\` (${flags.adapter === 'node' ? 'built-in node:http server' : `${flags.adapter} adapter`})`,\n flags.config ? '- **Configuration** with `@znight/config` (`src/app/app.config.ts`, `.env` files)' : undefined,\n flags.observability\n ? '- **Observability** with `@znight/observability` (structured logs, metrics, traces)'\n : undefined,\n flags.messaging ? '- **Messaging** with `@znight/messaging` (in-memory broker in `src/main.ts`)' : undefined,\n flags.schedule ? '- **Scheduled jobs** with `@znight/schedule` (`src/app/heartbeat.jobs.ts`)' : undefined,\n flags.openapi\n ? '- **OpenAPI** with `@znight/openapi` (`/openapi.json`, API reference at `/docs`, options in `src/api.ts`)'\n : undefined,\n ].filter(line => line !== undefined)\n const tree = [\n 'src/',\n '├─ main.ts # Application.create() + plugins + start()',\n flags.openapi\n ? '├─ api.ts # @OpenApiDocument: title, tags, security of openapi.json'\n : undefined,\n '├─ .znight/ # generated DI container (git-ignored)',\n '└─ app/',\n flags.config ? ' ├─ app.config.ts # @Config: settings read from the environment' : undefined,\n flags.messaging ? ' ├─ greeting.consumer.ts # @Consumer: handles the \"greetings\" queue' : undefined,\n ' ├─ greeting.controller.ts # @Controller: /greetings routes',\n ' ├─ greeting.schemas.ts # Zod schemas',\n ' ├─ greeting.service.ts # @Injectable',\n flags.schedule ? ' ├─ health.controller.ts # GET /health' : ' └─ health.controller.ts # GET /health',\n flags.schedule ? ' └─ heartbeat.jobs.ts # @Cron: a job every minute' : undefined,\n 'test/ # TestBed (unit) and TestApp (HTTP) tests',\n 'vite.config.ts # znight() plugin: generates the container, server build',\n 'znight.config.ts # compiler options',\n ].filter(line => line !== undefined)\n const configNote = flags.config\n ? `\n## Configuration\n\n\\`AppConfig\\` (\\`src/app/app.config.ts\\`) reads \\`PORT\\` and \\`APP_GREETING\\` from the environment or from\n\\`.env\\` / \\`.env.local\\` files. Missing or invalid values stop the application at boot with every\nproblem listed.${\n flags.bun\n ? `\n\n\\`bunfig.toml\\` turns Bun's own \\`.env\\` loading off (\\`env = false\\`): the files are read by\n\\`@znight/config\\`, the same way on Node.js and Bun.`\n : ''\n }\n`\n : ''\n const testNote = flags.bun\n ? '`bun test` regenerates the container first (`bunfig.toml` preloads `@znight/compiler/bun`).'\n : 'Vitest uses `vite.config.ts`, so the `znight()` plugin regenerates the container before the tests.'\n const compilerNote = flags.bun\n ? 'the `znight()` Vite plugin, the Bun preload of the tests and `znight generate`'\n : 'the `znight()` Vite plugin (builds and Vitest) and `znight generate`'\n return `# ${options.name}\n\nA [Znight](https://github.com/znight-org/znight) application: dependency injection resolved at **build\ntime** — no \\`reflect-metadata\\`, errors reported by the compiler with their location.\n\n${features.join('\\n')}\n\n## Scripts\n\n| Command | Description |\n| --- | --- |\n| \\`${run('dev')}\\` | Build in watch mode and restart the application on every change |\n| \\`${run('build')}\\` | Production build (\\`dist/main.js\\`) |\n| \\`${run('start')}\\` | Run the production build |\n| \\`${run('test')}\\` | Run the tests |\n| \\`${run('typecheck')}\\` | Generate the container, then type-check with \\`tsc\\` |\n| \\`${run('generate')}\\` | Generate \\`src/.znight/container.generated.ts\\` (\\`znight generate --check\\` in CI) |\n${\n flags.openapi\n ? `| \\`${run('openapi')}\\` | Write \\`openapi.json\\` (commit it; \\`${run('openapi:check')}\\` in CI) |\n`\n : ''\n}\n\\`\\`\\`sh\n${run('dev')}\ncurl localhost:3000/health\ncurl localhost:3000/greetings/Ada?excited=true\ncurl -X POST localhost:3000/greetings -H 'content-type: application/json' -d '{\"name\":\"Grace\"}'${flags.openapi ? '\\ncurl localhost:3000/openapi.json # the API reference is at http://localhost:3000/docs' : ''}\n\\`\\`\\`\n\n## Project structure\n\n\\`\\`\\`txt\n${tree.join('\\n')}\n\\`\\`\\`\n\nProviders are discovered by the compiler from their decorators: there are no modules to declare.\nIts options live in \\`znight.config.ts\\`, read by ${compilerNote}.\nAdd code with the generators:\n\n\\`\\`\\`sh\n${znight} g service users/user # src/users/user.service.ts\n${znight} g controller users/user # src/users/user.controller.ts${flags.schedule ? `\\n${znight} g job reports/digest # src/reports/digest.jobs.ts` : ''}\n\\`\\`\\`\n${configNote}\n## Tests\n\n${testNote}\n\n## Learn more\n\n- [Znight documentation](https://github.com/znight-org/znight#readme)\n`\n}\n","/** `znight new <name>`: scaffolds a project, interactively or from flags. */\nimport type { Command } from '../command.ts'\nimport type { CliContext } from '../context.ts'\nimport type { Prompts } from '../integrations/prompts.ts'\nimport type { Feature, HttpAdapterName, PackageManager } from '../scaffold/options.ts'\n\nimport { basename, resolve } from 'node:path'\n\nimport { defineCommand, hasFlag } from '../command.ts'\nimport { CliError, UsageError } from '../errors.ts'\nimport { toPackageName, unscopedName, validatePackageName } from '../names.ts'\nimport { initGit, installDependencies, targetState, writeProject } from '../scaffold/create.ts'\nimport {\n ADAPTER_LABELS,\n DEFAULT_FEATURES,\n detectPackageManager,\n FEATURE_LABELS,\n FEATURES,\n HTTP_ADAPTERS,\n installCommand,\n PACKAGE_MANAGERS,\n parseFeatures,\n runScript,\n} from '../scaffold/options.ts'\nimport { renderProject } from '../scaffold/templates.ts'\nimport { displayPath } from './shared.ts'\n\n/** `znight new` */\nexport const newCommand: Command = defineCommand({\n meta: {\n name: 'new',\n description: 'Create a new Znight project',\n usage: '[name] [options]',\n aliases: ['create', 'init'],\n examples: [\n 'znight new my-service',\n 'znight new my-service --yes --pm pnpm --adapter fastify --features config,observability,messaging',\n 'znight new my-worker --yes --features config,schedule',\n 'znight new . --yes --no-install',\n ],\n },\n args: {\n name: {\n type: 'positional',\n required: false,\n description: 'Project name (npm package name), or \".\" for the current directory',\n },\n yes: { type: 'boolean', alias: 'y', description: 'Do not ask questions: use the flags and the defaults' },\n pm: {\n type: 'enum',\n options: ['bun', 'npm', 'pnpm', 'yarn'],\n description: 'Package manager (default: the one running the CLI, bun under Bun, else npm)',\n },\n adapter: {\n type: 'enum',\n options: ['node', 'fastify', 'express', 'hono'],\n description: 'HTTP adapter (default: node, the built-in node:http server)',\n },\n features: {\n type: 'string',\n valueHint: 'list',\n description:\n 'Comma-separated features: config, observability, messaging, schedule, openapi, or \"all\" / \"none\" (default: config,observability)',\n },\n install: { type: 'boolean', default: true, description: 'Do not install the dependencies' },\n git: { type: 'boolean', default: true, description: 'Do not initialise a git repository' },\n dir: { type: 'string', valueHint: 'path', description: 'Target directory (default: ./<name>)' },\n force: { type: 'boolean', description: 'Write into a non-empty directory (existing files are overwritten)' },\n },\n async run({ args: options, cli, rawArgs }) {\n const interactive = cli.interactive && options.yes !== true\n const prompts = interactive ? await cli.services.loadPrompts() : undefined\n prompts?.intro(cli.colors.bold(`Create a Znight project ${cli.colors.dim(`v${cli.version}`)}`))\n\n // name and directory\n let name = options.name\n if (name === undefined || name === '') {\n if (prompts === undefined) {\n throw new UsageError('Missing project name', ['znight new <name> (or \".\" to use the current directory)'])\n }\n name = await prompts.text({\n message: 'Project name?',\n placeholder: 'my-service',\n validate: value => (value === '.' ? undefined : validatePackageName(value.trim())),\n })\n }\n name = name.trim()\n const inPlace = name === '.'\n if (inPlace) name = toPackageName(basename(cli.cwd))\n const problem = validatePackageName(name)\n if (problem !== undefined) {\n const candidate = toPackageName(name)\n throw new UsageError(\n `Invalid project name \"${name}\": ${problem}`,\n candidate !== '' && validatePackageName(candidate) === undefined ? [`try \"${candidate}\"`] : [],\n )\n }\n const directory = resolve(cli.cwd, options.dir ?? (inPlace ? '.' : unscopedName(name)))\n await checkTarget(directory, cli, prompts, options.force === true)\n\n // choices\n const packageManager: PackageManager =\n options.pm ??\n (await prompts?.select({\n message: 'Package manager?',\n choices: PACKAGE_MANAGERS.map(pm => ({ value: pm, label: pm })),\n initialValue: detectPackageManager(cli.env, cli.runtime.name === 'bun'),\n })) ??\n detectPackageManager(cli.env, cli.runtime.name === 'bun')\n const adapter: HttpAdapterName =\n options.adapter ??\n (await prompts?.select({\n message: 'HTTP adapter?',\n choices: HTTP_ADAPTERS.map(value => ({ value, label: ADAPTER_LABELS[value] })),\n initialValue: 'node',\n })) ??\n 'node'\n const features = await chooseFeatures(options.features, prompts)\n const install =\n prompts === undefined || hasFlag(rawArgs, 'install')\n ? options.install !== false\n : await prompts.confirm({ message: `Install the dependencies with ${packageManager}?`, initialValue: true })\n const git =\n prompts === undefined || hasFlag(rawArgs, 'git')\n ? options.git !== false\n : await prompts.confirm({ message: 'Initialise a git repository?', initialValue: true })\n\n // files\n const files = renderProject({ name, packageManager, adapter, features, znightVersion: cli.version })\n writeProject(directory, files)\n const where = displayPath(directory, cli.cwd)\n const summary = `${cli.colors.bold(name)} (${packageManager}, ${adapter}${features.length > 0 ? `, ${features.join(', ')}` : ''})`\n if (prompts === undefined) cli.reporter.success(`Created ${summary} in ${where}`)\n else prompts.note(files.map(file => file.path).join('\\n'), `Created ${summary} in ${where}`)\n\n if (git) await runGit(directory, cli, prompts)\n let installed = false\n if (install) installed = await runInstall(directory, packageManager, cli, prompts)\n\n // next steps\n const steps = [\n ...(inPlace && options.dir === undefined ? [] : [`cd ${where}`]),\n ...(installed ? [] : [installCommand(packageManager).join(' ')]),\n runScript(packageManager, 'dev'),\n ]\n if (prompts === undefined) {\n cli.reporter.log()\n cli.reporter.log(cli.colors.bold('Next steps:'))\n for (const step of steps) cli.reporter.log(` ${cli.colors.cyan(step)}`)\n cli.reporter.log()\n } else {\n prompts.outro(`Next steps:\\n${steps.map(step => ` ${cli.colors.cyan(step)}`).join('\\n')}`)\n }\n if (install && !installed) {\n throw new CliError('The project was created but installing the dependencies failed', {\n hints: [`run \"${installCommand(packageManager).join(' ')}\" in ${where}`],\n })\n }\n return 0\n },\n})\n\nasync function checkTarget(\n directory: string,\n cli: CliContext,\n prompts: Prompts | undefined,\n force: boolean,\n): Promise<void> {\n const state = targetState(directory)\n const where = displayPath(directory, cli.cwd)\n if (state === 'file') throw new CliError(`${where} exists and is not a directory`)\n if (state !== 'not-empty' || force) return\n if (prompts !== undefined) {\n const proceed = await prompts.confirm({\n message: `${where} is not empty. Write the project into it anyway (existing files are overwritten)?`,\n initialValue: false,\n })\n if (proceed) return\n }\n throw new CliError(`${where} is not empty`, {\n hints: ['choose another name or --dir, or pass --force to write into it anyway'],\n })\n}\n\nasync function chooseFeatures(value: string | undefined, prompts: Prompts | undefined): Promise<Feature[]> {\n if (value !== undefined) {\n const parsed = parseFeatures(value)\n if ('unknown' in parsed) {\n throw new UsageError(`Unknown feature${parsed.unknown.length > 1 ? 's' : ''}: ${parsed.unknown.join(', ')}`, [\n `available features: ${FEATURES.join(', ')} (or \"all\", \"none\")`,\n ])\n }\n return parsed.features\n }\n if (prompts === undefined) return [...DEFAULT_FEATURES]\n const selected = await prompts.multiselect({\n message: 'Features? (space to toggle)',\n choices: FEATURES.map(feature => ({ value: feature, label: FEATURE_LABELS[feature] })),\n initialValues: DEFAULT_FEATURES,\n })\n return FEATURES.filter(feature => selected.includes(feature))\n}\n\nasync function runGit(directory: string, cli: CliContext, prompts: Prompts | undefined): Promise<void> {\n const outcome = await initGit(cli.services.processes, directory, cli.env)\n const message = {\n initialized: 'Initialised a git repository',\n 'inside-repository': 'Already inside a git repository: skipped git init',\n unavailable: 'git is not available: skipped git init',\n failed: 'git init failed: skipped',\n }[outcome]\n if (outcome === 'initialized') {\n if (prompts === undefined) cli.reporter.success(message)\n } else {\n cli.reporter.warn(message)\n }\n}\n\nasync function runInstall(\n directory: string,\n packageManager: PackageManager,\n cli: CliContext,\n prompts: Prompts | undefined,\n): Promise<boolean> {\n const command = installCommand(packageManager).join(' ')\n const spinner = prompts?.spinner()\n if (spinner === undefined) cli.reporter.info(`Installing the dependencies (${command})...`)\n else spinner.start(`Installing the dependencies (${command})`)\n const result = await installDependencies(cli.services.processes, directory, packageManager, cli.env)\n const ok = result.code === 0 && result.error === undefined\n if (ok) {\n if (spinner === undefined) cli.reporter.success('Installed the dependencies')\n else spinner.stop('Installed the dependencies')\n return true\n }\n const reason =\n result.error === undefined\n ? `${command} exited with code ${result.code ?? result.signal}`\n : `${packageManager} could not be started (${result.error.message})`\n if (spinner === undefined) cli.reporter.error(reason)\n else spinner.stop(reason, true)\n const output = `${result.stdout}${result.stderr}`.trim()\n if (output !== '') cli.reporter.logError(output.split('\\n').slice(-30).join('\\n'))\n return false\n}\n","/**\n * `znight openapi`: writes the OpenAPI document of the application (`openapi.json`, or YAML by\n * extension) with `@znight/openapi/emit`, or checks that the committed file is up to date\n * (`--check`, for CI). The modules of the application run in a child process.\n */\nimport type { Command } from '../command.ts'\nimport type { CliContext } from '../context.ts'\nimport type { CompilerApi, Diagnostic } from '../integrations/compiler.ts'\nimport type { OpenApiEmitResultLike } from '../integrations/openapi.ts'\nimport type { ViteConfigLoader } from '../integrations/vite.ts'\n\nimport { existsSync } from 'node:fs'\n\nimport { defineCommand } from '../command.ts'\nimport { CliError, errorMessage } from '../errors.ts'\nimport { hasErrors } from '../integrations/compiler.ts'\nimport { formatDuration, plural } from '../output.ts'\nimport { compilerOptions } from './generate.ts'\nimport { displayPath, parseHttpPrefix, resolveRoot } from './shared.ts'\n\n/** Values of a repeatable string option (`-o a -o b`, `--output=a`, `--output b,c`). */\nexport function repeatedOption(rawArgs: readonly string[], name: string, alias: string): string[] {\n const values: string[] = []\n for (let index = 0; index < rawArgs.length; index++) {\n const token = rawArgs[index] ?? ''\n let value: string | undefined\n if (token === `--${name}` || token === `-${alias}`) value = rawArgs[++index]\n else if (token.startsWith(`--${name}=`)) value = token.slice(name.length + 3)\n else if (token.startsWith(`-${alias}=`)) value = token.slice(alias.length + 2)\n if (value === undefined) continue\n for (const part of value.split(',')) if (part.trim() !== '') values.push(part.trim())\n }\n return values\n}\n\n/** `znight openapi` */\nexport const openapiCommand: Command = defineCommand({\n meta: {\n name: 'openapi',\n description: 'Emit the OpenAPI document of the application (openapi.json, --check in CI)',\n usage: '[options]',\n examples: [\n 'znight openapi # writes openapi.json at the project root',\n 'znight openapi -o docs/openapi.yaml # YAML, chosen by the extension (needs yaml)',\n 'znight openapi --check # CI: exit 1 when the file is missing or stale',\n 'znight openapi --prefix /api # servers default when @OpenApiDocument declares none',\n 'znight openapi --runtime bun # load the modules with Bun',\n ],\n details: [\n 'The application is compiled like \"znight generate\" (compile errors stop everything), then its',\n 'generated module is loaded in a child process (Bun: the compiler preload; Node.js: a Vite server)',\n 'and @znight/openapi assembles the document. Nothing is instantiated. Outputs are only written',\n 'when they change. Requires @znight/openapi in the project.',\n ].join('\\n'),\n },\n args: {\n output: {\n type: 'string',\n alias: 'o',\n valueHint: 'file',\n description: 'Output file, repeatable (.yaml / .yml write YAML). Default: openapi.json',\n },\n check: { type: 'boolean', description: 'Do not write: exit with code 1 when an output is missing or stale' },\n prefix: { type: 'string', valueHint: 'path', description: 'HTTP prefix: the servers default (/api)' },\n runtime: {\n type: 'enum',\n options: ['auto', 'node', 'bun'],\n description: 'Runtime loading the application modules (default: auto, the one running the CLI)',\n },\n converters: {\n type: 'string',\n valueHint: 'file',\n description: 'Module whose default export is a SchemaConverter[] (custom schema libraries)',\n },\n root: { type: 'string', valueHint: 'dir', description: 'Project root (default: the current directory)' },\n config: { type: 'string', valueHint: 'file', description: 'Vite config file (default: vite.config.*)' },\n 'config-loader': {\n type: 'enum',\n options: ['bundle', 'runner', 'native'],\n description: 'How Vite loads the config file (default: bundle)',\n },\n },\n async run({ args, cli, rawArgs }) {\n const root = resolveRoot(cli, args.root)\n const outputs = repeatedOption(rawArgs, 'output', 'o')\n const prefix = parseHttpPrefix(args.prefix, 'prefix')\n const compiler = await cli.services.loadCompiler(root)\n const configLoader = args['config-loader'] as ViteConfigLoader | undefined\n const options = await compilerOptions(cli, compiler, root, args.config, configLoader)\n const openapi = await cli.services.loadOpenApi(root)\n const started = performance.now()\n let result: OpenApiEmitResultLike\n try {\n result = await openapi.emitOpenApi({\n root,\n output: outputs.length > 0 ? outputs : ['openapi.json'],\n ...(args.check === true ? { check: true } : {}),\n ...(prefix === undefined ? {} : { prefix }),\n ...(args.runtime === undefined ? {} : { runtime: args.runtime as 'auto' | 'node' | 'bun' }),\n ...(args.converters === undefined ? {} : { converters: args.converters }),\n ...(args.config === undefined ? {} : { config: args.config }),\n ...(configLoader === undefined ? {} : { configLoader }),\n compilerOptions: options,\n })\n } catch (error) {\n const hints = (error as { hints?: unknown } | null)?.hints\n throw new CliError(`OpenAPI emission failed: ${errorMessage(error)}`, {\n cause: error,\n hints: Array.isArray(hints) ? (hints as string[]) : [],\n })\n }\n printDiagnostics(cli, compiler, result.diagnostics, root)\n if (!result.ok || hasErrors(result.diagnostics)) {\n const errors = result.diagnostics.filter(diagnostic => diagnostic.severity === 'error').length\n cli.reporter.error(`OpenAPI emission failed: the application does not compile (${plural(errors, 'error')})`)\n return 1\n }\n for (const warning of result.warnings) cli.reporter.warn(`${warning.code}: ${warning.message}`)\n const elapsed = formatDuration(performance.now() - started)\n const operations = Object.values(result.document?.paths ?? {}).reduce(\n (count, item) => count + Object.keys(item).length,\n 0,\n )\n const stats = cli.colors.dim(`(${plural(operations, 'operation')}, ${result.runtime}, ${elapsed})`)\n if (args.check === true) {\n for (const file of result.staleFiles) {\n const shown = displayPath(file, cli.cwd)\n if (existsSync(file))\n cli.reporter.error(`${shown} is out of date`, ['run \"znight openapi\" and commit the result'])\n else cli.reporter.error(`${shown} is missing`, ['run \"znight openapi\" and commit the result'])\n }\n if (result.stale) return 1\n cli.reporter.success(\n `${result.outputs.map(file => cli.colors.bold(displayPath(file, cli.cwd))).join(', ')} up to date ${stats}`,\n )\n return 0\n }\n for (const file of result.outputs) {\n const shown = cli.colors.bold(displayPath(file, cli.cwd))\n cli.reporter.success(`${result.written.includes(file) ? 'Wrote' : 'Up to date:'} ${shown} ${stats}`)\n }\n return 0\n },\n})\n\nfunction printDiagnostics(\n cli: CliContext,\n compiler: CompilerApi,\n diagnostics: readonly Diagnostic[],\n root: string,\n): void {\n if (diagnostics.length === 0) return\n const text = compiler.formatDiagnostics(diagnostics, {\n color: cli.colors.isColorSupported,\n cwd: root,\n summary: false,\n })\n cli.reporter.logError(text.trimEnd())\n cli.reporter.logError()\n}\n","/**\n * Code generators of `znight g <schematic> <name>`: one file per schematic, kebab-case file names\n * (`user-profile.service.ts`), PascalCase classes (`UserProfileService`). Pure: {@link planSchematic}\n * computes the file, the command writes it.\n */\nimport { dirname, isAbsolute, join, normalize, relative } from 'node:path'\n\nimport { camelCase, constantCase, kebabCase, pascalCase } from '../names.ts'\n\n/** Available schematics. */\nexport type SchematicName =\n | 'service'\n | 'controller'\n | 'consumer'\n | 'config'\n | 'guard'\n | 'interceptor'\n | 'factory'\n | 'job'\n\n/** Names derived from the user input. */\nexport interface SchematicNames {\n /** `user-profile` */\n readonly kebab: string\n /** `UserProfile` */\n readonly pascal: string\n /** `userProfile` */\n readonly camel: string\n /** `UserProfileService` */\n readonly className: string\n /**\n * Dotted name of the element in the application: the directories of its file relative to `src/`\n * (or to the project root, for a `--path` outside `src/`) and its kebab name, without the directory\n * named after it (`reports.digest` for `src/reports/digest.jobs.ts`, `digest` for\n * `src/digest/digest.jobs.ts`). Unlike `kebab`, it tells apart elements of the same name in different\n * directories: the default name of a job (job names are unique in the application).\n */\n readonly qualified: string\n}\n\n/** Project facts that change the generated code. */\nexport interface SchematicContext {\n /** The project depends on `zod`: consumers get a message schema. */\n readonly zod: boolean\n /** `interceptor` only: a method interceptor (`@Intercept`, AOP) instead of an HTTP interceptor. */\n readonly aop: boolean\n}\n\n/** A schematic. */\nexport interface Schematic {\n readonly name: SchematicName\n readonly aliases: readonly string[]\n readonly description: string\n /** File and class suffix (`service` → `user.service.ts`, `UserService`). */\n readonly suffix: string\n render(names: SchematicNames, context: SchematicContext): string\n /** What to do next, printed after the file is created. */\n hint?(names: SchematicNames, context: SchematicContext): string | undefined\n}\n\nconst service: Schematic = {\n name: 'service',\n aliases: ['s'],\n description: 'An @Injectable() provider',\n suffix: 'service',\n render: names => `import { Injectable } from '@znight/core'\n\n@Injectable()\nexport class ${names.className} {\n // Declare dependencies as constructor parameters: the compiler resolves them from their types.\n // constructor(private readonly repository: ${names.pascal}Repository) {}\n}\n`,\n}\n\nconst controller: Schematic = {\n name: 'controller',\n aliases: ['co'],\n description: 'An HTTP @Controller() with two routes',\n suffix: 'controller',\n render: names => `import { Controller, Get, Param } from '@znight/http'\n\n@Controller('/${names.kebab}')\nexport class ${names.className} {\n /** GET /${names.kebab} */\n @Get()\n list(): unknown[] {\n return []\n }\n\n /** GET /${names.kebab}/:id */\n @Get('/:id')\n find(@Param('id') id: string): { id: string } {\n return { id }\n }\n}\n`,\n}\n\nconst consumer: Schematic = {\n name: 'consumer',\n aliases: ['cs'],\n description: 'A message @Consumer() (@znight/messaging)',\n suffix: 'consumer',\n render: (names, context) =>\n context.zod\n ? `import { Consumer, Message, OnMessage, Retry } from '@znight/messaging'\nimport { z } from 'zod'\n\nexport const ${names.pascal}Message = z.object({\n id: z.string(),\n})\nexport type ${names.pascal}Message = z.output<typeof ${names.pascal}Message>\n\n/**\n * Consumes the \"${names.kebab}\" queue.\n * Delivery is at-least-once: make the handler idempotent. Throw to retry, throw a NonRetryableError\n * to dead-letter the message right away.\n */\n@Consumer('${names.kebab}')\nexport class ${names.className} {\n @OnMessage()\n @Retry({ attempts: 3, backoff: 'exponential', delay: 1000 })\n handle(@Message(${names.pascal}Message) message: ${names.pascal}Message): void {\n console.log('received', message.id)\n }\n}\n`\n : `import { Consumer, Ctx, type InboundMessage, OnMessage, Retry } from '@znight/messaging'\n\n/**\n * Consumes the \"${names.kebab}\" queue.\n * Delivery is at-least-once: make the handler idempotent. Throw to retry, throw a NonRetryableError\n * to dead-letter the message right away.\n */\n@Consumer('${names.kebab}')\nexport class ${names.className} {\n @OnMessage()\n @Retry({ attempts: 3, backoff: 'exponential', delay: 1000 })\n handle(@Ctx() message: InboundMessage): void {\n console.log('received', message.id, message.payload)\n }\n}\n`,\n hint: () => 'consumers run with MessagingPlugin.configure({ driver }) in src/main.ts',\n}\n\nconst config: Schematic = {\n name: 'config',\n aliases: ['cf'],\n description: 'A @Config() class read from the environment (@znight/config)',\n suffix: 'config',\n render: names => `import { Config } from '@znight/config'\n\n/**\n * Settings read from the ${constantCase(names.camel)}_* environment variables (or .env files).\n * Validated at boot by ConfigPlugin: the type of a property selects its coercion, an initializer\n * makes it optional.\n */\n@Config('${names.camel}')\nexport class ${names.className} {\n /** ${constantCase(names.camel)}_ENABLED */\n enabled = true\n}\n`,\n hint: names => `inject ${names.className} anywhere; values are loaded by ConfigPlugin.configure() in src/main.ts`,\n}\n\nconst guard: Schematic = {\n name: 'guard',\n aliases: ['gu'],\n description: 'An HTTP guard (CanActivate)',\n suffix: 'guard',\n render: names => `import type { CanActivate, HttpContext } from '@znight/http'\n\nimport { Injectable } from '@znight/core'\n\n@Injectable()\nexport class ${names.className} implements CanActivate {\n // The route decisions this guard enforces (createRouteDecorator groups, see \"Route decisions\" in\n // the @znight/http README): the boot fails when a route of a required group has no guard\n // enforcing its decision.\n // static readonly enforces = [Public, Roles]\n\n canActivate(ctx: HttpContext): boolean | Promise<boolean> {\n // Return false (403 Forbidden) or throw an HttpException (UnauthorizedException...) to reject\n // the request, e.g. return ctx.header('authorization') !== undefined\n return true\n }\n}\n`,\n hint: names =>\n `use it with @UseGuard(${names.className}) on a controller or a route, or HttpPlugin.configure({ guards: [${names.className}] })`,\n}\n\nconst interceptor: Schematic = {\n name: 'interceptor',\n aliases: ['itc'],\n description: 'An HTTP interceptor (HttpInterceptor), or a method interceptor with --aop',\n suffix: 'interceptor',\n render: (names, context) =>\n context.aop\n ? `import { Injectable, type MethodInterceptor, type MethodInvocation } from '@znight/core'\n\n@Injectable()\nexport class ${names.className} implements MethodInterceptor {\n intercept(invocation: MethodInvocation): unknown {\n // Runs around every intercepted call. For a synchronous method, return synchronously.\n return invocation.proceed()\n }\n}\n`\n : `import type { CallHandler, HttpContext, HttpInterceptor } from '@znight/http'\n\nimport { Injectable } from '@znight/core'\n\n@Injectable()\nexport class ${names.className} implements HttpInterceptor {\n async intercept(ctx: HttpContext, next: CallHandler): Promise<unknown> {\n const started = performance.now()\n try {\n // the handler result (before serialisation): return it, transform it or replace it\n return await next()\n } finally {\n ctx.setHeader('server-timing', \\`app;dur=\\${(performance.now() - started).toFixed(1)}\\`)\n }\n }\n}\n`,\n hint: (names, context) =>\n context.aop\n ? `use it with @Intercept(${names.className}) on any provider method`\n : `use it with @UseInterceptor(${names.className}) on a controller or a route, or HttpPlugin.configure({ interceptors: [${names.className}] })`,\n}\n\nconst factory: Schematic = {\n name: 'factory',\n aliases: ['f'],\n description: 'A @Factory() whose @Provides() methods provide objects you do not own',\n suffix: 'factory',\n render: names => `import { Factory, Provides } from '@znight/core'\n\n/** Replace with the type you provide: a database pool, an SDK client... */\nexport class ${names.pascal}Client {\n close(): void {}\n}\n\n/**\n * @Provides methods create providers for classes you cannot decorate. Their parameters are injected,\n * their explicit return type is the provided type (Promise<T> for an async initialisation).\n */\n@Factory()\nexport class ${names.className} {\n @Provides({ dispose: 'close' })\n create${names.pascal}Client(): ${names.pascal}Client {\n return new ${names.pascal}Client()\n }\n}\n`,\n}\n\nconst job: Schematic = {\n name: 'job',\n aliases: ['j'],\n description: 'Scheduled jobs: @Cron, @Interval, @Timeout methods (@znight/schedule)',\n suffix: 'jobs',\n render: names => `import { Cron, type JobContext } from '@znight/schedule'\n\n/**\n * Scheduled jobs. A class with @Cron, @Interval or @Timeout methods becomes a singleton provider\n * (no decorator needed): declare its dependencies as constructor parameters.\n */\nexport class ${names.className} {\n /** Every day at 03:00 UTC (set timeZone to follow a local clock). A run still running is skipped. */\n @Cron('0 3 * * *', { name: '${names.qualified}.daily' })\n daily(ctx: JobContext): void {\n // checkpoint: throws when the run is aborted (shutdown, maxDuration or a lost lock)\n ctx.signal.throwIfAborted()\n }\n}\n`,\n hint: () =>\n 'jobs run with SchedulePlugin.configure() in src/main.ts; test them with createTestClock() from @znight/schedule/testing',\n}\n\n/** Every schematic, in display order. */\nexport const SCHEMATICS: readonly Schematic[] = [\n service,\n controller,\n consumer,\n config,\n guard,\n interceptor,\n factory,\n job,\n]\n\n/** Finds a schematic by name or alias. */\nexport function findSchematic(name: string): Schematic | undefined {\n const key = name.toLowerCase()\n return SCHEMATICS.find(schematic => schematic.name === key || schematic.aliases.includes(key))\n}\n\n/** Parsed `<name>` argument: optional directories and the base name. */\nexport interface ParsedSchematicName {\n /** Directory segments (`users/admin` → `['users']`), kebab-cased. */\n readonly directories: readonly string[]\n readonly names: SchematicNames\n}\n\n/**\n * Parses `users/user-profile`, `UserProfile`, `user_profile.service.ts`... A trailing suffix\n * matching the schematic (`user-service`, `UserService`, `user.service`) is dropped.\n *\n * @throws Error with a user-facing message when the name is invalid.\n */\nexport function parseSchematicName(input: string, schematic: Schematic): ParsedSchematicName {\n const segments = input\n .trim()\n .split(/[\\\\/]+/)\n .filter(segment => segment !== '')\n if (segments.length === 0) throw new Error('the name cannot be empty')\n if (isAbsolute(input) || segments.some(segment => segment === '.' || segment === '..')) {\n throw new Error(`invalid name \"${input}\": use a path relative to src/ without \".\" or \"..\" segments`)\n }\n const last = (segments.at(-1) ?? '').replace(/\\.[cm]?tsx?$/, '')\n let words = kebabCase(last)\n for (const suffix of [`-${schematic.suffix}`, `.${schematic.suffix}`]) {\n if (words.endsWith(suffix) && words !== suffix.slice(1)) words = words.slice(0, -suffix.length)\n }\n if (words === '') throw new Error(`invalid name \"${input}\"`)\n if (!/^[a-z]/.test(words)) throw new Error(`invalid name \"${input}\": it must start with a letter`)\n const directories = segments.slice(0, -1).map(segment => kebabCase(segment))\n if (directories.some(directory => directory === '')) throw new Error(`invalid name \"${input}\"`)\n const pascal = pascalCase(words)\n return {\n directories,\n names: {\n kebab: words,\n pascal,\n camel: camelCase(words),\n className: `${pascal}${pascalCase(schematic.suffix)}`,\n qualified: qualifiedName(directories, words),\n },\n }\n}\n\n/** `reports` + `digest` → `reports.digest`; the directory named after the element is left out. */\nfunction qualifiedName(directories: readonly string[], kebab: string): string {\n const segments = directories.at(-1) === kebab ? directories.slice(0, -1) : directories\n return [...segments, kebab].join('.')\n}\n\n/**\n * Directories of `directory` relative to `<root>/src`, or to `root` outside `src/`, kebab-cased\n * (`undefined` outside the project).\n */\nfunction sourceDirectories(root: string, directory: string): string[] | undefined {\n for (const base of [join(root, 'src'), root]) {\n const path = relative(base, directory)\n if (isAbsolute(path) || path === '..' || /^\\.\\.[\\\\/]/.test(path)) continue\n return path\n .split(/[\\\\/]+/)\n .map(segment => kebabCase(segment))\n .filter(segment => segment !== '')\n }\n return undefined\n}\n\n/** Where and what to generate. */\nexport interface SchematicPlan {\n readonly schematic: Schematic\n readonly names: SchematicNames\n /** Absolute path of the file. */\n readonly file: string\n readonly content: string\n readonly hint: string | undefined\n}\n\n/** Inputs of {@link planSchematic}. */\nexport interface PlanSchematicOptions {\n readonly schematic: Schematic\n readonly name: string\n /** Project root (contains `src/`). */\n readonly root: string\n /** Directory of `--path` (absolute), replacing `<root>/src`. */\n readonly path?: string | undefined\n /** Do not create a directory named after the element. */\n readonly flat?: boolean\n readonly context: SchematicContext\n}\n\n/**\n * Computes the file of a schematic:\n *\n * | Input | File |\n * | ---------------------------- | ------------------------------------- |\n * | `service user` | `src/user/user.service.ts` |\n * | `service users/user` | `src/users/user.service.ts` |\n * | `service user --flat` | `src/user.service.ts` |\n * | `service user --path lib/x` | `lib/x/user.service.ts` |\n */\nexport function planSchematic(options: PlanSchematicOptions): SchematicPlan {\n const { schematic, context } = options\n const parsed = parseSchematicName(options.name, schematic)\n const base = options.path ?? join(options.root, 'src')\n let directories = [...parsed.directories]\n if (directories.length === 0 && options.path === undefined && options.flat !== true)\n directories = [parsed.names.kebab]\n const file = normalize(join(base, ...directories, `${parsed.names.kebab}.${schematic.suffix}.ts`))\n // --path: the location of the file qualifies the name (src/emails/ → emails.digest)\n const located = options.path === undefined ? undefined : sourceDirectories(options.root, dirname(file))\n const names =\n located === undefined ? parsed.names : { ...parsed.names, qualified: qualifiedName(located, parsed.names.kebab) }\n return {\n schematic,\n names,\n file,\n content: schematic.render(names, context),\n hint: schematic.hint?.(names, context),\n }\n}\n","/** `znight g <schematic> <name>`: generates a service, controller, consumer, config, guard, interceptor, factory or job. */\nimport type { Command } from '../command.ts'\nimport type { Colors } from '../output.ts'\n\nimport { existsSync, mkdirSync, writeFileSync } from 'node:fs'\nimport { dirname, resolve } from 'node:path'\n\nimport { defineCommand, table } from '../command.ts'\nimport { CliError, UsageError } from '../errors.ts'\nimport { suggest } from '../names.ts'\nimport { findSchematic, planSchematic, SCHEMATICS } from '../schematics/index.ts'\nimport { displayPath, findProjectRoot, readManifest, resolveRoot } from './shared.ts'\n\nfunction schematicList(colors: Colors): string {\n return table(\n SCHEMATICS.map(\n schematic => [`${schematic.name} (${schematic.aliases.join(', ')})`, schematic.description] as const,\n ),\n colors,\n ).join('\\n')\n}\n\n/** `znight g` */\nexport const schematicCommand: Command = defineCommand({\n meta: {\n name: 'g',\n description: 'Generate a service, controller, consumer, config, guard, interceptor, factory or job',\n usage: '<schematic> <name> [options]',\n aliases: ['generate <schematic>'],\n details: colors =>\n `${colors.bold('Schematics')}\\n${schematicList(colors)}\\n\\nFiles are named <name>.<schematic>.ts (kebab-case), classes <Name><Schematic> (PascalCase).`,\n examples: [\n 'znight g service users/user # src/users/user.service.ts (UserService)',\n 'znight g controller order # src/order/order.controller.ts (OrderController)',\n 'znight g guard auth --flat # src/auth.guard.ts (AuthGuard)',\n 'znight g interceptor timing --aop # a method interceptor (@Intercept)',\n 'znight g consumer orders --path src/messaging',\n 'znight g job digest # src/digest/digest.jobs.ts (DigestJobs)',\n ],\n },\n args: {\n schematic: { type: 'positional', required: false, description: 'What to generate (see Schematics below)' },\n name: {\n type: 'positional',\n required: false,\n description: 'Name, optionally prefixed with directories relative to src/ (users/user-profile)',\n },\n path: { type: 'string', valueHint: 'dir', description: 'Directory of the file (default: src/<name>/)' },\n flat: { type: 'boolean', description: 'Do not create a directory named after the element' },\n force: { type: 'boolean', alias: 'f', description: 'Overwrite an existing file' },\n 'dry-run': { type: 'boolean', alias: 'd', description: 'Print the file instead of writing it' },\n aop: { type: 'boolean', description: 'interceptor: a method interceptor (@Intercept) instead of an HTTP one' },\n root: { type: 'string', valueHint: 'dir', description: 'Project root (default: the nearest package.json)' },\n },\n run({ args, cli }) {\n if (args.schematic === undefined || args.schematic === '') {\n throw new UsageError('Missing <schematic>', [`available schematics:\\n${schematicList(cli.colors)}`])\n }\n const schematic = findSchematic(args.schematic)\n if (schematic === undefined) {\n const candidate = suggest(\n args.schematic,\n SCHEMATICS.map(item => item.name),\n )\n throw new UsageError(`Unknown schematic \"${args.schematic}\"`, [\n ...(candidate === undefined ? [] : [`did you mean \"${candidate}\"?`]),\n `available schematics: ${SCHEMATICS.map(item => item.name).join(', ')}`,\n ])\n }\n if (args.name === undefined || args.name === '') {\n throw new UsageError('Missing <name>', [\n `znight g ${schematic.name} <name>, e.g. znight g ${schematic.name} users/user`,\n ])\n }\n const root = args.root === undefined ? findProjectRoot(cli.cwd) : resolveRoot(cli, args.root)\n const manifest = readManifest(root)\n const zod = manifest.dependencies?.['zod'] !== undefined || manifest.devDependencies?.['zod'] !== undefined\n let plan: ReturnType<typeof planSchematic>\n try {\n plan = planSchematic({\n schematic,\n name: args.name,\n root,\n path: args.path === undefined ? undefined : resolve(cli.cwd, args.path),\n flat: args.flat === true,\n context: { zod, aop: args.aop === true },\n })\n } catch (error) {\n throw new UsageError(error instanceof Error ? error.message : String(error))\n }\n const file = displayPath(plan.file, cli.cwd)\n if (args['dry-run'] === true) {\n cli.reporter.info(`Would create ${cli.colors.bold(file)} (${plan.names.className})`)\n cli.reporter.log()\n cli.reporter.log(plan.content)\n return 0\n }\n const exists = existsSync(plan.file)\n if (exists && args.force !== true) {\n throw new CliError(`${file} already exists`, { hints: ['pass --force to overwrite it'] })\n }\n mkdirSync(dirname(plan.file), { recursive: true })\n writeFileSync(plan.file, plan.content)\n cli.reporter.success(\n `${exists ? 'Overwrote' : 'Created'} ${cli.colors.bold(file)} ${cli.colors.dim(`(${plan.names.className})`)}`,\n )\n if (plan.hint !== undefined) cli.reporter.log(` ${cli.colors.dim(plan.hint)}`)\n return 0\n },\n})\n","/**\n * `znight start`: runs the production build with Node.js (or Bun). On POSIX the CLI process is\n * replaced by the runtime (`execve`): same PID, signals and exit code are native (ideal as a\n * container entry point). Elsewhere the application runs as a child process; signals are forwarded\n * and its exit code is returned.\n */\nimport type { Command } from '../command.ts'\n\nimport { existsSync } from 'node:fs'\nimport { resolve } from 'node:path'\n\nimport { defineCommand } from '../command.ts'\nimport { CliError } from '../errors.ts'\nimport { exitCodeOf } from '../integrations/process.ts'\nimport { type RuntimeOption, resolveRuntime, runtimeArguments, runtimeExecutable } from '../runtime.ts'\nimport { displayPath, resolveRoot } from './shared.ts'\n\n/** Entries tried when `--entry` is not given. */\nconst DEFAULT_ENTRIES = ['dist/main.js', 'dist/main.mjs']\n\n/** `znight start` */\nexport const startCommand: Command = defineCommand({\n meta: {\n name: 'start',\n description: 'Run the production build',\n usage: '[options] [-- <application arguments>]',\n examples: ['znight start', 'znight start --runtime bun', 'znight start --entry dist/worker.js -- --verbose'],\n details:\n 'NODE_ENV defaults to \"production\". Signals (SIGINT, SIGTERM) reach the application, which stops gracefully.',\n },\n args: {\n root: { type: 'string', valueHint: 'dir', description: 'Project root (default: the current directory)' },\n entry: { type: 'string', valueHint: 'file', description: 'File to run (default: dist/main.js)' },\n runtime: {\n type: 'enum',\n options: ['auto', 'node', 'bun'],\n default: 'auto',\n description: 'Runtime of the application (auto: the runtime running the CLI)',\n },\n },\n async run({ args, cli, passthrough }) {\n const root = resolveRoot(cli, args.root)\n const candidates = args.entry === undefined ? DEFAULT_ENTRIES : [args.entry]\n const entry = candidates.map(file => resolve(root, file)).find(file => existsSync(file))\n if (entry === undefined) {\n throw new CliError(`${displayPath(resolve(root, candidates[0] ?? ''), cli.cwd)} not found`, {\n hints: ['build the application first: znight build'],\n })\n }\n const runtime = resolveRuntime(args.runtime as RuntimeOption, cli.runtime)\n const executable = runtimeExecutable(runtime, cli.runtime, cli.env)\n if (executable === undefined) {\n throw new CliError(`Cannot find \"${runtime}\" in PATH`, { hints: ['install it, or choose another --runtime'] })\n }\n const argv = [...runtimeArguments(runtime), entry, ...passthrough]\n const env = { ...cli.env, NODE_ENV: cli.env['NODE_ENV'] ?? 'production' }\n const { processes } = cli.services\n if (processes.execve !== undefined) {\n const clean: Record<string, string> = {}\n for (const [key, value] of Object.entries(env)) if (value !== undefined) clean[key] = value\n processes.execve(executable, [executable, ...argv], clean, root)\n // only reached with a test double (a real execve never returns)\n return 0\n }\n const child = processes.spawn(executable, argv, { cwd: root, env, detached: true })\n const forward = (signal: NodeJS.Signals) => (): void => {\n child.kill(signal)\n }\n const listeners = (['SIGINT', 'SIGTERM', 'SIGHUP'] as const).map(signal => [signal, forward(signal)] as const)\n for (const [signal, listener] of listeners) cli.signals.on(signal, listener)\n try {\n const status = await child.exited\n if (status.error !== undefined) throw new CliError(`Cannot start ${runtime}: ${status.error.message}`)\n return exitCodeOf(status)\n } finally {\n for (const [signal, listener] of listeners) cli.signals.off(signal, listener)\n }\n },\n})\n","/**\n * Entry point of the CLI: global options, command dispatch, help, and error reporting with exit\n * codes (0 ok, 1 failure, 2 usage, 130 cancelled).\n */\nimport type { Command } from './command.ts'\nimport type { CliContext, CliContextOptions } from './context.ts'\n\nimport { renderCommandHelp, table } from './command.ts'\nimport { buildCommand } from './commands/build.ts'\nimport { devCommand } from './commands/dev.ts'\nimport { generateCommand } from './commands/generate.ts'\nimport { newCommand } from './commands/new.ts'\nimport { openapiCommand } from './commands/openapi.ts'\nimport { schematicCommand } from './commands/schematic.ts'\nimport { startCommand } from './commands/start.ts'\nimport { createContext } from './context.ts'\nimport { CancelledError, CliError, ExitCode, errorMessage, UsageError } from './errors.ts'\nimport { suggest } from './names.ts'\n\n/** Every command, in help order. */\nexport const COMMANDS: readonly Command[] = [\n newCommand,\n generateCommand,\n schematicCommand,\n devCommand,\n buildCommand,\n startCommand,\n openapiCommand,\n]\n\n/** Finds a command by name or alias. */\nexport function findCommand(name: string): Command | undefined {\n return COMMANDS.find(command => command.meta.name === name || command.meta.aliases?.includes(name) === true)\n}\n\ninterface GlobalOptions {\n color?: boolean\n debug: boolean\n rest: string[]\n}\n\n/** Extracts `--color`, `--no-color` and `--debug` (anywhere before `--`). */\nfunction extractGlobalOptions(argv: readonly string[]): GlobalOptions {\n const separator = argv.indexOf('--')\n const before = separator === -1 ? argv : argv.slice(0, separator)\n const after = separator === -1 ? [] : argv.slice(separator)\n const result: GlobalOptions = { debug: false, rest: [] }\n for (const arg of before) {\n if (arg === '--color') result.color = true\n else if (arg === '--no-color') result.color = false\n else if (arg === '--debug') result.debug = true\n else result.rest.push(arg)\n }\n result.rest.push(...after)\n return result\n}\n\n/**\n * Runs the CLI with `argv` (without the executable and script, i.e. `process.argv.slice(2)`).\n * Resolves with the exit code; never throws.\n */\nexport async function main(argv: readonly string[], options: CliContextOptions = {}): Promise<number> {\n const globals = extractGlobalOptions(argv)\n const cli = createContext({\n ...options,\n ...(globals.color === undefined ? {} : { color: globals.color }),\n ...(globals.debug ? { debug: true } : {}),\n })\n try {\n return await dispatch(globals.rest, cli)\n } catch (error) {\n return reportError(error, cli)\n }\n}\n\nasync function dispatch(argv: readonly string[], cli: CliContext): Promise<number> {\n const separator = argv.indexOf('--')\n const args = separator === -1 ? [...argv] : argv.slice(0, separator)\n const passthrough = separator === -1 ? [] : argv.slice(separator + 1)\n const [first, ...rest] = args\n\n if (first === undefined || first === '-h' || first === '--help') {\n cli.reporter.log(renderRootHelp(cli))\n return ExitCode.Ok\n }\n if (first === '-v' || first === '--version' || first === 'version') {\n cli.reporter.log(cli.version)\n return ExitCode.Ok\n }\n if (first === 'help') {\n const target = rest[0] === undefined ? undefined : findCommand(rest[0])\n if (rest[0] !== undefined && target === undefined) throw unknownCommand(rest[0])\n cli.reporter.log(target === undefined ? renderRootHelp(cli) : renderCommandHelp(target, cli.colors))\n return ExitCode.Ok\n }\n if (first.startsWith('-')) {\n throw new UsageError(`Unknown option ${first}`, ['options go after the command: znight <command> [options]'])\n }\n\n let command = findCommand(first)\n let commandArgs = rest\n // `generate:service user` and `generate service user` are aliases of `g service user`\n if (command === undefined && first.startsWith('generate:')) {\n command = schematicCommand\n commandArgs = [first.slice('generate:'.length), ...rest]\n } else if (command === generateCommand && rest[0] !== undefined && !rest[0].startsWith('-')) {\n command = schematicCommand\n }\n if (command === undefined) throw unknownCommand(first)\n\n if (commandArgs.includes('-h') || commandArgs.includes('--help')) {\n cli.reporter.log(renderCommandHelp(command, cli.colors))\n return ExitCode.Ok\n }\n try {\n return await command.execute(commandArgs, passthrough, cli)\n } catch (error) {\n if (error instanceof UsageError) {\n throw new UsageError(error.message, [...error.hints, `run \"znight ${command.meta.name} --help\" for the usage`])\n }\n throw error\n }\n}\n\nfunction unknownCommand(name: string): UsageError {\n const candidate = suggest(\n name,\n COMMANDS.flatMap(command => [command.meta.name, ...(command.meta.aliases ?? [])]),\n )\n return new UsageError(`Unknown command \"${name}\"`, [\n ...(candidate === undefined ? [] : [`did you mean \"znight ${candidate}\"?`]),\n 'run \"znight --help\" for the list of commands',\n ])\n}\n\n/** The help of `znight` (list of commands). */\nexport function renderRootHelp(cli: Pick<CliContext, 'colors' | 'version'>): string {\n const { colors } = cli\n const commands = table(\n [\n ['new <name>', newCommand.meta.description],\n ['generate', 'Generate the DI container (--check in CI, --watch)'],\n ['g <schematic> <name>', 'Generate a service, controller, consumer, config, guard, interceptor, factory or job'],\n ['dev', 'Build in watch mode, restart the application on every change'],\n ['build', buildCommand.meta.description],\n ['start', startCommand.meta.description],\n ['openapi', openapiCommand.meta.description],\n ],\n colors,\n )\n const options = table(\n [\n ['-h, --help', 'Show the help (also: znight <command> --help)'],\n ['-v, --version', 'Show the version'],\n ['--color, --no-color', 'Force or disable colors (NO_COLOR and FORCE_COLOR are honoured)'],\n ['--debug', 'Print the stack trace of unexpected errors (or ZNIGHT_DEBUG=1)'],\n ],\n colors,\n )\n return [\n `${colors.bold('znight')} ${colors.dim(`v${cli.version}`)} ${colors.dim('—')} compile-time dependency injection for TypeScript`,\n '',\n colors.bold('Usage'),\n ` ${colors.cyan('znight <command> [options]')}`,\n '',\n colors.bold('Commands'),\n ...commands,\n '',\n colors.bold('Global options'),\n ...options,\n '',\n `Run ${colors.cyan('znight <command> --help')} for the options of a command.`,\n '',\n ].join('\\n')\n}\n\nfunction reportError(error: unknown, cli: CliContext): number {\n if (error instanceof CancelledError) {\n cli.reporter.warn(error.message)\n return error.exitCode\n }\n if (error instanceof CliError) {\n cli.reporter.error(error.message, error.hints)\n if (cli.debug && error.cause !== undefined) cli.reporter.logError(stackOf(error.cause))\n return error.exitCode\n }\n cli.reporter.error(`Unexpected error: ${errorMessage(error)}`)\n if (cli.debug) cli.reporter.logError(stackOf(error))\n else cli.reporter.logError(cli.colors.dim(' run with --debug (or ZNIGHT_DEBUG=1) for the stack trace'))\n return ExitCode.Failure\n}\n\nfunction stackOf(error: unknown): string {\n return error instanceof Error && error.stack !== undefined ? error.stack : String(error)\n}\n"],"mappings":";;;;;;;;;;;;;;;;AAMA,MAAa,WAAW;;CAEtB,IAAI;;CAEJ,SAAS;;CAET,OAAO;;CAEP,WAAW;AACb;;AAgBA,IAAa,WAAb,cAA8B,MAAM;CAClC;CACA;CAEA,YAAY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