@lunora/codegen 1.0.0-alpha.382 → 1.0.0-alpha.383
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/index.d.mts +194 -93
- package/dist/index.d.ts +194 -93
- package/dist/index.mjs +1 -1
- package/dist/packem_shared/{GENERATED_HEADER-DPEvCN8Z.mjs → GENERATED_HEADER-Bzf6ZJ9r.mjs} +1 -1
- package/dist/packem_shared/{MUTATORS_FILENAME-Ipxibja6.mjs → MUTATORS_FILENAME-BGvYo46g.mjs} +1 -1
- package/dist/packem_shared/{NOTIFY_FILENAME-B-t7jQSm.mjs → NOTIFY_FILENAME-BJJObZHG.mjs} +1 -1
- package/dist/packem_shared/{OPENRPC_VERSION-DA0ZNkhl.mjs → OPENRPC_VERSION-CSjT8wJW.mjs} +1 -1
- package/dist/packem_shared/{SCHEMA_SNAPSHOT_FILENAME-CQyAtphV.mjs → SCHEMA_SNAPSHOT_FILENAME-kN0pgKNu.mjs} +9 -9
- package/dist/packem_shared/SCHEMA_SNAPSHOT_VERSION-BdxZuSxk.mjs +2 -0
- package/dist/packem_shared/{SHAPES_FILENAME-mgEi072Z.mjs → SHAPES_FILENAME-KyidzoqS.mjs} +1 -1
- package/dist/packem_shared/SchemaSnapshotParseError-ycDz8gOB.mjs +17 -0
- package/dist/packem_shared/{buildOpenApiDocument-Ct2wK_Tj.mjs → buildOpenApiDocument-afHH7rN5.mjs} +1 -1
- package/dist/packem_shared/{context-property-calls-DKMO9ShK.mjs → context-property-calls-B75cjwpy.mjs} +1 -1
- package/dist/packem_shared/{context-root-BPfMNAJM.mjs → context-root-D4Njep-A.mjs} +1 -1
- package/dist/packem_shared/{database-calls-hLzaOquW.mjs → database-calls-aAjZJdma.mjs} +1 -1
- package/dist/packem_shared/{discoverFunctions-a0IT8OSb.mjs → discoverFunctions-CoQM_L6f.mjs} +1 -1
- package/dist/packem_shared/{discoverHttpRoutes-DHDfKLoa.mjs → discoverHttpRoutes-BQM2CPSF.mjs} +1 -1
- package/dist/packem_shared/discoverHyperdriveCalls-PUg-BESh.mjs +1 -0
- package/dist/packem_shared/{discoverInserts-IAa3lRR4.mjs → discoverInserts-DldQpEfF.mjs} +1 -1
- package/dist/packem_shared/discoverMaskProcedures-_Ey4eJLn.mjs +1 -0
- package/dist/packem_shared/discoverMigrations-E9k4Ykku.mjs +1 -0
- package/dist/packem_shared/{discoverQueries-DZOGiEPs.mjs → discoverQueries-Bq2hqYHP.mjs} +1 -1
- package/dist/packem_shared/discoverR2sqlCalls-CeNnalpk.mjs +1 -0
- package/dist/packem_shared/{discoverRlsProcedures-B0DYk-gW.mjs → discoverRlsProcedures-MboagP9z.mjs} +1 -1
- package/dist/packem_shared/{discoverSchema-DmkjooXZ.mjs → discoverSchema-Cycd1-H0.mjs} +1 -1
- package/dist/packem_shared/{emitAgents-D8TkTpNh.mjs → emitAgents-BeM6PZv4.mjs} +1 -1
- package/dist/packem_shared/{emitApi-D6uqyYd_.mjs → emitApi-GFmStqmq.mjs} +1 -1
- package/dist/packem_shared/{emitApp-D9kGG9Mu.mjs → emitApp-D-6FIpYb.mjs} +10 -6
- package/dist/packem_shared/{emitCrons-C3RiGYk7.mjs → emitCrons-Drdn8Mjn.mjs} +1 -1
- package/dist/packem_shared/{emitDataModel-BMMht_iZ.mjs → emitDataModel-LTnwnhV6.mjs} +1 -1
- package/dist/packem_shared/{emitDrizzleSchema-BmCxM6tO.mjs → emitDrizzleSchema-CM9jh_F0.mjs} +1 -1
- package/dist/packem_shared/{emitFunctions-NGByI1FZ.mjs → emitFunctions-CfSXBV_A.mjs} +1 -1
- package/dist/packem_shared/{emitServer-4NV3vaOg.mjs → emitServer-4l7MPmK0.mjs} +1 -1
- package/dist/packem_shared/emitShard-B4fVJcJA.mjs +1 -0
- package/dist/packem_shared/{index-BjDVAPNW.mjs → index-11LAY5JO.mjs} +1 -1
- package/dist/packem_shared/parse-validator-BisfC8bR.mjs +1 -0
- package/dist/packem_shared/{qualifiers-CPQCkXC4.mjs → qualifiers-D1Q_3wo2.mjs} +1 -1
- package/dist/packem_shared/{server-BY1v1bTx.mjs → server-D69SOfX8.mjs} +1 -1
- package/dist/packem_shared/{shard-DNXF9VZ5.mjs → shard-CB0Ospyw.mjs} +1 -1
- package/dist/packem_shared/{shard-runtime-Bg8MOBzw.mjs → shard-runtime-lkQU8trx.mjs} +1 -1
- package/dist/packem_shared/{shared-BErjtci3.mjs → shared-A1XHcT4t.mjs} +1 -1
- package/package.json +3 -3
- package/dist/packem_shared/SCHEMA_SNAPSHOT_VERSION-SplX7j_9.mjs +0 -2
- package/dist/packem_shared/SchemaSnapshotParseError-CjKSMuex.mjs +0 -18
- package/dist/packem_shared/discoverHyperdriveCalls-i8Zcf64H.mjs +0 -1
- package/dist/packem_shared/discoverMaskProcedures-Bj6fPF4u.mjs +0 -1
- package/dist/packem_shared/discoverMigrations-Bv8kNIgy.mjs +0 -1
- package/dist/packem_shared/discoverR2sqlCalls-Lq6G--TZ.mjs +0 -1
- package/dist/packem_shared/emitShard-9NVueN79.mjs +0 -1
- package/dist/packem_shared/parse-validator-CP5CL6Q7.mjs +0 -1
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
const S=(e,t=2166136261)=>{let i=t;for(let r=0;r<e.length;r+=1)i^=e.charCodeAt(r),i=Math.imul(i,16777619);return(i>>>0).toString(16).padStart(8,"0")},A=e=>`${S(e,2166136261)}${S(e,16777619)}`,Z=1;function C(e){const t={},i=Object.keys(e);i.sort();for(const r of i)t[r]=e[r];return t}const I=e=>`${JSON.stringify(e,void 0,2)}
|
|
2
|
+
`,N=e=>A(I(e)),u=e=>typeof e=="object"&&e!==null,R=e=>u(e)&&u(e.fields)&&u(e.indexes)&&u(e.relations)&&typeof e.shardMode=="string",ee=e=>{if(e===void 0||e.trim()==="")return{status:"absent"};let t;try{t=JSON.parse(e)}catch(r){return{error:`baseline is not valid JSON: ${r instanceof Error?r.message:String(r)}`,status:"invalid"}}if(!u(t)||t.version!==1||!u(t.tables))return{error:`baseline is malformed or written by an incompatible version (expected version ${String(1)})`,status:"invalid"};for(const[r,o]of Object.entries(t.tables))if(!R(o))return{error:`baseline table "${r}" has an invalid structure`,status:"invalid"};return{snapshot:{jurisdiction:typeof t.jurisdiction=="string"?t.jurisdiction:void 0,migrationIds:Array.isArray(t.migrationIds)?t.migrationIds:[],tables:t.tables,version:1},status:"ok"}},V=(e,t)=>e.unique===t.unique&&e.fields.length===t.fields.length&&e.fields.every((i,r)=>i===t.fields[r]),O=e=>e.unique!==void 0,m=({nullable:e,optional:t,refined:i,unique:r,...o})=>JSON.stringify(C(o)),x=e=>({form:JSON.stringify([m(e),e.optional===!0,e.nullable===!0]),refined:e.refined===!0}),F=e=>e.kind==="union"&&e.members?e.members.map(t=>x(t)):[x({...e,nullable:!1,optional:!1})],D=(e,t)=>{if(t.kind!=="union")return!1;const i=F(t);return F(e).every(r=>i.some(o=>o.form===r.form&&(r.refined||!o.refined)))},c=e=>{switch(e.kind){case"array":return`array(${e.of?c(e.of):"?"})`;case"from":return e.output===void 0?"from":`from(${e.output})`;case"id":return`id(${e.ref??"?"})`;case"literal":return`literal(${e.literal??"?"})`;case"object":return`object({ ${Object.keys(e.fields??{}).join(", ")} })`;case"record":return`record(${e.key?c(e.key):"?"}, ${e.of?c(e.of):"?"})`;case"union":return(e.members??[]).map(t=>c(t)).join(" | ");default:return e.kind}},h=(e,t,i)=>({remediation:"backfill",scope:"table",severity:"breaking",summary:i,table:e,type:t}),p=(e,t,i)=>({remediation:"none",scope:"table",severity:"safe",summary:i,table:e,type:t}),M=(e,t)=>{const i=JSON.stringify(e),r=JSON.stringify(t);return i===r?0:i<r?-1:1},f=e=>({...e,...e.kind==="from"?{output:void 0}:{},...e.fields?{fields:Object.fromEntries(Object.entries(e.fields).map(([t,i])=>[t,f(i)]))}:{},...e.key?{key:f(e.key)}:{},...e.of?{of:f(e.of)}:{},...e.members?{members:e.members.map(t=>f(t)).toSorted(M)}:{}}),j=e=>e.kind==="union"?e.members??[]:[e],L=(e,t)=>{const i=[...e],r=[...t],o=new Set,n=new Set,s=(d,a)=>{for(const[$,k]of i.entries()){if(n.has($))continue;const y=r.findIndex((_,E)=>!o.has(E)&&d(k,_));y!==-1&&(o.add(y),n.add($),a&&([i[$],r[y]]=g(k,r[y])))}};return s((d,a)=>JSON.stringify(d)===JSON.stringify(a),!1),s((d,a)=>m(f(d))===m(f(a)),!0),[i,r]},g=(e,t)=>{if(e.kind==="union"||t.kind==="union"){const[o,n]=L(j(e),j(t)),s=(d,a)=>d.kind==="union"?{...d,members:a.toSorted(M)}:a[0];return[s(e,o),s(t,n)]}if(e.kind!==t.kind)return[e,t];if(e.kind==="from")return e.output===void 0||t.output===void 0?[{...e,output:void 0},{...t,output:void 0}]:[e,t];const i={...e.fields?{fields:{...e.fields}}:{}},r={...t.fields?{fields:{...t.fields}}:{}};for(const o of["key","of"])e[o]&&t[o]&&([i[o],r[o]]=g(e[o],t[o]));for(const o of Object.keys(e.fields??{})){const n=e.fields?.[o],s=t.fields?.[o];n&&s&&i.fields&&r.fields&&([i.fields[o],r.fields[o]]=g(n,s))}return[{...e,...i},{...t,...r}]},H=(e,t,i,r,o)=>{const[n,s]=g(i,r);if(n.kind===s.kind&&(!o||m(n)===m(s)))return;if(o&&D(n,s))return p(e,"widenedFieldShape",`field ${e}.${t} widened: ${c(n)} → ${c(s)} — every stored value stays valid`);if(n.kind!==s.kind)return h(e,"changedFieldKind",`field ${e}.${t} changed type: ${n.kind} → ${s.kind} — add a data migration to convert existing values`);const d=Object.values(s.fields??{});return o&&n.kind==="object"&&Object.keys(n.fields??{}).length===0&&d.length>0&&d.every(a=>a.optional)?p(e,"widenedFieldShape",`field ${e}.${t} now records its optional object shape — stored values stay valid`):h(e,"changedFieldShape",`field ${e}.${t} changed shape: ${c(n)} → ${c(s)} — stored values were written against the old shape; add a data migration to convert them`)},J=(e,t,i,r)=>{const o=[];return i.unique!==r.unique&&o.push(r.unique===!0?{...h(e,"addedFieldConstraint",`field ${e}.${t} became unique — existing duplicates would violate it; add a data migration to de-duplicate first`),field:t,uniqueOn:[t]}:p(e,"relaxedFieldConstraint",`field ${e}.${t} is no longer unique`)),i.nullable!==r.nullable&&o.push(r.nullable===!0?p(e,"relaxedFieldConstraint",`field ${e}.${t} became nullable`):h(e,"addedFieldConstraint",`field ${e}.${t} is no longer nullable — rows holding NULL would be invalid; add a data migration to backfill them`)),i.refined!==r.refined&&o.push(r.refined===!0?h(e,"addedFieldConstraint",`field ${e}.${t} gained a validation refinement — stored values were never checked against it; add a data migration if any could fail`):p(e,"relaxedFieldConstraint",`field ${e}.${t} dropped its validation refinement`)),o},P=(e,t,i,r)=>{const o=[],n=O(i)&&O(r),s=H(e,t,i,r,n);return s&&o.push(s),n&&o.push(...J(e,t,i,r)),i.optional&&!r.optional?o.push({remediation:"backfill",severity:"breaking",summary:`field ${e}.${t} became required — rows missing it would be invalid; add a data migration to backfill it`,table:e,scope:"table",type:"fieldOptionalToRequired"}):!i.optional&&r.optional&&o.push({remediation:"none",scope:"table",severity:"safe",summary:`field ${e}.${t} became optional`,table:e,type:"fieldRequiredToOptional"}),o},B=(e,t,i)=>i.optional?{remediation:"none",scope:"table",severity:"safe",summary:`added optional field ${e}.${t}`,table:e,type:"addedOptionalField"}:{remediation:"backfill",severity:"breaking",summary:`added required field ${e}.${t} — existing rows have no value; add a data migration to backfill it`,table:e,scope:"table",type:"addedRequiredField"},G=(e,t,i,r)=>{for(const[o,n]of Object.entries(i.fields)){const s=t.fields[o];s===void 0?r.push({...B(e,o,n),field:o}):r.push(...P(e,o,s,n).map(d=>({...d,field:o})))}for(const o of Object.keys(t.fields))i.fields[o]===void 0&&r.push({field:o,remediation:"backfill",severity:"breaking",summary:`removed field ${e}.${o} — add a data migration if stored data must be cleaned up`,table:e,scope:"table",type:"removedField"})},U=(e,t,i,r)=>{for(const[o,n]of Object.entries(i.indexes)){const s=t.indexes[o];if(s===void 0){r.push(n.unique?{remediation:"backfill",scope:"table",severity:"breaking",summary:`added unique index ${o} on ${e} — existing duplicates would violate it; add a data migration to de-duplicate first`,table:e,type:"addedIndex",uniqueOn:n.fields}:{remediation:"none",scope:"table",severity:"safe",summary:`added index ${o} on ${e}`,table:e,type:"addedIndex"});continue}V(s,n)||r.push(n.unique?{remediation:"backfill",scope:"table",severity:"breaking",summary:`index ${o} on ${e} changed shape and is unique — existing duplicates would violate it; add a data migration to de-duplicate first`,table:e,type:"changedIndex",uniqueOn:n.fields}:{remediation:"none",scope:"table",severity:"safe",summary:`index ${o} on ${e} changed shape — a query that relied on the old index may need updating`,table:e,type:"changedIndex"})}for(const o of Object.keys(t.indexes))i.indexes[o]===void 0&&r.push({remediation:"none",severity:"safe",index:o,summary:`removed index ${o} on ${e} — a query that used \`.withIndex("${o}")\` no longer compiles`,table:e,scope:"table",type:"removedIndex"})},W=(e,t,i,r)=>{for(const o of Object.keys(i.relations))t.relations[o]===void 0&&r.push({remediation:"none",scope:"schema",severity:"safe",summary:`added relation ${e}.${o}`,table:e,type:"addedRelation"});for(const o of Object.keys(t.relations))i.relations[o]===void 0&&r.push({remediation:"none",scope:"schema",severity:"safe",summary:`removed relation ${e}.${o} — the stored foreign-key values stay in place, but its \`onDelete\` action no longer runs and a \`with: { ${o} }\` read no longer compiles`,table:e,type:"removedRelation",warning:!0})},b="shardBy:_unknown_",v="global",K=(e,t)=>e===v&&t.startsWith(`${v}:`)||t===v&&e.startsWith(`${v}:`),z=(e,t,i)=>{if(t===i)return i!==b?void 0:{remediation:"rehome",scope:"table",severity:"breaking",summary:`table ${e} declares a non-literal .shardBy(...) key, so codegen cannot read which column partitions it — every such key records as "${b}" and two DIFFERENT keys would compare equal. Pass the shard key as a string literal; until then this is reported on every run, because the alternative is a silent pass on a re-home that strands every row (export/import is the only way back).`,table:e,type:"changedShardMode"};if(!K(t,i))return{remediation:"rehome",severity:"breaking",summary:`table ${e} changed shard mode: ${t} → ${i} — its physical storage moves, and existing rows do NOT follow the schema; re-home them with an export/import round trip (https://lunora.sh/docs/concepts/sharding#migrating-a-populated-table)`,table:e,scope:"table",type:"changedShardMode",...i===b?{}:{coverage:{shardMode:i,table:e}}}},T=e=>e.memory!==void 0,q=e=>e.after??0,w=e=>e.after===void 0?`{ field: "${e.field}" }`:`{ after: ${String(e.after)}, field: "${e.field}" }`,l=e=>e.after===void 0?`.ttl("${e.field}")`:`.ttl("${e.field}", { after: ${String(e.after)} })`,Q=(e,t,i)=>{if(t===void 0&&i===void 0)return;const r=(d,a)=>({coverage:{table:e,ttl:{...a.after===void 0?{}:{after:a.after},field:a.field}},expiry:{...a.after===void 0?{}:{after:a.after},field:a.field,...t===void 0?{}:{previous:{...t.after===void 0?{}:{after:t.after},field:t.field}}},remediation:"backfill",scope:"table",severity:"breaking",summary:d,table:e,type:"changedTtlPolicy"}),o=d=>({remediation:"none",scope:"table",severity:"safe",summary:d,table:e,type:"changedTtlPolicy",warning:!0});if(i===void 0)return o(`table ${e} dropped its TTL policy — its rows are no longer swept, so they stay until something else deletes them`);if(t===void 0)return r(`table ${e} gained a TTL policy ${l(i)} — every row already past the cutoff is deleted on the next alarm sweep; refresh or clear "${i.field}" on the rows that must survive, then declare a migration with covers: { table: "${e}", ttl: ${w(i)} }`,i);if(t.field!==i.field)return r(`table ${e} moved its TTL to a different column: ${l(t)} → ${l(i)} — rows are now expired by a column they were never written against; populate "${i.field}" on the rows that must survive, then declare a migration with covers: { table: "${e}", ttl: ${w(i)} }`,i);const n=q(t),s=q(i);return s<n?r(`table ${e} shortened its TTL: ${l(t)} → ${l(i)} — rows that were not expired under the old offset are deleted on the next alarm sweep; refresh "${i.field}" on the rows that must survive, then declare a migration with covers: { table: "${e}", ttl: ${w(i)} }`,i):s>n?o(`table ${e} lengthened its TTL: ${l(t)} → ${l(i)} — every row stays, and expires later than it would have`):void 0},Y=(e,t,i)=>{const r=[];return t.memory!==i.memory&&r.push(i.memory===!0?{remediation:"rehome",scope:"table",severity:"breaking",summary:`table ${e} became a .memory() table — every row is deleted in every shard on the next Durable Object cold start, and no data migration survives that; export the rows first if they must be kept, or revert`,table:e,type:"changedMemoryMode",coverage:{memory:!0,table:e}}:{remediation:"none",scope:"table",severity:"safe",summary:`table ${e} is no longer a .memory() table — its rows now survive a cold start`,table:e,type:"changedMemoryMode"}),t.commitOrdered!==i.commitOrdered&&r.push(i.commitOrdered===!0?{remediation:"backfill",scope:"table",severity:"breaking",summary:`table ${e} became .commitOrdered() — rows written before it carry no _commitSeq, so a \`_commitSeq > cursor\` changefeed never offers them; add a data migration over the table to stamp them (the rewrite allocates a sequence)`,table:e,type:"changedCommitOrdering",identityRewrites:!0}:{remediation:"none",scope:"table",severity:"safe",summary:`table ${e} is no longer .commitOrdered() — stored rows are untouched, but new rows carry no _commitSeq, so a \`_commitSeq > cursor\` changefeed stops advancing without erroring; update the consumers`,table:e,type:"changedCommitOrdering",warning:!0}),r},X=(e,t,i,r)=>{const o=z(e,t.shardMode,i.shardMode);if(o&&r.push(o),T(t)&&T(i)){r.push(...Y(e,t,i));const n=Q(e,t.ttl,i.ttl);n&&r.push(n)}G(e,t,i,r),U(e,t,i,r),W(e,t,i,r)},te=(e,t)=>{const i=[],r=e?.tables??{};for(const[o,n]of Object.entries(t.tables)){const s=r[o];if(s===void 0){i.push({remediation:"none",scope:"table",severity:"safe",summary:`added table ${o}`,table:o,type:"addedTable"});continue}X(o,s,n,i)}for(const o of Object.keys(r))t.tables[o]===void 0&&i.push({remediation:"none",scope:"table",severity:"safe",summary:`removed table ${o} — its rows are left in place in each shard's SQLite (nothing deletes them) but are unreachable through the schema; export the shard first if the data must be kept, or declare the table again to reach it`,table:o,type:"removedTable",warning:!0});if(e!==void 0&&e.jurisdiction!==t.jurisdiction){const o=e.jurisdiction??"(none)",n=t.jurisdiction??"(none)";i.push({remediation:"rehome",scope:"schema",severity:"breaking",summary:`Durable Object jurisdiction changed from ${o} to ${n} — this re-homes every DO and strands all existing shard, scheduler, and session-DO data in the old region (export then import to move it). Revert the change, or declare a migration with covers: { jurisdiction: "${t.jurisdiction??"none"}" } once the data is moved.`,type:"changedJurisdiction",coverage:{jurisdiction:t.jurisdiction??"none"}})}return{changes:i}};export{Z as SCHEMA_SNAPSHOT_VERSION,c as describeShape,P as diffExistingField,te as diffSchemaSnapshots,N as hashSchemaSnapshot,R as isValidTableSnapshot,ee as parseSnapshotJson,I as serializeSchemaSnapshot,C as sortKeys};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{existsSync as m}from"node:fs";import{join as u}from"node:path";import{SyntaxKind as p,Node as o}from"ts-morph";import{diagnosticAt as g}from"./CodegenDiagnosticError-BUXlG3P-.mjs";import{a as f}from"./module-specifiers-BctA0m_p.mjs";import{p as d}from"./parse-validator-
|
|
1
|
+
import{existsSync as m}from"node:fs";import{join as u}from"node:path";import{SyntaxKind as p,Node as o}from"ts-morph";import{diagnosticAt as g}from"./CodegenDiagnosticError-BUXlG3P-.mjs";import{a as f}from"./module-specifiers-BctA0m_p.mjs";import{p as d}from"./parse-validator-BisfC8bR.mjs";import{findObjectProperty as l}from"./isTestPath-JdN4KXhV.mjs";import{a as S}from"./attribution-DUbGYT4N.mjs";const h="shapes.ts",x=r=>{const t=r.getSymbol();if(!t)return r.getText()==="defineShape";for(const e of t.getDeclarations())if(o.isImportSpecifier(e))return f(e.getImportDeclaration().getModuleSpecifierValue())?e.getNameNode().getText()==="defineShape":!1;return!1},b=r=>{const t=r.getSymbol();if(!t)return!1;for(const e of t.getDeclarations()){if(!o.isNamespaceImport(e))continue;const i=e.getFirstAncestorByKind(p.ImportDeclaration);return i!==void 0&&f(i.getModuleSpecifierValue())}return!1},y=r=>{if(o.isIdentifier(r))return x(r);if(o.isPropertyAccessExpression(r)){const t=r.getExpression();return r.getName()==="defineShape"&&o.isIdentifier(t)&&b(t)}return!1},N=r=>{const[t]=r.getArguments();if(!t||!o.isObjectLiteralExpression(t))return;const e=l(t,"table");if(!e||!o.isPropertyAssignment(e))return;const i=e.getInitializer();return i&&o.isStringLiteral(i)?i.getLiteralValue():void 0},E=r=>{const[t]=r.getArguments();if(!t||!o.isObjectLiteralExpression(t))return{};const e=l(t,"args");if(!e||!o.isPropertyAssignment(e))return{};const i=e.getInitializer();return!i||!o.isObjectLiteralExpression(i)?{}:d(i)},I=r=>{const t=[];for(const e of r.getVariableDeclarations()){const i=e.getInitializer();if(i?.getKind()!==p.CallExpression)continue;const s=i,a=s.getExpression();if(!y(a))continue;const n=e.getNameNode();if(!o.isIdentifier(n)){if(e.getVariableStatement()?.hasExportKeyword()!==!0)continue;throw g(n,"defineShape exports must be plain named exports (no destructuring)")}const c=S(e,"binding");c!==void 0&&t.push({args:E(s),exportName:c,filePath:"shapes",table:N(s)})}return t},z=(r,t)=>{const e=u(t,h);if(!m(e))return[];const i=r.getSourceFile(e)??r.addSourceFileAtPath(e),s=I(i);return s.sort((a,n)=>a.exportName.localeCompare(n.exportName)),s};export{h as SHAPES_FILENAME,z as discoverShapes};
|
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
import{LunoraError as j}from"@lunora/errors";import{SCHEMA_SNAPSHOT_VERSION as I,sortKeys as v,diffSchemaSnapshots as O,parseSnapshotJson as T}from"./SCHEMA_SNAPSHOT_VERSION-BdxZuSxk.mjs";import{isHyperdriveGlobalTable as R}from"./isD1GlobalTable-udvHAAzD.mjs";const N=e=>{const t=e.shardMode;return t==="global"?`global:${R(e)?"hyperdrive":"d1"}`:t==="root"?t:`shardBy:${t.field}`},A=(e,t)=>{const n=JSON.stringify(e),i=JSON.stringify(t);return n===i?0:n<i?-1:1},g=e=>{const t=e.kind==="optional",n=t?e.inner:void 0,i=n??e,s={kind:t?n?.kind??"unknown":e.kind,nullable:i.column?.notNull===!1||e.column?.notNull===!1,optional:t,unique:i.column?.unique===!0||e.column?.unique===!0,...L[i.kind]?.(i)};return(i.hasRefinement===!0||e.hasRefinement===!0)&&(s.refined=!0),s},_=e=>{const t={};for(const[n,i]of Object.entries(e))t[n]=g(i);return v(t)},E=/import\(\s*["'`](?:[A-Za-z]:)?[\\/]/u,L={array:e=>e.inner?{of:g(e.inner)}:{},from:e=>e.tsType===void 0||E.test(e.tsType)?{}:{output:e.tsType},id:e=>e.tableName===void 0?{}:{ref:e.tableName},literal:e=>e.literalValue===void 0?{}:{literal:e.literalValue},object:e=>e.shape?{fields:_(e.shape)}:{},record:e=>({...e.keyType?{key:g(e.keyType)}:{},...e.valueType?{of:g(e.valueType)}:{}}),union:e=>e.members?{members:e.members.map(t=>g(t)).toSorted(A)}:{}},C=e=>{const t={};for(const[r,d]of Object.entries(e.shape))t[r]=g(d);const n={};for(const r of e.indexes)n[r.name]={fields:[...r.fields],unique:r.unique??!1};const i={};for(const r of e.relations)i[r.name]=r.through===void 0?{field:r.field,kind:r.kind,table:r.table}:{kind:r.kind,table:r.table,through:{...r.through}};const s={commitOrdered:e.commitOrdered===!0,fields:v(t),indexes:v(n),memory:e.memory===!0,relations:v(i),shardMode:N(e)};return e.ttl&&(s.ttl=e.ttl.after===void 0?{field:e.ttl.field}:{after:e.ttl.after,field:e.ttl.field}),s},W=(e,t)=>{const n={};for(const s of e.tables)n[s.name]=C(s);const i=[...t].sort();return{jurisdiction:e.jurisdiction,migrationIds:i,tables:v(n),version:I}};class D extends j{constructor(t){super("SCHEMA_SNAPSHOT_PARSE",t,{name:"SchemaSnapshotParseError"})}}const Z=e=>{const t=T(e);if(t.status==="invalid")throw new D(t.error);return t.status==="ok"?t.snapshot:void 0},G=e=>e.flatMap(t=>t.index===void 0?[]:[{file:t.file,function:t.scope.kind==="module"?"<module>":t.scope.name,index:t.index.name,line:t.line,table:t.table}]),F=" • For a change you know is safe: pass `--allow-schema-drift` to skip the block for this run. It checks nothing and leaves the baseline unchanged, so the next run drifts again.",q=()=>`${F}
|
|
2
|
+
`,k=e=>e.map(t=>` - ${t.summary}`).join(`
|
|
3
|
+
`),x=e=>e.remediation==="backfill"&&e.table!==void 0,H=(e,t)=>e===t||e==="global"&&t.startsWith("global:"),M=(e,t)=>{const n=t.coverage,i=e.covers;return n===void 0||i===void 0||n.table!==void 0&&(i.table!==n.table||e.table!==n.table||e.identity===!0)?!1:(n.ttl===void 0||i.ttl?.field===n.ttl.field&&(i.ttl.after??0)===(n.ttl.after??0))&&(n.jurisdiction===void 0||i.jurisdiction===n.jurisdiction)&&(n.memory!==!0||i.memory===!0)&&(n.shardMode===void 0||H(i.shardMode,n.shardMode))},P=(e,t)=>{if(e.type!=="removedIndex"||e.index===void 0)return e;const n=t.filter(s=>(s.table===e.table||s.table==="")&&(s.index===e.index||s.index===void 0));if(n.length===0)return e;const i=n.slice(0,5).map(s=>`${s.function} (${s.file}:${String(s.line)}${s.index===void 0?", index name is not a literal":""})`).join(", ");return{...e,remediation:"code",severity:"breaking",summary:`removed index ${e.index??""} on ${e.table??""} is still used by ${i}${n.length>5?` and ${String(n.length-5)} more`:""} — point the query at another index, or restore the index`}},J=/^[A-Za-z_]\w*$/u,U=e=>` lunora migrate create backfill_${e} --table ${e}`,z=(e,t,n)=>{const{identity:i,unresolved:s}=t,r=[...new Set(e.filter(a=>x(a)&&a.coverage===void 0).flatMap(a=>a.table??[]))],d=[];if(r.length>0){d.push(" • Add a `defineMigration({ id, table, up })` in lunora/ for each affected table, then re-run this command — the baseline is re-blessed on a successful deploy, not by `lunora migrate` itself.\n");const a=r.filter(l=>J.test(l));a.length>0&&d.push(`
|
|
4
|
+
Scaffold the missing migration(s) — the generated \`up\` is an identity placeholder you must fill in:
|
|
5
|
+
${a.map(l=>U(l)).join(`
|
|
6
|
+
`)}
|
|
7
|
+
|
|
8
|
+
`)}s.length>0&&d.push(` • Migration(s) ${s.join(", ")} declare a non-literal \`table\`, so codegen cannot tell which table they visit and they cover nothing. Use a string literal.
|
|
9
|
+
`),i.length>0&&e.some(a=>a.identityRewrites!==!0)&&d.push(` • Migration(s) ${i.join(", ")} return each document unchanged, so they rewrite no row and cover nothing. Fill in \`up\`.
|
|
10
|
+
`),r.length>0&&d.push(" • If the stored rows already fit the new schema, `lunora deploy` goes ahead on its own: it reads the rows of each affected table from the deployed worker (`--migrate-url` or the project link, plus `LUNORA_ADMIN_TOKEN`) and names any row that does not fit.\n");for(const a of e){const{coverage:l}=a;if(l===void 0)continue;const u=l.table??e.find(h=>h.table!==void 0)?.table??"users",f=`{ ${Object.entries(l).toSorted(([h],[p])=>h.localeCompare(p)).map(([h,p])=>`${h}: ${typeof p=="object"?`{ ${Object.entries(p).map(([y,$])=>`${y}: ${JSON.stringify($)}`).join(", ")} }`:JSON.stringify(p)}`).join(", ")} }`,m=l.table===void 0?"":` and iterates \`${l.table}\` with an \`up\` that rewrites rows`,S=a.summary.split(" — ")[0]??"",w=l.ttl===void 0?`Move the rows first (\`lunora export --tables ${u} --out ${u}.ndjson\`, deploy, \`lunora import ${u}.ndjson\`), then declare: `:`Decide which rows must survive and refresh \`${l.ttl.field}\` on them in \`up\`, then declare: `;d.push(` • "${S}" moves, empties or deletes data, so it stays blocked until a new migration declares \`covers: ${f}\`${m}. ${w}\`defineMigration({ id: "rehome_${u}", table: "${l.table??u}", covers: ${f}, up: (doc) => ({ ...doc, tenantId: doc.tenantId ?? "default" }) })\`.
|
|
11
|
+
`)}return d.push(q()),[`${n??"deploy"} blocked: ${String(e.length)} unresolved breaking schema change(s) since the last blessed schema baseline:`,k(e),"",`To fix:
|
|
12
|
+
${d.join("")}Docs: https://lunora.dev/docs/migrations`].join(`
|
|
13
|
+
`)},Q=e=>{const{allowDrift:t=!1,baseline:n,command:i,current:s,indexReferences:r=[],migrations:d}=e,a={changes:O(n,s).changes.map(o=>P(o,r))},l=a.changes.filter(o=>o.severity==="breaking"),u=s.migrationIds.filter(o=>!(n?.migrationIds??[]).includes(o)),f=d.filter(o=>u.includes(o.id)),m=(o,c,b=[])=>({blocked:o,changes:a.changes,newMigrationIds:u,reason:c,uncovered:b}),S=new Set(f.filter(o=>o.table!==""&&o.identity!==!0).map(o=>o.table)),w=f.filter(o=>o.table==="").map(o=>o.id),h=f.filter(o=>o.table!==""&&o.identity===!0).map(o=>o.id);if(a.changes.length===0||n===void 0)return m(!1,"");if(l.length===0)return m(!1,`schema drift detected (all additive/safe):
|
|
14
|
+
${k(a.changes)}`);const p=o=>o.coverage!==void 0?f.some(c=>M(c,o)):o.identityRewrites===!0&&o.table!==void 0?f.some(c=>c.table===o.table):x(o)&&S.has(o.table),y=l.filter(o=>!p(o));if(y.length===0){const o=f.filter(c=>l.some(b=>b.coverage===void 0?x(b)&&(c.identity!==!0||b.identityRewrites===!0)&&b.table===c.table:M(c,b))).map(c=>c.id);return m(!1,`breaking schema drift detected, covered by ${String(o.length)} new migration(s) (${o.join(", ")}):
|
|
15
|
+
${k(l)}`)}const $=z(y,{identity:h,unresolved:w},i);return t?m(!1,`${$}
|
|
16
|
+
|
|
17
|
+
(overridden by --allow-schema-drift)`,y):m(!0,$,y)};export{D as SchemaSnapshotParseError,W as buildSchemaSnapshot,Q as evaluateSchemaDrift,G as indexReferencesOf,Z as parseSchemaSnapshot};
|
package/dist/packem_shared/{buildOpenApiDocument-Ct2wK_Tj.mjs → buildOpenApiDocument-afHH7rN5.mjs}
RENAMED
|
@@ -1,3 +1,3 @@
|
|
|
1
|
-
import{m as b}from"./modules-DEBCI7Gm.mjs";import{r as E}from"./json-data-Chfs2Cz5.mjs";import{LUNORA_ERROR_CODES as P,objectSchema as g,validatorIrToJsonSchema as l}from"./LUNORA_ERROR_CODES-CjACC-MQ.mjs";import{G as A}from"./shared-
|
|
1
|
+
import{m as b}from"./modules-DEBCI7Gm.mjs";import{r as E}from"./json-data-Chfs2Cz5.mjs";import{LUNORA_ERROR_CODES as P,objectSchema as g,validatorIrToJsonSchema as l}from"./LUNORA_ERROR_CODES-CjACC-MQ.mjs";import{G as A}from"./shared-A1XHcT4t.mjs";import{s as m}from"./dispatch-namespace-DwTjD7BU.mjs";const T="/_lunora/rest",x=["authorization","cf-access-jwt-assertion","cookie","payment-signature","x-payment"],v=["x-d1-bookmark","x-lunora-shard-key"],j=e=>[...x,...(e.credentialHeaders??[]).map(t=>t.toLowerCase())],O=e=>Number.isFinite(e)?Math.max(0,Math.floor(e)):0,$=(...e)=>{const t=[];for(const r of e)for(const n of r?.split(",")??[]){const s=n.trim().toLowerCase();s!==""&&!t.includes(s)&&t.push(s)}return t.length===0?void 0:t.join(", ")},k=(e,t)=>{const r=[t,`max-age=${String(O(e.maxAge))}`];return e.staleWhileRevalidate!==void 0&&r.push(`stale-while-revalidate=${String(O(e.staleWhileRevalidate))}`),r.join(", ")},N=e=>e.scope==="public"?$(e.vary,...j(e),...v):$(e.vary,...v),q=e=>{const t=e.indexOf(":");if(!(t<=0||t>=e.length-1||e.indexOf(":",t+1)!==-1))return{name:e.slice(t+1),namespace:e.slice(0,t)}},_=e=>{const t=q(e);if(t!==void 0)return`${T}/${t.namespace}/${t.name}`},C=e=>e==="query"?"GET":"POST",y="#/components/responses/LunoraError",R=/:([A-Za-z_$][\w$]*)/gu,w=e=>[...e.matchAll(R)].map(t=>t[1]),D=e=>e.replaceAll(R,"{$1}"),f=e=>e.kind==="optional"?e.inner??e:e,I=e=>{const t=new Set(w(e.path)),r=[];for(const[n,s]of Object.entries(e.searchParams)){const c=f(s);r.push({description:`Query parameter \`${n}\``,in:"query",name:n,required:s.kind!=="optional",schema:l(c)})}for(const[n,s]of Object.entries(e.params)){const c=f(s);r.push({description:`Path parameter \`${n}\``,in:t.has(n)?"path":"query",name:n,required:t.has(n)?!0:s.kind!=="optional",schema:l(c)})}return r},S=e=>e?{content:{"application/json":{schema:l(e)}},description:"Successful response."}:{content:{"application/json":{schema:{description:"Return shape is TS-inferred (no `.output()` declared); best-effort — any JSON."}}},description:"Successful response. The return shape is TypeScript-inferred and not declared via `.output()`, so it is documented best-effort."},L=(e,t)=>{const r=I(e),n={description:`${e.stream?"Streaming (SSE) ":""}HTTP route handler \`${e.exportName}\` (${e.method} ${e.path}).`,operationId:`${e.method.toLowerCase()}_${m(e.path)}`,responses:{200:S(e.output),204:{description:"No content (handler returned `undefined`)."},default:{$ref:y}},summary:`${e.method} ${e.path}`,tags:[t]};return r.length>0&&(n.parameters=r),Object.keys(e.body).length>0&&(n.requestBody={content:{"application/json":{schema:g(e.body)}},required:!0}),e.stream&&(n["x-lunora-stream"]="text/event-stream"),n},F=(e,t)=>{const r=`${m(e.filePath)}:${e.exportName}`,n={additionalProperties:!1,properties:{args:g(e.args),functionPath:{const:r,type:"string"},shardKey:{description:"Optional shard key; omitted routes to the default shard.",type:"string"}},required:["functionPath"],type:"object"};return{operation:{description:`Invoke the \`${e.kind}\` \`${r}\` over the Lunora RPC envelope (POST /_lunora/rpc).`,operationId:r,requestBody:{content:{"application/json":{schema:n}},required:!0},responses:{200:S(e.output),default:{$ref:y}},summary:`${e.kind}: ${r}`,tags:[t],"x-lunora-function-kind":e.kind},pathKey:`/_lunora/rpc#${r}`}},H=(e,t)=>{if(e===void 0||t!=="get"||e.scope===void 0||e.maxAge===void 0)return{};const r={maxAge:e.maxAge,scope:e.scope,...e.staleWhileRevalidate===void 0?{}:{staleWhileRevalidate:e.staleWhileRevalidate},...e.tag===void 0?{}:{tag:e.tag},...e.vary===void 0?{}:{vary:e.vary}},n={"Cache-Control":{description:r.scope==="public"?"Caching policy. `public` applies only to an uncredentialed request — a request carrying `Authorization` or `Cookie` is always answered `private`.":"Caching policy. Restricted to the caller's own cache; never stored by a shared/edge cache.",schema:{example:k(r,r.scope),type:"string"}}};r.tag!==void 0&&(n["Cache-Tag"]={description:"Purge tag for `ctx.cache.purge({ tags: [...] })`.",schema:{example:r.tag,type:"string"}});const s=N(r);return s!==void 0&&(n.Vary={description:"Request headers this response varies by. The endpoint's own negotiated headers are merged in at runtime.",schema:{example:s,type:"string"}}),{headers:n}},M=(e,t)=>{const r=`${m(e.filePath)}:${e.exportName}`,n=_(r);if(n===void 0)return;const s=C(e.kind),c=s==="GET",i={description:`Public REST endpoint for the \`${e.kind}\` \`${r}\` (opt-in via \`.expose({ rest: true })\`). Routed through the procedure, so auth / RLS / validators are enforced.`,operationId:`rest_${m(n)}`,responses:{200:{content:{"application/json":{schema:{description:"Procedure result. The shape is TS-inferred from the return type; best-effort — any JSON."}}},description:"Successful result (TypeScript-inferred return shape, documented best-effort).",...H(e.expose?.cache,c?"get":"post")},default:{$ref:y}},summary:`${s} ${n}`,tags:[t],"x-lunora-function-kind":e.kind};if(c){const d=Object.entries(e.args).map(([u,h])=>{const o=f(h);return{description:`Argument \`${u}\` (JSON-encoded for non-string values).`,in:"query",name:u,required:h.kind!=="optional",schema:l(o)}});return d.length>0&&(i.parameters=d),{method:"get",operation:i,path:n}}return i.requestBody={content:{"application/json":{schema:g(e.args)}},required:Object.keys(e.args).length>0},{method:"post",operation:i,path:n}},J=e=>{const t=e.version??"0.0.0",r=Object.create(null),n=o=>r[o]??Object.create(null),s=new Set,c=e.modules??[],i=o=>b(c,o);for(const o of e.httpRoutes){const a=D(o.path),p=n(a);p[o.method.toLowerCase()]=L(o,i(o.filePath)),r[a]=p,s.add(i(o.filePath))}const d=e.functions.filter(o=>o.visibility!=="internal"&&o.kind!=="stream");for(const o of d){const{operation:a,pathKey:p}=F(o,i(o.filePath));r[p]={post:a},s.add(i(o.filePath))}for(const o of d){if(o.expose?.rest!==!0)continue;const a=M(o,i(o.filePath));if(a===void 0)continue;const p=n(a.path);p[a.method]=a.operation,r[a.path]=p}const u=[...s].toSorted((o,a)=>o.localeCompare(a)).map(o=>({description:c.find(p=>p.name===o)?.description??`Operations declared in \`lunora/${o}\`.`,name:o}));return{components:{responses:{LunoraError:{content:{"application/json":{schema:{additionalProperties:!1,description:"Standard Lunora error envelope.",properties:{error:{additionalProperties:!1,properties:{code:{description:"Machine-readable error code. Clients switch on this value.",enum:P,type:"string"},message:{description:"Human-readable error message (never echoes internal details).",type:"string"}},required:["code","message"],type:"object"}},required:["error"],type:"object"}}},description:"A Lunora error response. The HTTP status reflects the error code (e.g. BAD_REQUEST→400, UNAUTHORIZED→401, FORBIDDEN→403, NOT_FOUND→404)."}}},info:{description:"Auto-generated from @lunora/values-typed functions by @lunora/codegen. Do not edit — run `lunora codegen` to regenerate.",title:"Lunora API",version:t},openapi:"3.1.0",paths:Object.fromEntries(Object.entries(r).map(([o,a])=>[o,{...a}])),tags:u}},z=e=>`${JSON.stringify(J(e),void 0,2)}
|
|
2
2
|
`,K=e=>`${A}export const openApiSpec = ${E(e,"Record<string, unknown>")};
|
|
3
3
|
`;export{J as buildOpenApiDocument,z as emitOpenApi,K as emitOpenApiModule};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{Node as i}from"ts-morph";import{listLunoraSourceFiles as a,lunoraRelativePath as c,handlerOf as l}from"./isTestPath-JdN4KXhV.mjs";import{b as d,d as f}from"./attribution-DUbGYT4N.mjs";import{c as u}from"./context-root-
|
|
1
|
+
import{Node as i}from"ts-morph";import{listLunoraSourceFiles as a,lunoraRelativePath as c,handlerOf as l}from"./isTestPath-JdN4KXhV.mjs";import{b as d,d as f}from"./attribution-DUbGYT4N.mjs";import{c as u}from"./context-root-D4Njep-A.mjs";import{c as m}from"./classify-procedure-call-DtqiTjPg.mjs";const p=t=>{const r=t.getInitializer();if(!r||!i.isCallExpression(r))return;const e=m(r);if(!e||e.kind!=="query"&&e.kind!=="mutation")return;const o=l(r,e.receiver);return o?{exportName:f(t)??t.getName(),handler:o,kind:e.kind}:void 0},x=(t,r)=>{const e=t.getParent();return e&&i.isPropertyAccessExpression(e)&&e.getExpression()===t?`ctx.${r}.${e.getName()}`:`ctx.${r}`},h=(t,r,e)=>{const o=[];for(const n of u(t.handler,e))o.push({callee:x(n,e),exportName:t.exportName,file:r,kind:t.kind,line:n.getStartLineNumber()});return o},N=(t,r,e)=>{const o=[];for(const n of d(t)){const s=p(n);s&&o.push(...h(s,r,e))}return o},F=(t,r,e)=>{const o=[];for(const n of a(r)){const s=t.getSourceFile(n)??t.addSourceFileAtPath(n);o.push(...N(s,c(r,n),e))}return o};export{F as d};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{Node as r,SyntaxKind as d}from"ts-morph";import{unwrapExpression as l,memberAccessOf as C,descendantsOfKind as p,bindingKeyName as I,findObjectProperty as E,isConstDeclaration as D,walkChain as M}from"./isTestPath-JdN4KXhV.mjs";import{f as v,g as S,h as F}from"./attribution-DUbGYT4N.mjs";import{c as b}from"./classify-procedure-call-DtqiTjPg.mjs";import{isDefineMutatorCallee as w}from"./MUTATORS_FILENAME-
|
|
1
|
+
import{Node as r,SyntaxKind as d}from"ts-morph";import{unwrapExpression as l,memberAccessOf as C,descendantsOfKind as p,bindingKeyName as I,findObjectProperty as E,isConstDeclaration as D,walkChain as M}from"./isTestPath-JdN4KXhV.mjs";import{f as v,g as S,h as F}from"./attribution-DUbGYT4N.mjs";import{c as b}from"./classify-procedure-call-DtqiTjPg.mjs";import{isDefineMutatorCallee as w}from"./MUTATORS_FILENAME-BGvYo46g.mjs";const x=8,h=t=>{if(r.isMethodDeclaration(t))return t;const e=r.isPropertyAssignment(t)?l(t.getInitializer()):void 0,o=r.isShorthandPropertyAssignment(t)?t.getNameNode():e;if(r.isArrowFunction(o)||r.isFunctionExpression(o))return o;const i=r.isIdentifier(o)?v(o):void 0;if(r.isFunctionDeclaration(i))return i;const n=D(i)?l(i.getInitializer()):void 0;return r.isArrowFunction(n)||r.isFunctionExpression(n)?n:void 0},T=t=>{const e=l(t.getArguments()[0]),o=r.isObjectLiteralExpression(e)?e:void 0,i=E(o,"server"),n=E(o,"handler"),s=i!==void 0&&w(t.getExpression()),a=n===void 0?void 0:b(t),u=a!==void 0&&a.receiver===void 0;return[s?h(i):void 0,u?h(n):void 0].filter(f=>f!==void 0)},N=new WeakMap,O=t=>{const e=t.getSourceFile(),o=N.get(e.compilerNode);if(o!==void 0)return o;const i=new Set(e.getDescendantsOfKind(d.CallExpression).flatMap(n=>T(n)).map(n=>n.compilerNode));return N.set(e.compilerNode,i),i},A=t=>{const e=t.getParent();return(r.isArrowFunction(e)||r.isFunctionExpression(e)||r.isFunctionDeclaration(e)||r.isMethodDeclaration(e))&&e.getParameters()[0]===t&&O(t).has(e.compilerNode)},Q=t=>{const e=t.getParent();return(r.isArrowFunction(e)||r.isFunctionExpression(e)||r.isFunctionDeclaration(e)||r.isMethodDeclaration(e))&&e.getParameters()[1]===t&&O(t).has(e.compilerNode)},B=t=>t.getNameNode().getDescendantsOfKind(d.BindingElement).some(e=>e.getParent().getParent()===t&&["args","ctx"].includes(I(e))),g=(t,e,o)=>{const i=t.getParent().getParent(),n=I(t);if(t.getDotDotDotToken()!==void 0||e==="trust"&&S(t))return;let s;if(r.isParameterDeclaration(i)){if(!A(i)||B(i))return n==="ctx"?[]:void 0;s=[]}else r.isBindingElement(i)?s=g(i,e,o):r.isVariableDeclaration(i)&&o>0&&(s=c(i.getInitializer(),e,o-1));return s===void 0?void 0:[...s,n]},c=(t,e="discover",o=x)=>{const i=l(t),n=C(i);if(n!==void 0){const s=c(n.object,e,o);return s===void 0?void 0:[...s,n.member]}return r.isIdentifier(i)?H(i,e,o):void 0},H=(t,e,o)=>{const i=t.getText()==="ctx",n=e==="trust"||!i?v(t):void 0;return i&&!r.isVariableDeclaration(n)?r.isBindingElement(n)?g(n,e,o):[]:r.isParameterDeclaration(n)?r.isIdentifier(n.getNameNode())&&A(n)?[]:void 0:r.isBindingElement(n)?g(n,e,o):!(r.isVariableDeclaration(n)&&r.isIdentifier(n.getNameNode())&&o>0)||e==="trust"&&S(n)?void 0:c(n.getInitializer(),e,o-1)},q=t=>c(t,"discover"),K=t=>{const e=c(t);return e===void 0?void 0:["ctx",...e].join(".")},J=(t,e)=>{if(e(t.getText()))return!0;const o=K(t);return o!==void 0&&e(o)},Y=(t,e)=>{const o=l(t),i=C(o);if(i!==void 0&&i.member!==e.at(-1))return!1;const n=o===void 0?void 0:c(o);return n?.length===e.length&&n.every((s,a)=>s===e[a])},Z=(t,e)=>y(t).get(e)??[],U=t=>{const e=new Map;for(const i of p(t,d.BindingElement)){const n=r.isIdentifier(i.getNameNode())?g(i,"discover",x):void 0;n?.length===1&&n[0]!==void 0&&e.set(i.compilerNode,n[0])}const o=new Set([...e.keys()].map(i=>i.name.getText()));return p(t,d.Identifier).flatMap(i=>{const s=o.has(i.getText())&&!r.isBindingElement(i.getParent())?v(i):void 0,a=s===void 0?void 0:e.get(s.compilerNode);return a===void 0?[]:[[a,i]]})},P=new WeakMap,y=t=>{const e=P.get(t.compilerNode);if(e!==void 0)return e;const o=new Map;for(const[n,s]of[...z(t),...U(t)])o.set(n,[...o.get(n)??[],s]);const i=new Map([...o].map(([n,s])=>[n,s.toSorted((a,u)=>a.getPos()-u.getPos())]));return P.set(t.compilerNode,i),i},z=t=>t.getDescendantsOfKind(d.PropertyAccessExpression).flatMap(e=>_(e.getExpression())?[[e.getName(),e]]:[]),_=t=>r.isIdentifier(t)&&c(t)?.length===0,$=t=>{const e=c(t);return e?.length===1&&e[0]==="db"},R=new Set(["asId","createMultipartUpload","fetch","generateUploadUrl","getPresignedUrl","getSignedUrl","getUrl","normalizeId","resumeMultipartUpload","runAction","runMutation","runQuery","store","upload"]),k=new Set(["catch","flatMap","map","reduce","reduceRight","then"]),L=(t,e=x)=>{const o=M(t,u=>{const f=l(u.getExpression()),m=r.isPropertyAccessExpression(f)?f.getName():void 0;return m!==void 0&&(R.has(m)||k.has(m))?!1:void 0}),i=o.root;if(o.verdict!==void 0||!r.isIdentifier(i))return o.verdict??!1;if(c(i,"trust")!==void 0)return!0;const n=v(i),s=r.isBindingElement(n)?n.getFirstAncestorByKind(d.VariableDeclaration):n,a=D(s)&&e>0?s.getInitializer():void 0;return a!==void 0&&L(a,e-1)},ee=t=>(r.isIdentifier(t)?[t]:t.getDescendantsOfKind(d.Identifier)).some(o=>F(o)&&c(o,"trust")!==void 0);export{k as C,R as E,Q as a,K as b,Z as c,$ as d,q as e,L as f,_ as g,Y as i,J as m,ee as r};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{SyntaxKind as g,Node as n}from"ts-morph";import{descendantsOfKind as p}from"./isTestPath-JdN4KXhV.mjs";import{d as l}from"./context-root-
|
|
1
|
+
import{SyntaxKind as g,Node as n}from"ts-morph";import{descendantsOfKind as p}from"./isTestPath-JdN4KXhV.mjs";import{d as l}from"./context-root-D4Njep-A.mjs";const c=e=>n.isPropertyAccessExpression(e)&&e.getName()==="db"||n.isIdentifier(e)&&e.getText()==="db"||l(e),b=new Set(["findFirst","findFirstOrThrow","findMany","findUnique"]),E=e=>{const t=e.getExpression();if(!n.isPropertyAccessExpression(t)||!b.has(t.getName()))return;const s=t.getExpression();if(c(s))return{options:e.getArguments()[1],table:d(e)};if(n.isPropertyAccessExpression(s)){const o=s.getExpression();if(c(o))return{options:e.getArguments()[0],table:s.getName()}}},f=(e,t)=>{const s=e.getExpression();return!n.isPropertyAccessExpression(s)||!t.has(s.getName())?!1:c(s.getExpression())},d=e=>{const t=e.getArguments()[0];return t&&n.isStringLiteral(t)?t.getLiteralText():""},A=(e,t,s)=>{const o=new Set,i=new Set;for(const a of p(e,g.CallExpression))if(f(a,t)){const r=d(a);r!==""&&o.add(r)}else if(f(a,s)){const r=d(a);r!==""&&i.add(r)}return{tablesRead:[...o],tablesWritten:[...i]}};export{c as i,E as r,A as t};
|
package/dist/packem_shared/{discoverFunctions-a0IT8OSb.mjs → discoverFunctions-CoQM_L6f.mjs}
RENAMED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{LunoraError as d}from"@lunora/errors";import{Node as s,SyntaxKind as w}from"ts-morph";import{d as k}from"./declared-output-Iaar469J.mjs";import{findObjectProperty as g,bindingKeyName as C,listLunoraSourceFiles as I,lunoraRelativePath as R}from"./isTestPath-JdN4KXhV.mjs";import{e as F,i as _}from"./attribution-DUbGYT4N.mjs";import{u as E,p as V,c as A,r as z}from"./unwrap-handler-return-eQRIZSOX.mjs";import{b as v,s as $,c as j}from"./classify-procedure-call-DtqiTjPg.mjs";import{r as N,p as O,a as D}from"./parse-validator-CP5CL6Q7.mjs";import{s as M}from"./dispatch-namespace-DwTjD7BU.mjs";const W=t=>{const i=t.getArguments()[0];if(!i||!s.isObjectLiteralExpression(i))return"unknown";const e=g(i,"handler");if(!e||!s.isPropertyAssignment(e))return"unknown";const r=e.getInitializer();return!r||!(s.isArrowFunction(r)||s.isFunctionExpression(r))?"unknown":E(r)},H=t=>{const i=t.getArguments()[0];return!i||!(s.isArrowFunction(i)||s.isFunctionExpression(i))?"unknown":E(i)},B=t=>{let i={};for(const e of v(t)){if(e.name!=="input")continue;const r=e.call.getArguments()[0],o=r!==void 0&&s.isExpression(r)?N(r):void 0;o!==void 0&&(i={...O(o),...i})}return i},K=t=>{const i=v(t).find(r=>r.name==="output");if(!i)return;const e=i.call.getArguments()[0];return e&&s.isExpression(e)?V(i.call,()=>D(e)):void 0},x=(t,i)=>{const e=g(t,i);if(e===void 0||!s.isPropertyAssignment(e))return;const r=e.getInitializer();return r!==void 0&&s.isStringLiteral(r)?r.getLiteralValue():void 0},P=(t,i)=>{const e=g(t,i);if(e===void 0||!s.isPropertyAssignment(e))return;const r=e.getInitializer();return r!==void 0&&s.isNumericLiteral(r)?r.getLiteralValue():void 0},U=t=>{const i=g(t,"cache");if(i===void 0||!s.isPropertyAssignment(i))return;const e=i.getInitializer();if(e===void 0||!s.isObjectLiteralExpression(e))return;const r=x(e,"scope"),o=P(e,"maxAge"),n=P(e,"staleWhileRevalidate"),a=x(e,"tag"),l=x(e,"vary"),c={...o===void 0?{}:{maxAge:o},...r==="private"||r==="public"?{scope:r}:{},...n===void 0?{}:{staleWhileRevalidate:n},...a===void 0?{}:{tag:a},...l===void 0?{}:{vary:l}};return Object.keys(c).length===0?void 0:c},q=t=>{if(t===void 0||!s.isObjectLiteralExpression(t))return{};const i=U(t),e=g(t,"rest");return e!==void 0&&s.isPropertyAssignment(e)?{...i===void 0?{}:{cache:i},rest:e.getInitializer()?.getText()==="true"}:i===void 0?{}:{cache:i}},J=t=>{const i=v(t).find(e=>e.name==="expose");return i?q(i.call.getArguments()[0]):void 0},X=t=>{const i=v(t).find(n=>n.name==="x402");if(!i)return;const e=i.call.getArguments()[0];if(e===void 0||!s.isObjectLiteralExpression(e))return{};const r=g(e,"price");if(r===void 0||!s.isPropertyAssignment(r))return{};const o=r.getInitializer();return o===void 0?{}:s.isStringLiteral(o)?{price:o.getLiteralValue()}:s.isNumericLiteral(o)?{price:o.getLiteralValue()}:{}},G=t=>{const i=t.getArguments()[0];if(!i||!s.isObjectLiteralExpression(i))return{};const e=g(i,"args");if(!e||!s.isPropertyAssignment(e))return{};const r=e.getInitializer(),o=r===void 0?void 0:N(r);return o===void 0?{}:O(o)},p=(t,i)=>{throw new d("INTERNAL",`@lunora/codegen: lazy function registry needs literal ${i} in ${t.getSourceFile().getFilePath()}:${String(t.getStartLineNumber())}`)},b=(t,i,e)=>{if(!t||!s.isObjectLiteralExpression(t))return p(i,"metadata objects");const r=new Set;for(const o of t.getProperties()){if(!s.isPropertyAssignment(o))return p(o,"metadata fields without spreads, getters, or shorthand");const n=o.getNameNode(),a=s.isStringLiteral(n)?n.getLiteralValue():n.getText();if(!s.isIdentifier(n)&&!s.isStringLiteral(n)||!e.includes(a)||r.has(a))return p(o,"supported, unique metadata fields");r.add(a)}return t},m=(t,i)=>{const e=t.getProperty(i);return e&&s.isPropertyAssignment(e)?e.getInitializer():void 0},Q=t=>{const i=b(t,t,["credentialHeaders","maxAge","scope","staleWhileRevalidate","tag","vary"]),e={};for(const n of["maxAge","staleWhileRevalidate"]){const a=m(i,n);if(!(a===void 0&&n!=="maxAge")){if(!a||!s.isNumericLiteral(a))return p(t,`cache.${n}`);e[n]=a.getLiteralValue()}}const r=m(i,"scope");if(!r||!s.isStringLiteral(r)||!["private","public"].includes(r.getLiteralValue()))return p(t,"cache.scope");e.scope=r.getLiteralValue();for(const n of["tag","vary"]){const a=m(i,n);if(a!==void 0){if(!s.isStringLiteral(a))return p(a,`cache.${n}`);e[n]=a.getLiteralValue()}}const o=m(i,"credentialHeaders");if(o!==void 0){if(!s.isArrayLiteralExpression(o))return p(o,"cache.credentialHeaders");e.credentialHeaders=o.getElements().map(n=>s.isStringLiteral(n)?n.getLiteralValue():p(n,"cache.credentialHeaders string entries"))}return e},Y=t=>{const i=b(t.getArguments()[0],t,["rest","cache"]),e=m(i,"rest"),r=m(i,"cache");return e!==void 0&&!s.isTrueLiteral(e)&&!s.isFalseLiteral(e)?p(e,".expose({ rest })"):{...e?{rest:s.isTrueLiteral(e)}:{},...r?{cache:Q(r)}:{}}},Z=t=>{const i=b(t.getArguments()[0],t,["price"]),e=m(i,"price");return!e||!s.isStringLiteral(e)&&!s.isNumericLiteral(e)?p(t,"`.x402({ price })` value"):{price:e.getLiteralValue()}},ee=t=>{const{factory:i,steps:e}=$(t);if(!i)return p(t,"metadata from a resolvable Lunora factory root");const r={visibility:i.startsWith("internal")?"internal":"public"};for(const{call:o,name:n}of e){if(!["expose","input","meta","output","use","x402"].includes(n))return p(o,`known builder modifiers, got .${n}()`);n==="expose"&&r.expose===void 0&&(r.expose=Y(o)),n==="x402"&&r.x402===void 0&&(r.x402=Z(o))}return r},te=8,h=(t,i=0)=>{if(i>te)return;if(s.isCallExpression(t))return t;if(s.isParenthesizedExpression(t)||s.isAsExpression(t)||s.isSatisfiesExpression(t)||s.isNonNullExpression(t))return h(t.getExpression(),i+1);if(!s.isIdentifier(t)&&!s.isPropertyAccessExpression(t))return;const e=t.getSymbol()?.getValueDeclaration();return e?L(e,i+1):void 0},L=(t,i)=>{if(s.isVariableDeclaration(t)||s.isPropertyAssignment(t)){const e=t.getInitializer();return e?h(e,i):void 0}if(s.isShorthandPropertyAssignment(t)){const e=t.getValueSymbol()?.getValueDeclaration();return e?L(e,i+1):void 0}if(s.isBindingElement(t)){const e=C(t),n=t.getFirstAncestorByKind(w.VariableDeclaration)?.getInitializer()?.getType().getProperty(e)?.getValueDeclaration();return n?L(n,i+1):void 0}},ie=(t,i=()=>!0)=>{const e=t.getNameNode();if(s.isObjectBindingPattern(e)){const n=[];for(const a of e.getElements().filter(l=>i(l.getName()))){const l=h(a.getNameNode());l&&n.push([a.getName(),l])}return n}if(!i(t.getName()))return[];const r=t.getInitializer(),o=r&&(s.isCallExpression(r)?r:h(r));return o?[[t.getName(),o]]:[]},re=t=>{const i=t.getArguments()[0],e=s.isObjectLiteralExpression(i)?i.getProperty("name"):void 0,r=s.isPropertyAssignment(e)?e.getInitializer():void 0;if(!r||!s.isStringLiteral(r))throw new d("ROOM_NAME_NOT_LITERAL",'defineRoom needs a string-literal `name` (e.g. `defineRoom({ name: "chat", … })`) so codegen can type its reference.');return r.getLiteralValue()},ne=t=>t.startsWith("/")&&new URL(t,"https://lunora.invalid").pathname===t&&t!=="/_lunora"&&!t.startsWith("/_lunora/"),se=t=>{const i=t.getArguments()[0];if(!s.isObjectLiteralExpression(i))throw new d("SOCKET_PATH_NOT_LITERAL","defineWebSocket needs an object-literal options argument so codegen can read its `path` and `auth`.");const e=i.getProperty("path"),r=s.isPropertyAssignment(e)?e.getInitializer():void 0;if(!r||!s.isStringLiteral(r))throw new d("SOCKET_PATH_NOT_LITERAL",'defineWebSocket needs a string-literal `path` (e.g. `defineWebSocket({ path: "/chat", … })`) so codegen can route its upgrade.');const o=r.getLiteralValue();if(!ne(o))throw new d("SOCKET_PATH_INVALID",`defineWebSocket path "${o}" must be a plain URL path starting with "/" (no "?", "#", ".." or unencoded characters) and not under "/_lunora".`);if(i.getProperties().some(c=>s.isSpreadAssignment(c)||s.isPropertyAssignment(c)&&s.isComputedPropertyName(c.getNameNode())))throw new d("SOCKET_AUTH_NOT_LITERAL","defineWebSocket cannot spread its options or use a computed key: codegen must read `auth` as a literal `auth: true` or `auth: false`.");const a=i.getProperty("auth");if(a===void 0)return{auth:!1,path:o};const l=s.isPropertyAssignment(a)?a.getInitializer():void 0;if(l===void 0||!(s.isTrueLiteral(l)||s.isFalseLiteral(l)))throw new d("SOCKET_AUTH_NOT_LITERAL","defineWebSocket needs a literal `auth: true` or `auth: false`, so codegen can read whether the route requires a session. A shorthand or a variable is not read.");return{auth:s.isTrueLiteral(l),path:o}},oe=(t,i,e,r)=>{const o=r?ee(i):void 0,n=r?o?.expose:J(i),a=r?o?.x402:X(i),l=A(()=>K(i)),c=A(()=>H(t)),u=k({kind:e.kind,output:l.value});return z(u?l.erased:c.erased),{args:B(i),...n?{expose:n}:{},...a?{x402:a}:{},...e.adminOnly?{adminOnly:!0}:{},kind:e.kind,...l.value?{output:l.value}:{},returnType:c.value,visibility:o?.visibility==="internal"||e.visibility==="internal"?"internal":"public"}},ae=(t,i)=>{const e=j(t,i);if(!e)return;if(e.channel)return{args:{},channel:{kind:e.channel,name:re(t)},kind:e.kind,returnType:"void",visibility:e.visibility};const{receiver:r}=e;return r?oe(t,r,e,i):e.lifecycle?{args:{},kind:e.kind,lifecycle:e.lifecycle,returnType:"void",...e.lifecycle==="socket"?{socket:{...se(t),origin:`${t.getSourceFile().getFilePath()}@${String(t.getStart())}`}}:{},visibility:e.visibility}:{args:G(t),kind:e.kind,returnType:W(t),visibility:e.visibility}},S=t=>{const i=t?.getJsDocs().at(-1)?.getDescription().trim();return i===""?void 0:i},ce=t=>S(t.getFirstAncestor(i=>s.isVariableStatement(i))),le=(t,i)=>S(t.getVariableStatements().find(e=>e.isExported()&&e.getDeclarations().some(r=>r.getName()===i))),T=(t,i,e,r,o)=>{const n=ae(t,r);if(!n)return;const a=o??ce(t);return{args:n.args,...a?{description:a}:{},exportName:i,filePath:e,kind:n.kind,returnType:n.returnType,...n.output?{output:n.output}:{},visibility:n.visibility,...n.adminOnly?{adminOnly:!0}:{},...n.expose?{expose:n.expose}:{},...n.x402?{x402:n.x402}:{},...n.lifecycle?{lifecycle:n.lifecycle}:{},...n.channel?{channel:n.channel}:{},...n.socket?{socket:n.socket}:{}}},ue=(t,i,e)=>{const r=[];for(const o of t.getExportAssignments()){if(o.isExportEquals())continue;const n=h(o.getExpression()),a=n?T(n,"default",i,e):void 0;n&&a&&r.push({call:n,entry:a})}return r},pe=(t,i,e)=>{const r=F(t),o=new Map,n=(c,u)=>{if(c?.channel?.kind!=="room")return;const f=o.get(c.channel.name);if(f!==void 0&&f!==u)throw new d("DUPLICATE_ROOM_NAME",`Duplicate room name "${c.channel.name}" in ${i}: two defineRoom calls share it. Room names must be unique.`);o.set(c.channel.name,u)},a=t.getVariableStatements().flatMap(c=>c.getDeclarations()).flatMap(c=>ie(c,u=>r.has(u))).flatMap(([c,u])=>(r.get(c)??[]).filter(f=>_(f)).flatMap(f=>{const y=T(u,f,i,e,le(t,f));return n(y,u),y?[y]:[]})),l=new Set(a.map(c=>c.exportName));for(const{call:c,entry:u}of ue(t,i,e))l.has(u.exportName)||(n(u,c),a.push(u));return a},de=t=>{const i=new Map;for(const e of t){if(e.channel?.kind!=="room")continue;const r=i.get(e.channel.name);if(r!==void 0&&r.file!==e.filePath)throw new d("DUPLICATE_ROOM_NAME",`Duplicate room name "${e.channel.name}": defined in ${r.origin} and ${e.filePath}:${e.exportName}. Room names must be unique across the project.`);r===void 0&&i.set(e.channel.name,{file:e.filePath,origin:`${e.filePath}:${e.exportName}`})}},fe=t=>{const i=new Map;for(const e of t){const r=M(e.filePath),o=i.get(r);if(o&&o!==e.filePath)throw Object.assign(new Error(`Namespace collision: "${o}" and "${e.filePath}" both resolve to "${r}". Rename one of the files so the JS-identifier-sanitized names differ. (note: case-insensitive filesystems may also cause this — \`foo\` and \`FOO\` map to the same identifier)`),{code:"NAMESPACE_COLLISION",name:"LunoraError",paths:[o,e.filePath],status:500});i.set(r,e.filePath)}},Pe=(t,i,e={})=>{const r=I(i),o=[];for(const n of r){const a=t.getSourceFile(n)??t.addSourceFileAtPath(n),l=R(i,n);o.push(...pe(a,l,e.lazyFunctions===!0))}return o.sort((n,a)=>`${n.filePath}:${n.exportName}`.localeCompare(`${a.filePath}:${a.exportName}`)),fe(o),de(o),o};export{Pe as default};
|
|
1
|
+
import{LunoraError as d}from"@lunora/errors";import{Node as s,SyntaxKind as w}from"ts-morph";import{d as k}from"./declared-output-Iaar469J.mjs";import{findObjectProperty as g,bindingKeyName as C,listLunoraSourceFiles as I,lunoraRelativePath as R}from"./isTestPath-JdN4KXhV.mjs";import{e as F,i as _}from"./attribution-DUbGYT4N.mjs";import{u as E,p as V,c as A,r as z}from"./unwrap-handler-return-eQRIZSOX.mjs";import{b as v,s as $,c as j}from"./classify-procedure-call-DtqiTjPg.mjs";import{r as N,p as O,a as D}from"./parse-validator-BisfC8bR.mjs";import{s as M}from"./dispatch-namespace-DwTjD7BU.mjs";const W=t=>{const i=t.getArguments()[0];if(!i||!s.isObjectLiteralExpression(i))return"unknown";const e=g(i,"handler");if(!e||!s.isPropertyAssignment(e))return"unknown";const r=e.getInitializer();return!r||!(s.isArrowFunction(r)||s.isFunctionExpression(r))?"unknown":E(r)},H=t=>{const i=t.getArguments()[0];return!i||!(s.isArrowFunction(i)||s.isFunctionExpression(i))?"unknown":E(i)},B=t=>{let i={};for(const e of v(t)){if(e.name!=="input")continue;const r=e.call.getArguments()[0],o=r!==void 0&&s.isExpression(r)?N(r):void 0;o!==void 0&&(i={...O(o),...i})}return i},K=t=>{const i=v(t).find(r=>r.name==="output");if(!i)return;const e=i.call.getArguments()[0];return e&&s.isExpression(e)?V(i.call,()=>D(e)):void 0},x=(t,i)=>{const e=g(t,i);if(e===void 0||!s.isPropertyAssignment(e))return;const r=e.getInitializer();return r!==void 0&&s.isStringLiteral(r)?r.getLiteralValue():void 0},P=(t,i)=>{const e=g(t,i);if(e===void 0||!s.isPropertyAssignment(e))return;const r=e.getInitializer();return r!==void 0&&s.isNumericLiteral(r)?r.getLiteralValue():void 0},U=t=>{const i=g(t,"cache");if(i===void 0||!s.isPropertyAssignment(i))return;const e=i.getInitializer();if(e===void 0||!s.isObjectLiteralExpression(e))return;const r=x(e,"scope"),o=P(e,"maxAge"),n=P(e,"staleWhileRevalidate"),a=x(e,"tag"),l=x(e,"vary"),c={...o===void 0?{}:{maxAge:o},...r==="private"||r==="public"?{scope:r}:{},...n===void 0?{}:{staleWhileRevalidate:n},...a===void 0?{}:{tag:a},...l===void 0?{}:{vary:l}};return Object.keys(c).length===0?void 0:c},q=t=>{if(t===void 0||!s.isObjectLiteralExpression(t))return{};const i=U(t),e=g(t,"rest");return e!==void 0&&s.isPropertyAssignment(e)?{...i===void 0?{}:{cache:i},rest:e.getInitializer()?.getText()==="true"}:i===void 0?{}:{cache:i}},J=t=>{const i=v(t).find(e=>e.name==="expose");return i?q(i.call.getArguments()[0]):void 0},X=t=>{const i=v(t).find(n=>n.name==="x402");if(!i)return;const e=i.call.getArguments()[0];if(e===void 0||!s.isObjectLiteralExpression(e))return{};const r=g(e,"price");if(r===void 0||!s.isPropertyAssignment(r))return{};const o=r.getInitializer();return o===void 0?{}:s.isStringLiteral(o)?{price:o.getLiteralValue()}:s.isNumericLiteral(o)?{price:o.getLiteralValue()}:{}},G=t=>{const i=t.getArguments()[0];if(!i||!s.isObjectLiteralExpression(i))return{};const e=g(i,"args");if(!e||!s.isPropertyAssignment(e))return{};const r=e.getInitializer(),o=r===void 0?void 0:N(r);return o===void 0?{}:O(o)},p=(t,i)=>{throw new d("INTERNAL",`@lunora/codegen: lazy function registry needs literal ${i} in ${t.getSourceFile().getFilePath()}:${String(t.getStartLineNumber())}`)},b=(t,i,e)=>{if(!t||!s.isObjectLiteralExpression(t))return p(i,"metadata objects");const r=new Set;for(const o of t.getProperties()){if(!s.isPropertyAssignment(o))return p(o,"metadata fields without spreads, getters, or shorthand");const n=o.getNameNode(),a=s.isStringLiteral(n)?n.getLiteralValue():n.getText();if(!s.isIdentifier(n)&&!s.isStringLiteral(n)||!e.includes(a)||r.has(a))return p(o,"supported, unique metadata fields");r.add(a)}return t},m=(t,i)=>{const e=t.getProperty(i);return e&&s.isPropertyAssignment(e)?e.getInitializer():void 0},Q=t=>{const i=b(t,t,["credentialHeaders","maxAge","scope","staleWhileRevalidate","tag","vary"]),e={};for(const n of["maxAge","staleWhileRevalidate"]){const a=m(i,n);if(!(a===void 0&&n!=="maxAge")){if(!a||!s.isNumericLiteral(a))return p(t,`cache.${n}`);e[n]=a.getLiteralValue()}}const r=m(i,"scope");if(!r||!s.isStringLiteral(r)||!["private","public"].includes(r.getLiteralValue()))return p(t,"cache.scope");e.scope=r.getLiteralValue();for(const n of["tag","vary"]){const a=m(i,n);if(a!==void 0){if(!s.isStringLiteral(a))return p(a,`cache.${n}`);e[n]=a.getLiteralValue()}}const o=m(i,"credentialHeaders");if(o!==void 0){if(!s.isArrayLiteralExpression(o))return p(o,"cache.credentialHeaders");e.credentialHeaders=o.getElements().map(n=>s.isStringLiteral(n)?n.getLiteralValue():p(n,"cache.credentialHeaders string entries"))}return e},Y=t=>{const i=b(t.getArguments()[0],t,["rest","cache"]),e=m(i,"rest"),r=m(i,"cache");return e!==void 0&&!s.isTrueLiteral(e)&&!s.isFalseLiteral(e)?p(e,".expose({ rest })"):{...e?{rest:s.isTrueLiteral(e)}:{},...r?{cache:Q(r)}:{}}},Z=t=>{const i=b(t.getArguments()[0],t,["price"]),e=m(i,"price");return!e||!s.isStringLiteral(e)&&!s.isNumericLiteral(e)?p(t,"`.x402({ price })` value"):{price:e.getLiteralValue()}},ee=t=>{const{factory:i,steps:e}=$(t);if(!i)return p(t,"metadata from a resolvable Lunora factory root");const r={visibility:i.startsWith("internal")?"internal":"public"};for(const{call:o,name:n}of e){if(!["expose","input","meta","output","use","x402"].includes(n))return p(o,`known builder modifiers, got .${n}()`);n==="expose"&&r.expose===void 0&&(r.expose=Y(o)),n==="x402"&&r.x402===void 0&&(r.x402=Z(o))}return r},te=8,h=(t,i=0)=>{if(i>te)return;if(s.isCallExpression(t))return t;if(s.isParenthesizedExpression(t)||s.isAsExpression(t)||s.isSatisfiesExpression(t)||s.isNonNullExpression(t))return h(t.getExpression(),i+1);if(!s.isIdentifier(t)&&!s.isPropertyAccessExpression(t))return;const e=t.getSymbol()?.getValueDeclaration();return e?L(e,i+1):void 0},L=(t,i)=>{if(s.isVariableDeclaration(t)||s.isPropertyAssignment(t)){const e=t.getInitializer();return e?h(e,i):void 0}if(s.isShorthandPropertyAssignment(t)){const e=t.getValueSymbol()?.getValueDeclaration();return e?L(e,i+1):void 0}if(s.isBindingElement(t)){const e=C(t),n=t.getFirstAncestorByKind(w.VariableDeclaration)?.getInitializer()?.getType().getProperty(e)?.getValueDeclaration();return n?L(n,i+1):void 0}},ie=(t,i=()=>!0)=>{const e=t.getNameNode();if(s.isObjectBindingPattern(e)){const n=[];for(const a of e.getElements().filter(l=>i(l.getName()))){const l=h(a.getNameNode());l&&n.push([a.getName(),l])}return n}if(!i(t.getName()))return[];const r=t.getInitializer(),o=r&&(s.isCallExpression(r)?r:h(r));return o?[[t.getName(),o]]:[]},re=t=>{const i=t.getArguments()[0],e=s.isObjectLiteralExpression(i)?i.getProperty("name"):void 0,r=s.isPropertyAssignment(e)?e.getInitializer():void 0;if(!r||!s.isStringLiteral(r))throw new d("ROOM_NAME_NOT_LITERAL",'defineRoom needs a string-literal `name` (e.g. `defineRoom({ name: "chat", … })`) so codegen can type its reference.');return r.getLiteralValue()},ne=t=>t.startsWith("/")&&new URL(t,"https://lunora.invalid").pathname===t&&t!=="/_lunora"&&!t.startsWith("/_lunora/"),se=t=>{const i=t.getArguments()[0];if(!s.isObjectLiteralExpression(i))throw new d("SOCKET_PATH_NOT_LITERAL","defineWebSocket needs an object-literal options argument so codegen can read its `path` and `auth`.");const e=i.getProperty("path"),r=s.isPropertyAssignment(e)?e.getInitializer():void 0;if(!r||!s.isStringLiteral(r))throw new d("SOCKET_PATH_NOT_LITERAL",'defineWebSocket needs a string-literal `path` (e.g. `defineWebSocket({ path: "/chat", … })`) so codegen can route its upgrade.');const o=r.getLiteralValue();if(!ne(o))throw new d("SOCKET_PATH_INVALID",`defineWebSocket path "${o}" must be a plain URL path starting with "/" (no "?", "#", ".." or unencoded characters) and not under "/_lunora".`);if(i.getProperties().some(c=>s.isSpreadAssignment(c)||s.isPropertyAssignment(c)&&s.isComputedPropertyName(c.getNameNode())))throw new d("SOCKET_AUTH_NOT_LITERAL","defineWebSocket cannot spread its options or use a computed key: codegen must read `auth` as a literal `auth: true` or `auth: false`.");const a=i.getProperty("auth");if(a===void 0)return{auth:!1,path:o};const l=s.isPropertyAssignment(a)?a.getInitializer():void 0;if(l===void 0||!(s.isTrueLiteral(l)||s.isFalseLiteral(l)))throw new d("SOCKET_AUTH_NOT_LITERAL","defineWebSocket needs a literal `auth: true` or `auth: false`, so codegen can read whether the route requires a session. A shorthand or a variable is not read.");return{auth:s.isTrueLiteral(l),path:o}},oe=(t,i,e,r)=>{const o=r?ee(i):void 0,n=r?o?.expose:J(i),a=r?o?.x402:X(i),l=A(()=>K(i)),c=A(()=>H(t)),u=k({kind:e.kind,output:l.value});return z(u?l.erased:c.erased),{args:B(i),...n?{expose:n}:{},...a?{x402:a}:{},...e.adminOnly?{adminOnly:!0}:{},kind:e.kind,...l.value?{output:l.value}:{},returnType:c.value,visibility:o?.visibility==="internal"||e.visibility==="internal"?"internal":"public"}},ae=(t,i)=>{const e=j(t,i);if(!e)return;if(e.channel)return{args:{},channel:{kind:e.channel,name:re(t)},kind:e.kind,returnType:"void",visibility:e.visibility};const{receiver:r}=e;return r?oe(t,r,e,i):e.lifecycle?{args:{},kind:e.kind,lifecycle:e.lifecycle,returnType:"void",...e.lifecycle==="socket"?{socket:{...se(t),origin:`${t.getSourceFile().getFilePath()}@${String(t.getStart())}`}}:{},visibility:e.visibility}:{args:G(t),kind:e.kind,returnType:W(t),visibility:e.visibility}},S=t=>{const i=t?.getJsDocs().at(-1)?.getDescription().trim();return i===""?void 0:i},ce=t=>S(t.getFirstAncestor(i=>s.isVariableStatement(i))),le=(t,i)=>S(t.getVariableStatements().find(e=>e.isExported()&&e.getDeclarations().some(r=>r.getName()===i))),T=(t,i,e,r,o)=>{const n=ae(t,r);if(!n)return;const a=o??ce(t);return{args:n.args,...a?{description:a}:{},exportName:i,filePath:e,kind:n.kind,returnType:n.returnType,...n.output?{output:n.output}:{},visibility:n.visibility,...n.adminOnly?{adminOnly:!0}:{},...n.expose?{expose:n.expose}:{},...n.x402?{x402:n.x402}:{},...n.lifecycle?{lifecycle:n.lifecycle}:{},...n.channel?{channel:n.channel}:{},...n.socket?{socket:n.socket}:{}}},ue=(t,i,e)=>{const r=[];for(const o of t.getExportAssignments()){if(o.isExportEquals())continue;const n=h(o.getExpression()),a=n?T(n,"default",i,e):void 0;n&&a&&r.push({call:n,entry:a})}return r},pe=(t,i,e)=>{const r=F(t),o=new Map,n=(c,u)=>{if(c?.channel?.kind!=="room")return;const f=o.get(c.channel.name);if(f!==void 0&&f!==u)throw new d("DUPLICATE_ROOM_NAME",`Duplicate room name "${c.channel.name}" in ${i}: two defineRoom calls share it. Room names must be unique.`);o.set(c.channel.name,u)},a=t.getVariableStatements().flatMap(c=>c.getDeclarations()).flatMap(c=>ie(c,u=>r.has(u))).flatMap(([c,u])=>(r.get(c)??[]).filter(f=>_(f)).flatMap(f=>{const y=T(u,f,i,e,le(t,f));return n(y,u),y?[y]:[]})),l=new Set(a.map(c=>c.exportName));for(const{call:c,entry:u}of ue(t,i,e))l.has(u.exportName)||(n(u,c),a.push(u));return a},de=t=>{const i=new Map;for(const e of t){if(e.channel?.kind!=="room")continue;const r=i.get(e.channel.name);if(r!==void 0&&r.file!==e.filePath)throw new d("DUPLICATE_ROOM_NAME",`Duplicate room name "${e.channel.name}": defined in ${r.origin} and ${e.filePath}:${e.exportName}. Room names must be unique across the project.`);r===void 0&&i.set(e.channel.name,{file:e.filePath,origin:`${e.filePath}:${e.exportName}`})}},fe=t=>{const i=new Map;for(const e of t){const r=M(e.filePath),o=i.get(r);if(o&&o!==e.filePath)throw Object.assign(new Error(`Namespace collision: "${o}" and "${e.filePath}" both resolve to "${r}". Rename one of the files so the JS-identifier-sanitized names differ. (note: case-insensitive filesystems may also cause this — \`foo\` and \`FOO\` map to the same identifier)`),{code:"NAMESPACE_COLLISION",name:"LunoraError",paths:[o,e.filePath],status:500});i.set(r,e.filePath)}},Pe=(t,i,e={})=>{const r=I(i),o=[];for(const n of r){const a=t.getSourceFile(n)??t.addSourceFileAtPath(n),l=R(i,n);o.push(...pe(a,l,e.lazyFunctions===!0))}return o.sort((n,a)=>`${n.filePath}:${n.exportName}`.localeCompare(`${a.filePath}:${a.exportName}`)),fe(o),de(o),o};export{Pe as default};
|
package/dist/packem_shared/{discoverHttpRoutes-DHDfKLoa.mjs → discoverHttpRoutes-BQM2CPSF.mjs}
RENAMED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{Node as n}from"ts-morph";import{a as m,p as l}from"./parse-validator-
|
|
1
|
+
import{Node as n}from"ts-morph";import{a as m,p as l}from"./parse-validator-BisfC8bR.mjs";import{listLunoraSourceFiles as d,lunoraRelativePath as h}from"./isTestPath-JdN4KXhV.mjs";import{b as f,d as g}from"./attribution-DUbGYT4N.mjs";import{u as x}from"./unwrap-handler-return-eQRIZSOX.mjs";const u=new Set(["delete","get","head","options","patch","post","put"]),E=new Set(["body","params","searchParams"]),v=new Set(["handler","stream"]),P=s=>{const e=s.getArguments()[0];if(e&&n.isStringLiteral(e))return e.getLiteralValue()},S=s=>{const e=s.getArguments()[0];return e&&n.isObjectLiteralExpression(e)?l(e):{}},A=s=>{if(!n.isCallExpression(s))return;const e=s.getExpression();if(!n.isPropertyAccessExpression(e))return;const o=e.getName();if(!u.has(o))return;const a=e.getExpression();if(!n.isIdentifier(a)||a.getText()!=="httpRoute")return;const t=P(s);return t===void 0?void 0:{method:o.toUpperCase(),path:t}},b=(s,e)=>{const o={body:{},params:{},searchParams:{},stream:e==="stream"},a=s.getExpression();if(!n.isPropertyAccessExpression(a))return;let t=a.getExpression();for(;n.isCallExpression(t);){const i=t.getExpression();if(!n.isPropertyAccessExpression(i))break;const c=i.getName();if(u.has(c))break;if(E.has(c)){const p=S(t);o[c]={...p,...o[c]}}else if(c==="output"&&o.output===void 0){const p=t.getArguments()[0];p&&n.isExpression(p)&&(o.output=m(p))}t=i.getExpression()}const r=A(t);if(r)return o.method=r.method,o.path=r.path,o},T=s=>{const e=s.getArguments()[0];return!e||!(n.isArrowFunction(e)||n.isFunctionExpression(e))?"unknown":x(e,!0)},y=(s,e,o,a)=>{const t=e.getName();if(!v.has(t))return;const r=b(s,t);if(!(r?.method===void 0||r.path===void 0))return{body:r.body,exportName:o,filePath:a,method:r.method,params:r.params,path:r.path,searchParams:r.searchParams,stream:r.stream,...r.stream?{chunkType:T(s)}:{},...r.output?{output:r.output}:{}}},R=(s,e)=>{const o=[];for(const a of f(s)){const t=a.getInitializer();if(!t||!n.isCallExpression(t))continue;const r=t.getExpression();if(!n.isPropertyAccessExpression(r))continue;const i=y(t,r,g(a)??a.getName(),e);i&&o.push(i)}return o},L=(s,e)=>{const o=d(e),a=[];for(const t of o){const r=s.getSourceFile(t)??s.addSourceFileAtPath(t),i=h(e,t);a.push(...R(r,i))}return a.sort((t,r)=>`${t.method} ${t.path}`.localeCompare(`${r.method} ${r.path}`)||t.filePath.localeCompare(r.filePath)),a};export{L as default};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{d as o}from"./context-property-calls-B75cjwpy.mjs";const t=(r,e)=>o(r,e,"sql");export{t as default};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{Node as i}from"ts-morph";import{collectCallRows as n}from"./isTestPath-JdN4KXhV.mjs";import{c as a}from"./attribution-DUbGYT4N.mjs";import{i as c}from"./database-calls-
|
|
1
|
+
import{Node as i}from"ts-morph";import{collectCallRows as n}from"./isTestPath-JdN4KXhV.mjs";import{c as a}from"./attribution-DUbGYT4N.mjs";import{i as c}from"./database-calls-aAjZJdma.mjs";const l=t=>{const e=t.getExpression();if(!i.isPropertyAccessExpression(e)||e.getName()!=="insert")return!1;const r=e.getExpression();return c(r)},g=t=>{if(!i.isIdentifier(t))return;const e=t.getSymbol(),r=e?.getAliasedSymbol()?.getDeclarations()??e?.getDeclarations()??[];for(const s of r)if(i.isVariableDeclaration(s)){const o=s.getInitializer();if(o&&i.isStringLiteral(o))return o.getLiteralText()}},f=t=>{const e=t.getArguments()[0];return e?i.isStringLiteral(e)?e.getLiteralText():g(e)??"":""},d=(t,e)=>n(t,e,(r,s)=>l(r)?{file:s,line:r.getStartLineNumber(),scope:a(r),table:f(r)}:void 0);export{d as default};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import"./isTestPath-JdN4KXhV.mjs";import"./attribution-DUbGYT4N.mjs";import"./database-calls-aAjZJdma.mjs";import"./classify-procedure-call-DtqiTjPg.mjs";import{d as a}from"./index-11LAY5JO.mjs";export{a as default};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{SyntaxKind as p,Node as n}from"ts-morph";import{diagnosticAt as h}from"./CodegenDiagnosticError-BUXlG3P-.mjs";import{a as I}from"./module-specifiers-BctA0m_p.mjs";import{listLunoraSourceFiles as P,lunoraRelativePath as b,findObjectProperty as d}from"./isTestPath-JdN4KXhV.mjs";import{b as x,a as A}from"./attribution-DUbGYT4N.mjs";const S=i=>{const r=i.getSymbol();if(!r)return i.getText()==="defineMigration";for(const t of r.getDeclarations())if(n.isImportSpecifier(t))return I(t.getImportDeclaration().getModuleSpecifierValue())?t.getNameNode().getText()==="defineMigration":!1;return!1},u=(i,r)=>{const t=d(i,r);if(!t||!n.isPropertyAssignment(t))return;const e=t.getInitializer();return e&&n.isStringLiteral(e)?e.getLiteralValue():void 0},z=i=>{const r=n.isPropertyAssignment(i)?i.getInitializer():void 0;if(r===void 0||!n.isObjectLiteralExpression(r))return;const t=u(r,"field"),e=d(r,"after"),o=n.isPropertyAssignment(e)?e.getInitializer():void 0;if(!(t===void 0||e!==void 0&&!(o!==void 0&&n.isNumericLiteral(o))))return{...o!==void 0&&n.isNumericLiteral(o)?{after:o.getLiteralValue()}:{},field:t}},E=i=>{const r=d(i,"covers"),t=n.isPropertyAssignment(r)?r.getInitializer():void 0;if(t===void 0||!n.isObjectLiteralExpression(t))return;const e={};for(const s of["jurisdiction","shardMode","table"]){const c=u(t,s);c!==void 0&&(e[s]=c)}const o=z(d(t,"ttl"));o!==void 0&&(e.ttl=o);const a=d(t,"memory");return n.isPropertyAssignment(a)&&a.getInitializer()?.getKind()===p.TrueKeyword&&(e.memory=!0),Object.keys(e).length===0?void 0:e},g=i=>n.isParenthesizedExpression(i)?g(i.getExpression()):i,v=i=>n.isArrowFunction(i)||n.isFunctionExpression(i)||n.isMethodDeclaration(i)||n.isFunctionDeclaration(i),y=(i,r=4)=>{const t=g(i);if(v(t))return t;if(r===0||!n.isIdentifier(t))return;const e=t.getParent(),o=n.isShorthandPropertyAssignment(e)?e.getValueSymbol():t.getSymbol(),a=o?.getAliasedSymbol()??o,s=a?.getValueDeclaration()??a?.getDeclarations()[0];if(s!==void 0){if(n.isVariableDeclaration(s)){const c=s.getInitializer();return c===void 0?void 0:y(c,r-1)}return v(s)?s:void 0}},N=i=>{const r=d(i,"up");let t=r;n.isPropertyAssignment(r)?t=r.getInitializer():n.isShorthandPropertyAssignment(r)&&(t=r.getNameNode());const e=t===void 0?void 0:y(t);if(e===void 0)return!1;const o=e.getParameters()[0]?.getNameNode();if(o===void 0||!n.isIdentifier(o))return!1;const a=m=>{const f=m===void 0?void 0:g(m);return f!==void 0&&n.isIdentifier(f)&&f.getText()===o.getText()},s=e.getBody();if(s===void 0)return!1;if(!n.isBlock(s))return a(s);const[c,...l]=s.getStatements();return l.length===0&&c!==void 0&&n.isReturnStatement(c)&&a(c.getExpression())},D=(i,r)=>{const t=i.getInitializer();if(t?.getKind()!==p.CallExpression)return;const e=t.getExpression();if(!n.isIdentifier(e)||!S(e))return;const o=t.getArguments()[0];if(!o||!n.isObjectLiteralExpression(o))return;const a=u(o,"id"),s=A(i,"member");if(s===void 0)return;if(a===void 0||a.trim()==="")throw h(o,`Migration "${s}" in "${r}" must declare \`id\` as a non-empty string literal so codegen can key the registry.`,{code:"MIGRATION_ID_NOT_STATIC",name:"LunoraError",status:500});const c=E(o);return{...c===void 0?{}:{covers:c},exportName:s,filePath:r,id:a,...N(o)?{identity:!0}:{},table:u(o,"table")??""}},M=i=>{const r=new Map;for(const t of i){const e=r.get(t.id);if(e!==void 0)throw Object.assign(new Error(`Duplicate migration id "${t.id}": declared in both "${e}" and "${t.filePath}". Migration ids must be unique across the project.`),{code:"DUPLICATE_MIGRATION_ID",id:t.id,name:"LunoraError",paths:[e,t.filePath],status:500});r.set(t.id,t.filePath)}},j=(i,r)=>{const t=P(r),e=[];for(const o of t){const a=i.getSourceFile(o)??i.addSourceFileAtPath(o),s=b(r,o);for(const c of x(a)){const l=D(c,s);l&&e.push(l)}}return e.sort((o,a)=>o.id.localeCompare(a.id)),M(e),e};export{j as default};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{Node as i,SyntaxKind as u}from"ts-morph";import{collectCallRows as x}from"./isTestPath-JdN4KXhV.mjs";import{w as E,c as h}from"./attribution-DUbGYT4N.mjs";import{i as v}from"./database-calls-
|
|
1
|
+
import{Node as i,SyntaxKind as u}from"ts-morph";import{collectCallRows as x}from"./isTestPath-JdN4KXhV.mjs";import{w as E,c as h}from"./attribution-DUbGYT4N.mjs";import{i as v}from"./database-calls-aAjZJdma.mjs";const A=new Set(["withGeoIndex","withIndex","withSearchIndex"]),S=new Set(["collect","collectWithScores","first","paginate","take","unique"]),w=t=>{const e=t.getExpression();if(!i.isPropertyAccessExpression(e)||e.getName()!=="query")return!1;const n=e.getExpression();return v(n)},y=t=>{const e=[];let n=t;for(;;){const s=n.getParent();if(!s||!i.isPropertyAccessExpression(s))break;const r=s.getParent();if(!r||!i.isCallExpression(r))break;e.push(r),n=r}return e},l=t=>{const e=t.getExpression();return i.isPropertyAccessExpression(e)?e.getName():""},m=t=>{if(t===void 0||!(i.isArrowFunction(t)||i.isFunctionExpression(t)))return;const e=t.getParameters()[0]?.getNameNode();return e!==void 0&&i.isIdentifier(e)?e.getText():void 0},O=t=>{let e=t;for(;i.isCallExpression(e)||i.isPropertyAccessExpression(e);)e=e.getExpression();return e},P=(t,e)=>{const n=new Set,s=[t,...t.getDescendantsOfKind(u.CallExpression)].filter(r=>i.isCallExpression(r));for(const r of s){const c=r.getExpression();if(i.isPropertyAccessExpression(c)){const o=O(c);i.isIdentifier(o)&&o.getText()===e&&n.add(c.getName())}}return n},f=(t,e)=>{if(i.isParenthesizedExpression(t))return f(t.getExpression(),e);if(i.isConditionalExpression(t)){const n=f(t.getWhenFalse(),e);return new Set([...f(t.getWhenTrue(),e)].filter(s=>n.has(s)))}return P(t,e)},C=t=>{if(!(i.isArrowFunction(t)||i.isFunctionExpression(t)))return;const e=t.getBody();if(!i.isBlock(e))return i.isExpression(e)?[e]:void 0;const n=e.getDescendantsOfKind(u.ReturnStatement).filter(s=>s.getFirstAncestor(r=>i.isArrowFunction(r)||i.isFunctionExpression(r))?.compilerNode===t.compilerNode).map(s=>s.getExpression()).filter(s=>s!==void 0);return n.length===0?void 0:n},F=(t,e)=>{const n=C(t);if(n===void 0)return;const[s,...r]=n.map(o=>f(o,e));return[...s??new Set].filter(o=>r.every(d=>d.has(o))).toSorted((o,d)=>o.localeCompare(d))},I=(t,e)=>{const n=new Set;for(const s of t.getDescendantsOfKind(u.PropertyAccessExpression)){const r=s.getExpression();i.isIdentifier(r)&&r.getText()===e&&n.add(s.getName())}for(const s of t.getDescendantsOfKind(u.ElementAccessExpression)){const r=s.getExpression(),c=s.getArgumentExpression();i.isIdentifier(r)&&r.getText()===e&&c!==void 0&&i.isStringLiteral(c)&&n.add(c.getLiteralText())}return[...n]},N=t=>{if(t===void 0)return;const[e,n]=t.getArguments(),s=m(n),r=e!==void 0&&i.isStringLiteral(e)?e.getLiteralText():void 0;return n===void 0?{bounds:[],name:r}:{bounds:s===void 0?void 0:F(n,s),name:r}},T=t=>{const e=t.flatMap(n=>{const s=n.getArguments()[0],r=m(s);return s===void 0||r===void 0?[]:I(s,r)});if(e.length!==0)return[...new Set(e)].toSorted((n,s)=>n.localeCompare(s))},b=/\b[A-Za-z_$][\w$]*\._id\s*===?[^=]/u,D=t=>t.some(e=>l(e)==="filter"&&b.test(e.getArguments()[0]?.getText()??"")),L=t=>{const e=t.getArguments()[0];return e&&i.isStringLiteral(e)?e.getLiteralText():""},k=(t,e,n=[])=>{const s=x(t,e,(r,c)=>{if(!w(r))return;const o=y(r),d=o.map(a=>l(a)),p=o.filter(a=>l(a)==="filter"),g=p.length>0;return{file:c,filterFields:g?T(p):void 0,filtersPrimaryKey:g&&D(o),hasFilter:g,hasIndex:d.some(a=>A.has(a)),index:N(o.find(a=>l(a)==="withIndex")),line:r.getStartLineNumber(),scope:h(r),table:L(r),terminal:d.findLast(a=>S.has(a))}});return E(s,n)};export{k as default};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{d as r}from"./context-property-calls-B75cjwpy.mjs";const t=(s,o)=>r(s,o,"r2sql");export{t as default};
|
package/dist/packem_shared/{discoverRlsProcedures-B0DYk-gW.mjs → discoverRlsProcedures-MboagP9z.mjs}
RENAMED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{Node as o}from"ts-morph";import{listLunoraSourceFiles as c,lunoraRelativePath as f,findObjectProperty as u}from"./isTestPath-JdN4KXhV.mjs";import{b as p,d}from"./attribution-DUbGYT4N.mjs";import{t as m}from"./database-calls-
|
|
1
|
+
import{Node as o}from"ts-morph";import{listLunoraSourceFiles as c,lunoraRelativePath as f,findObjectProperty as u}from"./isTestPath-JdN4KXhV.mjs";import{b as p,d}from"./attribution-DUbGYT4N.mjs";import{t as m}from"./database-calls-aAjZJdma.mjs";import{c as b}from"./classify-procedure-call-DtqiTjPg.mjs";import{r as h}from"./chain-DuEHFGVW.mjs";const g=e=>{const t=e.getArguments()[0];if(!t||!o.isArrayLiteralExpression(t))return[];const r=[];for(const s of t.getElements()){if(!o.isObjectLiteralExpression(s))continue;const i=u(s,"table");if(!i||!o.isPropertyAssignment(i))continue;const n=i.getInitializer();n&&o.isStringLiteral(n)&&r.push(n.getLiteralText())}return r},y=e=>{const t=h(e);return{rlsTables:t.flatMap(r=>g(r)),usesRls:t.length>0}},v=new Set(["explain","findFirst","findFirstOrThrow","findMany","get","query"]),x=new Set(["delete","deleteMany","insert","insertMany","patch","patchIf","patchMany","replace"]),P=(e,t)=>{if(!o.isVariableDeclaration(e))return;const r=e.getInitializer();if(!r||!o.isCallExpression(r))return;const s=b(r);if(!s)return;const i=s.receiver?y(s.receiver):{rlsTables:[],usesRls:!1},{tablesRead:n,tablesWritten:a}=m(e,v,x);return{exportName:d(e)??e.getName(),file:t,rlsTables:i.rlsTables,tablesRead:n,tablesWritten:a,usesRls:i.usesRls,visibility:s.visibility}},M=(e,t)=>{const r=[];for(const s of c(t)){const i=e.getSourceFile(s)??e.addSourceFileAtPath(s),n=f(t,s);for(const a of p(i)){const l=P(a,n);l&&r.push(l)}}return r};export{M as default};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{LunoraError as C}from"@lunora/errors";import{Node as i,SyntaxKind as B}from"ts-morph";import{diagnosticAt as c}from"./CodegenDiagnosticError-BUXlG3P-.mjs";import{findObjectProperty as u,descendantsOfKind as V}from"./isTestPath-JdN4KXhV.mjs";import{createRequire as q}from"node:module";import{join as O}from"node:path";import{fileURLToPath as J}from"node:url";import{createJiti as U}from"jiti";import{r as K,p as W}from"./parse-validator-CP5CL6Q7.mjs";import{R as X}from"./reserved-words-CW1QFbTd.mjs";import{a as w}from"./property-name-7cBlgK_O.mjs";const Z=(e,t)=>`table "${e}" is .global() and declares vector index "${t}". Vector sync runs on the shard write path, which a global (D1/Hyperdrive) table's writes never take — the index would stay empty. Drop .global(), or keep the index yourself with ctx.vectors.upsert/deleteByIds.`,G=e=>{switch(typeof e){case"bigint":return e.toString();case"boolean":case"number":return String(e);case"string":return JSON.stringify(e);default:return e===null?"null":void 0}},H=e=>({...e?.defaultValue!==void 0||e?.defaultFn!==void 0||e?.serverDefault!==void 0?{hasDefault:!0}:{},...e?.onUpdateFn===void 0?{}:{hasOnUpdate:!0},notNull:e?.notNull??!0,...e?.unique===!0?{unique:!0}:{}}),g=e=>{const t=e?._meta??{},n=e?.kind??"unknown",s={column:H(t.column),kind:n};switch(n){case"array":case"optional":{s.inner=g(t.inner);break}case"from":break;case"id":{s.tableName=t.tableName;break}case"literal":{s.literalValue=G(t.value);break}case"object":{const r=t.shape??{};s.shape=Object.fromEntries(Object.entries(r).map(([o,a])=>[o,g(a)]));break}case"record":{s.valueType=g(t.valueValidator),t.keyValidator!==void 0&&(s.keyType=g(t.keyValidator));break}case"storage":{typeof t.bucket=="string"&&(s.bucket=t.bucket);break}case"union":{const r=t.members??[];s.members=r.map(o=>g(o));break}}return s},Q=e=>e?.kind==="global"?"global":e?.kind==="shardBy"&&typeof e.field=="string"?{field:e.field,kind:"shardBy"}:"root",Y=(e,t)=>{const n=[];e.relationMap&&Object.keys(e.relationMap).length>0&&n.push("relations"),e.rankIndexes&&e.rankIndexes.length>0&&n.push("rank indexes"),e.vectorIndexes&&e.vectorIndexes.length>0&&n.push("vector indexes"),n.length>0&&console.warn(`@lunora/codegen: package schema-extension table "${t}" declares ${n.join(" + ")}, which are not yet introspected from a node_modules extension — they will be absent from the generated types.`)},ee=(e,t)=>{const n=e.shape??{},s=(e.indexes??[]).map(r=>({fields:r.fields,name:r.name,...r.unique?{unique:!0}:{}}));return Y(e,t),{...e.isExternallyManaged?{externallyManaged:!0}:{},geoIndexes:[],indexes:s,name:t,rankIndexes:[],relations:[],searchIndexes:(e.searchIndexes??[]).map(r=>({field:r.field,...r.filterFields?{filterFields:r.filterFields}:{},...r.language===void 0?{}:{language:r.language},...r.staged===void 0?{}:{staged:r.staged},...r.strategy===void 0?{}:{strategy:r.strategy},name:r.name})),shape:Object.fromEntries(Object.entries(n).map(([r,o])=>[r,g(o)])),shardMode:Q(e.shardMode),vectorIndexes:[]}},te=e=>{const{key:t,tables:n}=e;if(typeof t!="string"||typeof n!="object"||n===null)return;const s=Object.entries(n).map(([a,l])=>ee(l,a)),r=e.vectorIndexes??{},o=Object.entries(r??{}).map(([a,l])=>({...l.dimensions===void 0?{}:{dimensions:l.dimensions},...l.field===void 0?{}:{field:l.field},...l.metadata===void 0?{}:{metadata:l.metadata},...l.metric===void 0?{}:{metric:l.metric},name:a,table:l.table??""}));return{bareTables:s,bareVectorIndexes:o,key:t}},ne=e=>{if(i.isIdentifier(e))return e.getText();if(i.isPropertyAccessExpression(e)){const t=e.getExpression();return i.isIdentifier(t)?t.getText():void 0}},re=e=>{const t=ne(e);if(t===void 0)return;const n=i.isPropertyAccessExpression(e)?e.getName():void 0,s=n===void 0?[]:[n];for(const r of e.getSourceFile().getImportDeclarations()){const o=r.getModuleSpecifierValue();for(const a of r.getNamedImports())if((a.getAliasNode()?.getText()??a.getName())===t)return{importedName:a.getName(),moduleSpecifier:o,propertyPath:s};if(r.getDefaultImport()?.getText()===t)return{importedName:"default",moduleSpecifier:o,propertyPath:s};if(r.getNamespaceImport()?.getText()===t&&n!==void 0)return{importedName:n,moduleSpecifier:o,propertyPath:[]}}},se=(e,t)=>{let n=e[t.importedName];for(const s of t.propertyPath){if(typeof n!="object"||n===null)return;n=n[s]}return n},ie=(e,t)=>{const n=re(e);if(n)try{const s=U(O(t,"noop.js")).esmResolve(n.moduleSpecifier),r=q(O(t,"noop.cjs"))(s.startsWith("file:")?J(s):s),o=se(r,n);return typeof o!="object"||o===null?void 0:te(o)}catch{return}},oe=new Set(["cosine","dot-product","euclidean"]),b=(e,t)=>{const n=u(e,t);if(n&&i.isPropertyAssignment(n))return n.getInitializer()},f=(e,t)=>{const n=b(e,t);if(n&&i.isStringLiteral(n))return n.getLiteralText()},y=(e,t)=>{const n=b(e,t);if(n&&i.isNumericLiteral(n))return Number(n.getLiteralText())},N=(e,t)=>{const n=b(e,t);if(n&&(i.isTrueLiteral(n)||i.isFalseLiteral(n)))return n.getLiteralValue()},v=(e,t)=>{const n=b(e,t);if(n&&i.isArrayLiteralExpression(n))return n.getElements().filter(s=>i.isStringLiteral(s)).map(s=>s.getLiteralText())},P=e=>e&&oe.has(e)?e:void 0,E=e=>e&&i.isStringLiteral(e)?e.getLiteralText():"_unnamed_",ae=(e,t)=>{const n=v(e,t);return n!==void 0&&n.length>0?n:void 0},j=(e,t,n,s,r)=>{let o=e;for(;;){const a=o.getParent();if(!a||!i.isPropertyAccessExpression(a))break;const l=a.getParent();if(!l||!i.isCallExpression(l))break;if(a.getName()===t){const d=l.getArguments()[0];if(!d||!i.isStringLiteral(d))throw c(l,`\`.${t}(...)\` expects a string literal (${r})`);const m=d.getLiteralText();if(!s.has(m))throw c(d,`unknown ${n} ${JSON.stringify(m)} — expected ${r}`);return m}o=l}},le=e=>`table "${e}" is both .global() and .ttl(). The TTL sweep is a shard's alarm deleting from that shard's own SQLite, and a global (D1/Hyperdrive) table's rows live outside every shard — so expired rows would never be deleted. Drop .ttl() and expire the rows from a cron, or keep the table shard-local.`,ce=/^(?:sqlite_|_cf_|__)/u,de=/__(?:agg|rank|geo|fts)_/u,fe=e=>ce.test(e)||de.test(e),ue=new Set(["cascade","restrict","set null"]),pe=new Set(["aggregate","asId","assertPatchAllowed","cdcChangedTables","count","delete","deleteAll","deleteMany","deleteRereadTables","deleteWhere","explain","findFirst","findFirstOrThrow","findMany","get","groupBy","insert","insertMany","insertManyUnsafe","inTransaction","lookupById","normalizeId","patch","patchIf","patchMany","patchWhere","query","rank","rankBefore","rankPage","rankPageRows","related","relationEdges","relationWrites","replace","restore","softDeleteFields","system","wipeShard"]),$=/^[A-Za-z_$][\w$]*$/u,k=(e,t)=>{if(pe.has(e))throw c(t,`table name "${e}" is reserved — the generated shard binds each table's facade onto the same object that carries \`ctx.db\`'s own members, so this table would overwrite \`ctx.db.${e}\` and every use of it would break. Rename the table.`);if(X.has(e))throw c(t,`table name "${e}" is a reserved JavaScript word — codegen interpolates table names into a bare \`const ${e} = sqliteTable(...)\` binding in the generated Drizzle module, which is a syntax error for a keyword. Rename the table.`);if(!$.test(e))throw c(t,`table name ${JSON.stringify(e)} is not a valid JS identifier — table names are used in generated type names (Doc_<name>) and must match [A-Za-z_$][A-Za-z0-9_$]*. Rename the table.`);if(fe(e))throw c(t,`table name ${JSON.stringify(e)} is reserved for framework tables — a leading \`__\` and the \`__agg_\`/\`__rank_\`/\`__geo_\`/\`__fts_\` infixes name Lunora's own bookkeeping and index companions, so the Studio and the admin API hide and refuse such a table. Rename the table.`)},ge=e=>e&&ue.has(e)?e:void 0,me=e=>{if(!i.isArrowFunction(e))return;let t=e.getBody();if(i.isParenthesizedExpression(t))t=t.getExpression();else if(i.isBlock(t)){const n=t.getStatements().find(s=>i.isReturnStatement(s));t=n&&i.isReturnStatement(n)?n.getExpression()??t:t}return i.isObjectLiteralExpression(t)?t:void 0},he=(e,t,n)=>{const s=i.isPropertyAssignment(e)?e.getInitializer():void 0;if(!s||!i.isObjectLiteralExpression(s))throw c(e,"relation `through` must be an object literal `{ table, from, to }` — codegen resolves it statically.");const[r,o,a]=["table","from","to"].map(l=>f(s,l));if(r===void 0||o===void 0||a===void 0)throw c(s,"relation `through` needs string-literal `table`, `from` and `to` — codegen resolves them statically.");if(o===a)throw c(s,`relation \`through\` has \`from\` and \`to\` both set to "${o}"; a link needs two different columns.`);return{kind:"many",name:t,table:n,through:{from:o,table:r,to:a}}},be=(e,t,n,s)=>{const r=s&&i.isObjectLiteralExpression(s)?s:void 0,o=e==="many"?r?.getProperty("through"):void 0;return o?he(o,t,n):{field:(r&&f(r,"field"))??"_unknown_",kind:e,name:t,onDelete:e==="one"&&r?ge(f(r,"onDelete")):void 0,references:(r&&f(r,"references"))??"_id",table:n}},xe=e=>{if(!i.isPropertyAssignment(e))return;const t=e.getInitializer();if(!t||!i.isCallExpression(t))return;const n=t.getExpression();if(!i.isPropertyAccessExpression(n))return;const s=n.getName();if(s!=="one"&&s!=="many")return;const[r,o]=t.getArguments();if(!r||!i.isStringLiteral(r))throw c(r??t,`relation target table must be a string literal — codegen resolves relation targets statically. Got ${r?r.getText():"no argument"}.`);const a=r.getLiteralText();return be(s,w(e),a,o)},ye=e=>{const t=me(e);if(!t)return[];const n=[];for(const s of t.getProperties()){const r=xe(s);r&&n.push(r)}return n},ve=(e,t,n)=>{if(!t.includes("."))return;const[s="",...r]=t.split("."),o=`${s}${r.map(a=>a.charAt(0).toUpperCase()+a.slice(1)).join("")}`;throw c(e,`index "${n}" indexes the nested path ${JSON.stringify(t)} — Lunora indexes only top-level columns. Denormalise the value into its own column (e.g. \`${o}\`), index that instead, and keep it in sync with a table \`.triggers()\` beforeInsert/beforeUpdate.`,{code:"INDEX_FIELD_NESTED_PATH",name:"LunoraError",status:500})},Ee=e=>{if(!e||!i.isObjectLiteralExpression(e))return!1;const t=u(e,"unique");if(!t||!i.isPropertyAssignment(t))return!1;const n=t.getInitializer();if(n===void 0)return!1;if(!i.isTrueLiteral(n)&&!i.isFalseLiteral(n))throw c(n,`\`unique\` must be a literal \`true\` or \`false\`, got ${JSON.stringify(n.getText())}`);return i.isTrueLiteral(n)},Ie=e=>{const[t,n,s]=e,r=Ee(s),o=E(t),a=n&&i.isArrayLiteralExpression(n)?n.getElements():[];for(const d of a)if(!i.isStringLiteral(d))throw c(d,`index "${o}" lists a non-literal field (${JSON.stringify(d.getText())}); codegen reads index fields statically, so every entry must be a string literal.`);const l=a.filter(d=>i.isStringLiteral(d));for(const d of l)ve(d,d.getLiteralText(),o);return{fields:l.map(d=>d.getLiteralText()),name:o,unique:r}},we=e=>{const[t,n]=e;let s="_unknown_",r,o,a,l;return n&&i.isObjectLiteralExpression(n)&&(s=f(n,"field")??s,r=v(n,"filterFields"),o=f(n,"language"),a=N(n,"staged"),l=f(n,"strategy")),{field:s,filterFields:r,language:o,name:E(t),staged:a,strategy:l}},ke=e=>{const[t,n]=e;let s="_unknown_",r;return n&&i.isObjectLiteralExpression(n)&&(s=f(n,"field")??s,r=y(n,"precision")),{field:s,name:E(t),precision:r}},Se=e=>{const[t,n]=e,s=t&&i.isStringLiteral(t)?t.getLiteralText():"_unknown_";let r;return n&&i.isObjectLiteralExpression(n)&&(r=y(n,"after")),{after:r,field:s}},Te=e=>{if(!i.isObjectLiteralExpression(e))return;const t=f(e,"field");return t===void 0?void 0:{direction:f(e,"direction")==="desc"?"desc":"asc",field:t}},_e=e=>{const[t,n]=e;let s=[],r;if(n&&i.isObjectLiteralExpression(n)){const o=u(n,"sortBy");if(o&&i.isPropertyAssignment(o)){const a=o.getInitializer();a&&i.isArrayLiteralExpression(a)&&(s=a.getElements().map(l=>Te(l)).filter(l=>l!==void 0))}r=v(n,"partitionBy")}return{name:E(t),partitionBy:r,sortBy:s}},Oe=(e,t)=>{const[n,s]=e,r=n&&i.isStringLiteral(n)?n.getLiteralText():"_unknown_";if(!(!s||!i.isObjectLiteralExpression(s)))return{dimensions:y(s,"dimensions"),field:r,metadata:v(s,"metadata"),metric:P(f(s,"metric")),name:f(s,"index")??"_unnamed_",table:t}},Le=e=>{const t=e[0];return t&&i.isObjectLiteralExpression(t)&&f(t,"backend")==="hyperdrive"?"hyperdrive":"d1"},L=(e,t)=>{if(e===void 0)return t;if(!i.isObjectLiteralExpression(e))throw c(e,"the options must be an object literal — codegen reads the column name from the source and cannot evaluate a variable or an expression here.");const n=u(e,"field");if(n===void 0)return t;const s=i.isPropertyAssignment(n)?n.getInitializer():void 0;if(s&&i.isStringLiteral(s))return s.getLiteralText();throw c(n,"`field` must be a string literal — codegen reads the column name from the source and cannot evaluate a constant or an expression here.")},Ae=e=>{const t=e[0];return!t||!i.isObjectLiteralExpression(t)?{binding:"",hasTenantBy:!1,unanalyzable:!0}:{binding:f(t,"binding")??"",columns:ae(t,"columns"),hasReconcile:u(t,"reconcileEveryMs")!==void 0,hasSoftDelete:u(t,"softDeleteColumn")!==void 0,hasTenantBy:u(t,"tenantBy")!==void 0,idColumn:f(t,"idColumn"),mode:f(t,"mode"),query:f(t,"query")}},Ne=(e,t,n,s)=>{switch(t){case"aggregateIndex":{e.aggregateIndexed=!0;break}case"commitOrdered":{e.commitOrdered=!0;break}case"externallyManaged":{e.externallyManaged=!0;break}case"geoIndex":{e.geoIndexes.push(ke(n));break}case"global":{e.shardMode="global",e.globalBackend=Le(n);break}case"index":{e.indexes.unshift(Ie(n));break}case"memory":{e.memory=!0;break}case"public":{e.isPublic=!0;break}case"rankIndex":{e.rankIndexes.push(_e(n));break}case"relations":{const r=n[0];r&&e.relations.push(...ye(r));break}case"searchIndex":{e.searchIndexes.push(we(n));break}case"shardBy":{const r=n[0];e.shardMode={field:r&&i.isStringLiteral(r)?r.getLiteralText():"_unknown_",kind:"shardBy"};break}case"softDelete":{e.softDelete={field:L(n[0],"deletedAt")};break}case"source":{e.externalSource=Ae(n),e.externallyManaged=!0;break}case"timestamps":{e.timestampsFields.push(L(n[0],"updatedAt"));break}case"ttl":{e.ttl=Se(n);break}case"vectorize":{const r=Oe(n,s);r&&e.vectorIndexes.push(r);break}}},A=["__vocab","_config","_content","_data","_docsize","_idx"],Pe=(e,t,n)=>{const s=new Set(n.map(r=>r.name));for(const r of n)for(const o of A){const a=`${r.name}${o}`;if(!s.has(a))continue;const l=o==="__vocab"?`the \`fts5vocab\` companion for "${a}" is created \`IF NOT EXISTS\`, so it silently resolves to "${r.name}"'s — the second index then reads the wrong vocabulary and returns wrong results, with no error`:`creating "${a}" is rejected (\`object name reserved for internal use: SQLITE_ERROR\`), which aborts the shard migration and leaves every sharded table unreadable`;throw c(e,`table "${t}" declares search indexes "${r.name}" and "${a}", whose generated FTS5 tables collide: "${r.name}" already owns "${t}__fts_${a}" as its "${o}" companion, so ${l}. Rename one of them so neither ends with another's name plus ${A.join(", ")}.`)}},je=(e,t,n)=>{if(n.ttl!==void 0&&n.shardMode==="global")throw c(e,le(t))},$e=(e,t,n)=>{const{softDelete:s,timestampsFields:r}=n,o={};s&&!(s.field in t)&&(o[s.field]={inner:{column:{notNull:!1},kind:"number"},kind:"optional"});const[a]=r;if(a===void 0)return{...t,...o};if(r.length>1)throw c(e,"`.timestamps()` was called more than once; one table tracks one last-change column.");if(a===s?.field)throw c(e,`\`.softDelete()\` and \`.timestamps()\` both use "${a}"; give one of them another field.`);const l=t[a];if(l===void 0)o[a]={column:{hasDefault:!0,hasOnUpdate:!0,notNull:!0},kind:"timestamp"};else if(l.kind!=="timestamp"||l.column?.hasOnUpdate!==!0||l.column.hasDefault!==!0)throw c(e,`\`.timestamps()\` would add "${a}", but the table already declares it as something other than \`v.timestamp().defaultNow().$onUpdateFn(() => Date.now())\`; remove the column or declare it that way.`);return{...t,...o}},D=(e,t)=>{const n={aggregateIndexed:!1,commitOrdered:!1,externallyManaged:!1,geoIndexes:[],indexes:[],isPublic:!1,memory:!1,rankIndexes:[],relations:[],searchIndexes:[],shardMode:"root",timestampsFields:[],vectorIndexes:[]};let s={},r=e;for(;i.isCallExpression(r);){const o=r.getExpression(),a=r.getArguments();if(i.isPropertyAccessExpression(o))Ne(n,o.getName(),a,t),r=o.getExpression();else if(i.isIdentifier(o)&&o.getText()==="defineTable"){const l=a[0];if(l&&i.isObjectLiteralExpression(l))s=W(l);else if(l)throw c(l,`table "${t}" calls defineTable(${JSON.stringify(l.getText())}), but codegen reads the field map syntactically and can only read an object literal. Inline the fields into the defineTable(...) call. To reuse them in an \`.input()\`, derive from the generated \`Doc_${t}\` / \`Insert_${t}\` type instead of sharing the runtime value.`);break}else break}return s=$e(e,s,n),Pe(e,t,n.searchIndexes),je(e,t,n),{...n.aggregateIndexed?{aggregateIndexed:!0}:{},commitOrdered:n.commitOrdered,externallyManaged:n.externallyManaged,externalSource:n.externalSource,geoIndexes:n.geoIndexes,globalBackend:n.shardMode==="global"?n.globalBackend??"d1":void 0,indexes:n.indexes,isPublic:n.isPublic,memory:n.memory,name:t,rankIndexes:n.rankIndexes,relations:n.relations,searchIndexes:n.searchIndexes,shape:s,shardMode:n.shardMode,softDelete:n.softDelete,ttl:n.ttl,vectorIndexes:n.vectorIndexes}},z=(e,t=[],n=new Set,s=new Set)=>{s.add(e);for(const r of e.getProperties()){if(i.isSpreadAssignment(r)){const a=K(r.getExpression());a!==void 0&&!s.has(a)&&z(a,t,n,s);continue}if(!i.isPropertyAssignment(r))continue;const o=r.getInitializer();if(o){const a=w(r);if(k(a,r.getNameNode()),n.has(a))throw c(r.getNameNode(),`defineSchema({...}): table "${a}" is declared more than once — the earlier declaration would be silently discarded. Remove the duplicate.`);n.add(a),t.push(D(o,a))}}return t},De=e=>{const t=u(e,"source");if(t&&i.isPropertyAssignment(t)){const n=t.getInitializer();if(n&&i.isObjectLiteralExpression(n))return f(n,"table")??"_unknown_"}return"_unknown_"},ze=e=>{if(!i.isPropertyAssignment(e))return;const t=e.getInitializer();if(!t||!i.isCallExpression(t))return;const n=t.getExpression();if(!i.isIdentifier(n)||n.getText()!=="defineVectorIndex")return;const s=t.getArguments()[0];if(!s||!i.isObjectLiteralExpression(s))return;const r=e.getNameNode(),o=i.isStringLiteral(r)?r.getLiteralText():r.getText();return{dimensions:y(s,"dimensions"),metric:P(f(s,"metric")),name:o,table:De(s)}},F=e=>{const t=[];for(const n of e.getProperties()){const s=ze(n);s&&t.push(s)}return t},S=(e,t)=>`${e}_${t}`,Fe=(e,t)=>{if(!$.test(e))throw c(t,`defineSchemaExtension key ${JSON.stringify(e)} is not a valid JS identifier — it is prefixed onto every table the extension contributes (\`${e}_<table>\`), and table names are used in generated type names (Doc_<name>) and must match [A-Za-z_$][A-Za-z0-9_$]*. Rename the extension key.`)},h=(e,t,n)=>n.has(e)?S(t,e):e,x=(e,t)=>{const n=s=>s===void 0?void 0:x(s,t);return{...e,...e.tableName===void 0?{}:{tableName:t(e.tableName)},...e.inner===void 0?{}:{inner:n(e.inner)},...e.keyType===void 0?{}:{keyType:n(e.keyType)},...e.valueType===void 0?{}:{valueType:n(e.valueType)},...e.members===void 0?{}:{members:e.members.map(s=>x(s,t))},...e.shape===void 0?{}:{shape:Object.fromEntries(Object.entries(e.shape).map(([s,r])=>[s,x(r,t)]))}}},Me=(e,t,n,s)=>{const r=S(t,e.name);return{...e,extensionKey:t,...s?{extensionFromPackage:!0}:{},name:r,shape:Object.fromEntries(Object.entries(e.shape).map(([o,a])=>[o,x(a,l=>h(l,t,n))])),relations:e.relations.map(o=>{const a=h(o.table,t,n);return o.through===void 0?{...o,table:a}:{...o,table:a,through:{...o.through,table:h(o.through.table,t,n)}}}),vectorIndexes:e.vectorIndexes.map(o=>({...o,table:h(o.table,t,n)}))}},Re=e=>{if(i.isVariableDeclaration(e)||i.isPropertyAssignment(e))return e.getInitializer();if(i.isShorthandPropertyAssignment(e))return e.getNameNode()},Ce=e=>{if(!i.isCallExpression(e))return!1;const t=e.getExpression();return i.isIdentifier(t)&&t.getText()==="defineSchemaExtension"},Be=e=>{if(i.isIdentifier(e))return e;if(i.isPropertyAccessExpression(e)){const t=e.getExpression();return i.isIdentifier(t)?t:void 0}},Ve=e=>{if(i.isObjectLiteralExpression(e))return e;if(i.isCallExpression(e)){const t=e.getExpression();let n;if(i.isIdentifier(t)?n=t.getText():i.isPropertyAccessExpression(t)&&(n=t.getName()),n==="definePlugin"){const s=e.getArguments()[1];return s&&i.isObjectLiteralExpression(s)?s:void 0}}},qe=(e,t)=>{const n=Re(e);if(n){if(i.isPropertyAccessExpression(t)){const s=Ve(n);return s?b(s,t.getName()):void 0}return n}},Je=e=>{let t=e,n=0;for(;t&&n<32;){if(n+=1,Ce(t))return t;const s=Be(t),r=s&&i.isIdentifier(s)?s.getSymbol():void 0,a=(r?.getAliasedSymbol()?.getDeclarations()??r?.getDeclarations()??[])[0];if(!a)return;const l=a.getSourceFile();if(l.isInNodeModules()||l.isDeclarationFile())return;t=qe(a,t)}},Ue=e=>{const[t,n]=e.getArguments();if(!(!t||!i.isStringLiteral(t))&&!(!n||!i.isObjectLiteralExpression(n)))return{key:t.getLiteralText(),keyNode:t,options:n}},Ke=e=>{const t=u(e,"tables");if(!t||!i.isPropertyAssignment(t))return[];const n=t.getInitializer();if(!n||!i.isObjectLiteralExpression(n))return[];const s=[];for(const r of n.getProperties()){if(!i.isPropertyAssignment(r))continue;const o=r.getInitializer();if(!o)continue;const a=w(r);k(a,r.getNameNode()),s.push(D(o,a))}return s},We=e=>{const t=u(e,"vectorIndexes");if(!t||!i.isPropertyAssignment(t))return[];const n=t.getInitializer();return!n||!i.isObjectLiteralExpression(n)?[]:F(n)},M=(e,t,n,s,r)=>{Fe(e,s);const o=new Set(t.map(d=>d.name)),a=t.map(d=>Me(d,e,o,r)),l=n.map(d=>({...d,name:S(e,d.name),table:h(d.table,e,o)}));return{tables:a,vectorIndexes:l}},Xe=(e,t,n)=>M(e,Ke(n),We(n),t,t.getSourceFile().getFilePath().includes("/node_modules/")),Ze=(e,t)=>{const n=e.getArguments()[0];if(!n)return;const s=Je(n);if(!s){if(t!==void 0){const o=ie(n,t);if(o){for(const a of o.bareTables)k(a.name,n);return M(o.key,o.bareTables,o.bareVectorIndexes,n,!0)}}console.warn(`@lunora/codegen: skipping \`.extend(${n.getText()})\` — its \`defineSchemaExtension(...)\` could not be resolved from local sources, and ${t===void 0?"no project root was available to resolve the package":"the package could not be imported/introspected"}. Extension tables will be absent from the generated types.`);return}const r=Ue(s);if(!r){console.warn("@lunora/codegen: skipping `.extend(...)` — `defineSchemaExtension` requires a string `key` and an options object literal.");return}return Xe(r.key,r.keyNode,r.options)},Ge=e=>{const t=[];let n=e;for(;;){const s=n.getParent();if(!s||!i.isPropertyAccessExpression(s))break;const r=s.getParent();if(!r||!i.isCallExpression(r))break;s.getName()==="extend"&&t.push(r),n=r}return t},He=(e,t,n)=>{const s=new Set(t.map(o=>o.name)),r=[];for(const o of Ge(e)){const a=Ze(o,n);if(a){for(const l of a.tables){if(s.has(l.name))throw c(o,`defineSchema(...).extend(...): table "${l.name}" already exists — another extension with the same key already contributed it.`);s.add(l.name),t.push(l)}r.push(...a.vectorIndexes)}}return r},Qe=new Set(["eu","fedramp","us"]),Ye=e=>j(e,"jurisdiction","jurisdiction",Qe,'"eu", "us", or "fedramp"'),et=e=>{let t=e;for(;;){const n=t.getParent(),s=n?.getParent();if(!n||!i.isPropertyAccessExpression(n)||!s||!i.isCallExpression(s))return!1;if(n.getName()==="jurisdiction"){const r=s.getArguments()[1];return r!==void 0&&i.isObjectLiteralExpression(r)&&N(r,"pinAuth")===!0}t=s}},tt=new Set(["required"]),nt=e=>j(e,"rls","rls mode",tt,'"required"'),rt=e=>{if(!i.isObjectLiteralExpression(e))return;const t=new Set;for(const n of e.getProperties()){const s=i.isPropertyAssignment(n)?n.getInitializer():void 0;if(!s||!i.isCallExpression(s))return;const r=s.getExpression(),o=s.getArguments()[1],a=o&&i.isObjectLiteralExpression(o)?f(o,"on"):void 0;if(!i.isIdentifier(r)||r.getText()!=="defineAggregateIndex"||a===void 0)return;t.add(a)}return t},st=(e,t)=>{if(t===void 0)return;const n=rt(t);for(const s of e)(n===void 0||n.has(s.name))&&(s.aggregateIndexed=!0)},ht=(e,t,n)=>{const s=e.addSourceFileAtPath(t),r=V(s,B.CallExpression).find(p=>{const _=p.getExpression();return i.isIdentifier(_)&&_.getText()==="defineSchema"});if(!r)throw new C("INTERNAL",`defineSchema() not found in ${t}`);const o=r.getArguments()[0];if(!o||!i.isObjectLiteralExpression(o))throw c(r,"defineSchema() expects an object literal");const a=z(o),l=r.getArguments()[1],d=l&&i.isObjectLiteralExpression(l)?F(l):[],m=He(r,a,n);st(a,r.getArguments()[2]);const T=[...a.flatMap(p=>p.vectorIndexes),...d,...m],R=new Set(a.filter(p=>p.shardMode==="global").map(p=>p.name)),I=T.find(p=>R.has(p.table));if(I)throw c(r,Z(I.table,I.name));return{jurisdiction:Ye(r),...et(r)?{jurisdictionPinsAuth:!0}:{},rlsMode:nt(r),tables:a,vectorIndexes:T}};export{ht as default};
|
|
1
|
+
import{LunoraError as C}from"@lunora/errors";import{Node as i,SyntaxKind as B}from"ts-morph";import{diagnosticAt as c}from"./CodegenDiagnosticError-BUXlG3P-.mjs";import{findObjectProperty as u,descendantsOfKind as V}from"./isTestPath-JdN4KXhV.mjs";import{createRequire as q}from"node:module";import{join as O}from"node:path";import{fileURLToPath as J}from"node:url";import{createJiti as U}from"jiti";import{r as K,p as W}from"./parse-validator-BisfC8bR.mjs";import{R as X}from"./reserved-words-CW1QFbTd.mjs";import{a as w}from"./property-name-7cBlgK_O.mjs";const Z=(e,t)=>`table "${e}" is .global() and declares vector index "${t}". Vector sync runs on the shard write path, which a global (D1/Hyperdrive) table's writes never take — the index would stay empty. Drop .global(), or keep the index yourself with ctx.vectors.upsert/deleteByIds.`,G=e=>{switch(typeof e){case"bigint":return e.toString();case"boolean":case"number":return String(e);case"string":return JSON.stringify(e);default:return e===null?"null":void 0}},H=e=>({...e?.defaultValue!==void 0||e?.defaultFn!==void 0||e?.serverDefault!==void 0?{hasDefault:!0}:{},...e?.onUpdateFn===void 0?{}:{hasOnUpdate:!0},notNull:e?.notNull??!0,...e?.unique===!0?{unique:!0}:{}}),g=e=>{const t=e?._meta??{},n=e?.kind??"unknown",s={column:H(t.column),kind:n};switch(n){case"array":case"optional":{s.inner=g(t.inner);break}case"from":break;case"id":{s.tableName=t.tableName;break}case"literal":{s.literalValue=G(t.value);break}case"object":{const r=t.shape??{};s.shape=Object.fromEntries(Object.entries(r).map(([o,a])=>[o,g(a)]));break}case"record":{s.valueType=g(t.valueValidator),t.keyValidator!==void 0&&(s.keyType=g(t.keyValidator));break}case"storage":{typeof t.bucket=="string"&&(s.bucket=t.bucket);break}case"union":{const r=t.members??[];s.members=r.map(o=>g(o));break}}return s},Q=e=>e?.kind==="global"?"global":e?.kind==="shardBy"&&typeof e.field=="string"?{field:e.field,kind:"shardBy"}:"root",Y=(e,t)=>{const n=[];e.relationMap&&Object.keys(e.relationMap).length>0&&n.push("relations"),e.rankIndexes&&e.rankIndexes.length>0&&n.push("rank indexes"),e.vectorIndexes&&e.vectorIndexes.length>0&&n.push("vector indexes"),n.length>0&&console.warn(`@lunora/codegen: package schema-extension table "${t}" declares ${n.join(" + ")}, which are not yet introspected from a node_modules extension — they will be absent from the generated types.`)},ee=(e,t)=>{const n=e.shape??{},s=(e.indexes??[]).map(r=>({fields:r.fields,name:r.name,...r.unique?{unique:!0}:{}}));return Y(e,t),{...e.isExternallyManaged?{externallyManaged:!0}:{},geoIndexes:[],indexes:s,name:t,rankIndexes:[],relations:[],searchIndexes:(e.searchIndexes??[]).map(r=>({field:r.field,...r.filterFields?{filterFields:r.filterFields}:{},...r.language===void 0?{}:{language:r.language},...r.staged===void 0?{}:{staged:r.staged},...r.strategy===void 0?{}:{strategy:r.strategy},name:r.name})),shape:Object.fromEntries(Object.entries(n).map(([r,o])=>[r,g(o)])),shardMode:Q(e.shardMode),vectorIndexes:[]}},te=e=>{const{key:t,tables:n}=e;if(typeof t!="string"||typeof n!="object"||n===null)return;const s=Object.entries(n).map(([a,l])=>ee(l,a)),r=e.vectorIndexes??{},o=Object.entries(r??{}).map(([a,l])=>({...l.dimensions===void 0?{}:{dimensions:l.dimensions},...l.field===void 0?{}:{field:l.field},...l.metadata===void 0?{}:{metadata:l.metadata},...l.metric===void 0?{}:{metric:l.metric},name:a,table:l.table??""}));return{bareTables:s,bareVectorIndexes:o,key:t}},ne=e=>{if(i.isIdentifier(e))return e.getText();if(i.isPropertyAccessExpression(e)){const t=e.getExpression();return i.isIdentifier(t)?t.getText():void 0}},re=e=>{const t=ne(e);if(t===void 0)return;const n=i.isPropertyAccessExpression(e)?e.getName():void 0,s=n===void 0?[]:[n];for(const r of e.getSourceFile().getImportDeclarations()){const o=r.getModuleSpecifierValue();for(const a of r.getNamedImports())if((a.getAliasNode()?.getText()??a.getName())===t)return{importedName:a.getName(),moduleSpecifier:o,propertyPath:s};if(r.getDefaultImport()?.getText()===t)return{importedName:"default",moduleSpecifier:o,propertyPath:s};if(r.getNamespaceImport()?.getText()===t&&n!==void 0)return{importedName:n,moduleSpecifier:o,propertyPath:[]}}},se=(e,t)=>{let n=e[t.importedName];for(const s of t.propertyPath){if(typeof n!="object"||n===null)return;n=n[s]}return n},ie=(e,t)=>{const n=re(e);if(n)try{const s=U(O(t,"noop.js")).esmResolve(n.moduleSpecifier),r=q(O(t,"noop.cjs"))(s.startsWith("file:")?J(s):s),o=se(r,n);return typeof o!="object"||o===null?void 0:te(o)}catch{return}},oe=new Set(["cosine","dot-product","euclidean"]),b=(e,t)=>{const n=u(e,t);if(n&&i.isPropertyAssignment(n))return n.getInitializer()},f=(e,t)=>{const n=b(e,t);if(n&&i.isStringLiteral(n))return n.getLiteralText()},y=(e,t)=>{const n=b(e,t);if(n&&i.isNumericLiteral(n))return Number(n.getLiteralText())},N=(e,t)=>{const n=b(e,t);if(n&&(i.isTrueLiteral(n)||i.isFalseLiteral(n)))return n.getLiteralValue()},v=(e,t)=>{const n=b(e,t);if(n&&i.isArrayLiteralExpression(n))return n.getElements().filter(s=>i.isStringLiteral(s)).map(s=>s.getLiteralText())},P=e=>e&&oe.has(e)?e:void 0,E=e=>e&&i.isStringLiteral(e)?e.getLiteralText():"_unnamed_",ae=(e,t)=>{const n=v(e,t);return n!==void 0&&n.length>0?n:void 0},j=(e,t,n,s,r)=>{let o=e;for(;;){const a=o.getParent();if(!a||!i.isPropertyAccessExpression(a))break;const l=a.getParent();if(!l||!i.isCallExpression(l))break;if(a.getName()===t){const d=l.getArguments()[0];if(!d||!i.isStringLiteral(d))throw c(l,`\`.${t}(...)\` expects a string literal (${r})`);const m=d.getLiteralText();if(!s.has(m))throw c(d,`unknown ${n} ${JSON.stringify(m)} — expected ${r}`);return m}o=l}},le=e=>`table "${e}" is both .global() and .ttl(). The TTL sweep is a shard's alarm deleting from that shard's own SQLite, and a global (D1/Hyperdrive) table's rows live outside every shard — so expired rows would never be deleted. Drop .ttl() and expire the rows from a cron, or keep the table shard-local.`,ce=/^(?:sqlite_|_cf_|__)/u,de=/__(?:agg|rank|geo|fts)_/u,fe=e=>ce.test(e)||de.test(e),ue=new Set(["cascade","restrict","set null"]),pe=new Set(["aggregate","asId","assertPatchAllowed","cdcChangedTables","count","delete","deleteAll","deleteMany","deleteRereadTables","deleteWhere","explain","findFirst","findFirstOrThrow","findMany","get","groupBy","insert","insertMany","insertManyUnsafe","inTransaction","lookupById","normalizeId","patch","patchIf","patchMany","patchWhere","query","rank","rankBefore","rankPage","rankPageRows","related","relationEdges","relationWrites","replace","restore","softDeleteFields","system","wipeShard"]),$=/^[A-Za-z_$][\w$]*$/u,k=(e,t)=>{if(pe.has(e))throw c(t,`table name "${e}" is reserved — the generated shard binds each table's facade onto the same object that carries \`ctx.db\`'s own members, so this table would overwrite \`ctx.db.${e}\` and every use of it would break. Rename the table.`);if(X.has(e))throw c(t,`table name "${e}" is a reserved JavaScript word — codegen interpolates table names into a bare \`const ${e} = sqliteTable(...)\` binding in the generated Drizzle module, which is a syntax error for a keyword. Rename the table.`);if(!$.test(e))throw c(t,`table name ${JSON.stringify(e)} is not a valid JS identifier — table names are used in generated type names (Doc_<name>) and must match [A-Za-z_$][A-Za-z0-9_$]*. Rename the table.`);if(fe(e))throw c(t,`table name ${JSON.stringify(e)} is reserved for framework tables — a leading \`__\` and the \`__agg_\`/\`__rank_\`/\`__geo_\`/\`__fts_\` infixes name Lunora's own bookkeeping and index companions, so the Studio and the admin API hide and refuse such a table. Rename the table.`)},ge=e=>e&&ue.has(e)?e:void 0,me=e=>{if(!i.isArrowFunction(e))return;let t=e.getBody();if(i.isParenthesizedExpression(t))t=t.getExpression();else if(i.isBlock(t)){const n=t.getStatements().find(s=>i.isReturnStatement(s));t=n&&i.isReturnStatement(n)?n.getExpression()??t:t}return i.isObjectLiteralExpression(t)?t:void 0},he=(e,t,n)=>{const s=i.isPropertyAssignment(e)?e.getInitializer():void 0;if(!s||!i.isObjectLiteralExpression(s))throw c(e,"relation `through` must be an object literal `{ table, from, to }` — codegen resolves it statically.");const[r,o,a]=["table","from","to"].map(l=>f(s,l));if(r===void 0||o===void 0||a===void 0)throw c(s,"relation `through` needs string-literal `table`, `from` and `to` — codegen resolves them statically.");if(o===a)throw c(s,`relation \`through\` has \`from\` and \`to\` both set to "${o}"; a link needs two different columns.`);return{kind:"many",name:t,table:n,through:{from:o,table:r,to:a}}},be=(e,t,n,s)=>{const r=s&&i.isObjectLiteralExpression(s)?s:void 0,o=e==="many"?r?.getProperty("through"):void 0;return o?he(o,t,n):{field:(r&&f(r,"field"))??"_unknown_",kind:e,name:t,onDelete:e==="one"&&r?ge(f(r,"onDelete")):void 0,references:(r&&f(r,"references"))??"_id",table:n}},xe=e=>{if(!i.isPropertyAssignment(e))return;const t=e.getInitializer();if(!t||!i.isCallExpression(t))return;const n=t.getExpression();if(!i.isPropertyAccessExpression(n))return;const s=n.getName();if(s!=="one"&&s!=="many")return;const[r,o]=t.getArguments();if(!r||!i.isStringLiteral(r))throw c(r??t,`relation target table must be a string literal — codegen resolves relation targets statically. Got ${r?r.getText():"no argument"}.`);const a=r.getLiteralText();return be(s,w(e),a,o)},ye=e=>{const t=me(e);if(!t)return[];const n=[];for(const s of t.getProperties()){const r=xe(s);r&&n.push(r)}return n},ve=(e,t,n)=>{if(!t.includes("."))return;const[s="",...r]=t.split("."),o=`${s}${r.map(a=>a.charAt(0).toUpperCase()+a.slice(1)).join("")}`;throw c(e,`index "${n}" indexes the nested path ${JSON.stringify(t)} — Lunora indexes only top-level columns. Denormalise the value into its own column (e.g. \`${o}\`), index that instead, and keep it in sync with a table \`.triggers()\` beforeInsert/beforeUpdate.`,{code:"INDEX_FIELD_NESTED_PATH",name:"LunoraError",status:500})},Ee=e=>{if(!e||!i.isObjectLiteralExpression(e))return!1;const t=u(e,"unique");if(!t||!i.isPropertyAssignment(t))return!1;const n=t.getInitializer();if(n===void 0)return!1;if(!i.isTrueLiteral(n)&&!i.isFalseLiteral(n))throw c(n,`\`unique\` must be a literal \`true\` or \`false\`, got ${JSON.stringify(n.getText())}`);return i.isTrueLiteral(n)},Ie=e=>{const[t,n,s]=e,r=Ee(s),o=E(t),a=n&&i.isArrayLiteralExpression(n)?n.getElements():[];for(const d of a)if(!i.isStringLiteral(d))throw c(d,`index "${o}" lists a non-literal field (${JSON.stringify(d.getText())}); codegen reads index fields statically, so every entry must be a string literal.`);const l=a.filter(d=>i.isStringLiteral(d));for(const d of l)ve(d,d.getLiteralText(),o);return{fields:l.map(d=>d.getLiteralText()),name:o,unique:r}},we=e=>{const[t,n]=e;let s="_unknown_",r,o,a,l;return n&&i.isObjectLiteralExpression(n)&&(s=f(n,"field")??s,r=v(n,"filterFields"),o=f(n,"language"),a=N(n,"staged"),l=f(n,"strategy")),{field:s,filterFields:r,language:o,name:E(t),staged:a,strategy:l}},ke=e=>{const[t,n]=e;let s="_unknown_",r;return n&&i.isObjectLiteralExpression(n)&&(s=f(n,"field")??s,r=y(n,"precision")),{field:s,name:E(t),precision:r}},Se=e=>{const[t,n]=e,s=t&&i.isStringLiteral(t)?t.getLiteralText():"_unknown_";let r;return n&&i.isObjectLiteralExpression(n)&&(r=y(n,"after")),{after:r,field:s}},Te=e=>{if(!i.isObjectLiteralExpression(e))return;const t=f(e,"field");return t===void 0?void 0:{direction:f(e,"direction")==="desc"?"desc":"asc",field:t}},_e=e=>{const[t,n]=e;let s=[],r;if(n&&i.isObjectLiteralExpression(n)){const o=u(n,"sortBy");if(o&&i.isPropertyAssignment(o)){const a=o.getInitializer();a&&i.isArrayLiteralExpression(a)&&(s=a.getElements().map(l=>Te(l)).filter(l=>l!==void 0))}r=v(n,"partitionBy")}return{name:E(t),partitionBy:r,sortBy:s}},Oe=(e,t)=>{const[n,s]=e,r=n&&i.isStringLiteral(n)?n.getLiteralText():"_unknown_";if(!(!s||!i.isObjectLiteralExpression(s)))return{dimensions:y(s,"dimensions"),field:r,metadata:v(s,"metadata"),metric:P(f(s,"metric")),name:f(s,"index")??"_unnamed_",table:t}},Le=e=>{const t=e[0];return t&&i.isObjectLiteralExpression(t)&&f(t,"backend")==="hyperdrive"?"hyperdrive":"d1"},L=(e,t)=>{if(e===void 0)return t;if(!i.isObjectLiteralExpression(e))throw c(e,"the options must be an object literal — codegen reads the column name from the source and cannot evaluate a variable or an expression here.");const n=u(e,"field");if(n===void 0)return t;const s=i.isPropertyAssignment(n)?n.getInitializer():void 0;if(s&&i.isStringLiteral(s))return s.getLiteralText();throw c(n,"`field` must be a string literal — codegen reads the column name from the source and cannot evaluate a constant or an expression here.")},Ae=e=>{const t=e[0];return!t||!i.isObjectLiteralExpression(t)?{binding:"",hasTenantBy:!1,unanalyzable:!0}:{binding:f(t,"binding")??"",columns:ae(t,"columns"),hasReconcile:u(t,"reconcileEveryMs")!==void 0,hasSoftDelete:u(t,"softDeleteColumn")!==void 0,hasTenantBy:u(t,"tenantBy")!==void 0,idColumn:f(t,"idColumn"),mode:f(t,"mode"),query:f(t,"query")}},Ne=(e,t,n,s)=>{switch(t){case"aggregateIndex":{e.aggregateIndexed=!0;break}case"commitOrdered":{e.commitOrdered=!0;break}case"externallyManaged":{e.externallyManaged=!0;break}case"geoIndex":{e.geoIndexes.push(ke(n));break}case"global":{e.shardMode="global",e.globalBackend=Le(n);break}case"index":{e.indexes.unshift(Ie(n));break}case"memory":{e.memory=!0;break}case"public":{e.isPublic=!0;break}case"rankIndex":{e.rankIndexes.push(_e(n));break}case"relations":{const r=n[0];r&&e.relations.push(...ye(r));break}case"searchIndex":{e.searchIndexes.push(we(n));break}case"shardBy":{const r=n[0];e.shardMode={field:r&&i.isStringLiteral(r)?r.getLiteralText():"_unknown_",kind:"shardBy"};break}case"softDelete":{e.softDelete={field:L(n[0],"deletedAt")};break}case"source":{e.externalSource=Ae(n),e.externallyManaged=!0;break}case"timestamps":{e.timestampsFields.push(L(n[0],"updatedAt"));break}case"ttl":{e.ttl=Se(n);break}case"vectorize":{const r=Oe(n,s);r&&e.vectorIndexes.push(r);break}}},A=["__vocab","_config","_content","_data","_docsize","_idx"],Pe=(e,t,n)=>{const s=new Set(n.map(r=>r.name));for(const r of n)for(const o of A){const a=`${r.name}${o}`;if(!s.has(a))continue;const l=o==="__vocab"?`the \`fts5vocab\` companion for "${a}" is created \`IF NOT EXISTS\`, so it silently resolves to "${r.name}"'s — the second index then reads the wrong vocabulary and returns wrong results, with no error`:`creating "${a}" is rejected (\`object name reserved for internal use: SQLITE_ERROR\`), which aborts the shard migration and leaves every sharded table unreadable`;throw c(e,`table "${t}" declares search indexes "${r.name}" and "${a}", whose generated FTS5 tables collide: "${r.name}" already owns "${t}__fts_${a}" as its "${o}" companion, so ${l}. Rename one of them so neither ends with another's name plus ${A.join(", ")}.`)}},je=(e,t,n)=>{if(n.ttl!==void 0&&n.shardMode==="global")throw c(e,le(t))},$e=(e,t,n)=>{const{softDelete:s,timestampsFields:r}=n,o={};s&&!(s.field in t)&&(o[s.field]={inner:{column:{notNull:!1},kind:"number"},kind:"optional"});const[a]=r;if(a===void 0)return{...t,...o};if(r.length>1)throw c(e,"`.timestamps()` was called more than once; one table tracks one last-change column.");if(a===s?.field)throw c(e,`\`.softDelete()\` and \`.timestamps()\` both use "${a}"; give one of them another field.`);const l=t[a];if(l===void 0)o[a]={column:{hasDefault:!0,hasOnUpdate:!0,notNull:!0},kind:"timestamp"};else if(l.kind!=="timestamp"||l.column?.hasOnUpdate!==!0||l.column.hasDefault!==!0)throw c(e,`\`.timestamps()\` would add "${a}", but the table already declares it as something other than \`v.timestamp().defaultNow().$onUpdateFn(() => Date.now())\`; remove the column or declare it that way.`);return{...t,...o}},D=(e,t)=>{const n={aggregateIndexed:!1,commitOrdered:!1,externallyManaged:!1,geoIndexes:[],indexes:[],isPublic:!1,memory:!1,rankIndexes:[],relations:[],searchIndexes:[],shardMode:"root",timestampsFields:[],vectorIndexes:[]};let s={},r=e;for(;i.isCallExpression(r);){const o=r.getExpression(),a=r.getArguments();if(i.isPropertyAccessExpression(o))Ne(n,o.getName(),a,t),r=o.getExpression();else if(i.isIdentifier(o)&&o.getText()==="defineTable"){const l=a[0];if(l&&i.isObjectLiteralExpression(l))s=W(l);else if(l)throw c(l,`table "${t}" calls defineTable(${JSON.stringify(l.getText())}), but codegen reads the field map syntactically and can only read an object literal. Inline the fields into the defineTable(...) call. To reuse them in an \`.input()\`, derive from the generated \`Doc_${t}\` / \`Insert_${t}\` type instead of sharing the runtime value.`);break}else break}return s=$e(e,s,n),Pe(e,t,n.searchIndexes),je(e,t,n),{...n.aggregateIndexed?{aggregateIndexed:!0}:{},commitOrdered:n.commitOrdered,externallyManaged:n.externallyManaged,externalSource:n.externalSource,geoIndexes:n.geoIndexes,globalBackend:n.shardMode==="global"?n.globalBackend??"d1":void 0,indexes:n.indexes,isPublic:n.isPublic,memory:n.memory,name:t,rankIndexes:n.rankIndexes,relations:n.relations,searchIndexes:n.searchIndexes,shape:s,shardMode:n.shardMode,softDelete:n.softDelete,ttl:n.ttl,vectorIndexes:n.vectorIndexes}},z=(e,t=[],n=new Set,s=new Set)=>{s.add(e);for(const r of e.getProperties()){if(i.isSpreadAssignment(r)){const a=K(r.getExpression());a!==void 0&&!s.has(a)&&z(a,t,n,s);continue}if(!i.isPropertyAssignment(r))continue;const o=r.getInitializer();if(o){const a=w(r);if(k(a,r.getNameNode()),n.has(a))throw c(r.getNameNode(),`defineSchema({...}): table "${a}" is declared more than once — the earlier declaration would be silently discarded. Remove the duplicate.`);n.add(a),t.push(D(o,a))}}return t},De=e=>{const t=u(e,"source");if(t&&i.isPropertyAssignment(t)){const n=t.getInitializer();if(n&&i.isObjectLiteralExpression(n))return f(n,"table")??"_unknown_"}return"_unknown_"},ze=e=>{if(!i.isPropertyAssignment(e))return;const t=e.getInitializer();if(!t||!i.isCallExpression(t))return;const n=t.getExpression();if(!i.isIdentifier(n)||n.getText()!=="defineVectorIndex")return;const s=t.getArguments()[0];if(!s||!i.isObjectLiteralExpression(s))return;const r=e.getNameNode(),o=i.isStringLiteral(r)?r.getLiteralText():r.getText();return{dimensions:y(s,"dimensions"),metric:P(f(s,"metric")),name:o,table:De(s)}},F=e=>{const t=[];for(const n of e.getProperties()){const s=ze(n);s&&t.push(s)}return t},S=(e,t)=>`${e}_${t}`,Fe=(e,t)=>{if(!$.test(e))throw c(t,`defineSchemaExtension key ${JSON.stringify(e)} is not a valid JS identifier — it is prefixed onto every table the extension contributes (\`${e}_<table>\`), and table names are used in generated type names (Doc_<name>) and must match [A-Za-z_$][A-Za-z0-9_$]*. Rename the extension key.`)},h=(e,t,n)=>n.has(e)?S(t,e):e,x=(e,t)=>{const n=s=>s===void 0?void 0:x(s,t);return{...e,...e.tableName===void 0?{}:{tableName:t(e.tableName)},...e.inner===void 0?{}:{inner:n(e.inner)},...e.keyType===void 0?{}:{keyType:n(e.keyType)},...e.valueType===void 0?{}:{valueType:n(e.valueType)},...e.members===void 0?{}:{members:e.members.map(s=>x(s,t))},...e.shape===void 0?{}:{shape:Object.fromEntries(Object.entries(e.shape).map(([s,r])=>[s,x(r,t)]))}}},Me=(e,t,n,s)=>{const r=S(t,e.name);return{...e,extensionKey:t,...s?{extensionFromPackage:!0}:{},name:r,shape:Object.fromEntries(Object.entries(e.shape).map(([o,a])=>[o,x(a,l=>h(l,t,n))])),relations:e.relations.map(o=>{const a=h(o.table,t,n);return o.through===void 0?{...o,table:a}:{...o,table:a,through:{...o.through,table:h(o.through.table,t,n)}}}),vectorIndexes:e.vectorIndexes.map(o=>({...o,table:h(o.table,t,n)}))}},Re=e=>{if(i.isVariableDeclaration(e)||i.isPropertyAssignment(e))return e.getInitializer();if(i.isShorthandPropertyAssignment(e))return e.getNameNode()},Ce=e=>{if(!i.isCallExpression(e))return!1;const t=e.getExpression();return i.isIdentifier(t)&&t.getText()==="defineSchemaExtension"},Be=e=>{if(i.isIdentifier(e))return e;if(i.isPropertyAccessExpression(e)){const t=e.getExpression();return i.isIdentifier(t)?t:void 0}},Ve=e=>{if(i.isObjectLiteralExpression(e))return e;if(i.isCallExpression(e)){const t=e.getExpression();let n;if(i.isIdentifier(t)?n=t.getText():i.isPropertyAccessExpression(t)&&(n=t.getName()),n==="definePlugin"){const s=e.getArguments()[1];return s&&i.isObjectLiteralExpression(s)?s:void 0}}},qe=(e,t)=>{const n=Re(e);if(n){if(i.isPropertyAccessExpression(t)){const s=Ve(n);return s?b(s,t.getName()):void 0}return n}},Je=e=>{let t=e,n=0;for(;t&&n<32;){if(n+=1,Ce(t))return t;const s=Be(t),r=s&&i.isIdentifier(s)?s.getSymbol():void 0,a=(r?.getAliasedSymbol()?.getDeclarations()??r?.getDeclarations()??[])[0];if(!a)return;const l=a.getSourceFile();if(l.isInNodeModules()||l.isDeclarationFile())return;t=qe(a,t)}},Ue=e=>{const[t,n]=e.getArguments();if(!(!t||!i.isStringLiteral(t))&&!(!n||!i.isObjectLiteralExpression(n)))return{key:t.getLiteralText(),keyNode:t,options:n}},Ke=e=>{const t=u(e,"tables");if(!t||!i.isPropertyAssignment(t))return[];const n=t.getInitializer();if(!n||!i.isObjectLiteralExpression(n))return[];const s=[];for(const r of n.getProperties()){if(!i.isPropertyAssignment(r))continue;const o=r.getInitializer();if(!o)continue;const a=w(r);k(a,r.getNameNode()),s.push(D(o,a))}return s},We=e=>{const t=u(e,"vectorIndexes");if(!t||!i.isPropertyAssignment(t))return[];const n=t.getInitializer();return!n||!i.isObjectLiteralExpression(n)?[]:F(n)},M=(e,t,n,s,r)=>{Fe(e,s);const o=new Set(t.map(d=>d.name)),a=t.map(d=>Me(d,e,o,r)),l=n.map(d=>({...d,name:S(e,d.name),table:h(d.table,e,o)}));return{tables:a,vectorIndexes:l}},Xe=(e,t,n)=>M(e,Ke(n),We(n),t,t.getSourceFile().getFilePath().includes("/node_modules/")),Ze=(e,t)=>{const n=e.getArguments()[0];if(!n)return;const s=Je(n);if(!s){if(t!==void 0){const o=ie(n,t);if(o){for(const a of o.bareTables)k(a.name,n);return M(o.key,o.bareTables,o.bareVectorIndexes,n,!0)}}console.warn(`@lunora/codegen: skipping \`.extend(${n.getText()})\` — its \`defineSchemaExtension(...)\` could not be resolved from local sources, and ${t===void 0?"no project root was available to resolve the package":"the package could not be imported/introspected"}. Extension tables will be absent from the generated types.`);return}const r=Ue(s);if(!r){console.warn("@lunora/codegen: skipping `.extend(...)` — `defineSchemaExtension` requires a string `key` and an options object literal.");return}return Xe(r.key,r.keyNode,r.options)},Ge=e=>{const t=[];let n=e;for(;;){const s=n.getParent();if(!s||!i.isPropertyAccessExpression(s))break;const r=s.getParent();if(!r||!i.isCallExpression(r))break;s.getName()==="extend"&&t.push(r),n=r}return t},He=(e,t,n)=>{const s=new Set(t.map(o=>o.name)),r=[];for(const o of Ge(e)){const a=Ze(o,n);if(a){for(const l of a.tables){if(s.has(l.name))throw c(o,`defineSchema(...).extend(...): table "${l.name}" already exists — another extension with the same key already contributed it.`);s.add(l.name),t.push(l)}r.push(...a.vectorIndexes)}}return r},Qe=new Set(["eu","fedramp","us"]),Ye=e=>j(e,"jurisdiction","jurisdiction",Qe,'"eu", "us", or "fedramp"'),et=e=>{let t=e;for(;;){const n=t.getParent(),s=n?.getParent();if(!n||!i.isPropertyAccessExpression(n)||!s||!i.isCallExpression(s))return!1;if(n.getName()==="jurisdiction"){const r=s.getArguments()[1];return r!==void 0&&i.isObjectLiteralExpression(r)&&N(r,"pinAuth")===!0}t=s}},tt=new Set(["required"]),nt=e=>j(e,"rls","rls mode",tt,'"required"'),rt=e=>{if(!i.isObjectLiteralExpression(e))return;const t=new Set;for(const n of e.getProperties()){const s=i.isPropertyAssignment(n)?n.getInitializer():void 0;if(!s||!i.isCallExpression(s))return;const r=s.getExpression(),o=s.getArguments()[1],a=o&&i.isObjectLiteralExpression(o)?f(o,"on"):void 0;if(!i.isIdentifier(r)||r.getText()!=="defineAggregateIndex"||a===void 0)return;t.add(a)}return t},st=(e,t)=>{if(t===void 0)return;const n=rt(t);for(const s of e)(n===void 0||n.has(s.name))&&(s.aggregateIndexed=!0)},ht=(e,t,n)=>{const s=e.addSourceFileAtPath(t),r=V(s,B.CallExpression).find(p=>{const _=p.getExpression();return i.isIdentifier(_)&&_.getText()==="defineSchema"});if(!r)throw new C("INTERNAL",`defineSchema() not found in ${t}`);const o=r.getArguments()[0];if(!o||!i.isObjectLiteralExpression(o))throw c(r,"defineSchema() expects an object literal");const a=z(o),l=r.getArguments()[1],d=l&&i.isObjectLiteralExpression(l)?F(l):[],m=He(r,a,n);st(a,r.getArguments()[2]);const T=[...a.flatMap(p=>p.vectorIndexes),...d,...m],R=new Set(a.filter(p=>p.shardMode==="global").map(p=>p.name)),I=T.find(p=>R.has(p.table));if(I)throw c(r,Z(I.table,I.name));return{jurisdiction:Ye(r),...et(r)?{jurisdictionPinsAuth:!0}:{},rlsMode:nt(r),tables:a,vectorIndexes:T}};export{ht as default};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import"./json-data-Chfs2Cz5.mjs";import{p as i,j as r,t as n,h as o,u as g,k as F,d as u,x as p,n as l,g as f,f as d,m as k,i as w,v as W,l as v,w as A}from"./shard-runtime-
|
|
1
|
+
import"./json-data-Chfs2Cz5.mjs";import{p as i,j as r,t as n,h as o,u as g,k as F,d as u,x as p,n as l,g as f,f as d,m as k,i as w,v as W,l as v,w as A}from"./shard-runtime-lkQU8trx.mjs";import"./shared-A1XHcT4t.mjs";import"./platform-8oj7iXQy.mjs";export{i as buildDoTypeImports,r as emitAgentFragments,n as emitAgents,o as emitContainerFragments,g as emitContainers,F as emitPaymentFragments,u as emitQueueFragments,p as emitQueues,l as emitQueuesMetadataFragments,f as emitServiceFragments,d as emitTopicFragments,k as emitWorkflowEventFragments,w as emitWorkflowFragments,W as emitWorkflows,v as emitWorkflowsMetadataFragments,A as queueAliasFindings};
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{AGENT_RUNTIME_FUNCTIONS as N}from"@lunora/agent/naming";import{LunoraError as R}from"@lunora/errors";import{r as d,a as w,b as P,c as L}from"./qualifiers-
|
|
1
|
+
import{AGENT_RUNTIME_FUNCTIONS as N}from"@lunora/agent/naming";import{LunoraError as R}from"@lunora/errors";import{r as d,a as w,b as P,c as L}from"./qualifiers-D1Q_3wo2.mjs";import{a as A,r as y,p as $,G as x,b as k,c as m,d as S,e as O,i as T}from"./shared-A1XHcT4t.mjs";import{s as g}from"./dispatch-namespace-DwTjD7BU.mjs";const j=t=>k(t,e=>{const s=d(y(e.args),e.filePath),n=d(L(e),e.filePath),o=`FunctionReference<"${e.kind}", ${s}, ${n}>`;return`${e.exportName}: ${T(e)?`${o} & { readonly sensitive: true }`:o};`},"type"),I=(t,e)=>{if(t.length===0&&e.length===0)return{block:"",importLine:""};const s=[];let n="";if(t.length>0&&(n+="\n/** Params type carried by a `defineWorkflow` definition (its phantom `__params`). */\ntype WorkflowParamsOf<Definition> = Definition extends { __params?: infer Params } ? (unknown extends Params ? Record<string, unknown> : Params) : Record<string, unknown>;\n"),n+=`
|
|
2
2
|
/** A typed reference to a durable workflow, addressable for \`cronJobs()\` targets. Mirrors \`@lunora/scheduler\`'s \`WorkflowReference\` structurally. */
|
|
3
3
|
export interface WorkflowReference<Params = Record<string, unknown>> {
|
|
4
4
|
readonly isLunoraWorkflow: true;
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{APP_METHOD_CAPABILITIES as q}from"./CAPABILITY_PROBES-DKYJ2K4t.mjs";import{i as I}from"./schema-BgM8A3XV.mjs";import{a as N,I as L,G as y}from"./shared-
|
|
1
|
+
import{APP_METHOD_CAPABILITIES as q}from"./CAPABILITY_PROBES-DKYJ2K4t.mjs";import{i as I}from"./schema-BgM8A3XV.mjs";import{a as N,I as L,G as y}from"./shared-A1XHcT4t.mjs";const j={configKey:"vectors",doc:"Wire the Vectorize index map backing `ctx.vectors`.",method:"vectors"},f=e=>[...q.filter(({key:r})=>e.capabilities.has(r)).map(({appMethod:r})=>r),...e.hasVectors?[j]:[]],w=e=>f(e).length>0,k=e=>(e.emailAgents?.length??0)>0,c=e=>e.tables.some(r=>I(r)),p=e=>e.liveStreams===!0&&(e.liveStreamDeclarations?.length??0)>0,$=e=>e.hasScheduler?`
|
|
2
2
|
/** Resolve the \`SchedulerDO\`-backed scheduler for this env; \`undefined\` until the namespace is wired. */
|
|
3
3
|
private resolveScheduler(env: Env): ReturnType<typeof createScheduler> | undefined {
|
|
4
4
|
const namespace = this.schedulerDeclaration?.namespace(env);
|
|
@@ -250,11 +250,12 @@ const buildGlobalIntrospector = (database: D1DatabaseLike): GlobalIntrospector =
|
|
|
250
250
|
* \`startLine\` plus positional counting would mis-attribute every row after
|
|
251
251
|
* the first gap. \`importGlobalRows\` prefers \`row.line\` when present and
|
|
252
252
|
* falls back to the position-derived count otherwise. A dry run is passed through and writes nothing;
|
|
253
|
-
* \`onConflict: "replace"\` overwrites a row whose \`_id\` already exists instead of reporting a conflict
|
|
253
|
+
* \`onConflict: "replace"\` overwrites a row whose \`_id\` already exists instead of reporting a conflict, and a row's
|
|
254
|
+
* \`op: "delete"\` removes the stored row it names.
|
|
254
255
|
*/
|
|
255
256
|
const buildGlobalImporter =
|
|
256
257
|
(database: D1DatabaseLike, cdc: boolean) =>
|
|
257
|
-
(request: { dryRun?: boolean; onConflict?: "replace" | "skip"; rows: ReadonlyArray<{ doc: Record<string, unknown>; line: number; table: string }>; startLine?: number }) => {
|
|
258
|
+
(request: { dryRun?: boolean; onConflict?: "replace" | "skip"; rows: ReadonlyArray<{ doc: Record<string, unknown>; line: number; op?: "delete"; table: string }>; startLine?: number }) => {
|
|
258
259
|
const exec = buildExec(database);
|
|
259
260
|
// Same reason the PITR applier carries it: a bulk import that skips the
|
|
260
261
|
// changelog restores rows no downstream consumer is ever told about.
|
|
@@ -264,7 +265,7 @@ const buildGlobalImporter =
|
|
|
264
265
|
dryRun: request.dryRun === true,
|
|
265
266
|
exec,
|
|
266
267
|
onConflict: request.onConflict ?? "skip",
|
|
267
|
-
rows: request.rows.map((row) => ({ doc: row.doc, line: row.line, table: row.table })),
|
|
268
|
+
rows: request.rows.map((row) => ({ doc: row.doc, line: row.line, ...(row.op === undefined ? {} : { op: row.op }), table: row.table })),
|
|
268
269
|
...(request.startLine === undefined ? {} : { startLine: request.startLine }),
|
|
269
270
|
});
|
|
270
271
|
};
|
|
@@ -553,10 +554,12 @@ ${S(e).join(`
|
|
|
553
554
|
// plane: the rows \`resolveTableSharding\` classifies as \`.global()\`
|
|
554
555
|
// land here, and without it they are reported, not written.
|
|
555
556
|
options.importGlobals = buildGlobalImporter(database, this.cdcEnabled);
|
|
556
|
-
// The importer above skips the write for a dry run,
|
|
557
|
-
//
|
|
557
|
+
// The importer above skips the write for a dry run, overwrites an
|
|
558
|
+
// existing \`_id\` under \`onConflict: "replace"\`, and removes the row
|
|
559
|
+
// an \`op: "delete"\` row names.
|
|
558
560
|
options.importGlobalsSupportsDryRun = true;
|
|
559
561
|
options.importGlobalsSupportsReplace = true;
|
|
562
|
+
options.importGlobalsSupportsDelete = true;
|
|
560
563
|
// The read/replay half of the same admin plane. Each one is the
|
|
561
564
|
// only reason its endpoint can see the global storage plane at
|
|
562
565
|
// all, and every one of them fails SILENTLY when unset — export
|
|
@@ -595,6 +598,7 @@ ${S(e).join(`
|
|
|
595
598
|
});
|
|
596
599
|
options.importGlobalsSupportsDryRun = true;
|
|
597
600
|
options.importGlobalsSupportsReplace = true;
|
|
601
|
+
options.importGlobalsSupportsDelete = true;
|
|
598
602
|
options.exportGlobals = (request) => exportHyperdriveGlobalRows({ engine, exec: exec(), schema: hyperdriveSchema, tables: request.tables });
|
|
599
603
|
options.syncGlobals = async (request) => {
|
|
600
604
|
const page = await readHyperdriveGlobalCdc(engine, exec(), request);
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{G as a,d as c}from"./shared-
|
|
1
|
+
import{G as a,d as c}from"./shared-A1XHcT4t.mjs";import{i as y}from"./schema-BgM8A3XV.mjs";const f=s=>s?`${a}/**
|
|
2
2
|
* The \`SchedulerDO\` Durable Object class, re-exported so a worker entry can
|
|
3
3
|
* forward it — wrangler binds only what the entry exports:
|
|
4
4
|
*
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{r as k}from"./qualifiers-
|
|
1
|
+
import{r as k}from"./qualifiers-D1Q_3wo2.mjs";import{a as i,e as o,v as d,f as v,G as M}from"./shared-A1XHcT4t.mjs";const _="schema",w=a=>{for(const e of a.tables)i(e.name,"table name");const l=a.tables.map(e=>`"${e.name}"`).join(" | ")||"never",m=a.tables.filter(e=>e.extensionKey===void 0).map(e=>`"${e.name}"`).join(" | ")||"never",p=a.tables.map(e=>{const t=Object.entries(e.shape).map(([g,r])=>{const s=o(g);if(r.kind==="optional"){const h=r.inner?d(r.inner):"unknown";return` ${s}?: ${h};`}return` ${s}: ${d(r)};`}).join(`
|
|
2
2
|
`),n=t?`
|
|
3
3
|
${t}
|
|
4
4
|
`:"",N=e.commitOrdered===!0?`
|
package/dist/packem_shared/{emitDrizzleSchema-BmCxM6tO.mjs → emitDrizzleSchema-CM9jh_F0.mjs}
RENAMED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{SCHEMA_MODULE_PATH as c}from"./emitDataModel-
|
|
1
|
+
import{SCHEMA_MODULE_PATH as c}from"./emitDataModel-LTnwnhV6.mjs";import{r as m}from"./qualifiers-D1Q_3wo2.mjs";import{G as b,a as z,d as T,v as f,u as A,g as x,c as h}from"./shared-A1XHcT4t.mjs";const d=e=>{switch(e.kind){case"array":case"object":case"record":case"union":return{builder:"text",mode:"json",notNull:!0,typeAnnotation:f(e)};case"bigint":return{builder:"blob",mode:"bigint",notNull:!0};case"boolean":return{builder:"integer",mode:"boolean",notNull:!0};case"bytes":return{builder:"blob",mode:"buffer",notNull:!0};case"date":case"timestamp":return{builder:"integer",notNull:!0};case"from":return{builder:"text",notNull:!0,typeAnnotation:f(e)};case"id":return{builder:"text",notNull:!0};case"literal":{const t=e.literalValue??"";return t.startsWith('"')||t.startsWith("'")?{builder:"text",notNull:!0}:t==="true"||t==="false"?{builder:"integer",mode:"boolean",notNull:!0}:t==="null"?{builder:"text",notNull:!0}:{builder:"real",notNull:!0}}case"null":return{builder:"text",notNull:!0};case"number":return{builder:"real",notNull:!0};case"optional":return{...e.inner?d(e.inner):{builder:"text",notNull:!1},notNull:!1};case"storage":case"string":return{builder:"text",notNull:!0};default:return{builder:"text",notNull:!0}}},N=(e,t)=>{const r=A(e);return r.kind==="id"&&r.tableName!==void 0&&t.has(r.tableName)?r.tableName:void 0},j=(e,t,r)=>{x(e,"drizzle column name");const n=d(t),o=n.mode?`, { mode: "${n.mode}" }`:"";let l=`${n.builder}("${e}"${o})`;n.typeAnnotation&&(l+=`.$type<${n.typeAnnotation}>()`);const s=N(t,r);return s!==void 0&&(l+=`.references((): AnySQLiteColumn => ${s}._id)`),n.notNull&&t.column?.notNull!==!1&&(l+=".notNull()"),l},I=e=>{const t=e.unique?"uniqueIndex":"index",r=e.fields.map(n=>(x(n,"drizzle index field"),`t.${n}`)).join(", ");return` ${h(e.name)}: ${t}(${JSON.stringify(e.name)}).on(${r}),`},S=(e,t)=>{z(e.name,"table name");const r=[' _id: text("_id").primaryKey(),',' _creationTime: integer("_creationTime").notNull(),',...Object.entries(e.shape).map(([o,l])=>` ${o}: ${j(o,l,t)},`)].join(`
|
|
2
2
|
`),n=e.indexes.length>0?`, (t) => ({
|
|
3
3
|
${e.indexes.map(o=>I(o)).join(`
|
|
4
4
|
`)}
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{LunoraError as A}from"@lunora/errors";import{L as de,s as j,G as D,d as U,I as T,b as M,r as he,c as me}from"./shared-
|
|
1
|
+
import{LunoraError as A}from"@lunora/errors";import{L as de,s as j,G as D,d as U,I as T,b as M,r as he,c as me}from"./shared-A1XHcT4t.mjs";import{v as pe}from"./parse-validator-BisfC8bR.mjs";import{renderAgentFunctionRegistry as ge,renderSandboxFunctionRegistry as fe}from"./emitApi-GFmStqmq.mjs";import{b as ye,a as $e,r as I,c as we}from"./qualifiers-D1Q_3wo2.mjs";import{s as g}from"./dispatch-namespace-DwTjD7BU.mjs";const ke=new Set(["any","bigint","boolean","date","id","null","number","storage","string","timestamp"]),J=r=>r.column!==void 0,Re=(r,t)=>{switch(r){case"bigint":return`if (typeof ${t} !== "bigint") return DEFER;
|
|
2
2
|
`;case"boolean":return`if (typeof ${t} !== "boolean") return DEFER;
|
|
3
3
|
`;case"date":case"number":case"timestamp":return`if (typeof ${t} !== "number" || !Number.isFinite(${t})) return DEFER;
|
|
4
4
|
`;case"null":return`if (${t} !== null) return DEFER;
|