@lunora/cli 1.0.0-alpha.248 → 1.0.0-alpha.249
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 +189 -34
- package/dist/index.d.ts +189 -34
- package/dist/index.mjs +1 -1
- package/dist/packem_chunks/dispatch.mjs +1 -0
- package/dist/packem_chunks/handler.mjs +1 -1
- package/dist/packem_chunks/handler10.mjs +1 -3
- package/dist/packem_chunks/handler11.mjs +2 -2
- package/dist/packem_chunks/handler12.mjs +1 -1
- 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 +2 -2
- package/dist/packem_chunks/handler17.mjs +1 -1
- package/dist/packem_chunks/handler18.mjs +1 -1
- package/dist/packem_chunks/handler19.mjs +7 -7
- package/dist/packem_chunks/handler2.mjs +1 -2
- package/dist/packem_chunks/handler20.mjs +1 -1
- package/dist/packem_chunks/handler21.mjs +1 -1
- package/dist/packem_chunks/handler22.mjs +3 -3
- package/dist/packem_chunks/handler23.mjs +1 -1
- package/dist/packem_chunks/handler24.mjs +2 -2
- package/dist/packem_chunks/handler25.mjs +15 -15
- package/dist/packem_chunks/handler26.mjs +8 -8
- package/dist/packem_chunks/handler3.mjs +1 -1
- 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 -3
- package/dist/packem_chunks/handler8.mjs +1 -1
- package/dist/packem_chunks/handler9.mjs +1 -1
- package/dist/packem_chunks/planDevCommand.mjs +6 -6
- package/dist/packem_chunks/runCodegenCommand.mjs +4 -4
- package/dist/packem_chunks/runDeployCommand.mjs +3 -3
- package/dist/packem_chunks/runInitCommand.mjs +52 -52
- package/dist/packem_chunks/runResetCommand.mjs +1 -1
- package/dist/packem_chunks/runRpcCommand.mjs +1 -1
- package/dist/packem_shared/COMMANDS-DEcogfwP.mjs +1 -0
- package/dist/packem_shared/DEFAULT_IMPORT_BATCH_SIZE-BgMPHEoe.mjs +1 -0
- package/dist/packem_shared/EXIT_CODE-08cwt3MK.mjs +1 -0
- package/dist/packem_shared/cli-CSnnYlA3.mjs +2 -0
- package/dist/packem_shared/command-Mmxzxyr5.mjs +1 -0
- package/dist/packem_shared/commands-Dr7KeeZ9.mjs +13 -0
- package/dist/packem_shared/createRecordingSpawner-sS7LEN7x.mjs +1 -0
- package/dist/packem_shared/import-D7qdpSmJ.mjs +12 -0
- package/dist/packem_shared/{prompt-cancelled-C8Sj7OqI.mjs → prompt-cancelled-BvsNxg_Q.mjs} +1 -1
- package/dist/packem_shared/render-lunora-error--4tmM6mt.mjs +3 -0
- package/dist/packem_shared/{resolve-B9ReA3FV.mjs → resolve-ZDra033Q.mjs} +2 -2
- package/dist/packem_shared/{resolve-target-BRvw8Pf7.mjs → resolve-target-C_ZloTvd.mjs} +1 -1
- package/dist/packem_shared/runAddCommand-M8Z6aCaL.mjs +1 -0
- package/dist/packem_shared/runExportCommand-LEwEr8p0.mjs +5 -0
- package/dist/packem_shared/runMigrateGenerateCommand-BMS_KnVC.mjs +11 -0
- package/dist/packem_shared/{storage-B0ixDDxG.mjs → storage-BEbcFWu4.mjs} +1 -1
- package/dist/packem_shared/{tui-prompts-DzYd2fL3.mjs → tui-prompts-B3YwUhGw.mjs} +1 -1
- package/dist/packem_shared/{wrangler-secrets-CCdt0mUl.mjs → wrangler-secrets-C9lJnd5N.mjs} +1 -1
- package/package.json +11 -11
- package/skills/lunora/SKILL.md +58 -0
- package/skills/lunora-functions/SKILL.md +42 -0
- package/skills/lunora-performance-audit/SKILL.md +37 -1
- package/skills/lunora-realtime/SKILL.md +15 -9
- package/dist/packem_chunks/runMigrateGenerateCommand.mjs +0 -11
- package/dist/packem_shared/COMMANDS-Z-YcPyYn.mjs +0 -1
- package/dist/packem_shared/DEFAULT_IMPORT_BATCH_SIZE-BMH-ZXl5.mjs +0 -1
- package/dist/packem_shared/cli-CbScYTbi.mjs +0 -3
- package/dist/packem_shared/command-CrAs0XG_.mjs +0 -1
- package/dist/packem_shared/commands-I18aR_DJ.mjs +0 -15
- package/dist/packem_shared/createRecordingSpawner-DJlNacZ6.mjs +0 -1
- package/dist/packem_shared/import-Dqd1MOOv.mjs +0 -12
- package/dist/packem_shared/output-format-B91O3X28.mjs +0 -2
- package/dist/packem_shared/runAddCommand-BXea8slz.mjs +0 -1
- package/dist/packem_shared/runExportCommand-Dq-SpjAe.mjs +0 -5
|
@@ -1,7 +1,7 @@
|
|
|
1
|
-
import{writeFileSync as
|
|
2
|
-
`)},
|
|
3
|
-
`)},
|
|
4
|
-
`)}const
|
|
5
|
-
`);
|
|
6
|
-
`)},I=new Date(0).toISOString(),m=(e,r)=>
|
|
7
|
-
`,"utf8"),s.written=c}return s.belowMinScore=
|
|
1
|
+
import{writeFileSync as h,existsSync as S,readFileSync as p}from"node:fs";import{isAbsolute as v,join as w}from"node:path";import{byCodepoint as b,scoreAdvisor as y,parseAdvisorMap as x,compareToBaseline as j}from"@lunora/advisor";import{runCodegen as A}from"@lunora/codegen";import{d as M}from"../packem_shared/command-Mmxzxyr5.mjs";import{EXIT_CODE as D}from"../packem_shared/EXIT_CODE-08cwt3MK.mjs";import{D as u}from"../packem_shared/cli-CSnnYlA3.mjs";const l={clean:"·",exempt:"–",failing:"✗",warned:"!"},d=(e,r)=>e.length>=r?e:e+" ".repeat(r-e.length),E=e=>`${e.id} (${e.visibility} ${e.kind})`,f=e=>{let r=0;for(const n of e)r=Math.max(r,n.id.length);return r},g=(e,r)=>` ${d(String(e.score),3)} ${l[e.coverage]} ${d(e.id,r)} ${e.visibility} ${e.kind}`,R=e=>{if(!e.comparable)return[` baseline not comparable (${e.reason}) — regenerate it; this run cannot verify anything`];if(!e.regressed)return[` no regression against baseline (score ${e.scoreDelta>=0?"+":""}${String(e.scoreDelta)})`];const r=[` REGRESSED against baseline (score ${e.scoreDelta>=0?"+":""}${String(e.scoreDelta)})`];for(const n of e.dropped)r.push(` ${n.id}: ${String(n.before)} → ${String(n.after)}`);for(const n of e.newFailing)r.push(` ${n}: now failing`);for(const n of e.worsened)r.push(` ${n}: more findings than the baseline`);return e.projectRegressed&&r.push(" project: new schema/config rules fired"),r},F=(e,r)=>{const n=e.procedures.filter(i=>i.coverage!=="clean"&&i.coverage!=="exempt"),t=f(n),o=[`advisor health ${String(e.score)}/100 — ${e.grade}`,` ${String(e.summary.clean)} clean · ${String(e.summary.warned)} warned · ${String(e.summary.failing)} failing · ${String(e.summary.exempt)} exempt (${String(e.summary.procedures)} procedures, ${String(e.summary.rulesFired)} rules fired)`];return e.project.checks.length>0&&o.push("",` project ${String(e.project.score)}/100 — ${e.project.checks.map(i=>i.name).join(", ")}`),n.length>0&&o.push("",...n.map(i=>g(i,t)),""," run with --all for every procedure, or --entry <file#export> for one"),r!==void 0&&o.push("",...R(r)),o.join(`
|
|
2
|
+
`)},k=e=>e.coverage==="exempt"?[` exempt: ${e.exemptReason===void 0||e.exemptReason===""?"no reason given":e.exemptReason}`]:e.checks.map(r=>{const n=r.occurrences>1?`, ×${String(r.occurrences)}`:"";return` ${r.name} (−${String(r.weight)}${n})`}),T=e=>{const r=new Map;for(const n of e){const t=r.get(n.file);t===void 0?r.set(n.file,[n]):t.push(n)}return[...r].toSorted(([n],[t])=>b(n,t))},B=e=>{const r=f(e.procedures),n=[`advisor health ${String(e.score)}/100 — ${e.grade}`,"",` legend: ${l.clean} clean ${l.warned} warned ${l.failing} failing ${l.exempt} exempt`];for(const[t,o]of T(e.procedures)){n.push("",` ${t}`);for(const i of o)n.push(g(i,r),...k(i))}return n.join(`
|
|
3
|
+
`)},C=(e,r)=>{const n=e.procedures.find(o=>o.id===r);if(n===void 0){const o=e.procedures.slice(0,10).map(i=>` ${i.id}`);return[`no procedure ${r} in the map. Known ids:`,...o,e.procedures.length>10?" …":""].filter(Boolean).join(`
|
|
4
|
+
`)}const t=[`${E(n)} — ${String(n.score)}/100, ${n.coverage}`,` weight in the global mean: ${String(n.weight)}`];if(n.checks.length===0)return t.push(""," no rule fired"),t.join(`
|
|
5
|
+
`);t.push(""," rules fired:");for(const o of n.checks)t.push(` [${o.level}] ${o.name} −${String(o.weight)}${o.occurrences>1?` (×${String(o.occurrences)})`:""}`);return t.join(`
|
|
6
|
+
`)},I=new Date(0).toISOString(),m=(e,r)=>v(r)?r:w(e,r),L=e=>{if(e===void 0)return{value:void 0};if(e===null||e==="")return{error:"--min-score needs a value between 0 and 100"};const r=Number(e);return Number.isFinite(r)&&r>=0&&r<=100?{value:r}:{error:"--min-score must be a number between 0 and 100"}},N=(e,r,n)=>{const t=m(r,n===null||n===""?u:n);if(!S(t))return{error:`baseline not found at ${t} — generate one with \`lunora advisor\` and commit it`};const o=x(JSON.parse(p(t,"utf8")));return o===void 0?{error:`baseline at ${t} is malformed — regenerate it with \`lunora advisor\``}:{comparison:j(e,o)}},P=e=>`baseline is not comparable (${e}) — regenerate it; this run verified nothing`,_=(e,r,n)=>r.entry!==void 0?C(e,r.entry):r.all===!0?B(e):F(e,n),G=e=>{const r=e.cwd??process.cwd(),n=e.format==="json",{logger:t}=e,o=L(e.minScore);if("error"in o)return e.logger.error(o.error),{code:D.USAGE,error:o.error};const{advisorContext:i,advisories:$}=A({dryRun:!0,projectRoot:r}),a=y(i?.procedureProtections??[],$,{generatedAt:e.generatedAt??I}),s={map:a};if(e.baseline!==void 0){const c=N(a,r,e.baseline);if("error"in c)return e.logger.error(c.error),{...s,error:c.error};s.comparison=c.comparison,c.comparison.comparable||e.logger.error(P(c.comparison.reason))}if(e.write!==!1){const c=m(r,e.out??u);h(c,`${JSON.stringify(a,void 0,4)}
|
|
7
|
+
`,"utf8"),s.written=c}return s.belowMinScore=o.value!==void 0&&a.score<o.value,s.belowMinScore&&t.error(`advisor score ${String(a.score)} is below the required ${String(o.value)}`),n||(t.info(_(a,e,s.comparison)),s.written!==void 0&&t.success(`wrote ${s.written}`)),s},H=e=>e.error!==void 0||e.belowMinScore===!0?!0:e.comparison!==void 0&&(!e.comparison.comparable||e.comparison.regressed),z=M(({cwd:e,format:r,logger:n,options:t})=>{const o=G({all:t.all,baseline:t.baseline,cwd:e,entry:t.entry,format:r,logger:n,minScore:t.minScore,out:t.out,write:t.write});return{code:o.code??(H(o)?1:0),data:{belowMinScore:o.belowMinScore,comparison:o.comparison,map:o.map,written:o.written},error:o.error}});export{z as execute,G as runAdvisorCommand};
|
|
@@ -1,2 +1 @@
|
|
|
1
|
-
import{mkdtempSync as
|
|
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{mkdtempSync as p,rmSync as u,existsSync as m,readdirSync as $,statSync as g}from"node:fs";import{tmpdir as S}from"node:os";import{join as y,relative as w}from"node:path";import{d as z}from"../packem_shared/command-Mmxzxyr5.mjs";import{EXIT_CODE as B}from"../packem_shared/EXIT_CODE-08cwt3MK.mjs";import{defaultSpawner as F}from"../packem_shared/createRecordingSpawner-sS7LEN7x.mjs";import{execArgsFor as h,detectPackageManager as x}from"@lunora/config";const v=e=>{const t=[],n=o=>{for(const s of $(o)){const r=y(o,s),i=g(r);i.isDirectory()?n(r):i.isFile()&&t.push({path:w(e,r),sizeBytes:i.size})}};return n(e),t},l=e=>e<1024?`${String(e)} B`:e<1024*1024?`${(e/1024).toFixed(1)} KiB`:`${(e/(1024*1024)).toFixed(2)} MiB`,M=e=>{const t=v(e),n=t.toSorted((r,i)=>i.sizeBytes-r.sizeBytes),o=t.reduce((r,i)=>r+i.sizeBytes,0);return{generatedFiles:t.filter(r=>r.path.includes("_generated")),outdir:e,topModules:n.slice(0,10),totalBytes:o,totalFiles:t.length}},O=(e,t)=>{if(t.info(`outdir: ${e.outdir}`),t.info(`total: ${String(e.totalFiles)} files, ${l(e.totalBytes)}`),e.topModules.length>0){t.info(""),t.info("top modules by size:");for(const n of e.topModules)t.info(` ${l(n.sizeBytes).padStart(10," ")} ${n.path}`)}if(e.generatedFiles.length>0){t.info(""),t.info(`_generated/ files: ${String(e.generatedFiles.length)}`);for(const n of e.generatedFiles)t.info(` ${l(n.sizeBytes).padStart(10," ")} ${n.path}`)}},j=async e=>{const t=e.cwd??process.cwd(),n=e.format==="json",{logger:o}=e;let s,r,i=!1;if(e.inspectOnly)s=e.inspectOnly;else{s=p(y(S(),"lunora-analyze-")),i=!0;const a=h(x(t),"wrangler",["deploy","--dry-run","--outdir",s]);r={args:a.args,command:a.command,cwd:t,stdoutToStderr:n},o.info(`analyze: building via ${r.command} ${r.args.join(" ")}`);const d=await(e.spawner??F)(r);if(d.code!==0){const f=`analyze: wrangler dry-run failed (exit ${String(d.code)})`;return o.error(f),u(s,{force:!0,recursive:!0}),{code:d.code,descriptor:r,error:f,report:void 0}}}try{if(!m(s)){const c=`analyze: outdir not found at ${s}`;return o.error(c),{code:B.NOT_FOUND,descriptor:r,error:c,report:void 0}}const a=M(s);return n||O(a,o),{code:0,descriptor:r,report:a}}finally{if(i&&m(s))try{u(s,{force:!0,recursive:!0})}catch{}}},N=z(async({cwd:e,format:t,logger:n})=>{const o=await j({cwd:e,format:t,logger:n});return{code:o.code,data:o.report,error:o.error}});export{N as execute,j as runAnalyzeCommand};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{join as
|
|
1
|
+
import{join as c,resolve as l}from"node:path";import{p as u}from"../packem_shared/deploy-target-DCWwiuAe.mjs";import{d as m}from"../packem_shared/command-Mmxzxyr5.mjs";import{defaultSpawner as f}from"../packem_shared/createRecordingSpawner-sS7LEN7x.mjs";import{runDeployCommand as p}from"./runDeployCommand.mjs";import{readdirSync as w,readFileSync as y}from"node:fs";import{gzipSync as g}from"node:zlib";const b=e=>!e.endsWith(".map")&&e!=="bundle-meta.json"&&e!=="README.md",S=e=>{let a;try{a=w(e,{recursive:!0,withFileTypes:!0})}catch{return}let n=0,r=0,t=0;for(const i of a){if(!i.isFile()||!b(i.name))continue;const d=y(c(i.parentPath,i.name));n+=1,t+=d.byteLength,r+=g(d).byteLength}return n===0?void 0:{files:n,gzipBytes:r,rawBytes:t}},s=".lunora/build",v=async e=>f({...e,stdoutToStderr:!0}),o=e=>`${(e/1024).toFixed(1)} KiB`,D=async e=>{const a=e.outDir??s,n=e.format==="json",{logger:r}=e,t=await p({allowSchemaDrift:e.allowSchemaDrift,apiSpec:e.apiSpec,commandName:"build",cwd:e.cwd,dryRun:!0,emitBindings:e.emitBindings,format:void 0,interactive:n?!1:void 0,logger:r,outDir:a,spawner:e.spawner??(n?v:void 0),strictAdvisories:e.strictAdvisories,target:e.target});if(t.code!==0)return t;r.success(`build complete — bundle written to ${a}`);const i=S(l(e.cwd??process.cwd(),a));return i===void 0?r.warn(`could not weigh the bundle — nothing uploadable was found in ${a}`):r.info(`bundle: ${o(i.rawBytes)} raw, ${o(i.gzipBytes)} gzipped across ${String(i.files)} file(s) — Cloudflare's Worker size limit (3 MB Free, 10 MB Paid) applies to the gzipped number`),{...t,bundle:i}},M=m(async({cwd:e,format:a,logger:n,options:r})=>{const t=await D({allowSchemaDrift:r.allowSchemaDrift===!0,apiSpec:u(r.apiSpec),cwd:e,emitBindings:r.emitBindings,format:a,logger:n,outDir:r.outDir,strictAdvisories:r.strictAdvisories,target:r.target});return{code:t.code,data:{bundle:t.bundle,deployment:t.deployment,outDir:r.outDir??s,validation:t.validation},error:t.error}});export{M as execute,D as runBuildCommand};
|
|
@@ -1,3 +1,3 @@
|
|
|
1
|
-
import{writeFileSync as E,existsSync as w,cpSync as j,statSync as b,lstatSync as I,readdirSync as N,mkdirSync as D,readFileSync as M}from"node:fs";import{join as u,sep as x,relative as B,resolve as O,dirname as K}from"node:path";import{SDK_TARGETS as V,SDK_LANGUAGES as G,generateSdk as P,isTypedSchema as Q}from"@lunora/codegen";import{LunoraError as d}from"@lunora/errors";import{d as J}from"../packem_shared/command-
|
|
1
|
+
import{writeFileSync as E,existsSync as w,cpSync as j,statSync as b,lstatSync as I,readdirSync as N,mkdirSync as D,readFileSync as M}from"node:fs";import{join as u,sep as x,relative as B,resolve as O,dirname as K}from"node:path";import{SDK_TARGETS as V,SDK_LANGUAGES as G,generateSdk as P,isTypedSchema as Q}from"@lunora/codegen";import{LunoraError as d}from"@lunora/errors";import{d as J}from"../packem_shared/command-Mmxzxyr5.mjs";import{r as _,a as U,b as q,c as H,s as W}from"../packem_shared/resolve-ZDra033Q.mjs";const $="gh:anolilab/lunora/sdks",v="lunora-transport.json",X=/_test\.|Tests?\./u,k=t=>t.startsWith("test_")||X.test(t),A=(t,n="")=>N(t).toSorted((e,r)=>e.localeCompare(r)).flatMap(e=>{const r=u(t,e),a=n.length>0?`${n}/${e}`:e;return b(r).isDirectory()?A(r,a):[a]}),C=(t,n)=>{const e=I(n);if(e.isSymbolicLink())throw new d("INTERNAL",`refusing to vendor "${B(t,n)}" — it is a symlink, not a regular file`);if(e.isDirectory())for(const r of N(n))k(r)||C(t,u(n,r))},F=(t,n,e,r)=>{const a=u(t,e);if(!w(a))throw new d("NOT_FOUND",`transport is missing ${e}`);C(t,a);const s=u(n,r);return j(a,s,{filter:o=>!k(o.slice(o.lastIndexOf(x)+1)),force:!0,recursive:!0}),b(s).isDirectory()?A(s).map(o=>`${r}/${o}`):[r]},R=(t,n)=>n.vendor.every(e=>w(u(t,e.from))),z=async(t,n)=>{const{language:e,logger:r,outputDirectory:a,registryOptions:s,target:o}=n,{cleanup:f,directory:h}=await H(e,{...s,ref:t},$);try{if(!R(h,o)){r.warn(`${$}/${e} does not exist at ${t}.`);return}return{files:o.vendor.flatMap(c=>F(h,a,c.from,c.to)).toSorted((c,l)=>c.localeCompare(l)),ref:t,source:`${$}/${e}`,versionMatched:t===_()}}finally{f()}},Y=(t,n)=>{const{language:e,outputDirectory:r,target:a}=n,s=u(t,e);if(!w(s))throw new d("NOT_FOUND",`no transport at ${s} — --from must point at a directory of per-language transports (the repo's \`sdks/\`)`);if(!R(s,a)){const o=a.vendor.map(f=>f.from).join(", ");throw new d("NOT_FOUND",`${s} is not a ${e} transport — expected it to contain ${o}`)}return{files:a.vendor.flatMap(o=>F(s,r,o.from,o.to)).toSorted((o,f)=>o.localeCompare(f)),ref:"local",source:s,versionMatched:!1}},Z=async t=>{const{allowUnsafeSource:n,from:e,language:r,logger:a,outputDirectory:s,ref:o,source:f,target:h}=t;if(e!==void 0)return Y(e,{language:r,outputDirectory:s,target:h});const c={allowUnsafeSource:n,logger:a,names:[],source:f},l=async i=>z(await q(i,a),{language:r,logger:a,outputDirectory:s,registryOptions:c,target:h});if(o!==void 0&&o.length>0){const i=await l(o);if(i===void 0)throw new d("NOT_FOUND",`--ref ${o} carries no ${r} transport — pick a ref that does, or pass --from <dir> to copy a local one`);return i}const m=_(),g=await l(m).catch(i=>{const y=i instanceof Error?i.message.split(`
|
|
2
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
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,3 +1,3 @@
|
|
|
1
|
-
import
|
|
2
|
-
`,"utf8"),await
|
|
3
|
-
`,headers:{authorization:`Bearer ${r.token}`,"content-type":"application/json"},method:"PUT"});if(!u.ok){const s=await u.text().catch(()=>"<no body>");throw new h("INTERNAL",`backup: snapshot ${c.file} was written but its manifest was not (HTTP ${String(u.status)}): ${s}`)}},stage:async c=>{const n=await E(l(_(),"lunora-backup-"));return{path:l(n,p("",c)),release:async()=>w(n,{force:!0,recursive:!0})}}}},be=".lunora-backups",q="/_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 a=(e.now??(()=>new Date))().toISOString(),t=await r.stage(a);try{const o=await de({cwd:e.cwd,fetchImpl:e.fetchImpl,logger:e.logger,out:t.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(a),d=await j(t.path);await r.commit(i,t.path,d);const f={bytes:d.bytes,createdAt:a,file:i,id:a,rows:o.rows,sha256:d.sha256,tables:e.tables};return await r.record(f),e.logger.success(`backup created: ${i} (${o.rows.toString()} rows, ${d.bytes.toString()} bytes)`),{code:0,entry:f}}finally{await t.release().catch(o=>{e.logger.warn(`backup: could not clean up staging (${o instanceof Error?o.message:String(o)})`)})}},Te=async(e,r,a)=>{if(r?.sha256===void 0)return a.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 t=await j(e);if(t.sha256!==r.sha256)return a.error(`--verify: ${r.file} does not match its recorded checksum (expected ${r.sha256}, got ${t.sha256}) — nothing was imported`),{code:1};a.success(`verified ${r.file} against its recorded sha256`)},Ne=async(e,r)=>{const a=await r.list();if(a.length===0)return e.logger.info(`no backups found in ${r.label}`),{code:0};for(const t of a)e.logger.info(`${t.id} ${t.rows.toString()} rows ${t.bytes.toString()} bytes ${t.file}`);return{code:0}},Se=async(e,r)=>{const{target:a}=e;if(a===void 0||a.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(d=>d.id===a),i=await r.materialize(o,a);if(i===void 0)return e.logger.error(`backup not found: ${a}`),{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(d=>{e.logger.warn(`backup: could not clean up the downloaded snapshot (${d instanceof Error?d.message:String(d)})`)})}},Ee=e=>{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 r=$(e.url,e.logger,e.cwd);if(r===void 0)return;if(e.restore===!0&&Y({prod:e.prod,url:r})&&e.yes!==!0){e.logger.error(`pitr --restore restores data in place at ${r}, which is not local. Re-run with --yes to confirm.`);return}const{token:a}=v({cwd:e.cwd??process.cwd(),token:e.token,url:r});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 t=e.adminFetch??globalThis.fetch;if(typeof t!="function")throw new TypeError("no fetch implementation available — pass pitrFetch or run on Node >= 18");return{fetchImpl:t,requestUrl:`${r}${pe}`,token:a}},Ie=(e,r)=>{const a={};return e.at!==void 0&&(a.time=e.at),r&&e.bookmark!==void 0&&(a.bookmark=e.bookmark),r&&e.restart===!0&&(a.restart=!0),a},_e=async e=>{const r=Ee(e);if(r===void 0)return{code:1};const a=e.restore===!0,t=a?ve:ye,o=Ie(e,a),i=a?"restore":"bookmark";e.logger.info(`POST ${r.requestUrl} -> pitr ${i}${e.shard===void 0?"":` (shard "${e.shard}")`}`);const d=await r.fetchImpl(r.requestUrl,{body:JSON.stringify({args:o,functionPath:t,shardKey:e.shard}),headers:{authorization:`Bearer ${r.token}`,"content-type":"application/json"},method:"POST"});return await b(d,e.logger),{code:d.ok?0:1}},xe=(e,r)=>{if(e.bucket===void 0){if(e.prefix!==void 0){e.logger.error("--prefix applies only to an R2 destination — pass --bucket alongside it, or use --dir to point at a local directory.");return}return fe(l(r,e.dir??be))}if(e.dir!==void 0){e.logger.error("--dir applies only to a local destination and does not apply alongside --bucket — drop one.");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 a=$(e.url,e.logger,e.cwd);if(a===void 0)return;const{token:t}=v({cwd:r,token:e.token,url:a});if(!t){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:a,bucket:e.bucket==="default"?void 0:e.bucket,fetchImpl:o,token:t},logger:e.logger,prefix:e.prefix})},L=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 a=$(e.url,e.logger,e.cwd);if(a===void 0)return;const{token:t}=v({cwd:e.cwd??process.cwd(),token:e.token,url:a});if(!t){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:a,fetchImpl:o,token:t}},C=(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 a of r.wouldDelete)e.logger.info(` ${A(a)}`)},Re=async e=>{const r=L(e);if(r===void 0)return{code:1};const a=await r.fetchImpl(`${r.baseUrl}${q}`,{headers:{authorization:`Bearer ${r.token}`},method:"GET"});if(!a.ok)return await b(a,e.logger),{code:1};const t=await a.json();return t.cron===void 0?(e.logger.info("no scheduled backup is configured (`backupCron`), so retention would delete nothing"),{code:0,preview:t}):t.keep<=0?(e.logger.info(`retention is off for cron "${t.cron}" (\`backupRetain\` unset) — every snapshot under ${t.prefix} is kept`),{code:0,preview:t}):(C(e,t),t.eligible===0&&e.logger.info(`no snapshot under ${t.prefix} was written by this cron, so retention has nothing of its own to remove`),{code:0,preview:t})},Pe=(e,r)=>{e.logger.success(`deleted ${r.deleted.length.toString()} backup(s)`);for(const a of r.deleted)e.logger.info(` ${A(a)}`);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=L(e);if(r===void 0)return{code:1};const a=await r.fetchImpl(`${r.baseUrl}${q}`,{headers:{authorization:`Bearer ${r.token}`},method:"GET"});if(!a.ok)return await b(a,e.logger),{code:1};const t=await a.json();if(t.keep<=0||t.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:t};if(t.wouldDelete.length===0)return e.logger.info(`nothing to prune — ${t.eligible.toString()} snapshot(s) under ${t.prefix} and retention keeps the newest ${t.keep.toString()}`),{code:0,preview:t};if(C(e,t),e.yes!==!0){const d=e.confirm??(K()?z:void 0);if(d===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:t};if(!await d(`delete ${t.wouldDelete.length.toString()} backup(s)? This cannot be undone. [y/N] `))return e.logger.info("nothing was deleted"),{code:0,preview:t}}const o=await r.fetchImpl(`${r.baseUrl}${ke}`,{body:JSON.stringify({confirm:t.wouldDelete}),headers:{authorization:`Bearer ${r.token}`,"content-type":"application/json"},method:"POST"});if(!o.ok)return await b(o,e.logger),{code:1,preview:t};const i=await o.json();return Pe(e,i),{code:i.failed.length>0?1:0,deleted:i.deleted,preview:t}},Ae=async e=>{const r=e.cwd??process.cwd();try{if(e.subcommand==="pitr")return await _e(e);if(e.subcommand==="retention")return await Re(e);if(e.subcommand==="prune")return await Oe(e);const a=xe(e,r);return a===void 0?{code:1}:e.subcommand==="create"?await $e(e,a):e.subcommand==="list"?await Ne(e,a):await Se(e,a)}catch(a){return e.logger.error(a instanceof Error?a.message:String(a)),{code:1}}},Be=e=>e==="create"||e==="list"||e==="pitr"||e==="prune"||e==="restore"||e==="retention",Ze=X(({argument:e,cwd:r,logger:a,options:t})=>{const o=e[0];return Be(o)?Ae({at:t.at,bookmark:t.bookmark,bucket:t.bucket,cwd:r,dir:t.dir,logger:a,prefix:t.prefix,prod:t.prod===!0,restart:t.restart===!0,restore:t.restore===!0,shard:t.shard,subcommand:o,tables:t.tables,target:e[1],token:t.token,url:Q({cwd:r,prod:t.prod===!0,url:t.url}),verify:t.verify===!0,yes:t.yes===!0}):(a.error(`backup: unknown subcommand "${o??""}" — expected create | list | restore | retention | prune | pitr`),{code:1})});export{Ze as execute,Ae as runBackupCommand};
|
|
1
|
+
import H,{join as m,resolve as N}from"node:path";import{isInteractive as z,promptYesNo as J}from"@lunora/config";import{backupObjectKey as v,isBackupManifestEntry as B,normalizeBackupPrefix as W,BACKUP_KEY_PREFIX as Y,backupManifestKey as X,isBackupManifestKey as Q,backupObjectKeyOfManifest as D}from"@lunora/runtime";import{r as E,t as V}from"../packem_shared/admin-token-VdUnvnKW.mjs";import{r as T}from"../packem_shared/admin-url-BhF5ufg1.mjs";import{d as Z}from"../packem_shared/command-Mmxzxyr5.mjs";import{EXIT_CODE as u,isRefusal as p,exitCodeForStatus as k}from"../packem_shared/EXIT_CODE-08cwt3MK.mjs";import{a as ee}from"../packem_shared/resolve-target-C_ZloTvd.mjs";import{runExportCommand as re}from"../packem_shared/runExportCommand-LEwEr8p0.mjs";import{b as te,l as ae,M as I,u as oe,r as ne}from"../packem_shared/import-D7qdpSmJ.mjs";import{readAndLogBody as y}from"./runRpcCommand.mjs";import{randomUUID as G,createHash as ie}from"node:crypto";import{existsSync as A,createReadStream as se,createWriteStream as ce}from"node:fs";import{mkdir as de,rm as b,rename as j,readFile as C,writeFile as ue,realpath as U,mkdtemp as _}from"node:fs/promises";import{LunoraError as w}from"@lunora/errors";import{i as x}from"../packem_shared/path-containment-CgxYZggb.mjs";import{tmpdir as R}from"node:os";import{Readable as le}from"node:stream";import{pipeline as fe}from"node:stream/promises";const S="manifest.json",q=async e=>{const t=ie("sha256");let r=0;for await(const a of se(e)){const o=a;r+=o.byteLength,t.update(o)}return{bytes:r,sha256:t.digest("hex")}},O=async e=>{const t=m(e,S);if(!A(t))return[];let r;try{r=JSON.parse(await C(t,"utf8"))}catch(a){const o=a instanceof Error?a.message:String(a);throw new w("INTERNAL",`backup: ${t} exists but is not valid JSON (${o}) — refusing to overwrite it; fix or remove it manually`,{cause:a})}if(!Array.isArray(r))throw new TypeError(`backup: ${t} exists but is not a JSON array — refusing to overwrite it; fix or remove it manually`);return r.filter(a=>B(a))},me=async(e,t)=>{const r=m(e,`${S}.${G()}.tmp`);try{await ue(r,`${JSON.stringify(t,void 0,2)}
|
|
2
|
+
`,"utf8"),await j(r,m(e,S))}catch(a){throw await b(r,{force:!0}),a}},ge=async(e,t)=>{const r=N(e),a=N(r,t.file),o=()=>{throw new w("INTERNAL",`backup: entry ${t.id} points outside ${r} (${t.file}) — refusing to read it`)};if(x(r,a)||o(),!!A(a))return x(await U(r),await U(a))||o(),a},he=e=>{const t=r=>v("",r);return{commit:async(r,a)=>{await j(a,m(e,r))},label:e,list:async()=>O(e),locate:t,materialize:async(r,a)=>{const o=i=>i===void 0?void 0:{path:i,release:()=>Promise.resolve()};return o(r===void 0?A(a)?a:void 0:await ge(e,r))},record:async r=>{const a=await O(e);a.push(r),await me(e,a)},stage:async r=>{await de(e,{recursive:!0});const a=m(e,`${t(r)}.${G()}.partial`);return{path:a,release:()=>b(a,{force:!0})}}}},we="/_lunora/admin/storage/object",be="/_lunora/admin/storage",P=8,ke=(e,t=H)=>{const r=t.basename(e);return r===""||r==="."||r===".."?"snapshot.ndjson":r},ye=e=>{const{context:t,logger:r}=e,a=W(e.prefix??Y),o=`bucket ${t.bucket??"(default)"} under ${a}`,i=te(t),n=c=>`${t.baseUrl}${we}?key=${encodeURIComponent(c)}${i}`,f=async c=>{const s=await t.fetchImpl(n(c),{headers:{authorization:`Bearer ${t.token}`},method:"GET"});if(!s.ok){const l=await s.text().catch(()=>"<no body>");throw new w("INTERNAL",`backup: could not read ${c} (HTTP ${String(s.status)}): ${l}`)}return s.text()},K=async c=>{try{const s=JSON.parse(await f(c));if(B(s))return s;r.warn(`backup: ignoring ${c} — not a backup manifest`)}catch(s){r.warn(`backup: ignoring ${c} — ${s instanceof Error?s.message:String(s)}`)}};return{commit:async(c,s,l)=>{if(l.bytes>I)throw new w("INTERNAL",`backup: the snapshot is ${String(l.bytes)} bytes, above the ${String(I)}-byte limit for a checksum-verified upload — nothing was written. Narrow it with \`--tables\`, or write it to a directory with \`--dir\` and move the file yourself (\`wrangler r2 object put\`).`);const d=await C(s);await oe(t,c,d,{contentType:"application/x-ndjson",id:c,sha256:l.sha256,size:l.bytes},r)},label:o,list:async()=>{const s=(await ae(t,a)).map(d=>d.key).filter(d=>Q(d)),l=[];for(let d=0;d<s.length;d+=P){const g=await Promise.all(s.slice(d,d+P).map(async h=>K(h)));l.push(...g.filter(h=>h!==void 0))}return l.toSorted((d,g)=>d.id.localeCompare(g.id))},locate:c=>v(a,c),materialize:async(c,s)=>{const l=c?.file??s,d=await t.fetchImpl(n(l),{headers:{authorization:`Bearer ${t.token}`},method:"GET"});if(d.status===404)return;if(!d.ok||d.body===null){const $=await d.text().catch(()=>"<no body>");throw new w("INTERNAL",`backup: could not download ${l} (HTTP ${String(d.status)}): ${$}`)}const g=await _(m(R(),"lunora-backup-")),h=m(g,ke(l));try{await fe(le.from(d.body),ce(h))}catch($){throw await b(g,{force:!0,recursive:!0}),$}return{path:h,release:async()=>b(g,{force:!0,recursive:!0})}},record:async c=>{const s=X(c.file),l=await t.fetchImpl(`${t.baseUrl}${be}?key=${encodeURIComponent(s)}${i}`,{body:`${JSON.stringify(c,void 0,2)}
|
|
3
|
+
`,headers:{authorization:`Bearer ${t.token}`,"content-type":"application/json"},method:"PUT"});if(!l.ok){const d=await l.text().catch(()=>"<no body>");throw new w("INTERNAL",`backup: snapshot ${c.file} was written but its manifest was not (HTTP ${String(l.status)}): ${d}`)}},stage:async c=>{const s=await _(m(R(),"lunora-backup-"));return{path:m(s,v("",c)),release:async()=>b(s,{force:!0,recursive:!0})}}}},pe=".lunora-backups",F="/_lunora/admin/backup/retention",$e="/_lunora/admin/backup/prune",ve="/_lunora/admin/pitr",Se="__lunora_admin__:getPitrBookmark",Ee="__lunora_admin__:pitrRestore",Te=async(e,t)=>{const r=(e.now??(()=>new Date))().toISOString(),a=await t.stage(r);try{const o=await re({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=t.locate(r),n=await q(a.path);await t.commit(i,a.path,n);const f={bytes:n.bytes,createdAt:r,file:i,id:r,rows:o.rows,sha256:n.sha256,tables:e.tables};return await t.record(f),e.logger.success(`backup created: ${i} (${o.rows.toString()} rows, ${n.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)})`)})}},Ae=async(e,t,r)=>{if(t?.sha256===void 0)return r.error(t===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 ${t.id} carries no recorded checksum — it was taken by a release before checksums existed`),{code:u.USAGE};const a=await q(e);if(a.sha256!==t.sha256)return r.error(`--verify: ${t.file} does not match its recorded checksum (expected ${t.sha256}, got ${a.sha256}) — nothing was imported`),{code:1};r.success(`verified ${t.file} against its recorded sha256`)},Ne=async(e,t)=>{const r=await t.list();if(r.length===0)return e.logger.info(`no backups found in ${t.label}`),{code:0,entries:[]};for(const a of r)e.logger.info(`${a.id} ${a.rows.toString()} rows ${a.bytes.toString()} bytes ${a.file}`);return{code:0,entries:r}},Ie=async(e,t)=>{const{target:r}=e;if(r===void 0||r.length===0)return e.logger.error("restore requires a backup id or file path. Usage: lunora backup restore <id|file>"),{code:u.USAGE};const o=(await t.list()).find(n=>n.id===r),i=await t.materialize(o,r);if(i===void 0)return e.logger.error(`backup not found: ${r}`),{code:u.NOT_FOUND};try{if(e.verify===!0){const f=await Ae(i.path,o,e.logger);if(f!==void 0)return f}const n=await ne({cwd:e.cwd,fetchImpl:e.fetchImpl,file:i.path,logger:e.logger,prod:e.prod,token:e.token,url:e.url,yes:e.yes});return{code:n.code,entry:o,restored:n.inserted}}finally{await i.release().catch(n=>{e.logger.warn(`backup: could not clean up the downloaded snapshot (${n instanceof Error?n.message:String(n)})`)})}},Ue=e=>{if(e.prod&&e.url===void 0)return e.logger.error("--prod requires an explicit --url (refusing to target the implicit localhost worker)"),{refused:u.USAGE};if(e.restore===!0&&e.at===void 0&&e.bookmark===void 0)return e.logger.error("pitr --restore requires --at <time> or --bookmark <bookmark>"),{refused:u.USAGE};const t=T(e.url,e.logger,e.cwd);if(t===void 0)return{refused:u.USAGE};if(e.restore===!0&&V({prod:e.prod,url:t})&&e.yes!==!0)return e.logger.error(`pitr --restore restores data in place at ${t}, which is not local. Re-run with --yes to confirm.`),{refused:u.USAGE};const{token:r}=E({cwd:e.cwd??process.cwd(),token:e.token,url:t});if(!r)return e.logger.error("admin token required — pass --token, set LUNORA_ADMIN_TOKEN, or add it to .dev.vars (local targets only)"),{refused:u.AUTH};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}${ve}`,token:r}},_e=(e,t)=>{const r={};return e.at!==void 0&&(r.time=e.at),t&&e.bookmark!==void 0&&(r.bookmark=e.bookmark),t&&e.restart===!0&&(r.restart=!0),r},xe=async e=>{const t=Ue(e);if(p(t))return{code:t.refused};const r=e.restore===!0,a=r?Ee:Se,o=_e(e,r),i=r?"restore":"bookmark";e.logger.info(`POST ${t.requestUrl} -> pitr ${i}${e.shard===void 0?"":` (shard "${e.shard}")`}`);const n=await t.fetchImpl(t.requestUrl,{body:JSON.stringify({args:o,functionPath:a,shardKey:e.shard}),headers:{authorization:`Bearer ${t.token}`,"content-type":"application/json"},method:"POST"});return{body:await y(n,e.logger),code:n.ok?0:k(n.status)}},Re=(e,t)=>{if(e.bucket===void 0)return e.prefix!==void 0?(e.logger.error("--prefix applies only to an R2 destination — pass --bucket alongside it, or use --dir to point at a local directory."),{refused:u.USAGE}):he(m(t,e.dir??pe));if(e.dir!==void 0)return e.logger.error("--dir applies only to a local destination and does not apply alongside --bucket — drop one."),{refused:u.USAGE};if(e.prod===!0&&e.url===void 0)return e.logger.error("--prod requires an explicit --url (refusing to target the implicit localhost worker)"),{refused:u.USAGE};const r=T(e.url,e.logger,e.cwd);if(r===void 0)return{refused:u.USAGE};const{token:a}=E({cwd:t,token:e.token,url:r});if(!a)return e.logger.error("admin token required — pass --token, set LUNORA_ADMIN_TOKEN, or add it to .dev.vars (local targets only)"),{refused:u.AUTH};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 ye({context:{baseUrl:r,bucket:e.bucket==="default"?void 0:e.bucket,fetchImpl:o,token:a},logger:e.logger,prefix:e.prefix})},L=e=>{const t=[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(t.length>0)return e.logger.error(`${t.join(" / ")} ${t.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.`),{refused:u.USAGE};if(e.prod===!0&&e.url===void 0)return e.logger.error("--prod requires an explicit --url (refusing to target the implicit localhost worker)"),{refused:u.USAGE};const r=T(e.url,e.logger,e.cwd);if(r===void 0)return{refused:u.USAGE};const{token:a}=E({cwd:e.cwd??process.cwd(),token:e.token,url:r});if(!a)return e.logger.error("admin token required — pass --token, set LUNORA_ADMIN_TOKEN, or add it to .dev.vars (local targets only)"),{refused:u.AUTH};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:r,fetchImpl:o,token:a}},M=(e,t)=>{e.logger.info(`backup retention would keep the newest ${t.keep.toString()} of ${t.eligible.toString()} under ${t.prefix} and delete ${t.wouldDelete.length.toString()}`);for(const r of t.wouldDelete)e.logger.info(` ${D(r)}`)},Oe=async e=>{const t=L(e);if(p(t))return{code:t.refused};const r=await t.fetchImpl(`${t.baseUrl}${F}`,{headers:{authorization:`Bearer ${t.token}`},method:"GET"});if(!r.ok)return await y(r,e.logger),{code:k(r.status)};const a=await r.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})},Pe=(e,t)=>{e.logger.success(`deleted ${t.deleted.length.toString()} backup(s)`);for(const r of t.deleted)e.logger.info(` ${D(r)}`);t.failed.length>0&&e.logger.warn(`${t.failed.length.toString()} could not be removed — the snapshot may be gone with its manifest left behind; run again to retry`),t.ignored>0&&e.logger.info(`${t.ignored.toString()} were already gone by the time the delete ran`),t.remaining>0&&e.logger.info(`${t.remaining.toString()} more are past the window — run \`lunora backup prune\` again`)},Be=async e=>{const t=L(e);if(p(t))return{code:t.refused};const r=await t.fetchImpl(`${t.baseUrl}${F}`,{headers:{authorization:`Bearer ${t.token}`},method:"GET"});if(!r.ok)return await y(r,e.logger),{code:k(r.status)};const a=await r.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:u.USAGE,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 n=e.confirm??(z()?J:void 0);if(n===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:u.USAGE,preview:a};if(!await n(`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 t.fetchImpl(`${t.baseUrl}${$e}`,{body:JSON.stringify({confirm:a.wouldDelete}),headers:{authorization:`Bearer ${t.token}`,"content-type":"application/json"},method:"POST"});if(!o.ok)return await y(o,e.logger),{code:k(o.status),preview:a};const i=await o.json();return Pe(e,i),{code:i.failed.length>0?1:0,deleted:i.deleted,preview:a}},De=async(e,t)=>{try{if(e.subcommand==="pitr")return await xe(e);if(e.subcommand==="retention")return await Oe(e);if(e.subcommand==="prune")return await Be(e);const r=Re(e,t);return p(r)?{code:r.refused}:e.subcommand==="create"?await Te(e,r):e.subcommand==="list"?await Ne(e,r):await Ie(e,r)}catch(r){return e.logger.error(r instanceof Error?r.message:String(r)),{code:1}}},Ge=async e=>{const t=e.cwd??process.cwd(),r=await De(e,t);return{...r,data:{subcommand:e.subcommand,...r.entries===void 0?{}:{entries:r.entries},...r.entry===void 0?{}:{entry:r.entry},...r.restored===void 0?{}:{restored:r.restored},...r.preview===void 0?{}:{preview:r.preview},...r.deleted===void 0?{}:{deleted:r.deleted},...r.body===void 0?{}:{result:r.body}}}},je=e=>e==="create"||e==="list"||e==="pitr"||e==="prune"||e==="restore"||e==="retention",or=Z(async({argument:e,cwd:t,format:r,logger:a,options:o})=>{const i=e[0];if(!je(i)){const f=`backup: unknown subcommand "${i??""}" — expected create | list | restore | retention | prune | pitr`;return a.error(f),{code:u.USAGE,error:f}}const n=await Ge({at:o.at,bookmark:o.bookmark,bucket:o.bucket,cwd:t,dir:o.dir,format:r,logger:a,prefix:o.prefix,prod:o.prod===!0,restart:o.restart===!0,restore:o.restore===!0,shard:o.shard,subcommand:i,tables:o.tables,target:e[1],token:o.token,url:ee({cwd:t,prod:o.prod===!0,url:o.url}),verify:o.verify===!0,yes:o.yes===!0});return{code:n.code,data:n.data,error:n.error}});export{or as execute,Ge as runBackupCommand};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{readdirSync as
|
|
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-Mmxzxyr5.mjs";import{EXIT_CODE as u}from"../packem_shared/EXIT_CODE-08cwt3MK.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,2 +1,2 @@
|
|
|
1
|
-
import{readLinkedProject as
|
|
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 ${
|
|
1
|
+
import{readLinkedProject as v,resolveDeployDriver as h,execArgsFor as b,detectPackageManager as y}from"@lunora/config";import{d as w}from"../packem_shared/command-Mmxzxyr5.mjs";import{EXIT_CODE as l}from"../packem_shared/EXIT_CODE-08cwt3MK.mjs";import{defaultSpawner as L}from"../packem_shared/createRecordingSpawner-sS7LEN7x.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 n=e.trim();if(f.test(n))return Number(n);const a=Date.parse(n);if(Number.isNaN(a))throw new TypeError(`logs: invalid ${t} "${e}" — pass epoch-millis or an ISO 8601 date`);return a},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 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:a}=n,r=n.seen,s=Array.isArray(r)?r.filter(i=>typeof i=="string"):void 0;return s!==void 0&&s.length>0?{seen:s,ts:a}:{ts:a}},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={},n=u(e.since,"--since");n!==void 0&&(t.sinceTs=n);const a=u(e.until,"--until");a!==void 0&&(t.untilTs=a);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(),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,a=t.R2_SQL_TOKEN,r=t.R2_SQL_BUCKET,s=[];if((n===void 0||n.length===0)&&s.push("R2_SQL_ACCOUNT_ID"),(a===void 0||a.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:l.USAGE,error:"not configured"};let i;try{i=p(e)}catch(o){return e.logger.error(o instanceof Error?o.message:String(o)),{code:l.USAGE,error:"invalid option"}}const d=S({accountId:n,apiToken:a,bucket:r,fetch:e.fetch}),c=await _(d,{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 ${C(c.nextCursor)} for the next page`),{code:0,rows:c.rows}},N=async e=>{const t=e.cwd??process.cwd(),n=e.env??v(t)?.env,a=h(e.target);if(a.toolchain===void 0){const c=`logs: deploy target "${a.id}" has no command-line toolchain`;return e.logger.error(c),{code:l.USAGE,descriptor:void 0,error:c}}const r=a.toolchain.tail({environment:n,format:e.format,search:e.search,status:e.status,temporary:e.temporary,worker:e.worker}),s=b(y(t),r.tool,r.args),i={args:s.args,command:s.command,cwd:t};return e.logger.info(`tailing logs via ${i.command} ${i.args.join(" ")}`),{code:(await(e.spawner??L)(i)).code,delegated:!0,descriptor:i}},U=w(async({argument:e,cwd:t,format:n,logger:a,options:r})=>{if(r.durable===!0){const s=await $({cursor:r.cursor,functionPrefix:r.functionPrefix,level:r.level,limit:r.limit,logger:a,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:n,logger:a,search:r.search,status:r.status,target:r.target,temporary:r.temporary===!0,worker:e[0]})});export{U as execute,N as runLogsCommand};
|
|
@@ -1,13 +1,13 @@
|
|
|
1
|
-
import{existsSync as
|
|
1
|
+
import{existsSync as O,readFileSync as I}from"node:fs";import{writeFile as M,mkdir as U}from"node:fs/promises";import{join as E}from"@visulima/path";import{d as B}from"../packem_shared/command-Mmxzxyr5.mjs";import{EXIT_CODE as L}from"../packem_shared/EXIT_CODE-08cwt3MK.mjs";import{createRequire as F}from"node:module";import{LunoraError as N}from"@lunora/errors";import{addArgsFor as Y,detectPackageManager as q,parseSchema as P,applyAdditiveEdit as H}from"@lunora/config";const K=/^\//,j=(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}`}},T=(e,t,n)=>{const r=F(E(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
2
|
|
|
3
3
|
Install it in your project:
|
|
4
4
|
|
|
5
|
-
${
|
|
5
|
+
${j(n,t)}`)}return r(e)},G=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.`)},J=e=>{try{const t=new URL(e).pathname.replace(K,"");return t===""?void 0:decodeURIComponent(t)}catch{return}},Q=async(e,t,n,r=process.cwd())=>{if(t==="postgres"){const m=T("pg","pg",r).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",r).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}},b=new Set(["_creationTime","_id"]),W={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()"},X={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"?W:X)[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}},x=/^[A-Z_$][\w$]*$/i,z=/[^\dA-Z]+(.)?/gi,Z=/^\d+/,V=/[^\w-]/g,ee=/[\u003C\u003E\u002F\u2028\u2029]/g,ne={"/":String.raw`\u002F`,"\u2028":String.raw`\u2028`,"\u2029":String.raw`\u2029`,"<":String.raw`\u003C`,">":String.raw`\u003E`},f=e=>JSON.stringify(e).replaceAll(ee,t=>ne[t]??t),S=e=>x.test(e)?e:f(e),te=e=>x.test(e)?`.${e}`:`[${f(e)}]`,C=e=>e.replaceAll("*/",String.raw`*\/`),re=e=>{const t=e.replaceAll(V,"_");return t===""?"table":t},ae=e=>{const n=e.replaceAll(z,(r,s)=>s?.toUpperCase()??"").replace(Z,"");return n===""?"table":`${n.charAt(0).toLowerCase()}${n.slice(1)}`},D=e=>e.columns.filter(t=>!b.has(t.name)),se=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=>!b.has(n))},k=(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}),oe=(e,t,n,r)=>{const s=[];for(const o of e.columns){if(b.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=k(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: \`${C(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=>!b.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=>!b.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
6
|
${s.join(`
|
|
7
7
|
`)}
|
|
8
8
|
})
|
|
9
9
|
${a.join(`
|
|
10
|
-
`)},`},
|
|
10
|
+
`)},`},ie=(e,t,n)=>{const r=new Set(e.tables.map(a=>a.name)),s=e.tables.map(a=>oe(a,e.dialect,r,n)).join(`
|
|
11
11
|
`);return`/**
|
|
12
12
|
* Generated by \`lunora introspect\` from an existing ${e.dialect==="postgres"?"Postgres":"MySQL"} database.
|
|
13
13
|
*
|
|
@@ -22,8 +22,8 @@ import { defineSchema, defineTable, v } from "${t.serverImport}";
|
|
|
22
22
|
export default defineSchema({
|
|
23
23
|
${s}
|
|
24
24
|
});
|
|
25
|
-
`},
|
|
26
|
-
* Generated by \`lunora introspect\` for the \`${
|
|
25
|
+
`},ce=(e,t,n,r=new Set([e.name]),s=[])=>{const a=ae(e.name),o=se(e),i=new Map(D(e).map(l=>[l.name,l])),c=o.map(l=>{const p=i.get(l);if(p===void 0)return;const v=k({...p,nullable:!1},r,e.name,[]),{expression:d,known:A}=w(v,t);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${te(e.name)}`;return`/**
|
|
26
|
+
* Generated by \`lunora introspect\` for the \`${C(e.name)}\` table — a
|
|
27
27
|
* starting point you own and edit.
|
|
28
28
|
*
|
|
29
29
|
* Both procedures are RPC-only. Add \`.expose({ rest: true })\` once you've decided
|
|
@@ -50,26 +50,26 @@ ${c.join(`
|
|
|
50
50
|
export const list = c.query.input(${a}List.args).query(({ args, ctx }) => ${u}.findMany(${a}List.toQueryArgs(args)));
|
|
51
51
|
|
|
52
52
|
export const get = c.query.input({ id: v.id(${f(e.name)}) }).query(({ args, ctx }) => ${u}.get(args.id));
|
|
53
|
-
`},
|
|
53
|
+
`},me=(e,t)=>{const n=[],r=new Set(e.tables.map(a=>a.name)),s=[{contents:ie(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(D(o).length===0){n.push(`${o.name}: no usable columns — procedure module skipped.`);continue}const i=re(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:ce(o,e.dialect,t,r,n),path:`${i}.ts`})}}return{files:s,warnings:n}},y=/^[A-Z_$][\w$]*$/i,le=e=>e.startsWith("v.optional(")&&e.endsWith(")")?e.slice(11,-1):e,ue=(e,t,n)=>{const r=[],s=new Set(t?.columns.map(a=>a.name));for(const a of e.columns){if(b.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);r.push({column:a.name,kind:"addOptionalColumn",table:e.name,validator:le(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},de=(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=>!b.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}r.push({fields:o,kind:"addIndex",name:a.name,table:e.name,...a.unique?{unique:!0}:{}})}}return r},pe=(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(!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&&r.push({global:{backend:"hyperdrive"},kind:"addTable",table:i.name}),r.push(...ue(i,c,{dialect:n,present:o,warnings:s}),...de(i,c,s))}return{edits:r,warnings:s}},ge=(e,t,n)=>{const r=P(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=pe(t,r.tables,n),a=[...s.warnings];let o=e,i=0;for(const c of s.edits){const m=H(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):""},fe=`
|
|
54
54
|
SELECT c.table_name, c.column_name, c.is_nullable, c.data_type, c.udt_name
|
|
55
55
|
FROM information_schema.columns c
|
|
56
56
|
JOIN information_schema.tables t
|
|
57
57
|
ON t.table_schema = c.table_schema AND t.table_name = c.table_name
|
|
58
58
|
WHERE c.table_schema = $1 AND t.table_type = 'BASE TABLE'
|
|
59
|
-
ORDER BY c.table_name, c.ordinal_position`,
|
|
59
|
+
ORDER BY c.table_name, c.ordinal_position`,ve=`
|
|
60
60
|
SELECT tc.table_name, kcu.column_name
|
|
61
61
|
FROM information_schema.table_constraints tc
|
|
62
62
|
JOIN information_schema.key_column_usage kcu
|
|
63
63
|
ON kcu.constraint_name = tc.constraint_name AND kcu.table_schema = tc.table_schema
|
|
64
64
|
WHERE tc.table_schema = $1 AND tc.constraint_type = 'PRIMARY KEY'
|
|
65
|
-
ORDER BY tc.table_name, kcu.ordinal_position`,
|
|
65
|
+
ORDER BY tc.table_name, kcu.ordinal_position`,he=`
|
|
66
66
|
SELECT tc.table_name, kcu.column_name, ccu.table_name AS foreign_table, ccu.column_name AS foreign_column
|
|
67
67
|
FROM information_schema.table_constraints tc
|
|
68
68
|
JOIN information_schema.key_column_usage kcu
|
|
69
69
|
ON kcu.constraint_name = tc.constraint_name AND kcu.table_schema = tc.table_schema
|
|
70
70
|
JOIN information_schema.constraint_column_usage ccu
|
|
71
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'`,
|
|
72
|
+
WHERE tc.table_schema = $1 AND tc.constraint_type = 'FOREIGN KEY'`,be=`
|
|
73
73
|
SELECT t.relname AS table_name, i.relname AS index_name, ix.indisunique AS is_unique, a.attname AS column_name
|
|
74
74
|
FROM pg_class t
|
|
75
75
|
JOIN pg_index ix ON t.oid = ix.indrelid
|
|
@@ -78,22 +78,22 @@ export const get = c.query.input({ id: v.id(${f(e.name)}) }).query(({ args, ctx
|
|
|
78
78
|
CROSS JOIN LATERAL unnest(ix.indkey) WITH ORDINALITY AS k(attnum, ord)
|
|
79
79
|
JOIN pg_attribute a ON a.attrelid = t.oid AND a.attnum = k.attnum
|
|
80
80
|
WHERE n.nspname = $1 AND t.relkind = 'r' AND NOT ix.indisprimary
|
|
81
|
-
ORDER BY t.relname, i.relname, k.ord`,
|
|
81
|
+
ORDER BY t.relname, i.relname, k.ord`,Ee=`
|
|
82
82
|
SELECT c.TABLE_NAME, c.COLUMN_NAME, c.IS_NULLABLE, c.DATA_TYPE
|
|
83
83
|
FROM information_schema.COLUMNS c
|
|
84
84
|
JOIN information_schema.TABLES t
|
|
85
85
|
ON t.TABLE_SCHEMA = c.TABLE_SCHEMA AND t.TABLE_NAME = c.TABLE_NAME
|
|
86
86
|
WHERE c.TABLE_SCHEMA = ? AND t.TABLE_TYPE = 'BASE TABLE'
|
|
87
|
-
ORDER BY c.TABLE_NAME, c.ORDINAL_POSITION`,
|
|
87
|
+
ORDER BY c.TABLE_NAME, c.ORDINAL_POSITION`,_e=`
|
|
88
88
|
SELECT TABLE_NAME, COLUMN_NAME
|
|
89
89
|
FROM information_schema.KEY_COLUMN_USAGE
|
|
90
90
|
WHERE TABLE_SCHEMA = ? AND CONSTRAINT_NAME = 'PRIMARY'
|
|
91
|
-
ORDER BY TABLE_NAME, ORDINAL_POSITION`,
|
|
91
|
+
ORDER BY TABLE_NAME, ORDINAL_POSITION`,ye=`
|
|
92
92
|
SELECT TABLE_NAME, COLUMN_NAME, REFERENCED_TABLE_NAME AS foreign_table, REFERENCED_COLUMN_NAME AS foreign_column
|
|
93
93
|
FROM information_schema.KEY_COLUMN_USAGE
|
|
94
|
-
WHERE TABLE_SCHEMA = ? AND REFERENCED_TABLE_NAME IS NOT NULL`,
|
|
94
|
+
WHERE TABLE_SCHEMA = ? AND REFERENCED_TABLE_NAME IS NOT NULL`,Ae=`
|
|
95
95
|
SELECT TABLE_NAME, INDEX_NAME AS index_name, NON_UNIQUE, COLUMN_NAME
|
|
96
96
|
FROM information_schema.STATISTICS
|
|
97
97
|
WHERE TABLE_SCHEMA = ? AND INDEX_NAME <> 'PRIMARY'
|
|
98
|
-
ORDER BY TABLE_NAME, INDEX_NAME, SEQ_IN_INDEX`,
|
|
99
|
-
`).length)} lines)`),!1):(await
|
|
98
|
+
ORDER BY TABLE_NAME, INDEX_NAME, SEQ_IN_INDEX`,_=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},Se=(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}},Ne=(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}))},we=async(e,t,n)=>{const r=t==="postgres",[s,a,o,i]=await Promise.all([e(r?fe:Ee,[n]),e(r?ve:_e,[n]),e(r?he:ye,[n]),e(r?be:Ae,[n])]),c=_(a),m=_(o),u=_(i),l=[];for(const[p,v]of _(s)){const d=new Map((m.get(p)??[]).map(h=>[g(h,"column_name"),{column:g(h,"foreign_column"),table:g(h,"foreign_table")}])),A=v.map(h=>{const R=g(h,"column_name"),$=d.get(R);return{...Se(h,t),name:R,nullable:g(h,"is_nullable").toUpperCase()==="YES",...$===void 0?{}:{references:$}}});l.push({columns:A,indexes:Ne(u.get(p)??[],t),name:p,primaryKey:(c.get(p)??[]).map(h=>g(h,"column_name"))})}return l.sort((p,v)=>p.name.localeCompare(v.name)),{dialect:t,tables:l}},Re=e=>{try{const t=JSON.parse(I(E(e,"package.json"),"utf8"));return t.dependencies?.lunorash===void 0&&t.devDependencies?.lunorash===void 0?"@lunora/server":"lunorash/server"}catch{return"@lunora/server"}},$e=async(e,t,n)=>{const r=E(t,e.path);return O(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 U(t,{recursive:!0}),await M(r,e.contents,"utf8"),n.logger.info(`wrote lunora/${e.path}`),!0)},Le=(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))},Te=async(e,t,n,r)=>{const s=ge(I(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 M(e,s.text,"utf8"),r.logger.info(`merged ${String(s.applied)} addition(s) into lunora/schema.ts`),!0)},Oe=async e=>{const t=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?G(e.url):e.dialect??"postgres",r=e.connection??await Q(e.url,n,e.schema,t);let s;try{s=await we(r.execute,n,r.schema)}finally{e.connection===void 0&&await r.close()}const a=Le(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}=me({...s,tables:a},{procedures:e.procedures!==!1,serverImport:Re(t)}),c=E(t,"lunora"),m=[],u=E(c,"schema.ts"),l=O(u)&&e.force!==!0,p=l?o.filter(d=>d.path!=="schema.ts"):o;l&&await Te(u,{...s,tables:a},n,e)&&m.push("schema.ts");for(const d of p)await $e(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}},Fe=B(async({cwd:e,format:t,logger:n,options:r})=>{const s=await Oe({cwd:e,dryRun:r.dryRun===!0,force:r.force===!0,format:t,logger:n,procedures:r.procedures!==!1,schema:r.schema,tables:r.tables===void 0?void 0:r.tables.split(",").map(a=>a.trim()),url:r.url??process.env.DATABASE_URL});return{code:s.code,data:s.dialect===void 0?void 0:{dialect:s.dialect,dryRun:r.dryRun===!0,tables:s.tables??[],written:s.written},error:s.error}});export{Fe as execute,Re as resolveServerImport,Oe as runIntrospectCommand};
|
|
@@ -1,10 +1,10 @@
|
|
|
1
|
-
import{V as
|
|
2
|
-
`),{action:"created",path:o};const{errors:c,value:i}=
|
|
3
|
-
${JSON.stringify({[e.key]:{[r.name]:o}},void 0,4)}`),{action:"printed",path:a})}const l=
|
|
1
|
+
import{V as R}from"../packem_shared/cli-CSnnYlA3.mjs";import{d as G}from"../packem_shared/command-Mmxzxyr5.mjs";import{EXIT_CODE as d}from"../packem_shared/EXIT_CODE-08cwt3MK.mjs";import{existsSync as f,readFileSync as h,mkdirSync as J,realpathSync as W,statSync as V,writeFileSync as z,chmodSync as H,renameSync as K,unlinkSync as q}from"node:fs";import{homedir as w}from"node:os";import{findWranglerFile as X}from"@lunora/config/cloudflare";import{join as s,dirname as B,relative as Z}from"@visulima/path";import{stringify as Q}from"smol-toml";import{parse as Y,modify as ee,applyEdits as re}from"jsonc-parser";import{detectPackageManager as te,execArgsFor as ne,readLiveDevServerState as S,DEV_STATE_DIR as oe}from"@lunora/config";import{resolveAdminToken as ae}from"@lunora/config/studio-host";import{connectLocalStdio as le}from"@lunora/mcp";import{resolve as y}from"node:path";import{i as ce}from"../packem_shared/path-containment-CgxYZggb.mjs";const m=e=>({args:[...e.args],command:e.command,...e.env===void 0?{}:{env:e.env}}),b=e=>e.transport==="http"?{type:"http",url:e.url}:m(e),se=e=>e.transport==="http"?{httpUrl:e.url}:m(e),ie=e=>e.transport==="http"?{serverUrl:e.url}:m(e),de=e=>({args:["-y","mcp-remote",e],command:"npx"}),ue=e=>e.transport==="http"?de(e.url):m(e),fe=e=>e.transport==="http"?{url:e.url}:m(e),me=e=>e.transport==="http"?{enabled:!0,type:"remote",url:e.url}:{command:[e.command,...e.args],enabled:!0,type:"local",...e.env===void 0?{}:{environment:e.env}},pe=e=>e.transport==="http"?{disabled:!1,type:"streamableHttp",url:e.url}:{disabled:!1,...m(e)},ge=({home:e,platform:r})=>{if(r==="darwin")return{global:s(e,"Library","Application Support","Claude","claude_desktop_config.json")};if(r==="win32"){const t=process.env.APPDATA;return t===void 0||t===""?{}:{global:s(t,"Claude","claude_desktop_config.json")}}return r==="linux"?{global:s(e,".config","Claude","claude_desktop_config.json")}:{}},ve=(e,r)=>Q({mcp_servers:{[e]:r.transport==="http"?{url:r.url}:{args:[...r.args],command:r.command,...r.env===void 0?{}:{env:r.env}}}}),v=[{buildEntry:b,paths:({projectRoot:e})=>({project:s(e,".mcp.json")}),format:"json",id:"claude-code",key:"mcpServers",label:"Claude Code"},{buildEntry:b,paths:({home:e,projectRoot:r})=>({global:s(e,".cursor","mcp.json"),project:s(r,".cursor","mcp.json")}),format:"json",id:"cursor",key:"mcpServers",label:"Cursor"},{buildEntry:b,paths:({projectRoot:e})=>({project:s(e,".vscode","mcp.json")}),format:"json",id:"vscode",key:"servers",label:"VS Code (GitHub Copilot)"},{buildEntry:se,paths:({home:e,projectRoot:r})=>({global:s(e,".gemini","settings.json"),project:s(r,".gemini","settings.json")}),format:"json",id:"gemini",key:"mcpServers",label:"Gemini CLI"},{buildEntry:ue,paths:ge,format:"json",id:"claude-desktop",key:"mcpServers",label:"Claude Desktop"},{buildEntry:ie,paths:({home:e})=>({global:s(e,".codeium","windsurf","mcp_config.json")}),format:"json",id:"windsurf",key:"mcpServers",label:"Windsurf"},{buildEntry:me,paths:({home:e,projectRoot:r})=>({global:s(e,".config","opencode","opencode.json"),project:s(r,"opencode.json")}),format:"json",id:"opencode",key:"mcp",label:"OpenCode"},{buildEntry:pe,paths:({home:e})=>({global:s(e,".cline","mcp.json")}),format:"json",id:"cline",key:"mcpServers",label:"Cline"},{buildEntry:fe,paths:({home:e})=>({global:s(e,".config","zed","settings.json")}),format:"json",id:"zed",key:"context_servers",label:"Zed"},{paths:({home:e,projectRoot:r})=>({global:s(e,".codex","config.toml"),project:s(r,".codex","config.toml")}),format:"manual",id:"codex",label:"Codex CLI",renderSnippet:ve}],x=v.map(e=>e.id),he=e=>v.find(r=>r.id===e.toLowerCase()),M=(e,r)=>{let t=e,n;try{t=W(e),n=V(t).mode}catch{}const a=`${t}.lunora-${Math.random().toString(36).slice(2,10)}.tmp`;try{z(a,r,"utf8"),n!==void 0&&H(a,n),K(a,t)}catch(o){try{q(a)}catch{}throw o}},ye={formattingOptions:{insertSpaces:!0,tabSize:4}},k=e=>{const r=[],t=Y(e,r,{allowTrailingComma:!0});return{errors:r,value:t}},g=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),E=(e,r,t)=>{if(!g(e))return;const n=e[r];return g(n)?n[t]:void 0},L=e=>{if(!f(e.path))return"absent";let r;try{r=h(e.path,"utf8")}catch{return"invalid"}if(r.trim().length===0)return"absent";const{errors:t,value:n}=k(r);return t.length>0||!g(n)?"invalid":E(n,e.key,e.name)===void 0?"absent":"present"},be=e=>L(e)==="present",U=(e,r,t,n,a)=>{try{const o=ee(e,[t,n],a,ye);o.length>0&&M(r,re(e,o));return}catch(o){return o instanceof Error?o.message:String(o)}},Se=e=>{const{entry:r,force:t=!1,key:n,name:a,path:o}=e,l=f(o)?h(o,"utf8"):"";if(l.trim().length===0)return J(B(o),{recursive:!0}),M(o,`${JSON.stringify({[n]:{[a]:r}},void 0,4)}
|
|
2
|
+
`),{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
4
|
|
|
5
|
-
${e.renderSnippet(r.name,r.spec)}`),{action:"printed",path:n}},
|
|
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
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=
|
|
8
|
-
`;const t=!
|
|
9
|
-
`},
|
|
10
|
-
`),{code:1,deployment:void 0}}const a=
|
|
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{d as
|
|
1
|
+
import{d as h}from"../packem_shared/command-Mmxzxyr5.mjs";import{i as p}from"../packem_shared/docker-DpVxvYpL.mjs";import{EXIT_CODE as m}from"../packem_shared/EXIT_CODE-08cwt3MK.mjs";import{defaultSpawner as S}from"../packem_shared/createRecordingSpawner-sS7LEN7x.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 +1 @@
|
|
|
1
|
-
import{d}from"../packem_shared/command-
|
|
1
|
+
import{d as i}from"../packem_shared/command-Mmxzxyr5.mjs";import{EXIT_CODE as c}from"../packem_shared/EXIT_CODE-08cwt3MK.mjs";import{defaultSpawner as l}from"../packem_shared/createRecordingSpawner-sS7LEN7x.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};
|