@lunora/cli 1.0.0-alpha.40 → 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 (134) hide show
  1. package/LICENSE.md +33 -0
  2. package/README.md +3 -1
  3. package/dist/bin.mjs +2 -10
  4. package/dist/index.d.mts +1034 -374
  5. package/dist/index.d.ts +1034 -374
  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 +1 -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 +3 -131
  13. package/dist/packem_chunks/handler14.mjs +1 -65
  14. package/dist/packem_chunks/handler15.mjs +1 -58
  15. package/dist/packem_chunks/handler16.mjs +1 -80
  16. package/dist/packem_chunks/handler17.mjs +7 -43
  17. package/dist/packem_chunks/handler18.mjs +1 -105
  18. package/dist/packem_chunks/handler19.mjs +1 -170
  19. package/dist/packem_chunks/handler2.mjs +1 -114
  20. package/dist/packem_chunks/handler20.mjs +3 -94
  21. package/dist/packem_chunks/handler21.mjs +3 -94
  22. package/dist/packem_chunks/handler22.mjs +1 -0
  23. package/dist/packem_chunks/handler23.mjs +2 -0
  24. package/dist/packem_chunks/handler24.mjs +99 -0
  25. package/dist/packem_chunks/handler25.mjs +2 -0
  26. package/dist/packem_chunks/handler26.mjs +9 -0
  27. package/dist/packem_chunks/handler27.mjs +1 -0
  28. package/dist/packem_chunks/handler3.mjs +1 -204
  29. package/dist/packem_chunks/handler4.mjs +3 -33
  30. package/dist/packem_chunks/handler5.mjs +1 -49
  31. package/dist/packem_chunks/handler6.mjs +1 -91
  32. package/dist/packem_chunks/handler7.mjs +1 -42
  33. package/dist/packem_chunks/handler8.mjs +2 -174
  34. package/dist/packem_chunks/handler9.mjs +1 -315
  35. package/dist/packem_chunks/runCodegenCommand.mjs +4 -52
  36. package/dist/packem_chunks/runDeployCommand.mjs +11 -594
  37. package/dist/packem_chunks/runDevCommand.mjs +2 -0
  38. package/dist/packem_chunks/runInitCommand.mjs +165 -1432
  39. package/dist/packem_chunks/runResetCommand.mjs +1 -41
  40. package/dist/packem_chunks/runRpcCommand.mjs +1 -68
  41. package/dist/packem_shared/COMMANDS-aSTSMwZS.mjs +1 -0
  42. package/dist/packem_shared/DEFAULT_IMPORT_BATCH_SIZE-CyIsI3S1.mjs +1 -0
  43. package/dist/packem_shared/EXIT_CODE-D_XCixv8.mjs +1 -0
  44. package/dist/packem_shared/admin-token-VdUnvnKW.mjs +1 -0
  45. package/dist/packem_shared/admin-url-DJB8P6Jh.mjs +1 -0
  46. package/dist/packem_shared/api-spec-lYyq4vL6.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/cap-error-body-YBKO32BF.mjs +1 -0
  50. package/dist/packem_shared/catalog-CahzmDLV.mjs +1 -0
  51. package/dist/packem_shared/cli-CFsmCYWp.mjs +2 -0
  52. package/dist/packem_shared/cli-manifest-DoQ_3bzs.mjs +1 -0
  53. package/dist/packem_shared/cloudflare-credentials-BVmZnDZk.mjs +1 -0
  54. package/dist/packem_shared/codegen-error-AmH54ofi.mjs +3 -0
  55. package/dist/packem_shared/command-BgjsvUFg.mjs +1 -0
  56. package/dist/packem_shared/commands-DvSfLvyt.mjs +13 -0
  57. package/dist/packem_shared/createLogger-4TujevyB.mjs +2 -0
  58. package/dist/packem_shared/createRecordingSpawner-Ch7zuQQE.mjs +1 -0
  59. package/dist/packem_shared/deploy-target-resolve-BTCW1Iv4.mjs +1 -0
  60. package/dist/packem_shared/diffSnapshots-htqNZT8Q.mjs +7 -0
  61. package/dist/packem_shared/docker-AqLAkOyY.mjs +1 -0
  62. package/dist/packem_shared/health-probe-Bw9JFfIy.mjs +1 -0
  63. package/dist/packem_shared/import-BRM1hs7j.mjs +12 -0
  64. package/dist/packem_shared/index-oHZBGBwB.mjs +1 -0
  65. package/dist/packem_shared/insertSchemaExtension-DuiV6cba.mjs +8 -0
  66. package/dist/packem_shared/lint-ignore-report-DKZagpqk.mjs +2 -0
  67. package/dist/packem_shared/mcp-config-file-CcDTeXIq.mjs +2 -0
  68. package/dist/packem_shared/open-url-EnKy--w-.mjs +1 -0
  69. package/dist/packem_shared/output-format-DWe_tkTR.mjs +2 -0
  70. package/dist/packem_shared/parseManifest-CwPTKdtS.mjs +1 -0
  71. package/dist/packem_shared/path-containment-CgxYZggb.mjs +1 -0
  72. package/dist/packem_shared/plan-DVfi3TrN.mjs +5 -0
  73. package/dist/packem_shared/planDevCommand-IglbXy5A.mjs +1 -0
  74. package/dist/packem_shared/platform-diagnostics-Cn2g6Jh-.mjs +4 -0
  75. package/dist/packem_shared/prompt-cancelled-BvsNxg_Q.mjs +1 -0
  76. package/dist/packem_shared/render-lunora-error-C3OJY5wk.mjs +2 -0
  77. package/dist/packem_shared/resolve-Bdc9KEUv.mjs +5 -0
  78. package/dist/packem_shared/resolve-target-C_ZloTvd.mjs +1 -0
  79. package/dist/packem_shared/runAddCommand-BChdJQ5L.mjs +1 -0
  80. package/dist/packem_shared/runExportCommand-slAq5BCF.mjs +5 -0
  81. package/dist/packem_shared/runMigrateGenerateCommand-BwemPIOz.mjs +11 -0
  82. package/dist/packem_shared/schemaIrToSnapshot-BHuNOfgs.mjs +1 -0
  83. package/dist/packem_shared/secret-key-8DPOH98z.mjs +1 -0
  84. package/dist/packem_shared/shared-D-zCOmgY.mjs +1 -0
  85. package/dist/packem_shared/storage-DNzYhXR-.mjs +1 -0
  86. package/dist/packem_shared/tui-prompts-B3YwUhGw.mjs +4 -0
  87. package/dist/packem_shared/variables-CPYyJtsL.mjs +1 -0
  88. package/dist/packem_shared/wrangler-name-Dsk5K1f-.mjs +1 -0
  89. package/dist/packem_shared/wrangler-secrets-CTQPpalP.mjs +1 -0
  90. package/package.json +39 -19
  91. package/skills/README.md +35 -17
  92. package/skills/lunora/SKILL.md +154 -64
  93. package/skills/lunora-create-package/SKILL.md +97 -84
  94. package/skills/lunora-deploy/SKILL.md +175 -105
  95. package/skills/lunora-functions/SKILL.md +362 -56
  96. package/skills/lunora-migration-helper/SKILL.md +162 -137
  97. package/skills/lunora-performance-audit/SKILL.md +137 -95
  98. package/skills/lunora-quickstart/SKILL.md +137 -136
  99. package/skills/lunora-realtime/SKILL.md +140 -99
  100. package/skills/lunora-setup-auth/SKILL.md +162 -102
  101. package/skills/lunora-setup-hyperdrive/SKILL.md +130 -109
  102. package/skills/lunora-setup-hyperdrive-global/SKILL.md +93 -90
  103. package/skills/lunora-setup-mail/SKILL.md +85 -113
  104. package/skills/lunora-setup-scheduler/SKILL.md +132 -96
  105. package/skills/lunora-setup-storage/SKILL.md +189 -95
  106. package/dist/packem_chunks/planDevCommand.mjs +0 -541
  107. package/dist/packem_chunks/runMigrateGenerateCommand.mjs +0 -397
  108. package/dist/packem_shared/COMMANDS-B0ftFD_3.mjs +0 -948
  109. package/dist/packem_shared/DEFAULT_IMPORT_BATCH_SIZE-Ck-2bU08.mjs +0 -244
  110. package/dist/packem_shared/admin-url-4UzT-CI4.mjs +0 -19
  111. package/dist/packem_shared/api-spec-CtA6ilu4.mjs +0 -13
  112. package/dist/packem_shared/buildRegistryIndex-BcYe607_.mjs +0 -38
  113. package/dist/packem_shared/codegen-error-DJG-ghs_.mjs +0 -31
  114. package/dist/packem_shared/command-D3lB_4Az.mjs +0 -19
  115. package/dist/packem_shared/commands-B-gR09Z_.mjs +0 -845
  116. package/dist/packem_shared/createLogger-B40gPzQo.mjs +0 -78
  117. package/dist/packem_shared/createRecordingSpawner-DxI3mebw.mjs +0 -43
  118. package/dist/packem_shared/detect-package-manager-DYp7n3mJ.mjs +0 -61
  119. package/dist/packem_shared/diffSnapshots-BeDvvNiF.mjs +0 -161
  120. package/dist/packem_shared/docker-hMQ97KSQ.mjs +0 -21
  121. package/dist/packem_shared/insertSchemaExtension-DAqbfr9Z.mjs +0 -64
  122. package/dist/packem_shared/open-url-Dfq6fAyT.mjs +0 -41
  123. package/dist/packem_shared/output-format-wUvAN6AL.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/prompt-cancelled-APzX1Im-.mjs +0 -9
  127. package/dist/packem_shared/resolve-target-qbsJ_5sF.mjs +0 -16
  128. package/dist/packem_shared/runAddCommand-bnY6-HKb.mjs +0 -4
  129. package/dist/packem_shared/schema-drift-gate-BtBt0as0.mjs +0 -79
  130. package/dist/packem_shared/schemaIrToSnapshot-DdsljJT-.mjs +0 -43
  131. package/dist/packem_shared/storage-BIsph-Vk.mjs +0 -84
  132. package/dist/packem_shared/tui-prompts-BjEN8XgP.mjs +0 -658
  133. package/dist/packem_shared/wrangler-name-cy4yhm9j.mjs +0 -12
  134. package/dist/packem_shared/wrangler-secrets-P2_ZUR-k.mjs +0 -47
@@ -1,174 +1,2 @@
1
- import { existsSync, readFileSync } from 'node:fs';
2
- import { join } from 'node:path';
3
- import { findWranglerFile, readWranglerJsonc, validateWranglerConfig, isPlaceholderValue, DEV_VARS_FILE, parseDevVariableEntries, inferLunoraBindings } from '@lunora/config';
4
- import { d as defineHandler } from '../packem_shared/command-D3lB_4Az.mjs';
5
-
6
- const SECRET_KEY_PATTERN = /(?:KEY|PASSWORD|SECRET|TOKEN)$/u;
7
- const isD1PlaceholderId = (databaseId) => {
8
- const value = databaseId.trim();
9
- if (value === "") {
10
- return true;
11
- }
12
- const lower = value.toLowerCase();
13
- return lower.includes("replace") || lower.startsWith("<") && lower.endsWith(">");
14
- };
15
- const readWrangler = (cwd) => {
16
- const path = findWranglerFile(cwd);
17
- if (path === void 0) {
18
- return { parsed: void 0, path: void 0 };
19
- }
20
- const { parsed } = readWranglerJsonc(path);
21
- return { parsed, path };
22
- };
23
- const checkWrangler = (parsed, path, findings) => {
24
- if (path === void 0) {
25
- findings.push({
26
- fix: "Run `lunora init` (or `lunora dev`) to scaffold and reconcile wrangler.jsonc.",
27
- level: "fail",
28
- message: "wrangler.jsonc not found."
29
- });
30
- return;
31
- }
32
- if (parsed === void 0) {
33
- findings.push({ fix: `Check ${path} is valid JSONC.`, level: "fail", message: `Could not parse ${path}.` });
34
- return;
35
- }
36
- const report = validateWranglerConfig(parsed);
37
- const shardError = report.errors.find((error) => error.includes("SHARD"));
38
- if (shardError === void 0) {
39
- findings.push({ level: "pass", message: "wrangler.jsonc present with a SHARD durable-object binding." });
40
- } else {
41
- findings.push({ fix: "Run `lunora dev` to auto-reconcile, or add the binding manually.", level: "fail", message: shardError });
42
- }
43
- };
44
- const checkD1Placeholders = (parsed, findings) => {
45
- if (parsed === void 0) {
46
- return;
47
- }
48
- const databases = (parsed.d1_databases ?? []).filter(Boolean);
49
- for (const database of databases) {
50
- const databaseId = typeof database.database_id === "string" ? database.database_id : "";
51
- if (isD1PlaceholderId(databaseId)) {
52
- const label = typeof database.binding === "string" && database.binding.length > 0 ? database.binding : "<unnamed>";
53
- findings.push({
54
- fix: "Run `wrangler d1 create <name>` and paste the returned database_id into wrangler.jsonc.",
55
- level: "fail",
56
- message: `D1 binding "${label}" has a placeholder database_id ("${databaseId || "<empty>"}").`
57
- });
58
- }
59
- }
60
- };
61
- const checkEmailDestination = (parsed, findings) => {
62
- if (parsed === void 0) {
63
- return;
64
- }
65
- const bindings = (parsed.send_email ?? []).filter(Boolean);
66
- for (const binding of bindings) {
67
- const destination = typeof binding.destination_address === "string" ? binding.destination_address : "";
68
- if (destination !== "" && isPlaceholderValue(destination)) {
69
- const label = typeof binding.name === "string" && binding.name.length > 0 ? binding.name : "send_email";
70
- findings.push({
71
- fix: "Set destination_address to a verified Cloudflare Email Routing address.",
72
- level: "warn",
73
- message: `send_email binding "${label}" has a placeholder destination_address ("${destination}").`
74
- });
75
- }
76
- }
77
- };
78
- const checkDevVariables = (cwd, findings) => {
79
- const devVariablesPath = join(cwd, DEV_VARS_FILE);
80
- if (!existsSync(devVariablesPath)) {
81
- return;
82
- }
83
- let content;
84
- try {
85
- content = readFileSync(devVariablesPath, "utf8");
86
- } catch {
87
- return;
88
- }
89
- const unfilled = parseDevVariableEntries(content).filter((entry) => SECRET_KEY_PATTERN.test(entry.key) && isPlaceholderValue(entry.value)).map((entry) => entry.key);
90
- if (unfilled.length > 0) {
91
- findings.push({
92
- fix: "Run `lunora dev` to auto-generate secrets, or fill them in by hand.",
93
- level: "warn",
94
- message: `${DEV_VARS_FILE} has unfilled secret value(s): ${unfilled.join(", ")}.`
95
- });
96
- }
97
- };
98
- const checkAdminToken = (findings) => {
99
- const token = process.env.LUNORA_ADMIN_TOKEN;
100
- if (token === void 0 || token.trim() === "") {
101
- findings.push({
102
- fix: "Set LUNORA_ADMIN_TOKEN (env or `.dev.vars`) to enable admin RPCs / studio.",
103
- level: "info",
104
- message: "LUNORA_ADMIN_TOKEN is not set."
105
- });
106
- } else {
107
- findings.push({ level: "pass", message: "LUNORA_ADMIN_TOKEN is set." });
108
- }
109
- };
110
- const checkContainers = async (cwd, findings) => {
111
- let containers;
112
- try {
113
- ({ containers } = await inferLunoraBindings({ projectRoot: cwd }));
114
- } catch {
115
- return;
116
- }
117
- for (const container of containers) {
118
- if (container.exported) {
119
- findings.push({ level: "pass", message: `container "${container.exportName}" is exported by the worker entry.` });
120
- } else {
121
- findings.push({
122
- fix: 'Add `export * from "./lunora/_generated/containers"` to your worker entry (or re-run `vis generate lunora-container`).',
123
- level: "fail",
124
- message: `container "${container.exportName}" is declared but ${container.className} is not exported by the worker entry.`
125
- });
126
- }
127
- }
128
- };
129
- const runDoctor = async (options) => {
130
- const cwd = options.cwd ?? process.cwd();
131
- const findings = [];
132
- const { parsed, path } = readWrangler(cwd);
133
- checkWrangler(parsed, path, findings);
134
- checkD1Placeholders(parsed, findings);
135
- checkEmailDestination(parsed, findings);
136
- checkDevVariables(cwd, findings);
137
- checkAdminToken(findings);
138
- await checkContainers(cwd, findings);
139
- const code = findings.some((finding) => finding.level === "fail") ? 1 : 0;
140
- return { code, findings };
141
- };
142
- const LEVEL_LABEL = { fail: "FAIL", info: "INFO", pass: "PASS", warn: "WARN" };
143
- const renderReport = (result, logger) => {
144
- logger.info("lunora doctor — project preflight");
145
- for (const finding of result.findings) {
146
- const line = `[${LEVEL_LABEL[finding.level]}] ${finding.message}`;
147
- if (finding.level === "fail") {
148
- logger.error(line);
149
- } else if (finding.level === "warn") {
150
- logger.warn(line);
151
- } else {
152
- logger.info(line);
153
- }
154
- if (finding.fix !== void 0 && finding.level !== "pass") {
155
- logger.info(` fix: ${finding.fix}`);
156
- }
157
- }
158
- const fails = result.findings.filter((finding) => finding.level === "fail").length;
159
- const warns = result.findings.filter((finding) => finding.level === "warn").length;
160
- if (fails > 0) {
161
- logger.error(`${String(fails)} failure(s), ${String(warns)} warning(s).`);
162
- } else if (warns > 0) {
163
- logger.warn(`0 failures, ${String(warns)} warning(s).`);
164
- } else {
165
- logger.success("all checks passed.");
166
- }
167
- };
168
- const execute = defineHandler(async ({ cwd, logger }) => {
169
- const result = await runDoctor({ cwd});
170
- renderReport(result, logger);
171
- return { code: result.code };
172
- });
173
-
174
- export { execute, runDoctor };
1
+ import{r as v}from"../packem_shared/admin-token-VdUnvnKW.mjs";import{r as M,a as y}from"../packem_shared/admin-url-DJB8P6Jh.mjs";import{d as x}from"../packem_shared/command-BgjsvUFg.mjs";import{EXIT_CODE as u,exitCodeForStatus as T}from"../packem_shared/EXIT_CODE-D_XCixv8.mjs";import{a as I}from"../packem_shared/resolve-target-C_ZloTvd.mjs";const O="__lunora_admin__:getFunctionStats",_=10,f=(r,o)=>({calls:r.calls,conflicts:r.conflicts??0,errors:r.errors,lastErrorMessage:r.lastErrorMessage,maxDurationMs:r.maxDurationMs,meanDurationMs:r.calls===0?0:r.totalDurationMs/r.calls,path:r.path,rate:o}),k=(r,o)=>{const t=r.filter(e=>(e.conflicts??0)>0).map(e=>f(e,e.calls===0?0:(e.conflicts??0)/e.calls)).toSorted((e,s)=>s.rate-e.rate||s.conflicts-e.conflicts).slice(0,o),n=r.filter(e=>e.errors>0).map(e=>f(e,e.calls===0?0:e.errors/e.calls)).toSorted((e,s)=>s.rate-e.rate||s.errors-e.errors).slice(0,o),a=r.map(e=>f(e,0)).toSorted((e,s)=>s.maxDurationMs-e.maxDurationMs).slice(0,o);return{errorHotspots:n,latencyOutliers:a,totalFunctions:r.length,writeContention:t}},p=r=>`${(r*100).toFixed(1)}%`,$=r=>r<1e3?`${Math.round(r).toString()}ms`:`${(r/1e3).toFixed(2)}s`,m=(r,o,t,n)=>[r,...o.length===0?[` ${t}`]:o.map(a=>` ${n(a)}`)],E=r=>{const o=t=>t.lastErrorMessage?` — ${t.lastErrorMessage}`:"";return[`Insights over ${r.totalFunctions.toString()} function${r.totalFunctions===1?"":"s"}`,"",...m("Write-conflict hot-spots (OCC contention — candidates for sharding):",r.writeContention,"none — no write conflicts observed",t=>`${t.path} ${t.conflicts.toString()}/${t.calls.toString()} calls (${p(t.rate)})`),"",...m("Error hot-spots:",r.errorHotspots,"none — no errors observed",t=>`${t.path} ${t.errors.toString()}/${t.calls.toString()} calls (${p(t.rate)})${o(t)}`),"",...m("Latency outliers (slowest single call):",r.latencyOutliers,"none — no functions have run",t=>`${t.path} max ${$(t.maxDurationMs)}, mean ${$(t.meanDurationMs)} over ${t.calls.toString()} calls`)].join(`
2
+ `)},i=(r,o,t)=>(r.error(o),{code:t,error:o}),F=r=>r===void 0||!Number.isFinite(r)||r<=0?_:Math.floor(r),A=async r=>{const{logger:o}=r;if(r.prod&&r.url===void 0)return i(o,"--prod requires an explicit --url (refusing to report from the implicit localhost worker)",u.USAGE);const t=M(r.url,o,r.cwd);if(t===void 0)return{code:u.USAGE,error:"could not resolve a usable worker URL"};const{token:n}=v({cwd:r.cwd??process.cwd(),token:r.token,url:t});if(!n)return i(o,"admin token required — pass --token, set LUNORA_ADMIN_TOKEN, or add it to .dev.vars (local targets only)",u.AUTH);const a=`${t}/_lunora/rpc`,e=y,s={args:{},functionPath:O};r.shard!==void 0&&(s.shardKey=r.shard),o.info(`POST ${a} -> insights`);const l=await e(a,{body:JSON.stringify(s),headers:{authorization:`Bearer ${n}`,"content-type":"application/json"},method:"POST"}),c=await l.text();if(!l.ok)return i(o,`insights failed: HTTP ${String(l.status)}: ${c}`,T(l.status));let d;try{d=JSON.parse(c)}catch{return i(o,`insights failed: worker returned non-JSON: ${c}`,1)}const S=d.result??d,{functions:h}=S;if(!Array.isArray(h))return i(o,"insights failed: response carried no `functions` array",1);const g=k(h,F(r.limit));return r.format!=="json"&&o.info(E(g)),{code:0,report:g}},L=x(async({cwd:r,format:o,logger:t,options:n})=>{const a=n.limit===void 0?void 0:Number.parseInt(n.limit,10),e=await A({cwd:r,fetchImpl:void 0,format:o,limit:a,logger:t,prod:n.prod,shard:n.shard,token:n.token,url:I({cwd:r,prod:n.prod===!0,url:n.url})});return{code:e.code,data:e.report,error:e.error}});export{k as buildInsightsReport,L as execute,E as formatInsightsReport,A as runInsightsCommand};
@@ -1,315 +1 @@
1
- import { writeFileSync, existsSync, readFileSync } from 'node:fs';
2
- import { join } from 'node:path';
3
- import { DEV_VARS_FILE, DEV_VARS_KEY_PATTERN, generateSecretValue, DEV_VARS_EXAMPLE_FILE, parseDevVariableEntries, isPlaceholderValue, packageNamesFromBindings, inferLunoraBindings, requiredSecrets, isMintableSecretKey } from '@lunora/config';
4
- import { d as defineHandler } from '../packem_shared/command-D3lB_4Az.mjs';
5
- import { defaultSpawner } from '../packem_shared/createRecordingSpawner-DxI3mebw.mjs';
6
- import { l as listRemoteSecrets } from '../packem_shared/wrangler-secrets-P2_ZUR-k.mjs';
7
-
8
- const NEWLINE_PRESENT = /[\r\n]/u;
9
- const UNREPRESENTABLE_PRESENT = /["\\]/u;
10
- const parseDevVariables = (content) => {
11
- const map = /* @__PURE__ */ new Map();
12
- for (const entry of parseDevVariableEntries(content)) {
13
- map.set(entry.key, entry);
14
- }
15
- return map;
16
- };
17
- const serializeDevVariables = (map) => {
18
- const lines = [];
19
- for (const entry of map.values()) {
20
- lines.push(`${entry.key}="${entry.value}"`);
21
- }
22
- return `${lines.join("\n")}
23
- `;
24
- };
25
- const redact = (value) => {
26
- if (value.length <= 4) {
27
- return "****";
28
- }
29
- return `${value.slice(0, 4)}${"*".repeat(Math.min(8, value.length - 4))}`;
30
- };
31
- const loadDevVariables = (devVariablesPath) => {
32
- if (!existsSync(devVariablesPath)) {
33
- return /* @__PURE__ */ new Map();
34
- }
35
- return parseDevVariables(readFileSync(devVariablesPath, "utf8"));
36
- };
37
- const runEnvList = (context) => {
38
- const map = loadDevVariables(context.devVariablesPath);
39
- if (map.size === 0) {
40
- context.logger.info(`${DEV_VARS_FILE}: (empty)`);
41
- return { code: 0, descriptors: [] };
42
- }
43
- for (const entry of map.values()) {
44
- context.logger.info(`${entry.key}=${redact(entry.value)}`);
45
- }
46
- return { code: 0, descriptors: [] };
47
- };
48
- const runEnvGet = (context) => {
49
- const { devVariablesPath, logger, options } = context;
50
- if (!options.key) {
51
- logger.error("env get requires a key. Usage: lunora env get <KEY>");
52
- return { code: 1, descriptors: [] };
53
- }
54
- const entry = loadDevVariables(devVariablesPath).get(options.key);
55
- if (!entry) {
56
- logger.error(`env: ${options.key} is not set in ${DEV_VARS_FILE}`);
57
- return { code: 1, descriptors: [] };
58
- }
59
- process.stdout.write(`${entry.value}
60
- `);
61
- return { code: 0, descriptors: [] };
62
- };
63
- const runEnvSet = (context) => {
64
- const { devVariablesPath, logger, options } = context;
65
- if (!options.key) {
66
- logger.error("env set requires a key. Usage: lunora env set <KEY> <VALUE>");
67
- return { code: 1, descriptors: [] };
68
- }
69
- if (!DEV_VARS_KEY_PATTERN.test(options.key)) {
70
- logger.error(`env: invalid key "${options.key}" — must match [A-Za-z_][A-Za-z0-9_]*`);
71
- return { code: 1, descriptors: [] };
72
- }
73
- if (options.value === void 0) {
74
- logger.error("env set requires a value. Usage: lunora env set <KEY> <VALUE>");
75
- return { code: 1, descriptors: [] };
76
- }
77
- if (NEWLINE_PRESENT.test(options.value)) {
78
- logger.error(`env: value for "${options.key}" contains a newline, which .dev.vars cannot represent`);
79
- return { code: 1, descriptors: [] };
80
- }
81
- if (UNREPRESENTABLE_PRESENT.test(options.value)) {
82
- logger.error(`env: value for "${options.key}" contains a double-quote or backslash, which .dev.vars cannot round-trip`);
83
- return { code: 1, descriptors: [] };
84
- }
85
- const map = loadDevVariables(devVariablesPath);
86
- map.set(options.key, { key: options.key, value: options.value });
87
- writeFileSync(devVariablesPath, serializeDevVariables(map), "utf8");
88
- logger.success(`env: set ${options.key} (${redact(options.value)}) in ${DEV_VARS_FILE}`);
89
- return { code: 0, descriptors: [] };
90
- };
91
- const runEnvUnset = (context) => {
92
- const { devVariablesPath, logger, options } = context;
93
- if (!options.key) {
94
- logger.error("env unset requires a key. Usage: lunora env unset <KEY>");
95
- return { code: 1, descriptors: [] };
96
- }
97
- const map = loadDevVariables(devVariablesPath);
98
- if (!map.delete(options.key)) {
99
- logger.warn(`env: ${options.key} was not set in ${DEV_VARS_FILE}`);
100
- return { code: 0, descriptors: [] };
101
- }
102
- writeFileSync(devVariablesPath, serializeDevVariables(map), "utf8");
103
- logger.success(`env: unset ${options.key} in ${DEV_VARS_FILE}`);
104
- return { code: 0, descriptors: [] };
105
- };
106
- const runEnvPush = async (context) => {
107
- const { devVariablesPath, logger, options } = context;
108
- if (!options.yes) {
109
- logger.error("env push uploads secrets to Cloudflare. Re-run with --yes to confirm.");
110
- return { code: 1, descriptors: [] };
111
- }
112
- const map = loadDevVariables(devVariablesPath);
113
- if (map.size === 0) {
114
- logger.warn(`${DEV_VARS_FILE}: nothing to push (empty)`);
115
- return { code: 0, descriptors: [] };
116
- }
117
- const spawner = options.spawner ?? defaultSpawner;
118
- const descriptors = [];
119
- for (const entry of map.values()) {
120
- const args = ["exec", "wrangler", "secret", "put", entry.key];
121
- if (options.prod) {
122
- args.push("--env", "production");
123
- }
124
- if (options.temporary) {
125
- args.push("--temporary");
126
- }
127
- const descriptor = {
128
- args,
129
- command: "pnpm",
130
- cwd: options.cwd ?? process.cwd(),
131
- // `wrangler secret put <name>` reads the value from stdin. We
132
- // pipe it through the spawner's `input` channel so the secret
133
- // never lands on the command line, in env, or in shell history.
134
- input: entry.value
135
- };
136
- descriptors.push(descriptor);
137
- logger.info(`pushing ${entry.key} -> wrangler secret${options.prod ? " (production)" : ""}`);
138
- const result = await spawner(descriptor);
139
- if (result.code !== 0) {
140
- logger.error(`env push: failed at ${entry.key} (exit ${String(result.code)})`);
141
- return { code: result.code, descriptors };
142
- }
143
- }
144
- logger.success(`env: pushed ${String(map.size)} secret(s)`);
145
- return { code: 0, descriptors };
146
- };
147
- const fetchRemoteSecretNames = (context) => {
148
- const lister = context.options.secretLister ?? listRemoteSecrets;
149
- return lister({
150
- cwd: context.cwd,
151
- env: context.options.prod ? "production" : void 0,
152
- temporary: context.options.temporary
153
- });
154
- };
155
- const runEnvDiff = async (context) => {
156
- const { devVariablesPath, logger } = context;
157
- const remote = await fetchRemoteSecretNames(context);
158
- if (!remote.ok) {
159
- logger.error(`env diff: ${remote.error ?? "failed to list remote secrets"}`);
160
- return { code: 1, descriptors: [] };
161
- }
162
- const localKeys = new Set(loadDevVariables(devVariablesPath).keys());
163
- const remoteKeys = new Set(remote.names);
164
- const localOnly = [...localKeys].filter((key) => !remoteKeys.has(key)).toSorted((a, b) => a.localeCompare(b));
165
- const remoteOnly = remote.names.filter((name) => !localKeys.has(name));
166
- const both = [...localKeys].filter((key) => remoteKeys.has(key)).toSorted((a, b) => a.localeCompare(b));
167
- for (const key of localOnly) {
168
- logger.info(`local only (run \`lunora env push\`): ${key}`);
169
- }
170
- for (const key of remoteOnly) {
171
- logger.info(`remote only (in Cloudflare, not ${DEV_VARS_FILE}): ${key}`);
172
- }
173
- logger.info(`in both: ${String(both.length)} secret(s)`);
174
- if (localOnly.length === 0 && remoteOnly.length === 0) {
175
- logger.success("env diff: local and remote secret names match");
176
- }
177
- return { code: 0, descriptors: [] };
178
- };
179
- const runEnvDoctor = (context) => {
180
- const { cwd, devVariablesPath, logger } = context;
181
- const examplePath = join(cwd, DEV_VARS_EXAMPLE_FILE);
182
- if (!existsSync(examplePath)) {
183
- logger.info(`env doctor: no ${DEV_VARS_EXAMPLE_FILE} to check against — nothing to validate.`);
184
- return { code: 0, descriptors: [] };
185
- }
186
- const exampleKeys = parseDevVariableEntries(readFileSync(examplePath, "utf8")).map((entry) => entry.key);
187
- const current = loadDevVariables(devVariablesPath);
188
- if (!existsSync(devVariablesPath)) {
189
- logger.error(`env doctor: ${DEV_VARS_FILE} is missing. Run \`lunora dev\` to scaffold it, or \`lunora env set <KEY> <VALUE>\`.`);
190
- logger.info(`expected (from ${DEV_VARS_EXAMPLE_FILE}): ${exampleKeys.join(", ")}`);
191
- return { code: 1, descriptors: [] };
192
- }
193
- const missing = exampleKeys.filter((key) => !current.has(key));
194
- const placeholders = [...current.values()].filter((entry) => isPlaceholderValue(entry.value)).map((entry) => entry.key);
195
- const exampleKeySet = new Set(exampleKeys);
196
- const extra = [...current.keys()].filter((key) => !exampleKeySet.has(key));
197
- for (const key of missing) {
198
- logger.error(`missing: ${key} is in ${DEV_VARS_EXAMPLE_FILE} but not ${DEV_VARS_FILE}`);
199
- }
200
- for (const key of placeholders) {
201
- logger.error(`unset: ${key} still has a placeholder value`);
202
- }
203
- for (const key of extra) {
204
- logger.info(`extra: ${key} is set locally but not listed in ${DEV_VARS_EXAMPLE_FILE}`);
205
- }
206
- if (missing.length === 0 && placeholders.length === 0) {
207
- logger.success(`env doctor: ${DEV_VARS_FILE} looks good (${String(current.size)} var(s)).`);
208
- return { code: 0, descriptors: [] };
209
- }
210
- return { code: 1, descriptors: [] };
211
- };
212
- const resolveMintableKeys = async (context) => {
213
- let packages = [];
214
- try {
215
- packages = packageNamesFromBindings(await inferLunoraBindings({ projectRoot: context.cwd }));
216
- } catch {
217
- }
218
- const fromPackages = requiredSecrets(packages).map((entry) => entry.key).filter((key) => isMintableSecretKey(key));
219
- const fromLocal = [...loadDevVariables(context.devVariablesPath).keys()].filter((key) => isMintableSecretKey(key));
220
- return [.../* @__PURE__ */ new Set([...fromPackages, ...fromLocal])];
221
- };
222
- const runEnvGenerate = async (context) => {
223
- const { devVariablesPath, logger, options } = context;
224
- let keys;
225
- if (options.key === void 0) {
226
- keys = await resolveMintableKeys(context);
227
- if (keys.length === 0) {
228
- logger.info("env generate: no locally-generatable secrets for this project. Name one explicitly: lunora env generate <KEY>");
229
- return { code: 0, descriptors: [] };
230
- }
231
- } else {
232
- if (!DEV_VARS_KEY_PATTERN.test(options.key)) {
233
- logger.error(`env: invalid key "${options.key}" — must match [A-Za-z_][A-Za-z0-9_]*`);
234
- return { code: 1, descriptors: [] };
235
- }
236
- keys = [options.key];
237
- }
238
- const generated = keys.map((key) => {
239
- return { key, value: generateSecretValue() };
240
- });
241
- if (options.set === true) {
242
- const map = loadDevVariables(devVariablesPath);
243
- for (const entry of generated) {
244
- map.set(entry.key, entry);
245
- }
246
- writeFileSync(devVariablesPath, serializeDevVariables(map), "utf8");
247
- logger.success(`env: generated ${String(generated.length)} secret(s) into ${DEV_VARS_FILE}: ${generated.map((entry) => entry.key).join(", ")}`);
248
- return { code: 0, descriptors: [] };
249
- }
250
- for (const entry of generated) {
251
- process.stdout.write(`${entry.key}=${entry.value}
252
- `);
253
- }
254
- return { code: 0, descriptors: [] };
255
- };
256
- const runEnvCommand = async (options) => {
257
- const cwd = options.cwd ?? process.cwd();
258
- const context = {
259
- cwd,
260
- devVariablesPath: join(cwd, DEV_VARS_FILE),
261
- logger: options.logger,
262
- options
263
- };
264
- switch (options.subcommand) {
265
- case "diff": {
266
- return runEnvDiff(context);
267
- }
268
- case "doctor": {
269
- return runEnvDoctor(context);
270
- }
271
- case "generate": {
272
- return runEnvGenerate(context);
273
- }
274
- case "get": {
275
- return runEnvGet(context);
276
- }
277
- case "list": {
278
- return runEnvList(context);
279
- }
280
- case "push": {
281
- return runEnvPush(context);
282
- }
283
- case "set": {
284
- return runEnvSet(context);
285
- }
286
- case "unset": {
287
- return runEnvUnset(context);
288
- }
289
- default: {
290
- options.logger.error(`env: unknown subcommand "${options.subcommand}"`);
291
- return { code: 1, descriptors: [] };
292
- }
293
- }
294
- };
295
- const isEnvSubcommand = (value) => value === "list" || value === "get" || value === "set" || value === "unset" || value === "push" || value === "diff" || value === "doctor" || value === "generate";
296
- const execute = defineHandler(({ argument, cwd, logger, options }) => {
297
- const sub = argument[0];
298
- if (!isEnvSubcommand(sub)) {
299
- logger.error(`env: unknown subcommand "${sub ?? ""}" — expected list | get | set | unset | push | diff | doctor | generate`);
300
- return { code: 1 };
301
- }
302
- return runEnvCommand({
303
- cwd,
304
- key: argument[1],
305
- logger,
306
- prod: options.prod === true,
307
- set: options.set === true,
308
- subcommand: sub,
309
- temporary: options.temporary === true,
310
- value: argument[2],
311
- yes: options.yes === true
312
- });
313
- });
314
-
315
- export { execute, runEnvCommand };
1
+ import{existsSync as u,rmSync as a}from"node:fs";import{join as i}from"node:path";import{writeLinkedProject as d,LINKED_PROJECT_FILE as o}from"@lunora/config";import{d as k}from"../packem_shared/command-BgjsvUFg.mjs";import{EXIT_CODE as c}from"../packem_shared/EXIT_CODE-D_XCixv8.mjs";import{r as s}from"../packem_shared/wrangler-name-Dsk5K1f-.mjs";const v=r=>{try{const{protocol:n}=new URL(r);return n==="http:"||n==="https:"}catch{return!1}},f=(r,n)=>{const e=i(r,o);return u(e)?(a(e),n.success(`link: removed ${o}`),{code:0}):(n.warn(`link: no ${o} to remove`),{code:0})},w=r=>{const n=r.cwd??process.cwd(),{logger:e}=r;if(r.remove)return f(n,e);if(r.url===void 0||r.url==="")return e.error("link requires a deployed Worker URL. Usage: lunora link --url <https://your-worker>"),{code:c.USAGE};if(!v(r.url))return e.error(`link: invalid --url "${r.url}" — expected an http(s) URL`),{code:c.USAGE};const l=r.now??(()=>new Date().toISOString()),t={env:r.env,linkedAt:l(),workerName:r.name??s(n),workerUrl:r.url},m=d(n,t);return e.success(`link: ${t.workerName??"(unnamed worker)"} -> ${r.url}`),e.info(`link: wrote ${m}`),t.env!==void 0&&e.info(`link: environment "${t.env}"`),{code:0,link:t}},y=k(({cwd:r,logger:n,options:e})=>w({cwd:r,env:e.env,logger:n,name:e.name,remove:e.remove===!0,url:e.url}));export{y as execute,w as runLinkCommand};
@@ -1,52 +1,4 @@
1
- import { runCodegen } from '@lunora/codegen';
2
- import { p as parseApiSpec } from '../packem_shared/api-spec-CtA6ilu4.mjs';
3
- import { d as defineHandler } from '../packem_shared/command-D3lB_4Az.mjs';
4
- import { v as validateOutputFormat, p as printJson, l as loggerForFormat, i as isJsonFormat } from '../packem_shared/output-format-wUvAN6AL.mjs';
5
-
6
- const CRON_TRIGGER_LIMIT = 3;
7
- const runCodegenCommand = (options) => {
8
- const projectRoot = options.cwd ?? process.cwd();
9
- const json = isJsonFormat(options.format);
10
- const logger = loggerForFormat(options.format, options.logger);
11
- const formatError = validateOutputFormat("codegen", options.format);
12
- if (formatError !== void 0) {
13
- options.logger.error(formatError);
14
- return { advisories: [], cronTriggers: [], error: formatError, outputDirectory: "" };
15
- }
16
- const result = runCodegen({ apiSpec: options.apiSpec, projectRoot });
17
- const commandResult = {
18
- advisories: result.advisories.map((advisory) => {
19
- return {
20
- detail: advisory.detail,
21
- level: advisory.level,
22
- name: advisory.name,
23
- remediation: advisory.remediation
24
- };
25
- }),
26
- cronTriggers: result.cronTriggers,
27
- outputDirectory: result.outputDirectory
28
- };
29
- logger.success(`codegen wrote dataModel.ts, api.ts, server.ts to ${result.outputDirectory}`);
30
- if (result.advisories.length > 0) {
31
- const count = result.advisories.length;
32
- const lines = result.advisories.map((advisory) => ` [${advisory.level}] ${advisory.name} — ${advisory.detail}
33
- ↳ ${advisory.remediation}`);
34
- logger.warn(`${count.toString()} schema ${count === 1 ? "advisory" : "advisories"}:
35
- ${lines.join("\n")}`);
36
- }
37
- if (result.cronTriggers.length > CRON_TRIGGER_LIMIT) {
38
- logger.warn(
39
- `${result.cronTriggers.length.toString()} distinct cron expressions declared — Cloudflare allows at most ${CRON_TRIGGER_LIMIT.toString()} Cron Triggers per Worker. Consolidate schedules (jobs can share one expression) or move finer-grained work to Durable Object alarms via @lunora/scheduler (runAfter/runAt).`
40
- );
41
- }
42
- if (json) {
43
- printJson(commandResult);
44
- }
45
- return commandResult;
46
- };
47
- const execute = defineHandler(({ cwd, logger, options }) => {
48
- const result = runCodegenCommand({ apiSpec: parseApiSpec(options.apiSpec), cwd, format: options.format, logger });
49
- return { code: result.error === void 0 ? 0 : 1 };
50
- });
51
-
52
- export { execute, runCodegenCommand };
1
+ import{runCodegen as h}from"@lunora/codegen";import{resolveLazyFunctions as m,applyLintIgnores as w,detectLintTools as y,inferLunoraBindings as $,resolveSchemaDirectory as A}from"@lunora/config";import{warnCloudflareCliConfigOnce as T,wranglerCodegenInputs as C,collectExportGaps as D}from"@lunora/config/cloudflare";import{r as S,a as x,e as k}from"../packem_shared/platform-diagnostics-Cn2g6Jh-.mjs";import{p as E}from"../packem_shared/api-spec-lYyq4vL6.mjs";import{d as b}from"../packem_shared/command-BgjsvUFg.mjs";import{r as I}from"../packem_shared/deploy-target-resolve-BTCW1Iv4.mjs";import{EXIT_CODE as L}from"../packem_shared/EXIT_CODE-D_XCixv8.mjs";import{r as O}from"../packem_shared/lint-ignore-report-DKZagpqk.mjs";const u=3,R=r=>{const s=r.cwd??process.cwd(),{logger:i}=r,e=S(r),o=I(s,r.target);if(o.target===void 0)return r.logger.error(o.error??"unknown deploy target"),{advisories:[],code:L.USAGE,cronTriggers:[],error:o.error??"unknown deploy target",failedAdvisories:0,outputDirectory:""};const{target:a}=o,t=h({apiSpec:r.apiSpec,lazyFunctions:m(r.lazyFunctions),projectRoot:s,target:a,...C(s)}),d={advisories:t.advisories.map(n=>({detail:n.detail,level:n.level,name:n.name,remediation:n.remediation})),cronTriggers:t.cronTriggers,failedAdvisories:0,outputDirectory:t.outputDirectory};if(i.success(`codegen wrote ${t.writtenFiles.join(", ")} to ${t.outputDirectory}`),t.advisories.length>0){const n=t.advisories.length,v=t.advisories.map(c=>` [${c.level}] ${c.name} — ${c.detail}
2
+ ↳ ${c.remediation}`);i.warn(`${n.toString()} schema ${n===1?"advisory":"advisories"}:
3
+ ${v.join(`
4
+ `)}`)}const g=x(t.platformDiagnostics,i);g.errors.length>0&&(d.error=g.errors.join("; "));const{errorAdvisories:l,names:p,shouldBlock:f}=k(d.advisories,e);return f&&i.error(`${l.length.toString()} ERROR-level ${l.length===1?"advisory":"advisories"} (${p.join(", ")}). Codegen wrote its output; this exit code is the gate. Pass --no-strict-advisories to downgrade it to a warning.`),t.cronTriggers.length>u&&i.warn(`${t.cronTriggers.length.toString()} distinct cron expressions declared — Cloudflare allows at most ${u.toString()} Cron Triggers per Worker. Consolidate schedules (jobs can share one expression) or move finer-grained work to Durable Object alarms via @lunora/scheduler (runAfter/runAt).`),{...d,failedAdvisories:e?l.length:0}},F=async(r,s)=>{let i;try{i=D(await $({projectRoot:r,schemaDir:A(r)}))}catch(e){s.warn(`could not check whether declared containers/workflows/agents are re-exported by the worker entry: ${e instanceof Error?e.message:String(e)}. Run \`lunora doctor\` to check explicitly.`);return}for(const e of i)s.warn(`${e.kind} "${e.exportName}" is declared but ${e.className} is not exported by the worker entry — add \`export * from "./lunora/_generated/${e.module}"\` so wrangler can provision its binding. Until then it deploys with nothing to run.`)},G=(r,s)=>{try{O(w(r,y(r)),s)}catch{}},W=b(async({cwd:r,format:s,logger:i,options:e})=>{const o=R({apiSpec:E(e.apiSpec),cwd:r,format:s,lazyFunctions:m(e.lazyFunctions),logger:i,strictAdvisories:e.strictAdvisories,target:e.target});if(o.outputDirectory!==""){const a=i;G(r,a),await F(r,a),T(r,t=>{a.warn(t)})}return{code:o.code??(o.error===void 0&&o.failedAdvisories===0?0:1),data:{advisories:o.advisories,cronTriggers:o.cronTriggers,failedAdvisories:o.failedAdvisories,outputDirectory:o.outputDirectory},error:o.error}});export{W as execute,R as runCodegenCommand};