@lunora/cli 1.0.0-alpha.127 → 1.0.0-alpha.129
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.
- package/dist/bin.mjs +1 -1
- package/dist/index.d.mts +24 -3
- package/dist/index.d.ts +24 -3
- package/dist/index.mjs +1 -1
- package/dist/packem_chunks/handler.mjs +1 -1
- package/dist/packem_chunks/handler10.mjs +1 -1
- package/dist/packem_chunks/handler11.mjs +1 -1
- package/dist/packem_chunks/handler16.mjs +1 -1
- package/dist/packem_chunks/handler17.mjs +1 -1
- package/dist/packem_chunks/handler18.mjs +2 -2
- package/dist/packem_chunks/handler21.mjs +1 -1
- package/dist/packem_chunks/handler24.mjs +1 -1
- package/dist/packem_chunks/handler3.mjs +2 -2
- package/dist/packem_chunks/planDevCommand.mjs +6 -6
- package/dist/packem_chunks/runCodegenCommand.mjs +4 -4
- package/dist/packem_chunks/runInitCommand.mjs +1 -1
- package/dist/packem_chunks/runMigrateGenerateCommand.mjs +3 -3
- package/dist/packem_shared/{COMMANDS-BpuzPHyn.mjs → COMMANDS-BHb52jlk.mjs} +1 -1
- package/dist/packem_shared/DEFAULT_IMPORT_BATCH_SIZE-CEOt386P.mjs +12 -0
- package/dist/packem_shared/cli-BxL0WCh4.mjs +3 -0
- package/dist/packem_shared/commands-C5pu77HK.mjs +19 -0
- package/dist/packem_shared/runAddCommand-CuvJ0l7a.mjs +1 -0
- package/dist/packem_shared/{storage-B-VWSXkl.mjs → storage-BazhWFmM.mjs} +1 -1
- package/package.json +11 -11
- package/dist/packem_shared/DEFAULT_IMPORT_BATCH_SIZE-C5vGgrhK.mjs +0 -8
- package/dist/packem_shared/cli-C6sRqIMQ.mjs +0 -3
- package/dist/packem_shared/commands-qFGULoQJ.mjs +0 -19
- package/dist/packem_shared/runAddCommand-Ct-8Rd8I.mjs +0 -1
package/dist/bin.mjs
CHANGED
|
@@ -1,3 +1,3 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
import{e}from"./packem_shared/cli-
|
|
2
|
+
import{e}from"./packem_shared/cli-BxL0WCh4.mjs";try{const r=await e();process.exit(r)}catch(r){process.stderr.write(`${r instanceof Error?r.message:String(r)}
|
|
3
3
|
`),process.exit(1)}
|
package/dist/index.d.mts
CHANGED
|
@@ -65,6 +65,12 @@ interface CodegenCommandOptions {
|
|
|
65
65
|
/** Output format: `pretty` (default) or `json`. */
|
|
66
66
|
format?: string;
|
|
67
67
|
logger: Logger;
|
|
68
|
+
/**
|
|
69
|
+
* Fail the run when any ERROR-level advisory is reported. Defaults to CI
|
|
70
|
+
* detection so a local `lunora codegen` stays advisory while a pipeline
|
|
71
|
+
* gates on it; `--no-strict-advisories` forces it off either way.
|
|
72
|
+
*/
|
|
73
|
+
strictAdvisories?: boolean;
|
|
68
74
|
/** Deploy target the emitted `ctx.*` surface is tailored to. Resolved by the caller; falls back to `"target"` in `lunora.json`, then `"cloudflare"`. */
|
|
69
75
|
target?: string;
|
|
70
76
|
}
|
|
@@ -78,6 +84,8 @@ interface CodegenCommandResult {
|
|
|
78
84
|
cronTriggers: ReadonlyArray<string>;
|
|
79
85
|
/** Set when the run failed: an invalid `--format`, an unregistered target, or an error-level platform diagnostic. */
|
|
80
86
|
error?: string;
|
|
87
|
+
/** ERROR-level advisories that made the run fail, when strict mode is on. */
|
|
88
|
+
failedAdvisories: number;
|
|
81
89
|
outputDirectory: string;
|
|
82
90
|
}
|
|
83
91
|
declare const runCodegenCommand: (options: CodegenCommandOptions) => CodegenCommandResult;
|
|
@@ -153,9 +161,10 @@ interface ImportCommandResult {
|
|
|
153
161
|
inserted: number;
|
|
154
162
|
}
|
|
155
163
|
/**
|
|
156
|
-
* Stream an NDJSON file
|
|
157
|
-
* `/_lunora/admin/import`.
|
|
158
|
-
* multi-GiB
|
|
164
|
+
* Stream an NDJSON file — or a `npx convex export --path <dir>` directory — in
|
|
165
|
+
* chunks, POSTing each batch to `/_lunora/admin/import`. The line buffer stays
|
|
166
|
+
* bounded by `batchSize`, so a multi-GiB source imports without buffering
|
|
167
|
+
* everything in memory.
|
|
159
168
|
*/
|
|
160
169
|
declare const runImportCommand: (options: ImportCommandOptions) => Promise<ImportCommandResult>;
|
|
161
170
|
/**
|
|
@@ -510,6 +519,8 @@ interface DevCommandOptions {
|
|
|
510
519
|
studio?: boolean;
|
|
511
520
|
/** Deploy target the emitted `ctx.*` surface is tailored to. Resolved by the caller; falls back to `"target"` in `lunora.json`, then `"cloudflare"`. */
|
|
512
521
|
target?: string;
|
|
522
|
+
/** Disable the `wrangler dev` spawn — an external task runner owns the worker. */
|
|
523
|
+
worker?: boolean;
|
|
513
524
|
/** `wrangler dev` port. */
|
|
514
525
|
workerPort?: number;
|
|
515
526
|
}
|
|
@@ -562,6 +573,16 @@ interface DevCommandPlan {
|
|
|
562
573
|
};
|
|
563
574
|
studioEnabled: boolean;
|
|
564
575
|
studioPort: number;
|
|
576
|
+
/**
|
|
577
|
+
* Whether this process spawns `wrangler dev`.
|
|
578
|
+
*
|
|
579
|
+
* `--no-worker` turns it off so an external task runner (Turbo, Nx, vis, a
|
|
580
|
+
* Procfile) can own worker supervision while `lunora dev` still provides
|
|
581
|
+
* codegen-watch and Studio. Without it, `lunora dev` insisted on being the
|
|
582
|
+
* process root, which is what blocked running the Lunora worker as one node
|
|
583
|
+
* in a larger dev graph.
|
|
584
|
+
*/
|
|
585
|
+
workerEnabled: boolean;
|
|
565
586
|
workerOrigin: string;
|
|
566
587
|
workerPort: number;
|
|
567
588
|
/** The primary child `lunora dev` spawns: `wrangler dev` (wrangler flavor) or the framework/`vite dev` server (vite / framework-worker). */
|
package/dist/index.d.ts
CHANGED
|
@@ -65,6 +65,12 @@ interface CodegenCommandOptions {
|
|
|
65
65
|
/** Output format: `pretty` (default) or `json`. */
|
|
66
66
|
format?: string;
|
|
67
67
|
logger: Logger;
|
|
68
|
+
/**
|
|
69
|
+
* Fail the run when any ERROR-level advisory is reported. Defaults to CI
|
|
70
|
+
* detection so a local `lunora codegen` stays advisory while a pipeline
|
|
71
|
+
* gates on it; `--no-strict-advisories` forces it off either way.
|
|
72
|
+
*/
|
|
73
|
+
strictAdvisories?: boolean;
|
|
68
74
|
/** Deploy target the emitted `ctx.*` surface is tailored to. Resolved by the caller; falls back to `"target"` in `lunora.json`, then `"cloudflare"`. */
|
|
69
75
|
target?: string;
|
|
70
76
|
}
|
|
@@ -78,6 +84,8 @@ interface CodegenCommandResult {
|
|
|
78
84
|
cronTriggers: ReadonlyArray<string>;
|
|
79
85
|
/** Set when the run failed: an invalid `--format`, an unregistered target, or an error-level platform diagnostic. */
|
|
80
86
|
error?: string;
|
|
87
|
+
/** ERROR-level advisories that made the run fail, when strict mode is on. */
|
|
88
|
+
failedAdvisories: number;
|
|
81
89
|
outputDirectory: string;
|
|
82
90
|
}
|
|
83
91
|
declare const runCodegenCommand: (options: CodegenCommandOptions) => CodegenCommandResult;
|
|
@@ -153,9 +161,10 @@ interface ImportCommandResult {
|
|
|
153
161
|
inserted: number;
|
|
154
162
|
}
|
|
155
163
|
/**
|
|
156
|
-
* Stream an NDJSON file
|
|
157
|
-
* `/_lunora/admin/import`.
|
|
158
|
-
* multi-GiB
|
|
164
|
+
* Stream an NDJSON file — or a `npx convex export --path <dir>` directory — in
|
|
165
|
+
* chunks, POSTing each batch to `/_lunora/admin/import`. The line buffer stays
|
|
166
|
+
* bounded by `batchSize`, so a multi-GiB source imports without buffering
|
|
167
|
+
* everything in memory.
|
|
159
168
|
*/
|
|
160
169
|
declare const runImportCommand: (options: ImportCommandOptions) => Promise<ImportCommandResult>;
|
|
161
170
|
/**
|
|
@@ -510,6 +519,8 @@ interface DevCommandOptions {
|
|
|
510
519
|
studio?: boolean;
|
|
511
520
|
/** Deploy target the emitted `ctx.*` surface is tailored to. Resolved by the caller; falls back to `"target"` in `lunora.json`, then `"cloudflare"`. */
|
|
512
521
|
target?: string;
|
|
522
|
+
/** Disable the `wrangler dev` spawn — an external task runner owns the worker. */
|
|
523
|
+
worker?: boolean;
|
|
513
524
|
/** `wrangler dev` port. */
|
|
514
525
|
workerPort?: number;
|
|
515
526
|
}
|
|
@@ -562,6 +573,16 @@ interface DevCommandPlan {
|
|
|
562
573
|
};
|
|
563
574
|
studioEnabled: boolean;
|
|
564
575
|
studioPort: number;
|
|
576
|
+
/**
|
|
577
|
+
* Whether this process spawns `wrangler dev`.
|
|
578
|
+
*
|
|
579
|
+
* `--no-worker` turns it off so an external task runner (Turbo, Nx, vis, a
|
|
580
|
+
* Procfile) can own worker supervision while `lunora dev` still provides
|
|
581
|
+
* codegen-watch and Studio. Without it, `lunora dev` insisted on being the
|
|
582
|
+
* process root, which is what blocked running the Lunora worker as one node
|
|
583
|
+
* in a larger dev graph.
|
|
584
|
+
*/
|
|
585
|
+
workerEnabled: boolean;
|
|
565
586
|
workerOrigin: string;
|
|
566
587
|
workerPort: number;
|
|
567
588
|
/** The primary child `lunora dev` spawns: `wrangler dev` (wrangler flavor) or the framework/`vite dev` server (vite / framework-worker). */
|
package/dist/index.mjs
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{s as o,t as n,e as a}from"./packem_shared/cli-
|
|
1
|
+
import{s as o,t as n,e as a}from"./packem_shared/cli-BxL0WCh4.mjs";import{runCodegenCommand as t}from"./packem_chunks/runCodegenCommand.mjs";import{DEFAULT_IMPORT_BATCH_SIZE as p,runExportCommand as f,runImportCommand as x}from"./packem_shared/DEFAULT_IMPORT_BATCH_SIZE-CEOt386P.mjs";import{runDeployCommand as C}from"./packem_chunks/runDeployCommand.mjs";import{planDevCommand as s,runDevCommand as u}from"./packem_chunks/planDevCommand.mjs";import{runInitCommand as g}from"./packem_chunks/runInitCommand.mjs";import{runMigrateGenerateCommand as R}from"./packem_chunks/runMigrateGenerateCommand.mjs";import{runResetCommand as E}from"./packem_chunks/runResetCommand.mjs";import{runRpcCommand as A}from"./packem_chunks/runRpcCommand.mjs";import{insertSchemaExtension as M}from"./packem_shared/insertSchemaExtension-DZReBZ4_.mjs";import{createLogger as _,pail as h}from"./packem_shared/createLogger--C3x1FNE.mjs";import{diffSnapshots as L,renderAddColumn as O,renderCreateIndex as b,renderCreateTable as w,renderDropIndex as B,renderDropTable as F,renderMigrationFile as P,validatorKindToSqlType as U}from"./packem_shared/diffSnapshots-9bDd9nOK.mjs";import{default as q}from"./packem_shared/schemaIrToSnapshot-Clwd2A8e.mjs";import{createRecordingSpawner as N,defaultSpawner as Q}from"./packem_shared/createRecordingSpawner-ByIqBepG.mjs";import{default as j}from"./packem_shared/parseManifest-x3WsxKHz.mjs";import{REQUIRED_COMPATIBILITY_DATE as H,REQUIRED_FLAG as K,validateWranglerProject as Y,validateWranglerConfig as Z}from"@lunora/config/cloudflare";import{buildRegistryIndex as J}from"./packem_shared/buildRegistryIndex-DwySASBu.mjs";import{k as $,q as rr,D as er}from"./packem_shared/commands-C5pu77HK.mjs";export{o as COMMANDS,p as DEFAULT_IMPORT_BATCH_SIZE,H as REQUIRED_COMPATIBILITY_DATE,K as REQUIRED_FLAG,n as VERSION,J as buildRegistryIndex,_ as createLogger,N as createRecordingSpawner,Q as defaultSpawner,L as diffSnapshots,M as insertSchemaExtension,h as pail,j as parseManifest,s as planDevCommand,O as renderAddColumn,b as renderCreateIndex,w as renderCreateTable,B as renderDropIndex,F as renderDropTable,P as renderMigrationFile,$ as runAddCommand,rr as runBuildIndexCommand,a as runCli,t as runCodegenCommand,C as runDeployCommand,u as runDevCommand,f as runExportCommand,x as runImportCommand,g as runInitCommand,R as runMigrateGenerateCommand,er as runRegistryViewCommand,E as runResetCommand,A as runRpcCommand,q as schemaIrToSnapshot,Y as validateWrangler,Z as validateWranglerConfig,U as validatorKindToSqlType};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{existsSync as y,readFileSync as $}from"node:fs";import{findWranglerFile as b}from"@lunora/config/cloudflare";import{join as p,basename as h}from"@visulima/path";import{i as k}from"../packem_shared/command-Bjv4VmYA.mjs";import{i as S,r as T,d as j,s as U}from"../packem_shared/output-format-D7cKB-O5.mjs";import{B as g,C as x}from"../packem_shared/tui-prompts-CCt3jm1k.mjs";import{d as C,r as
|
|
1
|
+
import{existsSync as y,readFileSync as $}from"node:fs";import{findWranglerFile as b}from"@lunora/config/cloudflare";import{join as p,basename as h}from"@visulima/path";import{i as k}from"../packem_shared/command-Bjv4VmYA.mjs";import{i as S,r as T,d as j,s as U}from"../packem_shared/output-format-D7cKB-O5.mjs";import{B as g,C as x}from"../packem_shared/tui-prompts-CCt3jm1k.mjs";import{d as C,r as R,l as q,i as B,o as l,u as D,a as m,b as F,c as L,e as f,f as M,g as d,n as N,h as W,s as u,j as A,k as O,p as G,m as J,q as K}from"../packem_shared/storage-BazhWFmM.mjs";import{k as P}from"../packem_shared/commands-C5pu77HK.mjs";const Q=r=>{const e=r.trim().toLowerCase();return O.find(a=>a.value===e||a.label.toLowerCase()===e||e==="auth0"&&a.value==="auth-auth0"||e==="clerk"&&a.value==="auth-clerk")?.value},w=r=>{try{const e=JSON.parse($(p(r,"package.json"),"utf8"));return{...e.dependencies,...e.devDependencies}}catch{return{}}},V=async r=>{const e=r.cwd??process.cwd(),a=W(w(e));return a!==void 0?a:r.yes===!0?(r.logger.warn(`add: couldn't detect your framework — using "${u}". Pass a specific item (e.g. \`lunora add auth-ui-vue\`) to override.`),u):await(r.promptSelect??((o,s,n)=>g(o,s,n)))("Which framework is your app?",A,{default:u})??u},X=async r=>{if(r.provider!==void 0&&r.provider!==""){const a=Q(r.provider);return a===void 0?(r.logger.warn(`add: unknown --provider "${r.provider}" — using "${d}" (email & password).`),d):a}if(r.yes===!0)return d;const e=r.promptSelect??((a,o,s)=>g(a,o,s));return N(e)},c=r=>r.promptText??((e,a)=>x(e,a)),Y=async r=>{const e=h(r.cwd??process.cwd());if(r.bucket!==void 0&&r.bucket!==""){const a=B(r.bucket);if(a!==void 0)return a;const o=l(e);return r.logger.warn(`add: "${r.bucket}" isn't a valid R2 bucket name (lowercase alphanumeric + hyphens, 3–63 chars) — using "${o}".`),o}return r.yes===!0?l(e):D(c(r),e)},Z=async r=>{const e=a=>{r.logger.warn(`add: ${a}`)};if(r.mailTo!==void 0&&r.mailTo!=="")return m(r.mailTo,e);if(r.yes!==!0)return m(await c(r)(F,{placeholder:"you@yourdomain.com"}),e)},z=async r=>{const e=h(r.cwd??process.cwd());if(r.db!==void 0&&r.db!==""){const a=L(r.db);if(a!==void 0)return a;const o=f(e);return r.logger.warn(`add: "${r.db}" isn't a usable D1 database name — using "${o}".`),o}return r.yes===!0?f(e):M(c(r),e)},E=async(r,e)=>r.kind==="auth"?[await X(e)]:r.kind==="auth-ui"?[await V(e)]:r.kind==="email"?[q]:[r.item],H=async r=>{const e=r.cwd??process.cwd(),a=r.feature===void 0?void 0:C(r.feature);if(a===void 0)return r.logger.error("add requires a feature or registry item. Usage: lunora add <auth|email|storage|crons|presence|…>"),{code:1,items:[]};if(!y(p(e,"lunora"))||b(e)===void 0)return r.logger.error("add: not a Lunora project here (need a lunora/ directory and a wrangler.jsonc). Run `lunora init` first."),{code:1,items:[]};if(a.kind==="auth-ui"&&R(w(e)))return r.logger.error("add: auth-ui has no React Native port — the screens render DOM elements and a stylesheet, which Metro has nothing to mount. Build the screens with React Native primitives against the same better-auth client (`@lunora/react-native/auth`); `lunora add auth` still installs the server half."),{code:1,items:[]};const o=await E(a,r),s=[];if(o.includes("storage")){const t=await Y(r);s.push(i=>G(i,t))}if(o.includes("mail")){const t=await Z(r);t!==void 0&&s.push(i=>J(i,t))}if(o.some(t=>t==="auth"||t.startsWith("auth-"))){const t=await z(r);s.push(i=>K(i,t))}const n=s.length>0?t=>{let i=t;for(const v of s)i=v(i);return i}:void 0;return{code:(await P({allowUnsafeSource:r.allowUnsafeSource,cwd:e,from:r.from,logger:r.logger,names:[...o],ref:r.ref,source:r.source,transformManifest:n,yes:!0})).code,items:o}},ir=k(async({argument:r,cwd:e,logger:a,options:o})=>{const s=S("add",o.format);if(s!==void 0)return a.error(s),{code:1};const n=U(o.format,a),t=await H({allowUnsafeSource:o.allowUnsafeSource===!0,bucket:o.bucket,cwd:e,db:o.db,feature:r[0],from:o.from,logger:n,mailTo:o.mailTo,provider:o.provider,ref:o.ref,source:o.source,yes:o.yes===!0});return T(o.format)&&j({code:t.code,items:t.items}),{code:t.code}});export{ir as execute,H as runAddFeature};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{i as p}from"../packem_shared/command-Bjv4VmYA.mjs";import{s as u}from"../packem_shared/resolve-target-vxaXHmvg.mjs";import{runExportCommand as m}from"../packem_shared/DEFAULT_IMPORT_BATCH_SIZE-
|
|
1
|
+
import{i as p}from"../packem_shared/command-Bjv4VmYA.mjs";import{s as u}from"../packem_shared/resolve-target-vxaXHmvg.mjs";import{runExportCommand as m}from"../packem_shared/DEFAULT_IMPORT_BATCH_SIZE-CEOt386P.mjs";const s=p(({argument:r,cwd:t,logger:e,options:o})=>m({cwd:t,logger:e,out:r[0]??o.out,prod:o.prod===!0,tables:o.tables,token:o.token,url:u({cwd:t,prod:o.prod===!0,url:o.url})}));export{s as execute};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{i as
|
|
1
|
+
import{i as n}from"../packem_shared/command-Bjv4VmYA.mjs";import{s as p}from"../packem_shared/resolve-target-vxaXHmvg.mjs";import{runImportCommand as i}from"../packem_shared/DEFAULT_IMPORT_BATCH_SIZE-CEOt386P.mjs";const l=n(({argument:a,cwd:e,logger:r,options:o})=>{const t=a[0];return t?i({batchSize:o.batchSize,cwd:e,file:t,logger:r,prod:o.prod===!0,table:o.table,token:o.token,url:p({cwd:e,prod:o.prod===!0,url:o.url}),yes:o.yes===!0}):(r.error("import requires a path. Usage: lunora import <file.ndjson | convex-export-dir> [--table <name>]"),{code:1})});export{l as execute};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{i as n}from"../packem_shared/command-Bjv4VmYA.mjs";import{
|
|
1
|
+
import{i as n}from"../packem_shared/command-Bjv4VmYA.mjs";import{k as c,D as f,q as a}from"../packem_shared/commands-C5pu77HK.mjs";const i=n(({argument:u,cwd:s,logger:o,options:e})=>{const r=u[0],t=u.slice(1);return r==="add"?c({allowUnsafeSource:e.allowUnsafeSource===!0,cwd:s,diff:e.diff===!0,dryRun:e.dryRun===!0,from:e.from,json:e.json===!0,logger:o,names:t,overwrite:e.overwrite===!0,ref:e.ref,source:e.source,yes:e.yes===!0}):r==="list"?c({cwd:s,from:e.from,json:e.json===!0,list:!0,logger:o,names:[],ref:e.ref,source:e.source}):r==="view"?f({allowUnsafeSource:e.allowUnsafeSource===!0,cwd:s,from:e.from,logger:o,names:t,ref:e.ref,source:e.source}):r==="build"?a({check:e.check===!0,from:e.from,logger:o,out:e.out}):(o.error("registry: unknown subcommand. Usage: lunora registry <add|list|view|build> [names…]"),{code:1})});export{i as execute};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{existsSync as
|
|
1
|
+
import{existsSync as c,readFileSync as g,readdirSync as p,statSync as k,mkdirSync as S,writeFileSync as y}from"node:fs";import{fileURLToPath as v}from"node:url";import{AGENT_RULES_DIR as u,detectAgentRules as L,LUNORA_SKILL_NAMES as R}from"@lunora/config";import{join as l,relative as $,resolve as j,dirname as d}from"@visulima/path";import{i as I}from"../packem_shared/command-Bjv4VmYA.mjs";const b=(r=d(v(import.meta.url)))=>{let e=r;for(let n=0;n<6;n+=1){const t=l(e,"package.json");if(c(t))try{if(JSON.parse(g(t,"utf8")).name==="@lunora/cli"){const s=l(e,"skills");return c(s)?s:void 0}}catch{}const o=d(e);if(o===e)break;e=o}},A=r=>p(r).filter(e=>{const n=l(r,e);return k(n).isDirectory()&&c(l(n,"SKILL.md"))}),m=(r,e,n)=>{S(e,{recursive:!0});let t=!1;for(const o of p(r)){const s=l(r,o),i=l(e,o);if(k(s).isDirectory()){t=m(s,i,n)||t;continue}c(i)&&!n||(y(i,g(s)),t=!0)}return t},_=["pnpm-workspace.yaml","pnpm-lock.yaml","yarn.lock","package-lock.json","bun.lock","bun.lockb",".git"],x=r=>{let e=r;for(;;){if(_.some(t=>c(l(e,t))))return e;const n=d(e);if(n===e)return r;e=n}},f=(r,e)=>e===void 0?x(r):j(r,e),D=r=>{const e=r.cwd??process.cwd(),n=f(e,r.dir),t=r.overwrite===!0,o=b();if(o===void 0)return r.logger.error("rules: could not locate the bundled skills (is @lunora/cli installed correctly?)."),{code:1,installed:[],skipped:[]};const s=[],i=[];for(const a of A(o)){const w=l(n,u,a);m(l(o,a),w,t)?s.push(a):i.push(a)}const h=$(e,l(n,u))||u;return s.length>0&&r.logger.success(`Installed ${String(s.length)} Lunora skill(s) into ${h}/: ${s.join(", ")}.`),i.length>0&&r.logger.info(`Skipped ${String(i.length)} existing skill(s) (re-run with --overwrite to replace): ${i.join(", ")}.`),r.logger.info("Your AI coding agent will pick these up automatically. Start with the `lunora` skill."),{code:0,installed:s,skipped:i}},E=r=>{const e=r.cwd??process.cwd(),n=f(e,r.dir),t=L(n);return t.installed?(r.logger.success(`Lunora agent rules are installed (${String(t.present.length)}/${String(R.length)} skills).`),t.missing.length>0&&r.logger.info(`Missing: ${t.missing.join(", ")}. Run \`lunora rules install\` to add them.`),{code:0,installed:t.present,skipped:[]}):(r.logger.warn("Lunora agent rules are not installed. Run `lunora rules install` so your AI agent knows how to use Lunora."),{code:r.strict===!0?1:0,installed:t.present,skipped:[]})},M=I(({argument:r,cwd:e,logger:n,options:t})=>{const o=r[0]??"check";return o==="install"?D({cwd:e,dir:t.dir,logger:n,overwrite:t.overwrite===!0}):o==="check"?E({cwd:e,dir:t.dir,logger:n,strict:t.strict===!0}):(n.error("rules: unknown subcommand. Usage: lunora rules <install|check>"),{code:1})});export{M as execute,b as resolveBundledSkillsDirectory,E as runRulesCheck,D as runRulesInstall};
|
|
@@ -1,3 +1,3 @@
|
|
|
1
|
-
import{existsSync as y}from"node:fs";import{mkdtemp as S,writeFile as v,rm as
|
|
1
|
+
import{existsSync as y}from"node:fs";import{mkdtemp as S,writeFile as v,rm as j}from"node:fs/promises";import{tmpdir as $}from"node:os";import{discoverSchema as k,schemaFromIr as C}from"@lunora/codegen";import{seedPlan as R}from"@lunora/seed";import{join as m}from"@visulima/path";import{Project as x}from"ts-morph";import{i as z}from"../packem_shared/command-Bjv4VmYA.mjs";import{s as A}from"../packem_shared/resolve-target-vxaXHmvg.mjs";import{i as F}from"../packem_shared/tui-prompts-CCt3jm1k.mjs";import{runImportCommand as I}from"../packem_shared/DEFAULT_IMPORT_BATCH_SIZE-CEOt386P.mjs";import{runResetCommand as T}from"./runResetCommand.mjs";const p=r=>{if(r===void 0)return!0;try{const{hostname:e}=new URL(r);return e==="localhost"||e==="127.0.0.1"||e==="[::1]"||e==="::1"}catch{return!1}},N=(r,e)=>typeof e=="bigint"?Number(e):e instanceof ArrayBuffer?[...new Uint8Array(e)]:e,c=r=>({code:r,conflicts:0,generated:0,inserted:0,ndjson:""}),U=(r,e)=>{if(!y(e))return r.logger.error(`schema not found: ${e} — run \`vis generate lunora-table --name=<name>\` to create one`),c(1);if(r.reset===!0&&(r.prod===!0||!p(r.url)))return r.logger.error("--reset only clears local .wrangler/state and cannot be combined with --prod or a remote --url"),c(1)},P=async(r,e,t,o)=>{const l=await S(m($(),"lunora-seed-")),a=m(l,"rows.ndjson");await v(a,r,"utf8");try{const n=await I({batchSize:o.batchSize,cwd:t,fetchImpl:o.fetchImpl,file:a,logger:o.logger,prod:o.prod,token:o.token,url:o.url}),d=n.body?.conflicts??0;return d>0&&o.logger.warn(`${String(d)} row(s) skipped — their _id already exists. Seeding is deterministic; re-run with --reset to wipe local state first, or a different --seed for fresh ids.`),{code:n.code,conflicts:d,generated:e,inserted:n.inserted,ndjson:r}}finally{await j(l,{force:!0,recursive:!0}).catch(()=>{})}},_=(r,e)=>{if(r.table===void 0||e.tables.some(o=>o.name===r.table))return;const t=e.tables.map(o=>o.name).join(", ");return r.logger.error(`unknown table "${r.table}" — schema defines: ${t||"(no tables)"}`),c(1)},B=async(r,e)=>{if(!(!(r.prod===!0||!p(r.url))||r.yes===!0)){if(!process.stdin.isTTY&&r.confirm===void 0)return r.logger.error("seed: refusing to insert into a non-local target without confirmation — re-run with --yes"),c(1);if(!await(r.confirm??F)(`This will insert ${String(e)} generated row(s) into ${r.url??"the production worker"}. Continue?`))return r.logger.info("seed: aborted"),c(1)}},G=async r=>{const e=r.cwd??process.cwd(),t=m(e,"lunora","schema.ts"),o=U(r,t);if(o!==void 0)return o;const l=new x({skipAddingFilesFromTsConfig:!0}),a=k(l,t),n=_(r,a);if(n!==void 0)return n;const d=C(a),g=R(d,{defaultCount:r.count??10,now:r.now,only:r.table===void 0?void 0:[r.table],seed:r.seed??0}),u=[];for(const{rows:f,table:h}of g)for(const b of f)u.push(JSON.stringify({doc:b,table:h},N));const i=u.length>0?`${u.join(`
|
|
2
2
|
`)}
|
|
3
|
-
`:"",s=u.length;if(r.dryRun===!0)return i.length>0&&process.stdout.write(i),r.logger.info(`generated ${String(s)} row(s) across ${String(g.length)} table(s) — dry run, nothing inserted`),{code:0,conflicts:0,generated:s,inserted:0,ndjson:i};if(r.reset===!0){const f=await T({cwd:e,logger:r.logger,yes:!0});if(f.code!==0)return{code:f.code,conflicts:0,generated:s,inserted:0,ndjson:i}}if(s===0)return r.logger.warn("no rows generated — nothing to insert"),{code:0,conflicts:0,generated:0,inserted:0,ndjson:i};const w=await B(r,s);return w!==void 0?w:P(i,s,e,r)},W=z(async({cwd:r,logger:e,options:t})=>({code:(await
|
|
3
|
+
`:"",s=u.length;if(r.dryRun===!0)return i.length>0&&process.stdout.write(i),r.logger.info(`generated ${String(s)} row(s) across ${String(g.length)} table(s) — dry run, nothing inserted`),{code:0,conflicts:0,generated:s,inserted:0,ndjson:i};if(r.reset===!0){const f=await T({cwd:e,logger:r.logger,yes:!0});if(f.code!==0)return{code:f.code,conflicts:0,generated:s,inserted:0,ndjson:i}}if(s===0)return r.logger.warn("no rows generated — nothing to insert"),{code:0,conflicts:0,generated:0,inserted:0,ndjson:i};const w=await B(r,s);return w!==void 0?w:P(i,s,e,r)},W=z(async({cwd:r,logger:e,options:t})=>({code:(await G({batchSize:t.batchSize,count:t.count,cwd:r,dryRun:t.dryRun===!0,logger:e,prod:t.prod===!0,reset:t.reset===!0,now:t.now,seed:t.seed,table:t.table,token:t.token,url:A({cwd:r,prod:t.prod===!0,url:t.url}),yes:t.yes===!0})).code}));export{W as execute,G as runSeedCommand};
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{writeFileSync as $,existsSync as v,readFileSync as S}from"node:fs";import{isAbsolute as w,join as b}from"node:path";import{byCodepoint as y,scoreAdvisor as x,parseAdvisorMap as j,compareToBaseline as R}from"@lunora/advisor";import{runCodegen as k}from"@lunora/codegen";import{i as A}from"../packem_shared/command-Bjv4VmYA.mjs";import{i as D,d as M,s as F,r as N}from"../packem_shared/output-format-D7cKB-O5.mjs";import{o as g}from"../packem_shared/cli-
|
|
1
|
+
import{writeFileSync as $,existsSync as v,readFileSync as S}from"node:fs";import{isAbsolute as w,join as b}from"node:path";import{byCodepoint as y,scoreAdvisor as x,parseAdvisorMap as j,compareToBaseline as R}from"@lunora/advisor";import{runCodegen as k}from"@lunora/codegen";import{i as A}from"../packem_shared/command-Bjv4VmYA.mjs";import{i as D,d as M,s as F,r as N}from"../packem_shared/output-format-D7cKB-O5.mjs";import{o as g}from"../packem_shared/cli-BxL0WCh4.mjs";const l={clean:"·",exempt:"–",failing:"✗",warned:"!"},u=(r,e)=>r.length>=e?r:r+" ".repeat(e-r.length),C=r=>`${r.id} (${r.visibility} ${r.kind})`,m=r=>{let e=0;for(const o of r)e=Math.max(e,o.id.length);return e},p=(r,e)=>` ${u(String(r.score),3)} ${l[r.coverage]} ${u(r.id,e)} ${r.visibility} ${r.kind}`,E=r=>{if(!r.comparable)return[` baseline not comparable (${r.reason}) — regenerate it; this run cannot verify anything`];if(!r.regressed)return[` no regression against baseline (score ${r.scoreDelta>=0?"+":""}${String(r.scoreDelta)})`];const e=[` REGRESSED against baseline (score ${r.scoreDelta>=0?"+":""}${String(r.scoreDelta)})`];for(const o of r.dropped)e.push(` ${o.id}: ${String(o.before)} → ${String(o.after)}`);for(const o of r.newFailing)e.push(` ${o}: now failing`);for(const o of r.worsened)e.push(` ${o}: more findings than the baseline`);return r.projectRegressed&&e.push(" project: new schema/config rules fired"),e},J=(r,e)=>{const o=r.procedures.filter(i=>i.coverage!=="clean"&&i.coverage!=="exempt"),n=m(o),t=[`advisor health ${String(r.score)}/100 — ${r.grade}`,` ${String(r.summary.clean)} clean · ${String(r.summary.warned)} warned · ${String(r.summary.failing)} failing · ${String(r.summary.exempt)} exempt (${String(r.summary.procedures)} procedures, ${String(r.summary.rulesFired)} rules fired)`];return r.project.checks.length>0&&t.push("",` project ${String(r.project.score)}/100 — ${r.project.checks.map(i=>i.name).join(", ")}`),o.length>0&&t.push("",...o.map(i=>p(i,n)),""," run with --all for every procedure, or --entry <file#export> for one"),e!==void 0&&t.push("",...E(e)),t.join(`
|
|
2
2
|
`)},O=r=>r.coverage==="exempt"?[` exempt: ${r.exemptReason===void 0||r.exemptReason===""?"no reason given":r.exemptReason}`]:r.checks.map(e=>{const o=e.occurrences>1?`, ×${String(e.occurrences)}`:"";return` ${e.name} (−${String(e.weight)}${o})`}),B=r=>{const e=new Map;for(const o of r){const n=e.get(o.file);n===void 0?e.set(o.file,[o]):n.push(o)}return[...e].toSorted(([o],[n])=>y(o,n))},P=r=>{const e=m(r.procedures),o=[`advisor health ${String(r.score)}/100 — ${r.grade}`,"",` legend: ${l.clean} clean ${l.warned} warned ${l.failing} failing ${l.exempt} exempt`];for(const[n,t]of B(r.procedures)){o.push("",` ${n}`);for(const i of t)o.push(p(i,e),...O(i))}return o.join(`
|
|
3
3
|
`)},T=(r,e)=>{const o=r.procedures.find(t=>t.id===e);if(o===void 0){const t=r.procedures.slice(0,10).map(i=>` ${i.id}`);return[`no procedure ${e} in the map. Known ids:`,...t,r.procedures.length>10?" …":""].filter(Boolean).join(`
|
|
4
4
|
`)}const n=[`${C(o)} — ${String(o.score)}/100, ${o.coverage}`,` weight in the global mean: ${String(o.weight)}`];if(o.checks.length===0)return n.push(""," no rule fired"),n.join(`
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{t as J}from"../packem_shared/cli-
|
|
1
|
+
import{t as J}from"../packem_shared/cli-BxL0WCh4.mjs";import{i as W}from"../packem_shared/command-Bjv4VmYA.mjs";import{existsSync as u,readFileSync as y,realpathSync as D,statSync as T,writeFileSync as z,chmodSync as H,renameSync as I,unlinkSync as K,mkdirSync as q}from"node:fs";import{homedir as w}from"node:os";import{findWranglerFile as G}from"@lunora/config/cloudflare";import{join as s,dirname as V,relative as Z}from"@visulima/path";import{P as B,M as Q}from"../packem_shared/detect-package-manager-B2eIuAiP.mjs";import{stringify as X}from"smol-toml";import{modify as x,applyEdits as C,parse as Y}from"jsonc-parser";import{readLiveDevServerState as b}from"@lunora/config";import{resolveAdminToken as oo}from"@lunora/config/studio-host";import{connectLocalStdio as to}from"@lunora/mcp";const m=o=>({args:[...o.args],command:o.command,...o.env===void 0?{}:{env:o.env}}),$=o=>o.transport==="http"?{type:"http",url:o.url}:m(o),eo=o=>o.transport==="http"?{httpUrl:o.url}:m(o),ro=o=>o.transport==="http"?{serverUrl:o.url}:m(o),no=o=>({args:["-y","mcp-remote",o],command:"npx"}),ao=o=>o.transport==="http"?no(o.url):m(o),io=o=>o.transport==="http"?{url:o.url}:m(o),lo=o=>o.transport==="http"?{enabled:!0,type:"remote",url:o.url}:{command:[o.command,...o.args],enabled:!0,type:"local",...o.env===void 0?{}:{environment:o.env}},so=o=>o.transport==="http"?{disabled:!1,type:"streamableHttp",url:o.url}:{disabled:!1,...m(o)},co=({home:o,platform:t})=>{if(t==="darwin")return{global:s(o,"Library","Application Support","Claude","claude_desktop_config.json")};if(t==="win32"){const e=process.env.APPDATA;return e===void 0||e===""?{}:{global:s(e,"Claude","claude_desktop_config.json")}}return t==="linux"?{global:s(o,".config","Claude","claude_desktop_config.json")}:{}},po=(o,t)=>X({mcp_servers:{[o]:t.transport==="http"?{url:t.url}:{args:[...t.args],command:t.command,...t.env===void 0?{}:{env:t.env}}}}),h=[{buildEntry:$,paths:({projectRoot:o})=>({project:s(o,".mcp.json")}),format:"json",id:"claude-code",key:"mcpServers",label:"Claude Code"},{buildEntry:$,paths:({home:o,projectRoot:t})=>({global:s(o,".cursor","mcp.json"),project:s(t,".cursor","mcp.json")}),format:"json",id:"cursor",key:"mcpServers",label:"Cursor"},{buildEntry:$,paths:({projectRoot:o})=>({project:s(o,".vscode","mcp.json")}),format:"json",id:"vscode",key:"servers",label:"VS Code (GitHub Copilot)"},{buildEntry:eo,paths:({home:o,projectRoot:t})=>({global:s(o,".gemini","settings.json"),project:s(t,".gemini","settings.json")}),format:"json",id:"gemini",key:"mcpServers",label:"Gemini CLI"},{buildEntry:ao,paths:co,format:"json",id:"claude-desktop",key:"mcpServers",label:"Claude Desktop"},{buildEntry:ro,paths:({home:o})=>({global:s(o,".codeium","windsurf","mcp_config.json")}),format:"json",id:"windsurf",key:"mcpServers",label:"Windsurf"},{buildEntry:lo,paths:({home:o,projectRoot:t})=>({global:s(o,".config","opencode","opencode.json"),project:s(t,"opencode.json")}),format:"json",id:"opencode",key:"mcp",label:"OpenCode"},{buildEntry:so,paths:({home:o})=>({global:s(o,".cline","mcp.json")}),format:"json",id:"cline",key:"mcpServers",label:"Cline"},{buildEntry:io,paths:({home:o})=>({global:s(o,".config","zed","settings.json")}),format:"json",id:"zed",key:"context_servers",label:"Zed"},{paths:({home:o,projectRoot:t})=>({global:s(o,".codex","config.toml"),project:s(t,".codex","config.toml")}),format:"manual",id:"codex",label:"Codex CLI",renderSnippet:po}],E=h.map(o=>o.id),uo=o=>h.find(t=>t.id===o.toLowerCase()),v=(o,t)=>{let e=o,r;try{e=D(o),r=T(e).mode}catch{}const n=`${e}.lunora-${Math.random().toString(36).slice(2,10)}.tmp`;try{z(n,t,"utf8"),r!==void 0&&H(n,r),I(n,e)}catch(a){try{K(n)}catch{}throw a}},R={formattingOptions:{insertSpaces:!0,tabSize:4}},k=o=>{const t=[],e=Y(o,t,{allowTrailingComma:!0});return{errors:t,value:e}},g=o=>typeof o=="object"&&o!==null&&!Array.isArray(o),j=(o,t,e)=>{if(!g(o))return;const r=o[t];return g(r)?r[e]:void 0},U=o=>{if(!u(o.path))return"absent";let t;try{t=y(o.path,"utf8")}catch{return"invalid"}if(t.trim().length===0)return"absent";const{errors:e,value:r}=k(t);return e.length>0||!g(r)?"invalid":j(r,o.key,o.name)===void 0?"absent":"present"},mo=o=>U(o)==="present",fo=o=>{const{entry:t,force:e=!1,key:r,name:n,path:a}=o;if(!u(a))return q(V(a),{recursive:!0}),v(a,`${JSON.stringify({[r]:{[n]:t}},void 0,4)}
|
|
2
2
|
`),{action:"created",path:a};const i=y(a,"utf8");if(i.trim().length===0)return v(a,`${JSON.stringify({[r]:{[n]:t}},void 0,4)}
|
|
3
3
|
`),{action:"created",path:a};const{errors:l,value:c}=k(i);if(l.length>0)return{action:"invalid",error:`parse error at offset ${String(l[0]?.offset??0)}`,path:a};if(!g(c))return{action:"invalid",error:"the file's root is not a JSON object",path:a};const f=c[r];if(f!==void 0&&!g(f))return{action:"invalid",error:`"${r}" is not an object`,path:a};if(j(c,r,n)!==void 0&&!e)return{action:"skipped",path:a};try{const d=x(i,[r,n],t,R);d.length>0&&v(a,C(i,d))}catch(d){return{action:"invalid",error:d instanceof Error?d.message:String(d),path:a}}return{action:"updated",path:a}},go=o=>{const{key:t,name:e,path:r}=o;if(!u(r))return{action:"absent",path:r};let n;try{n=y(r,"utf8")}catch(l){return{action:"invalid",error:l instanceof Error?l.message:String(l),path:r}}const{errors:a,value:i}=k(n);if(a.length>0)return{action:"invalid",error:`parse error at offset ${String(a[0]?.offset??0)}`,path:r};if(j(i,t,e)===void 0)return{action:"absent",path:r};try{const l=x(n,[t,e],void 0,R);l.length>0&&v(r,C(n,l))}catch(l){return{action:"invalid",error:l instanceof Error?l.message:String(l),path:r}}return{action:"removed",path:r}},ho=["global","project"],p=(o,t)=>{const e=Z(t,o);return e.length>0&&!e.startsWith("..")?e:o},vo=(o,t)=>{const e=o.paths(t);return ho.flatMap(r=>{const n=e[r];return n===void 0?[]:[{client:o,path:n,scope:r}]})},yo=(o,t,e,r)=>{const n=o.paths(t),a=e==="global"?"project":"global",i=n[e]??(r?void 0:n[a]);if(i!==void 0)return{client:o,path:i,scope:n[e]===void 0?a:e}},$o=o=>h.filter(t=>Object.values(t.paths(o)).some(e=>u(e))),N=(o,t,e,r)=>{if(o.length===0)return t();const n=[];for(const a of o){const i=uo(a);if(i===void 0){e.error(`mcp ${r}: unknown client "${a}". Known clients: ${E.join(", ")}.`);return}n.push(i)}return n},bo=o=>o.client.format==="json",wo="https://lunora.sh/mcp",_="lunora-docs",M="lunora",ko=o=>u(s(o,"lunora"))&&G(o)!==void 0,jo=o=>{const{args:t,command:e}=Q(o,"lunora",["mcp","serve"]);return{args:t,command:e,transport:"stdio"}},So=o=>({transport:"http",url:o}),Oo=o=>({home:o.home,platform:o.platform,projectRoot:o.cwd}),A=(o,t,e)=>yo(o,Oo(e),e.scope??t.preferredScope,e.scope!==void 0||!t.allowScopeFallback),xo=(o,t,e)=>{const r=A(o,t,e);if(r===void 0){e.logger.warn(`${o.label}: has no ${e.scope??t.preferredScope}-scoped config — skipped "${t.name}".`);return}const{path:n}=r,a=o.buildEntry(t.spec);if(e.print===!0){const c=p(n,e.cwd);return e.force!==!0&&mo({key:o.key,name:t.name,path:n})?(e.logger.info(`${o.label}: "${t.name}" already configured in ${c} — a real install would skip it (re-run with --force to replace).`),{action:"printed",path:n}):(e.logger.info(`${o.label} → ${c}
|
|
4
4
|
${JSON.stringify({[o.key]:{[t.name]:a}},void 0,4)}`),{action:"printed",path:n})}const i=fo({entry:a,force:e.force===!0,key:o.key,name:t.name,path:n}),l=p(n,e.cwd);return i.action==="invalid"?e.logger.error(`${o.label}: ${l} is not valid JSON (${i.error??"unknown error"}) — left untouched.`):i.action==="skipped"?e.logger.info(`${o.label}: "${t.name}" already configured in ${l} — re-run with --force to replace it.`):e.logger.success(`${o.label}: ${i.action==="created"?"created":"updated"} ${l} with "${t.name}".`),{action:i.action,path:n}},Co=(o,t,e)=>{const r=A(o,t,e)?.path;if(r===void 0){e.logger.warn(`${o.label}: no known config location on ${e.platform} — skipped.`);return}return e.logger.info(`${o.label}: add this to ${p(r,e.cwd)}
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{existsSync as l}from"node:fs";import{mkdir as m,readFile as f,writeFile as g}from"node:fs/promises";import{join as s}from"node:path";import{LunoraError as k}from"@lunora/errors";import{u as w}from"../packem_shared/admin-url-Ca-KI3d_.mjs";import{i as b}from"../packem_shared/command-Bjv4VmYA.mjs";import{s as y}from"../packem_shared/resolve-target-vxaXHmvg.mjs";import{runExportCommand as h,runImportCommand as $}from"../packem_shared/DEFAULT_IMPORT_BATCH_SIZE-
|
|
2
|
-
`,"utf8")},I=async(t,o)=>{await m(o,{recursive:!0});const r=(t.now??(()=>new Date))().toISOString(),e=`lunora-backup-${r.replaceAll(/[.:]/gu,"-")}.ndjson`,a=await h({cwd:t.cwd,fetchImpl:t.fetchImpl,logger:t.logger,out:s(o,e),prod:t.prod,tables:t.tables,token:t.token,url:t.url});if(a.code!==0)return{code:a.code};const i={bytes:a.bytes,createdAt:r,file:e,id:r,rows:a.rows,tables:t.tables},n=await u(o);return n.push(i),await x(o,n),t.logger.success(`backup created: ${e} (${a.rows.toString()} rows, ${a.bytes.toString()} bytes)`),{code:0,entry:i}},A=async(t,o)=>{const r=await u(o);if(r.length===0)return t.logger.info(`no backups found in ${o}`),{code:0};for(const e of r)t.logger.info(`${e.id} ${e.rows.toString()} rows ${e.bytes.toString()} bytes ${e.file}`);return{code:0}},E=async(t,o)=>{const{target:r}=t;if(r===void 0||r.length===0)return t.logger.error("restore requires a backup id or file path. Usage: lunora backup restore <id|file>"),{code:1};const e=(await u(o)).find(i=>i.id===r),a=e?s(o,e.file):r;return l(a)?{code:(await $({cwd:t.cwd,fetchImpl:t.fetchImpl,file:a,logger:t.logger,prod:t.prod,token:t.token,url:t.url,yes:t.yes})).code}:(t.logger.error(`backup not found: ${r}`),{code:1})},T=t=>{const o=t.token??process.env.LUNORA_ADMIN_TOKEN;if(!o){t.logger.error("admin token required — pass --token or set LUNORA_ADMIN_TOKEN");return}if(t.prod&&t.url===void 0){t.logger.error("--prod requires an explicit --url (refusing to target the implicit localhost worker)");return}if(t.restore===!0&&t.at===void 0&&t.bookmark===void 0){t.logger.error("pitr --restore requires --at <time> or --bookmark <bookmark>");return}if(t.restore===!0&&t.prod===!0&&t.yes!==!0){t.logger.error("pitr --restore --prod restores production data in place. Re-run with --yes to confirm.");return}const r=w(t.url,t.logger,t.cwd);if(r===void 0)return;const e=t.pitrFetch??globalThis.fetch;if(typeof e!="function")throw new TypeError("no fetch implementation available — pass pitrFetch or run on Node >= 18");return{fetchImpl:e,requestUrl:`${r}${S}`,token:o}},q=(t,o)=>{const r={};return t.at!==void 0&&(r.time=t.at),o&&t.bookmark!==void 0&&(r.bookmark=t.bookmark),o&&t.restart===!0&&(r.restart=!0),r},J=async t=>{const o=T(t);if(o===void 0)return{code:1};const r=t.restore===!0,e=r?_:N,a=q(t,r),i=r?"restore":"bookmark";t.logger.info(`POST ${o.requestUrl} -> pitr ${i}${t.shard===void 0?"":` (shard "${t.shard}")`}`);const n=await o.fetchImpl(o.requestUrl,{body:JSON.stringify({args:a,functionPath:e,shardKey:t.shard}),headers:{authorization:`Bearer ${o.token}`,"content-type":"application/json"},method:"POST"}),d=await n.text();let c;try{c=JSON.parse(d)}catch{c=d}return t.logger.info(JSON.stringify(c,void 0,2)),{code:n.ok?0:1}},
|
|
1
|
+
import{existsSync as l}from"node:fs";import{mkdir as m,readFile as f,writeFile as g}from"node:fs/promises";import{join as s}from"node:path";import{LunoraError as k}from"@lunora/errors";import{u as w}from"../packem_shared/admin-url-Ca-KI3d_.mjs";import{i as b}from"../packem_shared/command-Bjv4VmYA.mjs";import{s as y}from"../packem_shared/resolve-target-vxaXHmvg.mjs";import{runExportCommand as h,runImportCommand as $}from"../packem_shared/DEFAULT_IMPORT_BATCH_SIZE-CEOt386P.mjs";const v=".lunora-backups",p="manifest.json",S="/_lunora/admin/pitr",N="__lunora_admin__:getPitrBookmark",_="__lunora_admin__:pitrRestore",O=t=>typeof t=="object"&&t!==null&&typeof t.id=="string"&&typeof t.file=="string",u=async t=>{const o=s(t,p);if(!l(o))return[];let r;try{r=JSON.parse(await f(o,"utf8"))}catch(e){const a=e instanceof Error?e.message:String(e);throw new k("INTERNAL",`backup: ${o} exists but is not valid JSON (${a}) — refusing to overwrite it; fix or remove it manually`,{cause:e})}if(!Array.isArray(r))throw new TypeError(`backup: ${o} exists but is not a JSON array — refusing to overwrite it; fix or remove it manually`);return r.filter(O)},x=async(t,o)=>{await g(s(t,p),`${JSON.stringify(o,void 0,2)}
|
|
2
|
+
`,"utf8")},I=async(t,o)=>{await m(o,{recursive:!0});const r=(t.now??(()=>new Date))().toISOString(),e=`lunora-backup-${r.replaceAll(/[.:]/gu,"-")}.ndjson`,a=await h({cwd:t.cwd,fetchImpl:t.fetchImpl,logger:t.logger,out:s(o,e),prod:t.prod,tables:t.tables,token:t.token,url:t.url});if(a.code!==0)return{code:a.code};const i={bytes:a.bytes,createdAt:r,file:e,id:r,rows:a.rows,tables:t.tables},n=await u(o);return n.push(i),await x(o,n),t.logger.success(`backup created: ${e} (${a.rows.toString()} rows, ${a.bytes.toString()} bytes)`),{code:0,entry:i}},A=async(t,o)=>{const r=await u(o);if(r.length===0)return t.logger.info(`no backups found in ${o}`),{code:0};for(const e of r)t.logger.info(`${e.id} ${e.rows.toString()} rows ${e.bytes.toString()} bytes ${e.file}`);return{code:0}},E=async(t,o)=>{const{target:r}=t;if(r===void 0||r.length===0)return t.logger.error("restore requires a backup id or file path. Usage: lunora backup restore <id|file>"),{code:1};const e=(await u(o)).find(i=>i.id===r),a=e?s(o,e.file):r;return l(a)?{code:(await $({cwd:t.cwd,fetchImpl:t.fetchImpl,file:a,logger:t.logger,prod:t.prod,token:t.token,url:t.url,yes:t.yes})).code}:(t.logger.error(`backup not found: ${r}`),{code:1})},T=t=>{const o=t.token??process.env.LUNORA_ADMIN_TOKEN;if(!o){t.logger.error("admin token required — pass --token or set LUNORA_ADMIN_TOKEN");return}if(t.prod&&t.url===void 0){t.logger.error("--prod requires an explicit --url (refusing to target the implicit localhost worker)");return}if(t.restore===!0&&t.at===void 0&&t.bookmark===void 0){t.logger.error("pitr --restore requires --at <time> or --bookmark <bookmark>");return}if(t.restore===!0&&t.prod===!0&&t.yes!==!0){t.logger.error("pitr --restore --prod restores production data in place. Re-run with --yes to confirm.");return}const r=w(t.url,t.logger,t.cwd);if(r===void 0)return;const e=t.pitrFetch??globalThis.fetch;if(typeof e!="function")throw new TypeError("no fetch implementation available — pass pitrFetch or run on Node >= 18");return{fetchImpl:e,requestUrl:`${r}${S}`,token:o}},q=(t,o)=>{const r={};return t.at!==void 0&&(r.time=t.at),o&&t.bookmark!==void 0&&(r.bookmark=t.bookmark),o&&t.restart===!0&&(r.restart=!0),r},J=async t=>{const o=T(t);if(o===void 0)return{code:1};const r=t.restore===!0,e=r?_:N,a=q(t,r),i=r?"restore":"bookmark";t.logger.info(`POST ${o.requestUrl} -> pitr ${i}${t.shard===void 0?"":` (shard "${t.shard}")`}`);const n=await o.fetchImpl(o.requestUrl,{body:JSON.stringify({args:a,functionPath:e,shardKey:t.shard}),headers:{authorization:`Bearer ${o.token}`,"content-type":"application/json"},method:"POST"}),d=await n.text();let c;try{c=JSON.parse(d)}catch{c=d}return t.logger.info(JSON.stringify(c,void 0,2)),{code:n.ok?0:1}},R=async t=>{const o=t.cwd??process.cwd(),r=s(o,t.dir??v);try{return t.subcommand==="create"?await I(t,r):t.subcommand==="list"?await A(t,r):t.subcommand==="pitr"?await J(t):await E(t,r)}catch(e){return t.logger.error(e instanceof Error?e.message:String(e)),{code:1}}},U=t=>t==="create"||t==="list"||t==="pitr"||t==="restore",M=b(({argument:t,cwd:o,logger:r,options:e})=>{const a=t[0];return U(a)?R({at:e.at,bookmark:e.bookmark,cwd:o,dir:e.dir,logger:r,prod:e.prod===!0,restart:e.restart===!0,restore:e.restore===!0,shard:e.shard,subcommand:a,tables:e.tables,target:t[1],token:e.token,url:y({cwd:o,prod:e.prod===!0,url:e.url}),yes:e.yes===!0}):(r.error(`backup: unknown subcommand "${a??""}" — expected create | list | restore | pitr`),{code:1})});export{M as execute,R as runBackupCommand};
|
|
@@ -1,7 +1,7 @@
|
|
|
1
|
-
import{spawnSync as
|
|
2
|
-
`)),
|
|
3
|
-
`)+1)}finally{Y(
|
|
4
|
-
`);return
|
|
1
|
+
import{spawnSync as I,spawn as J}from"node:child_process";import{existsSync as N,watch as me,readFileSync as K,statSync as fe,openSync as z,readSync as ve,closeSync as Y,mkdirSync as we}from"node:fs";import{join as k,dirname as he}from"node:path";import{runCodegen as X}from"@lunora/codegen";import{detectAgentRules as Z,claimDevServerState as Q,clearDevServerState as f,readDevServerState as R,readLiveDevServerState as y,detectFramework as ee,readProjectDependencyNames as Se,DEV_HANDOFF_ENV as h,isRecordedProcessCurrent as ke,DEV_LOG_FILE as ye,DEV_LOG_FILE_ENV as re,DEV_DAEMON_ENV as T,updateDevServerState as oe,detectAiAgent as be,readProjectRemotePreference as $e,resolveTargetOrThrow as Ee,inferLunoraBindings as Ie,packageNamesFromBindings as Ne,ensureDevVarsExample as Re,ensureDevVariables as Te,isInteractive as Le,DEV_VARS_FILE as x,DEV_VARS_EXAMPLE_FILE as Oe,fillDevSecrets as Pe,claimAgentRulesHint as De,AGENT_RULES_HINT as xe,resolveDeployDriver as Ce,resolveProjectTarget as _e,discoverContainerInfo as Ae,streamContainerLogs as je,formatLunoraEvent as Me}from"@lunora/config";import{resolveRemoteEnabled as Fe,findWranglerFile as te,readWranglerJsonc as ne,materializeRemoteWranglerConfig as Ge}from"@lunora/config/cloudflare";import{r as He}from"../packem_shared/api-spec-BENwiyUa.mjs";import{l as Ue}from"../packem_shared/codegen-error-DJN6pTH5.mjs";import{a as Ve}from"../packem_shared/platform-diagnostics-C4TFj5Pu.mjs";import{i as We}from"../packem_shared/command-Bjv4VmYA.mjs";import{P as se,M as $,k as qe}from"../packem_shared/detect-package-manager-B2eIuAiP.mjs";import{createServer as Be,connect as Je}from"node:net";import{forceJsonLogging as Ke}from"../packem_shared/createLogger--C3x1FNE.mjs";import{networkInterfaces as ze}from"node:os";import{spawnShellCompat as ie}from"../packem_shared/createRecordingSpawner-ByIqBepG.mjs";import{createServer as Ye,request as Xe}from"node:http";import{loadStudioAssets as C,studioAssetsStamp as _,renderStudioHtml as Ze,resolveAdminToken as Qe,SCHEMA_EDIT_ENDPOINT as er,POLICY_SCAFFOLD_ENDPOINT as rr,SEED_ENDPOINT as or,serveJsonHandler as tr,isStandaloneModulePath as nr,readStandaloneAsset as sr,assetContentType as ir,handleSchemaEditRequest as ar,handlePolicyScaffoldRequest as dr,handleSeedRequest as cr}from"@lunora/config/studio-host";import{$ as lr}from"../packem_shared/tui-prompts-CCt3jm1k.mjs";import{d as v}from"../packem_shared/output-format-D7cKB-O5.mjs";const ur=100,pr=/[/\\]/u,A=(e,r,t)=>{const{apiSpec:o,logger:n,projectRoot:s,target:a}=e;try{const i=X({apiSpec:o,lunoraDirectory:r,projectRoot:s,target:a});n.success(`codegen: wrote ${r}/_generated (${t})`),Ve(i.platformDiagnostics,n)}catch(i){n.error(Ue(i,t))}},gr=e=>{const r=e.lunoraDirectory??"lunora",t=k(e.projectRoot,r),o=e.debounceMs??ur;A(e,r,"startup");let n,s;if(!N(t))return e.logger.warn(`codegen watch unavailable (no such directory: ${t}) — schema edits will NOT auto-regenerate. Run \`lunora codegen\` manually after each edit.`),{close:()=>{},watchAvailable:!1};try{s=me(t,{recursive:!0},(i,c)=>{typeof c=="string"&&c.split(pr).includes("_generated")||(n&&clearTimeout(n),n=setTimeout(()=>{A(e,r,`change: ${c??"?"}`)},o))})}catch(i){return e.logger.warn(`codegen watch unavailable (${i instanceof Error?i.message:String(i)}) — schema edits will NOT auto-regenerate. Run \`lunora codegen\` manually after each edit.`),{close:()=>{},watchAvailable:!1}}const a=s;return{close:()=>{n&&clearTimeout(n),a.close()},watchAvailable:!0}},mr=64,ae="127.0.0.1",fr=65535,vr=(e,r=ae)=>new Promise(t=>{const o=Be();o.once("error",()=>{t(!1)}),o.once("listening",()=>{o.close(()=>{t(!0)})}),o.listen(e,r)}),wr=async(e,r=ae,t=mr)=>{for(let o=e;o<e+t&&o<=fr;o+=1)if(await vr(o,r))return o;return e},j=(e=ze)=>Object.values(e()).some(r=>r?.some(t=>t.internal&&t.address==="::1")),M="/_lunora",F=e=>{const r=e.indexOf("?");return r===-1?e:e.slice(0,r)},hr=new Set(["127.0.0.1","::1","[::1]","localhost"]),G=e=>{if(e===void 0||e==="")return!1;const r=e.startsWith("[")?e.slice(0,e.indexOf("]")+1):e.split(":")[0]??e;return hr.has(r)},Sr=(e,r,t)=>{const o=Xe({headers:{...e.headers,host:t.host},hostname:t.hostname,method:e.method,path:e.url,port:t.port},n=>{r.writeHead(n.statusCode??502,n.headers),n.pipe(r)});o.on("error",n=>{r.statusCode=502,r.end(`lunora dev: worker unreachable (${n.message})`)}),e.pipe(o)},kr=5e3,yr=(e,r,t,o)=>{const n=Je({host:o.hostname,port:Number(o.port)},()=>{n.setTimeout(0);const s=[`${e.method??"GET"} ${e.url??"/"} HTTP/1.1`];for(const[a,i]of Object.entries(e.headers))if(a!=="host")for(const c of Array.isArray(i)?i:[i])c!==void 0&&s.push(`${a}: ${c}`);s.push(`host: ${o.host}`,"",""),n.write(s.join(`\r
|
|
2
|
+
`)),t.length>0&&n.write(t),n.pipe(r),r.pipe(n)});n.setTimeout(kr,()=>n.destroy()),n.on("error",()=>r.destroy()),r.on("error",()=>n.destroy())},br=async e=>{const r=e.host??"127.0.0.1",t=r==="127.0.0.1"||r==="localhost"||r==="::1",o=new URL(e.workerOrigin);let n=C(e.logger,import.meta.url),s=_(import.meta.url);const a=Ze({adminToken:t?Qe(e.cwd):void 0,basePath:"/",dataEditable:t,rulesInstalled:Z(e.cwd).installed,runAsIdentity:t,schemaEditable:t,scriptSrc:"/studio.js",styleHref:"/styles.css"}),i=(l,d,g)=>{l.statusCode=200,l.setHeader("Content-Type",g),l.end(d)},c=(l,d,g,b)=>{if(t){tr(l,d,g,e.cwd);return}d.statusCode=403,d.setHeader("Content-Type","text/plain"),d.end(b)},u=(l,d)=>{const g=l==="/styles.css",b=nr(l);if(!g&&!b)return!1;const O=_(import.meta.url);if(O!==s&&(n=C(e.logger,import.meta.url),s=O),n===void 0)return d.statusCode=501,d.setHeader("Content-Type","text/plain"),d.end("Lunora studio assets not found — install and build @lunora/studio."),!0;if(g)return i(d,n.styles,"text/css; charset=utf-8"),!0;const P=l.slice(l.lastIndexOf("/")+1),D=sr(P,import.meta.url);return D===void 0?(d.statusCode=404,d.setHeader("Content-Type","text/plain"),d.end("Not found"),!0):(i(d,D,ir(P)),!0)},p=Buffer.from(a),m=Ye((l,d)=>{const g=F(l.url??"/");if(t&&!G(l.headers.host)){d.statusCode=403,d.setHeader("Content-Type","text/plain"),d.end("Lunora studio: refusing a request whose Host is not a loopback literal (DNS-rebinding guard).");return}if(g.startsWith(M)){if(!t){d.statusCode=403,d.setHeader("Content-Type","text/plain"),d.end("Lunora studio: the worker admin proxy is only available on a loopback bind.");return}Sr(l,d,o);return}if(g===er){c(l,d,ar,"Lunora schema editing is only available on loopback hosts in dev.");return}if(g===rr){c(l,d,dr,"Lunora policy scaffolding is only available on loopback hosts in dev.");return}if(g===or){c(l,d,cr,"Lunora data seeding is only available on loopback hosts in dev.");return}u(g,d)||i(d,p,"text/html; charset=utf-8")});return m.on("upgrade",(l,d,g)=>{if(!t||!G(l.headers.host)){d.destroy();return}F(l.url??"").startsWith(M)?yr(l,d,g,o):d.destroy()}),await new Promise((l,d)=>{m.once("error",g=>{g.code==="EADDRINUSE"?d(new Error(`studio port ${String(e.port)} is already in use — pass a different port with --port, or stop the process using it`,{cause:g})):d(g)}),m.listen(e.port,r,()=>{l()})}),{close:()=>new Promise(l=>{m.close(()=>{l()})}),url:`http://${r==="0.0.0.0"||r==="::"?"localhost":r}:${String(e.port)}`}},$r=12e4,de=250,Er=1e4,Ir=100,Nr=40,w=256*1024,Rr="LUNORA_DEV_READY_TIMEOUT_MS",Tr=new Set(["nuxt","sveltekit"]),L=e=>Tr.has(ee(e).framework)?"framework-worker":Se(e).has("@lunora/vite")?"vite":"wrangler",ce=e=>{const r=se(e);let t;try{const o=K(k(e,"package.json"),"utf8");t=JSON.parse(o).scripts?.dev}catch{}if(t===void 0||t.trim()===""||t.includes("lunora")){const o=$(r,"vite",["dev"]);return{args:o.args,command:o.command}}return{args:["run","dev"],command:r}},E=e=>new Promise(r=>{setTimeout(r,e)}),Lr=async e=>{try{return await fetch(new URL("/_lunora/status",e),{signal:AbortSignal.timeout(1e3)}),!0}catch{return!1}},Or=e=>{we(he(e.logPath),{recursive:!0});const r=z(e.logPath,"w",384);let t;const o=ie(e.command,e.args);try{t=J(o.command,o.args,{cwd:e.cwd,detached:!0,env:e.env,shell:o.shell,stdio:["ignore",r,r],windowsHide:!0})}finally{Y(r)}return t.unref(),{exited:new Promise(n=>{t.on("error",()=>{n(1)}),t.on("exit",(s,a)=>{n(s??(a?1:0))})}),pid:t.pid}},Pr=e=>{try{const{size:r}=fe(e);if(r<=w)return K(e,"utf8");const t=z(e,"r");try{const o=Buffer.alloc(w),n=ve(t,o,0,w,r-w),s=o.toString("utf8",0,n);return s.slice(s.indexOf(`
|
|
3
|
+
`)+1)}finally{Y(t)}}catch{return}},le=(e,r)=>{const t=Pr(e);if(t===void 0)return[];const o=t.split(`
|
|
4
|
+
`);return o.at(-1)===""&&o.pop(),r>0?o.slice(-r):o},ue=(e,r)=>r?.logFile??k(e,ye),pe=e=>{e.info(" Stop: lunora dev stop"),e.info(" Status: lunora dev status"),e.info(" Logs: lunora dev logs")},S=(e,r)=>{e.warn(`Dev server already running at ${r.url} (pid ${String(r.pid)})`),pe(e)},Dr=(e,r)=>{e.success(`Dev server running at ${r.url} (pid ${String(r.pid)})`),r.studioUrl!==void 0&&e.info(` Studio: ${r.studioUrl}`),pe(e)},xr=async e=>{const{child:r,cwd:t,deadline:o,pollIntervalMs:n,probe:s}=e,a=r.exited.then(i=>({exitCode:i}));for(;Date.now()<o;){const i=y(t);if(i!==void 0&&i.pid!==process.pid&&await s(i.url))return{state:i,status:"ready"};const c=await Promise.race([a,E(n)]);if(c!==void 0)return{...c,status:"exited"}}return{status:"timeout"}},Cr=async e=>{const{cwd:r,logger:t}=e,o=ue(r,void 0),n=Number(process.env[Rr]??""),s=e.readyTimeoutMs??(Number.isFinite(n)&&n>0?n:$r),a=(e.spawnDetached??Or)({args:e.command.args,command:e.command.command,cwd:r,env:{...process.env,...e.env,[T]:"1",[re]:o,...process.env.FORCE_COLOR===void 0?{NO_COLOR:"1"}:{},...e.json?{LUNORA_LOG_JSON:"1"}:{}},logPath:o}),i=await xr({child:a,cwd:r,deadline:Date.now()+s,pollIntervalMs:e.pollIntervalMs??de,probe:e.probe??Lr});if(i.status==="ready")return Dr(t,i.state),{code:0};if(i.status==="exited"){t.error(`dev server exited before becoming ready (exit code ${String(i.exitCode)}). Last output:`);for(const u of le(o,Nr))t.error(` ${u}`);return f(r,a.pid??process.pid),{code:i.exitCode===0?1:i.exitCode}}a.pid!==void 0&&R(r)?.pid===process.pid&&oe(r,{logFile:o,pid:a.pid});const c=a.pid===void 0?"":` (pid ${String(a.pid)})`;return t.warn(`dev server did not confirm ready within ${String(Math.round(s/1e3))}s — it may still be compiling${c}. Check \`lunora dev status\` and \`lunora dev logs\`; \`lunora dev stop\` shuts it down.`),{code:1}},_r=(e,r)=>{const t=["dev"];return e.apiSpec!==void 0&&t.push("--api-spec",e.apiSpec),e.port!==void 0&&t.push("--port",String(e.port)),e.workerPort!==void 0&&t.push("--worker-port",String(e.workerPort)),e.codegen===!1&&t.push("--no-codegen"),e.studio===!1&&t.push("--no-studio"),e.worker===!1&&t.push("--no-worker"),e.target!==void 0&&t.push("--target",e.target),r&&t.push("--remote"),t},Ar=async e=>{const{cwd:r,jsonLogs:t,logger:o,options:n,remote:s}=e,a=e.run??Cr,i=L(r),c=i==="wrangler"?`http://localhost:${String(n.workerPort??8787)}`:"http://localhost:5173",u=Q(r,{background:!0,mode:"cli",pid:process.pid,startedAt:new Date().toISOString(),url:c});if(!u.ok)return u.existing!==void 0&&S(o,u.existing),{code:0};const p={[h]:String(process.pid)};try{return i==="vite"?await a({command:ce(r),cwd:r,env:{...s?{LUNORA_REMOTE:"1"}:{},...p},json:t,logger:o}):await a({command:{args:[process.argv[1]??"lunora",..._r(n,s)],command:process.execPath},cwd:r,env:p,json:t,logger:o})}finally{f(r,process.pid)}},jr=e=>{try{const r=I("ps",["-o","pgid=","-p",String(e)],{encoding:"utf8"}),t=Number.parseInt(r.stdout.trim(),10);return Number.isInteger(t)&&t>0?t:void 0}catch{return}},Mr=(e,r,t=process.platform,o=I)=>{if(t==="win32"){try{o("taskkill",["/pid",String(e.pid),"/T","/F"],{stdio:"ignore"})}catch{}return}if(e.background===!0)try{r(-(jr(e.pid)??e.pid),"SIGKILL");return}catch{}try{r(e.pid,"SIGKILL")}catch{}},Fr=(e,r)=>(r.json?v({pid:e.pid,stopped:!1}):r.logger.error(`dev server (pid ${String(e.pid)}) survived the force-kill — record kept; retry \`lunora dev stop\` or kill the process manually.`),{code:1}),Gr=async e=>{const{cwd:r,logger:t}=e,o=R(r),n=e.alive??(m=>m===o?.pid&&ke(o)),s=e.signal??((m,l)=>{process.kill(m,l)}),a=e.pollIntervalMs??de,i=e.stopGraceMs??Er,c=e.platform??process.platform,u=e.spawnSyncImpl??I;if(o===void 0||!n(o.pid))return o!==void 0&&f(r,o.pid),e.json?v({running:!1,stopped:!1}):t.info("No dev server running."),{code:0};try{s(o.pid,"SIGTERM")}catch{}const p=Date.now()+i;for(;n(o.pid)&&Date.now()<p;)await E(a);return n(o.pid)&&(Mr(o,s,c,u),await E(a),n(o.pid))?Fr(o,e):(f(r,o.pid),e.json?v({pid:o.pid,stopped:!0}):t.success(`Stopped dev server (pid ${String(o.pid)}).`),{code:0})},Hr=e=>{const{cwd:r,logger:t}=e,o=y(r);if(o===void 0)return e.json?v({running:!1}):t.info("No dev server running."),{code:0};const n=e.now??Date.now,s=o.startedAt===void 0?Number.NaN:Date.parse(o.startedAt),a=Number.isFinite(s)?Math.max(0,Math.round((n()-s)/1e3)):void 0;if(e.json)return v({background:o.background===!0,logFile:o.logFile,mode:o.mode,pid:o.pid,running:!0,startedAt:o.startedAt,studioUrl:o.studioUrl,uptimeSeconds:a,url:o.url}),{code:0};const i=[`pid ${String(o.pid)}`,...a===void 0?[]:[`uptime ${String(a)}s`],o.background===!0?"background":"foreground"];return t.success(`Dev server running at ${o.url} (${i.join(", ")})`),o.studioUrl!==void 0&&t.info(` Studio: ${o.studioUrl}`),o.logFile!==void 0&&t.info(` Logs: lunora dev logs (${o.logFile})`),{code:0}},Ur=e=>{const{cwd:r,logger:t}=e,o=R(r),n=ue(r,o);if(!N(n))return t.info("No dev server logs found — output is captured when the server runs in background mode (`lunora dev --background`)."),{code:0};const s=le(n,e.lines??Ir);return s.length>0&&process.stdout.write(`${s.join(`
|
|
5
5
|
`)}
|
|
6
|
-
`),{code:0}},Vr=e=>{const{cwd:r,json:
|
|
7
|
-
`);
|
|
6
|
+
`),{code:0}},Vr=e=>{const{cwd:r,json:t,lines:o,logger:n,subcommand:s}=e;if(s==="stop")return Gr({cwd:r,json:t,logger:n});if(s==="status")return Hr({cwd:r,json:t,logger:n});if(s==="logs")return Ur({cwd:r,lines:o,logger:n});if(s!==void 0)return n.error(`dev: unknown subcommand "${s}" — expected stop | status | logs (or no subcommand to start the dev server)`),{code:1}},H="wrangler.dev.jsonc",U=6173,ge=8787,V=5173,Wr=5e3,qr=(e,r)=>{const t=()=>{};if(!e.remote)return{args:[],plan:{bindings:[],cleanup:t,enabled:!1}};const o=(e.materializeRemote??Ge)({enabled:!0,projectRoot:r}),n=o.remoteBindings.map(a=>`${a.binding} (${a.kind})`),{cleanup:s}=o;return o.configPath===void 0?{args:[],plan:{bindings:n,cleanup:s,enabled:!0,reason:o.reason}}:{args:["--config",o.configPath],plan:{bindings:n,cleanup:s,enabled:!0}}},W=e=>ne(e).parsed?.dev?.ip,q=(e,r,t)=>{if(t!==void 0){const n=k(e,t);if(N(n)&&W(n)!==void 0)return[]}const o=te(e);return o!==void 0&&W(o)!==void 0?[]:r()?[]:["--ip","127.0.0.1"]},Br=async(e,r)=>{if(e.workerPort!==void 0)return e.workerPort;const t=te(r);if(t!==void 0){const{parsed:o}=ne(t);if(typeof o?.dev?.port=="number")return o.dev.port}return(e.findFreePort??wr)(ge)},Jr=e=>{const r=e.cwd??process.cwd(),t=se(r),o=e.flavor??L(r);if(o==="vite"||o==="framework-worker"){const p=ce(r);let m;if(o==="framework-worker"){const l=q(r,e.hasIpv6Loopback??j,H),d=Ce(_e(r)).toolchain?.dev({configPath:H,extraArgs:[...l,"--var","WORKER_ENV:development"]}),g=$(t,d?.tool??"wrangler",d?.args??[]);m={args:g.args,command:g.command,cwd:r,tag:"worker"}}return e.worker===!1&&e.logger.warn(`--no-worker does not apply to the ${o} flavor: Vite owns the worker, codegen and studio in-process. Run your framework's dev script instead.`),{codegenEnabled:!1,flavor:o,ipv4LoopbackForced:!1,remote:{bindings:[],cleanup:()=>{},enabled:e.remote===!0},...m?{sidecar:m}:{},studioEnabled:!1,studioPort:e.port??U,workerEnabled:!0,workerOrigin:`http://localhost:${String(V)}`,workerPort:V,wrangler:{args:p.args,command:p.command,cwd:r,...e.remote===!0?{env:{LUNORA_REMOTE:"1"}}:{},tag:"vite"}}}const n=ee(r),s=n.framework==="none"?void 0:`this project uses ${n.framework} — the worker runs inside Vite there. run \`${qe(t,"dev")}\` for the full app (frontend + HMR); \`lunora dev\` starts only the worker.`,a=e.workerPort??ge,i=qr(e,r),c=q(r,e.hasIpv6Loopback??j),u=$(t,"wrangler",["dev","--port",String(a),...c,"--var","WORKER_ENV:development",...i.args]);return{codegenEnabled:e.codegen!==!1,flavor:o,frameworkHint:s,ipv4LoopbackForced:c.length>0,remote:i.plan,studioEnabled:e.studio!==!1,studioPort:e.port??U,workerEnabled:e.worker!==!1,workerOrigin:`http://localhost:${String(a)}`,workerPort:a,wrangler:{args:u.args,command:u.command,cwd:r,tag:"wrangler"}}},B=(e,r,t,o)=>{if(e.length===0)return;const n=Me(e);if(n){o[n.level](`[lunora] ${n.text}`);return}const s=`[${r}] ${e}`;t==="stderr"?o.warn(s):o.info(s)},Kr=(e,r,t)=>{const o=(n,s)=>{if(!n)return;let a="";n.on("data",i=>{a+=i.toString("utf8");const c=a.split(`
|
|
7
|
+
`);a=c.pop()??"";for(const u of c)B(u.trimEnd(),r,s,t)}),n.on("end",()=>{B(a.trimEnd(),r,s,t),a=""})};o(e.stdout,"stdout"),o(e.stderr,"stderr")},zr=(e,r)=>{const t=ie(e.command,e.args),o=J(t.command,t.args,{cwd:e.cwd??process.cwd(),env:e.env?{...process.env,...e.env}:process.env,shell:t.shell,stdio:["inherit","pipe","pipe"]});return Kr(o,e.tag,r),{exited:new Promise(n=>{o.on("error",s=>{r.error(`[${e.tag}] failed to start: ${s.message}`),n(1)}),o.on("exit",s=>{n(s??0)})}),kill:n=>{try{o.kill(n)}catch{}}}},Yr=(e,r,t)=>{e.info(""),e.success("Lunora dev"),e.info(` ➜ Worker: ${r.workerOrigin}`),t!==void 0&&e.info(` ➜ Studio: ${t}`),r.codegenEnabled&&e.info(" ➜ Codegen: watching lunora/"),r.remote.enabled&&(r.remote.bindings.length>0?e.info(` ➜ Remote: ${r.remote.bindings.join(", ")} → deployed worker`):e.warn(` ➜ Remote: requested but inactive (${r.remote.reason??"no eligible bindings"}) — running fully local`)),e.info("")},Xr=(e,r)=>{Z(r).installed||!De()||(e.info(` ⓘ ${xe}`),e.info(""))},Zr=(e,r)=>{if(process.env.LUNORA_CONTAINER_LOGS==="0")return;const t=Ae(e,"lunora").containers.map(o=>({className:o.className,exportName:o.exportName}));if(t.length!==0)return je({containers:t,onLine:o=>{const n=`[container:${o.name}] ${o.text}`;o.level==="error"?r.warn(n):r.info(n)},onUnavailable:o=>{r.warn(`[container] Docker engine unreachable — container logs unavailable (${o})`)}})},Qr=async e=>{e.codegen?.close(),e.containerLogs?.close(),await e.studio?.close().catch(()=>{});try{e.remoteCleanup?.()}catch{}},eo=async(e,r)=>{try{const t=await Ie({projectRoot:r}),o=Ne(t),n=(e.ensureExample??Re)(r,o);n.length>0&&e.logger.info(`Updated .dev.vars.example with secrets for: ${o.join(", ")} (${n.join(", ")})`)}catch{}(await(e.ensureEnv??Te)({confirm:lr(),cwd:r,info:t=>{e.logger.info(t)}})).status==="declined"&&!Le()&&e.logger.info(`hint: ${x} was not scaffolded (non-interactive run). Copy ${Oe} → ${x} and fill in secrets, or run \`lunora dev\` in an interactive terminal to scaffold automatically.`);try{(e.fillSecrets??Pe)({cwd:r,info:t=>{e.logger.info(t)}})}catch{}},ro=(e,r,t,o)=>{if(e.flavor!=="wrangler")return;o!==void 0&&oe(r,{studioUrl:o});let n;try{n=Zr(r,t)}catch{}return Yr(t,e,o),n},oo=(e,r)=>{const t=Number(process.env[h]),o=Q(r,{background:process.env[T]==="1",logFile:process.env[re],mode:"cli",pid:process.pid,startedAt:new Date().toISOString(),url:e.workerOrigin},Number.isInteger(t)&&t>0?{supersedePid:t}:void 0);return o.ok?void 0:o.existing},to=async e=>{const r=e.cwd??process.cwd(),t=e.flavor??L(r),o=t==="wrangler"?await Br(e,r):e.workerPort;return Jr({...e,cwd:r,flavor:t,workerPort:o})},no=async e=>await new Promise(r=>{const t={},o=n=>{e.info(`received ${n} — shutting down`),t.sigint&&process.off("SIGINT",t.sigint),t.sigterm&&process.off("SIGTERM",t.sigterm),r(0)};t.sigint=()=>{o("SIGINT")},t.sigterm=()=>{o("SIGTERM")},process.on("SIGINT",t.sigint),process.on("SIGTERM",t.sigterm)}),so=async(e,r,t)=>{let o=0,n;const s=p=>{e.kill(p),r?.kill(p)},a=()=>{o+=1,o===1?(t.info("received SIGINT — shutting down (press Ctrl-C again to force-kill)"),s("SIGTERM"),n=setTimeout(()=>{s("SIGKILL")},Wr),n.unref()):s("SIGKILL")},i=()=>{s("SIGTERM")};process.on("SIGINT",a),process.on("SIGTERM",i);const c=[e.exited.then(p=>({code:p,who:"worker"}))];r!==void 0&&c.push(r.exited.then(p=>({code:p,who:"sidecar"})));const u=await Promise.race(c);return r!==void 0&&(u.who==="sidecar"?(t.warn("[worker] the Lunora sidecar (wrangler dev) exited — shutting down the framework dev server"),e.kill("SIGTERM")):r.kill("SIGTERM"),await Promise.allSettled([e.exited,r.exited])),n&&clearTimeout(n),process.off("SIGINT",a),process.off("SIGTERM",i),u.code},io=async(e,r,t,o)=>{if(r.studioEnabled)try{return await(e.startStudio??br)({cwd:t,logger:{warnOnce:n=>{o.warn(n)}},port:r.studioPort,workerOrigin:r.workerOrigin})}catch(n){o.warn(`studio server failed to start (${n instanceof Error?n.message:String(n)}) — continuing without it`);return}},ao=e=>{const r=[e.codegenEnabled?"codegen watch":void 0,e.studioEnabled?"studio":void 0].filter(t=>t!==void 0);return`--no-worker: not starting wrangler. ${r.length>0?`${r.join(" + ")} running`:"nothing else to run"}; your task runner owns the worker on ${e.workerOrigin}.`},co=(e,r,t,o,n)=>{if(e.sidecar!==void 0)try{X({apiSpec:r.apiSpec,lunoraDirectory:"lunora",projectRoot:t,target:n})}catch(s){o.warn(`codegen (pre-sidecar) failed: ${s instanceof Error?s.message:String(s)} — the framework dev server will retry`)}},lo=async e=>{const r=await to(e),{logger:t}=e,o=r.wrangler.cwd??process.cwd(),n=Ee(o,e.target),s={remoteCleanup:r.remote.cleanup};try{const a=Number(process.env[h]),i=y(o);if(i!==void 0&&i.pid!==process.pid&&i.pid!==a)return S(t,i),{code:0,plan:r};const c=oo(r,o);if(c!==void 0)return S(t,c),{code:0,plan:r};(r.flavor==="vite"||r.flavor==="framework-worker")&&(r.wrangler.env={...r.wrangler.env,[h]:String(process.pid)}),await eo(e,o),t.info(r.flavor==="vite"?"starting vite dev (worker + studio + codegen run inside Vite via @lunora/vite)":"starting wrangler dev + studio"),r.ipv4LoopbackForced&&t.info("no IPv6 loopback (::1) on this host — binding the worker to 127.0.0.1 (--ip) so wrangler dev doesn't crash. Pin `dev.ip` in wrangler.jsonc to override."),r.codegenEnabled&&(s.codegen=(e.startCodegen??gr)({apiSpec:e.apiSpec,logger:t,projectRoot:o,target:n})),s.studio=await io(e,r,o,t);const u=s.studio?.url;if(r.frameworkHint!==void 0&&t.warn(r.frameworkHint),!r.workerEnabled)return t.info(ao(r)),{code:await no(t),plan:r};co(r,e,o,t,n);const p=e.startWorker??zr,m=p(r.wrangler,t),l=r.sidecar===void 0?void 0:p(r.sidecar,t);return s.containerLogs=ro(r,o,t,u),Xr(t,o),{code:await so(m,l,t),plan:r}}finally{f(o,process.pid),await Qr(s)}},Oo=We(async({argument:e,cwd:r,logger:t,options:o})=>{const n=o.json===!0,s=Vr({cwd:r,json:n,lines:o.lines,logger:t,subcommand:e[0]});if(s!==void 0)return s;const a=process.env[T]==="1",i=a?void 0:be(),c=n||i!==void 0;c&&Ke(),i!==void 0&&o.background!==!0&&t.info(`AI agent detected (${i.name} via ${i.variable}) — starting the dev server in background mode with JSON logs. Set LUNORA_AGENT_MODE=0 to opt out.`);const u=Fe({configPreference:$e(r),envValue:process.env.LUNORA_REMOTE,flag:o.remote});if(!a&&(o.background===!0||i!==void 0)){const p=y(r);return p!==void 0?(S(t,p),{code:0}):Ar({cwd:r,jsonLogs:c,logger:t,options:o,remote:u})}return lo({apiSpec:He(o.apiSpec),codegen:o.codegen===!1?!1:void 0,cwd:r,logger:t,port:o.port,remote:u,studio:o.studio===!1?!1:void 0,target:o.target,workerPort:o.workerPort})});export{L as detectDevFlavor,Oo as execute,Jr as planDevCommand,qr as resolveRemotePlan,Br as resolveWorkerPort,lo as runDevCommand};
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{runCodegen as
|
|
2
|
-
↳ ${
|
|
3
|
-
${
|
|
4
|
-
`)}`)}const
|
|
1
|
+
import{runCodegen as $}from"@lunora/codegen";import{collectWranglerSecretVariables as w}from"@lunora/config/cloudflare";import{r as h}from"../packem_shared/api-spec-BENwiyUa.mjs";import{i as C}from"../packem_shared/command-Bjv4VmYA.mjs";import{i as S}from"../packem_shared/deploy-target-Dvr9vxpR.mjs";import{i as A,d as y,s as D,r as R}from"../packem_shared/output-format-D7cKB-O5.mjs";import{a as T}from"../packem_shared/platform-diagnostics-C4TFj5Pu.mjs";const u=3,b=r=>{const a=r.cwd??process.cwd(),i=R(r.format),t=D(r.format,r.logger),g=A("codegen",r.format);if(g!==void 0)return r.logger.error(g),{advisories:[],cronTriggers:[],error:g,failedAdvisories:0,outputDirectory:""};const p=r.strictAdvisories??(process.env.CI!==void 0&&process.env.CI!==""),c=S(a,r.target);if(c.target===void 0)return r.logger.error(c.error??"unknown deploy target"),{advisories:[],cronTriggers:[],error:c.error??"unknown deploy target",failedAdvisories:0,outputDirectory:""};const{target:f}=c,o=$({apiSpec:r.apiSpec,projectRoot:a,target:f,wranglerVariables:w(a)}),l={advisories:o.advisories.map(e=>({detail:e.detail,level:e.level,name:e.name,remediation:e.remediation})),cronTriggers:o.cronTriggers,failedAdvisories:0,outputDirectory:o.outputDirectory};if(t.success(`codegen wrote dataModel.ts, api.ts, server.ts to ${o.outputDirectory}`),o.advisories.length>0){const e=o.advisories.length,d=o.advisories.map(s=>` [${s.level}] ${s.name} — ${s.detail}
|
|
2
|
+
↳ ${s.remediation}`);t.warn(`${e.toString()} schema ${e===1?"advisory":"advisories"}:
|
|
3
|
+
${d.join(`
|
|
4
|
+
`)}`)}const m=T(o.platformDiagnostics,t);m!==void 0&&(l.error=m);const n=l.advisories.filter(e=>e.level==="ERROR");if(n.length>0&&p){const e=[...new Set(n.map(d=>d.name))].toSorted((d,s)=>d.localeCompare(s));t.error(`${n.length.toString()} ERROR-level ${n.length===1?"advisory":"advisories"} (${e.join(", ")}). Codegen wrote its output; this exit code is the gate. Pass --no-strict-advisories to downgrade it to a warning.`)}o.cronTriggers.length>u&&t.warn(`${o.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).`);const v={...l,failedAdvisories:p?n.length:0};return i&&y(v),v},W=C(({cwd:r,logger:a,options:i})=>{const t=b({apiSpec:h(i.apiSpec),cwd:r,format:i.format,logger:a,strictAdvisories:i.strictAdvisories,target:i.target});return{code:t.error===void 0&&t.failedAdvisories===0?0:1}});export{W as execute,b as runCodegenCommand};
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{existsSync as h,mkdirSync as L,writeFileSync as m,readFileSync as b,readdirSync as X,rmSync as I,mkdtempSync as Y,lstatSync as Me,cpSync as W,renameSync as Le}from"node:fs";import{tmpdir as Z}from"node:os";import{detectFramework as Se,isInteractive as g,LUNA_ART as Ae,LUNA_NAME as Ne,LUNA_SIGNOFF as Ie,paintAnswer as _e,BADGES as f}from"@lunora/config";import{walkSync as Re}from"@visulima/fs";import{join as p,dirname as $,basename as S,resolve as B,relative as Te}from"@visulima/path";import{downloadTemplate as ee}from"giget";import{modify as Oe,applyEdits as je}from"jsonc-parser";import{join as E,dirname as Be}from"node:path";import{i as Ee}from"../packem_shared/command-Bjv4VmYA.mjs";import{P as te,t as Pe,d as De,k as ze}from"../packem_shared/detect-package-manager-B2eIuAiP.mjs";import Ue from"magic-string";import{Project as ae,SyntaxKind as v}from"ts-morph";import{P}from"../packem_shared/prompt-cancelled-C8Sj7OqI.mjs";import{P as re,g as oe,b as Ve,L as se,
|
|
1
|
+
import{existsSync as h,mkdirSync as L,writeFileSync as m,readFileSync as b,readdirSync as X,rmSync as I,mkdtempSync as Y,lstatSync as Me,cpSync as W,renameSync as Le}from"node:fs";import{tmpdir as Z}from"node:os";import{detectFramework as Se,isInteractive as g,LUNA_ART as Ae,LUNA_NAME as Ne,LUNA_SIGNOFF as Ie,paintAnswer as _e,BADGES as f}from"@lunora/config";import{walkSync as Re}from"@visulima/fs";import{join as p,dirname as $,basename as S,resolve as B,relative as Te}from"@visulima/path";import{downloadTemplate as ee}from"giget";import{modify as Oe,applyEdits as je}from"jsonc-parser";import{join as E,dirname as Be}from"node:path";import{i as Ee}from"../packem_shared/command-Bjv4VmYA.mjs";import{P as te,t as Pe,d as De,k as ze}from"../packem_shared/detect-package-manager-B2eIuAiP.mjs";import Ue from"magic-string";import{Project as ae,SyntaxKind as v}from"ts-morph";import{P}from"../packem_shared/prompt-cancelled-C8Sj7OqI.mjs";import{P as re,g as oe,b as Ve,L as se,k as He}from"../packem_shared/commands-C5pu77HK.mjs";import{defaultSpawner as ie}from"../packem_shared/createRecordingSpawner-ByIqBepG.mjs";import{Y as We,h as qe,M as Fe,C as ne,U as Ke,i as le,X as ce,B as D,H as Je,W as Qe,Q as de,I as Ge,t as Xe}from"../packem_shared/tui-prompts-CCt3jm1k.mjs";import{l as pe,u as Ye,p as Ze,b as et,a as tt,m as at,n as rt,f as ue,q as he,h as ot}from"../packem_shared/storage-BazhWFmM.mjs";import{logStep as q}from"../packem_shared/createLogger--C3x1FNE.mjs";import st from"node:dns/promises";const it=`name: Deploy
|
|
2
2
|
|
|
3
3
|
on:
|
|
4
4
|
push:
|
|
@@ -1,5 +1,5 @@
|
|
|
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 $}from"@lunora/errors";import{join as c}from"@visulima/path";import{Project as w}from"ts-morph";import{u as F}from"../packem_shared/admin-url-Ca-KI3d_.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-
|
|
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 ${y} and write the SQL manually`),{code:0,empty:!1,migrationFile:g}},
|
|
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 $}from"@lunora/errors";import{join as c}from"@visulima/path";import{Project as w}from"ts-morph";import{u as F}from"../packem_shared/admin-url-Ca-KI3d_.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-CEOt386P.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 $("INTERNAL",`unsupported snapshot version: ${o.version}`);return o}catch(e){const o=e instanceof Error?e.message:String(e);throw new $("INTERNAL",`failed to read ${r}: ${o}`,{cause:e})}},G=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"),y=`${P(u)}_${b}.sql`,g=c(i,y);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 ${y} and write the SQL manually`),{code:0,empty:!1,migrationFile:g}},K="migrations.ts",v=/^[A-Za-z_]\w*$/u,Q=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";',V="__lunora_admin__:runMigration",W="__lunora_admin__:migrationStatus",Y="/_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)||Q.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,K);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
3
|
`:s.includes(f)||(s=`${f}
|
|
4
4
|
${s}`);const d=`export const ${t} = defineMigration({
|
|
5
5
|
id: "${o}",
|
|
@@ -8,4 +8,4 @@ ${s}`);const d=`export const ${t} = defineMigration({
|
|
|
8
8
|
});`;return S(a,{recursive:!0}),h(i,`${s.trimEnd()}
|
|
9
9
|
|
|
10
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,r.cwd);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}${
|
|
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,r.cwd);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}${Y}`,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"?W:V,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 G({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,G as runMigrateGenerateCommand,lr as runMigrateToHyperdriveCommand};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import"node:fs";import"node:path";import"node:url";import"@lunora/errors";import"@visulima/cerebro";import"@visulima/cerebro/command/completion";import"@visulima/cerebro/command/version";import{s as M,t as N,e as O}from"./cli-
|
|
1
|
+
import"node:fs";import"node:path";import"node:url";import"@lunora/errors";import"@visulima/cerebro";import"@visulima/cerebro/command/completion";import"@visulima/cerebro/command/version";import{s as M,t as N,e as O}from"./cli-BxL0WCh4.mjs";import"./createLogger--C3x1FNE.mjs";export{M as COMMANDS,N as VERSION,O as runCli};
|
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
import{createWriteStream as J,createReadStream as I}from"node:fs";import{unlink as A,stat as h,readdir as D}from"node:fs/promises";import{join as P}from"node:path";import{LunoraError as T}from"@lunora/errors";import{l as E}from"./admin-token-DV5A9T5b.mjs";import{u as j}from"./admin-url-Ca-KI3d_.mjs";const _="/_lunora/admin/export",R="/_lunora/admin/import",q=500,L=t=>{if(t===void 0)return;const r=t.split(",").map(o=>o.trim()).filter(o=>o.length>0);return r.length>0?r:void 0},N=async(t,r)=>{t.write(r)||await new Promise(o=>{t.once("drain",o)})},U=async(t,r)=>{const o=t.getReader(),e=new TextDecoder;let i=0,s=0,n="",c=!1;try{for(;!c;){const f=await o.read();if(c=f.done,f.value===void 0)continue;i+=f.value.length,n+=e.decode(f.value,{stream:!0});let l=n.indexOf(`
|
|
2
|
+
`);for(;l!==-1;){s+=1;const u=`${n.slice(0,l)}
|
|
3
|
+
`;await N(r,u),n=n.slice(l+1),l=n.indexOf(`
|
|
4
|
+
`)}}return n.length>0&&(s+=1,await N(r,`${n}
|
|
5
|
+
`)),{bytes:i,rows:s}}finally{o.releaseLock()}},C=async(t,r)=>{if(r!==void 0){t.destroy();try{await A(r)}catch{}}},X=async t=>{if(t.prod&&t.url===void 0)return t.logger.error("--prod requires an explicit --url (refusing to export from the implicit localhost worker)"),{bytes:0,code:1,rows:0};const r=j(t.url,t.logger,t.cwd);if(r===void 0)return{bytes:0,code:1,rows:0};const{token:o}=E({cwd:t.cwd??process.cwd(),token:t.token,url:r});if(!o)return t.logger.error("admin token required — pass --token, set LUNORA_ADMIN_TOKEN, or add it to .dev.vars (local targets only)"),{bytes:0,code:1,rows:0};const e=`${r}${_}`,i=L(t.tables),s=t.fetchImpl??globalThis.fetch;if(typeof s!="function")throw new TypeError("no fetch implementation available — pass fetchImpl or run on Node >= 18");t.logger.info(`POST ${e} -> export${i?` (tables: ${i.join(",")})`:""}`);const n=await s(e,{body:JSON.stringify(i?{tables:i}:{}),headers:{authorization:`Bearer ${o}`,"content-type":"application/json"},method:"POST"});if(!n.ok){const p=await n.text();return t.logger.error(`export failed: HTTP ${String(n.status)}: ${p}`),{bytes:0,code:1,rows:0}}if(!n.body)return t.logger.error("export response carried no body"),{bytes:0,code:1,rows:0};const c=t.out===void 0||t.out==="-"?void 0:t.out,f=c===void 0?process.stdout:J(c,{encoding:"utf8"});let l,u;try{({bytes:l,rows:u}=await U(n.body,f))}catch(p){throw await C(f,c),p}return c!==void 0&&(await new Promise((p,g)=>{f.end(y=>{y?g(y):p()})}),t.logger.success(`wrote ${String(u)} rows to ${c} (${String(l)} bytes)`)),{bytes:l,code:0,rows:u}},F=async t=>{if(t.prod&&t.url===void 0){t.logger.error("--prod requires an explicit --url (refusing to import to the implicit localhost worker)");return}if(t.prod&&t.yes!==!0){t.logger.error("import --prod bulk-writes production. Re-run with --yes to confirm.");return}const r=j(t.url,t.logger,t.cwd);if(r===void 0)return;const{token:o}=E({cwd:t.cwd??process.cwd(),token:t.token,url:r});if(!o){t.logger.error("admin token required — pass --token, set LUNORA_ADMIN_TOKEN, or add it to .dev.vars (local targets only)");return}try{const i=await h(t.file);if(!i.isFile()&&!i.isDirectory()){t.logger.error(`not a file or directory: ${t.file}`);return}}catch(i){const s=i instanceof Error?i.message:String(i);t.logger.error(`failed to stat ${t.file}: ${s}`);return}const e=t.fetchImpl??globalThis.fetch;if(typeof e!="function")throw new TypeError("no fetch implementation available — pass fetchImpl or run on Node >= 18");return{fetchImpl:e,requestUrl:`${r}${R}`,token:o}},k="_storage",z=async t=>{if(!(await h(t).catch(()=>{}))?.isDirectory())return;const r=[];for(const o of await D(t,{withFileTypes:!0})){if(!o.isDirectory())continue;const e=P(t,o.name,"documents.jsonl");(await h(e).catch(()=>{}))?.isFile()&&r.push({file:e,table:o.name})}return r.length>0?r.toSorted((o,e)=>o.table.localeCompare(e.table)):void 0};async function*B(t,r){let o="";for await(const i of I(t,{encoding:"utf8"})){o+=typeof i=="string"?i:i.toString("utf8");let s=o.indexOf(`
|
|
6
|
+
`);for(;s!==-1;){const n=o.slice(0,s).trim();o=o.slice(s+1),n.length>0&&(yield`${JSON.stringify({doc:JSON.parse(n),table:r})}
|
|
7
|
+
`),s=o.indexOf(`
|
|
8
|
+
`)}}const e=o.trim();e.length>0&&(yield`${JSON.stringify({doc:JSON.parse(e),table:r})}
|
|
9
|
+
`)}async function*H(t,r){for(const{file:o,table:e}of t){if(e===k){r.warn(`skipping "${k}" — those rows describe stored files. Upload the exported blobs to R2 and re-point the keys.`);continue}yield*B(o,e)}}const M=async t=>{const r=await z(t.file),o=await h(t.file);return r===void 0&&o.isDirectory()?(t.logger.error(`${t.file} is a directory but holds no <table>/documents.jsonl — expected a \`npx convex export --path <dir>\` dump, or pass an NDJSON file.`),{error:!0}):r&&t.table!==void 0?(t.logger.error("--table cannot be combined with a Convex export directory — each row's table comes from its source directory."),{error:!0}):{convexTables:r,error:!1}},Y=async t=>{const r=await F(t);if(r===void 0)return{body:void 0,code:1,inserted:0};const{fetchImpl:o,requestUrl:e,token:i}=r,s=t.batchSize??q,n=await M(t);if(n.error)return{body:void 0,code:1,inserted:0};const{convexTables:c}=n;t.logger.info(c?`POST ${e} -> import Convex export ${t.file} (${String(c.length)} tables)`:`POST ${e} -> import ${t.file}`);const f=c?H(c,t.logger):I(t.file,{encoding:"utf8"}),l={},u=[];let p=0,g="",y=[],v=0;const $=async()=>{if(y.length===0)return;const w=y.join(`
|
|
10
|
+
`);y=[];const d=await o(e,{body:w,headers:{authorization:`Bearer ${i}`,"content-type":"application/x-ndjson"},method:"POST"});if(!d.ok){const m=await d.text().catch(()=>"<no body>");throw new T("INTERNAL",`import batch failed (HTTP ${String(d.status)}): ${m}`)}const a=await d.json();if(a.inserted)for(const[m,b]of Object.entries(a.inserted))l[m]=(l[m]??0)+b;Array.isArray(a.errors)&&u.push(...a.errors),typeof a.conflicts=="number"&&(p+=a.conflicts)},S=w=>{const d=w.trim();if(d.length===0)return;if(v+=1,t.table===void 0){y.push(d);return}let a;try{a=JSON.parse(d)}catch(m){const b=m instanceof Error?m.message:String(m);throw new T("INTERNAL",`invalid JSON on line ${String(v)}: ${b}`,{cause:m})}y.push(JSON.stringify({doc:a,table:t.table}))};for await(const w of f){const d=typeof w=="string"?w:w.toString("utf8");g+=d;let a=g.indexOf(`
|
|
11
|
+
`);for(;a!==-1;)S(g.slice(0,a)),g=g.slice(a+1),a=g.indexOf(`
|
|
12
|
+
`),y.length>=s&&await $()}g.length>0&&S(g),await $();const x=Object.values(l).reduce((w,d)=>w+d,0),O={conflicts:p,errors:u,inserted:l};return t.logger.info(JSON.stringify(O,void 0,2)),t.logger.success(`imported ${String(x)} rows (${String(p)} conflicts, ${String(u.length)} errors)`),{body:O,code:u.length>0?1:0,inserted:x}};export{q as DEFAULT_IMPORT_BATCH_SIZE,X as runExportCommand,Y as runImportCommand};
|
|
@@ -0,0 +1,3 @@
|
|
|
1
|
+
import{mkdirSync as O,readFileSync as b,lstatSync as R,writeFileSync as B}from"node:fs";import{join as c,dirname as h}from"node:path";import{fileURLToPath as A}from"node:url";import{resolveHint as D,isLunoraError as w,flattenHint as L,findSolutionByMessage as E}from"@lunora/errors";import{createCerebro as j}from"@visulima/cerebro";import C from"@visulima/cerebro/command/completion";import I from"@visulima/cerebro/command/version";import{p as l}from"./api-spec-BENwiyUa.mjs";import{g as s}from"./deploy-target-Dvr9vxpR.mjs";import{createLogger as k}from"./createLogger--C3x1FNE.mjs";import{VisulimaError as _,renderError as P}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 auth-ui","Add copy-in auth screens for your framework (auto-detected)"],["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}]},y="lunora.advisor.map.json",U={description:"Score your app's advisor findings into a health map, and gate CI on it",examples:[["lunora advisor","Score the app and write lunora.advisor.map.json"],["lunora advisor --all","Show every procedure as a check matrix"],["lunora advisor --entry messages#sendMessage","Inspect one procedure"],["lunora advisor --min-score 80","Exit non-zero when the score drops below 80"],["lunora advisor --baseline","Fail on any regression against the committed map"]],group:"Develop",loader:()=>import("../packem_chunks/handler21.mjs").then(e=>({default:e.execute})),name:"advisor",options:[{description:"Show every procedure as a check matrix, not just the ones with findings",name:"all",type:Boolean},{description:`Compare against a committed map and fail on regression (default ${y})`,name:"baseline",type:String},{description:"Inspect a single procedure by `file#exportName`",name:"entry",type:String},{description:"Output format: pretty (default) or json",name:"format",type:String},{description:"Exit non-zero when the global score is below this value (0-100)",name:"min-score",type:String},{description:`Where to write the map (default ${y})`,name:"out",type:String},{description:"Write the map artifact to disk (default true; use --no-write to skip)",name:"write",type:Boolean}]},M={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}]},W={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}]},J={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: ${l} (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},s]},K={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: ${l} (default openapi)`,name:"api-spec",type:String},{description:"Output format: pretty (default) or json",name:"format",type:String},{description:"Don't fail on ERROR-level advisories (the gate defaults to on in CI, off locally)",name:"no-strict-advisories",type:Boolean},s]},q={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}]},F={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: ${l} (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},s,{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}]},H={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}]},V={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: ${l} (default openapi)`,name:"api-spec",type:String},{description:"Studio server port (default 6173)",name:"port",type:Number},s,{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 spawn wrangler dev — an external task runner owns the worker; codegen watch + studio still run",name:"no-worker",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}]},z={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"},G={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:[]},Y={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}]},Q={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}]},X={argument:{description:"Source NDJSON file, or a `npx convex export --path <dir>` directory",name:"file",type:String},description:"Bulk-insert rows from an NDJSON file — or a Convex export directory — via the worker's admin endpoint",examples:[["lunora import backup.ndjson","Bulk-insert rows from an NDJSON file"],["lunora import ./convex-export","Import a `npx convex export --path` directory (ids are preserved, so no remapping)"]],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}]},ee={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}]},te={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}]},re={description:"Scaffold lunora/schema.ts (and list/get procedures) from an existing Postgres or MySQL database",examples:[["lunora introspect --url postgres://localhost/shop","Scaffold a schema + procedures from every table"],["lunora introspect --tables users,orders","Introspect only these tables (DATABASE_URL is read by default)"],["lunora introspect --dry-run","Print what would be written without touching the filesystem"],["lunora introspect --no-procedures --force","Regenerate just the schema, overwriting the existing file"]],group:"Data",loader:()=>import("../packem_chunks/handler23.mjs").then(e=>({default:e.execute})),name:"introspect",options:[{description:"Database connection string (default: $DATABASE_URL)",name:"url",type:String},{description:"Postgres schema (default `public`) or MySQL database name",name:"schema",type:String},{description:"Comma-separated table allow-list (default: every base table)",name:"tables",type:String},{description:"Also emit list/get procedure modules per table (default true; --no-procedures to skip)",name:"procedures",type:Boolean},{description:"Overwrite files that already exist",name:"force",type:Boolean},{description:"Print what would be written without writing it",name:"dry-run",type:Boolean}]},oe={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}]},ne={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/handler22.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},s,{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}]},ae={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/handler24.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}]},ie={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}]},se={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: ${l} (default openapi)`,name:"api-spec",type:String},s,{description:"Re-bless the committed schema baseline (lunora/.lunora-schema.json) with the current shape",name:"update-schema-baseline",type:Boolean}]},le={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}]},pe={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}]},de={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)"],["lunora rules install --dir packages/app","Install into a specific root instead of the workspace root"]],group:"Project",loader:()=>import("../packem_chunks/handler17.mjs").then(e=>({default:e.execute})),name:"rules",options:[{description:"Install/check root (default: the detected workspace root, not the current directory)",name:"dir",type:String},{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}]},ce={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"],["lunora run messages:list --as user_123","Run as an authenticated user (needed when the app gates on identity)"]],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:"Run as this user id — dispatches through the admin-gated `runAs` op so identity-gated apps accept the call",name:"as",type:String},{description:`JSON-encoded extra identity claims to forge alongside --as (e.g. '{"org":"acme"}')`,name:"claims",type:String},{description:"Explicit shard key",name:"shard",type:String},{description:"Worker URL (defaults to the running dev server, else http://localhost:8787)",name:"url",type:String},{description:"Admin bearer for --as (prefer LUNORA_ADMIN_TOKEN or .dev.vars; --token is visible to other local processes via the process table)",name:"token",type:String}]},ue={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"],["lunora seed --seed 7 --now 1785000000000","Byte-identical rows across runs (pins the clock too)"]],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:"Epoch-ms reference for time columns (createdAt, expiresAt, …). Pin it with --seed for byte-identical rows across runs; defaults to now",name:"now",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}]},me={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: ${l} (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},s]},ge={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}]},he={filterStacktrace:()=>!1,hideErrorCodeView:!0},ye=(e,t={})=>{const r=e instanceof Error?e.message:String(e),o=D(w(e)?{code:e.code,hint:e.hint,message:r}:r),n=new _({hint:o===void 0?void 0:L(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="",P(n,he)},fe=(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,p=e[o-1]===t[a-1]?0:1;r[a]=Math.min((r[a-1]??0)+1,i+1,n+p),n=i}}return r[t.length]??0},ve=(e,t)=>{let r,o=Number.POSITIVE_INFINITY;for(const a of t){const i=fe(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},be=e=>`https://registry.npmjs.org/@lunora/cli/${e}`,we=1440*60*1e3,ke=1500,Se="0.0.0",xe=/^v/u,Ne=new Set(["alpha","beta","next"]),u=e=>{const t=e.trim().replace(xe,""),r=t.indexOf("-");return r===-1?{core:t,prerelease:""}:{core:t.slice(0,r),prerelease:t.slice(r+1)}},f=e=>{const[t,r,o]=u(e).core.split(".").map(n=>{const a=Number.parseInt(n,10);return Number.isFinite(a)?a:0});return[t??0,r??0,o??0]},Oe=(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},Re=(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 Oe(a,i)}return 0},Be=(e,t)=>{const r=f(e),o=f(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 Re(u(e).prerelease,u(t).prerelease)},Ae=e=>{const t=u(e).prerelease.split(".")[0]??"";return Ne.has(t)?t:"latest"},De=(e,t)=>Be(t,e)>0,Le=(e,t,r)=>t-e<r,Ee=(e,t,r="latest")=>`Update available for @lunora/cli: ${e} → ${t} — run \`pnpm add -D @lunora/cli@${r}\``,S=e=>c(e,"lunora-cli-update.json"),je=e=>{const t=e.XDG_CACHE_HOME&&e.XDG_CACHE_HOME.length>0?e.XDG_CACHE_HOME:c(T(),".cache"),r=c(t,"lunora");try{O(r,{mode:448,recursive:!0})}catch{}return r},Ce=e=>{try{const t=JSON.parse(b(S(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{}},v=(e,t)=>{try{const r=S(e);try{if(R(r).isSymbolicLink())return}catch{}B(r,`${JSON.stringify(t)}
|
|
3
|
+
`,"utf8")}catch{}},Ie=async(e,t)=>{try{const r=await e(be(t),{signal:AbortSignal.timeout(ke)});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}},_e=(e,t,r)=>e===Se||!r||t.CI!==void 0||t.LUNORA_NO_UPDATE_NOTIFIER!==void 0,Pe=async e=>{const t=e.env??process.env,r=e.isTTY??process.stdout.isTTY;if(_e(e.current,t,r))return;const o=e.cacheDir??je(t),n=(e.now??Date.now)(),a=e.ttlMs??we,i=Ae(e.current),p=Ce(o),N=p?.tag??"latest",m=p!==void 0&&N===i?p:void 0;let d=m?.latest;if(m===void 0||!Le(m.checkedAt,n,a)){const g=await Ie(e.fetchImpl??globalThis.fetch,i);g===void 0?v(o,{checkedAt:n,latest:e.current,tag:i}):(d=g,v(o,{checkedAt:n,latest:g,tag:i}))}d!==void 0&&De(e.current,d)&&e.logger.warn(Ee(e.current,d,i))},Te=["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"],$e=8,Ue=()=>{try{let e=h(A(import.meta.url));for(let t=0;t<$e;t+=1){try{const o=JSON.parse(b(c(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=h(e);if(r===e)break;e=r}}catch{}return"0.0.0"},x=Ue(),Me=[ee,$,V,K,U,J,F,q,se,oe,H,ne,ce,te,pe,ie,Q,X,ue,re,W,me,Z,G,Y,M,ge,z,le,de,ae],We=e=>{const t={value:0},r=j("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:x});for(const o of Me)r.addCommand(o);return r.addCommand(I),r.addCommand(C),{cli:r,exitCode:t}},Je=/Command "(?<name>[^"]+)" not found/u,Ke=e=>{const t=k(),r=e instanceof Error?e.message:String(e),o=Je.exec(r);if(!o?.groups){w(e)||E(r)!==void 0?t.error(ye(e)):t.error(r);return}const n=o.groups.name??"",a=ve(n,Te);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.")},rt=async(e={})=>{const{cli:t,exitCode:r}=We(e);try{await t.run({shouldExitProcess:!1})}catch(o){return Ke(o),1}return await Pe({current:x,logger:k()}),r.value};export{rt as e,y as o,Te as s,x as t};
|
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
import{existsSync as p,readFileSync as g,writeFileSync as $,mkdirSync as j,mkdtempSync as oe,rmSync as O}from"node:fs";import{dirname as w,join as l,relative as L}from"@visulima/path";import{DEV_VARS_FILE as se,parseDevVariableEntries as ie}from"@lunora/config";import{modify as W,applyEdits as U,parse as ae}from"jsonc-parser";import{fileURLToPath as ce}from"node:url";import{LunoraError as y}from"@lunora/errors";import{i as ue}from"./tui-prompts-CCt3jm1k.mjs";import{collectCatalog as de,buildRegistryIndex as fe}from"./buildRegistryIndex-DwySASBu.mjs";import{findWranglerFile as le,readWranglerJsonc as pe}from"@lunora/config/cloudflare";import{insertSchemaExtension as ge}from"./insertSchemaExtension-DZReBZ4_.mjs";import{createHash as me}from"node:crypto";import{tmpdir as $e}from"node:os";import{downloadTemplate as he}from"giget";import ye from"./parseManifest-x3WsxKHz.mjs";const ve="alpha",z="main",we=new Set(["alpha","beta","next"]),be=/^[\w./@-]+$/,ke=e=>!e.includes("..")&&be.test(e),M=()=>{try{let e=w(ce(import.meta.url));for(let t=0;t<6;t+=1){const n=l(e,"package.json");if(p(n)){const o=JSON.parse(g(n,"utf8"));if(o.name==="@lunora/cli"&&typeof o.version=="string")return o.version}const r=w(e);if(r===e)break;e=r}}catch{}return"0.0.0"},V=e=>{if(e==="0.0.0")return ve;const t=e.split("+")[0]??e,n=t.indexOf("-");if(n!==-1){const[r]=t.slice(n+1).split(".");if(r!==void 0&&we.has(r))return r}return z},B=e=>{if(e!==void 0&&e.length>0){if(!ke(e))throw new y("INTERNAL",`invalid --ref "${e}" — a ref may contain letters, digits, ".", "_", "-", "/", "@" and must not contain "..".`);return e}return V(M())},x="anolilab/lunora",F=/^[0-9a-f]{40}$/iu,H=String.raw`\d+\.\d+\.\d+(?:-[0-9A-Za-z-]+(?:\.[0-9A-Za-z-]+)+)?(?:\+[0-9A-Za-z.-]+)?`,Se=new RegExp(String.raw`^v?${H}$`,"u"),je=new RegExp(String.raw`^(?:@[\w.-]+\/)?[\w.-]+@${H}$`,"u"),xe=e=>F.test(e)||Se.test(e)||je.test(e),Ne=()=>{const e=process.env.GITHUB_TOKEN??process.env.GH_TOKEN;return e!==void 0&&e.length>0?{authorization:`Bearer ${e}`}:{}},Oe=async e=>{try{const t=await fetch(`https://api.github.com/repos/${x}/commits/${encodeURIComponent(e)}`,{headers:{accept:"application/vnd.github+json","user-agent":"lunora-cli",...Ne()},signal:AbortSignal.timeout(1e4)});if(!t.ok)return;const n=await t.json();return typeof n.sha=="string"&&F.test(n.sha)?n.sha:void 0}catch{return}},Re=async(e,t)=>{const n=B(e);if(xe(n))return n;const r=await Oe(n);return r===void 0?(t.warn(`could not pin ${x}#${n} to a commit — fetching the UNPINNED branch (set GITHUB_TOKEN if rate-limited).`),n):(t.info(`pinned ${x}#${n} → ${r}`),r)},Ae="latest",Ee=(e=M())=>{const t=V(e);return t===z?Ae:t},Te="https://registry.npmjs.org",_e=()=>{const e=process.env.npm_config_registry,t=e!==void 0&&e.length>0?e:Te;return t.endsWith("/")?t.slice(0,-1):t},Je=async(e,t)=>{try{const n=await fetch(`${_e()}/${e.replaceAll("/","%2F")}`,{headers:{accept:"application/vnd.npm.install-v1+json"},signal:AbortSignal.timeout(1e4)});return n.ok?(await n.json())["dist-tags"]?.[t]:void 0}catch{return}},_t=async(e,t)=>{const n=new Map;return await Promise.all([...new Set(e)].map(async r=>{const o=await Je(r,t);o!==void 0&&n.set(r,o)})),n},C=e=>{if(!e.startsWith("workspace:"))return e;const t=e.slice(10);return t===""||t==="*"||t==="^"||t==="~"?Ee():t},De=new Set(["@lunora/client","@lunora/do","@lunora/ratelimit","@lunora/runtime","@lunora/server","@lunora/values"]),Ie=/(['"])@lunora\/(client|do|ratelimit|runtime|server|values)(\/[^'"]*)?\1/gu,qe=e=>{const t=l(e,"package.json");if(!p(t))return!1;try{const n=JSON.parse(g(t,"utf8"));return n.dependencies?.lunorash!==void 0||n.devDependencies?.lunorash!==void 0}catch{return!1}},Pe=e=>e.replaceAll(Ie,(t,n,r,o)=>`${n}lunorash/${r}${o??""}${n}`),R=(e,t,n,r="dependencies",o=!1)=>{const s=Object.entries(e);if(s.length===0)return[];const a=l(t,"package.json");if(!p(a))return n.warn(`package.json not found at ${a} — skipping dependency updates`),[];let i=g(a,"utf8");const c=JSON.parse(i),u=[];for(const[d,f]of s){if(o&&De.has(d)){n.info(`dep provided by the lunorash umbrella, skipping: ${d}`);continue}if(c.dependencies?.[d]!==void 0||c.devDependencies?.[d]!==void 0){n.info(`dep already present: ${d}`);continue}const m=W(i,[r,d],C(f),{formattingOptions:{insertSpaces:!0,tabSize:4}});i=U(i,m),u.push(d)}return u.length>0&&($(a,i,"utf8"),n.success(`added ${String(u.length)} ${r==="devDependencies"?"devDependency(ies)":"dependency(ies)"} to package.json: ${u.join(", ")}`)),u},Le=(e,t,n)=>{if(e.length===0)return[];const r=l(t,se),o=p(r)?g(r,"utf8"):"",s=new Set(ie(o).map(u=>u.key)),a=[],i=[],c=[];for(const u of e)u.secret&&i.push(u.name),!s.has(u.name)&&(u.description&&c.push(`# ${u.description}`),c.push(`${u.name}=${u.secret?"":u.value??""}`),a.push(u.name));if(a.length>0){const u=o===""||o.endsWith(`
|
|
2
|
+
`)?o:`${o}
|
|
3
|
+
`;$(r,`${u}${c.join(`
|
|
4
|
+
`)}
|
|
5
|
+
`,"utf8"),n.success(`scaffolded ${String(a.length)} env var(s) into .dev.vars: ${a.join(", ")}`)}return i.length>0&&n.info(`set secret value(s) locally in .dev.vars, then for production: ${i.map(u=>`wrangler secret put ${u}`).join("; ")}`),a},A=new Set(["ai","analytics_engine_datasets","browser","d1_databases","durable_objects","hyperdrive","kv_namespaces","mtls_certificates","queues","r2_buckets","send_email","services","vars","vectorize","version_metadata","workflows"]),We=["binding","name","queue","pattern"],E=e=>{if(!(typeof e!="object"||e===null))for(const t of We){const n=e[t];if(typeof n=="string"&&n.length>0)return`${t}:${n}`}},Ue=(e,t,n,r)=>{const o=new Set(e.map(i=>JSON.stringify(i))),s=new Set(e.map(i=>E(i)).filter(i=>i!==void 0)),a=[];for(const i of t){if(o.has(JSON.stringify(i)))continue;const c=E(i);if(c!==void 0&&s.has(c)){r.warn(`${c.replace(":"," ")} already exists in ${n} — keeping the project's entry and skipping the registry item's. Reconcile by hand if the item needs different settings.`);continue}c!==void 0&&s.add(c),a.push(i)}return a},T=e=>Array.isArray(e),ze=(e,t)=>{let n=ae(e);for(const r of t){if(typeof n!="object"||n===null)return;n=n[r]}return n},Me=(e,t)=>{const n=e[0];return n!==void 0&&A.has(n)?!0:(t.warn(`skipping binding "${e.join(".")}" — only resource bindings (${[...A].join(", ")}) may be written, not exec/entrypoint keys`),!1)},G=Symbol("skip-binding"),Ve=(e,t,n)=>{const{value:r}=t;if(!T(r))return r;const o=ze(e,t.path);if(!T(o))return r;const s=Ue(o,r,t.path.join("."),n);return s.length===0?G:[...o,...s]},Be=(e,t,n)=>{if(e.length===0)return[];const r=["wrangler.jsonc","wrangler.json"].map(a=>l(t,a)).find(a=>p(a));if(!r)return n.warn("wrangler.jsonc not found — skipping binding updates"),[];let o=g(r,"utf8");const s=[];for(const a of e){if(!Me(a.path,n))continue;const i=Ve(o,a,n);if(i===G)continue;const c=W(o,[...a.path],i,{formattingOptions:{insertSpaces:!0,tabSize:4}});c.length!==0&&(o=U(o,c),s.push(a.path.join(".")))}return s.length>0&&($(r,o,"utf8"),n.success(`applied ${String(s.length)} binding(s) to ${r}: ${s.join(", ")}`)),s},Fe=(e,t,n,r=!1)=>{const o=[],s=[];return e.deps&&o.push(...R(e.deps,t,n,"dependencies",r)),e.devDependencies&&o.push(...R(e.devDependencies,t,n,"devDependencies",r)),e.bindings&&s.push(...Be(e.bindings,t,n)),e.envVars&&Le(e.envVars,t,n),{bindings:s,deps:o}},He=async(e,t)=>{const n=e.some(({manifest:c})=>Object.keys(c.deps??{}).length>0||Object.keys(c.devDependencies??{}).length>0),r=e.some(({manifest:c})=>(c.bindings??[]).length>0),o=t.source!==void 0&&t.source.length>0;if(!n&&!r&&!o||t.yes)return!0;const s=[];n&&s.push("add dependencies to package.json"),r&&s.push("write wrangler.jsonc bindings"),o&&s.push(`come from a non-default source (${String(t.source)})`);const a=s.join(", ");if(!process.stdin.isTTY&&t.confirm===void 0)return t.logger.error(`add: stdin is not a TTY and the requested items ${a} — re-run with --yes to confirm`),!1;const i=await(t.confirm??ue)(`The requested items ${a}. Continue?`);return i||t.logger.info("add: aborted"),i},S=1,Ce=".lunora-registry.json",Z=e=>l(e,"lunora",Ce),Ge=e=>typeof e!="object"||e===null||!("items"in e)?!1:typeof e.items=="object"&&e.items!==null,b=e=>me("sha256").update(e).digest("hex"),Ze=e=>{const t=Z(e);if(!p(t))return{items:{},version:S};try{const n=JSON.parse(g(t,"utf8"));if(Ge(n))return{items:n.items,version:S}}catch{}return{items:{},version:S}},Ke=(e,t)=>{$(Z(e),`${JSON.stringify(t,void 0,2)}
|
|
6
|
+
`,"utf8")},_=(e,t,n,r)=>{const o=e.items[t],s=o??{files:{}};o===void 0&&(e.items[t]=s),s.files[n]=b(r)},Ye=(e,t,n)=>e.items[t]?.files[n],J=e=>e===""?[]:e.split(`
|
|
7
|
+
`),Qe=(e,t)=>{const n=J(e),r=J(t);let o=0;for(;o<n.length&&o<r.length&&n[o]===r[o];)o+=1;let s=n.length,a=r.length;for(;s>o&&a>o&&n[s-1]===r[a-1];)s-=1,a-=1;if(o===s&&o===a)return[];const i=[];for(let c=Math.max(0,o-3);c<o;c+=1)i.push(` ${n[c]??""}`);for(let c=o;c<s;c+=1)i.push(`- ${n[c]??""}`);for(let c=o;c<a;c+=1)i.push(`+ ${r[c]??""}`);for(let c=a;c<Math.min(r.length,a+3);c+=1)i.push(` ${r[c]??""}`);return i},Xe=/\.[cm]?[jt]sx?$/u,K=(e,t,n)=>{const r=g(l(e,t.from),"utf8");return n&&Xe.test(t.to)?Pe(r):r},et=(e,t,n,r,o,s,a)=>{const i=l(r,"lunora","schema.ts");if(s)return o.info(`~ would merge .extend(${t}.extension) into lunora/schema.ts (and create ${e.to} if absent)`),{kind:"skipped",path:i};const c=l(r,e.to);p(c)||(j(w(c),{recursive:!0}),$(c,K(n,e,a),"utf8"));const u=a?"lunorash/server":"@lunora/server",d=p(i)?g(i,"utf8"):`import { defineSchema } from "${u}";
|
|
8
|
+
|
|
9
|
+
export const schema = defineSchema({});
|
|
10
|
+
`,f=ge(d,t);if(f.ok)return j(w(i),{recursive:!0}),$(i,f.text,"utf8"),o.success(`merged .extend(${t}.extension) into lunora/schema.ts`),{kind:"written",path:i};if(f.reason==="already-applied")return o.warn(`lunora/schema.ts already extends "${t}" — skipping`),{kind:"skipped",path:i};throw f.reason==="invalid-identifier"?new y("INTERNAL",`schema-extension item "${t}" is not a valid JS identifier — it is spliced into lunora/schema.ts as \`import { ${t} }\` / \`.extend(${t}.extension)\`. Rename the item to a valid identifier (no leading digit, no "-").`):new y("INTERNAL",`schema-extension merge failed for "${t}": ${f.reason}`)},tt=(e,t,n,r,o)=>{const s=Qe(t,n);if(s.length===0){o.info(`= ${e.to} (unchanged)`);return}o.info(`${r?"~":"+"} ${e.to}`);for(const a of s)o.info(` ${a}`)},nt=(e,t,n,r,o,s,a,i)=>{const c=l(r,e.to),u=K(n,e,i),d=p(c),f=d?g(c,"utf8"):"",m=re=>(j(w(c),{recursive:!0}),$(c,u,"utf8"),_(s,t,e.to,u),o.success(`${re}: ${e.to}`),{kind:"written",path:c});if(a.diff)return tt(e,f,u,d,o),{kind:"skipped",path:c};if(!d)return m("write");const h=b(f);if(h===b(u))return _(s,t,e.to,u),o.warn(`skip (exists): ${e.to}`),{kind:"skipped",path:c};if(a.overwrite)return m("overwrite");const v=Ye(s,t,e.to);return v===void 0?(o.warn(`skip (exists, untracked): ${e.to} — refusing to overwrite a file lunora didn't add (use --overwrite to force)`),{kind:"skipped",path:c}):v===h?m("update"):v===b(u)?(o.warn(`skip (locally edited): ${e.to}`),{kind:"skipped",path:c}):($(`${c}.new`,u,"utf8"),o.warn(`conflict: ${e.to} has local edits and an upstream update — wrote ${e.to}.new (use --overwrite to take theirs)`),{kind:"skipped",path:c})},rt=(e,t,n,r,o,s,a={},i=!1)=>e.merge==="schema-extension"?et(e,t,n,r,o,a.diff===!0,i):nt(e,t,n,r,o,s,a,i),D=["src/server.ts","src/server/index.ts","src/server/index.tsx","src/index.ts","src/worker.ts"],ot=e=>{const t=le(e);if(t===void 0)return;const{parsed:n}=pe(t);return typeof n?.main=="string"?n.main:void 0},st=e=>{const t=ot(e),n=t===void 0?D:[t,...D];for(const r of n){const o=l(e,r);if(!p(o))continue;const s=g(o,"utf8");if(!s.includes("createShardDO(")){if(r===t)break;continue}return{entryPath:o,main:r,source:s}}},it=(e,t,n)=>{const r=L(w(e),l(t,"lunora",n)).replaceAll("\\","/");return r.startsWith(".")?r:`./${r}`},at=(e,t)=>{for(const n of e){const r=`Add \`export * from "${`./lunora/${n.module}.js`}"\` to your worker entry`,o=n.comment?` (${n.comment})`:"";t.warn(`${r}${o}`)}return 0},ct=(e,t,n,r)=>{const o=[];for(const s of e){const a=it(t,n,s.module),i=a.replaceAll(/[.*+?^${}()|[\]\\]/g,String.raw`\$&`);new RegExp(String.raw`export\s+\*\s+from\s+["']${i}\.js["']`,"u").test(r)||(s.comment&&o.push(`
|
|
11
|
+
// ${s.comment}`),o.push(`export * from "${a}.js";`))}return o},ut=(e,t,n,r)=>{if(e.length===0)return 0;const o=st(t);if(o===void 0)return at(e,n);const s=ct(e,o.entryPath,t,o.source);if(s.length===0)return 0;if(r){for(const i of s)i!==""&&n.info(`~ entrypoint: ${i}`);return s.length}const a=o.source.endsWith(`
|
|
12
|
+
`)?"":`
|
|
13
|
+
`;return $(o.entryPath,`${o.source}${a}${s.join(`
|
|
14
|
+
`)}
|
|
15
|
+
`,"utf8"),n.success(`wrote ${String(s.length)} entrypoint re-export(s) to ${L(t,o.entryPath)}`),s.length},I=(e,t,n,r={})=>{const o=[],s=[],a=[],i=[],c=Ze(t),u=qe(t);for(const{directory:d,manifest:f}of e){for(const h of f.files){const v=rt(h,f.name,d,t,n,c,r,u);(v.kind==="written"?o:s).push(v.path)}if(f.entrypointReexports!==void 0&&ut(f.entrypointReexports,t,n,r.diff===!0),r.diff)continue;const m=Fe(f,t,n,u);a.push(...m.deps),i.push(...m.bindings)}return!r.diff&&Object.keys(c.items).length>0&&Ke(t,c),{bindings:i,deps:a,skipped:s,written:o}},Y="gh:anolilab/lunora/registry",q=/^[A-Za-z0-9][\w-]*$/u,dt=e=>{if(!q.test(e))throw new y("INTERNAL",`invalid registry item name "${e}" — names must match ${q.source} (letters, digits, "-", "_"; no path separators or "..")`)},ft=e=>e.includes("..")?!1:e.startsWith("gh:")||e.startsWith("github:")||e.startsWith("https://"),lt=e=>e.from===void 0&&e.source!==void 0&&e.source.length>0&&!e.allowUnsafeSource&&!ft(e.source),N=(e,t)=>lt(t)?`${e}: refusing --source ${String(t.source)} — only gh:, github:, or https:// sources are allowed (and may not contain ".."). Re-run with --allow-unsafe-source if you really want this.`:void 0,Q=async(e,t,n)=>{const r=oe(l($e(),`lunora-${t}-fetch-`)),o=l(r,t);n.info(`fetching ${e}`);try{const s=await he(e,{cwd:r,dir:o,force:!0,install:!1,silent:!0});return n.info(s.commit?`resolved ${s.source} @ ${s.commit}`:`resolved ${s.source}`),{cleanup:()=>{O(r,{force:!0,recursive:!0})},directory:o}}catch(s){throw O(r,{force:!0,recursive:!0}),s}},P=new WeakMap,X=async e=>{const t=P.get(e);if(t!==void 0)return t;const n=e.source!==void 0&&e.source.length>0?Promise.resolve(B(e.ref)):Re(e.ref,e.logger);return P.set(e,n),n},ee=async(e,t)=>{if(dt(e),t.from!==void 0){const r=l(t.from,e);if(!p(r))throw new y("INTERNAL",`registry item not found in local source: ${r}`);return{cleanup:()=>{},directory:r}}const n=t.source??Y;return Q(`${n}/${e}#${await X(t)}`,"item",t.logger)},pt=async e=>{if(e.from!==void 0){if(!p(e.from))throw new y("INTERNAL",`registry root not found: ${e.from}`);return{cleanup:()=>{},root:e.from}}const t=e.source??Y,{cleanup:n,directory:r}=await Q(`${t}#${await X(e)}`,"registry",e.logger);return{cleanup:n,root:r}},te=(e,t)=>{const n=JSON.parse(g(l(e,"registry.json"),"utf8"));return ye(n,t)},gt=async(e,t)=>{const n=[],r=[],o=new Set,s=new Set,a=async i=>{if(o.has(i))return;if(s.has(i))throw new y("INTERNAL",`cyclic registry dependency detected at "${i}"`);s.add(i);const{cleanup:c,directory:u}=await ee(i,t);r.push(c);const d=te(u,i);for(const f of d.requires??[])await a(f);s.delete(i),o.add(i),n.push({directory:u,manifest:d})};try{for(const i of e)await a(i)}catch(i){for(const c of r)c();throw i}return{cleanups:r,items:n}},k=()=>({bindings:[],code:0,deps:[],skipped:[],written:[]}),Jt=(e,t,n,r,o)=>e.bindings?{...e,bindings:e.bindings.map(s=>{if(s.path[0]!==t||!Array.isArray(s.value))return s;const a=s.value;return{...s,value:a.map(i=>typeof i=="object"&&i!==null&&i[n.key]===n.value?{...i,[r]:o}:i)}})}:e,ne=(e,t)=>{const n=t.title??t.description;e.info(`plan: ${t.name}${n?` — ${n}`:""}`);for(const s of t.files)e.info(` file ${s.to} (${s.merge})`);const r=new Map,o=s=>{const a=r.get(s);if(a!==void 0)return a;const i=C(s);return r.set(s,i),i};for(const[s,a]of Object.entries(t.deps??{}))e.info(` dep ${s}@${o(a)}`);for(const[s,a]of Object.entries(t.devDependencies??{}))e.info(` dev ${s}@${o(a)}`);for(const s of t.bindings??[])e.info(` bind ${s.path.join(".")} = ${JSON.stringify(s.value)}`);for(const s of t.envVars??[]){const a=s.secret?" (secret)":` = ${JSON.stringify(s.value??"")}`;e.info(` env ${s.name}${a}`)}for(const s of t.entrypointReexports??[]){const a=`./lunora/${s.module}`,i=s.comment?` // ${s.comment}`:"";e.info(` entry ${a}${i}`)}},mt=e=>{const t=e.map(({manifest:n})=>({bindings:(n.bindings??[]).map(r=>({path:r.path.join("."),value:r.value})),deps:Object.keys(n.deps??{}),devDependencies:Object.keys(n.devDependencies??{}),entrypointReexports:(n.entrypointReexports??[]).map(r=>({module:r.module,...r.comment?{comment:r.comment}:{}})),envVars:(n.envVars??[]).map(r=>({name:r.name,...r.secret?{secret:!0}:{value:r.value??""}})),files:n.files.map(r=>({merge:r.merge,to:r.to})),name:n.name,requires:n.requires??[],title:n.title}));process.stdout.write(`${JSON.stringify({items:t},void 0,2)}
|
|
16
|
+
`)},$t=(e,t,n,r,o)=>{o.success(`add complete: ${String(n)} written, ${String(r)} skipped`),o.info("next steps:"),o.info(" lunora codegen # regenerate _generated/ so the new tables/functions appear"),t.length>0&&o.info(" pnpm install # install newly-added dependencies");for(const{manifest:s}of e)s.docs&&o.info(`${s.name}: ${s.docs}`)},ht=async e=>{const t=k(),n=N("list",e);if(n)return e.logger.error(n),{...t,code:1};let r=()=>{};try{const o=await pt(e);r=o.cleanup;const s=de(o.root);if(e.json)return process.stdout.write(`${JSON.stringify(s,void 0,2)}
|
|
17
|
+
`),t;e.logger.info(`available registry items (${String(s.length)}):`);for(const a of s)e.logger.info(` ${a.name}${a.description?` — ${a.description}`:""}`);return t}catch(o){return e.logger.error(`list failed: ${o instanceof Error?o.message:String(o)}`),{...t,code:1}}finally{r()}},Dt=async e=>{const t=e.cwd??process.cwd(),n=k();if(e.list)return ht(e);if(e.names.length===0)return e.logger.error("add requires at least one item name. Usage: lunora registry add <name> [...names]"),{...n,code:1};const r=N("add",e);if(r)return e.logger.error(r),{...n,code:1};let o=[];try{const{cleanups:s,items:a}=await gt(e.names,e);o=s;const{transformManifest:i}=e,c=i?a.map(h=>({...h,manifest:i(h.manifest)})):a;for(const{manifest:h}of c)ne(e.logger,h);if(e.json&&mt(c),e.dryRun)return e.logger.info("dry-run: stopping before any files are written"),n;if(e.diff)return I(c,t,e.logger,{diff:!0}),e.logger.info("diff: preview only — re-run without --diff to apply"),n;if(!await He(c,e))return{...n,code:1};const{bindings:u,deps:d,skipped:f,written:m}=I(c,t,e.logger,{overwrite:e.overwrite});return $t(c,d,m.length,f.length,e.logger),{bindings:u,code:0,deps:d,skipped:f,written:m}}catch(s){return e.logger.error(`add failed: ${s instanceof Error?s.message:String(s)}`),{...n,code:1}}finally{for(const s of o)s()}},It=async e=>{const t=k();if(e.names.length===0)return e.logger.error("view requires an item name. Usage: lunora registry view <name>"),{...t,code:1};const n=N("view",e);if(n)return e.logger.error(n),{...t,code:1};const r=[];try{for(const o of e.names){const{cleanup:s,directory:a}=await ee(o,e);r.push(s);const i=te(a,o);ne(e.logger,i);for(const c of i.files){e.logger.info(`--- ${c.to} (${c.merge}) ---`);const u=g(l(a,c.from),"utf8");for(const d of u.split(`
|
|
18
|
+
`))e.logger.info(d)}}return t}catch(o){return e.logger.error(`view failed: ${o instanceof Error?o.message:String(o)}`),{...t,code:1}}finally{for(const o of r)o()}},qt=async e=>{const t=k(),n=e.from;if(n===void 0)return e.logger.error("registry build requires --from <registry root>"),{...t,code:1};if(!p(n))return e.logger.error(`registry root not found: ${n}`),{...t,code:1};const r=fe(n),o=e.out??l(n,"index.json");if(e.check){const s=p(o)?JSON.parse(g(o,"utf8")):{items:[]};return JSON.stringify(s.items??[])!==JSON.stringify(r.items)?(e.logger.error(`registry: ${o} is stale — run \`lunora registry build\` to regenerate it`),{...t,code:1}):(e.logger.success(`registry: ${o} is up to date (${String(r.items.length)} items)`),t)}return $(o,`${JSON.stringify({$schema:"./schema/registry.schema.json",...r},void 0,4)}
|
|
19
|
+
`,"utf8"),e.logger.success(`registry: wrote ${o} (${String(r.items.length)} items)`),t};export{It as D,Ee as L,_t as P,ht as R,Re as b,Jt as d,B as g,Dt as k,qt as q};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import"node:fs";import"@visulima/path";import{k as d,q as i,R as s,D as t}from"./commands-C5pu77HK.mjs";import"./buildRegistryIndex-DwySASBu.mjs";export{d as runAddCommand,i as runBuildIndexCommand,s as runListCommand,t as runRegistryViewCommand};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{d as r}from"./commands-
|
|
1
|
+
import{d as r}from"./commands-C5pu77HK.mjs";const o=[{description:"Email + password on better-auth (default)",label:"Email & password",value:"auth"},{description:"Clerk-hosted auth",label:"Clerk",value:"auth-clerk"},{description:"Auth0 (OIDC)",label:"Auth0",value:"auth-auth0"}],n="auth",O=async a=>await a("Which auth provider?",o,{default:n})??n,S="mail",y=[{description:"Next, react-router, TanStack Start, Astro islands",label:"React",value:"auth-ui-react"},{description:"Nuxt, Vue + Vite",label:"Vue",value:"auth-ui-vue"},{description:"SvelteKit, Svelte + Vite",label:"Svelte",value:"auth-ui-svelte"},{description:"TanStack Start Solid, Solid + Vite",label:"Solid",value:"auth-ui-solid"},{description:"Analog",label:"Angular",value:"auth-ui-angular"}],x="auth-ui-react",d=a=>Object.hasOwn(a,"react-native")||Object.hasOwn(a,"@lunora/react-native")||Object.hasOwn(a,"expo"),_=a=>{const e=t=>Object.hasOwn(a,t);if(!d(a)){if(e("@lunora/react"))return"auth-ui-react";if(e("@lunora/vue"))return"auth-ui-vue";if(e("@lunora/svelte"))return"auth-ui-svelte";if(e("@lunora/solid"))return"auth-ui-solid";if(e("@lunora/angular"))return"auth-ui-angular";if(e("react")||e("next"))return"auth-ui-react";if(e("vue")||e("nuxt"))return"auth-ui-vue";if(e("svelte")||e("@sveltejs/kit"))return"auth-ui-svelte";if(e("solid-js"))return"auth-ui-solid";if(e("@angular/core"))return"auth-ui-angular"}},A=a=>{const e=a.trim();if(e==="")return;const t=e.toLowerCase();return t==="auth-ui"||t==="auth-ui-"?{kind:"auth-ui"}:t==="auth"?{kind:"auth"}:t==="email"||t==="mail"?{kind:"email"}:{item:t,kind:"item"}},c=/[^a-z0-9]+/u,u=(a,e,t)=>{let i=a.toLowerCase().split(c).filter(Boolean).join("-").slice(0,t);return i.endsWith("-")&&(i=i.slice(0,-1)),i.length>=e?i:void 0},h="DB",v="Name your D1 database (run `wrangler d1 create` to get its id, then put it in wrangler.jsonc)",l=a=>u(a,1,64),f="lunora-db",b=a=>l(`${a}-db`)??f,V=async(a,e)=>{const t=b(e);return l(await a(v,{default:t,placeholder:t}))??t},C=(a,e)=>r(a,"d1_databases",{key:"binding",value:h},"database_name",e),m="SEND_EMAIL",D="Verified destination email for production delivery (blank = set it later in wrangler.jsonc)",p=a=>{const e=a.trim();if(e.length===0||e.includes(" "))return!1;const t=e.indexOf("@");if(t<=0||t!==e.lastIndexOf("@"))return!1;const i=e.slice(t+1);return i.length>=3&&i.includes(".")&&!i.startsWith(".")&&!i.endsWith(".")},N=(a,e)=>{const t=a.trim();if(t!==""){if(!p(t)){e(`"${t}" doesn't look like an email — leaving the placeholder; set destination_address in wrangler.jsonc.`);return}return t}},E=(a,e)=>r(a,"send_email",{key:"name",value:m},"destination_address",e),$="UPLOADS",g="Name your R2 bucket (you can rename it in wrangler.jsonc later)",s=a=>u(a,3,63),k="lunora-uploads",w=a=>s(`${a}-uploads`)??k,L=async(a,e)=>{const t=w(e);return s(await a(g,{default:t,placeholder:t}))??t},W=(a,e)=>r(a,"r2_buckets",{key:"binding",value:$},"bucket_name",e);export{N as a,D as b,l as c,A as d,b as e,V as f,n as g,_ as h,s as i,y as j,o as k,S as l,E as m,O as n,w as o,W as p,C as q,d as r,x as s,L as u};
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@lunora/cli",
|
|
3
|
-
"version": "1.0.0-alpha.
|
|
3
|
+
"version": "1.0.0-alpha.129",
|
|
4
4
|
"description": "The Lunora CLI: init, dev, deploy, codegen, run, reset, and migrate commands",
|
|
5
5
|
"keywords": [
|
|
6
6
|
"agent-skills",
|
|
@@ -52,16 +52,16 @@
|
|
|
52
52
|
},
|
|
53
53
|
"dependencies": {
|
|
54
54
|
"@bomb.sh/tab": "0.0.21",
|
|
55
|
-
"@lunora/advisor": "1.0.0-alpha.
|
|
56
|
-
"@lunora/bindings": "1.0.0-alpha.
|
|
57
|
-
"@lunora/codegen": "1.0.0-alpha.
|
|
58
|
-
"@lunora/config": "1.0.0-alpha.
|
|
59
|
-
"@lunora/container": "1.0.0-alpha.
|
|
60
|
-
"@lunora/d1": "1.0.0-alpha.
|
|
61
|
-
"@lunora/errors": "1.0.0-alpha.
|
|
62
|
-
"@lunora/mcp": "1.0.0-alpha.
|
|
63
|
-
"@lunora/runtime": "1.0.0-alpha.
|
|
64
|
-
"@lunora/seed": "1.0.0-alpha.
|
|
55
|
+
"@lunora/advisor": "1.0.0-alpha.59",
|
|
56
|
+
"@lunora/bindings": "1.0.0-alpha.15",
|
|
57
|
+
"@lunora/codegen": "1.0.0-alpha.81",
|
|
58
|
+
"@lunora/config": "1.0.0-alpha.106",
|
|
59
|
+
"@lunora/container": "1.0.0-alpha.18",
|
|
60
|
+
"@lunora/d1": "1.0.0-alpha.55",
|
|
61
|
+
"@lunora/errors": "1.0.0-alpha.10",
|
|
62
|
+
"@lunora/mcp": "1.0.0-alpha.51",
|
|
63
|
+
"@lunora/runtime": "1.0.0-alpha.48",
|
|
64
|
+
"@lunora/seed": "1.0.0-alpha.55",
|
|
65
65
|
"@visulima/cerebro": "3.0.0",
|
|
66
66
|
"@visulima/error": "6.0.0",
|
|
67
67
|
"@visulima/fs": "5.0.5",
|
|
@@ -1,8 +0,0 @@
|
|
|
1
|
-
import{createWriteStream as x,createReadStream as N}from"node:fs";import{unlink as I,stat as E}from"node:fs/promises";import{LunoraError as S}from"@lunora/errors";import{l as k}from"./admin-token-DV5A9T5b.mjs";import{u as O}from"./admin-url-Ca-KI3d_.mjs";const A="/_lunora/admin/export",_="/_lunora/admin/import",P=500,L=t=>{if(t===void 0)return;const r=t.split(",").map(o=>o.trim()).filter(o=>o.length>0);return r.length>0?r:void 0},T=async(t,r)=>{t.write(r)||await new Promise(o=>{t.once("drain",o)})},R=async(t,r)=>{const o=t.getReader(),u=new TextDecoder;let s=0,g=0,e="",a=!1;try{for(;!a;){const c=await o.read();if(a=c.done,c.value===void 0)continue;s+=c.value.length,e+=u.decode(c.value,{stream:!0});let l=e.indexOf(`
|
|
2
|
-
`);for(;l!==-1;){g+=1;const n=`${e.slice(0,l)}
|
|
3
|
-
`;await T(r,n),e=e.slice(l+1),l=e.indexOf(`
|
|
4
|
-
`)}}return e.length>0&&(g+=1,await T(r,`${e}
|
|
5
|
-
`)),{bytes:s,rows:g}}finally{o.releaseLock()}},j=async(t,r)=>{if(r!==void 0){t.destroy();try{await I(r)}catch{}}},B=async t=>{if(t.prod&&t.url===void 0)return t.logger.error("--prod requires an explicit --url (refusing to export from the implicit localhost worker)"),{bytes:0,code:1,rows:0};const r=O(t.url,t.logger,t.cwd);if(r===void 0)return{bytes:0,code:1,rows:0};const{token:o}=k({cwd:t.cwd??process.cwd(),token:t.token,url:r});if(!o)return t.logger.error("admin token required — pass --token, set LUNORA_ADMIN_TOKEN, or add it to .dev.vars (local targets only)"),{bytes:0,code:1,rows:0};const u=`${r}${A}`,s=L(t.tables),g=t.fetchImpl??globalThis.fetch;if(typeof g!="function")throw new TypeError("no fetch implementation available — pass fetchImpl or run on Node >= 18");t.logger.info(`POST ${u} -> export${s?` (tables: ${s.join(",")})`:""}`);const e=await g(u,{body:JSON.stringify(s?{tables:s}:{}),headers:{authorization:`Bearer ${o}`,"content-type":"application/json"},method:"POST"});if(!e.ok){const d=await e.text();return t.logger.error(`export failed: HTTP ${String(e.status)}: ${d}`),{bytes:0,code:1,rows:0}}if(!e.body)return t.logger.error("export response carried no body"),{bytes:0,code:1,rows:0};const a=t.out===void 0||t.out==="-"?void 0:t.out,c=a===void 0?process.stdout:x(a,{encoding:"utf8"});let l,n;try{({bytes:l,rows:n}=await R(e.body,c))}catch(d){throw await j(c,a),d}return a!==void 0&&(await new Promise((d,y)=>{c.end(w=>{w?y(w):d()})}),t.logger.success(`wrote ${String(n)} rows to ${a} (${String(l)} bytes)`)),{bytes:l,code:0,rows:n}},q=async t=>{if(t.prod&&t.url===void 0){t.logger.error("--prod requires an explicit --url (refusing to import to the implicit localhost worker)");return}if(t.prod&&t.yes!==!0){t.logger.error("import --prod bulk-writes production. Re-run with --yes to confirm.");return}const r=O(t.url,t.logger,t.cwd);if(r===void 0)return;const{token:o}=k({cwd:t.cwd??process.cwd(),token:t.token,url:r});if(!o){t.logger.error("admin token required — pass --token, set LUNORA_ADMIN_TOKEN, or add it to .dev.vars (local targets only)");return}try{if(!(await E(t.file)).isFile()){t.logger.error(`not a file: ${t.file}`);return}}catch(s){const g=s instanceof Error?s.message:String(s);t.logger.error(`failed to stat ${t.file}: ${g}`);return}const u=t.fetchImpl??globalThis.fetch;if(typeof u!="function")throw new TypeError("no fetch implementation available — pass fetchImpl or run on Node >= 18");return{fetchImpl:u,requestUrl:`${r}${_}`,token:o}},F=async t=>{const r=await q(t);if(r===void 0)return{body:void 0,code:1,inserted:0};const{fetchImpl:o,requestUrl:u,token:s}=r,g=t.batchSize??P;t.logger.info(`POST ${u} -> import ${t.file}`);const e=N(t.file,{encoding:"utf8"}),a={},c=[];let l=0,n="",d=[],y=0;const w=async()=>{if(d.length===0)return;const p=d.join(`
|
|
6
|
-
`);d=[];const f=await o(u,{body:p,headers:{authorization:`Bearer ${s}`,"content-type":"application/x-ndjson"},method:"POST"});if(!f.ok){const m=await f.text().catch(()=>"<no body>");throw new S("INTERNAL",`import batch failed (HTTP ${String(f.status)}): ${m}`)}const i=await f.json();if(i.inserted)for(const[m,h]of Object.entries(i.inserted))a[m]=(a[m]??0)+h;Array.isArray(i.errors)&&c.push(...i.errors),typeof i.conflicts=="number"&&(l+=i.conflicts)},b=p=>{const f=p.trim();if(f.length===0)return;if(y+=1,t.table===void 0){d.push(f);return}let i;try{i=JSON.parse(f)}catch(m){const h=m instanceof Error?m.message:String(m);throw new S("INTERNAL",`invalid JSON on line ${String(y)}: ${h}`,{cause:m})}d.push(JSON.stringify({doc:i,table:t.table}))};for await(const p of e){const f=typeof p=="string"?p:p.toString("utf8");n+=f;let i=n.indexOf(`
|
|
7
|
-
`);for(;i!==-1;)b(n.slice(0,i)),n=n.slice(i+1),i=n.indexOf(`
|
|
8
|
-
`),d.length>=g&&await w()}n.length>0&&b(n),await w();const $=Object.values(a).reduce((p,f)=>p+f,0),v={conflicts:l,errors:c,inserted:a};return t.logger.info(JSON.stringify(v,void 0,2)),t.logger.success(`imported ${String($)} rows (${String(l)} conflicts, ${String(c.length)} errors)`),{body:v,code:c.length>0?1:0,inserted:$}};export{P as DEFAULT_IMPORT_BATCH_SIZE,B as runExportCommand,F as runImportCommand};
|
|
@@ -1,3 +0,0 @@
|
|
|
1
|
-
import{mkdirSync as O,readFileSync as b,lstatSync as R,writeFileSync as A}from"node:fs";import{join as c,dirname as h}from"node:path";import{fileURLToPath as B}from"node:url";import{resolveHint as L,isLunoraError as w,flattenHint as D,findSolutionByMessage as j}from"@lunora/errors";import{createCerebro as E}from"@visulima/cerebro";import C from"@visulima/cerebro/command/completion";import I from"@visulima/cerebro/command/version";import{p as l}from"./api-spec-BENwiyUa.mjs";import{g as s}from"./deploy-target-Dvr9vxpR.mjs";import{createLogger as k}from"./createLogger--C3x1FNE.mjs";import{VisulimaError as _,renderError as P}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 auth-ui","Add copy-in auth screens for your framework (auto-detected)"],["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}]},y="lunora.advisor.map.json",U={description:"Score your app's advisor findings into a health map, and gate CI on it",examples:[["lunora advisor","Score the app and write lunora.advisor.map.json"],["lunora advisor --all","Show every procedure as a check matrix"],["lunora advisor --entry messages#sendMessage","Inspect one procedure"],["lunora advisor --min-score 80","Exit non-zero when the score drops below 80"],["lunora advisor --baseline","Fail on any regression against the committed map"]],group:"Develop",loader:()=>import("../packem_chunks/handler21.mjs").then(e=>({default:e.execute})),name:"advisor",options:[{description:"Show every procedure as a check matrix, not just the ones with findings",name:"all",type:Boolean},{description:`Compare against a committed map and fail on regression (default ${y})`,name:"baseline",type:String},{description:"Inspect a single procedure by `file#exportName`",name:"entry",type:String},{description:"Output format: pretty (default) or json",name:"format",type:String},{description:"Exit non-zero when the global score is below this value (0-100)",name:"min-score",type:String},{description:`Where to write the map (default ${y})`,name:"out",type:String},{description:"Write the map artifact to disk (default true; use --no-write to skip)",name:"write",type:Boolean}]},M={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}]},W={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}]},J={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: ${l} (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},s]},K={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: ${l} (default openapi)`,name:"api-spec",type:String},{description:"Output format: pretty (default) or json",name:"format",type:String},s]},q={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}]},F={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: ${l} (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},s,{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}]},H={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}]},V={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: ${l} (default openapi)`,name:"api-spec",type:String},{description:"Studio server port (default 6173)",name:"port",type:Number},s,{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}]},z={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"},G={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:[]},Y={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}]},Q={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}]},X={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}]},ee={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}]},te={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}]},re={description:"Scaffold lunora/schema.ts (and list/get procedures) from an existing Postgres or MySQL database",examples:[["lunora introspect --url postgres://localhost/shop","Scaffold a schema + procedures from every table"],["lunora introspect --tables users,orders","Introspect only these tables (DATABASE_URL is read by default)"],["lunora introspect --dry-run","Print what would be written without touching the filesystem"],["lunora introspect --no-procedures --force","Regenerate just the schema, overwriting the existing file"]],group:"Data",loader:()=>import("../packem_chunks/handler23.mjs").then(e=>({default:e.execute})),name:"introspect",options:[{description:"Database connection string (default: $DATABASE_URL)",name:"url",type:String},{description:"Postgres schema (default `public`) or MySQL database name",name:"schema",type:String},{description:"Comma-separated table allow-list (default: every base table)",name:"tables",type:String},{description:"Also emit list/get procedure modules per table (default true; --no-procedures to skip)",name:"procedures",type:Boolean},{description:"Overwrite files that already exist",name:"force",type:Boolean},{description:"Print what would be written without writing it",name:"dry-run",type:Boolean}]},oe={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}]},ne={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/handler22.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},s,{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}]},ae={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/handler24.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}]},ie={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}]},se={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: ${l} (default openapi)`,name:"api-spec",type:String},s,{description:"Re-bless the committed schema baseline (lunora/.lunora-schema.json) with the current shape",name:"update-schema-baseline",type:Boolean}]},le={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}]},pe={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}]},de={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}]},ce={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"],["lunora run messages:list --as user_123","Run as an authenticated user (needed when the app gates on identity)"]],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:"Run as this user id — dispatches through the admin-gated `runAs` op so identity-gated apps accept the call",name:"as",type:String},{description:`JSON-encoded extra identity claims to forge alongside --as (e.g. '{"org":"acme"}')`,name:"claims",type:String},{description:"Explicit shard key",name:"shard",type:String},{description:"Worker URL (defaults to the running dev server, else http://localhost:8787)",name:"url",type:String},{description:"Admin bearer for --as (prefer LUNORA_ADMIN_TOKEN or .dev.vars; --token is visible to other local processes via the process table)",name:"token",type:String}]},ue={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"],["lunora seed --seed 7 --now 1785000000000","Byte-identical rows across runs (pins the clock too)"]],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:"Epoch-ms reference for time columns (createdAt, expiresAt, …). Pin it with --seed for byte-identical rows across runs; defaults to now",name:"now",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}]},me={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: ${l} (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},s]},ge={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}]},he={filterStacktrace:()=>!1,hideErrorCodeView:!0},ye=(e,t={})=>{const r=e instanceof Error?e.message:String(e),o=L(w(e)?{code:e.code,hint:e.hint,message:r}:r),n=new _({hint:o===void 0?void 0:D(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="",P(n,he)},fe=(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,p=e[o-1]===t[a-1]?0:1;r[a]=Math.min((r[a-1]??0)+1,i+1,n+p),n=i}}return r[t.length]??0},ve=(e,t)=>{let r,o=Number.POSITIVE_INFINITY;for(const a of t){const i=fe(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},be=e=>`https://registry.npmjs.org/@lunora/cli/${e}`,we=1440*60*1e3,ke=1500,Se="0.0.0",xe=/^v/u,Ne=new Set(["alpha","beta","next"]),u=e=>{const t=e.trim().replace(xe,""),r=t.indexOf("-");return r===-1?{core:t,prerelease:""}:{core:t.slice(0,r),prerelease:t.slice(r+1)}},f=e=>{const[t,r,o]=u(e).core.split(".").map(n=>{const a=Number.parseInt(n,10);return Number.isFinite(a)?a:0});return[t??0,r??0,o??0]},Oe=(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},Re=(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 Oe(a,i)}return 0},Ae=(e,t)=>{const r=f(e),o=f(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 Re(u(e).prerelease,u(t).prerelease)},Be=e=>{const t=u(e).prerelease.split(".")[0]??"";return Ne.has(t)?t:"latest"},Le=(e,t)=>Ae(t,e)>0,De=(e,t,r)=>t-e<r,je=(e,t,r="latest")=>`Update available for @lunora/cli: ${e} → ${t} — run \`pnpm add -D @lunora/cli@${r}\``,S=e=>c(e,"lunora-cli-update.json"),Ee=e=>{const t=e.XDG_CACHE_HOME&&e.XDG_CACHE_HOME.length>0?e.XDG_CACHE_HOME:c(T(),".cache"),r=c(t,"lunora");try{O(r,{mode:448,recursive:!0})}catch{}return r},Ce=e=>{try{const t=JSON.parse(b(S(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{}},v=(e,t)=>{try{const r=S(e);try{if(R(r).isSymbolicLink())return}catch{}A(r,`${JSON.stringify(t)}
|
|
3
|
-
`,"utf8")}catch{}},Ie=async(e,t)=>{try{const r=await e(be(t),{signal:AbortSignal.timeout(ke)});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}},_e=(e,t,r)=>e===Se||!r||t.CI!==void 0||t.LUNORA_NO_UPDATE_NOTIFIER!==void 0,Pe=async e=>{const t=e.env??process.env,r=e.isTTY??process.stdout.isTTY;if(_e(e.current,t,r))return;const o=e.cacheDir??Ee(t),n=(e.now??Date.now)(),a=e.ttlMs??we,i=Be(e.current),p=Ce(o),N=p?.tag??"latest",m=p!==void 0&&N===i?p:void 0;let d=m?.latest;if(m===void 0||!De(m.checkedAt,n,a)){const g=await Ie(e.fetchImpl??globalThis.fetch,i);g===void 0?v(o,{checkedAt:n,latest:e.current,tag:i}):(d=g,v(o,{checkedAt:n,latest:g,tag:i}))}d!==void 0&&Le(e.current,d)&&e.logger.warn(je(e.current,d,i))},Te=["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"],$e=8,Ue=()=>{try{let e=h(B(import.meta.url));for(let t=0;t<$e;t+=1){try{const o=JSON.parse(b(c(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=h(e);if(r===e)break;e=r}}catch{}return"0.0.0"},x=Ue(),Me=[ee,$,V,K,U,J,F,q,se,oe,H,ne,ce,te,pe,ie,Q,X,ue,re,W,me,Z,G,Y,M,ge,z,le,de,ae],We=e=>{const t={value:0},r=E("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:x});for(const o of Me)r.addCommand(o);return r.addCommand(I),r.addCommand(C),{cli:r,exitCode:t}},Je=/Command "(?<name>[^"]+)" not found/u,Ke=e=>{const t=k(),r=e instanceof Error?e.message:String(e),o=Je.exec(r);if(!o?.groups){w(e)||j(r)!==void 0?t.error(ye(e)):t.error(r);return}const n=o.groups.name??"",a=ve(n,Te);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.")},rt=async(e={})=>{const{cli:t,exitCode:r}=We(e);try{await t.run({shouldExitProcess:!1})}catch(o){return Ke(o),1}return await Pe({current:x,logger:k()}),r.value};export{rt as e,y as o,Te as s,x as t};
|
|
@@ -1,19 +0,0 @@
|
|
|
1
|
-
import{existsSync as g,readFileSync as m,writeFileSync as y,mkdirSync as j,mkdtempSync as ee,rmSync as O}from"node:fs";import{dirname as w,join as l,relative as P}from"@visulima/path";import{DEV_VARS_FILE as te,parseDevVariableEntries as re}from"@lunora/config";import{modify as q,applyEdits as L,parse as ne}from"jsonc-parser";import{fileURLToPath as oe}from"node:url";import{LunoraError as v}from"@lunora/errors";import{i as se}from"./tui-prompts-CCt3jm1k.mjs";import{collectCatalog as ie,buildRegistryIndex as ae}from"./buildRegistryIndex-DwySASBu.mjs";import{findWranglerFile as ce,readWranglerJsonc as ue}from"@lunora/config/cloudflare";import{insertSchemaExtension as fe}from"./insertSchemaExtension-DZReBZ4_.mjs";import{createHash as de}from"node:crypto";import{tmpdir as le}from"node:os";import{downloadTemplate as pe}from"giget";import ge from"./parseManifest-x3WsxKHz.mjs";const me="alpha",W="main",$e=new Set(["alpha","beta","next"]),he=/^[\w./@-]+$/,ye=e=>!e.includes("..")&&he.test(e),z=()=>{try{let e=w(oe(import.meta.url));for(let t=0;t<6;t+=1){const r=l(e,"package.json");if(g(r)){const o=JSON.parse(m(r,"utf8"));if(o.name==="@lunora/cli"&&typeof o.version=="string")return o.version}const n=w(e);if(n===e)break;e=n}}catch{}return"0.0.0"},M=e=>{if(e==="0.0.0")return me;const t=e.split("+")[0]??e,r=t.indexOf("-");if(r!==-1){const[n]=t.slice(r+1).split(".");if(n!==void 0&&$e.has(n))return n}return W},U=e=>{if(e!==void 0&&e.length>0){if(!ye(e))throw new v("INTERNAL",`invalid --ref "${e}" — a ref may contain letters, digits, ".", "_", "-", "/", "@" and must not contain "..".`);return e}return M(z())},x="anolilab/lunora",V=/^[0-9a-f]{40}$/iu,B=String.raw`\d+\.\d+\.\d+(?:-[0-9A-Za-z-]+(?:\.[0-9A-Za-z-]+)+)?(?:\+[0-9A-Za-z.-]+)?`,ve=new RegExp(String.raw`^v?${B}$`,"u"),we=new RegExp(String.raw`^(?:@[\w.-]+\/)?[\w.-]+@${B}$`,"u"),be=e=>V.test(e)||ve.test(e)||we.test(e),ke=()=>{const e=process.env.GITHUB_TOKEN??process.env.GH_TOKEN;return e!==void 0&&e.length>0?{authorization:`Bearer ${e}`}:{}},Se=async e=>{try{const t=await fetch(`https://api.github.com/repos/${x}/commits/${encodeURIComponent(e)}`,{headers:{accept:"application/vnd.github+json","user-agent":"lunora-cli",...ke()},signal:AbortSignal.timeout(1e4)});if(!t.ok)return;const r=await t.json();return typeof r.sha=="string"&&V.test(r.sha)?r.sha:void 0}catch{return}},je=async(e,t)=>{const r=U(e);if(be(r))return r;const n=await Se(r);return n===void 0?(t.warn(`could not pin ${x}#${r} to a commit — fetching the UNPINNED branch (set GITHUB_TOKEN if rate-limited).`),r):(t.info(`pinned ${x}#${r} → ${n}`),n)},xe="latest",Ne=(e=z())=>{const t=M(e);return t===W?xe:t},Oe="https://registry.npmjs.org",Re=()=>{const e=process.env.npm_config_registry,t=e!==void 0&&e.length>0?e:Oe;return t.endsWith("/")?t.slice(0,-1):t},Ae=async(e,t)=>{try{const r=await fetch(`${Re()}/${e.replaceAll("/","%2F")}`,{headers:{accept:"application/vnd.npm.install-v1+json"},signal:AbortSignal.timeout(1e4)});return r.ok?(await r.json())["dist-tags"]?.[t]:void 0}catch{return}},jt=async(e,t)=>{const r=new Map;return await Promise.all([...new Set(e)].map(async n=>{const o=await Ae(n,t);o!==void 0&&r.set(n,o)})),r},Ee=e=>{if(!e.startsWith("workspace:"))return e;const t=e.slice(10);return t===""||t==="*"||t==="^"||t==="~"?Ne():t},Te=new Set(["@lunora/client","@lunora/do","@lunora/ratelimit","@lunora/runtime","@lunora/server","@lunora/values"]),_e=/(['"])@lunora\/(client|do|ratelimit|runtime|server|values)(\/[^'"]*)?\1/gu,Je=e=>{const t=l(e,"package.json");if(!g(t))return!1;try{const r=JSON.parse(m(t,"utf8"));return r.dependencies?.lunorash!==void 0||r.devDependencies?.lunorash!==void 0}catch{return!1}},De=e=>e.replaceAll(_e,(t,r,n,o)=>`${r}lunorash/${n}${o??""}${r}`),R=(e,t,r,n="dependencies",o=!1)=>{const s=Object.entries(e);if(s.length===0)return[];const c=l(t,"package.json");if(!g(c))return r.warn(`package.json not found at ${c} — skipping dependency updates`),[];let a=m(c,"utf8");const i=JSON.parse(a),u=[];for(const[f,d]of s){if(o&&Te.has(f)){r.info(`dep provided by the lunorash umbrella, skipping: ${f}`);continue}if(i.dependencies?.[f]!==void 0||i.devDependencies?.[f]!==void 0){r.info(`dep already present: ${f}`);continue}const p=q(a,[n,f],Ee(d),{formattingOptions:{insertSpaces:!0,tabSize:4}});a=L(a,p),u.push(f)}return u.length>0&&(y(c,a,"utf8"),r.success(`added ${String(u.length)} ${n==="devDependencies"?"devDependency(ies)":"dependency(ies)"} to package.json: ${u.join(", ")}`)),u},Ie=(e,t,r)=>{if(e.length===0)return[];const n=l(t,te),o=g(n)?m(n,"utf8"):"",s=new Set(re(o).map(u=>u.key)),c=[],a=[],i=[];for(const u of e)u.secret&&a.push(u.name),!s.has(u.name)&&(u.description&&i.push(`# ${u.description}`),i.push(`${u.name}=${u.secret?"":u.value??""}`),c.push(u.name));if(c.length>0){const u=o===""||o.endsWith(`
|
|
2
|
-
`)?o:`${o}
|
|
3
|
-
`;y(n,`${u}${i.join(`
|
|
4
|
-
`)}
|
|
5
|
-
`,"utf8"),r.success(`scaffolded ${String(c.length)} env var(s) into .dev.vars: ${c.join(", ")}`)}return a.length>0&&r.info(`set secret value(s) locally in .dev.vars, then for production: ${a.map(u=>`wrangler secret put ${u}`).join("; ")}`),c},A=new Set(["ai","analytics_engine_datasets","browser","d1_databases","durable_objects","hyperdrive","kv_namespaces","mtls_certificates","queues","r2_buckets","send_email","services","vars","vectorize","version_metadata","workflows"]),Pe=(e,t,r)=>{if(e.length===0)return[];const n=["wrangler.jsonc","wrangler.json"].map(i=>l(t,i)).find(i=>g(i));if(!n)return r.warn("wrangler.jsonc not found — skipping binding updates"),[];let o=m(n,"utf8");const s=[],c=i=>Array.isArray(i),a=i=>{let u=ne(o);for(const f of i){if(typeof u!="object"||u===null)return;u=u[f]}return u};for(const i of e){const u=i.path[0];if(u===void 0||!A.has(u)){r.warn(`skipping binding "${i.path.join(".")}" — only resource bindings (${[...A].join(", ")}) may be written, not exec/entrypoint keys`);continue}let{value:f}=i;if(c(f)){const p=a(i.path);if(c(p)){const $=new Set(p.map(h=>JSON.stringify(h)));f=[...p,...f.filter(h=>!$.has(JSON.stringify(h)))]}}const d=q(o,[...i.path],f,{formattingOptions:{insertSpaces:!0,tabSize:4}});d.length!==0&&(o=L(o,d),s.push(i.path.join(".")))}return s.length>0&&(y(n,o,"utf8"),r.success(`applied ${String(s.length)} binding(s) to ${n}: ${s.join(", ")}`)),s},qe=(e,t,r,n=!1)=>{const o=[],s=[];return e.deps&&o.push(...R(e.deps,t,r,"dependencies",n)),e.devDependencies&&o.push(...R(e.devDependencies,t,r,"devDependencies",n)),e.bindings&&s.push(...Pe(e.bindings,t,r)),e.envVars&&Ie(e.envVars,t,r),{bindings:s,deps:o}},Le=async(e,t)=>{const r=e.some(({manifest:i})=>Object.keys(i.deps??{}).length>0||Object.keys(i.devDependencies??{}).length>0),n=e.some(({manifest:i})=>(i.bindings??[]).length>0),o=t.source!==void 0&&t.source.length>0;if(!r&&!n&&!o||t.yes)return!0;const s=[];r&&s.push("add dependencies to package.json"),n&&s.push("write wrangler.jsonc bindings"),o&&s.push(`come from a non-default source (${String(t.source)})`);const c=s.join(", ");if(!process.stdin.isTTY&&t.confirm===void 0)return t.logger.error(`add: stdin is not a TTY and the requested items ${c} — re-run with --yes to confirm`),!1;const a=await(t.confirm??se)(`The requested items ${c}. Continue?`);return a||t.logger.info("add: aborted"),a},S=1,We=".lunora-registry.json",F=e=>l(e,"lunora",We),ze=e=>typeof e!="object"||e===null||!("items"in e)?!1:typeof e.items=="object"&&e.items!==null,b=e=>de("sha256").update(e).digest("hex"),Me=e=>{const t=F(e);if(!g(t))return{items:{},version:S};try{const r=JSON.parse(m(t,"utf8"));if(ze(r))return{items:r.items,version:S}}catch{}return{items:{},version:S}},Ue=(e,t)=>{y(F(e),`${JSON.stringify(t,void 0,2)}
|
|
6
|
-
`,"utf8")},E=(e,t,r,n)=>{const o=e.items[t],s=o??{files:{}};o===void 0&&(e.items[t]=s),s.files[r]=b(n)},Ve=(e,t,r)=>e.items[t]?.files[r],T=e=>e===""?[]:e.split(`
|
|
7
|
-
`),Be=(e,t)=>{const r=T(e),n=T(t);let o=0;for(;o<r.length&&o<n.length&&r[o]===n[o];)o+=1;let s=r.length,c=n.length;for(;s>o&&c>o&&r[s-1]===n[c-1];)s-=1,c-=1;if(o===s&&o===c)return[];const a=[];for(let i=Math.max(0,o-3);i<o;i+=1)a.push(` ${r[i]??""}`);for(let i=o;i<s;i+=1)a.push(`- ${r[i]??""}`);for(let i=o;i<c;i+=1)a.push(`+ ${n[i]??""}`);for(let i=c;i<Math.min(n.length,c+3);i+=1)a.push(` ${n[i]??""}`);return a},Fe=/\.[cm]?[jt]sx?$/u,H=(e,t,r)=>{const n=m(l(e,t.from),"utf8");return r&&Fe.test(t.to)?De(n):n},He=(e,t,r,n,o,s,c)=>{const a=l(n,"lunora","schema.ts");if(s)return o.info(`~ would merge .extend(${t}.extension) into lunora/schema.ts (and create ${e.to} if absent)`),{kind:"skipped",path:a};const i=l(n,e.to);g(i)||(j(w(i),{recursive:!0}),y(i,H(r,e,c),"utf8"));const u=c?"lunorash/server":"@lunora/server",f=g(a)?m(a,"utf8"):`import { defineSchema } from "${u}";
|
|
8
|
-
|
|
9
|
-
export const schema = defineSchema({});
|
|
10
|
-
`,d=fe(f,t);if(d.ok)return j(w(a),{recursive:!0}),y(a,d.text,"utf8"),o.success(`merged .extend(${t}.extension) into lunora/schema.ts`),{kind:"written",path:a};if(d.reason==="already-applied")return o.warn(`lunora/schema.ts already extends "${t}" — skipping`),{kind:"skipped",path:a};throw d.reason==="invalid-identifier"?new v("INTERNAL",`schema-extension item "${t}" is not a valid JS identifier — it is spliced into lunora/schema.ts as \`import { ${t} }\` / \`.extend(${t}.extension)\`. Rename the item to a valid identifier (no leading digit, no "-").`):new v("INTERNAL",`schema-extension merge failed for "${t}": ${d.reason}`)},Ge=(e,t,r,n,o)=>{const s=Be(t,r);if(s.length===0){o.info(`= ${e.to} (unchanged)`);return}o.info(`${n?"~":"+"} ${e.to}`);for(const c of s)o.info(` ${c}`)},Ze=(e,t,r,n,o,s,c,a)=>{const i=l(n,e.to),u=H(r,e,a),f=g(i),d=f?m(i,"utf8"):"",p=X=>(j(w(i),{recursive:!0}),y(i,u,"utf8"),E(s,t,e.to,u),o.success(`${X}: ${e.to}`),{kind:"written",path:i});if(c.diff)return Ge(e,d,u,f,o),{kind:"skipped",path:i};if(!f)return p("write");const $=b(d);if($===b(u))return E(s,t,e.to,u),o.warn(`skip (exists): ${e.to}`),{kind:"skipped",path:i};if(c.overwrite)return p("overwrite");const h=Ve(s,t,e.to);return h===void 0?(o.warn(`skip (exists, untracked): ${e.to} — refusing to overwrite a file lunora didn't add (use --overwrite to force)`),{kind:"skipped",path:i}):h===$?p("update"):h===b(u)?(o.warn(`skip (locally edited): ${e.to}`),{kind:"skipped",path:i}):(y(`${i}.new`,u,"utf8"),o.warn(`conflict: ${e.to} has local edits and an upstream update — wrote ${e.to}.new (use --overwrite to take theirs)`),{kind:"skipped",path:i})},Ce=(e,t,r,n,o,s,c={},a=!1)=>e.merge==="schema-extension"?He(e,t,r,n,o,c.diff===!0,a):Ze(e,t,r,n,o,s,c,a),_=["src/server.ts","src/server/index.ts","src/server/index.tsx","src/index.ts","src/worker.ts"],Ke=e=>{const t=ce(e);if(t===void 0)return;const{parsed:r}=ue(t);return typeof r?.main=="string"?r.main:void 0},Ye=e=>{const t=Ke(e),r=t===void 0?_:[t,..._];for(const n of r){const o=l(e,n);if(!g(o))continue;const s=m(o,"utf8");if(!s.includes("createShardDO(")){if(n===t)break;continue}return{entryPath:o,main:n,source:s}}},Qe=(e,t,r)=>{const n=P(w(e),l(t,"lunora",r)).replaceAll("\\","/");return n.startsWith(".")?n:`./${n}`},Xe=(e,t)=>{for(const r of e){const n=`Add \`export * from "${`./lunora/${r.module}.js`}"\` to your worker entry`,o=r.comment?` (${r.comment})`:"";t.warn(`${n}${o}`)}return 0},et=(e,t,r,n)=>{const o=[];for(const s of e){const c=Qe(t,r,s.module),a=c.replaceAll(/[.*+?^${}()|[\]\\]/g,String.raw`\$&`);new RegExp(String.raw`export\s+\*\s+from\s+["']${a}\.js["']`,"u").test(n)||(s.comment&&o.push(`
|
|
11
|
-
// ${s.comment}`),o.push(`export * from "${c}.js";`))}return o},tt=(e,t,r,n)=>{if(e.length===0)return 0;const o=Ye(t);if(o===void 0)return Xe(e,r);const s=et(e,o.entryPath,t,o.source);if(s.length===0)return 0;if(n){for(const a of s)a!==""&&r.info(`~ entrypoint: ${a}`);return s.length}const c=o.source.endsWith(`
|
|
12
|
-
`)?"":`
|
|
13
|
-
`;return y(o.entryPath,`${o.source}${c}${s.join(`
|
|
14
|
-
`)}
|
|
15
|
-
`,"utf8"),r.success(`wrote ${String(s.length)} entrypoint re-export(s) to ${P(t,o.entryPath)}`),s.length},J=(e,t,r,n={})=>{const o=[],s=[],c=[],a=[],i=Me(t),u=Je(t);for(const{directory:f,manifest:d}of e){for(const $ of d.files){const h=Ce($,d.name,f,t,r,i,n,u);(h.kind==="written"?o:s).push(h.path)}if(d.entrypointReexports!==void 0&&tt(d.entrypointReexports,t,r,n.diff===!0),n.diff)continue;const p=qe(d,t,r,u);c.push(...p.deps),a.push(...p.bindings)}return!n.diff&&Object.keys(i.items).length>0&&Ue(t,i),{bindings:a,deps:c,skipped:s,written:o}},G="gh:anolilab/lunora/registry",D=/^[A-Za-z0-9][\w-]*$/u,rt=e=>{if(!D.test(e))throw new v("INTERNAL",`invalid registry item name "${e}" — names must match ${D.source} (letters, digits, "-", "_"; no path separators or "..")`)},nt=e=>e.includes("..")?!1:e.startsWith("gh:")||e.startsWith("github:")||e.startsWith("https://"),ot=e=>e.from===void 0&&e.source!==void 0&&e.source.length>0&&!e.allowUnsafeSource&&!nt(e.source),N=(e,t)=>ot(t)?`${e}: refusing --source ${String(t.source)} — only gh:, github:, or https:// sources are allowed (and may not contain ".."). Re-run with --allow-unsafe-source if you really want this.`:void 0,Z=async(e,t,r)=>{const n=ee(l(le(),`lunora-${t}-fetch-`)),o=l(n,t);r.info(`fetching ${e}`);try{const s=await pe(e,{cwd:n,dir:o,force:!0,install:!1,silent:!0});return r.info(s.commit?`resolved ${s.source} @ ${s.commit}`:`resolved ${s.source}`),{cleanup:()=>{O(n,{force:!0,recursive:!0})},directory:o}}catch(s){throw O(n,{force:!0,recursive:!0}),s}},I=new WeakMap,C=async e=>{const t=I.get(e);if(t!==void 0)return t;const r=e.source!==void 0&&e.source.length>0?Promise.resolve(U(e.ref)):je(e.ref,e.logger);return I.set(e,r),r},K=async(e,t)=>{if(rt(e),t.from!==void 0){const n=l(t.from,e);if(!g(n))throw new v("INTERNAL",`registry item not found in local source: ${n}`);return{cleanup:()=>{},directory:n}}const r=t.source??G;return Z(`${r}/${e}#${await C(t)}`,"item",t.logger)},st=async e=>{if(e.from!==void 0){if(!g(e.from))throw new v("INTERNAL",`registry root not found: ${e.from}`);return{cleanup:()=>{},root:e.from}}const t=e.source??G,{cleanup:r,directory:n}=await Z(`${t}#${await C(e)}`,"registry",e.logger);return{cleanup:r,root:n}},Y=(e,t)=>{const r=JSON.parse(m(l(e,"registry.json"),"utf8"));return ge(r,t)},it=async(e,t)=>{const r=[],n=[],o=new Set,s=new Set,c=async a=>{if(o.has(a))return;if(s.has(a))throw new v("INTERNAL",`cyclic registry dependency detected at "${a}"`);s.add(a);const{cleanup:i,directory:u}=await K(a,t);n.push(i);const f=Y(u,a);for(const d of f.requires??[])await c(d);s.delete(a),o.add(a),r.push({directory:u,manifest:f})};try{for(const a of e)await c(a)}catch(a){for(const i of n)i();throw a}return{cleanups:n,items:r}},k=()=>({bindings:[],code:0,deps:[],skipped:[],written:[]}),xt=(e,t,r,n,o)=>e.bindings?{...e,bindings:e.bindings.map(s=>{if(s.path[0]!==t||!Array.isArray(s.value))return s;const c=s.value;return{...s,value:c.map(a=>typeof a=="object"&&a!==null&&a[r.key]===r.value?{...a,[n]:o}:a)}})}:e,Q=(e,t)=>{const r=t.title??t.description;e.info(`plan: ${t.name}${r?` — ${r}`:""}`);for(const n of t.files)e.info(` file ${n.to} (${n.merge})`);for(const[n,o]of Object.entries(t.deps??{}))e.info(` dep ${n}@${o}`);for(const[n,o]of Object.entries(t.devDependencies??{}))e.info(` dev ${n}@${o}`);for(const n of t.bindings??[])e.info(` bind ${n.path.join(".")} = ${JSON.stringify(n.value)}`);for(const n of t.envVars??[]){const o=n.secret?" (secret)":` = ${JSON.stringify(n.value??"")}`;e.info(` env ${n.name}${o}`)}for(const n of t.entrypointReexports??[]){const o=`./lunora/${n.module}`,s=n.comment?` // ${n.comment}`:"";e.info(` entry ${o}${s}`)}},at=e=>{const t=e.map(({manifest:r})=>({bindings:(r.bindings??[]).map(n=>({path:n.path.join("."),value:n.value})),deps:Object.keys(r.deps??{}),devDependencies:Object.keys(r.devDependencies??{}),entrypointReexports:(r.entrypointReexports??[]).map(n=>({module:n.module,...n.comment?{comment:n.comment}:{}})),envVars:(r.envVars??[]).map(n=>({name:n.name,...n.secret?{secret:!0}:{value:n.value??""}})),files:r.files.map(n=>({merge:n.merge,to:n.to})),name:r.name,requires:r.requires??[],title:r.title}));process.stdout.write(`${JSON.stringify({items:t},void 0,2)}
|
|
16
|
-
`)},ct=(e,t,r,n,o)=>{o.success(`add complete: ${String(r)} written, ${String(n)} skipped`),o.info("next steps:"),o.info(" lunora codegen # regenerate _generated/ so the new tables/functions appear"),t.length>0&&o.info(" pnpm install # install newly-added dependencies");for(const{manifest:s}of e)s.docs&&o.info(`${s.name}: ${s.docs}`)},ut=async e=>{const t=k(),r=N("list",e);if(r)return e.logger.error(r),{...t,code:1};let n=()=>{};try{const o=await st(e);n=o.cleanup;const s=ie(o.root);if(e.json)return process.stdout.write(`${JSON.stringify(s,void 0,2)}
|
|
17
|
-
`),t;e.logger.info(`available registry items (${String(s.length)}):`);for(const c of s)e.logger.info(` ${c.name}${c.description?` — ${c.description}`:""}`);return t}catch(o){return e.logger.error(`list failed: ${o instanceof Error?o.message:String(o)}`),{...t,code:1}}finally{n()}},Nt=async e=>{const t=e.cwd??process.cwd(),r=k();if(e.list)return ut(e);if(e.names.length===0)return e.logger.error("add requires at least one item name. Usage: lunora registry add <name> [...names]"),{...r,code:1};const n=N("add",e);if(n)return e.logger.error(n),{...r,code:1};let o=[];try{const{cleanups:s,items:c}=await it(e.names,e);o=s;const{transformManifest:a}=e,i=a?c.map($=>({...$,manifest:a($.manifest)})):c;for(const{manifest:$}of i)Q(e.logger,$);if(e.json&&at(i),e.dryRun)return e.logger.info("dry-run: stopping before any files are written"),r;if(e.diff)return J(i,t,e.logger,{diff:!0}),e.logger.info("diff: preview only — re-run without --diff to apply"),r;if(!await Le(i,e))return{...r,code:1};const{bindings:u,deps:f,skipped:d,written:p}=J(i,t,e.logger,{overwrite:e.overwrite});return ct(i,f,p.length,d.length,e.logger),{bindings:u,code:0,deps:f,skipped:d,written:p}}catch(s){return e.logger.error(`add failed: ${s instanceof Error?s.message:String(s)}`),{...r,code:1}}finally{for(const s of o)s()}},Ot=async e=>{const t=k();if(e.names.length===0)return e.logger.error("view requires an item name. Usage: lunora registry view <name>"),{...t,code:1};const r=N("view",e);if(r)return e.logger.error(r),{...t,code:1};const n=[];try{for(const o of e.names){const{cleanup:s,directory:c}=await K(o,e);n.push(s);const a=Y(c,o);Q(e.logger,a);for(const i of a.files){e.logger.info(`--- ${i.to} (${i.merge}) ---`);const u=m(l(c,i.from),"utf8");for(const f of u.split(`
|
|
18
|
-
`))e.logger.info(f)}}return t}catch(o){return e.logger.error(`view failed: ${o instanceof Error?o.message:String(o)}`),{...t,code:1}}finally{for(const o of n)o()}},Rt=async e=>{const t=k(),r=e.from;if(r===void 0)return e.logger.error("registry build requires --from <registry root>"),{...t,code:1};if(!g(r))return e.logger.error(`registry root not found: ${r}`),{...t,code:1};const n=ae(r),o=e.out??l(r,"index.json");if(e.check){const s=g(o)?JSON.parse(m(o,"utf8")):{items:[]};return JSON.stringify(s.items??[])!==JSON.stringify(n.items)?(e.logger.error(`registry: ${o} is stale — run \`lunora registry build\` to regenerate it`),{...t,code:1}):(e.logger.success(`registry: ${o} is up to date (${String(n.items.length)} items)`),t)}return y(o,`${JSON.stringify({$schema:"./schema/registry.schema.json",...n},void 0,4)}
|
|
19
|
-
`,"utf8"),e.logger.success(`registry: wrote ${o} (${String(n.items.length)} items)`),t};export{Ne as L,Nt as M,jt as P,ut as R,je as b,xt as d,U as g,Ot as k,Rt as q};
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import"node:fs";import"@visulima/path";import{M as d,q as i,R as s,k as t}from"./commands-qFGULoQJ.mjs";import"./buildRegistryIndex-DwySASBu.mjs";export{d as runAddCommand,i as runBuildIndexCommand,s as runListCommand,t as runRegistryViewCommand};
|