@lunora/cli 1.0.0-alpha.150 → 1.0.0-alpha.151

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.
@@ -1,2 +1 @@
1
- import{mkdirSync as s,writeFileSync as a}from"node:fs";import{isAbsolute as g,resolve as c,dirname as m}from"node:path";import{findWranglerFile as l,readWranglerJsonc as u,buildBindingManifest as p}from"@lunora/config/cloudflare";import{r as f}from"../packem_shared/api-spec-BENwiyUa.mjs";import{i as w}from"../packem_shared/command-0l-ZPhIX.mjs";import{runDeployCommand as b}from"./runDeployCommand.mjs";const h=".lunora/build",y=(i,r,n)=>{const e=l(i),d=e===void 0?void 0:u(e).parsed;if(d===void 0)return{error:`--emit-bindings found no readable wrangler config in ${i}. The manifest is derived from it, and an empty one would tell a deployer this Worker needs nothing.`};const o=p(d),t=g(r)?r:c(i,r);return s(m(t),{recursive:!0}),a(t,`${JSON.stringify(o,void 0,2)}
2
- `,"utf8"),n.success(`binding manifest written to ${t} (${o.bindings.length.toString()} bindings, ${o.crons.length.toString()} crons)`),o.unknown.length>0&&n.warn(`binding manifest does not model these wrangler sections: ${o.unknown.join(", ")}. Anything they bind must be provisioned by hand — please report them so the manifest can cover them.`),{}},v=async i=>{const r=i.outDir??h,n=await b({apiSpec:i.apiSpec,cwd:i.cwd,dryRun:!0,format:i.format,logger:i.logger,outDir:r,spawner:i.spawner,target:i.target});if(n.code!==0)return n;if(i.logger.success(`build complete — bundle written to ${r}`),i.emitBindings!==void 0){const{error:e}=y(i.cwd??process.cwd(),i.emitBindings,i.logger);if(e!==void 0)return i.logger.error(e),{...n,code:1}}return n},x=w(async({cwd:i,logger:r,options:n})=>({code:(await v({apiSpec:f(n.apiSpec),cwd:i,emitBindings:n.emitBindings,format:n.format,logger:r,outDir:n.outDir,target:n.target})).code}));export{x as execute,v as runBuildCommand};
1
+ import{i as d}from"../packem_shared/command-0l-ZPhIX.mjs";import{M as g,l as m}from"../packem_shared/detect-package-manager-DXDstphE.mjs";import{r as p}from"../packem_shared/docker-CKvYE9YF.mjs";import{defaultSpawner as l}from"../packem_shared/createRecordingSpawner-SKs4R1fc.mjs";const i=new Set(["build","delete","images","info","list","push"]),h=new Set(["build","push"]),w=async r=>{const[a,...n]=r.argument;if(a===void 0||!i.has(a))return r.logger.error(`lunora containers requires a subcommand: ${[...i].toSorted((c,u)=>c.localeCompare(u)).join(" | ")}. Example: lunora containers build ./containers/app --tag app:v1 --push`),{code:1};if(h.has(a)&&!(r.dockerAvailable??p)())return r.logger.error(`containers ${a} needs a running Docker-compatible engine (it builds/pushes images locally). Start Docker or Colima and retry. Note: container images must target linux/amd64.`),{code:1};const o=["containers",a,...n];r.tag!==void 0&&o.push("--tag",r.tag),r.push===!0&&o.push("--push"),r.env!==void 0&&o.push("--env",r.env);const t=r.cwd??process.cwd(),s=g(m(t),"wrangler",o),e={args:s.args,command:s.command,cwd:t};return r.logger.info(`running ${e.command} ${e.args.join(" ")}`),{code:(await(r.spawner??l)(e)).code,descriptor:e}},C=d(async({argument:r,cwd:a,logger:n,options:o})=>({code:(await w({argument:r,cwd:a,env:o.env,logger:n,push:o.push===!0,tag:o.tag})).code}));export{C as execute,w as runContainersCommand};
@@ -1 +1 @@
1
- import{i as d}from"../packem_shared/command-0l-ZPhIX.mjs";import{M as g,l as m}from"../packem_shared/detect-package-manager-DXDstphE.mjs";import{r as p}from"../packem_shared/docker-CKvYE9YF.mjs";import{defaultSpawner as l}from"../packem_shared/createRecordingSpawner-SKs4R1fc.mjs";const i=new Set(["build","delete","images","info","list","push"]),h=new Set(["build","push"]),w=async r=>{const[a,...n]=r.argument;if(a===void 0||!i.has(a))return r.logger.error(`lunora containers requires a subcommand: ${[...i].toSorted((c,u)=>c.localeCompare(u)).join(" | ")}. Example: lunora containers build ./containers/app --tag app:v1 --push`),{code:1};if(h.has(a)&&!(r.dockerAvailable??p)())return r.logger.error(`containers ${a} needs a running Docker-compatible engine (it builds/pushes images locally). Start Docker or Colima and retry. Note: container images must target linux/amd64.`),{code:1};const o=["containers",a,...n];r.tag!==void 0&&o.push("--tag",r.tag),r.push===!0&&o.push("--push"),r.env!==void 0&&o.push("--env",r.env);const t=r.cwd??process.cwd(),s=g(m(t),"wrangler",o),e={args:s.args,command:s.command,cwd:t};return r.logger.info(`running ${e.command} ${e.args.join(" ")}`),{code:(await(r.spawner??l)(e)).code,descriptor:e}},C=d(async({argument:r,cwd:a,logger:n,options:o})=>({code:(await w({argument:r,cwd:a,env:o.env,logger:n,push:o.push===!0,tag:o.tag})).code}));export{C as execute,w as runContainersCommand};
1
+ import{i as d}from"../packem_shared/command-0l-ZPhIX.mjs";import{M as a,l as m}from"../packem_shared/detect-package-manager-DXDstphE.mjs";import{defaultSpawner as c}from"../packem_shared/createRecordingSpawner-SKs4R1fc.mjs";const i=(r,e)=>(e!==void 0&&r.push("--env",e),r),p=r=>{const e=i(["deployments","list"],r.env);return r.json&&e.push("--json"),e},u=r=>{switch(r.subcommand){case"inspect":return r.versionId===void 0?{error:"deployments inspect requires a version id. Usage: lunora deployments inspect <version-id>"}:{args:i(["versions","view",r.versionId],r.env)};case"list":return{args:p(r)};case"promote":{if(r.versionId===void 0)return{error:"deployments promote requires a version id. Usage: lunora deployments promote <version-id> --yes"};if(!r.yes)return{error:"deployments promote shifts 100% of live traffic. Re-run with --yes to confirm."};const e=i(["versions","deploy",`${r.versionId}@100%`,"--yes"],r.env);return r.message!==void 0&&e.push("--message",r.message),{args:e}}case"rollback":{if(!r.yes)return{error:"deployments rollback changes the live version. Re-run with --yes to confirm."};const e=i(["rollback"],r.env);return r.versionId!==void 0&&e.push(r.versionId),e.push("--yes"),r.message!==void 0&&e.push("--message",r.message),{args:e}}default:return{error:`deployments: unknown subcommand "${r.subcommand}"`}}},l=async r=>{const{args:e,error:s}=u(r);if(s!==void 0||e===void 0)return r.logger.error(s??"deployments: nothing to run"),{code:1,descriptor:void 0,error:s};const o=r.cwd??process.cwd(),n=a(m(o),"wrangler",e),t={args:n.args,command:n.command,cwd:o};return r.logger.info(`${t.command} ${t.args.join(" ")}`),{code:(await(r.spawner??c)(t)).code,descriptor:t}},v=r=>r==="list"||r==="inspect"||r==="rollback"||r==="promote",w=d(({argument:r,cwd:e,logger:s,options:o})=>{const n=r[0];return v(n)?l({cwd:e,env:o.env,json:o.json===!0,logger:s,message:o.message,subcommand:n,versionId:r[1],yes:o.yes===!0}):(s.error(`deployments: unknown subcommand "${n??""}" — expected list | inspect | rollback | promote`),{code:1})});export{w as execute,l as runDeploymentsCommand};
@@ -1 +1 @@
1
- import{i as d}from"../packem_shared/command-0l-ZPhIX.mjs";import{M as a,l as m}from"../packem_shared/detect-package-manager-DXDstphE.mjs";import{defaultSpawner as c}from"../packem_shared/createRecordingSpawner-SKs4R1fc.mjs";const i=(r,e)=>(e!==void 0&&r.push("--env",e),r),p=r=>{const e=i(["deployments","list"],r.env);return r.json&&e.push("--json"),e},u=r=>{switch(r.subcommand){case"inspect":return r.versionId===void 0?{error:"deployments inspect requires a version id. Usage: lunora deployments inspect <version-id>"}:{args:i(["versions","view",r.versionId],r.env)};case"list":return{args:p(r)};case"promote":{if(r.versionId===void 0)return{error:"deployments promote requires a version id. Usage: lunora deployments promote <version-id> --yes"};if(!r.yes)return{error:"deployments promote shifts 100% of live traffic. Re-run with --yes to confirm."};const e=i(["versions","deploy",`${r.versionId}@100%`,"--yes"],r.env);return r.message!==void 0&&e.push("--message",r.message),{args:e}}case"rollback":{if(!r.yes)return{error:"deployments rollback changes the live version. Re-run with --yes to confirm."};const e=i(["rollback"],r.env);return r.versionId!==void 0&&e.push(r.versionId),e.push("--yes"),r.message!==void 0&&e.push("--message",r.message),{args:e}}default:return{error:`deployments: unknown subcommand "${r.subcommand}"`}}},l=async r=>{const{args:e,error:s}=u(r);if(s!==void 0||e===void 0)return r.logger.error(s??"deployments: nothing to run"),{code:1,descriptor:void 0,error:s};const o=r.cwd??process.cwd(),n=a(m(o),"wrangler",e),t={args:n.args,command:n.command,cwd:o};return r.logger.info(`${t.command} ${t.args.join(" ")}`),{code:(await(r.spawner??c)(t)).code,descriptor:t}},v=r=>r==="list"||r==="inspect"||r==="rollback"||r==="promote",w=d(({argument:r,cwd:e,logger:s,options:o})=>{const n=r[0];return v(n)?l({cwd:e,env:o.env,json:o.json===!0,logger:s,message:o.message,subcommand:n,versionId:r[1],yes:o.yes===!0}):(s.error(`deployments: unknown subcommand "${n??""}" — expected list | inspect | rollback | promote`),{code:1})});export{w as execute,l as runDeploymentsCommand};
1
+ import{i as s}from"../packem_shared/command-0l-ZPhIX.mjs";import{f as c}from"../packem_shared/open-url-zbbAo_D7.mjs";const t="https://lunora.sh/docs",g=r=>{let o=0,n=r.length;for(;o<n&&r[o]==="/";)o+=1;for(;n>o&&r[n-1]==="/";)n-=1;return r.slice(o,n)},l=r=>{if(!r||r.length===0)return t;const o=g(r);return o.length===0?t:`${t}/${o}`},i=async r=>{const o=l(r.section);r.logger.info(`opening ${o}`);try{await c(o,{opener:r.opener})}catch(n){const e=n instanceof Error?n.message:String(n);return r.logger.error(`docs: failed to open URL: ${e}`),{code:1,url:o}}return{code:0,url:o}},f=s(({argument:r,logger:o})=>i({logger:o,section:r[0]}));export{f as execute,i as runDocsCommand};
@@ -1 +1 @@
1
- import{i as s}from"../packem_shared/command-0l-ZPhIX.mjs";import{f as c}from"../packem_shared/open-url-zbbAo_D7.mjs";const t="https://lunora.sh/docs",g=r=>{let o=0,n=r.length;for(;o<n&&r[o]==="/";)o+=1;for(;n>o&&r[n-1]==="/";)n-=1;return r.slice(o,n)},l=r=>{if(!r||r.length===0)return t;const o=g(r);return o.length===0?t:`${t}/${o}`},i=async r=>{const o=l(r.section);r.logger.info(`opening ${o}`);try{await c(o,{opener:r.opener})}catch(n){const e=n instanceof Error?n.message:String(n);return r.logger.error(`docs: failed to open URL: ${e}`),{code:1,url:o}}return{code:0,url:o}},f=s(({argument:r,logger:o})=>i({logger:o,section:r[0]}));export{f as execute,i as runDocsCommand};
1
+ import{existsSync as p,readFileSync as v,realpathSync as g}from"node:fs";import{join as u,sep as x}from"node:path";import{isPlaceholderValue as w,DEV_VARS_FILE as h,parseDevVariableEntries as y,discoverSchemaInfo as $,inferLunoraBindings as b}from"@lunora/config";import{findWranglerFile as k,readWranglerJsonc as S,validateWranglerConfig as _,collectExportGaps as N}from"@lunora/config/cloudflare";import{i as R}from"../packem_shared/command-0l-ZPhIX.mjs";import{i as j,t as A,d as L,s as O}from"../packem_shared/output-format-Cv3aLqhP.mjs";import{o as D,p as E}from"../packem_shared/vectorize-metadata-BvZbbqUD.mjs";const C=/(?:KEY|PASSWORD|SECRET|TOKEN)$/u,I=a=>{const e=a.trim();if(e==="")return!0;const n=e.toLowerCase();return n.includes("replace")||n.startsWith("<")&&n.endsWith(">")},W=a=>{const e=k(a);if(e===void 0)return{parsed:void 0,path:void 0};const{parsed:n}=S(e);return{parsed:n,path:e}},M=(a,e,n)=>{if(e===void 0){n.push({code:"wrangler-missing",fix:"Run `lunora init` (or `lunora dev`) to scaffold and reconcile wrangler.jsonc.",level:"fail",message:"wrangler.jsonc not found."});return}if(a===void 0){n.push({code:"wrangler-unparseable",fix:`Check ${e} is valid JSONC.`,level:"fail",message:`Could not parse ${e}.`});return}const r=_(a).errors.find(s=>s.includes("SHARD"));r===void 0?n.push({code:"wrangler-shard-binding-ok",level:"pass",message:"wrangler.jsonc present with a SHARD durable-object binding."}):n.push({code:"wrangler-shard-binding-missing",fix:"Run `lunora dev` to auto-reconcile, or add the binding manually.",level:"fail",message:r})},z=(a,e)=>{const{info:n}=$(a,"lunora");for(const r of n?.vectorMetadata??[]){const s=E(r.kind);if(s===void 0){e.push({code:"vector-metadata-unfilterable",fix:"Filter on a string, number or boolean column, or drop it from `metadata`.",level:"warn",message:`vector index "${r.index}" declares metadata "${r.property}", whose type Vectorize cannot filter on.`});continue}e.push({code:"vector-metadata-index-required",fix:`wrangler ${D({index:r.index,property:r.property,type:s}).join(" ")}`,level:"info",message:`vector index "${r.index}" filters on metadata "${r.property}" — that needs a Vectorize metadata index (\`lunora deploy\` creates it).`})}},K=(a,e)=>{if(a===void 0)return;const n=(a.d1_databases??[]).filter(Boolean);for(const r of n){const s=typeof r.database_id=="string"?r.database_id:"";if(I(s)){const o=typeof r.binding=="string"&&r.binding.length>0?r.binding:"<unnamed>";e.push({code:"d1-placeholder-id",fix:"Run `wrangler d1 create <name>` and paste the returned database_id into wrangler.jsonc.",level:"fail",message:`D1 binding "${o}" has a placeholder database_id ("${s||"<empty>"}").`})}}},T=(a,e)=>{if(a===void 0)return;const n=(a.send_email??[]).filter(Boolean);for(const r of n){const s=typeof r.destination_address=="string"?r.destination_address:"";if(s!==""&&w(s)){const o=typeof r.name=="string"&&r.name.length>0?r.name:"send_email";e.push({code:"email-destination-placeholder",fix:"Set destination_address to a verified Cloudflare Email Routing address.",level:"warn",message:`send_email binding "${o}" has a placeholder destination_address ("${s}").`})}}},V=(a,e)=>{const n=u(a,h);if(!p(n))return;let r;try{r=v(n,"utf8")}catch{return}const s=y(r).filter(o=>C.test(o.key)&&w(o.value)).map(o=>o.key);s.length>0&&e.push({code:"dev-vars-missing-secret",fix:"Run `lunora dev` to auto-generate secrets, or fill them in by hand.",level:"warn",message:`${h} has unfilled secret value(s): ${s.join(", ")}.`})},F=a=>{const e=process.env.LUNORA_ADMIN_TOKEN;e===void 0||e.trim()===""?a.push({code:"admin-token-missing",fix:"Set LUNORA_ADMIN_TOKEN (env or `.dev.vars`) to enable admin RPCs / studio.",level:"info",message:"LUNORA_ADMIN_TOKEN is not set."}):a.push({code:"admin-token-set",level:"pass",message:"LUNORA_ADMIN_TOKEN is set."})},P=async(a,e)=>{let n;try{n=await b({projectRoot:a})}catch{return}const r=N(n),s=[...n.containers.map(o=>({...o,kind:"container"})),...n.workflows.map(o=>({...o,kind:"workflow"})),...n.agents.map(o=>({...o,kind:"agent"}))];for(const o of s.filter(i=>i.exported))e.push({code:"declared-export-ok",level:"pass",message:`${o.kind} "${o.exportName}" is exported by the worker entry.`});for(const o of r)e.push({code:"declared-export-missing",fix:`Add \`export * from "./lunora/_generated/${o.module}"\` to your worker entry (or re-run \`vis generate lunora-${o.kind}\`).`,level:"fail",message:`${o.kind} "${o.exportName}" is declared but ${o.className} is not exported by the worker entry.`})},U=/^[\^~><= ]+/u,B=/^(?<core>\d+\.\d+\.\d+)(?:-(?<channel>[a-z]+)\.(?<counter>\d+))?$/u,J=a=>{const e=a.replace(U,"").trim(),n=B.exec(e);if(!n?.groups)return;const{channel:r,core:s,counter:o}=n.groups;return{channel:r??"",core:s??"",counter:o===void 0?void 0:Number.parseInt(o,10),raw:e}},q=(a,e)=>{const n=u(a,"package.json");if(!p(n))return;let r;try{r=JSON.parse(v(n,"utf8"))}catch{return}const s={...r.devDependencies,...r.dependencies},o=[];for(const[t,l]of Object.entries(s)){if(t!=="lunorash"&&!t.startsWith("@lunora/"))continue;const m=J(l);m&&o.push({name:t,version:m})}if(o.length<2)return;const i=t=>t.map(l=>`${l.name}@${l.version.raw}`).join(", "),d=new Set(o.map(t=>t.version.core)),f=new Set(o.map(t=>t.version.channel));if(d.size>1){e.push({code:"version-skew-cores",fix:'Run `pnpm update "@lunora/*" lunorash` (or `npm`/`yarn` equivalent) so every Lunora package moves to the same release.',level:"warn",message:`Lunora packages span ${String(d.size)} different versions: ${i(o)}.`});return}if(f.size>1){e.push({code:"version-skew-channels",fix:"Pick one channel (all stable, or all alpha/beta) and update the odd package out.",level:"warn",message:`Lunora packages mix release channels (${[...f].map(t=>t===""?"stable":t).join(" + ")}): ${i(o)}.`});return}const c=o.map(t=>t.version.counter).filter(t=>t!==void 0);if(c.length>1){const t=Math.min(...c),l=Math.max(...c);e.push({code:"version-counter-spread",level:"info",message:c.length===o.length&&t===l?`Lunora packages are all at ${[...f][0]??""}.${String(l)}.`:`Lunora pre-release counters span ${String(t)}–${String(l)}: ${i(o)}.`})}},H=[u("@lunora","cli"),"lunorash"],G=(a,e,n)=>{if(e===void 0)return;const r=[];for(const o of H){const i=u(a,"node_modules",o);if(p(i))try{r.push(g(i))}catch{}}if(r.length===0)return;let s;try{s=g(e)}catch{return}r.some(o=>s===o||s.startsWith(`${o}${x}`))||n.push({code:"cli-shadowed",fix:"Run the project's own CLI: `pnpm exec lunora …` (or `npx lunora …`).",level:"warn",message:`the running lunora (${s}) is not the project's own install (${r.join(", ")}).`})},Y=async a=>{const e=a.cwd??process.cwd(),n=[],{parsed:r,path:s}=W(e);M(r,s,n),K(r,n),T(r,n),V(e,n),F(n),q(e,n),z(e,n),G(e,a.executablePath??process.argv[1],n),await P(e,n);const o={fail:0,info:0,pass:0,warn:0};for(const d of n)o[d.level]+=1;const i=o.fail>0?1:0;return{code:i,findings:n,ok:i===0,summary:o}},Q={fail:"FAIL",info:"INFO",pass:"PASS",warn:"WARN"},X=(a,e)=>{e.info("lunora doctor — project preflight");for(const s of a.findings){const o=`[${Q[s.level]}] ${s.message}`;s.level==="fail"?e.error(o):s.level==="warn"?e.warn(o):e.info(o),s.fix!==void 0&&s.level!=="pass"&&e.info(` fix: ${s.fix}`)}const{fail:n,warn:r}=a.summary;n>0?e.error(`${String(n)} failure(s), ${String(r)} warning(s).`):r>0?e.warn(`0 failures, ${String(r)} warning(s).`):e.success("all checks passed.")},Z=async a=>{const e=j("doctor",a.format);if(e!==void 0)return a.logger.error(e),{code:1,findings:[],ok:!1,summary:{fail:0,info:0,pass:0,warn:0}};const n=O(a.format,a.logger),r=await Y({...a});return X(r,n),A(a.format)&&L(r),r},ie=R(async({cwd:a,logger:e,options:n})=>({code:(await Z({cwd:a,format:n.format,logger:e})).code}));export{ie as execute,Y as runDoctor,Z as runDoctorCommand};
@@ -1 +1,3 @@
1
- import{existsSync as g,readFileSync as m}from"node:fs";import{join as h}from"node:path";import{isPlaceholderValue as v,DEV_VARS_FILE as p,parseDevVariableEntries as w,discoverSchemaInfo as $,inferLunoraBindings as x}from"@lunora/config";import{findWranglerFile as y,readWranglerJsonc as b,validateWranglerConfig as S,collectExportGaps as k}from"@lunora/config/cloudflare";import{i as _}from"../packem_shared/command-0l-ZPhIX.mjs";import{o as N,p as R}from"../packem_shared/vectorize-metadata-BvZbbqUD.mjs";const A=/(?:KEY|PASSWORD|SECRET|TOKEN)$/u,j=o=>{const e=o.trim();if(e==="")return!0;const n=e.toLowerCase();return n.includes("replace")||n.startsWith("<")&&n.endsWith(">")},O=o=>{const e=y(o);if(e===void 0)return{parsed:void 0,path:void 0};const{parsed:n}=b(e);return{parsed:n,path:e}},E=(o,e,n)=>{if(e===void 0){n.push({fix:"Run `lunora init` (or `lunora dev`) to scaffold and reconcile wrangler.jsonc.",level:"fail",message:"wrangler.jsonc not found."});return}if(o===void 0){n.push({fix:`Check ${e} is valid JSONC.`,level:"fail",message:`Could not parse ${e}.`});return}const t=S(o).errors.find(a=>a.includes("SHARD"));t===void 0?n.push({level:"pass",message:"wrangler.jsonc present with a SHARD durable-object binding."}):n.push({fix:"Run `lunora dev` to auto-reconcile, or add the binding manually.",level:"fail",message:t})},L=(o,e)=>{const{info:n}=$(o,"lunora");for(const t of n?.vectorMetadata??[]){const a=R(t.kind);if(a===void 0){e.push({fix:"Filter on a string, number or boolean column, or drop it from `metadata`.",level:"warn",message:`vector index "${t.index}" declares metadata "${t.property}", whose type Vectorize cannot filter on.`});continue}e.push({fix:`wrangler ${N({index:t.index,property:t.property,type:a}).join(" ")}`,level:"info",message:`vector index "${t.index}" filters on metadata "${t.property}" — that needs a Vectorize metadata index (\`lunora deploy\` creates it).`})}},D=(o,e)=>{if(o===void 0)return;const n=(o.d1_databases??[]).filter(Boolean);for(const t of n){const a=typeof t.database_id=="string"?t.database_id:"";if(j(a)){const r=typeof t.binding=="string"&&t.binding.length>0?t.binding:"<unnamed>";e.push({fix:"Run `wrangler d1 create <name>` and paste the returned database_id into wrangler.jsonc.",level:"fail",message:`D1 binding "${r}" has a placeholder database_id ("${a||"<empty>"}").`})}}},I=(o,e)=>{if(o===void 0)return;const n=(o.send_email??[]).filter(Boolean);for(const t of n){const a=typeof t.destination_address=="string"?t.destination_address:"";if(a!==""&&v(a)){const r=typeof t.name=="string"&&t.name.length>0?t.name:"send_email";e.push({fix:"Set destination_address to a verified Cloudflare Email Routing address.",level:"warn",message:`send_email binding "${r}" has a placeholder destination_address ("${a}").`})}}},C=(o,e)=>{const n=h(o,p);if(!g(n))return;let t;try{t=m(n,"utf8")}catch{return}const a=w(t).filter(r=>A.test(r.key)&&v(r.value)).map(r=>r.key);a.length>0&&e.push({fix:"Run `lunora dev` to auto-generate secrets, or fill them in by hand.",level:"warn",message:`${p} has unfilled secret value(s): ${a.join(", ")}.`})},W=o=>{const e=process.env.LUNORA_ADMIN_TOKEN;e===void 0||e.trim()===""?o.push({fix:"Set LUNORA_ADMIN_TOKEN (env or `.dev.vars`) to enable admin RPCs / studio.",level:"info",message:"LUNORA_ADMIN_TOKEN is not set."}):o.push({level:"pass",message:"LUNORA_ADMIN_TOKEN is set."})},M=async(o,e)=>{let n;try{n=await x({projectRoot:o})}catch{return}const t=k(n),a=[...n.containers.map(r=>({...r,kind:"container"})),...n.workflows.map(r=>({...r,kind:"workflow"})),...n.agents.map(r=>({...r,kind:"agent"}))];for(const r of a.filter(l=>l.exported))e.push({level:"pass",message:`${r.kind} "${r.exportName}" is exported by the worker entry.`});for(const r of t)e.push({fix:`Add \`export * from "./lunora/_generated/${r.module}"\` to your worker entry (or re-run \`vis generate lunora-${r.kind}\`).`,level:"fail",message:`${r.kind} "${r.exportName}" is declared but ${r.className} is not exported by the worker entry.`})},z=/^[\^~><= ]+/u,F=/^(?<core>\d+\.\d+\.\d+)(?:-(?<channel>[a-z]+)\.(?<counter>\d+))?$/u,K=o=>{const e=o.replace(z,"").trim(),n=F.exec(e);if(!n?.groups)return;const{channel:t,core:a,counter:r}=n.groups;return{channel:t??"",core:a??"",counter:r===void 0?void 0:Number.parseInt(r,10),raw:e}},T=(o,e)=>{const n=h(o,"package.json");if(!g(n))return;let t;try{t=JSON.parse(m(n,"utf8"))}catch{return}const a={...t.devDependencies,...t.dependencies},r=[];for(const[s,i]of Object.entries(a)){if(s!=="lunorash"&&!s.startsWith("@lunora/"))continue;const u=K(i);u&&r.push({name:s,version:u})}if(r.length<2)return;const l=s=>s.map(i=>`${i.name}@${i.version.raw}`).join(", "),f=new Set(r.map(s=>s.version.core)),c=new Set(r.map(s=>s.version.channel));if(f.size>1){e.push({fix:'Run `pnpm update "@lunora/*" lunorash` (or `npm`/`yarn` equivalent) so every Lunora package moves to the same release.',level:"warn",message:`Lunora packages span ${String(f.size)} different versions: ${l(r)}.`});return}if(c.size>1){e.push({fix:"Pick one channel (all stable, or all alpha/beta) and update the odd package out.",level:"warn",message:`Lunora packages mix release channels (${[...c].map(s=>s===""?"stable":s).join(" + ")}): ${l(r)}.`});return}const d=r.map(s=>s.version.counter).filter(s=>s!==void 0);if(d.length>1){const s=Math.min(...d),i=Math.max(...d);e.push({level:"info",message:d.length===r.length&&s===i?`Lunora packages are all at ${[...c][0]??""}.${String(i)}.`:`Lunora pre-release counters span ${String(s)}–${String(i)}: ${l(r)}.`})}},V=async o=>{const e=o.cwd??process.cwd(),n=[],{parsed:t,path:a}=O(e);return E(t,a,n),D(t,n),I(t,n),C(e,n),W(n),T(e,n),L(e,n),await M(e,n),{code:n.some(r=>r.level==="fail")?1:0,findings:n}},P={fail:"FAIL",info:"INFO",pass:"PASS",warn:"WARN"},B=(o,e)=>{e.info("lunora doctor — project preflight");for(const a of o.findings){const r=`[${P[a.level]}] ${a.message}`;a.level==="fail"?e.error(r):a.level==="warn"?e.warn(r):e.info(r),a.fix!==void 0&&a.level!=="pass"&&e.info(` fix: ${a.fix}`)}const n=o.findings.filter(a=>a.level==="fail").length,t=o.findings.filter(a=>a.level==="warn").length;n>0?e.error(`${String(n)} failure(s), ${String(t)} warning(s).`):t>0?e.warn(`0 failures, ${String(t)} warning(s).`):e.success("all checks passed.")},Q=_(async({cwd:o,logger:e})=>{const n=await V({cwd:o});return B(n,e),{code:n.code}});export{Q as execute,V as runDoctor};
1
+ import{writeFileSync as $,existsSync as h,readFileSync as V}from"node:fs";import{join as S}from"node:path";import{DEV_VARS_FILE as u,DEV_VARS_KEY_PATTERN as k,upsertDevVariableLine as A,isPlaceholderValue as P,resolveDeployDriver as K,resolveProjectTarget as R,generateSecretValue as D,DEV_VARS_EXAMPLE_FILE as v,parseDevVariableEntries as _,escapeRegExp as U,packageNamesFromBindings as Y,inferLunoraBindings as j,requiredSecrets as Z,isMintableSecretKey as E}from"@lunora/config";import{i as q}from"../packem_shared/command-0l-ZPhIX.mjs";import{l as C,M as F}from"../packem_shared/detect-package-manager-DXDstphE.mjs";import{defaultSpawner as M}from"../packem_shared/createRecordingSpawner-SKs4R1fc.mjs";import{f as B}from"../packem_shared/wrangler-secrets-D0Tv5GWn.mjs";const I=/[\r\n]/u,N=/["\\]/u,x=e=>new Map(_(e).map(s=>[s.key,s])),g=e=>h(e)?V(e,"utf8"):"",T=(e,s)=>e.replaceAll(new RegExp(String.raw`^[ \t]*${U(s)}[ \t]*=.*(?:\r?\n|$)`,"gmu"),""),L=e=>e.length<=4?"****":`${e.slice(0,4)}${"*".repeat(Math.min(8,e.length-4))}`,f=e=>x(g(e)),z=e=>e.env??(e.prod===!0?"production":void 0),X=e=>{const s=f(e.devVariablesPath);if(s.size===0)return e.logger.info(`${u}: (empty)`),{code:0,descriptors:[]};for(const t of s.values())e.logger.info(`${t.key}=${L(t.value)}`);return{code:0,descriptors:[]}},G=e=>{const{devVariablesPath:s,logger:t,options:r}=e;if(!r.key)return t.error("env get requires a key. Usage: lunora env get <KEY>"),{code:1,descriptors:[]};const o=f(s).get(r.key);return o?(process.stdout.write(`${o.value}
2
+ `),{code:0,descriptors:[]}):(t.error(`env: ${r.key} is not set in ${u}`),{code:1,descriptors:[]})},H=e=>{const{devVariablesPath:s,logger:t,options:r}=e;if(!r.key)return t.error("env set requires a key. Usage: lunora env set <KEY> <VALUE>"),{code:1,descriptors:[]};if(!k.test(r.key))return t.error(`env: invalid key "${r.key}" — must match [A-Za-z_][A-Za-z0-9_]*`),{code:1,descriptors:[]};if(r.value===void 0)return t.error("env set requires a value. Usage: lunora env set <KEY> <VALUE>"),{code:1,descriptors:[]};if(I.test(r.value))return t.error(`env: value for "${r.key}" contains a newline, which .dev.vars cannot represent`),{code:1,descriptors:[]};if(N.test(r.value))return t.error(`env: value for "${r.key}" contains a double-quote or backslash, which .dev.vars cannot round-trip`),{code:1,descriptors:[]};const o=g(s);return $(s,A(o,r.key,r.value),"utf8"),t.success(`env: set ${r.key} (${L(r.value)}) in ${u}`),{code:0,descriptors:[]}},J=e=>{const{devVariablesPath:s,logger:t,options:r}=e;if(!r.key)return t.error("env unset requires a key. Usage: lunora env unset <KEY>"),{code:1,descriptors:[]};if(!k.test(r.key))return t.error(`env: invalid key "${r.key}" — must match [A-Za-z_][A-Za-z0-9_]*`),{code:1,descriptors:[]};const o=g(s);return x(o).has(r.key)?($(s,T(o,r.key),"utf8"),t.success(`env: unset ${r.key} in ${u}`),{code:0,descriptors:[]}):(t.warn(`env: ${r.key} was not set in ${u}`),{code:0,descriptors:[]})},Q=async e=>{const{devVariablesPath:s,logger:t,options:r}=e;if(!r.yes)return t.error("env push uploads secrets to Cloudflare. Re-run with --yes to confirm."),{code:1,descriptors:[]};const o=f(s);if(o.size===0)return t.warn(`${u}: nothing to push (empty)`),{code:0,descriptors:[]};const i=[...o.values()].filter(n=>P(n.value)).map(n=>n.key);if(i.length>0)return t.error(`env push: refusing to upload placeholder value(s) for ${i.join(", ")} — run \`lunora env doctor\` to review, and \`lunora env generate --set\` (or \`lunora env set <KEY> <VALUE>\`) to fill them, then re-run.`),{code:1,descriptors:[]};const c=r.spawner??M,d=r.cwd??process.cwd(),p=C(d),a=[],l=z(r);for(const n of o.values()){const m=K(R(d)).toolchain?.secretPut({environment:l,key:n.key,temporary:r.temporary});if(m===void 0)return t.error("deploy target has no command-line toolchain; cannot push secrets"),{code:1,descriptors:[]};const w=F(p,m.tool,m.args),b={args:w.args,command:w.command,cwd:d,input:n.value};a.push(b),t.info(`pushing ${n.key} -> wrangler secret${l===void 0?"":` (${l})`}`);const y=await c(b);if(y.code!==0)return t.error(`env push: failed at ${n.key} (exit ${String(y.code)})`),{code:y.code,descriptors:a}}return t.success(`env: pushed ${String(o.size)} secret(s)`),{code:0,descriptors:a}},W=e=>(e.options.secretLister??B)({cwd:e.cwd,env:z(e.options),temporary:e.options.temporary}),O=async e=>{const{devVariablesPath:s,logger:t}=e,r=await W(e);if(!r.ok)return t.error(`env diff: ${r.error??"failed to list remote secrets"}`),{code:1,descriptors:[]};const o=new Set(f(s).keys()),i=new Set(r.names),c=[...o].filter(a=>!i.has(a)).toSorted((a,l)=>a.localeCompare(l)),d=r.names.filter(a=>!o.has(a)),p=[...o].filter(a=>i.has(a)).toSorted((a,l)=>a.localeCompare(l));for(const a of c)t.info(`local only (run \`lunora env push\`): ${a}`);for(const a of d)t.info(`remote only (in Cloudflare, not ${u}): ${a}`);return t.info(`in both: ${String(p.length)} secret(s)`),c.length===0&&d.length===0&&t.success("env diff: local and remote secret names match"),{code:0,descriptors:[]}},ee=e=>{const{cwd:s,devVariablesPath:t,logger:r}=e,o=S(s,v);if(!h(o))return r.info(`env doctor: no ${v} to check against — nothing to validate.`),{code:0,descriptors:[]};const i=_(V(o,"utf8")).map(n=>n.key),c=f(t);if(!h(t))return r.error(`env doctor: ${u} is missing. Run \`lunora dev\` to scaffold it, or \`lunora env set <KEY> <VALUE>\`.`),r.info(`expected (from ${v}): ${i.join(", ")}`),{code:1,descriptors:[]};const d=i.filter(n=>!c.has(n)),p=[...c.values()].filter(n=>P(n.value)).map(n=>n.key),a=new Set(i),l=[...c.keys()].filter(n=>!a.has(n));for(const n of d)r.error(`missing: ${n} is in ${v} but not ${u}`);for(const n of p)r.error(`unset: ${n} still has a placeholder value`);for(const n of l)r.info(`extra: ${n} is set locally but not listed in ${v}`);return d.length===0&&p.length===0?(r.success(`env doctor: ${u} looks good (${String(c.size)} var(s)).`),{code:0,descriptors:[]}):{code:1,descriptors:[]}},re=async e=>{let s=[];try{s=Y(await j({projectRoot:e.cwd}))}catch{}const t=Z(s).map(o=>o.key).filter(o=>E(o)),r=[...f(e.devVariablesPath).keys()].filter(o=>E(o));return[...new Set([...t,...r])]},te=async e=>{const{devVariablesPath:s,logger:t,options:r}=e;let o;if(r.key===void 0){if(o=await re(e),o.length===0)return t.info("env generate: no locally-generatable secrets for this project. Name one explicitly: lunora env generate <KEY>"),{code:0,descriptors:[]}}else{if(!k.test(r.key))return t.error(`env: invalid key "${r.key}" — must match [A-Za-z_][A-Za-z0-9_]*`),{code:1,descriptors:[]};o=[r.key]}const i=o.map(c=>({key:c,value:D()}));if(r.set===!0){let c=g(s);for(const d of i)c=A(c,d.key,d.value);return $(s,c,"utf8"),t.success(`env: generated ${String(i.length)} secret(s) into ${u}: ${i.map(d=>d.key).join(", ")}`),{code:0,descriptors:[]}}for(const c of i)process.stdout.write(`${c.key}=${c.value}
3
+ `);return{code:0,descriptors:[]}},oe=async e=>{const s=e.cwd??process.cwd(),t={cwd:s,devVariablesPath:S(s,u),logger:e.logger,options:e};switch(e.subcommand){case"diff":return O(t);case"doctor":return ee(t);case"generate":return te(t);case"get":return G(t);case"list":return X(t);case"push":return Q(t);case"set":return H(t);case"unset":return J(t);default:return e.logger.error(`env: unknown subcommand "${e.subcommand}"`),{code:1,descriptors:[]}}},se=new Set(["diff","doctor","generate","get","list","push","set","unset"]),ne=e=>typeof e=="string"&&se.has(e),fe=q(({argument:e,cwd:s,logger:t,options:r})=>{const o=e[0];return ne(o)?oe({cwd:s,env:r.env,key:e[1],logger:t,prod:r.prod===!0,set:r.set===!0,subcommand:o,temporary:r.temporary===!0,value:e[2],yes:r.yes===!0}):(t.error(`env: unknown subcommand "${o??""}" — expected list | get | set | unset | push | diff | doctor | generate`),{code:1})});export{fe as execute,oe as runEnvCommand};
@@ -1,3 +1 @@
1
- import{writeFileSync as $,existsSync as h,readFileSync as V}from"node:fs";import{join as S}from"node:path";import{DEV_VARS_FILE as u,DEV_VARS_KEY_PATTERN as k,upsertDevVariableLine as A,isPlaceholderValue as P,resolveDeployDriver as K,resolveProjectTarget as R,generateSecretValue as D,DEV_VARS_EXAMPLE_FILE as v,parseDevVariableEntries as _,escapeRegExp as U,packageNamesFromBindings as Y,inferLunoraBindings as j,requiredSecrets as Z,isMintableSecretKey as E}from"@lunora/config";import{i as q}from"../packem_shared/command-0l-ZPhIX.mjs";import{l as C,M as F}from"../packem_shared/detect-package-manager-DXDstphE.mjs";import{defaultSpawner as M}from"../packem_shared/createRecordingSpawner-SKs4R1fc.mjs";import{f as B}from"../packem_shared/wrangler-secrets-D0Tv5GWn.mjs";const I=/[\r\n]/u,N=/["\\]/u,x=e=>new Map(_(e).map(s=>[s.key,s])),g=e=>h(e)?V(e,"utf8"):"",T=(e,s)=>e.replaceAll(new RegExp(String.raw`^[ \t]*${U(s)}[ \t]*=.*(?:\r?\n|$)`,"gmu"),""),L=e=>e.length<=4?"****":`${e.slice(0,4)}${"*".repeat(Math.min(8,e.length-4))}`,f=e=>x(g(e)),z=e=>e.env??(e.prod===!0?"production":void 0),X=e=>{const s=f(e.devVariablesPath);if(s.size===0)return e.logger.info(`${u}: (empty)`),{code:0,descriptors:[]};for(const t of s.values())e.logger.info(`${t.key}=${L(t.value)}`);return{code:0,descriptors:[]}},G=e=>{const{devVariablesPath:s,logger:t,options:r}=e;if(!r.key)return t.error("env get requires a key. Usage: lunora env get <KEY>"),{code:1,descriptors:[]};const o=f(s).get(r.key);return o?(process.stdout.write(`${o.value}
2
- `),{code:0,descriptors:[]}):(t.error(`env: ${r.key} is not set in ${u}`),{code:1,descriptors:[]})},H=e=>{const{devVariablesPath:s,logger:t,options:r}=e;if(!r.key)return t.error("env set requires a key. Usage: lunora env set <KEY> <VALUE>"),{code:1,descriptors:[]};if(!k.test(r.key))return t.error(`env: invalid key "${r.key}" — must match [A-Za-z_][A-Za-z0-9_]*`),{code:1,descriptors:[]};if(r.value===void 0)return t.error("env set requires a value. Usage: lunora env set <KEY> <VALUE>"),{code:1,descriptors:[]};if(I.test(r.value))return t.error(`env: value for "${r.key}" contains a newline, which .dev.vars cannot represent`),{code:1,descriptors:[]};if(N.test(r.value))return t.error(`env: value for "${r.key}" contains a double-quote or backslash, which .dev.vars cannot round-trip`),{code:1,descriptors:[]};const o=g(s);return $(s,A(o,r.key,r.value),"utf8"),t.success(`env: set ${r.key} (${L(r.value)}) in ${u}`),{code:0,descriptors:[]}},J=e=>{const{devVariablesPath:s,logger:t,options:r}=e;if(!r.key)return t.error("env unset requires a key. Usage: lunora env unset <KEY>"),{code:1,descriptors:[]};if(!k.test(r.key))return t.error(`env: invalid key "${r.key}" — must match [A-Za-z_][A-Za-z0-9_]*`),{code:1,descriptors:[]};const o=g(s);return x(o).has(r.key)?($(s,T(o,r.key),"utf8"),t.success(`env: unset ${r.key} in ${u}`),{code:0,descriptors:[]}):(t.warn(`env: ${r.key} was not set in ${u}`),{code:0,descriptors:[]})},Q=async e=>{const{devVariablesPath:s,logger:t,options:r}=e;if(!r.yes)return t.error("env push uploads secrets to Cloudflare. Re-run with --yes to confirm."),{code:1,descriptors:[]};const o=f(s);if(o.size===0)return t.warn(`${u}: nothing to push (empty)`),{code:0,descriptors:[]};const i=[...o.values()].filter(n=>P(n.value)).map(n=>n.key);if(i.length>0)return t.error(`env push: refusing to upload placeholder value(s) for ${i.join(", ")} — run \`lunora env doctor\` to review, and \`lunora env generate --set\` (or \`lunora env set <KEY> <VALUE>\`) to fill them, then re-run.`),{code:1,descriptors:[]};const c=r.spawner??M,d=r.cwd??process.cwd(),p=C(d),a=[],l=z(r);for(const n of o.values()){const m=K(R(d)).toolchain?.secretPut({environment:l,key:n.key,temporary:r.temporary});if(m===void 0)return t.error("deploy target has no command-line toolchain; cannot push secrets"),{code:1,descriptors:[]};const w=F(p,m.tool,m.args),b={args:w.args,command:w.command,cwd:d,input:n.value};a.push(b),t.info(`pushing ${n.key} -> wrangler secret${l===void 0?"":` (${l})`}`);const y=await c(b);if(y.code!==0)return t.error(`env push: failed at ${n.key} (exit ${String(y.code)})`),{code:y.code,descriptors:a}}return t.success(`env: pushed ${String(o.size)} secret(s)`),{code:0,descriptors:a}},W=e=>(e.options.secretLister??B)({cwd:e.cwd,env:z(e.options),temporary:e.options.temporary}),O=async e=>{const{devVariablesPath:s,logger:t}=e,r=await W(e);if(!r.ok)return t.error(`env diff: ${r.error??"failed to list remote secrets"}`),{code:1,descriptors:[]};const o=new Set(f(s).keys()),i=new Set(r.names),c=[...o].filter(a=>!i.has(a)).toSorted((a,l)=>a.localeCompare(l)),d=r.names.filter(a=>!o.has(a)),p=[...o].filter(a=>i.has(a)).toSorted((a,l)=>a.localeCompare(l));for(const a of c)t.info(`local only (run \`lunora env push\`): ${a}`);for(const a of d)t.info(`remote only (in Cloudflare, not ${u}): ${a}`);return t.info(`in both: ${String(p.length)} secret(s)`),c.length===0&&d.length===0&&t.success("env diff: local and remote secret names match"),{code:0,descriptors:[]}},ee=e=>{const{cwd:s,devVariablesPath:t,logger:r}=e,o=S(s,v);if(!h(o))return r.info(`env doctor: no ${v} to check against — nothing to validate.`),{code:0,descriptors:[]};const i=_(V(o,"utf8")).map(n=>n.key),c=f(t);if(!h(t))return r.error(`env doctor: ${u} is missing. Run \`lunora dev\` to scaffold it, or \`lunora env set <KEY> <VALUE>\`.`),r.info(`expected (from ${v}): ${i.join(", ")}`),{code:1,descriptors:[]};const d=i.filter(n=>!c.has(n)),p=[...c.values()].filter(n=>P(n.value)).map(n=>n.key),a=new Set(i),l=[...c.keys()].filter(n=>!a.has(n));for(const n of d)r.error(`missing: ${n} is in ${v} but not ${u}`);for(const n of p)r.error(`unset: ${n} still has a placeholder value`);for(const n of l)r.info(`extra: ${n} is set locally but not listed in ${v}`);return d.length===0&&p.length===0?(r.success(`env doctor: ${u} looks good (${String(c.size)} var(s)).`),{code:0,descriptors:[]}):{code:1,descriptors:[]}},re=async e=>{let s=[];try{s=Y(await j({projectRoot:e.cwd}))}catch{}const t=Z(s).map(o=>o.key).filter(o=>E(o)),r=[...f(e.devVariablesPath).keys()].filter(o=>E(o));return[...new Set([...t,...r])]},te=async e=>{const{devVariablesPath:s,logger:t,options:r}=e;let o;if(r.key===void 0){if(o=await re(e),o.length===0)return t.info("env generate: no locally-generatable secrets for this project. Name one explicitly: lunora env generate <KEY>"),{code:0,descriptors:[]}}else{if(!k.test(r.key))return t.error(`env: invalid key "${r.key}" — must match [A-Za-z_][A-Za-z0-9_]*`),{code:1,descriptors:[]};o=[r.key]}const i=o.map(c=>({key:c,value:D()}));if(r.set===!0){let c=g(s);for(const d of i)c=A(c,d.key,d.value);return $(s,c,"utf8"),t.success(`env: generated ${String(i.length)} secret(s) into ${u}: ${i.map(d=>d.key).join(", ")}`),{code:0,descriptors:[]}}for(const c of i)process.stdout.write(`${c.key}=${c.value}
3
- `);return{code:0,descriptors:[]}},oe=async e=>{const s=e.cwd??process.cwd(),t={cwd:s,devVariablesPath:S(s,u),logger:e.logger,options:e};switch(e.subcommand){case"diff":return O(t);case"doctor":return ee(t);case"generate":return te(t);case"get":return G(t);case"list":return X(t);case"push":return Q(t);case"set":return H(t);case"unset":return J(t);default:return e.logger.error(`env: unknown subcommand "${e.subcommand}"`),{code:1,descriptors:[]}}},se=new Set(["diff","doctor","generate","get","list","push","set","unset"]),ne=e=>typeof e=="string"&&se.has(e),fe=q(({argument:e,cwd:s,logger:t,options:r})=>{const o=e[0];return ne(o)?oe({cwd:s,env:r.env,key:e[1],logger:t,prod:r.prod===!0,set:r.set===!0,subcommand:o,temporary:r.temporary===!0,value:e[2],yes:r.yes===!0}):(t.error(`env: unknown subcommand "${o??""}" — expected list | get | set | unset | push | diff | doctor | generate`),{code:1})});export{fe as execute,oe as runEnvCommand};
1
+ import{i as p}from"../packem_shared/command-0l-ZPhIX.mjs";import{d as u}from"../packem_shared/resolve-target-CeiNrCAx.mjs";import{runExportCommand as d}from"../packem_shared/runExportCommand-BpE4AbuX.mjs";const a=p(({argument:r,cwd:t,logger:e,options:o})=>d({cwd:t,logger:e,out:r[0]??o.out,prod:o.prod===!0,tables:o.tables,token:o.token,url:u({cwd:t,prod:o.prod===!0,url:o.url})}));export{a as execute};
@@ -1 +1 @@
1
- import{existsSync as $,readFileSync as x}from"node:fs";import{runCodegen as _,discoverMigrations as O}from"@lunora/codegen";import{readLinkedProject as N,writeLinkedProject as P,resolveDeployDriver as T,inferLunoraBindings as L,DEV_VARS_FILE as y,parseDevVariableEntries as U,isMintableSecretKey as C,discoverContainerInfo as I,packageNamesFromBindings as W,requiredSecrets as B,generateSecretValue as K,upsertDevVariableLine as q,writeDevVariablesFileAtomically as M,discoverSchemaInfo as V}from"@lunora/config";import{validateWranglerProject as Y,reconcileWranglerBindings as G,reconcileWranglerCompatibilityDate as z,reconcileWranglerCrons as H,findWranglerFile as J,readWranglerJsonc as Q}from"@lunora/config/cloudflare";import{join as f}from"@visulima/path";import{Spinner as X}from"@visulima/spinner";import{Project as Z}from"ts-morph";import{n as ee,t as re}from"../packem_shared/advisory-gate-yaOOyUQl.mjs";import{r as te}from"../packem_shared/api-spec-BENwiyUa.mjs";import{d as E}from"../packem_shared/wrangler-name-CHDf3rMP.mjs";import{i as oe}from"../packem_shared/command-0l-ZPhIX.mjs";import{i as ne}from"../packem_shared/deploy-target-Dvr9vxpR.mjs";import{M as S,l as R}from"../packem_shared/detect-package-manager-DXDstphE.mjs";import{o as ie,r as ae}from"../packem_shared/docker-CKvYE9YF.mjs";import{i as se,t as b,d as ce,s as le}from"../packem_shared/output-format-Cv3aLqhP.mjs";import{a as de}from"../packem_shared/platform-diagnostics-C4TFj5Pu.mjs";import{m as ge}from"../packem_shared/post-codegen-hook-DhL1RH5u.mjs";import{containerBuildTag as ue}from"@lunora/container";import{defaultSpawner as D}from"../packem_shared/createRecordingSpawner-SKs4R1fc.mjs";import{i as pe}from"../packem_shared/resolve-target-CeiNrCAx.mjs";import{R as me}from"../packem_shared/schema-drift-gate-d12lMICD.mjs";import{I as fe}from"../packem_shared/tui-prompts-BU3irGxV.mjs";import{m as ve,p as he}from"../packem_shared/vectorize-metadata-BvZbbqUD.mjs";import{f as we}from"../packem_shared/wrangler-secrets-D0Tv5GWn.mjs";import{runMigrateDataCommand as ye}from"./runMigrateGenerateCommand.mjs";const $e=/https?:\/\/[^\s"'<>]+\.workers\.dev[^\s"'<>]*/u,ke=/https:\/\/[^\s"'<>]+/u,be=e=>{const r=$e.exec(e);return r?r[0]:ke.exec(e)?.[0]},Se=({cwd:e,env:r,logger:t,now:o,output:n})=>{if(n===void 0||N(e)!==void 0)return;const i=be(n);if(i!==void 0)try{const a=(o??(()=>new Date().toISOString()))();P(e,{env:r,linkedAt:a,workerName:E(e),workerUrl:i}),t.success(`link: recorded ${i} in .lunora/project.json (run \`lunora link\` to change)`)}catch{}},Re=e=>{const{cwd:r,env:t,logger:o,migrated:n,mintedSecretsFile:i}=e;try{const a=N(r),c=a?.workerName??E(r);o.success("deploy complete"),o.info(` worker: ${c??"(see wrangler output above)"}`),t!==void 0&&o.info(` env: ${t}`),a?.workerUrl===void 0?o.info(" url: run `lunora link --url <https://your-worker>` to record it"):o.info(` url: ${a.workerUrl}`),n&&o.info(" migrations: applied"),i!==void 0&&o.info(` secrets: generated value(s) recorded in ${i}`),o.info(" studio: lunora view --remote"),o.info(" logs: lunora logs")}catch{}},De=async e=>{if(e.targets.length===0)return{builtTags:[],code:0};if(!(e.railpackAvailable??ie)()){const o="deploy blocked: a container uses `image: { build }` (Railpack), but Railpack isn't ready. Install the `railpack` CLI and start a BuildKit instance, e.g. `docker run --rm --privileged -d --name buildkit moby/buildkit` then `export BUILDKIT_HOST=docker-container://buildkit`. Alternatively switch the container's `image` to a Dockerfile path or a pre-built registry reference.";return e.logger.error(o),{builtTags:[],code:1,error:o}}const r=e.spawner??D,t=[];for(const o of e.targets){const n=ue(o.exportName),i={args:["build",o.buildDir,"--name",n],command:"railpack",cwd:e.cwd},a=S(R(e.cwd),"wrangler",["containers","push",n]),c={args:a.args,command:a.command,cwd:e.cwd};e.logger.info(`railpack: building "${o.exportName}" → ${n} from ${o.buildDir}`);const d=await r(i);if(d.code!==0){const s=`railpack build failed for container "${o.exportName}" (${o.buildDir})`;return e.logger.error(s),{builtTags:t,code:d.code,error:s}}e.logger.info(`railpack: pushing ${n} to the Cloudflare Registry`);const l=await r(c);if(l.code!==0){const s=`wrangler containers push failed for "${o.exportName}" (${n})`;return e.logger.error(s),{builtTags:t,code:l.code,error:s}}t.push(n)}return{builtTags:t,code:0}},F="<replace-with-d1-create-id>",A=e=>{const r=J(e);return r?Q(r).parsed:void 0},je=["LUNORA_ORIGIN_URL","LUNORA_WORKER_ORIGIN","AUTH_URL"],xe=e=>{try{const{hostname:r}=new URL(e);return r==="localhost"||r==="127.0.0.1"||r==="::1"||r==="[::1]"}catch{return!1}},Ne=e=>e.startsWith("./")||e.startsWith("../")||e.startsWith("/")||e.includes("Dockerfile"),Te=(e,r,t)=>{const o=(A(e)?.containers??[]).filter(i=>typeof i?.image=="string"&&Ne(i.image));if(o.length===0||t())return;const n=`deploy blocked: wrangler.jsonc declares ${String(o.length)} container(s) built from a local Dockerfile, but no Docker-compatible engine is available. Start Docker (or Colima), or point the container's \`image\` at a pre-built registry reference. Note: container images must target linux/amd64.`;return r.error(n),n},Ae=e=>$(f(e,"src","worker.ts"))?"src/worker.ts":void 0,Ce=(e,r)=>{for(const t of I(e,"lunora").containers){const{image:o}=t;if(o.kind==="dockerfile"&&!$(f(e,o.dockerfilePath))){const n=`deploy blocked: container "${t.exportName}" references a Dockerfile at "${o.dockerfilePath}" that does not exist. Create it or fix the \`image\` path in lunora/containers.ts.`;return r.error(n),n}if(o.kind==="build"&&!$(f(e,o.buildDir))){const n=`deploy blocked: container "${t.exportName}" references a Railpack build directory "${o.buildDir}" that does not exist. Create it or fix the \`image.build\` path in lunora/containers.ts.`;return r.error(n),n}}},Le=e=>b(e.format)?!1:e.interactive!==void 0?e.interactive:process.stdout.isTTY&&!process.env.CI,Ue=e=>(A(e)?.d1_databases??[]).find(r=>r.database_id===F)?.binding,Ie=async(e,r)=>{const t=I(e,"lunora").containers.filter(n=>n.image.kind==="build").map(n=>({buildDir:n.image.buildDir,exportName:n.exportName}));if(t.length===0)return;const o=await De({cwd:e,logger:r.logger,railpackAvailable:r.railpackAvailable,spawner:r.spawner,targets:t});return o.code===0?void 0:o.error??"railpack build failed"},Ee=(e,r,t)=>{if(t!==void 0)try{const o=H(e,t);o.changed&&r.success(`synced ${String(t.length)} cron trigger(s) → ${o.wranglerPath??"wrangler.jsonc"}`)}catch(o){const n=o instanceof Error?o.message:String(o);r.warn(`cron trigger sync skipped: ${n}`)}},Fe=async(e,r,t,o,n)=>{try{T(o);const i=await L({projectRoot:e}),a=G(e,i,n);a.changed&&r.success(`provisioned bindings: ${a.added.join(", ")} → ${a.wranglerPath??"wrangler.jsonc"}`);for(const c of a.warnings)r.warn(c)}catch(i){const a=i instanceof Error?i.message:String(i);r.warn(`binding inference skipped: ${a}`)}try{const i=z(e);i.changed&&r.success(`bumped compatibility_date to ${i.date??"unknown"} (Workers Cache enabled) → ${i.wranglerPath??"wrangler.jsonc"}`)}catch(i){const a=i instanceof Error?i.message:String(i);r.warn(`compatibility date sync skipped: ${a}`)}Ee(e,r,t)},_e=(e,r)=>{const t=f(e,y);if(!$(t))return;let o;try{o=U(x(t,"utf8")).length}catch{return}o!==0&&r.warn(`Note: \`lunora deploy\` does not push secrets. ${y} has ${String(o)} key(s); if you changed them, run \`lunora env push --yes\` to update the deployed secrets.`)},Oe=/(?:KEY|PASSWORD|SECRET|TOKEN)$/u,Pe=async e=>{let r=[];try{r=W(await L({projectRoot:e}))}catch{}const t=B(r).map(n=>n.key);let o=[];try{const n=f(e,y);$(n)&&(o=U(x(n,"utf8")).map(i=>i.key).filter(i=>Oe.test(i)))}catch{}return[...new Set([...t,...o])]},We=async(e,r,t,o)=>{const{logger:n}=r,i=r.spawner??D,a=R(e),c=r.env===void 0?"":` --env ${r.env}`,{toolchain:d}=T(o);if(d===void 0)return n.error("deploy target has no command-line toolchain; cannot push secrets"),{minted:[],ok:!1};const l=[];for(const s of t){const g=K(),u=d.secretPut({environment:r.env,key:s,temporary:r.temporary}),v=S(a,u.tool,u.args),m=await i({args:v.args,command:v.command,cwd:e,input:g});if(m.code!==0)return n.error(`failed to push secret ${s} (exit ${String(m.code)}); set it manually with \`wrangler secret put ${s}${c}\`.`),{minted:l,ok:!1};l.push({key:s,value:g}),n.success(`generated + pushed ${s}`)}return{minted:l,ok:!0}},Be=/^[\w-]+$/u,Ke=(e,r,t)=>{if(t.length===0)return;const o=t.map(c=>c.key).join(", ");if(r.env!==void 0&&!Be.test(r.env)){r.logger.warn(`${o}: minted and pushed for --env ${r.env}, but "${r.env}" isn't a safe filename fragment — the value could not be recorded. Capture it manually if you need it again.`);return}const n=r.env===void 0?y:`${y}.${r.env}`,i=f(e,n);let a=$(i)?x(i,"utf8"):"";for(const c of t)a=q(a,c.key,c.value);return M(i,a),r.logger.success(r.env===void 0?`${o}: value(s) recorded in ${n}`:`${o}: value(s) recorded in ${n} (kept separate from ${y} so \`lunora dev\` and a plain \`lunora env push\` don't inherit the --env ${r.env} value)`),n},qe=async(e,r,t,o)=>{if(r.dryRun===!0||r.preview===!0)return{};const{logger:n}=r,i=r.env===void 0?"":` --env ${r.env}`;let a;try{a=await(r.secretLister??we)({cwd:e,env:r.env,temporary:r.temporary})}catch{return{}}if(!a.ok)return{};const c=new Set(a.names),d=(await Pe(e)).filter(s=>!c.has(s));if(d.length===0)return{};if(!t)return{error:`missing required secret(s) on the deploy target: ${d.join(", ")}. Set them with \`wrangler secret put <KEY>${i}\` (or \`lunora env generate --set\` then \`lunora env push --yes${i}\`), then re-deploy.`};for(const s of d.filter(g=>!C(g)))n.warn(`required secret ${s} is not set on the target — set it with: wrangler secret put ${s}${i}`);const l=d.filter(s=>C(s));if(l.length===0)return{};if(await(r.secretConfirm??fe())(`${String(l.length)} required secret(s) not set on the target (${l.join(", ")}). Generate strong values and push them now?`)){const{minted:s,ok:g}=await We(e,r,l,o),u=Ke(e,r,s);return g?{mintedSecretsFile:u}:{error:"failed to push required secret(s) — set them manually and re-deploy",mintedSecretsFile:u}}return n.warn(`${String(l.length)} required secret(s) not set on the target: ${l.join(", ")}. Generate + push with \`lunora env generate --set\` then \`lunora env push --yes${i}\`.`),{}},Me=async(e,r)=>{const t=new Z({skipAddingFilesFromTsConfig:!0}),o=f(r,"lunora");let n;try{n=O(t,o)}catch(i){const a=i instanceof Error?i.message:String(i);return e.logger.warn(`--migrate: could not discover migrations (${a}); skipping`),0}if(n.length===0)return e.logger.info("--migrate: no data migrations declared in lunora/"),0;e.logger.info(`--migrate: running ${String(n.length)} migration(s) against deployed worker`);for(const i of n){e.logger.info(`--migrate: up "${i.id}" (table "${i.table}")`);const a={cwd:r,fetchImpl:e.fetchImpl,id:i.id,logger:e.logger,prod:!0,subcommand:"up",token:e.migrateToken,url:e.migrateUrl,yes:e.migrateYes===!0},c=await ye(a);if(c.code!==0)return e.logger.error(`--migrate: migration "${i.id}" failed — see output above`),c.code;e.logger.success(`--migrate: "${i.id}" applied`)}return 0},Ve=e=>{if(!e.migrate||e.dryRun||e.preview)return;if(e.migrateUrl===void 0){const t="--migrate requires --migrate-url <https://your-worker> — the deploy target URL is not captured automatically, refusing to default to localhost";return e.logger.error(t),t}if(e.migrateYes!==!0){const t="--migrate runs production data migrations after deploy. Re-run with --migrate-yes to confirm.";return e.logger.error(t),t}const r=e.migrateToken??process.env.LUNORA_ADMIN_TOKEN;if(r===void 0||r===""){const t="admin token required for --migrate — pass --migrate-token or set LUNORA_ADMIN_TOKEN";return e.logger.error(t),t}},Ye=async(e,r,t,o,n,i,a,c)=>{let d;r?(d=new X({name:"dots"}),d.start("running codegen")):t.info("running codegen");try{const l=_({apiSpec:o,projectRoot:e,target:n});d?.succeed("codegen complete"),d||t.success("codegen complete");const s=de(l.platformDiagnostics,t);if(s!==void 0)return{error:s};const{errorAdvisories:g,names:u,shouldBlock:v}=ee(l.advisories,c);if(v){const k=`${g.length.toString()} ERROR-level ${g.length===1?"advisory":"advisories"} (${u.join(", ")}). Pass --no-strict-advisories to downgrade this to a warning and deploy anyway.`;return t.error(k),{error:k}}const m=await ge({cwd:e,logger:t,spawner:i,stdoutToStderr:a});return m.error!==void 0?(t.error(m.error),{error:m.error}):{result:l}}catch(l){d?.failed("codegen failed");const s=l instanceof Error?l.message:String(l);return t.error(`codegen failed: ${s}`),{error:`codegen failed: ${s}`}}},Ge=(e,r)=>{const t=Ue(e);if(t===void 0)return;const o=`deploy blocked: the "${t}" D1 binding has a placeholder database_id ("${F}"). Run \`wrangler d1 create <name>\` to create the database, then replace the placeholder in wrangler.jsonc with the real id before deploying.`;return r.error(o),o},ze=(e,r)=>{const t=A(e)?.vars;if(!t)return;const o=je.filter(i=>typeof t[i]=="string"&&xe(t[i]));if(o.length===0)return;const n=`deploy blocked: ${o.join(", ")} in wrangler.jsonc point at localhost. A deployed Worker can't reach a loopback address, so this silently breaks scheduled-job dispatch / auth callbacks. Set each to the deployed worker's public URL (or move it to a secret with \`wrangler secret put\`) before deploying.`;return r.error(n),n},He=async(e,r)=>{const{info:t}=V(r,"lunora"),o=t?.vectorMetadata??[];if(o.length===0)return;const n=[];for(const a of o){const c=he(a.kind);if(c===void 0){e.logger.warn(`vector index "${a.index}" declares metadata "${a.property}", whose column type cannot be filtered on in Vectorize — it is stored with each vector but no filter will match it.`);continue}n.push({index:a.index,property:a.property,type:c})}if(n.length===0)return;const i=(await ve({cwd:r,entries:n,exec:S(R(r),"wrangler",[]),logger:e.logger,spawner:e.spawner??D})).filter(a=>a.status!=="failed").length;i>0&&e.logger.success(`vectorize metadata indexes ready: ${String(i)}/${String(n.length)}`)},Je=async(e,r,t,o,n,i)=>{await He(e,r);const a=e.migrate?await Me(e,r):0;return a===0&&n?.(),{code:a,descriptor:t,mintedSecretsFile:i,validation:o}},Qe=async(e,r)=>{const t=Ge(e,r.logger);if(t!==void 0)return t;const o=ze(e,r.logger);if(o!==void 0)return o;const n=Ce(e,r.logger);if(n!==void 0)return n;const i=Te(e,r.logger,r.dockerAvailable??ae);return i!==void 0?i:Ie(e,r)},Xe=(e,r,t)=>{const o=Ae(e);o!==void 0&&r.logger.info(`class-B composition: deploying ${o} (overrides wrangler main)`),r.temporary&&r.logger.info("temporary account: deploying to a short-lived Cloudflare account (~60min); wrangler will print a claim URL"),r.dryRun&&r.logger.info("dry run: validating + bundling without publishing"),r.outDir!==void 0&&r.logger.info(`build artifact: emitting bundle to ${r.outDir}`);const n=T(t),i={dryRun:r.dryRun,entry:o,environment:r.env,outDir:r.outDir,preview:r.preview,temporary:r.temporary};if(n.toolchain===void 0)throw new Error(`deploy target "${n.id}" has no command-line toolchain`);return n.toolchain.deploy(i)},w=(e,r)=>({code:1,descriptor:void 0,error:e,validation:{problems:[],wranglerPath:void 0},...r}),Ze=(e,r)=>{if(e.problems.length===0)return!1;r.error("wrangler.jsonc validation failed:");for(const t of e.problems)r.error(` - ${t}`);return!0},er=async e=>{const r=e.cwd??process.cwd(),t=Le(e),o=re(e),n=ne(r,e.target);if(n.target===void 0){const p=n.error??"unknown deploy target";return e.logger.error(p),w(p)}const{target:i}=n;let a;if(!e.skipCodegen){const p=await Ye(r,t,e.logger,e.apiSpec,i,e.spawner,b(e.format),o);if(p.error!==void 0)return w(p.error);a=p.result}let c;if(a!==void 0){const p=me({allowDrift:e.allowSchemaDrift===!0,codegen:a,command:"deploy",logger:e.logger,updateBaseline:e.updateSchemaBaseline===!0});if(p.blocked)return w("schema drift gate blocked deploy",{schemaDrift:{blocked:!0,reason:p.reason}});c=p.rebless}await Fe(r,e.logger,a?.cronTriggers,i,e.env);const d=Ve(e);if(d!==void 0)return w(d);const l=await Qe(r,e);if(l!==void 0)return w(l);const s=Y({environment:e.env,projectRoot:r});if(Ze(s,e.logger))return{code:1,descriptor:void 0,error:"wrangler validation failed",validation:s};_e(r,e.logger);const{error:g,mintedSecretsFile:u}=await qe(r,e,t,i);if(g!==void 0)return e.logger.error(g),{code:1,descriptor:void 0,error:g,mintedSecretsFile:u,validation:s};const v=!b(e.format)&&e.dryRun!==!0&&e.preview!==!0&&N(r)===void 0,m=Xe(r,e,i),k=S(R(r),m.tool,m.args),h={args:k.args,captureStdout:v,command:k.command,cwd:r,stdoutToStderr:b(e.format)};e.logger.info(`deploying via ${h.command} ${h.args.join(" ")}`);const j=await(e.spawner??D)(h);return j.code!==0?{code:j.code,descriptor:h,mintedSecretsFile:u,validation:s}:e.dryRun||e.preview?{code:0,descriptor:h,mintedSecretsFile:u,validation:s}:(Se({cwd:r,env:e.env,logger:e.logger,output:j.stdout}),Je(e,r,h,s,c,u))},rr=async e=>{const r=se("deploy",e.format);if(r!==void 0)return e.logger.error(r),w(r);const t=await er({...e,logger:le(e.format,e.logger)});return b(e.format)?(ce(t),t):(t.code===0&&e.dryRun!==!0&&e.preview!==!0?Re({cwd:e.cwd??process.cwd(),env:e.env,logger:e.logger,migrated:e.migrate===!0,mintedSecretsFile:t.mintedSecretsFile}):t.code===0&&e.preview===!0&&e.logger.success("preview version uploaded — see the preview URL in the wrangler output above"),t)},xr=oe(async({cwd:e,logger:r,options:t})=>({code:(await rr({allowSchemaDrift:t.allowSchemaDrift===!0,apiSpec:te(t.apiSpec),cwd:e,dryRun:t.dryRun===!0,env:t.env,format:t.format,logger:r,migrate:t.migrate===!0,migrateToken:t.migrateToken,migrateUrl:pe({cwd:e,env:t.env,url:t.migrateUrl}),migrateYes:t.migrateYes===!0,preview:t.preview===!0,skipCodegen:t.prebuilt===!0,strictAdvisories:t.strictAdvisories,target:t.target,temporary:t.temporary===!0,updateSchemaBaseline:t.updateSchemaBaseline===!0})).code}));export{xr as execute,rr as runDeployCommand};
1
+ import{existsSync as y,readFileSync as R}from"node:fs";import{runCodegen as O,discoverMigrations as _}from"@lunora/codegen";import{readLinkedProject as A,writeLinkedProject as B,resolveDeployDriver as D,inferLunoraBindings as U,DEV_VARS_FILE as w,parseDevVariableEntries as F,isMintableSecretKey as C,discoverContainerInfo as I,packageNamesFromBindings as P,requiredSecrets as W,generateSecretValue as K,upsertDevVariableLine as q,writeDevVariablesFileAtomically as M,discoverSchemaInfo as V}from"@lunora/config";import{validateWranglerProject as Y,reconcileWranglerBindings as G,reconcileWranglerCompatibilityDate as z,reconcileWranglerCrons as H,findWranglerFile as J,readWranglerJsonc as Q}from"@lunora/config/cloudflare";import{join as h}from"@visulima/path";import{Spinner as X}from"@visulima/spinner";import{Project as Z}from"ts-morph";import{n as ee,t as re}from"../packem_shared/advisory-gate-yaOOyUQl.mjs";import{r as te}from"../packem_shared/api-spec-BENwiyUa.mjs";import{d as j}from"../packem_shared/wrangler-name-CHDf3rMP.mjs";import{i as oe}from"../packem_shared/command-0l-ZPhIX.mjs";import{i as ne}from"../packem_shared/deploy-target-Dvr9vxpR.mjs";import{M as k,l as $}from"../packem_shared/detect-package-manager-DXDstphE.mjs";import{o as ie,r as ae}from"../packem_shared/docker-CKvYE9YF.mjs";import{p as se,b as ce,c as le}from"../packem_shared/health-probe-CiFgh1hn.mjs";import{i as de,t as b,d as ue,s as ge}from"../packem_shared/output-format-Cv3aLqhP.mjs";import{a as pe}from"../packem_shared/platform-diagnostics-C4TFj5Pu.mjs";import{m as me}from"../packem_shared/post-codegen-hook-DhL1RH5u.mjs";import{containerBuildTag as fe}from"@lunora/container";import{defaultSpawner as S}from"../packem_shared/createRecordingSpawner-SKs4R1fc.mjs";import{i as E}from"../packem_shared/resolve-target-CeiNrCAx.mjs";import{R as he}from"../packem_shared/schema-drift-gate-d12lMICD.mjs";import{I as ve}from"../packem_shared/tui-prompts-BU3irGxV.mjs";import{m as we,p as ye}from"../packem_shared/vectorize-metadata-BvZbbqUD.mjs";import{f as ke}from"../packem_shared/wrangler-secrets-D0Tv5GWn.mjs";import{runMigrateDataCommand as $e}from"./runMigrateGenerateCommand.mjs";const be=/https?:\/\/[^\s"'<>]+\.workers\.dev[^\s"'<>]*/u,Se=/https:\/\/[^\s"'<>]+/u,Re=e=>{if(e===void 0)return;const r=be.exec(e);return r?r[0]:Se.exec(e)?.[0]},N=e=>e===void 0?"":` (--env ${e})`,De=({cwd:e,env:r,logger:t,now:o,url:n})=>{if(n!==void 0)try{const i=A(e);if(i!==void 0){if(i.workerUrl===n&&i.env===r)return;t.warn(`link: .lunora/project.json records ${i.workerUrl??"(no url)"}${N(i.env)}, but this deploy published ${n}${N(r)}. Keeping the recorded value — run \`lunora link --url ${n}${r===void 0?"":` --env ${r}`}\` to update it.`);return}const a=(o??(()=>new Date().toISOString()))();B(e,{env:r,linkedAt:a,workerName:j(e),workerUrl:n}),t.success(`link: recorded ${n} in .lunora/project.json (run \`lunora link\` to change)`)}catch{}},je=e=>{const{cwd:r,env:t,logger:o,migrated:n,mintedSecretsFile:i}=e;try{const a=A(r),c=a?.workerName??j(r),l=e.url??a?.workerUrl;o.success("deploy complete"),o.info(` worker: ${c??"(see wrangler output above)"}`),t!==void 0&&o.info(` env: ${t}`),l===void 0?o.info(" url: run `lunora link --url <https://your-worker>` to record it"):o.info(` url: ${l}`),n&&o.info(" migrations: applied"),i!==void 0&&o.info(` secrets: generated value(s) recorded in ${i}`),o.info(" studio: lunora view --remote"),o.info(" logs: lunora logs")}catch{}},xe=async e=>{if(e.targets.length===0)return{builtTags:[],code:0};if(!(e.railpackAvailable??ie)()){const o="deploy blocked: a container uses `image: { build }` (Railpack), but Railpack isn't ready. Install the `railpack` CLI and start a BuildKit instance, e.g. `docker run --rm --privileged -d --name buildkit moby/buildkit` then `export BUILDKIT_HOST=docker-container://buildkit`. Alternatively switch the container's `image` to a Dockerfile path or a pre-built registry reference.";return e.logger.error(o),{builtTags:[],code:1,error:o}}const r=e.spawner??S,t=[];for(const o of e.targets){const n=fe(o.exportName),i={args:["build",o.buildDir,"--name",n],command:"railpack",cwd:e.cwd},a=k($(e.cwd),"wrangler",["containers","push",n]),c={args:a.args,command:a.command,cwd:e.cwd};e.logger.info(`railpack: building "${o.exportName}" → ${n} from ${o.buildDir}`);const l=await r(i);if(l.code!==0){const s=`railpack build failed for container "${o.exportName}" (${o.buildDir})`;return e.logger.error(s),{builtTags:t,code:l.code,error:s}}e.logger.info(`railpack: pushing ${n} to the Cloudflare Registry`);const d=await r(c);if(d.code!==0){const s=`wrangler containers push failed for "${o.exportName}" (${n})`;return e.logger.error(s),{builtTags:t,code:d.code,error:s}}t.push(n)}return{builtTags:t,code:0}},L="<replace-with-d1-create-id>",x=e=>{const r=J(e);return r?Q(r).parsed:void 0},Ce=["LUNORA_ORIGIN_URL","LUNORA_WORKER_ORIGIN","AUTH_URL"],Ne=e=>{try{const{hostname:r}=new URL(e);return r==="localhost"||r==="127.0.0.1"||r==="::1"||r==="[::1]"}catch{return!1}},Te=e=>e.startsWith("./")||e.startsWith("../")||e.startsWith("/")||e.includes("Dockerfile"),Ae=(e,r,t)=>{const o=(x(e)?.containers??[]).filter(i=>typeof i?.image=="string"&&Te(i.image));if(o.length===0||t())return;const n=`deploy blocked: wrangler.jsonc declares ${String(o.length)} container(s) built from a local Dockerfile, but no Docker-compatible engine is available. Start Docker (or Colima), or point the container's \`image\` at a pre-built registry reference. Note: container images must target linux/amd64.`;return r.error(n),n},Ue=e=>y(h(e,"src","worker.ts"))?"src/worker.ts":void 0,Fe=(e,r)=>{for(const t of I(e,"lunora").containers){const{image:o}=t;if(o.kind==="dockerfile"&&!y(h(e,o.dockerfilePath))){const n=`deploy blocked: container "${t.exportName}" references a Dockerfile at "${o.dockerfilePath}" that does not exist. Create it or fix the \`image\` path in lunora/containers.ts.`;return r.error(n),n}if(o.kind==="build"&&!y(h(e,o.buildDir))){const n=`deploy blocked: container "${t.exportName}" references a Railpack build directory "${o.buildDir}" that does not exist. Create it or fix the \`image.build\` path in lunora/containers.ts.`;return r.error(n),n}}},Ie=e=>b(e.format)?!1:e.interactive!==void 0?e.interactive:process.stdout.isTTY&&!process.env.CI,Ee=e=>(x(e)?.d1_databases??[]).find(r=>r.database_id===L)?.binding,Le=async(e,r)=>{const t=I(e,"lunora").containers.filter(n=>n.image.kind==="build").map(n=>({buildDir:n.image.buildDir,exportName:n.exportName}));if(t.length===0)return;const o=await xe({cwd:e,logger:r.logger,railpackAvailable:r.railpackAvailable,spawner:r.spawner,targets:t});return o.code===0?void 0:o.error??"railpack build failed"},Oe=(e,r,t)=>{if(t!==void 0)try{const o=H(e,t);o.changed&&r.success(`synced ${String(t.length)} cron trigger(s) → ${o.wranglerPath??"wrangler.jsonc"}`)}catch(o){const n=o instanceof Error?o.message:String(o);r.warn(`cron trigger sync skipped: ${n}`)}},_e=async(e,r,t,o,n)=>{try{D(o);const i=await U({projectRoot:e}),a=G(e,i,n);a.changed&&r.success(`provisioned bindings: ${a.added.join(", ")} → ${a.wranglerPath??"wrangler.jsonc"}`);for(const c of a.warnings)r.warn(c)}catch(i){const a=i instanceof Error?i.message:String(i);r.warn(`binding inference skipped: ${a}`)}try{const i=z(e);i.changed&&r.success(`bumped compatibility_date to ${i.date??"unknown"} (Workers Cache enabled) → ${i.wranglerPath??"wrangler.jsonc"}`)}catch(i){const a=i instanceof Error?i.message:String(i);r.warn(`compatibility date sync skipped: ${a}`)}Oe(e,r,t)},Be=(e,r)=>{const t=h(e,w);if(!y(t))return;let o;try{o=F(R(t,"utf8")).length}catch{return}o!==0&&r.warn(`Note: \`lunora deploy\` does not push secrets. ${w} has ${String(o)} key(s); if you changed them, run \`lunora env push --yes\` to update the deployed secrets.`)},Pe=/(?:KEY|PASSWORD|SECRET|TOKEN)$/u,We=async e=>{let r=[];try{r=P(await U({projectRoot:e}))}catch{}const t=W(r).map(n=>n.key);let o=[];try{const n=h(e,w);y(n)&&(o=F(R(n,"utf8")).map(i=>i.key).filter(i=>Pe.test(i)))}catch{}return[...new Set([...t,...o])]},Ke=async(e,r,t,o)=>{const{logger:n}=r,i=r.spawner??S,a=$(e),c=r.env===void 0?"":` --env ${r.env}`,{toolchain:l}=D(o);if(l===void 0)return n.error("deploy target has no command-line toolchain; cannot push secrets"),{minted:[],ok:!1};const d=[];for(const s of t){const u=K(),m=l.secretPut({environment:r.env,key:s,temporary:r.temporary}),f=k(a,m.tool,m.args),g=await i({args:f.args,command:f.command,cwd:e,input:u});if(g.code!==0)return n.error(`failed to push secret ${s} (exit ${String(g.code)}); set it manually with \`wrangler secret put ${s}${c}\`.`),{minted:d,ok:!1};d.push({key:s,value:u}),n.success(`generated + pushed ${s}`)}return{minted:d,ok:!0}},qe=/^[\w-]+$/u,Me=(e,r,t)=>{if(t.length===0)return;const o=t.map(c=>c.key).join(", ");if(r.env!==void 0&&!qe.test(r.env)){r.logger.warn(`${o}: minted and pushed for --env ${r.env}, but "${r.env}" isn't a safe filename fragment — the value could not be recorded. Capture it manually if you need it again.`);return}const n=r.env===void 0?w:`${w}.${r.env}`,i=h(e,n);let a=y(i)?R(i,"utf8"):"";for(const c of t)a=q(a,c.key,c.value);return M(i,a),r.logger.success(r.env===void 0?`${o}: value(s) recorded in ${n}`:`${o}: value(s) recorded in ${n} (kept separate from ${w} so \`lunora dev\` and a plain \`lunora env push\` don't inherit the --env ${r.env} value)`),n},Ve=async(e,r,t,o)=>{if(r.dryRun===!0||r.preview===!0)return{};const{logger:n}=r,i=r.env===void 0?"":` --env ${r.env}`;let a;try{a=await(r.secretLister??ke)({cwd:e,env:r.env,temporary:r.temporary})}catch{return{}}if(!a.ok)return{};const c=new Set(a.names),l=(await We(e)).filter(s=>!c.has(s));if(l.length===0)return{};if(!t)return{error:`missing required secret(s) on the deploy target: ${l.join(", ")}. Set them with \`wrangler secret put <KEY>${i}\` (or \`lunora env generate --set\` then \`lunora env push --yes${i}\`), then re-deploy.`};for(const s of l.filter(u=>!C(u)))n.warn(`required secret ${s} is not set on the target — set it with: wrangler secret put ${s}${i}`);const d=l.filter(s=>C(s));if(d.length===0)return{};if(await(r.secretConfirm??ve())(`${String(d.length)} required secret(s) not set on the target (${d.join(", ")}). Generate strong values and push them now?`)){const{minted:s,ok:u}=await Ke(e,r,d,o),m=Me(e,r,s);return u?{mintedSecretsFile:m}:{error:"failed to push required secret(s) — set them manually and re-deploy",mintedSecretsFile:m}}return n.warn(`${String(d.length)} required secret(s) not set on the target: ${d.join(", ")}. Generate + push with \`lunora env generate --set\` then \`lunora env push --yes${i}\`.`),{}},Ye=async(e,r)=>{const t=new Z({skipAddingFilesFromTsConfig:!0}),o=h(r,"lunora");let n;try{n=_(t,o)}catch(i){const a=i instanceof Error?i.message:String(i);return e.logger.warn(`--migrate: could not discover migrations (${a}); skipping`),0}if(n.length===0)return e.logger.info("--migrate: no data migrations declared in lunora/"),0;e.logger.info(`--migrate: running ${String(n.length)} migration(s) against deployed worker`);for(const i of n){e.logger.info(`--migrate: up "${i.id}" (table "${i.table}")`);const a={cwd:r,fetchImpl:e.fetchImpl,id:i.id,logger:e.logger,prod:!0,subcommand:"up",token:e.migrateToken,url:e.migrateUrl,yes:e.migrateYes===!0},c=await $e(a);if(c.code!==0)return e.logger.error(`--migrate: migration "${i.id}" failed — see output above`),c.code;e.logger.success(`--migrate: "${i.id}" applied`)}return 0},Ge=e=>{if(!e.migrate||e.dryRun||e.preview)return;if(e.migrateUrl===void 0){const t="--migrate requires --migrate-url <https://your-worker> — the deploy target URL is only known after wrangler runs, and this gate runs before it; refusing to default to localhost";return e.logger.error(t),t}if(e.migrateYes!==!0){const t="--migrate runs production data migrations after deploy. Re-run with --migrate-yes to confirm.";return e.logger.error(t),t}const r=e.migrateToken??process.env.LUNORA_ADMIN_TOKEN;if(r===void 0||r===""){const t="admin token required for --migrate — pass --migrate-token or set LUNORA_ADMIN_TOKEN";return e.logger.error(t),t}},ze=async(e,r,t,o,n,i,a,c)=>{let l;r?(l=new X({name:"dots"}),l.start("running codegen")):t.info("running codegen");try{const d=O({apiSpec:o,projectRoot:e,target:n});l?.succeed("codegen complete"),l||t.success("codegen complete");const s=pe(d.platformDiagnostics,t);if(s!==void 0)return{error:s};const{errorAdvisories:u,names:m,shouldBlock:f}=ee(d.advisories,c);if(f){const p=`${u.length.toString()} ERROR-level ${u.length===1?"advisory":"advisories"} (${m.join(", ")}). Pass --no-strict-advisories to downgrade this to a warning and deploy anyway.`;return t.error(p),{error:p}}const g=await me({cwd:e,logger:t,spawner:i,stdoutToStderr:a});return g.error!==void 0?(t.error(g.error),{error:g.error}):{result:d}}catch(d){l?.failed("codegen failed");const s=d instanceof Error?d.message:String(d);return t.error(`codegen failed: ${s}`),{error:`codegen failed: ${s}`}}},He=(e,r)=>{const t=Ee(e);if(t===void 0)return;const o=`deploy blocked: the "${t}" D1 binding has a placeholder database_id ("${L}"). Run \`wrangler d1 create <name>\` to create the database, then replace the placeholder in wrangler.jsonc with the real id before deploying.`;return r.error(o),o},Je=(e,r)=>{const t=x(e)?.vars;if(!t)return;const o=Ce.filter(i=>typeof t[i]=="string"&&Ne(t[i]));if(o.length===0)return;const n=`deploy blocked: ${o.join(", ")} in wrangler.jsonc point at localhost. A deployed Worker can't reach a loopback address, so this silently breaks scheduled-job dispatch / auth callbacks. Set each to the deployed worker's public URL (or move it to a secret with \`wrangler secret put\`) before deploying.`;return r.error(n),n},Qe=async(e,r)=>{const{info:t}=V(r,"lunora"),o=t?.vectorMetadata??[];if(o.length===0)return;const n=[];for(const a of o){const c=ye(a.kind);if(c===void 0){e.logger.warn(`vector index "${a.index}" declares metadata "${a.property}", whose column type cannot be filtered on in Vectorize — it is stored with each vector but no filter will match it.`);continue}n.push({index:a.index,property:a.property,type:c})}if(n.length===0)return;const i=(await we({cwd:r,entries:n,exec:k($(r),"wrangler",[]),logger:e.logger,spawner:e.spawner??S})).filter(a=>a.status!=="failed").length;i>0&&e.logger.success(`vectorize metadata indexes ready: ${String(i)}/${String(n.length)}`)},T=5,Xe=2e3,Ze=async(e,r,t)=>{if(e.healthCheck!==!0)return;const o=t??E({cwd:r,env:e.env});if(o===void 0){const i="--health-check: the deploy succeeded, but no URL to probe could be resolved — wrangler's output carried none and this checkout has no link for this environment. Run `lunora link --url <https://your-worker>` and re-deploy, or drop --health-check.";return e.logger.error(i),{error:i,ok:!1,url:""}}const n=await se({attempts:T,baseUrl:o,delayMs:Xe,fetchImpl:e.healthFetch,paths:[ce,le],sleep:e.healthSleep});return n.error===void 0?(e.logger.success(`health check ok (${n.url})`),{ok:!0,url:n.url}):(e.logger.error(`--health-check: the deploy succeeded, but the new version did not answer after ${String(T)} attempt(s) — ${n.error}`),{error:n.error,ok:!1,url:n.url})},er=async(e,r,t,o,n,i)=>{await Qe(e,r);const a=e.migrate?await Ye(e,r):0;return a===0&&n?.(),{code:a,descriptor:t,mintedSecretsFile:i,validation:o}},rr=async(e,r)=>{const t=He(e,r.logger);if(t!==void 0)return t;const o=Je(e,r.logger);if(o!==void 0)return o;const n=Fe(e,r.logger);if(n!==void 0)return n;const i=Ae(e,r.logger,r.dockerAvailable??ae);return i!==void 0?i:Le(e,r)},tr=(e,r,t)=>{const o=Ue(e);o!==void 0&&r.logger.info(`class-B composition: deploying ${o} (overrides wrangler main)`),r.temporary&&r.logger.info("temporary account: deploying to a short-lived Cloudflare account (~60min); wrangler will print a claim URL"),r.dryRun&&r.logger.info("dry run: validating + bundling without publishing"),r.outDir!==void 0&&r.logger.info(`build artifact: emitting bundle to ${r.outDir}`);const n=D(t),i={dryRun:r.dryRun,entry:o,environment:r.env,outDir:r.outDir,preview:r.preview,temporary:r.temporary};if(n.toolchain===void 0)throw new Error(`deploy target "${n.id}" has no command-line toolchain`);return n.toolchain.deploy(i)},v=(e,r)=>({code:1,descriptor:void 0,error:e,validation:{problems:[],wranglerPath:void 0},...r}),or=(e,r)=>{if(e.problems.length===0)return!1;r.error("wrangler.jsonc validation failed:");for(const t of e.problems)r.error(` - ${t}`);return!0},nr=(e,r,t)=>{const o=b(r.format),n=r.dryRun!==!0,i=tr(e,r,t),a=k($(e),i.tool,i.args);return{args:a.args,captureStdout:n&&!o,captureStdoutSilently:n&&o,command:a.command,cwd:e,stdoutToStderr:o&&!n}},ir=async({cwd:e,descriptor:r,mintedSecretsFile:t,options:o,reblessSchemaBaseline:n,stdout:i,validation:a})=>{const c={deployedAt:new Date().toISOString(),dryRun:o.dryRun===!0,env:o.env,preview:o.preview===!0,url:o.dryRun===!0?void 0:Re(i),workerName:j(e)};if(o.dryRun===!0||o.preview===!0)return o.healthCheck===!0&&o.logger.warn(`--health-check skipped: ${o.dryRun===!0?"a dry run publishes nothing":"a preview version serves no live traffic"}`),{code:0,deployment:c,descriptor:r,mintedSecretsFile:t,validation:a};o.temporary!==!0&&De({cwd:e,env:o.env,logger:o.logger,url:c.url});const l=await Ze(o,e,c.url);return l?.error!==void 0?{code:1,deployment:c,descriptor:r,healthCheck:l,mintedSecretsFile:t,validation:a}:{...await er(o,e,r,a,n,t),deployment:c,healthCheck:l}},ar=async e=>{const r=e.cwd??process.cwd(),t=Ie(e),o=re(e),n=ne(r,e.target);if(n.target===void 0){const p=n.error??"unknown deploy target";return e.logger.error(p),v(p)}const{target:i}=n;let a;if(!e.skipCodegen){const p=await ze(r,t,e.logger,e.apiSpec,i,e.spawner,b(e.format),o);if(p.error!==void 0)return v(p.error);a=p.result}let c;if(a!==void 0){const p=he({allowDrift:e.allowSchemaDrift===!0,codegen:a,command:"deploy",logger:e.logger,updateBaseline:e.updateSchemaBaseline===!0});if(p.blocked)return v("schema drift gate blocked deploy",{schemaDrift:{blocked:!0,reason:p.reason}});c=p.rebless}await _e(r,e.logger,a?.cronTriggers,i,e.env);const l=Ge(e);if(l!==void 0)return v(l);const d=await rr(r,e);if(d!==void 0)return v(d);const s=Y({environment:e.env,projectRoot:r});if(or(s,e.logger))return{code:1,descriptor:void 0,error:"wrangler validation failed",validation:s};Be(r,e.logger);const{error:u,mintedSecretsFile:m}=await Ve(r,e,t,i);if(u!==void 0)return e.logger.error(u),{code:1,descriptor:void 0,error:u,mintedSecretsFile:m,validation:s};const f=nr(r,e,i);e.logger.info(`deploying via ${f.command} ${f.args.join(" ")}`);const g=await(e.spawner??S)(f);return f.captureStdoutSilently===!0&&g.stdout!==void 0&&g.stdout!==""&&process.stderr.write(g.stdout),g.code!==0?{code:g.code,descriptor:f,mintedSecretsFile:m,validation:s}:ir({cwd:r,descriptor:f,mintedSecretsFile:m,options:e,reblessSchemaBaseline:c,stdout:g.stdout,validation:s})},sr=async e=>{const r=de("deploy",e.format);if(r!==void 0)return e.logger.error(r),v(r);const t=await ar({...e,logger:ge(e.format,e.logger)});if(b(e.format))return ue(t),t;if(t.code===0&&e.dryRun!==!0&&e.preview!==!0)je({cwd:e.cwd??process.cwd(),env:e.env,logger:e.logger,migrated:e.migrate===!0,mintedSecretsFile:t.mintedSecretsFile,url:t.deployment?.url});else if(t.code===0&&e.preview===!0){const o=t.deployment?.url;e.logger.success(o===void 0?"preview version uploaded":`preview version uploaded — ${o}`)}return t},Ir=oe(async({cwd:e,logger:r,options:t})=>({code:(await sr({allowSchemaDrift:t.allowSchemaDrift===!0,apiSpec:te(t.apiSpec),cwd:e,dryRun:t.dryRun===!0,env:t.env,format:t.format,healthCheck:t.healthCheck===!0,logger:r,migrate:t.migrate===!0,migrateToken:t.migrateToken,migrateUrl:E({cwd:e,env:t.env,url:t.migrateUrl}),migrateYes:t.migrateYes===!0,preview:t.preview===!0,skipCodegen:t.prebuilt===!0,strictAdvisories:t.strictAdvisories,target:t.target,temporary:t.temporary===!0,updateSchemaBaseline:t.updateSchemaBaseline===!0})).code}));export{Ir as execute,sr as runDeployCommand};
@@ -1 +1 @@
1
- import"node:fs";import"node:path";import"node:url";import"@lunora/errors";import"@visulima/cerebro";import"@visulima/cerebro/command/completion";import"@visulima/cerebro/command/version";import{d as S,t as A,i as C,f as D}from"./cli-DYGVS96x.mjs";import"./detect-package-manager-DXDstphE.mjs";import"./createLogger-BoSxdb2T.mjs";export{S as COMMANDS,A as REGISTERED_COMMAND_NAMES,C as VERSION,D as runCli};
1
+ import"node:fs";import"node:path";import"node:url";import"@lunora/errors";import"@visulima/cerebro";import"@visulima/cerebro/command/completion";import"@visulima/cerebro/command/version";import{d as S,t as A,i as C,f as D}from"./cli-RVVu3rxm.mjs";import"./detect-package-manager-DXDstphE.mjs";import"./createLogger-BoSxdb2T.mjs";export{S as COMMANDS,A as REGISTERED_COMMAND_NAMES,C as VERSION,D as runCli};
@@ -0,0 +1,3 @@
1
+ import{mkdirSync as A,readFileSync as w,lstatSync as B,writeFileSync as D}from"node:fs";import{join as u,dirname as y}from"node:path";import{fileURLToPath as L}from"node:url";import{resolveHint as j,isLunoraError as k,flattenHint as E,findSolutionByMessage as C}from"@lunora/errors";import{createCerebro as I}from"@visulima/cerebro";import $ from"@visulima/cerebro/command/completion";import _ from"@visulima/cerebro/command/version";import{p}from"./api-spec-BENwiyUa.mjs";import{g as s}from"./deploy-target-Dvr9vxpR.mjs";import{P as T,l as P}from"./detect-package-manager-DXDstphE.mjs";import{createLogger as S}from"./createLogger-BoSxdb2T.mjs";import{VisulimaError as U,renderError as M}from"@visulima/error";import{homedir as W}from"node:os";const J={argument:{description:"Feature or registry item: ai | auth | email | storage | crons | presence | queue | workflow | flags | backup | …",name:"feature",type:String},description:"Add a feature or registry item (ai, auth, email, storage, crons, …) to the current Lunora project",examples:[["lunora add auth","Add authentication (asks which provider)"],["lunora add auth --provider clerk","Add Clerk auth without prompting"],["lunora add auth-ui","Add copy-in auth screens for your framework (auto-detected)"],["lunora add email","Add transactional email (Cloudflare Email Workers + dev mail catcher)"],["lunora add storage","Add the R2 storage registry item (asks for the bucket name)"],["lunora add storage --bucket my-app-uploads","Add storage with a bucket name, no prompt"],["lunora add crons","Add the scheduled-jobs registry item"],["lunora add storage --ref alpha","Add an item from the alpha branch's registry"]],group:"Project",loader:()=>import("../packem_chunks/handler.mjs").then(e=>({default:e.execute})),name:"add",options:[{description:"auth: provider to use without prompting (auth | clerk | auth0)",name:"provider",type:String},{description:"auth: D1 database name to use without prompting (lowercase alphanumeric + hyphens)",name:"db",type:String},{description:"storage: R2 bucket name to use without prompting (lowercase alphanumeric + hyphens)",name:"bucket",type:String},{description:"email: verified destination address to use without prompting",name:"mail-to",type:String},{description:"Skip prompts (auth provider, DB name, bucket name, mail destination) and use the defaults",name:"yes",type:Boolean},{description:"Local registry root (offline; expects <name>/ subdirs)",name:"from",type:String},{description:"Override the remote registry source base (e.g. gh:owner/repo/registry)",name:"source",type:String},{description:"Fetch items from a git ref (branch, tag, or commit), e.g. --ref alpha. Overrides the version-derived default",name:"ref",type:String},{description:"Permit --source values outside gh:/github:/https://",name:"allow-unsafe-source",type:Boolean},{description:"Output format: pretty (default) or json",name:"format",type:String}]},f="lunora.advisor.map.json",K={description:"Score your app's advisor findings into a health map, and gate CI on it",examples:[["lunora advisor","Score the app and write lunora.advisor.map.json"],["lunora advisor --all","Show every procedure as a check matrix"],["lunora advisor --entry messages#sendMessage","Inspect one procedure"],["lunora advisor --min-score 80","Exit non-zero when the score drops below 80"],["lunora advisor --baseline","Fail on any regression against the committed map"]],group:"Develop",loader:()=>import("../packem_chunks/handler20.mjs").then(e=>({default:e.execute})),name:"advisor",options:[{description:"Show every procedure as a check matrix, not just the ones with findings",name:"all",type:Boolean},{description:`Compare against a committed map and fail on regression (default ${f})`,name:"baseline",type:String},{description:"Inspect a single procedure by `file#exportName`",name:"entry",type:String},{description:"Output format: pretty (default) or json",name:"format",type:String},{description:"Exit non-zero when the global score is below this value (0-100)",name:"min-score",type:String},{description:`Where to write the map (default ${f})`,name:"out",type:String},{description:"Write the map artifact to disk (default true; use --no-write to skip)",name:"no-write",type:Boolean}]},F={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}]},q={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}]},H={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"],["lunora build --emit-bindings bindings.json","Also write what the bundle needs provisioned, for an external deployer"]],group:"Deploy",loader:()=>import("../packem_chunks/handler21.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:"Write a JSON manifest of the bindings + crons the bundle needs to this path, for an IaC program to consume",name:"emit-bindings",type:String},{description:"Output format: pretty (default) or json",name:"format",type:String},{description:"Directory to write the bundled Worker to (default .lunora/build)",name:"out-dir",type:String},s]},z={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},{description:"Fail on ERROR-level advisories even locally (the gate already defaults to on in CI)",name:"strict-advisories",type:Boolean},{description:"Don't fail on ERROR-level advisories (the gate defaults to on in CI, off locally)",name:"no-strict-advisories",type:Boolean},s]},V={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/handler4.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}]},G={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 the deploy, probe the new version's health route (/_lunora/health/ready, falling back to /_lunora/health) and fail if it never answers",name:"health-check",type:Boolean},{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:"Fail the deploy on ERROR-level codegen advisories even locally (the gate already defaults to on in CI)",name:"strict-advisories",type:Boolean},{description:"Don't fail the deploy on ERROR-level codegen advisories (the gate defaults to on in CI, off locally). Never downgrades platform diagnostics.",name:"no-strict-advisories",type:Boolean},{description:"Upload a preview version (wrangler versions upload) instead of going live — prints a preview URL; doesn't shift production traffic",name:"preview",type:Boolean},s,{description:"Deploy to a temporary Cloudflare account when unauthenticated (wrangler deploy --temporary; live ~60min, then claim or it's deleted). Wrangler errors if you're already authenticated.",name:"temporary",type:Boolean},{description:"Re-bless the committed schema baseline (lunora/.lunora-schema.json) with the current shape",name:"update-schema-baseline",type:Boolean}]},Y={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/handler5.mjs").then(e=>({default:e.execute})),name:"deployments",options:[{description:"Cloudflare environment name",name:"env",type:String},{description:"Display `list` output as JSON",name:"json",type:Boolean},{description:"Reason/description recorded with a rollback or promote",name:"message",type:String},{description:"Confirm a rollback or promote (required — these change live traffic)",name:"yes",type:Boolean}]},Q={argument:{description:"Optional subcommand: stop (shut the running dev server down) | status (report it) | logs (print its captured output)",name:"args",type:String},description:"Run the dev stack: wrangler worker + studio + codegen watch",examples:[["lunora dev","Run the worker + studio + codegen watch"],["lunora dev --background","Run detached: blocks until ready, prints URL + PID, then returns"],["lunora dev stop","Stop the background/tracked dev server (idempotent)"],["lunora dev status","Report the running dev server (URL, PID, uptime)"],["lunora dev logs","Print the captured dev-server log (background runs)"],["lunora dev --json","Machine-readable JSON log lines (also LUNORA_LOG_JSON=1)"],["lunora dev --no-studio","Skip the embedded studio server"],["lunora dev --worker-port 8080","Use a custom wrangler dev port"],["lunora dev --remote","Proxy D1/KV/R2 to the deployed worker (also LUNORA_REMOTE=1)"]],group:"Develop",loader:()=>import("../packem_chunks/planDevCommand.mjs").then(e=>({default:e.execute})),name:"dev",options:[{description:`Which API spec(s) codegen emits: ${p} (default openapi)`,name:"api-spec",type:String},{description:"Studio server port (default 6173)",name:"port",type:Number},s,{description:"wrangler dev port (default 8787)",name:"worker-port",type:Number},{description:"Run the dev server as a managed background process (auto-enabled when an AI agent is detected; LUNORA_AGENT_MODE=0 disables)",name:"background",type:Boolean},{description:"Emit machine-readable JSON log lines (also LUNORA_LOG_JSON=1; auto-enabled for AI agents)",name:"json",type:Boolean},{description:"How many trailing lines `lunora dev logs` prints (default 100, 0 = all)",name:"lines",type:Number},{description:"Don't start the embedded studio server",name:"no-studio",type:Boolean},{description:"Don't spawn wrangler dev — an external task runner owns the worker; codegen watch + studio still run",name:"no-worker",type:Boolean},{description:"Don't watch + regenerate codegen",name:"no-codegen",type:Boolean},{description:"Proxy D1/KV/R2 bindings to the deployed worker (or set LUNORA_REMOTE=1)",name:"remote",type:Boolean}]},X={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/handler6.mjs").then(e=>({default:e.execute})),name:"docs"},Z={description:"Preflight the current Lunora project (wrangler bindings, placeholders, dev secrets)",examples:[["lunora doctor","Run the project preflight checks"],["lunora doctor --format json","Emit the findings as a machine-readable JSON document"]],group:"Project",loader:()=>import("../packem_chunks/handler7.mjs").then(e=>({default:e.execute})),name:"doctor",options:[{description:"Output format: pretty (default) or json",name:"format",type:String}]},ee={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/handler8.mjs").then(e=>({default:e.execute})),name:"env",options:[{description:"Target this Cloudflare environment for `push`/`diff` (passes --env <name> to wrangler)",name:"env",type:String},{description:"Alias for --env production",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}]},te={description:"Run every *.eval.ts under evals/ via @lunora/testing's evaluate/agentHarness — no live worker needed",examples:[["lunora eval","Run every eval under evals/, print the aggregate table"],["lunora eval --threshold 0.8","Non-zero exit if any eval's average score falls below 0.8"],["lunora eval --dir evals/support --format json","Run a subset and emit a machine-readable result"]],group:"Develop",loader:()=>import("../packem_chunks/handler23.mjs").then(e=>({default:e.execute})),name:"eval",options:[{description:"Directory to discover *.eval.ts files under (default evals/)",name:"dir",type:String},{description:"Output format: pretty (default) or json",name:"format",type:String},{description:"Score gate every eval's average must meet ([0,1]); a per-eval `threshold` export wins over this for that eval",name:"threshold",type:Number}]},re={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/handler9.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}]},oe={argument:{description:"Source NDJSON file, or a `npx convex export --path <dir>` directory",name:"file",type:String},description:"Bulk-insert rows from an NDJSON file — or a Convex export directory — via the worker's admin endpoint",examples:[["lunora import backup.ndjson","Bulk-insert rows from an NDJSON file"],["lunora import ./convex-export","Import a `npx convex export --path` directory (ids are preserved, so no remapping)"],["lunora import ./convex-export --with-storage","Also migrate blobs (verified sha256 upload) + `{ $storage }` refs"],["lunora import ./convex-export --scan","Write a candidate `lunora/import-convex.json` storage-column mapping (imports nothing)"],["lunora import ./snapshot.zip --with-storage --verify","Import a `npx convex export --path` zip snapshot with blob + row-parity checks"],["lunora import ./supabase-csv --from supabase","Import a directory of `COPY … TO STDOUT WITH CSV HEADER` dumps"],["lunora import ./firestore-json --from firebase --verify","Import Firestore documents (REST/Admin-SDK JSON) with row-parity checks"]],group:"Data",loader:()=>import("../packem_chunks/handler10.mjs").then(e=>({default:e.execute})),name:"import",options:[{description:"Source reader for a dump that cannot be detected: supabase | firebase (Convex and NDJSON are auto-detected)",name:"from",type:String},{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:"Also migrate file storage — Convex `_storage` blobs, or a Supabase/Firebase bucket (verified upload)",name:"with-storage",type:Boolean},{description:"Directory of storage objects to upload alongside the rows (Firebase: after `gcloud storage cp -r`)",name:"storage-dir",type:String},{description:"Write a candidate `lunora/import-convex.json` storage-column mapping and exit",name:"scan",type:Boolean},{description:"Verify row parity + dangling-storage after import (non-zero exit on mismatch)",name:"verify",type:Boolean},{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}]},ne={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/handler11.mjs").then(e=>({default:e.execute})),name:"info",options:[{description:"Emit a JSON snapshot instead of human text",name:"json",type:Boolean}]},ae={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}]},ie={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/handler12.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}]},se={description:"Scaffold lunora/schema.ts (and list/get procedures) from an existing Postgres or MySQL database",examples:[["lunora introspect --url postgres://localhost/shop","Scaffold a schema + procedures from every table"],["lunora introspect --tables users,orders","Introspect only these tables (DATABASE_URL is read by default)"],["lunora introspect --dry-run","Print what would be written without touching the filesystem"],["lunora introspect --no-procedures --force","Regenerate just the schema, overwriting the existing file"]],group:"Data",loader:()=>import("../packem_chunks/handler24.mjs").then(e=>({default:e.execute})),name:"introspect",options:[{description:"Database connection string (default: $DATABASE_URL)",name:"url",type:String},{description:"Postgres schema (default `public`) or MySQL database name",name:"schema",type:String},{description:"Comma-separated table allow-list (default: every base table)",name:"tables",type:String},{description:"Also emit list/get procedure modules per table (default true; --no-procedures to skip)",name:"procedures",type:Boolean},{description:"Overwrite files that already exist",name:"force",type:Boolean},{description:"Print what would be written without writing it",name:"dry-run",type:Boolean}]},le={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/handler13.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}]},pe={argument:{description:"Worker name (defaults to the name in wrangler config)",name:"worker",type:String},description:"Stream live logs from a deployed Worker, or read the durable log archive with --durable",group:"Deploy",loader:()=>import("../packem_chunks/handler22.mjs").then(e=>({default:e.execute})),name:"logs",options:[{description:"Cloudflare environment name",name:"env",type:String},{description:"Output format: pretty (default) or json",name:"format",type:String},{description:"Substring filter on log messages",name:"search",type:String},{description:"Filter by invocation status: ok, error, or canceled",name:"status",type:String},s,{description:"Tail a temporary-account deployment when unauthenticated (wrangler tail --temporary). Errors if you're already authenticated.",name:"temporary",type:Boolean},{description:"Read the durable log archive (pipelineLogSink → R2) via R2 SQL instead of tailing live",name:"durable",type:Boolean},{description:"durable: Iceberg table the Pipeline writes to (required with --durable)",name:"table",type:String},{description:"durable: Iceberg namespace (R2 Data Catalog database) the table lives in",name:"namespace",type:String},{description:"durable: lower time bound (epoch-millis or ISO 8601), inclusive",name:"since",type:String},{description:"durable: upper time bound (epoch-millis or ISO 8601), inclusive",name:"until",type:String},{description:"durable: exact severity filter (trace|debug|log|info|warn|error|fatal)",name:"level",type:String},{description:"durable: severity floor — this level and every more-severe one",name:"min-level",type:String},{description:"durable: keep function paths starting with this prefix (LIKE 'prefix%')",name:"function-prefix",type:String},{description:"durable: trace-id filter",name:"trace-id",type:String},{description:"durable: shard-key filter",name:"shard-key",type:String},{description:"durable: user-id filter",name:"user-id",type:String},{description:"durable: max rows (clamped to 1–10000; default 500)",name:"limit",type:String},{description:"durable: resume after a prior page — the opaque cursor token printed by the previous page (bare epoch-millis also accepted for back-compat)",name:"cursor",type:String},{description:"durable: emit one JSON object per line instead of a table",name:"ndjson",type:Boolean}]},de={argument:{description:"install [client…] | uninstall [client…] | serve",name:"args",type:String},description:"Connect your AI editor to Lunora over MCP (docs search + this project's dev server)",examples:[["lunora mcp install","Install into every MCP client already configured here"],["lunora mcp install claude-code cursor","Install into specific clients"],["lunora mcp install --list","List the supported clients and their config files"],["lunora mcp install --docs-only","Install only the hosted documentation server"],["lunora mcp install --print","Show the config that would be written, without writing it"],["lunora mcp install --global","Force every server into the machine-wide config"],["lunora mcp uninstall","Remove Lunora's MCP servers from every supported client"],["lunora mcp uninstall cursor","Remove them from one client"],["lunora mcp uninstall --print","Show what would be removed, without removing it"],["lunora mcp serve","Run the stdio MCP server (this is what your editor spawns)"],["lunora mcp serve --allow-writes","Also expose the mutation/action tools"],["lunora mcp serve --token $LUNORA_ADMIN_TOKEN","Expose the observability tools (logs, issues, advisories, insights, migrations) too"]],group:"Develop",loader:()=>import("../packem_chunks/handler25.mjs").then(e=>({default:e.execute})),name:"mcp",options:[{description:"install: replace entries that already exist",name:"force",type:Boolean},{description:"install: list the supported clients and their config files",name:"list",type:Boolean},{description:"install/uninstall: print what would change instead of writing it",name:"print",type:Boolean},{description:"install/uninstall: only the hosted documentation server",name:"docs-only",type:Boolean},{description:"install/uninstall: only this project's local server",name:"local-only",type:Boolean},{description:"install/uninstall: the machine-wide config (install default: docs server global, local server per-project)",name:"global",type:Boolean},{description:"install/uninstall: this project's config instead of the machine-wide one",name:"project",type:Boolean},{description:"serve: also expose the mutation/action tools (default: read-only)",name:"allow-writes",type:Boolean},{description:"serve: skip the documentation tools",name:"no-docs",type:Boolean},{description:"Docs site origin backing the documentation tools (default https://lunora.sh)",name:"docs-url",type:String},{description:"serve: deployment URL to expose (default: the running dev server)",name:"url",type:String},{description:"serve: bearer token (default: LUNORA_ADMIN_TOKEN from the environment or .dev.vars). Also gates the observability tools (logs, issues, advisories, query insights, migration status) — without a token they are not exposed at all",name:"token",type:String}]},ce={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}]},ue={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/handler14.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},s,{description:"Re-bless the committed schema baseline (lunora/.lunora-schema.json) with the current shape",name:"update-schema-baseline",type:Boolean}]},me={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/handler15.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}]},ge={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}]},he={argument:{description:"install | check",name:"subcommand",type:String},description:"Install the Lunora agent skills (AI rules) into .agents/skills/, or check they're present",examples:[["lunora rules install","Copy the Lunora agent skills into .agents/skills/"],["lunora rules install --overwrite","Reinstall, replacing edited skill files"],["lunora rules check","Report which Lunora skills are installed"],["lunora rules check --strict","Exit non-zero when rules are missing (CI gate)"],["lunora rules install --dir packages/app","Install into a specific root instead of the workspace root"]],group:"Project",loader:()=>import("../packem_chunks/handler16.mjs").then(e=>({default:e.execute})),name:"rules",options:[{description:"Install/check root (default: the detected workspace root, not the current directory)",name:"dir",type:String},{description:"install: overwrite skill files that already exist (default: skip them)",name:"overwrite",type:Boolean},{description:"check: exit non-zero when the rules are missing (for CI gating)",name:"strict",type:Boolean}]},ye={argument:{description:"Function path (e.g. messages:send)",name:"functionPath",type:String},description:"Send a single RPC to a running Lunora Worker",examples:[[`lunora run messages:send --args '{"text":"hi"}'`,"Call a function with JSON args"],["lunora run messages:list --shard channel:demo","Target a specific shard"],["lunora run messages:list --as user_123","Run as an authenticated user (needed when the app gates on identity)"]],group:"Develop",loader:()=>import("../packem_chunks/runRpcCommand.mjs").then(e=>({default:e.execute})),name:"run",options:[{description:"JSON-encoded args object",name:"args",type:String},{description:"Run as this user id — dispatches through the admin-gated `runAs` op so identity-gated apps accept the call",name:"as",type:String},{description:`JSON-encoded extra identity claims to forge alongside --as (e.g. '{"org":"acme"}')`,name:"claims",type:String},{description:"Explicit shard key",name:"shard",type:String},{description:"Worker URL (defaults to the running dev server, else http://localhost:8787)",name:"url",type:String},{description:"Admin bearer for --as (prefer LUNORA_ADMIN_TOKEN or .dev.vars; --token is visible to other local processes via the process table)",name:"token",type:String}]},fe={description:"Generate deterministic fake data from lunora/schema.ts and bulk-insert it via the worker's admin endpoint",examples:[["lunora seed","Seed every table with the default row count"],["lunora seed --table posts --count 50","Seed 50 posts; FK-parent tables are seeded automatically"],["lunora seed --reset","Wipe local .wrangler/state, then seed from scratch"],["lunora seed --seed 7 --dry-run","Print the NDJSON for seed 7 without inserting"],["lunora seed --seed 7 --now 1785000000000","Byte-identical rows across runs (pins the clock too)"]],group:"Data",loader:()=>import("../packem_chunks/handler17.mjs").then(e=>({default:e.execute})),name:"seed",options:[{description:"Rows per table (default 10)",name:"count",type:Number},{description:"Seed only this table; its FK-parent tables are seeded automatically",name:"table",type:String},{description:"Deterministic seed — same value yields identical rows (default 0)",name:"seed",type:Number},{description:"Epoch-ms reference for time columns (createdAt, expiresAt, …). Pin it with --seed for byte-identical rows across runs; defaults to now",name:"now",type:Number},{description:"Print the generated NDJSON instead of inserting",name:"dry-run",type:Boolean},{description:"Wipe local .wrangler/state before seeding (local dev only)",name:"reset",type:Boolean},{description:"Rows per HTTP request (default 500)",name:"batch-size",type:Number},{description:"Target production — requires an explicit --url",name:"prod",type:Boolean},{description:"Worker URL (default http://localhost:8787)",name:"url",type:String},{description:"Admin bearer token (prefer LUNORA_ADMIN_TOKEN; --token is visible to other local processes via the process table)",name:"token",type:String},{description:"Skip the confirmation prompt when seeding a non-local/production target",name:"yes",type:Boolean}]},ve={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/handler18.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},s]},be={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/handler19.mjs").then(e=>({default:e.execute})),name:"view",options:[{description:"Open the deployed worker URL instead of localhost",name:"remote",type:Boolean}]},we={filterStacktrace:()=>!1,hideErrorCodeView:!0},ke=(e,t={})=>{const r=e instanceof Error?e.message:String(e),o=j(k(e)?{code:e.code,hint:e.hint,message:r}:r),n=new U({hint:o===void 0?void 0:E(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="",M(n,we)},Se=(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,d=e[o-1]===t[a-1]?0:1;r[a]=Math.min((r[a-1]??0)+1,i+1,n+d),n=i}}return r[t.length]??0},xe=(e,t)=>{let r,o=Number.POSITIVE_INFINITY;for(const a of t){const i=Se(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},Re=e=>`https://registry.npmjs.org/@lunora/cli/${e}`,Oe=1440*60*1e3,Ne=1500,Ae="0.0.0",Be=/^v/u,De=new Set(["alpha","beta","next"]),m=e=>{const t=e.trim().replace(Be,""),r=t.indexOf("-");return r===-1?{core:t,prerelease:""}:{core:t.slice(0,r),prerelease:t.slice(r+1)}},v=e=>{const[t,r,o]=m(e).core.split(".").map(n=>{const a=Number.parseInt(n,10);return Number.isFinite(a)?a:0});return[t??0,r??0,o??0]},Le=(e,t)=>{const r=Number.parseInt(e,10),o=Number.parseInt(t,10);return String(r)===e&&String(o)===t?r>o?1:-1:e>t?1:-1},je=(e,t)=>{if(e===t)return 0;if(e===""||t==="")return e===""?1:-1;const r=e.split("."),o=t.split(".");for(let n=0;n<Math.max(r.length,o.length);n+=1){const a=r[n],i=o[n];if(a===void 0||i===void 0)return a===void 0?-1:1;if(a!==i)return Le(a,i)}return 0},Ee=(e,t)=>{const r=v(e),o=v(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 je(m(e).prerelease,m(t).prerelease)},Ce=e=>{const t=m(e).prerelease.split(".")[0]??"";return De.has(t)?t:"latest"},Ie=(e,t)=>Ee(t,e)>0,$e=(e,t,r)=>t-e<r,_e=(e,t,r="latest",o)=>{const n=`Update available for @lunora/cli: ${e} → ${t}`;if(o===void 0)return`${n} — add @lunora/cli@${r} as a dev dependency to update`;const{args:a,command:i}=T(o,[`@lunora/cli@${r}`],{dev:!0});return`${n} — run \`${i} ${a.join(" ")}\``},x=e=>u(e,"lunora-cli-update.json"),Te=e=>{const t=e.XDG_CACHE_HOME&&e.XDG_CACHE_HOME.length>0?e.XDG_CACHE_HOME:u(W(),".cache"),r=u(t,"lunora");try{A(r,{mode:448,recursive:!0})}catch{}return r},Pe=e=>{try{const t=JSON.parse(w(x(e),"utf8"));if(t!==null&&typeof t=="object"){const{checkedAt:r,latest:o}=t;if(typeof o=="string"&&typeof r=="number"){const{tag:n}=t;return{checkedAt:r,latest:o,...typeof n=="string"?{tag:n}:{}}}}}catch{}},b=(e,t)=>{try{const r=x(e);try{if(B(r).isSymbolicLink())return}catch{}D(r,`${JSON.stringify(t)}
3
+ `,"utf8")}catch{}},Ue=async(e,t)=>{try{const r=await e(Re(t),{signal:AbortSignal.timeout(Ne)});if(!r.ok)return;const o=await r.json(),n=o!==null&&typeof o=="object"?o.version:void 0;return typeof n=="string"?n:void 0}catch{return}},Me=(e,t,r)=>e===Ae||!r||t.CI!==void 0||t.LUNORA_NO_UPDATE_NOTIFIER!==void 0,We=async e=>{const t=e.env??process.env,r=e.isTTY??process.stdout.isTTY;if(Me(e.current,t,r))return;const o=e.cacheDir??Te(t),n=(e.now??Date.now)(),a=e.ttlMs??Oe,i=Ce(e.current),d=Pe(o),N=d?.tag??"latest",g=d!==void 0&&N===i?d:void 0;let c=g?.latest;if(g===void 0||!$e(g.checkedAt,n,a)){const h=await Ue(e.fetchImpl??globalThis.fetch,i);h===void 0?b(o,{checkedAt:n,latest:e.current,tag:i}):(c=h,b(o,{checkedAt:n,latest:h,tag:i}))}c!==void 0&&Ie(e.current,c)&&e.logger.warn(_e(e.current,c,i,e.manager))},Je=["init","add","dev","codegen","build","deploy","containers","prepare","link","deployments","logs","run","insights","reset","migrate","export","import","seed","backup","eval","verify","info","doctor","env","analyze","view","docs","registry","rules","mcp"],Ke=8,Fe=()=>{try{let e=y(L(import.meta.url));for(let t=0;t<Ke;t+=1){try{const o=JSON.parse(w(u(e,"package.json"),"utf8")),n=o!==null&&typeof o=="object"?o:void 0;if(n?.name==="@lunora/cli"&&typeof n.version=="string"&&n.version.length>0)return n.version}catch{}const r=y(e);if(r===e)break;e=r}}catch{}return"0.0.0"},R=Fe(),qe=[ae,J,Q,z,K,H,G,V,ue,le,Y,pe,ye,ie,ge,ce,re,oe,fe,se,q,te,ve,ne,Z,ee,F,be,X,me,he,de],O=[...qe,_,$],dt=O.map(e=>e.name),l=e=>e.replaceAll("{",String.raw`\{`).replaceAll("}",String.raw`\}`),He=e=>e.every(t=>typeof t=="string")?e.map(t=>l(t)):e.map(t=>typeof t=="string"?[l(t)]:t.map(r=>l(r))),ze=e=>({...e,...e.argument===void 0?{}:{argument:{...e.argument,description:l(e.argument.description??"")}},...e.description===void 0?{}:{description:l(e.description)},...e.examples===void 0?{}:{examples:He(e.examples)},...e.options===void 0?{}:{options:e.options.map(t=>({...t,description:l(t.description??"")}))}}),Ve=e=>{const t={value:0},r=I("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:R});for(const o of O)r.addCommand(ze(o));return{cli:r,exitCode:t}},Ge=/Command "(?<name>[^"]+)" not found/u,Ye=e=>{const t=S(),r=e instanceof Error?e.message:String(e),o=Ge.exec(r);if(!o?.groups){k(e)||C(r)!==void 0?t.error(ke(e)):t.error(r);return}const n=o.groups.name??"",a=xe(n,Je);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.")},ct=async(e={})=>{const{cli:t,exitCode:r}=Ve(e);try{await t.run({shouldExitProcess:!1})}catch(n){return Ye(n),1}let o;try{o=P(process.cwd())}catch{}return await We({current:R,logger:S(),manager:o}),r.value};export{Je as d,ct as f,R as i,f as o,dt as t};
@@ -0,0 +1 @@
1
+ const f="/_lunora/health",m="/_lunora/health/ready",d=(t,r=f)=>(t.endsWith("/")?t.slice(0,-1):t)+r,c=async(t,r,h)=>{let o={error:`health probe failed: no health path configured for ${t}`,url:t};for(const[l,u]of r.entries()){const e=d(t,u);let a;try{a=await h(e)}catch(n){const s=n instanceof Error?n.message:String(n);return{error:`health probe failed: could not reach ${e} (${s})`,url:e}}if(a.ok)return{url:e};if(o={error:`health probe failed: ${e} returned HTTP ${String(a.status)}`,url:e},a.status!==404||l===r.length-1)return o}return o},p=async t=>new Promise(r=>{setTimeout(r,t)}),g=async({attempts:t=1,baseUrl:r,delayMs:h=2e3,fetchImpl:o,paths:l=[f],sleep:u=p,timeoutMs:e=1e4})=>{const a=o??(i=>fetch(i,{signal:AbortSignal.timeout(e)})),n=Math.max(1,t);let s=await c(r,l,a);for(let i=1;i<n&&s.error!==void 0;i+=1)await u(h),s=await c(r,l,a);return s};export{m as b,f as c,g as p};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@lunora/cli",
3
- "version": "1.0.0-alpha.150",
3
+ "version": "1.0.0-alpha.151",
4
4
  "description": "The Lunora CLI: init, dev, deploy, codegen, migrate, seed, doctor, insights, logs, registry, and the rest of the project commands",
5
5
  "keywords": [
6
6
  "agent-skills",
@@ -59,7 +59,7 @@
59
59
  "@lunora/container": "1.0.0-alpha.25",
60
60
  "@lunora/d1": "1.0.0-alpha.68",
61
61
  "@lunora/errors": "1.0.0-alpha.16",
62
- "@lunora/mcp": "1.0.0-alpha.60",
62
+ "@lunora/mcp": "1.0.0-alpha.61",
63
63
  "@lunora/runtime": "1.0.0-alpha.57",
64
64
  "@lunora/seed": "1.0.0-alpha.66",
65
65
  "@visulima/cerebro": "3.0.0",
@@ -1,3 +0,0 @@
1
- import{mkdirSync as A,readFileSync as w,lstatSync as B,writeFileSync as D}from"node:fs";import{join as u,dirname as y}from"node:path";import{fileURLToPath as L}from"node:url";import{resolveHint as j,isLunoraError as S,flattenHint as E,findSolutionByMessage as C}from"@lunora/errors";import{createCerebro as I}from"@visulima/cerebro";import $ from"@visulima/cerebro/command/completion";import T from"@visulima/cerebro/command/version";import{p}from"./api-spec-BENwiyUa.mjs";import{g as s}from"./deploy-target-Dvr9vxpR.mjs";import{P,l as _}from"./detect-package-manager-DXDstphE.mjs";import{createLogger as k}from"./createLogger-BoSxdb2T.mjs";import{VisulimaError as U,renderError as M}from"@visulima/error";import{homedir as W}from"node:os";const J={argument:{description:"Feature or registry item: ai | auth | email | storage | crons | presence | queue | workflow | flags | backup | …",name:"feature",type:String},description:"Add a feature or registry item (ai, auth, email, storage, crons, …) to the current Lunora project",examples:[["lunora add auth","Add authentication (asks which provider)"],["lunora add auth --provider clerk","Add Clerk auth without prompting"],["lunora add auth-ui","Add copy-in auth screens for your framework (auto-detected)"],["lunora add email","Add transactional email (Cloudflare Email Workers + dev mail catcher)"],["lunora add storage","Add the R2 storage registry item (asks for the bucket name)"],["lunora add storage --bucket my-app-uploads","Add storage with a bucket name, no prompt"],["lunora add crons","Add the scheduled-jobs registry item"],["lunora add storage --ref alpha","Add an item from the alpha branch's registry"]],group:"Project",loader:()=>import("../packem_chunks/handler.mjs").then(e=>({default:e.execute})),name:"add",options:[{description:"auth: provider to use without prompting (auth | clerk | auth0)",name:"provider",type:String},{description:"auth: D1 database name to use without prompting (lowercase alphanumeric + hyphens)",name:"db",type:String},{description:"storage: R2 bucket name to use without prompting (lowercase alphanumeric + hyphens)",name:"bucket",type:String},{description:"email: verified destination address to use without prompting",name:"mail-to",type:String},{description:"Skip prompts (auth provider, DB name, bucket name, mail destination) and use the defaults",name:"yes",type:Boolean},{description:"Local registry root (offline; expects <name>/ subdirs)",name:"from",type:String},{description:"Override the remote registry source base (e.g. gh:owner/repo/registry)",name:"source",type:String},{description:"Fetch items from a git ref (branch, tag, or commit), e.g. --ref alpha. Overrides the version-derived default",name:"ref",type:String},{description:"Permit --source values outside gh:/github:/https://",name:"allow-unsafe-source",type:Boolean},{description:"Output format: pretty (default) or json",name:"format",type:String}]},f="lunora.advisor.map.json",K={description:"Score your app's advisor findings into a health map, and gate CI on it",examples:[["lunora advisor","Score the app and write lunora.advisor.map.json"],["lunora advisor --all","Show every procedure as a check matrix"],["lunora advisor --entry messages#sendMessage","Inspect one procedure"],["lunora advisor --min-score 80","Exit non-zero when the score drops below 80"],["lunora advisor --baseline","Fail on any regression against the committed map"]],group:"Develop",loader:()=>import("../packem_chunks/handler21.mjs").then(e=>({default:e.execute})),name:"advisor",options:[{description:"Show every procedure as a check matrix, not just the ones with findings",name:"all",type:Boolean},{description:`Compare against a committed map and fail on regression (default ${f})`,name:"baseline",type:String},{description:"Inspect a single procedure by `file#exportName`",name:"entry",type:String},{description:"Output format: pretty (default) or json",name:"format",type:String},{description:"Exit non-zero when the global score is below this value (0-100)",name:"min-score",type:String},{description:`Where to write the map (default ${f})`,name:"out",type:String},{description:"Write the map artifact to disk (default true; use --no-write to skip)",name:"no-write",type:Boolean}]},F={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}]},q={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}]},H={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"],["lunora build --emit-bindings bindings.json","Also write what the bundle needs provisioned, for an external deployer"]],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:"Write a JSON manifest of the bindings + crons the bundle needs to this path, for an IaC program to consume",name:"emit-bindings",type:String},{description:"Output format: pretty (default) or json",name:"format",type:String},{description:"Directory to write the bundled Worker to (default .lunora/build)",name:"out-dir",type:String},s]},z={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},{description:"Fail on ERROR-level advisories even locally (the gate already defaults to on in CI)",name:"strict-advisories",type:Boolean},{description:"Don't fail on ERROR-level advisories (the gate defaults to on in CI, off locally)",name:"no-strict-advisories",type:Boolean},s]},V={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}]},G={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:"Fail the deploy on ERROR-level codegen advisories even locally (the gate already defaults to on in CI)",name:"strict-advisories",type:Boolean},{description:"Don't fail the deploy on ERROR-level codegen advisories (the gate defaults to on in CI, off locally). Never downgrades platform diagnostics.",name:"no-strict-advisories",type:Boolean},{description:"Upload a preview version (wrangler versions upload) instead of going live — prints a preview URL; doesn't shift production traffic",name:"preview",type:Boolean},s,{description:"Deploy to a temporary Cloudflare account when unauthenticated (wrangler deploy --temporary; live ~60min, then claim or it's deleted). Wrangler errors if you're already authenticated.",name:"temporary",type:Boolean},{description:"Re-bless the committed schema baseline (lunora/.lunora-schema.json) with the current shape",name:"update-schema-baseline",type:Boolean}]},Y={argument:{description:"list | inspect <version-id> | rollback [version-id] | promote <version-id>",name:"subcommand",type:String},description:"List deployments and roll back / promote / inspect Worker versions",examples:[["lunora deployments list","Show the 10 most recent deployments"],["lunora deployments inspect <version-id>","View a specific Worker version"],["lunora deployments rollback --yes","Roll back to the previous version"],["lunora deployments promote <version-id> --yes","Send 100% of traffic to a version"]],group:"Deploy",loader:()=>import("../packem_chunks/handler6.mjs").then(e=>({default:e.execute})),name:"deployments",options:[{description:"Cloudflare environment name",name:"env",type:String},{description:"Display `list` output as JSON",name:"json",type:Boolean},{description:"Reason/description recorded with a rollback or promote",name:"message",type:String},{description:"Confirm a rollback or promote (required — these change live traffic)",name:"yes",type:Boolean}]},Q={argument:{description:"Optional subcommand: stop (shut the running dev server down) | status (report it) | logs (print its captured output)",name:"args",type:String},description:"Run the dev stack: wrangler worker + studio + codegen watch",examples:[["lunora dev","Run the worker + studio + codegen watch"],["lunora dev --background","Run detached: blocks until ready, prints URL + PID, then returns"],["lunora dev stop","Stop the background/tracked dev server (idempotent)"],["lunora dev status","Report the running dev server (URL, PID, uptime)"],["lunora dev logs","Print the captured dev-server log (background runs)"],["lunora dev --json","Machine-readable JSON log lines (also LUNORA_LOG_JSON=1)"],["lunora dev --no-studio","Skip the embedded studio server"],["lunora dev --worker-port 8080","Use a custom wrangler dev port"],["lunora dev --remote","Proxy D1/KV/R2 to the deployed worker (also LUNORA_REMOTE=1)"]],group:"Develop",loader:()=>import("../packem_chunks/planDevCommand.mjs").then(e=>({default:e.execute})),name:"dev",options:[{description:`Which API spec(s) codegen emits: ${p} (default openapi)`,name:"api-spec",type:String},{description:"Studio server port (default 6173)",name:"port",type:Number},s,{description:"wrangler dev port (default 8787)",name:"worker-port",type:Number},{description:"Run the dev server as a managed background process (auto-enabled when an AI agent is detected; LUNORA_AGENT_MODE=0 disables)",name:"background",type:Boolean},{description:"Emit machine-readable JSON log lines (also LUNORA_LOG_JSON=1; auto-enabled for AI agents)",name:"json",type:Boolean},{description:"How many trailing lines `lunora dev logs` prints (default 100, 0 = all)",name:"lines",type:Number},{description:"Don't start the embedded studio server",name:"no-studio",type:Boolean},{description:"Don't spawn wrangler dev — an external task runner owns the worker; codegen watch + studio still run",name:"no-worker",type:Boolean},{description:"Don't watch + regenerate codegen",name:"no-codegen",type:Boolean},{description:"Proxy D1/KV/R2 bindings to the deployed worker (or set LUNORA_REMOTE=1)",name:"remote",type:Boolean}]},X={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"},Z={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:[]},ee={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 this Cloudflare environment for `push`/`diff` (passes --env <name> to wrangler)",name:"env",type:String},{description:"Alias for --env production",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}]},te={description:"Run every *.eval.ts under evals/ via @lunora/testing's evaluate/agentHarness — no live worker needed",examples:[["lunora eval","Run every eval under evals/, print the aggregate table"],["lunora eval --threshold 0.8","Non-zero exit if any eval's average score falls below 0.8"],["lunora eval --dir evals/support --format json","Run a subset and emit a machine-readable result"]],group:"Develop",loader:()=>import("../packem_chunks/handler23.mjs").then(e=>({default:e.execute})),name:"eval",options:[{description:"Directory to discover *.eval.ts files under (default evals/)",name:"dir",type:String},{description:"Output format: pretty (default) or json",name:"format",type:String},{description:"Score gate every eval's average must meet ([0,1]); a per-eval `threshold` export wins over this for that eval",name:"threshold",type:Number}]},re={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}]},oe={argument:{description:"Source NDJSON file, or a `npx convex export --path <dir>` directory",name:"file",type:String},description:"Bulk-insert rows from an NDJSON file — or a Convex export directory — via the worker's admin endpoint",examples:[["lunora import backup.ndjson","Bulk-insert rows from an NDJSON file"],["lunora import ./convex-export","Import a `npx convex export --path` directory (ids are preserved, so no remapping)"],["lunora import ./convex-export --with-storage","Also migrate blobs (verified sha256 upload) + `{ $storage }` refs"],["lunora import ./convex-export --scan","Write a candidate `lunora/import-convex.json` storage-column mapping (imports nothing)"],["lunora import ./snapshot.zip --with-storage --verify","Import a `npx convex export --path` zip snapshot with blob + row-parity checks"],["lunora import ./supabase-csv --from supabase","Import a directory of `COPY … TO STDOUT WITH CSV HEADER` dumps"],["lunora import ./firestore-json --from firebase --verify","Import Firestore documents (REST/Admin-SDK JSON) with row-parity checks"]],group:"Data",loader:()=>import("../packem_chunks/handler11.mjs").then(e=>({default:e.execute})),name:"import",options:[{description:"Source reader for a dump that cannot be detected: supabase | firebase (Convex and NDJSON are auto-detected)",name:"from",type:String},{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:"Also migrate file storage — Convex `_storage` blobs, or a Supabase/Firebase bucket (verified upload)",name:"with-storage",type:Boolean},{description:"Directory of storage objects to upload alongside the rows (Firebase: after `gcloud storage cp -r`)",name:"storage-dir",type:String},{description:"Write a candidate `lunora/import-convex.json` storage-column mapping and exit",name:"scan",type:Boolean},{description:"Verify row parity + dangling-storage after import (non-zero exit on mismatch)",name:"verify",type:Boolean},{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}]},ne={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}]},ae={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}]},ie={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}]},se={description:"Scaffold lunora/schema.ts (and list/get procedures) from an existing Postgres or MySQL database",examples:[["lunora introspect --url postgres://localhost/shop","Scaffold a schema + procedures from every table"],["lunora introspect --tables users,orders","Introspect only these tables (DATABASE_URL is read by default)"],["lunora introspect --dry-run","Print what would be written without touching the filesystem"],["lunora introspect --no-procedures --force","Regenerate just the schema, overwriting the existing file"]],group:"Data",loader:()=>import("../packem_chunks/handler24.mjs").then(e=>({default:e.execute})),name:"introspect",options:[{description:"Database connection string (default: $DATABASE_URL)",name:"url",type:String},{description:"Postgres schema (default `public`) or MySQL database name",name:"schema",type:String},{description:"Comma-separated table allow-list (default: every base table)",name:"tables",type:String},{description:"Also emit list/get procedure modules per table (default true; --no-procedures to skip)",name:"procedures",type:Boolean},{description:"Overwrite files that already exist",name:"force",type:Boolean},{description:"Print what would be written without writing it",name:"dry-run",type:Boolean}]},le={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}]},pe={argument:{description:"Worker name (defaults to the name in wrangler config)",name:"worker",type:String},description:"Stream live logs from a deployed Worker, or read the durable log archive with --durable",group:"Deploy",loader:()=>import("../packem_chunks/handler22.mjs").then(e=>({default:e.execute})),name:"logs",options:[{description:"Cloudflare environment name",name:"env",type:String},{description:"Output format: pretty (default) or json",name:"format",type:String},{description:"Substring filter on log messages",name:"search",type:String},{description:"Filter by invocation status: ok, error, or canceled",name:"status",type:String},s,{description:"Tail a temporary-account deployment when unauthenticated (wrangler tail --temporary). Errors if you're already authenticated.",name:"temporary",type:Boolean},{description:"Read the durable log archive (pipelineLogSink → R2) via R2 SQL instead of tailing live",name:"durable",type:Boolean},{description:"durable: Iceberg table the Pipeline writes to (required with --durable)",name:"table",type:String},{description:"durable: Iceberg namespace (R2 Data Catalog database) the table lives in",name:"namespace",type:String},{description:"durable: lower time bound (epoch-millis or ISO 8601), inclusive",name:"since",type:String},{description:"durable: upper time bound (epoch-millis or ISO 8601), inclusive",name:"until",type:String},{description:"durable: exact severity filter (trace|debug|log|info|warn|error|fatal)",name:"level",type:String},{description:"durable: severity floor — this level and every more-severe one",name:"min-level",type:String},{description:"durable: keep function paths starting with this prefix (LIKE 'prefix%')",name:"function-prefix",type:String},{description:"durable: trace-id filter",name:"trace-id",type:String},{description:"durable: shard-key filter",name:"shard-key",type:String},{description:"durable: user-id filter",name:"user-id",type:String},{description:"durable: max rows (clamped to 1–10000; default 500)",name:"limit",type:String},{description:"durable: resume after a prior page — the opaque cursor token printed by the previous page (bare epoch-millis also accepted for back-compat)",name:"cursor",type:String},{description:"durable: emit one JSON object per line instead of a table",name:"ndjson",type:Boolean}]},de={argument:{description:"install [client…] | uninstall [client…] | serve",name:"args",type:String},description:"Connect your AI editor to Lunora over MCP (docs search + this project's dev server)",examples:[["lunora mcp install","Install into every MCP client already configured here"],["lunora mcp install claude-code cursor","Install into specific clients"],["lunora mcp install --list","List the supported clients and their config files"],["lunora mcp install --docs-only","Install only the hosted documentation server"],["lunora mcp install --print","Show the config that would be written, without writing it"],["lunora mcp install --global","Force every server into the machine-wide config"],["lunora mcp uninstall","Remove Lunora's MCP servers from every supported client"],["lunora mcp uninstall cursor","Remove them from one client"],["lunora mcp uninstall --print","Show what would be removed, without removing it"],["lunora mcp serve","Run the stdio MCP server (this is what your editor spawns)"],["lunora mcp serve --allow-writes","Also expose the mutation/action tools"]],group:"Develop",loader:()=>import("../packem_chunks/handler25.mjs").then(e=>({default:e.execute})),name:"mcp",options:[{description:"install: replace entries that already exist",name:"force",type:Boolean},{description:"install: list the supported clients and their config files",name:"list",type:Boolean},{description:"install/uninstall: print what would change instead of writing it",name:"print",type:Boolean},{description:"install/uninstall: only the hosted documentation server",name:"docs-only",type:Boolean},{description:"install/uninstall: only this project's local server",name:"local-only",type:Boolean},{description:"install/uninstall: the machine-wide config (install default: docs server global, local server per-project)",name:"global",type:Boolean},{description:"install/uninstall: this project's config instead of the machine-wide one",name:"project",type:Boolean},{description:"serve: also expose the mutation/action tools (default: read-only)",name:"allow-writes",type:Boolean},{description:"serve: skip the documentation tools",name:"no-docs",type:Boolean},{description:"Docs site origin backing the documentation tools (default https://lunora.sh)",name:"docs-url",type:String},{description:"serve: deployment URL to expose (default: the running dev server)",name:"url",type:String},{description:"serve: bearer token (default: LUNORA_ADMIN_TOKEN from the environment or .dev.vars)",name:"token",type:String}]},ce={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}]},ue={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},s,{description:"Re-bless the committed schema baseline (lunora/.lunora-schema.json) with the current shape",name:"update-schema-baseline",type:Boolean}]},me={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}]},ge={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}]},he={argument:{description:"install | check",name:"subcommand",type:String},description:"Install the Lunora agent skills (AI rules) into .agents/skills/, or check they're present",examples:[["lunora rules install","Copy the Lunora agent skills into .agents/skills/"],["lunora rules install --overwrite","Reinstall, replacing edited skill files"],["lunora rules check","Report which Lunora skills are installed"],["lunora rules check --strict","Exit non-zero when rules are missing (CI gate)"],["lunora rules install --dir packages/app","Install into a specific root instead of the workspace root"]],group:"Project",loader:()=>import("../packem_chunks/handler17.mjs").then(e=>({default:e.execute})),name:"rules",options:[{description:"Install/check root (default: the detected workspace root, not the current directory)",name:"dir",type:String},{description:"install: overwrite skill files that already exist (default: skip them)",name:"overwrite",type:Boolean},{description:"check: exit non-zero when the rules are missing (for CI gating)",name:"strict",type:Boolean}]},ye={argument:{description:"Function path (e.g. messages:send)",name:"functionPath",type:String},description:"Send a single RPC to a running Lunora Worker",examples:[[`lunora run messages:send --args '{"text":"hi"}'`,"Call a function with JSON args"],["lunora run messages:list --shard channel:demo","Target a specific shard"],["lunora run messages:list --as user_123","Run as an authenticated user (needed when the app gates on identity)"]],group:"Develop",loader:()=>import("../packem_chunks/runRpcCommand.mjs").then(e=>({default:e.execute})),name:"run",options:[{description:"JSON-encoded args object",name:"args",type:String},{description:"Run as this user id — dispatches through the admin-gated `runAs` op so identity-gated apps accept the call",name:"as",type:String},{description:`JSON-encoded extra identity claims to forge alongside --as (e.g. '{"org":"acme"}')`,name:"claims",type:String},{description:"Explicit shard key",name:"shard",type:String},{description:"Worker URL (defaults to the running dev server, else http://localhost:8787)",name:"url",type:String},{description:"Admin bearer for --as (prefer LUNORA_ADMIN_TOKEN or .dev.vars; --token is visible to other local processes via the process table)",name:"token",type:String}]},fe={description:"Generate deterministic fake data from lunora/schema.ts and bulk-insert it via the worker's admin endpoint",examples:[["lunora seed","Seed every table with the default row count"],["lunora seed --table posts --count 50","Seed 50 posts; FK-parent tables are seeded automatically"],["lunora seed --reset","Wipe local .wrangler/state, then seed from scratch"],["lunora seed --seed 7 --dry-run","Print the NDJSON for seed 7 without inserting"],["lunora seed --seed 7 --now 1785000000000","Byte-identical rows across runs (pins the clock too)"]],group:"Data",loader:()=>import("../packem_chunks/handler18.mjs").then(e=>({default:e.execute})),name:"seed",options:[{description:"Rows per table (default 10)",name:"count",type:Number},{description:"Seed only this table; its FK-parent tables are seeded automatically",name:"table",type:String},{description:"Deterministic seed — same value yields identical rows (default 0)",name:"seed",type:Number},{description:"Epoch-ms reference for time columns (createdAt, expiresAt, …). Pin it with --seed for byte-identical rows across runs; defaults to now",name:"now",type:Number},{description:"Print the generated NDJSON instead of inserting",name:"dry-run",type:Boolean},{description:"Wipe local .wrangler/state before seeding (local dev only)",name:"reset",type:Boolean},{description:"Rows per HTTP request (default 500)",name:"batch-size",type:Number},{description:"Target production — requires an explicit --url",name:"prod",type:Boolean},{description:"Worker URL (default http://localhost:8787)",name:"url",type:String},{description:"Admin bearer token (prefer LUNORA_ADMIN_TOKEN; --token is visible to other local processes via the process table)",name:"token",type:String},{description:"Skip the confirmation prompt when seeding a non-local/production target",name:"yes",type:Boolean}]},ve={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},s]},be={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}]},we={filterStacktrace:()=>!1,hideErrorCodeView:!0},Se=(e,t={})=>{const r=e instanceof Error?e.message:String(e),o=j(S(e)?{code:e.code,hint:e.hint,message:r}:r),n=new U({hint:o===void 0?void 0:E(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="",M(n,we)},ke=(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,d=e[o-1]===t[a-1]?0:1;r[a]=Math.min((r[a-1]??0)+1,i+1,n+d),n=i}}return r[t.length]??0},xe=(e,t)=>{let r,o=Number.POSITIVE_INFINITY;for(const a of t){const i=ke(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},Re=e=>`https://registry.npmjs.org/@lunora/cli/${e}`,Oe=1440*60*1e3,Ne=1500,Ae="0.0.0",Be=/^v/u,De=new Set(["alpha","beta","next"]),m=e=>{const t=e.trim().replace(Be,""),r=t.indexOf("-");return r===-1?{core:t,prerelease:""}:{core:t.slice(0,r),prerelease:t.slice(r+1)}},v=e=>{const[t,r,o]=m(e).core.split(".").map(n=>{const a=Number.parseInt(n,10);return Number.isFinite(a)?a:0});return[t??0,r??0,o??0]},Le=(e,t)=>{const r=Number.parseInt(e,10),o=Number.parseInt(t,10);return String(r)===e&&String(o)===t?r>o?1:-1:e>t?1:-1},je=(e,t)=>{if(e===t)return 0;if(e===""||t==="")return e===""?1:-1;const r=e.split("."),o=t.split(".");for(let n=0;n<Math.max(r.length,o.length);n+=1){const a=r[n],i=o[n];if(a===void 0||i===void 0)return a===void 0?-1:1;if(a!==i)return Le(a,i)}return 0},Ee=(e,t)=>{const r=v(e),o=v(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 je(m(e).prerelease,m(t).prerelease)},Ce=e=>{const t=m(e).prerelease.split(".")[0]??"";return De.has(t)?t:"latest"},Ie=(e,t)=>Ee(t,e)>0,$e=(e,t,r)=>t-e<r,Te=(e,t,r="latest",o)=>{const n=`Update available for @lunora/cli: ${e} → ${t}`;if(o===void 0)return`${n} — add @lunora/cli@${r} as a dev dependency to update`;const{args:a,command:i}=P(o,[`@lunora/cli@${r}`],{dev:!0});return`${n} — run \`${i} ${a.join(" ")}\``},x=e=>u(e,"lunora-cli-update.json"),Pe=e=>{const t=e.XDG_CACHE_HOME&&e.XDG_CACHE_HOME.length>0?e.XDG_CACHE_HOME:u(W(),".cache"),r=u(t,"lunora");try{A(r,{mode:448,recursive:!0})}catch{}return r},_e=e=>{try{const t=JSON.parse(w(x(e),"utf8"));if(t!==null&&typeof t=="object"){const{checkedAt:r,latest:o}=t;if(typeof o=="string"&&typeof r=="number"){const{tag:n}=t;return{checkedAt:r,latest:o,...typeof n=="string"?{tag:n}:{}}}}}catch{}},b=(e,t)=>{try{const r=x(e);try{if(B(r).isSymbolicLink())return}catch{}D(r,`${JSON.stringify(t)}
3
- `,"utf8")}catch{}},Ue=async(e,t)=>{try{const r=await e(Re(t),{signal:AbortSignal.timeout(Ne)});if(!r.ok)return;const o=await r.json(),n=o!==null&&typeof o=="object"?o.version:void 0;return typeof n=="string"?n:void 0}catch{return}},Me=(e,t,r)=>e===Ae||!r||t.CI!==void 0||t.LUNORA_NO_UPDATE_NOTIFIER!==void 0,We=async e=>{const t=e.env??process.env,r=e.isTTY??process.stdout.isTTY;if(Me(e.current,t,r))return;const o=e.cacheDir??Pe(t),n=(e.now??Date.now)(),a=e.ttlMs??Oe,i=Ce(e.current),d=_e(o),N=d?.tag??"latest",g=d!==void 0&&N===i?d:void 0;let c=g?.latest;if(g===void 0||!$e(g.checkedAt,n,a)){const h=await Ue(e.fetchImpl??globalThis.fetch,i);h===void 0?b(o,{checkedAt:n,latest:e.current,tag:i}):(c=h,b(o,{checkedAt:n,latest:h,tag:i}))}c!==void 0&&Ie(e.current,c)&&e.logger.warn(Te(e.current,c,i,e.manager))},Je=["init","add","dev","codegen","build","deploy","containers","prepare","link","deployments","logs","run","insights","reset","migrate","export","import","seed","backup","eval","verify","info","doctor","env","analyze","view","docs","registry","rules","mcp"],Ke=8,Fe=()=>{try{let e=y(L(import.meta.url));for(let t=0;t<Ke;t+=1){try{const o=JSON.parse(w(u(e,"package.json"),"utf8")),n=o!==null&&typeof o=="object"?o:void 0;if(n?.name==="@lunora/cli"&&typeof n.version=="string"&&n.version.length>0)return n.version}catch{}const r=y(e);if(r===e)break;e=r}}catch{}return"0.0.0"},R=Fe(),qe=[ae,J,Q,z,K,H,G,V,ue,le,Y,pe,ye,ie,ge,ce,re,oe,fe,se,q,te,ve,ne,Z,ee,F,be,X,me,he,de],O=[...qe,T,$],dt=O.map(e=>e.name),l=e=>e.replaceAll("{",String.raw`\{`).replaceAll("}",String.raw`\}`),He=e=>e.every(t=>typeof t=="string")?e.map(t=>l(t)):e.map(t=>typeof t=="string"?[l(t)]:t.map(r=>l(r))),ze=e=>({...e,...e.argument===void 0?{}:{argument:{...e.argument,description:l(e.argument.description??"")}},...e.description===void 0?{}:{description:l(e.description)},...e.examples===void 0?{}:{examples:He(e.examples)},...e.options===void 0?{}:{options:e.options.map(t=>({...t,description:l(t.description??"")}))}}),Ve=e=>{const t={value:0},r=I("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:R});for(const o of O)r.addCommand(ze(o));return{cli:r,exitCode:t}},Ge=/Command "(?<name>[^"]+)" not found/u,Ye=e=>{const t=k(),r=e instanceof Error?e.message:String(e),o=Ge.exec(r);if(!o?.groups){S(e)||C(r)!==void 0?t.error(Se(e)):t.error(r);return}const n=o.groups.name??"",a=xe(n,Je);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.")},ct=async(e={})=>{const{cli:t,exitCode:r}=Ve(e);try{await t.run({shouldExitProcess:!1})}catch(n){return Ye(n),1}let o;try{o=_(process.cwd())}catch{}return await We({current:R,logger:k(),manager:o}),r.value};export{Je as d,ct as f,R as i,f as o,dt as t};