@lunora/cli 1.0.0-alpha.34 → 1.0.0-alpha.340

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 (130) hide show
  1. package/LICENSE.md +33 -0
  2. package/README.md +1 -1
  3. package/dist/bin.mjs +2 -10
  4. package/dist/index.d.mts +1007 -372
  5. package/dist/index.d.ts +1007 -372
  6. package/dist/index.mjs +1 -19
  7. package/dist/packem_chunks/dispatch.mjs +1 -0
  8. package/dist/packem_chunks/handler.mjs +1 -160
  9. package/dist/packem_chunks/handler10.mjs +2 -16
  10. package/dist/packem_chunks/handler11.mjs +1 -22
  11. package/dist/packem_chunks/handler12.mjs +1 -192
  12. package/dist/packem_chunks/handler13.mjs +1 -131
  13. package/dist/packem_chunks/handler14.mjs +1 -65
  14. package/dist/packem_chunks/handler15.mjs +3 -58
  15. package/dist/packem_chunks/handler16.mjs +1 -80
  16. package/dist/packem_chunks/handler17.mjs +1 -43
  17. package/dist/packem_chunks/handler18.mjs +1 -105
  18. package/dist/packem_chunks/handler19.mjs +7 -170
  19. package/dist/packem_chunks/handler2.mjs +1 -114
  20. package/dist/packem_chunks/handler20.mjs +1 -94
  21. package/dist/packem_chunks/handler21.mjs +1 -94
  22. package/dist/packem_chunks/handler22.mjs +3 -0
  23. package/dist/packem_chunks/handler23.mjs +3 -0
  24. package/dist/packem_chunks/handler24.mjs +1 -0
  25. package/dist/packem_chunks/handler25.mjs +2 -0
  26. package/dist/packem_chunks/handler26.mjs +1 -0
  27. package/dist/packem_chunks/handler27.mjs +99 -0
  28. package/dist/packem_chunks/handler28.mjs +10 -0
  29. package/dist/packem_chunks/handler3.mjs +1 -204
  30. package/dist/packem_chunks/handler4.mjs +1 -33
  31. package/dist/packem_chunks/handler5.mjs +1 -49
  32. package/dist/packem_chunks/handler6.mjs +3 -91
  33. package/dist/packem_chunks/handler7.mjs +1 -42
  34. package/dist/packem_chunks/handler8.mjs +1 -174
  35. package/dist/packem_chunks/handler9.mjs +1 -315
  36. package/dist/packem_chunks/runCodegenCommand.mjs +4 -52
  37. package/dist/packem_chunks/runDeployCommand.mjs +7 -594
  38. package/dist/packem_chunks/runDevCommand.mjs +2 -0
  39. package/dist/packem_chunks/runInitCommand.mjs +164 -1432
  40. package/dist/packem_chunks/runResetCommand.mjs +1 -41
  41. package/dist/packem_chunks/runRpcCommand.mjs +1 -68
  42. package/dist/packem_shared/COMMANDS-DRMcVnnw.mjs +1 -0
  43. package/dist/packem_shared/DEFAULT_IMPORT_BATCH_SIZE-CyIsI3S1.mjs +1 -0
  44. package/dist/packem_shared/EXIT_CODE-D_XCixv8.mjs +1 -0
  45. package/dist/packem_shared/admin-token-VdUnvnKW.mjs +1 -0
  46. package/dist/packem_shared/admin-url-DJB8P6Jh.mjs +1 -0
  47. package/dist/packem_shared/binding-manifest-file-CQ1eQYy1.mjs +2 -0
  48. package/dist/packem_shared/buildRegistryIndex-Dc8D8AR6.mjs +1 -0
  49. package/dist/packem_shared/catalog-CahzmDLV.mjs +1 -0
  50. package/dist/packem_shared/cli-CG_JgNKu.mjs +2 -0
  51. package/dist/packem_shared/codegen-error-AmH54ofi.mjs +3 -0
  52. package/dist/packem_shared/command-CAXl2A1S.mjs +1 -0
  53. package/dist/packem_shared/commands-Cg06JNO2.mjs +13 -0
  54. package/dist/packem_shared/createLogger-Cl18I8AX.mjs +2 -0
  55. package/dist/packem_shared/createRecordingSpawner-CYhdPBD5.mjs +1 -0
  56. package/dist/packem_shared/deploy-target-DCWwiuAe.mjs +1 -0
  57. package/dist/packem_shared/diffSnapshots-WWwx-KvZ.mjs +5 -0
  58. package/dist/packem_shared/docker-DpVxvYpL.mjs +1 -0
  59. package/dist/packem_shared/health-probe-Bw9JFfIy.mjs +1 -0
  60. package/dist/packem_shared/import-BRM1hs7j.mjs +12 -0
  61. package/dist/packem_shared/index-oHZBGBwB.mjs +1 -0
  62. package/dist/packem_shared/insertSchemaExtension-DuiV6cba.mjs +8 -0
  63. package/dist/packem_shared/lint-ignore-report-DKZagpqk.mjs +2 -0
  64. package/dist/packem_shared/open-url-EnKy--w-.mjs +1 -0
  65. package/dist/packem_shared/output-format-B4eQHi5y.mjs +2 -0
  66. package/dist/packem_shared/parseManifest-CwPTKdtS.mjs +1 -0
  67. package/dist/packem_shared/path-containment-CgxYZggb.mjs +1 -0
  68. package/dist/packem_shared/plan-Cqn2uvTo.mjs +5 -0
  69. package/dist/packem_shared/planDevCommand-KxbFGmBZ.mjs +1 -0
  70. package/dist/packem_shared/platform-diagnostics-Cn2g6Jh-.mjs +4 -0
  71. package/dist/packem_shared/prompt-cancelled-BvsNxg_Q.mjs +1 -0
  72. package/dist/packem_shared/render-lunora-error-C3OJY5wk.mjs +2 -0
  73. package/dist/packem_shared/resolve-DUCSc7jQ.mjs +5 -0
  74. package/dist/packem_shared/resolve-target-C_ZloTvd.mjs +1 -0
  75. package/dist/packem_shared/runAddCommand-BsOrlyfD.mjs +1 -0
  76. package/dist/packem_shared/runExportCommand-slAq5BCF.mjs +5 -0
  77. package/dist/packem_shared/runMigrateGenerateCommand-Ii_WMZEA.mjs +11 -0
  78. package/dist/packem_shared/schemaIrToSnapshot-BjK-0IRo.mjs +1 -0
  79. package/dist/packem_shared/secret-key-DsMeUoEg.mjs +1 -0
  80. package/dist/packem_shared/shared-D-zCOmgY.mjs +1 -0
  81. package/dist/packem_shared/storage-ChJtQ9E4.mjs +1 -0
  82. package/dist/packem_shared/tui-prompts-B3YwUhGw.mjs +4 -0
  83. package/dist/packem_shared/variables-acxcvVQa.mjs +1 -0
  84. package/dist/packem_shared/wrangler-name-Dsk5K1f-.mjs +1 -0
  85. package/dist/packem_shared/wrangler-secrets-Bqi6kLuq.mjs +1 -0
  86. package/package.json +39 -19
  87. package/skills/README.md +35 -17
  88. package/skills/lunora/SKILL.md +123 -9
  89. package/skills/lunora-create-package/SKILL.md +4 -3
  90. package/skills/lunora-deploy/SKILL.md +42 -11
  91. package/skills/lunora-functions/SKILL.md +213 -15
  92. package/skills/lunora-migration-helper/SKILL.md +74 -21
  93. package/skills/lunora-performance-audit/SKILL.md +78 -9
  94. package/skills/lunora-quickstart/SKILL.md +95 -27
  95. package/skills/lunora-realtime/SKILL.md +73 -39
  96. package/skills/lunora-setup-auth/SKILL.md +33 -6
  97. package/skills/lunora-setup-hyperdrive/SKILL.md +33 -13
  98. package/skills/lunora-setup-hyperdrive-global/SKILL.md +5 -0
  99. package/skills/lunora-setup-mail/SKILL.md +34 -28
  100. package/skills/lunora-setup-scheduler/SKILL.md +18 -14
  101. package/skills/lunora-setup-storage/SKILL.md +187 -27
  102. package/dist/packem_chunks/planDevCommand.mjs +0 -541
  103. package/dist/packem_chunks/runMigrateGenerateCommand.mjs +0 -397
  104. package/dist/packem_shared/COMMANDS-B0ftFD_3.mjs +0 -948
  105. package/dist/packem_shared/DEFAULT_IMPORT_BATCH_SIZE-Ck-2bU08.mjs +0 -244
  106. package/dist/packem_shared/admin-url-4UzT-CI4.mjs +0 -19
  107. package/dist/packem_shared/api-spec-CtA6ilu4.mjs +0 -13
  108. package/dist/packem_shared/buildRegistryIndex-BcYe607_.mjs +0 -38
  109. package/dist/packem_shared/codegen-error-DJG-ghs_.mjs +0 -31
  110. package/dist/packem_shared/command-D3lB_4Az.mjs +0 -19
  111. package/dist/packem_shared/commands-B-gR09Z_.mjs +0 -845
  112. package/dist/packem_shared/createLogger-B40gPzQo.mjs +0 -78
  113. package/dist/packem_shared/createRecordingSpawner-DxI3mebw.mjs +0 -43
  114. package/dist/packem_shared/detect-package-manager-DYp7n3mJ.mjs +0 -61
  115. package/dist/packem_shared/diffSnapshots-BeDvvNiF.mjs +0 -161
  116. package/dist/packem_shared/docker-hMQ97KSQ.mjs +0 -21
  117. package/dist/packem_shared/insertSchemaExtension-DAqbfr9Z.mjs +0 -64
  118. package/dist/packem_shared/open-url-Dfq6fAyT.mjs +0 -41
  119. package/dist/packem_shared/output-format-wUvAN6AL.mjs +0 -17
  120. package/dist/packem_shared/parseArgs-YXFuKdEk.mjs +0 -56
  121. package/dist/packem_shared/parseManifest--vZf2FY1.mjs +0 -94
  122. package/dist/packem_shared/prompt-cancelled-APzX1Im-.mjs +0 -9
  123. package/dist/packem_shared/resolve-target-qbsJ_5sF.mjs +0 -16
  124. package/dist/packem_shared/runAddCommand-bnY6-HKb.mjs +0 -4
  125. package/dist/packem_shared/schema-drift-gate-BtBt0as0.mjs +0 -79
  126. package/dist/packem_shared/schemaIrToSnapshot-DdsljJT-.mjs +0 -43
  127. package/dist/packem_shared/storage-BIsph-Vk.mjs +0 -84
  128. package/dist/packem_shared/tui-prompts-BjEN8XgP.mjs +0 -658
  129. package/dist/packem_shared/wrangler-name-cy4yhm9j.mjs +0 -12
  130. package/dist/packem_shared/wrangler-secrets-P2_ZUR-k.mjs +0 -47
@@ -1,594 +1,7 @@
1
- import { existsSync, readFileSync } from 'node:fs';
2
- import { runCodegen, discoverMigrations } from '@lunora/codegen';
3
- import { readLinkedProject, writeLinkedProject, validateWranglerProject, inferLunoraBindings, reconcileWranglerBindings, DEV_VARS_FILE, parseDevVariableEntries, isMintableSecretKey, findWranglerFile, readWranglerJsonc, discoverContainerInfo, packageNamesFromBindings, requiredSecrets, generateSecretValue } from '@lunora/config';
4
- import { join } from '@visulima/path';
5
- import { Spinner } from '@visulima/spinner';
6
- import { Project } from 'ts-morph';
7
- import { p as parseApiSpec } from '../packem_shared/api-spec-CtA6ilu4.mjs';
8
- import { r as readWranglerName } from '../packem_shared/wrangler-name-cy4yhm9j.mjs';
9
- import { d as defineHandler } from '../packem_shared/command-D3lB_4Az.mjs';
10
- import { a as isRailpackAvailable, i as isDockerAvailable } from '../packem_shared/docker-hMQ97KSQ.mjs';
11
- import { v as validateOutputFormat, i as isJsonFormat, p as printJson, l as loggerForFormat } from '../packem_shared/output-format-wUvAN6AL.mjs';
12
- import { containerBuildTag } from '@lunora/container';
13
- import { defaultSpawner } from '../packem_shared/createRecordingSpawner-DxI3mebw.mjs';
14
- import { r as resolveWorkerUrl } from '../packem_shared/resolve-target-qbsJ_5sF.mjs';
15
- import { r as runSchemaDriftGate } from '../packem_shared/schema-drift-gate-BtBt0as0.mjs';
16
- import { c as createTuiConfirm } from '../packem_shared/tui-prompts-BjEN8XgP.mjs';
17
- import { l as listRemoteSecrets } from '../packem_shared/wrangler-secrets-P2_ZUR-k.mjs';
18
- import { runMigrateDataCommand } from './runMigrateGenerateCommand.mjs';
19
-
20
- const WORKERS_DEV_URL = /https?:\/\/[^\s"'<>]+\.workers\.dev[^\s"'<>]*/u;
21
- const ANY_HTTPS_URL = /https:\/\/[^\s"'<>]+/u;
22
- const parseDeployedUrl = (output) => {
23
- const workersDev = WORKERS_DEV_URL.exec(output);
24
- if (workersDev) {
25
- return workersDev[0];
26
- }
27
- return ANY_HTTPS_URL.exec(output)?.[0];
28
- };
29
- const autoLinkFromDeployOutput = ({ cwd, env, logger, now, output }) => {
30
- if (output === void 0 || readLinkedProject(cwd) !== void 0) {
31
- return;
32
- }
33
- const url = parseDeployedUrl(output);
34
- if (url === void 0) {
35
- return;
36
- }
37
- try {
38
- const stamp = (now ?? (() => (/* @__PURE__ */ new Date()).toISOString()))();
39
- writeLinkedProject(cwd, { env, linkedAt: stamp, workerName: readWranglerName(cwd), workerUrl: url });
40
- logger.success(`link: recorded ${url} in .lunora/project.json (run \`lunora link\` to change)`);
41
- } catch {
42
- }
43
- };
44
-
45
- const renderDeploySummary = (inputs) => {
46
- const { cwd, env, logger, migrated } = inputs;
47
- try {
48
- const link = readLinkedProject(cwd);
49
- const workerName = link?.workerName ?? readWranglerName(cwd);
50
- logger.success("deploy complete");
51
- logger.info(` worker: ${workerName ?? "(see wrangler output above)"}`);
52
- if (env !== void 0) {
53
- logger.info(` env: ${env}`);
54
- }
55
- if (link?.workerUrl === void 0) {
56
- logger.info(" url: run `lunora link --url <https://your-worker>` to record it");
57
- } else {
58
- logger.info(` url: ${link.workerUrl}`);
59
- }
60
- if (migrated) {
61
- logger.info(" migrations: applied");
62
- }
63
- logger.info(" studio: lunora view --remote");
64
- logger.info(" logs: lunora logs");
65
- } catch {
66
- }
67
- };
68
-
69
- const buildRailpackImages = async (options) => {
70
- if (options.targets.length === 0) {
71
- return { builtTags: [], code: 0 };
72
- }
73
- if (!(options.railpackAvailable ?? isRailpackAvailable)()) {
74
- const message = "deploy blocked: a container uses `image: { build }` (Railpack), but Railpack isn't ready. Install the `railpack` CLI and start a BuildKit instance, e.g. `docker run --rm --privileged -d --name buildkit moby/buildkit` then `export BUILDKIT_HOST=docker-container://buildkit`. Alternatively switch the container's `image` to a Dockerfile path or a pre-built registry reference.";
75
- options.logger.error(message);
76
- return { builtTags: [], code: 1, error: message };
77
- }
78
- const spawner = options.spawner ?? defaultSpawner;
79
- const builtTags = [];
80
- for (const target of options.targets) {
81
- const tag = containerBuildTag(target.exportName);
82
- const build = { args: ["build", target.buildDir, "--name", tag], command: "railpack", cwd: options.cwd };
83
- const push = { args: ["exec", "wrangler", "containers", "push", tag], command: "pnpm", cwd: options.cwd };
84
- options.logger.info(`railpack: building "${target.exportName}" → ${tag} from ${target.buildDir}`);
85
- const buildResult = await spawner(build);
86
- if (buildResult.code !== 0) {
87
- const message = `railpack build failed for container "${target.exportName}" (${target.buildDir})`;
88
- options.logger.error(message);
89
- return { builtTags, code: buildResult.code, error: message };
90
- }
91
- options.logger.info(`railpack: pushing ${tag} to the Cloudflare Registry`);
92
- const pushResult = await spawner(push);
93
- if (pushResult.code !== 0) {
94
- const message = `wrangler containers push failed for "${target.exportName}" (${tag})`;
95
- options.logger.error(message);
96
- return { builtTags, code: pushResult.code, error: message };
97
- }
98
- builtTags.push(tag);
99
- }
100
- return { builtTags, code: 0 };
101
- };
102
-
103
- const D1_PLACEHOLDER_ID = "<replace-with-d1-create-id>";
104
- const ORIGIN_VAR_NAMES = ["LUNORA_ORIGIN_URL", "LUNORA_WORKER_ORIGIN", "AUTH_URL"];
105
- const isLocalhostUrl = (value) => {
106
- try {
107
- const { hostname } = new URL(value);
108
- return hostname === "localhost" || hostname === "127.0.0.1" || hostname === "::1" || hostname === "[::1]";
109
- } catch {
110
- return false;
111
- }
112
- };
113
- const isLocalImagePath = (image) => image.startsWith("./") || image.startsWith("../") || image.startsWith("/") || image.includes("Dockerfile");
114
- const checkContainerDockerPreflight = (cwd, logger, dockerAvailable) => {
115
- const wranglerPath = findWranglerFile(cwd);
116
- if (!wranglerPath) {
117
- return void 0;
118
- }
119
- const { parsed } = readWranglerJsonc(wranglerPath);
120
- const localImages = (parsed?.containers ?? []).filter((entry) => typeof entry?.image === "string" && isLocalImagePath(entry.image));
121
- if (localImages.length === 0 || dockerAvailable()) {
122
- return void 0;
123
- }
124
- const message = `deploy blocked: wrangler.jsonc declares ${String(localImages.length)} container(s) built from a local Dockerfile, but no Docker-compatible engine is available. Start Docker (or Colima), or point the container's \`image\` at a pre-built registry reference. Note: container images must target linux/amd64.`;
125
- logger.error(message);
126
- return message;
127
- };
128
- const resolveComposedWorkerEntry = (cwd) => existsSync(join(cwd, "src", "worker.ts")) ? "src/worker.ts" : void 0;
129
- const checkContainerSourcesExist = (cwd, logger) => {
130
- for (const container of discoverContainerInfo(cwd, "lunora").containers) {
131
- const { image } = container;
132
- if (image.kind === "dockerfile" && !existsSync(join(cwd, image.dockerfilePath))) {
133
- const message = `deploy blocked: container "${container.exportName}" references a Dockerfile at "${image.dockerfilePath}" that does not exist. Create it or fix the \`image\` path in lunora/containers.ts.`;
134
- logger.error(message);
135
- return message;
136
- }
137
- if (image.kind === "build" && !existsSync(join(cwd, image.buildDir))) {
138
- const message = `deploy blocked: container "${container.exportName}" references a Railpack build directory "${image.buildDir}" that does not exist. Create it or fix the \`image.build\` path in lunora/containers.ts.`;
139
- logger.error(message);
140
- return message;
141
- }
142
- }
143
- return void 0;
144
- };
145
- const isInteractive = (options) => {
146
- if (isJsonFormat(options.format)) {
147
- return false;
148
- }
149
- if (options.interactive !== void 0) {
150
- return options.interactive;
151
- }
152
- return process.stdout.isTTY && !process.env.CI;
153
- };
154
- const findD1PlaceholderBinding = (cwd) => {
155
- const wranglerPath = findWranglerFile(cwd);
156
- if (!wranglerPath) {
157
- return void 0;
158
- }
159
- const { parsed } = readWranglerJsonc(wranglerPath);
160
- if (!parsed) {
161
- return void 0;
162
- }
163
- const placeholder = (parsed.d1_databases ?? []).find((entry) => entry.database_id === D1_PLACEHOLDER_ID);
164
- return placeholder?.binding;
165
- };
166
- const buildContainerImages = async (cwd, options) => {
167
- const targets = discoverContainerInfo(cwd, "lunora").containers.filter((container) => container.image.kind === "build").map((container) => {
168
- return { buildDir: container.image.buildDir, exportName: container.exportName };
169
- });
170
- if (targets.length === 0) {
171
- return void 0;
172
- }
173
- const result = await buildRailpackImages({
174
- cwd,
175
- logger: options.logger,
176
- railpackAvailable: options.railpackAvailable,
177
- spawner: options.spawner,
178
- targets
179
- });
180
- return result.code === 0 ? void 0 : result.error ?? "railpack build failed";
181
- };
182
- const provisionBindings = async (cwd, logger) => {
183
- try {
184
- const inferred = await inferLunoraBindings({ projectRoot: cwd });
185
- const reconciled = reconcileWranglerBindings(cwd, inferred);
186
- if (reconciled.changed) {
187
- logger.success(`provisioned bindings: ${reconciled.added.join(", ")} → ${reconciled.wranglerPath ?? "wrangler.jsonc"}`);
188
- }
189
- for (const warning of reconciled.warnings) {
190
- logger.warn(warning);
191
- }
192
- } catch (error) {
193
- const message = error instanceof Error ? error.message : String(error);
194
- logger.warn(`binding inference skipped: ${message}`);
195
- }
196
- };
197
- const warnDevVariablesNotPushed = (cwd, logger) => {
198
- const devVariablesPath = join(cwd, DEV_VARS_FILE);
199
- if (!existsSync(devVariablesPath)) {
200
- return;
201
- }
202
- let keyCount;
203
- try {
204
- keyCount = parseDevVariableEntries(readFileSync(devVariablesPath, "utf8")).length;
205
- } catch {
206
- return;
207
- }
208
- if (keyCount === 0) {
209
- return;
210
- }
211
- logger.warn(
212
- `Note: \`lunora deploy\` does not push secrets. ${DEV_VARS_FILE} has ${String(keyCount)} key(s); if you changed them, run \`lunora env push --yes\` to update the deployed secrets.`
213
- );
214
- };
215
- const SECRET_LIKE_KEY = /(?:KEY|PASSWORD|SECRET|TOKEN)$/u;
216
- const resolveRequiredSecretKeys = async (cwd) => {
217
- let packages = [];
218
- try {
219
- packages = packageNamesFromBindings(await inferLunoraBindings({ projectRoot: cwd }));
220
- } catch {
221
- }
222
- const fromPackages = requiredSecrets(packages).map((entry) => entry.key);
223
- let fromLocal = [];
224
- try {
225
- const devVariablesPath = join(cwd, DEV_VARS_FILE);
226
- if (existsSync(devVariablesPath)) {
227
- fromLocal = parseDevVariableEntries(readFileSync(devVariablesPath, "utf8")).map((entry) => entry.key).filter((key) => SECRET_LIKE_KEY.test(key));
228
- }
229
- } catch {
230
- }
231
- return [.../* @__PURE__ */ new Set([...fromPackages, ...fromLocal])];
232
- };
233
- const pushMintableSecrets = async (cwd, options, keys) => {
234
- const { logger } = options;
235
- const spawner = options.spawner ?? defaultSpawner;
236
- const environmentFlag = options.env === void 0 ? "" : ` --env ${options.env}`;
237
- for (const key of keys) {
238
- const args = ["exec", "wrangler", "secret", "put", key];
239
- if (options.env !== void 0) {
240
- args.push("--env", options.env);
241
- }
242
- if (options.temporary === true) {
243
- args.push("--temporary");
244
- }
245
- const pushResult = await spawner({ args, command: "pnpm", cwd, input: generateSecretValue() });
246
- if (pushResult.code !== 0) {
247
- logger.error(
248
- `failed to push secret ${key} (exit ${String(pushResult.code)}); set it manually with \`wrangler secret put ${key}${environmentFlag}\`.`
249
- );
250
- return false;
251
- }
252
- logger.success(`generated + pushed ${key}`);
253
- }
254
- return true;
255
- };
256
- const offerMissingSecrets = async (cwd, options, interactive) => {
257
- if (options.dryRun === true || options.preview === true) {
258
- return void 0;
259
- }
260
- const { logger } = options;
261
- const environmentFlag = options.env === void 0 ? "" : ` --env ${options.env}`;
262
- let remote;
263
- try {
264
- remote = await (options.secretLister ?? listRemoteSecrets)({ cwd, env: options.env, temporary: options.temporary });
265
- } catch {
266
- return void 0;
267
- }
268
- if (!remote.ok) {
269
- return void 0;
270
- }
271
- const remoteNames = new Set(remote.names);
272
- const required = await resolveRequiredSecretKeys(cwd);
273
- const missing = required.filter((key) => !remoteNames.has(key));
274
- if (missing.length === 0) {
275
- return void 0;
276
- }
277
- if (!interactive) {
278
- return `missing required secret(s) on the deploy target: ${missing.join(", ")}. Set them with \`wrangler secret put <KEY>${environmentFlag}\` (or \`lunora env generate --set\` then \`lunora env push --yes${options.env === void 0 ? "" : " --prod"}\`), then re-deploy.`;
279
- }
280
- for (const key of missing.filter((name) => !isMintableSecretKey(name))) {
281
- logger.warn(`required secret ${key} is not set on the target — set it with: wrangler secret put ${key}${environmentFlag}`);
282
- }
283
- const mintable = missing.filter((key) => isMintableSecretKey(key));
284
- if (mintable.length === 0) {
285
- return void 0;
286
- }
287
- const confirm = options.secretConfirm ?? createTuiConfirm();
288
- if (await confirm(`${String(mintable.length)} required secret(s) not set on the target (${mintable.join(", ")}). Generate strong values and push them now?`)) {
289
- await pushMintableSecrets(cwd, options, mintable);
290
- return void 0;
291
- }
292
- logger.warn(
293
- `${String(mintable.length)} required secret(s) not set on the target: ${mintable.join(", ")}. Generate + push with \`lunora env generate --set\` then \`lunora env push --yes${options.env === void 0 ? "" : " --prod"}\`.`
294
- );
295
- return void 0;
296
- };
297
- const runPostDeployMigrations = async (options, cwd) => {
298
- const project = new Project({ skipAddingFilesFromTsConfig: true });
299
- const lunoraDirectory = join(cwd, "lunora");
300
- let migrations;
301
- try {
302
- migrations = discoverMigrations(project, lunoraDirectory);
303
- } catch (error) {
304
- const message = error instanceof Error ? error.message : String(error);
305
- options.logger.warn(`--migrate: could not discover migrations (${message}); skipping`);
306
- return 0;
307
- }
308
- if (migrations.length === 0) {
309
- options.logger.info("--migrate: no data migrations declared in lunora/");
310
- return 0;
311
- }
312
- options.logger.info(`--migrate: running ${String(migrations.length)} migration(s) against deployed worker`);
313
- for (const migration of migrations) {
314
- options.logger.info(`--migrate: up "${migration.id}" (table "${migration.table}")`);
315
- const migrateOptions = {
316
- cwd,
317
- fetchImpl: options.fetchImpl,
318
- id: migration.id,
319
- logger: options.logger,
320
- // A `--migrate-url` is always set by this point (guarded above), so this
321
- // is a production migration — gate it behind the operator's explicit
322
- // `--migrate-yes`/`--yes` rather than auto-confirming.
323
- prod: true,
324
- subcommand: "up",
325
- token: options.migrateToken,
326
- url: options.migrateUrl,
327
- yes: options.migrateYes === true
328
- };
329
- const migrateResult = await runMigrateDataCommand(migrateOptions);
330
- if (migrateResult.code !== 0) {
331
- options.logger.error(`--migrate: migration "${migration.id}" failed — see output above`);
332
- return migrateResult.code;
333
- }
334
- options.logger.success(`--migrate: "${migration.id}" applied`);
335
- }
336
- return 0;
337
- };
338
- const validateMigrateDeployPreflight = (options) => {
339
- if (!options.migrate || options.dryRun || options.preview) {
340
- return void 0;
341
- }
342
- if (options.migrateUrl === void 0) {
343
- const message = "--migrate requires --migrate-url <https://your-worker> — the deploy target URL is not captured automatically, refusing to default to localhost";
344
- options.logger.error(message);
345
- return message;
346
- }
347
- if (options.migrateYes !== true) {
348
- const message = "--migrate runs production data migrations after deploy. Re-run with --migrate-yes to confirm.";
349
- options.logger.error(message);
350
- return message;
351
- }
352
- if ((options.migrateToken ?? process.env.LUNORA_ADMIN_TOKEN) === void 0 || (options.migrateToken ?? process.env.LUNORA_ADMIN_TOKEN) === "") {
353
- const message = "admin token required for --migrate — pass --migrate-token or set LUNORA_ADMIN_TOKEN";
354
- options.logger.error(message);
355
- return message;
356
- }
357
- return void 0;
358
- };
359
- const runCodegenStep = (cwd, interactive, logger, apiSpec) => {
360
- let codegenSpinner;
361
- if (interactive) {
362
- codegenSpinner = new Spinner({ name: "dots" });
363
- codegenSpinner.start("running codegen");
364
- } else {
365
- logger.info("running codegen");
366
- }
367
- try {
368
- const result = runCodegen({ apiSpec, projectRoot: cwd });
369
- codegenSpinner?.succeed("codegen complete");
370
- if (!codegenSpinner) {
371
- logger.success("codegen complete");
372
- }
373
- return { result };
374
- } catch (error) {
375
- codegenSpinner?.failed("codegen failed");
376
- const message = error instanceof Error ? error.message : String(error);
377
- logger.error(`codegen failed: ${message}`);
378
- return { error: `codegen failed: ${message}` };
379
- }
380
- };
381
- const checkD1Placeholder = (cwd, logger) => {
382
- const placeholderBinding = findD1PlaceholderBinding(cwd);
383
- if (placeholderBinding === void 0) {
384
- return void 0;
385
- }
386
- const message = `deploy blocked: the "${placeholderBinding}" D1 binding has a placeholder database_id ("${D1_PLACEHOLDER_ID}"). Run \`wrangler d1 create <name>\` to create the database, then replace the placeholder in wrangler.jsonc with the real id before deploying.`;
387
- logger.error(message);
388
- return message;
389
- };
390
- const checkLocalhostOriginVariables = (cwd, logger) => {
391
- const wranglerPath = findWranglerFile(cwd);
392
- if (!wranglerPath) {
393
- return void 0;
394
- }
395
- const { parsed } = readWranglerJsonc(wranglerPath);
396
- const variables = parsed?.vars;
397
- if (!variables) {
398
- return void 0;
399
- }
400
- const offenders = ORIGIN_VAR_NAMES.filter((name) => typeof variables[name] === "string" && isLocalhostUrl(variables[name]));
401
- if (offenders.length === 0) {
402
- return void 0;
403
- }
404
- const message = `deploy blocked: ${offenders.join(", ")} in wrangler.jsonc point at localhost. A deployed Worker can't reach a loopback address, so this silently breaks scheduled-job dispatch / auth callbacks. Set each to the deployed worker's public URL (or move it to a secret with \`wrangler secret put\`) before deploying.`;
405
- logger.error(message);
406
- return message;
407
- };
408
- const finalizeSuccessfulDeploy = async (options, cwd, descriptor, validation, reblessSchemaBaseline) => {
409
- if (options.migrate) {
410
- const migrateCode = await runPostDeployMigrations(options, cwd);
411
- if (migrateCode === 0) {
412
- reblessSchemaBaseline?.();
413
- }
414
- return { code: migrateCode, descriptor, validation };
415
- }
416
- reblessSchemaBaseline?.();
417
- return { code: 0, descriptor, validation };
418
- };
419
- const runPreDeployGates = async (cwd, options) => {
420
- const d1Error = checkD1Placeholder(cwd, options.logger);
421
- if (d1Error !== void 0) {
422
- return d1Error;
423
- }
424
- const localhostOriginError = checkLocalhostOriginVariables(cwd, options.logger);
425
- if (localhostOriginError !== void 0) {
426
- return localhostOriginError;
427
- }
428
- const sourceError = checkContainerSourcesExist(cwd, options.logger);
429
- if (sourceError !== void 0) {
430
- return sourceError;
431
- }
432
- const dockerError = checkContainerDockerPreflight(cwd, options.logger, options.dockerAvailable ?? isDockerAvailable);
433
- if (dockerError !== void 0) {
434
- return dockerError;
435
- }
436
- return buildContainerImages(cwd, options);
437
- };
438
- const buildWranglerDeployArgs = (cwd, options) => {
439
- const args = options.preview ? ["exec", "wrangler", "versions", "upload"] : ["exec", "wrangler", "deploy"];
440
- const composedEntry = resolveComposedWorkerEntry(cwd);
441
- if (composedEntry !== void 0) {
442
- args.push(composedEntry);
443
- options.logger.info(`class-B composition: deploying ${composedEntry} (overrides wrangler main)`);
444
- }
445
- if (options.env !== void 0) {
446
- args.push("--env", options.env);
447
- }
448
- if (options.temporary) {
449
- args.push("--temporary");
450
- options.logger.info("temporary account: deploying to a short-lived Cloudflare account (~60min); wrangler will print a claim URL");
451
- }
452
- if (options.dryRun) {
453
- args.push("--dry-run");
454
- options.logger.info("dry run: validating + bundling without publishing");
455
- }
456
- if (options.outDir !== void 0) {
457
- args.push("--outdir", options.outDir, "--metafile");
458
- options.logger.info(`build artifact: emitting bundle to ${options.outDir}`);
459
- }
460
- return args;
461
- };
462
- const reportWranglerProblems = (validation, logger) => {
463
- if (validation.problems.length === 0) {
464
- return false;
465
- }
466
- logger.error("wrangler.jsonc validation failed:");
467
- for (const problem of validation.problems) {
468
- logger.error(` - ${problem}`);
469
- }
470
- return true;
471
- };
472
- const executeDeploy = async (options) => {
473
- const cwd = options.cwd ?? process.cwd();
474
- const interactive = isInteractive(options);
475
- let codegen;
476
- if (!options.skipCodegen) {
477
- const codegenStep = runCodegenStep(cwd, interactive, options.logger, options.apiSpec);
478
- if (codegenStep.error !== void 0) {
479
- return {
480
- code: 1,
481
- descriptor: void 0,
482
- error: codegenStep.error,
483
- validation: { problems: [], wranglerPath: void 0 }
484
- };
485
- }
486
- codegen = codegenStep.result;
487
- }
488
- let reblessSchemaBaseline;
489
- if (codegen !== void 0) {
490
- const gate = runSchemaDriftGate({
491
- allowDrift: options.allowSchemaDrift === true,
492
- codegen,
493
- logger: options.logger,
494
- updateBaseline: options.updateSchemaBaseline === true
495
- });
496
- if (gate.blocked) {
497
- return {
498
- code: 1,
499
- descriptor: void 0,
500
- error: "schema drift gate blocked deploy",
501
- schemaDrift: { blocked: true, reason: gate.reason },
502
- validation: { problems: [], wranglerPath: void 0 }
503
- };
504
- }
505
- reblessSchemaBaseline = gate.rebless;
506
- }
507
- await provisionBindings(cwd, options.logger);
508
- const migratePreflightError = validateMigrateDeployPreflight(options);
509
- if (migratePreflightError !== void 0) {
510
- return { code: 1, descriptor: void 0, error: migratePreflightError, validation: { problems: [], wranglerPath: void 0 } };
511
- }
512
- const preflightError = await runPreDeployGates(cwd, options);
513
- if (preflightError !== void 0) {
514
- return { code: 1, descriptor: void 0, error: preflightError, validation: { problems: [], wranglerPath: void 0 } };
515
- }
516
- const validation = validateWranglerProject({ projectRoot: cwd });
517
- if (reportWranglerProblems(validation, options.logger)) {
518
- return { code: 1, descriptor: void 0, error: "wrangler validation failed", validation };
519
- }
520
- warnDevVariablesNotPushed(cwd, options.logger);
521
- const secretAbort = await offerMissingSecrets(cwd, options, interactive);
522
- if (secretAbort !== void 0) {
523
- options.logger.error(secretAbort);
524
- return { code: 1, descriptor: void 0, error: secretAbort, validation };
525
- }
526
- const shouldAutoLink = !isJsonFormat(options.format) && options.dryRun !== true && options.preview !== true && readLinkedProject(cwd) === void 0;
527
- const descriptor = {
528
- args: buildWranglerDeployArgs(cwd, options),
529
- captureStdout: shouldAutoLink,
530
- command: "pnpm",
531
- cwd,
532
- // In `--format json` mode stdout is reserved for the single JSON document,
533
- // so route wrangler's progress + deployed-URL output to stderr instead.
534
- stdoutToStderr: isJsonFormat(options.format)
535
- };
536
- options.logger.info(`deploying via ${descriptor.command} ${descriptor.args.join(" ")}`);
537
- const spawner = options.spawner ?? defaultSpawner;
538
- const result = await spawner(descriptor);
539
- if (result.code !== 0) {
540
- return { code: result.code, descriptor, validation };
541
- }
542
- if (options.dryRun) {
543
- return { code: 0, descriptor, validation };
544
- }
545
- if (options.preview) {
546
- return { code: 0, descriptor, validation };
547
- }
548
- autoLinkFromDeployOutput({ cwd, env: options.env, logger: options.logger, output: result.stdout });
549
- return finalizeSuccessfulDeploy(options, cwd, descriptor, validation, reblessSchemaBaseline);
550
- };
551
- const runDeployCommand = async (options) => {
552
- const formatError = validateOutputFormat("deploy", options.format);
553
- if (formatError !== void 0) {
554
- options.logger.error(formatError);
555
- return { code: 1, descriptor: void 0, error: formatError, validation: { problems: [], wranglerPath: void 0 } };
556
- }
557
- const result = await executeDeploy({ ...options, logger: loggerForFormat(options.format, options.logger) });
558
- if (isJsonFormat(options.format)) {
559
- printJson(result);
560
- return result;
561
- }
562
- if (result.code === 0 && options.dryRun !== true && options.preview !== true) {
563
- renderDeploySummary({ cwd: options.cwd ?? process.cwd(), env: options.env, logger: options.logger, migrated: options.migrate === true });
564
- } else if (result.code === 0 && options.preview === true) {
565
- options.logger.success("preview version uploaded — see the preview URL in the wrangler output above");
566
- }
567
- return result;
568
- };
569
- const execute = defineHandler(async ({ cwd, logger, options }) => {
570
- const result = await runDeployCommand({
571
- allowSchemaDrift: options.allowSchemaDrift === true,
572
- apiSpec: parseApiSpec(options.apiSpec),
573
- cwd,
574
- dryRun: options.dryRun === true,
575
- env: options.env,
576
- format: options.format,
577
- logger,
578
- migrate: options.migrate === true,
579
- migrateToken: options.migrateToken,
580
- // Fall back to the `.lunora/project.json` link so a linked checkout no
581
- // longer needs --migrate-url repeated on every `deploy --migrate`.
582
- migrateUrl: resolveWorkerUrl({ cwd, url: options.migrateUrl }),
583
- migrateYes: options.migrateYes === true,
584
- preview: options.preview === true,
585
- // `--prebuilt` trusts a prior `lunora build`/`prepare`: skip codegen (and
586
- // thus the drift gate, which has no fresh snapshot to measure).
587
- skipCodegen: options.prebuilt === true,
588
- temporary: options.temporary === true,
589
- updateSchemaBaseline: options.updateSchemaBaseline === true
590
- });
591
- return { code: result.code };
592
- });
593
-
594
- export { execute, runDeployCommand };
1
+ import{join as z,dirname as J}from"node:path";import{discoverMigrations as X,readServiceBindings as Q,runCodegen as Z}from"@lunora/codegen";import{readLinkedProject as N,execArgsFor as I,detectPackageManager as b,discoverContainerInfo as L,COMPOSED_WORKER_ENTRY as C,writeLinkedProject as ee,discoverSchemaInfo as re,DEV_VARS_FILE as w,parseDevVariableEntries as U,isMintableSecretKey as P,packageNamesFromBindings as te,inferLunoraBindings as F,resolveSchemaDirectory as O,requiredSecrets as ne,generateSecretValue as ae,toolchainExecArgs as E,upsertDevVariableLine as oe,writeDevVariablesFileAtomically as ie,resolveDeployDriver as R,planToolchainInvocation as W,runPostCodegenHook as se}from"@lunora/config";import{findWranglerFile as M,readWranglerJsonc as ce,mergeWranglerEnvironment as le,validateWranglerProject as de,reconcileWranglerBindings as ue,reconcileWranglerCompatibilityDate as ge,reconcileWranglerCrons as me,describePreservedCrons as fe}from"@lunora/config/cloudflare";import{Spinner as he}from"@visulima/spinner";import{r as ve,a as pe,e as ye}from"../packem_shared/platform-diagnostics-Cn2g6Jh-.mjs";import{p as we,a as ke}from"../packem_shared/deploy-target-DCWwiuAe.mjs";import{w as be}from"../packem_shared/binding-manifest-file-CQ1eQYy1.mjs";import{d as $e}from"../packem_shared/command-CAXl2A1S.mjs";import{r as A}from"../packem_shared/wrangler-name-Dsk5K1f-.mjs";import{EXIT_CODE as h}from"../packem_shared/EXIT_CODE-D_XCixv8.mjs";import{containerBuildTag as Se}from"@lunora/container";import{a as De,i as Ee}from"../packem_shared/docker-DpVxvYpL.mjs";import{defaultSpawner as $}from"../packem_shared/createRecordingSpawner-CYhdPBD5.mjs";import{r as B}from"../packem_shared/resolve-target-C_ZloTvd.mjs";import{p as Re,H as Ae,a as je,r as Ce}from"../packem_shared/health-probe-Bw9JFfIy.mjs";import{existsSync as p,readFileSync as k,writeFileSync as V}from"node:fs";import{join as y}from"@visulima/path";import{Project as Pe}from"ts-morph";import{m as xe,e as Te,i as _e}from"../packem_shared/secret-key-DsMeUoEg.mjs";import{runMigrateDataCommand as Ne}from"../packem_shared/runMigrateGenerateCommand-Ii_WMZEA.mjs";import{c as Ie}from"../packem_shared/tui-prompts-B3YwUhGw.mjs";import{l as Le}from"../packem_shared/wrangler-secrets-Bqi6kLuq.mjs";const Ue=e=>{const{cwd:r,env:a,logger:t,mintedSecretsFile:n}=e;try{const o=N(r),i=o?.workerName??A(r),s=e.url??o?.workerUrl;t.success("deploy complete"),t.info(` worker: ${i??"(see wrangler output above)"}`),a!==void 0&&t.info(` env: ${a}`),s===void 0?t.info(" url: run `lunora link --url <https://your-worker>` to record it"):t.info(` url: ${s}`),n!==void 0&&t.info(` secrets: generated value(s) recorded in ${n}`),e.logsAvailable&&t.info(" logs: lunora logs")}catch{}},Fe=async e=>{if(e.targets.length===0)return{builtTags:[],code:0};if(!(e.railpackAvailable??De)()){const t="deploy blocked: a container uses `image: { build }` (Railpack), but Railpack isn't ready. Install the `railpack` CLI and start a BuildKit instance, e.g. `docker run --rm --privileged -d --name buildkit moby/buildkit` then `export BUILDKIT_HOST=docker-container://buildkit`. Alternatively switch the container's `image` to a Dockerfile path or a pre-built registry reference.";return e.logger.error(t),{builtTags:[],code:1,error:t}}const r=e.spawner??$,a=[];for(const t of e.targets){const n=Se(t.exportName),o={args:["build",t.buildDir,"--name",n],command:"railpack",cwd:e.cwd},i=I(b(e.cwd),"wrangler",["containers","push",n]),s={args:i.args,command:i.command,cwd:e.cwd};e.logger.info(`railpack: building "${t.exportName}" → ${n} from ${t.buildDir}`);const c=await r(o);if(c.code!==0){const l=`railpack build failed for container "${t.exportName}" (${t.buildDir})`;return e.logger.error(l),{builtTags:a,code:c.code,error:l}}e.logger.info(`railpack: pushing ${n} to the Cloudflare Registry`);const d=await r(s);if(d.code!==0){const l=`wrangler containers push failed for "${t.exportName}" (${n})`;return e.logger.error(l),{builtTags:a,code:d.code,error:l}}a.push(n)}return{builtTags:a,code:0}},Oe=e=>{const a=[M(e),z(e,"package.json")].filter(t=>t!==void 0&&p(t)).map(t=>[t,k(t,"utf8")]);return()=>{for(const[t,n]of a)k(t,"utf8")!==n&&V(t,n,"utf8")}},H="<replace-with-d1-create-id>",x=e=>Array.isArray(e)?e.filter(r=>r!=null):void 0,j=(e,r)=>{const a=M(e);if(!a)return;const{parsed:t}=ce(a);if(t===void 0)return;const{error:n,merged:o}=le(t,r),i=n===void 0?o:t,{containers:s,d1_databases:c,vars:d}=i;return{containers:x(s),d1_databases:x(c),vars:typeof d=="object"&&d!==null&&!Array.isArray(d)?d:void 0}},We=/^127(?:\.\d{1,3}){3}$/,Me=e=>{try{const{hostname:r}=new URL(e);return r==="localhost"||We.test(r)||r==="::1"||r==="[::1]"}catch{return!1}},Be=e=>e.startsWith("./")||e.startsWith("../")||e.startsWith("/")||e.includes("Dockerfile"),Ve=(e,r,a,t="deploy",n)=>{const o=(j(e,n)?.containers??[]).filter(s=>typeof s?.image=="string"&&Be(s.image));if(o.length===0||a())return;const i=`${t} blocked: wrangler.jsonc declares ${String(o.length)} container(s) built from a local Dockerfile, but no Docker-compatible engine is available. Start Docker (or Colima), or point the container's \`image\` at a pre-built registry reference. Note: container images must target linux/amd64.`;return r.error(i),i},G=e=>p(y(e,C))?C:void 0,He=(e,r,a="deploy")=>{for(const t of L(e,"lunora").containers){const n=t.schedulingPolicy===void 0?t.image:void 0,i=[...n?.kind==="dockerfile"?[{field:"image",path:n.dockerfilePath}]:[],...Object.entries(t.schedulingPolicy==="durable_object"?t.images??{}:{}).flatMap(([s,c])=>c.kind==="dockerfile"?[{field:`images["${s}"]`,path:c.dockerfilePath}]:[])].find(s=>!p(y(e,s.path)));if(i!==void 0){const s=`${a} blocked: container "${t.exportName}" references a Dockerfile at "${i.path}" that does not exist. Create it or fix the \`${i.field}\` path in lunora/containers.ts.`;return r.error(s),s}if(n?.kind==="build"&&!p(y(e,n.buildDir))){const s=`${a} blocked: container "${t.exportName}" references a Railpack build directory "${n.buildDir}" that does not exist. Create it or fix the \`image.build\` path in lunora/containers.ts.`;return r.error(s),s}}},Ge=(e,r)=>(j(e,r)?.d1_databases??[]).find(a=>a.database_id===H)?.binding,Ke=e=>{if(!e.migrate||e.dryRun||e.preview)return;if(e.migrateUrl===void 0){const a="--migrate requires --migrate-url <https://your-worker> — the deploy target URL is only known after wrangler runs, and this gate runs before it; refusing to default to localhost";return e.logger.error(a),a}if(e.migrateYes!==!0){const a="--migrate runs production data migrations after deploy. Re-run with --migrate-yes to confirm.";return e.logger.error(a),a}const r=e.migrateToken??process.env.LUNORA_ADMIN_TOKEN;if(r===void 0||r===""){const a="admin token required for --migrate — pass --migrate-token or set LUNORA_ADMIN_TOKEN";return e.logger.error(a),a}},qe=(e,r,a="deploy",t)=>{const n=Ge(e,t);if(n===void 0)return;const o=`${a} blocked: the "${n}" D1 binding has a placeholder database_id ("${H}"). Run \`wrangler d1 create <name>\` to create the database, then replace the placeholder in wrangler.jsonc with the real id before deploying.`;return r.error(o),o},Ye=(e,r,a="deploy",t)=>{const n=j(e,t)?.vars;if(!n)return;const o=Object.entries(n).filter(([,s])=>typeof s=="string"&&Me(s)).map(([s])=>s).toSorted((s,c)=>s.localeCompare(c));if(o.length===0)return;const i=`${a} blocked: ${o.join(", ")} in wrangler.jsonc point at localhost. A deployed Worker can't reach a loopback address, so this silently breaks scheduled-job dispatch, reverse cross-shard relations, and auth callbacks. Set each to the deployed worker's public URL (or move it to a secret with \`wrangler secret put\`) before deploying.`;return r.error(i),i},ze=(e,r,a)=>{const t=qe(e,r.logger,a,r.env);if(t!==void 0)return{code:h.USAGE,error:t};const n=Ye(e,r.logger,a,r.env);if(n!==void 0)return{code:h.USAGE,error:n};const o=He(e,r.logger,a);if(o!==void 0)return{code:h.USAGE,error:o};const i=Ve(e,r.logger,r.dockerAvailable??Ee,a,r.env);return i===void 0?void 0:{code:h.MISSING_DEPENDENCY,error:i}},Je=/https?:\/\/[^\s"'<>]+\.workers\.dev[^\s"'<>]*/u,Xe=/https:\/\/[^\s"'<>]+/u,Qe=e=>{if(e===void 0)return;const r=Je.exec(e);return r?r[0]:Xe.exec(e)?.[0]},T=e=>e===void 0?"":` (--env ${e})`,Ze=({cwd:e,env:r,logger:a,now:t,url:n})=>{if(n!==void 0)try{const o=N(e);if(o!==void 0){if(o.workerUrl===n&&o.env===r)return;a.warn(`link: .lunora/project.json records ${o.workerUrl??"(no url)"}${T(o.env)}, but this deploy published ${n}${T(r)}. Keeping the recorded value — run \`lunora link --url ${n}${r===void 0?"":` --env ${r}`}\` to update it.`);return}const i=(t??(()=>new Date().toISOString()))();ee(e,{env:r,linkedAt:i,workerName:A(e),workerUrl:n}),a.success(`link: recorded ${n} in .lunora/project.json (run \`lunora link\` to change)`)}catch{}},er=async(e,r)=>{const a=new Pe({skipAddingFilesFromTsConfig:!0}),t=y(r,"lunora");let n;try{n=X(a,t)}catch(o){const i=o instanceof Error?o.message:String(o);return e.logger.warn(`--migrate: could not discover migrations (${i}); skipping`),0}if(n.length===0)return e.logger.info("--migrate: no data migrations declared in lunora/"),0;e.logger.info(`--migrate: running ${String(n.length)} migration(s) against deployed worker`);for(const o of n){e.logger.info(`--migrate: up "${o.id}" (table "${o.table}")`);const i={cwd:r,fetchImpl:e.fetchImpl,id:o.id,logger:e.logger,prod:!0,subcommand:"up",token:e.migrateToken,url:e.migrateUrl,yes:e.migrateYes===!0},s=await Ne(i);if(s.code!==0)return e.logger.error(`--migrate: migration "${o.id}" failed — see output above`),s.code;e.logger.success(`--migrate: "${o.id}" applied`)}return 0},rr=async(e,r)=>{const{info:a}=re(r,"lunora"),t=a?.vectorMetadata??[];if(t.length===0)return;const n=[];for(const s of t){const c=xe(s.kind);if(c===void 0){e.logger.warn(`vector index "${s.index}" declares metadata "${s.property}", whose column type cannot be filtered on in Vectorize — it is stored with each vector but no filter will match it.`);continue}n.push({index:s.index,property:s.property,type:c})}if(n.length===0)return;const i=(await Te({cwd:r,entries:n,exec:I(b(r),"wrangler",[]),logger:e.logger,spawner:e.spawner??$})).filter(s=>s.status!=="failed").length;i>0&&e.logger.success(`vectorize metadata indexes ready: ${String(i)}/${String(n.length)}`)},_=5,tr=2e3,nr=async(e,r,a)=>{if(e.healthCheck!==!0)return;const t=a??B({cwd:r,env:e.env});if(t===void 0){const o="--health-check: the deploy succeeded, but no URL to probe could be resolved — wrangler's output carried none and this checkout has no link for this environment. Run `lunora link --url <https://your-worker>` and re-deploy, or drop --health-check.";return e.logger.error(o),{error:o,ok:!1,url:""}}const n=await Re({attempts:_,baseUrl:t,delayMs:tr,fetchImpl:e.healthFetch,paths:[Ae,je],sleep:e.healthSleep});return n.error===void 0?(e.logger.success(`health check ok (${n.url})`),{ok:!0,url:n.url}):(e.logger.error(`--health-check: the deploy succeeded, but the new version did not answer after ${String(_)} attempt(s) — ${n.error}`),{error:n.error,ok:!1,url:n.url})},ar=async(e,r,a,t,n,o)=>{await rr(e,r);const i=e.migrate?await er(e,r):0;return i===0&&n?.(),{code:i,descriptor:a,mintedSecretsFile:o,validation:t}},or=async({cwd:e,descriptor:r,mintedSecretsFile:a,options:t,reblessSchemaBaseline:n,stdout:o,validation:i})=>{const s={deployedAt:new Date().toISOString(),dryRun:t.dryRun===!0,env:t.env,preview:t.preview===!0,url:t.dryRun===!0?void 0:Qe(o),workerName:A(e)};if(t.dryRun===!0||t.preview===!0)return t.healthCheck===!0&&t.logger.warn(`--health-check skipped: ${t.dryRun===!0?"a dry run publishes nothing":"a preview version serves no live traffic"}`),{code:0,deployment:s,descriptor:r,mintedSecretsFile:a,validation:i};t.temporary!==!0&&Ze({cwd:e,env:t.env,logger:t.logger,url:s.url});const c=await nr(t,e,s.url);return c?.error!==void 0?{code:h.UNAVAILABLE,deployment:s,descriptor:r,healthCheck:c,mintedSecretsFile:a,validation:i}:{...await ar(t,e,r,i,n,a),deployment:s,healthCheck:c}},ir=(e,r,a)=>{const t=y(e,w);if(!p(t))return;let n;try{n=U(k(t,"utf8")).length}catch{return}if(n===0)return;const o=a.toolchain?.secretPut!==void 0;r.warn(o?`Note: \`lunora deploy\` does not push secrets. ${w} has ${String(n)} key(s); if you changed them, run \`lunora env push --yes\` to update the deployed secrets.`:`Note: ${a.name} deploys read no secrets. ${w} has ${String(n)} key(s) that only the dev server sees; put the values the deployed worker needs in wrangler \`vars\`.`)},sr=async e=>{let r=[];try{r=te(await F({projectRoot:e,schemaDir:O(e)}))}catch{}const a=ne(r).map(n=>n.key);let t=[];try{const n=y(e,w);p(n)&&(t=U(k(n,"utf8")).map(o=>o.key).filter(o=>_e(o)))}catch{}return[...new Set([...a,...t])]},cr=async(e,r,a,t)=>{const{logger:n}=r,o=r.spawner??$,i=b(e),s=r.env===void 0?"":` --env ${r.env}`,c=t.toolchain?.secretPut;if(c===void 0)return n.error(`deploy target "${t.id}" has no secret store; cannot push secrets`),{minted:[],ok:!1};const d=[];for(const l of a){const m=ae(),u=c({environment:r.env,key:l,temporary:r.temporary}),g=E(i,u),f=await o({args:g.args,command:g.command,cwd:e,input:m});if(f.code!==0)return n.error(`failed to push secret ${l} (exit ${String(f.code)}); set it manually with \`wrangler secret put ${l}${s}\`.`),{minted:d,ok:!1};d.push({key:l,value:m}),n.success(`generated + pushed ${l}`)}return{minted:d,ok:!0}},lr=/^[\w-]+$/u,S=[".dev.vars",".dev.vars.*","!.dev.vars.example"],dr=/\r?\n/u,ur=(e,r)=>{const a=y(e,".gitignore");try{const t=p(a)?k(a,"utf8"):"",n=new Set(t.split(dr).map(c=>c.trim())),o=S.filter(c=>!n.has(c));if(o.length===0)return;const i=o.some(c=>!c.startsWith("!"))?[...o.filter(c=>!c.startsWith("!")),...S.filter(c=>c.startsWith("!"))]:o,s=t.length>0&&!t.endsWith(`
2
+ `)?`
3
+ `:"";V(a,`${t}${s}
4
+ # Lunora — never commit a minted secret
5
+ ${i.join(`
6
+ `)}
7
+ `,"utf8"),r.info(`.gitignore: added ${o.join(", ")} so the recorded secret cannot be committed`)}catch(t){r.warn(`could not update .gitignore (${t instanceof Error?t.message:String(t)}) — add \`${S.join("` and `")}\` by hand before committing.`)}},gr=(e,r,a)=>{if(a.length===0)return;const t=a.map(s=>s.key).join(", ");if(r.env!==void 0&&!lr.test(r.env)){r.logger.warn(`${t}: minted and pushed for --env ${r.env}, but "${r.env}" isn't a safe filename fragment — the value could not be recorded. Capture it manually if you need it again.`);return}const n=r.env===void 0?w:`${w}.${r.env}`;ur(e,r.logger);const o=y(e,n);let i=p(o)?k(o,"utf8"):"";for(const s of a)i=oe(i,s.key,s.value);return ie(o,i),r.logger.success(r.env===void 0?`${t}: value(s) recorded in ${n}`:`${t}: value(s) recorded in ${n} (kept separate from ${w} so \`lunora dev\` and a plain \`lunora env push\` don't inherit the --env ${r.env} value)`),n},mr=async(e,r,a,t)=>{if(r.dryRun===!0||r.preview===!0)return{};const{logger:n}=r,o=r.env===void 0?"":` --env ${r.env}`;let i;try{i=await(r.secretLister??Le)({cwd:e,env:r.env,temporary:r.temporary})}catch{return{}}if(!i.ok)return{};const s=new Set(i.names),d=(await sr(e)).filter(u=>!s.has(u));if(d.length===0)return{};if(!a)return{error:`missing required secret(s) on the deploy target: ${d.join(", ")}. Set them with \`wrangler secret put <KEY>${o}\` (or \`lunora env generate --set\` then \`lunora env push --yes${o}\`), then re-deploy.`};for(const u of d.filter(g=>!P(g)))n.warn(`required secret ${u} is not set on the target — set it with: wrangler secret put ${u}${o}`);const l=d.filter(u=>P(u));if(l.length===0)return{};if(await(r.secretConfirm??Ie())(`${String(l.length)} required secret(s) not set on the target (${l.join(", ")}). Generate strong values and push them now?`)){const{minted:u,ok:g}=await cr(e,r,l,t),f=gr(e,r,u);return g?{mintedSecretsFile:f}:{error:"failed to push required secret(s) — set them manually and re-deploy",mintedSecretsFile:f}}return n.warn(`${String(l.length)} required secret(s) not set on the target: ${l.join(", ")}. Generate + push with \`lunora env generate --set\` then \`lunora env push --yes${o}\`.`),{}},K=e=>e.format==="json"?!1:e.interactive!==void 0?e.interactive:process.stdout.isTTY&&!process.env.CI,fr=async(e,r)=>{if(r.dryRun===!0)return;const a=L(e,"lunora").containers.flatMap(n=>n.schedulingPolicy===void 0&&n.image.kind==="build"?[{buildDir:n.image.buildDir,exportName:n.exportName}]:[]);if(a.length===0)return;const t=await Fe({cwd:e,logger:r.logger,railpackAvailable:r.railpackAvailable,spawner:r.spawner,targets:a});return t.code===0?void 0:t.error??"railpack build failed"},hr=(e,r,a)=>{if(a!==void 0)try{const t=me(e,a);t.changed&&r.success(`synced ${String(a.length)} cron trigger(s) → ${t.wranglerPath??"wrangler.jsonc"}`);for(const o of t.warnings)r.warn(o);const n=fe(t.preserved);n!==void 0&&r.info(n)}catch(t){const n=t instanceof Error?t.message:String(t);r.warn(`cron trigger sync skipped: ${n}`)}},vr=async(e,r,a,t,n)=>{try{R(t);const o=await F({projectRoot:e,schemaDir:O(e)}),i=ue(e,o,n),s=i.wranglerPath??"wrangler.jsonc";if(i.added.length>0&&r.success(`provisioned bindings: ${i.added.join(", ")} → ${s}`),i.updated.length>0&&r.success(`updated bindings: ${i.updated.join(", ")} → ${s}`),i.devConfig!==void 0){const{added:c,path:d,updated:l}=i.devConfig;r.success(`dev sidecar bindings: ${[...c,...l].join(", ")} → ${d}`)}for(const c of i.warnings)r.warn(c)}catch(o){const i=o instanceof Error?o.message:String(o);r.warn(`binding inference skipped: ${i}`)}try{const o=ge(e);o.changed&&r.success(`bumped compatibility_date to ${o.date??"unknown"} (Workers Cache enabled) → ${o.wranglerPath??"wrangler.jsonc"}`)}catch(o){const i=o instanceof Error?o.message:String(o);r.warn(`compatibility date sync skipped: ${i}`)}hr(e,r,a)},pr=async(e,r,a,t,n,o,i,s)=>{let c;r?(c=new he({name:"dots"}),c.start("running codegen")):a.info("running codegen");try{const d=Z({apiSpec:t,projectRoot:e,target:n});c?.succeed("codegen complete"),c||a.success("codegen complete");const l=pe(d.platformDiagnostics,a);if(l.errors.length>0)return{error:l.errors.join("; ")};const{errorAdvisories:m,names:u,shouldBlock:g}=ye(d.advisories,s);if(g){const v=`${m.length.toString()} ERROR-level ${m.length===1?"advisory":"advisories"} (${u.join(", ")}). Pass --no-strict-advisories to downgrade this to a warning and continue.`;return a.error(v),{error:v}}const f=await se({cwd:e,logger:a,spawner:o,stdoutToStderr:i});return f.error!==void 0?{error:f.error}:{result:d}}catch(d){c?.failed("codegen failed");const l=d instanceof Error?d.message:String(d);return a.error(`codegen failed: ${l}`),{error:`codegen failed: ${l}`}}},yr=(e,r)=>({dryRun:r.dryRun,entry:G(e),environment:r.env,outDir:r.outDir,preview:r.preview,temporary:r.temporary}),q=(e,r,a)=>{const{toolchain:t}=a;if(t===void 0)throw new Error(`deploy target "${a.id}" has no command-line toolchain`);const n=yr(e,r);return W(a,e,"deploy",o=>t.deploy({...n,configPath:o}))},wr=(e,r,a)=>{const t=q(e,r,a),n=G(e);return n!==void 0&&r.logger.info(`class-B composition: deploying ${n} (overrides wrangler main)`),r.temporary&&r.logger.info("temporary account: deploying to a short-lived Cloudflare account (~60min); wrangler will print a claim URL"),r.dryRun&&r.logger.info("dry run: validating + bundling without publishing"),r.outDir!==void 0&&r.logger.info(`build artifact: emitting bundle to ${r.outDir}`),t.commit(),t.projection!==void 0&&t.projection.dropped.length>0&&r.logger.warn(`${a.name} ignores these wrangler keys, so they were left out of ${t.projection.configPath}: ${t.projection.dropped.join(", ")}`),t.command},D=(e,r)=>({code:h.USAGE,descriptor:void 0,error:e,validation:{problems:[],wranglerPath:void 0},...r}),kr=(e,r)=>{for(const a of e.report?.warnings??[])r.warn(`wrangler.jsonc: ${a}`);if(e.problems.length===0)return!1;r.error("wrangler.jsonc validation failed:");for(const a of e.problems)r.error(` - ${a}`);return!0},br=(e,r,a)=>{const t=r.format==="json",n=r.dryRun!==!0,o=wr(e,r,a),i=E(b(e),o);return{args:i.args,captureStdout:n&&!t,captureStdoutSilently:n&&t,command:i.command,cwd:e,stdoutToStderr:t&&!n}},$r=async(e,r)=>{const a=e.cwd??process.cwd(),t=K(e),n=ve(e),o={problems:[],wranglerPath:void 0},i=ke(a,e.target);if(i.target===void 0){const u=i.error??"unknown deploy target";return e.logger.error(u),{error:u,validation:o}}const{target:s}=i;try{q(a,e,R(s))}catch(u){const g=u instanceof Error?u.message:String(u);return e.logger.error(g),{error:g,target:s,validation:o}}let c;if(!e.skipCodegen){const u=await pr(a,t,e.logger,e.apiSpec,s,e.spawner,e.format==="json",n);if(u.error!==void 0)return{error:u.error,target:s,validation:o};c=u.result}let d;if(c!==void 0){const u=Ce({allowDrift:e.allowSchemaDrift===!0,codegen:c,command:r,logger:e.logger,updateBaseline:e.updateSchemaBaseline===!0});if(u.blocked)return{error:`schema drift gate blocked ${r}`,schemaDrift:{blocked:!0,reason:u.reason},target:s,validation:o};d=u.rebless}await vr(a,e.logger,c?.cronTriggers,s,e.env);const l=ze(a,e,r);if(l!==void 0)return{code:l.code,error:l.error,target:s,validation:o};const m=de({environment:e.env,projectRoot:a});return kr(m,e.logger)?{error:"wrangler validation failed",target:s,validation:m}:{codegen:c,reblessSchemaBaseline:d,target:s,validation:m}},Sr=e=>{if(e.skipServices===!0)return"--skip-services";if(e.preview===!0)return"--preview uploads the app version only";if(e.temporary===!0)return"--temporary deploys the app to a throwaway account"},Dr=async(e,r,a,t)=>{const{error:n,services:o}=Q(e);if(n!==void 0)return n;if(o.length===0)return;const{toolchain:i}=a,s=i===void 0?`target "${a.id}" has no deploy command`:Sr(r);if(s!==void 0||i===void 0){const l=o.map(m=>m.worker).join(", ");r.logger.warn(`services not deployed (${s??""}): ${l} — deploy them yourself if the app calls anything new`);return}const c=b(e),d=[...new Map(o.map(l=>[l.wranglerPath,l])).values()];for(const l of d){const m=J(l.wranglerPath);let u;try{u=W(a,m,"deploy",v=>i.deploy({configPath:v??l.wranglerPath,dryRun:r.dryRun===!0,environment:r.env}))}catch(v){return`service ${l.name} (${l.worker}): ${v instanceof Error?v.message:String(v)}`}u.commit();const g=E(c,u.command);r.logger.info(`deploying service ${l.name} (${l.worker}) via ${g.command} ${g.args.join(" ")}`);const f=await t({args:g.args,command:g.command,cwd:m,stdoutToStderr:r.format==="json"});if(f.code!==0)return`service ${l.name} (${l.worker}): ${g.command} ${g.args.join(" ")} exited ${String(f.code)} — stopping before the app`}},Er=async e=>{const r=e.cwd??process.cwd(),a=K(e),t=await $r(e,e.commandName??"deploy");if(t.error!==void 0){if(t.validation.problems.length>0)return{code:h.USAGE,descriptor:void 0,error:t.error,validation:t.validation};const Y=t.schemaDrift===void 0?void 0:{schemaDrift:t.schemaDrift};return D(t.error,{...Y,...t.code===void 0?{}:{code:t.code}})}const{reblessSchemaBaseline:n,validation:o}=t,i=R(t.target),s=Ke(e);if(s!==void 0)return D(s);const c=i.toolchain?.prebuildsContainerImages===!0?await fr(r,e):void 0;if(c!==void 0)return D(c);ir(r,e.logger,i);const{error:d,mintedSecretsFile:l}=await mr(r,e,a,i);if(d!==void 0)return e.logger.error(d),{code:h.USAGE,descriptor:void 0,error:d,mintedSecretsFile:l,validation:o};const m=e.spawner??$,u=await Dr(r,e,i,m);if(u!==void 0)return{code:h.FAILURE,descriptor:void 0,error:u,mintedSecretsFile:l,validation:o};const g=br(r,e,i);e.logger.info(`deploying via ${g.command} ${g.args.join(" ")}`);const f=await m(g);return g.captureStdoutSilently===!0&&f.stdout!==void 0&&f.stdout!==""&&process.stderr.write(f.stdout),f.code!==0?{code:f.code,descriptor:g,mintedSecretsFile:l,validation:o}:{...await or({cwd:r,descriptor:g,mintedSecretsFile:l,options:e,reblessSchemaBaseline:n,stdout:f.stdout,validation:o}),logsAvailable:i.toolchain?.tail!==void 0}},Rr=async e=>{const{logger:r}=e,a=e.dryRun===!0?Oe(e.cwd??process.cwd()):void 0;let t;try{if(t=await Er({...e,logger:r}),t.code===0&&e.emitBindings!==void 0){const{error:n}=be({destination:e.emitBindings,logger:r,projectRoot:e.cwd??process.cwd()});n!==void 0&&(r.error(n),t={...t,code:h.USAGE})}}finally{a?.()}if(e.format==="json")return t;if(t.code===0&&e.dryRun!==!0&&e.preview!==!0)Ue({cwd:e.cwd??process.cwd(),env:e.env,logger:e.logger,logsAvailable:t.logsAvailable===!0,mintedSecretsFile:t.mintedSecretsFile,url:t.deployment?.url});else if(t.code===0&&e.preview===!0){const n=t.deployment?.url;e.logger.success(n===void 0?"preview version uploaded":`preview version uploaded — ${n}`)}return t},Jr=$e(async({cwd:e,format:r,logger:a,options:t})=>{const n=await Rr({allowSchemaDrift:t.allowSchemaDrift===!0,apiSpec:we(t.apiSpec),cwd:e,dryRun:t.dryRun===!0,env:t.env,format:r,healthCheck:t.healthCheck===!0,logger:a,migrate:t.migrate===!0,migrateToken:t.migrateToken,migrateUrl:B({cwd:e,env:t.env,url:t.migrateUrl}),migrateYes:t.migrateYes===!0,preview:t.preview===!0,skipCodegen:t.prebuilt===!0,skipServices:t.skipServices===!0,strictAdvisories:t.strictAdvisories,target:t.target,temporary:t.temporary===!0,updateSchemaBaseline:t.updateSchemaBaseline===!0});return{code:n.code,data:{deployment:n.deployment,healthCheck:n.healthCheck,mintedSecretsFile:n.mintedSecretsFile,schemaDrift:n.schemaDrift,validation:n.validation},error:n.error}});export{Jr as execute,vr as provisionBindings,Rr as runDeployCommand,$r as runPreDeployPipeline};