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

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