@nifrajs/cli 5.16.0 → 5.18.0

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.
Files changed (183) hide show
  1. package/CHANGELOG.md +67 -0
  2. package/dist/check-diagnostics.d.ts +7 -0
  3. package/dist/check-diagnostics.d.ts.map +1 -1
  4. package/dist/check-diagnostics.js +3 -0
  5. package/dist/check-diagnostics.js.map +1 -1
  6. package/dist/check-scan-sql.d.ts +95 -0
  7. package/dist/check-scan-sql.d.ts.map +1 -0
  8. package/dist/check-scan-sql.js +1190 -0
  9. package/dist/check-scan-sql.js.map +1 -0
  10. package/dist/check-scan.d.ts +5 -93
  11. package/dist/check-scan.d.ts.map +1 -1
  12. package/dist/check-scan.js +20 -1207
  13. package/dist/check-scan.js.map +1 -1
  14. package/dist/check.d.ts.map +1 -1
  15. package/dist/check.js +9 -0
  16. package/dist/check.js.map +1 -1
  17. package/dist/cli.d.ts +2 -6
  18. package/dist/cli.d.ts.map +1 -1
  19. package/dist/cli.js +249 -80
  20. package/dist/cli.js.map +1 -1
  21. package/dist/command-catalog.d.ts +3 -0
  22. package/dist/command-catalog.d.ts.map +1 -1
  23. package/dist/command-catalog.js +18 -4
  24. package/dist/command-catalog.js.map +1 -1
  25. package/dist/frontend-guidance.js +1 -1
  26. package/dist/frontend-guidance.js.map +1 -1
  27. package/dist/internal/a11y-element.d.ts +33 -0
  28. package/dist/internal/a11y-element.d.ts.map +1 -0
  29. package/dist/internal/a11y-element.js +124 -0
  30. package/dist/internal/a11y-element.js.map +1 -0
  31. package/dist/internal/a11y-jsx.d.ts +12 -0
  32. package/dist/internal/a11y-jsx.d.ts.map +1 -0
  33. package/dist/internal/a11y-jsx.js +42 -0
  34. package/dist/internal/a11y-jsx.js.map +1 -0
  35. package/dist/internal/a11y-template.d.ts +11 -0
  36. package/dist/internal/a11y-template.d.ts.map +1 -0
  37. package/dist/internal/a11y-template.js +56 -0
  38. package/dist/internal/a11y-template.js.map +1 -0
  39. package/dist/internal/aria-data.d.ts +23 -0
  40. package/dist/internal/aria-data.d.ts.map +1 -0
  41. package/dist/internal/aria-data.js +220 -0
  42. package/dist/internal/aria-data.js.map +1 -0
  43. package/dist/internal/edit-distance.d.ts +3 -0
  44. package/dist/internal/edit-distance.d.ts.map +1 -0
  45. package/dist/internal/edit-distance.js +12 -0
  46. package/dist/internal/edit-distance.js.map +1 -0
  47. package/dist/internal/imported-as.d.ts +10 -0
  48. package/dist/internal/imported-as.d.ts.map +1 -0
  49. package/dist/internal/imported-as.js +23 -0
  50. package/dist/internal/imported-as.js.map +1 -0
  51. package/dist/internal/source-facts.d.ts +3 -0
  52. package/dist/internal/source-facts.d.ts.map +1 -1
  53. package/dist/internal/source-facts.js +2 -0
  54. package/dist/internal/source-facts.js.map +1 -1
  55. package/dist/internal/template-markup.d.ts +58 -0
  56. package/dist/internal/template-markup.d.ts.map +1 -0
  57. package/dist/internal/template-markup.js +221 -0
  58. package/dist/internal/template-markup.js.map +1 -0
  59. package/dist/internal/typescript-import.d.ts.map +1 -1
  60. package/dist/internal/typescript-import.js +11 -0
  61. package/dist/internal/typescript-import.js.map +1 -1
  62. package/dist/mcp-exec.d.ts.map +1 -1
  63. package/dist/mcp-exec.js +37 -23
  64. package/dist/mcp-exec.js.map +1 -1
  65. package/dist/mcp-http.js +1 -1
  66. package/dist/mcp-io.d.ts.map +1 -1
  67. package/dist/mcp-io.js +5 -3
  68. package/dist/mcp-io.js.map +1 -1
  69. package/dist/mcp-root.js +1 -1
  70. package/dist/mcp-root.js.map +1 -1
  71. package/dist/mcp-ws.d.ts.map +1 -1
  72. package/dist/mcp-ws.js +3 -2
  73. package/dist/mcp-ws.js.map +1 -1
  74. package/dist/migrate-layout-config.d.ts +63 -0
  75. package/dist/migrate-layout-config.d.ts.map +1 -0
  76. package/dist/migrate-layout-config.js +507 -0
  77. package/dist/migrate-layout-config.js.map +1 -0
  78. package/dist/migrate-layout-split.d.ts +46 -0
  79. package/dist/migrate-layout-split.d.ts.map +1 -0
  80. package/dist/migrate-layout-split.js +687 -0
  81. package/dist/migrate-layout-split.js.map +1 -0
  82. package/dist/migrate-layout.d.ts +4 -24
  83. package/dist/migrate-layout.d.ts.map +1 -1
  84. package/dist/migrate-layout.js +8 -1183
  85. package/dist/migrate-layout.js.map +1 -1
  86. package/dist/output-schemas.d.ts.map +1 -1
  87. package/dist/output-schemas.js +78 -10
  88. package/dist/output-schemas.js.map +1 -1
  89. package/dist/recipes/5.17.0.d.ts +10 -0
  90. package/dist/recipes/5.17.0.d.ts.map +1 -0
  91. package/dist/recipes/5.17.0.js +20 -0
  92. package/dist/recipes/5.17.0.js.map +1 -0
  93. package/dist/recipes/5.18.0.d.ts +9 -0
  94. package/dist/recipes/5.18.0.d.ts.map +1 -0
  95. package/dist/recipes/5.18.0.js +56 -0
  96. package/dist/recipes/5.18.0.js.map +1 -0
  97. package/dist/recipes/index.d.ts.map +1 -1
  98. package/dist/recipes/index.js +4 -0
  99. package/dist/recipes/index.js.map +1 -1
  100. package/dist/review.d.ts.map +1 -1
  101. package/dist/review.js +6 -0
  102. package/dist/review.js.map +1 -1
  103. package/dist/rules/a11y.d.ts +5 -0
  104. package/dist/rules/a11y.d.ts.map +1 -0
  105. package/dist/rules/a11y.js +78 -0
  106. package/dist/rules/a11y.js.map +1 -0
  107. package/dist/rules/codes.d.ts +6 -0
  108. package/dist/rules/codes.d.ts.map +1 -1
  109. package/dist/rules/codes.js +6 -0
  110. package/dist/rules/codes.js.map +1 -1
  111. package/dist/rules/comment-markers.js +1 -1
  112. package/dist/rules/comment-markers.js.map +1 -1
  113. package/dist/rules/explanations.d.ts.map +1 -1
  114. package/dist/rules/explanations.js +30 -0
  115. package/dist/rules/explanations.js.map +1 -1
  116. package/dist/rules/host-exposure.d.ts +23 -0
  117. package/dist/rules/host-exposure.d.ts.map +1 -0
  118. package/dist/rules/host-exposure.js +380 -0
  119. package/dist/rules/host-exposure.js.map +1 -0
  120. package/dist/rules/internal-links.d.ts.map +1 -1
  121. package/dist/rules/internal-links.js +16 -141
  122. package/dist/rules/internal-links.js.map +1 -1
  123. package/dist/rules/islands.d.ts +54 -0
  124. package/dist/rules/islands.d.ts.map +1 -1
  125. package/dist/rules/islands.js +577 -80
  126. package/dist/rules/islands.js.map +1 -1
  127. package/dist/rules/security.d.ts +1 -0
  128. package/dist/rules/security.d.ts.map +1 -1
  129. package/dist/rules/security.js +34 -7
  130. package/dist/rules/security.js.map +1 -1
  131. package/dist/runtime-differences.js +3 -3
  132. package/dist/runtime-differences.js.map +1 -1
  133. package/dist/scaffold.d.ts +1 -1
  134. package/dist/scaffold.d.ts.map +1 -1
  135. package/dist/scaffold.js +2 -2
  136. package/dist/scaffold.js.map +1 -1
  137. package/dist/source-rewrites.d.ts.map +1 -1
  138. package/dist/source-rewrites.js +2 -19
  139. package/dist/source-rewrites.js.map +1 -1
  140. package/docs/examples.json +4 -4
  141. package/docs/llms-full.txt +443 -46
  142. package/docs/types.json +490 -66
  143. package/package.json +12 -12
  144. package/src/check-diagnostics.ts +11 -0
  145. package/src/check-scan-sql.ts +1746 -0
  146. package/src/check-scan.ts +34 -1754
  147. package/src/check.ts +10 -1
  148. package/src/cli.ts +258 -98
  149. package/src/command-catalog.ts +21 -4
  150. package/src/frontend-guidance.ts +1 -1
  151. package/src/internal/a11y-element.ts +227 -0
  152. package/src/internal/a11y-jsx.ts +54 -0
  153. package/src/internal/a11y-template.ts +74 -0
  154. package/src/internal/aria-data.ts +242 -0
  155. package/src/internal/edit-distance.ts +16 -0
  156. package/src/internal/imported-as.ts +30 -0
  157. package/src/internal/source-facts.ts +4 -0
  158. package/src/internal/template-markup.ts +270 -0
  159. package/src/internal/typescript-import.ts +15 -0
  160. package/src/mcp-exec.ts +43 -22
  161. package/src/mcp-http.ts +1 -1
  162. package/src/mcp-io.ts +5 -3
  163. package/src/mcp-root.ts +1 -1
  164. package/src/mcp-ws.ts +3 -2
  165. package/src/migrate-layout-config.ts +615 -0
  166. package/src/migrate-layout-split.ts +870 -0
  167. package/src/migrate-layout.ts +37 -1468
  168. package/src/output-schemas.ts +85 -17
  169. package/src/recipes/5.17.0.ts +28 -0
  170. package/src/recipes/5.18.0.ts +63 -0
  171. package/src/recipes/index.ts +4 -0
  172. package/src/review.ts +6 -0
  173. package/src/rules/a11y.ts +119 -0
  174. package/src/rules/codes.ts +6 -0
  175. package/src/rules/comment-markers.ts +2 -2
  176. package/src/rules/explanations.ts +30 -0
  177. package/src/rules/host-exposure.ts +531 -0
  178. package/src/rules/internal-links.ts +21 -154
  179. package/src/rules/islands.ts +698 -86
  180. package/src/rules/security.ts +48 -7
  181. package/src/runtime-differences.ts +3 -3
  182. package/src/scaffold.ts +3 -3
  183. package/src/source-rewrites.ts +2 -15
package/src/check.ts CHANGED
@@ -27,6 +27,7 @@ import {
27
27
  type CheckDiagnostic,
28
28
  type CheckResult,
29
29
  collectCheckDiagnostics,
30
+ type HostTopology,
30
31
  type RuleOverride,
31
32
  safeIgnoreGlobMatch,
32
33
  } from "./check-diagnostics.ts"
@@ -283,6 +284,7 @@ async function loadCheckConfig(
283
284
  externalMounts?: unknown
284
285
  rules?: unknown
285
286
  tsconfigs?: unknown
287
+ hostTopology?: unknown
286
288
  }
287
289
  const raw = Array.isArray(parsed.externalMounts) ? parsed.externalMounts : []
288
290
  const externalMounts = raw
@@ -351,8 +353,15 @@ async function loadCheckConfig(
351
353
  '`tsconfigs` must be a non-empty array of tsconfig paths relative to the project, such as ["tsconfig.json"] - ignored',
352
354
  )
353
355
  }
354
- const config: CheckConfig =
356
+ let hostTopology: HostTopology | undefined
357
+ if (parsed.hostTopology !== undefined) {
358
+ if (parsed.hostTopology === "direct" || parsed.hostTopology === "proxied")
359
+ hostTopology = parsed.hostTopology
360
+ else warnings.push('`hostTopology` must be "direct" or "proxied" - ignored')
361
+ }
362
+ const config: { -readonly [K in keyof CheckConfig]: CheckConfig[K] } =
355
363
  tsconfigs === undefined ? { externalMounts, rules } : { externalMounts, rules, tsconfigs }
364
+ if (hostTopology !== undefined) config.hostTopology = hostTopology
356
365
  return { config, warnings }
357
366
  } catch (error) {
358
367
  return {
package/src/cli.ts CHANGED
@@ -13,24 +13,14 @@
13
13
  import { existsSync, readFileSync, realpathSync } from "node:fs"
14
14
  import { resolve } from "node:path"
15
15
  import { fileURLToPath } from "node:url"
16
- import {
17
- type CssLoadingMode,
18
- createWebApp,
19
- DEFAULT_DEV_PORT,
20
- type RenderAdapter,
21
- } from "@nifrajs/web"
16
+ import type { CssLoadingMode, RenderAdapter } from "@nifrajs/web"
22
17
  import { formatBuildLog } from "@nifrajs/web/diagnostic"
23
18
  import { discoverRoutes } from "@nifrajs/web/fs"
19
+ import { DEFAULT_DEV_PORT } from "@nifrajs/web/internal/runtime-contract"
24
20
  import { formatShadowedPages, shadowedPages } from "@nifrajs/web/route-manifest"
25
21
  import type { BunPlugin } from "bun"
26
22
  import { adapterFile, BACKEND_APP_FILE } from "./app-files.ts"
27
- import {
28
- bindCommandArgv,
29
- type CommandSpec,
30
- commandUsage,
31
- findCommandSpec,
32
- renderCommandCatalogHelp,
33
- } from "./command-catalog.ts"
23
+ import type { CommandSpec } from "./command-catalog.ts"
34
24
  import { applyEnvFiles, forgetAutoLoadedEnv, REFLECT_ENV, takeEnvFileFlags } from "./env-file.ts"
35
25
  import { FRAMEWORK_WEB_OPTIONS, type LoadedApp, loadApp, type NifraFramework } from "./load.ts"
36
26
  import { PROJECT_COMMANDS, runThroughLocalCli } from "./local-cli.ts"
@@ -363,12 +353,29 @@ Env: \`--env-file <path>\` works on EVERY command and may be repeated (later fil
363
353
  reflect your app import it, so an app that validates its environment at module scope needs that
364
354
  environment present - without it the app aborts before nifra runs a single check. A variable already
365
355
  set in the process environment is never overwritten by a file.
366
- e.g. \`nifra check --env-file .env.local\`
356
+ e.g. \`nifra check --env-file .env.local\``
357
+
358
+ const SHORT_HELP = `nifra - develop, build, and verify a nifra app
367
359
 
368
- ${renderCommandCatalogHelp()}`
360
+ Develop dev, build, start, scaffold, target, db
361
+ Verify check, review, assure, doctor, fix, smoke
362
+ Contracts routes, types, schemas, openapi, contracts
363
+ Agents mcp, docs-mcp, learn, context, runtime
364
+ nifra init-agents configures editor and agent discovery
365
+ nifra init-agents --sync-mcp refreshes MCP registrations
366
+
367
+ Run nifra <command> --help for command options or nifra help --all for the full catalog.
368
+
369
+ nifra check accepts --lints-only to skip typechecking.
370
+ With a contracts.lock.json, both modes import backend/app.ts (running its top-level code).`
371
+
372
+ async function fullHelp(): Promise<string> {
373
+ const { renderCommandCatalogHelp } = await import("./command-catalog.ts")
374
+ return `${HELP}\n\n${renderCommandCatalogHelp()}`
375
+ }
369
376
 
370
377
  // Kept in lockstep with packages/cli/package.json by check:publish's version-consistency gate.
371
- const CLI_VERSION = "5.16.0"
378
+ const CLI_VERSION = "5.18.0"
372
379
 
373
380
  // A render adapter + nifra server are opaque to the CLI (it just forwards them); cast at the seam.
374
381
  const asAdapter = (v: unknown): RenderAdapter => v as RenderAdapter
@@ -420,28 +427,36 @@ export function formatCliError(err: unknown): string {
420
427
 
421
428
  /** A failed command's message on stderr and, for a `--json` caller parsing stdout, as JSON there. */
422
429
  /** One catalog command's usage: its lines from {@link HELP} when it has them, else the catalog's. */
423
- export function commandHelp<Input, Output>(spec: CommandSpec<Input, Output>): string {
430
+ function commandHelp<Input, Output>(spec: CommandSpec<Input, Output>, usage: string): string {
424
431
  const name = spec.name.replace(/^db-/, "db ")
425
432
  const lines: string[] = []
426
433
  let inside = false
427
434
  for (const line of HELP.split("\n")) {
428
435
  if (line.startsWith(` nifra ${name} `) || line === ` nifra ${name}`) inside = true
429
436
  else if (!inside || !/^ {3,}\S/.test(line)) {
430
- // The first block is the hand-written one; the catalog's one-line summary repeats it below.
431
437
  if (lines.length > 0) break
432
438
  continue
433
439
  }
434
440
  lines.push(line)
435
441
  }
436
442
  if (lines.length > 0) return ["Usage:", ...lines].join("\n")
437
- const usage = commandUsage(spec)
438
443
  return `Usage:\n nifra ${name}${usage === "" ? "" : ` ${usage}`} ${spec.summary}`
439
444
  }
440
445
 
446
+ function manualBooleanFlag(args: readonly string[], name: string): boolean {
447
+ let enabled = false
448
+ for (const arg of args) {
449
+ if (arg === "--") break
450
+ if (arg === name) enabled = true
451
+ else if (arg.startsWith(`${name}=`)) enabled = arg.slice(name.length + 1) === "true"
452
+ }
453
+ return enabled
454
+ }
455
+
441
456
  function reportFailure(err: unknown, argv: readonly string[]): void {
442
457
  const message = formatCliError(err)
443
458
  console.error(message)
444
- if (argv.includes("--json") || argv.includes("--json=true"))
459
+ if (manualBooleanFlag(argv, "--json"))
445
460
  console.log(JSON.stringify({ ok: false, error: message }, null, 2))
446
461
  }
447
462
 
@@ -517,7 +532,7 @@ async function dev(app: LoadedApp, flags: Flags): Promise<void> {
517
532
  // present. Keep a second, authenticated copy of the user vector in the child's environment so
518
533
  // the configured process cannot silently fall back to `nifra`'s help and exit 0. The launch token
519
534
  // is still the proof boundary; these arguments are only a transport, never authorization.
520
- const childCliArgv = [...cliArgv()]
535
+ const childCliArgv = [...(await cliArgv())]
521
536
  const child = Bun.spawn(
522
537
  [
523
538
  process.execPath,
@@ -621,6 +636,7 @@ async function dev(app: LoadedApp, flags: Flags): Promise<void> {
621
636
  // scope; it has to defer to first render, which happens after this point. `@nifrajs/web-svelte`
622
637
  // loads its `Chain.svelte` that way for exactly this reason, and says so at the import.
623
638
  const { createDevServer } = await import("@nifrajs/web/dev")
639
+ const { createWebApp } = await import("@nifrajs/web")
624
640
  const { framework: fw, routesDir, outDir, backend } = app
625
641
  const server = await createDevServer({
626
642
  routesDir,
@@ -686,6 +702,7 @@ async function dev(app: LoadedApp, flags: Flags): Promise<void> {
686
702
  // Both attempts add a compiler. The fix removes one instead: `createViteDevServer` publishes its
687
703
  // `ssrLoadModule` via `setSsrModuleLoader`, and the adapter loads `Chain.svelte` AND `svelte/server`
688
704
  // through it - one toolchain, one runtime, context intact across the whole tree.
705
+ const { createWebApp } = await import("@nifrajs/web")
689
706
  const server = await createViteDevServer({
690
707
  root: cwd,
691
708
  routesDir,
@@ -1119,6 +1136,7 @@ async function buildPrerenderApp(
1119
1136
  app: LoadedApp,
1120
1137
  ): Promise<(client: BuiltManifest) => { fetch(req: Request): Response | Promise<Response> }> {
1121
1138
  const { plugin } = await import("bun")
1139
+ const { createWebApp } = await import("@nifrajs/web")
1122
1140
  const { framework: fw, routesDir, backend } = app
1123
1141
  for (const p of asBunPlugins(app.resolvedPlugins.serverPlugins)) plugin(p)
1124
1142
  return (client) =>
@@ -1370,8 +1388,83 @@ export function frontendCommandInput(
1370
1388
  }
1371
1389
 
1372
1390
  /** Dispatch a CLI invocation, including project-independent agent and documentation commands. */
1391
+ const MANUAL_HELP_COMMANDS = new Set([
1392
+ "mcp",
1393
+ "docs-mcp",
1394
+ "learn",
1395
+ "frontend",
1396
+ "runtime",
1397
+ "verify",
1398
+ "init-agents",
1399
+ "sdk",
1400
+ ])
1401
+
1402
+ function manualHelp(command: string): string {
1403
+ return HELP.split(/\n(?= {2}nifra )/)
1404
+ .filter((section) => section.startsWith(` nifra ${command} `))
1405
+ .map((section) => section.trimEnd())
1406
+ .join("\n")
1407
+ }
1408
+
1409
+ function manualFlagValue(argv: readonly string[], name: string): string | undefined {
1410
+ for (const [index, arg] of argv.entries()) {
1411
+ if (arg.startsWith(`${name}=`)) return arg.slice(name.length + 1)
1412
+ if (arg === name) {
1413
+ const value = argv[index + 1]
1414
+ return value === undefined || value.startsWith("-") ? "" : value
1415
+ }
1416
+ }
1417
+ return undefined
1418
+ }
1419
+
1420
+ function rejectUnknownManualFlags(
1421
+ args: readonly string[],
1422
+ valueFlags: readonly string[],
1423
+ booleanFlags: readonly string[],
1424
+ ): void {
1425
+ const valueSet = new Set(valueFlags)
1426
+ const boolSet = new Set(booleanFlags)
1427
+ for (let index = 0; index < args.length; index++) {
1428
+ const arg = args[index]
1429
+ if (arg === undefined || arg === "--") break
1430
+ if (!arg.startsWith("-")) continue
1431
+ const eq = arg.indexOf("=")
1432
+ const name = eq === -1 ? arg : arg.slice(0, eq)
1433
+ if (name === "--help" || name === "-h") continue
1434
+ if (boolSet.has(name)) {
1435
+ if (eq !== -1 && arg.slice(eq + 1) !== "true" && arg.slice(eq + 1) !== "false") {
1436
+ throw new Error(`[nifra] ${name} takes no value`)
1437
+ }
1438
+ continue
1439
+ }
1440
+ if (valueSet.has(name)) {
1441
+ if (eq !== -1) {
1442
+ if (arg.slice(eq + 1) === "") throw new Error(`[nifra] ${name} needs a value`)
1443
+ continue
1444
+ }
1445
+ const next = args[index + 1]
1446
+ if (next === undefined || next.startsWith("-")) {
1447
+ throw new Error(`[nifra] ${name} needs a value`)
1448
+ }
1449
+ index++
1450
+ continue
1451
+ }
1452
+ throw new Error(`[nifra] unknown option: ${arg} - see \`nifra help\``)
1453
+ }
1454
+ }
1455
+
1373
1456
  async function main(): Promise<void> {
1374
- const { argv: rawArgv, files: envFiles } = takeEnvFileFlags(cliArgv())
1457
+ const { argv: rawArgv, files: envFiles } = takeEnvFileFlags(await cliArgv())
1458
+ const helpCommand = rawArgv[0]
1459
+ if (
1460
+ helpCommand !== undefined &&
1461
+ ((MANUAL_HELP_COMMANDS.has(helpCommand) &&
1462
+ (rawArgv.includes("--help") || rawArgv.includes("-h"))) ||
1463
+ (helpCommand === "db" && (rawArgv[1] === "--help" || rawArgv[1] === "-h")))
1464
+ ) {
1465
+ console.log(manualHelp(helpCommand))
1466
+ return
1467
+ }
1375
1468
  // `nifra mcp` keeps none of the `.env` values Bun loaded at startup. Decided before the
1376
1469
  // `--env-file`s below, which the caller names explicitly and which stay.
1377
1470
  const forgotten =
@@ -1390,7 +1483,7 @@ async function main(): Promise<void> {
1390
1483
  "the verified dev configuration. Re-run `nifra dev`.",
1391
1484
  )
1392
1485
  }
1393
- console.log(HELP)
1486
+ console.log(argv.includes("--all") ? await fullHelp() : SHORT_HELP)
1394
1487
  return
1395
1488
  }
1396
1489
  if (command === "--version" || command === "-v") {
@@ -1406,7 +1499,7 @@ async function main(): Promise<void> {
1406
1499
  const exitCode = await runThroughLocalCli({
1407
1500
  cwd: process.cwd(),
1408
1501
  version: CLI_VERSION,
1409
- args: cliArgv(),
1502
+ args: await cliArgv(),
1410
1503
  })
1411
1504
  if (exitCode !== undefined) {
1412
1505
  process.exitCode = exitCode
@@ -1416,6 +1509,13 @@ async function main(): Promise<void> {
1416
1509
  // `mcp` runs a long-lived stdio server and loads the project lazily per-tool - it must not go through
1417
1510
  // the eager `loadApp` below (which would fail fast on a project that's API-only / not yet built).
1418
1511
  if (command === "mcp") {
1512
+ try {
1513
+ rejectUnknownManualFlags(argv.slice(1), [], [])
1514
+ } catch (err) {
1515
+ reportFailure(err, argv)
1516
+ process.exitCode = 1
1517
+ return
1518
+ }
1419
1519
  // Bun passes what it loaded to every subprocess whatever `process.env` says now, so the session
1420
1520
  // moves to a copy of this process that never loads `.env` files.
1421
1521
  if (forgotten.length > 0) {
@@ -1439,26 +1539,39 @@ async function main(): Promise<void> {
1439
1539
  // `docs-mcp` runs the PUBLIC docs MCP over HTTP - project-independent (serves the bundled corpus), so
1440
1540
  // it self-hosts anywhere Bun runs (a VPS behind a reverse proxy, a container). Long-lived; no loadApp.
1441
1541
  if (command === "docs-mcp") {
1442
- const { handleMcpHttp } = await import("./mcp-http.ts")
1443
- const portArg = argv[argv.indexOf("--port") + 1]
1444
- const port = Number(portArg && argv.includes("--port") ? portArg : (Bun.env.PORT ?? 8787))
1445
- if (!Number.isInteger(port) || port < 0 || port > 65535) {
1446
- throw new Error(`[nifra] invalid --port: ${port}`)
1542
+ try {
1543
+ rejectUnknownManualFlags(argv.slice(1), ["--port", "-p"], [])
1544
+ const { handleMcpHttp } = await import("./mcp-http.ts")
1545
+ const portArg =
1546
+ manualFlagValue(argv, "--port") ?? manualFlagValue(argv, "-p") ?? Bun.env.PORT ?? "8787"
1547
+ const port = /^\d+$/.test(portArg) ? Number(portArg) : Number.NaN
1548
+ if (!Number.isInteger(port) || port < 0 || port > 65535) {
1549
+ throw new Error(`[nifra] invalid --port: ${portArg}`)
1550
+ }
1551
+ const server = Bun.serve({ port, fetch: handleMcpHttp })
1552
+ console.log(`nifra docs MCP (HTTP) → ${server.url}`)
1553
+ } catch (err) {
1554
+ reportFailure(err, argv)
1555
+ process.exitCode = 1
1447
1556
  }
1448
- const server = Bun.serve({ port, fetch: handleMcpHttp })
1449
- console.log(`nifra docs MCP (HTTP) → ${server.url}`)
1450
1557
  return
1451
1558
  }
1452
1559
  // `learn` prints the guided build-an-app path (the human head of `nifra_learn`). Project-independent:
1453
1560
  // the path is static, so no project needs to load. `nifra learn` for the index, `nifra learn 3` for a step.
1454
1561
  if (command === "learn") {
1455
- const { renderLearnResult } = await import("./learn.ts")
1456
- const stepArg = argv[1]
1457
- console.log(
1458
- renderLearnResult(
1459
- stepArg !== undefined && /^\d+$/.test(stepArg) ? Number(stepArg) : undefined,
1460
- ),
1461
- )
1562
+ try {
1563
+ rejectUnknownManualFlags(argv.slice(1), [], [])
1564
+ const { renderLearnResult } = await import("./learn.ts")
1565
+ const stepArg = argv[1]
1566
+ console.log(
1567
+ renderLearnResult(
1568
+ stepArg !== undefined && /^\d+$/.test(stepArg) ? Number(stepArg) : undefined,
1569
+ ),
1570
+ )
1571
+ } catch (err) {
1572
+ reportFailure(err, argv)
1573
+ process.exitCode = 1
1574
+ }
1462
1575
  return
1463
1576
  }
1464
1577
  // `frontend` prints the client-side footgun catalog (the human head of `nifra_frontend`).
@@ -1495,6 +1608,7 @@ async function main(): Promise<void> {
1495
1608
  // `nifra db <sub>` is the catalog's `db-<sub>` command, projected to MCP as `nifra_db_<sub>`.
1496
1609
  const dbSub =
1497
1610
  command === "db" && argv[1] !== undefined && !argv[1].startsWith("-") ? argv[1] : undefined
1611
+ const { findCommandSpec, commandUsage, bindCommandArgv } = await import("./command-catalog.ts")
1498
1612
  if (command === "db" && (dbSub === undefined || findCommandSpec(`db-${dbSub}`) === undefined)) {
1499
1613
  throw new Error("[nifra] usage: nifra db schema|query|role|audit - see `nifra help`")
1500
1614
  }
@@ -1502,7 +1616,7 @@ async function main(): Promise<void> {
1502
1616
  if (catalogSpec?.transports.includes("cli")) {
1503
1617
  const commandArgs = argv.slice(dbSub === undefined ? 1 : 2)
1504
1618
  if (commandArgs.includes("--help") || commandArgs.includes("-h")) {
1505
- console.log(commandHelp(catalogSpec))
1619
+ console.log(commandHelp(catalogSpec, commandUsage(catalogSpec)))
1506
1620
  return
1507
1621
  }
1508
1622
  const markReflecting = installReflectionExitHint()
@@ -1515,13 +1629,19 @@ async function main(): Promise<void> {
1515
1629
  input = bindCommandArgv(catalogSpec, commandArgs)
1516
1630
  } catch (error) {
1517
1631
  const message = error instanceof Error ? error.message : String(error)
1518
- throw new Error(`[nifra] ${message}\n\n${commandHelp(catalogSpec)}`)
1632
+ throw new Error(
1633
+ `[nifra] ${message}\n\n${commandHelp(catalogSpec, commandUsage(catalogSpec))}`,
1634
+ )
1519
1635
  }
1520
1636
  markReflecting(command)
1521
1637
  const output = await catalogSpec.run(input, { cwd: process.cwd(), cliVersion: CLI_VERSION })
1522
1638
  markReflecting(undefined)
1523
1639
  const asRecord = output as Record<string, unknown>
1524
- const wantsJson = asRecord.json === true || argv.includes("--json")
1640
+ const jsonFlag =
1641
+ typeof input === "object" && input !== null ? Reflect.get(input, "json") : undefined
1642
+ const wantsJson =
1643
+ asRecord.json === true ||
1644
+ (typeof jsonFlag === "boolean" ? jsonFlag : argv.includes("--json"))
1525
1645
  if (wantsJson) {
1526
1646
  const value = catalogSpec.json?.(output, input) ?? output
1527
1647
  console.log(typeof value === "string" ? value : JSON.stringify(value, null, 2))
@@ -1554,50 +1674,60 @@ async function main(): Promise<void> {
1554
1674
  return
1555
1675
  }
1556
1676
  if (command === "verify") {
1557
- const { runReleaseVerification } = await import("./release-verification.ts")
1558
- const ok = await runReleaseVerification(process.cwd(), {
1559
- mode: argv.includes("--release") ? "release" : "default",
1560
- json: argv.includes("--json"),
1561
- })
1562
- if (!ok) process.exitCode = 1
1677
+ try {
1678
+ const commandArgs = argv.slice(1)
1679
+ rejectUnknownManualFlags(commandArgs, [], ["--release", "--json"])
1680
+ const { runReleaseVerification } = await import("./release-verification.ts")
1681
+ const ok = await runReleaseVerification(process.cwd(), {
1682
+ mode: manualBooleanFlag(commandArgs, "--release") ? "release" : "default",
1683
+ json: manualBooleanFlag(commandArgs, "--json"),
1684
+ })
1685
+ if (!ok) process.exitCode = 1
1686
+ } catch (err) {
1687
+ reportFailure(err, argv)
1688
+ process.exitCode = 1
1689
+ }
1563
1690
  return
1564
1691
  }
1565
1692
  // `init-agents` retrofits the agent files (.mcp.json, CLAUDE.md, AGENTS.md, …) into the cwd. It's a
1566
1693
  // pure file-writing command independent of the app loading, so dispatch it before the eager `loadApp`
1567
1694
  // (an existing app might be API-only or not yet built). It always succeeds unless a write throws.
1568
1695
  if (command === "init-agents") {
1569
- const { runInitAgents } = await import("./init-agents.ts")
1570
- await runInitAgents(process.cwd(), {
1571
- json: argv.includes("--json"),
1572
- force: argv.includes("--force"),
1573
- syncMcp: argv.includes("--sync-mcp"),
1574
- })
1696
+ try {
1697
+ const commandArgs = argv.slice(1)
1698
+ rejectUnknownManualFlags(commandArgs, [], ["--force", "--sync-mcp", "--json"])
1699
+ const { runInitAgents } = await import("./init-agents.ts")
1700
+ await runInitAgents(process.cwd(), {
1701
+ json: manualBooleanFlag(commandArgs, "--json"),
1702
+ force: manualBooleanFlag(commandArgs, "--force"),
1703
+ syncMcp: manualBooleanFlag(commandArgs, "--sync-mcp"),
1704
+ })
1705
+ } catch (err) {
1706
+ reportFailure(err, argv)
1707
+ process.exitCode = 1
1708
+ }
1575
1709
  return
1576
1710
  }
1577
1711
  if (command === "sdk") {
1578
- const languageIndex = argv.indexOf("--lang")
1579
- const language = languageIndex === -1 ? undefined : argv[languageIndex + 1]
1580
- const outIndex = argv.indexOf("--out")
1581
- const out = outIndex === -1 ? undefined : argv[outIndex + 1]
1582
- if (language !== "python" && language !== "go") {
1583
- console.error("[nifra] sdk needs --lang python or --lang go")
1584
- process.exitCode = 1
1585
- return
1586
- }
1587
- if (outIndex !== -1 && (out === undefined || out.startsWith("-"))) {
1588
- console.error("[nifra] --out needs a file path")
1589
- process.exitCode = 1
1590
- return
1591
- }
1592
1712
  try {
1713
+ const commandArgs = argv.slice(1)
1714
+ rejectUnknownManualFlags(commandArgs, ["--lang", "--out"], ["--strict", "--json"])
1715
+ const language = manualFlagValue(argv, "--lang")
1716
+ const out = manualFlagValue(argv, "--out")
1717
+ if (language !== "python" && language !== "go") {
1718
+ throw new Error("[nifra] sdk needs --lang python or --lang go")
1719
+ }
1720
+ if (out === "") {
1721
+ throw new Error("[nifra] --out needs a file path")
1722
+ }
1593
1723
  const { runSdk } = await import("./sdk.ts")
1594
1724
  await runSdk(process.cwd(), {
1595
1725
  language,
1596
1726
  ...(out !== undefined ? { out } : {}),
1597
- ...(argv.includes("--strict") ? { strict: true } : {}),
1727
+ ...(manualBooleanFlag(commandArgs, "--strict") ? { strict: true } : {}),
1598
1728
  })
1599
1729
  } catch (err) {
1600
- console.error(formatCliError(err))
1730
+ reportFailure(err, argv)
1601
1731
  process.exitCode = 1
1602
1732
  }
1603
1733
  exitIfHeldOpen(command)
@@ -1608,7 +1738,7 @@ async function main(): Promise<void> {
1608
1738
  // repo (API-only, not built, or mid-upgrade with edits that don't yet typecheck under dry-run).
1609
1739
  if (command === "upgrade") {
1610
1740
  if (argv.includes("--help") || argv.includes("-h")) {
1611
- console.log(HELP)
1741
+ console.log(manualHelp(command))
1612
1742
  return
1613
1743
  }
1614
1744
  const { parseUpgradeArgs, runUpgrade } = await import("./upgrade.ts")
@@ -1629,12 +1759,12 @@ async function main(): Promise<void> {
1629
1759
  // `doctor`, dispatch before the eager `loadApp` so it runs on an API-only / not-yet-built project.
1630
1760
  if (command !== "dev" && command !== "build" && command !== "start") {
1631
1761
  console.error(`[nifra] unknown command: ${command}\n`)
1632
- console.error(HELP)
1762
+ console.error(SHORT_HELP)
1633
1763
  process.exitCode = 1
1634
1764
  return
1635
1765
  }
1636
1766
  if (argv.includes("--help") || argv.includes("-h")) {
1637
- console.log(HELP)
1767
+ console.log(manualHelp(command))
1638
1768
  return
1639
1769
  }
1640
1770
  const flags = parseFlags(argv.slice(1))
@@ -1749,53 +1879,76 @@ function isMainModule(): boolean {
1749
1879
  * sees test-file paths and runner flags, not an exact Nifra command, while a direct CLI invocation
1750
1880
  * has one of the manual or catalogued command names below.
1751
1881
  */
1752
- function isCliCommandToken(value: string): boolean {
1753
- return (
1882
+ async function isCliCommandToken(value: string): Promise<boolean> {
1883
+ if (
1754
1884
  value === "dev" ||
1755
1885
  value === "build" ||
1756
1886
  value === "start" ||
1757
- value === "mcp" ||
1758
- value === "init-agents" ||
1887
+ MANUAL_HELP_COMMANDS.has(value) ||
1759
1888
  value === "upgrade" ||
1760
1889
  value === "db" ||
1761
1890
  value === "help" ||
1762
1891
  value === "--help" ||
1763
1892
  value === "-h" ||
1764
1893
  value === "--version" ||
1765
- value === "-v" ||
1766
- findCommandSpec(value) !== undefined
1894
+ value === "-v"
1767
1895
  )
1896
+ return true
1897
+ if (!/^[a-z][a-z0-9-]*$/.test(value)) return false
1898
+ const { findCommandSpec } = await import("./command-catalog.ts")
1899
+ return findCommandSpec(value) !== undefined
1768
1900
  }
1769
1901
 
1770
- function findCliCommand(values: readonly string[]): number {
1902
+ async function findCliCommand(values: readonly string[]): Promise<number> {
1771
1903
  // Most Bun/Node argv vectors reserve index 0 for the runtime and index 1 for the script. Bun 1.4
1772
1904
  // on Windows can omit the script for a directly spawned TS entry, leaving the command at index 0.
1773
1905
  // Accept that one exact-token shape while keeping arbitrary imported-module argv inert.
1774
- return values.findIndex((value) => isCliCommandToken(value))
1906
+ for (const [index, value] of values.entries()) {
1907
+ if (values[index - 1] === "--env-file" && !value.startsWith("-")) continue
1908
+ if (await isCliCommandToken(value)) return index
1909
+ }
1910
+ return -1
1775
1911
  }
1776
1912
 
1777
1913
  /**
1778
1914
  * The command vector from one runtime argv: the command, then its arguments. Arguments typed before
1779
1915
  * the command (`nifra --json check`) follow the command's own, ahead of any `--`, rather than being
1780
- * dropped. Only when index 1 is the script: a runtime flag there means the leading entries are the
1781
- * runtime's own, not the caller's.
1916
+ * dropped. Env-file flags go first instead, so they keep command-line order and a later file still
1917
+ * wins. A leading one also belongs to the CLI when Bun omits the script path.
1782
1918
  */
1783
1919
  export function commandArgv(values: readonly string[], commandIndex: number): readonly string[] {
1784
1920
  const command = values.slice(commandIndex)
1785
- const script = values[1]
1786
- if (commandIndex <= 2 || script === undefined || script.startsWith("-")) return command
1787
- const leading = values.slice(2, commandIndex)
1921
+ const runtimeEnvFile = values
1922
+ .slice(0, 2)
1923
+ .findIndex((value) => value === "--env-file" || value.startsWith("--env-file="))
1924
+ // With no env-file flag ahead of it, index 1 is the script, or a runtime flag whose neighbours
1925
+ // are the runtime's own.
1926
+ if (runtimeEnvFile === -1 && (values[1] === undefined || values[1].startsWith("-")))
1927
+ return command
1928
+
1929
+ const envFiles: string[] = []
1930
+ let others: string[] = []
1931
+ let scriptAhead = runtimeEnvFile !== -1
1932
+ for (let index = scriptAhead ? runtimeEnvFile : 2; index < commandIndex; index++) {
1933
+ const value = values[index] ?? ""
1934
+ if (value === "--env-file") envFiles.push(...values.slice(index, ++index + 1))
1935
+ else if (value.startsWith("--env-file=")) envFiles.push(value)
1936
+ else if (scriptAhead && !value.startsWith("-")) {
1937
+ // The script path: it and the runtime flags before it are not the caller's.
1938
+ scriptAhead = false
1939
+ others = []
1940
+ } else others.push(value)
1941
+ }
1788
1942
  const separator = command.indexOf("--")
1789
- return separator === -1
1790
- ? [...command, ...leading]
1791
- : [...command.slice(0, separator), ...leading, ...command.slice(separator)]
1943
+ const end = separator === -1 ? command.length : separator
1944
+ return [...envFiles, ...command.slice(0, end), ...others, ...command.slice(end)]
1792
1945
  }
1793
1946
 
1794
- function cliArgv(): readonly string[] {
1795
- const reexec = reexecCliArgv()
1947
+ async function cliArgv(): Promise<readonly string[]> {
1948
+ const reexec = await reexecCliArgv()
1796
1949
  if (reexec !== undefined) return reexec
1797
1950
  for (const values of [Bun.argv, process.argv]) {
1798
- const commandIndex = findCliCommand(values)
1951
+ const commandIndex = await findCliCommand(values)
1799
1952
  if (commandIndex >= 0) return commandArgv(values, commandIndex)
1800
1953
  }
1801
1954
  return Bun.argv.slice(2)
@@ -1807,7 +1960,7 @@ function cliArgv(): readonly string[] {
1807
1960
  * first item must be a real Nifra command, and malformed/oversized data is ignored so an inherited
1808
1961
  * environment can never turn an imported CLI module into an arbitrary command runner.
1809
1962
  */
1810
- function reexecCliArgv(): readonly string[] | undefined {
1963
+ async function reexecCliArgv(): Promise<readonly string[] | undefined> {
1811
1964
  if (!isBunDevReexecChild()) return undefined
1812
1965
  const encoded = process.env.NIFRA_BUN_DEV_ARGS
1813
1966
  if (encoded === undefined || encoded.length > 64 * 1024) return undefined
@@ -1825,13 +1978,20 @@ function reexecCliArgv(): readonly string[] | undefined {
1825
1978
  ) {
1826
1979
  return undefined
1827
1980
  }
1828
- const command = parsed[0]
1981
+ // commandArgv puts env-file flags ahead of the command.
1982
+ let at = 0
1983
+ while (at < parsed.length) {
1984
+ if (parsed[at] === "--env-file") at += 2
1985
+ else if (String(parsed[at]).startsWith("--env-file=")) at++
1986
+ else break
1987
+ }
1988
+ const command = parsed[at]
1829
1989
  if (typeof command !== "string") return undefined
1830
- return isCliCommandToken(command) ? (parsed as string[]) : undefined
1990
+ return (await isCliCommandToken(command)) ? (parsed as string[]) : undefined
1831
1991
  }
1832
1992
 
1833
- function hasCliCommandToken(): boolean {
1834
- return findCliCommand(Bun.argv) >= 0 || findCliCommand(process.argv) >= 0
1993
+ async function hasCliCommandToken(): Promise<boolean> {
1994
+ return (await findCliCommand(Bun.argv)) >= 0 || (await findCliCommand(process.argv)) >= 0
1835
1995
  }
1836
1996
 
1837
1997
  /**
@@ -1854,7 +2014,7 @@ function isBunDevReexecChild(): boolean {
1854
2014
 
1855
2015
  // Only run the CLI when invoked as the entry (`bun cli.ts …`), not when a test imports it for the
1856
2016
  // exported `parseFlags`.
1857
- if (isMainModule() || isBunDevReexecChild() || hasCliCommandToken()) {
2017
+ if (isMainModule() || isBunDevReexecChild() || (await hasCliCommandToken())) {
1858
2018
  // Keep the entry module alive until the async CLI has completed. Bun 1.4 on Windows can otherwise
1859
2019
  // terminate a process created by Bun.spawn while its first dynamic import is pending, leaving an
1860
2020
  // exit-0 child with no output. Imported test modules never enter this branch, so the CLI's top-level
@@ -1862,7 +2022,7 @@ if (isMainModule() || isBunDevReexecChild() || hasCliCommandToken()) {
1862
2022
  try {
1863
2023
  await main()
1864
2024
  } catch (err) {
1865
- reportFailure(err, cliArgv())
2025
+ reportFailure(err, await cliArgv())
1866
2026
  process.exitCode = 1
1867
2027
  }
1868
2028
  }