@lunora/shard-engine 1.0.0-alpha.59 → 1.0.0-alpha.60

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 (58) hide show
  1. package/dist/conformance/index.mjs +1 -1
  2. package/dist/index.d.mts +15 -4
  3. package/dist/index.d.ts +15 -4
  4. package/dist/index.mjs +1 -1
  5. package/dist/packem_shared/{ADMIN_FUNCTIONS-MzNUYBeH.mjs → ADMIN_FUNCTIONS-CkHqihb_.mjs} +1 -1
  6. package/dist/packem_shared/AGGREGATE_SQL_FUNCTION-DDEoMnJR.mjs +1 -0
  7. package/dist/packem_shared/AGG_COUNT-ZuAKCecq.mjs +1 -0
  8. package/dist/packem_shared/BIGINT_KEY_DIGITS-DIS6kqPO.mjs +1 -0
  9. package/dist/packem_shared/{CDC_LOG_TABLE-CAyqu8cg.mjs → CDC_LOG_TABLE-B-SKH98h.mjs} +1 -1
  10. package/dist/packem_shared/CURSOR_PREFIX-Bn8SFoGd.mjs +1 -0
  11. package/dist/packem_shared/CountRlsUnsupportedError-BvsDqfO2.mjs +1 -0
  12. package/dist/packem_shared/{DATA_MIGRATION_STATE_TABLE-BttUL9Sv.mjs → DATA_MIGRATION_STATE_TABLE-BNMWxRzv.mjs} +1 -1
  13. package/dist/packem_shared/{DEFAULT_MAX_RELATION_KEYS-Ciwtjo9t.mjs → DEFAULT_MAX_RELATION_KEYS-XESc7TiB.mjs} +1 -1
  14. package/dist/packem_shared/DEFAULT_MAX_RELAYS-DDOVsK5A.mjs +8 -0
  15. package/dist/packem_shared/{DEFAULT_TRANSACTION_LIMITS-D_xv2cwd.mjs → DEFAULT_TRANSACTION_LIMITS-UeeQm79B.mjs} +1 -1
  16. package/dist/packem_shared/NotUniqueError-BO_Arsyi.mjs +1 -0
  17. package/dist/packem_shared/{RANK_TIEBREAK-CkNuGm6a.mjs → RANK_TIEBREAK-3pXm7Ng_.mjs} +1 -1
  18. package/dist/packem_shared/RLS_UNWRAP_SYMBOL-BF5gi64E.mjs +1 -0
  19. package/dist/packem_shared/{ReactiveCache-Co_Q4zWX.mjs → ReactiveCache-D9NC5C9j.mjs} +1 -1
  20. package/dist/packem_shared/{applyOnDelete-tDhKaeB6.mjs → applyOnDelete-7JZ4vR9r.mjs} +1 -1
  21. package/dist/packem_shared/{backfillAggregateIndexes-pQWaX2Yu.mjs → backfillAggregateIndexes-BXftO36q.mjs} +1 -1
  22. package/dist/packem_shared/buildReprojectionMigration-Cmo0g3p3.mjs +1 -0
  23. package/dist/packem_shared/{buildShapeDiff-C-ipEyt_.mjs → buildShapeDiff-IXpIxdnF.mjs} +1 -1
  24. package/dist/packem_shared/{compileWhereSql-ByHAmOE-.mjs → compileWhereSql-B8tS0_nD.mjs} +1 -1
  25. package/dist/packem_shared/{computeRankPage-DEkYJ9Tz.mjs → computeRankPage-BvVrHUOx.mjs} +1 -1
  26. package/dist/packem_shared/createCompanionSync-CfuiObtd.mjs +1 -0
  27. package/dist/packem_shared/{createReplicaLink-D1Rmca3b.mjs → createReplicaLink-BPmCx8rV.mjs} +3 -3
  28. package/dist/packem_shared/ctx-db-companions-kHoblDbS.mjs +1 -0
  29. package/dist/packem_shared/defineEngineContractSuite-J4VL-C0q.mjs +1 -0
  30. package/dist/packem_shared/do-sql-ByyZb9U0.mjs +1 -0
  31. package/dist/packem_shared/estimate-bytes-DCVD8-i6.mjs +1 -0
  32. package/dist/packem_shared/{isSoftDeleted-CVu_TCeK.mjs → isSoftDeleted-BlFMzng2.mjs} +1 -1
  33. package/dist/packem_shared/{materializeExternalRows-CAPAra-0.mjs → materializeExternalRows-CFE0QRYx.mjs} +1 -1
  34. package/dist/packem_shared/{runShardMigrations-CkG92fSl.mjs → runShardMigrations-BvgoGgwG.mjs} +1 -1
  35. package/dist/packem_shared/{selectExpiredIds-BjZ_UtMx.mjs → selectExpiredIds-D-W5WEPH.mjs} +1 -1
  36. package/dist/packem_shared/{selectShapeMembers-DqikYFjS.mjs → selectShapeMembers-OatGcYrk.mjs} +1 -1
  37. package/dist/packem_shared/serializeSqlValue-xohfS85H.mjs +1 -0
  38. package/dist/packem_shared/sibling-channel-BkL5cTCc.mjs +1 -0
  39. package/dist/packem_shared/sql-projection-DML1_ex4.mjs +1 -0
  40. package/dist/packem_shared/where-sql-x1YKldcq.mjs +1 -0
  41. package/package.json +2 -2
  42. package/dist/packem_shared/AGGREGATE_SQL_FUNCTION-m1iUU1rv.mjs +0 -1
  43. package/dist/packem_shared/AGG_COUNT-DnmDMp-h.mjs +0 -1
  44. package/dist/packem_shared/BIGINT_KEY_DIGITS-GvEBhyR5.mjs +0 -1
  45. package/dist/packem_shared/CURSOR_PREFIX-qn6nNVS7.mjs +0 -1
  46. package/dist/packem_shared/CountRlsUnsupportedError-Bdfupt3g.mjs +0 -1
  47. package/dist/packem_shared/DEFAULT_MAX_RELAYS-C3L_1GLp.mjs +0 -8
  48. package/dist/packem_shared/NotUniqueError-CTSwCMsP.mjs +0 -1
  49. package/dist/packem_shared/RLS_UNWRAP_SYMBOL-B3RgW-Kb.mjs +0 -1
  50. package/dist/packem_shared/buildReprojectionMigration-C-EJ_eKR.mjs +0 -1
  51. package/dist/packem_shared/createCompanionSync-BpWcC55_.mjs +0 -1
  52. package/dist/packem_shared/ctx-db-companions-B4O4d95S.mjs +0 -1
  53. package/dist/packem_shared/defineEngineContractSuite-F4j85ofN.mjs +0 -1
  54. package/dist/packem_shared/do-sql-FNOnpyHm.mjs +0 -1
  55. package/dist/packem_shared/estimate-bytes-DKqVDdZQ.mjs +0 -1
  56. package/dist/packem_shared/serializeSqlValue-B_-zaEWZ.mjs +0 -1
  57. package/dist/packem_shared/sibling-channel-Cxvk0Zca.mjs +0 -1
  58. package/dist/packem_shared/where-sql-B1l5NcUZ.mjs +0 -1
@@ -0,0 +1 @@
1
+ import{LunoraError as $}from"@lunora/errors";import{D as st}from"./MAX_TOKEN_LENGTH-BakL9FUy-B3VwYY8C.mjs";import{c as hn,S as wn,l as De,a as pn}from"./ctx-db-companions-kHoblDbS.mjs";import{sql as i}from"drizzle-orm";import{d as gn}from"./wire-codec-C-FpWm52.mjs";import{throwingScheduler as $n,aggregateSqlFunction as Le,normalizeCountArgument as yn}from"./AGGREGATE_SQL_FUNCTION-DDEoMnJR.mjs";import{aggregateTableName as Ve,encodeAggregateKey as ze,readAggregateValue as Je}from"./aggregateTableName-C7o-gpms.mjs";import{mergeWhere as z,CountRlsUnsupportedError as Ye,selectIndexForGroupBy as En,selectIndexForCount as mn,selectIndexForAggregate as Sn}from"./CountRlsUnsupportedError-BvsDqfO2.mjs";import{backfillSearchIndexesForTable as _n,searchIndexCoversTable as Rn}from"./backfillAggregateIndexes-BXftO36q.mjs";import{backfillAggregateIndexes as Ir,backfillRankIndexes as Cr,backfillSearchIndexes as xr}from"./backfillAggregateIndexes-BXftO36q.mjs";import{appendCdcChange as Tn}from"./CDC_LOG_TABLE-B-SKH98h.mjs";import{CDC_LOG_TABLE as Mr,applyCdcChanges as Dr,bumpCdcEpoch as Lr,cdcCanVouchFor as kr,cdcSeqLeavingRows as Fr,cdcTouchesTables as qr,cdcTrimmedError as Br,compactCdcDocs as Wr,cursorBelowRetainedFloor as Ur,minCdcReplayableSeq as Pr,minCdcSeq as Gr,readCdcChangeKeys as Hr,readCdcChanges as Or,readCdcCursor as Nr,readCdcEpoch as jr,trimCdcChanges as Kr}from"./CDC_LOG_TABLE-B-SKH98h.mjs";import{allocateCommitSeq as An,COMMIT_SEQ_FIELD as vn}from"./COMMIT_SEQ_FIELD-BUdOMG5y.mjs";import{isMemoryTable as _t}from"./clearMemoryTables-BGbmag2i.mjs";import{computeRankPage as Rt}from"./computeRankPage-BvVrHUOx.mjs";import{SCAN_DEP as H}from"./SCAN_DEP-D7qE3iUe.mjs";import{runDrizzle as N,runSql as Se}from"./runDrizzle-2ULFQR_k.mjs";import{D as oe,k as ce,r as le,b as ke,A as Xe,a as Fe,e as X,o as In,t as jt,j as We,q as Tt,i as Cn,h as Kt,g as xn}from"./do-sql-ByyZb9U0.mjs";import{renderSql as Qt,unionAll as ct,WORKERD_SQLITE_LIMITS as Vt,sqliteInList as bn}from"./param-DlozcSQu.mjs";import{coveringGeohashes as Mn,boundingBoxGeohashes as Dn,haversineMeters as Ln,pointInBoundingBox as kn}from"./GEO_DEFAULT_PRECISION-CqpQZ-J_.mjs";import{NotFoundError as Fn}from"./NotFoundError-BhF7FeFr.mjs";import{softDeleteScope as de,normalizeOrderKeys as nt,uniqueIndexFields as zt,equalityPinnedFields as qn,buildSeekWhere as Jt,decodeCursor as ot,applySelect as At,encodeCursor as rt,tiebreakDirectionFor as Yt,buildSeekBeforeWhere as Bn}from"./CURSOR_PREFIX-Bn8SFoGd.mjs";import{rankTableName as vt,sortColumnName as It,resolveRankPartition as Wn,encodePartitionKey as Un,RANK_TIEBREAK as Pn,rankPivotConditionSql as Gn}from"./RANK_TIEBREAK-3pXm7Ng_.mjs";import{UNVOUCHABLE_DEP as Ct}from"./UNVOUCHABLE_DEP-C68htACn.mjs";import{indexKeysForRow as Hn,buildIndexRange as On}from"./buildIndexRange-CBKQmHSS.mjs";import{assertFlatPredicate as Ze,resolveRelationPredicates as xt}from"./DEFAULT_MAX_RELATION_KEYS-XESc7TiB.mjs";import{runRowValidators as et,resolveWith as bt,relationHooks as Mt,applyOnDelete as Nn,fanOutScalarCounts as jn}from"./applyOnDelete-7JZ4vR9r.mjs";import{guardWriter as Kn}from"./RLS_UNWRAP_SYMBOL-BF5gi64E.mjs";import{quoteIdentifier as _e}from"./quoteIdentifier-CObIFRhb.mjs";import{m as Qn}from"./sql-projection-DML1_ex4.mjs";import{createSystemReader as Vn}from"./createSystemReader-DcDLFfC-.mjs";import{ConflictError as Ee}from"./ConflictError-C8GtJmjS.mjs";import{runTriggers as zn}from"./hasTrigger-CjlwI4le.mjs";import{c as ne,t as Pe,r as Ue,j as me,i as Dt}from"./where-sql-x1YKldcq.mjs";import{CLIENT_WATERMARK_TABLE as Vr,advanceClientWatermark as zr,migrateClientWatermark as Jr,readClientWatermark as Yr}from"./CLIENT_WATERMARK_TABLE-CRnrAnJ2.mjs";import{GLOBAL_SHAPE_SNAPSHOT_TABLE as Zr,deleteGlobalShapeSnapshot as ei,deleteGlobalShapeSnapshotsForConnection as ti,migrateGlobalShapeSnapshot as ni,readGlobalShapeSnapshot as oi,writeGlobalShapeSnapshot as ri}from"./GLOBAL_SHAPE_SNAPSHOT_TABLE-DSA6mzyx.mjs";import{IDEMPOTENCY_TABLE as si,readIdempotent as ci,trimIdempotent as ai,writeIdempotent as di}from"./IDEMPOTENCY_TABLE-DOpm_oMF.mjs";import{runShardMigrations as ui}from"./runShardMigrations-BvgoGgwG.mjs";import{S as hi}from"./ctx-db-search-state-ruTuCsxa.mjs";import{selectShapeMembers as pi,selectShapeRows as gi}from"./selectShapeMembers-OatGcYrk.mjs";import{serializeSqlValue as re}from"./serializeSqlValue-xohfS85H.mjs";const Jn=o=>{const r=atob(o),t=Uint8Array.from(r,a=>a.codePointAt(0)??0);return new TextDecoder().decode(t)},Yn=()=>new $("BAD_REQUEST","invalid cursor"),Lt=16,kt=8,Y=1024,at=(o,r)=>r.query(o),Xn=(o,r)=>{if(o.length===0)return 0;let t=0;for(const[a,d]of r.entries()){const w=a===r.length-1;let E=0;for(const S of o)(w?S.startsWith(d):S===d)&&(E+=1);if(E===0)return 0;t+=E}return t},Zn=(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)}},eo=(o,r,t)=>{const a={eq:(d,w)=>{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>=kt)throw new $("BAD_REQUEST",`search index "${o.indexName}" on table "${r}": at most ${String(kt)} .eq() filters are supported per search query`);return o.filters.push({field:d,value:w}),a},search:(d,w)=>{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=at(w,t).length;if(S>Lt)throw new $("BAD_REQUEST",`search index "${E.indexName}" on table "${r}": at most ${String(Lt)} search terms are supported (got ${String(S)})`);return E.field=d,E.query=w,E.hasQuery=!0,a}};return a},to=o=>{if(o.length>Y)throw new $("BAD_REQUEST",`more than ${String(Y)} documents match this search — narrow it with filters or read it a page at a time with .paginate()`)},no=o=>Math.min(o.offset+o.numItems+1,Y),oo=o=>btoa(`search:${String(o)}`),ro=o=>{let r;try{r=Jn(o)}catch{return}if(!r.startsWith("search:"))return;const t=Number(r.slice(7));return Number.isInteger(t)&&t>=0?t:void 0},io=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?ro(o.cursor):0;if(t===void 0)throw Yn();if(t+r>=Y)throw new $("BAD_REQUEST",`search pagination reaches the ${String(Y)}-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,Y-t-1))} or fewer, or narrow the query or the filters instead`);return{numItems:r,offset:t}},so=(o,r)=>{const t=r.offset+r.numItems,a=r.numItems>0&&o.length>t;return{continueCursor:a?oo(t):null,isDone:!a,page:o.slice(r.offset,t)}},co=o=>{if(o===void 0)return Y+1;if(!Number.isFinite(o))return Y;const r=Math.max(0,Math.floor(o));if(r>Y)throw new $("BAD_REQUEST",`search returns at most ${String(Y)} documents (asked for ${String(r)}) — narrow the query or paginate instead`);return r},Ge=o=>{const r=new Map;return t=>{const a=r.get(t);if(a!==void 0)return a;const d=o(_e(t));return r.set(t,d),d}},ue=_e(oe),ao=Ge(o=>`INSERT INTO ${o} (id, _creationTime, ${ue}) VALUES (?, ?, ?)`),Ft=Ge(o=>`UPDATE ${o} SET ${ue} = ? WHERE id = ? AND ${ue} = ?`),lo=Ge(o=>`UPDATE ${o} SET _creationTime = ?, ${ue} = ? WHERE id = ? AND ${ue} = ?`),uo=Ge(o=>`DELETE FROM ${o} WHERE id = ? AND ${ue} = ?`),fo="SELECT changes() AS changed",qt=new Map,ho="",wo=o=>{const r=JSON.stringify(o),t=qt.get(r);if(t!==void 0)return t;const a=o.map(w=>i`SELECT ${i.raw(`'${w.replaceAll("'","''")}'`)} AS __t__, id, _creationTime, ${i.identifier(oe)} FROM ${i.identifier(w)} WHERE id = ${ho}`),{sql:d}=Qt("sqlite",i`${ct(a)} LIMIT 1`);return qt.set(r,d),d},po=(o,r)=>r.map(()=>o),go=/^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/iu,$o=o=>{if(!go.test(o))throw new $("INTERNAL",`invalid clientId ${JSON.stringify(o)}: a client-supplied row id must be a UUID`)},Bt=50,Xt=500,qe=Math.floor(Vt.boundParams/3),$e=Vt.boundParams,yo=128,ae=(o,r,t)=>{const a=r??Xt;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})},Eo=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},mo=o=>Math.max(o,Y),Zt=(o,r)=>{const t=o.filters.map(a=>i`${X(a.field)} = ${re(a.value)}`);return r&&t.push(r),t},So=(o,r,t,a,d)=>{const w=at(t.query,st(t.definition.language));if(w.length===0)return[];const E=wn(r,t.indexName),S=`${E}__vocab`,_=w.length-1,D=w.map((R,k)=>{const q=Zn(R,k===_),U=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(k))} AS ${i.identifier("__term__")}, COUNT(*) AS ${i.identifier("__n__")} FROM ${i.identifier(S)} WHERE ${U} GROUP BY ${i.identifier("doc")}`}),y=w.map((R,k)=>i`SUM(CASE WHEN u.${i.identifier("__term__")} = ${i.raw(String(k))} THEN u.${i.identifier("__n__")} ELSE 0 END)`),A=i`SELECT f.${i.identifier(De)} AS ${i.identifier(De)}, ${i.join(y,i` + `)} AS ${i.identifier("__score__")} FROM (${ct(D)}) u JOIN ${i.identifier(E)} f ON f.rowid = u.${i.identifier("doc")} GROUP BY f.${i.identifier(De)} HAVING ${i.join(y.map(R=>i`${R} > 0`),i` AND `)}`,I=Zt(t,d);let F=i`SELECT m.id, m._creationTime, m.${i.identifier(oe)}, s.${i.identifier("__score__")} AS ${i.identifier("__score__")} FROM (${A}) s JOIN ${i.identifier(r)} m ON m.id = s.${i.identifier(De)}`;I.length>0&&(F=i`${F} WHERE ${i.join(I,i` AND `)}`),F=i`${F} ORDER BY s.${i.identifier("__score__")} DESC, m._creationTime DESC, m.id ASC LIMIT ${i.raw(String(a))}`;const j=[];for(const R of N(o,F)){const k=Kt(R);if(k){const q=R.__score__;j.push({document:k,score:typeof q=="number"?q:Number(q??0)})}}return j},_o=(o,r,t,a,d)=>{const w=st(t.definition.language),E=at(t.query,w);if(E.length===0)return[];const S=Zt(t,d);let _=i`SELECT id, _creationTime, ${i.identifier(oe)} FROM ${i.identifier(r)}`;S.length>0&&(_=i`${_} WHERE ${i.join(S,i` AND `)}`),_=i`${_} ORDER BY _creationTime DESC, id ASC LIMIT ${i.raw(String(mo(a)))}`;const D=N(o,_).toArray(),y=[];for(const A of D){const I=Kt(A);if(!I)continue;const F=Xn(pn(I,t.definition),E);F>0&&y.push({creationTime:typeof I._creationTime=="number"?I._creationTime:0,doc:I,id:typeof I._id=="string"?I._id:"",score:F})}return y.sort((A,I)=>I.score-A.score||I.creationTime-A.creationTime||A.id.localeCompare(I.id)),y.slice(0,a).map(A=>({document:A.doc,score:A.score}))},tt=(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]`)},Ro=(o,r)=>{const t=o,a={near:(d,w)=>{if(t.within)throw new $("INTERNAL",`geo index "${t.indexName}" on table "${r}": call .near() or .within(), not both`);if(tt(d,".near() point",r,t.indexName),!Number.isFinite(w)||w<=0)throw new $("BAD_REQUEST",`geo index "${t.indexName}" on table "${r}": .near() radiusMeters must be a finite number > 0, got ${String(w)}`);return t.near={point:{lat:d.lat,lng:d.lng},radiusMeters:w},a},within:d=>{if(t.near)throw new $("INTERNAL",`geo index "${t.indexName}" on table "${r}": call .near() or .within(), not both`);if(tt(d.sw,".within() sw corner",r,t.indexName),tt(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},To=(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},Ao=(o,r)=>{const t=To(o,r.definition.field);if(!t)return;const a=typeof o._creationTime=="number"?o._creationTime:0;if(r.near){const d=Ln(r.near.point,t);return d<=r.near.radiusMeters?{creationTime:a,distance:d}:void 0}return kn(t,r.within)?{creationTime:a,distance:0}:void 0},vo=(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?Mn(t.near.point,t.near.radiusMeters):Dn(t.within),w=xn(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 _=i`SELECT m.id, m._creationTime, m.${i.identifier(oe)} FROM ${i.identifier(w)} g JOIN ${i.identifier(r)} m ON m.id = g.${i.identifier("__id__")} WHERE ${i.join(S,i` AND `)}`,D=N(o,_).toArray(),y=[];for(const A of D){const I=le(A),F=I?Ao(I,t):void 0;I&&F&&y.push({creationTime:F.creationTime,distance:F.distance,doc:I})}return y.sort((A,I)=>A.distance-I.distance||I.creationTime-A.creationTime),y},en=(o,r,t,a)=>{const d=[];for(const w of o)if(r.every(E=>E(a(w)))&&(d.push(w),typeof t=="number"&&d.length>=t))break;return d},Io=(o,r,t,a,d,w=()=>{})=>{const E=t.within!==void 0,S=vo(o,r,t,d).map(_=>({distanceMeters:E?null:_.distance,document:_.doc}));return w(S.length),typeof a=="number"?S.slice(0,Math.max(0,Math.floor(a))):S},tn=(o,r,t,a,d,w=()=>{})=>{const{geo:E}=t;if(!E)throw new $("INTERNAL","runGeoTerminalScored called without a staged geo query");const S=t.inMemoryFilters.length>0,_=Io(o,r,E,S?void 0:d,a,w);return S?en(_,t.inMemoryFilters,d,D=>D.document):_},nn=(o,r,t,a)=>{const d=`SELECT id, _creationTime, ${_e(oe)} FROM ${_e(o)}`,w=`ORDER BY ${t}${a===void 0?"":` LIMIT ${String(a)}`}`;return r===void 0?Ue(`${d} ${w}`):me(`${d} WHERE `,r,` ${w}`)},Co=(o,r,t,a,d,w=()=>{})=>tn(o,r,t,a,d,w).map(E=>E.document),xo=(o,r,t,a,d,w,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 _=i`SELECT id, _creationTime, ${i.identifier(oe)} FROM ${i.identifier(r)}`;S.length>0&&(_=i`${_} WHERE ${i.join(S,i` AND `)}`),_=i`${_} ORDER BY ${d}`,typeof w=="number"&&t.inMemoryFilters.length===0&&(_=i`${_} LIMIT ${i.raw(String(Math.max(0,Math.floor(w))))}`);const D=N(o,_).toArray();E(D.length);const y=[];for(const A of D){const I=le(A);if(I&&t.inMemoryFilters.every(F=>F(I))&&(y.push(I),typeof w=="number"&&y.length>=w))break}return y},ye={fieldRef:X,serialize:re},on=(o,r)=>{const t=r===void 0?void 0:o.shape[r];return t!==void 0&&Qn(t)},Wt=(o,r)=>r.some(t=>on(o,t)),Ut=(o,r,t)=>{if(on(o,r))throw new $("BAD_REQUEST",`${t}: "${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)`)},dt={fieldRef:o=>Ue(We(o)),serialize:re},bo=o=>{let r=0;const t=[],a={fieldRef:d=>Ue(We(d)),relationExists:d=>{const{childWhere:w,negated:E,parentTable:S,relation:_}=d,D=`__rel_${String(r)}`,y=t.at(-1)??S;r+=1,o(_.table,H);const A=_.kind==="one"?_.field:_.references,I=_.kind==="one"?_.references:_.field,F=Ue(`${Tt(D,I)} = ${Tt(y,A)}`);t.push(D);const j=ne(w,a,Pe);t.pop();const R=j===void 0?F:me(F," AND ",j),k=me("EXISTS (SELECT 1 FROM ",Dt(_.table)," AS ",Dt(D)," WHERE ",R,")");return E?me("NOT ",k):k},serialize:re};return a},rn=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")} ${Yt(o)==="desc"?"DESC":"ASC"}`),r.join(", ")},Mo=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(Yt(o)==="desc"?"DESC":"ASC")}`),i.join(r,i`, `)},Do={"<":"lt","<=":"lte","=":"eq",">":"gt",">=":"gte"},sn=o=>new Set(o.sqlConditions.filter(r=>r.comparator==="=").map(r=>r.field)),Lo=o=>{const r=sn(o);let t=0;for(;t<o.indexFields.length&&r.has(o.indexFields[t]??"");)t+=1;return o.indexFields.slice(t)},cn=(o,r)=>{const t=o.order,a=Lo(o),{shape:d}=r;return a.length>0?nt(a.map(w=>({[w]:t})),d,{pinned:sn(o),uniqueBy:zt(r.indexes,d)}):nt([{_creationTime:t}],d)},ko=(o,r,t,a)=>{const d=o.sqlConditions.map(w=>({[w.field]:{[Do[w.comparator]??"eq"]:w.value}}));if(t&&d.push(Jt(r,ot(t))),a&&d.push(Bn(r,ot(a))),d.length!==0)return d.length===1?d[0]:{AND:d}},Fo=(o,r,t)=>{const a=[];for(const d of o){const w=le(d);if(w&&r.every(E=>E(w))&&(a.push(w),t!==void 0&&a.length>t))break}return a},qo=(o,r,t,a,d,w,E=()=>{})=>{const S=Math.max(0,Math.floor(d.numItems)),_=cn(a,t),D=typeof d.endCursor=="string",y=ne(ko(a,_,d.cursor,d.endCursor),dt,Pe),A=w&&y?me(y," AND ",w):w??y,I=a.inMemoryFilters.length>0,F=nn(r,A,rn(_),I||D?void 0:S+1),j=Se(o,F.text,...F.params).toArray();E(j.length);const R=Fo(j,a.inMemoryFilters,I||D?void 0:S);if(D){const O=R.length>=2?R[Math.floor(R.length/2)-1]:void 0;return{continueCursor:d.endCursor??null,isDone:!0,page:R,splitCursor:O?rt(O,_):null}}const k=R.length>S,q=k?R.slice(0,S):R,U=q.at(-1);return{continueCursor:k&&U?rt(U,_):null,isDone:!k,page:q}};class Bo extends ${constructor(r="unique() found more than one matching document"){super("NOT_UNIQUE",r,{name:"NotUniqueError"})}}const Wo=/\s/u,Uo=String.fromCodePoint(0),Pt=(o,r,t)=>{if(!o.tables[r])throw new $("INTERNAL",`unknown table: ${r}`);return typeof t!="string"||t.length===0||Wo.test(t)||t.includes(Uo)?null:t},Po=(o,r,t,a=()=>{},d=()=>{},w=()=>{})=>{const E=r.tables[t];if(!E)throw new $("INTERNAL",`unknown table: ${t}`);const S=de(E.softDeleteMode,void 0),_=S?ne(S,ye):void 0,D=S?ne(S,dt,Pe):void 0,y={indexFields:[],indexName:void 0,inMemoryFilters:[],order:"asc",sqlConditions:[]};let A=0;const I=m=>{const{search:C}=y;if(!C)throw new $("INTERNAL","runSearchFetch called without a staged search");_n(o,t,E);const M=y.inMemoryFilters.length>0,L=co(M?void 0:m),K=Cn(o);if(K&&!Rn(o,t,C.definition))throw new $("SEARCH_INDEX_BUILDING",`search index "${C.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 Z=K?So(o,t,C,L,_):_o(o,t,C,L,_);return M?(A=Z.length,en(Z,y.inMemoryFilters,m,He=>He.document)):(m===void 0&&to(Z),Z)},F=m=>I(m).map(C=>C.document),j=m=>{const C=io(m);return so(F(no(C)),C)},R=()=>Mo(cn(y,E)),k=()=>{if(y.search||y.geo||y.indexName===void 0){d(void 0);return}d(On(t,y.indexName,y.indexFields,y.sqlConditions,re))},q=m=>{k();let C=0;const M=(()=>{if(y.search){const L=F(m);return C=A,L}return y.geo?Co(o,t,y,_,m,L=>{C=L}):xo(o,t,y,_,R(),m,L=>{C=L})})();return w(Math.max(C,M.length)),M},U=()=>{if(!y.search&&!y.geo)throw new $("INTERNAL",`ctx.db.query("${t}").collectWithScores() requires a staged .withSearchIndex(...) or .withGeoIndex(...)`);k();let m=0;const C=(()=>{if(y.search){const M=I(void 0);return m=A,M}return tn(o,t,y,_,void 0,M=>{m=M})})();return w(Math.max(m,C.length)),C},O={async*[Symbol.asyncIterator](){if(y.search){yield*q(void 0);return}const m=[...y.inMemoryFilters];let C;y.inMemoryFilters=[];try{for(;;){const M=await O.paginate({cursor:C??null,numItems:yo});for(const L of M.page)m.every(K=>K(L))&&(yield L);if(M.isDone||M.continueCursor===null)return;C=M.continueCursor}}finally{y.inMemoryFilters=m}},async collect(){return q(void 0)},async collectWithScores(){return U()},filter(m){return y.inMemoryFilters.push(m),O},async first(){return q(y.inMemoryFilters.length>0?void 0:1)[0]??null},order(m){return y.order=m==="desc"?"desc":"asc",O},async paginate(m){let C=0;if(k(),y.search){const L=j(m);return w(L.page.length),L}if(y.geo)throw new $("INTERNAL","pagination is not supported on geo queries; use .take(n) or .collect()");const M=qo(o,t,E,y,m,D,L=>{C=L});return w(Math.max(C,M.page.length)),M},async take(m){return q(m)},async unique(){const m=q(y.inMemoryFilters.length>0?void 0:2);if(m.length>1)throw new Bo(`unique() on table "${t}" matched ${String(m.length)} documents; expected at most one`);return m[0]??null},withGeoIndex(m,C){const M=(E.geoIndexes??[]).find(K=>K.name===m);if(!M)throw new $("INTERNAL",`unknown geo index "${m}" on table "${t}"`);a(t,m,"geo");const L={definition:M,indexName:m};if(y.geo=L,C(Ro(L,t)),!L.near&&!L.within)throw new $("INTERNAL",`geo index "${m}" on table "${t}" requires a .near(point, radius) or .within(box) call`);return O},withIndex(m,C){const M=E.indexes.find(L=>L.name===m);if(!M)throw new $("INTERNAL",`unknown index "${m}" on table "${t}"`);return a(t,m,"index"),y.indexName=m,y.indexFields=M.fields,C&&C(Eo(y)),O},withSearchIndex(m,C){const M=(E.searchIndexes??[]).find(K=>K.name===m);if(!M)throw new $("INTERNAL",`unknown search index "${m}" on table "${t}"`);a(t,m,"search");const L={definition:M,field:M.field,filters:[],hasQuery:!1,indexName:m,query:""};if(y.search=L,C(eo(L,t,st(M.language))),!L.hasQuery)throw new $("INTERNAL",`search index "${m}" on table "${t}" requires a .search(field, query) call`);return O}};return O},Gt=(o,r,t)=>{const a={...r};for(const[d,w]of jt(o)){if(w.serverDefault){a[d]=w.serverDefault({auth:t});continue}a[d]===void 0&&(w.defaultFn?a[d]=w.defaultFn():"defaultValue"in w&&(a[d]=w.defaultValue))}return a},Ht=(o,r,t,a)=>{const d=t;for(const[w,E]of jt(o)){if(E.serverDefault){w in r&&(d[w]=E.serverDefault({auth:a}));continue}E.onUpdateFn&&!(w in r)&&(d[w]=E.onUpdateFn())}},Ot=(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.`)},Go=/unique constraint failed/i,Ho=o=>o instanceof Error&&Go.test(o.message),Oo=/string or blob too big/iu,No=(o,r)=>{if(!(!(o instanceof Error)||!Oo.test(o.message)))throw new $("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.`)},it=(o,r,t,a)=>{try{Se(o,t,...a)}catch(d){throw Ho(d)?new Ee(`unique constraint violation on "${r}"`,"unique"):(No(d,r),d)}},Be=(o,r,t,a)=>{if(it(o,r,t,a),Se(o,fo).one().changed===0)throw new Ee(`optimistic concurrency conflict on "${r}" — the row changed during this mutation; refetch and retry`,"occ")},Nt=(o,r,t,a,d,w,E)=>{const S=[];for(let A=0;A<t.length+1;A+=1){const I=t[A],F=a[A],j=F?.direction==="desc"?"desc":"asc",R=I===void 0||F===void 0?i`${i.identifier(Pn)} < ${E}`:Gn(I,w[A],j,!1);if(R===void 0)continue;const k=[];for(let U=0;U<A;U+=1)k.push(i`${i.identifier(t[U])} IS ${w[U]}`);k.push(R);const[q]=k;S.push(k.length===1&&q!==void 0?q:i`(${i.join(k,i` AND `)})`)}const _=S.length>0?i.join(S,i` OR `):i`1 = 0`,D=N(o,i`SELECT COUNT(*) AS c FROM ${i.identifier(r)} WHERE ${i.identifier("__partition__")} = ${d} AND (${_})`).one(),y=N(o,i`SELECT COUNT(*) AS c FROM ${i.identifier(r)} WHERE ${i.identifier("__partition__")} = ${d}`).one();return{before:D.c,total:y.c}},Tr=o=>{const{sql:r}=o,{schema:t}=o,a=o.broadcast??(()=>{});let d;const w=()=>o.inTransaction?.()===!0,E=e=>t.tables[e]?.commitOrderedMode!==!0?{}:((d===void 0||!w())&&(d=An(r)),{[vn]: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(...Hn(s,h,re));return f.length>0?f:void 0},{headroom:_}=o;let D=!1;const y=async e=>{const n=D;D=!0;try{return await e()}finally{D=n}},A=o.onRead??(()=>{}),I=e=>{_t(t.tables[e])&&A(Ct,Ct)},F=o.onReadRange??(e=>{A(e.table,H)}),j=e=>{I(e.table),F(e)},R=(e,n)=>{n!==void 0&&n!==H&&!D&&_?.recordRead(1),I(e),A(e,n)},k=o.onIndexUse??(()=>{}),q=o.onWrite??(()=>{}),U=e=>{D||_?.recordWrite(e)},O=async e=>{U(e.doc),await q(e)},{cache:m}=o,C=o.clock??(()=>Date.now()),M=o.idGenerator??(()=>crypto.randomUUID()),L=o.scheduler??$n,{globalDb:K}=o,Z=o.auth??{identity:null,userId:null},He=o.cdc??!1,Oe=L,an=Vn({scheduler:typeof Oe.list=="function"&&typeof Oe.get=="function"?Oe:void 0,storage:o.storage}),fe=(e,n,s,f)=>{He&&!_t(t.tables[e])&&Tn(r,C(),e,n,s,f)},ie=e=>t.tables[e]?.shardMode?.kind==="global",lt=(e,n)=>{if(ie(e)){if(!K)throw new $("INTERNAL",`cross-backend ${n} for global table '${e}' requires a globalDb writer — pass one to createShardCtxDb({ globalDb })`);return K}return P},Ne=e=>lt(e,"cascade"),V=(e,n)=>{if(ie(e)){if(!K)throw new $("INTERNAL",`${n} on global table '${e}' requires a globalDb writer — pass one to createShardCtxDb({ globalDb })`);return K}},ut=async(e,n,s,f,h)=>{h&&U(s);const u=await e.insert(n,s,f);return a({key:u,op:"insert",row:{...s,_id:u},table:n}),u},je=(e,n)=>lt(e,"relation load").findMany(e,n),ft=(e,n)=>(ie(e)&&R(e,H),je(e,n)),dn=e=>!ie(e.table),ht=o.relationExistsPushDown??"auto",wt=ht!=="never",{maxRelationKeys:pt}=o,Re=(e,n,s)=>xt(e,{fetcher:ft,maxRelationKeys:pt,relationBaseWhere:s,schema:t,tableName:n}),gt=async(e,n,s,f)=>{const h=V(e,"relation grouped count");if(h)return R(e,H),jn((B,v)=>h.count(B,v),e,n,s,f);const u=t.tables[e];if(!u)throw new $("INTERNAL",`unknown table: ${e}`);R(e,H);const c=de(u.softDeleteMode,void 0),l={[n]:{in:s}},p=z(z(l,f),c),T=await Re(p,e,void 0),g=ne(T,ye),b=X(n);let x=i`SELECT ${b} AS __fk__, COUNT(*) AS count FROM ${i.identifier(e)}`;g&&(x=i`${x} WHERE ${g}`),x=i`${x} GROUP BY ${b}`;const G=N(r,x).toArray();return new Map(G.map(B=>[B.__fk__,B.count]))};let Te=0;const $t=new Set;for(const[e,n]of Object.entries(t.tables))for(const s of Object.values(n.triggerMap??{}))$t.add(`${e} ${s.timing} ${s.op}`);const ee=(e,n,s)=>$t.has(`${e} ${n} ${s}`),te=async(e,n,s)=>{if(Te+=1,Te>Bt)throw Te-=1,new Ee(`trigger recursion exceeded ${String(Bt)} levels on "${s.table}" — check for a self-triggering write`,"trigger");try{await zn({ctx:un,event:s,op:n,schema:t,tableName:s.table,timing:e})}finally{Te-=1}},{ensureBackfilledForTable:he,ensureBackfilledIndex:Ke,ensureRankBackfilled:Qe,ensureRankBackfilledForTable:we,syncAggregates:Ae,syncCompanionsForInsert:yt,syncGeo:ve,syncRanks:pe,syncSearch:Ie}=hn({broadcast:a,indexKeysFor:(e,n)=>S(e,n),invalidateCache:(e,n,s)=>m?.invalidate(e,n,S(e,s)),recordCdc:fe,schema:t,sql:r}),Et=(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})},mt=e=>Object.entries(t.tables).filter(([,n])=>n.shardMode?.kind!=="global").map(([n])=>n).filter(n=>e===void 0||n===e),ge=e=>e===void 0||ie(e)?K:void 0,se=(e,n)=>{const s=mt(n);for(let f=0;f<s.length;f+=$e){const h=s.slice(f,f+$e),[u]=Se(r,wo(h),...po(e,h)).toArray();if(!u)continue;const c=u.__t__,l=le(u);if(typeof c!="string"||!l)return;const p=u[oe];return{docJson:typeof p=="string"?p:ce(p??{}),row:l,tableName:c}}},ln=(e,n)=>{const s=[...new Set(e)],f=new Map;if(s.length===0)return f;const h=mt(n);for(let u=0;u<h.length;u+=$e){const c=h.slice(u,u+$e),l=Math.floor($e/c.length),p=bn(i`${i.identifier("id")}`,s,!1,l),T=c.map(g=>i`SELECT ${i.raw(`'${g.replaceAll("'","''")}'`)} AS __t__, id FROM ${i.identifier(g)} WHERE ${p}`);for(const g of N(r,ct(T))){const{id:b,__t__:x}=g;typeof x=="string"&&typeof b=="string"&&f.set(b,x)}}return f},St={assertRankPartitionLocal:Et,ensureRankBackfilled:Qe,onRead:R,rowToDocument:le,schema:t,sql:r},P={system:an,async aggregate(e,n){const s=V(e,"aggregate");if(s)return R(e,H),s.aggregate(e,n);const f=t.tables[e];if(!f)throw new $("INTERNAL",`unknown table: ${e}`);if(Le(n.op),n.op==="count")return P.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`);R(e,H);const h=de(f.softDeleteMode,void 0),u=z(z(n.baseWhere,n.where),h),c=await Re(u,e,n.relationBaseWhere),l=c!==u;if(f.aggregateIndexes&&!n.baseWhere&&!l&&(!h||Wt(f,[n.field]))){const B=Sn(f.aggregateIndexes,n.op,n.field,n.where);if(B){Ke(e,B.index);const v=ze(B.index.by??[],B.key),Q=Ve(e,B.index.name),J=N(r,i`SELECT ${ke} AS value, ${Xe} AS count FROM ${i.identifier(Q)} WHERE ${Fe} = ${v}`).toArray()[0];return Je(n.op,J)}}Ut(f,n.field,`aggregate(${e}, { op: "${n.op}", field: "${n.field}" })`);const p=ne(c,ye),T=Le(n.op),g=X(n.field);let b=i`SELECT ${i.raw(T)}(${g}) AS value FROM ${i.identifier(e)}`;p&&(b=i`${b} WHERE ${p}`);const G=N(r,b).toArray()[0]?.value;return G??null},asId(e,n){const s=Pt(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=V(e,"count");if(s)return R(e,H),s.count(e,n);const f=t.tables[e];if(!f)throw new $("INTERNAL",`unknown table: ${e}`);const h=yn(n);if(h.restrictsCounts)throw new Ye(e);R(e,H);const u=de(f.softDeleteMode,void 0),c=z(z(h.baseWhere,h.where),u),l=await Re(c,e,h.relationBaseWhere),p=l!==c;if(f.aggregateIndexes&&!h.baseWhere&&!p&&!u){const x=mn(f.aggregateIndexes,h.where);if(x){Ke(e,x.index);const G=ze(x.index.by??[],x.key),B=Ve(e,x.index.name),v=N(r,i`SELECT ${ke} AS value FROM ${i.identifier(B)} WHERE ${Fe} = ${G}`).toArray();return v[0]===void 0?0:v[0].value??0}}const T=ne(l,ye);let g=i`SELECT COUNT(*) AS count FROM ${i.identifier(e)}`;return T&&(g=i`${g} WHERE ${T}`),N(r,g).one().count},async delete(e,n,s){const f=se(e,n);if(!f){const g=ge(n);g&&(U(void 0),await g.delete(e,n,s));return}const{docJson:h,row:u,tableName:c}=f,l=t.tables[c],p=s?.hard===!0,T=!p&&l?.softDeleteMode?l.softDeleteMode.field:void 0;if(!(T&&u[T]!==null&&u[T]!==void 0)){if(ee(c,"before","delete")&&await te("before","delete",{id:e,op:"delete",previous:u,table:c}),await Nn({deletedId:e,deletedReference:g=>u[g],findHolders:async(g,b,x)=>(await Ne(g).findMany(g,{includeDeleted:p,where:{[b]:x}})).page,onCascade:(g,b)=>Ne(g).delete(b,void 0,s),onRestrict:g=>{throw new Ee(g,"restrict")},onSetNull:(g,b,x)=>Ne(g).patch(b,{[x]:null}),schema:t,tableName:c}),he(c),we(c),T){const g={...u,...E(c),[T]:C(),_id:e};Be(r,c,Ft(c),[ce(g),e,h]),Ie(c,e,g,u),ve(c,e,void 0),Ae(c,u,g),pe(c,e,u,void 0),m?.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}),ee(c,"after","delete")&&await te("after","delete",{id:e,op:"delete",previous:u,table:c}),await O({id:e,op:"delete",table:c});return}Be(r,c,uo(c),[e,h]),Ie(c,e,void 0),ve(c,e,void 0),Ae(c,u,void 0),pe(c,e,u,void 0),m?.invalidate(c,e,S(c,u)),fe(c,e,"delete"),a({indexKeys:S(c,u),key:e,op:"delete",table:c}),ee(c,"after","delete")&&await te("after","delete",{id:e,op:"delete",previous:u,table:c}),await O({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??Xt),f=n?.hard===void 0?void 0:{hard:n.hard},h=ie(e)?void 0:e;let u=0;return await y(async()=>{for(;;){const l=(await P.findMany(e,{limit:s})).page.map(p=>String(p._id));if(l.length===0)break;for(const p of l)await P.delete(p,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 P.delete(f,s);return{deleted:e.length}},async deleteWhere(e,n,s){const u=(await(V(e,"deleteWhere")??P).findMany(e,{where:n})).page.map(c=>String(c._id));if(ae(u.length,s?.limit,"deleteWhere"),P.deleteMany===void 0)throw new $("INTERNAL",`ctx.db.${e}.deleteMany is unavailable: this writer has no batch delete`);return P.deleteMany(u,s)},async findFirst(e,n={}){return(await P.findMany(e,{...n,limit:1,omitContinueCursor:!0})).page[0]??null},async findFirstOrThrow(e,n={}){const s=await P.findFirst(e,n);if(s===null)throw new Fn(`findFirstOrThrow: no "${e}" document matched`);return s},async findMany(e,n={}){const s=V(e,"findMany");if(s)return R(e,H),s.findMany(e,n);const f=t.tables[e];if(!f)throw new $("INTERNAL",`unknown table: ${e}`);const h=!n.where&&!n.baseWhere;h?R(e,H):R(e);const u=nt(n.orderBy,f.shape,{pinned:qn(n.where),uniqueBy:zt(f.indexes,f.shape)}),c=n.cursor?Jt(u,ot(n.cursor)):void 0;let l=z(n.baseWhere,n.where);l=z(l,de(f.softDeleteMode,n.includeDeleted)),l=await xt(l,{canPushExists:wt?dn:void 0,existsPushMode:ht==="always"?"always":"auto",fetcher:ft,maxRelationKeys:pt,relationBaseWhere:n.relationBaseWhere,schema:t,tableName:e}),c&&(l=l?{AND:[l,c]}:c);const p=wt?bo(R):dt,T=ne(l,p,Pe),g=typeof n.limit=="number"?Math.max(0,Math.floor(n.limit)):void 0,b=nn(e,T,rn(u),g===void 0?void 0:g+1),x=Se(r,b.text,...b.params).toArray();h&&!D&&_?.recordRead(x.length);const G=[];for(const J of x){const W=le(J);W&&(G.push(W),!h&&typeof W._id=="string"&&R(e,W._id))}if(g===void 0)return n.with&&await bt({groupedCounter:gt,fetcher:je,parents:G,...Mt(n),schema:t,tableName:e,with:n.with}),{continueCursor:null,isDone:!0,page:At(G,n.select,n.with)};const B=G.length>g,v=B?G.slice(0,g):G,Q=v.at(-1);return n.with&&await bt({fetcher:je,groupedCounter:gt,parents:v,...Mt(n),schema:t,tableName:e,with:n.with}),{continueCursor:B&&Q&&n.omitContinueCursor!==!0?rt(Q,u):null,isDone:!B,page:At(v,n.select,n.with)}},async get(e,n){const s=se(e,n);if(!s){const f=ge(n);return f?f.get(e,n):null}return R(s.tableName,e),s.row},async lookupById(e,n){const s=se(e,n);return s?(R(s.tableName,e),{row:s.row,tableName:s.tableName}):null},async groupBy(e,n){const s=V(e,"groupBy");if(s)return R(e,H),s.groupBy(e,n);const f=t.tables[e];if(!f)throw new $("INTERNAL",`unknown table: ${e}`);R(e,H);const h=n.agg??{op:"count"};if(Le(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=z(z(n.baseWhere,n.where),u),l=await Re(c,e,n.relationBaseWhere),p=l!==c,T=[...n.by,h.field];if(f.aggregateIndexes&&!n.baseWhere&&!p&&(!u||Wt(f,T))){const v=En(f.aggregateIndexes,h.op,h.field,n.by,n.where),Q=v===void 0?0:Object.keys(v.partial).length,J=v?.index.by?.length??0;if(v&&(Q===0||Q===J)){Ke(e,v.index);const W=Ve(e,v.index.name),Ce=Object.keys(v.partial),xe=[];if(Ce.length===(v.index.by??[]).length&&Ce.length>0){const be=ze(v.index.by??[],v.partial),Me=N(r,i`SELECT ${ke} AS value, ${Xe} AS count FROM ${i.identifier(W)} WHERE ${Fe} = ${be}`).toArray();return Me.length>0&&xe.push({key:{...v.partial},value:Je(h.op,Me[0])}),xe}const fn=N(r,i`SELECT ${Fe} AS key, ${ke} AS value, ${Xe} AS count FROM ${i.identifier(W)}`).toArray();for(const be of fn){const Me=gn(JSON.parse(be.key));xe.push({key:Me,value:Je(h.op,be)})}return xe}}for(const v of T){if(v===void 0)continue;const Q=v===h.field?`groupBy(${e}, { agg: { op: "${h.op}", field: "${v}" } })`:`groupBy(${e}, { by: [..."${v}"] })`;Ut(f,v,Q)}const g=ne(l,ye),b=n.by.map(v=>i`${X(v)} AS ${i.identifier(v)}`);if(h.op==="count")b.push(i`COUNT(*) AS value`);else{const{field:v}=h;if(v===void 0)throw new $("INTERNAL",`groupBy(${e}, { agg: { op: "${h.op}" } }): "field" is required for non-count reducers`);b.push(i`${i.raw(Le(h.op))}(${X(v)}) AS value`)}let x=i`SELECT ${i.join(b,i`, `)} FROM ${i.identifier(e)}`;g&&(x=i`${x} WHERE ${g}`),x=i`${x} GROUP BY ${i.join(n.by.map(v=>X(v)),i`, `)}`;const G=N(r,x).toArray(),B=[];for(const v of G){const Q={};for(const W of n.by)Q[W]=In(f.shape[W],v[W]??null);const{value:J}=v;B.push({key:Q,value:J==null?null:Number(J)})}return B},async insert(e,n,s){const f=V(e,"insert");if(f)return ut(f,e,n,s,!0);const h=t.tables[e];if(!h)throw new $("INTERNAL",`unknown table: ${e}`);const u=Gt(h,n,Z);et(h,u);let c;s?.clientId!==void 0?($o(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:C(),p={...u,...E(e),_creationTime:l,_id:c};return ee(e,"before","insert")&&await te("before","insert",{doc:{...p},id:c,op:"insert",table:e}),he(e),we(e),it(r,e,ao(e),[c,l,ce(p)]),yt(e,c,p),ee(e,"after","insert")&&await te("after","insert",{doc:p,id:c,op:"insert",table:e}),await O({doc:p,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=V(e,"insert");if(f){const l=[];for(const p of n)U(p);for(const p of n){const T=await f.insert(e,p,{allowExplicitId:s?.allowExplicitId});a({key:T,op:"insert",row:{...p,_id:T},table:e}),l.push(T)}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+=qe)u.push(E(e));const c=n.map((l,p)=>{const T=Gt(h,l,Z),g=s?.allowExplicitId===!0&&typeof T._id=="string"?T._id:M(),b=s?.allowExplicitId===!0&&typeof T._creationTime=="number"?T._creationTime:C(),x={...T,...u[Math.floor(p/qe)],_creationTime:b,_id:g};return{creationTime:b,document:x,id:g}});for(const l of c)U(l.document);for(let l=0;l<c.length;l+=qe){const p=i.join(c.slice(l,l+qe).map(g=>i`(${g.id}, ${g.creationTime}, ${ce(g.document)})`),i`, `),T=Qt("sqlite",i`INSERT INTO ${i.identifier(e)} (id, _creationTime, ${i.identifier(oe)}) VALUES ${p}`);it(r,e,T.sql,T.params)}for(const{document:l,id:p}of c)yt(e,p,l),await q({doc:l,id:p,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=V(e,"insert");if(u)for(const l of n)U(l);const c=async l=>u?ut(u,e,l,void 0,!1):P.insert(e,l);for(const l of n)try{h.push(await c(l))}catch(p){if(f&&p instanceof Ee&&p.kind==="unique")h.push(null);else throw p}return h},normalizeId(e,n){return Pt(t,e,n)},async patch(e,n,s){const f=se(e,s);if(!f){const T=ge(s);if(T){U(n),await T.patch(e,n,s);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}`);R(c,e),Ot("patch",n);const p={...u,...n,...E(c),_id:e};Ht(l,n,p,Z),et(l,p,!0),ee(c,"before","update")&&await te("before","update",{doc:{...p},id:e,op:"update",previous:u,table:c}),he(c),we(c),Be(r,c,Ft(c),[ce(p),e,h]),Ie(c,e,p,u),ve(c,e,p),Ae(c,u,p),pe(c,e,u,p),m?.invalidate(c,e,S(c,u,p)),fe(c,e,"update",p),a({indexKeys:S(c,u,p),key:e,op:"update",row:p,table:c}),ee(c,"after","update")&&await te("after","update",{doc:p,id:e,op:"update",previous:u,table:c}),await O({doc:p,id:e,op:"update",table:c})},async patchMany(e,n,s){ae(e.length,n?.limit,"patchMany");for(const f of e)await P.patch(f.id,f.patch,s);return{patched:e.length}},async patchWhere(e,n,s){const u=(await(V(e,"patchWhere")??P).findMany(e,{where:n.where})).page.map(c=>({id:String(c._id),patch:n.patch}));if(ae(u.length,s?.limit,"patchWhere"),P.patchMany===void 0)throw new $("INTERNAL",`ctx.db.${e}.patchMany is unavailable: this writer has no batch patch`);return await P.patchMany(u,s),{patched:u.length}},query(e){const n=V(e,"query");return n?(R(e,H),n.query(e)):Po(r,t,e,k,s=>{s?j(s):R(e,H)},s=>{D||_?.recordRead(s)})},async rank(e,n,s){const f=V(e,"rank");if(f)return R(e,H),f.rank(e,n,s);k(e,n,"rank");const h=t.tables[e];if(!h)throw new $("INTERNAL",`unknown table: ${e}`);const u=h.rankIndexes?.find(W=>W.name===n);if(!u)throw new $("INTERNAL",`unknown rankIndex "${n}" on table "${e}"`);if(Et(e,h,u),s.restrictsCounts)throw new Ye(e);R(e,H),Qe(e,u);const c=typeof s.row=="string"?s.row:s.row._id;if(!c)return null;const l=vt(e,u.name),p=u.sortBy.map((W,Ce)=>It(Ce)),T=p.map(W=>_e(W)).join(", "),g=N(r,i`SELECT ${i.identifier("__partition__")}, ${i.raw(T)} FROM ${i.identifier(l)} WHERE ${i.identifier("__id__")} = ${c}`).toArray(),[b]=g;if(b===void 0)return null;let x=b.__partition__;const G=z(s.baseWhere,s.where);Ze(G,t,e,"rank");const B=Wn(u,G);if(B){const W=Un(u.partitionBy??[],B);if(W!==x)return null;x=W}const v=p.map(W=>b[W]),{before:Q,total:J}=Nt(r,l,p,u.sortBy,x,v,c);return{position:Q+1,total:J}},async rankBefore(e,n,s){if(ie(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(p=>p.name===n);if(!h)throw new $("INTERNAL",`unknown rankIndex "${n}" on table "${e}"`);if(s.restrictsCounts)throw new Ye(e);R(e,H),Qe(e,h);const u=vt(e,h.name),c=h.sortBy.map((p,T)=>It(T)),l=h.sortBy.map((p,T)=>re(s.sortValues[T]??null));return Nt(r,u,c,h.sortBy,s.partitionKey,l,s.rowId)},async rankPage(e,n,s={}){Ze(z(s.baseWhere,s.where),t,e,"rankPage");const f=V(e,"rankPage");if(f)return R(e,H),f.rankPage(e,n,s);k(e,n,"rank");const{continueCursor:h,hasMore:u,rows:c}=Rt(St,e,n,s);return{continueCursor:h,isDone:!u,page:c.map(l=>l.doc)}},async rankPageRows(e,n,s={}){Ze(z(s.baseWhere,s.where),t,e,"rankPage"),k(e,n,"rank");const{directions:f,hasMore:h,rows:u}=Rt(St,e,n,s);return{directions:f,hasMore:h,rows:u}},async restore(e,n){const s=se(e,n);if(!s){const u=ge(n);if(u?.restore){await u.restore(e,n);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 P.patch(e,{[f]:null},n),h&&pe(s.tableName,e,void 0,s.row)},async replace(e,n,s,f){const h=se(e,s);if(!h){const b=ge(s);if(b){U(n),await b.replace(e,n,s,f);return}throw new $("NOT_FOUND",`document not found: ${e}`)}const{docJson:u,row:c,tableName:l}=h,p=t.tables[l];if(!p)throw new $("INTERNAL",`unknown table: ${l}`);Ot("replace",n);const T=f?.allowExplicitId&&typeof n._creationTime=="number"?n._creationTime:C(),g={...n,...E(l),_creationTime:T,_id:e};Ht(p,n,g,Z),et(p,g),ee(l,"before","update")&&await te("before","update",{doc:{...g},id:e,op:"update",previous:c,table:l}),he(l),we(l),Be(r,l,lo(l),[T,ce(g),e,u]),Ie(l,e,g,c),ve(l,e,g),Ae(l,c,g),pe(l,e,c,g),m?.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}),ee(l,"after","update")&&await te("after","update",{doc:g,id:e,op:"update",previous:c,table:l}),await O({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,p])=>n.has(l)||s!==void 0&&!s.includes(l)?!1:p.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}=P;if(c===void 0)throw new $("INTERNAL","wipeShard: this writer has no deleteAll");for(const l of f){const p=await c(l,{...e?.chunkSize===void 0?{}:{chunkSize:e.chunkSize},hard:!0});h[l]=p.deleted,u+=p.deleted}return{deleted:u,tables:h}}},un={db:P,scheduler:L};return o.enforceRls===!0?Kn(P,t,(e,n)=>se(e,n)?.tableName,(e,n)=>ln(e,n)):P};export{Mr as CDC_LOG_TABLE,Vr as CLIENT_WATERMARK_TABLE,Zr as GLOBAL_SHAPE_SNAPSHOT_TABLE,si as IDEMPOTENCY_TABLE,Bo as NotUniqueError,hi as SEARCH_STATE_TABLE,zr as advanceClientWatermark,Dr as applyCdcChanges,Ot as assertNoExplicitUndefined,$o as assertValidClientId,Ir as backfillAggregateIndexes,Cr as backfillRankIndexes,xr as backfillSearchIndexes,Lr as bumpCdcEpoch,kr as cdcCanVouchFor,Fr as cdcSeqLeavingRows,qr as cdcTouchesTables,Br as cdcTrimmedError,Wr as compactCdcDocs,Tr as createShardCtxDb,Ur as cursorBelowRetainedFloor,ei as deleteGlobalShapeSnapshot,ti as deleteGlobalShapeSnapshotsForConnection,Jr as migrateClientWatermark,ni as migrateGlobalShapeSnapshot,Pr as minCdcReplayableSeq,Gr as minCdcSeq,Pt as normalizeIdStructurally,Hr as readCdcChangeKeys,Or as readCdcChanges,Nr as readCdcCursor,jr as readCdcEpoch,Yr as readClientWatermark,oi as readGlobalShapeSnapshot,ci as readIdempotent,ui as runShardMigrations,pi as selectShapeMembers,gi as selectShapeRows,Kr as trimCdcChanges,ai as trimIdempotent,ri as writeGlobalShapeSnapshot,di as writeIdempotent};
@@ -1 +1 @@
1
- import{sql as s}from"drizzle-orm";import{matchesStaticWhere as f}from"./AGGREGATE_SQL_FUNCTION-m1iUU1rv.mjs";import{compareStrings as l}from"./aggregateTableName-C7o-gpms.mjs";import{serializeSqlValue as d}from"./serializeSqlValue-B_-zaEWZ.mjs";const a=Symbol("not-resolvable"),m=r=>{if(r!==null&&typeof r=="object"&&!Array.isArray(r)){const t=Object.keys(r);return t.length===1&&t[0]==="eq"?r.eq:a}return r},y=(r,t)=>{if(r.length===0)return"";const e={};for(const n of r.toSorted(l))e[n]=t[n]??null;return JSON.stringify(e)},k="__id__",N=r=>`__sort_k${String(r)}__`,h=(r,t)=>{const e=r.partitionBy??[],n=t??{};for(const o of Object.keys(n))if(o==="AND"||o==="OR"||o==="NOT")return;const i={};for(const o of e)if(o in n){const c=m(n[o]);if(c===a)return;i[o]=c}else if(r.where&&o in r.where)i[o]=r.where[o];else return;return i},O=(r,t)=>`${r}__rank_${t}`,$=(r,t)=>({partitionKey:y(r.partitionBy??[],t),rowId:t._id,sortValues:r.sortBy.map(e=>d(t[e.field]??null))}),K=(r,t,e,n)=>{const i=e!=="desc"===n;if(t==null)return i?s`${s.identifier(r)} IS NOT NULL`:void 0;const o=s`${s.identifier(r)} ${s.raw(i?">":"<")} ${t}`;return i?o:s`(${o} OR ${s.identifier(r)} IS NULL)`},R=f;export{k as RANK_TIEBREAK,y as encodePartitionKey,R as matchesRankStaticWhere,$ as rankKeyFromDoc,K as rankPivotConditionSql,O as rankTableName,h as resolveRankPartition,N as sortColumnName};
1
+ import{sql as s}from"drizzle-orm";import{matchesStaticWhere as f}from"./AGGREGATE_SQL_FUNCTION-DDEoMnJR.mjs";import{compareStrings as l}from"./aggregateTableName-C7o-gpms.mjs";import{serializeSqlValue as d}from"./serializeSqlValue-xohfS85H.mjs";const a=Symbol("not-resolvable"),m=r=>{if(r!==null&&typeof r=="object"&&!Array.isArray(r)){const t=Object.keys(r);return t.length===1&&t[0]==="eq"?r.eq:a}return r},y=(r,t)=>{if(r.length===0)return"";const e={};for(const n of r.toSorted(l))e[n]=t[n]??null;return JSON.stringify(e)},k="__id__",N=r=>`__sort_k${String(r)}__`,h=(r,t)=>{const e=r.partitionBy??[],n=t??{};for(const o of Object.keys(n))if(o==="AND"||o==="OR"||o==="NOT")return;const i={};for(const o of e)if(o in n){const c=m(n[o]);if(c===a)return;i[o]=c}else if(r.where&&o in r.where)i[o]=r.where[o];else return;return i},O=(r,t)=>`${r}__rank_${t}`,$=(r,t)=>({partitionKey:y(r.partitionBy??[],t),rowId:t._id,sortValues:r.sortBy.map(e=>d(t[e.field]??null))}),K=(r,t,e,n)=>{const i=e!=="desc"===n;if(t==null)return i?s`${s.identifier(r)} IS NOT NULL`:void 0;const o=s`${s.identifier(r)} ${s.raw(i?">":"<")} ${t}`;return i?o:s`(${o} OR ${s.identifier(r)} IS NULL)`},R=f;export{k as RANK_TIEBREAK,y as encodePartitionKey,R as matchesRankStaticWhere,$ as rankKeyFromDoc,K as rankPivotConditionSql,O as rankTableName,h as resolveRankPartition,N as sortColumnName};
@@ -0,0 +1 @@
1
+ import{LunoraError as y}from"@lunora/errors";const w=Symbol.for("lunora.ctxdb.rls-unwrap");class R extends y{table;constructor(n){super("RLS_REQUIRED",`ctx.db access to "${n}" 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=n}}const m=o=>Object.entries(o.tables).filter(([,n])=>n.shardMode?.kind!=="global").map(([n])=>n),M=(o,n,g)=>{const l=n?.tables,a=new Set(n?.exclude);for(const c of o)(l===void 0||l.includes(c))&&!a.has(c)&&g(c)},S={aggregate:"loop-gated",asId:"ungated",cdcChangedTables:"ungated",count:"loop-gated",delete:"id-gated",deleteAll:"loop-gated",deleteMany:"id-gated",deleteWhere:"inline-table-gated",findFirst:"loop-gated",findFirstOrThrow:"loop-gated",findMany:"loop-gated",get:"id-gated",groupBy:"loop-gated",insert:"loop-gated",insertMany:"loop-gated",insertManyUnsafe:"loop-gated",lookupById:"id-gated",normalizeId:"ungated",patch:"id-gated",patchMany:"id-gated",patchWhere:"inline-table-gated",query:"loop-gated",rank:"loop-gated",rankBefore:"loop-gated",rankPage:"loop-gated",rankPageRows:"loop-gated",replace:"id-gated",restore:"id-gated",system:"ungated",wipeShard:"sweep-gated"},W=Object.entries(S).filter(([,o])=>o==="loop-gated").map(([o])=>o),k=(o,n,g,l)=>{if(n.rlsMode!=="required")return o;const a=o,c=e=>{const t=n.tables[e];return t!==void 0&&t.isPublic!==!0},d=e=>{if(c(e))throw new R(e)},s=async(e,t)=>{if(t!==void 0){d(t);return}const r=await g(e);r!==void 0&&d(r)},p=async(e,t)=>{if(t!==void 0){d(t);return}if(!l){for(const i of e)await s(i,t);return}const r=await l([...new Set(e)],t);for(const i of e){const h=r.get(i);h!==void 0&&d(h)}},u={...o,delete:async(e,t,r)=>(await s(e,t),a.delete(e,t,r)),deleteMany:async(e,t,r)=>(await p(e,r),a.deleteMany(e,t,r)),deleteWhere:a.deleteWhere?async(e,t,r)=>(d(e),await a.deleteWhere?.(e,t,r)):void 0,get:async(e,t)=>(await s(e,t),a.get(e,t)),lookupById:async(e,t)=>(await s(e,t),a.lookupById?.(e,t)??null),patch:async(e,t,r)=>(await s(e,r),a.patch(e,t,r)),patchMany:async(e,t,r)=>(await p(e.map(i=>i.id),r),a.patchMany(e,t,r)),patchWhere:a.patchWhere?async(e,t,r)=>(d(e),await a.patchWhere?.(e,t,r)):void 0,replace:async(e,t,r,i)=>(await s(e,r),a.replace(e,t,r,i)),restore:async(e,t)=>(await s(e,t),a.restore?.(e,t))},f=a;for(const e of W){const t=f[e];typeof t=="function"&&(u[e]=(r,...i)=>(d(r),t.call(a,r,...i)))}if(a.wipeShard){const{wipeShard:e}=a;u.wipeShard=t=>(M(m(n),t,d),e.call(a,t))}return Object.defineProperty(u,w,{configurable:!0,enumerable:!1,value:o,writable:!1}),u};export{W as LOOP_GATED_METHODS,w as RLS_UNWRAP_SYMBOL,R as RlsRequiredError,S as WRITER_METHOD_GATING,k as guardWriter};
@@ -1 +1 @@
1
- import{stableWireKey as y}from"./stableWireKey-D2US4k_J.mjs";import{depKey as b,SCAN_DEP as p}from"./SCAN_DEP-D7qE3iUe.mjs";import{e as m}from"./estimate-bytes-DKqVDdZQ.mjs";import{keysTouchRanges as x}from"./buildIndexRange-CBKQmHSS.mjs";import{stableStringify as K}from"./stableStringify-DibjylKD.mjs";const l=(o,t,s)=>{let e=o.get(t);return e===void 0&&(e=s(),o.set(t,e)),e},v=1e3,E=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??v,this.maxBytes=t.maxBytes??E,this.now=t.now??(()=>(this.monotonic+=1,this.monotonic))}async run(t,s,e,i=()=>[]){const n=this.entries.get(t);if(n)return this.hits+=1,n.lastUsed=this.now(),this.entries.delete(t),this.entries.set(t,n),n.result;this.misses+=1;const c=this.generation,a=await e();if(this.generation!==c)return a;const h=m(a);if(h===void 0)return a;const f=i(),u={bytes:h,deps:s,ranges:f,lastUsed:this.now(),result:a,subscribers:new Set},d=this.entries.get(t);if(d){this.dropEntry(t,d);for(const r of d.subscribers)u.subscribers.add(r)}this.entries.set(t,u),this.totalBytes+=h;for(const r of s)l(this.tableIndex,r,()=>new Set).add(t);for(const r of f){const g=l(this.rangeIndex,r.table,()=>new Map);l(g,r,()=>new Set).add(t)}return this.evict(),a}invalidate(t,s,e){this.generation+=1;const i=[];return this.collectAndDrop(b(t,s),i),this.collectAndDrop(b(t,p),i),this.dropRangeDeps(t,e,i),i}invalidateTable(t){this.generation+=1;const s=[],e=`${t}:`;for(const i of this.tableIndex.keys())i.startsWith(e)&&this.collectAndDrop(i,s);return this.dropRangeDeps(t,void 0,s),s}subscribe(t,s){const e=this.entries.get(t);e&&e.subscribers.add(s)}unsubscribe(t,s){const e=this.entries.get(t);e&&e.subscribers.delete(s)}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 s=this.entries.get(t);return s?[...s.subscribers]:[]}stats(){return{bytes:this.totalBytes,entries:this.entries.size,evictions:this.evictions,hits:this.hits,misses:this.misses}}dropRangeDeps(t,s,e){const i=this.rangeIndex.get(t);if(!(!i||i.size===0))for(const[n,c]of i)x([n],s)&&this.dropKeys(c,e)}collectAndDrop(t,s){const e=this.tableIndex.get(t);e&&this.dropKeys(e,s)}dropKeys(t,s){for(const e of t){const i=this.entries.get(e);i&&(this.dropEntry(e,i),s.push(e))}}dropEntry(t,s){this.entries.delete(t),this.totalBytes-=s.bytes;for(const e of s.deps){const i=this.tableIndex.get(e);i&&(i.delete(t),i.size===0&&this.tableIndex.delete(e))}for(const e of s.ranges){const i=this.rangeIndex.get(e.table),n=i?.get(e);n?.delete(t),i&&n?.size===0&&(i.delete(e),i.size===0&&this.rangeIndex.delete(e.table))}}evict(){if(!(this.entries.size<=this.maxEntries&&this.totalBytes<=this.maxBytes))for(const[t,s]of this.entries){if(this.entries.size<=this.maxEntries&&this.totalBytes<=this.maxBytes)return;s.subscribers.size>0||(this.dropEntry(t,s),this.evictions+=1)}}}const D=(o,t,s)=>`${s??"\0anon"}\0${o}:${y(t)}`;export{A as ReactiveCache,D as reactiveCacheKey,K as stableStringify,y as stableWireKey};
1
+ import{stableWireKey as y}from"./stableWireKey-D2US4k_J.mjs";import{depKey as b,SCAN_DEP as p}from"./SCAN_DEP-D7qE3iUe.mjs";import{e as m}from"./estimate-bytes-DCVD8-i6.mjs";import{keysTouchRanges as x}from"./buildIndexRange-CBKQmHSS.mjs";import{stableStringify as K}from"./stableStringify-DibjylKD.mjs";const l=(o,t,s)=>{let e=o.get(t);return e===void 0&&(e=s(),o.set(t,e)),e},v=1e3,E=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??v,this.maxBytes=t.maxBytes??E,this.now=t.now??(()=>(this.monotonic+=1,this.monotonic))}async run(t,s,e,i=()=>[]){const n=this.entries.get(t);if(n)return this.hits+=1,n.lastUsed=this.now(),this.entries.delete(t),this.entries.set(t,n),n.result;this.misses+=1;const c=this.generation,a=await e();if(this.generation!==c)return a;const h=m(a);if(h===void 0)return a;const f=i(),u={bytes:h,deps:s,ranges:f,lastUsed:this.now(),result:a,subscribers:new Set},d=this.entries.get(t);if(d){this.dropEntry(t,d);for(const r of d.subscribers)u.subscribers.add(r)}this.entries.set(t,u),this.totalBytes+=h;for(const r of s)l(this.tableIndex,r,()=>new Set).add(t);for(const r of f){const g=l(this.rangeIndex,r.table,()=>new Map);l(g,r,()=>new Set).add(t)}return this.evict(),a}invalidate(t,s,e){this.generation+=1;const i=[];return this.collectAndDrop(b(t,s),i),this.collectAndDrop(b(t,p),i),this.dropRangeDeps(t,e,i),i}invalidateTable(t){this.generation+=1;const s=[],e=`${t}:`;for(const i of this.tableIndex.keys())i.startsWith(e)&&this.collectAndDrop(i,s);return this.dropRangeDeps(t,void 0,s),s}subscribe(t,s){const e=this.entries.get(t);e&&e.subscribers.add(s)}unsubscribe(t,s){const e=this.entries.get(t);e&&e.subscribers.delete(s)}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 s=this.entries.get(t);return s?[...s.subscribers]:[]}stats(){return{bytes:this.totalBytes,entries:this.entries.size,evictions:this.evictions,hits:this.hits,misses:this.misses}}dropRangeDeps(t,s,e){const i=this.rangeIndex.get(t);if(!(!i||i.size===0))for(const[n,c]of i)x([n],s)&&this.dropKeys(c,e)}collectAndDrop(t,s){const e=this.tableIndex.get(t);e&&this.dropKeys(e,s)}dropKeys(t,s){for(const e of t){const i=this.entries.get(e);i&&(this.dropEntry(e,i),s.push(e))}}dropEntry(t,s){this.entries.delete(t),this.totalBytes-=s.bytes;for(const e of s.deps){const i=this.tableIndex.get(e);i&&(i.delete(t),i.size===0&&this.tableIndex.delete(e))}for(const e of s.ranges){const i=this.rangeIndex.get(e.table),n=i?.get(e);n?.delete(t),i&&n?.size===0&&(i.delete(e),i.size===0&&this.rangeIndex.delete(e.table))}}evict(){if(!(this.entries.size<=this.maxEntries&&this.totalBytes<=this.maxBytes))for(const[t,s]of this.entries){if(this.entries.size<=this.maxEntries&&this.totalBytes<=this.maxBytes)return;s.subscribers.size>0||(this.dropEntry(t,s),this.evictions+=1)}}}const D=(o,t,s)=>`${s??"\0anon"}\0${o}:${y(t)}`;export{A as ReactiveCache,D as reactiveCacheKey,K as stableStringify,y as stableWireKey};
@@ -1 +1 @@
1
- import{LunoraError as D}from"@lunora/errors";import{applySelect as I}from"./CURSOR_PREFIX-qn6nNVS7.mjs";const W=Symbol.for("lunora.relations.fanOutBudget"),U=o=>({fanOutBudget:o[W],relationBaseWhere:o.relationBaseWhere,relationMask:o.relationMask}),A=(o,n)=>n.select?I(o,n.select,n.with):o,x=async(o,n,r,a,t)=>{const l=await Promise.all(a.map(async i=>{const h=t?{AND:[{[r]:i},t]}:{[r]:i};return[i,await o(n,h)]}));return new Map(l)},S=32,C=(o,n,r)=>{const a=new Map;for(const t of o)for(const l of r(t)){const i=l[n],h=a.get(i);h?h.push(l):a.set(i,[l])}return a},_=(o,n)=>({...o,[W]:n}),B=(o,n)=>{const r=new Set;for(const a of o){const t=a[n];t!=null&&r.add(t)}return[...r]},H=async o=>{const{groupedCounter:n,fanOutBudget:r,fetcher:a,parents:t,relationBaseWhere:l,relationMask:i,schema:h,tableName:m,with:v}=o,w=r??{remaining:S},k=(c,e)=>i?.(c,e)??e;if(t.length===0)return;const N=h.tables[m];if(!N)throw new D("INTERNAL",`unknown table: ${m}`);const O=N.relationMap??{},R=c=>{const e=O[c];if(!e)throw new D("INTERNAL",`unknown relation "${c}" on table "${m}"`);return e},V=async(c,e,s)=>{const u=B(t,e.field);if(u.length===0){for(const d of t)d[c]=null;return}const{page:p}=await a(e.table,_({baseWhere:l?.(e.table),relationBaseWhere:l,relationMask:i,where:{[e.references]:{in:u}},with:s.with},w)),b=new Map;for(const d of k(e.table,p))b.set(d[e.references],d);for(const d of t){const y=b.get(d[e.field]);d[c]=y?A([y],s)[0]??null:null}},$=async(c,e,s)=>{const u=B(t,e.references);if(u.length===0){for(const f of t)f[c]=[];return}const p=typeof s.limit=="number"?Math.max(0,Math.floor(s.limit)):void 0,b=async(f,g)=>{const{page:E}=await a(e.table,_({baseWhere:l?.(e.table),limit:g,orderBy:s.orderBy,relationBaseWhere:l,relationMask:i,where:s.where?{AND:[s.where,f]}:f,with:s.with},w));return E};if(p===0){for(const f of t)f[c]=[];return}const d=p!==void 0&&u.length<=w.remaining;d&&(w.remaining-=u.length);const y=d?await Promise.all(u.map(async f=>b({[e.field]:f},p))):[await b({[e.field]:{in:u}},void 0)],M=C(y,e.field,f=>k(e.table,f));for(const f of t){const g=M.get(f[e.references])??[];f[c]=A(p===void 0?g:g.slice(0,p),s)}},j=async c=>{for(const e of Object.keys(c)){const s=R(e),[u,p]=s.kind==="many"?[s.field,s.references]:[s.references,s.field],b=l?.(s.table),d=B(t,p),y=d.length===0?new Map:await n(s.table,u,d,b);for(const M of t){const f=M._count??{},g=M[p];f[e]=g==null?0:y.get(g)??0,M._count=f}}};for(const[c,e]of Object.entries(v)){if(e===void 0||e===!1)continue;if(c==="_count"){await j(e);continue}const s=R(c),u=e===!0?{}:e;await(s.kind==="one"?V(c,s,u):$(c,s,u))}},F=async(o,n,r)=>{const{deletedId:a,deletedReference:t,findHolders:l,onCascade:i,onRestrict:h,onSetNull:m,tableName:v}=o,w=r.references==="_id"?a:t(r.references);if(w==null)return;const k=await l(n,r.field,w);if(k.length!==0){r.onDelete==="restrict"&&h(`cannot delete "${v}" row: "${n}.${r.field}" still references it`);for(const N of k){const O=N._id;typeof O=="string"&&await(r.onDelete==="cascade"?i(n,O):m(n,O,r.field))}}},P=async o=>{const{schema:n,tableName:r}=o;if(!n.tables[r])throw new D("INTERNAL",`unknown table: ${r}`);for(const[a,t]of Object.entries(n.tables)){const l=t.relationMap;if(l)for(const i of Object.values(l))i.kind!=="one"||i.table!==r||!i.onDelete||await F(o,a,i)}},q=(o,n,r=!1)=>{for(const[a,t]of Object.entries(o.shape))a in n&&typeof t.parse=="function"&&(r&&n[a]===null&&t.kind==="optional"||t.parse(n[a]))};export{P as applyOnDelete,B as distinctValues,x as fanOutScalarCounts,U as relationHooks,H as resolveWith,q as runRowValidators};
1
+ import{LunoraError as D}from"@lunora/errors";import{applySelect as I}from"./CURSOR_PREFIX-Bn8SFoGd.mjs";const W=Symbol.for("lunora.relations.fanOutBudget"),U=o=>({fanOutBudget:o[W],relationBaseWhere:o.relationBaseWhere,relationMask:o.relationMask}),A=(o,n)=>n.select?I(o,n.select,n.with):o,x=async(o,n,r,a,t)=>{const l=await Promise.all(a.map(async i=>{const h=t?{AND:[{[r]:i},t]}:{[r]:i};return[i,await o(n,h)]}));return new Map(l)},S=32,C=(o,n,r)=>{const a=new Map;for(const t of o)for(const l of r(t)){const i=l[n],h=a.get(i);h?h.push(l):a.set(i,[l])}return a},_=(o,n)=>({...o,[W]:n}),B=(o,n)=>{const r=new Set;for(const a of o){const t=a[n];t!=null&&r.add(t)}return[...r]},H=async o=>{const{groupedCounter:n,fanOutBudget:r,fetcher:a,parents:t,relationBaseWhere:l,relationMask:i,schema:h,tableName:m,with:v}=o,w=r??{remaining:S},k=(c,e)=>i?.(c,e)??e;if(t.length===0)return;const N=h.tables[m];if(!N)throw new D("INTERNAL",`unknown table: ${m}`);const O=N.relationMap??{},R=c=>{const e=O[c];if(!e)throw new D("INTERNAL",`unknown relation "${c}" on table "${m}"`);return e},V=async(c,e,s)=>{const u=B(t,e.field);if(u.length===0){for(const d of t)d[c]=null;return}const{page:p}=await a(e.table,_({baseWhere:l?.(e.table),relationBaseWhere:l,relationMask:i,where:{[e.references]:{in:u}},with:s.with},w)),b=new Map;for(const d of k(e.table,p))b.set(d[e.references],d);for(const d of t){const y=b.get(d[e.field]);d[c]=y?A([y],s)[0]??null:null}},$=async(c,e,s)=>{const u=B(t,e.references);if(u.length===0){for(const f of t)f[c]=[];return}const p=typeof s.limit=="number"?Math.max(0,Math.floor(s.limit)):void 0,b=async(f,g)=>{const{page:E}=await a(e.table,_({baseWhere:l?.(e.table),limit:g,orderBy:s.orderBy,relationBaseWhere:l,relationMask:i,where:s.where?{AND:[s.where,f]}:f,with:s.with},w));return E};if(p===0){for(const f of t)f[c]=[];return}const d=p!==void 0&&u.length<=w.remaining;d&&(w.remaining-=u.length);const y=d?await Promise.all(u.map(async f=>b({[e.field]:f},p))):[await b({[e.field]:{in:u}},void 0)],M=C(y,e.field,f=>k(e.table,f));for(const f of t){const g=M.get(f[e.references])??[];f[c]=A(p===void 0?g:g.slice(0,p),s)}},j=async c=>{for(const e of Object.keys(c)){const s=R(e),[u,p]=s.kind==="many"?[s.field,s.references]:[s.references,s.field],b=l?.(s.table),d=B(t,p),y=d.length===0?new Map:await n(s.table,u,d,b);for(const M of t){const f=M._count??{},g=M[p];f[e]=g==null?0:y.get(g)??0,M._count=f}}};for(const[c,e]of Object.entries(v)){if(e===void 0||e===!1)continue;if(c==="_count"){await j(e);continue}const s=R(c),u=e===!0?{}:e;await(s.kind==="one"?V(c,s,u):$(c,s,u))}},F=async(o,n,r)=>{const{deletedId:a,deletedReference:t,findHolders:l,onCascade:i,onRestrict:h,onSetNull:m,tableName:v}=o,w=r.references==="_id"?a:t(r.references);if(w==null)return;const k=await l(n,r.field,w);if(k.length!==0){r.onDelete==="restrict"&&h(`cannot delete "${v}" row: "${n}.${r.field}" still references it`);for(const N of k){const O=N._id;typeof O=="string"&&await(r.onDelete==="cascade"?i(n,O):m(n,O,r.field))}}},P=async o=>{const{schema:n,tableName:r}=o;if(!n.tables[r])throw new D("INTERNAL",`unknown table: ${r}`);for(const[a,t]of Object.entries(n.tables)){const l=t.relationMap;if(l)for(const i of Object.values(l))i.kind!=="one"||i.table!==r||!i.onDelete||await F(o,a,i)}},q=(o,n,r=!1)=>{for(const[a,t]of Object.entries(o.shape))a in n&&typeof t.parse=="function"&&(r&&n[a]===null&&t.kind==="optional"||t.parse(n[a]))};export{P as applyOnDelete,B as distinctValues,x as fanOutScalarCounts,U as relationHooks,H as resolveWith,q as runRowValidators};
@@ -1 +1 @@
1
- import{m as O,c as T,l as b,r as E,a as C,w as L}from"./ctx-db-search-state-ruTuCsxa.mjs";import{S as R,r as M,i as x,l as h,y as _,d as y}from"./ctx-db-companions-B4O4d95S.mjs";import{sql as t}from"drizzle-orm";import{matchesStaticWhere as F}from"./AGGREGATE_SQL_FUNCTION-m1iUU1rv.mjs";import{aggregateTableName as N,encodeAggregateKey as D,foldAggregateTally as v}from"./aggregateTableName-C7o-gpms.mjs";import{runDrizzle as l}from"./runDrizzle-2ULFQR_k.mjs";import{i as w,r as p,a as B,b as G,A as U,D as I,h as H}from"./do-sql-FNOnpyHm.mjs";import{isLiveForCompanion as P}from"./CURSOR_PREFIX-qn6nNVS7.mjs";import{rankTableName as W,matchesRankStaticWhere as V}from"./RANK_TIEBREAK-CkNuGm6a.mjs";const 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=N(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=p(d);if(!f||!P(f,r)||n.where&&!F(f,n.where))continue;const g=D(c,f);v(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=M(n),c=A(e,o);for(const a of c){const s=p(a);!s||n.where&&!V(s,n.where)||x(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)},u=500,$=(e,o,n)=>{const r=R(o,n.name),i=T(n),c=b(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(u))}`:t`SELECT id, _creationTime, ${t.identifier(I)} FROM ${t.identifier(o)} WHERE id > ${a} ORDER BY id ASC LIMIT ${t.raw(String(u))}`).toArray();let d=a;for(const g of s){const{id:m}=g;if(typeof m!="string")continue;d=m,l(e,t`DELETE FROM ${t.identifier(r)} WHERE ${t.identifier(h)} = ${m}`);const S=H(g);S&&l(e,t`INSERT INTO ${t.identifier(r)} (${t.identifier(_)}, ${t.identifier(h)}) VALUES (${y(S,n)}, ${m})`)}const f=s.length<u;return L(e,r,d,f,i),{done:f,rows:s.length}},ae=(e,o,n)=>{const r=R(o,n.name),i=T(n);return b(E(e,r),i).finished?!0:C(e,r)},se=(e,o,n)=>{if(w(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(!w(e))return{done:!0,pages:0};O(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
+ import{m as O,c as T,l as b,r as E,a as C,w as L}from"./ctx-db-search-state-ruTuCsxa.mjs";import{S as R,r as M,i as x,l as h,y as _,d as y}from"./ctx-db-companions-kHoblDbS.mjs";import{sql as t}from"drizzle-orm";import{matchesStaticWhere as F}from"./AGGREGATE_SQL_FUNCTION-DDEoMnJR.mjs";import{aggregateTableName as N,encodeAggregateKey as D,foldAggregateTally as v}from"./aggregateTableName-C7o-gpms.mjs";import{runDrizzle as l}from"./runDrizzle-2ULFQR_k.mjs";import{i as w,r as p,a as B,b as G,A as U,D as I,h as H}from"./do-sql-ByyZb9U0.mjs";import{isLiveForCompanion as P}from"./CURSOR_PREFIX-Bn8SFoGd.mjs";import{rankTableName as W,matchesRankStaticWhere as V}from"./RANK_TIEBREAK-3pXm7Ng_.mjs";const 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=N(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=p(d);if(!f||!P(f,r)||n.where&&!F(f,n.where))continue;const g=D(c,f);v(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=M(n),c=A(e,o);for(const a of c){const s=p(a);!s||n.where&&!V(s,n.where)||x(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)},u=500,$=(e,o,n)=>{const r=R(o,n.name),i=T(n),c=b(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(u))}`:t`SELECT id, _creationTime, ${t.identifier(I)} FROM ${t.identifier(o)} WHERE id > ${a} ORDER BY id ASC LIMIT ${t.raw(String(u))}`).toArray();let d=a;for(const g of s){const{id:m}=g;if(typeof m!="string")continue;d=m,l(e,t`DELETE FROM ${t.identifier(r)} WHERE ${t.identifier(h)} = ${m}`);const S=H(g);S&&l(e,t`INSERT INTO ${t.identifier(r)} (${t.identifier(_)}, ${t.identifier(h)}) VALUES (${y(S,n)}, ${m})`)}const f=s.length<u;return L(e,r,d,f,i),{done:f,rows:s.length}},ae=(e,o,n)=>{const r=R(o,n.name),i=T(n);return b(E(e,r),i).finished?!0:C(e,r)},se=(e,o,n)=>{if(w(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(!w(e))return{done:!0,pages:0};O(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};
@@ -0,0 +1 @@
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-C-FpWm52.mjs";import{runSql as p}from"./runDrizzle-2ULFQR_k.mjs";import{k as d,D as E}from"./do-sql-ByyZb9U0.mjs";import{m as g}from"./sql-projection-DML1_ex4.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 +1 @@
1
- import{readCdcChangeKeys as s}from"./CDC_LOG_TABLE-CAyqu8cg.mjs";import{selectShapeMembers as h}from"./selectShapeMembers-DqikYFjS.mjs";import{shapeRangeKey as u}from"./ShapeDiffCache-gdaILV5E.mjs";import{projectColumns as g}from"./buildPokeFrames-BBE6J91z.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-B-SKH98h.mjs";import{selectShapeMembers as h}from"./selectShapeMembers-OatGcYrk.mjs";import{shapeRangeKey as u}from"./ShapeDiffCache-gdaILV5E.mjs";import{projectColumns as g}from"./buildPokeFrames-BBE6J91z.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 +1 @@
1
- import"./param-DlozcSQu.mjs";import{c as o,l as t}from"./where-sql-B1l5NcUZ.mjs";import"./RELATION_EXISTS_KEY-CFUhnZSZ.mjs";export{o as compileWhereSql,t as literalInList};
1
+ import"./param-DlozcSQu.mjs";import{c as o,l as t}from"./where-sql-x1YKldcq.mjs";import"./RELATION_EXISTS_KEY-CFUhnZSZ.mjs";export{o as compileWhereSql,t as literalInList};
@@ -1 +1 @@
1
- import{LunoraError as g}from"@lunora/errors";import{sql as o}from"drizzle-orm";import{mergeWhere as b}from"./CountRlsUnsupportedError-Bdfupt3g.mjs";import{SCAN_DEP as j}from"./SCAN_DEP-D7qE3iUe.mjs";import{runDrizzle as A}from"./runDrizzle-2ULFQR_k.mjs";import{sqliteInList as O}from"./param-DlozcSQu.mjs";import{decodeCursor as F,CURSOR_PREFIX as P,toBase64 as U}from"./CURSOR_PREFIX-qn6nNVS7.mjs";import{rankTableName as V,sortColumnName as z,resolveRankPartition as H,RANK_TIEBREAK as _,encodePartitionKey as J,rankPivotConditionSql as X}from"./RANK_TIEBREAK-CkNuGm6a.mjs";const Y="__doc__",G=n=>P+U(JSON.stringify(n)),Q=n=>n.after?[n.after.partitionKey,...n.after.sortValues,n.after.rowId]:n.cursor?F(n.cursor):void 0,Z=(n,r,f)=>{if(n?.length!==1+r.length+1)return;const t=[{column:"__partition__",direction:"asc"}];for(const[c,u]of r.entries())t.push({column:u,direction:f[c]?.direction??"asc"});t.push({column:_,direction:"asc"});const e=[];for(const[c,u]of t.entries()){const d=X(u.column,n[c],u.direction,!0);if(d===void 0)continue;const s=[];for(const[m,l]of t.slice(0,c).entries())s.push(o`${o.identifier(l.column)} IS ${n[m]}`);s.push(d);const[i]=s;e.push(s.length===1&&i!==void 0?i:o`(${o.join(s,o` AND `)})`)}return e.length===0?o`(1 = 0)`:o`(${o.join(e,o` OR `)})`},v=null,oo=(n,r)=>{if(n===void 0)return v;const f=[n.__partition__,...r.map(t=>n[t]),n[_]];return G(f)},no=(n,r,f)=>{const t=[];for(const e of n){const c=e[_];if(typeof c!="string")continue;const u=r.get(c);if(!u)continue;const d=typeof e.__partition__=="string"?e.__partition__:"",s=f.map(i=>e[i]??null);t.push({doc:u,key:{partitionKey:d,rowId:c,sortValues:s}})}return t},to=o`${o.identifier("id")}`,ro=(n,r,f)=>{const{rowToDocument:t}=n,e=new Map;if(f.length===0)return e;const c=A(n.sql,o`SELECT id, _creationTime, ${o.identifier(Y)} FROM ${o.identifier(r)} WHERE ${O(to,f,!1)}`).toArray();for(const u of c){const d=t(u),s=u.id;d&&typeof s=="string"&&e.set(s,d)}return e},_o=(n,r,f,t)=>{const{assertRankPartitionLocal:e,ensureRankBackfilled:c,onRead:u,schema:d}=n,s=d.tables[r];if(!s)throw new g("INTERNAL",`unknown table: ${r}`);const i=s.rankIndexes?.find(a=>a.name===f);if(!i)throw new g("INTERNAL",`unknown rankIndex "${f}" on table "${r}"`);e(r,s,i),u(r,j),c(r,i);const m=V(r,i.name),l=i.sortBy.map((a,w)=>z(w)),h=Math.max(1,Math.min(1e3,Math.floor(t.take??100))),T=b(t.baseWhere,t.where),k=H(i,T),R=[o`${o.identifier("__partition__")} ASC`];for(const[a,w]of l.entries()){const W=i.sortBy[a]?.direction;R.push(o`${o.identifier(w)} ${o.raw(W==="desc"?"DESC":"ASC")}`)}R.push(o`${o.identifier(_)} ASC`);const p=[];typeof t.partitionKey=="string"?p.push(o`${o.identifier("__partition__")} = ${t.partitionKey}`):k&&p.push(o`${o.identifier("__partition__")} = ${J(i.partitionBy??[],k)}`);const B=Q(t),E=Z(B,l,i.sortBy);E&&p.push(E);const I=o.identifier(_),S=o.identifier("__partition__"),D=p.length>0?o` WHERE ${o.join(p,o` AND `)}`:o``,L=l.length>0?o`${I}, ${S}, ${o.join(l.map(a=>o.identifier(a)),o`, `)}`:o`${I}, ${S}`,M=o`SELECT ${L} FROM ${o.identifier(m)}${D} ORDER BY ${o.join(R,o`, `)} LIMIT ${o.raw(String(h+1))}`,$=A(n.sql,M).toArray(),C=$.length>h,y=C?$.slice(0,h):$,K=y.map(a=>a[_]),q=no(y,ro(n,r,K),l),x=C?oo(y.at(-1),l):v,N=i.sortBy.map(a=>a.direction==="desc"?"desc":"asc");return{continueCursor:x,directions:N,hasMore:C,rows:q}};export{_o as computeRankPage,Q as resolveRankSeekTuple};
1
+ import{LunoraError as g}from"@lunora/errors";import{sql as o}from"drizzle-orm";import{mergeWhere as b}from"./CountRlsUnsupportedError-BvsDqfO2.mjs";import{SCAN_DEP as j}from"./SCAN_DEP-D7qE3iUe.mjs";import{runDrizzle as A}from"./runDrizzle-2ULFQR_k.mjs";import{sqliteInList as O}from"./param-DlozcSQu.mjs";import{decodeCursor as F,CURSOR_PREFIX as P,toBase64 as U}from"./CURSOR_PREFIX-Bn8SFoGd.mjs";import{rankTableName as V,sortColumnName as z,resolveRankPartition as H,RANK_TIEBREAK as _,encodePartitionKey as J,rankPivotConditionSql as X}from"./RANK_TIEBREAK-3pXm7Ng_.mjs";const Y="__doc__",G=n=>P+U(JSON.stringify(n)),Q=n=>n.after?[n.after.partitionKey,...n.after.sortValues,n.after.rowId]:n.cursor?F(n.cursor):void 0,Z=(n,r,f)=>{if(n?.length!==1+r.length+1)return;const t=[{column:"__partition__",direction:"asc"}];for(const[c,u]of r.entries())t.push({column:u,direction:f[c]?.direction??"asc"});t.push({column:_,direction:"asc"});const e=[];for(const[c,u]of t.entries()){const d=X(u.column,n[c],u.direction,!0);if(d===void 0)continue;const s=[];for(const[m,l]of t.slice(0,c).entries())s.push(o`${o.identifier(l.column)} IS ${n[m]}`);s.push(d);const[i]=s;e.push(s.length===1&&i!==void 0?i:o`(${o.join(s,o` AND `)})`)}return e.length===0?o`(1 = 0)`:o`(${o.join(e,o` OR `)})`},v=null,oo=(n,r)=>{if(n===void 0)return v;const f=[n.__partition__,...r.map(t=>n[t]),n[_]];return G(f)},no=(n,r,f)=>{const t=[];for(const e of n){const c=e[_];if(typeof c!="string")continue;const u=r.get(c);if(!u)continue;const d=typeof e.__partition__=="string"?e.__partition__:"",s=f.map(i=>e[i]??null);t.push({doc:u,key:{partitionKey:d,rowId:c,sortValues:s}})}return t},to=o`${o.identifier("id")}`,ro=(n,r,f)=>{const{rowToDocument:t}=n,e=new Map;if(f.length===0)return e;const c=A(n.sql,o`SELECT id, _creationTime, ${o.identifier(Y)} FROM ${o.identifier(r)} WHERE ${O(to,f,!1)}`).toArray();for(const u of c){const d=t(u),s=u.id;d&&typeof s=="string"&&e.set(s,d)}return e},_o=(n,r,f,t)=>{const{assertRankPartitionLocal:e,ensureRankBackfilled:c,onRead:u,schema:d}=n,s=d.tables[r];if(!s)throw new g("INTERNAL",`unknown table: ${r}`);const i=s.rankIndexes?.find(a=>a.name===f);if(!i)throw new g("INTERNAL",`unknown rankIndex "${f}" on table "${r}"`);e(r,s,i),u(r,j),c(r,i);const m=V(r,i.name),l=i.sortBy.map((a,w)=>z(w)),h=Math.max(1,Math.min(1e3,Math.floor(t.take??100))),T=b(t.baseWhere,t.where),k=H(i,T),R=[o`${o.identifier("__partition__")} ASC`];for(const[a,w]of l.entries()){const W=i.sortBy[a]?.direction;R.push(o`${o.identifier(w)} ${o.raw(W==="desc"?"DESC":"ASC")}`)}R.push(o`${o.identifier(_)} ASC`);const p=[];typeof t.partitionKey=="string"?p.push(o`${o.identifier("__partition__")} = ${t.partitionKey}`):k&&p.push(o`${o.identifier("__partition__")} = ${J(i.partitionBy??[],k)}`);const B=Q(t),E=Z(B,l,i.sortBy);E&&p.push(E);const I=o.identifier(_),S=o.identifier("__partition__"),D=p.length>0?o` WHERE ${o.join(p,o` AND `)}`:o``,L=l.length>0?o`${I}, ${S}, ${o.join(l.map(a=>o.identifier(a)),o`, `)}`:o`${I}, ${S}`,M=o`SELECT ${L} FROM ${o.identifier(m)}${D} ORDER BY ${o.join(R,o`, `)} LIMIT ${o.raw(String(h+1))}`,$=A(n.sql,M).toArray(),C=$.length>h,y=C?$.slice(0,h):$,K=y.map(a=>a[_]),q=no(y,ro(n,r,K),l),x=C?oo(y.at(-1),l):v,N=i.sortBy.map(a=>a.direction==="desc"?"desc":"asc");return{continueCursor:x,directions:N,hasMore:C,rows:q}};export{_o as computeRankPage,Q as resolveRankSeekTuple};
@@ -0,0 +1 @@
1
+ import{c as l,i as C,r as R}from"./ctx-db-companions-kHoblDbS.mjs";import"./AGGREGATE_SQL_FUNCTION-DDEoMnJR.mjs";import"./aggregateTableName-C7o-gpms.mjs";import"./runDrizzle-2ULFQR_k.mjs";import"./do-sql-ByyZb9U0.mjs";import"./param-DlozcSQu.mjs";import"./GEO_DEFAULT_PRECISION-CqpQZ-J_.mjs";import"./CURSOR_PREFIX-Bn8SFoGd.mjs";import"./RANK_TIEBREAK-3pXm7Ng_.mjs";import"./sql-projection-DML1_ex4.mjs";import"./serializeSqlValue-xohfS85H.mjs";export{l as createCompanionSync,C as insertRankRow,R as rankColumnsSql};
@@ -1,7 +1,7 @@
1
- import{d as u,e as S}from"./wire-codec-C-FpWm52.mjs";import{cursorBelowRetainedFloor as y}from"./CDC_LOG_TABLE-CAyqu8cg.mjs";import{envPositiveInt as v}from"./envOptionalPositiveInt-D2pY-c64.mjs";import{v as A,R as g,s as N,a as E,b as T}from"./sibling-channel-Cxvk0Zca.mjs";const L=["wnam","enam","sam","weur","eeur","apac","apac-ne","apac-se","oc","afr","me"],O=new Set(L),b=s=>typeof s=="string"&&O.has(s),l="::replica::",R=s=>{const e=s.lastIndexOf(l);if(e===-1)return;const t=s.slice(0,e),r=s.slice(e+l.length);if(!(t.length===0||!b(r)))return{ownerKey:t,region:r}},I=s=>{if(s==null||!/^\d+$/.test(s))return;const e=Number.parseInt(s,10);return Number.isSafeInteger(e)&&e>0?e:void 0},m=1e3,w=1e3,C=10,F=5e4,U=s=>v(s,"LUNORA_REPLICA_MAX_BOOTSTRAP_ROWS",F),d="__replica_state",h=new WeakSet,_=s=>{h.has(s)||(s.exec(`CREATE TABLE IF NOT EXISTS ${d} (
1
+ import{d as u,e as S}from"./wire-codec-C-FpWm52.mjs";import{cursorBelowRetainedFloor as y}from"./CDC_LOG_TABLE-B-SKH98h.mjs";import{envPositiveInt as v}from"./envOptionalPositiveInt-D2pY-c64.mjs";import{v as A,R as g,s as N,a as E,b as T}from"./sibling-channel-BkL5cTCc.mjs";const L=["wnam","enam","sam","weur","eeur","apac","apac-ne","apac-se","oc","afr","me"],O=new Set(L),b=s=>typeof s=="string"&&O.has(s),h="::replica::",R=s=>{const e=s.lastIndexOf(h);if(e===-1)return;const t=s.slice(0,e),r=s.slice(e+h.length);if(!(t.length===0||!b(r)))return{ownerKey:t,region:r}},I=s=>{if(s==null||!/^\d+$/.test(s))return;const e=Number.parseInt(s,10);return Number.isSafeInteger(e)&&e>0?e:void 0},m=1e3,w=1e3,C=10,F=5e4,U=s=>v(s,"LUNORA_REPLICA_MAX_BOOTSTRAP_ROWS",F),d="__replica_state",l=new WeakSet,_=s=>{l.has(s)||(s.exec(`CREATE TABLE IF NOT EXISTS ${d} (
2
2
  id INTEGER PRIMARY KEY CHECK (id = 1),
3
3
  epoch TEXT NOT NULL,
4
4
  applied_seq INTEGER NOT NULL,
5
5
  synced_at REAL NOT NULL
6
- )`),h.add(s))},c=s=>(_(s),s.exec(`SELECT epoch, applied_seq AS appliedSeq, synced_at AS syncedAtMs FROM ${d} WHERE id = 1`).toArray()[0]),f=(s,e)=>{_(s),s.exec(`INSERT INTO ${d} (id, epoch, applied_seq, synced_at) VALUES (1, ?, ?, ?)
7
- ON CONFLICT(id) DO UPDATE SET epoch = excluded.epoch, applied_seq = excluded.applied_seq, synced_at = excluded.synced_at`,e.epoch,e.appliedSeq,e.syncedAtMs)},q=s=>{const e=s.doName();if(e!==void 0&&R(e)!==void 0)return new Response("replica cannot serve replicas",{status:409});if(s.ownerEpoch()===void 0)return new Response("shard has no changelog to replicate",{status:409});if(E(s.env())===void 0)return new Response("replica control requires LUNORA_RELAY_SECRET",{status:403})},a=s=>Response.json(S(s)),P=async(s,e)=>{if(s.rowCount()>U(s.env()))return a({cursor:0,epoch:e,rows:[],truncated:!0});const t=s.ownerCursor()??0,r=await s.exportRows();return a({cursor:t,epoch:e,rows:r})},x=(s,e,t)=>{const r=s.ownerFloor();if(y(r,t))return a({changes:[],cursor:s.ownerCursor()??t,epoch:e,floor:r});const{changes:o,cursor:n}=s.readChanges(t,w);return a({changes:o,cursor:n,epoch:e,...r===void 0?{}:{floor:r}})},K=async(s,e)=>{const t=q(s);if(t!==void 0)return t;const r=s.ownerEpoch();let o;try{o=await e.text()}catch{return new Response("bad request",{status:400})}if(!await A(s.env(),e.headers.get(g),o))return new Response("forbidden",{status:403});let n;try{n=JSON.parse(o)}catch{return new Response("bad request",{status:400})}if(n.type==="replica_bootstrap")return P(s,r);if(n.type==="replica_pull"){const i=typeof n.sinceSeq=="number"&&Number.isInteger(n.sinceSeq)&&n.sinceSeq>=0?n.sinceSeq:0;return x(s,r,i)}return new Response("unknown replica frame",{status:400})};class M{constructor(e,t,r){this.host=e,this.ownerKey=t,this.region=r}host;ownerKey;region;divergent=!1;inFlight;async ensureFresh(e){if(this.divergent)return"unavailable";if(this.isCaughtUp(e))return"fresh";this.inFlight??=this.advance(e).finally(()=>{this.inFlight=void 0});const t=await this.inFlight;return t==="fresh"&&!this.isCaughtUp(e)?"stale":t}appliedSeq(){return c(this.host.sql())?.appliedSeq??0}isDivergent(){return this.divergent}async advance(e){let t=c(this.host.sql());if(t===void 0){const r=await this.bootstrap();if(r===void 0)return"unavailable";t=r}return this.catchUp(t,e)}isCaughtUp(e){const t=c(this.host.sql());return t!==void 0&&this.isFreshEnough(t,e)}async catchUp(e,t){let r=e;for(let o=0;o<C;o+=1){const n=await this.pull(r.appliedSeq);if(n===void 0)return t===void 0&&this.isFreshEnough(r,void 0)?"fresh":"unavailable";if(this.hasDiverged(r,n))return"unavailable";const i=n.changes.length<w;if(r=await this.applyPage(n),i||this.isFreshEnough(r,t))return this.isFreshEnough(r,t)?"fresh":"stale"}return this.isFreshEnough(r,t)?"fresh":"stale"}async applyPage(e){e.changes.length>0&&await this.host.applyChanges(e.changes);const t={appliedSeq:e.cursor,epoch:e.epoch,syncedAtMs:Date.now()};return f(this.host.sql(),t),t}hasDiverged(e,t){const r=t.changes.length===0&&t.cursor>e.appliedSeq,o=t.floor??(r?t.cursor:0),n=o>0&&o>e.appliedSeq+1;return t.epoch===e.epoch&&!n?!1:(this.divergent=!0,!0)}async bootstrap(){const e=await this.request({type:"replica_bootstrap"});if(e===void 0)return;const t=u(await e.json());if(t.truncated===!0){this.divergent=!0;return}const{errors:r}=await this.host.importRows(t.rows);if(r.length>0){this.divergent=!0;return}const o={appliedSeq:t.cursor,epoch:t.epoch,syncedAtMs:Date.now()};return f(this.host.sql(),o),o}isFreshEnough(e,t){return t!==void 0?e.appliedSeq>=t:Date.now()-e.syncedAtMs<=v(this.host.env(),"LUNORA_REPLICA_MAX_STALENESS_MS",m)}async pull(e){const t=await this.request({sinceSeq:e,type:"replica_pull"});return t===void 0?void 0:u(await t.json())}async request(e){const t=this.host.shardBinding(),r=N(this.host.env(),t,this.ownerKey);if(r===void 0)return;const o=JSON.stringify(e),n={"content-type":"application/json","x-lunora-shard-binding":t??""},i=E(this.host.env());i!==void 0&&(n[g]=await T(i,o));try{const p=await r.fetch("https://replica.internal/_lunora/replica",{body:o,headers:n,method:"POST"});return p.ok?p:void 0}catch{return}}}const j=s=>{const e=s.doName();if(e===void 0)return;const t=R(e);return t===void 0?void 0:new M(s,t.ownerKey,t.region)},G=async(s,e,t)=>{if(e.headers.get("x-lunora-replica-read")!=="1")return Response.json({error:{code:"REPLICA_READ_ONLY",message:`"${t}" is a write and cannot run on a read replica`}},{status:421});const r=await s.ensureFresh(I(e.headers.get("x-lunora-min-seq")));if(r!=="fresh")return Response.json({error:{code:"REPLICA_NOT_READY",message:`replica is ${r} for this read`}},{headers:{"x-lunora-replica-fallback":r},status:421})};export{j as createReplicaLink,G as gateReplicaDispatch,K as handleReplicaControl};
6
+ )`),l.add(s))},c=s=>(_(s),s.exec(`SELECT epoch, applied_seq AS appliedSeq, synced_at AS syncedAtMs FROM ${d} WHERE id = 1`).toArray()[0]),f=(s,e)=>{_(s),s.exec(`INSERT INTO ${d} (id, epoch, applied_seq, synced_at) VALUES (1, ?, ?, ?)
7
+ ON CONFLICT(id) DO UPDATE SET epoch = excluded.epoch, applied_seq = excluded.applied_seq, synced_at = excluded.synced_at`,e.epoch,e.appliedSeq,e.syncedAtMs)},q=s=>{const e=s.doName();if(e!==void 0&&R(e)!==void 0)return new Response("replica cannot serve replicas",{status:409});if(s.ownerEpoch()===void 0)return new Response("shard has no changelog to replicate",{status:409});if(E(s.env())===void 0)return new Response("replica control requires LUNORA_RELAY_SECRET",{status:403})},a=s=>Response.json(S(s)),P=async(s,e)=>{if(s.rowCount()>U(s.env()))return a({cursor:0,epoch:e,rows:[],truncated:!0});const t=s.ownerCursor()??0,r=await s.exportRows();return a({cursor:t,epoch:e,rows:r})},x=(s,e,t)=>{const r=s.ownerFloor();if(y(r,t))return a({changes:[],cursor:s.ownerCursor()??t,epoch:e,floor:r});const{changes:i,cursor:n}=s.readChanges(t,w);return a({changes:i,cursor:n,epoch:e,...r===void 0?{}:{floor:r}})},K=async(s,e)=>{const t=q(s);if(t!==void 0)return t;const r=s.ownerEpoch();let i;try{i=await e.text()}catch{return new Response("bad request",{status:400})}if(!await A(s.env(),e.headers.get(g),i))return new Response("forbidden",{status:403});let n;try{n=JSON.parse(i)}catch{return new Response("bad request",{status:400})}if(n.type==="replica_bootstrap")return P(s,r);if(n.type==="replica_pull"){const o=typeof n.sinceSeq=="number"&&Number.isInteger(n.sinceSeq)&&n.sinceSeq>=0?n.sinceSeq:0;return x(s,r,o)}return new Response("unknown replica frame",{status:400})};class M{constructor(e,t,r){this.host=e,this.ownerKey=t,this.region=r}host;ownerKey;region;divergent=!1;inFlight;async ensureFresh(e){if(this.divergent)return"unavailable";if(this.isCaughtUp(e))return"fresh";this.inFlight??=this.advance(e).finally(()=>{this.inFlight=void 0});const t=await this.inFlight;return t==="fresh"&&!this.isCaughtUp(e)?"stale":t}appliedSeq(){return c(this.host.sql())?.appliedSeq??0}isDivergent(){return this.divergent}async advance(e){let t=c(this.host.sql());if(t===void 0){const r=await this.bootstrap();if(r===void 0)return"unavailable";t=r}return this.catchUp(t,e)}isCaughtUp(e){const t=c(this.host.sql());return t!==void 0&&this.isFreshEnough(t,e)}async catchUp(e,t){let r=e;for(let i=0;i<C;i+=1){const n=await this.pull(r.appliedSeq);if(n===void 0)return t===void 0&&this.isFreshEnough(r,void 0)?"fresh":"unavailable";if(this.hasDiverged(r,n))return"unavailable";const o=n.changes.length<w;if(r=await this.applyPage(n),o||this.isFreshEnough(r,t))return this.isFreshEnough(r,t)?"fresh":"stale"}return this.isFreshEnough(r,t)?"fresh":"stale"}async applyPage(e){e.changes.length>0&&await this.host.applyChanges(e.changes);const t={appliedSeq:e.cursor,epoch:e.epoch,syncedAtMs:Date.now()};return f(this.host.sql(),t),t}hasDiverged(e,t){const r=t.changes.length===0&&t.cursor>e.appliedSeq,i=t.floor??(r?t.cursor:0),n=i>0&&i>e.appliedSeq+1;return t.epoch===e.epoch&&!n?!1:(this.divergent=!0,!0)}async bootstrap(){const e=await this.request({type:"replica_bootstrap"});if(e===void 0)return;const t=u(await e.json());if(t.truncated===!0){this.divergent=!0;return}const{errors:r}=await this.host.importRows(t.rows);if(r.length>0){this.divergent=!0;return}const i={appliedSeq:t.cursor,epoch:t.epoch,syncedAtMs:Date.now()};return f(this.host.sql(),i),i}isFreshEnough(e,t){return t!==void 0?e.appliedSeq>=t:Date.now()-e.syncedAtMs<=v(this.host.env(),"LUNORA_REPLICA_MAX_STALENESS_MS",m)}async pull(e){const t=await this.request({sinceSeq:e,type:"replica_pull"});return t===void 0?void 0:u(await t.json())}async request(e){const t=this.host.shardBinding(),r=N(this.host.env(),t,this.ownerKey,this.host.shardJurisdiction());if(r===void 0)return;const i=JSON.stringify(e),n={"content-type":"application/json","x-lunora-shard-binding":t??""},o=E(this.host.env());o!==void 0&&(n[g]=await T(o,i));try{const p=await r.fetch("https://replica.internal/_lunora/replica",{body:i,headers:n,method:"POST"});return p.ok?p:void 0}catch{return}}}const j=s=>{const e=s.doName();if(e===void 0)return;const t=R(e);return t===void 0?void 0:new M(s,t.ownerKey,t.region)},G=async(s,e,t)=>{if(e.headers.get("x-lunora-replica-read")!=="1")return Response.json({error:{code:"REPLICA_READ_ONLY",message:`"${t}" is a write and cannot run on a read replica`}},{status:421});const r=await s.ensureFresh(I(e.headers.get("x-lunora-min-seq")));if(r!=="fresh")return Response.json({error:{code:"REPLICA_NOT_READY",message:`replica is ${r} for this read`}},{headers:{"x-lunora-replica-fallback":r},status:421})};export{j as createReplicaLink,G as gateReplicaDispatch,K as handleReplicaControl};
@@ -0,0 +1 @@
1
+ import{D as ie}from"./MAX_TOKEN_LENGTH-BakL9FUy-B3VwYY8C.mjs";import{sql as e}from"drizzle-orm";import{matchesStaticWhere as P,aggregateSqlFunction as ce}from"./AGGREGATE_SQL_FUNCTION-DDEoMnJR.mjs";import{aggregateTableName as z,encodeAggregateKey as v,foldAggregateTally as J,coerceAggregateNumber as b}from"./aggregateTableName-C7o-gpms.mjs";import{runDrizzle as u}from"./runDrizzle-2ULFQR_k.mjs";import{i as fe,g as ae,D as M,r as q,a as L,b as h,A as p,c as D,e as U}from"./do-sql-ByyZb9U0.mjs";import{param as le,WORKERD_SQLITE_LIMITS as $e}from"./param-DlozcSQu.mjs";import{encodeGeohash as de,GEO_DEFAULT_PRECISION as ue}from"./GEO_DEFAULT_PRECISION-CqpQZ-J_.mjs";import{isLiveForCompanion as N}from"./CURSOR_PREFIX-Bn8SFoGd.mjs";import{encodePartitionKey as Ee,sortColumnName as _e,rankTableName as X,matchesRankStaticWhere as Y}from"./RANK_TIEBREAK-3pXm7Ng_.mjs";import{m as ye}from"./sql-projection-DML1_ex4.mjs";import{serializeSqlValue as Z}from"./serializeSqlValue-xohfS85H.mjs";const ge=(t,i)=>{if(!i.includes("."))return t[i];let f=t;for(const A of i.split(".")){if(f===null||typeof f!="object"||Array.isArray(f))return;f=f[A]}return f},pe=(t,i)=>`${t}__fts_${i}`,me="__text__",Q="__id__",he=1e3,Se=(t,i)=>i.document(t),W=(t,i)=>ge(t,i),Te=t=>typeof t=="string"?t:t==null?"":typeof t=="number"||typeof t=="bigint"||typeof t=="boolean"?String(t):JSON.stringify(t)??"",Re=(t,i,f)=>t!==void 0&&i!==void 0&&W(t,f.field)===W(i,f.field),Ae=(t,i)=>Se(Te(W(t,i.field)),ie(i.language)).slice(0,he),we=(t,i)=>Ae(t,i).join(" "),Fe=(t,i,f)=>[...t.partitionBy??[],...t.sortBy.map(S=>S.field),...t.where?Object.keys(t.where):[]].every(S=>i[S]===f[S]),x=t=>e.join(["__id__","__partition__",...t.sortBy.map((i,f)=>_e(f))].map(i=>e.identifier(i)),e`, `),ee=(t,i,f,A,S,y)=>{const c=Ee(f.partitionBy??[],y),C=f.sortBy.map(I=>Z(y[I.field]??null)),k=e.join([S,c,...C].map(I=>le(I)),e`, `);u(t,e`INSERT INTO ${e.identifier(i)} (${A}) VALUES (${k})`)},Oe=(t,i,f,A,S,y)=>{if(S&&y&&Fe(f,S,y))return;const c=X(i,f.name);S&&u(t,e`DELETE FROM ${e.identifier(c)} WHERE ${e.identifier("__id__")} = ${A}`),!(!y||f.where&&!Y(y,f.where))&&ee(t,c,f,x(f),A,y)},Be=t=>{const{broadcast:i,indexKeysFor:f,invalidateCache:A,recordCdc:S,schema:y,sql:c}=t,C=new Set,k=n=>y.tables[n]?.softDeleteMode?.field,I=new Set,j=(n,o)=>{const s=`${n}::${o.name}`;if(C.has(s))return;const l=z(n,o.name),$=o.by??[],d=k(n),_=new Map,m=u(c,e`SELECT id, _creationTime, ${e.identifier(M)} FROM ${e.identifier(n)}`).toArray();for(const T of m){const E=q(T);if(!E||!N(E,d)||o.where&&!P(E,o.where))continue;const R=v($,E);J(_,R,o,E)}u(c,e`DELETE FROM ${e.identifier(l)}`);const w=Math.floor($e.boundParams/3),F=[..._];for(let T=0;T<F.length;T+=w){const E=F.slice(T,T+w),R=e.join(E.map(([r,a])=>e`(${r}, ${a.value}, ${a.count})`),e`, `);u(c,e`INSERT INTO ${e.identifier(l)} (${L}, ${h}, ${p}) VALUES ${R}`)}C.add(s)},oe=(n,o,s)=>{const l=o.by??[],$=o.field??"",d=[],_=(r,a)=>{const g=Z(a);g===null?d.push(e`${U(r)} IS NULL`):d.push(e`${U(r)} = ${g}`)};for(const r of l)_(r,s[r]??null);const m=k(n);m!==void 0&&_(m,null);for(const[r,a]of Object.entries(o.where??{}))_(r,a!==null&&typeof a=="object"&&!Array.isArray(a)?a.eq:a);const w=d.length>0?e` WHERE ${e.join(d,e` AND `)}`:e``,F=y.tables[n]?.shape[$];if(F&&ye(F)){const r=u(c,e`SELECT id, _creationTime, ${e.identifier(M)} FROM ${e.identifier(n)}${w}`).toArray(),a=new Map;for(const g of r){const O=q(g);O&&J(a,"",o,O)}return{value:a.get("")?.value??null}}const T=ce(o.op),E=U($);return{value:u(c,e`SELECT ${e.raw(T)}(${E}) AS value FROM ${e.identifier(n)}${w}`).one().value??null}},ne=(n,o,s,l)=>{const $=z(n,o.name),{op:d}=o,_=o.field??"",m=r=>{u(c,e`DELETE FROM ${e.identifier($)} WHERE ${L} = ${r} AND ${p} <= 0`)},w=k(n),F=r=>!o.where||P(r,o.where),T=r=>N(r,w)&&F(r);l!==void 0&&d!=="count"&&F(l)&&b(l[_]);const E=s&&T(s)?s:void 0,R=l&&T(l)?l:void 0;if(!(!E&&!R)){if(d==="count"){for(const[r,a]of[[E,-1],[R,1]]){if(!r)continue;const g=v(o.by??[],r);u(c,D($,g,a,a,e`${h} = ${h} + excluded.${h}, ${p} = ${p} + excluded.${p}`))}E&&m(v(o.by??[],E));return}if(d==="sum"||d==="avg"){for(const[r,a]of[[E,-1],[R,1]]){if(!r)continue;const g=b(r[_]);if(g===void 0)continue;const O=v(o.by??[],r);u(c,D($,O,a*g,a,e`${h} = COALESCE(${h}, 0) + excluded.${h}, ${p} = ${p} + excluded.${p}`))}E&&m(v(o.by??[],E));return}if(E){const r=v(o.by??[],E),a=b(E[_]),g=u(c,e`SELECT ${h} AS value, ${p} AS count FROM ${e.identifier($)} WHERE ${L} = ${r}`).toArray()[0],O=(g?.count??0)-1;if(O<=0)u(c,e`DELETE FROM ${e.identifier($)} WHERE ${L} = ${r}`);else if(g&&a!==void 0&&g.value!==null&&a===g.value){const se=oe(n,o,E);u(c,e`UPDATE ${e.identifier($)} SET ${h} = ${se.value}, ${p} = ${O} WHERE ${L} = ${r}`)}else u(c,e`UPDATE ${e.identifier($)} SET ${p} = ${p} - 1 WHERE ${L} = ${r}`)}if(R){const r=v(o.by??[],R),a=b(R[_]);if(a===void 0)u(c,D($,r,null,1,e`${p} = ${p} + 1`));else{const g=d==="min"?"MIN":"MAX";u(c,D($,r,a,1,e`${h} = ${e.raw(g)}(COALESCE(${h}, excluded.${h}), excluded.${h}), ${p} = ${p} + 1`))}}}},te=n=>{for(const o of y.tables[n]?.aggregateIndexes??[])j(n,o)},H=(n,o,s)=>{for(const l of y.tables[n]?.aggregateIndexes??[])ne(n,l,o,s)},B=(n,o)=>{const s=`${n}::rank::${o.name}`;if(I.has(s))return;const l=X(n,o.name),$=u(c,e`SELECT id, _creationTime, ${e.identifier(M)} FROM ${e.identifier(n)}`).toArray();u(c,e`DELETE FROM ${e.identifier(l)}`);const d=x(o);for(const _ of $){const m=q(_);!m||o.where&&!Y(m,o.where)||ee(c,l,o,d,m._id,m)}I.add(s)},re=n=>{for(const o of y.tables[n]?.rankIndexes??[])B(n,o)},K=(n,o,s,l)=>{for(const $ of y.tables[n]?.rankIndexes??[])Oe(c,n,$,o,s,l)},V=(n,o,s,l)=>{const $=y.tables[n]?.searchIndexes??[];if(!($.length===0||!fe(c)))for(const d of $){if(Re(l,s,d))continue;const _=pe(n,d.name);u(c,e`DELETE FROM ${e.identifier(_)} WHERE ${e.identifier(Q)} = ${o}`),s&&u(c,e`INSERT INTO ${e.identifier(_)} (${e.identifier(me)}, ${e.identifier(Q)}) VALUES (${we(s,d)}, ${o})`)}},G=(n,o,s)=>{for(const l of y.tables[n]?.geoIndexes??[]){const $=ae(n,l.name);u(c,e`DELETE FROM ${e.identifier($)} WHERE ${e.identifier("__id__")} = ${o}`);const d=s?.[l.field];if(d!==null&&typeof d=="object"&&typeof d.lat=="number"&&typeof d.lng=="number"){const{lat:_,lng:m}=d,w=de({lat:_,lng:m},l.precision??ue);u(c,e`INSERT INTO ${e.identifier($)} (${e.identifier("__id__")}, ${e.identifier("__geohash__")}, ${e.identifier("__lat__")}, ${e.identifier("__lng__")}) VALUES (${o}, ${w}, ${_}, ${m})`)}}};return{ensureBackfilledForTable:te,ensureBackfilledIndex:j,ensureRankBackfilled:B,ensureRankBackfilledForTable:re,syncAggregates:H,syncCompanionsForInsert:(n,o,s)=>{V(n,o,s),G(n,o,s),H(n,void 0,s),K(n,o,void 0,s),A(n,o,s),S(n,o,"insert",s),i({indexKeys:f(n,s),key:o,op:"insert",row:s,table:n})},syncGeo:G,syncRanks:K,syncSearch:V}};export{pe as S,Ae as a,Be as c,we as d,ee as i,Q as l,x as r,me as y};
@@ -0,0 +1 @@
1
+ import{createShardCtxDb as v}from"./NotUniqueError-BO_Arsyi.mjs";import{createRelayLink as I}from"./DEFAULT_MAX_RELAYS-DDOVsK5A.mjs";import{ConflictError as N}from"./ConflictError-C8GtJmjS.mjs";import{runShardMigrations as _}from"./runShardMigrations-BvgoGgwG.mjs";import{relayName as F}from"./DEFAULT_PROMOTION_THRESHOLDS-Bfx7KakS.mjs";const E=(C,m={})=>({_meta:{column:{notNull:!0,...m}},kind:C}),W=(C,m,O)=>{const{describe:S,expect:n,it:y}=O;S(`engine contract: ${C}`,()=>{S("optimistic concurrency",()=>{const b=u=>({tables:{items:{indexes:[],shape:{title:E("string"),version:E("number",{notNull:!1})},triggerMap:{clobber:{handler:()=>{u.exec(`UPDATE "items" SET "__doc__" = json_set("__doc__", '$.version', 99) WHERE "id" = 'i1'`)},op:"update",timing:"before"}}}}});y("raises a CONFLICT of kind `occ` when a write's snapshot is clobbered",async()=>{const{close:u,host:h}=m();try{const i=h.sql,l=b(i);_(i,l);const s=v({schema:l,sql:i});await s.insert("items",{_id:"i1",title:"first",version:1},{allowExplicitId:!0}),await n(s.patch("i1",{title:"second"})).rejects.toBeInstanceOf(N)}finally{u?.()}}),y("reports the conflict as CONFLICT/409 rather than retrying it away",async()=>{const{close:u,host:h}=m();try{const i=h.sql,l=b(i);_(i,l);const s=v({schema:l,sql:i});await s.insert("items",{_id:"i1",title:"first",version:1},{allowExplicitId:!0});let o;try{await s.patch("i1",{title:"second"})}catch(t){o=t}const e=o;n(e.code).toBe("CONFLICT"),n(e.kind).toBe("occ")}finally{u?.()}}),y("leaves the row readable and unchanged after a conflict",async()=>{const{close:u,host:h}=m();try{const i=h.sql,l=b(i);_(i,l);const s=v({schema:l,sql:i});await s.insert("items",{_id:"i1",title:"first",version:1},{allowExplicitId:!0});try{await s.patch("i1",{title:"second"})}catch{}const o=await s.get("i1");n(o?.title).toBe("first"),n(o?.version).toBe(99)}finally{u?.()}}),y("raises a CONFLICT of kind `trigger` when a trigger writes its own row through the db",async()=>{const{close:u,host:h}=m();try{const i=h.sql,l={tables:{items:{indexes:[],shape:{title:E("string"),version:E("number",{notNull:!1})},triggerMap:{recurse:{handler:async(t,a)=>{await t.db.patch(a.doc._id,{version:99})},op:"update",timing:"before"}}}}};_(i,l);const s=v({schema:l,sql:i});await s.insert("items",{_id:"i1",title:"first",version:1},{allowExplicitId:!0});let o;try{await s.patch("i1",{title:"second"})}catch(t){o=t}const e=o;n(e).toBeInstanceOf(N),n(e.code).toBe("CONFLICT"),n(e.kind).toBe("trigger")}finally{u?.()}})}),S("shape-poke ordering",()=>{const b="shard-a",u={args:{},name:"messages"},h=(e,t,a,r)=>e.accept(t?.()??{},{connectionId:a,shapes:{[r]:u}}),i=(e,t,a)=>{let r=0,d=0;const c=g=>()=>{throw new Error(`the relay poke path must not reach RelayHost.${g}`)},p={fetch:(g,q)=>{if(JSON.parse(q?.body??"{}").type!=="relay_shape_subscribe")return Promise.resolve(new Response(void 0,{status:204}));const B=a[d];if(d+=1,B===void 0)throw new Error("the relay asked for more seeds than this fixture supplies");return Promise.resolve(Response.json(B))}},k={get:()=>p,getByName:()=>p,idFromName:g=>g},w={buildShapeDiff:c("buildShapeDiff"),computeOpLogShapeSeed:c("computeOpLogShapeSeed"),currentCdcEpoch:c("currentCdcEpoch"),deliverWhisperLocal:c("deliverWhisperLocal"),doName:()=>F(b,0),env:()=>({SHARD:k}),getWebSockets:()=>e.getSockets(),maskMetadata:c("maskMetadata"),nextPokeId:()=>(r+=1,`poke-${String(r)}`),readAttachment:g=>g.deserializeAttachment?.(),recordShapePokeFanout:()=>{},resolveShape:c("resolveShape"),rlsMetadata:c("rlsMetadata"),shardBinding:()=>"SHARD",shardJurisdiction:()=>{},sql:()=>t},f=I(w);if(f===void 0)throw new Error("expected a relay link for a `…::relay::N` name");return f},l=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 r=await e.seedRelayShape(t,a,u,{identity:void 0,userId:void 0});if(r!=="ok")throw new Error(`seed failed: ${JSON.stringify(r)}`)},o=(e={})=>l({...u,checkpoint:20,epoch:"e1",fromCursor:10,rowsPatch:[{id:"r1",op:"upsert",value:{title:"hello"}}],type:"relay_shape_poke",...e});y("frames a poke as pokeStart → pokePart per shape → pokeEnd, under one poke id",async()=>{const{close:e,createSocket:t,host:a,readFrames:r,sockets:d}=m();try{const c=i(d,a.sql,[{cursor:10,epoch:"e1",frames:[]}]),p=h(d,t,"c-alice","s1");await s(c,p,"s1"),await c.handleControl(o());const w=(await r(p)).map(f=>JSON.parse(f));n(w.map(f=>f.type)).toStrictEqual(["pokeStart","pokePart","pokeEnd"]),n(new Set(w.map(f=>f.pokeId)).size).toBe(1),n(w[1]?.shapeId).toBe("s1"),n(w[2]?.checkpoint).toBe(20)}finally{e?.()}}),y("delivers a poke only to sockets whose cursor matches, and advances them past it",async()=>{const{close:e,createSocket:t,host:a,readFrames:r,sockets:d}=m();try{const c=i(d,a.sql,[{cursor:10,epoch:"e1",frames:[]},{cursor:7,epoch:"e1",frames:[]}]),p=h(d,t,"c-alice","s1"),k=h(d,t,"c-bob","s2");await s(c,p,"s1"),await s(c,k,"s2"),await c.handleControl(o());const w=await r(p);n(w.length).toBe(3);const f=await r(k);n(f.length).toBe(0),await c.handleControl(o());const g=await r(p);n(g.length).toBe(3)}finally{e?.()}}),y("skips a socket whose cursor matches under a different CDC epoch",async()=>{const{close:e,createSocket:t,host:a,readFrames:r,sockets:d}=m();try{const c=i(d,a.sql,[{cursor:10,epoch:"e1",frames:[]}]),p=h(d,t,"c-alice","s1");await s(c,p,"s1"),await c.handleControl(o({epoch:"e2"}));const k=await r(p);n(k.length).toBe(0),await c.handleControl(o());const w=await r(p);n(w.length).toBe(3)}finally{e?.()}})}),S("RLS identity under live subscription",()=>{const b="shard-a",u={args:{},name:"lobby-messages"},h={args:{},name:"my-orders"},i=s=>{const o=[],e=[],t={fetch:(d,c)=>(o.push(JSON.parse(c?.body??"{}")),Promise.resolve(new Response(void 0,{status:204})))},r=I({buildShapeDiff:()=>[{id:"r1",op:"upsert",value:{}}],computeOpLogShapeSeed:()=>({baseCheckpoint:void 0,cursor:10,epoch:"e1",reset:!0,rowsPatch:[]}),currentCdcEpoch:()=>"e1",deliverWhisperLocal:()=>0,doName:()=>b,env:()=>({SHARD:{get:()=>t,getByName:()=>t,idFromName:d=>d}}),getWebSockets:()=>[],maskMetadata:()=>({columns:[]}),nextPokeId:()=>"poke-1",readAttachment:()=>({}),recordShapePokeFanout:()=>{},resolveShape:(d,c,p)=>(e.push(p),d===h.name?{columns:["id"],effectiveWhere:{org:p?.identity?.org??"anonymous"},global:!1,table:"orders"}:{columns:["id"],effectiveWhere:{room:"lobby"},global:!1,table:"messages"}),rlsMetadata:()=>({policies:[]}),shardBinding:()=>"SHARD",shardJurisdiction:()=>{},sql:()=>s});if(r===void 0)throw new Error("expected an owner link for an un-suffixed DO name");return{owner:r,posts:o,resolvedUnder:e}},l=async(s,o)=>{await s.handleControl(new Request("https://owner.internal/_lunora/relay",{body:JSON.stringify({...o,connectionId:"c-alice",identity:{org:"acme"},relayIndex:0,subId:"s1",type:"relay_shape_subscribe",userId:"u1"}),headers:{"content-type":"application/json"},method:"POST"}))};y("seeds a subscriber under its own forwarded identity, never the anonymous one",async()=>{const{close:s,host:o}=m();try{const{owner:e,resolvedUnder:t}=i(o.sql);await l(e,h),n(t.some(a=>a?.userId==="u1"&&a.identity?.org==="acme")).toBe(!0)}finally{s?.()}}),y("routes an identity-scoped shape to a per-socket poke, not the cohort multicast",async()=>{const{close:s,host:o}=m();try{const{owner:e,posts:t}=i(o.sql);await l(e,h),t.length=0,await e.onFlush(new Set(["orders"]),20);const a=t.filter(r=>r.type==="relay_shape_poke");n(a.length).toBe(1),n(a[0]?.targetConnectionId).toBe("c-alice")}finally{s?.()}}),y("still multicasts an identity-blind shape to the whole cohort",async()=>{const{close:s,host:o}=m();try{const{owner:e,posts:t}=i(o.sql);await l(e,u),t.length=0,await e.onFlush(new Set(["messages"]),20);const a=t.filter(r=>r.type==="relay_shape_poke");n(a.length).toBe(1),n(a[0]?.targetConnectionId).toBeUndefined()}finally{s?.()}})})})};export{W as defineEngineContractSuite};
@@ -0,0 +1 @@
1
+ import{LunoraError as _}from"@lunora/errors";import{sql as r}from"drizzle-orm";import{e as A,s as T}from"./sql-projection-DML1_ex4.mjs";import{quoteIdentifier as p}from"./quoteIdentifier-CObIFRhb.mjs";import{d as $,n as S,e as O}from"./wire-codec-C-FpWm52.mjs";import{runDrizzle as f}from"./runDrizzle-2ULFQR_k.mjs";import"./serializeSqlValue-xohfS85H.mjs";const b=/^[A-Za-z_$][\w$]*$/u,h=e=>b.test(e)?e:`"${e.replaceAll("\\",String.raw`\\`).replaceAll('"',String.raw`\"`)}"`,m="__doc__",a="__originals__",G=e=>{if(Object.hasOwn(e,a))throw new _("BAD_REQUEST",`"${a}" is reserved by the row store's document encoding and cannot be used as a field name — rename the field`);let t,o;for(const[s,i]of Object.entries(e)){const c=T(i);c!==void 0&&(t??={...e},o??=Object.create(null),t[s]=c,o[s]=i)}t&&o&&(t[a]=o);const n=t??e;try{return S(n)?JSON.stringify(O(n)):JSON.stringify(n)}catch(s){throw new _("BAD_REQUEST",`this document cannot be stored: ${s instanceof Error?s.message:String(s)}`)}},g=e=>{const t=$(JSON.parse(e)),o=t[a];if(o===null||typeof o!="object"||Array.isArray(o))return t;const n={...t};return delete n[a],{...n,...o}},J=(e,t)=>`${e}__geo_${t}`,E=(e,t)=>t==="_id"||t==="id"?`${e}id`:t==="_creationTime"?`${e}_creationTime`:`json_extract(${e}${m}, '$.${h(t).replaceAll("'","''")}')`,y=e=>E("",e),q=e=>r.raw(y(e)),N=(e,t)=>E(`${p(e)}.`,t),B=(e,t)=>r.raw(N(e,t)),z=(e,t,o,n)=>r`CREATE ${n?r`UNIQUE `:r``}INDEX IF NOT EXISTS ${r.identifier(e)} ON ${r.identifier(t)} (${o})`,l=r.identifier("__key__"),I=r.identifier("__value__"),j=r.identifier("__count__"),F=(e,t,o,n,s)=>r`INSERT INTO ${r.identifier(e)} (${l}, ${I}, ${j}) VALUES (${t}, ${o}, ${n}) ON CONFLICT(${l}) DO UPDATE SET ${s}`,W=(e,t)=>e===void 0||t!==0&&t!==1||A(e)!=="boolean"?t:t===1,d=new WeakMap,k=e=>{const t=d.get(e);if(t!==void 0)return t;const o=[];for(const[n,s]of Object.entries(e.shape)){const i=s._meta?.column;i&&o.push(Object.freeze([n,i]))}return Object.freeze(o),d.set(e,o),o},C=e=>{if(!e)return;const t=e[m];let o;typeof t=="string"?o=g(t):t&&typeof t=="object"?o=t:o={};const{id:n}=e;typeof n=="string"&&(o._id=n);const s=e._creationTime;return typeof s=="number"&&(o._creationTime=s),o},K=e=>{try{return C(e)}catch{return}},u=new WeakMap,M=e=>{const t=u.get(e);if(t!==void 0)return t;let o;try{f(e,r`CREATE VIRTUAL TABLE IF NOT EXISTS ${r.identifier("__lunora_fts_probe")} USING fts5(x)`),o=!0}catch{o=!1}finally{try{f(e,r`DROP TABLE IF EXISTS ${r.identifier("__lunora_fts_probe")}`)}catch{}}return u.set(e,o),o};export{j as A,m as D,l as a,I as b,F as c,z as d,q as e,B as f,J as g,K as h,M as i,y as j,G as k,g as l,h as m,a as n,W as o,N as q,C as r,k as t};
@@ -0,0 +1 @@
1
+ import{B as s}from"./sql-projection-DML1_ex4.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,4 +1,4 @@
1
- import{LunoraError as T}from"@lunora/errors";import{sql as m}from"drizzle-orm";import{runDrizzle as S}from"./runDrizzle-2ULFQR_k.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-CAPAra-0.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-2ULFQR_k.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-CFE0QRYx.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{applyCdcChanges as p}from"./CDC_LOG_TABLE-CAyqu8cg.mjs";import{selectShapeRows as m}from"./selectShapeMembers-DqikYFjS.mjs";import{diffExternalSource as g,projectExternalSourceRow as l}from"./diffExternalSource-DgDJhslq.mjs";import{stableStringify as d}from"./stableStringify-DibjylKD.mjs";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(c,n)&&r.push({id:c,op:"delete",seq:0,table:n,ts:0});continue}const u=await t.get(c,n);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-B-SKH98h.mjs";import{selectShapeRows as m}from"./selectShapeMembers-OatGcYrk.mjs";import{diffExternalSource as g,projectExternalSourceRow as l}from"./diffExternalSource-DgDJhslq.mjs";import{stableStringify as d}from"./stableStringify-DibjylKD.mjs";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(c,n)&&r.push({id:c,op:"delete",seq:0,table:n,ts:0});continue}const u=await t.get(c,n);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 p}from"@lunora/errors";import{S as L,y as N,l as h}from"./ctx-db-companions-B4O4d95S.mjs";import{sql as e}from"drizzle-orm";import{aggregateTableName as l}from"./aggregateTableName-C7o-gpms.mjs";import{backfillSearchIndexesForTable as R}from"./backfillAggregateIndexes-pQWaX2Yu.mjs";import{migrateCdcLog as O,migrateCdcMeta as x}from"./CDC_LOG_TABLE-CAyqu8cg.mjs";import{migrateClientWatermark as C}from"./CLIENT_WATERMARK_TABLE-CRnrAnJ2.mjs";import{migrateCommitSeq as $}from"./COMMIT_SEQ_FIELD-BUdOMG5y.mjs";import{migrateGlobalShapeSnapshot as U}from"./GLOBAL_SHAPE_SNAPSHOT_TABLE-DSA6mzyx.mjs";import{migrateIdempotency as b}from"./IDEMPOTENCY_TABLE-DOpm_oMF.mjs";import{m as D}from"./ctx-db-relay-shapes-Bg5YYnmN.mjs";import{m as X}from"./ctx-db-search-state-ruTuCsxa.mjs";import{migrateShapePokeCursor as G}from"./SHAPE_POKE_CURSOR_TABLE-ByJVDHds.mjs";import{runDrizzle as a}from"./runDrizzle-2ULFQR_k.mjs";import{D as M,d as E,e as g,t as F,i as B,g as y,a as Y,b as k,A as u}from"./do-sql-FNOnpyHm.mjs";import{renderSql as v}from"./param-DlozcSQu.mjs";import{migrateDurableStreams as P}from"./appendStreamChunk-C1Ok4b6J.mjs";import{rankTableName as w,sortColumnName as j}from"./RANK_TIEBREAK-CkNuGm6a.mjs";import{migrateReactorState as K}from"./REACTOR_STATE_TABLE-QPRFyxMS.mjs";import{recordSchemaVersion as V}from"./SCHEMA_HISTORY_MAX_VERSIONS-BluIj2s-.mjs";const A=e`_creationTime, id`,H=(i,o,n,r,t,s)=>{const f=a(i,e`SELECT sql FROM sqlite_master WHERE type = 'index' AND name = ${o} AND tbl_name = ${n}`).toArray()[0]?.sql;if(f==null)return;const m=c=>{const I=c.indexOf("(");return I===-1?void 0:c.slice(I,c.lastIndexOf(")")+1)},T=m(v("sqlite",E(o,n,r,t)).sql),_=m(f);if(!(T===void 0||_===void 0||T===_)){if(t){const c=e.join(s.map(S=>e`${S} IS NOT NULL`),e` AND `);if(a(i,e`SELECT 1 FROM ${e.identifier(n)} WHERE ${c} GROUP BY ${r} HAVING COUNT(*) > 1 LIMIT 1`).toArray().length>0)throw new p("INTERNAL",`unique index "${o}" on "${n}" cannot be re-created with its new column list: existing rows are duplicates under it. De-duplicate the table with a data migration first; the previous index is left in place.`)}a(i,e`DROP INDEX IF EXISTS ${e.identifier(o)}`)}},W=(i,o,n)=>{for(const r of n.indexes){const t=`${o}_${r.name}`,s=r.unique??!1,d=r.fields.map(T=>g(T)),f=e.join(d,e`, `),m=s?f:e`${f}, ${A}`;H(i,t,o,m,s,d),a(i,E(t,o,m,s))}for(const[r,t]of F(n)){if(!t.unique)continue;const s=`${o}_unique_${r}`;a(i,E(s,o,g(r),!0))}},z=(i,o,n)=>{if(!(!n.searchIndexes||n.searchIndexes.length===0||!B(i))){for(const r of n.searchIndexes){const t=L(o,r.name);a(i,e`CREATE VIRTUAL TABLE IF NOT EXISTS ${e.identifier(t)} USING fts5(${e.identifier(N)}, ${e.identifier(h)} UNINDEXED)`),a(i,e`CREATE VIRTUAL TABLE IF NOT EXISTS ${e.identifier(`${t}__vocab`)} USING fts5vocab(${e.identifier(t)}, ${e.raw("instance")})`)}R(i,o,n)}},J=(i,o,n)=>{if(n.geoIndexes)for(const r of n.geoIndexes){const t=y(o,r.name);a(i,e`CREATE TABLE IF NOT EXISTS ${e.identifier(t)} (${e.identifier("__id__")} TEXT PRIMARY KEY, ${e.identifier("__geohash__")} TEXT NOT NULL, ${e.identifier("__lat__")} REAL NOT NULL, ${e.identifier("__lng__")} REAL NOT NULL)`);const s=`${o}__geo_${r.name}__btree`;a(i,E(s,t,e`${e.identifier("__geohash__")} ASC, ${e.identifier("__id__")} ASC`,!1))}},Q=(i,o,n)=>{if(n.aggregateIndexes)for(const r of n.aggregateIndexes){const t=l(o,r.name);a(i,e`CREATE TABLE IF NOT EXISTS ${e.identifier(t)} (${Y} TEXT PRIMARY KEY, ${k} REAL, ${u} INTEGER NOT NULL DEFAULT 0)`),a(i,e`PRAGMA table_info(${e.identifier(t)})`).toArray().some(d=>d.name==="__count__")||a(i,e`ALTER TABLE ${e.identifier(t)} ADD COLUMN ${u} INTEGER NOT NULL DEFAULT 0`)}},Z=(i,o,n)=>{if(n.rankIndexes)for(const r of n.rankIndexes){const t=w(o,r.name),s=r.sortBy.map((_,c)=>j(c)),d=s.map(_=>e`${e.identifier(_)} BLOB`),f=d.length>0?e`, ${e.join(d,e`, `)}`:e``;a(i,e`CREATE TABLE IF NOT EXISTS ${e.identifier(t)} (${e.identifier("__id__")} TEXT PRIMARY KEY, ${e.identifier("__partition__")} TEXT NOT NULL${f})`);const m=[e`${e.identifier("__partition__")} ASC`];for(const[_,c]of s.entries()){const I=r.sortBy[_]?.direction;m.push(e`${e.identifier(c)} ${e.raw(I==="desc"?"DESC":"ASC")}`)}m.push(e`${e.identifier("__id__")} ASC`);const T=`${o}__rank_${r.name}__btree`;a(i,E(T,t,e.join(m,e`, `),!1))}},Se=(i,o,n={})=>{n.schemaSnapshot!==void 0&&V(i,n.schemaSnapshot.hash,n.schemaSnapshot.json),X(i);for(const[r,t]of Object.entries(o.tables))t.shardMode?.kind!=="global"&&(a(i,e`CREATE TABLE IF NOT EXISTS ${e.identifier(r)} (
1
+ import{LunoraError as p}from"@lunora/errors";import{S as L,y as N,l as h}from"./ctx-db-companions-kHoblDbS.mjs";import{sql as e}from"drizzle-orm";import{aggregateTableName as l}from"./aggregateTableName-C7o-gpms.mjs";import{backfillSearchIndexesForTable as R}from"./backfillAggregateIndexes-BXftO36q.mjs";import{migrateCdcLog as O,migrateCdcMeta as x}from"./CDC_LOG_TABLE-B-SKH98h.mjs";import{migrateClientWatermark as C}from"./CLIENT_WATERMARK_TABLE-CRnrAnJ2.mjs";import{migrateCommitSeq as $}from"./COMMIT_SEQ_FIELD-BUdOMG5y.mjs";import{migrateGlobalShapeSnapshot as U}from"./GLOBAL_SHAPE_SNAPSHOT_TABLE-DSA6mzyx.mjs";import{migrateIdempotency as b}from"./IDEMPOTENCY_TABLE-DOpm_oMF.mjs";import{m as D}from"./ctx-db-relay-shapes-Bg5YYnmN.mjs";import{m as X}from"./ctx-db-search-state-ruTuCsxa.mjs";import{migrateShapePokeCursor as G}from"./SHAPE_POKE_CURSOR_TABLE-ByJVDHds.mjs";import{runDrizzle as a}from"./runDrizzle-2ULFQR_k.mjs";import{D as M,d as E,e as g,t as F,i as B,g as y,a as Y,b as k,A as u}from"./do-sql-ByyZb9U0.mjs";import{renderSql as v}from"./param-DlozcSQu.mjs";import{migrateDurableStreams as P}from"./appendStreamChunk-C1Ok4b6J.mjs";import{rankTableName as w,sortColumnName as j}from"./RANK_TIEBREAK-3pXm7Ng_.mjs";import{migrateReactorState as K}from"./REACTOR_STATE_TABLE-QPRFyxMS.mjs";import{recordSchemaVersion as V}from"./SCHEMA_HISTORY_MAX_VERSIONS-BluIj2s-.mjs";const A=e`_creationTime, id`,H=(i,o,n,r,t,s)=>{const f=a(i,e`SELECT sql FROM sqlite_master WHERE type = 'index' AND name = ${o} AND tbl_name = ${n}`).toArray()[0]?.sql;if(f==null)return;const m=c=>{const I=c.indexOf("(");return I===-1?void 0:c.slice(I,c.lastIndexOf(")")+1)},T=m(v("sqlite",E(o,n,r,t)).sql),_=m(f);if(!(T===void 0||_===void 0||T===_)){if(t){const c=e.join(s.map(S=>e`${S} IS NOT NULL`),e` AND `);if(a(i,e`SELECT 1 FROM ${e.identifier(n)} WHERE ${c} GROUP BY ${r} HAVING COUNT(*) > 1 LIMIT 1`).toArray().length>0)throw new p("INTERNAL",`unique index "${o}" on "${n}" cannot be re-created with its new column list: existing rows are duplicates under it. De-duplicate the table with a data migration first; the previous index is left in place.`)}a(i,e`DROP INDEX IF EXISTS ${e.identifier(o)}`)}},W=(i,o,n)=>{for(const r of n.indexes){const t=`${o}_${r.name}`,s=r.unique??!1,d=r.fields.map(T=>g(T)),f=e.join(d,e`, `),m=s?f:e`${f}, ${A}`;H(i,t,o,m,s,d),a(i,E(t,o,m,s))}for(const[r,t]of F(n)){if(!t.unique)continue;const s=`${o}_unique_${r}`;a(i,E(s,o,g(r),!0))}},z=(i,o,n)=>{if(!(!n.searchIndexes||n.searchIndexes.length===0||!B(i))){for(const r of n.searchIndexes){const t=L(o,r.name);a(i,e`CREATE VIRTUAL TABLE IF NOT EXISTS ${e.identifier(t)} USING fts5(${e.identifier(N)}, ${e.identifier(h)} UNINDEXED)`),a(i,e`CREATE VIRTUAL TABLE IF NOT EXISTS ${e.identifier(`${t}__vocab`)} USING fts5vocab(${e.identifier(t)}, ${e.raw("instance")})`)}R(i,o,n)}},J=(i,o,n)=>{if(n.geoIndexes)for(const r of n.geoIndexes){const t=y(o,r.name);a(i,e`CREATE TABLE IF NOT EXISTS ${e.identifier(t)} (${e.identifier("__id__")} TEXT PRIMARY KEY, ${e.identifier("__geohash__")} TEXT NOT NULL, ${e.identifier("__lat__")} REAL NOT NULL, ${e.identifier("__lng__")} REAL NOT NULL)`);const s=`${o}__geo_${r.name}__btree`;a(i,E(s,t,e`${e.identifier("__geohash__")} ASC, ${e.identifier("__id__")} ASC`,!1))}},Q=(i,o,n)=>{if(n.aggregateIndexes)for(const r of n.aggregateIndexes){const t=l(o,r.name);a(i,e`CREATE TABLE IF NOT EXISTS ${e.identifier(t)} (${Y} TEXT PRIMARY KEY, ${k} REAL, ${u} INTEGER NOT NULL DEFAULT 0)`),a(i,e`PRAGMA table_info(${e.identifier(t)})`).toArray().some(d=>d.name==="__count__")||a(i,e`ALTER TABLE ${e.identifier(t)} ADD COLUMN ${u} INTEGER NOT NULL DEFAULT 0`)}},Z=(i,o,n)=>{if(n.rankIndexes)for(const r of n.rankIndexes){const t=w(o,r.name),s=r.sortBy.map((_,c)=>j(c)),d=s.map(_=>e`${e.identifier(_)} BLOB`),f=d.length>0?e`, ${e.join(d,e`, `)}`:e``;a(i,e`CREATE TABLE IF NOT EXISTS ${e.identifier(t)} (${e.identifier("__id__")} TEXT PRIMARY KEY, ${e.identifier("__partition__")} TEXT NOT NULL${f})`);const m=[e`${e.identifier("__partition__")} ASC`];for(const[_,c]of s.entries()){const I=r.sortBy[_]?.direction;m.push(e`${e.identifier(c)} ${e.raw(I==="desc"?"DESC":"ASC")}`)}m.push(e`${e.identifier("__id__")} ASC`);const T=`${o}__rank_${r.name}__btree`;a(i,E(T,t,e.join(m,e`, `),!1))}},Se=(i,o,n={})=>{n.schemaSnapshot!==void 0&&V(i,n.schemaSnapshot.hash,n.schemaSnapshot.json),X(i);for(const[r,t]of Object.entries(o.tables))t.shardMode?.kind!=="global"&&(a(i,e`CREATE TABLE IF NOT EXISTS ${e.identifier(r)} (
2
2
  id TEXT PRIMARY KEY,
3
3
  _creationTime REAL NOT NULL,
4
4
  ${e.identifier(M)} TEXT NOT NULL
@@ -1 +1 @@
1
- import{sql as o}from"drizzle-orm";import{runDrizzle as h}from"./runDrizzle-2ULFQR_k.mjs";import{e}from"./do-sql-FNOnpyHm.mjs";const E=(s,t,f,r)=>{const d=f-(t.after??0),i=[o`${e(t.field)} IS NOT NULL`,o`${e(t.field)} < ${d}`];t.softDeleteField!==void 0&&i.push(o`${e(t.softDeleteField)} IS NULL`);const l=o`SELECT id FROM ${o.identifier(t.table)} WHERE ${o.join(i,o` AND `)} LIMIT ${o.raw(String(Math.max(0,Math.floor(r))+1))}`,n=h(s,l).toArray(),a=n.length>r,$=n.slice(0,r).map(c=>c.id);return{hasMore:a,ids:$}};export{E as selectExpiredIds};
1
+ import{sql as o}from"drizzle-orm";import{runDrizzle as h}from"./runDrizzle-2ULFQR_k.mjs";import{e}from"./do-sql-ByyZb9U0.mjs";const E=(s,t,f,r)=>{const d=f-(t.after??0),i=[o`${e(t.field)} IS NOT NULL`,o`${e(t.field)} < ${d}`];t.softDeleteField!==void 0&&i.push(o`${e(t.softDeleteField)} IS NULL`);const l=o`SELECT id FROM ${o.identifier(t.table)} WHERE ${o.join(i,o` AND `)} LIMIT ${o.raw(String(Math.max(0,Math.floor(r))+1))}`,n=h(s,l).toArray(),a=n.length>r,$=n.slice(0,r).map(c=>c.id);return{hasMore:a,ids:$}};export{E as selectExpiredIds};
@@ -1 +1 @@
1
- import{sql as e}from"drizzle-orm";import{runDrizzle as m}from"./runDrizzle-2ULFQR_k.mjs";import{D as p,r as d,e as h}from"./do-sql-FNOnpyHm.mjs";import{sqliteInList as w}from"./param-DlozcSQu.mjs";import{c as S}from"./where-sql-B1l5NcUZ.mjs";import{serializeSqlValue as $}from"./serializeSqlValue-B_-zaEWZ.mjs";const C={fieldRef:h,serialize:$},g=o=>{if(o.length!==0)return w(e`${e.identifier("id")}`,o,!1)},u=(o,i)=>{const r=[];i&&r.push(i);const t=S(o,C);return t&&r.push(t),r.length===0?e``:e` WHERE ${e.join(r,e` AND `)}`},v=(o,i,r)=>{const t=u(r,void 0),s=m(o,e`SELECT id, _creationTime, ${e.identifier(p)} FROM ${e.identifier(i)}${t}`).toArray(),f=[];for(const l of s){const n=d(l),{id:c}=l;n!==void 0&&typeof c=="string"&&f.push({doc:n,id:c})}return f},z=(o,i,r,t)=>{const s=new Map;if(t.length===0)return s;const f=u(r,g(t)),l=m(o,e`SELECT id, _creationTime, ${e.identifier(p)} FROM ${e.identifier(i)}${f}`).toArray();for(const n of l){const c=d(n),{id:a}=n;c!==void 0&&typeof a=="string"&&s.set(a,c)}return s};export{z as selectShapeMembers,v as selectShapeRows};
1
+ import{sql as e}from"drizzle-orm";import{runDrizzle as m}from"./runDrizzle-2ULFQR_k.mjs";import{D as p,r as d,e as h}from"./do-sql-ByyZb9U0.mjs";import{sqliteInList as w}from"./param-DlozcSQu.mjs";import{c as S}from"./where-sql-x1YKldcq.mjs";import{serializeSqlValue as $}from"./serializeSqlValue-xohfS85H.mjs";const C={fieldRef:h,serialize:$},g=o=>{if(o.length!==0)return w(e`${e.identifier("id")}`,o,!1)},u=(o,i)=>{const r=[];i&&r.push(i);const t=S(o,C);return t&&r.push(t),r.length===0?e``:e` WHERE ${e.join(r,e` AND `)}`},v=(o,i,r)=>{const t=u(r,void 0),s=m(o,e`SELECT id, _creationTime, ${e.identifier(p)} FROM ${e.identifier(i)}${t}`).toArray(),f=[];for(const l of s){const n=d(l),{id:c}=l;n!==void 0&&typeof c=="string"&&f.push({doc:n,id:c})}return f},z=(o,i,r,t)=>{const s=new Map;if(t.length===0)return s;const f=u(r,g(t)),l=m(o,e`SELECT id, _creationTime, ${e.identifier(p)} FROM ${e.identifier(i)}${f}`).toArray();for(const n of l){const c=d(n),{id:a}=n;c!==void 0&&typeof a=="string"&&s.set(a,c)}return s};export{z as selectShapeMembers,v as selectShapeRows};
@@ -0,0 +1 @@
1
+ import{s as o}from"./sql-projection-DML1_ex4.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};
@@ -0,0 +1 @@
1
+ const c=(n,t)=>{const r=Math.max(n.length,t.length);let o=n.length^t.length;for(let e=0;e<r;e+=1){const i=e<n.length?n.charCodeAt(e):0,a=e<t.length?t.charCodeAt(e):0;o|=i^a}return o===0},d="LUNORA_RELAY_SECRET",g="x-lunora-relay-sig",l=n=>{const t=n?.[d];return typeof t=="string"&&t.length>0?t:void 0},u=async(n,t)=>{const r=new TextEncoder,o=await crypto.subtle.importKey("raw",r.encode(n),{hash:"SHA-256",name:"HMAC"},!1,["sign"]),e=await crypto.subtle.sign("HMAC",o,r.encode(t));return[...new Uint8Array(e)].map(i=>i.toString(16).padStart(2,"0")).join("")},f=async(n,t,r)=>{const o=l(n);return o===void 0?!0:t===null?!1:c(t,await u(o,r))},s=n=>{if(n===null||typeof n!="object")return;const t=n;return typeof t.idFromName=="function"&&typeof t.get=="function"?t:void 0},y=(n,t,r,o)=>{if(t===void 0)return;const e=s(n?.[t]);if(e===void 0)return;const i=o===void 0?e:s(e.jurisdiction?.(o));if(i!==void 0)return typeof i.getByName=="function"?i.getByName(r):i.get(i.idFromName(r))};export{g as R,l as a,u as b,y as s,f as v};
@@ -0,0 +1 @@
1
+ import{LunoraError as g}from"@lunora/errors";import{t as s}from"./base64-DfpzS4o_.mjs";const e=n=>{if(n.kind!=="optional")return n.kind;const t=n._meta?.inner;return t?e(t):n.kind},r=39,c="0",f="1",d=n=>Array.from(n,t=>String(9-Number(t))).join(""),m=n=>{const t=n<0n,i=(t?-n:n).toString();if(i.length>r)throw new g("BAD_REQUEST",`bigint ${n.toString()} has ${String(i.length)} digits, over the ${String(r)}-digit limit for a queryable column`);const o=i.padStart(r,"0");return t?c+d(o):f+o},y=/^\d+$/u,a=n=>{if(n.length!==r+1)return;const t=n.slice(0,1),i=n.slice(1);if(y.test(i))return t===f?BigInt(i):t===c?-BigInt(d(i)):void 0},S=n=>typeof n=="bigint"?m(n):n instanceof ArrayBuffer?s(new Uint8Array(n)):ArrayBuffer.isView(n)?s(new Uint8Array(n.buffer,n.byteOffset,n.byteLength)):void 0,u=n=>{const t=e(n);return t==="bigint"||t==="bytes"},B=n=>{const t=e(n);return u(n)||t==="any"||t==="union"||t==="from"};export{r as B,m as b,a as d,e,u as i,B as m,S as s};
@@ -0,0 +1 @@
1
+ import{LunoraError as T}from"@lunora/errors";import{sql as l}from"drizzle-orm";import{sqliteInList as d,isJsonSafe as $,WORKERD_SQLITE_LIMITS as O}from"./param-DlozcSQu.mjs";import{quoteIdentifier as m}from"./quoteIdentifier-CObIFRhb.mjs";import{RELATION_EXISTS_KEY as L}from"./RELATION_EXISTS_KEY-CFUhnZSZ.mjs";const R={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,s)=>d(n,t,o,s),negate:n=>l`NOT (${n})`,nullCheck:(n,t)=>t?l`${n} IS NOT NULL`:l`${n} IS NULL`,value:n=>l`${n}`},p=(...n)=>{let t="";const o=[];for(const s of n)typeof s=="string"?t+=s:(t+=s.text,o.push(...s.params));return{params:o,text:t}},h=n=>({params:[n],text:"?"}),I=n=>({params:[],text:n}),Y=n=>I(m(n)),Q={binary:(n,t,o)=>p(n," ".concat(t," "),h(o)),constant:n=>I(n?"1 = 1":"0 = 1"),connect:(n,t,o)=>p("(",n,") ".concat(o," ("),t,")"),contains:(n,t)=>p("instr(lower(",n,"), lower(",t,")) > 0"),inList:(n,t,o,s)=>{const i=o?" NOT IN ":" IN ";if(t.length>s&&!t.every(r=>$(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(s)} values or fewer.`);if(t.length<=s){const r=[n,i,"("];for(const[e,c]of t.entries())e>0&&r.push(", "),r.push(h(c));return r.push(")"),p(...r)}return p(n,i,'(SELECT "value" FROM json_each(',h(JSON.stringify(t)),"))")},negate:n=>p("NOT (",n,")"),nullCheck:(n,t)=>p(n,t?" IS NOT NULL":" IS NULL"),value:h},x=O.boundParams/2,S=["eq","ne","lt","lte","gt","gte","in","notIn","isNull","contains"],_=new Set(S),j={eq:"=",gt:">",gte:">=",lt:"<",lte:"<=",ne:"<>"},E=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,s,i)=>{const r=i.value(s.serialize(o,n));return s.containsExpr?s.containsExpr(t,r):i.contains(t,r)},y=(n,t,o,s,i,r,e)=>i===null?o==="eq"||o==="ne"?e.nullCheck(t,o==="ne"):e.constant(!1):e.binary(t,s,r.serialize(i,n)),C=(n,t,o,s,i,r)=>{if(!Array.isArray(s))throw new T("BAD_REQUEST",`\`${o==="IN"?"in":"notIn"}\` on "${n}" expects an array of values, received ${s===null?"null":typeof s}`);const e=s;if(e.length===0)return r.constant(o==="NOT IN");const c=e.map(u=>i.serialize(u,n)),a=o==="NOT IN";return i.inList?i.inList(t,c,a):r.inList(t,c,a,x)},G=(n,t,o)=>{const s=l.join(t.map(i=>l`${i}`),l`, `);return o?l`${n} NOT IN (${s})`:l`${n} IN (${s})`},D=(n,t,o,s,i)=>{const r=o,e=[];for(const c of S){if(!(c in r))continue;const a=r[c],u=j[c];u?e.push(y(n,t,c,u,a,s,i)):c==="isNull"?e.push(i.nullCheck(t,!a)):c==="contains"?e.push(w(n,t,a,s,i)):e.push(C(n,t,c==="in"?"IN":"NOT IN",a,s,i))}return e},U=(n,t,o,s)=>{const i=o.fieldRef(n);return E(t)?D(n,i,t,o,s):t===null?[s.nullCheck(i,!1)]:[s.binary(i,"=",o.serialize(t,n))]},N=(n,t,o)=>{if(n.length<=1)return n[0];const s=Math.floor(n.length/2);return o.connect(N(n.slice(0,s),t,o),N(n.slice(s),t,o),t)},k=(n,t,o,s)=>{const i=Array.isArray(n)?n:[],r=[];for(const e of i){const c=f(e??{},o,s);c!==void 0&&r.push(c)}return r.length===0?t==="OR"?s.constant(!1):void 0:N(r,t,s)},M=new Set(["AND","NOT","OR",L]),P=(n,t,o,s)=>{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 i=f(t??{},o,s);return i===void 0?void 0:s.negate(i)}return k(t,n,o,s)},f=(n,t,o)=>{const s=[];for(const[i,r]of Object.entries(n))if(M.has(i)){const e=P(i,r,t,o);e!==void 0&&s.push(e)}else s.push(...U(i,r,t,o));return N(s,"AND",o)},q=O.boundParams/2,b=n=>{let t=0,o=0;const s=i=>{const r=b(i);t+=r.lists,o+=r.scalars};if(Array.isArray(n)){for(const i of n)s(i);return{lists:t,scalars:o}}if(n===null||typeof n!="object")return{lists:t,scalars:o};for(const[i,r]of Object.entries(n))i==="in"||i==="notIn"?t+=1:i==="AND"||i==="NOT"||i==="OR"||E(r)?s(r):o+=1;return{lists:t,scalars:o}},J=(n,t,o=R)=>{if(!n||Object.keys(n).length===0)return;const{lists:s,scalars:i}=b(n);if(s===0)return f(n,t,o);const r=Math.max(1,Math.floor(Math.min(q,O.boundParams-i)/s)),e=t.inList??((c,a,u,A)=>o.inList(c,a,u,A??r));return f(n,{...t,inList:(c,a,u)=>e(c,a,u,r)},o)};export{J as c,Y as i,p as j,G as l,I as r,Q as t};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@lunora/shard-engine",
3
- "version": "1.0.0-alpha.59",
3
+ "version": "1.0.0-alpha.60",
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",
@@ -48,7 +48,7 @@
48
48
  "access": "public"
49
49
  },
50
50
  "dependencies": {
51
- "@lunora/errors": "1.0.0-alpha.34",
51
+ "@lunora/errors": "1.0.0-alpha.35",
52
52
  "@lunora/platform": "1.0.0-alpha.27",
53
53
  "drizzle-orm": "^0.45.2"
54
54
  },
@@ -1 +0,0 @@
1
- import{LunoraError as u}from"@lunora/errors";const f=new Set(["baseWhere","relationBaseWhere","restrictsCounts","where"]),c=()=>{throw new u("INTERNAL","ctx.scheduler: no scheduler configured for triggers. Pass `scheduler` to the ctx-db factory.")},h=(e,r)=>{for(const[n,t]of Object.entries(r)){const o=e[n];if(t!==null&&typeof t=="object"&&!Array.isArray(t)){const s=Object.keys(t);if(s.length===1&&s[0]==="eq"){if(o!==t.eq)return!1;continue}return!1}if(o!==t)return!1}return!0},l=e=>{if(e===void 0)return{};if(typeof e!="object"||Array.isArray(e))return{where:e};const r=Object.keys(e);return r.length===0?{}:r.every(n=>f.has(n))?e:{where:e}},i={avg:"AVG",count:"COUNT",max:"MAX",min:"MIN",sum:"SUM"},y=e=>{const r=i[e];if(r===void 0)throw new u("INTERNAL",`unknown aggregate op "${e}": expected one of ${Object.keys(i).join(", ")}`);return r},A={runAfter:c,runAt:c};export{i as AGGREGATE_SQL_FUNCTION,y as aggregateSqlFunction,h as matchesStaticWhere,l as normalizeCountArgument,A as throwingScheduler};
@@ -1 +0,0 @@
1
- import{A as r,a as l,b as i,D as n,n as m,c as q,d as c,l as d,k as f,g as p,i as u,j as A,e as D,q as G,f as S,r as _,t as h,h as C}from"./do-sql-FNOnpyHm.mjs";import{quoteIdentifier as b}from"./quoteIdentifier-CObIFRhb.mjs";import"./wire-codec-C-FpWm52.mjs";import"./runDrizzle-2ULFQR_k.mjs";import"./BIGINT_KEY_DIGITS-GvEBhyR5.mjs";import{serializeSqlValue as x}from"./serializeSqlValue-B_-zaEWZ.mjs";export{r as AGG_COUNT,l as AGG_KEY,i as AGG_VALUE,n as DOC_COLUMN,m as DOC_ORIGINALS_KEY,q as aggUpsertSql,c as createIndexSql,d as decodeDocJson,f as encodeDocJson,p as geoTableName,u as isFtsAvailable,A as jsonPath,D as jsonPathSql,G as qualifiedJsonPath,S as qualifiedJsonPathSql,b as quoteIdentifier,_ as rowToDocument,x as serializeSqlValue,h as tableColumns,C as tryRowToDocument};
@@ -1 +0,0 @@
1
- import{LunoraError as d}from"@lunora/errors";import{t as s}from"./base64-DfpzS4o_.mjs";const e=n=>{if(n.kind!=="optional")return n.kind;const t=n._meta?.inner;return t?e(t):n.kind},r=39,c="0",f="1",g=n=>Array.from(n,t=>String(9-Number(t))).join(""),m=n=>{const t=n<0n,i=(t?-n:n).toString();if(i.length>r)throw new d("BAD_REQUEST",`bigint ${n.toString()} has ${String(i.length)} digits, over the ${String(r)}-digit limit for a queryable column`);const o=i.padStart(r,"0");return t?c+g(o):f+o},y=/^\d+$/u,S=n=>{if(n.length!==r+1)return;const t=n.slice(0,1),i=n.slice(1);if(y.test(i))return t===f?BigInt(i):t===c?-BigInt(g(i)):void 0},E=n=>typeof n=="bigint"?m(n):n instanceof ArrayBuffer?s(new Uint8Array(n)):ArrayBuffer.isView(n)?s(new Uint8Array(n.buffer,n.byteOffset,n.byteLength)):void 0,u=n=>{const t=e(n);return t==="bigint"||t==="bytes"},p=n=>{const t=e(n);return u(n)||t==="any"||t==="union"||t==="from"};export{r as BIGINT_KEY_DIGITS,m as bigintSqlKey,S as decodeBigintSqlKey,u as isProjectedKind,p as mayHoldProjectedValue,E as sqlComparableProjection};
@@ -1 +0,0 @@
1
- import{LunoraError as _}from"@lunora/errors";import{d as N,e as E}from"./wire-codec-C-FpWm52.mjs";const p="id",b=e=>e.at(-1)?.direction==="desc"?"desc":"asc",h=new Set(["_id","id"]),y=new Set(["_creationTime","_id","id"]),g=(e,t)=>{if(y.has(e))return!1;const n=t?.[e];return n===void 0?!0:n.kind==="optional"||n._meta?.column?.notNull===!1},A=(e,t)=>{const n=[];for(const r of e??[])for(const[o,i]of Object.entries(r))n.push({direction:i,field:o,nullable:g(o,t)});return n.length===0?[{direction:"asc",field:"_creationTime",nullable:!1}]:(n.some(r=>h.has(r.field)||r.field==="_creationTime")||n.push({direction:b(n),field:"_creationTime",nullable:!1}),n)},F=/[\u0080-\u{10FFFF}]/u,O=e=>{if(!F.test(e))return btoa(e);const t=new TextEncoder().encode(e);let n="";for(const r of t)n+=String.fromCodePoint(r);return btoa(n)},T=e=>{const t=atob(e),n=Uint8Array.from(t,r=>r.codePointAt(0)??0);return new TextDecoder().decode(n)},u="~3",C=(e,t)=>{const n=t.map(r=>e[r.field]??null);return n.push(e._id),u+O(JSON.stringify(E(n)))},d=()=>new _("BAD_REQUEST","invalid cursor"),I=e=>{if(!e.startsWith(u))throw d();let t;try{t=N(JSON.parse(T(e.slice(u.length))))}catch{throw d()}if(!Array.isArray(t))throw d();return t.map(n=>n??null)},m=(e,t,n,r)=>{const{field:o}=e,i=e.direction!=="desc"===n;if(t===null)return i?r?{OR:[{[o]:{isNull:!1}},{[o]:{isNull:!0}}]}:{[o]:{isNull:!1}}:r?{[o]:{isNull:!0}}:{OR:[]};let s=i?"gt":"lt";r&&(s=i?"gte":"lte");const c={[o]:{[s]:t}};return i||!e.nullable?c:{OR:[c,{[o]:{isNull:!0}}]}},S=(e,t,n,r)=>{const o=e.some(l=>h.has(l.field))?e:[...e,{direction:b(e),field:p,nullable:!1}];if(t.length<o.length)throw d();const i=l=>{const a=o[l];if(a===void 0)throw d();const f=m(a,t[l],n,r&&l===o.length-1);return l===o.length-1?f:{OR:[f,{AND:[{[a.field]:{eq:t[l]}},i(l+1)]}]}},s=i(0),[c]=o;return o.length<2||c===void 0||c.nullable||t[0]===null?s:{AND:[m(c,t[0],n,!0),s]}},L=(e,t)=>S(e,t,!0,!1),k=(e,t)=>S(e,t,!1,!0),D=["_id","_creationTime"],W=(e,t,n)=>{if(!t)return e;const r=new Set([...t,...D,...n?Object.keys(n):[]]);return e.map(o=>{const i={};for(const s of r)s in o&&(i[s]=o[s]);return i})},B=(e,t)=>e&&t!==!0?{[e.field]:{isNull:!0}}:void 0,v=(e,t)=>t===void 0||e[t]===null||e[t]===void 0;export{u as CURSOR_PREFIX,W as applySelect,k as buildSeekBeforeWhere,L as buildSeekWhere,I as decodeCursor,C as encodeCursor,T as fromBase64,d as invalidCursor,v as isLiveForCompanion,A as normalizeOrderKeys,B as softDeleteScope,b as tiebreakDirectionFor,O as toBase64};
@@ -1 +0,0 @@
1
- import{LunoraError as p}from"@lunora/errors";class R extends p{constructor(n){super("COUNT_RLS_UNSUPPORTED",n===void 0?"count() is not supported in an RLS-restricted context":`count() is not supported on table "${n}" inside an RLS-restricted context`)}}const S=(e,n)=>e?n?{AND:[e,n]}:e:n,v=new Set(["AND","NOT","OR"]),d=Symbol("not-eq"),O=e=>{if(e!==null&&typeof e=="object"&&!Array.isArray(e)){const n=Object.keys(e);return n.length===1&&n[0]==="eq"?e.eq:d}return e},f=(e,n)=>{const i={};for(const[t,o]of Object.entries(e)){if(v.has(t)||!n(t))return;const r=O(o);if(r===d)return;i[t]=r}return i},l=(e,n,i)=>{const t={...n};if(!e)return t;for(const[o,r]of Object.entries(e))if(o in t){if(t[o]!==r)return}else if(o in i){if(i[o]!==r)return}else t[o]=r;return t},b=(e,n)=>{const i=e.by??[],t=n??{},o=f(t,r=>i.includes(r));if(o!==void 0){for(const r of i)if(!(r in o))return;return l(e.where,o,t)}},x=(e,n,i)=>{const t=f(n??{},o=>i.has(o));if(t!==void 0)return l(e.where,t,{})},y=(e,n,i,t)=>{let o;for(const r of e){if(r.op!==n||n!=="count"&&r.field!==i)continue;const s=b(r,t);s&&(!o||(r.by?.length??0)>(o.index.by?.length??0))&&(o={index:r,key:s})}return o},h=(e,n)=>y(e,"count",void 0,n),A=(e,n,i,t)=>y(e,n,i,t),N=(e,n,i,t,o)=>{const r=new Set(t);for(const s of e){if(s.op!==n||n!=="count"&&s.field!==i)continue;const c=s.by??[];if(c.length!==r.size||!c.every(a=>r.has(a)))continue;const u=x(s,o,r);if(u!==void 0)return{index:s,partial:u}}};export{R as CountRlsUnsupportedError,S as mergeWhere,b as planAggregateLookup,A as selectIndexForAggregate,h as selectIndexForCount,N as selectIndexForGroupBy};
@@ -1,8 +0,0 @@
1
- import{toErrorBody as k,LunoraError as D}from"@lunora/errors";import{e as N,d as v}from"./wire-codec-C-FpWm52.mjs";import{sql as y}from"drizzle-orm";import{runDrizzle as m}from"./runDrizzle-2ULFQR_k.mjs";import{WORKERD_SQLITE_LIMITS as F}from"./param-DlozcSQu.mjs";import{d as U,w,a as A,m as K,r as Y,b as $,c as W}from"./ctx-db-relay-shapes-Bg5YYnmN.mjs";import{envPositiveInt as g}from"./envOptionalPositiveInt-D2pY-c64.mjs";import{relayName as R,DEFAULT_PROMOTION_THRESHOLDS as T,nextPromotionState as B,shapeRoutingKey as E,relayProxyKey as M,parseRelayName as H,clampPromotionThresholds as q}from"./DEFAULT_PROMOTION_THRESHOLDS-Bfx7KakS.mjs";import{encodeRowsPatch as X,buildPokeFrames as O}from"./buildPokeFrames-BBE6J91z.mjs";import{v as j,R as L,s as z,a as G,b as V}from"./sibling-channel-Cxvk0Zca.mjs";import{awaitWsDrain as J,trySendFrame as x}from"./awaitWsDrain-apizgmKY.mjs";import{stableWireKey as b}from"./stableWireKey-D2US4k_J.mjs";const f="__lunora_relay_memos",Q=i=>{m(i,y`CREATE TABLE IF NOT EXISTS ${y.identifier(f)} (
2
- connection_id TEXT NOT NULL,
3
- sub_id TEXT NOT NULL,
4
- cursor INTEGER NOT NULL,
5
- epoch TEXT,
6
- PRIMARY KEY (connection_id, sub_id)
7
- )`)},Z=i=>{const e=m(i,y`SELECT connection_id, sub_id, cursor, epoch FROM ${y.identifier(f)}`).toArray(),s=new Map;for(const t of e){let o=s.get(t.connection_id);o===void 0&&(o=new Map,s.set(t.connection_id,o)),o.set(t.sub_id,{cursor:Number(t.cursor),epoch:t.epoch??void 0})}return s},ee=4,C=(i,e)=>{const s=Math.floor(F.boundParams/ee);for(let t=0;t<e.length;t+=s){const o=e.slice(t,t+s),n=y.join(o.map(r=>y`(${r.connectionId}, ${r.subId}, ${r.cursor}, ${r.epoch??null})`),y`, `);m(i,y`INSERT INTO ${y.identifier(f)} (connection_id, sub_id, cursor, epoch) VALUES ${n}
8
- ON CONFLICT(connection_id, sub_id) DO UPDATE SET cursor = excluded.cursor, epoch = excluded.epoch`)}},te=(i,e,s)=>{m(i,y`DELETE FROM ${y.identifier(f)} WHERE connection_id = ${e} AND sub_id = ${s}`)},se=(i,e)=>{m(i,y`DELETE FROM ${y.identifier(f)} WHERE connection_id = ${e}`)},oe=i=>{m(i,y`DELETE FROM ${y.identifier(f)}`)},re=2,ne=8,I={},ae=i=>{throw new D("INTERNAL",`unhandled relay frame: ${JSON.stringify(i)}`)},ie=(i,e)=>i===void 0||i.epoch!==e.epoch?!1:i.cursor>=e.fromCursor&&i.cursor<e.checkpoint,ce=i=>Response.json(i,{headers:{"content-type":"application/json"}}),S=()=>new Response(null,{status:204});class P{constructor(e,s){this.host=e,this.roleId=s}host;roleId;async handleControl(e){let s;try{s=await e.text()}catch{return new Response("bad request",{status:400})}if(!await j(this.host.env(),e.headers.get(L),s))return new Response("forbidden",{status:403});let t;try{t=JSON.parse(s)}catch{return new Response("bad request",{status:400})}switch(t.type){case"relay_attach":return this.onAttach(t.relayIndex),S();case"relay_detach":return this.onDetach(t.relayIndex),S();case"relay_frame":return this.host.deliverWhisperLocal(t.topic,t.frame,void 0),await this.onWhisperFrame(t),S();case"relay_shape_poke":{const o=this.host.getWebSockets().length,n=Date.now(),{delivered:r,matched:a}=this.onShapePoke({...t,args:v(t.args)});return this.host.recordShapePokeFanout(o,r,Date.now()-n),r<a?Response.json({delivered:r,matched:a},{status:503}):S()}case"relay_shape_subscribe":return ce(this.onShapeSubscribe({...t,args:v(t.args)}));case"relay_shape_unsubscribe":return this.onShapeUnsubscribe(t),S();default:return ae(t)}}maxRelays(){return g(this.host.env(),"LUNORA_MAX_RELAYS",ne)}canAddressSiblings(){return this.siblingStub(this.roleId.ownerKey)!==void 0}siblingStub(e){return z(this.host.env(),this.bindingName(),e)}bindingName(){return this.host.shardBinding()}async postRelayMessage(e,s){await this.requestRelayMessage(e,s)}async requestRelayMessage(e,s){const t=this.siblingStub(e);if(t===void 0)return;const o=JSON.stringify(s),n={"content-type":"application/json","x-lunora-shard-binding":this.host.shardBinding()??""},r=G(this.host.env());r!==void 0&&(n[L]=await V(r,o));try{return await t.fetch("https://relay.internal/_lunora/relay",{body:o,headers:n,method:"POST"})}catch{return}}}class he extends P{shapeUniformCache=new Map;relaySetCache;registryCache;recordedBinding;promotionState="owned";constructor(e,s){super(e,{ownerKey:s})}async forwardWhisper(e,s){if(!this.canAddressSiblings())return;const t=this.ownerRelaySet();t.size!==0&&await Promise.all([...t].map(o=>this.postRelayMessage(R(this.roleId.ownerKey,o),{frame:s,topic:e,type:"relay_frame"})))}async onFlush(e,s){this.canAddressSiblings()&&await Promise.all([this.multicastShapePokes(e,s),this.proxyShapePokes(e,s)])}seedRelayShape(){return Promise.resolve(void 0)}announce(){return Promise.resolve()}announceDrain(){return Promise.resolve()}releaseRelayShapes(){return Promise.resolve()}relayCount(){const e=this.host.getWebSockets().length,s=g(this.host.env(),"LUNORA_RELAY_THRESHOLD",T.tUp),t=g(this.host.env(),"LUNORA_RELAY_COLLAPSE_THRESHOLD",T.tDown);if(this.promotionState=B(this.promotionState,e,q(s,t)),this.promotionState==="owned")return 0;const o=g(this.host.env(),"LUNORA_RELAY_FAN",re);return Math.min(this.maxRelays(),Math.max(1,o))}minShapeCursor(){const{cohort:e,proxies:s}=this.relayShapes();let t;for(const o of[...e.values(),...s.values()])t=t===void 0?o.cursor:Math.min(t,o.cursor);return t}isShapeRelayUniform(e,s){const t=E(e,s),o=this.shapeUniformCache.get(t);if(o!==void 0)return o;const n=this.probeShapeRelayUniform(e,s);return this.shapeUniformCache.set(t,n),n}onShapeUnsubscribe(e){const{proxies:s}=this.relayShapes(),t=e.subId===void 0?void 0:M(e.relayIndex,e.connectionId,e.subId);for(const[o,n]of s)n.relayIndex!==e.relayIndex||n.connectionId!==e.connectionId||(t===void 0||o===t)&&s.delete(o);U(this.host.sql(),e.relayIndex,e.connectionId,e.subId)}onAttach(e){this.addRelayToSet(e)}onDetach(e){this.removeRelayFromSet(e)}async onWhisperFrame(e){await Promise.all([...this.ownerRelaySet()].filter(s=>s!==e.originRelay).map(s=>this.postRelayMessage(R(this.roleId.ownerKey,s),{frame:e.frame,topic:e.topic,type:"relay_frame"})))}onShapeSubscribe(e){return this.buildShapeSeedFrames(e)}onShapePoke(){return{delivered:0,matched:0}}buildShapePoke(e,s,t,o,n){let r;try{r=this.host.resolveShape(e.name,e.args,s)}catch{return}if(r===void 0||r.global===!0||!t.has(r.table))return;const a=e,h=a.cursor,c=this.host.buildShapeDiff(r,h,o);if(c.length!==0)return a.cursor=o,w(this.host.sql(),a.key,o),{args:N(e.args),checkpoint:o,epoch:n,fromCursor:h,name:e.name,rowsPatch:X(c),type:"relay_shape_poke"}}async multicastShapePokes(e,s){const t=this.ownerRelaySet();if(t.size===0)return;const{cohort:o}=this.relayShapes();if(o.size===0)return;const n=this.host.currentCdcEpoch(),r=[];for(const a of o.values()){const h=this.buildShapePoke(a,I,e,s,n);h&&r.push(this.multicastToRelays(t,h,a))}await Promise.all(r)}async multicastToRelays(e,s,t){(await Promise.all([...e].map(async n=>(await this.requestRelayMessage(R(this.roleId.ownerKey,n),s))?.ok===!0))).includes(!1)&&this.rewindShapeCursor(t,s.fromCursor)}async proxyShapePokes(e,s){if(this.ownerRelaySet().size===0)return;const{proxies:t}=this.relayShapes();if(t.size===0)return;const o=this.host.currentCdcEpoch(),n=[];for(const r of t.values()){const a=this.buildShapePoke(r,r.identity,e,s,o);a&&n.push(this.proxyToRelay(a,r))}await Promise.all(n)}async proxyToRelay(e,s){(await this.requestRelayMessage(R(this.roleId.ownerKey,s.relayIndex),{...e,targetConnectionId:s.connectionId}))?.ok!==!0&&this.rewindShapeCursor(s,e.fromCursor)}buildShapeSeedFrames(e){const s={identity:e.identity,userId:e.userId};let t;try{t=this.host.resolveShape(e.name,e.args,s)}catch(l){const{body:p}=k(l,{fallbackCode:"SHAPE_RESOLVE_FAILED",redactedMessage:"shape resolution failed"});return{error:{code:p.code,message:p.message}}}if(t===void 0||t.global===!0)return{error:{code:"SHAPE_NOT_FOUND",message:`shape not relayable: ${e.name}`}};e.relayIndex!==void 0&&this.addRelayToSet(e.relayIndex);const{baseCheckpoint:o,cursor:n,epoch:r,reset:a,rowsPatch:h}=this.host.computeOpLogShapeSeed({args:e.args,name:e.name,sinceEpoch:e.sinceEpoch,sinceSeq:e.sinceSeq},t);let c=n;const{cohort:d,proxies:_}=this.relayShapes();if(this.isShapeRelayUniform(e.name,e.args)){const l=E(e.name,e.args);let p=d.get(l);p===void 0&&(p={args:e.args,cursor:n,key:l,name:e.name},d.set(l,p),A(this.host.sql(),p)),c=p.cursor}else if(e.relayIndex!==void 0&&e.connectionId!==void 0){const l=M(e.relayIndex,e.connectionId,e.subId),p={args:e.args,connectionId:e.connectionId,cursor:n,identity:s,key:l,name:e.name,relayIndex:e.relayIndex};_.set(l,p),A(this.host.sql(),p)}else return{error:{code:"RELAY_SHAPE_UNROUTABLE",message:`shape ${e.name} is per-socket on a relay, but the subscribe carries no ${e.relayIndex===void 0?"relay index":"connection id"}`}};const u=O([{reset:a,rowsPatch:h,shapeId:e.subId}],{baseCheckpoint:o,checkpoint:c,epoch:r,lastMutationId:void 0,pokeId:this.host.nextPokeId()});return{cursor:c,epoch:r,frames:u}}ensureRelayTables(){this.host.sql().exec("CREATE TABLE IF NOT EXISTS __lunora_relays (idx INTEGER PRIMARY KEY)"),this.host.sql().exec("CREATE TABLE IF NOT EXISTS __lunora_relay_binding (id INTEGER PRIMARY KEY, binding TEXT NOT NULL)"),K(this.host.sql())}bindingName(){const e=this.host.shardBinding();if(e!==void 0&&e!=="")return e!==this.recordedBinding&&(this.recordedBinding=e,this.ensureRelayTables(),this.host.sql().exec("INSERT INTO __lunora_relay_binding (id, binding) VALUES (1, ?) ON CONFLICT(id) DO UPDATE SET binding = excluded.binding",e)),e;if(this.recordedBinding!==void 0)return this.recordedBinding;try{const s=this.host.sql().exec("SELECT binding FROM __lunora_relay_binding WHERE id = 1").toArray();this.recordedBinding=s[0]?.binding}catch{this.recordedBinding=void 0}return this.recordedBinding}relayShapes(){const e=this.registryCache;if(e!==void 0)return e;this.ensureRelayTables();const s={cohort:new Map,proxies:new Map};for(const t of Y(this.host.sql()))t.relayIndex===void 0||t.connectionId===void 0?s.cohort.set(t.key,{args:t.args,cursor:t.cursor,key:t.key,name:t.name}):s.proxies.set(t.key,{args:t.args,connectionId:t.connectionId,cursor:t.cursor,identity:t.identity??{},key:t.key,name:t.name,relayIndex:t.relayIndex});return this.registryCache=s,s}rewindShapeCursor(e,s){const t=e;t.cursor<=s||(t.cursor=s,w(this.host.sql(),t.key,s))}ownerRelaySet(){if(this.relaySetCache===void 0){this.ensureRelayTables();const e=this.host.sql().exec("SELECT idx FROM __lunora_relays").toArray();this.relaySetCache=new Set(e.map(s=>Number(s.idx)))}return this.relaySetCache}addRelayToSet(e){this.ensureRelayTables(),this.host.sql().exec("INSERT OR IGNORE INTO __lunora_relays (idx) VALUES (?)",e),this.ownerRelaySet().add(e)}removeRelayFromSet(e){this.ensureRelayTables(),this.host.sql().exec("DELETE FROM __lunora_relays WHERE idx = ?",e);const s=this.ownerRelaySet();s.delete(e);const{cohort:t,proxies:o}=this.relayShapes();for(const[n,r]of o)r.relayIndex===e&&o.delete(n);$(this.host.sql(),e),s.size===0&&(t.clear(),this.shapeUniformCache.clear(),W(this.host.sql()))}probeShapeRelayUniform(e,s){let t;try{t=this.host.resolveShape(e,s,I)}catch{return!1}if(t===void 0||t.global===!0||this.host.rlsMetadata().policies.some(c=>c.on==="read"&&c.table===t.table)||this.tableHasAnyMask(t.table))return!1;const o=b(t.effectiveWhere),n=b(t.columns);let r=!1;const a=c=>{const d={groups:[`grp_${c}`],roles:[c],sub:`__lunora_probe_${c}__`};return{identity:new Proxy(d,{get:(u,l)=>typeof l=="symbol"||l in u?Reflect.get(u,l):`${c}:${l}`,getOwnPropertyDescriptor:(u,l)=>(r=!0,Reflect.getOwnPropertyDescriptor(u,l)),has:(u,l)=>typeof l=="symbol"?Reflect.has(u,l):!0,ownKeys:u=>(r=!0,Reflect.ownKeys(u))}),userId:`__lunora_probe_${c}__`}};return[I,a("a"),a("b")].every(c=>{let d;try{d=this.host.resolveShape(e,s,c)}catch{return!1}return d!==void 0&&d.global!==!0&&d.table===t.table&&b(d.effectiveWhere)===o&&b(d.columns)===n})&&!r}tableHasAnyMask(e){return this.host.maskMetadata().columns.some(s=>s.table===e)}}class le extends P{relayAnnounced=!1;relayMemoCache;shapeControl=new Map;constructor(e,s,t){super(e,{ownerKey:s,relayIndex:t})}async forwardWhisper(e,s){this.canAddressSiblings()&&await this.postRelayMessage(this.roleId.ownerKey,{frame:s,originRelay:this.roleId.relayIndex,topic:e,type:"relay_frame"})}onFlush(){return Promise.resolve()}async seedRelayShape(e,s,t,o){if(!this.canAddressSiblings())return{code:"RELAY_MISCONFIGURED",message:"relay cannot address its owner"};const{connectionId:n}=this.host.readAttachment(e),r={args:N(t.args??{}),connectionId:n,identity:o.identity,name:t.name,relayIndex:this.roleId.relayIndex,sinceEpoch:t.sinceEpoch,sinceSeq:t.sinceSeq,subId:s,type:"relay_shape_subscribe",userId:o.userId},a=await this.queueShapeControl(n,async()=>(await this.announce(),this.requestRelayMessage(this.roleId.ownerKey,r)));if(a===void 0)return{code:"RELAY_SEED_FAILED",message:"owner did not answer the shape seed"};let h;try{h=await a.json()}catch{return{code:"RELAY_SEED_FAILED",message:"malformed shape seed from owner"}}if(h.error!==void 0)return h.error;if(h.frames===void 0)return{code:"RELAY_SEED_FAILED",message:"owner returned no shape frames"};await J(e);for(const c of h.frames)x(e,c);return this.recordRelayShapeMemo(e,s,h.cursor??0,h.epoch),"ok"}async announce(){if(this.relayAnnounced||!this.canAddressSiblings())return;this.relayAnnounced=!0,(await this.requestRelayMessage(this.roleId.ownerKey,{relayIndex:this.roleId.relayIndex,type:"relay_attach"}))?.ok||(this.relayAnnounced=!1)}async announceDrain(e){this.host.getWebSockets().some(s=>s!==e)||(this.relayMemos().clear(),oe(this.host.sql()),this.canAddressSiblings()&&(this.relayAnnounced=!1,await this.postRelayMessage(this.roleId.ownerKey,{relayIndex:this.roleId.relayIndex,type:"relay_detach"})))}async releaseRelayShapes(e,s){const{connectionId:t}=this.host.readAttachment(e);t!==void 0&&this.forgetRelayShapeMemos(t,s),!(t===void 0||!this.canAddressSiblings())&&await this.queueShapeControl(t,async()=>this.postRelayMessage(this.roleId.ownerKey,{connectionId:t,relayIndex:this.roleId.relayIndex,...s===void 0?{}:{subId:s},type:"relay_shape_unsubscribe"}))}relayCount(){return 0}isShapeRelayUniform(){return!1}minShapeCursor(){}onAttach(){}onDetach(){}onWhisperFrame(){return Promise.resolve()}onShapeSubscribe(){return{error:{code:"RELAY_CANNOT_SEED",message:"a relay has no op-log to seed from"}}}onShapeUnsubscribe(){}onShapePoke(e){return this.deliverShapePoke(e)}async queueShapeControl(e,s){if(e===void 0)return s();const t=(this.shapeControl.get(e)??Promise.resolve()).then(s,s),o={},n=()=>{this.shapeControl.get(e)===o.chain&&this.shapeControl.delete(e)},r=t.then(n,n);return o.chain=r,this.shapeControl.set(e,r),t}relayMemos(){return this.relayMemoCache===void 0&&(Q(this.host.sql()),this.relayMemoCache=Z(this.host.sql())),this.relayMemoCache}connectionMemos(e){const s=this.relayMemos();let t=s.get(e);return t===void 0&&(t=new Map,s.set(e,t)),t}recordRelayShapeMemo(e,s,t,o){const{connectionId:n}=this.host.readAttachment(e);n!==void 0&&(this.connectionMemos(n).set(s,{cursor:t,epoch:o}),C(this.host.sql(),[{connectionId:n,cursor:t,epoch:o,subId:s}]))}forgetRelayShapeMemos(e,s){if(s===void 0){this.relayMemos().delete(e),se(this.host.sql(),e);return}this.relayMemos().get(e)?.delete(s),te(this.host.sql(),e,s)}deliverShapePoke(e){const s=E(e.name,e.args),t=[];let o=0,n=0;for(const r of this.host.getWebSockets()){const{connectionId:a,shapes:h}=this.host.readAttachment(r);if(h===void 0||a===void 0||e.targetConnectionId!==void 0&&a!==e.targetConnectionId)continue;const c=this.pokeSocketShapes(r,h,this.connectionMemos(a),e,s);n+=c.matched.length,o+=c.sent;for(const d of c.matched)t.push({connectionId:a,cursor:e.checkpoint,epoch:e.epoch,subId:d})}return C(this.host.sql(),t),{delivered:o,matched:n}}pokeSocketShapes(e,s,t,o,n){const r=[];let a=0;for(const[h,c]of Object.entries(s)){const d=t.get(h);if(E(c.name,c.args)!==n||!ie(d,o))continue;const u=O([{baseCheckpoint:d?.cursor,rowsPatch:o.rowsPatch,shapeId:h}],{baseCheckpoint:void 0,checkpoint:o.checkpoint,epoch:o.epoch,lastMutationId:void 0,pokeId:this.host.nextPokeId()},{preEncoded:!0}).map(l=>x(e,l)).every(Boolean);t.set(h,{cursor:o.checkpoint,epoch:o.epoch}),r.push(h),u&&(a+=1)}return{matched:r,sent:a}}}const Ie=i=>{const e=i.doName();if(e===void 0)return;const s=H(e);return s===void 0?new he(i,e):new le(i,s.ownerKey,s.relayIndex)};export{ne as DEFAULT_MAX_RELAYS,he as OwnerRelay,le as RelayMember,Ie as createRelayLink};