@lunora/shard-engine 1.0.0-alpha.37 → 1.0.0-alpha.39
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/conformance/index.mjs +1 -1
- package/dist/index.d.mts +97 -7
- package/dist/index.d.ts +97 -7
- package/dist/index.mjs +1 -1
- package/dist/packem_shared/ADMIN_FUNCTIONS-DZ5yKTXx.mjs +1 -0
- package/dist/packem_shared/CDC_LOG_TABLE-VfPoURHu.mjs +15 -0
- package/dist/packem_shared/DEFAULT_MAX_RELAYS-BPv7jVgK.mjs +1 -0
- package/dist/packem_shared/GlobalPollTick-BNK4o-XT.mjs +1 -0
- package/dist/packem_shared/NotUniqueError-C4DEsHec.mjs +1 -0
- package/dist/packem_shared/SHAPE_POKE_CURSOR_TABLE-BBuXXk5v.mjs +7 -0
- package/dist/packem_shared/ShapeDiffCache-mE7ZzdPr.mjs +1 -0
- package/dist/packem_shared/UNVOUCHABLE_DEP-C68htACn.mjs +1 -0
- package/dist/packem_shared/awaitWsDrain-CeaR5jj8.mjs +1 -0
- package/dist/packem_shared/backfillAggregateIndexes-DDgDYJcc.mjs +1 -0
- package/dist/packem_shared/buildPokeFrames-BhYUbqzO.mjs +1 -0
- package/dist/packem_shared/buildShapeDiff-umdBNFzJ.mjs +1 -0
- package/dist/packem_shared/createReplicaLink-DZZxDW5c.mjs +7 -0
- package/dist/packem_shared/ctx-db-relay-shapes-Jf5xpD1r.mjs +17 -0
- package/dist/packem_shared/{defineEngineContractSuite-iK4MwBOl.mjs → defineEngineContractSuite-C6NKOjJn.mjs} +1 -1
- package/dist/packem_shared/envOptionalPositiveInt-D2pY-c64.mjs +1 -0
- package/dist/packem_shared/{isSoftDeleted-DR79pnU-.mjs → isSoftDeleted-CZirzdQL.mjs} +1 -1
- package/dist/packem_shared/materializeExternalRows-DYE0rlxi.mjs +1 -0
- package/dist/packem_shared/runShardMigrations-C6JwX3Ie.mjs +5 -0
- package/dist/packem_shared/selectShapeMembers-GfRzwoVo.mjs +1 -0
- package/dist/packem_shared/sibling-channel-Cxvk0Zca.mjs +1 -0
- package/package.json +3 -3
- package/dist/packem_shared/ADMIN_FUNCTIONS-2mZJ-FQW.mjs +0 -1
- package/dist/packem_shared/CDC_LOG_TABLE-B58N8NQO.mjs +0 -8
- package/dist/packem_shared/DEFAULT_MAX_RELAYS-tuHNDUZr.mjs +0 -1
- package/dist/packem_shared/NotUniqueError-THUZXy3C.mjs +0 -1
- package/dist/packem_shared/SHAPE_POKE_CURSOR_TABLE-Dh4HfSdC.mjs +0 -7
- package/dist/packem_shared/awaitWsDrain-Cs-1HHP6.mjs +0 -1
- package/dist/packem_shared/backfillAggregateIndexes-DVQ2sVuV.mjs +0 -1
- package/dist/packem_shared/buildPokeFrames-BXejpiII.mjs +0 -1
- package/dist/packem_shared/createReadFootprint-MRH1If3F.mjs +0 -1
- package/dist/packem_shared/createReplicaLink-C1JuP_DN.mjs +0 -7
- package/dist/packem_shared/materializeExternalRows-D5tgL1mR.mjs +0 -1
- package/dist/packem_shared/runShardMigrations-DtIbA812.mjs +0 -5
- package/dist/packem_shared/selectShapeMemberIds-B-pQJHAu.mjs +0 -1
- package/dist/packem_shared/sibling-channel-BRZpLiDA.mjs +0 -1
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{LunoraError as y}from"@lunora/errors";import{s as Ht,c as Nt,j as Je,a as jt,y as Ae,h as Kt}from"./ctx-db-companions-lTt-rvKG.mjs";import{sql as r}from"drizzle-orm";import{d as Ot}from"./wire-codec-BU9T2xJ7.mjs";import{throwingScheduler as Qt,aggregateSqlFunction as ve,normalizeCountArgument as zt}from"./AGGREGATE_SQL_FUNCTION-m1iUU1rv.mjs";import{aggregateTableName as Be,encodeAggregateKey as qe,readAggregateValue as Ue}from"./aggregateTableName-Cy5e03oz.mjs";import{mergeWhere as J,CountRlsUnsupportedError as Pe,selectIndexForGroupBy as Jt,selectIndexForCount as Vt,selectIndexForAggregate as Yt}from"./CountRlsUnsupportedError-Bdfupt3g.mjs";import{backfillSearchIndexesForTable as Xt}from"./backfillAggregateIndexes-DVQ2sVuV.mjs";import{backfillAggregateIndexes as Kr,backfillRankIndexes as Or,backfillSearchIndexes as Qr}from"./backfillAggregateIndexes-DVQ2sVuV.mjs";import{appendCdcChange as Zt}from"./CDC_LOG_TABLE-B58N8NQO.mjs";import{CDC_LOG_TABLE as Jr,applyCdcChanges as Vr,bumpCdcEpoch as Yr,minCdcSeq as Xr,readCdcChanges as Zr,readCdcCursor as eo,readCdcEpoch as to,trimCdcChanges as no}from"./CDC_LOG_TABLE-B58N8NQO.mjs";import{allocateCommitSeq as en,COMMIT_SEQ_FIELD as tn}from"./COMMIT_SEQ_FIELD-CSe_oNZu.mjs";import{isMemoryTable as nn}from"./clearMemoryTables-CXULwypv.mjs";import{computeRankPage as dt}from"./computeRankPage-Bby1Npkd.mjs";import{SCAN_DEP as H}from"./SCAN_DEP-D7qE3iUe.mjs";import{runDrizzle as q}from"./runDrizzle-it6rL9bR.mjs";import{D as K,k as se,r as de,b as Ie,A as Ge,a as Ce,e as V,t as It,f as lt,i as rn,h as Ct,g as on}from"./do-sql-Dk_DJxn4.mjs";import{WORKERD_SQLITE_LIMITS as xt,unionAll as Ke,sqliteInList as sn}from"./param-Ib8WHnrF.mjs";import{coveringGeohashes as cn,boundingBoxGeohashes as an,haversineMeters as dn,pointInBoundingBox as ln}from"./GEO_DEFAULT_PRECISION-CqpQZ-J_.mjs";import{NotFoundError as un}from"./NotFoundError-BhF7FeFr.mjs";import{softDeleteScope as ae,normalizeOrderKeys as fn,buildSeekWhere as Mt,decodeCursor as Oe,applySelect as ut,encodeCursor as Qe,buildSeekBeforeWhere as hn}from"./applySelect-BQbHyo-W.mjs";import{rankTableName as ft,sortColumnName as ht,resolveRankPartition as wn,encodePartitionKey as pn,RANK_TIEBREAK as gn}from"./RANK_TIEBREAK-ci3MaM65.mjs";import{indexKeysForRow as $n,buildIndexRange as yn}from"./buildIndexRange-CBKQmHSS.mjs";import{assertFlatPredicate as He,resolveRelationPredicates as wt}from"./DEFAULT_MAX_RELATION_KEYS-BAWGIEvC.mjs";import{runRowValidators as Ne,resolveWith as pt,relationHooks as gt,applyOnDelete as En,fanOutScalarCounts as mn}from"./applyOnDelete-BlcwKjuO.mjs";import{guardWriter as Sn}from"./RLS_UNWRAP_SYMBOL-BWloGsd3.mjs";import{i as _n}from"./sql-projection-BqmxFxQU.mjs";import{createSystemReader as Rn}from"./createSystemReader-BtYeSMDb.mjs";import{ConflictError as pe}from"./ConflictError-C8GtJmjS.mjs";import{runTriggers as Tn}from"./hasTrigger-CjlwI4le.mjs";import{compileWhereSql as te}from"./compileWhereSql-JBpSfQm9.mjs";import{CLIENT_WATERMARK_TABLE as oo,advanceClientWatermark as io,migrateClientWatermark as so,readClientWatermark as co}from"./CLIENT_WATERMARK_TABLE-BoS1HEqz.mjs";import{GLOBAL_SHAPE_SNAPSHOT_TABLE as lo,deleteGlobalShapeSnapshot as uo,deleteGlobalShapeSnapshotsForConnection as fo,migrateGlobalShapeSnapshot as ho,readGlobalShapeSnapshot as wo,writeGlobalShapeSnapshot as po}from"./GLOBAL_SHAPE_SNAPSHOT_TABLE-NWaL77m5.mjs";import{IDEMPOTENCY_TABLE as $o,readIdempotent as yo,trimIdempotent as Eo,writeIdempotent as mo}from"./IDEMPOTENCY_TABLE-DKVe2Ohf.mjs";import{runShardMigrations as _o}from"./runShardMigrations-DtIbA812.mjs";import{SEARCH_STATE_TABLE as To}from"./SEARCH_STATE_TABLE-Dju8ebbU.mjs";import{selectShapeMemberIds as vo,selectShapeRows as Io}from"./selectShapeMemberIds-B-pQJHAu.mjs";import{serializeSqlValue as oe}from"./serializeSqlValue-DbI1VQYM.mjs";import{quoteIdentifier as An}from"./quoteIdentifier-CObIFRhb.mjs";const vn=o=>{const i=new TextEncoder().encode(o);let t="";for(const a of i)t+=String.fromCodePoint(a);return btoa(t)},In=o=>{const i=atob(o),t=Uint8Array.from(i,a=>a.codePointAt(0)??0);return new TextDecoder().decode(t)},Cn=()=>new y("BAD_REQUEST","invalid cursor"),$t=16,yt=8,X=1024,Ve=(o,i)=>i.query(o),xn=(o,i,t)=>{const a=Ht(o,t);if(a.length===0)return 0;let f=0;for(const[p,E]of i.entries()){const R=p===i.length-1;let S=0;for(const $ of a)(R?$.startsWith(E):$===E)&&(S+=1);if(S===0)return 0;f+=S}return f},Mn=(o,i)=>{if(!i)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 f=o.slice(0,o.length-t.length);return{exact:!1,lower:o,upper:f+String.fromCodePoint(a)}},bn=(o,i,t)=>{const a={eq:(f,p)=>{if(!o.definition.filterFields?.includes(f))throw new y("INTERNAL",`field "${f}" is not a filter field of search index "${o.indexName}" on table "${i}"`);if(o.filters.length>=yt)throw new y("BAD_REQUEST",`search index "${o.indexName}" on table "${i}": at most ${String(yt)} .eq() filters are supported per search query`);return o.filters.push({field:f,value:p}),a},search:(f,p)=>{const E=o;if(f!==E.definition.field)throw new y("INTERNAL",`search index "${E.indexName}" on table "${i}" indexes "${E.definition.field}", not "${f}"`);const R=Ve(p,t).length;if(R>$t)throw new y("BAD_REQUEST",`search index "${E.indexName}" on table "${i}": at most ${String($t)} search terms are supported (got ${String(R)})`);return E.field=f,E.query=p,E.hasQuery=!0,a}};return a},Dn=o=>{if(o.length>X)throw new y("BAD_REQUEST",`more than ${String(X)} documents match this search — narrow it with filters or read it a page at a time with .paginate()`)},kn=o=>Math.min(o.offset+o.numItems+1,X),Ln=o=>vn(`search:${String(o)}`),Fn=o=>{let i;try{i=In(o)}catch{return}if(!i.startsWith("search:"))return;const t=Number(i.slice(7));return Number.isInteger(t)&&t>=0?t:void 0},Wn=o=>{if(typeof o.endCursor=="string")throw new y("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 y("BAD_REQUEST",`search pagination needs a finite numItems, got ${String(o.numItems)}`);const i=Math.max(0,Math.floor(o.numItems)),t=o.cursor?Fn(o.cursor):0;if(t===void 0)throw Cn();if(t+i>=X)throw new y("BAD_REQUEST",`search pagination reaches the ${String(X)}-document limit (offset ${String(t)} + ${String(i)} requested) — a page must end below the cap so the probe row that answers \`hasMore\` still fits: retry with numItems ${String(Math.max(1,X-t-1))} or fewer, or narrow the query or the filters instead`);return{numItems:i,offset:t}},Bn=(o,i)=>{const t=i.offset+i.numItems,a=i.numItems>0&&o.length>t;return{continueCursor:a?Ln(t):null,isDone:!a,page:o.slice(i.offset,t)}},qn=o=>{if(o===void 0)return X+1;if(!Number.isFinite(o))return X;const i=Math.max(0,Math.floor(o));if(i>X)throw new y("BAD_REQUEST",`search returns at most ${String(X)} documents (asked for ${String(i)}) — narrow the query or paginate instead`);return i},Un=/^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/iu,Pn=o=>{if(!Un.test(o))throw new y("INTERNAL",`invalid clientId ${JSON.stringify(o)}: a client-supplied row id must be a UUID`)},Et=50,bt=500,xe=Math.floor(xt.boundParams/3),we=xt.boundParams,Gn=128,ce=(o,i,t)=>{const a=i??bt;if(o>a)throw new y("BATCH_LIMIT_EXCEEDED",`${t}: batch of ${String(o)} exceeds the limit of ${String(a)} (raise options.limit or chunk the call)`,{status:400})},Hn=o=>{const i={eq:(t,a)=>(o.sqlConditions.push({comparator:"=",field:t,value:a}),i),gt:(t,a)=>(o.sqlConditions.push({comparator:">",field:t,value:a}),i),gte:(t,a)=>(o.sqlConditions.push({comparator:">=",field:t,value:a}),i),lt:(t,a)=>(o.sqlConditions.push({comparator:"<",field:t,value:a}),i),lte:(t,a)=>(o.sqlConditions.push({comparator:"<=",field:t,value:a}),i)};return i},Nn=o=>Math.max(o,X),Dt=(o,i)=>{const t=o.filters.map(a=>r`${V(a.field)} = ${oe(a.value)}`);return i&&t.push(i),t},jn=(o,i,t,a,f)=>{const p=Ve(t.query,Je(t.definition.language));if(p.length===0)return[];const E=jt(i,t.indexName),R=`${E}__vocab`,S=p.length-1,$=p.map((W,M)=>{const N=Mn(W,M===S),j=N.exact?r`${r.identifier("term")} = ${N.lower}`:r`${r.identifier("term")} >= ${N.lower} AND ${r.identifier("term")} < ${N.upper}`;return r`SELECT ${r.identifier("doc")}, ${r.raw(String(M))} AS ${r.identifier("__term__")}, COUNT(*) AS ${r.identifier("__n__")} FROM ${r.identifier(R)} WHERE ${j} GROUP BY ${r.identifier("doc")}`}),L=p.map((W,M)=>r`SUM(CASE WHEN u.${r.identifier("__term__")} = ${r.raw(String(M))} THEN u.${r.identifier("__n__")} ELSE 0 END)`),T=r`SELECT f.${r.identifier(Ae)} AS ${r.identifier(Ae)}, ${r.join(L,r` + `)} AS ${r.identifier("__score__")} FROM (${Ke($)}) u JOIN ${r.identifier(E)} f ON f.rowid = u.${r.identifier("doc")} GROUP BY f.${r.identifier(Ae)} HAVING ${r.join(L.map(W=>r`${W} > 0`),r` AND `)}`,v=Dt(t,f);let _=r`SELECT m.id, m._creationTime, m.${r.identifier(K)}, s.${r.identifier("__score__")} AS ${r.identifier("__score__")} FROM (${T}) s JOIN ${r.identifier(i)} m ON m.id = s.${r.identifier(Ae)}`;v.length>0&&(_=r`${_} WHERE ${r.join(v,r` AND `)}`),_=r`${_} ORDER BY s.${r.identifier("__score__")} DESC, m._creationTime DESC, m.id ASC LIMIT ${r.raw(String(a))}`;const F=[];for(const W of q(o,_)){const M=Ct(W);if(M){const N=W.__score__;F.push({document:M,score:typeof N=="number"?N:Number(N??0)})}}return F},Kn=(o,i,t,a,f)=>{const p=Je(t.definition.language),E=Ve(t.query,p);if(E.length===0)return[];const R=Dt(t,f);let S=r`SELECT id, _creationTime, ${r.identifier(K)} FROM ${r.identifier(i)}`;R.length>0&&(S=r`${S} WHERE ${r.join(R,r` AND `)}`),S=r`${S} ORDER BY _creationTime DESC, id ASC LIMIT ${r.raw(String(Nn(a)))}`;const $=q(o,S).toArray(),L=[];for(const T of $){const v=Ct(T);if(!v)continue;const _=xn(Kt(v,t.definition),E,p);_>0&&L.push({creationTime:typeof v._creationTime=="number"?v._creationTime:0,doc:v,id:typeof v._id=="string"?v._id:"",score:_})}return L.sort((T,v)=>v.score-T.score||v.creationTime-T.creationTime||T.id.localeCompare(v.id)),L.slice(0,a).map(T=>({document:T.doc,score:T.score}))},je=(o,i,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 y("BAD_REQUEST",`geo index "${a}" on table "${t}": ${i} must have a finite lat in [-90, 90] and lng in [-180, 180]`)},On=(o,i)=>{const t=o,a={near:(f,p)=>{if(t.within)throw new y("INTERNAL",`geo index "${t.indexName}" on table "${i}": call .near() or .within(), not both`);if(je(f,".near() point",i,t.indexName),!Number.isFinite(p)||p<=0)throw new y("BAD_REQUEST",`geo index "${t.indexName}" on table "${i}": .near() radiusMeters must be a finite number > 0, got ${String(p)}`);return t.near={point:{lat:f.lat,lng:f.lng},radiusMeters:p},a},within:f=>{if(t.near)throw new y("INTERNAL",`geo index "${t.indexName}" on table "${i}": call .near() or .within(), not both`);if(je(f.sw,".within() sw corner",i,t.indexName),je(f.ne,".within() ne corner",i,t.indexName),f.sw.lat>f.ne.lat)throw new y("BAD_REQUEST",`geo index "${t.indexName}" on table "${i}": .within() corners are transposed (sw.lat > ne.lat)`);if(f.sw.lng>f.ne.lng)throw new y("BAD_REQUEST",`geo index "${t.indexName}" on table "${i}": .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:f.ne.lat,lng:f.ne.lng},sw:{lat:f.sw.lat,lng:f.sw.lng}},a}};return a},Qn=(o,i)=>{const t=o[i];if(t===null||typeof t!="object")return;const{lat:a,lng:f}=t;return typeof a=="number"&&typeof f=="number"?{lat:a,lng:f}:void 0},zn=(o,i)=>{const t=Qn(o,i.definition.field);if(!t)return;const a=typeof o._creationTime=="number"?o._creationTime:0;if(i.near){const f=dn(i.near.point,t);return f<=i.near.radiusMeters?{creationTime:a,distance:f}:void 0}return ln(t,i.within)?{creationTime:a,distance:0}:void 0},Jn=(o,i,t,a)=>{if(!t.near&&!t.within)throw new y("INTERNAL",`geo index "${t.indexName}" on table "${i}": call .near(point, radius) or .within(box)`);const f=t.near?cn(t.near.point,t.near.radiusMeters):an(t.within),p=on(i,t.indexName),E=f.map(T=>r`(g.${r.identifier("__geohash__")} >= ${T} AND g.${r.identifier("__geohash__")} < ${`${T}{`})`),R=[r`(${r.join(E,r` OR `)})`];a&&R.push(a);const S=r`SELECT m.id, m._creationTime, m.${r.identifier(K)} FROM ${r.identifier(p)} g JOIN ${r.identifier(i)} m ON m.id = g.${r.identifier("__id__")} WHERE ${r.join(R,r` AND `)}`,$=q(o,S).toArray(),L=[];for(const T of $){const v=de(T),_=v?zn(v,t):void 0;v&&_&&L.push({creationTime:_.creationTime,distance:_.distance,doc:v})}return L.sort((T,v)=>T.distance-v.distance||v.creationTime-T.creationTime),L},kt=(o,i,t,a)=>{const f=[];for(const p of o)if(i.every(E=>E(a(p)))&&(f.push(p),typeof t=="number"&&f.length>=t))break;return f},Vn=(o,i,t,a,f,p=()=>{})=>{const E=t.within!==void 0,R=Jn(o,i,t,f).map(S=>({distanceMeters:E?null:S.distance,document:S.doc}));return p(R.length),typeof a=="number"?R.slice(0,Math.max(0,Math.floor(a))):R},Lt=(o,i,t,a,f,p=()=>{})=>{const{geo:E}=t;if(!E)throw new y("INTERNAL","runGeoTerminalScored called without a staged geo query");const R=t.inMemoryFilters.length>0,S=Vn(o,i,E,R?void 0:f,a,p);return R?kt(S,t.inMemoryFilters,f,$=>$.document):S},Yn=(o,i,t,a,f,p=()=>{})=>Lt(o,i,t,a,f,p).map(E=>E.document),Xn=(o,i,t,a,f,p,E=()=>{})=>{const R=[];for(const T of t.sqlConditions)R.push(r`${V(T.field)} ${r.raw(T.comparator)} ${oe(T.value)}`);a&&R.push(a);let S=r`SELECT id, _creationTime, ${r.identifier(K)} FROM ${r.identifier(i)}`;R.length>0&&(S=r`${S} WHERE ${r.join(R,r` AND `)}`),S=r`${S} ORDER BY ${f}`,typeof p=="number"&&t.inMemoryFilters.length===0&&(S=r`${S} LIMIT ${r.raw(String(Math.max(0,Math.floor(p))))}`);const $=q(o,S).toArray();E($.length);const L=[];for(const T of $){const v=de(T);if(v&&t.inMemoryFilters.every(_=>_(v))&&(L.push(v),typeof p=="number"&&L.length>=p))break}return L},re={fieldRef:V,serialize:oe},Ft=(o,i)=>{const t=i===void 0?void 0:o.shape[i];return t!==void 0&&_n(t)},mt=(o,i)=>i.some(t=>Ft(o,t)),St=(o,i,t)=>{if(Ft(o,i))throw new y("BAD_REQUEST",`${t}: "${i}" is stored as an order-preserving key, which SQL cannot reduce or group — declare an aggregateIndex covering this (by, field, op) so the maintained companion answers it`)},Zn=o=>{let i=0;const t=[],a={fieldRef:V,relationExists:f=>{const{childWhere:p,negated:E,parentTable:R,relation:S}=f,$=`__rel_${String(i)}`,L=t.at(-1)??R;i+=1,o(S.table,H);const T=S.kind==="one"?S.field:S.references,v=S.kind==="one"?S.references:S.field,_=r`${lt($,v)} = ${lt(L,T)}`;t.push($);const F=te(p,a);t.pop();const W=F?r`${_} AND ${F}`:_,M=r`EXISTS (SELECT 1 FROM ${r.identifier(S.table)} AS ${r.identifier($)} WHERE ${W})`;return E?r`NOT ${M}`:M},serialize:oe};return a},Wt=o=>{const i=o.map(t=>r`${V(t.field)} ${r.raw(t.direction==="desc"?"DESC":"ASC")}`);return o.some(t=>t.field==="_id"||t.field==="id")||i.push(r`${V("id")} ASC`),r.join(i,r`, `)},er={"<":"lt","<=":"lte","=":"eq",">":"gt",">=":"gte"},tr=o=>{const i=o.order;return o.indexFields.length>0?o.indexFields.map(t=>({direction:i,field:t})):[{direction:i,field:"_creationTime"}]},nr=(o,i,t,a)=>{const f=o.sqlConditions.map(p=>({[p.field]:{[er[p.comparator]??"eq"]:p.value}}));if(t&&f.push(Mt(i,Oe(t))),a&&f.push(hn(i,Oe(a))),f.length!==0)return f.length===1?f[0]:{AND:f}},rr=(o,i,t)=>{const a=[];for(const f of o){const p=de(f);if(p&&i.every(E=>E(p))&&(a.push(p),t!==void 0&&a.length>t))break}return a},or=(o,i,t,a,f,p=()=>{})=>{const E=Math.max(0,Math.floor(a.numItems)),R=tr(t),S=typeof a.endCursor=="string",$=te(nr(t,R,a.cursor,a.endCursor),re),L=f&&$?r`${$} AND ${f}`:f??$;let T=r`SELECT id, _creationTime, ${r.identifier(K)} FROM ${r.identifier(i)}`;L&&(T=r`${T} WHERE ${L}`),T=r`${T} ORDER BY ${Wt(R)}`;const v=t.inMemoryFilters.length>0;!v&&!S&&(T=r`${T} LIMIT ${r.raw(String(E+1))}`);const _=q(o,T).toArray();p(_.length);const F=rr(_,t.inMemoryFilters,v||S?void 0:E);if(S){const j=F.length>=2?F[Math.floor(F.length/2)-1]:void 0;return{continueCursor:a.endCursor??null,isDone:!0,page:F,splitCursor:j?Qe(j,R):null}}const W=F.length>E,M=W?F.slice(0,E):F,N=M.at(-1);return{continueCursor:W&&N?Qe(N,R):null,isDone:!W,page:M}};class ir extends y{constructor(i="unique() found more than one matching document"){super("NOT_UNIQUE",i,{name:"NotUniqueError"})}}const sr=/\s/u,cr=String.fromCodePoint(0),_t=(o,i,t)=>{if(!o.tables[i])throw new y("INTERNAL",`unknown table: ${i}`);return typeof t!="string"||t.length===0||sr.test(t)||t.includes(cr)?null:t},ar=(o,i,t,a=()=>{},f=()=>{},p=()=>{})=>{const E=i.tables[t];if(!E)throw new y("INTERNAL",`unknown table: ${t}`);const R=ae(E.softDeleteMode,void 0),S=R?te(R,re):void 0,$={indexFields:[],indexName:void 0,inMemoryFilters:[],order:"asc",sqlConditions:[]};let L=0;const T=m=>{const{search:b}=$;if(!b)throw new y("INTERNAL","runSearchFetch called without a staged search");Xt(o,t,E);const k=$.inMemoryFilters.length>0,C=qn(k?void 0:m),O=rn(o)?jn(o,t,b,C,S):Kn(o,t,b,C,S);return k?(L=O.length,kt(O,$.inMemoryFilters,m,be=>be.document)):(m===void 0&&Dn(O),O)},v=m=>T(m).map(b=>b.document),_=m=>{const b=Wn(m);return Bn(v(kn(b)),b)},F=()=>{const m=$.indexFields.length>0?$.indexFields:["_creationTime"],b=$.order==="desc"?"DESC":"ASC";return r.join(m.map(k=>r`${V(k)} ${r.raw(b)}`),r`, `)},W=()=>{if($.search||$.geo||$.indexName===void 0){f(void 0);return}f(yn(t,$.indexName,$.indexFields,$.sqlConditions,oe))},M=m=>{W();let b=0;const k=(()=>{if($.search){const C=v(m);return b=L,C}return $.geo?Yn(o,t,$,S,m,C=>{b=C}):Xn(o,t,$,S,F(),m,C=>{b=C})})();return p(Math.max(b,k.length)),k},N=()=>{if(!$.search&&!$.geo)throw new y("INTERNAL",`ctx.db.query("${t}").collectWithScores() requires a staged .withSearchIndex(...) or .withGeoIndex(...)`);W();let m=0;const b=(()=>{if($.search){const k=T(void 0);return m=L,k}return Lt(o,t,$,S,void 0,k=>{m=k})})();return p(Math.max(m,b.length)),b},j={async*[Symbol.asyncIterator](){const m=[...$.inMemoryFilters];let b;$.inMemoryFilters=[];try{for(;;){const k=await j.paginate({cursor:b??null,numItems:Gn});for(const C of k.page)m.every(O=>O(C))&&(yield C);if(k.isDone||k.continueCursor===null)return;b=k.continueCursor}}finally{$.inMemoryFilters=m}},async collect(){return M(void 0)},async collectWithScores(){return N()},filter(m){return $.inMemoryFilters.push(m),j},async first(){return M($.inMemoryFilters.length>0?void 0:1)[0]??null},order(m){return $.order=m==="desc"?"desc":"asc",j},async paginate(m){let b=0;if(W(),$.search){const C=_(m);return p(C.page.length),C}if($.geo)throw new y("INTERNAL","pagination is not supported on geo queries; use .take(n) or .collect()");const k=or(o,t,$,m,S,C=>{b=C});return p(Math.max(b,k.page.length)),k},async take(m){return M(m)},async unique(){const m=M($.inMemoryFilters.length>0?void 0:2);if(m.length>1)throw new ir(`unique() on table "${t}" matched ${String(m.length)} documents; expected at most one`);return m[0]??null},withGeoIndex(m,b){const k=(E.geoIndexes??[]).find(O=>O.name===m);if(!k)throw new y("INTERNAL",`unknown geo index "${m}" on table "${t}"`);a(t,m,"geo");const C={definition:k,indexName:m};if($.geo=C,b(On(C,t)),!C.near&&!C.within)throw new y("INTERNAL",`geo index "${m}" on table "${t}" requires a .near(point, radius) or .within(box) call`);return j},withIndex(m,b){const k=E.indexes.find(C=>C.name===m);if(!k)throw new y("INTERNAL",`unknown index "${m}" on table "${t}"`);return a(t,m,"index"),$.indexName=m,$.indexFields=k.fields,b&&b(Hn($)),j},withSearchIndex(m,b){const k=(E.searchIndexes??[]).find(O=>O.name===m);if(!k)throw new y("INTERNAL",`unknown search index "${m}" on table "${t}"`);a(t,m,"search");const C={definition:k,field:k.field,filters:[],hasQuery:!1,indexName:m,query:""};if($.search=C,b(bn(C,t,Je(k.language))),!C.hasQuery)throw new y("INTERNAL",`search index "${m}" on table "${t}" requires a .search(field, query) call`);return j}};return j},Rt=(o,i,t)=>{const a={...i};for(const[f,p]of It(o)){if(p.serverDefault){a[f]=p.serverDefault({auth:t});continue}a[f]===void 0&&(p.defaultFn?a[f]=p.defaultFn():"defaultValue"in p&&(a[f]=p.defaultValue))}return a},Tt=(o,i,t,a)=>{const f=t;for(const[p,E]of It(o)){if(E.serverDefault){p in i&&(f[p]=E.serverDefault({auth:a}));continue}E.onUpdateFn&&!(p in i)&&(f[p]=E.onUpdateFn())}},At=(o,i)=>{for(const t of Object.keys(i))if(i[t]===void 0)throw new y("INTERNAL",`Cannot ${o} field '${t}' to undefined — use null to clear a nullable field, or omit the key to leave it unchanged.`)},dr=/unique constraint failed/i,lr=o=>o instanceof Error&&dr.test(o.message),ze=(o,i,t)=>{try{q(o,t)}catch(a){throw lr(a)?new pe(`unique constraint violation on "${i}"`,"unique"):a}},Me=(o,i,t)=>{if(ze(o,i,t),q(o,r`SELECT changes() AS changed`).one().changed===0)throw new pe(`optimistic concurrency conflict on "${i}" — the row changed during this mutation; refetch and retry`,"occ")},vt=(o,i,t,a,f,p,E)=>{const R=[];for(let T=0;T<t.length+1;T+=1){const v=[];for(let M=0;M<T;M+=1)v.push(r`${r.identifier(t[M])} IS ${p[M]}`);const _=t[T],F=a[T];if(_!==void 0&&F!==void 0){const M=F.direction==="desc"?">":"<";v.push(r`${r.identifier(_)} ${r.raw(M)} ${p[T]}`)}else v.push(r`${r.identifier(gn)} < ${E}`);const[W]=v;R.push(v.length===1&&W!==void 0?W:r`(${r.join(v,r` AND `)})`)}const S=r.join(R,r` OR `),$=q(o,r`SELECT COUNT(*) AS c FROM ${r.identifier(i)} WHERE ${r.identifier("__partition__")} = ${f} AND (${S})`).one(),L=q(o,r`SELECT COUNT(*) AS c FROM ${r.identifier(i)} WHERE ${r.identifier("__partition__")} = ${f}`).one();return{before:$.c,total:L.c}},Hr=o=>{const{sql:i}=o,{schema:t}=o,a=o.broadcast??(()=>{});let f;const p=()=>o.inTransaction?.()===!0,E=e=>t.tables[e]?.commitOrderedMode!==!0?{}:((f===void 0||!p())&&(f=en(i)),{[tn]:f}),R=(e,...n)=>{const s=t.tables[e]?.indexes;if(!s||s.length===0)return;const u=[];for(const h of n)h&&u.push(...$n(s,h,oe));return u.length>0?u:void 0},{headroom:S}=o;let $=!1;const L=async e=>{const n=$;$=!0;try{return await e()}finally{$=n}},T=o.onRead??(()=>{}),v=o.onReadRange??(e=>{T(e.table,H)}),_=(e,n)=>{n!==void 0&&n!==H&&!$&&S?.recordRead(1),T(e,n)},F=o.onIndexUse??(()=>{}),W=o.onWrite??(()=>{}),M=e=>{$||S?.recordWrite(e)},N=async e=>{M(e.doc),await W(e)},{cache:j}=o,m=o.clock??(()=>Date.now()),b=o.idGenerator??(()=>crypto.randomUUID()),k=o.scheduler??Qt,{globalDb:C}=o,O=o.auth??{identity:null,userId:null},be=o.cdc??!1,De=k,Bt=Rn({scheduler:typeof De.list=="function"&&typeof De.get=="function"?De:void 0,storage:o.storage}),le=(e,n,s,u)=>{be&&!nn(t.tables[e])&&Zt(i,m(),e,n,s,u)},ie=e=>t.tables[e]?.shardMode?.kind==="global",Ye=(e,n)=>{if(ie(e)){if(!C)throw new y("INTERNAL",`cross-backend ${n} for global table '${e}' requires a globalDb writer — pass one to createShardCtxDb({ globalDb })`);return C}return U},ke=e=>Ye(e,"cascade"),z=(e,n)=>{if(ie(e)){if(!C)throw new y("INTERNAL",`${n} on global table '${e}' requires a globalDb writer — pass one to createShardCtxDb({ globalDb })`);return C}},Xe=async(e,n,s,u,h)=>{h&&M(s);const l=await e.insert(n,s,u);return a({key:l,op:"insert",row:{...s,_id:l},table:n}),l},Le=(e,n)=>Ye(e,"relation load").findMany(e,n),Ze=(e,n)=>(ie(e)&&_(e,H),Le(e,n)),qt=e=>!ie(e.table),et=o.relationExistsPushDown??"auto",tt=et!=="never",{maxRelationKeys:nt}=o,ge=(e,n,s)=>wt(e,{fetcher:Ze,maxRelationKeys:nt,relationBaseWhere:s,schema:t,tableName:n}),rt=async(e,n,s,u)=>{const h=z(e,"relation grouped count");if(h)return _(e,H),mn((B,I)=>h.count(B,I),e,n,s,u);const l=t.tables[e];if(!l)throw new y("INTERNAL",`unknown table: ${e}`);_(e,H);const c=ae(l.softDeleteMode,void 0),d={[n]:{in:s}},w=J(J(d,u),c),A=await ge(w,e,void 0),g=te(A,re),x=V(n);let D=r`SELECT ${x} AS __fk__, COUNT(*) AS count FROM ${r.identifier(e)}`;g&&(D=r`${D} WHERE ${g}`),D=r`${D} GROUP BY ${x}`;const P=q(i,D).toArray();return new Map(P.map(B=>[B.__fk__,B.count]))};let $e=0;const ot=new Set;for(const[e,n]of Object.entries(t.tables))for(const s of Object.values(n.triggerMap??{}))ot.add(`${e} ${s.timing} ${s.op}`);const Z=(e,n,s)=>ot.has(`${e} ${n} ${s}`),ee=async(e,n,s)=>{if($e+=1,$e>Et)throw $e-=1,new pe(`trigger recursion exceeded ${String(Et)} levels on "${s.table}" — check for a self-triggering write`,"trigger");try{await Tn({ctx:Pt,event:s,op:n,schema:t,tableName:s.table,timing:e})}finally{$e-=1}},{ensureBackfilledForTable:ue,ensureBackfilledIndex:Fe,ensureRankBackfilled:We,ensureRankBackfilledForTable:fe,syncAggregates:ye,syncCompanionsForInsert:it,syncGeo:Ee,syncRanks:he,syncSearch:me}=Nt({broadcast:a,indexKeysFor:(e,n)=>R(e,n),invalidateCache:(e,n,s)=>j?.invalidate(e,n,R(e,s)),recordCdc:le,schema:t,sql:i}),st=(e,n,s)=>{const{shardMode:u}=n;if(u?.kind==="shardBy"&&!(u.field!==void 0&&(s.partitionBy??[]).includes(u.field)))throw Object.assign(new Error(`rank index "${s.name}" on "${e}" partitions across shards (shard key "${u.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})},ct=e=>Object.entries(t.tables).filter(([,n])=>n.shardMode?.kind!=="global").map(([n])=>n).filter(n=>e===void 0||n===e),ne=(e,n)=>{const s=ct(n);for(let u=0;u<s.length;u+=we){const h=s.slice(u,u+we).map(g=>r`SELECT ${r.raw(`'${g.replaceAll("'","''")}'`)} AS __t__, id, _creationTime, ${r.identifier(K)} FROM ${r.identifier(g)} WHERE id = ${e}`),[l]=q(i,r`${Ke(h)} LIMIT 1`).toArray();if(!l)continue;const c=l.__t__,d=de(l);if(typeof c!="string"||!d)return;const w=l[K];return{docJson:typeof w=="string"?w:se(w??{}),row:d,tableName:c}}},Ut=(e,n)=>{const s=[...new Set(e)],u=new Map;if(s.length===0)return u;const h=ct(n);for(let l=0;l<h.length;l+=we){const c=h.slice(l,l+we),d=Math.floor(we/c.length),w=sn(r`${r.identifier("id")}`,s,!1,d),A=c.map(g=>r`SELECT ${r.raw(`'${g.replaceAll("'","''")}'`)} AS __t__, id FROM ${r.identifier(g)} WHERE ${w}`);for(const g of q(i,Ke(A))){const{id:x,__t__:D}=g;typeof D=="string"&&typeof x=="string"&&u.set(x,D)}}return u},at={assertRankPartitionLocal:st,ensureRankBackfilled:We,onRead:_,rowToDocument:de,schema:t,sql:i},U={system:Bt,async aggregate(e,n){const s=z(e,"aggregate");if(s)return _(e,H),s.aggregate(e,n);const u=t.tables[e];if(!u)throw new y("INTERNAL",`unknown table: ${e}`);if(ve(n.op),n.op==="count")return U.count(e,{baseWhere:n.baseWhere,relationBaseWhere:n.relationBaseWhere,restrictsCounts:n.restrictsCounts,where:n.where});if(!n.field)throw new y("INTERNAL",`aggregate(${e}, { op: "${n.op}" }): "field" is required for non-count reducers`);_(e,H);const h=ae(u.softDeleteMode,void 0),l=J(J(n.baseWhere,n.where),h),c=await ge(l,e,n.relationBaseWhere),d=c!==l;if(u.aggregateIndexes&&!n.baseWhere&&!d&&(!h||mt(u,[n.field]))){const B=Yt(u.aggregateIndexes,n.op,n.field,n.where);if(B){Fe(e,B.index);const I=qe(B.index.by??[],B.key),Q=Be(e,B.index.name),Y=q(i,r`SELECT ${Ie} AS value, ${Ge} AS count FROM ${r.identifier(Q)} WHERE ${Ce} = ${I}`).toArray()[0];return Ue(n.op,Y)}}St(u,n.field,`aggregate(${e}, { op: "${n.op}", field: "${n.field}" })`);const w=te(c,re),A=ve(n.op),g=V(n.field);let x=r`SELECT ${r.raw(A)}(${g}) AS value FROM ${r.identifier(e)}`;w&&(x=r`${x} WHERE ${w}`);const P=q(i,x).toArray()[0]?.value;return P??null},asId(e,n){const s=_t(t,e,n);if(s===null)throw new y("BAD_REQUEST",`asId("${e}", …): "${n}" is not a valid id for table "${e}"`,{status:400});return s},async count(e,n){const s=z(e,"count");if(s)return _(e,H),s.count(e,n);const u=t.tables[e];if(!u)throw new y("INTERNAL",`unknown table: ${e}`);const h=zt(n);if(h.restrictsCounts)throw new Pe(e);_(e,H);const l=ae(u.softDeleteMode,void 0),c=J(J(h.baseWhere,h.where),l),d=await ge(c,e,h.relationBaseWhere),w=d!==c;if(u.aggregateIndexes&&!h.baseWhere&&!w&&!l){const D=Vt(u.aggregateIndexes,h.where);if(D){Fe(e,D.index);const P=qe(D.index.by??[],D.key),B=Be(e,D.index.name),I=q(i,r`SELECT ${Ie} AS value FROM ${r.identifier(B)} WHERE ${Ce} = ${P}`).toArray();return I[0]===void 0?0:I[0].value??0}}const A=te(d,re);let g=r`SELECT COUNT(*) AS count FROM ${r.identifier(e)}`;return A&&(g=r`${g} WHERE ${A}`),q(i,g).one().count},async delete(e,n,s){const u=ne(e,n);if(!u){const g=n===void 0?C:void 0;g&&(M(void 0),await g.delete(e,void 0,s));return}const{docJson:h,row:l,tableName:c}=u,d=t.tables[c],w=s?.hard===!0,A=!w&&d?.softDeleteMode?d.softDeleteMode.field:void 0;if(!(A&&l[A]!==null&&l[A]!==void 0)){if(Z(c,"before","delete")&&await ee("before","delete",{id:e,op:"delete",previous:l,table:c}),await En({deletedId:e,deletedReference:g=>l[g],findHolders:async(g,x,D)=>(await ke(g).findMany(g,{includeDeleted:w,where:{[x]:D}})).page,onCascade:(g,x)=>ke(g).delete(x,void 0,s),onRestrict:g=>{throw new pe(g,"restrict")},onSetNull:(g,x,D)=>ke(g).patch(x,{[D]:null}),schema:t,tableName:c}),ue(c),fe(c),A){const g={...l,...E(c),[A]:m(),_id:e};Me(i,c,r`UPDATE ${r.identifier(c)} SET ${r.identifier(K)} = ${se(g)} WHERE id = ${e} AND ${r.identifier(K)} = ${h}`),me(c,e,g,l),Ee(c,e,void 0),ye(c,l,g),he(c,e,l,void 0),j?.invalidate(c,e,R(c,l,g)),le(c,e,"update",g),a({indexKeys:R(c,l,g),key:e,op:"update",row:g,table:c}),Z(c,"after","delete")&&await ee("after","delete",{id:e,op:"delete",previous:l,table:c}),await N({id:e,op:"delete",table:c});return}Me(i,c,r`DELETE FROM ${r.identifier(c)} WHERE id = ${e} AND ${r.identifier(K)} = ${h}`),me(c,e,void 0),Ee(c,e,void 0),ye(c,l,void 0),he(c,e,l,void 0),j?.invalidate(c,e,R(c,l)),le(c,e,"delete"),a({indexKeys:R(c,l),key:e,op:"delete",table:c}),Z(c,"after","delete")&&await ee("after","delete",{id:e,op:"delete",previous:l,table:c}),await N({id:e,op:"delete",table:c})}},async deleteAll(e,n){if(!t.tables[e])throw new y("INTERNAL",`unknown table: ${e}`);const s=Math.max(1,n?.chunkSize??bt),u=n?.hard===void 0?void 0:{hard:n.hard},h=ie(e)?void 0:e;let l=0;return await L(async()=>{for(;;){const d=(await U.findMany(e,{limit:s})).page.map(w=>String(w._id));if(d.length===0)break;for(const w of d)await U.delete(w,h,u),l+=1;if(d.length<s)break}}),{deleted:l}},async deleteMany(e,n,s){ce(e.length,n?.limit,"deleteMany");for(const u of e)await U.delete(u,s);return{deleted:e.length}},async deleteWhere(e,n,s){const l=(await(z(e,"deleteWhere")??U).findMany(e,{where:n})).page.map(c=>String(c._id));if(ce(l.length,s?.limit,"deleteWhere"),U.deleteMany===void 0)throw new y("INTERNAL",`ctx.db.${e}.deleteMany is unavailable: this writer has no batch delete`);return U.deleteMany(l,s)},async findFirst(e,n={}){return(await U.findMany(e,{...n,limit:1})).page[0]??null},async findFirstOrThrow(e,n={}){const s=await U.findFirst(e,n);if(s===null)throw new un(`findFirstOrThrow: no "${e}" document matched`);return s},async findMany(e,n={}){const s=z(e,"findMany");if(s)return _(e,H),s.findMany(e,n);const u=t.tables[e];if(!u)throw new y("INTERNAL",`unknown table: ${e}`);const h=!n.where&&!n.baseWhere;h?_(e,H):_(e);const l=fn(n.orderBy),c=n.cursor?Mt(l,Oe(n.cursor)):void 0;let d=J(n.baseWhere,n.where);d=J(d,ae(u.softDeleteMode,n.includeDeleted)),d=await wt(d,{canPushExists:tt?qt:void 0,existsPushMode:et==="always"?"always":"auto",fetcher:Ze,maxRelationKeys:nt,relationBaseWhere:n.relationBaseWhere,schema:t,tableName:e}),c&&(d=d?{AND:[d,c]}:c);const w=tt?Zn(_):re,A=te(d,w);let g=r`SELECT id, _creationTime, ${r.identifier(K)} FROM ${r.identifier(e)}`;A&&(g=r`${g} WHERE ${A}`),g=r`${g} ORDER BY ${Wt(l)}`;const x=typeof n.limit=="number"?Math.max(0,Math.floor(n.limit)):void 0;x!==void 0&&(g=r`${g} LIMIT ${r.raw(String(x+1))}`);const D=q(i,g).toArray();h&&!$&&S?.recordRead(D.length);const P=[];for(const Y of D){const G=de(Y);G&&(P.push(G),!h&&typeof G._id=="string"&&_(e,G._id))}if(x===void 0)return n.with&&await pt({groupedCounter:rt,fetcher:Le,parents:P,...gt(n),schema:t,tableName:e,with:n.with}),{continueCursor:null,isDone:!0,page:ut(P,n.select,n.with)};const B=P.length>x,I=B?P.slice(0,x):P,Q=I.at(-1);return n.with&&await pt({fetcher:Le,groupedCounter:rt,parents:I,...gt(n),schema:t,tableName:e,with:n.with}),{continueCursor:B&&Q?Qe(Q,l):null,isDone:!B,page:ut(I,n.select,n.with)}},async get(e,n){const s=ne(e,n);if(!s){const u=n===void 0?C:void 0;return u?u.get(e):null}return _(s.tableName,e),s.row},async lookupById(e,n){const s=ne(e,n);return s?(_(s.tableName,e),{row:s.row,tableName:s.tableName}):null},async groupBy(e,n){const s=z(e,"groupBy");if(s)return _(e,H),s.groupBy(e,n);const u=t.tables[e];if(!u)throw new y("INTERNAL",`unknown table: ${e}`);_(e,H);const h=n.agg??{op:"count"};if(ve(h.op),h.op!=="count"&&!h.field)throw new y("INTERNAL",`groupBy(${e}, { agg: { op: "${h.op}" } }): "field" is required for non-count reducers`);const l=ae(u.softDeleteMode,void 0),c=J(J(n.baseWhere,n.where),l),d=await ge(c,e,n.relationBaseWhere),w=d!==c,A=[...n.by,h.field];if(u.aggregateIndexes&&!n.baseWhere&&!w&&(!l||mt(u,A))){const I=Jt(u.aggregateIndexes,h.op,h.field,n.by,n.where),Q=I===void 0?0:Object.keys(I.partial).length,Y=I?.index.by?.length??0;if(I&&(Q===0||Q===Y)){Fe(e,I.index);const G=Be(e,I.index.name),Se=Object.keys(I.partial),_e=[];if(Se.length===(I.index.by??[]).length&&Se.length>0){const Re=qe(I.index.by??[],I.partial),Te=q(i,r`SELECT ${Ie} AS value, ${Ge} AS count FROM ${r.identifier(G)} WHERE ${Ce} = ${Re}`).toArray();return Te.length>0&&_e.push({key:{...I.partial},value:Ue(h.op,Te[0])}),_e}const Gt=q(i,r`SELECT ${Ce} AS key, ${Ie} AS value, ${Ge} AS count FROM ${r.identifier(G)}`).toArray();for(const Re of Gt){const Te=Ot(JSON.parse(Re.key));_e.push({key:Te,value:Ue(h.op,Re)})}return _e}}for(const I of A){if(I===void 0)continue;const Q=I===h.field?`groupBy(${e}, { agg: { op: "${h.op}", field: "${I}" } })`:`groupBy(${e}, { by: [..."${I}"] })`;St(u,I,Q)}const g=te(d,re),x=n.by.map(I=>r`${V(I)} AS ${r.identifier(I)}`);if(h.op==="count")x.push(r`COUNT(*) AS value`);else{const{field:I}=h;if(I===void 0)throw new y("INTERNAL",`groupBy(${e}, { agg: { op: "${h.op}" } }): "field" is required for non-count reducers`);x.push(r`${r.raw(ve(h.op))}(${V(I)}) AS value`)}let D=r`SELECT ${r.join(x,r`, `)} FROM ${r.identifier(e)}`;g&&(D=r`${D} WHERE ${g}`),D=r`${D} GROUP BY ${r.join(n.by.map(I=>V(I)),r`, `)}`;const P=q(i,D).toArray(),B=[];for(const I of P){const Q={};for(const G of n.by)Q[G]=I[G]??null;const{value:Y}=I;B.push({key:Q,value:Y==null?null:Number(Y)})}return B},async insert(e,n,s){const u=z(e,"insert");if(u)return Xe(u,e,n,s,!0);const h=t.tables[e];if(!h)throw new y("INTERNAL",`unknown table: ${e}`);const l=Rt(h,n,O);Ne(h,l);let c;s?.clientId!==void 0?(Pn(s.clientId),c=s.clientId):s?.allowExplicitId&&typeof l._id=="string"?c=l._id:c=b();const d=s?.allowExplicitId&&typeof l._creationTime=="number"?l._creationTime:m(),w={...l,...E(e),_creationTime:d,_id:c};return Z(e,"before","insert")&&await ee("before","insert",{doc:{...w},id:c,op:"insert",table:e}),ue(e),fe(e),ze(i,e,r`INSERT INTO ${r.identifier(e)} (id, _creationTime, ${r.identifier(K)}) VALUES (${c}, ${d}, ${se(w)})`),it(e,c,w),Z(e,"after","insert")&&await ee("after","insert",{doc:w,id:c,op:"insert",table:e}),await N({doc:w,id:c,op:"insert",table:e}),c},async insertManyUnsafe(e,n,s){if(ce(n.length,s?.limit,"insertManyUnsafe"),n.length===0)return[];const u=z(e,"insert");if(u){const d=[];for(const w of n)M(w);for(const w of n){const A=await u.insert(e,w,{allowExplicitId:s?.allowExplicitId});a({key:A,op:"insert",row:{...w,_id:A},table:e}),d.push(A)}return d}const h=t.tables[e];if(!h)throw new y("INTERNAL",`unknown table: ${e}`);ue(e),fe(e);const l=[];for(let d=0;d<n.length;d+=xe)l.push(E(e));const c=n.map((d,w)=>{const A=Rt(h,d,O),g=s?.allowExplicitId===!0&&typeof A._id=="string"?A._id:b(),x=s?.allowExplicitId===!0&&typeof A._creationTime=="number"?A._creationTime:m(),D={...A,...l[Math.floor(w/xe)],_creationTime:x,_id:g};return{creationTime:x,document:D,id:g}});for(const d of c)M(d.document);for(let d=0;d<c.length;d+=xe){const w=r.join(c.slice(d,d+xe).map(A=>r`(${A.id}, ${A.creationTime}, ${se(A.document)})`),r`, `);ze(i,e,r`INSERT INTO ${r.identifier(e)} (id, _creationTime, ${r.identifier(K)}) VALUES ${w}`)}for(const{document:d,id:w}of c)it(e,w,d),await W({doc:d,id:w,op:"insert",table:e});return c.map(d=>d.id)},async insertMany(e,n,s){ce(n.length,s?.limit,"insertMany");const u=s?.skipDuplicates===!0,h=[],l=z(e,"insert");if(l)for(const d of n)M(d);const c=async d=>l?Xe(l,e,d,void 0,!1):U.insert(e,d);for(const d of n)try{h.push(await c(d))}catch(w){if(u&&w instanceof pe&&w.kind==="unique")h.push(null);else throw w}return h},normalizeId(e,n){return _t(t,e,n)},async patch(e,n,s){const u=ne(e,s);if(!u){const A=s===void 0?C:void 0;if(A){M(n),await A.patch(e,n);return}throw new y("INTERNAL",`document not found: ${e}`)}const{docJson:h,row:l,tableName:c}=u,d=t.tables[c];if(!d)throw new y("INTERNAL",`unknown table: ${c}`);_(c,e),At("patch",n);const w={...l,...n,...E(c),_id:e};Tt(d,n,w,O),Ne(d,w,!0),Z(c,"before","update")&&await ee("before","update",{doc:{...w},id:e,op:"update",previous:l,table:c}),ue(c),fe(c),Me(i,c,r`UPDATE ${r.identifier(c)} SET ${r.identifier(K)} = ${se(w)} WHERE id = ${e} AND ${r.identifier(K)} = ${h}`),me(c,e,w,l),Ee(c,e,w),ye(c,l,w),he(c,e,l,w),j?.invalidate(c,e,R(c,l,w)),le(c,e,"update",w),a({indexKeys:R(c,l,w),key:e,op:"update",row:w,table:c}),Z(c,"after","update")&&await ee("after","update",{doc:w,id:e,op:"update",previous:l,table:c}),await N({doc:w,id:e,op:"update",table:c})},async patchMany(e,n,s){ce(e.length,n?.limit,"patchMany");for(const u of e)await U.patch(u.id,u.patch,s);return{patched:e.length}},async patchWhere(e,n,s){const l=(await(z(e,"patchWhere")??U).findMany(e,{where:n.where})).page.map(c=>({id:String(c._id),patch:n.patch}));if(ce(l.length,s?.limit,"patchWhere"),U.patchMany===void 0)throw new y("INTERNAL",`ctx.db.${e}.patchMany is unavailable: this writer has no batch patch`);return await U.patchMany(l,s),{patched:l.length}},query(e){const n=z(e,"query");return n?(_(e,H),n.query(e)):ar(i,t,e,F,s=>{s?v(s):_(e,H)},s=>{$||S?.recordRead(s)})},async rank(e,n,s){const u=z(e,"rank");if(u)return _(e,H),u.rank(e,n,s);F(e,n,"rank");const h=t.tables[e];if(!h)throw new y("INTERNAL",`unknown table: ${e}`);const l=h.rankIndexes?.find(G=>G.name===n);if(!l)throw new y("INTERNAL",`unknown rankIndex "${n}" on table "${e}"`);if(st(e,h,l),s.restrictsCounts)throw new Pe(e);_(e,H),We(e,l);const c=typeof s.row=="string"?s.row:s.row._id;if(!c)return null;const d=ft(e,l.name),w=l.sortBy.map((G,Se)=>ht(Se)),A=w.map(G=>An(G)).join(", "),g=q(i,r`SELECT ${r.identifier("__partition__")}, ${r.raw(A)} FROM ${r.identifier(d)} WHERE ${r.identifier("__id__")} = ${c}`).toArray(),[x]=g;if(x===void 0)return null;let D=x.__partition__;const P=J(s.baseWhere,s.where);He(P,t,e,"rank");const B=wn(l,P);if(B){const G=pn(l.partitionBy??[],B);if(G!==D)return null;D=G}const I=w.map(G=>x[G]),{before:Q,total:Y}=vt(i,d,w,l.sortBy,D,I,c);return{position:Q+1,total:Y}},async rankBefore(e,n,s){if(ie(e))throw new y("INTERNAL",`rankBefore is not supported on the global (.global()) table '${e}' — cross-shard rank cursors apply only to sharded tables`);const u=t.tables[e];if(!u)throw new y("INTERNAL",`unknown table: ${e}`);const h=u.rankIndexes?.find(w=>w.name===n);if(!h)throw new y("INTERNAL",`unknown rankIndex "${n}" on table "${e}"`);if(s.restrictsCounts)throw new Pe(e);_(e,H),We(e,h);const l=ft(e,h.name),c=h.sortBy.map((w,A)=>ht(A)),d=h.sortBy.map((w,A)=>oe(s.sortValues[A]??null));return vt(i,l,c,h.sortBy,s.partitionKey,d,s.rowId)},async rankPage(e,n,s={}){He(J(s.baseWhere,s.where),t,e,"rankPage");const u=z(e,"rankPage");if(u)return _(e,H),u.rankPage(e,n,s);F(e,n,"rank");const{continueCursor:h,hasMore:l,rows:c}=dt(at,e,n,s);return{continueCursor:h,isDone:!l,page:c.map(d=>d.doc)}},async rankPageRows(e,n,s={}){He(J(s.baseWhere,s.where),t,e,"rankPage"),F(e,n,"rank");const{directions:u,hasMore:h,rows:l}=dt(at,e,n,s);return{directions:u,hasMore:h,rows:l}},async restore(e,n){const s=ne(e,n);if(!s){const l=n===void 0?C:void 0;if(l?.restore){await l.restore(e);return}throw new y("INTERNAL",`document not found: ${e}`)}const u=t.tables[s.tableName]?.softDeleteMode?.field;if(!u)throw new y("INTERNAL",`ctx.db.restore: table "${s.tableName}" is not a .softDelete() table`);const h=s.row[u]!==null&&s.row[u]!==void 0;await U.patch(e,{[u]:null},n),h&&he(s.tableName,e,void 0,s.row)},async replace(e,n,s,u){const h=ne(e,s);if(!h){const x=s===void 0?C:void 0;if(x){M(n),await x.replace(e,n,void 0,u);return}throw new y("INTERNAL",`document not found: ${e}`)}const{docJson:l,row:c,tableName:d}=h,w=t.tables[d];if(!w)throw new y("INTERNAL",`unknown table: ${d}`);At("replace",n);const A=u?.allowExplicitId&&typeof n._creationTime=="number"?n._creationTime:m(),g={...n,...E(d),_creationTime:A,_id:e};Tt(w,n,g,O),Ne(w,g),Z(d,"before","update")&&await ee("before","update",{doc:{...g},id:e,op:"update",previous:c,table:d}),ue(d),fe(d),Me(i,d,r`UPDATE ${r.identifier(d)} SET _creationTime = ${A}, ${r.identifier(K)} = ${se(g)} WHERE id = ${e} AND ${r.identifier(K)} = ${l}`),me(d,e,g,c),Ee(d,e,g),ye(d,c,g),he(d,e,c,g),j?.invalidate(d,e,R(d,c,g)),le(d,e,"update",g),a({indexKeys:R(d,c,g),key:e,op:"update",row:g,table:d}),Z(d,"after","update")&&await ee("after","update",{doc:g,id:e,op:"update",previous:c,table:d}),await N({doc:g,id:e,op:"update",table:d})},async wipeShard(e){const n=new Set(e?.exclude),s=e?.tables,u=Object.entries(t.tables).filter(([d,w])=>n.has(d)||s!==void 0&&!s.includes(d)?!1:w.shardMode?.kind!=="global").map(([d])=>d);if(s!==void 0){for(const d of s)if(!t.tables[d])throw new y("INTERNAL",`wipeShard: unknown table: ${d}`)}const h={};let l=0;const{deleteAll:c}=U;if(c===void 0)throw new y("INTERNAL","wipeShard: this writer has no deleteAll");for(const d of u){const w=await c(d,{...e?.chunkSize===void 0?{}:{chunkSize:e.chunkSize},hard:!0});h[d]=w.deleted,l+=w.deleted}return{deleted:l,tables:h}}},Pt={db:U,scheduler:k};return o.enforceRls===!0?Sn(U,t,(e,n)=>ne(e,n)?.tableName,(e,n)=>Ut(e,n)):U};export{Jr as CDC_LOG_TABLE,oo as CLIENT_WATERMARK_TABLE,lo as GLOBAL_SHAPE_SNAPSHOT_TABLE,$o as IDEMPOTENCY_TABLE,ir as NotUniqueError,To as SEARCH_STATE_TABLE,io as advanceClientWatermark,Vr as applyCdcChanges,Pn as assertValidClientId,Kr as backfillAggregateIndexes,Or as backfillRankIndexes,Qr as backfillSearchIndexes,Yr as bumpCdcEpoch,Hr as createShardCtxDb,uo as deleteGlobalShapeSnapshot,fo as deleteGlobalShapeSnapshotsForConnection,so as migrateClientWatermark,ho as migrateGlobalShapeSnapshot,Xr as minCdcSeq,_t as normalizeIdStructurally,Zr as readCdcChanges,eo as readCdcCursor,to as readCdcEpoch,co as readClientWatermark,wo as readGlobalShapeSnapshot,yo as readIdempotent,_o as runShardMigrations,vo as selectShapeMemberIds,Io as selectShapeRows,no as trimCdcChanges,Eo as trimIdempotent,po as writeGlobalShapeSnapshot,mo as writeIdempotent};
|
|
@@ -1,7 +0,0 @@
|
|
|
1
|
-
import{sql as o}from"drizzle-orm";import{runDrizzle as n}from"./runDrizzle-it6rL9bR.mjs";const c="__shape_poke_cursor",d=r=>{n(r,o`CREATE TABLE IF NOT EXISTS ${o.identifier(c)} (
|
|
2
|
-
connection_id TEXT NOT NULL,
|
|
3
|
-
sub_id TEXT NOT NULL,
|
|
4
|
-
cursor INTEGER NOT NULL,
|
|
5
|
-
PRIMARY KEY (connection_id, sub_id)
|
|
6
|
-
)`)},T=(r,e,i)=>n(r,o`SELECT cursor FROM ${o.identifier(c)} WHERE connection_id = ${e} AND sub_id = ${i} LIMIT 1`).toArray()[0]?.cursor,u=(r,e,i,s)=>{n(r,o`INSERT INTO ${o.identifier(c)} (connection_id, sub_id, cursor) VALUES (${e}, ${i}, ${s})
|
|
7
|
-
ON CONFLICT(connection_id, sub_id) DO UPDATE SET cursor = excluded.cursor`)},_=(r,e,i)=>{n(r,o`DELETE FROM ${o.identifier(c)} WHERE connection_id = ${e} AND sub_id = ${i}`)},L=(r,e)=>{n(r,o`DELETE FROM ${o.identifier(c)} WHERE connection_id = ${e}`)};export{c as SHAPE_POKE_CURSOR_TABLE,_ as deleteShapePokeCursor,L as deleteShapePokeCursorsForConnection,d as migrateShapePokeCursor,T as readShapePokeCursor,u as writeShapePokeCursor};
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{stableStringify as h}from"./stableStringify-G9OF5wcs.mjs";import{i as m,e as I}from"./wire-codec-BU9T2xJ7.mjs";const w="_id",p="_creationTime",y="page",$=e=>{let t;for(const s of e){const n=s[p];if(typeof n=="number"){if(t!==void 0){if(n<t)return!0;if(n>t)return!1}t=n}}return!1},J=(e,t)=>{const s=t[p];if(typeof s!="number")return e.length;const n=$(e);for(const[o,r]of e.entries()){const i=r[p];if(typeof i=="number"&&(n?i<s:i>s))return o}return e.length},S="__lunora__",_=e=>{if(typeof e!="object"||e===null||Array.isArray(e))return;const t=e[w];return typeof t=="string"?t:void 0},A=e=>{const t=new Map,s=[];for(const n of e){const o=_(n);if(o===void 0||t.has(o))return;t.set(o,n),s.push(o)}return{byId:t,order:s}},x=(e,t)=>{const s=e.order.filter(o=>t.byId.has(o)),n=t.order.filter(o=>e.byId.has(o));return s.length!==n.length?!1:s.every((o,r)=>n[r]===o)},F=(e,t,s,n)=>{const o=[];for(const r of e.order)t.byId.has(r)||o.push({delta:{key:r,op:"delete",table:s},frame:`{"key":${JSON.stringify(r)},"op":"delete","table":${n}}`});return o},L=(e,t,s,n)=>{const o=[];for(const r of t.order){const i=t.byId.get(r),c=e.byId.get(r),d=JSON.stringify(I(i)),a=c===void 0?void 0:JSON.stringify(c);if(a===d)continue;const f=a===void 0?"insert":"update";o.push({delta:{key:r,op:f,row:i,table:s},frame:`{"key":${JSON.stringify(r)},"op":"${f}","row":${d},"table":${n}}`})}return o},N=(e,t)=>{if(Array.isArray(e)&&Array.isArray(t))return{next:t,previous:e};if(!m(e)||!m(t))return;const s=e[y],n=t[y];if(!Array.isArray(s)||!Array.isArray(n))return;const o=r=>Object.fromEntries(Object.entries(r).filter(([i])=>i!==y));if(h(o(e))===h(I(o(t))))return{next:n,previous:s}},E=(e,t,s)=>{const n=s.filter(({delta:r})=>r.op==="insert");if(n.length===0)return!0;const o=e.order.filter(r=>t.byId.has(r)).map(r=>e.byId.get(r));for(const{delta:r}of n){const i=r.row;o.splice(J(o,i),0,i)}return o.length===t.order.length&&o.every((r,i)=>r[w]===t.order[i])},D=(e,t,s)=>{let n;try{n=JSON.parse(e)}catch{return}const o=N(n,t);if(o===void 0)return;const r=A(o.previous),i=A(o.next);if(r===void 0||i===void 0||!x(r,i))return;const c=s===""?S:s,d=JSON.stringify(c),a=[...F(r,i,c,d),...L(r,i,c,d)];return E(r,i,a)?a:void 0},j=(e,t,s,n)=>{const o=D(e,t,s);if(o!==void 0){if(n!==void 0)for(const{frame:r}of o)n.push(r);return o.map(({delta:r})=>r)}},k=(e,t)=>{try{return e.send(t),!0}catch{return!1}},M=e=>{const{cursorSuffix:t,lastMutationId:s,nextResult:n,pageDeltas:o,previousJson:r,snapshotJson:i,subId:c,table:d}=e,a=JSON.stringify(c),f=(s===void 0?"":`,"lastMutationId":${String(s)}`)+t,u=`{"type":"data","id":${a},"data":${i}${f}}`,l=r!==void 0&&(o===!0||Array.isArray(n))?D(r,n,d):void 0;if(l===void 0||l.length===0)return[u];const g=[];let v=0;for(const{frame:O}of l){const b=`{"type":"delta","id":${a},"delta":${O}${f}}`;if(v+=b.length,v>=u.length)return[u];g.push(b)}return g},B=async e=>{let t=0;for(;t<100;){t+=1;const{bufferedAmount:s}=e;if(typeof s!="number"||s<1048576)return;await new Promise(n=>{setTimeout(n,20)})}};export{B as awaitWsDrain,M as subscriptionFrames,j as subscriptionListDeltas,k as trySendFrame};
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{r as k,i as A,a as p,j as $,y as E,S as O,h as C}from"./ctx-db-companions-lTt-rvKG.mjs";import{sql as n}from"drizzle-orm";import{matchesStaticWhere as L}from"./AGGREGATE_SQL_FUNCTION-m1iUU1rv.mjs";import{aggregateTableName as M,encodeAggregateKey as _,foldAggregateTally as y}from"./aggregateTableName-Cy5e03oz.mjs";import{migrateSearchState as D,readSearchBackfillState as F,writeSearchBackfillState as x}from"./SEARCH_STATE_TABLE-Dju8ebbU.mjs";import{runDrizzle as d}from"./runDrizzle-it6rL9bR.mjs";import{i as T,r as b,a as N,b as v,A as B,D as S,h as G}from"./do-sql-Dk_DJxn4.mjs";import{isLiveForCompanion as U}from"./applySelect-BQbHyo-W.mjs";import{rankTableName as W,matchesRankStaticWhere as j}from"./RANK_TIEBREAK-ci3MaM65.mjs";const H=(e,i)=>e.profile!==i?{cursor:void 0,finished:!1,wipe:e.cursor!==void 0||e.done}:{cursor:e.cursor,finished:e.done,wipe:!1},I=(e,i)=>d(e,n`SELECT COUNT(*) AS count FROM ${n.identifier(i)}`).one().count>0,R=(e,i)=>d(e,n`SELECT id, _creationTime, ${n.identifier(S)} FROM ${n.identifier(i)}`).toArray(),K=(e,i,t,o)=>{const r=M(i,t.name);if(I(e,r))return;const c=t.by??[],f=new Map,s=R(e,i);for(const l of s){const a=b(l);if(!a||!U(a,o)||t.where&&!L(a,t.where))continue;const g=_(c,a);y(f,g,t,a)}for(const[l,a]of f)d(e,n`INSERT INTO ${n.identifier(r)} (${N}, ${v}, ${B}) VALUES (${l}, ${a.value}, ${a.count})`)},oe=(e,i)=>{for(const[t,o]of Object.entries(i.tables))if(!(o.shardMode?.kind==="global"||!o.aggregateIndexes))for(const r of o.aggregateIndexes)K(e,t,r,o.softDeleteMode?.field)},V=(e,i,t)=>{const o=W(i,t.name);if(I(e,o))return;const r=k(t),c=R(e,i);for(const f of c){const s=b(f);!s||t.where&&!j(s,t.where)||A(e,o,t,r,s._id,s)}},ne=(e,i)=>{for(const[t,o]of Object.entries(i.tables))if(!(o.shardMode?.kind==="global"||!o.rankIndexes))for(const r of o.rankIndexes)V(e,t,r)},u=500,w=(e,i,t)=>{const o=p(i,t.name),{profile:r}=$(t.language),c=H(F(e,o),r);if(c.finished)return!0;c.wipe&&d(e,n`DELETE FROM ${n.identifier(o)}`);const{cursor:f}=c,s=d(e,f===void 0?n`SELECT id, _creationTime, ${n.identifier(S)} FROM ${n.identifier(i)} ORDER BY id ASC LIMIT ${n.raw(String(u))}`:n`SELECT id, _creationTime, ${n.identifier(S)} FROM ${n.identifier(i)} WHERE id > ${f} ORDER BY id ASC LIMIT ${n.raw(String(u))}`).toArray();let l=f;for(const g of s){const{id:m}=g;if(typeof m!="string")continue;l=m,d(e,n`DELETE FROM ${n.identifier(o)} WHERE ${n.identifier(E)} = ${m}`);const h=G(g);h&&d(e,n`INSERT INTO ${n.identifier(o)} (${n.identifier(O)}, ${n.identifier(E)}) VALUES (${C(h,t)}, ${m})`)}const a=s.length<u;return x(e,o,l,a,r),a},ie=(e,i,t)=>{if(T(e))for(const o of t.searchIndexes??[])o.staged||w(e,i,o)},te=(e,i)=>{if(T(e)){D(e);for(const[t,o]of Object.entries(i.tables))if(!(o.shardMode?.kind==="global"||!o.searchIndexes))for(const r of o.searchIndexes){let c=!1;for(;!c;)c=w(e,t,r)}}};export{oe as backfillAggregateIndexes,ne as backfillRankIndexes,te as backfillSearchIndexes,ie as backfillSearchIndexesForTable};
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{e as h}from"./wire-codec-BU9T2xJ7.mjs";const u=(t,e)=>{if(!e)return t;const a=Object.create(null);for(const n of["_id","_creationTime",...e])Object.hasOwn(t,n)&&(a[n]=t[n]);return a},y=(t,e,a)=>{const{columns:n,table:p}=a,i=new Map,r=[];for(const{doc:o,id:s}of t){const c=u(o,n),f=JSON.stringify(h(c));i.set(s,f);const d=e.get(s);d===void 0?r.push({key:s,op:"insert",table:p,value:c}):d!==f&&r.push({key:s,op:"update",table:p,value:c})}for(const o of e.keys())i.has(o)||r.push({key:o,op:"delete",table:p});return{next:i,rowsPatch:r}},l=t=>t.map(e=>e.value===void 0?e:{...e,value:h(e.value)}),b=(t,e,a={})=>{const{baseCheckpoint:n,checkpoint:p,epoch:i,lastMutationId:r,pokeId:o}=e,s=[JSON.stringify({baseCheckpoint:n,epoch:i,pokeId:o,type:"pokeStart"})];for(const c of t){const f=a.preEncoded?c.rowsPatch:l(c.rowsPatch);s.push(JSON.stringify({pokeId:o,rowsPatch:f,shapeId:c.shapeId,type:"pokePart",...r===void 0?{}:{lastMutationId:r}}))}return s.push(JSON.stringify({checkpoint:p,epoch:i,pokeId:o,type:"pokeEnd"})),s};export{b as buildPokeFrames,y as diffGlobalMembership,l as encodeRowsPatch,u as projectColumns};
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
const s=()=>{const n=new Set,t=new Map,o=new Set;return{onRead(e){n.add(e),o.add(e)},onReadRange(e){n.add(e.table);const a=t.get(e.table);a?a.push(e):t.set(e.table,[e])},ranges(){for(const e of o)t.delete(e);return t.size>0?t:void 0},tables:n}};export{s as createReadFootprint};
|
|
@@ -1,7 +0,0 @@
|
|
|
1
|
-
import{v as w,R as v,e as f,s as y,a as g,b as A}from"./sibling-channel-BRZpLiDA.mjs";const N=["wnam","enam","sam","weur","eeur","apac","apac-ne","apac-se","oc","afr","me"],T=new Set(N),L=s=>typeof s=="string"&&T.has(s),h="::replica::",E=s=>{const e=s.lastIndexOf(h);if(e===-1)return;const t=s.slice(0,e),n=s.slice(e+h.length);if(!(t.length===0||!L(n)))return{ownerKey:t,region:n}},O=s=>{if(s==null||!/^\d+$/.test(s))return;const e=Number.parseInt(s,10);return Number.isSafeInteger(e)&&e>0?e:void 0},b=1e3,R=1e3,I=10,C=5e4,q=s=>f(s,"LUNORA_REPLICA_MAX_BOOTSTRAP_ROWS",C),d="__replica_state",u=new WeakSet,S=s=>{u.has(s)||(s.exec(`CREATE TABLE IF NOT EXISTS ${d} (
|
|
2
|
-
id INTEGER PRIMARY KEY CHECK (id = 1),
|
|
3
|
-
epoch TEXT NOT NULL,
|
|
4
|
-
applied_seq INTEGER NOT NULL,
|
|
5
|
-
synced_at REAL NOT NULL
|
|
6
|
-
)`),u.add(s))},c=s=>(S(s),s.exec(`SELECT epoch, applied_seq AS appliedSeq, synced_at AS syncedAtMs FROM ${d} WHERE id = 1`).toArray()[0]),l=(s,e)=>{S(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)},m=s=>{const e=s.doName();if(e!==void 0&&E(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(g(s.env())===void 0)return new Response("replica control requires LUNORA_RELAY_SECRET",{status:403})},P=async(s,e)=>{const t=m(s);if(t!==void 0)return t;const n=s.ownerEpoch();let i;try{i=await e.text()}catch{return new Response("bad request",{status:400})}if(!await w(s.env(),e.headers.get(v),i))return new Response("forbidden",{status:403});let r;try{r=JSON.parse(i)}catch{return new Response("bad request",{status:400})}if(r.type==="replica_bootstrap"){if(s.rowCount()>q(s.env()))return Response.json({cursor:0,epoch:n,rows:[],truncated:!0});const o=s.ownerCursor()??0,a=await s.exportRows();return Response.json({cursor:o,epoch:n,rows:a})}if(r.type==="replica_pull"){const o=typeof r.sinceSeq=="number"&&Number.isInteger(r.sinceSeq)&&r.sinceSeq>=0?r.sinceSeq:0,{changes:a,cursor:_}=s.readChanges(o,R),p=s.ownerFloor();return Response.json({changes:a,cursor:_,epoch:n,...p===void 0?{}:{floor:p}})}return new Response("unknown replica frame",{status:400})};class U{constructor(e,t,n){this.host=e,this.ownerKey=t,this.region=n}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 n=await this.bootstrap();if(n===void 0)return"unavailable";t=n}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 n=e;for(let i=0;i<I;i+=1){const r=await this.pull(n.appliedSeq);if(r===void 0)return t===void 0&&this.isFreshEnough(n,void 0)?"fresh":"unavailable";if(this.hasDiverged(n,r))return"unavailable";const o=r.changes.length<R;if(n=await this.applyPage(r),o||this.isFreshEnough(n,t))return this.isFreshEnough(n,t)?"fresh":"stale"}return this.isFreshEnough(n,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 l(this.host.sql(),t),t}hasDiverged(e,t){const n=t.changes.length===0&&t.cursor>e.appliedSeq,i=t.floor??(n?t.cursor:0),r=i>0&&i>e.appliedSeq+1;return t.epoch===e.epoch&&!r?!1:(this.divergent=!0,!0)}async bootstrap(){const e=await this.request({type:"replica_bootstrap"});if(e===void 0)return;const t=await e.json();if(t.truncated===!0){this.divergent=!0;return}const{errors:n}=await this.host.importRows(t.rows);if(n.length>0){this.divergent=!0;return}const i={appliedSeq:t.cursor,epoch:t.epoch,syncedAtMs:Date.now()};return l(this.host.sql(),i),i}isFreshEnough(e,t){return t!==void 0?e.appliedSeq>=t:Date.now()-e.syncedAtMs<=f(this.host.env(),"LUNORA_REPLICA_MAX_STALENESS_MS",b)}async pull(e){const t=await this.request({sinceSeq:e,type:"replica_pull"});return t===void 0?void 0:await t.json()}async request(e){const t=this.host.shardBinding(),n=y(this.host.env(),t,this.ownerKey);if(n===void 0)return;const i=JSON.stringify(e),r={"content-type":"application/json","x-lunora-shard-binding":t??""},o=g(this.host.env());o!==void 0&&(r[v]=await A(o,i));try{const a=await n.fetch("https://replica.internal/_lunora/replica",{body:i,headers:r,method:"POST"});return a.ok?a:void 0}catch{return}}}const x=s=>{const e=s.doName();if(e===void 0)return;const t=E(e);return t===void 0?void 0:new U(s,t.ownerKey,t.region)},M=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 n=await s.ensureFresh(O(e.headers.get("x-lunora-min-seq")));if(n!=="fresh")return Response.json({error:{code:"REPLICA_NOT_READY",message:`replica is ${n} for this read`}},{headers:{"x-lunora-replica-fallback":n},status:421})};export{x as createReplicaLink,M as gateReplicaDispatch,P as handleReplicaControl};
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{applyCdcChanges as p}from"./CDC_LOG_TABLE-B58N8NQO.mjs";import{selectShapeRows as m}from"./selectShapeMemberIds-B-pQJHAu.mjs";import{diffExternalSource as g,projectExternalSourceRow as l}from"./diffExternalSource-DbHrcoZK.mjs";import{stableStringify as d}from"./stableStringify-G9OF5wcs.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,5 +0,0 @@
|
|
|
1
|
-
import{a as S,S as L,y as N}from"./ctx-db-companions-lTt-rvKG.mjs";import{sql as e}from"drizzle-orm";import{aggregateTableName as u}from"./aggregateTableName-Cy5e03oz.mjs";import{backfillSearchIndexesForTable as p}from"./backfillAggregateIndexes-DVQ2sVuV.mjs";import{migrateCdcLog as h,migrateCdcMeta as x}from"./CDC_LOG_TABLE-B58N8NQO.mjs";import{migrateClientWatermark as R}from"./CLIENT_WATERMARK_TABLE-BoS1HEqz.mjs";import{migrateCommitSeq as C}from"./COMMIT_SEQ_FIELD-CSe_oNZu.mjs";import{migrateGlobalShapeSnapshot as O}from"./GLOBAL_SHAPE_SNAPSHOT_TABLE-NWaL77m5.mjs";import{migrateIdempotency as b}from"./IDEMPOTENCY_TABLE-DKVe2Ohf.mjs";import{migrateSearchState as U}from"./SEARCH_STATE_TABLE-Dju8ebbU.mjs";import{migrateShapePokeCursor as l}from"./SHAPE_POKE_CURSOR_TABLE-Dh4HfSdC.mjs";import{runDrizzle as a}from"./runDrizzle-it6rL9bR.mjs";import{D as $,e as T,d,t as X,i as G,g as D,a as B,b as M,A as E}from"./do-sql-Dk_DJxn4.mjs";import{migrateDurableStreams as k}from"./appendStreamChunk-CH4e4nJn.mjs";import{rankTableName as F,sortColumnName as Y}from"./RANK_TIEBREAK-ci3MaM65.mjs";import{migrateReactorState as P}from"./REACTOR_STATE_TABLE-Cr9Orfp8.mjs";import{recordSchemaVersion as j}from"./SCHEMA_HISTORY_MAX_VERSIONS-DsycDXWm.mjs";const y=(r,n,o)=>{for(const i of o.indexes){const t=`${n}_${i.name}`,m=e.join(i.fields.map(s=>T(s)),e`, `);a(r,d(t,n,m,i.unique??!1))}for(const[i,t]of X(o)){if(!t.unique)continue;const m=`${n}_unique_${i}`;a(r,d(m,n,T(i),!0))}},v=(r,n,o)=>{if(!(!o.searchIndexes||o.searchIndexes.length===0||!G(r))){for(const i of o.searchIndexes){const t=S(n,i.name);a(r,e`CREATE VIRTUAL TABLE IF NOT EXISTS ${e.identifier(t)} USING fts5(${e.identifier(L)}, ${e.identifier(N)} UNINDEXED)`),a(r,e`CREATE VIRTUAL TABLE IF NOT EXISTS ${e.identifier(`${t}__vocab`)} USING fts5vocab(${e.identifier(t)}, ${e.raw("instance")})`)}p(r,n,o)}},K=(r,n,o)=>{if(o.geoIndexes)for(const i of o.geoIndexes){const t=D(n,i.name);a(r,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 m=`${n}__geo_${i.name}__btree`;a(r,d(m,t,e`${e.identifier("__geohash__")} ASC, ${e.identifier("__id__")} ASC`,!1))}},V=(r,n,o)=>{if(o.aggregateIndexes)for(const i of o.aggregateIndexes){const t=u(n,i.name);a(r,e`CREATE TABLE IF NOT EXISTS ${e.identifier(t)} (${B} TEXT PRIMARY KEY, ${M} REAL, ${E} INTEGER NOT NULL DEFAULT 0)`),a(r,e`PRAGMA table_info(${e.identifier(t)})`).toArray().some(s=>s.name==="__count__")||a(r,e`ALTER TABLE ${e.identifier(t)} ADD COLUMN ${E} INTEGER NOT NULL DEFAULT 0`)}},w=(r,n,o)=>{if(o.rankIndexes)for(const i of o.rankIndexes){const t=F(n,i.name),m=i.sortBy.map((f,_)=>Y(_)),s=m.map(f=>e`${e.identifier(f)} BLOB`),g=s.length>0?e`, ${e.join(s,e`, `)}`:e``;a(r,e`CREATE TABLE IF NOT EXISTS ${e.identifier(t)} (${e.identifier("__id__")} TEXT PRIMARY KEY, ${e.identifier("__partition__")} TEXT NOT NULL${g})`);const c=[e`${e.identifier("__partition__")} ASC`];for(const[f,_]of m.entries()){const I=i.sortBy[f]?.direction;c.push(e`${e.identifier(_)} ${e.raw(I==="desc"?"DESC":"ASC")}`)}c.push(e`${e.identifier("__id__")} ASC`);const A=`${n}__rank_${i.name}__btree`;a(r,d(A,t,e.join(c,e`, `),!1))}},de=(r,n,o={})=>{o.schemaSnapshot!==void 0&&j(r,o.schemaSnapshot.hash,o.schemaSnapshot.json),U(r);for(const[i,t]of Object.entries(n.tables))t.shardMode?.kind!=="global"&&(a(r,e`CREATE TABLE IF NOT EXISTS ${e.identifier(i)} (
|
|
2
|
-
id TEXT PRIMARY KEY,
|
|
3
|
-
_creationTime REAL NOT NULL,
|
|
4
|
-
${e.identifier($)} TEXT NOT NULL
|
|
5
|
-
)`),y(r,i,t),v(r,i,t),K(r,i,t),V(r,i,t),w(r,i,t));o.cdc&&(h(r),x(r),R(r),l(r)),Object.values(n.tables).some(i=>i.commitOrderedMode===!0)&&C(r),P(r),b(r),O(r),k(r)};export{de as runShardMigrations};
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{sql as e}from"drizzle-orm";import{runDrizzle as a}from"./runDrizzle-it6rL9bR.mjs";import{D as p,r as u,e as d}from"./do-sql-Dk_DJxn4.mjs";import{sqliteInList as h}from"./param-Ib8WHnrF.mjs";import{compileWhereSql as S}from"./compileWhereSql-JBpSfQm9.mjs";import{serializeSqlValue as w}from"./serializeSqlValue-DbI1VQYM.mjs";const C={fieldRef:d,serialize:w},$=r=>{if(r.length!==0)return h(e`${e.identifier("id")}`,r,!1)},m=(r,i)=>{const o=[];i&&o.push(i);const t=S(r,C);return t&&o.push(t),o.length===0?e``:e` WHERE ${e.join(o,e` AND `)}`},L=(r,i,o)=>{const t=m(o,void 0),c=a(r,e`SELECT id, _creationTime, ${e.identifier(p)} FROM ${e.identifier(i)}${t}`).toArray(),n=[];for(const s of c){const f=u(s),{id:l}=s;f!==void 0&&typeof l=="string"&&n.push({doc:f,id:l})}return n},M=(r,i,o,t)=>{if(t.length===0)return new Set;const c=m(o,$(t)),n=a(r,e`SELECT id FROM ${e.identifier(i)}${c}`).toArray();return new Set(n.map(s=>s.id))};export{M as selectShapeMemberIds,L as selectShapeRows};
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
const a=/^\d+$/,d=(n,t,r)=>{const e=n?.[t];let o=Number.NaN;return typeof e=="string"&&a.test(e.trim())?o=Number(e.trim()):typeof e=="number"&&(o=e),Number.isSafeInteger(o)&&o>0?o:r},c=(n,t)=>{const r=Math.max(n.length,t.length);let e=n.length^t.length;for(let o=0;o<r;o+=1){const s=o<n.length?n.charCodeAt(o):0,i=o<t.length?t.charCodeAt(o):0;e|=s^i}return e===0},u="LUNORA_RELAY_SECRET",y="x-lunora-relay-sig",f=n=>{const t=n?.[u];return typeof t=="string"&&t.length>0?t:void 0},l=async(n,t)=>{const r=new TextEncoder,e=await crypto.subtle.importKey("raw",r.encode(n),{hash:"SHA-256",name:"HMAC"},!1,["sign"]),o=await crypto.subtle.sign("HMAC",e,r.encode(t));return[...new Uint8Array(o)].map(s=>s.toString(16).padStart(2,"0")).join("")},m=async(n,t,r)=>{const e=f(n);return e===void 0?!0:t===null?!1:c(t,await l(e,r))},g=n=>{if(n===null||typeof n!="object")return;const t=n;return typeof t.idFromName=="function"&&typeof t.get=="function"?t:void 0},E=(n,t,r)=>{if(t===void 0)return;const e=g(n?.[t]);if(e!==void 0)return typeof e.getByName=="function"?e.getByName(r):e.get(e.idFromName(r))};export{y as R,f as a,l as b,d as e,E as s,m as v};
|