@lunora/cli 1.0.0-alpha.153 → 1.0.0-alpha.154

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (32) hide show
  1. package/dist/bin.mjs +1 -1
  2. package/dist/index.mjs +1 -1
  3. package/dist/packem_chunks/handler10.mjs +2 -1
  4. package/dist/packem_chunks/handler11.mjs +2 -2
  5. package/dist/packem_chunks/handler12.mjs +1 -2
  6. package/dist/packem_chunks/handler13.mjs +1 -1
  7. package/dist/packem_chunks/handler14.mjs +1 -1
  8. package/dist/packem_chunks/handler15.mjs +1 -1
  9. package/dist/packem_chunks/handler16.mjs +3 -1
  10. package/dist/packem_chunks/handler17.mjs +1 -3
  11. package/dist/packem_chunks/handler18.mjs +1 -1
  12. package/dist/packem_chunks/handler19.mjs +7 -1
  13. package/dist/packem_chunks/handler20.mjs +2 -7
  14. package/dist/packem_chunks/handler21.mjs +2 -2
  15. package/dist/packem_chunks/handler22.mjs +3 -2
  16. package/dist/packem_chunks/handler25.mjs +1 -1
  17. package/dist/packem_chunks/handler3.mjs +1 -2
  18. package/dist/packem_chunks/handler4.mjs +1 -1
  19. package/dist/packem_chunks/handler5.mjs +1 -1
  20. package/dist/packem_chunks/handler6.mjs +1 -1
  21. package/dist/packem_chunks/handler7.mjs +3 -1
  22. package/dist/packem_chunks/handler8.mjs +1 -3
  23. package/dist/packem_chunks/handler9.mjs +1 -1
  24. package/dist/packem_chunks/runMigrateGenerateCommand.mjs +1 -1
  25. package/dist/packem_shared/{COMMANDS-DMyRipjO.mjs → COMMANDS-Dxa7jNW-.mjs} +1 -1
  26. package/dist/packem_shared/{DEFAULT_IMPORT_BATCH_SIZE-Dqu4Zmi0.mjs → DEFAULT_IMPORT_BATCH_SIZE-D7L8R74L.mjs} +1 -1
  27. package/dist/packem_shared/cli-CV8K0mAX.mjs +3 -0
  28. package/dist/packem_shared/import-C9in1wC3.mjs +12 -0
  29. package/dist/packem_shared/path-containment-CcTCKfzV.mjs +1 -0
  30. package/package.json +11 -11
  31. package/dist/packem_shared/cli-RVVu3rxm.mjs +0 -3
  32. package/dist/packem_shared/import-DLyCq-2j.mjs +0 -12
@@ -1 +1,3 @@
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
+ 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{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
+ import{i as n}from"../packem_shared/command-0l-ZPhIX.mjs";import{d as m}from"../packem_shared/resolve-target-CeiNrCAx.mjs";import{w as i,S as s}from"../packem_shared/import-C9in1wC3.mjs";const f=n(({argument:a,cwd:r,logger:e,options:o})=>{const t=a[0];return t?o.from!==void 0&&!i.includes(o.from)?(e.error(`--from ${o.from} is not a known source. Expected one of: ${i.join(", ")}.`),{code:1}):s({batchSize:o.batchSize,cwd:r,file:t,from:o.from,logger:e,prod:o.prod===!0,scan:o.scan===!0,storageDir:o.storageDir,table:o.table,token:o.token,url:m({cwd:r,prod:o.prod===!0,url:o.url}),verify:o.verify===!0,withStorage:o.withStorage===!0,yes:o.yes===!0}):(e.error("import requires a path. Usage: lunora import <file.ndjson | convex-export-dir> [--table <name>]"),{code:1})});export{f as execute};
@@ -1,4 +1,4 @@
1
- import{existsSync as m,mkdirSync as k,writeFileSync as f,mkdtempSync as A,rmSync as I,readFileSync as T}from"node:fs";import{tmpdir as M}from"node:os";import{discoverSchema as _,readPackageDependencies as E,discoverMigrations as z}from"@lunora/codegen";import{isInteractive as F,promptSelect as N,promptText as R}from"@lunora/config";import{LunoraError as y}from"@lunora/errors";import{join as c}from"@visulima/path";import{Project as h}from"ts-morph";import{u as q}from"../packem_shared/admin-url-Ca-KI3d_.mjs";import{i as O}from"../packem_shared/command-0l-ZPhIX.mjs";import{diffSnapshots as D,renderMigrationFile as L}from"../packem_shared/diffSnapshots-BbwCuhoN.mjs";import{d as j}from"../packem_shared/resolve-target-CeiNrCAx.mjs";import B from"../packem_shared/schemaIrToSnapshot-Dahp39qH.mjs";import{readAndLogBody as H}from"./runRpcCommand.mjs";import{runExportCommand as P}from"../packem_shared/runExportCommand-BpE4AbuX.mjs";import{S as J}from"../packem_shared/import-DLyCq-2j.mjs";const u="__lunora_reproject__",W=r=>{if(!r.startsWith(u))return;const e=r.slice(u.length);return e===""?void 0:e},Z=".snapshot.json",x=/[^\da-z]+/gu,U=(r,e)=>{let o=0,t=r.length;for(;o<t&&r[o]===e;)o+=1;for(;t>o&&r[t-1]===e;)t-=1;return r.slice(o,t)},K=r=>{const e=U(r.toLowerCase().replaceAll(x,"_"),"_");return e===""?"auto":e},Q=r=>{const e=(o,t=2)=>o.toString().padStart(t,"0");return`${String(r.getUTCFullYear())}${e(r.getUTCMonth()+1)}${e(r.getUTCDate())}${e(r.getUTCHours())}${e(r.getUTCMinutes())}${e(r.getUTCSeconds())}`},Y=r=>{if(m(r))try{const e=T(r,"utf8"),o=JSON.parse(e);if(o.version!==1)throw new y("INTERNAL",`unsupported snapshot version: ${o.version}`);return o}catch(e){const o=e instanceof Error?e.message:String(e);throw new y("INTERNAL",`failed to read ${r}: ${o}`,{cause:e})}},G=r=>{const e=r.cwd??process.cwd(),o=c(e,"lunora","schema.ts");if(!m(o))return r.logger.error(`schema not found: ${o} — run \`vis generate lunora-table --name=<name>\` to create one`),{code:1,empty:!0,migrationFile:""};const t=new h({skipAddingFilesFromTsConfig:!0}),n=_(t,o),s=B(n),i=c(e,"lunora","migrations"),a=c(i,Z);let d;try{d=Y(a)}catch(p){return r.logger.error(p instanceof Error?p.message:String(p)),{code:1,empty:!0,migrationFile:""}}const l=D(d,s);if(l.empty)return r.logger.info("no schema changes detected — snapshot is already up to date"),{code:0,empty:!0,migrationFile:""};const b=(r.now??(()=>new Date))(),w=K(r.name??"auto"),$=`${Q(b)}_${w}.sql`,g=c(i,$);k(i,{recursive:!0});const C=L(w,l,b.toISOString());return f(g,C,"utf8"),f(a,`${JSON.stringify(s,void 0,4)}
1
+ import{existsSync as m,mkdirSync as k,writeFileSync as f,mkdtempSync as A,rmSync as I,readFileSync as T}from"node:fs";import{tmpdir as M}from"node:os";import{discoverSchema as _,readPackageDependencies as E,discoverMigrations as z}from"@lunora/codegen";import{isInteractive as F,promptSelect as N,promptText as R}from"@lunora/config";import{LunoraError as y}from"@lunora/errors";import{join as c}from"@visulima/path";import{Project as h}from"ts-morph";import{u as q}from"../packem_shared/admin-url-Ca-KI3d_.mjs";import{i as O}from"../packem_shared/command-0l-ZPhIX.mjs";import{diffSnapshots as D,renderMigrationFile as L}from"../packem_shared/diffSnapshots-BbwCuhoN.mjs";import{d as j}from"../packem_shared/resolve-target-CeiNrCAx.mjs";import B from"../packem_shared/schemaIrToSnapshot-Dahp39qH.mjs";import{readAndLogBody as H}from"./runRpcCommand.mjs";import{runExportCommand as P}from"../packem_shared/runExportCommand-BpE4AbuX.mjs";import{S as J}from"../packem_shared/import-C9in1wC3.mjs";const u="__lunora_reproject__",W=r=>{if(!r.startsWith(u))return;const e=r.slice(u.length);return e===""?void 0:e},Z=".snapshot.json",x=/[^\da-z]+/gu,U=(r,e)=>{let o=0,t=r.length;for(;o<t&&r[o]===e;)o+=1;for(;t>o&&r[t-1]===e;)t-=1;return r.slice(o,t)},K=r=>{const e=U(r.toLowerCase().replaceAll(x,"_"),"_");return e===""?"auto":e},Q=r=>{const e=(o,t=2)=>o.toString().padStart(t,"0");return`${String(r.getUTCFullYear())}${e(r.getUTCMonth()+1)}${e(r.getUTCDate())}${e(r.getUTCHours())}${e(r.getUTCMinutes())}${e(r.getUTCSeconds())}`},Y=r=>{if(m(r))try{const e=T(r,"utf8"),o=JSON.parse(e);if(o.version!==1)throw new y("INTERNAL",`unsupported snapshot version: ${o.version}`);return o}catch(e){const o=e instanceof Error?e.message:String(e);throw new y("INTERNAL",`failed to read ${r}: ${o}`,{cause:e})}},G=r=>{const e=r.cwd??process.cwd(),o=c(e,"lunora","schema.ts");if(!m(o))return r.logger.error(`schema not found: ${o} — run \`vis generate lunora-table --name=<name>\` to create one`),{code:1,empty:!0,migrationFile:""};const t=new h({skipAddingFilesFromTsConfig:!0}),n=_(t,o),s=B(n),i=c(e,"lunora","migrations"),a=c(i,Z);let d;try{d=Y(a)}catch(p){return r.logger.error(p instanceof Error?p.message:String(p)),{code:1,empty:!0,migrationFile:""}}const l=D(d,s);if(l.empty)return r.logger.info("no schema changes detected — snapshot is already up to date"),{code:0,empty:!0,migrationFile:""};const b=(r.now??(()=>new Date))(),w=K(r.name??"auto"),$=`${Q(b)}_${w}.sql`,g=c(i,$);k(i,{recursive:!0});const C=L(w,l,b.toISOString());return f(g,C,"utf8"),f(a,`${JSON.stringify(s,void 0,4)}
2
2
  `,"utf8"),r.logger.success(`wrote ${g}`),l.unsupported.length>0&&r.logger.warn(`${String(l.unsupported.length)} unsupported diff(s) — see the comment block in ${$} and write the SQL manually`),{code:0,empty:!1,migrationFile:g}},V="migrations.ts",v=/^[A-Za-z_]\w*$/u,X=new Set(["await","break","case","catch","class","const","continue","debugger","default","delete","do","else","enum","export","extends","false","finally","for","function","if","implements","import","in","instanceof","interface","let","new","null","package","private","protected","public","return","static","super","switch","this","throw","true","try","typeof","var","void","while","with","yield"]),S=/^import\s*\{\s*defineMigration\s*\}\s*from\s*["'](?:@lunora\/server|lunorash\/server)["'][^\n]*$/mu,rr=r=>`import { defineMigration } from "${E(r)?.has("lunorash")??!1?"lunorash/server":"@lunora/server"}";`,er="__lunora_admin__:runMigration",tr="__lunora_admin__:migrationStatus",or="/_lunora/migrate",nr=r=>U(r.trim().toLowerCase().replaceAll(x,"-"),"-"),ir=r=>r.split("-").filter(e=>e.length>0).map((e,o)=>o===0?e:e.charAt(0).toUpperCase()+e.slice(1)).join(""),ar=r=>{const e=c(r,"lunora","schema.ts");if(!m(e))return[];try{const o=new h({skipAddingFilesFromTsConfig:!0});return _(o,e).tables.map(t=>t.name)}catch{return[]}},sr=async r=>r.length>0?N("Which table does this migration iterate?",r.map(e=>({label:e,value:e}))):R("Target table for the migration: "),cr=async(r,e)=>{if(e.table!==void 0)return e.table;const o=e.promptTable??(F()?sr:void 0);if(o===void 0){e.logger.error("migrate create requires a target table when not running interactively — re-run with --table <table>");return}const t=(await o(ar(r)))?.trim();if(t===void 0||t===""){e.logger.error("no table selected — re-run with --table <table>");return}return t},dr=async r=>{const e=r.cwd??process.cwd(),o=nr(r.name);if(o==="")return r.logger.error(`invalid migration name: "${r.name}" — must contain at least one alphanumeric character`),{code:1,file:""};const t=ir(o);if(!v.test(t)||X.has(t))return r.logger.error(`invalid migration name: "${r.name}" derives the export \`${t}\`, which is not a valid identifier — pick a name that starts with a letter and isn't a reserved word`),{code:1,file:""};const n=await cr(e,r);if(n===void 0)return{code:1,file:""};if(!v.test(n))return r.logger.error(`invalid table: "${n}" — must be a valid identifier ([A-Za-z_][A-Za-z0-9_]*)`),{code:1,file:""};const s=c(e,"lunora"),i=c(s,V);let a=m(i)?T(i,"utf8"):"";if(a.includes(`id: "${o}"`)||new RegExp(String.raw`\bexport const ${t}\b`,"u").test(a))return r.logger.error(`a migration with id "${o}" (export \`${t}\`) already exists in ${i}`),{code:1,file:""};const d=rr(e);a.trim()===""?a=`${d}
3
3
  `:S.test(a)?a=a.replace(S,d):a=`${d}
4
4
  ${a}`;const l=`export const ${t} = defineMigration({
@@ -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-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};
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-CV8K0mAX.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 +1 @@
1
- import"node:fs";import"node:fs/promises";import"./admin-token-BKmc3AUm.mjs";import"./admin-url-Ca-KI3d_.mjs";import{R as I,S as T}from"./import-DLyCq-2j.mjs";import"./shared-Ce9bKz5c.mjs";export{I as DEFAULT_IMPORT_BATCH_SIZE,T as runImportCommand};
1
+ import"node:fs";import"node:fs/promises";import"./admin-token-BKmc3AUm.mjs";import"./admin-url-Ca-KI3d_.mjs";import{R as I,S as T}from"./import-C9in1wC3.mjs";import"./shared-Ce9bKz5c.mjs";export{I as DEFAULT_IMPORT_BATCH_SIZE,T as runImportCommand};
@@ -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/handler19.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) to a directory or an R2 bucket, 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 create --bucket default","Snapshot into an R2 bucket instead of a directory"],["lunora backup restore <id> --bucket default --verify","Restore from R2, checksum first"],["lunora backup pitr --at 2026-06-01T00:00:00Z","Point-in-time recovery (≤30 days)"]],group:"Data",loader:()=>import("../packem_chunks/handler22.mjs").then(e=>({default:e.execute})),name:"backup",options:[{description:"Backup directory (default .lunora-backups)",name:"dir",type:String},{description:"Store snapshots in this R2 bucket instead of a directory (use `default` for the app's default bucket)",name:"bucket",type:String},{description:"Key prefix for bucket-backed snapshots (default backups/)",name:"prefix",type:String},{description:"restore: verify the snapshot's checksum before importing anything",name:"verify",type:Boolean},{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/handler20.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/handler3.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/handler4.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/handler5.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/handler6.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/handler7.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/handler8.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/handler9.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/handler10.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/handler11.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/handler12.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/handler21.mjs").then(e=>({default:e.execute})),name:"logs",options:[{description:"Cloudflare environment name",name:"env",type:String},{description:"Output format: pretty (default) or json",name:"format",type:String},{description:"Substring filter on log messages",name:"search",type:String},{description:"Filter by invocation status: ok, error, or canceled",name:"status",type:String},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/handler13.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/handler14.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/handler15.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/handler16.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/handler17.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/handler18.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,12 @@
1
+ import{createReadStream as N}from"node:fs";import{open as De,stat as x,readdir as A,realpath as X,readFile as y,mkdir as C,writeFile as ce,appendFile as We}from"node:fs/promises";import{l as qe}from"./admin-token-BKmc3AUm.mjs";import{u as He}from"./admin-url-Ca-KI3d_.mjs";import{join as m,resolve as L,basename as p,dirname as le,relative as Ye,sep as Ke}from"node:path";import{createInterface as j}from"node:readline";import Ge from"adm-zip";import{e as de}from"./path-containment-CcTCKfzV.mjs";import{Transform as Xe}from"node:stream";import{createInflateRaw as Ze,crc32 as Qe}from"node:zlib";import{LunoraError as f}from"@lunora/errors";import{parse as et}from"csv-parse/sync";import{parse as ue}from"csv-parse";import{STORAGE_UPLOAD_MAX_BODY_BYTES as tt}from"@lunora/runtime";import{n as z,e as rt,t as nt}from"./shared-Ce9bKz5c.mjs";import{createHash as ot}from"node:crypto";const it=67324752,E=30,st=26,at=28,Z=0,ct=8,lt=async(e,t)=>{const r=await De(e,"r");try{const n=Buffer.alloc(E),{bytesRead:o}=await r.read(n,0,E,t);if(o<E||n.readUInt32LE(0)!==it)throw new Error(`${e}: no local file header at offset ${String(t)} — the archive is truncated or corrupt`);return t+E+n.readUInt16LE(st)+n.readUInt16LE(at)}finally{await r.close()}},Q=e=>{let t=0;return new Xe({flush(r){if(t===e.header.crc){r();return}r(new Error(`${e.entryName} failed its CRC check — the archive is corrupt or truncated (expected ${String(e.header.crc)}, read ${String(t)})`))},transform(r,n,o){t=Qe(r,t),o(void 0,r)}})},dt=async(e,t)=>{const{compressedSize:r,encrypted:n,method:o,offset:i}=t.header;if(n)throw new Error(`${t.entryName} is encrypted — decrypt the archive before importing`);if(o!==Z&&o!==ct)throw new Error(`${t.entryName} uses unsupported compression method ${String(o)} — re-create the archive with standard deflate`);if(r===0){if(t.header.size>0||t.header.crc!==0)throw new Error(`${t.entryName} declares 0 compressed bytes but ${String(t.header.size)} uncompressed with CRC ${String(t.header.crc)} — the archive is corrupt`);return}const s=await lt(e,i),a=N(e,{end:s+r-1,start:s});if(o===Z){const d=Q(t);return a.on("error",u=>d.destroy(u)),a.pipe(d)}const c=Ze(),l=Q(t);return a.on("error",d=>c.destroy(d)),c.on("error",d=>l.destroy(d)),a.pipe(c).pipe(l)},S="_storage",fe=e=>e.startsWith("_"),ut=e=>{for(const t of e.getEntries()){const r=t.entryName.replaceAll("\\","/").split("/");if(r.length>=2&&r[r.length-2]==="_storage")return r.slice(0,-1).join("/")}return"_storage"},ft=async e=>{const t=await x(e).catch(()=>{});if(t?.isDirectory())return{kind:"directory",root:e};if(t?.isFile()&&e.toLowerCase().endsWith(".zip")){const r=new Ge(e);return{kind:"zip",storagePrefix:ut(r),zip:r,zipPath:e}}},gt=async e=>{const t=[];for(const r of await A(e,{withFileTypes:!0})){if(!r.isDirectory())continue;const n=m(e,r.name,"documents.jsonl");(await x(n).catch(()=>{}))?.isFile()&&t.push({file:n,table:r.name})}return t},ht=e=>{const t=[];for(const r of e.getEntries()){if(r.isDirectory)continue;const n=r.entryName.replaceAll("\\","/"),o=n.split("/");o.length>=2&&o[o.length-1]==="documents.jsonl"&&t.push({file:n,table:o[o.length-2]})}return t},pt=async e=>{const t=e.kind==="directory"?await gt(e.root):ht(e.zip);return t.length>0?t.toSorted((r,n)=>r.table.localeCompare(n.table)):void 0},P=async function*(e,t){if(e.kind==="directory"){for await(const i of j({crlfDelay:Number.POSITIVE_INFINITY,input:N(t.file,{encoding:"utf8"})}))yield i;return}const r=e.zip.getEntry(t.file);if(r===null)throw new Error(`missing ${t.file} in archive`);const n=await dt(e.zipPath,r);if(n===void 0)return;const o=j({crlfDelay:Number.POSITIVE_INFINITY,input:n});try{for await(const i of o)yield i}finally{o.close(),n.destroy()}},mt=async(e,t)=>{if(e.kind==="directory"){const n=await X(m(e.root,"_storage")),o=await X(L(n,t)).catch(()=>{});if(o===void 0||!de(n,o))throw new Error(`blob ${t} resolves outside the snapshot's _storage directory`);return y(o)}const r=e.zip.readFile(`${e.storagePrefix}/${t}`);if(r===null)throw new Error(`missing blob ${t} in archive`);return Buffer.from(r)},$t=e=>{const t={conflicts:0,errors:[],inserted:{},received:0,warnings:[]};let r=[],n=0;const o=s=>{for(const[a,c]of Object.entries(s.inserted??{}))t.inserted[a]=(t.inserted[a]??0)+c;t.errors.push(...s.errors??[]),t.conflicts+=s.conflicts??0,t.received+=s.received??0;for(const a of s.warnings??[])t.warnings.includes(a)||t.warnings.push(a)},i=async()=>{if(r.length===0)return;const s=r.join(`
2
+ `);r=[],n=0;const a=await e.fetchImpl(e.requestUrl,{body:s,headers:{authorization:`Bearer ${e.token}`,"content-type":"application/x-ndjson"},method:"POST"});if(!a.ok){const c=await a.text().catch(()=>"<no body>");throw new f("INTERNAL",`import batch failed (HTTP ${String(a.status)}): ${c}`)}o(await a.json())};return{flush:i,push:async s=>{const a=Buffer.byteLength(s)+1;r.length>0&&n+a>e.maxBatchBytes&&await i(),r.push(s),n+=a,r.length>=e.batchSize&&await i()},totals:t}},ge=(e,t,r,n)=>{const o=[],i=[];let s=0;const a=d=>n?.[r]?.includes(d)===!0,c=(d,u,g=!1)=>{if(Array.isArray(d))return d.map(h=>c(h,u,g));if(d!==null&&typeof d=="object"){const h=d;if(typeof h.$storage=="string"){const b=h.$storage,w=t.get(b);return w===void 0?(i.push({column:u,storageId:b,table:r}),d):(s+=1,w)}return Object.fromEntries(Object.entries(h).map(([b,w])=>[b,c(w,u)]))}return typeof d=="string"&&t.has(d)?a(u)?(s+=1,t.get(d)??d):(o.push({column:u,storageId:d,table:r}),d):(g&&typeof d=="string"&&d.length>0&&a(u)&&n!==void 0&&i.push({column:u,storageId:d,table:r}),d)},l=Object.fromEntries(Object.entries(e).map(([d,u])=>[d,c(u,d,!0)]));return{ambiguous:o,document:l,rewritten:s,unmigrated:i}},wt=e=>{const{remapDocument:t,report:r,storageColumns:n,storageIdMap:o,table:i}=e,s=(c,l)=>{let d;try{d=JSON.parse(c)}catch(u){const g=u instanceof Error?u.message:String(u);throw new f("INTERNAL",`invalid JSON on line ${String(l)}: ${g}`,{cause:u})}return JSON.stringify({doc:d,table:i})},a=(c,l)=>{let d;try{d=JSON.parse(c)}catch(u){throw new f("INTERNAL",`line ${String(l)}: import envelope is not valid JSON — ${u instanceof Error?u.message:String(u)}`,{cause:u})}if(typeof d.table!="string")throw new f("INTERNAL",`line ${String(l)}: import envelope is missing a string \`table\``);if(d.doc!==null&&typeof d.doc=="object"&&!Array.isArray(d.doc)){let u=d.doc;if(o!==void 0){const g=ge(u,o,d.table,n);u=g.document,r.rewritten+=g.rewritten,r.ambiguous.push(...g.ambiguous),r.unmigrated.push(...g.unmigrated)}d.doc=t===void 0?u:t(u,d.table)}return JSON.stringify(d)};return(c,l)=>{const d=c.trim();if(d.length!==0)return i!==void 0?s(d,l):o===void 0&&t===void 0?d:a(d,l)}},he=async(e,t,r,n)=>{const o=await n(e).catch(()=>{});if(o===void 0)throw new f("INTERNAL",`${e} is not a readable directory`);const i=new Map;for(const[l,d]of Object.entries(t?.tables??{}))d.file!==void 0&&i.set(p(d.file),l);const s=o.filter(l=>l.isFile()&&r.matches(l.name)&&!r.authFiles.has(l.name)).map(l=>({file:m(e,l.name),table:i.get(l.name)??r.tableNameOf(l.name)}));if(s.length===0)throw new f("INTERNAL",`${e} ${r.emptyMessage}`);const a=new Set(s.map(l=>p(l.file))),c=[...i].filter(([l])=>!a.has(l));if(c.length>0)throw new f("INTERNAL",`${e}: the mapping names ${String(c.length)} file(s) that are not importable from this directory — ${c.map(([l,d])=>`\`${l}\` (table \`${d}\`)`).join(", ")}. Check the name and that the file is one this source reads.`);return s.toSorted((l,d)=>l.table.localeCompare(d.table))},pe=async function*(e,t,r,n){for(const o of e){r.has(o.table)||r.set(o.table,0),t.info(`reading ${p(o.file)} → ${o.table}`);for await(const i of n(o))r.set(o.table,(r.get(o.table)??0)+1),yield`${JSON.stringify({doc:i,table:o.table})}
3
+ `}},me=["timestamp-ms","timestamp-iso","json","bytea-base64","int8-string","number","boolean","text-array"],yt=e=>me.includes(e),bt=/^\\x([\dA-Fa-f]*)$/,ee=/^[+-]?\d+$/,$e=/[+-]\d{2}$/,we=/(?:Z|[+-]\d{2}:\d{2})$/i,ye=/^\+/,vt=/e/i,Nt=/e/i,St=e=>{const[t="0",r="0"]=e.split(Nt),n=Number(r),o=t.startsWith("-"),[i="0",s=""]=(o?t.slice(1):t).replace(ye,"").split("."),a=`${i}${s}`,c=i.length+n;let l;return c<=0?l=`0.${"0".repeat(-c)}${a}`:c>=a.length?l=`${a}${"0".repeat(c-a.length)}`:l=`${a.slice(0,c)}.${a.slice(c)}`,o?`-${l}`:l},Tt=/^0+(?=\d)/,te=e=>{const t=(vt.test(e.trim())?St(e.trim()):e.trim()).replace(ye,""),r=t.startsWith("-"),[n="0",o=""]=(r?t.slice(1):t).split("."),i=n.replace(Tt,"");let s=o.length;for(;s>0&&o[s-1]==="0";)s-=1;const a=o.slice(0,s),c=a.length>0?`${i}.${a}`:i;return r&&Number(c)!==0?`-${c}`:c},$=(e,t,r,n)=>{throw new f("INTERNAL",`column \`${e}\`: cannot reshape ${JSON.stringify(r)} as \`${t}\` — ${n}`)},re=(e,t,r)=>{const n=r.includes("T")?r:r.replace(" ","T"),o=$e.test(n)?`${n}:00`:n,i=we.test(o)?o:`${o}Z`,s=Date.parse(i);return Number.isNaN(s)&&$(e,t,r,"not a date Postgres or ISO-8601 syntax can express"),s},It=(e,t)=>{(!t.startsWith("{")||!t.endsWith("}"))&&$(e,"text-array",t,"not a Postgres array literal (expected `{…}`)");const r=t.slice(1,-1);if(r.length===0)return[];r.includes("{")&&$(e,"text-array",t,"nested arrays are not supported — map the column to `json` instead");const n=[];let o="",i=!1,s=!1,a=!1;const c=()=>{n.push(!s&&o==="NULL"?null:o),o="",s=!1};for(const l of r)a?(o+=l,a=!1):l==="\\"?a=!0:l==='"'?(i=!i,s=!0):l===","&&!i?c():o+=l;return c(),n},be=(e,t,r)=>{if(r===null)return null;switch(t){case"boolean":return["1","t","TRUE","true"].includes(r)?!0:["0","f","FALSE","false"].includes(r)?!1:$(e,t,r,"not a Postgres boolean literal");case"bytea-base64":{const n=bt.exec(r);if(n===null)return $(e,t,r,"not `bytea` hex output (expected a leading `\\x`) — set `bytea_output = 'hex'` before dumping");const o=n[1];return o.length%2!==0?$(e,t,r,"has an odd number of hex digits, so the dump is truncated — re-export the column"):Buffer.from(o,"hex").toString("base64")}case"int8-string":return ee.test(r)?r:$(e,t,r,"not an integer");case"json":try{return JSON.parse(r)}catch(n){return $(e,t,r,`invalid JSON — ${n instanceof Error?n.message:String(n)}`)}case"number":{const n=Number(r);if(r.trim().length===0||!Number.isFinite(n))return $(e,t,r,"not a finite number");if(ee.test(r)){if(!Number.isSafeInteger(n))return $(e,t,r,"exceeds Number.MAX_SAFE_INTEGER — map this column to `int8-string` to keep it lossless")}else if(te(String(n))!==te(r))return $(e,t,r,"has more precision than a JS number holds — map this column to `int8-string` or `json` to keep it lossless");return n}case"text-array":return It(e,r);case"timestamp-iso":{re(e,t,r);const n=r.includes("T")?r:r.replace(" ","T"),o=$e.test(n)?`${n}:00`:n;return we.test(o)?o:`${o}Z`}case"timestamp-ms":return re(e,t,r);default:return r}},Et="auth.",kt=new Set(["confirmation_token","email_change_token_current","email_change_token_new","encrypted_password","password","password_hash","passwordhash","reauthentication_token","recovery_token","salt"]),xt=String.raw`\N`,ve=(e,t)=>t.header?e:!t.quoting&&e.length===0||e===xt?null:e,At=e=>new Set([e?.auth?.file,e?.auth?.identitiesFile].filter(t=>t!==void 0).map(t=>p(t))),Rt=async(e,t)=>he(e,t,{authFiles:At(t),emptyMessage:"holds no .csv files — export each table with `COPY <table> TO STDOUT WITH CSV HEADER` first",matches:r=>r.toLowerCase().endsWith(".csv")&&!r.toLowerCase().startsWith(Et),tableNameOf:r=>p(r,".csv")},async r=>A(r,{withFileTypes:!0})),Ot=(e,t,r)=>{const n=t?.idColumn??"id",o=t?.types??{},i={};let s=!1;for(const[a,c]of Object.entries(e)){if(kt.has(a.toLowerCase()))throw new f("INTERNAL",`${r}.${a} is credential material — this looks like an auth dump being imported as a table. Name it under \`auth\` in the mapping instead; passwords are never migrated.`);const l=o[a],d=l===void 0?c:be(a,l,c);if(a===n){if(c===null)throw new f("INTERNAL",`id column \`${n}\` is NULL — every row needs an id to preserve`);i._id=c,s=!0}else{if(a==="_id")throw new f("INTERNAL",`${r}: source column \`_id\` collides with the reserved id field. Rename it in the source, or map it via \`tables.${r}.idColumn\` if it IS the id.`);i[a]=d}}if(!s)throw new f("INTERNAL",`${r}: no \`${n}\` column to preserve as the id (columns present: ${Object.keys(e).join(", ")}). Set \`tables.${r}.idColumn\` in the mapping.`);return i},Lt=async function*(e,t){const r=t?.tables?.[e.table],n=N(e.file).pipe(ue({cast:ve,columns:!0,relaxColumnCountLess:!1,skipEmptyLines:!0}));let o=0;const i=n[Symbol.asyncIterator]();for(;;){let s,a;try{if(s=await i.next(),s.done===!0)return;o+=1,a=Ot(s.value,r,e.table)}catch(c){throw new f("INTERNAL",`${p(e.file)} row ${String(o+1)}: ${c instanceof Error?c.message:String(c)}`,{cause:c})}yield a}},jt=async function*(e,t,r,n,o){yield*Te("supabase",o,t,r,n),yield*pe(e,r,n,i=>Lt(i,t))},_t=/^\d+$/,Ct=/[+-]\d{2}$/,_=e=>{if(e==null)return;if(typeof e=="number")return e;const t=Number(e);if(Number.isFinite(t)&&_t.test(e))return t;const r=e.includes("T")?e:e.replace(" ","T"),n=Date.parse(Ct.test(r)?`${r}:00`:r);return Number.isNaN(n)?void 0:n},Ne=e=>{if(typeof e=="string")try{const t=JSON.parse(e);return t!==null&&typeof t=="object"?t:void 0}catch{return}return e!==null&&typeof e=="object"?e:void 0},zt=e=>{const t=Ne(e);if(t!==void 0){for(const r of["name","full_name","user_name","preferred_username"])if(typeof t[r]=="string"&&t[r].length>0)return t[r]}},Pt=e=>{const t=Ne(e);if(t!==void 0){for(const r of["avatar_url","picture"])if(typeof t[r]=="string"&&t[r].length>0)return t[r]}},Ut=(e,t)=>{const{id:r}=e;if(typeof r!="string"||r.length===0)throw new f("INTERNAL","auth row is missing `id` — every user needs an id to preserve");const n=e.raw_user_meta_data,o={_id:r,email:e.email??null,emailVerified:typeof e.email_confirmed_at=="string"&&e.email_confirmed_at.length>0,id:r},i=zt(n),s=Pt(n),a=_(e.created_at),c=_(e.updated_at);return i!==void 0&&(o.name=i),s!==void 0&&(o.image=s),a!==void 0&&(o.createdAt=a),c!==void 0&&(o.updatedAt=c),{accounts:t.map(l=>{const d=typeof l.provider=="string"?l.provider:"unknown",u=typeof l.provider_id=="string"?l.provider_id:r,g=`${r}:${d}:${u}`;return{_id:g,accountId:u,id:g,providerId:d,userId:r}}),user:o}},Jt=e=>{const t=e.localId;if(typeof t!="string"||t.length===0)throw new f("INTERNAL","auth row is missing `localId` — every user needs an id to preserve");const r={_id:t,email:e.email??null,emailVerified:e.emailVerified===!0,id:t},n=_(e.createdAt);return typeof e.displayName=="string"&&(r.name=e.displayName),typeof e.photoUrl=="string"&&(r.image=e.photoUrl),n!==void 0&&(r.createdAt=n),{accounts:(e.providerUserInfo??[]).filter(o=>typeof o.providerId=="string"&&o.providerId!=="password").map(o=>{const i=o.providerId,s=o.rawId??o.federatedId??t,a=`${t}:${i}:${s}`;return{_id:a,accountId:s,id:a,providerId:i,userId:t}}),user:r}},Ft=(e,t)=>{const r=new Map,n=[],o=[];for(const{accounts:i,user:s}of e){const a=typeof s.email=="string"?s.email.toLowerCase():void 0;if(a!==void 0&&a.length>0){const c=r.get(a);c===void 0?r.set(a,String(s._id)):n.push(`${a} (ids ${c} and ${String(s._id)})`)}o.push(`${JSON.stringify({doc:s,table:"user"})}
4
+ `),t.set("user",(t.get("user")??0)+1);for(const c of i)o.push(`${JSON.stringify({doc:c,table:"account"})}
5
+ `),t.set("account",(t.get("account")??0)+1)}if(n.length>0)throw new f("INTERNAL",`auth import found ${String(n.length)} duplicate email(s), which would merge distinct users: ${n.slice(0,10).join("; ")}${n.length>10?" …":""}`);return o},U=(e,t)=>m(e,p(t)),Se=async e=>{const t=await y(e,"utf8");return et(t,{cast:ve,columns:!0,skipEmptyLines:!0})},Vt=async(e,t)=>{const r=new Map;if(t===void 0)return r;for(const n of await Se(U(e,t))){const o=n.user_id;typeof o=="string"&&r.set(o,[...r.get(o)??[],n])}return r},Mt=async(e,t)=>{const r=t.auth?.file;if(r===void 0)return[];const n=await Se(U(e,r)),o=await Vt(e,t.auth?.identitiesFile);return n.map(i=>Ut(i,o.get(i.id??"")??[]))},Bt=async(e,t)=>{const r=t.auth?.file;if(r===void 0)return[];const n=U(e,r);let o;try{o=JSON.parse(await y(n,"utf8"))}catch(s){throw new f("INTERNAL",`${p(n)}: invalid JSON — ${s instanceof Error?s.message:String(s)}`,{cause:s})}const i=Array.isArray(o)?o:o.users??[];if(!Array.isArray(i))throw new f("INTERNAL",`${p(n)}: expected \`{ users: [...] }\` from \`firebase auth:export\`, or a bare array`);return i.map(s=>Jt(s))},Te=async function*(e,t,r,n,o){if(r?.auth?.file===void 0)return;const i=e==="supabase"?await Mt(t,r):await Bt(t,r);n.info(`auth: ${String(i.length)} user(s) — passwords are never migrated; users reset via "forgot password"`);for(const s of Ft(i,o))yield s},ne=/\.(?:nd)?json$/i,Ie=e=>{const t=e.split("/").filter(r=>r.length>0);return t[t.length-1]??e},Dt=e=>{const t=Number(e.seconds??0),r=e.nanos??0;return Number.isFinite(t)&&Number.isFinite(r)?t*1e3+Math.floor(r/1e6):Number.NaN},Wt=(e,t)=>{const r=Array.isArray(e)?e:e.data;if(!Array.isArray(r))throw new f("INTERNAL",`${t}: \`bytesValue\` ${JSON.stringify(e)} is neither base64 nor a byte array`);return Buffer.from(r).toString("base64")},qt=(e,t)=>{const r=typeof e=="string"?Date.parse(e):Dt(e);if(Number.isNaN(r))throw new f("INTERNAL",`${t}: \`timestampValue\` ${JSON.stringify(e)} is neither an RFC-3339 string nor a \`{ seconds, nanos }\` protobuf timestamp`);return r},Ht=(e,t)=>typeof e=="string"?e:Wt(e,t),Ee=(e,t)=>{if("nullValue"in e)return null;if(e.stringValue!==void 0)return e.stringValue;if(e.booleanValue!==void 0)return e.booleanValue;if(e.integerValue!==void 0){const r=String(e.integerValue),n=Number(r);return Number.isSafeInteger(n)?n:r}if(e.doubleValue!==void 0)return Number(e.doubleValue);if(e.timestampValue!==void 0)return qt(e.timestampValue,t);if(e.bytesValue!==void 0)return Ht(e.bytesValue,t);if(e.geoPointValue!==void 0)return{latitude:e.geoPointValue.latitude??0,longitude:e.geoPointValue.longitude??0};if(e.referenceValue!==void 0)return Ie(e.referenceValue);if(e.arrayValue!==void 0)return(e.arrayValue.values??[]).map((r,n)=>Ee(r,`${t}[${String(n)}]`));if(e.mapValue!==void 0)return ke(e.mapValue.fields??{},t);throw new f("INTERNAL",`${t}: unrecognised Firestore value ${JSON.stringify(e).slice(0,80)}`)},Yt=new Set(["createTime","fields","name","readTime","updateTime"]),Kt=e=>{if(typeof e!="object"||e===null||Array.isArray(e))return!1;const t=Object.keys(e);return t.length===1&&t[0]?.endsWith("Value")===!0},Gt=e=>{if(typeof e.name=="string")return!0;const{fields:t}=e;return typeof t!="object"||t===null?!1:Object.keys(e).every(r=>Yt.has(r))&&!Kt(t)},ke=(e,t)=>Object.fromEntries(Object.entries(e).map(([r,n])=>[r,Ee(n,`${t}.${r}`)])),Xt=(e,t,r,n)=>{const o=Gt(e),i=ke(o?e.fields??{}:e,n),s=e.name??e.__name__,a=typeof s=="string"?Ie(s):t;if(a===void 0)throw new f("INTERNAL",`${n}: no document id — expected a \`name\`/\`__name__\` resource path, or a document keyed by its id`);const c=r?.types??{};for(const[l,d]of Object.entries(c)){const u=i[l];if(u!==void 0){if(u!==null&&typeof u!="boolean"&&typeof u!="number"&&typeof u!="string")throw new f("INTERNAL",`${n}.${l}: a \`${d}\` reshape needs a scalar, but this field decoded to an object or array`);i[l]=be(l,d,u===null?null:String(u))}}return{...i,_id:a}},Zt=async(e,t)=>he(e,t,{authFiles:new Set(t?.auth?.file===void 0?[]:[p(t.auth.file)]),emptyMessage:"holds no .json/.ndjson collection files",matches:r=>ne.test(r),tableNameOf:r=>r.replace(ne,"")},async r=>A(r,{withFileTypes:!0})),Qt=async function*(e){const t=j({crlfDelay:Number.POSITIVE_INFINITY,input:N(e,"utf8")});let r=0;try{for await(const n of t){r+=1;const o=n.trim();if(o.length!==0)try{yield{raw:JSON.parse(o)}}catch(i){throw new f("INTERNAL",`${p(e)} line ${String(r)}: invalid JSON — ${i instanceof Error?i.message:String(i)}`,{cause:i})}}}finally{t.close()}},er=async e=>{const t=await y(e,"utf8");let r;try{r=JSON.parse(t)}catch(n){throw new f("INTERNAL",`${p(e)}: invalid JSON — ${n instanceof Error?n.message:String(n)}`,{cause:n})}if(r!==null&&typeof r=="object"&&Array.isArray(r.documents))return r.documents.map(n=>({raw:n}));if(Array.isArray(r))return r.map(n=>({raw:n}));if(r!==null&&typeof r=="object")return Object.entries(r).map(([n,o])=>({fallbackId:n,raw:o}));throw new f("INTERNAL",`${p(e)}: expected an object, an array, or \`{ documents: [...] }\``)},tr=async function*(e,t){const r=t?.tables?.[e.table],n=e.file.toLowerCase().endsWith(".ndjson")?Qt(e.file):await er(e.file);let o=0;for await(const i of n)yield Xt(i.raw,i.fallbackId,r,`${e.table}[${String(o)}]`),o+=1},rr=async function*(e,t,r,n,o){yield*Te("firebase",o,t,r,n),yield*pe(e,r,n,i=>tr(i,t))},I=e=>e!==null&&typeof e=="object"&&!Array.isArray(e),J=(e,t)=>{if(!I(e))throw new f("INTERNAL",`${t}: expected a JSON object`);return e},T=(e,t,r)=>{const n=e[t];if(n!==void 0&&typeof n!="string")throw new f("INTERNAL",`${r}: \`${t}\` must be a string`);return n},xe=(e,t,r)=>{const n=e[t];if(n!==void 0&&(!Array.isArray(n)||n.some(o=>typeof o!="string")))throw new f("INTERNAL",`${r}: \`${t}\` must be an array of column names`);return n},nr=(e,t)=>{const r=J(e,t),n=T(r,"file",t),o=T(r,"idColumn",t),i=xe(r,"storageColumns",t),{types:s}=r;if(s!==void 0){if(!I(s))throw new f("INTERNAL",`${t}.types must be an object of column → reshape`);for(const[a,c]of Object.entries(s))if(!yt(c))throw new f("INTERNAL",`${t}.types.${a}: unknown reshape ${JSON.stringify(c)} — expected one of ${me.join(", ")}`)}return{file:n,idColumn:o,storageColumns:i,types:s}},or=(e,t)=>{if(e!==void 0){if(!I(e))throw new f("INTERNAL",`${t}: \`auth\` must be an object`);for(const r of["file","identitiesFile"])T(e,r,`${t}: auth`)}},ir=(e,t)=>{if(e!==void 0){if(!I(e))throw new f("INTERNAL",`${t}: \`tables\` must be an object of table → mapping`);return Object.fromEntries(Object.entries(e).map(([r,n])=>[r,nr(n,`${t}: tables.${r}`)]))}},sr=(e,t)=>{const r=J(e,t),n=T(r,"keyPrefix",t),{auth:o,tables:i}=r;return or(o,t),{auth:o,keyPrefix:n,tables:ir(i,t)}},Ae=e=>m("lunora",`import-${e}.json`),ar=async(e,t,r)=>{const n=Ae(t),o=m(e,n);let i;try{i=await y(o,"utf8")}catch(a){if(a.code==="ENOENT"){r.info(`no ${n} found — every column is copied through untouched (run with --scan to generate one)`);return}throw a}let s;try{s=JSON.parse(i)}catch(a){throw new f("INTERNAL",`${o}: invalid JSON — ${a instanceof Error?a.message:String(a)}`,{cause:a})}return sr(s,o)},cr=8,lr=24*1048576,dr=1e3,ur=/^[\dA-F]{64}$/i,fr=e=>{for(let t=0;t<e.length;t+=1){const r=e.codePointAt(t)??0;if(r<32||r===127)return!1}return!0},gr=/^[\d+/A-Z]{43}=$/i,hr=e=>ur.test(e)?e.toLowerCase():gr.test(e)?Buffer.from(e,"base64").toString("hex"):void 0,pr=(e,t)=>{const r=JSON.parse(e),n=r._id;if(typeof n!="string"||n.length===0||n.includes("/")||n.includes("\\"))throw new f("INTERNAL",`${t}: \`_id\` must be a path-free non-empty string`);if(typeof r.sha256!="string")throw new f("INTERNAL",`${t}: \`sha256\` is missing — re-export with \`npx convex export --include-file-storage\``);const o=hr(r.sha256);if(o===void 0)throw new f("INTERNAL",`${t}: \`sha256\` is neither base16 nor base64 SHA-256 (${r.sha256})`);if(typeof r.size!="number"||!Number.isInteger(r.size)||r.size<0)throw new f("INTERNAL",`${t}: \`size\` must be a non-negative integer`);if(r.contentType!==void 0&&(typeof r.contentType!="string"||!fr(r.contentType)))throw new f("INTERNAL",`${t}: \`contentType\` must be a string with no control characters`);return{contentType:typeof r.contentType=="string"?r.contentType:void 0,id:n,sha256:o,size:r.size}},F=async(e,t,r)=>{const n=[];try{let o=0;for await(const i of P(e,t)){const s=i.trim();o+=1,s.length>0&&n.push(pr(s,`_storage/documents.jsonl line ${String(o)}`))}}catch(o){const i=o instanceof Error?o.message:String(o);throw r.error(`failed to read _storage metadata: ${i}`),o}return n},Re=tt,R=e=>e.bucket===void 0?"":`&bucket=${encodeURIComponent(e.bucket)}`,V=async(e,t)=>{const r=[];let n;do{const o=`${e.baseUrl}${z}?prefix=${encodeURIComponent(t)}&limit=${String(dr)}${n===void 0?"":`&cursor=${encodeURIComponent(n)}`}${R(e)}`,i=await e.fetchImpl(o,{headers:{authorization:`Bearer ${e.token}`},method:"GET"});if(!i.ok){const c=await i.text().catch(()=>"<no body>");throw new f("INTERNAL",`storage list failed (HTTP ${String(i.status)}): ${c}`)}const s=await i.json();r.push(...s.objects??[]);const a=s.truncated===!0?s.cursor:void 0;if(a!==void 0&&a===n)throw new f("INTERNAL","storage list did not advance its cursor — refusing to page forever");n=a}while(n!==void 0);return r},mr=async(e,t,r,n)=>{const o=`${e.baseUrl}${z}?key=${encodeURIComponent(t)}&expectedSha256=${n.sha256}&expectedSize=${String(n.size)}${R(e)}`,i=await e.fetchImpl(o,{body:new Uint8Array(r),headers:{authorization:`Bearer ${e.token}`,"content-type":n.contentType??"application/octet-stream"},method:"PUT"});if(!i.ok){const a=await i.text().catch(()=>"<no body>");throw new f("INTERNAL",`blob upload failed (HTTP ${String(i.status)}): ${a}`)}const s=await i.json();if(s.sha256!==n.sha256)throw new f("INTERNAL",`blob upload verification failed: expected ${n.sha256}, got ${s.sha256??"none"}`);return t},$r=async(e,t)=>(await e.fetchImpl(`${e.baseUrl}${z}?key=${encodeURIComponent(t)}${R(e)}`,{headers:{authorization:`Bearer ${e.token}`},method:"DELETE"}).catch(()=>{}))?.ok===!0,wr=async(e,t,r,n,o)=>{const i=`${e.baseUrl}${rt}?key=${encodeURIComponent(t)}&method=PUT&contentType=${encodeURIComponent(n.contentType??"application/octet-stream")}${R(e)}`,s=await e.fetchImpl(i,{headers:{authorization:`Bearer ${e.token}`},method:"GET"});if(!s.ok){const h=await s.text().catch(()=>"<no body>");throw new f("INTERNAL",`blob ${t} is ${String(n.size)} bytes, above the ${String(Re)}-byte verified-upload cap, and no signed PUT URL could be minted (HTTP ${String(s.status)}): ${h}`)}const{url:a}=await s.json(),c=await e.fetchImpl(a,{body:new Uint8Array(r),headers:{"content-type":n.contentType??"application/octet-stream"},method:"PUT"});if(!c.ok){const h=await c.text().catch(()=>"<no body>");throw new f("INTERNAL",`signed PUT failed (HTTP ${String(c.status)}): ${h}`)}const l=(await V(e,t)).find(h=>h.key===t);if(l===void 0)throw new f("INTERNAL",`post-upload verification failed: blob not found at key ${t}`);const d=l.size!==void 0&&l.size!==n.size,u=l.sha256!==void 0&&l.sha256.toLowerCase()!==n.sha256;if(d||u){const h=await $r(e,t);throw new f("INTERNAL",`post-upload verification failed: expected sha256=${n.sha256} size=${String(n.size)}, got sha256=${l.sha256??"none"} size=${String(l.size??"none")}${h?" (the object was removed)":` — AND the object could not be removed: delete ${t} by hand before re-running, or the next run will treat it as already migrated`}`)}const g=[l.size===void 0?"size":void 0,l.sha256===void 0?"sha256":void 0].filter(Boolean);return g.length>0&&o.warn(`blob ${t} went through the signed-PUT path and the host reports no ${g.join(" or ")} for it — that much of the write is unverified`),t},Oe=async(e,t,r,n,o)=>{if(r.length!==n.size)throw new f("INTERNAL",`blob ${n.id} is ${String(r.length)} bytes on disk but the export declares ${String(n.size)}`);return r.length<=Re?mr(e,t,r,n):wr(e,t,r,n,o)},yr=e=>{const t=[];let r=[],n=0;for(const o of e)r.length>0&&(r.length>=cr||n+o.size>lr)&&(t.push(r),r=[],n=0),r.push(o),n+=o.size;return r.length>0&&t.push(r),t},br=async(e,t,r,n,o)=>{const i=await F(t,r,o),s=new Map,a=await V(e,n),c=new Map(a.map(u=>[u.key,u])),l=[];for(const u of i){const g=`${n}${u.sha256}`;c.get(g)?.size===u.size?s.set(u.id,g):l.push(u)}o.info(`migrating ${String(l.length)} storage blobs${s.size>0?` (${String(s.size)} already present)`:""}...`);const d=async u=>{try{const g=await mt(t,u.id);s.set(u.id,await Oe(e,`${n}${u.sha256}`,g,u,o))}catch(g){const h=g instanceof Error?g.message:String(g);throw o.error(`failed to upload blob ${u.id}: ${h}`),g}};for(const u of yr(l)){const g=(await Promise.allSettled(u.map(h=>d(h)))).find(h=>h.status==="rejected");if(g!==void 0)throw g.reason}return o.success(`migrated ${String(l.length)} storage blobs`),s};async function*vr(e,t,r){let n=0;for await(const o of P(e,t)){const i=o.trim();if(n+=1,i.length===0)continue;let s;try{s=JSON.parse(i)}catch(a){throw new f("INTERNAL",`${t.table}/documents.jsonl line ${String(n)}: invalid JSON — ${a instanceof Error?a.message:String(a)}`,{cause:a})}r.set(t.table,(r.get(t.table)??0)+1),yield`${JSON.stringify({doc:s,table:t.table})}
6
+ `}}async function*Nr(e,t,r,n,o){for(const i of t){if(fe(i.table)){i.table===S&&!n&&r.warn(`skipping "${S}" — those rows describe stored files, and their blobs were not migrated. Re-run with --with-storage to upload them and rewrite the references.`);continue}o.has(i.table)||o.set(i.table,0),yield*vr(e,i,o)}}const Pn=["firebase","supabase"],Sr=async(e,t,r)=>{if(e.withStorage===!0&&t==="firebase"&&e.storageDir===void 0)return e.logger.error("--with-storage on Firebase needs --storage-dir — download the bucket first with `gcloud storage cp -r gs://<bucket> <dir>`."),{kind:"invalid"};if(e.table!==void 0)return e.logger.error(`--table cannot be combined with --from ${t} — each row's table comes from its source file.`),{kind:"invalid"};const n=await ar(r,t,e.logger),o=Object.values(n?.tables??{}).some(i=>(i.storageColumns??[]).length>0);return e.verify===!0&&e.withStorage!==!0&&o?(e.logger.error("--verify with `storageColumns` declared requires --with-storage — otherwise every storage path stays unmigrated and only row counts would be checked."),{kind:"invalid"}):t==="supabase"?{kind:"supabase",mapping:n,tables:await Rt(e.file,n)}:{collections:await Zt(e.file,n),kind:"firebase",mapping:n}},Tr=async e=>{if(!await x(e.file).then(()=>!0,()=>!1))return!1;for(const[t,r]of[["--scan",e.scan],["--verify",e.verify],["--with-storage",e.withStorage]])if(r===!0)return e.logger.error(`${t} requires a Convex export directory or .zip snapshot — ${e.file} is not one.`),!0;return!1},Ir=async(e,t,r)=>{const n=t.find(i=>i.table===S);if(n===void 0)return r.logger.error("--verify cannot check file references: this export has no `_storage` table, so it was taken without `--include-file-storage`. Re-export with that flag and pass --with-storage, or drop --verify."),!0;const o=await F(e,n,r.logger);return o.length>0?(r.logger.error(`--verify on an export carrying ${String(o.length)} stored file(s) requires --with-storage — otherwise every file reference stays unmigrated and only row counts would be checked.`),!0):!1},Er=async(e,t)=>{if(e.from==="supabase"||e.from==="firebase")return Sr(e,e.from,t);const r=await ft(e.file),n=r===void 0?void 0:await pt(r);return r!==void 0&&n===void 0?(e.logger.error(`${e.file} is a ${r.kind==="zip"?".zip":"directory"} but holds no <table>/documents.jsonl — expected a \`npx convex export --path\` snapshot, or pass an NDJSON file.`),{kind:"invalid"}):r===void 0||n===void 0?await Tr(e)?{kind:"invalid"}:{kind:"ndjson"}:e.table!==void 0?(e.logger.error("--table cannot be combined with a Convex export directory — each row's table comes from its source directory."),{kind:"invalid"}):e.verify===!0&&e.withStorage!==!0&&await Ir(r,n,e)?{kind:"invalid"}:{kind:"convex",snapshot:r,tables:n}},k=m("lunora","import-convex.json"),kr=(e,t)=>{const r=J(e,t),n=T(r,"keyPrefix",t),o=r.storageColumns;if(o!==void 0){if(!I(o))throw new f("INTERNAL",`${t}: \`storageColumns\` must be an object of table → column names`);for(const i of Object.keys(o))xe(o,i,`${t}: storageColumns`)}return{keyPrefix:n,storageColumns:o}},xr=async(e,t)=>{const r=m(e,k);let n;try{n=await y(r,"utf8")}catch(i){if(i.code==="ENOENT"){t.info(`no ${k} found — rewriting only self-describing { $storage } refs (run with --scan to generate one)`);return}throw i}let o;try{o=JSON.parse(n)}catch(i){throw new f("INTERNAL",`${r}: invalid JSON — ${i instanceof Error?i.message:String(i)}`,{cause:i})}return kr(o,r)},Ar=(e,t,r)=>{try{return JSON.parse(e)}catch(n){throw new f("INTERNAL",`${t}/documents.jsonl line ${String(r)}: invalid JSON — ${n instanceof Error?n.message:String(n)}`,{cause:n})}},Rr=async(e,t,r)=>{const n=new Map([...r].map(s=>[s,s])),o=[];let i=0;for await(const s of P(e,t)){const a=s.trim();if(i+=1,a.length===0)continue;const{ambiguous:c}=ge(Ar(a,t.table,i),n,t.table);for(const{column:l}of c)o.includes(l)||o.push(l)}return o},Or=async(e,t,r)=>{const n={};for(const o of t){if(fe(o.table))continue;const i=await Rr(e,o,r);i.length>0&&(n[o.table]=i)}return n},Lr=async(e,t,r)=>{const n=m(t,k),o=`${JSON.stringify(e,void 0,4)}
7
+ `;await C(m(t,"lunora"),{recursive:!0});try{await ce(n,o,{encoding:"utf8",flag:"wx"}),r.success(`wrote candidate mapping to ${n} — review it, then re-run without --scan`)}catch(i){if(i.code!=="EEXIST")throw i;r.warn(`${n} already exists — leaving it untouched. Candidate mapping:`),r.info(o)}},jr=async(e,t,r,n)=>{const o=t.find(c=>c.table===S);if(o===void 0){n.error("no `_storage` table in this export — re-export with `npx convex export --include-file-storage`");return}const i=await F(e,o,n),s=new Set(i.map(c=>c.id));n.info(`found ${String(s.size)} storage ids`);const a={keyPrefix:"",storageColumns:await Or(e,t,s)};return await Lr(a,r,n),a},v=20,_r=(e,t,r)=>{let n=0;if(r.conflicts===0)for(const[o,i]of t){const s=r.inserted[o]??0;s<i&&(n+=1,e.error(`verify: ${o} inserted ${String(s)} of ${String(i)} source rows (${String(i-s)} missing)`))}else{const o=[...t.values()].reduce((s,a)=>s+a,0),i=Object.values(r.inserted).reduce((s,a)=>s+a,0)+r.conflicts;i<o&&(n+=1,e.error(`verify: ${String(i)} of ${String(o)} source rows accounted for across all tables (${String(o-i)} missing; ${String(r.conflicts)} already present)`))}return n>0?e.error(`verify: ${String(n)} row-parity check(s) failed`):e.success("verify: all source rows accounted for"),n},oe=(e,t,r)=>{const n=new Set;for(const o of t){const i=`${o.table} ${o.column} ${o.storageId}`;n.has(i)||(n.add(i),n.size<=v&&e.warn(r(o)))}n.size>v&&e.warn(`… and ${String(n.size-v)} more`)},Cr=(e,t,r)=>(e.info(`storage refs: ${String(t.rewritten)} rewritten, ${String(t.unmigrated.length)} unmigrated, ${String(t.ambiguous.length)} ambiguous`),oe(e,t.unmigrated,n=>`unmigrated storage reference ${n.table}.${n.column}: ${n.storageId} has no exported blob — re-export with \`npx convex export --include-file-storage\``),oe(e,t.ambiguous,n=>`unrewritten storage id in ${n.table}.${n.column}: ${n.storageId} — if that column holds storage references, add it to ${k} and re-import`),r&&t.unmigrated.length>0?(e.error(`verify: ${String(t.unmigrated.length)} storage reference(s) resolved to no migrated blob`),!0):!1),zr=(e,t,r)=>{for(const n of[...t].slice(0,v))e.warn(`storage path never transferred: ${n} — left as-is`);return t.size>v&&e.warn(`… and ${String(t.size-v)} more untransferred storage paths`),r&&t.size>0},ie=200,Pr=/^\\x[\dA-Fa-f]*$/,Ur=/^[+-]?\d+$/,Jr=/^[+-]?\d+\.\d+$/,Fr=/^\{.*\}$/,Vr=/^\d{4}-\d{2}-\d{2}[ T]\d{2}:\d{2}:\d{2}/,Mr=[["bytea-base64",e=>Pr.test(e)],["timestamp-ms",e=>Vr.test(e)],[e=>e.some(t=>!Number.isSafeInteger(Number(t)))?"int8-string":void 0,e=>Ur.test(e)],["boolean",e=>e==="f"||e==="t"],["number",e=>Jr.test(e)],[e=>e.every(t=>Fr.test(t))?"text-array":"json",e=>e.startsWith("{")||e.startsWith("[")]],Br=e=>{if(e.length!==0){for(const[t,r]of Mr)if(e.every(n=>r(n)))return typeof t=="function"?t(e):t}},Dr=(e,t)=>{for(const[r,n]of Object.entries(e)){if(n.length===0)continue;const o=t.get(r);o===void 0?t.set(r,[n]):o.push(n)}},Wr=async e=>{const t=new Map,r=N(e).pipe(ue({columns:!0,skipEmptyLines:!0,toLine:ie+1}));let n=0;for await(const i of r)if(Dr(i,t),n+=1,n>=ie)break;r.destroy();const o={};for(const[i,s]of t){const a=Br(s);a!==void 0&&(o[i]=a)}return o},Le=async(e,t,r,n)=>{const o=Ae(r),i=m(t,o),s=`${JSON.stringify(e,void 0,4)}
8
+ `;await C(le(i),{recursive:!0});try{await ce(i,s,{encoding:"utf8",flag:"wx"}),n.success(`wrote candidate mapping to ${i} — review the inferred types, then re-run without --scan`)}catch(a){if(a.code!=="EEXIST")throw a;n.warn(`${i} already exists — leaving it untouched. Candidate mapping:`),n.info(s)}},qr=async(e,t,r)=>{const n={};for(const i of e){const s=await Wr(i.file);r.info(`${p(i.file)} → ${i.table}: ${String(Object.keys(s).length)} column(s) need a reshape`),n[i.table]={file:p(i.file),idColumn:"id",...Object.keys(s).length>0?{types:s}:{}}}const o={keyPrefix:"",tables:n};return await Le(o,t,"supabase",r),o},Hr=async(e,t,r)=>{const n={};for(const i of e)n[i.table]={file:p(i.file),storageColumns:[]};r.info(`found ${String(e.length)} collection(s) — Firestore values are self-describing, so only storage columns need declaring`);const o={keyPrefix:"",tables:n};return await Le(o,t,"firebase",r),o},M=e=>m("lunora",`.import-storage-${e}.ndjson`),Yr=async(e,t,r)=>{const n=new Map;let o;try{o=await y(m(e,M(t)),"utf8")}catch(s){if(s.code==="ENOENT")return n;throw s}let i=0;for(const s of o.split(`
9
+ `)){const a=s.trim();if(a.length!==0)try{const c=JSON.parse(a);typeof c.path=="string"&&typeof c.key=="string"?n.set(c.path,c):i+=1}catch{i+=1}}return n.size>0&&r.info(`resuming: ${String(n.size)} object(s) already transferred${i>0?` (${String(i)} unreadable checkpoint line(s) ignored)`:""}`),n},Kr=async(e,t,r)=>{const n=m(e,M(t));await C(le(n),{recursive:!0}),await We(n,`${JSON.stringify(r)}
10
+ `,"utf8")},je=100,Gr=e=>e.split("/").map(t=>encodeURIComponent(t)).join("/"),Xr=async(e,t,r,n,o)=>{const i=await r(`${e.url}/storage/v1/object/list/${encodeURIComponent(t)}`,{body:JSON.stringify({limit:je,offset:o,prefix:n}),headers:{authorization:`Bearer ${e.serviceKey}`,"content-type":"application/json"},method:"POST"});if(!i.ok){const s=await i.text().catch(()=>"<no body>");throw new f("INTERNAL",`Supabase storage list failed for bucket ${t} (HTTP ${String(i.status)}): ${s}`)}return await i.json()},_e=async(e,t,r,n="")=>{const o=[];let i=0;for(;;){const s=await Xr(e,t,r,n,i);for(const a of s){const c=n===""?a.name:`${n}/${a.name}`;a.id===null||a.id===void 0?o.push(...await _e(e,t,r,c)):o.push({contentType:a.metadata?.mimetype,name:c})}if(s.length<je)return o;i+=s.length}},Zr=async(e,t,r)=>{const n=await t(`${e.url}/storage/v1/bucket`,{headers:{authorization:`Bearer ${e.serviceKey}`},method:"GET"});if(!n.ok){const s=await n.text().catch(()=>"<no body>");throw new f("INTERNAL",`Supabase bucket list failed (HTTP ${String(n.status)}): ${s} — check the project URL and that the key is the service-role key, not the anon key`)}const o=await n.json(),i=[];for(const s of o){const a=await _e(e,s.name,t);r.info(`supabase bucket ${s.name}: ${String(a.length)} object(s)`);for(const c of a){const l=`${s.name}/${c.name}`;i.push({contentType:c.contentType,bytes:async()=>{const d=await t(`${e.url}/storage/v1/object/${encodeURIComponent(s.name)}/${Gr(c.name)}`,{headers:{authorization:`Bearer ${e.serviceKey}`},method:"GET"});if(!d.ok){const u=await d.text().catch(()=>"<no body>");throw new f("INTERNAL",`Supabase download failed for ${l} (HTTP ${String(d.status)}): ${u}`)}if(d.arrayBuffer===void 0)throw new f("INTERNAL","the fetch implementation cannot read response bytes, which the storage transfer requires");return Buffer.from(await d.arrayBuffer())},path:l})}}return i},Qr=async e=>{const t=L(e),r=[],n=async o=>{const i=await A(o,{withFileTypes:!0}).catch(()=>{});if(i===void 0)throw new f("INTERNAL",`${e} is not a readable directory — download the bucket first with \`gcloud storage cp -r gs://<bucket> <dir>\``);for(const s of i){const a=L(o,s.name);if(!de(t,a))throw new f("INTERNAL",`${s.name} resolves outside ${e} — refusing to upload it`);s.isDirectory()?await n(a):s.isFile()&&r.push({bytes:async()=>y(a),path:Ye(t,a).split(Ke).join("/")})}};return await n(t),r},en=async(e,t,r,n,o)=>{const i=await t.bytes(),s=ot("sha256").update(i).digest("hex"),a=`${r.keyPrefix}${s}`;if(n.get(a)?.size!==i.length){const c={contentType:t.contentType,id:t.path,sha256:s,size:i.length};await Oe(e,a,i,c,o)}return await Kr(r.cwd,r.source,{key:a,path:t.path,size:i.length}),a},tn=(e,t)=>{const r=e>500?100:25;return n=>{if(n===e||n%r===0){const o=e===0?100:Math.round(n/e*100);t.info(`transferred ${String(n)}/${String(e)} object(s) (${String(o)}%)`)}}},se=async(e,t,r,n)=>{const o=new Map,i=await Yr(r.cwd,r.source,n),s=await V(e,r.keyPrefix),a=new Map(s.map(d=>[d.key,d]));i.size>0&&s.length===0&&n.warn(`the checkpoint records ${String(i.size)} transferred object(s) but the target holds none under \`${r.keyPrefix}\` — re-transferring (a different deployment, a wiped bucket, or a changed keyPrefix)`);const c=tn(t.length,n);let l=0;n.info(`transferring ${String(t.length)} object(s) to R2...`);for(const d of t){const u=i.get(d.path);if(u!==void 0&&a.has(u.key)){o.set(d.path,u.key),l+=1,c(l);continue}try{const g=await en(e,d,r,a,n);o.set(d.path,g)}catch(g){const h=g instanceof Error?g.message:String(g);throw n.error(`failed transferring ${d.path} after ${String(l)} object(s): ${h}`),n.error(`progress is saved — re-run the same command to continue from here (delete ${M(r.source)} to start over)`),g}l+=1,c(l)}return n.success(`transferred ${String(t.length)} object(s) to R2`),o},ae=/^\/+/,rn=/\/storage\/v1\/object\/(?:public\/|sign\/|authenticated\/)?/,nn=/[#?]/u,on=e=>{const t=new Map(e),r=new Map;for(const[n,o]of e){const i=n.indexOf("/");if(i===-1)continue;const s=n.slice(i+1);s.length===0||e.has(s)||r.set(s,r.has(s)?void 0:o)}for(const[n,o]of r)o!==void 0&&t.set(n,o);return t},sn=e=>{const t=rn.exec(e);if(t===null)return;const r=e.slice(t.index+t[0].length).split(nn)[0]??"";if(r.length!==0)try{return decodeURIComponent(r)}catch{return r}},an=(e,t)=>{const r=t.get(e);if(r!==void 0)return r;const n=e.replace(ae,""),o=t.get(n);if(o!==void 0)return o;const i=sn(e);return i===void 0?void 0:t.get(i)??t.get(i.replace(ae,""))},cn=500,ln=9e5,dn=async e=>{if(e.prod&&e.url===void 0){e.logger.error("--prod requires an explicit --url (refusing to import to the implicit localhost worker)");return}if(e.prod&&e.yes!==!0){e.logger.error("import --prod bulk-writes production. Re-run with --yes to confirm.");return}const t=He(e.url,e.logger,e.cwd);if(t===void 0)return;const{token:r}=qe({cwd:e.cwd??process.cwd(),token:e.token,url:t});if(!r){e.logger.error("admin token required — pass --token, set LUNORA_ADMIN_TOKEN, or add it to .dev.vars (local targets only)");return}try{const o=await x(e.file);if(!o.isFile()&&!o.isDirectory()){e.logger.error(`not a file or directory: ${e.file}`);return}}catch(o){const i=o instanceof Error?o.message:String(o);e.logger.error(`failed to stat ${e.file}: ${i}`);return}const n=e.fetchImpl??globalThis.fetch;if(typeof n!="function")throw new TypeError("no fetch implementation available — pass fetchImpl or run on Node >= 18");return{baseUrl:t,fetchImpl:n,requestUrl:`${t}${nt}`,token:r}},un=(e,t,r)=>({conflicts:e.conflicts,errors:e.errors,inserted:e.inserted,received:e.received,...t===void 0?{}:{storage:{ambiguous:r.ambiguous,blobs:t.size,rewritten:r.rewritten,unmigrated:r.unmigrated}},...e.warnings.length>0?{warnings:e.warnings}:{}}),fn=(e,t,r,n)=>{switch(e.kind){case"convex":return Nr(e.snapshot,e.tables,t.logger,r,n);case"firebase":return rr(e.collections,e.mapping,t.logger,n,t.file);case"supabase":return jt(e.tables,e.mapping,t.logger,n,t.file);default:return N(t.file,{encoding:"utf8"})}},gn=async(e,t,r)=>{switch(e.kind){case"convex":return jr(e.snapshot,e.tables,t,r);case"firebase":return Hr(e.collections,t,r);case"supabase":return qr(e.tables,t,r);default:{r.error("--scan needs a Convex, Supabase, or Firebase source.");return}}},hn=async(e,t,r,n)=>{const o=t.mapping?.keyPrefix??"";if(r.storageDir!==void 0)return se(e,await Qr(r.storageDir),{cwd:n,keyPrefix:o,source:t.kind},r.logger);if(t.kind==="firebase"){r.logger.error("--with-storage needs --storage-dir for a Firebase source: download the bucket first (`gcloud storage cp -r gs://<bucket> ./storage`), then point --storage-dir at it.");return}const i=process.env.SUPABASE_URL,s=process.env.SUPABASE_SERVICE_ROLE_KEY;if(i===void 0||s===void 0){r.logger.error("--with-storage needs SUPABASE_URL and SUPABASE_SERVICE_ROLE_KEY in the environment (the service-role key, not the anon key), or --storage-dir pointing at an already-downloaded bucket.");return}let a=i.length;for(;a>0&&i[a-1]==="/";)a-=1;const c=i.slice(0,a);if(!c.startsWith("https://")){r.logger.error(`SUPABASE_URL must be https:// — refusing to send the service-role key over ${c.split(":")[0]??"an unknown scheme"}.`);return}const l=await Zr({serviceKey:s,url:c},e.fetchImpl,r.logger);return se(e,l,{cwd:n,keyPrefix:o,source:t.kind},r.logger)},pn=(e,t,r,n,o)=>{const i=n.mapping?.tables?.[t]?.storageColumns??[];if(i.length===0)return e;const s={...e};for(const a of i){const c=s[a];if(typeof c!="string"||c.length===0)continue;const l=an(c,r);l===void 0?o.add(`${t}.${a}: ${c}`):s[a]=l}return s},mn=e=>{const t=e.source.kind==="supabase"||e.source.kind==="firebase"?e.source:void 0,{transferredPaths:r}=e,n=r===void 0||t===void 0?void 0:on(r);return wt({remapDocument:n===void 0||t===void 0?void 0:(o,i)=>pn(o,i,n,t,e.unresolvedPaths),report:e.report,storageColumns:e.storageColumns,storageIdMap:e.storageIdMap,table:e.table})},$n=async(e,t,r,n)=>{let o="",i=0;const s=async a=>{i+=1;const c=t(a,i);c!==void 0&&await r.push(c)};try{for await(const a of e){o+=typeof a=="string"?a:a.toString("utf8");let c=o.indexOf(`
11
+ `);for(;c!==-1;)await s(o.slice(0,c)),o=o.slice(c+1),c=o.indexOf(`
12
+ `)}o.length>0&&await s(o),await r.flush();return}catch(a){return n.error(`import failed part-way through: ${a instanceof Error?a.message:String(a)}`),n.error("the rows below had already been written — re-run the same command to resume (existing rows conflict rather than duplicate)"),a}},wn=async(e,t,r,n)=>{const o=await xr(r,n),i=t.tables.find(a=>a.table===S);if(i===void 0){n.error("--with-storage requires a Convex export with a `_storage` metadata table — re-export with `npx convex export --include-file-storage`.");return}const s=await br(e,t.snapshot,i,o?.keyPrefix??"",n);return n.info(`storage map: ${String(s.size)} blobs mapped`),{mapping:o,storageIdMap:s}},yn=async(e,t,r,n)=>{if(r.withStorage!==!0)return{};if(t.kind==="convex")return wn(e,t,n,r.logger);if(t.kind!=="supabase"&&t.kind!=="firebase")return{};try{const o=await hn(e,t,r,n);return o===void 0?void 0:{transferredPaths:o}}catch{r.logger.error("no rows were imported — fix the transfer and re-run; it will resume where it stopped");return}},bn=(e,t)=>{for(const o of t.warnings)e.warn(o);const r=t.received-t.insertedTotal-t.conflicts-t.errorCount;r>0&&e.warn(`${String(r)} of ${String(t.received)} rows were neither inserted, conflicted, nor reported as errors`);const n=`imported ${String(t.insertedTotal)} of ${String(t.received)} rows (${String(t.conflicts)} conflicts, ${String(t.errorCount)} errors)`;t.failed?e.error(n):e.success(n)},Un=async e=>{const t=e.cwd??process.cwd(),r=await Er(e,t);if(r.kind==="invalid")return{body:void 0,code:1,inserted:0};if(e.scan===!0)return{body:void 0,code:await gn(r,t,e.logger)===void 0?1:0,inserted:0};const n=await dn(e);if(n===void 0)return{body:void 0,code:1,inserted:0};const{baseUrl:o,fetchImpl:i,requestUrl:s,token:a}=n,c=e.batchSize??cn,l=await yn({baseUrl:o,fetchImpl:i,token:a},r,e,t);if(l===void 0)return{body:void 0,code:1,inserted:0};const{mapping:d,storageIdMap:u,transferredPaths:g}=l,h=new Set,b=d?.storageColumns,w={ambiguous:[],rewritten:0,unmigrated:[]};e.logger.info(r.kind==="convex"?`POST ${s} -> import Convex export ${e.file} (${String(r.tables.length)} tables)`:`POST ${s} -> import ${e.file}`);const B=new Map,Ce=fn(r,e,u!==void 0,B),O=$t({batchSize:c,fetchImpl:i,maxBatchBytes:ln,requestUrl:s,token:a}),ze=mn({report:w,source:r,storageColumns:b,storageIdMap:u,table:e.table,transferredPaths:g,unresolvedPaths:h}),D=await $n(Ce,ze,O,e.logger),{conflicts:W,errors:q,inserted:H,received:Pe,warnings:Ue}=O.totals,Je=e.verify===!0&&D===void 0?_r(e.logger,B,{conflicts:W,inserted:H}):0,Fe=u!==void 0&&Cr(e.logger,w,e.verify===!0),Ve=zr(e.logger,h,e.verify===!0),Y=Object.values(H).reduce((Me,Be)=>Me+Be,0),K=un(O.totals,u,w),G=D!==void 0||q.length>0||Je>0||Fe||Ve;return e.logger.info(JSON.stringify(K,void 0,2)),bn(e.logger,{conflicts:W,errorCount:q.length,failed:G,insertedTotal:Y,received:Pe,warnings:Ue}),{body:K,code:G?1:0,inserted:Y}};export{cn as R,Un as S,Re as a,Oe as b,R as c,V as m,Pn as w};
@@ -0,0 +1 @@
1
+ import{sep as r}from"node:path";const h=(t,e,o=r)=>e===t||e.startsWith(t.endsWith(o)?t:`${t}${o}`);export{h as e};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@lunora/cli",
3
- "version": "1.0.0-alpha.153",
3
+ "version": "1.0.0-alpha.154",
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",
@@ -52,16 +52,16 @@
52
52
  },
53
53
  "dependencies": {
54
54
  "@bomb.sh/tab": "0.0.21",
55
- "@lunora/advisor": "1.0.0-alpha.71",
56
- "@lunora/bindings": "1.0.0-alpha.23",
57
- "@lunora/codegen": "1.0.0-alpha.98",
58
- "@lunora/config": "1.0.0-alpha.127",
59
- "@lunora/container": "1.0.0-alpha.25",
60
- "@lunora/d1": "1.0.0-alpha.69",
61
- "@lunora/errors": "1.0.0-alpha.16",
62
- "@lunora/mcp": "1.0.0-alpha.62",
63
- "@lunora/runtime": "1.0.0-alpha.57",
64
- "@lunora/seed": "1.0.0-alpha.66",
55
+ "@lunora/advisor": "1.0.0-alpha.72",
56
+ "@lunora/bindings": "1.0.0-alpha.24",
57
+ "@lunora/codegen": "1.0.0-alpha.99",
58
+ "@lunora/config": "1.0.0-alpha.128",
59
+ "@lunora/container": "1.0.0-alpha.26",
60
+ "@lunora/d1": "1.0.0-alpha.70",
61
+ "@lunora/errors": "1.0.0-alpha.17",
62
+ "@lunora/mcp": "1.0.0-alpha.63",
63
+ "@lunora/runtime": "1.0.0-alpha.58",
64
+ "@lunora/seed": "1.0.0-alpha.67",
65
65
  "@visulima/cerebro": "3.0.0",
66
66
  "@visulima/error": "6.0.0",
67
67
  "@visulima/fs": "5.0.5",
@@ -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 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};