@lunora/cli 1.0.0-alpha.46 → 1.0.0-alpha.461
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/LICENSE.md +33 -0
- package/README.md +3 -1
- package/dist/bin.mjs +3 -10
- package/dist/cli.d.mts +31 -0
- package/dist/cli.d.ts +31 -0
- package/dist/cli.mjs +1 -0
- package/dist/index.d.mts +1096 -386
- package/dist/index.d.ts +1096 -386
- package/dist/index.mjs +1 -19
- package/dist/packem_chunks/cli.mjs +2 -0
- package/dist/packem_chunks/dispatch.mjs +1 -0
- package/dist/packem_chunks/handler.mjs +17 -158
- package/dist/packem_chunks/handler10.mjs +1 -16
- package/dist/packem_chunks/handler11.mjs +1 -22
- package/dist/packem_chunks/handler12.mjs +1 -192
- package/dist/packem_chunks/handler13.mjs +1 -131
- package/dist/packem_chunks/handler14.mjs +1 -65
- package/dist/packem_chunks/handler15.mjs +3 -58
- package/dist/packem_chunks/handler16.mjs +1 -80
- package/dist/packem_chunks/handler17.mjs +1 -43
- package/dist/packem_chunks/handler18.mjs +1 -105
- package/dist/packem_chunks/handler19.mjs +1 -170
- package/dist/packem_chunks/handler2.mjs +1 -114
- package/dist/packem_chunks/handler20.mjs +7 -94
- package/dist/packem_chunks/handler21.mjs +2 -94
- package/dist/packem_chunks/handler22.mjs +1 -0
- package/dist/packem_chunks/handler23.mjs +3 -0
- package/dist/packem_chunks/handler24.mjs +3 -0
- package/dist/packem_chunks/handler25.mjs +1 -0
- package/dist/packem_chunks/handler26.mjs +2 -0
- package/dist/packem_chunks/handler27.mjs +99 -0
- package/dist/packem_chunks/handler28.mjs +15 -0
- package/dist/packem_chunks/handler29.mjs +1 -0
- package/dist/packem_chunks/handler3.mjs +1 -204
- package/dist/packem_chunks/handler30.mjs +1 -0
- package/dist/packem_chunks/handler4.mjs +1 -33
- package/dist/packem_chunks/handler5.mjs +3 -49
- package/dist/packem_chunks/handler6.mjs +1 -91
- package/dist/packem_chunks/handler7.mjs +1 -42
- package/dist/packem_chunks/handler8.mjs +1 -174
- package/dist/packem_chunks/handler9.mjs +2 -315
- package/dist/packem_chunks/runCodegenCommand.mjs +4 -52
- package/dist/packem_chunks/runDevCommand.mjs +6 -0
- package/dist/packem_chunks/runInitCommand.mjs +212 -1432
- package/dist/packem_chunks/runResetCommand.mjs +1 -41
- package/dist/packem_chunks/runRpcCommand.mjs +1 -68
- package/dist/packem_shared/DEFAULT_IMPORT_BATCH_SIZE-5xxKz-zB.mjs +1 -0
- package/dist/packem_shared/EXIT_CODE-DVjUgIaG.mjs +1 -0
- package/dist/packem_shared/admin-token-VdUnvnKW.mjs +1 -0
- package/dist/packem_shared/admin-url-DJB8P6Jh.mjs +1 -0
- package/dist/packem_shared/api-spec-lYyq4vL6.mjs +1 -0
- package/dist/packem_shared/binding-manifest-file-CQ1eQYy1.mjs +2 -0
- package/dist/packem_shared/buildRegistryIndex-Dc8D8AR6.mjs +1 -0
- package/dist/packem_shared/cap-error-body-YBKO32BF.mjs +1 -0
- package/dist/packem_shared/catalog-CahzmDLV.mjs +1 -0
- package/dist/packem_shared/cli-manifest-DoQ_3bzs.mjs +1 -0
- package/dist/packem_shared/cloudflare-credentials-BVmZnDZk.mjs +1 -0
- package/dist/packem_shared/codegen-error-AmH54ofi.mjs +3 -0
- package/dist/packem_shared/command-B6vu47iR.mjs +1 -0
- package/dist/packem_shared/commands-DC3ZX1yk.mjs +13 -0
- package/dist/packem_shared/createLogger-4TujevyB.mjs +2 -0
- package/dist/packem_shared/createRecordingSpawner-01ZngIwK.mjs +1 -0
- package/dist/packem_shared/deploy-target-resolve-BTCW1Iv4.mjs +1 -0
- package/dist/packem_shared/diffSnapshots-htqNZT8Q.mjs +7 -0
- package/dist/packem_shared/docker-DpVxvYpL.mjs +1 -0
- package/dist/packem_shared/free-port-DjbFhaaT.mjs +1 -0
- package/dist/packem_shared/health-probe-Bw9JFfIy.mjs +1 -0
- package/dist/packem_shared/import-DoAUdyfU.mjs +13 -0
- package/dist/packem_shared/index-oHZBGBwB.mjs +1 -0
- package/dist/packem_shared/insertSchemaExtension-CbTH3lCQ.mjs +10 -0
- package/dist/packem_shared/lint-ignore-report-DKZagpqk.mjs +2 -0
- package/dist/packem_shared/mcp-config-file-GR1Y_CVw.mjs +2 -0
- package/dist/packem_shared/open-url-EnKy--w-.mjs +1 -0
- package/dist/packem_shared/output-format-DWe_tkTR.mjs +2 -0
- package/dist/packem_shared/parseManifest-CwPTKdtS.mjs +1 -0
- package/dist/packem_shared/path-containment-CgxYZggb.mjs +1 -0
- package/dist/packem_shared/plan-BH4ZfiFs.mjs +5 -0
- package/dist/packem_shared/planDevCommand-I8-NB_CN.mjs +1 -0
- package/dist/packem_shared/platform-diagnostics-Cn2g6Jh-.mjs +4 -0
- package/dist/packem_shared/prompt-cancelled-BvsNxg_Q.mjs +1 -0
- package/dist/packem_shared/render-lunora-error-DUo0pA61.mjs +2 -0
- package/dist/packem_shared/resolve-Bdc9KEUv.mjs +5 -0
- package/dist/packem_shared/resolve-target-C_ZloTvd.mjs +1 -0
- package/dist/packem_shared/runAddCommand-CTblwN9O.mjs +1 -0
- package/dist/packem_shared/runDeployCommand-Tgy9tGRV.mjs +1 -0
- package/dist/packem_shared/runExportCommand-DiMCQ-Il.mjs +5 -0
- package/dist/packem_shared/runMigrateGenerateCommand-Bd2W9t1k.mjs +11 -0
- package/dist/packem_shared/schemaIrToSnapshot-BHuNOfgs.mjs +1 -0
- package/dist/packem_shared/shared-D-zCOmgY.mjs +1 -0
- package/dist/packem_shared/storage-BLLoZRJa.mjs +1 -0
- package/dist/packem_shared/tui-prompts-B3YwUhGw.mjs +4 -0
- package/dist/packem_shared/variables-CPYyJtsL.mjs +1 -0
- package/dist/packem_shared/vectorize-metadata-BVSF8z2h.mjs +2 -0
- package/dist/packem_shared/wrangler-name-Dsk5K1f-.mjs +1 -0
- package/dist/packem_shared/wrangler-secrets-DlSlWvRH.mjs +1 -0
- package/package.json +44 -19
- package/skills/README.md +36 -17
- package/skills/lunora/SKILL.md +158 -65
- package/skills/lunora-cloudflare-audit/SKILL.md +164 -0
- package/skills/lunora-create-package/SKILL.md +97 -84
- package/skills/lunora-deploy/SKILL.md +178 -105
- package/skills/lunora-functions/SKILL.md +367 -60
- package/skills/lunora-migration-helper/SKILL.md +168 -137
- package/skills/lunora-performance-audit/SKILL.md +137 -95
- package/skills/lunora-quickstart/SKILL.md +136 -136
- package/skills/lunora-realtime/SKILL.md +217 -97
- package/skills/lunora-setup-auth/SKILL.md +203 -101
- package/skills/lunora-setup-hyperdrive/SKILL.md +138 -109
- package/skills/lunora-setup-hyperdrive-global/SKILL.md +137 -92
- package/skills/lunora-setup-mail/SKILL.md +87 -113
- package/skills/lunora-setup-scheduler/SKILL.md +133 -97
- package/skills/lunora-setup-storage/SKILL.md +189 -95
- package/dist/packem_chunks/planDevCommand.mjs +0 -541
- package/dist/packem_chunks/runDeployCommand.mjs +0 -594
- package/dist/packem_chunks/runMigrateGenerateCommand.mjs +0 -397
- package/dist/packem_shared/COMMANDS-B0ftFD_3.mjs +0 -948
- package/dist/packem_shared/DEFAULT_IMPORT_BATCH_SIZE-Ck-2bU08.mjs +0 -244
- package/dist/packem_shared/admin-url-4UzT-CI4.mjs +0 -19
- package/dist/packem_shared/api-spec-CtA6ilu4.mjs +0 -13
- package/dist/packem_shared/buildRegistryIndex-BcYe607_.mjs +0 -38
- package/dist/packem_shared/codegen-error-DJG-ghs_.mjs +0 -31
- package/dist/packem_shared/command-D3lB_4Az.mjs +0 -19
- package/dist/packem_shared/commands-B-gR09Z_.mjs +0 -845
- package/dist/packem_shared/createLogger-B40gPzQo.mjs +0 -78
- package/dist/packem_shared/createRecordingSpawner-DxI3mebw.mjs +0 -43
- package/dist/packem_shared/detect-package-manager-DYp7n3mJ.mjs +0 -61
- package/dist/packem_shared/diffSnapshots-BeDvvNiF.mjs +0 -161
- package/dist/packem_shared/docker-hMQ97KSQ.mjs +0 -21
- package/dist/packem_shared/insertSchemaExtension-DAqbfr9Z.mjs +0 -64
- package/dist/packem_shared/open-url-Dfq6fAyT.mjs +0 -41
- package/dist/packem_shared/output-format-wUvAN6AL.mjs +0 -17
- package/dist/packem_shared/parseArgs-YXFuKdEk.mjs +0 -56
- package/dist/packem_shared/parseManifest--vZf2FY1.mjs +0 -94
- package/dist/packem_shared/prompt-cancelled-APzX1Im-.mjs +0 -9
- package/dist/packem_shared/resolve-target-qbsJ_5sF.mjs +0 -16
- package/dist/packem_shared/runAddCommand-bnY6-HKb.mjs +0 -4
- package/dist/packem_shared/schema-drift-gate-BtBt0as0.mjs +0 -79
- package/dist/packem_shared/schemaIrToSnapshot-DdsljJT-.mjs +0 -43
- package/dist/packem_shared/storage-BIsph-Vk.mjs +0 -84
- package/dist/packem_shared/tui-prompts-BjEN8XgP.mjs +0 -658
- package/dist/packem_shared/wrangler-name-cy4yhm9j.mjs +0 -12
- package/dist/packem_shared/wrangler-secrets-P2_ZUR-k.mjs +0 -47
|
@@ -0,0 +1,3 @@
|
|
|
1
|
+
import z,{join as m,resolve as I}from"node:path";import{isInteractive as J,promptYesNo as W}from"@lunora/config";import{backupObjectKey as v,isBackupManifestEntry as D,normalizeBackupPrefix as Y,BACKUP_KEY_PREFIX as X,backupManifestKey as Q,isBackupManifestKey as V,backupObjectKeyOfManifest as G}from"@lunora/runtime";import{r as E,t as Z}from"../packem_shared/admin-token-VdUnvnKW.mjs";import{r as A,a as T}from"../packem_shared/admin-url-DJB8P6Jh.mjs";import{d as ee}from"../packem_shared/command-B6vu47iR.mjs";import{EXIT_CODE as u,isRefusal as p,exitCodeForStatus as k}from"../packem_shared/EXIT_CODE-DVjUgIaG.mjs";import{a as re}from"../packem_shared/resolve-target-C_ZloTvd.mjs";import{runExportCommand as te}from"../packem_shared/runExportCommand-DiMCQ-Il.mjs";import{b as ae,l as oe,M as U,u as ne,r as ie}from"../packem_shared/import-DoAUdyfU.mjs";import{readAndLogBody as y}from"./runRpcCommand.mjs";import{randomUUID as j,createHash as se}from"node:crypto";import{existsSync as N,createReadStream as ce,createWriteStream as de}from"node:fs";import{mkdir as ue,rm as b,rename as C,readFile as q,writeFile as le,realpath as _,mkdtemp as x}from"node:fs/promises";import{LunoraError as w}from"@lunora/errors";import{i as R}from"../packem_shared/path-containment-CgxYZggb.mjs";import{tmpdir as O}from"node:os";import{Readable as fe}from"node:stream";import{pipeline as me}from"node:stream/promises";const S="manifest.json",L=async e=>{const t=se("sha256");let r=0;for await(const a of ce(e)){const o=a;r+=o.byteLength,t.update(o)}return{bytes:r,sha256:t.digest("hex")}},P=async e=>{const t=m(e,S);if(!N(t))return[];let r;try{r=JSON.parse(await q(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=>D(a))},ge=async(e,t)=>{const r=m(e,`${S}.${j()}.tmp`);try{await le(r,`${JSON.stringify(t,void 0,2)}
|
|
2
|
+
`,"utf8"),await C(r,m(e,S))}catch(a){throw await b(r,{force:!0}),a}},he=async(e,t)=>{const r=I(e),a=I(r,t.file),o=()=>{throw new w("INTERNAL",`backup: entry ${t.id} points outside ${r} (${t.file}) — refusing to read it`)};if(R(r,a)||o(),!!N(a))return R(await _(r),await _(a))||o(),a},we=e=>{const t=r=>v("",r);return{commit:async(r,a)=>{await C(a,m(e,r))},label:e,list:async()=>P(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?N(a)?a:void 0:await he(e,r))},record:async r=>{const a=await P(e);a.push(r),await ge(e,a)},stage:async r=>{await ue(e,{recursive:!0});const a=m(e,`${t(r)}.${j()}.partial`);return{path:a,release:()=>b(a,{force:!0})}}}},be="/_lunora/admin/storage/object",ke="/_lunora/admin/storage",B=8,ye=(e,t=z)=>{const r=t.basename(e);return r===""||r==="."||r===".."?"snapshot.ndjson":r},pe=e=>{const{context:t,logger:r}=e,a=Y(e.prefix??X),o=`bucket ${t.bucket??"(default)"} under ${a}`,i=ae(t),n=c=>`${t.baseUrl}${be}?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()},H=async c=>{try{const s=JSON.parse(await f(c));if(D(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>U)throw new w("INTERNAL",`backup: the snapshot is ${String(l.bytes)} bytes, above the ${String(U)}-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 q(s);await ne(t,c,d,{contentType:"application/x-ndjson",id:c,sha256:l.sha256,size:l.bytes},r)},label:o,list:async()=>{const s=(await oe(t,a)).map(d=>d.key).filter(d=>V(d)),l=[];for(let d=0;d<s.length;d+=B){const g=await Promise.all(s.slice(d,d+B).map(async h=>H(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 x(m(O(),"lunora-backup-")),h=m(g,ye(l));try{await me(fe.from(d.body),de(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=Q(c.file),l=await t.fetchImpl(`${t.baseUrl}${ke}?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 x(m(O(),"lunora-backup-"));return{path:m(s,v("",c)),release:async()=>b(s,{force:!0,recursive:!0})}}}},$e=".lunora-backups",F="/_lunora/admin/backup/retention",ve="/_lunora/admin/backup/prune",Se="/_lunora/admin/pitr",Ee="__lunora_admin__:getPitrBookmark",Ae="__lunora_admin__:pitrRestore",Te=async(e,t)=>{const r=(e.now??(()=>new Date))().toISOString(),a=await t.stage(r);try{const o=await te({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 L(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)})`)})}},Ne=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 L(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`)},Ie=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}},Ue=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 Ne(i.path,o,e.logger);if(f!==void 0)return f}const n=await ie({cwd:e.cwd,fetchImpl:e.fetchImpl,file:i.path,logger:e.logger,prod:e.prod,replace:e.replace,token:e.token,url:e.url,yes:e.yes});return{code:n.code,entry:o,restored:n.inserted+(n.replaced??0)}}finally{await i.release().catch(n=>{e.logger.warn(`backup: could not clean up the downloaded snapshot (${n instanceof Error?n.message:String(n)})`)})}},_e=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=A(e.url,e.logger,e.cwd);if(t===void 0)return{refused:u.USAGE};if(e.restore===!0&&Z({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});return r?{fetchImpl:e.adminFetch??T,requestUrl:`${t}${Se}`,token:r}:(e.logger.error("admin token required — pass --token, set LUNORA_ADMIN_TOKEN, or add it to .dev.vars (local targets only)"),{refused:u.AUTH})},xe=(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},Re=async e=>{const t=_e(e);if(p(t))return{code:t.refused};const r=e.restore===!0,a=r?Ae:Ee,o=xe(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)}},Oe=(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}):we(m(t,e.dir??$e));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=A(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??T;return pe({context:{baseUrl:r,bucket:e.bucket==="default"?void 0:e.bucket,fetchImpl:o,token:a},logger:e.logger,prefix:e.prefix})},M=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=A(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??T;return{baseUrl:r,fetchImpl:o,token:a}},K=(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(` ${G(r)}`)},Pe=async e=>{const t=M(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}):(K(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})},Be=(e,t)=>{e.logger.success(`deleted ${t.deleted.length.toString()} backup(s)`);for(const r of t.deleted)e.logger.info(` ${G(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`)},De=async e=>{const t=M(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(K(e,a),e.yes!==!0){const n=e.confirm??(J()?W: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}${ve}`,{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 Be(e,i),{code:i.failed.length>0?1:0,deleted:i.deleted,preview:a}},Ge=async(e,t)=>{try{if(e.subcommand==="pitr")return await Re(e);if(e.subcommand==="retention")return await Pe(e);if(e.subcommand==="prune")return await De(e);const r=Oe(e,t);return p(r)?{code:r.refused}:e.subcommand==="create"?await Te(e,r):e.subcommand==="list"?await Ie(e,r):await Ue(e,r)}catch(r){return e.logger.error(r instanceof Error?r.message:String(r)),{code:1}}},je=async e=>{const t=e.cwd??process.cwd(),r=await Ge(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}}}},Ce=e=>e==="create"||e==="list"||e==="pitr"||e==="prune"||e==="restore"||e==="retention",nr=ee(async({argument:e,cwd:t,format:r,logger:a,options:o})=>{const i=e[0];if(!Ce(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 je({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,replace:o.replace===!0,restart:o.restart===!0,restore:o.restore===!0,shard:o.shard,subcommand:i,tables:o.tables,target:e[1],token:o.token,url:re({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{nr as execute,je as runBackupCommand};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{readdirSync as E,lstatSync as S,existsSync as y}from"node:fs";import{join as m,basename as $}from"node:path";import{d as w}from"../packem_shared/command-B6vu47iR.mjs";import{EXIT_CODE as h}from"../packem_shared/EXIT_CODE-DVjUgIaG.mjs";const l=".eval.ts",F=new Set([".git","_generated","dist","node_modules"]),p=(e,s=[])=>{let r;try{r=E(e)}catch{return s}for(const t of r){const n=m(e,t);let o;try{o=S(n)}catch{continue}if(o.isDirectory()){if(F.has(t))continue;p(n,s)}else o.isFile()&&t.endsWith(l)&&s.push(n)}return s.toSorted((t,n)=>t.localeCompare(n))},b=e=>typeof e=="object"&&e!==null&&typeof e.run=="function",g=e=>typeof e=="number"&&Number.isFinite(e)&&e>=0&&e<=1,R="evals";let u;const T=async()=>(u??=import("jiti").then(({createJiti:e})=>e(import.meta.url,{interopDefault:!1})),u),f=e=>$(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}),A=e=>({evals:e.evals.map(s=>x(s))}),v=(e,s,r)=>(e.error(s),{code:r,error:s,evals:[]}),L=(e,s,r)=>{if(!y(e))return r.info(`eval: no "${s}" directory — nothing to run`),[];const t=p(e);return t.length===0&&r.info(`eval: no ${l} files found under "${s}"`),t},I=async e=>{const t=(await(await T()).import(e)).default;if(!b(t))throw new Error("does not default-export an eval module (expected `{ run(): Promise<EvalResult>, name?, threshold? }`)");return t},O=async(e,s)=>{let r;try{r=await I(e)}catch(o){return{error:o instanceof Error?o.message:String(o),name:f(e),passed:!1,path:e}}const t=r.name??f(e);if(r.threshold!==void 0&&!g(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 n=r.threshold??s;try{const o=await r.run(),a=n===void 0||o.average>=n;return{name:t,passed:a,path:e,result:o,threshold:n}}catch(o){return{error:o instanceof Error?o.message:String(o),name:t,passed:!1,path:e,threshold:n}}},_=async(e,s)=>{const r=[];for(const t of e)r.push(await O(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 n=t.result===void 0?"—":t.result.average.toFixed(3),o=t.threshold===void 0?"—":t.threshold.toFixed(3);r.push(`${t.name.padEnd(s)} ${n.padEnd(6)} ${o.padEnd(9)} ${D(t)}`)}return r},M=async e=>{const s=e.cwd??process.cwd(),{logger:r}=e;if(e.threshold!==void 0&&!g(e.threshold))return v(r,`eval: --threshold must be a number in [0, 1] — received "${String(e.threshold)}"`,h.USAGE);const t=e.dir??R,n=m(s,t),o=L(n,t,r),a=await _(o,e.threshold);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 v(r,d,h.USAGE)}for(const d of C(a))r.info(d);const i=a.filter(d=>!d.passed),c=i.length>0?1:0;return c===0?r.success(`eval: ${String(a.length)} eval(s) passed`):r.error(`eval: ${String(i.length)}/${String(a.length)} eval(s) failed`),{code:c,evals:a}},N=w(async({cwd:e,format:s,logger:r,options:t})=>{const n=await M({cwd:e,dir:t.dir,format:s,logger:r,threshold:t.threshold});return{code:n.code,data:A(n),error:n.error}});export{N as execute,M as runEvalCommand};
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
import{readLinkedProject as h,resolveDeployDriver as b}from"@lunora/config";import{d as y}from"../packem_shared/command-B6vu47iR.mjs";import{r as w}from"../packem_shared/deploy-target-resolve-BTCW1Iv4.mjs";import{EXIT_CODE as m}from"../packem_shared/EXIT_CODE-DVjUgIaG.mjs";import{defaultSpawner as E}from"../packem_shared/createRecordingSpawner-01ZngIwK.mjs";import{createR2Sql as L}from"@lunora/bindings/r2sql";import{createPipelineLogReader as S}from"@lunora/runtime";import{toolchainExecArgs as _,detectPackageManager as T}from"@lunora/config/cli";const p=["trace","debug","log","info","warn","error","fatal"],C=new Set(p),v=/^\d+$/,f=(e,r)=>{if(e===void 0)return;const a=e.trim();if(v.test(a))return Number(a);const n=Date.parse(a);if(Number.isNaN(n))throw new TypeError(`logs: invalid ${r} "${e}" — pass epoch-millis or an ISO 8601 date`);return n},I=e=>Buffer.from(JSON.stringify(e),"utf8").toString("base64url"),$=e=>{const r=e.trim();if(v.test(r))return{ts:Number(r)};let a;try{a=JSON.parse(Buffer.from(r,"base64url").toString("utf8"))}catch{throw new TypeError(`logs: invalid --cursor "${e}" — expected the token printed by the previous page (or a bare epoch-millis ts)`)}if(typeof a!="object"||a===null||typeof a.ts!="number"||!Number.isFinite(a.ts))throw new TypeError(`logs: invalid --cursor "${e}" — expected the token printed by the previous page (or a bare epoch-millis ts)`);const{ts:n}=a,t=a.seen,s=Array.isArray(t)?t.filter(o=>typeof o=="string"):void 0;return s!==void 0&&s.length>0?{seen:s,ts:n}:{ts:n}},g=(e,r)=>{if(e!==void 0){if(!C.has(e))throw new TypeError(`logs: invalid ${r} "${e}" — expected one of trace, debug, log, info, warn, error, fatal`);return e}},R=e=>{const r={},a=f(e.since,"--since");a!==void 0&&(r.sinceTs=a);const n=f(e.until,"--until");n!==void 0&&(r.untilTs=n);const t=g(e.level,"--level");t!==void 0&&(r.level=t);const s=g(e.minLevel,"--min-level");if(s!==void 0&&(r.minLevel=s),e.functionPrefix!==void 0&&(r.functionPathPrefix=e.functionPrefix),e.traceId!==void 0&&(r.traceId=e.traceId),e.shardKey!==void 0&&(r.shardKey=e.shardKey),e.userId!==void 0&&(r.userId=e.userId),e.limit!==void 0){const o=Number(e.limit);if(!Number.isFinite(o))throw new TypeError(`logs: invalid --limit "${e.limit}" — expected a number`);r.limit=o}return e.cursor!==void 0&&(r.cursor=$(e.cursor)),r},N=e=>{const r=new Date(e.ts).toISOString(),a=e.level.toUpperCase().padEnd(5);return`${r} ${a} ${e.functionPath} ${e.message}`},O=async e=>{const r=e.environment??process.env,a=r.R2_SQL_ACCOUNT_ID,n=r.R2_SQL_TOKEN,t=r.R2_SQL_BUCKET,s=[];if((a===void 0||a.length===0)&&s.push("R2_SQL_ACCOUNT_ID"),(n===void 0||n.length===0)&&s.push("R2_SQL_TOKEN"),(t===void 0||t.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:m.USAGE,error:"not configured"};let o;try{o=R(e)}catch(i){return e.logger.error(i instanceof Error?i.message:String(i)),{code:m.USAGE,error:"invalid option"}}const u=L({accountId:a,apiToken:n,bucket:t,fetch:e.fetch}),c=await S(u,{namespace:e.namespace,table:e.table}).query(o);for(const i of c.rows)process.stdout.write(`${e.ndjson===!0?JSON.stringify(i):N(i)}
|
|
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 ${I(c.nextCursor)} for the next page`),{code:0,rows:c.rows}},x=async e=>{const r=e.cwd??process.cwd(),a=e.env??h(r)?.env,n=w(r,e.target);if(n.target===void 0){const d=`logs: ${n.error??"no deploy target"}`;return e.logger.error(d),{code:m.USAGE,descriptor:void 0,error:d}}const t=b(n.target),s=t.toolchain?.tail;if(s===void 0){const d=`logs: deploy target "${t.id}" has no log tail`;return e.logger.error(d),{code:m.USAGE,descriptor:void 0,error:d}}const o=s({environment:a,format:e.format,search:e.search,status:e.status,temporary:e.temporary,worker:e.worker}),u=_(T(r),o),l={args:u.args,command:u.command,cwd:r};return e.logger.info(`tailing logs via ${l.command} ${l.args.join(" ")}`),{code:(await(e.spawner??E)(l)).code,delegated:!0,descriptor:l}},G=y(async({argument:e,cwd:r,format:a,logger:n,options:t})=>{if(t.durable===!0){const s=await O({cursor:t.cursor,functionPrefix:t.functionPrefix,level:t.level,limit:t.limit,logger:n,minLevel:t.minLevel,namespace:t.namespace,ndjson:t.ndjson===!0,shardKey:t.shardKey,since:t.since,table:t.table,traceId:t.traceId,until:t.until,userId:t.userId});return{...s,...s.rows===void 0?{}:{delegated:!0}}}return x({cwd:r,env:t.env,format:a,logger:n,search:t.search,status:t.status,target:t.target,temporary:t.temporary===!0,worker:e[0]})});export{G as execute,x as runLogsCommand};
|
|
@@ -0,0 +1,99 @@
|
|
|
1
|
+
import{existsSync as O,readFileSync as k}from"node:fs";import{writeFile as I,mkdir as U}from"node:fs/promises";import{parseSchema as B,applyAdditiveEdit as F,projectUsesUmbrella as Y}from"@lunora/config";import{join as _}from"@visulima/path";import{d as q}from"../packem_shared/command-B6vu47iR.mjs";import{EXIT_CODE as L}from"../packem_shared/EXIT_CODE-DVjUgIaG.mjs";import{createRequire as P}from"node:module";import{LunoraError as N}from"@lunora/errors";import{addArgsFor as H,detectPackageManager as K}from"@lunora/config/cli";const j=/^\//,G=(e,r)=>{try{const{args:n,command:t}=H(K(e),[r],{dev:!0});return`${t} ${n.join(" ")}`}catch{return`<your-package-manager> add -D ${r}`}},T=(e,r,n)=>{const t=P(_(n,"noop.cjs"));try{t.resolve(e)}catch{throw new N("INTERNAL",`\`lunora introspect\` needs the \`${r}\` driver to read this database, and it isn't installed.
|
|
2
|
+
|
|
3
|
+
Install it in your project:
|
|
4
|
+
|
|
5
|
+
${G(n,r)}`)}return t(e)},Q=e=>{const r=e.slice(0,Math.max(0,e.indexOf(":"))).toLowerCase();if(r==="postgres"||r==="postgresql")return"postgres";if(r==="mysql"||r==="mariadb")return"mysql";throw new N("INTERNAL",`Unrecognised database URL scheme \`${r}\`. Expected a \`postgres://\`, \`postgresql://\`, \`mysql://\`, or \`mariadb://\` connection string.`)},J=e=>{try{const r=new URL(e).pathname.replace(j,"");return r===""?void 0:decodeURIComponent(r)}catch{return}},W=async(e,r,n,t=process.cwd())=>{if(r==="postgres"){const m=T("pg","pg",t).Client,u=new m({connectionString:e});return await u.connect(),{close:async()=>{await u.end()},execute:async(l,p)=>(await u.query(l,[...p])).rows,schema:n??"public"}}const a=T("mysql2/promise","mysql2",t).createConnection,o=await a(e),i=n??J(e);if(i===void 0)throw new N("INTERNAL","A MySQL connection string must name a database (`mysql://host/<database>`), or pass `--schema`.");return{close:async()=>{await o.end()},execute:async(c,m)=>{const[u]=await o.execute(c,[...m]);return Array.isArray(u)?u:[]},schema:i}},h=new Set(["_creationTime","_id"]),X={bigint:"v.bigint()",bigserial:"v.bigint()",bit:"v.string()",bool:"v.boolean()",boolean:"v.boolean()",box:"v.string()",bpchar:"v.string()",bytea:"v.bytes()",char:"v.string()",character:"v.string()","character varying":"v.string()",cidr:"v.string()",circle:"v.string()",citext:"v.string()",date:"v.date()","double precision":"v.number()",float4:"v.number()",float8:"v.number()",inet:"v.string()",int:"v.number()",int2:"v.number()",int4:"v.number()",int8:"v.bigint()",integer:"v.number()",interval:"v.string()",json:"v.any()",jsonb:"v.any()",line:"v.string()",lseg:"v.string()",macaddr:"v.string()",money:"v.number()",name:"v.string()",numeric:"v.number()",path:"v.string()",point:"v.string()",polygon:"v.string()",real:"v.number()",serial:"v.number()",smallint:"v.number()",smallserial:"v.number()",text:"v.string()",time:"v.string()","time with time zone":"v.string()","time without time zone":"v.string()",timestamp:"v.timestamp()","timestamp with time zone":"v.timestamp()","timestamp without time zone":"v.timestamp()",timestamptz:"v.timestamp()",tsquery:"v.string()",tsvector:"v.string()",uuid:"v.string()",varbit:"v.string()",varchar:"v.string()",xml:"v.string()"},z={bigint:"v.bigint()",binary:"v.bytes()",bit:"v.number()",blob:"v.bytes()",char:"v.string()",date:"v.date()",datetime:"v.timestamp()",decimal:"v.number()",double:"v.number()",enum:"v.string()",float:"v.number()",int:"v.number()",integer:"v.number()",json:"v.any()",longblob:"v.bytes()",longtext:"v.string()",mediumblob:"v.bytes()",mediumint:"v.number()",mediumtext:"v.string()",numeric:"v.number()",set:"v.string()",smallint:"v.number()",text:"v.string()",time:"v.string()",timestamp:"v.timestamp()",tinyblob:"v.bytes()",tinyint:"v.number()",tinytext:"v.string()",varbinary:"v.bytes()",varchar:"v.string()",year:"v.number()"},w=(e,r)=>{const t=(r==="postgres"?X:z)[e.dataType],s=e.references===void 0?t:`v.id(${JSON.stringify(e.references.table)})`;let a=s??"v.any()";for(let o=0;o<e.arrayDepth;o+=1)a=`v.array(${a})`;return e.nullable&&(a=`v.optional(${a})`),{expression:a,known:s!==void 0}},M=/^[A-Z_$][\w$]*$/i,Z=/[^\dA-Z]+(.)?/gi,V=/^\d+/,ee=/[^\w-]/g,ne=/[\u003C\u003E\u002F\u2028\u2029]/g,te={"/":String.raw`\u002F`,"\u2028":String.raw`\u2028`,"\u2029":String.raw`\u2029`,"<":String.raw`\u003C`,">":String.raw`\u003E`},f=e=>JSON.stringify(e).replaceAll(ne,r=>te[r]??r),S=e=>M.test(e)?e:f(e),re=e=>M.test(e)?`.${e}`:`[${f(e)}]`,x=e=>e.replaceAll("*/",String.raw`*\/`),ae=e=>{const r=e.replaceAll(ee,"_");return r===""?"table":r},se=e=>{const n=e.replaceAll(Z,(t,s)=>s?.toUpperCase()??"").replace(V,"");return n===""?"table":`${n.charAt(0).toLowerCase()}${n.slice(1)}`},C=e=>e.columns.filter(r=>!h.has(r.name)),oe=e=>{const r=new Set(e.primaryKey);for(const n of e.indexes)for(const t of n.columns)r.add(t);for(const n of e.columns)n.references!==void 0&&r.add(n.name);return[...r].filter(n=>!h.has(n))},D=(e,r,n,t)=>e.references===void 0||r.has(e.references.table)?e:(t.push(`${n}.${e.name}: references \`${e.references.table}\`, which isn't in the generated schema — emitted as a plain column instead of \`v.id(...)\`.`),{arrayDepth:e.arrayDepth,dataType:e.dataType,name:e.name,nullable:e.nullable}),ie=(e,r,n,t)=>{const s=[];for(const o of e.columns){if(h.has(o.name)){t.push(`${e.name}.${o.name}: skipped — \`${o.name}\` is a Lunora system column. Rename it in the source database or map it by hand.`);continue}const i=D(o,n,e.name,t),{expression:c,known:m}=w(i,r);!m&&i.references===void 0&&(t.push(`${e.name}.${o.name}: no mapping for SQL type \`${o.dataType}\` — emitted as \`v.any()\`.`),s.push(` // TODO: \`${x(o.dataType)}\` has no direct validator; narrow this.`)),s.push(` ${S(o.name)}: ${c},`)}const a=[' .global({ backend: "hyperdrive" })'];if(e.primaryKey.length>0&&e.primaryKey.every(o=>!h.has(o))){const o=e.primaryKey.map(i=>f(i)).join(", ");a.push(` .index(${f(`by_${e.primaryKey.join("_")}`)}, [${o}], { unique: true })`)}for(const o of e.indexes){const i=o.columns.filter(u=>!h.has(u));if(i.length===0)continue;const c=i.map(u=>f(u)).join(", "),m=o.unique?", { unique: true }":"";a.push(` .index(${f(o.name)}, [${c}]${m})`)}return` ${S(e.name)}: defineTable({
|
|
6
|
+
${s.join(`
|
|
7
|
+
`)}
|
|
8
|
+
})
|
|
9
|
+
${a.join(`
|
|
10
|
+
`)},`},ce=(e,r,n)=>{const t=new Set(e.tables.map(a=>a.name)),s=e.tables.map(a=>ie(a,e.dialect,t,n)).join(`
|
|
11
|
+
`);return`/**
|
|
12
|
+
* Generated by \`lunora introspect\` from an existing ${e.dialect==="postgres"?"Postgres":"MySQL"} database.
|
|
13
|
+
*
|
|
14
|
+
* This file is a STARTING POINT, not a build artifact — it is written once and is
|
|
15
|
+
* yours to edit. Review it before shipping: column types are mapped
|
|
16
|
+
* conservatively, and every table is \`.global({ backend: "hyperdrive" })\` because
|
|
17
|
+
* its rows live in the external database. Re-running \`lunora introspect\` will not
|
|
18
|
+
* overwrite it unless you pass \`--force\`.
|
|
19
|
+
*/
|
|
20
|
+
import { defineSchema, defineTable, v } from "${r.serverImport}";
|
|
21
|
+
|
|
22
|
+
export default defineSchema({
|
|
23
|
+
${s}
|
|
24
|
+
});
|
|
25
|
+
`},me=(e,r,n,t=new Set([e.name]),s=[])=>{const a=se(e.name),o=oe(e),i=new Map(C(e).map(l=>[l.name,l])),c=o.map(l=>{const p=i.get(l);if(p===void 0)return;const v=D({...p,nullable:!1},t,e.name,[]),{expression:d,known:A}=w(v,r);return!A&&v.references===void 0&&s.push(`${e.name}.${l}: filter falls back to \`v.any()\` (no mapping for SQL type \`${p.dataType}\`).`),` ${S(l)}: ${d},`}).filter(l=>l!==void 0),m=[f("_creationTime"),...o.map(l=>f(l))].join(", "),u=`ctx.db${re(e.name)}`;return`/**
|
|
26
|
+
* Generated by \`lunora introspect\` for the \`${x(e.name)}\` table — a
|
|
27
|
+
* starting point you own and edit.
|
|
28
|
+
*
|
|
29
|
+
* Both procedures are RPC-only. Add \`.expose({ rest: true })\` once you've decided
|
|
30
|
+
* this data should be public, and gate them with your auth/RLS middleware first —
|
|
31
|
+
* \`introspect\` cannot know who is allowed to read this table.
|
|
32
|
+
*/
|
|
33
|
+
import { defineListArgs, v } from "${n.serverImport}";
|
|
34
|
+
|
|
35
|
+
import type { Doc } from "./_generated/dataModel";
|
|
36
|
+
import { c } from "./_generated/server";
|
|
37
|
+
|
|
38
|
+
const ${a}List = defineListArgs<Doc<${f(e.name)}>>()({
|
|
39
|
+
// Only index-backed columns are published as filterable, so a caller cannot
|
|
40
|
+
// reach a column you did not choose to expose. Note that \`contains\` and the
|
|
41
|
+
// negative operators still scan — narrow this list, and review it, before
|
|
42
|
+
// adding \`.expose({ rest: true })\`.
|
|
43
|
+
filter: {
|
|
44
|
+
${c.join(`
|
|
45
|
+
`)}
|
|
46
|
+
},
|
|
47
|
+
orderBy: [${m}],
|
|
48
|
+
});
|
|
49
|
+
|
|
50
|
+
export const list = c.query.input(${a}List.args).query(({ args, ctx }) => ${u}.findMany(${a}List.toQueryArgs(args)));
|
|
51
|
+
|
|
52
|
+
export const get = c.query.input({ id: v.id(${f(e.name)}) }).query(({ args, ctx }) => ${u}.get(args.id));
|
|
53
|
+
`},le=(e,r)=>{const n=[],t=new Set(e.tables.map(a=>a.name)),s=[{contents:ce(e,r,n),path:"schema.ts"}];if(r.procedures){const a=new Map([["schema","the generated schema module"]]);for(const o of e.tables){if(C(o).length===0){n.push(`${o.name}: no usable columns — procedure module skipped.`);continue}const i=ae(o.name);i!==o.name&&n.push(`${o.name}: written as \`${i}.ts\` — the table name isn't usable as a filename.`);const c=a.get(i);if(c!==void 0){n.push(`${o.name}: procedure module skipped — its filename \`${i}.ts\` collides with table \`${c}\`.`);continue}a.set(i,o.name),s.push({contents:me(o,e.dialect,r,t,n),path:`${i}.ts`})}}return{files:s,warnings:n}},y=/^[A-Z_$][\w$]*$/i,ue=e=>e.startsWith("v.optional(")&&e.endsWith(")")?e.slice(11,-1):e,de=(e,r,n)=>{const t=[],s=new Set(r?.columns.map(a=>a.name));for(const a of e.columns){if(h.has(a.name)||s.has(a.name))continue;if(!y.test(a.name)){n.warnings.push(`${e.name}.${a.name}: skipped — column names must be bare identifiers to merge.`);continue}const o=a.references!==void 0&&!n.present.has(a.references.table),{expression:i}=w(o?{...a,references:void 0}:a,n.dialect);t.push({column:a.name,kind:"addOptionalColumn",table:e.name,validator:ue(i)}),!a.nullable&&r!==void 0&&n.warnings.push(`${e.name}.${a.name}: added as \`v.optional(...)\` — a required column on an existing table needs a backfill migration.`)}return t},pe=(e,r,n)=>{const t=[],s=new Set(r?.indexes.map(a=>a.name));for(const a of e.indexes){const o=a.columns.filter(i=>!h.has(i));if(!(s.has(a.name)||o.length===0)){if(!y.test(a.name)||!o.every(i=>y.test(i))){n.push(`${e.name}: index \`${a.name}\` skipped — index and column names must be bare identifiers to merge.`);continue}t.push({fields:o,kind:"addIndex",name:a.name,table:e.name,...a.unique?{unique:!0}:{}})}}return t},ge=(e,r,n)=>{const t=[],s=[],a=new Map(r.map(i=>[i.name,i])),o=new Set([...a.keys(),...e.tables.map(i=>i.name)]);for(const i of e.tables){if(!y.test(i.name)){s.push(`${i.name}: skipped — merging into an existing schema needs a table name that is a bare identifier.`);continue}const c=a.get(i.name);c===void 0&&t.push({global:{backend:"hyperdrive"},kind:"addTable",table:i.name}),t.push(...de(i,c,{dialect:n,present:o,warnings:s}),...pe(i,c,s))}return{edits:t,warnings:s}},fe=(e,r,n)=>{const t=B(e);if(!t.ok)return{applied:0,warnings:[`lunora/schema.ts could not be parsed (${t.reason}) — leave it alone and merge by hand, or pass --force.`]};const s=ge(r,t.tables,n),a=[...s.warnings];let o=e,i=0;for(const c of s.edits){const m=F(o,c);m.ok?(o=m.text,i+=1):a.push(`${c.table}: skipped one edit (${m.reason}).`)}return{applied:i,warnings:a,...i===0?{}:{text:o}}},g=(e,r)=>{const n=e[r]??e[r.toLowerCase()]??e[r.toUpperCase()];return typeof n=="string"?n:typeof n=="number"||typeof n=="bigint"||typeof n=="boolean"?String(n):""},ve=`
|
|
54
|
+
SELECT c.table_name, c.column_name, c.is_nullable, c.data_type, c.udt_name
|
|
55
|
+
FROM information_schema.columns c
|
|
56
|
+
JOIN information_schema.tables t
|
|
57
|
+
ON t.table_schema = c.table_schema AND t.table_name = c.table_name
|
|
58
|
+
WHERE c.table_schema = $1 AND t.table_type = 'BASE TABLE'
|
|
59
|
+
ORDER BY c.table_name, c.ordinal_position`,be=`
|
|
60
|
+
SELECT tc.table_name, kcu.column_name
|
|
61
|
+
FROM information_schema.table_constraints tc
|
|
62
|
+
JOIN information_schema.key_column_usage kcu
|
|
63
|
+
ON kcu.constraint_name = tc.constraint_name AND kcu.table_schema = tc.table_schema
|
|
64
|
+
WHERE tc.table_schema = $1 AND tc.constraint_type = 'PRIMARY KEY'
|
|
65
|
+
ORDER BY tc.table_name, kcu.ordinal_position`,he=`
|
|
66
|
+
SELECT tc.table_name, kcu.column_name, ccu.table_name AS foreign_table, ccu.column_name AS foreign_column
|
|
67
|
+
FROM information_schema.table_constraints tc
|
|
68
|
+
JOIN information_schema.key_column_usage kcu
|
|
69
|
+
ON kcu.constraint_name = tc.constraint_name AND kcu.table_schema = tc.table_schema
|
|
70
|
+
JOIN information_schema.constraint_column_usage ccu
|
|
71
|
+
ON ccu.constraint_name = tc.constraint_name AND ccu.table_schema = tc.table_schema
|
|
72
|
+
WHERE tc.table_schema = $1 AND tc.constraint_type = 'FOREIGN KEY'`,Ee=`
|
|
73
|
+
SELECT t.relname AS table_name, i.relname AS index_name, ix.indisunique AS is_unique, a.attname AS column_name
|
|
74
|
+
FROM pg_class t
|
|
75
|
+
JOIN pg_index ix ON t.oid = ix.indrelid
|
|
76
|
+
JOIN pg_class i ON i.oid = ix.indexrelid
|
|
77
|
+
JOIN pg_namespace n ON n.oid = t.relnamespace
|
|
78
|
+
CROSS JOIN LATERAL unnest(ix.indkey) WITH ORDINALITY AS k(attnum, ord)
|
|
79
|
+
JOIN pg_attribute a ON a.attrelid = t.oid AND a.attnum = k.attnum
|
|
80
|
+
WHERE n.nspname = $1 AND t.relkind = 'r' AND NOT ix.indisprimary
|
|
81
|
+
ORDER BY t.relname, i.relname, k.ord`,_e=`
|
|
82
|
+
SELECT c.TABLE_NAME, c.COLUMN_NAME, c.IS_NULLABLE, c.DATA_TYPE
|
|
83
|
+
FROM information_schema.COLUMNS c
|
|
84
|
+
JOIN information_schema.TABLES t
|
|
85
|
+
ON t.TABLE_SCHEMA = c.TABLE_SCHEMA AND t.TABLE_NAME = c.TABLE_NAME
|
|
86
|
+
WHERE c.TABLE_SCHEMA = ? AND t.TABLE_TYPE = 'BASE TABLE'
|
|
87
|
+
ORDER BY c.TABLE_NAME, c.ORDINAL_POSITION`,ye=`
|
|
88
|
+
SELECT TABLE_NAME, COLUMN_NAME
|
|
89
|
+
FROM information_schema.KEY_COLUMN_USAGE
|
|
90
|
+
WHERE TABLE_SCHEMA = ? AND CONSTRAINT_NAME = 'PRIMARY'
|
|
91
|
+
ORDER BY TABLE_NAME, ORDINAL_POSITION`,Ae=`
|
|
92
|
+
SELECT TABLE_NAME, COLUMN_NAME, REFERENCED_TABLE_NAME AS foreign_table, REFERENCED_COLUMN_NAME AS foreign_column
|
|
93
|
+
FROM information_schema.KEY_COLUMN_USAGE
|
|
94
|
+
WHERE TABLE_SCHEMA = ? AND REFERENCED_TABLE_NAME IS NOT NULL`,Se=`
|
|
95
|
+
SELECT TABLE_NAME, INDEX_NAME AS index_name, NON_UNIQUE, COLUMN_NAME
|
|
96
|
+
FROM information_schema.STATISTICS
|
|
97
|
+
WHERE TABLE_SCHEMA = ? AND INDEX_NAME <> 'PRIMARY'
|
|
98
|
+
ORDER BY TABLE_NAME, INDEX_NAME, SEQ_IN_INDEX`,E=e=>{const r=new Map;for(const n of e){const t=g(n,"table_name"),s=r.get(t);s===void 0?r.set(t,[n]):s.push(n)}return r},Ne=(e,r)=>{const n=g(e,"data_type").toLowerCase();if(r!=="postgres")return{arrayDepth:0,dataType:n};const t=g(e,"udt_name").toLowerCase();return n==="array"&&t.startsWith("_")?{arrayDepth:1,dataType:t.slice(1)}:{arrayDepth:0,dataType:t===""?n:t}},we=(e,r)=>{const n=new Map;for(const t of e){const s=g(t,"index_name"),a=r==="postgres"?g(t,"is_unique")==="true":g(t,"NON_UNIQUE")==="0",o=n.get(s);o===void 0?n.set(s,{columns:[g(t,"column_name")],unique:a}):o.columns.push(g(t,"column_name"))}return[...n.entries()].map(([t,s])=>({columns:s.columns,name:t,unique:s.unique}))},Re=async(e,r,n)=>{const t=r==="postgres",[s,a,o,i]=await Promise.all([e(t?ve:_e,[n]),e(t?be:ye,[n]),e(t?he:Ae,[n]),e(t?Ee:Se,[n])]),c=E(a),m=E(o),u=E(i),l=[];for(const[p,v]of E(s)){const d=new Map((m.get(p)??[]).map(b=>[g(b,"column_name"),{column:g(b,"foreign_column"),table:g(b,"foreign_table")}])),A=v.map(b=>{const R=g(b,"column_name"),$=d.get(R);return{...Ne(b,r),name:R,nullable:g(b,"is_nullable").toUpperCase()==="YES",...$===void 0?{}:{references:$}}});l.push({columns:A,indexes:we(u.get(p)??[],r),name:p,primaryKey:(c.get(p)??[]).map(b=>g(b,"column_name"))})}return l.sort((p,v)=>p.name.localeCompare(v.name)),{dialect:r,tables:l}},$e=e=>Y(e)?"lunorash/server":"@lunora/server",Le=async(e,r,n)=>{const t=_(r,e.path);return O(t)&&n.force!==!0?(n.logger.warn(`skipped lunora/${e.path} — it already exists (pass --force to overwrite)`),!1):n.dryRun===!0?(n.logger.info(`would write lunora/${e.path} (${String(e.contents.split(`
|
|
99
|
+
`).length)} lines)`),!1):(await U(r,{recursive:!0}),await I(t,e.contents,"utf8"),n.logger.info(`wrote lunora/${e.path}`),!0)},Te=(e,r)=>{const n=r.tables;if(n===void 0||n.length===0)return e.tables;for(const t of n)e.tables.some(s=>s.name===t)||r.logger.warn(`--tables: no table named "${t}" exists in this schema — skipped.`);return e.tables.filter(t=>n.includes(t.name))},Oe=async(e,r,n,t)=>{const s=fe(k(e,"utf8"),r,n);for(const a of s.warnings)t.logger.warn(a);return s.text===void 0?(t.logger.info("lunora/schema.ts is already up to date with the database."),!1):t.dryRun===!0?(t.logger.info(`would merge ${String(s.applied)} addition(s) into lunora/schema.ts`),!1):(await I(e,s.text,"utf8"),t.logger.info(`merged ${String(s.applied)} addition(s) into lunora/schema.ts`),!0)},Ie=async e=>{const r=e.cwd??process.cwd();if(e.connection===void 0&&(e.url===void 0||e.url==="")){const d="`lunora introspect` needs a database URL: pass --url, or set DATABASE_URL.";return e.logger.error(d),{code:L.USAGE,error:d,written:[]}}const n=e.connection===void 0?Q(e.url):e.dialect??"postgres",t=e.connection??await W(e.url,n,e.schema,r);let s;try{s=await Re(t.execute,n,t.schema)}finally{e.connection===void 0&&await t.close()}const a=Te(s,e);if(a.length===0){const d="no tables found to introspect — check --schema and --tables.";return e.logger.error(d),{code:L.NOT_FOUND,error:d,written:[]}}const{files:o,warnings:i}=le({...s,tables:a},{procedures:e.procedures!==!1,serverImport:$e(r)}),c=_(r,"lunora"),m=[],u=_(c,"schema.ts"),l=O(u)&&e.force!==!0,p=l?o.filter(d=>d.path!=="schema.ts"):o;l&&await Oe(u,{...s,tables:a},n,e)&&m.push("schema.ts");for(const d of p)await Le(d,c,e)&&m.push(d.path);for(const d of i)e.logger.warn(d);e.logger.info(`introspected ${String(a.length)} table(s) from ${n}. Review the generated files before running \`lunora dev\`.`);const v=a.map(d=>d.name);return{code:0,dialect:n,tables:v,written:m}},qe=q(async({cwd:e,format:r,logger:n,options:t})=>{const s=await Ie({cwd:e,dryRun:t.dryRun===!0,force:t.force===!0,format:r,logger:n,procedures:t.procedures!==!1,schema:t.schema,tables:t.tables===void 0?void 0:t.tables.split(",").map(a=>a.trim()),url:t.url??process.env.DATABASE_URL});return{code:s.code,data:s.dialect===void 0?void 0:{dialect:s.dialect,dryRun:t.dryRun===!0,tables:s.tables??[],written:s.written},error:s.error}});export{qe as execute,$e as resolveServerImport,Ie as runIntrospectCommand};
|
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
import{V as te}from"./cli.mjs";import{d as re}from"../packem_shared/command-B6vu47iR.mjs";import{EXIT_CODE as f}from"../packem_shared/EXIT_CODE-DVjUgIaG.mjs";import{existsSync as m,readFileSync as F,statSync as ne,watch as oe}from"node:fs";import{homedir as C}from"node:os";import{findWranglerFile as le}from"@lunora/config/cloudflare";import{join as i,relative as ae}from"@visulima/path";import{stringify as ce}from"smol-toml";import{h as se,u as ie,i as de,r as ue}from"../packem_shared/mcp-config-file-GR1Y_CVw.mjs";import{detectPackageManager as me,execArgsFor as fe}from"@lunora/config/cli";import{resolve as $,join as pe,dirname as L}from"node:path";import{readLiveDevServerState as b,DEV_STATE_DIR as ge}from"@lunora/config";import{resolveAdminToken as he}from"@lunora/config/studio-host";import{connectLocalStdio as ve,connectFunctionStdio as ye}from"@lunora/mcp";import{i as we}from"../packem_shared/path-containment-CgxYZggb.mjs";const g=e=>({args:[...e.args],command:e.command,...e.env===void 0?{}:{env:e.env}}),j=e=>e.transport==="http"?{type:"http",url:e.url}:g(e),be=e=>e.transport==="http"?{httpUrl:e.url}:g(e),Se=e=>e.transport==="http"?{serverUrl:e.url}:g(e),ke=e=>({args:["-y","mcp-remote",e],command:"npx"}),Ee=e=>e.transport==="http"?ke(e.url):g(e),$e=e=>e.transport==="http"?{url:e.url}:g(e),je=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}},Oe=e=>e.transport==="http"?{disabled:!1,type:"streamableHttp",url:e.url}:{disabled:!1,...g(e)},Ce=({home:e,platform:t})=>{if(t==="darwin")return{global:i(e,"Library","Application Support","Claude","claude_desktop_config.json")};if(t==="win32"){const r=process.env.APPDATA;return r===void 0||r===""?{}:{global:i(r,"Claude","claude_desktop_config.json")}}return t==="linux"?{global:i(e,".config","Claude","claude_desktop_config.json")}:{}},_e=(e,t)=>ce({mcp_servers:{[e]:t.transport==="http"?{url:t.url}:{args:[...t.args],command:t.command,...t.env===void 0?{}:{env:t.env}}}}),v=[{buildEntry:j,paths:({projectRoot:e})=>({project:i(e,".mcp.json")}),format:"json",id:"claude-code",key:"mcpServers",label:"Claude Code"},{buildEntry:j,paths:({home:e,projectRoot:t})=>({global:i(e,".cursor","mcp.json"),project:i(t,".cursor","mcp.json")}),format:"json",id:"cursor",key:"mcpServers",label:"Cursor"},{buildEntry:j,paths:({projectRoot:e})=>({project:i(e,".vscode","mcp.json")}),format:"json",id:"vscode",key:"servers",label:"VS Code (GitHub Copilot)"},{buildEntry:be,paths:({home:e,projectRoot:t})=>({global:i(e,".gemini","settings.json"),project:i(t,".gemini","settings.json")}),format:"json",id:"gemini",key:"mcpServers",label:"Gemini CLI"},{buildEntry:Ee,paths:Ce,format:"json",id:"claude-desktop",key:"mcpServers",label:"Claude Desktop"},{buildEntry:Se,paths:({home:e})=>({global:i(e,".codeium","windsurf","mcp_config.json")}),format:"json",id:"windsurf",key:"mcpServers",label:"Windsurf"},{buildEntry:je,paths:({home:e,projectRoot:t})=>({global:i(e,".config","opencode","opencode.json"),project:i(t,"opencode.json")}),format:"json",id:"opencode",key:"mcp",label:"OpenCode"},{buildEntry:Oe,paths:({home:e})=>({global:i(e,".cline","mcp.json")}),format:"json",id:"cline",key:"mcpServers",label:"Cline"},{buildEntry:$e,paths:({home:e})=>({global:i(e,".config","zed","settings.json")}),format:"json",id:"zed",key:"context_servers",label:"Zed"},{paths:({home:e,projectRoot:t})=>({global:i(e,".codex","config.toml"),project:i(t,".codex","config.toml")}),format:"manual",id:"codex",label:"Codex CLI",renderSnippet:_e}],P=v.map(e=>e.id),Me=e=>v.find(t=>t.id===e.toLowerCase()),Ue=["global","project"],p=(e,t)=>{const r=ae(t,e);return r.length>0&&!r.startsWith("..")?r:e},xe=(e,t)=>{const r=e.paths(t);return Ue.flatMap(n=>{const o=r[n];return o===void 0?[]:[{client:e,path:o,scope:n}]})},Le=(e,t,r,n)=>{const o=e.paths(t),l=r==="global"?"project":"global",a=o[r]??(n?void 0:o[l]);if(a!==void 0)return{client:e,path:a,scope:o[r]===void 0?l:r}},Ne=e=>v.filter(t=>Object.values(t.paths(e)).some(r=>m(r))),I=(e,t,r,n)=>{if(e.length===0)return t();const o=[];for(const l of e){const a=Me(l);if(a===void 0){r.error(`mcp ${n}: unknown client "${l}". Known clients: ${P.join(", ")}.`);return}o.push(a)}return o},Ae=e=>e.client.format==="json",De="https://lunora.sh/mcp",R="lunora-docs",H="lunora",Te=e=>m(i(e,"lunora"))&&le(e)!==void 0,Fe=e=>{const{args:t,command:r}=fe(e,"lunora",["mcp","serve"]);return{args:t,command:r,transport:"stdio"}},Pe=e=>({transport:"http",url:e}),Ie=e=>({home:e.home,platform:e.platform,projectRoot:e.cwd}),W=(e,t,r)=>Le(e,Ie(r),r.scope??t.preferredScope,r.scope!==void 0||!t.allowScopeFallback),Re=(e,t,r)=>{const n=W(e,t,r);if(n===void 0){r.logger.warn(`${e.label}: has no ${r.scope??t.preferredScope}-scoped config — skipped "${t.name}".`);return}const{path:o}=n,l=e.buildEntry(t.spec);if(r.print===!0){const d=p(o,r.cwd);return r.force!==!0&&se({key:e.key,name:t.name,path:o})?(r.logger.info(`${e.label}: "${t.name}" already configured in ${d} — a real install would skip it (re-run with --force to replace).`),{action:"printed",path:o}):(r.logger.info(`${e.label} → ${d}
|
|
2
|
+
${JSON.stringify({[e.key]:{[t.name]:l}},void 0,4)}`),{action:"printed",path:o})}const a=ie({entry:l,force:r.force===!0,key:e.key,name:t.name,path:o}),c=p(o,r.cwd);return a.action==="invalid"?r.logger.error(`${e.label}: ${c} is not valid JSON (${a.error??"unknown error"}) — left untouched.`):a.action==="skipped"?r.logger.info(`${e.label}: "${t.name}" already configured in ${c} — re-run with --force to replace it.`):r.logger.success(`${e.label}: ${a.action==="created"?"created":"updated"} ${c} with "${t.name}".`),{action:a.action,path:o}},He=(e,t,r)=>{const n=W(e,t,r)?.path;if(n===void 0){r.logger.warn(`${e.label}: no known config location on ${r.platform} — skipped.`);return}return r.logger.info(`${e.label}: add this to ${p(n,r.cwd)}
|
|
3
|
+
|
|
4
|
+
${e.renderSnippet(t.name,t.spec)}`),{action:"printed",path:n}},We=e=>{const t=[];return e.localOnly!==!0&&t.push({allowScopeFallback:!0,name:R,preferredScope:"global",spec:Pe(e.docsUrl??De)}),e.docsOnly!==!0&&Te(e.cwd)&&t.push({allowScopeFallback:!1,name:H,preferredScope:"project",spec:Fe(me(e.cwd))}),t},Ge=e=>{const t=e.home??C(),r=e.platform??process.platform;e.logger.info("Supported MCP clients:");for(const n of v){const o=n.paths({home:t,platform:r,projectRoot:e.cwd}),l=a=>{const c=o[a];return c===void 0?"—":p(c,e.cwd)};e.logger.info(` ${n.id.padEnd(15)} ${n.label.padEnd(24)} project: ${l("project").padEnd(30)} global: ${l("global")}`)}return{code:0,written:[]}},Je=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).",Ve=(e,t,r)=>{const n=[];for(const o of e)for(const l of t){const a=o.format==="json"?Re(o,l,r):He(o,l,r);a!==void 0&&n.push({action:a.action,client:o.id,path:a.path,server:l.name})}return n},ze=e=>{const t=e.home??C(),r=e.platform??process.platform,n=I(e.clients,()=>Ne({home:t,platform:r,projectRoot:e.cwd}),e.logger,"install");if(n===void 0)return{code:f.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: ${P.join(", ")}.`),{code:f.NOT_FOUND,written:[]};e.clients.length===0&&e.logger.info(`Detected ${String(n.length)} configured client(s): ${n.map(a=>a.label).join(", ")}.`);const o=We(e);if(o.length===0)return e.logger.error(`mcp install: nothing to install — ${Je(e)}`),{code:f.USAGE,written:[]};const l=Ve(n,o,{...e,home:t,platform:r});return l.some(a=>a.action==="created"||a.action==="updated")&&e.logger.info("Restart your editor (or reload its MCP servers) to pick up the change."),{code:l.some(a=>a.action==="invalid")?1:0,written:l}},G=100,J=1e3,N=e=>({content:[{text:JSON.stringify(e,void 0,2),type:"text"}]}),Ke=e=>({content:[{text:e,type:"text"}]}),qe=e=>{const t=typeof e=="string"?Number(e):e;return typeof t!="number"||!Number.isFinite(t)?G:Math.min(J,Math.max(1,Math.floor(t)))},A=(e,t)=>{if(t===void 0)return;const r=$(e,ge);return we(r,$(e,t))?$(e,t):void 0},Be=(e,t)=>{const r=F(e,"utf8").split(`
|
|
5
|
+
`);return r.at(-1)===""&&r.pop(),r.slice(-t).join(`
|
|
6
|
+
`)},Xe=e=>[{definition:{annotations:{destructiveHint:!1,idempotentHint:!0,openWorldHint:!1,readOnlyHint:!0,title:"Check the local dev server"},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 t=b(e);return N(t===void 0?{hint:"Start it with `lunora dev` in the project directory.",running:!1}:{background:t.background===!0,logFile:A(e,t.logFile),mode:t.mode,pid:t.pid,running:!0,startedAt:t.startedAt,studioUrl:t.studioUrl,url:t.url})}},{definition:{annotations:{destructiveHint:!1,idempotentHint:!0,openWorldHint:!1,readOnlyHint:!0,title:"Read the local dev server log"},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(G)}, max ${String(J)})`,type:"number"}},type:"object"},name:"lunora_dev_logs"},handle:async t=>{const r=b(e);if(r===void 0)return{content:[{text:"no dev server is running — start one with `lunora dev`",type:"text"}],isError:!0};const n=A(e,r.logFile);if(n===void 0||!m(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 o=qe(t.lines),l=Be(n,o);return Ke(l.length===0?"(the dev server log is empty)":l)}}],O={methods:[],openrpc:"1.3.2"},Ze=e=>e instanceof Error&&e.code==="ENOENT",Qe=new Set(["127.0.0.1","::1","localhost"]),V=e=>{try{const{hostname:t}=new URL(e);return Qe.has(t.startsWith("[")?t.slice(1,-1):t)}catch{return!1}},D=e=>{const t=e.url??b(e.cwd)?.url;if(t===void 0||t.length===0)return;if(e.token!==void 0&&e.token.length>0)return{token:e.token,url:t};if(!V(t))return{url:t};const r=he(e.cwd);return r===void 0||r.length===0?{url:t}:{token:r,url:t}},z=async e=>{await new Promise(t=>{const r=()=>{t()};e.onclose=r,process.stdin.once("close",r),process.stdin.once("end",r)})},Ye=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}
|
|
7
|
+
`;const r=!V(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} (${r})
|
|
8
|
+
`},K=e=>{process.stderr.write(e)},et=async(e,t)=>{const r=e.writeError??K,n=pe(e.cwd,"lunora","_generated","openrpc.json"),o=()=>e.url??b(e.cwd)?.url;let l,a;const c=s=>{r(`lunora mcp serve --functions: kept the last tool list — the rewritten document did not load: ${String(s)}
|
|
9
|
+
`)};let d={mtimeMs:-1,spec:O};const y=()=>{let s;try{s=ne(n).mtimeMs,a=void 0}catch(u){if(Ze(u))d.spec!==O&&(d={mtimeMs:-1,spec:O});else{const E=u.code??String(u);a!==E&&(a=E,c(u))}return d.spec}if(s!==d.mtimeMs)try{d={mtimeMs:s,spec:JSON.parse(F(n,"utf8"))}}catch(u){l!==s&&(l=s,c(u))}return d.spec};let w;try{w=await t({allowWrites:e.allowWrites===!0,onReloadError:c,openRpcSpec:y,url:o,version:e.version,...e.token===void 0||e.token.length===0?{}:{token:e.token}})}catch(s){const u=s instanceof Error?s.message:String(s);return r(`lunora mcp serve --functions: failed to start — ${u}
|
|
10
|
+
`),{code:1,deployment:void 0}}const q=e.token===void 0||e.token.length===0,S=o(),B=S===void 0||S.length===0?"no deployment yet (start `lunora dev` or pass --url; calls fail until one runs)":S,X=m(n)?"":" (no openrpc.json yet: run `lunora codegen --api-spec openrpc`; the functions appear once it exists)";r(`lunora mcp serve --functions: ready — ${B}${q?" (no --token: only public functions answer, and writes are refused)":""}${X}
|
|
11
|
+
`);const k=L(n),_=s=>{r(`lunora mcp serve --functions: the tool list will not be announced on a change — ${String(s)}
|
|
12
|
+
`)},Z=()=>{if(m(k))return k;const s=L(k);return m(s)?s:e.cwd};let M=m(n),h;const U=()=>{const s=Z();if(h?.directory!==s){h?.watcher.close(),h=void 0;try{const u=oe(s,(E,Q)=>{const x=m(n),Y=Q==="openrpc.json"||x!==M;M=x,U(),Y&&w.sendToolListChanged?.().catch(ee=>{r(`lunora mcp serve --functions: could not announce the tool list change — ${String(ee)}
|
|
13
|
+
`)})});u.on("error",_),h={directory:s,watcher:u}}catch(u){_(u)}}};U();try{await z(w)}finally{h?.watcher.close();try{await w.close?.()}catch(s){r(`lunora mcp serve --functions: could not close the server — ${String(s)}
|
|
14
|
+
`)}}return{code:0,deployment:void 0}},tt=async(e,t=ve,r=ye)=>{if(e.functions===!0)return et(e,r);const n=e.writeError??K;let o;try{o=await t({allowWrites:e.allowWrites===!0,deployment:()=>D(e),docs:e.noDocs===!0?!1:{...e.docsUrl===void 0?{}:{baseUrl:e.docsUrl}},extraTools:Xe(e.cwd),version:e.version})}catch(a){const c=a instanceof Error?a.message:String(a);return n(`lunora mcp serve: failed to start — ${c}
|
|
15
|
+
`),{code:1,deployment:void 0}}const l=D(e);return n(Ye(l)),await z(o),{code:0,deployment:l}},rt=e=>{const t=[];return e.localOnly!==!0&&t.push(R),e.docsOnly!==!0&&t.push(H),t},nt=(e,t,r,n)=>{const o=ue({key:e.key,name:t,path:r}),l=p(r,n.cwd);return o.action==="removed"?n.logger.success(`${e.label}: removed "${t}" from ${l}.`):o.action==="invalid"&&n.logger.error(`${e.label}: ${l} is not valid JSON (${o.error??"unknown error"}) — left untouched.`),{action:o.action,path:r}},ot=(e,t,r,n)=>{const o=de({key:e.key,name:t,path:r}),l=p(r,n.cwd);return o==="invalid"?(n.logger.error(`${e.label}: ${l} is not valid JSON — a real run would report it and exit non-zero.`),{action:"invalid",path:r}):o==="absent"?{action:"absent",path:r}:(n.logger.info(`${e.label}: would remove "${t}" from ${l}.`),{action:"removed",path:r})},lt=(e,t,r)=>e.flatMap(n=>xe(n,t)).filter(Ae).filter(n=>r===void 0||n.scope===r),at=e=>{const t=e.home??C(),r=e.platform??process.platform,n=I(e.clients,()=>v,e.logger,"uninstall");if(n===void 0)return{code:f.USAGE,removed:[]};const o=rt(e);if(o.length===0)return e.logger.error("mcp uninstall: nothing to remove — `--docs-only` and `--local-only` are mutually exclusive, pass at most one."),{code:f.USAGE,removed:[]};const l=[],a={home:t,platform:r,projectRoot:e.cwd};for(const c of lt(n,a,e.scope))for(const d of o){const y=e.print===!0?ot(c.client,d,c.path,e):nt(c.client,d,c.path,e);y.action!=="absent"&&l.push({...y,client:c.client.id,server:d})}return l.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:l.some(c=>c.action==="invalid")?1:0,removed:l}},T=e=>e.global===!0?"global":e.project===!0?"project":void 0,ct=async(e,t)=>{const{code:r}=await tt({allowWrites:t.allowWrites===!0,cwd:e,functions:t.functions===!0,noDocs:t.docs===!1,version:te,...t.docsUrl===void 0?{}:{docsUrl:t.docsUrl},...t.token===void 0?{}:{token:t.token},...t.url===void 0?{}:{url:t.url}});return{code:r}},Et=re(async({argument:e,cwd:t,logger:r,options:n})=>{const[o,...l]=e;if(o==="serve")return ct(t,n);if(o==="uninstall"){const a=T(n),{code:c}=at({clients:l,cwd:t,docsOnly:n.docsOnly===!0,localOnly:n.localOnly===!0,logger:r,print:n.print===!0,...a===void 0?{}:{scope:a}});return{code:c}}if(o==="install"){if(n.list===!0)return Ge({cwd:t,logger:r});const a=T(n),{code:c}=ze({clients:l,cwd:t,docsOnly:n.docsOnly===!0,force:n.force===!0,localOnly:n.localOnly===!0,logger:r,print:n.print===!0,...a===void 0?{}:{scope:a},...n.docsUrl===void 0?{}:{docsUrl:n.docsUrl}});return{code:c}}return r.error("mcp: unknown subcommand. Usage: lunora mcp <install|uninstall|serve>"),{code:f.USAGE}});export{Et as execute};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{existsSync as b,readFileSync as L,realpathSync as A}from"node:fs";import{join as h}from"node:path";import{readProjectTarget as u,DEFAULT_TARGET as f,readServiceBindings as B}from"@lunora/codegen";import{DEV_VARS_FILE as m,parseDevVariableEntries as C,isPlaceholderValue as O,readProjectDependencies as M,discoverSchemaInfo as G,inferLunoraBindings as V,resolveSchemaDirectory as K,probeCelldToolchain as q,D1_PLACEHOLDER_ID as W}from"@lunora/config";import{GLOBAL_FETCH_STRICTLY_PUBLIC_FLAG as g,resolveObservabilitySampling as y,findWranglerFile as T,readWranglerJsonc as D,buildBindingManifest as H,validateWranglerProject as z,UNEXPORTED_CLASS_MARKER as x,detectCloudflareCliConfig as J,collectExportGaps as Y}from"@lunora/config/cloudflare";import{a as Q,i as X,m as Z,c as ee,b as te,d as ne,e as oe,f as re}from"../packem_shared/vectorize-metadata-BVSF8z2h.mjs";import{r as se,d as ae}from"../packem_shared/admin-token-VdUnvnKW.mjs";import{r as ie,n as w,c as ce}from"../packem_shared/cloudflare-credentials-BVmZnDZk.mjs";import{d as le}from"../packem_shared/command-B6vu47iR.mjs";import{i as de}from"../packem_shared/path-containment-CgxYZggb.mjs";import{A as $,a as R,b as k}from"../packem_shared/variables-CPYyJtsL.mjs";const ue=(o,t)=>{const e=new Set,n=s=>{for(const[a,c]of Object.entries(s??{}))typeof c=="string"&&c.trim().length>0&&e.add(a)};n(o.vars);for(const s of Object.values(o.env??{}))n(s.vars);const r=h(t,m);if(b(r))try{n(Object.fromEntries(C(L(r,"utf8")).map(s=>[s.key,s.value])))}catch{}return e},fe=(o,t,e,n)=>{if(o===void 0||!e)return;const r=ue(o,t),s=r.has($),a=o.ai?.binding;!s&&(typeof a!="string"||a.length===0)&&n.push({code:"ai-binding-missing",fix:`Run \`lunora dev\` (it adds the binding), add \`"ai": { "binding": "AI" }\` to wrangler.jsonc, or set ${$} to an OpenAI-compatible proxy.`,level:"warn",message:"the project uses ctx.ai (@lunora/ai / env.AI) but wrangler.jsonc declares no `ai` binding — model calls will fail at runtime."}),r.has(R)&&n.push({code:"ai-gateway-token-unused",fix:"Make the gateway unauthenticated for ctx.ai, or remove the token. A bring-your-own AI SDK provider built with `resolveAiGateway` does send it.",level:"warn",message:`${R} is set, but ctx.ai's Workers AI binding cannot send a gateway token — it is ignored on that path.`}),!s&&!r.has(k)&&n.push({code:"ai-gateway-default",fix:`Run \`lunora cloudflare ai-gateway\` to create a gateway for this app and write ${k} into wrangler vars.`,level:"info",message:`no ${k} in vars or ${m} — \`<provider>/<model>\` slugs route through the account's \`default\` AI Gateway.`})},pe=(o,t,e)=>{if(o===void 0||!t)return;const n=[];(o.compatibility_flags??[]).includes(g)||n.push("the top level");for(const[r,s]of Object.entries(o.env??{}))s.compatibility_flags!==void 0&&!s.compatibility_flags.includes(g)&&n.push(`env.${r}`);n.length>0&&e.push({code:"cimd-fetch-not-strictly-public",fix:`Add "${g}" to "compatibility_flags" in wrangler.jsonc.`,level:"warn",message:`@lunora/auth/cimd/workers is imported, but ${n.join(", ")} of wrangler.jsonc lacks the ${g} compatibility flag — workersCimdFetch() refuses to build without it.`})},N=5e3,he="https://api.cloudflare.com/client/v4/user/tokens/verify",U=o=>{if(typeof o!="object"||o===null||!("result"in o)||"success"in o&&o.success===!1)return;const{result:t}=o;return typeof t=="object"&&t!==null&&"status"in t&&typeof t.status=="string"?t.status:void 0},ge=async(o,t)=>{const e=await t(he,{headers:{Authorization:`Bearer ${o}`},signal:AbortSignal.timeout(N)}),n=await e.json().catch(()=>{});return{reported:e.ok?U(n):void 0,status:e.status}},me=async(o,t,e)=>{const n=await ce({accountId:o,apiToken:t,fetch:e,init:{signal:AbortSignal.timeout(N)},path:"/tokens/verify"});return n.ok?{reported:U(n.body),status:200}:{reported:void 0,status:n.status}},ve=async(o,t,e)=>{const n=await me(o,t,e);return n.reported!==void 0?n.reported==="active"?{verdict:"active"}:{verdict:"rejected"}:n.status===401||n.status===403?{verdict:"rejected"}:{reason:`HTTP ${String(n.status)}`,verdict:"unchecked"}},be=async(o,t,e)=>{const n=await ge(o,e);if(n.reported!==void 0)return n.reported==="active"?{verdict:"active"}:{verdict:"rejected"};if(n.status!==401&&n.status!==403)return{reason:`HTTP ${String(n.status)}`,verdict:"unchecked"};if(t.length===0)return{reason:"the user endpoint refused it, and no account id is set to check an account-owned token",verdict:"unchecked"};const r=await Promise.all(t.map(async s=>await ve(s,o,e).catch(a=>({reason:a instanceof Error?a.message:String(a),verdict:"unchecked"}))));return r.find(s=>s.verdict==="active")??r.find(s=>s.verdict==="unchecked")??{verdict:"rejected"}},we=o=>{const t=[o?.account_id,...Object.values(o?.env??{}).map(e=>e?.account_id)];return[...new Set(t.map(e=>w(e)).filter(e=>e!==void 0))]},ke=async(o,t,e)=>{const n=t.environment??process.env,r=we(o),{accountId:s,token:a}=ie(n,r[0]),c=w(n.CLOUDFLARE_ACCOUNT_ID)===void 0?r:[s].filter(d=>d!==void 0);if(a===void 0){e.push({code:"cloudflare-token-unchecked",fix:"Set CLOUDFLARE_API_TOKEN to verify it.",level:"info",message:"the Cloudflare API token was not verified: CLOUDFLARE_API_TOKEN is not set."});return}const i=t.fetch??globalThis.fetch.bind(globalThis);let l;try{l=await be(a,c,i)}catch(d){l={reason:d instanceof Error?d.message:String(d),verdict:"unchecked"}}l.verdict==="active"?e.push({code:"cloudflare-token-ok",level:"pass",message:"the Cloudflare API token is active."}):l.verdict==="rejected"?e.push({code:"cloudflare-token-rejected",fix:"Create a token at https://dash.cloudflare.com/profile/api-tokens with the Workers Scripts Edit permission, then set CLOUDFLARE_API_TOKEN to it.",level:"fail",message:"the Cloudflare API token is not active, so deploys with it will fail."}):e.push({code:"cloudflare-token-unchecked",level:"info",message:`the Cloudflare API token could not be verified (${l.reason}).`})},S=o=>{const{logs:t,traces:e}=y(o);return Object.entries({logs:t,traces:e}).filter(([,n])=>n.enabled&&n.headSamplingRate>=1).map(([n])=>n)},ye=(o,t)=>{if(o===void 0)return;const e=[],n=S(o.observability);n.length>0&&e.push(`${n.join(" + ")} (top level)`);for(const[r,s]of Object.entries(o.env??{})){const a=s?.observability;if(a===void 0)continue;const c=S(a);c.length>0&&e.push(`${c.join(" + ")} (env.${r})`)}e.length!==0&&t.push({code:"observability-full-sampling",fix:"For a high-traffic Worker, lower head_sampling_rate in wrangler.jsonc: under observability for logs, under observability.traces for traces — e.g. 0.1 keeps 10% of requests. Lunora never changes a rate you set.",level:"info",message:`observability samples every request (head_sampling_rate 1) for ${e.join(", ")}. From 2026-12-01 Workers Observability is billed: Free caps ingestion at 0.5 GB/day; Paid includes 50 GB per billing cycle, then $0.25/GB.`})},v=o=>o.enabled&&o.headSamplingRate>0,j=o=>{if(!o||o.redact_query_string===!0)return!1;const{logs:t,traces:e}=y(o);return v(t)||v(e)},E=o=>{const{logs:t,traces:e}=y(o);return[v(t)&&"request logs",v(e)&&"traces"].filter(Boolean).join(" and ")},_e=(o,t)=>{if(o===void 0)return;const e=[],n=new Set;j(o.observability)&&(e.push("top level"),n.add(E(o.observability)));for(const[r,s]of Object.entries(o.env??{})){const a=s?.observability;j(a)&&(e.push(`env.${r}`),n.add(E(a)))}e.length!==0&&t.push({code:"observability-query-unredacted",fix:'Set "redact_query_string": true in each observability block listed above in wrangler.jsonc. Lunora never changes a value you set.',level:"warn",message:`${[...n].join(" / ")} keep query strings (redact_query_string is not true) for ${e.join(", ")}. Emailed auth links carry their token in the query, so that token is stored with the request URL.`})},P={ai:"Workers AI",browser:"Browser Rendering",images:"Cloudflare Images (Image Transformations)"},I=["Argo Smart Routing","Log Explorer"],Ae=o=>{const t=[["top level",o],...Object.entries(o.env??{}).flatMap(([n,r])=>r?[[`env.${n}`,r]]:[])],e=new Map;for(const[n,r]of t)for(const s of H(r).bindings)P[s.type]!==void 0&&e.set(s.type,[...e.get(s.type)??[],n]);return e},xe=(o,t)=>{if((u(o)??f)!=="cloudflare")return;const e=T(o),n=e===void 0?void 0:D(e).parsed;if(n!==void 0)for(const[r,s]of Ae(n)){const a=P[r]??r;t.push({code:"paid-product-bound",fix:"Create an account budget alert in the dashboard: Manage Account > Billing > Billable Usage > Create budget alert. Lunora cannot create or read one.",level:"info",message:`${a} is bound (${s.join(", ")}) and billed per use. No documented usage-alert product covers it, and lunora cannot read budget alerts, so an account budget alert is the only cap.`})}t.push({code:"paid-product-unknown",level:"info",message:`enablement of ${I.join(" and ")} cannot be read by lunora (dashboard settings); check the dashboard if your account uses ${I.length>1?"them":"it"}.`})},$e=(o,t)=>{for(const e of B(o).services)for(const n of e.publicScopes){const r=n===""?"":` (env.${n})`;t.push({code:"service-workers-dev",fix:`If ${e.name} has no public route (custom domain or route, including ones set outside ${e.wranglerPath}), set \`"workers_dev": false\`${r}. Keep its internal auth (HMAC) either way.`,level:"warn",message:`service ${e.name} (${e.worker}) has no route in its wrangler config and still serves on workers.dev${r}; a custom domain set elsewhere would also be public.`})}},F=o=>{const t=T(o);if(t===void 0)return{parsed:void 0,path:void 0};const{parsed:e}=D(t);return{parsed:e,path:t}},Re=(o,t,e,n)=>{if(e===void 0){n.push({code:"wrangler-missing",fix:"Run `lunora init` (or `lunora dev`) to scaffold and reconcile wrangler.jsonc.",level:"fail",message:"wrangler.jsonc not found."});return}if(t===void 0){n.push({code:"wrangler-unparseable",fix:`Check ${e} is valid JSONC.`,level:"fail",message:`Could not parse ${e}.`});return}const{report:r}=z({projectRoot:o});for(const c of r.errors.filter(i=>i.includes(x)))n.push({code:"wrangler-class-unexported",level:"fail",message:c});for(const c of r.warnings.filter(i=>i.includes("LUNORA_ORIGIN_URL")))n.push({code:"scheduler-origin-missing",fix:"Set LUNORA_ORIGIN_URL in wrangler vars to the worker's public URL (or `wrangler secret put LUNORA_ORIGIN_URL`).",level:"warn",message:c});const s=c=>c.includes(x)||c.includes("SHARD");for(const c of r.errors.filter(i=>!s(i)))n.push({code:"wrangler-invalid",fix:"Fix the reported wrangler.jsonc problem; `lunora verify` reports the same set.",level:"fail",message:c});for(const c of r.warnings.filter(i=>!i.includes("LUNORA_ORIGIN_URL")))n.push({code:"wrangler-advisory",level:"warn",message:c});const a=r.errors.find(c=>c.includes("SHARD"));a===void 0?n.push({code:"wrangler-shard-binding-ok",level:"pass",message:"wrangler.jsonc present with a SHARD durable-object binding."}):n.push({code:"wrangler-shard-binding-missing",fix:"Run `lunora dev` to auto-reconcile, or add the binding manually.",level:"fail",message:a})},Se=(o,t)=>{b(h(o,"lunora.json"))&&t.push({code:"stale-lunora-json",fix:'Move `target` / `remote` into `lunora.config.ts` (`export default { target: "…" }`), then delete lunora.json.',level:"warn",message:"lunora.json is present but no longer read — lunora.config.* replaced it, so any `target` or `remote` in it is being ignored."})},je=(o,t)=>{const e=J(o);e!==void 0&&t.push({code:"cf-config-present",fix:e.fix,level:"warn",message:e.message})},Ee=(o,t)=>{o===void 0||o.limits?.cpu_ms!==void 0||t.push({code:"cpu-limit-missing",fix:'Add `"limits": { "cpu_ms": 30000 }` to wrangler.jsonc, tuned to your slowest legitimate handler.',level:"info",message:"no limits.cpu_ms is set — a runaway handler can burn CPU up to the platform default before anything stops it."})},Ie=(o,t)=>{const e=(o?.r2_buckets??[]).map(n=>n?.bucket_name).filter(n=>typeof n=="string"&&n.length>0);e.length!==0&&t.push({code:"r2-lifecycle-unset",fix:"wrangler r2 bucket lifecycle list <bucket> — add an abort-incomplete-multipart rule if none exists.",level:"info",message:`R2 bucket(s) ${e.join(", ")}: verify a lifecycle rule aborts incomplete multipart uploads — orphaned parts are billed but invisible in a listing.`})},Le=(o,t)=>{const{error:e,info:n}=G(o,"lunora");if(e!==void 0){t.push({code:"schema-unreadable",fix:"Fix the parse error, then re-run `lunora doctor`. `lunora codegen` reports the same failure with the offending source.",level:"fail",message:`lunora/schema.ts could not be parsed, so every schema-derived check was skipped: ${e}`});return}for(const r of n?.vectorMetadata??[]){const s=Z(r.kind);if(s===void 0){t.push({code:"vector-metadata-unfilterable",fix:"Filter on a string, number or boolean column, or drop it from `metadata`.",level:"warn",message:`vector index "${r.index}" declares metadata "${r.property}", whose type Vectorize cannot filter on.`});continue}t.push({code:"vector-metadata-index-required",fix:`wrangler ${ee({index:r.index,property:r.property,type:s}).join(" ")}`,level:"info",message:`vector index "${r.index}" filters on metadata "${r.property}" — that needs a Vectorize metadata index (\`lunora deploy\` creates it).`})}},Ce=o=>{const t=o?.d1_databases;return Array.isArray(t)?t.filter(Boolean):[]},Oe=(o,t,e)=>{const n=Ce(o),r=[];for(const s of n){const a=typeof s.database_id=="string"?s.database_id:"";if(e?oe(a)&&a!==W:re(a)){const i=typeof s.binding=="string"&&s.binding.length>0?s.binding:"<unnamed>";r.push({code:"d1-placeholder-id",fix:e?"Set database_id to the database celld should use.":"Run `lunora doctor --fix` to create the database and write its id into wrangler.jsonc, or run `wrangler d1 create <name>` and paste the returned database_id in yourself.",level:"fail",message:`D1 binding "${i}"${t} has a placeholder database_id ("${a||"<empty>"}").`})}}return r},Te=(o,t,e)=>{if(t===void 0)return;const n=(u(o)??f)==="celld",r=[{config:t,suffix:""},...Object.entries(n?{}:t.env??{}).map(([s,a])=>({config:a,suffix:` in env.${s}`}))];for(const{config:s,suffix:a}of r)e.push(...Oe(s,a,n))},De=(o,t)=>{if(o===void 0)return;const e=(o.send_email??[]).filter(Boolean);for(const n of e){const r=typeof n.destination_address=="string"?n.destination_address:"";if(r!==""&&O(r)){const s=typeof n.name=="string"&&n.name.length>0?n.name:"send_email";t.push({code:"email-destination-placeholder",fix:"Set destination_address to a verified Cloudflare Email Routing address.",level:"warn",message:`send_email binding "${s}" has a placeholder destination_address ("${r}").`})}}},Ne=(o,t)=>{const e=h(o,m);if(!b(e))return;let n;try{n=L(e,"utf8")}catch{return}const r=C(n).filter(s=>X(s.key)&&O(s.value)).map(s=>s.key);r.length>0&&t.push({code:"dev-vars-missing-secret",fix:"Run `lunora dev` to auto-generate secrets, or fill them in by hand.",level:"warn",message:`${m} has unfilled secret value(s): ${r.join(", ")}.`})},Ue=(o,t)=>{const{source:e}=se({cwd:o});e===void 0?t.push({code:"admin-token-missing",fix:"Set LUNORA_ADMIN_TOKEN (env or `.dev.vars`) to enable admin RPCs / studio.",level:"info",message:"LUNORA_ADMIN_TOKEN is not set."}):t.push({code:"admin-token-set",level:"pass",message:`LUNORA_ADMIN_TOKEN is set (${ae(e)}).`})},Pe=async(o,t)=>{try{return await V({projectRoot:o,schemaDir:K(o)})}catch(e){t.push({code:"declared-export-unchecked",fix:"Make sure the worker entry resolves (see `lunora codegen`), then re-run.",level:"warn",message:`could not check whether declared containers/workflows/agents are re-exported by the worker entry: ${e instanceof Error?e.message:String(e)}`});return}},Fe=(o,t)=>{const e=Y(o),n=[...o.containers.map(r=>({...r,kind:"container"})),...o.workflows.map(r=>({...r,kind:"workflow"})),...o.agents.map(r=>({...r,kind:"agent"}))];for(const r of n.filter(s=>s.exported))t.push({code:"declared-export-ok",level:"pass",message:`${r.kind} "${r.exportName}" is exported by the worker entry.`});for(const r of e)t.push({code:"declared-export-missing",fix:`Add \`export * from "./lunora/_generated/${r.module}"\` to your worker entry (or re-run \`vis generate lunora-${r.kind}\`).`,level:"fail",message:`${r.kind} "${r.exportName}" is declared but ${r.className} is not exported by the worker entry.`})},Be=/^[\^~><= ]+/u,Me=/^(?<core>\d+\.\d+\.\d+)(?:-(?<channel>[a-z]+)\.(?<counter>\d+))?$/u,Ge=o=>{const t=o.replace(Be,"").trim(),e=Me.exec(t);if(!e?.groups)return;const{channel:n,core:r,counter:s}=e.groups;return{channel:n??"",core:r??"",counter:s===void 0?void 0:Number.parseInt(s,10),raw:t}},Ve=(o,t)=>{const e=M(o),n=[];for(const[i,l]of Object.entries(e)){if(i!=="lunorash"&&!i.startsWith("@lunora/"))continue;const d=Ge(l);d&&n.push({name:i,version:d})}if(n.length<2)return;const r=i=>i.map(l=>`${l.name}@${l.version.raw}`).join(", "),s=new Set(n.map(i=>i.version.core)),a=new Set(n.map(i=>i.version.channel));if(s.size>1){t.push({code:"version-skew-cores",fix:'Run `pnpm update "@lunora/*" lunorash` (or `npm`/`yarn` equivalent) so every Lunora package moves to the same release.',level:"warn",message:`Lunora packages span ${String(s.size)} different versions: ${r(n)}.`});return}if(a.size>1){t.push({code:"version-skew-channels",fix:"Pick one channel (all stable, or all alpha/beta) and update the odd package out.",level:"warn",message:`Lunora packages mix release channels (${[...a].map(i=>i===""?"stable":i).join(" + ")}): ${r(n)}.`});return}const c=n.map(i=>i.version.counter).filter(i=>i!==void 0);if(c.length>1){const i=Math.min(...c),l=Math.max(...c);t.push({code:"version-counter-spread",level:"info",message:c.length===n.length&&i===l?`Lunora packages are all at ${[...a][0]??""}.${String(l)}.`:`Lunora pre-release counters span ${String(i)}–${String(l)}: ${r(n)}.`})}},Ke=[h("@lunora","cli"),"lunorash"],qe=(o,t,e)=>{if(t===void 0)return;const n=[];for(const s of Ke){const a=h(o,"node_modules",s);if(b(a))try{n.push(A(a))}catch{}}if(n.length===0)return;let r;try{r=A(t)}catch{return}n.some(s=>de(s,r))||e.push({code:"cli-shadowed",fix:"Run the project's own CLI: `pnpm exec lunora …` (or `npx lunora …`).",level:"warn",message:`the running lunora (${r}) is not the project's own install (${n.join(", ")}).`})},We={full:{code:"do-class-budget-full",level:"warn"},near:{code:"do-class-budget-near",level:"warn"},ok:{code:"do-class-budget-ok",level:"pass"},unchecked:{code:"do-class-budget-unchecked",level:"info"}},He=o=>{const t=new Map,e=(n,r)=>{const s=w(n);s!==void 0&&t.set(s,[...t.get(s)??[],r])};e(o?.account_id,"top level");for(const[n,r]of Object.entries(o?.env??{}))e(r?.account_id,`env.${n}`);return t},ze=async(o,t,e,n)=>{if((u(o)??f)!=="cloudflare")return;const s=w((e.environment??process.env).CLOUDFLARE_ACCOUNT_ID)!==void 0?[]:[...He(t)],a=s.length===0?[[void 0,[]]]:s,c=await Promise.all(a.map(async([i,l])=>({accountId:i,blocks:l,budget:await te({accountId:i,environment:e.environment,fetch:e.fetch})})));for(const{accountId:i,blocks:l,budget:d}of c)n.push({...We[d.verdict],message:c.length>1?`account ${String(i)} (${l.join(", ")}): ${d.message}`:d.message,...d.fix===void 0?{}:{fix:d.fix}})},Je="CELLD_BUCKET is not set — a live `lunora deploy` needs it to name the fleet bucket; `lunora dev` and a dry run do not.",Ye=async(o,t,e)=>{if((u(o)??f)!=="celld")return;const n={...process.env,...t.environment},r=await q({dryRun:!0,env:n,purpose:"deploy"}),s=(n.CELLD_BUCKET??"").trim()===""?[...r.warnings,Je]:r.warnings;for(const a of r.errors)e.push({code:"celld-toolchain-missing",level:"fail",message:a});for(const a of s)e.push({code:"celld-toolchain-warn",level:"warn",message:a});r.errors.length===0&&s.length===0&&e.push({code:"celld-toolchain-ok",level:"pass",message:"celld, esbuild and CELLD_BUCKET are in place for a deploy."})},Qe={mismatch:{code:"artifacts-jurisdiction-mismatch",level:"fail"},missing:{code:"artifacts-namespace-missing",level:"fail"},ok:{code:"artifacts-jurisdiction-ok",level:"pass"},unchecked:{code:"artifacts-jurisdiction-unchecked",level:"warn"}},Xe=async(o,t,e,n,r)=>{if(e===void 0||t===void 0||(u(o)??f)!=="cloudflare")return;const s=[["",t],...Object.entries(t.env??{}).map(([i,l])=>[`env.${i}: `,l])],a=new Map;for(const[i,l]of s){const d=l.account_id??t.account_id;for(const p of l.artifacts??[]){const _=`${String(d)}/${String(p?.namespace)}`;typeof p?.binding=="string"&&typeof p.namespace=="string"&&!a.has(_)&&a.set(_,{accountId:d,binding:p.binding,label:i,namespace:p.namespace})}}const c=await Promise.all([...a.values()].map(async({label:i,...l})=>({check:await ne({...l,environment:n.environment,fetch:n.fetch,jurisdiction:e,missingOk:!0}),label:i})));for(const{check:i,label:l}of c)r.push({...Qe[i.verdict],message:`${l}${i.message}`,...i.fix===void 0?{}:{fix:i.fix}})},Ze=async o=>{const t=o.cwd??process.cwd(),e=[],{parsed:n,path:r}=F(t);Re(t,n,r,e),je(t,e),Te(t,n,e),De(n,e),Ee(n,e),Ie(n,e),ye(n,e),_e(n,e),Ne(t,e),Ue(t,e),Ve(t,e),Le(t,e),Se(t,e),qe(t,o.executablePath??process.argv[1],e),$e(t,e),xe(t,e);const s=await Pe(t,e);s!==void 0&&Fe(s,e),fe(n,t,s?.usesAi===!0,e),await Ye(t,o,e),await ze(t,n,o,e),(u(t)??f)==="cloudflare"&&await ke(n,o,e),await Xe(t,n,s?.jurisdiction,o,e),pe(n,s?.usesCimdWorkers===!0,e);const a={fail:0,info:0,pass:0,warn:0};for(const i of e)a[i.level]+=1;const c=a.fail>0?1:0;return{code:c,findings:e,ok:c===0,summary:a}},et={fail:"FAIL",info:"INFO",pass:"PASS",warn:"WARN"},tt=(o,t)=>{t.info("lunora doctor — project preflight");for(const r of o.findings){const s=`[${et[r.level]}] ${r.message}`;r.level==="fail"?t.error(s):r.level==="warn"?t.warn(s):t.info(s),r.fix!==void 0&&r.level!=="pass"&&t.info(` fix: ${r.fix}`)}const{fail:e,warn:n}=o.summary;e>0?t.error(`${String(e)} failure(s), ${String(n)} warning(s).`):n>0?t.warn(`0 failures, ${String(n)} warning(s).`):t.success("all checks passed.")},nt=async o=>{const{logger:t}=o,e=await Ze({...o});return tt(e,t),e},ht=le(async({cwd:o,format:t,logger:e,options:n})=>{if(n.fix===!0){const{path:s}=F(o),a=await Q({configPath:s,cwd:o,dryRun:n.dryRun===!0,logger:e});for(const c of a.applied)e.info(`fix: ${c}`);for(const c of a.skipped)e.warn(`not fixed: ${c}`)}const r=await nt({cwd:o,format:t,logger:e});return{code:r.code,data:{findings:r.findings,summary:r.summary}}});export{ht as execute,Ze as runDoctor,nt as runDoctorCommand};
|
|
@@ -1,204 +1 @@
|
|
|
1
|
-
import
|
|
2
|
-
import { mkdir, readFile, writeFile } from 'node:fs/promises';
|
|
3
|
-
import { join } from 'node:path';
|
|
4
|
-
import { r as resolveAdminBaseUrl } from '../packem_shared/admin-url-4UzT-CI4.mjs';
|
|
5
|
-
import { d as defineHandler } from '../packem_shared/command-D3lB_4Az.mjs';
|
|
6
|
-
import { a as resolveProductionWorkerUrl } from '../packem_shared/resolve-target-qbsJ_5sF.mjs';
|
|
7
|
-
import { runExportCommand, runImportCommand } from '../packem_shared/DEFAULT_IMPORT_BATCH_SIZE-Ck-2bU08.mjs';
|
|
8
|
-
|
|
9
|
-
const DEFAULT_BACKUP_DIR = ".lunora-backups";
|
|
10
|
-
const MANIFEST_FILE = "manifest.json";
|
|
11
|
-
const PITR_ENDPOINT_PATH = "/_lunora/admin/pitr";
|
|
12
|
-
const GET_PITR_BOOKMARK_OP = "__lunora_admin__:getPitrBookmark";
|
|
13
|
-
const PITR_RESTORE_OP = "__lunora_admin__:pitrRestore";
|
|
14
|
-
const isManifestEntry = (value) => typeof value === "object" && value !== null && typeof value.id === "string" && typeof value.file === "string";
|
|
15
|
-
const readManifest = async (directory) => {
|
|
16
|
-
const path = join(directory, MANIFEST_FILE);
|
|
17
|
-
if (!existsSync(path)) {
|
|
18
|
-
return [];
|
|
19
|
-
}
|
|
20
|
-
let parsed;
|
|
21
|
-
try {
|
|
22
|
-
parsed = JSON.parse(await readFile(path, "utf8"));
|
|
23
|
-
} catch (error) {
|
|
24
|
-
const message = error instanceof Error ? error.message : String(error);
|
|
25
|
-
throw new Error(`backup: ${path} exists but is not valid JSON (${message}) — refusing to overwrite it; fix or remove it manually`, { cause: error });
|
|
26
|
-
}
|
|
27
|
-
if (!Array.isArray(parsed)) {
|
|
28
|
-
throw new TypeError(`backup: ${path} exists but is not a JSON array — refusing to overwrite it; fix or remove it manually`);
|
|
29
|
-
}
|
|
30
|
-
return parsed.filter(isManifestEntry);
|
|
31
|
-
};
|
|
32
|
-
const writeManifest = async (directory, entries) => {
|
|
33
|
-
await writeFile(join(directory, MANIFEST_FILE), `${JSON.stringify(entries, void 0, 2)}
|
|
34
|
-
`, "utf8");
|
|
35
|
-
};
|
|
36
|
-
const runBackupCreate = async (options, directory) => {
|
|
37
|
-
await mkdir(directory, { recursive: true });
|
|
38
|
-
const timestamp = (options.now ?? (() => /* @__PURE__ */ new Date()))().toISOString();
|
|
39
|
-
const file = `lunora-backup-${timestamp.replaceAll(/[.:]/gu, "-")}.ndjson`;
|
|
40
|
-
const result = await runExportCommand({
|
|
41
|
-
fetchImpl: options.fetchImpl,
|
|
42
|
-
logger: options.logger,
|
|
43
|
-
out: join(directory, file),
|
|
44
|
-
prod: options.prod,
|
|
45
|
-
tables: options.tables,
|
|
46
|
-
token: options.token,
|
|
47
|
-
url: options.url
|
|
48
|
-
});
|
|
49
|
-
if (result.code !== 0) {
|
|
50
|
-
return { code: result.code };
|
|
51
|
-
}
|
|
52
|
-
const entry = { bytes: result.bytes, createdAt: timestamp, file, id: timestamp, rows: result.rows, tables: options.tables };
|
|
53
|
-
const manifest = await readManifest(directory);
|
|
54
|
-
manifest.push(entry);
|
|
55
|
-
await writeManifest(directory, manifest);
|
|
56
|
-
options.logger.success(`backup created: ${file} (${result.rows.toString()} rows, ${result.bytes.toString()} bytes)`);
|
|
57
|
-
return { code: 0, entry };
|
|
58
|
-
};
|
|
59
|
-
const runBackupList = async (options, directory) => {
|
|
60
|
-
const manifest = await readManifest(directory);
|
|
61
|
-
if (manifest.length === 0) {
|
|
62
|
-
options.logger.info(`no backups found in ${directory}`);
|
|
63
|
-
return { code: 0 };
|
|
64
|
-
}
|
|
65
|
-
for (const entry of manifest) {
|
|
66
|
-
options.logger.info(`${entry.id} ${entry.rows.toString()} rows ${entry.bytes.toString()} bytes ${entry.file}`);
|
|
67
|
-
}
|
|
68
|
-
return { code: 0 };
|
|
69
|
-
};
|
|
70
|
-
const runBackupRestore = async (options, directory) => {
|
|
71
|
-
const { target } = options;
|
|
72
|
-
if (target === void 0 || target.length === 0) {
|
|
73
|
-
options.logger.error("restore requires a backup id or file path. Usage: lunora backup restore <id|file>");
|
|
74
|
-
return { code: 1 };
|
|
75
|
-
}
|
|
76
|
-
const manifest = await readManifest(directory);
|
|
77
|
-
const matched = manifest.find((entry) => entry.id === target);
|
|
78
|
-
const file = matched ? join(directory, matched.file) : target;
|
|
79
|
-
if (!existsSync(file)) {
|
|
80
|
-
options.logger.error(`backup not found: ${target}`);
|
|
81
|
-
return { code: 1 };
|
|
82
|
-
}
|
|
83
|
-
const result = await runImportCommand({
|
|
84
|
-
fetchImpl: options.fetchImpl,
|
|
85
|
-
file,
|
|
86
|
-
logger: options.logger,
|
|
87
|
-
prod: options.prod,
|
|
88
|
-
token: options.token,
|
|
89
|
-
url: options.url
|
|
90
|
-
});
|
|
91
|
-
return { code: result.code };
|
|
92
|
-
};
|
|
93
|
-
const resolvePitrRequest = (options) => {
|
|
94
|
-
const token = options.token ?? process.env.LUNORA_ADMIN_TOKEN;
|
|
95
|
-
if (!token) {
|
|
96
|
-
options.logger.error("admin token required — pass --token or set LUNORA_ADMIN_TOKEN");
|
|
97
|
-
return void 0;
|
|
98
|
-
}
|
|
99
|
-
if (options.prod && options.url === void 0) {
|
|
100
|
-
options.logger.error("--prod requires an explicit --url (refusing to target the implicit localhost worker)");
|
|
101
|
-
return void 0;
|
|
102
|
-
}
|
|
103
|
-
if (options.restore === true && options.at === void 0 && options.bookmark === void 0) {
|
|
104
|
-
options.logger.error("pitr --restore requires --at <time> or --bookmark <bookmark>");
|
|
105
|
-
return void 0;
|
|
106
|
-
}
|
|
107
|
-
if (options.restore === true && options.prod === true && options.yes !== true) {
|
|
108
|
-
options.logger.error("pitr --restore --prod restores production data in place. Re-run with --yes to confirm.");
|
|
109
|
-
return void 0;
|
|
110
|
-
}
|
|
111
|
-
const baseUrl = resolveAdminBaseUrl(options.url, options.logger);
|
|
112
|
-
if (baseUrl === void 0) {
|
|
113
|
-
return void 0;
|
|
114
|
-
}
|
|
115
|
-
const fetchImpl = options.pitrFetch ?? globalThis.fetch;
|
|
116
|
-
if (typeof fetchImpl !== "function") {
|
|
117
|
-
throw new TypeError("no fetch implementation available — pass pitrFetch or run on Node >= 18");
|
|
118
|
-
}
|
|
119
|
-
return { fetchImpl, requestUrl: `${baseUrl}${PITR_ENDPOINT_PATH}`, token };
|
|
120
|
-
};
|
|
121
|
-
const buildPitrArgs = (options, isRestore) => {
|
|
122
|
-
const args = {};
|
|
123
|
-
if (options.at !== void 0) {
|
|
124
|
-
args.time = options.at;
|
|
125
|
-
}
|
|
126
|
-
if (isRestore && options.bookmark !== void 0) {
|
|
127
|
-
args.bookmark = options.bookmark;
|
|
128
|
-
}
|
|
129
|
-
if (isRestore && options.restart === true) {
|
|
130
|
-
args.restart = true;
|
|
131
|
-
}
|
|
132
|
-
return args;
|
|
133
|
-
};
|
|
134
|
-
const runBackupPitr = async (options) => {
|
|
135
|
-
const request = resolvePitrRequest(options);
|
|
136
|
-
if (request === void 0) {
|
|
137
|
-
return { code: 1 };
|
|
138
|
-
}
|
|
139
|
-
const isRestore = options.restore === true;
|
|
140
|
-
const functionPath = isRestore ? PITR_RESTORE_OP : GET_PITR_BOOKMARK_OP;
|
|
141
|
-
const args = buildPitrArgs(options, isRestore);
|
|
142
|
-
const action = isRestore ? "restore" : "bookmark";
|
|
143
|
-
options.logger.info(`POST ${request.requestUrl} -> pitr ${action}${options.shard === void 0 ? "" : ` (shard "${options.shard}")`}`);
|
|
144
|
-
const response = await request.fetchImpl(request.requestUrl, {
|
|
145
|
-
body: JSON.stringify({ args, functionPath, shardKey: options.shard }),
|
|
146
|
-
headers: { authorization: `Bearer ${request.token}`, "content-type": "application/json" },
|
|
147
|
-
method: "POST"
|
|
148
|
-
});
|
|
149
|
-
const text = await response.text();
|
|
150
|
-
let body;
|
|
151
|
-
try {
|
|
152
|
-
body = JSON.parse(text);
|
|
153
|
-
} catch {
|
|
154
|
-
body = text;
|
|
155
|
-
}
|
|
156
|
-
options.logger.info(JSON.stringify(body, void 0, 2));
|
|
157
|
-
return { code: response.ok ? 0 : 1 };
|
|
158
|
-
};
|
|
159
|
-
const runBackupCommand = async (options) => {
|
|
160
|
-
const cwd = options.cwd ?? process.cwd();
|
|
161
|
-
const directory = join(cwd, options.dir ?? DEFAULT_BACKUP_DIR);
|
|
162
|
-
try {
|
|
163
|
-
if (options.subcommand === "create") {
|
|
164
|
-
return await runBackupCreate(options, directory);
|
|
165
|
-
}
|
|
166
|
-
if (options.subcommand === "list") {
|
|
167
|
-
return await runBackupList(options, directory);
|
|
168
|
-
}
|
|
169
|
-
if (options.subcommand === "pitr") {
|
|
170
|
-
return await runBackupPitr(options);
|
|
171
|
-
}
|
|
172
|
-
return await runBackupRestore(options, directory);
|
|
173
|
-
} catch (error) {
|
|
174
|
-
options.logger.error(error instanceof Error ? error.message : String(error));
|
|
175
|
-
return { code: 1 };
|
|
176
|
-
}
|
|
177
|
-
};
|
|
178
|
-
const isBackupSubcommand = (value) => value === "create" || value === "list" || value === "pitr" || value === "restore";
|
|
179
|
-
const execute = defineHandler(({ argument, cwd, logger, options }) => {
|
|
180
|
-
const sub = argument[0];
|
|
181
|
-
if (!isBackupSubcommand(sub)) {
|
|
182
|
-
logger.error(`backup: unknown subcommand "${sub ?? ""}" — expected create | list | restore | pitr`);
|
|
183
|
-
return { code: 1 };
|
|
184
|
-
}
|
|
185
|
-
return runBackupCommand({
|
|
186
|
-
at: options.at,
|
|
187
|
-
bookmark: options.bookmark,
|
|
188
|
-
cwd,
|
|
189
|
-
dir: options.dir,
|
|
190
|
-
logger,
|
|
191
|
-
prod: options.prod === true,
|
|
192
|
-
restart: options.restart === true,
|
|
193
|
-
restore: options.restore === true,
|
|
194
|
-
shard: options.shard,
|
|
195
|
-
subcommand: sub,
|
|
196
|
-
tables: options.tables,
|
|
197
|
-
target: argument[1],
|
|
198
|
-
token: options.token,
|
|
199
|
-
url: resolveProductionWorkerUrl({ cwd, prod: options.prod === true, url: options.url }),
|
|
200
|
-
yes: options.yes === true
|
|
201
|
-
});
|
|
202
|
-
});
|
|
203
|
-
|
|
204
|
-
export { execute, runBackupCommand };
|
|
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-B6vu47iR.mjs";import{EXIT_CODE as B}from"../packem_shared/EXIT_CODE-DVjUgIaG.mjs";import{defaultSpawner as F}from"../packem_shared/createRecordingSpawner-01ZngIwK.mjs";import{execArgsFor as h,detectPackageManager as x}from"@lunora/config/cli";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};
|