@lunora/shard-engine 1.0.0-alpha.24 → 1.0.0-alpha.26
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 +79 -2
- package/dist/index.d.ts +79 -2
- package/dist/index.mjs +1 -1
- package/dist/packem_shared/{ADMIN_FUNCTIONS-B5HZoizX.mjs → ADMIN_FUNCTIONS-Cj1pJjVg.mjs} +1 -1
- package/dist/packem_shared/{AGG_COUNT-DmQFpsDX.mjs → AGG_COUNT-CKtq03Go.mjs} +1 -1
- package/dist/packem_shared/{CDC_LOG_TABLE-DH-KHUfU.mjs → CDC_LOG_TABLE-DNFFQwF_.mjs} +1 -1
- package/dist/packem_shared/{DEFAULT_MAX_RELATION_KEYS-DjKka36Z.mjs → DEFAULT_MAX_RELATION_KEYS-BV1RCoat.mjs} +1 -1
- package/dist/packem_shared/{DEFAULT_MAX_RELAYS-B19vrJxP.mjs → DEFAULT_MAX_RELAYS-Cinp9pPC.mjs} +1 -1
- package/dist/packem_shared/{DEFAULT_PROMOTION_THRESHOLDS-B2rUe1bg.mjs → DEFAULT_PROMOTION_THRESHOLDS-DYGNAo1I.mjs} +1 -1
- package/dist/packem_shared/DurableStreamRunner-B54Jt9Iu.mjs +1 -0
- package/dist/packem_shared/{NotUniqueError-By65lhla.mjs → NotUniqueError-DYo7r67J.mjs} +1 -1
- package/dist/packem_shared/{RANK_TIEBREAK-DDtST3gN.mjs → RANK_TIEBREAK-BGk411OR.mjs} +1 -1
- package/dist/packem_shared/{ReactiveCache-Cu8IfE1M.mjs → ReactiveCache-D_T10KLy.mjs} +1 -1
- package/dist/packem_shared/{aggregateTableName-DgYMC5tr.mjs → aggregateTableName-DN7gk6uh.mjs} +1 -1
- package/dist/packem_shared/appendStreamChunk-ksZYy1hZ.mjs +19 -0
- package/dist/packem_shared/{applyOnDelete-By23GK-k.mjs → applyOnDelete-crbAzVfE.mjs} +1 -1
- package/dist/packem_shared/{applySelect-UY-o13Ia.mjs → applySelect-5w13bMAR.mjs} +1 -1
- package/dist/packem_shared/awaitWsDrain-PT9o0d6J.mjs +1 -0
- package/dist/packem_shared/{backfillAggregateIndexes-BEMWTEq1.mjs → backfillAggregateIndexes-DTOIsYbi.mjs} +1 -1
- package/dist/packem_shared/{buildPokeFrames-CqxaN8_H.mjs → buildPokeFrames-DmB-FBeQ.mjs} +1 -1
- package/dist/packem_shared/{buildReprojectionMigration-YQSJX2cC.mjs → buildReprojectionMigration-JUwsTNTB.mjs} +1 -1
- package/dist/packem_shared/{computeRankPage-D1ygctSC.mjs → computeRankPage-BU8LXvQs.mjs} +1 -1
- package/dist/packem_shared/createCompanionSync-D-ckGBdA.mjs +1 -0
- package/dist/packem_shared/{ctx-db-companions-c12P7dbv.mjs → ctx-db-companions-BJlCofon.mjs} +1 -1
- package/dist/packem_shared/{defineEngineContractSuite-Dp5E4UvF.mjs → defineEngineContractSuite-CvdzORsy.mjs} +1 -1
- package/dist/packem_shared/{do-sql-C7qrlm6-.mjs → do-sql-DKSFK627.mjs} +1 -1
- package/dist/packem_shared/{isSoftDeleted-Tr2to2aw.mjs → isSoftDeleted-DyEJueIu.mjs} +1 -1
- package/dist/packem_shared/{materializeExternalRows-D53xwGfY.mjs → materializeExternalRows-C-5TKdc1.mjs} +1 -1
- package/dist/packem_shared/runShardMigrations-BCuK60KT.mjs +5 -0
- package/dist/packem_shared/{selectExpiredIds-C3Vv1gPm.mjs → selectExpiredIds-C4Ry_NxG.mjs} +1 -1
- package/dist/packem_shared/{selectShapeMemberIds-WzxOG62k.mjs → selectShapeMemberIds-Bkkug6vU.mjs} +1 -1
- package/dist/packem_shared/{stableWireKey-l3cjIt-9.mjs → stableWireKey-Diuu1gGc.mjs} +1 -1
- package/dist/packem_shared/{wire-codec-Dsy70M3Q.mjs → wire-codec-Dh0j-GnY.mjs} +1 -1
- package/package.json +3 -3
- package/dist/packem_shared/awaitWsDrain-Bp2jKzIb.mjs +0 -1
- package/dist/packem_shared/createCompanionSync-D7DEvUvt.mjs +0 -1
- package/dist/packem_shared/runShardMigrations-BWElJTC8.mjs +0 -5
|
@@ -1 +1 @@
|
|
|
1
|
-
import{LunoraError as g}from"@lunora/errors";import{n as Bt,S as qt,x as Qe,T as Se,y as Ut,c as Pt}from"./ctx-db-companions-c12P7dbv.mjs";import{sql as r}from"drizzle-orm";import{s as Ht}from"./wire-codec-Dsy70M3Q.mjs";import{aggregateSqlFunction as Re,normalizeCountArgument as Gt,throwingScheduler as jt}from"./AGGREGATE_SQL_FUNCTION-CTo0-9iZ.mjs";import{encodeAggregateKey as De,readAggregateValue as Le,aggregateTableName as Oe}from"./aggregateTableName-DgYMC5tr.mjs";import{mergeWhere as Y,CountRlsUnsupportedError as Fe,selectIndexForGroupBy as Qt,selectIndexForCount as Kt,selectIndexForAggregate as Yt}from"./CountRlsUnsupportedError-8BqPYQoP.mjs";import{backfillSearchIndexesForTable as zt}from"./backfillAggregateIndexes-BEMWTEq1.mjs";import{backfillAggregateIndexes as Fr,backfillRankIndexes as Wr,backfillSearchIndexes as Br}from"./backfillAggregateIndexes-BEMWTEq1.mjs";import{appendCdcChange as Jt}from"./CDC_LOG_TABLE-DH-KHUfU.mjs";import{CDC_LOG_TABLE as Ur,applyCdcChanges as Pr,bumpCdcEpoch as Hr,minCdcSeq as Gr,readCdcChanges as jr,readCdcCursor as Qr,readCdcEpoch as Kr,trimCdcChanges as Yr}from"./CDC_LOG_TABLE-DH-KHUfU.mjs";import{computeRankPage as at}from"./computeRankPage-D1ygctSC.mjs";import{SCAN_DEP as U}from"./SCAN_DEP-D_yR9EeV.mjs";import{runDrizzle as W}from"./runDrizzle-C3n5gJsk.mjs";import{a as H,L as se,p as Ae,T as We,c as xe,N as J,E as ce,I as St,C as Vt,D as Rt,h as Xt,O as st}from"./do-sql-C7qrlm6-.mjs";import{WORKERD_SQLITE_LIMITS as At,unionAll as Pe,sqliteInList as Zt}from"./param-CYxL68V-.mjs";import{coveringGeohashes as en,boundingBoxGeohashes as tn,pointInBoundingBox as nn,haversineMeters as rn}from"./GEO_DEFAULT_PRECISION-DyI5zggj.mjs";import{NotFoundError as on}from"./NotFoundError-BhF7FeFr.mjs";import{normalizeOrderKeys as an,buildSeekWhere as xt,decodeCursor as He,applySelect as dt,encodeCursor as Ge,softDeleteScope as le,buildSeekBeforeWhere as sn}from"./applySelect-UY-o13Ia.mjs";import{sortColumnName as lt,resolveRankPartition as dn,encodePartitionKey as ln,RANK_TIEBREAK as cn,rankTableName as ct}from"./RANK_TIEBREAK-DDtST3gN.mjs";import{indexKeysForRow as un,buildIndexRange as fn}from"./buildIndexRange-DFsdtPjD.mjs";import{assertFlatPredicate as Be,resolveRelationPredicates as ut}from"./DEFAULT_MAX_RELATION_KEYS-DjKka36Z.mjs";import{runRowValidators as qe,resolveWith as ft,relationHooks as ht,applyOnDelete as hn,fanOutScalarCounts as mn}from"./applyOnDelete-By23GK-k.mjs";import{guardWriter as pn}from"./RLS_UNWRAP_SYMBOL-DcqORh2s.mjs";import{f as $n}from"./sql-projection-jfoe331H.mjs";import{createSystemReader as wn}from"./createSystemReader-DcDcrtM3.mjs";import{ConflictError as pe}from"./ConflictError-C8GtJmjS.mjs";import{runTriggers as gn}from"./hasTrigger-CbkOHExZ.mjs";import{compileWhereSql as te}from"./compileWhereSql-B3hq_v98.mjs";import{CLIENT_WATERMARK_TABLE as Jr,advanceClientWatermark as Vr,migrateClientWatermark as Xr,readClientWatermark as Zr}from"./CLIENT_WATERMARK_TABLE-LrKfdxyt.mjs";import{GLOBAL_SHAPE_SNAPSHOT_TABLE as to,deleteGlobalShapeSnapshot as no,deleteGlobalShapeSnapshotsForConnection as ro,migrateGlobalShapeSnapshot as oo,readGlobalShapeSnapshot as io,writeGlobalShapeSnapshot as ao}from"./GLOBAL_SHAPE_SNAPSHOT_TABLE-B2LKe4KU.mjs";import{IDEMPOTENCY_TABLE as lo,readIdempotent as co,trimIdempotent as uo,writeIdempotent as fo}from"./IDEMPOTENCY_TABLE-tQ5mnqvw.mjs";import{runShardMigrations as mo}from"./runShardMigrations-BWElJTC8.mjs";import{SEARCH_STATE_TABLE as $o}from"./SEARCH_STATE_TABLE-DRk_SB72.mjs";import{selectShapeMemberIds as go,selectShapeRows as bo}from"./selectShapeMemberIds-WzxOG62k.mjs";import{serializeSqlValue as ie}from"./serializeSqlValue-BR4UOWoP.mjs";import{quoteIdentifier as bn}from"./quoteIdentifier-CObIFRhb.mjs";const En=o=>{const i=new TextEncoder().encode(o);let t="";for(const d of i)t+=String.fromCodePoint(d);return btoa(t)},yn=o=>{const i=atob(o),t=Uint8Array.from(i,d=>d.codePointAt(0)??0);return new TextDecoder().decode(t)},Nn=()=>new g("BAD_REQUEST","invalid cursor"),mt=16,pt=8,V=1024,Ke=(o,i)=>i.query(o),_n=(o,i,t)=>{const d=Bt(o,t);if(d.length===0)return 0;let f=0;for(const[m,b]of i.entries()){const S=m===i.length-1;let y=0;for(const w of d)(S?w.startsWith(b):w===b)&&(y+=1);if(y===0)return 0;f+=y}return f},Tn=(o,i)=>{if(!i)return{exact:!0,lower:o,upper:o};const t=[...o].at(-1)??"",d=(t.codePointAt(0)??0)+1;if(d>=55296&&d<=57343||d>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(d)}},Sn=(o,i,t)=>{const d={eq:(f,m)=>{if(!o.definition.filterFields?.includes(f))throw new g("INTERNAL",`field "${f}" is not a filter field of search index "${o.indexName}" on table "${i}"`);if(o.filters.length>=pt)throw new g("BAD_REQUEST",`search index "${o.indexName}" on table "${i}": at most ${String(pt)} .eq() filters are supported per search query`);return o.filters.push({field:f,value:m}),d},search:(f,m)=>{const b=o;if(f!==b.definition.field)throw new g("INTERNAL",`search index "${b.indexName}" on table "${i}" indexes "${b.definition.field}", not "${f}"`);const S=Ke(m,t).length;if(S>mt)throw new g("BAD_REQUEST",`search index "${b.indexName}" on table "${i}": at most ${String(mt)} search terms are supported (got ${String(S)})`);return b.field=f,b.query=m,b.hasQuery=!0,d}};return d},Rn=o=>{if(o.length>V)throw new g("BAD_REQUEST",`more than ${String(V)} documents match this search — narrow it with filters or read it a page at a time with .paginate()`)},An=o=>Math.min(o.offset+o.numItems+1,V),xn=o=>En(`search:${String(o)}`),In=o=>{let i;try{i=yn(o)}catch{return}if(!i.startsWith("search:"))return;const t=Number(i.slice(7));return Number.isInteger(t)&&t>=0?t:void 0},vn=o=>{if(typeof o.endCursor=="string")throw new g("BAD_REQUEST","bounded (endCursor) pagination is not supported on search queries — relevance order has no stable range boundary");const i=Math.max(0,Math.floor(o.numItems)),t=o.cursor?In(o.cursor):0;if(t===void 0)throw Nn();if(t+i>V)throw new g("BAD_REQUEST",`search pagination reaches past the ${String(V)}-document limit (offset ${String(t)} + ${String(i)} requested) — narrow the query or the filters instead`);return{numItems:i,offset:t}},Cn=(o,i)=>{const t=i.offset+i.numItems,d=i.numItems>0&&o.length>t;return{continueCursor:d?xn(t):null,isDone:!d,page:o.slice(i.offset,t)}},Mn=o=>{if(o===void 0)return V+1;if(!Number.isFinite(o))return V;const i=Math.max(0,Math.floor(o));if(i>V)throw new g("BAD_REQUEST",`search returns at most ${String(V)} documents (asked for ${String(i)}) — narrow the query or paginate instead`);return i},kn=/^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/iu,Dn=o=>{if(!kn.test(o))throw new g("INTERNAL",`invalid clientId ${JSON.stringify(o)}: a client-supplied row id must be a UUID`)},$t=50,It=500,wt=Math.floor(At.boundParams/3),me=At.boundParams,Ln=128,de=(o,i,t)=>{const d=i??It;if(o>d)throw new g("BATCH_LIMIT_EXCEEDED",`${t}: batch of ${String(o)} exceeds the limit of ${String(d)} (raise options.limit or chunk the call)`,{status:400})},On=o=>{const i={eq:(t,d)=>(o.sqlConditions.push({comparator:"=",field:t,value:d}),i),gt:(t,d)=>(o.sqlConditions.push({comparator:">",field:t,value:d}),i),gte:(t,d)=>(o.sqlConditions.push({comparator:">=",field:t,value:d}),i),lt:(t,d)=>(o.sqlConditions.push({comparator:"<",field:t,value:d}),i),lte:(t,d)=>(o.sqlConditions.push({comparator:"<=",field:t,value:d}),i)};return i},Fn=o=>Math.max(o,V),vt=(o,i)=>{const t=o.filters.map(d=>r`${J(d.field)} = ${ie(d.value)}`);return i&&t.push(i),t},Wn=(o,i,t,d,f)=>{const m=Ke(t.query,Qe(t.definition.language));if(m.length===0)return[];const b=Pt(i,t.indexName),S=`${b}__vocab`,y=m.length-1,w=m.map((L,M)=>{const G=Tn(L,M===y),j=G.exact?r`${r.identifier("term")} = ${G.lower}`:r`${r.identifier("term")} >= ${G.lower} AND ${r.identifier("term")} < ${G.upper}`;return r`SELECT ${r.identifier("doc")}, ${r.raw(String(M))} AS ${r.identifier("__term__")}, COUNT(*) AS ${r.identifier("__n__")} FROM ${r.identifier(S)} WHERE ${j} GROUP BY ${r.identifier("doc")}`}),N=m.map((L,M)=>r`SUM(CASE WHEN u.${r.identifier("__term__")} = ${r.raw(String(M))} THEN u.${r.identifier("__n__")} ELSE 0 END)`),_=r`SELECT f.${r.identifier(Se)} AS ${r.identifier(Se)}, ${r.join(N,r` + `)} AS ${r.identifier("__score__")} FROM (${Pe(w)}) u JOIN ${r.identifier(b)} f ON f.rowid = u.${r.identifier("doc")} GROUP BY f.${r.identifier(Se)} HAVING ${r.join(N.map(L=>r`${L} > 0`),r` AND `)}`,T=vt(t,f);let v=r`SELECT m.id, m._creationTime, m.${r.identifier(H)}, s.${r.identifier("__score__")} AS ${r.identifier("__score__")} FROM (${_}) s JOIN ${r.identifier(i)} m ON m.id = s.${r.identifier(Se)}`;T.length>0&&(v=r`${v} WHERE ${r.join(T,r` AND `)}`),v=r`${v} ORDER BY s.${r.identifier("__score__")} DESC, m._creationTime DESC, m.id ASC LIMIT ${r.raw(String(d))}`;const O=[];for(const L of W(o,v)){const M=Rt(L);if(M){const G=L.__score__;O.push({document:M,score:typeof G=="number"?G:Number(G??0)})}}return O},Bn=(o,i,t,d,f)=>{const m=Qe(t.definition.language),b=Ke(t.query,m);if(b.length===0)return[];const S=vt(t,f);let y=r`SELECT id, _creationTime, ${r.identifier(H)} FROM ${r.identifier(i)}`;S.length>0&&(y=r`${y} WHERE ${r.join(S,r` AND `)}`),y=r`${y} ORDER BY _creationTime DESC, id ASC LIMIT ${r.raw(String(Fn(d)))}`;const w=W(o,y).toArray(),N=[];for(const _ of w){const T=Rt(_);if(!T)continue;const v=_n(Ut(T,t.definition),b,m);v>0&&N.push({creationTime:typeof T._creationTime=="number"?T._creationTime:0,doc:T,id:typeof T._id=="string"?T._id:"",score:v})}return N.sort((_,T)=>T.score-_.score||T.creationTime-_.creationTime||_.id.localeCompare(T.id)),N.slice(0,d).map(_=>({document:_.doc,score:_.score}))},Ue=(o,i,t,d)=>{if(!Number.isFinite(o.lat)||o.lat<-90||o.lat>90||!Number.isFinite(o.lng)||o.lng<-180||o.lng>180)throw new g("BAD_REQUEST",`geo index "${d}" on table "${t}": ${i} must have a finite lat in [-90, 90] and lng in [-180, 180]`)},qn=(o,i)=>{const t=o,d={near:(f,m)=>{if(t.within)throw new g("INTERNAL",`geo index "${t.indexName}" on table "${i}": call .near() or .within(), not both`);if(Ue(f,".near() point",i,t.indexName),!Number.isFinite(m)||m<=0)throw new g("BAD_REQUEST",`geo index "${t.indexName}" on table "${i}": .near() radiusMeters must be a finite number > 0, got ${String(m)}`);return t.near={point:{lat:f.lat,lng:f.lng},radiusMeters:m},d},within:f=>{if(t.near)throw new g("INTERNAL",`geo index "${t.indexName}" on table "${i}": call .near() or .within(), not both`);if(Ue(f.sw,".within() sw corner",i,t.indexName),Ue(f.ne,".within() ne corner",i,t.indexName),f.sw.lat>f.ne.lat)throw new g("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 g("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}},d}};return d},Un=(o,i)=>{const t=o[i];if(t===null||typeof t!="object")return;const{lat:d,lng:f}=t;return typeof d=="number"&&typeof f=="number"?{lat:d,lng:f}:void 0},Pn=(o,i)=>{const t=Un(o,i.definition.field);if(!t)return;const d=typeof o._creationTime=="number"?o._creationTime:0;if(i.near){const f=rn(i.near.point,t);return f<=i.near.radiusMeters?{creationTime:d,distance:f}:void 0}return nn(t,i.within)?{creationTime:d,distance:0}:void 0},Hn=(o,i,t,d)=>{if(!t.near&&!t.within)throw new g("INTERNAL",`geo index "${t.indexName}" on table "${i}": call .near(point, radius) or .within(box)`);const f=t.near?en(t.near.point,t.near.radiusMeters):tn(t.within),m=Xt(i,t.indexName),b=f.map(_=>r`(g.${r.identifier("__geohash__")} >= ${_} AND g.${r.identifier("__geohash__")} < ${`${_}{`})`),S=[r`(${r.join(b,r` OR `)})`];d&&S.push(d);const y=r`SELECT m.id, m._creationTime, m.${r.identifier(H)} FROM ${r.identifier(m)} g JOIN ${r.identifier(i)} m ON m.id = g.${r.identifier("__id__")} WHERE ${r.join(S,r` AND `)}`,w=W(o,y).toArray(),N=[];for(const _ of w){const T=ce(_),v=T?Pn(T,t):void 0;T&&v&&N.push({creationTime:v.creationTime,distance:v.distance,doc:T})}return N.sort((_,T)=>_.distance-T.distance||T.creationTime-_.creationTime),N},Ct=(o,i,t,d)=>{const f=[];for(const m of o)if(i.every(b=>b(d(m)))&&(f.push(m),typeof t=="number"&&f.length>=t))break;return f},Gn=(o,i,t,d,f,m=()=>{})=>{const b=t.within!==void 0,S=Hn(o,i,t,f).map(y=>({distanceMeters:b?null:y.distance,document:y.doc}));return m(S.length),typeof d=="number"?S.slice(0,Math.max(0,Math.floor(d))):S},Mt=(o,i,t,d,f,m=()=>{})=>{const{geo:b}=t;if(!b)throw new g("INTERNAL","runGeoTerminalScored called without a staged geo query");const S=t.inMemoryFilters.length>0,y=Gn(o,i,b,S?void 0:f,d,m);return S?Ct(y,t.inMemoryFilters,f,w=>w.document):y},jn=(o,i,t,d,f,m=()=>{})=>Mt(o,i,t,d,f,m).map(b=>b.document),Qn=(o,i,t,d,f,m,b=()=>{})=>{const S=[];for(const _ of t.sqlConditions)S.push(r`${J(_.field)} ${r.raw(_.comparator)} ${ie(_.value)}`);d&&S.push(d);let y=r`SELECT id, _creationTime, ${r.identifier(H)} FROM ${r.identifier(i)}`;S.length>0&&(y=r`${y} WHERE ${r.join(S,r` AND `)}`),y=r`${y} ORDER BY ${f}`,typeof m=="number"&&t.inMemoryFilters.length===0&&(y=r`${y} LIMIT ${r.raw(String(Math.max(0,Math.floor(m))))}`);const w=W(o,y).toArray();b(w.length);const N=[];for(const _ of w){const T=ce(_);if(T&&t.inMemoryFilters.every(v=>v(T))&&(N.push(T),typeof m=="number"&&N.length>=m))break}return N},oe={fieldRef:J,serialize:ie},kt=(o,i)=>{const t=i===void 0?void 0:o.shape[i];return t!==void 0&&$n(t)},gt=(o,i)=>i.some(t=>kt(o,t)),bt=(o,i,t)=>{if(kt(o,i))throw new g("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`)},Kn=o=>{let i=0;const t=[],d={fieldRef:J,relationExists:f=>{const{childWhere:m,negated:b,parentTable:S,relation:y}=f,w=`__rel_${String(i)}`,N=t.at(-1)??S;i+=1,o(y.table,U);const _=y.kind==="one"?y.field:y.references,T=y.kind==="one"?y.references:y.field,v=r`${st(w,T)} = ${st(N,_)}`;t.push(w);const O=te(m,d);t.pop();const L=O?r`${v} AND ${O}`:v,M=r`EXISTS (SELECT 1 FROM ${r.identifier(y.table)} AS ${r.identifier(w)} WHERE ${L})`;return b?r`NOT ${M}`:M},serialize:ie};return d},Dt=o=>{const i=o.map(t=>r`${J(t.field)} ${r.raw(t.direction==="desc"?"DESC":"ASC")}`);return o.some(t=>t.field==="_id"||t.field==="id")||i.push(r`${J("id")} ASC`),r.join(i,r`, `)},Yn={"<":"lt","<=":"lte","=":"eq",">":"gt",">=":"gte"},zn=o=>{const i=o.order;return o.indexFields.length>0?o.indexFields.map(t=>({direction:i,field:t})):[{direction:i,field:"_creationTime"}]},Jn=(o,i,t,d)=>{const f=o.sqlConditions.map(m=>({[m.field]:{[Yn[m.comparator]??"eq"]:m.value}}));if(t&&f.push(xt(i,He(t))),d&&f.push(sn(i,He(d))),f.length!==0)return f.length===1?f[0]:{AND:f}},Vn=(o,i,t)=>{const d=[];for(const f of o){const m=ce(f);if(m&&i.every(b=>b(m))&&(d.push(m),t!==void 0&&d.length>t))break}return d},Xn=(o,i,t,d,f,m=()=>{})=>{const b=Math.max(0,Math.floor(d.numItems)),S=zn(t),y=typeof d.endCursor=="string",w=te(Jn(t,S,d.cursor,d.endCursor),oe),N=f&&w?r`${w} AND ${f}`:f??w;let _=r`SELECT id, _creationTime, ${r.identifier(H)} FROM ${r.identifier(i)}`;N&&(_=r`${_} WHERE ${N}`),_=r`${_} ORDER BY ${Dt(S)}`;const T=t.inMemoryFilters.length>0;!T&&!y&&(_=r`${_} LIMIT ${r.raw(String(b+1))}`);const v=W(o,_).toArray();m(v.length);const O=Vn(v,t.inMemoryFilters,T||y?void 0:b);if(y){const j=O.length>=2?O[Math.floor(O.length/2)-1]:void 0;return{continueCursor:d.endCursor??null,isDone:!0,page:O,splitCursor:j?Ge(j,S):null}}const L=O.length>b,M=L?O.slice(0,b):O,G=M.at(-1);return{continueCursor:L&&G?Ge(G,S):null,isDone:!L,page:M}};class Zn extends g{constructor(i="unique() found more than one matching document"){super("NOT_UNIQUE",i,{name:"NotUniqueError"})}}const er=/\s/u,tr=String.fromCodePoint(0),Et=(o,i,t)=>{if(!o.tables[i])throw new g("INTERNAL",`unknown table: ${i}`);return typeof t!="string"||t.length===0||er.test(t)||t.includes(tr)?null:t},nr=(o,i,t,d=()=>{},f=()=>{},m=()=>{})=>{const b=i.tables[t];if(!b)throw new g("INTERNAL",`unknown table: ${t}`);const S=le(b.softDeleteMode,void 0),y=S?te(S,oe):void 0,w={indexFields:[],indexName:void 0,inMemoryFilters:[],order:"asc",sqlConditions:[]};let N=0;const _=E=>{const{search:I}=w;if(!I)throw new g("INTERNAL","runSearchFetch called without a staged search");zt(o,t,b);const C=w.inMemoryFilters.length>0,k=Mn(C?void 0:E),z=Vt(o)?Wn(o,t,I,k,y):Bn(o,t,I,k,y);return C?(N=z.length,Ct(z,w.inMemoryFilters,E,ne=>ne.document)):(E===void 0&&Rn(z),z)},T=E=>_(E).map(I=>I.document),v=E=>{const I=vn(E);return Cn(T(An(I)),I)},O=()=>{const E=w.indexFields.length>0?w.indexFields:["_creationTime"],I=w.order==="desc"?"DESC":"ASC";return r.join(E.map(C=>r`${J(C)} ${r.raw(I)}`),r`, `)},L=()=>{if(w.search||w.geo||w.indexName===void 0){f(void 0);return}f(fn(t,w.indexName,w.indexFields,w.sqlConditions,ie))},M=E=>{L();let I=0;const C=(()=>{if(w.search){const k=T(E);return I=N,k}return w.geo?jn(o,t,w,y,E,k=>{I=k}):Qn(o,t,w,y,O(),E,k=>{I=k})})();return m(Math.max(I,C.length)),C},G=()=>{if(!w.search&&!w.geo)throw new g("INTERNAL",`ctx.db.query("${t}").collectWithScores() requires a staged .withSearchIndex(...) or .withGeoIndex(...)`);L();let E=0;const I=(()=>{if(w.search){const C=_(void 0);return E=N,C}return Mt(o,t,w,y,void 0,C=>{E=C})})();return m(Math.max(E,I.length)),I},j={async*[Symbol.asyncIterator](){const E=[...w.inMemoryFilters];let I;w.inMemoryFilters=[];try{for(;;){const C=await j.paginate({cursor:I??null,numItems:Ln});for(const k of C.page)E.every(z=>z(k))&&(yield k);if(C.isDone||C.continueCursor===null)return;I=C.continueCursor}}finally{w.inMemoryFilters=E}},async collect(){return M(void 0)},async collectWithScores(){return G()},filter(E){return w.inMemoryFilters.push(E),j},async first(){return M(w.inMemoryFilters.length>0?void 0:1)[0]??null},order(E){return w.order=E==="desc"?"desc":"asc",j},async paginate(E){let I=0;if(L(),w.search){const k=v(E);return m(k.page.length),k}if(w.geo)throw new g("INTERNAL","pagination is not supported on geo queries; use .take(n) or .collect()");const C=Xn(o,t,w,E,y,k=>{I=k});return m(Math.max(I,C.page.length)),C},async take(E){return M(E)},async unique(){const E=M(w.inMemoryFilters.length>0?void 0:2);if(E.length>1)throw new Zn(`unique() on table "${t}" matched ${String(E.length)} documents; expected at most one`);return E[0]??null},withGeoIndex(E,I){const C=(b.geoIndexes??[]).find(z=>z.name===E);if(!C)throw new g("INTERNAL",`unknown geo index "${E}" on table "${t}"`);d(t,E,"geo");const k={definition:C,indexName:E};if(w.geo=k,I(qn(k,t)),!k.near&&!k.within)throw new g("INTERNAL",`geo index "${E}" on table "${t}" requires a .near(point, radius) or .within(box) call`);return j},withIndex(E,I){const C=b.indexes.find(k=>k.name===E);if(!C)throw new g("INTERNAL",`unknown index "${E}" on table "${t}"`);return d(t,E,"index"),w.indexName=E,w.indexFields=C.fields,I&&I(On(w)),j},withSearchIndex(E,I){const C=(b.searchIndexes??[]).find(z=>z.name===E);if(!C)throw new g("INTERNAL",`unknown search index "${E}" on table "${t}"`);d(t,E,"search");const k={definition:C,field:C.field,filters:[],hasQuery:!1,indexName:E,query:""};if(w.search=k,I(Sn(k,t,Qe(C.language))),!k.hasQuery)throw new g("INTERNAL",`search index "${E}" on table "${t}" requires a .search(field, query) call`);return j}};return j},yt=(o,i,t)=>{const d={...i};for(const[f,m]of St(o)){if(m.serverDefault){d[f]=m.serverDefault({auth:t});continue}d[f]===void 0&&(m.defaultFn?d[f]=m.defaultFn():"defaultValue"in m&&(d[f]=m.defaultValue))}return d},Nt=(o,i,t,d)=>{const f=t;for(const[m,b]of St(o)){if(b.serverDefault){m in i&&(f[m]=b.serverDefault({auth:d}));continue}b.onUpdateFn&&!(m in i)&&(f[m]=b.onUpdateFn())}},_t=(o,i)=>{for(const t of Object.keys(i))if(i[t]===void 0)throw new g("INTERNAL",`Cannot ${o} field '${t}' to undefined — use null to clear a nullable field, or omit the key to leave it unchanged.`)},rr=/unique constraint failed/i,or=o=>o instanceof Error&&rr.test(o.message),je=(o,i,t)=>{try{W(o,t)}catch(d){throw or(d)?new pe(`unique constraint violation on "${i}"`,"unique"):d}},Ie=(o,i,t)=>{if(je(o,i,t),W(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")},Tt=(o,i,t,d,f,m,b)=>{const S=[];for(let _=0;_<t.length+1;_+=1){const T=[];for(let M=0;M<_;M+=1)T.push(r`${r.identifier(t[M])} IS ${m[M]}`);const v=t[_],O=d[_];if(v!==void 0&&O!==void 0){const M=O.direction==="desc"?">":"<";T.push(r`${r.identifier(v)} ${r.raw(M)} ${m[_]}`)}else T.push(r`${r.identifier(cn)} < ${b}`);const[L]=T;S.push(T.length===1&&L!==void 0?L:r`(${r.join(T,r` AND `)})`)}const y=r.join(S,r` OR `),w=W(o,r`SELECT COUNT(*) AS c FROM ${r.identifier(i)} WHERE ${r.identifier("__partition__")} = ${f} AND (${y})`).one(),N=W(o,r`SELECT COUNT(*) AS c FROM ${r.identifier(i)} WHERE ${r.identifier("__partition__")} = ${f}`).one();return{before:w.c,total:N.c}},Dr=o=>{const{sql:i}=o,{schema:t}=o,d=o.broadcast??(()=>{}),f=(e,...n)=>{const a=t.tables[e]?.indexes;if(!a||a.length===0)return;const c=[];for(const h of n)h&&c.push(...un(a,h,ie));return c.length>0?c:void 0},{headroom:m}=o;let b=!1;const S=async e=>{const n=b;b=!0;try{return await e()}finally{b=n}},y=o.onRead??(()=>{}),w=o.onReadRange??(e=>{y(e.table,U)}),N=(e,n)=>{n!==void 0&&n!==U&&!b&&m?.recordRead(1),y(e,n)},_=o.onIndexUse??(()=>{}),T=o.onWrite??(()=>{}),v=e=>{b||m?.recordWrite(e)},O=async e=>{v(e.doc),await T(e)},{cache:L}=o,M=o.clock??(()=>Date.now()),G=o.idGenerator??(()=>crypto.randomUUID()),j=o.scheduler??jt,{globalDb:E}=o,I=o.auth??{identity:null,userId:null},C=o.cdc??!1,k=j,z=wn({scheduler:typeof k.list=="function"&&typeof k.get=="function"?k:void 0,storage:o.storage}),ne=(e,n,a,c)=>{C&&Jt(i,M(),e,n,a,c)},ae=e=>t.tables[e]?.shardMode?.kind==="global",Ye=(e,n)=>{if(ae(e)){if(!E)throw new g("INTERNAL",`cross-backend ${n} for global table '${e}' requires a globalDb writer — pass one to createShardCtxDb({ globalDb })`);return E}return B},ve=e=>Ye(e,"cascade"),K=(e,n)=>{if(ae(e)){if(!E)throw new g("INTERNAL",`${n} on global table '${e}' requires a globalDb writer — pass one to createShardCtxDb({ globalDb })`);return E}},ze=async(e,n,a,c,h)=>{h&&v(a);const u=await e.insert(n,a,c);return d({key:u,op:"insert",row:{...a,_id:u},table:n}),u},Ce=(e,n)=>Ye(e,"relation load").findMany(e,n),Je=(e,n)=>(ae(e)&&N(e,U),Ce(e,n)),Lt=e=>!ae(e.table),Ve=o.relationExistsPushDown??"auto",Xe=Ve!=="never",{maxRelationKeys:Ze}=o,$e=(e,n,a)=>ut(e,{fetcher:Je,maxRelationKeys:Ze,relationBaseWhere:a,schema:t,tableName:n}),et=async(e,n,a,c)=>{const h=K(e,"relation grouped count");if(h)return N(e,U),mn((P,x)=>h.count(P,x),e,n,a,c);const u=t.tables[e];if(!u)throw new g("INTERNAL",`unknown table: ${e}`);N(e,U);const s=le(u.softDeleteMode,void 0),l={[n]:{in:a}},p=Y(Y(l,c),s),R=await $e(p,e,void 0),$=te(R,oe),A=J(n);let D=r`SELECT ${A} AS __fk__, COUNT(*) AS count FROM ${r.identifier(e)}`;$&&(D=r`${D} WHERE ${$}`),D=r`${D} GROUP BY ${A}`;const F=W(i,D).toArray();return new Map(F.map(P=>[P.__fk__,P.count]))};let we=0;const tt=new Set;for(const[e,n]of Object.entries(t.tables))for(const a of Object.values(n.triggerMap??{}))tt.add(`${e} ${a.timing} ${a.op}`);const X=(e,n,a)=>tt.has(`${e} ${n} ${a}`),Z=async(e,n,a)=>{if(we+=1,we>$t)throw we-=1,new pe(`trigger recursion exceeded ${String($t)} levels on "${a.table}" — check for a self-triggering write`,"trigger");try{await gn({ctx:Ft,event:a,op:n,schema:t,tableName:a.table,timing:e})}finally{we-=1}},{ensureBackfilledForTable:ue,ensureBackfilledIndex:Me,ensureRankBackfilled:ke,ensureRankBackfilledForTable:fe,syncAggregates:ge,syncCompanionsForInsert:nt,syncGeo:be,syncRanks:he,syncSearch:Ee}=qt({broadcast:d,indexKeysFor:(e,n)=>f(e,n),invalidateCache:(e,n,a)=>L?.invalidate(e,n,f(e,a)),recordCdc:ne,schema:t,sql:i}),rt=(e,n,a)=>{const{shardMode:c}=n;if(c?.kind==="shardBy"&&!(c.field!==void 0&&(a.partitionBy??[]).includes(c.field)))throw Object.assign(new Error(`rank index "${a.name}" on "${e}" partitions across shards (shard key "${c.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})},ot=e=>Object.entries(t.tables).filter(([,n])=>n.shardMode?.kind!=="global").map(([n])=>n).filter(n=>e===void 0||n===e),re=(e,n)=>{const a=ot(n);for(let c=0;c<a.length;c+=me){const h=a.slice(c,c+me).map(R=>r`SELECT ${r.raw(`'${R.replaceAll("'","''")}'`)} AS __t__, id, _creationTime, ${r.identifier(H)} FROM ${r.identifier(R)} WHERE id = ${e}`),[u]=W(i,r`${Pe(h)} LIMIT 1`).toArray();if(!u)continue;const s=u.__t__,l=ce(u);if(typeof s!="string"||!l)return;const p=u[H];return{docJson:typeof p=="string"?p:se(p??{}),row:l,tableName:s}}},Ot=(e,n)=>{const a=[...new Set(e)],c=new Map;if(a.length===0)return c;const h=ot(n);for(let u=0;u<h.length;u+=me){const s=h.slice(u,u+me),l=Math.floor(me/s.length),p=Zt(r`${r.identifier("id")}`,a,!1,l),R=s.map($=>r`SELECT ${r.raw(`'${$.replaceAll("'","''")}'`)} AS __t__, id FROM ${r.identifier($)} WHERE ${p}`);for(const $ of W(i,Pe(R))){const{id:A,__t__:D}=$;typeof D=="string"&&typeof A=="string"&&c.set(A,D)}}return c},it={assertRankPartitionLocal:rt,ensureRankBackfilled:ke,onRead:N,rowToDocument:ce,schema:t,sql:i},B={system:z,async aggregate(e,n){const a=K(e,"aggregate");if(a)return N(e,U),a.aggregate(e,n);const c=t.tables[e];if(!c)throw new g("INTERNAL",`unknown table: ${e}`);if(Re(n.op),n.op==="count")return B.count(e,{baseWhere:n.baseWhere,relationBaseWhere:n.relationBaseWhere,restrictsCounts:n.restrictsCounts,where:n.where});if(!n.field)throw new g("INTERNAL",`aggregate(${e}, { op: "${n.op}" }): "field" is required for non-count reducers`);N(e,U);const h=le(c.softDeleteMode,void 0),u=Y(Y(n.baseWhere,n.where),h),s=await $e(u,e,n.relationBaseWhere),l=s!==u;if(c.aggregateIndexes&&!n.baseWhere&&!l&&(!h||gt(c,[n.field]))){const F=Yt(c.aggregateIndexes,n.op,n.field,n.where);if(F){Me(e,F.index);const P=De(F.index.by??[],F.key),x=Oe(e,F.index.name),Q=W(i,r`SELECT ${Ae} AS value, ${We} AS count FROM ${r.identifier(x)} WHERE ${xe} = ${P}`).toArray()[0];return Le(n.op,Q)}}bt(c,n.field,`aggregate(${e}, { op: "${n.op}", field: "${n.field}" })`);const p=te(s,oe),R=Re(n.op),$=J(n.field);let A=r`SELECT ${r.raw(R)}(${$}) AS value FROM ${r.identifier(e)}`;return p&&(A=r`${A} WHERE ${p}`),W(i,A).toArray()[0]?.value??null},asId(e,n){const a=Et(t,e,n);if(a===null)throw new g("BAD_REQUEST",`asId("${e}", …): "${n}" is not a valid id for table "${e}"`,{status:400});return a},async count(e,n){const a=K(e,"count");if(a)return N(e,U),a.count(e,n);const c=t.tables[e];if(!c)throw new g("INTERNAL",`unknown table: ${e}`);const h=Gt(n);if(h.restrictsCounts)throw new Fe(e);N(e,U);const u=le(c.softDeleteMode,void 0),s=Y(Y(h.baseWhere,h.where),u),l=await $e(s,e,h.relationBaseWhere),p=l!==s;if(c.aggregateIndexes&&!h.baseWhere&&!p&&!u){const A=Kt(c.aggregateIndexes,h.where);if(A){Me(e,A.index);const D=De(A.index.by??[],A.key),F=Oe(e,A.index.name),P=W(i,r`SELECT ${Ae} AS value FROM ${r.identifier(F)} WHERE ${xe} = ${D}`).toArray();return P[0]===void 0?0:P[0].value??0}}const R=te(l,oe);let $=r`SELECT COUNT(*) AS count FROM ${r.identifier(e)}`;return R&&($=r`${$} WHERE ${R}`),W(i,$).one().count},async delete(e,n,a){const c=re(e,n);if(!c){const $=n===void 0?E:void 0;$&&(v(void 0),await $.delete(e,void 0,a));return}const{docJson:h,row:u,tableName:s}=c,l=t.tables[s],p=a?.hard===!0,R=!p&&l?.softDeleteMode?l.softDeleteMode.field:void 0;if(!(R&&u[R]!==null&&u[R]!==void 0)){if(X(s,"before","delete")&&await Z("before","delete",{id:e,op:"delete",previous:u,table:s}),await hn({deletedId:e,deletedReference:$=>u[$],findHolders:async($,A,D)=>(await ve($).findMany($,{includeDeleted:p,where:{[A]:D}})).page,onCascade:($,A)=>ve($).delete(A,void 0,a),onRestrict:$=>{throw new pe($,"restrict")},onSetNull:($,A,D)=>ve($).patch(A,{[D]:null}),schema:t,tableName:s}),ue(s),fe(s),R){const $={...u,[R]:M(),_id:e};Ie(i,s,r`UPDATE ${r.identifier(s)} SET ${r.identifier(H)} = ${se($)} WHERE id = ${e} AND ${r.identifier(H)} = ${h}`),Ee(s,e,$,u),be(s,e,void 0),ge(s,u,$),he(s,e,u,void 0),L?.invalidate(s,e,f(s,u,$)),ne(s,e,"update",$),d({indexKeys:f(s,u,$),key:e,op:"update",row:$,table:s}),X(s,"after","delete")&&await Z("after","delete",{id:e,op:"delete",previous:u,table:s}),await O({id:e,op:"delete",table:s});return}Ie(i,s,r`DELETE FROM ${r.identifier(s)} WHERE id = ${e} AND ${r.identifier(H)} = ${h}`),Ee(s,e,void 0),be(s,e,void 0),ge(s,u,void 0),he(s,e,u,void 0),L?.invalidate(s,e,f(s,u)),ne(s,e,"delete"),d({indexKeys:f(s,u),key:e,op:"delete",table:s}),X(s,"after","delete")&&await Z("after","delete",{id:e,op:"delete",previous:u,table:s}),await O({id:e,op:"delete",table:s})}},async deleteAll(e,n){if(!t.tables[e])throw new g("INTERNAL",`unknown table: ${e}`);const a=Math.max(1,n?.chunkSize??It),c=n?.hard===void 0?void 0:{hard:n.hard},h=ae(e)?void 0:e;let u=0;return await S(async()=>{for(;;){const s=(await B.findMany(e,{limit:a})).page.map(l=>String(l._id));if(s.length===0)break;for(const l of s)await B.delete(l,h,c),u+=1;if(s.length<a)break}}),{deleted:u}},async deleteMany(e,n,a){de(e.length,n?.limit,"deleteMany");for(const c of e)await B.delete(c,a);return{deleted:e.length}},async deleteWhere(e,n,a){const c=(await(K(e,"deleteWhere")??B).findMany(e,{where:n})).page.map(h=>String(h._id));if(de(c.length,a?.limit,"deleteWhere"),B.deleteMany===void 0)throw new g("INTERNAL",`ctx.db.${e}.deleteMany is unavailable: this writer has no batch delete`);return B.deleteMany(c,a)},async findFirst(e,n={}){return(await B.findMany(e,{...n,limit:1})).page[0]??null},async findFirstOrThrow(e,n={}){const a=await B.findFirst(e,n);if(a===null)throw new on(`findFirstOrThrow: no "${e}" document matched`);return a},async findMany(e,n={}){const a=K(e,"findMany");if(a)return N(e,U),a.findMany(e,n);const c=t.tables[e];if(!c)throw new g("INTERNAL",`unknown table: ${e}`);const h=!n.where&&!n.baseWhere;h?N(e,U):N(e);const u=an(n.orderBy),s=n.cursor?xt(u,He(n.cursor)):void 0;let l=Y(n.baseWhere,n.where);l=Y(l,le(c.softDeleteMode,n.includeDeleted)),l=await ut(l,{canPushExists:Xe?Lt:void 0,existsPushMode:Ve==="always"?"always":"auto",fetcher:Je,maxRelationKeys:Ze,relationBaseWhere:n.relationBaseWhere,schema:t,tableName:e}),s&&(l=l?{AND:[l,s]}:s);const p=Xe?Kn(N):oe,R=te(l,p);let $=r`SELECT id, _creationTime, ${r.identifier(H)} FROM ${r.identifier(e)}`;R&&($=r`${$} WHERE ${R}`),$=r`${$} ORDER BY ${Dt(u)}`;const A=typeof n.limit=="number"?Math.max(0,Math.floor(n.limit)):void 0;A!==void 0&&($=r`${$} LIMIT ${r.raw(String(A+1))}`);const D=W(i,$).toArray();h&&!b&&m?.recordRead(D.length);const F=[];for(const ee of D){const q=ce(ee);q&&(F.push(q),!h&&typeof q._id=="string"&&N(e,q._id))}if(A===void 0)return n.with&&await ft({groupedCounter:et,fetcher:Ce,parents:F,...ht(n),schema:t,tableName:e,with:n.with}),{continueCursor:null,isDone:!0,page:dt(F,n.select,n.with)};const P=F.length>A,x=P?F.slice(0,A):F,Q=x.at(-1);return n.with&&await ft({fetcher:Ce,groupedCounter:et,parents:x,...ht(n),schema:t,tableName:e,with:n.with}),{continueCursor:P&&Q?Ge(Q,u):null,isDone:!P,page:dt(x,n.select,n.with)}},async get(e,n){const a=re(e,n);if(!a){const c=n===void 0?E:void 0;return c?c.get(e):null}return N(a.tableName,e),a.row},async lookupById(e,n){const a=re(e,n);return a?(N(a.tableName,e),{row:a.row,tableName:a.tableName}):null},async groupBy(e,n){const a=K(e,"groupBy");if(a)return N(e,U),a.groupBy(e,n);const c=t.tables[e];if(!c)throw new g("INTERNAL",`unknown table: ${e}`);N(e,U);const h=n.agg??{op:"count"};if(Re(h.op),h.op!=="count"&&!h.field)throw new g("INTERNAL",`groupBy(${e}, { agg: { op: "${h.op}" } }): "field" is required for non-count reducers`);const u=le(c.softDeleteMode,void 0),s=Y(Y(n.baseWhere,n.where),u),l=await $e(s,e,n.relationBaseWhere),p=l!==s,R=[...n.by,h.field];if(c.aggregateIndexes&&!n.baseWhere&&!p&&(!u||gt(c,R))){const x=Qt(c.aggregateIndexes,h.op,h.field,n.by,n.where),Q=x===void 0?0:Object.keys(x.partial).length,ee=x?.index.by?.length??0;if(x&&(Q===0||Q===ee)){Me(e,x.index);const q=Oe(e,x.index.name),ye=Object.keys(x.partial),Ne=[];if(ye.length===(x.index.by??[]).length&&ye.length>0){const _e=De(x.index.by??[],x.partial),Te=W(i,r`SELECT ${Ae} AS value, ${We} AS count FROM ${r.identifier(q)} WHERE ${xe} = ${_e}`).toArray();return Te.length>0&&Ne.push({key:{...x.partial},value:Le(h.op,Te[0])}),Ne}const Wt=W(i,r`SELECT ${xe} AS key, ${Ae} AS value, ${We} AS count FROM ${r.identifier(q)}`).toArray();for(const _e of Wt){const Te=Ht(JSON.parse(_e.key));Ne.push({key:Te,value:Le(h.op,_e)})}return Ne}}for(const x of R){if(x===void 0)continue;const Q=x===h.field?`groupBy(${e}, { agg: { op: "${h.op}", field: "${x}" } })`:`groupBy(${e}, { by: [..."${x}"] })`;bt(c,x,Q)}const $=te(l,oe),A=n.by.map(x=>r`${J(x)} AS ${r.identifier(x)}`);if(h.op==="count")A.push(r`COUNT(*) AS value`);else{const{field:x}=h;if(x===void 0)throw new g("INTERNAL",`groupBy(${e}, { agg: { op: "${h.op}" } }): "field" is required for non-count reducers`);A.push(r`${r.raw(Re(h.op))}(${J(x)}) AS value`)}let D=r`SELECT ${r.join(A,r`, `)} FROM ${r.identifier(e)}`;$&&(D=r`${D} WHERE ${$}`),D=r`${D} GROUP BY ${r.join(n.by.map(x=>J(x)),r`, `)}`;const F=W(i,D).toArray(),P=[];for(const x of F){const Q={};for(const q of n.by)Q[q]=x[q]??null;const{value:ee}=x;P.push({key:Q,value:ee==null?null:Number(ee)})}return P},async insert(e,n,a){const c=K(e,"insert");if(c)return ze(c,e,n,a,!0);const h=t.tables[e];if(!h)throw new g("INTERNAL",`unknown table: ${e}`);const u=yt(h,n,I);qe(h,u);let s;a?.clientId!==void 0?(Dn(a.clientId),s=a.clientId):a?.allowExplicitId&&typeof u._id=="string"?s=u._id:s=G();const l=a?.allowExplicitId&&typeof u._creationTime=="number"?u._creationTime:M(),p={...u,_creationTime:l,_id:s};return X(e,"before","insert")&&await Z("before","insert",{doc:{...p},id:s,op:"insert",table:e}),ue(e),fe(e),je(i,e,r`INSERT INTO ${r.identifier(e)} (id, _creationTime, ${r.identifier(H)}) VALUES (${s}, ${l}, ${se(p)})`),nt(e,s,p),X(e,"after","insert")&&await Z("after","insert",{doc:p,id:s,op:"insert",table:e}),await O({doc:p,id:s,op:"insert",table:e}),s},async insertManyUnsafe(e,n,a){if(de(n.length,a?.limit,"insertManyUnsafe"),n.length===0)return[];const c=K(e,"insert");if(c){const s=[];for(const l of n)v(l);for(const l of n){const p=await c.insert(e,l,{allowExplicitId:a?.allowExplicitId});d({key:p,op:"insert",row:{...l,_id:p},table:e}),s.push(p)}return s}const h=t.tables[e];if(!h)throw new g("INTERNAL",`unknown table: ${e}`);ue(e),fe(e);const u=n.map(s=>{const l=yt(h,s,I),p=a?.allowExplicitId===!0&&typeof l._id=="string"?l._id:G(),R=a?.allowExplicitId===!0&&typeof l._creationTime=="number"?l._creationTime:M();return{creationTime:R,document:{...l,_creationTime:R,_id:p},id:p}});for(const s of u)v(s.document);for(let s=0;s<u.length;s+=wt){const l=r.join(u.slice(s,s+wt).map(p=>r`(${p.id}, ${p.creationTime}, ${se(p.document)})`),r`, `);je(i,e,r`INSERT INTO ${r.identifier(e)} (id, _creationTime, ${r.identifier(H)}) VALUES ${l}`)}for(const{document:s,id:l}of u)nt(e,l,s),await T({doc:s,id:l,op:"insert",table:e});return u.map(s=>s.id)},async insertMany(e,n,a){de(n.length,a?.limit,"insertMany");const c=a?.skipDuplicates===!0,h=[],u=K(e,"insert");if(u)for(const l of n)v(l);const s=async l=>u?ze(u,e,l,void 0,!1):B.insert(e,l);for(const l of n)try{h.push(await s(l))}catch(p){if(c&&p instanceof pe&&p.kind==="unique")h.push(null);else throw p}return h},normalizeId(e,n){return Et(t,e,n)},async patch(e,n,a){const c=re(e,a);if(!c){const R=a===void 0?E:void 0;if(R){v(n),await R.patch(e,n);return}throw new g("INTERNAL",`document not found: ${e}`)}const{docJson:h,row:u,tableName:s}=c,l=t.tables[s];if(!l)throw new g("INTERNAL",`unknown table: ${s}`);N(s,e),_t("patch",n);const p={...u,...n,_id:e};Nt(l,n,p,I),qe(l,p,!0),X(s,"before","update")&&await Z("before","update",{doc:{...p},id:e,op:"update",previous:u,table:s}),ue(s),fe(s),Ie(i,s,r`UPDATE ${r.identifier(s)} SET ${r.identifier(H)} = ${se(p)} WHERE id = ${e} AND ${r.identifier(H)} = ${h}`),Ee(s,e,p,u),be(s,e,p),ge(s,u,p),he(s,e,u,p),L?.invalidate(s,e,f(s,u,p)),ne(s,e,"update",p),d({indexKeys:f(s,u,p),key:e,op:"update",row:p,table:s}),X(s,"after","update")&&await Z("after","update",{doc:p,id:e,op:"update",previous:u,table:s}),await O({doc:p,id:e,op:"update",table:s})},async patchMany(e,n,a){de(e.length,n?.limit,"patchMany");for(const c of e)await B.patch(c.id,c.patch,a);return{patched:e.length}},async patchWhere(e,n,a){const c=(await(K(e,"patchWhere")??B).findMany(e,{where:n.where})).page.map(h=>({id:String(h._id),patch:n.patch}));if(de(c.length,a?.limit,"patchWhere"),B.patchMany===void 0)throw new g("INTERNAL",`ctx.db.${e}.patchMany is unavailable: this writer has no batch patch`);return await B.patchMany(c,a),{patched:c.length}},query(e){const n=K(e,"query");return n?(N(e,U),n.query(e)):nr(i,t,e,_,a=>{a?w(a):N(e,U)},a=>{b||m?.recordRead(a)})},async rank(e,n,a){const c=K(e,"rank");if(c)return N(e,U),c.rank(e,n,a);_(e,n,"rank");const h=t.tables[e];if(!h)throw new g("INTERNAL",`unknown table: ${e}`);const u=h.rankIndexes?.find(q=>q.name===n);if(!u)throw new g("INTERNAL",`unknown rankIndex "${n}" on table "${e}"`);if(rt(e,h,u),a.restrictsCounts)throw new Fe(e);N(e,U),ke(e,u);const s=typeof a.row=="string"?a.row:a.row._id;if(!s)return null;const l=ct(e,u.name),p=u.sortBy.map((q,ye)=>lt(ye)),R=p.map(q=>bn(q)).join(", "),$=W(i,r`SELECT ${r.identifier("__partition__")}, ${r.raw(R)} FROM ${r.identifier(l)} WHERE ${r.identifier("__id__")} = ${s}`).toArray(),[A]=$;if(A===void 0)return null;let D=A.__partition__;const F=Y(a.baseWhere,a.where);Be(F,t,e,"rank");const P=dn(u,F);if(P){const q=ln(u.partitionBy??[],P);if(q!==D)return null;D=q}const x=p.map(q=>A[q]),{before:Q,total:ee}=Tt(i,l,p,u.sortBy,D,x,s);return{position:Q+1,total:ee}},async rankBefore(e,n,a){if(ae(e))throw new g("INTERNAL",`rankBefore is not supported on the global (.global()) table '${e}' — cross-shard rank cursors apply only to sharded tables`);const c=t.tables[e];if(!c)throw new g("INTERNAL",`unknown table: ${e}`);const h=c.rankIndexes?.find(p=>p.name===n);if(!h)throw new g("INTERNAL",`unknown rankIndex "${n}" on table "${e}"`);if(a.restrictsCounts)throw new Fe(e);N(e,U),ke(e,h);const u=ct(e,h.name),s=h.sortBy.map((p,R)=>lt(R)),l=h.sortBy.map((p,R)=>ie(a.sortValues[R]??null));return Tt(i,u,s,h.sortBy,a.partitionKey,l,a.rowId)},async rankPage(e,n,a={}){Be(Y(a.baseWhere,a.where),t,e,"rankPage");const c=K(e,"rankPage");if(c)return N(e,U),c.rankPage(e,n,a);_(e,n,"rank");const{continueCursor:h,hasMore:u,rows:s}=at(it,e,n,a);return{continueCursor:h,isDone:!u,page:s.map(l=>l.doc)}},async rankPageRows(e,n,a={}){Be(Y(a.baseWhere,a.where),t,e,"rankPage"),_(e,n,"rank");const{directions:c,hasMore:h,rows:u}=at(it,e,n,a);return{directions:c,hasMore:h,rows:u}},async restore(e,n){const a=re(e,n);if(!a){const u=n===void 0?E:void 0;if(u?.restore){await u.restore(e);return}throw new g("INTERNAL",`document not found: ${e}`)}const c=t.tables[a.tableName]?.softDeleteMode?.field;if(!c)throw new g("INTERNAL",`ctx.db.restore: table "${a.tableName}" is not a .softDelete() table`);const h=a.row[c]!==null&&a.row[c]!==void 0;await B.patch(e,{[c]:null},n),h&&he(a.tableName,e,void 0,a.row)},async replace(e,n,a,c){const h=re(e,a);if(!h){const A=a===void 0?E:void 0;if(A){v(n),await A.replace(e,n,void 0,c);return}throw new g("INTERNAL",`document not found: ${e}`)}const{docJson:u,row:s,tableName:l}=h,p=t.tables[l];if(!p)throw new g("INTERNAL",`unknown table: ${l}`);_t("replace",n);const R=c?.allowExplicitId&&typeof n._creationTime=="number"?n._creationTime:M(),$={...n,_creationTime:R,_id:e};Nt(p,n,$,I),qe(p,$),X(l,"before","update")&&await Z("before","update",{doc:{...$},id:e,op:"update",previous:s,table:l}),ue(l),fe(l),Ie(i,l,r`UPDATE ${r.identifier(l)} SET _creationTime = ${R}, ${r.identifier(H)} = ${se($)} WHERE id = ${e} AND ${r.identifier(H)} = ${u}`),Ee(l,e,$,s),be(l,e,$),ge(l,s,$),he(l,e,s,$),L?.invalidate(l,e,f(l,s,$)),ne(l,e,"update",$),d({indexKeys:f(l,s,$),key:e,op:"update",row:$,table:l}),X(l,"after","update")&&await Z("after","update",{doc:$,id:e,op:"update",previous:s,table:l}),await O({doc:$,id:e,op:"update",table:l})},async wipeShard(e){const n=new Set(e?.exclude),a=e?.tables,c=Object.entries(t.tables).filter(([l,p])=>n.has(l)||a!==void 0&&!a.includes(l)?!1:p.shardMode?.kind!=="global").map(([l])=>l);if(a!==void 0){for(const l of a)if(!t.tables[l])throw new g("INTERNAL",`wipeShard: unknown table: ${l}`)}const h={};let u=0;const{deleteAll:s}=B;if(s===void 0)throw new g("INTERNAL","wipeShard: this writer has no deleteAll");for(const l of c){const p=await s(l,{...e?.chunkSize===void 0?{}:{chunkSize:e.chunkSize},hard:!0});h[l]=p.deleted,u+=p.deleted}return{deleted:u,tables:h}}},Ft={db:B,scheduler:j};return o.enforceRls===!0?pn(B,t,(e,n)=>re(e,n)?.tableName,(e,n)=>Ot(e,n)):B};export{Ur as CDC_LOG_TABLE,Jr as CLIENT_WATERMARK_TABLE,to as GLOBAL_SHAPE_SNAPSHOT_TABLE,lo as IDEMPOTENCY_TABLE,Zn as NotUniqueError,$o as SEARCH_STATE_TABLE,Vr as advanceClientWatermark,Pr as applyCdcChanges,Dn as assertValidClientId,Fr as backfillAggregateIndexes,Wr as backfillRankIndexes,Br as backfillSearchIndexes,Hr as bumpCdcEpoch,Dr as createShardCtxDb,no as deleteGlobalShapeSnapshot,ro as deleteGlobalShapeSnapshotsForConnection,Xr as migrateClientWatermark,oo as migrateGlobalShapeSnapshot,Gr as minCdcSeq,Et as normalizeIdStructurally,jr as readCdcChanges,Qr as readCdcCursor,Kr as readCdcEpoch,Zr as readClientWatermark,io as readGlobalShapeSnapshot,co as readIdempotent,mo as runShardMigrations,go as selectShapeMemberIds,bo as selectShapeRows,Yr as trimCdcChanges,uo as trimIdempotent,ao as writeGlobalShapeSnapshot,fo as writeIdempotent};
|
|
1
|
+
import{LunoraError as g}from"@lunora/errors";import{n as Bt,S as qt,x as Qe,T as Se,y as Ut,c as Pt}from"./ctx-db-companions-BJlCofon.mjs";import{sql as r}from"drizzle-orm";import{s as Ht}from"./wire-codec-Dh0j-GnY.mjs";import{aggregateSqlFunction as Re,normalizeCountArgument as Gt,throwingScheduler as jt}from"./AGGREGATE_SQL_FUNCTION-CTo0-9iZ.mjs";import{encodeAggregateKey as De,readAggregateValue as Le,aggregateTableName as Oe}from"./aggregateTableName-DN7gk6uh.mjs";import{mergeWhere as Y,CountRlsUnsupportedError as Fe,selectIndexForGroupBy as Qt,selectIndexForCount as Kt,selectIndexForAggregate as Yt}from"./CountRlsUnsupportedError-8BqPYQoP.mjs";import{backfillSearchIndexesForTable as zt}from"./backfillAggregateIndexes-DTOIsYbi.mjs";import{backfillAggregateIndexes as Fr,backfillRankIndexes as Wr,backfillSearchIndexes as Br}from"./backfillAggregateIndexes-DTOIsYbi.mjs";import{appendCdcChange as Jt}from"./CDC_LOG_TABLE-DNFFQwF_.mjs";import{CDC_LOG_TABLE as Ur,applyCdcChanges as Pr,bumpCdcEpoch as Hr,minCdcSeq as Gr,readCdcChanges as jr,readCdcCursor as Qr,readCdcEpoch as Kr,trimCdcChanges as Yr}from"./CDC_LOG_TABLE-DNFFQwF_.mjs";import{computeRankPage as at}from"./computeRankPage-BU8LXvQs.mjs";import{SCAN_DEP as U}from"./SCAN_DEP-D_yR9EeV.mjs";import{runDrizzle as W}from"./runDrizzle-C3n5gJsk.mjs";import{a as H,L as se,p as Ae,T as We,c as xe,N as J,E as ce,I as St,C as Vt,D as Rt,h as Xt,O as st}from"./do-sql-DKSFK627.mjs";import{WORKERD_SQLITE_LIMITS as At,unionAll as Pe,sqliteInList as Zt}from"./param-CYxL68V-.mjs";import{coveringGeohashes as en,boundingBoxGeohashes as tn,pointInBoundingBox as nn,haversineMeters as rn}from"./GEO_DEFAULT_PRECISION-DyI5zggj.mjs";import{NotFoundError as on}from"./NotFoundError-BhF7FeFr.mjs";import{normalizeOrderKeys as an,buildSeekWhere as xt,decodeCursor as He,applySelect as dt,encodeCursor as Ge,softDeleteScope as le,buildSeekBeforeWhere as sn}from"./applySelect-5w13bMAR.mjs";import{sortColumnName as lt,resolveRankPartition as dn,encodePartitionKey as ln,RANK_TIEBREAK as cn,rankTableName as ct}from"./RANK_TIEBREAK-BGk411OR.mjs";import{indexKeysForRow as un,buildIndexRange as fn}from"./buildIndexRange-DFsdtPjD.mjs";import{assertFlatPredicate as Be,resolveRelationPredicates as ut}from"./DEFAULT_MAX_RELATION_KEYS-BV1RCoat.mjs";import{runRowValidators as qe,resolveWith as ft,relationHooks as ht,applyOnDelete as hn,fanOutScalarCounts as mn}from"./applyOnDelete-crbAzVfE.mjs";import{guardWriter as pn}from"./RLS_UNWRAP_SYMBOL-DcqORh2s.mjs";import{f as $n}from"./sql-projection-jfoe331H.mjs";import{createSystemReader as wn}from"./createSystemReader-DcDcrtM3.mjs";import{ConflictError as pe}from"./ConflictError-C8GtJmjS.mjs";import{runTriggers as gn}from"./hasTrigger-CbkOHExZ.mjs";import{compileWhereSql as te}from"./compileWhereSql-B3hq_v98.mjs";import{CLIENT_WATERMARK_TABLE as Jr,advanceClientWatermark as Vr,migrateClientWatermark as Xr,readClientWatermark as Zr}from"./CLIENT_WATERMARK_TABLE-LrKfdxyt.mjs";import{GLOBAL_SHAPE_SNAPSHOT_TABLE as to,deleteGlobalShapeSnapshot as no,deleteGlobalShapeSnapshotsForConnection as ro,migrateGlobalShapeSnapshot as oo,readGlobalShapeSnapshot as io,writeGlobalShapeSnapshot as ao}from"./GLOBAL_SHAPE_SNAPSHOT_TABLE-B2LKe4KU.mjs";import{IDEMPOTENCY_TABLE as lo,readIdempotent as co,trimIdempotent as uo,writeIdempotent as fo}from"./IDEMPOTENCY_TABLE-tQ5mnqvw.mjs";import{runShardMigrations as mo}from"./runShardMigrations-BCuK60KT.mjs";import{SEARCH_STATE_TABLE as $o}from"./SEARCH_STATE_TABLE-DRk_SB72.mjs";import{selectShapeMemberIds as go,selectShapeRows as bo}from"./selectShapeMemberIds-Bkkug6vU.mjs";import{serializeSqlValue as ie}from"./serializeSqlValue-BR4UOWoP.mjs";import{quoteIdentifier as bn}from"./quoteIdentifier-CObIFRhb.mjs";const En=o=>{const i=new TextEncoder().encode(o);let t="";for(const d of i)t+=String.fromCodePoint(d);return btoa(t)},yn=o=>{const i=atob(o),t=Uint8Array.from(i,d=>d.codePointAt(0)??0);return new TextDecoder().decode(t)},Nn=()=>new g("BAD_REQUEST","invalid cursor"),mt=16,pt=8,V=1024,Ke=(o,i)=>i.query(o),_n=(o,i,t)=>{const d=Bt(o,t);if(d.length===0)return 0;let f=0;for(const[m,b]of i.entries()){const S=m===i.length-1;let y=0;for(const w of d)(S?w.startsWith(b):w===b)&&(y+=1);if(y===0)return 0;f+=y}return f},Tn=(o,i)=>{if(!i)return{exact:!0,lower:o,upper:o};const t=[...o].at(-1)??"",d=(t.codePointAt(0)??0)+1;if(d>=55296&&d<=57343||d>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(d)}},Sn=(o,i,t)=>{const d={eq:(f,m)=>{if(!o.definition.filterFields?.includes(f))throw new g("INTERNAL",`field "${f}" is not a filter field of search index "${o.indexName}" on table "${i}"`);if(o.filters.length>=pt)throw new g("BAD_REQUEST",`search index "${o.indexName}" on table "${i}": at most ${String(pt)} .eq() filters are supported per search query`);return o.filters.push({field:f,value:m}),d},search:(f,m)=>{const b=o;if(f!==b.definition.field)throw new g("INTERNAL",`search index "${b.indexName}" on table "${i}" indexes "${b.definition.field}", not "${f}"`);const S=Ke(m,t).length;if(S>mt)throw new g("BAD_REQUEST",`search index "${b.indexName}" on table "${i}": at most ${String(mt)} search terms are supported (got ${String(S)})`);return b.field=f,b.query=m,b.hasQuery=!0,d}};return d},Rn=o=>{if(o.length>V)throw new g("BAD_REQUEST",`more than ${String(V)} documents match this search — narrow it with filters or read it a page at a time with .paginate()`)},An=o=>Math.min(o.offset+o.numItems+1,V),xn=o=>En(`search:${String(o)}`),In=o=>{let i;try{i=yn(o)}catch{return}if(!i.startsWith("search:"))return;const t=Number(i.slice(7));return Number.isInteger(t)&&t>=0?t:void 0},vn=o=>{if(typeof o.endCursor=="string")throw new g("BAD_REQUEST","bounded (endCursor) pagination is not supported on search queries — relevance order has no stable range boundary");const i=Math.max(0,Math.floor(o.numItems)),t=o.cursor?In(o.cursor):0;if(t===void 0)throw Nn();if(t+i>V)throw new g("BAD_REQUEST",`search pagination reaches past the ${String(V)}-document limit (offset ${String(t)} + ${String(i)} requested) — narrow the query or the filters instead`);return{numItems:i,offset:t}},Cn=(o,i)=>{const t=i.offset+i.numItems,d=i.numItems>0&&o.length>t;return{continueCursor:d?xn(t):null,isDone:!d,page:o.slice(i.offset,t)}},Mn=o=>{if(o===void 0)return V+1;if(!Number.isFinite(o))return V;const i=Math.max(0,Math.floor(o));if(i>V)throw new g("BAD_REQUEST",`search returns at most ${String(V)} documents (asked for ${String(i)}) — narrow the query or paginate instead`);return i},kn=/^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/iu,Dn=o=>{if(!kn.test(o))throw new g("INTERNAL",`invalid clientId ${JSON.stringify(o)}: a client-supplied row id must be a UUID`)},$t=50,It=500,wt=Math.floor(At.boundParams/3),me=At.boundParams,Ln=128,de=(o,i,t)=>{const d=i??It;if(o>d)throw new g("BATCH_LIMIT_EXCEEDED",`${t}: batch of ${String(o)} exceeds the limit of ${String(d)} (raise options.limit or chunk the call)`,{status:400})},On=o=>{const i={eq:(t,d)=>(o.sqlConditions.push({comparator:"=",field:t,value:d}),i),gt:(t,d)=>(o.sqlConditions.push({comparator:">",field:t,value:d}),i),gte:(t,d)=>(o.sqlConditions.push({comparator:">=",field:t,value:d}),i),lt:(t,d)=>(o.sqlConditions.push({comparator:"<",field:t,value:d}),i),lte:(t,d)=>(o.sqlConditions.push({comparator:"<=",field:t,value:d}),i)};return i},Fn=o=>Math.max(o,V),vt=(o,i)=>{const t=o.filters.map(d=>r`${J(d.field)} = ${ie(d.value)}`);return i&&t.push(i),t},Wn=(o,i,t,d,f)=>{const m=Ke(t.query,Qe(t.definition.language));if(m.length===0)return[];const b=Pt(i,t.indexName),S=`${b}__vocab`,y=m.length-1,w=m.map((L,M)=>{const G=Tn(L,M===y),j=G.exact?r`${r.identifier("term")} = ${G.lower}`:r`${r.identifier("term")} >= ${G.lower} AND ${r.identifier("term")} < ${G.upper}`;return r`SELECT ${r.identifier("doc")}, ${r.raw(String(M))} AS ${r.identifier("__term__")}, COUNT(*) AS ${r.identifier("__n__")} FROM ${r.identifier(S)} WHERE ${j} GROUP BY ${r.identifier("doc")}`}),N=m.map((L,M)=>r`SUM(CASE WHEN u.${r.identifier("__term__")} = ${r.raw(String(M))} THEN u.${r.identifier("__n__")} ELSE 0 END)`),_=r`SELECT f.${r.identifier(Se)} AS ${r.identifier(Se)}, ${r.join(N,r` + `)} AS ${r.identifier("__score__")} FROM (${Pe(w)}) u JOIN ${r.identifier(b)} f ON f.rowid = u.${r.identifier("doc")} GROUP BY f.${r.identifier(Se)} HAVING ${r.join(N.map(L=>r`${L} > 0`),r` AND `)}`,T=vt(t,f);let v=r`SELECT m.id, m._creationTime, m.${r.identifier(H)}, s.${r.identifier("__score__")} AS ${r.identifier("__score__")} FROM (${_}) s JOIN ${r.identifier(i)} m ON m.id = s.${r.identifier(Se)}`;T.length>0&&(v=r`${v} WHERE ${r.join(T,r` AND `)}`),v=r`${v} ORDER BY s.${r.identifier("__score__")} DESC, m._creationTime DESC, m.id ASC LIMIT ${r.raw(String(d))}`;const O=[];for(const L of W(o,v)){const M=Rt(L);if(M){const G=L.__score__;O.push({document:M,score:typeof G=="number"?G:Number(G??0)})}}return O},Bn=(o,i,t,d,f)=>{const m=Qe(t.definition.language),b=Ke(t.query,m);if(b.length===0)return[];const S=vt(t,f);let y=r`SELECT id, _creationTime, ${r.identifier(H)} FROM ${r.identifier(i)}`;S.length>0&&(y=r`${y} WHERE ${r.join(S,r` AND `)}`),y=r`${y} ORDER BY _creationTime DESC, id ASC LIMIT ${r.raw(String(Fn(d)))}`;const w=W(o,y).toArray(),N=[];for(const _ of w){const T=Rt(_);if(!T)continue;const v=_n(Ut(T,t.definition),b,m);v>0&&N.push({creationTime:typeof T._creationTime=="number"?T._creationTime:0,doc:T,id:typeof T._id=="string"?T._id:"",score:v})}return N.sort((_,T)=>T.score-_.score||T.creationTime-_.creationTime||_.id.localeCompare(T.id)),N.slice(0,d).map(_=>({document:_.doc,score:_.score}))},Ue=(o,i,t,d)=>{if(!Number.isFinite(o.lat)||o.lat<-90||o.lat>90||!Number.isFinite(o.lng)||o.lng<-180||o.lng>180)throw new g("BAD_REQUEST",`geo index "${d}" on table "${t}": ${i} must have a finite lat in [-90, 90] and lng in [-180, 180]`)},qn=(o,i)=>{const t=o,d={near:(f,m)=>{if(t.within)throw new g("INTERNAL",`geo index "${t.indexName}" on table "${i}": call .near() or .within(), not both`);if(Ue(f,".near() point",i,t.indexName),!Number.isFinite(m)||m<=0)throw new g("BAD_REQUEST",`geo index "${t.indexName}" on table "${i}": .near() radiusMeters must be a finite number > 0, got ${String(m)}`);return t.near={point:{lat:f.lat,lng:f.lng},radiusMeters:m},d},within:f=>{if(t.near)throw new g("INTERNAL",`geo index "${t.indexName}" on table "${i}": call .near() or .within(), not both`);if(Ue(f.sw,".within() sw corner",i,t.indexName),Ue(f.ne,".within() ne corner",i,t.indexName),f.sw.lat>f.ne.lat)throw new g("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 g("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}},d}};return d},Un=(o,i)=>{const t=o[i];if(t===null||typeof t!="object")return;const{lat:d,lng:f}=t;return typeof d=="number"&&typeof f=="number"?{lat:d,lng:f}:void 0},Pn=(o,i)=>{const t=Un(o,i.definition.field);if(!t)return;const d=typeof o._creationTime=="number"?o._creationTime:0;if(i.near){const f=rn(i.near.point,t);return f<=i.near.radiusMeters?{creationTime:d,distance:f}:void 0}return nn(t,i.within)?{creationTime:d,distance:0}:void 0},Hn=(o,i,t,d)=>{if(!t.near&&!t.within)throw new g("INTERNAL",`geo index "${t.indexName}" on table "${i}": call .near(point, radius) or .within(box)`);const f=t.near?en(t.near.point,t.near.radiusMeters):tn(t.within),m=Xt(i,t.indexName),b=f.map(_=>r`(g.${r.identifier("__geohash__")} >= ${_} AND g.${r.identifier("__geohash__")} < ${`${_}{`})`),S=[r`(${r.join(b,r` OR `)})`];d&&S.push(d);const y=r`SELECT m.id, m._creationTime, m.${r.identifier(H)} FROM ${r.identifier(m)} g JOIN ${r.identifier(i)} m ON m.id = g.${r.identifier("__id__")} WHERE ${r.join(S,r` AND `)}`,w=W(o,y).toArray(),N=[];for(const _ of w){const T=ce(_),v=T?Pn(T,t):void 0;T&&v&&N.push({creationTime:v.creationTime,distance:v.distance,doc:T})}return N.sort((_,T)=>_.distance-T.distance||T.creationTime-_.creationTime),N},Ct=(o,i,t,d)=>{const f=[];for(const m of o)if(i.every(b=>b(d(m)))&&(f.push(m),typeof t=="number"&&f.length>=t))break;return f},Gn=(o,i,t,d,f,m=()=>{})=>{const b=t.within!==void 0,S=Hn(o,i,t,f).map(y=>({distanceMeters:b?null:y.distance,document:y.doc}));return m(S.length),typeof d=="number"?S.slice(0,Math.max(0,Math.floor(d))):S},Mt=(o,i,t,d,f,m=()=>{})=>{const{geo:b}=t;if(!b)throw new g("INTERNAL","runGeoTerminalScored called without a staged geo query");const S=t.inMemoryFilters.length>0,y=Gn(o,i,b,S?void 0:f,d,m);return S?Ct(y,t.inMemoryFilters,f,w=>w.document):y},jn=(o,i,t,d,f,m=()=>{})=>Mt(o,i,t,d,f,m).map(b=>b.document),Qn=(o,i,t,d,f,m,b=()=>{})=>{const S=[];for(const _ of t.sqlConditions)S.push(r`${J(_.field)} ${r.raw(_.comparator)} ${ie(_.value)}`);d&&S.push(d);let y=r`SELECT id, _creationTime, ${r.identifier(H)} FROM ${r.identifier(i)}`;S.length>0&&(y=r`${y} WHERE ${r.join(S,r` AND `)}`),y=r`${y} ORDER BY ${f}`,typeof m=="number"&&t.inMemoryFilters.length===0&&(y=r`${y} LIMIT ${r.raw(String(Math.max(0,Math.floor(m))))}`);const w=W(o,y).toArray();b(w.length);const N=[];for(const _ of w){const T=ce(_);if(T&&t.inMemoryFilters.every(v=>v(T))&&(N.push(T),typeof m=="number"&&N.length>=m))break}return N},oe={fieldRef:J,serialize:ie},kt=(o,i)=>{const t=i===void 0?void 0:o.shape[i];return t!==void 0&&$n(t)},gt=(o,i)=>i.some(t=>kt(o,t)),bt=(o,i,t)=>{if(kt(o,i))throw new g("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`)},Kn=o=>{let i=0;const t=[],d={fieldRef:J,relationExists:f=>{const{childWhere:m,negated:b,parentTable:S,relation:y}=f,w=`__rel_${String(i)}`,N=t.at(-1)??S;i+=1,o(y.table,U);const _=y.kind==="one"?y.field:y.references,T=y.kind==="one"?y.references:y.field,v=r`${st(w,T)} = ${st(N,_)}`;t.push(w);const O=te(m,d);t.pop();const L=O?r`${v} AND ${O}`:v,M=r`EXISTS (SELECT 1 FROM ${r.identifier(y.table)} AS ${r.identifier(w)} WHERE ${L})`;return b?r`NOT ${M}`:M},serialize:ie};return d},Dt=o=>{const i=o.map(t=>r`${J(t.field)} ${r.raw(t.direction==="desc"?"DESC":"ASC")}`);return o.some(t=>t.field==="_id"||t.field==="id")||i.push(r`${J("id")} ASC`),r.join(i,r`, `)},Yn={"<":"lt","<=":"lte","=":"eq",">":"gt",">=":"gte"},zn=o=>{const i=o.order;return o.indexFields.length>0?o.indexFields.map(t=>({direction:i,field:t})):[{direction:i,field:"_creationTime"}]},Jn=(o,i,t,d)=>{const f=o.sqlConditions.map(m=>({[m.field]:{[Yn[m.comparator]??"eq"]:m.value}}));if(t&&f.push(xt(i,He(t))),d&&f.push(sn(i,He(d))),f.length!==0)return f.length===1?f[0]:{AND:f}},Vn=(o,i,t)=>{const d=[];for(const f of o){const m=ce(f);if(m&&i.every(b=>b(m))&&(d.push(m),t!==void 0&&d.length>t))break}return d},Xn=(o,i,t,d,f,m=()=>{})=>{const b=Math.max(0,Math.floor(d.numItems)),S=zn(t),y=typeof d.endCursor=="string",w=te(Jn(t,S,d.cursor,d.endCursor),oe),N=f&&w?r`${w} AND ${f}`:f??w;let _=r`SELECT id, _creationTime, ${r.identifier(H)} FROM ${r.identifier(i)}`;N&&(_=r`${_} WHERE ${N}`),_=r`${_} ORDER BY ${Dt(S)}`;const T=t.inMemoryFilters.length>0;!T&&!y&&(_=r`${_} LIMIT ${r.raw(String(b+1))}`);const v=W(o,_).toArray();m(v.length);const O=Vn(v,t.inMemoryFilters,T||y?void 0:b);if(y){const j=O.length>=2?O[Math.floor(O.length/2)-1]:void 0;return{continueCursor:d.endCursor??null,isDone:!0,page:O,splitCursor:j?Ge(j,S):null}}const L=O.length>b,M=L?O.slice(0,b):O,G=M.at(-1);return{continueCursor:L&&G?Ge(G,S):null,isDone:!L,page:M}};class Zn extends g{constructor(i="unique() found more than one matching document"){super("NOT_UNIQUE",i,{name:"NotUniqueError"})}}const er=/\s/u,tr=String.fromCodePoint(0),Et=(o,i,t)=>{if(!o.tables[i])throw new g("INTERNAL",`unknown table: ${i}`);return typeof t!="string"||t.length===0||er.test(t)||t.includes(tr)?null:t},nr=(o,i,t,d=()=>{},f=()=>{},m=()=>{})=>{const b=i.tables[t];if(!b)throw new g("INTERNAL",`unknown table: ${t}`);const S=le(b.softDeleteMode,void 0),y=S?te(S,oe):void 0,w={indexFields:[],indexName:void 0,inMemoryFilters:[],order:"asc",sqlConditions:[]};let N=0;const _=E=>{const{search:I}=w;if(!I)throw new g("INTERNAL","runSearchFetch called without a staged search");zt(o,t,b);const C=w.inMemoryFilters.length>0,k=Mn(C?void 0:E),z=Vt(o)?Wn(o,t,I,k,y):Bn(o,t,I,k,y);return C?(N=z.length,Ct(z,w.inMemoryFilters,E,ne=>ne.document)):(E===void 0&&Rn(z),z)},T=E=>_(E).map(I=>I.document),v=E=>{const I=vn(E);return Cn(T(An(I)),I)},O=()=>{const E=w.indexFields.length>0?w.indexFields:["_creationTime"],I=w.order==="desc"?"DESC":"ASC";return r.join(E.map(C=>r`${J(C)} ${r.raw(I)}`),r`, `)},L=()=>{if(w.search||w.geo||w.indexName===void 0){f(void 0);return}f(fn(t,w.indexName,w.indexFields,w.sqlConditions,ie))},M=E=>{L();let I=0;const C=(()=>{if(w.search){const k=T(E);return I=N,k}return w.geo?jn(o,t,w,y,E,k=>{I=k}):Qn(o,t,w,y,O(),E,k=>{I=k})})();return m(Math.max(I,C.length)),C},G=()=>{if(!w.search&&!w.geo)throw new g("INTERNAL",`ctx.db.query("${t}").collectWithScores() requires a staged .withSearchIndex(...) or .withGeoIndex(...)`);L();let E=0;const I=(()=>{if(w.search){const C=_(void 0);return E=N,C}return Mt(o,t,w,y,void 0,C=>{E=C})})();return m(Math.max(E,I.length)),I},j={async*[Symbol.asyncIterator](){const E=[...w.inMemoryFilters];let I;w.inMemoryFilters=[];try{for(;;){const C=await j.paginate({cursor:I??null,numItems:Ln});for(const k of C.page)E.every(z=>z(k))&&(yield k);if(C.isDone||C.continueCursor===null)return;I=C.continueCursor}}finally{w.inMemoryFilters=E}},async collect(){return M(void 0)},async collectWithScores(){return G()},filter(E){return w.inMemoryFilters.push(E),j},async first(){return M(w.inMemoryFilters.length>0?void 0:1)[0]??null},order(E){return w.order=E==="desc"?"desc":"asc",j},async paginate(E){let I=0;if(L(),w.search){const k=v(E);return m(k.page.length),k}if(w.geo)throw new g("INTERNAL","pagination is not supported on geo queries; use .take(n) or .collect()");const C=Xn(o,t,w,E,y,k=>{I=k});return m(Math.max(I,C.page.length)),C},async take(E){return M(E)},async unique(){const E=M(w.inMemoryFilters.length>0?void 0:2);if(E.length>1)throw new Zn(`unique() on table "${t}" matched ${String(E.length)} documents; expected at most one`);return E[0]??null},withGeoIndex(E,I){const C=(b.geoIndexes??[]).find(z=>z.name===E);if(!C)throw new g("INTERNAL",`unknown geo index "${E}" on table "${t}"`);d(t,E,"geo");const k={definition:C,indexName:E};if(w.geo=k,I(qn(k,t)),!k.near&&!k.within)throw new g("INTERNAL",`geo index "${E}" on table "${t}" requires a .near(point, radius) or .within(box) call`);return j},withIndex(E,I){const C=b.indexes.find(k=>k.name===E);if(!C)throw new g("INTERNAL",`unknown index "${E}" on table "${t}"`);return d(t,E,"index"),w.indexName=E,w.indexFields=C.fields,I&&I(On(w)),j},withSearchIndex(E,I){const C=(b.searchIndexes??[]).find(z=>z.name===E);if(!C)throw new g("INTERNAL",`unknown search index "${E}" on table "${t}"`);d(t,E,"search");const k={definition:C,field:C.field,filters:[],hasQuery:!1,indexName:E,query:""};if(w.search=k,I(Sn(k,t,Qe(C.language))),!k.hasQuery)throw new g("INTERNAL",`search index "${E}" on table "${t}" requires a .search(field, query) call`);return j}};return j},yt=(o,i,t)=>{const d={...i};for(const[f,m]of St(o)){if(m.serverDefault){d[f]=m.serverDefault({auth:t});continue}d[f]===void 0&&(m.defaultFn?d[f]=m.defaultFn():"defaultValue"in m&&(d[f]=m.defaultValue))}return d},Nt=(o,i,t,d)=>{const f=t;for(const[m,b]of St(o)){if(b.serverDefault){m in i&&(f[m]=b.serverDefault({auth:d}));continue}b.onUpdateFn&&!(m in i)&&(f[m]=b.onUpdateFn())}},_t=(o,i)=>{for(const t of Object.keys(i))if(i[t]===void 0)throw new g("INTERNAL",`Cannot ${o} field '${t}' to undefined — use null to clear a nullable field, or omit the key to leave it unchanged.`)},rr=/unique constraint failed/i,or=o=>o instanceof Error&&rr.test(o.message),je=(o,i,t)=>{try{W(o,t)}catch(d){throw or(d)?new pe(`unique constraint violation on "${i}"`,"unique"):d}},Ie=(o,i,t)=>{if(je(o,i,t),W(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")},Tt=(o,i,t,d,f,m,b)=>{const S=[];for(let _=0;_<t.length+1;_+=1){const T=[];for(let M=0;M<_;M+=1)T.push(r`${r.identifier(t[M])} IS ${m[M]}`);const v=t[_],O=d[_];if(v!==void 0&&O!==void 0){const M=O.direction==="desc"?">":"<";T.push(r`${r.identifier(v)} ${r.raw(M)} ${m[_]}`)}else T.push(r`${r.identifier(cn)} < ${b}`);const[L]=T;S.push(T.length===1&&L!==void 0?L:r`(${r.join(T,r` AND `)})`)}const y=r.join(S,r` OR `),w=W(o,r`SELECT COUNT(*) AS c FROM ${r.identifier(i)} WHERE ${r.identifier("__partition__")} = ${f} AND (${y})`).one(),N=W(o,r`SELECT COUNT(*) AS c FROM ${r.identifier(i)} WHERE ${r.identifier("__partition__")} = ${f}`).one();return{before:w.c,total:N.c}},Dr=o=>{const{sql:i}=o,{schema:t}=o,d=o.broadcast??(()=>{}),f=(e,...n)=>{const a=t.tables[e]?.indexes;if(!a||a.length===0)return;const c=[];for(const h of n)h&&c.push(...un(a,h,ie));return c.length>0?c:void 0},{headroom:m}=o;let b=!1;const S=async e=>{const n=b;b=!0;try{return await e()}finally{b=n}},y=o.onRead??(()=>{}),w=o.onReadRange??(e=>{y(e.table,U)}),N=(e,n)=>{n!==void 0&&n!==U&&!b&&m?.recordRead(1),y(e,n)},_=o.onIndexUse??(()=>{}),T=o.onWrite??(()=>{}),v=e=>{b||m?.recordWrite(e)},O=async e=>{v(e.doc),await T(e)},{cache:L}=o,M=o.clock??(()=>Date.now()),G=o.idGenerator??(()=>crypto.randomUUID()),j=o.scheduler??jt,{globalDb:E}=o,I=o.auth??{identity:null,userId:null},C=o.cdc??!1,k=j,z=wn({scheduler:typeof k.list=="function"&&typeof k.get=="function"?k:void 0,storage:o.storage}),ne=(e,n,a,c)=>{C&&Jt(i,M(),e,n,a,c)},ae=e=>t.tables[e]?.shardMode?.kind==="global",Ye=(e,n)=>{if(ae(e)){if(!E)throw new g("INTERNAL",`cross-backend ${n} for global table '${e}' requires a globalDb writer — pass one to createShardCtxDb({ globalDb })`);return E}return B},ve=e=>Ye(e,"cascade"),K=(e,n)=>{if(ae(e)){if(!E)throw new g("INTERNAL",`${n} on global table '${e}' requires a globalDb writer — pass one to createShardCtxDb({ globalDb })`);return E}},ze=async(e,n,a,c,h)=>{h&&v(a);const u=await e.insert(n,a,c);return d({key:u,op:"insert",row:{...a,_id:u},table:n}),u},Ce=(e,n)=>Ye(e,"relation load").findMany(e,n),Je=(e,n)=>(ae(e)&&N(e,U),Ce(e,n)),Lt=e=>!ae(e.table),Ve=o.relationExistsPushDown??"auto",Xe=Ve!=="never",{maxRelationKeys:Ze}=o,$e=(e,n,a)=>ut(e,{fetcher:Je,maxRelationKeys:Ze,relationBaseWhere:a,schema:t,tableName:n}),et=async(e,n,a,c)=>{const h=K(e,"relation grouped count");if(h)return N(e,U),mn((P,x)=>h.count(P,x),e,n,a,c);const u=t.tables[e];if(!u)throw new g("INTERNAL",`unknown table: ${e}`);N(e,U);const s=le(u.softDeleteMode,void 0),l={[n]:{in:a}},p=Y(Y(l,c),s),R=await $e(p,e,void 0),$=te(R,oe),A=J(n);let D=r`SELECT ${A} AS __fk__, COUNT(*) AS count FROM ${r.identifier(e)}`;$&&(D=r`${D} WHERE ${$}`),D=r`${D} GROUP BY ${A}`;const F=W(i,D).toArray();return new Map(F.map(P=>[P.__fk__,P.count]))};let we=0;const tt=new Set;for(const[e,n]of Object.entries(t.tables))for(const a of Object.values(n.triggerMap??{}))tt.add(`${e} ${a.timing} ${a.op}`);const X=(e,n,a)=>tt.has(`${e} ${n} ${a}`),Z=async(e,n,a)=>{if(we+=1,we>$t)throw we-=1,new pe(`trigger recursion exceeded ${String($t)} levels on "${a.table}" — check for a self-triggering write`,"trigger");try{await gn({ctx:Ft,event:a,op:n,schema:t,tableName:a.table,timing:e})}finally{we-=1}},{ensureBackfilledForTable:ue,ensureBackfilledIndex:Me,ensureRankBackfilled:ke,ensureRankBackfilledForTable:fe,syncAggregates:ge,syncCompanionsForInsert:nt,syncGeo:be,syncRanks:he,syncSearch:Ee}=qt({broadcast:d,indexKeysFor:(e,n)=>f(e,n),invalidateCache:(e,n,a)=>L?.invalidate(e,n,f(e,a)),recordCdc:ne,schema:t,sql:i}),rt=(e,n,a)=>{const{shardMode:c}=n;if(c?.kind==="shardBy"&&!(c.field!==void 0&&(a.partitionBy??[]).includes(c.field)))throw Object.assign(new Error(`rank index "${a.name}" on "${e}" partitions across shards (shard key "${c.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})},ot=e=>Object.entries(t.tables).filter(([,n])=>n.shardMode?.kind!=="global").map(([n])=>n).filter(n=>e===void 0||n===e),re=(e,n)=>{const a=ot(n);for(let c=0;c<a.length;c+=me){const h=a.slice(c,c+me).map(R=>r`SELECT ${r.raw(`'${R.replaceAll("'","''")}'`)} AS __t__, id, _creationTime, ${r.identifier(H)} FROM ${r.identifier(R)} WHERE id = ${e}`),[u]=W(i,r`${Pe(h)} LIMIT 1`).toArray();if(!u)continue;const s=u.__t__,l=ce(u);if(typeof s!="string"||!l)return;const p=u[H];return{docJson:typeof p=="string"?p:se(p??{}),row:l,tableName:s}}},Ot=(e,n)=>{const a=[...new Set(e)],c=new Map;if(a.length===0)return c;const h=ot(n);for(let u=0;u<h.length;u+=me){const s=h.slice(u,u+me),l=Math.floor(me/s.length),p=Zt(r`${r.identifier("id")}`,a,!1,l),R=s.map($=>r`SELECT ${r.raw(`'${$.replaceAll("'","''")}'`)} AS __t__, id FROM ${r.identifier($)} WHERE ${p}`);for(const $ of W(i,Pe(R))){const{id:A,__t__:D}=$;typeof D=="string"&&typeof A=="string"&&c.set(A,D)}}return c},it={assertRankPartitionLocal:rt,ensureRankBackfilled:ke,onRead:N,rowToDocument:ce,schema:t,sql:i},B={system:z,async aggregate(e,n){const a=K(e,"aggregate");if(a)return N(e,U),a.aggregate(e,n);const c=t.tables[e];if(!c)throw new g("INTERNAL",`unknown table: ${e}`);if(Re(n.op),n.op==="count")return B.count(e,{baseWhere:n.baseWhere,relationBaseWhere:n.relationBaseWhere,restrictsCounts:n.restrictsCounts,where:n.where});if(!n.field)throw new g("INTERNAL",`aggregate(${e}, { op: "${n.op}" }): "field" is required for non-count reducers`);N(e,U);const h=le(c.softDeleteMode,void 0),u=Y(Y(n.baseWhere,n.where),h),s=await $e(u,e,n.relationBaseWhere),l=s!==u;if(c.aggregateIndexes&&!n.baseWhere&&!l&&(!h||gt(c,[n.field]))){const F=Yt(c.aggregateIndexes,n.op,n.field,n.where);if(F){Me(e,F.index);const P=De(F.index.by??[],F.key),x=Oe(e,F.index.name),Q=W(i,r`SELECT ${Ae} AS value, ${We} AS count FROM ${r.identifier(x)} WHERE ${xe} = ${P}`).toArray()[0];return Le(n.op,Q)}}bt(c,n.field,`aggregate(${e}, { op: "${n.op}", field: "${n.field}" })`);const p=te(s,oe),R=Re(n.op),$=J(n.field);let A=r`SELECT ${r.raw(R)}(${$}) AS value FROM ${r.identifier(e)}`;return p&&(A=r`${A} WHERE ${p}`),W(i,A).toArray()[0]?.value??null},asId(e,n){const a=Et(t,e,n);if(a===null)throw new g("BAD_REQUEST",`asId("${e}", …): "${n}" is not a valid id for table "${e}"`,{status:400});return a},async count(e,n){const a=K(e,"count");if(a)return N(e,U),a.count(e,n);const c=t.tables[e];if(!c)throw new g("INTERNAL",`unknown table: ${e}`);const h=Gt(n);if(h.restrictsCounts)throw new Fe(e);N(e,U);const u=le(c.softDeleteMode,void 0),s=Y(Y(h.baseWhere,h.where),u),l=await $e(s,e,h.relationBaseWhere),p=l!==s;if(c.aggregateIndexes&&!h.baseWhere&&!p&&!u){const A=Kt(c.aggregateIndexes,h.where);if(A){Me(e,A.index);const D=De(A.index.by??[],A.key),F=Oe(e,A.index.name),P=W(i,r`SELECT ${Ae} AS value FROM ${r.identifier(F)} WHERE ${xe} = ${D}`).toArray();return P[0]===void 0?0:P[0].value??0}}const R=te(l,oe);let $=r`SELECT COUNT(*) AS count FROM ${r.identifier(e)}`;return R&&($=r`${$} WHERE ${R}`),W(i,$).one().count},async delete(e,n,a){const c=re(e,n);if(!c){const $=n===void 0?E:void 0;$&&(v(void 0),await $.delete(e,void 0,a));return}const{docJson:h,row:u,tableName:s}=c,l=t.tables[s],p=a?.hard===!0,R=!p&&l?.softDeleteMode?l.softDeleteMode.field:void 0;if(!(R&&u[R]!==null&&u[R]!==void 0)){if(X(s,"before","delete")&&await Z("before","delete",{id:e,op:"delete",previous:u,table:s}),await hn({deletedId:e,deletedReference:$=>u[$],findHolders:async($,A,D)=>(await ve($).findMany($,{includeDeleted:p,where:{[A]:D}})).page,onCascade:($,A)=>ve($).delete(A,void 0,a),onRestrict:$=>{throw new pe($,"restrict")},onSetNull:($,A,D)=>ve($).patch(A,{[D]:null}),schema:t,tableName:s}),ue(s),fe(s),R){const $={...u,[R]:M(),_id:e};Ie(i,s,r`UPDATE ${r.identifier(s)} SET ${r.identifier(H)} = ${se($)} WHERE id = ${e} AND ${r.identifier(H)} = ${h}`),Ee(s,e,$,u),be(s,e,void 0),ge(s,u,$),he(s,e,u,void 0),L?.invalidate(s,e,f(s,u,$)),ne(s,e,"update",$),d({indexKeys:f(s,u,$),key:e,op:"update",row:$,table:s}),X(s,"after","delete")&&await Z("after","delete",{id:e,op:"delete",previous:u,table:s}),await O({id:e,op:"delete",table:s});return}Ie(i,s,r`DELETE FROM ${r.identifier(s)} WHERE id = ${e} AND ${r.identifier(H)} = ${h}`),Ee(s,e,void 0),be(s,e,void 0),ge(s,u,void 0),he(s,e,u,void 0),L?.invalidate(s,e,f(s,u)),ne(s,e,"delete"),d({indexKeys:f(s,u),key:e,op:"delete",table:s}),X(s,"after","delete")&&await Z("after","delete",{id:e,op:"delete",previous:u,table:s}),await O({id:e,op:"delete",table:s})}},async deleteAll(e,n){if(!t.tables[e])throw new g("INTERNAL",`unknown table: ${e}`);const a=Math.max(1,n?.chunkSize??It),c=n?.hard===void 0?void 0:{hard:n.hard},h=ae(e)?void 0:e;let u=0;return await S(async()=>{for(;;){const s=(await B.findMany(e,{limit:a})).page.map(l=>String(l._id));if(s.length===0)break;for(const l of s)await B.delete(l,h,c),u+=1;if(s.length<a)break}}),{deleted:u}},async deleteMany(e,n,a){de(e.length,n?.limit,"deleteMany");for(const c of e)await B.delete(c,a);return{deleted:e.length}},async deleteWhere(e,n,a){const c=(await(K(e,"deleteWhere")??B).findMany(e,{where:n})).page.map(h=>String(h._id));if(de(c.length,a?.limit,"deleteWhere"),B.deleteMany===void 0)throw new g("INTERNAL",`ctx.db.${e}.deleteMany is unavailable: this writer has no batch delete`);return B.deleteMany(c,a)},async findFirst(e,n={}){return(await B.findMany(e,{...n,limit:1})).page[0]??null},async findFirstOrThrow(e,n={}){const a=await B.findFirst(e,n);if(a===null)throw new on(`findFirstOrThrow: no "${e}" document matched`);return a},async findMany(e,n={}){const a=K(e,"findMany");if(a)return N(e,U),a.findMany(e,n);const c=t.tables[e];if(!c)throw new g("INTERNAL",`unknown table: ${e}`);const h=!n.where&&!n.baseWhere;h?N(e,U):N(e);const u=an(n.orderBy),s=n.cursor?xt(u,He(n.cursor)):void 0;let l=Y(n.baseWhere,n.where);l=Y(l,le(c.softDeleteMode,n.includeDeleted)),l=await ut(l,{canPushExists:Xe?Lt:void 0,existsPushMode:Ve==="always"?"always":"auto",fetcher:Je,maxRelationKeys:Ze,relationBaseWhere:n.relationBaseWhere,schema:t,tableName:e}),s&&(l=l?{AND:[l,s]}:s);const p=Xe?Kn(N):oe,R=te(l,p);let $=r`SELECT id, _creationTime, ${r.identifier(H)} FROM ${r.identifier(e)}`;R&&($=r`${$} WHERE ${R}`),$=r`${$} ORDER BY ${Dt(u)}`;const A=typeof n.limit=="number"?Math.max(0,Math.floor(n.limit)):void 0;A!==void 0&&($=r`${$} LIMIT ${r.raw(String(A+1))}`);const D=W(i,$).toArray();h&&!b&&m?.recordRead(D.length);const F=[];for(const ee of D){const q=ce(ee);q&&(F.push(q),!h&&typeof q._id=="string"&&N(e,q._id))}if(A===void 0)return n.with&&await ft({groupedCounter:et,fetcher:Ce,parents:F,...ht(n),schema:t,tableName:e,with:n.with}),{continueCursor:null,isDone:!0,page:dt(F,n.select,n.with)};const P=F.length>A,x=P?F.slice(0,A):F,Q=x.at(-1);return n.with&&await ft({fetcher:Ce,groupedCounter:et,parents:x,...ht(n),schema:t,tableName:e,with:n.with}),{continueCursor:P&&Q?Ge(Q,u):null,isDone:!P,page:dt(x,n.select,n.with)}},async get(e,n){const a=re(e,n);if(!a){const c=n===void 0?E:void 0;return c?c.get(e):null}return N(a.tableName,e),a.row},async lookupById(e,n){const a=re(e,n);return a?(N(a.tableName,e),{row:a.row,tableName:a.tableName}):null},async groupBy(e,n){const a=K(e,"groupBy");if(a)return N(e,U),a.groupBy(e,n);const c=t.tables[e];if(!c)throw new g("INTERNAL",`unknown table: ${e}`);N(e,U);const h=n.agg??{op:"count"};if(Re(h.op),h.op!=="count"&&!h.field)throw new g("INTERNAL",`groupBy(${e}, { agg: { op: "${h.op}" } }): "field" is required for non-count reducers`);const u=le(c.softDeleteMode,void 0),s=Y(Y(n.baseWhere,n.where),u),l=await $e(s,e,n.relationBaseWhere),p=l!==s,R=[...n.by,h.field];if(c.aggregateIndexes&&!n.baseWhere&&!p&&(!u||gt(c,R))){const x=Qt(c.aggregateIndexes,h.op,h.field,n.by,n.where),Q=x===void 0?0:Object.keys(x.partial).length,ee=x?.index.by?.length??0;if(x&&(Q===0||Q===ee)){Me(e,x.index);const q=Oe(e,x.index.name),ye=Object.keys(x.partial),Ne=[];if(ye.length===(x.index.by??[]).length&&ye.length>0){const _e=De(x.index.by??[],x.partial),Te=W(i,r`SELECT ${Ae} AS value, ${We} AS count FROM ${r.identifier(q)} WHERE ${xe} = ${_e}`).toArray();return Te.length>0&&Ne.push({key:{...x.partial},value:Le(h.op,Te[0])}),Ne}const Wt=W(i,r`SELECT ${xe} AS key, ${Ae} AS value, ${We} AS count FROM ${r.identifier(q)}`).toArray();for(const _e of Wt){const Te=Ht(JSON.parse(_e.key));Ne.push({key:Te,value:Le(h.op,_e)})}return Ne}}for(const x of R){if(x===void 0)continue;const Q=x===h.field?`groupBy(${e}, { agg: { op: "${h.op}", field: "${x}" } })`:`groupBy(${e}, { by: [..."${x}"] })`;bt(c,x,Q)}const $=te(l,oe),A=n.by.map(x=>r`${J(x)} AS ${r.identifier(x)}`);if(h.op==="count")A.push(r`COUNT(*) AS value`);else{const{field:x}=h;if(x===void 0)throw new g("INTERNAL",`groupBy(${e}, { agg: { op: "${h.op}" } }): "field" is required for non-count reducers`);A.push(r`${r.raw(Re(h.op))}(${J(x)}) AS value`)}let D=r`SELECT ${r.join(A,r`, `)} FROM ${r.identifier(e)}`;$&&(D=r`${D} WHERE ${$}`),D=r`${D} GROUP BY ${r.join(n.by.map(x=>J(x)),r`, `)}`;const F=W(i,D).toArray(),P=[];for(const x of F){const Q={};for(const q of n.by)Q[q]=x[q]??null;const{value:ee}=x;P.push({key:Q,value:ee==null?null:Number(ee)})}return P},async insert(e,n,a){const c=K(e,"insert");if(c)return ze(c,e,n,a,!0);const h=t.tables[e];if(!h)throw new g("INTERNAL",`unknown table: ${e}`);const u=yt(h,n,I);qe(h,u);let s;a?.clientId!==void 0?(Dn(a.clientId),s=a.clientId):a?.allowExplicitId&&typeof u._id=="string"?s=u._id:s=G();const l=a?.allowExplicitId&&typeof u._creationTime=="number"?u._creationTime:M(),p={...u,_creationTime:l,_id:s};return X(e,"before","insert")&&await Z("before","insert",{doc:{...p},id:s,op:"insert",table:e}),ue(e),fe(e),je(i,e,r`INSERT INTO ${r.identifier(e)} (id, _creationTime, ${r.identifier(H)}) VALUES (${s}, ${l}, ${se(p)})`),nt(e,s,p),X(e,"after","insert")&&await Z("after","insert",{doc:p,id:s,op:"insert",table:e}),await O({doc:p,id:s,op:"insert",table:e}),s},async insertManyUnsafe(e,n,a){if(de(n.length,a?.limit,"insertManyUnsafe"),n.length===0)return[];const c=K(e,"insert");if(c){const s=[];for(const l of n)v(l);for(const l of n){const p=await c.insert(e,l,{allowExplicitId:a?.allowExplicitId});d({key:p,op:"insert",row:{...l,_id:p},table:e}),s.push(p)}return s}const h=t.tables[e];if(!h)throw new g("INTERNAL",`unknown table: ${e}`);ue(e),fe(e);const u=n.map(s=>{const l=yt(h,s,I),p=a?.allowExplicitId===!0&&typeof l._id=="string"?l._id:G(),R=a?.allowExplicitId===!0&&typeof l._creationTime=="number"?l._creationTime:M();return{creationTime:R,document:{...l,_creationTime:R,_id:p},id:p}});for(const s of u)v(s.document);for(let s=0;s<u.length;s+=wt){const l=r.join(u.slice(s,s+wt).map(p=>r`(${p.id}, ${p.creationTime}, ${se(p.document)})`),r`, `);je(i,e,r`INSERT INTO ${r.identifier(e)} (id, _creationTime, ${r.identifier(H)}) VALUES ${l}`)}for(const{document:s,id:l}of u)nt(e,l,s),await T({doc:s,id:l,op:"insert",table:e});return u.map(s=>s.id)},async insertMany(e,n,a){de(n.length,a?.limit,"insertMany");const c=a?.skipDuplicates===!0,h=[],u=K(e,"insert");if(u)for(const l of n)v(l);const s=async l=>u?ze(u,e,l,void 0,!1):B.insert(e,l);for(const l of n)try{h.push(await s(l))}catch(p){if(c&&p instanceof pe&&p.kind==="unique")h.push(null);else throw p}return h},normalizeId(e,n){return Et(t,e,n)},async patch(e,n,a){const c=re(e,a);if(!c){const R=a===void 0?E:void 0;if(R){v(n),await R.patch(e,n);return}throw new g("INTERNAL",`document not found: ${e}`)}const{docJson:h,row:u,tableName:s}=c,l=t.tables[s];if(!l)throw new g("INTERNAL",`unknown table: ${s}`);N(s,e),_t("patch",n);const p={...u,...n,_id:e};Nt(l,n,p,I),qe(l,p,!0),X(s,"before","update")&&await Z("before","update",{doc:{...p},id:e,op:"update",previous:u,table:s}),ue(s),fe(s),Ie(i,s,r`UPDATE ${r.identifier(s)} SET ${r.identifier(H)} = ${se(p)} WHERE id = ${e} AND ${r.identifier(H)} = ${h}`),Ee(s,e,p,u),be(s,e,p),ge(s,u,p),he(s,e,u,p),L?.invalidate(s,e,f(s,u,p)),ne(s,e,"update",p),d({indexKeys:f(s,u,p),key:e,op:"update",row:p,table:s}),X(s,"after","update")&&await Z("after","update",{doc:p,id:e,op:"update",previous:u,table:s}),await O({doc:p,id:e,op:"update",table:s})},async patchMany(e,n,a){de(e.length,n?.limit,"patchMany");for(const c of e)await B.patch(c.id,c.patch,a);return{patched:e.length}},async patchWhere(e,n,a){const c=(await(K(e,"patchWhere")??B).findMany(e,{where:n.where})).page.map(h=>({id:String(h._id),patch:n.patch}));if(de(c.length,a?.limit,"patchWhere"),B.patchMany===void 0)throw new g("INTERNAL",`ctx.db.${e}.patchMany is unavailable: this writer has no batch patch`);return await B.patchMany(c,a),{patched:c.length}},query(e){const n=K(e,"query");return n?(N(e,U),n.query(e)):nr(i,t,e,_,a=>{a?w(a):N(e,U)},a=>{b||m?.recordRead(a)})},async rank(e,n,a){const c=K(e,"rank");if(c)return N(e,U),c.rank(e,n,a);_(e,n,"rank");const h=t.tables[e];if(!h)throw new g("INTERNAL",`unknown table: ${e}`);const u=h.rankIndexes?.find(q=>q.name===n);if(!u)throw new g("INTERNAL",`unknown rankIndex "${n}" on table "${e}"`);if(rt(e,h,u),a.restrictsCounts)throw new Fe(e);N(e,U),ke(e,u);const s=typeof a.row=="string"?a.row:a.row._id;if(!s)return null;const l=ct(e,u.name),p=u.sortBy.map((q,ye)=>lt(ye)),R=p.map(q=>bn(q)).join(", "),$=W(i,r`SELECT ${r.identifier("__partition__")}, ${r.raw(R)} FROM ${r.identifier(l)} WHERE ${r.identifier("__id__")} = ${s}`).toArray(),[A]=$;if(A===void 0)return null;let D=A.__partition__;const F=Y(a.baseWhere,a.where);Be(F,t,e,"rank");const P=dn(u,F);if(P){const q=ln(u.partitionBy??[],P);if(q!==D)return null;D=q}const x=p.map(q=>A[q]),{before:Q,total:ee}=Tt(i,l,p,u.sortBy,D,x,s);return{position:Q+1,total:ee}},async rankBefore(e,n,a){if(ae(e))throw new g("INTERNAL",`rankBefore is not supported on the global (.global()) table '${e}' — cross-shard rank cursors apply only to sharded tables`);const c=t.tables[e];if(!c)throw new g("INTERNAL",`unknown table: ${e}`);const h=c.rankIndexes?.find(p=>p.name===n);if(!h)throw new g("INTERNAL",`unknown rankIndex "${n}" on table "${e}"`);if(a.restrictsCounts)throw new Fe(e);N(e,U),ke(e,h);const u=ct(e,h.name),s=h.sortBy.map((p,R)=>lt(R)),l=h.sortBy.map((p,R)=>ie(a.sortValues[R]??null));return Tt(i,u,s,h.sortBy,a.partitionKey,l,a.rowId)},async rankPage(e,n,a={}){Be(Y(a.baseWhere,a.where),t,e,"rankPage");const c=K(e,"rankPage");if(c)return N(e,U),c.rankPage(e,n,a);_(e,n,"rank");const{continueCursor:h,hasMore:u,rows:s}=at(it,e,n,a);return{continueCursor:h,isDone:!u,page:s.map(l=>l.doc)}},async rankPageRows(e,n,a={}){Be(Y(a.baseWhere,a.where),t,e,"rankPage"),_(e,n,"rank");const{directions:c,hasMore:h,rows:u}=at(it,e,n,a);return{directions:c,hasMore:h,rows:u}},async restore(e,n){const a=re(e,n);if(!a){const u=n===void 0?E:void 0;if(u?.restore){await u.restore(e);return}throw new g("INTERNAL",`document not found: ${e}`)}const c=t.tables[a.tableName]?.softDeleteMode?.field;if(!c)throw new g("INTERNAL",`ctx.db.restore: table "${a.tableName}" is not a .softDelete() table`);const h=a.row[c]!==null&&a.row[c]!==void 0;await B.patch(e,{[c]:null},n),h&&he(a.tableName,e,void 0,a.row)},async replace(e,n,a,c){const h=re(e,a);if(!h){const A=a===void 0?E:void 0;if(A){v(n),await A.replace(e,n,void 0,c);return}throw new g("INTERNAL",`document not found: ${e}`)}const{docJson:u,row:s,tableName:l}=h,p=t.tables[l];if(!p)throw new g("INTERNAL",`unknown table: ${l}`);_t("replace",n);const R=c?.allowExplicitId&&typeof n._creationTime=="number"?n._creationTime:M(),$={...n,_creationTime:R,_id:e};Nt(p,n,$,I),qe(p,$),X(l,"before","update")&&await Z("before","update",{doc:{...$},id:e,op:"update",previous:s,table:l}),ue(l),fe(l),Ie(i,l,r`UPDATE ${r.identifier(l)} SET _creationTime = ${R}, ${r.identifier(H)} = ${se($)} WHERE id = ${e} AND ${r.identifier(H)} = ${u}`),Ee(l,e,$,s),be(l,e,$),ge(l,s,$),he(l,e,s,$),L?.invalidate(l,e,f(l,s,$)),ne(l,e,"update",$),d({indexKeys:f(l,s,$),key:e,op:"update",row:$,table:l}),X(l,"after","update")&&await Z("after","update",{doc:$,id:e,op:"update",previous:s,table:l}),await O({doc:$,id:e,op:"update",table:l})},async wipeShard(e){const n=new Set(e?.exclude),a=e?.tables,c=Object.entries(t.tables).filter(([l,p])=>n.has(l)||a!==void 0&&!a.includes(l)?!1:p.shardMode?.kind!=="global").map(([l])=>l);if(a!==void 0){for(const l of a)if(!t.tables[l])throw new g("INTERNAL",`wipeShard: unknown table: ${l}`)}const h={};let u=0;const{deleteAll:s}=B;if(s===void 0)throw new g("INTERNAL","wipeShard: this writer has no deleteAll");for(const l of c){const p=await s(l,{...e?.chunkSize===void 0?{}:{chunkSize:e.chunkSize},hard:!0});h[l]=p.deleted,u+=p.deleted}return{deleted:u,tables:h}}},Ft={db:B,scheduler:j};return o.enforceRls===!0?pn(B,t,(e,n)=>re(e,n)?.tableName,(e,n)=>Ot(e,n)):B};export{Ur as CDC_LOG_TABLE,Jr as CLIENT_WATERMARK_TABLE,to as GLOBAL_SHAPE_SNAPSHOT_TABLE,lo as IDEMPOTENCY_TABLE,Zn as NotUniqueError,$o as SEARCH_STATE_TABLE,Vr as advanceClientWatermark,Pr as applyCdcChanges,Dn as assertValidClientId,Fr as backfillAggregateIndexes,Wr as backfillRankIndexes,Br as backfillSearchIndexes,Hr as bumpCdcEpoch,Dr as createShardCtxDb,no as deleteGlobalShapeSnapshot,ro as deleteGlobalShapeSnapshotsForConnection,Xr as migrateClientWatermark,oo as migrateGlobalShapeSnapshot,Gr as minCdcSeq,Et as normalizeIdStructurally,jr as readCdcChanges,Qr as readCdcCursor,Kr as readCdcEpoch,Zr as readClientWatermark,io as readGlobalShapeSnapshot,co as readIdempotent,mo as runShardMigrations,go as selectShapeMemberIds,bo as selectShapeRows,Yr as trimCdcChanges,uo as trimIdempotent,ao as writeGlobalShapeSnapshot,fo as writeIdempotent};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{matchesStaticWhere as l}from"./AGGREGATE_SQL_FUNCTION-CTo0-9iZ.mjs";import{compareStrings as c}from"./aggregateTableName-
|
|
1
|
+
import{matchesStaticWhere as l}from"./AGGREGATE_SQL_FUNCTION-CTo0-9iZ.mjs";import{compareStrings as c}from"./aggregateTableName-DN7gk6uh.mjs";import{serializeSqlValue as f}from"./serializeSqlValue-BR4UOWoP.mjs";const n=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:n}return r},u=(r,t)=>{if(r.length===0)return"";const o={};for(const s of r.toSorted(c))o[s]=t[s]??null;return JSON.stringify(o)},h="__id__",k=r=>`__sort_k${String(r)}__`,S=(r,t)=>{const o=r.partitionBy??[],s=t??{};for(const e of Object.keys(s))if(e==="AND"||e==="OR"||e==="NOT")return;const i={};for(const e of o)if(e in s){const a=m(s[e]);if(a===n)return;i[e]=a}else if(r.where&&e in r.where)i[e]=r.where[e];else return;return i},d=(r,t)=>`${r}__rank_${t}`,b=(r,t)=>({partitionKey:u(r.partitionBy??[],t),rowId:t._id,sortValues:r.sortBy.map(o=>f(t[o.field]??null))}),g=l;export{h as RANK_TIEBREAK,u as encodePartitionKey,g as matchesRankStaticWhere,b as rankKeyFromDoc,d as rankTableName,S as resolveRankPartition,k as sortColumnName};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{stableWireKey as p}from"./stableWireKey-
|
|
1
|
+
import{stableWireKey as p}from"./stableWireKey-Diuu1gGc.mjs";import{depKey as l,SCAN_DEP as f}from"./SCAN_DEP-D_yR9EeV.mjs";import{o as m}from"./estimate-bytes-Drp8rhPs.mjs";import{keysTouchRanges as u}from"./buildIndexRange-DFsdtPjD.mjs";import{stableStringify as A}from"./stableStringify-BjLh4gvA.mjs";const c=(o,t,e)=>{let s=o.get(t);return s===void 0&&(s=e(),o.set(t,s)),s},x=1e3,g=4*1024*1024;class z{entries=new Map;tableIndex=new Map;rangeIndex=new Map;totalBytes=0;hits=0;misses=0;evictions=0;maxEntries;maxBytes;now;monotonic=0;constructor(t={}){this.maxEntries=t.maxEntries??x,this.maxBytes=t.maxBytes??g,this.now=t.now??(()=>(this.monotonic+=1,this.monotonic))}async run(t,e,s,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 r=await s(),h=m(r);if(h===void 0)return r;const d=i(),b={bytes:h,deps:e,ranges:d,lastUsed:this.now(),result:r,subscribers:new Set};this.entries.set(t,b),this.totalBytes+=h;for(const a of e)c(this.tableIndex,a,()=>new Set).add(t);for(const a of d){const y=c(this.rangeIndex,a.table,()=>new Map);c(y,a,()=>new Set).add(t)}return this.evict(),r}invalidate(t,e,s){const i=[];return this.collectAndDrop(l(t,e),i),this.collectAndDrop(l(t,f),i),this.dropRangeDeps(t,s,i),i}invalidateTable(t){const e=[],s=`${t}:`;for(const i of this.tableIndex.keys())i.startsWith(s)&&this.collectAndDrop(i,e);return this.dropRangeDeps(t,void 0,e),e}subscribe(t,e){const s=this.entries.get(t);s&&s.subscribers.add(e)}unsubscribe(t,e){const s=this.entries.get(t);s&&s.subscribers.delete(e)}size(){return{bytes:this.totalBytes,entries:this.entries.size}}clear(){this.entries.clear(),this.tableIndex.clear(),this.rangeIndex.clear(),this.totalBytes=0}subscribers(t){const e=this.entries.get(t);return e?[...e.subscribers]:[]}stats(){return{bytes:this.totalBytes,entries:this.entries.size,evictions:this.evictions,hits:this.hits,misses:this.misses}}dropRangeDeps(t,e,s){const i=this.rangeIndex.get(t);if(!(!i||i.size===0))for(const[n,r]of i)u([n],e)&&this.dropKeys(r,s)}collectAndDrop(t,e){const s=this.tableIndex.get(t);s&&this.dropKeys(s,e)}dropKeys(t,e){for(const s of t){const i=this.entries.get(s);i&&(this.dropEntry(s,i),e.push(s))}}dropEntry(t,e){this.entries.delete(t),this.totalBytes-=e.bytes;for(const s of e.deps){const i=this.tableIndex.get(s);i&&(i.delete(t),i.size===0&&this.tableIndex.delete(s))}for(const s of e.ranges){const i=this.rangeIndex.get(s.table),n=i?.get(s);n?.delete(t),i&&n?.size===0&&(i.delete(s),i.size===0&&this.rangeIndex.delete(s.table))}}evict(){if(!(this.entries.size<=this.maxEntries&&this.totalBytes<=this.maxBytes))for(const[t,e]of this.entries){if(this.entries.size<=this.maxEntries&&this.totalBytes<=this.maxBytes)return;e.subscribers.size>0||(this.dropEntry(t,e),this.evictions+=1)}}}const E=(o,t,e)=>`${e??"\0anon"}\0${o}:${p(t)}`;export{z as ReactiveCache,E as reactiveCacheKey,A as stableStringify,p as stableWireKey};
|
package/dist/packem_shared/{aggregateTableName-DgYMC5tr.mjs → aggregateTableName-DN7gk6uh.mjs}
RENAMED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{LunoraError as l}from"@lunora/errors";import{a as g}from"./wire-codec-
|
|
1
|
+
import{LunoraError as l}from"@lunora/errors";import{a as g}from"./wire-codec-Dh0j-GnY.mjs";const n=BigInt(Number.MAX_SAFE_INTEGER),i=(e,t)=>e<t?-1:e>t?1:0,s=(e,t)=>`${e}__agg_${t}`,c=e=>{if(typeof e=="bigint"){if(e>n||e<-n)throw new l("BAD_REQUEST",`bigint ${e.toString()} exceeds Number.MAX_SAFE_INTEGER, so an aggregateIndex declared over this column cannot tally it exactly (the companion's value column is a REAL) — drop the aggregateIndex, aggregate a narrower column, or read the rows and reduce them in the handler`);return Number(e)}if(typeof e=="number")return Number.isFinite(e)?e:void 0},d=(e,t,o,u)=>{const r=e.get(t)??{count:0,value:null};if(o.op==="count"){r.count+=1,r.value=r.count,e.set(t,r);return}const a=c(u[o.field??""]);if(o.op==="sum"||o.op==="avg"){a!==void 0&&(r.value=(r.value??0)+a,r.count+=1),e.set(t,r);return}r.count+=1,a!==void 0&&(r.value===null?r.value=a:r.value=o.op==="min"?Math.min(r.value,a):Math.max(r.value,a)),e.set(t,r)},f=(e,t)=>e==="count"?t?.value??0:!t||t.count===0?null:e==="avg"?t.value===null?null:t.value/t.count:t.value,p=(e,t)=>{if(e.length===0)return"";const o={};for(const u of e.toSorted(i))o[u]=t[u]??null;return JSON.stringify(g(o))};export{s as aggregateTableName,c as coerceAggregateNumber,i as compareStrings,p as encodeAggregateKey,d as foldAggregateTally,f as readAggregateValue};
|
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
import{sql as e}from"drizzle-orm";import{runDrizzle as E}from"./runDrizzle-C3n5gJsk.mjs";const n="__stream_runs",T="__stream_chunks",L=r=>{E(r,e`CREATE TABLE IF NOT EXISTS ${e.identifier(n)} (
|
|
2
|
+
run_key TEXT PRIMARY KEY,
|
|
3
|
+
status TEXT NOT NULL,
|
|
4
|
+
last_seq INTEGER NOT NULL DEFAULT 0,
|
|
5
|
+
error_code TEXT,
|
|
6
|
+
error TEXT,
|
|
7
|
+
started_at REAL NOT NULL,
|
|
8
|
+
ttl_ms REAL NOT NULL
|
|
9
|
+
)`),E(r,e`CREATE TABLE IF NOT EXISTS ${e.identifier(T)} (
|
|
10
|
+
run_key TEXT NOT NULL,
|
|
11
|
+
seq INTEGER NOT NULL,
|
|
12
|
+
data_json TEXT NOT NULL,
|
|
13
|
+
PRIMARY KEY (run_key, seq)
|
|
14
|
+
)`)},d=(r,t)=>{const s=E(r,e`SELECT status, last_seq, error_code, error, started_at FROM ${e.identifier(n)} WHERE run_key = ${t} LIMIT 1`).toArray()[0];if(s!==void 0)return{...s.error===null?{}:{error:s.error},...s.error_code===null?{}:{errorCode:s.error_code},lastSeq:s.last_seq,startedAt:s.started_at,status:s.status}},$=(r,t,s,a)=>d(r,t)!==void 0?!1:(E(r,e`INSERT INTO ${e.identifier(n)} (run_key, status, last_seq, started_at, ttl_ms)
|
|
15
|
+
VALUES (${t}, ${"running"}, 0, ${s}, ${a})`),!0),N=(r,t)=>{E(r,e`DELETE FROM ${e.identifier(T)} WHERE run_key = ${t}`),E(r,e`DELETE FROM ${e.identifier(n)} WHERE run_key = ${t}`)},S=(r,t,s,a)=>{E(r,e`INSERT OR IGNORE INTO ${e.identifier(T)} (run_key, seq, data_json) VALUES (${t}, ${s}, ${a})`)},l=(r,t,s)=>E(r,e`SELECT seq, data_json FROM ${e.identifier(T)} WHERE run_key = ${t} AND seq > ${s} ORDER BY seq ASC`).toArray().map(a=>({dataJson:a.data_json,seq:a.seq})),m=(r,t,s,a,i)=>{const _=i?.code??null,R=i?.message??null;E(r,e`UPDATE ${e.identifier(n)}
|
|
16
|
+
SET status = ${s}, last_seq = ${a}, error_code = ${_}, error = ${R}
|
|
17
|
+
WHERE run_key = ${t}`)},A=(r,t)=>{E(r,e`DELETE FROM ${e.identifier(T)} WHERE run_key IN (
|
|
18
|
+
SELECT run_key FROM ${e.identifier(n)} WHERE started_at + ttl_ms < ${t}
|
|
19
|
+
)`),E(r,e`DELETE FROM ${e.identifier(n)} WHERE started_at + ttl_ms < ${t}`)};export{T as STREAM_CHUNKS_TABLE,n as STREAM_RUNS_TABLE,S as appendStreamChunk,$ as claimStreamRun,N as deleteStreamRun,m as finishStreamRun,L as migrateDurableStreams,l as readStreamChunks,d as readStreamRun,A as trimStreamRuns};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{LunoraError as B}from"@lunora/errors";import{applySelect as A}from"./applySelect-
|
|
1
|
+
import{LunoraError as B}from"@lunora/errors";import{applySelect as A}from"./applySelect-5w13bMAR.mjs";const C=s=>({relationBaseWhere:s.relationBaseWhere,relationMask:s.relationMask}),$=(s,o)=>o.select?A(s,o.select,o.with):s,E=async(s,o,t,a,r)=>{const u=await Promise.all(a.map(async i=>{const p=r?{AND:[{[t]:i},r]}:{[t]:i};return[i,await s(o,p)]}));return new Map(u)},R=(s,o)=>{const t=new Set;for(const a of s){const r=a[o];r!=null&&t.add(r)}return[...t]},S=async s=>{const{groupedCounter:o,fetcher:t,parents:a,relationBaseWhere:r,relationMask:u,schema:i,tableName:p,with:O}=s,M=(l,e)=>u?.(l,e)??e;if(a.length===0)return;const g=i.tables[p];if(!g)throw new B("INTERNAL",`unknown table: ${p}`);const N=g.relationMap??{},W=l=>{const e=N[l];if(!e)throw new B("INTERNAL",`unknown relation "${l}" on table "${p}"`);return e},k=async(l,e,n)=>{const d=R(a,e.field);if(d.length===0){for(const c of a)c[l]=null;return}const{page:b}=await t(e.table,{baseWhere:r?.(e.table),relationBaseWhere:r,relationMask:u,where:{[e.references]:{in:d}},with:n.with}),y=new Map;for(const c of M(e.table,b))y.set(c[e.references],c);for(const c of a){const w=y.get(c[e.field]);c[l]=w?$([w],n)[0]??null:null}},j=async(l,e,n)=>{const d=R(a,e.references);if(d.length===0){for(const f of a)f[l]=[];return}const b={[e.field]:{in:d}},y=n.where?{AND:[n.where,b]}:b,{page:c}=await t(e.table,{baseWhere:r?.(e.table),orderBy:n.orderBy,relationBaseWhere:r,relationMask:u,where:y,with:n.with}),w=new Map;for(const f of M(e.table,c)){const h=f[e.field],D=w.get(h);D?D.push(f):w.set(h,[f])}const m=typeof n.limit=="number"?Math.max(0,Math.floor(n.limit)):void 0;for(const f of a){const h=w.get(f[e.references])??[];f[l]=$(m===void 0?h:h.slice(0,m),n)}},v=async l=>{for(const e of Object.keys(l)){const n=W(e),[d,b]=n.kind==="many"?[n.field,n.references]:[n.references,n.field],y=r?.(n.table),c=R(a,b),w=c.length===0?new Map:await o(n.table,d,c,y);for(const m of a){const f=m._count??{},h=m[b];f[e]=h==null?0:w.get(h)??0,m._count=f}}};for(const[l,e]of Object.entries(O)){if(e===void 0||e===!1)continue;if(l==="_count"){await v(e);continue}const n=W(l),d=e===!0?{}:e;await(n.kind==="one"?k(l,n,d):j(l,n,d))}},I=async(s,o,t)=>{const{deletedId:a,deletedReference:r,findHolders:u,onCascade:i,onRestrict:p,onSetNull:O,tableName:M}=s,g=t.references==="_id"?a:r(t.references);if(g==null)return;const N=await u(o,t.field,g);if(N.length!==0){t.onDelete==="restrict"&&p(`cannot delete "${M}" row: "${o}.${t.field}" still references it`);for(const W of N){const k=W._id;typeof k=="string"&&await(t.onDelete==="cascade"?i(o,k):O(o,k,t.field))}}},T=async s=>{const{schema:o,tableName:t}=s;if(!o.tables[t])throw new B("INTERNAL",`unknown table: ${t}`);for(const[a,r]of Object.entries(o.tables)){const u=r.relationMap;if(u)for(const i of Object.values(u))i.kind!=="one"||i.table!==t||!i.onDelete||await I(s,a,i)}},V=(s,o,t=!1)=>{for(const[a,r]of Object.entries(s.shape))a in o&&typeof r.parse=="function"&&(t&&o[a]===null&&r.kind==="optional"||r.parse(o[a]))};export{T as applyOnDelete,R as distinctValues,E as fanOutScalarCounts,C as relationHooks,S as resolveWith,V as runRowValidators};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{LunoraError as h}from"@lunora/errors";import{s as m,a as S}from"./wire-codec-
|
|
1
|
+
import{LunoraError as h}from"@lunora/errors";import{s as m,a as S}from"./wire-codec-Dh0j-GnY.mjs";const g="id",y=new Set(["_id","id"]),C=r=>{const e=[];for(const o of r??[])for(const[t,i]of Object.entries(o))e.push({direction:i,field:t});return e.length===0?[{direction:"asc",field:"_creationTime"}]:e},w=r=>{const e=new TextEncoder().encode(r);let o="";for(const t of e)o+=String.fromCodePoint(t);return btoa(o)},b=r=>{const e=atob(r),o=Uint8Array.from(e,t=>t.codePointAt(0)??0);return new TextDecoder().decode(o)},D=(r,e)=>{const o=e.map(t=>r[t.field]);return o.push(r._id),w(JSON.stringify(S(o)))},a=()=>new h("BAD_REQUEST","invalid cursor"),E=r=>{let e;try{e=m(JSON.parse(b(r)))}catch{throw a()}if(!Array.isArray(e))throw a();return e},f=(r,e,o)=>{const t=r.some(s=>y.has(s.field))?r:[...r,{direction:"asc",field:g}],i=[];for(const[s,n]of t.entries()){const c=[];for(const[u,p]of t.slice(0,s).entries())c.push({[p.field]:{eq:e[u]}});const l=o(n.direction,s===t.length-1);c.push({[n.field]:{[l]:e[s]}});const[d]=c;i.push(c.length===1&&d!==void 0?d:{AND:c})}return{OR:i}},T=(r,e)=>f(r,e,o=>o==="desc"?"lt":"gt"),v=(r,e)=>r==="desc"?e?"gte":"gt":e?"lte":"lt",k=(r,e)=>f(r,e,v),A=["_id","_creationTime"],B=(r,e,o)=>{if(!e)return r;const t=new Set([...e,...A,...o?Object.keys(o):[]]);return r.map(i=>{const s={};for(const n of t)n in i&&(s[n]=i[n]);return s})},N=(r,e)=>r&&e!==!0?{[r.field]:{isNull:!0}}:void 0,x=(r,e)=>e===void 0||r[e]===null||r[e]===void 0;export{B as applySelect,k as buildSeekBeforeWhere,T as buildSeekWhere,E as decodeCursor,D as encodeCursor,b as fromBase64,a as invalidCursor,x as isLiveForCompanion,C as normalizeOrderKeys,N as softDeleteScope,w as toBase64};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{stableStringify as v}from"./stableStringify-BjLh4gvA.mjs";import{A as m,a as A}from"./wire-codec-Dh0j-GnY.mjs";const S="_id",p="_creationTime",y="page",O=r=>{let t;for(const s of r){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},w=(r,t)=>{const s=t[p];if(typeof s!="number")return r.length;const n=O(r);for(const[o,e]of r.entries()){const i=e[p];if(typeof i=="number"&&(n?i<s:i>s))return o}return r.length},x="__lunora__",N=r=>{if(typeof r!="object"||r===null||Array.isArray(r))return;const t=r[S];return typeof t=="string"?t:void 0},$=r=>{const t=new Map,s=[];for(const n of r){const o=N(n);if(o===void 0||t.has(o))return;t.set(o,n),s.push(o)}return{byId:t,order:s}},_=(r,t)=>{const s=r.order.filter(o=>t.byId.has(o)),n=t.order.filter(o=>r.byId.has(o));return s.length!==n.length?!1:s.every((o,e)=>n[e]===o)},k=(r,t,s,n)=>{const o=[];for(const e of r.order)t.byId.has(e)||o.push({delta:{key:e,op:"delete",table:s},frame:`{"key":${JSON.stringify(e)},"op":"delete","table":${n}}`});return o},D=(r,t,s,n)=>{const o=[];for(const e of t.order){const i=t.byId.get(e),a=r.byId.get(e),u=JSON.stringify(A(i)),f=a===void 0?void 0:JSON.stringify(a);if(f===u)continue;const d=f===void 0?"insert":"update";o.push({delta:{key:e,op:d,row:i,table:s},frame:`{"key":${JSON.stringify(e)},"op":"${d}","row":${u},"table":${n}}`})}return o},M=(r,t)=>{if(Array.isArray(r)&&Array.isArray(t))return{next:t,previous:r};if(!m(r)||!m(t))return;const s=r[y],n=t[y];if(!Array.isArray(s)||!Array.isArray(n))return;const o=e=>Object.fromEntries(Object.entries(e).filter(([i])=>i!==y));if(v(o(r))===v(A(o(t))))return{next:n,previous:s}},j=(r,t,s)=>{const n=s.filter(({delta:e})=>e.op==="insert");if(n.length===0)return!0;const o=r.order.filter(e=>t.byId.has(e)).map(e=>r.byId.get(e));for(const{delta:e}of n){const i=e.row;o.splice(w(o,i),0,i)}return o.length===t.order.length&&o.every((e,i)=>e[S]===t.order[i])},I=(r,t,s)=>{let n;try{n=JSON.parse(r)}catch{return}const o=M(n,t);if(o===void 0)return;const e=$(o.previous),i=$(o.next);if(e===void 0||i===void 0||!_(e,i))return;const a=s===""?x:s,u=JSON.stringify(a),f=[...k(e,i,a,u),...D(e,i,a,u)];return j(e,i,f)?f:void 0},P=(r,t,s,n)=>{const o=I(r,t,s);if(o!==void 0){if(n!==void 0)for(const{frame:e}of o)n.push(e);return o.map(({delta:e})=>e)}},T=(r,t)=>{try{return r.send(t),!0}catch{return!1}},E=r=>{const{cursorSuffix:t,lastMutationId:s,nextResult:n,pageDeltas:o,previousJson:e,snapshotJson:i,subId:a,table:u}=r,f=JSON.stringify(a),d=(s===void 0?"":`,"lastMutationId":${String(s)}`)+t,c=`{"type":"data","id":${f},"data":${i}${d}}`,l=e!==void 0&&(o===!0||Array.isArray(n))?I(e,n,u):void 0;if(l===void 0||l.length===0)return[c];const b=[];let g=0;for(const{frame:J}of l){const h=`{"type":"delta","id":${f},"delta":${J}${d}}`;if(g+=h.length,g>=c.length)return[c];b.push(h)}return b},R=async r=>{let t=0;for(;t<100;){t+=1;const{bufferedAmount:s}=r;if(typeof s!="number"||s<1048576)return;await new Promise(n=>{setTimeout(n,20)})}};export{R as awaitWsDrain,E as subscriptionFrames,P as subscriptionListDeltas,T as trySendFrame};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{B as R,W as x,x as k,T as S,l as O,y as M,c as w}from"./ctx-db-companions-
|
|
1
|
+
import{B as R,W as x,x as k,T as S,l as O,y as M,c as w}from"./ctx-db-companions-BJlCofon.mjs";import"@lunora/errors";import{sql as r}from"drizzle-orm";import{matchesStaticWhere as A}from"./AGGREGATE_SQL_FUNCTION-CTo0-9iZ.mjs";import{encodeAggregateKey as L,foldAggregateTally as C,aggregateTableName as F}from"./aggregateTableName-DN7gk6uh.mjs";import{migrateSearchState as y,readSearchBackfillState as D,writeSearchBackfillState as N}from"./SEARCH_STATE_TABLE-DRk_SB72.mjs";import{runDrizzle as d}from"./runDrizzle-C3n5gJsk.mjs";import{C as T,E as p,c as v,p as B,T as W,a as E,D as j}from"./do-sql-DKSFK627.mjs";import{isLiveForCompanion as _}from"./applySelect-5w13bMAR.mjs";import{matchesRankStaticWhere as U,rankTableName as V}from"./RANK_TIEBREAK-BGk411OR.mjs";const Y=(e,o)=>e.profile!==o?{cursor:void 0,finished:!1,wipe:e.cursor!==void 0||e.done}:{cursor:e.cursor,finished:e.done,wipe:!1},u=(e,o)=>d(e,r`SELECT COUNT(*) AS count FROM ${r.identifier(o)}`).one().count>0,I=(e,o)=>d(e,r`SELECT id, _creationTime, ${r.identifier(E)} FROM ${r.identifier(o)}`).toArray(),q=(e,o,n,i)=>{const t=F(o,n.name);if(u(e,t))return;const s=n.by??[],c=new Map,f=I(e,o);for(const l of f){const a=p(l);if(!a||!_(a,i)||n.where&&!A(a,n.where))continue;const $=L(s,a);C(c,$,n,a)}for(const[l,a]of c)d(e,r`INSERT INTO ${r.identifier(t)} (${v}, ${B}, ${W}) VALUES (${l}, ${a.value}, ${a.count})`)},re=(e,o)=>{for(const[n,i]of Object.entries(o.tables))if(!(i.shardMode?.kind==="global"||!i.aggregateIndexes))for(const t of i.aggregateIndexes)q(e,n,t,i.softDeleteMode?.field)},z=(e,o,n)=>{const i=V(o,n.name);if(u(e,i))return;const t=R(n),s=I(e,o);for(const c of s){const f=p(c);!f||n.where&&!U(f,n.where)||x(e,i,n,t,f._id,f)}},oe=(e,o)=>{for(const[n,i]of Object.entries(o.tables))if(!(i.shardMode?.kind==="global"||!i.rankIndexes))for(const t of i.rankIndexes)z(e,n,t)},g=500,b=(e,o,n)=>{const i=w(o,n.name),{profile:t}=k(n.language),s=Y(D(e,i),t);if(s.finished)return!0;s.wipe&&d(e,r`DELETE FROM ${r.identifier(i)}`);const{cursor:c}=s,f=d(e,c===void 0?r`SELECT id, _creationTime, ${r.identifier(E)} FROM ${r.identifier(o)} ORDER BY id ASC LIMIT ${r.raw(String(g))}`:r`SELECT id, _creationTime, ${r.identifier(E)} FROM ${r.identifier(o)} WHERE id > ${c} ORDER BY id ASC LIMIT ${r.raw(String(g))}`).toArray();let l=c;for(const $ of f){const{id:m}=$;if(typeof m!="string")continue;l=m,d(e,r`DELETE FROM ${r.identifier(i)} WHERE ${r.identifier(S)} = ${m}`);const h=j($);h&&d(e,r`INSERT INTO ${r.identifier(i)} (${r.identifier(O)}, ${r.identifier(S)}) VALUES (${M(h,n)}, ${m})`)}const a=f.length<g;return N(e,i,l,a,t),a},ne=(e,o,n)=>{if(T(e))for(const i of n.searchIndexes??[])i.staged||b(e,o,i)},te=(e,o)=>{if(T(e)){y(e);for(const[n,i]of Object.entries(o.tables))if(!(i.shardMode?.kind==="global"||!i.searchIndexes))for(const t of i.searchIndexes){let s=!1;for(;!s;)s=b(e,n,t)}}};export{re as backfillAggregateIndexes,oe as backfillRankIndexes,te as backfillSearchIndexes,ne as backfillSearchIndexesForTable};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{a as u}from"./wire-codec-
|
|
1
|
+
import{a as u}from"./wire-codec-Dh0j-GnY.mjs";const l=(t,o)=>{if(!o)return t;const r=Object.create(null);for(const a of["_id","_creationTime",...o])Object.hasOwn(t,a)&&(r[a]=t[a]);return r},b=(t,o,r)=>{const{columns:a,table:i}=r,n=new Map,p=[];for(const{doc:e,id:s}of t){const c=l(e,a),d=JSON.stringify(u(c));n.set(s,d);const h=o.get(s);h===void 0?p.push({key:s,op:"insert",table:i,value:c}):h!==d&&p.push({key:s,op:"update",table:i,value:c})}for(const e of o.keys())n.has(e)||p.push({key:e,op:"delete",table:i});return{next:n,rowsPatch:p}},f=t=>t.map(o=>o.value===void 0?o:{...o,value:u(o.value)}),y=(t,o,r={})=>{const{baseCheckpoint:a,checkpoint:i,epoch:n,lastMutationId:p,pokeId:e}=o,s=[JSON.stringify({baseCheckpoint:a,epoch:n,pokeId:e,type:"pokeStart"})];for(const c of t){const d=r.preEncoded?c.rowsPatch:f(c.rowsPatch);s.push(JSON.stringify({pokeId:e,rowsPatch:d,shapeId:c.shapeId,type:"pokePart",...p===void 0?{}:{lastMutationId:p}}))}return s.push(JSON.stringify({checkpoint:i,epoch:n,pokeId:e,type:"pokeEnd"})),s};export{y as buildPokeFrames,b as diffGlobalMembership,f as encodeRowsPatch,l as projectColumns};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{quoteIdentifier as _}from"./quoteIdentifier-CObIFRhb.mjs";import{reprojectionMigrationTable as u}from"./REPROJECTION_MIGRATION_PREFIX-D2dltRFC.mjs";import{REPROJECTION_MIGRATION_PREFIX as L,reprojectionMigrationId as C}from"./REPROJECTION_MIGRATION_PREFIX-D2dltRFC.mjs";import{a as m}from"./wire-codec-
|
|
1
|
+
import{quoteIdentifier as _}from"./quoteIdentifier-CObIFRhb.mjs";import{reprojectionMigrationTable as u}from"./REPROJECTION_MIGRATION_PREFIX-D2dltRFC.mjs";import{REPROJECTION_MIGRATION_PREFIX as L,reprojectionMigrationId as C}from"./REPROJECTION_MIGRATION_PREFIX-D2dltRFC.mjs";import{a as m}from"./wire-codec-Dh0j-GnY.mjs";import{runSql as p}from"./runDrizzle-C3n5gJsk.mjs";import{L as E,a as g}from"./do-sql-DKSFK627.mjs";import{y as b}from"./sql-projection-jfoe331H.mjs";const R=m(0n)[0],l=t=>t.shardMode?.kind==="global"?[]:Object.entries(t.shape).filter(([,r])=>b(r)).map(([r])=>r),T=t=>Object.entries(t.tables).filter(([,r])=>l(r).length>0).map(([r])=>r),f=t=>{const r=`json_each(${_(g)}) AS __f__`;return{params:[JSON.stringify(t),R,"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 (?, ?))`}},M=(t,r,o)=>{if(o.length===0)return 0;const{params:e,sql:n}=f(o);return p(t,`SELECT COUNT(*) AS count FROM ${_(r)} WHERE ${n}`,...e).toArray()[0]?.count??0},$=(t,r,o,e)=>{const{params:n,sql:i}=f(o);return p(t,`SELECT 1 FROM ${_(r)} WHERE id = ? AND (${i}) LIMIT 1`,e,...n).toArray().length>0},N=(t,r,o)=>{const e=u(t);if(e===void 0)return;const n=r.tables[e];if(!n)return;const i=l(n);if(i.length!==0)return{id:t,table:e,up:a=>{const s=a._id;if(!(typeof s!="string"||!$(o,e,i,s))){try{E(a)}catch(c){console.warn(`${t}: skipping row ${s} — it cannot be re-projected: ${c instanceof Error?c.message:String(c)}`);return}return a}}}};export{L as REPROJECTION_MIGRATION_PREFIX,N as buildReprojectionMigration,M as countLegacyRows,l as reprojectableFields,C as reprojectionMigrationId,T as reprojectionTables};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{LunoraError as N}from"@lunora/errors";import{sql as t}from"drizzle-orm";import{mergeWhere as v}from"./CountRlsUnsupportedError-8BqPYQoP.mjs";import{SCAN_DEP as x}from"./SCAN_DEP-D_yR9EeV.mjs";import{runDrizzle as B}from"./runDrizzle-C3n5gJsk.mjs";import{sqliteInList as O}from"./param-CYxL68V-.mjs";import{decodeCursor as W,toBase64 as z}from"./applySelect-
|
|
1
|
+
import{LunoraError as N}from"@lunora/errors";import{sql as t}from"drizzle-orm";import{mergeWhere as v}from"./CountRlsUnsupportedError-8BqPYQoP.mjs";import{SCAN_DEP as x}from"./SCAN_DEP-D_yR9EeV.mjs";import{runDrizzle as B}from"./runDrizzle-C3n5gJsk.mjs";import{sqliteInList as O}from"./param-CYxL68V-.mjs";import{decodeCursor as W,toBase64 as z}from"./applySelect-5w13bMAR.mjs";import{sortColumnName as F,resolveRankPartition as H,RANK_TIEBREAK as m,encodePartitionKey as J,rankTableName as V}from"./RANK_TIEBREAK-BGk411OR.mjs";const Y="__doc__",G=n=>z(JSON.stringify(n)),X=n=>n.after?[n.after.partitionKey,...n.after.sortValues,n.after.rowId]:n.cursor?W(n.cursor):void 0,Z=(n,o,f)=>{if(n?.length!==1+o.length+1)return;const r=[{column:"__partition__",direction:"asc"}];for(const[s,a]of o.entries())r.push({column:a,direction:f[s]?.direction??"asc"});r.push({column:m,direction:"asc"});const e=[];for(const[s,a]of r.entries()){const c=[];for(const[i,l]of r.slice(0,s).entries())c.push(t`${t.identifier(l.column)} IS ${n[i]}`);c.push(t`${t.identifier(a.column)} ${t.raw(a.direction==="desc"?"<":">")} ${n[s]}`);const[p]=c;e.push(c.length===1&&p!==void 0?p:t`(${t.join(c,t` AND `)})`)}return t`(${t.join(e,t` OR `)})`},C=null,Q=(n,o)=>{if(n===void 0)return C;const f=[n.__partition__,...o.map(r=>n[r]),n[m]];return G(f)},U=(n,o,f)=>{const r=[];for(const e of n){const s=e[m];if(typeof s!="string")continue;const a=o.get(s);if(!a)continue;const c=typeof e.__partition__=="string"?e.__partition__:"",p=f.map(i=>e[i]??null);r.push({doc:a,key:{partitionKey:c,rowId:s,sortValues:p}})}return r},tt=t`${t.identifier("id")}`,nt=(n,o,f)=>{const{rowToDocument:r}=n,e=new Map;if(f.length===0)return e;const s=B(n.sql,t`SELECT id, _creationTime, ${t.identifier(Y)} FROM ${t.identifier(o)} WHERE ${O(tt,f,!1)}`).toArray();for(const a of s){const c=r(a),p=a.id;c&&typeof p=="string"&&e.set(p,c)}return e},pt=(n,o,f,r)=>{const{assertRankPartitionLocal:e,ensureRankBackfilled:s,onRead:a,schema:c}=n,p=c.tables[o];if(!p)throw new N("INTERNAL",`unknown table: ${o}`);const i=p.rankIndexes?.find(u=>u.name===f);if(!i)throw new N("INTERNAL",`unknown rankIndex "${f}" on table "${o}"`);e(o,p,i),a(o,x),s(o,i);const l=V(o,i.name),d=i.sortBy.map((u,w)=>F(w)),$=Math.max(1,Math.min(1e3,Math.floor(r.take??100))),S=v(r.baseWhere,r.where),R=H(i,S),h=[t`${t.identifier("__partition__")} ASC`];for(const[u,w]of d.entries()){const q=i.sortBy[u]?.direction;h.push(t`${t.identifier(w)} ${t.raw(q==="desc"?"DESC":"ASC")}`)}h.push(t`${t.identifier(m)} ASC`);const _=[];typeof r.partitionKey=="string"?_.push(t`${t.identifier("__partition__")} = ${r.partitionKey}`):R&&_.push(t`${t.identifier("__partition__")} = ${J(i.partitionBy??[],R)}`);const T=X(r),k=Z(T,d,i.sortBy);k&&_.push(k);const I=t.identifier(m),A=t.identifier("__partition__"),L=_.length>0?t` WHERE ${t.join(_,t` AND `)}`:t``,M=d.length>0?t`${I}, ${A}, ${t.join(d.map(u=>t.identifier(u)),t`, `)}`:t`${I}, ${A}`,D=t`SELECT ${M} FROM ${t.identifier(l)}${L} ORDER BY ${t.join(h,t`, `)} LIMIT ${t.raw(String($+1))}`,y=B(n.sql,D).toArray(),g=y.length>$,E=g?y.slice(0,$):y,K=E.map(u=>u[m]),b=U(E,nt(n,o,K),d),P=g?Q(E.at(-1),d):C,j=i.sortBy.map(u=>u.direction==="desc"?"desc":"asc");return{continueCursor:P,directions:j,hasMore:g,rows:b}};export{pt as computeRankPage,nt as hydrateDocsById};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{S as C,W as R,B as f}from"./ctx-db-companions-BJlCofon.mjs";import"@lunora/errors";import"drizzle-orm";import"./AGGREGATE_SQL_FUNCTION-CTo0-9iZ.mjs";import"./aggregateTableName-DN7gk6uh.mjs";import"./runDrizzle-C3n5gJsk.mjs";import"./do-sql-DKSFK627.mjs";import"./param-CYxL68V-.mjs";import"./GEO_DEFAULT_PRECISION-DyI5zggj.mjs";import"./applySelect-5w13bMAR.mjs";import"./RANK_TIEBREAK-BGk411OR.mjs";import"./sql-projection-jfoe331H.mjs";import"./serializeSqlValue-BR4UOWoP.mjs";export{C as createCompanionSync,R as insertRankRow,f as rankColumnsSql};
|
package/dist/packem_shared/{ctx-db-companions-c12P7dbv.mjs → ctx-db-companions-BJlCofon.mjs}
RENAMED
|
@@ -1 +1 @@
|
|
|
1
|
-
import"@lunora/errors";import{sql as e}from"drizzle-orm";import{matchesStaticWhere as P,aggregateSqlFunction as de}from"./AGGREGATE_SQL_FUNCTION-CTo0-9iZ.mjs";import{encodeAggregateKey as N,foldAggregateTally as V,coerceAggregateNumber as F,aggregateTableName as G}from"./aggregateTableName-
|
|
1
|
+
import"@lunora/errors";import{sql as e}from"drizzle-orm";import{matchesStaticWhere as P,aggregateSqlFunction as de}from"./AGGREGATE_SQL_FUNCTION-CTo0-9iZ.mjs";import{encodeAggregateKey as N,foldAggregateTally as V,coerceAggregateNumber as F,aggregateTableName as G}from"./aggregateTableName-DN7gk6uh.mjs";import{runDrizzle as u}from"./runDrizzle-C3n5gJsk.mjs";import{C as ce,a as M,E as D,c as j,p as S,T as _,h as fe,A as C,N as k}from"./do-sql-DKSFK627.mjs";import{param as ue,WORKERD_SQLITE_LIMITS as $e}from"./param-CYxL68V-.mjs";import{encodeGeohash as me,GEO_DEFAULT_PRECISION as Ee}from"./GEO_DEFAULT_PRECISION-DyI5zggj.mjs";import{isLiveForCompanion as J}from"./applySelect-5w13bMAR.mjs";import{encodePartitionKey as he,sortColumnName as pe,matchesRankStaticWhere as Y,rankTableName as Z}from"./RANK_TIEBREAK-BGk411OR.mjs";import{y as ge}from"./sql-projection-jfoe331H.mjs";import{serializeSqlValue as ee}from"./serializeSqlValue-BR4UOWoP.mjs";const _e=["de","en","es","fr","it","nl","none","pt"],ye=o=>_e.includes(o),be="a an and are as at be but by for if in into is it no not of on or such that the their then there these they this to was will with",Se="aber als am an auch auf aus bei bin bis bist da dass der den des dem die das denn dir du ein eine für hat ich im in ist mit nicht noch nur oder sich sie sind über und von vor war wie wir zu zum zur",Te="a al como con de del el en es la las lo los mas no o para pero por que se su sus un una uno y ya",ve="au aux avec ce ces dans de des du elle en et eux il je la le les leur lui ma mais me même mes moi mon ne nos notre nous on ou par pas pour qu que qui sa se ses son sur ta te tes toi ton tu un une vos votre vous y",we="a ai al alla anche che chi ci coi col come con da dal degli dei del della di do e ed gli ha hai hanno i il in la le lo ma mi ne nei nel non o per più quale quanto se si sono su sul tra un una uno vi",Ae="aan al als bij dan dat de der deze die dit door een en er het hij ij in is je kan me men met mij na naar niet nog nu of om ons ook op over te tot uit van voor was wat we wij zij zijn zo",Re="a ao aos as até com como da das de do dos e em entre era essa esse esta este eu foi há isso já mais mas me mesmo meu na nas no nos num numa o os ou para pela pelo por qual que quem se sem seu só sua também te tem um uma você",Le=/[\u0300-\u036F]/gu,ne=o=>o.normalize("NFD").replaceAll(Le,"").normalize("NFC").toLowerCase(),O=o=>new Set(ne(o).split(" ")),Ie={de:O(Se),en:O(be),es:O(Te),fr:O(ve),it:O(we),nl:O(Ae),none:new Set,pt:O(Re)},Ne=2,Oe=256,Q=new Map,je=o=>{const a=o!==void 0&&ye(o)?o:"none",l=Q.get(a);if(l)return l;const g=Ie[a],w=r=>{const A=(ne(r).match(/[\p{L}\p{N}]+/gu)??[]).filter(T=>T.length<=Oe);return g.size===0?A:A.filter(T=>!g.has(T))},m={document:w,profile:`${a}-v${String(Ne)}`,query:r=>{const A=w(r);return A.filter((T,L)=>A.lastIndexOf(T)===L)}};return Q.set(a,m),m},xe=(o,a)=>{if(!a.includes("."))return o[a];let l=o;for(const g of a.split(".")){if(l===null||typeof l!="object"||Array.isArray(l))return;l=l[g]}return l},Fe=(o,a)=>`${o}__fts_${a}`,Ce="__text__",X="__id__",Me=1e3,De=(o,a)=>a.document(o),q=(o,a)=>xe(o,a),ke=o=>typeof o=="string"?o:o==null?"":typeof o=="number"||typeof o=="bigint"||typeof o=="boolean"?String(o):JSON.stringify(o)??"",qe=(o,a,l)=>o!==void 0&&a!==void 0&&q(o,l.field)===q(a,l.field),ze=(o,a)=>De(ke(q(o,a.field)),je(a.language)).slice(0,Me).join(" "),We=(o,a,l)=>[...o.partitionBy??[],...o.sortBy.map(g=>g.field),...o.where?Object.keys(o.where):[]].every(g=>a[g]===l[g]),oe=o=>e.join(["__id__","__partition__",...o.sortBy.map((a,l)=>pe(l))].map(a=>e.identifier(a)),e`, `),te=(o,a,l,g,w,m)=>{const r=he(l.partitionBy??[],m),A=l.sortBy.map(L=>ee(m[L.field]??null)),T=e.join([w,r,...A].map(L=>ue(L)),e`, `);u(o,e`INSERT INTO ${e.identifier(a)} (${g}) VALUES (${T})`)},Be=(o,a,l,g,w,m)=>{if(w&&m&&We(l,w,m))return;const r=Z(a,l.name);w&&u(o,e`DELETE FROM ${e.identifier(r)} WHERE ${e.identifier("__id__")} = ${g}`),!(!m||l.where&&!Y(m,l.where))&&te(o,r,l,oe(l),g,m)},nn=o=>{const{broadcast:a,indexKeysFor:l,invalidateCache:g,recordCdc:w,schema:m,sql:r}=o,A=new Set,T=t=>m.tables[t]?.softDeleteMode?.field,L=new Set,z=(t,n)=>{const s=`${t}::${n.name}`;if(A.has(s))return;const d=G(t,n.name),c=n.by??[],f=T(t),h=new Map,y=u(r,e`SELECT id, _creationTime, ${e.identifier(M)} FROM ${e.identifier(t)}`).toArray();for(const v of y){const $=D(v);if(!$||!J($,f)||n.where&&!P($,n.where))continue;const E=N(c,$);V(h,E,n,$)}u(r,e`DELETE FROM ${e.identifier(d)}`);const R=Math.floor($e.boundParams/3),I=[...h];for(let v=0;v<I.length;v+=R){const $=I.slice(v,v+R),E=e.join($.map(([i,p])=>e`(${i}, ${p.value}, ${p.count})`),e`, `);u(r,e`INSERT INTO ${e.identifier(d)} (${j}, ${S}, ${_}) VALUES ${E}`)}A.add(s)},ie=(t,n,s)=>{const d=n.by??[],c=n.field??"",f=[],h=(E,i)=>{const p=ee(i);p===null?f.push(e`${k(E)} IS NULL`):f.push(e`${k(E)} = ${p}`)};for(const E of d)h(E,s[E]??null);const y=T(t);y!==void 0&&h(y,null);for(const[E,i]of Object.entries(n.where??{}))h(E,i!==null&&typeof i=="object"&&!Array.isArray(i)?i.eq:i);const R=f.length>0?e` WHERE ${e.join(f,e` AND `)}`:e``,I=m.tables[t]?.shape[c];if(I&&ge(I)){const E=u(r,e`SELECT id, _creationTime, ${e.identifier(M)} FROM ${e.identifier(t)}${R}`).toArray(),i=new Map;for(const p of E){const b=D(p);b&&V(i,"",n,b)}return{value:i.get("")?.value??null}}const v=de(n.op),$=k(c);return{value:u(r,e`SELECT ${e.raw(v)}(${$}) AS value FROM ${e.identifier(t)}${R}`).one().value??null}},re=(t,n,s,d)=>{const c=G(t,n.name),{op:f}=n,h=n.field??"",y=i=>{u(r,e`DELETE FROM ${e.identifier(c)} WHERE ${j} = ${i} AND ${_} <= 0`)},R=T(t),I=i=>!n.where||P(i,n.where),v=i=>J(i,R)&&I(i);d!==void 0&&f!=="count"&&I(d)&&F(d[h]);const $=s&&v(s)?s:void 0,E=d&&v(d)?d:void 0;if(!(!$&&!E)){if(f==="count"){for(const[i,p]of[[$,-1],[E,1]]){if(!i)continue;const b=N(n.by??[],i);u(r,C(c,b,p,p,e`${S} = ${S} + excluded.${S}, ${_} = ${_} + excluded.${_}`))}$&&y(N(n.by??[],$));return}if(f==="sum"||f==="avg"){for(const[i,p]of[[$,-1],[E,1]]){if(!i)continue;const b=F(i[h]);if(b===void 0)continue;const x=N(n.by??[],i);u(r,C(c,x,p*b,p,e`${S} = COALESCE(${S}, 0) + excluded.${S}, ${_} = ${_} + excluded.${_}`))}$&&y(N(n.by??[],$));return}if($){const i=N(n.by??[],$),p=F($[h]),b=u(r,e`SELECT ${S} AS value, ${_} AS count FROM ${e.identifier(c)} WHERE ${j} = ${i}`).toArray()[0],x=(b?.count??0)-1;if(x<=0)u(r,e`DELETE FROM ${e.identifier(c)} WHERE ${j} = ${i}`);else if(b&&p!==void 0&&b.value!==null&&p===b.value){const le=ie(t,n,$);u(r,e`UPDATE ${e.identifier(c)} SET ${S} = ${le.value}, ${_} = ${x} WHERE ${j} = ${i}`)}else u(r,e`UPDATE ${e.identifier(c)} SET ${_} = ${_} - 1 WHERE ${j} = ${i}`)}if(E){const i=N(n.by??[],E),p=F(E[h]);if(p===void 0)u(r,C(c,i,null,1,e`${_} = ${_} + 1`));else{const b=f==="min"?"MIN":"MAX";u(r,C(c,i,p,1,e`${S} = ${e.raw(b)}(COALESCE(${S}, excluded.${S}), excluded.${S}), ${_} = ${_} + 1`))}}}},ae=t=>{for(const n of m.tables[t]?.aggregateIndexes??[])z(t,n)},W=(t,n,s)=>{for(const d of m.tables[t]?.aggregateIndexes??[])re(t,d,n,s)},B=(t,n)=>{const s=`${t}::rank::${n.name}`;if(L.has(s))return;const d=Z(t,n.name),c=u(r,e`SELECT id, _creationTime, ${e.identifier(M)} FROM ${e.identifier(t)}`).toArray();u(r,e`DELETE FROM ${e.identifier(d)}`);const f=oe(n);for(const h of c){const y=D(h);!y||n.where&&!Y(y,n.where)||te(r,d,n,f,y._id,y)}L.add(s)},se=t=>{for(const n of m.tables[t]?.rankIndexes??[])B(t,n)},H=(t,n,s,d)=>{for(const c of m.tables[t]?.rankIndexes??[])Be(r,t,c,n,s,d)},U=(t,n,s,d)=>{const c=m.tables[t]?.searchIndexes??[];if(!(c.length===0||!ce(r)))for(const f of c){if(qe(d,s,f))continue;const h=Fe(t,f.name);u(r,e`DELETE FROM ${e.identifier(h)} WHERE ${e.identifier(X)} = ${n}`),s&&u(r,e`INSERT INTO ${e.identifier(h)} (${e.identifier(Ce)}, ${e.identifier(X)}) VALUES (${ze(s,f)}, ${n})`)}},K=(t,n,s)=>{for(const d of m.tables[t]?.geoIndexes??[]){const c=fe(t,d.name);u(r,e`DELETE FROM ${e.identifier(c)} WHERE ${e.identifier("__id__")} = ${n}`);const f=s?.[d.field];if(f!==null&&typeof f=="object"&&typeof f.lat=="number"&&typeof f.lng=="number"){const{lat:h,lng:y}=f,R=me({lat:h,lng:y},d.precision??Ee);u(r,e`INSERT INTO ${e.identifier(c)} (${e.identifier("__id__")}, ${e.identifier("__geohash__")}, ${e.identifier("__lat__")}, ${e.identifier("__lng__")}) VALUES (${n}, ${R}, ${h}, ${y})`)}}};return{ensureBackfilledForTable:ae,ensureBackfilledIndex:z,ensureRankBackfilled:B,ensureRankBackfilledForTable:se,syncAggregates:W,syncCompanionsForInsert:(t,n,s)=>{U(t,n,s),K(t,n,s),W(t,void 0,s),H(t,n,void 0,s),g(t,n,s),w(t,n,"insert",s),a({indexKeys:l(t,s),key:n,op:"insert",row:s,table:t})},syncGeo:K,syncRanks:H,syncSearch:U}};export{oe as B,nn as S,X as T,te as W,Fe as c,Ce as l,De as n,je as x,ze as y};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{createShardCtxDb as b}from"./NotUniqueError-
|
|
1
|
+
import{createShardCtxDb as b}from"./NotUniqueError-DYo7r67J.mjs";import{createRelayLink as I}from"./DEFAULT_MAX_RELAYS-Cinp9pPC.mjs";import{ConflictError as N}from"./ConflictError-C8GtJmjS.mjs";import{runShardMigrations as v}from"./runShardMigrations-BCuK60KT.mjs";import{relayName as q}from"./DEFAULT_PROMOTION_THRESHOLDS-DYGNAo1I.mjs";const C=(_,m={})=>({_meta:{column:{notNull:!0,...m}},kind:_}),D=(_,m,E)=>{const{describe:k,expect:i,it:f}=E;k(`engine contract: ${_}`,()=>{k("optimistic concurrency",()=>{const g=p=>({tables:{items:{indexes:[],shape:{title:C("string"),version:C("number",{notNull:!1})},triggerMap:{clobber:{handler:()=>{p.exec(`UPDATE "items" SET "__doc__" = json_set("__doc__", '$.version', 99) WHERE "id" = 'i1'`)},op:"update",timing:"before"}}}}});f("raises a CONFLICT of kind `occ` when a write's snapshot is clobbered",async()=>{const{close:p,host:d}=m();try{const c=d.sql,l=g(c);v(c,l);const s=b({schema:l,sql:c});await s.insert("items",{_id:"i1",title:"first",version:1},{allowExplicitId:!0}),await i(s.patch("i1",{title:"second"})).rejects.toBeInstanceOf(N)}finally{p?.()}}),f("reports the conflict as CONFLICT/409 rather than retrying it away",async()=>{const{close:p,host:d}=m();try{const c=d.sql,l=g(c);v(c,l);const s=b({schema:l,sql:c});await s.insert("items",{_id:"i1",title:"first",version:1},{allowExplicitId:!0});let r;try{await s.patch("i1",{title:"second"})}catch(t){r=t}const e=r;i(e.code).toBe("CONFLICT"),i(e.kind).toBe("occ")}finally{p?.()}}),f("leaves the row readable and unchanged after a conflict",async()=>{const{close:p,host:d}=m();try{const c=d.sql,l=g(c);v(c,l);const s=b({schema:l,sql:c});await s.insert("items",{_id:"i1",title:"first",version:1},{allowExplicitId:!0});try{await s.patch("i1",{title:"second"})}catch{}const r=await s.get("i1");i(r?.title).toBe("first"),i(r?.version).toBe(99)}finally{p?.()}}),f("raises a CONFLICT of kind `trigger` when a trigger writes its own row through the db",async()=>{const{close:p,host:d}=m();try{const c=d.sql,l={tables:{items:{indexes:[],shape:{title:C("string"),version:C("number",{notNull:!1})},triggerMap:{recurse:{handler:async(t,o)=>{await t.db.patch(o.doc._id,{version:99})},op:"update",timing:"before"}}}}};v(c,l);const s=b({schema:l,sql:c});await s.insert("items",{_id:"i1",title:"first",version:1},{allowExplicitId:!0});let r;try{await s.patch("i1",{title:"second"})}catch(t){r=t}const e=r;i(e).toBeInstanceOf(N),i(e.code).toBe("CONFLICT"),i(e.kind).toBe("trigger")}finally{p?.()}})}),k("shape-poke ordering",()=>{const g="shard-a",p={args:{},name:"messages"},d=(e,t,o,a)=>e.accept(t?.()??{},{connectionId:o,shapes:{[a]:p}}),c=(e,t)=>{let o=0,a=0;const n=u=>()=>{throw new Error(`the relay poke path must not reach RelayHost.${u}`)},h={fetch:(u,O)=>{if(JSON.parse(O?.body??"{}").type!=="relay_shape_subscribe")return Promise.resolve(new Response(void 0,{status:204}));const B=t[a];if(a+=1,B===void 0)throw new Error("the relay asked for more seeds than this fixture supplies");return Promise.resolve(Response.json(B))}},y={get:()=>h,getByName:()=>h,idFromName:u=>u},w={buildShapeDiff:n("buildShapeDiff"),computeOpLogShapeSeed:n("computeOpLogShapeSeed"),currentCdcEpoch:n("currentCdcEpoch"),deliverWhisperLocal:n("deliverWhisperLocal"),doName:()=>q(g,0),env:()=>({SHARD:y}),getWebSockets:()=>e.getSockets(),maskMetadata:n("maskMetadata"),nextPokeId:()=>(o+=1,`poke-${String(o)}`),readAttachment:u=>u.deserializeAttachment?.(),recordShapePokeFanout:()=>{},resolveShape:n("resolveShape"),rlsMetadata:n("rlsMetadata"),shardBinding:()=>"SHARD",sql:n("sql")},S=I(w);if(S===void 0)throw new Error("expected a relay link for a `…::relay::N` name");return S},l=e=>new Request("https://relay.internal/_lunora/relay",{body:JSON.stringify(e),headers:{"content-type":"application/json"},method:"POST"}),s=async(e,t,o)=>{const a=await e.seedRelayShape(t,o,p,{identity:void 0,userId:void 0});if(a!=="ok")throw new Error(`seed failed: ${JSON.stringify(a)}`)},r=(e={})=>l({...p,checkpoint:20,epoch:"e1",fromCursor:10,rowsPatch:[{id:"r1",op:"upsert",value:{title:"hello"}}],type:"relay_shape_poke",...e});f("frames a poke as pokeStart → pokePart per shape → pokeEnd, under one poke id",async()=>{const{close:e,createSocket:t,readFrames:o,sockets:a}=m();try{const n=c(a,[{cursor:10,epoch:"e1",frames:[]}]),h=d(a,t,"c-alice","s1");await s(n,h,"s1"),await n.handleControl(r());const y=(await o(h)).map(w=>JSON.parse(w));i(y.map(w=>w.type)).toStrictEqual(["pokeStart","pokePart","pokeEnd"]),i(new Set(y.map(w=>w.pokeId)).size).toBe(1),i(y[1]?.shapeId).toBe("s1"),i(y[2]?.checkpoint).toBe(20)}finally{e?.()}}),f("delivers a poke only to sockets whose cursor matches, and advances them past it",async()=>{const{close:e,createSocket:t,readFrames:o,sockets:a}=m();try{const n=c(a,[{cursor:10,epoch:"e1",frames:[]},{cursor:7,epoch:"e1",frames:[]}]),h=d(a,t,"c-alice","s1"),y=d(a,t,"c-bob","s2");await s(n,h,"s1"),await s(n,y,"s2"),await n.handleControl(r());const w=await o(h);i(w.length).toBe(3);const S=await o(y);i(S.length).toBe(0),await n.handleControl(r());const u=await o(h);i(u.length).toBe(3)}finally{e?.()}}),f("skips a socket whose cursor matches under a different CDC epoch",async()=>{const{close:e,createSocket:t,readFrames:o,sockets:a}=m();try{const n=c(a,[{cursor:10,epoch:"e1",frames:[]}]),h=d(a,t,"c-alice","s1");await s(n,h,"s1"),await n.handleControl(r({epoch:"e2"}));const y=await o(h);i(y.length).toBe(0),await n.handleControl(r());const w=await o(h);i(w.length).toBe(3)}finally{e?.()}})}),k("RLS identity under live subscription",()=>{const g="shard-a",p={args:{},name:"lobby-messages"},d={args:{},name:"my-orders"},c=s=>{const r=[],e=[],t={fetch:(a,n)=>(r.push(JSON.parse(n?.body??"{}")),Promise.resolve(new Response(void 0,{status:204})))},o=I({buildShapeDiff:()=>[{id:"r1",op:"upsert",value:{}}],computeOpLogShapeSeed:()=>({baseCheckpoint:void 0,cursor:10,epoch:"e1",rowsPatch:[]}),currentCdcEpoch:()=>"e1",deliverWhisperLocal:()=>0,doName:()=>g,env:()=>({SHARD:{get:()=>t,getByName:()=>t,idFromName:a=>a}}),getWebSockets:()=>[],maskMetadata:()=>({columns:[]}),nextPokeId:()=>"poke-1",readAttachment:()=>({}),recordShapePokeFanout:()=>{},resolveShape:(a,n,h)=>(e.push(h),a===d.name?{columns:["id"],effectiveWhere:{org:h?.identity?.org??"anonymous"},global:!1,table:"orders"}:{columns:["id"],effectiveWhere:{room:"lobby"},global:!1,table:"messages"}),rlsMetadata:()=>({policies:[]}),shardBinding:()=>"SHARD",sql:()=>s});if(o===void 0)throw new Error("expected an owner link for an un-suffixed DO name");return{owner:o,posts:r,resolvedUnder:e}},l=async(s,r)=>{await s.handleControl(new Request("https://owner.internal/_lunora/relay",{body:JSON.stringify({...r,connectionId:"c-alice",identity:{org:"acme"},relayIndex:0,subId:"s1",type:"relay_shape_subscribe",userId:"u1"}),headers:{"content-type":"application/json"},method:"POST"}))};f("seeds a subscriber under its own forwarded identity, never the anonymous one",async()=>{const{close:s,host:r}=m();try{const{owner:e,resolvedUnder:t}=c(r.sql);await l(e,d),i(t.some(o=>o?.userId==="u1"&&o.identity?.org==="acme")).toBe(!0)}finally{s?.()}}),f("routes an identity-scoped shape to a per-socket poke, not the cohort multicast",async()=>{const{close:s,host:r}=m();try{const{owner:e,posts:t}=c(r.sql);await l(e,d),t.length=0,await e.onFlush(new Set(["orders"]),20);const o=t.filter(a=>a.type==="relay_shape_poke");i(o.length).toBe(1),i(o[0]?.targetConnectionId).toBe("c-alice")}finally{s?.()}}),f("still multicasts an identity-blind shape to the whole cohort",async()=>{const{close:s,host:r}=m();try{const{owner:e,posts:t}=c(r.sql);await l(e,p),t.length=0,await e.onFlush(new Set(["messages"]),20);const o=t.filter(a=>a.type==="relay_shape_poke");i(o.length).toBe(1),i(o[0]?.targetConnectionId).toBeUndefined()}finally{s?.()}})})})};export{D as defineEngineContractSuite};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{LunoraError as c}from"@lunora/errors";import{sql as o}from"drizzle-orm";import{quoteIdentifier as m}from"./quoteIdentifier-CObIFRhb.mjs";import{s as u,a as p}from"./wire-codec-
|
|
1
|
+
import{LunoraError as c}from"@lunora/errors";import{sql as o}from"drizzle-orm";import{quoteIdentifier as m}from"./quoteIdentifier-CObIFRhb.mjs";import{s as u,a as p}from"./wire-codec-Dh0j-GnY.mjs";import{runDrizzle as _}from"./runDrizzle-C3n5gJsk.mjs";import{b as E}from"./sql-projection-jfoe331H.mjs";import"./serializeSqlValue-BR4UOWoP.mjs";const T=/^[A-Za-z_$][\w$]*$/u,S=e=>T.test(e)?e:`"${e.replaceAll("\\",String.raw`\\`).replaceAll('"',String.raw`\"`)}"`,l="__doc__",s="__originals__",R=e=>{if(Object.hasOwn(e,s))throw new c("BAD_REQUEST",`"${s}" is reserved by the row store's document encoding and cannot be used as a field name — rename the field`);let t,r;for(const[i,n]of Object.entries(e)){const a=E(n);a!==void 0&&(t??={...e},r??=Object.create(null),t[i]=a,r[i]=n)}t&&r&&(t[s]=r);try{return JSON.stringify(p(t??e))}catch(i){throw new c("BAD_REQUEST",`this document cannot be stored: ${i instanceof Error?i.message:String(i)}`)}},y=e=>{const t=u(JSON.parse(e)),{[s]:r,...i}=t;return r===null||typeof r!="object"||Array.isArray(r)?t:{...i,...r}},C=(e,t)=>`${e}__geo_${t}`,d=(e,t)=>t==="_id"||t==="id"?`${e}id`:t==="_creationTime"?`${e}_creationTime`:`json_extract(${e}${l}, '$.${S(t).replaceAll("'","''")}')`,A=e=>d("",e),v=e=>o.raw(A(e)),O=(e,t)=>d(`${m(e)}.`,t),B=(e,t)=>o.raw(O(e,t)),F=(e,t,r,i)=>o`CREATE ${i?o`UNIQUE `:o``}INDEX IF NOT EXISTS ${o.identifier(e)} ON ${o.identifier(t)} (${r})`,f=o.identifier("__key__"),I=o.identifier("__value__"),h=o.identifier("__count__"),X=(e,t,r,i,n)=>o`INSERT INTO ${o.identifier(e)} (${f}, ${I}, ${h}) VALUES (${t}, ${r}, ${i}) ON CONFLICT(${f}) DO UPDATE SET ${n}`,x=e=>{const t=[];for(const[r,i]of Object.entries(e.shape)){const n=i._meta?.column;n&&t.push([r,n])}return t},b=e=>{if(!e)return;const t=e[l];let r;typeof t=="string"?r=y(t):t&&typeof t=="object"?r=t:r={};const{id:i}=e;typeof i=="string"&&(r._id=i);const n=e._creationTime;return typeof n=="number"&&(r._creationTime=n),r},z=e=>{try{return b(e)}catch{return}},$=new WeakMap,P=e=>{const t=$.get(e);if(t!==void 0)return t;let r;try{_(e,o`CREATE VIRTUAL TABLE IF NOT EXISTS ${o.identifier("__lunora_fts_probe")} USING fts5(x)`),r=!0}catch{r=!1}finally{try{_(e,o`DROP TABLE IF EXISTS ${o.identifier("__lunora_fts_probe")}`)}catch{}}return $.set(e,r),r};export{X as A,P as C,z as D,b as E,x as I,R as L,v as N,B as O,O as S,h as T,A as _,l as a,f as c,y as g,C as h,S as j,I as p,s,F as y};
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{LunoraError as E}from"@lunora/errors";import{sql as m}from"drizzle-orm";import{runDrizzle as h}from"./runDrizzle-C3n5gJsk.mjs";import{liftSourceId as x}from"./liftSourceId-DApAbu7Q.mjs";import{normalizeSourceValue as K}from"./liftSourceId-DApAbu7Q.mjs";import{runExternalSourceTick as v,materializeExternalRowsIncremental as M}from"./materializeExternalRows-
|
|
1
|
+
import{LunoraError as E}from"@lunora/errors";import{sql as m}from"drizzle-orm";import{runDrizzle as h}from"./runDrizzle-C3n5gJsk.mjs";import{liftSourceId as x}from"./liftSourceId-DApAbu7Q.mjs";import{normalizeSourceValue as K}from"./liftSourceId-DApAbu7Q.mjs";import{runExternalSourceTick as v,materializeExternalRowsIncremental as M}from"./materializeExternalRows-C-5TKdc1.mjs";const _="__lunora_source_cursor",D=e=>e instanceof Date?`d:${e.toISOString()}`:typeof e=="bigint"?`b:${e.toString()}`:typeof e=="number"?`n:${e.toString()}`:`s:${e}`,R=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}},k=/^-?\d+$/,I=/^-?\d+(?:\.\d+)?$/,A=(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"&&I.test(e)&&I.test(t)?k.test(e)&&k.test(t)?BigInt(e)>BigInt(t):Number(e)>Number(t):String(e)>String(t),q=(e,t,a)=>{let n=a===null?void 0:R(a);for(const r of e){const s=r[t];if(s==null)continue;const i=s;(n===void 0||A(i,n))&&(n=i)}return n===void 0?null:D(n)},O=e=>{h(e,m`CREATE TABLE IF NOT EXISTS ${m.identifier(_)} (
|
|
2
2
|
table_name TEXT NOT NULL,
|
|
3
3
|
shard_key TEXT NOT NULL,
|
|
4
4
|
watermark TEXT,
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{applyCdcChanges as m}from"./CDC_LOG_TABLE-
|
|
1
|
+
import{applyCdcChanges as m}from"./CDC_LOG_TABLE-DNFFQwF_.mjs";import{selectShapeRows as f}from"./selectShapeMemberIds-Bkkug6vU.mjs";import{diffExternalSource as g,projectExternalSourceRow as c}from"./diffExternalSource-DMpkJta1.mjs";import{stableStringify as p}from"./stableStringify-BjLh4gvA.mjs";const x=async(t,s,r,e)=>{const{changes:n,nextBaseline:a}=g(s,r,e);return await m(t,n),{applied:n.length,nextBaseline:a}},E=async(t,s,r)=>{const{columns:e,deletedIds:n,table:a}=r,i=[];for(const u of s){const l=c(u,e),o=String(l._id);if(n?.has(o)){await t.get(o,a)&&i.push({id:o,op:"delete",seq:0,table:a,ts:0});continue}const d=await t.get(o,a);d&&p(c({...d,_id:o},e))===p(l)||i.push({doc:l,id:o,op:"insert",seq:0,table:a,ts:0})}return await m(t,i),{applied:i.length}},h=(t,s,r)=>{const e=new Map;for(const{doc:n,id:a}of f(t,s,void 0))e.set(a,p(c({...n,_id:a},r)));return e},R=async(t,s,r,e)=>{const n=h(t,e.table,e.columns);return x(s,r,n,e)};export{x as materializeExternalRows,E as materializeExternalRowsIncremental,h as readExternalSourceBaseline,R as runExternalSourceTick};
|
|
@@ -0,0 +1,5 @@
|
|
|
1
|
+
import{l as I,T as N,c as S}from"./ctx-db-companions-BJlCofon.mjs";import"@lunora/errors";import{sql as e}from"drizzle-orm";import{aggregateTableName as p}from"./aggregateTableName-DN7gk6uh.mjs";import{backfillSearchIndexesForTable as g}from"./backfillAggregateIndexes-DTOIsYbi.mjs";import{migrateCdcLog as l,migrateCdcMeta as h}from"./CDC_LOG_TABLE-DNFFQwF_.mjs";import{migrateClientWatermark as R}from"./CLIENT_WATERMARK_TABLE-LrKfdxyt.mjs";import{migrateGlobalShapeSnapshot as C}from"./GLOBAL_SHAPE_SNAPSHOT_TABLE-B2LKe4KU.mjs";import{migrateIdempotency as O}from"./IDEMPOTENCY_TABLE-tQ5mnqvw.mjs";import{migrateSearchState as u}from"./SEARCH_STATE_TABLE-DRk_SB72.mjs";import{runDrizzle as a}from"./runDrizzle-C3n5gJsk.mjs";import{a as U,N as E,y as _,I as b,C as X,c as x,p as B,T as c,h as D}from"./do-sql-DKSFK627.mjs";import{migrateDurableStreams as F}from"./appendStreamChunk-ksZYy1hZ.mjs";import{sortColumnName as M,rankTableName as Y}from"./RANK_TIEBREAK-BGk411OR.mjs";import{recordSchemaVersion as k}from"./SCHEMA_HISTORY_MAX_VERSIONS-CEK7b_7v.mjs";const y=(r,t,o)=>{for(const i of o.indexes){const n=`${t}_${i.name}`,s=e.join(i.fields.map(f=>E(f)),e`, `);a(r,_(n,t,s,i.unique??!1))}for(const[i,n]of b(o)){if(!n.unique)continue;const s=`${t}_unique_${i}`;a(r,_(s,t,E(i),!0))}},j=(r,t,o)=>{if(!(!o.searchIndexes||o.searchIndexes.length===0||!X(r))){for(const i of o.searchIndexes){const n=S(t,i.name);a(r,e`CREATE VIRTUAL TABLE IF NOT EXISTS ${e.identifier(n)} USING fts5(${e.identifier(I)}, ${e.identifier(N)} UNINDEXED)`),a(r,e`CREATE VIRTUAL TABLE IF NOT EXISTS ${e.identifier(`${n}__vocab`)} USING fts5vocab(${e.identifier(n)}, ${e.raw("instance")})`)}g(r,t,o)}},q=(r,t,o)=>{if(o.geoIndexes)for(const i of o.geoIndexes){const n=D(t,i.name);a(r,e`CREATE TABLE IF NOT EXISTS ${e.identifier(n)} (${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=`${t}__geo_${i.name}__btree`;a(r,_(s,n,e`${e.identifier("__geohash__")} ASC, ${e.identifier("__id__")} ASC`,!1))}},G=(r,t,o)=>{if(o.aggregateIndexes)for(const i of o.aggregateIndexes){const n=p(t,i.name);a(r,e`CREATE TABLE IF NOT EXISTS ${e.identifier(n)} (${x} TEXT PRIMARY KEY, ${B} REAL, ${c} INTEGER NOT NULL DEFAULT 0)`),a(r,e`PRAGMA table_info(${e.identifier(n)})`).toArray().some(s=>s.name==="__count__")||a(r,e`ALTER TABLE ${e.identifier(n)} ADD COLUMN ${c} INTEGER NOT NULL DEFAULT 0`)}},P=(r,t,o)=>{if(o.rankIndexes)for(const i of o.rankIndexes){const n=Y(t,i.name),s=i.sortBy.map((T,d)=>M(d)),f=s.map(T=>e`${e.identifier(T)} BLOB`),$=f.length>0?e`, ${e.join(f,e`, `)}`:e``;a(r,e`CREATE TABLE IF NOT EXISTS ${e.identifier(n)} (${e.identifier("__id__")} TEXT PRIMARY KEY, ${e.identifier("__partition__")} TEXT NOT NULL${$})`);const m=[e`${e.identifier("__partition__")} ASC`];for(const[T,d]of s.entries()){const A=i.sortBy[T]?.direction;m.push(e`${e.identifier(d)} ${e.raw(A==="desc"?"DESC":"ASC")}`)}m.push(e`${e.identifier("__id__")} ASC`);const L=`${t}__rank_${i.name}__btree`;a(r,_(L,n,e.join(m,e`, `),!1))}},te=(r,t,o={})=>{o.schemaSnapshot!==void 0&&k(r,o.schemaSnapshot.hash,o.schemaSnapshot.json),u(r);for(const[i,n]of Object.entries(t.tables))n.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(U)} TEXT NOT NULL
|
|
5
|
+
)`),y(r,i,n),j(r,i,n),q(r,i,n),G(r,i,n),P(r,i,n));o.cdc&&(l(r),h(r),R(r)),O(r),C(r),F(r)};export{te as runShardMigrations};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{sql as e}from"drizzle-orm";import{runDrizzle as $}from"./runDrizzle-C3n5gJsk.mjs";import{N as r}from"./do-sql-
|
|
1
|
+
import{sql as e}from"drizzle-orm";import{runDrizzle as $}from"./runDrizzle-C3n5gJsk.mjs";import{N as r}from"./do-sql-DKSFK627.mjs";const E=(d,i,s,o)=>{const f=s-(i.after??0),t=[e`${r(i.field)} IS NOT NULL`,e`${r(i.field)} < ${f}`];i.softDeleteField!==void 0&&t.push(e`${r(i.softDeleteField)} IS NULL`);const a=e`SELECT id FROM ${e.identifier(i.table)} WHERE ${e.join(t,e` AND `)} LIMIT ${e.raw(String(Math.max(0,Math.floor(o))+1))}`,l=$(d,a).toArray(),n=l.length>o,m=l.slice(0,o).map(p=>p.id);return{hasMore:n,ids:m}};export{E as selectExpiredIds};
|
package/dist/packem_shared/{selectShapeMemberIds-WzxOG62k.mjs → selectShapeMemberIds-Bkkug6vU.mjs}
RENAMED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{sql as e}from"drizzle-orm";import{runDrizzle as m}from"./runDrizzle-C3n5gJsk.mjs";import{a as c,E as a,N as u}from"./do-sql-
|
|
1
|
+
import{sql as e}from"drizzle-orm";import{runDrizzle as m}from"./runDrizzle-C3n5gJsk.mjs";import{a as c,E as a,N as u}from"./do-sql-DKSFK627.mjs";import{sqliteInList as h}from"./param-CYxL68V-.mjs";import{compileWhereSql as S}from"./compileWhereSql-B3hq_v98.mjs";import{serializeSqlValue as E}from"./serializeSqlValue-BR4UOWoP.mjs";const $={fieldRef:u,serialize:E},R=i=>{if(i.length!==0)return h(e`${e.identifier("id")}`,i,!1)},p=(i,o)=>{const r=[];o&&r.push(o);const t=S(i,$);return t&&r.push(t),r.length===0?e``:e` WHERE ${e.join(r,e` AND `)}`},L=(i,o,r)=>{const t=p(r,void 0),f=m(i,e`SELECT id, _creationTime, ${e.identifier(c)} FROM ${e.identifier(o)}${t}`).toArray(),n=[];for(const s of f){const d=a(s),{id:l}=s;d!==void 0&&typeof l=="string"&&n.push({doc:d,id:l})}return n},M=(i,o,r,t)=>{if(t.length===0)return new Set;const f=p(r,R(t)),n=m(i,e`SELECT id FROM ${e.identifier(o)}${f}`).toArray();return new Set(n.map(s=>s.id))};export{M as selectShapeMemberIds,L as selectShapeRows};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{stableStringify as r}from"./stableStringify-BjLh4gvA.mjs";import{a as e}from"./wire-codec-
|
|
1
|
+
import{stableStringify as r}from"./stableStringify-BjLh4gvA.mjs";import{a as e}from"./wire-codec-Dh0j-GnY.mjs";const i=t=>r(e(t));export{i as stableWireKey};
|