@lunora/cli 1.0.0-alpha.217 → 1.0.0-alpha.219
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/bin.mjs +1 -1
- package/dist/index.d.mts +8 -0
- package/dist/index.d.ts +8 -0
- package/dist/index.mjs +1 -1
- package/dist/packem_chunks/handler.mjs +1 -1
- package/dist/packem_chunks/handler10.mjs +4 -1
- package/dist/packem_chunks/handler11.mjs +2 -4
- package/dist/packem_chunks/handler12.mjs +1 -2
- package/dist/packem_chunks/handler13.mjs +1 -1
- package/dist/packem_chunks/handler14.mjs +1 -1
- package/dist/packem_chunks/handler15.mjs +1 -1
- package/dist/packem_chunks/handler16.mjs +3 -1
- package/dist/packem_chunks/handler17.mjs +1 -3
- package/dist/packem_chunks/handler18.mjs +1 -1
- package/dist/packem_chunks/handler19.mjs +7 -1
- package/dist/packem_chunks/handler2.mjs +2 -1
- package/dist/packem_chunks/handler20.mjs +1 -7
- package/dist/packem_chunks/handler21.mjs +3 -1
- package/dist/packem_chunks/handler22.mjs +3 -2
- package/dist/packem_chunks/handler23.mjs +1 -3
- package/dist/packem_chunks/handler24.mjs +2 -3
- package/dist/packem_chunks/handler25.mjs +99 -1
- package/dist/packem_chunks/handler26.mjs +10 -99
- package/dist/packem_chunks/handler3.mjs +1 -2
- package/dist/packem_chunks/handler4.mjs +1 -1
- package/dist/packem_chunks/handler5.mjs +1 -1
- package/dist/packem_chunks/handler6.mjs +1 -1
- package/dist/packem_chunks/handler7.mjs +3 -1
- package/dist/packem_chunks/handler8.mjs +1 -3
- package/dist/packem_chunks/handler9.mjs +1 -1
- package/dist/packem_chunks/planDevCommand.mjs +6 -6
- package/dist/packem_chunks/runDeployCommand.mjs +1 -0
- package/dist/packem_chunks/runInitCommand.mjs +89 -63
- package/dist/packem_chunks/runMigrateGenerateCommand.mjs +3 -3
- package/dist/packem_shared/{COMMANDS-Cf45cyJN.mjs → COMMANDS-BbQ3-hLn.mjs} +1 -1
- package/dist/packem_shared/{DEFAULT_IMPORT_BATCH_SIZE-CYq3UJmD.mjs → DEFAULT_IMPORT_BATCH_SIZE-BPQYMEmV.mjs} +1 -1
- package/dist/packem_shared/{buildRegistryIndex-BcJgAx76.mjs → buildRegistryIndex-DVmy8fHE.mjs} +1 -1
- package/dist/packem_shared/catalog-Cbzph90w.mjs +1 -0
- package/dist/packem_shared/cli-DOBnG22n.mjs +3 -0
- package/dist/packem_shared/commands-CLLQuHqU.mjs +15 -0
- package/dist/packem_shared/{diffSnapshots-Cnoe8Ob4.mjs → diffSnapshots-DtC5Cs4Z.mjs} +3 -3
- package/dist/packem_shared/{import-8FCB0cUX.mjs → import-DuHtoh4_.mjs} +7 -7
- package/dist/packem_shared/resolve-BWFT7RvE.mjs +5 -0
- package/dist/packem_shared/runAddCommand-BABRWlOb.mjs +1 -0
- package/dist/packem_shared/schemaIrToSnapshot-VpPguG3W.mjs +1 -0
- package/dist/packem_shared/{storage-D5s4vbtJ.mjs → storage-DlUnv7uG.mjs} +1 -1
- package/dist/packem_shared/vectorize-metadata-dXpl2_Ar.mjs +1 -0
- package/package.json +11 -11
- package/skills/lunora-deploy/SKILL.md +42 -11
- package/skills/lunora-functions/SKILL.md +42 -14
- package/skills/lunora-migration-helper/SKILL.md +4 -4
- package/skills/lunora-performance-audit/SKILL.md +8 -5
- package/skills/lunora-quickstart/SKILL.md +3 -3
- package/skills/lunora-setup-auth/SKILL.md +23 -6
- package/skills/lunora-setup-hyperdrive/SKILL.md +33 -13
- package/skills/lunora-setup-mail/SKILL.md +34 -28
- package/skills/lunora-setup-scheduler/SKILL.md +15 -10
- package/skills/lunora-setup-storage/SKILL.md +182 -25
- package/dist/packem_chunks/handler27.mjs +0 -10
- package/dist/packem_shared/catalog-CJaormx0.mjs +0 -1
- package/dist/packem_shared/cli-CqNvbTR1.mjs +0 -3
- package/dist/packem_shared/commands-YfMX-Mto.mjs +0 -19
- package/dist/packem_shared/resolve-DZAGzg67.mjs +0 -1
- package/dist/packem_shared/runAddCommand-vE21wRIK.mjs +0 -1
- package/dist/packem_shared/runDeployCommand-o64lz-UD.mjs +0 -1
- package/dist/packem_shared/schemaIrToSnapshot-ogkcpHjM.mjs +0 -1
- package/dist/packem_shared/vectorize-metadata-DbziRKpX.mjs +0 -1
|
@@ -1,3 +1 @@
|
|
|
1
|
-
import{
|
|
2
|
-
`)[0]??i.message:String(i);a.warn(`could not fetch the transport at ${m} (${y}).`)});if(g!==void 0)return g;const p=await l(void 0);if(p===void 0)throw new d("NOT_FOUND",`no ${r} transport at ${m} or on the release branch. This language may not be released yet — pass --from <dir> to copy one from a checkout, or --ref <tag> to name a ref that has it.`);return a.warn(`FALLBACK: the transport is NOT version-matched to this CLI (${U()}). Wanted ${m}, used ${p.ref}. The vendored wire protocol may not be the one this surface was generated against; ${v} records what was actually copied.`),p},ee=(t,n,e)=>{const r={cliVersion:U(),files:e.files,language:n,note:e.versionMatched?"Vendored by `lunora sdk generate` at the ref matching the CLI that generated the surface beside it. Regenerate with a newer CLI to upgrade.":"Vendored by `lunora sdk generate` from a ref that is NOT this CLI's release tag, so the transport and the generated surface may be different protocol vintages.",ref:e.ref,source:e.source,versionMatched:e.versionMatched};E(u(t,v),`${JSON.stringify(r,void 0,4)}
|
|
3
|
-
`,"utf8")},te=u("lunora","_generated","openrpc.json"),re=t=>{if(!w(t))throw new d("NOT_FOUND",`no OpenRPC document at ${t} — run \`lunora codegen --api-spec openrpc\` (or \`--api-spec both\`) first, or pass --spec`);let n;try{n=JSON.parse(M(t,"utf8"))}catch(e){throw new d("BAD_REQUEST",`${t} is not valid JSON: ${e instanceof Error?e.message:String(e)}`)}if(n===null||typeof n!="object"||!Array.isArray(n.methods))throw new d("BAD_REQUEST",`${t} is not an OpenRPC document (no \`methods\` array)`);return n},de=J(async({argument:t,cwd:n,logger:e,options:r})=>{const a=t[0]??"generate";if(a!=="generate")throw new d("BAD_REQUEST",`unknown subcommand "${a}" — the only one is \`lunora sdk generate\``);const s=r.lang??"python",o=V[s];if(o===void 0)throw new d("BAD_REQUEST",`unsupported --lang "${s}" — expected one of: ${G.join(" | ")}`);const f=W("sdk generate",{allowUnsafeSource:r.allowUnsafeSource,logger:e,names:[],source:r.source});if(f!==void 0)throw new d("BAD_REQUEST",f);const h=O(n,r.spec??te),c=O(n,r.out??u("sdk",s)),l=re(h);l.methods.length===0&&e.warn(`${h} declares no methods — writing an empty SDK.`);const{files:m,undeclared:g,unrepresentable:p}=await P(l,o);D(c,{recursive:!0});const i=await Z({allowUnsafeSource:r.allowUnsafeSource,from:r.from,language:s,logger:e,outputDirectory:c,ref:r.ref,source:r.source,target:o});ee(c,s,i);for(const[S,L]of Object.entries(m)){const T=u(c,S);D(K(T),{recursive:!0}),E(T,L,"utf8")}const y=l.methods.filter(S=>!Q(S.result?.schema)).length;return e.success(`Generated ${s} SDK for ${String(l.methods.length)} function(s) → ${c}`),e.info(`Vendored the ${s} transport (${String(i.files.length)} file(s)) from ${i.source} @ ${i.ref}${i.versionMatched?" — version-matched to this CLI":""}; see ${v}.`),e.info(o.requires.length>0?`Install in the consuming project: ${o.requires.join(", ")}.`:"Nothing to install — the transport is vendored and needs only the standard library."),g.length>0&&e.warn(`${String(g.length)} schema(s) are not expressible as a named ${s} model, so those arguments or returns stay untyped: ${g.join(", ")}`),p.length>0&&e.warn(`${String(p.length)} function(s) take or return a \`v.bigint()\`/\`v.bytes()\`, which no generated model can carry — their parameters stay untyped, so pass wire values directly: ${p.join(", ")}`),y>0&&e.warn(`${String(y)} of ${String(l.methods.length)} function(s) return an untyped result — declare \`.output()\` on them for typed returns.`),{code:0}});export{de as execute};
|
|
1
|
+
import{readdirSync as w,lstatSync as R,existsSync as T}from"node:fs";import{join as v,basename as $}from"node:path";import{pathToFileURL as O}from"node:url";import{d as _}from"../packem_shared/command-DwC11Cwe.mjs";import{v as N,i as g,p as E,l as x}from"../packem_shared/output-format-DfogXx0p.mjs";const c=".eval.ts",b=new Set([".git","_generated","dist","node_modules"]),p=(e,s=[])=>{let r;try{r=w(e)}catch{return s}for(const t of r){const o=v(e,t);let n;try{n=R(o)}catch{continue}if(n.isDirectory()){if(b.has(t))continue;p(o,s)}else n.isFile()&&t.endsWith(c)&&s.push(o)}return s.toSorted((t,o)=>t.localeCompare(o))},L=e=>typeof e=="object"&&e!==null&&typeof e.run=="function",S=e=>typeof e=="number"&&Number.isFinite(e)&&e>=0&&e<=1,I="evals",A='"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)',D=/unknown file extension ".ts"/i,y=e=>e instanceof Error?e.code==="ERR_UNKNOWN_FILE_EXTENSION"?!0:D.test(e.message):!1,m=e=>$(e,c),M=e=>({average:e.result?.average,error:e.error,items:e.result?.items,name:e.name,passed:e.passed,path:e.path,threshold:e.threshold}),F=e=>({code:e.code,error:e.error,evals:e.evals.map(s=>M(s))}),i=(e,s,r)=>{e.error(r);const t={code:1,error:r,evals:[]};return g(s)&&E(F(t)),t},U=(e,s,r)=>{if(!T(e))return r.info(`eval: no "${s}" directory — nothing to run`),[];const t=p(e);return t.length===0&&r.info(`eval: no ${c} files found under "${s}"`),t},C=async e=>{const r=(await import(O(e).href)).default;if(!L(r))throw new Error("does not default-export an eval module (expected `{ run(): Promise<EvalResult>, name?, threshold? }`)");return r},J=async(e,s)=>{let r;try{r=await C(e)}catch(n){if(y(n))throw n;return{error:n instanceof Error?n.message:String(n),name:m(e),passed:!1,path:e}}const t=r.name??m(e);if(r.threshold!==void 0&&!S(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(),l=o===void 0||n.average>=o;return{name:t,passed:l,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}}},W=async(e,s)=>{const r=[];for(const t of e)r.push(await J(t,s));return r},H=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)`},V=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)} ${H(t)}`)}return r},X=async e=>{const s=e.cwd??process.cwd(),r=x(e.format,e.logger),t=N("eval",e.format);if(t!==void 0)return e.logger.error(t),{code:1,error:t,evals:[]};if(e.threshold!==void 0&&!S(e.threshold))return i(r,e.format,`eval: --threshold must be a number in [0, 1] — received "${String(e.threshold)}"`);const o=e.dir??I,n=v(s,o),l=U(n,o,r);let d;try{d=await W(l,e.threshold)}catch(a){if(!y(a))throw a;return i(r,e.format,A)}if(e.threshold!==void 0&&d.length===0){const a=`eval: --threshold ${String(e.threshold)} was set but 0 eval files were discovered under "${o}" — nothing was gated`;return i(r,e.format,a)}for(const a of V(d))r.info(a);const h=d.filter(a=>!a.passed),f=h.length>0?1:0;f===0?r.success(`eval: ${String(d.length)} eval(s) passed`):r.error(`eval: ${String(h.length)}/${String(d.length)} eval(s) failed`);const u={code:f,evals:d};return g(e.format)&&E(F(u)),u},z=_(async({cwd:e,logger:s,options:r})=>({code:(await X({cwd:e,dir:r.dir,format:r.format,logger:s,threshold:r.threshold})).code}));export{z as execute,X as runEvalCommand};
|
|
@@ -1,3 +1,2 @@
|
|
|
1
|
-
import
|
|
2
|
-
|
|
3
|
-
`,headers:{authorization:`Bearer ${r.token}`,"content-type":"application/json"},method:"PUT"});if(!d.ok){const s=await d.text().catch(()=>"<no body>");throw new h("INTERNAL",`backup: snapshot ${c.file} was written but its manifest was not (HTTP ${String(d.status)}): ${s}`)}},stage:async c=>{const n=await S(l(I(),"lunora-backup-"));return{path:l(n,p("",c)),release:async()=>w(n,{force:!0,recursive:!0})}}}},be=".lunora-backups",L="/_lunora/admin/backup/retention",ke="/_lunora/admin/backup/prune",pe="/_lunora/admin/pitr",ye="__lunora_admin__:getPitrBookmark",ve="__lunora_admin__:pitrRestore",$e=async(e,r)=>{const t=(e.now??(()=>new Date))().toISOString(),a=await r.stage(t);try{const o=await ue({cwd:e.cwd,fetchImpl:e.fetchImpl,logger:e.logger,out:a.path,prod:e.prod,tables:e.tables,token:e.token,url:e.url});if(o.code!==0)return{code:o.code};const i=r.locate(t),u=await j(a.path);await r.commit(i,a.path,u);const f={bytes:u.bytes,createdAt:t,file:i,id:t,rows:o.rows,sha256:u.sha256,tables:e.tables};return await r.record(f),e.logger.success(`backup created: ${i} (${o.rows.toString()} rows, ${u.bytes.toString()} bytes)`),{code:0,entry:f}}finally{await a.release().catch(o=>{e.logger.warn(`backup: could not clean up staging (${o instanceof Error?o.message:String(o)})`)})}},Te=async(e,r,t)=>{if(r?.sha256===void 0)return t.error(r===void 0?"--verify needs a recorded checksum, and a snapshot restored by path/key has no manifest entry — restore it by its backup id instead":`--verify: backup ${r.id} carries no recorded checksum — it was taken by a release before checksums existed`),{code:1};const a=await j(e);if(a.sha256!==r.sha256)return t.error(`--verify: ${r.file} does not match its recorded checksum (expected ${r.sha256}, got ${a.sha256}) — nothing was imported`),{code:1};t.success(`verified ${r.file} against its recorded sha256`)},Ne=async(e,r)=>{const t=await r.list();if(t.length===0)return e.logger.info(`no backups found in ${r.label}`),{code:0};for(const a of t)e.logger.info(`${a.id} ${a.rows.toString()} rows ${a.bytes.toString()} bytes ${a.file}`);return{code:0}},Se=async(e,r)=>{const{target:t}=e;if(t===void 0||t.length===0)return e.logger.error("restore requires a backup id or file path. Usage: lunora backup restore <id|file>"),{code:1};const o=(await r.list()).find(u=>u.id===t),i=await r.materialize(o,t);if(i===void 0)return e.logger.error(`backup not found: ${t}`),{code:1};try{if(e.verify===!0){const f=await Te(i.path,o,e.logger);if(f!==void 0)return f}return{code:(await se({cwd:e.cwd,fetchImpl:e.fetchImpl,file:i.path,logger:e.logger,prod:e.prod,token:e.token,url:e.url,yes:e.yes})).code}}finally{await i.release().catch(u=>{e.logger.warn(`backup: could not clean up the downloaded snapshot (${u instanceof Error?u.message:String(u)})`)})}},Ee=e=>{const r=e.token??process.env.LUNORA_ADMIN_TOKEN;if(!r){e.logger.error("admin token required — pass --token or set LUNORA_ADMIN_TOKEN");return}if(e.prod&&e.url===void 0){e.logger.error("--prod requires an explicit --url (refusing to target the implicit localhost worker)");return}if(e.restore===!0&&e.at===void 0&&e.bookmark===void 0){e.logger.error("pitr --restore requires --at <time> or --bookmark <bookmark>");return}const t=v(e.url,e.logger,e.cwd);if(t===void 0)return;if(e.restore===!0&&Y({prod:e.prod,url:t})&&e.yes!==!0){e.logger.error(`pitr --restore restores data in place at ${t}, which is not local. Re-run with --yes to confirm.`);return}const a=e.adminFetch??globalThis.fetch;if(typeof a!="function")throw new TypeError("no fetch implementation available — pass pitrFetch or run on Node >= 18");return{fetchImpl:a,requestUrl:`${t}${pe}`,token:r}},Ie=(e,r)=>{const t={};return e.at!==void 0&&(t.time=e.at),r&&e.bookmark!==void 0&&(t.bookmark=e.bookmark),r&&e.restart===!0&&(t.restart=!0),t},_e=async e=>{const r=Ee(e);if(r===void 0)return{code:1};const t=e.restore===!0,a=t?ve:ye,o=Ie(e,t),i=t?"restore":"bookmark";e.logger.info(`POST ${r.requestUrl} -> pitr ${i}${e.shard===void 0?"":` (shard "${e.shard}")`}`);const u=await r.fetchImpl(r.requestUrl,{body:JSON.stringify({args:o,functionPath:a,shardKey:e.shard}),headers:{authorization:`Bearer ${r.token}`,"content-type":"application/json"},method:"POST"});return await b(u,e.logger),{code:u.ok?0:1}},Re=(e,r)=>{if(e.bucket===void 0)return fe(l(r,e.dir??be));if(e.prod===!0&&e.url===void 0){e.logger.error("--prod requires an explicit --url (refusing to target the implicit localhost worker)");return}const t=v(e.url,e.logger,e.cwd);if(t===void 0)return;const{token:a}=A({cwd:r,token:e.token,url:t});if(!a){e.logger.error("admin token required — pass --token, set LUNORA_ADMIN_TOKEN, or add it to .dev.vars (local targets only)");return}const o=e.fetchImpl??globalThis.fetch;if(typeof o!="function")throw new TypeError("no fetch implementation available — pass fetchImpl or run on Node >= 18");return we({context:{baseUrl:t,bucket:e.bucket==="default"?void 0:e.bucket,fetchImpl:o,token:a},logger:e.logger,prefix:e.prefix})},q=e=>{const r=[e.bucket===void 0?void 0:"--bucket",e.prefix===void 0?void 0:"--prefix",e.dir===void 0?void 0:"--dir"].filter(i=>i!==void 0);if(r.length>0){e.logger.error(`${r.join(" / ")} ${r.length===1?"does":"do"} not apply here — retention and prune act on the store the worker itself is configured with (\`backupStore\`), not a destination you name.`);return}if(e.prod===!0&&e.url===void 0){e.logger.error("--prod requires an explicit --url (refusing to target the implicit localhost worker)");return}const t=v(e.url,e.logger,e.cwd);if(t===void 0)return;const{token:a}=A({cwd:e.cwd??process.cwd(),token:e.token,url:t});if(!a){e.logger.error("admin token required — pass --token, set LUNORA_ADMIN_TOKEN, or add it to .dev.vars (local targets only)");return}const o=e.adminFetch??globalThis.fetch;if(typeof o!="function")throw new TypeError("no fetch implementation available — pass pitrFetch or run on Node >= 18");return{baseUrl:t,fetchImpl:o,token:a}},M=(e,r)=>{e.logger.info(`backup retention would keep the newest ${r.keep.toString()} of ${r.eligible.toString()} under ${r.prefix} and delete ${r.wouldDelete.length.toString()}`);for(const t of r.wouldDelete)e.logger.info(` ${O(t)}`)},Pe=async e=>{const r=q(e);if(r===void 0)return{code:1};const t=await r.fetchImpl(`${r.baseUrl}${L}`,{headers:{authorization:`Bearer ${r.token}`},method:"GET"});if(!t.ok)return await b(t,e.logger),{code:1};const a=await t.json();return a.cron===void 0?(e.logger.info("no scheduled backup is configured (`backupCron`), so retention would delete nothing"),{code:0,preview:a}):a.keep<=0?(e.logger.info(`retention is off for cron "${a.cron}" (\`backupRetain\` unset) — every snapshot under ${a.prefix} is kept`),{code:0,preview:a}):(M(e,a),a.eligible===0&&e.logger.info(`no snapshot under ${a.prefix} was written by this cron, so retention has nothing of its own to remove`),{code:0,preview:a})},xe=(e,r)=>{e.logger.success(`deleted ${r.deleted.length.toString()} backup(s)`);for(const t of r.deleted)e.logger.info(` ${O(t)}`);r.failed.length>0&&e.logger.warn(`${r.failed.length.toString()} could not be removed — the snapshot may be gone with its manifest left behind; run again to retry`),r.ignored>0&&e.logger.info(`${r.ignored.toString()} were already gone by the time the delete ran`),r.remaining>0&&e.logger.info(`${r.remaining.toString()} more are past the window — run \`lunora backup prune\` again`)},Oe=async e=>{const r=q(e);if(r===void 0)return{code:1};const t=await r.fetchImpl(`${r.baseUrl}${L}`,{headers:{authorization:`Bearer ${r.token}`},method:"GET"});if(!t.ok)return await b(t,e.logger),{code:1};const a=await t.json();if(a.keep<=0||a.cron===void 0)return e.logger.error("backup prune needs a retention window: set `backupRetain` (and `backupCron`) on the worker. Without one there is nothing past the window to remove."),{code:1,preview:a};if(a.wouldDelete.length===0)return e.logger.info(`nothing to prune — ${a.eligible.toString()} snapshot(s) under ${a.prefix} and retention keeps the newest ${a.keep.toString()}`),{code:0,preview:a};if(M(e,a),e.yes!==!0){const u=e.confirm??(F()?z:void 0);if(u===void 0)return e.logger.error("refusing to delete backups without confirmation — re-run with --yes (there is no undo for an object-store delete)"),{code:1,preview:a};if(!await u(`delete ${a.wouldDelete.length.toString()} backup(s)? This cannot be undone. [y/N] `))return e.logger.info("nothing was deleted"),{code:0,preview:a}}const o=await r.fetchImpl(`${r.baseUrl}${ke}`,{body:JSON.stringify({confirm:a.wouldDelete}),headers:{authorization:`Bearer ${r.token}`,"content-type":"application/json"},method:"POST"});if(!o.ok)return await b(o,e.logger),{code:1,preview:a};const i=await o.json();return xe(e,i),{code:i.failed.length>0?1:0,deleted:i.deleted,preview:a}},Ae=async e=>{const r=e.cwd??process.cwd();try{if(e.subcommand==="pitr")return await _e(e);if(e.subcommand==="retention")return await Pe(e);if(e.subcommand==="prune")return await Oe(e);const t=Re(e,r);return t===void 0?{code:1}:e.subcommand==="create"?await $e(e,t):e.subcommand==="list"?await Ne(e,t):await Se(e,t)}catch(t){return e.logger.error(t instanceof Error?t.message:String(t)),{code:1}}},Ue=e=>e==="create"||e==="list"||e==="pitr"||e==="prune"||e==="restore"||e==="retention",Ze=X(({argument:e,cwd:r,logger:t,options:a})=>{const o=e[0];return Ue(o)?Ae({at:a.at,bookmark:a.bookmark,bucket:a.bucket,cwd:r,dir:a.dir,logger:t,prefix:a.prefix,prod:a.prod===!0,restart:a.restart===!0,restore:a.restore===!0,shard:a.shard,subcommand:o,tables:a.tables,target:e[1],token:a.token,url:Q({cwd:r,prod:a.prod===!0,url:a.url}),verify:a.verify===!0,yes:a.yes===!0}):(t.error(`backup: unknown subcommand "${o??""}" — expected create | list | restore | retention | prune | pitr`),{code:1})});export{Ze as execute,Ae as runBackupCommand};
|
|
1
|
+
import{readLinkedProject as g,resolveDeployDriver as v,execArgsFor as h,detectPackageManager as y}from"@lunora/config";import{d as b}from"../packem_shared/command-DwC11Cwe.mjs";import{defaultSpawner as w}from"../packem_shared/createRecordingSpawner-DJlNacZ6.mjs";import{createR2Sql as L}from"@lunora/bindings/r2sql";import{createPipelineLogReader as _}from"@lunora/runtime";const S=["trace","debug","log","info","warn","error","fatal"],T=new Set(S),m=/^\d+$/,d=(e,t)=>{if(e===void 0)return;const n=e.trim();if(m.test(n))return Number(n);const r=Date.parse(n);if(Number.isNaN(r))throw new TypeError(`logs: invalid ${t} "${e}" — pass epoch-millis or an ISO 8601 date`);return r},E=e=>Buffer.from(JSON.stringify(e),"utf8").toString("base64url"),C=e=>{const t=e.trim();if(m.test(t))return{ts:Number(t)};let n;try{n=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 n!="object"||n===null||typeof n.ts!="number"||!Number.isFinite(n.ts))throw new TypeError(`logs: invalid --cursor "${e}" — expected the token printed by the previous page (or a bare epoch-millis ts)`);const{ts:r}=n,s=n.seen,a=Array.isArray(s)?s.filter(i=>typeof i=="string"):void 0;return a!==void 0&&a.length>0?{seen:a,ts:r}:{ts:r}},u=(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}},I=e=>{const t={},n=d(e.since,"--since");n!==void 0&&(t.sinceTs=n);const r=d(e.until,"--until");r!==void 0&&(t.untilTs=r);const s=u(e.level,"--level");s!==void 0&&(t.level=s);const a=u(e.minLevel,"--min-level");if(a!==void 0&&(t.minLevel=a),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=C(e.cursor)),t},R=e=>{const t=new Date(e.ts).toISOString(),n=e.level.toUpperCase().padEnd(5);return`${t} ${n} ${e.functionPath} ${e.message}`},$=async e=>{const t=e.environment??process.env,n=t.R2_SQL_ACCOUNT_ID,r=t.R2_SQL_TOKEN,s=t.R2_SQL_BUCKET,a=[];if((n===void 0||n.length===0)&&a.push("R2_SQL_ACCOUNT_ID"),(r===void 0||r.length===0)&&a.push("R2_SQL_TOKEN"),(s===void 0||s.length===0)&&a.push("R2_SQL_BUCKET"),(e.table===void 0||e.table.length===0)&&a.push("--table"),a.length>0)return e.logger.error(`logs --durable: R2 SQL not configured (missing ${a.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:1,error:"not configured"};let i;try{i=I(e)}catch(o){return e.logger.error(o instanceof Error?o.message:String(o)),{code:1,error:"invalid option"}}const l=L({accountId:n,apiToken:r,bucket:s,fetch:e.fetch}),c=await _(l,{namespace:e.namespace,table:e.table}).query(i);for(const o of c.rows)process.stdout.write(`${e.ndjson===!0?JSON.stringify(o):R(o)}
|
|
2
|
+
`);return c.rows.length===0?e.logger.info("logs --durable: no matching log records"):c.nextCursor!==void 0&&e.logger.info(`logs --durable: more rows available — pass --cursor ${E(c.nextCursor)} for the next page`),{code:0,rows:c.rows}},x=new Set(["json","pretty"]),N=async e=>{const t=e.cwd??process.cwd();if(e.format!==void 0&&!x.has(e.format))return e.logger.error(`logs: unknown --format "${e.format}" — expected pretty | json`),{code:1,descriptor:void 0,error:"invalid format"};const n=e.env??g(t)?.env,r=v(e.target);if(r.toolchain===void 0)return e.logger.error(`logs: deploy target "${r.id}" has no command-line toolchain`),{code:1,descriptor:void 0,error:"no toolchain"};const s=r.toolchain.tail({environment:n,format:e.format,search:e.search,status:e.status,temporary:e.temporary,worker:e.worker}),a=h(y(t),s.tool,s.args),i={args:a.args,command:a.command,cwd:t};return e.logger.info(`tailing logs via ${i.command} ${i.args.join(" ")}`),{code:(await(e.spawner??w)(i)).code,descriptor:i}},k=b(({argument:e,cwd:t,logger:n,options:r})=>r.durable===!0?$({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}):N({cwd:t,env:r.env,format:r.format,logger:n,search:r.search,status:r.status,target:r.target,temporary:r.temporary===!0,worker:e[0]}));export{k as execute,N as runLogsCommand};
|
|
@@ -1 +1,99 @@
|
|
|
1
|
-
import{
|
|
1
|
+
import{existsSync as T,readFileSync as O}from"node:fs";import{writeFile as I,mkdir as k}from"node:fs/promises";import{join as b}from"@visulima/path";import{d as B}from"../packem_shared/command-DwC11Cwe.mjs";import{createRequire as U}from"node:module";import{LunoraError as N}from"@lunora/errors";import{addArgsFor as Y,detectPackageManager as q,parseSchema as F,applyAdditiveEdit as P}from"@lunora/config";const H=/^\//,K=(e,t)=>{try{const{args:n,command:r}=Y(q(e),[t],{dev:!0});return`${r} ${n.join(" ")}`}catch{return`<your-package-manager> add -D ${t}`}},L=(e,t,n)=>{const r=U(b(n,"noop.cjs"));try{r.resolve(e)}catch{throw new N("INTERNAL",`\`lunora introspect\` needs the \`${t}\` driver to read this database, and it isn't installed.
|
|
2
|
+
|
|
3
|
+
Install it in your project:
|
|
4
|
+
|
|
5
|
+
${K(n,t)}`)}return r(e)},j=e=>{const t=e.slice(0,Math.max(0,e.indexOf(":"))).toLowerCase();if(t==="postgres"||t==="postgresql")return"postgres";if(t==="mysql"||t==="mariadb")return"mysql";throw new N("INTERNAL",`Unrecognised database URL scheme \`${t}\`. Expected a \`postgres://\`, \`postgresql://\`, \`mysql://\`, or \`mariadb://\` connection string.`)},G=e=>{try{const t=new URL(e).pathname.replace(H,"");return t===""?void 0:decodeURIComponent(t)}catch{return}},J=async(e,t,n,r=process.cwd())=>{if(t==="postgres"){const m=L("pg","pg",r).Client,u=new m({connectionString:e});return await u.connect(),{close:async()=>{await u.end()},execute:async(l,d)=>(await u.query(l,[...d])).rows,schema:n??"public"}}const a=L("mysql2/promise","mysql2",r).createConnection,o=await a(e),i=n??G(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"]),Q={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()"},W={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,t)=>{const r=(t==="postgres"?Q:W)[e.dataType],s=e.references===void 0?r:`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,X=/[^\dA-Z]+(.)?/gi,z=/^\d+/,Z=/[^\w-]/g,V=/[\u003C\u003E\u002F\u2028\u2029]/g,ee={"/":String.raw`\u002F`,"\u2028":String.raw`\u2028`,"\u2029":String.raw`\u2029`,"<":String.raw`\u003C`,">":String.raw`\u003E`},f=e=>JSON.stringify(e).replaceAll(V,t=>ee[t]??t),S=e=>M.test(e)?e:f(e),ne=e=>M.test(e)?`.${e}`:`[${f(e)}]`,x=e=>e.replaceAll("*/",String.raw`*\/`),te=e=>{const t=e.replaceAll(Z,"_");return t===""?"table":t},re=e=>{const n=e.replaceAll(X,(r,s)=>s?.toUpperCase()??"").replace(z,"");return n===""?"table":`${n.charAt(0).toLowerCase()}${n.slice(1)}`},C=e=>e.columns.filter(t=>!h.has(t.name)),ae=e=>{const t=new Set(e.primaryKey);for(const n of e.indexes)for(const r of n.columns)t.add(r);for(const n of e.columns)n.references!==void 0&&t.add(n.name);return[...t].filter(n=>!h.has(n))},D=(e,t,n,r)=>e.references===void 0||t.has(e.references.table)?e:(r.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}),se=(e,t,n,r)=>{const s=[];for(const o of e.columns){if(h.has(o.name)){r.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,r),{expression:c,known:m}=w(i,t);!m&&i.references===void 0&&(r.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
|
+
`)},`},oe=(e,t,n)=>{const r=new Set(e.tables.map(a=>a.name)),s=e.tables.map(a=>se(a,e.dialect,r,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 "${t.serverImport}";
|
|
21
|
+
|
|
22
|
+
export default defineSchema({
|
|
23
|
+
${s}
|
|
24
|
+
});
|
|
25
|
+
`},ie=(e,t,n,r=new Set([e.name]),s=[])=>{const a=re(e.name),o=ae(e),i=new Map(C(e).map(l=>[l.name,l])),c=o.map(l=>{const d=i.get(l);if(d===void 0)return;const p=D({...d,nullable:!1},r,e.name,[]),{expression:y,known:A}=w(p,t);return!A&&p.references===void 0&&s.push(`${e.name}.${l}: filter falls back to \`v.any()\` (no mapping for SQL type \`${d.dataType}\`).`),` ${S(l)}: ${y},`}).filter(l=>l!==void 0),m=[f("_creationTime"),...o.map(l=>f(l))].join(", "),u=`ctx.db${ne(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
|
+
`},ce=(e,t)=>{const n=[],r=new Set(e.tables.map(a=>a.name)),s=[{contents:oe(e,t,n),path:"schema.ts"}];if(t.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=te(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:ie(o,e.dialect,t,r,n),path:`${i}.ts`})}}return{files:s,warnings:n}},_=/^[A-Z_$][\w$]*$/i,me=e=>e.startsWith("v.optional(")&&e.endsWith(")")?e.slice(11,-1):e,le=(e,t,n)=>{const r=[],s=new Set(t?.columns.map(a=>a.name));for(const a of e.columns){if(h.has(a.name)||s.has(a.name))continue;if(!_.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);r.push({column:a.name,kind:"addOptionalColumn",table:e.name,validator:me(i)}),!a.nullable&&t!==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 r},ue=(e,t,n)=>{const r=[],s=new Set(t?.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(!_.test(a.name)||!o.every(i=>_.test(i))){n.push(`${e.name}: index \`${a.name}\` skipped — index and column names must be bare identifiers to merge.`);continue}r.push({fields:o,kind:"addIndex",name:a.name,table:e.name,...a.unique?{unique:!0}:{}})}}return r},de=(e,t,n)=>{const r=[],s=[],a=new Map(t.map(i=>[i.name,i])),o=new Set([...a.keys(),...e.tables.map(i=>i.name)]);for(const i of e.tables){if(!_.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&&r.push({global:{backend:"hyperdrive"},kind:"addTable",table:i.name}),r.push(...le(i,c,{dialect:n,present:o,warnings:s}),...ue(i,c,s))}return{edits:r,warnings:s}},pe=(e,t,n)=>{const r=F(e);if(!r.ok)return{applied:0,warnings:[`lunora/schema.ts could not be parsed (${r.reason}) — leave it alone and merge by hand, or pass --force.`]};const s=de(t,r.tables,n),a=[...s.warnings];let o=e,i=0;for(const c of s.edits){const m=P(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,t)=>{const n=e[t]??e[t.toLowerCase()]??e[t.toUpperCase()];return typeof n=="string"?n:typeof n=="number"||typeof n=="bigint"||typeof n=="boolean"?String(n):""},ge=`
|
|
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`,fe=`
|
|
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`,ve=`
|
|
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'`,he=`
|
|
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`,be=`
|
|
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`,Ee=`
|
|
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`,_e=`
|
|
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`,ye=`
|
|
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 t=new Map;for(const n of e){const r=g(n,"table_name"),s=t.get(r);s===void 0?t.set(r,[n]):s.push(n)}return t},Ae=(e,t)=>{const n=g(e,"data_type").toLowerCase();if(t!=="postgres")return{arrayDepth:0,dataType:n};const r=g(e,"udt_name").toLowerCase();return n==="array"&&r.startsWith("_")?{arrayDepth:1,dataType:r.slice(1)}:{arrayDepth:0,dataType:r===""?n:r}},Se=(e,t)=>{const n=new Map;for(const r of e){const s=g(r,"index_name"),a=t==="postgres"?g(r,"is_unique")==="true":g(r,"NON_UNIQUE")==="0",o=n.get(s);o===void 0?n.set(s,{columns:[g(r,"column_name")],unique:a}):o.columns.push(g(r,"column_name"))}return[...n.entries()].map(([r,s])=>({columns:s.columns,name:r,unique:s.unique}))},Ne=async(e,t,n)=>{const r=t==="postgres",[s,a,o,i]=await Promise.all([e(r?ge:be,[n]),e(r?fe:Ee,[n]),e(r?ve:_e,[n]),e(r?he:ye,[n])]),c=E(a),m=E(o),u=E(i),l=[];for(const[d,p]of E(s)){const y=new Map((m.get(d)??[]).map(v=>[g(v,"column_name"),{column:g(v,"foreign_column"),table:g(v,"foreign_table")}])),A=p.map(v=>{const R=g(v,"column_name"),$=y.get(R);return{...Ae(v,t),name:R,nullable:g(v,"is_nullable").toUpperCase()==="YES",...$===void 0?{}:{references:$}}});l.push({columns:A,indexes:Se(u.get(d)??[],t),name:d,primaryKey:(c.get(d)??[]).map(v=>g(v,"column_name"))})}return l.sort((d,p)=>d.name.localeCompare(p.name)),{dialect:t,tables:l}},we=e=>{try{const t=JSON.parse(O(b(e,"package.json"),"utf8"));return t.dependencies?.lunorash===void 0&&t.devDependencies?.lunorash===void 0?"@lunora/server":"lunorash/server"}catch{return"@lunora/server"}},Re=async(e,t,n)=>{const r=b(t,e.path);return T(r)&&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 k(t,{recursive:!0}),await I(r,e.contents,"utf8"),n.logger.info(`wrote lunora/${e.path}`),!0)},$e=(e,t)=>{const n=t.tables;if(n===void 0||n.length===0)return e.tables;for(const r of n)e.tables.some(s=>s.name===r)||t.logger.warn(`--tables: no table named "${r}" exists in this schema — skipped.`);return e.tables.filter(r=>n.includes(r.name))},Le=async(e,t,n,r)=>{const s=pe(O(e,"utf8"),t,n);for(const a of s.warnings)r.logger.warn(a);return s.text===void 0?(r.logger.info("lunora/schema.ts is already up to date with the database."),!1):r.dryRun===!0?(r.logger.info(`would merge ${String(s.applied)} addition(s) into lunora/schema.ts`),!1):(await I(e,s.text,"utf8"),r.logger.info(`merged ${String(s.applied)} addition(s) into lunora/schema.ts`),!0)},Te=async e=>{const t=e.cwd??process.cwd();if(e.connection===void 0&&(e.url===void 0||e.url===""))return e.logger.error("`lunora introspect` needs a database URL: pass --url, or set DATABASE_URL."),{code:1,written:[]};const n=e.connection===void 0?j(e.url):e.dialect??"postgres",r=e.connection??await J(e.url,n,e.schema,t);let s;try{s=await Ne(r.execute,n,r.schema)}finally{e.connection===void 0&&await r.close()}const a=$e(s,e);if(a.length===0)return e.logger.error("no tables found to introspect — check --schema and --tables."),{code:1,written:[]};const{files:o,warnings:i}=ce({...s,tables:a},{procedures:e.procedures!==!1,serverImport:we(t)}),c=b(t,"lunora"),m=[],u=b(c,"schema.ts"),l=T(u)&&e.force!==!0,d=l?o.filter(p=>p.path!=="schema.ts"):o;l&&await Le(u,{...s,tables:a},n,e)&&m.push("schema.ts");for(const p of d)await Re(p,c,e)&&m.push(p.path);for(const p of i)e.logger.warn(p);return e.logger.info(`introspected ${String(a.length)} table(s) from ${n}. Review the generated files before running \`lunora dev\`.`),{code:0,written:m}},Be=B(async({cwd:e,logger:t,options:n})=>({code:(await Te({cwd:e,dryRun:n.dryRun===!0,force:n.force===!0,logger:t,procedures:n.procedures!==!1,schema:n.schema,tables:n.tables===void 0?void 0:n.tables.split(",").map(s=>s.trim()),url:n.url??process.env.DATABASE_URL})).code}));export{Be as execute,we as resolveServerImport,Te as runIntrospectCommand};
|
|
@@ -1,99 +1,10 @@
|
|
|
1
|
-
import{existsSync as
|
|
2
|
-
|
|
3
|
-
|
|
4
|
-
|
|
5
|
-
|
|
6
|
-
|
|
7
|
-
`)}
|
|
8
|
-
|
|
9
|
-
|
|
10
|
-
`)}
|
|
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 "${t.serverImport}";
|
|
21
|
-
|
|
22
|
-
export default defineSchema({
|
|
23
|
-
${s}
|
|
24
|
-
});
|
|
25
|
-
`},ie=(e,t,n,r=new Set([e.name]),s=[])=>{const a=re(e.name),o=ae(e),i=new Map(C(e).map(l=>[l.name,l])),c=o.map(l=>{const d=i.get(l);if(d===void 0)return;const p=D({...d,nullable:!1},r,e.name,[]),{expression:y,known:A}=w(p,t);return!A&&p.references===void 0&&s.push(`${e.name}.${l}: filter falls back to \`v.any()\` (no mapping for SQL type \`${d.dataType}\`).`),` ${S(l)}: ${y},`}).filter(l=>l!==void 0),m=[f("_creationTime"),...o.map(l=>f(l))].join(", "),u=`ctx.db${ne(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
|
-
`},ce=(e,t)=>{const n=[],r=new Set(e.tables.map(a=>a.name)),s=[{contents:oe(e,t,n),path:"schema.ts"}];if(t.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=te(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:ie(o,e.dialect,t,r,n),path:`${i}.ts`})}}return{files:s,warnings:n}},_=/^[A-Z_$][\w$]*$/i,me=e=>e.startsWith("v.optional(")&&e.endsWith(")")?e.slice(11,-1):e,le=(e,t,n)=>{const r=[],s=new Set(t?.columns.map(a=>a.name));for(const a of e.columns){if(h.has(a.name)||s.has(a.name))continue;if(!_.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);r.push({column:a.name,kind:"addOptionalColumn",table:e.name,validator:me(i)}),!a.nullable&&t!==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 r},ue=(e,t,n)=>{const r=[],s=new Set(t?.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(!_.test(a.name)||!o.every(i=>_.test(i))){n.push(`${e.name}: index \`${a.name}\` skipped — index and column names must be bare identifiers to merge.`);continue}r.push({fields:o,kind:"addIndex",name:a.name,table:e.name,...a.unique?{unique:!0}:{}})}}return r},de=(e,t,n)=>{const r=[],s=[],a=new Map(t.map(i=>[i.name,i])),o=new Set([...a.keys(),...e.tables.map(i=>i.name)]);for(const i of e.tables){if(!_.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&&r.push({global:{backend:"hyperdrive"},kind:"addTable",table:i.name}),r.push(...le(i,c,{dialect:n,present:o,warnings:s}),...ue(i,c,s))}return{edits:r,warnings:s}},pe=(e,t,n)=>{const r=F(e);if(!r.ok)return{applied:0,warnings:[`lunora/schema.ts could not be parsed (${r.reason}) — leave it alone and merge by hand, or pass --force.`]};const s=de(t,r.tables,n),a=[...s.warnings];let o=e,i=0;for(const c of s.edits){const m=P(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,t)=>{const n=e[t]??e[t.toLowerCase()]??e[t.toUpperCase()];return typeof n=="string"?n:typeof n=="number"||typeof n=="bigint"||typeof n=="boolean"?String(n):""},ge=`
|
|
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`,fe=`
|
|
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`,ve=`
|
|
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'`,he=`
|
|
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`,be=`
|
|
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`,Ee=`
|
|
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`,_e=`
|
|
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`,ye=`
|
|
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 t=new Map;for(const n of e){const r=g(n,"table_name"),s=t.get(r);s===void 0?t.set(r,[n]):s.push(n)}return t},Ae=(e,t)=>{const n=g(e,"data_type").toLowerCase();if(t!=="postgres")return{arrayDepth:0,dataType:n};const r=g(e,"udt_name").toLowerCase();return n==="array"&&r.startsWith("_")?{arrayDepth:1,dataType:r.slice(1)}:{arrayDepth:0,dataType:r===""?n:r}},Se=(e,t)=>{const n=new Map;for(const r of e){const s=g(r,"index_name"),a=t==="postgres"?g(r,"is_unique")==="true":g(r,"NON_UNIQUE")==="0",o=n.get(s);o===void 0?n.set(s,{columns:[g(r,"column_name")],unique:a}):o.columns.push(g(r,"column_name"))}return[...n.entries()].map(([r,s])=>({columns:s.columns,name:r,unique:s.unique}))},Ne=async(e,t,n)=>{const r=t==="postgres",[s,a,o,i]=await Promise.all([e(r?ge:be,[n]),e(r?fe:Ee,[n]),e(r?ve:_e,[n]),e(r?he:ye,[n])]),c=E(a),m=E(o),u=E(i),l=[];for(const[d,p]of E(s)){const y=new Map((m.get(d)??[]).map(v=>[g(v,"column_name"),{column:g(v,"foreign_column"),table:g(v,"foreign_table")}])),A=p.map(v=>{const R=g(v,"column_name"),$=y.get(R);return{...Ae(v,t),name:R,nullable:g(v,"is_nullable").toUpperCase()==="YES",...$===void 0?{}:{references:$}}});l.push({columns:A,indexes:Se(u.get(d)??[],t),name:d,primaryKey:(c.get(d)??[]).map(v=>g(v,"column_name"))})}return l.sort((d,p)=>d.name.localeCompare(p.name)),{dialect:t,tables:l}},we=e=>{try{const t=JSON.parse(O(b(e,"package.json"),"utf8"));return t.dependencies?.lunorash===void 0&&t.devDependencies?.lunorash===void 0?"@lunora/server":"lunorash/server"}catch{return"@lunora/server"}},Re=async(e,t,n)=>{const r=b(t,e.path);return T(r)&&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 k(t,{recursive:!0}),await I(r,e.contents,"utf8"),n.logger.info(`wrote lunora/${e.path}`),!0)},$e=(e,t)=>{const n=t.tables;if(n===void 0||n.length===0)return e.tables;for(const r of n)e.tables.some(s=>s.name===r)||t.logger.warn(`--tables: no table named "${r}" exists in this schema — skipped.`);return e.tables.filter(r=>n.includes(r.name))},Le=async(e,t,n,r)=>{const s=pe(O(e,"utf8"),t,n);for(const a of s.warnings)r.logger.warn(a);return s.text===void 0?(r.logger.info("lunora/schema.ts is already up to date with the database."),!1):r.dryRun===!0?(r.logger.info(`would merge ${String(s.applied)} addition(s) into lunora/schema.ts`),!1):(await I(e,s.text,"utf8"),r.logger.info(`merged ${String(s.applied)} addition(s) into lunora/schema.ts`),!0)},Te=async e=>{const t=e.cwd??process.cwd();if(e.connection===void 0&&(e.url===void 0||e.url===""))return e.logger.error("`lunora introspect` needs a database URL: pass --url, or set DATABASE_URL."),{code:1,written:[]};const n=e.connection===void 0?j(e.url):e.dialect??"postgres",r=e.connection??await J(e.url,n,e.schema,t);let s;try{s=await Ne(r.execute,n,r.schema)}finally{e.connection===void 0&&await r.close()}const a=$e(s,e);if(a.length===0)return e.logger.error("no tables found to introspect — check --schema and --tables."),{code:1,written:[]};const{files:o,warnings:i}=ce({...s,tables:a},{procedures:e.procedures!==!1,serverImport:we(t)}),c=b(t,"lunora"),m=[],u=b(c,"schema.ts"),l=T(u)&&e.force!==!0,d=l?o.filter(p=>p.path!=="schema.ts"):o;l&&await Le(u,{...s,tables:a},n,e)&&m.push("schema.ts");for(const p of d)await Re(p,c,e)&&m.push(p.path);for(const p of i)e.logger.warn(p);return e.logger.info(`introspected ${String(a.length)} table(s) from ${n}. Review the generated files before running \`lunora dev\`.`),{code:0,written:m}},Be=B(async({cwd:e,logger:t,options:n})=>({code:(await Te({cwd:e,dryRun:n.dryRun===!0,force:n.force===!0,logger:t,procedures:n.procedures!==!1,schema:n.schema,tables:n.tables===void 0?void 0:n.tables.split(",").map(s=>s.trim()),url:n.url??process.env.DATABASE_URL})).code}));export{Be as execute,we as resolveServerImport,Te as runIntrospectCommand};
|
|
1
|
+
import{V as I}from"../packem_shared/cli-DOBnG22n.mjs";import{d as R}from"../packem_shared/command-DwC11Cwe.mjs";import{existsSync as u,readFileSync as v,mkdirSync as J,realpathSync as W,statSync as V,writeFileSync as z,chmodSync as G,renameSync as H,unlinkSync as K}from"node:fs";import{homedir as w}from"node:os";import{findWranglerFile as q}from"@lunora/config/cloudflare";import{join as s,dirname as B,relative as X}from"@visulima/path";import{stringify as Z}from"smol-toml";import{parse as Q,modify as Y,applyEdits as ee}from"jsonc-parser";import{detectPackageManager as re,execArgsFor as te,readLiveDevServerState as b,DEV_STATE_DIR as ne}from"@lunora/config";import{resolveAdminToken as oe}from"@lunora/config/studio-host";import{connectLocalStdio as ae}from"@lunora/mcp";import{resolve as h}from"node:path";import{i as le}from"../packem_shared/path-containment-CgxYZggb.mjs";const f=e=>({args:[...e.args],command:e.command,...e.env===void 0?{}:{env:e.env}}),y=e=>e.transport==="http"?{type:"http",url:e.url}:f(e),ce=e=>e.transport==="http"?{httpUrl:e.url}:f(e),se=e=>e.transport==="http"?{serverUrl:e.url}:f(e),ie=e=>({args:["-y","mcp-remote",e],command:"npx"}),de=e=>e.transport==="http"?ie(e.url):f(e),ue=e=>e.transport==="http"?{url:e.url}:f(e),fe=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}},me=e=>e.transport==="http"?{disabled:!1,type:"streamableHttp",url:e.url}:{disabled:!1,...f(e)},pe=({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")}:{}},ge=(e,r)=>Z({mcp_servers:{[e]:r.transport==="http"?{url:r.url}:{args:[...r.args],command:r.command,...r.env===void 0?{}:{env:r.env}}}}),g=[{buildEntry:y,paths:({projectRoot:e})=>({project:s(e,".mcp.json")}),format:"json",id:"claude-code",key:"mcpServers",label:"Claude Code"},{buildEntry:y,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:y,paths:({projectRoot:e})=>({project:s(e,".vscode","mcp.json")}),format:"json",id:"vscode",key:"servers",label:"VS Code (GitHub Copilot)"},{buildEntry:ce,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:de,paths:pe,format:"json",id:"claude-desktop",key:"mcpServers",label:"Claude Desktop"},{buildEntry:se,paths:({home:e})=>({global:s(e,".codeium","windsurf","mcp_config.json")}),format:"json",id:"windsurf",key:"mcpServers",label:"Windsurf"},{buildEntry:fe,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:me,paths:({home:e})=>({global:s(e,".cline","mcp.json")}),format:"json",id:"cline",key:"mcpServers",label:"Cline"},{buildEntry:ue,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:ge}],x=g.map(e=>e.id),ve=e=>g.find(r=>r.id===e.toLowerCase()),_=(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&&G(a,n),H(a,t)}catch(o){try{K(a)}catch{}throw o}},he={formattingOptions:{insertSpaces:!0,tabSize:4}},S=e=>{const r=[],t=Q(e,r,{allowTrailingComma:!0});return{errors:r,value:t}},p=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),k=(e,r,t)=>{if(!p(e))return;const n=e[r];return p(n)?n[t]:void 0},M=e=>{if(!u(e.path))return"absent";let r;try{r=v(e.path,"utf8")}catch{return"invalid"}if(r.trim().length===0)return"absent";const{errors:t,value:n}=S(r);return t.length>0||!p(n)?"invalid":k(n,e.key,e.name)===void 0?"absent":"present"},ye=e=>M(e)==="present",L=(e,r,t,n,a)=>{try{const o=Y(e,[t,n],a,he);o.length>0&&_(r,ee(e,o));return}catch(o){return o instanceof Error?o.message:String(o)}},be=e=>{const{entry:r,force:t=!1,key:n,name:a,path:o}=e,l=u(o)?v(o,"utf8"):"";if(l.trim().length===0)return J(B(o),{recursive:!0}),_(o,`${JSON.stringify({[n]:{[a]:r}},void 0,4)}
|
|
2
|
+
`),{action:"created",path:o};const{errors:c,value:i}=S(l);if(c.length>0)return{action:"invalid",error:`parse error at offset ${String(c[0]?.offset??0)}`,path:o};if(!p(i))return{action:"invalid",error:"the file's root is not a JSON object",path:o};const m=i[n];if(m!==void 0&&!p(m))return{action:"invalid",error:`"${n}" is not an object`,path:o};if(k(i,n,a)!==void 0&&!t)return{action:"skipped",path:o};const $=L(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(!u(n))return{action:"absent",path:n};let a;try{a=v(n,"utf8")}catch(i){return{action:"invalid",error:i instanceof Error?i.message:String(i),path:n}}const{errors:o,value:l}=S(a);if(o.length>0)return{action:"invalid",error:`parse error at offset ${String(o[0]?.offset??0)}`,path:n};if(k(l,r,t)===void 0)return{action:"absent",path:n};const c=L(a,n,r,t,void 0);return c===void 0?{action:"removed",path:n}:{action:"invalid",error:c,path:n}},Se=["global","project"],d=(e,r)=>{const t=X(r,e);return t.length>0&&!t.startsWith("..")?t:e},ke=(e,r)=>{const t=e.paths(r);return Se.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}},Ee=e=>g.filter(r=>Object.values(r.paths(e)).some(t=>u(t))),N=(e,r,t,n)=>{if(e.length===0)return r();const a=[];for(const o of e){const l=ve(o);if(l===void 0){t.error(`mcp ${n}: unknown client "${o}". Known clients: ${x.join(", ")}.`);return}a.push(l)}return a},je=e=>e.client.format==="json",Oe="https://lunora.sh/mcp",A="lunora-docs",U="lunora",Ce=e=>u(s(e,"lunora"))&&q(e)!==void 0,xe=e=>{const{args:r,command:t}=te(e,"lunora",["mcp","serve"]);return{args:r,command:t,transport:"stdio"}},_e=e=>({transport:"http",url:e}),Me=e=>({home:e.home,platform:e.platform,projectRoot:e.cwd}),D=(e,r,t)=>$e(e,Me(t),t.scope??r.preferredScope,t.scope!==void 0||!r.allowScopeFallback),Le=(e,r,t)=>{const n=D(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=d(a,t.cwd);return t.force!==!0&&ye({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=be({entry:o,force:t.force===!0,key:e.key,name:r.name,path:a}),c=d(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}},Ne=(e,r,t)=>{const n=D(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 ${d(n,t.cwd)}
|
|
4
|
+
|
|
5
|
+
${e.renderSnippet(r.name,r.spec)}`),{action:"printed",path:n}},Ae=e=>{const r=[];return e.localOnly!==!0&&r.push({allowScopeFallback:!0,name:A,preferredScope:"global",spec:_e(e.docsUrl??Oe)}),e.docsOnly!==!0&&Ce(e.cwd)&&r.push({allowScopeFallback:!1,name:U,preferredScope:"project",spec:xe(re(e.cwd))}),r},Ue=e=>{const r=e.home??w(),t=e.platform??process.platform;e.logger.info("Supported MCP clients:");for(const n of g){const a=n.paths({home:r,platform:t,projectRoot:e.cwd}),o=l=>{const c=a[l];return c===void 0?"—":d(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:[]}},De=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"?Le(a,o,t):Ne(a,o,t);l!==void 0&&n.push({action:l.action,client:a.id,path:l.path,server:o.name})}return n},Te=e=>{const r=e.home??w(),t=e.platform??process.platform,n=N(e.clients,()=>Ee({home:r,platform:t,projectRoot:e.cwd}),e.logger,"install");if(n===void 0)return{code:1,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:1,written:[]};e.clients.length===0&&e.logger.info(`Detected ${String(n.length)} configured client(s): ${n.map(l=>l.label).join(", ")}.`);const a=Ae(e);if(a.length===0)return e.logger.error(`mcp install: nothing to install — ${De(e)}`),{code:1,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,T=1e3,E=e=>({content:[{text:JSON.stringify(e,void 0,2),type:"text"}]}),Fe=e=>({content:[{text:e,type:"text"}]}),Ie=e=>{const r=typeof e=="string"?Number(e):e;return typeof r!="number"||!Number.isFinite(r)?P:Math.min(T,Math.max(1,Math.floor(r)))},j=(e,r)=>{if(r===void 0)return;const t=h(e,ne);return le(t,h(e,r))?h(e,r):void 0},Re=(e,r)=>{const t=v(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=b(e);return E(r===void 0?{hint:"Start it with `lunora dev` in the project directory.",running:!1}:{background:r.background===!0,logFile:j(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(T)})`,type:"number"}},type:"object"},name:"lunora_dev_logs"},handle:async r=>{const t=b(e);if(t===void 0)return{content:[{text:"no dev server is running — start one with `lunora dev`",type:"text"}],isError:!0};const n=j(e,t.logFile);if(n===void 0||!u(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=Ie(r.lines),o=Re(n,a);return Fe(o.length===0?"(the dev server log is empty)":o)}}],We=new Set(["127.0.0.1","::1","localhost"]),F=e=>{try{const{hostname:r}=new URL(e);return We.has(r.startsWith("[")?r.slice(1,-1):r)}catch{return!1}},O=e=>{const r=e.url??b(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(!F(r))return{url:r};const t=oe(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=!F(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
|
+
`},Ge=async(e,r=ae)=>{const t=e.writeError??(o=>{process.stderr.write(o)});let n;try{n=await r({allowWrites:e.allowWrites===!0,deployment:()=>O(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=O(e);return t(ze(a)),await Ve(n),{code:0,deployment:a}},He=e=>{const r=[];return e.localOnly!==!0&&r.push(A),e.docsOnly!==!0&&r.push(U),r},Ke=(e,r,t,n)=>{const a=we({key:e.key,name:r,path:t}),o=d(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}},qe=(e,r,t,n)=>{const a=M({key:e.key,name:r,path:t}),o=d(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=>ke(n,r)).filter(je).filter(n=>t===void 0||n.scope===t),Xe=e=>{const r=e.home??w(),t=e.platform??process.platform,n=N(e.clients,()=>g,e.logger,"uninstall");if(n===void 0)return{code:1,removed:[]};const a=He(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:1,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 m=e.print===!0?qe(c.client,i,c.path,e):Ke(c.client,i,c.path,e);m.action!=="absent"&&o.push({...m,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}},C=e=>e.global===!0?"global":e.project===!0?"project":void 0,Ze=async(e,r)=>{const{code:t}=await Ge({allowWrites:r.allowWrites===!0,cwd:e,noDocs:r.docs===!1,version:I,...r.docsUrl===void 0?{}:{docsUrl:r.docsUrl},...r.token===void 0?{}:{token:r.token},...r.url===void 0?{}:{url:r.url}});return{code:t}},ur=R(async({argument:e,cwd:r,logger:t,options:n})=>{const[a,...o]=e;if(a==="serve")return Ze(r,n);if(a==="uninstall"){const l=C(n),{code:c}=Xe({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 Ue({cwd:r,logger:t});const l=C(n),{code:c}=Te({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:1}});export{ur as execute};
|
|
@@ -1,2 +1 @@
|
|
|
1
|
-
import{
|
|
2
|
-
`):h(o,r),{code:0,descriptor:s,report:o}}finally{if(i&&l(n))try{d(n,{force:!0,recursive:!0})}catch{}}},C=S(({cwd:e,logger:t,options:r})=>x({cwd:e,json:r.json===!0,logger:t}));export{C as execute,x as runAnalyzeCommand};
|
|
1
|
+
import{d as i}from"../packem_shared/command-DwC11Cwe.mjs";import{i as l}from"../packem_shared/docker-DpVxvYpL.mjs";import{defaultSpawner as m}from"../packem_shared/createRecordingSpawner-DJlNacZ6.mjs";import{execArgsFor as g,detectPackageManager as p}from"@lunora/config";const o=new Set(["build","delete","images","info","list","push"]),f=new Set(["build","push"]),h=async e=>{const[a,...t]=e.argument;if(a===void 0||!o.has(a))return e.logger.error(`lunora containers requires a subcommand: ${[...o].toSorted((u,d)=>u.localeCompare(d)).join(" | ")}. Example: lunora containers build ./containers/app --tag app:v1 --push`),{code:1};if(f.has(a)&&!(e.dockerAvailable??l)())return e.logger.error(`containers ${a} needs a running Docker-compatible engine (it builds/pushes images locally). Start Docker or Colima and retry. Note: container images must target linux/amd64.`),{code:1};const r=["containers",a,...t];e.tag!==void 0&&r.push("--tag",e.tag),e.push===!0&&r.push("--push"),e.env!==void 0&&r.push("--env",e.env);const s=e.cwd??process.cwd(),c=g(p(s),"wrangler",r),n={args:c.args,command:c.command,cwd:s};return e.logger.info(`running ${n.command} ${n.args.join(" ")}`),{code:(await(e.spawner??m)(n)).code,descriptor:n}},D=i(async({argument:e,cwd:a,logger:t,options:r})=>({code:(await h({argument:e,cwd:a,env:r.env,logger:t,push:r.push===!0,tag:r.tag})).code}));export{D as execute,h as runContainersCommand};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{d
|
|
1
|
+
import{d}from"../packem_shared/command-DwC11Cwe.mjs";import{defaultSpawner as a}from"../packem_shared/createRecordingSpawner-DJlNacZ6.mjs";import{execArgsFor as m,detectPackageManager as i}from"@lunora/config";const t=(e,r)=>(r!==void 0&&e.push("--env",r),e),u=e=>{const r=t(["deployments","list"],e.env);return e.json&&r.push("--json"),r},l=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:t(["versions","view",e.versionId],e.env)};case"list":return{args:u(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=t(["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=t(["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}"`}}},v=async e=>{const{args:r,error:n}=l(e);if(n!==void 0||r===void 0)return e.logger.error(n??"deployments: nothing to run"),{code:1,descriptor:void 0,error:n};const s=e.cwd??process.cwd(),o=m(i(s),"wrangler",r),c={args:o.args,command:o.command,cwd:s};return e.logger.info(`${c.command} ${c.args.join(" ")}`),{code:(await(e.spawner??a)(c)).code,descriptor:c}},g=e=>e==="list"||e==="inspect"||e==="rollback"||e==="promote",h=d(({argument:e,cwd:r,logger:n,options:s})=>{const o=e[0];return g(o)?v({cwd:r,env:s.env,json:s.json===!0,logger:n,message:s.message,subcommand:o,versionId:e[1],yes:s.yes===!0}):(n.error(`deployments: unknown subcommand "${o??""}" — expected list | inspect | rollback | promote`),{code:1})});export{h as execute,v as runDeploymentsCommand};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{d}from"../packem_shared/command-DwC11Cwe.mjs";import{
|
|
1
|
+
import{d as s}from"../packem_shared/command-DwC11Cwe.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 @@
|
|
|
1
|
-
import{d as
|
|
1
|
+
import{existsSync as p,readFileSync as v,realpathSync as h}from"node:fs";import{join as u}from"node:path";import{isPlaceholderValue as w,DEV_VARS_FILE as g,parseDevVariableEntries as k,discoverSchemaInfo as x,inferLunoraBindings as b}from"@lunora/config";import{findWranglerFile as y,readWranglerJsonc as $,validateWranglerConfig as S,collectExportGaps as _}from"@lunora/config/cloudflare";import{i as A,m as N,c as R}from"../packem_shared/vectorize-metadata-dXpl2_Ar.mjs";import{r as L,d as E}from"../packem_shared/admin-token-VdUnvnKW.mjs";import{d as I}from"../packem_shared/command-DwC11Cwe.mjs";import{v as j,i as D,p as O,l as V}from"../packem_shared/output-format-DfogXx0p.mjs";import{i as C}from"../packem_shared/path-containment-CgxYZggb.mjs";const F=o=>{const e=o.trim();if(e==="")return!0;const n=e.toLowerCase();return n.includes("replace")||n.startsWith("<")&&n.endsWith(">")},P=o=>{const e=y(o);if(e===void 0)return{parsed:void 0,path:void 0};const{parsed:n}=$(e);return{parsed:n,path:e}},W=(o,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(o===void 0){n.push({code:"wrangler-unparseable",fix:`Check ${e} is valid JSONC.`,level:"fail",message:`Could not parse ${e}.`});return}const t=S(o).errors.find(r=>r.includes("SHARD"));t===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:t})},M=(o,e)=>{const{info:n}=x(o,"lunora");for(const a of n?.vectorMetadata??[]){const t=N(a.kind);if(t===void 0){e.push({code:"vector-metadata-unfilterable",fix:"Filter on a string, number or boolean column, or drop it from `metadata`.",level:"warn",message:`vector index "${a.index}" declares metadata "${a.property}", whose type Vectorize cannot filter on.`});continue}e.push({code:"vector-metadata-index-required",fix:`wrangler ${R({index:a.index,property:a.property,type:t}).join(" ")}`,level:"info",message:`vector index "${a.index}" filters on metadata "${a.property}" — that needs a Vectorize metadata index (\`lunora deploy\` creates it).`})}},T=(o,e)=>{if(o===void 0)return;const n=(o.d1_databases??[]).filter(Boolean);for(const a of n){const t=typeof a.database_id=="string"?a.database_id:"";if(F(t)){const r=typeof a.binding=="string"&&a.binding.length>0?a.binding:"<unnamed>";e.push({code:"d1-placeholder-id",fix:"Run `wrangler d1 create <name>` and paste the returned database_id into wrangler.jsonc.",level:"fail",message:`D1 binding "${r}" has a placeholder database_id ("${t||"<empty>"}").`})}}},z=(o,e)=>{if(o===void 0)return;const n=(o.send_email??[]).filter(Boolean);for(const a of n){const t=typeof a.destination_address=="string"?a.destination_address:"";if(t!==""&&w(t)){const r=typeof a.name=="string"&&a.name.length>0?a.name:"send_email";e.push({code:"email-destination-placeholder",fix:"Set destination_address to a verified Cloudflare Email Routing address.",level:"warn",message:`send_email binding "${r}" has a placeholder destination_address ("${t}").`})}}},B=(o,e)=>{const n=u(o,g);if(!p(n))return;let a;try{a=v(n,"utf8")}catch{return}const t=k(a).filter(r=>A(r.key)&&w(r.value)).map(r=>r.key);t.length>0&&e.push({code:"dev-vars-missing-secret",fix:"Run `lunora dev` to auto-generate secrets, or fill them in by hand.",level:"warn",message:`${g} has unfilled secret value(s): ${t.join(", ")}.`})},J=(o,e)=>{const{source:n}=L({cwd:o});n===void 0?e.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."}):e.push({code:"admin-token-set",level:"pass",message:`LUNORA_ADMIN_TOKEN is set (${E(n)}).`})},K=async(o,e)=>{let n;try{n=await b({projectRoot:o})}catch{return}const a=_(n),t=[...n.containers.map(r=>({...r,kind:"container"})),...n.workflows.map(r=>({...r,kind:"workflow"})),...n.agents.map(r=>({...r,kind:"agent"}))];for(const r of t.filter(i=>i.exported))e.push({code:"declared-export-ok",level:"pass",message:`${r.kind} "${r.exportName}" is exported by the worker entry.`});for(const r of a)e.push({code:"declared-export-missing",fix:`Add \`export * from "./lunora/_generated/${r.module}"\` to your worker entry (or re-run \`vis generate lunora-${r.kind}\`).`,level:"fail",message:`${r.kind} "${r.exportName}" is declared but ${r.className} is not exported by the worker entry.`})},U=/^[\^~><= ]+/u,G=/^(?<core>\d+\.\d+\.\d+)(?:-(?<channel>[a-z]+)\.(?<counter>\d+))?$/u,H=o=>{const e=o.replace(U,"").trim(),n=G.exec(e);if(!n?.groups)return;const{channel:a,core:t,counter:r}=n.groups;return{channel:a??"",core:t??"",counter:r===void 0?void 0:Number.parseInt(r,10),raw:e}},q=(o,e)=>{const n=u(o,"package.json");if(!p(n))return;let a;try{a=JSON.parse(v(n,"utf8"))}catch{return}const t={...a.devDependencies,...a.dependencies},r=[];for(const[s,c]of Object.entries(t)){if(s!=="lunorash"&&!s.startsWith("@lunora/"))continue;const m=H(c);m&&r.push({name:s,version:m})}if(r.length<2)return;const i=s=>s.map(c=>`${c.name}@${c.version.raw}`).join(", "),l=new Set(r.map(s=>s.version.core)),f=new Set(r.map(s=>s.version.channel));if(l.size>1){e.push({code:"version-skew-cores",fix:'Run `pnpm update "@lunora/*" lunorash` (or `npm`/`yarn` equivalent) so every Lunora package moves to the same release.',level:"warn",message:`Lunora packages span ${String(l.size)} different versions: ${i(r)}.`});return}if(f.size>1){e.push({code:"version-skew-channels",fix:"Pick one channel (all stable, or all alpha/beta) and update the odd package out.",level:"warn",message:`Lunora packages mix release channels (${[...f].map(s=>s===""?"stable":s).join(" + ")}): ${i(r)}.`});return}const d=r.map(s=>s.version.counter).filter(s=>s!==void 0);if(d.length>1){const s=Math.min(...d),c=Math.max(...d);e.push({code:"version-counter-spread",level:"info",message:d.length===r.length&&s===c?`Lunora packages are all at ${[...f][0]??""}.${String(c)}.`:`Lunora pre-release counters span ${String(s)}–${String(c)}: ${i(r)}.`})}},X=[u("@lunora","cli"),"lunorash"],Q=(o,e,n)=>{if(e===void 0)return;const a=[];for(const r of X){const i=u(o,"node_modules",r);if(p(i))try{a.push(h(i))}catch{}}if(a.length===0)return;let t;try{t=h(e)}catch{return}a.some(r=>C(r,t))||n.push({code:"cli-shadowed",fix:"Run the project's own CLI: `pnpm exec lunora …` (or `npx lunora …`).",level:"warn",message:`the running lunora (${t}) is not the project's own install (${a.join(", ")}).`})},Y=async o=>{const e=o.cwd??process.cwd(),n=[],{parsed:a,path:t}=P(e);W(a,t,n),T(a,n),z(a,n),B(e,n),J(e,n),q(e,n),M(e,n),Q(e,o.executablePath??process.argv[1],n),await K(e,n);const r={fail:0,info:0,pass:0,warn:0};for(const l of n)r[l.level]+=1;const i=r.fail>0?1:0;return{code:i,findings:n,ok:i===0,summary:r}},Z={fail:"FAIL",info:"INFO",pass:"PASS",warn:"WARN"},ee=(o,e)=>{e.info("lunora doctor — project preflight");for(const t of o.findings){const r=`[${Z[t.level]}] ${t.message}`;t.level==="fail"?e.error(r):t.level==="warn"?e.warn(r):e.info(r),t.fix!==void 0&&t.level!=="pass"&&e.info(` fix: ${t.fix}`)}const{fail:n,warn:a}=o.summary;n>0?e.error(`${String(n)} failure(s), ${String(a)} warning(s).`):a>0?e.warn(`0 failures, ${String(a)} warning(s).`):e.success("all checks passed.")},ne=async o=>{const e=j("doctor",o.format);if(e!==void 0)return o.logger.error(e),{code:1,findings:[],ok:!1,summary:{fail:0,info:0,pass:0,warn:0}};const n=V(o.format,o.logger),a=await Y({...o});return ee(a,n),D(o.format)&&O(a),a},ue=I(async({cwd:o,logger:e,options:n})=>({code:(await ne({cwd:o,format:n.format,logger:e})).code}));export{ue as execute,Y as runDoctor,ne as runDoctorCommand};
|