@lunora/shard-engine 1.0.0-alpha.181 → 1.0.0-alpha.182

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.
Files changed (36) hide show
  1. package/dist/conformance/index.mjs +1 -1
  2. package/dist/index.d.mts +49 -5
  3. package/dist/index.d.ts +49 -5
  4. package/dist/index.mjs +1 -1
  5. package/dist/packem_shared/ADMIN_FUNCTIONS-BMBnudzO.mjs +1 -0
  6. package/dist/packem_shared/AGG_COUNT-dVi3FAjZ.mjs +1 -0
  7. package/dist/packem_shared/{CDC_LOG_TABLE-CTkXVeJx.mjs → CDC_LOG_TABLE-BFGgqai8.mjs} +1 -1
  8. package/dist/packem_shared/{DEFAULT_MAX_RELATION_KEYS-DQkJExDV.mjs → DEFAULT_MAX_RELATION_KEYS-DfrMi_eE.mjs} +1 -1
  9. package/dist/packem_shared/DEFAULT_TRANSACTION_LIMITS-D7p7Ys0M.mjs +1 -0
  10. package/dist/packem_shared/NotUniqueError-CO-HgL4c.mjs +1 -0
  11. package/dist/packem_shared/{ReactiveCache-Cy7oH_7w.mjs → ReactiveCache-5XPk8qfW.mjs} +1 -1
  12. package/dist/packem_shared/SCHEDULE_OUTBOX_TABLE-iyyiSjsO.mjs +18 -0
  13. package/dist/packem_shared/{VECTOR_BACKFILL_MAX_PAGES-UY0toTIR.mjs → VECTOR_BACKFILL_MAX_PAGES-DcQpf83n.mjs} +1 -1
  14. package/dist/packem_shared/{applyInsertDefaults-BJo578fn.mjs → applyInsertDefaults-CVukTkQ5.mjs} +1 -1
  15. package/dist/packem_shared/{backfillAggregateIndexes-CRNxxM19.mjs → backfillAggregateIndexes-Pk0KLrfk.mjs} +1 -1
  16. package/dist/packem_shared/{buildReprojectionMigration-DAh1inpL.mjs → buildReprojectionMigration-B8aEpETD.mjs} +1 -1
  17. package/dist/packem_shared/{buildShapeDiff-CCpH5fNc.mjs → buildShapeDiff-CdLJTijm.mjs} +1 -1
  18. package/dist/packem_shared/createCompanionSync-CEht4hXX.mjs +1 -0
  19. package/dist/packem_shared/{createReplicaLink-D0YNQDzD.mjs → createReplicaLink-DVXW9rR6.mjs} +1 -1
  20. package/dist/packem_shared/{defineEngineContractSuite-DKON0Z5G.mjs → defineEngineContractSuite-C4w7jbyk.mjs} +1 -1
  21. package/dist/packem_shared/do-sql-105TONaE.mjs +1 -0
  22. package/dist/packem_shared/estimate-bytes-C-C35VXL.mjs +1 -0
  23. package/dist/packem_shared/{isSoftDeleted-QCy5JKnY.mjs → isSoftDeleted-BBWKE0Sm.mjs} +1 -1
  24. package/dist/packem_shared/{isTtlExpired-BmiUp7MF.mjs → isTtlExpired-DNxmZA6e.mjs} +1 -1
  25. package/dist/packem_shared/{materializeExternalRows-BakYlgvb.mjs → materializeExternalRows-CHPRx8fu.mjs} +1 -1
  26. package/dist/packem_shared/{runShardMigrations-DOiPunti.mjs → runShardMigrations-xu993yo2.mjs} +1 -1
  27. package/dist/packem_shared/{selectShapeMembers-BhK79123.mjs → selectShapeMembers-Dqx_m7BF.mjs} +1 -1
  28. package/package.json +2 -2
  29. package/dist/packem_shared/ADMIN_FUNCTIONS-CgMPqUvK.mjs +0 -1
  30. package/dist/packem_shared/AGG_COUNT-BkqKHbcG.mjs +0 -1
  31. package/dist/packem_shared/DEFAULT_TRANSACTION_LIMITS-Dmj5VBrV.mjs +0 -1
  32. package/dist/packem_shared/NotUniqueError-Dn6Cj7W1.mjs +0 -1
  33. package/dist/packem_shared/SCHEDULE_OUTBOX_TABLE-DcZI7Yhl.mjs +0 -11
  34. package/dist/packem_shared/createCompanionSync-qhvw6wyL.mjs +0 -1
  35. package/dist/packem_shared/do-sql-RROYQPCM.mjs +0 -1
  36. package/dist/packem_shared/estimate-bytes-_k74s6LZ.mjs +0 -1
@@ -1 +1 @@
1
- import{LunoraError as h}from"@lunora/errors";import{i as S,R as L}from"./relation-operators-BEg-CvCH.mjs";import{mergeWhere as w}from"./CountRlsUnsupportedError-BvsDqfO2.mjs";import{isMemoryTable as R}from"./clearMemoryTables-aMRERF0w.mjs";import{normalizeOrderKeys as j,uniqueIndexFields as M,equalityPinnedFields as P,buildSeekWhere as k,decodeCursor as I,softDeleteScope as K}from"./CURSOR_PREFIX-6offuG6M.mjs";import{distinctValues as O}from"./applyInsertDefaults-BJo578fn.mjs";import{RELATION_EXISTS_KEY as _}from"./RELATION_EXISTS_KEY-wxgj6rSL.mjs";const v={every:{kind:"many",negateChild:!0,negated:!0},is:{kind:"one",negated:!1},isNot:{kind:"one",negated:!0,nullDisjunct:!0},none:{kind:"many",negated:!0},some:{kind:"many",negated:!1}},A=e=>L.has(e)?e:void 0,g=e=>{const t=A(e),r=t===void 0?void 0:v[t];if(!r)throw new h("INTERNAL",`unknown relation operator "${e}"`);return r},C=e=>e.kind==="one"?{clause:e.field,project:e.references}:{clause:e.references,project:e.field},D=5e3,f=Symbol("relation-key-overflow"),p=e=>Array.isArray(e)?e.map(t=>t??{}):[],N=e=>{if(e.length===1){const[t]=e;return t??{}}return e.length===0?{}:{AND:e}},y=e=>S(e),u=(e,t,r)=>{const n=t.tables[r]?.relationMap??{};return Object.keys(e).some(o=>{const a=e[o];return o==="AND"||o==="OR"?p(a).some(s=>u(s,t,r)):o==="NOT"?u(a??{},t,r):!!n[o]&&y(a)})},oe=(e,t,r,n)=>{if(e&&u(e,t,r))throw new h("INTERNAL",`relation-crossing predicates are not supported in ${n}() — use them in findMany/findFirst or an RLS read policy`)},B=async(e,t,r,n)=>{const o=await l(t,e.table,n),{page:a}=await n.fetcher(e.table,{baseWhere:n.relationBaseWhere?.(e.table),relationBaseWhere:n.relationBaseWhere,where:o});return O(a,r)},W=(e,t,r)=>{throw new h("INTERNAL",`relation predicate on "${e.table}" matched ${String(t)} rows, exceeding the ${String(r.maxRelationKeys)}-key limit; narrow the predicate (a same-shard EXISTS push-down lifts this cap)`)},F=(e,t,r)=>{throw new h("INTERNAL",`relation predicate on "${e.table}" matched at least ${String(t)} distinct keys, exceeding the ${String(r.maxRelationKeys)}-key limit; narrow the predicate`)},q=async(e,t,r,n,o)=>{const a=await B(e,t,r,n);return a.length<=n.maxRelationKeys?a:o?f:W(e,a.length,n)},b=async(e,t,r,n)=>{const o=await l(t,e.table,n),a=n.maxRelationKeys+1,s=new Set;let d;for(;;){const i=await n.fetcher(e.table,{baseWhere:n.relationBaseWhere?.(e.table),cursor:d,limit:a,relationBaseWhere:n.relationBaseWhere,where:o});if(i.page.length>a)throw new h("INTERNAL",`relation predicate on "${e.table}" read ${String(i.page.length)} rows for a page of at most ${String(a)}; the fetcher did not honour the page limit`);for(const c of O(i.page,r))s.add(c);if(s.size>n.maxRelationKeys&&F(e,s.size,n),i.isDone)return[...s];if(typeof i.continueCursor!="string")throw new h("INTERNAL",`relation predicate on "${e.table}" returned a page that is not final but has no cursor to continue from`);if(i.continueCursor===d)throw new h("INTERNAL",`relation predicate on "${e.table}" paged with a cursor that did not advance`);d=i.continueCursor}},H=async(e,t,r,n,o)=>{const a=g(e),{clause:s,project:d}=C(t),i=await q(t,a.negateChild?{NOT:r}:r,d,n,o);return i===f?f:a.negated?a.nullDisjunct?{OR:[{[s]:{notIn:i}},{[s]:{isNull:!0}}]}:{[s]:{notIn:i}}:{[s]:{in:i}}},z=async(e,t,r,n)=>{const o=g(e),{from:a,table:s,to:d}=t.through,i=await b(t,o.negateChild?{NOT:r}:r,"_id",n),c=i.length===0?[]:await b({table:s},{[d]:{in:i}},a,n);return{_id:o.negated?{notIn:c}:{in:c}}},E=async(e,t,r,n,o)=>{const a=g(e),s=o.relationBaseWhere?.(t.table),d=a.negateChild?{NOT:r}:r,$={childWhere:await l(s?{AND:[s,d]}:d,t.table,o),negated:a.negated,parentTable:n,relation:t};return{[_]:$}},Y=(e,t,r)=>{const n=A(e),o=n===void 0?void 0:v[n];if(o&&o.kind!==r.kind)throw new h("INTERNAL",`relation operator "${e}" requires a to-${o.kind} relation, but "${t}" is to-${r.kind}`)},x=async(e,t,r,n,o)=>{const a=[];for(const s of Object.keys(r)){Y(s,e,t);const d=r[s]??{};if(t.through!==void 0){a.push(await z(s,t,d,o));continue}const i=o.canPushExists?.(t)??!1;if(i&&o.existsPushMode==="always"){a.push(await E(s,t,d,n,o));continue}const c=await H(s,t,d,o,i);c===f?a.push(await E(s,t,d,n,o)):a.push(c)}return N(a)},Q=async(e,t,r,n)=>{if(e==="AND"||e==="OR"){const a=[];for(const s of p(t))a.push(await l(s,r,n));return{[e]:a}}if(e==="NOT")return{NOT:await l(t??{},r,n)};const o=n.schema.tables[r]?.relationMap?.[e];return o&&y(t)?x(e,o,t,r,n):{[e]:t}},l=async(e,t,r)=>{const n=[];for(const o of Object.keys(e))n.push(await Q(o,e[o],t,r));return N(n)},X=async(e,t)=>!e||!u(e,t.schema,t.tableName)?e:l(e,t.tableName,{canPushExists:t.canPushExists,existsPushMode:t.existsPushMode??"auto",fetcher:t.fetcher,maxRelationKeys:t.maxRelationKeys??D,relationBaseWhere:t.relationBaseWhere,schema:t.schema}),ae=async(e,t,r)=>{const n=j(t.orderBy,e.shape,{pinned:P(t.where),uniqueBy:M(e.indexes,e.shape)}),o=t.cursor?k(n,I(t.cursor)):void 0;let a=w(t.baseWhere,t.where);a=w(a,K(e.softDeleteMode,t.includeDeleted)),a=await X(a,{...r,relationBaseWhere:t.relationBaseWhere}),o&&(a=a?{AND:[a,o]}:o);const s=typeof t.limit=="number"?Math.max(0,Math.floor(t.limit)):void 0;return{fetchLimit:s===void 0?void 0:s+1,limit:s,orderKeys:n,predicate:a}},m=(e,t,r)=>{for(const n of e){const o=T(n,t,r);if(o)return o}},U=(e,t,r,n)=>{if(e==="AND"||e==="OR")return m(p(t),r,n);if(e==="NOT")return m([t??{}],r,n);const o=r.tables[n]?.relationMap?.[e];if(!o||!y(t))return;const a=o.through===void 0?[o.table]:[o.table,o.through.table],s=a.find(i=>r.tables[i]?.shardMode?.kind==="shardBy");if(s!==void 0)return{kind:"shard",relation:e,target:s};const d=a.find(i=>R(r.tables[i]));return d!==void 0?{kind:"memory",relation:e,target:d}:m(Object.values(t),r,o.table)},T=(e,t,r)=>{for(const n of Object.keys(e)){const o=U(n,e[n],t,r);if(o)return o}},V=(e,t,r)=>{if(!(t.tables[r]?.shardMode?.kind==="global"||!u(e,t,r)))throw Object.assign(new Error(`shape on "${r}" filters by a relation, which a shard-local shape cannot replicate: its seed and membership probe read "${r}" alone, so the relation never matches, and a write that only touches the related table never moves the shape. Fix it by (a) denormalizing the related columns into "${r}" and filtering on those, (b) moving "${r}" to .global() so it is served through the latency-tiered D1 shape tier, or (c) reading it through a live query (\`useQuery\`), which does resolve relations.`),{code:"SHAPE_RELATION_PREDICATE",name:"LunoraError",status:400})},se=(e,t,r)=>{if(R(t.tables[r]))throw Object.assign(new Error(`shape on "${r}" replicates from the changelog, which never records a .memory() table — the shape would seed once and never update again. Fix it by (a) dropping .memory() from "${r}" so its writes reach the changelog, or (b) reading it through a live query (\`useQuery\`), which refreshes off the changed-table set rather than the log.`),{code:"SHAPE_MEMORY_TABLE",name:"LunoraError",status:400});if(!e)return;const n=T(e,t,r);if(!n){V(e,t,r);return}throw n.kind==="memory"?Object.assign(new Error(`shape on "${r}" joins the .memory() table "${n.target}" via relation "${n.relation}" — writes to a .memory() table never reach the changelog, so the shape is never told its membership changed and would serve stale rows indefinitely. Fix it by (a) dropping .memory() from "${n.target}", or (b) reading it through a live query (\`useQuery\`), which refreshes off the changed-table set rather than the log.`),{code:"SHAPE_MEMORY_TABLE",name:"LunoraError",status:400}):Object.assign(new Error(`shape on "${r}" joins the sharded table "${n.target}" via relation "${n.relation}" — a live shape cannot replicate rows that live in another shard's Durable Object. Fix it by (a) denormalizing the joined columns into "${r}", or (b) moving "${n.target}" to .global() so it is served through the latency-tiered D1 shape tier.`),{code:"SHAPE_CROSS_SHARD_JOIN",name:"LunoraError",status:400})};export{D as DEFAULT_MAX_RELATION_KEYS,oe as assertFlatPredicate,se as assertShapeShardable,ae as composeReadPredicate,u as containsRelationPredicate,y as isRelationPredicate,X as resolveRelationPredicates};
1
+ import{LunoraError as h}from"@lunora/errors";import{i as S,R as L}from"./relation-operators-BEg-CvCH.mjs";import{mergeWhere as w}from"./CountRlsUnsupportedError-BvsDqfO2.mjs";import{isMemoryTable as R}from"./clearMemoryTables-aMRERF0w.mjs";import{normalizeOrderKeys as j,uniqueIndexFields as M,equalityPinnedFields as P,buildSeekWhere as k,decodeCursor as I,softDeleteScope as K}from"./CURSOR_PREFIX-6offuG6M.mjs";import{distinctValues as O}from"./applyInsertDefaults-CVukTkQ5.mjs";import{RELATION_EXISTS_KEY as _}from"./RELATION_EXISTS_KEY-wxgj6rSL.mjs";const v={every:{kind:"many",negateChild:!0,negated:!0},is:{kind:"one",negated:!1},isNot:{kind:"one",negated:!0,nullDisjunct:!0},none:{kind:"many",negated:!0},some:{kind:"many",negated:!1}},A=e=>L.has(e)?e:void 0,g=e=>{const t=A(e),r=t===void 0?void 0:v[t];if(!r)throw new h("INTERNAL",`unknown relation operator "${e}"`);return r},C=e=>e.kind==="one"?{clause:e.field,project:e.references}:{clause:e.references,project:e.field},D=5e3,f=Symbol("relation-key-overflow"),p=e=>Array.isArray(e)?e.map(t=>t??{}):[],N=e=>{if(e.length===1){const[t]=e;return t??{}}return e.length===0?{}:{AND:e}},y=e=>S(e),u=(e,t,r)=>{const n=t.tables[r]?.relationMap??{};return Object.keys(e).some(o=>{const a=e[o];return o==="AND"||o==="OR"?p(a).some(s=>u(s,t,r)):o==="NOT"?u(a??{},t,r):!!n[o]&&y(a)})},oe=(e,t,r,n)=>{if(e&&u(e,t,r))throw new h("INTERNAL",`relation-crossing predicates are not supported in ${n}() — use them in findMany/findFirst or an RLS read policy`)},B=async(e,t,r,n)=>{const o=await l(t,e.table,n),{page:a}=await n.fetcher(e.table,{baseWhere:n.relationBaseWhere?.(e.table),relationBaseWhere:n.relationBaseWhere,where:o});return O(a,r)},W=(e,t,r)=>{throw new h("INTERNAL",`relation predicate on "${e.table}" matched ${String(t)} rows, exceeding the ${String(r.maxRelationKeys)}-key limit; narrow the predicate (a same-shard EXISTS push-down lifts this cap)`)},F=(e,t,r)=>{throw new h("INTERNAL",`relation predicate on "${e.table}" matched at least ${String(t)} distinct keys, exceeding the ${String(r.maxRelationKeys)}-key limit; narrow the predicate`)},q=async(e,t,r,n,o)=>{const a=await B(e,t,r,n);return a.length<=n.maxRelationKeys?a:o?f:W(e,a.length,n)},b=async(e,t,r,n)=>{const o=await l(t,e.table,n),a=n.maxRelationKeys+1,s=new Set;let d;for(;;){const i=await n.fetcher(e.table,{baseWhere:n.relationBaseWhere?.(e.table),cursor:d,limit:a,relationBaseWhere:n.relationBaseWhere,where:o});if(i.page.length>a)throw new h("INTERNAL",`relation predicate on "${e.table}" read ${String(i.page.length)} rows for a page of at most ${String(a)}; the fetcher did not honour the page limit`);for(const c of O(i.page,r))s.add(c);if(s.size>n.maxRelationKeys&&F(e,s.size,n),i.isDone)return[...s];if(typeof i.continueCursor!="string")throw new h("INTERNAL",`relation predicate on "${e.table}" returned a page that is not final but has no cursor to continue from`);if(i.continueCursor===d)throw new h("INTERNAL",`relation predicate on "${e.table}" paged with a cursor that did not advance`);d=i.continueCursor}},H=async(e,t,r,n,o)=>{const a=g(e),{clause:s,project:d}=C(t),i=await q(t,a.negateChild?{NOT:r}:r,d,n,o);return i===f?f:a.negated?a.nullDisjunct?{OR:[{[s]:{notIn:i}},{[s]:{isNull:!0}}]}:{[s]:{notIn:i}}:{[s]:{in:i}}},z=async(e,t,r,n)=>{const o=g(e),{from:a,table:s,to:d}=t.through,i=await b(t,o.negateChild?{NOT:r}:r,"_id",n),c=i.length===0?[]:await b({table:s},{[d]:{in:i}},a,n);return{_id:o.negated?{notIn:c}:{in:c}}},E=async(e,t,r,n,o)=>{const a=g(e),s=o.relationBaseWhere?.(t.table),d=a.negateChild?{NOT:r}:r,$={childWhere:await l(s?{AND:[s,d]}:d,t.table,o),negated:a.negated,parentTable:n,relation:t};return{[_]:$}},Y=(e,t,r)=>{const n=A(e),o=n===void 0?void 0:v[n];if(o&&o.kind!==r.kind)throw new h("INTERNAL",`relation operator "${e}" requires a to-${o.kind} relation, but "${t}" is to-${r.kind}`)},x=async(e,t,r,n,o)=>{const a=[];for(const s of Object.keys(r)){Y(s,e,t);const d=r[s]??{};if(t.through!==void 0){a.push(await z(s,t,d,o));continue}const i=o.canPushExists?.(t)??!1;if(i&&o.existsPushMode==="always"){a.push(await E(s,t,d,n,o));continue}const c=await H(s,t,d,o,i);c===f?a.push(await E(s,t,d,n,o)):a.push(c)}return N(a)},Q=async(e,t,r,n)=>{if(e==="AND"||e==="OR"){const a=[];for(const s of p(t))a.push(await l(s,r,n));return{[e]:a}}if(e==="NOT")return{NOT:await l(t??{},r,n)};const o=n.schema.tables[r]?.relationMap?.[e];return o&&y(t)?x(e,o,t,r,n):{[e]:t}},l=async(e,t,r)=>{const n=[];for(const o of Object.keys(e))n.push(await Q(o,e[o],t,r));return N(n)},X=async(e,t)=>!e||!u(e,t.schema,t.tableName)?e:l(e,t.tableName,{canPushExists:t.canPushExists,existsPushMode:t.existsPushMode??"auto",fetcher:t.fetcher,maxRelationKeys:t.maxRelationKeys??D,relationBaseWhere:t.relationBaseWhere,schema:t.schema}),ae=async(e,t,r)=>{const n=j(t.orderBy,e.shape,{pinned:P(t.where),uniqueBy:M(e.indexes,e.shape)}),o=t.cursor?k(n,I(t.cursor)):void 0;let a=w(t.baseWhere,t.where);a=w(a,K(e.softDeleteMode,t.includeDeleted)),a=await X(a,{...r,relationBaseWhere:t.relationBaseWhere}),o&&(a=a?{AND:[a,o]}:o);const s=typeof t.limit=="number"?Math.max(0,Math.floor(t.limit)):void 0;return{fetchLimit:s===void 0?void 0:s+1,limit:s,orderKeys:n,predicate:a}},m=(e,t,r)=>{for(const n of e){const o=T(n,t,r);if(o)return o}},U=(e,t,r,n)=>{if(e==="AND"||e==="OR")return m(p(t),r,n);if(e==="NOT")return m([t??{}],r,n);const o=r.tables[n]?.relationMap?.[e];if(!o||!y(t))return;const a=o.through===void 0?[o.table]:[o.table,o.through.table],s=a.find(i=>r.tables[i]?.shardMode?.kind==="shardBy");if(s!==void 0)return{kind:"shard",relation:e,target:s};const d=a.find(i=>R(r.tables[i]));return d!==void 0?{kind:"memory",relation:e,target:d}:m(Object.values(t),r,o.table)},T=(e,t,r)=>{for(const n of Object.keys(e)){const o=U(n,e[n],t,r);if(o)return o}},V=(e,t,r)=>{if(!(t.tables[r]?.shardMode?.kind==="global"||!u(e,t,r)))throw Object.assign(new Error(`shape on "${r}" filters by a relation, which a shard-local shape cannot replicate: its seed and membership probe read "${r}" alone, so the relation never matches, and a write that only touches the related table never moves the shape. Fix it by (a) denormalizing the related columns into "${r}" and filtering on those, (b) moving "${r}" to .global() so it is served through the latency-tiered D1 shape tier, or (c) reading it through a live query (\`useQuery\`), which does resolve relations.`),{code:"SHAPE_RELATION_PREDICATE",name:"LunoraError",status:400})},se=(e,t,r)=>{if(R(t.tables[r]))throw Object.assign(new Error(`shape on "${r}" replicates from the changelog, which never records a .memory() table — the shape would seed once and never update again. Fix it by (a) dropping .memory() from "${r}" so its writes reach the changelog, or (b) reading it through a live query (\`useQuery\`), which refreshes off the changed-table set rather than the log.`),{code:"SHAPE_MEMORY_TABLE",name:"LunoraError",status:400});if(!e)return;const n=T(e,t,r);if(!n){V(e,t,r);return}throw n.kind==="memory"?Object.assign(new Error(`shape on "${r}" joins the .memory() table "${n.target}" via relation "${n.relation}" — writes to a .memory() table never reach the changelog, so the shape is never told its membership changed and would serve stale rows indefinitely. Fix it by (a) dropping .memory() from "${n.target}", or (b) reading it through a live query (\`useQuery\`), which refreshes off the changed-table set rather than the log.`),{code:"SHAPE_MEMORY_TABLE",name:"LunoraError",status:400}):Object.assign(new Error(`shape on "${r}" joins the sharded table "${n.target}" via relation "${n.relation}" — a live shape cannot replicate rows that live in another shard's Durable Object. Fix it by (a) denormalizing the joined columns into "${r}", or (b) moving "${n.target}" to .global() so it is served through the latency-tiered D1 shape tier.`),{code:"SHAPE_CROSS_SHARD_JOIN",name:"LunoraError",status:400})};export{D as DEFAULT_MAX_RELATION_KEYS,oe as assertFlatPredicate,se as assertShapeShardable,ae as composeReadPredicate,u as containsRelationPredicate,y as isRelationPredicate,X as resolveRelationPredicates};
@@ -0,0 +1 @@
1
+ import{LunoraError as r}from"@lunora/errors";import{e as a}from"./estimate-bytes-C-C35VXL.mjs";const o={maxReadBytes:32*1024*1024,maxReadRows:1e5,maxWrittenBytes:32*1024*1024,maxWrittenRows:5e4},n=.8,h={readBytes:"maxReadBytes",readRows:"maxReadRows",writtenBytes:"maxWrittenBytes",writtenRows:"maxWrittenRows"},w={readBytes:(s,t)=>`this transaction read ${s} bytes, over the ${t}-byte limit`,readRows:(s,t)=>`this transaction read ${s} documents, over the ${t}-document limit`,writtenBytes:(s,t)=>`this transaction wrote ${s} bytes, over the ${t}-byte limit`,writtenRows:(s,t)=>`this transaction wrote ${s} documents, over the ${t}-document limit`};class c{readBytes=0;readRows=0;writtenRows=0;writtenBytes=0;limits;onNearLimit;warned=new Set;chargedDocuments=new Set;constructor(t={},e){this.limits={...o,...t},this.onNearLimit=e}recordRead(t){this.readRows+=t,this.check("readRows",this.readRows)}recordReadBytes(t){this.readBytes+=t,this.check("readBytes",this.readBytes)}recordDocumentRead(t,e){this.chargedDocuments.has(t)||(this.recordReadBytes(e),this.chargedDocuments.add(t))}beginReadWindow(){this.readBytes=0,this.chargedDocuments.clear()}recordWrite(t){const e=a(t);if(e===void 0)throw new r("BAD_REQUEST","this document is not JSON-serializable (cyclic or non-JSON value); it cannot be written");this.writtenRows+=1,this.writtenBytes+=e,this.check("writtenRows",this.writtenRows),this.check("writtenBytes",this.writtenBytes)}headroom(){return{readBytes:this.readBytes,readRows:this.readRows,remainingReadBytes:Math.max(0,this.limits.maxReadBytes-this.readBytes),remainingReadRows:Math.max(0,this.limits.maxReadRows-this.readRows),remainingWrittenBytes:Math.max(0,this.limits.maxWrittenBytes-this.writtenBytes),remainingWrittenRows:Math.max(0,this.limits.maxWrittenRows-this.writtenRows),writtenBytes:this.writtenBytes,writtenRows:this.writtenRows}}check(t,e){const i=this.limits[h[t]];if(e>i)throw new r("TRANSACTION_LIMIT_EXCEEDED",w[t](String(e),String(i)));if(e>=i*n&&!this.warned.has(t)){this.warned.add(t);try{this.onNearLimit?.({kind:t,limit:i,used:e})}catch{}}}}export{o as DEFAULT_TRANSACTION_LIMITS,c as TransactionHeadroomTracker};
@@ -0,0 +1 @@
1
+ import{LunoraError as S}from"@lunora/errors";import{q as mt}from"./MAX_TOKEN_LENGTH-iFEGEcDL-DBPC6ZWl.mjs";import{S as qn,l as qe,s as Pn}from"./fts-companion-CE3EmIjk.mjs";import{decodeWire as Un,stableWireKey as Pt}from"@lunora/wire";import{sql as a}from"drizzle-orm";import{throwingScheduler as On,aggregateSqlFunction as Pe,normalizeCountArgument as jn}from"./AGGREGATE_SQL_FUNCTION-C_ZipS9R.mjs";import{aggregateTableName as it,encodeAggregateKey as st,readAggregateValue as ct}from"./aggregateTableName-B_CtIQCS.mjs";import{mergeWhere as Q,CountRlsUnsupportedError as at,selectIndexForGroupBy as Gn,selectIndexForCount as Hn,selectIndexForAggregate as Kn}from"./CountRlsUnsupportedError-BvsDqfO2.mjs";import{backfillSearchIndexesForTable as Nn,searchIndexCoversTable as Qn}from"./backfillAggregateIndexes-Pk0KLrfk.mjs";import{backfillAggregateIndexes as Bi,backfillRankIndexes as qi,backfillSearchIndexes as Pi}from"./backfillAggregateIndexes-Pk0KLrfk.mjs";import{appendCdcChange as Vn,readCdcDocAtOrBefore as Jn}from"./CDC_LOG_TABLE-BFGgqai8.mjs";import{CDC_LOG_TABLE as Oi,applyCdcChanges as ji,bumpCdcEpoch as Gi,cdcCanVouchFor as Hi,cdcForkedError as Ki,cdcSeqLeavingRows as Ni,cdcTouchesTables as Qi,cdcTrimmedError as Vi,compactCdcDocs as Ji,cursorBelowRetainedFloor as zi,minCdcReplayableSeq as Yi,minCdcSeq as Xi,readCdcChangeKeys as Zi,readCdcChanges as es,readCdcCursor as ts,readCdcEpoch as ns,trimCdcChanges as os}from"./CDC_LOG_TABLE-BFGgqai8.mjs";import{allocateCommitSeq as zn,COMMIT_SEQ_FIELD as Yn}from"./COMMIT_SEQ_FIELD-Da1DjGqo.mjs";import{createCompanionSync as Xn}from"./createCompanionSync-CEht4hXX.mjs";import{isMemoryTable as Ut}from"./clearMemoryTables-aMRERF0w.mjs";import{computeRankPage as Ot}from"./computeRankPage-BZIpATcs.mjs";import{SCAN_DEP as j}from"./SCAN_DEP-D7qE3iUe.mjs";import{runSql as he,runDrizzle as K}from"./runDrizzle-RC09zZrh.mjs";import{p as Zn,j as wt,D as ie,r as xe,W as eo,k as le,b as Ue,A as dt,a as Oe,m as ue,e as fe,s as to,t as no,u as oo,i as ro,q as jt,h as gn,g as io}from"./do-sql-105TONaE.mjs";import{renderSql as yn,unionAll as $n,WORKERD_SQLITE_LIMITS as En}from"./WORKERD_SQLITE_LIMITS-B_4w7tzY.mjs";import{a as so,u as co}from"./estimate-bytes-C-C35VXL.mjs";import{coveringGeohashes as ao,boundingBoxGeohashes as lo,haversineMeters as uo,pointInBoundingBox as fo}from"./GEO_DEFAULT_PRECISION-CqpQZ-J_.mjs";import{NotFoundError as ho}from"./NotFoundError-BhF7FeFr.mjs";import{resolvePatch as wo,assertPatchAllowed as po,operatorFields as go,readPatchField as Gt}from"./assertPatchAllowed-CA_H466g.mjs";import{tiebreakDirectionFor as yo,encodeCursor as Qe,nullsOrderSuffix as $o,normalizeOrderKeys as Ht,uniqueIndexFields as Eo,buildSeekWhere as mo,decodeCursor as Kt,buildSeekBeforeWhere as So,softDeleteScope as Ae,applySelect as pt}from"./CURSOR_PREFIX-6offuG6M.mjs";import{rankTableName as Nt,sortColumnName as Qt,resolveRankPartition as Ro,encodePartitionKey as vo,RANK_TIEBREAK as To,rankPivotConditionSql as _o}from"./RANK_TIEBREAK-D3ye2GsL.mjs";import{UNVOUCHABLE_DEP as Vt}from"./UNVOUCHABLE_DEP-Ds9gxVqs.mjs";import{idIndexKey as Ao,withUnknownIndexKeys as Io,indexKeysForRow as xo,buildIndexRange as bo}from"./buildIndexRange-BTChxh3k.mjs";import{r as Ve,j as be,c as Z,t as ze,i as Jt}from"./where-sql-BjY4rnqb.mjs";import{serializeSqlValue as Ce}from"./serializeSqlValue-DeoBMpZ2.mjs";import{quoteIdentifier as Me}from"./quoteIdentifier-CObIFRhb.mjs";import{whereOfFilter as Co,isPushableWhere as Mo}from"./isPushableWhere-BeYAOjUb.mjs";import{deriveRelationEdges as Do,findRelated as ko}from"./RELATED_DEFAULT_LIMIT-CVqN4JEu.mjs";import{assertFlatPredicate as lt,resolveRelationPredicates as Lo,composeReadPredicate as Fo}from"./DEFAULT_MAX_RELATION_KEYS-DfrMi_eE.mjs";import{describeRelationWrites as Wo}from"./describeRelationWrites-omar6-u9.mjs";import{runRowValidators as je,transformOnlyDefinition as Bo,applyInsertDefaults as gt,resolveWith as zt,relationHooks as Yt,applyOnDelete as qo,fanOutScalarCounts as Po}from"./applyInsertDefaults-CVukTkQ5.mjs";import{guardWriter as Uo}from"./RLS_UNWRAP_SYMBOL-H6J96vgK.mjs";import{mayHoldProjectedValue as Oo}from"./BIGINT_KEY_DIGITS-DE6yshOt.mjs";import{createSystemReader as jo}from"./createSystemReader-BSCxr8Qs.mjs";import{ConflictError as se}from"./ConflictError-C8GtJmjS.mjs";import{hasTrigger as Xt,runTriggers as Go}from"./hasTrigger-CjlwI4le.mjs";import{advanceClientWatermark as is,migrateClientWatermark as ss,readClientWatermark as cs}from"./CLIENT_WATERMARK_TABLE-De7z_OHV.mjs";import{IDEMPOTENCY_TABLE as ds,readIdempotent as ls,trimIdempotent as us,writeIdempotent as fs}from"./IDEMPOTENCY_TABLE-COrgeP3O.mjs";import{runShardMigrations as ws}from"./runShardMigrations-xu993yo2.mjs";import{selectShapeMembers as gs,selectShapeRows as ys}from"./selectShapeMembers-Dqx_m7BF.mjs";const Ho=n=>{const r=atob(n),o=Uint8Array.from(r,s=>s.codePointAt(0)??0);return new TextDecoder().decode(o)},Ko=()=>new S("BAD_REQUEST","invalid cursor"),Zt=16,en=8,z=1024,St=(n,r)=>r.query(n),No=(n,r)=>{if(n.length===0)return 0;let o=0;for(const[s,c]of r.entries()){const u=s===r.length-1;let g=0;for(const m of n)(u?m.startsWith(c):m===c)&&(g+=1);if(g===0)return 0;o+=g}return o},Qo=(n,r)=>{if(!r)return{exact:!0,lower:n,upper:n};const o=[...n].at(-1)??"",s=(o.codePointAt(0)??0)+1;if(s>=55296&&s<=57343||s>1114111)return{exact:!0,lower:n,upper:n};const c=n.slice(0,n.length-o.length);return{exact:!1,lower:n,upper:c+String.fromCodePoint(s)}},Vo=(n,r,o)=>{const s={eq:(c,u)=>{if(!n.definition.filterFields?.includes(c))throw new S("INTERNAL",`field "${c}" is not a filter field of search index "${n.indexName}" on table "${r}"`);if(n.filters.length>=en)throw new S("BAD_REQUEST",`search index "${n.indexName}" on table "${r}": at most ${String(en)} .eq() filters are supported per search query`);return n.filters.push({field:c,value:u}),s},search:(c,u)=>{const g=n;if(c!==g.definition.field)throw new S("INTERNAL",`search index "${g.indexName}" on table "${r}" indexes "${g.definition.field}", not "${c}"`);const m=St(u,o).length;if(m>Zt)throw new S("BAD_REQUEST",`search index "${g.indexName}" on table "${r}": at most ${String(Zt)} search terms are supported (got ${String(m)})`);return g.field=c,g.query=u,g.hasQuery=!0,s}};return s},Jo=n=>{if(n.length>z)throw new S("BAD_REQUEST",`more than ${String(z)} documents match this search — narrow it with filters or read it a page at a time with .paginate()`)},zo=n=>Math.min(n.offset+n.numItems+1,z),Yo=n=>btoa(`search:${String(n)}`),Xo=n=>{let r;try{r=Ho(n)}catch{return}if(!r.startsWith("search:"))return;const o=Number(r.slice(7));return Number.isInteger(o)&&o>=0?o:void 0},Zo=n=>{if(typeof n.endCursor=="string")throw new S("BAD_REQUEST","bounded (endCursor) pagination is not supported on search queries — relevance order has no stable range boundary");if(!Number.isFinite(n.numItems))throw new S("BAD_REQUEST",`search pagination needs a finite numItems, got ${String(n.numItems)}`);const r=Math.max(0,Math.floor(n.numItems)),o=n.cursor?Xo(n.cursor):0;if(o===void 0)throw Ko();if(o+r>=z)throw new S("BAD_REQUEST",`search pagination reaches the ${String(z)}-document limit (offset ${String(o)} + ${String(r)} requested) — a page must end below the cap so the probe row that answers \`hasMore\` still fits: retry with numItems ${String(Math.max(1,z-o-1))} or fewer, or narrow the query or the filters instead`);return{numItems:r,offset:o}},er=(n,r)=>{const o=r.offset+r.numItems,s=r.numItems>0&&n.length>o;return{continueCursor:s?Yo(o):null,isDone:!s,page:n.slice(r.offset,o)}},tr=n=>{if(n===void 0)return z+1;if(!Number.isFinite(n))return z;const r=Math.max(0,Math.floor(n));if(r>z)throw new S("BAD_REQUEST",`search returns at most ${String(z)} documents (asked for ${String(r)}) — narrow the query or paginate instead`);return r},mn=500,Sn=(n,r,o)=>{if(n!==void 0&&n!==Number.POSITIVE_INFINITY&&(!Number.isInteger(n)||n<0))throw o(`${r}: batch limit must be a non-negative integer`);return n??mn},Rn=(n,r,o,s)=>{if(n>r)throw s(`${o}: batch of ${String(n)} exceeds the limit of ${String(r)} (raise options.limit or chunk the call)`)},nr=32,or=1024,vn=(n,r,o,s)=>{const c=`SELECT id, _creationTime, ${Me(ie)} FROM ${Me(n)}`,u=`ORDER BY ${o}${s===void 0?"":` LIMIT ${String(s)}`}`;return r===void 0?Ve(`${c} ${u}`):be(`${c} WHERE `,r,` ${u}`)},Ye={fieldRef:n=>Ve(wt(n)),rangeTypeGuard:(n,r)=>Ve(Zn(n,r)),serialize:Ce},rr=n=>n===void 0?"":$o(n==="first"),Tn=n=>{const r=n.map(o=>`${wt(o.field)} ${o.direction==="desc"?"DESC":"ASC"}${rr(o.nulls)}`);return n.some(o=>o.field==="_id"||o.field==="id")||r.push(`${wt("id")} ${yo(n)==="desc"?"DESC":"ASC"}`),r.join(", ")},ir={"<":"lt","<=":"lte","=":"eq",">":"gt",">=":"gte"},_n=n=>new Set(n.sqlConditions.filter(r=>r.comparator==="=").map(r=>r.field)),sr=n=>{const r=_n(n);let o=0;for(;o<n.indexFields.length&&r.has(n.indexFields[o]??"");)o+=1;return n.indexFields.slice(o)},cr=(n,r)=>{const o=n.order,s=sr(n),{shape:c}=r;return s.length>0?Ht(s.map(u=>({[u]:o})),c,{pinned:_n(n),uniqueBy:Eo(r.indexes,c)}):Ht([{_creationTime:o}],c)},ar=(n,r,o,s)=>{const c=n.sqlConditions.map(u=>({[u.field]:{[ir[u.comparator]??"eq"]:u.value}}));if(o&&c.push(mo(r,Kt(o))),s&&c.push(So(r,Kt(s))),c.length!==0)return c.length===1?c[0]:{AND:c}},dr=n=>{if(n.want!==void 0)return n.selective?Math.max(n.want,nr):n.want},yt=(n,r,o,s,c,u,g)=>{const m=cr(s,o),y=Tn(m),l=[],{filters:D,want:I}=u;let T=u.cursor??void 0,x=dr(u);if(I===0)return{documents:l,orderKeys:m};for(;;){const B=Z(ar(s,m,T,u.endCursor),Ye,ze),P=vn(r,c&&B?be(B," AND ",c):c??B,y,x),W=he(n,P.text,...P.params).toArray();let U={};g(W.length);for(const G of W)if(U=xe(G),D.every(ee=>ee(U))&&l.push(U)===I)return{documents:l,orderKeys:m};if(x===void 0||W.length<x)return{documents:l,orderKeys:m};T=Qe(U,m),x=Math.max(x,Math.min(x*2,or))}},lr=(n,r,o,s,c,u,g,m)=>{const y=Math.max(0,Math.floor(c.numItems));if(typeof c.endCursor=="string"){const{documents:B,orderKeys:P}=yt(n,r,o,s,u,{cursor:c.cursor,endCursor:c.endCursor,filters:g.all,selective:g.selective,want:void 0},m),W=B.length>=2?B[Math.floor(B.length/2)-1]:void 0;return{continueCursor:c.endCursor,isDone:!0,page:B,splitCursor:W?Qe(W,P):null}}const{documents:l,orderKeys:D}=yt(n,r,o,s,u,{cursor:c.cursor,filters:g.all,selective:g.selective,want:y+1},m),I=l.length>y,T=I?l.slice(0,y):l,x=T.at(-1);return{continueCursor:I&&x?Qe(x,D):null,isDone:!I,page:T}},Xe=n=>{const r=new Map;return o=>{const s=r.get(o);if(s!==void 0)return s;const c=n(Me(o));return r.set(o,c),c}},we=Me(ie),ur=Xe(n=>`INSERT INTO ${n} (id, _creationTime, ${we}) VALUES (?, ?, ?)`),tn=Xe(n=>`UPDATE ${n} SET ${we} = ? WHERE id = ? AND ${we} = ?`),fr=Xe(n=>`UPDATE ${n} SET _creationTime = ?, ${we} = ? WHERE id = ? AND ${we} = ?`),hr=Xe(n=>`DELETE FROM ${n} WHERE id = ? AND ${we} = ?`),wr="SELECT changes() AS changed",nn=new Map,pr="",gr=n=>{const r=JSON.stringify(n),o=nn.get(r);if(o!==void 0)return o;const s=n.map(u=>a`SELECT ${a.raw(`'${u.replaceAll("'","''")}'`)} AS __t__, id, _creationTime, ${a.identifier(ie)} FROM ${a.identifier(u)} WHERE id = ${pr}`),{sql:c}=yn("sqlite",a`${$n(s)} LIMIT 1`);return nn.set(r,c),c},yr=(n,r)=>r.map(()=>n),$r=/^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/iu,Er=n=>{if(!$r.test(n))throw new S("INTERNAL",`invalid clientId ${JSON.stringify(n)}: a client-supplied row id must be a UUID`)},$t=n=>{if(n.includes("\0"))throw new S("BAD_REQUEST",`invalid row id ${JSON.stringify(n)}: a row id cannot hold a NUL character (U+0000)`)},mr=(n,r,o,s)=>{if(o!==!0)return;const c=n!==void 0&&"serverDefault"in(n.shape._id?._meta?.column??{});for(const u of r){const g=c?gt(n,u,s)._id:u._id;typeof g=="string"&&$t(g)}},on=50,Ge=Math.floor(En.boundParams/3),rn=En.boundParams,Sr=128,Je=n=>new S("BATCH_LIMIT_EXCEEDED",n,{status:400}),He=(n,r,o)=>{Rn(n,Sn(r,o,Je),o,Je)},sn=async(n,r,o,s,c)=>{const u=Sn(s,c,Je),{page:g}=await n.findMany(r,Number.isFinite(u)?{limit:u+1,omitContinueCursor:!0,where:o}:{where:o});return g.length>u&&Rn(Math.max(await n.count(r,{where:o}),g.length),u,c,Je),g},Rr=n=>{const r={eq:(o,s)=>(n.sqlConditions.push({comparator:"=",field:o,value:s}),r),gt:(o,s)=>(n.sqlConditions.push({comparator:">",field:o,value:s}),r),gte:(o,s)=>(n.sqlConditions.push({comparator:">=",field:o,value:s}),r),lt:(o,s)=>(n.sqlConditions.push({comparator:"<",field:o,value:s}),r),lte:(o,s)=>(n.sqlConditions.push({comparator:"<=",field:o,value:s}),r)};return r},vr=n=>Math.max(n,z),An=(n,r)=>{const o=n.filters.map(s=>a`${fe(s.field)} = ${Ce(s.value)}`);return r&&o.push(r),o},Tr=(n,r,o,s,c)=>{const u=St(o.query,mt(o.definition.language));if(u.length===0)return[];const g=qn(r,o.indexName),m=`${g}__vocab`,y=u.length-1,l=u.map((P,W)=>{const U=Qo(P,W===y),G=U.exact?a`${a.identifier("term")} = ${U.lower}`:a`${a.identifier("term")} >= ${U.lower} AND ${a.identifier("term")} < ${U.upper}`;return a`SELECT ${a.identifier("doc")}, ${a.raw(String(W))} AS ${a.identifier("__term__")}, COUNT(*) AS ${a.identifier("__n__")} FROM ${a.identifier(m)} WHERE ${G} GROUP BY ${a.identifier("doc")}`}),D=u.map((P,W)=>a`SUM(CASE WHEN u.${a.identifier("__term__")} = ${a.raw(String(W))} THEN u.${a.identifier("__n__")} ELSE 0 END)`),I=a`SELECT f.${a.identifier(qe)} AS ${a.identifier(qe)}, ${a.join(D,a` + `)} AS ${a.identifier("__score__")} FROM (${$n(l)}) u JOIN ${a.identifier(g)} f ON f.rowid = u.${a.identifier("doc")} GROUP BY f.${a.identifier(qe)} HAVING ${a.join(D.map(P=>a`${P} > 0`),a` AND `)}`,T=An(o,c);let x=a`SELECT m.id, m._creationTime, m.${a.identifier(ie)}, s.${a.identifier("__score__")} AS ${a.identifier("__score__")} FROM (${I}) s JOIN ${a.identifier(r)} m ON m.id = s.${a.identifier(qe)}`;T.length>0&&(x=a`${x} WHERE ${a.join(T,a` AND `)}`),x=a`${x} ORDER BY s.${a.identifier("__score__")} DESC, m._creationTime DESC, m.id ASC LIMIT ${a.raw(String(s))}`;const B=[];for(const P of K(n,x)){const W=gn(P);if(W){const U=P.__score__;B.push({document:W,score:typeof U=="number"?U:Number(U??0)})}}return B},_r=(n,r,o,s,c)=>{const u=mt(o.definition.language),g=St(o.query,u);if(g.length===0)return[];const m=An(o,c);let y=a`SELECT id, _creationTime, ${a.identifier(ie)} FROM ${a.identifier(r)}`;m.length>0&&(y=a`${y} WHERE ${a.join(m,a` AND `)}`),y=a`${y} ORDER BY _creationTime DESC, id ASC LIMIT ${a.raw(String(vr(s)))}`;const l=K(n,y).toArray(),D=[];for(const I of l){const T=gn(I);if(!T)continue;const x=No(Pn(T,o.definition),g);x>0&&D.push({creationTime:typeof T._creationTime=="number"?T._creationTime:0,doc:T,id:typeof T._id=="string"?T._id:"",score:x})}return D.sort((I,T)=>T.score-I.score||T.creationTime-I.creationTime||I.id.localeCompare(T.id)),D.slice(0,s).map(I=>({document:I.doc,score:I.score}))},ut=(n,r,o,s)=>{if(!Number.isFinite(n.lat)||n.lat<-90||n.lat>90||!Number.isFinite(n.lng)||n.lng<-180||n.lng>180)throw new S("BAD_REQUEST",`geo index "${s}" on table "${o}": ${r} must have a finite lat in [-90, 90] and lng in [-180, 180]`)},Ar=(n,r)=>{const o=n,s={near:(c,u)=>{if(o.within)throw new S("INTERNAL",`geo index "${o.indexName}" on table "${r}": call .near() or .within(), not both`);if(ut(c,".near() point",r,o.indexName),!Number.isFinite(u)||u<=0)throw new S("BAD_REQUEST",`geo index "${o.indexName}" on table "${r}": .near() radiusMeters must be a finite number > 0, got ${String(u)}`);return o.near={point:{lat:c.lat,lng:c.lng},radiusMeters:u},s},within:c=>{if(o.near)throw new S("INTERNAL",`geo index "${o.indexName}" on table "${r}": call .near() or .within(), not both`);if(ut(c.sw,".within() sw corner",r,o.indexName),ut(c.ne,".within() ne corner",r,o.indexName),c.sw.lat>c.ne.lat)throw new S("BAD_REQUEST",`geo index "${o.indexName}" on table "${r}": .within() corners are transposed (sw.lat > ne.lat)`);if(c.sw.lng>c.ne.lng)throw new S("BAD_REQUEST",`geo index "${o.indexName}" on table "${r}": .within() box crosses the antimeridian (sw.lng > ne.lng), which is not supported — split it into two boxes at ±180 and union the results`);return o.within={ne:{lat:c.ne.lat,lng:c.ne.lng},sw:{lat:c.sw.lat,lng:c.sw.lng}},s}};return s},Ir=(n,r)=>{const o=n[r];if(o===null||typeof o!="object")return;const{lat:s,lng:c}=o;return typeof s=="number"&&typeof c=="number"?{lat:s,lng:c}:void 0},xr=(n,r)=>{const o=Ir(n,r.definition.field);if(!o)return;const s=typeof n._creationTime=="number"?n._creationTime:0;if(r.near){const c=uo(r.near.point,o);return c<=r.near.radiusMeters?{creationTime:s,distance:c}:void 0}return fo(o,r.within)?{creationTime:s,distance:0}:void 0},br=(n,r,o,s)=>{if(!o.near&&!o.within)throw new S("INTERNAL",`geo index "${o.indexName}" on table "${r}": call .near(point, radius) or .within(box)`);const c=o.near?ao(o.near.point,o.near.radiusMeters):lo(o.within),u=io(r,o.indexName),g=c.map(I=>a`(g.${a.identifier("__geohash__")} >= ${I} AND g.${a.identifier("__geohash__")} < ${`${I}{`})`),m=[a`(${a.join(g,a` OR `)})`];s&&m.push(s);const y=a`SELECT m.id, m._creationTime, m.${a.identifier(ie)} FROM ${a.identifier(u)} g JOIN ${a.identifier(r)} m ON m.id = g.${a.identifier("__id__")} WHERE ${a.join(m,a` AND `)}`,l=K(n,y).toArray(),D=[];for(const I of l){const T=xe(I),x=T?xr(T,o):void 0;T&&x&&D.push({creationTime:x.creationTime,distance:x.distance,doc:T})}return D.sort((I,T)=>I.distance-T.distance||T.creationTime-I.creationTime),D},In=(n,r,o,s)=>{const c=[];for(const u of n)if(r.every(g=>g(s(u)))&&(c.push(u),typeof o=="number"&&c.length>=o))break;return c},Cr=(n,r,o,s,c,u=()=>{})=>{const g=o.within!==void 0,m=br(n,r,o,c).map(y=>({distanceMeters:g?null:y.distance,document:y.doc}));return u(m.length),typeof s=="number"?m.slice(0,Math.max(0,Math.floor(s))):m},cn=(n,r,o,s,c,u,g=()=>{})=>{const{geo:m}=o;if(!m)throw new S("INTERNAL","runGeoTerminalScored called without a staged geo query");const y=c.length>0,l=Cr(n,r,m,y?void 0:u,s,g);return y?In(l,c,u,D=>D.document):l},an=(n,r,o)=>{const s=n.shape[r];if(s!==void 0&&Oo(s))throw new S("BAD_REQUEST",`${o}: "${r}" may hold an order-preserving key rather than a value SQL can reduce or group — declare an aggregateIndex covering this (by, field, op) so the maintained companion answers it instead (its running total is a REAL, so it stays exact only while the total is inside 2^53)`)},Mr=n=>{let r=0;const o=[],s={...Ye,relationExists:c=>{const{childWhere:u,negated:g,parentTable:m,relation:y}=c,l=`__rel_${String(r)}`,D=o.at(-1)??m;r+=1,n(y.table,j);const I=y.kind==="one"?y.field:y.references,T=y.kind==="one"?y.references:y.field,x=Ve(`${jt(l,T)} = ${jt(D,I)}`);o.push(l);const B=Z(u,s,ze);o.pop();const P=B===void 0?x:be(x," AND ",B),W=be("EXISTS (SELECT 1 FROM ",Jt(y.table)," AS ",Jt(l)," WHERE ",P,")");return g?be("NOT ",W):W}};return s};class Dr extends S{constructor(r="unique() found more than one matching document"){super("NOT_UNIQUE",r,{name:"NotUniqueError"})}}const kr=/\s/u,Lr=String.fromCodePoint(0),dn=(n,r,o)=>{if(!n.tables[r])throw new S("INTERNAL",`unknown table: ${r}`);return typeof o!="string"||o.length===0||kr.test(o)||o.includes(Lr)?null:o},xn=(n,r,o,s=()=>{},c=()=>{},u=()=>{},g)=>{const m=r.tables[o];if(!m)throw new S("INTERNAL",`unknown table: ${o}`);const y=Ae(m.softDeleteMode,void 0),l=g??{indexFields:[],indexName:void 0,inMemoryFilters:[],order:"asc",sqlConditions:[],verifyFilters:[]},D=()=>{const R=Q(y,l.pushedWhere);return R?Z(R,ue):void 0},I=()=>{const R=Q(y,l.pushedWhere);return R?Z(R,Ye,ze):void 0},T=()=>[...l.inMemoryFilters,...l.verifyFilters];let x=0;const B=R=>{const{search:C}=l;if(!C)throw new S("INTERNAL","runSearchFetch called without a staged search");Nn(oo(n),o,m);const L=l.inMemoryFilters.length>0,F=tr(L?void 0:R),k=ro(n);if(k&&!Qn(n,o,C.definition))throw new S("SEARCH_INDEX_BUILDING",`search index "${C.indexName}" on table "${o}" is still backfilling and currently covers only part of the table — retry once it finishes, or run the backfillSearch admin operation to complete it now`);const pe=D(),te=k?Tr(n,o,C,F,pe):_r(n,o,C,F,pe);!L&&R===void 0&&Jo(te);const ge=T();return x=te.length,ge.length>0?In(te,ge,R,J=>J.document):te},P=R=>B(R).map(C=>C.document),W=R=>{const C=Zo(R);return er(P(zo(C)),C)},U=()=>{if(l.search||l.geo||l.indexName===void 0){c(void 0);return}c(bo(o,l.indexName,l.indexFields,l.sqlConditions,Ce))},G=R=>{U();let C=0;const L=(()=>{if(l.search){const F=P(R);return C=x,F}return l.geo?cn(n,o,l,D(),T(),R,F=>{C=F}).map(F=>F.document):yt(n,o,m,l,I(),{filters:T(),selective:l.inMemoryFilters.length>0,want:R===void 0?void 0:Math.max(0,Math.floor(R))},F=>{C+=F}).documents})();return u(Math.max(C,L.length)),L},ee=()=>{if(!l.search&&!l.geo)throw new S("INTERNAL",`ctx.db.query("${o}").collectWithScores() requires a staged .withSearchIndex(...) or .withGeoIndex(...)`);U();let R=0;const C=(()=>{if(l.search){const L=B(void 0);return R=x,L}return cn(n,o,l,D(),T(),void 0,L=>{R=L})})();return u(Math.max(R,C.length)),C},N={async*[Symbol.asyncIterator](){const R=xn(n,r,o,s,c,u,{...l,indexFields:[...l.indexFields],inMemoryFilters:[...l.inMemoryFilters],sqlConditions:[...l.sqlConditions],verifyFilters:[...l.verifyFilters]});if(l.search){yield*await R.collect();return}let C;for(;;){const L=await R.paginate({cursor:C??null,numItems:Sr});if(yield*L.page,L.isDone||L.continueCursor===null)return;C=L.continueCursor}},async collect(){return G(void 0)},async collectWithScores(){return ee()},filter(R){const C=Co(R);return C!==void 0&&Mo(C,m.shape)?(l.pushedWhere=Q(l.pushedWhere,C),l.verifyFilters.push(R)):l.inMemoryFilters.push(R),N},async first(){return G(1)[0]??null},order(R){return l.order=R==="desc"?"desc":"asc",N},async paginate(R){let C=0;if(U(),l.search){const F=W(R);return u(F.page.length),F}if(l.geo)throw new S("INTERNAL","pagination is not supported on geo queries; use .take(n) or .collect()");const L=lr(n,o,m,l,R,I(),{all:T(),selective:l.inMemoryFilters.length>0},F=>{C+=F});return u(Math.max(C,L.page.length)),L},async take(R){return G(R)},async unique(){const R=G(2);if(R.length>1)throw new Dr(`unique() on table "${o}" matched ${String(R.length)} documents; expected at most one`);return R[0]??null},withGeoIndex(R,C){const L=(m.geoIndexes??[]).find(k=>k.name===R);if(!L)throw new S("INTERNAL",`unknown geo index "${R}" on table "${o}"`);s(o,R,"geo");const F={definition:L,indexName:R};if(l.geo=F,C(Ar(F,o)),!F.near&&!F.within)throw new S("INTERNAL",`geo index "${R}" on table "${o}" requires a .near(point, radius) or .within(box) call`);return N},withIndex(R,C){const L=m.indexes.find(F=>F.name===R);if(!L)throw new S("INTERNAL",`unknown index "${R}" on table "${o}"`);return s(o,R,"index"),l.indexName=R,l.indexFields=L.fields,C&&C(Rr(l)),N},withSearchIndex(R,C){const L=(m.searchIndexes??[]).find(k=>k.name===R);if(!L)throw new S("INTERNAL",`unknown search index "${R}" on table "${o}"`);s(o,R,"search");const F={definition:L,field:L.field,filters:[],hasQuery:!1,indexName:R,query:""};if(l.search=F,C(Vo(F,o,mt(L.language))),!F.hasQuery)throw new S("INTERNAL",`search index "${R}" on table "${o}" requires a .search(field, query) call`);return N}};return N},ft=(n,r,o,s)=>{const c=o;for(const[u,g]of no(n)){if(g.serverDefault){u in r&&(c[u]=g.serverDefault({auth:s}));continue}g.onUpdateFn&&!(u in r)&&(c[u]=g.onUpdateFn())}},ln=5,un=(n,r)=>{for(const o of Object.keys(r))if(r[o]===void 0)throw new S("INTERNAL",`Cannot ${n} field '${o}' to undefined — use null to clear a nullable field, or omit the key to leave it unchanged.`)},fn=["_commitSeq","_creationTime","_id"],Ke=n=>fn.some(r=>r in n)?Object.fromEntries(Object.entries(n).filter(([r])=>!fn.includes(r))):n,Fr=/unique constraint failed/i,Wr=n=>n instanceof Error&&Fr.test(n.message),Br=/string or blob too big/iu,qr=(n,r)=>{if(!(!(n instanceof Error)||!Br.test(n.message)))throw new S("PAYLOAD_TOO_LARGE",`document is too large to store in "${r}": a single row cannot exceed the storage engine's per-row ceiling (2 MB on a Durable Object's SQLite). The limit is on the STORED bytes, which are UTF-8, and v.bytes()/v.bigint() columns are stored twice on a shard-local table. Keep the payload in R2 (ctx.storage) and store a reference on the row.`)},Et=(n,r,o,s)=>{try{he(n,o,...s)}catch(c){throw Wr(c)?new se(`unique constraint violation on "${r}"`,"unique"):(qr(c,r),c)}},Ne=(n,r,o,s)=>{if(Et(n,r,o,s),he(n,wr).one().changed===0)throw new se(`optimistic concurrency conflict on "${r}" — the row changed during this mutation; refetch and retry`,"occ")},hn=(n,r,o,s,c,u,g)=>{const m=[];for(let I=0;I<o.length+1;I+=1){const T=o[I],x=s[I],B=x?.direction==="desc"?"desc":"asc",P=T===void 0||x===void 0?a`${a.identifier(To)} < ${g}`:_o(T,u[I],B,!1);if(P===void 0)continue;const W=[];for(let G=0;G<I;G+=1)W.push(a`${a.identifier(o[G])} IS ${u[G]}`);W.push(P);const[U]=W;m.push(W.length===1&&U!==void 0?U:a`(${a.join(W,a` AND `)})`)}const y=m.length>0?a.join(m,a` OR `):a`1 = 0`,l=K(n,a`SELECT COUNT(*) AS c FROM ${a.identifier(r)} WHERE ${a.identifier("__partition__")} = ${c} AND (${y})`).one(),D=K(n,a`SELECT COUNT(*) AS c FROM ${a.identifier(r)} WHERE ${a.identifier("__partition__")} = ${c}`).one();return{before:l.c,total:D.c}},Pr=n=>{const r=new Map;for(const[s,c]of Object.entries(n.tables))for(const u of Object.values(c.relationMap??{}))u.kind==="one"&&(u.onDelete==="cascade"||u.onDelete==="set null")&&r.set(u.table,[...r.get(u.table)??[],{holder:s,op:u.onDelete==="cascade"?"delete":"update"}]);const o=s=>{const c=new Set,u=[s];for(let g=u.pop();g!==void 0;g=u.pop())for(const{holder:m,op:y}of r.get(g)??[]){if(m===s||Xt(n,m,y))return!0;c.has(m)||(c.add(m),u.push(m))}return!1};return new Set(Object.entries(n.tables).filter(([s,c])=>c.shardMode?.kind==="global"||Xt(n,s,"delete")||o(s)).map(([s])=>s))},Ur=n=>{const r=new Map;for(const[o,s]of Object.entries(n.tables))s.softDeleteMode&&r.set(o,s.softDeleteMode.field);return r},ht=new WeakMap,Or=(n,r)=>{let o=ht.get(r.tables);if(!ht.has(r.tables)){const c=Object.keys(r.tables).map(u=>u.replaceAll(/[$()*+.?[\\\]^{|}]/gu,String.raw`\$&`));o=c.length===0?void 0:new RegExp(`"(${c.join("|")})"`,"gu"),ht.set(r.tables,o)}if(o===void 0)return;const s=new Set;for(const c of n.matchAll(o))s.add(c[1]);return s.size===1?[...s][0]:void 0},jr=(n,r,o)=>{for(const s of n){const c=s,u=c?.[ie];if(typeof u=="string"){const g=c?.id,m=co(u);typeof g!="string"?r.recordReadBytes(m):o===void 0?r.recordDocumentRead(`${g}\0${String(m)}`,m):r.recordDocumentRead(`${o}\0${g}`,m)}}},Gr=(n,r,o)=>{if(r===void 0)return n;const s=(c,...u)=>{const g=n.exec(c,...u),m=g.one.bind(g),y=g[Symbol.iterator].bind(g),l=o===void 0?void 0:Or(c,o);let D=!1;const I=T=>{jr(T,r,l)};return g.toArray=()=>{const T=[];for(const x of{[Symbol.iterator]:y})I([x]),T.push(x);return T},g.one=()=>{D=!0;try{const T=m();return I([T]),T}finally{D=!1}},g[Symbol.iterator]=function*(){for(const x of{[Symbol.iterator]:y})D||I([x]),yield x},g};return new Proxy(n,{get:(c,u)=>u==="exec"?s:u===eo?c:Reflect.get(c,u,c)})},Hr=new Map([["findFirst","rows"],["findFirstOrThrow","rows"],["findMany","page"],["get","rows"],["lookupById","lookup"],["rankPage","page"]]),Kr=new Map([["collect","rows"],["collectWithScores","scored"],["first","rows"],["paginate","page"],["take","rows"],["unique","rows"]]),Ie=(n,r,o)=>{if(typeof n!="object"||n===null)return;const s=so(n);if(s===void 0)return;const c=n._id;typeof c=="string"?o.recordDocumentRead(`global\0${r}\0${c}`,s):o.recordReadBytes(s)},bn=(n,r,o,s)=>{if(typeof n!="object"||n===null)return;const c=n;switch(r){case"lookup":{Ie(c.row,typeof c.tableName=="string"?c.tableName:o,s);return}case"page":{for(const u of c.page??[])Ie(u,o,s);return}case"rows":{for(const u of Array.isArray(n)?n:[n])Ie(u,o,s);return}default:for(const u of Array.isArray(n)?n:[])Ie(u.document,o,s)}},Cn=(n,r,o)=>new Proxy(n,{get:(s,c)=>{const u=Reflect.get(s,c,s);if(typeof u!="function")return u;if(c===Symbol.asyncIterator)return async function*(){for await(const y of Reflect.apply(u,s,[]))Ie(y,r,o),yield y};const g=Kr.get(c);return(...m)=>{const y=Reflect.apply(u,s,m);return g!==void 0?Promise.resolve(y).then(l=>(bn(l,g,r,o),l)):typeof y=="object"&&y!==null&&!(y instanceof Promise)?Cn(y,r,o):y}}}),Nr=new Set(["findFirst","findFirstOrThrow","findMany"]),Qr=n=>{const r=n[1],o=r?.select;if(!Array.isArray(o))return;const s=Object.fromEntries(Object.entries(r).filter(([g])=>g!=="select")),c=s.with,u=g=>pt(g,o,c);return{args:[n[0],s,...n.slice(2)],project:(g,m)=>typeof g!="object"||g===null?g:m==="page"?{...g,page:u(g.page)}:u([g])[0]}},Vr=(n,r)=>n===void 0||r===void 0?n:new Proxy(n,{get:(o,s)=>{const c=Reflect.get(o,s,o);if(typeof c!="function")return c;if(s==="query")return(...g)=>Cn(Reflect.apply(c,o,g),String(g[0]),r);const u=Hr.get(s);return u===void 0?c:async(...g)=>{const m=Nr.has(s)?Qr(g):void 0,y=await Reflect.apply(c,o,m?.args??g);return bn(y,u,String(g[0]),r),m===void 0?y:m.project(y,u)}}}),wn=new WeakMap,pn=new WeakMap,Jr=n=>{const{baselineSeq:r,onStalePatchDropped:o}=n,{headroom:s}=n,c=wn.get(n)??{value:void 0},u=pn.get(n)??{value:0};let g;const m=()=>{if(g===void 0){const e={...n,enforceRls:!1,headroom:void 0};wn.set(e,c),pn.set(e,u),g=Jr(e)}return g},y=Gr(n.sql,s,n.schema),{schema:l}=n,D=n.broadcast??(()=>{}),I=(e,t)=>{if(!Object.hasOwn(l.tables,e))throw new S("BAD_REQUEST",`${t}: "${e}" is not a table in this schema`)},T=Do(l),x=new Map;for(const e of T){const t=i=>(l.tables[i]?.shardMode?.kind??"root")==="root";!e.array&&t(e.sourceTable)&&t(e.targetTable)&&x.set(e.sourceTable,[...x.get(e.sourceTable)??[],e])}const B=(e,t,i)=>{for(const d of x.get(e)??[]){const w=t[d.column];if(typeof w!="string"||i?.[d.column]===w||d.targetTable===e&&t._id===w)continue;if(K(y,a`SELECT 1 FROM ${a.identifier(d.targetTable)} WHERE id = ${w} LIMIT 1`).toArray().length===0)throw new S("VALIDATION_ERROR",`${d.name} references ${d.targetTable} row "${w}", which does not exist`)}},P=Wo(l,n.inTransaction),W=Pr(l),U=Ur(l),G=()=>n.inTransaction?.()===!0,ee=e=>l.tables[e]?.commitOrderedMode!==!0?{}:((c.value===void 0||!G())&&(c.value=zn(y)),{[Yn]:c.value}),N=(e,...t)=>{const i=l.tables[e]?.indexes??[],d=[];let w;for(const p of t)p&&(typeof p._id=="string"&&p._id!==w&&(w=p._id,d.push(Ao(w))),d.push(...Io(i,xo(i,p,Ce))));return d.length>0?d:void 0},R=n.onRead??(()=>{}),C=e=>{Ut(l.tables[e])&&R(Vt,Vt)},L=n.onReadRange??(e=>{R(e.table,j)}),F=e=>{C(e.table),L(e)},k=(e,t,i)=>{t!==void 0&&t!==j&&s?.recordRead(1),C(e),R(e,t,i)},pe=(e,t)=>{const i=e.row._id;k(e.tableName,typeof i=="string"?i:t,typeof i=="string")},te=n.onIndexUse??(()=>{}),ge=n.onWrite??(()=>{}),J=e=>{s?.recordWrite(e)},ye=async e=>{J(e.doc),await ge(e)},{cache:$e}=n,Ee=n.clock??(()=>Date.now()),Rt=n.idGenerator??(()=>crypto.randomUUID()),vt=n.scheduler??On,me=Vr(n.globalDb,s),ce=n.auth??{identity:null,userId:null},Tt=n.cdc??!1,Ze=vt,Mn=jo({scheduler:typeof Ze.list=="function"&&typeof Ze.get=="function"?Ze:void 0,storage:n.storage}),Se=(e,t,i,d)=>{Tt&&!Ut(l.tables[e])&&Vn(y,Ee(),e,t,i,d)},_t=(e,t,i,d)=>{const w=l.tables[e];if(w?.dropStalePatchesMode!==!0||!Tt)return!1;const p=r?.();if(p===void 0)return!1;const f=Jn(y,e,t,p);if(f===void 0)return!1;const h=go(w,i);return Object.keys(Ke(i)).some($=>!h.has($)&&Pt(Gt(f,$))!==Pt(Gt(d,$)))},ae=e=>l.tables[e]?.shardMode?.kind==="global",At=(e,t)=>{if(ae(e)){if(!me)throw new S("INTERNAL",`cross-backend ${t} for global table '${e}' requires a globalDb writer — pass one to createShardCtxDb({ globalDb })`);return me}return O},et=e=>At(e,"cascade"),H=(e,t)=>{if(ae(e)){if(!me)throw new S("INTERNAL",`${t} on global table '${e}' requires a globalDb writer — pass one to createShardCtxDb({ globalDb })`);return me}},It=async(e,t,i,d,w)=>{w&&J(i);const p=await e.insert(t,i,d);return D({key:p,op:"insert",row:{...i,_id:p},table:t}),p},tt=(e,t)=>At(e,"relation load").findMany(e,t),xt=(e,t)=>(ae(e)&&k(e,j),tt(e,t)),Dn=e=>!ae(e.table),bt=n.relationExistsPushDown??"auto",Ct=bt!=="never",{maxRelationKeys:Mt}=n,De=(e,t,i)=>Lo(e,{fetcher:xt,maxRelationKeys:Mt,relationBaseWhere:i,schema:l,tableName:t}),Dt=async(e,t,i,d)=>{const w=H(e,"relation grouped count");if(w)return k(e,j),Po((E,q)=>w.count(E,q),e,t,i,d);const p=l.tables[e];if(!p)throw new S("INTERNAL",`unknown table: ${e}`);k(e,j);const f=Ae(p.softDeleteMode,void 0),h={[t]:{in:i}},$=Q(Q(h,d),f),v=await De($,e,void 0),b=Z(v,ue),_=fe(t);let A=a`SELECT ${_} AS __fk__, COUNT(*) AS count FROM ${a.identifier(e)}`;b&&(A=a`${A} WHERE ${b}`),A=a`${A} GROUP BY ${_}`;const M=K(y,A).toArray();return new Map(M.map(E=>[E.__fk__,E.count]))},kt=new Set;for(const[e,t]of Object.entries(l.tables))for(const i of Object.values(t.triggerMap??{}))kt.add(`${e} ${i.timing} ${i.op}`);const ne=(e,t,i)=>kt.has(`${e} ${t} ${i}`),oe=async(e,t,i)=>{if(u.value+=1,u.value>on)throw u.value-=1,new se(`trigger recursion exceeded ${String(on)} levels on "${i.table}" — check for a self-triggering write`,"trigger");try{await Go({ctx:Wn,event:i,op:t,schema:l,tableName:i.table,timing:e})}finally{u.value-=1}},{ensureBackfilledForTable:Re,ensureBackfilledIndex:nt,ensureRankBackfilled:ot,ensureRankBackfilledForTable:ve,syncAggregates:ke,syncCompanionsForInsert:Lt,syncGeo:Le,syncRanks:Te,syncSearch:Fe}=Xn({broadcast:D,indexKeysFor:(e,t)=>N(e,t),invalidateCache:(e,t,i)=>$e?.invalidate(e,t,N(e,i)),recordCdc:Se,schema:l,sql:y,verified:n.companionMemo?.verified}),Ft=(e,t,i)=>{const{shardMode:d}=t;if(d?.kind==="shardBy"&&!(d.field!==void 0&&(i.partitionBy??[]).includes(d.field)))throw Object.assign(new Error(`rank index "${i.name}" on "${e}" partitions across shards (shard key "${d.field??"?"}" is not in partitionBy) — a shard-local rank()/rankPage() would be wrong; roll it up through the Query Coordinator instead`),{code:"CROSS_SHARD_RANK_UNSUPPORTED",name:"LunoraError",status:400})},Wt=e=>Object.entries(l.tables).filter(([,t])=>t.shardMode?.kind!=="global").map(([t])=>t).filter(t=>e===void 0||t===e),_e=e=>e===void 0||ae(e)?me:void 0,rt=async(e,t,i,d,w)=>{for(let p=0;p<i.length;p+=1)J(void 0);if(w!==void 0&&e.deleteMany!==void 0)return e.deleteMany(t,i,w.options);for(const p of i)await e.delete(t,p,d);return{deleted:i.length}},re=(e,t)=>{const i=Wt(t);for(let d=0;d<i.length;d+=rn){const w=i.slice(d,d+rn),[p]=he(y,gr(w),...yr(e,w)).toArray();if(!p)continue;const f=p.__t__,h=xe(p);if(typeof f!="string"||!h)return;const $=p[ie];return{docJson:typeof $=="string"?$:le($??{}),row:h,tableName:f}}},Bt={assertRankPartitionLocal:Ft,ensureRankBackfilled:ot,onRead:k,rowToDocument:xe,schema:l,sql:y},kn=(e,t,i)=>{const d=Z(i,ue);return d===void 0||K(y,a`SELECT 1 FROM ${a.identifier(e)} WHERE ${a.identifier("id")} = ${t} AND ${d}`).toArray().length>0},Ln=(e,t,i,d)=>_t(e,t,i,d)?(o?.({fields:Object.keys(Ke(i)),id:t,table:e}),!0):!1,Fn=async(e,t,i,d,w)=>{const p=re(t,e);if(!p)return{applied:!1,doc:null};if(k(e,t),!kn(e,t,i.where)||Ln(e,t,i.patch,p.row))return{applied:!1,doc:p.row};try{await w(i.patch)}catch(f){if(f instanceof se&&f.kind==="occ"&&d)return;throw f}return{applied:!0,doc:re(t,e)?.row??null}},qt=async(e,t,i,d)=>{const{fetchLimit:w,limit:p,orderKeys:f,predicate:h}=await Fo(t,i,{canPushExists:Ct?Dn:void 0,existsPushMode:bt==="always"?"always":"auto",fetcher:xt,maxRelationKeys:Mt,schema:l,tableName:e}),$=Ct?Mr(d):Ye,v=Z(h,$,ze),b=vn(e,v,Tn(f),w);return{limit:p,orderKeys:f,statement:b}},O={system:Mn,async aggregate(e,t){const i=H(e,"aggregate");if(i)return k(e,j),i.aggregate(e,t);const d=l.tables[e];if(!d)throw new S("INTERNAL",`unknown table: ${e}`);if(Pe(t.op),t.op==="count")return O.count(e,{baseWhere:t.baseWhere,relationBaseWhere:t.relationBaseWhere,restrictsCounts:t.restrictsCounts,where:t.where});if(!t.field)throw new S("INTERNAL",`aggregate(${e}, { op: "${t.op}" }): "field" is required for non-count reducers`);k(e,j);const w=Ae(d.softDeleteMode,void 0),p=Q(Q(t.baseWhere,t.where),w),f=await De(p,e,t.relationBaseWhere),h=f!==p;if(d.aggregateIndexes&&!t.baseWhere&&!h){const E=Kn(d.aggregateIndexes,t.op,t.field,t.where);if(E){nt(e,E.index);const q=st(E.index.by??[],E.key),Y=it(e,E.index.name),X=K(y,a`SELECT ${Ue} AS value, ${dt} AS count FROM ${a.identifier(Y)} WHERE ${Oe} = ${q}`).toArray()[0];return ct(t.op,X)}}an(d,t.field,`aggregate(${e}, { op: "${t.op}", field: "${t.field}" })`);const $=Z(f,ue),v=Pe(t.op),b=fe(t.field);let _=a`SELECT ${a.raw(v)}(${b}) AS value FROM ${a.identifier(e)}`;$&&(_=a`${_} WHERE ${$}`);const M=K(y,_).toArray()[0]?.value;return M??null},asId(e,t){const i=dn(l,e,t);if(i===null)throw new S("BAD_REQUEST",`asId("${e}", …): "${t}" is not a valid id for table "${e}"`,{status:400});return i},async count(e,t){const i=H(e,"count");if(i)return k(e,j),i.count(e,t);const d=l.tables[e];if(!d)throw new S("INTERNAL",`unknown table: ${e}`);const w=jn(t);if(w.restrictsCounts)throw new at(e);k(e,j);const p=Ae(d.softDeleteMode,void 0),f=Q(Q(w.baseWhere,w.where),p),h=await De(f,e,w.relationBaseWhere),$=h!==f;if(d.aggregateIndexes&&!w.baseWhere&&!$){const A=Hn(d.aggregateIndexes,w.where);if(A){nt(e,A.index);const M=st(A.index.by??[],A.key),E=it(e,A.index.name),q=K(y,a`SELECT ${Ue} AS value FROM ${a.identifier(E)} WHERE ${Oe} = ${M}`).toArray();return q[0]===void 0?0:q[0].value??0}}const v=Z(h,ue);let b=a`SELECT COUNT(*) AS count FROM ${a.identifier(e)}`;return v&&(b=a`${b} WHERE ${v}`),K(y,b).one().count},async delete(e,t,i){I(e,"ctx.db.delete(table, id)");const d=re(t,e);if(!d){const A=_e(e);A&&await rt(A,e,[t],i);return}const{docJson:w,row:p,tableName:f}=d,h=l.tables[f],$=i?.hard===!0,v=!$&&h?.softDeleteMode?h:void 0,b=v?.softDeleteMode?.field;if(b&&p[b]!==null&&p[b]!==void 0)return;if(ne(f,"before","delete")&&await oe("before","delete",{id:t,op:"delete",previous:p,table:f}),i?.skipOnDelete!==!0&&await qo({deletedId:t,deletedReference:A=>p[A],findHolders:async(A,M,E,q)=>(await et(A).findMany(A,{...q,includeDeleted:$,where:{[M]:E}})).page,onCascade:(A,M)=>et(A).delete(A,M,i),onRestrict:A=>{throw new se(A,"restrict")},onSetNull:(A,M,E)=>et(A).patch(A,M,{[E]:null}),schema:l,tableName:f}),Re(f),ve(f),v&&b){const A={[b]:Ee()},M={...p,...ee(f),...A,_id:t};ft(v,A,M,ce),Ne(y,f,tn(f),[le(M),t,w]),Fe(f,t,M,p),Le(f,t,void 0),ke(f,p,M),Te(f,t,p,void 0);const E=N(f,p,M);$e?.invalidate(f,t,E),Se(f,t,"update",M),D({indexKeys:E,key:t,op:"update",row:M,table:f}),ne(f,"after","delete")&&await oe("after","delete",{id:t,op:"delete",previous:p,table:f}),await ye({id:t,op:"delete",table:f});return}Ne(y,f,hr(f),[t,w]),Fe(f,t,void 0),Le(f,t,void 0),ke(f,p,void 0),Te(f,t,p,void 0);const _=N(f,p);$e?.invalidate(f,t,_),Se(f,t,"delete"),D({indexKeys:_,key:t,op:"delete",table:f}),ne(f,"after","delete")&&await oe("after","delete",{id:t,op:"delete",previous:p,table:f}),await ye({id:t,op:"delete",table:f})},async deleteAll(e,t){if(!l.tables[e])throw new S("INTERNAL",`unknown table: ${e}`);if(s!==void 0)return m().deleteAll(e,t);const i=Math.max(1,t?.chunkSize??mn),d=t?.hard===void 0?void 0:{hard:t.hard},w=H(e,"deleteAll");let p=0;for(;;){const h=(await O.findMany(e,{limit:i})).page.map($=>String($._id));if(h.length===0)break;for(const $ of h)await(w===void 0?O.delete(e,$,d):rt(w,e,[$],d)),p+=1;if(h.length<i)break}return{deleted:p}},async deleteMany(e,t,i){I(e,"ctx.db.deleteMany(table, ids)"),He(t.length,i?.limit,"deleteMany");for(const d of t)await O.delete(e,d);return{deleted:t.length}},async deleteWhere(e,t,i){const d=H(e,"deleteWhere"),p=(await sn(d??O,e,t,i?.limit,"deleteWhere")).map(f=>String(f._id));if(d)return rt(d,e,p,void 0,{options:i});if(O.deleteMany===void 0)throw new S("INTERNAL",`ctx.db.${e}.deleteMany is unavailable: this writer has no batch delete`);return O.deleteMany(e,p,i)},async findFirst(e,t={}){return(await O.findMany(e,{...t,limit:1,omitContinueCursor:!0})).page[0]??null},async findFirstOrThrow(e,t={}){const i=await O.findFirst(e,t);if(i===null)throw new ho(`findFirstOrThrow: no "${e}" document matched`);return i},async findMany(e,t={}){const i=H(e,"findMany");if(i)return k(e,j),i.findMany(e,t);const d=l.tables[e];if(!d)throw new S("INTERNAL",`unknown table: ${e}`);const w=!t.where&&!t.baseWhere;w?k(e,j):k(e);const{limit:p,orderKeys:f,statement:h}=await qt(e,d,t,k),$=he(y,h.text,...h.params).toArray();w&&s?.recordRead($.length);const v=[];for(const M of $){const E=xe(M);E&&(v.push(E),!w&&typeof E._id=="string"&&k(e,E._id))}if(p===void 0)return t.with&&await zt({groupedCounter:Dt,fetcher:tt,parents:v,...Yt(t),schema:l,tableName:e,with:t.with}),{continueCursor:null,isDone:!0,page:pt(v,t.select,t.with)};const b=v.length>p,_=b?v.slice(0,p):v,A=_.at(-1);return t.with&&await zt({fetcher:tt,groupedCounter:Dt,parents:_,...Yt(t),schema:l,tableName:e,with:t.with}),{continueCursor:b&&A&&t.omitContinueCursor!==!0?Qe(A,f):null,isDone:!b,page:pt(_,t.select,t.with)}},async explain(e,t={}){const i=H(e,"explain");if(i)return i.explain(e,t);const d=l.tables[e];if(!d)throw new S("INTERNAL",`unknown table: ${e}`);const{statement:w}=await qt(e,d,t,()=>{}),p=he(y,`EXPLAIN QUERY PLAN ${w.text}`,...w.params).toArray();return{params:w.params,plan:p.map(f=>String(f.detail)),sql:w.text}},async get(e,t){I(e,"ctx.db.get(table, id)");const i=re(t,e);if(!i){const d=_e(e);return d?d.get(e,t):(C(e),R(e,t,!0),null)}return pe(i,t),i.row},async lookupById(e,t){const i=re(e,t);if(!i){for(const d of Wt(t))C(d),R(d,e,!0);return null}return pe(i,e),{row:i.row,tableName:i.tableName}},async groupBy(e,t){const i=H(e,"groupBy");if(i)return k(e,j),i.groupBy(e,t);const d=l.tables[e];if(!d)throw new S("INTERNAL",`unknown table: ${e}`);k(e,j);const w=t.agg??{op:"count"};if(Pe(w.op),w.op!=="count"&&!w.field)throw new S("INTERNAL",`groupBy(${e}, { agg: { op: "${w.op}" } }): "field" is required for non-count reducers`);const p=Ae(d.softDeleteMode,void 0),f=Q(Q(t.baseWhere,t.where),p),h=await De(f,e,t.relationBaseWhere),$=h!==f;if(d.aggregateIndexes&&!t.baseWhere&&!$){const E=Gn(d.aggregateIndexes,w.op,w.field,t.by,t.where),q=E===void 0?0:Object.keys(E.partial).length,Y=E?.index.by?.length??0;if(E&&(q===0||q===Y)){nt(e,E.index);const X=it(e,E.index.name),V=Object.keys(E.partial),de=[];if(V.length===(E.index.by??[]).length&&V.length>0){const We=st(E.index.by??[],E.partial),Be=K(y,a`SELECT ${Ue} AS value, ${dt} AS count FROM ${a.identifier(X)} WHERE ${Oe} = ${We}`).toArray();return Be.length>0&&de.push({key:{...E.partial},value:ct(w.op,Be[0])}),de}const Bn=K(y,a`SELECT ${Oe} AS key, ${Ue} AS value, ${dt} AS count FROM ${a.identifier(X)}`).toArray();for(const We of Bn){const Be=Un(JSON.parse(We.key));de.push({key:Be,value:ct(w.op,We)})}return de}}for(const E of[...t.by,w.field]){if(E===void 0)continue;const q=E===w.field?`groupBy(${e}, { agg: { op: "${w.op}", field: "${E}" } })`:`groupBy(${e}, { by: [..."${E}"] })`;an(d,E,q)}const v=Z(h,ue),b=t.by.map(E=>a`${fe(E)} AS ${a.identifier(E)}`);if(w.op==="count")b.push(a`COUNT(*) AS value`);else{const{field:E}=w;if(E===void 0)throw new S("INTERNAL",`groupBy(${e}, { agg: { op: "${w.op}" } }): "field" is required for non-count reducers`);b.push(a`${a.raw(Pe(w.op))}(${fe(E)}) AS value`)}let _=a`SELECT ${a.join(b,a`, `)} FROM ${a.identifier(e)}`;v&&(_=a`${_} WHERE ${v}`),_=a`${_} GROUP BY ${a.join(t.by.map(E=>fe(E)),a`, `)}`;const A=K(y,_).toArray(),M=[];for(const E of A){const q={};for(const X of t.by)q[X]=to(d.shape[X],E[X]??null);const{value:Y}=E;M.push({key:q,value:Y==null?null:Number(Y)})}return M},async insert(e,t,i){const d=H(e,"insert");if(d)return It(d,e,t,i,!0);const w=l.tables[e];if(!w)throw new S("INTERNAL",`unknown table: ${e}`);const p=i?.allowExplicitId===!0,f=je(w,gt(w,t,ce),{supplied:t,trusted:p});let h;i?.clientId!==void 0?(Er(i.clientId),h=i.clientId):i?.allowExplicitId&&typeof f._id=="string"?($t(f._id),h=f._id):h=Rt();const $=i?.allowExplicitId&&typeof f._creationTime=="number"?f._creationTime:Ee(),v={...f,...ee(e),_creationTime:$,_id:h};return ne(e,"before","insert")&&await oe("before","insert",{doc:{...v},id:h,op:"insert",table:e}),p||B(e,v),Re(e),ve(e),Et(y,e,ur(e),[h,$,le(v)]),Lt(e,h,v),ne(e,"after","insert")&&await oe("after","insert",{doc:v,id:h,op:"insert",table:e}),await ye({doc:v,id:h,op:"insert",table:e}),h},async insertManyUnsafe(e,t,i){if(He(t.length,i?.limit,"insertManyUnsafe"),t.length===0)return[];const d=H(e,"insert");if(d){const $=[];mr(l.tables[e],t,i?.allowExplicitId,ce);for(const v of t)J(v);for(const v of t){const b=await d.insert(e,v,{allowExplicitId:i?.allowExplicitId});D({key:b,op:"insert",row:{...v,_id:b},table:e}),$.push(b)}return $}const w=l.tables[e];if(!w)throw new S("INTERNAL",`unknown table: ${e}`);Re(e),ve(e);const p=[];for(let $=0;$<t.length;$+=Ge)p.push(ee(e));const f=i?.allowExplicitId===!0?void 0:Bo(w),h=t.map(($,v)=>{const b=gt(w,$,ce),_=f===void 0?b:je(f,b,{supplied:$}),A=i?.allowExplicitId===!0&&typeof _._id=="string"?_._id:void 0;A!==void 0&&$t(A);const M=A??Rt(),E=i?.allowExplicitId===!0&&typeof _._creationTime=="number"?_._creationTime:Ee(),q={..._,...p[Math.floor(v/Ge)],_creationTime:E,_id:M};return{creationTime:E,document:q,id:M}});for(const $ of h)J($.document);for(let $=0;$<h.length;$+=Ge){const v=a.join(h.slice($,$+Ge).map(_=>a`(${_.id}, ${_.creationTime}, ${le(_.document)})`),a`, `),b=yn("sqlite",a`INSERT INTO ${a.identifier(e)} (id, _creationTime, ${a.identifier(ie)}) VALUES ${v}`);Et(y,e,b.sql,b.params)}for(const{document:$,id:v}of h)Lt(e,v,$),await ge({doc:$,id:v,op:"insert",table:e});return h.map($=>$.id)},async insertMany(e,t,i){He(t.length,i?.limit,"insertMany");const d=i?.skipDuplicates===!0,w=[],p=H(e,"insert");if(p)for(const h of t)J(h);const f=async h=>p?It(p,e,h,void 0,!1):O.insert(e,h);for(const h of t)try{w.push(await f(h))}catch($){if(d&&$ instanceof se&&$.kind==="unique")w.push(null);else throw $}return w},normalizeId(e,t){return dn(l,e,t)},async patch(e,t,i,d){I(e,"ctx.db.patch(table, id, values)");const w=re(t,e);if(!w){const M=_e(e);if(M){J(i),await M.patch(e,t,i,d);return}throw new S("NOT_FOUND",`document not found: ${t}`)}const{docJson:p,row:f,tableName:h}=w,$=l.tables[h];if(!$)throw new S("INTERNAL",`unknown table: ${h}`);if(k(h,t),un("patch",i),_t(h,t,i,f)){o?.({fields:Object.keys(Ke(i)),id:t,table:h});return}const v=wo($,i,f),b={...f,...Ke(v),...ee(h),_id:t};ft($,v,b,ce);const _=je($,b,{only:new Set(Object.keys(v)),previous:()=>f,tolerateStoredNull:!0});po(d,f,_),ne(h,"before","update")&&await oe("before","update",{doc:{..._},id:t,op:"update",previous:f,table:h}),B(h,_,f),Re(h),ve(h),Ne(y,h,tn(h),[le(_),t,p]),Fe(h,t,_,f),Le(h,t,_),ke(h,f,_),Te(h,t,f,_);const A=N(h,f,_);$e?.invalidate(h,t,A),Se(h,t,"update",_),D({indexKeys:A,key:t,op:"update",row:_,table:h}),ne(h,"after","update")&&await oe("after","update",{doc:_,id:t,op:"update",previous:f,table:h}),await ye({doc:_,id:t,op:"update",table:h})},async patchIf(e,t,i){const d=H(e,"patchIf");if(d){if(d.patchIf===void 0)throw new S("INTERNAL",`ctx.db.patchIf on global table '${e}' is unsupported: its backend has no conditional write`);return J(i.patch),d.patchIf(e,t,i)}if(!l.tables[e])throw new S("INTERNAL",`unknown table: ${e}`);for(let w=1;w<=ln;w+=1){const p=await Fn(e,t,i,w<ln,f=>O.patch(e,t,f,{verify:i.verify}));if(p!==void 0)return p}throw new se(`patchIf on "${e}" kept conflicting; the row changed on every attempt`,"occ")},async patchMany(e,t,i){I(e,"ctx.db.patchMany(table, patches)"),He(t.length,i?.limit,"patchMany");for(const d of t)await O.patch(e,d.id,d.patch);return{patched:t.length}},async patchWhere(e,t,i){const d=H(e,"patchWhere")??O,p=(await sn(d,e,t.where,i?.limit,"patchWhere")).map(f=>({id:String(f._id),patch:t.patch}));if(O.patchMany===void 0)throw new S("INTERNAL",`ctx.db.${e}.patchMany is unavailable: this writer has no batch patch`);return await O.patchMany(e,p,i),{patched:p.length}},async related(e,t){return ko(O,T,e,t)},relationEdges:T,deleteRereadTables:W,inTransaction:G,softDeleteFields:U,relationWrites:P,query(e){const t=H(e,"query");return t?(k(e,j),t.query(e)):xn(y,l,e,te,i=>{i?F(i):k(e,j)},i=>{s?.recordRead(i)})},async rank(e,t,i){const d=H(e,"rank");if(d)return k(e,j),d.rank(e,t,i);te(e,t,"rank");const w=l.tables[e];if(!w)throw new S("INTERNAL",`unknown table: ${e}`);const p=w.rankIndexes?.find(V=>V.name===t);if(!p)throw new S("INTERNAL",`unknown rankIndex "${t}" on table "${e}"`);if(Ft(e,w,p),i.restrictsCounts)throw new at(e);k(e,j),ot(e,p);const f=typeof i.row=="string"?i.row:i.row._id;if(!f)return null;const h=Nt(e,p.name),$=p.sortBy.map((V,de)=>Qt(de)),v=$.map(V=>Me(V)).join(", "),b=K(y,a`SELECT ${a.identifier("__partition__")}, ${a.raw(v)} FROM ${a.identifier(h)} WHERE ${a.identifier("__id__")} = ${f}`).toArray(),[_]=b;if(_===void 0)return null;let A=_.__partition__;const M=Q(i.baseWhere,i.where);lt(M,l,e,"rank");const E=Ro(p,M);if(E){const V=vo(p.partitionBy??[],E);if(V!==A)return null;A=V}const q=$.map(V=>_[V]),{before:Y,total:X}=hn(y,h,$,p.sortBy,A,q,f);return{position:Y+1,total:X}},async rankBefore(e,t,i){if(ae(e))throw new S("INTERNAL",`rankBefore is not supported on the global (.global()) table '${e}' — cross-shard rank cursors apply only to sharded tables`);const d=l.tables[e];if(!d)throw new S("INTERNAL",`unknown table: ${e}`);const w=d.rankIndexes?.find($=>$.name===t);if(!w)throw new S("INTERNAL",`unknown rankIndex "${t}" on table "${e}"`);if(i.restrictsCounts)throw new at(e);k(e,j),ot(e,w);const p=Nt(e,w.name),f=w.sortBy.map(($,v)=>Qt(v)),h=w.sortBy.map(($,v)=>Ce(i.sortValues[v]??null));return hn(y,p,f,w.sortBy,i.partitionKey,h,i.rowId)},async rankPage(e,t,i={}){lt(Q(i.baseWhere,i.where),l,e,"rankPage");const d=H(e,"rankPage");if(d)return k(e,j),d.rankPage(e,t,i);te(e,t,"rank");const{continueCursor:w,hasMore:p,rows:f}=Ot(Bt,e,t,i);return{continueCursor:w,isDone:!p,page:f.map(h=>h.doc)}},async rankPageRows(e,t,i={}){lt(Q(i.baseWhere,i.where),l,e,"rankPage"),te(e,t,"rank");const{directions:d,hasMore:w,rows:p}=Ot(Bt,e,t,i);return{directions:d,hasMore:w,rows:p}},async restore(e,t){I(e,"ctx.db.restore(table, id)");const i=re(t,e);if(!i){const p=_e(e);if(p?.restore){await p.restore(e,t);return}throw new S("NOT_FOUND",`document not found: ${t}`)}const d=l.tables[i.tableName]?.softDeleteMode?.field;if(!d)throw new S("INTERNAL",`ctx.db.restore: table "${i.tableName}" is not a .softDelete() table`);const w=i.row[d]!==null&&i.row[d]!==void 0;await O.patch(e,t,{[d]:null}),w&&Te(i.tableName,t,void 0,i.row)},async replace(e,t,i,d){I(e,"ctx.db.replace(table, id, document)");const w=re(t,e);if(!w){const q=_e(e);if(q){J(i),await q.replace(e,t,i,d);return}throw new S("NOT_FOUND",`document not found: ${t}`)}const{docJson:p,row:f,tableName:h}=w,$=l.tables[h];if(!$)throw new S("INTERNAL",`unknown table: ${h}`);un("replace",i);const v=d?.allowExplicitId&&typeof i._creationTime=="number"?i._creationTime:void 0,b=typeof f._creationTime=="number"?f._creationTime:void 0,_=v??b??Ee(),A={...i,...ee(h),_creationTime:_,_id:t};ft($,i,A,ce);const M=d?.allowExplicitId===!0,E=je($,A,{previous:()=>f,supplied:i,trusted:M});ne(h,"before","update")&&await oe("before","update",{doc:{...E},id:t,op:"update",previous:f,table:h}),M||B(h,E,f),Re(h),ve(h),Ne(y,h,fr(h),[_,le(E),t,p]),Fe(h,t,E,f),Le(h,t,E),ke(h,f,E),Te(h,t,f,E),$e?.invalidate(h,t,N(h,f,E)),Se(h,t,"update",E),D({indexKeys:N(h,f,E),key:t,op:"update",row:E,table:h}),ne(h,"after","update")&&await oe("after","update",{doc:E,id:t,op:"update",previous:f,table:h}),await ye({doc:E,id:t,op:"update",table:h})},async wipeShard(e){const t=new Set(e?.exclude),i=e?.tables,d=Object.entries(l.tables).filter(([h,$])=>t.has(h)||i!==void 0&&!i.includes(h)?!1:$.shardMode?.kind!=="global").map(([h])=>h);if(i!==void 0){for(const h of i)if(!l.tables[h])throw new S("INTERNAL",`wipeShard: unknown table: ${h}`)}const w={};let p=0;const{deleteAll:f}=O;if(f===void 0)throw new S("INTERNAL","wipeShard: this writer has no deleteAll");for(const h of d){const $=await f(h,{...e?.chunkSize===void 0?{}:{chunkSize:e.chunkSize},hard:!0});w[h]=$.deleted,p+=$.deleted}return{deleted:p,tables:w}}},Wn={db:O,scheduler:vt};return n.enforceRls===!0?Uo(O,l,(e,t)=>re(e,t)?.tableName,T):O};export{Oi as CDC_LOG_TABLE,ds as IDEMPOTENCY_TABLE,Dr as NotUniqueError,is as advanceClientWatermark,ji as applyCdcChanges,un as assertNoExplicitUndefined,$t as assertStorableRowId,Er as assertValidClientId,Bi as backfillAggregateIndexes,qi as backfillRankIndexes,Pi as backfillSearchIndexes,Gi as bumpCdcEpoch,Hi as cdcCanVouchFor,Ki as cdcForkedError,Ni as cdcSeqLeavingRows,Qi as cdcTouchesTables,Vi as cdcTrimmedError,Ji as compactCdcDocs,Jr as createShardCtxDb,zi as cursorBelowRetainedFloor,Gr as meterReadBytes,ss as migrateClientWatermark,Yi as minCdcReplayableSeq,Xi as minCdcSeq,dn as normalizeIdStructurally,Zi as readCdcChangeKeys,es as readCdcChanges,ts as readCdcCursor,ns as readCdcEpoch,cs as readClientWatermark,ls as readIdempotent,ws as runShardMigrations,gs as selectShapeMembers,ys as selectShapeRows,Ke as stripReservedPatchFields,os as trimCdcChanges,us as trimIdempotent,fs as writeIdempotent};
@@ -1 +1 @@
1
- import{stableWireKey as y}from"@lunora/wire";import{stableStringify as M,stableWireKey as T}from"@lunora/wire";import{depKey as l,SCAN_DEP as p}from"./SCAN_DEP-D7qE3iUe.mjs";import{e as m}from"./estimate-bytes-_k74s6LZ.mjs";import{isPointRange as x,keysTouchRanges as v}from"./buildIndexRange-BTChxh3k.mjs";const f=(o,t,e)=>{let s=o.get(t);return s===void 0&&(s=e(),o.set(t,s)),s},E=1e3,B=4*1024*1024;class A{entries=new Map;tableIndex=new Map;rangeIndex=new Map;totalBytes=0;hits=0;misses=0;evictions=0;maxEntries;maxBytes;now;monotonic=0;generation=0;constructor(t={}){this.maxEntries=t.maxEntries??E,this.maxBytes=t.maxBytes??B,this.now=t.now??(()=>(this.monotonic+=1,this.monotonic))}async run(t,e,s,i=()=>[]){const r=this.entries.get(t);if(r)return this.hits+=1,r.lastUsed=this.now(),this.entries.delete(t),this.entries.set(t,r),r.result;this.misses+=1;const c=this.generation,a=await s();if(this.generation!==c)return a;const h=m(a);if(h===void 0)return a;const b=i().filter(n=>!x(n)||!e.has(l(n.table,n.lo))),u={bytes:h,deps:e,ranges:b,lastUsed:this.now(),result:a,subscribers:new Set},d=this.entries.get(t);if(d){this.dropEntry(t,d);for(const n of d.subscribers)u.subscribers.add(n)}this.entries.set(t,u),this.totalBytes+=h;for(const n of e)f(this.tableIndex,n,()=>new Set).add(t);for(const n of b){const g=f(this.rangeIndex,n.table,()=>new Map);f(g,n,()=>new Set).add(t)}return this.evict(),a}invalidate(t,e,s){this.generation+=1;const i=[];return this.collectAndDrop(l(t,e),i),this.collectAndDrop(l(t,p),i),this.dropRangeDeps(t,s,i),i}invalidateTable(t){this.generation+=1;const e=[],s=`${t}:`;for(const i of this.tableIndex.keys())i.startsWith(s)&&this.collectAndDrop(i,e);return this.dropRangeDeps(t,void 0,e),e}subscribe(t,e){const s=this.entries.get(t);s&&s.subscribers.add(e)}unsubscribe(t,e){const s=this.entries.get(t);s&&s.subscribers.delete(e)}size(){return{bytes:this.totalBytes,entries:this.entries.size}}clear(){this.generation+=1,this.entries.clear(),this.tableIndex.clear(),this.rangeIndex.clear(),this.totalBytes=0}subscribers(t){const e=this.entries.get(t);return e?[...e.subscribers]:[]}stats(){return{bytes:this.totalBytes,entries:this.entries.size,evictions:this.evictions,hits:this.hits,misses:this.misses}}dropRangeDeps(t,e,s){const i=this.rangeIndex.get(t);if(!(!i||i.size===0))for(const[r,c]of i)v([r],e)&&this.dropKeys(c,s)}collectAndDrop(t,e){const s=this.tableIndex.get(t);s&&this.dropKeys(s,e)}dropKeys(t,e){for(const s of t){const i=this.entries.get(s);i&&(this.dropEntry(s,i),e.push(s))}}dropEntry(t,e){this.entries.delete(t),this.totalBytes-=e.bytes;for(const s of e.deps){const i=this.tableIndex.get(s);i&&(i.delete(t),i.size===0&&this.tableIndex.delete(s))}for(const s of e.ranges){const i=this.rangeIndex.get(s.table),r=i?.get(s);r?.delete(t),i&&r?.size===0&&(i.delete(s),i.size===0&&this.rangeIndex.delete(s.table))}}evict(){if(!(this.entries.size<=this.maxEntries&&this.totalBytes<=this.maxBytes))for(const[t,e]of this.entries){if(this.entries.size<=this.maxEntries&&this.totalBytes<=this.maxBytes)return;e.subscribers.size>0||(this.dropEntry(t,e),this.evictions+=1)}}}const D=(o,t,e)=>`${e??"\0anon"}\0${o}:${y(t)}`;export{A as ReactiveCache,D as reactiveCacheKey,M as stableStringify,T as stableWireKey};
1
+ import{stableWireKey as y}from"@lunora/wire";import{stableStringify as M,stableWireKey as T}from"@lunora/wire";import{depKey as l,SCAN_DEP as p}from"./SCAN_DEP-D7qE3iUe.mjs";import{e as m}from"./estimate-bytes-C-C35VXL.mjs";import{isPointRange as x,keysTouchRanges as v}from"./buildIndexRange-BTChxh3k.mjs";const f=(o,t,e)=>{let s=o.get(t);return s===void 0&&(s=e(),o.set(t,s)),s},E=1e3,B=4*1024*1024;class A{entries=new Map;tableIndex=new Map;rangeIndex=new Map;totalBytes=0;hits=0;misses=0;evictions=0;maxEntries;maxBytes;now;monotonic=0;generation=0;constructor(t={}){this.maxEntries=t.maxEntries??E,this.maxBytes=t.maxBytes??B,this.now=t.now??(()=>(this.monotonic+=1,this.monotonic))}async run(t,e,s,i=()=>[]){const r=this.entries.get(t);if(r)return this.hits+=1,r.lastUsed=this.now(),this.entries.delete(t),this.entries.set(t,r),r.result;this.misses+=1;const c=this.generation,a=await s();if(this.generation!==c)return a;const h=m(a);if(h===void 0)return a;const b=i().filter(n=>!x(n)||!e.has(l(n.table,n.lo))),u={bytes:h,deps:e,ranges:b,lastUsed:this.now(),result:a,subscribers:new Set},d=this.entries.get(t);if(d){this.dropEntry(t,d);for(const n of d.subscribers)u.subscribers.add(n)}this.entries.set(t,u),this.totalBytes+=h;for(const n of e)f(this.tableIndex,n,()=>new Set).add(t);for(const n of b){const g=f(this.rangeIndex,n.table,()=>new Map);f(g,n,()=>new Set).add(t)}return this.evict(),a}invalidate(t,e,s){this.generation+=1;const i=[];return this.collectAndDrop(l(t,e),i),this.collectAndDrop(l(t,p),i),this.dropRangeDeps(t,s,i),i}invalidateTable(t){this.generation+=1;const e=[],s=`${t}:`;for(const i of this.tableIndex.keys())i.startsWith(s)&&this.collectAndDrop(i,e);return this.dropRangeDeps(t,void 0,e),e}subscribe(t,e){const s=this.entries.get(t);s&&s.subscribers.add(e)}unsubscribe(t,e){const s=this.entries.get(t);s&&s.subscribers.delete(e)}size(){return{bytes:this.totalBytes,entries:this.entries.size}}clear(){this.generation+=1,this.entries.clear(),this.tableIndex.clear(),this.rangeIndex.clear(),this.totalBytes=0}subscribers(t){const e=this.entries.get(t);return e?[...e.subscribers]:[]}stats(){return{bytes:this.totalBytes,entries:this.entries.size,evictions:this.evictions,hits:this.hits,misses:this.misses}}dropRangeDeps(t,e,s){const i=this.rangeIndex.get(t);if(!(!i||i.size===0))for(const[r,c]of i)v([r],e)&&this.dropKeys(c,s)}collectAndDrop(t,e){const s=this.tableIndex.get(t);s&&this.dropKeys(s,e)}dropKeys(t,e){for(const s of t){const i=this.entries.get(s);i&&(this.dropEntry(s,i),e.push(s))}}dropEntry(t,e){this.entries.delete(t),this.totalBytes-=e.bytes;for(const s of e.deps){const i=this.tableIndex.get(s);i&&(i.delete(t),i.size===0&&this.tableIndex.delete(s))}for(const s of e.ranges){const i=this.rangeIndex.get(s.table),r=i?.get(s);r?.delete(t),i&&r?.size===0&&(i.delete(s),i.size===0&&this.rangeIndex.delete(s.table))}}evict(){if(!(this.entries.size<=this.maxEntries&&this.totalBytes<=this.maxBytes))for(const[t,e]of this.entries){if(this.entries.size<=this.maxEntries&&this.totalBytes<=this.maxBytes)return;e.subscribers.size>0||(this.dropEntry(t,e),this.evictions+=1)}}}const D=(o,t,e)=>`${e??"\0anon"}\0${o}:${y(t)}`;export{A as ReactiveCache,D as reactiveCacheKey,M as stableStringify,T as stableWireKey};
@@ -0,0 +1,18 @@
1
+ import{LunoraError as $}from"@lunora/errors";import{isPlainObject as S}from"@lunora/wire";import{sql as n}from"drizzle-orm";import{runDrizzle as d}from"./runDrizzle-RC09zZrh.mjs";const a="__schedule_outbox",h=t=>{d(t,n`CREATE TABLE IF NOT EXISTS ${n.identifier(a)} (
2
+ id TEXT PRIMARY KEY,
3
+ envelope_json TEXT NOT NULL,
4
+ attempts INTEGER NOT NULL,
5
+ next_attempt_at REAL NOT NULL,
6
+ created_at REAL NOT NULL,
7
+ dead INTEGER NOT NULL DEFAULT 0
8
+ )`),d(t,n`CREATE INDEX IF NOT EXISTS ${n.identifier(`${a}_due`)} ON ${n.identifier(a)} (dead, next_attempt_at)`),d(t,n`CREATE INDEX IF NOT EXISTS ${n.identifier(`${a}_age`)} ON ${n.identifier(a)} (created_at, id)`)},L=(t,e,r,o)=>{d(t,n`INSERT OR REPLACE INTO ${n.identifier(a)} (id, envelope_json, attempts, next_attempt_at, created_at, dead)
9
+ VALUES (${e}, ${r}, 0, ${o}, ${o}, 0)`)},A=(t,e)=>{d(t,n`DELETE FROM ${n.identifier(a)} WHERE id = ${e}`)},b=(t,e,r)=>d(t,n`SELECT id, envelope_json, attempts, next_attempt_at FROM ${n.identifier(a)}
10
+ WHERE dead = 0 AND next_attempt_at <= ${e}
11
+ ORDER BY next_attempt_at ASC LIMIT ${r}`).toArray().map(E=>({attempts:E.attempts,envelopeJson:E.envelope_json,id:E.id,nextAttemptAt:E.next_attempt_at})),D=(t,e,r)=>{const o=d(t,n`SELECT id, envelope_json, attempts, next_attempt_at FROM ${n.identifier(a)}
12
+ WHERE id = ${e} AND dead = 0 AND next_attempt_at <= ${r}`).toArray()[0];return o===void 0?void 0:{attempts:o.attempts,envelopeJson:o.envelope_json,id:o.id,nextAttemptAt:o.next_attempt_at}},j=(t,e,r,o)=>{d(t,n`UPDATE ${n.identifier(a)} SET attempts = ${r}, next_attempt_at = ${o} WHERE id = ${e}`)},y=(t,e,r,o)=>{d(t,n`UPDATE ${n.identifier(a)} SET attempts = ${r}, next_attempt_at = ${o}, dead = 1 WHERE id = ${e}`)},C=t=>{const r=d(t,n`SELECT MIN(CASE WHEN dead = 0 THEN next_attempt_at END) AS due, COUNT(*) AS total FROM ${n.identifier(a)}`).toArray()[0];return{dueAt:r?.due??void 0,populated:(r?.total??0)>0}},H=(t,e)=>{d(t,n`DELETE FROM ${n.identifier(a)} WHERE dead = 1 AND next_attempt_at < ${e}`)},N=t=>{if(typeof t=="string")return t;if(S(t))return typeof t.__lunoraRef=="string"?t.__lunoraRef:typeof t.className=="string"?t.className:void 0},T=t=>{let e;if(t.target_type==="text")e=t.target;else if(t.target_type==="object"&&typeof t.target=="string")try{e=JSON.parse(t.target)}catch{e=void 0}return{attempts:t.attempts,createdAt:t.created_at,forever:t.forever===1,id:t.id,nextAttemptAt:t.next_attempt_at,parked:t.dead===1,target:N(e),when:typeof t.when_ts=="number"?t.when_ts:void 0}},m=/^(\d+(?:\.\d+)?):(.+)$/su,f=t=>`${String(t.createdAt)}:${t.id}`,O=t=>{const e=m.exec(t);if(e!==null)return{createdAt:Number(e[1]),id:e[2]}},g=(t,e,r)=>{const o=r===void 0?void 0:O(r);if(r!==void 0&&o===void 0)throw new $("BAD_REQUEST",`getScheduleOutbox: malformed cursor ${JSON.stringify(r)}`);const E=o===void 0?n``:n`WHERE (created_at, id) > (${o.createdAt}, ${o.id})`,i=n`(CASE WHEN json_valid(envelope_json) THEN envelope_json END)`,s=d(t,n`SELECT id, attempts, next_attempt_at, created_at, dead,
13
+ CASE WHEN json_type(${i}) = 'object' THEN json_type(${i}, '$.target') END AS target_type,
14
+ CASE WHEN json_type(${i}) = 'object' AND json_type(${i}, '$.target') IN ('text', 'object') THEN json_extract(${i}, '$.target') END AS target,
15
+ CASE WHEN json_type(${i}) = 'object' AND json_type(${i}, '$.when') IN ('integer', 'real') THEN json_extract(${i}, '$.when') END AS when_ts,
16
+ CASE WHEN json_type(${i}) = 'object' AND json_type(${i}, '$.options.retry.forever') = 'true' THEN 1 ELSE 0 END AS forever
17
+ FROM ${n.identifier(a)}
18
+ ${E} ORDER BY created_at ASC, id ASC LIMIT ${e+1}`).toArray(),_=s.slice(0,e).map(u=>T(u)),c=_.at(-1);return{entries:_,nextCursor:s.length>e&&c!==void 0?f(c):void 0}},I=(t,e)=>{const r=d(t,n`SELECT created_at, envelope_json, dead FROM ${n.identifier(a)} WHERE id = ${e}`).toArray()[0];return r===void 0?void 0:{createdAt:r.created_at,parked:r.dead===1,version:`${String(r.created_at)}:${r.envelope_json}`}},p=(t,e)=>d(t,n`SELECT id FROM ${n.identifier(a)} WHERE id = ${e}`).toArray().length>0,U=(t,e,r)=>p(t,e)?(d(t,n`UPDATE ${n.identifier(a)} SET attempts = 0, next_attempt_at = ${r}, dead = 0 WHERE id = ${e}`),!0):!1,W=(t,e)=>p(t,e)?(A(t,e),!0):!1;export{a as SCHEDULE_OUTBOX_TABLE,j as deferScheduleOutbox,W as dropScheduleOutbox,A as forgetScheduleOutbox,p as hasScheduleOutboxEntry,h as migrateScheduleOutbox,y as parkScheduleOutbox,C as probeScheduleOutbox,b as readDueScheduleOutbox,D as readDueScheduleOutboxEntry,g as readScheduleOutbox,I as readScheduleOutboxState,L as recordScheduleOutbox,U as requeueScheduleOutbox,H as trimScheduleOutbox};
@@ -1 +1 @@
1
- import{isLunoraError as S}from"@lunora/errors";import{l as R,b as L}from"./ctx-db-search-state-CPKPy8N6.mjs";import{sql as e}from"drizzle-orm";import{readKeysetPage as _}from"./backfillAggregateIndexes-CRNxxM19.mjs";import{runDrizzle as p}from"./runDrizzle-RC09zZrh.mjs";import{h}from"./do-sql-RROYQPCM.mjs";const u="__lunora_vector_backfill",m=50,k=20,w=20,N=3,O=i=>{p(i,e`CREATE TABLE IF NOT EXISTS ${e.identifier(u)} (${e.identifier("companion")} TEXT PRIMARY KEY, ${e.identifier("cursor")} TEXT, ${e.identifier("done")} INTEGER NOT NULL DEFAULT 0, ${e.identifier("profile")} TEXT, ${e.identifier("strikes")} INTEGER NOT NULL DEFAULT 0)`);try{p(i,e`ALTER TABLE ${e.identifier(u)} ADD COLUMN ${e.identifier("strikes")} INTEGER NOT NULL DEFAULT 0`)}catch{}},C=(i,o)=>{const[s]=p(i,e`SELECT ${e.identifier("strikes")} FROM ${e.identifier(u)} WHERE ${e.identifier("companion")} = ${o}`).toArray();return s?.strikes??0},$=(i,o,s,d,t,r=0)=>{const n=s??null;p(i,e`INSERT INTO ${e.identifier(u)} (${e.identifier("companion")}, ${e.identifier("cursor")}, ${e.identifier("done")}, ${e.identifier("profile")}, ${e.identifier("strikes")}) VALUES (${o}, ${n}, ${d?1:0}, ${t}, ${r}) ON CONFLICT (${e.identifier("companion")}) DO UPDATE SET ${e.identifier("cursor")} = excluded.${e.identifier("cursor")}, ${e.identifier("done")} = excluded.${e.identifier("done")}, ${e.identifier("profile")} = excluded.${e.identifier("profile")}, ${e.identifier("strikes")} = excluded.${e.identifier("strikes")}`)},A=(i,o,s)=>{const d=_(i,o,s,m+1),t={documents:[],lastId:s,more:d.length>m,unparseable:[]};for(const r of d.slice(0,m)){if(typeof r.id!="string")continue;t.lastId=r.id;const n=h(r);n?t.documents.push({doc:n,id:t.lastId}):t.unparseable.push(t.lastId)}return t},D=(i,o,s,d,t)=>{const r=t instanceof Error?t.message:String(t),n=L(i,u,o),a=n.profile===d&&n.cursor===s?C(i,o):0;if(S(t)&&t.code==="SERVICE_UNAVAILABLE")return a>0&&$(i,o,s,!1,d,0),{error:r};const f=a+1;if(f<N)return $(i,o,s,!1,d,f),{error:r};const c=A(i,o,s),l=[...c.documents.map(E=>E.id),...c.unparseable];return console.warn(`[@lunora/shard-engine] vector backfill: a page of "${o}" failed ${String(f)} times in a row; its ${String(l.length)} row(s) are recorded as failed:`,t),{failedIds:l,page:c}},F=async(i,o,s,d,t)=>{const{profile:r,table:n}=o;try{const{failures:a,page:f}=await t(()=>A(i,n,s),async c=>({failures:await d(n,c.documents),page:c}));return a.length>0&&console.warn(`[@lunora/shard-engine] vector backfill: ${String(a.length)} row(s) of "${n}" could not be indexed:`,a),{failedIds:[...f.unparseable,...a.map(c=>c.id)],page:f}}catch(a){return D(i,n,s,r,a)}},y=async(i,o,s,d)=>{if(O(i),d.restart===!0)for(const{profile:n,table:a}of o)$(i,a,void 0,!1,n);const t=Math.min(d.maxPages??1,k),r={done:!1,failed:0,failedIds:[],pages:0,rows:0};for(const{profile:n,table:a}of o){const f=R(L(i,u,a),n);let{cursor:c}=f,l=f.finished;for(;!l;){if(r.pages>=t)return r;const E=await F(i,{profile:n,table:a},c,s,d.ordered);if("error"in E)return{...r,error:E.error};const{failedIds:g,page:T}=E,I=T.documents.length+T.unparseable.length;r.pages+=I>0?1:0,r.rows+=I,r.failed+=g.length,r.failedIds=[...r.failedIds,...g].slice(0,w),c=T.lastId,l=!T.more,$(i,a,c,l,n)}}return{...r,done:!0}};export{k as VECTOR_BACKFILL_MAX_PAGES,m as VECTOR_BACKFILL_PAGE_ROWS,y as backfillVectorIndexes};
1
+ import{isLunoraError as S}from"@lunora/errors";import{l as R,b as L}from"./ctx-db-search-state-CPKPy8N6.mjs";import{sql as e}from"drizzle-orm";import{readKeysetPage as _}from"./backfillAggregateIndexes-Pk0KLrfk.mjs";import{runDrizzle as p}from"./runDrizzle-RC09zZrh.mjs";import{h}from"./do-sql-105TONaE.mjs";const u="__lunora_vector_backfill",m=50,k=20,w=20,N=3,O=i=>{p(i,e`CREATE TABLE IF NOT EXISTS ${e.identifier(u)} (${e.identifier("companion")} TEXT PRIMARY KEY, ${e.identifier("cursor")} TEXT, ${e.identifier("done")} INTEGER NOT NULL DEFAULT 0, ${e.identifier("profile")} TEXT, ${e.identifier("strikes")} INTEGER NOT NULL DEFAULT 0)`);try{p(i,e`ALTER TABLE ${e.identifier(u)} ADD COLUMN ${e.identifier("strikes")} INTEGER NOT NULL DEFAULT 0`)}catch{}},C=(i,o)=>{const[s]=p(i,e`SELECT ${e.identifier("strikes")} FROM ${e.identifier(u)} WHERE ${e.identifier("companion")} = ${o}`).toArray();return s?.strikes??0},$=(i,o,s,d,t,r=0)=>{const n=s??null;p(i,e`INSERT INTO ${e.identifier(u)} (${e.identifier("companion")}, ${e.identifier("cursor")}, ${e.identifier("done")}, ${e.identifier("profile")}, ${e.identifier("strikes")}) VALUES (${o}, ${n}, ${d?1:0}, ${t}, ${r}) ON CONFLICT (${e.identifier("companion")}) DO UPDATE SET ${e.identifier("cursor")} = excluded.${e.identifier("cursor")}, ${e.identifier("done")} = excluded.${e.identifier("done")}, ${e.identifier("profile")} = excluded.${e.identifier("profile")}, ${e.identifier("strikes")} = excluded.${e.identifier("strikes")}`)},A=(i,o,s)=>{const d=_(i,o,s,m+1),t={documents:[],lastId:s,more:d.length>m,unparseable:[]};for(const r of d.slice(0,m)){if(typeof r.id!="string")continue;t.lastId=r.id;const n=h(r);n?t.documents.push({doc:n,id:t.lastId}):t.unparseable.push(t.lastId)}return t},D=(i,o,s,d,t)=>{const r=t instanceof Error?t.message:String(t),n=L(i,u,o),a=n.profile===d&&n.cursor===s?C(i,o):0;if(S(t)&&t.code==="SERVICE_UNAVAILABLE")return a>0&&$(i,o,s,!1,d,0),{error:r};const f=a+1;if(f<N)return $(i,o,s,!1,d,f),{error:r};const c=A(i,o,s),l=[...c.documents.map(E=>E.id),...c.unparseable];return console.warn(`[@lunora/shard-engine] vector backfill: a page of "${o}" failed ${String(f)} times in a row; its ${String(l.length)} row(s) are recorded as failed:`,t),{failedIds:l,page:c}},F=async(i,o,s,d,t)=>{const{profile:r,table:n}=o;try{const{failures:a,page:f}=await t(()=>A(i,n,s),async c=>({failures:await d(n,c.documents),page:c}));return a.length>0&&console.warn(`[@lunora/shard-engine] vector backfill: ${String(a.length)} row(s) of "${n}" could not be indexed:`,a),{failedIds:[...f.unparseable,...a.map(c=>c.id)],page:f}}catch(a){return D(i,n,s,r,a)}},y=async(i,o,s,d)=>{if(O(i),d.restart===!0)for(const{profile:n,table:a}of o)$(i,a,void 0,!1,n);const t=Math.min(d.maxPages??1,k),r={done:!1,failed:0,failedIds:[],pages:0,rows:0};for(const{profile:n,table:a}of o){const f=R(L(i,u,a),n);let{cursor:c}=f,l=f.finished;for(;!l;){if(r.pages>=t)return r;const E=await F(i,{profile:n,table:a},c,s,d.ordered);if("error"in E)return{...r,error:E.error};const{failedIds:g,page:T}=E,I=T.documents.length+T.unparseable.length;r.pages+=I>0?1:0,r.rows+=I,r.failed+=g.length,r.failedIds=[...r.failedIds,...g].slice(0,w),c=T.lastId,l=!T.more,$(i,a,c,l,n)}}return{...r,done:!0}};export{k as VECTOR_BACKFILL_MAX_PAGES,m as VECTOR_BACKFILL_PAGE_ROWS,y as backfillVectorIndexes};
@@ -1 +1 @@
1
- import{LunoraError as S}from"@lunora/errors";import{t as z}from"./do-sql-RROYQPCM.mjs";import{applySelect as Y}from"./CURSOR_PREFIX-6offuG6M.mjs";const U=Symbol.for("lunora.relations.fanOutBudget"),de=e=>({fanOutBudget:e[U],relationBaseWhere:e.relationBaseWhere,relationMask:e.relationMask}),L=(e,t)=>t.select?Y(e,t.select,t.with):e,pe=async(e,t,n,r,o)=>{const a=await Promise.all(r.map(async c=>{const u=o?{AND:[{[n]:c},o]}:{[n]:c};return[c,await e(t,u)]}));return new Map(a)},ee=32,B=1e4,te=(e,t,n)=>{const r=new Map;for(const o of e)for(const a of n(o)){const c=a[t],u=r.get(c);u?u.push(a):r.set(c,[a])}return r},W=(e,t)=>({...e,[U]:t}),ne=(e,t)=>{const n=new Map;for(const[o,a]of e)for(const c of a){const u=n.get(c);u?u.push(o):n.set(c,[o])}const r=new Map;for(const o of t)for(const a of n.get(o._id)??[]){const c=r.get(a);c?c.push(o):r.set(a,[o])}return r},D=(e,t)=>{const n=new Set;for(const r of e){const o=r[t];o!=null&&n.add(o)}return[...n]},he=async e=>{const{groupedCounter:t,fanOutBudget:n,fetcher:r,parents:o,relationBaseWhere:a,relationMask:c,schema:u,tableName:p,with:b}=e,O=n??{remaining:ee},y=(f,s)=>c?.(f,s)??s;if(o.length===0)return;const M=u.tables[p];if(!M)throw new S("INTERNAL",`unknown table: ${p}`);const _=M.relationMap??{},G=(f,s)=>{const i=d=>u.tables[d]?.shardMode?.kind??"root";return i(f)===i(s)&&i(f)!=="shardBy"},R=f=>{const s=_[f];if(!s)throw new S("INTERNAL",`unknown relation "${f}" on table "${p}"`);return s},X=async(f,s,i)=>{const d=D(o,s.field);if(d.length===0){for(const h of o)h[f]=null;return}const{page:l}=await r(s.table,W({baseWhere:a?.(s.table),relationBaseWhere:a,relationMask:c,where:{[s.references]:{in:d}},with:i.with},O)),w=new Map;for(const h of y(s.table,l))w.set(h[s.references],h);for(const h of o){const A=w.get(h[s.field]);h[f]=A?L([A],i)[0]??null:null}},j=async(f,s,i,d)=>{const{page:l}=await r(f,W({baseWhere:a?.(f),limit:d,orderBy:s.orderBy,relationBaseWhere:a,relationMask:c,where:s.where?{AND:[s.where,i]}:i,with:s.with},O));return l},T=(f,s,i,d,l)=>{for(const w of o){const h=l.get(w[d])??[];w[f]=L(i===void 0?h:h.slice(0,i),s)}},K=async(f,s,i)=>{const d=D(o,s.references);if(d.length===0){for(const g of o)g[f]=[];return}const l=typeof i.limit=="number"?Math.max(0,Math.floor(i.limit)):void 0,w=(g,k)=>j(s.table,i,g,k);if(l===0){for(const g of o)g[f]=[];return}const h=l!==void 0&&d.length<=O.remaining;h&&(O.remaining-=d.length);const A=h?await Promise.all(d.map(async g=>w({[s.field]:g},l))):[await w({[s.field]:{in:d}},void 0)],m=te(A,s.field,g=>y(s.table,g));T(f,i,l,s.references,m)},I=async f=>{const{from:s,table:i,to:d}=f.through,l=new Map,w=D(o,"_id");if(w.length===0)return l;const h=await j(i,{},{[s]:{in:w}},B+1);if(h.length>B)throw new S("INTERNAL",`loading "${p}" relations through "${i}" read more than ${String(B)} join rows for one page; load fewer ${p} rows at a time`);for(const A of y(i,h)){const m=A[s],g=A[d];if(m==null||g===null||g===void 0)continue;const k=l.get(m);k?k.add(g):l.set(m,new Set([g]))}return l},q=async(f,s,i)=>{const d=typeof i.limit=="number"?Math.max(0,Math.floor(i.limit)):void 0,l=d===0?new Map:await I(s),w=(A,m)=>j(s.table,i,{_id:{in:[...A]}},m);let h=new Map;if(l.size>0&&d!==void 0&&l.size<=O.remaining){O.remaining-=l.size;const A=[...l.keys()],m=await Promise.all([...l.values()].map(async g=>w(g,d)));h=new Map(A.map((g,k)=>[g,y(s.table,m[k]??[])]))}else if(l.size>0){const A=new Set([...l.values()].flatMap(m=>[...m]));h=ne(l,y(s.table,await w(A,void 0)))}T(f,i,d,"_id",h)},Z=async(f,s)=>{const i=[...s];if(i.length===0)return new Set;if(G(p,f)){const l=await t(f,"_id",i,a?.(f));return new Set(i.filter(w=>(l.get(w)??0)>0))}const d=await j(f,{},{_id:{in:i}},void 0);return new Set(d.map(l=>l._id))},J=async(f,s)=>{const i=await I(s),d=await Z(s.table,new Set([...i.values()].flatMap(l=>[...l])));for(const l of o){const w=l._count??{};w[f]=[...i.get(l._id)??[]].filter(h=>d.has(h)).length,l._count=w}},Q=async f=>{for(const s of Object.keys(f)){const i=R(s);if(i.through!==void 0){await J(s,i);continue}const[d,l]=i.kind==="many"?[i.field,i.references]:[i.references,i.field],w=a?.(i.table),h=D(o,l),A=h.length===0?new Map:await t(i.table,d,h,w);for(const m of o){const g=m._count??{},k=m[l];g[s]=k==null?0:A.get(k)??0,m._count=g}}};for(const[f,s]of Object.entries(b)){if(s===void 0||s===!1)continue;if(f==="_count"){await Q(s);continue}const i=R(f),d=s===!0?{}:s;i.through===void 0?await(i.kind==="one"?X(f,i,d):K(f,i,d)):await q(f,i,d)}},N=1e4,x=500,oe=async(e,t,n,r,o)=>{const a=new Set;let c=o;for(;;){const u=c!==void 0,p=c??await e();let b=!1;c=void 0;for(const O of p){const y=O._id;if(!(typeof y!="string"||a.has(y))){if(a.add(y),b=!0,a.size>N)throw n();await t(y)}}if(!u){if(p.length<x)return;if(!b)throw new S("INTERNAL",r)}}},H=(e,t,n)=>new S("CASCADE_LIMIT",`cannot delete "${e}" row: more than ${String(N)} ${t} rows reference it (onDelete: ${n}) — delete or re-point them in batches first`,{status:400}),re=async(e,t,n,r)=>{const{deletedId:o,deletedReference:a,findHolders:c,onRestrict:u,tableName:p}=e,b=n.references==="_id"?o:a(n.references);if(b==null)return;const{field:O}=n,y=`"${t}.${O}"`,M=await c(t,O,b,{limit:r==="restrict"?1:N+1,select:["_id"]});if(M.length!==0){if(r==="restrict")return u(`cannot delete "${p}" row: ${y} still references it`);if(M.length>N)throw H(p,y,r);return{action:r,field:O,holderTable:t,label:y,probe:M,referencedValue:b}}},se=async(e,t,n)=>{const{findHolders:r,onCascade:o,onSetNull:a,tableName:c}=e,{action:u,field:p,holderTable:b,label:O,probe:y,referencedValue:M}=t;await oe(()=>r(b,p,M,{limit:x}),_=>u==="cascade"?o(b,_):a(b,_,p),()=>H(c,O,u),`onDelete on "${c}" made no progress: ${O} rows still match after being processed`,n?y:void 0)},we=async e=>{const{schema:t,tableName:n}=e;if(!t.tables[n])throw new S("INTERNAL",`unknown table: ${n}`);const r=[];for(const[o,a]of Object.entries(t.tables)){const c=a.relationMap;if(c)for(const u of Object.values(c)){if(u.kind!=="one"||u.table!==n||!u.onDelete)continue;const p=await re(e,o,u,u.onDelete);p&&r.push(p)}}for(const[o,a]of r.entries())await se(e,a,o===0)},P=new WeakMap,V=e=>{const t=P.get(e);if(t!==void 0)return t;const n=e._meta,r=[n?.inner,n?.keyValidator,n?.valueValidator,...n?.members??[],...Object.values(n?.shape??{})],o=e.kind==="from"||r.some(a=>a!==void 0&&V(a));return P.set(e,o),o},$=e=>{const t=Object.getPrototypeOf(e);return t===Object.prototype||t===null},F=e=>e instanceof ArrayBuffer?new Uint8Array(e):ArrayBuffer.isView(e)?new Uint8Array(e.buffer,e.byteOffset,e.byteLength):void 0,E=(e,t)=>{if(Object.is(e,t))return!0;if(e instanceof Date&&t instanceof Date)return e.getTime()===t.getTime();const n=F(e),r=F(t);if(n!==void 0||r!==void 0)return n!==void 0&&r!==void 0&&Object.getPrototypeOf(e)===Object.getPrototypeOf(t)&&n.length===r.length&&n.every((u,p)=>u===r[p]);if(Array.isArray(e)||Array.isArray(t))return Array.isArray(e)&&Array.isArray(t)&&e.length===t.length&&e.every((u,p)=>E(u,t[p]));if(typeof e!="object"||typeof t!="object"||e===null||t===null||!$(e)||!$(t))return!1;const o=e,a=t,c=Object.keys(o);return c.length===Object.keys(a).length&&c.every(u=>u in a&&E(o[u],a[u]))},C=new WeakMap,ge=e=>{if(C.has(e))return C.get(e);const t=Object.fromEntries(Object.entries(e.shape).filter(([,r])=>V(r))),n=Object.keys(t).length>0?{...e,shape:t}:void 0;return C.set(e,n),n},ie=e=>{let t;return(n,r)=>e===void 0?!1:(t??=e()??{},n in t&&E(r,t[n]))},ae=(e,t)=>{const n=new Set(Object.keys(t).filter(r=>t[r]!==void 0));for(const[r,o]of z(e))o.serverDefault&&n.delete(r);return n},ce=(e,t,n,r,o)=>n.trusted===!0||r!==void 0&&!r.has(e)||o(e,t),v=e=>typeof e!="object"||e===null?e:e instanceof Date?new Date(e):e instanceof ArrayBuffer||ArrayBuffer.isView(e)?structuredClone(e):Array.isArray(e)?e.map(t=>v(t)):e instanceof Map?new Map([...e].map(([t,n])=>[v(t),v(n)])):e instanceof Set?new Set([...e].map(t=>v(t))):$(e)?Object.fromEntries(Object.entries(e).map(([t,n])=>[t,v(n)])):e,ye=(e,t,n)=>{const r={...t};for(const[o,a]of z(e)){if(a.serverDefault){r[o]=a.serverDefault({auth:n});continue}if(r[o]===void 0){if(a.defaultFn)r[o]=a.defaultFn();else if("defaultValue"in a){const{defaultValue:c}=a;r[o]=v(c)}}}return r},me=(e,t,n={})=>{let r;const o=ie(n.previous),a=n.only??(n.supplied===void 0?void 0:ae(e,n.supplied));for(const[c,u]of Object.entries(e.shape)){if(!(c in t)||typeof u.parse!="function")continue;const p=V(u);if(p&&ce(c,t[c],n,a,o)||n.tolerateStoredNull===!0&&t[c]===null&&u.kind==="optional")continue;const b=u.parse(t[c]);p&&(r??={...t},r[c]=b)}return r??t};export{B as MAX_LINK_ROWS,ye as applyInsertDefaults,we as applyOnDelete,D as distinctValues,pe as fanOutScalarCounts,de as relationHooks,he as resolveWith,me as runRowValidators,ge as transformOnlyDefinition};
1
+ import{LunoraError as S}from"@lunora/errors";import{t as z}from"./do-sql-105TONaE.mjs";import{applySelect as Y}from"./CURSOR_PREFIX-6offuG6M.mjs";const U=Symbol.for("lunora.relations.fanOutBudget"),de=e=>({fanOutBudget:e[U],relationBaseWhere:e.relationBaseWhere,relationMask:e.relationMask}),L=(e,t)=>t.select?Y(e,t.select,t.with):e,pe=async(e,t,n,r,o)=>{const a=await Promise.all(r.map(async c=>{const u=o?{AND:[{[n]:c},o]}:{[n]:c};return[c,await e(t,u)]}));return new Map(a)},ee=32,B=1e4,te=(e,t,n)=>{const r=new Map;for(const o of e)for(const a of n(o)){const c=a[t],u=r.get(c);u?u.push(a):r.set(c,[a])}return r},W=(e,t)=>({...e,[U]:t}),ne=(e,t)=>{const n=new Map;for(const[o,a]of e)for(const c of a){const u=n.get(c);u?u.push(o):n.set(c,[o])}const r=new Map;for(const o of t)for(const a of n.get(o._id)??[]){const c=r.get(a);c?c.push(o):r.set(a,[o])}return r},D=(e,t)=>{const n=new Set;for(const r of e){const o=r[t];o!=null&&n.add(o)}return[...n]},he=async e=>{const{groupedCounter:t,fanOutBudget:n,fetcher:r,parents:o,relationBaseWhere:a,relationMask:c,schema:u,tableName:p,with:b}=e,O=n??{remaining:ee},y=(f,s)=>c?.(f,s)??s;if(o.length===0)return;const M=u.tables[p];if(!M)throw new S("INTERNAL",`unknown table: ${p}`);const _=M.relationMap??{},G=(f,s)=>{const i=d=>u.tables[d]?.shardMode?.kind??"root";return i(f)===i(s)&&i(f)!=="shardBy"},R=f=>{const s=_[f];if(!s)throw new S("INTERNAL",`unknown relation "${f}" on table "${p}"`);return s},X=async(f,s,i)=>{const d=D(o,s.field);if(d.length===0){for(const h of o)h[f]=null;return}const{page:l}=await r(s.table,W({baseWhere:a?.(s.table),relationBaseWhere:a,relationMask:c,where:{[s.references]:{in:d}},with:i.with},O)),w=new Map;for(const h of y(s.table,l))w.set(h[s.references],h);for(const h of o){const A=w.get(h[s.field]);h[f]=A?L([A],i)[0]??null:null}},j=async(f,s,i,d)=>{const{page:l}=await r(f,W({baseWhere:a?.(f),limit:d,orderBy:s.orderBy,relationBaseWhere:a,relationMask:c,where:s.where?{AND:[s.where,i]}:i,with:s.with},O));return l},T=(f,s,i,d,l)=>{for(const w of o){const h=l.get(w[d])??[];w[f]=L(i===void 0?h:h.slice(0,i),s)}},K=async(f,s,i)=>{const d=D(o,s.references);if(d.length===0){for(const g of o)g[f]=[];return}const l=typeof i.limit=="number"?Math.max(0,Math.floor(i.limit)):void 0,w=(g,k)=>j(s.table,i,g,k);if(l===0){for(const g of o)g[f]=[];return}const h=l!==void 0&&d.length<=O.remaining;h&&(O.remaining-=d.length);const A=h?await Promise.all(d.map(async g=>w({[s.field]:g},l))):[await w({[s.field]:{in:d}},void 0)],m=te(A,s.field,g=>y(s.table,g));T(f,i,l,s.references,m)},I=async f=>{const{from:s,table:i,to:d}=f.through,l=new Map,w=D(o,"_id");if(w.length===0)return l;const h=await j(i,{},{[s]:{in:w}},B+1);if(h.length>B)throw new S("INTERNAL",`loading "${p}" relations through "${i}" read more than ${String(B)} join rows for one page; load fewer ${p} rows at a time`);for(const A of y(i,h)){const m=A[s],g=A[d];if(m==null||g===null||g===void 0)continue;const k=l.get(m);k?k.add(g):l.set(m,new Set([g]))}return l},q=async(f,s,i)=>{const d=typeof i.limit=="number"?Math.max(0,Math.floor(i.limit)):void 0,l=d===0?new Map:await I(s),w=(A,m)=>j(s.table,i,{_id:{in:[...A]}},m);let h=new Map;if(l.size>0&&d!==void 0&&l.size<=O.remaining){O.remaining-=l.size;const A=[...l.keys()],m=await Promise.all([...l.values()].map(async g=>w(g,d)));h=new Map(A.map((g,k)=>[g,y(s.table,m[k]??[])]))}else if(l.size>0){const A=new Set([...l.values()].flatMap(m=>[...m]));h=ne(l,y(s.table,await w(A,void 0)))}T(f,i,d,"_id",h)},Z=async(f,s)=>{const i=[...s];if(i.length===0)return new Set;if(G(p,f)){const l=await t(f,"_id",i,a?.(f));return new Set(i.filter(w=>(l.get(w)??0)>0))}const d=await j(f,{},{_id:{in:i}},void 0);return new Set(d.map(l=>l._id))},J=async(f,s)=>{const i=await I(s),d=await Z(s.table,new Set([...i.values()].flatMap(l=>[...l])));for(const l of o){const w=l._count??{};w[f]=[...i.get(l._id)??[]].filter(h=>d.has(h)).length,l._count=w}},Q=async f=>{for(const s of Object.keys(f)){const i=R(s);if(i.through!==void 0){await J(s,i);continue}const[d,l]=i.kind==="many"?[i.field,i.references]:[i.references,i.field],w=a?.(i.table),h=D(o,l),A=h.length===0?new Map:await t(i.table,d,h,w);for(const m of o){const g=m._count??{},k=m[l];g[s]=k==null?0:A.get(k)??0,m._count=g}}};for(const[f,s]of Object.entries(b)){if(s===void 0||s===!1)continue;if(f==="_count"){await Q(s);continue}const i=R(f),d=s===!0?{}:s;i.through===void 0?await(i.kind==="one"?X(f,i,d):K(f,i,d)):await q(f,i,d)}},N=1e4,x=500,oe=async(e,t,n,r,o)=>{const a=new Set;let c=o;for(;;){const u=c!==void 0,p=c??await e();let b=!1;c=void 0;for(const O of p){const y=O._id;if(!(typeof y!="string"||a.has(y))){if(a.add(y),b=!0,a.size>N)throw n();await t(y)}}if(!u){if(p.length<x)return;if(!b)throw new S("INTERNAL",r)}}},H=(e,t,n)=>new S("CASCADE_LIMIT",`cannot delete "${e}" row: more than ${String(N)} ${t} rows reference it (onDelete: ${n}) — delete or re-point them in batches first`,{status:400}),re=async(e,t,n,r)=>{const{deletedId:o,deletedReference:a,findHolders:c,onRestrict:u,tableName:p}=e,b=n.references==="_id"?o:a(n.references);if(b==null)return;const{field:O}=n,y=`"${t}.${O}"`,M=await c(t,O,b,{limit:r==="restrict"?1:N+1,select:["_id"]});if(M.length!==0){if(r==="restrict")return u(`cannot delete "${p}" row: ${y} still references it`);if(M.length>N)throw H(p,y,r);return{action:r,field:O,holderTable:t,label:y,probe:M,referencedValue:b}}},se=async(e,t,n)=>{const{findHolders:r,onCascade:o,onSetNull:a,tableName:c}=e,{action:u,field:p,holderTable:b,label:O,probe:y,referencedValue:M}=t;await oe(()=>r(b,p,M,{limit:x}),_=>u==="cascade"?o(b,_):a(b,_,p),()=>H(c,O,u),`onDelete on "${c}" made no progress: ${O} rows still match after being processed`,n?y:void 0)},we=async e=>{const{schema:t,tableName:n}=e;if(!t.tables[n])throw new S("INTERNAL",`unknown table: ${n}`);const r=[];for(const[o,a]of Object.entries(t.tables)){const c=a.relationMap;if(c)for(const u of Object.values(c)){if(u.kind!=="one"||u.table!==n||!u.onDelete)continue;const p=await re(e,o,u,u.onDelete);p&&r.push(p)}}for(const[o,a]of r.entries())await se(e,a,o===0)},P=new WeakMap,V=e=>{const t=P.get(e);if(t!==void 0)return t;const n=e._meta,r=[n?.inner,n?.keyValidator,n?.valueValidator,...n?.members??[],...Object.values(n?.shape??{})],o=e.kind==="from"||r.some(a=>a!==void 0&&V(a));return P.set(e,o),o},$=e=>{const t=Object.getPrototypeOf(e);return t===Object.prototype||t===null},F=e=>e instanceof ArrayBuffer?new Uint8Array(e):ArrayBuffer.isView(e)?new Uint8Array(e.buffer,e.byteOffset,e.byteLength):void 0,E=(e,t)=>{if(Object.is(e,t))return!0;if(e instanceof Date&&t instanceof Date)return e.getTime()===t.getTime();const n=F(e),r=F(t);if(n!==void 0||r!==void 0)return n!==void 0&&r!==void 0&&Object.getPrototypeOf(e)===Object.getPrototypeOf(t)&&n.length===r.length&&n.every((u,p)=>u===r[p]);if(Array.isArray(e)||Array.isArray(t))return Array.isArray(e)&&Array.isArray(t)&&e.length===t.length&&e.every((u,p)=>E(u,t[p]));if(typeof e!="object"||typeof t!="object"||e===null||t===null||!$(e)||!$(t))return!1;const o=e,a=t,c=Object.keys(o);return c.length===Object.keys(a).length&&c.every(u=>u in a&&E(o[u],a[u]))},C=new WeakMap,ge=e=>{if(C.has(e))return C.get(e);const t=Object.fromEntries(Object.entries(e.shape).filter(([,r])=>V(r))),n=Object.keys(t).length>0?{...e,shape:t}:void 0;return C.set(e,n),n},ie=e=>{let t;return(n,r)=>e===void 0?!1:(t??=e()??{},n in t&&E(r,t[n]))},ae=(e,t)=>{const n=new Set(Object.keys(t).filter(r=>t[r]!==void 0));for(const[r,o]of z(e))o.serverDefault&&n.delete(r);return n},ce=(e,t,n,r,o)=>n.trusted===!0||r!==void 0&&!r.has(e)||o(e,t),v=e=>typeof e!="object"||e===null?e:e instanceof Date?new Date(e):e instanceof ArrayBuffer||ArrayBuffer.isView(e)?structuredClone(e):Array.isArray(e)?e.map(t=>v(t)):e instanceof Map?new Map([...e].map(([t,n])=>[v(t),v(n)])):e instanceof Set?new Set([...e].map(t=>v(t))):$(e)?Object.fromEntries(Object.entries(e).map(([t,n])=>[t,v(n)])):e,ye=(e,t,n)=>{const r={...t};for(const[o,a]of z(e)){if(a.serverDefault){r[o]=a.serverDefault({auth:n});continue}if(r[o]===void 0){if(a.defaultFn)r[o]=a.defaultFn();else if("defaultValue"in a){const{defaultValue:c}=a;r[o]=v(c)}}}return r},me=(e,t,n={})=>{let r;const o=ie(n.previous),a=n.only??(n.supplied===void 0?void 0:ae(e,n.supplied));for(const[c,u]of Object.entries(e.shape)){if(!(c in t)||typeof u.parse!="function")continue;const p=V(u);if(p&&ce(c,t[c],n,a,o)||n.tolerateStoredNull===!0&&t[c]===null&&u.kind==="optional")continue;const b=u.parse(t[c]);p&&(r??={...t},r[c]=b)}return r??t};export{B as MAX_LINK_ROWS,ye as applyInsertDefaults,we as applyOnDelete,D as distinctValues,pe as fanOutScalarCounts,de as relationHooks,he as resolveWith,me as runRowValidators,ge as transformOnlyDefinition};
@@ -1 +1 @@
1
- import{m as P,c as E,l as w,r as T,a as D,w as F}from"./ctx-db-search-state-CPKPy8N6.mjs";import{S as I,c as L,g as _,d as x,e as b,a as k}from"./fts-companion-CE3EmIjk.mjs";import{sql as i}from"drizzle-orm";import{ensureAggregateCompanion as y,ensureRankCompanion as B}from"./createCompanionSync-qhvw6wyL.mjs";import{runDrizzle as p,runAll as C}from"./runDrizzle-RC09zZrh.mjs";import{i as M,D as m,h as A}from"./do-sql-RROYQPCM.mjs";import{sqliteInList as U}from"./WORKERD_SQLITE_LIMITS-B_4w7tzY.mjs";const v=(e,o)=>p(e,i`SELECT 1 FROM ${i.identifier(o)} LIMIT 1`).toArray().length>0,Q=(e,o)=>{for(const[r,n]of Object.entries(o.tables))if(n.shardMode?.kind!=="global")for(const t of n.aggregateIndexes??[])y(e,r,t,n.softDeleteMode?.field)},X=(e,o)=>{for(const[r,n]of Object.entries(o.tables))if(n.shardMode?.kind!=="global")for(const t of n.rankIndexes??[])B(e,r,t,n.softDeleteMode?.field)},H=(e,o,r,n)=>p(e,r===void 0?i`SELECT id, _creationTime, ${i.identifier(m)} FROM ${i.identifier(o)} ORDER BY id ASC LIMIT ${i.raw(String(n))}`:i`SELECT id, _creationTime, ${i.identifier(m)} FROM ${i.identifier(o)} WHERE id > ${r} ORDER BY id ASC LIMIT ${i.raw(String(n))}`).toArray(),h=500,O=(e,o,r)=>{const n=I(o,r.name),t=E(r),a=w(T(e,n),t);if(a.finished)return{done:!0,rows:0};const{cursor:c}=a,s=H(e,o,c,h);let f=c;for(const g of s){const{id:u}=g;if(typeof u!="string")continue;f=u;const S=A(g);C(e,S?x(n,u,b(S,r)):k(n,u))}const d=s.length<h;return F(e,n,f,d,t),{done:d,rows:s.length}},l=(e,o)=>i`${i.identifier(e)}.${i.identifier(o)}`,R=500,$=(e,o,r)=>{const n=I(o,r.name),t=p(e,L(n,R)).toArray(),a=_(t);if(a.size===0)return!0;const c=new Map;for(const s of p(e,i`SELECT ${l(o,"id")}, ${l(o,"_creationTime")}, ${l(o,m)} FROM ${i.identifier(o)} WHERE ${U(l(o,"id"),[...a.keys()],!1)}`))c.set(String(s.id),s);for(const[s,f]of a){const d=c.get(s),g=d?A(d):void 0;C(e,g?x(n,s,b(g,r),{unmappedRowids:f}):k(n,s,{unmappedRowids:f}))}return t.length<R},W=(e,o,r,n)=>{let t=0;for(;t<n&&!$(e,o,r);)t+=1;return t},Z=(e,o,r)=>{const n=I(o,r.name),t=E(r);return w(T(e,n),t).finished?!0:D(e,n)},q=(e,o,r)=>{if(M(e))for(const n of r.searchIndexes??[])$(e,o,n),!(n.staged&&v(e,o))&&O(e,o,n)},j=(e,o,r,n)=>{let t=0;for(;;){if(t>=n)return{done:!1,pages:t};const a=O(e,o,r);if(a.rows>0&&(t+=1),a.done)return{done:!0,pages:t}}},ee=(e,o,r={})=>{if(!M(e))return{done:!0,pages:0};P(e);const n=r.maxPages??Number.POSITIVE_INFINITY;let t=0;for(const[a,c]of Object.entries(o.tables))if(!(c.shardMode?.kind==="global"||!c.searchIndexes))for(const s of c.searchIndexes){if(t+=W(e,a,s,n-t),t>=n)return{done:!1,pages:t};const f=j(e,a,s,n-t);if(t+=f.pages,!f.done)return{done:!1,pages:t}}return{done:!0,pages:t}};export{Q as backfillAggregateIndexes,X as backfillRankIndexes,ee as backfillSearchIndexes,q as backfillSearchIndexesForTable,H as readKeysetPage,Z as searchIndexCoversTable};
1
+ import{m as P,c as E,l as w,r as T,a as D,w as F}from"./ctx-db-search-state-CPKPy8N6.mjs";import{S as I,c as L,g as _,d as x,e as b,a as k}from"./fts-companion-CE3EmIjk.mjs";import{sql as i}from"drizzle-orm";import{ensureAggregateCompanion as y,ensureRankCompanion as B}from"./createCompanionSync-CEht4hXX.mjs";import{runDrizzle as p,runAll as C}from"./runDrizzle-RC09zZrh.mjs";import{i as M,D as m,h as A}from"./do-sql-105TONaE.mjs";import{sqliteInList as U}from"./WORKERD_SQLITE_LIMITS-B_4w7tzY.mjs";const v=(e,o)=>p(e,i`SELECT 1 FROM ${i.identifier(o)} LIMIT 1`).toArray().length>0,Q=(e,o)=>{for(const[r,n]of Object.entries(o.tables))if(n.shardMode?.kind!=="global")for(const t of n.aggregateIndexes??[])y(e,r,t,n.softDeleteMode?.field)},X=(e,o)=>{for(const[r,n]of Object.entries(o.tables))if(n.shardMode?.kind!=="global")for(const t of n.rankIndexes??[])B(e,r,t,n.softDeleteMode?.field)},H=(e,o,r,n)=>p(e,r===void 0?i`SELECT id, _creationTime, ${i.identifier(m)} FROM ${i.identifier(o)} ORDER BY id ASC LIMIT ${i.raw(String(n))}`:i`SELECT id, _creationTime, ${i.identifier(m)} FROM ${i.identifier(o)} WHERE id > ${r} ORDER BY id ASC LIMIT ${i.raw(String(n))}`).toArray(),h=500,O=(e,o,r)=>{const n=I(o,r.name),t=E(r),a=w(T(e,n),t);if(a.finished)return{done:!0,rows:0};const{cursor:c}=a,s=H(e,o,c,h);let f=c;for(const g of s){const{id:u}=g;if(typeof u!="string")continue;f=u;const S=A(g);C(e,S?x(n,u,b(S,r)):k(n,u))}const d=s.length<h;return F(e,n,f,d,t),{done:d,rows:s.length}},l=(e,o)=>i`${i.identifier(e)}.${i.identifier(o)}`,R=500,$=(e,o,r)=>{const n=I(o,r.name),t=p(e,L(n,R)).toArray(),a=_(t);if(a.size===0)return!0;const c=new Map;for(const s of p(e,i`SELECT ${l(o,"id")}, ${l(o,"_creationTime")}, ${l(o,m)} FROM ${i.identifier(o)} WHERE ${U(l(o,"id"),[...a.keys()],!1)}`))c.set(String(s.id),s);for(const[s,f]of a){const d=c.get(s),g=d?A(d):void 0;C(e,g?x(n,s,b(g,r),{unmappedRowids:f}):k(n,s,{unmappedRowids:f}))}return t.length<R},W=(e,o,r,n)=>{let t=0;for(;t<n&&!$(e,o,r);)t+=1;return t},Z=(e,o,r)=>{const n=I(o,r.name),t=E(r);return w(T(e,n),t).finished?!0:D(e,n)},q=(e,o,r)=>{if(M(e))for(const n of r.searchIndexes??[])$(e,o,n),!(n.staged&&v(e,o))&&O(e,o,n)},j=(e,o,r,n)=>{let t=0;for(;;){if(t>=n)return{done:!1,pages:t};const a=O(e,o,r);if(a.rows>0&&(t+=1),a.done)return{done:!0,pages:t}}},ee=(e,o,r={})=>{if(!M(e))return{done:!0,pages:0};P(e);const n=r.maxPages??Number.POSITIVE_INFINITY;let t=0;for(const[a,c]of Object.entries(o.tables))if(!(c.shardMode?.kind==="global"||!c.searchIndexes))for(const s of c.searchIndexes){if(t+=W(e,a,s,n-t),t>=n)return{done:!1,pages:t};const f=j(e,a,s,n-t);if(t+=f.pages,!f.done)return{done:!1,pages:t}}return{done:!0,pages:t}};export{Q as backfillAggregateIndexes,X as backfillRankIndexes,ee as backfillSearchIndexes,q as backfillSearchIndexesForTable,H as readKeysetPage,Z as searchIndexCoversTable};
@@ -1 +1 @@
1
- import{encodeWire as u}from"@lunora/wire";import{quoteIdentifier as l}from"./quoteIdentifier-CObIFRhb.mjs";import{reprojectionMigrationTable as d}from"./REPROJECTION_MIGRATION_PREFIX-Czcb6_mO.mjs";import{REPROJECTION_MIGRATION_PREFIX as v,reprojectionMigrationId as w}from"./REPROJECTION_MIGRATION_PREFIX-Czcb6_mO.mjs";import{runSql as p}from"./runDrizzle-RC09zZrh.mjs";import{k as m,D as E}from"./do-sql-RROYQPCM.mjs";import{mayHoldProjectedValue as g}from"./BIGINT_KEY_DIGITS-DE6yshOt.mjs";const b=u(0n)[0],_=e=>e.shardMode?.kind==="global"?[]:Object.entries(e.shape).filter(([,r])=>g(r)).map(([r])=>r),M=e=>Object.entries(e.tables).filter(([,r])=>_(r).length>0).map(([r])=>r),f=e=>{const r=`json_each(${l(E)}) AS __f__`;return{params:[JSON.stringify(e),b,"bigint","bytes"],sql:`EXISTS (SELECT 1 FROM ${r} WHERE __f__.type = 'array' AND __f__.key IN (SELECT value FROM json_each(?)) AND json_extract(__f__.value, '$[0]') = ? AND json_extract(__f__.value, '$[1]') IN (?, ?))`}},N=(e,r,o)=>{if(o.length===0)return 0;const{params:t,sql:n}=f(o);return p(e,`SELECT COUNT(*) AS count FROM ${l(r)} WHERE ${n}`,...t).toArray()[0]?.count??0},R=(e,r,o,t)=>{const{params:n,sql:i}=f(o);return p(e,`SELECT 1 FROM ${l(r)} WHERE id = ? AND (${i}) LIMIT 1`,t,...n).toArray().length>0},S=(e,r,o)=>{const t=d(e);if(t===void 0)return;const n=r.tables[t];if(!n)return;const i=_(n);if(i.length!==0)return{id:e,table:t,up:s=>{const a=s._id;if(!(typeof a!="string"||!R(o,t,i,a))){try{m(s)}catch(c){console.warn(`${e}: skipping row ${a} — it cannot be re-projected: ${c instanceof Error?c.message:String(c)}`);return}return s}}}};export{v as REPROJECTION_MIGRATION_PREFIX,S as buildReprojectionMigration,N as countLegacyRows,_ as reprojectableFields,w as reprojectionMigrationId,M as reprojectionTables};
1
+ import{encodeWire as u}from"@lunora/wire";import{quoteIdentifier as l}from"./quoteIdentifier-CObIFRhb.mjs";import{reprojectionMigrationTable as d}from"./REPROJECTION_MIGRATION_PREFIX-Czcb6_mO.mjs";import{REPROJECTION_MIGRATION_PREFIX as v,reprojectionMigrationId as w}from"./REPROJECTION_MIGRATION_PREFIX-Czcb6_mO.mjs";import{runSql as p}from"./runDrizzle-RC09zZrh.mjs";import{k as m,D as E}from"./do-sql-105TONaE.mjs";import{mayHoldProjectedValue as g}from"./BIGINT_KEY_DIGITS-DE6yshOt.mjs";const b=u(0n)[0],_=e=>e.shardMode?.kind==="global"?[]:Object.entries(e.shape).filter(([,r])=>g(r)).map(([r])=>r),M=e=>Object.entries(e.tables).filter(([,r])=>_(r).length>0).map(([r])=>r),f=e=>{const r=`json_each(${l(E)}) AS __f__`;return{params:[JSON.stringify(e),b,"bigint","bytes"],sql:`EXISTS (SELECT 1 FROM ${r} WHERE __f__.type = 'array' AND __f__.key IN (SELECT value FROM json_each(?)) AND json_extract(__f__.value, '$[0]') = ? AND json_extract(__f__.value, '$[1]') IN (?, ?))`}},N=(e,r,o)=>{if(o.length===0)return 0;const{params:t,sql:n}=f(o);return p(e,`SELECT COUNT(*) AS count FROM ${l(r)} WHERE ${n}`,...t).toArray()[0]?.count??0},R=(e,r,o,t)=>{const{params:n,sql:i}=f(o);return p(e,`SELECT 1 FROM ${l(r)} WHERE id = ? AND (${i}) LIMIT 1`,t,...n).toArray().length>0},S=(e,r,o)=>{const t=d(e);if(t===void 0)return;const n=r.tables[t];if(!n)return;const i=_(n);if(i.length!==0)return{id:e,table:t,up:s=>{const a=s._id;if(!(typeof a!="string"||!R(o,t,i,a))){try{m(s)}catch(c){console.warn(`${e}: skipping row ${a} — it cannot be re-projected: ${c instanceof Error?c.message:String(c)}`);return}return s}}}};export{v as REPROJECTION_MIGRATION_PREFIX,S as buildReprojectionMigration,N as countLegacyRows,_ as reprojectableFields,w as reprojectionMigrationId,M as reprojectionTables};
@@ -1 +1 @@
1
- import{readCdcChangeKeys as s}from"./CDC_LOG_TABLE-CTkXVeJx.mjs";import{selectShapeMembers as h}from"./selectShapeMembers-BhK79123.mjs";import{shapeRangeKey as u}from"./ShapeDiffCache-iNO-hUiy.mjs";import{projectColumns as g}from"./buildPokeFrames-WR-hp0mX.mjs";const C=(m,e,a,i,p,f=s)=>{const r=u(e.table,a,i),n=p.changedKeys(r,()=>f(m,e.table,a,i));if(n.length===0)return[];const b=p.members(e,r,()=>h(m,e.table,e.effectiveWhere,n.map(t=>t.id))),o=[];for(const t of n){const c=b.get(t.id);if(c===void 0){t.op!=="insert"&&o.push({key:t.id,op:"delete",table:e.table});continue}o.push({key:t.id,op:t.op,table:e.table,value:g(c,e.columns)})}return o};export{C as buildShapeDiff};
1
+ import{readCdcChangeKeys as s}from"./CDC_LOG_TABLE-BFGgqai8.mjs";import{selectShapeMembers as h}from"./selectShapeMembers-Dqx_m7BF.mjs";import{shapeRangeKey as u}from"./ShapeDiffCache-iNO-hUiy.mjs";import{projectColumns as g}from"./buildPokeFrames-WR-hp0mX.mjs";const C=(m,e,a,i,p,f=s)=>{const r=u(e.table,a,i),n=p.changedKeys(r,()=>f(m,e.table,a,i));if(n.length===0)return[];const b=p.members(e,r,()=>h(m,e.table,e.effectiveWhere,n.map(t=>t.id))),o=[];for(const t of n){const c=b.get(t.id);if(c===void 0){t.op!=="insert"&&o.push({key:t.id,op:"delete",table:e.table});continue}o.push({key:t.id,op:t.op,table:e.table,value:g(c,e.columns)})}return o};export{C as buildShapeDiff};
@@ -0,0 +1 @@
1
+ import{N as uo,S as $o,d as Eo,e as go,a as po}from"./fts-companion-CE3EmIjk.mjs";import{sql as o}from"drizzle-orm";import{r as Y}from"./json-field-path-DeJW4U9z.mjs";import{matchesStaticWhere as X,aggregateSqlFunction as mo}from"./AGGREGATE_SQL_FUNCTION-C_ZipS9R.mjs";import{aggregateTableName as j,foldAggregateTally as J,encodeAggregateKey as k,coerceAggregateNumber as U}from"./aggregateTableName-B_CtIQCS.mjs";import{aggregateSignature as ho,readCompanionSignature as Z,rankSignature as So,writeCompanionSignature as N}from"./CompanionMemo-BXU5vfak.mjs";import{runAll as _o,runDrizzle as g}from"./runDrizzle-RC09zZrh.mjs";import{i as yo,g as Ro,a as F,b as A,A as h,c as H,D as x,u as oo,r as eo,e as V}from"./do-sql-105TONaE.mjs";import{WORKERD_SQLITE_LIMITS as no,param as q}from"./WORKERD_SQLITE_LIMITS-B_4w7tzY.mjs";import{encodeGeohash as To,GEO_DEFAULT_PRECISION as Ao}from"./GEO_DEFAULT_PRECISION-CqpQZ-J_.mjs";import{isLiveForCompanion as to}from"./CURSOR_PREFIX-6offuG6M.mjs";import{rankTableName as B,matchesRankStaticWhere as ro,sortColumnName as wo,encodePartitionKey as Co}from"./RANK_TIEBREAK-D3ye2GsL.mjs";import{mayHoldProjectedValue as Io}from"./BIGINT_KEY_DIGITS-DE6yshOt.mjs";import{serializeSqlValue as so}from"./serializeSqlValue-DeoBMpZ2.mjs";const Oo=(r,f,t)=>[...r.partitionBy??[],...r.sortBy.map(l=>l.field),...r.where?Object.keys(r.where):[]].every(l=>Y(f,l)===Y(t,l)),io=r=>o.join(["__id__","__partition__",...r.sortBy.map((f,t)=>wo(t))].map(f=>o.identifier(f)),o`, `),co=(r,f,t)=>{const $=Co(r.partitionBy??[],t),l=r.sortBy.map(s=>so(t[s.field]??null)),c=o.join([f,$,...l].map(s=>q(s)),o`, `);return o`(${c})`},vo=(r,f,t,$,l,c)=>{g(r,o`INSERT INTO ${o.identifier(f)} (${$}) VALUES ${co(t,l,c)}`)},Q=1e3,ao=function*(f,t,$,l){let c;for(;;){const s=c===void 0?o``:o` WHERE id > ${q(c)}`,y=[...g(oo(f),o`SELECT id, _creationTime, ${o.identifier(x)} FROM ${o.identifier(t)}${s} ORDER BY id LIMIT ${q(Q)}`)];for(const S of y){const R=eo(S);R&&to(R,$)&&l(R)&&(yield R)}if(y.length<Q)return;c=String(y.at(-1)?.id)}},ko=(r,f,t,$,l)=>{const c=j(f,t.name),s=t.by??[],y=new Map;for(const w of ao(r,f,$,I=>!t.where||X(I,t.where)))J(y,k(s,w),t,w);g(r,o`DELETE FROM ${o.identifier(c)}`);const S=Math.floor(no.boundParams/3),R=[...y];for(let w=0;w<R.length;w+=S){const I=R.slice(w,w+S),P=o.join(I.map(([b,D])=>o`(${b}, ${D.value}, ${D.count})`),o`, `);g(r,o`INSERT INTO ${o.identifier(c)} (${F}, ${A}, ${h}) VALUES ${P}`)}N(r,c,l)},Lo=(r,f,t,$)=>{const l=ho(t,$);Z(r,j(f,t.name))!==l&&ko(r,f,t,$,l)},Fo=(r,f,t,$,l)=>{const c=B(f,t.name),s=io(t);g(r,o`DELETE FROM ${o.identifier(c)}`);const y=Math.max(1,Math.floor(no.boundParams/(2+t.sortBy.length)));let S=[];const R=()=>{S.length>0&&(g(r,o`INSERT INTO ${o.identifier(c)} (${s}) VALUES ${o.join(S,o`, `)}`),S=[])};for(const w of ao(r,f,$,I=>!t.where||ro(I,t.where)))S.push(co(t,w._id,w)),S.length>=y&&R();R(),N(r,c,l)},Do=(r,f,t,$)=>{const l=So(t,$);Z(r,B(f,t.name))!==l&&Fo(r,f,t,$,l)},Mo=(r,f,t,$,l,c)=>{if(l&&c&&Oo(t,l,c))return;const s=B(f,t.name);l&&g(r,o`DELETE FROM ${o.identifier(s)} WHERE ${o.identifier("__id__")} = ${$}`),!(!c||t.where&&!ro(c,t.where))&&vo(r,s,t,io(t),$,c)},Jo=r=>{const{broadcast:f,indexKeysFor:t,invalidateCache:$,recordCdc:l,schema:c,sql:s}=r,y=r.verified??new Set,S=e=>c.tables[e]?.softDeleteMode?.field,R=(e,n)=>{const a=j(e,n.name);y.has(a)||(Lo(s,e,n,S(e)),y.add(a))},w=(e,n,a)=>{const p=n.by??[],d=n.field??"",E=[],_=(i,u)=>{const m=so(u);m===null?E.push(o`${V(i)} IS NULL`):E.push(o`${V(i)} = ${m}`)};for(const i of p)_(i,a[i]??null);const C=S(e);C!==void 0&&_(C,null);for(const[i,u]of Object.entries(n.where??{}))_(i,u!==null&&typeof u=="object"&&!Array.isArray(u)?u.eq:u);const L=E.length>0?o` WHERE ${o.join(E,o` AND `)}`:o``,M=c.tables[e]?.shape[d];if(M&&Io(M)){const i=g(oo(s),o`SELECT id, _creationTime, ${o.identifier(x)} FROM ${o.identifier(e)}${L}`).toArray(),u=new Map;for(const m of i){const v=eo(m);v&&J(u,"",n,v)}return{value:u.get("")?.value??null}}const W=mo(n.op),T=V(d);return{value:g(s,o`SELECT ${o.raw(W)}(${T}) AS value FROM ${o.identifier(e)}${L}`).one().value??null}},I=(e,n,a,p)=>{const d=j(e,n.name),{op:E}=n,_=n.field??"",C=i=>{g(s,o`DELETE FROM ${o.identifier(d)} WHERE ${F} = ${i} AND ${h} <= 0`)},L=S(e),M=i=>!n.where||X(i,n.where),W=i=>to(i,L)&&M(i);p!==void 0&&E!=="count"&&M(p)&&U(p[_]);const T=a&&W(a)?a:void 0,O=p&&W(p)?p:void 0;if(!(!T&&!O)){if(E==="count"){for(const[i,u]of[[T,-1],[O,1]]){if(!i)continue;const m=k(n.by??[],i);g(s,H(d,m,u,u,o`${A} = ${A} + excluded.${A}, ${h} = ${h} + excluded.${h}`))}T&&C(k(n.by??[],T));return}if(E==="sum"||E==="avg"){for(const[i,u]of[[T,-1],[O,1]]){if(!i)continue;const m=U(i[_]);if(m===void 0)continue;const v=k(n.by??[],i);g(s,H(d,v,u*m,u,o`${A} = COALESCE(${A}, 0) + excluded.${A}, ${h} = ${h} + excluded.${h}`))}T&&C(k(n.by??[],T));return}if(T){const i=k(n.by??[],T),u=U(T[_]),m=g(s,o`SELECT ${A} AS value, ${h} AS count FROM ${o.identifier(d)} WHERE ${F} = ${i}`).toArray()[0],v=(m?.count??0)-1;if(v<=0)g(s,o`DELETE FROM ${o.identifier(d)} WHERE ${F} = ${i}`);else if(m&&u!==void 0&&m.value!==null&&u===m.value){const lo=w(e,n,T);g(s,o`UPDATE ${o.identifier(d)} SET ${A} = ${lo.value}, ${h} = ${v} WHERE ${F} = ${i}`)}else g(s,o`UPDATE ${o.identifier(d)} SET ${h} = ${h} - 1 WHERE ${F} = ${i}`)}if(O){const i=k(n.by??[],O),u=U(O[_]);if(u===void 0)g(s,H(d,i,null,1,o`${h} = ${h} + 1`));else{const m=E==="min"?"MIN":"MAX";g(s,H(d,i,u,1,o`${A} = ${o.raw(m)}(COALESCE(${A}, excluded.${A}), excluded.${A}), ${h} = ${h} + 1`))}}}},P=e=>{for(const n of c.tables[e]?.aggregateIndexes??[])R(e,n)},b=(e,n,a)=>{for(const p of c.tables[e]?.aggregateIndexes??[])I(e,p,n,a)},D=(e,n)=>{const a=B(e,n.name);y.has(a)||(Do(s,e,n,S(e)),y.add(a))},fo=e=>{for(const n of c.tables[e]?.rankIndexes??[])D(e,n)},G=(e,n,a,p)=>{for(const d of c.tables[e]?.rankIndexes??[])Mo(s,e,d,n,a,p)},K=(e,n,a,p)=>{const d=c.tables[e]?.searchIndexes??[];if(!(d.length===0||!yo(s)))for(const E of d){if(uo(p,a,E))continue;const _=$o(e,E.name);_o(s,a?Eo(_,n,go(a,E)):po(_,n))}},z=(e,n,a)=>{for(const p of c.tables[e]?.geoIndexes??[]){const d=Ro(e,p.name);g(s,o`DELETE FROM ${o.identifier(d)} WHERE ${o.identifier("__id__")} = ${n}`);const E=a?.[p.field];if(E!==null&&typeof E=="object"&&typeof E.lat=="number"&&typeof E.lng=="number"){const{lat:_,lng:C}=E,L=To({lat:_,lng:C},p.precision??Ao);g(s,o`INSERT INTO ${o.identifier(d)} (${o.identifier("__id__")}, ${o.identifier("__geohash__")}, ${o.identifier("__lat__")}, ${o.identifier("__lng__")}) VALUES (${n}, ${L}, ${_}, ${C})`)}}};return{ensureBackfilledForTable:P,ensureBackfilledIndex:R,ensureRankBackfilled:D,ensureRankBackfilledForTable:fo,syncAggregates:b,syncCompanionsForInsert:(e,n,a)=>{K(e,n,a),z(e,n,a),b(e,void 0,a),G(e,n,void 0,a),$(e,n,a),l(e,n,"insert",a),f({indexKeys:t(e,a),key:n,op:"insert",row:a,table:e})},syncGeo:z,syncRanks:G,syncSearch:K}};export{Jo as createCompanionSync,Lo as ensureAggregateCompanion,Do as ensureRankCompanion};
@@ -1,4 +1,4 @@
1
- import{LunoraError as T}from"@lunora/errors";import{decodeWire as v,encodeWire as N}from"@lunora/wire";import{cursorBelowRetainedFloor as b}from"./CDC_LOG_TABLE-CTkXVeJx.mjs";import{envPositiveInt as E}from"./envOptionalPositiveInt-D2pY-c64.mjs";import{e as I}from"./estimate-bytes-_k74s6LZ.mjs";import{siblingStub as L}from"./stubByName-B8cFYipA.mjs";import{DEFAULT_TRANSACTION_LIMITS as O}from"./DEFAULT_TRANSACTION_LIMITS-Dmj5VBrV.mjs";import{verifySiblingBody as C,RELAY_SIGNATURE_HEADER as S,siblingSecretOf as R,signSiblingBody as U}from"./RELAY_SIGNATURE_HEADER-DP0glzE_.mjs";const q=["wnam","enam","sam","weur","eeur","apac","apac-ne","apac-se","oc","afr","me"],x=new Set(q),F=r=>typeof r=="string"&&x.has(r),w="::replica::",_=r=>{const e=r.lastIndexOf(w);if(e===-1)return;const t=r.slice(0,e),s=r.slice(e+w.length);if(!(t.length===0||!F(s)))return{ownerKey:t,region:s}},M=r=>{if(r==null||!/^\d+$/.test(r))return;const e=Number.parseInt(r,10);return Number.isSafeInteger(e)&&e>0?e:void 0},P=1e3,A=1e3,B=10,D=5e4,W=r=>E(r,"LUNORA_REPLICA_MAX_BOOTSTRAP_ROWS",D),f="__replica_state",g=new WeakSet,m=r=>{g.has(r)||(r.exec(`CREATE TABLE IF NOT EXISTS ${f} (
1
+ import{LunoraError as T}from"@lunora/errors";import{decodeWire as v,encodeWire as N}from"@lunora/wire";import{cursorBelowRetainedFloor as b}from"./CDC_LOG_TABLE-BFGgqai8.mjs";import{envPositiveInt as E}from"./envOptionalPositiveInt-D2pY-c64.mjs";import{e as I}from"./estimate-bytes-C-C35VXL.mjs";import{siblingStub as L}from"./stubByName-B8cFYipA.mjs";import{DEFAULT_TRANSACTION_LIMITS as O}from"./DEFAULT_TRANSACTION_LIMITS-D7p7Ys0M.mjs";import{verifySiblingBody as C,RELAY_SIGNATURE_HEADER as S,siblingSecretOf as R,signSiblingBody as U}from"./RELAY_SIGNATURE_HEADER-DP0glzE_.mjs";const q=["wnam","enam","sam","weur","eeur","apac","apac-ne","apac-se","oc","afr","me"],x=new Set(q),F=r=>typeof r=="string"&&x.has(r),w="::replica::",_=r=>{const e=r.lastIndexOf(w);if(e===-1)return;const t=r.slice(0,e),s=r.slice(e+w.length);if(!(t.length===0||!F(s)))return{ownerKey:t,region:s}},M=r=>{if(r==null||!/^\d+$/.test(r))return;const e=Number.parseInt(r,10);return Number.isSafeInteger(e)&&e>0?e:void 0},P=1e3,A=1e3,B=10,D=5e4,W=r=>E(r,"LUNORA_REPLICA_MAX_BOOTSTRAP_ROWS",D),f="__replica_state",g=new WeakSet,m=r=>{g.has(r)||(r.exec(`CREATE TABLE IF NOT EXISTS ${f} (
2
2
  id INTEGER PRIMARY KEY CHECK (id = 1),
3
3
  epoch TEXT NOT NULL,
4
4
  applied_seq INTEGER NOT NULL,
@@ -1 +1 @@
1
- import{createShardCtxDb as C}from"./NotUniqueError-Dn6Cj7W1.mjs";import{createRelayLink as N}from"./DEFAULT_MAX_RELAYS-B66neS_B.mjs";import{ConflictError as q}from"./ConflictError-C8GtJmjS.mjs";import{runShardMigrations as B}from"./runShardMigrations-DOiPunti.mjs";import{d as x}from"./relay-CKEdfUjH.mjs";const v=(O,y={})=>({_meta:{column:{notNull:!0,...y}},kind:O}),W=(O,y,F)=>{const{describe:_,expect:l,it:b}=F;_(`engine contract: ${O}`,()=>{_("optimistic concurrency",()=>{const g=u=>({tables:{items:{indexes:[],shape:{title:v("string"),version:v("number",{notNull:!1})},triggerMap:{clobber:{handler:()=>{u.exec(`UPDATE "items" SET "__doc__" = json_set("__doc__", '$.version', 99) WHERE "id" = 'i1'`)},op:"update",timing:"before"}}}}});b("raises a CONFLICT of kind `occ` when a write's snapshot is clobbered",async()=>{const{close:u,host:h}=y();try{const d=h.sql,p=g(d);B(d,p);const s=C({schema:p,sql:d});await s.insert("items",{_id:"i1",title:"first",version:1},{allowExplicitId:!0}),await l(s.patch("items","i1",{title:"second"})).rejects.toBeInstanceOf(q)}finally{u?.()}}),b("reports the conflict as CONFLICT/409 rather than retrying it away",async()=>{const{close:u,host:h}=y();try{const d=h.sql,p=g(d);B(d,p);const s=C({schema:p,sql:d});await s.insert("items",{_id:"i1",title:"first",version:1},{allowExplicitId:!0});let r;try{await s.patch("items","i1",{title:"second"})}catch(t){r=t}const e=r;l(e.code).toBe("CONFLICT"),l(e.kind).toBe("occ")}finally{u?.()}}),b("leaves the row readable and unchanged after a conflict",async()=>{const{close:u,host:h}=y();try{const d=h.sql,p=g(d);B(d,p);const s=C({schema:p,sql:d});await s.insert("items",{_id:"i1",title:"first",version:1},{allowExplicitId:!0});try{await s.patch("items","i1",{title:"second"})}catch{}const r=await s.get("items","i1");l(r?.title).toBe("first"),l(r?.version).toBe(99)}finally{u?.()}}),b("raises a CONFLICT of kind `trigger` when a trigger writes its own row through the db",async()=>{const{close:u,host:h}=y();try{const d=h.sql,p={tables:{items:{indexes:[],shape:{title:v("string"),version:v("number",{notNull:!1})},triggerMap:{recurse:{handler:async(t,a)=>{await t.db.patch("items",a.doc._id,{version:99})},op:"update",timing:"before"}}}}};B(d,p);const s=C({schema:p,sql:d});await s.insert("items",{_id:"i1",title:"first",version:1},{allowExplicitId:!0});let r;try{await s.patch("items","i1",{title:"second"})}catch(t){r=t}const e=r;l(e).toBeInstanceOf(q),l(e.code).toBe("CONFLICT"),l(e.kind).toBe("trigger")}finally{u?.()}})}),_("shape-poke ordering",()=>{const g="shard-a",u={args:{},name:"messages"},h=(e,t,a,n)=>e.accept(t?.()??{},{connectionId:a,shapes:{[n]:u}}),d=(e,t,a,n=new Set)=>{let c=0,i=0;const o=k=>()=>{throw new Error(`the relay poke path must not reach RelayHost.${k}`)},m={fetch:(k,E)=>{if(JSON.parse(E?.body??"{}").type!=="relay_shape_subscribe")return Promise.resolve(new Response(void 0,{status:204}));const I=a[i];if(i+=1,I===void 0)throw new Error("the relay asked for more seeds than this fixture supplies");return Promise.resolve(Response.json(I))}},f={get:()=>m,getByName:()=>m,idFromName:k=>k},w={buildShapeDiff:o("buildShapeDiff"),computeOpLogShapeSeed:o("computeOpLogShapeSeed"),currentCdcEpoch:o("currentCdcEpoch"),deliverWhisperLocal:o("deliverWhisperLocal"),dropIfLapsed:k=>n.has((k.deserializeAttachment?.()).connectionId??""),doName:()=>x(g,0),env:()=>({SHARD:f}),getWebSockets:()=>e.getSockets(),maskMetadata:o("maskMetadata"),nextPokeId:()=>(c+=1,`poke-${String(c)}`),readAttachment:k=>k.deserializeAttachment?.(),recordShapePokeFanout:()=>{},resolveShape:o("resolveShape"),rlsMetadata:o("rlsMetadata"),shardBinding:()=>"SHARD",shardJurisdiction:()=>{},sql:()=>t},S=N(w);if(S===void 0)throw new Error("expected a relay link for a `…::relay::N` name");return S},p=e=>new Request("https://relay.internal/_lunora/relay",{body:JSON.stringify(e),headers:{"content-type":"application/json"},method:"POST"}),s=async(e,t,a)=>{const n=await e.seedRelayShape(t,a,u,{identity:void 0,userId:void 0});if(n!=="ok")throw new Error(`seed failed: ${JSON.stringify(n)}`)},r=(e={})=>p({...u,checkpoint:20,epoch:"e1",fromCursor:10,rowsPatch:[{id:"r1",op:"upsert",value:{title:"hello"}}],type:"relay_shape_poke",...e});b("frames a poke as pokeStart → pokePart per shape → pokeEnd, under one poke id",async()=>{const{close:e,createSocket:t,host:a,readFrames:n,sockets:c}=y();try{const i=d(c,a.sql,[{cursor:10,epoch:"e1",frames:[]}]),o=h(c,t,"c-alice","s1");await s(i,o,"s1"),await i.handleControl(r());const f=(await n(o)).map(w=>JSON.parse(w));l(f.map(w=>w.type)).toStrictEqual(["pokeStart","pokePart","pokeEnd"]),l(new Set(f.map(w=>w.pokeId)).size).toBe(1),l(f[1]?.shapeId).toBe("s1"),l(f[2]?.checkpoint).toBe(20)}finally{e?.()}}),b("delivers a poke only to sockets whose cursor matches, and advances them past it",async()=>{const{close:e,createSocket:t,host:a,readFrames:n,sockets:c}=y();try{const i=d(c,a.sql,[{cursor:10,epoch:"e1",frames:[]},{cursor:7,epoch:"e1",frames:[]}]),o=h(c,t,"c-alice","s1"),m=h(c,t,"c-bob","s2");await s(i,o,"s1"),await s(i,m,"s2"),await i.handleControl(r());const f=await n(o);l(f.length).toBe(3);const w=await n(m);l(w.length).toBe(0),await i.handleControl(r());const S=await n(o);l(S.length).toBe(3)}finally{e?.()}}),b("pokes no subscriber the host reports lapsed, and still pokes the others",async()=>{const{close:e,createSocket:t,host:a,readFrames:n,sockets:c}=y();try{const i=new Set,o=d(c,a.sql,[{cursor:10,epoch:"e1",frames:[]},{cursor:10,epoch:"e1",frames:[]}],i),m=h(c,t,"c-alice","s1"),f=h(c,t,"c-bob","s2");await s(o,m,"s1"),await s(o,f,"s2"),i.add("c-bob"),await o.handleControl(r());const w=await n(m),S=await n(f);l(w.length).toBe(3),l(S.length).toBe(0)}finally{e?.()}}),b("skips a socket whose cursor matches under a different CDC epoch",async()=>{const{close:e,createSocket:t,host:a,readFrames:n,sockets:c}=y();try{const i=d(c,a.sql,[{cursor:10,epoch:"e1",frames:[]}]),o=h(c,t,"c-alice","s1");await s(i,o,"s1"),await i.handleControl(r({epoch:"e2"}));const m=await n(o);l(m.length).toBe(0),await i.handleControl(r());const f=await n(o);l(f.length).toBe(3)}finally{e?.()}})}),_("orderBy null placement",()=>{const g=[["a",void 0],["b",3],["c",void 0],["d",1],["e",void 0],["f",3],["g",2],["h",void 0]],u=[{nulls:"first",sort:"asc"},{nulls:"last",sort:"asc"},{nulls:"first",sort:"desc"},{nulls:"last",sort:"desc"}],h=({nulls:p,sort:s})=>{const r=new Map(g.map(([t],a)=>[t,a])),e=s==="asc"?1:-1;return g.toSorted(([t,a],[n,c])=>a!==c?a===void 0?p==="first"?-1:1:c===void 0?p==="first"?1:-1:(a-c)*e:((r.get(t)??0)-(r.get(n)??0))*e).map(([t])=>t)},d=p=>p.map(s=>String(s.label));b("pages every placement in threes with no row skipped or repeated",async()=>{const{close:p,host:s}=y();try{const r=s.sql,e=u.map((i,o)=>`items_${String(o)}`),t={label:v("string"),score:v("number",{notNull:!1})},a={tables:Object.fromEntries(e.map(i=>[i,{indexes:[{fields:["score"],name:"by_score"}],shape:t}]))};B(r,a);let n=17e11;const c=C({clock:()=>(n+=1e3,n),schema:a,sql:r});for(const i of e)for(const[o,m]of g)await c.insert(i,m===void 0?{label:o}:{label:o,score:m});for(const[i,o]of u.entries()){const m=e[i]??"",f=await c.findMany(m,{orderBy:[{score:o}]});l(d(f.page)).toStrictEqual(h(o));const w=[];let S;for(let k=0;k<g.length+2;k+=1){const E=await c.findMany(m,{cursor:S,limit:3,orderBy:[{score:o}]});if(w.push(...d(E.page)),E.isDone)break;S=E.continueCursor}l(w).toStrictEqual(h(o))}}finally{p?.()}})}),_("RLS identity under live subscription",()=>{const g="shard-a",u={args:{},name:"lobby-messages"},h={args:{},name:"my-orders"},d=s=>{const r=[],e=[],t={fetch:(c,i)=>(r.push(JSON.parse(i?.body??"{}")),Promise.resolve(new Response(void 0,{status:204})))},n=N({buildShapeDiff:()=>[{id:"r1",op:"upsert",value:{}}],computeOpLogShapeSeed:()=>({baseCheckpoint:void 0,cursor:10,epoch:"e1",reset:!0,rowsPatch:[]}),currentCdcEpoch:()=>"e1",deliverWhisperLocal:()=>0,dropIfLapsed:()=>!1,doName:()=>g,env:()=>({SHARD:{get:()=>t,getByName:()=>t,idFromName:c=>c}}),getWebSockets:()=>[],maskMetadata:()=>({columns:[]}),nextPokeId:()=>"poke-1",readAttachment:()=>({}),recordShapePokeFanout:()=>{},resolveShape:(c,i,o)=>(e.push(o),c===h.name?{columns:["id"],effectiveWhere:{org:o?.identity?.org??"anonymous"},global:!1,table:"orders"}:{columns:["id"],effectiveWhere:{room:"lobby"},global:!1,table:"messages"}),rlsMetadata:()=>({policies:[]}),shardBinding:()=>"SHARD",shardJurisdiction:()=>{},sql:()=>s});if(n===void 0)throw new Error("expected an owner link for an un-suffixed DO name");return{owner:n,posts:r,resolvedUnder:e}},p=async(s,r)=>{await s.handleControl(new Request("https://owner.internal/_lunora/relay",{body:JSON.stringify({...r,connectionId:"c-alice",identity:{org:"acme"},relayIndex:0,subId:"s1",type:"relay_shape_subscribe",userId:"u1"}),headers:{"content-type":"application/json"},method:"POST"}))};b("seeds a subscriber under its own forwarded identity, never the anonymous one",async()=>{const{close:s,host:r}=y();try{const{owner:e,resolvedUnder:t}=d(r.sql);await p(e,h),l(t.some(a=>a?.userId==="u1"&&a.identity?.org==="acme")).toBe(!0)}finally{s?.()}}),b("routes an identity-scoped shape to a per-socket poke, not the cohort multicast",async()=>{const{close:s,host:r}=y();try{const{owner:e,posts:t}=d(r.sql);await p(e,h),t.length=0,await e.onFlush(new Set(["orders"]),20);const a=t.filter(n=>n.type==="relay_shape_poke");l(a.length).toBe(1),l(a[0]?.targetConnectionId).toBe("c-alice")}finally{s?.()}}),b("still multicasts an identity-blind shape to the whole cohort",async()=>{const{close:s,host:r}=y();try{const{owner:e,posts:t}=d(r.sql);await p(e,u),t.length=0,await e.onFlush(new Set(["messages"]),20);const a=t.filter(n=>n.type==="relay_shape_poke");l(a.length).toBe(1),l(a[0]?.targetConnectionId).toBeUndefined()}finally{s?.()}})})})};export{W as defineEngineContractSuite};
1
+ import{createShardCtxDb as C}from"./NotUniqueError-CO-HgL4c.mjs";import{createRelayLink as N}from"./DEFAULT_MAX_RELAYS-B66neS_B.mjs";import{ConflictError as q}from"./ConflictError-C8GtJmjS.mjs";import{runShardMigrations as B}from"./runShardMigrations-xu993yo2.mjs";import{d as x}from"./relay-CKEdfUjH.mjs";const v=(O,y={})=>({_meta:{column:{notNull:!0,...y}},kind:O}),W=(O,y,F)=>{const{describe:_,expect:l,it:b}=F;_(`engine contract: ${O}`,()=>{_("optimistic concurrency",()=>{const g=u=>({tables:{items:{indexes:[],shape:{title:v("string"),version:v("number",{notNull:!1})},triggerMap:{clobber:{handler:()=>{u.exec(`UPDATE "items" SET "__doc__" = json_set("__doc__", '$.version', 99) WHERE "id" = 'i1'`)},op:"update",timing:"before"}}}}});b("raises a CONFLICT of kind `occ` when a write's snapshot is clobbered",async()=>{const{close:u,host:h}=y();try{const d=h.sql,p=g(d);B(d,p);const s=C({schema:p,sql:d});await s.insert("items",{_id:"i1",title:"first",version:1},{allowExplicitId:!0}),await l(s.patch("items","i1",{title:"second"})).rejects.toBeInstanceOf(q)}finally{u?.()}}),b("reports the conflict as CONFLICT/409 rather than retrying it away",async()=>{const{close:u,host:h}=y();try{const d=h.sql,p=g(d);B(d,p);const s=C({schema:p,sql:d});await s.insert("items",{_id:"i1",title:"first",version:1},{allowExplicitId:!0});let r;try{await s.patch("items","i1",{title:"second"})}catch(t){r=t}const e=r;l(e.code).toBe("CONFLICT"),l(e.kind).toBe("occ")}finally{u?.()}}),b("leaves the row readable and unchanged after a conflict",async()=>{const{close:u,host:h}=y();try{const d=h.sql,p=g(d);B(d,p);const s=C({schema:p,sql:d});await s.insert("items",{_id:"i1",title:"first",version:1},{allowExplicitId:!0});try{await s.patch("items","i1",{title:"second"})}catch{}const r=await s.get("items","i1");l(r?.title).toBe("first"),l(r?.version).toBe(99)}finally{u?.()}}),b("raises a CONFLICT of kind `trigger` when a trigger writes its own row through the db",async()=>{const{close:u,host:h}=y();try{const d=h.sql,p={tables:{items:{indexes:[],shape:{title:v("string"),version:v("number",{notNull:!1})},triggerMap:{recurse:{handler:async(t,a)=>{await t.db.patch("items",a.doc._id,{version:99})},op:"update",timing:"before"}}}}};B(d,p);const s=C({schema:p,sql:d});await s.insert("items",{_id:"i1",title:"first",version:1},{allowExplicitId:!0});let r;try{await s.patch("items","i1",{title:"second"})}catch(t){r=t}const e=r;l(e).toBeInstanceOf(q),l(e.code).toBe("CONFLICT"),l(e.kind).toBe("trigger")}finally{u?.()}})}),_("shape-poke ordering",()=>{const g="shard-a",u={args:{},name:"messages"},h=(e,t,a,n)=>e.accept(t?.()??{},{connectionId:a,shapes:{[n]:u}}),d=(e,t,a,n=new Set)=>{let c=0,i=0;const o=k=>()=>{throw new Error(`the relay poke path must not reach RelayHost.${k}`)},m={fetch:(k,E)=>{if(JSON.parse(E?.body??"{}").type!=="relay_shape_subscribe")return Promise.resolve(new Response(void 0,{status:204}));const I=a[i];if(i+=1,I===void 0)throw new Error("the relay asked for more seeds than this fixture supplies");return Promise.resolve(Response.json(I))}},f={get:()=>m,getByName:()=>m,idFromName:k=>k},w={buildShapeDiff:o("buildShapeDiff"),computeOpLogShapeSeed:o("computeOpLogShapeSeed"),currentCdcEpoch:o("currentCdcEpoch"),deliverWhisperLocal:o("deliverWhisperLocal"),dropIfLapsed:k=>n.has((k.deserializeAttachment?.()).connectionId??""),doName:()=>x(g,0),env:()=>({SHARD:f}),getWebSockets:()=>e.getSockets(),maskMetadata:o("maskMetadata"),nextPokeId:()=>(c+=1,`poke-${String(c)}`),readAttachment:k=>k.deserializeAttachment?.(),recordShapePokeFanout:()=>{},resolveShape:o("resolveShape"),rlsMetadata:o("rlsMetadata"),shardBinding:()=>"SHARD",shardJurisdiction:()=>{},sql:()=>t},S=N(w);if(S===void 0)throw new Error("expected a relay link for a `…::relay::N` name");return S},p=e=>new Request("https://relay.internal/_lunora/relay",{body:JSON.stringify(e),headers:{"content-type":"application/json"},method:"POST"}),s=async(e,t,a)=>{const n=await e.seedRelayShape(t,a,u,{identity:void 0,userId:void 0});if(n!=="ok")throw new Error(`seed failed: ${JSON.stringify(n)}`)},r=(e={})=>p({...u,checkpoint:20,epoch:"e1",fromCursor:10,rowsPatch:[{id:"r1",op:"upsert",value:{title:"hello"}}],type:"relay_shape_poke",...e});b("frames a poke as pokeStart → pokePart per shape → pokeEnd, under one poke id",async()=>{const{close:e,createSocket:t,host:a,readFrames:n,sockets:c}=y();try{const i=d(c,a.sql,[{cursor:10,epoch:"e1",frames:[]}]),o=h(c,t,"c-alice","s1");await s(i,o,"s1"),await i.handleControl(r());const f=(await n(o)).map(w=>JSON.parse(w));l(f.map(w=>w.type)).toStrictEqual(["pokeStart","pokePart","pokeEnd"]),l(new Set(f.map(w=>w.pokeId)).size).toBe(1),l(f[1]?.shapeId).toBe("s1"),l(f[2]?.checkpoint).toBe(20)}finally{e?.()}}),b("delivers a poke only to sockets whose cursor matches, and advances them past it",async()=>{const{close:e,createSocket:t,host:a,readFrames:n,sockets:c}=y();try{const i=d(c,a.sql,[{cursor:10,epoch:"e1",frames:[]},{cursor:7,epoch:"e1",frames:[]}]),o=h(c,t,"c-alice","s1"),m=h(c,t,"c-bob","s2");await s(i,o,"s1"),await s(i,m,"s2"),await i.handleControl(r());const f=await n(o);l(f.length).toBe(3);const w=await n(m);l(w.length).toBe(0),await i.handleControl(r());const S=await n(o);l(S.length).toBe(3)}finally{e?.()}}),b("pokes no subscriber the host reports lapsed, and still pokes the others",async()=>{const{close:e,createSocket:t,host:a,readFrames:n,sockets:c}=y();try{const i=new Set,o=d(c,a.sql,[{cursor:10,epoch:"e1",frames:[]},{cursor:10,epoch:"e1",frames:[]}],i),m=h(c,t,"c-alice","s1"),f=h(c,t,"c-bob","s2");await s(o,m,"s1"),await s(o,f,"s2"),i.add("c-bob"),await o.handleControl(r());const w=await n(m),S=await n(f);l(w.length).toBe(3),l(S.length).toBe(0)}finally{e?.()}}),b("skips a socket whose cursor matches under a different CDC epoch",async()=>{const{close:e,createSocket:t,host:a,readFrames:n,sockets:c}=y();try{const i=d(c,a.sql,[{cursor:10,epoch:"e1",frames:[]}]),o=h(c,t,"c-alice","s1");await s(i,o,"s1"),await i.handleControl(r({epoch:"e2"}));const m=await n(o);l(m.length).toBe(0),await i.handleControl(r());const f=await n(o);l(f.length).toBe(3)}finally{e?.()}})}),_("orderBy null placement",()=>{const g=[["a",void 0],["b",3],["c",void 0],["d",1],["e",void 0],["f",3],["g",2],["h",void 0]],u=[{nulls:"first",sort:"asc"},{nulls:"last",sort:"asc"},{nulls:"first",sort:"desc"},{nulls:"last",sort:"desc"}],h=({nulls:p,sort:s})=>{const r=new Map(g.map(([t],a)=>[t,a])),e=s==="asc"?1:-1;return g.toSorted(([t,a],[n,c])=>a!==c?a===void 0?p==="first"?-1:1:c===void 0?p==="first"?1:-1:(a-c)*e:((r.get(t)??0)-(r.get(n)??0))*e).map(([t])=>t)},d=p=>p.map(s=>String(s.label));b("pages every placement in threes with no row skipped or repeated",async()=>{const{close:p,host:s}=y();try{const r=s.sql,e=u.map((i,o)=>`items_${String(o)}`),t={label:v("string"),score:v("number",{notNull:!1})},a={tables:Object.fromEntries(e.map(i=>[i,{indexes:[{fields:["score"],name:"by_score"}],shape:t}]))};B(r,a);let n=17e11;const c=C({clock:()=>(n+=1e3,n),schema:a,sql:r});for(const i of e)for(const[o,m]of g)await c.insert(i,m===void 0?{label:o}:{label:o,score:m});for(const[i,o]of u.entries()){const m=e[i]??"",f=await c.findMany(m,{orderBy:[{score:o}]});l(d(f.page)).toStrictEqual(h(o));const w=[];let S;for(let k=0;k<g.length+2;k+=1){const E=await c.findMany(m,{cursor:S,limit:3,orderBy:[{score:o}]});if(w.push(...d(E.page)),E.isDone)break;S=E.continueCursor}l(w).toStrictEqual(h(o))}}finally{p?.()}})}),_("RLS identity under live subscription",()=>{const g="shard-a",u={args:{},name:"lobby-messages"},h={args:{},name:"my-orders"},d=s=>{const r=[],e=[],t={fetch:(c,i)=>(r.push(JSON.parse(i?.body??"{}")),Promise.resolve(new Response(void 0,{status:204})))},n=N({buildShapeDiff:()=>[{id:"r1",op:"upsert",value:{}}],computeOpLogShapeSeed:()=>({baseCheckpoint:void 0,cursor:10,epoch:"e1",reset:!0,rowsPatch:[]}),currentCdcEpoch:()=>"e1",deliverWhisperLocal:()=>0,dropIfLapsed:()=>!1,doName:()=>g,env:()=>({SHARD:{get:()=>t,getByName:()=>t,idFromName:c=>c}}),getWebSockets:()=>[],maskMetadata:()=>({columns:[]}),nextPokeId:()=>"poke-1",readAttachment:()=>({}),recordShapePokeFanout:()=>{},resolveShape:(c,i,o)=>(e.push(o),c===h.name?{columns:["id"],effectiveWhere:{org:o?.identity?.org??"anonymous"},global:!1,table:"orders"}:{columns:["id"],effectiveWhere:{room:"lobby"},global:!1,table:"messages"}),rlsMetadata:()=>({policies:[]}),shardBinding:()=>"SHARD",shardJurisdiction:()=>{},sql:()=>s});if(n===void 0)throw new Error("expected an owner link for an un-suffixed DO name");return{owner:n,posts:r,resolvedUnder:e}},p=async(s,r)=>{await s.handleControl(new Request("https://owner.internal/_lunora/relay",{body:JSON.stringify({...r,connectionId:"c-alice",identity:{org:"acme"},relayIndex:0,subId:"s1",type:"relay_shape_subscribe",userId:"u1"}),headers:{"content-type":"application/json"},method:"POST"}))};b("seeds a subscriber under its own forwarded identity, never the anonymous one",async()=>{const{close:s,host:r}=y();try{const{owner:e,resolvedUnder:t}=d(r.sql);await p(e,h),l(t.some(a=>a?.userId==="u1"&&a.identity?.org==="acme")).toBe(!0)}finally{s?.()}}),b("routes an identity-scoped shape to a per-socket poke, not the cohort multicast",async()=>{const{close:s,host:r}=y();try{const{owner:e,posts:t}=d(r.sql);await p(e,h),t.length=0,await e.onFlush(new Set(["orders"]),20);const a=t.filter(n=>n.type==="relay_shape_poke");l(a.length).toBe(1),l(a[0]?.targetConnectionId).toBe("c-alice")}finally{s?.()}}),b("still multicasts an identity-blind shape to the whole cohort",async()=>{const{close:s,host:r}=y();try{const{owner:e,posts:t}=d(r.sql);await p(e,u),t.length=0,await e.onFlush(new Set(["messages"]),20);const a=t.filter(n=>n.type==="relay_shape_poke");l(a.length).toBe(1),l(a[0]?.targetConnectionId).toBeUndefined()}finally{s?.()}})})})};export{W as defineEngineContractSuite};
@@ -0,0 +1 @@
1
+ import{LunoraError as c}from"@lunora/errors";import{WIRE_TAG as T,decodeWire as $,needsWireEncoding as h,encodeWire as A}from"@lunora/wire";import{sql as n}from"drizzle-orm";import{e as O}from"./effective-kind-BmG_zCAy.mjs";import{S as g,i as y,s as b,F as N}from"./json-field-path-DeJW4U9z.mjs";import{quoteIdentifier as I}from"./quoteIdentifier-CObIFRhb.mjs";import{runDrizzle as d}from"./runDrizzle-RC09zZrh.mjs";import{serializeSqlValue as j}from"./serializeSqlValue-DeoBMpZ2.mjs";import{sqlComparableProjection as L}from"./BIGINT_KEY_DIGITS-DE6yshOt.mjs";const w=/^[A-Za-z_$][\w$]*$/u,f=e=>w.test(e)?e:`"${e.replaceAll("\\",String.raw`\\`).replaceAll('"',String.raw`\"`)}"`,l="__doc__",i="__originals__",H=e=>{if(Object.hasOwn(e,i))throw new c("BAD_REQUEST",`"${i}" is reserved by the row store's document encoding and cannot be used as a field name — rename the field`);let t,r;for(const[s,a]of Object.entries(e)){const _=L(a);_!==void 0&&(t??={...e},r??=Object.create(null),t[s]=_,r[s]=a)}t&&r&&(t[i]=r);const o=t??e;try{return h(o)?JSON.stringify(A(o)):JSON.stringify(o)}catch(s){throw new c("BAD_REQUEST",`this document cannot be stored: ${s instanceof Error?s.message:String(s)}`)}},P=e=>{const t=JSON.parse(e),r=e.includes(T)||e.includes(String.raw`\u`)?$(t):t,o=r[i];if(o===null||typeof o!="object"||Array.isArray(o))return r;const s={...r};return delete s[i],{...s,...o}},Z=(e,t)=>`${e}__geo_${t}`,D=e=>{try{return b(e)}catch(t){throw t instanceof N?new c("VALIDATION_ERROR",t.message):t}},S=e=>`'$.${(y(e)?D(e).map(r=>f(r)).join("."):f(e)).replaceAll("'","''")}'`,E=(e,t)=>t==="_id"||t==="id"?`${e}id`:t==="_creationTime"?`${e}_creationTime`:`json_extract(${e}${l}, ${S(t)})`,R=e=>E("",e),q=(e,t)=>`NULLIF(json_type(${l}, ${S(e)}), 'null') IN (${g[t]})`,C=e=>n.raw(R(e)),U=(e,t)=>n.raw(q(e,t)),G=(e,t)=>E(`${I(e)}.`,t),ee=(e,t)=>n.raw(G(e,t)),te=(e,t,r,o)=>n`CREATE ${o?n`UNIQUE `:n``}INDEX IF NOT EXISTS ${n.identifier(e)} ON ${n.identifier(t)} (${r})`,u=n.identifier("__key__"),v=n.identifier("__value__"),F=n.identifier("__count__"),re=(e,t,r,o,s)=>n`INSERT INTO ${n.identifier(e)} (${u}, ${v}, ${F}) VALUES (${t}, ${r}, ${o}) ON CONFLICT(${u}) DO UPDATE SET ${s}`,oe=(e,t)=>e===void 0||t!==0&&t!==1||O(e)!=="boolean"?t:t===1,m=new WeakMap,ne=e=>{const t=m.get(e);if(t!==void 0)return t;const r=[];for(const[o,s]of Object.entries(e.shape)){const a=s._meta?.column;a&&r.push(Object.freeze([o,a]))}return Object.freeze(r),m.set(e,r),r},J=e=>{if(!e)return;const t=e[l];let r;typeof t=="string"?r=P(t):t&&typeof t=="object"?r=t:r={};const{id:o}=e;typeof o=="string"&&(r._id=o);const s=e._creationTime;return typeof s=="number"&&(r._creationTime=s),r},se=e=>{try{return J(e)}catch{return}},p=new WeakMap,W=Symbol("lunora.wrappedSql"),z=e=>e[W]??e,ae=e=>{const t=z(e),r=p.get(t);if(r!==void 0)return r;let o;try{d(t,n`CREATE VIRTUAL TABLE IF NOT EXISTS ${n.identifier("__lunora_fts_probe")} USING fts5(x)`),o=!0}catch{o=!1}finally{try{d(t,n`DROP TABLE IF EXISTS ${n.identifier("__lunora_fts_probe")}`)}catch{}}return p.set(t,o),o},ie={fieldRef:C,rangeTypeGuard:U,serialize:j};export{F as A,l as D,W,u as a,v as b,re as c,te as d,C as e,ee as f,Z as g,se as h,ae as i,R as j,H as k,P as l,ie as m,i as n,f as o,q as p,G as q,J as r,oe as s,ne as t,z as u,U as v};
@@ -0,0 +1 @@
1
+ import{BIGINT_KEY_DIGITS as f}from"./BIGINT_KEY_DIGITS-DE6yshOt.mjs";const s=40,c=(e,t)=>{let n=0;const i=(o,r)=>typeof r=="bigint"?(n+=f+1+s,r.toString()):r instanceof ArrayBuffer||ArrayBuffer.isView(r)?(n+=2*Math.ceil(r.byteLength/3)*4+s,""):r;try{const o=JSON.stringify(e,i);return(o===void 0?0:t(o))+n}catch{return}},y=e=>c(e,t=>t.length),a=e=>{let t=0;for(const n of e){const i=n.codePointAt(0)??0;i<128?t+=1:i<2048?t+=2:i<65536?t+=3:t+=4}return t},l=e=>c(e,a);export{l as a,y as e,a as u};
@@ -1,4 +1,4 @@
1
- import{LunoraError as T}from"@lunora/errors";import{sql as m}from"drizzle-orm";import{runDrizzle as S}from"./runDrizzle-RC09zZrh.mjs";import{liftSourceId as A}from"./liftSourceId-CA3ENhXj.mjs";import{normalizeSourceValue as W}from"./liftSourceId-CA3ENhXj.mjs";import{runExternalSourceTick as C,materializeExternalRowsIncremental as D}from"./materializeExternalRows-BakYlgvb.mjs";const p="__lunora_source_cursor",M=e=>e instanceof Date?`d:${e.toISOString()}`:typeof e=="bigint"?`b:${e.toString()}`:typeof e=="number"?`n:${e.toString()}`:`s:${e}`,v=e=>{const t=e.slice(2);switch(e[0]){case"b":return BigInt(t);case"d":return new Date(t);case"n":return Number(t);default:return t}},h=/^-?\d+$/,N=/^-?\d+(?:\.\d+)?$/,x=(e,t)=>e instanceof Date&&t instanceof Date?e.getTime()>t.getTime():typeof e=="bigint"&&typeof t=="bigint"||typeof e=="number"&&typeof t=="number"?e>t:typeof e=="string"&&typeof t=="string"&&N.test(e)&&N.test(t)?h.test(e)&&h.test(t)?BigInt(e)>BigInt(t):Number(e)>Number(t):String(e)>String(t),O=(e,t,o)=>{let n=o===null?void 0:v(o);for(const r of e){const c=r[t];if(c==null)continue;const a=c;(n===void 0||x(a,n))&&(n=a)}return n===void 0?null:M(n)},B=e=>{S(e,m`CREATE TABLE IF NOT EXISTS ${m.identifier(p)} (
1
+ import{LunoraError as T}from"@lunora/errors";import{sql as m}from"drizzle-orm";import{runDrizzle as S}from"./runDrizzle-RC09zZrh.mjs";import{liftSourceId as A}from"./liftSourceId-CA3ENhXj.mjs";import{normalizeSourceValue as W}from"./liftSourceId-CA3ENhXj.mjs";import{runExternalSourceTick as C,materializeExternalRowsIncremental as D}from"./materializeExternalRows-CHPRx8fu.mjs";const p="__lunora_source_cursor",M=e=>e instanceof Date?`d:${e.toISOString()}`:typeof e=="bigint"?`b:${e.toString()}`:typeof e=="number"?`n:${e.toString()}`:`s:${e}`,v=e=>{const t=e.slice(2);switch(e[0]){case"b":return BigInt(t);case"d":return new Date(t);case"n":return Number(t);default:return t}},h=/^-?\d+$/,N=/^-?\d+(?:\.\d+)?$/,x=(e,t)=>e instanceof Date&&t instanceof Date?e.getTime()>t.getTime():typeof e=="bigint"&&typeof t=="bigint"||typeof e=="number"&&typeof t=="number"?e>t:typeof e=="string"&&typeof t=="string"&&N.test(e)&&N.test(t)?h.test(e)&&h.test(t)?BigInt(e)>BigInt(t):Number(e)>Number(t):String(e)>String(t),O=(e,t,o)=>{let n=o===null?void 0:v(o);for(const r of e){const c=r[t];if(c==null)continue;const a=c;(n===void 0||x(a,n))&&(n=a)}return n===void 0?null:M(n)},B=e=>{S(e,m`CREATE TABLE IF NOT EXISTS ${m.identifier(p)} (
2
2
  table_name TEXT NOT NULL,
3
3
  shard_key TEXT NOT NULL,
4
4
  watermark TEXT,
@@ -1 +1 @@
1
- import{sql as t}from"drizzle-orm";import{runDrizzle as l}from"./runDrizzle-RC09zZrh.mjs";import{e as i}from"./do-sql-RROYQPCM.mjs";const f=(r,o)=>{const n=o-(r.after??0),e=[t`${i(r.field)} IS NOT NULL`,t`${i(r.field)} < ${n}`];return r.softDeleteField!==void 0&&e.push(t`${i(r.softDeleteField)} IS NULL`),e},L=(r,o,n,e)=>{const d=t`SELECT id FROM ${t.identifier(o.table)} WHERE ${t.join(f(o,n),t` AND `)} LIMIT ${t.raw(String(Math.max(0,Math.floor(e))+1))}`,s=l(r,d).toArray(),a=s.length>e,$=s.slice(0,e).map(E=>E.id);return{hasMore:a,ids:$}},S=(r,o,n,e)=>{const d=t`SELECT 1 AS hit FROM ${t.identifier(o.table)} WHERE id = ${n} AND ${t.join(f(o,e),t` AND `)}`;return l(r,d).toArray().length>0},c=(r,o)=>o===void 0?i(r):t`${i(o)}, ${i(r)}`,h=(r,o)=>{const n=o.softDeleteField===void 0?t``:t` WHERE ${i(o.softDeleteField)} IS NULL`,e=t`SELECT MIN(${i(o.field)}) AS expiry FROM ${t.identifier(o.table)}${n}`,d=l(r,e).toArray()[0]?.expiry;return typeof d=="number"?d+(o.after??0):void 0};export{S as isTtlExpired,h as nextTtlExpiry,L as selectExpiredIds,c as ttlIndexColumns};
1
+ import{sql as t}from"drizzle-orm";import{runDrizzle as l}from"./runDrizzle-RC09zZrh.mjs";import{e as i}from"./do-sql-105TONaE.mjs";const f=(r,o)=>{const n=o-(r.after??0),e=[t`${i(r.field)} IS NOT NULL`,t`${i(r.field)} < ${n}`];return r.softDeleteField!==void 0&&e.push(t`${i(r.softDeleteField)} IS NULL`),e},L=(r,o,n,e)=>{const d=t`SELECT id FROM ${t.identifier(o.table)} WHERE ${t.join(f(o,n),t` AND `)} LIMIT ${t.raw(String(Math.max(0,Math.floor(e))+1))}`,s=l(r,d).toArray(),a=s.length>e,$=s.slice(0,e).map(E=>E.id);return{hasMore:a,ids:$}},S=(r,o,n,e)=>{const d=t`SELECT 1 AS hit FROM ${t.identifier(o.table)} WHERE id = ${n} AND ${t.join(f(o,e),t` AND `)}`;return l(r,d).toArray().length>0},c=(r,o)=>o===void 0?i(r):t`${i(o)}, ${i(r)}`,h=(r,o)=>{const n=o.softDeleteField===void 0?t``:t` WHERE ${i(o.softDeleteField)} IS NULL`,e=t`SELECT MIN(${i(o.field)}) AS expiry FROM ${t.identifier(o.table)}${n}`,d=l(r,e).toArray()[0]?.expiry;return typeof d=="number"?d+(o.after??0):void 0};export{S as isTtlExpired,h as nextTtlExpiry,L as selectExpiredIds,c as ttlIndexColumns};
@@ -1 +1 @@
1
- import{applyCdcChanges as p}from"./CDC_LOG_TABLE-CTkXVeJx.mjs";import{selectShapeRows as m}from"./selectShapeMembers-BhK79123.mjs";import{diffExternalSource as g,projectExternalSourceRow as l}from"./diffExternalSource-B0FZlDoL.mjs";import{stableStringify as d}from"@lunora/wire";const x=async(t,s,a,e)=>{const{changes:o,nextBaseline:n}=g(s,a,e);return await p(t,o),{applied:o.length,nextBaseline:n}},R=async(t,s,a)=>{const{columns:e,deletedIds:o,table:n}=a,r=[];for(const f of s){const i=l(f,e),c=String(i._id);if(o?.has(c)){await t.get(n,c)&&r.push({id:c,op:"delete",seq:0,table:n,ts:0});continue}const u=await t.get(n,c);u&&d(l({...u,_id:c},e))===d(i)||r.push({doc:i,id:c,op:"insert",seq:0,table:n,ts:0})}return await p(t,r),{applied:r.length}},h=(t,s,a)=>{const e=new Map;for(const{doc:o,id:n}of m(t,s,void 0))e.set(n,d(l({...o,_id:n},a)));return e},_=async(t,s,a,e)=>{const o=h(t,e.table,e.columns);return x(s,a,o,e)};export{x as materializeExternalRows,R as materializeExternalRowsIncremental,h as readExternalSourceBaseline,_ as runExternalSourceTick};
1
+ import{applyCdcChanges as p}from"./CDC_LOG_TABLE-BFGgqai8.mjs";import{selectShapeRows as m}from"./selectShapeMembers-Dqx_m7BF.mjs";import{diffExternalSource as g,projectExternalSourceRow as l}from"./diffExternalSource-B0FZlDoL.mjs";import{stableStringify as d}from"@lunora/wire";const x=async(t,s,a,e)=>{const{changes:o,nextBaseline:n}=g(s,a,e);return await p(t,o),{applied:o.length,nextBaseline:n}},R=async(t,s,a)=>{const{columns:e,deletedIds:o,table:n}=a,r=[];for(const f of s){const i=l(f,e),c=String(i._id);if(o?.has(c)){await t.get(n,c)&&r.push({id:c,op:"delete",seq:0,table:n,ts:0});continue}const u=await t.get(n,c);u&&d(l({...u,_id:c},e))===d(i)||r.push({doc:i,id:c,op:"insert",seq:0,table:n,ts:0})}return await p(t,r),{applied:r.length}},h=(t,s,a)=>{const e=new Map;for(const{doc:o,id:n}of m(t,s,void 0))e.set(n,d(l({...o,_id:n},a)));return e},_=async(t,s,a,e)=>{const o=h(t,e.table,e.columns);return x(s,a,o,e)};export{x as materializeExternalRows,R as materializeExternalRowsIncremental,h as readExternalSourceBaseline,_ as runExternalSourceTick};
@@ -1,4 +1,4 @@
1
- import{LunoraError as X}from"@lunora/errors";import{f as y,S as $}from"./fts-companion-CE3EmIjk.mjs";import{sql as t}from"drizzle-orm";import{aggregateTableName as R}from"./aggregateTableName-B_CtIQCS.mjs";import{backfillSearchIndexesForTable as b}from"./backfillAggregateIndexes-CRNxxM19.mjs";import{migrateCdcLog as k,migrateCdcMeta as w}from"./CDC_LOG_TABLE-CTkXVeJx.mjs";import{migrateClientWatermark as P}from"./CLIENT_WATERMARK_TABLE-De7z_OHV.mjs";import{migrateCommitSeq as B}from"./COMMIT_SEQ_FIELD-Da1DjGqo.mjs";import{migrateCompanionState as G}from"./CompanionMemo-BXU5vfak.mjs";import{migrateGlobalShapeSnapshot as Y}from"./GLOBAL_SHAPE_SNAPSHOT_TABLE-Bb6-aZuH.mjs";import{migrateIdempotency as v}from"./IDEMPOTENCY_TABLE-COrgeP3O.mjs";import{m as W}from"./ctx-db-relay-shapes-DBobAek2.mjs";import{migrateScheduleOutbox as j}from"./SCHEDULE_OUTBOX_TABLE-DcZI7Yhl.mjs";import{m as H}from"./ctx-db-search-state-CPKPy8N6.mjs";import{migrateShapePokeCursor as K}from"./SHAPE_POKE_CURSOR_TABLE-BGvY3sFI.mjs";import{runDrizzle as d,runAll as V}from"./runDrizzle-RC09zZrh.mjs";import{D as z,d as l,e as p,t as Q,i as Z,g as J,a as q,b as ee,A as O}from"./do-sql-RROYQPCM.mjs";import{renderSql as N}from"./WORKERD_SQLITE_LIMITS-B_4w7tzY.mjs";import{migrateDurableStreams as te}from"./appendStreamChunk-BZYgGE9Y.mjs";import{rankTableName as x,sortColumnName as re}from"./RANK_TIEBREAK-D3ye2GsL.mjs";import{migrateReactorState as ne}from"./REACTOR_STATE_TABLE-D2Mn204f.mjs";import{recordSchemaVersion as oe}from"./SCHEMA_HISTORY_MAX_VERSIONS-CEwFjj-O.mjs";import{ttlIndexColumns as ie}from"./isTtlExpired-BmiUp7MF.mjs";const g=t`_creationTime, id`,D="__by_creation",ae="__ttl",se=`, ${N("sqlite",g).sql})`,A="__lunora_framework_indexes",f=e=>e.replaceAll(/[A-Z]/gu,r=>r.toLowerCase());class U extends X{}const F=(e,r,n,a,i,o)=>{const s=t.join(i.map(m=>t`${m} IS NOT NULL`),t` AND `);if(d(e,t`SELECT 1 FROM ${t.identifier(n)} WHERE ${s} GROUP BY ${a} HAVING COUNT(*) > 1 LIMIT 1`).toArray().length>0)throw new U("UNIQUE_INDEX_DUPLICATES",`unique index "${r}" on "${n}" ${o}: existing rows are duplicates under it. De-duplicate the table with a data migration first; the previous index is left in place.`)},L=(e,r,n,a,i,o)=>{const c=d(e,t`SELECT sql FROM sqlite_master WHERE type = 'index' AND name = ${r} COLLATE NOCASE AND tbl_name = ${n} COLLATE NOCASE`).toArray()[0]?.sql;if(c==null)return;const m=E=>{const I=E.indexOf("(");return I===-1?void 0:E.slice(I,E.lastIndexOf(")")+1)},_=m(N("sqlite",l(r,n,a,i)).sql),T=m(c);_===void 0||T===void 0||_===T||(i&&F(e,r,n,a,o,"cannot be re-created with its new column list"),d(e,t`DROP INDEX IF EXISTS ${t.identifier(r)}`))},de=(e,r,n)=>d(e,t`SELECT 1 FROM sqlite_master WHERE type = 'index' AND name = ${r} COLLATE NOCASE AND tbl_name = ${n} COLLATE NOCASE LIMIT 1`).toArray().length>0,C=(e,r,n,a,i,o)=>{i&&!de(e,r,n)&&F(e,r,n,a,o,"cannot be created"),d(e,l(r,n,a,i))},h=(e,r)=>{try{r()}catch(n){if(e===void 0||!(n instanceof U))throw n;e.push(n.message)}},ce=(e,r,n)=>f(r).startsWith(`${f(e)}_`)&&f(r)!==f(`${e}${D}`)&&n!==null&&(n.includes("json_extract(")||n.trimEnd().endsWith(se)),S=new WeakMap,u=(e,r,n)=>{let a=S.get(e);a===void 0&&(a=new Set(d(e,t`SELECT name FROM ${t.identifier(A)}`).toArray().map(i=>f(i.name))),S.set(e,a)),!a.has(f(r))&&(d(e,t`INSERT OR IGNORE INTO ${t.identifier(A)} (name, table_name) VALUES (${r}, ${n})`),a.add(f(r)))},me=(e,r)=>{const n=d(e,t`SELECT 1 FROM sqlite_master WHERE type = 'table' AND name = ${A} COLLATE NOCASE`).toArray().length>0;if(d(e,t`CREATE TABLE IF NOT EXISTS ${t.identifier(A)} (name TEXT PRIMARY KEY COLLATE NOCASE, table_name TEXT NOT NULL)`),!n)for(const a of r){const i=d(e,t`SELECT name, sql FROM sqlite_master WHERE type = 'index' AND tbl_name = ${a} COLLATE NOCASE AND sql IS NOT NULL`).toArray();for(const{name:o,sql:s}of i)ce(a,o,s)&&u(e,o,a)}},fe=(e,r,n)=>{const a=new Set([...n].map(o=>f(o))),i=d(e,t`SELECT "l"."name" FROM ${t.identifier(A)} AS "l" WHERE "l"."table_name" = ${r} COLLATE NOCASE`).toArray();for(const{name:o}of i)a.has(f(o))||(d(e,t`DROP INDEX IF EXISTS ${t.identifier(o)}`),d(e,t`DELETE FROM ${t.identifier(A)} WHERE ${t.identifier(A)}."name" = ${o}`),S.get(e)?.delete(f(o)))},Ee=(e,r,n,a)=>{const i=`${r}${ae}`,o=new Set([...a].map(c=>f(c)));if(n.ttlPolicy===void 0||o.has(f(i)))return;const s=ie(n.ttlPolicy.field,n.softDeleteMode?.field);a.add(i);try{L(e,i,r,s,!1,[]),d(e,l(i,r,s,!1)),u(e,i,r)}catch{}},_e=(e,r,n,a)=>{const i=new Set;for(const o of n.indexes){const s=`${r}_${o.name}`,c=o.unique??!1,m=o.fields.map(E=>p(E)),_=t.join(m,t`, `),T=c?_:t`${_}, ${g}`;i.add(s),h(a,()=>{L(e,s,r,T,c,m),C(e,s,r,T,c,m),u(e,s,r)})}for(const[o,s]of Q(n)){if(!s.unique)continue;const c=p(o),m=`${r}_unique_${o}`;i.add(m),h(a,()=>{L(e,m,r,c,!0,[c]),C(e,m,r,c,!0,[c]),u(e,m,r)})}Ee(e,r,n,i),fe(e,r,i)},Te=(e,r,n)=>{if(!(!n.searchIndexes||n.searchIndexes.length===0||!Z(e))){for(const a of n.searchIndexes)V(e,y($(r,a.name)));b(e,r,n)}},Ae=(e,r,n)=>{if(n.geoIndexes)for(const a of n.geoIndexes){const i=J(r,a.name);d(e,t`CREATE TABLE IF NOT EXISTS ${t.identifier(i)} (${t.identifier("__id__")} TEXT PRIMARY KEY, ${t.identifier("__geohash__")} TEXT NOT NULL, ${t.identifier("__lat__")} REAL NOT NULL, ${t.identifier("__lng__")} REAL NOT NULL)`);const o=`${r}__geo_${a.name}__btree`;d(e,l(o,i,t`${t.identifier("__geohash__")} ASC, ${t.identifier("__id__")} ASC`,!1))}},Ie=(e,r,n)=>{if(n.aggregateIndexes)for(const a of n.aggregateIndexes){const i=R(r,a.name);d(e,t`CREATE TABLE IF NOT EXISTS ${t.identifier(i)} (${q} TEXT PRIMARY KEY, ${ee} REAL, ${O} INTEGER NOT NULL DEFAULT 0)`),d(e,t`PRAGMA table_info(${t.identifier(i)})`).toArray().some(s=>s.name==="__count__")||d(e,t`ALTER TABLE ${t.identifier(i)} ADD COLUMN ${O} INTEGER NOT NULL DEFAULT 0`)}},le=(e,r,n)=>{const a=d(e,t`PRAGMA table_info(${t.identifier(r)})`).toArray().map(i=>i.name).filter(i=>i.startsWith("__sort_k"));a.length>0&&(a.length!==n.length||a.some((i,o)=>i!==n[o]))&&d(e,t`DROP TABLE ${t.identifier(r)}`)},Le=(e,r,n)=>{if(n.rankIndexes)for(const a of n.rankIndexes){const i=x(r,a.name),o=a.sortBy.map((E,I)=>re(I)),s=o.map(E=>t`${t.identifier(E)} BLOB`),c=s.length>0?t`, ${t.join(s,t`, `)}`:t``;le(e,i,o),d(e,t`CREATE TABLE IF NOT EXISTS ${t.identifier(i)} (${t.identifier("__id__")} TEXT PRIMARY KEY, ${t.identifier("__partition__")} TEXT NOT NULL${c})`);const m=[t`${t.identifier("__partition__")} ASC`];for(const[E,I]of o.entries()){const M=a.sortBy[E]?.direction;m.push(t`${t.identifier(I)} ${t.raw(M==="desc"?"DESC":"ASC")}`)}m.push(t`${t.identifier("__id__")} ASC`);const _=`${r}__rank_${a.name}__btree`,T=t.join(m,t`, `);L(e,_,i,T,!1,[]),d(e,l(_,i,T,!1))}},Ye=(e,r,n={})=>{const a=n.deferBlockedUniqueIndexes?[]:void 0;S.delete(e),n.schemaSnapshot!==void 0&&oe(e,n.schemaSnapshot.hash,n.schemaSnapshot.json),H(e),me(e,Object.entries(r.tables).filter(([,o])=>o.shardMode?.kind!=="global").map(([o])=>o));const i=[];for(const[o,s]of Object.entries(r.tables))s.shardMode?.kind!=="global"&&(d(e,t`CREATE TABLE IF NOT EXISTS ${t.identifier(o)} (
1
+ import{LunoraError as X}from"@lunora/errors";import{f as y,S as $}from"./fts-companion-CE3EmIjk.mjs";import{sql as t}from"drizzle-orm";import{aggregateTableName as R}from"./aggregateTableName-B_CtIQCS.mjs";import{backfillSearchIndexesForTable as b}from"./backfillAggregateIndexes-Pk0KLrfk.mjs";import{migrateCdcLog as k,migrateCdcMeta as w}from"./CDC_LOG_TABLE-BFGgqai8.mjs";import{migrateClientWatermark as P}from"./CLIENT_WATERMARK_TABLE-De7z_OHV.mjs";import{migrateCommitSeq as B}from"./COMMIT_SEQ_FIELD-Da1DjGqo.mjs";import{migrateCompanionState as G}from"./CompanionMemo-BXU5vfak.mjs";import{migrateGlobalShapeSnapshot as Y}from"./GLOBAL_SHAPE_SNAPSHOT_TABLE-Bb6-aZuH.mjs";import{migrateIdempotency as v}from"./IDEMPOTENCY_TABLE-COrgeP3O.mjs";import{m as W}from"./ctx-db-relay-shapes-DBobAek2.mjs";import{migrateScheduleOutbox as j}from"./SCHEDULE_OUTBOX_TABLE-iyyiSjsO.mjs";import{m as H}from"./ctx-db-search-state-CPKPy8N6.mjs";import{migrateShapePokeCursor as K}from"./SHAPE_POKE_CURSOR_TABLE-BGvY3sFI.mjs";import{runDrizzle as d,runAll as V}from"./runDrizzle-RC09zZrh.mjs";import{D as z,d as l,e as p,t as Q,i as Z,g as J,a as q,b as ee,A as O}from"./do-sql-105TONaE.mjs";import{renderSql as N}from"./WORKERD_SQLITE_LIMITS-B_4w7tzY.mjs";import{migrateDurableStreams as te}from"./appendStreamChunk-BZYgGE9Y.mjs";import{rankTableName as x,sortColumnName as re}from"./RANK_TIEBREAK-D3ye2GsL.mjs";import{migrateReactorState as ne}from"./REACTOR_STATE_TABLE-D2Mn204f.mjs";import{recordSchemaVersion as oe}from"./SCHEMA_HISTORY_MAX_VERSIONS-CEwFjj-O.mjs";import{ttlIndexColumns as ie}from"./isTtlExpired-DNxmZA6e.mjs";const g=t`_creationTime, id`,D="__by_creation",ae="__ttl",se=`, ${N("sqlite",g).sql})`,A="__lunora_framework_indexes",f=e=>e.replaceAll(/[A-Z]/gu,r=>r.toLowerCase());class U extends X{}const F=(e,r,n,a,i,o)=>{const s=t.join(i.map(m=>t`${m} IS NOT NULL`),t` AND `);if(d(e,t`SELECT 1 FROM ${t.identifier(n)} WHERE ${s} GROUP BY ${a} HAVING COUNT(*) > 1 LIMIT 1`).toArray().length>0)throw new U("UNIQUE_INDEX_DUPLICATES",`unique index "${r}" on "${n}" ${o}: existing rows are duplicates under it. De-duplicate the table with a data migration first; the previous index is left in place.`)},L=(e,r,n,a,i,o)=>{const c=d(e,t`SELECT sql FROM sqlite_master WHERE type = 'index' AND name = ${r} COLLATE NOCASE AND tbl_name = ${n} COLLATE NOCASE`).toArray()[0]?.sql;if(c==null)return;const m=E=>{const I=E.indexOf("(");return I===-1?void 0:E.slice(I,E.lastIndexOf(")")+1)},_=m(N("sqlite",l(r,n,a,i)).sql),T=m(c);_===void 0||T===void 0||_===T||(i&&F(e,r,n,a,o,"cannot be re-created with its new column list"),d(e,t`DROP INDEX IF EXISTS ${t.identifier(r)}`))},de=(e,r,n)=>d(e,t`SELECT 1 FROM sqlite_master WHERE type = 'index' AND name = ${r} COLLATE NOCASE AND tbl_name = ${n} COLLATE NOCASE LIMIT 1`).toArray().length>0,C=(e,r,n,a,i,o)=>{i&&!de(e,r,n)&&F(e,r,n,a,o,"cannot be created"),d(e,l(r,n,a,i))},h=(e,r)=>{try{r()}catch(n){if(e===void 0||!(n instanceof U))throw n;e.push(n.message)}},ce=(e,r,n)=>f(r).startsWith(`${f(e)}_`)&&f(r)!==f(`${e}${D}`)&&n!==null&&(n.includes("json_extract(")||n.trimEnd().endsWith(se)),S=new WeakMap,u=(e,r,n)=>{let a=S.get(e);a===void 0&&(a=new Set(d(e,t`SELECT name FROM ${t.identifier(A)}`).toArray().map(i=>f(i.name))),S.set(e,a)),!a.has(f(r))&&(d(e,t`INSERT OR IGNORE INTO ${t.identifier(A)} (name, table_name) VALUES (${r}, ${n})`),a.add(f(r)))},me=(e,r)=>{const n=d(e,t`SELECT 1 FROM sqlite_master WHERE type = 'table' AND name = ${A} COLLATE NOCASE`).toArray().length>0;if(d(e,t`CREATE TABLE IF NOT EXISTS ${t.identifier(A)} (name TEXT PRIMARY KEY COLLATE NOCASE, table_name TEXT NOT NULL)`),!n)for(const a of r){const i=d(e,t`SELECT name, sql FROM sqlite_master WHERE type = 'index' AND tbl_name = ${a} COLLATE NOCASE AND sql IS NOT NULL`).toArray();for(const{name:o,sql:s}of i)ce(a,o,s)&&u(e,o,a)}},fe=(e,r,n)=>{const a=new Set([...n].map(o=>f(o))),i=d(e,t`SELECT "l"."name" FROM ${t.identifier(A)} AS "l" WHERE "l"."table_name" = ${r} COLLATE NOCASE`).toArray();for(const{name:o}of i)a.has(f(o))||(d(e,t`DROP INDEX IF EXISTS ${t.identifier(o)}`),d(e,t`DELETE FROM ${t.identifier(A)} WHERE ${t.identifier(A)}."name" = ${o}`),S.get(e)?.delete(f(o)))},Ee=(e,r,n,a)=>{const i=`${r}${ae}`,o=new Set([...a].map(c=>f(c)));if(n.ttlPolicy===void 0||o.has(f(i)))return;const s=ie(n.ttlPolicy.field,n.softDeleteMode?.field);a.add(i);try{L(e,i,r,s,!1,[]),d(e,l(i,r,s,!1)),u(e,i,r)}catch{}},_e=(e,r,n,a)=>{const i=new Set;for(const o of n.indexes){const s=`${r}_${o.name}`,c=o.unique??!1,m=o.fields.map(E=>p(E)),_=t.join(m,t`, `),T=c?_:t`${_}, ${g}`;i.add(s),h(a,()=>{L(e,s,r,T,c,m),C(e,s,r,T,c,m),u(e,s,r)})}for(const[o,s]of Q(n)){if(!s.unique)continue;const c=p(o),m=`${r}_unique_${o}`;i.add(m),h(a,()=>{L(e,m,r,c,!0,[c]),C(e,m,r,c,!0,[c]),u(e,m,r)})}Ee(e,r,n,i),fe(e,r,i)},Te=(e,r,n)=>{if(!(!n.searchIndexes||n.searchIndexes.length===0||!Z(e))){for(const a of n.searchIndexes)V(e,y($(r,a.name)));b(e,r,n)}},Ae=(e,r,n)=>{if(n.geoIndexes)for(const a of n.geoIndexes){const i=J(r,a.name);d(e,t`CREATE TABLE IF NOT EXISTS ${t.identifier(i)} (${t.identifier("__id__")} TEXT PRIMARY KEY, ${t.identifier("__geohash__")} TEXT NOT NULL, ${t.identifier("__lat__")} REAL NOT NULL, ${t.identifier("__lng__")} REAL NOT NULL)`);const o=`${r}__geo_${a.name}__btree`;d(e,l(o,i,t`${t.identifier("__geohash__")} ASC, ${t.identifier("__id__")} ASC`,!1))}},Ie=(e,r,n)=>{if(n.aggregateIndexes)for(const a of n.aggregateIndexes){const i=R(r,a.name);d(e,t`CREATE TABLE IF NOT EXISTS ${t.identifier(i)} (${q} TEXT PRIMARY KEY, ${ee} REAL, ${O} INTEGER NOT NULL DEFAULT 0)`),d(e,t`PRAGMA table_info(${t.identifier(i)})`).toArray().some(s=>s.name==="__count__")||d(e,t`ALTER TABLE ${t.identifier(i)} ADD COLUMN ${O} INTEGER NOT NULL DEFAULT 0`)}},le=(e,r,n)=>{const a=d(e,t`PRAGMA table_info(${t.identifier(r)})`).toArray().map(i=>i.name).filter(i=>i.startsWith("__sort_k"));a.length>0&&(a.length!==n.length||a.some((i,o)=>i!==n[o]))&&d(e,t`DROP TABLE ${t.identifier(r)}`)},Le=(e,r,n)=>{if(n.rankIndexes)for(const a of n.rankIndexes){const i=x(r,a.name),o=a.sortBy.map((E,I)=>re(I)),s=o.map(E=>t`${t.identifier(E)} BLOB`),c=s.length>0?t`, ${t.join(s,t`, `)}`:t``;le(e,i,o),d(e,t`CREATE TABLE IF NOT EXISTS ${t.identifier(i)} (${t.identifier("__id__")} TEXT PRIMARY KEY, ${t.identifier("__partition__")} TEXT NOT NULL${c})`);const m=[t`${t.identifier("__partition__")} ASC`];for(const[E,I]of o.entries()){const M=a.sortBy[E]?.direction;m.push(t`${t.identifier(I)} ${t.raw(M==="desc"?"DESC":"ASC")}`)}m.push(t`${t.identifier("__id__")} ASC`);const _=`${r}__rank_${a.name}__btree`,T=t.join(m,t`, `);L(e,_,i,T,!1,[]),d(e,l(_,i,T,!1))}},Ye=(e,r,n={})=>{const a=n.deferBlockedUniqueIndexes?[]:void 0;S.delete(e),n.schemaSnapshot!==void 0&&oe(e,n.schemaSnapshot.hash,n.schemaSnapshot.json),H(e),me(e,Object.entries(r.tables).filter(([,o])=>o.shardMode?.kind!=="global").map(([o])=>o));const i=[];for(const[o,s]of Object.entries(r.tables))s.shardMode?.kind!=="global"&&(d(e,t`CREATE TABLE IF NOT EXISTS ${t.identifier(o)} (
2
2
  id TEXT PRIMARY KEY,
3
3
  _creationTime REAL NOT NULL,
4
4
  ${t.identifier(z)} TEXT NOT NULL
@@ -1 +1 @@
1
- import{sql as e}from"drizzle-orm";import{runDrizzle as l}from"./runDrizzle-RC09zZrh.mjs";import{D as p,r as a,m as h}from"./do-sql-RROYQPCM.mjs";import{sqliteInList as w}from"./WORKERD_SQLITE_LIMITS-B_4w7tzY.mjs";import{c as $}from"./where-sql-BjY4rnqb.mjs";const C=o=>{if(o.length!==0)return w(e`${e.identifier("id")}`,o,!1)},u=(o,i)=>{const r=[];i&&r.push(i);const t=$(o,h);return t&&r.push(t),r.length===0?e``:e` WHERE ${e.join(r,e` AND `)}`},M=(o,i,r)=>{const t=u(r,void 0),n=l(o,e`SELECT id, _creationTime, ${e.identifier(p)} FROM ${e.identifier(i)}${t}`).toArray(),f=[];for(const m of n){const s=a(m),{id:c}=m;s!==void 0&&typeof c=="string"&&f.push({doc:s,id:c})}return f},T=(o,i,r,t)=>{const n=new Map;if(t.length===0)return n;const f=u(r,C(t)),m=l(o,e`SELECT id, _creationTime, ${e.identifier(p)} FROM ${e.identifier(i)}${f}`).toArray();for(const s of m){const c=a(s),{id:d}=s;c!==void 0&&typeof d=="string"&&n.set(d,c)}return n};export{T as selectShapeMembers,M as selectShapeRows};
1
+ import{sql as e}from"drizzle-orm";import{runDrizzle as l}from"./runDrizzle-RC09zZrh.mjs";import{D as p,r as a,m as h}from"./do-sql-105TONaE.mjs";import{sqliteInList as w}from"./WORKERD_SQLITE_LIMITS-B_4w7tzY.mjs";import{c as $}from"./where-sql-BjY4rnqb.mjs";const C=o=>{if(o.length!==0)return w(e`${e.identifier("id")}`,o,!1)},u=(o,i)=>{const r=[];i&&r.push(i);const t=$(o,h);return t&&r.push(t),r.length===0?e``:e` WHERE ${e.join(r,e` AND `)}`},M=(o,i,r)=>{const t=u(r,void 0),n=l(o,e`SELECT id, _creationTime, ${e.identifier(p)} FROM ${e.identifier(i)}${t}`).toArray(),f=[];for(const m of n){const s=a(m),{id:c}=m;s!==void 0&&typeof c=="string"&&f.push({doc:s,id:c})}return f},T=(o,i,r,t)=>{const n=new Map;if(t.length===0)return n;const f=u(r,C(t)),m=l(o,e`SELECT id, _creationTime, ${e.identifier(p)} FROM ${e.identifier(i)}${f}`).toArray();for(const s of m){const c=a(s),{id:d}=s;c!==void 0&&typeof d=="string"&&n.set(d,c)}return n};export{T as selectShapeMembers,M as selectShapeRows};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@lunora/shard-engine",
3
- "version": "1.0.0-alpha.181",
3
+ "version": "1.0.0-alpha.182",
4
4
  "description": "Host-neutral reactive engine for Lunora: per-shard state, OCC, CDC, reactive subscriptions, and the poke protocol. Consumes @lunora/platform host contracts and can be mounted on any platform host.",
5
5
  "keywords": [
6
6
  "cloudflare",
@@ -49,7 +49,7 @@
49
49
  },
50
50
  "dependencies": {
51
51
  "@lunora/errors": ">=1.0.0-alpha.77 <2.0.0-0",
52
- "@lunora/platform": "1.0.0-alpha.77",
52
+ "@lunora/platform": "1.0.0-alpha.78",
53
53
  "@lunora/wire": "1.0.0-alpha.6",
54
54
  "drizzle-orm": "1.0.0-rc.5"
55
55
  },