@lunora/cli 1.0.0-alpha.325 → 1.0.0-alpha.326

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/bin.mjs CHANGED
@@ -1,3 +1,3 @@
1
1
  #!/usr/bin/env node
2
- import{r as e}from"./packem_shared/cli-o9i8dzCS.mjs";try{const r=await e();process.exit(r)}catch(r){process.stderr.write(`${r instanceof Error?r.message:String(r)}
2
+ import{r as e}from"./packem_shared/cli-D1ZleZMH.mjs";try{const r=await e();process.exit(r)}catch(r){process.stderr.write(`${r instanceof Error?r.message:String(r)}
3
3
  `),process.exit(1)}
package/dist/index.d.mts CHANGED
@@ -1315,7 +1315,7 @@ interface LintToolOfferDeps {
1315
1315
  defaults?: ReadonlyArray<LintTool>;
1316
1316
  }) => Promise<LintTool[]>;
1317
1317
  }
1318
- type Template = "analog" | "astro" | "expo" | "next" | "nuxt" | "react-router" | "solid-v2" | "standalone" | "sveltekit" | "tanstack-start-react" | "tanstack-start-solid" | "vinext" | "vinext-pages";
1318
+ type Template = "analog" | "astro" | "expo" | "next" | "nuxt" | "react-router" | "rspack-react" | "solid-v2" | "standalone" | "sveltekit" | "tanstack-start-react" | "tanstack-start-react-rspack" | "tanstack-start-solid" | "vinext" | "vinext-pages";
1319
1319
  interface InitCommandOptions {
1320
1320
  /**
1321
1321
  * Add features non-interactively after scaffolding (the `--add` flag): a
package/dist/index.d.ts CHANGED
@@ -1315,7 +1315,7 @@ interface LintToolOfferDeps {
1315
1315
  defaults?: ReadonlyArray<LintTool>;
1316
1316
  }) => Promise<LintTool[]>;
1317
1317
  }
1318
- type Template = "analog" | "astro" | "expo" | "next" | "nuxt" | "react-router" | "solid-v2" | "standalone" | "sveltekit" | "tanstack-start-react" | "tanstack-start-solid" | "vinext" | "vinext-pages";
1318
+ type Template = "analog" | "astro" | "expo" | "next" | "nuxt" | "react-router" | "rspack-react" | "solid-v2" | "standalone" | "sveltekit" | "tanstack-start-react" | "tanstack-start-react-rspack" | "tanstack-start-solid" | "vinext" | "vinext-pages";
1319
1319
  interface InitCommandOptions {
1320
1320
  /**
1321
1321
  * Add features non-interactively after scaffolding (the `--add` flag): a
package/dist/index.mjs CHANGED
@@ -1 +1 @@
1
- import{C as o,V as a,r as n}from"./packem_shared/cli-o9i8dzCS.mjs";import{runCodegenCommand as m}from"./packem_chunks/runCodegenCommand.mjs";import{runDeployCommand as p}from"./packem_chunks/runDeployCommand.mjs";import{runDevCommand as f}from"./packem_chunks/runDevCommand.mjs";import{p as i}from"./packem_shared/plan-B-KsxVne.mjs";import{runInitCommand as l}from"./packem_chunks/runInitCommand.mjs";import{runMigrateGenerateCommand as I}from"./packem_shared/runMigrateGenerateCommand-CDHswpMU.mjs";import{runResetCommand as g}from"./packem_chunks/runResetCommand.mjs";import{runRpcCommand as T}from"./packem_chunks/runRpcCommand.mjs";import{EXIT_CODE as S,exitCodeForCode as A,exitCodeForError as c,exitCodeForStatus as M}from"./packem_shared/EXIT_CODE-08cwt3MK.mjs";import{insertSchemaExtension as v}from"./packem_shared/insertSchemaExtension-DuiV6cba.mjs";import{createLogger as b,pail as O}from"./packem_shared/createLogger-Cl18I8AX.mjs";import{diffSnapshots as y,renderAddColumn as L,renderCreateIndex as w,renderCreateTable as B,renderDropIndex as P,renderDropTable as U,renderMigrationFile as V,validatorKindToSqlType as W}from"./packem_shared/diffSnapshots-WWwx-KvZ.mjs";import{default as N}from"./packem_shared/schemaIrToSnapshot-BjK-0IRo.mjs";import{createRecordingSpawner as j,defaultSpawner as q}from"./packem_shared/createRecordingSpawner-sS7LEN7x.mjs";import{default as K}from"./packem_shared/parseManifest-CwPTKdtS.mjs";import{D as Y,r as Z}from"./packem_shared/import-D7qdpSmJ.mjs";import{REQUIRED_COMPATIBILITY_DATE as z,REQUIRED_FLAG as J,validateWranglerProject as $,validateWranglerConfig as rr}from"@lunora/config/cloudflare";import{b as or}from"./packem_shared/catalog-CahzmDLV.mjs";import{r as nr,a as tr,b as mr}from"./packem_shared/commands-CNqednoX.mjs";import{runExportCommand as pr}from"./packem_shared/runExportCommand-DxsJHYZt.mjs";export{o as COMMANDS,Y as DEFAULT_IMPORT_BATCH_SIZE,S as EXIT_CODE,z as REQUIRED_COMPATIBILITY_DATE,J as REQUIRED_FLAG,a as VERSION,or as buildRegistryIndex,b as createLogger,j as createRecordingSpawner,q as defaultSpawner,y as diffSnapshots,A as exitCodeForCode,c as exitCodeForError,M as exitCodeForStatus,v as insertSchemaExtension,O as pail,K as parseManifest,i as planDevCommand,L as renderAddColumn,w as renderCreateIndex,B as renderCreateTable,P as renderDropIndex,U as renderDropTable,V as renderMigrationFile,nr as runAddCommand,tr as runBuildIndexCommand,n as runCli,m as runCodegenCommand,p as runDeployCommand,f as runDevCommand,pr as runExportCommand,Z as runImportCommand,l as runInitCommand,I as runMigrateGenerateCommand,mr as runRegistryViewCommand,g as runResetCommand,T as runRpcCommand,N as schemaIrToSnapshot,$ as validateWrangler,rr as validateWranglerConfig,W as validatorKindToSqlType};
1
+ import{C as o,V as a,r as n}from"./packem_shared/cli-D1ZleZMH.mjs";import{runCodegenCommand as m}from"./packem_chunks/runCodegenCommand.mjs";import{runDeployCommand as p}from"./packem_chunks/runDeployCommand.mjs";import{runDevCommand as f}from"./packem_chunks/runDevCommand.mjs";import{p as i}from"./packem_shared/plan-B-KsxVne.mjs";import{runInitCommand as l}from"./packem_chunks/runInitCommand.mjs";import{runMigrateGenerateCommand as I}from"./packem_shared/runMigrateGenerateCommand-CDHswpMU.mjs";import{runResetCommand as g}from"./packem_chunks/runResetCommand.mjs";import{runRpcCommand as T}from"./packem_chunks/runRpcCommand.mjs";import{EXIT_CODE as S,exitCodeForCode as A,exitCodeForError as c,exitCodeForStatus as M}from"./packem_shared/EXIT_CODE-08cwt3MK.mjs";import{insertSchemaExtension as v}from"./packem_shared/insertSchemaExtension-DuiV6cba.mjs";import{createLogger as b,pail as O}from"./packem_shared/createLogger-Cl18I8AX.mjs";import{diffSnapshots as y,renderAddColumn as L,renderCreateIndex as w,renderCreateTable as B,renderDropIndex as P,renderDropTable as U,renderMigrationFile as V,validatorKindToSqlType as W}from"./packem_shared/diffSnapshots-WWwx-KvZ.mjs";import{default as N}from"./packem_shared/schemaIrToSnapshot-BjK-0IRo.mjs";import{createRecordingSpawner as j,defaultSpawner as q}from"./packem_shared/createRecordingSpawner-sS7LEN7x.mjs";import{default as K}from"./packem_shared/parseManifest-CwPTKdtS.mjs";import{D as Y,r as Z}from"./packem_shared/import-D7qdpSmJ.mjs";import{REQUIRED_COMPATIBILITY_DATE as z,REQUIRED_FLAG as J,validateWranglerProject as $,validateWranglerConfig as rr}from"@lunora/config/cloudflare";import{b as or}from"./packem_shared/catalog-CahzmDLV.mjs";import{r as nr,a as tr,b as mr}from"./packem_shared/commands-CNqednoX.mjs";import{runExportCommand as pr}from"./packem_shared/runExportCommand-DxsJHYZt.mjs";export{o as COMMANDS,Y as DEFAULT_IMPORT_BATCH_SIZE,S as EXIT_CODE,z as REQUIRED_COMPATIBILITY_DATE,J as REQUIRED_FLAG,a as VERSION,or as buildRegistryIndex,b as createLogger,j as createRecordingSpawner,q as defaultSpawner,y as diffSnapshots,A as exitCodeForCode,c as exitCodeForError,M as exitCodeForStatus,v as insertSchemaExtension,O as pail,K as parseManifest,i as planDevCommand,L as renderAddColumn,w as renderCreateIndex,B as renderCreateTable,P as renderDropIndex,U as renderDropTable,V as renderMigrationFile,nr as runAddCommand,tr as runBuildIndexCommand,n as runCli,m as runCodegenCommand,p as runDeployCommand,f as runDevCommand,pr as runExportCommand,Z as runImportCommand,l as runInitCommand,I as runMigrateGenerateCommand,mr as runRegistryViewCommand,g as runResetCommand,T as runRpcCommand,N as schemaIrToSnapshot,$ as validateWrangler,rr as validateWranglerConfig,W as validatorKindToSqlType};
@@ -1,4 +1,4 @@
1
- import{writeFileSync as h,existsSync as S,readFileSync as p}from"node:fs";import{isAbsolute as v,join as w}from"node:path";import{byCodepoint as b,scoreAdvisor as y,parseAdvisorMap as x,compareToBaseline as j}from"@lunora/advisor";import{runCodegen as A}from"@lunora/codegen";import{d as M}from"../packem_shared/command-B--jgXSc.mjs";import{EXIT_CODE as D}from"../packem_shared/EXIT_CODE-08cwt3MK.mjs";import{D as u}from"../packem_shared/cli-o9i8dzCS.mjs";const l={clean:"·",exempt:"–",failing:"✗",warned:"!"},d=(e,r)=>e.length>=r?e:e+" ".repeat(r-e.length),E=e=>`${e.id} (${e.visibility} ${e.kind})`,f=e=>{let r=0;for(const n of e)r=Math.max(r,n.id.length);return r},g=(e,r)=>` ${d(String(e.score),3)} ${l[e.coverage]} ${d(e.id,r)} ${e.visibility} ${e.kind}`,R=e=>{if(!e.comparable)return[` baseline not comparable (${e.reason}) — regenerate it; this run cannot verify anything`];if(!e.regressed)return[` no regression against baseline (score ${e.scoreDelta>=0?"+":""}${String(e.scoreDelta)})`];const r=[` REGRESSED against baseline (score ${e.scoreDelta>=0?"+":""}${String(e.scoreDelta)})`];for(const n of e.dropped)r.push(` ${n.id}: ${String(n.before)} → ${String(n.after)}`);for(const n of e.newFailing)r.push(` ${n}: now failing`);for(const n of e.worsened)r.push(` ${n}: more findings than the baseline`);return e.projectRegressed&&r.push(" project: new schema/config rules fired"),r},F=(e,r)=>{const n=e.procedures.filter(i=>i.coverage!=="clean"&&i.coverage!=="exempt"),t=f(n),o=[`advisor health ${String(e.score)}/100 — ${e.grade}`,` ${String(e.summary.clean)} clean · ${String(e.summary.warned)} warned · ${String(e.summary.failing)} failing · ${String(e.summary.exempt)} exempt (${String(e.summary.procedures)} procedures, ${String(e.summary.rulesFired)} rules fired)`];return e.project.checks.length>0&&o.push("",` project ${String(e.project.score)}/100 — ${e.project.checks.map(i=>i.name).join(", ")}`),n.length>0&&o.push("",...n.map(i=>g(i,t)),""," run with --all for every procedure, or --entry <file#export> for one"),r!==void 0&&o.push("",...R(r)),o.join(`
1
+ import{writeFileSync as h,existsSync as S,readFileSync as p}from"node:fs";import{isAbsolute as v,join as w}from"node:path";import{byCodepoint as b,scoreAdvisor as y,parseAdvisorMap as x,compareToBaseline as j}from"@lunora/advisor";import{runCodegen as A}from"@lunora/codegen";import{d as M}from"../packem_shared/command-B--jgXSc.mjs";import{EXIT_CODE as D}from"../packem_shared/EXIT_CODE-08cwt3MK.mjs";import{D as u}from"../packem_shared/cli-D1ZleZMH.mjs";const l={clean:"·",exempt:"–",failing:"✗",warned:"!"},d=(e,r)=>e.length>=r?e:e+" ".repeat(r-e.length),E=e=>`${e.id} (${e.visibility} ${e.kind})`,f=e=>{let r=0;for(const n of e)r=Math.max(r,n.id.length);return r},g=(e,r)=>` ${d(String(e.score),3)} ${l[e.coverage]} ${d(e.id,r)} ${e.visibility} ${e.kind}`,R=e=>{if(!e.comparable)return[` baseline not comparable (${e.reason}) — regenerate it; this run cannot verify anything`];if(!e.regressed)return[` no regression against baseline (score ${e.scoreDelta>=0?"+":""}${String(e.scoreDelta)})`];const r=[` REGRESSED against baseline (score ${e.scoreDelta>=0?"+":""}${String(e.scoreDelta)})`];for(const n of e.dropped)r.push(` ${n.id}: ${String(n.before)} → ${String(n.after)}`);for(const n of e.newFailing)r.push(` ${n}: now failing`);for(const n of e.worsened)r.push(` ${n}: more findings than the baseline`);return e.projectRegressed&&r.push(" project: new schema/config rules fired"),r},F=(e,r)=>{const n=e.procedures.filter(i=>i.coverage!=="clean"&&i.coverage!=="exempt"),t=f(n),o=[`advisor health ${String(e.score)}/100 — ${e.grade}`,` ${String(e.summary.clean)} clean · ${String(e.summary.warned)} warned · ${String(e.summary.failing)} failing · ${String(e.summary.exempt)} exempt (${String(e.summary.procedures)} procedures, ${String(e.summary.rulesFired)} rules fired)`];return e.project.checks.length>0&&o.push("",` project ${String(e.project.score)}/100 — ${e.project.checks.map(i=>i.name).join(", ")}`),n.length>0&&o.push("",...n.map(i=>g(i,t)),""," run with --all for every procedure, or --entry <file#export> for one"),r!==void 0&&o.push("",...R(r)),o.join(`
2
2
  `)},k=e=>e.coverage==="exempt"?[` exempt: ${e.exemptReason===void 0||e.exemptReason===""?"no reason given":e.exemptReason}`]:e.checks.map(r=>{const n=r.occurrences>1?`, ×${String(r.occurrences)}`:"";return` ${r.name} (−${String(r.weight)}${n})`}),T=e=>{const r=new Map;for(const n of e){const t=r.get(n.file);t===void 0?r.set(n.file,[n]):t.push(n)}return[...r].toSorted(([n],[t])=>b(n,t))},B=e=>{const r=f(e.procedures),n=[`advisor health ${String(e.score)}/100 — ${e.grade}`,"",` legend: ${l.clean} clean ${l.warned} warned ${l.failing} failing ${l.exempt} exempt`];for(const[t,o]of T(e.procedures)){n.push("",` ${t}`);for(const i of o)n.push(g(i,r),...k(i))}return n.join(`
3
3
  `)},C=(e,r)=>{const n=e.procedures.find(o=>o.id===r);if(n===void 0){const o=e.procedures.slice(0,10).map(i=>` ${i.id}`);return[`no procedure ${r} in the map. Known ids:`,...o,e.procedures.length>10?" …":""].filter(Boolean).join(`
4
4
  `)}const t=[`${E(n)} — ${String(n.score)}/100, ${n.coverage}`,` weight in the global mean: ${String(n.weight)}`];if(n.checks.length===0)return t.push(""," no rule fired"),t.join(`
@@ -1,4 +1,4 @@
1
- import{V as R}from"../packem_shared/cli-o9i8dzCS.mjs";import{d as G}from"../packem_shared/command-B--jgXSc.mjs";import{EXIT_CODE as d}from"../packem_shared/EXIT_CODE-08cwt3MK.mjs";import{existsSync as f,readFileSync as h,mkdirSync as J,realpathSync as W,statSync as V,writeFileSync as z,chmodSync as H,renameSync as K,unlinkSync as q}from"node:fs";import{homedir as w}from"node:os";import{findWranglerFile as X}from"@lunora/config/cloudflare";import{join as s,dirname as B,relative as Z}from"@visulima/path";import{stringify as Q}from"smol-toml";import{parse as Y,modify as ee,applyEdits as re}from"jsonc-parser";import{detectPackageManager as te,execArgsFor as ne,readLiveDevServerState as S,DEV_STATE_DIR as oe}from"@lunora/config";import{resolveAdminToken as ae}from"@lunora/config/studio-host";import{connectLocalStdio as le}from"@lunora/mcp";import{resolve as y}from"node:path";import{i as ce}from"../packem_shared/path-containment-CgxYZggb.mjs";const m=e=>({args:[...e.args],command:e.command,...e.env===void 0?{}:{env:e.env}}),b=e=>e.transport==="http"?{type:"http",url:e.url}:m(e),se=e=>e.transport==="http"?{httpUrl:e.url}:m(e),ie=e=>e.transport==="http"?{serverUrl:e.url}:m(e),de=e=>({args:["-y","mcp-remote",e],command:"npx"}),ue=e=>e.transport==="http"?de(e.url):m(e),fe=e=>e.transport==="http"?{url:e.url}:m(e),me=e=>e.transport==="http"?{enabled:!0,type:"remote",url:e.url}:{command:[e.command,...e.args],enabled:!0,type:"local",...e.env===void 0?{}:{environment:e.env}},pe=e=>e.transport==="http"?{disabled:!1,type:"streamableHttp",url:e.url}:{disabled:!1,...m(e)},ge=({home:e,platform:r})=>{if(r==="darwin")return{global:s(e,"Library","Application Support","Claude","claude_desktop_config.json")};if(r==="win32"){const t=process.env.APPDATA;return t===void 0||t===""?{}:{global:s(t,"Claude","claude_desktop_config.json")}}return r==="linux"?{global:s(e,".config","Claude","claude_desktop_config.json")}:{}},ve=(e,r)=>Q({mcp_servers:{[e]:r.transport==="http"?{url:r.url}:{args:[...r.args],command:r.command,...r.env===void 0?{}:{env:r.env}}}}),v=[{buildEntry:b,paths:({projectRoot:e})=>({project:s(e,".mcp.json")}),format:"json",id:"claude-code",key:"mcpServers",label:"Claude Code"},{buildEntry:b,paths:({home:e,projectRoot:r})=>({global:s(e,".cursor","mcp.json"),project:s(r,".cursor","mcp.json")}),format:"json",id:"cursor",key:"mcpServers",label:"Cursor"},{buildEntry:b,paths:({projectRoot:e})=>({project:s(e,".vscode","mcp.json")}),format:"json",id:"vscode",key:"servers",label:"VS Code (GitHub Copilot)"},{buildEntry:se,paths:({home:e,projectRoot:r})=>({global:s(e,".gemini","settings.json"),project:s(r,".gemini","settings.json")}),format:"json",id:"gemini",key:"mcpServers",label:"Gemini CLI"},{buildEntry:ue,paths:ge,format:"json",id:"claude-desktop",key:"mcpServers",label:"Claude Desktop"},{buildEntry:ie,paths:({home:e})=>({global:s(e,".codeium","windsurf","mcp_config.json")}),format:"json",id:"windsurf",key:"mcpServers",label:"Windsurf"},{buildEntry:me,paths:({home:e,projectRoot:r})=>({global:s(e,".config","opencode","opencode.json"),project:s(r,"opencode.json")}),format:"json",id:"opencode",key:"mcp",label:"OpenCode"},{buildEntry:pe,paths:({home:e})=>({global:s(e,".cline","mcp.json")}),format:"json",id:"cline",key:"mcpServers",label:"Cline"},{buildEntry:fe,paths:({home:e})=>({global:s(e,".config","zed","settings.json")}),format:"json",id:"zed",key:"context_servers",label:"Zed"},{paths:({home:e,projectRoot:r})=>({global:s(e,".codex","config.toml"),project:s(r,".codex","config.toml")}),format:"manual",id:"codex",label:"Codex CLI",renderSnippet:ve}],x=v.map(e=>e.id),he=e=>v.find(r=>r.id===e.toLowerCase()),M=(e,r)=>{let t=e,n;try{t=W(e),n=V(t).mode}catch{}const a=`${t}.lunora-${Math.random().toString(36).slice(2,10)}.tmp`;try{z(a,r,"utf8"),n!==void 0&&H(a,n),K(a,t)}catch(o){try{q(a)}catch{}throw o}},ye={formattingOptions:{insertSpaces:!0,tabSize:4}},k=e=>{const r=[],t=Y(e,r,{allowTrailingComma:!0});return{errors:r,value:t}},g=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),E=(e,r,t)=>{if(!g(e))return;const n=e[r];return g(n)?n[t]:void 0},L=e=>{if(!f(e.path))return"absent";let r;try{r=h(e.path,"utf8")}catch{return"invalid"}if(r.trim().length===0)return"absent";const{errors:t,value:n}=k(r);return t.length>0||!g(n)?"invalid":E(n,e.key,e.name)===void 0?"absent":"present"},be=e=>L(e)==="present",U=(e,r,t,n,a)=>{try{const o=ee(e,[t,n],a,ye);o.length>0&&M(r,re(e,o));return}catch(o){return o instanceof Error?o.message:String(o)}},Se=e=>{const{entry:r,force:t=!1,key:n,name:a,path:o}=e,l=f(o)?h(o,"utf8"):"";if(l.trim().length===0)return J(B(o),{recursive:!0}),M(o,`${JSON.stringify({[n]:{[a]:r}},void 0,4)}
1
+ import{V as R}from"../packem_shared/cli-D1ZleZMH.mjs";import{d as G}from"../packem_shared/command-B--jgXSc.mjs";import{EXIT_CODE as d}from"../packem_shared/EXIT_CODE-08cwt3MK.mjs";import{existsSync as f,readFileSync as h,mkdirSync as J,realpathSync as W,statSync as V,writeFileSync as z,chmodSync as H,renameSync as K,unlinkSync as q}from"node:fs";import{homedir as w}from"node:os";import{findWranglerFile as X}from"@lunora/config/cloudflare";import{join as s,dirname as B,relative as Z}from"@visulima/path";import{stringify as Q}from"smol-toml";import{parse as Y,modify as ee,applyEdits as re}from"jsonc-parser";import{detectPackageManager as te,execArgsFor as ne,readLiveDevServerState as S,DEV_STATE_DIR as oe}from"@lunora/config";import{resolveAdminToken as ae}from"@lunora/config/studio-host";import{connectLocalStdio as le}from"@lunora/mcp";import{resolve as y}from"node:path";import{i as ce}from"../packem_shared/path-containment-CgxYZggb.mjs";const m=e=>({args:[...e.args],command:e.command,...e.env===void 0?{}:{env:e.env}}),b=e=>e.transport==="http"?{type:"http",url:e.url}:m(e),se=e=>e.transport==="http"?{httpUrl:e.url}:m(e),ie=e=>e.transport==="http"?{serverUrl:e.url}:m(e),de=e=>({args:["-y","mcp-remote",e],command:"npx"}),ue=e=>e.transport==="http"?de(e.url):m(e),fe=e=>e.transport==="http"?{url:e.url}:m(e),me=e=>e.transport==="http"?{enabled:!0,type:"remote",url:e.url}:{command:[e.command,...e.args],enabled:!0,type:"local",...e.env===void 0?{}:{environment:e.env}},pe=e=>e.transport==="http"?{disabled:!1,type:"streamableHttp",url:e.url}:{disabled:!1,...m(e)},ge=({home:e,platform:r})=>{if(r==="darwin")return{global:s(e,"Library","Application Support","Claude","claude_desktop_config.json")};if(r==="win32"){const t=process.env.APPDATA;return t===void 0||t===""?{}:{global:s(t,"Claude","claude_desktop_config.json")}}return r==="linux"?{global:s(e,".config","Claude","claude_desktop_config.json")}:{}},ve=(e,r)=>Q({mcp_servers:{[e]:r.transport==="http"?{url:r.url}:{args:[...r.args],command:r.command,...r.env===void 0?{}:{env:r.env}}}}),v=[{buildEntry:b,paths:({projectRoot:e})=>({project:s(e,".mcp.json")}),format:"json",id:"claude-code",key:"mcpServers",label:"Claude Code"},{buildEntry:b,paths:({home:e,projectRoot:r})=>({global:s(e,".cursor","mcp.json"),project:s(r,".cursor","mcp.json")}),format:"json",id:"cursor",key:"mcpServers",label:"Cursor"},{buildEntry:b,paths:({projectRoot:e})=>({project:s(e,".vscode","mcp.json")}),format:"json",id:"vscode",key:"servers",label:"VS Code (GitHub Copilot)"},{buildEntry:se,paths:({home:e,projectRoot:r})=>({global:s(e,".gemini","settings.json"),project:s(r,".gemini","settings.json")}),format:"json",id:"gemini",key:"mcpServers",label:"Gemini CLI"},{buildEntry:ue,paths:ge,format:"json",id:"claude-desktop",key:"mcpServers",label:"Claude Desktop"},{buildEntry:ie,paths:({home:e})=>({global:s(e,".codeium","windsurf","mcp_config.json")}),format:"json",id:"windsurf",key:"mcpServers",label:"Windsurf"},{buildEntry:me,paths:({home:e,projectRoot:r})=>({global:s(e,".config","opencode","opencode.json"),project:s(r,"opencode.json")}),format:"json",id:"opencode",key:"mcp",label:"OpenCode"},{buildEntry:pe,paths:({home:e})=>({global:s(e,".cline","mcp.json")}),format:"json",id:"cline",key:"mcpServers",label:"Cline"},{buildEntry:fe,paths:({home:e})=>({global:s(e,".config","zed","settings.json")}),format:"json",id:"zed",key:"context_servers",label:"Zed"},{paths:({home:e,projectRoot:r})=>({global:s(e,".codex","config.toml"),project:s(r,".codex","config.toml")}),format:"manual",id:"codex",label:"Codex CLI",renderSnippet:ve}],x=v.map(e=>e.id),he=e=>v.find(r=>r.id===e.toLowerCase()),M=(e,r)=>{let t=e,n;try{t=W(e),n=V(t).mode}catch{}const a=`${t}.lunora-${Math.random().toString(36).slice(2,10)}.tmp`;try{z(a,r,"utf8"),n!==void 0&&H(a,n),K(a,t)}catch(o){try{q(a)}catch{}throw o}},ye={formattingOptions:{insertSpaces:!0,tabSize:4}},k=e=>{const r=[],t=Y(e,r,{allowTrailingComma:!0});return{errors:r,value:t}},g=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),E=(e,r,t)=>{if(!g(e))return;const n=e[r];return g(n)?n[t]:void 0},L=e=>{if(!f(e.path))return"absent";let r;try{r=h(e.path,"utf8")}catch{return"invalid"}if(r.trim().length===0)return"absent";const{errors:t,value:n}=k(r);return t.length>0||!g(n)?"invalid":E(n,e.key,e.name)===void 0?"absent":"present"},be=e=>L(e)==="present",U=(e,r,t,n,a)=>{try{const o=ee(e,[t,n],a,ye);o.length>0&&M(r,re(e,o));return}catch(o){return o instanceof Error?o.message:String(o)}},Se=e=>{const{entry:r,force:t=!1,key:n,name:a,path:o}=e,l=f(o)?h(o,"utf8"):"";if(l.trim().length===0)return J(B(o),{recursive:!0}),M(o,`${JSON.stringify({[n]:{[a]:r}},void 0,4)}
2
2
  `),{action:"created",path:o};const{errors:c,value:i}=k(l);if(c.length>0)return{action:"invalid",error:`parse error at offset ${String(c[0]?.offset??0)}`,path:o};if(!g(i))return{action:"invalid",error:"the file's root is not a JSON object",path:o};const p=i[n];if(p!==void 0&&!g(p))return{action:"invalid",error:`"${n}" is not an object`,path:o};if(E(i,n,a)!==void 0&&!t)return{action:"skipped",path:o};const $=U(l,o,n,a,r);return $===void 0?{action:"updated",path:o}:{action:"invalid",error:$,path:o}},we=e=>{const{key:r,name:t,path:n}=e;if(!f(n))return{action:"absent",path:n};let a;try{a=h(n,"utf8")}catch(i){return{action:"invalid",error:i instanceof Error?i.message:String(i),path:n}}const{errors:o,value:l}=k(a);if(o.length>0)return{action:"invalid",error:`parse error at offset ${String(o[0]?.offset??0)}`,path:n};if(E(l,r,t)===void 0)return{action:"absent",path:n};const c=U(a,n,r,t,void 0);return c===void 0?{action:"removed",path:n}:{action:"invalid",error:c,path:n}},ke=["global","project"],u=(e,r)=>{const t=Z(r,e);return t.length>0&&!t.startsWith("..")?t:e},Ee=(e,r)=>{const t=e.paths(r);return ke.flatMap(n=>{const a=t[n];return a===void 0?[]:[{client:e,path:a,scope:n}]})},$e=(e,r,t,n)=>{const a=e.paths(r),o=t==="global"?"project":"global",l=a[t]??(n?void 0:a[o]);if(l!==void 0)return{client:e,path:l,scope:a[t]===void 0?o:t}},je=e=>v.filter(r=>Object.values(r.paths(e)).some(t=>f(t))),A=(e,r,t,n)=>{if(e.length===0)return r();const a=[];for(const o of e){const l=he(o);if(l===void 0){t.error(`mcp ${n}: unknown client "${o}". Known clients: ${x.join(", ")}.`);return}a.push(l)}return a},Oe=e=>e.client.format==="json",Ce="https://lunora.sh/mcp",N="lunora-docs",D="lunora",_e=e=>f(s(e,"lunora"))&&X(e)!==void 0,xe=e=>{const{args:r,command:t}=ne(e,"lunora",["mcp","serve"]);return{args:r,command:t,transport:"stdio"}},Me=e=>({transport:"http",url:e}),Le=e=>({home:e.home,platform:e.platform,projectRoot:e.cwd}),T=(e,r,t)=>$e(e,Le(t),t.scope??r.preferredScope,t.scope!==void 0||!r.allowScopeFallback),Ue=(e,r,t)=>{const n=T(e,r,t);if(n===void 0){t.logger.warn(`${e.label}: has no ${t.scope??r.preferredScope}-scoped config — skipped "${r.name}".`);return}const{path:a}=n,o=e.buildEntry(r.spec);if(t.print===!0){const i=u(a,t.cwd);return t.force!==!0&&be({key:e.key,name:r.name,path:a})?(t.logger.info(`${e.label}: "${r.name}" already configured in ${i} — a real install would skip it (re-run with --force to replace).`),{action:"printed",path:a}):(t.logger.info(`${e.label} → ${i}
3
3
  ${JSON.stringify({[e.key]:{[r.name]:o}},void 0,4)}`),{action:"printed",path:a})}const l=Se({entry:o,force:t.force===!0,key:e.key,name:r.name,path:a}),c=u(a,t.cwd);return l.action==="invalid"?t.logger.error(`${e.label}: ${c} is not valid JSON (${l.error??"unknown error"}) — left untouched.`):l.action==="skipped"?t.logger.info(`${e.label}: "${r.name}" already configured in ${c} — re-run with --force to replace it.`):t.logger.success(`${e.label}: ${l.action==="created"?"created":"updated"} ${c} with "${r.name}".`),{action:l.action,path:a}},Ae=(e,r,t)=>{const n=T(e,r,t)?.path;if(n===void 0){t.logger.warn(`${e.label}: no known config location on ${t.platform} — skipped.`);return}return t.logger.info(`${e.label}: add this to ${u(n,t.cwd)}
4
4
 
@@ -1,3 +1,3 @@
1
- import{runCodegen as O}from"@lunora/codegen";import{runPostCodegenHook as G,detectAgentRules as P,updateDevServerState as $,readDevServerState as j,discoverContainerInfo as F,streamContainerLogs as H,formatLunoraEvent as V,DEV_DAEMON_ENV as C,detectAiAgent as B,readProjectRemotePreference as U,readLiveDevServerState as M,DEV_HANDOFF_ENV as y,clearDevServerState as W,claimDevServerState as X,DEV_LOG_FILE_ENV as K,inferLunoraBindings as Y,packageNamesFromBindings as J,ensureDevVarsExample as z,ensureDevVariables as Q,isInteractive as Z,DEV_VARS_FILE as T,DEV_VARS_EXAMPLE_FILE as q,fillDevSecrets as ee,DEV_BINDINGS_FILE as te,DEV_STATE_FILE as x,claimAgentRulesHint as re,AGENT_RULES_HINT as oe}from"@lunora/config";import{resolveRemoteEnabled as ne}from"@lunora/config/cloudflare";import{p as ie,a as ae}from"../packem_shared/deploy-target-DCWwiuAe.mjs";import{w as se}from"../packem_shared/binding-manifest-file-CQ1eQYy1.mjs";import{existsSync as ce,watch as de}from"node:fs";import{join as le}from"node:path";import{a as ue}from"../packem_shared/codegen-error-AmH54ofi.mjs";import{a as fe}from"../packem_shared/platform-diagnostics-Cn2g6Jh-.mjs";import{d as me}from"../packem_shared/command-B--jgXSc.mjs";import{EXIT_CODE as ge}from"../packem_shared/EXIT_CODE-08cwt3MK.mjs";import{forceJsonLogging as ve}from"../packem_shared/createLogger-Cl18I8AX.mjs";import{createServer as we,request as he}from"node:http";import{connect as pe}from"node:net";import{pipeline as Se}from"node:stream";import{loadStudioAssets as k,studioAssetsStamp as I,renderStudioHtml as ye,resolveAdminToken as Ee,transportRejectionReason as R,SCHEMA_EDIT_ENDPOINT as be,POLICY_SCAFFOLD_ENDPOINT as Te,SEED_ENDPOINT as ke,sendStudioDocument as Ie,serveJsonHandler as Re,isStandaloneModulePath as De,readStandaloneAsset as _e,assetContentType as Le,handleSchemaEditRequest as Ne,handlePolicyScaffoldRequest as Ae,handleSeedRequest as Oe,applyStudioAssetCache as Pe}from"@lunora/config/studio-host";import{c as $e}from"../packem_shared/tui-prompts-B3YwUhGw.mjs";import{setTimeout as Ce}from"node:timers/promises";import{r as Me,d as xe,P as Ge,a as je,b as E,s as Fe,c as He,e as Ve,f as Be,g as Ue}from"../packem_shared/plan-B-KsxVne.mjs";import{provisionBindings as We}from"./runDeployCommand.mjs";import{spawn as Xe}from"node:child_process";import{spawnShellCompat as Ke}from"../packem_shared/createRecordingSpawner-sS7LEN7x.mjs";const Ye=100,Je=300,ze=/[/\\]/u,Qe=(e,t,r)=>{const{apiSpec:n,logger:o,projectRoot:a,target:c}=e;try{const i=O({apiSpec:n,lunoraDirectory:t,projectRoot:a,target:c});o.success(`codegen: wrote ${t}/_generated (${r})`),fe(i.platformDiagnostics,o)}catch(i){return o.error(ue(i,r)),!1}return!0},Ze=e=>{const t=e.lunoraDirectory??"lunora",r=le(e.projectRoot,t),n=e.debounceMs??Ye;let o=!1,a=!1,c=!1,i,d=0,f=Promise.resolve(),w;const p=new Promise(m=>{w=m}),h=m=>{o||(i=m,!a&&(a=!0,f=(async()=>{try{for(;i!==void 0;){const v=i;if(i=void 0,!!Qe(e,t,v)){c=!0;try{(await G({cwd:e.projectRoot,logger:e.logger,spawner:e.spawner,stdoutToStderr:e.jsonLogs})).ran&&(d=Date.now())}finally{c=!1}}}}catch(v){e.logger.error(`codegen watch: ${v instanceof Error?v.message:String(v)}`)}finally{a=!1,w()}})()))};h("startup");const l=m=>(e.logger.warn(`codegen watch unavailable (${m}) — schema edits will NOT auto-regenerate. Run \`lunora codegen\` manually after each edit.`),{close:()=>(o=!0,i=void 0,f),ready:p,watchAvailable:!1});let s,u;if(!ce(r))return l(`no such directory: ${r}`);try{u=de(r,{recursive:!0},(m,v)=>{if(!(typeof v=="string"&&v.split(ze).includes("_generated"))){if(c||Date.now()-d<Je){s&&(clearTimeout(s),s=void 0);return}s&&clearTimeout(s),s=setTimeout(()=>{h(`change: ${v??"?"}`)},n)}})}catch(m){return l(m instanceof Error?m.message:String(m))}const g=u;return{close:()=>(o=!0,i=void 0,s&&clearTimeout(s),g.close(),f),ready:p,watchAvailable:!0}},D="/_lunora",_=e=>{const t=e.indexOf("?");return t===-1?e:e.slice(0,t)},L=3e4,N=(e,t,r)=>{const n=he({headers:{...e.headers,host:r.host},hostname:r.hostname,method:e.method,path:e.url,port:r.port},o=>{t.writeHead(o.statusCode??502,o.headers),Se(o,t,()=>{})});n.setTimeout(L,()=>{n.destroy(new Error(`no response within ${String(L)}ms`))}),n.on("error",o=>{if(t.headersSent){t.destroy();return}t.statusCode=o.message.startsWith("no response within")?504:502,t.end(`lunora dev: worker unreachable (${o.message})`)}),t.on("close",()=>{t.writableFinished||n.destroy()}),e.pipe(n)},qe=5e3,et=(e,t,r,n)=>{const o=pe({host:n.hostname,port:Number(n.port)},()=>{o.setTimeout(0);const a=[`${e.method??"GET"} ${e.url??"/"} HTTP/1.1`];for(const[c,i]of Object.entries(e.headers))if(c!=="host")for(const d of Array.isArray(i)?i:[i])d!==void 0&&a.push(`${c}: ${d}`);a.push(`host: ${n.host}`,"",""),o.write(a.join(`\r
2
- `)),r.length>0&&o.write(r),o.pipe(t),t.pipe(o)});o.setTimeout(qe,()=>o.destroy()),o.on("error",()=>t.destroy()),t.on("error",()=>o.destroy())},tt=async e=>{const t=e.host??"127.0.0.1",r=t==="127.0.0.1"||t==="localhost"||t==="::1",n=new URL(e.workerOrigin);let o=k(e.logger,import.meta.url),a=I(import.meta.url);const c=ye({adminToken:r?Ee(e.cwd):void 0,basePath:"/",dataEditable:r,rulesInstalled:P(e.cwd).installed,runAsIdentity:r,schemaEditable:r,scriptSrc:"/studio.js",styleHref:"/styles.css"}),i=(l,s,u,g,m)=>{Pe(l,s,m,a)||(s.statusCode=200,s.setHeader("Content-Type",g),s.end(u))},d=(l,s,u)=>{l.statusCode=s,l.setHeader("Content-Type","text/plain"),l.end(u)},f=(l,s,u,g)=>{if(r){Re(l,s,u,e.cwd,{apiSpec:e.apiSpec});return}d(s,403,g)},w=(l,s,u)=>{const g=l==="/styles.css",m=De(l);if(!g&&!m)return!1;const v=I(import.meta.url);if(v!==a&&(o=k(e.logger,import.meta.url),a=v),o===void 0)return d(u,501,"Lunora studio assets not found — install and build @lunora/studio."),!0;if(g)return i(s,u,o.styles,"text/css; charset=utf-8","styles.css"),!0;const S=l.slice(l.lastIndexOf("/")+1),b=_e(S,import.meta.url);return b===void 0?(d(u,404,"Not found"),!0):(i(s,u,b,Le(S),S),!0)},p=Buffer.from(c),h=we((l,s)=>{const u=_(l.url??"/");if(r){const m=R(l,e.logger);if(m!==void 0){d(s,403,m);return}}if(u.startsWith(D)){if(!r){d(s,403,"Lunora studio: the worker admin proxy is only available on a loopback bind.");return}N(l,s,n);return}if(u===be){f(l,s,Ne,"Lunora schema editing is only available on loopback hosts in dev.");return}if(u===Te){f(l,s,Ae,"Lunora policy scaffolding is only available on loopback hosts in dev.");return}if(u===ke){f(l,s,Oe,"Lunora data seeding is only available on loopback hosts in dev.");return}if(w(u,l,s))return;const g=l.headers["sec-fetch-mode"];if(r&&typeof g=="string"&&g!=="navigate"){N(l,s,n);return}Ie(s,p)});return h.on("upgrade",(l,s,u)=>{if(!r||R(l,e.logger)!==void 0){s.destroy();return}_(l.url??"").startsWith(D)?et(l,s,u,n):s.destroy()}),await new Promise((l,s)=>{h.once("error",u=>{u.code==="EADDRINUSE"?s(new Error(`studio port ${String(e.port)} is already in use — pass a different port with --port, or stop the process using it`,{cause:u})):s(u)}),h.listen(e.port,t,()=>{l()})}),{close:()=>new Promise(l=>{h.close(()=>{l()})}),url:`http://${t==="0.0.0.0"||t==="::"?"localhost":t}:${String(e.port)}`}},rt=async e=>{const{cwd:t,logger:r,origin:n,signal:o}=e,a=e.probe??xe,c=Me(e.readyTimeoutMs),i=Date.now()+c,d=()=>o.aborted;for(;!d()&&Date.now()<i;){let f=!1;try{f=await a(n,o)}catch{}if(d()||Date.now()>=i)break;if(f)return $(t,{readyAt:new Date().toISOString()},{expectedPid:process.pid}),j(t)?.readyAt!==void 0;try{await Ce(Ge,void 0,{signal:o})}catch{}}return d()||r.warn(`server did not answer on ${n} within ${String(Math.round(c/1e3))}s — .lunora/dev.json will have no readyAt, so anything polling for readiness will keep waiting. The server itself is unaffected; raise LUNORA_DEV_READY_TIMEOUT_MS if it is just slow to boot.`),!1},ot=5e3,A=(e,t,r,n)=>{if(e.length===0)return;const o=V(e);if(o){n[o.level](`[lunora] ${o.text}`);return}const a=`[${t}] ${e}`;r==="stderr"?n.warn(a):n.info(a)},nt=(e,t,r)=>{const n=(o,a)=>{if(!o)return;let c="";o.on("data",i=>{c+=i.toString("utf8");const d=c.split(`
3
- `);c=d.pop()??"";for(const f of d)A(f.trimEnd(),t,a,r)}),o.on("end",()=>{A(c.trimEnd(),t,a,r),c=""})};n(e.stdout,"stdout"),n(e.stderr,"stderr")},it=(e,t)=>{const r=Ke(e.command,e.args),n=Xe(r.command,r.args,{cwd:e.cwd??process.cwd(),env:e.env?{...process.env,...e.env}:process.env,shell:r.shell,stdio:["inherit","pipe","pipe"]});return nt(n,e.tag,t),{exited:new Promise(o=>{n.on("error",a=>{t.error(`[${e.tag}] failed to start: ${a.message}`),o(1)}),n.on("exit",(a,c)=>{o(a??(c?1:0))})}),kill:o=>{try{n.kill(o)}catch{}}}},at=(e,t)=>{if(process.env.LUNORA_CONTAINER_LOGS==="0")return;const n=F(e,"lunora").containers.map(o=>({className:o.className,exportName:o.exportName}));if(n.length!==0)return H({containers:n,onLine:o=>{const a=`[container:${o.name}] ${o.text}`;o.level==="error"?t.warn(a):t.info(a)},onUnavailable:o=>{t.warn(`[container] Docker engine unreachable — container logs unavailable (${o})`)}})},st=async e=>{e.readyProbe?.abort(),await e.codegen?.close().catch(()=>{}),e.containerLogs?.close(),await e.studio?.close().catch(()=>{});try{e.remoteCleanup?.()}catch{}},ct=async e=>await new Promise(t=>{const r={},n=c=>{e.info(`received ${c} — shutting down`),r.sigint&&process.off("SIGINT",r.sigint),r.sigterm&&process.off("SIGTERM",r.sigterm),t(0)},o=()=>{n("SIGINT")},a=()=>{n("SIGTERM")};r.sigint=o,r.sigterm=a,process.on("SIGINT",o),process.on("SIGTERM",a)}),dt=async(e,t,r)=>{let n=0,o;const a=f=>{e.kill(f),t?.kill(f)},c=()=>{n+=1,n===1?(r.info("received SIGINT — shutting down (press Ctrl-C again to force-kill)"),a("SIGTERM"),o=setTimeout(()=>{a("SIGKILL")},ot),o.unref()):a("SIGKILL")},i=()=>{a("SIGTERM")};process.on("SIGINT",c),process.on("SIGTERM",i);const d=await Promise.race([e.exited.then(f=>({code:f,who:"worker"})),...t===void 0?[]:[t.exited.then(f=>({code:f,who:"sidecar"}))]]);return t!==void 0&&(d.who==="sidecar"?(r.warn("[worker] the Lunora sidecar (wrangler dev) exited — shutting down the framework dev server"),e.kill("SIGTERM")):t.kill("SIGTERM"),await Promise.allSettled([e.exited,t.exited])),o&&clearTimeout(o),process.off("SIGINT",c),process.off("SIGTERM",i),d.code},lt=(e,t,r,n)=>{e.info(""),e.success("Lunora dev"),e.info(` ➜ Worker: ${t.workerOrigin}`),r!==void 0&&e.info(` ➜ Studio: ${r}`),t.runsCodegenWatch&&e.info(" ➜ Codegen: watching lunora/"),n!==void 0&&e.info(` ➜ Supervisor: ${n} (needs) · ${x} (status)`),t.remote.enabled&&(t.remote.bindings.length>0?e.info(` ➜ Remote: ${t.remote.bindings.join(", ")} → deployed worker`):e.warn(` ➜ Remote: requested but inactive (${t.remote.reason??"no eligible bindings"}) — running fully local`)),e.info("")},ut=(e,t)=>{P(t).installed||!re()||(e.info(` ⓘ ${oe}`),e.info(""))},ft=async(e,t)=>{try{const n=await Y({projectRoot:t}),o=J(n),a=(e.ensureExample??z)(t,o);a.length>0&&e.logger.info(`Updated .dev.vars.example with secrets for: ${o.join(", ")} (${a.join(", ")})`)}catch{}(await(e.ensureEnv??Q)({confirm:$e(),cwd:t,info:n=>{e.logger.info(n)}})).status==="declined"&&!Z()&&e.logger.info(`hint: ${T} was not scaffolded (non-interactive run). Copy ${q} → ${T} and fill in secrets, or run \`lunora dev\` in an interactive terminal to scaffold automatically.`);try{(e.fillSecrets??ee)({cwd:t,info:n=>{e.logger.info(n)}})}catch{}},mt=(e,t,r,n,o)=>{if(e.flavor!=="wrangler")return;n!==void 0&&$(t,{studioUrl:n});let a;try{a=at(t,r)}catch{}return lt(r,e,n,o),a},gt=(e,t)=>{const r=Number(process.env[y]),n=X(t,{background:process.env[C]==="1",logFile:process.env[K],mode:"cli",pid:process.pid,startedAt:new Date().toISOString(),url:e.workerOrigin},Number.isInteger(r)&&r>0?{supersedePid:r}:void 0);return n.ok?void 0:n.existing},vt=e=>{const{cwd:t,destination:r,logger:n,plan:o}=e,a=r!==void 0,c=r??te,i=se({destination:c,dev:{...o.flavor==="wrangler"?{origin:o.workerOrigin}:{},statusFile:x},logger:a?n:{...n,success:()=>{},warn:()=>{}},projectRoot:t});return i.error!==void 0?a?i:(n.debug?.(`skipped the default binding manifest: ${i.error}`),{}):{written:c}},wt=async(e,t,r,n)=>{if(t.studioEnabled)try{return await(e.startStudio??tt)({apiSpec:e.apiSpec,cwd:r,logger:{warnOnce:o=>{n.warn(o)}},port:t.studioPort,workerOrigin:t.workerOrigin})}catch(o){n.warn(`studio server failed to start (${o instanceof Error?o.message:String(o)}) — continuing without it`);return}},ht=e=>{const t=[e.runsCodegenWatch?"codegen watch":void 0,e.studioEnabled?"studio":void 0].filter(n=>n!==void 0);return`--no-worker: not starting wrangler. ${t.length>0?`${t.join(" + ")} running`:"nothing else to run"}; your task runner owns the worker on ${e.workerOrigin}.`},pt=(e,t,r,n,o)=>{if(!(e.sidecar===void 0||!Ue(t)))try{O({apiSpec:t.apiSpec,lunoraDirectory:"lunora",projectRoot:r,target:o})}catch(a){n.warn(`codegen (pre-sidecar) failed: ${a instanceof Error?a.message:String(a)} — the framework dev server will retry`)}},St=e=>e.flavor==="vite"?"starting vite dev (worker + studio + codegen run inside Vite via @lunora/vite)":`starting ${e.wrangler.tag} dev + studio`,yt=async e=>{const{logger:t}=e,r=e.cwd??process.cwd(),n=e.flavor??He(r),o=ae(r,e.target);if(o.target===void 0)throw new Error(o.error??"unknown deploy target");const{target:a}=o,c=Ve(a,n,t);c==="wrangler"&&await We(r,t,void 0,a,void 0);const i=await Be({...e,flavor:c,target:a}),d={remoteCleanup:i.remote.cleanup};try{const f=Number(process.env[y]),w=M(r);if(w!==void 0&&w.pid!==process.pid&&w.pid!==f)return E(t,w),{code:0,plan:i};const p=gt(i,r);if(p!==void 0)return E(t,p),{code:0,plan:i};(i.flavor==="vite"||i.flavor==="framework-worker")&&(i.wrangler.env={...i.wrangler.env,[y]:String(process.pid)}),await ft(e,r),t.info(St(i)),i.ipv4LoopbackForced&&t.info("no IPv6 loopback (::1) on this host — binding the worker to 127.0.0.1 (--ip) so wrangler dev doesn't crash. Pin `dev.ip` in wrangler.jsonc to override."),i.runsCodegenWatch&&(d.codegen=(e.startCodegen??Ze)({apiSpec:e.apiSpec,jsonLogs:e.jsonLogs,logger:t,projectRoot:r,target:a})),d.studio=await wt(e,i,r,t);const h=vt({cwd:r,destination:e.emitBindings,logger:t,plan:i});if(h.error!==void 0)return t.error(h.error),{code:ge.USAGE,plan:i};await d.codegen?.ready;const l=d.studio?.url;i.frameworkHint!==void 0&&t.warn(i.frameworkHint);const s=()=>{i.flavor==="wrangler"&&(d.readyProbe=new AbortController,rt({cwd:r,logger:t,origin:i.workerOrigin,probe:e.probeReady,signal:d.readyProbe.signal}))};if(!i.workerEnabled)return s(),t.info(ht(i)),{code:await(e.waitForInterrupt??ct)(t),plan:i};pt(i,e,r,t,a);const u=e.startWorker??it,g=u(i.wrangler,t),m=i.sidecar===void 0?void 0:u(i.sidecar,t);return s(),d.containerLogs=mt(i,r,t,l,h.written),ut(t,r),{code:await dt(g,m,t),plan:i}}finally{d.readyProbe?.abort(),W(r,process.pid),await st(d)}},Et=e=>({codegen:e.codegen===!1?!1:void 0,studio:e.studio===!1?!1:void 0,worker:e.worker===!1?!1:void 0}),Ut=me(async({argument:e,cwd:t,logger:r,options:n})=>{const o=n.json===!0,a=je({cwd:t,json:o,lines:n.lines,logger:r,subcommand:e[0]});if(a!==void 0)return a;const c=process.env[C]==="1",i=c?void 0:B(),d=o||i!==void 0;d&&ve(),i!==void 0&&n.background!==!0&&r.info(`AI agent detected (${i.name} via ${i.variable}) — starting the dev server in background mode with JSON logs. Set LUNORA_AGENT_MODE=0 to opt out.`);const f=ne({configPreference:U(t),envValue:process.env.LUNORA_REMOTE,flag:n.remote});if(!c&&(n.background===!0||i!==void 0)){const w=M(t);return w!==void 0?(E(r,w),{code:0}):Fe({cwd:t,jsonLogs:d,logger:r,options:n,remote:f})}return yt({apiSpec:ie(n.apiSpec),cwd:t,emitBindings:n.emitBindings,inspectorPort:n.inspectorPort,jsonLogs:d,logger:r,port:n.port,remote:f,target:n.target,workerPort:n.workerPort,...Et(n)})});export{Ut as execute,Et as negatableDevFlags,yt as runDevCommand};
1
+ import{runCodegen as P}from"@lunora/codegen";import{runPostCodegenHook as G,detectAgentRules as O,updateDevServerState as $,readDevServerState as j,discoverContainerInfo as F,streamContainerLogs as H,formatLunoraEvent as V,DEV_DAEMON_ENV as C,detectAiAgent as B,readProjectRemotePreference as U,readLiveDevServerState as M,DEV_HANDOFF_ENV as y,clearDevServerState as W,claimDevServerState as X,DEV_LOG_FILE_ENV as K,inferLunoraBindings as Y,packageNamesFromBindings as J,ensureDevVarsExample as z,ensureDevVariables as Q,isInteractive as Z,DEV_VARS_FILE as T,DEV_VARS_EXAMPLE_FILE as q,fillDevSecrets as ee,DEV_BINDINGS_FILE as te,DEV_STATE_FILE as x,claimAgentRulesHint as re,AGENT_RULES_HINT as oe}from"@lunora/config";import{resolveRemoteEnabled as ne}from"@lunora/config/cloudflare";import{p as ie,a as ae}from"../packem_shared/deploy-target-DCWwiuAe.mjs";import{w as se}from"../packem_shared/binding-manifest-file-CQ1eQYy1.mjs";import{existsSync as ce,watch as de}from"node:fs";import{join as le}from"node:path";import{a as ue}from"../packem_shared/codegen-error-AmH54ofi.mjs";import{a as fe}from"../packem_shared/platform-diagnostics-Cn2g6Jh-.mjs";import{d as me}from"../packem_shared/command-B--jgXSc.mjs";import{EXIT_CODE as ge}from"../packem_shared/EXIT_CODE-08cwt3MK.mjs";import{forceJsonLogging as ve}from"../packem_shared/createLogger-Cl18I8AX.mjs";import{createServer as we,request as he}from"node:http";import{connect as pe}from"node:net";import{pipeline as Se}from"node:stream";import{loadStudioAssets as k,studioAssetsStamp as I,renderStudioHtml as ye,resolveAdminToken as Ee,requestPathname as R,transportRejectionReason as D,SCHEMA_EDIT_ENDPOINT as be,POLICY_SCAFFOLD_ENDPOINT as Te,SEED_ENDPOINT as ke,sendStudioDocument as Ie,serveJsonHandler as Re,isStandaloneModulePath as De,readStandaloneAsset as _e,assetContentType as Le,handleSchemaEditRequest as Ne,handlePolicyScaffoldRequest as Ae,handleSeedRequest as Pe,applyStudioAssetCache as Oe}from"@lunora/config/studio-host";import{c as $e}from"../packem_shared/tui-prompts-B3YwUhGw.mjs";import{setTimeout as Ce}from"node:timers/promises";import{r as Me,d as xe,P as Ge,a as je,b as E,s as Fe,c as He,e as Ve,f as Be,g as Ue}from"../packem_shared/plan-B-KsxVne.mjs";import{provisionBindings as We}from"./runDeployCommand.mjs";import{spawn as Xe}from"node:child_process";import{spawnShellCompat as Ke}from"../packem_shared/createRecordingSpawner-sS7LEN7x.mjs";const Ye=100,Je=300,ze=/[/\\]/u,Qe=(e,t,r)=>{const{apiSpec:n,logger:o,projectRoot:a,target:c}=e;try{const i=P({apiSpec:n,lunoraDirectory:t,projectRoot:a,target:c});o.success(`codegen: wrote ${t}/_generated (${r})`),fe(i.platformDiagnostics,o)}catch(i){return o.error(ue(i,r)),!1}return!0},Ze=e=>{const t=e.lunoraDirectory??"lunora",r=le(e.projectRoot,t),n=e.debounceMs??Ye;let o=!1,a=!1,c=!1,i,d=0,f=Promise.resolve(),w;const p=new Promise(m=>{w=m}),h=m=>{o||(i=m,!a&&(a=!0,f=(async()=>{try{for(;i!==void 0;){const v=i;if(i=void 0,!!Qe(e,t,v)){c=!0;try{(await G({cwd:e.projectRoot,logger:e.logger,spawner:e.spawner,stdoutToStderr:e.jsonLogs})).ran&&(d=Date.now())}finally{c=!1}}}}catch(v){e.logger.error(`codegen watch: ${v instanceof Error?v.message:String(v)}`)}finally{a=!1,w()}})()))};h("startup");const l=m=>(e.logger.warn(`codegen watch unavailable (${m}) — schema edits will NOT auto-regenerate. Run \`lunora codegen\` manually after each edit.`),{close:()=>(o=!0,i=void 0,f),ready:p,watchAvailable:!1});let s,u;if(!ce(r))return l(`no such directory: ${r}`);try{u=de(r,{recursive:!0},(m,v)=>{if(!(typeof v=="string"&&v.split(ze).includes("_generated"))){if(c||Date.now()-d<Je){s&&(clearTimeout(s),s=void 0);return}s&&clearTimeout(s),s=setTimeout(()=>{h(`change: ${v??"?"}`)},n)}})}catch(m){return l(m instanceof Error?m.message:String(m))}const g=u;return{close:()=>(o=!0,i=void 0,s&&clearTimeout(s),g.close(),f),ready:p,watchAvailable:!0}},_="/_lunora",L=3e4,N=(e,t,r)=>{const n=he({headers:{...e.headers,host:r.host},hostname:r.hostname,method:e.method,path:e.url,port:r.port},o=>{t.writeHead(o.statusCode??502,o.headers),Se(o,t,()=>{})});n.setTimeout(L,()=>{n.destroy(new Error(`no response within ${String(L)}ms`))}),n.on("error",o=>{if(t.headersSent){t.destroy();return}t.statusCode=o.message.startsWith("no response within")?504:502,t.end(`lunora dev: worker unreachable (${o.message})`)}),t.on("close",()=>{t.writableFinished||n.destroy()}),e.pipe(n)},qe=5e3,et=(e,t,r,n)=>{const o=pe({host:n.hostname,port:Number(n.port)},()=>{o.setTimeout(0);const a=[`${e.method??"GET"} ${e.url??"/"} HTTP/1.1`];for(const[c,i]of Object.entries(e.headers))if(c!=="host")for(const d of Array.isArray(i)?i:[i])d!==void 0&&a.push(`${c}: ${d}`);a.push(`host: ${n.host}`,"",""),o.write(a.join(`\r
2
+ `)),r.length>0&&o.write(r),o.pipe(t),t.pipe(o)});o.setTimeout(qe,()=>o.destroy()),o.on("error",()=>t.destroy()),t.on("error",()=>o.destroy())},tt=async e=>{const t=e.host??"127.0.0.1",r=t==="127.0.0.1"||t==="localhost"||t==="::1",n=new URL(e.workerOrigin);let o=k(e.logger,import.meta.url),a=I(import.meta.url);const c=ye({adminToken:r?Ee(e.cwd):void 0,basePath:"/",dataEditable:r,rulesInstalled:O(e.cwd).installed,runAsIdentity:r,schemaEditable:r,scriptSrc:"/studio.js",styleHref:"/styles.css"}),i=(l,s,u,g,m)=>{Oe(l,s,m,a)||(s.statusCode=200,s.setHeader("Content-Type",g),s.end(u))},d=(l,s,u)=>{l.statusCode=s,l.setHeader("Content-Type","text/plain"),l.end(u)},f=(l,s,u,g)=>{if(r){Re(l,s,u,e.cwd,{apiSpec:e.apiSpec});return}d(s,403,g)},w=(l,s,u)=>{const g=l==="/styles.css",m=De(l);if(!g&&!m)return!1;const v=I(import.meta.url);if(v!==a&&(o=k(e.logger,import.meta.url),a=v),o===void 0)return d(u,501,"Lunora studio assets not found — install and build @lunora/studio."),!0;if(g)return i(s,u,o.styles,"text/css; charset=utf-8","styles.css"),!0;const S=l.slice(l.lastIndexOf("/")+1),b=_e(S,import.meta.url);return b===void 0?(d(u,404,"Not found"),!0):(i(s,u,b,Le(S),S),!0)},p=Buffer.from(c),h=we((l,s)=>{const u=R(l.url??"/");if(r){const m=D(l,e.logger);if(m!==void 0){d(s,403,m);return}}if(u.startsWith(_)){if(!r){d(s,403,"Lunora studio: the worker admin proxy is only available on a loopback bind.");return}N(l,s,n);return}if(u===be){f(l,s,Ne,"Lunora schema editing is only available on loopback hosts in dev.");return}if(u===Te){f(l,s,Ae,"Lunora policy scaffolding is only available on loopback hosts in dev.");return}if(u===ke){f(l,s,Pe,"Lunora data seeding is only available on loopback hosts in dev.");return}if(w(u,l,s))return;const g=l.headers["sec-fetch-mode"];if(r&&typeof g=="string"&&g!=="navigate"){N(l,s,n);return}Ie(s,p)});return h.on("upgrade",(l,s,u)=>{if(!r||D(l,e.logger)!==void 0){s.destroy();return}R(l.url??"").startsWith(_)?et(l,s,u,n):s.destroy()}),await new Promise((l,s)=>{h.once("error",u=>{u.code==="EADDRINUSE"?s(new Error(`studio port ${String(e.port)} is already in use — pass a different port with --port, or stop the process using it`,{cause:u})):s(u)}),h.listen(e.port,t,()=>{l()})}),{close:()=>new Promise(l=>{h.close(()=>{l()})}),url:`http://${t==="0.0.0.0"||t==="::"?"localhost":t}:${String(e.port)}`}},rt=async e=>{const{cwd:t,logger:r,origin:n,signal:o}=e,a=e.probe??xe,c=Me(e.readyTimeoutMs),i=Date.now()+c,d=()=>o.aborted;for(;!d()&&Date.now()<i;){let f=!1;try{f=await a(n,o)}catch{}if(d()||Date.now()>=i)break;if(f)return $(t,{readyAt:new Date().toISOString()},{expectedPid:process.pid}),j(t)?.readyAt!==void 0;try{await Ce(Ge,void 0,{signal:o})}catch{}}return d()||r.warn(`server did not answer on ${n} within ${String(Math.round(c/1e3))}s — .lunora/dev.json will have no readyAt, so anything polling for readiness will keep waiting. The server itself is unaffected; raise LUNORA_DEV_READY_TIMEOUT_MS if it is just slow to boot.`),!1},ot=5e3,A=(e,t,r,n)=>{if(e.length===0)return;const o=V(e);if(o){n[o.level](`[lunora] ${o.text}`);return}const a=`[${t}] ${e}`;r==="stderr"?n.warn(a):n.info(a)},nt=(e,t,r)=>{const n=(o,a)=>{if(!o)return;let c="";o.on("data",i=>{c+=i.toString("utf8");const d=c.split(`
3
+ `);c=d.pop()??"";for(const f of d)A(f.trimEnd(),t,a,r)}),o.on("end",()=>{A(c.trimEnd(),t,a,r),c=""})};n(e.stdout,"stdout"),n(e.stderr,"stderr")},it=(e,t)=>{const r=Ke(e.command,e.args),n=Xe(r.command,r.args,{cwd:e.cwd??process.cwd(),env:e.env?{...process.env,...e.env}:process.env,shell:r.shell,stdio:["inherit","pipe","pipe"]});return nt(n,e.tag,t),{exited:new Promise(o=>{n.on("error",a=>{t.error(`[${e.tag}] failed to start: ${a.message}`),o(1)}),n.on("exit",(a,c)=>{o(a??(c?1:0))})}),kill:o=>{try{n.kill(o)}catch{}}}},at=(e,t)=>{if(process.env.LUNORA_CONTAINER_LOGS==="0")return;const n=F(e,"lunora").containers.map(o=>({className:o.className,exportName:o.exportName}));if(n.length!==0)return H({containers:n,onLine:o=>{const a=`[container:${o.name}] ${o.text}`;o.level==="error"?t.warn(a):t.info(a)},onUnavailable:o=>{t.warn(`[container] Docker engine unreachable — container logs unavailable (${o})`)}})},st=async e=>{e.readyProbe?.abort(),await e.codegen?.close().catch(()=>{}),e.containerLogs?.close(),await e.studio?.close().catch(()=>{});try{e.remoteCleanup?.()}catch{}},ct=async e=>await new Promise(t=>{const r={},n=c=>{e.info(`received ${c} — shutting down`),r.sigint&&process.off("SIGINT",r.sigint),r.sigterm&&process.off("SIGTERM",r.sigterm),t(0)},o=()=>{n("SIGINT")},a=()=>{n("SIGTERM")};r.sigint=o,r.sigterm=a,process.on("SIGINT",o),process.on("SIGTERM",a)}),dt=async(e,t,r)=>{let n=0,o;const a=f=>{e.kill(f),t?.kill(f)},c=()=>{n+=1,n===1?(r.info("received SIGINT — shutting down (press Ctrl-C again to force-kill)"),a("SIGTERM"),o=setTimeout(()=>{a("SIGKILL")},ot),o.unref()):a("SIGKILL")},i=()=>{a("SIGTERM")};process.on("SIGINT",c),process.on("SIGTERM",i);const d=await Promise.race([e.exited.then(f=>({code:f,who:"worker"})),...t===void 0?[]:[t.exited.then(f=>({code:f,who:"sidecar"}))]]);return t!==void 0&&(d.who==="sidecar"?(r.warn("[worker] the Lunora sidecar (wrangler dev) exited — shutting down the framework dev server"),e.kill("SIGTERM")):t.kill("SIGTERM"),await Promise.allSettled([e.exited,t.exited])),o&&clearTimeout(o),process.off("SIGINT",c),process.off("SIGTERM",i),d.code},lt=(e,t,r,n)=>{e.info(""),e.success("Lunora dev"),e.info(` ➜ Worker: ${t.workerOrigin}`),r!==void 0&&e.info(` ➜ Studio: ${r}`),t.runsCodegenWatch&&e.info(" ➜ Codegen: watching lunora/"),n!==void 0&&e.info(` ➜ Supervisor: ${n} (needs) · ${x} (status)`),t.remote.enabled&&(t.remote.bindings.length>0?e.info(` ➜ Remote: ${t.remote.bindings.join(", ")} → deployed worker`):e.warn(` ➜ Remote: requested but inactive (${t.remote.reason??"no eligible bindings"}) — running fully local`)),e.info("")},ut=(e,t)=>{O(t).installed||!re()||(e.info(` ⓘ ${oe}`),e.info(""))},ft=async(e,t)=>{try{const n=await Y({projectRoot:t}),o=J(n),a=(e.ensureExample??z)(t,o);a.length>0&&e.logger.info(`Updated .dev.vars.example with secrets for: ${o.join(", ")} (${a.join(", ")})`)}catch{}(await(e.ensureEnv??Q)({confirm:$e(),cwd:t,info:n=>{e.logger.info(n)}})).status==="declined"&&!Z()&&e.logger.info(`hint: ${T} was not scaffolded (non-interactive run). Copy ${q} → ${T} and fill in secrets, or run \`lunora dev\` in an interactive terminal to scaffold automatically.`);try{(e.fillSecrets??ee)({cwd:t,info:n=>{e.logger.info(n)}})}catch{}},mt=(e,t,r,n,o)=>{if(e.flavor!=="wrangler")return;n!==void 0&&$(t,{studioUrl:n});let a;try{a=at(t,r)}catch{}return lt(r,e,n,o),a},gt=(e,t)=>{const r=Number(process.env[y]),n=X(t,{background:process.env[C]==="1",logFile:process.env[K],mode:"cli",pid:process.pid,startedAt:new Date().toISOString(),url:e.workerOrigin},Number.isInteger(r)&&r>0?{supersedePid:r}:void 0);return n.ok?void 0:n.existing},vt=e=>{const{cwd:t,destination:r,logger:n,plan:o}=e,a=r!==void 0,c=r??te,i=se({destination:c,dev:{...o.flavor==="wrangler"?{origin:o.workerOrigin}:{},statusFile:x},logger:a?n:{...n,success:()=>{},warn:()=>{}},projectRoot:t});return i.error!==void 0?a?i:(n.debug?.(`skipped the default binding manifest: ${i.error}`),{}):{written:c}},wt=async(e,t,r,n)=>{if(t.studioEnabled)try{return await(e.startStudio??tt)({apiSpec:e.apiSpec,cwd:r,logger:{warnOnce:o=>{n.warn(o)}},port:t.studioPort,workerOrigin:t.workerOrigin})}catch(o){n.warn(`studio server failed to start (${o instanceof Error?o.message:String(o)}) — continuing without it`);return}},ht=e=>{const t=[e.runsCodegenWatch?"codegen watch":void 0,e.studioEnabled?"studio":void 0].filter(n=>n!==void 0);return`--no-worker: not starting wrangler. ${t.length>0?`${t.join(" + ")} running`:"nothing else to run"}; your task runner owns the worker on ${e.workerOrigin}.`},pt=(e,t,r,n,o)=>{if(!(e.sidecar===void 0||!Ue(t)))try{P({apiSpec:t.apiSpec,lunoraDirectory:"lunora",projectRoot:r,target:o})}catch(a){n.warn(`codegen (pre-sidecar) failed: ${a instanceof Error?a.message:String(a)} — the framework dev server will retry`)}},St=e=>e.flavor==="vite"?"starting vite dev (worker + studio + codegen run inside Vite via @lunora/vite)":`starting ${e.wrangler.tag} dev + studio`,yt=async e=>{const{logger:t}=e,r=e.cwd??process.cwd(),n=e.flavor??He(r),o=ae(r,e.target);if(o.target===void 0)throw new Error(o.error??"unknown deploy target");const{target:a}=o,c=Ve(a,n,t);c==="wrangler"&&await We(r,t,void 0,a,void 0);const i=await Be({...e,flavor:c,target:a}),d={remoteCleanup:i.remote.cleanup};try{const f=Number(process.env[y]),w=M(r);if(w!==void 0&&w.pid!==process.pid&&w.pid!==f)return E(t,w),{code:0,plan:i};const p=gt(i,r);if(p!==void 0)return E(t,p),{code:0,plan:i};(i.flavor==="vite"||i.flavor==="framework-worker")&&(i.wrangler.env={...i.wrangler.env,[y]:String(process.pid)}),await ft(e,r),t.info(St(i)),i.ipv4LoopbackForced&&t.info("no IPv6 loopback (::1) on this host — binding the worker to 127.0.0.1 (--ip) so wrangler dev doesn't crash. Pin `dev.ip` in wrangler.jsonc to override."),i.runsCodegenWatch&&(d.codegen=(e.startCodegen??Ze)({apiSpec:e.apiSpec,jsonLogs:e.jsonLogs,logger:t,projectRoot:r,target:a})),d.studio=await wt(e,i,r,t);const h=vt({cwd:r,destination:e.emitBindings,logger:t,plan:i});if(h.error!==void 0)return t.error(h.error),{code:ge.USAGE,plan:i};await d.codegen?.ready;const l=d.studio?.url;i.frameworkHint!==void 0&&t.warn(i.frameworkHint);const s=()=>{i.flavor==="wrangler"&&(d.readyProbe=new AbortController,rt({cwd:r,logger:t,origin:i.workerOrigin,probe:e.probeReady,signal:d.readyProbe.signal}))};if(!i.workerEnabled)return s(),t.info(ht(i)),{code:await(e.waitForInterrupt??ct)(t),plan:i};pt(i,e,r,t,a);const u=e.startWorker??it,g=u(i.wrangler,t),m=i.sidecar===void 0?void 0:u(i.sidecar,t);return s(),d.containerLogs=mt(i,r,t,l,h.written),ut(t,r),{code:await dt(g,m,t),plan:i}}finally{d.readyProbe?.abort(),W(r,process.pid),await st(d)}},Et=e=>({codegen:e.codegen===!1?!1:void 0,studio:e.studio===!1?!1:void 0,worker:e.worker===!1?!1:void 0}),Ut=me(async({argument:e,cwd:t,logger:r,options:n})=>{const o=n.json===!0,a=je({cwd:t,json:o,lines:n.lines,logger:r,subcommand:e[0]});if(a!==void 0)return a;const c=process.env[C]==="1",i=c?void 0:B(),d=o||i!==void 0;d&&ve(),i!==void 0&&n.background!==!0&&r.info(`AI agent detected (${i.name} via ${i.variable}) — starting the dev server in background mode with JSON logs. Set LUNORA_AGENT_MODE=0 to opt out.`);const f=ne({configPreference:U(t),envValue:process.env.LUNORA_REMOTE,flag:n.remote});if(!c&&(n.background===!0||i!==void 0)){const w=M(t);return w!==void 0?(E(r,w),{code:0}):Fe({cwd:t,jsonLogs:d,logger:r,options:n,remote:f})}return yt({apiSpec:ie(n.apiSpec),cwd:t,emitBindings:n.emitBindings,inspectorPort:n.inspectorPort,jsonLogs:d,logger:r,port:n.port,remote:f,target:n.target,workerPort:n.workerPort,...Et(n)})});export{Ut as execute,Et as negatableDevFlags,yt as runDevCommand};
@@ -1,4 +1,4 @@
1
- import{existsSync as m,mkdirSync as M,writeFileSync as w,readFileSync as k,readdirSync as ce,rmSync as O,lstatSync as de,mkdtempSync as ue,copyFileSync as Ge,renameSync as Ye}from"node:fs";import{tmpdir as pe}from"node:os";import{installArgsFor as he,execArgsFor as Je,detectFramework as Xe,isInteractive as y,LUNA_ART as Qe,LUNA_NAME as Ze,LUNA_SIGNOFF as et,BADGES as v,paintAnswer as tt,detectPackageManager as P,detectInstalledManagers as rt,runScriptCommand as at,detectLintTools as ot,addArgsFor as nt,applyLintIgnores as st}from"@lunora/config";import{walkSync as it}from"@visulima/fs";import{join as p,dirname as A,basename as _,resolve as me,relative as fe}from"@visulima/path";import{downloadTemplate as ge}from"giget";import{modify as lt,applyEdits as ct}from"jsonc-parser";import{join as K,dirname as dt}from"node:path";import{d as ut}from"../packem_shared/command-B--jgXSc.mjs";import{EXIT_CODE as f}from"../packem_shared/EXIT_CODE-08cwt3MK.mjs";import pt from"magic-string";import{Project as ht,SyntaxKind as g}from"ts-morph";import{P as q}from"../packem_shared/prompt-cancelled-BvsNxg_Q.mjs";import{m as ve,n as mt,o as we,q as ye,b as ft}from"../packem_shared/resolve-DUCSc7jQ.mjs";import{defaultSpawner as be}from"../packem_shared/createRecordingSpawner-sS7LEN7x.mjs";import{d as gt,e as vt,f as wt,a as xe,t as G,g as ke,h as yt,b as Ce,i as Se,w as bt,j as xt,k as Le,l as kt}from"../packem_shared/tui-prompts-B3YwUhGw.mjs";import{A as Me,E as Ae,p as Ct,w as St,M as Lt,r as Mt,k as At,e as Et,c as Ee,l as Ne,i as Nt,f as _t}from"../packem_shared/storage-J4xhM4FU.mjs";import{r as It}from"../packem_shared/commands-CNqednoX.mjs";import{logStep as Q}from"../packem_shared/createLogger-Cl18I8AX.mjs";import{r as $t}from"../packem_shared/lint-ignore-report-DKZagpqk.mjs";import Rt from"node:dns/promises";const Y={bun:{githubCacheKey:void 0,githubSetupStep:` - uses: oven-sh/setup-bun@v2
1
+ import{existsSync as m,mkdirSync as M,writeFileSync as w,readFileSync as x,readdirSync as ce,rmSync as T,lstatSync as de,mkdtempSync as ue,copyFileSync as Ge,renameSync as Ye}from"node:fs";import{tmpdir as pe}from"node:os";import{installArgsFor as he,execArgsFor as Je,detectFramework as Xe,isInteractive as y,LUNA_ART as Qe,LUNA_NAME as Ze,LUNA_SIGNOFF as et,BADGES as v,paintAnswer as tt,detectPackageManager as P,detectInstalledManagers as rt,runScriptCommand as at,detectLintTools as ot,addArgsFor as nt,applyLintIgnores as st}from"@lunora/config";import{walkSync as it}from"@visulima/fs";import{join as p,dirname as A,basename as _,resolve as me,relative as fe}from"@visulima/path";import{downloadTemplate as ge}from"giget";import{modify as lt,applyEdits as ct}from"jsonc-parser";import{join as K,dirname as dt}from"node:path";import{d as ut}from"../packem_shared/command-B--jgXSc.mjs";import{EXIT_CODE as f}from"../packem_shared/EXIT_CODE-08cwt3MK.mjs";import pt from"magic-string";import{Project as ht,SyntaxKind as g}from"ts-morph";import{P as q}from"../packem_shared/prompt-cancelled-BvsNxg_Q.mjs";import{m as ve,n as mt,o as we,q as ye,b as ft}from"../packem_shared/resolve-DUCSc7jQ.mjs";import{defaultSpawner as be}from"../packem_shared/createRecordingSpawner-sS7LEN7x.mjs";import{d as gt,e as vt,f as wt,a as ke,t as G,g as xe,h as yt,b as Ce,i as Se,w as bt,j as kt,k as Le,l as xt}from"../packem_shared/tui-prompts-B3YwUhGw.mjs";import{A as Me,E as Ae,p as Ct,w as St,M as Lt,r as Mt,k as At,e as Et,c as Ee,l as Ne,i as Nt,f as _t}from"../packem_shared/storage-J4xhM4FU.mjs";import{r as It}from"../packem_shared/commands-CNqednoX.mjs";import{logStep as Q}from"../packem_shared/createLogger-Cl18I8AX.mjs";import{r as Rt}from"../packem_shared/lint-ignore-report-DKZagpqk.mjs";import $t from"node:dns/promises";const Y={bun:{githubCacheKey:void 0,githubSetupStep:` - uses: oven-sh/setup-bun@v2
2
2
  `,gitlabImage:"oven/bun:1",gitlabProvisionScript:[],installCmd:"bun install --frozen-lockfile",lockfile:"bun.lockb"},npm:{githubCacheKey:"npm",githubSetupStep:"",gitlabImage:"node:22",gitlabProvisionScript:[],installCmd:"npm ci",lockfile:"package-lock.json"},pnpm:{githubCacheKey:"pnpm",githubSetupStep:` - uses: pnpm/action-setup@v4
3
3
  with:
4
4
  version: latest
@@ -7,7 +7,7 @@ ${e.githubSetupStep} - uses: actions/setup-node@v4
7
7
  with:
8
8
  node-version: 22
9
9
  ${e.githubCacheKey===void 0?"":` cache: ${e.githubCacheKey}
10
- `} - run: ${e.installCmd}`,Ot=e=>{const t=Y[e],r=t.githubCacheKey===void 0?`# (below) requires it — run \`${e} install\` locally and`:`# (below) and the ${e} cache both require it — run \`${e} install\` locally and`;return`name: Deploy
10
+ `} - run: ${e.installCmd}`,Tt=e=>{const t=Y[e],r=t.githubCacheKey===void 0?`# (below) requires it — run \`${e} install\` locally and`:`# (below) and the ${e} cache both require it — run \`${e} install\` locally and`;return`name: Deploy
11
11
 
12
12
  on:
13
13
  push:
@@ -49,7 +49,7 @@ ${Z(t)}
49
49
  steps:
50
50
  ${Z(t)}
51
51
  - run: ${L(e,["deploy","--preview"])}
52
- `},Tt=e=>{const t=Y[e],r=[...t.gitlabProvisionScript,t.installCmd].map(a=>` - ${a}`).join(`
52
+ `},Ot=e=>{const t=Y[e],r=[...t.gitlabProvisionScript,t.installCmd].map(a=>` - ${a}`).join(`
53
53
  `);return`stages:
54
54
  - deploy
55
55
 
@@ -84,16 +84,16 @@ preview:
84
84
  - if: $CI_PIPELINE_SOURCE == "merge_request_event"
85
85
  script:
86
86
  - ${L(e,["deploy","--preview"])}
87
- `},_e={github:{file:K(".github","workflows","deploy.yml"),secretsHint:"repository secrets (Settings → Secrets and variables → Actions)"},gitlab:{file:".gitlab-ci.yml",secretsHint:"masked CI/CD variables (Settings → CI/CD → Variables)"}},Pt=(e,t)=>e==="github"?Ot(t):Tt(t),Dt=e=>e==="github"||e==="gitlab",Bt=(e,t,r,a={})=>{const o=K(e,_e[t].file);return m(o)&&a.overwrite!==!0?{path:o,skipped:!0,written:!1}:(M(dt(o),{recursive:!0}),w(o,Pt(t,r),"utf8"),{path:o,skipped:!1,written:!0})},jt=(e,t,r,a,o={})=>{const n=_e[t];try{const s=Bt(e,t,r,o);if(s.skipped)a.info(`--ci ${t}: ${n.file} already exists — left unchanged (re-run with overwrite to replace).`);else{const i=he(r),l=[i.command,...i.args].join(" "),{installCmd:c,lockfile:u}=Y[r];a.success(`--ci ${t}: wrote ${n.file}`),a.info(`--ci ${t}: set CLOUDFLARE_API_TOKEN and CLOUDFLARE_ACCOUNT_ID as ${n.secretsHint} to enable deploys.`),a.info(`--ci ${t}: run \`${l}\` and commit ${u} before pushing — the pipeline runs \`${c}\`.`)}return s}catch(s){const i=s instanceof Error?s.message:String(s);return a.warn(`--ci ${t}: could not write ${n.file} (${i})`),{path:K(e,n.file),skipped:!1,written:!1}}},Ut={astro:"@lunora/react",none:"@lunora/react",nuxt:"@lunora/vue","react-router":"@lunora/react","solid-start":"@lunora/solid",sveltekit:"@lunora/svelte","tanstack-start":"@lunora/react","tanstack-start-solid":"@lunora/solid",vinext:"@lunora/react"},Vt=e=>{const t=Xe(e);return{...t,adapter:Ut[t.framework]}},R="lunora()",ee='import { lunora } from "@lunora/vite";',Ft="@lunora/vite",Wt="lunora",Ht=e=>{for(const t of e.getStatements()){if(t.getKind()!==g.ExportAssignment)continue;const r=t.asKindOrThrow(g.ExportAssignment).getExpression();if(r.getKind()!==g.CallExpression)continue;const a=r.asKindOrThrow(g.CallExpression);if(a.getExpression().getText()!=="defineConfig")continue;const o=a.getArguments()[0];if(o?.getKind()===g.ObjectLiteralExpression)return o.asKindOrThrow(g.ObjectLiteralExpression)}},zt=e=>{for(const t of e.getStatements()){if(t.getKind()!==g.ExportAssignment)continue;const r=t.asKindOrThrow(g.ExportAssignment).getExpression();if(r.getKind()===g.ObjectLiteralExpression)return r.asKindOrThrow(g.ObjectLiteralExpression)}},Kt=e=>e.getDescendantsOfKind(g.CallExpression).some(t=>t.getExpression().getText()===Wt),qt=e=>e.getImportDeclarations().some(t=>t.getModuleSpecifierValue()===Ft),Gt=e=>new ht({compilerOptions:{allowJs:!0},useInMemoryFileSystem:!0}).createSourceFile("vite.config.ts",e,{overwrite:!0}),Yt=(e,t)=>{const r=t.getImportDeclarations().at(-1)?.getEnd()??0;r===0?e.prepend(`${ee}
87
+ `},_e={github:{file:K(".github","workflows","deploy.yml"),secretsHint:"repository secrets (Settings → Secrets and variables → Actions)"},gitlab:{file:".gitlab-ci.yml",secretsHint:"masked CI/CD variables (Settings → CI/CD → Variables)"}},Pt=(e,t)=>e==="github"?Tt(t):Ot(t),Dt=e=>e==="github"||e==="gitlab",Bt=(e,t,r,a={})=>{const o=K(e,_e[t].file);return m(o)&&a.overwrite!==!0?{path:o,skipped:!0,written:!1}:(M(dt(o),{recursive:!0}),w(o,Pt(t,r),"utf8"),{path:o,skipped:!1,written:!0})},jt=(e,t,r,a,o={})=>{const n=_e[t];try{const s=Bt(e,t,r,o);if(s.skipped)a.info(`--ci ${t}: ${n.file} already exists — left unchanged (re-run with overwrite to replace).`);else{const i=he(r),l=[i.command,...i.args].join(" "),{installCmd:c,lockfile:u}=Y[r];a.success(`--ci ${t}: wrote ${n.file}`),a.info(`--ci ${t}: set CLOUDFLARE_API_TOKEN and CLOUDFLARE_ACCOUNT_ID as ${n.secretsHint} to enable deploys.`),a.info(`--ci ${t}: run \`${l}\` and commit ${u} before pushing — the pipeline runs \`${c}\`.`)}return s}catch(s){const i=s instanceof Error?s.message:String(s);return a.warn(`--ci ${t}: could not write ${n.file} (${i})`),{path:K(e,n.file),skipped:!1,written:!1}}},Ut={astro:"@lunora/react",none:"@lunora/react",nuxt:"@lunora/vue","react-router":"@lunora/react","solid-start":"@lunora/solid",sveltekit:"@lunora/svelte","tanstack-start":"@lunora/react","tanstack-start-solid":"@lunora/solid",vinext:"@lunora/react"},Vt=e=>{const t=Xe(e);return{...t,adapter:Ut[t.framework]}},$="lunora()",ee='import { lunora } from "@lunora/vite";',Ft="@lunora/vite",Wt="lunora",Ht=e=>{for(const t of e.getStatements()){if(t.getKind()!==g.ExportAssignment)continue;const r=t.asKindOrThrow(g.ExportAssignment).getExpression();if(r.getKind()!==g.CallExpression)continue;const a=r.asKindOrThrow(g.CallExpression);if(a.getExpression().getText()!=="defineConfig")continue;const o=a.getArguments()[0];if(o?.getKind()===g.ObjectLiteralExpression)return o.asKindOrThrow(g.ObjectLiteralExpression)}},zt=e=>{for(const t of e.getStatements()){if(t.getKind()!==g.ExportAssignment)continue;const r=t.asKindOrThrow(g.ExportAssignment).getExpression();if(r.getKind()===g.ObjectLiteralExpression)return r.asKindOrThrow(g.ObjectLiteralExpression)}},Kt=e=>e.getDescendantsOfKind(g.CallExpression).some(t=>t.getExpression().getText()===Wt),qt=e=>e.getImportDeclarations().some(t=>t.getModuleSpecifierValue()===Ft),Gt=e=>new ht({compilerOptions:{allowJs:!0},useInMemoryFileSystem:!0}).createSourceFile("vite.config.ts",e,{overwrite:!0}),Yt=(e,t)=>{const r=t.getImportDeclarations().at(-1)?.getEnd()??0;r===0?e.prepend(`${ee}
88
88
  `):e.appendLeft(r,`
89
- ${ee}`)},Jt=(e,t)=>{const r=t.getProperty("plugins");if(r===void 0){const s=t.getProperties(),i=t.getStart()+1;if(s.length===0){e.appendLeft(i,` plugins: [${R}] `);return}const l=s[0];if(l===void 0)return"could not locate the start of the Vite config object's first property";e.appendLeft(l.getStart(),`plugins: [${R}],
90
- `);return}const a=r.getDescendantsOfKind(g.ArrayLiteralExpression)[0];if(a===void 0)return"the Vite config's `plugins` is not an array literal — add `lunora()` to it by hand";const o=a.getElements();if(o.length===0){e.appendLeft(a.getStart()+1,R);return}const n=o[0];if(n===void 0)return"could not locate the first entry of the Vite config's `plugins` array";e.appendLeft(n.getStart(),`${R}, `)},Ie=e=>{const t=Gt(e);if(Kt(t))return{changed:!1,code:e,reason:"lunora plugin already present"};const r=Ht(t)??zt(t);if(r===void 0)return{changed:!1,code:e,reason:"could not locate a Vite config plugins array to patch"};const a=new pt(e);qt(t)||Yt(a,t);const o=Jt(a,r);return o!==void 0?{changed:!1,code:e,reason:o}:{changed:!0,code:a.toString()}},Xt=/enotfound|eai_again|econnrefused|etimedout|network|fetch failed|getaddrinfo/u,Qt=/404|not found|could not find|no such/u,Zt=(e,t)=>{const r=e instanceof Error?e.message:String(e),a=r.toLowerCase(),o=`failed to download template "${t.templateType}" from ${t.remote}: ${r}`;return Qt.test(a)?{hints:[`Check the template name "${t.templateType}" and the ref "${t.ref}".`,"List/inspect available templates, or target a branch/tag with `--ref <branch>`."],message:`template "${t.templateType}" not found at ${t.remote}: ${r}`}:Xt.test(a)?{hints:["You appear to be offline or unable to reach GitHub.","To scaffold without a network, point at a local template root: `lunora init --from <dir>`."],message:o}:{hints:["If this is a network/offline issue, scaffold from a local root with `lunora init --from <dir>`."],message:o}},T=async(e,t,r)=>{if(y()){await vt(v[e],t,r);return}if(process.stdout.write(`
89
+ ${ee}`)},Jt=(e,t)=>{const r=t.getProperty("plugins");if(r===void 0){const s=t.getProperties(),i=t.getStart()+1;if(s.length===0){e.appendLeft(i,` plugins: [${$}] `);return}const l=s[0];if(l===void 0)return"could not locate the start of the Vite config object's first property";e.appendLeft(l.getStart(),`plugins: [${$}],
90
+ `);return}const a=r.getDescendantsOfKind(g.ArrayLiteralExpression)[0];if(a===void 0)return"the Vite config's `plugins` is not an array literal — add `lunora()` to it by hand";const o=a.getElements();if(o.length===0){e.appendLeft(a.getStart()+1,$);return}const n=o[0];if(n===void 0)return"could not locate the first entry of the Vite config's `plugins` array";e.appendLeft(n.getStart(),`${$}, `)},Ie=e=>{const t=Gt(e);if(Kt(t))return{changed:!1,code:e,reason:"lunora plugin already present"};const r=Ht(t)??zt(t);if(r===void 0)return{changed:!1,code:e,reason:"could not locate a Vite config plugins array to patch"};const a=new pt(e);qt(t)||Yt(a,t);const o=Jt(a,r);return o!==void 0?{changed:!1,code:e,reason:o}:{changed:!0,code:a.toString()}},Xt=/enotfound|eai_again|econnrefused|etimedout|network|fetch failed|getaddrinfo/u,Qt=/404|not found|could not find|no such/u,Zt=(e,t)=>{const r=e instanceof Error?e.message:String(e),a=r.toLowerCase(),o=`failed to download template "${t.templateType}" from ${t.remote}: ${r}`;return Qt.test(a)?{hints:[`Check the template name "${t.templateType}" and the ref "${t.ref}".`,"List/inspect available templates, or target a branch/tag with `--ref <branch>`."],message:`template "${t.templateType}" not found at ${t.remote}: ${r}`}:Xt.test(a)?{hints:["You appear to be offline or unable to reach GitHub.","To scaffold without a network, point at a local template root: `lunora init --from <dir>`."],message:o}:{hints:["If this is a network/offline issue, scaffold from a local root with `lunora init --from <dir>`."],message:o}},O=async(e,t,r)=>{if(y()){await vt(v[e],t,r);return}if(process.stdout.write(`
91
91
  `),r===void 0||r===""){Q(e,t);return}const a=r.split(`
92
92
  `).map(o=>tt(o)).join(`
93
93
  `);Q(e,`${t}
94
94
  ${a}`)},er=async e=>{if(y()){await gt();return}e.info(`
95
95
  ${Qe}
96
- ${Ze}: ${et}`)},$e=[{description:"LLMs via Workers AI (summarize, generate, stream)",label:"AI",value:"ai"},{description:"Sign-up / sign-in (asks which provider)",label:"Authentication",value:"auth"},{description:"Copy-in auth screens for your framework (sign in/up, reset, 2FA)",label:"Auth UI",value:"auth-ui"},{description:"Snapshot + restore your Durable Object data",label:"Backups",value:"backup"},{description:"Headless browser screenshots + PDFs",label:"Browser rendering",value:"browser"},{description:"Zero Trust identity via Cloudflare Access",label:"Cloudflare Access",value:"cloudflare-access"},{description:"Scheduled jobs via Cron Triggers (@lunora/scheduler)",label:"Cron jobs",value:"crons"},{description:"Cloudflare Email Workers + a dev mail catcher",label:"Transactional email",value:"email"},{description:"OpenFeature feature flags (ctx.flags)",label:"Feature flags",value:"flags"},{description:"External Postgres/MySQL via Hyperdrive",label:"Hyperdrive",value:"hyperdrive"},{description:"Stripe-first payments (checkout, subscription, webhooks)",label:"Payments",value:"payment"},{description:"Live presence / who's-online over hibernated WebSockets",label:"Presence",value:"presence"},{description:"Async message queues (push/pull consumers)",label:"Queues",value:"queue"},{description:"Typed R2 buckets + signed URLs (@lunora/storage)",label:"File storage",value:"storage"},{description:"Durable long-running workflows (step.do, sleep, branch)",label:"Workflows",value:"workflow"}],te=$e.map(e=>e.value),tr=e=>e==="email"?Ae:e,rr=(e,t)=>{const r=[];for(const a of e.split(",").map(o=>o.trim()).filter(Boolean))te.includes(a)?r.includes(a)||r.push(a):t(`init: unknown --add feature "${a}" — expected ${te.join(" | ")}; skipping.`);return r},Re=e=>e.resolveAuthUiItem===void 0?"auth-ui-react":e.resolveAuthUiItem(),ar=async e=>{const t=await Et(e.select),r=await Ee(e.text,e.projectName);return{label:"auth",names:[t],transformManifest:a=>Ne(a,r)}},or=async e=>{const t=await e.text(Lt,{placeholder:"you@yourdomain.com"}),r=Mt(t,a=>{e.logger.warn(a)});return{label:"email",names:[Ae],transformManifest:r===void 0?void 0:a=>At(a,r)}},nr=async(e,t)=>{const r=Re(e);if(r===void 0){e.logger.error(`init: ${Me}`);return}if(t)return{label:"auth-ui",names:[r]};const a=await Ee(e.text,e.projectName);return{label:"auth-ui",names:[r],transformManifest:o=>Ne(o,a)}},sr=async e=>{const t=await Ct(e.text,e.projectName);return{label:"storage",names:["storage"],transformManifest:r=>St(r,t)}},ir=(e,t)=>{const r=[];let a=!1;for(const o of t){if(o!=="auth-ui"){r.push({label:o,names:[tr(o)]});continue}const n=Re(e);if(n===void 0){e.logger.error(`init: ${Me}`),a=!0;continue}r.push({label:o,names:[n]})}return{plans:r,refused:a}},lr={auth:ar,"auth-ui":async(e,t)=>nr(e,t.includes("auth")),email:or,storage:sr},re=async e=>{if(e.preselected!==void 0&&e.preselected.length>0){const{plans:a,refused:o}=ir(e,e.preselected);return await e.applyAll(a)&&!o}if(!e.interactive)return e.logger.info("tip: add features later with `lunora add <ai|auth|backup|browser|cloudflare-access|crons|email|flags|hyperdrive|payment|presence|queue|storage|workflow>`."),!0;const t=await e.multiSelect("Which features do you want to add?",$e,{defaults:[]});if(t.length===0)return!0;const r=[];for(const a of t){const o=lr[a],n=o?await o(e,t):{label:a,names:[a]};n!==void 0&&r.push(n)}return await e.applyAll(r),!0},cr=[{description:"Adds an ignores entry to eslint.config.js",label:"ESLint",value:"eslint"},{description:"Writes .prettierignore",label:"Prettier",value:"prettier"},{description:"Adds negated patterns to biome.json",label:"Biome",value:"biome"},{description:"Writes ignorePatterns to .oxlintrc.json",label:"oxlint (oxc)",value:"oxlint"}],dr="Which linter/formatter do you use? We'll tell it to skip Lunora's generated files.",ur=async e=>{const t=e.interactive?await e.multiSelect(dr,cr,{defaults:e.detected}):[...e.detected];if(t.length===0)return[];const r=e.apply(t);return $t(r,e.logger),r},I="M 259.500 10.552 C 220.080 15.859, 182.424 32.566, 152.500 58.025 C 110.179 94.031, 85.380 137.183, 77.518 188.500 C 75.410 202.255, 74.569 225.677, 75.796 236.466 C 76.757 244.917, 76.683 245.692, 74.518 249.966 C 63.118 272.466, 53.141 303.876, 51.382 322.799 L 50.718 329.943 71.960 320.471 C 83.643 315.262, 93.326 311, 93.478 311 C 93.630 311, 96.547 316.063, 99.959 322.250 C 103.371 328.438, 107.249 334.850, 108.577 336.500 L 110.990 339.500 110.981 336 C 110.977 334.075, 111.499 324.991, 112.143 315.813 L 113.312 299.127 121.406 293.336 C 132.495 285.403, 149.593 271.554, 161 261.268 C 171.556 251.748, 189.116 235, 188.540 235 C 188.337 235, 183.069 238.648, 176.835 243.106 C 142.318 267.789, 68.537 314, 63.646 314 C 61.843 314, 72.791 281.179, 80.905 262.259 C 92.233 235.845, 107.473 212.389, 132.106 183.453 L 138.451 176 148.268 176 C 176.192 176, 197.512 187.154, 212.868 209.797 C 216.470 215.108, 217.035 216.595, 216.477 219.297 C 211.386 243.968, 202.359 274.496, 193.797 296 C 183.898 320.861, 167.147 352.101, 152.395 373.215 L 147.004 380.930 152.891 385.830 C 161.400 392.911, 165.563 396, 166.594 395.998 C 167.092 395.998, 168.772 391.641, 170.327 386.317 C 176.279 365.934, 188.422 338.749, 200.942 317.778 C 223.060 280.731, 256.432 244.369, 294.500 215.836 C 309.956 204.252, 313.937 201.603, 314.719 202.385 C 315.116 202.783, 315.449 213.096, 315.460 225.304 C 315.474 241.855, 315.021 250.405, 313.680 258.924 C 307.009 301.272, 291.175 336.677, 263.112 372 C 255.259 381.883, 227.182 410.673, 218.516 417.727 L 213.532 421.783 223.439 424.880 C 281.705 443.093, 349.165 436.018, 398.616 406.508 C 446.728 377.797, 483.322 331.466, 497.366 281.481 C 503.381 260.075, 504.480 250.741, 504.491 221 C 504.501 191.997, 503.598 184.047, 497.987 163.732 C 484.768 115.871, 452.505 72.708, 407.718 42.964 C 381.051 25.254, 352.818 14.828, 319.695 10.460 C 305.932 8.645, 273.298 8.695, 259.500 10.552",N=`/* The welcome page is a full-bleed starter — reset the browser's default
96
+ ${Ze}: ${et}`)},Re=[{description:"LLMs via Workers AI (summarize, generate, stream)",label:"AI",value:"ai"},{description:"Sign-up / sign-in (asks which provider)",label:"Authentication",value:"auth"},{description:"Copy-in auth screens for your framework (sign in/up, reset, 2FA)",label:"Auth UI",value:"auth-ui"},{description:"Snapshot + restore your Durable Object data",label:"Backups",value:"backup"},{description:"Headless browser screenshots + PDFs",label:"Browser rendering",value:"browser"},{description:"Zero Trust identity via Cloudflare Access",label:"Cloudflare Access",value:"cloudflare-access"},{description:"Scheduled jobs via Cron Triggers (@lunora/scheduler)",label:"Cron jobs",value:"crons"},{description:"Cloudflare Email Workers + a dev mail catcher",label:"Transactional email",value:"email"},{description:"OpenFeature feature flags (ctx.flags)",label:"Feature flags",value:"flags"},{description:"External Postgres/MySQL via Hyperdrive",label:"Hyperdrive",value:"hyperdrive"},{description:"Stripe-first payments (checkout, subscription, webhooks)",label:"Payments",value:"payment"},{description:"Live presence / who's-online over hibernated WebSockets",label:"Presence",value:"presence"},{description:"Async message queues (push/pull consumers)",label:"Queues",value:"queue"},{description:"Typed R2 buckets + signed URLs (@lunora/storage)",label:"File storage",value:"storage"},{description:"Durable long-running workflows (step.do, sleep, branch)",label:"Workflows",value:"workflow"}],te=Re.map(e=>e.value),tr=e=>e==="email"?Ae:e,rr=(e,t)=>{const r=[];for(const a of e.split(",").map(o=>o.trim()).filter(Boolean))te.includes(a)?r.includes(a)||r.push(a):t(`init: unknown --add feature "${a}" — expected ${te.join(" | ")}; skipping.`);return r},$e=e=>e.resolveAuthUiItem===void 0?"auth-ui-react":e.resolveAuthUiItem(),ar=async e=>{const t=await Et(e.select),r=await Ee(e.text,e.projectName);return{label:"auth",names:[t],transformManifest:a=>Ne(a,r)}},or=async e=>{const t=await e.text(Lt,{placeholder:"you@yourdomain.com"}),r=Mt(t,a=>{e.logger.warn(a)});return{label:"email",names:[Ae],transformManifest:r===void 0?void 0:a=>At(a,r)}},nr=async(e,t)=>{const r=$e(e);if(r===void 0){e.logger.error(`init: ${Me}`);return}if(t)return{label:"auth-ui",names:[r]};const a=await Ee(e.text,e.projectName);return{label:"auth-ui",names:[r],transformManifest:o=>Ne(o,a)}},sr=async e=>{const t=await Ct(e.text,e.projectName);return{label:"storage",names:["storage"],transformManifest:r=>St(r,t)}},ir=(e,t)=>{const r=[];let a=!1;for(const o of t){if(o!=="auth-ui"){r.push({label:o,names:[tr(o)]});continue}const n=$e(e);if(n===void 0){e.logger.error(`init: ${Me}`),a=!0;continue}r.push({label:o,names:[n]})}return{plans:r,refused:a}},lr={auth:ar,"auth-ui":async(e,t)=>nr(e,t.includes("auth")),email:or,storage:sr},re=async e=>{if(e.preselected!==void 0&&e.preselected.length>0){const{plans:a,refused:o}=ir(e,e.preselected);return await e.applyAll(a)&&!o}if(!e.interactive)return e.logger.info("tip: add features later with `lunora add <ai|auth|backup|browser|cloudflare-access|crons|email|flags|hyperdrive|payment|presence|queue|storage|workflow>`."),!0;const t=await e.multiSelect("Which features do you want to add?",Re,{defaults:[]});if(t.length===0)return!0;const r=[];for(const a of t){const o=lr[a],n=o?await o(e,t):{label:a,names:[a]};n!==void 0&&r.push(n)}return await e.applyAll(r),!0},cr=[{description:"Adds an ignores entry to eslint.config.js",label:"ESLint",value:"eslint"},{description:"Writes .prettierignore",label:"Prettier",value:"prettier"},{description:"Adds negated patterns to biome.json",label:"Biome",value:"biome"},{description:"Writes ignorePatterns to .oxlintrc.json",label:"oxlint (oxc)",value:"oxlint"}],dr="Which linter/formatter do you use? We'll tell it to skip Lunora's generated files.",ur=async e=>{const t=e.interactive?await e.multiSelect(dr,cr,{defaults:e.detected}):[...e.detected];if(t.length===0)return[];const r=e.apply(t);return Rt(r,e.logger),r},I="M 259.500 10.552 C 220.080 15.859, 182.424 32.566, 152.500 58.025 C 110.179 94.031, 85.380 137.183, 77.518 188.500 C 75.410 202.255, 74.569 225.677, 75.796 236.466 C 76.757 244.917, 76.683 245.692, 74.518 249.966 C 63.118 272.466, 53.141 303.876, 51.382 322.799 L 50.718 329.943 71.960 320.471 C 83.643 315.262, 93.326 311, 93.478 311 C 93.630 311, 96.547 316.063, 99.959 322.250 C 103.371 328.438, 107.249 334.850, 108.577 336.500 L 110.990 339.500 110.981 336 C 110.977 334.075, 111.499 324.991, 112.143 315.813 L 113.312 299.127 121.406 293.336 C 132.495 285.403, 149.593 271.554, 161 261.268 C 171.556 251.748, 189.116 235, 188.540 235 C 188.337 235, 183.069 238.648, 176.835 243.106 C 142.318 267.789, 68.537 314, 63.646 314 C 61.843 314, 72.791 281.179, 80.905 262.259 C 92.233 235.845, 107.473 212.389, 132.106 183.453 L 138.451 176 148.268 176 C 176.192 176, 197.512 187.154, 212.868 209.797 C 216.470 215.108, 217.035 216.595, 216.477 219.297 C 211.386 243.968, 202.359 274.496, 193.797 296 C 183.898 320.861, 167.147 352.101, 152.395 373.215 L 147.004 380.930 152.891 385.830 C 161.400 392.911, 165.563 396, 166.594 395.998 C 167.092 395.998, 168.772 391.641, 170.327 386.317 C 176.279 365.934, 188.422 338.749, 200.942 317.778 C 223.060 280.731, 256.432 244.369, 294.500 215.836 C 309.956 204.252, 313.937 201.603, 314.719 202.385 C 315.116 202.783, 315.449 213.096, 315.460 225.304 C 315.474 241.855, 315.021 250.405, 313.680 258.924 C 307.009 301.272, 291.175 336.677, 263.112 372 C 255.259 381.883, 227.182 410.673, 218.516 417.727 L 213.532 421.783 223.439 424.880 C 281.705 443.093, 349.165 436.018, 398.616 406.508 C 446.728 377.797, 483.322 331.466, 497.366 281.481 C 503.381 260.075, 504.480 250.741, 504.491 221 C 504.501 191.997, 503.598 184.047, 497.987 163.732 C 484.768 115.871, 452.505 72.708, 407.718 42.964 C 381.051 25.254, 352.818 14.828, 319.695 10.460 C 305.932 8.645, 273.298 8.695, 259.500 10.552",N=`/* The welcome page is a full-bleed starter — reset the browser's default
97
97
  body margin/padding so it sits flush; everything else is scoped under
98
98
  .lunora-welcome (collision-safe). */
99
99
  body {
@@ -1069,7 +1069,7 @@ render(
1069
1069
  <\/script>
1070
1070
 
1071
1071
  <App />
1072
- `,xr=`import "./app.css";
1072
+ `,kr=`import "./app.css";
1073
1073
 
1074
1074
  import { mount } from "svelte";
1075
1075
 
@@ -1079,7 +1079,7 @@ import Root from "./Root.svelte";
1079
1079
  const app = mount(Root, { target: document.getElementById("app")! });
1080
1080
 
1081
1081
  export default app;
1082
- `,B={react:{adapter:"@lunora/react",createViteTemplate:"react-ts",files:[{contents:vr,path:"src/main.tsx"},{contents:pr,path:"src/App.tsx"},{contents:N,path:"src/index.css"}],label:"React"},solid:{adapter:"@lunora/solid",createViteTemplate:"solid-ts",files:[{contents:yr,path:"src/index.tsx"},{contents:mr,path:"src/App.tsx"},{contents:N,path:"src/index.css"}],label:"Solid"},svelte:{adapter:"@lunora/svelte",createViteTemplate:"svelte-ts",files:[{contents:br,path:"src/Root.svelte"},{contents:xr,path:"src/main.ts"},{contents:fr,path:"src/App.svelte"},{contents:N,path:"src/app.css"}],label:"Svelte"},vanilla:{adapter:"lunorash/client",createViteTemplate:"vanilla-ts",files:[{contents:gr,path:"src/main.ts"},{contents:N,path:"src/style.css"}],label:"Vanilla"},vue:{adapter:"@lunora/vue",createViteTemplate:"vue-ts",files:[{contents:wr,path:"src/main.ts"},{contents:hr,path:"src/App.vue"},{contents:N,path:"src/style.css"}],label:"Vue"}},j=e=>Object.hasOwn(B,e),kr=`/**
1082
+ `,B={react:{adapter:"@lunora/react",createViteTemplate:"react-ts",files:[{contents:vr,path:"src/main.tsx"},{contents:pr,path:"src/App.tsx"},{contents:N,path:"src/index.css"}],label:"React"},solid:{adapter:"@lunora/solid",createViteTemplate:"solid-ts",files:[{contents:yr,path:"src/index.tsx"},{contents:mr,path:"src/App.tsx"},{contents:N,path:"src/index.css"}],label:"Solid"},svelte:{adapter:"@lunora/svelte",createViteTemplate:"svelte-ts",files:[{contents:br,path:"src/Root.svelte"},{contents:kr,path:"src/main.ts"},{contents:fr,path:"src/App.svelte"},{contents:N,path:"src/app.css"}],label:"Svelte"},vanilla:{adapter:"lunorash/client",createViteTemplate:"vanilla-ts",files:[{contents:gr,path:"src/main.ts"},{contents:N,path:"src/style.css"}],label:"Vanilla"},vue:{adapter:"@lunora/vue",createViteTemplate:"vue-ts",files:[{contents:wr,path:"src/main.ts"},{contents:hr,path:"src/App.vue"},{contents:N,path:"src/style.css"}],label:"Vue"}},j=e=>Object.hasOwn(B,e),xr=`/**
1083
1083
  * Rate-limit schema extension + plugin.
1084
1084
  *
1085
1085
  * Defines the \`ratelimit_buckets\` table used by \`createDbStore\` for durable,
@@ -1222,14 +1222,14 @@ export default app;
1222
1222
  # Leave it unset to use the page origin; set it to point at a deployed Worker:
1223
1223
  #
1224
1224
  # VITE_LUNORA_URL=https://my-app.example.workers.dev
1225
- `,Er={"@cloudflare/workers-types":"^4.20260611.1",wrangler:"^4.100.0"},C=(e,t,r,a)=>{const o=p(e,t);M(A(o),{recursive:!0}),w(o,r,"utf8"),a.push(o)},Nr=/\r?\n/,_r=e=>{const t=p(e,".gitignore"),r=m(t)?k(t,"utf8"):"",a=new Set(r.split(Nr)),o=ae.filter(i=>!a.has(i));if(o.length===0)return;const n=o.some(i=>!i.startsWith("!"))?[...o.filter(i=>!i.startsWith("!")),...ae.filter(i=>i.startsWith("!"))]:o,s=r.length>0&&!r.endsWith(`
1225
+ `,Er={"@cloudflare/workers-types":"^4.20260611.1",wrangler:"^4.100.0"},C=(e,t,r,a)=>{const o=p(e,t);M(A(o),{recursive:!0}),w(o,r,"utf8"),a.push(o)},Nr=/\r?\n/,_r=e=>{const t=p(e,".gitignore"),r=m(t)?x(t,"utf8"):"",a=new Set(r.split(Nr)),o=ae.filter(i=>!a.has(i));if(o.length===0)return;const n=o.some(i=>!i.startsWith("!"))?[...o.filter(i=>!i.startsWith("!")),...ae.filter(i=>i.startsWith("!"))]:o,s=r.length>0&&!r.endsWith(`
1226
1226
  `)?`
1227
1227
  `:"";w(t,`${r}${s}
1228
1228
  # Lunora
1229
1229
  ${n.join(`
1230
1230
  `)}
1231
- `,"utf8")},U=e=>e==="lunorash"||e.startsWith("@lunora/"),Ir=(e,t,r,a)=>U(e)?a.get(e)??r:t,S=(e,t,r)=>({...e,[t]:r}),oe=(e,t,r)=>Object.fromEntries(Object.entries(e).map(([a,o])=>[a,Ir(a,o,t,r)])),$r=async(e,t,r,a)=>{const o=p(e,"package.json"),n=JSON.parse(k(o,"utf8"));let s=S(n.dependencies??{},"lunorash",a);s=S(s,"@lunora/ratelimit",a),r.adapter.startsWith("@lunora/")&&(s=S(s,r.adapter,a));for(const[u,h]of Object.entries(r.extraDependencies??{}))s=S(s,u,h);let i=S(n.devDependencies??{},"@lunora/vite",a);i=S(i,"@lunora/studio",a);for(const[u,h]of Object.entries(Er))i=S(i,u,h);const l=[...Object.keys(s),...Object.keys(i)].filter(u=>U(u)),c=await ve(l,a);n.name=t,n.imports={...n.imports,"#lunora/*":"./lunora/*"},n.dependencies=oe(s,a,c),n.devDependencies=oe(i,a,c),n.scripts={...n.scripts,codegen:"lunora codegen",deploy:"vite build && lunora deploy"},w(o,`${JSON.stringify(n,void 0,4)}
1232
- `,"utf8")},Rr=["vite.config.ts","vite.config.mts","vite.config.js","vite.config.mjs"],Oe=e=>Rr.map(t=>p(e,t)).find(t=>m(t)),Or=(e,t)=>{const r=Oe(e);if(r===void 0){t.warn("overlay: no vite.config found in the create-vite base — add `lunora()` to your Vite plugins manually.");return}const a=Ie(k(r,"utf8"));a.changed&&w(r,a.code,"utf8")},Tr=async e=>{const{adapter:t,distTag:r,logger:a,name:o,target:n}=e,s=[];C(n,p("lunora","ratelimit","schema.ts"),kr,s),C(n,p("lunora","schema.ts"),Cr,s),C(n,p("lunora","messages.ts"),Sr,s),C(n,p("src","server.ts"),Lr,s),C(n,"wrangler.jsonc",Mr.replaceAll("__NAME__",o),s),C(n,".env.example",Ar,s);for(const i of t.files)C(n,i.path,i.contents,s);return Or(n,a),await $r(n,o,t,r),_r(n),s},Pr=["lunar","silver","silent","waning","waxing","crescent","cosmic","stellar","orbital","gibbous","twilight","midnight","shimmering","drifting","weightless"],Dr=["moon","tide","crater","comet","eclipse","halo","orbit","nebula","voyager","lander","rover","beacon","harbor","meadow","fox"],ne=e=>e[Math.floor(Math.random()*e.length)],Br=()=>`${ne(Pr)}-${ne(Dr)}`,jr=async()=>Rt.lookup("github.com").then(()=>!0,()=>!1),Ur=/^(?:gh|github):([^/]+)\/([^#/]+)(?:\/[^#]*)?(?:#(.+))?$/,Te=e=>{const t=Ur.exec(e);if(t===null)return;const[,r,a,o]=t;if(!(r===void 0||a===void 0))return{owner:r,ref:o??"HEAD",repo:a}},Vr=async e=>{const t=Te(e);if(t===void 0)return;const r=`https://codeload.github.com/${t.owner}/${t.repo}/tar.gz/${t.ref}`;try{const a=await fetch(r,{method:"HEAD"});return a.status===404?!1:a.ok?!0:void 0}catch{return}},Pe=async e=>e.isLocal||!(e.source===void 0||Te(e.source)!==void 0)?!0:await jr()?e.source!==void 0&&await Vr(e.source)===!1?(e.logger.error(`template source not found: ${e.source} — double-check --ref / --source, or browse the templates at https://lunora.sh/docs.`),!1):!0:(e.logger.error("you appear to be offline — connect to the internet and try again, or scaffold from a local template with `--from <dir>`."),!1),x={extras:"Let's finish setting up your app.",framework:"Which framework should we launch?",git:"Initialize a new git repository? (optional)",install:"Install dependencies now?",name:"Where should we land your project?",nextHeader:"Liftoff confirmed — explore your project!",packageManager:"Which package manager?"},Fr=new Set([".gitignore",".html",".js",".json",".jsonc",".md",".mjs",".ts",".tsx"]),Wr=`import { defineConfig } from "vite";
1231
+ `,"utf8")},U=e=>e==="lunorash"||e.startsWith("@lunora/"),Ir=(e,t,r,a)=>U(e)?a.get(e)??r:t,S=(e,t,r)=>({...e,[t]:r}),oe=(e,t,r)=>Object.fromEntries(Object.entries(e).map(([a,o])=>[a,Ir(a,o,t,r)])),Rr=async(e,t,r,a)=>{const o=p(e,"package.json"),n=JSON.parse(x(o,"utf8"));let s=S(n.dependencies??{},"lunorash",a);s=S(s,"@lunora/ratelimit",a),r.adapter.startsWith("@lunora/")&&(s=S(s,r.adapter,a));for(const[u,h]of Object.entries(r.extraDependencies??{}))s=S(s,u,h);let i=S(n.devDependencies??{},"@lunora/vite",a);i=S(i,"@lunora/studio",a);for(const[u,h]of Object.entries(Er))i=S(i,u,h);const l=[...Object.keys(s),...Object.keys(i)].filter(u=>U(u)),c=await ve(l,a);n.name=t,n.imports={...n.imports,"#lunora/*":"./lunora/*"},n.dependencies=oe(s,a,c),n.devDependencies=oe(i,a,c),n.scripts={...n.scripts,codegen:"lunora codegen",deploy:"vite build && lunora deploy"},w(o,`${JSON.stringify(n,void 0,4)}
1232
+ `,"utf8")},$r=["vite.config.ts","vite.config.mts","vite.config.js","vite.config.mjs"],Te=e=>$r.map(t=>p(e,t)).find(t=>m(t)),Tr=(e,t)=>{const r=Te(e);if(r===void 0){t.warn("overlay: no vite.config found in the create-vite base — add `lunora()` to your Vite plugins manually.");return}const a=Ie(x(r,"utf8"));a.changed&&w(r,a.code,"utf8")},Or=async e=>{const{adapter:t,distTag:r,logger:a,name:o,target:n}=e,s=[];C(n,p("lunora","ratelimit","schema.ts"),xr,s),C(n,p("lunora","schema.ts"),Cr,s),C(n,p("lunora","messages.ts"),Sr,s),C(n,p("src","server.ts"),Lr,s),C(n,"wrangler.jsonc",Mr.replaceAll("__NAME__",o),s),C(n,".env.example",Ar,s);for(const i of t.files)C(n,i.path,i.contents,s);return Tr(n,a),await Rr(n,o,t,r),_r(n),s},Pr=["lunar","silver","silent","waning","waxing","crescent","cosmic","stellar","orbital","gibbous","twilight","midnight","shimmering","drifting","weightless"],Dr=["moon","tide","crater","comet","eclipse","halo","orbit","nebula","voyager","lander","rover","beacon","harbor","meadow","fox"],ne=e=>e[Math.floor(Math.random()*e.length)],Br=()=>`${ne(Pr)}-${ne(Dr)}`,jr=async()=>$t.lookup("github.com").then(()=>!0,()=>!1),Ur=/^(?:gh|github):([^/]+)\/([^#/]+)(?:\/[^#]*)?(?:#(.+))?$/,Oe=e=>{const t=Ur.exec(e);if(t===null)return;const[,r,a,o]=t;if(!(r===void 0||a===void 0))return{owner:r,ref:o??"HEAD",repo:a}},Vr=async e=>{const t=Oe(e);if(t===void 0)return;const r=`https://codeload.github.com/${t.owner}/${t.repo}/tar.gz/${t.ref}`;try{const a=await fetch(r,{method:"HEAD"});return a.status===404?!1:a.ok?!0:void 0}catch{return}},Pe=async e=>e.isLocal||!(e.source===void 0||Oe(e.source)!==void 0)?!0:await jr()?e.source!==void 0&&await Vr(e.source)===!1?(e.logger.error(`template source not found: ${e.source} — double-check --ref / --source, or browse the templates at https://lunora.sh/docs.`),!1):!0:(e.logger.error("you appear to be offline — connect to the internet and try again, or scaffold from a local template with `--from <dir>`."),!1),k={extras:"Let's finish setting up your app.",framework:"Which framework should we launch?",git:"Initialize a new git repository? (optional)",install:"Install dependencies now?",name:"Where should we land your project?",nextHeader:"Liftoff confirmed — explore your project!",packageManager:"Which package manager?"},Fr=new Set([".gitignore",".html",".js",".json",".jsonc",".md",".mjs",".ts",".tsx"]),Wr=`import { defineConfig } from "vite";
1233
1233
  import { lunora } from "@lunora/vite";
1234
1234
 
1235
1235
  export default defineConfig({ plugins: [lunora()] });
@@ -1256,8 +1256,8 @@ export const send = mutation
1256
1256
  .mutation(async ({ args }) => {
1257
1257
  return { channelId: args.channelId, text: args.text };
1258
1258
  });
1259
- `,Kr="gh:anolilab/lunora/templates",qr=e=>{const t=e.lastIndexOf(".");return t===-1?!1:Fr.has(e.slice(t))},Gr=/^[a-z0-9_][a-z0-9\-_]*$/u,Yr=/([a-z0-9])([A-Z])/gu,Jr=/[^a-z0-9_]/gu,Xr=e=>{const t=e.replaceAll(Yr,"$1-$2").toLowerCase().replaceAll(Jr,"-").split("-").filter(r=>r.length>0);return t.length>0?t.join("-"):"my-app"},Qr=(e,t)=>e.replaceAll("{{name}}",t),Zr=async(e,t)=>{const r=new Set;for(const a of e)if(_(a)==="package.json")try{const o=JSON.parse(k(a,"utf8"));for(const n of["dependencies","devDependencies"])for(const s of Object.keys(o[n]??{}))U(s)&&r.add(s)}catch{}return ve(r,t)},ea=(e,t,r)=>{let a;try{a=JSON.parse(e)}catch{return e}let o=e;for(const n of["dependencies","devDependencies"])for(const s of Object.keys(a[n]??{})){if(!U(s))continue;const i=r.get(s)??t,l=lt(o,[n,s],i,{formattingOptions:{insertSpaces:!0,tabSize:4}});o=ct(o,l)}return o},ta=["@parcel/watcher","esbuild","lmdb","msgpackr-extract","rs-module-lexer","sharp","unrs-resolver","vue-demi","workerd"],ra=["cpu-features","protobufjs","ssh2"],De="pnpm-workspace.yaml",aa=()=>["# pnpm reads its settings from here (the package.json `pnpm` field is no longer read).","# Pre-approve the toolchain's native build scripts so `pnpm install` runs them","# without the interactive `pnpm approve-builds` step; deny the optional native","# builds a scaffold doesn't need (so no C/C++ toolchain is required).","allowBuilds:",...ta.map(e=>` '${e}': true`),...ra.map(e=>` '${e}': false`),""].join(`
1260
- `),Be=e=>{const t=p(e,De);m(t)||w(t,aa(),"utf8")},V=e=>{const t=[];for(const r of it(e,{includeDirs:!1,includeFiles:!0}))de(r.path).isSymbolicLink()||t.push(r.path);return t},se="vitejs/vite",ie=(e,t)=>{for(const r of V(e)){const a=p(t,fe(e,r));M(A(a),{recursive:!0}),Ge(r,a)}},je=async(e,t,r)=>{const a=V(e),o=[],n=we(),s=await Zr(a,n);for(const i of a){const l=fe(e,i),c=p(t,l);M(A(c),{recursive:!0});const u=k(i);let h=qr(i)?Qr(u.toString("utf8"),r):void 0;h!==void 0&&_(i)==="package.json"&&(h=ea(h,n,s)),h===void 0?w(c,u):w(c,h,"utf8"),o.push(c)}return o},H=(e,t,r)=>t!==void 0&&t.length>0?t:`${Kr}/${e}#${ye(r)}`,oa=e=>e.includes("..")?!1:e.startsWith("gh:")||e.startsWith("github:")||e.startsWith("https://"),E=(e,t)=>{e.info(`[dry-run] would ${t}`)},Ue=(e,t,r)=>(e.error(`init: the template at ${r} contains no files — nothing was scaffolded. Check the template name, \`--source\` layout and \`--ref\`.`),{code:f.NOT_FOUND,files:[],target:t}),Ve="Template files copied.",J=(e,t,r)=>{y()&&process.stdout.write(`
1261
- `),e.success(`scaffolded ${String(t.length)} files into ${r}`)},na=(e,t)=>{const{args:r,command:a}=nt(e,t);return`${a} ${r.join(" ")}`},Fe=(e,t)=>{let r=me(e);for(;;){if(t(r))return!0;const a=A(r);if(a===r)return!1;r=a}},sa=e=>{if(m(p(e,De)))return!0;const t=p(e,"package.json");if(!m(t))return!1;try{return JSON.parse(k(t,"utf8")).workspaces!==void 0}catch{return!1}},X=e=>Fe(e,sa),ia=e=>Fe(e,t=>m(p(t,".git"))),la=async(e,t)=>{if(e.yes===!0||!y()||ia(A(t)))return;if(!await Ce(x.git,{badge:v.git,defaultYes:!1})){await Se("Sounds good! You can always run git init manually.");return}if(e.dryRun===!0){E(e.logger,"initialize a git repository");return}const r=e.spawner??be;(await bt("Initializing a git repository…",()=>r({args:["init"],command:"git",cwd:t}))).code===0?await T("git","Initialized an empty git repository."):e.logger.warn("`git init` failed — initialize it yourself later with `git init`.")},ca=async(e,t,r,a)=>{const o=[{code:`cd ./${e}`,lead:"Enter your project directory using"}];t===void 0&&o.push({code:`${r} install`,lead:"Install dependencies with",tail:a?" from the workspace root":void 0}),o.push({code:at(r,"dev"),lead:"Run",tail:" to start the dev server."},{code:"lunora add",lead:"Add features like auth or storage using"});const n=[{code:"https://lunora.sh/docs",lead:"Read the docs at"},{code:"https://lunora.sh/chat",lead:"Stuck? Join the chat at"}];if(y()){await xt(v.next,x.nextHeader,o,n);return}const s=o.map(i=>`${i.lead} ${i.code}${i.tail??""}`);s.push("",...n.map(i=>`${i.lead} ${i.code}${i.tail??""}`)),await T("next",x.nextHeader,s.join(`
1262
- `))},da=e=>e.yes!==!0&&(e.installPrompt!==void 0||y()),ua=async(e,t)=>{if(!da(e)||X(A(t)))return;const r=rt(e.packageManagerProbe),[a]=r;if(a===void 0)return;if(!await(e.installPrompt?.confirmInstall??(async()=>Ce(x.install,{badge:v.deps,defaultYes:!0})))()){await Se("No problem! Remember to install dependencies after setup.");return}let n=a;if(r.length>1&&(n=e.installPrompt?await e.installPrompt.selectManager(r):await G(x.packageManager,r.map(u=>({label:u,value:u})),{badge:v.deps,default:a})??a),e.dryRun===!0){E(e.logger,`install dependencies with ${n}`);return}n==="pnpm"&&Be(t);const s=e.spawner??be,{args:i,command:l}=he(n);await T("deps",`Installing dependencies with ${n}…`);const c=await s({args:i,command:l,cwd:t});if(c.code!==0){e.logger.warn(`\`${l} install\` exited with code ${String(c.code)} — run it yourself in ${_(t)}/.`);return}return await T("deps",`Dependencies installed with ${n}.`),n},pa=async(e,t,r,a,o,n)=>{const s=p(e,t);if(!m(s))return o.error(`template not found in local source: ${s}`),{code:f.NOT_FOUND,files:[],target:r};const i=await je(s,r,a);return i.length===0?Ue(o,r,s):(n(),J(o,i,r),{code:0,files:i,target:r})},ha=async e=>{const{logger:t,markComplete:r,name:a,ref:o,source:n,target:s,templateType:i}=e,l=ue(p(pe(),"lunora-init-fetch-")),c=p(l,"template");try{const u=n!==void 0&&n.length>0?o:await ft(o,t),h=H(i,n,u);let d,b=[];if(await Le([{label:`${i} template fetched`,run:async()=>{d=await ge(h,{cwd:l,dir:c,force:!0,install:!1,silent:!0})}},{label:`files copied into ${a}/`,run:async()=>{b=await je(c,s,a)}}],{end:Ve,start:"Project initializing…"}),b.length===0)return Ue(t,s,d?.source??h);r();const $=V(c);return y()&&process.stdout.write(`
1263
- `),t.info(d?.commit?`template: ${d.source} @ ${d.commit} (${String($.length)} files)`:`template: ${d?.source??h} (${String($.length)} files)`),J(t,b,s),{code:0,files:b,target:s}}catch(u){if(u instanceof q)throw u;const{hints:h,message:d}=Zt(u,{ref:ye(o),remote:H(i,n,o),templateType:i});t.error(d);for(const b of h)t.warn(b);return{code:1,files:[],target:s}}finally{O(l,{force:!0,recursive:!0})}},ma=e=>{for(const t of["_gitignore","_npmrc","_gitattributes"]){const r=p(e,t);m(r)&&Ye(r,p(e,`.${t.slice(1)}`))}},fa=async e=>{const{framework:t,logger:r,markComplete:a,name:o,overlayBaseFrom:n,target:s}=e,i=B[t],l=ue(p(pe(),"lunora-vite-base-"));try{let c;if(n!==void 0&&(c=p(n,`template-${i.createViteTemplate}`),!m(c)))return r.error(`create-vite base not found on disk: ${c}`),{code:f.NOT_FOUND,files:[],target:s};const u=async()=>{if(c!==void 0){ie(c,s);return}const d=p(l,"base"),b=await mt(se,"main",r),$=`github:${se}/packages/create-vite/template-${i.createViteTemplate}#${b}`;await ge($,{cwd:l,dir:d,force:!0,install:!1,silent:!0}),ma(d),ie(d,s)};let h=[];return await Le([{label:`create-vite (${i.label}) base ready`,run:u},{label:`Lunora overlay applied (${i.label})`,run:async()=>{h=await Tr({adapter:i,distTag:we(),logger:r,name:o,target:s})}}],{end:Ve,start:"Project initializing…"}),a(),J(r,h,s),{code:0,files:[...V(s)],target:s}}catch(c){if(c instanceof q)throw c;const u=c instanceof Error?c.message:String(c);return r.error(`failed to scaffold the ${i.label} base: ${u}`),{code:1,files:[],target:s}}finally{O(l,{force:!0,recursive:!0})}},z=(e,t,r,a,o)=>(o.error(`init --in-place: could not ${e} ${t}: ${r instanceof Error?r.message:String(r)}`),{code:1,files:[],target:a}),ga=(e,t)=>{const r=p(e,"vite.config.ts");try{w(r,Wr,"utf8")}catch(a){return z("write",r,a,e,t)}return t.success(`created ${r} with lunora() plugin`),{code:0,files:[r],target:e}},va=(e,t,r)=>{let a;try{a=k(e,"utf8")}catch(n){return z("read",e,n,t,r)}const o=Ie(a);if(!o.changed)return r.info(`${e}: ${o.reason??"no changes needed"}`),{code:0,files:[],target:t};try{w(e,o.code,"utf8")}catch(n){return z("write",e,n,t,r)}return r.success(`patched ${e} — added lunora() plugin`),{code:0,files:[e],target:t}},wa=(e,t)=>{const r=p(e,"lunora"),a=p(r,"schema.ts");if(m(a))return t.info(`lunora/ already present — left ${a} untouched`),[];const o=[];try{M(r,{recursive:!0}),w(a,Hr,"utf8"),o.push(a);const n=p(r,"messages.ts");m(n)||(w(n,zr,"utf8"),o.push(n)),t.success(`scaffolded lunora/ (${String(o.length)} file(s))`)}catch(n){const s=n instanceof Error?n.message:String(n);t.error(`init --here: could not scaffold lunora/: ${s}`)}return o},We=e=>e==="sveltekit"||e==="nuxt"||e==="astro",ya=(e,t,r)=>{const{adapter:a,class:o,framework:n}=e;r.info(""),r.info(`detected framework: ${n} (class ${o})`),r.info("next steps:");const s=[a,"@lunora/client","@lunora/runtime","@lunora/server"];We(n)||s.push("@lunora/vite"),r.info(` 1. install the adapter: ${na(t,s)}`),r.info(" 2. run codegen: lunora codegen"),o==="A"?(r.info(" 3. compose one worker: wrap your worker entry with"),r.info(" createWorker({ httpRouter: <your framework SSR handler>, shardDO: ShardDO, ... })"),r.info(` 4. add the provider: mount the ${a} provider in your root layout/route`),r.info(" 5. make a loader live: preloadQuery() in a loader, usePreloadedQuery() in the component"),r.info(" see https://lunora.sh/docs/frameworks/reactive-loaders")):o==="B"?(r.info(" 3. inject Lunora: mount Lunora realtime under /_lunora/* in your server hook"),r.info(` (${n} owns its Cloudflare adapter — Lunora composes into its server entry)`),r.info(` 4. add the provider: mount the ${a} provider in your root layout`),r.info(" 5. read the guide: https://lunora.sh/docs/frameworks/deploy")):(r.info(" 3. add the provider: wrap your app with the LunoraProvider from @lunora/react"),r.info(" 4. read the guide: https://lunora.sh/docs/frameworks/bring-your-framework")),r.info("")},ba=(e,t,r)=>{if(We(t))return r.info(`${t} wires Lunora through its server entry, not a lunora() Vite plugin — leaving the Vite config alone (see next steps)`),{code:0,files:[],target:e};const a=Oe(e);return a===void 0?ga(e,r):va(a,e,r)},xa=(e,t)=>{const r=Vt(e),a=ba(e,r.framework,t);if(a.code!==0)return a;const o=wa(e,t);return ya(r,P(e),t),{code:0,files:[...a.files,...o],target:e}},ka=e=>e.yes!==!0&&(e.prompt!==void 0||(e.interactive??y())),le=async(e,t,r)=>{r.dryRun!==!0&&await ur({apply:a=>st(e,a),detected:ot(e),interactive:t,logger:r.logger,multiSelect:r.lintPrompt??((a,o,n)=>ke(a,o,{...n,badge:v.add}))})},Ca=async(e,t)=>{const r=ka(e),a=e.add===void 0?[]:rr(e.add,s=>{e.logger.warn(s)}),n={applyAll:async s=>{if(s.length===0)return!0;if(e.dryRun===!0)return E(e.logger,`add ${s.map(d=>d.label).join(", ")}`),!0;const i=[],l=y()?{error:d=>{i.push({level:"error",message:d})},info:()=>{},success:()=>{},warn:d=>{i.push({level:"warn",message:d})}}:e.logger,c=s.map(d=>({running:`adding ${d.label}…`,task:()=>It({allowUnsafeSource:e.allowUnsafeSource,cwd:t,from:e.registryFrom,logger:l,names:[...d.names],ref:e.ref,source:e.registrySource,transformManifest:d.transformManifest,yes:!0})})),u=`added ${s.map(d=>d.label).join(", ")}`,h=await kt(v.add,c,u);for(const{level:d,message:b}of i)e.logger[d](b);return h.every(d=>d.code===0)},interactive:r,logger:e.logger,multiSelect:e.prompt?.multiSelect??((s,i,l)=>ke(s,i,{...l,badge:v.add})),preselected:a.length>0?a:void 0,projectName:_(t),resolveAuthUiItem:()=>{let s;try{const i=JSON.parse(k(p(t,"package.json"),"utf8"));s={...i.dependencies,...i.devDependencies}}catch{return"auth-ui-react"}if(!Nt(s))return _t(s)??"auth-ui-react"},select:e.prompt?.select??((s,i,l)=>G(s,i,{...l,badge:v.add})),text:e.prompt?.text??((s,i)=>xe(s,{...i,badge:v.add}))};if(a.length>0){const s=await re(n);return await le(t,r,e),s}return y()&&await yt(x.extras),await re(n),await le(t,r,e),!0},F="react",He=[{description:"React SPA — official create-vite base + the Lunora layer (the default)",label:"React",value:"react"},{description:"Vue SPA — create-vite base + Lunora",label:"Vue",value:"vue"},{description:"Solid SPA — create-vite base + Lunora",label:"Solid",value:"solid"},{description:"Solid 2.0 SPA — the Solid 2 line (@solidjs/web, vite-plugin-solid 3)",label:"Solid 2",value:"solid-v2"},{description:"Svelte SPA — create-vite base + Lunora",label:"Svelte",value:"svelte"},{description:"Next.js (App Router) — OpenNext on Cloudflare + a standalone Lunora worker",label:"Next.js",value:"next"},{description:"TanStack Start (React) — SSR with live-loader routes",label:"TanStack Start · React",value:"tanstack-start-react"},{description:"TanStack Start (Solid)",label:"TanStack Start · Solid",value:"tanstack-start-solid"},{description:"Next.js App Router on Vite (vinext) — composed into the Lunora worker (experimental)",label:"vinext · App Router",value:"vinext"},{description:"Next.js Pages Router on Vite (vinext) — composed into one worker (experimental)",label:"vinext · Pages Router",value:"vinext-pages"},{description:"React Router (v7, framework mode) — SSR composed into the Lunora worker",label:"React Router",value:"react-router"},{description:"Astro (islands) — single-worker, Lunora composed into the adapter worker",label:"Astro",value:"astro"},{description:"AnalogJS (Angular) — single-worker, Lunora mounted in Nitro",label:"Analog",value:"analog"},{description:"Nuxt (Vue) — single-worker, Lunora mounted in Nitro",label:"Nuxt",value:"nuxt"},{description:"SvelteKit — single-worker, Lunora composed into the adapter worker",label:"SvelteKit",value:"sveltekit"},{description:"React Native (Expo) — an iOS/Android/web app + a Lunora worker backend",label:"React Native · Expo",value:"expo"},{description:"Worker only — no frontend",label:"Standalone",value:"standalone"}],ze=Object.keys(B).join("|"),Ke=He.filter(e=>!j(e.value)).map(e=>e.value),qe=Ke.join("|"),Sa=e=>j(e)?{framework:e,kind:"overlay"}:{kind:"template",templateType:e},La=async e=>e.vite!==void 0?{framework:e.vite,kind:"overlay"}:e.templateType!==void 0?{kind:"template",templateType:e.templateType}:!y()||e.yes===!0?{framework:F,kind:"overlay"}:Sa(await G(x.framework,He,{badge:v.tmpl,default:F})??F),Ma=e=>{if(y()||e.yes===!0)return;const t=[];if(e.name===void 0&&t.push("a project name (`lunora init <name>`)"),e.templateType===void 0&&e.vite===void 0&&t.push(`a framework — \`--vite <${ze}>\` for an SPA, or \`-t <${qe}>\` for a bespoke template`),t.length!==0)return`lunora init can't prompt in a non-interactive terminal — provide ${t.join(" and ")}, or pass --yes to accept the defaults.`},Aa=async(e,t,r,a,o)=>j(t)?await Pe({isLocal:e.overlayBaseFrom!==void 0,logger:e.logger})?(M(a,{recursive:!0}),fa({framework:t,logger:e.logger,markComplete:o,name:r,overlayBaseFrom:e.overlayBaseFrom,target:a})):{code:1,files:[],target:a}:(e.logger.error(`init: unknown framework "${t}". Supported overlays: ${Object.keys(B).join(", ")}.`),{code:f.USAGE,files:[],target:a}),Ea=async(e,t,r,a,o)=>e.from!==void 0?await pa(e.from,t,a,r,e.logger,o):e.source!==void 0&&e.source.length>0&&!e.allowUnsafeSource&&!oa(e.source)?(e.logger.error(`init: refusing --source ${e.source} — only gh:, github:, or https:// sources are allowed (and may not contain ".."). Re-run with --allow-unsafe-source if you really want this.`),{code:f.USAGE,files:[],target:a}):await Pe({isLocal:!1,logger:e.logger,source:H(t,e.source,e.ref)})?ha({logger:e.logger,markComplete:o,name:r,ref:e.ref,source:e.source,target:a,templateType:t}):{code:1,files:[],target:a},Na=(e,t)=>{if(X(t))return;let r;try{r=P(e)}catch{return}r==="pnpm"&&Be(e)},_a=async(e,t,r)=>{await wt("realtime backend on Cloudflare Workers + Durable Objects");const a=Ma(e);if(a!==void 0)return e.logger.error(a),{code:f.USAGE,files:[],target:""};const o=Br(),n=e.name??await xe(x.name,{badge:v.dir,default:o,placeholder:o}),s=await La(e),i=n.trim();if(i.length===0)return e.logger.error("init: refusing an empty project name — pass a directory name (e.g. `lunora init my-app`)."),{code:f.USAGE,files:[],target:""};if(i.includes("/")||i.includes("\\")||i===".."||i===".")return e.logger.error(`init: refusing project name "${i}" — must not contain path separators or be "." / "..".`),{code:f.USAGE,files:[],target:""};if(!Gr.test(i))return e.logger.error(`init: refusing project name "${i}" — a Cloudflare Worker name must be lowercase letters, digits, "-" or "_" (starting with a letter, digit or "_"), and wrangler rejects anything else. Try \`${Xr(i)}\`.`),{code:f.USAGE,files:[],target:""};const l=me(t,i),c=de(l,{throwIfNoEntry:!1});if(c?.isSymbolicLink()===!0)return e.logger.error(`init: refusing to scaffold into "${l}" — it is a symlink. Remove it, or scaffold into a different directory name.`),{code:f.CONFLICT,files:[],target:l};const u=c!==void 0;if(u&&ce(l).length>0)return e.logger.error(`target directory not empty: ${l}`),{code:f.CONFLICT,files:[],target:l};if(e.dryRun===!0){const d=s.kind==="overlay"?`the ${s.framework} create-vite overlay`:`the ${s.templateType} template`;return E(e.logger,`scaffold ${d} into ${l}`),{code:0,files:[],target:l}}r.record(l,u);const h=s.kind==="overlay"?await Aa(e,s.framework,i,l,r.complete):await Ea(e,s.templateType,i,l,r.complete);return h.code===0&&Na(l,t),h},W=(e,t)=>{const{target:r,targetPreExisted:a}=e;if(!(r===void 0||!m(r))){if(a===!0)for(const o of ce(r))O(p(r,o),{force:!0,recursive:!0});else O(r,{force:!0,recursive:!0});t.info(`removed the partially-created project at ${r}`)}},Ia=async(e,t,r)=>e.inPlace!==!0?_a(e,t,r):e.dryRun===!0?(E(e.logger,`configure Lunora into ${t}`),{code:0,files:[],target:t}):xa(t,e.logger),$a=async(e,t,r)=>{const a=await Ca(e,t.target),o=e.inPlace===!0?void 0:await ua(e,t.target);if(e.inPlace!==!0){await la(e,t.target);const n=o??P(t.target);await ca(_(t.target),o,n,X(r)),await er(e.logger)}return a},Ra=(e,t,r)=>{if(t.code!==0||e.ci===void 0)return;if(e.dryRun===!0){E(e.logger,`scaffold a ${e.ci} CI deploy pipeline`);return}const a=e.inPlace===!0?r:t.target;try{const o=P(a);jt(a,e.ci,o,e.logger)}catch{e.logger.warn(`--ci ${e.ci}: could not detect a package manager for this project — skipped the CI pipeline.`)}},Oa=async e=>{const t=e.cwd??process.cwd(),r={};let a;try{a=await Ia(e,t,{complete:()=>{r.target=void 0},record:(o,n)=>{r.target=o,r.targetPreExisted=n}}),a.code===0&&a.target!==""?(r.target=void 0,await $a(e,a,t)||(a={...a,code:1})):a.code!==0&&W(r,e.logger)}catch(o){if(o instanceof q)return W(r,e.logger),process.stdout.write("\n ✖ Setup cancelled — run `lunora init` again whenever you're ready. 🌙\n"),{code:130,files:[],target:""};throw W(r,e.logger),o}return Ra(e,a,t),a},Ta=e=>typeof e=="string"&&Ke.includes(e),Pa=(e,t)=>{if(e!==void 0){if(Dt(e))return e;t.warn(`init: unknown --ci "${e}" — expected github | gitlab; skipping CI scaffold.`)}},Da=e=>e===void 0?{}:Ta(e)?{templateType:e}:j(e)?{vite:e}:{error:`init: unknown --template "${e}" — expected a bespoke template (${qe}) or an overlay framework (${ze}).`},no=ut(({argument:e,cwd:t,logger:r,options:a})=>{const o=Da(a.template);return"error"in o?(r.error(o.error),{code:f.USAGE}):Oa({add:a.add,allowUnsafeSource:a.allowUnsafeSource===!0,cwd:t,ci:Pa(a.ci,r),dryRun:a.dryRun===!0,from:a.from,inPlace:a.here===!0,interactive:a.interactive===!0?!0:void 0,logger:r,name:e[0],ref:a.ref,source:a.source,templateType:o.templateType,vite:a.vite??o.vite,yes:a.yes===!0})});export{He as FRAMEWORK_CHOICES,no as execute,Ta as isTemplate,Da as resolveTemplateFlag,H as resolveTemplateSource,Oa as runInitCommand};
1259
+ `,Kr="gh:anolilab/lunora/templates",qr=e=>{const t=e.lastIndexOf(".");return t===-1?!1:Fr.has(e.slice(t))},Gr=/^[a-z0-9_][a-z0-9\-_]*$/u,Yr=/([a-z0-9])([A-Z])/gu,Jr=/[^a-z0-9_]/gu,Xr=e=>{const t=e.replaceAll(Yr,"$1-$2").toLowerCase().replaceAll(Jr,"-").split("-").filter(r=>r.length>0);return t.length>0?t.join("-"):"my-app"},Qr=(e,t)=>e.replaceAll("{{name}}",t),Zr=async(e,t)=>{const r=new Set;for(const a of e)if(_(a)==="package.json")try{const o=JSON.parse(x(a,"utf8"));for(const n of["dependencies","devDependencies"])for(const s of Object.keys(o[n]??{}))U(s)&&r.add(s)}catch{}return ve(r,t)},ea=(e,t,r)=>{let a;try{a=JSON.parse(e)}catch{return e}let o=e;for(const n of["dependencies","devDependencies"])for(const s of Object.keys(a[n]??{})){if(!U(s))continue;const i=r.get(s)??t,l=lt(o,[n,s],i,{formattingOptions:{insertSpaces:!0,tabSize:4}});o=ct(o,l)}return o},ta=["@parcel/watcher","esbuild","lmdb","msgpackr-extract","rs-module-lexer","sharp","unrs-resolver","vue-demi","workerd"],ra=["cpu-features","protobufjs","ssh2"],De="pnpm-workspace.yaml",aa=()=>["# pnpm reads its settings from here (the package.json `pnpm` field is no longer read).","# Pre-approve the toolchain's native build scripts so `pnpm install` runs them","# without the interactive `pnpm approve-builds` step; deny the optional native","# builds a scaffold doesn't need (so no C/C++ toolchain is required).","allowBuilds:",...ta.map(e=>` '${e}': true`),...ra.map(e=>` '${e}': false`),""].join(`
1260
+ `),Be=e=>{const t=p(e,De);m(t)||w(t,aa(),"utf8")},V=e=>{const t=[];for(const r of it(e,{includeDirs:!1,includeFiles:!0}))de(r.path).isSymbolicLink()||t.push(r.path);return t},se="vitejs/vite",ie=(e,t)=>{for(const r of V(e)){const a=p(t,fe(e,r));M(A(a),{recursive:!0}),Ge(r,a)}},je=async(e,t,r)=>{const a=V(e),o=[],n=we(),s=await Zr(a,n);for(const i of a){const l=fe(e,i),c=p(t,l);M(A(c),{recursive:!0});const u=x(i);let h=qr(i)?Qr(u.toString("utf8"),r):void 0;h!==void 0&&_(i)==="package.json"&&(h=ea(h,n,s)),h===void 0?w(c,u):w(c,h,"utf8"),o.push(c)}return o},H=(e,t,r)=>t!==void 0&&t.length>0?t:`${Kr}/${e}#${ye(r)}`,oa=e=>e.includes("..")?!1:e.startsWith("gh:")||e.startsWith("github:")||e.startsWith("https://"),E=(e,t)=>{e.info(`[dry-run] would ${t}`)},Ue=(e,t,r)=>(e.error(`init: the template at ${r} contains no files — nothing was scaffolded. Check the template name, \`--source\` layout and \`--ref\`.`),{code:f.NOT_FOUND,files:[],target:t}),Ve="Template files copied.",J=(e,t,r)=>{y()&&process.stdout.write(`
1261
+ `),e.success(`scaffolded ${String(t.length)} files into ${r}`)},na=(e,t)=>{const{args:r,command:a}=nt(e,t);return`${a} ${r.join(" ")}`},Fe=(e,t)=>{let r=me(e);for(;;){if(t(r))return!0;const a=A(r);if(a===r)return!1;r=a}},sa=e=>{if(m(p(e,De)))return!0;const t=p(e,"package.json");if(!m(t))return!1;try{return JSON.parse(x(t,"utf8")).workspaces!==void 0}catch{return!1}},X=e=>Fe(e,sa),ia=e=>Fe(e,t=>m(p(t,".git"))),la=async(e,t)=>{if(e.yes===!0||!y()||ia(A(t)))return;if(!await Ce(k.git,{badge:v.git,defaultYes:!1})){await Se("Sounds good! You can always run git init manually.");return}if(e.dryRun===!0){E(e.logger,"initialize a git repository");return}const r=e.spawner??be;(await bt("Initializing a git repository…",()=>r({args:["init"],command:"git",cwd:t}))).code===0?await O("git","Initialized an empty git repository."):e.logger.warn("`git init` failed — initialize it yourself later with `git init`.")},ca=async(e,t,r,a)=>{const o=[{code:`cd ./${e}`,lead:"Enter your project directory using"}];t===void 0&&o.push({code:`${r} install`,lead:"Install dependencies with",tail:a?" from the workspace root":void 0}),o.push({code:at(r,"dev"),lead:"Run",tail:" to start the dev server."},{code:"lunora add",lead:"Add features like auth or storage using"});const n=[{code:"https://lunora.sh/docs",lead:"Read the docs at"},{code:"https://lunora.sh/chat",lead:"Stuck? Join the chat at"}];if(y()){await kt(v.next,k.nextHeader,o,n);return}const s=o.map(i=>`${i.lead} ${i.code}${i.tail??""}`);s.push("",...n.map(i=>`${i.lead} ${i.code}${i.tail??""}`)),await O("next",k.nextHeader,s.join(`
1262
+ `))},da=e=>e.yes!==!0&&(e.installPrompt!==void 0||y()),ua=async(e,t)=>{if(!da(e)||X(A(t)))return;const r=rt(e.packageManagerProbe),[a]=r;if(a===void 0)return;if(!await(e.installPrompt?.confirmInstall??(async()=>Ce(k.install,{badge:v.deps,defaultYes:!0})))()){await Se("No problem! Remember to install dependencies after setup.");return}let n=a;if(r.length>1&&(n=e.installPrompt?await e.installPrompt.selectManager(r):await G(k.packageManager,r.map(u=>({label:u,value:u})),{badge:v.deps,default:a})??a),e.dryRun===!0){E(e.logger,`install dependencies with ${n}`);return}n==="pnpm"&&Be(t);const s=e.spawner??be,{args:i,command:l}=he(n);await O("deps",`Installing dependencies with ${n}…`);const c=await s({args:i,command:l,cwd:t});if(c.code!==0){e.logger.warn(`\`${l} install\` exited with code ${String(c.code)} — run it yourself in ${_(t)}/.`);return}return await O("deps",`Dependencies installed with ${n}.`),n},pa=async(e,t,r,a,o,n)=>{const s=p(e,t);if(!m(s))return o.error(`template not found in local source: ${s}`),{code:f.NOT_FOUND,files:[],target:r};const i=await je(s,r,a);return i.length===0?Ue(o,r,s):(n(),J(o,i,r),{code:0,files:i,target:r})},ha=async e=>{const{logger:t,markComplete:r,name:a,ref:o,source:n,target:s,templateType:i}=e,l=ue(p(pe(),"lunora-init-fetch-")),c=p(l,"template");try{const u=n!==void 0&&n.length>0?o:await ft(o,t),h=H(i,n,u);let d,b=[];if(await Le([{label:`${i} template fetched`,run:async()=>{d=await ge(h,{cwd:l,dir:c,force:!0,install:!1,silent:!0})}},{label:`files copied into ${a}/`,run:async()=>{b=await je(c,s,a)}}],{end:Ve,start:"Project initializing…"}),b.length===0)return Ue(t,s,d?.source??h);r();const R=V(c);return y()&&process.stdout.write(`
1263
+ `),t.info(d?.commit?`template: ${d.source} @ ${d.commit} (${String(R.length)} files)`:`template: ${d?.source??h} (${String(R.length)} files)`),J(t,b,s),{code:0,files:b,target:s}}catch(u){if(u instanceof q)throw u;const{hints:h,message:d}=Zt(u,{ref:ye(o),remote:H(i,n,o),templateType:i});t.error(d);for(const b of h)t.warn(b);return{code:1,files:[],target:s}}finally{T(l,{force:!0,recursive:!0})}},ma=e=>{for(const t of["_gitignore","_npmrc","_gitattributes"]){const r=p(e,t);m(r)&&Ye(r,p(e,`.${t.slice(1)}`))}},fa=async e=>{const{framework:t,logger:r,markComplete:a,name:o,overlayBaseFrom:n,target:s}=e,i=B[t],l=ue(p(pe(),"lunora-vite-base-"));try{let c;if(n!==void 0&&(c=p(n,`template-${i.createViteTemplate}`),!m(c)))return r.error(`create-vite base not found on disk: ${c}`),{code:f.NOT_FOUND,files:[],target:s};const u=async()=>{if(c!==void 0){ie(c,s);return}const d=p(l,"base"),b=await mt(se,"main",r),R=`github:${se}/packages/create-vite/template-${i.createViteTemplate}#${b}`;await ge(R,{cwd:l,dir:d,force:!0,install:!1,silent:!0}),ma(d),ie(d,s)};let h=[];return await Le([{label:`create-vite (${i.label}) base ready`,run:u},{label:`Lunora overlay applied (${i.label})`,run:async()=>{h=await Or({adapter:i,distTag:we(),logger:r,name:o,target:s})}}],{end:Ve,start:"Project initializing…"}),a(),J(r,h,s),{code:0,files:[...V(s)],target:s}}catch(c){if(c instanceof q)throw c;const u=c instanceof Error?c.message:String(c);return r.error(`failed to scaffold the ${i.label} base: ${u}`),{code:1,files:[],target:s}}finally{T(l,{force:!0,recursive:!0})}},z=(e,t,r,a,o)=>(o.error(`init --in-place: could not ${e} ${t}: ${r instanceof Error?r.message:String(r)}`),{code:1,files:[],target:a}),ga=(e,t)=>{const r=p(e,"vite.config.ts");try{w(r,Wr,"utf8")}catch(a){return z("write",r,a,e,t)}return t.success(`created ${r} with lunora() plugin`),{code:0,files:[r],target:e}},va=(e,t,r)=>{let a;try{a=x(e,"utf8")}catch(n){return z("read",e,n,t,r)}const o=Ie(a);if(!o.changed)return r.info(`${e}: ${o.reason??"no changes needed"}`),{code:0,files:[],target:t};try{w(e,o.code,"utf8")}catch(n){return z("write",e,n,t,r)}return r.success(`patched ${e} — added lunora() plugin`),{code:0,files:[e],target:t}},wa=(e,t)=>{const r=p(e,"lunora"),a=p(r,"schema.ts");if(m(a))return t.info(`lunora/ already present — left ${a} untouched`),[];const o=[];try{M(r,{recursive:!0}),w(a,Hr,"utf8"),o.push(a);const n=p(r,"messages.ts");m(n)||(w(n,zr,"utf8"),o.push(n)),t.success(`scaffolded lunora/ (${String(o.length)} file(s))`)}catch(n){const s=n instanceof Error?n.message:String(n);t.error(`init --here: could not scaffold lunora/: ${s}`)}return o},We=e=>e==="sveltekit"||e==="nuxt"||e==="astro",ya=(e,t,r)=>{const{adapter:a,class:o,framework:n}=e;r.info(""),r.info(`detected framework: ${n} (class ${o})`),r.info("next steps:");const s=[a,"@lunora/client","@lunora/runtime","@lunora/server"];We(n)||s.push("@lunora/vite"),r.info(` 1. install the adapter: ${na(t,s)}`),r.info(" 2. run codegen: lunora codegen"),o==="A"?(r.info(" 3. compose one worker: wrap your worker entry with"),r.info(" createWorker({ httpRouter: <your framework SSR handler>, shardDO: ShardDO, ... })"),r.info(` 4. add the provider: mount the ${a} provider in your root layout/route`),r.info(" 5. make a loader live: preloadQuery() in a loader, usePreloadedQuery() in the component"),r.info(" see https://lunora.sh/docs/frameworks/reactive-loaders")):o==="B"?(r.info(" 3. inject Lunora: mount Lunora realtime under /_lunora/* in your server hook"),r.info(` (${n} owns its Cloudflare adapter — Lunora composes into its server entry)`),r.info(` 4. add the provider: mount the ${a} provider in your root layout`),r.info(" 5. read the guide: https://lunora.sh/docs/frameworks/deploy")):(r.info(" 3. add the provider: wrap your app with the LunoraProvider from @lunora/react"),r.info(" 4. read the guide: https://lunora.sh/docs/frameworks/bring-your-framework")),r.info("")},ba=(e,t,r)=>{if(We(t))return r.info(`${t} wires Lunora through its server entry, not a lunora() Vite plugin — leaving the Vite config alone (see next steps)`),{code:0,files:[],target:e};const a=Te(e);return a===void 0?ga(e,r):va(a,e,r)},ka=(e,t)=>{const r=Vt(e),a=ba(e,r.framework,t);if(a.code!==0)return a;const o=wa(e,t);return ya(r,P(e),t),{code:0,files:[...a.files,...o],target:e}},xa=e=>e.yes!==!0&&(e.prompt!==void 0||(e.interactive??y())),le=async(e,t,r)=>{r.dryRun!==!0&&await ur({apply:a=>st(e,a),detected:ot(e),interactive:t,logger:r.logger,multiSelect:r.lintPrompt??((a,o,n)=>xe(a,o,{...n,badge:v.add}))})},Ca=async(e,t)=>{const r=xa(e),a=e.add===void 0?[]:rr(e.add,s=>{e.logger.warn(s)}),n={applyAll:async s=>{if(s.length===0)return!0;if(e.dryRun===!0)return E(e.logger,`add ${s.map(d=>d.label).join(", ")}`),!0;const i=[],l=y()?{error:d=>{i.push({level:"error",message:d})},info:()=>{},success:()=>{},warn:d=>{i.push({level:"warn",message:d})}}:e.logger,c=s.map(d=>({running:`adding ${d.label}…`,task:()=>It({allowUnsafeSource:e.allowUnsafeSource,cwd:t,from:e.registryFrom,logger:l,names:[...d.names],ref:e.ref,source:e.registrySource,transformManifest:d.transformManifest,yes:!0})})),u=`added ${s.map(d=>d.label).join(", ")}`,h=await xt(v.add,c,u);for(const{level:d,message:b}of i)e.logger[d](b);return h.every(d=>d.code===0)},interactive:r,logger:e.logger,multiSelect:e.prompt?.multiSelect??((s,i,l)=>xe(s,i,{...l,badge:v.add})),preselected:a.length>0?a:void 0,projectName:_(t),resolveAuthUiItem:()=>{let s;try{const i=JSON.parse(x(p(t,"package.json"),"utf8"));s={...i.dependencies,...i.devDependencies}}catch{return"auth-ui-react"}if(!Nt(s))return _t(s)??"auth-ui-react"},select:e.prompt?.select??((s,i,l)=>G(s,i,{...l,badge:v.add})),text:e.prompt?.text??((s,i)=>ke(s,{...i,badge:v.add}))};if(a.length>0){const s=await re(n);return await le(t,r,e),s}return y()&&await yt(k.extras),await re(n),await le(t,r,e),!0},F="react",He=[{description:"React SPA — official create-vite base + the Lunora layer (the default)",label:"React",value:"react"},{description:"Vue SPA — create-vite base + Lunora",label:"Vue",value:"vue"},{description:"Solid SPA — create-vite base + Lunora",label:"Solid",value:"solid"},{description:"Solid 2.0 SPA — the Solid 2 line (@solidjs/web, vite-plugin-solid 3)",label:"Solid 2",value:"solid-v2"},{description:"Svelte SPA — create-vite base + Lunora",label:"Svelte",value:"svelte"},{description:"React SPA on Rsbuild — the Worker runs under wrangler dev behind the dev server",label:"React · Rsbuild",value:"rspack-react"},{description:"Next.js (App Router) — OpenNext on Cloudflare + a standalone Lunora worker",label:"Next.js",value:"next"},{description:"TanStack Start (React) — SSR with live-loader routes",label:"TanStack Start · React",value:"tanstack-start-react"},{description:"TanStack Start (React) on Rsbuild — SSR composed into the Lunora worker",label:"TanStack Start · React · Rsbuild",value:"tanstack-start-react-rspack"},{description:"TanStack Start (Solid)",label:"TanStack Start · Solid",value:"tanstack-start-solid"},{description:"Next.js App Router on Vite (vinext) — composed into the Lunora worker (experimental)",label:"vinext · App Router",value:"vinext"},{description:"Next.js Pages Router on Vite (vinext) — composed into one worker (experimental)",label:"vinext · Pages Router",value:"vinext-pages"},{description:"React Router (v7, framework mode) — SSR composed into the Lunora worker",label:"React Router",value:"react-router"},{description:"Astro (islands) — single-worker, Lunora composed into the adapter worker",label:"Astro",value:"astro"},{description:"AnalogJS (Angular) — single-worker, Lunora mounted in Nitro",label:"Analog",value:"analog"},{description:"Nuxt (Vue) — single-worker, Lunora mounted in Nitro",label:"Nuxt",value:"nuxt"},{description:"SvelteKit — single-worker, Lunora composed into the adapter worker",label:"SvelteKit",value:"sveltekit"},{description:"React Native (Expo) — an iOS/Android/web app + a Lunora worker backend",label:"React Native · Expo",value:"expo"},{description:"Worker only — no frontend",label:"Standalone",value:"standalone"}],ze=Object.keys(B).join("|"),Ke=He.filter(e=>!j(e.value)).map(e=>e.value),qe=Ke.join("|"),Sa=e=>j(e)?{framework:e,kind:"overlay"}:{kind:"template",templateType:e},La=async e=>e.vite!==void 0?{framework:e.vite,kind:"overlay"}:e.templateType!==void 0?{kind:"template",templateType:e.templateType}:!y()||e.yes===!0?{framework:F,kind:"overlay"}:Sa(await G(k.framework,He,{badge:v.tmpl,default:F})??F),Ma=e=>{if(y()||e.yes===!0)return;const t=[];if(e.name===void 0&&t.push("a project name (`lunora init <name>`)"),e.templateType===void 0&&e.vite===void 0&&t.push(`a framework — \`--vite <${ze}>\` for an SPA, or \`-t <${qe}>\` for a bespoke template`),t.length!==0)return`lunora init can't prompt in a non-interactive terminal — provide ${t.join(" and ")}, or pass --yes to accept the defaults.`},Aa=async(e,t,r,a,o)=>j(t)?await Pe({isLocal:e.overlayBaseFrom!==void 0,logger:e.logger})?(M(a,{recursive:!0}),fa({framework:t,logger:e.logger,markComplete:o,name:r,overlayBaseFrom:e.overlayBaseFrom,target:a})):{code:1,files:[],target:a}:(e.logger.error(`init: unknown framework "${t}". Supported overlays: ${Object.keys(B).join(", ")}.`),{code:f.USAGE,files:[],target:a}),Ea=async(e,t,r,a,o)=>e.from!==void 0?await pa(e.from,t,a,r,e.logger,o):e.source!==void 0&&e.source.length>0&&!e.allowUnsafeSource&&!oa(e.source)?(e.logger.error(`init: refusing --source ${e.source} — only gh:, github:, or https:// sources are allowed (and may not contain ".."). Re-run with --allow-unsafe-source if you really want this.`),{code:f.USAGE,files:[],target:a}):await Pe({isLocal:!1,logger:e.logger,source:H(t,e.source,e.ref)})?ha({logger:e.logger,markComplete:o,name:r,ref:e.ref,source:e.source,target:a,templateType:t}):{code:1,files:[],target:a},Na=(e,t)=>{if(X(t))return;let r;try{r=P(e)}catch{return}r==="pnpm"&&Be(e)},_a=async(e,t,r)=>{await wt("realtime backend on Cloudflare Workers + Durable Objects");const a=Ma(e);if(a!==void 0)return e.logger.error(a),{code:f.USAGE,files:[],target:""};const o=Br(),n=e.name??await ke(k.name,{badge:v.dir,default:o,placeholder:o}),s=await La(e),i=n.trim();if(i.length===0)return e.logger.error("init: refusing an empty project name — pass a directory name (e.g. `lunora init my-app`)."),{code:f.USAGE,files:[],target:""};if(i.includes("/")||i.includes("\\")||i===".."||i===".")return e.logger.error(`init: refusing project name "${i}" — must not contain path separators or be "." / "..".`),{code:f.USAGE,files:[],target:""};if(!Gr.test(i))return e.logger.error(`init: refusing project name "${i}" — a Cloudflare Worker name must be lowercase letters, digits, "-" or "_" (starting with a letter, digit or "_"), and wrangler rejects anything else. Try \`${Xr(i)}\`.`),{code:f.USAGE,files:[],target:""};const l=me(t,i),c=de(l,{throwIfNoEntry:!1});if(c?.isSymbolicLink()===!0)return e.logger.error(`init: refusing to scaffold into "${l}" — it is a symlink. Remove it, or scaffold into a different directory name.`),{code:f.CONFLICT,files:[],target:l};const u=c!==void 0;if(u&&ce(l).length>0)return e.logger.error(`target directory not empty: ${l}`),{code:f.CONFLICT,files:[],target:l};if(e.dryRun===!0){const d=s.kind==="overlay"?`the ${s.framework} create-vite overlay`:`the ${s.templateType} template`;return E(e.logger,`scaffold ${d} into ${l}`),{code:0,files:[],target:l}}r.record(l,u);const h=s.kind==="overlay"?await Aa(e,s.framework,i,l,r.complete):await Ea(e,s.templateType,i,l,r.complete);return h.code===0&&Na(l,t),h},W=(e,t)=>{const{target:r,targetPreExisted:a}=e;if(!(r===void 0||!m(r))){if(a===!0)for(const o of ce(r))T(p(r,o),{force:!0,recursive:!0});else T(r,{force:!0,recursive:!0});t.info(`removed the partially-created project at ${r}`)}},Ia=async(e,t,r)=>e.inPlace!==!0?_a(e,t,r):e.dryRun===!0?(E(e.logger,`configure Lunora into ${t}`),{code:0,files:[],target:t}):ka(t,e.logger),Ra=async(e,t,r)=>{const a=await Ca(e,t.target),o=e.inPlace===!0?void 0:await ua(e,t.target);if(e.inPlace!==!0){await la(e,t.target);const n=o??P(t.target);await ca(_(t.target),o,n,X(r)),await er(e.logger)}return a},$a=(e,t,r)=>{if(t.code!==0||e.ci===void 0)return;if(e.dryRun===!0){E(e.logger,`scaffold a ${e.ci} CI deploy pipeline`);return}const a=e.inPlace===!0?r:t.target;try{const o=P(a);jt(a,e.ci,o,e.logger)}catch{e.logger.warn(`--ci ${e.ci}: could not detect a package manager for this project — skipped the CI pipeline.`)}},Ta=async e=>{const t=e.cwd??process.cwd(),r={};let a;try{a=await Ia(e,t,{complete:()=>{r.target=void 0},record:(o,n)=>{r.target=o,r.targetPreExisted=n}}),a.code===0&&a.target!==""?(r.target=void 0,await Ra(e,a,t)||(a={...a,code:1})):a.code!==0&&W(r,e.logger)}catch(o){if(o instanceof q)return W(r,e.logger),process.stdout.write("\n ✖ Setup cancelled — run `lunora init` again whenever you're ready. 🌙\n"),{code:130,files:[],target:""};throw W(r,e.logger),o}return $a(e,a,t),a},Oa=e=>typeof e=="string"&&Ke.includes(e),Pa=(e,t)=>{if(e!==void 0){if(Dt(e))return e;t.warn(`init: unknown --ci "${e}" — expected github | gitlab; skipping CI scaffold.`)}},Da=e=>e===void 0?{}:Oa(e)?{templateType:e}:j(e)?{vite:e}:{error:`init: unknown --template "${e}" — expected a bespoke template (${qe}) or an overlay framework (${ze}).`},no=ut(({argument:e,cwd:t,logger:r,options:a})=>{const o=Da(a.template);return"error"in o?(r.error(o.error),{code:f.USAGE}):Ta({add:a.add,allowUnsafeSource:a.allowUnsafeSource===!0,cwd:t,ci:Pa(a.ci,r),dryRun:a.dryRun===!0,from:a.from,inPlace:a.here===!0,interactive:a.interactive===!0?!0:void 0,logger:r,name:e[0],ref:a.ref,source:a.source,templateType:o.templateType,vite:a.vite??o.vite,yes:a.yes===!0})});export{He as FRAMEWORK_CHOICES,no as execute,Oa as isTemplate,Da as resolveTemplateFlag,H as resolveTemplateSource,Ta as runInitCommand};
@@ -1 +1 @@
1
- import{C as i,R as m,V as p,r as s}from"./cli-o9i8dzCS.mjs";import"./EXIT_CODE-08cwt3MK.mjs";import"./createLogger-Cl18I8AX.mjs";import"./render-lunora-error-DgaSmNLc.mjs";export{i as COMMANDS,m as REGISTERED_COMMAND_NAMES,p as VERSION,s as runCli};
1
+ import{C as i,R as m,V as p,r as s}from"./cli-D1ZleZMH.mjs";import"./EXIT_CODE-08cwt3MK.mjs";import"./createLogger-Cl18I8AX.mjs";import"./render-lunora-error-DgaSmNLc.mjs";export{i as COMMANDS,m as REGISTERED_COMMAND_NAMES,p as VERSION,s as runCli};
@@ -1,2 +1,2 @@
1
- import{mkdirSync as A,readFileSync as S,lstatSync as D,writeFileSync as B}from"node:fs";import{join as m,dirname as y}from"node:path";import{fileURLToPath as E}from"node:url";import{isLunoraError as L,findSolutionByMessage as I}from"@lunora/errors";import{createCerebro as j}from"@visulima/cerebro";import T from"@visulima/cerebro/command/completion";import _ from"@visulima/cerebro/command/version";import{O as i}from"./output-format-B4eQHi5y.mjs";import{A as p,T as l}from"./deploy-target-DCWwiuAe.mjs";import{SDK_LANGUAGES as P}from"@lunora/codegen";import{exitCodeForError as U,EXIT_CODE as M}from"./EXIT_CODE-08cwt3MK.mjs";import{setCommandLogger as v,createLogger as x}from"./createLogger-Cl18I8AX.mjs";import{r as W}from"./render-lunora-error-DgaSmNLc.mjs";import{homedir as J}from"node:os";import{addArgsFor as F,detectPackageManager as K}from"@lunora/config";const H={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},i]},b="lunora.advisor.map.json",$={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 ${b})`,name:"baseline",type:String},{description:"Inspect a single procedure by `file#exportName`",name:"entry",type:String},i,{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 ${b})`,name:"out",type:String},{description:"Write the map artifact to disk (the default)",name:"write",type:Boolean},{description:"Don't write the map artifact to disk — report only",name:"no-write",type:Boolean}]},V={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:[i]},G={argument:{description:"create | list | restore <id|file> | retention | prune | 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 list --format json","Same, as a single JSON document on stdout"],["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 retention","Show what the platform's retention would delete next"],["lunora backup prune","Delete the snapshots past the retention window (the only command that deletes backups)"],["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},i,{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 destructive step without prompting: a production pitr --restore, or backup prune",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}]},q={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:"Override the schema-drift gate for this run (build even with breaking schema drift and no migration; the committed baseline is not advanced)",name:"allow-schema-drift",type:Boolean},{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},i,{description:"Directory to write the bundled Worker to (default .lunora/build)",name:"out-dir",type:String},{description:"Fail the build 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 build on ERROR-level codegen advisories (the gate defaults to on in CI, off locally). Never downgrades platform diagnostics.",name:"no-strict-advisories",type:Boolean},l]},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},i,{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},l]},Y={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 list --format json","List container instances as JSON (also `info`, `images list`)"],["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},{...i,description:"Output format: pretty (default) or json (read subcommands: list | info | images list)"}]},Q={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 --migrate-yes --migrate-url <url>","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 for this run (deploy even with breaking schema drift and no migration; the committed baseline is not advanced — use --update-schema-baseline to accept the new shape)",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},i,{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},l,{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}]},X={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},{...i,description:"Output format: pretty (default) or json (`list` only)"},{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}]},Z={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, ready/starting)"],["lunora dev status --json","Same as JSON — poll `.ready` to gate a dependent step in a task graph"],["lunora dev logs","Print the captured dev-server log (background runs)"],["lunora dev --json","Stream machine-readable JSON log LINES (a stream, not a --format json document)"],["lunora dev --emit-bindings dev-manifest.json","Write what this worker needs + where it serves, for a task runner"],["lunora dev --no-studio","Skip the embedded studio server"],["lunora dev --worker-port 8080","Use a custom wrangler dev port"],["lunora dev --inspector-port 9235","Pin wrangler's devtools inspector port instead of letting it walk up from 9229"],["lunora dev --remote","Proxy D1/KV/R2 to the deployed worker (also LUNORA_REMOTE=1)"]],group:"Develop",loader:()=>import("../packem_chunks/runDevCommand.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:"Write the binding manifest (plus the dev origin) to <file>, for a supervisor that owns the rest of the graph",name:"emit-bindings",type:String},{description:"wrangler dev inspector port, for `wrangler dev` only (defaults to `dev.inspector_port` in wrangler.jsonc; unset, wrangler probes upward from 9229 and can take a sibling worker's pinned port)",name:"inspector-port",type:Number},{description:"Studio server port (default 6173)",name:"port",type:Number},l,{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:"Machine-readable JSON log lines while the server runs, and a JSON result for `dev status`/`dev stop` (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:"Serve the embedded studio at /__lunora (default)",name:"studio",type:Boolean},{description:"Don't start the embedded studio server",name:"no-studio",type:Boolean},{description:"Spawn wrangler dev for the worker (default)",name:"worker",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:"Run codegen on startup and watch for changes (default)",name:"codegen",type:Boolean},{description:"Don't run codegen — no watch, no startup generate (or set LUNORA_CODEGEN=0)",name:"no-codegen",type:Boolean},{description:"Proxy D1/KV/R2 bindings to the deployed worker (or set LUNORA_REMOTE=1)",name:"remote",type:Boolean}]},ee={argument:{description:"Optional path under the docs site (e.g. packages/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 packages/studio","Open a specific docs section"]],group:"Project",loader:()=>import("../packem_chunks/handler5.mjs").then(e=>({default:e.execute})),name:"docs"},te={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:[i]},re={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"],["lunora env diff --format json","Same, as a single JSON document on stdout"]],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},i,{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}]},oe={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},i,{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}]},ne={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"],["lunora export --out backup.ndjson --format json","Write the dump to a file and report rows/bytes as JSON"]],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},{...i,description:"Output format: pretty (default) or json — json needs --out <file>, since stdout carries the NDJSON"},{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}]},ae={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},i,{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}]},ie={description:"Print resolved project config: @lunora/* versions, wrangler summary, schema overview",examples:[["lunora info","Print resolved project config"],["lunora info --format json","Emit a JSON snapshot"],["lunora info --bindings","List what this Worker needs provisioned: bindings, crons, vars"],["lunora info --bindings --format json","Emit the manifest a deployer or task runner consumes"],["lunora info --bindings --out reqs.json","Write that manifest to a file"]],group:"Project",loader:()=>import("../packem_chunks/handler10.mjs").then(e=>({default:e.execute})),name:"info",options:[{description:"Report only what this Worker needs provisioned, as the binding manifest",name:"bindings",type:Boolean},i,{description:"With --bindings: write the manifest to <file> instead of stdout",name:"out",type:String}]},se={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 -t solid-v2","Scaffold a Solid 2.0 SPA"],["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:"Template: analog | astro | expo | next | nuxt | react-router | solid-v2 | standalone | sveltekit | tanstack-start-react | tanstack-start-solid | vinext | vinext-pages. Also accepts an overlay framework (react | vue | solid | svelte), same as --vite.",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 | auth-ui | 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}]},le={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 --format 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},i,{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}]},de={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/handler25.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 (the default)",name:"procedures",type:Boolean},{description:"Emit only the schema — skip the per-table list/get procedure modules",name:"no-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},i]},pe={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}]},ce={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/handler24.mjs").then(e=>({default:e.execute})),name:"logs",options:[{description:"Cloudflare environment name",name:"env",type:String},i,{description:"Substring filter on log messages",name:"search",type:String},{description:"Filter by invocation status: ok, error, or canceled",name:"status",type:String},l,{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}]},ue={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/handler26.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: expose the documentation tools (default)",name:"docs",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}]},me={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 status backfill-names --format json","Same, as a single JSON document on stdout"],["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/dispatch.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},i,{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}]},ge={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 for this run (proceed even with breaking schema drift and no migration; the committed baseline is not advanced)",name:"allow-schema-drift",type:Boolean},{description:`Which API spec(s) to emit: ${p} (default openapi)`,name:"api-spec",type:String},{description:"Fail on ERROR-level codegen advisories even locally (the gate already defaults to on in CI)",name:"strict-advisories",type:Boolean},{description:"Don't fail on ERROR-level codegen advisories (the gate defaults to on in CI, off locally). Never downgrades platform diagnostics.",name:"no-strict-advisories",type:Boolean},l,{description:"Re-bless the committed schema baseline (lunora/.lunora-schema.json) with the current shape",name:"update-schema-baseline",type:Boolean}]},he={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 --from ./registry --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},{...i,description:"Output format: pretty (default) or json (add plan / list)"},{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}]},fe={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}]},ye={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}]},ve={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)"],["lunora run messages:list --format json","Emit the RPC result as a single JSON document on stdout"]],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},i,{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}]},be={argument:{description:"<generate>",name:"args",type:String},description:"Generate a self-contained typed client SDK for another language from the project's OpenRPC surface",examples:[["lunora sdk generate --lang python","Emit a Python SDK, transport included, into ./sdk/python"],["lunora sdk generate --lang go --out ./clients/go","Choose the language and output directory"],["lunora sdk generate --lang dart","A Flutter-ready Dart client — live queries arrive as a Stream"],["lunora sdk generate --lang kotlin","Any of the registered targets; --lang lists them"],["lunora sdk generate --lang rust --from ./sdks","Copy the transport from a local checkout instead of fetching it"]],group:"Project",loader:()=>import("../packem_chunks/handler21.mjs").then(e=>({default:e.execute})),name:"sdk",options:[{description:`Target language: ${P.join(" | ")}`,name:"lang",type:String},{description:"Output directory (default ./sdk/<lang>)",name:"out",type:String},{description:"Path to the OpenRPC document (default ./lunora/_generated/openrpc.json)",name:"spec",type:String},{description:"Copy the transport from a local directory of per-language transports (the repo's `sdks/`) instead of fetching it",name:"from",type:String},{description:"Git ref to fetch the transport from (default: this CLI's own release tag, so the transport matches the generated surface)",name:"ref",type:String},{description:"Override the remote transport source base (default gh:anolilab/lunora/sdks)",name:"source",type:String},{description:"Permit --source values outside gh:/github:/https://",name:"allow-unsafe-source",type:Boolean}]},we={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 --format json","Report generated / inserted / conflicts per table as JSON"],["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},i,{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}]},ke={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"],["lunora verify --env production","Validate the env.production view, as `lunora deploy --env production` will"]],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:"Cloudflare environment name — validate the env.<name> view of wrangler.jsonc, as `lunora deploy --env` does",name:"env",type:String},i,{description:"Probe this deployment's /_lunora/health endpoint (off by default; keeps verify offline-safe)",name:"health-url",type:String},{description:"Fail verification on ERROR-level codegen advisories even locally (the gate already defaults to on in CI)",name:"strict-advisories",type:Boolean},{description:"Don't fail verification 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:"Run the TypeScript type-check step (default)",name:"typecheck",type:Boolean},{description:"Skip the TypeScript type-check step",name:"no-typecheck",type:Boolean},l]},Se={description:"Open the Lunora studio in your browser (the running dev server's, or the default local one)",examples:[["lunora view","Open the studio for the running dev server"]],group:"Project",loader:()=>import("../packem_chunks/handler18.mjs").then(e=>({default:e.execute})),name:"view"},xe=(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 s=r[a]??0,c=e[o-1]===t[a-1]?0:1;r[a]=Math.min((r[a-1]??0)+1,s+1,n+c),n=s}}return r[t.length]??0},Re=(e,t)=>{let r,o=Number.POSITIVE_INFINITY;for(const a of t){const s=xe(e,a);s<o&&(o=s,r=a)}const n=Math.max(2,Math.ceil(e.length/3));return r!==void 0&&o<=n?r:void 0},Ce=e=>`https://registry.npmjs.org/@lunora/cli/${e}`,Ne=1440*60*1e3,Oe=1500,Ae="0.0.0",De=/^v/u,Be=new Set(["alpha","beta","next"]),g=e=>{const t=e.trim().replace(De,""),r=t.indexOf("-");return r===-1?{core:t,prerelease:""}:{core:t.slice(0,r),prerelease:t.slice(r+1)}},w=e=>{const[t,r,o]=g(e).core.split(".").map(n=>{const a=Number.parseInt(n,10);return Number.isFinite(a)?a:0});return[t??0,r??0,o??0]},Ee=(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},Le=(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],s=o[n];if(a===void 0||s===void 0)return a===void 0?-1:1;if(a!==s)return Ee(a,s)}return 0},Ie=(e,t)=>{const r=w(e),o=w(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 Le(g(e).prerelease,g(t).prerelease)},je=e=>{const t=g(e).prerelease.split(".")[0]??"";return Be.has(t)?t:"latest"},Te=(e,t)=>Ie(t,e)>0,_e=(e,t,r)=>t-e<r,Pe=(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:s}=F(o,[`@lunora/cli@${r}`],{dev:!0});return`${n} — run \`${s} ${a.join(" ")}\``},R=e=>m(e,"lunora-cli-update.json"),Ue=e=>{const t=e.XDG_CACHE_HOME&&e.XDG_CACHE_HOME.length>0?e.XDG_CACHE_HOME:m(J(),".cache"),r=m(t,"lunora");try{A(r,{mode:448,recursive:!0})}catch{}return r},Me=e=>{try{const t=JSON.parse(S(R(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{}},k=(e,t)=>{try{const r=R(e);try{if(D(r).isSymbolicLink())return}catch{}B(r,`${JSON.stringify(t)}
1
+ import{mkdirSync as A,readFileSync as S,lstatSync as D,writeFileSync as B}from"node:fs";import{join as m,dirname as y}from"node:path";import{fileURLToPath as E}from"node:url";import{isLunoraError as L,findSolutionByMessage as I}from"@lunora/errors";import{createCerebro as j}from"@visulima/cerebro";import T from"@visulima/cerebro/command/completion";import _ from"@visulima/cerebro/command/version";import{O as i}from"./output-format-B4eQHi5y.mjs";import{A as p,T as l}from"./deploy-target-DCWwiuAe.mjs";import{SDK_LANGUAGES as P}from"@lunora/codegen";import{exitCodeForError as U,EXIT_CODE as M}from"./EXIT_CODE-08cwt3MK.mjs";import{setCommandLogger as v,createLogger as x}from"./createLogger-Cl18I8AX.mjs";import{r as W}from"./render-lunora-error-DgaSmNLc.mjs";import{homedir as J}from"node:os";import{addArgsFor as F,detectPackageManager as K}from"@lunora/config";const H={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},i]},b="lunora.advisor.map.json",$={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 ${b})`,name:"baseline",type:String},{description:"Inspect a single procedure by `file#exportName`",name:"entry",type:String},i,{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 ${b})`,name:"out",type:String},{description:"Write the map artifact to disk (the default)",name:"write",type:Boolean},{description:"Don't write the map artifact to disk — report only",name:"no-write",type:Boolean}]},V={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:[i]},G={argument:{description:"create | list | restore <id|file> | retention | prune | 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 list --format json","Same, as a single JSON document on stdout"],["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 retention","Show what the platform's retention would delete next"],["lunora backup prune","Delete the snapshots past the retention window (the only command that deletes backups)"],["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},i,{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 destructive step without prompting: a production pitr --restore, or backup prune",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}]},q={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:"Override the schema-drift gate for this run (build even with breaking schema drift and no migration; the committed baseline is not advanced)",name:"allow-schema-drift",type:Boolean},{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},i,{description:"Directory to write the bundled Worker to (default .lunora/build)",name:"out-dir",type:String},{description:"Fail the build 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 build on ERROR-level codegen advisories (the gate defaults to on in CI, off locally). Never downgrades platform diagnostics.",name:"no-strict-advisories",type:Boolean},l]},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},i,{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},l]},Y={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 list --format json","List container instances as JSON (also `info`, `images list`)"],["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},{...i,description:"Output format: pretty (default) or json (read subcommands: list | info | images list)"}]},Q={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 --migrate-yes --migrate-url <url>","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 for this run (deploy even with breaking schema drift and no migration; the committed baseline is not advanced — use --update-schema-baseline to accept the new shape)",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},i,{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},l,{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}]},X={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},{...i,description:"Output format: pretty (default) or json (`list` only)"},{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}]},Z={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, ready/starting)"],["lunora dev status --json","Same as JSON — poll `.ready` to gate a dependent step in a task graph"],["lunora dev logs","Print the captured dev-server log (background runs)"],["lunora dev --json","Stream machine-readable JSON log LINES (a stream, not a --format json document)"],["lunora dev --emit-bindings dev-manifest.json","Write what this worker needs + where it serves, for a task runner"],["lunora dev --no-studio","Skip the embedded studio server"],["lunora dev --worker-port 8080","Use a custom wrangler dev port"],["lunora dev --inspector-port 9235","Pin wrangler's devtools inspector port instead of letting it walk up from 9229"],["lunora dev --remote","Proxy D1/KV/R2 to the deployed worker (also LUNORA_REMOTE=1)"]],group:"Develop",loader:()=>import("../packem_chunks/runDevCommand.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:"Write the binding manifest (plus the dev origin) to <file>, for a supervisor that owns the rest of the graph",name:"emit-bindings",type:String},{description:"wrangler dev inspector port, for `wrangler dev` only (defaults to `dev.inspector_port` in wrangler.jsonc; unset, wrangler probes upward from 9229 and can take a sibling worker's pinned port)",name:"inspector-port",type:Number},{description:"Studio server port (default 6173)",name:"port",type:Number},l,{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:"Machine-readable JSON log lines while the server runs, and a JSON result for `dev status`/`dev stop` (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:"Serve the embedded studio at /__lunora (default)",name:"studio",type:Boolean},{description:"Don't start the embedded studio server",name:"no-studio",type:Boolean},{description:"Spawn wrangler dev for the worker (default)",name:"worker",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:"Run codegen on startup and watch for changes (default)",name:"codegen",type:Boolean},{description:"Don't run codegen — no watch, no startup generate (or set LUNORA_CODEGEN=0)",name:"no-codegen",type:Boolean},{description:"Proxy D1/KV/R2 bindings to the deployed worker (or set LUNORA_REMOTE=1)",name:"remote",type:Boolean}]},ee={argument:{description:"Optional path under the docs site (e.g. packages/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 packages/studio","Open a specific docs section"]],group:"Project",loader:()=>import("../packem_chunks/handler5.mjs").then(e=>({default:e.execute})),name:"docs"},te={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:[i]},re={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"],["lunora env diff --format json","Same, as a single JSON document on stdout"]],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},i,{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}]},oe={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},i,{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}]},ne={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"],["lunora export --out backup.ndjson --format json","Write the dump to a file and report rows/bytes as JSON"]],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},{...i,description:"Output format: pretty (default) or json — json needs --out <file>, since stdout carries the NDJSON"},{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}]},ae={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},i,{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}]},ie={description:"Print resolved project config: @lunora/* versions, wrangler summary, schema overview",examples:[["lunora info","Print resolved project config"],["lunora info --format json","Emit a JSON snapshot"],["lunora info --bindings","List what this Worker needs provisioned: bindings, crons, vars"],["lunora info --bindings --format json","Emit the manifest a deployer or task runner consumes"],["lunora info --bindings --out reqs.json","Write that manifest to a file"]],group:"Project",loader:()=>import("../packem_chunks/handler10.mjs").then(e=>({default:e.execute})),name:"info",options:[{description:"Report only what this Worker needs provisioned, as the binding manifest",name:"bindings",type:Boolean},i,{description:"With --bindings: write the manifest to <file> instead of stdout",name:"out",type:String}]},se={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 -t solid-v2","Scaffold a Solid 2.0 SPA"],["lunora init my-app -t rspack-react","Scaffold a React SPA on Rsbuild"],["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:"Template: analog | astro | expo | next | nuxt | react-router | rspack-react | solid-v2 | standalone | sveltekit | tanstack-start-react | tanstack-start-react-rspack | tanstack-start-solid | vinext | vinext-pages. Also accepts an overlay framework (react | vue | solid | svelte), same as --vite.",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 | auth-ui | 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}]},le={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 --format 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},i,{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}]},de={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/handler25.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 (the default)",name:"procedures",type:Boolean},{description:"Emit only the schema — skip the per-table list/get procedure modules",name:"no-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},i]},pe={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}]},ce={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/handler24.mjs").then(e=>({default:e.execute})),name:"logs",options:[{description:"Cloudflare environment name",name:"env",type:String},i,{description:"Substring filter on log messages",name:"search",type:String},{description:"Filter by invocation status: ok, error, or canceled",name:"status",type:String},l,{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}]},ue={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/handler26.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: expose the documentation tools (default)",name:"docs",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}]},me={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 status backfill-names --format json","Same, as a single JSON document on stdout"],["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/dispatch.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},i,{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}]},ge={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 for this run (proceed even with breaking schema drift and no migration; the committed baseline is not advanced)",name:"allow-schema-drift",type:Boolean},{description:`Which API spec(s) to emit: ${p} (default openapi)`,name:"api-spec",type:String},{description:"Fail on ERROR-level codegen advisories even locally (the gate already defaults to on in CI)",name:"strict-advisories",type:Boolean},{description:"Don't fail on ERROR-level codegen advisories (the gate defaults to on in CI, off locally). Never downgrades platform diagnostics.",name:"no-strict-advisories",type:Boolean},l,{description:"Re-bless the committed schema baseline (lunora/.lunora-schema.json) with the current shape",name:"update-schema-baseline",type:Boolean}]},he={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 --from ./registry --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},{...i,description:"Output format: pretty (default) or json (add plan / list)"},{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}]},fe={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}]},ye={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}]},ve={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)"],["lunora run messages:list --format json","Emit the RPC result as a single JSON document on stdout"]],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},i,{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}]},be={argument:{description:"<generate>",name:"args",type:String},description:"Generate a self-contained typed client SDK for another language from the project's OpenRPC surface",examples:[["lunora sdk generate --lang python","Emit a Python SDK, transport included, into ./sdk/python"],["lunora sdk generate --lang go --out ./clients/go","Choose the language and output directory"],["lunora sdk generate --lang dart","A Flutter-ready Dart client — live queries arrive as a Stream"],["lunora sdk generate --lang kotlin","Any of the registered targets; --lang lists them"],["lunora sdk generate --lang rust --from ./sdks","Copy the transport from a local checkout instead of fetching it"]],group:"Project",loader:()=>import("../packem_chunks/handler21.mjs").then(e=>({default:e.execute})),name:"sdk",options:[{description:`Target language: ${P.join(" | ")}`,name:"lang",type:String},{description:"Output directory (default ./sdk/<lang>)",name:"out",type:String},{description:"Path to the OpenRPC document (default ./lunora/_generated/openrpc.json)",name:"spec",type:String},{description:"Copy the transport from a local directory of per-language transports (the repo's `sdks/`) instead of fetching it",name:"from",type:String},{description:"Git ref to fetch the transport from (default: this CLI's own release tag, so the transport matches the generated surface)",name:"ref",type:String},{description:"Override the remote transport source base (default gh:anolilab/lunora/sdks)",name:"source",type:String},{description:"Permit --source values outside gh:/github:/https://",name:"allow-unsafe-source",type:Boolean}]},we={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 --format json","Report generated / inserted / conflicts per table as JSON"],["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},i,{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}]},ke={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"],["lunora verify --env production","Validate the env.production view, as `lunora deploy --env production` will"]],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:"Cloudflare environment name — validate the env.<name> view of wrangler.jsonc, as `lunora deploy --env` does",name:"env",type:String},i,{description:"Probe this deployment's /_lunora/health endpoint (off by default; keeps verify offline-safe)",name:"health-url",type:String},{description:"Fail verification on ERROR-level codegen advisories even locally (the gate already defaults to on in CI)",name:"strict-advisories",type:Boolean},{description:"Don't fail verification 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:"Run the TypeScript type-check step (default)",name:"typecheck",type:Boolean},{description:"Skip the TypeScript type-check step",name:"no-typecheck",type:Boolean},l]},Se={description:"Open the Lunora studio in your browser (the running dev server's, or the default local one)",examples:[["lunora view","Open the studio for the running dev server"]],group:"Project",loader:()=>import("../packem_chunks/handler18.mjs").then(e=>({default:e.execute})),name:"view"},xe=(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 s=r[a]??0,c=e[o-1]===t[a-1]?0:1;r[a]=Math.min((r[a-1]??0)+1,s+1,n+c),n=s}}return r[t.length]??0},Re=(e,t)=>{let r,o=Number.POSITIVE_INFINITY;for(const a of t){const s=xe(e,a);s<o&&(o=s,r=a)}const n=Math.max(2,Math.ceil(e.length/3));return r!==void 0&&o<=n?r:void 0},Ce=e=>`https://registry.npmjs.org/@lunora/cli/${e}`,Ne=1440*60*1e3,Oe=1500,Ae="0.0.0",De=/^v/u,Be=new Set(["alpha","beta","next"]),g=e=>{const t=e.trim().replace(De,""),r=t.indexOf("-");return r===-1?{core:t,prerelease:""}:{core:t.slice(0,r),prerelease:t.slice(r+1)}},w=e=>{const[t,r,o]=g(e).core.split(".").map(n=>{const a=Number.parseInt(n,10);return Number.isFinite(a)?a:0});return[t??0,r??0,o??0]},Ee=(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},Le=(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],s=o[n];if(a===void 0||s===void 0)return a===void 0?-1:1;if(a!==s)return Ee(a,s)}return 0},Ie=(e,t)=>{const r=w(e),o=w(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 Le(g(e).prerelease,g(t).prerelease)},je=e=>{const t=g(e).prerelease.split(".")[0]??"";return Be.has(t)?t:"latest"},Te=(e,t)=>Ie(t,e)>0,_e=(e,t,r)=>t-e<r,Pe=(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:s}=F(o,[`@lunora/cli@${r}`],{dev:!0});return`${n} — run \`${s} ${a.join(" ")}\``},R=e=>m(e,"lunora-cli-update.json"),Ue=e=>{const t=e.XDG_CACHE_HOME&&e.XDG_CACHE_HOME.length>0?e.XDG_CACHE_HOME:m(J(),".cache"),r=m(t,"lunora");try{A(r,{mode:448,recursive:!0})}catch{}return r},Me=e=>{try{const t=JSON.parse(S(R(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{}},k=(e,t)=>{try{const r=R(e);try{if(D(r).isSymbolicLink())return}catch{}B(r,`${JSON.stringify(t)}
2
2
  `,"utf8")}catch{}},We=async(e,t)=>{try{const r=await e(Ce(t),{signal:AbortSignal.timeout(Oe)});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}},Je=(e,t,r)=>e===Ae||!r||t.CI!==void 0||t.LUNORA_NO_UPDATE_NOTIFIER!==void 0,Fe=async e=>{const t=e.env??process.env,r=e.isTTY??process.stdout.isTTY;if(Je(e.current,t,r))return;const o=e.cacheDir??Ue(t),n=(e.now??Date.now)(),a=e.ttlMs??Ne,s=je(e.current),c=Me(o),O=c?.tag??"latest",h=c!==void 0&&O===s?c:void 0;let u=h?.latest;if(h===void 0||!_e(h.checkedAt,n,a)){const f=await We(e.fetchImpl??globalThis.fetch,s);f===void 0?k(o,{checkedAt:n,latest:e.current,tag:s}):(u=f,k(o,{checkedAt:n,latest:f,tag:s}))}u!==void 0&&Te(e.current,u)&&e.logger.warn(Pe(e.current,u,s,e.manager))},Ke=["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"],He=8,$e=()=>{try{let e=y(E(import.meta.url));for(let t=0;t<He;t+=1){try{const o=JSON.parse(S(m(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"},C=$e(),Ve=[se,H,Z,z,$,q,Q,Y,ge,pe,X,ce,ve,le,fe,me,ne,ae,we,de,G,oe,ke,ie,te,re,V,Se,ee,he,ye,ue,be],N=[...Ve,_,T],gt=N.map(e=>e.name),d=e=>e.replaceAll("{",String.raw`\{`).replaceAll("}",String.raw`\}`),Ge=e=>e.every(t=>typeof t=="string")?e.map(t=>d(t)):e.map(t=>typeof t=="string"?[d(t)]:t.map(r=>d(r))),qe=e=>({...e,...e.argument===void 0?{}:{argument:{...e.argument,description:d(e.argument.description??"")}},...e.description===void 0?{}:{description:d(e.description)},...e.examples===void 0?{}:{examples:Ge(e.examples)},...e.options===void 0?{}:{options:e.options.map(t=>({...t,description:d(t.description??"")}))}}),ze=e=>{const t={value:0},r=j("lunora",{argv:e.argv===void 0?void 0:[...e.argv],cwd:e.cwd,exit:o=>{t.value=typeof o=="number"?o:0},logger:e.logger,packageName:"@lunora/cli",packageVersion:C});for(const o of N)r.addCommand(qe(o));return{cli:r,exitCode:t}},Ye=/Command "(?<name>[^"]+)" not found/u,Qe=e=>{const t=x(),r=e instanceof Error?e.message:String(e),o=Ye.exec(r);if(!o?.groups)return L(e)||I(r)!==void 0?t.error(W(e)):t.error(r),U(e);const n=o.groups.name??"",a=Re(n,Ke);return 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."),M.USAGE},Xe=e=>({debug:t=>{e.debug(t)},error:t=>{e.error(t)},info:t=>{e.info(t)},success:t=>{e.info(t)},warn:t=>{e.warn(t)}}),ht=async(e={})=>{const{cli:t,exitCode:r}=ze(e);e.logger!==void 0&&v(Xe(e.logger));try{await t.run({shouldExitProcess:!1})}catch(n){return Qe(n)}finally{v(void 0)}let o;try{o=K(process.cwd())}catch{}return await Fe({current:C,logger:x(),manager:o}),r.value};export{Ke as C,b as D,gt as R,C as V,ht as r};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@lunora/cli",
3
- "version": "1.0.0-alpha.325",
3
+ "version": "1.0.0-alpha.326",
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",
@@ -54,8 +54,8 @@
54
54
  "@bomb.sh/tab": "0.0.22",
55
55
  "@lunora/advisor": "1.0.0-alpha.171",
56
56
  "@lunora/bindings": "1.0.0-alpha.84",
57
- "@lunora/codegen": "1.0.0-alpha.238",
58
- "@lunora/config": "1.0.0-alpha.283",
57
+ "@lunora/codegen": "1.0.0-alpha.239",
58
+ "@lunora/config": "1.0.0-alpha.284",
59
59
  "@lunora/container": "1.0.0-alpha.63",
60
60
  "@lunora/d1": "1.0.0-alpha.151",
61
61
  "@lunora/errors": "1.0.0-alpha.47",
@@ -69,19 +69,21 @@ create-vite base and applies the Lunora layer on top. Use it for a plain SPA:
69
69
  templates fetched remotely (via `giget`) from
70
70
  `gh:anolilab/lunora/templates/<type>`:
71
71
 
72
- | `-t` value | Stack |
73
- | ---------------------- | ---------------------------------------------------------- |
74
- | `next` | Next.js (App Router, OpenNext on Cloudflare) |
75
- | `tanstack-start-react` | TanStack Start (React) — SSR with live-loader routes |
76
- | `tanstack-start-solid` | TanStack Start (Solid) |
77
- | `solid-v2` | Solid 2.0 SPA (`@solidjs/web`, `vite-plugin-solid` 3) |
78
- | `react-router` | React Router v7 (framework mode), SSR in the Lunora worker |
79
- | `astro` | Astro + a standalone Lunora worker |
80
- | `analog` | AnalogJS (Angular) — single worker, Lunora in Nitro |
81
- | `nuxt` | Nuxt (Vue) — single worker, Lunora in Nitro |
82
- | `sveltekit` | SvelteKit + a standalone Lunora worker |
83
- | `expo` | React Native (Expo) — iOS/Android/web + a Lunora worker |
84
- | `standalone` | Worker-only Lunora backend, no frontend |
72
+ | `-t` value | Stack |
73
+ | ----------------------------- | ---------------------------------------------------------- |
74
+ | `next` | Next.js (App Router, OpenNext on Cloudflare) |
75
+ | `tanstack-start-react` | TanStack Start (React) — SSR with live-loader routes |
76
+ | `tanstack-start-solid` | TanStack Start (Solid) |
77
+ | `tanstack-start-react-rspack` | TanStack Start (React) on Rsbuild, single worker |
78
+ | `solid-v2` | Solid 2.0 SPA (`@solidjs/web`, `vite-plugin-solid` 3) |
79
+ | `rspack-react` | React SPA on Rsbuild (`@lunora/rspack`) |
80
+ | `react-router` | React Router v7 (framework mode), SSR in the Lunora worker |
81
+ | `astro` | Astro + a standalone Lunora worker |
82
+ | `analog` | AnalogJS (Angular) — single worker, Lunora in Nitro |
83
+ | `nuxt` | Nuxt (Vue) — single worker, Lunora in Nitro |
84
+ | `sveltekit` | SvelteKit + a standalone Lunora worker |
85
+ | `expo` | React Native (Expo) — iOS/Android/web + a Lunora worker |
86
+ | `standalone` | Worker-only Lunora backend, no frontend |
85
87
 
86
88
  > There is **no `--template vite`.** SPAs go through `--vite <framework>`; `-t`
87
89
  > is only for the bespoke templates above. The one exception is `solid-v2`: