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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (43) hide show
  1. package/dist/bin.mjs +1 -1
  2. package/dist/index.d.mts +2 -2
  3. package/dist/index.d.ts +2 -2
  4. package/dist/index.mjs +1 -1
  5. package/dist/packem_chunks/handler10.mjs +1 -2
  6. package/dist/packem_chunks/handler11.mjs +1 -1
  7. package/dist/packem_chunks/handler12.mjs +1 -1
  8. package/dist/packem_chunks/handler13.mjs +3 -1
  9. package/dist/packem_chunks/handler14.mjs +1 -1
  10. package/dist/packem_chunks/handler15.mjs +1 -3
  11. package/dist/packem_chunks/handler16.mjs +1 -1
  12. package/dist/packem_chunks/handler17.mjs +7 -1
  13. package/dist/packem_chunks/handler18.mjs +1 -1
  14. package/dist/packem_chunks/handler19.mjs +3 -7
  15. package/dist/packem_chunks/handler20.mjs +3 -1
  16. package/dist/packem_chunks/handler21.mjs +1 -1
  17. package/dist/packem_chunks/handler22.mjs +2 -3
  18. package/dist/packem_chunks/handler23.mjs +1 -3
  19. package/dist/packem_chunks/handler24.mjs +99 -1
  20. package/dist/packem_chunks/handler25.mjs +10 -2
  21. package/dist/packem_chunks/handler26.mjs +1 -1
  22. package/dist/packem_chunks/handler3.mjs +1 -1
  23. package/dist/packem_chunks/handler4.mjs +3 -1
  24. package/dist/packem_chunks/handler5.mjs +1 -1
  25. package/dist/packem_chunks/handler6.mjs +1 -3
  26. package/dist/packem_chunks/handler7.mjs +1 -1
  27. package/dist/packem_chunks/handler8.mjs +2 -1
  28. package/dist/packem_chunks/handler9.mjs +1 -1
  29. package/dist/packem_chunks/runDeployCommand.mjs +1 -1
  30. package/dist/packem_shared/{COMMANDS-CWnIJmxM.mjs → COMMANDS-DKQ655_4.mjs} +1 -1
  31. package/dist/packem_shared/cli-C74xjzMK.mjs +2 -0
  32. package/dist/packem_shared/cloudflare-credentials-BVmZnDZk.mjs +1 -0
  33. package/dist/packem_shared/{docker-DpVxvYpL.mjs → docker-AqLAkOyY.mjs} +1 -1
  34. package/dist/packem_shared/secret-key-6bCftsxj.mjs +1 -0
  35. package/dist/packem_shared/variables-CPYyJtsL.mjs +1 -0
  36. package/package.json +5 -5
  37. package/skills/lunora-deploy/SKILL.md +4 -4
  38. package/dist/packem_chunks/handler27.mjs +0 -99
  39. package/dist/packem_chunks/handler28.mjs +0 -10
  40. package/dist/packem_shared/cli-6BRlq6nw.mjs +0 -2
  41. package/dist/packem_shared/cloudflare-credentials-lC5JtPLe.mjs +0 -1
  42. package/dist/packem_shared/secret-key-BCrqNJ68.mjs +0 -1
  43. package/dist/packem_shared/variables-acxcvVQa.mjs +0 -1
@@ -1 +1,99 @@
1
- import{readdirSync as g,lstatSync as S,existsSync as y}from"node:fs";import{join as E,basename as T}from"node:path";import{pathToFileURL as w}from"node:url";import{d as R}from"../packem_shared/command-CAXl2A1S.mjs";import{EXIT_CODE as u}from"../packem_shared/EXIT_CODE-D_XCixv8.mjs";const l=".eval.ts",$=new Set([".git","_generated","dist","node_modules"]),v=(e,s=[])=>{let r;try{r=g(e)}catch{return s}for(const t of r){const o=E(e,t);let n;try{n=S(o)}catch{continue}if(n.isDirectory()){if($.has(t))continue;v(o,s)}else n.isFile()&&t.endsWith(l)&&s.push(o)}return s.toSorted((t,o)=>t.localeCompare(o))},_=e=>typeof e=="object"&&e!==null&&typeof e.run=="function",m=e=>typeof e=="number"&&Number.isFinite(e)&&e>=0&&e<=1,F="evals",O='"lunora eval" needs native TypeScript execution — run Node ≥23.6, or a TS loader/transform (tracked in plans/245-eval-runner-design.md §8.3)',N=/unknown file extension ".ts"/i,p=e=>e instanceof Error?e.code==="ERR_UNKNOWN_FILE_EXTENSION"?!0:N.test(e.message):!1,f=e=>T(e,l),x=e=>({average:e.result?.average,error:e.error,items:e.result?.items,name:e.name,passed:e.passed,path:e.path,threshold:e.threshold}),b=e=>({evals:e.evals.map(s=>x(s))}),i=(e,s,r)=>(e.error(s),{code:r,error:s,evals:[]}),A=(e,s,r)=>{if(!y(e))return r.info(`eval: no "${s}" directory — nothing to run`),[];const t=v(e);return t.length===0&&r.info(`eval: no ${l} files found under "${s}"`),t},I=async e=>{const r=(await import(w(e).href)).default;if(!_(r))throw new Error("does not default-export an eval module (expected `{ run(): Promise<EvalResult>, name?, threshold? }`)");return r},L=async(e,s)=>{let r;try{r=await I(e)}catch(n){if(p(n))throw n;return{error:n instanceof Error?n.message:String(n),name:f(e),passed:!1,path:e}}const t=r.name??f(e);if(r.threshold!==void 0&&!m(r.threshold))return{error:`invalid \`threshold\` export: must be a number in [0, 1] — received ${JSON.stringify(r.threshold)}`,name:t,passed:!1,path:e};const o=r.threshold??s;try{const n=await r.run(),a=o===void 0||n.average>=o;return{name:t,passed:a,path:e,result:n,threshold:o}}catch(n){return{error:n instanceof Error?n.message:String(n),name:t,passed:!1,path:e,threshold:o}}},U=async(e,s)=>{const r=[];for(const t of e)r.push(await L(t,s));return r},D=e=>{if(e.error!==void 0)return`ERROR: ${e.error}`;const s=e.passed?"pass":"FAIL",r=e.result?.items.length??0;return`${s} (${String(r)} cases)`},C=e=>{if(e.length===0)return[];const s=Math.max(4,...e.map(t=>t.name.length)),r=[`${"NAME".padEnd(s)} SCORE THRESHOLD STATUS`];for(const t of e){const o=t.result===void 0?"—":t.result.average.toFixed(3),n=t.threshold===void 0?"—":t.threshold.toFixed(3);r.push(`${t.name.padEnd(s)} ${o.padEnd(6)} ${n.padEnd(9)} ${D(t)}`)}return r},M=async e=>{const s=e.cwd??process.cwd(),{logger:r}=e;if(e.threshold!==void 0&&!m(e.threshold))return i(r,`eval: --threshold must be a number in [0, 1] — received "${String(e.threshold)}"`,u.USAGE);const t=e.dir??F,o=E(s,t),n=A(o,t,r);let a;try{a=await U(n,e.threshold)}catch(d){if(!p(d))throw d;return i(r,O,1)}if(e.threshold!==void 0&&a.length===0){const d=`eval: --threshold ${String(e.threshold)} was set but 0 eval files were discovered under "${t}" — nothing was gated`;return i(r,d,u.USAGE)}for(const d of C(a))r.info(d);const c=a.filter(d=>!d.passed),h=c.length>0?1:0;return h===0?r.success(`eval: ${String(a.length)} eval(s) passed`):r.error(`eval: ${String(c.length)}/${String(a.length)} eval(s) failed`),{code:h,evals:a}},V=R(async({cwd:e,format:s,logger:r,options:t})=>{const o=await M({cwd:e,dir:t.dir,format:s,logger:r,threshold:t.threshold});return{code:o.code,data:b(o),error:o.error}});export{V as execute,M as runEvalCommand};
1
+ import{existsSync as O,readFileSync as k}from"node:fs";import{writeFile as I,mkdir as U}from"node:fs/promises";import{addArgsFor as B,detectPackageManager as F,parseSchema as Y,applyAdditiveEdit as q,projectUsesUmbrella as P}from"@lunora/config";import{join as _}from"@visulima/path";import{d as H}from"../packem_shared/command-CAXl2A1S.mjs";import{EXIT_CODE as L}from"../packem_shared/EXIT_CODE-D_XCixv8.mjs";import{createRequire as K}from"node:module";import{LunoraError as N}from"@lunora/errors";const j=/^\//,G=(e,r)=>{try{const{args:n,command:t}=B(F(e),[r],{dev:!0});return`${t} ${n.join(" ")}`}catch{return`<your-package-manager> add -D ${r}`}},T=(e,r,n)=>{const t=K(_(n,"noop.cjs"));try{t.resolve(e)}catch{throw new N("INTERNAL",`\`lunora introspect\` needs the \`${r}\` driver to read this database, and it isn't installed.
2
+
3
+ Install it in your project:
4
+
5
+ ${G(n,r)}`)}return t(e)},Q=e=>{const r=e.slice(0,Math.max(0,e.indexOf(":"))).toLowerCase();if(r==="postgres"||r==="postgresql")return"postgres";if(r==="mysql"||r==="mariadb")return"mysql";throw new N("INTERNAL",`Unrecognised database URL scheme \`${r}\`. Expected a \`postgres://\`, \`postgresql://\`, \`mysql://\`, or \`mariadb://\` connection string.`)},J=e=>{try{const r=new URL(e).pathname.replace(j,"");return r===""?void 0:decodeURIComponent(r)}catch{return}},W=async(e,r,n,t=process.cwd())=>{if(r==="postgres"){const m=T("pg","pg",t).Client,u=new m({connectionString:e});return await u.connect(),{close:async()=>{await u.end()},execute:async(l,p)=>(await u.query(l,[...p])).rows,schema:n??"public"}}const a=T("mysql2/promise","mysql2",t).createConnection,o=await a(e),i=n??J(e);if(i===void 0)throw new N("INTERNAL","A MySQL connection string must name a database (`mysql://host/<database>`), or pass `--schema`.");return{close:async()=>{await o.end()},execute:async(c,m)=>{const[u]=await o.execute(c,[...m]);return Array.isArray(u)?u:[]},schema:i}},h=new Set(["_creationTime","_id"]),X={bigint:"v.bigint()",bigserial:"v.bigint()",bit:"v.string()",bool:"v.boolean()",boolean:"v.boolean()",box:"v.string()",bpchar:"v.string()",bytea:"v.bytes()",char:"v.string()",character:"v.string()","character varying":"v.string()",cidr:"v.string()",circle:"v.string()",citext:"v.string()",date:"v.date()","double precision":"v.number()",float4:"v.number()",float8:"v.number()",inet:"v.string()",int:"v.number()",int2:"v.number()",int4:"v.number()",int8:"v.bigint()",integer:"v.number()",interval:"v.string()",json:"v.any()",jsonb:"v.any()",line:"v.string()",lseg:"v.string()",macaddr:"v.string()",money:"v.number()",name:"v.string()",numeric:"v.number()",path:"v.string()",point:"v.string()",polygon:"v.string()",real:"v.number()",serial:"v.number()",smallint:"v.number()",smallserial:"v.number()",text:"v.string()",time:"v.string()","time with time zone":"v.string()","time without time zone":"v.string()",timestamp:"v.timestamp()","timestamp with time zone":"v.timestamp()","timestamp without time zone":"v.timestamp()",timestamptz:"v.timestamp()",tsquery:"v.string()",tsvector:"v.string()",uuid:"v.string()",varbit:"v.string()",varchar:"v.string()",xml:"v.string()"},z={bigint:"v.bigint()",binary:"v.bytes()",bit:"v.number()",blob:"v.bytes()",char:"v.string()",date:"v.date()",datetime:"v.timestamp()",decimal:"v.number()",double:"v.number()",enum:"v.string()",float:"v.number()",int:"v.number()",integer:"v.number()",json:"v.any()",longblob:"v.bytes()",longtext:"v.string()",mediumblob:"v.bytes()",mediumint:"v.number()",mediumtext:"v.string()",numeric:"v.number()",set:"v.string()",smallint:"v.number()",text:"v.string()",time:"v.string()",timestamp:"v.timestamp()",tinyblob:"v.bytes()",tinyint:"v.number()",tinytext:"v.string()",varbinary:"v.bytes()",varchar:"v.string()",year:"v.number()"},w=(e,r)=>{const t=(r==="postgres"?X:z)[e.dataType],s=e.references===void 0?t:`v.id(${JSON.stringify(e.references.table)})`;let a=s??"v.any()";for(let o=0;o<e.arrayDepth;o+=1)a=`v.array(${a})`;return e.nullable&&(a=`v.optional(${a})`),{expression:a,known:s!==void 0}},M=/^[A-Z_$][\w$]*$/i,Z=/[^\dA-Z]+(.)?/gi,V=/^\d+/,ee=/[^\w-]/g,ne=/[\u003C\u003E\u002F\u2028\u2029]/g,te={"/":String.raw`\u002F`,"\u2028":String.raw`\u2028`,"\u2029":String.raw`\u2029`,"<":String.raw`\u003C`,">":String.raw`\u003E`},f=e=>JSON.stringify(e).replaceAll(ne,r=>te[r]??r),S=e=>M.test(e)?e:f(e),re=e=>M.test(e)?`.${e}`:`[${f(e)}]`,x=e=>e.replaceAll("*/",String.raw`*\/`),ae=e=>{const r=e.replaceAll(ee,"_");return r===""?"table":r},se=e=>{const n=e.replaceAll(Z,(t,s)=>s?.toUpperCase()??"").replace(V,"");return n===""?"table":`${n.charAt(0).toLowerCase()}${n.slice(1)}`},C=e=>e.columns.filter(r=>!h.has(r.name)),oe=e=>{const r=new Set(e.primaryKey);for(const n of e.indexes)for(const t of n.columns)r.add(t);for(const n of e.columns)n.references!==void 0&&r.add(n.name);return[...r].filter(n=>!h.has(n))},D=(e,r,n,t)=>e.references===void 0||r.has(e.references.table)?e:(t.push(`${n}.${e.name}: references \`${e.references.table}\`, which isn't in the generated schema — emitted as a plain column instead of \`v.id(...)\`.`),{arrayDepth:e.arrayDepth,dataType:e.dataType,name:e.name,nullable:e.nullable}),ie=(e,r,n,t)=>{const s=[];for(const o of e.columns){if(h.has(o.name)){t.push(`${e.name}.${o.name}: skipped — \`${o.name}\` is a Lunora system column. Rename it in the source database or map it by hand.`);continue}const i=D(o,n,e.name,t),{expression:c,known:m}=w(i,r);!m&&i.references===void 0&&(t.push(`${e.name}.${o.name}: no mapping for SQL type \`${o.dataType}\` — emitted as \`v.any()\`.`),s.push(` // TODO: \`${x(o.dataType)}\` has no direct validator; narrow this.`)),s.push(` ${S(o.name)}: ${c},`)}const a=[' .global({ backend: "hyperdrive" })'];if(e.primaryKey.length>0&&e.primaryKey.every(o=>!h.has(o))){const o=e.primaryKey.map(i=>f(i)).join(", ");a.push(` .index(${f(`by_${e.primaryKey.join("_")}`)}, [${o}], { unique: true })`)}for(const o of e.indexes){const i=o.columns.filter(u=>!h.has(u));if(i.length===0)continue;const c=i.map(u=>f(u)).join(", "),m=o.unique?", { unique: true }":"";a.push(` .index(${f(o.name)}, [${c}]${m})`)}return` ${S(e.name)}: defineTable({
6
+ ${s.join(`
7
+ `)}
8
+ })
9
+ ${a.join(`
10
+ `)},`},ce=(e,r,n)=>{const t=new Set(e.tables.map(a=>a.name)),s=e.tables.map(a=>ie(a,e.dialect,t,n)).join(`
11
+ `);return`/**
12
+ * Generated by \`lunora introspect\` from an existing ${e.dialect==="postgres"?"Postgres":"MySQL"} database.
13
+ *
14
+ * This file is a STARTING POINT, not a build artifact — it is written once and is
15
+ * yours to edit. Review it before shipping: column types are mapped
16
+ * conservatively, and every table is \`.global({ backend: "hyperdrive" })\` because
17
+ * its rows live in the external database. Re-running \`lunora introspect\` will not
18
+ * overwrite it unless you pass \`--force\`.
19
+ */
20
+ import { defineSchema, defineTable, v } from "${r.serverImport}";
21
+
22
+ export default defineSchema({
23
+ ${s}
24
+ });
25
+ `},me=(e,r,n,t=new Set([e.name]),s=[])=>{const a=se(e.name),o=oe(e),i=new Map(C(e).map(l=>[l.name,l])),c=o.map(l=>{const p=i.get(l);if(p===void 0)return;const v=D({...p,nullable:!1},t,e.name,[]),{expression:d,known:A}=w(v,r);return!A&&v.references===void 0&&s.push(`${e.name}.${l}: filter falls back to \`v.any()\` (no mapping for SQL type \`${p.dataType}\`).`),` ${S(l)}: ${d},`}).filter(l=>l!==void 0),m=[f("_creationTime"),...o.map(l=>f(l))].join(", "),u=`ctx.db${re(e.name)}`;return`/**
26
+ * Generated by \`lunora introspect\` for the \`${x(e.name)}\` table — a
27
+ * starting point you own and edit.
28
+ *
29
+ * Both procedures are RPC-only. Add \`.expose({ rest: true })\` once you've decided
30
+ * this data should be public, and gate them with your auth/RLS middleware first —
31
+ * \`introspect\` cannot know who is allowed to read this table.
32
+ */
33
+ import { defineListArgs, v } from "${n.serverImport}";
34
+
35
+ import type { Doc } from "./_generated/dataModel";
36
+ import { c } from "./_generated/server";
37
+
38
+ const ${a}List = defineListArgs<Doc<${f(e.name)}>>()({
39
+ // Only index-backed columns are published as filterable, so a caller cannot
40
+ // reach a column you did not choose to expose. Note that \`contains\` and the
41
+ // negative operators still scan — narrow this list, and review it, before
42
+ // adding \`.expose({ rest: true })\`.
43
+ filter: {
44
+ ${c.join(`
45
+ `)}
46
+ },
47
+ orderBy: [${m}],
48
+ });
49
+
50
+ export const list = c.query.input(${a}List.args).query(({ args, ctx }) => ${u}.findMany(${a}List.toQueryArgs(args)));
51
+
52
+ export const get = c.query.input({ id: v.id(${f(e.name)}) }).query(({ args, ctx }) => ${u}.get(args.id));
53
+ `},le=(e,r)=>{const n=[],t=new Set(e.tables.map(a=>a.name)),s=[{contents:ce(e,r,n),path:"schema.ts"}];if(r.procedures){const a=new Map([["schema","the generated schema module"]]);for(const o of e.tables){if(C(o).length===0){n.push(`${o.name}: no usable columns — procedure module skipped.`);continue}const i=ae(o.name);i!==o.name&&n.push(`${o.name}: written as \`${i}.ts\` — the table name isn't usable as a filename.`);const c=a.get(i);if(c!==void 0){n.push(`${o.name}: procedure module skipped — its filename \`${i}.ts\` collides with table \`${c}\`.`);continue}a.set(i,o.name),s.push({contents:me(o,e.dialect,r,t,n),path:`${i}.ts`})}}return{files:s,warnings:n}},y=/^[A-Z_$][\w$]*$/i,ue=e=>e.startsWith("v.optional(")&&e.endsWith(")")?e.slice(11,-1):e,de=(e,r,n)=>{const t=[],s=new Set(r?.columns.map(a=>a.name));for(const a of e.columns){if(h.has(a.name)||s.has(a.name))continue;if(!y.test(a.name)){n.warnings.push(`${e.name}.${a.name}: skipped — column names must be bare identifiers to merge.`);continue}const o=a.references!==void 0&&!n.present.has(a.references.table),{expression:i}=w(o?{...a,references:void 0}:a,n.dialect);t.push({column:a.name,kind:"addOptionalColumn",table:e.name,validator:ue(i)}),!a.nullable&&r!==void 0&&n.warnings.push(`${e.name}.${a.name}: added as \`v.optional(...)\` — a required column on an existing table needs a backfill migration.`)}return t},pe=(e,r,n)=>{const t=[],s=new Set(r?.indexes.map(a=>a.name));for(const a of e.indexes){const o=a.columns.filter(i=>!h.has(i));if(!(s.has(a.name)||o.length===0)){if(!y.test(a.name)||!o.every(i=>y.test(i))){n.push(`${e.name}: index \`${a.name}\` skipped — index and column names must be bare identifiers to merge.`);continue}t.push({fields:o,kind:"addIndex",name:a.name,table:e.name,...a.unique?{unique:!0}:{}})}}return t},ge=(e,r,n)=>{const t=[],s=[],a=new Map(r.map(i=>[i.name,i])),o=new Set([...a.keys(),...e.tables.map(i=>i.name)]);for(const i of e.tables){if(!y.test(i.name)){s.push(`${i.name}: skipped — merging into an existing schema needs a table name that is a bare identifier.`);continue}const c=a.get(i.name);c===void 0&&t.push({global:{backend:"hyperdrive"},kind:"addTable",table:i.name}),t.push(...de(i,c,{dialect:n,present:o,warnings:s}),...pe(i,c,s))}return{edits:t,warnings:s}},fe=(e,r,n)=>{const t=Y(e);if(!t.ok)return{applied:0,warnings:[`lunora/schema.ts could not be parsed (${t.reason}) — leave it alone and merge by hand, or pass --force.`]};const s=ge(r,t.tables,n),a=[...s.warnings];let o=e,i=0;for(const c of s.edits){const m=q(o,c);m.ok?(o=m.text,i+=1):a.push(`${c.table}: skipped one edit (${m.reason}).`)}return{applied:i,warnings:a,...i===0?{}:{text:o}}},g=(e,r)=>{const n=e[r]??e[r.toLowerCase()]??e[r.toUpperCase()];return typeof n=="string"?n:typeof n=="number"||typeof n=="bigint"||typeof n=="boolean"?String(n):""},ve=`
54
+ SELECT c.table_name, c.column_name, c.is_nullable, c.data_type, c.udt_name
55
+ FROM information_schema.columns c
56
+ JOIN information_schema.tables t
57
+ ON t.table_schema = c.table_schema AND t.table_name = c.table_name
58
+ WHERE c.table_schema = $1 AND t.table_type = 'BASE TABLE'
59
+ ORDER BY c.table_name, c.ordinal_position`,be=`
60
+ SELECT tc.table_name, kcu.column_name
61
+ FROM information_schema.table_constraints tc
62
+ JOIN information_schema.key_column_usage kcu
63
+ ON kcu.constraint_name = tc.constraint_name AND kcu.table_schema = tc.table_schema
64
+ WHERE tc.table_schema = $1 AND tc.constraint_type = 'PRIMARY KEY'
65
+ ORDER BY tc.table_name, kcu.ordinal_position`,he=`
66
+ SELECT tc.table_name, kcu.column_name, ccu.table_name AS foreign_table, ccu.column_name AS foreign_column
67
+ FROM information_schema.table_constraints tc
68
+ JOIN information_schema.key_column_usage kcu
69
+ ON kcu.constraint_name = tc.constraint_name AND kcu.table_schema = tc.table_schema
70
+ JOIN information_schema.constraint_column_usage ccu
71
+ ON ccu.constraint_name = tc.constraint_name AND ccu.table_schema = tc.table_schema
72
+ WHERE tc.table_schema = $1 AND tc.constraint_type = 'FOREIGN KEY'`,Ee=`
73
+ SELECT t.relname AS table_name, i.relname AS index_name, ix.indisunique AS is_unique, a.attname AS column_name
74
+ FROM pg_class t
75
+ JOIN pg_index ix ON t.oid = ix.indrelid
76
+ JOIN pg_class i ON i.oid = ix.indexrelid
77
+ JOIN pg_namespace n ON n.oid = t.relnamespace
78
+ CROSS JOIN LATERAL unnest(ix.indkey) WITH ORDINALITY AS k(attnum, ord)
79
+ JOIN pg_attribute a ON a.attrelid = t.oid AND a.attnum = k.attnum
80
+ WHERE n.nspname = $1 AND t.relkind = 'r' AND NOT ix.indisprimary
81
+ ORDER BY t.relname, i.relname, k.ord`,_e=`
82
+ SELECT c.TABLE_NAME, c.COLUMN_NAME, c.IS_NULLABLE, c.DATA_TYPE
83
+ FROM information_schema.COLUMNS c
84
+ JOIN information_schema.TABLES t
85
+ ON t.TABLE_SCHEMA = c.TABLE_SCHEMA AND t.TABLE_NAME = c.TABLE_NAME
86
+ WHERE c.TABLE_SCHEMA = ? AND t.TABLE_TYPE = 'BASE TABLE'
87
+ ORDER BY c.TABLE_NAME, c.ORDINAL_POSITION`,ye=`
88
+ SELECT TABLE_NAME, COLUMN_NAME
89
+ FROM information_schema.KEY_COLUMN_USAGE
90
+ WHERE TABLE_SCHEMA = ? AND CONSTRAINT_NAME = 'PRIMARY'
91
+ ORDER BY TABLE_NAME, ORDINAL_POSITION`,Ae=`
92
+ SELECT TABLE_NAME, COLUMN_NAME, REFERENCED_TABLE_NAME AS foreign_table, REFERENCED_COLUMN_NAME AS foreign_column
93
+ FROM information_schema.KEY_COLUMN_USAGE
94
+ WHERE TABLE_SCHEMA = ? AND REFERENCED_TABLE_NAME IS NOT NULL`,Se=`
95
+ SELECT TABLE_NAME, INDEX_NAME AS index_name, NON_UNIQUE, COLUMN_NAME
96
+ FROM information_schema.STATISTICS
97
+ WHERE TABLE_SCHEMA = ? AND INDEX_NAME <> 'PRIMARY'
98
+ ORDER BY TABLE_NAME, INDEX_NAME, SEQ_IN_INDEX`,E=e=>{const r=new Map;for(const n of e){const t=g(n,"table_name"),s=r.get(t);s===void 0?r.set(t,[n]):s.push(n)}return r},Ne=(e,r)=>{const n=g(e,"data_type").toLowerCase();if(r!=="postgres")return{arrayDepth:0,dataType:n};const t=g(e,"udt_name").toLowerCase();return n==="array"&&t.startsWith("_")?{arrayDepth:1,dataType:t.slice(1)}:{arrayDepth:0,dataType:t===""?n:t}},we=(e,r)=>{const n=new Map;for(const t of e){const s=g(t,"index_name"),a=r==="postgres"?g(t,"is_unique")==="true":g(t,"NON_UNIQUE")==="0",o=n.get(s);o===void 0?n.set(s,{columns:[g(t,"column_name")],unique:a}):o.columns.push(g(t,"column_name"))}return[...n.entries()].map(([t,s])=>({columns:s.columns,name:t,unique:s.unique}))},Re=async(e,r,n)=>{const t=r==="postgres",[s,a,o,i]=await Promise.all([e(t?ve:_e,[n]),e(t?be:ye,[n]),e(t?he:Ae,[n]),e(t?Ee:Se,[n])]),c=E(a),m=E(o),u=E(i),l=[];for(const[p,v]of E(s)){const d=new Map((m.get(p)??[]).map(b=>[g(b,"column_name"),{column:g(b,"foreign_column"),table:g(b,"foreign_table")}])),A=v.map(b=>{const R=g(b,"column_name"),$=d.get(R);return{...Ne(b,r),name:R,nullable:g(b,"is_nullable").toUpperCase()==="YES",...$===void 0?{}:{references:$}}});l.push({columns:A,indexes:we(u.get(p)??[],r),name:p,primaryKey:(c.get(p)??[]).map(b=>g(b,"column_name"))})}return l.sort((p,v)=>p.name.localeCompare(v.name)),{dialect:r,tables:l}},$e=e=>P(e)?"lunorash/server":"@lunora/server",Le=async(e,r,n)=>{const t=_(r,e.path);return O(t)&&n.force!==!0?(n.logger.warn(`skipped lunora/${e.path} — it already exists (pass --force to overwrite)`),!1):n.dryRun===!0?(n.logger.info(`would write lunora/${e.path} (${String(e.contents.split(`
99
+ `).length)} lines)`),!1):(await U(r,{recursive:!0}),await I(t,e.contents,"utf8"),n.logger.info(`wrote lunora/${e.path}`),!0)},Te=(e,r)=>{const n=r.tables;if(n===void 0||n.length===0)return e.tables;for(const t of n)e.tables.some(s=>s.name===t)||r.logger.warn(`--tables: no table named "${t}" exists in this schema — skipped.`);return e.tables.filter(t=>n.includes(t.name))},Oe=async(e,r,n,t)=>{const s=fe(k(e,"utf8"),r,n);for(const a of s.warnings)t.logger.warn(a);return s.text===void 0?(t.logger.info("lunora/schema.ts is already up to date with the database."),!1):t.dryRun===!0?(t.logger.info(`would merge ${String(s.applied)} addition(s) into lunora/schema.ts`),!1):(await I(e,s.text,"utf8"),t.logger.info(`merged ${String(s.applied)} addition(s) into lunora/schema.ts`),!0)},Ie=async e=>{const r=e.cwd??process.cwd();if(e.connection===void 0&&(e.url===void 0||e.url==="")){const d="`lunora introspect` needs a database URL: pass --url, or set DATABASE_URL.";return e.logger.error(d),{code:L.USAGE,error:d,written:[]}}const n=e.connection===void 0?Q(e.url):e.dialect??"postgres",t=e.connection??await W(e.url,n,e.schema,r);let s;try{s=await Re(t.execute,n,t.schema)}finally{e.connection===void 0&&await t.close()}const a=Te(s,e);if(a.length===0){const d="no tables found to introspect — check --schema and --tables.";return e.logger.error(d),{code:L.NOT_FOUND,error:d,written:[]}}const{files:o,warnings:i}=le({...s,tables:a},{procedures:e.procedures!==!1,serverImport:$e(r)}),c=_(r,"lunora"),m=[],u=_(c,"schema.ts"),l=O(u)&&e.force!==!0,p=l?o.filter(d=>d.path!=="schema.ts"):o;l&&await Oe(u,{...s,tables:a},n,e)&&m.push("schema.ts");for(const d of p)await Le(d,c,e)&&m.push(d.path);for(const d of i)e.logger.warn(d);e.logger.info(`introspected ${String(a.length)} table(s) from ${n}. Review the generated files before running \`lunora dev\`.`);const v=a.map(d=>d.name);return{code:0,dialect:n,tables:v,written:m}},Ye=H(async({cwd:e,format:r,logger:n,options:t})=>{const s=await Ie({cwd:e,dryRun:t.dryRun===!0,force:t.force===!0,format:r,logger:n,procedures:t.procedures!==!1,schema:t.schema,tables:t.tables===void 0?void 0:t.tables.split(",").map(a=>a.trim()),url:t.url??process.env.DATABASE_URL});return{code:s.code,data:s.dialect===void 0?void 0:{dialect:s.dialect,dryRun:t.dryRun===!0,tables:s.tables??[],written:s.written},error:s.error}});export{Ye as execute,$e as resolveServerImport,Ie as runIntrospectCommand};
@@ -1,2 +1,10 @@
1
- import{readLinkedProject as v,resolveDeployDriver as h,toolchainExecArgs as b,detectPackageManager as y}from"@lunora/config";import{d as w}from"../packem_shared/command-CAXl2A1S.mjs";import{EXIT_CODE as d}from"../packem_shared/EXIT_CODE-D_XCixv8.mjs";import{defaultSpawner as L}from"../packem_shared/createRecordingSpawner-Ch7zuQQE.mjs";import{createR2Sql as S}from"@lunora/bindings/r2sql";import{createPipelineLogReader as _}from"@lunora/runtime";const E=["trace","debug","log","info","warn","error","fatal"],T=new Set(E),f=/^\d+$/,u=(e,t)=>{if(e===void 0)return;const a=e.trim();if(f.test(a))return Number(a);const n=Date.parse(a);if(Number.isNaN(n))throw new TypeError(`logs: invalid ${t} "${e}" — pass epoch-millis or an ISO 8601 date`);return n},C=e=>Buffer.from(JSON.stringify(e),"utf8").toString("base64url"),I=e=>{const t=e.trim();if(f.test(t))return{ts:Number(t)};let a;try{a=JSON.parse(Buffer.from(t,"base64url").toString("utf8"))}catch{throw new TypeError(`logs: invalid --cursor "${e}" — expected the token printed by the previous page (or a bare epoch-millis ts)`)}if(typeof a!="object"||a===null||typeof a.ts!="number"||!Number.isFinite(a.ts))throw new TypeError(`logs: invalid --cursor "${e}" — expected the token printed by the previous page (or a bare epoch-millis ts)`);const{ts:n}=a,r=a.seen,s=Array.isArray(r)?r.filter(i=>typeof i=="string"):void 0;return s!==void 0&&s.length>0?{seen:s,ts:n}:{ts:n}},m=(e,t)=>{if(e!==void 0){if(!T.has(e))throw new TypeError(`logs: invalid ${t} "${e}" — expected one of trace, debug, log, info, warn, error, fatal`);return e}},p=e=>{const t={},a=u(e.since,"--since");a!==void 0&&(t.sinceTs=a);const n=u(e.until,"--until");n!==void 0&&(t.untilTs=n);const r=m(e.level,"--level");r!==void 0&&(t.level=r);const s=m(e.minLevel,"--min-level");if(s!==void 0&&(t.minLevel=s),e.functionPrefix!==void 0&&(t.functionPathPrefix=e.functionPrefix),e.traceId!==void 0&&(t.traceId=e.traceId),e.shardKey!==void 0&&(t.shardKey=e.shardKey),e.userId!==void 0&&(t.userId=e.userId),e.limit!==void 0){const i=Number(e.limit);if(!Number.isFinite(i))throw new TypeError(`logs: invalid --limit "${e.limit}" — expected a number`);t.limit=i}return e.cursor!==void 0&&(t.cursor=I(e.cursor)),t},R=e=>{const t=new Date(e.ts).toISOString(),a=e.level.toUpperCase().padEnd(5);return`${t} ${a} ${e.functionPath} ${e.message}`},$=async e=>{const t=e.environment??process.env,a=t.R2_SQL_ACCOUNT_ID,n=t.R2_SQL_TOKEN,r=t.R2_SQL_BUCKET,s=[];if((a===void 0||a.length===0)&&s.push("R2_SQL_ACCOUNT_ID"),(n===void 0||n.length===0)&&s.push("R2_SQL_TOKEN"),(r===void 0||r.length===0)&&s.push("R2_SQL_BUCKET"),(e.table===void 0||e.table.length===0)&&s.push("--table"),s.length>0)return e.logger.error(`logs --durable: R2 SQL not configured (missing ${s.join(", ")}). The Pipeline must write to an R2 Data Catalog (Iceberg) table, and you must supply R2_SQL_ACCOUNT_ID / R2_SQL_TOKEN / R2_SQL_BUCKET plus --table — see the observability docs.`),{code:d.USAGE,error:"not configured"};let i;try{i=p(e)}catch(c){return e.logger.error(c instanceof Error?c.message:String(c)),{code:d.USAGE,error:"invalid option"}}const o=S({accountId:a,apiToken:n,bucket:r,fetch:e.fetch}),l=await _(o,{namespace:e.namespace,table:e.table}).query(i);for(const c of l.rows)process.stdout.write(`${e.ndjson===!0?JSON.stringify(c):R(c)}
2
- `);return l.rows.length===0?e.logger.info("logs --durable: no matching log records"):l.nextCursor!==void 0&&e.logger.info(`logs --durable: more rows available — pass --cursor ${C(l.nextCursor)} for the next page`),{code:0,rows:l.rows}},N=async e=>{const t=e.cwd??process.cwd(),a=e.env??v(t)?.env,n=h(e.target),r=n.toolchain?.tail;if(r===void 0){const c=`logs: deploy target "${n.id}" has no log tail`;return e.logger.error(c),{code:d.USAGE,descriptor:void 0,error:c}}const s=r({environment:a,format:e.format,search:e.search,status:e.status,temporary:e.temporary,worker:e.worker}),i=b(y(t),s),o={args:i.args,command:i.command,cwd:t};return e.logger.info(`tailing logs via ${o.command} ${o.args.join(" ")}`),{code:(await(e.spawner??L)(o)).code,delegated:!0,descriptor:o}},U=w(async({argument:e,cwd:t,format:a,logger:n,options:r})=>{if(r.durable===!0){const s=await $({cursor:r.cursor,functionPrefix:r.functionPrefix,level:r.level,limit:r.limit,logger:n,minLevel:r.minLevel,namespace:r.namespace,ndjson:r.ndjson===!0,shardKey:r.shardKey,since:r.since,table:r.table,traceId:r.traceId,until:r.until,userId:r.userId});return{...s,...s.rows===void 0?{}:{delegated:!0}}}return N({cwd:t,env:r.env,format:a,logger:n,search:r.search,status:r.status,target:r.target,temporary:r.temporary===!0,worker:e[0]})});export{U as execute,N as runLogsCommand};
1
+ import{V as R}from"../packem_shared/cli-C74xjzMK.mjs";import{d as G}from"../packem_shared/command-CAXl2A1S.mjs";import{EXIT_CODE as d}from"../packem_shared/EXIT_CODE-D_XCixv8.mjs";import{existsSync as f,readFileSync as h,mkdirSync as J,realpathSync as W,statSync as V,writeFileSync as z,chmodSync as H,renameSync as K,unlinkSync as q}from"node:fs";import{homedir as w}from"node:os";import{findWranglerFile as X}from"@lunora/config/cloudflare";import{join as s,dirname as B,relative as Z}from"@visulima/path";import{stringify as Q}from"smol-toml";import{parse as Y,modify as ee,applyEdits as re}from"jsonc-parser";import{detectPackageManager as te,execArgsFor as ne,readLiveDevServerState as S,DEV_STATE_DIR as oe}from"@lunora/config";import{resolveAdminToken as ae}from"@lunora/config/studio-host";import{connectLocalStdio as le}from"@lunora/mcp";import{resolve as y}from"node:path";import{i as ce}from"../packem_shared/path-containment-CgxYZggb.mjs";const m=e=>({args:[...e.args],command:e.command,...e.env===void 0?{}:{env:e.env}}),b=e=>e.transport==="http"?{type:"http",url:e.url}:m(e),se=e=>e.transport==="http"?{httpUrl:e.url}:m(e),ie=e=>e.transport==="http"?{serverUrl:e.url}:m(e),de=e=>({args:["-y","mcp-remote",e],command:"npx"}),ue=e=>e.transport==="http"?de(e.url):m(e),fe=e=>e.transport==="http"?{url:e.url}:m(e),me=e=>e.transport==="http"?{enabled:!0,type:"remote",url:e.url}:{command:[e.command,...e.args],enabled:!0,type:"local",...e.env===void 0?{}:{environment:e.env}},pe=e=>e.transport==="http"?{disabled:!1,type:"streamableHttp",url:e.url}:{disabled:!1,...m(e)},ge=({home:e,platform:r})=>{if(r==="darwin")return{global:s(e,"Library","Application Support","Claude","claude_desktop_config.json")};if(r==="win32"){const t=process.env.APPDATA;return t===void 0||t===""?{}:{global:s(t,"Claude","claude_desktop_config.json")}}return r==="linux"?{global:s(e,".config","Claude","claude_desktop_config.json")}:{}},ve=(e,r)=>Q({mcp_servers:{[e]:r.transport==="http"?{url:r.url}:{args:[...r.args],command:r.command,...r.env===void 0?{}:{env:r.env}}}}),v=[{buildEntry:b,paths:({projectRoot:e})=>({project:s(e,".mcp.json")}),format:"json",id:"claude-code",key:"mcpServers",label:"Claude Code"},{buildEntry:b,paths:({home:e,projectRoot:r})=>({global:s(e,".cursor","mcp.json"),project:s(r,".cursor","mcp.json")}),format:"json",id:"cursor",key:"mcpServers",label:"Cursor"},{buildEntry:b,paths:({projectRoot:e})=>({project:s(e,".vscode","mcp.json")}),format:"json",id:"vscode",key:"servers",label:"VS Code (GitHub Copilot)"},{buildEntry:se,paths:({home:e,projectRoot:r})=>({global:s(e,".gemini","settings.json"),project:s(r,".gemini","settings.json")}),format:"json",id:"gemini",key:"mcpServers",label:"Gemini CLI"},{buildEntry:ue,paths:ge,format:"json",id:"claude-desktop",key:"mcpServers",label:"Claude Desktop"},{buildEntry:ie,paths:({home:e})=>({global:s(e,".codeium","windsurf","mcp_config.json")}),format:"json",id:"windsurf",key:"mcpServers",label:"Windsurf"},{buildEntry:me,paths:({home:e,projectRoot:r})=>({global:s(e,".config","opencode","opencode.json"),project:s(r,"opencode.json")}),format:"json",id:"opencode",key:"mcp",label:"OpenCode"},{buildEntry:pe,paths:({home:e})=>({global:s(e,".cline","mcp.json")}),format:"json",id:"cline",key:"mcpServers",label:"Cline"},{buildEntry:fe,paths:({home:e})=>({global:s(e,".config","zed","settings.json")}),format:"json",id:"zed",key:"context_servers",label:"Zed"},{paths:({home:e,projectRoot:r})=>({global:s(e,".codex","config.toml"),project:s(r,".codex","config.toml")}),format:"manual",id:"codex",label:"Codex CLI",renderSnippet:ve}],x=v.map(e=>e.id),he=e=>v.find(r=>r.id===e.toLowerCase()),M=(e,r)=>{let t=e,n;try{t=W(e),n=V(t).mode}catch{}const a=`${t}.lunora-${Math.random().toString(36).slice(2,10)}.tmp`;try{z(a,r,"utf8"),n!==void 0&&H(a,n),K(a,t)}catch(o){try{q(a)}catch{}throw o}},ye={formattingOptions:{insertSpaces:!0,tabSize:4}},k=e=>{const r=[],t=Y(e,r,{allowTrailingComma:!0});return{errors:r,value:t}},g=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),E=(e,r,t)=>{if(!g(e))return;const n=e[r];return g(n)?n[t]:void 0},L=e=>{if(!f(e.path))return"absent";let r;try{r=h(e.path,"utf8")}catch{return"invalid"}if(r.trim().length===0)return"absent";const{errors:t,value:n}=k(r);return t.length>0||!g(n)?"invalid":E(n,e.key,e.name)===void 0?"absent":"present"},be=e=>L(e)==="present",U=(e,r,t,n,a)=>{try{const o=ee(e,[t,n],a,ye);o.length>0&&M(r,re(e,o));return}catch(o){return o instanceof Error?o.message:String(o)}},Se=e=>{const{entry:r,force:t=!1,key:n,name:a,path:o}=e,l=f(o)?h(o,"utf8"):"";if(l.trim().length===0)return J(B(o),{recursive:!0}),M(o,`${JSON.stringify({[n]:{[a]:r}},void 0,4)}
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
+ ${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
+
5
+ ${e.renderSnippet(r.name,r.spec)}`),{action:"printed",path:n}},Ne=e=>{const r=[];return e.localOnly!==!0&&r.push({allowScopeFallback:!0,name:N,preferredScope:"global",spec:Me(e.docsUrl??Ce)}),e.docsOnly!==!0&&_e(e.cwd)&&r.push({allowScopeFallback:!1,name:D,preferredScope:"project",spec:xe(te(e.cwd))}),r},De=e=>{const r=e.home??w(),t=e.platform??process.platform;e.logger.info("Supported MCP clients:");for(const n of v){const a=n.paths({home:r,platform:t,projectRoot:e.cwd}),o=l=>{const c=a[l];return c===void 0?"—":u(c,e.cwd)};e.logger.info(` ${n.id.padEnd(15)} ${n.label.padEnd(24)} project: ${o("project").padEnd(30)} global: ${o("global")}`)}return{code:0,written:[]}},Te=e=>e.docsOnly===!0&&e.localOnly===!0?"`--docs-only` and `--local-only` are mutually exclusive — pass at most one.":"`--local-only` was set but this directory is not a Lunora project (no `lunora/` directory and wrangler config).",Pe=(e,r,t)=>{const n=[];for(const a of e)for(const o of r){const l=a.format==="json"?Ue(a,o,t):Ae(a,o,t);l!==void 0&&n.push({action:l.action,client:a.id,path:l.path,server:o.name})}return n},Fe=e=>{const r=e.home??w(),t=e.platform??process.platform,n=A(e.clients,()=>je({home:r,platform:t,projectRoot:e.cwd}),e.logger,"install");if(n===void 0)return{code:d.USAGE,written:[]};if(n.length===0)return e.logger.error(`mcp install: no MCP client config found — name one explicitly, e.g. \`lunora mcp install claude-code\`. Known clients: ${x.join(", ")}.`),{code:d.NOT_FOUND,written:[]};e.clients.length===0&&e.logger.info(`Detected ${String(n.length)} configured client(s): ${n.map(l=>l.label).join(", ")}.`);const a=Ne(e);if(a.length===0)return e.logger.error(`mcp install: nothing to install — ${Te(e)}`),{code:d.USAGE,written:[]};const o=Pe(n,a,{...e,home:r,platform:t});return o.some(l=>l.action==="created"||l.action==="updated")&&e.logger.info("Restart your editor (or reload its MCP servers) to pick up the change."),{code:o.some(l=>l.action==="invalid")?1:0,written:o}},P=100,F=1e3,j=e=>({content:[{text:JSON.stringify(e,void 0,2),type:"text"}]}),Ie=e=>({content:[{text:e,type:"text"}]}),Re=e=>{const r=typeof e=="string"?Number(e):e;return typeof r!="number"||!Number.isFinite(r)?P:Math.min(F,Math.max(1,Math.floor(r)))},O=(e,r)=>{if(r===void 0)return;const t=y(e,oe);return ce(t,y(e,r))?y(e,r):void 0},Ge=(e,r)=>{const t=h(e,"utf8").split(`
6
+ `);return t.at(-1)===""&&t.pop(),t.slice(-r).join(`
7
+ `)},Je=e=>[{definition:{description:"Report whether a `lunora dev` server is running for this project, and its URL, studio URL, mode and uptime. Call this first when a query or mutation tool fails to connect.",inputSchema:{properties:{},type:"object"},name:"lunora_dev_status"},handle:async()=>{const r=S(e);return j(r===void 0?{hint:"Start it with `lunora dev` in the project directory.",running:!1}:{background:r.background===!0,logFile:O(e,r.logFile),mode:r.mode,pid:r.pid,running:!0,startedAt:r.startedAt,studioUrl:r.studioUrl,url:r.url})}},{definition:{description:"Return the tail of the running dev server's captured log — worker output, request errors, and stack traces. Only available when the server was started in the background (`lunora dev --background`); a foreground server prints to its own terminal.",inputSchema:{properties:{lines:{description:`How many trailing lines to return (default ${String(P)}, max ${String(F)})`,type:"number"}},type:"object"},name:"lunora_dev_logs"},handle:async r=>{const t=S(e);if(t===void 0)return{content:[{text:"no dev server is running — start one with `lunora dev`",type:"text"}],isError:!0};const n=O(e,t.logFile);if(n===void 0||!f(n))return{content:[{text:"this dev server is not capturing its output to a file (it runs in the foreground) — restart it with `lunora dev --background` to make its logs readable here",type:"text"}],isError:!0};const a=Re(r.lines),o=Ge(n,a);return Ie(o.length===0?"(the dev server log is empty)":o)}}],We=new Set(["127.0.0.1","::1","localhost"]),I=e=>{try{const{hostname:r}=new URL(e);return We.has(r.startsWith("[")?r.slice(1,-1):r)}catch{return!1}},C=e=>{const r=e.url??S(e.cwd)?.url;if(r===void 0||r.length===0)return;if(e.token!==void 0&&e.token.length>0)return{token:e.token,url:r};if(!I(r))return{url:r};const t=ae(e.cwd);return t===void 0||t.length===0?{url:r}:{token:t,url:r}},Ve=async e=>{await new Promise(r=>{const t=()=>{r()};e.onclose=t,process.stdin.once("close",t),process.stdin.once("end",t)})},ze=e=>{if(e===void 0)return"lunora mcp serve: ready (documentation tools). No dev server running yet — start `lunora dev` and the deployment tools start working, no restart needed.\n";if(e.token!==void 0)return`lunora mcp serve: ready — deployment at ${e.url}
8
+ `;const t=!I(e.url)?"the project's admin token was NOT sent to this non-local url; pass --token to authenticate deliberately":"no LUNORA_ADMIN_TOKEN in the environment or .dev.vars; the deployment tools will be refused until one is set";return`lunora mcp serve: ready — deployment at ${e.url} (${t})
9
+ `},He=async(e,r=le)=>{const t=e.writeError??(o=>{process.stderr.write(o)});let n;try{n=await r({allowWrites:e.allowWrites===!0,deployment:()=>C(e),docs:e.noDocs===!0?!1:{...e.docsUrl===void 0?{}:{baseUrl:e.docsUrl}},extraTools:Je(e.cwd),version:e.version})}catch(o){const l=o instanceof Error?o.message:String(o);return t(`lunora mcp serve: failed to start — ${l}
10
+ `),{code:1,deployment:void 0}}const a=C(e);return t(ze(a)),await Ve(n),{code:0,deployment:a}},Ke=e=>{const r=[];return e.localOnly!==!0&&r.push(N),e.docsOnly!==!0&&r.push(D),r},qe=(e,r,t,n)=>{const a=we({key:e.key,name:r,path:t}),o=u(t,n.cwd);return a.action==="removed"?n.logger.success(`${e.label}: removed "${r}" from ${o}.`):a.action==="invalid"&&n.logger.error(`${e.label}: ${o} is not valid JSON (${a.error??"unknown error"}) — left untouched.`),{action:a.action,path:t}},Xe=(e,r,t,n)=>{const a=L({key:e.key,name:r,path:t}),o=u(t,n.cwd);return a==="invalid"?(n.logger.error(`${e.label}: ${o} is not valid JSON — a real run would report it and exit non-zero.`),{action:"invalid",path:t}):a==="absent"?{action:"absent",path:t}:(n.logger.info(`${e.label}: would remove "${r}" from ${o}.`),{action:"removed",path:t})},Be=(e,r,t)=>e.flatMap(n=>Ee(n,r)).filter(Oe).filter(n=>t===void 0||n.scope===t),Ze=e=>{const r=e.home??w(),t=e.platform??process.platform,n=A(e.clients,()=>v,e.logger,"uninstall");if(n===void 0)return{code:d.USAGE,removed:[]};const a=Ke(e);if(a.length===0)return e.logger.error("mcp uninstall: nothing to remove — `--docs-only` and `--local-only` are mutually exclusive, pass at most one."),{code:d.USAGE,removed:[]};const o=[],l={home:r,platform:t,projectRoot:e.cwd};for(const c of Be(n,l,e.scope))for(const i of a){const p=e.print===!0?Xe(c.client,i,c.path,e):qe(c.client,i,c.path,e);p.action!=="absent"&&o.push({...p,client:c.client.id,server:i})}return o.length===0?e.logger.info("Nothing to remove — no Lunora MCP servers were configured in the clients checked."):e.print===!0&&e.logger.info("Nothing was changed — re-run without --print to remove these."),{code:o.some(c=>c.action==="invalid")?1:0,removed:o}},_=e=>e.global===!0?"global":e.project===!0?"project":void 0,Qe=async(e,r)=>{const{code:t}=await He({allowWrites:r.allowWrites===!0,cwd:e,noDocs:r.docs===!1,version:R,...r.docsUrl===void 0?{}:{docsUrl:r.docsUrl},...r.token===void 0?{}:{token:r.token},...r.url===void 0?{}:{url:r.url}});return{code:t}},mr=G(async({argument:e,cwd:r,logger:t,options:n})=>{const[a,...o]=e;if(a==="serve")return Qe(r,n);if(a==="uninstall"){const l=_(n),{code:c}=Ze({clients:o,cwd:r,docsOnly:n.docsOnly===!0,localOnly:n.localOnly===!0,logger:t,print:n.print===!0,...l===void 0?{}:{scope:l}});return{code:c}}if(a==="install"){if(n.list===!0)return De({cwd:r,logger:t});const l=_(n),{code:c}=Fe({clients:o,cwd:r,docsOnly:n.docsOnly===!0,force:n.force===!0,localOnly:n.localOnly===!0,logger:t,print:n.print===!0,...l===void 0?{}:{scope:l},...n.docsUrl===void 0?{}:{docsUrl:n.docsUrl}});return{code:c}}return t.error("mcp: unknown subcommand. Usage: lunora mcp <install|uninstall|serve>"),{code:d.USAGE}});export{mr as execute};
@@ -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{d as _e}from"../packem_shared/command-CAXl2A1S.mjs";import{r as Ee}from"../packem_shared/deploy-target-DCWwiuAe.mjs";import{exitCodeForStatus as W,EXIT_CODE as m}from"../packem_shared/EXIT_CODE-D_XCixv8.mjs";import{writeFileSync as Te}from"node:fs";import{findWranglerFile as de,readWranglerJsonc as ue,applyModify as Oe}from"@lunora/config/cloudflare";import{r as fe,n as Y,c as ke}from"../packem_shared/cloudflare-credentials-BVmZnDZk.mjs";import{c as Ce,b as Ie}from"../packem_shared/variables-CPYyJtsL.mjs";import{b as Ne}from"../packem_shared/tui-prompts-B3YwUhGw.mjs";import{a as Ue}from"../packem_shared/docker-AqLAkOyY.mjs";import{defaultSpawner as me}from"../packem_shared/createRecordingSpawner-Ch7zuQQE.mjs";import{execArgsFor as he,detectPackageManager as ge}from"@lunora/config";import{a as k}from"../packem_shared/cli-C74xjzMK.mjs";const H=256,De=e=>e.length>H?`${e.slice(0,H)}… (truncated)`:e,Re="https://api.cloudflare.com/client/v4/accounts",K=64,V={byok:"https://developers.cloudflare.com/ai-gateway/configuration/bring-your-own-keys/",unifiedBilling:"https://developers.cloudflare.com/ai-gateway/features/unified-billing/"},b=(e,t,r)=>(e.error(r),{code:t,error:r}),X=async(e,t,r,o={})=>{const n=await e(t,{...o,headers:{Authorization:`Bearer ${r}`,"Content-Type":"application/json"}}),s=await n.text();let a;try{a=JSON.parse(s)}catch{}return{body:a,ok:n.ok&&a?.success!==!1,status:n.status,text:s}},Q=e=>{const t=(e.body?.errors??[]).map(r=>r.message).filter(r=>typeof r=="string");return`${String(e.status)}: ${De(t.length>0?t.join("; "):e.text)}`},je=(e,t,r)=>{let o=e;const n=[];for(const[s,a]of Object.entries(r))t?.[s]!==a&&(o=Oe(o,["vars",s],a),n.push(s));return{changed:n,text:o}},Me=(e,t)=>{e.info(`next: \`<provider>/<model>\` slugs (e.g. "anthropic/claude-sonnet-5") now route through gateway "${t}". Before the first call,`),e.info(` configure how the provider is paid for in the Cloudflare dashboard (AI > AI Gateway > ${t}):`),e.info(` - Unified Billing (OpenAI, Anthropic, Google, xAI, Groq, DeepSeek): load credits — ${V.unifiedBilling}`),e.info(` - a key stored on the gateway (Mistral, Perplexity, OpenRouter, …): ${V.byok}`),e.info(" Then redeploy (`lunora deploy`) so the Worker picks up the new vars.")},Le=async(e,t,r,o,n,s)=>{const a=`${Re}/${encodeURIComponent(r)}/ai-gateway/gateways`,i=await X(t,`${a}/${encodeURIComponent(n)}`,o);if(i.ok){const l=i.body?.result?.collect_logs;return{action:"existing",collectLogs:typeof l=="boolean"?l:s}}if(i.status===401||i.status===403)return b(e,W(i.status),`ai-gateway: could not read AI Gateway "${n}" (${Q(i)})`);const c=await X(t,a,o,{body:JSON.stringify({cache_invalidate_on_update:!0,cache_ttl:0,collect_logs:s,id:n,rate_limiting_interval:0,rate_limiting_limit:0}),method:"POST"});return c.ok?{action:"created",collectLogs:s}:b(e,W(c.status),`ai-gateway: could not create AI Gateway "${n}" (${Q(c)})`)},Pe=e=>{const{logger:t}=e,r=de(e.cwd);if(r===void 0)return b(t,m.NOT_FOUND,"ai-gateway: no wrangler.jsonc found — run `lunora init` (or `lunora dev`) first.");const{parsed:o,text:n}=ue(r);if(o===void 0)return b(t,m.USAGE,`ai-gateway: could not parse ${r} as JSONC.`);const s=Y(e.id)??Y(o.name);return s===void 0?b(t,m.USAGE,"ai-gateway: no gateway id — pass --id <id>, or set `name` in wrangler.jsonc."):s.length>K?b(t,m.USAGE,`ai-gateway: gateway id "${s}" is longer than ${String(K)} characters — pass a shorter --id.`):{gatewayId:s,parsed:o,text:n,wranglerPath:r}},j=e=>e?"on":"off",Ge=(e,t)=>(e.info(`ai-gateway (dry run): would create or reuse AI Gateway "${t.gatewayId}" (log collection ${j(t.collectLogs)}).`),e.info(t.varsWritten.length===0?`ai-gateway (dry run): ${t.wranglerPath} vars are already up to date.`:`ai-gateway (dry run): would write ${t.varsWritten.join(", ")} into ${t.wranglerPath} vars.`),t.accountId===void 0&&e.warn("ai-gateway (dry run): no CLOUDFLARE_ACCOUNT_ID (or `account_id` in wrangler.jsonc) — a real run will stop there."),{code:0,data:t}),Fe=async e=>{const{logger:t}=e,r=Pe(e);if("code"in r)return r;const{gatewayId:o,parsed:n,text:s,wranglerPath:a}=r,i=e.logs!==!1,{accountId:c,token:l}=fe(e.environment??process.env,n.account_id),f={[Ie]:o,...c===void 0?{}:{[Ce]:c}},d=je(s,n.vars,f);if(e.dryRun===!0)return Ge(t,{accountId:c,action:"planned",collectLogs:i,dryRun:!0,gatewayId:o,varsWritten:d.changed,wranglerPath:a});if(l===void 0||c===void 0){const g=[l===void 0?"CLOUDFLARE_API_TOKEN (an API token with AI Gateway Write)":void 0,c===void 0?"CLOUDFLARE_ACCOUNT_ID (or `account_id` in wrangler.jsonc)":void 0].filter(y=>y!==void 0);return b(t,m.AUTH,`ai-gateway: missing ${g.join(" and ")}.`)}const h=await Le(t,e.fetch??globalThis.fetch.bind(globalThis),c,l,o,i);return"code"in h?h:(h.action==="created"?t.success(`ai-gateway: created AI Gateway "${o}" (log collection ${j(h.collectLogs)}).`):t.info(`ai-gateway: AI Gateway "${o}" already exists — reusing it (log collection ${j(h.collectLogs)}; change it in the dashboard).`),d.changed.length>0?(Te(a,d.text,"utf8"),t.success(`ai-gateway: wrote ${d.changed.join(", ")} into ${a} vars.`)):t.info(`ai-gateway: ${a} vars are already up to date.`),Me(t,o),{code:0,data:{accountId:c,action:h.action,collectLogs:h.collectLogs,dryRun:!1,gatewayId:o,varsWritten:d.changed,wranglerPath:a}})},xe=15e3,qe="https://api.cloudflare.com/client/v4/graphql",_={analytics:"Account Analytics Read",notificationsRead:"Notifications Read",notificationsWrite:"Notifications Write"},Be={auth:m.AUTH,failure:m.FAILURE,"not-found":m.NOT_FOUND,permission:m.PERMISSION,"rate-limited":m.RATE_LIMITED,rejected:m.USAGE,unavailable:m.UNAVAILABLE};class S extends Error{kind;status;constructor(t,r,o){super(t),this.name="CloudflareApiError",this.kind=r,this.status=o}}const Je=e=>e===401?"auth":e===403?"permission":e===404?"not-found":e===429?"rate-limited":e>=500?"unavailable":"rejected",pe=e=>{try{const r=JSON.parse(e);if(Array.isArray(r.errors)){const o=r.errors.map(n=>typeof n=="object"&&n!==null&&"message"in n?String(n.message):void 0).filter(n=>n!==void 0&&n.length>0);if(o.length>0)return o}}catch{}const t=e.trim().slice(0,200);return t.length>0?[t]:[]},We=9106,Ye=(e,t)=>{try{const r=JSON.parse(e);return Array.isArray(r.errors)&&r.errors.some(o=>typeof o=="object"&&o!==null&&"code"in o&&o.code===t)}catch{return!1}},z=(e,t,r,o)=>{const n=t===400&&Ye(r,We)?"auth":Je(t),s=pe(r).join("; ");let a="";return n==="auth"?a=` — check that CLOUDFLARE_API_TOKEN is a valid token; it needs the "${o}" permission on this account`:n==="permission"&&(a=` — the API token needs the "${o}" permission on this account`),new S(`${e} failed (HTTP ${String(t)})${s.length>0?`: ${s}`:""}${a}.`,n,t)},Z=(e,t)=>{const r=t instanceof Error&&(t.name==="TimeoutError"||t.name==="AbortError");let o=t instanceof Error?t.message:String(t);return r&&(o="no answer in time"),new S(`${e} failed: ${o}.`,"unavailable")},He=10,Ke=e=>{const{accountId:t,token:r}=e,o=e.timeoutMs??xe,n=e.fetch??globalThis.fetch.bind(globalThis),s=async(a,i,c,l)=>{let f;try{f=await ke({accountId:t,apiToken:r,fetch:n,init:{method:i,signal:AbortSignal.timeout(o),...l===void 0?{}:{body:JSON.stringify(l)}},path:c})}catch(d){throw Z(a,d)}if(!f.ok)throw z(a,f.status,f.text,i==="GET"?_.notificationsRead:_.notificationsWrite);return f.body};return{accountId:t,graphql:async(a,i,c={})=>{let l;try{l=await n(qe,{body:JSON.stringify({query:i,variables:c}),headers:{Authorization:`Bearer ${r}`,"Content-Type":"application/json"},method:"POST",signal:AbortSignal.timeout(o)})}catch(d){throw Z(a,d)}const f=await l.text();if(!l.ok)throw z(a,l.status,f,_.analytics);try{const d=JSON.parse(f);return{data:d.data??void 0,errors:Array.isArray(d.errors)&&d.errors.length>0?pe(f):[]}}catch{throw new S(`${a} failed: the GraphQL API answered with something that is not JSON.`,"unavailable",l.status)}},notifications:async(a,i,c,l)=>(await s(a,i,c,l)).result,notificationsList:async(a,i,c=He)=>{const l=async f=>{const d=await s(a,"GET",`${i}${i.includes("?")?"&":"?"}page=${String(f)}`),h=Array.isArray(d.result)?d.result:[],g=d.result_info;return typeof g?.total_pages=="number"&&f<g.total_pages&&f<c?[...h,...await l(f+1)]:h};return l(1)}}},$="billing_usage_alert",ee={"do-duration":"worker_durable_objects_duration","do-requests":"worker_durable_objects_requests","do-rows-read":"worker_durable_objects_storage_reads","do-rows-written":"worker_durable_objects_storage_writes","workers-requests":"worker_requests"},Ve=6,C=e=>typeof e=="object"&&e!==null&&!Array.isArray(e)?e:void 0,N=(e,t)=>{const r=t.toLowerCase(),o=Object.keys(e).find(n=>n.toLowerCase()===r);return o===void 0?void 0:e[o]},M=(e,t)=>{for(const r of t){const o=N(e,r);if(typeof o=="string"&&o.length>0)return o}},Xe=e=>{if(typeof e=="string"&&e.length>0)return{id:e,source:"available-alerts"};const t=C(e),r=t===void 0?void 0:M(t,["id","value","key","name"]);if(t===void 0||r===void 0)return;const o=M(t,["description","label","display_name","displayName","name"]);return{id:r,source:"available-alerts",...o===void 0||o===r?{}:{label:o}}},Qe=["AvailableValues","available_values","values","options","enum","choices"],ye=e=>e.map(t=>Xe(t)).filter(t=>t!==void 0),ze=e=>M(e,["key","name","filter","id"])!=="product"?[]:Qe.flatMap(t=>{const r=N(e,t);return Array.isArray(r)?ye(r):[]}),L=(e,t,r)=>{if(t>Ve)return;if(Array.isArray(e)){for(const n of e)L(n,t+1,r);return}const o=C(e);if(o!==void 0){r.push(...ze(o));for(const[n,s]of Object.entries(o))n.toLowerCase()==="product"&&Array.isArray(s)?r.push(...ye(s)):typeof s=="object"&&s!==null&&L(s,t+1,r)}},Ze=e=>{const t=C(e);if(t!==void 0){for(const r of Object.values(t))if(Array.isArray(r)){const o=r.map(n=>C(n)).find(n=>n!==void 0&&N(n,"type")===$);if(o!==void 0)return o}}},et=e=>e.filter(t=>t.alert_type===$&&Array.isArray(t.filters?.product)).flatMap(t=>(t.filters?.product).filter(r=>typeof r=="string"&&r.length>0)).map(t=>({id:t,source:"existing-policy"})),tt=(e,t,r)=>{const o=Ze(e),n=[];o!==void 0&&L(N(o,"filter_options"),0,n);const s=new Map;for(const a of[...n,...et(r)])s.has(a.id)||s.set(a.id,a);return{eligible:t?o!==void 0:void 0,products:[...s.values()]}},rt=/[^a-z\d]+/u,ot=e=>`${e.id} ${e.label??""}`.toLowerCase().split(rt).filter(t=>t.length>0),nt={"d1-rows-read":{all:[["d1"],["read"]]},"d1-rows-written":{all:[["d1"],["writ"]]},"do-duration":{all:[["durable"],["duration"]]},"do-requests":{all:[["durable"],["request"]]},"do-rows-read":{all:[["durable"],["read"]],none:["request"]},"do-rows-written":{all:[["durable"],["writ"]]},"workers-cpu":{all:[["worker"],["cpu"]],none:["durable"]},"workers-requests":{all:[["worker"],["request"]],none:["durable","cpu","kv","d1"]}},st=(e,t)=>{const r=ot(t),o=a=>r.some(i=>i.startsWith(a)),{all:n,none:s=[]}=nt[e];return n.every(a=>a.some(i=>o(i)))&&!s.some(a=>o(a))},we=(e,t)=>{const r=ee[e],o=r===void 0?void 0:t.find(a=>a.id===r);if(o!==void 0)return{product:o,status:"matched"};const n=new Set(Object.values(ee)),s=t.filter(a=>!n.has(a.id)&&st(e,a));return s.length===1&&s[0]!==void 0?{product:s[0],status:"matched"}:s.length>1?{candidates:s.map(a=>a.id),status:"ambiguous"}:r===void 0?{status:"no-product"}:{product:{id:r,source:"documented"},status:"matched"}},te="workersInvocationsAdaptive",at="durableObjectsInvocationsAdaptiveGroups",R="durableObjectsPeriodicGroups",re="d1AnalyticsAdaptiveGroups",A=[{candidates:[{field:"requests",unit:"count"}],dataset:te,filter:"datetime",id:"workers-requests",label:"Workers requests"},{candidates:[{field:"cpuTimeUs",unit:"microseconds"}],dataset:te,filter:"datetime",id:"workers-cpu",label:"Workers CPU time"},{candidates:[{field:"requests",unit:"count"}],dataset:at,filter:"date",id:"do-requests",label:"Durable Objects requests"},{candidates:[{field:"activeTime",unit:"unknown"}],dataset:R,filter:"date",id:"do-duration",label:"Durable Objects duration"},{candidates:[{field:"rowsRead",unit:"count"}],dataset:R,filter:"date",id:"do-rows-read",label:"Durable Objects rows read"},{candidates:[{field:"rowsWritten",unit:"count"}],dataset:R,filter:"date",id:"do-rows-written",label:"Durable Objects rows written"},{candidates:[{field:"rowsRead",unit:"count"}],dataset:re,filter:"datetime-hour",id:"d1-rows-read",label:"D1 rows read"},{candidates:[{field:"rowsWritten",unit:"count"}],dataset:re,filter:"datetime-hour",id:"d1-rows-written",label:"D1 rows written"}],oe=e=>String(e).padStart(2,"0"),it=e=>{const t=new Date(Date.UTC(e.getUTCFullYear(),e.getUTCMonth()-1,1)),r=new Date(Date.UTC(e.getUTCFullYear(),e.getUTCMonth(),0)),o=new Date(Date.UTC(e.getUTCFullYear(),e.getUTCMonth(),1)),n=s=>`${String(s.getUTCFullYear())}-${oe(s.getUTCMonth()+1)}-${oe(s.getUTCDate())}`;return{endDate:n(r),nextStartDate:n(o),startDate:n(t)}},ct=(e,t)=>{const r=JSON.stringify(`${t.startDate}T00:00:00Z`),o=JSON.stringify(`${t.nextStartDate}T00:00:00Z`);switch(e){case"date":return`{ date_geq: ${JSON.stringify(t.startDate)}, date_lt: ${JSON.stringify(t.nextStartDate)} }`;case"datetime":return`{ datetime_geq: ${r}, datetime_lt: ${o} }`;default:return`{ AND: [{ datetimeHour_geq: ${r}, datetimeHour_lt: ${o} }] }`}},lt=e=>`query LunoraTypeFields { __type(name: ${JSON.stringify(e)}) { fields { name type { name ofType { name ofType { name ofType { name } } } } } } }`,dt=e=>{let t=e;for(;t!=null;){if(typeof t.name=="string"&&t.name.length>0)return t.name;t=t.ofType}},ut=e=>{const t=new Map;return async r=>{const o=t.get(r);if(o!==void 0)return o;const n=e.graphql(`Reading the analytics schema (${r})`,lt(r)).then(s=>{if(s.errors.length>0)throw new S(`Reading the analytics schema failed: ${s.errors.join("; ")}.`,"rejected");const i=s.data?.__type?.fields??[];return new Map(i.map(c=>[c.name,dt(c.type)]))});return t.set(r,n),n}},ve=async(e,t,r)=>{const o=await e(t),[n,...s]=r;if(n===void 0)return o;const a=o.get(n);if(a===void 0)throw new S(`the analytics schema has no \`${n}\` on \`${t}\``,"rejected");return ve(e,a,s)},ft=e=>e instanceof Error?e.message:String(e),mt=async(e,t,r,o,n)=>{const{id:s,label:a}=o;try{const i=await ve(t,r,["viewer","accounts",o.dataset,"sum"]),c=o.candidates.find(y=>i.has(y.field));if(c===void 0){const y=o.candidates.map(u=>`\`${u.field}\``).join(", ");return{id:s,label:a,reason:`\`${o.dataset}.sum\` exposes no ${y} field`,status:"unavailable"}}const l=`query LunoraUsage($accountTag: string) { viewer { accounts(filter: { accountTag: $accountTag }) { ${o.dataset}(limit: 1, filter: ${ct(o.filter,n)}) { sum { ${c.field} } } } } }`,f=await e.graphql(`Reading ${a}`,l,{accountTag:e.accountId});if(f.errors.length>0)return{id:s,label:a,reason:f.errors.join("; "),status:"unavailable"};const d=f.data?.viewer?.accounts?.[0]?.[o.dataset],h=Array.isArray(d)?d[0]:void 0,g=h===void 0?0:h.sum?.[c.field];return typeof g!="number"||!Number.isFinite(g)?{id:s,label:a,reason:`the response carried no number for \`${c.field}\``,status:"unavailable"}:{field:`${o.dataset}.sum.${c.field}`,id:s,label:a,status:"ok",unit:c.unit,value:g}}catch(i){return{id:s,label:a,reason:ft(i),status:"unavailable"}}},ht=async(e,t)=>{const r=await e.graphql("Reading the analytics schema","query LunoraQueryRoot { __schema { queryType { name } } }"),o=r.data?.__schema?.queryType?.name;if(r.errors.length>0||o===void 0){const s=r.errors.length>0?r.errors.join("; "):"the schema root could not be read";return A.map(({id:a,label:i})=>({id:a,label:i,reason:s,status:"unavailable"}))}const n=ut(e);return Promise.all(A.map(async s=>mt(e,n,o,s,t)))},U="Lunora usage: ",gt=3,x="Cloudflare does not document the unit of a usage alert's limit; limits are sent as plain request counts. Check the stored limit in the dashboard.",pt={"do-requests":1e6,"workers-requests":1e7},yt=100,wt=e=>{const t=Math.ceil(e);if(t<=0)return 0;const r=10**Math.max(0,Math.floor(Math.log10(t))-1);return Math.ceil(t/r)*r},vt=(e,t,r)=>{const o=wt(e*t);return o>r?{basis:"history",threshold:o}:{basis:"floor",threshold:r}},P=e=>{const t=e.filters?.product;return Array.isArray(t)?t.filter(r=>typeof r=="string"):[]},bt=e=>{const t=e.filters?.limit,r=Array.isArray(t)?t[0]:void 0,o=typeof r=="string"?Number(r):Number.NaN;return Number.isFinite(o)?o:void 0},q=e=>{const t={};for(const[r,o]of Object.entries(e?.mechanisms??{}))Array.isArray(o)&&(t[r]=o.filter(n=>typeof n=="object"&&n!==null&&"id"in n&&typeof n.id=="string"));return t},$t=(e,t)=>{const r={};for(const[o,n]of[...Object.entries(e),...Object.entries(t)]){const s=new Set((r[o]??[]).map(a=>a.id));r[o]=[...r[o]??[],...n.filter(a=>!s.has(a.id))]}return Object.fromEntries(Object.entries(r).filter(([,o])=>o.length>0))},I=e=>Object.entries(e).flatMap(([t,r])=>r.map(o=>`${t}:${o.id}`)),At=(e,t)=>JSON.stringify(I(e).toSorted((r,o)=>r.localeCompare(o)))===JSON.stringify(I(t).toSorted((r,o)=>r.localeCompare(o))),St=(e,t)=>e.enabled===!0&&e.name===t.name&&JSON.stringify(e.filters?.limit)===JSON.stringify(t.filters.limit)&&JSON.stringify(P(e))===JSON.stringify(t.filters.product)&&At(q(e),t.mechanisms),_t=(e,t)=>{const r={};return e.length>0&&(r.email=e.map(o=>({id:o}))),t.length>0&&(r.webhooks=t.map(o=>({id:o}))),r},Et=(e,t,r)=>{const o=r.thresholds?.[e],n=r.usage.find(c=>c.id===e),s=n?.status==="ok"?n.value:void 0;if(o!==void 0)return{basis:"explicit",lastMonth:s,threshold:o};const a=pt[e];return a===void 0?{kind:"unit-unverified",reason:`the unit Cloudflare meters "${t.id}" in is not documented and cannot be matched to the usage reading; set one yourself with --threshold ${e}=<n>`}:s!==void 0?{...vt(s,r.multiplier,a),lastMonth:s}:r.allowFloor===!0?{basis:"floor-usage-unavailable",lastMonth:void 0,threshold:a}:{kind:"usage-unavailable",reason:`last month's usage could not be read (${n?.status==="unavailable"?n.reason:"no reading"}), and an alert at the floor could fire every month on an account that already exceeds it; pass --threshold ${e}=<n>, or --allow-floor`}},Tt=(e,t)=>{const r=bt(e);if(r===void 0||t===void 0||r<=0||t<=0)return;const o=Math.max(r/t,t/r);return o>=yt?`its limit ${String(r)} differs from the ${String(t)} this would plan by ${String(Math.round(o))}× — one of the two may be in the wrong unit`:void 0},G=e=>`${U}${e}`,Ot=(e,t)=>e===void 0?"create":St(e,t)?"unchanged":"update",kt=(e,t)=>{switch(e){case"explicit":return"set with --threshold";case"floor-usage-unavailable":return"the included monthly allowance, applied with --allow-floor because usage could not be read";case"history":return`${String(t)}× last month`;default:return"the included monthly allowance (floor)"}},Ct=(e,t,r)=>{const{id:o,label:n}=e,s=we(o,t.products);if(s.status==="no-product")return{kind:"no-product",metric:o,reason:"Cloudflare has no usage alert for this product; the account-wide budget alert is its guard"};if(s.status==="ambiguous")return{kind:"ambiguous",metric:o,reason:`several offered products could mean this metric (${s.candidates.join(", ")})`};const{product:a}=s,i=r.find(p=>p.name===G(n)),c=r.find(p=>p.enabled===!0&&p.name?.startsWith(U)!==!0&&P(p).includes(a.id)),l=Et(o,a,t);if(i===void 0&&c!==void 0){const p=Tt(c,"threshold"in l?l.threshold:void 0);return{kind:"covered",metric:o,reason:`already alerted by the existing policy "${c.name??c.id??"?"}"`,...p===void 0?{}:{warning:p}}}if(!("threshold"in l))return{...l,metric:o};const f=_t(t.emails,t.webhooks),d=q(i),h=i===void 0||t.replaceRecipients===!0?f:$t(d,f),g=new Set(I(d)),y=new Set(I(h)),u={alert_type:$,description:`Managed by \`lunora cloudflare alerts setup\`: ${kt(l.basis,t.multiplier)}.`,enabled:!0,filters:{limit:[String(l.threshold)],product:[a.id]},mechanisms:h,name:G(n)},w=i===void 0?[]:P(i);return{action:Ot(i,u),basis:l.basis,body:u,lastMonth:l.lastMonth,metric:o,...i?.id===void 0?{}:{policyId:i.id},...i!==void 0&&JSON.stringify(w)!==JSON.stringify([a.id])?{previousProduct:w}:{},product:a.id,productSource:a.source,recipients:{added:[...y].filter(p=>!g.has(p)),removed:[...g].filter(p=>!y.has(p))},threshold:l.threshold}},It=e=>{const t=e.policies.filter(n=>n.alert_type===$),r=new Set(A.map(n=>G(n.label))),o={alerts:[],duplicates:[],orphans:t.filter(n=>n.name?.startsWith(U)===!0&&!r.has(n.name)),skipped:[]};for(const n of r)o.duplicates.push(...t.filter(s=>s.name===n).slice(1));for(const n of A){const s=Ct(n,e,t);"action"in s?o.alerts.push(s):o.skipped.push(s)}return o},Nt="Cloudflare's API has no endpoint that sends a test notification — not for webhooks and not for email — so `lunora cloudflare alerts test` sends nothing.",Ut="To test a webhook for real, create it in the dashboard (Alerts > Destinations > Webhooks > Create) and finish with Save and Test.",Dt="Email destinations cannot be tested at all: Cloudflare offers no test send for them. Check the address on each policy below instead.",ne=e=>Array.isArray(e)?e:[],se=30,Rt=async(e,t,r,o,n)=>{const s=t.filter(u=>u.alert_type===$&&u.name?.startsWith(U)===!0),a=s.map(u=>q(u)),i=new Set([...a.flatMap(u=>(u.webhooks??[]).map(w=>w.id)),...r]),c=[...new Set(a.flatMap(u=>(u.email??[]).map(w=>w.id)))],l=new Set(s.map(u=>u.id)),f=new Date(n.getTime()-se*24*60*60*1e3).toISOString(),[d,h]=await Promise.all([e.notifications("Listing webhook destinations","GET","/alerting/v3/destinations/webhooks"),s.length===0?Promise.resolve([]):e.notificationsList("Reading notification history",`/alerting/v3/history?per_page=25&since=${encodeURIComponent(f)}`)]),g=ne(d).map(u=>({...u,referenced:u.id!==void 0&&i.has(u.id)})),y=ne(h).filter(u=>u.alert_type===$&&u.policy_id!==void 0&&l.has(u.policy_id));o.warn(Nt),s.length===0&&o.info("No `lunora cloudflare alerts setup` policies exist on this account yet — run `lunora cloudflare alerts setup` first.");for(const u of[...i].filter(w=>!g.some(p=>p.id===w)))o.warn(`Webhook destination ${u} is referenced but does not exist on this account.`);for(const u of g.filter(w=>w.referenced))o.info(`webhook "${u.name??u.id??"?"}" (${u.type??"generic"}): last delivered ${u.last_success??"never"}, last failed ${u.last_failure??"never"}`);if(o.info(Ut),c.length>0&&o.info(`${Dt} Addresses on the policies: ${c.join(", ")}.`),y.length===0)o.info(`Cloudflare's notification history shows nothing sent for these policies in the last ${String(se)} days (they only fire once a threshold is crossed).`);else for(const u of y)o.info(`sent ${u.sent??"?"}: "${u.name??"?"}" via ${u.mechanism_type??"?"} to ${u.mechanism??"?"}`);return{emails:c,history:y,testSent:!1,webhooks:g}},D="Budget alert (account-wide USD threshold): Cloudflare documents no API to create or read one, so this cannot be checked. Create it in the dashboard: Manage Account > Billing > Billable Usage > Create budget alert.",jt="Alerts > Overview > Create an Alert, alert type Usage Based Billing",v=(e,t,r,o)=>(e.error(r),{code:t,error:r,...o===void 0?{}:{data:o}}),B=(e,t,r)=>{if(t instanceof S)return v(e,Be[t.kind],t.message,r);throw t},J=(e,t)=>({accountId:e.accountId,budgetAlert:{checkable:!1,dashboardPath:"Manage Account > Billing > Billable Usage"},limitUnitCaveat:x,...t===void 0?{}:{eligible:t.discovery.eligible,period:t.period,products:t.discovery.products}}),E=e=>e.toLocaleString("en-US",{maximumFractionDigits:0}),be=(e,t)=>{t===!1&&e.warn("This account is not eligible for Usage Based Billing notifications (they are offered to Pay-as-you-go accounts; most Enterprise contracts are not supported).")},$e=e=>({code:m.SUCCESS,data:e}),Mt=/^[^\s@]+@[^\s@][^\s.@]*\.[^\s@]+$/u,Ae=new Set(A.map(e=>e.id)),Lt=e=>Ae.has(e),Pt=e=>{const t={};for(const r of e.flatMap(o=>o.split(","))){const[o="",n=""]=r.split("=").map(a=>a.trim()),s=Number(n);if(!Lt(o))return{error:`--threshold "${r}": unknown metric "${o}" — one of ${[...Ae].join(", ")}.`};if(!Number.isFinite(s)||s<=0)return{error:`--threshold "${r}": the limit must be a positive number.`};t[o]=Math.ceil(s)}return t},Gt=e=>{const t=(e.emails??[]).flatMap(a=>a.split(",")).map(a=>a.trim()).filter(a=>a.length>0),r=(e.webhooks??[]).map(a=>a.trim()).filter(a=>a.length>0),o=e.multiplier===void 0?gt:Number(e.multiplier),n=Pt(e.thresholds??[]);if(t.length===0&&r.length===0)return{error:"alerts setup needs somewhere to send the alerts: pass --email <address> and/or --webhook <destination-id>."};const s=t.find(a=>!Mt.test(a));return s!==void 0?{error:`--email "${s}" is not an email address.`}:!Number.isFinite(o)||o<1?{error:`--multiplier must be a number of at least 1 (got "${e.multiplier??""}").`}:"error"in n?n:{allowFloor:e.allowFloor===!0,emails:t,multiplier:o,replaceRecipients:e.replaceRecipients===!0,thresholds:n,webhooks:r}},Ft={explicit:()=>"set with --threshold",floor:e=>`floor: included monthly allowance; last month ${E(e.lastMonth??0)}`,"floor-usage-unavailable":()=>"floor: usage could not be read, applied with --allow-floor",history:e=>`last month ${E(e.lastMonth??0)}`},xt=e=>{const t=[...e.added.map(r=>`+${r}`),...e.removed.map(r=>`-${r}`)];return t.length===0?"recipients unchanged":`recipients ${t.join(" ")}`},qt=e=>{const t=e.productSource==="documented"?"documented id":"offered by the account",r=e.previousProduct===void 0?"":`, product was ${e.previousProduct.join(", ")||"none"}`;return`${e.action.padEnd(9)} ${e.body.name} — product ${e.product} (${t}${r}), limit ${E(e.threshold)} (${Ft[e.basis](e)}); ${xt(e.recipients)}`},F=e=>A.find(t=>t.id===e)?.label??e,Bt=(e,t,r,o)=>{o.info(`Usage alerts at ${String(t)}× last month (${r.startDate} to ${r.endDate}), never below the included allowance:`);for(const n of e.alerts)o.info(` ${qt(n)}`);for(const n of e.skipped)o.info(` skipped ${F(n.metric)} — ${n.reason}`),n.warning!==void 0&&o.warn(`${F(n.metric)}: the existing alert ${n.warning}.`);for(const n of e.orphans)o.warn(`"${n.name??"?"}" (${n.id??"?"}) is named like a \`lunora cloudflare alerts\` policy but matches no metric; it was left alone.`);for(const n of e.duplicates)o.warn(`"${n.name??"?"}" exists more than once; ${n.id??"?"} was left alone — delete the extra one in the dashboard.`);e.skipped.some(n=>n.kind==="unit-unverified"||n.kind==="ambiguous")&&o.info(`To set the skipped ones by hand: ${jt}.`),o.info(x),o.info(D)},Jt=async(e,t)=>{if(e.yes===!0)return;if(e.confirm===void 0&&(!process.stdin.isTTY||e.format==="json"))return v(e.logger,m.USAGE,"alerts setup: refusing to change notification policies without confirmation — re-run with --yes.");const r=t.flatMap(s=>s.recipients.removed),o=r.length===0?"":` This REMOVES recipients: ${[...new Set(r)].join(", ")}.`;if(!await(e.confirm??Ne)(`Apply ${String(t.length)} notification policy change(s)?${o}`))return e.logger.info("alerts setup: aborted"),{code:m.CANCELLED,error:"alerts setup: aborted at the confirmation prompt"}},Wt=async(e,t,r,o)=>{const s=(await Promise.all(t.map(async a=>e.notifications(`Reading webhook destination ${a}`,"GET",`/alerting/v3/destinations/webhooks/${encodeURIComponent(a)}`).then(()=>{},i=>({error:i,id:a}))))).find(a=>a!==void 0);if(s!==void 0)return s.error instanceof S&&s.error.kind==="not-found"?v(r,m.USAGE,`--webhook ${s.id}: no such webhook destination on account ${e.accountId}.`,o):B(r,s.error,o)},Yt=async(e,t)=>{const r=t.action==="create"?await e.notifications(`Creating "${t.body.name}"`,"POST","/alerting/v3/policies",t.body):await e.notifications(`Updating "${t.body.name}"`,"PUT",`/alerting/v3/policies/${encodeURIComponent(t.policyId??"")}`,t.body);return typeof r=="object"&&r!==null&&"id"in r&&typeof r.id=="string"?r.id:t.policyId},Ht=async(e,t,r)=>await Promise.all(t.map(async({alert:n,id:s})=>{try{const a=await e.notifications(`Reading back "${n.body.name}"`,"GET",`/alerting/v3/policies/${encodeURIComponent(s)}`),i={enabled:a?.enabled,id:s,limit:a?.filters?.limit,name:a?.name,product:a?.filters?.product};return r.info(`Cloudflare stored "${i.name??n.body.name}": product ${JSON.stringify(i.product)}, limit ${JSON.stringify(i.limit)}.`),JSON.stringify(i.limit)!==JSON.stringify(n.body.filters.limit)&&r.warn(`"${n.body.name}": Cloudflare stored limit ${JSON.stringify(i.limit)}, not the ${JSON.stringify(n.body.filters.limit)} sent.`),i}catch(a){return r.warn(`Could not read "${n.body.name}" back: ${a instanceof Error?a.message:String(a)}`),{id:s}}})),Kt=async(e,t,r,o)=>{const n=[],s=[];let a;for(const c of t)try{const l=await Yt(e,c);n.push({action:c.action,metric:c.metric,...l===void 0?{}:{policyId:l}}),l!==void 0&&s.push({alert:c,id:l}),r.success(`${c.action==="create"?"Created":"Updated"} "${c.body.name}".`)}catch(l){a=l;break}const i={...o,applied:n,stored:await Ht(e,s,r)};return a===void 0?i:B(r,a,i)},ae=(e,t,r)=>{const o=t.skipped.filter(n=>n.kind==="usage-unavailable");return o.length>0?v(r,m.FAILURE,`alerts setup: no alert was set for ${o.map(n=>F(n.metric)).join(", ")} because last month's usage could not be read — pass --threshold <metric>=<n>, or --allow-floor to accept the floor.`,e):{code:m.SUCCESS,data:e}},Vt=async(e,t,r,o)=>{const{logger:n}=r,s=J(e,t),a=await Wt(e,o.webhooks,n,s);if(a!==void 0)return a;if(t.discovery.eligible===!1)return be(n,!1),n.info(D),v(n,m.PERMISSION,"alerts setup: the account cannot create Usage Based Billing notifications.",s);const i=It({...o,policies:t.policies,products:t.discovery.products,usage:t.usage});s.plan=i,Bt(i,o.multiplier,t.period,n);const c=i.alerts.filter(d=>d.action!=="unchanged");if(r.dryRun===!0||c.length===0)return n.info(r.dryRun===!0?"Dry run: nothing was changed.":"Every alert is already up to date."),ae(s,i,n);const l=await Jt(r,c);if(l!==void 0)return{...l,data:s};const f=await Kt(e,c,n,s);return"code"in f?f:ae(f,i,n)},Xt=e=>e.status!=="ok"?`unavailable (${e.reason})`:e.unit==="microseconds"?`${E(e.value)} µs`:E(e.value),Qt=(e,t,r)=>t?"no-product":e===void 0?"unknown":r.some(o=>o.enabled)?"active":r.length>0?"disabled-only":"none",ie=e=>e.map(t=>`"${t.name??t.id??"?"}" (limit ${JSON.stringify(t.limit)})${t.enabled?"":" — disabled, not protecting you"}`).join(", "),zt={active:e=>`alert: ${ie(e.alerts)}`,"disabled-only":e=>`alert: none active; ${ie(e.alerts)}`,"no-product":()=>"alert: none possible — Cloudflare has no usage alert for this; the budget alert is its guard",none:()=>"alert: none",unknown:()=>"alert: unknown (several offered products could mean this)"},Zt=(e,t,r)=>{const o=we(e.id,t.discovery.products),n=o.status==="matched"?o.product:void 0,s=(n===void 0?[]:r.filter(a=>Array.isArray(a.filters?.product)&&a.filters.product.includes(n.id))).map(a=>({enabled:a.enabled===!0,id:a.id,limit:a.filters?.limit,name:a.name}));return{alerts:s,coverage:Qt(n?.id,o.status==="no-product",s),id:e.id,label:e.label,...n===void 0?{}:{product:n.id,productSource:n.source},usage:e}},er=(e,t,r)=>{const o=t.policies.filter(s=>s.alert_type===$),n=t.usage.map(s=>Zt(s,t,o));r.info(`Cloudflare account ${e.accountId} — usage ${t.period.startDate} to ${t.period.endDate}`);for(const s of n)r.info(` ${s.label}: ${Xt(s.usage)} — ${zt[s.coverage](s)}`);return r.info(`Usage Based Billing notifications on the account: ${String(o.length)} (${String(o.filter(s=>s.enabled===!0).length)} enabled).`),r.info(x),be(r,t.discovery.eligible),r.info(D),$e({...J(e,t),metrics:n})},tr=e=>{const t=de(e);return t===void 0?void 0:ue(t).parsed?.account_id},rr=e=>{const{accountId:t,token:r}=fe(e.environment??process.env,tr(e.cwd));return r===void 0?v(e.logger,m.AUTH,`CLOUDFLARE_API_TOKEN is not set. \`lunora cloudflare alerts\` calls the Cloudflare API with an API token (a wrangler login session is not reused); create one with the "${_.notificationsWrite}" and "${_.analytics}" permissions ("${_.notificationsRead}" is enough for status and test).`):t===void 0?v(e.logger,m.USAGE,"No Cloudflare account: set CLOUDFLARE_ACCOUNT_ID or `account_id` in wrangler.jsonc."):Ke({accountId:t,token:r,...e.fetch===void 0?{}:{fetch:e.fetch}})},Se=async e=>{const t=await e.notifications("Listing notification policies","GET","/alerting/v3/policies");return Array.isArray(t)?t:[]},or=async(e,t)=>{const r=it(t.now??new Date),{logger:o}=t,[n,s,a]=await Promise.all([Se(e),e.notifications("Listing the alert types this account is eligible for","GET","/alerting/v3/available_alerts").then(i=>({ok:!0,value:i}),i=>({error:i,ok:!1})),ht(e,r).catch(i=>{const c=i instanceof Error?i.message:String(i);return o.warn(`Usage could not be read: ${c}`),A.map(({id:l,label:f})=>({id:l,label:f,reason:c,status:"unavailable"}))})]);return s.ok||o.warn(`Could not read which alert types the account is eligible for: ${s.error instanceof Error?s.error.message:String(s.error)}`),{discovery:tt(s.ok?s.value:void 0,s.ok,n),period:r,policies:n,usage:a}},nr=async(e,t)=>{const r=await Se(e),o=await Rt(e,r,t.webhooks??[],t.logger,t.now??new Date);return t.logger.info(D),$e({...J(e),deliveries:o})},sr=async e=>{const t=e.subcommand==="setup"?Gt(e):void 0;if(t!==void 0&&"error"in t)return v(e.logger,m.USAGE,t.error);const r=rr(e);if(!("graphql"in r))return r;try{if(e.subcommand==="test")return await nr(r,e);const o=await or(r,e);return t===void 0?er(r,o,e.logger):await Vt(r,o,e,t)}catch(o){return B(e.logger,o)}},ce=new Set(["build","delete","images","info","list","push"]),ar=new Set(["build","push"]),le=new Set(["images list","info","list"]),ir=async e=>{const[t,...r]=e.argument;if(t===void 0||!ce.has(t)){const d=`lunora cloudflare containers requires a subcommand: ${[...ce].toSorted((h,g)=>h.localeCompare(g)).join(" | ")}. Example: lunora cloudflare containers build ./containers/app --tag app:v1 --push`;return e.logger.error(d),{code:m.USAGE,error:d}}const o=e.format==="json",n=t==="images"?`images ${r[0]??""}`.trim():t;if(o&&!le.has(n)){const d=`containers ${n}: --format json is only available for the read subcommands (${[...le].toSorted((h,g)=>h.localeCompare(g)).join(" | ")}) — wrangler has no JSON rendering for the rest.`;return e.logger.error(d),{code:m.USAGE,error:d}}if(ar.has(t)&&!(e.dockerAvailable??Ue)()){const d=`containers ${t} needs a running Docker-compatible engine (it builds/pushes images locally). Start Docker or Colima and retry. Note: container images must target linux/amd64.`;return e.logger.error(d),{code:m.MISSING_DEPENDENCY,error:d}}const s=["containers",t,...r];o&&s.push("--json"),e.tag!==void 0&&s.push("--tag",e.tag),e.push===!0&&s.push("--push"),e.env!==void 0&&s.push("--env",e.env);const a=e.cwd??process.cwd(),i=he(ge(a),"wrangler",s),c={args:i.args,command:i.command,cwd:a};return e.logger.info(`running ${c.command} ${c.args.join(" ")}`),{code:(await(e.spawner??me)(c)).code,delegated:o,descriptor:c}},O=(e,t)=>(t!==void 0&&e.push("--env",t),e),cr=e=>{const t=O(["deployments","list"],e.env);return e.format==="json"&&t.push("--json"),t},lr=e=>{switch(e.subcommand){case"inspect":return e.versionId===void 0?{error:"deployments inspect requires a version id. Usage: lunora cloudflare deployments inspect <version-id>"}:{args:O(["versions","view",e.versionId],e.env)};case"list":return{args:cr(e)};case"promote":{if(e.versionId===void 0)return{error:"deployments promote requires a version id. Usage: lunora cloudflare deployments promote <version-id> --yes"};if(!e.yes)return{error:"deployments promote shifts 100% of live traffic. Re-run with --yes to confirm."};const t=O(["versions","deploy",`${e.versionId}@100%`,"--yes"],e.env);return e.message!==void 0&&t.push("--message",e.message),{args:t}}case"rollback":{if(!e.yes)return{error:"deployments rollback changes the live version. Re-run with --yes to confirm."};const t=O(["rollback"],e.env);return e.versionId!==void 0&&t.push(e.versionId),t.push("--yes"),e.message!==void 0&&t.push("--message",e.message),{args:t}}default:return{error:`deployments: unknown subcommand "${e.subcommand}"`}}},dr=async e=>{if(e.format==="json"&&e.subcommand!=="list"){const l=`deployments ${e.subcommand}: --format json is only available for \`deployments list\` — wrangler has no JSON rendering for the others.`;return e.logger.error(l),{code:m.USAGE,descriptor:void 0,error:l}}const{args:t,error:r}=lr(e);if(r!==void 0||t===void 0)return e.logger.error(r??"deployments: nothing to run"),{code:m.USAGE,descriptor:void 0,error:r};const{logger:o}=e,n=e.cwd??process.cwd(),s=he(ge(n),"wrangler",t),a={args:s.args,command:s.command,cwd:n};return o.info(`${a.command} ${a.args.join(" ")}`),{code:(await(e.spawner??me)(a)).code,delegated:e.format==="json",descriptor:a}},ur=e=>e==="list"||e==="inspect"||e==="rollback"||e==="promote",fr={ai:{absorbs:"gateway",tool:"ai-gateway"},alert:{tool:"alerts"}},mr=(e,t)=>{const r=fr[e];if(r!==void 0)return{rest:r.absorbs!==void 0&&t[0]===r.absorbs?t.slice(1):t,tool:r.tool};const o=k.find(n=>n.name===e)?.name;return o===void 0?void 0:{rest:t,tool:o}},hr={celld:"celld",node:"Node"},gr=e=>e==="status"||e==="setup"||e==="test",T=(e,t,r)=>(e.error(r),{code:t,error:r}),pr=e=>{const t=Math.max(...k.map(r=>r.name.length));e.info("lunora cloudflare <tool> — tools for an app deployed to your own Cloudflare account:");for(const r of k)e.info(` ${r.name.padEnd(t)} ${r.summary}`),r.usage!==""&&e.info(` ${" ".repeat(t)} lunora cloudflare ${r.name} ${r.usage}`);return e.info("Run `lunora cloudflare --help` for every tool's arguments and options."),{code:0}},yr=(e,t,r)=>{const{error:o,target:n}=Ee(e,r);return n===void 0?o??"no deploy target":n==="cloudflare"?void 0:`${r===void 0?`this project deploys to ${hr[n]??`"${n}"`}`:`\`--target ${n}\``} — \`lunora cloudflare ${t}\` only applies to Cloudflare.`},wr=(e,{logger:t,rest:r})=>r.length===0?void 0:T(t,m.USAGE,`cloudflare ${e}: takes no arguments, got "${r.join(" ")}"`),vr=async e=>{const{cwd:t,logger:r,options:o}=e;return wr("ai-gateway",e)??Fe({cwd:t,dryRun:o.dryRun===!0,id:o.id,logger:r,logs:o.logs})},br=async({cwd:e,format:t,logger:r,options:o,rest:n})=>{const s=n[0]??"status";return gr(s)?sr({allowFloor:o.allowFloor===!0,cwd:e,dryRun:o.dryRun===!0,format:t,logger:r,replaceRecipients:o.replaceRecipients===!0,subcommand:s,yes:o.yes===!0,...o.email===void 0?{}:{emails:o.email},...o.webhook===void 0?{}:{webhooks:o.webhook},...o.multiplier===void 0?{}:{multiplier:o.multiplier},...o.threshold===void 0?{}:{thresholds:o.threshold}}):T(r,m.USAGE,`cloudflare alerts: unknown subcommand "${s}" — expected status | setup | test`)},$r=async({cwd:e,format:t,logger:r,options:o,rest:n})=>{const s=await ir({argument:n,cwd:e,env:o.env,format:t,logger:r,push:o.push===!0,tag:o.tag});return{code:s.code,delegated:s.delegated,error:s.error}},Ar=async({cwd:e,format:t,logger:r,options:o,rest:n})=>{const[s,a]=n;if(!ur(s))return T(r,m.USAGE,`cloudflare deployments: unknown subcommand "${s??""}" — expected list | inspect | rollback | promote`);const i=await dr({cwd:e,env:o.env,format:t,logger:r,message:o.message,subcommand:s,versionId:a,yes:o.yes===!0});return{code:i.code,delegated:i.delegated,error:i.error}},Sr={"ai-gateway":vr,alerts:br,containers:$r,deployments:Ar},Mr=_e(async({argument:e,cwd:t,format:r,logger:o,options:n})=>{const[s,...a]=e;if(s===void 0||s==="")return pr(o);const i=mr(s,a);if(i===void 0)return T(o,m.USAGE,`cloudflare: unknown tool "${s}" — expected ${k.map(f=>f.name).join(" | ")}`);const{tool:c}=i,l=yr(t,c,n.target);return l!==void 0?T(o,m.USAGE,l):Sr[c]({cwd:t,format:r,logger:o,options:n,rest:i.rest})});export{Mr as execute};
@@ -1 +1 @@
1
- import{d as h}from"../packem_shared/command-CAXl2A1S.mjs";import{i as p}from"../packem_shared/docker-DpVxvYpL.mjs";import{EXIT_CODE as m}from"../packem_shared/EXIT_CODE-D_XCixv8.mjs";import{defaultSpawner as S}from"../packem_shared/createRecordingSpawner-Ch7zuQQE.mjs";import{execArgsFor as w,detectPackageManager as v}from"@lunora/config";const u=new Set(["build","delete","images","info","list","push"]),b=new Set(["build","push"]),f=new Set(["images list","info","list"]),E=async e=>{const[r,...t]=e.argument;if(r===void 0||!u.has(r)){const n=`lunora containers requires a subcommand: ${[...u].toSorted((i,d)=>i.localeCompare(d)).join(" | ")}. Example: lunora containers build ./containers/app --tag app:v1 --push`;return e.logger.error(n),{code:m.USAGE,error:n}}const o=e.format==="json",s=r==="images"?`images ${t[0]??""}`.trim():r;if(o&&!f.has(s)){const n=`containers ${s}: --format json is only available for the read subcommands (${[...f].toSorted((i,d)=>i.localeCompare(d)).join(" | ")}) — wrangler has no JSON rendering for the rest.`;return e.logger.error(n),{code:m.USAGE,error:n}}if(b.has(r)&&!(e.dockerAvailable??p)()){const n=`containers ${r} needs a running Docker-compatible engine (it builds/pushes images locally). Start Docker or Colima and retry. Note: container images must target linux/amd64.`;return e.logger.error(n),{code:m.MISSING_DEPENDENCY,error:n}}const a=["containers",r,...t];o&&a.push("--json"),e.tag!==void 0&&a.push("--tag",e.tag),e.push===!0&&a.push("--push"),e.env!==void 0&&a.push("--env",e.env);const l=e.cwd??process.cwd(),g=w(v(l),"wrangler",a),c={args:g.args,command:g.command,cwd:l};return e.logger.info(`running ${c.command} ${c.args.join(" ")}`),{code:(await(e.spawner??S)(c)).code,delegated:o,descriptor:c}},k=h(async({argument:e,cwd:r,format:t,logger:o,options:s})=>{const a=await E({argument:e,cwd:r,env:s.env,format:t,logger:o,push:s.push===!0,tag:s.tag});return{code:a.code,delegated:a.delegated,error:a.error}});export{k as execute,E as runContainersCommand};
1
+ import{d as s}from"../packem_shared/command-CAXl2A1S.mjs";import{o as c}from"../packem_shared/open-url-EnKy--w-.mjs";const n="https://lunora.sh/docs",l=r=>{let e=0,t=r.length;for(;e<t&&r[e]==="/";)e+=1;for(;t>e&&r[t-1]==="/";)t-=1;return r.slice(e,t)},i=r=>{if(!r||r.length===0)return n;const e=l(r);return e.length===0?n:`${n}/${e}`},a=async r=>{const e=i(r.section);r.logger.info(`opening ${e}`);try{await c(e,{opener:r.opener})}catch(t){const o=t instanceof Error?t.message:String(t);return r.logger.error(`docs: failed to open URL: ${o}`),{code:1,url:e}}return{code:0,url:e}},m=s(({argument:r,logger:e})=>a({logger:e,section:r[0]}));export{m as execute,a as runDocsCommand};
@@ -1 +1,3 @@
1
- import{d as i}from"../packem_shared/command-CAXl2A1S.mjs";import{EXIT_CODE as c}from"../packem_shared/EXIT_CODE-D_XCixv8.mjs";import{defaultSpawner as l}from"../packem_shared/createRecordingSpawner-Ch7zuQQE.mjs";import{execArgsFor as u,detectPackageManager as g}from"@lunora/config";const a=(e,r)=>(r!==void 0&&e.push("--env",r),e),f=e=>{const r=a(["deployments","list"],e.env);return e.format==="json"&&r.push("--json"),r},v=e=>{switch(e.subcommand){case"inspect":return e.versionId===void 0?{error:"deployments inspect requires a version id. Usage: lunora deployments inspect <version-id>"}:{args:a(["versions","view",e.versionId],e.env)};case"list":return{args:f(e)};case"promote":{if(e.versionId===void 0)return{error:"deployments promote requires a version id. Usage: lunora deployments promote <version-id> --yes"};if(!e.yes)return{error:"deployments promote shifts 100% of live traffic. Re-run with --yes to confirm."};const r=a(["versions","deploy",`${e.versionId}@100%`,"--yes"],e.env);return e.message!==void 0&&r.push("--message",e.message),{args:r}}case"rollback":{if(!e.yes)return{error:"deployments rollback changes the live version. Re-run with --yes to confirm."};const r=a(["rollback"],e.env);return e.versionId!==void 0&&r.push(e.versionId),r.push("--yes"),e.message!==void 0&&r.push("--message",e.message),{args:r}}default:return{error:`deployments: unknown subcommand "${e.subcommand}"`}}},y=async e=>{if(e.format==="json"&&e.subcommand!=="list"){const m=`deployments ${e.subcommand}: --format json is only available for \`deployments list\` — wrangler has no JSON rendering for the others.`;return e.logger.error(m),{code:c.USAGE,descriptor:void 0,error:m}}const{args:r,error:t}=v(e);if(t!==void 0||r===void 0)return e.logger.error(t??"deployments: nothing to run"),{code:c.USAGE,descriptor:void 0,error:t};const{logger:d}=e,n=e.cwd??process.cwd(),o=u(g(n),"wrangler",r),s={args:o.args,command:o.command,cwd:n};return d.info(`${s.command} ${s.args.join(" ")}`),{code:(await(e.spawner??l)(s)).code,delegated:e.format==="json",descriptor:s}},p=e=>e==="list"||e==="inspect"||e==="rollback"||e==="promote",A=i(({argument:e,cwd:r,format:t,logger:d,options:n})=>{const o=e[0];if(!p(o)){const s=`deployments: unknown subcommand "${o??""}" — expected list | inspect | rollback | promote`;return d.error(s),{code:c.USAGE,error:s}}return y({cwd:r,env:n.env,format:t,logger:d,message:n.message,subcommand:o,versionId:e[1],yes:n.yes===!0})});export{A as execute,y as runDeploymentsCommand};
1
+ import{existsSync as E,readFileSync as P}from"node:fs";import{join as D}from"node:path";import{DEV_VARS_FILE as m,DEV_VARS_KEY_PATTERN as b,writeDevVariablesFileAtomically as w,removeDevVariableLine as K,upsertDevVariableLine as _,isPlaceholderValue as S,detectPackageManager as j,resolveDeployDriver as z,resolveProjectTarget as M,toolchainExecArgs as T,generateSecretValue as C,DEV_VARS_EXAMPLE_FILE as g,parseDevVariableEntries as G,secretSourcesFromBindings as O,inferLunoraBindings as Y,resolveSchemaDirectory as F,requiredSecrets as q,isMintableSecretKey as U}from"@lunora/config";import{d as Z}from"../packem_shared/command-CAXl2A1S.mjs";import{EXIT_CODE as d}from"../packem_shared/EXIT_CODE-D_XCixv8.mjs";import{defaultSpawner as B}from"../packem_shared/createRecordingSpawner-Ch7zuQQE.mjs";import{l as I}from"../packem_shared/wrangler-secrets-3chIVv3H.mjs";const X=/[\r\n]/u,H=/["\\]/u,L=e=>new Map(G(e).map(o=>[o.key,o])),h=e=>E(e)?P(e,"utf8"):"",R=e=>e.length<=4?"****":`${e.slice(0,4)}${"*".repeat(Math.min(8,e.length-4))}`,p=e=>L(h(e)),$=e=>e.env??(e.prod===!0?"production":void 0),W=e=>{const o=p(e.devVariablesPath),t={file:m,keys:[...o.keys()],subcommand:"list"};if(o.size===0)return e.logger.info(`${m}: (empty)`),{code:0,data:t,descriptors:[]};for(const r of o.values())e.logger.info(`${r.key}=${R(r.value)}`);return{code:0,data:t,descriptors:[]}},J=e=>{const{devVariablesPath:o,logger:t,options:r}=e;if(!r.key)return t.error("env get requires a key. Usage: lunora env get <KEY>"),{code:d.USAGE,descriptors:[]};const s=p(o).get(r.key);return s?(r.format!=="json"&&process.stdout.write(`${s.value}
2
+ `),{code:0,data:{key:r.key,subcommand:"get",value:s.value},descriptors:[]}):(t.error(`env: ${r.key} is not set in ${m}`),{code:d.NOT_FOUND,descriptors:[]})},Q=e=>{const{devVariablesPath:o,logger:t,options:r}=e;if(!r.key)return t.error("env set requires a key. Usage: lunora env set <KEY> <VALUE>"),{code:d.USAGE,descriptors:[]};if(!b.test(r.key))return t.error(`env: invalid key "${r.key}" — must match [A-Za-z_][A-Za-z0-9_]*`),{code:d.USAGE,descriptors:[]};if(r.value===void 0)return t.error("env set requires a value. Usage: lunora env set <KEY> <VALUE>"),{code:d.USAGE,descriptors:[]};if(X.test(r.value))return t.error(`env: value for "${r.key}" contains a newline, which .dev.vars cannot represent`),{code:d.USAGE,descriptors:[]};if(H.test(r.value))return t.error(`env: value for "${r.key}" contains a double-quote or backslash, which .dev.vars cannot round-trip`),{code:d.USAGE,descriptors:[]};const s=h(o);return w(o,_(s,r.key,r.value)),t.success(`env: set ${r.key} (${R(r.value)}) in ${m}`),{code:0,data:{key:r.key,subcommand:"set"},descriptors:[]}},x=e=>{const{devVariablesPath:o,logger:t,options:r}=e;if(!r.key)return t.error("env unset requires a key. Usage: lunora env unset <KEY>"),{code:d.USAGE,descriptors:[]};if(!b.test(r.key))return t.error(`env: invalid key "${r.key}" — must match [A-Za-z_][A-Za-z0-9_]*`),{code:d.USAGE,descriptors:[]};const s=h(o);return L(s).has(r.key)?(w(o,K(s,r.key)),t.success(`env: unset ${r.key} in ${m}`),{code:0,data:{key:r.key,removed:!0,subcommand:"unset"},descriptors:[]}):(t.warn(`env: ${r.key} was not set in ${m}`),{code:0,data:{key:r.key,removed:!1,subcommand:"unset"},descriptors:[]})},ee=async e=>{const{devVariablesPath:o,logger:t,options:r}=e;if(!r.yes)return t.error("env push uploads secrets to Cloudflare. Re-run with --yes to confirm."),{code:d.USAGE,descriptors:[]};const s=p(o);if(s.size===0)return t.warn(`${m}: nothing to push (empty)`),{code:0,data:{pushed:[],subcommand:"push",target:$(r)},descriptors:[]};const n=[...s.values()].filter(a=>S(a.value)).map(a=>a.key);if(n.length>0)return t.error(`env push: refusing to upload placeholder value(s) for ${n.join(", ")} — run \`lunora env doctor\` to review, and \`lunora env generate --set\` (or \`lunora env set <KEY> <VALUE>\`) to fill them, then re-run.`),{code:d.USAGE,descriptors:[]};const c=r.spawner??B,u=r.cwd??process.cwd(),l=j(u),i=[],v=$(r),f=z(M(u)),y=f.toolchain?.secretPut;if(y===void 0)return t.error(`deploy target "${f.id}" has no secret store; cannot push secrets`),{code:d.USAGE,descriptors:[]};for(const a of s.values()){const N=y({environment:v,key:a.key,temporary:r.temporary}),A=T(l,N),V={args:A.args,command:A.command,cwd:u,input:a.value};i.push(V),t.info(`pushing ${a.key} -> wrangler secret${v===void 0?"":` (${v})`}`);const k=await c(V);if(k.code!==0)return t.error(`env push: failed at ${a.key} (exit ${String(k.code)})`),{code:k.code,descriptors:i}}return t.success(`env: pushed ${String(s.size)} secret(s)`),{code:0,data:{pushed:[...s.keys()],subcommand:"push",target:v},descriptors:i}},re=e=>(e.options.secretLister??I)({cwd:e.cwd,env:$(e.options),temporary:e.options.temporary}),te=async e=>{const{devVariablesPath:o,logger:t}=e,r=await re(e);if(!r.ok)return t.error(`env diff: ${r.error??"failed to list remote secrets"}`),{code:1,descriptors:[]};const s=new Set(p(o).keys()),n=new Set(r.names),c=[...s].filter(i=>!n.has(i)).toSorted((i,v)=>i.localeCompare(v)),u=r.names.filter(i=>!s.has(i)),l=[...s].filter(i=>n.has(i)).toSorted((i,v)=>i.localeCompare(v));for(const i of c)t.info(`local only (run \`lunora env push\`): ${i}`);for(const i of u)t.info(`remote only (in Cloudflare, not ${m}): ${i}`);return t.info(`in both: ${String(l.length)} secret(s)`),c.length===0&&u.length===0&&t.success("env diff: local and remote secret names match"),{code:0,data:{both:l,localOnly:c,remoteOnly:u,subcommand:"diff"},descriptors:[]}},se=e=>{const{cwd:o,devVariablesPath:t,logger:r}=e,s=D(o,g);if(!E(s))return r.info(`env doctor: no ${g} to check against — nothing to validate.`),{code:0,data:{extra:[],missing:[],ok:!0,placeholders:[],subcommand:"doctor"},descriptors:[]};const n=G(P(s,"utf8")).map(a=>a.key),c=p(t);if(!E(t))return r.error(`env doctor: ${m} is missing. Run \`lunora dev\` to scaffold it, or \`lunora env set <KEY> <VALUE>\`.`),r.info(`expected (from ${g}): ${n.join(", ")}`),{code:d.NOT_FOUND,descriptors:[]};const u=n.filter(a=>!c.has(a)),l=[...c.values()].filter(a=>S(a.value)).map(a=>a.key),i=new Set(n),v=[...c.keys()].filter(a=>!i.has(a));for(const a of u)r.error(`missing: ${a} is in ${g} but not ${m}`);for(const a of l)r.error(`unset: ${a} still has a placeholder value`);for(const a of v)r.info(`extra: ${a} is set locally but not listed in ${g}`);const f=u.length===0&&l.length===0,y={extra:v,missing:u,ok:f,placeholders:l,subcommand:"doctor"};return f?(r.success(`env doctor: ${m} looks good (${String(c.size)} var(s)).`),{code:0,data:y,descriptors:[]}):{code:1,data:y,descriptors:[]}},oe=async e=>{let o=[];try{o=O(await Y({projectRoot:e.cwd,schemaDir:F(e.cwd)}))}catch{}const t=q(o).map(s=>s.key).filter(s=>U(s)),r=[...p(e.devVariablesPath).keys()].filter(s=>U(s));return[...new Set([...t,...r])]},ne=(e,o,t)=>{const r=p(e),s=n=>{const c=r.get(n);return c!==void 0&&c.value!==""&&!S(c.value)};return{live:o.filter(n=>s(n.key)).map(n=>n.key),writable:t?o:o.filter(n=>!s(n.key))}},ae=(e,o)=>{const{devVariablesPath:t,logger:r,options:s}=e,{live:n,writable:c}=ne(t,o,s.yes===!0);if(c.length===0)return r.error(`env generate --set: ${n.join(", ")} already hold(s) a live secret and rotating it is irreversible (outstanding signed URLs and bearers stop verifying). Re-run with --yes to rotate anyway.`),{code:d.USAGE,descriptors:[]};n.length>0&&r.warn(`env generate --set: left ${n.join(", ")} untouched (already set) — re-run with --yes to rotate them too`);let u=h(t);for(const l of c)u=_(u,l.key,l.value);return w(t,u),r.success(`env: generated ${String(c.length)} secret(s) into ${m}: ${c.map(l=>l.key).join(", ")}`),{code:0,data:{subcommand:"generate",written:c.map(l=>l.key)},descriptors:[]}},ce=async e=>{const{logger:o,options:t}=e;let r;if(t.key===void 0){if(r=await oe(e),r.length===0)return o.info("env generate: no locally-generatable secrets for this project. Name one explicitly: lunora env generate <KEY>"),{code:0,data:{secrets:[],subcommand:"generate"},descriptors:[]}}else{if(!b.test(t.key))return o.error(`env: invalid key "${t.key}" — must match [A-Za-z_][A-Za-z0-9_]*`),{code:d.USAGE,descriptors:[]};r=[t.key]}const s=r.map(n=>({key:n,value:C()}));if(t.set===!0)return ae(e,s);if(t.format!=="json")for(const n of s)process.stdout.write(`${n.key}=${n.value}
3
+ `);return{code:0,data:{secrets:s,subcommand:"generate"},descriptors:[]}},ie=async e=>{const{options:o}=e;switch(o.subcommand){case"diff":return te(e);case"doctor":return se(e);case"generate":return ce(e);case"get":return J(e);case"list":return W(e);case"push":return ee(e);case"set":return Q(e);case"unset":return x(e);default:return e.logger.error(`env: unknown subcommand "${o.subcommand}"`),{code:d.USAGE,descriptors:[]}}},de=async e=>{const o=e.cwd??process.cwd(),t={cwd:o,devVariablesPath:D(o,m),logger:e.logger,options:e};return ie(t)},ue=new Set(["diff","doctor","generate","get","list","push","set","unset"]),le=e=>typeof e=="string"&&ue.has(e),ke=Z(({argument:e,cwd:o,format:t,logger:r,options:s})=>{const n=e[0];if(!le(n)){const c=`env: unknown subcommand "${n??""}" — expected list | get | set | unset | push | diff | doctor | generate`;return r.error(c),{code:d.USAGE,error:c}}return de({cwd:o,env:s.env,format:t,key:e[1],logger:r,prod:s.prod===!0,set:s.set===!0,subcommand:n,temporary:s.temporary===!0,value:e[2],yes:s.yes===!0})});export{ke as execute,de as runEnvCommand};
@@ -1 +1 @@
1
- import{d as s}from"../packem_shared/command-CAXl2A1S.mjs";import{o as c}from"../packem_shared/open-url-EnKy--w-.mjs";const n="https://lunora.sh/docs",l=r=>{let e=0,t=r.length;for(;e<t&&r[e]==="/";)e+=1;for(;t>e&&r[t-1]==="/";)t-=1;return r.slice(e,t)},i=r=>{if(!r||r.length===0)return n;const e=l(r);return e.length===0?n:`${n}/${e}`},a=async r=>{const e=i(r.section);r.logger.info(`opening ${e}`);try{await c(e,{opener:r.opener})}catch(t){const o=t instanceof Error?t.message:String(t);return r.logger.error(`docs: failed to open URL: ${o}`),{code:1,url:e}}return{code:0,url:e}},m=s(({argument:r,logger:e})=>a({logger:e,section:r[0]}));export{m as execute,a as runDocsCommand};
1
+ import{d}from"../packem_shared/command-CAXl2A1S.mjs";import{a as l}from"../packem_shared/resolve-target-C_ZloTvd.mjs";import{runExportCommand as m}from"../packem_shared/runExportCommand-slAq5BCF.mjs";const k=d(({argument:o,cwd:e,format:t,logger:u,options:r})=>m({cwd:e,format:t,logger:u,out:o[0]??r.out,prod:r.prod===!0,tables:r.tables,token:r.token,url:l({cwd:e,prod:r.prod===!0,url:r.url})}));export{k as execute};
@@ -1,3 +1 @@
1
- import{existsSync as E,readFileSync as P}from"node:fs";import{join as D}from"node:path";import{DEV_VARS_FILE as m,DEV_VARS_KEY_PATTERN as b,writeDevVariablesFileAtomically as w,removeDevVariableLine as K,upsertDevVariableLine as _,isPlaceholderValue as S,detectPackageManager as j,resolveDeployDriver as z,resolveProjectTarget as M,toolchainExecArgs as T,generateSecretValue as C,DEV_VARS_EXAMPLE_FILE as g,parseDevVariableEntries as G,secretSourcesFromBindings as O,inferLunoraBindings as Y,resolveSchemaDirectory as F,requiredSecrets as q,isMintableSecretKey as U}from"@lunora/config";import{d as Z}from"../packem_shared/command-CAXl2A1S.mjs";import{EXIT_CODE as d}from"../packem_shared/EXIT_CODE-D_XCixv8.mjs";import{defaultSpawner as B}from"../packem_shared/createRecordingSpawner-Ch7zuQQE.mjs";import{l as I}from"../packem_shared/wrangler-secrets-3chIVv3H.mjs";const X=/[\r\n]/u,H=/["\\]/u,L=e=>new Map(G(e).map(o=>[o.key,o])),h=e=>E(e)?P(e,"utf8"):"",R=e=>e.length<=4?"****":`${e.slice(0,4)}${"*".repeat(Math.min(8,e.length-4))}`,p=e=>L(h(e)),$=e=>e.env??(e.prod===!0?"production":void 0),W=e=>{const o=p(e.devVariablesPath),t={file:m,keys:[...o.keys()],subcommand:"list"};if(o.size===0)return e.logger.info(`${m}: (empty)`),{code:0,data:t,descriptors:[]};for(const r of o.values())e.logger.info(`${r.key}=${R(r.value)}`);return{code:0,data:t,descriptors:[]}},J=e=>{const{devVariablesPath:o,logger:t,options:r}=e;if(!r.key)return t.error("env get requires a key. Usage: lunora env get <KEY>"),{code:d.USAGE,descriptors:[]};const s=p(o).get(r.key);return s?(r.format!=="json"&&process.stdout.write(`${s.value}
2
- `),{code:0,data:{key:r.key,subcommand:"get",value:s.value},descriptors:[]}):(t.error(`env: ${r.key} is not set in ${m}`),{code:d.NOT_FOUND,descriptors:[]})},Q=e=>{const{devVariablesPath:o,logger:t,options:r}=e;if(!r.key)return t.error("env set requires a key. Usage: lunora env set <KEY> <VALUE>"),{code:d.USAGE,descriptors:[]};if(!b.test(r.key))return t.error(`env: invalid key "${r.key}" — must match [A-Za-z_][A-Za-z0-9_]*`),{code:d.USAGE,descriptors:[]};if(r.value===void 0)return t.error("env set requires a value. Usage: lunora env set <KEY> <VALUE>"),{code:d.USAGE,descriptors:[]};if(X.test(r.value))return t.error(`env: value for "${r.key}" contains a newline, which .dev.vars cannot represent`),{code:d.USAGE,descriptors:[]};if(H.test(r.value))return t.error(`env: value for "${r.key}" contains a double-quote or backslash, which .dev.vars cannot round-trip`),{code:d.USAGE,descriptors:[]};const s=h(o);return w(o,_(s,r.key,r.value)),t.success(`env: set ${r.key} (${R(r.value)}) in ${m}`),{code:0,data:{key:r.key,subcommand:"set"},descriptors:[]}},x=e=>{const{devVariablesPath:o,logger:t,options:r}=e;if(!r.key)return t.error("env unset requires a key. Usage: lunora env unset <KEY>"),{code:d.USAGE,descriptors:[]};if(!b.test(r.key))return t.error(`env: invalid key "${r.key}" — must match [A-Za-z_][A-Za-z0-9_]*`),{code:d.USAGE,descriptors:[]};const s=h(o);return L(s).has(r.key)?(w(o,K(s,r.key)),t.success(`env: unset ${r.key} in ${m}`),{code:0,data:{key:r.key,removed:!0,subcommand:"unset"},descriptors:[]}):(t.warn(`env: ${r.key} was not set in ${m}`),{code:0,data:{key:r.key,removed:!1,subcommand:"unset"},descriptors:[]})},ee=async e=>{const{devVariablesPath:o,logger:t,options:r}=e;if(!r.yes)return t.error("env push uploads secrets to Cloudflare. Re-run with --yes to confirm."),{code:d.USAGE,descriptors:[]};const s=p(o);if(s.size===0)return t.warn(`${m}: nothing to push (empty)`),{code:0,data:{pushed:[],subcommand:"push",target:$(r)},descriptors:[]};const n=[...s.values()].filter(a=>S(a.value)).map(a=>a.key);if(n.length>0)return t.error(`env push: refusing to upload placeholder value(s) for ${n.join(", ")} — run \`lunora env doctor\` to review, and \`lunora env generate --set\` (or \`lunora env set <KEY> <VALUE>\`) to fill them, then re-run.`),{code:d.USAGE,descriptors:[]};const c=r.spawner??B,u=r.cwd??process.cwd(),l=j(u),i=[],v=$(r),f=z(M(u)),y=f.toolchain?.secretPut;if(y===void 0)return t.error(`deploy target "${f.id}" has no secret store; cannot push secrets`),{code:d.USAGE,descriptors:[]};for(const a of s.values()){const N=y({environment:v,key:a.key,temporary:r.temporary}),A=T(l,N),V={args:A.args,command:A.command,cwd:u,input:a.value};i.push(V),t.info(`pushing ${a.key} -> wrangler secret${v===void 0?"":` (${v})`}`);const k=await c(V);if(k.code!==0)return t.error(`env push: failed at ${a.key} (exit ${String(k.code)})`),{code:k.code,descriptors:i}}return t.success(`env: pushed ${String(s.size)} secret(s)`),{code:0,data:{pushed:[...s.keys()],subcommand:"push",target:v},descriptors:i}},re=e=>(e.options.secretLister??I)({cwd:e.cwd,env:$(e.options),temporary:e.options.temporary}),te=async e=>{const{devVariablesPath:o,logger:t}=e,r=await re(e);if(!r.ok)return t.error(`env diff: ${r.error??"failed to list remote secrets"}`),{code:1,descriptors:[]};const s=new Set(p(o).keys()),n=new Set(r.names),c=[...s].filter(i=>!n.has(i)).toSorted((i,v)=>i.localeCompare(v)),u=r.names.filter(i=>!s.has(i)),l=[...s].filter(i=>n.has(i)).toSorted((i,v)=>i.localeCompare(v));for(const i of c)t.info(`local only (run \`lunora env push\`): ${i}`);for(const i of u)t.info(`remote only (in Cloudflare, not ${m}): ${i}`);return t.info(`in both: ${String(l.length)} secret(s)`),c.length===0&&u.length===0&&t.success("env diff: local and remote secret names match"),{code:0,data:{both:l,localOnly:c,remoteOnly:u,subcommand:"diff"},descriptors:[]}},se=e=>{const{cwd:o,devVariablesPath:t,logger:r}=e,s=D(o,g);if(!E(s))return r.info(`env doctor: no ${g} to check against — nothing to validate.`),{code:0,data:{extra:[],missing:[],ok:!0,placeholders:[],subcommand:"doctor"},descriptors:[]};const n=G(P(s,"utf8")).map(a=>a.key),c=p(t);if(!E(t))return r.error(`env doctor: ${m} is missing. Run \`lunora dev\` to scaffold it, or \`lunora env set <KEY> <VALUE>\`.`),r.info(`expected (from ${g}): ${n.join(", ")}`),{code:d.NOT_FOUND,descriptors:[]};const u=n.filter(a=>!c.has(a)),l=[...c.values()].filter(a=>S(a.value)).map(a=>a.key),i=new Set(n),v=[...c.keys()].filter(a=>!i.has(a));for(const a of u)r.error(`missing: ${a} is in ${g} but not ${m}`);for(const a of l)r.error(`unset: ${a} still has a placeholder value`);for(const a of v)r.info(`extra: ${a} is set locally but not listed in ${g}`);const f=u.length===0&&l.length===0,y={extra:v,missing:u,ok:f,placeholders:l,subcommand:"doctor"};return f?(r.success(`env doctor: ${m} looks good (${String(c.size)} var(s)).`),{code:0,data:y,descriptors:[]}):{code:1,data:y,descriptors:[]}},oe=async e=>{let o=[];try{o=O(await Y({projectRoot:e.cwd,schemaDir:F(e.cwd)}))}catch{}const t=q(o).map(s=>s.key).filter(s=>U(s)),r=[...p(e.devVariablesPath).keys()].filter(s=>U(s));return[...new Set([...t,...r])]},ne=(e,o,t)=>{const r=p(e),s=n=>{const c=r.get(n);return c!==void 0&&c.value!==""&&!S(c.value)};return{live:o.filter(n=>s(n.key)).map(n=>n.key),writable:t?o:o.filter(n=>!s(n.key))}},ae=(e,o)=>{const{devVariablesPath:t,logger:r,options:s}=e,{live:n,writable:c}=ne(t,o,s.yes===!0);if(c.length===0)return r.error(`env generate --set: ${n.join(", ")} already hold(s) a live secret and rotating it is irreversible (outstanding signed URLs and bearers stop verifying). Re-run with --yes to rotate anyway.`),{code:d.USAGE,descriptors:[]};n.length>0&&r.warn(`env generate --set: left ${n.join(", ")} untouched (already set) — re-run with --yes to rotate them too`);let u=h(t);for(const l of c)u=_(u,l.key,l.value);return w(t,u),r.success(`env: generated ${String(c.length)} secret(s) into ${m}: ${c.map(l=>l.key).join(", ")}`),{code:0,data:{subcommand:"generate",written:c.map(l=>l.key)},descriptors:[]}},ce=async e=>{const{logger:o,options:t}=e;let r;if(t.key===void 0){if(r=await oe(e),r.length===0)return o.info("env generate: no locally-generatable secrets for this project. Name one explicitly: lunora env generate <KEY>"),{code:0,data:{secrets:[],subcommand:"generate"},descriptors:[]}}else{if(!b.test(t.key))return o.error(`env: invalid key "${t.key}" — must match [A-Za-z_][A-Za-z0-9_]*`),{code:d.USAGE,descriptors:[]};r=[t.key]}const s=r.map(n=>({key:n,value:C()}));if(t.set===!0)return ae(e,s);if(t.format!=="json")for(const n of s)process.stdout.write(`${n.key}=${n.value}
3
- `);return{code:0,data:{secrets:s,subcommand:"generate"},descriptors:[]}},ie=async e=>{const{options:o}=e;switch(o.subcommand){case"diff":return te(e);case"doctor":return se(e);case"generate":return ce(e);case"get":return J(e);case"list":return W(e);case"push":return ee(e);case"set":return Q(e);case"unset":return x(e);default:return e.logger.error(`env: unknown subcommand "${o.subcommand}"`),{code:d.USAGE,descriptors:[]}}},de=async e=>{const o=e.cwd??process.cwd(),t={cwd:o,devVariablesPath:D(o,m),logger:e.logger,options:e};return ie(t)},ue=new Set(["diff","doctor","generate","get","list","push","set","unset"]),le=e=>typeof e=="string"&&ue.has(e),ke=Z(({argument:e,cwd:o,format:t,logger:r,options:s})=>{const n=e[0];if(!le(n)){const c=`env: unknown subcommand "${n??""}" — expected list | get | set | unset | push | diff | doctor | generate`;return r.error(c),{code:d.USAGE,error:c}}return de({cwd:o,env:s.env,format:t,key:e[1],logger:r,prod:s.prod===!0,set:s.set===!0,subcommand:n,temporary:s.temporary===!0,value:e[2],yes:s.yes===!0})});export{ke as execute,de as runEnvCommand};
1
+ import{d}from"../packem_shared/command-CAXl2A1S.mjs";import{EXIT_CODE as m}from"../packem_shared/EXIT_CODE-D_XCixv8.mjs";import{a as n}from"../packem_shared/resolve-target-C_ZloTvd.mjs";import{I as u,r as i}from"../packem_shared/import-BRM1hs7j.mjs";const b=d(({argument:f,cwd:a,format:c,logger:t,options:r})=>{const o=f[0];if(!o){const e="import requires a path. Usage: lunora import <file.ndjson | convex-export-dir> [--table <name>]";return t.error(e),{code:m.USAGE,error:e}}if(r.from!==void 0&&!u.includes(r.from)){const e=`--from ${r.from} is not a known source. Expected one of: ${u.join(", ")}.`;return t.error(e),{code:m.USAGE,error:e}}return i({batchSize:r.batchSize,cwd:a,file:o,format:c,from:r.from,logger:t,prod:r.prod===!0,scan:r.scan===!0,storageDir:r.storageDir,table:r.table,token:r.token,url:n({cwd:a,prod:r.prod===!0,url:r.url}),verify:r.verify===!0,withStorage:r.withStorage===!0,yes:r.yes===!0})});export{b as execute};
@@ -1 +1 @@
1
- import{d}from"../packem_shared/command-CAXl2A1S.mjs";import{a as l}from"../packem_shared/resolve-target-C_ZloTvd.mjs";import{runExportCommand as m}from"../packem_shared/runExportCommand-slAq5BCF.mjs";const k=d(({argument:o,cwd:e,format:t,logger:u,options:r})=>m({cwd:e,format:t,logger:u,out:o[0]??r.out,prod:r.prod===!0,tables:r.tables,token:r.token,url:l({cwd:e,prod:r.prod===!0,url:r.url})}));export{k as execute};
1
+ import{readFileSync as g,existsSync as b}from"node:fs";import{join as y}from"node:path";import{discoverSchema as h}from"@lunora/codegen";import{readLinkedProject as v,readProjectManifest as $}from"@lunora/config";import{findWranglerFile as p}from"@lunora/config/cloudflare";import{parse as k}from"jsonc-parser";import{Project as w}from"ts-morph";import{w as j,d as m}from"../packem_shared/binding-manifest-file-CQ1eQYy1.mjs";import{d as S}from"../packem_shared/command-CAXl2A1S.mjs";import{EXIT_CODE as f}from"../packem_shared/EXIT_CODE-D_XCixv8.mjs";const d=(n,e)=>{if(n===null||typeof n!="object")return;const i=n[e];return typeof i=="string"&&i.length>0?i:void 0},x=(n,e)=>{if(n===null||typeof n!="object")return[];const i=n[e];return Array.isArray(i)?i:[]},E=(n,e)=>{const{manifest:i}=m(e);return{bindings:(i?.bindings??[]).map(r=>`${r.type}:${r.binding}`),compatibilityDate:d(n,"compatibility_date"),compatibilityFlags:x(n,"compatibility_flags").filter(r=>typeof r=="string"),main:d(n,"main"),name:d(n,"name")}},F=n=>({tables:n.tables.map(e=>{let i="root";return e.shardMode==="global"?i="global":typeof e.shardMode=="object"&&(i=`shardBy(${e.shardMode.field})`),{indexes:e.indexes.length,name:e.name,shard:i}}),vectorIndexes:n.vectorIndexes.length}),P=n=>{const e=$(n);if(e===void 0)return[];const i=["dependencies","devDependencies","peerDependencies","optionalDependencies"],r=new Map;for(const s of i){const a=e[s];if(!(a===null||typeof a!="object"))for(const[t,o]of Object.entries(a))t.startsWith("@lunora/")&&typeof o=="string"&&!r.has(t)&&r.set(t,o)}return[...r.entries()].toSorted(([s],[a])=>s.localeCompare(a)).map(([s,a])=>({name:s,version:a}))},M=n=>{const e=P(n),i=p(n);let r;if(i)try{r=E(k(g(i,"utf8")),n)}catch{r=void 0}const s=y(n,"lunora","schema.ts");let a,t;if(b(s))try{const o=new w({skipAddingFilesFromTsConfig:!0,useInMemoryFileSystem:!1});a=F(h(o,s))}catch(o){t=o instanceof Error?o.message:String(o)}return{link:v(n),lunoraPackages:e,projectRoot:n,schema:a,schemaError:t,wrangler:r,wranglerPath:i}},I=(n,e)=>{if(e.info(`project: ${n.projectRoot}`),e.info(""),e.info("@lunora/* packages:"),n.lunoraPackages.length===0)e.info(" (none found in package.json)");else for(const i of n.lunoraPackages)e.info(` ${i.name}@${i.version}`);if(e.info(""),n.wrangler?(e.info(`wrangler: ${n.wranglerPath??""}`),e.info(` name: ${n.wrangler.name??"<unset>"}`),e.info(` main: ${n.wrangler.main??"<unset>"}`),e.info(` compatibility_date: ${n.wrangler.compatibilityDate??"<unset>"}`),e.info(` compatibility_flags: ${n.wrangler.compatibilityFlags.join(", ")||"<none>"}`),e.info(` bindings: ${n.wrangler.bindings.join(", ")||"<none>"}`)):e.info("wrangler: (not found)"),e.info(""),n.link?(e.info(`link: ${n.link.workerName??"(unnamed)"} -> ${n.link.workerUrl??"<no url>"}`),n.link.env!==void 0&&e.info(` env: ${n.link.env}`)):e.info("link: (not linked — run `lunora link --url <https://your-worker>`)"),e.info(""),n.schemaError!==void 0)e.warn(`schema: parse error — ${n.schemaError}`);else if(n.schema){e.info(`schema: ${String(n.schema.tables.length)} table(s), ${String(n.schema.vectorIndexes)} vector index(es)`);for(const i of n.schema.tables)e.info(` ${i.name} [${i.shard}, ${String(i.indexes)} index(es)]`)}else e.info("schema: (no lunora/schema.ts)")},A=n=>{const{cwd:e,json:i,logger:r,out:s}=n;if(s!==void 0){const{error:o}=j({destination:s,logger:r,projectRoot:e});return o!==void 0?(r.error(o),{code:f.USAGE,error:o}):{code:0}}const{error:a,manifest:t}=m(e);if(t===void 0){const o=a??"could not derive the binding manifest";return r.error(o),{code:f.USAGE,error:o}}if(i)return{code:0,data:t};if(t.bindings.length===0)r.info("No bindings declared.");else{const o=Math.max(...t.bindings.map(c=>c.type.length));r.info(`${String(t.bindings.length)} binding(s):`);for(const c of t.bindings){const l=[c.resource,c.className,c.resourceId].filter(u=>u!==void 0).join(" ");r.info(` ${c.type.padEnd(o)} ${c.binding}${l===""?"":` ${l}`}`)}}return t.crons.length>0&&r.info(`${String(t.crons.length)} cron trigger(s): ${t.crons.join(", ")}`),t.vars.length>0&&r.info(`${String(t.vars.length)} var(s): ${t.vars.join(", ")}`),t.unknown.length>0&&r.warn(`not modelled by the manifest: ${t.unknown.join(", ")} — anything they bind must be provisioned by hand.`),{code:0,data:t}},D=n=>{const e=n.cwd??process.cwd(),i=n.format==="json",{logger:r}=n;if(n.bindings===!0)return A({cwd:e,json:i,logger:r,out:n.out});if(n.out!==void 0){const a="--out only applies with --bindings; the full info snapshot prints to stdout under --format json.";return r.error(a),{code:f.USAGE,error:a}}const s=M(e);return i||I(s,r),{code:0,data:s,snapshot:s}},H=S(({cwd:n,format:e,logger:i,options:r})=>D({bindings:r.bindings===!0,cwd:n,format:e,logger:i,out:r.out}));export{M as collectInfo,H as execute,D as runInfoCommand};
@@ -1 +1,2 @@
1
- import{d}from"../packem_shared/command-CAXl2A1S.mjs";import{EXIT_CODE as m}from"../packem_shared/EXIT_CODE-D_XCixv8.mjs";import{a as n}from"../packem_shared/resolve-target-C_ZloTvd.mjs";import{I as u,r as i}from"../packem_shared/import-BRM1hs7j.mjs";const b=d(({argument:f,cwd:a,format:c,logger:t,options:r})=>{const o=f[0];if(!o){const e="import requires a path. Usage: lunora import <file.ndjson | convex-export-dir> [--table <name>]";return t.error(e),{code:m.USAGE,error:e}}if(r.from!==void 0&&!u.includes(r.from)){const e=`--from ${r.from} is not a known source. Expected one of: ${u.join(", ")}.`;return t.error(e),{code:m.USAGE,error:e}}return i({batchSize:r.batchSize,cwd:a,file:o,format:c,from:r.from,logger:t,prod:r.prod===!0,scan:r.scan===!0,storageDir:r.storageDir,table:r.table,token:r.token,url:n({cwd:a,prod:r.prod===!0,url:r.url}),verify:r.verify===!0,withStorage:r.withStorage===!0,yes:r.yes===!0})});export{b as execute};
1
+ import{r as v}from"../packem_shared/admin-token-VdUnvnKW.mjs";import{r as M,a as y}from"../packem_shared/admin-url-DJB8P6Jh.mjs";import{d as x}from"../packem_shared/command-CAXl2A1S.mjs";import{EXIT_CODE as u,exitCodeForStatus as T}from"../packem_shared/EXIT_CODE-D_XCixv8.mjs";import{a as I}from"../packem_shared/resolve-target-C_ZloTvd.mjs";const O="__lunora_admin__:getFunctionStats",_=10,f=(r,o)=>({calls:r.calls,conflicts:r.conflicts??0,errors:r.errors,lastErrorMessage:r.lastErrorMessage,maxDurationMs:r.maxDurationMs,meanDurationMs:r.calls===0?0:r.totalDurationMs/r.calls,path:r.path,rate:o}),k=(r,o)=>{const t=r.filter(e=>(e.conflicts??0)>0).map(e=>f(e,e.calls===0?0:(e.conflicts??0)/e.calls)).toSorted((e,s)=>s.rate-e.rate||s.conflicts-e.conflicts).slice(0,o),n=r.filter(e=>e.errors>0).map(e=>f(e,e.calls===0?0:e.errors/e.calls)).toSorted((e,s)=>s.rate-e.rate||s.errors-e.errors).slice(0,o),a=r.map(e=>f(e,0)).toSorted((e,s)=>s.maxDurationMs-e.maxDurationMs).slice(0,o);return{errorHotspots:n,latencyOutliers:a,totalFunctions:r.length,writeContention:t}},p=r=>`${(r*100).toFixed(1)}%`,$=r=>r<1e3?`${Math.round(r).toString()}ms`:`${(r/1e3).toFixed(2)}s`,m=(r,o,t,n)=>[r,...o.length===0?[` ${t}`]:o.map(a=>` ${n(a)}`)],E=r=>{const o=t=>t.lastErrorMessage?` — ${t.lastErrorMessage}`:"";return[`Insights over ${r.totalFunctions.toString()} function${r.totalFunctions===1?"":"s"}`,"",...m("Write-conflict hot-spots (OCC contention — candidates for sharding):",r.writeContention,"none — no write conflicts observed",t=>`${t.path} ${t.conflicts.toString()}/${t.calls.toString()} calls (${p(t.rate)})`),"",...m("Error hot-spots:",r.errorHotspots,"none — no errors observed",t=>`${t.path} ${t.errors.toString()}/${t.calls.toString()} calls (${p(t.rate)})${o(t)}`),"",...m("Latency outliers (slowest single call):",r.latencyOutliers,"none — no functions have run",t=>`${t.path} max ${$(t.maxDurationMs)}, mean ${$(t.meanDurationMs)} over ${t.calls.toString()} calls`)].join(`
2
+ `)},i=(r,o,t)=>(r.error(o),{code:t,error:o}),F=r=>r===void 0||!Number.isFinite(r)||r<=0?_:Math.floor(r),A=async r=>{const{logger:o}=r;if(r.prod&&r.url===void 0)return i(o,"--prod requires an explicit --url (refusing to report from the implicit localhost worker)",u.USAGE);const t=M(r.url,o,r.cwd);if(t===void 0)return{code:u.USAGE,error:"could not resolve a usable worker URL"};const{token:n}=v({cwd:r.cwd??process.cwd(),token:r.token,url:t});if(!n)return i(o,"admin token required — pass --token, set LUNORA_ADMIN_TOKEN, or add it to .dev.vars (local targets only)",u.AUTH);const a=`${t}/_lunora/rpc`,e=y,s={args:{},functionPath:O};r.shard!==void 0&&(s.shardKey=r.shard),o.info(`POST ${a} -> insights`);const l=await e(a,{body:JSON.stringify(s),headers:{authorization:`Bearer ${n}`,"content-type":"application/json"},method:"POST"}),c=await l.text();if(!l.ok)return i(o,`insights failed: HTTP ${String(l.status)}: ${c}`,T(l.status));let d;try{d=JSON.parse(c)}catch{return i(o,`insights failed: worker returned non-JSON: ${c}`,1)}const S=d.result??d,{functions:h}=S;if(!Array.isArray(h))return i(o,"insights failed: response carried no `functions` array",1);const g=k(h,F(r.limit));return r.format!=="json"&&o.info(E(g)),{code:0,report:g}},L=x(async({cwd:r,format:o,logger:t,options:n})=>{const a=n.limit===void 0?void 0:Number.parseInt(n.limit,10),e=await A({cwd:r,fetchImpl:void 0,format:o,limit:a,logger:t,prod:n.prod,shard:n.shard,token:n.token,url:I({cwd:r,prod:n.prod===!0,url:n.url})});return{code:e.code,data:e.report,error:e.error}});export{k as buildInsightsReport,L as execute,E as formatInsightsReport,A as runInsightsCommand};
@@ -1 +1 @@
1
- import{readFileSync as g,existsSync as b}from"node:fs";import{join as y}from"node:path";import{discoverSchema as h}from"@lunora/codegen";import{readLinkedProject as v,readProjectManifest as $}from"@lunora/config";import{findWranglerFile as p}from"@lunora/config/cloudflare";import{parse as k}from"jsonc-parser";import{Project as w}from"ts-morph";import{w as j,d as m}from"../packem_shared/binding-manifest-file-CQ1eQYy1.mjs";import{d as S}from"../packem_shared/command-CAXl2A1S.mjs";import{EXIT_CODE as f}from"../packem_shared/EXIT_CODE-D_XCixv8.mjs";const d=(n,e)=>{if(n===null||typeof n!="object")return;const i=n[e];return typeof i=="string"&&i.length>0?i:void 0},x=(n,e)=>{if(n===null||typeof n!="object")return[];const i=n[e];return Array.isArray(i)?i:[]},E=(n,e)=>{const{manifest:i}=m(e);return{bindings:(i?.bindings??[]).map(r=>`${r.type}:${r.binding}`),compatibilityDate:d(n,"compatibility_date"),compatibilityFlags:x(n,"compatibility_flags").filter(r=>typeof r=="string"),main:d(n,"main"),name:d(n,"name")}},F=n=>({tables:n.tables.map(e=>{let i="root";return e.shardMode==="global"?i="global":typeof e.shardMode=="object"&&(i=`shardBy(${e.shardMode.field})`),{indexes:e.indexes.length,name:e.name,shard:i}}),vectorIndexes:n.vectorIndexes.length}),P=n=>{const e=$(n);if(e===void 0)return[];const i=["dependencies","devDependencies","peerDependencies","optionalDependencies"],r=new Map;for(const s of i){const a=e[s];if(!(a===null||typeof a!="object"))for(const[t,o]of Object.entries(a))t.startsWith("@lunora/")&&typeof o=="string"&&!r.has(t)&&r.set(t,o)}return[...r.entries()].toSorted(([s],[a])=>s.localeCompare(a)).map(([s,a])=>({name:s,version:a}))},M=n=>{const e=P(n),i=p(n);let r;if(i)try{r=E(k(g(i,"utf8")),n)}catch{r=void 0}const s=y(n,"lunora","schema.ts");let a,t;if(b(s))try{const o=new w({skipAddingFilesFromTsConfig:!0,useInMemoryFileSystem:!1});a=F(h(o,s))}catch(o){t=o instanceof Error?o.message:String(o)}return{link:v(n),lunoraPackages:e,projectRoot:n,schema:a,schemaError:t,wrangler:r,wranglerPath:i}},I=(n,e)=>{if(e.info(`project: ${n.projectRoot}`),e.info(""),e.info("@lunora/* packages:"),n.lunoraPackages.length===0)e.info(" (none found in package.json)");else for(const i of n.lunoraPackages)e.info(` ${i.name}@${i.version}`);if(e.info(""),n.wrangler?(e.info(`wrangler: ${n.wranglerPath??""}`),e.info(` name: ${n.wrangler.name??"<unset>"}`),e.info(` main: ${n.wrangler.main??"<unset>"}`),e.info(` compatibility_date: ${n.wrangler.compatibilityDate??"<unset>"}`),e.info(` compatibility_flags: ${n.wrangler.compatibilityFlags.join(", ")||"<none>"}`),e.info(` bindings: ${n.wrangler.bindings.join(", ")||"<none>"}`)):e.info("wrangler: (not found)"),e.info(""),n.link?(e.info(`link: ${n.link.workerName??"(unnamed)"} -> ${n.link.workerUrl??"<no url>"}`),n.link.env!==void 0&&e.info(` env: ${n.link.env}`)):e.info("link: (not linked — run `lunora link --url <https://your-worker>`)"),e.info(""),n.schemaError!==void 0)e.warn(`schema: parse error — ${n.schemaError}`);else if(n.schema){e.info(`schema: ${String(n.schema.tables.length)} table(s), ${String(n.schema.vectorIndexes)} vector index(es)`);for(const i of n.schema.tables)e.info(` ${i.name} [${i.shard}, ${String(i.indexes)} index(es)]`)}else e.info("schema: (no lunora/schema.ts)")},A=n=>{const{cwd:e,json:i,logger:r,out:s}=n;if(s!==void 0){const{error:o}=j({destination:s,logger:r,projectRoot:e});return o!==void 0?(r.error(o),{code:f.USAGE,error:o}):{code:0}}const{error:a,manifest:t}=m(e);if(t===void 0){const o=a??"could not derive the binding manifest";return r.error(o),{code:f.USAGE,error:o}}if(i)return{code:0,data:t};if(t.bindings.length===0)r.info("No bindings declared.");else{const o=Math.max(...t.bindings.map(c=>c.type.length));r.info(`${String(t.bindings.length)} binding(s):`);for(const c of t.bindings){const l=[c.resource,c.className,c.resourceId].filter(u=>u!==void 0).join(" ");r.info(` ${c.type.padEnd(o)} ${c.binding}${l===""?"":` ${l}`}`)}}return t.crons.length>0&&r.info(`${String(t.crons.length)} cron trigger(s): ${t.crons.join(", ")}`),t.vars.length>0&&r.info(`${String(t.vars.length)} var(s): ${t.vars.join(", ")}`),t.unknown.length>0&&r.warn(`not modelled by the manifest: ${t.unknown.join(", ")} — anything they bind must be provisioned by hand.`),{code:0,data:t}},D=n=>{const e=n.cwd??process.cwd(),i=n.format==="json",{logger:r}=n;if(n.bindings===!0)return A({cwd:e,json:i,logger:r,out:n.out});if(n.out!==void 0){const a="--out only applies with --bindings; the full info snapshot prints to stdout under --format json.";return r.error(a),{code:f.USAGE,error:a}}const s=M(e);return i||I(s,r),{code:0,data:s,snapshot:s}},H=S(({cwd:n,format:e,logger:i,options:r})=>D({bindings:r.bindings===!0,cwd:n,format:e,logger:i,out:r.out}));export{M as collectInfo,H as execute,D as runInfoCommand};
1
+ import{existsSync as u,rmSync as a}from"node:fs";import{join as i}from"node:path";import{writeLinkedProject as d,LINKED_PROJECT_FILE as o}from"@lunora/config";import{d as k}from"../packem_shared/command-CAXl2A1S.mjs";import{EXIT_CODE as c}from"../packem_shared/EXIT_CODE-D_XCixv8.mjs";import{r as s}from"../packem_shared/wrangler-name-Dsk5K1f-.mjs";const v=r=>{try{const{protocol:n}=new URL(r);return n==="http:"||n==="https:"}catch{return!1}},f=(r,n)=>{const e=i(r,o);return u(e)?(a(e),n.success(`link: removed ${o}`),{code:0}):(n.warn(`link: no ${o} to remove`),{code:0})},w=r=>{const n=r.cwd??process.cwd(),{logger:e}=r;if(r.remove)return f(n,e);if(r.url===void 0||r.url==="")return e.error("link requires a deployed Worker URL. Usage: lunora link --url <https://your-worker>"),{code:c.USAGE};if(!v(r.url))return e.error(`link: invalid --url "${r.url}" — expected an http(s) URL`),{code:c.USAGE};const l=r.now??(()=>new Date().toISOString()),t={env:r.env,linkedAt:l(),workerName:r.name??s(n),workerUrl:r.url},m=d(n,t);return e.success(`link: ${t.workerName??"(unnamed worker)"} -> ${r.url}`),e.info(`link: wrote ${m}`),t.env!==void 0&&e.info(`link: environment "${t.env}"`),{code:0,link:t}},y=k(({cwd:r,logger:n,options:e})=>w({cwd:r,env:e.env,logger:n,name:e.name,remove:e.remove===!0,url:e.url}));export{y as execute,w as runLinkCommand};