@lunora/cli 1.0.0-alpha.12 → 1.0.0-alpha.120

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 (94) hide show
  1. package/LICENSE.md +6 -0
  2. package/__assets__/package-og.svg +1 -1
  3. package/dist/bin.mjs +2 -10
  4. package/dist/index.d.mts +357 -321
  5. package/dist/index.d.ts +357 -321
  6. package/dist/index.mjs +1 -19
  7. package/dist/packem_chunks/handler.mjs +1 -150
  8. package/dist/packem_chunks/handler10.mjs +1 -22
  9. package/dist/packem_chunks/handler11.mjs +1 -192
  10. package/dist/packem_chunks/handler12.mjs +2 -131
  11. package/dist/packem_chunks/handler13.mjs +2 -65
  12. package/dist/packem_chunks/handler14.mjs +1 -58
  13. package/dist/packem_chunks/handler15.mjs +1 -79
  14. package/dist/packem_chunks/handler16.mjs +1 -43
  15. package/dist/packem_chunks/handler17.mjs +1 -105
  16. package/dist/packem_chunks/handler18.mjs +3 -170
  17. package/dist/packem_chunks/handler19.mjs +1 -89
  18. package/dist/packem_chunks/handler2.mjs +2 -114
  19. package/dist/packem_chunks/handler20.mjs +1 -94
  20. package/dist/packem_chunks/handler21.mjs +2 -311
  21. package/dist/packem_chunks/handler22.mjs +11 -0
  22. package/dist/packem_chunks/handler3.mjs +2 -204
  23. package/dist/packem_chunks/handler4.mjs +1 -33
  24. package/dist/packem_chunks/handler5.mjs +1 -49
  25. package/dist/packem_chunks/handler6.mjs +1 -91
  26. package/dist/packem_chunks/handler7.mjs +1 -42
  27. package/dist/packem_chunks/handler8.mjs +1 -174
  28. package/dist/packem_chunks/handler9.mjs +8 -16
  29. package/dist/packem_chunks/planDevCommand.mjs +7 -500
  30. package/dist/packem_chunks/runCodegenCommand.mjs +4 -52
  31. package/dist/packem_chunks/runDeployCommand.mjs +1 -504
  32. package/dist/packem_chunks/runInitCommand.mjs +996 -1265
  33. package/dist/packem_chunks/runMigrateGenerateCommand.mjs +9 -395
  34. package/dist/packem_chunks/runResetCommand.mjs +1 -41
  35. package/dist/packem_chunks/runRpcCommand.mjs +1 -68
  36. package/dist/packem_shared/COMMANDS-CQNSsSgS.mjs +3 -0
  37. package/dist/packem_shared/DEFAULT_IMPORT_BATCH_SIZE-DL87PIEl.mjs +8 -0
  38. package/dist/packem_shared/admin-url-DfVehV3e.mjs +1 -0
  39. package/dist/packem_shared/api-spec-BENwiyUa.mjs +1 -0
  40. package/dist/packem_shared/buildRegistryIndex-DwySASBu.mjs +1 -0
  41. package/dist/packem_shared/codegen-error-DJN6pTH5.mjs +3 -0
  42. package/dist/packem_shared/command-Bjv4VmYA.mjs +1 -0
  43. package/dist/packem_shared/commands-BhX2Bo9B.mjs +19 -0
  44. package/dist/packem_shared/createLogger--C3x1FNE.mjs +2 -0
  45. package/dist/packem_shared/createRecordingSpawner-ByIqBepG.mjs +1 -0
  46. package/dist/packem_shared/detect-package-manager-B2eIuAiP.mjs +1 -0
  47. package/dist/packem_shared/diffSnapshots-9bDd9nOK.mjs +5 -0
  48. package/dist/packem_shared/docker-CKvYE9YF.mjs +1 -0
  49. package/dist/packem_shared/insertSchemaExtension-DZReBZ4_.mjs +8 -0
  50. package/dist/packem_shared/open-url-CTU_g9gr.mjs +1 -0
  51. package/dist/packem_shared/output-format-D7cKB-O5.mjs +2 -0
  52. package/dist/packem_shared/parseManifest-x3WsxKHz.mjs +1 -0
  53. package/dist/packem_shared/prompt-cancelled-C8Sj7OqI.mjs +1 -0
  54. package/dist/packem_shared/resolve-target-vxaXHmvg.mjs +1 -0
  55. package/dist/packem_shared/runAddCommand--TBYJQYi.mjs +1 -0
  56. package/dist/packem_shared/schema-drift-gate-CpqG-xP4.mjs +1 -0
  57. package/dist/packem_shared/schemaIrToSnapshot-Clwd2A8e.mjs +1 -0
  58. package/dist/packem_shared/storage-DOvAKGi4.mjs +1 -0
  59. package/dist/packem_shared/tui-prompts-CCt3jm1k.mjs +4 -0
  60. package/dist/packem_shared/vectorize-metadata-BvZbbqUD.mjs +1 -0
  61. package/dist/packem_shared/wrangler-name-HIl0Z6yx.mjs +1 -0
  62. package/dist/packem_shared/wrangler-secrets-BMRJwKQU.mjs +1 -0
  63. package/package.json +23 -16
  64. package/skills/README.md +28 -14
  65. package/skills/lunora/SKILL.md +48 -9
  66. package/skills/lunora-functions/SKILL.md +38 -3
  67. package/skills/lunora-migration-helper/SKILL.md +36 -17
  68. package/skills/lunora-performance-audit/SKILL.md +36 -6
  69. package/skills/lunora-quickstart/SKILL.md +86 -24
  70. package/skills/lunora-realtime/SKILL.md +43 -30
  71. package/dist/packem_shared/COMMANDS-D3h9Iwvl.mjs +0 -944
  72. package/dist/packem_shared/DEFAULT_IMPORT_BATCH_SIZE-Ck-2bU08.mjs +0 -244
  73. package/dist/packem_shared/admin-url-4UzT-CI4.mjs +0 -19
  74. package/dist/packem_shared/api-spec-CtA6ilu4.mjs +0 -13
  75. package/dist/packem_shared/buildRegistryIndex-BcYe607_.mjs +0 -38
  76. package/dist/packem_shared/command-BC30oSBW.mjs +0 -14
  77. package/dist/packem_shared/commands-DVr4lduS.mjs +0 -812
  78. package/dist/packem_shared/createLogger-B40gPzQo.mjs +0 -78
  79. package/dist/packem_shared/createRecordingSpawner-DxI3mebw.mjs +0 -43
  80. package/dist/packem_shared/detect-package-manager-DYp7n3mJ.mjs +0 -61
  81. package/dist/packem_shared/diffSnapshots-BeDvvNiF.mjs +0 -161
  82. package/dist/packem_shared/docker-hMQ97KSQ.mjs +0 -21
  83. package/dist/packem_shared/insertSchemaExtension-DAqbfr9Z.mjs +0 -64
  84. package/dist/packem_shared/open-url-Dfq6fAyT.mjs +0 -41
  85. package/dist/packem_shared/output-format-wUvAN6AL.mjs +0 -17
  86. package/dist/packem_shared/parseArgs-YXFuKdEk.mjs +0 -56
  87. package/dist/packem_shared/parseManifest--vZf2FY1.mjs +0 -94
  88. package/dist/packem_shared/resolve-target-qbsJ_5sF.mjs +0 -16
  89. package/dist/packem_shared/runAddCommand-C-NOz8NJ.mjs +0 -4
  90. package/dist/packem_shared/schema-drift-gate-BtBt0as0.mjs +0 -79
  91. package/dist/packem_shared/schemaIrToSnapshot-DdsljJT-.mjs +0 -43
  92. package/dist/packem_shared/storage-DL9OE4oE.mjs +0 -84
  93. package/dist/packem_shared/tui-prompts-M6OWsuyw.mjs +0 -663
  94. package/dist/packem_shared/wrangler-name-cy4yhm9j.mjs +0 -12
@@ -1,397 +1,11 @@
1
- import { existsSync, mkdirSync, writeFileSync, mkdtempSync, rmSync, readFileSync } from 'node:fs';
2
- import { tmpdir } from 'node:os';
3
- import { discoverSchema, discoverMigrations } from '@lunora/codegen';
4
- import { join } from '@visulima/path';
5
- import { Project } from 'ts-morph';
6
- import { r as resolveAdminBaseUrl } from '../packem_shared/admin-url-4UzT-CI4.mjs';
7
- import { d as defineHandler } from '../packem_shared/command-BC30oSBW.mjs';
8
- import { diffSnapshots, renderMigrationFile } from '../packem_shared/diffSnapshots-BeDvvNiF.mjs';
9
- import { a as resolveProductionWorkerUrl } from '../packem_shared/resolve-target-qbsJ_5sF.mjs';
10
- import schemaIrToSnapshot from '../packem_shared/schemaIrToSnapshot-DdsljJT-.mjs';
11
- import { runExportCommand, runImportCommand } from '../packem_shared/DEFAULT_IMPORT_BATCH_SIZE-Ck-2bU08.mjs';
12
-
13
- const SNAPSHOT_FILENAME = ".snapshot.json";
14
- const NON_ALPHANUMERIC = /[^\da-z]+/gu;
15
- const trimChar = (value, char) => {
16
- let start = 0;
17
- let end = value.length;
18
- while (start < end && value[start] === char) {
19
- start += 1;
20
- }
21
- while (end > start && value[end - 1] === char) {
22
- end -= 1;
23
- }
24
- return value.slice(start, end);
25
- };
26
- const slugify = (input) => {
27
- const slug = trimChar(input.toLowerCase().replaceAll(NON_ALPHANUMERIC, "_"), "_");
28
- return slug === "" ? "auto" : slug;
29
- };
30
- const formatTimestamp = (now) => {
31
- const pad = (n, w = 2) => n.toString().padStart(w, "0");
32
- return `${String(now.getUTCFullYear())}${pad(now.getUTCMonth() + 1)}${pad(now.getUTCDate())}${pad(now.getUTCHours())}${pad(
33
- now.getUTCMinutes()
34
- )}${pad(now.getUTCSeconds())}`;
35
- };
36
- const loadSnapshot = (path) => {
37
- if (!existsSync(path)) {
38
- return void 0;
39
- }
40
- try {
41
- const raw = readFileSync(path, "utf8");
42
- const parsed = JSON.parse(raw);
43
- if (parsed.version !== 1) {
44
- throw new Error(`unsupported snapshot version: ${parsed.version}`);
45
- }
46
- return parsed;
47
- } catch (error) {
48
- const message = error instanceof Error ? error.message : String(error);
49
- throw new Error(`failed to read ${path}: ${message}`, { cause: error });
50
- }
51
- };
52
- const runMigrateGenerateCommand = (options) => {
53
- const cwd = options.cwd ?? process.cwd();
54
- const schemaPath = join(cwd, "lunora", "schema.ts");
55
- if (!existsSync(schemaPath)) {
56
- options.logger.error(`schema not found: ${schemaPath} — run \`vis generate lunora-table --name=<name>\` to create one`);
57
- return { code: 1, empty: true, migrationFile: "" };
58
- }
59
- const project = new Project({ skipAddingFilesFromTsConfig: true });
60
- const schemaIr = discoverSchema(project, schemaPath);
61
- const nextSnapshot = schemaIrToSnapshot(schemaIr);
62
- const migrationsDirectory = join(cwd, "lunora", "migrations");
63
- const snapshotPath = join(migrationsDirectory, SNAPSHOT_FILENAME);
64
- let previousSnapshot;
65
- try {
66
- previousSnapshot = loadSnapshot(snapshotPath);
67
- } catch (error) {
68
- options.logger.error(error instanceof Error ? error.message : String(error));
69
- return { code: 1, empty: true, migrationFile: "" };
70
- }
71
- const diff = diffSnapshots(previousSnapshot, nextSnapshot);
72
- if (diff.empty) {
73
- options.logger.info("no schema changes detected — snapshot is already up to date");
74
- return { code: 0, empty: true, migrationFile: "" };
75
- }
76
- const nowFunction = options.now ?? (() => /* @__PURE__ */ new Date());
77
- const now = nowFunction();
78
- const slug = slugify(options.name ?? "auto");
79
- const timestamp = formatTimestamp(now);
80
- const filename = `${timestamp}_${slug}.sql`;
81
- const migrationFile = join(migrationsDirectory, filename);
82
- mkdirSync(migrationsDirectory, { recursive: true });
83
- const body = renderMigrationFile(slug, diff, now.toISOString());
84
- writeFileSync(migrationFile, body, "utf8");
85
- writeFileSync(snapshotPath, `${JSON.stringify(nextSnapshot, void 0, 4)}
86
- `, "utf8");
87
- options.logger.success(`wrote ${migrationFile}`);
88
- if (diff.unsupported.length > 0) {
89
- options.logger.warn(`${String(diff.unsupported.length)} unsupported diff(s) — see the comment block in ${filename} and write the SQL manually`);
90
- }
91
- return { code: 0, empty: false, migrationFile };
92
- };
93
- const DATA_MIGRATIONS_FILENAME = "migrations.ts";
94
- const IDENTIFIER_PATTERN = /^[A-Za-z_]\w*$/u;
95
- const RESERVED_WORDS = /* @__PURE__ */ new Set([
96
- "await",
97
- "break",
98
- "case",
99
- "catch",
100
- "class",
101
- "const",
102
- "continue",
103
- "debugger",
104
- "default",
105
- "delete",
106
- "do",
107
- "else",
108
- "enum",
109
- "export",
110
- "extends",
111
- "false",
112
- "finally",
113
- "for",
114
- "function",
115
- "if",
116
- "implements",
117
- "import",
118
- "in",
119
- "instanceof",
120
- "interface",
121
- "let",
122
- "new",
123
- "null",
124
- "package",
125
- "private",
126
- "protected",
127
- "public",
128
- "return",
129
- "static",
130
- "super",
131
- "switch",
132
- "this",
133
- "throw",
134
- "true",
135
- "try",
136
- "typeof",
137
- "var",
138
- "void",
139
- "while",
140
- "with",
141
- "yield"
142
- ]);
143
- const DEFINE_MIGRATION_IMPORT = `import { defineMigration } from "@lunora/server";`;
144
- const RUN_MIGRATION_OP = "__lunora_admin__:runMigration";
145
- const MIGRATION_STATUS_OP = "__lunora_admin__:migrationStatus";
146
- const MIGRATE_ENDPOINT_PATH = "/_lunora/migrate";
147
- const kebabCase = (input) => trimChar(input.trim().toLowerCase().replaceAll(NON_ALPHANUMERIC, "-"), "-");
148
- const camelCase = (slug) => slug.split("-").filter((part) => part.length > 0).map((part, index) => {
149
- if (index === 0) {
150
- return part;
151
- }
152
- return part.charAt(0).toUpperCase() + part.slice(1);
153
- }).join("");
154
- const runMigrateCreateCommand = (options) => {
155
- const cwd = options.cwd ?? process.cwd();
156
- const slug = kebabCase(options.name);
157
- if (slug === "") {
158
- options.logger.error(`invalid migration name: "${options.name}" — must contain at least one alphanumeric character`);
159
- return { code: 1, file: "" };
160
- }
161
- const exportName = camelCase(slug);
162
- if (!IDENTIFIER_PATTERN.test(exportName) || RESERVED_WORDS.has(exportName)) {
163
- options.logger.error(
164
- `invalid migration name: "${options.name}" derives the export \`${exportName}\`, which is not a valid identifier — pick a name that starts with a letter and isn't a reserved word`
165
- );
166
- return { code: 1, file: "" };
167
- }
168
- const table = options.table ?? "TODO_table";
169
- if (!IDENTIFIER_PATTERN.test(table)) {
170
- options.logger.error(`invalid --table: "${table}" — must be a valid identifier ([A-Za-z_][A-Za-z0-9_]*)`);
171
- return { code: 1, file: "" };
172
- }
173
- const lunoraDirectory = join(cwd, "lunora");
174
- const file = join(lunoraDirectory, DATA_MIGRATIONS_FILENAME);
175
- let content = existsSync(file) ? readFileSync(file, "utf8") : "";
176
- if (content.includes(`id: "${slug}"`) || new RegExp(String.raw`\bexport const ${exportName}\b`, "u").test(content)) {
177
- options.logger.error(`a migration with id "${slug}" (export \`${exportName}\`) already exists in ${file}`);
178
- return { code: 1, file: "" };
179
- }
180
- if (content.trim() === "") {
181
- content = `${DEFINE_MIGRATION_IMPORT}
182
- `;
183
- } else if (!content.includes(DEFINE_MIGRATION_IMPORT)) {
184
- content = `${DEFINE_MIGRATION_IMPORT}
185
- ${content}`;
186
- }
187
- const block = `export const ${exportName} = defineMigration({
188
- id: "${slug}",
189
- table: "${table}",
1
+ import{existsSync as m,mkdirSync as S,writeFileSync as h,mkdtempSync as C,rmSync as I,readFileSync as k}from"node:fs";import{tmpdir as A}from"node:os";import{discoverSchema as T,discoverMigrations as N}from"@lunora/codegen";import{isInteractive as M,promptSelect as z,promptText as E}from"@lunora/config";import{LunoraError as y}from"@lunora/errors";import{join as c}from"@visulima/path";import{Project as w}from"ts-morph";import{a as F}from"../packem_shared/admin-url-DfVehV3e.mjs";import{i as O}from"../packem_shared/command-Bjv4VmYA.mjs";import{diffSnapshots as R,renderMigrationFile as q}from"../packem_shared/diffSnapshots-9bDd9nOK.mjs";import{s as D}from"../packem_shared/resolve-target-vxaXHmvg.mjs";import L from"../packem_shared/schemaIrToSnapshot-Clwd2A8e.mjs";import{runExportCommand as j,runImportCommand as B}from"../packem_shared/DEFAULT_IMPORT_BATCH_SIZE-DL87PIEl.mjs";const H=".snapshot.json",x=/[^\da-z]+/gu,U=(r,e)=>{let o=0,t=r.length;for(;o<t&&r[o]===e;)o+=1;for(;t>o&&r[t-1]===e;)t-=1;return r.slice(o,t)},J=r=>{const e=U(r.toLowerCase().replaceAll(x,"_"),"_");return e===""?"auto":e},P=r=>{const e=(o,t=2)=>o.toString().padStart(t,"0");return`${String(r.getUTCFullYear())}${e(r.getUTCMonth()+1)}${e(r.getUTCDate())}${e(r.getUTCHours())}${e(r.getUTCMinutes())}${e(r.getUTCSeconds())}`},Z=r=>{if(m(r))try{const e=k(r,"utf8"),o=JSON.parse(e);if(o.version!==1)throw new y("INTERNAL",`unsupported snapshot version: ${o.version}`);return o}catch(e){const o=e instanceof Error?e.message:String(e);throw new y("INTERNAL",`failed to read ${r}: ${o}`,{cause:e})}},K=r=>{const e=r.cwd??process.cwd(),o=c(e,"lunora","schema.ts");if(!m(o))return r.logger.error(`schema not found: ${o} — run \`vis generate lunora-table --name=<name>\` to create one`),{code:1,empty:!0,migrationFile:""};const t=new w({skipAddingFilesFromTsConfig:!0}),n=T(t,o),a=L(n),i=c(e,"lunora","migrations"),s=c(i,H);let d;try{d=Z(s)}catch(p){return r.logger.error(p instanceof Error?p.message:String(p)),{code:1,empty:!0,migrationFile:""}}const l=R(d,a);if(l.empty)return r.logger.info("no schema changes detected — snapshot is already up to date"),{code:0,empty:!0,migrationFile:""};const u=(r.now??(()=>new Date))(),b=J(r.name??"auto"),$=`${P(u)}_${b}.sql`,g=c(i,$);S(i,{recursive:!0});const _=q(b,l,u.toISOString());return h(g,_,"utf8"),h(s,`${JSON.stringify(a,void 0,4)}
2
+ `,"utf8"),r.logger.success(`wrote ${g}`),l.unsupported.length>0&&r.logger.warn(`${String(l.unsupported.length)} unsupported diff(s) — see the comment block in ${$} and write the SQL manually`),{code:0,empty:!1,migrationFile:g}},Q="migrations.ts",v=/^[A-Za-z_]\w*$/u,V=new Set(["await","break","case","catch","class","const","continue","debugger","default","delete","do","else","enum","export","extends","false","finally","for","function","if","implements","import","in","instanceof","interface","let","new","null","package","private","protected","public","return","static","super","switch","this","throw","true","try","typeof","var","void","while","with","yield"]),f='import { defineMigration } from "@lunora/server";',W="__lunora_admin__:runMigration",Y="__lunora_admin__:migrationStatus",G="/_lunora/migrate",X=r=>U(r.trim().toLowerCase().replaceAll(x,"-"),"-"),rr=r=>r.split("-").filter(e=>e.length>0).map((e,o)=>o===0?e:e.charAt(0).toUpperCase()+e.slice(1)).join(""),er=r=>{const e=c(r,"lunora","schema.ts");if(!m(e))return[];try{const o=new w({skipAddingFilesFromTsConfig:!0});return T(o,e).tables.map(t=>t.name)}catch{return[]}},tr=async r=>r.length>0?z("Which table does this migration iterate?",r.map(e=>({label:e,value:e}))):E("Target table for the migration: "),or=async(r,e)=>{if(e.table!==void 0)return e.table;const o=e.promptTable??(M()?tr:void 0);if(o===void 0){e.logger.error("migrate create requires a target table when not running interactively — re-run with --table <table>");return}const t=(await o(er(r)))?.trim();if(t===void 0||t===""){e.logger.error("no table selected — re-run with --table <table>");return}return t},nr=async r=>{const e=r.cwd??process.cwd(),o=X(r.name);if(o==="")return r.logger.error(`invalid migration name: "${r.name}" — must contain at least one alphanumeric character`),{code:1,file:""};const t=rr(o);if(!v.test(t)||V.has(t))return r.logger.error(`invalid migration name: "${r.name}" derives the export \`${t}\`, which is not a valid identifier — pick a name that starts with a letter and isn't a reserved word`),{code:1,file:""};const n=await or(e,r);if(n===void 0)return{code:1,file:""};if(!v.test(n))return r.logger.error(`invalid table: "${n}" — must be a valid identifier ([A-Za-z_][A-Za-z0-9_]*)`),{code:1,file:""};const a=c(e,"lunora"),i=c(a,Q);let s=m(i)?k(i,"utf8"):"";if(s.includes(`id: "${o}"`)||new RegExp(String.raw`\bexport const ${t}\b`,"u").test(s))return r.logger.error(`a migration with id "${o}" (export \`${t}\`) already exists in ${i}`),{code:1,file:""};s.trim()===""?s=`${f}
3
+ `:s.includes(f)||(s=`${f}
4
+ ${s}`);const d=`export const ${t} = defineMigration({
5
+ id: "${o}",
6
+ table: "${n}",
190
7
  up: (document) => document,
191
- });`;
192
- mkdirSync(lunoraDirectory, { recursive: true });
193
- writeFileSync(file, `${content.trimEnd()}
194
-
195
- ${block}
196
- `, "utf8");
197
- options.logger.success(`scaffolded migration "${slug}" in ${file}`);
198
- if (options.table === void 0) {
199
- options.logger.warn(`set the \`table\` field on "${slug}" — it defaults to "${table}"`);
200
- }
201
- return { code: 0, file };
202
- };
203
- const resolveMigrationTable = (cwd, id) => {
204
- const project = new Project({ skipAddingFilesFromTsConfig: true });
205
- const migrations = discoverMigrations(project, join(cwd, "lunora"));
206
- return migrations.find((migration) => migration.id === id)?.table;
207
- };
208
- const resolveValidatedTable = (cwd, options) => {
209
- let table;
210
- try {
211
- table = resolveMigrationTable(cwd, options.id);
212
- } catch (error) {
213
- options.logger.error(error instanceof Error ? error.message : String(error));
214
- return void 0;
215
- }
216
- if (table === void 0) {
217
- options.logger.error(`migration "${options.id}" not found under lunora/ — declare it with defineMigration({ id: "${options.id}", ... })`);
218
- return void 0;
219
- }
220
- if (table === "") {
221
- options.logger.error(`migration "${options.id}" must declare \`table\` as a static string literal`);
222
- return void 0;
223
- }
224
- return table;
225
- };
226
- const resolveMigrateDataRequest = (options) => {
227
- const cwd = options.cwd ?? process.cwd();
228
- if (options.prod && options.url === void 0) {
229
- options.logger.error("--prod requires an explicit --url (refusing to migrate the implicit localhost worker)");
230
- return void 0;
231
- }
232
- if (options.prod && (options.subcommand === "up" || options.subcommand === "down") && !options.yes) {
233
- options.logger.error(`migrate ${options.subcommand} --prod runs the migration against production. Re-run with --yes to confirm.`);
234
- return void 0;
235
- }
236
- const token = options.token ?? process.env.LUNORA_ADMIN_TOKEN;
237
- if (!token) {
238
- options.logger.error("admin token required — pass --token or set LUNORA_ADMIN_TOKEN");
239
- return void 0;
240
- }
241
- const table = resolveValidatedTable(cwd, options);
242
- if (table === void 0) {
243
- return void 0;
244
- }
245
- const baseUrl = resolveAdminBaseUrl(options.url, options.logger);
246
- if (baseUrl === void 0) {
247
- return void 0;
248
- }
249
- const fetchImpl = options.fetchImpl ?? globalThis.fetch;
250
- if (typeof fetchImpl !== "function") {
251
- throw new TypeError("no fetch implementation available — pass fetchImpl or run on Node >= 18");
252
- }
253
- return { fetchImpl, requestUrl: `${baseUrl}${MIGRATE_ENDPOINT_PATH}`, table, token };
254
- };
255
- const buildMigrateArgs = (options) => {
256
- const args = { id: options.id };
257
- if (options.subcommand === "status") {
258
- return args;
259
- }
260
- args.direction = options.subcommand;
261
- if (options.dryRun) {
262
- args.dryRun = true;
263
- }
264
- if (options.batchSize !== void 0) {
265
- args.batchSize = options.batchSize;
266
- }
267
- if (options.maxBatches !== void 0) {
268
- args.maxBatches = options.maxBatches;
269
- }
270
- return args;
271
- };
272
- const runMigrateDataCommand = async (options) => {
273
- const request = resolveMigrateDataRequest(options);
274
- if (request === void 0) {
275
- return { body: void 0, code: 1, requestUrl: "" };
276
- }
277
- const { fetchImpl, requestUrl, table, token } = request;
278
- const functionPath = options.subcommand === "status" ? MIGRATION_STATUS_OP : RUN_MIGRATION_OP;
279
- const args = buildMigrateArgs(options);
280
- options.logger.info(`POST ${requestUrl} -> ${options.subcommand} ${options.id} (table "${table}")`);
281
- const response = await fetchImpl(requestUrl, {
282
- body: JSON.stringify({ args, functionPath, table }),
283
- headers: { authorization: `Bearer ${token}`, "content-type": "application/json" },
284
- method: "POST"
285
- });
286
- const text = await response.text();
287
- let body;
288
- try {
289
- body = JSON.parse(text);
290
- } catch {
291
- body = text;
292
- }
293
- options.logger.info(JSON.stringify(body, void 0, 2));
294
- return { body, code: response.ok ? 0 : 1, requestUrl };
295
- };
296
- const runMigrateToHyperdriveCommand = async (options) => {
297
- const { logger } = options;
298
- const fromUrl = options.fromUrl ?? options.toUrl;
299
- const toUrl = options.toUrl ?? options.fromUrl;
300
- if (fromUrl !== void 0 && fromUrl === toUrl) {
301
- logger.error(
302
- "source and target are the same deployment — pass distinct --from-url and --to-url so the D1 export and Hyperdrive import don't run against one database"
303
- );
304
- return { code: 1 };
305
- }
306
- const temporaryDirectory = options.out === void 0 ? mkdtempSync(join(tmpdir(), "lunora-d1ps-")) : void 0;
307
- const dumpPath = options.out ?? join(temporaryDirectory, "dump.ndjson");
308
- logger.info(`Exporting .global() data from the D1 source (${fromUrl ?? "http://localhost:8787"}) …`);
309
- const exportResult = await runExportCommand({
310
- fetchImpl: options.fetchImpl,
311
- logger,
312
- out: dumpPath,
313
- prod: options.prod,
314
- tables: options.tables,
315
- token: options.fromToken,
316
- url: fromUrl
317
- });
318
- if (exportResult.code !== 0) {
319
- return { code: exportResult.code };
320
- }
321
- logger.info(`Exported ${String(exportResult.rows)} row(s) (${String(exportResult.bytes)} bytes).`);
322
- logger.info(`Importing into the Hyperdrive target (${toUrl ?? "http://localhost:8787"}) …`);
323
- const importResult = await runImportCommand({
324
- batchSize: options.batchSize,
325
- fetchImpl: options.fetchImpl,
326
- file: dumpPath,
327
- logger,
328
- prod: options.prod,
329
- token: options.toToken,
330
- url: toUrl
331
- });
332
- if (temporaryDirectory !== void 0) {
333
- rmSync(temporaryDirectory, { force: true, recursive: true });
334
- }
335
- if (importResult.code !== 0) {
336
- return { code: importResult.code };
337
- }
338
- if (importResult.inserted === exportResult.rows) {
339
- logger.info(`✓ Migrated ${String(exportResult.rows)} row(s) — counts match. Verify your app reads from Hyperdrive, then decommission the D1 binding.`);
340
- } else {
341
- logger.warn(
342
- `Imported ${String(importResult.inserted)} of ${String(exportResult.rows)} exported row(s) — the remainder likely already existed in the target (see conflicts above). Re-run after resolving, or inspect the dump with --out.`
343
- );
344
- }
345
- return { code: 0 };
346
- };
347
- const execute = defineHandler(({ argument, cwd, logger, options }) => {
348
- const sub = argument[0];
349
- if (sub === "generate") {
350
- return runMigrateGenerateCommand({ cwd, logger, name: argument[1] ?? options.name });
351
- }
352
- if (sub === "d1-to-hyperdrive") {
353
- return runMigrateToHyperdriveCommand({
354
- batchSize: options.batchSize,
355
- fromToken: options.fromToken ?? options.token,
356
- fromUrl: options.fromUrl ?? options.url,
357
- logger,
358
- out: options.out,
359
- prod: options.prod === true,
360
- tables: options.tables,
361
- toToken: options.toToken ?? options.token,
362
- toUrl: options.toUrl ?? options.url
363
- });
364
- }
365
- if (sub === "create") {
366
- const name = argument[1] ?? options.name;
367
- if (!name) {
368
- logger.error("migrate create requires a name. Usage: lunora migrate create <name> [--table <table>]");
369
- return { code: 1 };
370
- }
371
- return runMigrateCreateCommand({ cwd, logger, name, table: options.table });
372
- }
373
- if (sub === "up" || sub === "down" || sub === "status") {
374
- const id = argument[1] ?? options.name;
375
- if (!id) {
376
- logger.error(`migrate ${sub} requires a migration id. Usage: lunora migrate ${sub} <id>`);
377
- return { code: 1 };
378
- }
379
- return runMigrateDataCommand({
380
- batchSize: options.batchSize,
381
- cwd,
382
- dryRun: options.dryRun === true,
383
- id,
384
- logger,
385
- maxBatches: options.steps,
386
- prod: options.prod === true,
387
- subcommand: sub,
388
- token: options.token,
389
- url: resolveProductionWorkerUrl({ cwd, prod: options.prod === true, url: options.url }),
390
- yes: options.yes === true
391
- });
392
- }
393
- logger.error(`unknown migrate subcommand: "${sub ?? ""}" — expected generate | create | up | down | status`);
394
- return { code: 1 };
395
- });
8
+ });`;return S(a,{recursive:!0}),h(i,`${s.trimEnd()}
396
9
 
397
- export { execute, runMigrateCreateCommand, runMigrateDataCommand, runMigrateGenerateCommand, runMigrateToHyperdriveCommand };
10
+ ${d}
11
+ `,"utf8"),r.logger.success(`scaffolded migration "${o}" in ${i}`),{code:0,file:i}},ir=(r,e)=>{const o=new w({skipAddingFilesFromTsConfig:!0});return N(o,c(r,"lunora")).find(t=>t.id===e)?.table},ar=(r,e)=>{let o;try{o=ir(r,e.id)}catch(t){e.logger.error(t instanceof Error?t.message:String(t));return}if(o===void 0){e.logger.error(`migration "${e.id}" not found under lunora/ — declare it with defineMigration({ id: "${e.id}", ... })`);return}if(o===""){e.logger.error(`migration "${e.id}" must declare \`table\` as a static string literal`);return}return o},sr=r=>{const e=r.cwd??process.cwd();if(r.prod&&r.url===void 0){r.logger.error("--prod requires an explicit --url (refusing to migrate the implicit localhost worker)");return}if(r.prod&&(r.subcommand==="up"||r.subcommand==="down")&&!r.yes){r.logger.error(`migrate ${r.subcommand} --prod runs the migration against production. Re-run with --yes to confirm.`);return}const o=r.token??process.env.LUNORA_ADMIN_TOKEN;if(!o){r.logger.error("admin token required — pass --token or set LUNORA_ADMIN_TOKEN");return}const t=ar(e,r);if(t===void 0)return;const n=F(r.url,r.logger);if(n===void 0)return;const a=r.fetchImpl??globalThis.fetch;if(typeof a!="function")throw new TypeError("no fetch implementation available — pass fetchImpl or run on Node >= 18");return{fetchImpl:a,requestUrl:`${n}${G}`,table:t,token:o}},cr=r=>{const e={id:r.id};return r.subcommand==="status"||(e.direction=r.subcommand,r.dryRun&&(e.dryRun=!0),r.batchSize!==void 0&&(e.batchSize=r.batchSize),r.maxBatches!==void 0&&(e.maxBatches=r.maxBatches)),e},dr=async r=>{const e=sr(r);if(e===void 0)return{body:void 0,code:1,requestUrl:""};const{fetchImpl:o,requestUrl:t,table:n,token:a}=e,i=r.subcommand==="status"?Y:W,s=cr(r);r.logger.info(`POST ${t} -> ${r.subcommand} ${r.id} (table "${n}")`);const d=await o(t,{body:JSON.stringify({args:s,functionPath:i,table:n}),headers:{authorization:`Bearer ${a}`,"content-type":"application/json"},method:"POST"}),l=await d.text();let u;try{u=JSON.parse(l)}catch{u=l}return r.logger.info(JSON.stringify(u,void 0,2)),{body:u,code:d.ok?0:1,requestUrl:t}},lr=async r=>{const{logger:e}=r,o=r.fromUrl??r.toUrl,t=r.toUrl??r.fromUrl;if(o!==void 0&&o===t)return e.error("source and target are the same deployment — pass distinct --from-url and --to-url so the D1 export and Hyperdrive import don't run against one database"),{code:1};const n=r.out===void 0?C(c(A(),"lunora-d1ps-")):void 0,a=r.out??c(n,"dump.ndjson");try{e.info(`Exporting .global() data from the D1 source (${o??"http://localhost:8787"}) …`);const i=await j({fetchImpl:r.fetchImpl,logger:e,out:a,prod:r.prod,tables:r.tables,token:r.fromToken,url:o});if(i.code!==0)return{code:i.code};e.info(`Exported ${String(i.rows)} row(s) (${String(i.bytes)} bytes).`),e.info(`Importing into the Hyperdrive target (${t??"http://localhost:8787"}) …`);const s=await B({batchSize:r.batchSize,fetchImpl:r.fetchImpl,file:a,logger:e,prod:r.prod,token:r.toToken,url:t});return s.code!==0?{code:s.code}:(s.inserted===i.rows?e.info(`✓ Migrated ${String(i.rows)} row(s) — counts match. Verify your app reads from Hyperdrive, then decommission the D1 binding.`):e.warn(`Imported ${String(s.inserted)} of ${String(i.rows)} exported row(s) — the remainder likely already existed in the target (see conflicts above). Re-run after resolving, or inspect the dump with --out.`),{code:0})}finally{n!==void 0&&I(n,{force:!0,recursive:!0})}},Tr=O(({argument:r,cwd:e,logger:o,options:t})=>{const n=r[0];if(n==="generate")return K({cwd:e,logger:o,name:r[1]??t.name});if(n==="d1-to-hyperdrive")return lr({batchSize:t.batchSize,fromToken:t.fromToken??t.token,fromUrl:t.fromUrl??t.url,logger:o,out:t.out,prod:t.prod===!0,tables:t.tables,toToken:t.toToken??t.token,toUrl:t.toUrl??t.url});if(n==="create"){const a=r[1]??t.name;return a?nr({cwd:e,logger:o,name:a,table:t.table}):(o.error("migrate create requires a name. Usage: lunora migrate create <name> [--table <table>]"),{code:1})}if(n==="up"||n==="down"||n==="status"){const a=r[1]??t.name;return a?dr({batchSize:t.batchSize,cwd:e,dryRun:t.dryRun===!0,id:a,logger:o,maxBatches:t.steps,prod:t.prod===!0,subcommand:n,token:t.token,url:D({cwd:e,prod:t.prod===!0,url:t.url}),yes:t.yes===!0}):(o.error(`migrate ${n} requires a migration id. Usage: lunora migrate ${n} <id>`),{code:1})}return o.error(`unknown migrate subcommand: "${n??""}" — expected generate | create | up | down | status`),{code:1}});export{Tr as execute,nr as runMigrateCreateCommand,dr as runMigrateDataCommand,K as runMigrateGenerateCommand,lr as runMigrateToHyperdriveCommand};
@@ -1,41 +1 @@
1
- import { existsSync, rmSync } from 'node:fs';
2
- import { join } from '@visulima/path';
3
- import { d as defineHandler } from '../packem_shared/command-BC30oSBW.mjs';
4
- import { b as tuiConfirm } from '../packem_shared/tui-prompts-M6OWsuyw.mjs';
5
-
6
- const runResetCommand = async (options) => {
7
- const cwd = options.cwd ?? process.cwd();
8
- const targets = [join(cwd, ".wrangler", "state")];
9
- if (options.all) {
10
- targets.push(join(cwd, ".lunora-cache"));
11
- }
12
- if (!options.yes) {
13
- const isTty = process.stdin.isTTY;
14
- if (!isTty && options.confirm === void 0) {
15
- options.logger.error("reset: stdin is not a TTY — re-run with --yes to confirm deleting .wrangler/state");
16
- return { code: 1, removed: [] };
17
- }
18
- const confirmer = options.confirm ?? tuiConfirm;
19
- const confirmed = await confirmer("This will delete .wrangler/state. Continue?");
20
- if (!confirmed) {
21
- options.logger.info("reset: aborted");
22
- return { code: 1, removed: [] };
23
- }
24
- }
25
- const removed = [];
26
- for (const target of targets) {
27
- if (existsSync(target)) {
28
- rmSync(target, { force: true, recursive: true });
29
- removed.push(target);
30
- options.logger.success(`removed ${target}`);
31
- } else {
32
- options.logger.info(`skipped (not present): ${target}`);
33
- }
34
- }
35
- return { code: 0, removed };
36
- };
37
- const execute = defineHandler(
38
- ({ cwd, logger, options }) => runResetCommand({ all: options.all === true, cwd, logger, yes: options.yes === true })
39
- );
40
-
41
- export { execute, runResetCommand };
1
+ import{existsSync as i,rmSync as c}from"node:fs";import{join as n}from"@visulima/path";import{i as l}from"../packem_shared/command-Bjv4VmYA.mjs";import{i as a}from"../packem_shared/tui-prompts-CCt3jm1k.mjs";const d=async e=>{const t=e.cwd??process.cwd(),r=[n(t,".wrangler","state")];if(e.all&&r.push(n(t,".lunora-cache")),!e.yes){if(!process.stdin.isTTY&&e.confirm===void 0)return e.logger.error("reset: stdin is not a TTY — re-run with --yes to confirm deleting .wrangler/state"),{code:1,removed:[]};if(!await(e.confirm??a)("This will delete .wrangler/state. Continue?"))return e.logger.info("reset: aborted"),{code:1,removed:[]}}const s=[];for(const o of r)i(o)?(c(o,{force:!0,recursive:!0}),s.push(o),e.logger.success(`removed ${o}`)):e.logger.info(`skipped (not present): ${o}`);return{code:0,removed:s}},p=l(({cwd:e,logger:t,options:r})=>d({all:r.all===!0,cwd:e,logger:t,yes:r.yes===!0}));export{p as execute,d as runResetCommand};
@@ -1,68 +1 @@
1
- import { d as defineHandler } from '../packem_shared/command-BC30oSBW.mjs';
2
- import { r as resolveWorkerUrl } from '../packem_shared/resolve-target-qbsJ_5sF.mjs';
3
-
4
- const parseArgsJson = (raw) => {
5
- if (raw === void 0 || raw.length === 0) {
6
- return {};
7
- }
8
- try {
9
- return JSON.parse(raw);
10
- } catch (error) {
11
- const message = error instanceof Error ? error.message : String(error);
12
- throw new Error(`failed to parse --args as JSON: ${message}`, { cause: error });
13
- }
14
- };
15
- const TRAILING_SLASH = /\/$/u;
16
- const runRpcCommand = async (options) => {
17
- const resolvedUrl = resolveWorkerUrl({ cwd: options.cwd ?? process.cwd(), url: options.url });
18
- const baseUrl = (resolvedUrl ?? "http://localhost:8787").replace(TRAILING_SLASH, "");
19
- const requestUrl = `${baseUrl}/_lunora/rpc`;
20
- const fetchImpl = options.fetchImpl ?? globalThis.fetch;
21
- if (typeof fetchImpl !== "function") {
22
- throw new TypeError("no fetch implementation available — pass --fetch via dependency injection or run on Node >= 18");
23
- }
24
- let parsedArgs;
25
- try {
26
- parsedArgs = parseArgsJson(options.args);
27
- } catch (error) {
28
- const message = error instanceof Error ? error.message : String(error);
29
- options.logger.error(message);
30
- return { body: void 0, code: 1, requestUrl };
31
- }
32
- const payload = {
33
- args: parsedArgs,
34
- functionPath: options.functionPath
35
- };
36
- if (options.shard !== void 0) {
37
- payload.shardKey = options.shard;
38
- }
39
- options.logger.info(`POST ${requestUrl} -> ${options.functionPath}`);
40
- const response = await fetchImpl(requestUrl, {
41
- body: JSON.stringify(payload),
42
- headers: { "content-type": "application/json" },
43
- method: "POST"
44
- });
45
- const text = await response.text();
46
- let body;
47
- try {
48
- body = JSON.parse(text);
49
- } catch {
50
- body = text;
51
- }
52
- options.logger.info(JSON.stringify(body, void 0, 2));
53
- return {
54
- body,
55
- code: response.ok ? 0 : 1,
56
- requestUrl
57
- };
58
- };
59
- const execute = defineHandler(({ argument, cwd, logger, options }) => {
60
- const functionPath = argument[0];
61
- if (!functionPath) {
62
- logger.error("missing function path. Usage: lunora run <functionPath> [--args <json>]");
63
- return { code: 1 };
64
- }
65
- return runRpcCommand({ args: options.args, cwd, functionPath, logger, shard: options.shard, url: options.url });
66
- });
67
-
68
- export { execute, runRpcCommand };
1
+ import{LunoraError as d}from"@lunora/errors";import{i as g}from"../packem_shared/command-Bjv4VmYA.mjs";import{t as l}from"../packem_shared/resolve-target-vxaXHmvg.mjs";const h=r=>{if(r===void 0||r.length===0)return{};try{return JSON.parse(r)}catch(o){const t=o instanceof Error?o.message:String(o);throw new d("INTERNAL",`failed to parse --args as JSON: ${t}`,{cause:o})}},f=/\/$/u,p=async r=>{const o=`${(l({cwd:r.cwd??process.cwd(),url:r.url})??"http://localhost:8787").replace(f,"")}/_lunora/rpc`,t=r.fetchImpl??globalThis.fetch;if(typeof t!="function")throw new TypeError("no fetch implementation available — pass --fetch via dependency injection or run on Node >= 18");let e;try{e=h(r.args)}catch(s){const u=s instanceof Error?s.message:String(s);return r.logger.error(u),{body:void 0,code:1,requestUrl:o}}const a={args:e,functionPath:r.functionPath};r.shard!==void 0&&(a.shardKey=r.shard),r.logger.info(`POST ${o} -> ${r.functionPath}`);const c=await t(o,{body:JSON.stringify(a),headers:{"content-type":"application/json"},method:"POST"}),i=await c.text();let n;try{n=JSON.parse(i)}catch{n=i}return r.logger.info(JSON.stringify(n,void 0,2)),{body:n,code:c.ok?0:1,requestUrl:o}},S=g(({argument:r,cwd:o,logger:t,options:e})=>{const a=r[0];return a?p({args:e.args,cwd:o,functionPath:a,logger:t,shard:e.shard,url:e.url}):(t.error("missing function path. Usage: lunora run <functionPath> [--args <json>]"),{code:1})});export{S as execute,p as runRpcCommand};
@@ -0,0 +1,3 @@
1
+ import{mkdirSync as x,readFileSync as f,lstatSync as N,writeFileSync as O}from"node:fs";import{join as d,dirname as g}from"node:path";import{fileURLToPath as R}from"node:url";import{resolveHint as B,isLunoraError as v,flattenHint as A,findSolutionByMessage as L}from"@lunora/errors";import{createCerebro as D}from"@visulima/cerebro";import C from"@visulima/cerebro/command/completion";import j from"@visulima/cerebro/command/version";import{p as s}from"./api-spec-BENwiyUa.mjs";import{createLogger as b}from"./createLogger--C3x1FNE.mjs";import{VisulimaError as E,renderError as I}from"@visulima/error";import{homedir as T}from"node:os";const _={argument:{description:"Feature or registry item: ai | auth | email | storage | crons | presence | queue | workflow | flags | backup | …",name:"feature",type:String},description:"Add a feature or registry item (ai, auth, email, storage, crons, …) to the current Lunora project",examples:[["lunora add auth","Add authentication (asks which provider)"],["lunora add auth --provider clerk","Add Clerk auth without prompting"],["lunora add email","Add transactional email (Cloudflare Email Workers + dev mail catcher)"],["lunora add storage","Add the R2 storage registry item (asks for the bucket name)"],["lunora add storage --bucket my-app-uploads","Add storage with a bucket name, no prompt"],["lunora add crons","Add the scheduled-jobs registry item"],["lunora add storage --ref alpha","Add an item from the alpha branch's registry"]],group:"Project",loader:()=>import("../packem_chunks/handler.mjs").then(e=>({default:e.execute})),name:"add",options:[{description:"auth: provider to use without prompting (auth | clerk | auth0)",name:"provider",type:String},{description:"auth: D1 database name to use without prompting (lowercase alphanumeric + hyphens)",name:"db",type:String},{description:"storage: R2 bucket name to use without prompting (lowercase alphanumeric + hyphens)",name:"bucket",type:String},{description:"email: verified destination address to use without prompting",name:"mail-to",type:String},{description:"Skip prompts (auth provider, DB name, bucket name, mail destination) and use the defaults",name:"yes",type:Boolean},{description:"Local registry root (offline; expects <name>/ subdirs)",name:"from",type:String},{description:"Override the remote registry source base (e.g. gh:owner/repo/registry)",name:"source",type:String},{description:"Fetch items from a git ref (branch, tag, or commit), e.g. --ref alpha. Overrides the version-derived default",name:"ref",type:String},{description:"Permit --source values outside gh:/github:/https://",name:"allow-unsafe-source",type:Boolean},{description:"Output format: pretty (default) or json",name:"format",type:String}]},P={description:"Run wrangler dry-run and report bundle size, top modules, and _generated files",examples:[["lunora analyze","Report the worker bundle size + heaviest modules"]],group:"Deploy",loader:()=>import("../packem_chunks/handler2.mjs").then(e=>({default:e.execute})),name:"analyze",options:[{description:"Emit a JSON report instead of human text",name:"json",type:Boolean}]},$={argument:{description:"create | list | restore <id|file> | pitr",name:"subcommand",type:String},description:"Managed snapshot backups (create | list | restore) plus native point-in-time recovery (pitr)",examples:[["lunora backup create","Snapshot every table to a backup file"],["lunora backup list","List recorded snapshots"],["lunora backup restore <id>","Restore a snapshot by id"],["lunora backup pitr --at 2026-06-01T00:00:00Z","Point-in-time recovery (≤30 days)"]],group:"Data",loader:()=>import("../packem_chunks/handler3.mjs").then(e=>({default:e.execute})),name:"backup",options:[{description:"Backup directory (default .lunora-backups)",name:"dir",type:String},{description:"Comma-separated table allowlist (create)",name:"tables",type:String},{description:"pitr: time to read/restore to (ISO or epoch-ms, ≤30 days)",name:"at",type:String},{description:"pitr --restore: explicit bookmark to restore to (wins over --at)",name:"bookmark",type:String},{description:"pitr: perform a restore instead of just reading the bookmark",name:"restore",type:Boolean},{description:"pitr --restore: restart the shard now so recovery applies immediately",name:"restart",type:Boolean},{description:"pitr: target shard key (default: root shard)",name:"shard",type:String},{description:"Target production — requires an explicit --url",name:"prod",type:Boolean},{description:"Confirm a production pitr --restore (required with --prod)",name:"yes",type:Boolean},{description:"Worker URL (default http://localhost:8787)",name:"url",type:String},{description:"Admin bearer token (prefer LUNORA_ADMIN_TOKEN; --token is visible to other local processes via the process table)",name:"token",type:String}]},U={description:"Codegen + validate + bundle the Worker to disk without deploying",examples:[["lunora build","Bundle to .lunora/build without deploying"],["lunora build --out-dir dist-worker","Bundle to a custom directory"]],group:"Deploy",loader:()=>import("../packem_chunks/handler4.mjs").then(e=>({default:e.execute})),name:"build",options:[{description:`Which API spec(s) to emit: ${s} (default openapi)`,name:"api-spec",type:String},{description:"Output format: pretty (default) or json",name:"format",type:String},{description:"Directory to write the bundled Worker to (default .lunora/build)",name:"out-dir",type:String}]},M={description:"Run codegen for lunora/ functions and schema",examples:[["lunora codegen","Generate lunora/_generated/ from your schema + functions"]],group:"Develop",loader:()=>import("../packem_chunks/runCodegenCommand.mjs").then(e=>({default:e.execute})),name:"codegen",options:[{description:`Which API spec(s) to emit: ${s} (default openapi)`,name:"api-spec",type:String},{description:"Output format: pretty (default) or json",name:"format",type:String}]},W={argument:{description:"<build|push|images|list|info|delete> [args…]",name:"args",type:String},description:"Build/push container images and manage container instances (wraps wrangler containers)",examples:[["lunora containers build ./containers/transcoder --tag transcoder:v1","Build a container image with the local Docker engine"],["lunora containers build ./containers/transcoder --tag transcoder:v1 --push","Build and push to the Cloudflare Registry in one step"],["lunora containers push transcoder:v1","Push a locally-tagged image to the Cloudflare Registry"],["lunora containers images list","List images in your Cloudflare Registry"],["lunora containers images delete transcoder:v1","Delete an image to free registry storage"]],group:"Deploy",loader:()=>import("../packem_chunks/handler5.mjs").then(e=>({default:e.execute})),name:"containers",options:[{description:"build: push the image to the Cloudflare Registry after building",name:"push",type:Boolean},{description:"build: name:tag for the image (forwarded to wrangler --tag)",name:"tag",type:String},{description:"Cloudflare environment name",name:"env",type:String}]},J={description:"Codegen, validate wrangler, then wrangler deploy",examples:[["lunora deploy","Deploy to Cloudflare"],["lunora deploy --env production","Deploy to a named environment"],["lunora deploy --dry-run","Validate + bundle without publishing"],["lunora deploy --migrate","Deploy, then run pending data migrations"]],group:"Deploy",loader:()=>import("../packem_chunks/runDeployCommand.mjs").then(e=>({default:e.execute})),name:"deploy",options:[{description:"Override the schema-drift gate (deploy even with breaking schema drift and no migration)",name:"allow-schema-drift",type:Boolean},{description:`Which API spec(s) to emit: ${s} (default openapi)`,name:"api-spec",type:String},{description:"Validate, bundle, and run pre-deploy gates without publishing (wrangler deploy --dry-run)",name:"dry-run",type:Boolean},{description:"Cloudflare environment name",name:"env",type:String},{description:"Output format: pretty (default) or json",name:"format",type:String},{description:"After a successful deploy, run pending data migrations against the live worker",name:"migrate",type:Boolean},{description:"Skip codegen + the schema-drift gate (assumes `lunora build`/`prepare` already ran in this CI run). Wrangler still bundles the worker.",name:"prebuilt",type:Boolean},{description:"Admin bearer token for --migrate (falls back to LUNORA_ADMIN_TOKEN)",name:"migrate-token",type:String},{description:"Worker URL for --migrate (REQUIRED with --migrate; the deploy target URL is not captured automatically)",name:"migrate-url",type:String},{description:"Confirm running the production data migration triggered by --migrate (required with --migrate)",name:"migrate-yes",type:Boolean},{description:"Upload a preview version (wrangler versions upload) instead of going live — prints a preview URL; doesn't shift production traffic",name:"preview",type:Boolean},{description:"Deploy to a temporary Cloudflare account when unauthenticated (wrangler deploy --temporary; live ~60min, then claim or it's deleted). Wrangler errors if you're already authenticated.",name:"temporary",type:Boolean},{description:"Re-bless the committed schema baseline (lunora/.lunora-schema.json) with the current shape",name:"update-schema-baseline",type:Boolean}]},K={argument:{description:"list | inspect <version-id> | rollback [version-id] | promote <version-id>",name:"subcommand",type:String},description:"List deployments and roll back / promote / inspect Worker versions",examples:[["lunora deployments list","Show the 10 most recent deployments"],["lunora deployments inspect <version-id>","View a specific Worker version"],["lunora deployments rollback --yes","Roll back to the previous version"],["lunora deployments promote <version-id> --yes","Send 100% of traffic to a version"]],group:"Deploy",loader:()=>import("../packem_chunks/handler6.mjs").then(e=>({default:e.execute})),name:"deployments",options:[{description:"Cloudflare environment name",name:"env",type:String},{description:"Display `list` output as JSON",name:"json",type:Boolean},{description:"Reason/description recorded with a rollback or promote",name:"message",type:String},{description:"Confirm a rollback or promote (required — these change live traffic)",name:"yes",type:Boolean}]},q={argument:{description:"Optional subcommand: stop (shut the running dev server down) | status (report it) | logs (print its captured output)",name:"args",type:String},description:"Run the dev stack: wrangler worker + studio + codegen watch",examples:[["lunora dev","Run the worker + studio + codegen watch"],["lunora dev --background","Run detached: blocks until ready, prints URL + PID, then returns"],["lunora dev stop","Stop the background/tracked dev server (idempotent)"],["lunora dev status","Report the running dev server (URL, PID, uptime)"],["lunora dev logs","Print the captured dev-server log (background runs)"],["lunora dev --json","Machine-readable JSON log lines (also LUNORA_LOG_JSON=1)"],["lunora dev --no-studio","Skip the embedded studio server"],["lunora dev --worker-port 8080","Use a custom wrangler dev port"],["lunora dev --remote","Proxy D1/KV/R2 to the deployed worker (also LUNORA_REMOTE=1)"]],group:"Develop",loader:()=>import("../packem_chunks/planDevCommand.mjs").then(e=>({default:e.execute})),name:"dev",options:[{description:`Which API spec(s) codegen emits: ${s} (default openapi)`,name:"api-spec",type:String},{description:"Studio server port (default 6173)",name:"port",type:Number},{description:"wrangler dev port (default 8787)",name:"worker-port",type:Number},{description:"Run the dev server as a managed background process (auto-enabled when an AI agent is detected; LUNORA_AGENT_MODE=0 disables)",name:"background",type:Boolean},{description:"Emit machine-readable JSON log lines (also LUNORA_LOG_JSON=1; auto-enabled for AI agents)",name:"json",type:Boolean},{description:"How many trailing lines `lunora dev logs` prints (default 100, 0 = all)",name:"lines",type:Number},{description:"Don't start the embedded studio server",name:"no-studio",type:Boolean},{description:"Don't watch + regenerate codegen",name:"no-codegen",type:Boolean},{description:"Proxy D1/KV/R2 bindings to the deployed worker (or set LUNORA_REMOTE=1)",name:"remote",type:Boolean}]},F={argument:{description:"Optional path under the docs site (e.g. addons/studio)",name:"section",type:String},description:"Open the Lunora docs in your browser (optional [section] path)",examples:[["lunora docs","Open the Lunora docs"],["lunora docs addons/studio","Open a specific docs section"]],group:"Project",loader:()=>import("../packem_chunks/handler7.mjs").then(e=>({default:e.execute})),name:"docs"},H={description:"Preflight the current Lunora project (wrangler bindings, placeholders, dev secrets)",examples:[["lunora doctor","Run the project preflight checks"]],group:"Project",loader:()=>import("../packem_chunks/handler8.mjs").then(e=>({default:e.execute})),name:"doctor",options:[]},V={argument:{description:"list | get <KEY> | set <KEY> <VALUE> | unset <KEY> | generate [KEY] | push | diff | doctor",name:"subcommand",type:String},description:"Manage .dev.vars and sync secrets via wrangler (list | get | set | unset | generate | push | diff | doctor)",examples:[["lunora env list","List .dev.vars keys"],["lunora env set API_KEY secret","Set a local variable"],["lunora env generate","Generate strong values for the project's secrets (print KEY=value)"],["lunora env generate AUTH_SECRET --set","Generate one secret and write it to .dev.vars"],["lunora env push --yes","Upload secrets to Cloudflare"],["lunora env diff","Compare local .dev.vars keys against Cloudflare"]],group:"Data",loader:()=>import("../packem_chunks/handler9.mjs").then(e=>({default:e.execute})),name:"env",options:[{description:"Target production for `push` (passes --env production to wrangler)",name:"prod",type:Boolean},{description:"For `generate` — write the generated secrets into .dev.vars instead of printing them",name:"set",type:Boolean},{description:"Push secrets to a temporary-account deployment when unauthenticated (wrangler secret put --temporary). Errors if you're already authenticated.",name:"temporary",type:Boolean},{description:"Required for `push` — confirms uploading secrets to Cloudflare",name:"yes",type:Boolean}]},G={argument:{description:"Optional path (alias for --out)",name:"path",type:String},description:"Stream NDJSON of every shard-local + global table from the worker",examples:[["lunora export --out backup.ndjson","Dump every table to an NDJSON file"],["lunora export --tables messages,users","Export only specific tables"]],group:"Data",loader:()=>import("../packem_chunks/handler10.mjs").then(e=>({default:e.execute})),name:"export",options:[{description:"Output file path (`-` for stdout, default)",name:"out",type:String},{description:"Comma-separated table allowlist",name:"tables",type:String},{description:"Target production — requires an explicit --url",name:"prod",type:Boolean},{description:"Worker URL (default http://localhost:8787)",name:"url",type:String},{description:"Admin bearer token (prefer LUNORA_ADMIN_TOKEN; --token is visible to other local processes via the process table)",name:"token",type:String}]},Y={argument:{description:"Source NDJSON file",name:"file",type:String},description:"Bulk-insert rows from an NDJSON file via the worker's admin endpoint",examples:[["lunora import backup.ndjson","Bulk-insert rows from an NDJSON file"]],group:"Data",loader:()=>import("../packem_chunks/handler11.mjs").then(e=>({default:e.execute})),name:"import",options:[{description:"Wrap each bare doc as `{table:<name>,doc:...}`",name:"table",type:String},{description:"Rows per HTTP request (default 500)",name:"batch-size",type:Number},{description:"Target production — requires an explicit --url",name:"prod",type:Boolean},{description:"Confirm bulk-writing production (required with --prod)",name:"yes",type:Boolean},{description:"Worker URL (default http://localhost:8787)",name:"url",type:String},{description:"Admin bearer token (prefer LUNORA_ADMIN_TOKEN; --token is visible to other local processes via the process table)",name:"token",type:String}]},z={description:"Print resolved project config: @lunora/* versions, wrangler summary, schema overview",examples:[["lunora info","Print resolved project config"],["lunora info --json","Emit a JSON snapshot"]],group:"Project",loader:()=>import("../packem_chunks/handler12.mjs").then(e=>({default:e.execute})),name:"info",options:[{description:"Emit a JSON snapshot instead of human text",name:"json",type:Boolean}]},Q={argument:{description:"Project name",name:"name",type:String},description:"Scaffold a new Lunora project",examples:[["lunora init my-app","Scaffold with the default (vite) template"],["lunora init my-app -t next","Scaffold a Next.js app"],["lunora init my-app -t tanstack-start-react","Scaffold a TanStack Start (React) app"],["lunora init my-app -t tanstack-start-solid","Scaffold a TanStack Start (Solid) app"],["lunora init my-app --ref alpha","Scaffold from the alpha branch's templates"],["lunora init --here","Add Lunora to the current project"],["lunora init my-app --ci github","Scaffold + add a GitHub Actions deploy pipeline"],["lunora init my-app --ci gitlab","Scaffold + add a GitLab CI deploy pipeline"]],group:"Project",loader:()=>import("../packem_chunks/runInitCommand.mjs").then(e=>({default:e.execute})),name:"init",options:[{alias:"t",description:"Bespoke template (standalone | astro | next | nuxt | sveltekit | tanstack-start-react | tanstack-start-solid). For an SPA use --vite react|vue|solid|svelte.",name:"template",type:String},{description:"Scaffold via the create-vite overlay for a framework (react | vue | solid | svelte | vanilla) — official create-vite base + Lunora layer",name:"vite",type:String},{description:"Local templates root to copy from (offline-friendly; expects <type>/ subdirs)",name:"from",type:String},{description:"Override the remote template source (e.g. gh:owner/repo/sub#ref)",name:"source",type:String},{description:"Fetch templates from a git ref (branch, tag, or commit), e.g. --ref alpha. Overrides the version-derived default",name:"ref",type:String},{description:"Permit --source values outside gh:/github:/https:// (e.g. local file://)",name:"allow-unsafe-source",type:Boolean},{description:"Add Lunora to the current project: detect the framework, patch the config, scaffold lunora/, print per-framework wiring steps",name:"here",type:Boolean},{alias:"i",description:"After scaffolding, offer to add auth + email (defaults on when stdin is a TTY)",name:"interactive",type:Boolean},{alias:"y",description:"Skip the auth/email offer; scaffold only",name:"yes",type:Boolean},{description:"Also scaffold a CI deploy pipeline: github (.github/workflows/deploy.yml) or gitlab (.gitlab-ci.yml)",name:"ci",type:String},{description:"Add features non-interactively after scaffolding (comma-separated): ai | auth | backup | browser | cloudflare-access | crons | email | flags | hyperdrive | payment | presence | queue | storage | workflow",name:"add",type:String},{description:"Walk through every step (prompts + output) without writing files, installing, or running git",name:"dry-run",type:Boolean}]},X={description:"Report write-conflict hot-spots, error rates, and latency outliers from a running Worker",examples:[["lunora insights","Report against the local dev worker"],["lunora insights --shard channel:demo","Scope the report to one shard"],["lunora insights --json","Emit the raw report as JSON"],["lunora insights --prod --url https://app.example.com --token $LUNORA_ADMIN_TOKEN","Report against production"]],group:"Develop",loader:()=>import("../packem_chunks/handler13.mjs").then(e=>({default:e.execute})),name:"insights",options:[{description:"Explicit shard key (defaults to the root shard)",name:"shard",type:String},{description:"Max rows per section (default 10)",name:"limit",type:String},{description:"Emit a JSON report instead of human text",name:"json",type:Boolean},{description:"Target production — requires an explicit --url",name:"prod",type:Boolean},{description:"Worker URL (default http://localhost:8787)",name:"url",type:String},{description:"Admin bearer token (or LUNORA_ADMIN_TOKEN)",name:"token",type:String}]},Z={description:"Link this checkout to its deployed Worker (writes .lunora/project.json)",examples:[["lunora link --url https://app.acme.workers.dev","Link to a deployed Worker URL"],["lunora link --url https://app.acme.workers.dev --env production","Link a named environment"],["lunora link --remove","Remove the link"]],group:"Deploy",loader:()=>import("../packem_chunks/handler14.mjs").then(e=>({default:e.execute})),name:"link",options:[{description:"Cloudflare environment name to record alongside the link",name:"env",type:String},{description:"Worker name (defaults to the `name` in wrangler config)",name:"name",type:String},{description:"Remove the existing link (.lunora/project.json)",name:"remove",type:Boolean},{description:"Deployed Worker URL to link (e.g. https://app.acme.workers.dev)",name:"url",type:String}]},ee={argument:{description:"Worker name (defaults to the name in wrangler config)",name:"worker",type:String},description:"Stream live logs from a deployed Worker, or read the durable log archive with --durable",group:"Deploy",loader:()=>import("../packem_chunks/handler21.mjs").then(e=>({default:e.execute})),name:"logs",options:[{description:"Cloudflare environment name",name:"env",type:String},{description:"Output format: pretty (default) or json",name:"format",type:String},{description:"Substring filter on log messages",name:"search",type:String},{description:"Filter by invocation status: ok, error, or canceled",name:"status",type:String},{description:"Tail a temporary-account deployment when unauthenticated (wrangler tail --temporary). Errors if you're already authenticated.",name:"temporary",type:Boolean},{description:"Read the durable log archive (pipelineLogSink → R2) via R2 SQL instead of tailing live",name:"durable",type:Boolean},{description:"durable: Iceberg table the Pipeline writes to (required with --durable)",name:"table",type:String},{description:"durable: Iceberg namespace (R2 Data Catalog database) the table lives in",name:"namespace",type:String},{description:"durable: lower time bound (epoch-millis or ISO 8601), inclusive",name:"since",type:String},{description:"durable: upper time bound (epoch-millis or ISO 8601), inclusive",name:"until",type:String},{description:"durable: exact severity filter (trace|debug|log|info|warn|error|fatal)",name:"level",type:String},{description:"durable: severity floor — this level and every more-severe one",name:"min-level",type:String},{description:"durable: keep function paths starting with this prefix (LIKE 'prefix%')",name:"function-prefix",type:String},{description:"durable: trace-id filter",name:"trace-id",type:String},{description:"durable: shard-key filter",name:"shard-key",type:String},{description:"durable: user-id filter",name:"user-id",type:String},{description:"durable: max rows (clamped to 1–10000; default 500)",name:"limit",type:String},{description:"durable: resume after a prior page — the opaque cursor token printed by the previous page (bare epoch-millis also accepted for back-compat)",name:"cursor",type:String},{description:"durable: emit one JSON object per line instead of a table",name:"ndjson",type:Boolean}]},te={argument:{description:"install [client…] | uninstall [client…] | serve",name:"args",type:String},description:"Connect your AI editor to Lunora over MCP (docs search + this project's dev server)",examples:[["lunora mcp install","Install into every MCP client already configured here"],["lunora mcp install claude-code cursor","Install into specific clients"],["lunora mcp install --list","List the supported clients and their config files"],["lunora mcp install --docs-only","Install only the hosted documentation server"],["lunora mcp install --print","Show the config that would be written, without writing it"],["lunora mcp install --global","Force every server into the machine-wide config"],["lunora mcp uninstall","Remove Lunora's MCP servers from every supported client"],["lunora mcp uninstall cursor","Remove them from one client"],["lunora mcp uninstall --print","Show what would be removed, without removing it"],["lunora mcp serve","Run the stdio MCP server (this is what your editor spawns)"],["lunora mcp serve --allow-writes","Also expose the mutation/action tools"]],group:"Develop",loader:()=>import("../packem_chunks/handler22.mjs").then(e=>({default:e.execute})),name:"mcp",options:[{description:"install: replace entries that already exist",name:"force",type:Boolean},{description:"install: list the supported clients and their config files",name:"list",type:Boolean},{description:"install/uninstall: print what would change instead of writing it",name:"print",type:Boolean},{description:"install/uninstall: only the hosted documentation server",name:"docs-only",type:Boolean},{description:"install/uninstall: only this project's local server",name:"local-only",type:Boolean},{description:"install/uninstall: the machine-wide config (install default: docs server global, local server per-project)",name:"global",type:Boolean},{description:"install/uninstall: this project's config instead of the machine-wide one",name:"project",type:Boolean},{description:"serve: also expose the mutation/action tools (default: read-only)",name:"allow-writes",type:Boolean},{description:"serve: skip the documentation tools",name:"no-docs",type:Boolean},{description:"Docs site origin backing the documentation tools (default https://lunora.sh)",name:"docs-url",type:String},{description:"serve: deployment URL to expose (default: the running dev server)",name:"url",type:String},{description:"serve: bearer token (default: LUNORA_ADMIN_TOKEN from the environment or .dev.vars)",name:"token",type:String}]},re={argument:{description:"generate | create | up | down | status | d1-to-hyperdrive [name|id]",name:"subcommand",type:String},description:"Schema (generate), online data (create | up | down | status), and backend (d1-to-hyperdrive) migrations",examples:[["lunora migrate generate","Diff lunora/schema.ts and emit a SQL migration"],["lunora migrate create add_users_email","Scaffold a data migration"],["lunora migrate up backfill-names","Run a data migration across shards"],["lunora migrate status backfill-names","Report a migration's per-shard status"],["lunora migrate d1-to-hyperdrive --from-url https://old --to-url https://new","Copy .global() data from D1 to Hyperdrive"]],group:"Data",loader:()=>import("../packem_chunks/runMigrateGenerateCommand.mjs").then(e=>({default:e.execute})),name:"migrate",options:[{description:"Migration name slug (e.g. add_users_email)",name:"name",type:String},{description:"Target table for `create` (prompted for interactively when omitted)",name:"table",type:String},{description:"Preview a data migration without rewriting rows",name:"dry-run",type:Boolean},{description:"Rows per batch for a data migration",name:"batch-size",type:Number},{description:"Cap batches processed this run (maps to the runner's maxBatches)",name:"steps",type:Number},{description:"Target production — requires an explicit --url",name:"prod",type:Boolean},{description:"Worker URL (default http://localhost:8787)",name:"url",type:String},{description:"Admin bearer token (prefer LUNORA_ADMIN_TOKEN; --token is visible to other local processes via the process table)",name:"token",type:String},{description:"Required with --prod for up/down — confirms running against production",name:"yes",type:Boolean},{description:"d1-to-hyperdrive: source (D1) worker URL (defaults to --url)",name:"from-url",type:String},{description:"d1-to-hyperdrive: source admin token (defaults to --token / LUNORA_ADMIN_TOKEN)",name:"from-token",type:String},{description:"d1-to-hyperdrive: target (Hyperdrive) worker URL (defaults to --url)",name:"to-url",type:String},{description:"d1-to-hyperdrive: target admin token (defaults to --token / LUNORA_ADMIN_TOKEN)",name:"to-token",type:String},{description:"d1-to-hyperdrive: comma-separated .global() tables to move (default: all global tables)",name:"tables",type:String},{description:"d1-to-hyperdrive: keep the intermediate NDJSON dump at this path",name:"out",type:String}]},oe={description:"Run codegen + binding reconcile + wrangler validation (no Vite) — for CI",examples:[["lunora prepare","Codegen + binding reconcile + validate (CI, before deploy)"]],group:"Deploy",loader:()=>import("../packem_chunks/handler15.mjs").then(e=>({default:e.execute})),name:"prepare",options:[{description:"Override the schema-drift gate (proceed even with breaking schema drift and no migration)",name:"allow-schema-drift",type:Boolean},{description:`Which API spec(s) to emit: ${s} (default openapi)`,name:"api-spec",type:String},{description:"Re-bless the committed schema baseline (lunora/.lunora-schema.json) with the current shape",name:"update-schema-baseline",type:Boolean}]},ne={argument:{description:"<add|list|view|build> [item names…]",name:"args",type:String},description:"Component registry: add/list/view items, or build the catalog",examples:[["lunora registry list","List available registry items"],["lunora registry add presence","Scaffold a registry item into lunora/"],["lunora registry build --check","Verify the committed catalog is current"]],group:"Project",loader:()=>import("../packem_chunks/handler16.mjs").then(e=>({default:e.execute})),name:"registry",options:[{description:"add: print the plan and stop without writing",name:"dry-run",type:Boolean},{description:"add: preview the file changes (content diff) and write nothing",name:"diff",type:Boolean},{description:"add: force-overwrite existing files (take the incoming copy)",name:"overwrite",type:Boolean},{description:"add: skip the package.json mutation confirmation prompt",name:"yes",type:Boolean},{description:"Local registry root (offline; expects <name>/ subdirs)",name:"from",type:String},{description:"Override the remote registry source base (e.g. gh:owner/repo/registry)",name:"source",type:String},{description:"Fetch items from a git ref (branch, tag, or commit), e.g. --ref alpha. Overrides the version-derived default",name:"ref",type:String},{description:"Permit --source values outside gh:/github:/https://",name:"allow-unsafe-source",type:Boolean},{description:"Emit JSON output (add plan / list)",name:"json",type:Boolean},{description:"build: output path for the catalog (default <root>/index.json)",name:"out",type:String},{description:"build: verify the index is current instead of rewriting it",name:"check",type:Boolean}]},ae={description:"Clear local Miniflare state (and .lunora-cache with --all)",examples:[["lunora reset","Clear local Miniflare state"],["lunora reset --all","Also remove .lunora-cache"]],group:"Develop",loader:()=>import("../packem_chunks/runResetCommand.mjs").then(e=>({default:e.execute})),name:"reset",options:[{description:"Also remove .lunora-cache",name:"all",type:Boolean},{description:"Skip the confirmation prompt (required when stdin is not a TTY)",name:"yes",type:Boolean}]},ie={argument:{description:"install | check",name:"subcommand",type:String},description:"Install the Lunora agent skills (AI rules) into .agents/skills/, or check they're present",examples:[["lunora rules install","Copy the Lunora agent skills into .agents/skills/"],["lunora rules install --overwrite","Reinstall, replacing edited skill files"],["lunora rules check","Report which Lunora skills are installed"],["lunora rules check --strict","Exit non-zero when rules are missing (CI gate)"]],group:"Project",loader:()=>import("../packem_chunks/handler17.mjs").then(e=>({default:e.execute})),name:"rules",options:[{description:"install: overwrite skill files that already exist (default: skip them)",name:"overwrite",type:Boolean},{description:"check: exit non-zero when the rules are missing (for CI gating)",name:"strict",type:Boolean}]},se={argument:{description:"Function path (e.g. messages:send)",name:"functionPath",type:String},description:"Send a single RPC to a running Lunora Worker",examples:[[`lunora run messages:send --args '{"text":"hi"}'`,"Call a function with JSON args"],["lunora run messages:list --shard channel:demo","Target a specific shard"]],group:"Develop",loader:()=>import("../packem_chunks/runRpcCommand.mjs").then(e=>({default:e.execute})),name:"run",options:[{description:"JSON-encoded args object",name:"args",type:String},{description:"Explicit shard key",name:"shard",type:String},{description:"Worker URL (default http://localhost:8787)",name:"url",type:String}]},le={description:"Generate deterministic fake data from lunora/schema.ts and bulk-insert it via the worker's admin endpoint",examples:[["lunora seed","Seed every table with the default row count"],["lunora seed --table posts --count 50","Seed 50 posts; FK-parent tables are seeded automatically"],["lunora seed --reset","Wipe local .wrangler/state, then seed from scratch"],["lunora seed --seed 7 --dry-run","Print the NDJSON for seed 7 without inserting"]],group:"Data",loader:()=>import("../packem_chunks/handler18.mjs").then(e=>({default:e.execute})),name:"seed",options:[{description:"Rows per table (default 10)",name:"count",type:Number},{description:"Seed only this table; its FK-parent tables are seeded automatically",name:"table",type:String},{description:"Deterministic seed — same value yields identical rows (default 0)",name:"seed",type:Number},{description:"Print the generated NDJSON instead of inserting",name:"dry-run",type:Boolean},{description:"Wipe local .wrangler/state before seeding (local dev only)",name:"reset",type:Boolean},{description:"Rows per HTTP request (default 500)",name:"batch-size",type:Number},{description:"Target production — requires an explicit --url",name:"prod",type:Boolean},{description:"Worker URL (default http://localhost:8787)",name:"url",type:String},{description:"Admin bearer token (prefer LUNORA_ADMIN_TOKEN; --token is visible to other local processes via the process table)",name:"token",type:String},{description:"Skip the confirmation prompt when seeding a non-local/production target",name:"yes",type:Boolean}]},pe={description:"Validate wrangler.jsonc + codegen dry-run + tsc --noEmit (no files written)",examples:[["lunora verify","Validate wrangler + codegen + tsc"],["lunora verify --no-typecheck","Skip the TypeScript type-check"],["lunora verify --health-url https://my-app.workers.dev","Also probe the deployment's /_lunora/health"]],group:"Deploy",loader:()=>import("../packem_chunks/handler19.mjs").then(e=>({default:e.execute})),name:"verify",options:[{description:"Treat breaking schema drift as a warning instead of a failure",name:"allow-schema-drift",type:Boolean},{description:`Which API spec(s) to emit: ${s} (default openapi)`,name:"api-spec",type:String},{description:"Output format: pretty (default) or json",name:"format",type:String},{description:"Probe this deployment's /_lunora/health endpoint (off by default; keeps verify offline-safe)",name:"health-url",type:String},{description:"Skip the TypeScript type-check step",name:"no-typecheck",type:Boolean}]},de={description:"Open the Lunora studio in your browser (local dev by default, --remote for production)",examples:[["lunora view","Open the studio for local dev"],["lunora view --remote","Open the deployed studio"]],group:"Project",loader:()=>import("../packem_chunks/handler20.mjs").then(e=>({default:e.execute})),name:"view",options:[{description:"Open the deployed worker URL instead of localhost",name:"remote",type:Boolean}]},ce={filterStacktrace:()=>!1,hideErrorCodeView:!0},ue=(e,t={})=>{const r=e instanceof Error?e.message:String(e),o=B(v(e)?{code:e.code,hint:e.hint,message:r}:r),n=new E({hint:o===void 0?void 0:A(o).split(`
2
+ `),message:t.reason===void 0?r:`${t.reason}: ${r}`,name:e instanceof Error&&e.name.length>0?e.name:"Error"});return n.stack="",I(n,ce)},me=(e,t)=>{const r=Array.from({length:t.length+1},(o,n)=>n);for(let o=1;o<=e.length;o+=1){let n=r[0]??0;r[0]=o;for(let a=1;a<=t.length;a+=1){const i=r[a]??0,l=e[o-1]===t[a-1]?0:1;r[a]=Math.min((r[a-1]??0)+1,i+1,n+l),n=i}}return r[t.length]??0},ge=(e,t)=>{let r,o=Number.POSITIVE_INFINITY;for(const a of t){const i=me(e,a);i<o&&(o=i,r=a)}const n=Math.max(2,Math.ceil(e.length/3));return r!==void 0&&o<=n?r:void 0},he=e=>`https://registry.npmjs.org/@lunora/cli/${e}`,ye=1440*60*1e3,fe=1500,ve="0.0.0",be=/^v/u,ke=new Set(["alpha","beta","next"]),c=e=>{const t=e.trim().replace(be,""),r=t.indexOf("-");return r===-1?{core:t,prerelease:""}:{core:t.slice(0,r),prerelease:t.slice(r+1)}},h=e=>{const[t,r,o]=c(e).core.split(".").map(n=>{const a=Number.parseInt(n,10);return Number.isFinite(a)?a:0});return[t??0,r??0,o??0]},we=(e,t)=>{const r=Number.parseInt(e,10),o=Number.parseInt(t,10);return String(r)===e&&String(o)===t?r>o?1:-1:e>t?1:-1},Se=(e,t)=>{if(e===t)return 0;if(e===""||t==="")return e===""?1:-1;const r=e.split("."),o=t.split(".");for(let n=0;n<Math.max(r.length,o.length);n+=1){const a=r[n],i=o[n];if(a===void 0||i===void 0)return a===void 0?-1:1;if(a!==i)return we(a,i)}return 0},xe=(e,t)=>{const r=h(e),o=h(t);for(let n=0;n<3;n+=1)if((r[n]??0)!==(o[n]??0))return(r[n]??0)>(o[n]??0)?1:-1;return Se(c(e).prerelease,c(t).prerelease)},Ne=e=>{const t=c(e).prerelease.split(".")[0]??"";return ke.has(t)?t:"latest"},Oe=(e,t)=>xe(t,e)>0,Re=(e,t,r)=>t-e<r,Be=(e,t,r="latest")=>`Update available for @lunora/cli: ${e} → ${t} — run \`pnpm add -D @lunora/cli@${r}\``,k=e=>d(e,"lunora-cli-update.json"),Ae=e=>{const t=e.XDG_CACHE_HOME&&e.XDG_CACHE_HOME.length>0?e.XDG_CACHE_HOME:d(T(),".cache"),r=d(t,"lunora");try{x(r,{mode:448,recursive:!0})}catch{}return r},Le=e=>{try{const t=JSON.parse(f(k(e),"utf8"));if(t!==null&&typeof t=="object"){const{checkedAt:r,latest:o}=t;if(typeof o=="string"&&typeof r=="number"){const{tag:n}=t;return{checkedAt:r,latest:o,...typeof n=="string"?{tag:n}:{}}}}}catch{}},y=(e,t)=>{try{const r=k(e);try{if(N(r).isSymbolicLink())return}catch{}O(r,`${JSON.stringify(t)}
3
+ `,"utf8")}catch{}},De=async(e,t)=>{try{const r=await e(he(t),{signal:AbortSignal.timeout(fe)});if(!r.ok)return;const o=await r.json(),n=o!==null&&typeof o=="object"?o.version:void 0;return typeof n=="string"?n:void 0}catch{return}},Ce=(e,t,r)=>e===ve||!r||t.CI!==void 0||t.LUNORA_NO_UPDATE_NOTIFIER!==void 0,je=async e=>{const t=e.env??process.env,r=e.isTTY??process.stdout.isTTY;if(Ce(e.current,t,r))return;const o=e.cacheDir??Ae(t),n=(e.now??Date.now)(),a=e.ttlMs??ye,i=Ne(e.current),l=Le(o),S=l?.tag??"latest",u=l!==void 0&&S===i?l:void 0;let p=u?.latest;if(u===void 0||!Re(u.checkedAt,n,a)){const m=await De(e.fetchImpl??globalThis.fetch,i);m===void 0?y(o,{checkedAt:n,latest:e.current,tag:i}):(p=m,y(o,{checkedAt:n,latest:m,tag:i}))}p!==void 0&&Oe(e.current,p)&&e.logger.warn(Be(e.current,p,i))},Ee=["init","add","dev","codegen","build","deploy","containers","prepare","link","deployments","logs","run","insights","reset","migrate","export","import","seed","backup","verify","info","doctor","env","analyze","view","docs","registry","rules","mcp"],Ie=8,Te=()=>{try{let e=g(R(import.meta.url));for(let t=0;t<Ie;t+=1){try{const o=JSON.parse(f(d(e,"package.json"),"utf8")),n=o!==null&&typeof o=="object"?o:void 0;if(n?.name==="@lunora/cli"&&typeof n.version=="string"&&n.version.length>0)return n.version}catch{}const r=g(e);if(r===e)break;e=r}}catch{}return"0.0.0"},w=Te(),_e=[Q,_,q,M,U,J,W,oe,Z,K,ee,se,X,ae,re,G,Y,le,$,pe,z,H,V,P,de,F,ne,ie,te],Pe=e=>{const t={value:0},r=D("lunora",{argv:e.argv===void 0?void 0:[...e.argv],cwd:e.cwd,exit:o=>{t.value=typeof o=="number"?o:0},logger:e.logger,packageName:"@lunora/cli",packageVersion:w});for(const o of _e)r.addCommand(o);return r.addCommand(j),r.addCommand(C),{cli:r,exitCode:t}},$e=/Command "(?<name>[^"]+)" not found/u,Ue=e=>{const t=b(),r=e instanceof Error?e.message:String(e),o=$e.exec(r);if(!o?.groups){v(e)||L(r)!==void 0?t.error(ue(e)):t.error(r);return}const n=o.groups.name??"",a=ge(n,Ee);t.error(`Unknown command "${n}".${a===void 0?"":` Did you mean "${a}"?`}`),t.info("Run `lunora --help` to list commands, or `lunora docs` to open the documentation.")},Qe=async(e={})=>{const{cli:t,exitCode:r}=Pe(e);try{await t.run({shouldExitProcess:!1})}catch(o){return Ue(o),1}return await je({current:w,logger:b()}),r.value};export{Ee as COMMANDS,w as VERSION,Qe as runCli};