@lunora/cli 1.0.0-alpha.377 → 1.0.0-alpha.378

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-C74xjzMK.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-B5fWPcrA.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.mjs CHANGED
@@ -1 +1 @@
1
- import{C as o,V as a,r as n}from"./packem_shared/cli-C74xjzMK.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-DJeIwzFu.mjs";import{runInitCommand as l}from"./packem_chunks/runInitCommand.mjs";import{runMigrateGenerateCommand as I}from"./packem_shared/runMigrateGenerateCommand-Ii_WMZEA.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-D_XCixv8.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-Ch7zuQQE.mjs";import{default as K}from"./packem_shared/parseManifest-CwPTKdtS.mjs";import{D as Y,r as Z}from"./packem_shared/import-BRM1hs7j.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-DgUDxkA8.mjs";import{runExportCommand as pr}from"./packem_shared/runExportCommand-slAq5BCF.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-B5fWPcrA.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-DJeIwzFu.mjs";import{runInitCommand as l}from"./packem_chunks/runInitCommand.mjs";import{runMigrateGenerateCommand as I}from"./packem_shared/runMigrateGenerateCommand-Ii_WMZEA.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-D_XCixv8.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-Ch7zuQQE.mjs";import{default as K}from"./packem_shared/parseManifest-CwPTKdtS.mjs";import{D as Y,r as Z}from"./packem_shared/import-BRM1hs7j.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-DgUDxkA8.mjs";import{runExportCommand as pr}from"./packem_shared/runExportCommand-slAq5BCF.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 w,join as v}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{wranglerCodegenInputs as M}from"@lunora/config/cloudflare";import{d as D}from"../packem_shared/command-CAXl2A1S.mjs";import{EXIT_CODE as E}from"../packem_shared/EXIT_CODE-D_XCixv8.mjs";import{D as u}from"../packem_shared/cli-C74xjzMK.mjs";const l={clean:"·",exempt:"–",failing:"✗",warned:"!"},d=(e,r)=>e.length>=r?e:e+" ".repeat(r-e.length),R=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}`,F=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},k=(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("",...F(r)),o.join(`
1
+ import{writeFileSync as h,existsSync as S,readFileSync as p}from"node:fs";import{isAbsolute as w,join as v}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{wranglerCodegenInputs as M}from"@lunora/config/cloudflare";import{d as D}from"../packem_shared/command-CAXl2A1S.mjs";import{EXIT_CODE as E}from"../packem_shared/EXIT_CODE-D_XCixv8.mjs";import{D as u}from"../packem_shared/cli-B5fWPcrA.mjs";const l={clean:"·",exempt:"–",failing:"✗",warned:"!"},d=(e,r)=>e.length>=r?e:e+" ".repeat(r-e.length),R=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}`,F=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},k=(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("",...F(r)),o.join(`
2
2
  `)},C=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),...C(i))}return n.join(`
3
3
  `)},I=(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=[`${R(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-C74xjzMK.mjs";import{d as G}from"../packem_shared/command-CAXl2A1S.mjs";import{EXIT_CODE as d}from"../packem_shared/EXIT_CODE-D_XCixv8.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-B5fWPcrA.mjs";import{d as G}from"../packem_shared/command-CAXl2A1S.mjs";import{EXIT_CODE as d}from"../packem_shared/EXIT_CODE-D_XCixv8.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 +1 @@
1
- import{d as _e}from"../packem_shared/command-CAXl2A1S.mjs";import{r as Ee}from"../packem_shared/deploy-target-DCWwiuAe.mjs";import{exitCodeForStatus as W,EXIT_CODE as m}from"../packem_shared/EXIT_CODE-D_XCixv8.mjs";import{writeFileSync as Te}from"node:fs";import{findWranglerFile as de,readWranglerJsonc as ue,applyModify as Oe}from"@lunora/config/cloudflare";import{r as fe,n as Y,c as ke}from"../packem_shared/cloudflare-credentials-BVmZnDZk.mjs";import{c as Ce,b as Ie}from"../packem_shared/variables-CPYyJtsL.mjs";import{b as Ne}from"../packem_shared/tui-prompts-B3YwUhGw.mjs";import{a as Ue}from"../packem_shared/docker-AqLAkOyY.mjs";import{defaultSpawner as me}from"../packem_shared/createRecordingSpawner-Ch7zuQQE.mjs";import{execArgsFor as he,detectPackageManager as ge}from"@lunora/config";import{a as k}from"../packem_shared/cli-C74xjzMK.mjs";const H=256,De=e=>e.length>H?`${e.slice(0,H)}… (truncated)`:e,Re="https://api.cloudflare.com/client/v4/accounts",K=64,V={byok:"https://developers.cloudflare.com/ai-gateway/configuration/bring-your-own-keys/",unifiedBilling:"https://developers.cloudflare.com/ai-gateway/features/unified-billing/"},b=(e,t,r)=>(e.error(r),{code:t,error:r}),X=async(e,t,r,o={})=>{const n=await e(t,{...o,headers:{Authorization:`Bearer ${r}`,"Content-Type":"application/json"}}),s=await n.text();let a;try{a=JSON.parse(s)}catch{}return{body:a,ok:n.ok&&a?.success!==!1,status:n.status,text:s}},Q=e=>{const t=(e.body?.errors??[]).map(r=>r.message).filter(r=>typeof r=="string");return`${String(e.status)}: ${De(t.length>0?t.join("; "):e.text)}`},je=(e,t,r)=>{let o=e;const n=[];for(const[s,a]of Object.entries(r))t?.[s]!==a&&(o=Oe(o,["vars",s],a),n.push(s));return{changed:n,text:o}},Me=(e,t)=>{e.info(`next: \`<provider>/<model>\` slugs (e.g. "anthropic/claude-sonnet-5") now route through gateway "${t}". Before the first call,`),e.info(` configure how the provider is paid for in the Cloudflare dashboard (AI > AI Gateway > ${t}):`),e.info(` - Unified Billing (OpenAI, Anthropic, Google, xAI, Groq, DeepSeek): load credits — ${V.unifiedBilling}`),e.info(` - a key stored on the gateway (Mistral, Perplexity, OpenRouter, …): ${V.byok}`),e.info(" Then redeploy (`lunora deploy`) so the Worker picks up the new vars.")},Le=async(e,t,r,o,n,s)=>{const a=`${Re}/${encodeURIComponent(r)}/ai-gateway/gateways`,i=await X(t,`${a}/${encodeURIComponent(n)}`,o);if(i.ok){const l=i.body?.result?.collect_logs;return{action:"existing",collectLogs:typeof l=="boolean"?l:s}}if(i.status===401||i.status===403)return b(e,W(i.status),`ai-gateway: could not read AI Gateway "${n}" (${Q(i)})`);const c=await X(t,a,o,{body:JSON.stringify({cache_invalidate_on_update:!0,cache_ttl:0,collect_logs:s,id:n,rate_limiting_interval:0,rate_limiting_limit:0}),method:"POST"});return c.ok?{action:"created",collectLogs:s}:b(e,W(c.status),`ai-gateway: could not create AI Gateway "${n}" (${Q(c)})`)},Pe=e=>{const{logger:t}=e,r=de(e.cwd);if(r===void 0)return b(t,m.NOT_FOUND,"ai-gateway: no wrangler.jsonc found — run `lunora init` (or `lunora dev`) first.");const{parsed:o,text:n}=ue(r);if(o===void 0)return b(t,m.USAGE,`ai-gateway: could not parse ${r} as JSONC.`);const s=Y(e.id)??Y(o.name);return s===void 0?b(t,m.USAGE,"ai-gateway: no gateway id — pass --id <id>, or set `name` in wrangler.jsonc."):s.length>K?b(t,m.USAGE,`ai-gateway: gateway id "${s}" is longer than ${String(K)} characters — pass a shorter --id.`):{gatewayId:s,parsed:o,text:n,wranglerPath:r}},j=e=>e?"on":"off",Ge=(e,t)=>(e.info(`ai-gateway (dry run): would create or reuse AI Gateway "${t.gatewayId}" (log collection ${j(t.collectLogs)}).`),e.info(t.varsWritten.length===0?`ai-gateway (dry run): ${t.wranglerPath} vars are already up to date.`:`ai-gateway (dry run): would write ${t.varsWritten.join(", ")} into ${t.wranglerPath} vars.`),t.accountId===void 0&&e.warn("ai-gateway (dry run): no CLOUDFLARE_ACCOUNT_ID (or `account_id` in wrangler.jsonc) — a real run will stop there."),{code:0,data:t}),Fe=async e=>{const{logger:t}=e,r=Pe(e);if("code"in r)return r;const{gatewayId:o,parsed:n,text:s,wranglerPath:a}=r,i=e.logs!==!1,{accountId:c,token:l}=fe(e.environment??process.env,n.account_id),f={[Ie]:o,...c===void 0?{}:{[Ce]:c}},d=je(s,n.vars,f);if(e.dryRun===!0)return Ge(t,{accountId:c,action:"planned",collectLogs:i,dryRun:!0,gatewayId:o,varsWritten:d.changed,wranglerPath:a});if(l===void 0||c===void 0){const g=[l===void 0?"CLOUDFLARE_API_TOKEN (an API token with AI Gateway Write)":void 0,c===void 0?"CLOUDFLARE_ACCOUNT_ID (or `account_id` in wrangler.jsonc)":void 0].filter(y=>y!==void 0);return b(t,m.AUTH,`ai-gateway: missing ${g.join(" and ")}.`)}const h=await Le(t,e.fetch??globalThis.fetch.bind(globalThis),c,l,o,i);return"code"in h?h:(h.action==="created"?t.success(`ai-gateway: created AI Gateway "${o}" (log collection ${j(h.collectLogs)}).`):t.info(`ai-gateway: AI Gateway "${o}" already exists — reusing it (log collection ${j(h.collectLogs)}; change it in the dashboard).`),d.changed.length>0?(Te(a,d.text,"utf8"),t.success(`ai-gateway: wrote ${d.changed.join(", ")} into ${a} vars.`)):t.info(`ai-gateway: ${a} vars are already up to date.`),Me(t,o),{code:0,data:{accountId:c,action:h.action,collectLogs:h.collectLogs,dryRun:!1,gatewayId:o,varsWritten:d.changed,wranglerPath:a}})},xe=15e3,qe="https://api.cloudflare.com/client/v4/graphql",_={analytics:"Account Analytics Read",notificationsRead:"Notifications Read",notificationsWrite:"Notifications Write"},Be={auth:m.AUTH,failure:m.FAILURE,"not-found":m.NOT_FOUND,permission:m.PERMISSION,"rate-limited":m.RATE_LIMITED,rejected:m.USAGE,unavailable:m.UNAVAILABLE};class S extends Error{kind;status;constructor(t,r,o){super(t),this.name="CloudflareApiError",this.kind=r,this.status=o}}const Je=e=>e===401?"auth":e===403?"permission":e===404?"not-found":e===429?"rate-limited":e>=500?"unavailable":"rejected",pe=e=>{try{const r=JSON.parse(e);if(Array.isArray(r.errors)){const o=r.errors.map(n=>typeof n=="object"&&n!==null&&"message"in n?String(n.message):void 0).filter(n=>n!==void 0&&n.length>0);if(o.length>0)return o}}catch{}const t=e.trim().slice(0,200);return t.length>0?[t]:[]},We=9106,Ye=(e,t)=>{try{const r=JSON.parse(e);return Array.isArray(r.errors)&&r.errors.some(o=>typeof o=="object"&&o!==null&&"code"in o&&o.code===t)}catch{return!1}},z=(e,t,r,o)=>{const n=t===400&&Ye(r,We)?"auth":Je(t),s=pe(r).join("; ");let a="";return n==="auth"?a=` — check that CLOUDFLARE_API_TOKEN is a valid token; it needs the "${o}" permission on this account`:n==="permission"&&(a=` — the API token needs the "${o}" permission on this account`),new S(`${e} failed (HTTP ${String(t)})${s.length>0?`: ${s}`:""}${a}.`,n,t)},Z=(e,t)=>{const r=t instanceof Error&&(t.name==="TimeoutError"||t.name==="AbortError");let o=t instanceof Error?t.message:String(t);return r&&(o="no answer in time"),new S(`${e} failed: ${o}.`,"unavailable")},He=10,Ke=e=>{const{accountId:t,token:r}=e,o=e.timeoutMs??xe,n=e.fetch??globalThis.fetch.bind(globalThis),s=async(a,i,c,l)=>{let f;try{f=await ke({accountId:t,apiToken:r,fetch:n,init:{method:i,signal:AbortSignal.timeout(o),...l===void 0?{}:{body:JSON.stringify(l)}},path:c})}catch(d){throw Z(a,d)}if(!f.ok)throw z(a,f.status,f.text,i==="GET"?_.notificationsRead:_.notificationsWrite);return f.body};return{accountId:t,graphql:async(a,i,c={})=>{let l;try{l=await n(qe,{body:JSON.stringify({query:i,variables:c}),headers:{Authorization:`Bearer ${r}`,"Content-Type":"application/json"},method:"POST",signal:AbortSignal.timeout(o)})}catch(d){throw Z(a,d)}const f=await l.text();if(!l.ok)throw z(a,l.status,f,_.analytics);try{const d=JSON.parse(f);return{data:d.data??void 0,errors:Array.isArray(d.errors)&&d.errors.length>0?pe(f):[]}}catch{throw new S(`${a} failed: the GraphQL API answered with something that is not JSON.`,"unavailable",l.status)}},notifications:async(a,i,c,l)=>(await s(a,i,c,l)).result,notificationsList:async(a,i,c=He)=>{const l=async f=>{const d=await s(a,"GET",`${i}${i.includes("?")?"&":"?"}page=${String(f)}`),h=Array.isArray(d.result)?d.result:[],g=d.result_info;return typeof g?.total_pages=="number"&&f<g.total_pages&&f<c?[...h,...await l(f+1)]:h};return l(1)}}},$="billing_usage_alert",ee={"do-duration":"worker_durable_objects_duration","do-requests":"worker_durable_objects_requests","do-rows-read":"worker_durable_objects_storage_reads","do-rows-written":"worker_durable_objects_storage_writes","workers-requests":"worker_requests"},Ve=6,C=e=>typeof e=="object"&&e!==null&&!Array.isArray(e)?e:void 0,N=(e,t)=>{const r=t.toLowerCase(),o=Object.keys(e).find(n=>n.toLowerCase()===r);return o===void 0?void 0:e[o]},M=(e,t)=>{for(const r of t){const o=N(e,r);if(typeof o=="string"&&o.length>0)return o}},Xe=e=>{if(typeof e=="string"&&e.length>0)return{id:e,source:"available-alerts"};const t=C(e),r=t===void 0?void 0:M(t,["id","value","key","name"]);if(t===void 0||r===void 0)return;const o=M(t,["description","label","display_name","displayName","name"]);return{id:r,source:"available-alerts",...o===void 0||o===r?{}:{label:o}}},Qe=["AvailableValues","available_values","values","options","enum","choices"],ye=e=>e.map(t=>Xe(t)).filter(t=>t!==void 0),ze=e=>M(e,["key","name","filter","id"])!=="product"?[]:Qe.flatMap(t=>{const r=N(e,t);return Array.isArray(r)?ye(r):[]}),L=(e,t,r)=>{if(t>Ve)return;if(Array.isArray(e)){for(const n of e)L(n,t+1,r);return}const o=C(e);if(o!==void 0){r.push(...ze(o));for(const[n,s]of Object.entries(o))n.toLowerCase()==="product"&&Array.isArray(s)?r.push(...ye(s)):typeof s=="object"&&s!==null&&L(s,t+1,r)}},Ze=e=>{const t=C(e);if(t!==void 0){for(const r of Object.values(t))if(Array.isArray(r)){const o=r.map(n=>C(n)).find(n=>n!==void 0&&N(n,"type")===$);if(o!==void 0)return o}}},et=e=>e.filter(t=>t.alert_type===$&&Array.isArray(t.filters?.product)).flatMap(t=>(t.filters?.product).filter(r=>typeof r=="string"&&r.length>0)).map(t=>({id:t,source:"existing-policy"})),tt=(e,t,r)=>{const o=Ze(e),n=[];o!==void 0&&L(N(o,"filter_options"),0,n);const s=new Map;for(const a of[...n,...et(r)])s.has(a.id)||s.set(a.id,a);return{eligible:t?o!==void 0:void 0,products:[...s.values()]}},rt=/[^a-z\d]+/u,ot=e=>`${e.id} ${e.label??""}`.toLowerCase().split(rt).filter(t=>t.length>0),nt={"d1-rows-read":{all:[["d1"],["read"]]},"d1-rows-written":{all:[["d1"],["writ"]]},"do-duration":{all:[["durable"],["duration"]]},"do-requests":{all:[["durable"],["request"]]},"do-rows-read":{all:[["durable"],["read"]],none:["request"]},"do-rows-written":{all:[["durable"],["writ"]]},"workers-cpu":{all:[["worker"],["cpu"]],none:["durable"]},"workers-requests":{all:[["worker"],["request"]],none:["durable","cpu","kv","d1"]}},st=(e,t)=>{const r=ot(t),o=a=>r.some(i=>i.startsWith(a)),{all:n,none:s=[]}=nt[e];return n.every(a=>a.some(i=>o(i)))&&!s.some(a=>o(a))},we=(e,t)=>{const r=ee[e],o=r===void 0?void 0:t.find(a=>a.id===r);if(o!==void 0)return{product:o,status:"matched"};const n=new Set(Object.values(ee)),s=t.filter(a=>!n.has(a.id)&&st(e,a));return s.length===1&&s[0]!==void 0?{product:s[0],status:"matched"}:s.length>1?{candidates:s.map(a=>a.id),status:"ambiguous"}:r===void 0?{status:"no-product"}:{product:{id:r,source:"documented"},status:"matched"}},te="workersInvocationsAdaptive",at="durableObjectsInvocationsAdaptiveGroups",R="durableObjectsPeriodicGroups",re="d1AnalyticsAdaptiveGroups",A=[{candidates:[{field:"requests",unit:"count"}],dataset:te,filter:"datetime",id:"workers-requests",label:"Workers requests"},{candidates:[{field:"cpuTimeUs",unit:"microseconds"}],dataset:te,filter:"datetime",id:"workers-cpu",label:"Workers CPU time"},{candidates:[{field:"requests",unit:"count"}],dataset:at,filter:"date",id:"do-requests",label:"Durable Objects requests"},{candidates:[{field:"activeTime",unit:"unknown"}],dataset:R,filter:"date",id:"do-duration",label:"Durable Objects duration"},{candidates:[{field:"rowsRead",unit:"count"}],dataset:R,filter:"date",id:"do-rows-read",label:"Durable Objects rows read"},{candidates:[{field:"rowsWritten",unit:"count"}],dataset:R,filter:"date",id:"do-rows-written",label:"Durable Objects rows written"},{candidates:[{field:"rowsRead",unit:"count"}],dataset:re,filter:"datetime-hour",id:"d1-rows-read",label:"D1 rows read"},{candidates:[{field:"rowsWritten",unit:"count"}],dataset:re,filter:"datetime-hour",id:"d1-rows-written",label:"D1 rows written"}],oe=e=>String(e).padStart(2,"0"),it=e=>{const t=new Date(Date.UTC(e.getUTCFullYear(),e.getUTCMonth()-1,1)),r=new Date(Date.UTC(e.getUTCFullYear(),e.getUTCMonth(),0)),o=new Date(Date.UTC(e.getUTCFullYear(),e.getUTCMonth(),1)),n=s=>`${String(s.getUTCFullYear())}-${oe(s.getUTCMonth()+1)}-${oe(s.getUTCDate())}`;return{endDate:n(r),nextStartDate:n(o),startDate:n(t)}},ct=(e,t)=>{const r=JSON.stringify(`${t.startDate}T00:00:00Z`),o=JSON.stringify(`${t.nextStartDate}T00:00:00Z`);switch(e){case"date":return`{ date_geq: ${JSON.stringify(t.startDate)}, date_lt: ${JSON.stringify(t.nextStartDate)} }`;case"datetime":return`{ datetime_geq: ${r}, datetime_lt: ${o} }`;default:return`{ AND: [{ datetimeHour_geq: ${r}, datetimeHour_lt: ${o} }] }`}},lt=e=>`query LunoraTypeFields { __type(name: ${JSON.stringify(e)}) { fields { name type { name ofType { name ofType { name ofType { name } } } } } } }`,dt=e=>{let t=e;for(;t!=null;){if(typeof t.name=="string"&&t.name.length>0)return t.name;t=t.ofType}},ut=e=>{const t=new Map;return async r=>{const o=t.get(r);if(o!==void 0)return o;const n=e.graphql(`Reading the analytics schema (${r})`,lt(r)).then(s=>{if(s.errors.length>0)throw new S(`Reading the analytics schema failed: ${s.errors.join("; ")}.`,"rejected");const i=s.data?.__type?.fields??[];return new Map(i.map(c=>[c.name,dt(c.type)]))});return t.set(r,n),n}},ve=async(e,t,r)=>{const o=await e(t),[n,...s]=r;if(n===void 0)return o;const a=o.get(n);if(a===void 0)throw new S(`the analytics schema has no \`${n}\` on \`${t}\``,"rejected");return ve(e,a,s)},ft=e=>e instanceof Error?e.message:String(e),mt=async(e,t,r,o,n)=>{const{id:s,label:a}=o;try{const i=await ve(t,r,["viewer","accounts",o.dataset,"sum"]),c=o.candidates.find(y=>i.has(y.field));if(c===void 0){const y=o.candidates.map(u=>`\`${u.field}\``).join(", ");return{id:s,label:a,reason:`\`${o.dataset}.sum\` exposes no ${y} field`,status:"unavailable"}}const l=`query LunoraUsage($accountTag: string) { viewer { accounts(filter: { accountTag: $accountTag }) { ${o.dataset}(limit: 1, filter: ${ct(o.filter,n)}) { sum { ${c.field} } } } } }`,f=await e.graphql(`Reading ${a}`,l,{accountTag:e.accountId});if(f.errors.length>0)return{id:s,label:a,reason:f.errors.join("; "),status:"unavailable"};const d=f.data?.viewer?.accounts?.[0]?.[o.dataset],h=Array.isArray(d)?d[0]:void 0,g=h===void 0?0:h.sum?.[c.field];return typeof g!="number"||!Number.isFinite(g)?{id:s,label:a,reason:`the response carried no number for \`${c.field}\``,status:"unavailable"}:{field:`${o.dataset}.sum.${c.field}`,id:s,label:a,status:"ok",unit:c.unit,value:g}}catch(i){return{id:s,label:a,reason:ft(i),status:"unavailable"}}},ht=async(e,t)=>{const r=await e.graphql("Reading the analytics schema","query LunoraQueryRoot { __schema { queryType { name } } }"),o=r.data?.__schema?.queryType?.name;if(r.errors.length>0||o===void 0){const s=r.errors.length>0?r.errors.join("; "):"the schema root could not be read";return A.map(({id:a,label:i})=>({id:a,label:i,reason:s,status:"unavailable"}))}const n=ut(e);return Promise.all(A.map(async s=>mt(e,n,o,s,t)))},U="Lunora usage: ",gt=3,x="Cloudflare does not document the unit of a usage alert's limit; limits are sent as plain request counts. Check the stored limit in the dashboard.",pt={"do-requests":1e6,"workers-requests":1e7},yt=100,wt=e=>{const t=Math.ceil(e);if(t<=0)return 0;const r=10**Math.max(0,Math.floor(Math.log10(t))-1);return Math.ceil(t/r)*r},vt=(e,t,r)=>{const o=wt(e*t);return o>r?{basis:"history",threshold:o}:{basis:"floor",threshold:r}},P=e=>{const t=e.filters?.product;return Array.isArray(t)?t.filter(r=>typeof r=="string"):[]},bt=e=>{const t=e.filters?.limit,r=Array.isArray(t)?t[0]:void 0,o=typeof r=="string"?Number(r):Number.NaN;return Number.isFinite(o)?o:void 0},q=e=>{const t={};for(const[r,o]of Object.entries(e?.mechanisms??{}))Array.isArray(o)&&(t[r]=o.filter(n=>typeof n=="object"&&n!==null&&"id"in n&&typeof n.id=="string"));return t},$t=(e,t)=>{const r={};for(const[o,n]of[...Object.entries(e),...Object.entries(t)]){const s=new Set((r[o]??[]).map(a=>a.id));r[o]=[...r[o]??[],...n.filter(a=>!s.has(a.id))]}return Object.fromEntries(Object.entries(r).filter(([,o])=>o.length>0))},I=e=>Object.entries(e).flatMap(([t,r])=>r.map(o=>`${t}:${o.id}`)),At=(e,t)=>JSON.stringify(I(e).toSorted((r,o)=>r.localeCompare(o)))===JSON.stringify(I(t).toSorted((r,o)=>r.localeCompare(o))),St=(e,t)=>e.enabled===!0&&e.name===t.name&&JSON.stringify(e.filters?.limit)===JSON.stringify(t.filters.limit)&&JSON.stringify(P(e))===JSON.stringify(t.filters.product)&&At(q(e),t.mechanisms),_t=(e,t)=>{const r={};return e.length>0&&(r.email=e.map(o=>({id:o}))),t.length>0&&(r.webhooks=t.map(o=>({id:o}))),r},Et=(e,t,r)=>{const o=r.thresholds?.[e],n=r.usage.find(c=>c.id===e),s=n?.status==="ok"?n.value:void 0;if(o!==void 0)return{basis:"explicit",lastMonth:s,threshold:o};const a=pt[e];return a===void 0?{kind:"unit-unverified",reason:`the unit Cloudflare meters "${t.id}" in is not documented and cannot be matched to the usage reading; set one yourself with --threshold ${e}=<n>`}:s!==void 0?{...vt(s,r.multiplier,a),lastMonth:s}:r.allowFloor===!0?{basis:"floor-usage-unavailable",lastMonth:void 0,threshold:a}:{kind:"usage-unavailable",reason:`last month's usage could not be read (${n?.status==="unavailable"?n.reason:"no reading"}), and an alert at the floor could fire every month on an account that already exceeds it; pass --threshold ${e}=<n>, or --allow-floor`}},Tt=(e,t)=>{const r=bt(e);if(r===void 0||t===void 0||r<=0||t<=0)return;const o=Math.max(r/t,t/r);return o>=yt?`its limit ${String(r)} differs from the ${String(t)} this would plan by ${String(Math.round(o))}× — one of the two may be in the wrong unit`:void 0},G=e=>`${U}${e}`,Ot=(e,t)=>e===void 0?"create":St(e,t)?"unchanged":"update",kt=(e,t)=>{switch(e){case"explicit":return"set with --threshold";case"floor-usage-unavailable":return"the included monthly allowance, applied with --allow-floor because usage could not be read";case"history":return`${String(t)}× last month`;default:return"the included monthly allowance (floor)"}},Ct=(e,t,r)=>{const{id:o,label:n}=e,s=we(o,t.products);if(s.status==="no-product")return{kind:"no-product",metric:o,reason:"Cloudflare has no usage alert for this product; the account-wide budget alert is its guard"};if(s.status==="ambiguous")return{kind:"ambiguous",metric:o,reason:`several offered products could mean this metric (${s.candidates.join(", ")})`};const{product:a}=s,i=r.find(p=>p.name===G(n)),c=r.find(p=>p.enabled===!0&&p.name?.startsWith(U)!==!0&&P(p).includes(a.id)),l=Et(o,a,t);if(i===void 0&&c!==void 0){const p=Tt(c,"threshold"in l?l.threshold:void 0);return{kind:"covered",metric:o,reason:`already alerted by the existing policy "${c.name??c.id??"?"}"`,...p===void 0?{}:{warning:p}}}if(!("threshold"in l))return{...l,metric:o};const f=_t(t.emails,t.webhooks),d=q(i),h=i===void 0||t.replaceRecipients===!0?f:$t(d,f),g=new Set(I(d)),y=new Set(I(h)),u={alert_type:$,description:`Managed by \`lunora cloudflare alerts setup\`: ${kt(l.basis,t.multiplier)}.`,enabled:!0,filters:{limit:[String(l.threshold)],product:[a.id]},mechanisms:h,name:G(n)},w=i===void 0?[]:P(i);return{action:Ot(i,u),basis:l.basis,body:u,lastMonth:l.lastMonth,metric:o,...i?.id===void 0?{}:{policyId:i.id},...i!==void 0&&JSON.stringify(w)!==JSON.stringify([a.id])?{previousProduct:w}:{},product:a.id,productSource:a.source,recipients:{added:[...y].filter(p=>!g.has(p)),removed:[...g].filter(p=>!y.has(p))},threshold:l.threshold}},It=e=>{const t=e.policies.filter(n=>n.alert_type===$),r=new Set(A.map(n=>G(n.label))),o={alerts:[],duplicates:[],orphans:t.filter(n=>n.name?.startsWith(U)===!0&&!r.has(n.name)),skipped:[]};for(const n of r)o.duplicates.push(...t.filter(s=>s.name===n).slice(1));for(const n of A){const s=Ct(n,e,t);"action"in s?o.alerts.push(s):o.skipped.push(s)}return o},Nt="Cloudflare's API has no endpoint that sends a test notification — not for webhooks and not for email — so `lunora cloudflare alerts test` sends nothing.",Ut="To test a webhook for real, create it in the dashboard (Alerts > Destinations > Webhooks > Create) and finish with Save and Test.",Dt="Email destinations cannot be tested at all: Cloudflare offers no test send for them. Check the address on each policy below instead.",ne=e=>Array.isArray(e)?e:[],se=30,Rt=async(e,t,r,o,n)=>{const s=t.filter(u=>u.alert_type===$&&u.name?.startsWith(U)===!0),a=s.map(u=>q(u)),i=new Set([...a.flatMap(u=>(u.webhooks??[]).map(w=>w.id)),...r]),c=[...new Set(a.flatMap(u=>(u.email??[]).map(w=>w.id)))],l=new Set(s.map(u=>u.id)),f=new Date(n.getTime()-se*24*60*60*1e3).toISOString(),[d,h]=await Promise.all([e.notifications("Listing webhook destinations","GET","/alerting/v3/destinations/webhooks"),s.length===0?Promise.resolve([]):e.notificationsList("Reading notification history",`/alerting/v3/history?per_page=25&since=${encodeURIComponent(f)}`)]),g=ne(d).map(u=>({...u,referenced:u.id!==void 0&&i.has(u.id)})),y=ne(h).filter(u=>u.alert_type===$&&u.policy_id!==void 0&&l.has(u.policy_id));o.warn(Nt),s.length===0&&o.info("No `lunora cloudflare alerts setup` policies exist on this account yet — run `lunora cloudflare alerts setup` first.");for(const u of[...i].filter(w=>!g.some(p=>p.id===w)))o.warn(`Webhook destination ${u} is referenced but does not exist on this account.`);for(const u of g.filter(w=>w.referenced))o.info(`webhook "${u.name??u.id??"?"}" (${u.type??"generic"}): last delivered ${u.last_success??"never"}, last failed ${u.last_failure??"never"}`);if(o.info(Ut),c.length>0&&o.info(`${Dt} Addresses on the policies: ${c.join(", ")}.`),y.length===0)o.info(`Cloudflare's notification history shows nothing sent for these policies in the last ${String(se)} days (they only fire once a threshold is crossed).`);else for(const u of y)o.info(`sent ${u.sent??"?"}: "${u.name??"?"}" via ${u.mechanism_type??"?"} to ${u.mechanism??"?"}`);return{emails:c,history:y,testSent:!1,webhooks:g}},D="Budget alert (account-wide USD threshold): Cloudflare documents no API to create or read one, so this cannot be checked. Create it in the dashboard: Manage Account > Billing > Billable Usage > Create budget alert.",jt="Alerts > Overview > Create an Alert, alert type Usage Based Billing",v=(e,t,r,o)=>(e.error(r),{code:t,error:r,...o===void 0?{}:{data:o}}),B=(e,t,r)=>{if(t instanceof S)return v(e,Be[t.kind],t.message,r);throw t},J=(e,t)=>({accountId:e.accountId,budgetAlert:{checkable:!1,dashboardPath:"Manage Account > Billing > Billable Usage"},limitUnitCaveat:x,...t===void 0?{}:{eligible:t.discovery.eligible,period:t.period,products:t.discovery.products}}),E=e=>e.toLocaleString("en-US",{maximumFractionDigits:0}),be=(e,t)=>{t===!1&&e.warn("This account is not eligible for Usage Based Billing notifications (they are offered to Pay-as-you-go accounts; most Enterprise contracts are not supported).")},$e=e=>({code:m.SUCCESS,data:e}),Mt=/^[^\s@]+@[^\s@][^\s.@]*\.[^\s@]+$/u,Ae=new Set(A.map(e=>e.id)),Lt=e=>Ae.has(e),Pt=e=>{const t={};for(const r of e.flatMap(o=>o.split(","))){const[o="",n=""]=r.split("=").map(a=>a.trim()),s=Number(n);if(!Lt(o))return{error:`--threshold "${r}": unknown metric "${o}" — one of ${[...Ae].join(", ")}.`};if(!Number.isFinite(s)||s<=0)return{error:`--threshold "${r}": the limit must be a positive number.`};t[o]=Math.ceil(s)}return t},Gt=e=>{const t=(e.emails??[]).flatMap(a=>a.split(",")).map(a=>a.trim()).filter(a=>a.length>0),r=(e.webhooks??[]).map(a=>a.trim()).filter(a=>a.length>0),o=e.multiplier===void 0?gt:Number(e.multiplier),n=Pt(e.thresholds??[]);if(t.length===0&&r.length===0)return{error:"alerts setup needs somewhere to send the alerts: pass --email <address> and/or --webhook <destination-id>."};const s=t.find(a=>!Mt.test(a));return s!==void 0?{error:`--email "${s}" is not an email address.`}:!Number.isFinite(o)||o<1?{error:`--multiplier must be a number of at least 1 (got "${e.multiplier??""}").`}:"error"in n?n:{allowFloor:e.allowFloor===!0,emails:t,multiplier:o,replaceRecipients:e.replaceRecipients===!0,thresholds:n,webhooks:r}},Ft={explicit:()=>"set with --threshold",floor:e=>`floor: included monthly allowance; last month ${E(e.lastMonth??0)}`,"floor-usage-unavailable":()=>"floor: usage could not be read, applied with --allow-floor",history:e=>`last month ${E(e.lastMonth??0)}`},xt=e=>{const t=[...e.added.map(r=>`+${r}`),...e.removed.map(r=>`-${r}`)];return t.length===0?"recipients unchanged":`recipients ${t.join(" ")}`},qt=e=>{const t=e.productSource==="documented"?"documented id":"offered by the account",r=e.previousProduct===void 0?"":`, product was ${e.previousProduct.join(", ")||"none"}`;return`${e.action.padEnd(9)} ${e.body.name} — product ${e.product} (${t}${r}), limit ${E(e.threshold)} (${Ft[e.basis](e)}); ${xt(e.recipients)}`},F=e=>A.find(t=>t.id===e)?.label??e,Bt=(e,t,r,o)=>{o.info(`Usage alerts at ${String(t)}× last month (${r.startDate} to ${r.endDate}), never below the included allowance:`);for(const n of e.alerts)o.info(` ${qt(n)}`);for(const n of e.skipped)o.info(` skipped ${F(n.metric)} — ${n.reason}`),n.warning!==void 0&&o.warn(`${F(n.metric)}: the existing alert ${n.warning}.`);for(const n of e.orphans)o.warn(`"${n.name??"?"}" (${n.id??"?"}) is named like a \`lunora cloudflare alerts\` policy but matches no metric; it was left alone.`);for(const n of e.duplicates)o.warn(`"${n.name??"?"}" exists more than once; ${n.id??"?"} was left alone — delete the extra one in the dashboard.`);e.skipped.some(n=>n.kind==="unit-unverified"||n.kind==="ambiguous")&&o.info(`To set the skipped ones by hand: ${jt}.`),o.info(x),o.info(D)},Jt=async(e,t)=>{if(e.yes===!0)return;if(e.confirm===void 0&&(!process.stdin.isTTY||e.format==="json"))return v(e.logger,m.USAGE,"alerts setup: refusing to change notification policies without confirmation — re-run with --yes.");const r=t.flatMap(s=>s.recipients.removed),o=r.length===0?"":` This REMOVES recipients: ${[...new Set(r)].join(", ")}.`;if(!await(e.confirm??Ne)(`Apply ${String(t.length)} notification policy change(s)?${o}`))return e.logger.info("alerts setup: aborted"),{code:m.CANCELLED,error:"alerts setup: aborted at the confirmation prompt"}},Wt=async(e,t,r,o)=>{const s=(await Promise.all(t.map(async a=>e.notifications(`Reading webhook destination ${a}`,"GET",`/alerting/v3/destinations/webhooks/${encodeURIComponent(a)}`).then(()=>{},i=>({error:i,id:a}))))).find(a=>a!==void 0);if(s!==void 0)return s.error instanceof S&&s.error.kind==="not-found"?v(r,m.USAGE,`--webhook ${s.id}: no such webhook destination on account ${e.accountId}.`,o):B(r,s.error,o)},Yt=async(e,t)=>{const r=t.action==="create"?await e.notifications(`Creating "${t.body.name}"`,"POST","/alerting/v3/policies",t.body):await e.notifications(`Updating "${t.body.name}"`,"PUT",`/alerting/v3/policies/${encodeURIComponent(t.policyId??"")}`,t.body);return typeof r=="object"&&r!==null&&"id"in r&&typeof r.id=="string"?r.id:t.policyId},Ht=async(e,t,r)=>await Promise.all(t.map(async({alert:n,id:s})=>{try{const a=await e.notifications(`Reading back "${n.body.name}"`,"GET",`/alerting/v3/policies/${encodeURIComponent(s)}`),i={enabled:a?.enabled,id:s,limit:a?.filters?.limit,name:a?.name,product:a?.filters?.product};return r.info(`Cloudflare stored "${i.name??n.body.name}": product ${JSON.stringify(i.product)}, limit ${JSON.stringify(i.limit)}.`),JSON.stringify(i.limit)!==JSON.stringify(n.body.filters.limit)&&r.warn(`"${n.body.name}": Cloudflare stored limit ${JSON.stringify(i.limit)}, not the ${JSON.stringify(n.body.filters.limit)} sent.`),i}catch(a){return r.warn(`Could not read "${n.body.name}" back: ${a instanceof Error?a.message:String(a)}`),{id:s}}})),Kt=async(e,t,r,o)=>{const n=[],s=[];let a;for(const c of t)try{const l=await Yt(e,c);n.push({action:c.action,metric:c.metric,...l===void 0?{}:{policyId:l}}),l!==void 0&&s.push({alert:c,id:l}),r.success(`${c.action==="create"?"Created":"Updated"} "${c.body.name}".`)}catch(l){a=l;break}const i={...o,applied:n,stored:await Ht(e,s,r)};return a===void 0?i:B(r,a,i)},ae=(e,t,r)=>{const o=t.skipped.filter(n=>n.kind==="usage-unavailable");return o.length>0?v(r,m.FAILURE,`alerts setup: no alert was set for ${o.map(n=>F(n.metric)).join(", ")} because last month's usage could not be read — pass --threshold <metric>=<n>, or --allow-floor to accept the floor.`,e):{code:m.SUCCESS,data:e}},Vt=async(e,t,r,o)=>{const{logger:n}=r,s=J(e,t),a=await Wt(e,o.webhooks,n,s);if(a!==void 0)return a;if(t.discovery.eligible===!1)return be(n,!1),n.info(D),v(n,m.PERMISSION,"alerts setup: the account cannot create Usage Based Billing notifications.",s);const i=It({...o,policies:t.policies,products:t.discovery.products,usage:t.usage});s.plan=i,Bt(i,o.multiplier,t.period,n);const c=i.alerts.filter(d=>d.action!=="unchanged");if(r.dryRun===!0||c.length===0)return n.info(r.dryRun===!0?"Dry run: nothing was changed.":"Every alert is already up to date."),ae(s,i,n);const l=await Jt(r,c);if(l!==void 0)return{...l,data:s};const f=await Kt(e,c,n,s);return"code"in f?f:ae(f,i,n)},Xt=e=>e.status!=="ok"?`unavailable (${e.reason})`:e.unit==="microseconds"?`${E(e.value)} µs`:E(e.value),Qt=(e,t,r)=>t?"no-product":e===void 0?"unknown":r.some(o=>o.enabled)?"active":r.length>0?"disabled-only":"none",ie=e=>e.map(t=>`"${t.name??t.id??"?"}" (limit ${JSON.stringify(t.limit)})${t.enabled?"":" — disabled, not protecting you"}`).join(", "),zt={active:e=>`alert: ${ie(e.alerts)}`,"disabled-only":e=>`alert: none active; ${ie(e.alerts)}`,"no-product":()=>"alert: none possible — Cloudflare has no usage alert for this; the budget alert is its guard",none:()=>"alert: none",unknown:()=>"alert: unknown (several offered products could mean this)"},Zt=(e,t,r)=>{const o=we(e.id,t.discovery.products),n=o.status==="matched"?o.product:void 0,s=(n===void 0?[]:r.filter(a=>Array.isArray(a.filters?.product)&&a.filters.product.includes(n.id))).map(a=>({enabled:a.enabled===!0,id:a.id,limit:a.filters?.limit,name:a.name}));return{alerts:s,coverage:Qt(n?.id,o.status==="no-product",s),id:e.id,label:e.label,...n===void 0?{}:{product:n.id,productSource:n.source},usage:e}},er=(e,t,r)=>{const o=t.policies.filter(s=>s.alert_type===$),n=t.usage.map(s=>Zt(s,t,o));r.info(`Cloudflare account ${e.accountId} — usage ${t.period.startDate} to ${t.period.endDate}`);for(const s of n)r.info(` ${s.label}: ${Xt(s.usage)} — ${zt[s.coverage](s)}`);return r.info(`Usage Based Billing notifications on the account: ${String(o.length)} (${String(o.filter(s=>s.enabled===!0).length)} enabled).`),r.info(x),be(r,t.discovery.eligible),r.info(D),$e({...J(e,t),metrics:n})},tr=e=>{const t=de(e);return t===void 0?void 0:ue(t).parsed?.account_id},rr=e=>{const{accountId:t,token:r}=fe(e.environment??process.env,tr(e.cwd));return r===void 0?v(e.logger,m.AUTH,`CLOUDFLARE_API_TOKEN is not set. \`lunora cloudflare alerts\` calls the Cloudflare API with an API token (a wrangler login session is not reused); create one with the "${_.notificationsWrite}" and "${_.analytics}" permissions ("${_.notificationsRead}" is enough for status and test).`):t===void 0?v(e.logger,m.USAGE,"No Cloudflare account: set CLOUDFLARE_ACCOUNT_ID or `account_id` in wrangler.jsonc."):Ke({accountId:t,token:r,...e.fetch===void 0?{}:{fetch:e.fetch}})},Se=async e=>{const t=await e.notifications("Listing notification policies","GET","/alerting/v3/policies");return Array.isArray(t)?t:[]},or=async(e,t)=>{const r=it(t.now??new Date),{logger:o}=t,[n,s,a]=await Promise.all([Se(e),e.notifications("Listing the alert types this account is eligible for","GET","/alerting/v3/available_alerts").then(i=>({ok:!0,value:i}),i=>({error:i,ok:!1})),ht(e,r).catch(i=>{const c=i instanceof Error?i.message:String(i);return o.warn(`Usage could not be read: ${c}`),A.map(({id:l,label:f})=>({id:l,label:f,reason:c,status:"unavailable"}))})]);return s.ok||o.warn(`Could not read which alert types the account is eligible for: ${s.error instanceof Error?s.error.message:String(s.error)}`),{discovery:tt(s.ok?s.value:void 0,s.ok,n),period:r,policies:n,usage:a}},nr=async(e,t)=>{const r=await Se(e),o=await Rt(e,r,t.webhooks??[],t.logger,t.now??new Date);return t.logger.info(D),$e({...J(e),deliveries:o})},sr=async e=>{const t=e.subcommand==="setup"?Gt(e):void 0;if(t!==void 0&&"error"in t)return v(e.logger,m.USAGE,t.error);const r=rr(e);if(!("graphql"in r))return r;try{if(e.subcommand==="test")return await nr(r,e);const o=await or(r,e);return t===void 0?er(r,o,e.logger):await Vt(r,o,e,t)}catch(o){return B(e.logger,o)}},ce=new Set(["build","delete","images","info","list","push"]),ar=new Set(["build","push"]),le=new Set(["images list","info","list"]),ir=async e=>{const[t,...r]=e.argument;if(t===void 0||!ce.has(t)){const d=`lunora cloudflare containers requires a subcommand: ${[...ce].toSorted((h,g)=>h.localeCompare(g)).join(" | ")}. Example: lunora cloudflare containers build ./containers/app --tag app:v1 --push`;return e.logger.error(d),{code:m.USAGE,error:d}}const o=e.format==="json",n=t==="images"?`images ${r[0]??""}`.trim():t;if(o&&!le.has(n)){const d=`containers ${n}: --format json is only available for the read subcommands (${[...le].toSorted((h,g)=>h.localeCompare(g)).join(" | ")}) — wrangler has no JSON rendering for the rest.`;return e.logger.error(d),{code:m.USAGE,error:d}}if(ar.has(t)&&!(e.dockerAvailable??Ue)()){const d=`containers ${t} needs a running Docker-compatible engine (it builds/pushes images locally). Start Docker or Colima and retry. Note: container images must target linux/amd64.`;return e.logger.error(d),{code:m.MISSING_DEPENDENCY,error:d}}const s=["containers",t,...r];o&&s.push("--json"),e.tag!==void 0&&s.push("--tag",e.tag),e.push===!0&&s.push("--push"),e.env!==void 0&&s.push("--env",e.env);const a=e.cwd??process.cwd(),i=he(ge(a),"wrangler",s),c={args:i.args,command:i.command,cwd:a};return e.logger.info(`running ${c.command} ${c.args.join(" ")}`),{code:(await(e.spawner??me)(c)).code,delegated:o,descriptor:c}},O=(e,t)=>(t!==void 0&&e.push("--env",t),e),cr=e=>{const t=O(["deployments","list"],e.env);return e.format==="json"&&t.push("--json"),t},lr=e=>{switch(e.subcommand){case"inspect":return e.versionId===void 0?{error:"deployments inspect requires a version id. Usage: lunora cloudflare deployments inspect <version-id>"}:{args:O(["versions","view",e.versionId],e.env)};case"list":return{args:cr(e)};case"promote":{if(e.versionId===void 0)return{error:"deployments promote requires a version id. Usage: lunora cloudflare deployments promote <version-id> --yes"};if(!e.yes)return{error:"deployments promote shifts 100% of live traffic. Re-run with --yes to confirm."};const t=O(["versions","deploy",`${e.versionId}@100%`,"--yes"],e.env);return e.message!==void 0&&t.push("--message",e.message),{args:t}}case"rollback":{if(!e.yes)return{error:"deployments rollback changes the live version. Re-run with --yes to confirm."};const t=O(["rollback"],e.env);return e.versionId!==void 0&&t.push(e.versionId),t.push("--yes"),e.message!==void 0&&t.push("--message",e.message),{args:t}}default:return{error:`deployments: unknown subcommand "${e.subcommand}"`}}},dr=async e=>{if(e.format==="json"&&e.subcommand!=="list"){const l=`deployments ${e.subcommand}: --format json is only available for \`deployments list\` — wrangler has no JSON rendering for the others.`;return e.logger.error(l),{code:m.USAGE,descriptor:void 0,error:l}}const{args:t,error:r}=lr(e);if(r!==void 0||t===void 0)return e.logger.error(r??"deployments: nothing to run"),{code:m.USAGE,descriptor:void 0,error:r};const{logger:o}=e,n=e.cwd??process.cwd(),s=he(ge(n),"wrangler",t),a={args:s.args,command:s.command,cwd:n};return o.info(`${a.command} ${a.args.join(" ")}`),{code:(await(e.spawner??me)(a)).code,delegated:e.format==="json",descriptor:a}},ur=e=>e==="list"||e==="inspect"||e==="rollback"||e==="promote",fr={ai:{absorbs:"gateway",tool:"ai-gateway"},alert:{tool:"alerts"}},mr=(e,t)=>{const r=fr[e];if(r!==void 0)return{rest:r.absorbs!==void 0&&t[0]===r.absorbs?t.slice(1):t,tool:r.tool};const o=k.find(n=>n.name===e)?.name;return o===void 0?void 0:{rest:t,tool:o}},hr={celld:"celld",node:"Node"},gr=e=>e==="status"||e==="setup"||e==="test",T=(e,t,r)=>(e.error(r),{code:t,error:r}),pr=e=>{const t=Math.max(...k.map(r=>r.name.length));e.info("lunora cloudflare <tool> — tools for an app deployed to your own Cloudflare account:");for(const r of k)e.info(` ${r.name.padEnd(t)} ${r.summary}`),r.usage!==""&&e.info(` ${" ".repeat(t)} lunora cloudflare ${r.name} ${r.usage}`);return e.info("Run `lunora cloudflare --help` for every tool's arguments and options."),{code:0}},yr=(e,t,r)=>{const{error:o,target:n}=Ee(e,r);return n===void 0?o??"no deploy target":n==="cloudflare"?void 0:`${r===void 0?`this project deploys to ${hr[n]??`"${n}"`}`:`\`--target ${n}\``} — \`lunora cloudflare ${t}\` only applies to Cloudflare.`},wr=(e,{logger:t,rest:r})=>r.length===0?void 0:T(t,m.USAGE,`cloudflare ${e}: takes no arguments, got "${r.join(" ")}"`),vr=async e=>{const{cwd:t,logger:r,options:o}=e;return wr("ai-gateway",e)??Fe({cwd:t,dryRun:o.dryRun===!0,id:o.id,logger:r,logs:o.logs})},br=async({cwd:e,format:t,logger:r,options:o,rest:n})=>{const s=n[0]??"status";return gr(s)?sr({allowFloor:o.allowFloor===!0,cwd:e,dryRun:o.dryRun===!0,format:t,logger:r,replaceRecipients:o.replaceRecipients===!0,subcommand:s,yes:o.yes===!0,...o.email===void 0?{}:{emails:o.email},...o.webhook===void 0?{}:{webhooks:o.webhook},...o.multiplier===void 0?{}:{multiplier:o.multiplier},...o.threshold===void 0?{}:{thresholds:o.threshold}}):T(r,m.USAGE,`cloudflare alerts: unknown subcommand "${s}" — expected status | setup | test`)},$r=async({cwd:e,format:t,logger:r,options:o,rest:n})=>{const s=await ir({argument:n,cwd:e,env:o.env,format:t,logger:r,push:o.push===!0,tag:o.tag});return{code:s.code,delegated:s.delegated,error:s.error}},Ar=async({cwd:e,format:t,logger:r,options:o,rest:n})=>{const[s,a]=n;if(!ur(s))return T(r,m.USAGE,`cloudflare deployments: unknown subcommand "${s??""}" — expected list | inspect | rollback | promote`);const i=await dr({cwd:e,env:o.env,format:t,logger:r,message:o.message,subcommand:s,versionId:a,yes:o.yes===!0});return{code:i.code,delegated:i.delegated,error:i.error}},Sr={"ai-gateway":vr,alerts:br,containers:$r,deployments:Ar},Mr=_e(async({argument:e,cwd:t,format:r,logger:o,options:n})=>{const[s,...a]=e;if(s===void 0||s==="")return pr(o);const i=mr(s,a);if(i===void 0)return T(o,m.USAGE,`cloudflare: unknown tool "${s}" — expected ${k.map(f=>f.name).join(" | ")}`);const{tool:c}=i,l=yr(t,c,n.target);return l!==void 0?T(o,m.USAGE,l):Sr[c]({cwd:t,format:r,logger:o,options:n,rest:i.rest})});export{Mr as execute};
1
+ import{d as De}from"../packem_shared/command-CAXl2A1S.mjs";import{r as Me}from"../packem_shared/deploy-target-DCWwiuAe.mjs";import{exitCodeForStatus as L,EXIT_CODE as l}from"../packem_shared/EXIT_CODE-D_XCixv8.mjs";import{writeFileSync as $e,mkdirSync as je,renameSync as Le,rmSync as Pe}from"node:fs";import{findWranglerFile as W,readWranglerJsonc as H,applyModify as Ge}from"@lunora/config/cloudflare";import{r as Y,n as Q,c as Fe}from"../packem_shared/cloudflare-credentials-BVmZnDZk.mjs";import{c as xe,b as Be}from"../packem_shared/variables-CPYyJtsL.mjs";import{b as qe}from"../packem_shared/tui-prompts-B3YwUhGw.mjs";import{a as Je}from"../packem_shared/docker-AqLAkOyY.mjs";import{defaultSpawner as Ae}from"../packem_shared/createRecordingSpawner-Ch7zuQQE.mjs";import{execArgsFor as Se,detectPackageManager as _e}from"@lunora/config";import{a as C}from"../packem_shared/cli-B5fWPcrA.mjs";import{resolve as We,dirname as He}from"node:path";const Z=256,P=e=>e.length>Z?`${e.slice(0,Z)}… (truncated)`:e,Ye="https://api.cloudflare.com/client/v4/accounts",ee=64,te={byok:"https://developers.cloudflare.com/ai-gateway/configuration/bring-your-own-keys/",unifiedBilling:"https://developers.cloudflare.com/ai-gateway/features/unified-billing/"},A=(e,t,r)=>(e.error(r),{code:t,error:r}),re=async(e,t,r,o={})=>{const n=await e(t,{...o,headers:{Authorization:`Bearer ${r}`,"Content-Type":"application/json"}}),a=await n.text();let s;try{s=JSON.parse(a)}catch{}return{body:s,ok:n.ok&&s?.success!==!1,status:n.status,text:a}},oe=e=>{const t=(e.body?.errors??[]).map(r=>r.message).filter(r=>typeof r=="string");return`${String(e.status)}: ${P(t.length>0?t.join("; "):e.text)}`},Ke=(e,t,r)=>{let o=e;const n=[];for(const[a,s]of Object.entries(r))t?.[a]!==s&&(o=Ge(o,["vars",a],s),n.push(a));return{changed:n,text:o}},Ve=(e,t)=>{e.info(`next: \`<provider>/<model>\` slugs (e.g. "anthropic/claude-sonnet-5") now route through gateway "${t}". Before the first call,`),e.info(` configure how the provider is paid for in the Cloudflare dashboard (AI > AI Gateway > ${t}):`),e.info(` - Unified Billing (OpenAI, Anthropic, Google, xAI, Groq, DeepSeek): load credits — ${te.unifiedBilling}`),e.info(` - a key stored on the gateway (Mistral, Perplexity, OpenRouter, …): ${te.byok}`),e.info(" Then redeploy (`lunora deploy`) so the Worker picks up the new vars.")},Xe=async(e,t,r,o,n,a)=>{const s=`${Ye}/${encodeURIComponent(r)}/ai-gateway/gateways`,i=await re(t,`${s}/${encodeURIComponent(n)}`,o);if(i.ok){const d=i.body?.result?.collect_logs;return{action:"existing",collectLogs:typeof d=="boolean"?d:a}}if(i.status===401||i.status===403)return A(e,L(i.status),`ai-gateway: could not read AI Gateway "${n}" (${oe(i)})`);const c=await re(t,s,o,{body:JSON.stringify({cache_invalidate_on_update:!0,cache_ttl:0,collect_logs:a,id:n,rate_limiting_interval:0,rate_limiting_limit:0}),method:"POST"});return c.ok?{action:"created",collectLogs:a}:A(e,L(c.status),`ai-gateway: could not create AI Gateway "${n}" (${oe(c)})`)},ze=e=>{const{logger:t}=e,r=W(e.cwd);if(r===void 0)return A(t,l.NOT_FOUND,"ai-gateway: no wrangler.jsonc found — run `lunora init` (or `lunora dev`) first.");const{parsed:o,text:n}=H(r);if(o===void 0)return A(t,l.USAGE,`ai-gateway: could not parse ${r} as JSONC.`);const a=Q(e.id)??Q(o.name);return a===void 0?A(t,l.USAGE,"ai-gateway: no gateway id — pass --id <id>, or set `name` in wrangler.jsonc."):a.length>ee?A(t,l.USAGE,`ai-gateway: gateway id "${a}" is longer than ${String(ee)} characters — pass a shorter --id.`):{gatewayId:a,parsed:o,text:n,wranglerPath:r}},G=e=>e?"on":"off",Qe=(e,t)=>(e.info(`ai-gateway (dry run): would create or reuse AI Gateway "${t.gatewayId}" (log collection ${G(t.collectLogs)}).`),e.info(t.varsWritten.length===0?`ai-gateway (dry run): ${t.wranglerPath} vars are already up to date.`:`ai-gateway (dry run): would write ${t.varsWritten.join(", ")} into ${t.wranglerPath} vars.`),t.accountId===void 0&&e.warn("ai-gateway (dry run): no CLOUDFLARE_ACCOUNT_ID (or `account_id` in wrangler.jsonc) — a real run will stop there."),{code:0,data:t}),Ze=async e=>{const{logger:t}=e,r=ze(e);if("code"in r)return r;const{gatewayId:o,parsed:n,text:a,wranglerPath:s}=r,i=e.logs!==!1,{accountId:c,token:d}=Y(e.environment??process.env,n.account_id),m={[Be]:o,...c===void 0?{}:{[xe]:c}},u=Ke(a,n.vars,m);if(e.dryRun===!0)return Qe(t,{accountId:c,action:"planned",collectLogs:i,dryRun:!0,gatewayId:o,varsWritten:u.changed,wranglerPath:s});if(d===void 0||c===void 0){const h=[d===void 0?"CLOUDFLARE_API_TOKEN (an API token with AI Gateway Write)":void 0,c===void 0?"CLOUDFLARE_ACCOUNT_ID (or `account_id` in wrangler.jsonc)":void 0].filter(p=>p!==void 0);return A(t,l.AUTH,`ai-gateway: missing ${h.join(" and ")}.`)}const g=await Xe(t,e.fetch??globalThis.fetch.bind(globalThis),c,d,o,i);return"code"in g?g:(g.action==="created"?t.success(`ai-gateway: created AI Gateway "${o}" (log collection ${G(g.collectLogs)}).`):t.info(`ai-gateway: AI Gateway "${o}" already exists — reusing it (log collection ${G(g.collectLogs)}; change it in the dashboard).`),u.changed.length>0?($e(s,u.text,"utf8"),t.success(`ai-gateway: wrote ${u.changed.join(", ")} into ${s} vars.`)):t.info(`ai-gateway: ${s} vars are already up to date.`),Ve(t,o),{code:0,data:{accountId:c,action:g.action,collectLogs:g.collectLogs,dryRun:!1,gatewayId:o,varsWritten:u.changed,wranglerPath:s}})},et=15e3,tt="https://api.cloudflare.com/client/v4/graphql",T={analytics:"Account Analytics Read",notificationsRead:"Notifications Read",notificationsWrite:"Notifications Write"},rt={auth:l.AUTH,failure:l.FAILURE,"not-found":l.NOT_FOUND,permission:l.PERMISSION,"rate-limited":l.RATE_LIMITED,rejected:l.USAGE,unavailable:l.UNAVAILABLE};class E extends Error{kind;status;constructor(t,r,o){super(t),this.name="CloudflareApiError",this.kind=r,this.status=o}}const ot=e=>e===401?"auth":e===403?"permission":e===404?"not-found":e===429?"rate-limited":e>=500?"unavailable":"rejected",Ee=e=>{try{const r=JSON.parse(e);if(Array.isArray(r.errors)){const o=r.errors.map(n=>typeof n=="object"&&n!==null&&"message"in n?String(n.message):void 0).filter(n=>n!==void 0&&n.length>0);if(o.length>0)return o}}catch{}const t=e.trim().slice(0,200);return t.length>0?[t]:[]},nt=9106,at=(e,t)=>{try{const r=JSON.parse(e);return Array.isArray(r.errors)&&r.errors.some(o=>typeof o=="object"&&o!==null&&"code"in o&&o.code===t)}catch{return!1}},ne=(e,t,r,o)=>{const n=t===400&&at(r,nt)?"auth":ot(t),a=Ee(r).join("; ");let s="";return n==="auth"?s=` — check that CLOUDFLARE_API_TOKEN is a valid token; it needs the "${o}" permission on this account`:n==="permission"&&(s=` — the API token needs the "${o}" permission on this account`),new E(`${e} failed (HTTP ${String(t)})${a.length>0?`: ${a}`:""}${s}.`,n,t)},ae=(e,t)=>{const r=t instanceof Error&&(t.name==="TimeoutError"||t.name==="AbortError");let o=t instanceof Error?t.message:String(t);return r&&(o="no answer in time"),new E(`${e} failed: ${o}.`,"unavailable")},st=10,it=e=>{const{accountId:t,token:r}=e,o=e.timeoutMs??et,n=e.fetch??globalThis.fetch.bind(globalThis),a=async(s,i,c,d)=>{let m;try{m=await Fe({accountId:t,apiToken:r,fetch:n,init:{method:i,signal:AbortSignal.timeout(o),...d===void 0?{}:{body:JSON.stringify(d)}},path:c})}catch(u){throw ae(s,u)}if(!m.ok)throw ne(s,m.status,m.text,i==="GET"?T.notificationsRead:T.notificationsWrite);return m.body};return{accountId:t,graphql:async(s,i,c={})=>{let d;try{d=await n(tt,{body:JSON.stringify({query:i,variables:c}),headers:{Authorization:`Bearer ${r}`,"Content-Type":"application/json"},method:"POST",signal:AbortSignal.timeout(o)})}catch(u){throw ae(s,u)}const m=await d.text();if(!d.ok)throw ne(s,d.status,m,T.analytics);try{const u=JSON.parse(m);return{data:u.data??void 0,errors:Array.isArray(u.errors)&&u.errors.length>0?Ee(m):[]}}catch{throw new E(`${s} failed: the GraphQL API answered with something that is not JSON.`,"unavailable",d.status)}},notifications:async(s,i,c,d)=>(await a(s,i,c,d)).result,notificationsList:async(s,i,c=st)=>{const d=async m=>{const u=await a(s,"GET",`${i}${i.includes("?")?"&":"?"}page=${String(m)}`),g=Array.isArray(u.result)?u.result:[],h=u.result_info;return typeof h?.total_pages=="number"&&m<h.total_pages&&m<c?[...g,...await d(m+1)]:g};return d(1)}}},S="billing_usage_alert",se={"do-duration":"worker_durable_objects_duration","do-requests":"worker_durable_objects_requests","do-rows-read":"worker_durable_objects_storage_reads","do-rows-written":"worker_durable_objects_storage_writes","workers-requests":"worker_requests"},ct=6,N=e=>typeof e=="object"&&e!==null&&!Array.isArray(e)?e:void 0,R=(e,t)=>{const r=t.toLowerCase(),o=Object.keys(e).find(n=>n.toLowerCase()===r);return o===void 0?void 0:e[o]},F=(e,t)=>{for(const r of t){const o=R(e,r);if(typeof o=="string"&&o.length>0)return o}},dt=e=>{if(typeof e=="string"&&e.length>0)return{id:e,source:"available-alerts"};const t=N(e),r=t===void 0?void 0:F(t,["id","value","key","name"]);if(t===void 0||r===void 0)return;const o=F(t,["description","label","display_name","displayName","name"]);return{id:r,source:"available-alerts",...o===void 0||o===r?{}:{label:o}}},lt=["AvailableValues","available_values","values","options","enum","choices"],Te=e=>e.map(t=>dt(t)).filter(t=>t!==void 0),ut=e=>F(e,["key","name","filter","id"])!=="product"?[]:lt.flatMap(t=>{const r=R(e,t);return Array.isArray(r)?Te(r):[]}),x=(e,t,r)=>{if(t>ct)return;if(Array.isArray(e)){for(const n of e)x(n,t+1,r);return}const o=N(e);if(o!==void 0){r.push(...ut(o));for(const[n,a]of Object.entries(o))n.toLowerCase()==="product"&&Array.isArray(a)?r.push(...Te(a)):typeof a=="object"&&a!==null&&x(a,t+1,r)}},ft=e=>{const t=N(e);if(t!==void 0){for(const r of Object.values(t))if(Array.isArray(r)){const o=r.map(n=>N(n)).find(n=>n!==void 0&&R(n,"type")===S);if(o!==void 0)return o}}},mt=e=>e.filter(t=>t.alert_type===S&&Array.isArray(t.filters?.product)).flatMap(t=>(t.filters?.product).filter(r=>typeof r=="string"&&r.length>0)).map(t=>({id:t,source:"existing-policy"})),ht=(e,t,r)=>{const o=ft(e),n=[];o!==void 0&&x(R(o,"filter_options"),0,n);const a=new Map;for(const s of[...n,...mt(r)])a.has(s.id)||a.set(s.id,s);return{eligible:t?o!==void 0:void 0,products:[...a.values()]}},gt=/[^a-z\d]+/u,pt=e=>`${e.id} ${e.label??""}`.toLowerCase().split(gt).filter(t=>t.length>0),yt={"d1-rows-read":{all:[["d1"],["read"]]},"d1-rows-written":{all:[["d1"],["writ"]]},"do-duration":{all:[["durable"],["duration"]]},"do-requests":{all:[["durable"],["request"]]},"do-rows-read":{all:[["durable"],["read"]],none:["request"]},"do-rows-written":{all:[["durable"],["writ"]]},"workers-cpu":{all:[["worker"],["cpu"]],none:["durable"]},"workers-requests":{all:[["worker"],["request"]],none:["durable","cpu","kv","d1"]}},wt=(e,t)=>{const r=pt(t),o=s=>r.some(i=>i.startsWith(s)),{all:n,none:a=[]}=yt[e];return n.every(s=>s.some(i=>o(i)))&&!a.some(s=>o(s))},Ie=(e,t)=>{const r=se[e],o=r===void 0?void 0:t.find(s=>s.id===r);if(o!==void 0)return{product:o,status:"matched"};const n=new Set(Object.values(se)),a=t.filter(s=>!n.has(s.id)&&wt(e,s));return a.length===1&&a[0]!==void 0?{product:a[0],status:"matched"}:a.length>1?{candidates:a.map(s=>s.id),status:"ambiguous"}:r===void 0?{status:"no-product"}:{product:{id:r,source:"documented"},status:"matched"}},ie="workersInvocationsAdaptive",vt="durableObjectsInvocationsAdaptiveGroups",j="durableObjectsPeriodicGroups",ce="d1AnalyticsAdaptiveGroups",_=[{candidates:[{field:"requests",unit:"count"}],dataset:ie,filter:"datetime",id:"workers-requests",label:"Workers requests"},{candidates:[{field:"cpuTimeUs",unit:"microseconds"}],dataset:ie,filter:"datetime",id:"workers-cpu",label:"Workers CPU time"},{candidates:[{field:"requests",unit:"count"}],dataset:vt,filter:"date",id:"do-requests",label:"Durable Objects requests"},{candidates:[{field:"activeTime",unit:"unknown"}],dataset:j,filter:"date",id:"do-duration",label:"Durable Objects duration"},{candidates:[{field:"rowsRead",unit:"count"}],dataset:j,filter:"date",id:"do-rows-read",label:"Durable Objects rows read"},{candidates:[{field:"rowsWritten",unit:"count"}],dataset:j,filter:"date",id:"do-rows-written",label:"Durable Objects rows written"},{candidates:[{field:"rowsRead",unit:"count"}],dataset:ce,filter:"datetime-hour",id:"d1-rows-read",label:"D1 rows read"},{candidates:[{field:"rowsWritten",unit:"count"}],dataset:ce,filter:"datetime-hour",id:"d1-rows-written",label:"D1 rows written"}],de=e=>String(e).padStart(2,"0"),bt=e=>{const t=new Date(Date.UTC(e.getUTCFullYear(),e.getUTCMonth()-1,1)),r=new Date(Date.UTC(e.getUTCFullYear(),e.getUTCMonth(),0)),o=new Date(Date.UTC(e.getUTCFullYear(),e.getUTCMonth(),1)),n=a=>`${String(a.getUTCFullYear())}-${de(a.getUTCMonth()+1)}-${de(a.getUTCDate())}`;return{endDate:n(r),nextStartDate:n(o),startDate:n(t)}},$t=(e,t)=>{const r=JSON.stringify(`${t.startDate}T00:00:00Z`),o=JSON.stringify(`${t.nextStartDate}T00:00:00Z`);switch(e){case"date":return`{ date_geq: ${JSON.stringify(t.startDate)}, date_lt: ${JSON.stringify(t.nextStartDate)} }`;case"datetime":return`{ datetime_geq: ${r}, datetime_lt: ${o} }`;default:return`{ AND: [{ datetimeHour_geq: ${r}, datetimeHour_lt: ${o} }] }`}},At=e=>`query LunoraTypeFields { __type(name: ${JSON.stringify(e)}) { fields { name type { name ofType { name ofType { name ofType { name } } } } } } }`,St=e=>{let t=e;for(;t!=null;){if(typeof t.name=="string"&&t.name.length>0)return t.name;t=t.ofType}},_t=e=>{const t=new Map;return async r=>{const o=t.get(r);if(o!==void 0)return o;const n=e.graphql(`Reading the analytics schema (${r})`,At(r)).then(a=>{if(a.errors.length>0)throw new E(`Reading the analytics schema failed: ${a.errors.join("; ")}.`,"rejected");const i=a.data?.__type?.fields??[];return new Map(i.map(c=>[c.name,St(c.type)]))});return t.set(r,n),n}},Oe=async(e,t,r)=>{const o=await e(t),[n,...a]=r;if(n===void 0)return o;const s=o.get(n);if(s===void 0)throw new E(`the analytics schema has no \`${n}\` on \`${t}\``,"rejected");return Oe(e,s,a)},Et=e=>e instanceof Error?e.message:String(e),Tt=async(e,t,r,o,n)=>{const{id:a,label:s}=o;try{const i=await Oe(t,r,["viewer","accounts",o.dataset,"sum"]),c=o.candidates.find(p=>i.has(p.field));if(c===void 0){const p=o.candidates.map(f=>`\`${f.field}\``).join(", ");return{id:a,label:s,reason:`\`${o.dataset}.sum\` exposes no ${p} field`,status:"unavailable"}}const d=`query LunoraUsage($accountTag: string) { viewer { accounts(filter: { accountTag: $accountTag }) { ${o.dataset}(limit: 1, filter: ${$t(o.filter,n)}) { sum { ${c.field} } } } } }`,m=await e.graphql(`Reading ${s}`,d,{accountTag:e.accountId});if(m.errors.length>0)return{id:a,label:s,reason:m.errors.join("; "),status:"unavailable"};const u=m.data?.viewer?.accounts?.[0]?.[o.dataset],g=Array.isArray(u)?u[0]:void 0,h=g===void 0?0:g.sum?.[c.field];return typeof h!="number"||!Number.isFinite(h)?{id:a,label:s,reason:`the response carried no number for \`${c.field}\``,status:"unavailable"}:{field:`${o.dataset}.sum.${c.field}`,id:a,label:s,status:"ok",unit:c.unit,value:h}}catch(i){return{id:a,label:s,reason:Et(i),status:"unavailable"}}},It=async(e,t)=>{const r=await e.graphql("Reading the analytics schema","query LunoraQueryRoot { __schema { queryType { name } } }"),o=r.data?.__schema?.queryType?.name;if(r.errors.length>0||o===void 0){const a=r.errors.length>0?r.errors.join("; "):"the schema root could not be read";return _.map(({id:s,label:i})=>({id:s,label:i,reason:a,status:"unavailable"}))}const n=_t(e);return Promise.all(_.map(async a=>Tt(e,n,o,a,t)))},D="Lunora usage: ",Ot=3,K="Cloudflare does not document the unit of a usage alert's limit; limits are sent as plain request counts. Check the stored limit in the dashboard.",kt={"do-requests":1e6,"workers-requests":1e7},Ct=100,Nt=e=>{const t=Math.ceil(e);if(t<=0)return 0;const r=10**Math.max(0,Math.floor(Math.log10(t))-1);return Math.ceil(t/r)*r},Ut=(e,t,r)=>{const o=Nt(e*t);return o>r?{basis:"history",threshold:o}:{basis:"floor",threshold:r}},B=e=>{const t=e.filters?.product;return Array.isArray(t)?t.filter(r=>typeof r=="string"):[]},Rt=e=>{const t=e.filters?.limit,r=Array.isArray(t)?t[0]:void 0,o=typeof r=="string"?Number(r):Number.NaN;return Number.isFinite(o)?o:void 0},V=e=>{const t={};for(const[r,o]of Object.entries(e?.mechanisms??{}))Array.isArray(o)&&(t[r]=o.filter(n=>typeof n=="object"&&n!==null&&"id"in n&&typeof n.id=="string"));return t},Dt=(e,t)=>{const r={};for(const[o,n]of[...Object.entries(e),...Object.entries(t)]){const a=new Set((r[o]??[]).map(s=>s.id));r[o]=[...r[o]??[],...n.filter(s=>!a.has(s.id))]}return Object.fromEntries(Object.entries(r).filter(([,o])=>o.length>0))},U=e=>Object.entries(e).flatMap(([t,r])=>r.map(o=>`${t}:${o.id}`)),Mt=(e,t)=>JSON.stringify(U(e).toSorted((r,o)=>r.localeCompare(o)))===JSON.stringify(U(t).toSorted((r,o)=>r.localeCompare(o))),jt=(e,t)=>e.enabled===!0&&e.name===t.name&&JSON.stringify(e.filters?.limit)===JSON.stringify(t.filters.limit)&&JSON.stringify(B(e))===JSON.stringify(t.filters.product)&&Mt(V(e),t.mechanisms),Lt=(e,t)=>{const r={};return e.length>0&&(r.email=e.map(o=>({id:o}))),t.length>0&&(r.webhooks=t.map(o=>({id:o}))),r},Pt=(e,t,r)=>{const o=r.thresholds?.[e],n=r.usage.find(c=>c.id===e),a=n?.status==="ok"?n.value:void 0;if(o!==void 0)return{basis:"explicit",lastMonth:a,threshold:o};const s=kt[e];return s===void 0?{kind:"unit-unverified",reason:`the unit Cloudflare meters "${t.id}" in is not documented and cannot be matched to the usage reading; set one yourself with --threshold ${e}=<n>`}:a!==void 0?{...Ut(a,r.multiplier,s),lastMonth:a}:r.allowFloor===!0?{basis:"floor-usage-unavailable",lastMonth:void 0,threshold:s}:{kind:"usage-unavailable",reason:`last month's usage could not be read (${n?.status==="unavailable"?n.reason:"no reading"}), and an alert at the floor could fire every month on an account that already exceeds it; pass --threshold ${e}=<n>, or --allow-floor`}},Gt=(e,t)=>{const r=Rt(e);if(r===void 0||t===void 0||r<=0||t<=0)return;const o=Math.max(r/t,t/r);return o>=Ct?`its limit ${String(r)} differs from the ${String(t)} this would plan by ${String(Math.round(o))}× — one of the two may be in the wrong unit`:void 0},q=e=>`${D}${e}`,Ft=(e,t)=>e===void 0?"create":jt(e,t)?"unchanged":"update",xt=(e,t)=>{switch(e){case"explicit":return"set with --threshold";case"floor-usage-unavailable":return"the included monthly allowance, applied with --allow-floor because usage could not be read";case"history":return`${String(t)}× last month`;default:return"the included monthly allowance (floor)"}},Bt=(e,t,r)=>{const{id:o,label:n}=e,a=Ie(o,t.products);if(a.status==="no-product")return{kind:"no-product",metric:o,reason:"Cloudflare has no usage alert for this product; the account-wide budget alert is its guard"};if(a.status==="ambiguous")return{kind:"ambiguous",metric:o,reason:`several offered products could mean this metric (${a.candidates.join(", ")})`};const{product:s}=a,i=r.find(y=>y.name===q(n)),c=r.find(y=>y.enabled===!0&&y.name?.startsWith(D)!==!0&&B(y).includes(s.id)),d=Pt(o,s,t);if(i===void 0&&c!==void 0){const y=Gt(c,"threshold"in d?d.threshold:void 0);return{kind:"covered",metric:o,reason:`already alerted by the existing policy "${c.name??c.id??"?"}"`,...y===void 0?{}:{warning:y}}}if(!("threshold"in d))return{...d,metric:o};const m=Lt(t.emails,t.webhooks),u=V(i),g=i===void 0||t.replaceRecipients===!0?m:Dt(u,m),h=new Set(U(u)),p=new Set(U(g)),f={alert_type:S,description:`Managed by \`lunora cloudflare alerts setup\`: ${xt(d.basis,t.multiplier)}.`,enabled:!0,filters:{limit:[String(d.threshold)],product:[s.id]},mechanisms:g,name:q(n)},w=i===void 0?[]:B(i);return{action:Ft(i,f),basis:d.basis,body:f,lastMonth:d.lastMonth,metric:o,...i?.id===void 0?{}:{policyId:i.id},...i!==void 0&&JSON.stringify(w)!==JSON.stringify([s.id])?{previousProduct:w}:{},product:s.id,productSource:s.source,recipients:{added:[...p].filter(y=>!h.has(y)),removed:[...h].filter(y=>!p.has(y))},threshold:d.threshold}},qt=e=>{const t=e.policies.filter(n=>n.alert_type===S),r=new Set(_.map(n=>q(n.label))),o={alerts:[],duplicates:[],orphans:t.filter(n=>n.name?.startsWith(D)===!0&&!r.has(n.name)),skipped:[]};for(const n of r)o.duplicates.push(...t.filter(a=>a.name===n).slice(1));for(const n of _){const a=Bt(n,e,t);"action"in a?o.alerts.push(a):o.skipped.push(a)}return o},Jt="Cloudflare's API has no endpoint that sends a test notification — not for webhooks and not for email — so `lunora cloudflare alerts test` sends nothing.",Wt="To test a webhook for real, create it in the dashboard (Alerts > Destinations > Webhooks > Create) and finish with Save and Test.",Ht="Email destinations cannot be tested at all: Cloudflare offers no test send for them. Check the address on each policy below instead.",le=e=>Array.isArray(e)?e:[],ue=30,Yt=async(e,t,r,o,n)=>{const a=t.filter(f=>f.alert_type===S&&f.name?.startsWith(D)===!0),s=a.map(f=>V(f)),i=new Set([...s.flatMap(f=>(f.webhooks??[]).map(w=>w.id)),...r]),c=[...new Set(s.flatMap(f=>(f.email??[]).map(w=>w.id)))],d=new Set(a.map(f=>f.id)),m=new Date(n.getTime()-ue*24*60*60*1e3).toISOString(),[u,g]=await Promise.all([e.notifications("Listing webhook destinations","GET","/alerting/v3/destinations/webhooks"),a.length===0?Promise.resolve([]):e.notificationsList("Reading notification history",`/alerting/v3/history?per_page=25&since=${encodeURIComponent(m)}`)]),h=le(u).map(f=>({...f,referenced:f.id!==void 0&&i.has(f.id)})),p=le(g).filter(f=>f.alert_type===S&&f.policy_id!==void 0&&d.has(f.policy_id));o.warn(Jt),a.length===0&&o.info("No `lunora cloudflare alerts setup` policies exist on this account yet — run `lunora cloudflare alerts setup` first.");for(const f of[...i].filter(w=>!h.some(y=>y.id===w)))o.warn(`Webhook destination ${f} is referenced but does not exist on this account.`);for(const f of h.filter(w=>w.referenced))o.info(`webhook "${f.name??f.id??"?"}" (${f.type??"generic"}): last delivered ${f.last_success??"never"}, last failed ${f.last_failure??"never"}`);if(o.info(Wt),c.length>0&&o.info(`${Ht} Addresses on the policies: ${c.join(", ")}.`),p.length===0)o.info(`Cloudflare's notification history shows nothing sent for these policies in the last ${String(ue)} days (they only fire once a threshold is crossed).`);else for(const f of p)o.info(`sent ${f.sent??"?"}: "${f.name??"?"}" via ${f.mechanism_type??"?"} to ${f.mechanism??"?"}`);return{emails:c,history:p,testSent:!1,webhooks:h}},M="Budget alert (account-wide USD threshold): Cloudflare documents no API to create or read one, so this cannot be checked. Create it in the dashboard: Manage Account > Billing > Billable Usage > Create budget alert.",Kt="Alerts > Overview > Create an Alert, alert type Usage Based Billing",$=(e,t,r,o)=>(e.error(r),{code:t,error:r,...o===void 0?{}:{data:o}}),X=(e,t,r)=>{if(t instanceof E)return $(e,rt[t.kind],t.message,r);throw t},z=(e,t)=>({accountId:e.accountId,budgetAlert:{checkable:!1,dashboardPath:"Manage Account > Billing > Billable Usage"},limitUnitCaveat:K,...t===void 0?{}:{eligible:t.discovery.eligible,period:t.period,products:t.discovery.products}}),O=e=>e.toLocaleString("en-US",{maximumFractionDigits:0}),ke=(e,t)=>{t===!1&&e.warn("This account is not eligible for Usage Based Billing notifications (they are offered to Pay-as-you-go accounts; most Enterprise contracts are not supported).")},Ce=e=>({code:l.SUCCESS,data:e}),Vt=/^[^\s@]+@[^\s@][^\s.@]*\.[^\s@]+$/u,Ne=new Set(_.map(e=>e.id)),Xt=e=>Ne.has(e),zt=e=>{const t={};for(const r of e.flatMap(o=>o.split(","))){const[o="",n=""]=r.split("=").map(s=>s.trim()),a=Number(n);if(!Xt(o))return{error:`--threshold "${r}": unknown metric "${o}" — one of ${[...Ne].join(", ")}.`};if(!Number.isFinite(a)||a<=0)return{error:`--threshold "${r}": the limit must be a positive number.`};t[o]=Math.ceil(a)}return t},Qt=e=>{const t=(e.emails??[]).flatMap(s=>s.split(",")).map(s=>s.trim()).filter(s=>s.length>0),r=(e.webhooks??[]).map(s=>s.trim()).filter(s=>s.length>0),o=e.multiplier===void 0?Ot:Number(e.multiplier),n=zt(e.thresholds??[]);if(t.length===0&&r.length===0)return{error:"alerts setup needs somewhere to send the alerts: pass --email <address> and/or --webhook <destination-id>."};const a=t.find(s=>!Vt.test(s));return a!==void 0?{error:`--email "${a}" is not an email address.`}:!Number.isFinite(o)||o<1?{error:`--multiplier must be a number of at least 1 (got "${e.multiplier??""}").`}:"error"in n?n:{allowFloor:e.allowFloor===!0,emails:t,multiplier:o,replaceRecipients:e.replaceRecipients===!0,thresholds:n,webhooks:r}},Zt={explicit:()=>"set with --threshold",floor:e=>`floor: included monthly allowance; last month ${O(e.lastMonth??0)}`,"floor-usage-unavailable":()=>"floor: usage could not be read, applied with --allow-floor",history:e=>`last month ${O(e.lastMonth??0)}`},er=e=>{const t=[...e.added.map(r=>`+${r}`),...e.removed.map(r=>`-${r}`)];return t.length===0?"recipients unchanged":`recipients ${t.join(" ")}`},tr=e=>{const t=e.productSource==="documented"?"documented id":"offered by the account",r=e.previousProduct===void 0?"":`, product was ${e.previousProduct.join(", ")||"none"}`;return`${e.action.padEnd(9)} ${e.body.name} — product ${e.product} (${t}${r}), limit ${O(e.threshold)} (${Zt[e.basis](e)}); ${er(e.recipients)}`},J=e=>_.find(t=>t.id===e)?.label??e,rr=(e,t,r,o)=>{o.info(`Usage alerts at ${String(t)}× last month (${r.startDate} to ${r.endDate}), never below the included allowance:`);for(const n of e.alerts)o.info(` ${tr(n)}`);for(const n of e.skipped)o.info(` skipped ${J(n.metric)} — ${n.reason}`),n.warning!==void 0&&o.warn(`${J(n.metric)}: the existing alert ${n.warning}.`);for(const n of e.orphans)o.warn(`"${n.name??"?"}" (${n.id??"?"}) is named like a \`lunora cloudflare alerts\` policy but matches no metric; it was left alone.`);for(const n of e.duplicates)o.warn(`"${n.name??"?"}" exists more than once; ${n.id??"?"} was left alone — delete the extra one in the dashboard.`);e.skipped.some(n=>n.kind==="unit-unverified"||n.kind==="ambiguous")&&o.info(`To set the skipped ones by hand: ${Kt}.`),o.info(K),o.info(M)},or=async(e,t)=>{if(e.yes===!0)return;if(e.confirm===void 0&&(!process.stdin.isTTY||e.format==="json"))return $(e.logger,l.USAGE,"alerts setup: refusing to change notification policies without confirmation — re-run with --yes.");const r=t.flatMap(a=>a.recipients.removed),o=r.length===0?"":` This REMOVES recipients: ${[...new Set(r)].join(", ")}.`;if(!await(e.confirm??qe)(`Apply ${String(t.length)} notification policy change(s)?${o}`))return e.logger.info("alerts setup: aborted"),{code:l.CANCELLED,error:"alerts setup: aborted at the confirmation prompt"}},nr=async(e,t,r,o)=>{const a=(await Promise.all(t.map(async s=>e.notifications(`Reading webhook destination ${s}`,"GET",`/alerting/v3/destinations/webhooks/${encodeURIComponent(s)}`).then(()=>{},i=>({error:i,id:s}))))).find(s=>s!==void 0);if(a!==void 0)return a.error instanceof E&&a.error.kind==="not-found"?$(r,l.USAGE,`--webhook ${a.id}: no such webhook destination on account ${e.accountId}.`,o):X(r,a.error,o)},ar=async(e,t)=>{const r=t.action==="create"?await e.notifications(`Creating "${t.body.name}"`,"POST","/alerting/v3/policies",t.body):await e.notifications(`Updating "${t.body.name}"`,"PUT",`/alerting/v3/policies/${encodeURIComponent(t.policyId??"")}`,t.body);return typeof r=="object"&&r!==null&&"id"in r&&typeof r.id=="string"?r.id:t.policyId},sr=async(e,t,r)=>await Promise.all(t.map(async({alert:n,id:a})=>{try{const s=await e.notifications(`Reading back "${n.body.name}"`,"GET",`/alerting/v3/policies/${encodeURIComponent(a)}`),i={enabled:s?.enabled,id:a,limit:s?.filters?.limit,name:s?.name,product:s?.filters?.product};return r.info(`Cloudflare stored "${i.name??n.body.name}": product ${JSON.stringify(i.product)}, limit ${JSON.stringify(i.limit)}.`),JSON.stringify(i.limit)!==JSON.stringify(n.body.filters.limit)&&r.warn(`"${n.body.name}": Cloudflare stored limit ${JSON.stringify(i.limit)}, not the ${JSON.stringify(n.body.filters.limit)} sent.`),i}catch(s){return r.warn(`Could not read "${n.body.name}" back: ${s instanceof Error?s.message:String(s)}`),{id:a}}})),ir=async(e,t,r,o)=>{const n=[],a=[];let s;for(const c of t)try{const d=await ar(e,c);n.push({action:c.action,metric:c.metric,...d===void 0?{}:{policyId:d}}),d!==void 0&&a.push({alert:c,id:d}),r.success(`${c.action==="create"?"Created":"Updated"} "${c.body.name}".`)}catch(d){s=d;break}const i={...o,applied:n,stored:await sr(e,a,r)};return s===void 0?i:X(r,s,i)},fe=(e,t,r)=>{const o=t.skipped.filter(n=>n.kind==="usage-unavailable");return o.length>0?$(r,l.FAILURE,`alerts setup: no alert was set for ${o.map(n=>J(n.metric)).join(", ")} because last month's usage could not be read — pass --threshold <metric>=<n>, or --allow-floor to accept the floor.`,e):{code:l.SUCCESS,data:e}},cr=async(e,t,r,o)=>{const{logger:n}=r,a=z(e,t),s=await nr(e,o.webhooks,n,a);if(s!==void 0)return s;if(t.discovery.eligible===!1)return ke(n,!1),n.info(M),$(n,l.PERMISSION,"alerts setup: the account cannot create Usage Based Billing notifications.",a);const i=qt({...o,policies:t.policies,products:t.discovery.products,usage:t.usage});a.plan=i,rr(i,o.multiplier,t.period,n);const c=i.alerts.filter(u=>u.action!=="unchanged");if(r.dryRun===!0||c.length===0)return n.info(r.dryRun===!0?"Dry run: nothing was changed.":"Every alert is already up to date."),fe(a,i,n);const d=await or(r,c);if(d!==void 0)return{...d,data:a};const m=await ir(e,c,n,a);return"code"in m?m:fe(m,i,n)},dr=e=>e.status!=="ok"?`unavailable (${e.reason})`:e.unit==="microseconds"?`${O(e.value)} µs`:O(e.value),lr=(e,t,r)=>t?"no-product":e===void 0?"unknown":r.some(o=>o.enabled)?"active":r.length>0?"disabled-only":"none",me=e=>e.map(t=>`"${t.name??t.id??"?"}" (limit ${JSON.stringify(t.limit)})${t.enabled?"":" — disabled, not protecting you"}`).join(", "),ur={active:e=>`alert: ${me(e.alerts)}`,"disabled-only":e=>`alert: none active; ${me(e.alerts)}`,"no-product":()=>"alert: none possible — Cloudflare has no usage alert for this; the budget alert is its guard",none:()=>"alert: none",unknown:()=>"alert: unknown (several offered products could mean this)"},fr=(e,t,r)=>{const o=Ie(e.id,t.discovery.products),n=o.status==="matched"?o.product:void 0,a=(n===void 0?[]:r.filter(s=>Array.isArray(s.filters?.product)&&s.filters.product.includes(n.id))).map(s=>({enabled:s.enabled===!0,id:s.id,limit:s.filters?.limit,name:s.name}));return{alerts:a,coverage:lr(n?.id,o.status==="no-product",a),id:e.id,label:e.label,...n===void 0?{}:{product:n.id,productSource:n.source},usage:e}},mr=(e,t,r)=>{const o=t.policies.filter(a=>a.alert_type===S),n=t.usage.map(a=>fr(a,t,o));r.info(`Cloudflare account ${e.accountId} — usage ${t.period.startDate} to ${t.period.endDate}`);for(const a of n)r.info(` ${a.label}: ${dr(a.usage)} — ${ur[a.coverage](a)}`);return r.info(`Usage Based Billing notifications on the account: ${String(o.length)} (${String(o.filter(a=>a.enabled===!0).length)} enabled).`),r.info(K),ke(r,t.discovery.eligible),r.info(M),Ce({...z(e,t),metrics:n})},hr=e=>{const t=W(e);return t===void 0?void 0:H(t).parsed?.account_id},gr=e=>{const{accountId:t,token:r}=Y(e.environment??process.env,hr(e.cwd));return r===void 0?$(e.logger,l.AUTH,`CLOUDFLARE_API_TOKEN is not set. \`lunora cloudflare alerts\` calls the Cloudflare API with an API token (a wrangler login session is not reused); create one with the "${T.notificationsWrite}" and "${T.analytics}" permissions ("${T.notificationsRead}" is enough for status and test).`):t===void 0?$(e.logger,l.USAGE,"No Cloudflare account: set CLOUDFLARE_ACCOUNT_ID or `account_id` in wrangler.jsonc."):it({accountId:t,token:r,...e.fetch===void 0?{}:{fetch:e.fetch}})},Ue=async e=>{const t=await e.notifications("Listing notification policies","GET","/alerting/v3/policies");return Array.isArray(t)?t:[]},pr=async(e,t)=>{const r=bt(t.now??new Date),{logger:o}=t,[n,a,s]=await Promise.all([Ue(e),e.notifications("Listing the alert types this account is eligible for","GET","/alerting/v3/available_alerts").then(i=>({ok:!0,value:i}),i=>({error:i,ok:!1})),It(e,r).catch(i=>{const c=i instanceof Error?i.message:String(i);return o.warn(`Usage could not be read: ${c}`),_.map(({id:d,label:m})=>({id:d,label:m,reason:c,status:"unavailable"}))})]);return a.ok||o.warn(`Could not read which alert types the account is eligible for: ${a.error instanceof Error?a.error.message:String(a.error)}`),{discovery:ht(a.ok?a.value:void 0,a.ok,n),period:r,policies:n,usage:s}},yr=async(e,t)=>{const r=await Ue(e),o=await Yt(e,r,t.webhooks??[],t.logger,t.now??new Date);return t.logger.info(M),Ce({...z(e),deliveries:o})},wr=async e=>{const t=e.subcommand==="setup"?Qt(e):void 0;if(t!==void 0&&"error"in t)return $(e.logger,l.USAGE,t.error);const r=gr(e);if(!("graphql"in r))return r;try{if(e.subcommand==="test")return await yr(r,e);const o=await pr(r,e);return t===void 0?mr(r,o,e.logger):await cr(r,o,e,t)}catch(o){return X(e.logger,o)}},he=new Set(["build","delete","images","info","list","push"]),vr=new Set(["build","push"]),ge=new Set(["images list","info","list"]),br=async e=>{const[t,...r]=e.argument;if(t===void 0||!he.has(t)){const u=`lunora cloudflare containers requires a subcommand: ${[...he].toSorted((g,h)=>g.localeCompare(h)).join(" | ")}. Example: lunora cloudflare containers build ./containers/app --tag app:v1 --push`;return e.logger.error(u),{code:l.USAGE,error:u}}const o=e.format==="json",n=t==="images"?`images ${r[0]??""}`.trim():t;if(o&&!ge.has(n)){const u=`containers ${n}: --format json is only available for the read subcommands (${[...ge].toSorted((g,h)=>g.localeCompare(h)).join(" | ")}) — wrangler has no JSON rendering for the rest.`;return e.logger.error(u),{code:l.USAGE,error:u}}if(vr.has(t)&&!(e.dockerAvailable??Je)()){const u=`containers ${t} needs a running Docker-compatible engine (it builds/pushes images locally). Start Docker or Colima and retry. Note: container images must target linux/amd64.`;return e.logger.error(u),{code:l.MISSING_DEPENDENCY,error:u}}const a=["containers",t,...r];o&&a.push("--json"),e.tag!==void 0&&a.push("--tag",e.tag),e.push===!0&&a.push("--push"),e.env!==void 0&&a.push("--env",e.env);const s=e.cwd??process.cwd(),i=Se(_e(s),"wrangler",a),c={args:i.args,command:i.command,cwd:s};return e.logger.info(`running ${c.command} ${c.args.join(" ")}`),{code:(await(e.spawner??Ae)(c)).code,delegated:o,descriptor:c}},k=(e,t)=>(t!==void 0&&e.push("--env",t),e),$r=e=>{const t=k(["deployments","list"],e.env);return e.format==="json"&&t.push("--json"),t},Ar=e=>{switch(e.subcommand){case"inspect":return e.versionId===void 0?{error:"deployments inspect requires a version id. Usage: lunora cloudflare deployments inspect <version-id>"}:{args:k(["versions","view",e.versionId],e.env)};case"list":return{args:$r(e)};case"promote":{if(e.versionId===void 0)return{error:"deployments promote requires a version id. Usage: lunora cloudflare deployments promote <version-id> --yes"};if(!e.yes)return{error:"deployments promote shifts 100% of live traffic. Re-run with --yes to confirm."};const t=k(["versions","deploy",`${e.versionId}@100%`,"--yes"],e.env);return e.message!==void 0&&t.push("--message",e.message),{args:t}}case"rollback":{if(!e.yes)return{error:"deployments rollback changes the live version. Re-run with --yes to confirm."};const t=k(["rollback"],e.env);return e.versionId!==void 0&&t.push(e.versionId),t.push("--yes"),e.message!==void 0&&t.push("--message",e.message),{args:t}}default:return{error:`deployments: unknown subcommand "${e.subcommand}"`}}},Sr=async e=>{if(e.format==="json"&&e.subcommand!=="list"){const d=`deployments ${e.subcommand}: --format json is only available for \`deployments list\` — wrangler has no JSON rendering for the others.`;return e.logger.error(d),{code:l.USAGE,descriptor:void 0,error:d}}const{args:t,error:r}=Ar(e);if(r!==void 0||t===void 0)return e.logger.error(r??"deployments: nothing to run"),{code:l.USAGE,descriptor:void 0,error:r};const{logger:o}=e,n=e.cwd??process.cwd(),a=Se(_e(n),"wrangler",t),s={args:a.args,command:a.command,cwd:n};return o.info(`${s.command} ${s.args.join(" ")}`),{code:(await(e.spawner??Ae)(s)).code,delegated:e.format==="json",descriptor:s}},_r=e=>e==="list"||e==="inspect"||e==="rollback"||e==="promote",Er="https://api.cloudflare.com/client/v4/accounts",Re="Workers Scripts Read",pe=1e3,ye=5e4,Tr=1e4,Ir=3e4,we=[31,139],ve=["cpu","heap"],Or=/^[\da-f]{64}$/iu,b=(e,t,r)=>(e.error(r),{code:t,error:r}),be=e=>{try{const t=JSON.parse(e);if(Array.isArray(t.errors)){const r=t.errors.map(o=>typeof o=="object"&&o!==null&&"message"in o?String(o.message):"").filter(o=>o.length>0);if(r.length>0)return P(r.join("; "))}}catch{}return P(e.trim())},kr=e=>{switch(e){case 401:case 403:return` — check that CLOUDFLARE_API_TOKEN is valid and has the "${Re}" permission on this account`;case 404:return" — check the worker name, version, and (for a Durable Object) the namespace and actor ids";case 429:return" — rate limited; wait and retry";default:return""}},Cr=e=>{const t=e.type??"cpu";if(!ve.includes(t))return{error:`profile: invalid --type "${e.type??""}" — expected ${ve.join(" | ")}`};const r=e.durationMs===void 0?Tr:Number(e.durationMs);return!Number.isInteger(r)||r<pe||r>ye?{error:`profile: invalid --duration-ms "${e.durationMs??""}" — expected an integer from ${String(pe)} to ${String(ye)}`}:e.namespaceId===void 0!=(e.actorId===void 0)?{error:"profile: --namespace-id and --actor-id must be passed together to profile a Durable Object"}:e.actorId!==void 0&&!Or.test(e.actorId)?{error:"profile: --actor-id must be a 64-character hexadecimal Durable Object id"}:{durationMs:r,profileType:t}},Nr=e=>{const{logger:t}=e,r=W(e.cwd),o=r===void 0?void 0:H(r).parsed,{accountId:n,token:a}=Y(e.environment??process.env,o?.account_id);if(a===void 0)return b(t,l.AUTH,`CLOUDFLARE_API_TOKEN is not set. \`lunora cloudflare profile\` calls the Cloudflare API with an API token (a wrangler login session is not reused); create one with the "${Re}" permission.`);if(n===void 0)return b(t,l.USAGE,"No Cloudflare account: set CLOUDFLARE_ACCOUNT_ID or `account_id` in wrangler.jsonc.");const s=typeof o?.name=="string"&&o.name.length>0?o.name:void 0,i=e.worker??s;if(i===void 0)return b(t,l.USAGE,"profile: no Worker name — pass one, or set `name` in wrangler.jsonc.");const c=e.worker===void 0&&e.env!==void 0?`${i}-${e.env}`:i;return{accountId:n,sourceMapsMissing:o!==void 0&&o.upload_source_maps!==!0,token:a,worker:c}},Ur=(e,t)=>{const r=`${e}.${String(process.pid)}.tmp`;try{$e(r,t),Le(r,e);return}catch(o){return Pe(r,{force:!0}),o instanceof Error?o.message:String(o)}},Rr=async e=>{const{logger:t}=e,r=Cr(e);if("error"in r)return b(t,l.USAGE,r.error);const o=Nr(e);if("code"in o)return o;const{durationMs:n,profileType:a}=r,{accountId:s,token:i,worker:c}=o,d=e.version??"latest",m={duration_ms:n,profile_type:a,...e.namespaceId===void 0||e.actorId===void 0?{}:{actor_id:e.actorId,namespace_id:e.namespaceId}},u=`${Er}/${encodeURIComponent(s)}/workers/workers/${encodeURIComponent(c)}/versions/${encodeURIComponent(d)}/profile`,g=e.fetch??globalThis.fetch.bind(globalThis);t.info(`Profiling ${c}@${d} (${a}) for ${String(n)} ms — keep traffic flowing to it…`);let h;try{h=await g(u,{body:JSON.stringify(m),headers:{Authorization:`Bearer ${i}`,"Content-Type":"application/json"},method:"POST",signal:AbortSignal.timeout(n+Ir)})}catch(v){return b(t,l.UNAVAILABLE,`profile failed: ${v instanceof Error?v.message:String(v)}.`)}if(!h.ok){const v=be(await h.text());return b(t,L(h.status),`profile failed (HTTP ${String(h.status)})${v.length>0?`: ${v}`:""}${kr(h.status)}.`)}const p=new Uint8Array(await h.arrayBuffer());if(p[0]!==we[0]||p[1]!==we[1]){const v=be(new TextDecoder().decode(p));return b(t,l.FAILURE,`profile failed: the API answered 200 with something that is not a gzip profile${v.length>0?`: ${v}`:""}.`)}const f=(e.now??new Date).toISOString().replaceAll(/[:.]/gu,"-"),w=We(e.cwd,e.out??`${c}-${a}-${f}.pprof.gz`);je(He(w),{recursive:!0});const y=Ur(w,p);return y!==void 0?b(t,l.FAILURE,`profile failed: could not write ${w}: ${y}.`):(t.success(`Wrote ${String(p.byteLength)} bytes to ${w}`),t.info("Open it with `go tool pprof -http=: <file>` (pprof reads gzip directly) or upload it to a flamegraph viewer."),o.sourceMapsMissing&&t.warn("wrangler config has no `upload_source_maps: true` — TypeScript function names in the profile may be mangled."),{code:l.SUCCESS,data:{bytes:p.byteLength,durationMs:n,file:w,profileType:a,version:d,worker:c}})},Dr={ai:{absorbs:"gateway",tool:"ai-gateway"},alert:{tool:"alerts"}},Mr=(e,t)=>{const r=Dr[e];if(r!==void 0)return{rest:r.absorbs!==void 0&&t[0]===r.absorbs?t.slice(1):t,tool:r.tool};const o=C.find(n=>n.name===e)?.name;return o===void 0?void 0:{rest:t,tool:o}},jr={celld:"celld",node:"Node"},Lr=e=>e==="status"||e==="setup"||e==="test",I=(e,t,r)=>(e.error(r),{code:t,error:r}),Pr=e=>{const t=Math.max(...C.map(r=>r.name.length));e.info("lunora cloudflare <tool> — tools for an app deployed to your own Cloudflare account:");for(const r of C)e.info(` ${r.name.padEnd(t)} ${r.summary}`),r.usage!==""&&e.info(` ${" ".repeat(t)} lunora cloudflare ${r.name} ${r.usage}`);return e.info("Run `lunora cloudflare --help` for every tool's arguments and options."),{code:0}},Gr=(e,t,r)=>{const{error:o,target:n}=Me(e,r);return n===void 0?o??"no deploy target":n==="cloudflare"?void 0:`${r===void 0?`this project deploys to ${jr[n]??`"${n}"`}`:`\`--target ${n}\``} — \`lunora cloudflare ${t}\` only applies to Cloudflare.`},Fr=(e,{logger:t,rest:r})=>r.length===0?void 0:I(t,l.USAGE,`cloudflare ${e}: takes no arguments, got "${r.join(" ")}"`),xr=async e=>{const{cwd:t,logger:r,options:o}=e;return Fr("ai-gateway",e)??Ze({cwd:t,dryRun:o.dryRun===!0,id:o.id,logger:r,logs:o.logs})},Br=async({cwd:e,format:t,logger:r,options:o,rest:n})=>{const a=n[0]??"status";return Lr(a)?wr({allowFloor:o.allowFloor===!0,cwd:e,dryRun:o.dryRun===!0,format:t,logger:r,replaceRecipients:o.replaceRecipients===!0,subcommand:a,yes:o.yes===!0,...o.email===void 0?{}:{emails:o.email},...o.webhook===void 0?{}:{webhooks:o.webhook},...o.multiplier===void 0?{}:{multiplier:o.multiplier},...o.threshold===void 0?{}:{thresholds:o.threshold}}):I(r,l.USAGE,`cloudflare alerts: unknown subcommand "${a}" — expected status | setup | test`)},qr=async({cwd:e,format:t,logger:r,options:o,rest:n})=>{const a=await br({argument:n,cwd:e,env:o.env,format:t,logger:r,push:o.push===!0,tag:o.tag});return{code:a.code,delegated:a.delegated,error:a.error}},Jr=async({cwd:e,format:t,logger:r,options:o,rest:n})=>{const[a,s]=n;if(!_r(a))return I(r,l.USAGE,`cloudflare deployments: unknown subcommand "${a??""}" — expected list | inspect | rollback | promote`);const i=await Sr({cwd:e,env:o.env,format:t,logger:r,message:o.message,subcommand:a,versionId:s,yes:o.yes===!0});return{code:i.code,delegated:i.delegated,error:i.error}},Wr=async({cwd:e,logger:t,options:r,rest:o})=>o.length>1?I(t,l.USAGE,`cloudflare profile: takes at most one argument (the worker), got "${o.join(" ")}"`):Rr({actorId:r.actorId,cwd:e,durationMs:r.durationMs,env:r.env,logger:t,namespaceId:r.namespaceId,out:r.out,type:r.type,version:r.versionId,worker:o[0]}),Hr={"ai-gateway":xr,alerts:Br,containers:qr,deployments:Jr,profile:Wr},so=De(async({argument:e,cwd:t,format:r,logger:o,options:n})=>{const[a,...s]=e;if(a===void 0||a==="")return Pr(o);const i=Mr(a,s);if(i===void 0)return I(o,l.USAGE,`cloudflare: unknown tool "${a}" — expected ${C.map(m=>m.name).join(" | ")}`);const{tool:c}=i,d=Gr(t,c,n.target);return d!==void 0?I(o,l.USAGE,d):Hr[c]({cwd:t,format:r,logger:o,options:n,rest:i.rest})});export{so as execute};
@@ -7,5 +7,5 @@ ${r.join(`
7
7
  # Lunora — never commit a minted secret
8
8
  ${i.join(`
9
9
  `)}
10
- `,"utf8"),r.info(`.gitignore: added ${a.join(", ")} so the recorded secret cannot be committed`)}catch(t){r.warn(`could not update .gitignore (${t instanceof Error?t.message:String(t)}) — add \`${E.join("` and `")}\` by hand before committing.`)}},Ar=(e,r,o)=>{if(o.length===0)return;const t=o.map(s=>s.key).join(", ");if(r.env!==void 0&&!Sr.test(r.env)){r.logger.warn(`${t}: minted and pushed for --env ${r.env}, but "${r.env}" isn't a safe filename fragment — the value could not be recorded. Capture it manually if you need it again.`);return}const n=r.env===void 0?w:`${w}.${r.env}`;Er(e,r.logger);const a=y(e,n);let i=p(a)?k(a,"utf8"):"";for(const s of o)i=de(i,s.key,s.value);return le(a,i),r.logger.success(r.env===void 0?`${t}: value(s) recorded in ${n}`:`${t}: value(s) recorded in ${n} (kept separate from ${w} so \`lunora dev\` and a plain \`lunora env push\` don't inherit the --env ${r.env} value)`),n},Rr=async(e,r,o,t)=>{if(r.dryRun===!0||r.preview===!0)return{};const{logger:n}=r,a=r.env===void 0?"":` --env ${r.env}`;let i;try{i=await(r.secretLister??He)({cwd:e,env:r.env,temporary:r.temporary})}catch{return{}}if(!i.ok)return{};const s=new Set(i.names),l=(await br(e)).filter(m=>!s.has(m));if(l.length===0)return{};if(!o)return{error:`missing required secret(s) on the deploy target: ${l.join(", ")}. Set them with \`wrangler secret put <KEY>${a}\` (or \`lunora env generate --set\` then \`lunora env push --yes${a}\`), then re-deploy.`};for(const m of l.filter(u=>!I(u)))n.warn(`required secret ${m} is not set on the target — set it with: wrangler secret put ${m}${a}`);const d=l.filter(m=>I(m));if(d.length===0)return{};if(await(r.secretConfirm??We())(`${String(d.length)} required secret(s) not set on the target (${d.join(", ")}). Generate strong values and push them now?`)){const{minted:m,ok:u}=await $r(e,r,d,t),f=Ar(e,r,m);return u?{mintedSecretsFile:f}:{error:"failed to push required secret(s) — set them manually and re-deploy",mintedSecretsFile:f}}return n.warn(`${String(d.length)} required secret(s) not set on the target: ${d.join(", ")}. Generate + push with \`lunora env generate --set\` then \`lunora env push --yes${a}\`.`),{}},ee=e=>e.format==="json"?!1:e.interactive!==void 0?e.interactive:process.stdout.isTTY&&!process.env.CI,jr=async(e,r)=>{if(r.dryRun===!0)return;const o=V(e,"lunora").containers.flatMap(n=>n.schedulingPolicy===void 0&&n.image.kind==="build"?[{buildDir:n.image.buildDir,exportName:n.exportName}]:[]);if(o.length===0)return;const t=await Qe({cwd:e,logger:r.logger,railpackAvailable:r.railpackAvailable,spawner:r.spawner,targets:o});return t.code===0?void 0:t.error??"railpack build failed"},Cr=(e,r,o)=>{if(o!==void 0)try{const t=pe(e,o);t.changed&&r.success(`synced ${String(o.length)} cron trigger(s) → ${t.wranglerPath??"wrangler.jsonc"}`);for(const a of t.warnings)r.warn(a);const n=ye(t.preserved);n!==void 0&&r.info(n)}catch(t){const n=t instanceof Error?t.message:String(t);r.warn(`cron trigger sync skipped: ${n}`)}},Pr=async(e,r,o,t,n)=>{try{C(t);const a=await q({projectRoot:e,schemaDir:R(e)}),i=ve(e,a,n),s=i.wranglerPath??"wrangler.jsonc";if(i.added.length>0&&r.success(`provisioned bindings: ${i.added.join(", ")} → ${s}`),i.updated.length>0&&r.success(`updated bindings: ${i.updated.join(", ")} → ${s}`),i.devConfig!==void 0){const{added:c,path:l,updated:d}=i.devConfig;r.success(`dev sidecar bindings: ${[...c,...d].join(", ")} → ${l}`)}for(const c of i.warnings)r.warn(c)}catch(a){const i=a instanceof Error?a.message:String(a);r.warn(`binding inference skipped: ${i}`)}try{const a=he(e);a.changed&&r.success(`bumped compatibility_date to ${a.date??"unknown"} (Workers Cache enabled) → ${a.wranglerPath??"wrangler.jsonc"}`)}catch(a){const i=a instanceof Error?a.message:String(a);r.warn(`compatibility date sync skipped: ${i}`)}Cr(e,r,o)},xr=async(e,r,o,t,n,a,i,s)=>{let c;r?(c=new we({name:"dots"}),c.start("running codegen")):o.info("running codegen");try{const l=oe({apiSpec:t,projectRoot:e,target:n,...fe(e)});c?.succeed("codegen complete"),c||o.success("codegen complete");const d=be(l.platformDiagnostics,o);if(d.errors.length>0)return{error:d.errors.join("; ")};const{errorAdvisories:g,names:m,shouldBlock:u}=$e(l.advisories,s);if(u){const v=`${g.length.toString()} ERROR-level ${g.length===1?"advisory":"advisories"} (${m.join(", ")}). Pass --no-strict-advisories to downgrade this to a warning and continue.`;return o.error(v),{error:v}}const f=await ue({cwd:e,logger:o,spawner:a,stdoutToStderr:i});return f.error!==void 0?{error:f.error}:{result:l}}catch(l){c?.failed("codegen failed");const d=l instanceof Error?l.message:String(l);return o.error(`codegen failed: ${d}`),{error:`codegen failed: ${d}`}}},_r=(e,r)=>({dryRun:r.dryRun,entry:Z(e),environment:r.env,outDir:r.outDir,preview:r.preview,temporary:r.temporary}),re=(e,r,o)=>{const{toolchain:t}=o;if(t===void 0)throw new Error(`deploy target "${o.id}" has no command-line toolchain`);const n=_r(e,r);return Y(o,e,"deploy",a=>t.deploy({...n,configPath:a}))},Tr=(e,r,o)=>{const t=re(e,r,o),n=Z(e);return n!==void 0&&r.logger.info(`class-B composition: deploying ${n} (overrides wrangler main)`),r.temporary&&r.logger.info("temporary account: deploying to a short-lived Cloudflare account (~60min); wrangler will print a claim URL"),r.dryRun&&r.logger.info("dry run: validating + bundling without publishing"),r.outDir!==void 0&&r.logger.info(`build artifact: emitting bundle to ${r.outDir}`),t.commit(),t.projection!==void 0&&t.projection.dropped.length>0&&r.logger.warn(`${o.name} ignores these wrangler keys, so they were left out of ${t.projection.configPath}: ${t.projection.dropped.join(", ")}`),t.command},A=(e,r)=>({code:h.USAGE,descriptor:void 0,error:e,validation:{problems:[],wranglerPath:void 0},...r}),Nr=(e,r)=>{for(const o of e.report?.warnings??[])r.warn(`wrangler.jsonc: ${o}`);if(e.problems.length===0)return!1;r.error("wrangler.jsonc validation failed:");for(const o of e.problems)r.error(` - ${o}`);return!0},Ir=(e,r,o)=>{const t=r.format==="json",n=r.dryRun!==!0,a=Tr(e,r,o),i=j(b(e),a);return{args:i.args,captureStdout:n&&!t,captureStdoutSilently:n&&t,command:i.command,cwd:e,stdoutToStderr:t&&!n}},Lr=async(e,r)=>{const o=e.cwd??process.cwd(),t=ee(e),n=ke(e),a={problems:[],wranglerPath:void 0},i=De(o,e.target);if(i.target===void 0){const u=i.error??"unknown deploy target";return e.logger.error(u),{error:u,validation:a}}const{target:s}=i;try{re(o,e,C(s))}catch(u){const f=u instanceof Error?u.message:String(u);return e.logger.error(f),{error:f,target:s,validation:a}}let c;if(!e.skipCodegen){const u=await xr(o,t,e.logger,e.apiSpec,s,e.spawner,e.format==="json",n);if(u.error!==void 0)return{error:u.error,target:s,validation:a};c=u.result}let l;if(c!==void 0){const u=Oe({allowDrift:e.allowSchemaDrift===!0,codegen:c,command:r,logger:e.logger,updateBaseline:e.updateSchemaBaseline===!0});if(u.blocked)return{error:`schema drift gate blocked ${r}`,schemaDrift:{blocked:!0,reason:u.reason},target:s,validation:a};l=u.rebless}const d=c&&Je({current:c.architecture,cwd:o,environment:e.env,logger:e.logger});await Pr(o,e.logger,c?.cronTriggers,s,e.env);const g=dr(o,e,r);if(g!==void 0)return{code:g.code,error:g.error,target:s,validation:a};const m=me({environment:e.env,projectRoot:o});return Nr(m,e.logger)?{error:"wrangler validation failed",target:s,validation:m}:{codegen:c,reblessSchemaBaseline:l,recordArchitecture:d,target:s,validation:m}},Mr=e=>{if(e.skipServices===!0)return"--skip-services";if(e.preview===!0)return"--preview uploads the app version only";if(e.temporary===!0)return"--temporary deploys the app to a throwaway account"},Ur=async(e,r,o,t)=>{const{error:n,services:a}=ne(e);if(n!==void 0)return n;if(a.length===0)return;const{toolchain:i}=o,s=i===void 0?`target "${o.id}" has no deploy command`:Mr(r);if(s!==void 0||i===void 0){const d=a.map(g=>g.worker).join(", ");r.logger.warn(`services not deployed (${s??""}): ${d} — deploy them yourself if the app calls anything new`);return}const c=b(e),l=[...new Map(a.map(d=>[d.wranglerPath,d])).values()];for(const d of l){const g=F(d.wranglerPath);let m;try{m=Y(o,g,"deploy",v=>i.deploy({configPath:v??d.wranglerPath,dryRun:r.dryRun===!0,environment:r.env}))}catch(v){return`service ${d.name} (${d.worker}): ${v instanceof Error?v.message:String(v)}`}m.commit();const u=j(c,m.command);r.logger.info(`deploying service ${d.name} (${d.worker}) via ${u.command} ${u.args.join(" ")}`);const f=await t({args:u.args,command:u.command,cwd:g,stdoutToStderr:r.format==="json"});if(f.code!==0)return`service ${d.name} (${d.worker}): ${u.command} ${u.args.join(" ")} exited ${String(f.code)} — stopping before the app`}},Or=async(e,r,o,t)=>{if(r!=="cloudflare")return;const n=e===void 0?void 0:P(e).parsed,a=(o===void 0?void 0:n?.env?.[o]?.account_id)??n?.account_id,i=await Pe({accountId:a});(i.verdict==="near"||i.verdict==="full")&&t.warn(i.fix===void 0?i.message:`${i.message} ${i.fix}`)},Fr=async(e,r,o,t,n)=>{const a=o==="cloudflare"&&r!==void 0?P(r).parsed:void 0;if(a===void 0)return;const i=(J(a,t).merged.artifacts??[]).flatMap(g=>typeof g?.binding=="string"&&typeof g.namespace=="string"?[{binding:g.binding,namespace:g.namespace}]:[]),s=i.length===0?void 0:G(e,R(e)).info?.jurisdiction;if(s===void 0)return;const c=(t===void 0?void 0:a.env?.[t]?.account_id)??a.account_id,l=await Promise.all(i.map(async g=>Ce({...g,accountId:c,jurisdiction:s}))),d=[];for(const g of l){const m=g.fix===void 0?g.message:`${g.message} ${g.fix}`;g.verdict==="unchecked"?n.warn(m):g.verdict!=="ok"&&(n.error(m),d.push(m))}return d.length===0?void 0:d.join(`
10
+ `,"utf8"),r.info(`.gitignore: added ${a.join(", ")} so the recorded secret cannot be committed`)}catch(t){r.warn(`could not update .gitignore (${t instanceof Error?t.message:String(t)}) — add \`${E.join("` and `")}\` by hand before committing.`)}},Ar=(e,r,o)=>{if(o.length===0)return;const t=o.map(s=>s.key).join(", ");if(r.env!==void 0&&!Sr.test(r.env)){r.logger.warn(`${t}: minted and pushed for --env ${r.env}, but "${r.env}" isn't a safe filename fragment — the value could not be recorded. Capture it manually if you need it again.`);return}const n=r.env===void 0?w:`${w}.${r.env}`;Er(e,r.logger);const a=y(e,n);let i=p(a)?k(a,"utf8"):"";for(const s of o)i=de(i,s.key,s.value);return le(a,i),r.logger.success(r.env===void 0?`${t}: value(s) recorded in ${n}`:`${t}: value(s) recorded in ${n} (kept separate from ${w} so \`lunora dev\` and a plain \`lunora env push\` don't inherit the --env ${r.env} value)`),n},Rr=async(e,r,o,t)=>{if(r.dryRun===!0||r.preview===!0)return{};const{logger:n}=r,a=r.env===void 0?"":` --env ${r.env}`;let i;try{i=await(r.secretLister??He)({cwd:e,env:r.env,temporary:r.temporary})}catch{return{}}if(!i.ok)return{};const s=new Set(i.names),l=(await br(e)).filter(m=>!s.has(m));if(l.length===0)return{};if(!o)return{error:`missing required secret(s) on the deploy target: ${l.join(", ")}. Set them with \`wrangler secret put <KEY>${a}\` (or \`lunora env generate --set\` then \`lunora env push --yes${a}\`), then re-deploy.`};for(const m of l.filter(u=>!I(u)))n.warn(`required secret ${m} is not set on the target — set it with: wrangler secret put ${m}${a}`);const d=l.filter(m=>I(m));if(d.length===0)return{};if(await(r.secretConfirm??We())(`${String(d.length)} required secret(s) not set on the target (${d.join(", ")}). Generate strong values and push them now?`)){const{minted:m,ok:u}=await $r(e,r,d,t),f=Ar(e,r,m);return u?{mintedSecretsFile:f}:{error:"failed to push required secret(s) — set them manually and re-deploy",mintedSecretsFile:f}}return n.warn(`${String(d.length)} required secret(s) not set on the target: ${d.join(", ")}. Generate + push with \`lunora env generate --set\` then \`lunora env push --yes${a}\`.`),{}},ee=e=>e.format==="json"?!1:e.interactive!==void 0?e.interactive:process.stdout.isTTY&&!process.env.CI,jr=async(e,r)=>{if(r.dryRun===!0)return;const o=V(e,"lunora").containers.flatMap(n=>n.schedulingPolicy===void 0&&n.image.kind==="build"?[{buildDir:n.image.buildDir,exportName:n.exportName}]:[]);if(o.length===0)return;const t=await Qe({cwd:e,logger:r.logger,railpackAvailable:r.railpackAvailable,spawner:r.spawner,targets:o});return t.code===0?void 0:t.error??"railpack build failed"},Cr=(e,r,o)=>{if(o!==void 0)try{const t=pe(e,o);t.changed&&r.success(`synced ${String(o.length)} cron trigger(s) → ${t.wranglerPath??"wrangler.jsonc"}`);for(const a of t.warnings)r.warn(a);const n=ye(t.preserved);n!==void 0&&r.info(n)}catch(t){const n=t instanceof Error?t.message:String(t);r.warn(`cron trigger sync skipped: ${n}`)}},Pr=async(e,r,o,t,n)=>{try{C(t);const a=await q({projectRoot:e,schemaDir:R(e)}),i=ve(e,a,n,t),s=i.wranglerPath??"wrangler.jsonc";if(i.added.length>0&&r.success(`provisioned bindings: ${i.added.join(", ")} → ${s}`),i.updated.length>0&&r.success(`updated bindings: ${i.updated.join(", ")} → ${s}`),i.devConfig!==void 0){const{added:c,path:l,updated:d}=i.devConfig;r.success(`dev sidecar bindings: ${[...c,...d].join(", ")} → ${l}`)}for(const c of i.warnings)r.warn(c)}catch(a){const i=a instanceof Error?a.message:String(a);r.warn(`binding inference skipped: ${i}`)}try{const a=he(e);a.changed&&r.success(`bumped compatibility_date to ${a.date??"unknown"} (Workers Cache enabled) → ${a.wranglerPath??"wrangler.jsonc"}`)}catch(a){const i=a instanceof Error?a.message:String(a);r.warn(`compatibility date sync skipped: ${i}`)}Cr(e,r,o)},xr=async(e,r,o,t,n,a,i,s)=>{let c;r?(c=new we({name:"dots"}),c.start("running codegen")):o.info("running codegen");try{const l=oe({apiSpec:t,projectRoot:e,target:n,...fe(e)});c?.succeed("codegen complete"),c||o.success("codegen complete");const d=be(l.platformDiagnostics,o);if(d.errors.length>0)return{error:d.errors.join("; ")};const{errorAdvisories:g,names:m,shouldBlock:u}=$e(l.advisories,s);if(u){const v=`${g.length.toString()} ERROR-level ${g.length===1?"advisory":"advisories"} (${m.join(", ")}). Pass --no-strict-advisories to downgrade this to a warning and continue.`;return o.error(v),{error:v}}const f=await ue({cwd:e,logger:o,spawner:a,stdoutToStderr:i});return f.error!==void 0?{error:f.error}:{result:l}}catch(l){c?.failed("codegen failed");const d=l instanceof Error?l.message:String(l);return o.error(`codegen failed: ${d}`),{error:`codegen failed: ${d}`}}},_r=(e,r)=>({dryRun:r.dryRun,entry:Z(e),environment:r.env,outDir:r.outDir,preview:r.preview,temporary:r.temporary}),re=(e,r,o)=>{const{toolchain:t}=o;if(t===void 0)throw new Error(`deploy target "${o.id}" has no command-line toolchain`);const n=_r(e,r);return Y(o,e,"deploy",a=>t.deploy({...n,configPath:a}))},Tr=(e,r,o)=>{const t=re(e,r,o),n=Z(e);return n!==void 0&&r.logger.info(`class-B composition: deploying ${n} (overrides wrangler main)`),r.temporary&&r.logger.info("temporary account: deploying to a short-lived Cloudflare account (~60min); wrangler will print a claim URL"),r.dryRun&&r.logger.info("dry run: validating + bundling without publishing"),r.outDir!==void 0&&r.logger.info(`build artifact: emitting bundle to ${r.outDir}`),t.commit(),t.projection!==void 0&&t.projection.dropped.length>0&&r.logger.warn(`${o.name} ignores these wrangler keys, so they were left out of ${t.projection.configPath}: ${t.projection.dropped.join(", ")}`),t.command},A=(e,r)=>({code:h.USAGE,descriptor:void 0,error:e,validation:{problems:[],wranglerPath:void 0},...r}),Nr=(e,r)=>{for(const o of e.report?.warnings??[])r.warn(`wrangler.jsonc: ${o}`);if(e.problems.length===0)return!1;r.error("wrangler.jsonc validation failed:");for(const o of e.problems)r.error(` - ${o}`);return!0},Ir=(e,r,o)=>{const t=r.format==="json",n=r.dryRun!==!0,a=Tr(e,r,o),i=j(b(e),a);return{args:i.args,captureStdout:n&&!t,captureStdoutSilently:n&&t,command:i.command,cwd:e,stdoutToStderr:t&&!n}},Lr=async(e,r)=>{const o=e.cwd??process.cwd(),t=ee(e),n=ke(e),a={problems:[],wranglerPath:void 0},i=De(o,e.target);if(i.target===void 0){const u=i.error??"unknown deploy target";return e.logger.error(u),{error:u,validation:a}}const{target:s}=i;try{re(o,e,C(s))}catch(u){const f=u instanceof Error?u.message:String(u);return e.logger.error(f),{error:f,target:s,validation:a}}let c;if(!e.skipCodegen){const u=await xr(o,t,e.logger,e.apiSpec,s,e.spawner,e.format==="json",n);if(u.error!==void 0)return{error:u.error,target:s,validation:a};c=u.result}let l;if(c!==void 0){const u=Oe({allowDrift:e.allowSchemaDrift===!0,codegen:c,command:r,logger:e.logger,updateBaseline:e.updateSchemaBaseline===!0});if(u.blocked)return{error:`schema drift gate blocked ${r}`,schemaDrift:{blocked:!0,reason:u.reason},target:s,validation:a};l=u.rebless}const d=c&&Je({current:c.architecture,cwd:o,environment:e.env,logger:e.logger});await Pr(o,e.logger,c?.cronTriggers,s,e.env);const g=dr(o,e,r);if(g!==void 0)return{code:g.code,error:g.error,target:s,validation:a};const m=me({environment:e.env,projectRoot:o});return Nr(m,e.logger)?{error:"wrangler validation failed",target:s,validation:m}:{codegen:c,reblessSchemaBaseline:l,recordArchitecture:d,target:s,validation:m}},Mr=e=>{if(e.skipServices===!0)return"--skip-services";if(e.preview===!0)return"--preview uploads the app version only";if(e.temporary===!0)return"--temporary deploys the app to a throwaway account"},Ur=async(e,r,o,t)=>{const{error:n,services:a}=ne(e);if(n!==void 0)return n;if(a.length===0)return;const{toolchain:i}=o,s=i===void 0?`target "${o.id}" has no deploy command`:Mr(r);if(s!==void 0||i===void 0){const d=a.map(g=>g.worker).join(", ");r.logger.warn(`services not deployed (${s??""}): ${d} — deploy them yourself if the app calls anything new`);return}const c=b(e),l=[...new Map(a.map(d=>[d.wranglerPath,d])).values()];for(const d of l){const g=F(d.wranglerPath);let m;try{m=Y(o,g,"deploy",v=>i.deploy({configPath:v??d.wranglerPath,dryRun:r.dryRun===!0,environment:r.env}))}catch(v){return`service ${d.name} (${d.worker}): ${v instanceof Error?v.message:String(v)}`}m.commit();const u=j(c,m.command);r.logger.info(`deploying service ${d.name} (${d.worker}) via ${u.command} ${u.args.join(" ")}`);const f=await t({args:u.args,command:u.command,cwd:g,stdoutToStderr:r.format==="json"});if(f.code!==0)return`service ${d.name} (${d.worker}): ${u.command} ${u.args.join(" ")} exited ${String(f.code)} — stopping before the app`}},Or=async(e,r,o,t)=>{if(r!=="cloudflare")return;const n=e===void 0?void 0:P(e).parsed,a=(o===void 0?void 0:n?.env?.[o]?.account_id)??n?.account_id,i=await Pe({accountId:a});(i.verdict==="near"||i.verdict==="full")&&t.warn(i.fix===void 0?i.message:`${i.message} ${i.fix}`)},Fr=async(e,r,o,t,n)=>{const a=o==="cloudflare"&&r!==void 0?P(r).parsed:void 0;if(a===void 0)return;const i=(J(a,t).merged.artifacts??[]).flatMap(g=>typeof g?.binding=="string"&&typeof g.namespace=="string"?[{binding:g.binding,namespace:g.namespace}]:[]),s=i.length===0?void 0:G(e,R(e)).info?.jurisdiction;if(s===void 0)return;const c=(t===void 0?void 0:a.env?.[t]?.account_id)??a.account_id,l=await Promise.all(i.map(async g=>Ce({...g,accountId:c,jurisdiction:s}))),d=[];for(const g of l){const m=g.fix===void 0?g.message:`${g.message} ${g.fix}`;g.verdict==="unchecked"?n.warn(m):g.verdict!=="ok"&&(n.error(m),d.push(m))}return d.length===0?void 0:d.join(`
11
11
  `)},Br=async e=>{const r=e.cwd??process.cwd(),o=ee(e),t=await Lr(e,e.commandName??"deploy");if(t.error!==void 0){if(t.validation.problems.length>0)return{code:h.USAGE,descriptor:void 0,error:t.error,validation:t.validation};const v=t.schemaDrift===void 0?void 0:{schemaDrift:t.schemaDrift};return A(t.error,{...v,...t.code===void 0?{}:{code:t.code}})}const{validation:n}=t,a=C(t.target),i=ir(e)??await Fr(r,n.wranglerPath,t.target,e.env,e.logger);if(i!==void 0)return A(i);const s=a.toolchain?.prebuildsContainerImages===!0?await jr(r,e):void 0;if(s!==void 0)return A(s);kr(r,e.logger,a),ge(r,v=>{e.logger.warn(v)}),await Or(n.wranglerPath,t.target,e.env,e.logger);const{error:c,mintedSecretsFile:l}=await Rr(r,e,o,a);if(c!==void 0)return e.logger.error(c),{code:h.USAGE,descriptor:void 0,error:c,mintedSecretsFile:l,validation:n};const d=e.spawner??D,g=await Ur(r,e,a,d);if(g!==void 0)return{code:h.FAILURE,descriptor:void 0,error:g,mintedSecretsFile:l,validation:n};const m=Ir(r,e,a);e.logger.info(`deploying via ${m.command} ${m.args.join(" ")}`);const u=await d(m);return m.captureStdoutSilently===!0&&u.stdout!==void 0&&u.stdout!==""&&process.stderr.write(u.stdout),u.code!==0?{code:u.code,descriptor:m,mintedSecretsFile:l,validation:n}:{...await wr({...t,cwd:r,descriptor:m,mintedSecretsFile:l,options:e,stdout:u.stdout}),logsAvailable:a.toolchain?.tail!==void 0}},Wr=async e=>{const{logger:r}=e,o=e.dryRun===!0?Ze(e.cwd??process.cwd()):void 0;let t;try{if(t=await Br({...e,logger:r}),t.code===0&&e.emitBindings!==void 0){const{error:n}=xe({destination:e.emitBindings,logger:r,projectRoot:e.cwd??process.cwd()});n!==void 0&&(r.error(n),t={...t,code:h.USAGE})}}finally{o?.()}if(e.format==="json")return t;if(t.code===0&&e.dryRun!==!0&&e.preview!==!0)Xe({cwd:e.cwd??process.cwd(),env:e.env,logger:e.logger,logsAvailable:t.logsAvailable===!0,mintedSecretsFile:t.mintedSecretsFile,url:t.deployment?.url});else if(t.code===0&&e.preview===!0){const n=t.deployment?.url;e.logger.success(n===void 0?"preview version uploaded":`preview version uploaded — ${n}`)}return t},gt=_e(async({cwd:e,format:r,logger:o,options:t})=>{const n=await Wr({allowSchemaDrift:t.allowSchemaDrift===!0,apiSpec:Se(t.apiSpec),cwd:e,dryRun:t.dryRun===!0,env:t.env,format:r,healthCheck:t.healthCheck===!0,logger:o,migrate:t.migrate===!0,migrateToken:t.migrateToken,migrateUrl:X({cwd:e,env:t.env,url:t.migrateUrl}),migrateYes:t.migrateYes===!0,preview:t.preview===!0,skipCodegen:t.prebuilt===!0,skipServices:t.skipServices===!0,strictAdvisories:t.strictAdvisories,target:t.target,temporary:t.temporary===!0,updateSchemaBaseline:t.updateSchemaBaseline===!0});return{code:n.code,data:{deployment:n.deployment,healthCheck:n.healthCheck,mintedSecretsFile:n.mintedSecretsFile,schemaDrift:n.schemaDrift,validation:n.validation},error:n.error}});export{gt as execute,Pr as provisionBindings,Wr as runDeployCommand,Lr as runPreDeployPipeline};
@@ -1 +1 @@
1
- import{C as E,R as M,V as a,r as s}from"./cli-C74xjzMK.mjs";import"./cli-manifest-CRet0egA.mjs";import"./EXIT_CODE-D_XCixv8.mjs";import"./createLogger-Cl18I8AX.mjs";import"./render-lunora-error-C3OJY5wk.mjs";export{E as COMMANDS,M as REGISTERED_COMMAND_NAMES,a as VERSION,s as runCli};
1
+ import{C as E,R as M,V as a,r as s}from"./cli-B5fWPcrA.mjs";import"./cli-manifest-CRet0egA.mjs";import"./EXIT_CODE-D_XCixv8.mjs";import"./createLogger-Cl18I8AX.mjs";import"./render-lunora-error-C3OJY5wk.mjs";export{E as COMMANDS,M as REGISTERED_COMMAND_NAMES,a as VERSION,s as runCli};
@@ -0,0 +1,2 @@
1
+ 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 s}from"./output-format-B4eQHi5y.mjs";import{A as m,T as p}from"./deploy-target-DCWwiuAe.mjs";import{SDK_LANGUAGES as P}from"@lunora/codegen";import{r as M}from"./cli-manifest-CRet0egA.mjs";import{EXIT_CODE as y,exitCodeForError as U}from"./EXIT_CODE-D_XCixv8.mjs";import{setCommandLogger as k,createLogger as v}from"./createLogger-Cl18I8AX.mjs";import{r as W}from"./render-lunora-error-C3OJY5wk.mjs";import{mkdirSync as $,readFileSync as F,lstatSync as J,writeFileSync as K}from"node:fs";import{homedir as G}from"node:os";import{join as b}from"node:path";import{addArgsFor as V,detectPackageManager as q}from"@lunora/config";const z={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},s]},S="lunora.advisor.map.json",H={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/handler17.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 ${S})`,name:"baseline",type:String},{description:"Inspect a single procedure by `file#exportName`",name:"entry",type:String},s,{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 ${S})`,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}]},Y={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:[s]},Q={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/handler20.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},s,{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}]},X={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/handler18.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: ${m} (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},s,{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},p]},Z=[{name:"alerts",summary:"usage alerts that catch a runaway bill",usage:"[status | setup | test]"},{name:"ai-gateway",summary:"create or reuse an AI Gateway for ctx.ai and write its id into wrangler vars",usage:""},{name:"containers",summary:"build and push container images, manage instances (wraps wrangler containers)",usage:"<build|push|images|list|info|delete> [args…]"},{name:"deployments",summary:"deployment history; roll back or promote Worker versions",usage:"list | inspect <version-id> | rollback [version-id] | promote <version-id>"},{name:"profile",summary:"capture an on-demand CPU or heap profile (pprof) from the live Worker or one of its Durable Objects",usage:"[worker]"}],R={argument:{description:`${Z.map(e=>e.name).join(" | ")}, then the tool's own arguments`,name:"tool",type:String},description:"Cloudflare-only tools: usage alerts, AI Gateway, containers, deployments, profiling",examples:[["lunora cloudflare","List the tools"],["lunora cloudflare alerts","Show last month's usage and which products have an alert"],["lunora cloudflare alerts setup --email ops@example.com --dry-run","Show the alerts setup would create, without creating them"],["lunora cloudflare alerts setup --email ops@example.com --multiplier 5 --yes","Create or update the alerts at 5x last month"],["lunora cloudflare alerts setup --email ops@example.com --threshold do-duration=500000 --yes","Also alert on Durable Objects duration at a limit you choose"],["lunora cloudflare alerts test","Show what Cloudflare has delivered to your alert destinations"],["lunora cloudflare ai-gateway","Create (or reuse) a gateway named after the worker and wire it into wrangler vars"],["lunora cloudflare ai-gateway --id my-gateway --no-logs","Use an explicit gateway id, with prompt/response log collection off"],["lunora cloudflare ai-gateway --dry-run","Print what would be created and written, without calling Cloudflare"],["lunora cloudflare containers build ./containers/transcoder --tag transcoder:v1 --push","Build an image and push it to the Cloudflare Registry"],["lunora cloudflare containers images list","List images in your Cloudflare Registry"],["lunora cloudflare containers list --format json","List container instances as JSON (also `info`, `images list`)"],["lunora cloudflare containers images delete transcoder:v1","Delete an image to free registry storage"],["lunora cloudflare deployments list","Show the 10 most recent deployments"],["lunora cloudflare deployments inspect <version-id>","View a specific Worker version"],["lunora cloudflare deployments rollback --yes","Roll back to the previous version"],["lunora cloudflare deployments promote <version-id> --yes","Send 100% of traffic to a version"],["lunora cloudflare profile","Capture a 10s CPU profile of the latest version into ./<worker>-cpu-<time>.pprof.gz"],["lunora cloudflare profile --type heap --duration-ms 30000 --out heap.pprof.gz","Capture a 30s heap (allocation) profile"],["lunora cloudflare profile --namespace-id <id> --actor-id <64-hex>","Profile one Durable Object instance"]],group:"Deploy",loader:()=>import("../packem_chunks/handler26.mjs").then(e=>({default:e.execute})),name:"cloudflare",options:[{description:"alerts setup: email address to notify. Repeatable",lazyMultiple:!0,name:"email",type:String},{description:"alerts setup / test: Cloudflare webhook destination id. Repeatable",lazyMultiple:!0,name:"webhook",type:String},{description:"alerts setup: alert at this many times last month's usage (default 3)",name:"multiplier",type:String},{description:"alerts setup: set one metric's limit yourself, in the product's unit: <metric>=<n>. Repeatable",lazyMultiple:!0,name:"threshold",type:String},{description:"alerts setup: accept the floor for a metric whose usage could not be read",name:"allow-floor",type:Boolean},{description:"alerts setup: replace an updated alert's recipients instead of adding to them",name:"replace-recipients",type:Boolean},{description:"alerts setup / ai-gateway: show the plan without creating, updating or writing anything",name:"dry-run",type:Boolean},{description:"alerts setup: apply the plan without asking (required when stdin is not a TTY). deployments rollback / promote: confirm the traffic change (required)",name:"yes",type:Boolean},{description:"ai-gateway: gateway id (default: the worker `name` from wrangler.jsonc)",name:"id",type:String},{description:"ai-gateway: collect request/response logs in the gateway (default)",name:"logs",type:Boolean},{description:"ai-gateway: create the gateway with log collection off (prompts and responses are not stored)",name:"no-logs",type:Boolean},{description:"containers build: name:tag for the image (forwarded to wrangler --tag)",name:"tag",type:String},{description:"containers build: push the image to the Cloudflare Registry after building",name:"push",type:Boolean},{description:"containers / deployments / profile: Cloudflare environment name",name:"env",type:String},{description:"profile: capture window in ms, 1000–50000 (default 10000)",name:"duration-ms",type:String},{description:"profile: cpu (default) or heap",name:"type",type:String},{description:"profile: Worker version id to profile (default latest)",name:"version-id",type:String},{description:"profile: file to write the gzip pprof to (default <worker>-<type>-<time>.pprof.gz)",name:"out",type:String},{description:"profile: Durable Object namespace id (with --actor-id)",name:"namespace-id",type:String},{description:"profile: Durable Object instance id, 64 hex characters (with --namespace-id)",name:"actor-id",type:String},{description:"deployments rollback / promote: reason recorded with the change",name:"message",type:String},{...s,description:"Output format: pretty (default) or json (containers: list | info | images list; deployments: list only)"},p]},ee={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: ${m} (default openapi)`,name:"api-spec",type:String},s,{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},p]},te={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: ${m} (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},s,{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},{description:"Deploy only the app, not the lunora.config services it binds (they deploy first by default)",name:"skip-services",type:Boolean},p,{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}]},re={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)"],["lunora dev --local","Start no remote proxy session, e.g. in CI where a service's `ai` binding has no credentials"],["lunora dev --tunnel","Share the worker on a public *.trycloudflare.com URL (needs cloudflared ≥ 2026.9.3)"],["lunora dev --tunnel --allow-mail you@example.com","Same, but visitors must confirm an allowed email with a one-time PIN"]],group:"Develop",loader:()=>import("../packem_chunks/runDevCommand.mjs").then(e=>({default:e.execute})),name:"dev",options:[{description:`Which API spec(s) codegen emits: ${m} (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},p,{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},{description:"Pass --local to wrangler dev: no remote proxy session, so an `ai` binding (in the app or a service) cannot stop dev from starting without Cloudflare credentials — it fails when called instead",name:"local",type:Boolean},{description:"Share the worker through a Cloudflare quick tunnel (*.trycloudflare.com, needs cloudflared ≥ 2026.9.3). PUBLIC unless --allow-mail is given",name:"tunnel",type:Boolean},{description:"With --tunnel: only these emails get in, after a one-time PIN (passed to cloudflared as --allowed-mail). Repeatable; accepts a comma list and '*@domain'",lazyMultiple:!0,name:"allow-mail",type:String}]},oe={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/handler3.mjs").then(e=>({default:e.execute})),name:"docs"},ne={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/handler23.mjs").then(e=>({default:e.execute})),name:"doctor",options:[s]},ae={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/handler4.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},s,{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}]},ie={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/handler21.mjs").then(e=>({default:e.execute})),name:"eval",options:[{description:"Directory to discover *.eval.ts files under (default evals/)",name:"dir",type:String},s,{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}]},se={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/handler5.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},{...s,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}]},le={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/handler6.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},s,{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}]},de={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/handler7.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},s,{description:"With --bindings: write the manifest to <file> instead of stdout",name:"out",type:String}]},pe={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}]},ce={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/handler8.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},s,{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}]},ue={description:"Scaffold lunora/schema.ts (and list/get procedures) from an existing Postgres or MySQL database",examples:[["lunora introspect --url postgres://localhost/shop","Scaffold a schema + procedures from every table"],["lunora introspect --tables users,orders","Introspect only these tables (DATABASE_URL is read by default)"],["lunora introspect --dry-run","Print what would be written without touching the filesystem"],["lunora introspect --no-procedures --force","Regenerate just the schema, overwriting the existing file"]],group:"Data",loader:()=>import("../packem_chunks/handler24.mjs").then(e=>({default:e.execute})),name:"introspect",options:[{description:"Database connection string (default: $DATABASE_URL)",name:"url",type:String},{description:"Postgres schema (default `public`) or MySQL database name",name:"schema",type:String},{description:"Comma-separated table allow-list (default: every base table)",name:"tables",type:String},{description:"Also emit list/get procedure modules per table (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},s]},me={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/handler9.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}]},he={argument:{description:"Worker name (defaults to the name in wrangler config)",name:"worker",type:String},description:"Stream live logs from a deployed Worker, or read the durable log archive with --durable",group:"Deploy",loader:()=>import("../packem_chunks/handler22.mjs").then(e=>({default:e.execute})),name:"logs",options:[{description:"Cloudflare environment name",name:"env",type:String},s,{description:"Substring filter on log messages",name:"search",type:String},{description:"Filter by invocation status: ok, error, or canceled",name:"status",type:String},p,{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}]},ge={argument:{description:"install [client…] | uninstall [client…] | serve",name:"args",type:String},description:"Connect your AI editor to Lunora over MCP (docs search + this project's dev server)",examples:[["lunora mcp install","Install into every MCP client already configured here"],["lunora mcp install claude-code cursor","Install into specific clients"],["lunora mcp install --list","List the supported clients and their config files"],["lunora mcp install --docs-only","Install only the hosted documentation server"],["lunora mcp install --print","Show the config that would be written, without writing it"],["lunora mcp install --global","Force every server into the machine-wide config"],["lunora mcp uninstall","Remove Lunora's MCP servers from every supported client"],["lunora mcp uninstall cursor","Remove them from one client"],["lunora mcp uninstall --print","Show what would be removed, without removing it"],["lunora mcp serve","Run the stdio MCP server (this is what your editor spawns)"],["lunora mcp serve --allow-writes","Also expose the mutation/action tools"],["lunora mcp serve --token $LUNORA_ADMIN_TOKEN","Expose the observability tools (logs, issues, advisories, insights, migrations) too"]],group:"Develop",loader:()=>import("../packem_chunks/handler25.mjs").then(e=>({default:e.execute})),name:"mcp",options:[{description:"install: replace entries that already exist",name:"force",type:Boolean},{description:"install: list the supported clients and their config files",name:"list",type:Boolean},{description:"install/uninstall: print what would change instead of writing it",name:"print",type:Boolean},{description:"install/uninstall: only the hosted documentation server",name:"docs-only",type:Boolean},{description:"install/uninstall: only this project's local server",name:"local-only",type:Boolean},{description:"install/uninstall: the machine-wide config (install default: docs server global, local server per-project)",name:"global",type:Boolean},{description:"install/uninstall: this project's config instead of the machine-wide one",name:"project",type:Boolean},{description:"serve: also expose the mutation/action tools (default: read-only)",name:"allow-writes",type:Boolean},{description:"serve: 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}]},fe={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},s,{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}]},ye={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/handler10.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: ${m} (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},p,{description:"Re-bless the committed schema baseline (lunora/.lunora-schema.json) with the current shape",name:"update-schema-baseline",type:Boolean}]},ve={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/handler11.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},{...s,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}]},be={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}]},we={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/handler12.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}]},ke={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},s,{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}]},Se={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/handler19.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}]},xe={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/handler13.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},s,{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}]},Ce={argument:{description:"prune",name:"subcommand",type:String},description:"Maintain the shard registry: prune shards that no longer hold any rows of their .shardBy() table",examples:[["lunora shards prune --dry-run","Show which registered shards are empty, without removing anything"],["lunora shards prune","Remove the empty shards from the registry"],["lunora shards prune --tables messages","Only prune the shards listed for `messages`"],["lunora shards prune --prod --url https://app.example.com","Prune production"]],group:"Data",loader:()=>import("../packem_chunks/handler14.mjs").then(e=>({default:e.execute})),name:"shards",options:[{description:"Comma-separated .shardBy() tables (default: all of them)",name:"tables",type:String},{description:"Report what would be pruned without changing the registry",name:"dry-run",type:Boolean},s,{description:"Target production — requires an explicit --url",name:"prod",type:Boolean},{description:"Worker URL (defaults to the running dev server)",name:"url",type:String},{description:"Admin bearer token (or LUNORA_ADMIN_TOKEN)",name:"token",type:String}]},Re={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/handler15.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: ${m} (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},s,{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},p]},Oe={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/handler16.mjs").then(e=>({default:e.execute})),name:"view"},Ne=(e,t)=>{const r=Array.from({length:t.length+1},(o,n)=>n);for(let o=1;o<=e.length;o+=1){let n=r[0]??0;r[0]=o;for(let a=1;a<=t.length;a+=1){const i=r[a]??0,l=e[o-1]===t[a-1]?0:1;r[a]=Math.min((r[a-1]??0)+1,i+1,n+l),n=i}}return r[t.length]??0},O=(e,t)=>{let r,o=Number.POSITIVE_INFINITY;for(const a of t){const i=Ne(e,a);i<o&&(o=i,r=a)}const n=Math.max(2,Math.ceil(e.length/3));return r!==void 0&&o<=n?r:void 0},Ae=e=>`https://registry.npmjs.org/@lunora/cli/${e}`,Be=1440*60*1e3,De=1500,Ee="0.0.0",Le=/^v/u,Ie=new Set(["alpha","beta","next"]),g=e=>{const t=e.trim().replace(Le,""),r=t.indexOf("-");return r===-1?{core:t,prerelease:""}:{core:t.slice(0,r),prerelease:t.slice(r+1)}},x=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]},je=(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},Te=(e,t)=>{if(e===t)return 0;if(e===""||t==="")return e===""?1:-1;const r=e.split("."),o=t.split(".");for(let n=0;n<Math.max(r.length,o.length);n+=1){const a=r[n],i=o[n];if(a===void 0||i===void 0)return a===void 0?-1:1;if(a!==i)return je(a,i)}return 0},_e=(e,t)=>{const r=x(e),o=x(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 Te(g(e).prerelease,g(t).prerelease)},Pe=e=>{const t=g(e).prerelease.split(".")[0]??"";return Ie.has(t)?t:"latest"},Me=(e,t)=>_e(t,e)>0,Ue=(e,t,r)=>t-e<r,We=(e,t,r="latest",o)=>{const n=`Update available for @lunora/cli: ${e} → ${t}`;if(o===void 0)return`${n} — add @lunora/cli@${r} as a dev dependency to update`;const{args:a,command:i}=V(o,[`@lunora/cli@${r}`],{dev:!0});return`${n} — run \`${i} ${a.join(" ")}\``},N=e=>b(e,"lunora-cli-update.json"),$e=e=>{const t=e.XDG_CACHE_HOME&&e.XDG_CACHE_HOME.length>0?e.XDG_CACHE_HOME:b(G(),".cache"),r=b(t,"lunora");try{$(r,{mode:448,recursive:!0})}catch{}return r},Fe=e=>{try{const t=JSON.parse(F(N(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{}},C=(e,t)=>{try{const r=N(e);try{if(J(r).isSymbolicLink())return}catch{}K(r,`${JSON.stringify(t)}
2
+ `,"utf8")}catch{}},Je=async(e,t)=>{try{const r=await e(Ae(t),{signal:AbortSignal.timeout(De)});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}},Ke=(e,t,r)=>e===Ee||!r||t.CI!==void 0||t.LUNORA_NO_UPDATE_NOTIFIER!==void 0,Ge=async e=>{const t=e.env??process.env,r=e.isTTY??process.stdout.isTTY;if(Ke(e.current,t,r))return;const o=e.cacheDir??$e(t),n=(e.now??Date.now)(),a=e.ttlMs??Be,i=Pe(e.current),l=Fe(o),c=l?.tag??"latest",d=l!==void 0&&c===i?l:void 0;let h=d?.latest;if(d===void 0||!Ue(d.checkedAt,n,a)){const f=await Je(e.fetchImpl??globalThis.fetch,i);f===void 0?C(o,{checkedAt:n,latest:e.current,tag:i}):(h=f,C(o,{checkedAt:n,latest:f,tag:i}))}h!==void 0&&Me(e.current,h)&&e.logger.warn(We(e.current,h,i,e.manager))},A=["init","add","dev","codegen","build","deploy","prepare","link","cloudflare","logs","run","insights","reset","migrate","export","import","seed","shards","backup","eval","verify","info","doctor","env","analyze","view","docs","registry","rules","mcp"],B=M(),Ve=[pe,z,re,ee,H,X,te,ye,me,R,he,ke,ce,be,fe,se,le,xe,Ce,ue,Q,ie,Re,de,ne,ae,Y,Oe,oe,ve,we,ge,Se],D=[...Ve,_,T],wt=D.map(e=>e.name),u=e=>e.replaceAll("{",String.raw`\{`).replaceAll("}",String.raw`\}`),qe=e=>e.every(t=>typeof t=="string")?e.map(t=>u(t)):e.map(t=>typeof t=="string"?[u(t)]:t.map(r=>u(r))),ze=e=>({...e,...e.argument===void 0?{}:{argument:{...e.argument,description:u(e.argument.description??"")}},...e.description===void 0?{}:{description:u(e.description)},...e.examples===void 0?{}:{examples:qe(e.examples)},...e.options===void 0?{}:{options:e.options.map(t=>({...t,description:u(t.description??"")}))}}),He=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:B});for(const o of D)r.addCommand(ze(o));return{cli:r,exitCode:t}},Ye=/Command "(?<name>[^"]+)" not found/u,w={ai:{absorbs:"gateway",to:"cloudflare ai-gateway"},alerts:{to:"cloudflare alerts"},containers:{to:"cloudflare containers"},deployments:{to:"cloudflare deployments"}},Qe=new Set((R.options??[]).filter(e=>e.type!==Boolean).map(e=>`--${e.name}`)),Xe=/^[\w@%+=:,./-]+$/u,Ze=e=>Xe.test(e)?e:`'${e.replaceAll("'",String.raw`'\''`)}'`,et=(e,t)=>{const r=e.indexOf(t);return r===-1?[...e]:[...e.slice(0,r),...e.slice(r+1)]},tt=(e,t)=>e.findIndex((r,o)=>r===t&&(o===0||!Qe.has(e[o-1]??""))),rt=e=>{const t=O(e,[...A,...Object.keys(w)]);return t!==void 0&&Object.hasOwn(w,t)?t:void 0},E=(e,t,r)=>{const o=rt(e),n=o===void 0?void 0:w[o];if(o===void 0||n===void 0)return;const a=e===o?"":`\`lunora ${e}\` is not a command. `;let i=[...t];if(n.absorbs!==void 0){const d=tt(i,n.absorbs);if(d===-1&&r===void 0)return`${a}\`lunora ${o}\` had one subcommand, \`${n.absorbs}\`; it moved to \`lunora ${n.to}\`.`;i=d===-1?i:[...i.slice(0,d),...i.slice(d+1)]}const l=n.absorbs===void 0?o:`${o} ${n.absorbs}`,c=r??["lunora",n.to,...i.map(d=>Ze(d))].join(" ");return`${a}\`lunora ${l}\` moved to \`lunora ${n.to}\`. Run: ${c}`},ot=(e,t)=>{const r=v(),o=e instanceof Error?e.message:String(e),n=Ye.exec(o);if(!n?.groups)return L(e)||I(o)!==void 0?r.error(W(e)):r.error(o),U(e);const a=n.groups.name??"",i=a.split(" ")[0]??"",l=E(i,et(t,i));if(l!==void 0)return r.error(l),y.USAGE;const c=O(a,A);return r.error(`Unknown command "${a}".${c===void 0?"":` Did you mean "${c}"?`}`),r.info("Run `lunora --help` to list commands, or `lunora docs` to open the documentation."),y.USAGE},nt=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)}}),kt=async(e={})=>{const{cli:t,exitCode:r}=He(e);e.logger!==void 0&&k(nt(e.logger));const o=e.argv??process.argv.slice(2);try{const a=o[0]==="help"&&o[1]!==void 0?E(o[1],o.slice(2),"lunora help cloudflare"):void 0;if(a!==void 0)return v().error(a),y.USAGE;await t.run({shouldExitProcess:!1})}catch(a){return ot(a,o)}finally{k(void 0)}let n;try{n=q(process.cwd())}catch{}return await Ge({current:B,logger:v(),manager:n}),r.value};export{A as C,S as D,wt as R,B as V,Z as a,kt as r};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@lunora/cli",
3
- "version": "1.0.0-alpha.377",
3
+ "version": "1.0.0-alpha.378",
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",
@@ -55,7 +55,7 @@
55
55
  "@lunora/advisor": "1.0.0-alpha.206",
56
56
  "@lunora/bindings": "1.0.0-alpha.103",
57
57
  "@lunora/codegen": "1.0.0-alpha.290",
58
- "@lunora/config": "1.0.0-alpha.333",
58
+ "@lunora/config": "1.0.0-alpha.334",
59
59
  "@lunora/container": "1.0.0-alpha.72",
60
60
  "@lunora/d1": "1.0.0-alpha.169",
61
61
  "@lunora/errors": ">=1.0.0-alpha.51 <2.0.0-0",
@@ -1,2 +0,0 @@
1
- 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 s}from"./output-format-B4eQHi5y.mjs";import{A as m,T as p}from"./deploy-target-DCWwiuAe.mjs";import{SDK_LANGUAGES as P}from"@lunora/codegen";import{r as M}from"./cli-manifest-CRet0egA.mjs";import{EXIT_CODE as y,exitCodeForError as U}from"./EXIT_CODE-D_XCixv8.mjs";import{setCommandLogger as k,createLogger as v}from"./createLogger-Cl18I8AX.mjs";import{r as W}from"./render-lunora-error-C3OJY5wk.mjs";import{mkdirSync as $,readFileSync as F,lstatSync as J,writeFileSync as K}from"node:fs";import{homedir as G}from"node:os";import{join as b}from"node:path";import{addArgsFor as V,detectPackageManager as q}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},s]},S="lunora.advisor.map.json",z={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/handler17.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 ${S})`,name:"baseline",type:String},{description:"Inspect a single procedure by `file#exportName`",name:"entry",type:String},s,{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 ${S})`,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}]},Y={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:[s]},Q={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/handler20.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},s,{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}]},X={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/handler18.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: ${m} (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},s,{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},p]},Z=[{name:"alerts",summary:"usage alerts that catch a runaway bill",usage:"[status | setup | test]"},{name:"ai-gateway",summary:"create or reuse an AI Gateway for ctx.ai and write its id into wrangler vars",usage:""},{name:"containers",summary:"build and push container images, manage instances (wraps wrangler containers)",usage:"<build|push|images|list|info|delete> [args…]"},{name:"deployments",summary:"deployment history; roll back or promote Worker versions",usage:"list | inspect <version-id> | rollback [version-id] | promote <version-id>"}],C={argument:{description:`${Z.map(e=>e.name).join(" | ")}, then the tool's own arguments`,name:"tool",type:String},description:"Cloudflare-only tools: usage alerts, AI Gateway, containers, deployments",examples:[["lunora cloudflare","List the tools"],["lunora cloudflare alerts","Show last month's usage and which products have an alert"],["lunora cloudflare alerts setup --email ops@example.com --dry-run","Show the alerts setup would create, without creating them"],["lunora cloudflare alerts setup --email ops@example.com --multiplier 5 --yes","Create or update the alerts at 5x last month"],["lunora cloudflare alerts setup --email ops@example.com --threshold do-duration=500000 --yes","Also alert on Durable Objects duration at a limit you choose"],["lunora cloudflare alerts test","Show what Cloudflare has delivered to your alert destinations"],["lunora cloudflare ai-gateway","Create (or reuse) a gateway named after the worker and wire it into wrangler vars"],["lunora cloudflare ai-gateway --id my-gateway --no-logs","Use an explicit gateway id, with prompt/response log collection off"],["lunora cloudflare ai-gateway --dry-run","Print what would be created and written, without calling Cloudflare"],["lunora cloudflare containers build ./containers/transcoder --tag transcoder:v1 --push","Build an image and push it to the Cloudflare Registry"],["lunora cloudflare containers images list","List images in your Cloudflare Registry"],["lunora cloudflare containers list --format json","List container instances as JSON (also `info`, `images list`)"],["lunora cloudflare containers images delete transcoder:v1","Delete an image to free registry storage"],["lunora cloudflare deployments list","Show the 10 most recent deployments"],["lunora cloudflare deployments inspect <version-id>","View a specific Worker version"],["lunora cloudflare deployments rollback --yes","Roll back to the previous version"],["lunora cloudflare deployments promote <version-id> --yes","Send 100% of traffic to a version"]],group:"Deploy",loader:()=>import("../packem_chunks/handler26.mjs").then(e=>({default:e.execute})),name:"cloudflare",options:[{description:"alerts setup: email address to notify. Repeatable",lazyMultiple:!0,name:"email",type:String},{description:"alerts setup / test: Cloudflare webhook destination id. Repeatable",lazyMultiple:!0,name:"webhook",type:String},{description:"alerts setup: alert at this many times last month's usage (default 3)",name:"multiplier",type:String},{description:"alerts setup: set one metric's limit yourself, in the product's unit: <metric>=<n>. Repeatable",lazyMultiple:!0,name:"threshold",type:String},{description:"alerts setup: accept the floor for a metric whose usage could not be read",name:"allow-floor",type:Boolean},{description:"alerts setup: replace an updated alert's recipients instead of adding to them",name:"replace-recipients",type:Boolean},{description:"alerts setup / ai-gateway: show the plan without creating, updating or writing anything",name:"dry-run",type:Boolean},{description:"alerts setup: apply the plan without asking (required when stdin is not a TTY). deployments rollback / promote: confirm the traffic change (required)",name:"yes",type:Boolean},{description:"ai-gateway: gateway id (default: the worker `name` from wrangler.jsonc)",name:"id",type:String},{description:"ai-gateway: collect request/response logs in the gateway (default)",name:"logs",type:Boolean},{description:"ai-gateway: create the gateway with log collection off (prompts and responses are not stored)",name:"no-logs",type:Boolean},{description:"containers build: name:tag for the image (forwarded to wrangler --tag)",name:"tag",type:String},{description:"containers build: push the image to the Cloudflare Registry after building",name:"push",type:Boolean},{description:"containers / deployments: Cloudflare environment name",name:"env",type:String},{description:"deployments rollback / promote: reason recorded with the change",name:"message",type:String},{...s,description:"Output format: pretty (default) or json (containers: list | info | images list; deployments: list only)"},p]},ee={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: ${m} (default openapi)`,name:"api-spec",type:String},s,{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},p]},te={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: ${m} (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},s,{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},{description:"Deploy only the app, not the lunora.config services it binds (they deploy first by default)",name:"skip-services",type:Boolean},p,{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}]},re={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)"],["lunora dev --local","Start no remote proxy session, e.g. in CI where a service's `ai` binding has no credentials"],["lunora dev --tunnel","Share the worker on a public *.trycloudflare.com URL (needs cloudflared ≥ 2026.9.3)"],["lunora dev --tunnel --allow-mail you@example.com","Same, but visitors must confirm an allowed email with a one-time PIN"]],group:"Develop",loader:()=>import("../packem_chunks/runDevCommand.mjs").then(e=>({default:e.execute})),name:"dev",options:[{description:`Which API spec(s) codegen emits: ${m} (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},p,{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},{description:"Pass --local to wrangler dev: no remote proxy session, so an `ai` binding (in the app or a service) cannot stop dev from starting without Cloudflare credentials — it fails when called instead",name:"local",type:Boolean},{description:"Share the worker through a Cloudflare quick tunnel (*.trycloudflare.com, needs cloudflared ≥ 2026.9.3). PUBLIC unless --allow-mail is given",name:"tunnel",type:Boolean},{description:"With --tunnel: only these emails get in, after a one-time PIN (passed to cloudflared as --allowed-mail). Repeatable; accepts a comma list and '*@domain'",lazyMultiple:!0,name:"allow-mail",type:String}]},oe={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/handler3.mjs").then(e=>({default:e.execute})),name:"docs"},ne={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/handler23.mjs").then(e=>({default:e.execute})),name:"doctor",options:[s]},ae={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/handler4.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},s,{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}]},ie={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/handler21.mjs").then(e=>({default:e.execute})),name:"eval",options:[{description:"Directory to discover *.eval.ts files under (default evals/)",name:"dir",type:String},s,{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}]},se={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/handler5.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},{...s,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}]},le={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/handler6.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},s,{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}]},de={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/handler7.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},s,{description:"With --bindings: write the manifest to <file> instead of stdout",name:"out",type:String}]},pe={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}]},ce={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/handler8.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},s,{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}]},ue={description:"Scaffold lunora/schema.ts (and list/get procedures) from an existing Postgres or MySQL database",examples:[["lunora introspect --url postgres://localhost/shop","Scaffold a schema + procedures from every table"],["lunora introspect --tables users,orders","Introspect only these tables (DATABASE_URL is read by default)"],["lunora introspect --dry-run","Print what would be written without touching the filesystem"],["lunora introspect --no-procedures --force","Regenerate just the schema, overwriting the existing file"]],group:"Data",loader:()=>import("../packem_chunks/handler24.mjs").then(e=>({default:e.execute})),name:"introspect",options:[{description:"Database connection string (default: $DATABASE_URL)",name:"url",type:String},{description:"Postgres schema (default `public`) or MySQL database name",name:"schema",type:String},{description:"Comma-separated table allow-list (default: every base table)",name:"tables",type:String},{description:"Also emit list/get procedure modules per table (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},s]},me={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/handler9.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}]},he={argument:{description:"Worker name (defaults to the name in wrangler config)",name:"worker",type:String},description:"Stream live logs from a deployed Worker, or read the durable log archive with --durable",group:"Deploy",loader:()=>import("../packem_chunks/handler22.mjs").then(e=>({default:e.execute})),name:"logs",options:[{description:"Cloudflare environment name",name:"env",type:String},s,{description:"Substring filter on log messages",name:"search",type:String},{description:"Filter by invocation status: ok, error, or canceled",name:"status",type:String},p,{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}]},ge={argument:{description:"install [client…] | uninstall [client…] | serve",name:"args",type:String},description:"Connect your AI editor to Lunora over MCP (docs search + this project's dev server)",examples:[["lunora mcp install","Install into every MCP client already configured here"],["lunora mcp install claude-code cursor","Install into specific clients"],["lunora mcp install --list","List the supported clients and their config files"],["lunora mcp install --docs-only","Install only the hosted documentation server"],["lunora mcp install --print","Show the config that would be written, without writing it"],["lunora mcp install --global","Force every server into the machine-wide config"],["lunora mcp uninstall","Remove Lunora's MCP servers from every supported client"],["lunora mcp uninstall cursor","Remove them from one client"],["lunora mcp uninstall --print","Show what would be removed, without removing it"],["lunora mcp serve","Run the stdio MCP server (this is what your editor spawns)"],["lunora mcp serve --allow-writes","Also expose the mutation/action tools"],["lunora mcp serve --token $LUNORA_ADMIN_TOKEN","Expose the observability tools (logs, issues, advisories, insights, migrations) too"]],group:"Develop",loader:()=>import("../packem_chunks/handler25.mjs").then(e=>({default:e.execute})),name:"mcp",options:[{description:"install: replace entries that already exist",name:"force",type:Boolean},{description:"install: list the supported clients and their config files",name:"list",type:Boolean},{description:"install/uninstall: print what would change instead of writing it",name:"print",type:Boolean},{description:"install/uninstall: only the hosted documentation server",name:"docs-only",type:Boolean},{description:"install/uninstall: only this project's local server",name:"local-only",type:Boolean},{description:"install/uninstall: the machine-wide config (install default: docs server global, local server per-project)",name:"global",type:Boolean},{description:"install/uninstall: this project's config instead of the machine-wide one",name:"project",type:Boolean},{description:"serve: also expose the mutation/action tools (default: read-only)",name:"allow-writes",type:Boolean},{description:"serve: 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}]},fe={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},s,{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}]},ye={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/handler10.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: ${m} (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},p,{description:"Re-bless the committed schema baseline (lunora/.lunora-schema.json) with the current shape",name:"update-schema-baseline",type:Boolean}]},ve={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/handler11.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},{...s,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}]},be={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}]},we={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/handler12.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}]},ke={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},s,{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}]},Se={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/handler19.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}]},xe={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/handler13.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},s,{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}]},Re={argument:{description:"prune",name:"subcommand",type:String},description:"Maintain the shard registry: prune shards that no longer hold any rows of their .shardBy() table",examples:[["lunora shards prune --dry-run","Show which registered shards are empty, without removing anything"],["lunora shards prune","Remove the empty shards from the registry"],["lunora shards prune --tables messages","Only prune the shards listed for `messages`"],["lunora shards prune --prod --url https://app.example.com","Prune production"]],group:"Data",loader:()=>import("../packem_chunks/handler14.mjs").then(e=>({default:e.execute})),name:"shards",options:[{description:"Comma-separated .shardBy() tables (default: all of them)",name:"tables",type:String},{description:"Report what would be pruned without changing the registry",name:"dry-run",type:Boolean},s,{description:"Target production — requires an explicit --url",name:"prod",type:Boolean},{description:"Worker URL (defaults to the running dev server)",name:"url",type:String},{description:"Admin bearer token (or LUNORA_ADMIN_TOKEN)",name:"token",type:String}]},Ce={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/handler15.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: ${m} (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},s,{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},p]},Oe={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/handler16.mjs").then(e=>({default:e.execute})),name:"view"},Ne=(e,t)=>{const r=Array.from({length:t.length+1},(o,n)=>n);for(let o=1;o<=e.length;o+=1){let n=r[0]??0;r[0]=o;for(let a=1;a<=t.length;a+=1){const i=r[a]??0,l=e[o-1]===t[a-1]?0:1;r[a]=Math.min((r[a-1]??0)+1,i+1,n+l),n=i}}return r[t.length]??0},O=(e,t)=>{let r,o=Number.POSITIVE_INFINITY;for(const a of t){const i=Ne(e,a);i<o&&(o=i,r=a)}const n=Math.max(2,Math.ceil(e.length/3));return r!==void 0&&o<=n?r:void 0},Ae=e=>`https://registry.npmjs.org/@lunora/cli/${e}`,Be=1440*60*1e3,De=1500,Ee="0.0.0",Le=/^v/u,Ie=new Set(["alpha","beta","next"]),g=e=>{const t=e.trim().replace(Le,""),r=t.indexOf("-");return r===-1?{core:t,prerelease:""}:{core:t.slice(0,r),prerelease:t.slice(r+1)}},x=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]},je=(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},Te=(e,t)=>{if(e===t)return 0;if(e===""||t==="")return e===""?1:-1;const r=e.split("."),o=t.split(".");for(let n=0;n<Math.max(r.length,o.length);n+=1){const a=r[n],i=o[n];if(a===void 0||i===void 0)return a===void 0?-1:1;if(a!==i)return je(a,i)}return 0},_e=(e,t)=>{const r=x(e),o=x(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 Te(g(e).prerelease,g(t).prerelease)},Pe=e=>{const t=g(e).prerelease.split(".")[0]??"";return Ie.has(t)?t:"latest"},Me=(e,t)=>_e(t,e)>0,Ue=(e,t,r)=>t-e<r,We=(e,t,r="latest",o)=>{const n=`Update available for @lunora/cli: ${e} → ${t}`;if(o===void 0)return`${n} — add @lunora/cli@${r} as a dev dependency to update`;const{args:a,command:i}=V(o,[`@lunora/cli@${r}`],{dev:!0});return`${n} — run \`${i} ${a.join(" ")}\``},N=e=>b(e,"lunora-cli-update.json"),$e=e=>{const t=e.XDG_CACHE_HOME&&e.XDG_CACHE_HOME.length>0?e.XDG_CACHE_HOME:b(G(),".cache"),r=b(t,"lunora");try{$(r,{mode:448,recursive:!0})}catch{}return r},Fe=e=>{try{const t=JSON.parse(F(N(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{}},R=(e,t)=>{try{const r=N(e);try{if(J(r).isSymbolicLink())return}catch{}K(r,`${JSON.stringify(t)}
2
- `,"utf8")}catch{}},Je=async(e,t)=>{try{const r=await e(Ae(t),{signal:AbortSignal.timeout(De)});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}},Ke=(e,t,r)=>e===Ee||!r||t.CI!==void 0||t.LUNORA_NO_UPDATE_NOTIFIER!==void 0,Ge=async e=>{const t=e.env??process.env,r=e.isTTY??process.stdout.isTTY;if(Ke(e.current,t,r))return;const o=e.cacheDir??$e(t),n=(e.now??Date.now)(),a=e.ttlMs??Be,i=Pe(e.current),l=Fe(o),c=l?.tag??"latest",d=l!==void 0&&c===i?l:void 0;let h=d?.latest;if(d===void 0||!Ue(d.checkedAt,n,a)){const f=await Je(e.fetchImpl??globalThis.fetch,i);f===void 0?R(o,{checkedAt:n,latest:e.current,tag:i}):(h=f,R(o,{checkedAt:n,latest:f,tag:i}))}h!==void 0&&Me(e.current,h)&&e.logger.warn(We(e.current,h,i,e.manager))},A=["init","add","dev","codegen","build","deploy","prepare","link","cloudflare","logs","run","insights","reset","migrate","export","import","seed","shards","backup","eval","verify","info","doctor","env","analyze","view","docs","registry","rules","mcp"],B=M(),Ve=[pe,H,re,ee,z,X,te,ye,me,C,he,ke,ce,be,fe,se,le,xe,Re,ue,Q,ie,Ce,de,ne,ae,Y,Oe,oe,ve,we,ge,Se],D=[...Ve,_,T],wt=D.map(e=>e.name),u=e=>e.replaceAll("{",String.raw`\{`).replaceAll("}",String.raw`\}`),qe=e=>e.every(t=>typeof t=="string")?e.map(t=>u(t)):e.map(t=>typeof t=="string"?[u(t)]:t.map(r=>u(r))),He=e=>({...e,...e.argument===void 0?{}:{argument:{...e.argument,description:u(e.argument.description??"")}},...e.description===void 0?{}:{description:u(e.description)},...e.examples===void 0?{}:{examples:qe(e.examples)},...e.options===void 0?{}:{options:e.options.map(t=>({...t,description:u(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:B});for(const o of D)r.addCommand(He(o));return{cli:r,exitCode:t}},Ye=/Command "(?<name>[^"]+)" not found/u,w={ai:{absorbs:"gateway",to:"cloudflare ai-gateway"},alerts:{to:"cloudflare alerts"},containers:{to:"cloudflare containers"},deployments:{to:"cloudflare deployments"}},Qe=new Set((C.options??[]).filter(e=>e.type!==Boolean).map(e=>`--${e.name}`)),Xe=/^[\w@%+=:,./-]+$/u,Ze=e=>Xe.test(e)?e:`'${e.replaceAll("'",String.raw`'\''`)}'`,et=(e,t)=>{const r=e.indexOf(t);return r===-1?[...e]:[...e.slice(0,r),...e.slice(r+1)]},tt=(e,t)=>e.findIndex((r,o)=>r===t&&(o===0||!Qe.has(e[o-1]??""))),rt=e=>{const t=O(e,[...A,...Object.keys(w)]);return t!==void 0&&Object.hasOwn(w,t)?t:void 0},E=(e,t,r)=>{const o=rt(e),n=o===void 0?void 0:w[o];if(o===void 0||n===void 0)return;const a=e===o?"":`\`lunora ${e}\` is not a command. `;let i=[...t];if(n.absorbs!==void 0){const d=tt(i,n.absorbs);if(d===-1&&r===void 0)return`${a}\`lunora ${o}\` had one subcommand, \`${n.absorbs}\`; it moved to \`lunora ${n.to}\`.`;i=d===-1?i:[...i.slice(0,d),...i.slice(d+1)]}const l=n.absorbs===void 0?o:`${o} ${n.absorbs}`,c=r??["lunora",n.to,...i.map(d=>Ze(d))].join(" ");return`${a}\`lunora ${l}\` moved to \`lunora ${n.to}\`. Run: ${c}`},ot=(e,t)=>{const r=v(),o=e instanceof Error?e.message:String(e),n=Ye.exec(o);if(!n?.groups)return L(e)||I(o)!==void 0?r.error(W(e)):r.error(o),U(e);const a=n.groups.name??"",i=a.split(" ")[0]??"",l=E(i,et(t,i));if(l!==void 0)return r.error(l),y.USAGE;const c=O(a,A);return r.error(`Unknown command "${a}".${c===void 0?"":` Did you mean "${c}"?`}`),r.info("Run `lunora --help` to list commands, or `lunora docs` to open the documentation."),y.USAGE},nt=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)}}),kt=async(e={})=>{const{cli:t,exitCode:r}=ze(e);e.logger!==void 0&&k(nt(e.logger));const o=e.argv??process.argv.slice(2);try{const a=o[0]==="help"&&o[1]!==void 0?E(o[1],o.slice(2),"lunora help cloudflare"):void 0;if(a!==void 0)return v().error(a),y.USAGE;await t.run({shouldExitProcess:!1})}catch(a){return ot(a,o)}finally{k(void 0)}let n;try{n=q(process.cwd())}catch{}return await Ge({current:B,logger:v(),manager:n}),r.value};export{A as C,S as D,wt as R,B as V,Z as a,kt as r};