@lunora/shard-engine 1.0.0-alpha.51 → 1.0.0-alpha.52

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 (59) hide show
  1. package/dist/conformance/index.mjs +1 -1
  2. package/dist/index.d.mts +5 -16
  3. package/dist/index.d.ts +5 -16
  4. package/dist/index.mjs +1 -1
  5. package/dist/packem_shared/{ADMIN_FUNCTIONS-oJ7IyZP6.mjs → ADMIN_FUNCTIONS-1OWiZgrN.mjs} +1 -1
  6. package/dist/packem_shared/AGG_COUNT-gkJ8xtVW.mjs +1 -0
  7. package/dist/packem_shared/{sql-projection-BqmxFxQU.mjs → BIGINT_KEY_DIGITS-Djq7G5Xx.mjs} +1 -1
  8. package/dist/packem_shared/{CDC_LOG_TABLE-gl0FuepJ.mjs → CDC_LOG_TABLE-Cva29kfS.mjs} +4 -4
  9. package/dist/packem_shared/{CURSOR_PREFIX-CoJUQfCI.mjs → CURSOR_PREFIX-B1i1J8Zi.mjs} +1 -1
  10. package/dist/packem_shared/{DATA_MIGRATION_STATE_TABLE-BHzhEE-y.mjs → DATA_MIGRATION_STATE_TABLE-Jrx6cqEc.mjs} +1 -1
  11. package/dist/packem_shared/DEFAULT_MAX_RELATION_KEYS-BbmpfQE4.mjs +1 -0
  12. package/dist/packem_shared/{DEFAULT_MAX_RELAYS-CH446J5m.mjs → DEFAULT_MAX_RELAYS-BVaTptvb.mjs} +1 -1
  13. package/dist/packem_shared/{DEFAULT_PROMOTION_THRESHOLDS-DcJw42RT.mjs → DEFAULT_PROMOTION_THRESHOLDS-CrzPqmGP.mjs} +1 -1
  14. package/dist/packem_shared/{DEFAULT_TRANSACTION_LIMITS-Bcoi7Bvf.mjs → DEFAULT_TRANSACTION_LIMITS-D_gjjTFo.mjs} +1 -1
  15. package/dist/packem_shared/{DurableStreamRunner-C3NUyv3s.mjs → DurableStreamRunner-Ds3cmo3F.mjs} +1 -1
  16. package/dist/packem_shared/NotUniqueError-C7gJLEay.mjs +1 -0
  17. package/dist/packem_shared/{RANK_TIEBREAK-D157XEqw.mjs → RANK_TIEBREAK-BXD4YaG3.mjs} +1 -1
  18. package/dist/packem_shared/RLS_UNWRAP_SYMBOL-CepZvBVl.mjs +1 -0
  19. package/dist/packem_shared/{ReactiveCache-BngdZxr9.mjs → ReactiveCache-CwSgH_wK.mjs} +1 -1
  20. package/dist/packem_shared/{ShapeDiffCache-CLm5XXd1.mjs → ShapeDiffCache-BmVH30dI.mjs} +1 -1
  21. package/dist/packem_shared/{aggregateTableName-CGi8gxeK.mjs → aggregateTableName-CCCIulmn.mjs} +1 -1
  22. package/dist/packem_shared/{applyOnDelete-BOOJzpbw.mjs → applyOnDelete-CeHLU-Hh.mjs} +1 -1
  23. package/dist/packem_shared/{awaitWsDrain-CjWMVZOG.mjs → awaitWsDrain-BqSGNI0W.mjs} +1 -1
  24. package/dist/packem_shared/backfillAggregateIndexes-BCmY3OYO.mjs +1 -0
  25. package/dist/packem_shared/{buildPokeFrames-C8km3IhJ.mjs → buildPokeFrames-CySyxldi.mjs} +1 -1
  26. package/dist/packem_shared/buildReprojectionMigration-D-9DU7D2.mjs +1 -0
  27. package/dist/packem_shared/{buildShapeDiff-BW5lKBzQ.mjs → buildShapeDiff-C-jrV9kY.mjs} +1 -1
  28. package/dist/packem_shared/{compileWhereSql-BB1JlUhC.mjs → compileWhereSql-ByHAmOE-.mjs} +1 -1
  29. package/dist/packem_shared/{computeRankPage-BH2rv2mc.mjs → computeRankPage-CuWuhRZN.mjs} +1 -1
  30. package/dist/packem_shared/createCompanionSync-DlYfWB_e.mjs +1 -0
  31. package/dist/packem_shared/{createReplicaLink-DujqFlHs.mjs → createReplicaLink-COCkDNMK.mjs} +1 -1
  32. package/dist/packem_shared/ctx-db-companions-CTabzjgb.mjs +1 -0
  33. package/dist/packem_shared/{ctx-db-relay-shapes-CnOeftkH.mjs → ctx-db-relay-shapes-B4bmET4W.mjs} +1 -1
  34. package/dist/packem_shared/{defineEngineContractSuite-B-fWLvpW.mjs → defineEngineContractSuite-BQBhgHJM.mjs} +1 -1
  35. package/dist/packem_shared/do-sql-qxXsaO03.mjs +1 -0
  36. package/dist/packem_shared/estimate-bytes-D6KN5_7y.mjs +1 -0
  37. package/dist/packem_shared/{isSoftDeleted-B6TNznFv.mjs → isSoftDeleted-cRWEfyMb.mjs} +1 -1
  38. package/dist/packem_shared/{materializeExternalRows-DZPYRDXu.mjs → materializeExternalRows-DDXDqsGW.mjs} +1 -1
  39. package/dist/packem_shared/{runShardMigrations-BqH93Q8t.mjs → runShardMigrations-DiCqfU82.mjs} +1 -1
  40. package/dist/packem_shared/{selectExpiredIds-D784Mqvh.mjs → selectExpiredIds-DHm7CSED.mjs} +1 -1
  41. package/dist/packem_shared/{selectShapeMembers-CLK9q18N.mjs → selectShapeMembers-CPdl1Ht1.mjs} +1 -1
  42. package/dist/packem_shared/serializeSqlValue-BBtrWwiu.mjs +1 -0
  43. package/dist/packem_shared/{stableWireKey-9bjKL5Gy.mjs → stableWireKey-CSJKu_ID.mjs} +1 -1
  44. package/dist/packem_shared/where-sql-B1l5NcUZ.mjs +1 -0
  45. package/dist/packem_shared/wire-codec-UyQIjlyN.mjs +1 -0
  46. package/package.json +3 -3
  47. package/dist/packem_shared/AGG_COUNT-JTc_jUaL.mjs +0 -1
  48. package/dist/packem_shared/DEFAULT_MAX_RELATION_KEYS-Fb5vfB-T.mjs +0 -1
  49. package/dist/packem_shared/NotUniqueError-DucaxGnP.mjs +0 -1
  50. package/dist/packem_shared/RLS_UNWRAP_SYMBOL-BWloGsd3.mjs +0 -1
  51. package/dist/packem_shared/backfillAggregateIndexes-CTPj9dAd.mjs +0 -1
  52. package/dist/packem_shared/buildReprojectionMigration-CR2RSgJd.mjs +0 -1
  53. package/dist/packem_shared/createCompanionSync-Bo-oIkyU.mjs +0 -1
  54. package/dist/packem_shared/ctx-db-companions-BFBIVIOd.mjs +0 -1
  55. package/dist/packem_shared/do-sql-bkXQEBl8.mjs +0 -1
  56. package/dist/packem_shared/estimate-bytes-CzG5x1f8.mjs +0 -1
  57. package/dist/packem_shared/serializeSqlValue-DbI1VQYM.mjs +0 -1
  58. package/dist/packem_shared/where-sql-4RHk2frP.mjs +0 -1
  59. package/dist/packem_shared/wire-codec-COhOSEe4.mjs +0 -1
@@ -1 +0,0 @@
1
- import{LunoraError as $}from"@lunora/errors";import{c as sn,q as rt,S as cn,l as Me,a as an}from"./ctx-db-companions-BFBIVIOd.mjs";import{sql as i}from"drizzle-orm";import{d as dn}from"./wire-codec-COhOSEe4.mjs";import{throwingScheduler as ln,aggregateSqlFunction as De,normalizeCountArgument as un}from"./AGGREGATE_SQL_FUNCTION-m1iUU1rv.mjs";import{aggregateTableName as Ke,encodeAggregateKey as Qe,readAggregateValue as ze}from"./aggregateTableName-CGi8gxeK.mjs";import{mergeWhere as Q,CountRlsUnsupportedError as Je,selectIndexForGroupBy as fn,selectIndexForCount as hn,selectIndexForAggregate as wn}from"./CountRlsUnsupportedError-Bdfupt3g.mjs";import{backfillSearchIndexesForTable as pn,searchIndexCoversTable as gn}from"./backfillAggregateIndexes-CTPj9dAd.mjs";import{backfillAggregateIndexes as wr,backfillRankIndexes as pr,backfillSearchIndexes as gr}from"./backfillAggregateIndexes-CTPj9dAd.mjs";import{appendCdcChange as $n}from"./CDC_LOG_TABLE-gl0FuepJ.mjs";import{CDC_LOG_TABLE as yr,applyCdcChanges as Er,bumpCdcEpoch as mr,cdcCanVouchFor as Sr,cdcSeqLeavingRows as _r,cdcTouchesTables as Tr,cdcTrimmedError as Rr,compactCdcDocs as vr,cursorBelowRetainedFloor as Ar,minCdcReplayableSeq as Ir,minCdcSeq as Cr,readCdcChangeKeys as xr,readCdcChanges as br,readCdcCursor as Mr,readCdcEpoch as Dr,trimCdcChanges as kr}from"./CDC_LOG_TABLE-gl0FuepJ.mjs";import{allocateCommitSeq as yn,COMMIT_SEQ_FIELD as En}from"./COMMIT_SEQ_FIELD-BUdOMG5y.mjs";import{isMemoryTable as mn}from"./clearMemoryTables-BGbmag2i.mjs";import{computeRankPage as mt}from"./computeRankPage-BH2rv2mc.mjs";import{SCAN_DEP as G}from"./SCAN_DEP-D7qE3iUe.mjs";import{runDrizzle as O,runSql as me}from"./runDrizzle-2ULFQR_k.mjs";import{D as ne,k as ce,r as le,b as ke,A as Ve,a as Le,e as X,t as Gt,j as We,q as St,i as Sn,h as Ht,g as _n}from"./do-sql-bkXQEBl8.mjs";import{renderSql as Nt,unionAll as it,WORKERD_SQLITE_LIMITS as Ot,sqliteInList as Tn}from"./param-DlozcSQu.mjs";import{coveringGeohashes as Rn,boundingBoxGeohashes as vn,haversineMeters as An,pointInBoundingBox as In}from"./GEO_DEFAULT_PRECISION-CqpQZ-J_.mjs";import{NotFoundError as Cn}from"./NotFoundError-BhF7FeFr.mjs";import{softDeleteScope as de,normalizeOrderKeys as et,buildSeekWhere as jt,decodeCursor as tt,applySelect as _t,encodeCursor as nt,tiebreakDirectionFor as Kt,buildSeekBeforeWhere as xn}from"./CURSOR_PREFIX-CoJUQfCI.mjs";import{rankTableName as Tt,sortColumnName as Rt,resolveRankPartition as bn,encodePartitionKey as Mn,RANK_TIEBREAK as Dn}from"./RANK_TIEBREAK-D157XEqw.mjs";import{indexKeysForRow as kn,buildIndexRange as Ln}from"./buildIndexRange-CBKQmHSS.mjs";import{assertFlatPredicate as Ye,resolveRelationPredicates as vt}from"./DEFAULT_MAX_RELATION_KEYS-Fb5vfB-T.mjs";import{runRowValidators as Xe,resolveWith as At,relationHooks as It,applyOnDelete as Fn,fanOutScalarCounts as qn}from"./applyOnDelete-BOOJzpbw.mjs";import{guardWriter as Wn}from"./RLS_UNWRAP_SYMBOL-BWloGsd3.mjs";import{quoteIdentifier as Se}from"./quoteIdentifier-CObIFRhb.mjs";import{i as Bn}from"./sql-projection-BqmxFxQU.mjs";import{createSystemReader as Un}from"./createSystemReader-DcDLFfC-.mjs";import{ConflictError as ye}from"./ConflictError-C8GtJmjS.mjs";import{runTriggers as Pn}from"./hasTrigger-CjlwI4le.mjs";import{c as te,t as Ue,r as Be,j as Ee,i as Ct}from"./where-sql-4RHk2frP.mjs";import{CLIENT_WATERMARK_TABLE as Fr,advanceClientWatermark as qr,migrateClientWatermark as Wr,readClientWatermark as Br}from"./CLIENT_WATERMARK_TABLE-CRnrAnJ2.mjs";import{GLOBAL_SHAPE_SNAPSHOT_TABLE as Pr,deleteGlobalShapeSnapshot as Gr,deleteGlobalShapeSnapshotsForConnection as Hr,migrateGlobalShapeSnapshot as Nr,readGlobalShapeSnapshot as Or,writeGlobalShapeSnapshot as jr}from"./GLOBAL_SHAPE_SNAPSHOT_TABLE-DSA6mzyx.mjs";import{IDEMPOTENCY_TABLE as Qr,readIdempotent as zr,trimIdempotent as Jr,writeIdempotent as Vr}from"./IDEMPOTENCY_TABLE-DOpm_oMF.mjs";import{runShardMigrations as Xr}from"./runShardMigrations-BqH93Q8t.mjs";import{SEARCH_STATE_TABLE as ei}from"./SEARCH_STATE_TABLE-xmYM_nOd.mjs";import{selectShapeMembers as ni,selectShapeRows as oi}from"./selectShapeMembers-CLK9q18N.mjs";import{serializeSqlValue as re}from"./serializeSqlValue-DbI1VQYM.mjs";const Gn=o=>{const r=atob(o),t=Uint8Array.from(r,a=>a.codePointAt(0)??0);return new TextDecoder().decode(t)},Hn=()=>new $("BAD_REQUEST","invalid cursor"),xt=16,bt=8,V=1024,st=(o,r)=>r.query(o),Nn=(o,r)=>{if(o.length===0)return 0;let t=0;for(const[a,d]of r.entries()){const p=a===r.length-1;let E=0;for(const S of o)(p?S.startsWith(d):S===d)&&(E+=1);if(E===0)return 0;t+=E}return t},On=(o,r)=>{if(!r)return{exact:!0,lower:o,upper:o};const t=[...o].at(-1)??"",a=(t.codePointAt(0)??0)+1;if(a>=55296&&a<=57343||a>1114111)return{exact:!0,lower:o,upper:o};const d=o.slice(0,o.length-t.length);return{exact:!1,lower:o,upper:d+String.fromCodePoint(a)}},jn=(o,r,t)=>{const a={eq:(d,p)=>{if(!o.definition.filterFields?.includes(d))throw new $("INTERNAL",`field "${d}" is not a filter field of search index "${o.indexName}" on table "${r}"`);if(o.filters.length>=bt)throw new $("BAD_REQUEST",`search index "${o.indexName}" on table "${r}": at most ${String(bt)} .eq() filters are supported per search query`);return o.filters.push({field:d,value:p}),a},search:(d,p)=>{const E=o;if(d!==E.definition.field)throw new $("INTERNAL",`search index "${E.indexName}" on table "${r}" indexes "${E.definition.field}", not "${d}"`);const S=st(p,t).length;if(S>xt)throw new $("BAD_REQUEST",`search index "${E.indexName}" on table "${r}": at most ${String(xt)} search terms are supported (got ${String(S)})`);return E.field=d,E.query=p,E.hasQuery=!0,a}};return a},Kn=o=>{if(o.length>V)throw new $("BAD_REQUEST",`more than ${String(V)} documents match this search — narrow it with filters or read it a page at a time with .paginate()`)},Qn=o=>Math.min(o.offset+o.numItems+1,V),zn=o=>btoa(`search:${String(o)}`),Jn=o=>{let r;try{r=Gn(o)}catch{return}if(!r.startsWith("search:"))return;const t=Number(r.slice(7));return Number.isInteger(t)&&t>=0?t:void 0},Vn=o=>{if(typeof o.endCursor=="string")throw new $("BAD_REQUEST","bounded (endCursor) pagination is not supported on search queries — relevance order has no stable range boundary");if(!Number.isFinite(o.numItems))throw new $("BAD_REQUEST",`search pagination needs a finite numItems, got ${String(o.numItems)}`);const r=Math.max(0,Math.floor(o.numItems)),t=o.cursor?Jn(o.cursor):0;if(t===void 0)throw Hn();if(t+r>=V)throw new $("BAD_REQUEST",`search pagination reaches the ${String(V)}-document limit (offset ${String(t)} + ${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,V-t-1))} or fewer, or narrow the query or the filters instead`);return{numItems:r,offset:t}},Yn=(o,r)=>{const t=r.offset+r.numItems,a=r.numItems>0&&o.length>t;return{continueCursor:a?zn(t):null,isDone:!a,page:o.slice(r.offset,t)}},Xn=o=>{if(o===void 0)return V+1;if(!Number.isFinite(o))return V;const r=Math.max(0,Math.floor(o));if(r>V)throw new $("BAD_REQUEST",`search returns at most ${String(V)} documents (asked for ${String(r)}) — narrow the query or paginate instead`);return r},Pe=o=>{const r=new Map;return t=>{const a=r.get(t);if(a!==void 0)return a;const d=o(Se(t));return r.set(t,d),d}},ue=Se(ne),Zn=Pe(o=>`INSERT INTO ${o} (id, _creationTime, ${ue}) VALUES (?, ?, ?)`),Mt=Pe(o=>`UPDATE ${o} SET ${ue} = ? WHERE id = ? AND ${ue} = ?`),eo=Pe(o=>`UPDATE ${o} SET _creationTime = ?, ${ue} = ? WHERE id = ? AND ${ue} = ?`),to=Pe(o=>`DELETE FROM ${o} WHERE id = ? AND ${ue} = ?`),no="SELECT changes() AS changed",Dt=new Map,oo="",ro=o=>{const r=JSON.stringify(o),t=Dt.get(r);if(t!==void 0)return t;const a=o.map(p=>i`SELECT ${i.raw(`'${p.replaceAll("'","''")}'`)} AS __t__, id, _creationTime, ${i.identifier(ne)} FROM ${i.identifier(p)} WHERE id = ${oo}`),{sql:d}=Nt("sqlite",i`${it(a)} LIMIT 1`);return Dt.set(r,d),d},io=(o,r)=>r.map(()=>o),so=/^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/iu,co=o=>{if(!so.test(o))throw new $("INTERNAL",`invalid clientId ${JSON.stringify(o)}: a client-supplied row id must be a UUID`)},kt=50,Qt=500,Fe=Math.floor(Ot.boundParams/3),ge=Ot.boundParams,ao=128,ae=(o,r,t)=>{const a=r??Qt;if(o>a)throw new $("BATCH_LIMIT_EXCEEDED",`${t}: batch of ${String(o)} exceeds the limit of ${String(a)} (raise options.limit or chunk the call)`,{status:400})},lo=o=>{const r={eq:(t,a)=>(o.sqlConditions.push({comparator:"=",field:t,value:a}),r),gt:(t,a)=>(o.sqlConditions.push({comparator:">",field:t,value:a}),r),gte:(t,a)=>(o.sqlConditions.push({comparator:">=",field:t,value:a}),r),lt:(t,a)=>(o.sqlConditions.push({comparator:"<",field:t,value:a}),r),lte:(t,a)=>(o.sqlConditions.push({comparator:"<=",field:t,value:a}),r)};return r},uo=o=>Math.max(o,V),zt=(o,r)=>{const t=o.filters.map(a=>i`${X(a.field)} = ${re(a.value)}`);return r&&t.push(r),t},fo=(o,r,t,a,d)=>{const p=st(t.query,rt(t.definition.language));if(p.length===0)return[];const E=cn(r,t.indexName),S=`${E}__vocab`,T=p.length-1,L=p.map((F,x)=>{const q=On(F,x===T),z=q.exact?i`${i.identifier("term")} = ${q.lower}`:i`${i.identifier("term")} >= ${q.lower} AND ${i.identifier("term")} < ${q.upper}`;return i`SELECT ${i.identifier("doc")}, ${i.raw(String(x))} AS ${i.identifier("__term__")}, COUNT(*) AS ${i.identifier("__n__")} FROM ${i.identifier(S)} WHERE ${z} GROUP BY ${i.identifier("doc")}`}),y=p.map((F,x)=>i`SUM(CASE WHEN u.${i.identifier("__term__")} = ${i.raw(String(x))} THEN u.${i.identifier("__n__")} ELSE 0 END)`),A=i`SELECT f.${i.identifier(Me)} AS ${i.identifier(Me)}, ${i.join(y,i` + `)} AS ${i.identifier("__score__")} FROM (${it(L)}) u JOIN ${i.identifier(E)} f ON f.rowid = u.${i.identifier("doc")} GROUP BY f.${i.identifier(Me)} HAVING ${i.join(y.map(F=>i`${F} > 0`),i` AND `)}`,v=zt(t,d);let _=i`SELECT m.id, m._creationTime, m.${i.identifier(ne)}, s.${i.identifier("__score__")} AS ${i.identifier("__score__")} FROM (${A}) s JOIN ${i.identifier(r)} m ON m.id = s.${i.identifier(Me)}`;v.length>0&&(_=i`${_} WHERE ${i.join(v,i` AND `)}`),_=i`${_} ORDER BY s.${i.identifier("__score__")} DESC, m._creationTime DESC, m.id ASC LIMIT ${i.raw(String(a))}`;const H=[];for(const F of O(o,_)){const x=Ht(F);if(x){const q=F.__score__;H.push({document:x,score:typeof q=="number"?q:Number(q??0)})}}return H},ho=(o,r,t,a,d)=>{const p=rt(t.definition.language),E=st(t.query,p);if(E.length===0)return[];const S=zt(t,d);let T=i`SELECT id, _creationTime, ${i.identifier(ne)} FROM ${i.identifier(r)}`;S.length>0&&(T=i`${T} WHERE ${i.join(S,i` AND `)}`),T=i`${T} ORDER BY _creationTime DESC, id ASC LIMIT ${i.raw(String(uo(a)))}`;const L=O(o,T).toArray(),y=[];for(const A of L){const v=Ht(A);if(!v)continue;const _=Nn(an(v,t.definition),E);_>0&&y.push({creationTime:typeof v._creationTime=="number"?v._creationTime:0,doc:v,id:typeof v._id=="string"?v._id:"",score:_})}return y.sort((A,v)=>v.score-A.score||v.creationTime-A.creationTime||A.id.localeCompare(v.id)),y.slice(0,a).map(A=>({document:A.doc,score:A.score}))},Ze=(o,r,t,a)=>{if(!Number.isFinite(o.lat)||o.lat<-90||o.lat>90||!Number.isFinite(o.lng)||o.lng<-180||o.lng>180)throw new $("BAD_REQUEST",`geo index "${a}" on table "${t}": ${r} must have a finite lat in [-90, 90] and lng in [-180, 180]`)},wo=(o,r)=>{const t=o,a={near:(d,p)=>{if(t.within)throw new $("INTERNAL",`geo index "${t.indexName}" on table "${r}": call .near() or .within(), not both`);if(Ze(d,".near() point",r,t.indexName),!Number.isFinite(p)||p<=0)throw new $("BAD_REQUEST",`geo index "${t.indexName}" on table "${r}": .near() radiusMeters must be a finite number > 0, got ${String(p)}`);return t.near={point:{lat:d.lat,lng:d.lng},radiusMeters:p},a},within:d=>{if(t.near)throw new $("INTERNAL",`geo index "${t.indexName}" on table "${r}": call .near() or .within(), not both`);if(Ze(d.sw,".within() sw corner",r,t.indexName),Ze(d.ne,".within() ne corner",r,t.indexName),d.sw.lat>d.ne.lat)throw new $("BAD_REQUEST",`geo index "${t.indexName}" on table "${r}": .within() corners are transposed (sw.lat > ne.lat)`);if(d.sw.lng>d.ne.lng)throw new $("BAD_REQUEST",`geo index "${t.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 t.within={ne:{lat:d.ne.lat,lng:d.ne.lng},sw:{lat:d.sw.lat,lng:d.sw.lng}},a}};return a},po=(o,r)=>{const t=o[r];if(t===null||typeof t!="object")return;const{lat:a,lng:d}=t;return typeof a=="number"&&typeof d=="number"?{lat:a,lng:d}:void 0},go=(o,r)=>{const t=po(o,r.definition.field);if(!t)return;const a=typeof o._creationTime=="number"?o._creationTime:0;if(r.near){const d=An(r.near.point,t);return d<=r.near.radiusMeters?{creationTime:a,distance:d}:void 0}return In(t,r.within)?{creationTime:a,distance:0}:void 0},$o=(o,r,t,a)=>{if(!t.near&&!t.within)throw new $("INTERNAL",`geo index "${t.indexName}" on table "${r}": call .near(point, radius) or .within(box)`);const d=t.near?Rn(t.near.point,t.near.radiusMeters):vn(t.within),p=_n(r,t.indexName),E=d.map(A=>i`(g.${i.identifier("__geohash__")} >= ${A} AND g.${i.identifier("__geohash__")} < ${`${A}{`})`),S=[i`(${i.join(E,i` OR `)})`];a&&S.push(a);const T=i`SELECT m.id, m._creationTime, m.${i.identifier(ne)} FROM ${i.identifier(p)} g JOIN ${i.identifier(r)} m ON m.id = g.${i.identifier("__id__")} WHERE ${i.join(S,i` AND `)}`,L=O(o,T).toArray(),y=[];for(const A of L){const v=le(A),_=v?go(v,t):void 0;v&&_&&y.push({creationTime:_.creationTime,distance:_.distance,doc:v})}return y.sort((A,v)=>A.distance-v.distance||v.creationTime-A.creationTime),y},Jt=(o,r,t,a)=>{const d=[];for(const p of o)if(r.every(E=>E(a(p)))&&(d.push(p),typeof t=="number"&&d.length>=t))break;return d},yo=(o,r,t,a,d,p=()=>{})=>{const E=t.within!==void 0,S=$o(o,r,t,d).map(T=>({distanceMeters:E?null:T.distance,document:T.doc}));return p(S.length),typeof a=="number"?S.slice(0,Math.max(0,Math.floor(a))):S},Vt=(o,r,t,a,d,p=()=>{})=>{const{geo:E}=t;if(!E)throw new $("INTERNAL","runGeoTerminalScored called without a staged geo query");const S=t.inMemoryFilters.length>0,T=yo(o,r,E,S?void 0:d,a,p);return S?Jt(T,t.inMemoryFilters,d,L=>L.document):T},Yt=(o,r,t,a)=>{const d=`SELECT id, _creationTime, ${Se(ne)} FROM ${Se(o)}`,p=`ORDER BY ${t}${a===void 0?"":` LIMIT ${String(a)}`}`;return r===void 0?Be(`${d} ${p}`):Ee(`${d} WHERE `,r,` ${p}`)},Eo=(o,r,t,a,d,p=()=>{})=>Vt(o,r,t,a,d,p).map(E=>E.document),mo=(o,r,t,a,d,p,E=()=>{})=>{const S=[];for(const A of t.sqlConditions)S.push(i`${X(A.field)} ${i.raw(A.comparator)} ${re(A.value)}`);a&&S.push(a);let T=i`SELECT id, _creationTime, ${i.identifier(ne)} FROM ${i.identifier(r)}`;S.length>0&&(T=i`${T} WHERE ${i.join(S,i` AND `)}`),T=i`${T} ORDER BY ${d}`,typeof p=="number"&&t.inMemoryFilters.length===0&&(T=i`${T} LIMIT ${i.raw(String(Math.max(0,Math.floor(p))))}`);const L=O(o,T).toArray();E(L.length);const y=[];for(const A of L){const v=le(A);if(v&&t.inMemoryFilters.every(_=>_(v))&&(y.push(v),typeof p=="number"&&y.length>=p))break}return y},$e={fieldRef:X,serialize:re},Xt=(o,r)=>{const t=r===void 0?void 0:o.shape[r];return t!==void 0&&Bn(t)},Lt=(o,r)=>r.some(t=>Xt(o,t)),Ft=(o,r,t)=>{if(Xt(o,r))throw new $("BAD_REQUEST",`${t}: "${r}" is stored as an order-preserving key, which SQL cannot reduce or group — declare an aggregateIndex covering this (by, field, op) so the maintained companion answers it`)},ct={fieldRef:o=>Be(We(o)),serialize:re},So=o=>{let r=0;const t=[],a={fieldRef:d=>Be(We(d)),relationExists:d=>{const{childWhere:p,negated:E,parentTable:S,relation:T}=d,L=`__rel_${String(r)}`,y=t.at(-1)??S;r+=1,o(T.table,G);const A=T.kind==="one"?T.field:T.references,v=T.kind==="one"?T.references:T.field,_=Be(`${St(L,v)} = ${St(y,A)}`);t.push(L);const H=te(p,a,Ue);t.pop();const F=H===void 0?_:Ee(_," AND ",H),x=Ee("EXISTS (SELECT 1 FROM ",Ct(T.table)," AS ",Ct(L)," WHERE ",F,")");return E?Ee("NOT ",x):x},serialize:re};return a},Zt=o=>{const r=o.map(t=>`${We(t.field)} ${t.direction==="desc"?"DESC":"ASC"}`);return o.some(t=>t.field==="_id"||t.field==="id")||r.push(`${We("id")} ${Kt(o)==="desc"?"DESC":"ASC"}`),r.join(", ")},_o=o=>{const r=o.map(t=>i`${X(t.field)} ${i.raw(t.direction==="desc"?"DESC":"ASC")}`);return o.some(t=>t.field==="_id"||t.field==="id")||r.push(i`${X("id")} ${i.raw(Kt(o)==="desc"?"DESC":"ASC")}`),i.join(r,i`, `)},To={"<":"lt","<=":"lte","=":"eq",">":"gt",">=":"gte"},Ro=o=>{const r=new Set(o.sqlConditions.filter(a=>a.comparator==="=").map(a=>a.field));let t=0;for(;t<o.indexFields.length&&r.has(o.indexFields[t]??"");)t+=1;return o.indexFields.slice(t)},en=(o,r)=>{const t=o.order,a=Ro(o);return a.length>0?et(a.map(d=>({[d]:t})),r):et([{_creationTime:t}],r)},vo=(o,r,t,a)=>{const d=o.sqlConditions.map(p=>({[p.field]:{[To[p.comparator]??"eq"]:p.value}}));if(t&&d.push(jt(r,tt(t))),a&&d.push(xn(r,tt(a))),d.length!==0)return d.length===1?d[0]:{AND:d}},Ao=(o,r,t)=>{const a=[];for(const d of o){const p=le(d);if(p&&r.every(E=>E(p))&&(a.push(p),t!==void 0&&a.length>t))break}return a},Io=(o,r,t,a,d,p,E=()=>{})=>{const S=Math.max(0,Math.floor(d.numItems)),T=en(a,t),L=typeof d.endCursor=="string",y=te(vo(a,T,d.cursor,d.endCursor),ct,Ue),A=p&&y?Ee(y," AND ",p):p??y,v=a.inMemoryFilters.length>0,_=Yt(r,A,Zt(T),v||L?void 0:S+1),H=me(o,_.text,..._.params).toArray();E(H.length);const F=Ao(H,a.inMemoryFilters,v||L?void 0:S);if(L){const N=F.length>=2?F[Math.floor(F.length/2)-1]:void 0;return{continueCursor:d.endCursor??null,isDone:!0,page:F,splitCursor:N?nt(N,T):null}}const x=F.length>S,q=x?F.slice(0,S):F,z=q.at(-1);return{continueCursor:x&&z?nt(z,T):null,isDone:!x,page:q}};class Co extends ${constructor(r="unique() found more than one matching document"){super("NOT_UNIQUE",r,{name:"NotUniqueError"})}}const xo=/\s/u,bo=String.fromCodePoint(0),qt=(o,r,t)=>{if(!o.tables[r])throw new $("INTERNAL",`unknown table: ${r}`);return typeof t!="string"||t.length===0||xo.test(t)||t.includes(bo)?null:t},Mo=(o,r,t,a=()=>{},d=()=>{},p=()=>{})=>{const E=r.tables[t];if(!E)throw new $("INTERNAL",`unknown table: ${t}`);const S=de(E.softDeleteMode,void 0),T=S?te(S,$e):void 0,L=S?te(S,ct,Ue):void 0,y={indexFields:[],indexName:void 0,inMemoryFilters:[],order:"asc",sqlConditions:[]};let A=0;const v=m=>{const{search:b}=y;if(!b)throw new $("INTERNAL","runSearchFetch called without a staged search");pn(o,t,E);const C=y.inMemoryFilters.length>0,k=Xn(C?void 0:m),Y=Sn(o);if(Y&&!gn(o,t,b.definition))throw new $("SEARCH_INDEX_BUILDING",`search index "${b.indexName}" on table "${t}" 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 oe=Y?fo(o,t,b,k,T):ho(o,t,b,k,T);return C?(A=oe.length,Jt(oe,y.inMemoryFilters,m,Ge=>Ge.document)):(m===void 0&&Kn(oe),oe)},_=m=>v(m).map(b=>b.document),H=m=>{const b=Vn(m);return Yn(_(Qn(b)),b)},F=()=>_o(en(y,E.shape)),x=()=>{if(y.search||y.geo||y.indexName===void 0){d(void 0);return}d(Ln(t,y.indexName,y.indexFields,y.sqlConditions,re))},q=m=>{x();let b=0;const C=(()=>{if(y.search){const k=_(m);return b=A,k}return y.geo?Eo(o,t,y,T,m,k=>{b=k}):mo(o,t,y,T,F(),m,k=>{b=k})})();return p(Math.max(b,C.length)),C},z=()=>{if(!y.search&&!y.geo)throw new $("INTERNAL",`ctx.db.query("${t}").collectWithScores() requires a staged .withSearchIndex(...) or .withGeoIndex(...)`);x();let m=0;const b=(()=>{if(y.search){const C=v(void 0);return m=A,C}return Vt(o,t,y,T,void 0,C=>{m=C})})();return p(Math.max(m,b.length)),b},N={async*[Symbol.asyncIterator](){if(y.search){yield*q(void 0);return}const m=[...y.inMemoryFilters];let b;y.inMemoryFilters=[];try{for(;;){const C=await N.paginate({cursor:b??null,numItems:ao});for(const k of C.page)m.every(Y=>Y(k))&&(yield k);if(C.isDone||C.continueCursor===null)return;b=C.continueCursor}}finally{y.inMemoryFilters=m}},async collect(){return q(void 0)},async collectWithScores(){return z()},filter(m){return y.inMemoryFilters.push(m),N},async first(){return q(y.inMemoryFilters.length>0?void 0:1)[0]??null},order(m){return y.order=m==="desc"?"desc":"asc",N},async paginate(m){let b=0;if(x(),y.search){const k=H(m);return p(k.page.length),k}if(y.geo)throw new $("INTERNAL","pagination is not supported on geo queries; use .take(n) or .collect()");const C=Io(o,t,E.shape,y,m,L,k=>{b=k});return p(Math.max(b,C.page.length)),C},async take(m){return q(m)},async unique(){const m=q(y.inMemoryFilters.length>0?void 0:2);if(m.length>1)throw new Co(`unique() on table "${t}" matched ${String(m.length)} documents; expected at most one`);return m[0]??null},withGeoIndex(m,b){const C=(E.geoIndexes??[]).find(Y=>Y.name===m);if(!C)throw new $("INTERNAL",`unknown geo index "${m}" on table "${t}"`);a(t,m,"geo");const k={definition:C,indexName:m};if(y.geo=k,b(wo(k,t)),!k.near&&!k.within)throw new $("INTERNAL",`geo index "${m}" on table "${t}" requires a .near(point, radius) or .within(box) call`);return N},withIndex(m,b){const C=E.indexes.find(k=>k.name===m);if(!C)throw new $("INTERNAL",`unknown index "${m}" on table "${t}"`);return a(t,m,"index"),y.indexName=m,y.indexFields=C.fields,b&&b(lo(y)),N},withSearchIndex(m,b){const C=(E.searchIndexes??[]).find(Y=>Y.name===m);if(!C)throw new $("INTERNAL",`unknown search index "${m}" on table "${t}"`);a(t,m,"search");const k={definition:C,field:C.field,filters:[],hasQuery:!1,indexName:m,query:""};if(y.search=k,b(jn(k,t,rt(C.language))),!k.hasQuery)throw new $("INTERNAL",`search index "${m}" on table "${t}" requires a .search(field, query) call`);return N}};return N},Wt=(o,r,t)=>{const a={...r};for(const[d,p]of Gt(o)){if(p.serverDefault){a[d]=p.serverDefault({auth:t});continue}a[d]===void 0&&(p.defaultFn?a[d]=p.defaultFn():"defaultValue"in p&&(a[d]=p.defaultValue))}return a},Bt=(o,r,t,a)=>{const d=t;for(const[p,E]of Gt(o)){if(E.serverDefault){p in r&&(d[p]=E.serverDefault({auth:a}));continue}E.onUpdateFn&&!(p in r)&&(d[p]=E.onUpdateFn())}},Ut=(o,r)=>{for(const t of Object.keys(r))if(r[t]===void 0)throw new $("INTERNAL",`Cannot ${o} field '${t}' to undefined — use null to clear a nullable field, or omit the key to leave it unchanged.`)},Do=/unique constraint failed/i,ko=o=>o instanceof Error&&Do.test(o.message),ot=(o,r,t,a)=>{try{me(o,t,...a)}catch(d){throw ko(d)?new ye(`unique constraint violation on "${r}"`,"unique"):d}},qe=(o,r,t,a)=>{if(ot(o,r,t,a),me(o,no).one().changed===0)throw new ye(`optimistic concurrency conflict on "${r}" — the row changed during this mutation; refetch and retry`,"occ")},Pt=(o,r,t,a,d,p,E)=>{const S=[];for(let A=0;A<t.length+1;A+=1){const v=[];for(let x=0;x<A;x+=1)v.push(i`${i.identifier(t[x])} IS ${p[x]}`);const _=t[A],H=a[A];if(_!==void 0&&H!==void 0){const x=H.direction==="desc"?">":"<";v.push(i`${i.identifier(_)} ${i.raw(x)} ${p[A]}`)}else v.push(i`${i.identifier(Dn)} < ${E}`);const[F]=v;S.push(v.length===1&&F!==void 0?F:i`(${i.join(v,i` AND `)})`)}const T=i.join(S,i` OR `),L=O(o,i`SELECT COUNT(*) AS c FROM ${i.identifier(r)} WHERE ${i.identifier("__partition__")} = ${d} AND (${T})`).one(),y=O(o,i`SELECT COUNT(*) AS c FROM ${i.identifier(r)} WHERE ${i.identifier("__partition__")} = ${d}`).one();return{before:L.c,total:y.c}},ur=o=>{const{sql:r}=o,{schema:t}=o,a=o.broadcast??(()=>{});let d;const p=()=>o.inTransaction?.()===!0,E=e=>t.tables[e]?.commitOrderedMode!==!0?{}:((d===void 0||!p())&&(d=yn(r)),{[En]:d}),S=(e,...n)=>{const s=t.tables[e]?.indexes;if(!s||s.length===0)return;const f=[];for(const h of n)h&&f.push(...kn(s,h,re));return f.length>0?f:void 0},{headroom:T}=o;let L=!1;const y=async e=>{const n=L;L=!0;try{return await e()}finally{L=n}},A=o.onRead??(()=>{}),v=o.onReadRange??(e=>{A(e.table,G)}),_=(e,n)=>{n!==void 0&&n!==G&&!L&&T?.recordRead(1),A(e,n)},H=o.onIndexUse??(()=>{}),F=o.onWrite??(()=>{}),x=e=>{L||T?.recordWrite(e)},q=async e=>{x(e.doc),await F(e)},{cache:z}=o,N=o.clock??(()=>Date.now()),m=o.idGenerator??(()=>crypto.randomUUID()),b=o.scheduler??ln,{globalDb:C}=o,k=o.auth??{identity:null,userId:null},Y=o.cdc??!1,oe=b,Ge=Un({scheduler:typeof oe.list=="function"&&typeof oe.get=="function"?oe:void 0,storage:o.storage}),fe=(e,n,s,f)=>{Y&&!mn(t.tables[e])&&$n(r,N(),e,n,s,f)},se=e=>t.tables[e]?.shardMode?.kind==="global",at=(e,n)=>{if(se(e)){if(!C)throw new $("INTERNAL",`cross-backend ${n} for global table '${e}' requires a globalDb writer — pass one to createShardCtxDb({ globalDb })`);return C}return B},He=e=>at(e,"cascade"),K=(e,n)=>{if(se(e)){if(!C)throw new $("INTERNAL",`${n} on global table '${e}' requires a globalDb writer — pass one to createShardCtxDb({ globalDb })`);return C}},dt=async(e,n,s,f,h)=>{h&&x(s);const u=await e.insert(n,s,f);return a({key:u,op:"insert",row:{...s,_id:u},table:n}),u},Ne=(e,n)=>at(e,"relation load").findMany(e,n),lt=(e,n)=>(se(e)&&_(e,G),Ne(e,n)),tn=e=>!se(e.table),ut=o.relationExistsPushDown??"auto",ft=ut!=="never",{maxRelationKeys:ht}=o,_e=(e,n,s)=>vt(e,{fetcher:lt,maxRelationKeys:ht,relationBaseWhere:s,schema:t,tableName:n}),wt=async(e,n,s,f)=>{const h=K(e,"relation grouped count");if(h)return _(e,G),qn((W,I)=>h.count(W,I),e,n,s,f);const u=t.tables[e];if(!u)throw new $("INTERNAL",`unknown table: ${e}`);_(e,G);const c=de(u.softDeleteMode,void 0),l={[n]:{in:s}},w=Q(Q(l,f),c),R=await _e(w,e,void 0),g=te(R,$e),D=X(n);let M=i`SELECT ${D} AS __fk__, COUNT(*) AS count FROM ${i.identifier(e)}`;g&&(M=i`${M} WHERE ${g}`),M=i`${M} GROUP BY ${D}`;const U=O(r,M).toArray();return new Map(U.map(W=>[W.__fk__,W.count]))};let Te=0;const pt=new Set;for(const[e,n]of Object.entries(t.tables))for(const s of Object.values(n.triggerMap??{}))pt.add(`${e} ${s.timing} ${s.op}`);const Z=(e,n,s)=>pt.has(`${e} ${n} ${s}`),ee=async(e,n,s)=>{if(Te+=1,Te>kt)throw Te-=1,new ye(`trigger recursion exceeded ${String(kt)} levels on "${s.table}" — check for a self-triggering write`,"trigger");try{await Pn({ctx:on,event:s,op:n,schema:t,tableName:s.table,timing:e})}finally{Te-=1}},{ensureBackfilledForTable:he,ensureBackfilledIndex:Oe,ensureRankBackfilled:je,ensureRankBackfilledForTable:we,syncAggregates:Re,syncCompanionsForInsert:gt,syncGeo:ve,syncRanks:pe,syncSearch:Ae}=sn({broadcast:a,indexKeysFor:(e,n)=>S(e,n),invalidateCache:(e,n,s)=>z?.invalidate(e,n,S(e,s)),recordCdc:fe,schema:t,sql:r}),$t=(e,n,s)=>{const{shardMode:f}=n;if(f?.kind==="shardBy"&&!(f.field!==void 0&&(s.partitionBy??[]).includes(f.field)))throw Object.assign(new Error(`rank index "${s.name}" on "${e}" partitions across shards (shard key "${f.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})},yt=e=>Object.entries(t.tables).filter(([,n])=>n.shardMode?.kind!=="global").map(([n])=>n).filter(n=>e===void 0||n===e),ie=(e,n)=>{const s=yt(n);for(let f=0;f<s.length;f+=ge){const h=s.slice(f,f+ge),[u]=me(r,ro(h),...io(e,h)).toArray();if(!u)continue;const c=u.__t__,l=le(u);if(typeof c!="string"||!l)return;const w=u[ne];return{docJson:typeof w=="string"?w:ce(w??{}),row:l,tableName:c}}},nn=(e,n)=>{const s=[...new Set(e)],f=new Map;if(s.length===0)return f;const h=yt(n);for(let u=0;u<h.length;u+=ge){const c=h.slice(u,u+ge),l=Math.floor(ge/c.length),w=Tn(i`${i.identifier("id")}`,s,!1,l),R=c.map(g=>i`SELECT ${i.raw(`'${g.replaceAll("'","''")}'`)} AS __t__, id FROM ${i.identifier(g)} WHERE ${w}`);for(const g of O(r,it(R))){const{id:D,__t__:M}=g;typeof M=="string"&&typeof D=="string"&&f.set(D,M)}}return f},Et={assertRankPartitionLocal:$t,ensureRankBackfilled:je,onRead:_,rowToDocument:le,schema:t,sql:r},B={system:Ge,async aggregate(e,n){const s=K(e,"aggregate");if(s)return _(e,G),s.aggregate(e,n);const f=t.tables[e];if(!f)throw new $("INTERNAL",`unknown table: ${e}`);if(De(n.op),n.op==="count")return B.count(e,{baseWhere:n.baseWhere,relationBaseWhere:n.relationBaseWhere,restrictsCounts:n.restrictsCounts,where:n.where});if(!n.field)throw new $("INTERNAL",`aggregate(${e}, { op: "${n.op}" }): "field" is required for non-count reducers`);_(e,G);const h=de(f.softDeleteMode,void 0),u=Q(Q(n.baseWhere,n.where),h),c=await _e(u,e,n.relationBaseWhere),l=c!==u;if(f.aggregateIndexes&&!n.baseWhere&&!l&&(!h||Lt(f,[n.field]))){const W=wn(f.aggregateIndexes,n.op,n.field,n.where);if(W){Oe(e,W.index);const I=Qe(W.index.by??[],W.key),j=Ke(e,W.index.name),J=O(r,i`SELECT ${ke} AS value, ${Ve} AS count FROM ${i.identifier(j)} WHERE ${Le} = ${I}`).toArray()[0];return ze(n.op,J)}}Ft(f,n.field,`aggregate(${e}, { op: "${n.op}", field: "${n.field}" })`);const w=te(c,$e),R=De(n.op),g=X(n.field);let D=i`SELECT ${i.raw(R)}(${g}) AS value FROM ${i.identifier(e)}`;w&&(D=i`${D} WHERE ${w}`);const U=O(r,D).toArray()[0]?.value;return U??null},asId(e,n){const s=qt(t,e,n);if(s===null)throw new $("BAD_REQUEST",`asId("${e}", …): "${n}" is not a valid id for table "${e}"`,{status:400});return s},async count(e,n){const s=K(e,"count");if(s)return _(e,G),s.count(e,n);const f=t.tables[e];if(!f)throw new $("INTERNAL",`unknown table: ${e}`);const h=un(n);if(h.restrictsCounts)throw new Je(e);_(e,G);const u=de(f.softDeleteMode,void 0),c=Q(Q(h.baseWhere,h.where),u),l=await _e(c,e,h.relationBaseWhere),w=l!==c;if(f.aggregateIndexes&&!h.baseWhere&&!w&&!u){const M=hn(f.aggregateIndexes,h.where);if(M){Oe(e,M.index);const U=Qe(M.index.by??[],M.key),W=Ke(e,M.index.name),I=O(r,i`SELECT ${ke} AS value FROM ${i.identifier(W)} WHERE ${Le} = ${U}`).toArray();return I[0]===void 0?0:I[0].value??0}}const R=te(l,$e);let g=i`SELECT COUNT(*) AS count FROM ${i.identifier(e)}`;return R&&(g=i`${g} WHERE ${R}`),O(r,g).one().count},async delete(e,n,s){const f=ie(e,n);if(!f){const g=n===void 0?C:void 0;g&&(x(void 0),await g.delete(e,void 0,s));return}const{docJson:h,row:u,tableName:c}=f,l=t.tables[c],w=s?.hard===!0,R=!w&&l?.softDeleteMode?l.softDeleteMode.field:void 0;if(!(R&&u[R]!==null&&u[R]!==void 0)){if(Z(c,"before","delete")&&await ee("before","delete",{id:e,op:"delete",previous:u,table:c}),await Fn({deletedId:e,deletedReference:g=>u[g],findHolders:async(g,D,M)=>(await He(g).findMany(g,{includeDeleted:w,where:{[D]:M}})).page,onCascade:(g,D)=>He(g).delete(D,void 0,s),onRestrict:g=>{throw new ye(g,"restrict")},onSetNull:(g,D,M)=>He(g).patch(D,{[M]:null}),schema:t,tableName:c}),he(c),we(c),R){const g={...u,...E(c),[R]:N(),_id:e};qe(r,c,Mt(c),[ce(g),e,h]),Ae(c,e,g,u),ve(c,e,void 0),Re(c,u,g),pe(c,e,u,void 0),z?.invalidate(c,e,S(c,u,g)),fe(c,e,"update",g),a({indexKeys:S(c,u,g),key:e,op:"update",row:g,table:c}),Z(c,"after","delete")&&await ee("after","delete",{id:e,op:"delete",previous:u,table:c}),await q({id:e,op:"delete",table:c});return}qe(r,c,to(c),[e,h]),Ae(c,e,void 0),ve(c,e,void 0),Re(c,u,void 0),pe(c,e,u,void 0),z?.invalidate(c,e,S(c,u)),fe(c,e,"delete"),a({indexKeys:S(c,u),key:e,op:"delete",table:c}),Z(c,"after","delete")&&await ee("after","delete",{id:e,op:"delete",previous:u,table:c}),await q({id:e,op:"delete",table:c})}},async deleteAll(e,n){if(!t.tables[e])throw new $("INTERNAL",`unknown table: ${e}`);const s=Math.max(1,n?.chunkSize??Qt),f=n?.hard===void 0?void 0:{hard:n.hard},h=se(e)?void 0:e;let u=0;return await y(async()=>{for(;;){const l=(await B.findMany(e,{limit:s})).page.map(w=>String(w._id));if(l.length===0)break;for(const w of l)await B.delete(w,h,f),u+=1;if(l.length<s)break}}),{deleted:u}},async deleteMany(e,n,s){ae(e.length,n?.limit,"deleteMany");for(const f of e)await B.delete(f,s);return{deleted:e.length}},async deleteWhere(e,n,s){const u=(await(K(e,"deleteWhere")??B).findMany(e,{where:n})).page.map(c=>String(c._id));if(ae(u.length,s?.limit,"deleteWhere"),B.deleteMany===void 0)throw new $("INTERNAL",`ctx.db.${e}.deleteMany is unavailable: this writer has no batch delete`);return B.deleteMany(u,s)},async findFirst(e,n={}){return(await B.findMany(e,{...n,limit:1,omitContinueCursor:!0})).page[0]??null},async findFirstOrThrow(e,n={}){const s=await B.findFirst(e,n);if(s===null)throw new Cn(`findFirstOrThrow: no "${e}" document matched`);return s},async findMany(e,n={}){const s=K(e,"findMany");if(s)return _(e,G),s.findMany(e,n);const f=t.tables[e];if(!f)throw new $("INTERNAL",`unknown table: ${e}`);const h=!n.where&&!n.baseWhere;h?_(e,G):_(e);const u=et(n.orderBy,f.shape),c=n.cursor?jt(u,tt(n.cursor)):void 0;let l=Q(n.baseWhere,n.where);l=Q(l,de(f.softDeleteMode,n.includeDeleted)),l=await vt(l,{canPushExists:ft?tn:void 0,existsPushMode:ut==="always"?"always":"auto",fetcher:lt,maxRelationKeys:ht,relationBaseWhere:n.relationBaseWhere,schema:t,tableName:e}),c&&(l=l?{AND:[l,c]}:c);const w=ft?So(_):ct,R=te(l,w,Ue),g=typeof n.limit=="number"?Math.max(0,Math.floor(n.limit)):void 0,D=Yt(e,R,Zt(u),g===void 0?void 0:g+1),M=me(r,D.text,...D.params).toArray();h&&!L&&T?.recordRead(M.length);const U=[];for(const J of M){const P=le(J);P&&(U.push(P),!h&&typeof P._id=="string"&&_(e,P._id))}if(g===void 0)return n.with&&await At({groupedCounter:wt,fetcher:Ne,parents:U,...It(n),schema:t,tableName:e,with:n.with}),{continueCursor:null,isDone:!0,page:_t(U,n.select,n.with)};const W=U.length>g,I=W?U.slice(0,g):U,j=I.at(-1);return n.with&&await At({fetcher:Ne,groupedCounter:wt,parents:I,...It(n),schema:t,tableName:e,with:n.with}),{continueCursor:W&&j&&n.omitContinueCursor!==!0?nt(j,u):null,isDone:!W,page:_t(I,n.select,n.with)}},async get(e,n){const s=ie(e,n);if(!s){const f=n===void 0?C:void 0;return f?f.get(e):null}return _(s.tableName,e),s.row},async lookupById(e,n){const s=ie(e,n);return s?(_(s.tableName,e),{row:s.row,tableName:s.tableName}):null},async groupBy(e,n){const s=K(e,"groupBy");if(s)return _(e,G),s.groupBy(e,n);const f=t.tables[e];if(!f)throw new $("INTERNAL",`unknown table: ${e}`);_(e,G);const h=n.agg??{op:"count"};if(De(h.op),h.op!=="count"&&!h.field)throw new $("INTERNAL",`groupBy(${e}, { agg: { op: "${h.op}" } }): "field" is required for non-count reducers`);const u=de(f.softDeleteMode,void 0),c=Q(Q(n.baseWhere,n.where),u),l=await _e(c,e,n.relationBaseWhere),w=l!==c,R=[...n.by,h.field];if(f.aggregateIndexes&&!n.baseWhere&&!w&&(!u||Lt(f,R))){const I=fn(f.aggregateIndexes,h.op,h.field,n.by,n.where),j=I===void 0?0:Object.keys(I.partial).length,J=I?.index.by?.length??0;if(I&&(j===0||j===J)){Oe(e,I.index);const P=Ke(e,I.index.name),Ie=Object.keys(I.partial),Ce=[];if(Ie.length===(I.index.by??[]).length&&Ie.length>0){const xe=Qe(I.index.by??[],I.partial),be=O(r,i`SELECT ${ke} AS value, ${Ve} AS count FROM ${i.identifier(P)} WHERE ${Le} = ${xe}`).toArray();return be.length>0&&Ce.push({key:{...I.partial},value:ze(h.op,be[0])}),Ce}const rn=O(r,i`SELECT ${Le} AS key, ${ke} AS value, ${Ve} AS count FROM ${i.identifier(P)}`).toArray();for(const xe of rn){const be=dn(JSON.parse(xe.key));Ce.push({key:be,value:ze(h.op,xe)})}return Ce}}for(const I of R){if(I===void 0)continue;const j=I===h.field?`groupBy(${e}, { agg: { op: "${h.op}", field: "${I}" } })`:`groupBy(${e}, { by: [..."${I}"] })`;Ft(f,I,j)}const g=te(l,$e),D=n.by.map(I=>i`${X(I)} AS ${i.identifier(I)}`);if(h.op==="count")D.push(i`COUNT(*) AS value`);else{const{field:I}=h;if(I===void 0)throw new $("INTERNAL",`groupBy(${e}, { agg: { op: "${h.op}" } }): "field" is required for non-count reducers`);D.push(i`${i.raw(De(h.op))}(${X(I)}) AS value`)}let M=i`SELECT ${i.join(D,i`, `)} FROM ${i.identifier(e)}`;g&&(M=i`${M} WHERE ${g}`),M=i`${M} GROUP BY ${i.join(n.by.map(I=>X(I)),i`, `)}`;const U=O(r,M).toArray(),W=[];for(const I of U){const j={};for(const P of n.by)j[P]=I[P]??null;const{value:J}=I;W.push({key:j,value:J==null?null:Number(J)})}return W},async insert(e,n,s){const f=K(e,"insert");if(f)return dt(f,e,n,s,!0);const h=t.tables[e];if(!h)throw new $("INTERNAL",`unknown table: ${e}`);const u=Wt(h,n,k);Xe(h,u);let c;s?.clientId!==void 0?(co(s.clientId),c=s.clientId):s?.allowExplicitId&&typeof u._id=="string"?c=u._id:c=m();const l=s?.allowExplicitId&&typeof u._creationTime=="number"?u._creationTime:N(),w={...u,...E(e),_creationTime:l,_id:c};return Z(e,"before","insert")&&await ee("before","insert",{doc:{...w},id:c,op:"insert",table:e}),he(e),we(e),ot(r,e,Zn(e),[c,l,ce(w)]),gt(e,c,w),Z(e,"after","insert")&&await ee("after","insert",{doc:w,id:c,op:"insert",table:e}),await q({doc:w,id:c,op:"insert",table:e}),c},async insertManyUnsafe(e,n,s){if(ae(n.length,s?.limit,"insertManyUnsafe"),n.length===0)return[];const f=K(e,"insert");if(f){const l=[];for(const w of n)x(w);for(const w of n){const R=await f.insert(e,w,{allowExplicitId:s?.allowExplicitId});a({key:R,op:"insert",row:{...w,_id:R},table:e}),l.push(R)}return l}const h=t.tables[e];if(!h)throw new $("INTERNAL",`unknown table: ${e}`);he(e),we(e);const u=[];for(let l=0;l<n.length;l+=Fe)u.push(E(e));const c=n.map((l,w)=>{const R=Wt(h,l,k),g=s?.allowExplicitId===!0&&typeof R._id=="string"?R._id:m(),D=s?.allowExplicitId===!0&&typeof R._creationTime=="number"?R._creationTime:N(),M={...R,...u[Math.floor(w/Fe)],_creationTime:D,_id:g};return{creationTime:D,document:M,id:g}});for(const l of c)x(l.document);for(let l=0;l<c.length;l+=Fe){const w=i.join(c.slice(l,l+Fe).map(g=>i`(${g.id}, ${g.creationTime}, ${ce(g.document)})`),i`, `),R=Nt("sqlite",i`INSERT INTO ${i.identifier(e)} (id, _creationTime, ${i.identifier(ne)}) VALUES ${w}`);ot(r,e,R.sql,R.params)}for(const{document:l,id:w}of c)gt(e,w,l),await F({doc:l,id:w,op:"insert",table:e});return c.map(l=>l.id)},async insertMany(e,n,s){ae(n.length,s?.limit,"insertMany");const f=s?.skipDuplicates===!0,h=[],u=K(e,"insert");if(u)for(const l of n)x(l);const c=async l=>u?dt(u,e,l,void 0,!1):B.insert(e,l);for(const l of n)try{h.push(await c(l))}catch(w){if(f&&w instanceof ye&&w.kind==="unique")h.push(null);else throw w}return h},normalizeId(e,n){return qt(t,e,n)},async patch(e,n,s){const f=ie(e,s);if(!f){const R=s===void 0?C:void 0;if(R){x(n),await R.patch(e,n);return}throw new $("NOT_FOUND",`document not found: ${e}`)}const{docJson:h,row:u,tableName:c}=f,l=t.tables[c];if(!l)throw new $("INTERNAL",`unknown table: ${c}`);_(c,e),Ut("patch",n);const w={...u,...n,...E(c),_id:e};Bt(l,n,w,k),Xe(l,w,!0),Z(c,"before","update")&&await ee("before","update",{doc:{...w},id:e,op:"update",previous:u,table:c}),he(c),we(c),qe(r,c,Mt(c),[ce(w),e,h]),Ae(c,e,w,u),ve(c,e,w),Re(c,u,w),pe(c,e,u,w),z?.invalidate(c,e,S(c,u,w)),fe(c,e,"update",w),a({indexKeys:S(c,u,w),key:e,op:"update",row:w,table:c}),Z(c,"after","update")&&await ee("after","update",{doc:w,id:e,op:"update",previous:u,table:c}),await q({doc:w,id:e,op:"update",table:c})},async patchMany(e,n,s){ae(e.length,n?.limit,"patchMany");for(const f of e)await B.patch(f.id,f.patch,s);return{patched:e.length}},async patchWhere(e,n,s){const u=(await(K(e,"patchWhere")??B).findMany(e,{where:n.where})).page.map(c=>({id:String(c._id),patch:n.patch}));if(ae(u.length,s?.limit,"patchWhere"),B.patchMany===void 0)throw new $("INTERNAL",`ctx.db.${e}.patchMany is unavailable: this writer has no batch patch`);return await B.patchMany(u,s),{patched:u.length}},query(e){const n=K(e,"query");return n?(_(e,G),n.query(e)):Mo(r,t,e,H,s=>{s?v(s):_(e,G)},s=>{L||T?.recordRead(s)})},async rank(e,n,s){const f=K(e,"rank");if(f)return _(e,G),f.rank(e,n,s);H(e,n,"rank");const h=t.tables[e];if(!h)throw new $("INTERNAL",`unknown table: ${e}`);const u=h.rankIndexes?.find(P=>P.name===n);if(!u)throw new $("INTERNAL",`unknown rankIndex "${n}" on table "${e}"`);if($t(e,h,u),s.restrictsCounts)throw new Je(e);_(e,G),je(e,u);const c=typeof s.row=="string"?s.row:s.row._id;if(!c)return null;const l=Tt(e,u.name),w=u.sortBy.map((P,Ie)=>Rt(Ie)),R=w.map(P=>Se(P)).join(", "),g=O(r,i`SELECT ${i.identifier("__partition__")}, ${i.raw(R)} FROM ${i.identifier(l)} WHERE ${i.identifier("__id__")} = ${c}`).toArray(),[D]=g;if(D===void 0)return null;let M=D.__partition__;const U=Q(s.baseWhere,s.where);Ye(U,t,e,"rank");const W=bn(u,U);if(W){const P=Mn(u.partitionBy??[],W);if(P!==M)return null;M=P}const I=w.map(P=>D[P]),{before:j,total:J}=Pt(r,l,w,u.sortBy,M,I,c);return{position:j+1,total:J}},async rankBefore(e,n,s){if(se(e))throw new $("INTERNAL",`rankBefore is not supported on the global (.global()) table '${e}' — cross-shard rank cursors apply only to sharded tables`);const f=t.tables[e];if(!f)throw new $("INTERNAL",`unknown table: ${e}`);const h=f.rankIndexes?.find(w=>w.name===n);if(!h)throw new $("INTERNAL",`unknown rankIndex "${n}" on table "${e}"`);if(s.restrictsCounts)throw new Je(e);_(e,G),je(e,h);const u=Tt(e,h.name),c=h.sortBy.map((w,R)=>Rt(R)),l=h.sortBy.map((w,R)=>re(s.sortValues[R]??null));return Pt(r,u,c,h.sortBy,s.partitionKey,l,s.rowId)},async rankPage(e,n,s={}){Ye(Q(s.baseWhere,s.where),t,e,"rankPage");const f=K(e,"rankPage");if(f)return _(e,G),f.rankPage(e,n,s);H(e,n,"rank");const{continueCursor:h,hasMore:u,rows:c}=mt(Et,e,n,s);return{continueCursor:h,isDone:!u,page:c.map(l=>l.doc)}},async rankPageRows(e,n,s={}){Ye(Q(s.baseWhere,s.where),t,e,"rankPage"),H(e,n,"rank");const{directions:f,hasMore:h,rows:u}=mt(Et,e,n,s);return{directions:f,hasMore:h,rows:u}},async restore(e,n){const s=ie(e,n);if(!s){const u=n===void 0?C:void 0;if(u?.restore){await u.restore(e);return}throw new $("NOT_FOUND",`document not found: ${e}`)}const f=t.tables[s.tableName]?.softDeleteMode?.field;if(!f)throw new $("INTERNAL",`ctx.db.restore: table "${s.tableName}" is not a .softDelete() table`);const h=s.row[f]!==null&&s.row[f]!==void 0;await B.patch(e,{[f]:null},n),h&&pe(s.tableName,e,void 0,s.row)},async replace(e,n,s,f){const h=ie(e,s);if(!h){const D=s===void 0?C:void 0;if(D){x(n),await D.replace(e,n,void 0,f);return}throw new $("NOT_FOUND",`document not found: ${e}`)}const{docJson:u,row:c,tableName:l}=h,w=t.tables[l];if(!w)throw new $("INTERNAL",`unknown table: ${l}`);Ut("replace",n);const R=f?.allowExplicitId&&typeof n._creationTime=="number"?n._creationTime:N(),g={...n,...E(l),_creationTime:R,_id:e};Bt(w,n,g,k),Xe(w,g),Z(l,"before","update")&&await ee("before","update",{doc:{...g},id:e,op:"update",previous:c,table:l}),he(l),we(l),qe(r,l,eo(l),[R,ce(g),e,u]),Ae(l,e,g,c),ve(l,e,g),Re(l,c,g),pe(l,e,c,g),z?.invalidate(l,e,S(l,c,g)),fe(l,e,"update",g),a({indexKeys:S(l,c,g),key:e,op:"update",row:g,table:l}),Z(l,"after","update")&&await ee("after","update",{doc:g,id:e,op:"update",previous:c,table:l}),await q({doc:g,id:e,op:"update",table:l})},async wipeShard(e){const n=new Set(e?.exclude),s=e?.tables,f=Object.entries(t.tables).filter(([l,w])=>n.has(l)||s!==void 0&&!s.includes(l)?!1:w.shardMode?.kind!=="global").map(([l])=>l);if(s!==void 0){for(const l of s)if(!t.tables[l])throw new $("INTERNAL",`wipeShard: unknown table: ${l}`)}const h={};let u=0;const{deleteAll:c}=B;if(c===void 0)throw new $("INTERNAL","wipeShard: this writer has no deleteAll");for(const l of f){const w=await c(l,{...e?.chunkSize===void 0?{}:{chunkSize:e.chunkSize},hard:!0});h[l]=w.deleted,u+=w.deleted}return{deleted:u,tables:h}}},on={db:B,scheduler:b};return o.enforceRls===!0?Wn(B,t,(e,n)=>ie(e,n)?.tableName,(e,n)=>nn(e,n)):B};export{yr as CDC_LOG_TABLE,Fr as CLIENT_WATERMARK_TABLE,Pr as GLOBAL_SHAPE_SNAPSHOT_TABLE,Qr as IDEMPOTENCY_TABLE,Co as NotUniqueError,ei as SEARCH_STATE_TABLE,qr as advanceClientWatermark,Er as applyCdcChanges,Ut as assertNoExplicitUndefined,co as assertValidClientId,wr as backfillAggregateIndexes,pr as backfillRankIndexes,gr as backfillSearchIndexes,mr as bumpCdcEpoch,Sr as cdcCanVouchFor,_r as cdcSeqLeavingRows,Tr as cdcTouchesTables,Rr as cdcTrimmedError,vr as compactCdcDocs,ur as createShardCtxDb,Ar as cursorBelowRetainedFloor,Gr as deleteGlobalShapeSnapshot,Hr as deleteGlobalShapeSnapshotsForConnection,Wr as migrateClientWatermark,Nr as migrateGlobalShapeSnapshot,Ir as minCdcReplayableSeq,Cr as minCdcSeq,qt as normalizeIdStructurally,xr as readCdcChangeKeys,br as readCdcChanges,Mr as readCdcCursor,Dr as readCdcEpoch,Br as readClientWatermark,Or as readGlobalShapeSnapshot,zr as readIdempotent,Xr as runShardMigrations,ni as selectShapeMembers,oi as selectShapeRows,kr as trimCdcChanges,Jr as trimIdempotent,jr as writeGlobalShapeSnapshot,Vr as writeIdempotent};
@@ -1 +0,0 @@
1
- import{LunoraError as g}from"@lunora/errors";const p=Symbol.for("lunora.ctxdb.rls-unwrap");class R extends g{table;constructor(a){super("RLS_REQUIRED",`ctx.db access to "${a}" is denied: the schema is marked .rls("required"), so this table is protected. Apply RLS with .use(rls(policies)) in the procedure, or mark the table .public() to opt it out.`,{name:"RlsRequiredError"}),this.table=a}}const S=o=>Object.entries(o.tables).filter(([,a])=>a.shardMode?.kind!=="global").map(([a])=>a),M=(o,a,l)=>{const u=a?.tables,n=new Set(a?.exclude);for(const d of o)(u===void 0||u.includes(d))&&!n.has(d)&&l(d)},m=["aggregate","count","deleteAll","findFirst","findFirstOrThrow","findMany","groupBy","insert","insertMany","insertManyUnsafe","query","rank","rankBefore","rankPage","rankPageRows"],v=(o,a,l,u)=>{if(a.rlsMode!=="required")return o;const n=o,d=r=>{const t=a.tables[r];return t!==void 0&&t.isPublic!==!0},s=r=>{if(d(r))throw new R(r)},c=async(r,t)=>{if(t!==void 0){s(t);return}const e=await l(r);e!==void 0&&s(e)},h=async(r,t)=>{if(t!==void 0){s(t);return}if(!u){for(const i of r)await c(i,t);return}const e=await u([...new Set(r)],t);for(const i of r){const y=e.get(i);y!==void 0&&s(y)}},f={...o,[p]:o,delete:async(r,t,e)=>(await c(r,t),n.delete(r,t,e)),deleteMany:async(r,t,e)=>(await h(r,e),n.deleteMany(r,t,e)),deleteWhere:n.deleteWhere?async(r,t,e)=>(s(r),await n.deleteWhere?.(r,t,e)):void 0,get:async(r,t)=>(await c(r,t),n.get(r,t)),lookupById:async(r,t)=>(await c(r,t),n.lookupById?.(r,t)??null),patch:async(r,t,e)=>(await c(r,e),n.patch(r,t,e)),patchMany:async(r,t,e)=>(await h(r.map(i=>i.id),e),n.patchMany(r,t,e)),patchWhere:n.patchWhere?async(r,t,e)=>(s(r),await n.patchWhere?.(r,t,e)):void 0,replace:async(r,t,e,i)=>(await c(r,e),n.replace(r,t,e,i)),restore:async(r,t)=>(await c(r,t),n.restore?.(r,t))},w=n;for(const r of m){const t=w[r];typeof t=="function"&&(f[r]=(e,...i)=>(s(e),t.call(n,e,...i)))}if(n.wipeShard){const{wipeShard:r}=n;f.wipeShard=t=>(M(S(a),t,s),r.call(n,t))}return f};export{p as RLS_UNWRAP_SYMBOL,R as RlsRequiredError,v as guardWriter};
@@ -1 +0,0 @@
1
- import{S as T,q as b,r as O,i as C,l as h,y as L,d as M}from"./ctx-db-companions-BFBIVIOd.mjs";import{sql as t}from"drizzle-orm";import{matchesStaticWhere as x}from"./AGGREGATE_SQL_FUNCTION-m1iUU1rv.mjs";import{aggregateTableName as _,encodeAggregateKey as y,foldAggregateTally as F}from"./aggregateTableName-CGi8gxeK.mjs";import{migrateSearchState as N,readSearchBackfillState as E,readSearchIndexCoverage as D,writeSearchBackfillState as v}from"./SEARCH_STATE_TABLE-xmYM_nOd.mjs";import{runDrizzle as l}from"./runDrizzle-2ULFQR_k.mjs";import{i as p,r as w,a as B,b as G,A as U,D as I,h as H}from"./do-sql-bkXQEBl8.mjs";import{isLiveForCompanion as P}from"./CURSOR_PREFIX-CoJUQfCI.mjs";import{rankTableName as W,matchesRankStaticWhere as V}from"./RANK_TIEBREAK-D157XEqw.mjs";const R=(e,o)=>e.profile!==o?{cursor:void 0,finished:!1,wipe:e.cursor!==void 0||e.done}:{cursor:e.cursor,finished:e.done,wipe:!1},k=(e,o)=>l(e,t`SELECT COUNT(*) AS count FROM ${t.identifier(o)}`).one().count>0,Y=(e,o)=>l(e,t`SELECT 1 FROM ${t.identifier(o)} LIMIT 1`).toArray().length>0,A=(e,o)=>l(e,t`SELECT id, _creationTime, ${t.identifier(I)} FROM ${t.identifier(o)}`).toArray(),j=(e,o,n,r)=>{const i=_(o,n.name);if(k(e,i))return;const c=n.by??[],a=new Map,s=A(e,o);for(const d of s){const f=w(d);if(!f||!P(f,r)||n.where&&!x(f,n.where))continue;const g=y(c,f);F(a,g,n,f)}for(const[d,f]of a)l(e,t`INSERT INTO ${t.identifier(i)} (${B}, ${G}, ${U}) VALUES (${d}, ${f.value}, ${f.count})`)},te=(e,o)=>{for(const[n,r]of Object.entries(o.tables))if(!(r.shardMode?.kind==="global"||!r.aggregateIndexes))for(const i of r.aggregateIndexes)j(e,n,i,r.softDeleteMode?.field)},K=(e,o,n)=>{const r=W(o,n.name);if(k(e,r))return;const i=O(n),c=A(e,o);for(const a of c){const s=w(a);!s||n.where&&!V(s,n.where)||C(e,r,n,i,s._id,s)}},ie=(e,o)=>{for(const[n,r]of Object.entries(o.tables))if(!(r.shardMode?.kind==="global"||!r.rankIndexes))for(const i of r.rankIndexes)K(e,n,i)},m=500,$=(e,o,n)=>{const r=T(o,n.name),{profile:i}=b(n.language),c=R(E(e,r),i);if(c.finished)return{done:!0,rows:0};const{cursor:a}=c,s=l(e,a===void 0?t`SELECT id, _creationTime, ${t.identifier(I)} FROM ${t.identifier(o)} ORDER BY id ASC LIMIT ${t.raw(String(m))}`:t`SELECT id, _creationTime, ${t.identifier(I)} FROM ${t.identifier(o)} WHERE id > ${a} ORDER BY id ASC LIMIT ${t.raw(String(m))}`).toArray();let d=a;for(const g of s){const{id:u}=g;if(typeof u!="string")continue;d=u,l(e,t`DELETE FROM ${t.identifier(r)} WHERE ${t.identifier(h)} = ${u}`);const S=H(g);S&&l(e,t`INSERT INTO ${t.identifier(r)} (${t.identifier(L)}, ${t.identifier(h)}) VALUES (${M(S,n)}, ${u})`)}const f=s.length<m;return v(e,r,d,f,i),{done:f,rows:s.length}},ae=(e,o,n)=>{const r=T(o,n.name),{profile:i}=b(n.language);return R(E(e,r),i).finished?!0:D(e,r)},se=(e,o,n)=>{if(p(e))for(const r of n.searchIndexes??[])r.staged&&Y(e,o)||$(e,o,r)},z=(e,o,n,r)=>{let i=0;for(;;){if(i>=r)return{done:!1,pages:i};const c=$(e,o,n);if(c.rows>0&&(i+=1),c.done)return{done:!0,pages:i}}},ce=(e,o,n={})=>{if(!p(e))return{done:!0,pages:0};N(e);const r=n.maxPages??Number.POSITIVE_INFINITY;let i=0;for(const[c,a]of Object.entries(o.tables))if(!(a.shardMode?.kind==="global"||!a.searchIndexes))for(const s of a.searchIndexes){const d=z(e,c,s,r-i);if(i+=d.pages,!d.done)return{done:!1,pages:i}}return{done:!0,pages:i}};export{te as backfillAggregateIndexes,ie as backfillRankIndexes,ce as backfillSearchIndexes,se as backfillSearchIndexesForTable,ae as searchIndexCoversTable};
@@ -1 +0,0 @@
1
- import{quoteIdentifier as l}from"./quoteIdentifier-CObIFRhb.mjs";import{reprojectionMigrationTable as u}from"./REPROJECTION_MIGRATION_PREFIX-Czcb6_mO.mjs";import{REPROJECTION_MIGRATION_PREFIX as v,reprojectionMigrationId as w}from"./REPROJECTION_MIGRATION_PREFIX-Czcb6_mO.mjs";import{e as m}from"./wire-codec-COhOSEe4.mjs";import{runSql as p}from"./runDrizzle-2ULFQR_k.mjs";import{k as d,D as E}from"./do-sql-bkXQEBl8.mjs";import{m as g}from"./sql-projection-BqmxFxQU.mjs";const b=m(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=u(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{d(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 +0,0 @@
1
- import{c as l,i as C,r as R}from"./ctx-db-companions-BFBIVIOd.mjs";import"./AGGREGATE_SQL_FUNCTION-m1iUU1rv.mjs";import"./aggregateTableName-CGi8gxeK.mjs";import"./runDrizzle-2ULFQR_k.mjs";import"./do-sql-bkXQEBl8.mjs";import"./param-DlozcSQu.mjs";import"./GEO_DEFAULT_PRECISION-CqpQZ-J_.mjs";import"./CURSOR_PREFIX-CoJUQfCI.mjs";import"./RANK_TIEBREAK-D157XEqw.mjs";import"./sql-projection-BqmxFxQU.mjs";import"./serializeSqlValue-DbI1VQYM.mjs";export{l as createCompanionSync,C as insertRankRow,R as rankColumnsSql};
@@ -1 +0,0 @@
1
- import{sql as e}from"drizzle-orm";import{matchesStaticWhere as P,aggregateSqlFunction as le}from"./AGGREGATE_SQL_FUNCTION-m1iUU1rv.mjs";import{aggregateTableName as N,encodeAggregateKey as I,foldAggregateTally as J,coerceAggregateNumber as C}from"./aggregateTableName-CGi8gxeK.mjs";import{runDrizzle as $}from"./runDrizzle-2ULFQR_k.mjs";import{i as fe,g as ue,D,r as M,a as q,b as S,A as g,c as j,e as z}from"./do-sql-bkXQEBl8.mjs";import{param as de,WORKERD_SQLITE_LIMITS as $e}from"./param-DlozcSQu.mjs";import{encodeGeohash as me,GEO_DEFAULT_PRECISION as Ee}from"./GEO_DEFAULT_PRECISION-CqpQZ-J_.mjs";import{isLiveForCompanion as Q}from"./CURSOR_PREFIX-CoJUQfCI.mjs";import{encodePartitionKey as pe,sortColumnName as he,rankTableName as Z,matchesRankStaticWhere as x}from"./RANK_TIEBREAK-D157XEqw.mjs";import{m as ge}from"./sql-projection-BqmxFxQU.mjs";import{serializeSqlValue as ee}from"./serializeSqlValue-DbI1VQYM.mjs";const ye=["de","en","es","fr","it","nl","none","pt"],_e=n=>ye.includes(n),Se="a an and are as at be but by for if in into is it no not of on or such that the their then there these they this to was will with",we="aber als am an auch auf aus bei bin bis bist da dass der den des dem die das denn dir du ein eine für hat ich im in ist mit nicht noch nur oder sich sie sind über und von vor war wie wir zu zum zur",Te="a al como con de del el en es la las lo los mas no o para pero por que se su sus un una uno y ya",ve="au aux avec ce ces dans de des du elle en et eux il je la le les leur lui ma mais me même mes moi mon ne nos notre nous on ou par pas pour qu que qui sa se ses son sur ta te tes toi ton tu un une vos votre vous y",Re="a ai al alla anche che chi ci coi col come con da dal degli dei del della di do e ed gli ha hai hanno i il in la le lo ma mi ne nei nel non o per più quale quanto se si sono su sul tra un una uno vi",Ae="aan al als bij dan dat de der deze die dit door een en er het hij ij in is je kan me men met mij na naar niet nog nu of om ons ook op over te tot uit van voor was wat we wij zij zijn zo",Fe="a ao aos as até com como da das de do dos e em entre era essa esse esta este eu foi há isso já mais mas me mesmo meu na nas no nos num numa o os ou para pela pelo por qual que quem se sem seu só sua também te tem um uma você",be=/[\u0300-\u036F]/gu,Oe=/[\u0080-\u{10FFFF}]/u,Le=/[\p{L}\p{N}]+/gu,oe=n=>Oe.test(n)?n.normalize("NFD").replaceAll(be,"").normalize("NFC").toLowerCase():n.toLowerCase(),k=n=>new Set(oe(n).split(" ")),Ie={de:k(we),en:k(Se),es:k(Te),fr:k(ve),it:k(Re),nl:k(Ae),none:new Set,pt:k(Fe)},ke=2,qe=256,X=new Map,Ce=n=>{const s=n!==void 0&&_e(n)?n:"none",c=X.get(s);if(c)return c;const w=Ie[s],y=r=>{const A=(oe(r).match(Le)??[]).filter(T=>T.length<=qe);return w.size===0?A:A.filter(T=>!w.has(T))},E={document:y,profile:`${s}-v${String(ke)}`,query:r=>{const A=y(r);return A.filter((T,b)=>A.lastIndexOf(T)===b)}};return X.set(s,E),E},je=(n,s)=>{if(!s.includes("."))return n[s];let c=n;for(const w of s.split(".")){if(c===null||typeof c!="object"||Array.isArray(c))return;c=c[w]}return c},De=(n,s)=>`${n}__fts_${s}`,Me="__text__",Y="__id__",ze=1e3,Ue=(n,s)=>s.document(n),U=(n,s)=>je(n,s),We=n=>typeof n=="string"?n:n==null?"":typeof n=="number"||typeof n=="bigint"||typeof n=="boolean"?String(n):JSON.stringify(n)??"",He=(n,s,c)=>n!==void 0&&s!==void 0&&U(n,c.field)===U(s,c.field),Be=(n,s)=>Ue(We(U(n,s.field)),Ce(s.language)).slice(0,ze),Ke=(n,s)=>Be(n,s).join(" "),Ve=(n,s,c)=>[...n.partitionBy??[],...n.sortBy.map(y=>y.field),...n.where?Object.keys(n.where):[]].every(y=>s[y]===c[y]),ne=n=>e.join(["__id__","__partition__",...n.sortBy.map((s,c)=>he(c))].map(s=>e.identifier(s)),e`, `),te=(n,s,c,w,y,E)=>{const r=pe(c.partitionBy??[],E),A=c.sortBy.map(b=>ee(E[b.field]??null)),T=e.join([y,r,...A].map(b=>de(b)),e`, `);$(n,e`INSERT INTO ${e.identifier(s)} (${w}) VALUES (${T})`)},Ge=(n,s,c,w,y,E)=>{if(y&&E&&Ve(c,y,E))return;const r=Z(s,c.name);y&&$(n,e`DELETE FROM ${e.identifier(r)} WHERE ${e.identifier("__id__")} = ${w}`),!(!E||c.where&&!x(E,c.where))&&te(n,r,c,ne(c),w,E)},so=n=>{const{broadcast:s,indexKeysFor:c,invalidateCache:w,recordCdc:y,schema:E,sql:r}=n,A=new Set,T=t=>E.tables[t]?.softDeleteMode?.field,b=new Set,W=(t,o)=>{const a=`${t}::${o.name}`;if(A.has(a))return;const f=N(t,o.name),u=o.by??[],d=T(t),p=new Map,_=$(r,e`SELECT id, _creationTime, ${e.identifier(D)} FROM ${e.identifier(t)}`).toArray();for(const v of _){const m=M(v);if(!m||!Q(m,d)||o.where&&!P(m,o.where))continue;const R=I(u,m);J(p,R,o,m)}$(r,e`DELETE FROM ${e.identifier(f)}`);const F=Math.floor($e.boundParams/3),O=[...p];for(let v=0;v<O.length;v+=F){const m=O.slice(v,v+F),R=e.join(m.map(([i,l])=>e`(${i}, ${l.value}, ${l.count})`),e`, `);$(r,e`INSERT INTO ${e.identifier(f)} (${q}, ${S}, ${g}) VALUES ${R}`)}A.add(a)},se=(t,o,a)=>{const f=o.by??[],u=o.field??"",d=[],p=(i,l)=>{const h=ee(l);h===null?d.push(e`${z(i)} IS NULL`):d.push(e`${z(i)} = ${h}`)};for(const i of f)p(i,a[i]??null);const _=T(t);_!==void 0&&p(_,null);for(const[i,l]of Object.entries(o.where??{}))p(i,l!==null&&typeof l=="object"&&!Array.isArray(l)?l.eq:l);const F=d.length>0?e` WHERE ${e.join(d,e` AND `)}`:e``,O=E.tables[t]?.shape[u];if(O&&ge(O)){const i=$(r,e`SELECT id, _creationTime, ${e.identifier(D)} FROM ${e.identifier(t)}${F}`).toArray(),l=new Map;for(const h of i){const L=M(h);L&&J(l,"",o,L)}return{value:l.get("")?.value??null}}const v=le(o.op),m=z(u);return{value:$(r,e`SELECT ${e.raw(v)}(${m}) AS value FROM ${e.identifier(t)}${F}`).one().value??null}},ie=(t,o,a,f)=>{const u=N(t,o.name),{op:d}=o,p=o.field??"",_=i=>{$(r,e`DELETE FROM ${e.identifier(u)} WHERE ${q} = ${i} AND ${g} <= 0`)},F=T(t),O=i=>!o.where||P(i,o.where),v=i=>Q(i,F)&&O(i);f!==void 0&&d!=="count"&&O(f)&&C(f[p]);const m=a&&v(a)?a:void 0,R=f&&v(f)?f:void 0;if(!(!m&&!R)){if(d==="count"){for(const[i,l]of[[m,-1],[R,1]]){if(!i)continue;const h=I(o.by??[],i);$(r,j(u,h,l,l,e`${S} = ${S} + excluded.${S}, ${g} = ${g} + excluded.${g}`))}m&&_(I(o.by??[],m));return}if(d==="sum"||d==="avg"){for(const[i,l]of[[m,-1],[R,1]]){if(!i)continue;const h=C(i[p]);if(h===void 0)continue;const L=I(o.by??[],i);$(r,j(u,L,l*h,l,e`${S} = COALESCE(${S}, 0) + excluded.${S}, ${g} = ${g} + excluded.${g}`))}m&&_(I(o.by??[],m));return}if(m){const i=I(o.by??[],m),l=C(m[p]),h=$(r,e`SELECT ${S} AS value, ${g} AS count FROM ${e.identifier(u)} WHERE ${q} = ${i}`).toArray()[0],L=(h?.count??0)-1;if(L<=0)$(r,e`DELETE FROM ${e.identifier(u)} WHERE ${q} = ${i}`);else if(h&&l!==void 0&&h.value!==null&&l===h.value){const ce=se(t,o,m);$(r,e`UPDATE ${e.identifier(u)} SET ${S} = ${ce.value}, ${g} = ${L} WHERE ${q} = ${i}`)}else $(r,e`UPDATE ${e.identifier(u)} SET ${g} = ${g} - 1 WHERE ${q} = ${i}`)}if(R){const i=I(o.by??[],R),l=C(R[p]);if(l===void 0)$(r,j(u,i,null,1,e`${g} = ${g} + 1`));else{const h=d==="min"?"MIN":"MAX";$(r,j(u,i,l,1,e`${S} = ${e.raw(h)}(COALESCE(${S}, excluded.${S}), excluded.${S}), ${g} = ${g} + 1`))}}}},re=t=>{for(const o of E.tables[t]?.aggregateIndexes??[])W(t,o)},H=(t,o,a)=>{for(const f of E.tables[t]?.aggregateIndexes??[])ie(t,f,o,a)},B=(t,o)=>{const a=`${t}::rank::${o.name}`;if(b.has(a))return;const f=Z(t,o.name),u=$(r,e`SELECT id, _creationTime, ${e.identifier(D)} FROM ${e.identifier(t)}`).toArray();$(r,e`DELETE FROM ${e.identifier(f)}`);const d=ne(o);for(const p of u){const _=M(p);!_||o.where&&!x(_,o.where)||te(r,f,o,d,_._id,_)}b.add(a)},ae=t=>{for(const o of E.tables[t]?.rankIndexes??[])B(t,o)},K=(t,o,a,f)=>{for(const u of E.tables[t]?.rankIndexes??[])Ge(r,t,u,o,a,f)},V=(t,o,a,f)=>{const u=E.tables[t]?.searchIndexes??[];if(!(u.length===0||!fe(r)))for(const d of u){if(He(f,a,d))continue;const p=De(t,d.name);$(r,e`DELETE FROM ${e.identifier(p)} WHERE ${e.identifier(Y)} = ${o}`),a&&$(r,e`INSERT INTO ${e.identifier(p)} (${e.identifier(Me)}, ${e.identifier(Y)}) VALUES (${Ke(a,d)}, ${o})`)}},G=(t,o,a)=>{for(const f of E.tables[t]?.geoIndexes??[]){const u=ue(t,f.name);$(r,e`DELETE FROM ${e.identifier(u)} WHERE ${e.identifier("__id__")} = ${o}`);const d=a?.[f.field];if(d!==null&&typeof d=="object"&&typeof d.lat=="number"&&typeof d.lng=="number"){const{lat:p,lng:_}=d,F=me({lat:p,lng:_},f.precision??Ee);$(r,e`INSERT INTO ${e.identifier(u)} (${e.identifier("__id__")}, ${e.identifier("__geohash__")}, ${e.identifier("__lat__")}, ${e.identifier("__lng__")}) VALUES (${o}, ${F}, ${p}, ${_})`)}}};return{ensureBackfilledForTable:re,ensureBackfilledIndex:W,ensureRankBackfilled:B,ensureRankBackfilledForTable:ae,syncAggregates:H,syncCompanionsForInsert:(t,o,a)=>{V(t,o,a),G(t,o,a),H(t,void 0,a),K(t,o,void 0,a),w(t,o,a),y(t,o,"insert",a),s({indexKeys:c(t,a),key:o,op:"insert",row:a,table:t})},syncGeo:G,syncRanks:K,syncSearch:V}};export{De as S,Be as a,so as c,Ke as d,te as i,Y as l,Ce as q,ne as r,Me as y};
@@ -1 +0,0 @@
1
- import{LunoraError as _}from"@lunora/errors";import{sql as o}from"drizzle-orm";import{quoteIdentifier as A}from"./quoteIdentifier-CObIFRhb.mjs";import{d as T,n as $,e as p}from"./wire-codec-COhOSEe4.mjs";import{runDrizzle as l}from"./runDrizzle-2ULFQR_k.mjs";import{s as S}from"./sql-projection-BqmxFxQU.mjs";import"./serializeSqlValue-DbI1VQYM.mjs";const O=/^[A-Za-z_$][\w$]*$/u,b=e=>O.test(e)?e:`"${e.replaceAll("\\",String.raw`\\`).replaceAll('"',String.raw`\"`)}"`,m="__doc__",i="__originals__",R=e=>{if(Object.hasOwn(e,i))throw new _("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 c=S(a);c!==void 0&&(t??={...e},r??=Object.create(null),t[s]=c,r[s]=a)}t&&r&&(t[i]=r);const n=t??e;try{return $(n)?JSON.stringify(p(n)):JSON.stringify(n)}catch(s){throw new _("BAD_REQUEST",`this document cannot be stored: ${s instanceof Error?s.message:String(s)}`)}},h=e=>{const t=T(JSON.parse(e)),r=t[i];if(r===null||typeof r!="object"||Array.isArray(r))return t;const n={...t};return delete n[i],{...n,...r}},G=(e,t)=>`${e}__geo_${t}`,E=(e,t)=>t==="_id"||t==="id"?`${e}id`:t==="_creationTime"?`${e}_creationTime`:`json_extract(${e}${m}, '$.${b(t).replaceAll("'","''")}')`,g=e=>E("",e),J=e=>o.raw(g(e)),N=(e,t)=>E(`${A(e)}.`,t),q=(e,t)=>o.raw(N(e,t)),B=(e,t,r,n)=>o`CREATE ${n?o`UNIQUE `:o``}INDEX IF NOT EXISTS ${o.identifier(e)} ON ${o.identifier(t)} (${r})`,f=o.identifier("__key__"),y=o.identifier("__value__"),I=o.identifier("__count__"),z=(e,t,r,n,s)=>o`INSERT INTO ${o.identifier(e)} (${f}, ${y}, ${I}) VALUES (${t}, ${r}, ${n}) ON CONFLICT(${f}) DO UPDATE SET ${s}`,d=new WeakMap,F=e=>{const t=d.get(e);if(t!==void 0)return t;const r=[];for(const[n,s]of Object.entries(e.shape)){const a=s._meta?.column;a&&r.push(Object.freeze([n,a]))}return Object.freeze(r),d.set(e,r),r},j=e=>{if(!e)return;const t=e[m];let r;typeof t=="string"?r=h(t):t&&typeof t=="object"?r=t:r={};const{id:n}=e;typeof n=="string"&&(r._id=n);const s=e._creationTime;return typeof s=="number"&&(r._creationTime=s),r},W=e=>{try{return j(e)}catch{return}},u=new WeakMap,k=e=>{const t=u.get(e);if(t!==void 0)return t;let r;try{l(e,o`CREATE VIRTUAL TABLE IF NOT EXISTS ${o.identifier("__lunora_fts_probe")} USING fts5(x)`),r=!0}catch{r=!1}finally{try{l(e,o`DROP TABLE IF EXISTS ${o.identifier("__lunora_fts_probe")}`)}catch{}}return u.set(e,r),r};export{I as A,m as D,f as a,y as b,z as c,B as d,J as e,q as f,G as g,W as h,k as i,g as j,R as k,h as l,b as m,i as n,N as q,j as r,F as t};
@@ -1 +0,0 @@
1
- import{B as s}from"./sql-projection-BqmxFxQU.mjs";const n=40,f=i=>{let e=0;const o=(r,t)=>typeof t=="bigint"?(e+=s+1+n,t.toString()):t instanceof ArrayBuffer||ArrayBuffer.isView(t)?(e+=2*Math.ceil(t.byteLength/3)*4+n,""):t;try{const r=JSON.stringify(i,o);return(r===void 0?0:r.length)+e}catch{return}};export{f as e};
@@ -1 +0,0 @@
1
- import{s as o}from"./sql-projection-BqmxFxQU.mjs";const n=r=>typeof r=="boolean"?r?1:0:r===null||typeof r=="string"||typeof r=="number"?r:o(r)??JSON.stringify(r);export{n as serializeSqlValue};
@@ -1 +0,0 @@
1
- import{LunoraError as T}from"@lunora/errors";import{sql as l}from"drizzle-orm";import{sqliteInList as A,isJsonSafe as m,WORKERD_SQLITE_LIMITS as O}from"./param-DlozcSQu.mjs";import{quoteIdentifier as R}from"./quoteIdentifier-CObIFRhb.mjs";import{RELATION_EXISTS_KEY as L}from"./RELATION_EXISTS_KEY-CFUhnZSZ.mjs";const $={binary:(n,t,o)=>l`${n} ${l.raw(t)} ${o}`,constant:n=>n?l`1 = 1`:l`0 = 1`,connect:(n,t,o)=>l`(${n}) ${l.raw(o)} (${t})`,contains:(n,t)=>l`instr(lower(${n}), lower(${t})) > 0`,inList:(n,t,o,i)=>A(n,t,o,i),negate:n=>l`NOT (${n})`,nullCheck:(n,t)=>t?l`${n} IS NOT NULL`:l`${n} IS NULL`,value:n=>l`${n}`},u=(...n)=>{let t="";const o=[];for(const i of n)typeof i=="string"?t+=i:(t+=i.text,o.push(...i.params));return{params:o,text:t}},p=n=>({params:[n],text:"?"}),S=n=>({params:[],text:n}),B=n=>S(R(n)),G={binary:(n,t,o)=>u(n," ".concat(t," "),p(o)),constant:n=>S(n?"1 = 1":"0 = 1"),connect:(n,t,o)=>u("(",n,") ".concat(o," ("),t,")"),contains:(n,t)=>u("instr(lower(",n,"), lower(",t,")) > 0"),inList:(n,t,o,i)=>{const s=o?" NOT IN ":" IN ";if(t.length>i&&!t.every(r=>m(r)))throw new T("BAD_REQUEST",`an "in" list of ${String(t.length)} values holds a value JSON cannot carry (bytes, a non-finite number, or malformed text), so it cannot be bound as one parameter — and ${String(t.length)} placeholders exceed SQLite's per-statement cap of 100 on Durable Objects and D1. Narrow the list to ${String(i)} values or fewer.`);if(t.length<=i){const r=[n,s,"("];for(const[e,c]of t.entries())e>0&&r.push(", "),r.push(p(c));return r.push(")"),u(...r)}return u(n,s,'(SELECT "value" FROM json_each(',p(JSON.stringify(t)),"))")},negate:n=>u("NOT (",n,")"),nullCheck:(n,t)=>u(n,t?" IS NOT NULL":" IS NULL"),value:p},x=O.boundParams/2,I=["eq","ne","lt","lte","gt","gte","in","notIn","isNull","contains"],_=new Set(I),j={eq:"=",gt:">",gte:">=",lt:"<",lte:"<=",ne:"<>"},d=n=>{if(n===null||typeof n!="object"||Array.isArray(n))return!1;const t=Object.keys(n);return t.length>0&&t.every(o=>_.has(o))},w=(n,t,o,i)=>{const s=i.value(o.serialize(t));return o.containsExpr?o.containsExpr(n,s):i.contains(n,s)},C=(n,t,o,i,s,r)=>i===null?t==="eq"||t==="ne"?r.nullCheck(n,t==="ne"):r.constant(!1):r.binary(n,o,s.serialize(i)),y=(n,t,o,i,s)=>{const r=Array.isArray(o)?o:[];if(r.length===0)return s.constant(t==="NOT IN");const e=r.map(a=>i.serialize(a)),c=t==="NOT IN";return i.inList?i.inList(n,e,c):s.inList(n,e,c,x)},J=(n,t,o)=>{const i=l.join(t.map(s=>l`${s}`),l`, `);return o?l`${n} NOT IN (${i})`:l`${n} IN (${i})`},k=(n,t,o,i)=>{const s=t,r=[];for(const e of I){if(!(e in s))continue;const c=s[e],a=j[e];a?r.push(C(n,e,a,c,o,i)):e==="isNull"?r.push(i.nullCheck(n,!c)):e==="contains"?r.push(w(n,c,o,i)):r.push(y(n,e==="in"?"IN":"NOT IN",c,o,i))}return r},D=(n,t,o,i)=>{const s=o.fieldRef(n);return d(t)?k(s,t,o,i):t===null?[i.nullCheck(s,!1)]:[i.binary(s,"=",o.serialize(t))]},f=(n,t,o)=>{if(n.length<=1)return n[0];const i=Math.floor(n.length/2);return o.connect(f(n.slice(0,i),t,o),f(n.slice(i),t,o),t)},U=(n,t,o,i)=>{const s=Array.isArray(n)?n:[],r=[];for(const e of s){const c=h(e??{},o,i);c!==void 0&&r.push(c)}return r.length===0?t==="OR"?i.constant(!1):void 0:f(r,t,i)},M=new Set(["AND","NOT","OR",L]),P=(n,t,o,i)=>{if(n===L){if(!o.relationExists)throw new T("INTERNAL","encountered a relation EXISTS marker without a relationExists strategy hook");return o.relationExists(t)}if(n==="NOT"){const s=h(t??{},o,i);return s===void 0?void 0:i.negate(s)}return U(t,n,o,i)},h=(n,t,o)=>{const i=[];for(const[s,r]of Object.entries(n))if(M.has(s)){const e=P(s,r,t,o);e!==void 0&&i.push(e)}else i.push(...D(s,r,t,o));return f(i,"AND",o)},q=O.boundParams/2,E=n=>{let t=0,o=0;const i=s=>{const r=E(s);t+=r.lists,o+=r.scalars};if(Array.isArray(n)){for(const s of n)i(s);return{lists:t,scalars:o}}if(n===null||typeof n!="object")return{lists:t,scalars:o};for(const[s,r]of Object.entries(n))s==="in"||s==="notIn"?t+=1:s==="AND"||s==="NOT"||s==="OR"||d(r)?i(r):o+=1;return{lists:t,scalars:o}},Q=(n,t,o=$)=>{if(!n||Object.keys(n).length===0)return;const{lists:i,scalars:s}=E(n);if(i===0)return h(n,t,o);const r=Math.max(1,Math.floor(Math.min(q,O.boundParams-s)/i)),e=t.inList??((c,a,N,b)=>o.inList(c,a,N,b??r));return h(n,{...t,inList:(c,a,N)=>e(c,a,N,r)},o)};export{Q as c,B as i,u as j,J as l,S as r,G as t};
@@ -1 +0,0 @@
1
- import{t as w,f as l}from"./base64-DfpzS4o_.mjs";const o="$lunora.wire$",m=64,A=1024,g="__proto__",p={BigInt64Array,BigUint64Array,Float32Array,Float64Array,Int8Array,Int16Array,Int32Array,Uint8Array,Uint8ClampedArray,Uint16Array,Uint32Array},O={Error,EvalError,RangeError,ReferenceError,SyntaxError,TypeError,URIError},j=r=>{if(r===null||typeof r!="object")return!1;const t=Object.getPrototypeOf(r);return t===null||t===Object.prototype},E=(r,t=0)=>{if(t>m)return!0;if(r===null)return!1;const c=typeof r;if(c==="string"||c==="boolean")return!1;if(c==="number")return!Number.isFinite(r);if(c!=="object")return!0;if(Array.isArray(r))return r.length>0&&r[0]===o?!0:r.some(f=>f===void 0||E(f,t+1));if(!j(r)||Object.hasOwn(r,g))return!0;for(const f of Object.keys(r)){const i=r[f];if(i!==void 0&&E(i,t+1))return!0}return!1},u=(r,t=0)=>{if(t>m)throw new RangeError(`wire-codec: value nesting exceeds the ${m}-level limit`);if(r===void 0)return[o,"undefined"];if(r===null)return null;const c=typeof r;if(c==="bigint")return[o,"bigint",r.toString()];if(c==="number"){const e=r;return Number.isNaN(e)?[o,"nan"]:e===1/0?[o,"inf"]:e===-1/0?[o,"-inf"]:e}if(c!=="object")return r;if(r instanceof Date)return[o,"date",u(r.getTime(),t+1)];if(r instanceof Error){const e=r,n={};for(const a of Object.keys(e))e[a]!==void 0&&(n[a]=u(e[a],t+1));const s=[o,"error",e.name,e.message,n];return e.cause!==void 0&&s.push(u(e.cause,t+1)),s}if(r instanceof URL)return[o,"url",r.href];if(r instanceof Map)return[o,"map",[...r.entries()].map(([e,n])=>[u(e,t+1),u(n,t+1)])];if(r instanceof Set)return[o,"set",[...r].map(e=>u(e,t+1))];if(r instanceof ArrayBuffer)return[o,"bytes",w(new Uint8Array(r)),"ArrayBuffer"];if(ArrayBuffer.isView(r)){const e=r,n=e.constructor.name,s=new Uint8Array(e.buffer,e.byteOffset,e.byteLength);return n==="Uint8Array"?[o,"bytes",w(s)]:[o,"bytes",w(s),n]}if(Array.isArray(r)){const e=r.map(n=>u(n,t+1));return e.length>0&&e[0]===o?[o,"arr",e]:e}if(!j(r)){const e=r.constructor?.name??"value";throw new TypeError(`wire-codec: cannot encode a ${e} over the Lunora wire — only plain objects, arrays, and the supported built-ins (Date, Error, URL, Map, Set, ArrayBuffer/typed arrays, bigint) round-trip`)}const f=r,i={};for(const e of Object.keys(f)){const n=f[e];if(n===void 0)continue;const s=u(n,t+1);e===g?Object.defineProperty(i,e,{configurable:!0,enumerable:!0,value:s,writable:!0}):i[e]=s}return i},y=(r,t=0)=>{if(t>m)throw new RangeError(`wire-codec: value nesting exceeds the ${m}-level limit`);if(r===null||typeof r!="object")return r;if(Array.isArray(r)){if(r[0]===o)switch(r[1]){case"-inf":return-1/0;case"arr":return r[2].map(e=>y(e,t+1));case"bigint":{const e=r[2];if(typeof e!="string"||e.length>A||!/^-?\d+$/.test(e))throw new RangeError(`wire-codec: invalid or over-long bigint (max ${A} digits)`);return BigInt(e)}case"date":return new Date(y(r[2],t+1));case"map":{const e=r[2];return new Map(e.map(n=>{if(!Array.isArray(n)||n.length!==2)throw new TypeError("wire-codec: malformed map entry — expected a [key, value] pair");return[y(n[0],t+1),y(n[1],t+1)]}))}case"set":return new Set(r[2].map(e=>y(e,t+1)));case"url":return new URL(r[2]);case"error":{const e=r[2],n=r[3],s=(Object.hasOwn(O,e)?O[e]:void 0)??Error,a=new s(n);a.name!==e&&Object.defineProperty(a,"name",{configurable:!0,value:e,writable:!0});const d=y(r[4],t+1);for(const b of Object.keys(d))b===g?Object.defineProperty(a,b,{configurable:!0,enumerable:!0,value:d[b],writable:!0}):a[b]=d[b];return r.length>5&&Object.defineProperty(a,"cause",{configurable:!0,value:y(r[5],t+1),writable:!0}),a}case"bytes":{const e=l(r[2]),n=r[3]??"Uint8Array";if(n==="ArrayBuffer")return e.buffer.byteLength===e.byteLength?e.buffer:e.slice().buffer;const s=Object.hasOwn(p,n)?p[n]:void 0;return s?new s(e.slice().buffer):e}case"inf":return 1/0;case"nan":return Number.NaN;case"undefined":return;default:return r.map(e=>y(e,t+1))}return r.map(i=>y(i,t+1))}const c=r,f={};for(const i of Object.keys(c)){const e=y(c[i],t+1);i===g?Object.defineProperty(f,i,{configurable:!0,enumerable:!0,value:e,writable:!0}):f[i]=e}return f};export{y as d,u as e,j as i,E as n};