@lunora/cli 1.0.0-alpha.214 → 1.0.0-alpha.216
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/bin.mjs +1 -1
- package/dist/index.d.mts +36 -1
- package/dist/index.d.ts +36 -1
- package/dist/index.mjs +1 -1
- package/dist/packem_chunks/handler.mjs +1 -1
- package/dist/packem_chunks/handler10.mjs +1 -4
- package/dist/packem_chunks/handler11.mjs +4 -2
- package/dist/packem_chunks/handler12.mjs +2 -1
- package/dist/packem_chunks/handler13.mjs +1 -1
- package/dist/packem_chunks/handler14.mjs +1 -1
- package/dist/packem_chunks/handler15.mjs +1 -1
- package/dist/packem_chunks/handler16.mjs +1 -3
- package/dist/packem_chunks/handler17.mjs +3 -1
- package/dist/packem_chunks/handler18.mjs +1 -1
- package/dist/packem_chunks/handler19.mjs +1 -7
- package/dist/packem_chunks/handler2.mjs +1 -2
- package/dist/packem_chunks/handler20.mjs +7 -1
- package/dist/packem_chunks/handler21.mjs +1 -2
- package/dist/packem_chunks/handler22.mjs +2 -3
- package/dist/packem_chunks/handler23.mjs +3 -3
- package/dist/packem_chunks/handler24.mjs +3 -1
- package/dist/packem_chunks/handler25.mjs +1 -99
- package/dist/packem_chunks/handler26.mjs +99 -10
- package/dist/packem_chunks/handler27.mjs +10 -0
- package/dist/packem_chunks/handler3.mjs +2 -1
- package/dist/packem_chunks/handler4.mjs +1 -1
- package/dist/packem_chunks/handler5.mjs +1 -1
- package/dist/packem_chunks/handler6.mjs +1 -1
- package/dist/packem_chunks/handler7.mjs +1 -3
- package/dist/packem_chunks/handler8.mjs +3 -1
- package/dist/packem_chunks/handler9.mjs +1 -1
- package/dist/packem_chunks/planDevCommand.mjs +1 -1
- package/dist/packem_chunks/runCodegenCommand.mjs +2 -2
- package/dist/packem_chunks/runInitCommand.mjs +38 -38
- package/dist/packem_chunks/runMigrateGenerateCommand.mjs +6 -6
- package/dist/packem_chunks/runRpcCommand.mjs +1 -1
- package/dist/packem_shared/{COMMANDS-BuKOBthp.mjs → COMMANDS-Cf45cyJN.mjs} +1 -1
- package/dist/packem_shared/DEFAULT_IMPORT_BATCH_SIZE-CYq3UJmD.mjs +1 -0
- package/dist/packem_shared/admin-token-VdUnvnKW.mjs +1 -0
- package/dist/packem_shared/admin-url-BhF5ufg1.mjs +1 -0
- package/dist/packem_shared/buildRegistryIndex-BcJgAx76.mjs +1 -0
- package/dist/packem_shared/catalog-CJaormx0.mjs +1 -0
- package/dist/packem_shared/cli-CqNvbTR1.mjs +3 -0
- package/dist/packem_shared/commands-YfMX-Mto.mjs +19 -0
- package/dist/packem_shared/diffSnapshots-Cnoe8Ob4.mjs +5 -0
- package/dist/packem_shared/{import-CdHdZRjj.mjs → import-8FCB0cUX.mjs} +10 -10
- package/dist/packem_shared/platform-diagnostics-D0YzAdXm.mjs +4 -0
- package/dist/packem_shared/runAddCommand-vE21wRIK.mjs +1 -0
- package/dist/packem_shared/runDeployCommand-o64lz-UD.mjs +1 -0
- package/dist/packem_shared/runExportCommand-Dq-SpjAe.mjs +5 -0
- package/dist/packem_shared/schema-drift-gate-BDCkQ1S6.mjs +1 -0
- package/dist/packem_shared/schemaIrToSnapshot-ogkcpHjM.mjs +1 -0
- package/dist/packem_shared/{storage-wIUel5Az.mjs → storage-D5s4vbtJ.mjs} +1 -1
- package/package.json +11 -11
- package/dist/packem_chunks/runDeployCommand.mjs +0 -1
- package/dist/packem_shared/DEFAULT_IMPORT_BATCH_SIZE-Cf8ZymM1.mjs +0 -1
- package/dist/packem_shared/admin-token-rxXZbVMZ.mjs +0 -1
- package/dist/packem_shared/admin-url-Cil3Or6N.mjs +0 -1
- package/dist/packem_shared/buildRegistryIndex-Zi3bBqpc.mjs +0 -1
- package/dist/packem_shared/cli-CiD-rkxB.mjs +0 -3
- package/dist/packem_shared/commands-BNKj7r1R.mjs +0 -19
- package/dist/packem_shared/diffSnapshots-CIOFQN_a.mjs +0 -5
- package/dist/packem_shared/platform-diagnostics-uOXqysk3.mjs +0 -4
- package/dist/packem_shared/runAddCommand-D1Dj8-pK.mjs +0 -1
- package/dist/packem_shared/runExportCommand-DmXKEWSq.mjs +0 -5
- package/dist/packem_shared/schema-drift-gate-Bt_plRtS.mjs +0 -1
- package/dist/packem_shared/schemaIrToSnapshot-qpRoV7HY.mjs +0 -1
|
@@ -1,3 +1,2 @@
|
|
|
1
|
-
import{
|
|
2
|
-
`)
|
|
3
|
-
`,"utf8")},te=u("lunora","_generated","openrpc.json"),re=t=>{if(!w(t))throw new d("NOT_FOUND",`no OpenRPC document at ${t} — run \`lunora codegen --api-spec openrpc\` (or \`--api-spec both\`) first, or pass --spec`);let n;try{n=JSON.parse(M(t,"utf8"))}catch(e){throw new d("BAD_REQUEST",`${t} is not valid JSON: ${e instanceof Error?e.message:String(e)}`)}if(n===null||typeof n!="object"||!Array.isArray(n.methods))throw new d("BAD_REQUEST",`${t} is not an OpenRPC document (no \`methods\` array)`);return n},de=J(async({argument:t,cwd:n,logger:e,options:r})=>{const a=t[0]??"generate";if(a!=="generate")throw new d("BAD_REQUEST",`unknown subcommand "${a}" — the only one is \`lunora sdk generate\``);const s=r.lang??"python",o=V[s];if(o===void 0)throw new d("BAD_REQUEST",`unsupported --lang "${s}" — expected one of: ${G.join(" | ")}`);const f=W("sdk generate",{allowUnsafeSource:r.allowUnsafeSource,logger:e,names:[],source:r.source});if(f!==void 0)throw new d("BAD_REQUEST",f);const h=O(n,r.spec??te),c=O(n,r.out??u("sdk",s)),l=re(h);l.methods.length===0&&e.warn(`${h} declares no methods — writing an empty SDK.`);const{files:m,undeclared:g,unrepresentable:p}=await P(l,o);D(c,{recursive:!0});const i=await Z({allowUnsafeSource:r.allowUnsafeSource,from:r.from,language:s,logger:e,outputDirectory:c,ref:r.ref,source:r.source,target:o});ee(c,s,i);for(const[S,L]of Object.entries(m)){const T=u(c,S);D(K(T),{recursive:!0}),E(T,L,"utf8")}const y=l.methods.filter(S=>!Q(S.result?.schema)).length;return e.success(`Generated ${s} SDK for ${String(l.methods.length)} function(s) → ${c}`),e.info(`Vendored the ${s} transport (${String(i.files.length)} file(s)) from ${i.source} @ ${i.ref}${i.versionMatched?" — version-matched to this CLI":""}; see ${v}.`),e.info(o.requires.length>0?`Install in the consuming project: ${o.requires.join(", ")}.`:"Nothing to install — the transport is vendored and needs only the standard library."),g.length>0&&e.warn(`${String(g.length)} schema(s) are not expressible as a named ${s} model, so those arguments or returns stay untyped: ${g.join(", ")}`),p.length>0&&e.warn(`${String(p.length)} function(s) take or return a \`v.bigint()\`/\`v.bytes()\`, which no generated model can carry — their parameters stay untyped, so pass wire values directly: ${p.join(", ")}`),y>0&&e.warn(`${String(y)} of ${String(l.methods.length)} function(s) return an untyped result — declare \`.output()\` on them for typed returns.`),{code:0}});export{de as execute};
|
|
1
|
+
import{readLinkedProject as g,resolveDeployDriver as v,execArgsFor as h,detectPackageManager as y}from"@lunora/config";import{d as b}from"../packem_shared/command-DwC11Cwe.mjs";import{defaultSpawner as w}from"../packem_shared/createRecordingSpawner-DJlNacZ6.mjs";import{createR2Sql as L}from"@lunora/bindings/r2sql";import{createPipelineLogReader as S}from"@lunora/runtime";const _=new Set(["debug","error","fatal","info","log","trace","warn"]),m=/^\d+$/,d=(e,t)=>{if(e===void 0)return;const a=e.trim();if(m.test(a))return Number(a);const r=Date.parse(a);if(Number.isNaN(r))throw new TypeError(`logs: invalid ${t} "${e}" — pass epoch-millis or an ISO 8601 date`);return r},T=e=>Buffer.from(JSON.stringify(e),"utf8").toString("base64url"),C=e=>{const t=e.trim();if(m.test(t))return{ts:Number(t)};let a;try{a=JSON.parse(Buffer.from(t,"base64url").toString("utf8"))}catch{throw new TypeError(`logs: invalid --cursor "${e}" — expected the token printed by the previous page (or a bare epoch-millis ts)`)}if(typeof a!="object"||a===null||typeof a.ts!="number"||!Number.isFinite(a.ts))throw new TypeError(`logs: invalid --cursor "${e}" — expected the token printed by the previous page (or a bare epoch-millis ts)`);const{ts:r}=a,i=a.seen,n=Array.isArray(i)?i.filter(s=>typeof s=="string"):void 0;return n!==void 0&&n.length>0?{seen:n,ts:r}:{ts:r}},u=(e,t)=>{if(e!==void 0){if(!_.has(e))throw new TypeError(`logs: invalid ${t} "${e}" — expected one of trace, debug, log, info, warn, error, fatal`);return e}},I=e=>{const t={},a=d(e.since,"--since");a!==void 0&&(t.sinceTs=a);const r=d(e.until,"--until");r!==void 0&&(t.untilTs=r);const i=u(e.level,"--level");i!==void 0&&(t.level=i);const n=u(e.minLevel,"--min-level");if(n!==void 0&&(t.minLevel=n),e.functionPrefix!==void 0&&(t.functionPathPrefix=e.functionPrefix),e.traceId!==void 0&&(t.traceId=e.traceId),e.shardKey!==void 0&&(t.shardKey=e.shardKey),e.userId!==void 0&&(t.userId=e.userId),e.limit!==void 0){const s=Number(e.limit);if(!Number.isFinite(s))throw new TypeError(`logs: invalid --limit "${e.limit}" — expected a number`);t.limit=s}return e.cursor!==void 0&&(t.cursor=C(e.cursor)),t},$=e=>{const t=new Date(e.ts).toISOString(),a=e.level.toUpperCase().padEnd(5);return`${t} ${a} ${e.functionPath} ${e.message}`},x=async e=>{const t=e.environment??process.env,a=t.R2_SQL_ACCOUNT_ID,r=t.R2_SQL_TOKEN,i=t.R2_SQL_BUCKET,n=[];if((a===void 0||a.length===0)&&n.push("R2_SQL_ACCOUNT_ID"),(r===void 0||r.length===0)&&n.push("R2_SQL_TOKEN"),(i===void 0||i.length===0)&&n.push("R2_SQL_BUCKET"),(e.table===void 0||e.table.length===0)&&n.push("--table"),n.length>0)return e.logger.error(`logs --durable: R2 SQL not configured (missing ${n.join(", ")}). The Pipeline must write to an R2 Data Catalog (Iceberg) table, and you must supply R2_SQL_ACCOUNT_ID / R2_SQL_TOKEN / R2_SQL_BUCKET plus --table — see the observability docs.`),{code:1,error:"not configured"};let s;try{s=I(e)}catch(o){return e.logger.error(o instanceof Error?o.message:String(o)),{code:1,error:"invalid option"}}const l=L({accountId:a,apiToken:r,bucket:i,fetch:e.fetch}),c=await S(l,{namespace:e.namespace,table:e.table}).query(s);for(const o of c.rows)process.stdout.write(`${e.ndjson===!0?JSON.stringify(o):$(o)}
|
|
2
|
+
`);return c.rows.length===0?e.logger.info("logs --durable: no matching log records"):c.nextCursor!==void 0&&e.logger.info(`logs --durable: more rows available — pass --cursor ${T(c.nextCursor)} for the next page`),{code:0,rows:c.rows}},E=new Set(["json","pretty"]),N=async e=>{const t=e.cwd??process.cwd();if(e.format!==void 0&&!E.has(e.format))return e.logger.error(`logs: unknown --format "${e.format}" — expected pretty | json`),{code:1,descriptor:void 0,error:"invalid format"};const a=e.env??g(t)?.env,r=v(e.target);if(r.toolchain===void 0)return e.logger.error(`logs: deploy target "${r.id}" has no command-line toolchain`),{code:1,descriptor:void 0,error:"no toolchain"};const i=r.toolchain.tail({environment:a,format:e.format,search:e.search,status:e.status,temporary:e.temporary,worker:e.worker}),n=h(y(t),i.tool,i.args),s={args:n.args,command:n.command,cwd:t};return e.logger.info(`tailing logs via ${s.command} ${s.args.join(" ")}`),{code:(await(e.spawner??w)(s)).code,descriptor:s}},Q=b(({argument:e,cwd:t,logger:a,options:r})=>r.durable===!0?x({cursor:r.cursor,functionPrefix:r.functionPrefix,level:r.level,limit:r.limit,logger:a,minLevel:r.minLevel,namespace:r.namespace,ndjson:r.ndjson===!0,shardKey:r.shardKey,since:r.since,table:r.table,traceId:r.traceId,until:r.until,userId:r.userId}):N({cwd:t,env:r.env,format:r.format,logger:a,search:r.search,status:r.status,target:r.target,temporary:r.temporary===!0,worker:e[0]}));export{Q as execute,N as runLogsCommand};
|
|
@@ -1,3 +1,3 @@
|
|
|
1
|
-
import
|
|
2
|
-
|
|
3
|
-
`,
|
|
1
|
+
import{writeFileSync as E,existsSync as w,cpSync as j,statSync as b,lstatSync as I,readdirSync as N,mkdirSync as D,readFileSync as M}from"node:fs";import{join as u,sep as x,relative as B,resolve as O,dirname as K}from"node:path";import{SDK_TARGETS as V,SDK_LANGUAGES as G,generateSdk as P,isTypedSchema as Q}from"@lunora/codegen";import{LunoraError as d}from"@lunora/errors";import{d as J}from"../packem_shared/command-DwC11Cwe.mjs";import{r as _,a as U,b as q,c as H,s as W}from"../packem_shared/resolve-DZAGzg67.mjs";const $="gh:anolilab/lunora/sdks",v="lunora-transport.json",X=/_test\.|Tests?\./u,k=t=>t.startsWith("test_")||X.test(t),A=(t,n="")=>N(t).toSorted((e,r)=>e.localeCompare(r)).flatMap(e=>{const r=u(t,e),a=n.length>0?`${n}/${e}`:e;return b(r).isDirectory()?A(r,a):[a]}),C=(t,n)=>{const e=I(n);if(e.isSymbolicLink())throw new d("INTERNAL",`refusing to vendor "${B(t,n)}" — it is a symlink, not a regular file`);if(e.isDirectory())for(const r of N(n))k(r)||C(t,u(n,r))},F=(t,n,e,r)=>{const a=u(t,e);if(!w(a))throw new d("NOT_FOUND",`transport is missing ${e}`);C(t,a);const s=u(n,r);return j(a,s,{filter:o=>!k(o.slice(o.lastIndexOf(x)+1)),force:!0,recursive:!0}),b(s).isDirectory()?A(s).map(o=>`${r}/${o}`):[r]},R=(t,n)=>n.vendor.every(e=>w(u(t,e.from))),z=async(t,n)=>{const{language:e,logger:r,outputDirectory:a,registryOptions:s,target:o}=n,{cleanup:f,directory:h}=await H(e,{...s,ref:t},$);try{if(!R(h,o)){r.warn(`${$}/${e} does not exist at ${t}.`);return}return{files:o.vendor.flatMap(c=>F(h,a,c.from,c.to)).toSorted((c,l)=>c.localeCompare(l)),ref:t,source:`${$}/${e}`,versionMatched:t===_()}}finally{f()}},Y=(t,n)=>{const{language:e,outputDirectory:r,target:a}=n,s=u(t,e);if(!w(s))throw new d("NOT_FOUND",`no transport at ${s} — --from must point at a directory of per-language transports (the repo's \`sdks/\`)`);if(!R(s,a)){const o=a.vendor.map(f=>f.from).join(", ");throw new d("NOT_FOUND",`${s} is not a ${e} transport — expected it to contain ${o}`)}return{files:a.vendor.flatMap(o=>F(s,r,o.from,o.to)).toSorted((o,f)=>o.localeCompare(f)),ref:"local",source:s,versionMatched:!1}},Z=async t=>{const{allowUnsafeSource:n,from:e,language:r,logger:a,outputDirectory:s,ref:o,source:f,target:h}=t;if(e!==void 0)return Y(e,{language:r,outputDirectory:s,target:h});const c={allowUnsafeSource:n,logger:a,names:[],source:f},l=async i=>z(await q(i,a),{language:r,logger:a,outputDirectory:s,registryOptions:c,target:h});if(o!==void 0&&o.length>0){const i=await l(o);if(i===void 0)throw new d("NOT_FOUND",`--ref ${o} carries no ${r} transport — pick a ref that does, or pass --from <dir> to copy a local one`);return i}const m=_(),g=await l(m).catch(i=>{const y=i instanceof Error?i.message.split(`
|
|
2
|
+
`)[0]??i.message:String(i);a.warn(`could not fetch the transport at ${m} (${y}).`)});if(g!==void 0)return g;const p=await l(void 0);if(p===void 0)throw new d("NOT_FOUND",`no ${r} transport at ${m} or on the release branch. This language may not be released yet — pass --from <dir> to copy one from a checkout, or --ref <tag> to name a ref that has it.`);return a.warn(`FALLBACK: the transport is NOT version-matched to this CLI (${U()}). Wanted ${m}, used ${p.ref}. The vendored wire protocol may not be the one this surface was generated against; ${v} records what was actually copied.`),p},ee=(t,n,e)=>{const r={cliVersion:U(),files:e.files,language:n,note:e.versionMatched?"Vendored by `lunora sdk generate` at the ref matching the CLI that generated the surface beside it. Regenerate with a newer CLI to upgrade.":"Vendored by `lunora sdk generate` from a ref that is NOT this CLI's release tag, so the transport and the generated surface may be different protocol vintages.",ref:e.ref,source:e.source,versionMatched:e.versionMatched};E(u(t,v),`${JSON.stringify(r,void 0,4)}
|
|
3
|
+
`,"utf8")},te=u("lunora","_generated","openrpc.json"),re=t=>{if(!w(t))throw new d("NOT_FOUND",`no OpenRPC document at ${t} — run \`lunora codegen --api-spec openrpc\` (or \`--api-spec both\`) first, or pass --spec`);let n;try{n=JSON.parse(M(t,"utf8"))}catch(e){throw new d("BAD_REQUEST",`${t} is not valid JSON: ${e instanceof Error?e.message:String(e)}`)}if(n===null||typeof n!="object"||!Array.isArray(n.methods))throw new d("BAD_REQUEST",`${t} is not an OpenRPC document (no \`methods\` array)`);return n},de=J(async({argument:t,cwd:n,logger:e,options:r})=>{const a=t[0]??"generate";if(a!=="generate")throw new d("BAD_REQUEST",`unknown subcommand "${a}" — the only one is \`lunora sdk generate\``);const s=r.lang??"python",o=V[s];if(o===void 0)throw new d("BAD_REQUEST",`unsupported --lang "${s}" — expected one of: ${G.join(" | ")}`);const f=W("sdk generate",{allowUnsafeSource:r.allowUnsafeSource,logger:e,names:[],source:r.source});if(f!==void 0)throw new d("BAD_REQUEST",f);const h=O(n,r.spec??te),c=O(n,r.out??u("sdk",s)),l=re(h);l.methods.length===0&&e.warn(`${h} declares no methods — writing an empty SDK.`);const{files:m,undeclared:g,unrepresentable:p}=await P(l,o);D(c,{recursive:!0});const i=await Z({allowUnsafeSource:r.allowUnsafeSource,from:r.from,language:s,logger:e,outputDirectory:c,ref:r.ref,source:r.source,target:o});ee(c,s,i);for(const[S,L]of Object.entries(m)){const T=u(c,S);D(K(T),{recursive:!0}),E(T,L,"utf8")}const y=l.methods.filter(S=>!Q(S.result?.schema)).length;return e.success(`Generated ${s} SDK for ${String(l.methods.length)} function(s) → ${c}`),e.info(`Vendored the ${s} transport (${String(i.files.length)} file(s)) from ${i.source} @ ${i.ref}${i.versionMatched?" — version-matched to this CLI":""}; see ${v}.`),e.info(o.requires.length>0?`Install in the consuming project: ${o.requires.join(", ")}.`:"Nothing to install — the transport is vendored and needs only the standard library."),g.length>0&&e.warn(`${String(g.length)} schema(s) are not expressible as a named ${s} model, so those arguments or returns stay untyped: ${g.join(", ")}`),p.length>0&&e.warn(`${String(p.length)} function(s) take or return a \`v.bigint()\`/\`v.bytes()\`, which no generated model can carry — their parameters stay untyped, so pass wire values directly: ${p.join(", ")}`),y>0&&e.warn(`${String(y)} of ${String(l.methods.length)} function(s) return an untyped result — declare \`.output()\` on them for typed returns.`),{code:0}});export{de as execute};
|
|
@@ -1 +1,3 @@
|
|
|
1
|
-
import
|
|
1
|
+
import K,{join as l,resolve as T}from"node:path";import{isInteractive as F,promptYesNo as z}from"@lunora/config";import{backupObjectKey as p,isBackupManifestEntry as x,normalizeBackupPrefix as H,BACKUP_KEY_PREFIX as J,backupManifestKey as G,isBackupManifestKey as W,backupObjectKeyOfManifest as O}from"@lunora/runtime";import{r as A,t as Y}from"../packem_shared/admin-token-VdUnvnKW.mjs";import{r as v}from"../packem_shared/admin-url-BhF5ufg1.mjs";import{d as X}from"../packem_shared/command-DwC11Cwe.mjs";import{r as Q}from"../packem_shared/resolve-target-BRvw8Pf7.mjs";import{readAndLogBody as b}from"./runRpcCommand.mjs";import{randomUUID as U,createHash as V}from"node:crypto";import{existsSync as $,createReadStream as Z,createWriteStream as ee}from"node:fs";import{mkdir as re,rm as w,rename as B,readFile as D,writeFile as te,realpath as N,mkdtemp as S}from"node:fs/promises";import{LunoraError as h}from"@lunora/errors";import{i as E}from"../packem_shared/path-containment-CgxYZggb.mjs";import{tmpdir as I}from"node:os";import{Readable as ae}from"node:stream";import{pipeline as oe}from"node:stream/promises";import{b as ne,l as ie,M as _,u as ce,r as se}from"../packem_shared/import-8FCB0cUX.mjs";import{runExportCommand as ue}from"../packem_shared/runExportCommand-Dq-SpjAe.mjs";const y="manifest.json",j=async e=>{const r=V("sha256");let t=0;for await(const a of Z(e)){const o=a;t+=o.byteLength,r.update(o)}return{bytes:t,sha256:r.digest("hex")}},R=async e=>{const r=l(e,y);if(!$(r))return[];let t;try{t=JSON.parse(await D(r,"utf8"))}catch(a){const o=a instanceof Error?a.message:String(a);throw new h("INTERNAL",`backup: ${r} exists but is not valid JSON (${o}) — refusing to overwrite it; fix or remove it manually`,{cause:a})}if(!Array.isArray(t))throw new TypeError(`backup: ${r} exists but is not a JSON array — refusing to overwrite it; fix or remove it manually`);return t.filter(a=>x(a))},de=async(e,r)=>{const t=l(e,`${y}.${U()}.tmp`);try{await te(t,`${JSON.stringify(r,void 0,2)}
|
|
2
|
+
`,"utf8"),await B(t,l(e,y))}catch(a){throw await w(t,{force:!0}),a}},le=async(e,r)=>{const t=T(e),a=T(t,r.file),o=()=>{throw new h("INTERNAL",`backup: entry ${r.id} points outside ${t} (${r.file}) — refusing to read it`)};if(E(t,a)||o(),!!$(a))return E(await N(t),await N(a))||o(),a},fe=e=>{const r=t=>p("",t);return{commit:async(t,a)=>{await B(a,l(e,t))},label:e,list:async()=>R(e),locate:r,materialize:async(t,a)=>{const o=i=>i===void 0?void 0:{path:i,release:()=>Promise.resolve()};return o(t===void 0?$(a)?a:void 0:await le(e,t))},record:async t=>{const a=await R(e);a.push(t),await de(e,a)},stage:async t=>{await re(e,{recursive:!0});const a=l(e,`${r(t)}.${U()}.partial`);return{path:a,release:()=>w(a,{force:!0})}}}},me="/_lunora/admin/storage/object",ge="/_lunora/admin/storage",P=8,he=(e,r=K)=>{const t=r.basename(e);return t===""||t==="."||t===".."?"snapshot.ndjson":t},we=e=>{const{context:r,logger:t}=e,a=H(e.prefix??J),o=`bucket ${r.bucket??"(default)"} under ${a}`,i=ne(r),u=c=>`${r.baseUrl}${me}?key=${encodeURIComponent(c)}${i}`,f=async c=>{const n=await r.fetchImpl(u(c),{headers:{authorization:`Bearer ${r.token}`},method:"GET"});if(!n.ok){const d=await n.text().catch(()=>"<no body>");throw new h("INTERNAL",`backup: could not read ${c} (HTTP ${String(n.status)}): ${d}`)}return n.text()},C=async c=>{try{const n=JSON.parse(await f(c));if(x(n))return n;t.warn(`backup: ignoring ${c} — not a backup manifest`)}catch(n){t.warn(`backup: ignoring ${c} — ${n instanceof Error?n.message:String(n)}`)}};return{commit:async(c,n,d)=>{if(d.bytes>_)throw new h("INTERNAL",`backup: the snapshot is ${String(d.bytes)} bytes, above the ${String(_)}-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 s=await D(n);await ce(r,c,s,{contentType:"application/x-ndjson",id:c,sha256:d.sha256,size:d.bytes},t)},label:o,list:async()=>{const n=(await ie(r,a)).map(s=>s.key).filter(s=>W(s)),d=[];for(let s=0;s<n.length;s+=P){const m=await Promise.all(n.slice(s,s+P).map(async g=>C(g)));d.push(...m.filter(g=>g!==void 0))}return d.toSorted((s,m)=>s.id.localeCompare(m.id))},locate:c=>p(a,c),materialize:async(c,n)=>{const d=c?.file??n,s=await r.fetchImpl(u(d),{headers:{authorization:`Bearer ${r.token}`},method:"GET"});if(s.status===404)return;if(!s.ok||s.body===null){const k=await s.text().catch(()=>"<no body>");throw new h("INTERNAL",`backup: could not download ${d} (HTTP ${String(s.status)}): ${k}`)}const m=await S(l(I(),"lunora-backup-")),g=l(m,he(d));try{await oe(ae.from(s.body),ee(g))}catch(k){throw await w(m,{force:!0,recursive:!0}),k}return{path:g,release:async()=>w(m,{force:!0,recursive:!0})}},record:async c=>{const n=G(c.file),d=await r.fetchImpl(`${r.baseUrl}${ge}?key=${encodeURIComponent(n)}${i}`,{body:`${JSON.stringify(c,void 0,2)}
|
|
3
|
+
`,headers:{authorization:`Bearer ${r.token}`,"content-type":"application/json"},method:"PUT"});if(!d.ok){const s=await d.text().catch(()=>"<no body>");throw new h("INTERNAL",`backup: snapshot ${c.file} was written but its manifest was not (HTTP ${String(d.status)}): ${s}`)}},stage:async c=>{const n=await S(l(I(),"lunora-backup-"));return{path:l(n,p("",c)),release:async()=>w(n,{force:!0,recursive:!0})}}}},be=".lunora-backups",L="/_lunora/admin/backup/retention",ke="/_lunora/admin/backup/prune",pe="/_lunora/admin/pitr",ye="__lunora_admin__:getPitrBookmark",ve="__lunora_admin__:pitrRestore",$e=async(e,r)=>{const t=(e.now??(()=>new Date))().toISOString(),a=await r.stage(t);try{const o=await ue({cwd:e.cwd,fetchImpl:e.fetchImpl,logger:e.logger,out:a.path,prod:e.prod,tables:e.tables,token:e.token,url:e.url});if(o.code!==0)return{code:o.code};const i=r.locate(t),u=await j(a.path);await r.commit(i,a.path,u);const f={bytes:u.bytes,createdAt:t,file:i,id:t,rows:o.rows,sha256:u.sha256,tables:e.tables};return await r.record(f),e.logger.success(`backup created: ${i} (${o.rows.toString()} rows, ${u.bytes.toString()} bytes)`),{code:0,entry:f}}finally{await a.release().catch(o=>{e.logger.warn(`backup: could not clean up staging (${o instanceof Error?o.message:String(o)})`)})}},Te=async(e,r,t)=>{if(r?.sha256===void 0)return t.error(r===void 0?"--verify needs a recorded checksum, and a snapshot restored by path/key has no manifest entry — restore it by its backup id instead":`--verify: backup ${r.id} carries no recorded checksum — it was taken by a release before checksums existed`),{code:1};const a=await j(e);if(a.sha256!==r.sha256)return t.error(`--verify: ${r.file} does not match its recorded checksum (expected ${r.sha256}, got ${a.sha256}) — nothing was imported`),{code:1};t.success(`verified ${r.file} against its recorded sha256`)},Ne=async(e,r)=>{const t=await r.list();if(t.length===0)return e.logger.info(`no backups found in ${r.label}`),{code:0};for(const a of t)e.logger.info(`${a.id} ${a.rows.toString()} rows ${a.bytes.toString()} bytes ${a.file}`);return{code:0}},Se=async(e,r)=>{const{target:t}=e;if(t===void 0||t.length===0)return e.logger.error("restore requires a backup id or file path. Usage: lunora backup restore <id|file>"),{code:1};const o=(await r.list()).find(u=>u.id===t),i=await r.materialize(o,t);if(i===void 0)return e.logger.error(`backup not found: ${t}`),{code:1};try{if(e.verify===!0){const f=await Te(i.path,o,e.logger);if(f!==void 0)return f}return{code:(await se({cwd:e.cwd,fetchImpl:e.fetchImpl,file:i.path,logger:e.logger,prod:e.prod,token:e.token,url:e.url,yes:e.yes})).code}}finally{await i.release().catch(u=>{e.logger.warn(`backup: could not clean up the downloaded snapshot (${u instanceof Error?u.message:String(u)})`)})}},Ee=e=>{const r=e.token??process.env.LUNORA_ADMIN_TOKEN;if(!r){e.logger.error("admin token required — pass --token or set LUNORA_ADMIN_TOKEN");return}if(e.prod&&e.url===void 0){e.logger.error("--prod requires an explicit --url (refusing to target the implicit localhost worker)");return}if(e.restore===!0&&e.at===void 0&&e.bookmark===void 0){e.logger.error("pitr --restore requires --at <time> or --bookmark <bookmark>");return}const t=v(e.url,e.logger,e.cwd);if(t===void 0)return;if(e.restore===!0&&Y({prod:e.prod,url:t})&&e.yes!==!0){e.logger.error(`pitr --restore restores data in place at ${t}, which is not local. Re-run with --yes to confirm.`);return}const a=e.adminFetch??globalThis.fetch;if(typeof a!="function")throw new TypeError("no fetch implementation available — pass pitrFetch or run on Node >= 18");return{fetchImpl:a,requestUrl:`${t}${pe}`,token:r}},Ie=(e,r)=>{const t={};return e.at!==void 0&&(t.time=e.at),r&&e.bookmark!==void 0&&(t.bookmark=e.bookmark),r&&e.restart===!0&&(t.restart=!0),t},_e=async e=>{const r=Ee(e);if(r===void 0)return{code:1};const t=e.restore===!0,a=t?ve:ye,o=Ie(e,t),i=t?"restore":"bookmark";e.logger.info(`POST ${r.requestUrl} -> pitr ${i}${e.shard===void 0?"":` (shard "${e.shard}")`}`);const u=await r.fetchImpl(r.requestUrl,{body:JSON.stringify({args:o,functionPath:a,shardKey:e.shard}),headers:{authorization:`Bearer ${r.token}`,"content-type":"application/json"},method:"POST"});return await b(u,e.logger),{code:u.ok?0:1}},Re=(e,r)=>{if(e.bucket===void 0)return fe(l(r,e.dir??be));if(e.prod===!0&&e.url===void 0){e.logger.error("--prod requires an explicit --url (refusing to target the implicit localhost worker)");return}const t=v(e.url,e.logger,e.cwd);if(t===void 0)return;const{token:a}=A({cwd:r,token:e.token,url:t});if(!a){e.logger.error("admin token required — pass --token, set LUNORA_ADMIN_TOKEN, or add it to .dev.vars (local targets only)");return}const o=e.fetchImpl??globalThis.fetch;if(typeof o!="function")throw new TypeError("no fetch implementation available — pass fetchImpl or run on Node >= 18");return we({context:{baseUrl:t,bucket:e.bucket==="default"?void 0:e.bucket,fetchImpl:o,token:a},logger:e.logger,prefix:e.prefix})},q=e=>{const r=[e.bucket===void 0?void 0:"--bucket",e.prefix===void 0?void 0:"--prefix",e.dir===void 0?void 0:"--dir"].filter(i=>i!==void 0);if(r.length>0){e.logger.error(`${r.join(" / ")} ${r.length===1?"does":"do"} not apply here — retention and prune act on the store the worker itself is configured with (\`backupStore\`), not a destination you name.`);return}if(e.prod===!0&&e.url===void 0){e.logger.error("--prod requires an explicit --url (refusing to target the implicit localhost worker)");return}const t=v(e.url,e.logger,e.cwd);if(t===void 0)return;const{token:a}=A({cwd:e.cwd??process.cwd(),token:e.token,url:t});if(!a){e.logger.error("admin token required — pass --token, set LUNORA_ADMIN_TOKEN, or add it to .dev.vars (local targets only)");return}const o=e.adminFetch??globalThis.fetch;if(typeof o!="function")throw new TypeError("no fetch implementation available — pass pitrFetch or run on Node >= 18");return{baseUrl:t,fetchImpl:o,token:a}},M=(e,r)=>{e.logger.info(`backup retention would keep the newest ${r.keep.toString()} of ${r.eligible.toString()} under ${r.prefix} and delete ${r.wouldDelete.length.toString()}`);for(const t of r.wouldDelete)e.logger.info(` ${O(t)}`)},Pe=async e=>{const r=q(e);if(r===void 0)return{code:1};const t=await r.fetchImpl(`${r.baseUrl}${L}`,{headers:{authorization:`Bearer ${r.token}`},method:"GET"});if(!t.ok)return await b(t,e.logger),{code:1};const a=await t.json();return a.cron===void 0?(e.logger.info("no scheduled backup is configured (`backupCron`), so retention would delete nothing"),{code:0,preview:a}):a.keep<=0?(e.logger.info(`retention is off for cron "${a.cron}" (\`backupRetain\` unset) — every snapshot under ${a.prefix} is kept`),{code:0,preview:a}):(M(e,a),a.eligible===0&&e.logger.info(`no snapshot under ${a.prefix} was written by this cron, so retention has nothing of its own to remove`),{code:0,preview:a})},xe=(e,r)=>{e.logger.success(`deleted ${r.deleted.length.toString()} backup(s)`);for(const t of r.deleted)e.logger.info(` ${O(t)}`);r.failed.length>0&&e.logger.warn(`${r.failed.length.toString()} could not be removed — the snapshot may be gone with its manifest left behind; run again to retry`),r.ignored>0&&e.logger.info(`${r.ignored.toString()} were already gone by the time the delete ran`),r.remaining>0&&e.logger.info(`${r.remaining.toString()} more are past the window — run \`lunora backup prune\` again`)},Oe=async e=>{const r=q(e);if(r===void 0)return{code:1};const t=await r.fetchImpl(`${r.baseUrl}${L}`,{headers:{authorization:`Bearer ${r.token}`},method:"GET"});if(!t.ok)return await b(t,e.logger),{code:1};const a=await t.json();if(a.keep<=0||a.cron===void 0)return e.logger.error("backup prune needs a retention window: set `backupRetain` (and `backupCron`) on the worker. Without one there is nothing past the window to remove."),{code:1,preview:a};if(a.wouldDelete.length===0)return e.logger.info(`nothing to prune — ${a.eligible.toString()} snapshot(s) under ${a.prefix} and retention keeps the newest ${a.keep.toString()}`),{code:0,preview:a};if(M(e,a),e.yes!==!0){const u=e.confirm??(F()?z:void 0);if(u===void 0)return e.logger.error("refusing to delete backups without confirmation — re-run with --yes (there is no undo for an object-store delete)"),{code:1,preview:a};if(!await u(`delete ${a.wouldDelete.length.toString()} backup(s)? This cannot be undone. [y/N] `))return e.logger.info("nothing was deleted"),{code:0,preview:a}}const o=await r.fetchImpl(`${r.baseUrl}${ke}`,{body:JSON.stringify({confirm:a.wouldDelete}),headers:{authorization:`Bearer ${r.token}`,"content-type":"application/json"},method:"POST"});if(!o.ok)return await b(o,e.logger),{code:1,preview:a};const i=await o.json();return xe(e,i),{code:i.failed.length>0?1:0,deleted:i.deleted,preview:a}},Ae=async e=>{const r=e.cwd??process.cwd();try{if(e.subcommand==="pitr")return await _e(e);if(e.subcommand==="retention")return await Pe(e);if(e.subcommand==="prune")return await Oe(e);const t=Re(e,r);return t===void 0?{code:1}:e.subcommand==="create"?await $e(e,t):e.subcommand==="list"?await Ne(e,t):await Se(e,t)}catch(t){return e.logger.error(t instanceof Error?t.message:String(t)),{code:1}}},Ue=e=>e==="create"||e==="list"||e==="pitr"||e==="prune"||e==="restore"||e==="retention",Ze=X(({argument:e,cwd:r,logger:t,options:a})=>{const o=e[0];return Ue(o)?Ae({at:a.at,bookmark:a.bookmark,bucket:a.bucket,cwd:r,dir:a.dir,logger:t,prefix:a.prefix,prod:a.prod===!0,restart:a.restart===!0,restore:a.restore===!0,shard:a.shard,subcommand:o,tables:a.tables,target:e[1],token:a.token,url:Q({cwd:r,prod:a.prod===!0,url:a.url}),verify:a.verify===!0,yes:a.yes===!0}):(t.error(`backup: unknown subcommand "${o??""}" — expected create | list | restore | retention | prune | pitr`),{code:1})});export{Ze as execute,Ae as runBackupCommand};
|
|
@@ -1,99 +1 @@
|
|
|
1
|
-
import{
|
|
2
|
-
|
|
3
|
-
Install it in your project:
|
|
4
|
-
|
|
5
|
-
${K(n,t)}`)}return r(e)},j=e=>{const t=e.slice(0,Math.max(0,e.indexOf(":"))).toLowerCase();if(t==="postgres"||t==="postgresql")return"postgres";if(t==="mysql"||t==="mariadb")return"mysql";throw new N("INTERNAL",`Unrecognised database URL scheme \`${t}\`. Expected a \`postgres://\`, \`postgresql://\`, \`mysql://\`, or \`mariadb://\` connection string.`)},G=e=>{try{const t=new URL(e).pathname.replace(H,"");return t===""?void 0:decodeURIComponent(t)}catch{return}},J=async(e,t,n,r=process.cwd())=>{if(t==="postgres"){const m=L("pg","pg",r).Client,u=new m({connectionString:e});return await u.connect(),{close:async()=>{await u.end()},execute:async(l,d)=>(await u.query(l,[...d])).rows,schema:n??"public"}}const a=L("mysql2/promise","mysql2",r).createConnection,o=await a(e),i=n??G(e);if(i===void 0)throw new N("INTERNAL","A MySQL connection string must name a database (`mysql://host/<database>`), or pass `--schema`.");return{close:async()=>{await o.end()},execute:async(c,m)=>{const[u]=await o.execute(c,[...m]);return Array.isArray(u)?u:[]},schema:i}},h=new Set(["_creationTime","_id"]),Q={bigint:"v.bigint()",bigserial:"v.bigint()",bit:"v.string()",bool:"v.boolean()",boolean:"v.boolean()",box:"v.string()",bpchar:"v.string()",bytea:"v.bytes()",char:"v.string()",character:"v.string()","character varying":"v.string()",cidr:"v.string()",circle:"v.string()",citext:"v.string()",date:"v.date()","double precision":"v.number()",float4:"v.number()",float8:"v.number()",inet:"v.string()",int:"v.number()",int2:"v.number()",int4:"v.number()",int8:"v.bigint()",integer:"v.number()",interval:"v.string()",json:"v.any()",jsonb:"v.any()",line:"v.string()",lseg:"v.string()",macaddr:"v.string()",money:"v.number()",name:"v.string()",numeric:"v.number()",path:"v.string()",point:"v.string()",polygon:"v.string()",real:"v.number()",serial:"v.number()",smallint:"v.number()",smallserial:"v.number()",text:"v.string()",time:"v.string()","time with time zone":"v.string()","time without time zone":"v.string()",timestamp:"v.timestamp()","timestamp with time zone":"v.timestamp()","timestamp without time zone":"v.timestamp()",timestamptz:"v.timestamp()",tsquery:"v.string()",tsvector:"v.string()",uuid:"v.string()",varbit:"v.string()",varchar:"v.string()",xml:"v.string()"},W={bigint:"v.bigint()",binary:"v.bytes()",bit:"v.number()",blob:"v.bytes()",char:"v.string()",date:"v.date()",datetime:"v.timestamp()",decimal:"v.number()",double:"v.number()",enum:"v.string()",float:"v.number()",int:"v.number()",integer:"v.number()",json:"v.any()",longblob:"v.bytes()",longtext:"v.string()",mediumblob:"v.bytes()",mediumint:"v.number()",mediumtext:"v.string()",numeric:"v.number()",set:"v.string()",smallint:"v.number()",text:"v.string()",time:"v.string()",timestamp:"v.timestamp()",tinyblob:"v.bytes()",tinyint:"v.number()",tinytext:"v.string()",varbinary:"v.bytes()",varchar:"v.string()",year:"v.number()"},w=(e,t)=>{const r=(t==="postgres"?Q:W)[e.dataType],s=e.references===void 0?r:`v.id(${JSON.stringify(e.references.table)})`;let a=s??"v.any()";for(let o=0;o<e.arrayDepth;o+=1)a=`v.array(${a})`;return e.nullable&&(a=`v.optional(${a})`),{expression:a,known:s!==void 0}},M=/^[A-Z_$][\w$]*$/i,X=/[^\dA-Z]+(.)?/gi,z=/^\d+/,Z=/[^\w-]/g,V=/[\u003C\u003E\u002F\u2028\u2029]/g,ee={"/":String.raw`\u002F`,"\u2028":String.raw`\u2028`,"\u2029":String.raw`\u2029`,"<":String.raw`\u003C`,">":String.raw`\u003E`},f=e=>JSON.stringify(e).replaceAll(V,t=>ee[t]??t),S=e=>M.test(e)?e:f(e),ne=e=>M.test(e)?`.${e}`:`[${f(e)}]`,x=e=>e.replaceAll("*/",String.raw`*\/`),te=e=>{const t=e.replaceAll(Z,"_");return t===""?"table":t},re=e=>{const n=e.replaceAll(X,(r,s)=>s?.toUpperCase()??"").replace(z,"");return n===""?"table":`${n.charAt(0).toLowerCase()}${n.slice(1)}`},C=e=>e.columns.filter(t=>!h.has(t.name)),ae=e=>{const t=new Set(e.primaryKey);for(const n of e.indexes)for(const r of n.columns)t.add(r);for(const n of e.columns)n.references!==void 0&&t.add(n.name);return[...t].filter(n=>!h.has(n))},D=(e,t,n,r)=>e.references===void 0||t.has(e.references.table)?e:(r.push(`${n}.${e.name}: references \`${e.references.table}\`, which isn't in the generated schema — emitted as a plain column instead of \`v.id(...)\`.`),{arrayDepth:e.arrayDepth,dataType:e.dataType,name:e.name,nullable:e.nullable}),se=(e,t,n,r)=>{const s=[];for(const o of e.columns){if(h.has(o.name)){r.push(`${e.name}.${o.name}: skipped — \`${o.name}\` is a Lunora system column. Rename it in the source database or map it by hand.`);continue}const i=D(o,n,e.name,r),{expression:c,known:m}=w(i,t);!m&&i.references===void 0&&(r.push(`${e.name}.${o.name}: no mapping for SQL type \`${o.dataType}\` — emitted as \`v.any()\`.`),s.push(` // TODO: \`${x(o.dataType)}\` has no direct validator; narrow this.`)),s.push(` ${S(o.name)}: ${c},`)}const a=[' .global({ backend: "hyperdrive" })'];if(e.primaryKey.length>0&&e.primaryKey.every(o=>!h.has(o))){const o=e.primaryKey.map(i=>f(i)).join(", ");a.push(` .index(${f(`by_${e.primaryKey.join("_")}`)}, [${o}], { unique: true })`)}for(const o of e.indexes){const i=o.columns.filter(u=>!h.has(u));if(i.length===0)continue;const c=i.map(u=>f(u)).join(", "),m=o.unique?", { unique: true }":"";a.push(` .index(${f(o.name)}, [${c}]${m})`)}return` ${S(e.name)}: defineTable({
|
|
6
|
-
${s.join(`
|
|
7
|
-
`)}
|
|
8
|
-
})
|
|
9
|
-
${a.join(`
|
|
10
|
-
`)},`},oe=(e,t,n)=>{const r=new Set(e.tables.map(a=>a.name)),s=e.tables.map(a=>se(a,e.dialect,r,n)).join(`
|
|
11
|
-
`);return`/**
|
|
12
|
-
* Generated by \`lunora introspect\` from an existing ${e.dialect==="postgres"?"Postgres":"MySQL"} database.
|
|
13
|
-
*
|
|
14
|
-
* This file is a STARTING POINT, not a build artifact — it is written once and is
|
|
15
|
-
* yours to edit. Review it before shipping: column types are mapped
|
|
16
|
-
* conservatively, and every table is \`.global({ backend: "hyperdrive" })\` because
|
|
17
|
-
* its rows live in the external database. Re-running \`lunora introspect\` will not
|
|
18
|
-
* overwrite it unless you pass \`--force\`.
|
|
19
|
-
*/
|
|
20
|
-
import { defineSchema, defineTable, v } from "${t.serverImport}";
|
|
21
|
-
|
|
22
|
-
export default defineSchema({
|
|
23
|
-
${s}
|
|
24
|
-
});
|
|
25
|
-
`},ie=(e,t,n,r=new Set([e.name]),s=[])=>{const a=re(e.name),o=ae(e),i=new Map(C(e).map(l=>[l.name,l])),c=o.map(l=>{const d=i.get(l);if(d===void 0)return;const p=D({...d,nullable:!1},r,e.name,[]),{expression:y,known:A}=w(p,t);return!A&&p.references===void 0&&s.push(`${e.name}.${l}: filter falls back to \`v.any()\` (no mapping for SQL type \`${d.dataType}\`).`),` ${S(l)}: ${y},`}).filter(l=>l!==void 0),m=[f("_creationTime"),...o.map(l=>f(l))].join(", "),u=`ctx.db${ne(e.name)}`;return`/**
|
|
26
|
-
* Generated by \`lunora introspect\` for the \`${x(e.name)}\` table — a
|
|
27
|
-
* starting point you own and edit.
|
|
28
|
-
*
|
|
29
|
-
* Both procedures are RPC-only. Add \`.expose({ rest: true })\` once you've decided
|
|
30
|
-
* this data should be public, and gate them with your auth/RLS middleware first —
|
|
31
|
-
* \`introspect\` cannot know who is allowed to read this table.
|
|
32
|
-
*/
|
|
33
|
-
import { defineListArgs, v } from "${n.serverImport}";
|
|
34
|
-
|
|
35
|
-
import type { Doc } from "./_generated/dataModel";
|
|
36
|
-
import { c } from "./_generated/server";
|
|
37
|
-
|
|
38
|
-
const ${a}List = defineListArgs<Doc<${f(e.name)}>>()({
|
|
39
|
-
// Only index-backed columns are published as filterable, so a caller cannot
|
|
40
|
-
// reach a column you did not choose to expose. Note that \`contains\` and the
|
|
41
|
-
// negative operators still scan — narrow this list, and review it, before
|
|
42
|
-
// adding \`.expose({ rest: true })\`.
|
|
43
|
-
filter: {
|
|
44
|
-
${c.join(`
|
|
45
|
-
`)}
|
|
46
|
-
},
|
|
47
|
-
orderBy: [${m}],
|
|
48
|
-
});
|
|
49
|
-
|
|
50
|
-
export const list = c.query.input(${a}List.args).query(({ args, ctx }) => ${u}.findMany(${a}List.toQueryArgs(args)));
|
|
51
|
-
|
|
52
|
-
export const get = c.query.input({ id: v.id(${f(e.name)}) }).query(({ args, ctx }) => ${u}.get(args.id));
|
|
53
|
-
`},ce=(e,t)=>{const n=[],r=new Set(e.tables.map(a=>a.name)),s=[{contents:oe(e,t,n),path:"schema.ts"}];if(t.procedures){const a=new Map([["schema","the generated schema module"]]);for(const o of e.tables){if(C(o).length===0){n.push(`${o.name}: no usable columns — procedure module skipped.`);continue}const i=te(o.name);i!==o.name&&n.push(`${o.name}: written as \`${i}.ts\` — the table name isn't usable as a filename.`);const c=a.get(i);if(c!==void 0){n.push(`${o.name}: procedure module skipped — its filename \`${i}.ts\` collides with table \`${c}\`.`);continue}a.set(i,o.name),s.push({contents:ie(o,e.dialect,t,r,n),path:`${i}.ts`})}}return{files:s,warnings:n}},_=/^[A-Z_$][\w$]*$/i,me=e=>e.startsWith("v.optional(")&&e.endsWith(")")?e.slice(11,-1):e,le=(e,t,n)=>{const r=[],s=new Set(t?.columns.map(a=>a.name));for(const a of e.columns){if(h.has(a.name)||s.has(a.name))continue;if(!_.test(a.name)){n.warnings.push(`${e.name}.${a.name}: skipped — column names must be bare identifiers to merge.`);continue}const o=a.references!==void 0&&!n.present.has(a.references.table),{expression:i}=w(o?{...a,references:void 0}:a,n.dialect);r.push({column:a.name,kind:"addOptionalColumn",table:e.name,validator:me(i)}),!a.nullable&&t!==void 0&&n.warnings.push(`${e.name}.${a.name}: added as \`v.optional(...)\` — a required column on an existing table needs a backfill migration.`)}return r},ue=(e,t,n)=>{const r=[],s=new Set(t?.indexes.map(a=>a.name));for(const a of e.indexes){const o=a.columns.filter(i=>!h.has(i));if(!(s.has(a.name)||o.length===0)){if(!_.test(a.name)||!o.every(i=>_.test(i))){n.push(`${e.name}: index \`${a.name}\` skipped — index and column names must be bare identifiers to merge.`);continue}r.push({fields:o,kind:"addIndex",name:a.name,table:e.name,...a.unique?{unique:!0}:{}})}}return r},de=(e,t,n)=>{const r=[],s=[],a=new Map(t.map(i=>[i.name,i])),o=new Set([...a.keys(),...e.tables.map(i=>i.name)]);for(const i of e.tables){if(!_.test(i.name)){s.push(`${i.name}: skipped — merging into an existing schema needs a table name that is a bare identifier.`);continue}const c=a.get(i.name);c===void 0&&r.push({global:{backend:"hyperdrive"},kind:"addTable",table:i.name}),r.push(...le(i,c,{dialect:n,present:o,warnings:s}),...ue(i,c,s))}return{edits:r,warnings:s}},pe=(e,t,n)=>{const r=F(e);if(!r.ok)return{applied:0,warnings:[`lunora/schema.ts could not be parsed (${r.reason}) — leave it alone and merge by hand, or pass --force.`]};const s=de(t,r.tables,n),a=[...s.warnings];let o=e,i=0;for(const c of s.edits){const m=P(o,c);m.ok?(o=m.text,i+=1):a.push(`${c.table}: skipped one edit (${m.reason}).`)}return{applied:i,warnings:a,...i===0?{}:{text:o}}},g=(e,t)=>{const n=e[t]??e[t.toLowerCase()]??e[t.toUpperCase()];return typeof n=="string"?n:typeof n=="number"||typeof n=="bigint"||typeof n=="boolean"?String(n):""},ge=`
|
|
54
|
-
SELECT c.table_name, c.column_name, c.is_nullable, c.data_type, c.udt_name
|
|
55
|
-
FROM information_schema.columns c
|
|
56
|
-
JOIN information_schema.tables t
|
|
57
|
-
ON t.table_schema = c.table_schema AND t.table_name = c.table_name
|
|
58
|
-
WHERE c.table_schema = $1 AND t.table_type = 'BASE TABLE'
|
|
59
|
-
ORDER BY c.table_name, c.ordinal_position`,fe=`
|
|
60
|
-
SELECT tc.table_name, kcu.column_name
|
|
61
|
-
FROM information_schema.table_constraints tc
|
|
62
|
-
JOIN information_schema.key_column_usage kcu
|
|
63
|
-
ON kcu.constraint_name = tc.constraint_name AND kcu.table_schema = tc.table_schema
|
|
64
|
-
WHERE tc.table_schema = $1 AND tc.constraint_type = 'PRIMARY KEY'
|
|
65
|
-
ORDER BY tc.table_name, kcu.ordinal_position`,ve=`
|
|
66
|
-
SELECT tc.table_name, kcu.column_name, ccu.table_name AS foreign_table, ccu.column_name AS foreign_column
|
|
67
|
-
FROM information_schema.table_constraints tc
|
|
68
|
-
JOIN information_schema.key_column_usage kcu
|
|
69
|
-
ON kcu.constraint_name = tc.constraint_name AND kcu.table_schema = tc.table_schema
|
|
70
|
-
JOIN information_schema.constraint_column_usage ccu
|
|
71
|
-
ON ccu.constraint_name = tc.constraint_name AND ccu.table_schema = tc.table_schema
|
|
72
|
-
WHERE tc.table_schema = $1 AND tc.constraint_type = 'FOREIGN KEY'`,he=`
|
|
73
|
-
SELECT t.relname AS table_name, i.relname AS index_name, ix.indisunique AS is_unique, a.attname AS column_name
|
|
74
|
-
FROM pg_class t
|
|
75
|
-
JOIN pg_index ix ON t.oid = ix.indrelid
|
|
76
|
-
JOIN pg_class i ON i.oid = ix.indexrelid
|
|
77
|
-
JOIN pg_namespace n ON n.oid = t.relnamespace
|
|
78
|
-
CROSS JOIN LATERAL unnest(ix.indkey) WITH ORDINALITY AS k(attnum, ord)
|
|
79
|
-
JOIN pg_attribute a ON a.attrelid = t.oid AND a.attnum = k.attnum
|
|
80
|
-
WHERE n.nspname = $1 AND t.relkind = 'r' AND NOT ix.indisprimary
|
|
81
|
-
ORDER BY t.relname, i.relname, k.ord`,be=`
|
|
82
|
-
SELECT c.TABLE_NAME, c.COLUMN_NAME, c.IS_NULLABLE, c.DATA_TYPE
|
|
83
|
-
FROM information_schema.COLUMNS c
|
|
84
|
-
JOIN information_schema.TABLES t
|
|
85
|
-
ON t.TABLE_SCHEMA = c.TABLE_SCHEMA AND t.TABLE_NAME = c.TABLE_NAME
|
|
86
|
-
WHERE c.TABLE_SCHEMA = ? AND t.TABLE_TYPE = 'BASE TABLE'
|
|
87
|
-
ORDER BY c.TABLE_NAME, c.ORDINAL_POSITION`,Ee=`
|
|
88
|
-
SELECT TABLE_NAME, COLUMN_NAME
|
|
89
|
-
FROM information_schema.KEY_COLUMN_USAGE
|
|
90
|
-
WHERE TABLE_SCHEMA = ? AND CONSTRAINT_NAME = 'PRIMARY'
|
|
91
|
-
ORDER BY TABLE_NAME, ORDINAL_POSITION`,_e=`
|
|
92
|
-
SELECT TABLE_NAME, COLUMN_NAME, REFERENCED_TABLE_NAME AS foreign_table, REFERENCED_COLUMN_NAME AS foreign_column
|
|
93
|
-
FROM information_schema.KEY_COLUMN_USAGE
|
|
94
|
-
WHERE TABLE_SCHEMA = ? AND REFERENCED_TABLE_NAME IS NOT NULL`,ye=`
|
|
95
|
-
SELECT TABLE_NAME, INDEX_NAME AS index_name, NON_UNIQUE, COLUMN_NAME
|
|
96
|
-
FROM information_schema.STATISTICS
|
|
97
|
-
WHERE TABLE_SCHEMA = ? AND INDEX_NAME <> 'PRIMARY'
|
|
98
|
-
ORDER BY TABLE_NAME, INDEX_NAME, SEQ_IN_INDEX`,E=e=>{const t=new Map;for(const n of e){const r=g(n,"table_name"),s=t.get(r);s===void 0?t.set(r,[n]):s.push(n)}return t},Ae=(e,t)=>{const n=g(e,"data_type").toLowerCase();if(t!=="postgres")return{arrayDepth:0,dataType:n};const r=g(e,"udt_name").toLowerCase();return n==="array"&&r.startsWith("_")?{arrayDepth:1,dataType:r.slice(1)}:{arrayDepth:0,dataType:r===""?n:r}},Se=(e,t)=>{const n=new Map;for(const r of e){const s=g(r,"index_name"),a=t==="postgres"?g(r,"is_unique")==="true":g(r,"NON_UNIQUE")==="0",o=n.get(s);o===void 0?n.set(s,{columns:[g(r,"column_name")],unique:a}):o.columns.push(g(r,"column_name"))}return[...n.entries()].map(([r,s])=>({columns:s.columns,name:r,unique:s.unique}))},Ne=async(e,t,n)=>{const r=t==="postgres",[s,a,o,i]=await Promise.all([e(r?ge:be,[n]),e(r?fe:Ee,[n]),e(r?ve:_e,[n]),e(r?he:ye,[n])]),c=E(a),m=E(o),u=E(i),l=[];for(const[d,p]of E(s)){const y=new Map((m.get(d)??[]).map(v=>[g(v,"column_name"),{column:g(v,"foreign_column"),table:g(v,"foreign_table")}])),A=p.map(v=>{const R=g(v,"column_name"),$=y.get(R);return{...Ae(v,t),name:R,nullable:g(v,"is_nullable").toUpperCase()==="YES",...$===void 0?{}:{references:$}}});l.push({columns:A,indexes:Se(u.get(d)??[],t),name:d,primaryKey:(c.get(d)??[]).map(v=>g(v,"column_name"))})}return l.sort((d,p)=>d.name.localeCompare(p.name)),{dialect:t,tables:l}},we=e=>{try{const t=JSON.parse(O(b(e,"package.json"),"utf8"));return t.dependencies?.lunorash===void 0&&t.devDependencies?.lunorash===void 0?"@lunora/server":"lunorash/server"}catch{return"@lunora/server"}},Re=async(e,t,n)=>{const r=b(t,e.path);return T(r)&&n.force!==!0?(n.logger.warn(`skipped lunora/${e.path} — it already exists (pass --force to overwrite)`),!1):n.dryRun===!0?(n.logger.info(`would write lunora/${e.path} (${String(e.contents.split(`
|
|
99
|
-
`).length)} lines)`),!1):(await k(t,{recursive:!0}),await I(r,e.contents,"utf8"),n.logger.info(`wrote lunora/${e.path}`),!0)},$e=(e,t)=>{const n=t.tables;if(n===void 0||n.length===0)return e.tables;for(const r of n)e.tables.some(s=>s.name===r)||t.logger.warn(`--tables: no table named "${r}" exists in this schema — skipped.`);return e.tables.filter(r=>n.includes(r.name))},Le=async(e,t,n,r)=>{const s=pe(O(e,"utf8"),t,n);for(const a of s.warnings)r.logger.warn(a);return s.text===void 0?(r.logger.info("lunora/schema.ts is already up to date with the database."),!1):r.dryRun===!0?(r.logger.info(`would merge ${String(s.applied)} addition(s) into lunora/schema.ts`),!1):(await I(e,s.text,"utf8"),r.logger.info(`merged ${String(s.applied)} addition(s) into lunora/schema.ts`),!0)},Te=async e=>{const t=e.cwd??process.cwd();if(e.connection===void 0&&(e.url===void 0||e.url===""))return e.logger.error("`lunora introspect` needs a database URL: pass --url, or set DATABASE_URL."),{code:1,written:[]};const n=e.connection===void 0?j(e.url):e.dialect??"postgres",r=e.connection??await J(e.url,n,e.schema,t);let s;try{s=await Ne(r.execute,n,r.schema)}finally{e.connection===void 0&&await r.close()}const a=$e(s,e);if(a.length===0)return e.logger.error("no tables found to introspect — check --schema and --tables."),{code:1,written:[]};const{files:o,warnings:i}=ce({...s,tables:a},{procedures:e.procedures!==!1,serverImport:we(t)}),c=b(t,"lunora"),m=[],u=b(c,"schema.ts"),l=T(u)&&e.force!==!0,d=l?o.filter(p=>p.path!=="schema.ts"):o;l&&await Le(u,{...s,tables:a},n,e)&&m.push("schema.ts");for(const p of d)await Re(p,c,e)&&m.push(p.path);for(const p of i)e.logger.warn(p);return e.logger.info(`introspected ${String(a.length)} table(s) from ${n}. Review the generated files before running \`lunora dev\`.`),{code:0,written:m}},Be=B(async({cwd:e,logger:t,options:n})=>({code:(await Te({cwd:e,dryRun:n.dryRun===!0,force:n.force===!0,logger:t,procedures:n.procedures!==!1,schema:n.schema,tables:n.tables===void 0?void 0:n.tables.split(",").map(s=>s.trim()),url:n.url??process.env.DATABASE_URL})).code}));export{Be as execute,we as resolveServerImport,Te as runIntrospectCommand};
|
|
1
|
+
import{readdirSync as w,lstatSync as R,existsSync as T}from"node:fs";import{join as v,basename as $}from"node:path";import{pathToFileURL as O}from"node:url";import{d as _}from"../packem_shared/command-DwC11Cwe.mjs";import{v as N,i as g,p as E,l as x}from"../packem_shared/output-format-DfogXx0p.mjs";const c=".eval.ts",b=new Set([".git","_generated","dist","node_modules"]),p=(e,s=[])=>{let r;try{r=w(e)}catch{return s}for(const t of r){const o=v(e,t);let n;try{n=R(o)}catch{continue}if(n.isDirectory()){if(b.has(t))continue;p(o,s)}else n.isFile()&&t.endsWith(c)&&s.push(o)}return s.toSorted((t,o)=>t.localeCompare(o))},L=e=>typeof e=="object"&&e!==null&&typeof e.run=="function",S=e=>typeof e=="number"&&Number.isFinite(e)&&e>=0&&e<=1,I="evals",A='"lunora eval" needs native TypeScript execution — run Node ≥23.6, or a TS loader/transform (tracked in plans/245-eval-runner-design.md §8.3)',D=/unknown file extension ".ts"/i,y=e=>e instanceof Error?e.code==="ERR_UNKNOWN_FILE_EXTENSION"?!0:D.test(e.message):!1,m=e=>$(e,c),M=e=>({average:e.result?.average,error:e.error,items:e.result?.items,name:e.name,passed:e.passed,path:e.path,threshold:e.threshold}),F=e=>({code:e.code,error:e.error,evals:e.evals.map(s=>M(s))}),i=(e,s,r)=>{e.error(r);const t={code:1,error:r,evals:[]};return g(s)&&E(F(t)),t},U=(e,s,r)=>{if(!T(e))return r.info(`eval: no "${s}" directory — nothing to run`),[];const t=p(e);return t.length===0&&r.info(`eval: no ${c} files found under "${s}"`),t},C=async e=>{const r=(await import(O(e).href)).default;if(!L(r))throw new Error("does not default-export an eval module (expected `{ run(): Promise<EvalResult>, name?, threshold? }`)");return r},J=async(e,s)=>{let r;try{r=await C(e)}catch(n){if(y(n))throw n;return{error:n instanceof Error?n.message:String(n),name:m(e),passed:!1,path:e}}const t=r.name??m(e);if(r.threshold!==void 0&&!S(r.threshold))return{error:`invalid \`threshold\` export: must be a number in [0, 1] — received ${JSON.stringify(r.threshold)}`,name:t,passed:!1,path:e};const o=r.threshold??s;try{const n=await r.run(),l=o===void 0||n.average>=o;return{name:t,passed:l,path:e,result:n,threshold:o}}catch(n){return{error:n instanceof Error?n.message:String(n),name:t,passed:!1,path:e,threshold:o}}},W=async(e,s)=>{const r=[];for(const t of e)r.push(await J(t,s));return r},H=e=>{if(e.error!==void 0)return`ERROR: ${e.error}`;const s=e.passed?"pass":"FAIL",r=e.result?.items.length??0;return`${s} (${String(r)} cases)`},V=e=>{if(e.length===0)return[];const s=Math.max(4,...e.map(t=>t.name.length)),r=[`${"NAME".padEnd(s)} SCORE THRESHOLD STATUS`];for(const t of e){const o=t.result===void 0?"—":t.result.average.toFixed(3),n=t.threshold===void 0?"—":t.threshold.toFixed(3);r.push(`${t.name.padEnd(s)} ${o.padEnd(6)} ${n.padEnd(9)} ${H(t)}`)}return r},X=async e=>{const s=e.cwd??process.cwd(),r=x(e.format,e.logger),t=N("eval",e.format);if(t!==void 0)return e.logger.error(t),{code:1,error:t,evals:[]};if(e.threshold!==void 0&&!S(e.threshold))return i(r,e.format,`eval: --threshold must be a number in [0, 1] — received "${String(e.threshold)}"`);const o=e.dir??I,n=v(s,o),l=U(n,o,r);let d;try{d=await W(l,e.threshold)}catch(a){if(!y(a))throw a;return i(r,e.format,A)}if(e.threshold!==void 0&&d.length===0){const a=`eval: --threshold ${String(e.threshold)} was set but 0 eval files were discovered under "${o}" — nothing was gated`;return i(r,e.format,a)}for(const a of V(d))r.info(a);const h=d.filter(a=>!a.passed),f=h.length>0?1:0;f===0?r.success(`eval: ${String(d.length)} eval(s) passed`):r.error(`eval: ${String(h.length)}/${String(d.length)} eval(s) failed`);const u={code:f,evals:d};return g(e.format)&&E(F(u)),u},z=_(async({cwd:e,logger:s,options:r})=>({code:(await X({cwd:e,dir:r.dir,format:r.format,logger:s,threshold:r.threshold})).code}));export{z as execute,X as runEvalCommand};
|
|
@@ -1,10 +1,99 @@
|
|
|
1
|
-
import{
|
|
2
|
-
|
|
3
|
-
|
|
4
|
-
|
|
5
|
-
${
|
|
6
|
-
|
|
7
|
-
`)}
|
|
8
|
-
|
|
9
|
-
|
|
10
|
-
`)
|
|
1
|
+
import{existsSync as T,readFileSync as O}from"node:fs";import{writeFile as I,mkdir as k}from"node:fs/promises";import{join as b}from"@visulima/path";import{d as B}from"../packem_shared/command-DwC11Cwe.mjs";import{createRequire as U}from"node:module";import{LunoraError as N}from"@lunora/errors";import{addArgsFor as Y,detectPackageManager as q,parseSchema as F,applyAdditiveEdit as P}from"@lunora/config";const H=/^\//,K=(e,t)=>{try{const{args:n,command:r}=Y(q(e),[t],{dev:!0});return`${r} ${n.join(" ")}`}catch{return`<your-package-manager> add -D ${t}`}},L=(e,t,n)=>{const r=U(b(n,"noop.cjs"));try{r.resolve(e)}catch{throw new N("INTERNAL",`\`lunora introspect\` needs the \`${t}\` driver to read this database, and it isn't installed.
|
|
2
|
+
|
|
3
|
+
Install it in your project:
|
|
4
|
+
|
|
5
|
+
${K(n,t)}`)}return r(e)},j=e=>{const t=e.slice(0,Math.max(0,e.indexOf(":"))).toLowerCase();if(t==="postgres"||t==="postgresql")return"postgres";if(t==="mysql"||t==="mariadb")return"mysql";throw new N("INTERNAL",`Unrecognised database URL scheme \`${t}\`. Expected a \`postgres://\`, \`postgresql://\`, \`mysql://\`, or \`mariadb://\` connection string.`)},G=e=>{try{const t=new URL(e).pathname.replace(H,"");return t===""?void 0:decodeURIComponent(t)}catch{return}},J=async(e,t,n,r=process.cwd())=>{if(t==="postgres"){const m=L("pg","pg",r).Client,u=new m({connectionString:e});return await u.connect(),{close:async()=>{await u.end()},execute:async(l,d)=>(await u.query(l,[...d])).rows,schema:n??"public"}}const a=L("mysql2/promise","mysql2",r).createConnection,o=await a(e),i=n??G(e);if(i===void 0)throw new N("INTERNAL","A MySQL connection string must name a database (`mysql://host/<database>`), or pass `--schema`.");return{close:async()=>{await o.end()},execute:async(c,m)=>{const[u]=await o.execute(c,[...m]);return Array.isArray(u)?u:[]},schema:i}},h=new Set(["_creationTime","_id"]),Q={bigint:"v.bigint()",bigserial:"v.bigint()",bit:"v.string()",bool:"v.boolean()",boolean:"v.boolean()",box:"v.string()",bpchar:"v.string()",bytea:"v.bytes()",char:"v.string()",character:"v.string()","character varying":"v.string()",cidr:"v.string()",circle:"v.string()",citext:"v.string()",date:"v.date()","double precision":"v.number()",float4:"v.number()",float8:"v.number()",inet:"v.string()",int:"v.number()",int2:"v.number()",int4:"v.number()",int8:"v.bigint()",integer:"v.number()",interval:"v.string()",json:"v.any()",jsonb:"v.any()",line:"v.string()",lseg:"v.string()",macaddr:"v.string()",money:"v.number()",name:"v.string()",numeric:"v.number()",path:"v.string()",point:"v.string()",polygon:"v.string()",real:"v.number()",serial:"v.number()",smallint:"v.number()",smallserial:"v.number()",text:"v.string()",time:"v.string()","time with time zone":"v.string()","time without time zone":"v.string()",timestamp:"v.timestamp()","timestamp with time zone":"v.timestamp()","timestamp without time zone":"v.timestamp()",timestamptz:"v.timestamp()",tsquery:"v.string()",tsvector:"v.string()",uuid:"v.string()",varbit:"v.string()",varchar:"v.string()",xml:"v.string()"},W={bigint:"v.bigint()",binary:"v.bytes()",bit:"v.number()",blob:"v.bytes()",char:"v.string()",date:"v.date()",datetime:"v.timestamp()",decimal:"v.number()",double:"v.number()",enum:"v.string()",float:"v.number()",int:"v.number()",integer:"v.number()",json:"v.any()",longblob:"v.bytes()",longtext:"v.string()",mediumblob:"v.bytes()",mediumint:"v.number()",mediumtext:"v.string()",numeric:"v.number()",set:"v.string()",smallint:"v.number()",text:"v.string()",time:"v.string()",timestamp:"v.timestamp()",tinyblob:"v.bytes()",tinyint:"v.number()",tinytext:"v.string()",varbinary:"v.bytes()",varchar:"v.string()",year:"v.number()"},w=(e,t)=>{const r=(t==="postgres"?Q:W)[e.dataType],s=e.references===void 0?r:`v.id(${JSON.stringify(e.references.table)})`;let a=s??"v.any()";for(let o=0;o<e.arrayDepth;o+=1)a=`v.array(${a})`;return e.nullable&&(a=`v.optional(${a})`),{expression:a,known:s!==void 0}},M=/^[A-Z_$][\w$]*$/i,X=/[^\dA-Z]+(.)?/gi,z=/^\d+/,Z=/[^\w-]/g,V=/[\u003C\u003E\u002F\u2028\u2029]/g,ee={"/":String.raw`\u002F`,"\u2028":String.raw`\u2028`,"\u2029":String.raw`\u2029`,"<":String.raw`\u003C`,">":String.raw`\u003E`},f=e=>JSON.stringify(e).replaceAll(V,t=>ee[t]??t),S=e=>M.test(e)?e:f(e),ne=e=>M.test(e)?`.${e}`:`[${f(e)}]`,x=e=>e.replaceAll("*/",String.raw`*\/`),te=e=>{const t=e.replaceAll(Z,"_");return t===""?"table":t},re=e=>{const n=e.replaceAll(X,(r,s)=>s?.toUpperCase()??"").replace(z,"");return n===""?"table":`${n.charAt(0).toLowerCase()}${n.slice(1)}`},C=e=>e.columns.filter(t=>!h.has(t.name)),ae=e=>{const t=new Set(e.primaryKey);for(const n of e.indexes)for(const r of n.columns)t.add(r);for(const n of e.columns)n.references!==void 0&&t.add(n.name);return[...t].filter(n=>!h.has(n))},D=(e,t,n,r)=>e.references===void 0||t.has(e.references.table)?e:(r.push(`${n}.${e.name}: references \`${e.references.table}\`, which isn't in the generated schema — emitted as a plain column instead of \`v.id(...)\`.`),{arrayDepth:e.arrayDepth,dataType:e.dataType,name:e.name,nullable:e.nullable}),se=(e,t,n,r)=>{const s=[];for(const o of e.columns){if(h.has(o.name)){r.push(`${e.name}.${o.name}: skipped — \`${o.name}\` is a Lunora system column. Rename it in the source database or map it by hand.`);continue}const i=D(o,n,e.name,r),{expression:c,known:m}=w(i,t);!m&&i.references===void 0&&(r.push(`${e.name}.${o.name}: no mapping for SQL type \`${o.dataType}\` — emitted as \`v.any()\`.`),s.push(` // TODO: \`${x(o.dataType)}\` has no direct validator; narrow this.`)),s.push(` ${S(o.name)}: ${c},`)}const a=[' .global({ backend: "hyperdrive" })'];if(e.primaryKey.length>0&&e.primaryKey.every(o=>!h.has(o))){const o=e.primaryKey.map(i=>f(i)).join(", ");a.push(` .index(${f(`by_${e.primaryKey.join("_")}`)}, [${o}], { unique: true })`)}for(const o of e.indexes){const i=o.columns.filter(u=>!h.has(u));if(i.length===0)continue;const c=i.map(u=>f(u)).join(", "),m=o.unique?", { unique: true }":"";a.push(` .index(${f(o.name)}, [${c}]${m})`)}return` ${S(e.name)}: defineTable({
|
|
6
|
+
${s.join(`
|
|
7
|
+
`)}
|
|
8
|
+
})
|
|
9
|
+
${a.join(`
|
|
10
|
+
`)},`},oe=(e,t,n)=>{const r=new Set(e.tables.map(a=>a.name)),s=e.tables.map(a=>se(a,e.dialect,r,n)).join(`
|
|
11
|
+
`);return`/**
|
|
12
|
+
* Generated by \`lunora introspect\` from an existing ${e.dialect==="postgres"?"Postgres":"MySQL"} database.
|
|
13
|
+
*
|
|
14
|
+
* This file is a STARTING POINT, not a build artifact — it is written once and is
|
|
15
|
+
* yours to edit. Review it before shipping: column types are mapped
|
|
16
|
+
* conservatively, and every table is \`.global({ backend: "hyperdrive" })\` because
|
|
17
|
+
* its rows live in the external database. Re-running \`lunora introspect\` will not
|
|
18
|
+
* overwrite it unless you pass \`--force\`.
|
|
19
|
+
*/
|
|
20
|
+
import { defineSchema, defineTable, v } from "${t.serverImport}";
|
|
21
|
+
|
|
22
|
+
export default defineSchema({
|
|
23
|
+
${s}
|
|
24
|
+
});
|
|
25
|
+
`},ie=(e,t,n,r=new Set([e.name]),s=[])=>{const a=re(e.name),o=ae(e),i=new Map(C(e).map(l=>[l.name,l])),c=o.map(l=>{const d=i.get(l);if(d===void 0)return;const p=D({...d,nullable:!1},r,e.name,[]),{expression:y,known:A}=w(p,t);return!A&&p.references===void 0&&s.push(`${e.name}.${l}: filter falls back to \`v.any()\` (no mapping for SQL type \`${d.dataType}\`).`),` ${S(l)}: ${y},`}).filter(l=>l!==void 0),m=[f("_creationTime"),...o.map(l=>f(l))].join(", "),u=`ctx.db${ne(e.name)}`;return`/**
|
|
26
|
+
* Generated by \`lunora introspect\` for the \`${x(e.name)}\` table — a
|
|
27
|
+
* starting point you own and edit.
|
|
28
|
+
*
|
|
29
|
+
* Both procedures are RPC-only. Add \`.expose({ rest: true })\` once you've decided
|
|
30
|
+
* this data should be public, and gate them with your auth/RLS middleware first —
|
|
31
|
+
* \`introspect\` cannot know who is allowed to read this table.
|
|
32
|
+
*/
|
|
33
|
+
import { defineListArgs, v } from "${n.serverImport}";
|
|
34
|
+
|
|
35
|
+
import type { Doc } from "./_generated/dataModel";
|
|
36
|
+
import { c } from "./_generated/server";
|
|
37
|
+
|
|
38
|
+
const ${a}List = defineListArgs<Doc<${f(e.name)}>>()({
|
|
39
|
+
// Only index-backed columns are published as filterable, so a caller cannot
|
|
40
|
+
// reach a column you did not choose to expose. Note that \`contains\` and the
|
|
41
|
+
// negative operators still scan — narrow this list, and review it, before
|
|
42
|
+
// adding \`.expose({ rest: true })\`.
|
|
43
|
+
filter: {
|
|
44
|
+
${c.join(`
|
|
45
|
+
`)}
|
|
46
|
+
},
|
|
47
|
+
orderBy: [${m}],
|
|
48
|
+
});
|
|
49
|
+
|
|
50
|
+
export const list = c.query.input(${a}List.args).query(({ args, ctx }) => ${u}.findMany(${a}List.toQueryArgs(args)));
|
|
51
|
+
|
|
52
|
+
export const get = c.query.input({ id: v.id(${f(e.name)}) }).query(({ args, ctx }) => ${u}.get(args.id));
|
|
53
|
+
`},ce=(e,t)=>{const n=[],r=new Set(e.tables.map(a=>a.name)),s=[{contents:oe(e,t,n),path:"schema.ts"}];if(t.procedures){const a=new Map([["schema","the generated schema module"]]);for(const o of e.tables){if(C(o).length===0){n.push(`${o.name}: no usable columns — procedure module skipped.`);continue}const i=te(o.name);i!==o.name&&n.push(`${o.name}: written as \`${i}.ts\` — the table name isn't usable as a filename.`);const c=a.get(i);if(c!==void 0){n.push(`${o.name}: procedure module skipped — its filename \`${i}.ts\` collides with table \`${c}\`.`);continue}a.set(i,o.name),s.push({contents:ie(o,e.dialect,t,r,n),path:`${i}.ts`})}}return{files:s,warnings:n}},_=/^[A-Z_$][\w$]*$/i,me=e=>e.startsWith("v.optional(")&&e.endsWith(")")?e.slice(11,-1):e,le=(e,t,n)=>{const r=[],s=new Set(t?.columns.map(a=>a.name));for(const a of e.columns){if(h.has(a.name)||s.has(a.name))continue;if(!_.test(a.name)){n.warnings.push(`${e.name}.${a.name}: skipped — column names must be bare identifiers to merge.`);continue}const o=a.references!==void 0&&!n.present.has(a.references.table),{expression:i}=w(o?{...a,references:void 0}:a,n.dialect);r.push({column:a.name,kind:"addOptionalColumn",table:e.name,validator:me(i)}),!a.nullable&&t!==void 0&&n.warnings.push(`${e.name}.${a.name}: added as \`v.optional(...)\` — a required column on an existing table needs a backfill migration.`)}return r},ue=(e,t,n)=>{const r=[],s=new Set(t?.indexes.map(a=>a.name));for(const a of e.indexes){const o=a.columns.filter(i=>!h.has(i));if(!(s.has(a.name)||o.length===0)){if(!_.test(a.name)||!o.every(i=>_.test(i))){n.push(`${e.name}: index \`${a.name}\` skipped — index and column names must be bare identifiers to merge.`);continue}r.push({fields:o,kind:"addIndex",name:a.name,table:e.name,...a.unique?{unique:!0}:{}})}}return r},de=(e,t,n)=>{const r=[],s=[],a=new Map(t.map(i=>[i.name,i])),o=new Set([...a.keys(),...e.tables.map(i=>i.name)]);for(const i of e.tables){if(!_.test(i.name)){s.push(`${i.name}: skipped — merging into an existing schema needs a table name that is a bare identifier.`);continue}const c=a.get(i.name);c===void 0&&r.push({global:{backend:"hyperdrive"},kind:"addTable",table:i.name}),r.push(...le(i,c,{dialect:n,present:o,warnings:s}),...ue(i,c,s))}return{edits:r,warnings:s}},pe=(e,t,n)=>{const r=F(e);if(!r.ok)return{applied:0,warnings:[`lunora/schema.ts could not be parsed (${r.reason}) — leave it alone and merge by hand, or pass --force.`]};const s=de(t,r.tables,n),a=[...s.warnings];let o=e,i=0;for(const c of s.edits){const m=P(o,c);m.ok?(o=m.text,i+=1):a.push(`${c.table}: skipped one edit (${m.reason}).`)}return{applied:i,warnings:a,...i===0?{}:{text:o}}},g=(e,t)=>{const n=e[t]??e[t.toLowerCase()]??e[t.toUpperCase()];return typeof n=="string"?n:typeof n=="number"||typeof n=="bigint"||typeof n=="boolean"?String(n):""},ge=`
|
|
54
|
+
SELECT c.table_name, c.column_name, c.is_nullable, c.data_type, c.udt_name
|
|
55
|
+
FROM information_schema.columns c
|
|
56
|
+
JOIN information_schema.tables t
|
|
57
|
+
ON t.table_schema = c.table_schema AND t.table_name = c.table_name
|
|
58
|
+
WHERE c.table_schema = $1 AND t.table_type = 'BASE TABLE'
|
|
59
|
+
ORDER BY c.table_name, c.ordinal_position`,fe=`
|
|
60
|
+
SELECT tc.table_name, kcu.column_name
|
|
61
|
+
FROM information_schema.table_constraints tc
|
|
62
|
+
JOIN information_schema.key_column_usage kcu
|
|
63
|
+
ON kcu.constraint_name = tc.constraint_name AND kcu.table_schema = tc.table_schema
|
|
64
|
+
WHERE tc.table_schema = $1 AND tc.constraint_type = 'PRIMARY KEY'
|
|
65
|
+
ORDER BY tc.table_name, kcu.ordinal_position`,ve=`
|
|
66
|
+
SELECT tc.table_name, kcu.column_name, ccu.table_name AS foreign_table, ccu.column_name AS foreign_column
|
|
67
|
+
FROM information_schema.table_constraints tc
|
|
68
|
+
JOIN information_schema.key_column_usage kcu
|
|
69
|
+
ON kcu.constraint_name = tc.constraint_name AND kcu.table_schema = tc.table_schema
|
|
70
|
+
JOIN information_schema.constraint_column_usage ccu
|
|
71
|
+
ON ccu.constraint_name = tc.constraint_name AND ccu.table_schema = tc.table_schema
|
|
72
|
+
WHERE tc.table_schema = $1 AND tc.constraint_type = 'FOREIGN KEY'`,he=`
|
|
73
|
+
SELECT t.relname AS table_name, i.relname AS index_name, ix.indisunique AS is_unique, a.attname AS column_name
|
|
74
|
+
FROM pg_class t
|
|
75
|
+
JOIN pg_index ix ON t.oid = ix.indrelid
|
|
76
|
+
JOIN pg_class i ON i.oid = ix.indexrelid
|
|
77
|
+
JOIN pg_namespace n ON n.oid = t.relnamespace
|
|
78
|
+
CROSS JOIN LATERAL unnest(ix.indkey) WITH ORDINALITY AS k(attnum, ord)
|
|
79
|
+
JOIN pg_attribute a ON a.attrelid = t.oid AND a.attnum = k.attnum
|
|
80
|
+
WHERE n.nspname = $1 AND t.relkind = 'r' AND NOT ix.indisprimary
|
|
81
|
+
ORDER BY t.relname, i.relname, k.ord`,be=`
|
|
82
|
+
SELECT c.TABLE_NAME, c.COLUMN_NAME, c.IS_NULLABLE, c.DATA_TYPE
|
|
83
|
+
FROM information_schema.COLUMNS c
|
|
84
|
+
JOIN information_schema.TABLES t
|
|
85
|
+
ON t.TABLE_SCHEMA = c.TABLE_SCHEMA AND t.TABLE_NAME = c.TABLE_NAME
|
|
86
|
+
WHERE c.TABLE_SCHEMA = ? AND t.TABLE_TYPE = 'BASE TABLE'
|
|
87
|
+
ORDER BY c.TABLE_NAME, c.ORDINAL_POSITION`,Ee=`
|
|
88
|
+
SELECT TABLE_NAME, COLUMN_NAME
|
|
89
|
+
FROM information_schema.KEY_COLUMN_USAGE
|
|
90
|
+
WHERE TABLE_SCHEMA = ? AND CONSTRAINT_NAME = 'PRIMARY'
|
|
91
|
+
ORDER BY TABLE_NAME, ORDINAL_POSITION`,_e=`
|
|
92
|
+
SELECT TABLE_NAME, COLUMN_NAME, REFERENCED_TABLE_NAME AS foreign_table, REFERENCED_COLUMN_NAME AS foreign_column
|
|
93
|
+
FROM information_schema.KEY_COLUMN_USAGE
|
|
94
|
+
WHERE TABLE_SCHEMA = ? AND REFERENCED_TABLE_NAME IS NOT NULL`,ye=`
|
|
95
|
+
SELECT TABLE_NAME, INDEX_NAME AS index_name, NON_UNIQUE, COLUMN_NAME
|
|
96
|
+
FROM information_schema.STATISTICS
|
|
97
|
+
WHERE TABLE_SCHEMA = ? AND INDEX_NAME <> 'PRIMARY'
|
|
98
|
+
ORDER BY TABLE_NAME, INDEX_NAME, SEQ_IN_INDEX`,E=e=>{const t=new Map;for(const n of e){const r=g(n,"table_name"),s=t.get(r);s===void 0?t.set(r,[n]):s.push(n)}return t},Ae=(e,t)=>{const n=g(e,"data_type").toLowerCase();if(t!=="postgres")return{arrayDepth:0,dataType:n};const r=g(e,"udt_name").toLowerCase();return n==="array"&&r.startsWith("_")?{arrayDepth:1,dataType:r.slice(1)}:{arrayDepth:0,dataType:r===""?n:r}},Se=(e,t)=>{const n=new Map;for(const r of e){const s=g(r,"index_name"),a=t==="postgres"?g(r,"is_unique")==="true":g(r,"NON_UNIQUE")==="0",o=n.get(s);o===void 0?n.set(s,{columns:[g(r,"column_name")],unique:a}):o.columns.push(g(r,"column_name"))}return[...n.entries()].map(([r,s])=>({columns:s.columns,name:r,unique:s.unique}))},Ne=async(e,t,n)=>{const r=t==="postgres",[s,a,o,i]=await Promise.all([e(r?ge:be,[n]),e(r?fe:Ee,[n]),e(r?ve:_e,[n]),e(r?he:ye,[n])]),c=E(a),m=E(o),u=E(i),l=[];for(const[d,p]of E(s)){const y=new Map((m.get(d)??[]).map(v=>[g(v,"column_name"),{column:g(v,"foreign_column"),table:g(v,"foreign_table")}])),A=p.map(v=>{const R=g(v,"column_name"),$=y.get(R);return{...Ae(v,t),name:R,nullable:g(v,"is_nullable").toUpperCase()==="YES",...$===void 0?{}:{references:$}}});l.push({columns:A,indexes:Se(u.get(d)??[],t),name:d,primaryKey:(c.get(d)??[]).map(v=>g(v,"column_name"))})}return l.sort((d,p)=>d.name.localeCompare(p.name)),{dialect:t,tables:l}},we=e=>{try{const t=JSON.parse(O(b(e,"package.json"),"utf8"));return t.dependencies?.lunorash===void 0&&t.devDependencies?.lunorash===void 0?"@lunora/server":"lunorash/server"}catch{return"@lunora/server"}},Re=async(e,t,n)=>{const r=b(t,e.path);return T(r)&&n.force!==!0?(n.logger.warn(`skipped lunora/${e.path} — it already exists (pass --force to overwrite)`),!1):n.dryRun===!0?(n.logger.info(`would write lunora/${e.path} (${String(e.contents.split(`
|
|
99
|
+
`).length)} lines)`),!1):(await k(t,{recursive:!0}),await I(r,e.contents,"utf8"),n.logger.info(`wrote lunora/${e.path}`),!0)},$e=(e,t)=>{const n=t.tables;if(n===void 0||n.length===0)return e.tables;for(const r of n)e.tables.some(s=>s.name===r)||t.logger.warn(`--tables: no table named "${r}" exists in this schema — skipped.`);return e.tables.filter(r=>n.includes(r.name))},Le=async(e,t,n,r)=>{const s=pe(O(e,"utf8"),t,n);for(const a of s.warnings)r.logger.warn(a);return s.text===void 0?(r.logger.info("lunora/schema.ts is already up to date with the database."),!1):r.dryRun===!0?(r.logger.info(`would merge ${String(s.applied)} addition(s) into lunora/schema.ts`),!1):(await I(e,s.text,"utf8"),r.logger.info(`merged ${String(s.applied)} addition(s) into lunora/schema.ts`),!0)},Te=async e=>{const t=e.cwd??process.cwd();if(e.connection===void 0&&(e.url===void 0||e.url===""))return e.logger.error("`lunora introspect` needs a database URL: pass --url, or set DATABASE_URL."),{code:1,written:[]};const n=e.connection===void 0?j(e.url):e.dialect??"postgres",r=e.connection??await J(e.url,n,e.schema,t);let s;try{s=await Ne(r.execute,n,r.schema)}finally{e.connection===void 0&&await r.close()}const a=$e(s,e);if(a.length===0)return e.logger.error("no tables found to introspect — check --schema and --tables."),{code:1,written:[]};const{files:o,warnings:i}=ce({...s,tables:a},{procedures:e.procedures!==!1,serverImport:we(t)}),c=b(t,"lunora"),m=[],u=b(c,"schema.ts"),l=T(u)&&e.force!==!0,d=l?o.filter(p=>p.path!=="schema.ts"):o;l&&await Le(u,{...s,tables:a},n,e)&&m.push("schema.ts");for(const p of d)await Re(p,c,e)&&m.push(p.path);for(const p of i)e.logger.warn(p);return e.logger.info(`introspected ${String(a.length)} table(s) from ${n}. Review the generated files before running \`lunora dev\`.`),{code:0,written:m}},Be=B(async({cwd:e,logger:t,options:n})=>({code:(await Te({cwd:e,dryRun:n.dryRun===!0,force:n.force===!0,logger:t,procedures:n.procedures!==!1,schema:n.schema,tables:n.tables===void 0?void 0:n.tables.split(",").map(s=>s.trim()),url:n.url??process.env.DATABASE_URL})).code}));export{Be as execute,we as resolveServerImport,Te as runIntrospectCommand};
|