@lunora/cli 1.0.0-alpha.46 → 1.0.0-alpha.461

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 (142) hide show
  1. package/LICENSE.md +33 -0
  2. package/README.md +3 -1
  3. package/dist/bin.mjs +3 -10
  4. package/dist/cli.d.mts +31 -0
  5. package/dist/cli.d.ts +31 -0
  6. package/dist/cli.mjs +1 -0
  7. package/dist/index.d.mts +1096 -386
  8. package/dist/index.d.ts +1096 -386
  9. package/dist/index.mjs +1 -19
  10. package/dist/packem_chunks/cli.mjs +2 -0
  11. package/dist/packem_chunks/dispatch.mjs +1 -0
  12. package/dist/packem_chunks/handler.mjs +17 -158
  13. package/dist/packem_chunks/handler10.mjs +1 -16
  14. package/dist/packem_chunks/handler11.mjs +1 -22
  15. package/dist/packem_chunks/handler12.mjs +1 -192
  16. package/dist/packem_chunks/handler13.mjs +1 -131
  17. package/dist/packem_chunks/handler14.mjs +1 -65
  18. package/dist/packem_chunks/handler15.mjs +3 -58
  19. package/dist/packem_chunks/handler16.mjs +1 -80
  20. package/dist/packem_chunks/handler17.mjs +1 -43
  21. package/dist/packem_chunks/handler18.mjs +1 -105
  22. package/dist/packem_chunks/handler19.mjs +1 -170
  23. package/dist/packem_chunks/handler2.mjs +1 -114
  24. package/dist/packem_chunks/handler20.mjs +7 -94
  25. package/dist/packem_chunks/handler21.mjs +2 -94
  26. package/dist/packem_chunks/handler22.mjs +1 -0
  27. package/dist/packem_chunks/handler23.mjs +3 -0
  28. package/dist/packem_chunks/handler24.mjs +3 -0
  29. package/dist/packem_chunks/handler25.mjs +1 -0
  30. package/dist/packem_chunks/handler26.mjs +2 -0
  31. package/dist/packem_chunks/handler27.mjs +99 -0
  32. package/dist/packem_chunks/handler28.mjs +15 -0
  33. package/dist/packem_chunks/handler29.mjs +1 -0
  34. package/dist/packem_chunks/handler3.mjs +1 -204
  35. package/dist/packem_chunks/handler30.mjs +1 -0
  36. package/dist/packem_chunks/handler4.mjs +1 -33
  37. package/dist/packem_chunks/handler5.mjs +3 -49
  38. package/dist/packem_chunks/handler6.mjs +1 -91
  39. package/dist/packem_chunks/handler7.mjs +1 -42
  40. package/dist/packem_chunks/handler8.mjs +1 -174
  41. package/dist/packem_chunks/handler9.mjs +2 -315
  42. package/dist/packem_chunks/runCodegenCommand.mjs +4 -52
  43. package/dist/packem_chunks/runDevCommand.mjs +6 -0
  44. package/dist/packem_chunks/runInitCommand.mjs +212 -1432
  45. package/dist/packem_chunks/runResetCommand.mjs +1 -41
  46. package/dist/packem_chunks/runRpcCommand.mjs +1 -68
  47. package/dist/packem_shared/DEFAULT_IMPORT_BATCH_SIZE-5xxKz-zB.mjs +1 -0
  48. package/dist/packem_shared/EXIT_CODE-DVjUgIaG.mjs +1 -0
  49. package/dist/packem_shared/admin-token-VdUnvnKW.mjs +1 -0
  50. package/dist/packem_shared/admin-url-DJB8P6Jh.mjs +1 -0
  51. package/dist/packem_shared/api-spec-lYyq4vL6.mjs +1 -0
  52. package/dist/packem_shared/binding-manifest-file-CQ1eQYy1.mjs +2 -0
  53. package/dist/packem_shared/buildRegistryIndex-Dc8D8AR6.mjs +1 -0
  54. package/dist/packem_shared/cap-error-body-YBKO32BF.mjs +1 -0
  55. package/dist/packem_shared/catalog-CahzmDLV.mjs +1 -0
  56. package/dist/packem_shared/cli-manifest-DoQ_3bzs.mjs +1 -0
  57. package/dist/packem_shared/cloudflare-credentials-BVmZnDZk.mjs +1 -0
  58. package/dist/packem_shared/codegen-error-AmH54ofi.mjs +3 -0
  59. package/dist/packem_shared/command-B6vu47iR.mjs +1 -0
  60. package/dist/packem_shared/commands-DC3ZX1yk.mjs +13 -0
  61. package/dist/packem_shared/createLogger-4TujevyB.mjs +2 -0
  62. package/dist/packem_shared/createRecordingSpawner-01ZngIwK.mjs +1 -0
  63. package/dist/packem_shared/deploy-target-resolve-BTCW1Iv4.mjs +1 -0
  64. package/dist/packem_shared/diffSnapshots-htqNZT8Q.mjs +7 -0
  65. package/dist/packem_shared/docker-DpVxvYpL.mjs +1 -0
  66. package/dist/packem_shared/free-port-DjbFhaaT.mjs +1 -0
  67. package/dist/packem_shared/health-probe-Bw9JFfIy.mjs +1 -0
  68. package/dist/packem_shared/import-DoAUdyfU.mjs +13 -0
  69. package/dist/packem_shared/index-oHZBGBwB.mjs +1 -0
  70. package/dist/packem_shared/insertSchemaExtension-CbTH3lCQ.mjs +10 -0
  71. package/dist/packem_shared/lint-ignore-report-DKZagpqk.mjs +2 -0
  72. package/dist/packem_shared/mcp-config-file-GR1Y_CVw.mjs +2 -0
  73. package/dist/packem_shared/open-url-EnKy--w-.mjs +1 -0
  74. package/dist/packem_shared/output-format-DWe_tkTR.mjs +2 -0
  75. package/dist/packem_shared/parseManifest-CwPTKdtS.mjs +1 -0
  76. package/dist/packem_shared/path-containment-CgxYZggb.mjs +1 -0
  77. package/dist/packem_shared/plan-BH4ZfiFs.mjs +5 -0
  78. package/dist/packem_shared/planDevCommand-I8-NB_CN.mjs +1 -0
  79. package/dist/packem_shared/platform-diagnostics-Cn2g6Jh-.mjs +4 -0
  80. package/dist/packem_shared/prompt-cancelled-BvsNxg_Q.mjs +1 -0
  81. package/dist/packem_shared/render-lunora-error-DUo0pA61.mjs +2 -0
  82. package/dist/packem_shared/resolve-Bdc9KEUv.mjs +5 -0
  83. package/dist/packem_shared/resolve-target-C_ZloTvd.mjs +1 -0
  84. package/dist/packem_shared/runAddCommand-CTblwN9O.mjs +1 -0
  85. package/dist/packem_shared/runDeployCommand-Tgy9tGRV.mjs +1 -0
  86. package/dist/packem_shared/runExportCommand-DiMCQ-Il.mjs +5 -0
  87. package/dist/packem_shared/runMigrateGenerateCommand-Bd2W9t1k.mjs +11 -0
  88. package/dist/packem_shared/schemaIrToSnapshot-BHuNOfgs.mjs +1 -0
  89. package/dist/packem_shared/shared-D-zCOmgY.mjs +1 -0
  90. package/dist/packem_shared/storage-BLLoZRJa.mjs +1 -0
  91. package/dist/packem_shared/tui-prompts-B3YwUhGw.mjs +4 -0
  92. package/dist/packem_shared/variables-CPYyJtsL.mjs +1 -0
  93. package/dist/packem_shared/vectorize-metadata-BVSF8z2h.mjs +2 -0
  94. package/dist/packem_shared/wrangler-name-Dsk5K1f-.mjs +1 -0
  95. package/dist/packem_shared/wrangler-secrets-DlSlWvRH.mjs +1 -0
  96. package/package.json +44 -19
  97. package/skills/README.md +36 -17
  98. package/skills/lunora/SKILL.md +158 -65
  99. package/skills/lunora-cloudflare-audit/SKILL.md +164 -0
  100. package/skills/lunora-create-package/SKILL.md +97 -84
  101. package/skills/lunora-deploy/SKILL.md +178 -105
  102. package/skills/lunora-functions/SKILL.md +367 -60
  103. package/skills/lunora-migration-helper/SKILL.md +168 -137
  104. package/skills/lunora-performance-audit/SKILL.md +137 -95
  105. package/skills/lunora-quickstart/SKILL.md +136 -136
  106. package/skills/lunora-realtime/SKILL.md +217 -97
  107. package/skills/lunora-setup-auth/SKILL.md +203 -101
  108. package/skills/lunora-setup-hyperdrive/SKILL.md +138 -109
  109. package/skills/lunora-setup-hyperdrive-global/SKILL.md +137 -92
  110. package/skills/lunora-setup-mail/SKILL.md +87 -113
  111. package/skills/lunora-setup-scheduler/SKILL.md +133 -97
  112. package/skills/lunora-setup-storage/SKILL.md +189 -95
  113. package/dist/packem_chunks/planDevCommand.mjs +0 -541
  114. package/dist/packem_chunks/runDeployCommand.mjs +0 -594
  115. package/dist/packem_chunks/runMigrateGenerateCommand.mjs +0 -397
  116. package/dist/packem_shared/COMMANDS-B0ftFD_3.mjs +0 -948
  117. package/dist/packem_shared/DEFAULT_IMPORT_BATCH_SIZE-Ck-2bU08.mjs +0 -244
  118. package/dist/packem_shared/admin-url-4UzT-CI4.mjs +0 -19
  119. package/dist/packem_shared/api-spec-CtA6ilu4.mjs +0 -13
  120. package/dist/packem_shared/buildRegistryIndex-BcYe607_.mjs +0 -38
  121. package/dist/packem_shared/codegen-error-DJG-ghs_.mjs +0 -31
  122. package/dist/packem_shared/command-D3lB_4Az.mjs +0 -19
  123. package/dist/packem_shared/commands-B-gR09Z_.mjs +0 -845
  124. package/dist/packem_shared/createLogger-B40gPzQo.mjs +0 -78
  125. package/dist/packem_shared/createRecordingSpawner-DxI3mebw.mjs +0 -43
  126. package/dist/packem_shared/detect-package-manager-DYp7n3mJ.mjs +0 -61
  127. package/dist/packem_shared/diffSnapshots-BeDvvNiF.mjs +0 -161
  128. package/dist/packem_shared/docker-hMQ97KSQ.mjs +0 -21
  129. package/dist/packem_shared/insertSchemaExtension-DAqbfr9Z.mjs +0 -64
  130. package/dist/packem_shared/open-url-Dfq6fAyT.mjs +0 -41
  131. package/dist/packem_shared/output-format-wUvAN6AL.mjs +0 -17
  132. package/dist/packem_shared/parseArgs-YXFuKdEk.mjs +0 -56
  133. package/dist/packem_shared/parseManifest--vZf2FY1.mjs +0 -94
  134. package/dist/packem_shared/prompt-cancelled-APzX1Im-.mjs +0 -9
  135. package/dist/packem_shared/resolve-target-qbsJ_5sF.mjs +0 -16
  136. package/dist/packem_shared/runAddCommand-bnY6-HKb.mjs +0 -4
  137. package/dist/packem_shared/schema-drift-gate-BtBt0as0.mjs +0 -79
  138. package/dist/packem_shared/schemaIrToSnapshot-DdsljJT-.mjs +0 -43
  139. package/dist/packem_shared/storage-BIsph-Vk.mjs +0 -84
  140. package/dist/packem_shared/tui-prompts-BjEN8XgP.mjs +0 -658
  141. package/dist/packem_shared/wrangler-name-cy4yhm9j.mjs +0 -12
  142. package/dist/packem_shared/wrangler-secrets-P2_ZUR-k.mjs +0 -47
package/dist/index.d.mts CHANGED
@@ -1,33 +1,14 @@
1
- import { CodegenOptions, SchemaIR } from '@lunora/codegen';
2
- import '@visulima/cerebro';
3
- import { ensureDevVariables, ensureDevVarsExample, fillDevSecrets, materializeRemoteWranglerConfig } from '@lunora/config';
4
- export { REQUIRED_COMPATIBILITY_DATE, REQUIRED_FLAG, type WranglerProjectValidationOptions as WranglerValidationOptions, type WranglerValidationReport, type WranglerProjectValidationResult as WranglerValidationResult, validateWranglerProject as validateWrangler, validateWranglerConfig } from '@lunora/config';
5
- /** Every command name the CLI registers (drives the `CommandName` type + tests). */
6
- declare const COMMANDS: readonly ["init", "add", "dev", "codegen", "build", "deploy", "containers", "prepare", "link", "deployments", "logs", "run", "insights", "reset", "migrate", "export", "import", "seed", "backup", "verify", "info", "doctor", "env", "analyze", "view", "docs", "registry", "rules"];
7
- type CommandName = (typeof COMMANDS)[number];
8
- declare const VERSION: string;
9
- interface RunCliOptions {
10
- argv?: ReadonlyArray<string>;
11
- cwd?: string;
12
- /**
13
- * Inject a console-like logger so callers (tests) can capture cerebro's
14
- * help / version / usage rendering. Omitted in production, where cerebro
15
- * uses its default stdout/stderr logger.
16
- */
17
- logger?: Console;
18
- }
1
+ export { COMMANDS, type CommandName, type RunCliOptions, VERSION, runCli } from "./cli.mjs";
2
+ import { CodegenOptions, Finding, FieldSnapshot, SchemaIR } from '@lunora/codegen';
3
+ import { CelldToolchainProbeOptions, CelldToolchainProbe, DiscoveryCache, DevProcessSpawner, ensureDevVariables, ensureDevVarsExample, fillDevSecrets, startCelldDevSession, writeCelldDevProjection, LintTool, LintIgnoreOutcome } from '@lunora/config';
4
+ import { materializeDevWranglerConfig, materializeServiceDevConfigs, startLocalHyperdrive, WithheldBinding } from '@lunora/config/cloudflare';
5
+ export { REQUIRED_COMPATIBILITY_DATE, REQUIRED_FLAG, type WranglerProjectValidationOptions as WranglerValidationOptions, type WranglerValidationReport, type WranglerProjectValidationResult as WranglerValidationResult, validateWranglerProject as validateWrangler, validateWranglerConfig } from '@lunora/config/cloudflare';
6
+ import { PackageManager, PackageManagerProbe } from '@lunora/config/cli';
19
7
  /**
20
- * Run the CLI and resolve to the process exit code. cerebro handles help,
21
- * version, usage, and unknown commands (the latter throws, caught here as 1).
22
- * `shouldExitProcess: false` keeps the process alive so callers/tests read the
23
- * captured exit code.
24
- */
25
- declare const runCli: (options?: RunCliOptions) => Promise<number>;
26
- /**
27
- * The `--api-spec` flag's accepted values, mirroring `@lunora/codegen`'s
28
- * `CodegenOptions["apiSpec"]`. `"openapi"` (the default) emits `openapi.json`;
29
- * `"openrpc"` emits `openrpc.json`; `"both"` emits both; `"none"` emits neither.
30
- */
8
+ * The `--api-spec` flag's accepted values, mirroring `@lunora/codegen`'s
9
+ * `CodegenOptions["apiSpec"]`. `"openapi"` (the default) emits `openapi.json`;
10
+ * `"openrpc"` emits `openrpc.json`; `"both"` emits both; `"none"` emits neither.
11
+ */
31
12
  type ApiSpec = NonNullable<CodegenOptions["apiSpec"]>;
32
13
  interface Logger {
33
14
  debug?: (message: string) => void;
@@ -37,11 +18,11 @@ interface Logger {
37
18
  warn: (message: string) => void;
38
19
  }
39
20
  /**
40
- * Narrowed view over the pail instance. `createPail` returns an intersection
41
- * type that includes a constructor signature and `(...args: any[])` logger
42
- * overloads, which the type-aware linter cannot safely resolve. We only ever
43
- * call the level methods with a string, so we describe exactly that surface.
44
- */
21
+ * Narrowed view over the pail instance. `createPail` returns an intersection
22
+ * type that includes a constructor signature and `(...args: any[])` logger
23
+ * overloads, which the type-aware linter cannot safely resolve. We only ever
24
+ * call the level methods with a string, so we describe exactly that surface.
25
+ */
45
26
  interface PailLogger {
46
27
  debug: (message: string) => void;
47
28
  error: (message: string) => void;
@@ -51,59 +32,109 @@ interface PailLogger {
51
32
  }
52
33
  declare const createLogger: () => Logger;
53
34
  /**
54
- * Logger whose every channel writes to `process.stderr`. Used by commands in
55
- * `--format json` mode so all human/progress output stays off stdout — leaving
56
- * stdout for the single JSON document the command prints, so `… --format json`
57
- * stays cleanly pipeable (`| jq`). Each line carries a one-character level tag
58
- * so the stream is still readable when a human watches it.
59
- */
60
- /**
61
- * Direct access to the underlying pail instance for advanced use-cases.
62
- * A Proxy keeps the public `pail` binding lazy: the real pail is only
63
- * constructed on first property access, so importing this module (and thus
64
- * the package barrel) stays side-effect-free.
65
- */
35
+ * Direct access to the underlying pail instance for advanced use-cases.
36
+ * A Proxy keeps the public `pail` binding lazy: the real pail is only
37
+ * constructed on first property access, so importing this module (and thus
38
+ * the package barrel) stays side-effect-free.
39
+ */
66
40
  declare const pail: PailLogger;
67
41
  /**
68
- * Emit a badged step line through the shared pail (the `init` flow's off-TTY
69
- * fallback for the create-astro-style transcript). The `message` may contain
70
- * newlines — `LunoraReporter` indents continuation lines under the badge so a
71
- * dimmed answer sits below its question.
72
- */
42
+ * The two renderings every Lunora command speaks. `pretty` is the human-facing
43
+ * default; `json` puts the command's structured result on stdout as a single
44
+ * JSON document and moves every human line to stderr.
45
+ *
46
+ * Resolved ONCE, by `defineHandler`, from the raw `--format` string — a command
47
+ * body receives this narrowed type and never re-validates it.
48
+ */
49
+ type OutputFormat = "json" | "pretty";
50
+ /**
51
+ * The envelope `--format json` puts on stdout — the same three keys for every
52
+ * command, so a consumer parses one shape and never has to know which command
53
+ * produced it.
54
+ *
55
+ * - `code` is the exit code the process will terminate with.
56
+ * - `data` is the command's own payload, and is absent when the run produced
57
+ * none — which is what a failure before any work looks like.
58
+ * - `error` is the single-line reason for a non-zero `code`. It is the half that
59
+ * makes a FAILURE machine-readable: before the envelope, a failed command wrote
60
+ * nothing at all to stdout and the reason could only be scraped out of English
61
+ * prose on stderr.
62
+ *
63
+ * `defineHandler` serializes exactly these keys, once, after the body returns —
64
+ * so a body may return a richer result for its in-process callers without
65
+ * widening the document, and a failure gets one for free.
66
+ */
67
+ interface CommandResult<TData> {
68
+ /** Process exit code — one of `EXIT_CODE`. */
69
+ code: number;
70
+ /** The command's structured payload. Absent when the run produced none. */
71
+ data?: TData;
72
+ /**
73
+ * Set by a command that forwards `--format json` to a child process which
74
+ * writes the document itself (`wrangler … --json`, `wrangler tail`). The
75
+ * envelope is suppressed for that run: stdout already carries exactly one
76
+ * document, and appending a second would make the stream unparseable.
77
+ */
78
+ delegated?: boolean;
79
+ /** Why the run failed. Set whenever `code` is non-zero and a reason is known. */
80
+ error?: string;
81
+ }
73
82
  interface CodegenCommandOptions {
74
83
  /** Which API spec(s) to emit. Defaults to codegen's `"openapi"` when omitted. */
75
84
  apiSpec?: ApiSpec;
76
85
  cwd?: string;
77
86
  /** Output format: `pretty` (default) or `json`. */
78
- format?: string;
87
+ format?: OutputFormat;
88
+ /** Opt into per-module lazy function loading; also enabled by LUNORA_LAZY_FUNCTIONS. */
89
+ lazyFunctions?: boolean;
79
90
  logger: Logger;
91
+ /**
92
+ * Fail the run when any ERROR-level advisory is reported. Defaults to CI
93
+ * detection so a local `lunora codegen` stays advisory while a pipeline
94
+ * gates on it; `--no-strict-advisories` forces it off either way.
95
+ */
96
+ strictAdvisories?: boolean;
97
+ /** Deploy target the emitted `ctx.*` surface is tailored to. Resolved by the caller; falls back to `"target"` in `lunora.config.*`, then `"cloudflare"`. */
98
+ target?: string;
80
99
  }
81
- interface CodegenCommandResult {
100
+ /** The `--format json` payload: what codegen wrote, and what it has to say about it. */
101
+ interface CodegenCommandData {
82
102
  advisories: ReadonlyArray<{
83
103
  detail: string;
84
- level: string;
104
+ level: Finding["level"];
85
105
  name: string;
86
106
  remediation: string;
87
107
  }>;
88
108
  cronTriggers: ReadonlyArray<string>;
89
- /** Set when the run aborted on an invalid `--format` before codegen ran. */
90
- error?: string;
109
+ /** ERROR-level advisories that made the run fail, when strict mode is on. */
110
+ failedAdvisories: number;
91
111
  outputDirectory: string;
92
112
  }
113
+ interface CodegenCommandResult extends CodegenCommandData {
114
+ /**
115
+ * Exit code, when the run resolved one itself. Only a USAGE refusal does —
116
+ * every other outcome is classified from `error`/`failedAdvisories` by
117
+ * `execute`, which cannot tell a bad `--format` (the invocation is wrong,
118
+ * exit 2) from a failed codegen (exit 1) after the fact.
119
+ */
120
+ code?: number;
121
+ /** Set when the run failed: an unregistered target, or an error-level platform diagnostic. */
122
+ error?: string;
123
+ }
93
124
  declare const runCodegenCommand: (options: CodegenCommandOptions) => CodegenCommandResult;
94
- /** `lunora codegen` handler (lazy-loaded via the command's `loader`). */
95
- /** Rows per HTTP request when importing. Convex uses ~500; same here. */
96
- declare const DEFAULT_IMPORT_BATCH_SIZE = 500;
97
125
  /**
98
- * Minimal projection of `globalThis.fetch` for the export path — we need
99
- * `body` as a stream-iterable, which the shared {@link FetchLike} type
100
- * intentionally hides for the JSON-only commands.
101
- */
126
+ * Minimal projection of `globalThis.fetch` for the transfer commands: `body` is
127
+ * exposed as a stream-iterable (the export path pipes it) and accepts bytes (the
128
+ * blob path uploads them). The JSON-only commands use the narrower `FetchLike`
129
+ * in `../run/handler` instead.
130
+ */
102
131
  type StreamingFetchLike = (input: string, init?: {
103
- body?: string;
132
+ body?: string | Uint8Array;
104
133
  headers?: Record<string, string>;
105
134
  method?: string;
106
135
  }) => Promise<{
136
+ /** Optional: only the storage transfer reads raw bytes, and only real `fetch` needs to supply it. */
137
+ arrayBuffer?: () => Promise<ArrayBuffer>;
107
138
  body: ReadableStream<Uint8Array> | null;
108
139
  json: () => Promise<unknown>;
109
140
  ok: boolean;
@@ -113,6 +144,12 @@ type StreamingFetchLike = (input: string, init?: {
113
144
  interface ExportCommandOptions {
114
145
  cwd?: string;
115
146
  fetchImpl?: StreamingFetchLike;
147
+ /**
148
+ * Output format: `pretty` (default) or `json`. `json` reports the run as a
149
+ * single document and therefore requires a file destination — with `--out -`
150
+ * (or none) stdout already carries the NDJSON stream.
151
+ */
152
+ format?: OutputFormat;
116
153
  logger: Logger;
117
154
  /** Output file path; `undefined`/`-` streams to stdout. */
118
155
  out?: string;
@@ -125,18 +162,97 @@ interface ExportCommandOptions {
125
162
  /** Worker URL (default `http://localhost:8787`). */
126
163
  url?: string;
127
164
  }
128
- interface ExportCommandResult {
165
+ /** The `--format json` payload: what was dumped, from which tables, and where to. */
166
+ interface ExportCommandData {
167
+ bytes: number;
168
+ /** The file the dump landed in. */
169
+ out: string;
170
+ rows: number;
171
+ /** The table allowlist, omitted when the export covered every table. */
172
+ tables?: string[];
173
+ }
174
+ interface ExportCommandResult extends CommandResult<ExportCommandData> {
129
175
  bytes: number;
130
- code: number;
131
176
  /** Number of NDJSON lines streamed (0 on error). */
132
177
  rows: number;
133
178
  }
134
179
  /**
135
- * Stream an export. The worker emits NDJSON; we count newlines as we go and
136
- * pipe straight to the output sink, so a 10M-row export doesn't materialise
137
- * the body in memory.
138
- */
180
+ * Stream an export. The worker emits NDJSON; we count newlines as we go and
181
+ * pipe straight to the output sink, so a 10M-row export doesn't materialise
182
+ * the body in memory.
183
+ */
139
184
  declare const runExportCommand: (options: ExportCommandOptions) => Promise<ExportCommandResult>;
185
+ /** One row-scoped failure as the admin import endpoint reports it. */
186
+ interface ImportRowError {
187
+ code: string;
188
+ line: number;
189
+ message: string;
190
+ table: string;
191
+ }
192
+ /**
193
+ * One SHARD the fan-out never reached, as the admin import endpoint reports it.
194
+ *
195
+ * Distinct from {@link ImportRowError}: the rows a dead shard owned contribute
196
+ * to neither `inserted` nor `errors`, so an unknown slice of the batch is simply
197
+ * missing. The endpoint answers 207 Multi-Status when this array is non-empty.
198
+ */
199
+ interface ImportShardFailure {
200
+ message: string;
201
+ shardKey: string;
202
+ timedOut: boolean;
203
+ }
204
+ /**
205
+ * The sources `--from` accepts.
206
+ *
207
+ * Only the two that cannot be detected. A Convex snapshot announces itself (a
208
+ * directory of `<table>/documents.jsonl`, or a `.zip` of one) and anything else
209
+ * is NDJSON, so naming those would advertise a control this does not implement:
210
+ * `--from ndjson` against a Convex export would have to either refuse it or
211
+ * silently import it as Convex, and the second is what an unhonoured flag
212
+ * actually did.
213
+ */
214
+ declare const IMPORT_SOURCE_NAMES: readonly ["firebase", "supabase"];
215
+ type ImportSourceName = (typeof IMPORT_SOURCE_NAMES)[number];
216
+ /**
217
+ * The storage-reference rewrite: turning a Convex storage id into the
218
+ * content-hash R2 key its blob was migrated to.
219
+ *
220
+ * Split out of `./storage-mapping` (which owns the mapping *file*) because it
221
+ * has two callers that must never diverge — the import rewrite and `--scan`,
222
+ * which runs this same walk as a dry run to propose the mapping. A detector
223
+ * that proposed columns the rewrite would not touch, or missed ones it would,
224
+ * is worse than no detector.
225
+ */
226
+ /** One reference the walk could not rewrite, with where it was found. */
227
+ interface UnresolvedStorageReference {
228
+ column: string;
229
+ storageId: string;
230
+ table: string;
231
+ }
232
+ /**
233
+ * What a run's storage references resolved to. The two failure buckets are
234
+ * deliberately separate, because they are not the same problem and do not have
235
+ * the same remedy:
236
+ *
237
+ * `unmigrated` is a reference to a blob that does not exist — the export omitted
238
+ * it, or `--include-file-storage` was not passed. Nothing the operator writes in
239
+ * a mapping file can fix it, and the data is broken after import, so it fails
240
+ * `--verify`.
241
+ *
242
+ * `ambiguous` is a string that exactly matches a blob that *did* migrate, sitting
243
+ * in a column the mapping does not name. It may be a storage reference the
244
+ * mapping forgot, or it may be user text that happens to equal an id. Failing the
245
+ * run on a coincidence is not defensible, so it warns and names the column the
246
+ * operator would add to resolve it.
247
+ */
248
+ interface StorageRemapReport {
249
+ ambiguous: UnresolvedStorageReference[];
250
+ /** Number of references rewritten to a content-hash key. */
251
+ rewritten: number;
252
+ unmigrated: UnresolvedStorageReference[];
253
+ }
254
+ /** Rows per HTTP request when importing. Convex uses ~500; same here. */
255
+ declare const DEFAULT_IMPORT_BATCH_SIZE = 500;
140
256
  interface ImportCommandOptions {
141
257
  /** Rows per HTTP request. Defaults to {@link DEFAULT_IMPORT_BATCH_SIZE}. */
142
258
  batchSize?: number;
@@ -144,84 +260,237 @@ interface ImportCommandOptions {
144
260
  fetchImpl?: StreamingFetchLike;
145
261
  /** Source NDJSON file. Required. */
146
262
  file: string;
263
+ /** Output format: `pretty` (default) or `json`. */
264
+ format?: OutputFormat;
265
+ /**
266
+ * Which reader to use. Omit to auto-detect between a Convex export snapshot
267
+ * and a plain NDJSON file; `supabase`/`firebase` must be explicit, because a
268
+ * directory of CSV or JSON has no signature that distinguishes it from
269
+ * anything else a user might point at.
270
+ */
271
+ from?: ImportSourceName;
147
272
  logger: Logger;
148
273
  prod?: boolean;
149
274
  /**
150
- * Wrap each line as `{table:&lt;name>,doc:&lt;line>}`. Use when the source NDJSON
151
- * is bare docs from a single table — Convex's `convex import --table users`
152
- * shape.
153
- */
275
+ * Overwrite rows whose `_id` already exists in the target instead of
276
+ * reporting them as conflicts (`?onConflict=replace`).
277
+ */
278
+ replace?: boolean;
279
+ /**
280
+ * Scan the export for columns holding `_storage` ids and write a candidate
281
+ * `lunora/import-convex.json`. Scan-only: nothing is imported.
282
+ */
283
+ scan?: boolean;
284
+ /**
285
+ * Local directory of storage objects to migrate alongside the rows — how
286
+ * Firebase Cloud Storage arrives, after `gcloud storage cp -r`.
287
+ */
288
+ storageDir?: string;
289
+ /**
290
+ * Wrap each line as `{table:<name>,doc:<line>}`. Use when the source NDJSON
291
+ * is bare docs from a single table — Convex's `convex import --table users`
292
+ * shape.
293
+ */
154
294
  table?: string;
155
295
  token?: string;
156
296
  url?: string;
297
+ /**
298
+ * Verify per-table row parity + dangling-storage after import. Exits non-zero
299
+ * when a table's inserted count differs from its source line count, or when a
300
+ * document references a storage id that was not migrated.
301
+ */
302
+ verify?: boolean;
303
+ /**
304
+ * Also migrate Convex `_storage` blobs: read `_storage/documents.jsonl`, upload
305
+ * each blob with sha256+size verification, and build the `storageId → key` map.
306
+ * Off by default so the plain-document import path is unchanged.
307
+ */
308
+ withStorage?: boolean;
309
+ /** Confirm bulk-writing production. Required alongside `--prod`. */
310
+ yes?: boolean;
157
311
  }
158
- interface ImportCommandResult {
159
- body: unknown;
160
- code: number;
312
+ /**
313
+ * The JSON summary a run prints and returns — the same object either way, so a
314
+ * caller reading `body.conflicts` does not have to cast its way there.
315
+ *
316
+ * `undefined` on every path that imports nothing: a rejected source, a failed
317
+ * storage phase, or `--scan` (whose product is the mapping file it writes, not
318
+ * a return value).
319
+ */
320
+ interface ImportSummary {
321
+ conflicts: number;
322
+ errors: ImportRowError[];
323
+ /** Shards the endpoint could not reach (it answered 207). Their rows are MISSING, not rejected — present only when non-empty. */
324
+ failed?: ImportShardFailure[];
325
+ inserted: Record<string, number>;
326
+ received: number;
327
+ /** Existing rows overwritten under `--replace`. */
328
+ replaced: number;
329
+ storage?: {
330
+ /** Up to {@link UNRESOLVED_REPORT_LIMIT} distinct references — a sample, not the whole set. See `ambiguousTotal`. */
331
+ ambiguous: StorageRemapReport["ambiguous"];
332
+ /** How many DISTINCT `(table, column, storageId)` references were ambiguous. */
333
+ ambiguousTotal: number;
334
+ blobs: number;
335
+ rewritten: number;
336
+ /** Up to {@link UNRESOLVED_REPORT_LIMIT} distinct references — a sample, not the whole set. See `unmigratedTotal`. */
337
+ unmigrated: StorageRemapReport["unmigrated"];
338
+ /** How many DISTINCT `(table, column, storageId)` references resolved to no migrated blob. */
339
+ unmigratedTotal: number;
340
+ };
341
+ warnings?: string[];
342
+ }
343
+ /** The `--format json` payload: which file went in, and what the endpoint made of it. */
344
+ interface ImportCommandData {
345
+ file: string;
346
+ inserted: number;
347
+ /** The batcher's own roll-up: inserted-per-table, conflicts, row errors, unreached shards. */
348
+ summary: ImportSummary;
349
+ }
350
+ interface ImportCommandResult extends CommandResult<ImportCommandData> {
351
+ body: ImportSummary | undefined;
161
352
  /** Total inserted rows across batches. */
162
353
  inserted: number;
354
+ /** Existing rows overwritten under `--replace`; absent when the run wrote nothing. */
355
+ replaced?: number;
163
356
  }
164
- /**
165
- * Stream an NDJSON file in chunks, POSTing each batch to
166
- * `/_lunora/admin/import`. We keep the line buffer bounded by `batchSize` so a
167
- * multi-GiB file imports without buffering everything in memory.
168
- */
169
357
  declare const runImportCommand: (options: ImportCommandOptions) => Promise<ImportCommandResult>;
170
358
  /**
171
- * Injectable probe for a Docker-compatible container engine. Tests pass a
172
- * stub; production uses {@link isDockerAvailable}.
173
- */
359
+ * Every exit code `lunora` can terminate with. Stable — a value never changes
360
+ * meaning, and a new bucket takes the next free number.
361
+ */
362
+ declare const EXIT_CODE: {
363
+ /** The command did what was asked. */
364
+ readonly SUCCESS: 0;
365
+ /** A failure that fits none of the narrower buckets. */
366
+ readonly FAILURE: 1;
367
+ /** Bad usage, bad input, or a validation failure — the invocation itself, or the project source it read, is wrong. */
368
+ readonly USAGE: 2;
369
+ /** Not authenticated: no credential, or an expired one. */
370
+ readonly AUTH: 3;
371
+ /** Authenticated, but not allowed to do this. */
372
+ readonly PERMISSION: 4;
373
+ /** The named thing does not exist. */
374
+ readonly NOT_FOUND: 5;
375
+ /** The write lost a race, or the name is already taken. */
376
+ readonly CONFLICT: 6;
377
+ /** Rate limited — back off and retry. */
378
+ readonly RATE_LIMITED: 7;
379
+ /** The far side is unavailable or timed out. Retryable. */
380
+ readonly UNAVAILABLE: 8;
381
+ /** A local tool the command shells out to (wrangler, git, docker, …) is missing, or not running. */
382
+ readonly MISSING_DEPENDENCY: 9;
383
+ /** Interactive cancel — the POSIX `128 + SIGINT` convention. */
384
+ readonly CANCELLED: 130;
385
+ };
386
+ /** One of {@link EXIT_CODE}'s values. */
387
+ type ExitCode = (typeof EXIT_CODE)[keyof typeof EXIT_CODE];
388
+ /** The exit code for a transport status; `undefined` and anything unmapped are a general failure. */
389
+ declare const exitCodeForStatus: (status: number | undefined) => ExitCode;
390
+ /**
391
+ * The exit code for a Lunora error `code`, resolved through the catalog. An
392
+ * unregistered code has no status to derive from, so it is a general failure.
393
+ */
394
+ declare const exitCodeForCode: (code: string) => ExitCode;
395
+ /**
396
+ * The exit code for a thrown value. A Lunora error is classified by its `code`
397
+ * (override table first) and then by the `status` the instance carries — which
398
+ * is the catalog's, unless the throw site passed a more specific one (the
399
+ * upstream-API codes do). Anything else is a general failure.
400
+ */
401
+ declare const exitCodeForError: (error: unknown) => ExitCode;
402
+ /**
403
+ * Injectable probe for a Docker-compatible container engine. Tests pass a
404
+ * stub; production uses {@link isDockerAvailable}.
405
+ */
174
406
  type DockerProbe = () => boolean;
175
407
  /**
176
- * True when a Docker-compatible engine answers `docker info` — the same
177
- * prerequisite `wrangler deploy` has for building and pushing a container
178
- * image from a local Dockerfile. Quiet by design (output discarded): callers
179
- * own the messaging.
180
- */
408
+ * The shared `/_lunora/health` probe used by `lunora verify --health-url` and
409
+ * `lunora deploy --health-check`.
410
+ *
411
+ * Both commands ask the same question — "does this deployment answer?" — so
412
+ * they ask it through one implementation with one error-message shape. The
413
+ * runtime auto-registers both routes (`packages/runtime/src/health-routes.ts`):
414
+ * `/_lunora/health/ready` is the readiness gate ("can this version serve"), and
415
+ * `/_lunora/health` is the aggregate that also exists on older deployments.
416
+ *
417
+ * The probe is transport-only: it never throws, and reports its verdict as an
418
+ * `{ error }` message the caller decides what to do with.
419
+ */
420
+ /**
421
+ * Minimal fetch surface the probe needs — a subset of the global `fetch`,
422
+ * injectable so a test can feed a canned response without a network.
423
+ */
424
+ type HealthFetch = (url: string) => Promise<{
425
+ ok: boolean;
426
+ status: number;
427
+ }>;
181
428
  interface SpawnDescriptor {
182
429
  args: ReadonlyArray<string>;
183
430
  /**
184
- * Capture the child's stdout (in addition to streaming it to the parent), so
185
- * the caller can parse it — used by `deploy` to read the deployed URL from
186
- * `wrangler deploy` output. Each chunk is still teed to the parent's stdout
187
- * so the user sees live progress. Mutually exclusive with `stdoutToStderr`.
188
- */
431
+ * Capture the child's stderr (in addition to streaming it to the parent).
432
+ * Needed when a tool reports the *expected* outcome as an error there —
433
+ * `wrangler vectorize create-metadata-index` writes "already exists" to
434
+ * stderr, and without this the caller can only see a bare exit code and
435
+ * would warn on every re-run. Composes with `stdoutToStderr`, so a caller
436
+ * can keep stdout clean for `--format json` and still read the reason.
437
+ */
438
+ captureStderr?: boolean;
439
+ /**
440
+ * Capture the child's stdout (in addition to streaming it to the parent), so
441
+ * the caller can parse it — used by `deploy` to read the deployed URL from
442
+ * `wrangler deploy` output. Each chunk is still teed to the parent's stdout
443
+ * so the user sees live progress. Mutually exclusive with `stdoutToStderr`
444
+ * and `captureStdoutSilently`.
445
+ */
189
446
  captureStdout?: boolean;
447
+ /**
448
+ * Capture the child's stdout WITHOUT teeing it to the parent's stdout —
449
+ * for output that is parsed, never displayed (e.g. `wrangler secret list
450
+ * --format json`). Unlike `captureStdout`, nothing is written to
451
+ * `process.stdout`, so it can't interleave with — and corrupt — a
452
+ * caller's own stdout (notably `lunora deploy --format json`, which must
453
+ * emit exactly one JSON document). Mutually exclusive with `captureStdout`
454
+ * and `stdoutToStderr`.
455
+ */
456
+ captureStdoutSilently?: boolean;
190
457
  command: string;
191
458
  cwd?: string;
192
459
  env?: Readonly<Record<string, string>>;
193
460
  /**
194
- * Pipe this string into the child's stdin and close it. Used to feed
195
- * `wrangler secret put` its value without exposing it on the command
196
- * line or in env. When absent, stdin is inherited from the parent.
197
- */
461
+ * Pipe this string into the child's stdin and close it. Used to feed
462
+ * `wrangler secret put` its value without exposing it on the command
463
+ * line or in env. When absent, stdin is inherited from the parent.
464
+ */
198
465
  input?: string;
199
466
  /**
200
- * Route the child's stdout to the parent's STDERR instead of stdout. Set in
201
- * `--format json` mode so a spawned tool's human output (e.g. `wrangler
202
- * deploy`'s progress + the deployed URL) can't interleave with — and corrupt
203
- * — the single JSON document the command prints to stdout.
204
- */
467
+ * Route the child's stdout to the parent's STDERR instead of stdout. Set in
468
+ * `--format json` mode so a spawned tool's human output (e.g. `wrangler
469
+ * deploy`'s progress + the deployed URL) can't interleave with — and corrupt
470
+ * — the single JSON document the command prints to stdout.
471
+ */
205
472
  stdoutToStderr?: boolean;
206
473
  }
207
474
  interface SpawnResult {
208
475
  code: number;
209
- /** The captured stdout, present only when the descriptor set `captureStdout`. */
476
+ /** The captured stderr, present only when the descriptor set `captureStderr`. */
477
+ stderr?: string;
478
+ /** The captured stdout, present only when the descriptor set `captureStdout` or `captureStdoutSilently`. */
210
479
  stdout?: string;
211
480
  }
212
481
  /**
213
- * Injectable spawner. Tests pass a stub that just records the descriptor
214
- * instead of executing a real subprocess.
215
- */
482
+ * Injectable spawner. Tests pass a stub that just records the descriptor
483
+ * instead of executing a real subprocess.
484
+ */
216
485
  type Spawner = (descriptor: SpawnDescriptor) => Promise<SpawnResult>;
217
486
  declare const defaultSpawner: Spawner;
218
487
  interface RecordedSpawn {
219
488
  descriptor: SpawnDescriptor;
220
489
  }
221
490
  /**
222
- * Test helper: returns a spawner that records every invocation and resolves
223
- * with the configured exit code.
224
- */
491
+ * Test helper: returns a spawner that records every invocation and resolves
492
+ * with the configured exit code.
493
+ */
225
494
  declare const createRecordingSpawner: (exitCode?: number) => {
226
495
  calls: RecordedSpawn[];
227
496
  spawner: Spawner;
@@ -239,6 +508,8 @@ interface ListRemoteSecretsInputs {
239
508
  env?: string;
240
509
  /** Injected command runner; defaults to a real `wrangler secret list`. */
241
510
  runner?: SecretListRunner;
511
+ /** The deploy target the caller resolved (`--target`, else the config's). Defaults to the config's. */
512
+ target?: string;
242
513
  /** Target a temporary-account deployment (`--temporary`). */
243
514
  temporary?: boolean;
244
515
  }
@@ -250,11 +521,6 @@ interface ListRemoteSecretsResult {
250
521
  /** False when wrangler failed or its output could not be parsed. */
251
522
  ok: boolean;
252
523
  }
253
- /**
254
- * Parse `wrangler secret list --format json` output into a sorted name list.
255
- * The payload is an array of `{ name, type }`; anything else yields `undefined`
256
- * so the caller can report a parse failure rather than silently returning [].
257
- */
258
524
  type FetchLike = (input: string, init?: {
259
525
  body?: string;
260
526
  headers?: Record<string, string>;
@@ -267,83 +533,149 @@ type FetchLike = (input: string, init?: {
267
533
  }>;
268
534
  interface RunCommandOptions {
269
535
  args?: string;
536
+ /** Forge this user id for the call (dispatches through the admin-gated `runAs` op). */
537
+ as?: string;
538
+ /** JSON-encoded extra identity claims to accompany {@link RunCommandOptions.as}. */
539
+ claims?: string;
270
540
  cwd?: string;
271
541
  fetchImpl?: FetchLike;
542
+ /** Output format: `pretty` (default) or `json`. */
543
+ format?: OutputFormat;
272
544
  functionPath: string;
273
545
  logger: Logger;
274
546
  shard?: string;
547
+ /** Admin bearer for the `runAs` dispatch; resolved from the environment / `.dev.vars` when absent. */
548
+ token?: string;
275
549
  url?: string;
276
550
  }
277
551
  interface RunCommandResult {
278
552
  body: unknown;
279
553
  code: number;
554
+ /** Why the call failed before (or at) the RPC, for the `--format json` envelope. */
555
+ error?: string;
280
556
  requestUrl: string;
281
557
  }
282
558
  declare const runRpcCommand: (options: RunCommandOptions) => Promise<RunCommandResult>;
283
- /** `lunora run &lt;functionPath>` handler (lazy-loaded via the command's `loader`). */
284
559
  interface DeployCommandOptions {
560
+ /** Deploy even though the app enables the open-shard option (the `open_shard_access` gate). */
561
+ allowOpenShards?: boolean;
285
562
  /** Override the schema-drift gate — deploy even with breaking drift and no new migration. */
286
563
  allowSchemaDrift?: boolean;
287
564
  /** Which API spec(s) codegen emits. Defaults to codegen's `"openapi"` when omitted. */
288
565
  apiSpec?: ApiSpec;
566
+ /** The Vite metafile path this run's client build keeps for `lunora build`'s copy; unset, the build's metafile is discarded. */
567
+ bundleMetaPath?: string;
568
+ /** The celld toolchain check a celld deploy runs before codegen; injected in tests. Defaults to `probeCelldToolchain`. */
569
+ celldToolchain?: (options: CelldToolchainProbeOptions) => Promise<CelldToolchainProbe>;
570
+ /**
571
+ * The `--env` this run's client build was given as `CLOUDFLARE_ENV`. Set only when a client build ran, so the generated config
572
+ * it wrote is for that environment; without it the environment's Hyperdrive id is not written into that config.
573
+ */
574
+ clientBuildEnvironment?: string;
575
+ /**
576
+ * Set when the caller's stdout must stay a single JSON document but `format` is
577
+ * not `"json"`. `lunora build` sets it, since it hands deploy `format: undefined`.
578
+ */
579
+ clientBuildOutputJson?: boolean;
580
+ /** Set when this run's client build ran, so the spec it recorded is the one to emit. */
581
+ clientBuildRan?: boolean;
582
+ /**
583
+ * The command the operator actually ran. `build` delegates here with
584
+ * `dryRun: true`; without this the gate names the wrong command in its
585
+ * blocked message and offers flags the real caller does not accept.
586
+ */
587
+ commandName?: PreDeployCommand;
289
588
  cwd?: string;
290
589
  /** Docker-availability probe injected in tests. Defaults to a real `docker info` check. */
590
+ /** Memoises project discovery for this invocation; `executeDeploy` creates one, and codegen clears it. */
591
+ discoveryCache?: DiscoveryCache;
291
592
  dockerAvailable?: DockerProbe;
292
593
  /**
293
- * Validate, bundle, and run all pre-deploy gates without publishing
294
- * (`wrangler deploy --dry-run`). Post-deploy steps (data migrations, schema
295
- * baseline re-bless) are skipped since nothing shipped.
296
- */
594
+ * Validate, bundle, and run all pre-deploy gates without publishing
595
+ * (`wrangler deploy --dry-run`). Post-deploy steps (data migrations, schema
596
+ * baseline re-bless) are skipped since nothing shipped.
597
+ */
297
598
  dryRun?: boolean;
599
+ /**
600
+ * Write the binding manifest (`build --emit-bindings`) to this path once the
601
+ * bundle exists. Owned here rather than by the caller because it is the last
602
+ * artifact that has to read the PROVISIONED `wrangler.jsonc`, and the dry-run
603
+ * rollback below closes that window as soon as this function returns.
604
+ * Relative paths resolve against the project root.
605
+ */
606
+ emitBindings?: string;
298
607
  env?: string;
299
608
  /** Fetch implementation injected in tests for `--migrate` RPC calls. */
300
609
  fetchImpl?: FetchLike;
301
610
  /** Output format: `pretty` (default) or `json`. */
302
- format?: string;
611
+ format?: OutputFormat;
612
+ /**
613
+ * `false` (`--no-framework-build`) skips the vite/rsbuild client build that
614
+ * runs before wrangler when wrangler reads its output. `--prebuilt` skips it
615
+ * too: that artifact was built earlier.
616
+ */
617
+ frameworkBuild?: boolean;
618
+ /**
619
+ * After a successful live deploy, probe the new version's health route
620
+ * (`/_lunora/health/ready`, falling back to `/_lunora/health`) and fail the
621
+ * command when it never answers. Opt-in, not default-on: a worker whose
622
+ * health route is admin-gated or unreachable from CI must still be
623
+ * deployable, and a default network step would turn a successful deploy
624
+ * into a red build for an unrelated reason.
625
+ */
626
+ healthCheck?: boolean;
627
+ /** Injectable fetch for `--health-check`; defaults to the global `fetch`. */
628
+ healthFetch?: HealthFetch;
629
+ /** Injectable inter-attempt delay for `--health-check`; injected in tests to skip the real wait. */
630
+ healthSleep?: (ms: number) => Promise<void>;
303
631
  /** Set to `false` to disable interactive spinners (test injection). */
304
632
  interactive?: boolean;
633
+ /** Opt into per-module lazy function imports. */
634
+ lazyFunctions?: boolean;
305
635
  logger: Logger;
306
636
  /**
307
- * When true, after a successful `wrangler deploy`, discover and run all
308
- * pending data migrations via the worker's `/_lunora/migrate` admin RPC.
309
- * The worker must be live (exit 0) before migrations are attempted.
310
- *
311
- * Implementation note: the status RPC returns the full shard-level
312
- * migration state, but there is no single authoritative "list of pending
313
- * migration ids" that can be read client-side before running the worker.
314
- * Instead, `--migrate` runs `migrate status` followed by `migrate up` for
315
- * each migration id discovered locally via `discoverMigrations`. The
316
- * worker's `MigrationRunner` is idempotent — running `up` on an already-
317
- * applied migration is a no-op — so this approach is safe.
318
- */
637
+ * When true, after a successful `wrangler deploy`, discover and run all
638
+ * pending data migrations via the worker's `/_lunora/migrate` admin RPC.
639
+ * The worker must be live (exit 0) before migrations are attempted.
640
+ *
641
+ * Implementation note: the status RPC returns the full shard-level
642
+ * migration state, but there is no single authoritative "list of pending
643
+ * migration ids" that can be read client-side before running the worker.
644
+ * Instead, `--migrate` runs `migrate status` followed by `migrate up` for
645
+ * each migration id discovered locally via `discoverMigrations`. The
646
+ * worker's `MigrationRunner` is idempotent — running `up` on an already-
647
+ * applied migration is a no-op — so this approach is safe.
648
+ */
319
649
  migrate?: boolean;
320
650
  /** Admin bearer token for `--migrate` (falls back to `LUNORA_ADMIN_TOKEN`). */
321
651
  migrateToken?: string;
322
652
  /**
323
- * Worker URL for `--migrate`. REQUIRED when `--migrate` is set — the deploy
324
- * handler never captures the URL `wrangler deploy` published to, so there is
325
- * no safe default; omitting it would silently target `http://localhost:8787`
326
- * (the dev worker), applying the migration to local state instead of prod.
327
- */
653
+ * Worker URL for `--migrate`. REQUIRED when `--migrate` is set — the deploy
654
+ * handler never captures the URL `wrangler deploy` published to, so there is
655
+ * no safe default; omitting it would silently target `http://localhost:8787`
656
+ * (the dev worker), applying the migration to local state instead of prod.
657
+ */
328
658
  migrateUrl?: string;
329
659
  /**
330
- * Confirm a production data migration triggered via `--migrate` (the
331
- * `migrate up --prod` confirmation the standalone command requires). Without
332
- * it a `--migrate --migrate-url &lt;prod>` deploy refuses to run the migration.
333
- */
660
+ * Confirm a production data migration triggered via `--migrate` (the
661
+ * `migrate up --prod` confirmation the standalone command requires). Without
662
+ * it a `--migrate --migrate-url <prod>` deploy refuses to run the migration.
663
+ */
334
664
  migrateYes?: boolean;
665
+ /** Set once the open-shard gate has run for this deploy, so the pipeline does not run it again. */
666
+ openShardGatePassed?: boolean;
335
667
  /**
336
- * Emit the bundled worker to this directory via `wrangler deploy --outdir`
337
- * (paired with `dryRun` by `lunora build`). Also writes esbuild metadata to
338
- * `&lt;outDir>/bundle-meta.json`. When unset, no artifact is written.
339
- */
668
+ * Emit the bundled worker to this directory via `wrangler deploy --outdir`
669
+ * (paired with `dryRun` by `lunora build`). Also writes esbuild metadata to
670
+ * `<outDir>/bundle-meta.json`. When unset, no artifact is written.
671
+ */
340
672
  outDir?: string;
341
673
  /**
342
- * Upload a preview version (`wrangler versions upload`) instead of a live
343
- * `wrangler deploy`. Codegen + the drift gate + validation still run, but
344
- * the post-deploy finalize (migrations, baseline re-bless, auto-link, the
345
- * production summary) is skipped — a preview never shifts live traffic.
346
- */
674
+ * Upload a preview version (`wrangler versions upload`) instead of a live
675
+ * `wrangler deploy`. Codegen + the drift gate + validation still run, but
676
+ * the post-deploy finalize (migrations, baseline re-bless, auto-link, the
677
+ * production summary) is skipped — a preview never shifts live traffic.
678
+ */
347
679
  preview?: boolean;
348
680
  /** Railpack-availability probe injected in tests. Defaults to a real `railpack --version` + `BUILDKIT_HOST` check. */
349
681
  railpackAvailable?: DockerProbe;
@@ -352,24 +684,106 @@ interface DeployCommandOptions {
352
684
  /** Remote-secret lister for the missing-secret offer; injected in tests. Defaults to `wrangler secret list`. */
353
685
  secretLister?: (inputs: ListRemoteSecretsInputs) => Promise<ListRemoteSecretsResult>;
354
686
  skipCodegen?: boolean;
687
+ /** Deploy only the app, leaving the `lunora.config` services it binds as they are (`--skip-services`). */
688
+ skipServices?: boolean;
689
+ /**
690
+ * Starts the smoke check's `wrangler dev`. Unset, the check launches a real server; a caller that must
691
+ * not start one (a test, or an embedding that stubs subprocesses) passes its own launcher.
692
+ */
693
+ smokeLauncher?: DevProcessSpawner;
694
+ /**
695
+ * Evaluate every lazy function module in workerd before shipping, so a module that throws on
696
+ * load fails the deploy instead of its first caller. Nothing to check for an eager
697
+ * registry; `false` (`--no-smoke-load`) skips it. Default on.
698
+ */
699
+ smokeLoad?: boolean;
355
700
  spawner?: Spawner;
356
701
  /**
357
- * Deploy to a temporary Cloudflare account (`wrangler deploy --temporary`).
358
- * For unauthenticated use only: wrangler provisions a short-lived account +
359
- * token, deploys, and prints a claim URL; the deployment stays live ~60
360
- * minutes before the unclaimed account is deleted. Wrangler itself errors
361
- * if credentials are already present (OAuth / `CLOUDFLARE_API_TOKEN` /
362
- * global API key), so we pass the flag straight through without guarding.
363
- */
702
+ * Fail the deploy when codegen reports an ERROR-level advisory. Same
703
+ * option `lunora codegen` exposes as `--no-strict-advisories`; defaults to
704
+ * CI detection (on in CI, off locally) so a legitimately-partial target
705
+ * can still be shipped interactively. Does NOT gate platform diagnostics
706
+ * (`platform_unsupported_feature` / `platform_unknown_target`), which
707
+ * always block — those mean the emitted `ctx.*` surface does not match
708
+ * what the target can serve, not merely a style nit.
709
+ */
710
+ strictAdvisories?: boolean;
711
+ /**
712
+ * Deploy target. Falls back to `"target"` in `lunora.config.*`, then
713
+ * `"cloudflare"`, which selects the wrangler
714
+ * toolchain — i.e. today's behavior for every project. An unregistered name
715
+ * throws rather than falling back, so a typo can never ship the app to the
716
+ * wrong provider.
717
+ */
718
+ target?: string;
719
+ /**
720
+ * Deploy to a temporary Cloudflare account (`wrangler deploy --temporary`).
721
+ * For unauthenticated use only: wrangler provisions a short-lived account +
722
+ * token, deploys, and prints a claim URL; the deployment stays live ~60
723
+ * minutes before the unclaimed account is deleted. Wrangler itself errors
724
+ * if credentials are already present (OAuth / `CLOUDFLARE_API_TOKEN` /
725
+ * global API key), so we pass the flag straight through without guarding.
726
+ */
364
727
  temporary?: boolean;
365
728
  /** Re-bless the committed schema baseline with the current shape (accepts breaking drift). */
366
729
  updateSchemaBaseline?: boolean;
367
730
  }
731
+ /**
732
+ * What this run put where — the identity of the thing that was just deployed.
733
+ *
734
+ * Present on every run that reached (and completed) the wrangler invocation,
735
+ * including `--dry-run` and `--preview`, so a consumer can tell "nothing went
736
+ * live" from "went live" without inferring it from a missing `url`. A dry run
737
+ * publishes nothing and therefore never carries a `url`.
738
+ *
739
+ * No `versionId`: the pinned wrangler (see the `wrangler` catalog entry in
740
+ * `pnpm-workspace.yaml`) has no structured deploy output
741
+ * and no flag that returns the version id — it only prints it in prose, and
742
+ * scraping a second value out of prose is exactly what this shouldn't do. The
743
+ * id is available from `lunora cloudflare deployments list` after the fact.
744
+ */
745
+ interface DeployedIdentity {
746
+ /** ISO-8601 stamp taken when the wrangler invocation returned. */
747
+ deployedAt: string;
748
+ /** True when `--dry-run` validated + bundled without publishing. */
749
+ dryRun: boolean;
750
+ /** The Cloudflare environment this run targeted, when `--env` named one. */
751
+ env?: string;
752
+ /** True when `--preview` uploaded a version instead of shifting live traffic. */
753
+ preview: boolean;
754
+ /** The URL wrangler reported publishing to; absent on a dry run, or when the output carried no URL. */
755
+ url?: string;
756
+ /** The Worker name from the project's wrangler config. */
757
+ workerName?: string;
758
+ }
368
759
  interface DeployCommandResult {
369
760
  code: number;
761
+ /** What was deployed and where — set once the wrangler invocation completed. */
762
+ deployment?: DeployedIdentity;
370
763
  descriptor: SpawnDescriptor | undefined;
371
764
  /** Set when the run aborted before reaching the wrangler invocation. */
372
765
  error?: string;
766
+ /**
767
+ * The `--health-check` probe's verdict, when the flag was set and the probe
768
+ * ran. A red probe fails the command (`code` is non-zero) — but the deploy
769
+ * itself still succeeded, which is why the reason is reported separately
770
+ * from `error`.
771
+ */
772
+ healthCheck?: {
773
+ error?: string;
774
+ ok: boolean;
775
+ url: string;
776
+ };
777
+ /** Whether the target a successful deploy shipped to has a log tail for `lunora logs`. */
778
+ logsAvailable?: boolean;
779
+ /**
780
+ * The `.dev.vars`-shaped filename (never a full path, never a value) a
781
+ * secret minted during this run was recorded into, when the missing-
782
+ * secret gate minted one — `.dev.vars` for the default environment, or a
783
+ * `.dev.vars.<env>` sibling for an explicit `--env`. `undefined` when
784
+ * nothing was minted this run.
785
+ */
786
+ mintedSecretsFile?: string;
373
787
  /** The schema-drift gate verdict, when it ran (skipped on `--skip-codegen`). */
374
788
  schemaDrift?: {
375
789
  blocked: boolean;
@@ -381,52 +795,115 @@ interface DeployCommandResult {
381
795
  };
382
796
  }
383
797
  /**
384
- * Run a deploy, then (in `--format json` mode) serialize the structured
385
- * {@link DeployCommandResult} to stdout. Human/progress logging is routed to
386
- * stderr for json output so stdout carries only the single JSON document.
387
- */
798
+ * The commands that run the pre-deploy pipeline, as the OPERATOR typed them.
799
+ *
800
+ * These checks are reached from `lunora deploy`, `lunora prepare` and
801
+ * `lunora build`, and a blocked run naming a command the operator never ran
802
+ * reads as a bug in the tool rather than a problem in the project.
803
+ *
804
+ * `build` is one of them: it delegates to `runDeployCommand({ dryRun: true })`.
805
+ * The name is threaded through rather than assumed, because the drift gate uses
806
+ * it for two operator-facing decisions — which override flags to offer, and what
807
+ * to call the thing that was blocked. Hardcoding `"deploy"` here meant `lunora
808
+ * build` reported "deploy blocked" for a deploy nobody attempted and recommended
809
+ * a flag `build` rejects with a raw stack trace.
810
+ */
811
+ type PreDeployCommand = "build" | "deploy" | "prepare";
812
+ /**
813
+ * Run a deploy. In `--format json` mode the human/progress channel is already on
814
+ * stderr (`defineHandler` routed it) and the Vercel-style summary is skipped, so
815
+ * stdout is left to the single result document `execute` returns.
816
+ */
388
817
  declare const runDeployCommand: (options: DeployCommandOptions) => Promise<DeployCommandResult>;
389
- /** `lunora deploy` handler (lazy-loaded via the command's `loader`). */
390
818
  /**
391
- * Start the codegen watch loop and return a handle to stop it. Regenerates on
392
- * startup, then on debounced changes under `lunora/` (ignoring writes to the
393
- * `_generated/` output to avoid a feedback loop). If the platform can't do a
394
- * recursive watch, it logs once and falls back to startup-only codegen.
395
- */
819
+ * Start the codegen watch loop and return a handle to stop it. Regenerates on
820
+ * startup, then on debounced changes under `lunora/` (ignoring writes to the
821
+ * `_generated/` output to avoid a feedback loop). If the platform can't do a
822
+ * recursive watch, it logs once and falls back to startup-only codegen.
823
+ */
396
824
  declare const startCodegenWatch: (options: CodegenWatcherOptions) => CodegenWatcherHandle;
397
825
  interface CodegenWatcherOptions {
398
826
  /** Which API spec(s) to emit. Defaults to codegen's `"openapi"` when omitted. */
399
827
  apiSpec?: CodegenOptions["apiSpec"];
400
828
  /** Debounce window for coalescing rapid edits. Defaults to 100ms. */
401
829
  debounceMs?: number;
830
+ /**
831
+ * The caller's logs are NDJSON on stdout, so the `postcodegen` hook's own
832
+ * stdout must be routed to stderr or it corrupts the stream. `lunora dev`
833
+ * turns this on for `--json` AND for a detected AI agent.
834
+ */
835
+ jsonLogs?: boolean;
836
+ /** Opt into per-module lazy function loading; omitted keeps the eager registry. */
837
+ lazyFunctions?: CodegenOptions["lazyFunctions"];
402
838
  logger: Logger;
403
839
  /** Override the lunora subdirectory name. Defaults to `"lunora"`. */
404
840
  lunoraDirectory?: string;
405
841
  /** Project root containing the `lunora/` directory. */
406
842
  projectRoot: string;
843
+ /** Process spawner for the `postcodegen` hook. Injectable so tests need no real subprocess. */
844
+ spawner?: Spawner;
845
+ /** Deploy target the emitted `ctx.*` surface is tailored to. Resolved by the caller; falls back to `"target"` in `lunora.config.*`, then `"cloudflare"`. */
846
+ target?: string;
407
847
  }
408
848
  interface CodegenWatcherHandle {
409
- /** Stop watching and cancel any pending regeneration. */
410
- close: () => void;
411
- /**
412
- * `true` when the platform supports recursive watch and the loop is active.
413
- * `false` when `fs.watch({ recursive })` threw — startup-only codegen was run
414
- * but schema edits will NOT auto-regenerate. Callers can surface this in the
415
- * dev banner so the degraded state is visible beyond the single startup warning.
416
- */
849
+ /**
850
+ * Stop watching, drop any queued regeneration, and resolve once the run
851
+ * already in flight has finished.
852
+ *
853
+ * Awaiting the result is what keeps a `postcodegen` child from being
854
+ * orphaned by the caller's `process.exit`; a caller that only needs the
855
+ * watcher detached can ignore it.
856
+ */
857
+ close: () => Promise<void>;
858
+ /**
859
+ * Resolves once the startup regeneration — codegen AND the project's
860
+ * `postcodegen` — has finished.
861
+ *
862
+ * Await it before starting anything that reads generated output. `runCodegen`
863
+ * is synchronous and has already run by the time `startCodegenWatch` returns,
864
+ * but the hook is the step that FINISHES that output, so a worker spawned
865
+ * without waiting can bundle the unfinished copy. Resolves (never rejects)
866
+ * even when codegen or the hook failed — both report for themselves, and a
867
+ * dev server still has to come up.
868
+ */
869
+ ready: Promise<void>;
870
+ /**
871
+ * `true` when the platform supports recursive watch and the loop is active.
872
+ * `false` when `fs.watch({ recursive })` threw — startup-only codegen was run
873
+ * but schema edits will NOT auto-regenerate. Callers can surface this in the
874
+ * dev banner so the degraded state is visible beyond the single startup warning.
875
+ */
417
876
  watchAvailable: boolean;
418
877
  }
419
878
  /**
420
- * Start the studio server and resolve once it is listening. Loads the static
421
- * bundle + renders the host HTML once up front; serves them and proxies
422
- * `/_lunora/*` (HTTP + WS) to the worker.
423
- */
879
+ * Readiness probe seam — tests swap the real HTTP probe out.
880
+ *
881
+ * The optional `signal` lets a caller cancel an attempt already in flight. Its
882
+ * absence is why a teardown used to leave one request dangling for up to
883
+ * {@link ATTEMPT_TIMEOUT_MS} after the dev server had been told to stop.
884
+ */
885
+ type ReadinessProbe = (origin: string, signal?: AbortSignal) => Promise<boolean>;
886
+ /**
887
+ * Start the studio server and resolve once it is listening. Loads the static
888
+ * bundle + renders the host HTML once up front; serves them and proxies
889
+ * `/_lunora/*` (HTTP + WS) to the worker.
890
+ */
424
891
  declare const startStudioServer: (options: StudioServerOptions) => Promise<StudioServerHandle>;
425
892
  interface StudioServerOptions {
893
+ /**
894
+ * API-spec mode the host runs codegen with, forwarded to the local endpoints
895
+ * so a studio edit regenerates the SAME spec files the host's own codegen run
896
+ * writes. Codegen writes the spec its mode names and deletes the other, so
897
+ * omitting it made every studio edit delete an `apiSpec: "openrpc"` project's
898
+ * `openrpc.json`.
899
+ */
900
+ apiSpec?: CodegenOptions["apiSpec"];
426
901
  /** Project root — `.dev.vars` is read from here for the admin token. */
427
902
  cwd: string;
428
903
  /** Loopback host to bind. Defaults to `127.0.0.1` (admin tooling stays local). */
429
904
  host?: string;
905
+ /** Lazy function mode the host runs codegen with, forwarded to local source-edit endpoints. */
906
+ lazyFunctions?: CodegenOptions["lazyFunctions"];
430
907
  /** One-time warning sink for a missing/unbuilt `@lunora/studio`. */
431
908
  logger?: {
432
909
  warnOnce?: (message: string) => void;
@@ -442,6 +919,25 @@ interface StudioServerHandle {
442
919
  /** The URL to open in a browser. */
443
920
  url: string;
444
921
  }
922
+ /**
923
+ * How the dev child runs. `wrangler` is the classic `lunora dev` stack (wrangler
924
+ * worker + embedded studio + codegen watch) for a standalone class-C project.
925
+ * `vite` is a project whose BUNDLER PLUGIN already runs the worker — `@lunora/vite`
926
+ * inside the Vite dev server, or `@lunora/rspack/rsbuild` alongside an Rsbuild
927
+ * one — together with studio and codegen, so `lunora dev` runs the project's own
928
+ * dev script and gets out of the way — this also covers class-B
929
+ * frameworks whose own dev server runs the worker in `workerd` (Astro 6 +
930
+ * `@astrojs/cloudflare`, which embeds `@cloudflare/vite-plugin` in `astro dev`:
931
+ * SSR + `/_lunora/*` + `ShardDO` in one process, HMR intact). `framework-worker`
932
+ * is a class-B framework whose dev server CANNOT host the `ShardDO` Durable
933
+ * Object (SvelteKit / Nuxt: their adapters use wrangler's `getPlatformProxy()`,
934
+ * which runs an empty-script Miniflare and does not emulate internal DOs); there
935
+ * `lunora dev` runs the framework's own dev server (front door, HMR, and — via
936
+ * its `@lunora/vite` plugin — studio + codegen) AND a second `wrangler dev`
937
+ * sidecar that owns the real `ShardDO` in `workerd`, wired via the committed
938
+ * `wrangler.dev.jsonc`.
939
+ */
940
+ type DevFlavor = "framework-worker" | "vite" | "wrangler";
445
941
  /** A running worker child the orchestrator controls: send signals, await its exit. */
446
942
  interface WorkerProcess {
447
943
  /** Resolves with the worker's exit code (1 if it failed to start). */
@@ -452,103 +948,232 @@ interface WorkerProcess {
452
948
  type WorkerSpawner = (descriptor: SpawnDescriptor & {
453
949
  tag: string;
454
950
  }, logger: Logger) => WorkerProcess;
951
+ /** What a long-lived child runs: the one-shot descriptor's command/args/cwd/env, plus how to spawn it. */
952
+ interface LongLivedDescriptor {
953
+ args: ReadonlyArray<string>;
954
+ command: string;
955
+ cwd?: string;
956
+ /** A real executable, never a package-manager shim — spawned without a shell, with stdin ignored. */
957
+ direct?: boolean;
958
+ env?: Readonly<Record<string, string>>;
959
+ }
960
+ /** Spawns a long-lived child and streams its output line by line. Injectable for tests. */
961
+ type LongLivedSpawner = (descriptor: LongLivedDescriptor, onLine: (line: string, kind: "stderr" | "stdout") => void, onError?: (error: Error) => void) => WorkerProcess;
962
+ /** A `--tunnel` request, built once from the parsed flags. */
963
+ interface DevTunnelRequest {
964
+ /** Normalized `--allow-mail` entries, passed to cloudflared as `--allowed-mail`; empty opens a PUBLIC tunnel. */
965
+ allowMail: ReadonlyArray<string>;
966
+ /** Injection seam for tests — the one-shot spawner the `cloudflared --version` probe runs through. */
967
+ spawner?: Spawner;
968
+ /** Injection seam for tests — starts the long-lived `cloudflared tunnel` child. */
969
+ startChild?: LongLivedSpawner;
970
+ }
455
971
  interface DevCommandOptions {
456
972
  /** Which API spec(s) the codegen watcher emits. Defaults to codegen's `"openapi"` when omitted. */
457
973
  apiSpec?: ApiSpec;
458
974
  /** Disable the codegen watch loop. */
459
975
  codegen?: boolean;
460
976
  cwd?: string;
977
+ /**
978
+ * Override where the binding manifest is written. One is always produced at
979
+ * `DEV_BINDINGS_FILE`; naming a path also makes a derivation failure
980
+ * fatal, since a named path means something is waiting on it.
981
+ */
982
+ emitBindings?: string;
461
983
  /** Injection seam for tests — defaults to the real `.dev.vars` scaffolder. */
462
984
  ensureEnv?: typeof ensureDevVariables;
463
985
  /** Injection seam for tests — defaults to the real `.dev.vars.example` package-aware scaffolder. */
464
986
  ensureExample?: typeof ensureDevVarsExample;
465
987
  /** Injection seam for tests — defaults to the real empty-secret/admin-token filler. */
466
988
  fillSecrets?: typeof fillDevSecrets;
989
+ /** Injection seam for tests — defaults to the real free-port probe (`findAvailablePort`). */
990
+ findFreePort?: (preferred: number) => Promise<number>;
991
+ /** Dev flavor override (tests / callers that already detected it) — defaults to `detectDevFlavor`. */
992
+ flavor?: DevFlavor;
993
+ /** Injection seam for tests — defaults to the real IPv6-loopback probe (`hasIpv6Loopback`). */
994
+ hasIpv6Loopback?: () => boolean;
995
+ /** `wrangler dev` devtools inspector port (`--inspector-port`). Wrangler flavor only — see `resolveInspectorPort`. */
996
+ inspectorPort?: number;
997
+ /**
998
+ * Logs are NDJSON on stdout (`--json`, or a detected AI agent). Forwarded to
999
+ * the codegen watcher so a `postcodegen` script's own stdout is routed to
1000
+ * stderr instead of corrupting the stream.
1001
+ */
1002
+ jsonLogs?: boolean;
1003
+ /** Opt into per-module lazy function loading for CLI codegen. */
1004
+ lazyFunctions?: boolean;
1005
+ /** Pass `--local` to `wrangler dev`: no remote proxy session, so a binding with no local mode (`ai`) cannot stop the session from starting. */
1006
+ local?: boolean;
467
1007
  logger: Logger;
468
- /** Injection seam for tests — defaults to the real remote-config materializer. */
469
- materializeRemote?: typeof materializeRemoteWranglerConfig;
1008
+ /** Injection seam for tests — defaults to the real dev-config materializer (remote bindings and the logged-out `ai` withholding). */
1009
+ materializeDev?: typeof materializeDevWranglerConfig;
1010
+ /** Injection seam for tests — defaults to the real per-service dev-config materializer. */
1011
+ materializeServiceConfigs?: typeof materializeServiceDevConfigs;
470
1012
  /** Studio server port. */
471
1013
  port?: number;
1014
+ /** Injection seam for tests — defaults to the real HTTP readiness probe. Without it the suite issues live GETs to the dev port. */
1015
+ probeReady?: ReadinessProbe;
472
1016
  /** Proxy D1/KV/R2 bindings to the deployed worker during dev (`LUNORA_REMOTE=1` / `--remote`); DO shards stay local. */
473
1017
  remote?: boolean;
1018
+ /** Starts the celld dev session for the celld target; injected in tests. */
1019
+ startCelldSession?: typeof startCelldDevSession;
474
1020
  /** Injection seam for tests — defaults to the real codegen watcher. */
475
1021
  startCodegen?: typeof startCodegenWatch;
1022
+ /** Injection seam for tests — defaults to the embedded Postgres behind a Hyperdrive binding. */
1023
+ startHyperdrive?: typeof startLocalHyperdrive;
476
1024
  /** Injection seam for tests — defaults to the real studio server. */
477
1025
  startStudio?: typeof startStudioServer;
478
1026
  /** Injection seam for tests — defaults to spawning a real `wrangler dev`. */
479
1027
  startWorker?: WorkerSpawner;
480
1028
  /** Disable the embedded studio server. */
481
1029
  studio?: boolean;
1030
+ /** Deploy target the emitted `ctx.*` surface is tailored to. Resolved by the caller; falls back to `"target"` in `lunora.config.*`, then `"cloudflare"`. */
1031
+ target?: string;
1032
+ /** `--tunnel`: share the worker's origin through a Cloudflare quick tunnel. Absent means no tunnel. */
1033
+ tunnel?: DevTunnelRequest;
1034
+ /**
1035
+ * Injection seam for tests — defaults to parking until SIGINT.
1036
+ *
1037
+ * Attached mode (`--no-worker`) ends only on a signal, so without this the
1038
+ * whole branch is unreachable from a test. That is how the readiness probe
1039
+ * came to be wired after the early return, reported for a flavor it never
1040
+ * covered, and shipped.
1041
+ */
1042
+ waitForInterrupt?: (logger: Logger) => Promise<number>;
1043
+ /** Disable the `wrangler dev` spawn — an external task runner owns the worker. */
1044
+ worker?: boolean;
482
1045
  /** `wrangler dev` port. */
483
1046
  workerPort?: number;
1047
+ /** Writes the celld projection for a `--no-worker` run; injected in tests. */
1048
+ writeCelldProjection?: typeof writeCelldDevProjection;
484
1049
  }
485
1050
  interface DevRemotePlan {
486
1051
  /** Short binding labels remoted (e.g. `"DB (D1)"`), for the banner. */
487
1052
  bindings: string[];
488
1053
  /**
489
- * Removes the generated temp wrangler config when dev exits. Always present
490
- * and idempotent — a no-op when remote mode is off or nothing was
491
- * materialized. The dev loop calls it on every shutdown path.
492
- */
1054
+ * Removes the generated temp wrangler config when dev exits. Always present
1055
+ * and idempotent — a no-op when remote mode is off or nothing was
1056
+ * materialized. The dev loop calls it on every shutdown path.
1057
+ */
493
1058
  cleanup: () => void;
494
1059
  /** Whether remote mode was requested. */
495
1060
  enabled: boolean;
496
1061
  /** Why remote mode didn't take effect despite being requested, for logging. */
497
1062
  reason?: string;
1063
+ /** Remote-only bindings (`ai`, `artifacts`) a session left out for lack of Cloudflare credentials, for the banner warning. */
1064
+ withheld: WithheldBinding[];
498
1065
  }
499
1066
  interface DevCommandPlan {
500
- codegenEnabled: boolean;
1067
+ /**
1068
+ * `true` when the worker is a celld dev session (a target running its own
1069
+ * dev server) rather than {@link DevCommandPlan.wrangler}'s process: services
1070
+ * registered first, a service edit re-registering it and restarting the app.
1071
+ */
1072
+ celldSession?: true;
1073
+ /** Which stack the child runs — see {@link DevFlavor}. */
1074
+ flavor: DevFlavor;
1075
+ /**
1076
+ * One-line redirect hint printed when a meta-framework is detected on the
1077
+ * wrangler flavor: without `@lunora/vite` in the dependencies the worker
1078
+ * still runs *inside* the framework's dev server, so the user should run
1079
+ * their framework dev script for the full app. `undefined` for the vite
1080
+ * flavor (`lunora dev` already runs the project's dev script there) and
1081
+ * for a standalone project. Purely informational: the wrangler spawn runs
1082
+ * regardless.
1083
+ */
1084
+ frameworkHint?: string;
1085
+ /**
1086
+ * True when `wrangler dev` was given `--ip 127.0.0.1` because the host has no
1087
+ * IPv6 loopback (`::1`) — surfaced so the dev loop can note the rebind.
1088
+ * Always `false` for the vite flavor (the plugin owns its own bind).
1089
+ */
1090
+ ipv4LoopbackForced: boolean;
501
1091
  /** The remote-binding decision: which D1/KV/R2 bindings hit the deployed worker. */
502
1092
  remote: DevRemotePlan;
1093
+ runsCodegenWatch: boolean;
1094
+ /**
1095
+ * Unlinks the copies of service configs written so a service's custom build
1096
+ * runs in its own folder (`materializeServiceDevConfigs`). Idempotent; absent
1097
+ * for a flavor that runs no services through a `wrangler dev` of its own.
1098
+ */
1099
+ serviceConfigCleanup?: () => void;
1100
+ /**
1101
+ * The `wrangler dev` sidecar for the `framework-worker` flavor (SvelteKit /
1102
+ * Nuxt): a second child that owns the real `ShardDO` in `workerd`, wired via
1103
+ * the committed `wrangler.dev.jsonc`. `undefined` for every other flavor —
1104
+ * only the two-process class-B stack has a sidecar. When present, `wrangler`
1105
+ * (above) is the framework's own dev server (the front door / HMR) and this
1106
+ * is the Lunora realtime plane.
1107
+ */
1108
+ sidecar?: SpawnDescriptor & {
1109
+ tag: string;
1110
+ };
503
1111
  studioEnabled: boolean;
504
1112
  studioPort: number;
1113
+ /**
1114
+ * Whether this process spawns `wrangler dev`.
1115
+ *
1116
+ * `--no-worker` turns it off so an external task runner (Turbo, Nx, vis, a
1117
+ * Procfile) can own worker supervision while `lunora dev` still provides
1118
+ * codegen-watch and Studio. Without it, `lunora dev` insisted on being the
1119
+ * process root, which is what blocked running the Lunora worker as one node
1120
+ * in a larger dev graph.
1121
+ */
1122
+ workerEnabled: boolean;
505
1123
  workerOrigin: string;
506
1124
  workerPort: number;
507
- /** The single child process `lunora dev` spawns: `wrangler dev`. */
1125
+ /** The primary child `lunora dev` spawns: `wrangler dev` (wrangler flavor) or the framework/`vite dev` server (vite / framework-worker). */
508
1126
  wrangler: SpawnDescriptor & {
509
1127
  tag: string;
510
1128
  };
511
1129
  }
512
1130
  /**
513
- * Resolve remote-binding mode into the extra `wrangler dev` args + a banner
514
- * summary. When `--remote`/`LUNORA_REMOTE` is set we materialize a temp wrangler
515
- * config with `"remote": true` on each D1/KV/R2 binding (Durable Object shards
516
- * stay local) and point `wrangler dev --config` at it, so the local worker reads
517
- * and writes the **deployed** resources. When disabled, or when there's nothing
518
- * to remote, the args stay empty and dev runs fully local.
519
- */
520
- /**
521
- * Plan `lunora dev`: it runs the worker via `wrangler dev` and nothing else as a
522
- * child process. Vite is intentionally NOT spawned — a project may not use Vite,
523
- * and when it does, the `@lunora/vite` plugin already runs the worker inside
524
- * Vite, so the user runs `vite` themselves. Pure + synchronous so it's unit-testable.
525
- */
526
- declare const planDevCommand: (options: DevCommandOptions) => DevCommandPlan;
527
- /**
528
- * Start codegen watch + the studio server, spawn `wrangler dev`, print the
529
- * banner, and resolve when the worker exits or the user interrupts — tearing
530
- * down the sibling servers either way. The three side-effecting pieces (worker,
531
- * studio, codegen) are injectable so this is testable without real I/O.
532
- */
1131
+ * Start codegen watch + the studio server, spawn `wrangler dev`, print the
1132
+ * banner, and resolve when the worker exits or the user interrupts — tearing
1133
+ * down the sibling servers either way. The three side-effecting pieces (worker,
1134
+ * studio, codegen) are injectable so this is testable without real I/O.
1135
+ */
533
1136
  declare const runDevCommand: (options: DevCommandOptions) => Promise<{
534
1137
  code: number;
535
1138
  plan: DevCommandPlan;
536
1139
  }>;
537
- /** `lunora dev` handler (lazy-loaded via the command's `loader`). */
1140
+ /**
1141
+ * Plan `lunora dev`. Wrangler flavor: the worker runs via `wrangler dev` and
1142
+ * nothing else as a child process. Vite flavor (`@lunora/vite` declared): the
1143
+ * plugin already runs the worker inside the Vite dev server, so the one child
1144
+ * is the project's own dev script (`vite dev`, `astro dev`, …) and every CLI
1145
+ * sibling is disabled. Pure + synchronous so it's unit-testable.
1146
+ */
1147
+ declare const planDevCommand: (options: DevCommandOptions) => DevCommandPlan;
538
1148
  /** Supported CI providers. */
539
1149
  type CiProvider = "github" | "gitlab";
540
- type PackageManager = "pnpm" | "npm" | "yarn" | "bun";
541
- /** True when `manager` is on PATH — probed by running `&lt;manager> --version`. Injectable for tests. */
542
- type PackageManagerProbe = (manager: PackageManager) => boolean;
543
- /**
544
- * The package managers actually installed on this machine, in preference order
545
- * ({@link INSTALL_PREFERENCE} — pnpm > bun > yarn > npm). The first entry is the
546
- * recommended default for the install prompt; the whole list is what the user
547
- * picks from. Empty when none are found.
548
- */
1150
+ /**
1151
+ * The per-framework auth-UI registry items (`auth-ui` resolves to one of these).
1152
+ *
1153
+ * Solid has two because these are copy-in source files, not a compiled package:
1154
+ * the 1.x and 2.0 spellings are mutually exclusive in the source itself, so the
1155
+ * two majors get one item each and {@link detectAuthUiItem} picks.
1156
+ */
1157
+ type AuthUiItem = "auth-ui-angular" | "auth-ui-react" | "auth-ui-solid" | "auth-ui-solid-v2" | "auth-ui-svelte" | "auth-ui-vue";
549
1158
  /** A registry item a feature can install. */
550
- type FeatureItem = "auth" | "auth-auth0" | "auth-clerk" | "mail";
551
- /** The auth-provider choices offered for `add auth` / the init auth prompt. Each value is a registry item name. */
1159
+ type FeatureItem = "auth" | "auth-auth0" | "auth-clerk" | AuthUiItem | "mail";
1160
+ /** One catalog entry as `lunora registry list` reports it. */
1161
+ interface CatalogItem {
1162
+ description?: string;
1163
+ name: string;
1164
+ }
1165
+ /** A built index entry (catalog item plus its short `title`). */
1166
+ interface IndexItem extends CatalogItem {
1167
+ title?: string;
1168
+ }
1169
+ /**
1170
+ * Build the catalog (`index.json` contents) from a local registry root by
1171
+ * reading every item's `registry.json`. Used by both `lunora registry build`
1172
+ * and the registry tests so the committed index can't drift from the item dirs.
1173
+ */
1174
+ declare const buildRegistryIndex: (root: string) => {
1175
+ items: IndexItem[];
1176
+ };
552
1177
  /** A single file the item scaffolds into the project. */
553
1178
  interface RegistryFile {
554
1179
  /** Source path inside the item dir (e.g. `schema.ts`). */
@@ -564,10 +1189,10 @@ interface RegistryBinding {
564
1189
  value: unknown;
565
1190
  }
566
1191
  /**
567
- * An environment variable an item needs. Scaffolded into `.dev.vars` (Workers'
568
- * local-secrets file) on add — non-secrets get their `value`; secrets get an
569
- * empty placeholder and a reminder to run `wrangler secret put` for production.
570
- */
1192
+ * An environment variable an item needs. Scaffolded into `.dev.vars` (Workers'
1193
+ * local-secrets file) on add — non-secrets get their `value`; secrets get an
1194
+ * empty placeholder and a reminder to run `wrangler secret put` for production.
1195
+ */
571
1196
  interface RegistryEnvVariable {
572
1197
  /** Human note on what the variable is for. */
573
1198
  description?: string;
@@ -578,6 +1203,13 @@ interface RegistryEnvVariable {
578
1203
  /** A default/example value for non-secret vars. */
579
1204
  value?: string;
580
1205
  }
1206
+ /** A re-export the item needs injected into the worker entry point (class-B/C only). */
1207
+ interface EntrypointReexport {
1208
+ /** Optional JS comment placed above the re-export line. */
1209
+ comment?: string;
1210
+ /** Module specifier (e.g. `"_generated/workflows"` → `export * from "./lunora/_generated/workflows"`). */
1211
+ module: string;
1212
+ }
581
1213
  /** The `registry.json` manifest shape. */
582
1214
  interface RegistryManifest {
583
1215
  /** wrangler.jsonc additions (best-effort structural edits). */
@@ -589,6 +1221,8 @@ interface RegistryManifest {
589
1221
  devDependencies?: Readonly<Record<string, string>>;
590
1222
  /** Post-install guidance printed after the item is added (per-item next steps). */
591
1223
  docs?: string;
1224
+ /** Worker-entry re-exports the item needs (class-B/C only). */
1225
+ entrypointReexports?: ReadonlyArray<EntrypointReexport>;
592
1226
  /** Environment variables the item needs; scaffolded into `.dev.vars`. */
593
1227
  envVars?: ReadonlyArray<RegistryEnvVariable>;
594
1228
  files: ReadonlyArray<RegistryFile>;
@@ -610,10 +1244,10 @@ interface AddCommandOptions {
610
1244
  diff?: boolean;
611
1245
  /** Print the plan and stop without writing anything. */
612
1246
  dryRun?: boolean;
1247
+ /** Output format: `pretty` (default) or `json` — a JSON snapshot of the plan/list. */
1248
+ format?: OutputFormat;
613
1249
  /** Local registry root (offline / tests). Expects per-item subdirs, each with a `registry.json`. */
614
1250
  from?: string;
615
- /** Emit a JSON snapshot of the plan/result. */
616
- json?: boolean;
617
1251
  /** `--list`: enumerate available items instead of adding. */
618
1252
  list?: boolean;
619
1253
  logger: Logger;
@@ -628,19 +1262,51 @@ interface AddCommandOptions {
628
1262
  /** Override the remote registry source base (default gh:anolilab/lunora/registry). */
629
1263
  source?: string;
630
1264
  /**
631
- * Customize each resolved manifest after it is loaded but before the plan is
632
- * printed / reconciled — used to inject user-chosen values into otherwise
633
- * static manifests (e.g. the R2 `bucket_name` the init storage prompt asks
634
- * for). Applied to every item; return the manifest unchanged to leave it as-is.
635
- */
1265
+ * Customize each resolved manifest after it is loaded but before the plan is
1266
+ * printed / reconciled — used to inject user-chosen values into otherwise
1267
+ * static manifests (e.g. the R2 `bucket_name` the init storage prompt asks
1268
+ * for). Applied to every item; return the manifest unchanged to leave it as-is.
1269
+ */
636
1270
  transformManifest?: (manifest: RegistryManifest) => RegistryManifest;
637
1271
  /** Skip the package.json mutation confirmation prompt. */
638
1272
  yes?: boolean;
639
1273
  }
640
- interface AddCommandResult {
1274
+ /**
1275
+ * One item in the `--format json` plan snapshot. Carries the concrete binding
1276
+ * VALUES, not just the key paths, so a plan consumer can audit the mutation
1277
+ * before it is applied.
1278
+ */
1279
+ interface RegistryPlanItem {
1280
+ bindings: {
1281
+ path: string;
1282
+ value: unknown;
1283
+ }[];
1284
+ deps: string[];
1285
+ devDependencies: string[];
1286
+ entrypointReexports: {
1287
+ comment?: string;
1288
+ module: string;
1289
+ }[];
1290
+ envVars: {
1291
+ name: string;
1292
+ secret?: boolean;
1293
+ value?: string;
1294
+ }[];
1295
+ files: {
1296
+ merge: RegistryFile["merge"];
1297
+ to: string;
1298
+ }[];
1299
+ name: string;
1300
+ requires: ReadonlyArray<string>;
1301
+ title?: string;
1302
+ }
1303
+ /** The `--format json` payload: the catalog (`list`) or the resolved plan (`add`). */
1304
+ interface RegistryCommandData {
1305
+ items: ReadonlyArray<CatalogItem | RegistryPlanItem>;
1306
+ }
1307
+ interface AddCommandResult extends CommandResult<RegistryCommandData> {
641
1308
  /** Bindings written to wrangler.jsonc. */
642
1309
  bindings: ReadonlyArray<string>;
643
- code: number;
644
1310
  /** Deps added to package.json. */
645
1311
  deps: ReadonlyArray<string>;
646
1312
  /** Files skipped because they already existed. */
@@ -648,34 +1314,40 @@ interface AddCommandResult {
648
1314
  /** Files written (absolute paths). */
649
1315
  written: ReadonlyArray<string>;
650
1316
  }
651
- /** One resolved item: its parsed manifest plus the (possibly staged) directory it lives in. */
1317
+ type ExternalAuthProvider = "auth0" | "clerk" | "workos";
1318
+ /** The `--auth` values: Lunora's own auth, an external provider, or none. */
1319
+ type AuthChoice = ExternalAuthProvider | "lunora" | "none";
652
1320
  /**
653
- * A feature offered in the post-scaffold multi-select. `auth`/`email` carry a
654
- * sub-prompt or alias; every other value IS the registry item name applied
655
- * directly (`storage` → the `storage` registry item, etc.).
656
- */
657
- type StackFeature = "auth" | "backup" | "crons" | "email" | "presence" | "ratelimit" | "storage";
1321
+ * A feature offered in the post-scaffold multi-select. `auth`/`email` carry a
1322
+ * sub-prompt or alias; every other value IS the registry item name applied
1323
+ * directly (`storage` → the `storage` registry item, etc.).
1324
+ */
1325
+ type StackFeature = "ai" | "auth" | "auth-ui" | "backup" | "browser" | "cloudflare-access" | "crons" | "email" | "flags" | "hyperdrive" | "payment" | "presence" | "queue" | "storage" | "workflow";
658
1326
  /** Customize a resolved manifest before it is written (e.g. inject the chosen R2 bucket name). */
659
1327
  type OfferTransformManifest = (manifest: RegistryManifest) => RegistryManifest;
660
1328
  /**
661
- * One feature ready to apply: the registry item name(s), an optional manifest
662
- * transform, and a short `label` (the feature value) shown on the combined
663
- * progress line. Built up-front by the collectors so every prompt is answered
664
- * before any apply runs.
665
- */
1329
+ * One feature ready to apply: the registry item name(s), an optional manifest
1330
+ * transform, and a short `label` (the feature value) shown on the combined
1331
+ * progress line. Built up-front by the collectors so every prompt is answered
1332
+ * before any apply runs.
1333
+ */
666
1334
  interface FeatureApply {
1335
+ /** An external identity provider to wire into the Worker and client once its registry item is applied. */
1336
+ externalAuth?: ExternalAuthProvider;
667
1337
  label: string;
668
1338
  names: ReadonlyArray<string>;
669
1339
  transformManifest?: OfferTransformManifest;
670
1340
  }
671
1341
  interface OfferDeps {
672
1342
  /**
673
- * Apply the collected features into the new project in one batch — resolves
674
- * `true` when every item succeeds. The CLI renders this as a single progress
675
- * line whose label changes per feature; each plan's `transformManifest`
676
- * customizes that item's manifest before it is written.
677
- */
1343
+ * Apply the collected features into the new project in one batch — resolves
1344
+ * `true` when every item succeeds. The CLI renders this as a single progress
1345
+ * line whose label changes per feature; each plan's `transformManifest`
1346
+ * customizes that item's manifest before it is written.
1347
+ */
678
1348
  applyAll: (plans: ReadonlyArray<FeatureApply>) => Promise<boolean>;
1349
+ /** The auth choice made up front (the `--auth` flag). When set, the interactive auth question is skipped. */
1350
+ auth?: AuthChoice;
679
1351
  /** When `false`, skip all prompts and print the later-setup hint. */
680
1352
  interactive: boolean;
681
1353
  logger: Logger;
@@ -688,13 +1360,24 @@ interface OfferDeps {
688
1360
  defaults?: ReadonlyArray<StackFeature>;
689
1361
  }) => Promise<StackFeature[]>;
690
1362
  /**
691
- * Features chosen non-interactively (the `--add` flag). When set, the
692
- * multi-select and every sub-prompt are skipped — each feature is applied with
693
- * its shipped defaults (base registry item, placeholder bindings).
694
- */
1363
+ * Features chosen non-interactively (the `--add` flag). When set, the
1364
+ * multi-select and every sub-prompt are skipped — each feature is applied with
1365
+ * its shipped defaults (base registry item, placeholder bindings).
1366
+ */
695
1367
  preselected?: ReadonlyArray<StackFeature>;
696
1368
  /** The new project's name — seeds smart defaults like the `project-uploads` bucket name. */
697
1369
  projectName: string;
1370
+ /**
1371
+ * Resolve which per-framework auth-UI item (`auth-ui-react|vue|…`) fits the
1372
+ * scaffolded project. Injected by the CLI (detected from the template's deps);
1373
+ * defaults to `auth-ui-react` when absent so this module stays pure/testable.
1374
+ *
1375
+ * `undefined` is a REFUSAL, not "unknown": no auth-UI item fits this project
1376
+ * (React Native). `lunora add auth-ui` already refuses there, and this offer
1377
+ * used to `?? "auth-ui-react"` its way past that — copying ~85 DOM files into
1378
+ * an Expo app and exiting 0.
1379
+ */
1380
+ resolveAuthUiItem?: () => string | undefined;
698
1381
  /** Single-select among the auth providers (TTY-backed in production). */
699
1382
  select: (message: string, options: ReadonlyArray<{
700
1383
  description?: string;
@@ -703,120 +1386,147 @@ interface OfferDeps {
703
1386
  }>, settings?: {
704
1387
  default?: FeatureItem;
705
1388
  }) => Promise<FeatureItem | undefined>;
1389
+ /** Single-select among the auth choices (TTY-backed in production). */
1390
+ selectAuth: (message: string, options: ReadonlyArray<{
1391
+ description?: string;
1392
+ label: string;
1393
+ value: AuthChoice;
1394
+ }>, settings?: {
1395
+ default?: AuthChoice;
1396
+ }) => Promise<AuthChoice | undefined>;
706
1397
  /** Single-line text input (TTY-backed in production) — used for the storage bucket-name prompt. */
707
1398
  text: (message: string, settings?: {
708
1399
  default?: string;
709
1400
  placeholder?: string;
710
1401
  }) => Promise<string>;
711
1402
  }
712
- /**
713
- * Offer the stack features (auth, email, storage, rate limiting, crons,
714
- * presence, backups) in ONE multi-select after a successful scaffold. Auth,
715
- * email, and storage run a follow-up prompt (provider / destination / bucket
716
- * name); every other feature value is applied as its registry item directly.
717
- *
718
- * Every question is asked FIRST (in selection order), then the picked features
719
- * are applied together via {@link OfferDeps.applyAll} — the CLI renders that as a
720
- * single progress line whose label changes per feature, instead of one spinner
721
- * per item. Non-interactive: prints how to add them later and changes nothing.
722
- */
723
- type Template = "analog" | "astro" | "next" | "nuxt" | "react-router" | "standalone" | "sveltekit" | "tanstack-start-react" | "tanstack-start-solid";
1403
+ /** One choice in the multi-select. */
1404
+ interface LintToolOption {
1405
+ description: string;
1406
+ label: string;
1407
+ value: LintTool;
1408
+ }
1409
+ interface LintToolOfferDeps {
1410
+ /** Write the ignores for the chosen tools — `applyLintIgnores` in production. */
1411
+ apply: (tools: ReadonlyArray<LintTool>) => LintIgnoreOutcome[];
1412
+ /** Tools already detectable in the scaffolded project — pre-selected in the prompt. */
1413
+ detected: ReadonlyArray<LintTool>;
1414
+ /** False in CI / `--yes` / off a TTY: skip the prompt and configure whatever was detected. */
1415
+ interactive: boolean;
1416
+ logger: Logger;
1417
+ multiSelect: (message: string, choices: ReadonlyArray<LintToolOption>, settings?: {
1418
+ defaults?: ReadonlyArray<LintTool>;
1419
+ }) => Promise<LintTool[]>;
1420
+ }
1421
+ type Template = "analog" | "astro" | "expo" | "next" | "nuxt" | "rspack-react" | "saas" | "solid-v2" | "standalone" | "sveltekit" | "tanstack-start-react" | "tanstack-start-react-rspack" | "tanstack-start-solid" | "vinext" | "vinext-pages";
724
1422
  interface InitCommandOptions {
725
1423
  /**
726
- * Add features non-interactively after scaffolding (the `--add` flag): a
727
- * comma-separated list of `auth | email | storage | ratelimit | crons |
728
- * presence | backup`. Bypasses the interactive multi-select and sub-prompts —
729
- * each named feature is applied with its shipped defaults.
730
- */
1424
+ * Add features non-interactively after scaffolding (the `--add` flag): a
1425
+ * comma-separated list of `ai | auth | auth-ui | backup | browser | cloudflare-access | crons | email | flags | hyperdrive | payment | presence | queue | storage | workflow`.
1426
+ * Bypasses the interactive multi-select and sub-prompts —
1427
+ * each named feature is applied with its shipped defaults.
1428
+ */
731
1429
  add?: string;
732
1430
  /**
733
- * When true, accept `--source` values that don't start with `gh:` /
734
- * `github:` / `https://` or that contain `..`. Defaults to false; the CLI
735
- * gate exists to stop arbitrary filesystem / scheme sources from being
736
- * pulled without the caller opting in.
737
- */
1431
+ * When true, accept `--source` values that don't start with `gh:` /
1432
+ * `github:` / `https://` or that contain `..`. Defaults to false; the CLI
1433
+ * gate exists to stop arbitrary filesystem / scheme sources from being
1434
+ * pulled without the caller opting in.
1435
+ */
738
1436
  allowUnsafeSource?: boolean;
1437
+ /**
1438
+ * The auth choice (the `--auth` flag): `lunora` (better-auth), `clerk`,
1439
+ * `workos`, `auth0` or `none`. Skips the interactive auth question; without a
1440
+ * TTY it is applied with its shipped defaults.
1441
+ */
1442
+ auth?: string;
739
1443
  /** When set, also scaffold a CI deploy pipeline for the given provider. */
740
1444
  ci?: CiProvider;
741
1445
  cwd?: string;
742
1446
  /**
743
- * Walk the whole flow — prompts, task list, next-steps, mascot — but make no
744
- * changes: skip the template fetch/copy, the feature applies, the dependency
745
- * install, and `git init`. Each skipped action logs a `would …` line instead.
746
- */
1447
+ * Walk the whole flow — prompts, task list, next-steps, mascot — but make no
1448
+ * changes: skip the template fetch/copy, the feature applies, the dependency
1449
+ * install, and `git init`. Each skipped action logs a `would …` line instead.
1450
+ */
747
1451
  dryRun?: boolean;
748
1452
  /**
749
- * Local directory containing the template subdirs (e.g. `vite/`,
750
- * `standalone/`). When provided, skips the network fetch entirely.
751
- * Useful for offline runs, the clean-machine smoke test, and unit tests.
752
- */
1453
+ * Local directory containing the template subdirs (e.g. `vite/`,
1454
+ * `standalone/`). When provided, skips the network fetch entirely.
1455
+ * Useful for offline runs, the clean-machine smoke test, and unit tests.
1456
+ */
753
1457
  from?: string;
754
1458
  /**
755
- * When true, configure Lunora into the CURRENT project (`cwd`) instead of
756
- * scaffolding a new directory. Finds an existing `vite.config.*` and
757
- * patches it via `patchViteConfig`, or creates a minimal one when absent.
758
- * All other scaffold options (`name`, `templateType`, `source`, `from`)
759
- * are ignored in this mode.
760
- */
1459
+ * When true, configure Lunora into the CURRENT project (`cwd`) instead of
1460
+ * scaffolding a new directory. Finds an existing `vite.config.*` and
1461
+ * patches it via `patchViteConfig`, or creates a minimal one when absent.
1462
+ * All other scaffold options (`name`, `templateType`, `source`, `from`)
1463
+ * are ignored in this mode.
1464
+ */
761
1465
  inPlace?: boolean;
762
1466
  /**
763
- * Inject the post-scaffold install offer's prompts (tests). When set, the
764
- * offer runs regardless of TTY: `confirmInstall` drives the yes/no, and
765
- * `selectManager` picks among the detected managers.
766
- */
1467
+ * Inject the post-scaffold install offer's prompts (tests). When set, the
1468
+ * offer runs regardless of TTY: `confirmInstall` drives the yes/no, and
1469
+ * `selectManager` picks among the detected managers.
1470
+ */
767
1471
  installPrompt?: {
768
1472
  confirmInstall: () => Promise<boolean>;
769
1473
  selectManager: (managers: ReadonlyArray<PackageManager>) => Promise<PackageManager>;
770
1474
  };
771
1475
  /**
772
- * Force the post-scaffold "add auth / email?" offer on (the `--interactive`
773
- * flag). When omitted, the offer runs only when stdin is a TTY. `--yes`
774
- * suppresses it regardless. Has no effect once {@link prompt} is injected.
775
- */
1476
+ * Force the post-scaffold "add auth / email?" offer on (the `--interactive`
1477
+ * flag). When omitted, the offer runs only when stdin is a TTY. `--yes`
1478
+ * suppresses it regardless. Has no effect once {@link prompt} is injected.
1479
+ */
776
1480
  interactive?: boolean;
1481
+ /**
1482
+ * Test seam for the lint/formatter multi-select. Separate from {@link prompt}
1483
+ * because that one is pinned to the feature-offer's value union — reusing it
1484
+ * here would only typecheck through a cast.
1485
+ */
1486
+ lintPrompt?: LintToolOfferDeps["multiSelect"];
777
1487
  logger: Logger;
778
1488
  name?: string;
779
1489
  /**
780
- * Local directory holding create-vite bases (one `template-&lt;id>/` subdir per
781
- * framework). When set with `vite`, the overlay copies the base from disk
782
- * instead of fetching `create-vite` over the network — offline mode + tests.
783
- */
1490
+ * Local directory holding create-vite bases (one `template-<id>/` subdir per
1491
+ * framework). When set with `vite`, the overlay copies the base from disk
1492
+ * instead of fetching `create-vite` over the network — offline mode + tests.
1493
+ */
784
1494
  overlayBaseFrom?: string;
785
- /** Probe for which package managers are installed (tests). Defaults to a real `&lt;pm> --version` check. */
1495
+ /** Probe for which package managers are installed (tests). Defaults to a real `<pm> --version` check. */
786
1496
  packageManagerProbe?: PackageManagerProbe;
787
1497
  /**
788
- * Inject the offer's prompts (tests). When set, the offer is treated as
789
- * interactive regardless of TTY, and these drive the feature multi-select,
790
- * the auth-provider sub-select, and the storage bucket-name text input.
791
- */
792
- prompt?: Pick<OfferDeps, "multiSelect" | "select" | "text">;
1498
+ * Inject the offer's prompts (tests). When set, the offer is treated as
1499
+ * interactive regardless of TTY, and these drive the feature multi-select,
1500
+ * the auth-provider sub-select, and the storage bucket-name text input.
1501
+ */
1502
+ prompt?: Partial<Pick<OfferDeps, "selectAuth">> & Pick<OfferDeps, "multiSelect" | "select" | "text">;
793
1503
  /**
794
- * Override the git ref (branch, tag, or commit) the default template source
795
- * is fetched from. Takes precedence over the version-derived ref. Ignored
796
- * when `source` or `from` is set.
797
- */
1504
+ * Override the git ref (branch, tag, or commit) the default template source
1505
+ * is fetched from. Takes precedence over the version-derived ref. Ignored
1506
+ * when `source` or `from` is set.
1507
+ */
798
1508
  ref?: string;
799
1509
  /** Local registry root for the offer's `runAddCommand` (offline / tests). Mirrors `from` but for registry items. */
800
1510
  registryFrom?: string;
801
1511
  /** Override the remote registry source base for the offer (default `gh:anolilab/lunora/registry`). */
802
1512
  registrySource?: string;
803
1513
  /**
804
- * Override the remote source giget downloads from. Default:
805
- * `gh:anolilab/lunora/templates/&lt;templateType>#&lt;ref>`, where `&lt;ref>` is
806
- * the `ref` option when set, else derived from the CLI version (pre-release
807
- * channels → their branch, stable → `main`). Tests typically use `from`
808
- * instead to skip the network.
809
- */
1514
+ * Override the remote source giget downloads from. Default:
1515
+ * `gh:anolilab/lunora/templates/<templateType>#<ref>`, where `<ref>` is
1516
+ * the `ref` option when set, else derived from the CLI version (pre-release
1517
+ * channels → their branch, stable → `main`). Tests typically use `from`
1518
+ * instead to skip the network.
1519
+ */
810
1520
  source?: string;
811
1521
  /** Spawner for the post-scaffold dependency install (tests inject a recording stub). Defaults to a real subprocess. */
812
1522
  spawner?: Spawner;
813
1523
  templateType?: Template;
814
1524
  /**
815
- * Scaffold via the **create-vite overlay** for this framework (`react`,
816
- * `vue`, `solid`, `svelte`, `vanilla`) instead of a bespoke template: fetch
817
- * the official create-vite base and apply the Lunora layer on top. Takes
818
- * precedence over `templateType`.
819
- */
1525
+ * Scaffold via the **create-vite overlay** for this framework (`react`,
1526
+ * `vue`, `solid`, `svelte`, `vanilla`) instead of a bespoke template: fetch
1527
+ * the official create-vite base and apply the Lunora layer on top. Takes
1528
+ * precedence over `templateType`.
1529
+ */
820
1530
  vite?: string;
821
1531
  /** Suppress the offer entirely (the `--yes` flag): scaffold only, print the later-setup hint. */
822
1532
  yes?: boolean;
@@ -826,8 +1536,12 @@ interface InitCommandResult {
826
1536
  files: ReadonlyArray<string>;
827
1537
  target: string;
828
1538
  }
1539
+ /**
1540
+ * `lunora init` entry: scaffold (in-place or a new directory), then — on success
1541
+ * — offer to add auth + email via the registry. The offer never affects the
1542
+ * scaffold's exit code.
1543
+ */
829
1544
  declare const runInitCommand: (options: InitCommandOptions) => Promise<InitCommandResult>;
830
- /** Narrow a raw `--template` value to a known {@link Template}. */
831
1545
  interface MigrateGenerateCommandOptions {
832
1546
  cwd?: string;
833
1547
  logger: Logger;
@@ -840,42 +1554,25 @@ interface MigrateGenerateCommandResult {
840
1554
  code: number;
841
1555
  /** Whether the diff was empty (no changes detected). */
842
1556
  empty: boolean;
1557
+ /** Why it failed, when the reason is known — the shared `CommandResult` contract. */
1558
+ error?: string;
843
1559
  /** Absolute path to the migration file (empty string when nothing was written). */
844
1560
  migrationFile: string;
845
1561
  }
846
1562
  declare const runMigrateGenerateCommand: (options: MigrateGenerateCommandOptions) => MigrateGenerateCommandResult;
847
- /** One catalog entry as `lunora registry list` reports it. */
848
- interface CatalogItem {
849
- description?: string;
850
- name: string;
851
- }
852
- /** A built index entry (catalog item plus its short `title`). */
853
- interface IndexItem extends CatalogItem {
854
- title?: string;
855
- }
856
- /** Names of the subdirectories under `root` that ship a `registry.json`. */
857
-
858
- /**
859
- * Build the catalog (`index.json` contents) from a local registry root by
860
- * reading every item's `registry.json`. Used by both `lunora registry build`
861
- * and the registry tests so the committed index can't drift from the item dirs.
862
- */
863
- declare const buildRegistryIndex: (root: string) => {
864
- items: IndexItem[];
865
- };
866
1563
  /** `lunora registry add` (one or more item names): scaffold items into the project. */
867
1564
  declare const runAddCommand: (options: AddCommandOptions) => Promise<AddCommandResult>;
868
1565
  /**
869
- * `lunora registry view` — inspect a registry item without installing it:
870
- * print its plan (files / deps / env vars) followed by the full contents of each
871
- * file it would scaffold. Resolves only the named item — no `requires` expansion.
872
- */
1566
+ * `lunora registry view` — inspect a registry item without installing it:
1567
+ * print its plan (files / deps / env vars) followed by the full contents of each
1568
+ * file it would scaffold. Resolves only the named item — no `requires` expansion.
1569
+ */
873
1570
  declare const runRegistryViewCommand: (options: AddCommandOptions) => Promise<AddCommandResult>;
874
1571
  /**
875
- * `lunora registry build` — regenerate `index.json` from the item directories
876
- * (the catalog `list` reads). With `--check`, verify the committed index matches
877
- * instead of rewriting it (exits non-zero on drift) — a CI guard.
878
- */
1572
+ * `lunora registry build` — regenerate `index.json` from the item directories
1573
+ * (the catalog `list` reads). With `--check`, verify the committed index matches
1574
+ * instead of rewriting it (exits non-zero on drift) — a CI guard.
1575
+ */
879
1576
  declare const runBuildIndexCommand: (options: AddCommandOptions) => Promise<AddCommandResult>;
880
1577
  /** Validate + narrow a parsed JSON value into a {@link RegistryManifest}. */
881
1578
  declare const parseManifest: (raw: unknown, itemName: string) => RegistryManifest;
@@ -893,23 +1590,6 @@ interface ResetCommandResult {
893
1590
  removed: ReadonlyArray<string>;
894
1591
  }
895
1592
  declare const runResetCommand: (options: ResetCommandOptions) => Promise<ResetCommandResult>;
896
- /** `lunora reset` handler (lazy-loaded via the command's `loader`). */
897
- /**
898
- * Tiny argv parser.
899
- *
900
- * Supports long options (`--name value`, `--name=value`, `--flag`), short
901
- * options (`-x value`, `-xvalue`), positional arguments (everything else, in
902
- * order), and a `--` terminator after which everything is positional.
903
- *
904
- * Intentionally small — replaces a full CLI library for the handful of
905
- * subcommands we need.
906
- */
907
- interface ParsedArgs {
908
- flags: Record<string, boolean>;
909
- options: Record<string, string>;
910
- positional: ReadonlyArray<string>;
911
- }
912
- declare const parseArgs: (argv: ReadonlyArray<string>, booleanFlags?: ReadonlySet<string>) => ParsedArgs;
913
1593
  type InsertSchemaExtensionResult = {
914
1594
  ok: true;
915
1595
  text: string;
@@ -918,12 +1598,12 @@ type InsertSchemaExtensionResult = {
918
1598
  reason: "already-applied" | "invalid-identifier" | "no-define-schema" | "non-object-argument";
919
1599
  };
920
1600
  /**
921
- * Append `.extend(&lt;key>.extension)` and a managed import to an existing
922
- * `lunora/schema.ts`. Idempotent: a second call for the same `key` returns
923
- * `already-applied` and leaves the text unchanged.
924
- * @param source the current `lunora/schema.ts` contents
925
- * @param key the registry item key (e.g. `"ratelimit"`)
926
- */
1601
+ * Append `.extend(<key>.extension)` and a managed import to an existing
1602
+ * `lunora/schema.ts`. Idempotent: a second call for the same `key` returns
1603
+ * `already-applied` and leaves the text unchanged.
1604
+ * @param source the current `lunora/schema.ts` contents
1605
+ * @param key the registry item key (e.g. `"ratelimit"`)
1606
+ */
927
1607
  declare const insertSchemaExtension: (source: string, key: string) => InsertSchemaExtensionResult;
928
1608
  /** Compact snapshot of a single global table — what we persist + diff. */
929
1609
  interface TableSnapshot {
@@ -933,6 +1613,20 @@ interface TableSnapshot {
933
1613
  name: string;
934
1614
  }
935
1615
  interface ColumnSnapshot {
1616
+ /**
1617
+ * The column's full validator shape — the SAME {@link FieldSnapshot} the
1618
+ * deploy gate diffs (`shared/schema-snapshot.ts`), not a second parallel
1619
+ * format.
1620
+ *
1621
+ * `sqlType` alone is lossy: `bigint`, `array`, `record`, `id`, `literal` and
1622
+ * `string` all map to the TEXT affinity, so `v.string()` → `v.bigint()` was
1623
+ * byte-identical here and `migrate generate` answered "no schema changes
1624
+ * detected" for a change `lunora prepare` blocks as breaking.
1625
+ *
1626
+ * Optional so a `.snapshot.json` written before this existed still parses —
1627
+ * it simply gets no deep check until the next generate rewrites it.
1628
+ */
1629
+ field?: FieldSnapshot;
936
1630
  /** True when the column accepts NULL (validator wrapped in v.optional). */
937
1631
  nullable: boolean;
938
1632
  /** SQLite type affinity, derived from the validator. */
@@ -966,26 +1660,42 @@ interface SchemaDiff {
966
1660
  unsupported: ReadonlyArray<UnsupportedEntry>;
967
1661
  }
968
1662
  /**
969
- * Map a Lunora validator kind to a SQLite type affinity — the canonical
970
- * `@lunora/d1/dialect` mapping. Re-exported under this name because
971
- * `schema-snapshot.ts` builds the persisted snapshot from it.
972
- */
1663
+ * Map a Lunora validator kind to a SQLite type affinity — the canonical
1664
+ * `@lunora/d1/dialect` mapping. Re-exported under this name because
1665
+ * `schema-snapshot.ts` builds the persisted snapshot from it.
1666
+ */
973
1667
  declare const validatorKindToSqlType: (kind: string) => ColumnSnapshot["sqlType"];
974
- /** Emit `CREATE TABLE` SQL for a new global table. */
1668
+ /**
1669
+ * Emit `CREATE TABLE` SQL for a new global table.
1670
+ *
1671
+ * Refuses a table past D1's column ceiling rather than writing SQL that
1672
+ * `lunora migrate up` will reject: the runtime auto-provisioner checks the same
1673
+ * number, and a migration file is the worse place to find out — the failure
1674
+ * lands later, against a database, with none of the schema context that names
1675
+ * which table and field to split.
1676
+ */
975
1677
  declare const renderCreateTable: (table: TableSnapshot) => string;
976
1678
  declare const renderDropTable: (tableName: string) => string;
1679
+ /**
1680
+ * `ALTER TABLE … ADD COLUMN`, always nullable. SQLite rejects `ADD COLUMN … NOT NULL` without a default on a table
1681
+ * that already has rows, and D1 is SQLite, so a NOT NULL add fails exactly when it matters. The runtime
1682
+ * auto-provisioner makes the same choice (see `alterGlobalTableDrift` in `@lunora/sql-store`), and the declared
1683
+ * `notNull` is still enforced on write. Existing rows read the new column as NULL until they are written, so for a
1684
+ * required column the statement is followed by a comment that says so and gives the backfill to run. The snapshot
1685
+ * records no default value, so the value is left for the author to fill in rather than guessed.
1686
+ */
977
1687
  declare const renderAddColumn: (tableName: string, columnName: string, column: ColumnSnapshot) => string;
978
1688
  declare const renderCreateIndex: (tableName: string, index: IndexSnapshot) => string;
979
1689
  declare const renderDropIndex: (tableName: string, indexName: string) => string;
980
1690
  /**
981
- * Compute a {@link SchemaDiff} from two snapshots. Pure function — no I/O.
982
- */
1691
+ * Compute a {@link SchemaDiff} from two snapshots. Pure function — no I/O.
1692
+ */
983
1693
  declare const diffSnapshots: (previous: SchemaSnapshot | undefined, next: SchemaSnapshot) => SchemaDiff;
984
1694
  /**
985
- * Render a complete migration file body from a diff. Includes a header,
986
- * each SQL statement, and (if any) a trailing comment block describing the
987
- * manual SQL the user needs to fill in for unsupported deltas.
988
- */
1695
+ * Render a complete migration file body from a diff. Includes a header,
1696
+ * each SQL statement, and (if any) a trailing comment block describing the
1697
+ * manual SQL the user needs to fill in for unsupported deltas.
1698
+ */
989
1699
  declare const renderMigrationFile: (name: string, diff: SchemaDiff, generatedAt: string) => string;
990
1700
  declare const schemaIrToSnapshot: (ir: SchemaIR) => SchemaSnapshot;
991
- export { type AddCommandOptions, type AddCommandResult, COMMANDS, type ColumnSnapshot, type CommandName, DEFAULT_IMPORT_BATCH_SIZE, type DeployCommandOptions, type DeployCommandResult, type DevCommandOptions, type DevCommandPlan, type DiffEntry, type ExportCommandOptions, type ExportCommandResult, type FetchLike, type ImportCommandOptions, type ImportCommandResult, type IndexSnapshot, type InitCommandOptions, type InitCommandResult, type InsertSchemaExtensionResult, type Logger, type MigrateGenerateCommandOptions, type MigrateGenerateCommandResult, type RecordedSpawn, type RegistryBinding, type RegistryFile, type RegistryManifest, type ResetCommandOptions, type ResetCommandResult, type RunCliOptions, type RunCommandOptions, type RunCommandResult, type SchemaDiff, type SchemaSnapshot, type SpawnDescriptor, type SpawnResult, type Spawner, type StreamingFetchLike, type TableSnapshot, type Template, type UnsupportedEntry, VERSION, buildRegistryIndex, createLogger, createRecordingSpawner, defaultSpawner, diffSnapshots, insertSchemaExtension, pail, parseArgs, parseManifest, planDevCommand, renderAddColumn, renderCreateIndex, renderCreateTable, renderDropIndex, renderDropTable, renderMigrationFile, runAddCommand, runBuildIndexCommand, runCli, runCodegenCommand, runDeployCommand, runDevCommand, runExportCommand, runImportCommand, runInitCommand, runMigrateGenerateCommand, runRegistryViewCommand, runResetCommand, runRpcCommand, schemaIrToSnapshot, validatorKindToSqlType };
1701
+ export { type AddCommandOptions, type AddCommandResult, type ColumnSnapshot, DEFAULT_IMPORT_BATCH_SIZE, type DeployCommandOptions, type DeployCommandResult, type DeployedIdentity, type DevCommandOptions, type DevCommandPlan, type DiffEntry, EXIT_CODE, type ExitCode, type ExportCommandOptions, type ExportCommandResult, type FetchLike, type ImportCommandOptions, type ImportCommandResult, type IndexSnapshot, type InitCommandOptions, type InitCommandResult, type InsertSchemaExtensionResult, type Logger, type MigrateGenerateCommandOptions, type MigrateGenerateCommandResult, type RecordedSpawn, type RegistryBinding, type RegistryFile, type RegistryManifest, type ResetCommandOptions, type ResetCommandResult, type RunCommandOptions, type RunCommandResult, type SchemaDiff, type SchemaSnapshot, type SpawnDescriptor, type SpawnResult, type Spawner, type StreamingFetchLike, type TableSnapshot, type Template, type UnsupportedEntry, buildRegistryIndex, createLogger, createRecordingSpawner, defaultSpawner, diffSnapshots, exitCodeForCode, exitCodeForError, exitCodeForStatus, insertSchemaExtension, pail, parseManifest, planDevCommand, renderAddColumn, renderCreateIndex, renderCreateTable, renderDropIndex, renderDropTable, renderMigrationFile, runAddCommand, runBuildIndexCommand, runCodegenCommand, runDeployCommand, runDevCommand, runExportCommand, runImportCommand, runInitCommand, runMigrateGenerateCommand, runRegistryViewCommand, runResetCommand, runRpcCommand, schemaIrToSnapshot, validatorKindToSqlType };