@lunora/cli 1.0.0-alpha.105 → 1.0.0-alpha.107

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 CHANGED
@@ -1,3 +1,3 @@
1
1
  #!/usr/bin/env node
2
- import{runCli as s}from"./packem_shared/COMMANDS-DRqlsGT2.mjs";try{const r=await s();process.exit(r)}catch(r){process.stderr.write(`${r instanceof Error?r.message:String(r)}
2
+ import{runCli as s}from"./packem_shared/COMMANDS-CExxeifl.mjs";try{const r=await s();process.exit(r)}catch(r){process.stderr.write(`${r instanceof Error?r.message:String(r)}
3
3
  `),process.exit(1)}
package/dist/index.mjs CHANGED
@@ -1 +1 @@
1
- import{COMMANDS as o,VERSION as n,runCli as a}from"./packem_shared/COMMANDS-DRqlsGT2.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-DL87PIEl.mjs";import{runDeployCommand as C}from"./packem_chunks/runDeployCommand.mjs";import{planDevCommand as u,runDevCommand as s}from"./packem_chunks/planDevCommand.mjs";import{runInitCommand as g}from"./packem_chunks/runInitCommand.mjs";import{runMigrateGenerateCommand as T}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 c}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-C8_7nffs.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";import{buildRegistryIndex as J}from"./packem_shared/buildRegistryIndex-DwySASBu.mjs";import{M as $,q as rr,k as er}from"./packem_shared/commands-BhX2Bo9B.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,c as insertSchemaExtension,h as pail,j as parseManifest,u 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,s as runDevCommand,f as runExportCommand,x as runImportCommand,g as runInitCommand,T as runMigrateGenerateCommand,er as runRegistryViewCommand,E as runResetCommand,A as runRpcCommand,q as schemaIrToSnapshot,Y as validateWrangler,Z as validateWranglerConfig,U as validatorKindToSqlType};
1
+ import{COMMANDS as o,VERSION as n,runCli as a}from"./packem_shared/COMMANDS-CExxeifl.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-DL87PIEl.mjs";import{runDeployCommand as C}from"./packem_chunks/runDeployCommand.mjs";import{planDevCommand as u,runDevCommand as s}from"./packem_chunks/planDevCommand.mjs";import{runInitCommand as g}from"./packem_chunks/runInitCommand.mjs";import{runMigrateGenerateCommand as T}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 c}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-C8_7nffs.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";import{buildRegistryIndex as J}from"./packem_shared/buildRegistryIndex-DwySASBu.mjs";import{M as $,q as rr,k as er}from"./packem_shared/commands-BhX2Bo9B.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,c as insertSchemaExtension,h as pail,j as parseManifest,u 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,s as runDevCommand,f as runExportCommand,x as runImportCommand,g as runInitCommand,T as runMigrateGenerateCommand,er as runRegistryViewCommand,E as runResetCommand,A as runRpcCommand,q as schemaIrToSnapshot,Y as validateWrangler,Z as validateWranglerConfig,U as validatorKindToSqlType};
@@ -1,2 +1,2 @@
1
- import{readLinkedProject as m}from"@lunora/config";import{i as g}from"../packem_shared/command-Bjv4VmYA.mjs";import{M as p,P as f}from"../packem_shared/detect-package-manager-B2eIuAiP.mjs";import{defaultSpawner as v}from"../packem_shared/createRecordingSpawner-C8_7nffs.mjs";import{createR2Sql as h}from"@lunora/bindings/r2sql";import{createPipelineLogReader as w}from"@lunora/runtime";const b=new Set(["debug","error","fatal","info","log","trace","warn"]),y=/^\d+$/,c=(r,e)=>{if(r===void 0)return;const t=r.trim();if(y.test(t))return Number(t);const o=Date.parse(t);if(Number.isNaN(o))throw new TypeError(`logs: invalid ${e} "${r}" — pass epoch-millis or an ISO 8601 date`);return o},d=(r,e)=>{if(r!==void 0){if(!b.has(r))throw new TypeError(`logs: invalid ${e} "${r}" — expected one of trace, debug, log, info, warn, error, fatal`);return r}},_=r=>{const e={},t=c(r.since,"--since");t!==void 0&&(e.sinceTs=t);const o=c(r.until,"--until");o!==void 0&&(e.untilTs=o);const s=d(r.level,"--level");s!==void 0&&(e.level=s);const n=d(r.minLevel,"--min-level");if(n!==void 0&&(e.minLevel=n),r.functionPrefix!==void 0&&(e.functionPathPrefix=r.functionPrefix),r.traceId!==void 0&&(e.traceId=r.traceId),r.shardKey!==void 0&&(e.shardKey=r.shardKey),r.userId!==void 0&&(e.userId=r.userId),r.limit!==void 0){const i=Number(r.limit);if(!Number.isFinite(i))throw new TypeError(`logs: invalid --limit "${r.limit}" — expected a number`);e.limit=i}if(r.cursor!==void 0){const i=Number(r.cursor);if(!Number.isFinite(i))throw new TypeError(`logs: invalid --cursor "${r.cursor}" — expected the epoch-millis ts from a prior page's nextCursor`);e.cursor={ts:i}}return e},S=r=>{const e=new Date(r.ts).toISOString(),t=r.level.toUpperCase().padEnd(5);return`${e} ${t} ${r.functionPath} ${r.message}`},L=async r=>{const e=r.environment??process.env,t=e.R2_SQL_ACCOUNT_ID,o=e.R2_SQL_TOKEN,s=e.R2_SQL_BUCKET,n=[];if((t===void 0||t.length===0)&&n.push("R2_SQL_ACCOUNT_ID"),(o===void 0||o.length===0)&&n.push("R2_SQL_TOKEN"),(s===void 0||s.length===0)&&n.push("R2_SQL_BUCKET"),(r.table===void 0||r.table.length===0)&&n.push("--table"),n.length>0)return r.logger.error(`logs --durable: R2 SQL not configured (missing ${n.join(", ")}). The Pipeline must write to an R2 Data Catalog (Iceberg) table, and you must supply R2_SQL_ACCOUNT_ID / R2_SQL_TOKEN / R2_SQL_BUCKET plus --table — see the observability docs.`),{code:1,error:"not configured"};let i;try{i=_(r)}catch(a){return r.logger.error(a instanceof Error?a.message:String(a)),{code:1,error:"invalid option"}}const u=h({accountId:t,apiToken:o,bucket:s,fetch:r.fetch}),l=await w(u,{namespace:r.namespace,table:r.table}).query(i);for(const a of l.rows)process.stdout.write(`${r.ndjson===!0?JSON.stringify(a):S(a)}
2
- `);return l.rows.length===0?r.logger.info("logs --durable: no matching log records"):l.nextCursor!==void 0&&r.logger.info(`logs --durable: more rows available — pass --cursor ${String(l.nextCursor.ts)} for the next page`),{code:0,rows:l.rows}},I=new Set(["json","pretty"]),T=async r=>{const e=r.cwd??process.cwd();if(r.format!==void 0&&!I.has(r.format))return r.logger.error(`logs: unknown --format "${r.format}" — expected pretty | json`),{code:1,descriptor:void 0,error:"invalid format"};const t=["tail"];r.worker!==void 0&&t.push(r.worker);const o=r.env??m(e)?.env;o!==void 0&&t.push("--env",o),r.format!==void 0&&t.push("--format",r.format),r.status!==void 0&&t.push("--status",r.status),r.search!==void 0&&t.push("--search",r.search),r.temporary&&t.push("--temporary");const s=p(f(e),"wrangler",t),n={args:s.args,command:s.command,cwd:e};return r.logger.info(`tailing logs via ${n.command} ${n.args.join(" ")}`),{code:(await(r.spawner??v)(n)).code,descriptor:n}},K=g(({argument:r,cwd:e,logger:t,options:o})=>o.durable===!0?L({cursor:o.cursor,functionPrefix:o.functionPrefix,level:o.level,limit:o.limit,logger:t,minLevel:o.minLevel,namespace:o.namespace,ndjson:o.ndjson===!0,shardKey:o.shardKey,since:o.since,table:o.table,traceId:o.traceId,until:o.until,userId:o.userId}):T({cwd:e,env:o.env,format:o.format,logger:t,search:o.search,status:o.status,temporary:o.temporary===!0,worker:r[0]}));export{K as execute,T as runLogsCommand};
1
+ import{readLinkedProject as p}from"@lunora/config";import{i as f}from"../packem_shared/command-Bjv4VmYA.mjs";import{M as g,P as v}from"../packem_shared/detect-package-manager-B2eIuAiP.mjs";import{defaultSpawner as h}from"../packem_shared/createRecordingSpawner-C8_7nffs.mjs";import{createR2Sql as b}from"@lunora/bindings/r2sql";import{createPipelineLogReader as w}from"@lunora/runtime";const y=new Set(["debug","error","fatal","info","log","trace","warn"]),d=/^\d+$/,c=(r,t)=>{if(r===void 0)return;const o=r.trim();if(d.test(o))return Number(o);const e=Date.parse(o);if(Number.isNaN(e))throw new TypeError(`logs: invalid ${t} "${r}" — pass epoch-millis or an ISO 8601 date`);return e},S=r=>Buffer.from(JSON.stringify(r),"utf8").toString("base64url"),_=r=>{const t=r.trim();if(d.test(t))return{ts:Number(t)};let o;try{o=JSON.parse(Buffer.from(t,"base64url").toString("utf8"))}catch{throw new TypeError(`logs: invalid --cursor "${r}" — expected the token printed by the previous page (or a bare epoch-millis ts)`)}if(typeof o!="object"||o===null||typeof o.ts!="number"||!Number.isFinite(o.ts))throw new TypeError(`logs: invalid --cursor "${r}" — expected the token printed by the previous page (or a bare epoch-millis ts)`);const{ts:e}=o,s=o.seen,n=Array.isArray(s)?s.filter(i=>typeof i=="string"):void 0;return n!==void 0&&n.length>0?{seen:n,ts:e}:{ts:e}},u=(r,t)=>{if(r!==void 0){if(!y.has(r))throw new TypeError(`logs: invalid ${t} "${r}" — expected one of trace, debug, log, info, warn, error, fatal`);return r}},$=r=>{const t={},o=c(r.since,"--since");o!==void 0&&(t.sinceTs=o);const e=c(r.until,"--until");e!==void 0&&(t.untilTs=e);const s=u(r.level,"--level");s!==void 0&&(t.level=s);const n=u(r.minLevel,"--min-level");if(n!==void 0&&(t.minLevel=n),r.functionPrefix!==void 0&&(t.functionPathPrefix=r.functionPrefix),r.traceId!==void 0&&(t.traceId=r.traceId),r.shardKey!==void 0&&(t.shardKey=r.shardKey),r.userId!==void 0&&(t.userId=r.userId),r.limit!==void 0){const i=Number(r.limit);if(!Number.isFinite(i))throw new TypeError(`logs: invalid --limit "${r.limit}" — expected a number`);t.limit=i}return r.cursor!==void 0&&(t.cursor=_(r.cursor)),t},L=r=>{const t=new Date(r.ts).toISOString(),o=r.level.toUpperCase().padEnd(5);return`${t} ${o} ${r.functionPath} ${r.message}`},T=async r=>{const t=r.environment??process.env,o=t.R2_SQL_ACCOUNT_ID,e=t.R2_SQL_TOKEN,s=t.R2_SQL_BUCKET,n=[];if((o===void 0||o.length===0)&&n.push("R2_SQL_ACCOUNT_ID"),(e===void 0||e.length===0)&&n.push("R2_SQL_TOKEN"),(s===void 0||s.length===0)&&n.push("R2_SQL_BUCKET"),(r.table===void 0||r.table.length===0)&&n.push("--table"),n.length>0)return r.logger.error(`logs --durable: R2 SQL not configured (missing ${n.join(", ")}). The Pipeline must write to an R2 Data Catalog (Iceberg) table, and you must supply R2_SQL_ACCOUNT_ID / R2_SQL_TOKEN / R2_SQL_BUCKET plus --table — see the observability docs.`),{code:1,error:"not configured"};let i;try{i=$(r)}catch(a){return r.logger.error(a instanceof Error?a.message:String(a)),{code:1,error:"invalid option"}}const m=b({accountId:o,apiToken:e,bucket:s,fetch:r.fetch}),l=await w(m,{namespace:r.namespace,table:r.table}).query(i);for(const a of l.rows)process.stdout.write(`${r.ndjson===!0?JSON.stringify(a):L(a)}
2
+ `);return l.rows.length===0?r.logger.info("logs --durable: no matching log records"):l.nextCursor!==void 0&&r.logger.info(`logs --durable: more rows available — pass --cursor ${S(l.nextCursor)} for the next page`),{code:0,rows:l.rows}},I=new Set(["json","pretty"]),N=async r=>{const t=r.cwd??process.cwd();if(r.format!==void 0&&!I.has(r.format))return r.logger.error(`logs: unknown --format "${r.format}" — expected pretty | json`),{code:1,descriptor:void 0,error:"invalid format"};const o=["tail"];r.worker!==void 0&&o.push(r.worker);const e=r.env??p(t)?.env;e!==void 0&&o.push("--env",e),r.format!==void 0&&o.push("--format",r.format),r.status!==void 0&&o.push("--status",r.status),r.search!==void 0&&o.push("--search",r.search),r.temporary&&o.push("--temporary");const s=g(v(t),"wrangler",o),n={args:s.args,command:s.command,cwd:t};return r.logger.info(`tailing logs via ${n.command} ${n.args.join(" ")}`),{code:(await(r.spawner??h)(n)).code,descriptor:n}},P=f(({argument:r,cwd:t,logger:o,options:e})=>e.durable===!0?T({cursor:e.cursor,functionPrefix:e.functionPrefix,level:e.level,limit:e.limit,logger:o,minLevel:e.minLevel,namespace:e.namespace,ndjson:e.ndjson===!0,shardKey:e.shardKey,since:e.since,table:e.table,traceId:e.traceId,until:e.until,userId:e.userId}):N({cwd:t,env:e.env,format:e.format,logger:o,search:e.search,status:e.status,temporary:e.temporary===!0,worker:r[0]}));export{P as execute,N as runLogsCommand};
@@ -0,0 +1,3 @@
1
+ import{mkdirSync as f,readFileSync as u,lstatSync as v,writeFileSync as b}from"node:fs";import{resolveHint as k,isLunoraError as m,flattenHint as S,findSolutionByMessage as w}from"@lunora/errors";import{createCerebro as x}from"@visulima/cerebro";import O from"@visulima/cerebro/command/completion";import N from"@visulima/cerebro/command/version";import{p}from"./api-spec-BENwiyUa.mjs";import{createLogger as g}from"./createLogger--C3x1FNE.mjs";import{VisulimaError as R,renderError as A}from"@visulima/error";import{homedir as B}from"node:os";import{join as d}from"node:path";const D={argument:{description:"Feature or registry item: ai | auth | email | storage | crons | presence | queue | workflow | flags | backup | …",name:"feature",type:String},description:"Add a feature or registry item (ai, auth, email, storage, crons, …) to the current Lunora project",examples:[["lunora add auth","Add authentication (asks which provider)"],["lunora add auth --provider clerk","Add Clerk auth without prompting"],["lunora add email","Add transactional email (Cloudflare Email Workers + dev mail catcher)"],["lunora add storage","Add the R2 storage registry item (asks for the bucket name)"],["lunora add storage --bucket my-app-uploads","Add storage with a bucket name, no prompt"],["lunora add crons","Add the scheduled-jobs registry item"],["lunora add storage --ref alpha","Add an item from the alpha branch's registry"]],group:"Project",loader:()=>import("../packem_chunks/handler.mjs").then(e=>({default:e.execute})),name:"add",options:[{description:"auth: provider to use without prompting (auth | clerk | auth0)",name:"provider",type:String},{description:"auth: D1 database name to use without prompting (lowercase alphanumeric + hyphens)",name:"db",type:String},{description:"storage: R2 bucket name to use without prompting (lowercase alphanumeric + hyphens)",name:"bucket",type:String},{description:"email: verified destination address to use without prompting",name:"mail-to",type:String},{description:"Skip prompts (auth provider, DB name, bucket name, mail destination) and use the defaults",name:"yes",type:Boolean},{description:"Local registry root (offline; expects <name>/ subdirs)",name:"from",type:String},{description:"Override the remote registry source base (e.g. gh:owner/repo/registry)",name:"source",type:String},{description:"Fetch items from a git ref (branch, tag, or commit), e.g. --ref alpha. Overrides the version-derived default",name:"ref",type:String},{description:"Permit --source values outside gh:/github:/https://",name:"allow-unsafe-source",type:Boolean},{description:"Output format: pretty (default) or json",name:"format",type:String}]},L={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}]},E={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}]},C={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: ${p} (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}]},j={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: ${p} (default openapi)`,name:"api-spec",type:String},{description:"Output format: pretty (default) or json",name:"format",type:String}]},T={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}]},_={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: ${p} (default openapi)`,name:"api-spec",type:String},{description:"Validate, bundle, and run pre-deploy gates without publishing (wrangler deploy --dry-run)",name:"dry-run",type:Boolean},{description:"Cloudflare environment name",name:"env",type:String},{description:"Output format: pretty (default) or json",name:"format",type:String},{description:"After a successful deploy, run pending data migrations against the live worker",name:"migrate",type:Boolean},{description:"Skip codegen + the schema-drift gate (assumes `lunora build`/`prepare` already ran in this CI run). Wrangler still bundles the worker.",name:"prebuilt",type:Boolean},{description:"Admin bearer token for --migrate (falls back to LUNORA_ADMIN_TOKEN)",name:"migrate-token",type:String},{description:"Worker URL for --migrate (REQUIRED with --migrate; the deploy target URL is not captured automatically)",name:"migrate-url",type:String},{description:"Confirm running the production data migration triggered by --migrate (required with --migrate)",name:"migrate-yes",type:Boolean},{description:"Upload a preview version (wrangler versions upload) instead of going live — prints a preview URL; doesn't shift production traffic",name:"preview",type:Boolean},{description:"Deploy to a temporary Cloudflare account when unauthenticated (wrangler deploy --temporary; live ~60min, then claim or it's deleted). Wrangler errors if you're already authenticated.",name:"temporary",type:Boolean},{description:"Re-bless the committed schema baseline (lunora/.lunora-schema.json) with the current shape",name:"update-schema-baseline",type:Boolean}]},I={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}]},$={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: ${p} (default openapi)`,name:"api-spec",type:String},{description:"Studio server port (default 6173)",name:"port",type:Number},{description:"wrangler dev port (default 8787)",name:"worker-port",type:Number},{description:"Run the dev server as a managed background process (auto-enabled when an AI agent is detected; LUNORA_AGENT_MODE=0 disables)",name:"background",type:Boolean},{description:"Emit machine-readable JSON log lines (also LUNORA_LOG_JSON=1; auto-enabled for AI agents)",name:"json",type:Boolean},{description:"How many trailing lines `lunora dev logs` prints (default 100, 0 = all)",name:"lines",type:Number},{description:"Don't start the embedded studio server",name:"no-studio",type:Boolean},{description:"Don't watch + regenerate codegen",name:"no-codegen",type:Boolean},{description:"Proxy D1/KV/R2 bindings to the deployed worker (or set LUNORA_REMOTE=1)",name:"remote",type:Boolean}]},U={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"},P={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:[]},W={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}]},M={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}]},J={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}]},K={description:"Print resolved project config: @lunora/* versions, wrangler summary, schema overview",examples:[["lunora info","Print resolved project config"],["lunora info --json","Emit a JSON snapshot"]],group:"Project",loader:()=>import("../packem_chunks/handler12.mjs").then(e=>({default:e.execute})),name:"info",options:[{description:"Emit a JSON snapshot instead of human text",name:"json",type:Boolean}]},q={argument:{description:"Project name",name:"name",type:String},description:"Scaffold a new Lunora project",examples:[["lunora init my-app","Scaffold with the default (vite) template"],["lunora init my-app -t next","Scaffold a Next.js app"],["lunora init my-app -t tanstack-start-react","Scaffold a TanStack Start (React) app"],["lunora init my-app -t tanstack-start-solid","Scaffold a TanStack Start (Solid) app"],["lunora init my-app --ref alpha","Scaffold from the alpha branch's templates"],["lunora init --here","Add Lunora to the current project"],["lunora init my-app --ci github","Scaffold + add a GitHub Actions deploy pipeline"],["lunora init my-app --ci gitlab","Scaffold + add a GitLab CI deploy pipeline"]],group:"Project",loader:()=>import("../packem_chunks/runInitCommand.mjs").then(e=>({default:e.execute})),name:"init",options:[{alias:"t",description:"Bespoke template (standalone | astro | next | nuxt | sveltekit | tanstack-start-react | tanstack-start-solid). For an SPA use --vite react|vue|solid|svelte.",name:"template",type:String},{description:"Scaffold via the create-vite overlay for a framework (react | vue | solid | svelte | vanilla) — official create-vite base + Lunora layer",name:"vite",type:String},{description:"Local templates root to copy from (offline-friendly; expects <type>/ subdirs)",name:"from",type:String},{description:"Override the remote template source (e.g. gh:owner/repo/sub#ref)",name:"source",type:String},{description:"Fetch templates from a git ref (branch, tag, or commit), e.g. --ref alpha. Overrides the version-derived default",name:"ref",type:String},{description:"Permit --source values outside gh:/github:/https:// (e.g. local file://)",name:"allow-unsafe-source",type:Boolean},{description:"Add Lunora to the current project: detect the framework, patch the config, scaffold lunora/, print per-framework wiring steps",name:"here",type:Boolean},{alias:"i",description:"After scaffolding, offer to add auth + email (defaults on when stdin is a TTY)",name:"interactive",type:Boolean},{alias:"y",description:"Skip the auth/email offer; scaffold only",name:"yes",type:Boolean},{description:"Also scaffold a CI deploy pipeline: github (.github/workflows/deploy.yml) or gitlab (.gitlab-ci.yml)",name:"ci",type:String},{description:"Add features non-interactively after scaffolding (comma-separated): ai | auth | backup | browser | cloudflare-access | crons | email | flags | hyperdrive | payment | presence | queue | storage | workflow",name:"add",type:String},{description:"Walk through every step (prompts + output) without writing files, installing, or running git",name:"dry-run",type:Boolean}]},H={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}]},F={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}]},V={argument:{description:"Worker name (defaults to the name in wrangler config)",name:"worker",type:String},description:"Stream live logs from a deployed Worker, or read the durable log archive with --durable",group:"Deploy",loader:()=>import("../packem_chunks/handler21.mjs").then(e=>({default:e.execute})),name:"logs",options:[{description:"Cloudflare environment name",name:"env",type:String},{description:"Output format: pretty (default) or json",name:"format",type:String},{description:"Substring filter on log messages",name:"search",type:String},{description:"Filter by invocation status: ok, error, or canceled",name:"status",type:String},{description:"Tail a temporary-account deployment when unauthenticated (wrangler tail --temporary). Errors if you're already authenticated.",name:"temporary",type:Boolean},{description:"Read the durable log archive (pipelineLogSink → R2) via R2 SQL instead of tailing live",name:"durable",type:Boolean},{description:"durable: Iceberg table the Pipeline writes to (required with --durable)",name:"table",type:String},{description:"durable: Iceberg namespace (R2 Data Catalog database) the table lives in",name:"namespace",type:String},{description:"durable: lower time bound (epoch-millis or ISO 8601), inclusive",name:"since",type:String},{description:"durable: upper time bound (epoch-millis or ISO 8601), inclusive",name:"until",type:String},{description:"durable: exact severity filter (trace|debug|log|info|warn|error|fatal)",name:"level",type:String},{description:"durable: severity floor — this level and every more-severe one",name:"min-level",type:String},{description:"durable: keep function paths starting with this prefix (LIKE 'prefix%')",name:"function-prefix",type:String},{description:"durable: trace-id filter",name:"trace-id",type:String},{description:"durable: shard-key filter",name:"shard-key",type:String},{description:"durable: user-id filter",name:"user-id",type:String},{description:"durable: max rows (clamped to 1–10000; default 500)",name:"limit",type:String},{description:"durable: resume after a prior page — the opaque cursor token printed by the previous page (bare epoch-millis also accepted for back-compat)",name:"cursor",type:String},{description:"durable: emit one JSON object per line instead of a table",name:"ndjson",type:Boolean}]},G={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}]},Y={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: ${p} (default openapi)`,name:"api-spec",type:String},{description:"Re-bless the committed schema baseline (lunora/.lunora-schema.json) with the current shape",name:"update-schema-baseline",type:Boolean}]},z={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}]},Q={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}]},X={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}]},Z={argument:{description:"Function path (e.g. messages:send)",name:"functionPath",type:String},description:"Send a single RPC to a running Lunora Worker",examples:[[`lunora run messages:send --args '{"text":"hi"}'`,"Call a function with JSON args"],["lunora run messages:list --shard channel:demo","Target a specific shard"]],group:"Develop",loader:()=>import("../packem_chunks/runRpcCommand.mjs").then(e=>({default:e.execute})),name:"run",options:[{description:"JSON-encoded args object",name:"args",type:String},{description:"Explicit shard key",name:"shard",type:String},{description:"Worker URL (default http://localhost:8787)",name:"url",type:String}]},ee={description:"Generate deterministic fake data from lunora/schema.ts and bulk-insert it via the worker's admin endpoint",examples:[["lunora seed","Seed every table with the default row count"],["lunora seed --table posts --count 50","Seed 50 posts; FK-parent tables are seeded automatically"],["lunora seed --reset","Wipe local .wrangler/state, then seed from scratch"],["lunora seed --seed 7 --dry-run","Print the NDJSON for seed 7 without inserting"]],group:"Data",loader:()=>import("../packem_chunks/handler18.mjs").then(e=>({default:e.execute})),name:"seed",options:[{description:"Rows per table (default 10)",name:"count",type:Number},{description:"Seed only this table; its FK-parent tables are seeded automatically",name:"table",type:String},{description:"Deterministic seed — same value yields identical rows (default 0)",name:"seed",type:Number},{description:"Print the generated NDJSON instead of inserting",name:"dry-run",type:Boolean},{description:"Wipe local .wrangler/state before seeding (local dev only)",name:"reset",type:Boolean},{description:"Rows per HTTP request (default 500)",name:"batch-size",type:Number},{description:"Target production — requires an explicit --url",name:"prod",type:Boolean},{description:"Worker URL (default http://localhost:8787)",name:"url",type:String},{description:"Admin bearer token (prefer LUNORA_ADMIN_TOKEN; --token is visible to other local processes via the process table)",name:"token",type:String},{description:"Skip the confirmation prompt when seeding a non-local/production target",name:"yes",type:Boolean}]},te={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: ${p} (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}]},re={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}]},oe={filterStacktrace:()=>!1,hideErrorCodeView:!0},ne=(e,t={})=>{const r=e instanceof Error?e.message:String(e),o=k(m(e)?{code:e.code,hint:e.hint,message:r}:r),n=new R({hint:o===void 0?void 0:S(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="",A(n,oe)},ae=(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,s=e[o-1]===t[a-1]?0:1;r[a]=Math.min((r[a-1]??0)+1,i+1,n+s),n=i}}return r[t.length]??0},ie=(e,t)=>{let r,o=Number.POSITIVE_INFINITY;for(const a of t){const i=ae(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},se="https://registry.npmjs.org/@lunora/cli/latest",pe=1440*60*1e3,le=1500,de="0.0.0",ce=/^v/u,c=e=>{const t=e.trim().replace(ce,"").split("-")[0]??"",[r,o,n]=t.split(".").map(a=>{const i=Number.parseInt(a,10);return Number.isFinite(i)?i:0});return[r??0,o??0,n??0]},ue=(e,t)=>{const r=c(e),o=c(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 0},me=(e,t)=>ue(t,e)>0,ge=(e,t,r)=>t-e<r,he=(e,t)=>`Update available for @lunora/cli: ${e} → ${t} — run \`pnpm add -D @lunora/cli@latest\``,h=e=>d(e,"lunora-cli-update.json"),ye=e=>{const t=e.XDG_CACHE_HOME&&e.XDG_CACHE_HOME.length>0?e.XDG_CACHE_HOME:d(B(),".cache"),r=d(t,"lunora");try{f(r,{mode:448,recursive:!0})}catch{}return r},fe=e=>{try{const t=JSON.parse(u(h(e),"utf8"));if(t!==null&&typeof t=="object"){const{checkedAt:r,latest:o}=t;if(typeof o=="string"&&typeof r=="number")return{checkedAt:r,latest:o}}}catch{}},ve=(e,t)=>{try{const r=h(e);try{if(v(r).isSymbolicLink())return}catch{}b(r,`${JSON.stringify(t)}
3
+ `,"utf8")}catch{}},be=async e=>{try{const t=await e(se,{signal:AbortSignal.timeout(le)});if(!t.ok)return;const r=await t.json(),o=r!==null&&typeof r=="object"?r.version:void 0;return typeof o=="string"?o:void 0}catch{return}},ke=(e,t,r)=>e===de||!r||t.CI!==void 0||t.LUNORA_NO_UPDATE_NOTIFIER!==void 0,Se=async e=>{const t=e.env??process.env,r=e.isTTY??process.stdout.isTTY;if(ke(e.current,t,r))return;const o=e.cacheDir??ye(t),n=(e.now??Date.now)(),a=e.ttlMs??pe,i=fe(o);let s=i?.latest;if(i===void 0||!ge(i.checkedAt,n,a)){const l=await be(e.fetchImpl??globalThis.fetch);l!==void 0&&(s=l,ve(o,{checkedAt:n,latest:l}))}s!==void 0&&me(e.current,s)&&e.logger.warn(he(e.current,s))},we=["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"],xe=()=>{try{const e=JSON.parse(u(new URL("../package.json",import.meta.url),"utf8")),t=e!==null&&typeof e=="object"?e.version:void 0;return typeof t=="string"&&t.length>0?t:"0.0.0"}catch{return"0.0.0"}},y=xe(),Oe=[q,D,$,j,C,_,T,Y,F,I,V,Z,H,Q,G,M,J,ee,E,te,K,P,W,L,re,U,z,X],Ne=e=>{const t={value:0},r=x("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:y});for(const o of Oe)r.addCommand(o);return r.addCommand(N),r.addCommand(O),{cli:r,exitCode:t}},Re=/Command "(?<name>[^"]+)" not found/u,Ae=e=>{const t=g(),r=e instanceof Error?e.message:String(e),o=Re.exec(r);if(!o?.groups){m(e)||w(r)!==void 0?t.error(ne(e)):t.error(r);return}const n=o.groups.name??"",a=ie(n,we);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.")},Ue=async(e={})=>{const{cli:t,exitCode:r}=Ne(e);try{await t.run({shouldExitProcess:!1})}catch(o){return Ae(o),1}return await Se({current:y,logger:g()}),r.value};export{we as COMMANDS,y as VERSION,Ue as runCli};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@lunora/cli",
3
- "version": "1.0.0-alpha.105",
3
+ "version": "1.0.0-alpha.107",
4
4
  "description": "The Lunora CLI: init, dev, deploy, codegen, run, reset, and migrate commands",
5
5
  "keywords": [
6
6
  "agent-skills",
@@ -53,13 +53,13 @@
53
53
  "dependencies": {
54
54
  "@bomb.sh/tab": "0.0.21",
55
55
  "@lunora/bindings": "1.0.0-alpha.11",
56
- "@lunora/codegen": "1.0.0-alpha.58",
57
- "@lunora/config": "1.0.0-alpha.84",
56
+ "@lunora/codegen": "1.0.0-alpha.60",
57
+ "@lunora/config": "1.0.0-alpha.86",
58
58
  "@lunora/container": "1.0.0-alpha.16",
59
- "@lunora/d1": "1.0.0-alpha.43",
59
+ "@lunora/d1": "1.0.0-alpha.44",
60
60
  "@lunora/errors": "1.0.0-alpha.8",
61
- "@lunora/runtime": "1.0.0-alpha.39",
62
- "@lunora/seed": "1.0.0-alpha.33",
61
+ "@lunora/runtime": "1.0.0-alpha.40",
62
+ "@lunora/seed": "1.0.0-alpha.35",
63
63
  "@visulima/cerebro": "3.0.0",
64
64
  "@visulima/error": "6.0.0",
65
65
  "@visulima/fs": "5.0.5",
package/skills/README.md CHANGED
@@ -9,21 +9,35 @@ framework correctly. They ship inside `@lunora/cli` and are discovered by the
9
9
  Each skill is a `SKILL.md` with YAML frontmatter (`name`, `description`) in its
10
10
  own directory:
11
11
 
12
- | Skill | Use for |
13
- | -------------------------- | --------------------------------------------------------------------------- |
14
- | `lunora` | Router — start here, then switch to the matching skill below. |
15
- | `lunora-quickstart` | `lunora init` / adding Lunora to an app + first round-trip. |
16
- | `lunora-functions` | Core authoring rules — schema, validators, query/mutation/action, `ctx.db`. |
17
- | `lunora-realtime` | Client reactivity — live hooks, optimistic updates, `@lunora/db`. |
18
- | `lunora-setup-auth` | Authentication via `lunora registry add auth` (+ providers). |
19
- | `lunora-setup-mail` | Transactional email via `lunora registry add mail` — `sendEmail` actions. |
20
- | `lunora-setup-storage` | R2 file storage via `lunora registry add storage` — signed upload/download. |
21
- | `lunora-setup-scheduler` | Deferred (`ctx.scheduler`) + cron jobs (`lunora registry add crons`). |
22
- | `lunora-create-package` | Building a reusable registry item or `@lunora/*` package. |
23
- | `lunora-migration-helper` | Schema/data migrations, `.global()` D1 flow, the drift gate. |
24
- | `lunora-deploy` | Deploying to Cloudflare wrangler bindings, secrets, the gate. |
25
- | `lunora-performance-audit` | Scans, indexes, OCC write conflicts, sharding/`.global()`. |
12
+ | Skill | Use for |
13
+ | -------------------------------- | ---------------------------------------------------------------------------- |
14
+ | `lunora` | Router — start here, then switch to the matching skill below. |
15
+ | `lunora-quickstart` | `lunora init` / adding Lunora to an app + first round-trip. |
16
+ | `lunora-functions` | Core authoring rules — schema, validators, query/mutation/action, `ctx.db`. |
17
+ | `lunora-realtime` | Client reactivity — live hooks, optimistic updates, `@lunora/db`. |
18
+ | `lunora-setup-auth` | Authentication via `lunora registry add auth` (+ providers). |
19
+ | `lunora-setup-mail` | Transactional email via `lunora registry add mail` — `sendEmail` actions. |
20
+ | `lunora-setup-storage` | R2 file storage via `lunora registry add storage` — signed upload/download. |
21
+ | `lunora-setup-scheduler` | Deferred (`ctx.scheduler`) + cron jobs (`lunora registry add crons`). |
22
+ | `lunora-setup-hyperdrive` | Existing Postgres/MySQL from an action `ctx.sql`, non-reactive. |
23
+ | `lunora-setup-hyperdrive-global` | Postgres/MySQL as a reactive `.global()` backend; D1 Hyperdrive migration. |
24
+ | `lunora-create-package` | Building a reusable registry item or `@lunora/*` package. |
25
+ | `lunora-migration-helper` | Schema/data migrations, `.global()` DDL flow, the drift gate. |
26
+ | `lunora-deploy` | Deploying to Cloudflare — wrangler bindings, secrets, the gate. |
27
+ | `lunora-performance-audit` | `lunora insights`, scans, indexes, OCC conflicts, sharding/`.global()`. |
26
28
 
27
29
  These are mirrored into `.agents/skills/` and `.claude/skills/` (via symlinks)
28
30
  so agents working inside this repo pick them up directly. The source of truth
29
31
  lives here so the published `@lunora/cli` tarball carries them.
32
+
33
+ **Adding a skill?** Create it here, then mirror it through both hops:
34
+
35
+ ```bash
36
+ ln -s ../../packages/cli/skills/<name> .agents/skills/<name>
37
+ ln -s ../../.agents/skills/<name> .claude/skills/<name>
38
+ ```
39
+
40
+ `scripts/check-skill-mirrors.js` (run on every `pnpm install`) fails if a mirror
41
+ is missing, dangling, or has become a real directory — a copied directory keeps
42
+ resolving while it silently drifts from the source, so it is treated as an
43
+ error rather than a warning.
@@ -14,8 +14,9 @@ Lunora exposes a Convex-style functional API (`defineSchema`, `query`,
14
14
  `mutation`, `action`) on top of Cloudflare Workers and Durable Objects. State
15
15
  lives in a per-app `ShardDO` (SQLite, OCC, hibernated WebSocket subscriptions)
16
16
  by default; `.shardBy(key)` partitions it across many DOs and `.global()`
17
- replicates a table to D1 for low-latency cross-region reads. A Vite plugin
18
- drives codegen and end-to-end type sync.
17
+ replicates a table to D1 or to Postgres/MySQL over Hyperdrive — for
18
+ low-latency cross-region reads. A Vite plugin drives codegen and end-to-end
19
+ type sync.
19
20
 
20
21
  If a more specific Lunora skill clearly matches the request, use that instead.
21
22
 
@@ -47,12 +48,13 @@ After codegen is green, use the most specific Lunora skill for the task:
47
48
  - Wiring live data into a client (hooks, optimistic updates): `lunora-realtime`
48
49
  - Authentication setup (email/password, OAuth, magic link, OTP):
49
50
  `lunora-setup-auth`
50
- - Wiring a prebuilt capability (mail, file storage, scheduled jobs, rate
51
- limiting, vectors, AI, containers, payments, MCP): install it with
52
- `lunora registry add <item>` (see `lunora registry list`). Capabilities with a
53
- dedicated skill: `lunora-setup-mail` (mail), `lunora-setup-storage` (R2 file
54
- storage), `lunora-setup-scheduler` (deferred `ctx.scheduler` + cron jobs). For
55
- the rest, read the item's README after installing.
51
+ - Transactional email: `lunora-setup-mail`
52
+ - R2 file storage (signed upload/download): `lunora-setup-storage`
53
+ - Deferred work (`ctx.scheduler`) and cron jobs: `lunora-setup-scheduler`
54
+ - Querying an **existing** Postgres/MySQL database from an action (`ctx.sql`,
55
+ non-reactive): `lunora-setup-hyperdrive`
56
+ - Using Postgres/MySQL as a **reactive `.global()` backend**, or migrating a D1
57
+ `.global()` dataset onto it: `lunora-setup-hyperdrive-global`
56
58
  - Building a reusable capability — a registry item or an `@lunora/*` package:
57
59
  `lunora-create-package`
58
60
  - Planning or running a schema/data migration: `lunora-migration-helper`
@@ -64,6 +66,41 @@ After codegen is green, use the most specific Lunora skill for the task:
64
66
  If one of those clearly matches the user's goal, switch to it instead of staying
65
67
  in this skill.
66
68
 
69
+ ## Capabilities Without a Dedicated Skill
70
+
71
+ Most other capabilities install as a **registry item** — `lunora registry add
72
+ <item>` scaffolds the `lunora/` glue, wrangler bindings, and env vars, then
73
+ prints post-install steps. Browse with `lunora registry list`; preview with
74
+ `lunora registry view <item>`. Read the installed item's README, and the
75
+ package's `docs/` for the API.
76
+
77
+ | Goal | Install / package |
78
+ | --------------------------------------------- | ------------------------------------------------------------ |
79
+ | Background jobs on Cloudflare Queues | `registry add queue` → `@lunora/queue` (`ctx.queues`) |
80
+ | Durable multi-step workflows | `registry add workflow` → `@lunora/workflow` (`ctx.runStep`) |
81
+ | Durable AI agents (tool loops, HITL, memory) | `@lunora/agent` (`defineAgent`) |
82
+ | Workers AI / RAG | `registry add ai` → `@lunora/ai` (`ctx.ai`, `defineRag`) |
83
+ | Feature flags (OpenFeature) | `registry add flags` → `@lunora/flags` (`ctx.flags`) |
84
+ | Payments (Stripe / Polar) | `registry add payment` → `@lunora/payment` |
85
+ | Rate limiting | `registry add ratelimit` → `@lunora/ratelimit` |
86
+ | Headless browser (action-only) | `registry add browser` → `@lunora/browser` (`ctx.browser`) |
87
+ | Cloudflare Containers | `@lunora/container` (`defineContainer`, `ctx.containers`) |
88
+ | Presence / who's-here | `registry add presence` |
89
+ | Cloudflare Access (Zero Trust) identity | `registry add cloudflare-access` |
90
+ | Backup / restore | `registry add backup` |
91
+ | Testing (in-memory harness, agent doubles) | `@lunora/testing` (`lunoraTest`) |
92
+ | Deterministic seed data | `@lunora/seed` + `lunora seed` |
93
+ | Local-first replica / offline mirror | `@lunora/replica` |
94
+ | Exposing the deployment to AI agents over MCP | `@lunora/mcp` |
95
+
96
+ Scaffolding inside this repo uses `vis generate lunora-<kind>` — `query`,
97
+ `mutation`, `action`, `http-route`, `table`, `cron`, `container`, `workflow`,
98
+ `queue`, `step`, `agent`, `flags`, `collections`, `package` (`vis generate
99
+ --list` for the full set). Most take a name: **always** pass it as
100
+ `--name=value`, since vis parses a space-separated `--name foo` as `--name=true`
101
+ plus a stray positional. `lunora-flags` and `lunora-collections` are singletons
102
+ and take no name.
103
+
67
104
  ## Core Mental Model
68
105
 
69
106
  - **Functions** live in `lunora/*.ts` and are one of `query` (reactive read),
@@ -75,7 +112,9 @@ in this skill.
75
112
  - **Reads go through indexes.** Prefer `ctx.db.query("t").withIndex(...)` over
76
113
  `.filter(...)`; declare the index with `.index("by_x", ["x"])`.
77
114
  - **Clients** subscribe over WebSocket. `useQuery`/`useMutation` (React, Vue,
78
- Solid, Svelte) re-render the moment a mutation changes the queried rows.
115
+ Solid, Svelte, React Native; signals in Angular) re-render the moment a
116
+ mutation changes the queried rows. Subscriptions run under the socket's
117
+ verified identity, so `rls()` / `ctx.auth` apply to live updates too.
79
118
 
80
119
  ## When Not to Use
81
120
 
@@ -150,9 +150,44 @@ Declare the index and constrain with `.withIndex`.
150
150
 
151
151
  ## Other `ctx` capabilities
152
152
 
153
- `ctx.auth` (the resolved session: `ctx.auth.userId`), `ctx.scheduler`
154
- (`runAfter` / `runAt` for deferred work), `ctx.storage` (R2), `ctx.vectors`
155
- (Vectorize), andwhen their packages are wired — `ctx.ai` and `ctx.containers`.
153
+ Always available:
154
+
155
+ - `ctx.auth`the resolved session (`ctx.auth.userId`).
156
+ - `ctx.scheduler` — `runAfter` / `runAt` for deferred work.
157
+ - `ctx.secrets` — Cloudflare Secrets Store.
158
+ - `ctx.span` / `ctx.trace` — the current span and a scoped tracing helper for
159
+ wide events.
160
+
161
+ Added by their package when wired. **A dependency in `package.json` is not
162
+ enough** — codegen scans the `lunora/` source set and flips a capability on only
163
+ when a file there imports the `@lunora/*` package or reads its `ctx.*` helper.
164
+ So write the call first, then run `lunora codegen` to surface the typed context:
165
+
166
+ | `ctx.*` | Package |
167
+ | ----------------------------------------------------------------------------------------- | ----------------------------- |
168
+ | `ctx.storage` | `@lunora/storage` (R2) |
169
+ | `ctx.ai` | `@lunora/ai` (Workers AI) |
170
+ | `ctx.flags` | `@lunora/flags` (OpenFeature) |
171
+ | `ctx.queues.<name>` | `@lunora/queue` |
172
+ | `ctx.workflows` / `ctx.runStep` | `@lunora/workflow` |
173
+ | `ctx.containers` | `@lunora/container` |
174
+ | `ctx.browser` (action-only) | `@lunora/browser` |
175
+ | `ctx.sql` (action-only) | `@lunora/hyperdrive` |
176
+ | `ctx.kv` / `ctx.images` / `ctx.analytics` / `ctx.pipelines` / `ctx.vectors` / `ctx.r2sql` | `@lunora/bindings` subpaths |
177
+
178
+ Two exceptions to the usage scan, and one extra requirement:
179
+
180
+ - **`ctx.flags` gates on a declaration file**, not on usage — codegen wires it
181
+ only when `lunora/flags.ts` exists (`vis generate lunora-flags` creates it).
182
+ `ctx.notify` / `ctx.push` work the same way via `lunora/notify.ts`.
183
+ - **`ctx.sql` also needs the real resource.** Codegen types the field, but the
184
+ connection needs a `HYPERDRIVE` binding (`wrangler hyperdrive create`) and an
185
+ explicit `createHyperdrive(ctx.env.HYPERDRIVE)` + driver adapter in the
186
+ action — see `lunora-setup-hyperdrive`. Bindings codegen can provision on its
187
+ own (e.g. `BROWSER` for `ctx.browser`) need no manual wrangler step.
188
+
189
+ `ctx.browser` and `ctx.sql` are **action-only** by design — they are
190
+ non-deterministic and would break query reactivity and mutation replay.
156
191
 
157
192
  ## HTTP endpoints
158
193
 
@@ -2,7 +2,8 @@
2
2
  name: lunora-migration-helper
3
3
  description: Plans Lunora schema and data migrations with widen-migrate-narrow. Use for
4
4
  breaking schema changes, backfills, table reshaping, online data migrations
5
- (`defineMigration` + `lunora migrate up`), the `.global()` D1 SQL flow, and the
5
+ (`defineMigration` + `lunora migrate up`), the `.global()` D1 / Hyperdrive
6
+ structural flows, and the
6
7
  pre-deploy schema-drift gate.
7
8
  ---
8
9
 
@@ -15,7 +16,7 @@ Safely change a Lunora schema and migrate data when making breaking changes.
15
16
  - Adding required fields to existing tables.
16
17
  - Changing field types or structure.
17
18
  - Splitting/merging tables, renaming/removing fields.
18
- - Reshaping `.global()` (D1-backed) tables.
19
+ - Reshaping `.global()` tables (D1- or Hyperdrive-backed).
19
20
 
20
21
  ## When Not to Use
21
22
 
@@ -23,21 +24,35 @@ Safely change a Lunora schema and migrate data when making breaking changes.
23
24
  - Adding **optional** fields that need no backfill.
24
25
  - Adding new tables or indexes with no correctness concern.
25
26
 
26
- ## Two Storage Layers — Know Which You Are Migrating
27
+ ## Storage Layers — Know Which You Are Migrating
27
28
 
28
- Lunora tables live in one of two backends, and they migrate differently:
29
+ Lunora tables live in one of three backends, and they migrate differently:
29
30
 
30
31
  - **ShardDO SQLite (default `root`, and `.shardBy(key)` tables).** State lives in
31
32
  the per-app / per-shard Durable Object. Data is reshaped with **online data
32
33
  migrations** — `defineMigration` declarations run by `lunora migrate up`,
33
34
  resumable per shard.
34
- - **`.global()` tables (D1).** Replicated to D1 for cross-region reads. Their
35
- structural DDL gets versioned **SQL migrations** via `lunora migrate generate`,
36
- applied by `@lunora/d1`'s runner at deploy time.
37
-
38
- A breaking change to a `.global()` table needs a generated SQL migration; a data
39
- backfill (either layer) is an online `defineMigration`. Both follow the same
40
- **widen migrate narrow** discipline.
35
+ - **`.global()` on D1 (the default global backend).** Replicated to D1 for
36
+ cross-region reads. Structural DDL gets versioned **SQL migrations** via
37
+ `lunora migrate generate`, applied by `@lunora/d1`'s runner at deploy time.
38
+ - **`.global({ backend: "hyperdrive" })` on Postgres/MySQL.** The same reactive
39
+ `.global()` contract served over Cloudflare Hyperdrive. Structural DDL works
40
+ differently here: tables **auto-provision on first use** the runtime applies
41
+ the DDL through the dialect — so there is no `lunora migrate generate` step
42
+ and no versioned SQL file to commit. See `lunora-setup-hyperdrive-global`.
43
+
44
+ So: a breaking structural change to a **D1-backed** `.global()` table needs a
45
+ generated SQL migration; the Hyperdrive-backed equivalent provisions itself. A
46
+ data backfill (any layer) is always an online `defineMigration`. All three
47
+ follow the same **widen → migrate → narrow** discipline — check the table's
48
+ backend before assuming which structural path applies.
49
+
50
+ > **Moving an existing dataset between global backends.** To move a `.global()`
51
+ > dataset from D1 onto Hyperdrive, use
52
+ > `lunora migrate d1-to-hyperdrive --from-url <d1-worker> --to-url <hd-worker>`
53
+ > (`--tables` scopes it; `--out` keeps the intermediate NDJSON dump). This is a
54
+ > backend move, not a schema change — the widen → migrate → narrow discipline
55
+ > below still governs any reshaping you do on either side of it.
41
56
 
42
57
  ## Key Principle: Widen, Migrate, Narrow
43
58
 
@@ -129,7 +144,10 @@ lunora migrate down backfill-display-name # revert (if `down` defined)
129
144
  Useful flags: `--batch-size <n>`, `--steps <n>` (cap batches this run), and
130
145
  `--prod --url <worker> --yes` to target production (with `LUNORA_ADMIN_TOKEN`).
131
146
 
132
- ## `.global()` (D1) Structural Migration Flow
147
+ ## `.global()` on D1 Structural Migration Flow
148
+
149
+ This flow is **D1-specific**. Hyperdrive-backed globals auto-provision their DDL
150
+ at runtime and skip it entirely.
133
151
 
134
152
  ```bash
135
153
  # 1. Edit lunora/schema.ts (widen: add the optional new field to the .global() table).
@@ -146,8 +164,8 @@ lunora deploy
146
164
  ```
147
165
 
148
166
  `lunora migrate generate` only considers `.global()` tables (root/sharded tables
149
- are not D1-backed). Run it after each schema edit in the widen and narrow steps;
150
- backfill data with an online migration between them.
167
+ live in ShardDO SQLite, not D1). Run it after each schema edit in the widen and
168
+ narrow steps; backfill data with an online migration between them.
151
169
 
152
170
  ## The Schema-Drift Gate
153
171
 
@@ -176,9 +194,10 @@ add the migration — not to bypass it.
176
194
  transform before it touches real rows.
177
195
  5. **Deleting a field prematurely.** Deprecate with `v.optional` + a comment;
178
196
  delete only once nothing references it.
179
- 6. **Migrating the wrong layer.** A `.global()` structural change needs `lunora
180
- migrate generate` (SQL); a data backfill needs a `defineMigration`. Check the
181
- table's `.global()` / `.shardBy()` modifier first.
197
+ 6. **Migrating the wrong layer.** A D1-backed `.global()` structural change needs
198
+ `lunora migrate generate` (SQL); a Hyperdrive-backed one auto-provisions; a
199
+ data backfill needs a `defineMigration`. Check the table's `.global()` /
200
+ `.shardBy()` modifier — and, for `.global()`, its `backend` — first.
182
201
 
183
202
  ## Checklist
184
203
 
@@ -2,8 +2,8 @@
2
2
  name: lunora-performance-audit
3
3
  description: Diagnoses and fixes Lunora performance problems — full-table scans, missing
4
4
  indexes, OCC write conflicts, oversized subscriptions, and sharding/`.global()`
5
- scaling. Use when queries are slow, mutations conflict, or `@lunora/advisor`
6
- flags a table.
5
+ scaling. Use when queries are slow, mutations conflict, `lunora insights`
6
+ reports a hot-spot, or `@lunora/advisor` flags a table.
7
7
  ---
8
8
 
9
9
  # Lunora Performance Audit
@@ -34,12 +34,35 @@ apply it across sibling functions consistently.
34
34
 
35
35
  ## Signal Gathering
36
36
 
37
- Start with the static advisors — they need no traffic:
37
+ ### Runtime signal: `lunora insights`
38
+
39
+ When the worker is running and has served traffic, start here — it reports the
40
+ measured problem, not a suspected one:
41
+
42
+ ```bash
43
+ lunora insights # against the local dev worker
44
+ lunora insights --shard channel:demo # scope to one shard
45
+ lunora insights --limit 25 --json # machine-readable, more rows
46
+ lunora insights --prod --url https://app.example.com --token $LUNORA_ADMIN_TOKEN
47
+ ```
48
+
49
+ It ranks per-function **write-conflict hot-spots** (OCC contention — the
50
+ sharding signal), **error rates**, and **latency outliers**. A function at the
51
+ top of the write-conflict list is the direct input to the OCC section below; a
52
+ latency outlier usually resolves to the read-amplification section.
53
+
54
+ The Studio **Issues** panel and `lunora logs` cover the error side in more
55
+ detail once `insights` tells you where to look.
56
+
57
+ ### Static signal: the advisors
58
+
59
+ These need no traffic, so they also work on a cold codebase:
38
60
 
39
61
  - **Lunora Studio → Advisors tab** surfaces `@lunora/advisor` findings live in
40
62
  dev.
41
- - `@lunora/advisor` runs static lints over `defineSchema` + discovered query
42
- reads / insert writes. Relevant performance/schema rules:
63
+ - `@lunora/advisor` runs ~90 static lints over `defineSchema` + discovered query
64
+ reads / insert writes (plus a few runtime lints). The performance/schema rules
65
+ most relevant here:
43
66
  - `filter-without-index` — a query filters a table with no covering index.
44
67
  - `unindexed-foreign-key` — a relation/FK column has no index.
45
68
  - `duplicate-index` / `empty-index` — wasted or malformed indexes.
@@ -75,7 +98,8 @@ column. Fix every sibling query on the table the same way.
75
98
 
76
99
  ## Problem Class: Write Conflicts (OCC)
77
100
 
78
- **Symptom:** mutations on hot rows retry or fail under concurrency. ShardDO uses
101
+ **Symptom:** mutations on hot rows retry or fail under concurrency, or the
102
+ function tops the write-conflict section of `lunora insights`. ShardDO uses
79
103
  optimistic concurrency control — concurrent writes to the same DO that touch
80
104
  overlapping state conflict and retry.
81
105
 
@@ -115,6 +139,11 @@ cross-region reads (with read-your-writes via the Sessions API). Reserve it for
115
139
  read-mostly tables — `.global()` adds the D1 migration flow (see the
116
140
  `lunora-migration-helper` skill) and write-path cost.
117
141
 
142
+ If the dataset outgrows D1, `.global({ backend: "hyperdrive" })` serves the same
143
+ reactive `.global()` contract from Postgres/MySQL over Cloudflare Hyperdrive —
144
+ see the `lunora-setup-hyperdrive-global` skill (and `lunora migrate
145
+ d1-to-hyperdrive` to move an existing dataset).
146
+
118
147
  ### `.shardBy(key)` vs `.global()` — choose one per table
119
148
 
120
149
  - `.shardBy(key)`: partitions a table across Durable Objects by key — scales
@@ -135,6 +164,7 @@ read-mostly tables — `.global()` adds the D1 migration flow (see the
135
164
  ## Checklist
136
165
 
137
166
  - [ ] Scoped one concrete flow; traced every `ctx.db` read/write.
167
+ - [ ] Ran `lunora insights` (if the worker has traffic) for the measured signal.
138
168
  - [ ] Checked the Studio Advisors tab / `@lunora/advisor` findings.
139
169
  - [ ] Read amplification: replaced `.filter()` with an indexed `.withIndex()`.
140
170
  - [ ] Write conflicts: narrowed writes and/or partitioned with `.shardBy(key)`.
@@ -45,28 +45,65 @@ Set up a working Lunora project as fast as possible.
45
45
  plugin + `lunora/` already wired together).
46
46
 
47
47
  ```bash
48
- lunora init my-app --template vite
48
+ lunora init my-app --vite react
49
49
  cd my-app
50
50
  pnpm install
51
51
  ```
52
52
 
53
- ### Pick a template
53
+ ### Pick a stack: `--vite` (SPA) or `-t` (bespoke template)
54
54
 
55
- | Template | Stack |
56
- | ---------------------- | ---------------------------------------------- |
57
- | `vite` | React + Vite (the simplest full-stack starter) |
58
- | `standalone` | Worker-only Lunora backend, no frontend |
59
- | `astro` | Astro integration |
60
- | `next` | Next.js (App Router, OpenNext on Cloudflare) |
61
- | `nuxt` | Nuxt (Vue) |
62
- | `sveltekit` | SvelteKit |
63
- | `tanstack-start-react` | TanStack Start (React) |
64
- | `tanstack-start-solid` | TanStack Start (Solid) |
55
+ There are **two scaffold paths**, and they take different flags:
65
56
 
66
- If the user has not specified a preference, default to `vite`. Pass `--template`
67
- explicitly to avoid the interactive prompt. Templates are fetched remotely (via
68
- `giget`) from `gh:anolilab/lunora/templates/<type>`; pass `--from <dir>` to use a
69
- local template directory offline.
57
+ **`--vite <framework>` the create-vite overlay.** Fetches the official
58
+ create-vite base and applies the Lunora layer on top. Use it for a plain SPA:
59
+
60
+ | `--vite` value | Stack |
61
+ | -------------- | ----------------------------------------------- |
62
+ | `react` | React SPA (**the default**) |
63
+ | `vue` | Vue SPA |
64
+ | `solid` | Solid SPA |
65
+ | `svelte` | Svelte SPA |
66
+ | `vanilla` | No framework (overlay-only — not in the picker) |
67
+
68
+ **`-t` / `--template <type>` — a bespoke Lunora template.** Whole-project
69
+ templates fetched remotely (via `giget`) from
70
+ `gh:anolilab/lunora/templates/<type>`:
71
+
72
+ | `-t` value | Stack |
73
+ | ---------------------- | ---------------------------------------------------------- |
74
+ | `next` | Next.js (App Router, OpenNext on Cloudflare) |
75
+ | `tanstack-start-react` | TanStack Start (React) — SSR with live-loader routes |
76
+ | `tanstack-start-solid` | TanStack Start (Solid) |
77
+ | `react-router` | React Router v7 (framework mode), SSR in the Lunora worker |
78
+ | `astro` | Astro + a standalone Lunora worker |
79
+ | `analog` | AnalogJS (Angular) — single worker, Lunora in Nitro |
80
+ | `nuxt` | Nuxt (Vue) — single worker, Lunora in Nitro |
81
+ | `sveltekit` | SvelteKit + a standalone Lunora worker |
82
+ | `expo` | React Native (Expo) — iOS/Android/web + a Lunora worker |
83
+ | `standalone` | Worker-only Lunora backend, no frontend |
84
+
85
+ > There is **no `--template vite`.** SPAs go through `--vite <framework>`; `-t`
86
+ > is only for the bespoke templates above.
87
+
88
+ With neither flag, an interactive run shows the framework picker (defaulting to
89
+ the React overlay) and a **non-interactive run errors out** — so as an agent,
90
+ always pass `--vite` or `-t` explicitly. If the user stated no preference,
91
+ use `--vite react`.
92
+
93
+ ### Useful `init` flags
94
+
95
+ ```bash
96
+ lunora init my-app --vite react --ci github # + a GitHub Actions deploy pipeline (or --ci gitlab)
97
+ lunora init my-app -t next --add auth,email # scaffold capabilities non-interactively
98
+ lunora init my-app --vite react --yes # skip the interactive auth/email offer
99
+ lunora init my-app --vite react --dry-run # walk every step, write nothing
100
+ ```
101
+
102
+ `--add` accepts a comma-separated list of `ai | auth | backup | browser |
103
+ cloudflare-access | crons | email | flags | hyperdrive | payment | presence |
104
+ queue | storage | workflow`. `--ref <branch|tag|commit>` pins the template
105
+ source (e.g. `--ref alpha`); `--from <dir>` copies from a local templates root
106
+ offline (expects `<type>/` subdirs).
70
107
 
71
108
  ### Generate types and push the first run
72
109
 
@@ -152,9 +189,12 @@ createRoot(document.querySelector("#root")!).render(
152
189
  );
153
190
  ```
154
191
 
155
- Vue, Solid, and Svelte have matching providers in `@lunora/vue`, `@lunora/solid`,
156
- and `@lunora/svelte`. `VITE_LUNORA_URL` is optional — it defaults to
157
- `location.origin`, which is correct for the single-origin dev setup.
192
+ Every client adapter has a matching provider: `@lunora/vue`, `@lunora/solid`,
193
+ `@lunora/svelte`, `@lunora/angular` (`provideLunora` / `injectLunoraClient`),
194
+ and `@lunora/react-native` (`createLunoraClient`, re-exporting `@lunora/react`).
195
+ For meta-frameworks, `@lunora/astro` and `@lunora/nuxt` mount Lunora on the
196
+ server side. `VITE_LUNORA_URL` is optional — it defaults to `location.origin`,
197
+ which is correct for the single-origin dev setup.
158
198
 
159
199
  ## Writing Your First Function
160
200
 
@@ -253,7 +293,8 @@ ids, `.dev.vars` secrets, and container exports.
253
293
  ## Checklist
254
294
 
255
295
  - [ ] Determined starting point: new project or existing app.
256
- - [ ] New project: scaffolded with `lunora init --template <t>`.
296
+ - [ ] New project: scaffolded with `lunora init --vite <framework>` (SPA) or
297
+ `lunora init -t <template>` (bespoke) — never `--template vite`.
257
298
  - [ ] Existing app: ran `lunora init --here` and wired `LunoraProvider`.
258
299
  - [ ] Ran `lunora codegen`: `lunora/_generated/` exists and typecheck is clean.
259
300
  - [ ] Dev server is running — user terminal, or `lunora dev --background`
@@ -2,8 +2,8 @@
2
2
  name: lunora-realtime
3
3
  description: Wires Lunora's live data into a client. Use for `LunoraClient`/`LunoraProvider`,
4
4
  reactive `useQuery`/`useSubscription`, `useMutation` with optimistic updates,
5
- pagination, connection status, the React/Vue/Solid/Svelte adapters, and the
6
- `@lunora/db` TanStack binding.
5
+ pagination, connection status, the React/Vue/Solid/Svelte/Angular/React Native
6
+ adapters, and the `@lunora/db` TanStack binding.
7
7
  ---
8
8
 
9
9
  # Lunora Realtime
@@ -15,7 +15,8 @@ automatic rollback.
15
15
 
16
16
  ## When to Use
17
17
 
18
- - Wiring a frontend to a Lunora backend (React, Vue, Solid, Svelte).
18
+ - Wiring a frontend to a Lunora backend (React, Vue, Solid, Svelte, Angular,
19
+ React Native/Expo, or an Astro/Nuxt meta-framework).
19
20
  - Adding optimistic updates, pagination, or presence to the UI.
20
21
  - Choosing between live hooks and the `@lunora/db` collection layer.
21
22
 
@@ -42,6 +43,19 @@ const client = new LunoraClient({ url });
42
43
  Vue / Solid / Svelte have matching providers in `@lunora/vue`, `@lunora/solid`,
43
44
  `@lunora/svelte`; the hook names and semantics below mirror across them.
44
45
 
46
+ Two adapters differ in shape:
47
+
48
+ - **`@lunora/angular`** is signal-based rather than hook-based: register with
49
+ `provideLunora(...)`, read the client via `injectLunoraClient()`, and use
50
+ `liveQuery(...)` / `mutate(...)` / `connectionStatus(...)` in place of the
51
+ hooks below.
52
+ - **`@lunora/react-native`** re-exports all of `@lunora/react` and adds
53
+ `createLunoraClient` (plus `@lunora/react-native/auth` for the better-auth
54
+ Expo bridge) — build the client with that instead of `new LunoraClient`.
55
+
56
+ For SSR meta-frameworks, `@lunora/astro` and `@lunora/nuxt` compose Lunora into
57
+ the server (Nitro for Nuxt) and ship reactive-loader server helpers.
58
+
45
59
  ## Live Queries
46
60
 
47
61
  `useQuery(reference, args)` opens a subscription and returns the value, or
@@ -67,33 +81,32 @@ const todos = useQuery(api.todos.list, {}) as Doc<"todos">[] | undefined;
67
81
 
68
82
  ## Authorization & Live Queries
69
83
 
70
- Subscriptions re-run the query handler **server-side under anonymous
71
- identity**. The one-shot `fetch` RPC behind the initial load carries the
72
- caller's identity, but the live WebSocket channel (the subscription seed and
73
- every write-driven refresh) does not it evaluates as anonymous.
74
-
75
- This matters for any query that authorizes or filters on the authenticated
76
- user:
77
-
78
- - A query guarded by `.use(rls(...))` or one that reads `ctx.auth.userId`
79
- directly returns the user's rows on the **initial** HTTP fetch, but its
80
- **live** updates evaluate anonymously and may resolve to an empty/denied
81
- set.
82
- - This **fails closed** — the live channel shows _less_ data, never another
83
- user's data, so there is no leak. But it is a correctness caveat: the
84
- initial render and the live updates can disagree.
85
-
86
- The supported pattern today is to scope per-user data **outside** of
87
- `ctx.auth` inside a subscribed query:
88
-
89
- - Partition the data by shard with `.shardBy(userId)` (or tenant/room), so the
90
- subscription is already scoped to the right state, or
91
- - Pass the identifier as an **explicit query arg**
92
- (`useQuery(api.todos.list, { userId })`) and filter on the arg rather than on
93
- `ctx.auth`.
94
-
95
- Reserve `rls()` / `ctx.auth`-based filtering for non-subscribed reads (one-shot
96
- actions/queries) where identity is always present.
84
+ **Live queries are identity-aware.** At the WebSocket upgrade the runtime
85
+ stamps the caller's verified identity onto the socket (from the server-minted
86
+ `x-lunora-userid` / `x-lunora-identity` headers, which a client cannot forge).
87
+ Every subscription re-run, shape resolution, and poke-driven refresh executes
88
+ under that socket's own identity, passed by value so a concurrent RPC can't
89
+ clobber it.
90
+
91
+ Practically, this means:
92
+
93
+ - `.use(rls(...))` and `ctx.auth.userId` work the same in a subscribed query as
94
+ in a one-shot read. Shape subscriptions AND-merge the shape predicate with
95
+ the table's RLS read base-where, so the membership query the poke protocol
96
+ runs is RLS-correct by constructionnever the client's word for it.
97
+ - An **anonymous** socket carries no identity, so an RLS/`ctx.auth` query fails
98
+ closed (empty/denied) rather than leaking another user's rows.
99
+ - **Token expiry is enforced on the socket.** When the resolved credential
100
+ carries an expiry, the DO sends a `TOKEN_EXPIRED` error frame and closes with
101
+ code `4001` at the next send at or after that instant. `LunoraClient`
102
+ reconnects automatically and re-resolves a fresh identity — but surface it in
103
+ the UI if a re-login is required.
104
+
105
+ You can still scope data structurally when it fits the domain — `.shardBy(userId)`
106
+ (or tenant/room) partitions state so a subscription is narrow by construction,
107
+ and explicit query args keep subscriptions cheap (see the args-scoping note
108
+ above). Prefer those for _performance_; use `rls()` / `ctx.auth` for
109
+ _authorization_. They compose.
97
110
 
98
111
  ## Mutations + Optimistic Updates
99
112
 
@@ -1,3 +0,0 @@
1
- import{mkdirSync as f,readFileSync as u,lstatSync as v,writeFileSync as b}from"node:fs";import{resolveHint as k,isLunoraError as m,flattenHint as S,findSolutionByMessage as w}from"@lunora/errors";import{createCerebro as x}from"@visulima/cerebro";import O from"@visulima/cerebro/command/completion";import N from"@visulima/cerebro/command/version";import{p as l}from"./api-spec-BENwiyUa.mjs";import{createLogger as g}from"./createLogger--C3x1FNE.mjs";import{VisulimaError as R,renderError as A}from"@visulima/error";import{homedir as B}from"node:os";import{join as d}from"node:path";const D={argument:{description:"Feature or registry item: ai | auth | email | storage | crons | presence | queue | workflow | flags | backup | …",name:"feature",type:String},description:"Add a feature or registry item (ai, auth, email, storage, crons, …) to the current Lunora project",examples:[["lunora add auth","Add authentication (asks which provider)"],["lunora add auth --provider clerk","Add Clerk auth without prompting"],["lunora add email","Add transactional email (Cloudflare Email Workers + dev mail catcher)"],["lunora add storage","Add the R2 storage registry item (asks for the bucket name)"],["lunora add storage --bucket my-app-uploads","Add storage with a bucket name, no prompt"],["lunora add crons","Add the scheduled-jobs registry item"],["lunora add storage --ref alpha","Add an item from the alpha branch's registry"]],group:"Project",loader:()=>import("../packem_chunks/handler.mjs").then(e=>({default:e.execute})),name:"add",options:[{description:"auth: provider to use without prompting (auth | clerk | auth0)",name:"provider",type:String},{description:"auth: D1 database name to use without prompting (lowercase alphanumeric + hyphens)",name:"db",type:String},{description:"storage: R2 bucket name to use without prompting (lowercase alphanumeric + hyphens)",name:"bucket",type:String},{description:"email: verified destination address to use without prompting",name:"mail-to",type:String},{description:"Skip prompts (auth provider, DB name, bucket name, mail destination) and use the defaults",name:"yes",type:Boolean},{description:"Local registry root (offline; expects <name>/ subdirs)",name:"from",type:String},{description:"Override the remote registry source base (e.g. gh:owner/repo/registry)",name:"source",type:String},{description:"Fetch items from a git ref (branch, tag, or commit), e.g. --ref alpha. Overrides the version-derived default",name:"ref",type:String},{description:"Permit --source values outside gh:/github:/https://",name:"allow-unsafe-source",type:Boolean},{description:"Output format: pretty (default) or json",name:"format",type:String}]},L={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}]},E={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}]},C={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}]},j={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}]},T={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}]},_={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},{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}]},I={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}]},$={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},{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}]},U={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"},P={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:[]},W={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}]},M={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}]},J={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}]},K={description:"Print resolved project config: @lunora/* versions, wrangler summary, schema overview",examples:[["lunora info","Print resolved project config"],["lunora info --json","Emit a JSON snapshot"]],group:"Project",loader:()=>import("../packem_chunks/handler12.mjs").then(e=>({default:e.execute})),name:"info",options:[{description:"Emit a JSON snapshot instead of human text",name:"json",type:Boolean}]},q={argument:{description:"Project name",name:"name",type:String},description:"Scaffold a new Lunora project",examples:[["lunora init my-app","Scaffold with the default (vite) template"],["lunora init my-app -t next","Scaffold a Next.js app"],["lunora init my-app -t tanstack-start-react","Scaffold a TanStack Start (React) app"],["lunora init my-app -t tanstack-start-solid","Scaffold a TanStack Start (Solid) app"],["lunora init my-app --ref alpha","Scaffold from the alpha branch's templates"],["lunora init --here","Add Lunora to the current project"],["lunora init my-app --ci github","Scaffold + add a GitHub Actions deploy pipeline"],["lunora init my-app --ci gitlab","Scaffold + add a GitLab CI deploy pipeline"]],group:"Project",loader:()=>import("../packem_chunks/runInitCommand.mjs").then(e=>({default:e.execute})),name:"init",options:[{alias:"t",description:"Bespoke template (standalone | astro | next | nuxt | sveltekit | tanstack-start-react | tanstack-start-solid). For an SPA use --vite react|vue|solid|svelte.",name:"template",type:String},{description:"Scaffold via the create-vite overlay for a framework (react | vue | solid | svelte | vanilla) — official create-vite base + Lunora layer",name:"vite",type:String},{description:"Local templates root to copy from (offline-friendly; expects <type>/ subdirs)",name:"from",type:String},{description:"Override the remote template source (e.g. gh:owner/repo/sub#ref)",name:"source",type:String},{description:"Fetch templates from a git ref (branch, tag, or commit), e.g. --ref alpha. Overrides the version-derived default",name:"ref",type:String},{description:"Permit --source values outside gh:/github:/https:// (e.g. local file://)",name:"allow-unsafe-source",type:Boolean},{description:"Add Lunora to the current project: detect the framework, patch the config, scaffold lunora/, print per-framework wiring steps",name:"here",type:Boolean},{alias:"i",description:"After scaffolding, offer to add auth + email (defaults on when stdin is a TTY)",name:"interactive",type:Boolean},{alias:"y",description:"Skip the auth/email offer; scaffold only",name:"yes",type:Boolean},{description:"Also scaffold a CI deploy pipeline: github (.github/workflows/deploy.yml) or gitlab (.gitlab-ci.yml)",name:"ci",type:String},{description:"Add features non-interactively after scaffolding (comma-separated): ai | auth | backup | browser | cloudflare-access | crons | email | flags | hyperdrive | payment | presence | queue | storage | workflow",name:"add",type:String},{description:"Walk through every step (prompts + output) without writing files, installing, or running git",name:"dry-run",type:Boolean}]},H={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}]},F={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}]},V={argument:{description:"Worker name (defaults to the name in wrangler config)",name:"worker",type:String},description:"Stream live logs from a deployed Worker, or read the durable log archive with --durable",group:"Deploy",loader:()=>import("../packem_chunks/handler21.mjs").then(e=>({default:e.execute})),name:"logs",options:[{description:"Cloudflare environment name",name:"env",type:String},{description:"Output format: pretty (default) or json",name:"format",type:String},{description:"Substring filter on log messages",name:"search",type:String},{description:"Filter by invocation status: ok, error, or canceled",name:"status",type:String},{description:"Tail a temporary-account deployment when unauthenticated (wrangler tail --temporary). Errors if you're already authenticated.",name:"temporary",type:Boolean},{description:"Read the durable log archive (pipelineLogSink → R2) via R2 SQL instead of tailing live",name:"durable",type:Boolean},{description:"durable: Iceberg table the Pipeline writes to (required with --durable)",name:"table",type:String},{description:"durable: Iceberg namespace (R2 Data Catalog database) the table lives in",name:"namespace",type:String},{description:"durable: lower time bound (epoch-millis or ISO 8601), inclusive",name:"since",type:String},{description:"durable: upper time bound (epoch-millis or ISO 8601), inclusive",name:"until",type:String},{description:"durable: exact severity filter (trace|debug|log|info|warn|error|fatal)",name:"level",type:String},{description:"durable: severity floor — this level and every more-severe one",name:"min-level",type:String},{description:"durable: keep function paths starting with this prefix (LIKE 'prefix%')",name:"function-prefix",type:String},{description:"durable: trace-id filter",name:"trace-id",type:String},{description:"durable: shard-key filter",name:"shard-key",type:String},{description:"durable: user-id filter",name:"user-id",type:String},{description:"durable: max rows (clamped to 1–10000; default 500)",name:"limit",type:String},{description:"durable: resume after a prior page — the ts from its nextCursor",name:"cursor",type:String},{description:"durable: emit one JSON object per line instead of a table",name:"ndjson",type:Boolean}]},G={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}]},Y={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},{description:"Re-bless the committed schema baseline (lunora/.lunora-schema.json) with the current shape",name:"update-schema-baseline",type:Boolean}]},z={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}]},Q={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}]},X={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}]},Z={argument:{description:"Function path (e.g. messages:send)",name:"functionPath",type:String},description:"Send a single RPC to a running Lunora Worker",examples:[[`lunora run messages:send --args '{"text":"hi"}'`,"Call a function with JSON args"],["lunora run messages:list --shard channel:demo","Target a specific shard"]],group:"Develop",loader:()=>import("../packem_chunks/runRpcCommand.mjs").then(e=>({default:e.execute})),name:"run",options:[{description:"JSON-encoded args object",name:"args",type:String},{description:"Explicit shard key",name:"shard",type:String},{description:"Worker URL (default http://localhost:8787)",name:"url",type:String}]},ee={description:"Generate deterministic fake data from lunora/schema.ts and bulk-insert it via the worker's admin endpoint",examples:[["lunora seed","Seed every table with the default row count"],["lunora seed --table posts --count 50","Seed 50 posts; FK-parent tables are seeded automatically"],["lunora seed --reset","Wipe local .wrangler/state, then seed from scratch"],["lunora seed --seed 7 --dry-run","Print the NDJSON for seed 7 without inserting"]],group:"Data",loader:()=>import("../packem_chunks/handler18.mjs").then(e=>({default:e.execute})),name:"seed",options:[{description:"Rows per table (default 10)",name:"count",type:Number},{description:"Seed only this table; its FK-parent tables are seeded automatically",name:"table",type:String},{description:"Deterministic seed — same value yields identical rows (default 0)",name:"seed",type:Number},{description:"Print the generated NDJSON instead of inserting",name:"dry-run",type:Boolean},{description:"Wipe local .wrangler/state before seeding (local dev only)",name:"reset",type:Boolean},{description:"Rows per HTTP request (default 500)",name:"batch-size",type:Number},{description:"Target production — requires an explicit --url",name:"prod",type:Boolean},{description:"Worker URL (default http://localhost:8787)",name:"url",type:String},{description:"Admin bearer token (prefer LUNORA_ADMIN_TOKEN; --token is visible to other local processes via the process table)",name:"token",type:String},{description:"Skip the confirmation prompt when seeding a non-local/production target",name:"yes",type:Boolean}]},te={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}]},re={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}]},oe={filterStacktrace:()=>!1,hideErrorCodeView:!0},ne=(e,t={})=>{const r=e instanceof Error?e.message:String(e),o=k(m(e)?{code:e.code,hint:e.hint,message:r}:r),n=new R({hint:o===void 0?void 0:S(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="",A(n,oe)},ae=(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,s=e[o-1]===t[a-1]?0:1;r[a]=Math.min((r[a-1]??0)+1,i+1,n+s),n=i}}return r[t.length]??0},ie=(e,t)=>{let r,o=Number.POSITIVE_INFINITY;for(const a of t){const i=ae(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},se="https://registry.npmjs.org/@lunora/cli/latest",le=1440*60*1e3,pe=1500,de="0.0.0",ce=/^v/u,c=e=>{const t=e.trim().replace(ce,"").split("-")[0]??"",[r,o,n]=t.split(".").map(a=>{const i=Number.parseInt(a,10);return Number.isFinite(i)?i:0});return[r??0,o??0,n??0]},ue=(e,t)=>{const r=c(e),o=c(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 0},me=(e,t)=>ue(t,e)>0,ge=(e,t,r)=>t-e<r,he=(e,t)=>`Update available for @lunora/cli: ${e} → ${t} — run \`pnpm add -D @lunora/cli@latest\``,h=e=>d(e,"lunora-cli-update.json"),ye=e=>{const t=e.XDG_CACHE_HOME&&e.XDG_CACHE_HOME.length>0?e.XDG_CACHE_HOME:d(B(),".cache"),r=d(t,"lunora");try{f(r,{mode:448,recursive:!0})}catch{}return r},fe=e=>{try{const t=JSON.parse(u(h(e),"utf8"));if(t!==null&&typeof t=="object"){const{checkedAt:r,latest:o}=t;if(typeof o=="string"&&typeof r=="number")return{checkedAt:r,latest:o}}}catch{}},ve=(e,t)=>{try{const r=h(e);try{if(v(r).isSymbolicLink())return}catch{}b(r,`${JSON.stringify(t)}
3
- `,"utf8")}catch{}},be=async e=>{try{const t=await e(se,{signal:AbortSignal.timeout(pe)});if(!t.ok)return;const r=await t.json(),o=r!==null&&typeof r=="object"?r.version:void 0;return typeof o=="string"?o:void 0}catch{return}},ke=(e,t,r)=>e===de||!r||t.CI!==void 0||t.LUNORA_NO_UPDATE_NOTIFIER!==void 0,Se=async e=>{const t=e.env??process.env,r=e.isTTY??process.stdout.isTTY;if(ke(e.current,t,r))return;const o=e.cacheDir??ye(t),n=(e.now??Date.now)(),a=e.ttlMs??le,i=fe(o);let s=i?.latest;if(i===void 0||!ge(i.checkedAt,n,a)){const p=await be(e.fetchImpl??globalThis.fetch);p!==void 0&&(s=p,ve(o,{checkedAt:n,latest:p}))}s!==void 0&&me(e.current,s)&&e.logger.warn(he(e.current,s))},we=["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"],xe=()=>{try{const e=JSON.parse(u(new URL("../package.json",import.meta.url),"utf8")),t=e!==null&&typeof e=="object"?e.version:void 0;return typeof t=="string"&&t.length>0?t:"0.0.0"}catch{return"0.0.0"}},y=xe(),Oe=[q,D,$,j,C,_,T,Y,F,I,V,Z,H,Q,G,M,J,ee,E,te,K,P,W,L,re,U,z,X],Ne=e=>{const t={value:0},r=x("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:y});for(const o of Oe)r.addCommand(o);return r.addCommand(N),r.addCommand(O),{cli:r,exitCode:t}},Re=/Command "(?<name>[^"]+)" not found/u,Ae=e=>{const t=g(),r=e instanceof Error?e.message:String(e),o=Re.exec(r);if(!o?.groups){m(e)||w(r)!==void 0?t.error(ne(e)):t.error(r);return}const n=o.groups.name??"",a=ie(n,we);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.")},Ue=async(e={})=>{const{cli:t,exitCode:r}=Ne(e);try{await t.run({shouldExitProcess:!1})}catch(o){return Ae(o),1}return await Se({current:y,logger:g()}),r.value};export{we as COMMANDS,y as VERSION,Ue as runCli};