@lunora/cli 1.0.0-alpha.4 → 1.0.0-alpha.400

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 +3 -1
  3. package/__assets__/package-og.svg +1 -1
  4. package/dist/bin.mjs +2 -10
  5. package/dist/index.d.mts +1161 -372
  6. package/dist/index.d.ts +1161 -372
  7. package/dist/index.mjs +1 -19
  8. package/dist/packem_chunks/dispatch.mjs +1 -0
  9. package/dist/packem_chunks/handler.mjs +1 -78
  10. package/dist/packem_chunks/handler10.mjs +1 -22
  11. package/dist/packem_chunks/handler11.mjs +1 -192
  12. package/dist/packem_chunks/handler12.mjs +1 -131
  13. package/dist/packem_chunks/handler13.mjs +3 -65
  14. package/dist/packem_chunks/handler14.mjs +1 -58
  15. package/dist/packem_chunks/handler15.mjs +1 -79
  16. package/dist/packem_chunks/handler16.mjs +1 -43
  17. package/dist/packem_chunks/handler17.mjs +7 -105
  18. package/dist/packem_chunks/handler18.mjs +1 -172
  19. package/dist/packem_chunks/handler19.mjs +1 -89
  20. package/dist/packem_chunks/handler2.mjs +1 -114
  21. package/dist/packem_chunks/handler20.mjs +3 -94
  22. package/dist/packem_chunks/handler21.mjs +3 -311
  23. package/dist/packem_chunks/handler22.mjs +1 -0
  24. package/dist/packem_chunks/handler23.mjs +2 -0
  25. package/dist/packem_chunks/handler24.mjs +99 -0
  26. package/dist/packem_chunks/handler25.mjs +2 -0
  27. package/dist/packem_chunks/handler26.mjs +9 -0
  28. package/dist/packem_chunks/handler27.mjs +1 -0
  29. package/dist/packem_chunks/handler3.mjs +1 -204
  30. package/dist/packem_chunks/handler4.mjs +3 -33
  31. package/dist/packem_chunks/handler5.mjs +1 -49
  32. package/dist/packem_chunks/handler6.mjs +1 -91
  33. package/dist/packem_chunks/handler7.mjs +1 -42
  34. package/dist/packem_chunks/handler8.mjs +2 -174
  35. package/dist/packem_chunks/handler9.mjs +1 -16
  36. package/dist/packem_chunks/runCodegenCommand.mjs +4 -52
  37. package/dist/packem_chunks/runDeployCommand.mjs +11 -504
  38. package/dist/packem_chunks/runDevCommand.mjs +2 -0
  39. package/dist/packem_chunks/runInitCommand.mjs +1176 -576
  40. package/dist/packem_chunks/runResetCommand.mjs +1 -41
  41. package/dist/packem_chunks/runRpcCommand.mjs +1 -68
  42. package/dist/packem_shared/COMMANDS-aSTSMwZS.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/api-spec-lYyq4vL6.mjs +1 -0
  48. package/dist/packem_shared/binding-manifest-file-CQ1eQYy1.mjs +2 -0
  49. package/dist/packem_shared/buildRegistryIndex-Dc8D8AR6.mjs +1 -0
  50. package/dist/packem_shared/cap-error-body-YBKO32BF.mjs +1 -0
  51. package/dist/packem_shared/catalog-CahzmDLV.mjs +1 -0
  52. package/dist/packem_shared/cli-CFsmCYWp.mjs +2 -0
  53. package/dist/packem_shared/cli-manifest-DoQ_3bzs.mjs +1 -0
  54. package/dist/packem_shared/cloudflare-credentials-BVmZnDZk.mjs +1 -0
  55. package/dist/packem_shared/codegen-error-AmH54ofi.mjs +3 -0
  56. package/dist/packem_shared/command-BgjsvUFg.mjs +1 -0
  57. package/dist/packem_shared/commands-DvSfLvyt.mjs +13 -0
  58. package/dist/packem_shared/createLogger-4TujevyB.mjs +2 -0
  59. package/dist/packem_shared/createRecordingSpawner-Ch7zuQQE.mjs +1 -0
  60. package/dist/packem_shared/deploy-target-resolve-BTCW1Iv4.mjs +1 -0
  61. package/dist/packem_shared/diffSnapshots-htqNZT8Q.mjs +7 -0
  62. package/dist/packem_shared/docker-AqLAkOyY.mjs +1 -0
  63. package/dist/packem_shared/health-probe-Bw9JFfIy.mjs +1 -0
  64. package/dist/packem_shared/import-BRM1hs7j.mjs +12 -0
  65. package/dist/packem_shared/index-oHZBGBwB.mjs +1 -0
  66. package/dist/packem_shared/insertSchemaExtension-DuiV6cba.mjs +8 -0
  67. package/dist/packem_shared/lint-ignore-report-DKZagpqk.mjs +2 -0
  68. package/dist/packem_shared/mcp-config-file-CcDTeXIq.mjs +2 -0
  69. package/dist/packem_shared/open-url-EnKy--w-.mjs +1 -0
  70. package/dist/packem_shared/output-format-DWe_tkTR.mjs +2 -0
  71. package/dist/packem_shared/parseManifest-CwPTKdtS.mjs +1 -0
  72. package/dist/packem_shared/path-containment-CgxYZggb.mjs +1 -0
  73. package/dist/packem_shared/plan-DVfi3TrN.mjs +5 -0
  74. package/dist/packem_shared/planDevCommand-IglbXy5A.mjs +1 -0
  75. package/dist/packem_shared/platform-diagnostics-Cn2g6Jh-.mjs +4 -0
  76. package/dist/packem_shared/prompt-cancelled-BvsNxg_Q.mjs +1 -0
  77. package/dist/packem_shared/render-lunora-error-C3OJY5wk.mjs +2 -0
  78. package/dist/packem_shared/resolve-Bdc9KEUv.mjs +5 -0
  79. package/dist/packem_shared/resolve-target-C_ZloTvd.mjs +1 -0
  80. package/dist/packem_shared/runAddCommand-BChdJQ5L.mjs +1 -0
  81. package/dist/packem_shared/runExportCommand-slAq5BCF.mjs +5 -0
  82. package/dist/packem_shared/runMigrateGenerateCommand-BwemPIOz.mjs +11 -0
  83. package/dist/packem_shared/schemaIrToSnapshot-BHuNOfgs.mjs +1 -0
  84. package/dist/packem_shared/secret-key-8DPOH98z.mjs +1 -0
  85. package/dist/packem_shared/shared-D-zCOmgY.mjs +1 -0
  86. package/dist/packem_shared/storage-DNzYhXR-.mjs +1 -0
  87. package/dist/packem_shared/tui-prompts-B3YwUhGw.mjs +4 -0
  88. package/dist/packem_shared/variables-CPYyJtsL.mjs +1 -0
  89. package/dist/packem_shared/wrangler-name-Dsk5K1f-.mjs +1 -0
  90. package/dist/packem_shared/wrangler-secrets-CTQPpalP.mjs +1 -0
  91. package/package.json +41 -19
  92. package/skills/README.md +35 -17
  93. package/skills/lunora/SKILL.md +154 -64
  94. package/skills/lunora-create-package/SKILL.md +97 -84
  95. package/skills/lunora-deploy/SKILL.md +175 -105
  96. package/skills/lunora-functions/SKILL.md +362 -56
  97. package/skills/lunora-migration-helper/SKILL.md +162 -137
  98. package/skills/lunora-performance-audit/SKILL.md +137 -95
  99. package/skills/lunora-quickstart/SKILL.md +137 -136
  100. package/skills/lunora-realtime/SKILL.md +140 -99
  101. package/skills/lunora-setup-auth/SKILL.md +162 -102
  102. package/skills/lunora-setup-hyperdrive/SKILL.md +130 -109
  103. package/skills/lunora-setup-hyperdrive-global/SKILL.md +93 -90
  104. package/skills/lunora-setup-mail/SKILL.md +85 -113
  105. package/skills/lunora-setup-scheduler/SKILL.md +132 -96
  106. package/skills/lunora-setup-storage/SKILL.md +189 -91
  107. package/dist/packem_chunks/planDevCommand.mjs +0 -543
  108. package/dist/packem_chunks/runMigrateGenerateCommand.mjs +0 -397
  109. package/dist/packem_shared/COMMANDS-CHw4zOZ9.mjs +0 -922
  110. package/dist/packem_shared/DEFAULT_IMPORT_BATCH_SIZE-Ck-2bU08.mjs +0 -244
  111. package/dist/packem_shared/admin-url-4UzT-CI4.mjs +0 -19
  112. package/dist/packem_shared/api-spec-CtA6ilu4.mjs +0 -13
  113. package/dist/packem_shared/buildRegistryIndex-BcYe607_.mjs +0 -38
  114. package/dist/packem_shared/command-BDXcJCCJ.mjs +0 -14
  115. package/dist/packem_shared/commands-SUPdjsu5.mjs +0 -787
  116. package/dist/packem_shared/createLogger-CHPNjFw2.mjs +0 -73
  117. package/dist/packem_shared/defaultSpawner-DxI3mebw.mjs +0 -43
  118. package/dist/packem_shared/diffSnapshots-RR2ZE8Ya.mjs +0 -161
  119. package/dist/packem_shared/docker-hMQ97KSQ.mjs +0 -21
  120. package/dist/packem_shared/features-ocSSpZtS.mjs +0 -24
  121. package/dist/packem_shared/insertSchemaExtension-BuzF6-t2.mjs +0 -59
  122. package/dist/packem_shared/open-url-Dfq6fAyT.mjs +0 -41
  123. package/dist/packem_shared/output-format-7gyGR3h8.mjs +0 -17
  124. package/dist/packem_shared/parseArgs-YXFuKdEk.mjs +0 -56
  125. package/dist/packem_shared/parseManifest--vZf2FY1.mjs +0 -94
  126. package/dist/packem_shared/resolve-target-qbsJ_5sF.mjs +0 -16
  127. package/dist/packem_shared/runAddCommand-Txwh1Xw1.mjs +0 -4
  128. package/dist/packem_shared/schema-drift-gate-BtBt0as0.mjs +0 -79
  129. package/dist/packem_shared/schemaIrToSnapshot-aBTo7TM5.mjs +0 -43
  130. package/dist/packem_shared/wrangler-name-cy4yhm9j.mjs +0 -12
@@ -1,543 +0,0 @@
1
- import { spawn } from 'node:child_process';
2
- import { detectAgentRules, inferLunoraBindings, packageNamesFromBindings, ensureDevVarsExample, ensureDevVariables, createConfirm, isInteractive, DEV_VARS_FILE, DEV_VARS_EXAMPLE_FILE, claimAgentRulesHint, AGENT_RULES_HINT, materializeRemoteWranglerConfig, formatLunoraEvent, resolveRemoteEnabled, readProjectRemotePreference } from '@lunora/config';
3
- import { p as parseApiSpec } from '../packem_shared/api-spec-CtA6ilu4.mjs';
4
- import { existsSync, watch, readFileSync } from 'node:fs';
5
- import { join } from 'node:path';
6
- import { runCodegen } from '@lunora/codegen';
7
- import { d as defineHandler } from '../packem_shared/command-BDXcJCCJ.mjs';
8
- import { dirname, join as join$1 } from '@visulima/path';
9
- import { createServer, request } from 'node:http';
10
- import { connect } from 'node:net';
11
- import { loadStudioAssets, studioAssetsStamp, renderStudioHtml, resolveAdminToken, SCHEMA_EDIT_ENDPOINT, POLICY_SCAFFOLD_ENDPOINT, SEED_ENDPOINT, serveJsonHandler, handleSchemaEditRequest, handlePolicyScaffoldRequest, handleSeedRequest } from '@lunora/config/studio-host';
12
-
13
- const DEFAULT_DEBOUNCE_MS = 100;
14
- const PATH_SEGMENT_SEPARATOR = /[/\\]/u;
15
- const runOnce = (projectRoot, lunoraDirectory, apiSpec, logger, reason) => {
16
- try {
17
- runCodegen({ apiSpec, lunoraDirectory, projectRoot });
18
- logger.success(`codegen: wrote ${lunoraDirectory}/_generated (${reason})`);
19
- } catch (error) {
20
- logger.error(`codegen failed (${reason}): ${error instanceof Error ? error.message : String(error)}`);
21
- }
22
- };
23
- const startCodegenWatch = (options) => {
24
- const lunoraDirectory = options.lunoraDirectory ?? "lunora";
25
- const watchDirectory = join(options.projectRoot, lunoraDirectory);
26
- const debounceMs = options.debounceMs ?? DEFAULT_DEBOUNCE_MS;
27
- const { apiSpec } = options;
28
- runOnce(options.projectRoot, lunoraDirectory, apiSpec, options.logger, "startup");
29
- let timer;
30
- let watcher;
31
- if (!existsSync(watchDirectory)) {
32
- options.logger.warn(
33
- `codegen watch unavailable (no such directory: ${watchDirectory}) — schema edits will NOT auto-regenerate. Run \`lunora codegen\` manually after each edit.`
34
- );
35
- return {
36
- close: () => {
37
- },
38
- watchAvailable: false
39
- };
40
- }
41
- try {
42
- watcher = watch(watchDirectory, { recursive: true }, (_event, filename) => {
43
- if (typeof filename === "string" && filename.split(PATH_SEGMENT_SEPARATOR).includes("_generated")) {
44
- return;
45
- }
46
- if (timer) {
47
- clearTimeout(timer);
48
- }
49
- timer = setTimeout(runOnce, debounceMs, options.projectRoot, lunoraDirectory, apiSpec, options.logger, `change: ${filename ?? "?"}`);
50
- });
51
- } catch (error) {
52
- options.logger.warn(
53
- `codegen watch unavailable (${error instanceof Error ? error.message : String(error)}) — schema edits will NOT auto-regenerate. Run \`lunora codegen\` manually after each edit.`
54
- );
55
- return {
56
- close: () => {
57
- },
58
- watchAvailable: false
59
- };
60
- }
61
- const liveWatcher = watcher;
62
- return {
63
- close: () => {
64
- if (timer) {
65
- clearTimeout(timer);
66
- }
67
- liveWatcher.close();
68
- },
69
- watchAvailable: true
70
- };
71
- };
72
-
73
- const FALLBACK = "pnpm";
74
- const KNOWN_MANAGERS = ["pnpm", "yarn", "npm", "bun"];
75
- const parseDeclaredManager = (declared) => {
76
- if (typeof declared !== "string") {
77
- return void 0;
78
- }
79
- return KNOWN_MANAGERS.find((manager) => declared.startsWith(`${manager}@`));
80
- };
81
- const readDeclaredManager = (directory) => {
82
- const candidate = join$1(directory, "package.json");
83
- if (!existsSync(candidate)) {
84
- return void 0;
85
- }
86
- try {
87
- const parsed = JSON.parse(readFileSync(candidate, "utf8"));
88
- return parseDeclaredManager(parsed.packageManager);
89
- } catch {
90
- return void 0;
91
- }
92
- };
93
- const detectPackageManager = (startDirectory) => {
94
- let directory = startDirectory;
95
- while (directory && directory !== dirname(directory)) {
96
- const declared = readDeclaredManager(directory);
97
- if (declared !== void 0) {
98
- return declared;
99
- }
100
- directory = dirname(directory);
101
- }
102
- return FALLBACK;
103
- };
104
- const execArgsFor = (manager, command, args) => {
105
- if (manager === "yarn") {
106
- return { args: [command, ...args], command: "yarn" };
107
- }
108
- if (manager === "bun") {
109
- return { args: ["x", command, ...args], command: "bun" };
110
- }
111
- if (manager === "npm") {
112
- return { args: ["--", command, ...args], command: "npx" };
113
- }
114
- return { args: ["exec", command, ...args], command: "pnpm" };
115
- };
116
-
117
- const PROXY_PREFIX = "/_lunora";
118
- const pathnameOf = (url) => {
119
- const queryIndex = url.indexOf("?");
120
- return queryIndex === -1 ? url : url.slice(0, queryIndex);
121
- };
122
- const LOOPBACK_HOST_NAMES = /* @__PURE__ */ new Set(["127.0.0.1", "::1", "[::1]", "localhost"]);
123
- const isLoopbackHost = (hostHeader) => {
124
- if (hostHeader === void 0 || hostHeader === "") {
125
- return false;
126
- }
127
- const withoutPort = hostHeader.startsWith("[") ? hostHeader.slice(0, hostHeader.indexOf("]") + 1) : hostHeader.split(":")[0] ?? hostHeader;
128
- return LOOPBACK_HOST_NAMES.has(withoutPort);
129
- };
130
- const proxyHttp = (request$1, response, worker) => {
131
- const upstream = request(
132
- {
133
- headers: { ...request$1.headers, host: worker.host },
134
- hostname: worker.hostname,
135
- method: request$1.method,
136
- path: request$1.url,
137
- port: worker.port
138
- },
139
- (upstreamResponse) => {
140
- response.writeHead(upstreamResponse.statusCode ?? 502, upstreamResponse.headers);
141
- upstreamResponse.pipe(response);
142
- }
143
- );
144
- upstream.on("error", (error) => {
145
- response.statusCode = 502;
146
- response.end(`lunora dev: worker unreachable (${error.message})`);
147
- });
148
- request$1.pipe(upstream);
149
- };
150
- const UPGRADE_CONNECT_TIMEOUT_MS = 5e3;
151
- const proxyUpgrade = (request, clientSocket, head, worker) => {
152
- const upstream = connect({ host: worker.hostname, port: Number(worker.port) }, () => {
153
- upstream.setTimeout(0);
154
- const lines = [`${request.method ?? "GET"} ${request.url ?? "/"} HTTP/1.1`];
155
- for (const [key, value] of Object.entries(request.headers)) {
156
- if (key === "host") {
157
- continue;
158
- }
159
- for (const item of Array.isArray(value) ? value : [value]) {
160
- if (item !== void 0) {
161
- lines.push(`${key}: ${item}`);
162
- }
163
- }
164
- }
165
- lines.push(`host: ${worker.host}`, "", "");
166
- upstream.write(lines.join("\r\n"));
167
- if (head.length > 0) {
168
- upstream.write(head);
169
- }
170
- upstream.pipe(clientSocket);
171
- clientSocket.pipe(upstream);
172
- });
173
- upstream.setTimeout(UPGRADE_CONNECT_TIMEOUT_MS, () => upstream.destroy());
174
- upstream.on("error", () => clientSocket.destroy());
175
- clientSocket.on("error", () => upstream.destroy());
176
- };
177
- const startStudioServer = async (options) => {
178
- const host = options.host ?? "127.0.0.1";
179
- const isLoopback = host === "127.0.0.1" || host === "localhost" || host === "::1";
180
- const worker = new URL(options.workerOrigin);
181
- let assets = loadStudioAssets(options.logger, import.meta.url);
182
- let assetsStamp = studioAssetsStamp(import.meta.url);
183
- const html = renderStudioHtml({
184
- // The admin token grants full read/write over the local worker. Only embed
185
- // it for a loopback bind: a non-loopback (LAN/0.0.0.0) bind would otherwise
186
- // hand the token to any network client that GETs `/`.
187
- adminToken: isLoopback ? resolveAdminToken(options.cwd) : void 0,
188
- basePath: "/",
189
- dataEditable: isLoopback,
190
- rulesInstalled: detectAgentRules(options.cwd).installed,
191
- runAsIdentity: isLoopback,
192
- schemaEditable: isLoopback,
193
- scriptSrc: "/studio.js",
194
- styleHref: "/styles.css"
195
- });
196
- const sendAsset = (response, body, contentType) => {
197
- response.statusCode = 200;
198
- response.setHeader("Content-Type", contentType);
199
- response.end(body);
200
- };
201
- const serveLoopbackOnly = (request, response, handle, deniedMessage) => {
202
- if (isLoopback) {
203
- serveJsonHandler(request, response, handle, options.cwd);
204
- return;
205
- }
206
- response.statusCode = 403;
207
- response.setHeader("Content-Type", "text/plain");
208
- response.end(deniedMessage);
209
- };
210
- const serveStaticAsset = (pathname, response) => {
211
- if (pathname !== "/studio.js" && pathname !== "/styles.css") {
212
- return false;
213
- }
214
- const stamp = studioAssetsStamp(import.meta.url);
215
- if (stamp !== assetsStamp) {
216
- assets = loadStudioAssets(options.logger, import.meta.url);
217
- assetsStamp = stamp;
218
- }
219
- if (assets === void 0) {
220
- response.statusCode = 501;
221
- response.setHeader("Content-Type", "text/plain");
222
- response.end("Lunora studio assets not found — install and build @lunora/studio.");
223
- return true;
224
- }
225
- const isScript = pathname === "/studio.js";
226
- sendAsset(response, isScript ? assets.script : assets.styles, isScript ? "text/javascript; charset=utf-8" : "text/css; charset=utf-8");
227
- return true;
228
- };
229
- const document = Buffer.from(html);
230
- const server = createServer((request, response) => {
231
- const pathname = pathnameOf(request.url ?? "/");
232
- if (isLoopback && !isLoopbackHost(request.headers.host)) {
233
- response.statusCode = 403;
234
- response.setHeader("Content-Type", "text/plain");
235
- response.end("Lunora studio: refusing a request whose Host is not a loopback literal (DNS-rebinding guard).");
236
- return;
237
- }
238
- if (pathname.startsWith(PROXY_PREFIX)) {
239
- if (!isLoopback) {
240
- response.statusCode = 403;
241
- response.setHeader("Content-Type", "text/plain");
242
- response.end("Lunora studio: the worker admin proxy is only available on a loopback bind.");
243
- return;
244
- }
245
- proxyHttp(request, response, worker);
246
- return;
247
- }
248
- if (pathname === SCHEMA_EDIT_ENDPOINT) {
249
- serveLoopbackOnly(request, response, handleSchemaEditRequest, "Lunora schema editing is only available on loopback hosts in dev.");
250
- return;
251
- }
252
- if (pathname === POLICY_SCAFFOLD_ENDPOINT) {
253
- serveLoopbackOnly(request, response, handlePolicyScaffoldRequest, "Lunora policy scaffolding is only available on loopback hosts in dev.");
254
- return;
255
- }
256
- if (pathname === SEED_ENDPOINT) {
257
- serveLoopbackOnly(request, response, handleSeedRequest, "Lunora data seeding is only available on loopback hosts in dev.");
258
- return;
259
- }
260
- if (serveStaticAsset(pathname, response)) {
261
- return;
262
- }
263
- sendAsset(response, document, "text/html; charset=utf-8");
264
- });
265
- server.on("upgrade", (request, socket, head) => {
266
- if (!isLoopback || !isLoopbackHost(request.headers.host)) {
267
- socket.destroy();
268
- return;
269
- }
270
- if (pathnameOf(request.url ?? "").startsWith(PROXY_PREFIX)) {
271
- proxyUpgrade(request, socket, head, worker);
272
- } else {
273
- socket.destroy();
274
- }
275
- });
276
- await new Promise((resolve, reject) => {
277
- server.once("error", (error) => {
278
- if (error.code === "EADDRINUSE") {
279
- reject(
280
- new Error(`studio port ${String(options.port)} is already in use — pass a different port with --port, or stop the process using it`, {
281
- cause: error
282
- })
283
- );
284
- } else {
285
- reject(error);
286
- }
287
- });
288
- server.listen(options.port, host, () => {
289
- resolve();
290
- });
291
- });
292
- return {
293
- close: () => new Promise((resolve) => {
294
- server.close(() => {
295
- resolve();
296
- });
297
- }),
298
- url: `http://${host === "0.0.0.0" || host === "::" ? "localhost" : host}:${String(options.port)}`
299
- };
300
- };
301
-
302
- const DEFAULT_STUDIO_PORT = 6173;
303
- const DEFAULT_WORKER_PORT = 8787;
304
- const SIGINT_GRACE_MS = 5e3;
305
- const resolveRemotePlan = (options, cwd) => {
306
- const noopCleanup = () => {
307
- };
308
- if (!options.remote) {
309
- return { args: [], plan: { bindings: [], cleanup: noopCleanup, enabled: false } };
310
- }
311
- const materialize = options.materializeRemote ?? materializeRemoteWranglerConfig;
312
- const result = materialize({ enabled: true, projectRoot: cwd });
313
- const bindings = result.remoteBindings.map((binding) => `${binding.binding} (${binding.kind})`);
314
- const { cleanup } = result;
315
- if (result.configPath === void 0) {
316
- return { args: [], plan: { bindings, cleanup, enabled: true, reason: result.reason } };
317
- }
318
- return { args: ["--config", result.configPath], plan: { bindings, cleanup, enabled: true } };
319
- };
320
- const planDevCommand = (options) => {
321
- const cwd = options.cwd ?? process.cwd();
322
- const workerPort = options.workerPort ?? DEFAULT_WORKER_PORT;
323
- const manager = detectPackageManager(cwd);
324
- const remote = resolveRemotePlan(options, cwd);
325
- const exec = execArgsFor(manager, "wrangler", ["dev", "--port", String(workerPort), "--var", "WORKER_ENV:development", ...remote.args]);
326
- return {
327
- codegenEnabled: options.codegen !== false,
328
- remote: remote.plan,
329
- studioEnabled: options.studio !== false,
330
- studioPort: options.port ?? DEFAULT_STUDIO_PORT,
331
- workerOrigin: `http://localhost:${String(workerPort)}`,
332
- workerPort,
333
- wrangler: { args: exec.args, command: exec.command, cwd, tag: "wrangler" }
334
- };
335
- };
336
- const emitChildLine = (line, tag, kind, logger) => {
337
- if (line.length === 0) {
338
- return;
339
- }
340
- const formatted = formatLunoraEvent(line);
341
- if (formatted) {
342
- logger[formatted.level](`[lunora] ${formatted.text}`);
343
- return;
344
- }
345
- const prefixed = `[${tag}] ${line}`;
346
- if (kind === "stderr") {
347
- logger.warn(prefixed);
348
- } else {
349
- logger.info(prefixed);
350
- }
351
- };
352
- const pipeChildOutput = (child, tag, logger) => {
353
- const pumpStream = (stream, kind) => {
354
- if (!stream) {
355
- return;
356
- }
357
- let buffer = "";
358
- stream.on("data", (chunk) => {
359
- buffer += chunk.toString("utf8");
360
- const lines = buffer.split("\n");
361
- buffer = lines.pop() ?? "";
362
- for (const line of lines) {
363
- emitChildLine(line.trimEnd(), tag, kind, logger);
364
- }
365
- });
366
- stream.on("end", () => {
367
- emitChildLine(buffer.trimEnd(), tag, kind, logger);
368
- buffer = "";
369
- });
370
- };
371
- pumpStream(child.stdout, "stdout");
372
- pumpStream(child.stderr, "stderr");
373
- };
374
- const defaultWorkerSpawner = (descriptor, logger) => {
375
- const child = spawn(descriptor.command, [...descriptor.args], {
376
- cwd: descriptor.cwd ?? process.cwd(),
377
- env: process.env,
378
- stdio: ["inherit", "pipe", "pipe"]
379
- });
380
- pipeChildOutput(child, descriptor.tag, logger);
381
- return {
382
- exited: new Promise((resolve) => {
383
- child.on("error", (error) => {
384
- logger.error(`[${descriptor.tag}] failed to start: ${error.message}`);
385
- resolve(1);
386
- });
387
- child.on("exit", (code) => {
388
- resolve(code ?? 0);
389
- });
390
- }),
391
- kill: (signal) => {
392
- try {
393
- child.kill(signal);
394
- } catch {
395
- }
396
- }
397
- };
398
- };
399
- const printBanner = (logger, plan, studioUrl) => {
400
- logger.info("");
401
- logger.success("Lunora dev");
402
- logger.info(` ➜ Worker: ${plan.workerOrigin}`);
403
- if (studioUrl !== void 0) {
404
- logger.info(` ➜ Studio: ${studioUrl}`);
405
- }
406
- if (plan.codegenEnabled) {
407
- logger.info(" ➜ Codegen: watching lunora/");
408
- }
409
- if (plan.remote.enabled) {
410
- if (plan.remote.bindings.length > 0) {
411
- logger.info(` ➜ Remote: ${plan.remote.bindings.join(", ")} → deployed worker`);
412
- } else {
413
- logger.warn(` ➜ Remote: requested but inactive (${plan.remote.reason ?? "no eligible bindings"}) — running fully local`);
414
- }
415
- }
416
- logger.info("");
417
- };
418
- const printAgentRulesHint = (logger, cwd) => {
419
- if (detectAgentRules(cwd).installed || !claimAgentRulesHint()) {
420
- return;
421
- }
422
- logger.info(` ⓘ ${AGENT_RULES_HINT}`);
423
- logger.info("");
424
- };
425
- const teardown = async (handles) => {
426
- handles.codegen?.close();
427
- await handles.studio?.close().catch(() => void 0);
428
- try {
429
- handles.remoteCleanup?.();
430
- } catch {
431
- }
432
- };
433
- const offerDevVariablesScaffold = async (options, cwd) => {
434
- try {
435
- const bindings = await inferLunoraBindings({ projectRoot: cwd });
436
- const packageNames = packageNamesFromBindings(bindings);
437
- const addedKeys = (options.ensureExample ?? ensureDevVarsExample)(cwd, packageNames);
438
- if (addedKeys.length > 0) {
439
- options.logger.info(`Updated .dev.vars.example with secrets for: ${packageNames.join(", ")} (${addedKeys.join(", ")})`);
440
- }
441
- } catch {
442
- }
443
- const result = await (options.ensureEnv ?? ensureDevVariables)({
444
- confirm: createConfirm(),
445
- cwd,
446
- info: (message) => {
447
- options.logger.info(message);
448
- }
449
- });
450
- if (result.status === "declined" && !isInteractive()) {
451
- options.logger.info(
452
- `hint: ${DEV_VARS_FILE} was not scaffolded (non-interactive run). Copy ${DEV_VARS_EXAMPLE_FILE} → ${DEV_VARS_FILE} and fill in secrets, or run \`lunora dev\` in an interactive terminal to scaffold automatically.`
453
- );
454
- }
455
- };
456
- const runDevCommand = async (options) => {
457
- const plan = planDevCommand(options);
458
- const { logger } = options;
459
- const cwd = plan.wrangler.cwd ?? process.cwd();
460
- const handles = { remoteCleanup: plan.remote.cleanup };
461
- try {
462
- await offerDevVariablesScaffold(options, cwd);
463
- logger.info("starting wrangler dev + studio");
464
- if (plan.codegenEnabled) {
465
- handles.codegen = (options.startCodegen ?? startCodegenWatch)({ apiSpec: options.apiSpec, logger, projectRoot: cwd });
466
- }
467
- let studioUrl;
468
- if (plan.studioEnabled) {
469
- try {
470
- handles.studio = await (options.startStudio ?? startStudioServer)({
471
- cwd,
472
- logger: {
473
- warnOnce: (message) => {
474
- logger.warn(message);
475
- }
476
- },
477
- port: plan.studioPort,
478
- workerOrigin: plan.workerOrigin
479
- });
480
- studioUrl = handles.studio.url;
481
- } catch (error) {
482
- logger.warn(`studio server failed to start (${error instanceof Error ? error.message : String(error)}) — continuing without it`);
483
- }
484
- }
485
- const worker = (options.startWorker ?? defaultWorkerSpawner)(plan.wrangler, logger);
486
- printBanner(logger, plan, studioUrl);
487
- printAgentRulesHint(logger, cwd);
488
- let sigintCount = 0;
489
- let escalationTimer;
490
- const onSigint = () => {
491
- sigintCount += 1;
492
- if (sigintCount === 1) {
493
- logger.info("received SIGINT — shutting down (press Ctrl-C again to force-kill)");
494
- worker.kill("SIGTERM");
495
- escalationTimer = setTimeout(() => {
496
- worker.kill("SIGKILL");
497
- }, SIGINT_GRACE_MS);
498
- escalationTimer.unref();
499
- } else {
500
- worker.kill("SIGKILL");
501
- }
502
- };
503
- const onSigterm = () => {
504
- worker.kill("SIGTERM");
505
- };
506
- process.on("SIGINT", onSigint);
507
- process.on("SIGTERM", onSigterm);
508
- const code = await worker.exited;
509
- if (escalationTimer) {
510
- clearTimeout(escalationTimer);
511
- }
512
- process.off("SIGINT", onSigint);
513
- process.off("SIGTERM", onSigterm);
514
- return { code, plan };
515
- } finally {
516
- await teardown(handles);
517
- }
518
- };
519
- const execute = defineHandler(
520
- ({ cwd, logger, options }) => runDevCommand({
521
- apiSpec: parseApiSpec(options.apiSpec),
522
- // cerebro parses `--no-codegen`/`--no-studio` as the negation of the
523
- // `codegen`/`studio` booleans (runtime key drops the `no-` prefix), so a
524
- // passed flag arrives as `false`, absent as `true` (the option default).
525
- codegen: options.codegen === false ? false : void 0,
526
- cwd,
527
- logger,
528
- port: options.port,
529
- // Remote-binding mode obeys a clear precedence: an explicit `--remote`
530
- // flag wins, then `LUNORA_REMOTE` in the environment, then the `remote`
531
- // key in the project's `lunora.json` (a project default). See
532
- // `resolveRemoteEnabled` in @lunora/config.
533
- remote: resolveRemoteEnabled({
534
- configPreference: readProjectRemotePreference(cwd),
535
- envValue: process.env["LUNORA_REMOTE"],
536
- flag: options.remote
537
- }),
538
- studio: options.studio === false ? false : void 0,
539
- workerPort: options.workerPort
540
- })
541
- );
542
-
543
- export { execute, planDevCommand, resolveRemotePlan, runDevCommand };