@lunora/cli 1.0.0-alpha.370 → 1.0.0-alpha.371

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-6BRlq6nw.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-DVVI8I8G.mjs";try{const r=await e();process.exit(r)}catch(r){process.stderr.write(`${r instanceof Error?r.message:String(r)}
3
3
  `),process.exit(1)}
package/dist/index.d.mts CHANGED
@@ -3,7 +3,7 @@ import { ensureDevVariables, ensureDevVarsExample, fillDevSecrets, startCelldDev
3
3
  import { materializeRemoteWranglerConfig, materializeServiceDevConfigs } from '@lunora/config/cloudflare';
4
4
  export { REQUIRED_COMPATIBILITY_DATE, REQUIRED_FLAG, type WranglerProjectValidationOptions as WranglerValidationOptions, type WranglerValidationReport, type WranglerProjectValidationResult as WranglerValidationResult, validateWranglerProject as validateWrangler, validateWranglerConfig } from '@lunora/config/cloudflare';
5
5
  /** Every command name the CLI registers (drives the `CommandName` type + tests). */
6
- declare const COMMANDS: readonly ["init", "add", "dev", "codegen", "build", "deploy", "containers", "ai", "prepare", "link", "deployments", "logs", "run", "insights", "reset", "migrate", "export", "import", "seed", "shards", "backup", "eval", "verify", "info", "doctor", "env", "analyze", "view", "docs", "registry", "rules", "mcp"];
6
+ declare const COMMANDS: readonly ["init", "add", "dev", "codegen", "build", "deploy", "containers", "ai", "prepare", "link", "deployments", "cloudflare", "logs", "run", "insights", "reset", "migrate", "export", "import", "seed", "shards", "backup", "eval", "verify", "info", "doctor", "env", "analyze", "view", "docs", "registry", "rules", "mcp"];
7
7
  type CommandName = (typeof COMMANDS)[number];
8
8
  declare const VERSION: string;
9
9
  interface RunCliOptions {
package/dist/index.d.ts CHANGED
@@ -3,7 +3,7 @@ import { ensureDevVariables, ensureDevVarsExample, fillDevSecrets, startCelldDev
3
3
  import { materializeRemoteWranglerConfig, materializeServiceDevConfigs } from '@lunora/config/cloudflare';
4
4
  export { REQUIRED_COMPATIBILITY_DATE, REQUIRED_FLAG, type WranglerProjectValidationOptions as WranglerValidationOptions, type WranglerValidationReport, type WranglerProjectValidationResult as WranglerValidationResult, validateWranglerProject as validateWrangler, validateWranglerConfig } from '@lunora/config/cloudflare';
5
5
  /** Every command name the CLI registers (drives the `CommandName` type + tests). */
6
- declare const COMMANDS: readonly ["init", "add", "dev", "codegen", "build", "deploy", "containers", "ai", "prepare", "link", "deployments", "logs", "run", "insights", "reset", "migrate", "export", "import", "seed", "shards", "backup", "eval", "verify", "info", "doctor", "env", "analyze", "view", "docs", "registry", "rules", "mcp"];
6
+ declare const COMMANDS: readonly ["init", "add", "dev", "codegen", "build", "deploy", "containers", "ai", "prepare", "link", "deployments", "cloudflare", "logs", "run", "insights", "reset", "migrate", "export", "import", "seed", "shards", "backup", "eval", "verify", "info", "doctor", "env", "analyze", "view", "docs", "registry", "rules", "mcp"];
7
7
  type CommandName = (typeof COMMANDS)[number];
8
8
  declare const VERSION: string;
9
9
  interface RunCliOptions {
package/dist/index.mjs CHANGED
@@ -1 +1 @@
1
- import{C as o,V as a,r as n}from"./packem_shared/cli-6BRlq6nw.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-DVVI8I8G.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-6BRlq6nw.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-DVVI8I8G.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 +1 @@
1
- import{existsSync as g,readFileSync as x,realpathSync as b}from"node:fs";import{join as f}from"node:path";import{readServiceBindings as I,readProjectTarget as $,DEFAULT_TARGET as A}from"@lunora/codegen";import{DEV_VARS_FILE as p,parseDevVariableEntries as R,isPlaceholderValue as S,readProjectDependencies as L,discoverSchemaInfo as O,inferLunoraBindings as N,resolveSchemaDirectory as C}from"@lunora/config";import{GLOBAL_FETCH_STRICTLY_PUBLIC_FLAG as m,resolveObservabilitySampling as E,findWranglerFile as D,readWranglerJsonc as P,validateWranglerProject as T,UNEXPORTED_CLASS_MARKER as w,detectCloudflareCliConfig as F,collectExportGaps as U}from"@lunora/config/cloudflare";import{i as G,m as V,c as B,a as M,b as W}from"../packem_shared/secret-key-BCrqNJ68.mjs";import{r as K,d as z}from"../packem_shared/admin-token-VdUnvnKW.mjs";import{n as j}from"../packem_shared/cloudflare-credentials-lC5JtPLe.mjs";import{d as H}from"../packem_shared/command-CAXl2A1S.mjs";import{i as J}from"../packem_shared/path-containment-CgxYZggb.mjs";import{b as k,c as y,a as h}from"../packem_shared/variables-acxcvVQa.mjs";const q=(t,r)=>{const e=new Set,n=s=>{for(const[c,i]of Object.entries(s??{}))typeof i=="string"&&i.trim().length>0&&e.add(c)};n(t.vars);for(const s of Object.values(t.env??{}))n(s.vars);const o=f(r,p);if(g(o))try{n(Object.fromEntries(R(x(o,"utf8")).map(s=>[s.key,s.value])))}catch{}return e},Y=(t,r,e,n)=>{if(t===void 0||!e)return;const o=q(t,r),s=o.has(k),c=t.ai?.binding;!s&&(typeof c!="string"||c.length===0)&&n.push({code:"ai-binding-missing",fix:`Run \`lunora dev\` (it adds the binding), add \`"ai": { "binding": "AI" }\` to wrangler.jsonc, or set ${k} to an OpenAI-compatible proxy.`,level:"warn",message:"the project uses ctx.ai (@lunora/ai / env.AI) but wrangler.jsonc declares no `ai` binding — model calls will fail at runtime."}),o.has(y)&&n.push({code:"ai-gateway-token-unused",fix:"Make the gateway unauthenticated for ctx.ai, or remove the token. A bring-your-own AI SDK provider built with `resolveAiGateway` does send it.",level:"warn",message:`${y} is set, but ctx.ai's Workers AI binding cannot send a gateway token — it is ignored on that path.`}),!s&&!o.has(h)&&n.push({code:"ai-gateway-default",fix:`Run \`lunora ai gateway\` to create a gateway for this app and write ${h} into wrangler vars.`,level:"info",message:`no ${h} in vars or ${p} — \`<provider>/<model>\` slugs route through the account's \`default\` AI Gateway.`})},X=(t,r,e)=>{if(t===void 0||!r)return;const n=[];(t.compatibility_flags??[]).includes(m)||n.push("the top level");for(const[o,s]of Object.entries(t.env??{}))s.compatibility_flags!==void 0&&!s.compatibility_flags.includes(m)&&n.push(`env.${o}`);n.length>0&&e.push({code:"cimd-fetch-not-strictly-public",fix:`Add "${m}" to "compatibility_flags" in wrangler.jsonc.`,level:"warn",message:`@lunora/auth/cimd/workers is imported, but ${n.join(", ")} of wrangler.jsonc lacks the ${m} compatibility flag — workersCimdFetch() refuses to build without it.`})},_=t=>{const{logs:r,traces:e}=E(t);return Object.entries({logs:r,traces:e}).filter(([,n])=>n.enabled&&n.headSamplingRate>=1).map(([n])=>n)},Q=(t,r)=>{if(t===void 0)return;const e=[],n=_(t.observability);n.length>0&&e.push(`${n.join(" + ")} (top level)`);for(const[o,s]of Object.entries(t.env??{})){if(s.observability===void 0)continue;const c=_(s.observability);c.length>0&&e.push(`${c.join(" + ")} (env.${o})`)}e.length!==0&&r.push({code:"observability-full-sampling",fix:"For a high-traffic Worker, lower head_sampling_rate in wrangler.jsonc: under observability for logs, under observability.traces for traces — e.g. 0.1 keeps 10% of requests. Lunora never changes a rate you set.",level:"info",message:`observability samples every request (head_sampling_rate 1) for ${e.join(", ")}. From 2026-12-01 Workers Observability is billed: Free caps ingestion at 0.5 GB/day; Paid includes 50 GB per billing cycle, then $0.25/GB.`})},Z=(t,r)=>{for(const e of I(t).services)for(const n of e.publicScopes){const o=n===""?"":` (env.${n})`;r.push({code:"service-workers-dev",fix:`If ${e.name} has no public route (custom domain or route, including ones set outside ${e.wranglerPath}), set \`"workers_dev": false\`${o}. Keep its internal auth (HMAC) either way.`,level:"warn",message:`service ${e.name} (${e.worker}) has no route in its wrangler config and still serves on workers.dev${o}; a custom domain set elsewhere would also be public.`})}},ee=t=>{const r=t.trim();if(r==="")return!0;const e=r.toLowerCase();return e.includes("replace")||e.startsWith("<")&&e.endsWith(">")},ne=t=>{const r=D(t);if(r===void 0)return{parsed:void 0,path:void 0};const{parsed:e}=P(r);return{parsed:e,path:r}},re=(t,r,e,n)=>{if(e===void 0){n.push({code:"wrangler-missing",fix:"Run `lunora init` (or `lunora dev`) to scaffold and reconcile wrangler.jsonc.",level:"fail",message:"wrangler.jsonc not found."});return}if(r===void 0){n.push({code:"wrangler-unparseable",fix:`Check ${e} is valid JSONC.`,level:"fail",message:`Could not parse ${e}.`});return}const{report:o}=T({projectRoot:t});for(const i of o.errors.filter(a=>a.includes(w)))n.push({code:"wrangler-class-unexported",level:"fail",message:i});for(const i of o.warnings.filter(a=>a.includes("LUNORA_ORIGIN_URL")))n.push({code:"scheduler-origin-missing",fix:"Set LUNORA_ORIGIN_URL in wrangler vars to the worker's public URL (or `wrangler secret put LUNORA_ORIGIN_URL`).",level:"warn",message:i});const s=i=>i.includes(w)||i.includes("SHARD");for(const i of o.errors.filter(a=>!s(a)))n.push({code:"wrangler-invalid",fix:"Fix the reported wrangler.jsonc problem; `lunora verify` reports the same set.",level:"fail",message:i});for(const i of o.warnings.filter(a=>!a.includes("LUNORA_ORIGIN_URL")))n.push({code:"wrangler-advisory",level:"warn",message:i});const c=o.errors.find(i=>i.includes("SHARD"));c===void 0?n.push({code:"wrangler-shard-binding-ok",level:"pass",message:"wrangler.jsonc present with a SHARD durable-object binding."}):n.push({code:"wrangler-shard-binding-missing",fix:"Run `lunora dev` to auto-reconcile, or add the binding manually.",level:"fail",message:c})},te=(t,r)=>{g(f(t,"lunora.json"))&&r.push({code:"stale-lunora-json",fix:'Move `target` / `remote` into `lunora.config.ts` (`export default { target: "…" }`), then delete lunora.json.',level:"warn",message:"lunora.json is present but no longer read — lunora.config.* replaced it, so any `target` or `remote` in it is being ignored."})},oe=(t,r)=>{const e=F(t);e!==void 0&&r.push({code:"cf-config-present",fix:e.fix,level:"warn",message:e.message})},se=(t,r)=>{t===void 0||t.limits?.cpu_ms!==void 0||r.push({code:"cpu-limit-missing",fix:'Add `"limits": { "cpu_ms": 30000 }` to wrangler.jsonc, tuned to your slowest legitimate handler.',level:"info",message:"no limits.cpu_ms is set — a runaway handler can burn CPU up to the platform default before anything stops it."})},ae=(t,r)=>{const e=(t?.r2_buckets??[]).map(n=>n?.bucket_name).filter(n=>typeof n=="string"&&n.length>0);e.length!==0&&r.push({code:"r2-lifecycle-unset",fix:"wrangler r2 bucket lifecycle list <bucket> — add an abort-incomplete-multipart rule if none exists.",level:"info",message:`R2 bucket(s) ${e.join(", ")}: verify a lifecycle rule aborts incomplete multipart uploads — orphaned parts are billed but invisible in a listing.`})},ie=(t,r)=>{const{error:e,info:n}=O(t,"lunora");if(e!==void 0){r.push({code:"schema-unreadable",fix:"Fix the parse error, then re-run `lunora doctor`. `lunora codegen` reports the same failure with the offending source.",level:"fail",message:`lunora/schema.ts could not be parsed, so every schema-derived check was skipped: ${e}`});return}for(const o of n?.vectorMetadata??[]){const s=V(o.kind);if(s===void 0){r.push({code:"vector-metadata-unfilterable",fix:"Filter on a string, number or boolean column, or drop it from `metadata`.",level:"warn",message:`vector index "${o.index}" declares metadata "${o.property}", whose type Vectorize cannot filter on.`});continue}r.push({code:"vector-metadata-index-required",fix:`wrangler ${B({index:o.index,property:o.property,type:s}).join(" ")}`,level:"info",message:`vector index "${o.index}" filters on metadata "${o.property}" — that needs a Vectorize metadata index (\`lunora deploy\` creates it).`})}},ce=(t,r)=>{if(t===void 0)return;const e=(t.d1_databases??[]).filter(Boolean);for(const n of e){const o=typeof n.database_id=="string"?n.database_id:"";if(ee(o)){const s=typeof n.binding=="string"&&n.binding.length>0?n.binding:"<unnamed>";r.push({code:"d1-placeholder-id",fix:"Run `wrangler d1 create <name>` and paste the returned database_id into wrangler.jsonc.",level:"fail",message:`D1 binding "${s}" has a placeholder database_id ("${o||"<empty>"}").`})}}},le=(t,r)=>{if(t===void 0)return;const e=(t.send_email??[]).filter(Boolean);for(const n of e){const o=typeof n.destination_address=="string"?n.destination_address:"";if(o!==""&&S(o)){const s=typeof n.name=="string"&&n.name.length>0?n.name:"send_email";r.push({code:"email-destination-placeholder",fix:"Set destination_address to a verified Cloudflare Email Routing address.",level:"warn",message:`send_email binding "${s}" has a placeholder destination_address ("${o}").`})}}},de=(t,r)=>{const e=f(t,p);if(!g(e))return;let n;try{n=x(e,"utf8")}catch{return}const o=R(n).filter(s=>G(s.key)&&S(s.value)).map(s=>s.key);o.length>0&&r.push({code:"dev-vars-missing-secret",fix:"Run `lunora dev` to auto-generate secrets, or fill them in by hand.",level:"warn",message:`${p} has unfilled secret value(s): ${o.join(", ")}.`})},ue=(t,r)=>{const{source:e}=K({cwd:t});e===void 0?r.push({code:"admin-token-missing",fix:"Set LUNORA_ADMIN_TOKEN (env or `.dev.vars`) to enable admin RPCs / studio.",level:"info",message:"LUNORA_ADMIN_TOKEN is not set."}):r.push({code:"admin-token-set",level:"pass",message:`LUNORA_ADMIN_TOKEN is set (${z(e)}).`})},fe=async(t,r)=>{try{return await N({projectRoot:t,schemaDir:C(t)})}catch(e){r.push({code:"declared-export-unchecked",fix:"Make sure the worker entry resolves (see `lunora codegen`), then re-run.",level:"warn",message:`could not check whether declared containers/workflows/agents are re-exported by the worker entry: ${e instanceof Error?e.message:String(e)}`});return}},me=(t,r)=>{const e=U(t),n=[...t.containers.map(o=>({...o,kind:"container"})),...t.workflows.map(o=>({...o,kind:"workflow"})),...t.agents.map(o=>({...o,kind:"agent"}))];for(const o of n.filter(s=>s.exported))r.push({code:"declared-export-ok",level:"pass",message:`${o.kind} "${o.exportName}" is exported by the worker entry.`});for(const o of e)r.push({code:"declared-export-missing",fix:`Add \`export * from "./lunora/_generated/${o.module}"\` to your worker entry (or re-run \`vis generate lunora-${o.kind}\`).`,level:"fail",message:`${o.kind} "${o.exportName}" is declared but ${o.className} is not exported by the worker entry.`})},pe=/^[\^~><= ]+/u,ge=/^(?<core>\d+\.\d+\.\d+)(?:-(?<channel>[a-z]+)\.(?<counter>\d+))?$/u,he=t=>{const r=t.replace(pe,"").trim(),e=ge.exec(r);if(!e?.groups)return;const{channel:n,core:o,counter:s}=e.groups;return{channel:n??"",core:o??"",counter:s===void 0?void 0:Number.parseInt(s,10),raw:r}},ve=(t,r)=>{const e=L(t),n=[];for(const[a,l]of Object.entries(e)){if(a!=="lunorash"&&!a.startsWith("@lunora/"))continue;const d=he(l);d&&n.push({name:a,version:d})}if(n.length<2)return;const o=a=>a.map(l=>`${l.name}@${l.version.raw}`).join(", "),s=new Set(n.map(a=>a.version.core)),c=new Set(n.map(a=>a.version.channel));if(s.size>1){r.push({code:"version-skew-cores",fix:'Run `pnpm update "@lunora/*" lunorash` (or `npm`/`yarn` equivalent) so every Lunora package moves to the same release.',level:"warn",message:`Lunora packages span ${String(s.size)} different versions: ${o(n)}.`});return}if(c.size>1){r.push({code:"version-skew-channels",fix:"Pick one channel (all stable, or all alpha/beta) and update the odd package out.",level:"warn",message:`Lunora packages mix release channels (${[...c].map(a=>a===""?"stable":a).join(" + ")}): ${o(n)}.`});return}const i=n.map(a=>a.version.counter).filter(a=>a!==void 0);if(i.length>1){const a=Math.min(...i),l=Math.max(...i);r.push({code:"version-counter-spread",level:"info",message:i.length===n.length&&a===l?`Lunora packages are all at ${[...c][0]??""}.${String(l)}.`:`Lunora pre-release counters span ${String(a)}–${String(l)}: ${o(n)}.`})}},be=[f("@lunora","cli"),"lunorash"],we=(t,r,e)=>{if(r===void 0)return;const n=[];for(const s of be){const c=f(t,"node_modules",s);if(g(c))try{n.push(b(c))}catch{}}if(n.length===0)return;let o;try{o=b(r)}catch{return}n.some(s=>J(s,o))||e.push({code:"cli-shadowed",fix:"Run the project's own CLI: `pnpm exec lunora …` (or `npx lunora …`).",level:"warn",message:`the running lunora (${o}) is not the project's own install (${n.join(", ")}).`})},ke={full:{code:"do-class-budget-full",level:"warn"},near:{code:"do-class-budget-near",level:"warn"},ok:{code:"do-class-budget-ok",level:"pass"},unchecked:{code:"do-class-budget-unchecked",level:"info"}},ye=t=>{const r=new Map,e=(n,o)=>{const s=j(n);s!==void 0&&r.set(s,[...r.get(s)??[],o])};e(t?.account_id,"top level");for(const[n,o]of Object.entries(t?.env??{}))e(o?.account_id,`env.${n}`);return r},_e=async(t,r,e,n)=>{if(($(t)??A)!=="cloudflare")return;const s=j((e.environment??process.env).CLOUDFLARE_ACCOUNT_ID)!==void 0?[]:[...ye(r)],c=s.length===0?[[void 0,[]]]:s,i=await Promise.all(c.map(async([a,l])=>({accountId:a,blocks:l,budget:await M({accountId:a,environment:e.environment,fetch:e.fetch})})));for(const{accountId:a,blocks:l,budget:d}of i)n.push({...ke[d.verdict],message:i.length>1?`account ${String(a)} (${l.join(", ")}): ${d.message}`:d.message,...d.fix===void 0?{}:{fix:d.fix}})},xe={mismatch:{code:"artifacts-jurisdiction-mismatch",level:"fail"},missing:{code:"artifacts-namespace-missing",level:"fail"},ok:{code:"artifacts-jurisdiction-ok",level:"pass"},unchecked:{code:"artifacts-jurisdiction-unchecked",level:"warn"}},$e=async(t,r,e,n,o)=>{if(e===void 0||r===void 0||($(t)??A)!=="cloudflare")return;const s=[["",r],...Object.entries(r.env??{}).map(([a,l])=>[`env.${a}: `,l])],c=new Map;for(const[a,l]of s){const d=l.account_id??r.account_id;for(const u of l.artifacts??[]){const v=`${String(d)}/${String(u?.namespace)}`;typeof u?.binding=="string"&&typeof u.namespace=="string"&&!c.has(v)&&c.set(v,{accountId:d,binding:u.binding,label:a,namespace:u.namespace})}}const i=await Promise.all([...c.values()].map(async({label:a,...l})=>({check:await W({...l,environment:n.environment,fetch:n.fetch,jurisdiction:e}),label:a})));for(const{check:a,label:l}of i)o.push({...xe[a.verdict],message:`${l}${a.message}`,...a.fix===void 0?{}:{fix:a.fix}})},Ae=async t=>{const r=t.cwd??process.cwd(),e=[],{parsed:n,path:o}=ne(r);re(r,n,o,e),oe(r,e),ce(n,e),le(n,e),se(n,e),ae(n,e),Q(n,e),de(r,e),ue(r,e),ve(r,e),ie(r,e),te(r,e),we(r,t.executablePath??process.argv[1],e),Z(r,e);const s=await fe(r,e);s!==void 0&&me(s,e),Y(n,r,s?.usesAi===!0,e),await _e(r,n,t,e),await $e(r,n,s?.jurisdiction,t,e),X(n,s?.usesCimdWorkers===!0,e);const c={fail:0,info:0,pass:0,warn:0};for(const a of e)c[a.level]+=1;const i=c.fail>0?1:0;return{code:i,findings:e,ok:i===0,summary:c}},Re={fail:"FAIL",info:"INFO",pass:"PASS",warn:"WARN"},Se=(t,r)=>{r.info("lunora doctor — project preflight");for(const o of t.findings){const s=`[${Re[o.level]}] ${o.message}`;o.level==="fail"?r.error(s):o.level==="warn"?r.warn(s):r.info(s),o.fix!==void 0&&o.level!=="pass"&&r.info(` fix: ${o.fix}`)}const{fail:e,warn:n}=t.summary;e>0?r.error(`${String(e)} failure(s), ${String(n)} warning(s).`):n>0?r.warn(`0 failures, ${String(n)} warning(s).`):r.success("all checks passed.")},je=async t=>{const{logger:r}=t,e=await Ae({...t});return Se(e,r),e},Ge=H(async({cwd:t,format:r,logger:e})=>{const n=await je({cwd:t,format:r,logger:e});return{code:n.code,data:{findings:n.findings,summary:n.summary}}});export{Ge as execute,Ae as runDoctor,je as runDoctorCommand};
1
+ import{existsSync as g,readFileSync as x,realpathSync as b}from"node:fs";import{join as f}from"node:path";import{readServiceBindings as I,readProjectTarget as $,DEFAULT_TARGET as A}from"@lunora/codegen";import{DEV_VARS_FILE as p,parseDevVariableEntries as R,isPlaceholderValue as S,readProjectDependencies as L,discoverSchemaInfo as O,inferLunoraBindings as N,resolveSchemaDirectory as C}from"@lunora/config";import{GLOBAL_FETCH_STRICTLY_PUBLIC_FLAG as m,resolveObservabilitySampling as E,findWranglerFile as D,readWranglerJsonc as P,validateWranglerProject as T,UNEXPORTED_CLASS_MARKER as w,detectCloudflareCliConfig as F,collectExportGaps as U}from"@lunora/config/cloudflare";import{i as G,m as V,c as B,a as M,b as W}from"../packem_shared/secret-key-Bc77jm1S.mjs";import{r as K,d as z}from"../packem_shared/admin-token-VdUnvnKW.mjs";import{n as j}from"../packem_shared/cloudflare-credentials-lC5JtPLe.mjs";import{d as H}from"../packem_shared/command-CAXl2A1S.mjs";import{i as J}from"../packem_shared/path-containment-CgxYZggb.mjs";import{b as k,c as y,a as h}from"../packem_shared/variables-acxcvVQa.mjs";const q=(t,r)=>{const e=new Set,n=s=>{for(const[c,i]of Object.entries(s??{}))typeof i=="string"&&i.trim().length>0&&e.add(c)};n(t.vars);for(const s of Object.values(t.env??{}))n(s.vars);const o=f(r,p);if(g(o))try{n(Object.fromEntries(R(x(o,"utf8")).map(s=>[s.key,s.value])))}catch{}return e},Y=(t,r,e,n)=>{if(t===void 0||!e)return;const o=q(t,r),s=o.has(k),c=t.ai?.binding;!s&&(typeof c!="string"||c.length===0)&&n.push({code:"ai-binding-missing",fix:`Run \`lunora dev\` (it adds the binding), add \`"ai": { "binding": "AI" }\` to wrangler.jsonc, or set ${k} to an OpenAI-compatible proxy.`,level:"warn",message:"the project uses ctx.ai (@lunora/ai / env.AI) but wrangler.jsonc declares no `ai` binding — model calls will fail at runtime."}),o.has(y)&&n.push({code:"ai-gateway-token-unused",fix:"Make the gateway unauthenticated for ctx.ai, or remove the token. A bring-your-own AI SDK provider built with `resolveAiGateway` does send it.",level:"warn",message:`${y} is set, but ctx.ai's Workers AI binding cannot send a gateway token — it is ignored on that path.`}),!s&&!o.has(h)&&n.push({code:"ai-gateway-default",fix:`Run \`lunora ai gateway\` to create a gateway for this app and write ${h} into wrangler vars.`,level:"info",message:`no ${h} in vars or ${p} — \`<provider>/<model>\` slugs route through the account's \`default\` AI Gateway.`})},X=(t,r,e)=>{if(t===void 0||!r)return;const n=[];(t.compatibility_flags??[]).includes(m)||n.push("the top level");for(const[o,s]of Object.entries(t.env??{}))s.compatibility_flags!==void 0&&!s.compatibility_flags.includes(m)&&n.push(`env.${o}`);n.length>0&&e.push({code:"cimd-fetch-not-strictly-public",fix:`Add "${m}" to "compatibility_flags" in wrangler.jsonc.`,level:"warn",message:`@lunora/auth/cimd/workers is imported, but ${n.join(", ")} of wrangler.jsonc lacks the ${m} compatibility flag — workersCimdFetch() refuses to build without it.`})},_=t=>{const{logs:r,traces:e}=E(t);return Object.entries({logs:r,traces:e}).filter(([,n])=>n.enabled&&n.headSamplingRate>=1).map(([n])=>n)},Q=(t,r)=>{if(t===void 0)return;const e=[],n=_(t.observability);n.length>0&&e.push(`${n.join(" + ")} (top level)`);for(const[o,s]of Object.entries(t.env??{})){if(s.observability===void 0)continue;const c=_(s.observability);c.length>0&&e.push(`${c.join(" + ")} (env.${o})`)}e.length!==0&&r.push({code:"observability-full-sampling",fix:"For a high-traffic Worker, lower head_sampling_rate in wrangler.jsonc: under observability for logs, under observability.traces for traces — e.g. 0.1 keeps 10% of requests. Lunora never changes a rate you set.",level:"info",message:`observability samples every request (head_sampling_rate 1) for ${e.join(", ")}. From 2026-12-01 Workers Observability is billed: Free caps ingestion at 0.5 GB/day; Paid includes 50 GB per billing cycle, then $0.25/GB.`})},Z=(t,r)=>{for(const e of I(t).services)for(const n of e.publicScopes){const o=n===""?"":` (env.${n})`;r.push({code:"service-workers-dev",fix:`If ${e.name} has no public route (custom domain or route, including ones set outside ${e.wranglerPath}), set \`"workers_dev": false\`${o}. Keep its internal auth (HMAC) either way.`,level:"warn",message:`service ${e.name} (${e.worker}) has no route in its wrangler config and still serves on workers.dev${o}; a custom domain set elsewhere would also be public.`})}},ee=t=>{const r=t.trim();if(r==="")return!0;const e=r.toLowerCase();return e.includes("replace")||e.startsWith("<")&&e.endsWith(">")},ne=t=>{const r=D(t);if(r===void 0)return{parsed:void 0,path:void 0};const{parsed:e}=P(r);return{parsed:e,path:r}},re=(t,r,e,n)=>{if(e===void 0){n.push({code:"wrangler-missing",fix:"Run `lunora init` (or `lunora dev`) to scaffold and reconcile wrangler.jsonc.",level:"fail",message:"wrangler.jsonc not found."});return}if(r===void 0){n.push({code:"wrangler-unparseable",fix:`Check ${e} is valid JSONC.`,level:"fail",message:`Could not parse ${e}.`});return}const{report:o}=T({projectRoot:t});for(const i of o.errors.filter(a=>a.includes(w)))n.push({code:"wrangler-class-unexported",level:"fail",message:i});for(const i of o.warnings.filter(a=>a.includes("LUNORA_ORIGIN_URL")))n.push({code:"scheduler-origin-missing",fix:"Set LUNORA_ORIGIN_URL in wrangler vars to the worker's public URL (or `wrangler secret put LUNORA_ORIGIN_URL`).",level:"warn",message:i});const s=i=>i.includes(w)||i.includes("SHARD");for(const i of o.errors.filter(a=>!s(a)))n.push({code:"wrangler-invalid",fix:"Fix the reported wrangler.jsonc problem; `lunora verify` reports the same set.",level:"fail",message:i});for(const i of o.warnings.filter(a=>!a.includes("LUNORA_ORIGIN_URL")))n.push({code:"wrangler-advisory",level:"warn",message:i});const c=o.errors.find(i=>i.includes("SHARD"));c===void 0?n.push({code:"wrangler-shard-binding-ok",level:"pass",message:"wrangler.jsonc present with a SHARD durable-object binding."}):n.push({code:"wrangler-shard-binding-missing",fix:"Run `lunora dev` to auto-reconcile, or add the binding manually.",level:"fail",message:c})},te=(t,r)=>{g(f(t,"lunora.json"))&&r.push({code:"stale-lunora-json",fix:'Move `target` / `remote` into `lunora.config.ts` (`export default { target: "…" }`), then delete lunora.json.',level:"warn",message:"lunora.json is present but no longer read — lunora.config.* replaced it, so any `target` or `remote` in it is being ignored."})},oe=(t,r)=>{const e=F(t);e!==void 0&&r.push({code:"cf-config-present",fix:e.fix,level:"warn",message:e.message})},se=(t,r)=>{t===void 0||t.limits?.cpu_ms!==void 0||r.push({code:"cpu-limit-missing",fix:'Add `"limits": { "cpu_ms": 30000 }` to wrangler.jsonc, tuned to your slowest legitimate handler.',level:"info",message:"no limits.cpu_ms is set — a runaway handler can burn CPU up to the platform default before anything stops it."})},ae=(t,r)=>{const e=(t?.r2_buckets??[]).map(n=>n?.bucket_name).filter(n=>typeof n=="string"&&n.length>0);e.length!==0&&r.push({code:"r2-lifecycle-unset",fix:"wrangler r2 bucket lifecycle list <bucket> — add an abort-incomplete-multipart rule if none exists.",level:"info",message:`R2 bucket(s) ${e.join(", ")}: verify a lifecycle rule aborts incomplete multipart uploads — orphaned parts are billed but invisible in a listing.`})},ie=(t,r)=>{const{error:e,info:n}=O(t,"lunora");if(e!==void 0){r.push({code:"schema-unreadable",fix:"Fix the parse error, then re-run `lunora doctor`. `lunora codegen` reports the same failure with the offending source.",level:"fail",message:`lunora/schema.ts could not be parsed, so every schema-derived check was skipped: ${e}`});return}for(const o of n?.vectorMetadata??[]){const s=V(o.kind);if(s===void 0){r.push({code:"vector-metadata-unfilterable",fix:"Filter on a string, number or boolean column, or drop it from `metadata`.",level:"warn",message:`vector index "${o.index}" declares metadata "${o.property}", whose type Vectorize cannot filter on.`});continue}r.push({code:"vector-metadata-index-required",fix:`wrangler ${B({index:o.index,property:o.property,type:s}).join(" ")}`,level:"info",message:`vector index "${o.index}" filters on metadata "${o.property}" — that needs a Vectorize metadata index (\`lunora deploy\` creates it).`})}},ce=(t,r)=>{if(t===void 0)return;const e=(t.d1_databases??[]).filter(Boolean);for(const n of e){const o=typeof n.database_id=="string"?n.database_id:"";if(ee(o)){const s=typeof n.binding=="string"&&n.binding.length>0?n.binding:"<unnamed>";r.push({code:"d1-placeholder-id",fix:"Run `wrangler d1 create <name>` and paste the returned database_id into wrangler.jsonc.",level:"fail",message:`D1 binding "${s}" has a placeholder database_id ("${o||"<empty>"}").`})}}},le=(t,r)=>{if(t===void 0)return;const e=(t.send_email??[]).filter(Boolean);for(const n of e){const o=typeof n.destination_address=="string"?n.destination_address:"";if(o!==""&&S(o)){const s=typeof n.name=="string"&&n.name.length>0?n.name:"send_email";r.push({code:"email-destination-placeholder",fix:"Set destination_address to a verified Cloudflare Email Routing address.",level:"warn",message:`send_email binding "${s}" has a placeholder destination_address ("${o}").`})}}},de=(t,r)=>{const e=f(t,p);if(!g(e))return;let n;try{n=x(e,"utf8")}catch{return}const o=R(n).filter(s=>G(s.key)&&S(s.value)).map(s=>s.key);o.length>0&&r.push({code:"dev-vars-missing-secret",fix:"Run `lunora dev` to auto-generate secrets, or fill them in by hand.",level:"warn",message:`${p} has unfilled secret value(s): ${o.join(", ")}.`})},ue=(t,r)=>{const{source:e}=K({cwd:t});e===void 0?r.push({code:"admin-token-missing",fix:"Set LUNORA_ADMIN_TOKEN (env or `.dev.vars`) to enable admin RPCs / studio.",level:"info",message:"LUNORA_ADMIN_TOKEN is not set."}):r.push({code:"admin-token-set",level:"pass",message:`LUNORA_ADMIN_TOKEN is set (${z(e)}).`})},fe=async(t,r)=>{try{return await N({projectRoot:t,schemaDir:C(t)})}catch(e){r.push({code:"declared-export-unchecked",fix:"Make sure the worker entry resolves (see `lunora codegen`), then re-run.",level:"warn",message:`could not check whether declared containers/workflows/agents are re-exported by the worker entry: ${e instanceof Error?e.message:String(e)}`});return}},me=(t,r)=>{const e=U(t),n=[...t.containers.map(o=>({...o,kind:"container"})),...t.workflows.map(o=>({...o,kind:"workflow"})),...t.agents.map(o=>({...o,kind:"agent"}))];for(const o of n.filter(s=>s.exported))r.push({code:"declared-export-ok",level:"pass",message:`${o.kind} "${o.exportName}" is exported by the worker entry.`});for(const o of e)r.push({code:"declared-export-missing",fix:`Add \`export * from "./lunora/_generated/${o.module}"\` to your worker entry (or re-run \`vis generate lunora-${o.kind}\`).`,level:"fail",message:`${o.kind} "${o.exportName}" is declared but ${o.className} is not exported by the worker entry.`})},pe=/^[\^~><= ]+/u,ge=/^(?<core>\d+\.\d+\.\d+)(?:-(?<channel>[a-z]+)\.(?<counter>\d+))?$/u,he=t=>{const r=t.replace(pe,"").trim(),e=ge.exec(r);if(!e?.groups)return;const{channel:n,core:o,counter:s}=e.groups;return{channel:n??"",core:o??"",counter:s===void 0?void 0:Number.parseInt(s,10),raw:r}},ve=(t,r)=>{const e=L(t),n=[];for(const[a,l]of Object.entries(e)){if(a!=="lunorash"&&!a.startsWith("@lunora/"))continue;const d=he(l);d&&n.push({name:a,version:d})}if(n.length<2)return;const o=a=>a.map(l=>`${l.name}@${l.version.raw}`).join(", "),s=new Set(n.map(a=>a.version.core)),c=new Set(n.map(a=>a.version.channel));if(s.size>1){r.push({code:"version-skew-cores",fix:'Run `pnpm update "@lunora/*" lunorash` (or `npm`/`yarn` equivalent) so every Lunora package moves to the same release.',level:"warn",message:`Lunora packages span ${String(s.size)} different versions: ${o(n)}.`});return}if(c.size>1){r.push({code:"version-skew-channels",fix:"Pick one channel (all stable, or all alpha/beta) and update the odd package out.",level:"warn",message:`Lunora packages mix release channels (${[...c].map(a=>a===""?"stable":a).join(" + ")}): ${o(n)}.`});return}const i=n.map(a=>a.version.counter).filter(a=>a!==void 0);if(i.length>1){const a=Math.min(...i),l=Math.max(...i);r.push({code:"version-counter-spread",level:"info",message:i.length===n.length&&a===l?`Lunora packages are all at ${[...c][0]??""}.${String(l)}.`:`Lunora pre-release counters span ${String(a)}–${String(l)}: ${o(n)}.`})}},be=[f("@lunora","cli"),"lunorash"],we=(t,r,e)=>{if(r===void 0)return;const n=[];for(const s of be){const c=f(t,"node_modules",s);if(g(c))try{n.push(b(c))}catch{}}if(n.length===0)return;let o;try{o=b(r)}catch{return}n.some(s=>J(s,o))||e.push({code:"cli-shadowed",fix:"Run the project's own CLI: `pnpm exec lunora …` (or `npx lunora …`).",level:"warn",message:`the running lunora (${o}) is not the project's own install (${n.join(", ")}).`})},ke={full:{code:"do-class-budget-full",level:"warn"},near:{code:"do-class-budget-near",level:"warn"},ok:{code:"do-class-budget-ok",level:"pass"},unchecked:{code:"do-class-budget-unchecked",level:"info"}},ye=t=>{const r=new Map,e=(n,o)=>{const s=j(n);s!==void 0&&r.set(s,[...r.get(s)??[],o])};e(t?.account_id,"top level");for(const[n,o]of Object.entries(t?.env??{}))e(o?.account_id,`env.${n}`);return r},_e=async(t,r,e,n)=>{if(($(t)??A)!=="cloudflare")return;const s=j((e.environment??process.env).CLOUDFLARE_ACCOUNT_ID)!==void 0?[]:[...ye(r)],c=s.length===0?[[void 0,[]]]:s,i=await Promise.all(c.map(async([a,l])=>({accountId:a,blocks:l,budget:await M({accountId:a,environment:e.environment,fetch:e.fetch})})));for(const{accountId:a,blocks:l,budget:d}of i)n.push({...ke[d.verdict],message:i.length>1?`account ${String(a)} (${l.join(", ")}): ${d.message}`:d.message,...d.fix===void 0?{}:{fix:d.fix}})},xe={mismatch:{code:"artifacts-jurisdiction-mismatch",level:"fail"},missing:{code:"artifacts-namespace-missing",level:"fail"},ok:{code:"artifacts-jurisdiction-ok",level:"pass"},unchecked:{code:"artifacts-jurisdiction-unchecked",level:"warn"}},$e=async(t,r,e,n,o)=>{if(e===void 0||r===void 0||($(t)??A)!=="cloudflare")return;const s=[["",r],...Object.entries(r.env??{}).map(([a,l])=>[`env.${a}: `,l])],c=new Map;for(const[a,l]of s){const d=l.account_id??r.account_id;for(const u of l.artifacts??[]){const v=`${String(d)}/${String(u?.namespace)}`;typeof u?.binding=="string"&&typeof u.namespace=="string"&&!c.has(v)&&c.set(v,{accountId:d,binding:u.binding,label:a,namespace:u.namespace})}}const i=await Promise.all([...c.values()].map(async({label:a,...l})=>({check:await W({...l,environment:n.environment,fetch:n.fetch,jurisdiction:e}),label:a})));for(const{check:a,label:l}of i)o.push({...xe[a.verdict],message:`${l}${a.message}`,...a.fix===void 0?{}:{fix:a.fix}})},Ae=async t=>{const r=t.cwd??process.cwd(),e=[],{parsed:n,path:o}=ne(r);re(r,n,o,e),oe(r,e),ce(n,e),le(n,e),se(n,e),ae(n,e),Q(n,e),de(r,e),ue(r,e),ve(r,e),ie(r,e),te(r,e),we(r,t.executablePath??process.argv[1],e),Z(r,e);const s=await fe(r,e);s!==void 0&&me(s,e),Y(n,r,s?.usesAi===!0,e),await _e(r,n,t,e),await $e(r,n,s?.jurisdiction,t,e),X(n,s?.usesCimdWorkers===!0,e);const c={fail:0,info:0,pass:0,warn:0};for(const a of e)c[a.level]+=1;const i=c.fail>0?1:0;return{code:i,findings:e,ok:i===0,summary:c}},Re={fail:"FAIL",info:"INFO",pass:"PASS",warn:"WARN"},Se=(t,r)=>{r.info("lunora doctor — project preflight");for(const o of t.findings){const s=`[${Re[o.level]}] ${o.message}`;o.level==="fail"?r.error(s):o.level==="warn"?r.warn(s):r.info(s),o.fix!==void 0&&o.level!=="pass"&&r.info(` fix: ${o.fix}`)}const{fail:e,warn:n}=t.summary;e>0?r.error(`${String(e)} failure(s), ${String(n)} warning(s).`):n>0?r.warn(`0 failures, ${String(n)} warning(s).`):r.success("all checks passed.")},je=async t=>{const{logger:r}=t,e=await Ae({...t});return Se(e,r),e},Ge=H(async({cwd:t,format:r,logger:e})=>{const n=await je({cwd:t,format:r,logger:e});return{code:n.code,data:{findings:n.findings,summary:n.summary}}});export{Ge as execute,Ae as runDoctor,je as runDoctorCommand};
@@ -1,4 +1,4 @@
1
- import{V as R}from"../packem_shared/cli-6BRlq6nw.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-DVVI8I8G.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
 
@@ -0,0 +1 @@
1
+ import{d as ne}from"../packem_shared/command-CAXl2A1S.mjs";import{EXIT_CODE as h}from"../packem_shared/EXIT_CODE-D_XCixv8.mjs";import{readProjectTarget as se,DEFAULT_TARGET as ie}from"@lunora/codegen";import{findWranglerFile as ae,readWranglerJsonc as ce}from"@lunora/config/cloudflare";import{r as le}from"../packem_shared/cloudflare-credentials-lC5JtPLe.mjs";import{c as de}from"../packem_shared/cloudflare-rest--YUlUUlB.mjs";import{b as ue}from"../packem_shared/tui-prompts-B3YwUhGw.mjs";const fe=15e3,he="https://api.cloudflare.com/client/v4/graphql",S={analytics:"Account Analytics Read",notificationsRead:"Notifications Read",notificationsWrite:"Notifications Write"},me={auth:h.AUTH,failure:h.FAILURE,"not-found":h.NOT_FOUND,permission:h.PERMISSION,"rate-limited":h.RATE_LIMITED,rejected:h.USAGE,unavailable:h.UNAVAILABLE};class A extends Error{kind;status;constructor(t,r,o){super(t),this.name="CloudflareApiError",this.kind=r,this.status=o}}const pe=e=>e===401?"auth":e===403?"permission":e===404?"not-found":e===429?"rate-limited":e>=500?"unavailable":"rejected",X=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]:[]},ge=9106,be=(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}},q=(e,t,r,o)=>{const n=t===400&&be(r,ge)?"auth":pe(t),s=X(r).join("; ");let i="";return n==="auth"?i=` — check that CLOUDFLARE_API_TOKEN is a valid token; it needs the "${o}" permission on this account`:n==="permission"&&(i=` — the API token needs the "${o}" permission on this account`),new A(`${e} failed (HTTP ${String(t)})${s.length>0?`: ${s}`:""}${i}.`,n,t)},G=(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 A(`${e} failed: ${o}.`,"unavailable")},ye=10,we=e=>{const{accountId:t,token:r}=e,o=e.timeoutMs??fe,n=e.fetch??globalThis.fetch.bind(globalThis),s=async(i,a,c,l)=>{let u;try{u=await de({accountId:t,apiToken:r,fetch:n,init:{method:a,signal:AbortSignal.timeout(o),...l===void 0?{}:{body:JSON.stringify(l)}},path:c})}catch(f){throw G(i,f)}if(!u.ok)throw q(i,u.status,u.text,a==="GET"?S.notificationsRead:S.notificationsWrite);return u.body};return{accountId:t,graphql:async(i,a,c={})=>{let l;try{l=await n(he,{body:JSON.stringify({query:a,variables:c}),headers:{Authorization:`Bearer ${r}`,"Content-Type":"application/json"},method:"POST",signal:AbortSignal.timeout(o)})}catch(f){throw G(i,f)}const u=await l.text();if(!l.ok)throw q(i,l.status,u,S.analytics);try{const f=JSON.parse(u);return{data:f.data??void 0,errors:Array.isArray(f.errors)&&f.errors.length>0?X(u):[]}}catch{throw new A(`${i} failed: the GraphQL API answered with something that is not JSON.`,"unavailable",l.status)}},notifications:async(i,a,c,l)=>(await s(i,a,c,l)).result,notificationsList:async(i,a,c=ye)=>{const l=async u=>{const f=await s(i,"GET",`${a}${a.includes("?")?"&":"?"}page=${String(u)}`),y=Array.isArray(f.result)?f.result:[],p=f.result_info;return typeof p?.total_pages=="number"&&u<p.total_pages&&u<c?[...y,...await l(u+1)]:y};return l(1)}}},v="billing_usage_alert",J={"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,E=e=>typeof e=="object"&&e!==null&&!Array.isArray(e)?e:void 0,k=(e,t)=>{const r=t.toLowerCase(),o=Object.keys(e).find(n=>n.toLowerCase()===r);return o===void 0?void 0:e[o]},N=(e,t)=>{for(const r of t){const o=k(e,r);if(typeof o=="string"&&o.length>0)return o}},$e=e=>{if(typeof e=="string"&&e.length>0)return{id:e,source:"available-alerts"};const t=E(e),r=t===void 0?void 0:N(t,["id","value","key","name"]);if(t===void 0||r===void 0)return;const o=N(t,["description","label","display_name","displayName","name"]);return{id:r,source:"available-alerts",...o===void 0||o===r?{}:{label:o}}},Ae=["AvailableValues","available_values","values","options","enum","choices"],Q=e=>e.map(t=>$e(t)).filter(t=>t!==void 0),Se=e=>N(e,["key","name","filter","id"])!=="product"?[]:Ae.flatMap(t=>{const r=k(e,t);return Array.isArray(r)?Q(r):[]}),U=(e,t,r)=>{if(t>ve)return;if(Array.isArray(e)){for(const n of e)U(n,t+1,r);return}const o=E(e);if(o!==void 0){r.push(...Se(o));for(const[n,s]of Object.entries(o))n.toLowerCase()==="product"&&Array.isArray(s)?r.push(...Q(s)):typeof s=="object"&&s!==null&&U(s,t+1,r)}},Te=e=>{const t=E(e);if(t!==void 0){for(const r of Object.values(t))if(Array.isArray(r)){const o=r.map(n=>E(n)).find(n=>n!==void 0&&k(n,"type")===v);if(o!==void 0)return o}}},Ee=e=>e.filter(t=>t.alert_type===v&&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"})),_e=(e,t,r)=>{const o=Te(e),n=[];o!==void 0&&U(k(o,"filter_options"),0,n);const s=new Map;for(const i of[...n,...Ee(r)])s.has(i.id)||s.set(i.id,i);return{eligible:t?o!==void 0:void 0,products:[...s.values()]}},ke=/[^a-z\d]+/u,Oe=e=>`${e.id} ${e.label??""}`.toLowerCase().split(ke).filter(t=>t.length>0),Ce={"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"]}},Ie=(e,t)=>{const r=Oe(t),o=i=>r.some(a=>a.startsWith(i)),{all:n,none:s=[]}=Ce[e];return n.every(i=>i.some(a=>o(a)))&&!s.some(i=>o(i))},z=(e,t)=>{const r=J[e],o=r===void 0?void 0:t.find(i=>i.id===r);if(o!==void 0)return{product:o,status:"matched"};const n=new Set(Object.values(J)),s=t.filter(i=>!n.has(i.id)&&Ie(e,i));return s.length===1&&s[0]!==void 0?{product:s[0],status:"matched"}:s.length>1?{candidates:s.map(i=>i.id),status:"ambiguous"}:r===void 0?{status:"no-product"}:{product:{id:r,source:"documented"},status:"matched"}},B="workersInvocationsAdaptive",Ne="durableObjectsInvocationsAdaptiveGroups",I="durableObjectsPeriodicGroups",x="d1AnalyticsAdaptiveGroups",$=[{candidates:[{field:"requests",unit:"count"}],dataset:B,filter:"datetime",id:"workers-requests",label:"Workers requests"},{candidates:[{field:"cpuTimeUs",unit:"microseconds"}],dataset:B,filter:"datetime",id:"workers-cpu",label:"Workers CPU time"},{candidates:[{field:"requests",unit:"count"}],dataset:Ne,filter:"date",id:"do-requests",label:"Durable Objects requests"},{candidates:[{field:"activeTime",unit:"unknown"}],dataset:I,filter:"date",id:"do-duration",label:"Durable Objects duration"},{candidates:[{field:"rowsRead",unit:"count"}],dataset:I,filter:"date",id:"do-rows-read",label:"Durable Objects rows read"},{candidates:[{field:"rowsWritten",unit:"count"}],dataset:I,filter:"date",id:"do-rows-written",label:"Durable Objects rows written"},{candidates:[{field:"rowsRead",unit:"count"}],dataset:x,filter:"datetime-hour",id:"d1-rows-read",label:"D1 rows read"},{candidates:[{field:"rowsWritten",unit:"count"}],dataset:x,filter:"datetime-hour",id:"d1-rows-written",label:"D1 rows written"}],W=e=>String(e).padStart(2,"0"),Ue=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())}-${W(s.getUTCMonth()+1)}-${W(s.getUTCDate())}`;return{endDate:n(r),nextStartDate:n(o),startDate:n(t)}},De=(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} }] }`}},Re=e=>`query LunoraTypeFields { __type(name: ${JSON.stringify(e)}) { fields { name type { name ofType { name ofType { name ofType { name } } } } } } }`,Me=e=>{let t=e;for(;t!=null;){if(typeof t.name=="string"&&t.name.length>0)return t.name;t=t.ofType}},Le=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})`,Re(r)).then(s=>{if(s.errors.length>0)throw new A(`Reading the analytics schema failed: ${s.errors.join("; ")}.`,"rejected");const a=s.data?.__type?.fields??[];return new Map(a.map(c=>[c.name,Me(c.type)]))});return t.set(r,n),n}},Z=async(e,t,r)=>{const o=await e(t),[n,...s]=r;if(n===void 0)return o;const i=o.get(n);if(i===void 0)throw new A(`the analytics schema has no \`${n}\` on \`${t}\``,"rejected");return Z(e,i,s)},Pe=e=>e instanceof Error?e.message:String(e),je=async(e,t,r,o,n)=>{const{id:s,label:i}=o;try{const a=await Z(t,r,["viewer","accounts",o.dataset,"sum"]),c=o.candidates.find(g=>a.has(g.field));if(c===void 0){const g=o.candidates.map(d=>`\`${d.field}\``).join(", ");return{id:s,label:i,reason:`\`${o.dataset}.sum\` exposes no ${g} field`,status:"unavailable"}}const l=`query LunoraUsage($accountTag: string) { viewer { accounts(filter: { accountTag: $accountTag }) { ${o.dataset}(limit: 1, filter: ${De(o.filter,n)}) { sum { ${c.field} } } } } }`,u=await e.graphql(`Reading ${i}`,l,{accountTag:e.accountId});if(u.errors.length>0)return{id:s,label:i,reason:u.errors.join("; "),status:"unavailable"};const f=u.data?.viewer?.accounts?.[0]?.[o.dataset],y=Array.isArray(f)?f[0]:void 0,p=y===void 0?0:y.sum?.[c.field];return typeof p!="number"||!Number.isFinite(p)?{id:s,label:i,reason:`the response carried no number for \`${c.field}\``,status:"unavailable"}:{field:`${o.dataset}.sum.${c.field}`,id:s,label:i,status:"ok",unit:c.unit,value:p}}catch(a){return{id:s,label:i,reason:Pe(a),status:"unavailable"}}},Fe=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 $.map(({id:i,label:a})=>({id:i,label:a,reason:s,status:"unavailable"}))}const n=Le(e);return Promise.all($.map(async s=>je(e,n,o,s,t)))},O="Lunora usage: ",qe=3,L="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.",Ge={"do-requests":1e6,"workers-requests":1e7},Je=100,Be=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},xe=(e,t,r)=>{const o=Be(e*t);return o>r?{basis:"history",threshold:o}:{basis:"floor",threshold:r}},D=e=>{const t=e.filters?.product;return Array.isArray(t)?t.filter(r=>typeof r=="string"):[]},We=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},P=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},He=(e,t)=>{const r={};for(const[o,n]of[...Object.entries(e),...Object.entries(t)]){const s=new Set((r[o]??[]).map(i=>i.id));r[o]=[...r[o]??[],...n.filter(i=>!s.has(i.id))]}return Object.fromEntries(Object.entries(r).filter(([,o])=>o.length>0))},_=e=>Object.entries(e).flatMap(([t,r])=>r.map(o=>`${t}:${o.id}`)),Ye=(e,t)=>JSON.stringify(_(e).toSorted((r,o)=>r.localeCompare(o)))===JSON.stringify(_(t).toSorted((r,o)=>r.localeCompare(o))),Ke=(e,t)=>e.enabled===!0&&e.name===t.name&&JSON.stringify(e.filters?.limit)===JSON.stringify(t.filters.limit)&&JSON.stringify(D(e))===JSON.stringify(t.filters.product)&&Ye(P(e),t.mechanisms),Ve=(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},Xe=(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 i=Ge[e];return i===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?{...xe(s,r.multiplier,i),lastMonth:s}:r.allowFloor===!0?{basis:"floor-usage-unavailable",lastMonth:void 0,threshold:i}:{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`}},Qe=(e,t)=>{const r=We(e);if(r===void 0||t===void 0||r<=0||t<=0)return;const o=Math.max(r/t,t/r);return o>=Je?`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},R=e=>`${O}${e}`,ze=(e,t)=>e===void 0?"create":Ke(e,t)?"unchanged":"update",Ze=(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)"}},et=(e,t,r)=>{const{id:o,label:n}=e,s=z(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:i}=s,a=r.find(m=>m.name===R(n)),c=r.find(m=>m.enabled===!0&&m.name?.startsWith(O)!==!0&&D(m).includes(i.id)),l=Xe(o,i,t);if(a===void 0&&c!==void 0){const m=Qe(c,"threshold"in l?l.threshold:void 0);return{kind:"covered",metric:o,reason:`already alerted by the existing policy "${c.name??c.id??"?"}"`,...m===void 0?{}:{warning:m}}}if(!("threshold"in l))return{...l,metric:o};const u=Ve(t.emails,t.webhooks),f=P(a),y=a===void 0||t.replaceRecipients===!0?u:He(f,u),p=new Set(_(f)),g=new Set(_(y)),d={alert_type:v,description:`Managed by \`lunora cloudflare alerts setup\`: ${Ze(l.basis,t.multiplier)}.`,enabled:!0,filters:{limit:[String(l.threshold)],product:[i.id]},mechanisms:y,name:R(n)},w=a===void 0?[]:D(a);return{action:ze(a,d),basis:l.basis,body:d,lastMonth:l.lastMonth,metric:o,...a?.id===void 0?{}:{policyId:a.id},...a!==void 0&&JSON.stringify(w)!==JSON.stringify([i.id])?{previousProduct:w}:{},product:i.id,productSource:i.source,recipients:{added:[...g].filter(m=>!p.has(m)),removed:[...p].filter(m=>!g.has(m))},threshold:l.threshold}},tt=e=>{const t=e.policies.filter(n=>n.alert_type===v),r=new Set($.map(n=>R(n.label))),o={alerts:[],duplicates:[],orphans:t.filter(n=>n.name?.startsWith(O)===!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 $){const s=et(n,e,t);"action"in s?o.alerts.push(s):o.skipped.push(s)}return o},rt="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.",ot="To test a webhook for real, create it in the dashboard (Alerts > Destinations > Webhooks > Create) and finish with Save and Test.",nt="Email destinations cannot be tested at all: Cloudflare offers no test send for them. Check the address on each policy below instead.",H=e=>Array.isArray(e)?e:[],Y=30,st=async(e,t,r,o,n)=>{const s=t.filter(d=>d.alert_type===v&&d.name?.startsWith(O)===!0),i=s.map(d=>P(d)),a=new Set([...i.flatMap(d=>(d.webhooks??[]).map(w=>w.id)),...r]),c=[...new Set(i.flatMap(d=>(d.email??[]).map(w=>w.id)))],l=new Set(s.map(d=>d.id)),u=new Date(n.getTime()-Y*24*60*60*1e3).toISOString(),[f,y]=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(u)}`)]),p=H(f).map(d=>({...d,referenced:d.id!==void 0&&a.has(d.id)})),g=H(y).filter(d=>d.alert_type===v&&d.policy_id!==void 0&&l.has(d.policy_id));o.warn(rt),s.length===0&&o.info("No `lunora cloudflare alerts setup` policies exist on this account yet — run `lunora cloudflare alerts setup` first.");for(const d of[...a].filter(w=>!p.some(m=>m.id===w)))o.warn(`Webhook destination ${d} is referenced but does not exist on this account.`);for(const d of p.filter(w=>w.referenced))o.info(`webhook "${d.name??d.id??"?"}" (${d.type??"generic"}): last delivered ${d.last_success??"never"}, last failed ${d.last_failure??"never"}`);if(o.info(ot),c.length>0&&o.info(`${nt} Addresses on the policies: ${c.join(", ")}.`),g.length===0)o.info(`Cloudflare's notification history shows nothing sent for these policies in the last ${String(Y)} days (they only fire once a threshold is crossed).`);else for(const d of g)o.info(`sent ${d.sent??"?"}: "${d.name??"?"}" via ${d.mechanism_type??"?"} to ${d.mechanism??"?"}`);return{emails:c,history:g,testSent:!1,webhooks:p}},C="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.",it="Alerts > Overview > Create an Alert, alert type Usage Based Billing",b=(e,t,r,o)=>(e.error(r),{code:t,error:r,...o===void 0?{}:{data:o}}),j=(e,t,r)=>{if(t instanceof A)return b(e,me[t.kind],t.message,r);throw t},F=(e,t)=>({accountId:e.accountId,budgetAlert:{checkable:!1,dashboardPath:"Manage Account > Billing > Billable Usage"},limitUnitCaveat:L,...t===void 0?{}:{eligible:t.discovery.eligible,period:t.period,products:t.discovery.products}}),T=e=>e.toLocaleString("en-US",{maximumFractionDigits:0}),ee=(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).")},te=e=>({code:h.SUCCESS,data:e}),at=/^[^\s@]+@[^\s@][^\s.@]*\.[^\s@]+$/u,re=new Set($.map(e=>e.id)),ct=e=>re.has(e),lt=e=>{const t={};for(const r of e.flatMap(o=>o.split(","))){const[o="",n=""]=r.split("=").map(i=>i.trim()),s=Number(n);if(!ct(o))return{error:`--threshold "${r}": unknown metric "${o}" — one of ${[...re].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},dt=e=>{const t=(e.emails??[]).flatMap(i=>i.split(",")).map(i=>i.trim()).filter(i=>i.length>0),r=(e.webhooks??[]).map(i=>i.trim()).filter(i=>i.length>0),o=e.multiplier===void 0?qe:Number(e.multiplier),n=lt(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(i=>!at.test(i));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}},ut={explicit:()=>"set with --threshold",floor:e=>`floor: included monthly allowance; last month ${T(e.lastMonth??0)}`,"floor-usage-unavailable":()=>"floor: usage could not be read, applied with --allow-floor",history:e=>`last month ${T(e.lastMonth??0)}`},ft=e=>{const t=[...e.added.map(r=>`+${r}`),...e.removed.map(r=>`-${r}`)];return t.length===0?"recipients unchanged":`recipients ${t.join(" ")}`},ht=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 ${T(e.threshold)} (${ut[e.basis](e)}); ${ft(e.recipients)}`},M=e=>$.find(t=>t.id===e)?.label??e,mt=(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(` ${ht(n)}`);for(const n of e.skipped)o.info(` skipped ${M(n.metric)} — ${n.reason}`),n.warning!==void 0&&o.warn(`${M(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: ${it}.`),o.info(L),o.info(C)},pt=async(e,t)=>{if(e.yes===!0)return;if(e.confirm===void 0&&(!process.stdin.isTTY||e.format==="json"))return b(e.logger,h.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??ue)(`Apply ${String(t.length)} notification policy change(s)?${o}`))return e.logger.info("alerts setup: aborted"),{code:h.CANCELLED,error:"alerts setup: aborted at the confirmation prompt"}},gt=async(e,t,r,o)=>{const s=(await Promise.all(t.map(async i=>e.notifications(`Reading webhook destination ${i}`,"GET",`/alerting/v3/destinations/webhooks/${encodeURIComponent(i)}`).then(()=>{},a=>({error:a,id:i}))))).find(i=>i!==void 0);if(s!==void 0)return s.error instanceof A&&s.error.kind==="not-found"?b(r,h.USAGE,`--webhook ${s.id}: no such webhook destination on account ${e.accountId}.`,o):j(r,s.error,o)},bt=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},yt=async(e,t,r)=>await Promise.all(t.map(async({alert:n,id:s})=>{try{const i=await e.notifications(`Reading back "${n.body.name}"`,"GET",`/alerting/v3/policies/${encodeURIComponent(s)}`),a={enabled:i?.enabled,id:s,limit:i?.filters?.limit,name:i?.name,product:i?.filters?.product};return r.info(`Cloudflare stored "${a.name??n.body.name}": product ${JSON.stringify(a.product)}, limit ${JSON.stringify(a.limit)}.`),JSON.stringify(a.limit)!==JSON.stringify(n.body.filters.limit)&&r.warn(`"${n.body.name}": Cloudflare stored limit ${JSON.stringify(a.limit)}, not the ${JSON.stringify(n.body.filters.limit)} sent.`),a}catch(i){return r.warn(`Could not read "${n.body.name}" back: ${i instanceof Error?i.message:String(i)}`),{id:s}}})),wt=async(e,t,r,o)=>{const n=[],s=[];let i;for(const c of t)try{const l=await bt(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){i=l;break}const a={...o,applied:n,stored:await yt(e,s,r)};return i===void 0?a:j(r,i,a)},K=(e,t,r)=>{const o=t.skipped.filter(n=>n.kind==="usage-unavailable");return o.length>0?b(r,h.FAILURE,`alerts setup: no alert was set for ${o.map(n=>M(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:h.SUCCESS,data:e}},vt=async(e,t,r,o)=>{const{logger:n}=r,s=F(e,t),i=await gt(e,o.webhooks,n,s);if(i!==void 0)return i;if(t.discovery.eligible===!1)return ee(n,!1),n.info(C),b(n,h.PERMISSION,"alerts setup: the account cannot create Usage Based Billing notifications.",s);const a=tt({...o,policies:t.policies,products:t.discovery.products,usage:t.usage});s.plan=a,mt(a,o.multiplier,t.period,n);const c=a.alerts.filter(f=>f.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."),K(s,a,n);const l=await pt(r,c);if(l!==void 0)return{...l,data:s};const u=await wt(e,c,n,s);return"code"in u?u:K(u,a,n)},$t=e=>e.status!=="ok"?`unavailable (${e.reason})`:e.unit==="microseconds"?`${T(e.value)} µs`:T(e.value),At=(e,t,r)=>t?"no-product":e===void 0?"unknown":r.some(o=>o.enabled)?"active":r.length>0?"disabled-only":"none",V=e=>e.map(t=>`"${t.name??t.id??"?"}" (limit ${JSON.stringify(t.limit)})${t.enabled?"":" — disabled, not protecting you"}`).join(", "),St={active:e=>`alert: ${V(e.alerts)}`,"disabled-only":e=>`alert: none active; ${V(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)"},Tt=(e,t,r)=>{const o=z(e.id,t.discovery.products),n=o.status==="matched"?o.product:void 0,s=(n===void 0?[]:r.filter(i=>Array.isArray(i.filters?.product)&&i.filters.product.includes(n.id))).map(i=>({enabled:i.enabled===!0,id:i.id,limit:i.filters?.limit,name:i.name}));return{alerts:s,coverage:At(n?.id,o.status==="no-product",s),id:e.id,label:e.label,...n===void 0?{}:{product:n.id,productSource:n.source},usage:e}},Et=(e,t,r)=>{const o=t.policies.filter(s=>s.alert_type===v),n=t.usage.map(s=>Tt(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}: ${$t(s.usage)} — ${St[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(L),ee(r,t.discovery.eligible),r.info(C),te({...F(e,t),metrics:n})},_t={celld:"celld",node:"Node"},kt=e=>{const t=ae(e);return t===void 0?void 0:ce(t).parsed?.account_id},Ot=e=>{const t=se(e.cwd)??ie;if(t!=="cloudflare")return b(e.logger,h.USAGE,`this project deploys to ${_t[t]??`"${t}"`} — \`lunora cloudflare alerts\` only applies to Cloudflare accounts.`);const{accountId:r,token:o}=le(e.environment??process.env,kt(e.cwd));return o===void 0?b(e.logger,h.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 "${S.notificationsWrite}" and "${S.analytics}" permissions ("${S.notificationsRead}" is enough for status and test).`):r===void 0?b(e.logger,h.USAGE,"No Cloudflare account: set CLOUDFLARE_ACCOUNT_ID or `account_id` in wrangler.jsonc."):we({accountId:r,token:o,...e.fetch===void 0?{}:{fetch:e.fetch}})},oe=async e=>{const t=await e.notifications("Listing notification policies","GET","/alerting/v3/policies");return Array.isArray(t)?t:[]},Ct=async(e,t)=>{const r=Ue(t.now??new Date),{logger:o}=t,[n,s,i]=await Promise.all([oe(e),e.notifications("Listing the alert types this account is eligible for","GET","/alerting/v3/available_alerts").then(a=>({ok:!0,value:a}),a=>({error:a,ok:!1})),Fe(e,r).catch(a=>{const c=a instanceof Error?a.message:String(a);return o.warn(`Usage could not be read: ${c}`),$.map(({id:l,label:u})=>({id:l,label:u,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:_e(s.ok?s.value:void 0,s.ok,n),period:r,policies:n,usage:i}},It=async(e,t)=>{const r=await oe(e),o=await st(e,r,t.webhooks??[],t.logger,t.now??new Date);return t.logger.info(C),te({...F(e),deliveries:o})},Nt=async e=>{const t=e.subcommand==="setup"?dt(e):void 0;if(t!==void 0&&"error"in t)return b(e.logger,h.USAGE,t.error);const r=Ot(e);if(!("graphql"in r))return r;try{if(e.subcommand==="test")return await It(r,e);const o=await Ct(r,e);return t===void 0?Et(r,o,e.logger):await vt(r,o,e,t)}catch(o){return j(e.logger,o)}},Ut=new Set(["alert","alerts"]),Dt=e=>e==="status"||e==="setup"||e==="test",Gt=ne(async({argument:e,cwd:t,format:r,logger:o,options:n})=>{const[s="",i="status"]=e;return Ut.has(s)?Dt(i)?Nt({allowFloor:n.allowFloor===!0,cwd:t,dryRun:n.dryRun===!0,format:r,logger:o,replaceRecipients:n.replaceRecipients===!0,subcommand:i,yes:n.yes===!0,...n.email===void 0?{}:{emails:n.email},...n.webhook===void 0?{}:{webhooks:n.webhook},...n.multiplier===void 0?{}:{multiplier:n.multiplier},...n.threshold===void 0?{}:{thresholds:n.threshold}}):b(o,h.USAGE,`cloudflare alerts: unknown subcommand "${i}" — expected status | setup | test`):b(o,h.USAGE,`cloudflare: unknown tool "${s}" — expected alerts (lunora cloudflare alerts [status | setup | test])`)});export{Gt as execute};
@@ -1,4 +1,4 @@
1
- import{dirname as F,join as B}from"node:path";import{discoverMigrations as te,readServiceBindings as ne,runCodegen as oe}from"@lunora/codegen";import{readLinkedProject as W,execArgsFor as H,detectPackageManager as b,discoverContainerInfo as V,COMPOSED_WORKER_ENTRY as N,writeLinkedProject as ae,discoverSchemaInfo as G,DEV_VARS_FILE as w,parseDevVariableEntries as K,isMintableSecretKey as I,secretSourcesFromBindings as ie,inferLunoraBindings as q,resolveSchemaDirectory as R,requiredSecrets as se,generateSecretValue as ce,toolchainExecArgs as j,upsertDevVariableLine as de,writeDevVariablesFileAtomically as le,resolveDeployDriver as C,planToolchainInvocation as Y,runPostCodegenHook as ue}from"@lunora/config";import{findWranglerFile as z,readWranglerJsonc as P,mergeWranglerEnvironment as J,warnCloudflareCliConfigOnce as ge,validateWranglerProject as me,wranglerCodegenInputs as fe,reconcileWranglerBindings as ve,reconcileWranglerCompatibilityDate as he,reconcileWranglerCrons as pe,describePreservedCrons as ye}from"@lunora/config/cloudflare";import{Spinner as we}from"@visulima/spinner";import{r as ke,a as be,e as $e}from"../packem_shared/platform-diagnostics-Cn2g6Jh-.mjs";import{p as Se,a as De}from"../packem_shared/deploy-target-DCWwiuAe.mjs";import{mkdirSync as Ee,writeFileSync as x,existsSync as p,readFileSync as k}from"node:fs";import{m as Ae,e as Re,i as je,b as Ce,a as Pe}from"../packem_shared/secret-key-BCrqNJ68.mjs";import{w as xe}from"../packem_shared/binding-manifest-file-CQ1eQYy1.mjs";import{d as _e}from"../packem_shared/command-CAXl2A1S.mjs";import{r as _}from"../packem_shared/wrangler-name-Dsk5K1f-.mjs";import{EXIT_CODE as h}from"../packem_shared/EXIT_CODE-D_XCixv8.mjs";import{containerBuildTag as Te}from"@lunora/container";import{a as Ne,i as Ie}from"../packem_shared/docker-DpVxvYpL.mjs";import{defaultSpawner as D}from"../packem_shared/createRecordingSpawner-Ch7zuQQE.mjs";import{r as X}from"../packem_shared/resolve-target-C_ZloTvd.mjs";import{p as Le,H as Me,a as Ue,r as Oe}from"../packem_shared/health-probe-Bw9JFfIy.mjs";import{join as y}from"@visulima/path";import{Project as Fe}from"ts-morph";import{runMigrateDataCommand as Be}from"../packem_shared/runMigrateGenerateCommand-Ii_WMZEA.mjs";import{c as We}from"../packem_shared/tui-prompts-B3YwUhGw.mjs";import{l as He}from"../packem_shared/wrangler-secrets-3chIVv3H.mjs";const Ve=Object.freeze({edges:[],nodes:[],modules:[],unresolved:[],version:1}),Ge=20,L=e=>`${e.from} -${e.kind}-> ${e.to}`,$=(e,r)=>{const o=new Set(e);return r.filter(t=>!o.has(t)).toSorted((t,n)=>t.localeCompare(n))},Ke=(e,r)=>{const o=e.modules.map(i=>i.name),t=r.modules.map(i=>i.name),n=e.edges.map(i=>L(i)),a=r.edges.map(i=>L(i));return{addedEdges:$(n,a),addedModules:$(o,t),removedEdges:$(a,n),removedModules:$(t,o)}},S=(e,r,o)=>{if(o.length===0)return[];const t=o.slice(0,Ge).map(a=>` ${e} ${a}`),n=o.length-t.length;return[`${r}:`,...t,...n>0?[` … and ${n.toString()} more`]:[]]},qe=e=>{const r=[...S("+","modules added",e.addedModules),...S("-","modules removed",e.removedModules),...S("+","edges added",e.addedEdges),...S("-","edges removed",e.removedEdges)];return r.length===0?void 0:`architecture changes since the last deploy:
1
+ import{dirname as F,join as B}from"node:path";import{discoverMigrations as te,readServiceBindings as ne,runCodegen as oe}from"@lunora/codegen";import{readLinkedProject as W,execArgsFor as H,detectPackageManager as b,discoverContainerInfo as V,COMPOSED_WORKER_ENTRY as N,writeLinkedProject as ae,discoverSchemaInfo as G,DEV_VARS_FILE as w,parseDevVariableEntries as K,isMintableSecretKey as I,secretSourcesFromBindings as ie,inferLunoraBindings as q,resolveSchemaDirectory as R,requiredSecrets as se,generateSecretValue as ce,toolchainExecArgs as j,upsertDevVariableLine as de,writeDevVariablesFileAtomically as le,resolveDeployDriver as C,planToolchainInvocation as Y,runPostCodegenHook as ue}from"@lunora/config";import{findWranglerFile as z,readWranglerJsonc as P,mergeWranglerEnvironment as J,warnCloudflareCliConfigOnce as ge,validateWranglerProject as me,wranglerCodegenInputs as fe,reconcileWranglerBindings as ve,reconcileWranglerCompatibilityDate as he,reconcileWranglerCrons as pe,describePreservedCrons as ye}from"@lunora/config/cloudflare";import{Spinner as we}from"@visulima/spinner";import{r as ke,a as be,e as $e}from"../packem_shared/platform-diagnostics-Cn2g6Jh-.mjs";import{p as Se,a as De}from"../packem_shared/deploy-target-DCWwiuAe.mjs";import{mkdirSync as Ee,writeFileSync as x,existsSync as p,readFileSync as k}from"node:fs";import{m as Ae,e as Re,i as je,b as Ce,a as Pe}from"../packem_shared/secret-key-Bc77jm1S.mjs";import{w as xe}from"../packem_shared/binding-manifest-file-CQ1eQYy1.mjs";import{d as _e}from"../packem_shared/command-CAXl2A1S.mjs";import{r as _}from"../packem_shared/wrangler-name-Dsk5K1f-.mjs";import{EXIT_CODE as h}from"../packem_shared/EXIT_CODE-D_XCixv8.mjs";import{containerBuildTag as Te}from"@lunora/container";import{a as Ne,i as Ie}from"../packem_shared/docker-DpVxvYpL.mjs";import{defaultSpawner as D}from"../packem_shared/createRecordingSpawner-Ch7zuQQE.mjs";import{r as X}from"../packem_shared/resolve-target-C_ZloTvd.mjs";import{p as Le,H as Me,a as Ue,r as Oe}from"../packem_shared/health-probe-Bw9JFfIy.mjs";import{join as y}from"@visulima/path";import{Project as Fe}from"ts-morph";import{runMigrateDataCommand as Be}from"../packem_shared/runMigrateGenerateCommand-Ii_WMZEA.mjs";import{c as We}from"../packem_shared/tui-prompts-B3YwUhGw.mjs";import{l as He}from"../packem_shared/wrangler-secrets-3chIVv3H.mjs";const Ve=Object.freeze({edges:[],nodes:[],modules:[],unresolved:[],version:1}),Ge=20,L=e=>`${e.from} -${e.kind}-> ${e.to}`,$=(e,r)=>{const o=new Set(e);return r.filter(t=>!o.has(t)).toSorted((t,n)=>t.localeCompare(n))},Ke=(e,r)=>{const o=e.modules.map(i=>i.name),t=r.modules.map(i=>i.name),n=e.edges.map(i=>L(i)),a=r.edges.map(i=>L(i));return{addedEdges:$(n,a),addedModules:$(o,t),removedEdges:$(a,n),removedModules:$(t,o)}},S=(e,r,o)=>{if(o.length===0)return[];const t=o.slice(0,Ge).map(a=>` ${e} ${a}`),n=o.length-t.length;return[`${r}:`,...t,...n>0?[` … and ${n.toString()} more`]:[]]},qe=e=>{const r=[...S("+","modules added",e.addedModules),...S("-","modules removed",e.removedModules),...S("+","edges added",e.addedEdges),...S("-","edges removed",e.removedEdges)];return r.length===0?void 0:`architecture changes since the last deploy:
2
2
  ${r.join(`
3
3
  `)}`},Ye=(e,r)=>B(e,".lunora",r===void 0?"architecture.json":`architecture.${r}.json`),ze=e=>{if(p(e))try{const r=JSON.parse(k(e,"utf8"));return r.version===1&&Array.isArray(r.modules)&&Array.isArray(r.edges)?r:void 0}catch{return}},Je=e=>{const{cwd:r,environment:o,logger:t}=e,n=Ye(r,o),a=ze(n),i=e.current??(a===void 0?void 0:Ve);if(i===void 0)return;const s=a===void 0?void 0:qe(Ke(a,i));return s!==void 0&&t.info(s),()=>{try{Ee(F(n),{recursive:!0}),x(n,`${JSON.stringify(i,void 0,2)}
4
4
  `,"utf8")}catch(c){t.warn(`could not record the deployed architecture at ${n}: ${c instanceof Error?c.message:String(c)}`)}}},Xe=e=>{const{cwd:r,env:o,logger:t,mintedSecretsFile:n}=e;try{const a=W(r),i=a?.workerName??_(r),s=e.url??a?.workerUrl;t.success("deploy complete"),t.info(` worker: ${i??"(see wrangler output above)"}`),o!==void 0&&t.info(` env: ${o}`),s===void 0?t.info(" url: run `lunora link --url <https://your-worker>` to record it"):t.info(` url: ${s}`),n!==void 0&&t.info(` secrets: generated value(s) recorded in ${n}`),e.logsAvailable&&t.info(" logs: lunora logs")}catch{}},Qe=async e=>{if(e.targets.length===0)return{builtTags:[],code:0};if(!(e.railpackAvailable??Ne)()){const t="deploy blocked: a container uses `image: { build }` (Railpack), but Railpack isn't ready. Install the `railpack` CLI and start a BuildKit instance, e.g. `docker run --rm --privileged -d --name buildkit moby/buildkit` then `export BUILDKIT_HOST=docker-container://buildkit`. Alternatively switch the container's `image` to a Dockerfile path or a pre-built registry reference.";return e.logger.error(t),{builtTags:[],code:1,error:t}}const r=e.spawner??D,o=[];for(const t of e.targets){const n=Te(t.exportName),a={args:["build",t.buildDir,"--name",n],command:"railpack",cwd:e.cwd},i=H(b(e.cwd),"wrangler",["containers","push",n]),s={args:i.args,command:i.command,cwd:e.cwd};e.logger.info(`railpack: building "${t.exportName}" → ${n} from ${t.buildDir}`);const c=await r(a);if(c.code!==0){const d=`railpack build failed for container "${t.exportName}" (${t.buildDir})`;return e.logger.error(d),{builtTags:o,code:c.code,error:d}}e.logger.info(`railpack: pushing ${n} to the Cloudflare Registry`);const l=await r(s);if(l.code!==0){const d=`wrangler containers push failed for "${t.exportName}" (${n})`;return e.logger.error(d),{builtTags:o,code:l.code,error:d}}o.push(n)}return{builtTags:o,code:0}},Ze=e=>{const o=[z(e),B(e,"package.json")].filter(t=>t!==void 0&&p(t)).map(t=>[t,k(t,"utf8")]);return()=>{for(const[t,n]of o)k(t,"utf8")!==n&&x(t,n,"utf8")}},Q="<replace-with-d1-create-id>",M=e=>Array.isArray(e)?e.filter(r=>r!=null):void 0,T=(e,r)=>{const o=z(e);if(!o)return;const{parsed:t}=P(o);if(t===void 0)return;const{error:n,merged:a}=J(t,r),i=n===void 0?a:t,{containers:s,d1_databases:c,vars:l}=i;return{containers:M(s),d1_databases:M(c),vars:typeof l=="object"&&l!==null&&!Array.isArray(l)?l:void 0}},er=/^127(?:\.\d{1,3}){3}$/,rr=e=>{try{const{hostname:r}=new URL(e);return r==="localhost"||er.test(r)||r==="::1"||r==="[::1]"}catch{return!1}},tr=e=>e.startsWith("./")||e.startsWith("../")||e.startsWith("/")||e.includes("Dockerfile"),nr=(e,r,o,t="deploy",n)=>{const a=(T(e,n)?.containers??[]).filter(s=>typeof s?.image=="string"&&tr(s.image));if(a.length===0||o())return;const i=`${t} blocked: wrangler.jsonc declares ${String(a.length)} container(s) built from a local Dockerfile, but no Docker-compatible engine is available. Start Docker (or Colima), or point the container's \`image\` at a pre-built registry reference. Note: container images must target linux/amd64.`;return r.error(i),i},Z=e=>p(y(e,N))?N:void 0,or=(e,r,o="deploy")=>{for(const t of V(e,"lunora").containers){const n=t.schedulingPolicy===void 0?t.image:void 0,i=[...n?.kind==="dockerfile"?[{field:"image",path:n.dockerfilePath}]:[],...Object.entries(t.schedulingPolicy==="durable_object"?t.images??{}:{}).flatMap(([s,c])=>c.kind==="dockerfile"?[{field:`images["${s}"]`,path:c.dockerfilePath}]:[])].find(s=>!p(y(e,s.path)));if(i!==void 0){const s=`${o} blocked: container "${t.exportName}" references a Dockerfile at "${i.path}" that does not exist. Create it or fix the \`${i.field}\` path in lunora/containers.ts.`;return r.error(s),s}if(n?.kind==="build"&&!p(y(e,n.buildDir))){const s=`${o} blocked: container "${t.exportName}" references a Railpack build directory "${n.buildDir}" that does not exist. Create it or fix the \`image.build\` path in lunora/containers.ts.`;return r.error(s),s}}},ar=(e,r)=>(T(e,r)?.d1_databases??[]).find(o=>o.database_id===Q)?.binding,ir=e=>{if(!e.migrate||e.dryRun||e.preview)return;if(e.migrateUrl===void 0){const o="--migrate requires --migrate-url <https://your-worker> — the deploy target URL is only known after wrangler runs, and this gate runs before it; refusing to default to localhost";return e.logger.error(o),o}if(e.migrateYes!==!0){const o="--migrate runs production data migrations after deploy. Re-run with --migrate-yes to confirm.";return e.logger.error(o),o}const r=e.migrateToken??process.env.LUNORA_ADMIN_TOKEN;if(r===void 0||r===""){const o="admin token required for --migrate — pass --migrate-token or set LUNORA_ADMIN_TOKEN";return e.logger.error(o),o}},sr=(e,r,o="deploy",t)=>{const n=ar(e,t);if(n===void 0)return;const a=`${o} blocked: the "${n}" D1 binding has a placeholder database_id ("${Q}"). Run \`wrangler d1 create <name>\` to create the database, then replace the placeholder in wrangler.jsonc with the real id before deploying.`;return r.error(a),a},cr=(e,r,o="deploy",t)=>{const n=T(e,t)?.vars;if(!n)return;const a=Object.entries(n).filter(([,s])=>typeof s=="string"&&rr(s)).map(([s])=>s).toSorted((s,c)=>s.localeCompare(c));if(a.length===0)return;const i=`${o} blocked: ${a.join(", ")} in wrangler.jsonc point at localhost. A deployed Worker can't reach a loopback address, so this silently breaks scheduled-job dispatch, reverse cross-shard relations, and auth callbacks. Set each to the deployed worker's public URL (or move it to a secret with \`wrangler secret put\`) before deploying.`;return r.error(i),i},dr=(e,r,o)=>{const t=sr(e,r.logger,o,r.env);if(t!==void 0)return{code:h.USAGE,error:t};const n=cr(e,r.logger,o,r.env);if(n!==void 0)return{code:h.USAGE,error:n};const a=or(e,r.logger,o);if(a!==void 0)return{code:h.USAGE,error:a};const i=nr(e,r.logger,r.dockerAvailable??Ie,o,r.env);return i===void 0?void 0:{code:h.MISSING_DEPENDENCY,error:i}},lr=/https?:\/\/[^\s"'<>]+\.workers\.dev[^\s"'<>]*/u,ur=/https:\/\/[^\s"'<>]+/u,gr=e=>{if(e===void 0)return;const r=lr.exec(e);return r?r[0]:ur.exec(e)?.[0]},U=e=>e===void 0?"":` (--env ${e})`,mr=({cwd:e,env:r,logger:o,now:t,url:n})=>{if(n!==void 0)try{const a=W(e);if(a!==void 0){if(a.workerUrl===n&&a.env===r)return;o.warn(`link: .lunora/project.json records ${a.workerUrl??"(no url)"}${U(a.env)}, but this deploy published ${n}${U(r)}. Keeping the recorded value — run \`lunora link --url ${n}${r===void 0?"":` --env ${r}`}\` to update it.`);return}const i=(t??(()=>new Date().toISOString()))();ae(e,{env:r,linkedAt:i,workerName:_(e),workerUrl:n}),o.success(`link: recorded ${n} in .lunora/project.json (run \`lunora link\` to change)`)}catch{}},fr=async(e,r)=>{const o=new Fe({skipAddingFilesFromTsConfig:!0}),t=y(r,"lunora");let n;try{n=te(o,t)}catch(a){const i=a instanceof Error?a.message:String(a);return e.logger.warn(`--migrate: could not discover migrations (${i}); skipping`),0}if(n.length===0)return e.logger.info("--migrate: no data migrations declared in lunora/"),0;e.logger.info(`--migrate: running ${String(n.length)} migration(s) against deployed worker`);for(const a of n){e.logger.info(`--migrate: up "${a.id}" (table "${a.table}")`);const i={cwd:r,fetchImpl:e.fetchImpl,id:a.id,logger:e.logger,prod:!0,subcommand:"up",token:e.migrateToken,url:e.migrateUrl,yes:e.migrateYes===!0},s=await Be(i);if(s.code!==0)return e.logger.error(`--migrate: migration "${a.id}" failed — see output above`),s.code;e.logger.success(`--migrate: "${a.id}" applied`)}return 0},vr=async(e,r)=>{const{info:o}=G(r,"lunora"),t=o?.vectorMetadata??[];if(t.length===0)return;const n=[];for(const s of t){const c=Ae(s.kind);if(c===void 0){e.logger.warn(`vector index "${s.index}" declares metadata "${s.property}", whose column type cannot be filtered on in Vectorize — it is stored with each vector but no filter will match it.`);continue}n.push({index:s.index,property:s.property,type:c})}if(n.length===0)return;const i=(await Re({cwd:r,entries:n,exec:H(b(r),"wrangler",[]),logger:e.logger,spawner:e.spawner??D})).filter(s=>s.status!=="failed").length;i>0&&e.logger.success(`vectorize metadata indexes ready: ${String(i)}/${String(n.length)}`)},O=5,hr=2e3,pr=async(e,r,o)=>{if(e.healthCheck!==!0)return;const t=o??X({cwd:r,env:e.env});if(t===void 0){const a="--health-check: the deploy succeeded, but no URL to probe could be resolved — wrangler's output carried none and this checkout has no link for this environment. Run `lunora link --url <https://your-worker>` and re-deploy, or drop --health-check.";return e.logger.error(a),{error:a,ok:!1,url:""}}const n=await Le({attempts:O,baseUrl:t,delayMs:hr,fetchImpl:e.healthFetch,paths:[Me,Ue],sleep:e.healthSleep});return n.error===void 0?(e.logger.success(`health check ok (${n.url})`),{ok:!0,url:n.url}):(e.logger.error(`--health-check: the deploy succeeded, but the new version did not answer after ${String(O)} attempt(s) — ${n.error}`),{error:n.error,ok:!1,url:n.url})},yr=async(e,r,o,t,n,a)=>{await vr(e,r);const i=e.migrate?await fr(e,r):0;return i===0&&n?.(),{code:i,descriptor:o,mintedSecretsFile:a,validation:t}},wr=async({cwd:e,descriptor:r,mintedSecretsFile:o,options:t,reblessSchemaBaseline:n,recordArchitecture:a,stdout:i,validation:s})=>{const c={deployedAt:new Date().toISOString(),dryRun:t.dryRun===!0,env:t.env,preview:t.preview===!0,url:t.dryRun===!0?void 0:gr(i),workerName:_(e)};if(t.dryRun===!0||t.preview===!0)return t.healthCheck===!0&&t.logger.warn(`--health-check skipped: ${t.dryRun===!0?"a dry run publishes nothing":"a preview version serves no live traffic"}`),{code:0,deployment:c,descriptor:r,mintedSecretsFile:o,validation:s};t.temporary!==!0&&(a?.(),mr({cwd:e,env:t.env,logger:t.logger,url:c.url}));const l=await pr(t,e,c.url);return l?.error!==void 0?{code:h.UNAVAILABLE,deployment:c,descriptor:r,healthCheck:l,mintedSecretsFile:o,validation:s}:{...await yr(t,e,r,s,n,o),deployment:c,healthCheck:l}},kr=(e,r,o)=>{const t=y(e,w);if(!p(t))return;let n;try{n=K(k(t,"utf8")).length}catch{return}if(n===0)return;const a=o.toolchain?.secretPut!==void 0;r.warn(a?`Note: \`lunora deploy\` does not push secrets. ${w} has ${String(n)} key(s); if you changed them, run \`lunora env push --yes\` to update the deployed secrets.`:`Note: ${o.name} deploys read no secrets. ${w} has ${String(n)} key(s) that only the dev server sees; put the values the deployed worker needs in wrangler \`vars\`.`)},br=async e=>{let r=[];try{r=ie(await q({projectRoot:e,schemaDir:R(e)}))}catch{}const o=se(r).map(n=>n.key);let t=[];try{const n=y(e,w);p(n)&&(t=K(k(n,"utf8")).map(a=>a.key).filter(a=>je(a)))}catch{}return[...new Set([...o,...t])]},$r=async(e,r,o,t)=>{const{logger:n}=r,a=r.spawner??D,i=b(e),s=r.env===void 0?"":` --env ${r.env}`,c=t.toolchain?.secretPut;if(c===void 0)return n.error(`deploy target "${t.id}" has no secret store; cannot push secrets`),{minted:[],ok:!1};const l=[];for(const d of o){const g=ce(),m=c({environment:r.env,key:d,temporary:r.temporary}),u=j(i,m),f=await a({args:u.args,command:u.command,cwd:e,input:g});if(f.code!==0)return n.error(`failed to push secret ${d} (exit ${String(f.code)}); set it manually with \`wrangler secret put ${d}${s}\`.`),{minted:l,ok:!1};l.push({key:d,value:g}),n.success(`generated + pushed ${d}`)}return{minted:l,ok:!0}},Sr=/^[\w-]+$/u,E=[".dev.vars",".dev.vars.*","!.dev.vars.example"],Dr=/\r?\n/u,Er=(e,r)=>{const o=y(e,".gitignore");try{const t=p(o)?k(o,"utf8"):"",n=new Set(t.split(Dr).map(c=>c.trim())),a=E.filter(c=>!n.has(c));if(a.length===0)return;const i=a.some(c=>!c.startsWith("!"))?[...a.filter(c=>!c.startsWith("!")),...E.filter(c=>c.startsWith("!"))]:a,s=t.length>0&&!t.endsWith(`
@@ -1 +1 @@
1
- import{C as E,R as M,V as a,r as s}from"./cli-6BRlq6nw.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-DVVI8I8G.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 N,findSolutionByMessage as O}from"@lunora/errors";import{createCerebro as A}from"@visulima/cerebro";import B from"@visulima/cerebro/command/completion";import D from"@visulima/cerebro/command/version";import{O as a}from"./output-format-B4eQHi5y.mjs";import{A as p,T as l}from"./deploy-target-DCWwiuAe.mjs";import{SDK_LANGUAGES as E}from"@lunora/codegen";import{r as I}from"./cli-manifest-CRet0egA.mjs";import{exitCodeForError as L,EXIT_CODE as j}from"./EXIT_CODE-D_XCixv8.mjs";import{setCommandLogger as y,createLogger as k}from"./createLogger-Cl18I8AX.mjs";import{r as T}from"./render-lunora-error-C3OJY5wk.mjs";import{mkdirSync as P,readFileSync as _,lstatSync as M,writeFileSync as U}from"node:fs";import{homedir as W}from"node:os";import{join as f}from"node:path";import{addArgsFor as F,detectPackageManager as J}from"@lunora/config";const K={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},a]},v="lunora.advisor.map.json",$={description:"Score your app's advisor findings into a health map, and gate CI on it",examples:[["lunora advisor","Score the app and write lunora.advisor.map.json"],["lunora advisor --all","Show every procedure as a check matrix"],["lunora advisor --entry messages#sendMessage","Inspect one procedure"],["lunora advisor --min-score 80","Exit non-zero when the score drops below 80"],["lunora advisor --baseline","Fail on any regression against the committed map"]],group:"Develop",loader:()=>import("../packem_chunks/handler19.mjs").then(e=>({default:e.execute})),name:"advisor",options:[{description:"Show every procedure as a check matrix, not just the ones with findings",name:"all",type:Boolean},{description:`Compare against a committed map and fail on regression (default ${v})`,name:"baseline",type:String},{description:"Inspect a single procedure by `file#exportName`",name:"entry",type:String},a,{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 ${v})`,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}]},q={argument:{description:"gateway",name:"subcommand",type:String},description:"Provision a Cloudflare AI Gateway for ctx.ai and write its id into wrangler vars",examples:[["lunora ai gateway","Create (or reuse) a gateway named after the worker and wire it into wrangler vars"],["lunora ai gateway --id my-gateway","Use an explicit gateway id"],["lunora ai gateway --no-logs","Create the gateway with prompt/response log collection off"],["lunora ai gateway --dry-run","Print what would be created and written, without calling Cloudflare"]],group:"Deploy",loader:()=>import("../packem_chunks/handler20.mjs").then(e=>({default:e.execute})),name:"ai",options:[{description:"Gateway id (default: the worker `name` from wrangler.jsonc)",name:"id",type:String},{description:"Collect request/response logs in the gateway (default)",name:"logs",type:Boolean},{description:"Create the gateway with log collection off (prompts and responses are not stored)",name:"no-logs",type:Boolean},{description:"Print what would be created and written, without calling Cloudflare or editing files",name:"dry-run",type:Boolean},a]},H={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:[a]},V={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/handler23.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},a,{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}]},G={description:"Codegen + validate + bundle the Worker to disk without deploying",examples:[["lunora build","Bundle to .lunora/build without deploying"],["lunora build --out-dir dist-worker","Bundle to a custom directory"],["lunora build --emit-bindings bindings.json","Also write what the bundle needs provisioned, for an external deployer"]],group:"Deploy",loader:()=>import("../packem_chunks/handler21.mjs").then(e=>({default:e.execute})),name:"build",options:[{description:"Override the schema-drift gate for this run (build even with breaking schema drift and no migration; the committed baseline is not advanced)",name:"allow-schema-drift",type:Boolean},{description:`Which API spec(s) to emit: ${p} (default openapi)`,name:"api-spec",type:String},{description:"Write a JSON manifest of the bindings + crons the bundle needs to this path, for an IaC program to consume",name:"emit-bindings",type:String},a,{description:"Directory to write the bundled Worker to (default .lunora/build)",name:"out-dir",type:String},{description:"Fail the build on ERROR-level codegen advisories even locally (the gate already defaults to on in CI)",name:"strict-advisories",type:Boolean},{description:"Don't fail the build on ERROR-level codegen advisories (the gate defaults to on in CI, off locally). Never downgrades platform diagnostics.",name:"no-strict-advisories",type:Boolean},l]},z={argument:{description:"alerts [status | setup | test]",name:"tool",type:String},description:"Cloudflare-only tools: usage alerts that catch a runaway bill",examples:[["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"]],group:"Deploy",loader:()=>import("../packem_chunks/handler29.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: show the plan without creating or updating anything",name:"dry-run",type:Boolean},{description:"alerts setup: apply the plan without asking (required when stdin is not a TTY)",name:"yes",type:Boolean},a]},Y={description:"Run codegen for lunora/ functions and schema",examples:[["lunora codegen","Generate lunora/_generated/ from your schema + functions"]],group:"Develop",loader:()=>import("../packem_chunks/runCodegenCommand.mjs").then(e=>({default:e.execute})),name:"codegen",options:[{description:`Which API spec(s) to emit: ${p} (default openapi)`,name:"api-spec",type:String},a,{description:"Fail on ERROR-level advisories even locally (the gate already defaults to on in CI)",name:"strict-advisories",type:Boolean},{description:"Don't fail on ERROR-level advisories (the gate defaults to on in CI, off locally)",name:"no-strict-advisories",type:Boolean},l]},Q={argument:{description:"<build|push|images|list|info|delete> [args…]",name:"args",type:String},description:"Build/push container images and manage container instances (wraps wrangler containers)",examples:[["lunora containers build ./containers/transcoder --tag transcoder:v1","Build a container image with the local Docker engine"],["lunora containers build ./containers/transcoder --tag transcoder:v1 --push","Build and push to the Cloudflare Registry in one step"],["lunora containers push transcoder:v1","Push a locally-tagged image to the Cloudflare Registry"],["lunora containers images list","List images in your Cloudflare Registry"],["lunora containers list --format json","List container instances as JSON (also `info`, `images list`)"],["lunora containers images delete transcoder:v1","Delete an image to free registry storage"]],group:"Deploy",loader:()=>import("../packem_chunks/handler3.mjs").then(e=>({default:e.execute})),name:"containers",options:[{description:"build: push the image to the Cloudflare Registry after building",name:"push",type:Boolean},{description:"build: name:tag for the image (forwarded to wrangler --tag)",name:"tag",type:String},{description:"Cloudflare environment name",name:"env",type:String},{...a,description:"Output format: pretty (default) or json (read subcommands: list | info | images list)"}]},X={description:"Codegen, validate wrangler, then wrangler deploy",examples:[["lunora deploy","Deploy to Cloudflare"],["lunora deploy --env production","Deploy to a named environment"],["lunora deploy --dry-run","Validate + bundle without publishing"],["lunora deploy --migrate --migrate-yes --migrate-url <url>","Deploy, then run pending data migrations"]],group:"Deploy",loader:()=>import("../packem_chunks/runDeployCommand.mjs").then(e=>({default:e.execute})),name:"deploy",options:[{description:"Override the schema-drift gate for this run (deploy even with breaking schema drift and no migration; the committed baseline is not advanced — use --update-schema-baseline to accept the new shape)",name:"allow-schema-drift",type:Boolean},{description:`Which API spec(s) to emit: ${p} (default openapi)`,name:"api-spec",type:String},{description:"Validate, bundle, and run pre-deploy gates without publishing (wrangler deploy --dry-run)",name:"dry-run",type:Boolean},{description:"Cloudflare environment name",name:"env",type:String},a,{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},l,{description:"Deploy to a temporary Cloudflare account when unauthenticated (wrangler deploy --temporary; live ~60min, then claim or it's deleted). Wrangler errors if you're already authenticated.",name:"temporary",type:Boolean},{description:"Re-bless the committed schema baseline (lunora/.lunora-schema.json) with the current shape",name:"update-schema-baseline",type:Boolean}]},Z={argument:{description:"list | inspect <version-id> | rollback [version-id] | promote <version-id>",name:"subcommand",type:String},description:"List deployments and roll back / promote / inspect Worker versions",examples:[["lunora deployments list","Show the 10 most recent deployments"],["lunora deployments inspect <version-id>","View a specific Worker version"],["lunora deployments rollback --yes","Roll back to the previous version"],["lunora deployments promote <version-id> --yes","Send 100% of traffic to a version"]],group:"Deploy",loader:()=>import("../packem_chunks/handler4.mjs").then(e=>({default:e.execute})),name:"deployments",options:[{description:"Cloudflare environment name",name:"env",type:String},{...a,description:"Output format: pretty (default) or json (`list` only)"},{description:"Reason/description recorded with a rollback or promote",name:"message",type:String},{description:"Confirm a rollback or promote (required — these change live traffic)",name:"yes",type:Boolean}]},ee={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: ${p} (default openapi)`,name:"api-spec",type:String},{description:"Write the binding manifest (plus the dev origin) to <file>, for a supervisor that owns the rest of the graph",name:"emit-bindings",type:String},{description:"wrangler dev inspector port, for `wrangler dev` only (defaults to `dev.inspector_port` in wrangler.jsonc; unset, wrangler probes upward from 9229 and can take a sibling worker's pinned port)",name:"inspector-port",type:Number},{description:"Studio server port (default 6173)",name:"port",type:Number},l,{description:"wrangler dev port (default 8787)",name:"worker-port",type:Number},{description:"Run the dev server as a managed background process (auto-enabled when an AI agent is detected; LUNORA_AGENT_MODE=0 disables)",name:"background",type:Boolean},{description:"Machine-readable JSON log lines while the server runs, and a JSON result for `dev status`/`dev stop` (also LUNORA_LOG_JSON=1; auto-enabled for AI agents)",name:"json",type:Boolean},{description:"How many trailing lines `lunora dev logs` prints (default 100, 0 = all)",name:"lines",type:Number},{description:"Serve the embedded studio at /__lunora (default)",name:"studio",type:Boolean},{description:"Don't start the embedded studio server",name:"no-studio",type:Boolean},{description:"Spawn wrangler dev for the worker (default)",name:"worker",type:Boolean},{description:"Don't spawn wrangler dev — an external task runner owns the worker; codegen watch + studio still run",name:"no-worker",type:Boolean},{description:"Run codegen on startup and watch for changes (default)",name:"codegen",type:Boolean},{description:"Don't run codegen — no watch, no startup generate (or set LUNORA_CODEGEN=0)",name:"no-codegen",type:Boolean},{description:"Proxy D1/KV/R2 bindings to the deployed worker (or set LUNORA_REMOTE=1)",name:"remote",type:Boolean},{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}]},te={argument:{description:"Optional path under the docs site (e.g. packages/studio)",name:"section",type:String},description:"Open the Lunora docs in your browser (optional [section] path)",examples:[["lunora docs","Open the Lunora docs"],["lunora docs packages/studio","Open a specific docs section"]],group:"Project",loader:()=>import("../packem_chunks/handler5.mjs").then(e=>({default:e.execute})),name:"docs"},re={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/handler26.mjs").then(e=>({default:e.execute})),name:"doctor",options:[a]},oe={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/handler6.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},a,{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}]},ne={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/handler24.mjs").then(e=>({default:e.execute})),name:"eval",options:[{description:"Directory to discover *.eval.ts files under (default evals/)",name:"dir",type:String},a,{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}]},ae={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/handler7.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},{...a,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}]},ie={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/handler8.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},a,{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}]},se={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/handler9.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},a,{description:"With --bindings: write the manifest to <file> instead of stdout",name:"out",type:String}]},le={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}]},de={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/handler10.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},a,{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}]},pe={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/handler27.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},a]},ce={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/handler11.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}]},ue={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/handler25.mjs").then(e=>({default:e.execute})),name:"logs",options:[{description:"Cloudflare environment name",name:"env",type:String},a,{description:"Substring filter on log messages",name:"search",type:String},{description:"Filter by invocation status: ok, error, or canceled",name:"status",type:String},l,{description:"Tail a temporary-account deployment when unauthenticated (wrangler tail --temporary). Errors if you're already authenticated.",name:"temporary",type:Boolean},{description:"Read the durable log archive (pipelineLogSink → R2) via R2 SQL instead of tailing live",name:"durable",type:Boolean},{description:"durable: Iceberg table the Pipeline writes to (required with --durable)",name:"table",type:String},{description:"durable: Iceberg namespace (R2 Data Catalog database) the table lives in",name:"namespace",type:String},{description:"durable: lower time bound (epoch-millis or ISO 8601), inclusive",name:"since",type:String},{description:"durable: upper time bound (epoch-millis or ISO 8601), inclusive",name:"until",type:String},{description:"durable: exact severity filter (trace|debug|log|info|warn|error|fatal)",name:"level",type:String},{description:"durable: severity floor — this level and every more-severe one",name:"min-level",type:String},{description:"durable: keep function paths starting with this prefix (LIKE 'prefix%')",name:"function-prefix",type:String},{description:"durable: trace-id filter",name:"trace-id",type:String},{description:"durable: shard-key filter",name:"shard-key",type:String},{description:"durable: user-id filter",name:"user-id",type:String},{description:"durable: max rows (clamped to 1–10000; default 500)",name:"limit",type:String},{description:"durable: resume after a prior page — the opaque cursor token printed by the previous page (bare epoch-millis also accepted for back-compat)",name:"cursor",type:String},{description:"durable: emit one JSON object per line instead of a table",name:"ndjson",type:Boolean}]},me={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/handler28.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}]},ge={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},a,{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}]},he={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/handler12.mjs").then(e=>({default:e.execute})),name:"prepare",options:[{description:"Override the schema-drift gate for this run (proceed even with breaking schema drift and no migration; the committed baseline is not advanced)",name:"allow-schema-drift",type:Boolean},{description:`Which API spec(s) to emit: ${p} (default openapi)`,name:"api-spec",type:String},{description:"Fail on ERROR-level codegen advisories even locally (the gate already defaults to on in CI)",name:"strict-advisories",type:Boolean},{description:"Don't fail on ERROR-level codegen advisories (the gate defaults to on in CI, off locally). Never downgrades platform diagnostics.",name:"no-strict-advisories",type:Boolean},l,{description:"Re-bless the committed schema baseline (lunora/.lunora-schema.json) with the current shape",name:"update-schema-baseline",type:Boolean}]},fe={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/handler13.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},{...a,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}]},ye={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}]},ve={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/handler14.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}]},be={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},a,{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}]},we={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/handler22.mjs").then(e=>({default:e.execute})),name:"sdk",options:[{description:`Target language: ${E.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}]},ke={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/handler15.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},a,{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}]},Se={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/handler16.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},a,{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}]},xe={description:"Validate wrangler.jsonc + codegen dry-run + tsc --noEmit (no files written)",examples:[["lunora verify","Validate wrangler + codegen + tsc"],["lunora verify --no-typecheck","Skip the TypeScript type-check"],["lunora verify --health-url https://my-app.workers.dev","Also probe the deployment's /_lunora/health"],["lunora verify --env production","Validate the env.production view, as `lunora deploy --env production` will"]],group:"Deploy",loader:()=>import("../packem_chunks/handler17.mjs").then(e=>({default:e.execute})),name:"verify",options:[{description:"Treat breaking schema drift as a warning instead of a failure",name:"allow-schema-drift",type:Boolean},{description:`Which API spec(s) to emit: ${p} (default openapi)`,name:"api-spec",type:String},{description:"Cloudflare environment name — validate the env.<name> view of wrangler.jsonc, as `lunora deploy --env` does",name:"env",type:String},a,{description:"Probe this deployment's /_lunora/health endpoint (off by default; keeps verify offline-safe)",name:"health-url",type:String},{description:"Fail verification on ERROR-level codegen advisories even locally (the gate already defaults to on in CI)",name:"strict-advisories",type:Boolean},{description:"Don't fail verification on ERROR-level codegen advisories (the gate defaults to on in CI, off locally). Never downgrades platform diagnostics.",name:"no-strict-advisories",type:Boolean},{description:"Run the TypeScript type-check step (default)",name:"typecheck",type:Boolean},{description:"Skip the TypeScript type-check step",name:"no-typecheck",type:Boolean},l]},Ce={description:"Open the Lunora studio in your browser (the running dev server's, or the default local one)",examples:[["lunora view","Open the studio for the running dev server"]],group:"Project",loader:()=>import("../packem_chunks/handler18.mjs").then(e=>({default:e.execute})),name:"view"},Re=(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 i=1;i<=t.length;i+=1){const s=r[i]??0,c=e[o-1]===t[i-1]?0:1;r[i]=Math.min((r[i-1]??0)+1,s+1,n+c),n=s}}return r[t.length]??0},Ne=(e,t)=>{let r,o=Number.POSITIVE_INFINITY;for(const i of t){const s=Re(e,i);s<o&&(o=s,r=i)}const n=Math.max(2,Math.ceil(e.length/3));return r!==void 0&&o<=n?r:void 0},Oe=e=>`https://registry.npmjs.org/@lunora/cli/${e}`,Ae=1440*60*1e3,Be=1500,De="0.0.0",Ee=/^v/u,Ie=new Set(["alpha","beta","next"]),m=e=>{const t=e.trim().replace(Ee,""),r=t.indexOf("-");return r===-1?{core:t,prerelease:""}:{core:t.slice(0,r),prerelease:t.slice(r+1)}},b=e=>{const[t,r,o]=m(e).core.split(".").map(n=>{const i=Number.parseInt(n,10);return Number.isFinite(i)?i:0});return[t??0,r??0,o??0]},Le=(e,t)=>{const r=Number.parseInt(e,10),o=Number.parseInt(t,10);return String(r)===e&&String(o)===t?r>o?1:-1:e>t?1:-1},je=(e,t)=>{if(e===t)return 0;if(e===""||t==="")return e===""?1:-1;const r=e.split("."),o=t.split(".");for(let n=0;n<Math.max(r.length,o.length);n+=1){const i=r[n],s=o[n];if(i===void 0||s===void 0)return i===void 0?-1:1;if(i!==s)return Le(i,s)}return 0},Te=(e,t)=>{const r=b(e),o=b(t);for(let n=0;n<3;n+=1)if((r[n]??0)!==(o[n]??0))return(r[n]??0)>(o[n]??0)?1:-1;return je(m(e).prerelease,m(t).prerelease)},Pe=e=>{const t=m(e).prerelease.split(".")[0]??"";return Ie.has(t)?t:"latest"},_e=(e,t)=>Te(t,e)>0,Me=(e,t,r)=>t-e<r,Ue=(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:i,command:s}=F(o,[`@lunora/cli@${r}`],{dev:!0});return`${n} — run \`${s} ${i.join(" ")}\``},S=e=>f(e,"lunora-cli-update.json"),We=e=>{const t=e.XDG_CACHE_HOME&&e.XDG_CACHE_HOME.length>0?e.XDG_CACHE_HOME:f(W(),".cache"),r=f(t,"lunora");try{P(r,{mode:448,recursive:!0})}catch{}return r},Fe=e=>{try{const t=JSON.parse(_(S(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{}},w=(e,t)=>{try{const r=S(e);try{if(M(r).isSymbolicLink())return}catch{}U(r,`${JSON.stringify(t)}
2
+ `,"utf8")}catch{}},Je=async(e,t)=>{try{const r=await e(Oe(t),{signal:AbortSignal.timeout(Be)});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===De||!r||t.CI!==void 0||t.LUNORA_NO_UPDATE_NOTIFIER!==void 0,$e=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??We(t),n=(e.now??Date.now)(),i=e.ttlMs??Ae,s=Pe(e.current),c=Fe(o),R=c?.tag??"latest",g=c!==void 0&&R===s?c:void 0;let u=g?.latest;if(g===void 0||!Me(g.checkedAt,n,i)){const h=await Je(e.fetchImpl??globalThis.fetch,s);h===void 0?w(o,{checkedAt:n,latest:e.current,tag:s}):(u=h,w(o,{checkedAt:n,latest:h,tag:s}))}u!==void 0&&_e(e.current,u)&&e.logger.warn(Ue(e.current,u,s,e.manager))},qe=["init","add","dev","codegen","build","deploy","containers","ai","prepare","link","deployments","cloudflare","logs","run","insights","reset","migrate","export","import","seed","shards","backup","eval","verify","info","doctor","env","analyze","view","docs","registry","rules","mcp"],x=I(),He=[le,K,ee,Y,$,G,X,Q,q,he,ce,Z,z,ue,be,de,ye,ge,ae,ie,ke,Se,pe,V,ne,xe,se,re,oe,H,Ce,te,fe,ve,me,we],C=[...He,D,B],gt=C.map(e=>e.name),d=e=>e.replaceAll("{",String.raw`\{`).replaceAll("}",String.raw`\}`),Ve=e=>e.every(t=>typeof t=="string")?e.map(t=>d(t)):e.map(t=>typeof t=="string"?[d(t)]:t.map(r=>d(r))),Ge=e=>({...e,...e.argument===void 0?{}:{argument:{...e.argument,description:d(e.argument.description??"")}},...e.description===void 0?{}:{description:d(e.description)},...e.examples===void 0?{}:{examples:Ve(e.examples)},...e.options===void 0?{}:{options:e.options.map(t=>({...t,description:d(t.description??"")}))}}),ze=e=>{const t={value:0},r=A("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:x});for(const o of C)r.addCommand(Ge(o));return{cli:r,exitCode:t}},Ye=/Command "(?<name>[^"]+)" not found/u,Qe=e=>{const t=k(),r=e instanceof Error?e.message:String(e),o=Ye.exec(r);if(!o?.groups)return N(e)||O(r)!==void 0?t.error(T(e)):t.error(r),L(e);const n=o.groups.name??"",i=Ne(n,qe);return t.error(`Unknown command "${n}".${i===void 0?"":` Did you mean "${i}"?`}`),t.info("Run `lunora --help` to list commands, or `lunora docs` to open the documentation."),j.USAGE},Xe=e=>({debug:t=>{e.debug(t)},error:t=>{e.error(t)},info:t=>{e.info(t)},success:t=>{e.info(t)},warn:t=>{e.warn(t)}}),ht=async(e={})=>{const{cli:t,exitCode:r}=ze(e);e.logger!==void 0&&y(Xe(e.logger));try{await t.run({shouldExitProcess:!1})}catch(n){return Qe(n)}finally{y(void 0)}let o;try{o=J(process.cwd())}catch{}return await $e({current:x,logger:k(),manager:o}),r.value};export{qe as C,v as D,gt as R,x as V,ht as r};
@@ -0,0 +1 @@
1
+ const l="https://api.cloudflare.com/client/v4/accounts",u=async({accountId:o,apiToken:a,fetch:c,init:n,path:r})=>{const e=await(c??globalThis.fetch.bind(globalThis))(`${l}/${encodeURIComponent(o)}${r}`,{...n,headers:{Authorization:`Bearer ${a}`,"Content-Type":"application/json"}}),s=await e.text();let t;try{t=JSON.parse(s)}catch{return{ok:!1,status:e.status,text:s}}return!e.ok||typeof t!="object"||t===null||t.success===!1?{ok:!1,status:e.status,text:s}:{body:t,ok:!0}};export{u as c};
@@ -0,0 +1 @@
1
+ import{c as $}from"./cloudflare-rest--YUlUUlB.mjs";import{r as E}from"./cloudflare-credentials-lC5JtPLe.mjs";const v=5e3,m=(e,r,t)=>`POST https://api.cloudflare.com/client/v4/accounts/${e}/artifacts/namespaces with body { "namespace": "${r}", "jurisdiction": "${t}" }`,P=async e=>{const{binding:r,jurisdiction:t,namespace:s}=e,a=`Artifacts namespace "${s}" (binding ${r})`,{accountId:c,token:i}=E(e.environment??process.env,e.accountId);if(i===void 0||c===void 0)return{fix:"Set CLOUDFLARE_API_TOKEN (with Artifacts read access) and CLOUDFLARE_ACCOUNT_ID (or `account_id` in wrangler.jsonc) to check it.",message:`the jurisdiction of ${a} was not checked against the schema's "${t}".`,verdict:"unchecked"};let n;try{n=await $({accountId:c,apiToken:i,...e.fetch===void 0?{}:{fetch:e.fetch},init:{signal:AbortSignal.timeout(v)},path:`/artifacts/namespaces/${encodeURIComponent(s)}`})}catch(l){return{message:`the jurisdiction of ${a} could not be read (${l instanceof Error?l.message:String(l)}).`,verdict:"unchecked"}}if(!n.ok&&n.status===404)return{fix:`Create it before the first repo: ${m(c,s,t)}.`,message:`${a} does not exist, and the first repo create() would make it unrestricted — the schema pins data to "${t}".`,verdict:"missing"};if(!n.ok)return{...n.status===401||n.status===403?{fix:`Give CLOUDFLARE_API_TOKEN Artifacts read access on account ${c}.`}:{},message:`the jurisdiction of ${a} could not be read (HTTP ${String(n.status)}).`,verdict:"unchecked"};const{result:o}=n.body,d=typeof o=="object"&&o!==null&&"jurisdiction"in o?o.jurisdiction:void 0;return typeof d!="string"?{message:`the jurisdiction of ${a} could not be read (the response carried none).`,verdict:"unchecked"}:d===t?{message:`${a} is in the "${d}" jurisdiction, as the schema pins.`,verdict:"ok"}:{fix:`A namespace's jurisdiction cannot change: create one with ${m(c,"<name>",t)}, point the binding's "namespace" at it, and move the repos over.`,message:`${a} is in the "${d}" jurisdiction, but the schema pins data to "${t}".`,verdict:"mismatch"}},h=100,u=500,g=10,C=5e3,f="Delete the Workers you no longer need (old preview / staging deploys free their classes), or set `durableObjects: { merge: true }` in lunora.config before an app's first deploy so it spends one class instead of up to three.",T=e=>e>=u?{fix:f,message:`the Cloudflare account has ${String(e)} Durable Object classes — the Workers Paid cap is ${String(u)}, so a deploy that adds one will fail.`,verdict:"full"}:e>=u-g?{fix:f,message:`the Cloudflare account has ${String(e)} of ${String(u)} Durable Object classes (Workers Paid cap).`,verdict:"near"}:e>=h-g&&e<=h?{fix:f,message:`the Cloudflare account has ${String(e)} Durable Object classes — on Workers Free the cap is ${String(h)} (Paid: ${String(u)}).`,verdict:"near"}:{message:`the Cloudflare account has ${String(e)} Durable Object classes (caps: ${String(h)} Free, ${String(u)} Paid).`,verdict:"ok"},D=async(e={})=>{const{accountId:r,token:t}=E(e.environment??process.env,e.accountId);if(t===void 0||r===void 0)return{fix:"Set CLOUDFLARE_API_TOKEN (Workers Scripts Read) and CLOUDFLARE_ACCOUNT_ID (or `account_id` in wrangler.jsonc) to check it.",message:"the account's Durable Object class count was not checked.",verdict:"unchecked"};try{const s=await $({accountId:r,apiToken:t,...e.fetch===void 0?{}:{fetch:e.fetch},init:{signal:AbortSignal.timeout(C)},path:"/workers/durable_objects/namespaces?per_page=1"}),a=s.ok?s.body.result_info:void 0,c=typeof a=="object"&&a!==null&&"total_count"in a?a.total_count:void 0;return typeof c!="number"?{message:`the account's Durable Object class count could not be read${s.ok?"":` (HTTP ${String(s.status)})`}.`,verdict:"unchecked"}:T(c)}catch(s){return{message:`the account's Durable Object class count could not be read (${s instanceof Error?s.message:String(s)}).`,verdict:"unchecked"}}},x=e=>{switch(e){case"boolean":return"boolean";case"date":case"number":case"timestamp":return"number";case"id":case"literal":case"string":return"string";default:return}},j=/already (?:exists|indexed)|duplicate/iu,p=e=>["vectorize","create-metadata-index",e.index,`--property-name=${e.property}`,`--type=${e.type}`],k=async(e,r)=>{try{return await e(r)}catch(t){return{code:1,stderr:t instanceof Error?t.message:String(t)}}},w=async e=>{const{cwd:r,entries:t,exec:s,logger:a,spawner:c}=e,i=[];for(const n of t){const o=await k(c,{args:[...s.args,...p(n)],captureStderr:!0,command:s.command,cwd:r,stdoutToStderr:!0});if(o.code===0){i.push({entry:n,status:"created"});continue}const d=`${o.stderr??""}${o.stdout??""}`;if(j.test(d)){i.push({entry:n,status:"exists"});continue}i.push({entry:n,error:d.trim()||`exit code ${String(o.code)}`,status:"failed"}),a.warn(`could not create the Vectorize metadata index for "${n.property}" on "${n.index}" — filters on that property will match nothing until it exists. Run: wrangler ${p(n).join(" ")}`)}return i},S=e=>e.endsWith("S")?e.slice(0,-1):e,b=e=>e.replaceAll(/([a-z\d])([A-Z])/gu,"$1_$2").toUpperCase().split(/[_-]+/u).filter(r=>r.length>0),_=new Set(["CREDENTIAL","DSN","PASSPHRASE","PASSWD","PASSWORD","SECRET","TOKEN"]),A=["ACCESS_KEY","API_KEY","ENCRYPTION_KEY","PRIVATE_KEY","SIGNING_KEY"],I=new RegExp(`(?:${[..._,...A.map(e=>e.replaceAll("_",""))].join("|")})S?$`,"iu"),O=e=>b(e).some(r=>r==="PUBLIC"||r==="PUBLISHABLE"),L=e=>{if(O(e))return!1;const r=b(e);if(r.some(s=>_.has(S(s))))return!0;const t=S(r.join("_"));return A.some(s=>t===s||t.endsWith(`_${s}`))||I.test(e)};export{D as a,P as b,p as c,w as e,L as i,x as m};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@lunora/cli",
3
- "version": "1.0.0-alpha.370",
3
+ "version": "1.0.0-alpha.371",
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",
@@ -1,2 +0,0 @@
1
- import{isLunoraError as N,findSolutionByMessage as O}from"@lunora/errors";import{createCerebro as A}from"@visulima/cerebro";import B from"@visulima/cerebro/command/completion";import D from"@visulima/cerebro/command/version";import{O as a}from"./output-format-B4eQHi5y.mjs";import{A as p,T as l}from"./deploy-target-DCWwiuAe.mjs";import{SDK_LANGUAGES as E}from"@lunora/codegen";import{r as I}from"./cli-manifest-CRet0egA.mjs";import{exitCodeForError as L,EXIT_CODE as j}from"./EXIT_CODE-D_XCixv8.mjs";import{setCommandLogger as y,createLogger as k}from"./createLogger-Cl18I8AX.mjs";import{r as T}from"./render-lunora-error-C3OJY5wk.mjs";import{mkdirSync as P,readFileSync as _,lstatSync as U,writeFileSync as M}from"node:fs";import{homedir as W}from"node:os";import{join as f}from"node:path";import{addArgsFor as F,detectPackageManager as J}from"@lunora/config";const K={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},a]},v="lunora.advisor.map.json",$={description:"Score your app's advisor findings into a health map, and gate CI on it",examples:[["lunora advisor","Score the app and write lunora.advisor.map.json"],["lunora advisor --all","Show every procedure as a check matrix"],["lunora advisor --entry messages#sendMessage","Inspect one procedure"],["lunora advisor --min-score 80","Exit non-zero when the score drops below 80"],["lunora advisor --baseline","Fail on any regression against the committed map"]],group:"Develop",loader:()=>import("../packem_chunks/handler19.mjs").then(e=>({default:e.execute})),name:"advisor",options:[{description:"Show every procedure as a check matrix, not just the ones with findings",name:"all",type:Boolean},{description:`Compare against a committed map and fail on regression (default ${v})`,name:"baseline",type:String},{description:"Inspect a single procedure by `file#exportName`",name:"entry",type:String},a,{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 ${v})`,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}]},q={argument:{description:"gateway",name:"subcommand",type:String},description:"Provision a Cloudflare AI Gateway for ctx.ai and write its id into wrangler vars",examples:[["lunora ai gateway","Create (or reuse) a gateway named after the worker and wire it into wrangler vars"],["lunora ai gateway --id my-gateway","Use an explicit gateway id"],["lunora ai gateway --no-logs","Create the gateway with prompt/response log collection off"],["lunora ai gateway --dry-run","Print what would be created and written, without calling Cloudflare"]],group:"Deploy",loader:()=>import("../packem_chunks/handler20.mjs").then(e=>({default:e.execute})),name:"ai",options:[{description:"Gateway id (default: the worker `name` from wrangler.jsonc)",name:"id",type:String},{description:"Collect request/response logs in the gateway (default)",name:"logs",type:Boolean},{description:"Create the gateway with log collection off (prompts and responses are not stored)",name:"no-logs",type:Boolean},{description:"Print what would be created and written, without calling Cloudflare or editing files",name:"dry-run",type:Boolean},a]},H={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:[a]},V={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/handler23.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},a,{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}]},G={description:"Codegen + validate + bundle the Worker to disk without deploying",examples:[["lunora build","Bundle to .lunora/build without deploying"],["lunora build --out-dir dist-worker","Bundle to a custom directory"],["lunora build --emit-bindings bindings.json","Also write what the bundle needs provisioned, for an external deployer"]],group:"Deploy",loader:()=>import("../packem_chunks/handler21.mjs").then(e=>({default:e.execute})),name:"build",options:[{description:"Override the schema-drift gate for this run (build even with breaking schema drift and no migration; the committed baseline is not advanced)",name:"allow-schema-drift",type:Boolean},{description:`Which API spec(s) to emit: ${p} (default openapi)`,name:"api-spec",type:String},{description:"Write a JSON manifest of the bindings + crons the bundle needs to this path, for an IaC program to consume",name:"emit-bindings",type:String},a,{description:"Directory to write the bundled Worker to (default .lunora/build)",name:"out-dir",type:String},{description:"Fail the build on ERROR-level codegen advisories even locally (the gate already defaults to on in CI)",name:"strict-advisories",type:Boolean},{description:"Don't fail the build on ERROR-level codegen advisories (the gate defaults to on in CI, off locally). Never downgrades platform diagnostics.",name:"no-strict-advisories",type:Boolean},l]},z={description:"Run codegen for lunora/ functions and schema",examples:[["lunora codegen","Generate lunora/_generated/ from your schema + functions"]],group:"Develop",loader:()=>import("../packem_chunks/runCodegenCommand.mjs").then(e=>({default:e.execute})),name:"codegen",options:[{description:`Which API spec(s) to emit: ${p} (default openapi)`,name:"api-spec",type:String},a,{description:"Fail on ERROR-level advisories even locally (the gate already defaults to on in CI)",name:"strict-advisories",type:Boolean},{description:"Don't fail on ERROR-level advisories (the gate defaults to on in CI, off locally)",name:"no-strict-advisories",type:Boolean},l]},Y={argument:{description:"<build|push|images|list|info|delete> [args…]",name:"args",type:String},description:"Build/push container images and manage container instances (wraps wrangler containers)",examples:[["lunora containers build ./containers/transcoder --tag transcoder:v1","Build a container image with the local Docker engine"],["lunora containers build ./containers/transcoder --tag transcoder:v1 --push","Build and push to the Cloudflare Registry in one step"],["lunora containers push transcoder:v1","Push a locally-tagged image to the Cloudflare Registry"],["lunora containers images list","List images in your Cloudflare Registry"],["lunora containers list --format json","List container instances as JSON (also `info`, `images list`)"],["lunora containers images delete transcoder:v1","Delete an image to free registry storage"]],group:"Deploy",loader:()=>import("../packem_chunks/handler3.mjs").then(e=>({default:e.execute})),name:"containers",options:[{description:"build: push the image to the Cloudflare Registry after building",name:"push",type:Boolean},{description:"build: name:tag for the image (forwarded to wrangler --tag)",name:"tag",type:String},{description:"Cloudflare environment name",name:"env",type:String},{...a,description:"Output format: pretty (default) or json (read subcommands: list | info | images list)"}]},Q={description:"Codegen, validate wrangler, then wrangler deploy",examples:[["lunora deploy","Deploy to Cloudflare"],["lunora deploy --env production","Deploy to a named environment"],["lunora deploy --dry-run","Validate + bundle without publishing"],["lunora deploy --migrate --migrate-yes --migrate-url <url>","Deploy, then run pending data migrations"]],group:"Deploy",loader:()=>import("../packem_chunks/runDeployCommand.mjs").then(e=>({default:e.execute})),name:"deploy",options:[{description:"Override the schema-drift gate for this run (deploy even with breaking schema drift and no migration; the committed baseline is not advanced — use --update-schema-baseline to accept the new shape)",name:"allow-schema-drift",type:Boolean},{description:`Which API spec(s) to emit: ${p} (default openapi)`,name:"api-spec",type:String},{description:"Validate, bundle, and run pre-deploy gates without publishing (wrangler deploy --dry-run)",name:"dry-run",type:Boolean},{description:"Cloudflare environment name",name:"env",type:String},a,{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},l,{description:"Deploy to a temporary Cloudflare account when unauthenticated (wrangler deploy --temporary; live ~60min, then claim or it's deleted). Wrangler errors if you're already authenticated.",name:"temporary",type:Boolean},{description:"Re-bless the committed schema baseline (lunora/.lunora-schema.json) with the current shape",name:"update-schema-baseline",type:Boolean}]},X={argument:{description:"list | inspect <version-id> | rollback [version-id] | promote <version-id>",name:"subcommand",type:String},description:"List deployments and roll back / promote / inspect Worker versions",examples:[["lunora deployments list","Show the 10 most recent deployments"],["lunora deployments inspect <version-id>","View a specific Worker version"],["lunora deployments rollback --yes","Roll back to the previous version"],["lunora deployments promote <version-id> --yes","Send 100% of traffic to a version"]],group:"Deploy",loader:()=>import("../packem_chunks/handler4.mjs").then(e=>({default:e.execute})),name:"deployments",options:[{description:"Cloudflare environment name",name:"env",type:String},{...a,description:"Output format: pretty (default) or json (`list` only)"},{description:"Reason/description recorded with a rollback or promote",name:"message",type:String},{description:"Confirm a rollback or promote (required — these change live traffic)",name:"yes",type:Boolean}]},Z={argument:{description:"Optional subcommand: stop (shut the running dev server down) | status (report it) | logs (print its captured output)",name:"args",type:String},description:"Run the dev stack: wrangler worker + studio + codegen watch",examples:[["lunora dev","Run the worker + studio + codegen watch"],["lunora dev --background","Run detached: blocks until ready, prints URL + PID, then returns"],["lunora dev stop","Stop the background/tracked dev server (idempotent)"],["lunora dev status","Report the running dev server (URL, PID, uptime, ready/starting)"],["lunora dev status --json","Same as JSON — poll `.ready` to gate a dependent step in a task graph"],["lunora dev logs","Print the captured dev-server log (background runs)"],["lunora dev --json","Stream machine-readable JSON log LINES (a stream, not a --format json document)"],["lunora dev --emit-bindings dev-manifest.json","Write what this worker needs + where it serves, for a task runner"],["lunora dev --no-studio","Skip the embedded studio server"],["lunora dev --worker-port 8080","Use a custom wrangler dev port"],["lunora dev --inspector-port 9235","Pin wrangler's devtools inspector port instead of letting it walk up from 9229"],["lunora dev --remote","Proxy D1/KV/R2 to the deployed worker (also LUNORA_REMOTE=1)"],["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: ${p} (default openapi)`,name:"api-spec",type:String},{description:"Write the binding manifest (plus the dev origin) to <file>, for a supervisor that owns the rest of the graph",name:"emit-bindings",type:String},{description:"wrangler dev inspector port, for `wrangler dev` only (defaults to `dev.inspector_port` in wrangler.jsonc; unset, wrangler probes upward from 9229 and can take a sibling worker's pinned port)",name:"inspector-port",type:Number},{description:"Studio server port (default 6173)",name:"port",type:Number},l,{description:"wrangler dev port (default 8787)",name:"worker-port",type:Number},{description:"Run the dev server as a managed background process (auto-enabled when an AI agent is detected; LUNORA_AGENT_MODE=0 disables)",name:"background",type:Boolean},{description:"Machine-readable JSON log lines while the server runs, and a JSON result for `dev status`/`dev stop` (also LUNORA_LOG_JSON=1; auto-enabled for AI agents)",name:"json",type:Boolean},{description:"How many trailing lines `lunora dev logs` prints (default 100, 0 = all)",name:"lines",type:Number},{description:"Serve the embedded studio at /__lunora (default)",name:"studio",type:Boolean},{description:"Don't start the embedded studio server",name:"no-studio",type:Boolean},{description:"Spawn wrangler dev for the worker (default)",name:"worker",type:Boolean},{description:"Don't spawn wrangler dev — an external task runner owns the worker; codegen watch + studio still run",name:"no-worker",type:Boolean},{description:"Run codegen on startup and watch for changes (default)",name:"codegen",type:Boolean},{description:"Don't run codegen — no watch, no startup generate (or set LUNORA_CODEGEN=0)",name:"no-codegen",type:Boolean},{description:"Proxy D1/KV/R2 bindings to the deployed worker (or set LUNORA_REMOTE=1)",name:"remote",type:Boolean},{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}]},ee={argument:{description:"Optional path under the docs site (e.g. packages/studio)",name:"section",type:String},description:"Open the Lunora docs in your browser (optional [section] path)",examples:[["lunora docs","Open the Lunora docs"],["lunora docs packages/studio","Open a specific docs section"]],group:"Project",loader:()=>import("../packem_chunks/handler5.mjs").then(e=>({default:e.execute})),name:"docs"},te={description:"Preflight the current Lunora project (wrangler bindings, placeholders, dev secrets)",examples:[["lunora doctor","Run the project preflight checks"],["lunora doctor --format json","Emit the findings as a machine-readable JSON document"]],group:"Project",loader:()=>import("../packem_chunks/handler26.mjs").then(e=>({default:e.execute})),name:"doctor",options:[a]},re={argument:{description:"list | get <KEY> | set <KEY> <VALUE> | unset <KEY> | generate [KEY] | push | diff | doctor",name:"subcommand",type:String},description:"Manage .dev.vars and sync secrets via wrangler (list | get | set | unset | generate | push | diff | doctor)",examples:[["lunora env list","List .dev.vars keys"],["lunora env set API_KEY secret","Set a local variable"],["lunora env generate","Generate strong values for the project's secrets (print KEY=value)"],["lunora env generate AUTH_SECRET --set","Generate one secret and write it to .dev.vars"],["lunora env push --yes","Upload secrets to Cloudflare"],["lunora env diff","Compare local .dev.vars keys against Cloudflare"],["lunora env diff --format json","Same, as a single JSON document on stdout"]],group:"Data",loader:()=>import("../packem_chunks/handler6.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},a,{description:"For `generate` — write the generated secrets into .dev.vars instead of printing them",name:"set",type:Boolean},{description:"Push secrets to a temporary-account deployment when unauthenticated (wrangler secret put --temporary). Errors if you're already authenticated.",name:"temporary",type:Boolean},{description:"Required for `push` — confirms uploading secrets to Cloudflare",name:"yes",type:Boolean}]},oe={description:"Run every *.eval.ts under evals/ via @lunora/testing's evaluate/agentHarness — no live worker needed",examples:[["lunora eval","Run every eval under evals/, print the aggregate table"],["lunora eval --threshold 0.8","Non-zero exit if any eval's average score falls below 0.8"],["lunora eval --dir evals/support --format json","Run a subset and emit a machine-readable result"]],group:"Develop",loader:()=>import("../packem_chunks/handler24.mjs").then(e=>({default:e.execute})),name:"eval",options:[{description:"Directory to discover *.eval.ts files under (default evals/)",name:"dir",type:String},a,{description:"Score gate every eval's average must meet ([0,1]); a per-eval `threshold` export wins over this for that eval",name:"threshold",type:Number}]},ne={argument:{description:"Optional path (alias for --out)",name:"path",type:String},description:"Stream NDJSON of every shard-local + global table from the worker",examples:[["lunora export --out backup.ndjson","Dump every table to an NDJSON file"],["lunora export --tables messages,users","Export only specific tables"],["lunora export --out backup.ndjson --format json","Write the dump to a file and report rows/bytes as JSON"]],group:"Data",loader:()=>import("../packem_chunks/handler7.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},{...a,description:"Output format: pretty (default) or json — json needs --out <file>, since stdout carries the NDJSON"},{description:"Target production — requires an explicit --url",name:"prod",type:Boolean},{description:"Worker URL (default http://localhost:8787)",name:"url",type:String},{description:"Admin bearer token (prefer LUNORA_ADMIN_TOKEN; --token is visible to other local processes via the process table)",name:"token",type:String}]},ae={argument:{description:"Source NDJSON file, or a `npx convex export --path <dir>` directory",name:"file",type:String},description:"Bulk-insert rows from an NDJSON file — or a Convex export directory — via the worker's admin endpoint",examples:[["lunora import backup.ndjson","Bulk-insert rows from an NDJSON file"],["lunora import ./convex-export","Import a `npx convex export --path` directory (ids are preserved, so no remapping)"],["lunora import ./convex-export --with-storage","Also migrate blobs (verified sha256 upload) + `{ $storage }` refs"],["lunora import ./convex-export --scan","Write a candidate `lunora/import-convex.json` storage-column mapping (imports nothing)"],["lunora import ./snapshot.zip --with-storage --verify","Import a `npx convex export --path` zip snapshot with blob + row-parity checks"],["lunora import ./supabase-csv --from supabase","Import a directory of `COPY … TO STDOUT WITH CSV HEADER` dumps"],["lunora import ./firestore-json --from firebase --verify","Import Firestore documents (REST/Admin-SDK JSON) with row-parity checks"]],group:"Data",loader:()=>import("../packem_chunks/handler8.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},a,{description:"Rows per HTTP request (default 500)",name:"batch-size",type:Number},{description:"Also migrate file storage — Convex `_storage` blobs, or a Supabase/Firebase bucket (verified upload)",name:"with-storage",type:Boolean},{description:"Directory of storage objects to upload alongside the rows (Firebase: after `gcloud storage cp -r`)",name:"storage-dir",type:String},{description:"Write a candidate `lunora/import-convex.json` storage-column mapping and exit",name:"scan",type:Boolean},{description:"Verify row parity + dangling-storage after import (non-zero exit on mismatch)",name:"verify",type:Boolean},{description:"Target production — requires an explicit --url",name:"prod",type:Boolean},{description:"Confirm bulk-writing production (required with --prod)",name:"yes",type:Boolean},{description:"Worker URL (default http://localhost:8787)",name:"url",type:String},{description:"Admin bearer token (prefer LUNORA_ADMIN_TOKEN; --token is visible to other local processes via the process table)",name:"token",type:String}]},ie={description:"Print resolved project config: @lunora/* versions, wrangler summary, schema overview",examples:[["lunora info","Print resolved project config"],["lunora info --format json","Emit a JSON snapshot"],["lunora info --bindings","List what this Worker needs provisioned: bindings, crons, vars"],["lunora info --bindings --format json","Emit the manifest a deployer or task runner consumes"],["lunora info --bindings --out reqs.json","Write that manifest to a file"]],group:"Project",loader:()=>import("../packem_chunks/handler9.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},a,{description:"With --bindings: write the manifest to <file> instead of stdout",name:"out",type:String}]},se={argument:{description:"Project name",name:"name",type:String},description:"Scaffold a new Lunora project",examples:[["lunora init my-app","Scaffold with the default (vite) template"],["lunora init my-app -t next","Scaffold a Next.js app"],["lunora init my-app -t tanstack-start-react","Scaffold a TanStack Start (React) app"],["lunora init my-app -t tanstack-start-solid","Scaffold a TanStack Start (Solid) app"],["lunora init my-app -t solid-v2","Scaffold a Solid 2.0 SPA"],["lunora init my-app -t rspack-react","Scaffold a React SPA on Rsbuild"],["lunora init my-app --ref alpha","Scaffold from the alpha branch's templates"],["lunora init --here","Add Lunora to the current project"],["lunora init my-app --ci github","Scaffold + add a GitHub Actions deploy pipeline"],["lunora init my-app --ci gitlab","Scaffold + add a GitLab CI deploy pipeline"]],group:"Project",loader:()=>import("../packem_chunks/runInitCommand.mjs").then(e=>({default:e.execute})),name:"init",options:[{alias:"t",description:"Template: analog | astro | expo | next | nuxt | react-router | rspack-react | solid-v2 | standalone | sveltekit | tanstack-start-react | tanstack-start-react-rspack | tanstack-start-solid | vinext | vinext-pages. Also accepts an overlay framework (react | vue | solid | svelte), same as --vite.",name:"template",type:String},{description:"Scaffold via the create-vite overlay for a framework (react | vue | solid | svelte | vanilla) — official create-vite base + Lunora layer",name:"vite",type:String},{description:"Local templates root to copy from (offline-friendly; expects <type>/ subdirs)",name:"from",type:String},{description:"Override the remote template source (e.g. gh:owner/repo/sub#ref)",name:"source",type:String},{description:"Fetch templates from a git ref (branch, tag, or commit), e.g. --ref alpha. Overrides the version-derived default",name:"ref",type:String},{description:"Permit --source values outside gh:/github:/https:// (e.g. local file://)",name:"allow-unsafe-source",type:Boolean},{description:"Add Lunora to the current project: detect the framework, patch the config, scaffold lunora/, print per-framework wiring steps",name:"here",type:Boolean},{alias:"i",description:"After scaffolding, offer to add auth + email (defaults on when stdin is a TTY)",name:"interactive",type:Boolean},{alias:"y",description:"Skip the auth/email offer; scaffold only",name:"yes",type:Boolean},{description:"Also scaffold a CI deploy pipeline: github (.github/workflows/deploy.yml) or gitlab (.gitlab-ci.yml)",name:"ci",type:String},{description:"Add features non-interactively after scaffolding (comma-separated): ai | auth | auth-ui | backup | browser | cloudflare-access | crons | email | flags | hyperdrive | payment | presence | queue | storage | workflow",name:"add",type:String},{description:"Walk through every step (prompts + output) without writing files, installing, or running git",name:"dry-run",type:Boolean}]},le={description:"Report write-conflict hot-spots, error rates, and latency outliers from a running Worker",examples:[["lunora insights","Report against the local dev worker"],["lunora insights --shard channel:demo","Scope the report to one shard"],["lunora insights --format json","Emit the raw report as JSON"],["lunora insights --prod --url https://app.example.com --token $LUNORA_ADMIN_TOKEN","Report against production"]],group:"Develop",loader:()=>import("../packem_chunks/handler10.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},a,{description:"Target production — requires an explicit --url",name:"prod",type:Boolean},{description:"Worker URL (default http://localhost:8787)",name:"url",type:String},{description:"Admin bearer token (or LUNORA_ADMIN_TOKEN)",name:"token",type:String}]},de={description:"Scaffold lunora/schema.ts (and list/get procedures) from an existing Postgres or MySQL database",examples:[["lunora introspect --url postgres://localhost/shop","Scaffold a schema + procedures from every table"],["lunora introspect --tables users,orders","Introspect only these tables (DATABASE_URL is read by default)"],["lunora introspect --dry-run","Print what would be written without touching the filesystem"],["lunora introspect --no-procedures --force","Regenerate just the schema, overwriting the existing file"]],group:"Data",loader:()=>import("../packem_chunks/handler27.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},a]},pe={description:"Link this checkout to its deployed Worker (writes .lunora/project.json)",examples:[["lunora link --url https://app.acme.workers.dev","Link to a deployed Worker URL"],["lunora link --url https://app.acme.workers.dev --env production","Link a named environment"],["lunora link --remove","Remove the link"]],group:"Deploy",loader:()=>import("../packem_chunks/handler11.mjs").then(e=>({default:e.execute})),name:"link",options:[{description:"Cloudflare environment name to record alongside the link",name:"env",type:String},{description:"Worker name (defaults to the `name` in wrangler config)",name:"name",type:String},{description:"Remove the existing link (.lunora/project.json)",name:"remove",type:Boolean},{description:"Deployed Worker URL to link (e.g. https://app.acme.workers.dev)",name:"url",type:String}]},ce={argument:{description:"Worker name (defaults to the name in wrangler config)",name:"worker",type:String},description:"Stream live logs from a deployed Worker, or read the durable log archive with --durable",group:"Deploy",loader:()=>import("../packem_chunks/handler25.mjs").then(e=>({default:e.execute})),name:"logs",options:[{description:"Cloudflare environment name",name:"env",type:String},a,{description:"Substring filter on log messages",name:"search",type:String},{description:"Filter by invocation status: ok, error, or canceled",name:"status",type:String},l,{description:"Tail a temporary-account deployment when unauthenticated (wrangler tail --temporary). Errors if you're already authenticated.",name:"temporary",type:Boolean},{description:"Read the durable log archive (pipelineLogSink → R2) via R2 SQL instead of tailing live",name:"durable",type:Boolean},{description:"durable: Iceberg table the Pipeline writes to (required with --durable)",name:"table",type:String},{description:"durable: Iceberg namespace (R2 Data Catalog database) the table lives in",name:"namespace",type:String},{description:"durable: lower time bound (epoch-millis or ISO 8601), inclusive",name:"since",type:String},{description:"durable: upper time bound (epoch-millis or ISO 8601), inclusive",name:"until",type:String},{description:"durable: exact severity filter (trace|debug|log|info|warn|error|fatal)",name:"level",type:String},{description:"durable: severity floor — this level and every more-severe one",name:"min-level",type:String},{description:"durable: keep function paths starting with this prefix (LIKE 'prefix%')",name:"function-prefix",type:String},{description:"durable: trace-id filter",name:"trace-id",type:String},{description:"durable: shard-key filter",name:"shard-key",type:String},{description:"durable: user-id filter",name:"user-id",type:String},{description:"durable: max rows (clamped to 1–10000; default 500)",name:"limit",type:String},{description:"durable: resume after a prior page — the opaque cursor token printed by the previous page (bare epoch-millis also accepted for back-compat)",name:"cursor",type:String},{description:"durable: emit one JSON object per line instead of a table",name:"ndjson",type:Boolean}]},ue={argument:{description:"install [client…] | uninstall [client…] | serve",name:"args",type:String},description:"Connect your AI editor to Lunora over MCP (docs search + this project's dev server)",examples:[["lunora mcp install","Install into every MCP client already configured here"],["lunora mcp install claude-code cursor","Install into specific clients"],["lunora mcp install --list","List the supported clients and their config files"],["lunora mcp install --docs-only","Install only the hosted documentation server"],["lunora mcp install --print","Show the config that would be written, without writing it"],["lunora mcp install --global","Force every server into the machine-wide config"],["lunora mcp uninstall","Remove Lunora's MCP servers from every supported client"],["lunora mcp uninstall cursor","Remove them from one client"],["lunora mcp uninstall --print","Show what would be removed, without removing it"],["lunora mcp serve","Run the stdio MCP server (this is what your editor spawns)"],["lunora mcp serve --allow-writes","Also expose the mutation/action tools"],["lunora mcp serve --token $LUNORA_ADMIN_TOKEN","Expose the observability tools (logs, issues, advisories, insights, migrations) too"]],group:"Develop",loader:()=>import("../packem_chunks/handler28.mjs").then(e=>({default:e.execute})),name:"mcp",options:[{description:"install: replace entries that already exist",name:"force",type:Boolean},{description:"install: list the supported clients and their config files",name:"list",type:Boolean},{description:"install/uninstall: print what would change instead of writing it",name:"print",type:Boolean},{description:"install/uninstall: only the hosted documentation server",name:"docs-only",type:Boolean},{description:"install/uninstall: only this project's local server",name:"local-only",type:Boolean},{description:"install/uninstall: the machine-wide config (install default: docs server global, local server per-project)",name:"global",type:Boolean},{description:"install/uninstall: this project's config instead of the machine-wide one",name:"project",type:Boolean},{description:"serve: also expose the mutation/action tools (default: read-only)",name:"allow-writes",type:Boolean},{description:"serve: expose the documentation tools (default)",name:"docs",type:Boolean},{description:"serve: skip the documentation tools",name:"no-docs",type:Boolean},{description:"Docs site origin backing the documentation tools (default https://lunora.sh)",name:"docs-url",type:String},{description:"serve: deployment URL to expose (default: the running dev server)",name:"url",type:String},{description:"serve: bearer token (default: LUNORA_ADMIN_TOKEN from the environment or .dev.vars). Also gates the observability tools (logs, issues, advisories, query insights, migration status) — without a token they are not exposed at all",name:"token",type:String}]},me={argument:{description:"generate | create | up | down | status | d1-to-hyperdrive [name|id]",name:"subcommand",type:String},description:"Schema (generate), online data (create | up | down | status), and backend (d1-to-hyperdrive) migrations",examples:[["lunora migrate generate","Diff lunora/schema.ts and emit a SQL migration"],["lunora migrate create add_users_email","Scaffold a data migration"],["lunora migrate up backfill-names","Run a data migration across shards"],["lunora migrate status backfill-names","Report a migration's per-shard status"],["lunora migrate status backfill-names --format json","Same, as a single JSON document on stdout"],["lunora migrate d1-to-hyperdrive --from-url https://old --to-url https://new","Copy .global() data from D1 to Hyperdrive"]],group:"Data",loader:()=>import("../packem_chunks/dispatch.mjs").then(e=>({default:e.execute})),name:"migrate",options:[{description:"Migration name slug (e.g. add_users_email)",name:"name",type:String},{description:"Target table for `create` (prompted for interactively when omitted)",name:"table",type:String},{description:"Preview a data migration without rewriting rows",name:"dry-run",type:Boolean},a,{description:"Rows per batch for a data migration",name:"batch-size",type:Number},{description:"Cap batches processed this run (maps to the runner's maxBatches)",name:"steps",type:Number},{description:"Target production — requires an explicit --url",name:"prod",type:Boolean},{description:"Worker URL (default http://localhost:8787)",name:"url",type:String},{description:"Admin bearer token (prefer LUNORA_ADMIN_TOKEN; --token is visible to other local processes via the process table)",name:"token",type:String},{description:"Required with --prod for up/down — confirms running against production",name:"yes",type:Boolean},{description:"d1-to-hyperdrive: source (D1) worker URL (defaults to --url)",name:"from-url",type:String},{description:"d1-to-hyperdrive: source admin token (defaults to --token / LUNORA_ADMIN_TOKEN)",name:"from-token",type:String},{description:"d1-to-hyperdrive: target (Hyperdrive) worker URL (defaults to --url)",name:"to-url",type:String},{description:"d1-to-hyperdrive: target admin token (defaults to --token / LUNORA_ADMIN_TOKEN)",name:"to-token",type:String},{description:"d1-to-hyperdrive: comma-separated .global() tables to move (default: all global tables)",name:"tables",type:String},{description:"d1-to-hyperdrive: keep the intermediate NDJSON dump at this path",name:"out",type:String}]},ge={description:"Run codegen + binding reconcile + wrangler validation (no Vite) — for CI",examples:[["lunora prepare","Codegen + binding reconcile + validate (CI, before deploy)"]],group:"Deploy",loader:()=>import("../packem_chunks/handler12.mjs").then(e=>({default:e.execute})),name:"prepare",options:[{description:"Override the schema-drift gate for this run (proceed even with breaking schema drift and no migration; the committed baseline is not advanced)",name:"allow-schema-drift",type:Boolean},{description:`Which API spec(s) to emit: ${p} (default openapi)`,name:"api-spec",type:String},{description:"Fail on ERROR-level codegen advisories even locally (the gate already defaults to on in CI)",name:"strict-advisories",type:Boolean},{description:"Don't fail on ERROR-level codegen advisories (the gate defaults to on in CI, off locally). Never downgrades platform diagnostics.",name:"no-strict-advisories",type:Boolean},l,{description:"Re-bless the committed schema baseline (lunora/.lunora-schema.json) with the current shape",name:"update-schema-baseline",type:Boolean}]},he={argument:{description:"<add|list|view|build> [item names…]",name:"args",type:String},description:"Component registry: add/list/view items, or build the catalog",examples:[["lunora registry list","List available registry items"],["lunora registry add presence","Scaffold a registry item into lunora/"],["lunora registry build --from ./registry --check","Verify the committed catalog is current"]],group:"Project",loader:()=>import("../packem_chunks/handler13.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},{...a,description:"Output format: pretty (default) or json (add plan / list)"},{description:"build: output path for the catalog (default <root>/index.json)",name:"out",type:String},{description:"build: verify the index is current instead of rewriting it",name:"check",type:Boolean}]},fe={description:"Clear local Miniflare state (and .lunora-cache with --all)",examples:[["lunora reset","Clear local Miniflare state"],["lunora reset --all","Also remove .lunora-cache"]],group:"Develop",loader:()=>import("../packem_chunks/runResetCommand.mjs").then(e=>({default:e.execute})),name:"reset",options:[{description:"Also remove .lunora-cache",name:"all",type:Boolean},{description:"Skip the confirmation prompt (required when stdin is not a TTY)",name:"yes",type:Boolean}]},ye={argument:{description:"install | check",name:"subcommand",type:String},description:"Install the Lunora agent skills (AI rules) into .agents/skills/, or check they're present",examples:[["lunora rules install","Copy the Lunora agent skills into .agents/skills/"],["lunora rules install --overwrite","Reinstall, replacing edited skill files"],["lunora rules check","Report which Lunora skills are installed"],["lunora rules check --strict","Exit non-zero when rules are missing (CI gate)"],["lunora rules install --dir packages/app","Install into a specific root instead of the workspace root"]],group:"Project",loader:()=>import("../packem_chunks/handler14.mjs").then(e=>({default:e.execute})),name:"rules",options:[{description:"Install/check root (default: the detected workspace root, not the current directory)",name:"dir",type:String},{description:"install: overwrite skill files that already exist (default: skip them)",name:"overwrite",type:Boolean},{description:"check: exit non-zero when the rules are missing (for CI gating)",name:"strict",type:Boolean}]},ve={argument:{description:"Function path (e.g. messages:send)",name:"functionPath",type:String},description:"Send a single RPC to a running Lunora Worker",examples:[[`lunora run messages:send --args '{"text":"hi"}'`,"Call a function with JSON args"],["lunora run messages:list --shard channel:demo","Target a specific shard"],["lunora run messages:list --as user_123","Run as an authenticated user (needed when the app gates on identity)"],["lunora run messages:list --format json","Emit the RPC result as a single JSON document on stdout"]],group:"Develop",loader:()=>import("../packem_chunks/runRpcCommand.mjs").then(e=>({default:e.execute})),name:"run",options:[{description:"JSON-encoded args object",name:"args",type:String},{description:"Run as this user id — dispatches through the admin-gated `runAs` op so identity-gated apps accept the call",name:"as",type:String},{description:`JSON-encoded extra identity claims to forge alongside --as (e.g. '{"org":"acme"}')`,name:"claims",type:String},{description:"Explicit shard key",name:"shard",type:String},a,{description:"Worker URL (defaults to the running dev server, else http://localhost:8787)",name:"url",type:String},{description:"Admin bearer for --as (prefer LUNORA_ADMIN_TOKEN or .dev.vars; --token is visible to other local processes via the process table)",name:"token",type:String}]},be={argument:{description:"<generate>",name:"args",type:String},description:"Generate a self-contained typed client SDK for another language from the project's OpenRPC surface",examples:[["lunora sdk generate --lang python","Emit a Python SDK, transport included, into ./sdk/python"],["lunora sdk generate --lang go --out ./clients/go","Choose the language and output directory"],["lunora sdk generate --lang dart","A Flutter-ready Dart client — live queries arrive as a Stream"],["lunora sdk generate --lang kotlin","Any of the registered targets; --lang lists them"],["lunora sdk generate --lang rust --from ./sdks","Copy the transport from a local checkout instead of fetching it"]],group:"Project",loader:()=>import("../packem_chunks/handler22.mjs").then(e=>({default:e.execute})),name:"sdk",options:[{description:`Target language: ${E.join(" | ")}`,name:"lang",type:String},{description:"Output directory (default ./sdk/<lang>)",name:"out",type:String},{description:"Path to the OpenRPC document (default ./lunora/_generated/openrpc.json)",name:"spec",type:String},{description:"Copy the transport from a local directory of per-language transports (the repo's `sdks/`) instead of fetching it",name:"from",type:String},{description:"Git ref to fetch the transport from (default: this CLI's own release tag, so the transport matches the generated surface)",name:"ref",type:String},{description:"Override the remote transport source base (default gh:anolilab/lunora/sdks)",name:"source",type:String},{description:"Permit --source values outside gh:/github:/https://",name:"allow-unsafe-source",type:Boolean}]},we={description:"Generate deterministic fake data from lunora/schema.ts and bulk-insert it via the worker's admin endpoint",examples:[["lunora seed","Seed every table with the default row count"],["lunora seed --table posts --count 50","Seed 50 posts; FK-parent tables are seeded automatically"],["lunora seed --reset","Wipe local .wrangler/state, then seed from scratch"],["lunora seed --seed 7 --dry-run","Print the NDJSON for seed 7 without inserting"],["lunora seed --format json","Report generated / inserted / conflicts per table as JSON"],["lunora seed --seed 7 --now 1785000000000","Byte-identical rows across runs (pins the clock too)"]],group:"Data",loader:()=>import("../packem_chunks/handler15.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},a,{description:"Wipe local .wrangler/state before seeding (local dev only)",name:"reset",type:Boolean},{description:"Rows per HTTP request (default 500)",name:"batch-size",type:Number},{description:"Target production — requires an explicit --url",name:"prod",type:Boolean},{description:"Worker URL (default http://localhost:8787)",name:"url",type:String},{description:"Admin bearer token (prefer LUNORA_ADMIN_TOKEN; --token is visible to other local processes via the process table)",name:"token",type:String},{description:"Skip the confirmation prompt when seeding a non-local/production target",name:"yes",type:Boolean}]},ke={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/handler16.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},a,{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}]},Se={description:"Validate wrangler.jsonc + codegen dry-run + tsc --noEmit (no files written)",examples:[["lunora verify","Validate wrangler + codegen + tsc"],["lunora verify --no-typecheck","Skip the TypeScript type-check"],["lunora verify --health-url https://my-app.workers.dev","Also probe the deployment's /_lunora/health"],["lunora verify --env production","Validate the env.production view, as `lunora deploy --env production` will"]],group:"Deploy",loader:()=>import("../packem_chunks/handler17.mjs").then(e=>({default:e.execute})),name:"verify",options:[{description:"Treat breaking schema drift as a warning instead of a failure",name:"allow-schema-drift",type:Boolean},{description:`Which API spec(s) to emit: ${p} (default openapi)`,name:"api-spec",type:String},{description:"Cloudflare environment name — validate the env.<name> view of wrangler.jsonc, as `lunora deploy --env` does",name:"env",type:String},a,{description:"Probe this deployment's /_lunora/health endpoint (off by default; keeps verify offline-safe)",name:"health-url",type:String},{description:"Fail verification on ERROR-level codegen advisories even locally (the gate already defaults to on in CI)",name:"strict-advisories",type:Boolean},{description:"Don't fail verification on ERROR-level codegen advisories (the gate defaults to on in CI, off locally). Never downgrades platform diagnostics.",name:"no-strict-advisories",type:Boolean},{description:"Run the TypeScript type-check step (default)",name:"typecheck",type:Boolean},{description:"Skip the TypeScript type-check step",name:"no-typecheck",type:Boolean},l]},xe={description:"Open the Lunora studio in your browser (the running dev server's, or the default local one)",examples:[["lunora view","Open the studio for the running dev server"]],group:"Project",loader:()=>import("../packem_chunks/handler18.mjs").then(e=>({default:e.execute})),name:"view"},Ce=(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 i=1;i<=t.length;i+=1){const s=r[i]??0,c=e[o-1]===t[i-1]?0:1;r[i]=Math.min((r[i-1]??0)+1,s+1,n+c),n=s}}return r[t.length]??0},Re=(e,t)=>{let r,o=Number.POSITIVE_INFINITY;for(const i of t){const s=Ce(e,i);s<o&&(o=s,r=i)}const n=Math.max(2,Math.ceil(e.length/3));return r!==void 0&&o<=n?r:void 0},Ne=e=>`https://registry.npmjs.org/@lunora/cli/${e}`,Oe=1440*60*1e3,Ae=1500,Be="0.0.0",De=/^v/u,Ee=new Set(["alpha","beta","next"]),m=e=>{const t=e.trim().replace(De,""),r=t.indexOf("-");return r===-1?{core:t,prerelease:""}:{core:t.slice(0,r),prerelease:t.slice(r+1)}},b=e=>{const[t,r,o]=m(e).core.split(".").map(n=>{const i=Number.parseInt(n,10);return Number.isFinite(i)?i:0});return[t??0,r??0,o??0]},Ie=(e,t)=>{const r=Number.parseInt(e,10),o=Number.parseInt(t,10);return String(r)===e&&String(o)===t?r>o?1:-1:e>t?1:-1},Le=(e,t)=>{if(e===t)return 0;if(e===""||t==="")return e===""?1:-1;const r=e.split("."),o=t.split(".");for(let n=0;n<Math.max(r.length,o.length);n+=1){const i=r[n],s=o[n];if(i===void 0||s===void 0)return i===void 0?-1:1;if(i!==s)return Ie(i,s)}return 0},je=(e,t)=>{const r=b(e),o=b(t);for(let n=0;n<3;n+=1)if((r[n]??0)!==(o[n]??0))return(r[n]??0)>(o[n]??0)?1:-1;return Le(m(e).prerelease,m(t).prerelease)},Te=e=>{const t=m(e).prerelease.split(".")[0]??"";return Ee.has(t)?t:"latest"},Pe=(e,t)=>je(t,e)>0,_e=(e,t,r)=>t-e<r,Ue=(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:i,command:s}=F(o,[`@lunora/cli@${r}`],{dev:!0});return`${n} — run \`${s} ${i.join(" ")}\``},S=e=>f(e,"lunora-cli-update.json"),Me=e=>{const t=e.XDG_CACHE_HOME&&e.XDG_CACHE_HOME.length>0?e.XDG_CACHE_HOME:f(W(),".cache"),r=f(t,"lunora");try{P(r,{mode:448,recursive:!0})}catch{}return r},We=e=>{try{const t=JSON.parse(_(S(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{}},w=(e,t)=>{try{const r=S(e);try{if(U(r).isSymbolicLink())return}catch{}M(r,`${JSON.stringify(t)}
2
- `,"utf8")}catch{}},Fe=async(e,t)=>{try{const r=await e(Ne(t),{signal:AbortSignal.timeout(Ae)});if(!r.ok)return;const o=await r.json(),n=o!==null&&typeof o=="object"?o.version:void 0;return typeof n=="string"?n:void 0}catch{return}},Je=(e,t,r)=>e===Be||!r||t.CI!==void 0||t.LUNORA_NO_UPDATE_NOTIFIER!==void 0,Ke=async e=>{const t=e.env??process.env,r=e.isTTY??process.stdout.isTTY;if(Je(e.current,t,r))return;const o=e.cacheDir??Me(t),n=(e.now??Date.now)(),i=e.ttlMs??Oe,s=Te(e.current),c=We(o),R=c?.tag??"latest",g=c!==void 0&&R===s?c:void 0;let u=g?.latest;if(g===void 0||!_e(g.checkedAt,n,i)){const h=await Fe(e.fetchImpl??globalThis.fetch,s);h===void 0?w(o,{checkedAt:n,latest:e.current,tag:s}):(u=h,w(o,{checkedAt:n,latest:h,tag:s}))}u!==void 0&&Pe(e.current,u)&&e.logger.warn(Ue(e.current,u,s,e.manager))},$e=["init","add","dev","codegen","build","deploy","containers","ai","prepare","link","deployments","logs","run","insights","reset","migrate","export","import","seed","shards","backup","eval","verify","info","doctor","env","analyze","view","docs","registry","rules","mcp"],x=I(),qe=[se,K,Z,z,$,G,Q,Y,q,ge,pe,X,ce,ve,le,fe,me,ne,ae,we,ke,de,V,oe,Se,ie,te,re,H,xe,ee,he,ye,ue,be],C=[...qe,D,B],mt=C.map(e=>e.name),d=e=>e.replaceAll("{",String.raw`\{`).replaceAll("}",String.raw`\}`),He=e=>e.every(t=>typeof t=="string")?e.map(t=>d(t)):e.map(t=>typeof t=="string"?[d(t)]:t.map(r=>d(r))),Ve=e=>({...e,...e.argument===void 0?{}:{argument:{...e.argument,description:d(e.argument.description??"")}},...e.description===void 0?{}:{description:d(e.description)},...e.examples===void 0?{}:{examples:He(e.examples)},...e.options===void 0?{}:{options:e.options.map(t=>({...t,description:d(t.description??"")}))}}),Ge=e=>{const t={value:0},r=A("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:x});for(const o of C)r.addCommand(Ve(o));return{cli:r,exitCode:t}},ze=/Command "(?<name>[^"]+)" not found/u,Ye=e=>{const t=k(),r=e instanceof Error?e.message:String(e),o=ze.exec(r);if(!o?.groups)return N(e)||O(r)!==void 0?t.error(T(e)):t.error(r),L(e);const n=o.groups.name??"",i=Re(n,$e);return t.error(`Unknown command "${n}".${i===void 0?"":` Did you mean "${i}"?`}`),t.info("Run `lunora --help` to list commands, or `lunora docs` to open the documentation."),j.USAGE},Qe=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)}}),gt=async(e={})=>{const{cli:t,exitCode:r}=Ge(e);e.logger!==void 0&&y(Qe(e.logger));try{await t.run({shouldExitProcess:!1})}catch(n){return Ye(n)}finally{y(void 0)}let o;try{o=J(process.cwd())}catch{}return await Ke({current:x,logger:k(),manager:o}),r.value};export{$e as C,v as D,mt as R,x as V,gt as r};
@@ -1 +0,0 @@
1
- import{r as $}from"./cloudflare-credentials-lC5JtPLe.mjs";const C="https://api.cloudflare.com/client/v4/accounts",b=async({accountId:e,apiToken:r,fetch:t,init:s,path:a})=>{const c=await(t??globalThis.fetch.bind(globalThis))(`${C}/${encodeURIComponent(e)}${a}`,{...s,headers:{Authorization:`Bearer ${r}`,"Content-Type":"application/json"}}),o=await c.text();let n;try{n=JSON.parse(o)}catch{return{ok:!1,status:c.status,text:o}}return!c.ok||typeof n!="object"||n===null||n.success===!1?{ok:!1,status:c.status,text:o}:{body:n,ok:!0}},v=5e3,p=(e,r,t)=>`POST https://api.cloudflare.com/client/v4/accounts/${e}/artifacts/namespaces with body { "namespace": "${r}", "jurisdiction": "${t}" }`,P=async e=>{const{binding:r,jurisdiction:t,namespace:s}=e,a=`Artifacts namespace "${s}" (binding ${r})`,{accountId:c,token:o}=$(e.environment??process.env,e.accountId);if(o===void 0||c===void 0)return{fix:"Set CLOUDFLARE_API_TOKEN (with Artifacts read access) and CLOUDFLARE_ACCOUNT_ID (or `account_id` in wrangler.jsonc) to check it.",message:`the jurisdiction of ${a} was not checked against the schema's "${t}".`,verdict:"unchecked"};let n;try{n=await b({accountId:c,apiToken:o,...e.fetch===void 0?{}:{fetch:e.fetch},init:{signal:AbortSignal.timeout(v)},path:`/artifacts/namespaces/${encodeURIComponent(s)}`})}catch(l){return{message:`the jurisdiction of ${a} could not be read (${l instanceof Error?l.message:String(l)}).`,verdict:"unchecked"}}if(!n.ok&&n.status===404)return{fix:`Create it before the first repo: ${p(c,s,t)}.`,message:`${a} does not exist, and the first repo create() would make it unrestricted — the schema pins data to "${t}".`,verdict:"missing"};if(!n.ok)return{...n.status===401||n.status===403?{fix:`Give CLOUDFLARE_API_TOKEN Artifacts read access on account ${c}.`}:{},message:`the jurisdiction of ${a} could not be read (HTTP ${String(n.status)}).`,verdict:"unchecked"};const{result:i}=n.body,u=typeof i=="object"&&i!==null&&"jurisdiction"in i?i.jurisdiction:void 0;return typeof u!="string"?{message:`the jurisdiction of ${a} could not be read (the response carried none).`,verdict:"unchecked"}:u===t?{message:`${a} is in the "${u}" jurisdiction, as the schema pins.`,verdict:"ok"}:{fix:`A namespace's jurisdiction cannot change: create one with ${p(c,"<name>",t)}, point the binding's "namespace" at it, and move the repos over.`,message:`${a} is in the "${u}" jurisdiction, but the schema pins data to "${t}".`,verdict:"mismatch"}},h=100,d=500,m=10,T=5e3,f="Delete the Workers you no longer need (old preview / staging deploys free their classes), or set `durableObjects: { merge: true }` in lunora.config before an app's first deploy so it spends one class instead of up to three.",k=e=>e>=d?{fix:f,message:`the Cloudflare account has ${String(e)} Durable Object classes — the Workers Paid cap is ${String(d)}, so a deploy that adds one will fail.`,verdict:"full"}:e>=d-m?{fix:f,message:`the Cloudflare account has ${String(e)} of ${String(d)} Durable Object classes (Workers Paid cap).`,verdict:"near"}:e>=h-m&&e<=h?{fix:f,message:`the Cloudflare account has ${String(e)} Durable Object classes — on Workers Free the cap is ${String(h)} (Paid: ${String(d)}).`,verdict:"near"}:{message:`the Cloudflare account has ${String(e)} Durable Object classes (caps: ${String(h)} Free, ${String(d)} Paid).`,verdict:"ok"},x=async(e={})=>{const{accountId:r,token:t}=$(e.environment??process.env,e.accountId);if(t===void 0||r===void 0)return{fix:"Set CLOUDFLARE_API_TOKEN (Workers Scripts Read) and CLOUDFLARE_ACCOUNT_ID (or `account_id` in wrangler.jsonc) to check it.",message:"the account's Durable Object class count was not checked.",verdict:"unchecked"};try{const s=await b({accountId:r,apiToken:t,...e.fetch===void 0?{}:{fetch:e.fetch},init:{signal:AbortSignal.timeout(T)},path:"/workers/durable_objects/namespaces?per_page=1"}),a=s.ok?s.body.result_info:void 0,c=typeof a=="object"&&a!==null&&"total_count"in a?a.total_count:void 0;return typeof c!="number"?{message:`the account's Durable Object class count could not be read${s.ok?"":` (HTTP ${String(s.status)})`}.`,verdict:"unchecked"}:k(c)}catch(s){return{message:`the account's Durable Object class count could not be read (${s instanceof Error?s.message:String(s)}).`,verdict:"unchecked"}}},D=e=>{switch(e){case"boolean":return"boolean";case"date":case"number":case"timestamp":return"number";case"id":case"literal":case"string":return"string";default:return}},j=/already (?:exists|indexed)|duplicate/iu,g=e=>["vectorize","create-metadata-index",e.index,`--property-name=${e.property}`,`--type=${e.type}`],y=async(e,r)=>{try{return await e(r)}catch(t){return{code:1,stderr:t instanceof Error?t.message:String(t)}}},w=async e=>{const{cwd:r,entries:t,exec:s,logger:a,spawner:c}=e,o=[];for(const n of t){const i=await y(c,{args:[...s.args,...g(n)],captureStderr:!0,command:s.command,cwd:r,stdoutToStderr:!0});if(i.code===0){o.push({entry:n,status:"created"});continue}const u=`${i.stderr??""}${i.stdout??""}`;if(j.test(u)){o.push({entry:n,status:"exists"});continue}o.push({entry:n,error:u.trim()||`exit code ${String(i.code)}`,status:"failed"}),a.warn(`could not create the Vectorize metadata index for "${n.property}" on "${n.index}" — filters on that property will match nothing until it exists. Run: wrangler ${g(n).join(" ")}`)}return o},S=e=>e.endsWith("S")?e.slice(0,-1):e,E=e=>e.replaceAll(/([a-z\d])([A-Z])/gu,"$1_$2").toUpperCase().split(/[_-]+/u).filter(r=>r.length>0),A=new Set(["CREDENTIAL","DSN","PASSPHRASE","PASSWD","PASSWORD","SECRET","TOKEN"]),_=["ACCESS_KEY","API_KEY","ENCRYPTION_KEY","PRIVATE_KEY","SIGNING_KEY"],O=new RegExp(`(?:${[...A,..._.map(e=>e.replaceAll("_",""))].join("|")})S?$`,"iu"),I=e=>E(e).some(r=>r==="PUBLIC"||r==="PUBLISHABLE"),L=e=>{if(I(e))return!1;const r=E(e);if(r.some(s=>A.has(S(s))))return!0;const t=S(r.join("_"));return _.some(s=>t===s||t.endsWith(`_${s}`))||O.test(e)};export{x as a,P as b,g as c,w as e,L as i,D as m};