@lunora/shard-engine 1.0.0-alpha.125 → 1.0.0-alpha.127
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 +1 -0
- package/dist/index.d.ts +1 -0
- package/dist/index.mjs +1 -1
- package/dist/packem_shared/DEFAULT_MAX_RELATION_KEYS-Bk8B9GIQ.mjs +1 -0
- package/dist/packem_shared/{NotUniqueError-Btdx6-eQ.mjs → NotUniqueError-BXDZxdAt.mjs} +1 -1
- package/dist/packem_shared/{defineEngineContractSuite-DTLpGhSW.mjs → defineEngineContractSuite-dlOQgRU1.mjs} +1 -1
- package/package.json +2 -2
- package/dist/packem_shared/DEFAULT_MAX_RELATION_KEYS-BfhdOkA2.mjs +0 -1
|
@@ -1 +1 @@
|
|
|
1
|
-
import{defineEngineContractSuite as t}from"../packem_shared/defineEngineContractSuite-
|
|
1
|
+
import{defineEngineContractSuite as t}from"../packem_shared/defineEngineContractSuite-dlOQgRU1.mjs";export{t as defineEngineContractSuite};
|
package/dist/index.d.mts
CHANGED
|
@@ -1091,6 +1091,7 @@ interface ScheduleOutboxEnvelope {
|
|
|
1091
1091
|
when: number;
|
|
1092
1092
|
}
|
|
1093
1093
|
interface ScheduleOutbox {
|
|
1094
|
+
admit: (target: string) => number | undefined;
|
|
1094
1095
|
forget: (id: string) => void;
|
|
1095
1096
|
record: (id: string, envelope: ScheduleOutboxEnvelope) => void;
|
|
1096
1097
|
wake: () => void;
|
package/dist/index.d.ts
CHANGED
|
@@ -1091,6 +1091,7 @@ interface ScheduleOutboxEnvelope {
|
|
|
1091
1091
|
when: number;
|
|
1092
1092
|
}
|
|
1093
1093
|
interface ScheduleOutbox {
|
|
1094
|
+
admit: (target: string) => number | undefined;
|
|
1094
1095
|
forget: (id: string) => void;
|
|
1095
1096
|
record: (id: string, envelope: ScheduleOutboxEnvelope) => void;
|
|
1096
1097
|
wake: () => void;
|
package/dist/index.mjs
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{exportShardRows as o,importShardRows as a,parseExportShardArgs as t,parseImportShardArgs as s,selectExportTables as i,validateImportRow as l}from"./packem_shared/exportShardRows-CTDgQEF8.mjs";import{AGGREGATE_SQL_FUNCTION as d,aggregateSqlFunction as c,matchesStaticWhere as m,normalizeCountArgument as p,throwingScheduler as S}from"./packem_shared/AGGREGATE_SQL_FUNCTION-BMtvQHac.mjs";import{aggregateTableName as f,coerceAggregateNumber as h,encodeAggregateKey as x,foldAggregateTally as E,readAggregateValue as T}from"./packem_shared/aggregateTableName-DbAttCNH.mjs";import{CountRlsUnsupportedError as C,mergeWhere as A,planAggregateLookup as g,selectIndexForAggregate as _,selectIndexForCount as I,selectIndexForGroupBy as b}from"./packem_shared/CountRlsUnsupportedError-BvsDqfO2.mjs";import{AUDIT_LOG_TABLE as D,appendAuditEntry as P,ensureAuditTable as O,readAuditLog as F}from"./packem_shared/AUDIT_LOG_TABLE-CZNxCRLv.mjs";import{NotUniqueError as y,assertNoExplicitUndefined as N,assertValidClientId as k,createShardCtxDb as B,normalizeIdStructurally as U,stripReservedPatchFields as G}from"./packem_shared/NotUniqueError-Btdx6-eQ.mjs";import{backfillAggregateIndexes as q,backfillRankIndexes as v,backfillSearchIndexes as K,backfillSearchIndexesForTable as W}from"./packem_shared/backfillAggregateIndexes-CJrtolQ9.mjs";import{CDC_LOG_TABLE as H,CDC_LOG_TABLE_SEQ_INDEX as V,CDC_META_TABLE as z,appendCdcChange as Q,applyCdcChanges as Y,bumpCdcEpoch as j,cdcCanVouchFor as J,cdcForkedError as Z,cdcSeqLeavingRows as $,cdcTouchesTables as ee,cdcTrimmedError as re,compactCdcDocs as oe,cursorBelowRetainedFloor as ae,migrateCdcLog as te,migrateCdcMeta as se,minCdcReplayableSeq as ie,minCdcSeq as le,readCdcChangeKeys as ne,readCdcChanges as de,readCdcCursor as ce,readCdcEpoch as me,trimCdcChanges as pe}from"./packem_shared/CDC_LOG_TABLE-BPEzVAil.mjs";import{archiveCdcSegment as ue,cdcArchiveRewound as fe,readArchivedCdcChanges as he,readCdcArchivedThrough as xe,writeCdcArchivedThrough as Ee}from"./packem_shared/archiveCdcSegment-BON69Nug.mjs";import{CLIENT_WATERMARK_TABLE as Re,advanceClientWatermark as Ce,migrateClientWatermark as Ae,readClientWatermark as ge}from"./packem_shared/CLIENT_WATERMARK_TABLE-vLjfNhBR.mjs";import{COMMIT_SEQ_FIELD as Ie,COMMIT_SEQ_TABLE as be,allocateCommitSeq as Le,migrateCommitSeq as De,readCommitSeq as Pe}from"./packem_shared/COMMIT_SEQ_FIELD-BY_vc9bw.mjs";import{clearCompanionSignatures as Fe}from"./packem_shared/clearCompanionSignatures-C2CSfkeQ.mjs";import{createCompanionSync as ye}from"./packem_shared/createCompanionSync-B7dV2y4L.mjs";import{GLOBAL_SHAPE_SNAPSHOT_TABLE as ke,deleteGlobalShapeSnapshot as Be,deleteGlobalShapeSnapshotsForConnection as Ue,migrateGlobalShapeSnapshot as Ge,readGlobalShapeSnapshot as we,writeGlobalShapeSnapshot as qe}from"./packem_shared/GLOBAL_SHAPE_SNAPSHOT_TABLE-pMxZ-obU.mjs";import{IDEMPOTENCY_TABLE as Ke,migrateIdempotency as We,readIdempotent as Xe,trimIdempotent as He,writeIdempotent as Ve}from"./packem_shared/IDEMPOTENCY_TABLE-AOJCuq5U.mjs";import{clearMemoryTables as Qe,isMemoryTable as Ye,memoryTableNames as je}from"./packem_shared/clearMemoryTables-CogAvVHR.mjs";import{computeRankPage as Ze,resolveRankSeekTuple as $e}from"./packem_shared/computeRankPage-CFeFkZ_k.mjs";import{SCHEDULE_OUTBOX_TABLE as rr,deferScheduleOutbox as or,forgetScheduleOutbox as ar,migrateScheduleOutbox as tr,parkScheduleOutbox as sr,probeScheduleOutbox as ir,readDueScheduleOutbox as lr,recordScheduleOutbox as nr,trimScheduleOutbox as dr}from"./packem_shared/SCHEDULE_OUTBOX_TABLE-CgLvGxpY.mjs";import{S as mr,m as pr,r as Sr,w as ur}from"./packem_shared/ctx-db-search-state-DVCp4JQf.mjs";import{SHAPE_POKE_CURSOR_TABLE as hr,deleteShapePokeCursor as xr,deleteShapePokeCursorsForConnection as Er,migrateShapePokeCursor as Tr,minShapePokeCursor as Rr,readShapePokeCursor as Cr,writeShapePokeCursor as Ar,writeShapePokeCursors as gr}from"./packem_shared/SHAPE_POKE_CURSOR_TABLE-cn0stGAL.mjs";import{selectShapeMembers as Ir,selectShapeRows as br}from"./packem_shared/selectShapeMembers-CU8Kl2Bq.mjs";import{DATA_MIGRATION_STATE_TABLE as Dr,readMigrationStatus as Pr,runDataMigration as Or}from"./packem_shared/DATA_MIGRATION_STATE_TABLE-CqPrNKql.mjs";import{SCAN_DEP as Mr,createDependencyTracker as yr,depKey as Nr,tableFromDepKey as kr}from"./packem_shared/SCAN_DEP-D7qE3iUe.mjs";import{runDrizzle as Ur,runSql as Gr}from"./packem_shared/runDrizzle-Du5HLitO.mjs";import{A as qr,a as vr,b as Kr,D as Wr,c as Xr,d as Hr,g as Vr,i as zr,j as Qr,e as Yr,q as jr,f as Jr,r as Zr,t as $r,h as eo}from"./packem_shared/do-sql-Cg3zXJpF.mjs";import{WORKERD_SQLITE_LIMITS as oo,param as ao,renderSql as to,sqliteInList as so,unionAll as io}from"./packem_shared/WORKERD_SQLITE_LIMITS-DBH23L_S.mjs";import{appendStreamChunk as no,claimStreamRun as co,deleteStreamRun as mo,finishStreamRun as po,migrateDurableStreams as So,readStreamChunks as uo,readStreamRun as fo,trimStreamRuns as ho}from"./packem_shared/appendStreamChunk-7ZyAZGg_.mjs";import{DurableStreamRunner as Eo,MAX_DURABLE_STREAM_BYTES as To,MAX_DURABLE_STREAM_CHUNKS as Ro,decideDurableAttach as Co}from"./packem_shared/DurableStreamRunner-y2CRbfuZ.mjs";import{envOptionalPositiveInt as go,envPositiveInt as _o}from"./packem_shared/envOptionalPositiveInt-D2pY-c64.mjs";import{diffExternalSource as bo}from"./packem_shared/diffExternalSource-DgDJhslq.mjs";import{liftSourceId as Do,normalizeSourceDocument as Po,normalizeSourceValue as Oo}from"./packem_shared/liftSourceId-CA3ENhXj.mjs";import{materializeExternalRows as Mo,materializeExternalRowsIncremental as yo,readExternalSourceBaseline as No,runExternalSourceTick as ko}from"./packem_shared/materializeExternalRows-Cx6_A2W3.mjs";import{isSoftDeleted as Uo,isSourceDue as Go,pullExternalSourceIncrementalTick as wo,pullExternalSourceTick as qo}from"./packem_shared/isSoftDeleted-BTGu2iBl.mjs";import{f as Ko,a as Wo,b as Xo,c as Ho,d as Vo,g as zo}from"./packem_shared/fts-companion-pUdD6kF-.mjs";import{GEO_DEFAULT_PRECISION as Yo,boundingBoxCenter as jo,boundingBoxGeohashes as Jo,coveringGeohashes as Zo,encodeGeohash as $o,haversineMeters as ea,pointInBoundingBox as ra}from"./packem_shared/GEO_DEFAULT_PRECISION-CqpQZ-J_.mjs";import{default as aa}from"./packem_shared/GlobalPollTick-BNK4o-XT.mjs";import{ADMIN_FUNCTIONS as sa,ADMIN_FUNCTION_PREFIX as ia,DEFAULT_FANOUT_TOPIC_LIMIT as la,FLAGS_FUNCTION_PREFIX as na,MAX_PAGE_SIZE as da,RELATION_FUNCTION_PREFIX as ca,createFanoutCounters as ma,createGlobalPollCounters as pa,createShapeProbeCounters as Sa,facetColumn as ua,findStorageReferences as fa,isVacuousFilterClause as ha,listTables as xa,readTablePage as Ea,recordFanoutPass as Ta,recordGlobalPollPass as Ra,recordShapeProbePass as Ca,selectMatchingIds as Aa,summarizeFanoutTopics as ga,summarizeSubscriptions as _a}from"./packem_shared/ADMIN_FUNCTIONS-Bsvi2ytY.mjs";import{MAIL_RETENTION as ba,MAIL_TABLE as La,clearCapturedMail as Da,ensureMailTable as Pa,readCapturedMail as Oa,recordCapturedMail as Fa}from"./packem_shared/MAIL_RETENTION-BxAGL3hK.mjs";import{NotFoundError as ya}from"./packem_shared/NotFoundError-BhF7FeFr.mjs";import{assertPatchAllowed as ka,operatorFields as Ba,patchDependsOnRow as Ua,readPatchField as Ga,resolvePatch as wa}from"./packem_shared/assertPatchAllowed-BJ_2LgkQ.mjs";import{armRestore as va,readBookmark as Ka}from"./packem_shared/armRestore-Bu1_8SUa.mjs";import{CURSOR_PREFIX as Xa,applySelect as Ha,buildSeekBeforeWhere as Va,buildSeekWhere as za,decodeCursor as Qa,encodeCursor as Ya,equalityPinnedFields as ja,normalizeOrderKeys as Ja,nullsFirstOf as Za,nullsOrderSuffix as $a,softDeleteScope as et,tiebreakDirectionFor as rt,uniqueIndexFields as ot}from"./packem_shared/CURSOR_PREFIX-BztyXqNP.mjs";import{QUEUE_TABLE as tt,clearQueueMessages as st,isLossyBody as it,readQueueMessageById as lt,readQueueMessages as nt,recordQueueMessages as dt}from"./packem_shared/QUEUE_TABLE-DKANxmEZ.mjs";import{RANK_TIEBREAK as mt,encodePartitionKey as pt,matchesRankStaticWhere as St,rankKeyFromDoc as ut,rankPivotConditionSql as ft,rankTableName as ht,resolveRankPartition as xt,sortColumnName as Et}from"./packem_shared/RANK_TIEBREAK-BKugKf70.mjs";import{ReactiveCache as Rt,reactiveCacheKey as Ct}from"./packem_shared/ReactiveCache-Bdzsahf3.mjs";import{REACTOR_STATE_TABLE as gt,listReactorStates as _t,migrateReactorState as It,reactorNeedsRun as bt,readReactorState as Lt,writeReactorState as Dt}from"./packem_shared/REACTOR_STATE_TABLE-B8IehLv8.mjs";import{UNVOUCHABLE_DEP as Ot,createReadFootprint as Ft,markUnvouchableReads as Mt}from"./packem_shared/UNVOUCHABLE_DEP-C68htACn.mjs";import{buildIndexRange as Nt,indexKeysForRow as kt,keysTouchRanges as Bt}from"./packem_shared/buildIndexRange-6nIZDf4m.mjs";import{isPushableWhere as Gt,whereFilter as wt,whereOfFilter as qt}from"./packem_shared/isPushableWhere-BeYAOjUb.mjs";import{RELATED_DEFAULT_LIMIT as Kt,RELATED_DEPTH_DECAY as Wt,RELATED_MAX_DEPTH as Xt,RELATED_MAX_LIMIT as Ht,deriveRelationEdges as Vt,findRelated as zt}from"./packem_shared/RELATED_DEFAULT_LIMIT-Me5elP-K.mjs";import{DEFAULT_MAX_RELATION_KEYS as Yt,assertFlatPredicate as jt,assertShapeShardable as Jt,composeReadPredicate as Zt,containsRelationPredicate as $t,isRelationPredicate as es,resolveRelationPredicates as rs}from"./packem_shared/DEFAULT_MAX_RELATION_KEYS-BfhdOkA2.mjs";import{describeRelationWrites as as}from"./packem_shared/describeRelationWrites-omar6-u9.mjs";import{applyOnDelete as ss,distinctValues as is,fanOutScalarCounts as ls,relationHooks as ns,resolveWith as ds,runRowValidators as cs}from"./packem_shared/applyOnDelete-CGVYKtaW.mjs";import{DEFAULT_PROMOTION_THRESHOLDS as ps,clampPromotionThresholds as Ss,nextPromotionState as us,relayCountFor as fs,shapeRoutingKey as hs}from"./packem_shared/DEFAULT_PROMOTION_THRESHOLDS-DEURXMvk.mjs";import{DEFAULT_MAX_RELAYS as Es,OwnerRelay as Ts,RelayMember as Rs,createRelayLink as Cs}from"./packem_shared/DEFAULT_MAX_RELAYS-BqSpObEl.mjs";import{createReplicaLink as gs,gateReplicaDispatch as _s,handleReplicaControl as Is}from"./packem_shared/createReplicaLink-B9F5PAQ0.mjs";import{buildReprojectionMigration as Ls,countLegacyRows as Ds,reprojectableFields as Ps,reprojectionTables as Os}from"./packem_shared/buildReprojectionMigration-CRS4SNgc.mjs";import{RLS_UNWRAP_SYMBOL as Ms,RlsRequiredError as ys,guardWriter as Ns}from"./packem_shared/RLS_UNWRAP_SYMBOL-qYcAxjuk.mjs";import{SCHEMA_HISTORY_MAX_VERSIONS as Bs,readSchemaHistory as Us,readSchemaVersion as Gs,recordSchemaVersion as ws}from"./packem_shared/SCHEMA_HISTORY_MAX_VERSIONS-BMcUIqBY.mjs";import{serializeSqlValue as vs}from"./packem_shared/serializeSqlValue-BbZ5hKM7.mjs";import{buildSettings as Ws,isDevEnvironment as Xs,readDeployInfo as Hs}from"./packem_shared/buildSettings-BRkZd6_E.mjs";import{buildShapeDiff as zs}from"./packem_shared/buildShapeDiff-C3hPtSKO.mjs";import{ShapeDiffCache as Ys,createShapeDiffCache as js,globalShapeReadKey as Js}from"./packem_shared/ShapeDiffCache-Br3kxusw.mjs";import{buildPokeFrames as $s,diffGlobalMembership as ei,encodeRowsPatch as ri,projectColumns as oi}from"./packem_shared/buildPokeFrames-CDOP-XYp.mjs";import{ShardRunner as ti}from"./packem_shared/ShardRunner-CrveaPId.mjs";import{stubByName as ii}from"./packem_shared/stubByName-C_P73AOx.mjs";import{runSocketPool as ni}from"./packem_shared/runSocketPool-CZJ2X9cF.mjs";import{MAX_SQL_ROWS as ci,assertReadonly as mi,lintReadonlySql as pi,runReadonlySql as Si}from"./packem_shared/MAX_SQL_ROWS-Dh_Ty0Zo.mjs";import{BIGINT_KEY_DIGITS as fi,bigintSqlKey as hi,decodeBigintSqlKey as xi,decodeFloat64SqlKey as Ei,float64SqlKey as Ti}from"./packem_shared/BIGINT_KEY_DIGITS-C9a7Ix7k.mjs";import{awaitWsDrain as Ci,subscriptionFrames as Ai,subscriptionListDeltas as gi,trySendFrame as _i}from"./packem_shared/awaitWsDrain-D4E7Oiwo.mjs";import{mergeChangedKeys as bi,recordChangedKeys as Li,writeTouchesMemo as Di}from"./packem_shared/mergeChangedKeys-DH9RAARR.mjs";import{createSystemReader as Oi}from"./packem_shared/createSystemReader-DcDLFfC-.mjs";import{ConflictError as Mi}from"./packem_shared/ConflictError-C8GtJmjS.mjs";import{DEFAULT_TRANSACTION_LIMITS as Ni,TransactionHeadroomTracker as ki}from"./packem_shared/DEFAULT_TRANSACTION_LIMITS-DiR5z5EX.mjs";import{hasTrigger as Ui,runTriggers as Gi}from"./packem_shared/hasTrigger-CjlwI4le.mjs";import{selectExpiredIds as qi}from"./packem_shared/selectExpiredIds-CilDdUr2.mjs";import{VECTOR_BACKFILL_MAX_PAGES as Ki,backfillVectorIndexes as Wi}from"./packem_shared/VECTOR_BACKFILL_MAX_PAGES-D9DeCfM2.mjs";import{c as Hi,s as Vi}from"./packem_shared/where-sql-Dn9trjRu.mjs";import{RELATION_EXISTS_KEY as Qi}from"./packem_shared/RELATION_EXISTS_KEY-wxgj6rSL.mjs";import{REPROJECTION_MIGRATION_PREFIX as ji,reprojectionMigrationId as Ji}from"./packem_shared/REPROJECTION_MIGRATION_PREFIX-Czcb6_mO.mjs";import{isInternalTableName as $i}from"./packem_shared/isInternalTableName-BoljO2tP.mjs";import{quoteIdentifier as rl}from"./packem_shared/quoteIdentifier-CObIFRhb.mjs";import{runShardMigrations as al}from"./packem_shared/runShardMigrations-eqHNBW6S.mjs";import{stableStringify as sl}from"./packem_shared/stableStringify-DibjylKD.mjs";import{stableWireKey as ll}from"./packem_shared/stableWireKey-Bdh5JSdg.mjs";export{sa as ADMIN_FUNCTIONS,ia as ADMIN_FUNCTION_PREFIX,d as AGGREGATE_SQL_FUNCTION,qr as AGG_COUNT,vr as AGG_KEY,Kr as AGG_VALUE,D as AUDIT_LOG_TABLE,fi as BIGINT_KEY_DIGITS,H as CDC_LOG_TABLE,V as CDC_LOG_TABLE_SEQ_INDEX,z as CDC_META_TABLE,Re as CLIENT_WATERMARK_TABLE,Ie as COMMIT_SEQ_FIELD,be as COMMIT_SEQ_TABLE,Xa as CURSOR_PREFIX,Mi as ConflictError,C as CountRlsUnsupportedError,Dr as DATA_MIGRATION_STATE_TABLE,la as DEFAULT_FANOUT_TOPIC_LIMIT,Yt as DEFAULT_MAX_RELATION_KEYS,Es as DEFAULT_MAX_RELAYS,ps as DEFAULT_PROMOTION_THRESHOLDS,Ni as DEFAULT_TRANSACTION_LIMITS,Wr as DOC_COLUMN,Eo as DurableStreamRunner,na as FLAGS_FUNCTION_PREFIX,Yo as GEO_DEFAULT_PRECISION,ke as GLOBAL_SHAPE_SNAPSHOT_TABLE,aa as GlobalPollTick,Ke as IDEMPOTENCY_TABLE,ba as MAIL_RETENTION,La as MAIL_TABLE,To as MAX_DURABLE_STREAM_BYTES,Ro as MAX_DURABLE_STREAM_CHUNKS,da as MAX_PAGE_SIZE,ci as MAX_SQL_ROWS,ya as NotFoundError,y as NotUniqueError,Ts as OwnerRelay,tt as QUEUE_TABLE,mt as RANK_TIEBREAK,gt as REACTOR_STATE_TABLE,Kt as RELATED_DEFAULT_LIMIT,Wt as RELATED_DEPTH_DECAY,Xt as RELATED_MAX_DEPTH,Ht as RELATED_MAX_LIMIT,Qi as RELATION_EXISTS_KEY,ca as RELATION_FUNCTION_PREFIX,ji as REPROJECTION_MIGRATION_PREFIX,Ms as RLS_UNWRAP_SYMBOL,Rt as ReactiveCache,Rs as RelayMember,ys as RlsRequiredError,Mr as SCAN_DEP,rr as SCHEDULE_OUTBOX_TABLE,Bs as SCHEMA_HISTORY_MAX_VERSIONS,mr as SEARCH_STATE_TABLE,hr as SHAPE_POKE_CURSOR_TABLE,Ys as ShapeDiffCache,ti as ShardRunner,ki as TransactionHeadroomTracker,Ot as UNVOUCHABLE_DEP,Ki as VECTOR_BACKFILL_MAX_PAGES,oo as WORKERD_SQLITE_LIMITS,Ce as advanceClientWatermark,Xr as aggUpsertSql,c as aggregateSqlFunction,f as aggregateTableName,Le as allocateCommitSeq,P as appendAuditEntry,Q as appendCdcChange,no as appendStreamChunk,Y as applyCdcChanges,ss as applyOnDelete,Ha as applySelect,ue as archiveCdcSegment,va as armRestore,jt as assertFlatPredicate,N as assertNoExplicitUndefined,ka as assertPatchAllowed,mi as assertReadonly,Jt as assertShapeShardable,k as assertValidClientId,Ci as awaitWsDrain,q as backfillAggregateIndexes,v as backfillRankIndexes,K as backfillSearchIndexes,W as backfillSearchIndexesForTable,Wi as backfillVectorIndexes,hi as bigintSqlKey,jo as boundingBoxCenter,Jo as boundingBoxGeohashes,Nt as buildIndexRange,$s as buildPokeFrames,Ls as buildReprojectionMigration,Va as buildSeekBeforeWhere,za as buildSeekWhere,Ws as buildSettings,zs as buildShapeDiff,j as bumpCdcEpoch,fe as cdcArchiveRewound,J as cdcCanVouchFor,Z as cdcForkedError,$ as cdcSeqLeavingRows,ee as cdcTouchesTables,re as cdcTrimmedError,co as claimStreamRun,Ss as clampPromotionThresholds,Da as clearCapturedMail,Fe as clearCompanionSignatures,Qe as clearMemoryTables,st as clearQueueMessages,h as coerceAggregateNumber,oe as compactCdcDocs,Hi as compileWhereSql,Zt as composeReadPredicate,Ze as computeRankPage,$t as containsRelationPredicate,Ds as countLegacyRows,Zo as coveringGeohashes,ye as createCompanionSync,yr as createDependencyTracker,ma as createFanoutCounters,pa as createGlobalPollCounters,Hr as createIndexSql,Ft as createReadFootprint,Cs as createRelayLink,gs as createReplicaLink,js as createShapeDiffCache,Sa as createShapeProbeCounters,B as createShardCtxDb,Oi as createSystemReader,ae as cursorBelowRetainedFloor,Co as decideDurableAttach,xi as decodeBigintSqlKey,Qa as decodeCursor,Ei as decodeFloat64SqlKey,or as deferScheduleOutbox,Be as deleteGlobalShapeSnapshot,Ue as deleteGlobalShapeSnapshotsForConnection,xr as deleteShapePokeCursor,Er as deleteShapePokeCursorsForConnection,mo as deleteStreamRun,Nr as depKey,Vt as deriveRelationEdges,as as describeRelationWrites,bo as diffExternalSource,ei as diffGlobalMembership,is as distinctValues,x as encodeAggregateKey,Ya as encodeCursor,$o as encodeGeohash,pt as encodePartitionKey,ri as encodeRowsPatch,O as ensureAuditTable,Pa as ensureMailTable,go as envOptionalPositiveInt,_o as envPositiveInt,ja as equalityPinnedFields,o as exportShardRows,ua as facetColumn,ls as fanOutScalarCounts,zt as findRelated,fa as findStorageReferences,po as finishStreamRun,Ti as float64SqlKey,E as foldAggregateTally,ar as forgetScheduleOutbox,Ko as ftsCompanionDdl,Wo as ftsPurgeDocument,Xo as ftsRowidMapName,Ho as ftsUnmappedPage,Vo as ftsWriteDocument,_s as gateReplicaDispatch,Vr as geoTableName,Js as globalShapeReadKey,zo as groupUnmappedRows,Ns as guardWriter,Is as handleReplicaControl,Ui as hasTrigger,ea as haversineMeters,a as importShardRows,kt as indexKeysForRow,Xs as isDevEnvironment,zr as isFtsAvailable,$i as isInternalTableName,it as isLossyBody,Ye as isMemoryTable,Gt as isPushableWhere,es as isRelationPredicate,Uo as isSoftDeleted,Go as isSourceDue,ha as isVacuousFilterClause,Qr as jsonPath,Yr as jsonPathSql,Bt as keysTouchRanges,Do as liftSourceId,pi as lintReadonlySql,_t as listReactorStates,xa as listTables,Mt as markUnvouchableReads,St as matchesRankStaticWhere,m as matchesStaticWhere,Mo as materializeExternalRows,yo as materializeExternalRowsIncremental,je as memoryTableNames,bi as mergeChangedKeys,A as mergeWhere,te as migrateCdcLog,se as migrateCdcMeta,Ae as migrateClientWatermark,De as migrateCommitSeq,So as migrateDurableStreams,Ge as migrateGlobalShapeSnapshot,We as migrateIdempotency,It as migrateReactorState,tr as migrateScheduleOutbox,pr as migrateSearchState,Tr as migrateShapePokeCursor,ie as minCdcReplayableSeq,le as minCdcSeq,Rr as minShapePokeCursor,us as nextPromotionState,p as normalizeCountArgument,U as normalizeIdStructurally,Ja as normalizeOrderKeys,Po as normalizeSourceDocument,Oo as normalizeSourceValue,Za as nullsFirstOf,$a as nullsOrderSuffix,Ba as operatorFields,ao as param,sr as parkScheduleOutbox,t as parseExportShardArgs,s as parseImportShardArgs,Ua as patchDependsOnRow,g as planAggregateLookup,ra as pointInBoundingBox,ir as probeScheduleOutbox,oi as projectColumns,wo as pullExternalSourceIncrementalTick,qo as pullExternalSourceTick,jr as qualifiedJsonPath,Jr as qualifiedJsonPathSql,rl as quoteIdentifier,ut as rankKeyFromDoc,ft as rankPivotConditionSql,ht as rankTableName,Ct as reactiveCacheKey,bt as reactorNeedsRun,T as readAggregateValue,he as readArchivedCdcChanges,F as readAuditLog,Ka as readBookmark,Oa as readCapturedMail,xe as readCdcArchivedThrough,ne as readCdcChangeKeys,de as readCdcChanges,ce as readCdcCursor,me as readCdcEpoch,ge as readClientWatermark,Pe as readCommitSeq,Hs as readDeployInfo,lr as readDueScheduleOutbox,No as readExternalSourceBaseline,we as readGlobalShapeSnapshot,Xe as readIdempotent,Pr as readMigrationStatus,Ga as readPatchField,lt as readQueueMessageById,nt as readQueueMessages,Lt as readReactorState,Us as readSchemaHistory,Gs as readSchemaVersion,Sr as readSearchBackfillState,Cr as readShapePokeCursor,uo as readStreamChunks,fo as readStreamRun,Ea as readTablePage,Fa as recordCapturedMail,Li as recordChangedKeys,Ta as recordFanoutPass,Ra as recordGlobalPollPass,dt as recordQueueMessages,nr as recordScheduleOutbox,ws as recordSchemaVersion,Ca as recordShapeProbePass,ns as relationHooks,fs as relayCountFor,to as renderSql,Ps as reprojectableFields,Ji as reprojectionMigrationId,Os as reprojectionTables,wa as resolvePatch,xt as resolveRankPartition,$e as resolveRankSeekTuple,rs as resolveRelationPredicates,ds as resolveWith,Zr as rowToDocument,Or as runDataMigration,Ur as runDrizzle,ko as runExternalSourceTick,Si as runReadonlySql,cs as runRowValidators,al as runShardMigrations,ni as runSocketPool,Gr as runSql,Gi as runTriggers,qi as selectExpiredIds,i as selectExportTables,_ as selectIndexForAggregate,I as selectIndexForCount,b as selectIndexForGroupBy,Aa as selectMatchingIds,Ir as selectShapeMembers,br as selectShapeRows,vs as serializeSqlValue,Vi as serverInList,hs as shapeRoutingKey,et as softDeleteScope,Et as sortColumnName,so as sqliteInList,sl as stableStringify,ll as stableWireKey,G as stripReservedPatchFields,ii as stubByName,Ai as subscriptionFrames,gi as subscriptionListDeltas,ga as summarizeFanoutTopics,_a as summarizeSubscriptions,$r as tableColumns,kr as tableFromDepKey,S as throwingScheduler,rt as tiebreakDirectionFor,pe as trimCdcChanges,He as trimIdempotent,dr as trimScheduleOutbox,ho as trimStreamRuns,eo as tryRowToDocument,_i as trySendFrame,io as unionAll,ot as uniqueIndexFields,l as validateImportRow,wt as whereFilter,qt as whereOfFilter,Ee as writeCdcArchivedThrough,qe as writeGlobalShapeSnapshot,Ve as writeIdempotent,Dt as writeReactorState,ur as writeSearchBackfillState,Ar as writeShapePokeCursor,gr as writeShapePokeCursors,Di as writeTouchesMemo};
|
|
1
|
+
import{exportShardRows as o,importShardRows as a,parseExportShardArgs as t,parseImportShardArgs as s,selectExportTables as i,validateImportRow as l}from"./packem_shared/exportShardRows-CTDgQEF8.mjs";import{AGGREGATE_SQL_FUNCTION as d,aggregateSqlFunction as c,matchesStaticWhere as m,normalizeCountArgument as p,throwingScheduler as S}from"./packem_shared/AGGREGATE_SQL_FUNCTION-BMtvQHac.mjs";import{aggregateTableName as f,coerceAggregateNumber as h,encodeAggregateKey as x,foldAggregateTally as E,readAggregateValue as T}from"./packem_shared/aggregateTableName-DbAttCNH.mjs";import{CountRlsUnsupportedError as C,mergeWhere as A,planAggregateLookup as g,selectIndexForAggregate as _,selectIndexForCount as I,selectIndexForGroupBy as b}from"./packem_shared/CountRlsUnsupportedError-BvsDqfO2.mjs";import{AUDIT_LOG_TABLE as D,appendAuditEntry as P,ensureAuditTable as O,readAuditLog as F}from"./packem_shared/AUDIT_LOG_TABLE-CZNxCRLv.mjs";import{NotUniqueError as y,assertNoExplicitUndefined as N,assertValidClientId as k,createShardCtxDb as B,normalizeIdStructurally as U,stripReservedPatchFields as G}from"./packem_shared/NotUniqueError-BXDZxdAt.mjs";import{backfillAggregateIndexes as q,backfillRankIndexes as v,backfillSearchIndexes as K,backfillSearchIndexesForTable as W}from"./packem_shared/backfillAggregateIndexes-CJrtolQ9.mjs";import{CDC_LOG_TABLE as H,CDC_LOG_TABLE_SEQ_INDEX as V,CDC_META_TABLE as z,appendCdcChange as Q,applyCdcChanges as Y,bumpCdcEpoch as j,cdcCanVouchFor as J,cdcForkedError as Z,cdcSeqLeavingRows as $,cdcTouchesTables as ee,cdcTrimmedError as re,compactCdcDocs as oe,cursorBelowRetainedFloor as ae,migrateCdcLog as te,migrateCdcMeta as se,minCdcReplayableSeq as ie,minCdcSeq as le,readCdcChangeKeys as ne,readCdcChanges as de,readCdcCursor as ce,readCdcEpoch as me,trimCdcChanges as pe}from"./packem_shared/CDC_LOG_TABLE-BPEzVAil.mjs";import{archiveCdcSegment as ue,cdcArchiveRewound as fe,readArchivedCdcChanges as he,readCdcArchivedThrough as xe,writeCdcArchivedThrough as Ee}from"./packem_shared/archiveCdcSegment-BON69Nug.mjs";import{CLIENT_WATERMARK_TABLE as Re,advanceClientWatermark as Ce,migrateClientWatermark as Ae,readClientWatermark as ge}from"./packem_shared/CLIENT_WATERMARK_TABLE-vLjfNhBR.mjs";import{COMMIT_SEQ_FIELD as Ie,COMMIT_SEQ_TABLE as be,allocateCommitSeq as Le,migrateCommitSeq as De,readCommitSeq as Pe}from"./packem_shared/COMMIT_SEQ_FIELD-BY_vc9bw.mjs";import{clearCompanionSignatures as Fe}from"./packem_shared/clearCompanionSignatures-C2CSfkeQ.mjs";import{createCompanionSync as ye}from"./packem_shared/createCompanionSync-B7dV2y4L.mjs";import{GLOBAL_SHAPE_SNAPSHOT_TABLE as ke,deleteGlobalShapeSnapshot as Be,deleteGlobalShapeSnapshotsForConnection as Ue,migrateGlobalShapeSnapshot as Ge,readGlobalShapeSnapshot as we,writeGlobalShapeSnapshot as qe}from"./packem_shared/GLOBAL_SHAPE_SNAPSHOT_TABLE-pMxZ-obU.mjs";import{IDEMPOTENCY_TABLE as Ke,migrateIdempotency as We,readIdempotent as Xe,trimIdempotent as He,writeIdempotent as Ve}from"./packem_shared/IDEMPOTENCY_TABLE-AOJCuq5U.mjs";import{clearMemoryTables as Qe,isMemoryTable as Ye,memoryTableNames as je}from"./packem_shared/clearMemoryTables-CogAvVHR.mjs";import{computeRankPage as Ze,resolveRankSeekTuple as $e}from"./packem_shared/computeRankPage-CFeFkZ_k.mjs";import{SCHEDULE_OUTBOX_TABLE as rr,deferScheduleOutbox as or,forgetScheduleOutbox as ar,migrateScheduleOutbox as tr,parkScheduleOutbox as sr,probeScheduleOutbox as ir,readDueScheduleOutbox as lr,recordScheduleOutbox as nr,trimScheduleOutbox as dr}from"./packem_shared/SCHEDULE_OUTBOX_TABLE-CgLvGxpY.mjs";import{S as mr,m as pr,r as Sr,w as ur}from"./packem_shared/ctx-db-search-state-DVCp4JQf.mjs";import{SHAPE_POKE_CURSOR_TABLE as hr,deleteShapePokeCursor as xr,deleteShapePokeCursorsForConnection as Er,migrateShapePokeCursor as Tr,minShapePokeCursor as Rr,readShapePokeCursor as Cr,writeShapePokeCursor as Ar,writeShapePokeCursors as gr}from"./packem_shared/SHAPE_POKE_CURSOR_TABLE-cn0stGAL.mjs";import{selectShapeMembers as Ir,selectShapeRows as br}from"./packem_shared/selectShapeMembers-CU8Kl2Bq.mjs";import{DATA_MIGRATION_STATE_TABLE as Dr,readMigrationStatus as Pr,runDataMigration as Or}from"./packem_shared/DATA_MIGRATION_STATE_TABLE-CqPrNKql.mjs";import{SCAN_DEP as Mr,createDependencyTracker as yr,depKey as Nr,tableFromDepKey as kr}from"./packem_shared/SCAN_DEP-D7qE3iUe.mjs";import{runDrizzle as Ur,runSql as Gr}from"./packem_shared/runDrizzle-Du5HLitO.mjs";import{A as qr,a as vr,b as Kr,D as Wr,c as Xr,d as Hr,g as Vr,i as zr,j as Qr,e as Yr,q as jr,f as Jr,r as Zr,t as $r,h as eo}from"./packem_shared/do-sql-Cg3zXJpF.mjs";import{WORKERD_SQLITE_LIMITS as oo,param as ao,renderSql as to,sqliteInList as so,unionAll as io}from"./packem_shared/WORKERD_SQLITE_LIMITS-DBH23L_S.mjs";import{appendStreamChunk as no,claimStreamRun as co,deleteStreamRun as mo,finishStreamRun as po,migrateDurableStreams as So,readStreamChunks as uo,readStreamRun as fo,trimStreamRuns as ho}from"./packem_shared/appendStreamChunk-7ZyAZGg_.mjs";import{DurableStreamRunner as Eo,MAX_DURABLE_STREAM_BYTES as To,MAX_DURABLE_STREAM_CHUNKS as Ro,decideDurableAttach as Co}from"./packem_shared/DurableStreamRunner-y2CRbfuZ.mjs";import{envOptionalPositiveInt as go,envPositiveInt as _o}from"./packem_shared/envOptionalPositiveInt-D2pY-c64.mjs";import{diffExternalSource as bo}from"./packem_shared/diffExternalSource-DgDJhslq.mjs";import{liftSourceId as Do,normalizeSourceDocument as Po,normalizeSourceValue as Oo}from"./packem_shared/liftSourceId-CA3ENhXj.mjs";import{materializeExternalRows as Mo,materializeExternalRowsIncremental as yo,readExternalSourceBaseline as No,runExternalSourceTick as ko}from"./packem_shared/materializeExternalRows-Cx6_A2W3.mjs";import{isSoftDeleted as Uo,isSourceDue as Go,pullExternalSourceIncrementalTick as wo,pullExternalSourceTick as qo}from"./packem_shared/isSoftDeleted-BTGu2iBl.mjs";import{f as Ko,a as Wo,b as Xo,c as Ho,d as Vo,g as zo}from"./packem_shared/fts-companion-pUdD6kF-.mjs";import{GEO_DEFAULT_PRECISION as Yo,boundingBoxCenter as jo,boundingBoxGeohashes as Jo,coveringGeohashes as Zo,encodeGeohash as $o,haversineMeters as ea,pointInBoundingBox as ra}from"./packem_shared/GEO_DEFAULT_PRECISION-CqpQZ-J_.mjs";import{default as aa}from"./packem_shared/GlobalPollTick-BNK4o-XT.mjs";import{ADMIN_FUNCTIONS as sa,ADMIN_FUNCTION_PREFIX as ia,DEFAULT_FANOUT_TOPIC_LIMIT as la,FLAGS_FUNCTION_PREFIX as na,MAX_PAGE_SIZE as da,RELATION_FUNCTION_PREFIX as ca,createFanoutCounters as ma,createGlobalPollCounters as pa,createShapeProbeCounters as Sa,facetColumn as ua,findStorageReferences as fa,isVacuousFilterClause as ha,listTables as xa,readTablePage as Ea,recordFanoutPass as Ta,recordGlobalPollPass as Ra,recordShapeProbePass as Ca,selectMatchingIds as Aa,summarizeFanoutTopics as ga,summarizeSubscriptions as _a}from"./packem_shared/ADMIN_FUNCTIONS-Bsvi2ytY.mjs";import{MAIL_RETENTION as ba,MAIL_TABLE as La,clearCapturedMail as Da,ensureMailTable as Pa,readCapturedMail as Oa,recordCapturedMail as Fa}from"./packem_shared/MAIL_RETENTION-BxAGL3hK.mjs";import{NotFoundError as ya}from"./packem_shared/NotFoundError-BhF7FeFr.mjs";import{assertPatchAllowed as ka,operatorFields as Ba,patchDependsOnRow as Ua,readPatchField as Ga,resolvePatch as wa}from"./packem_shared/assertPatchAllowed-BJ_2LgkQ.mjs";import{armRestore as va,readBookmark as Ka}from"./packem_shared/armRestore-Bu1_8SUa.mjs";import{CURSOR_PREFIX as Xa,applySelect as Ha,buildSeekBeforeWhere as Va,buildSeekWhere as za,decodeCursor as Qa,encodeCursor as Ya,equalityPinnedFields as ja,normalizeOrderKeys as Ja,nullsFirstOf as Za,nullsOrderSuffix as $a,softDeleteScope as et,tiebreakDirectionFor as rt,uniqueIndexFields as ot}from"./packem_shared/CURSOR_PREFIX-BztyXqNP.mjs";import{QUEUE_TABLE as tt,clearQueueMessages as st,isLossyBody as it,readQueueMessageById as lt,readQueueMessages as nt,recordQueueMessages as dt}from"./packem_shared/QUEUE_TABLE-DKANxmEZ.mjs";import{RANK_TIEBREAK as mt,encodePartitionKey as pt,matchesRankStaticWhere as St,rankKeyFromDoc as ut,rankPivotConditionSql as ft,rankTableName as ht,resolveRankPartition as xt,sortColumnName as Et}from"./packem_shared/RANK_TIEBREAK-BKugKf70.mjs";import{ReactiveCache as Rt,reactiveCacheKey as Ct}from"./packem_shared/ReactiveCache-Bdzsahf3.mjs";import{REACTOR_STATE_TABLE as gt,listReactorStates as _t,migrateReactorState as It,reactorNeedsRun as bt,readReactorState as Lt,writeReactorState as Dt}from"./packem_shared/REACTOR_STATE_TABLE-B8IehLv8.mjs";import{UNVOUCHABLE_DEP as Ot,createReadFootprint as Ft,markUnvouchableReads as Mt}from"./packem_shared/UNVOUCHABLE_DEP-C68htACn.mjs";import{buildIndexRange as Nt,indexKeysForRow as kt,keysTouchRanges as Bt}from"./packem_shared/buildIndexRange-6nIZDf4m.mjs";import{isPushableWhere as Gt,whereFilter as wt,whereOfFilter as qt}from"./packem_shared/isPushableWhere-BeYAOjUb.mjs";import{RELATED_DEFAULT_LIMIT as Kt,RELATED_DEPTH_DECAY as Wt,RELATED_MAX_DEPTH as Xt,RELATED_MAX_LIMIT as Ht,deriveRelationEdges as Vt,findRelated as zt}from"./packem_shared/RELATED_DEFAULT_LIMIT-Me5elP-K.mjs";import{DEFAULT_MAX_RELATION_KEYS as Yt,assertFlatPredicate as jt,assertShapeShardable as Jt,composeReadPredicate as Zt,containsRelationPredicate as $t,isRelationPredicate as es,resolveRelationPredicates as rs}from"./packem_shared/DEFAULT_MAX_RELATION_KEYS-Bk8B9GIQ.mjs";import{describeRelationWrites as as}from"./packem_shared/describeRelationWrites-omar6-u9.mjs";import{applyOnDelete as ss,distinctValues as is,fanOutScalarCounts as ls,relationHooks as ns,resolveWith as ds,runRowValidators as cs}from"./packem_shared/applyOnDelete-CGVYKtaW.mjs";import{DEFAULT_PROMOTION_THRESHOLDS as ps,clampPromotionThresholds as Ss,nextPromotionState as us,relayCountFor as fs,shapeRoutingKey as hs}from"./packem_shared/DEFAULT_PROMOTION_THRESHOLDS-DEURXMvk.mjs";import{DEFAULT_MAX_RELAYS as Es,OwnerRelay as Ts,RelayMember as Rs,createRelayLink as Cs}from"./packem_shared/DEFAULT_MAX_RELAYS-BqSpObEl.mjs";import{createReplicaLink as gs,gateReplicaDispatch as _s,handleReplicaControl as Is}from"./packem_shared/createReplicaLink-B9F5PAQ0.mjs";import{buildReprojectionMigration as Ls,countLegacyRows as Ds,reprojectableFields as Ps,reprojectionTables as Os}from"./packem_shared/buildReprojectionMigration-CRS4SNgc.mjs";import{RLS_UNWRAP_SYMBOL as Ms,RlsRequiredError as ys,guardWriter as Ns}from"./packem_shared/RLS_UNWRAP_SYMBOL-qYcAxjuk.mjs";import{SCHEMA_HISTORY_MAX_VERSIONS as Bs,readSchemaHistory as Us,readSchemaVersion as Gs,recordSchemaVersion as ws}from"./packem_shared/SCHEMA_HISTORY_MAX_VERSIONS-BMcUIqBY.mjs";import{serializeSqlValue as vs}from"./packem_shared/serializeSqlValue-BbZ5hKM7.mjs";import{buildSettings as Ws,isDevEnvironment as Xs,readDeployInfo as Hs}from"./packem_shared/buildSettings-BRkZd6_E.mjs";import{buildShapeDiff as zs}from"./packem_shared/buildShapeDiff-C3hPtSKO.mjs";import{ShapeDiffCache as Ys,createShapeDiffCache as js,globalShapeReadKey as Js}from"./packem_shared/ShapeDiffCache-Br3kxusw.mjs";import{buildPokeFrames as $s,diffGlobalMembership as ei,encodeRowsPatch as ri,projectColumns as oi}from"./packem_shared/buildPokeFrames-CDOP-XYp.mjs";import{ShardRunner as ti}from"./packem_shared/ShardRunner-CrveaPId.mjs";import{stubByName as ii}from"./packem_shared/stubByName-C_P73AOx.mjs";import{runSocketPool as ni}from"./packem_shared/runSocketPool-CZJ2X9cF.mjs";import{MAX_SQL_ROWS as ci,assertReadonly as mi,lintReadonlySql as pi,runReadonlySql as Si}from"./packem_shared/MAX_SQL_ROWS-Dh_Ty0Zo.mjs";import{BIGINT_KEY_DIGITS as fi,bigintSqlKey as hi,decodeBigintSqlKey as xi,decodeFloat64SqlKey as Ei,float64SqlKey as Ti}from"./packem_shared/BIGINT_KEY_DIGITS-C9a7Ix7k.mjs";import{awaitWsDrain as Ci,subscriptionFrames as Ai,subscriptionListDeltas as gi,trySendFrame as _i}from"./packem_shared/awaitWsDrain-D4E7Oiwo.mjs";import{mergeChangedKeys as bi,recordChangedKeys as Li,writeTouchesMemo as Di}from"./packem_shared/mergeChangedKeys-DH9RAARR.mjs";import{createSystemReader as Oi}from"./packem_shared/createSystemReader-DcDLFfC-.mjs";import{ConflictError as Mi}from"./packem_shared/ConflictError-C8GtJmjS.mjs";import{DEFAULT_TRANSACTION_LIMITS as Ni,TransactionHeadroomTracker as ki}from"./packem_shared/DEFAULT_TRANSACTION_LIMITS-DiR5z5EX.mjs";import{hasTrigger as Ui,runTriggers as Gi}from"./packem_shared/hasTrigger-CjlwI4le.mjs";import{selectExpiredIds as qi}from"./packem_shared/selectExpiredIds-CilDdUr2.mjs";import{VECTOR_BACKFILL_MAX_PAGES as Ki,backfillVectorIndexes as Wi}from"./packem_shared/VECTOR_BACKFILL_MAX_PAGES-D9DeCfM2.mjs";import{c as Hi,s as Vi}from"./packem_shared/where-sql-Dn9trjRu.mjs";import{RELATION_EXISTS_KEY as Qi}from"./packem_shared/RELATION_EXISTS_KEY-wxgj6rSL.mjs";import{REPROJECTION_MIGRATION_PREFIX as ji,reprojectionMigrationId as Ji}from"./packem_shared/REPROJECTION_MIGRATION_PREFIX-Czcb6_mO.mjs";import{isInternalTableName as $i}from"./packem_shared/isInternalTableName-BoljO2tP.mjs";import{quoteIdentifier as rl}from"./packem_shared/quoteIdentifier-CObIFRhb.mjs";import{runShardMigrations as al}from"./packem_shared/runShardMigrations-eqHNBW6S.mjs";import{stableStringify as sl}from"./packem_shared/stableStringify-DibjylKD.mjs";import{stableWireKey as ll}from"./packem_shared/stableWireKey-Bdh5JSdg.mjs";export{sa as ADMIN_FUNCTIONS,ia as ADMIN_FUNCTION_PREFIX,d as AGGREGATE_SQL_FUNCTION,qr as AGG_COUNT,vr as AGG_KEY,Kr as AGG_VALUE,D as AUDIT_LOG_TABLE,fi as BIGINT_KEY_DIGITS,H as CDC_LOG_TABLE,V as CDC_LOG_TABLE_SEQ_INDEX,z as CDC_META_TABLE,Re as CLIENT_WATERMARK_TABLE,Ie as COMMIT_SEQ_FIELD,be as COMMIT_SEQ_TABLE,Xa as CURSOR_PREFIX,Mi as ConflictError,C as CountRlsUnsupportedError,Dr as DATA_MIGRATION_STATE_TABLE,la as DEFAULT_FANOUT_TOPIC_LIMIT,Yt as DEFAULT_MAX_RELATION_KEYS,Es as DEFAULT_MAX_RELAYS,ps as DEFAULT_PROMOTION_THRESHOLDS,Ni as DEFAULT_TRANSACTION_LIMITS,Wr as DOC_COLUMN,Eo as DurableStreamRunner,na as FLAGS_FUNCTION_PREFIX,Yo as GEO_DEFAULT_PRECISION,ke as GLOBAL_SHAPE_SNAPSHOT_TABLE,aa as GlobalPollTick,Ke as IDEMPOTENCY_TABLE,ba as MAIL_RETENTION,La as MAIL_TABLE,To as MAX_DURABLE_STREAM_BYTES,Ro as MAX_DURABLE_STREAM_CHUNKS,da as MAX_PAGE_SIZE,ci as MAX_SQL_ROWS,ya as NotFoundError,y as NotUniqueError,Ts as OwnerRelay,tt as QUEUE_TABLE,mt as RANK_TIEBREAK,gt as REACTOR_STATE_TABLE,Kt as RELATED_DEFAULT_LIMIT,Wt as RELATED_DEPTH_DECAY,Xt as RELATED_MAX_DEPTH,Ht as RELATED_MAX_LIMIT,Qi as RELATION_EXISTS_KEY,ca as RELATION_FUNCTION_PREFIX,ji as REPROJECTION_MIGRATION_PREFIX,Ms as RLS_UNWRAP_SYMBOL,Rt as ReactiveCache,Rs as RelayMember,ys as RlsRequiredError,Mr as SCAN_DEP,rr as SCHEDULE_OUTBOX_TABLE,Bs as SCHEMA_HISTORY_MAX_VERSIONS,mr as SEARCH_STATE_TABLE,hr as SHAPE_POKE_CURSOR_TABLE,Ys as ShapeDiffCache,ti as ShardRunner,ki as TransactionHeadroomTracker,Ot as UNVOUCHABLE_DEP,Ki as VECTOR_BACKFILL_MAX_PAGES,oo as WORKERD_SQLITE_LIMITS,Ce as advanceClientWatermark,Xr as aggUpsertSql,c as aggregateSqlFunction,f as aggregateTableName,Le as allocateCommitSeq,P as appendAuditEntry,Q as appendCdcChange,no as appendStreamChunk,Y as applyCdcChanges,ss as applyOnDelete,Ha as applySelect,ue as archiveCdcSegment,va as armRestore,jt as assertFlatPredicate,N as assertNoExplicitUndefined,ka as assertPatchAllowed,mi as assertReadonly,Jt as assertShapeShardable,k as assertValidClientId,Ci as awaitWsDrain,q as backfillAggregateIndexes,v as backfillRankIndexes,K as backfillSearchIndexes,W as backfillSearchIndexesForTable,Wi as backfillVectorIndexes,hi as bigintSqlKey,jo as boundingBoxCenter,Jo as boundingBoxGeohashes,Nt as buildIndexRange,$s as buildPokeFrames,Ls as buildReprojectionMigration,Va as buildSeekBeforeWhere,za as buildSeekWhere,Ws as buildSettings,zs as buildShapeDiff,j as bumpCdcEpoch,fe as cdcArchiveRewound,J as cdcCanVouchFor,Z as cdcForkedError,$ as cdcSeqLeavingRows,ee as cdcTouchesTables,re as cdcTrimmedError,co as claimStreamRun,Ss as clampPromotionThresholds,Da as clearCapturedMail,Fe as clearCompanionSignatures,Qe as clearMemoryTables,st as clearQueueMessages,h as coerceAggregateNumber,oe as compactCdcDocs,Hi as compileWhereSql,Zt as composeReadPredicate,Ze as computeRankPage,$t as containsRelationPredicate,Ds as countLegacyRows,Zo as coveringGeohashes,ye as createCompanionSync,yr as createDependencyTracker,ma as createFanoutCounters,pa as createGlobalPollCounters,Hr as createIndexSql,Ft as createReadFootprint,Cs as createRelayLink,gs as createReplicaLink,js as createShapeDiffCache,Sa as createShapeProbeCounters,B as createShardCtxDb,Oi as createSystemReader,ae as cursorBelowRetainedFloor,Co as decideDurableAttach,xi as decodeBigintSqlKey,Qa as decodeCursor,Ei as decodeFloat64SqlKey,or as deferScheduleOutbox,Be as deleteGlobalShapeSnapshot,Ue as deleteGlobalShapeSnapshotsForConnection,xr as deleteShapePokeCursor,Er as deleteShapePokeCursorsForConnection,mo as deleteStreamRun,Nr as depKey,Vt as deriveRelationEdges,as as describeRelationWrites,bo as diffExternalSource,ei as diffGlobalMembership,is as distinctValues,x as encodeAggregateKey,Ya as encodeCursor,$o as encodeGeohash,pt as encodePartitionKey,ri as encodeRowsPatch,O as ensureAuditTable,Pa as ensureMailTable,go as envOptionalPositiveInt,_o as envPositiveInt,ja as equalityPinnedFields,o as exportShardRows,ua as facetColumn,ls as fanOutScalarCounts,zt as findRelated,fa as findStorageReferences,po as finishStreamRun,Ti as float64SqlKey,E as foldAggregateTally,ar as forgetScheduleOutbox,Ko as ftsCompanionDdl,Wo as ftsPurgeDocument,Xo as ftsRowidMapName,Ho as ftsUnmappedPage,Vo as ftsWriteDocument,_s as gateReplicaDispatch,Vr as geoTableName,Js as globalShapeReadKey,zo as groupUnmappedRows,Ns as guardWriter,Is as handleReplicaControl,Ui as hasTrigger,ea as haversineMeters,a as importShardRows,kt as indexKeysForRow,Xs as isDevEnvironment,zr as isFtsAvailable,$i as isInternalTableName,it as isLossyBody,Ye as isMemoryTable,Gt as isPushableWhere,es as isRelationPredicate,Uo as isSoftDeleted,Go as isSourceDue,ha as isVacuousFilterClause,Qr as jsonPath,Yr as jsonPathSql,Bt as keysTouchRanges,Do as liftSourceId,pi as lintReadonlySql,_t as listReactorStates,xa as listTables,Mt as markUnvouchableReads,St as matchesRankStaticWhere,m as matchesStaticWhere,Mo as materializeExternalRows,yo as materializeExternalRowsIncremental,je as memoryTableNames,bi as mergeChangedKeys,A as mergeWhere,te as migrateCdcLog,se as migrateCdcMeta,Ae as migrateClientWatermark,De as migrateCommitSeq,So as migrateDurableStreams,Ge as migrateGlobalShapeSnapshot,We as migrateIdempotency,It as migrateReactorState,tr as migrateScheduleOutbox,pr as migrateSearchState,Tr as migrateShapePokeCursor,ie as minCdcReplayableSeq,le as minCdcSeq,Rr as minShapePokeCursor,us as nextPromotionState,p as normalizeCountArgument,U as normalizeIdStructurally,Ja as normalizeOrderKeys,Po as normalizeSourceDocument,Oo as normalizeSourceValue,Za as nullsFirstOf,$a as nullsOrderSuffix,Ba as operatorFields,ao as param,sr as parkScheduleOutbox,t as parseExportShardArgs,s as parseImportShardArgs,Ua as patchDependsOnRow,g as planAggregateLookup,ra as pointInBoundingBox,ir as probeScheduleOutbox,oi as projectColumns,wo as pullExternalSourceIncrementalTick,qo as pullExternalSourceTick,jr as qualifiedJsonPath,Jr as qualifiedJsonPathSql,rl as quoteIdentifier,ut as rankKeyFromDoc,ft as rankPivotConditionSql,ht as rankTableName,Ct as reactiveCacheKey,bt as reactorNeedsRun,T as readAggregateValue,he as readArchivedCdcChanges,F as readAuditLog,Ka as readBookmark,Oa as readCapturedMail,xe as readCdcArchivedThrough,ne as readCdcChangeKeys,de as readCdcChanges,ce as readCdcCursor,me as readCdcEpoch,ge as readClientWatermark,Pe as readCommitSeq,Hs as readDeployInfo,lr as readDueScheduleOutbox,No as readExternalSourceBaseline,we as readGlobalShapeSnapshot,Xe as readIdempotent,Pr as readMigrationStatus,Ga as readPatchField,lt as readQueueMessageById,nt as readQueueMessages,Lt as readReactorState,Us as readSchemaHistory,Gs as readSchemaVersion,Sr as readSearchBackfillState,Cr as readShapePokeCursor,uo as readStreamChunks,fo as readStreamRun,Ea as readTablePage,Fa as recordCapturedMail,Li as recordChangedKeys,Ta as recordFanoutPass,Ra as recordGlobalPollPass,dt as recordQueueMessages,nr as recordScheduleOutbox,ws as recordSchemaVersion,Ca as recordShapeProbePass,ns as relationHooks,fs as relayCountFor,to as renderSql,Ps as reprojectableFields,Ji as reprojectionMigrationId,Os as reprojectionTables,wa as resolvePatch,xt as resolveRankPartition,$e as resolveRankSeekTuple,rs as resolveRelationPredicates,ds as resolveWith,Zr as rowToDocument,Or as runDataMigration,Ur as runDrizzle,ko as runExternalSourceTick,Si as runReadonlySql,cs as runRowValidators,al as runShardMigrations,ni as runSocketPool,Gr as runSql,Gi as runTriggers,qi as selectExpiredIds,i as selectExportTables,_ as selectIndexForAggregate,I as selectIndexForCount,b as selectIndexForGroupBy,Aa as selectMatchingIds,Ir as selectShapeMembers,br as selectShapeRows,vs as serializeSqlValue,Vi as serverInList,hs as shapeRoutingKey,et as softDeleteScope,Et as sortColumnName,so as sqliteInList,sl as stableStringify,ll as stableWireKey,G as stripReservedPatchFields,ii as stubByName,Ai as subscriptionFrames,gi as subscriptionListDeltas,ga as summarizeFanoutTopics,_a as summarizeSubscriptions,$r as tableColumns,kr as tableFromDepKey,S as throwingScheduler,rt as tiebreakDirectionFor,pe as trimCdcChanges,He as trimIdempotent,dr as trimScheduleOutbox,ho as trimStreamRuns,eo as tryRowToDocument,_i as trySendFrame,io as unionAll,ot as uniqueIndexFields,l as validateImportRow,wt as whereFilter,qt as whereOfFilter,Ee as writeCdcArchivedThrough,qe as writeGlobalShapeSnapshot,Ve as writeIdempotent,Dt as writeReactorState,ur as writeSearchBackfillState,Ar as writeShapePokeCursor,gr as writeShapePokeCursors,Di as writeTouchesMemo};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{LunoraError as h}from"@lunora/errors";import{i as S,R as L}from"./relation-operators-BEg-CvCH.mjs";import{mergeWhere as w}from"./CountRlsUnsupportedError-BvsDqfO2.mjs";import{isMemoryTable as R}from"./clearMemoryTables-CogAvVHR.mjs";import{normalizeOrderKeys as j,uniqueIndexFields as M,equalityPinnedFields as P,buildSeekWhere as k,decodeCursor as I,softDeleteScope as K}from"./CURSOR_PREFIX-BztyXqNP.mjs";import{distinctValues as O}from"./applyOnDelete-CGVYKtaW.mjs";import{RELATION_EXISTS_KEY as _}from"./RELATION_EXISTS_KEY-wxgj6rSL.mjs";const v={every:{kind:"many",negateChild:!0,negated:!0},is:{kind:"one",negated:!1},isNot:{kind:"one",negated:!0,nullDisjunct:!0},none:{kind:"many",negated:!0},some:{kind:"many",negated:!1}},A=e=>L.has(e)?e:void 0,g=e=>{const t=A(e),r=t===void 0?void 0:v[t];if(!r)throw new h("INTERNAL",`unknown relation operator "${e}"`);return r},C=e=>e.kind==="one"?{clause:e.field,project:e.references}:{clause:e.references,project:e.field},D=5e3,f=Symbol("relation-key-overflow"),p=e=>Array.isArray(e)?e.map(t=>t??{}):[],N=e=>{if(e.length===1){const[t]=e;return t??{}}return e.length===0?{}:{AND:e}},y=e=>S(e),u=(e,t,r)=>{const n=t.tables[r]?.relationMap??{};return Object.keys(e).some(o=>{const a=e[o];return o==="AND"||o==="OR"?p(a).some(s=>u(s,t,r)):o==="NOT"?u(a??{},t,r):!!n[o]&&y(a)})},oe=(e,t,r,n)=>{if(e&&u(e,t,r))throw new h("INTERNAL",`relation-crossing predicates are not supported in ${n}() — use them in findMany/findFirst or an RLS read policy`)},B=async(e,t,r,n)=>{const o=await l(t,e.table,n),{page:a}=await n.fetcher(e.table,{baseWhere:n.relationBaseWhere?.(e.table),relationBaseWhere:n.relationBaseWhere,where:o});return O(a,r)},W=(e,t,r)=>{throw new h("INTERNAL",`relation predicate on "${e.table}" matched ${String(t)} rows, exceeding the ${String(r.maxRelationKeys)}-key limit; narrow the predicate (a same-shard EXISTS push-down lifts this cap)`)},F=(e,t,r)=>{throw new h("INTERNAL",`relation predicate on "${e.table}" matched at least ${String(t)} distinct keys, exceeding the ${String(r.maxRelationKeys)}-key limit; narrow the predicate`)},q=async(e,t,r,n,o)=>{const a=await B(e,t,r,n);return a.length<=n.maxRelationKeys?a:o?f:W(e,a.length,n)},b=async(e,t,r,n)=>{const o=await l(t,e.table,n),a=n.maxRelationKeys+1,s=new Set;let d;for(;;){const i=await n.fetcher(e.table,{baseWhere:n.relationBaseWhere?.(e.table),cursor:d,limit:a,relationBaseWhere:n.relationBaseWhere,where:o});if(i.page.length>a)throw new h("INTERNAL",`relation predicate on "${e.table}" read ${String(i.page.length)} rows for a page of at most ${String(a)}; the fetcher did not honour the page limit`);for(const c of O(i.page,r))s.add(c);if(s.size>n.maxRelationKeys&&F(e,s.size,n),i.isDone)return[...s];if(typeof i.continueCursor!="string")throw new h("INTERNAL",`relation predicate on "${e.table}" returned a page that is not final but has no cursor to continue from`);if(i.continueCursor===d)throw new h("INTERNAL",`relation predicate on "${e.table}" paged with a cursor that did not advance`);d=i.continueCursor}},H=async(e,t,r,n,o)=>{const a=g(e),{clause:s,project:d}=C(t),i=await q(t,a.negateChild?{NOT:r}:r,d,n,o);return i===f?f:a.negated?a.nullDisjunct?{OR:[{[s]:{notIn:i}},{[s]:{isNull:!0}}]}:{[s]:{notIn:i}}:{[s]:{in:i}}},z=async(e,t,r,n)=>{const o=g(e),{from:a,table:s,to:d}=t.through,i=await b(t,o.negateChild?{NOT:r}:r,"_id",n),c=i.length===0?[]:await b({table:s},{[d]:{in:i}},a,n);return{_id:o.negated?{notIn:c}:{in:c}}},E=async(e,t,r,n,o)=>{const a=g(e),s=o.relationBaseWhere?.(t.table),d=a.negateChild?{NOT:r}:r,$={childWhere:await l(s?{AND:[s,d]}:d,t.table,o),negated:a.negated,parentTable:n,relation:t};return{[_]:$}},Y=(e,t,r)=>{const n=A(e),o=n===void 0?void 0:v[n];if(o&&o.kind!==r.kind)throw new h("INTERNAL",`relation operator "${e}" requires a to-${o.kind} relation, but "${t}" is to-${r.kind}`)},x=async(e,t,r,n,o)=>{const a=[];for(const s of Object.keys(r)){Y(s,e,t);const d=r[s]??{};if(t.through!==void 0){a.push(await z(s,t,d,o));continue}const i=o.canPushExists?.(t)??!1;if(i&&o.existsPushMode==="always"){a.push(await E(s,t,d,n,o));continue}const c=await H(s,t,d,o,i);c===f?a.push(await E(s,t,d,n,o)):a.push(c)}return N(a)},Q=async(e,t,r,n)=>{if(e==="AND"||e==="OR"){const a=[];for(const s of p(t))a.push(await l(s,r,n));return{[e]:a}}if(e==="NOT")return{NOT:await l(t??{},r,n)};const o=n.schema.tables[r]?.relationMap?.[e];return o&&y(t)?x(e,o,t,r,n):{[e]:t}},l=async(e,t,r)=>{const n=[];for(const o of Object.keys(e))n.push(await Q(o,e[o],t,r));return N(n)},X=async(e,t)=>!e||!u(e,t.schema,t.tableName)?e:l(e,t.tableName,{canPushExists:t.canPushExists,existsPushMode:t.existsPushMode??"auto",fetcher:t.fetcher,maxRelationKeys:t.maxRelationKeys??D,relationBaseWhere:t.relationBaseWhere,schema:t.schema}),ae=async(e,t,r)=>{const n=j(t.orderBy,e.shape,{pinned:P(t.where),uniqueBy:M(e.indexes,e.shape)}),o=t.cursor?k(n,I(t.cursor)):void 0;let a=w(t.baseWhere,t.where);a=w(a,K(e.softDeleteMode,t.includeDeleted)),a=await X(a,{...r,relationBaseWhere:t.relationBaseWhere}),o&&(a=a?{AND:[a,o]}:o);const s=typeof t.limit=="number"?Math.max(0,Math.floor(t.limit)):void 0;return{fetchLimit:s===void 0?void 0:s+1,limit:s,orderKeys:n,predicate:a}},m=(e,t,r)=>{for(const n of e){const o=T(n,t,r);if(o)return o}},U=(e,t,r,n)=>{if(e==="AND"||e==="OR")return m(p(t),r,n);if(e==="NOT")return m([t??{}],r,n);const o=r.tables[n]?.relationMap?.[e];if(!o||!y(t))return;const a=o.through===void 0?[o.table]:[o.table,o.through.table],s=a.find(i=>r.tables[i]?.shardMode?.kind==="shardBy");if(s!==void 0)return{kind:"shard",relation:e,target:s};const d=a.find(i=>R(r.tables[i]));return d!==void 0?{kind:"memory",relation:e,target:d}:m(Object.values(t),r,o.table)},T=(e,t,r)=>{for(const n of Object.keys(e)){const o=U(n,e[n],t,r);if(o)return o}},V=(e,t,r)=>{if(!(t.tables[r]?.shardMode?.kind==="global"||!u(e,t,r)))throw Object.assign(new Error(`shape on "${r}" filters by a relation, which a shard-local shape cannot replicate: its seed and membership probe read "${r}" alone, so the relation never matches, and a write that only touches the related table never moves the shape. Fix it by (a) denormalizing the related columns into "${r}" and filtering on those, (b) moving "${r}" to .global() so it is served through the latency-tiered D1 shape tier, or (c) reading it through a live query (\`useQuery\`), which does resolve relations.`),{code:"SHAPE_RELATION_PREDICATE",name:"LunoraError",status:400})},se=(e,t,r)=>{if(R(t.tables[r]))throw Object.assign(new Error(`shape on "${r}" replicates from the changelog, which never records a .memory() table — the shape would seed once and never update again. Fix it by (a) dropping .memory() from "${r}" so its writes reach the changelog, or (b) reading it through a live query (\`useQuery\`), which refreshes off the changed-table set rather than the log.`),{code:"SHAPE_MEMORY_TABLE",name:"LunoraError",status:400});if(!e)return;const n=T(e,t,r);if(!n){V(e,t,r);return}throw n.kind==="memory"?Object.assign(new Error(`shape on "${r}" joins the .memory() table "${n.target}" via relation "${n.relation}" — writes to a .memory() table never reach the changelog, so the shape is never told its membership changed and would serve stale rows indefinitely. Fix it by (a) dropping .memory() from "${n.target}", or (b) reading it through a live query (\`useQuery\`), which refreshes off the changed-table set rather than the log.`),{code:"SHAPE_MEMORY_TABLE",name:"LunoraError",status:400}):Object.assign(new Error(`shape on "${r}" joins the sharded table "${n.target}" via relation "${n.relation}" — a live shape cannot replicate rows that live in another shard's Durable Object. Fix it by (a) denormalizing the joined columns into "${r}", or (b) moving "${n.target}" to .global() so it is served through the latency-tiered D1 shape tier.`),{code:"SHAPE_CROSS_SHARD_JOIN",name:"LunoraError",status:400})};export{D as DEFAULT_MAX_RELATION_KEYS,oe as assertFlatPredicate,se as assertShapeShardable,ae as composeReadPredicate,u as containsRelationPredicate,y as isRelationPredicate,X as resolveRelationPredicates};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{LunoraError as y}from"@lunora/errors";import{D as lt}from"./MAX_TOKEN_LENGTH-BakL9FUy-B3VwYY8C.mjs";import{S as Sn,l as Fe,h as _n}from"./fts-companion-pUdD6kF-.mjs";import{sql as c}from"drizzle-orm";import{d as Rn}from"./wire-codec-BYCSiazv.mjs";import{stableWireKey as Ct}from"./stableWireKey-Bdh5JSdg.mjs";import{throwingScheduler as Tn,aggregateSqlFunction as qe,normalizeCountArgument as vn}from"./AGGREGATE_SQL_FUNCTION-BMtvQHac.mjs";import{aggregateTableName as Xe,encodeAggregateKey as Ze,readAggregateValue as et}from"./aggregateTableName-DbAttCNH.mjs";import{mergeWhere as N,CountRlsUnsupportedError as tt,selectIndexForGroupBy as An,selectIndexForCount as In,selectIndexForAggregate as Cn}from"./CountRlsUnsupportedError-BvsDqfO2.mjs";import{backfillSearchIndexesForTable as xn,searchIndexCoversTable as bn}from"./backfillAggregateIndexes-CJrtolQ9.mjs";import{backfillAggregateIndexes as ni,backfillRankIndexes as ri,backfillSearchIndexes as oi}from"./backfillAggregateIndexes-CJrtolQ9.mjs";import{appendCdcChange as Mn,readCdcDocAtOrBefore as Dn}from"./CDC_LOG_TABLE-BPEzVAil.mjs";import{CDC_LOG_TABLE as si,applyCdcChanges as ci,bumpCdcEpoch as ai,cdcCanVouchFor as di,cdcForkedError as li,cdcSeqLeavingRows as ui,cdcTouchesTables as fi,cdcTrimmedError as hi,compactCdcDocs as wi,cursorBelowRetainedFloor as pi,minCdcReplayableSeq as gi,minCdcSeq as yi,readCdcChangeKeys as $i,readCdcChanges as Ei,readCdcCursor as mi,readCdcEpoch as Si,trimCdcChanges as _i}from"./CDC_LOG_TABLE-BPEzVAil.mjs";import{allocateCommitSeq as kn,COMMIT_SEQ_FIELD as Ln}from"./COMMIT_SEQ_FIELD-BY_vc9bw.mjs";import{createCompanionSync as Fn}from"./createCompanionSync-B7dV2y4L.mjs";import{isMemoryTable as xt}from"./clearMemoryTables-CogAvVHR.mjs";import{computeRankPage as bt}from"./computeRankPage-CFeFkZ_k.mjs";import{SCAN_DEP as O}from"./SCAN_DEP-D7qE3iUe.mjs";import{runSql as we,runDrizzle as G}from"./runDrizzle-Du5HLitO.mjs";import{p as qn,j as ct,D as oe,r as Te,k as le,b as We,A as nt,a as Be,m as fe,e as he,s as Wn,t as tn,i as Bn,q as Mt,h as nn,g as Pn}from"./do-sql-Cg3zXJpF.mjs";import{renderSql as rn,unionAll as ut,WORKERD_SQLITE_LIMITS as on,sqliteInList as Un}from"./WORKERD_SQLITE_LIMITS-DBH23L_S.mjs";import{coveringGeohashes as On,boundingBoxGeohashes as Hn,haversineMeters as Gn,pointInBoundingBox as jn}from"./GEO_DEFAULT_PRECISION-CqpQZ-J_.mjs";import{NotFoundError as Kn}from"./NotFoundError-BhF7FeFr.mjs";import{resolvePatch as Nn,assertPatchAllowed as Qn,operatorFields as Vn,readPatchField as Dt}from"./assertPatchAllowed-BJ_2LgkQ.mjs";import{tiebreakDirectionFor as Jn,encodeCursor as He,nullsOrderSuffix as zn,normalizeOrderKeys as kt,uniqueIndexFields as Yn,buildSeekWhere as Xn,decodeCursor as Lt,buildSeekBeforeWhere as Zn,softDeleteScope as Re,applySelect as Ft}from"./CURSOR_PREFIX-BztyXqNP.mjs";import{rankTableName as qt,sortColumnName as Wt,resolveRankPartition as er,encodePartitionKey as tr,RANK_TIEBREAK as nr,rankPivotConditionSql as rr}from"./RANK_TIEBREAK-BKugKf70.mjs";import{UNVOUCHABLE_DEP as Bt}from"./UNVOUCHABLE_DEP-C68htACn.mjs";import{indexKeysForRow as or,buildIndexRange as ir}from"./buildIndexRange-6nIZDf4m.mjs";import{r as Ge,j as ve,c as X,t as je,i as Pt}from"./where-sql-Dn9trjRu.mjs";import{serializeSqlValue as Ae}from"./serializeSqlValue-BbZ5hKM7.mjs";import{quoteIdentifier as Ie}from"./quoteIdentifier-CObIFRhb.mjs";import{whereOfFilter as sr,isPushableWhere as cr}from"./isPushableWhere-BeYAOjUb.mjs";import{deriveRelationEdges as ar,findRelated as dr}from"./RELATED_DEFAULT_LIMIT-Me5elP-K.mjs";import{assertFlatPredicate as rt,resolveRelationPredicates as lr,composeReadPredicate as ur}from"./DEFAULT_MAX_RELATION_KEYS-BfhdOkA2.mjs";import{describeRelationWrites as fr}from"./describeRelationWrites-omar6-u9.mjs";import{runRowValidators as ot,resolveWith as Ut,relationHooks as Ot,applyOnDelete as hr,fanOutScalarCounts as wr}from"./applyOnDelete-CGVYKtaW.mjs";import{guardWriter as pr}from"./RLS_UNWRAP_SYMBOL-qYcAxjuk.mjs";import{mayHoldProjectedValue as gr}from"./BIGINT_KEY_DIGITS-C9a7Ix7k.mjs";import{createSystemReader as yr}from"./createSystemReader-DcDLFfC-.mjs";import{ConflictError as ae}from"./ConflictError-C8GtJmjS.mjs";import{runTriggers as $r}from"./hasTrigger-CjlwI4le.mjs";import{advanceClientWatermark as Ti,migrateClientWatermark as vi,readClientWatermark as Ai}from"./CLIENT_WATERMARK_TABLE-vLjfNhBR.mjs";import{IDEMPOTENCY_TABLE as Ci,readIdempotent as xi,trimIdempotent as bi,writeIdempotent as Mi}from"./IDEMPOTENCY_TABLE-AOJCuq5U.mjs";import{runShardMigrations as ki}from"./runShardMigrations-eqHNBW6S.mjs";import{selectShapeMembers as Fi,selectShapeRows as qi}from"./selectShapeMembers-CU8Kl2Bq.mjs";const Er=n=>{const i=atob(n),r=Uint8Array.from(i,a=>a.codePointAt(0)??0);return new TextDecoder().decode(r)},mr=()=>new y("BAD_REQUEST","invalid cursor"),Ht=16,Gt=8,z=1024,ft=(n,i)=>i.query(n),Sr=(n,i)=>{if(n.length===0)return 0;let r=0;for(const[a,s]of i.entries()){const w=a===i.length-1;let A=0;for(const T of n)(w?T.startsWith(s):T===s)&&(A+=1);if(A===0)return 0;r+=A}return r},_r=(n,i)=>{if(!i)return{exact:!0,lower:n,upper:n};const r=[...n].at(-1)??"",a=(r.codePointAt(0)??0)+1;if(a>=55296&&a<=57343||a>1114111)return{exact:!0,lower:n,upper:n};const s=n.slice(0,n.length-r.length);return{exact:!1,lower:n,upper:s+String.fromCodePoint(a)}},Rr=(n,i,r)=>{const a={eq:(s,w)=>{if(!n.definition.filterFields?.includes(s))throw new y("INTERNAL",`field "${s}" is not a filter field of search index "${n.indexName}" on table "${i}"`);if(n.filters.length>=Gt)throw new y("BAD_REQUEST",`search index "${n.indexName}" on table "${i}": at most ${String(Gt)} .eq() filters are supported per search query`);return n.filters.push({field:s,value:w}),a},search:(s,w)=>{const A=n;if(s!==A.definition.field)throw new y("INTERNAL",`search index "${A.indexName}" on table "${i}" indexes "${A.definition.field}", not "${s}"`);const T=ft(w,r).length;if(T>Ht)throw new y("BAD_REQUEST",`search index "${A.indexName}" on table "${i}": at most ${String(Ht)} search terms are supported (got ${String(T)})`);return A.field=s,A.query=w,A.hasQuery=!0,a}};return a},Tr=n=>{if(n.length>z)throw new y("BAD_REQUEST",`more than ${String(z)} documents match this search — narrow it with filters or read it a page at a time with .paginate()`)},vr=n=>Math.min(n.offset+n.numItems+1,z),Ar=n=>btoa(`search:${String(n)}`),Ir=n=>{let i;try{i=Er(n)}catch{return}if(!i.startsWith("search:"))return;const r=Number(i.slice(7));return Number.isInteger(r)&&r>=0?r:void 0},Cr=n=>{if(typeof n.endCursor=="string")throw new y("BAD_REQUEST","bounded (endCursor) pagination is not supported on search queries — relevance order has no stable range boundary");if(!Number.isFinite(n.numItems))throw new y("BAD_REQUEST",`search pagination needs a finite numItems, got ${String(n.numItems)}`);const i=Math.max(0,Math.floor(n.numItems)),r=n.cursor?Ir(n.cursor):0;if(r===void 0)throw mr();if(r+i>=z)throw new y("BAD_REQUEST",`search pagination reaches the ${String(z)}-document limit (offset ${String(r)} + ${String(i)} requested) — a page must end below the cap so the probe row that answers \`hasMore\` still fits: retry with numItems ${String(Math.max(1,z-r-1))} or fewer, or narrow the query or the filters instead`);return{numItems:i,offset:r}},xr=(n,i)=>{const r=i.offset+i.numItems,a=i.numItems>0&&n.length>r;return{continueCursor:a?Ar(r):null,isDone:!a,page:n.slice(i.offset,r)}},br=n=>{if(n===void 0)return z+1;if(!Number.isFinite(n))return z;const i=Math.max(0,Math.floor(n));if(i>z)throw new y("BAD_REQUEST",`search returns at most ${String(z)} documents (asked for ${String(i)}) — narrow the query or paginate instead`);return i},Mr=32,Dr=1024,sn=(n,i,r,a)=>{const s=`SELECT id, _creationTime, ${Ie(oe)} FROM ${Ie(n)}`,w=`ORDER BY ${r}${a===void 0?"":` LIMIT ${String(a)}`}`;return i===void 0?Ge(`${s} ${w}`):ve(`${s} WHERE `,i,` ${w}`)},Ke={fieldRef:n=>Ge(ct(n)),rangeTypeGuard:(n,i)=>Ge(qn(n,i)),serialize:Ae},kr=n=>n===void 0?"":zn(n==="first"),cn=n=>{const i=n.map(r=>`${ct(r.field)} ${r.direction==="desc"?"DESC":"ASC"}${kr(r.nulls)}`);return n.some(r=>r.field==="_id"||r.field==="id")||i.push(`${ct("id")} ${Jn(n)==="desc"?"DESC":"ASC"}`),i.join(", ")},Lr={"<":"lt","<=":"lte","=":"eq",">":"gt",">=":"gte"},an=n=>new Set(n.sqlConditions.filter(i=>i.comparator==="=").map(i=>i.field)),Fr=n=>{const i=an(n);let r=0;for(;r<n.indexFields.length&&i.has(n.indexFields[r]??"");)r+=1;return n.indexFields.slice(r)},qr=(n,i)=>{const r=n.order,a=Fr(n),{shape:s}=i;return a.length>0?kt(a.map(w=>({[w]:r})),s,{pinned:an(n),uniqueBy:Yn(i.indexes,s)}):kt([{_creationTime:r}],s)},Wr=(n,i,r,a)=>{const s=n.sqlConditions.map(w=>({[w.field]:{[Lr[w.comparator]??"eq"]:w.value}}));if(r&&s.push(Xn(i,Lt(r))),a&&s.push(Zn(i,Lt(a))),s.length!==0)return s.length===1?s[0]:{AND:s}},Br=n=>{if(n.want!==void 0)return n.selective?Math.max(n.want,Mr):n.want},at=(n,i,r,a,s,w,A)=>{const T=qr(a,r),b=cn(T),g=[],{filters:k,want:v}=w;let C=w.cursor??void 0,x=Br(w);if(v===0)return{documents:g,orderKeys:T};for(;;){const U=X(Wr(a,T,C,w.endCursor),Ke,je),q=sn(i,s&&U?ve(U," AND ",s):s??U,b,x),F=we(n,q.text,...q.params).toArray();let W={};A(F.length);for(const j of F)if(W=Te(j),k.every(L=>L(W))&&g.push(W)===v)return{documents:g,orderKeys:T};if(x===void 0||F.length<x)return{documents:g,orderKeys:T};C=He(W,T),x=Math.max(x,Math.min(x*2,Dr))}},Pr=(n,i,r,a,s,w,A,T)=>{const b=Math.max(0,Math.floor(s.numItems));if(typeof s.endCursor=="string"){const{documents:U,orderKeys:q}=at(n,i,r,a,w,{cursor:s.cursor,endCursor:s.endCursor,filters:A.all,selective:A.selective,want:void 0},T),F=U.length>=2?U[Math.floor(U.length/2)-1]:void 0;return{continueCursor:s.endCursor,isDone:!0,page:U,splitCursor:F?He(F,q):null}}const{documents:g,orderKeys:k}=at(n,i,r,a,w,{cursor:s.cursor,filters:A.all,selective:A.selective,want:b+1},T),v=g.length>b,C=v?g.slice(0,b):g,x=C.at(-1);return{continueCursor:v&&x?He(x,k):null,isDone:!v,page:C}},Ne=n=>{const i=new Map;return r=>{const a=i.get(r);if(a!==void 0)return a;const s=n(Ie(r));return i.set(r,s),s}},pe=Ie(oe),Ur=Ne(n=>`INSERT INTO ${n} (id, _creationTime, ${pe}) VALUES (?, ?, ?)`),jt=Ne(n=>`UPDATE ${n} SET ${pe} = ? WHERE id = ? AND ${pe} = ?`),Or=Ne(n=>`UPDATE ${n} SET _creationTime = ?, ${pe} = ? WHERE id = ? AND ${pe} = ?`),Hr=Ne(n=>`DELETE FROM ${n} WHERE id = ? AND ${pe} = ?`),Gr="SELECT changes() AS changed",Kt=new Map,jr="",Kr=n=>{const i=JSON.stringify(n),r=Kt.get(i);if(r!==void 0)return r;const a=n.map(w=>c`SELECT ${c.raw(`'${w.replaceAll("'","''")}'`)} AS __t__, id, _creationTime, ${c.identifier(oe)} FROM ${c.identifier(w)} WHERE id = ${jr}`),{sql:s}=rn("sqlite",c`${ut(a)} LIMIT 1`);return Kt.set(i,s),s},Nr=(n,i)=>i.map(()=>n),Qr=/^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/iu,Vr=n=>{if(!Qr.test(n))throw new y("INTERNAL",`invalid clientId ${JSON.stringify(n)}: a client-supplied row id must be a UUID`)},Nt=50,dn=500,Pe=Math.floor(on.boundParams/3),_e=on.boundParams,Jr=128,ue=(n,i,r)=>{const a=i??dn;if(n>a)throw new y("BATCH_LIMIT_EXCEEDED",`${r}: batch of ${String(n)} exceeds the limit of ${String(a)} (raise options.limit or chunk the call)`,{status:400})},zr=n=>{const i={eq:(r,a)=>(n.sqlConditions.push({comparator:"=",field:r,value:a}),i),gt:(r,a)=>(n.sqlConditions.push({comparator:">",field:r,value:a}),i),gte:(r,a)=>(n.sqlConditions.push({comparator:">=",field:r,value:a}),i),lt:(r,a)=>(n.sqlConditions.push({comparator:"<",field:r,value:a}),i),lte:(r,a)=>(n.sqlConditions.push({comparator:"<=",field:r,value:a}),i)};return i},Yr=n=>Math.max(n,z),ln=(n,i)=>{const r=n.filters.map(a=>c`${he(a.field)} = ${Ae(a.value)}`);return i&&r.push(i),r},Xr=(n,i,r,a,s)=>{const w=ft(r.query,lt(r.definition.language));if(w.length===0)return[];const A=Sn(i,r.indexName),T=`${A}__vocab`,b=w.length-1,g=w.map((q,F)=>{const W=_r(q,F===b),j=W.exact?c`${c.identifier("term")} = ${W.lower}`:c`${c.identifier("term")} >= ${W.lower} AND ${c.identifier("term")} < ${W.upper}`;return c`SELECT ${c.identifier("doc")}, ${c.raw(String(F))} AS ${c.identifier("__term__")}, COUNT(*) AS ${c.identifier("__n__")} FROM ${c.identifier(T)} WHERE ${j} GROUP BY ${c.identifier("doc")}`}),k=w.map((q,F)=>c`SUM(CASE WHEN u.${c.identifier("__term__")} = ${c.raw(String(F))} THEN u.${c.identifier("__n__")} ELSE 0 END)`),v=c`SELECT f.${c.identifier(Fe)} AS ${c.identifier(Fe)}, ${c.join(k,c` + `)} AS ${c.identifier("__score__")} FROM (${ut(g)}) u JOIN ${c.identifier(A)} f ON f.rowid = u.${c.identifier("doc")} GROUP BY f.${c.identifier(Fe)} HAVING ${c.join(k.map(q=>c`${q} > 0`),c` AND `)}`,C=ln(r,s);let x=c`SELECT m.id, m._creationTime, m.${c.identifier(oe)}, s.${c.identifier("__score__")} AS ${c.identifier("__score__")} FROM (${v}) s JOIN ${c.identifier(i)} m ON m.id = s.${c.identifier(Fe)}`;C.length>0&&(x=c`${x} WHERE ${c.join(C,c` AND `)}`),x=c`${x} ORDER BY s.${c.identifier("__score__")} DESC, m._creationTime DESC, m.id ASC LIMIT ${c.raw(String(a))}`;const U=[];for(const q of G(n,x)){const F=nn(q);if(F){const W=q.__score__;U.push({document:F,score:typeof W=="number"?W:Number(W??0)})}}return U},Zr=(n,i,r,a,s)=>{const w=lt(r.definition.language),A=ft(r.query,w);if(A.length===0)return[];const T=ln(r,s);let b=c`SELECT id, _creationTime, ${c.identifier(oe)} FROM ${c.identifier(i)}`;T.length>0&&(b=c`${b} WHERE ${c.join(T,c` AND `)}`),b=c`${b} ORDER BY _creationTime DESC, id ASC LIMIT ${c.raw(String(Yr(a)))}`;const g=G(n,b).toArray(),k=[];for(const v of g){const C=nn(v);if(!C)continue;const x=Sr(_n(C,r.definition),A);x>0&&k.push({creationTime:typeof C._creationTime=="number"?C._creationTime:0,doc:C,id:typeof C._id=="string"?C._id:"",score:x})}return k.sort((v,C)=>C.score-v.score||C.creationTime-v.creationTime||v.id.localeCompare(C.id)),k.slice(0,a).map(v=>({document:v.doc,score:v.score}))},it=(n,i,r,a)=>{if(!Number.isFinite(n.lat)||n.lat<-90||n.lat>90||!Number.isFinite(n.lng)||n.lng<-180||n.lng>180)throw new y("BAD_REQUEST",`geo index "${a}" on table "${r}": ${i} must have a finite lat in [-90, 90] and lng in [-180, 180]`)},eo=(n,i)=>{const r=n,a={near:(s,w)=>{if(r.within)throw new y("INTERNAL",`geo index "${r.indexName}" on table "${i}": call .near() or .within(), not both`);if(it(s,".near() point",i,r.indexName),!Number.isFinite(w)||w<=0)throw new y("BAD_REQUEST",`geo index "${r.indexName}" on table "${i}": .near() radiusMeters must be a finite number > 0, got ${String(w)}`);return r.near={point:{lat:s.lat,lng:s.lng},radiusMeters:w},a},within:s=>{if(r.near)throw new y("INTERNAL",`geo index "${r.indexName}" on table "${i}": call .near() or .within(), not both`);if(it(s.sw,".within() sw corner",i,r.indexName),it(s.ne,".within() ne corner",i,r.indexName),s.sw.lat>s.ne.lat)throw new y("BAD_REQUEST",`geo index "${r.indexName}" on table "${i}": .within() corners are transposed (sw.lat > ne.lat)`);if(s.sw.lng>s.ne.lng)throw new y("BAD_REQUEST",`geo index "${r.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 r.within={ne:{lat:s.ne.lat,lng:s.ne.lng},sw:{lat:s.sw.lat,lng:s.sw.lng}},a}};return a},to=(n,i)=>{const r=n[i];if(r===null||typeof r!="object")return;const{lat:a,lng:s}=r;return typeof a=="number"&&typeof s=="number"?{lat:a,lng:s}:void 0},no=(n,i)=>{const r=to(n,i.definition.field);if(!r)return;const a=typeof n._creationTime=="number"?n._creationTime:0;if(i.near){const s=Gn(i.near.point,r);return s<=i.near.radiusMeters?{creationTime:a,distance:s}:void 0}return jn(r,i.within)?{creationTime:a,distance:0}:void 0},ro=(n,i,r,a)=>{if(!r.near&&!r.within)throw new y("INTERNAL",`geo index "${r.indexName}" on table "${i}": call .near(point, radius) or .within(box)`);const s=r.near?On(r.near.point,r.near.radiusMeters):Hn(r.within),w=Pn(i,r.indexName),A=s.map(v=>c`(g.${c.identifier("__geohash__")} >= ${v} AND g.${c.identifier("__geohash__")} < ${`${v}{`})`),T=[c`(${c.join(A,c` OR `)})`];a&&T.push(a);const b=c`SELECT m.id, m._creationTime, m.${c.identifier(oe)} FROM ${c.identifier(w)} g JOIN ${c.identifier(i)} m ON m.id = g.${c.identifier("__id__")} WHERE ${c.join(T,c` AND `)}`,g=G(n,b).toArray(),k=[];for(const v of g){const C=Te(v),x=C?no(C,r):void 0;C&&x&&k.push({creationTime:x.creationTime,distance:x.distance,doc:C})}return k.sort((v,C)=>v.distance-C.distance||C.creationTime-v.creationTime),k},un=(n,i,r,a)=>{const s=[];for(const w of n)if(i.every(A=>A(a(w)))&&(s.push(w),typeof r=="number"&&s.length>=r))break;return s},oo=(n,i,r,a,s,w=()=>{})=>{const A=r.within!==void 0,T=ro(n,i,r,s).map(b=>({distanceMeters:A?null:b.distance,document:b.doc}));return w(T.length),typeof a=="number"?T.slice(0,Math.max(0,Math.floor(a))):T},Qt=(n,i,r,a,s,w,A=()=>{})=>{const{geo:T}=r;if(!T)throw new y("INTERNAL","runGeoTerminalScored called without a staged geo query");const b=s.length>0,g=oo(n,i,T,b?void 0:w,a,A);return b?un(g,s,w,k=>k.document):g},Vt=(n,i,r)=>{const a=n.shape[i];if(a!==void 0&&gr(a))throw new y("BAD_REQUEST",`${r}: "${i}" may hold an order-preserving key rather than a value SQL can reduce or group — declare an aggregateIndex covering this (by, field, op) so the maintained companion answers it instead (its running total is a REAL, so it stays exact only while the total is inside 2^53)`)},io=n=>{let i=0;const r=[],a={...Ke,relationExists:s=>{const{childWhere:w,negated:A,parentTable:T,relation:b}=s,g=`__rel_${String(i)}`,k=r.at(-1)??T;i+=1,n(b.table,O);const v=b.kind==="one"?b.field:b.references,C=b.kind==="one"?b.references:b.field,x=Ge(`${Mt(g,C)} = ${Mt(k,v)}`);r.push(g);const U=X(w,a,je);r.pop();const q=U===void 0?x:ve(x," AND ",U),F=ve("EXISTS (SELECT 1 FROM ",Pt(b.table)," AS ",Pt(g)," WHERE ",q,")");return A?ve("NOT ",F):F}};return a};class so extends y{constructor(i="unique() found more than one matching document"){super("NOT_UNIQUE",i,{name:"NotUniqueError"})}}const co=/\s/u,ao=String.fromCodePoint(0),Jt=(n,i,r)=>{if(!n.tables[i])throw new y("INTERNAL",`unknown table: ${i}`);return typeof r!="string"||r.length===0||co.test(r)||r.includes(ao)?null:r},fn=(n,i,r,a=()=>{},s=()=>{},w=()=>{},A)=>{const T=i.tables[r];if(!T)throw new y("INTERNAL",`unknown table: ${r}`);const b=Re(T.softDeleteMode,void 0),g=A??{indexFields:[],indexName:void 0,inMemoryFilters:[],order:"asc",sqlConditions:[],verifyFilters:[]},k=()=>{const $=N(b,g.pushedWhere);return $?X($,fe):void 0},v=()=>{const $=N(b,g.pushedWhere);return $?X($,Ke,je):void 0},C=()=>[...g.inMemoryFilters,...g.verifyFilters];let x=0;const U=$=>{const{search:I}=g;if(!I)throw new y("INTERNAL","runSearchFetch called without a staged search");xn(n,r,T);const M=g.inMemoryFilters.length>0,D=br(M?void 0:$),Q=Bn(n);if(Q&&!bn(n,r,I.definition))throw new y("SEARCH_INDEX_BUILDING",`search index "${I.indexName}" on table "${r}" is still backfilling and currently covers only part of the table — retry once it finishes, or run the backfillSearch admin operation to complete it now`);const ge=k(),ie=Q?Xr(n,r,I,D,ge):Zr(n,r,I,D,ge);!M&&$===void 0&&Tr(ie);const re=C();return x=ie.length,re.length>0?un(ie,re,$,se=>se.document):ie},q=$=>U($).map(I=>I.document),F=$=>{const I=Cr($);return xr(q(vr(I)),I)},W=()=>{if(g.search||g.geo||g.indexName===void 0){s(void 0);return}s(ir(r,g.indexName,g.indexFields,g.sqlConditions,Ae))},j=$=>{W();let I=0;const M=(()=>{if(g.search){const D=q($);return I=x,D}return g.geo?Qt(n,r,g,k(),C(),$,D=>{I=D}).map(D=>D.document):at(n,r,T,g,v(),{filters:C(),selective:g.inMemoryFilters.length>0,want:$===void 0?void 0:Math.max(0,Math.floor($))},D=>{I+=D}).documents})();return w(Math.max(I,M.length)),M},L=()=>{if(!g.search&&!g.geo)throw new y("INTERNAL",`ctx.db.query("${r}").collectWithScores() requires a staged .withSearchIndex(...) or .withGeoIndex(...)`);W();let $=0;const I=(()=>{if(g.search){const M=U(void 0);return $=x,M}return Qt(n,r,g,k(),C(),void 0,M=>{$=M})})();return w(Math.max($,I.length)),I},J={async*[Symbol.asyncIterator](){const $=fn(n,i,r,a,s,w,{...g,indexFields:[...g.indexFields],inMemoryFilters:[...g.inMemoryFilters],sqlConditions:[...g.sqlConditions],verifyFilters:[...g.verifyFilters]});if(g.search){yield*await $.collect();return}let I;for(;;){const M=await $.paginate({cursor:I??null,numItems:Jr});if(yield*M.page,M.isDone||M.continueCursor===null)return;I=M.continueCursor}},async collect(){return j(void 0)},async collectWithScores(){return L()},filter($){const I=sr($);return I!==void 0&&cr(I,T.shape)?(g.pushedWhere=N(g.pushedWhere,I),g.verifyFilters.push($)):g.inMemoryFilters.push($),J},async first(){return j(1)[0]??null},order($){return g.order=$==="desc"?"desc":"asc",J},async paginate($){let I=0;if(W(),g.search){const D=F($);return w(D.page.length),D}if(g.geo)throw new y("INTERNAL","pagination is not supported on geo queries; use .take(n) or .collect()");const M=Pr(n,r,T,g,$,v(),{all:C(),selective:g.inMemoryFilters.length>0},D=>{I+=D});return w(Math.max(I,M.page.length)),M},async take($){return j($)},async unique(){const $=j(2);if($.length>1)throw new so(`unique() on table "${r}" matched ${String($.length)} documents; expected at most one`);return $[0]??null},withGeoIndex($,I){const M=(T.geoIndexes??[]).find(Q=>Q.name===$);if(!M)throw new y("INTERNAL",`unknown geo index "${$}" on table "${r}"`);a(r,$,"geo");const D={definition:M,indexName:$};if(g.geo=D,I(eo(D,r)),!D.near&&!D.within)throw new y("INTERNAL",`geo index "${$}" on table "${r}" requires a .near(point, radius) or .within(box) call`);return J},withIndex($,I){const M=T.indexes.find(D=>D.name===$);if(!M)throw new y("INTERNAL",`unknown index "${$}" on table "${r}"`);return a(r,$,"index"),g.indexName=$,g.indexFields=M.fields,I&&I(zr(g)),J},withSearchIndex($,I){const M=(T.searchIndexes??[]).find(Q=>Q.name===$);if(!M)throw new y("INTERNAL",`unknown search index "${$}" on table "${r}"`);a(r,$,"search");const D={definition:M,field:M.field,filters:[],hasQuery:!1,indexName:$,query:""};if(g.search=D,I(Rr(D,r,lt(M.language))),!D.hasQuery)throw new y("INTERNAL",`search index "${$}" on table "${r}" requires a .search(field, query) call`);return J}};return J},zt=(n,i,r)=>{const a={...i};for(const[s,w]of tn(n)){if(w.serverDefault){a[s]=w.serverDefault({auth:r});continue}a[s]===void 0&&(w.defaultFn?a[s]=w.defaultFn():"defaultValue"in w&&(a[s]=w.defaultValue))}return a},st=(n,i,r,a)=>{const s=r;for(const[w,A]of tn(n)){if(A.serverDefault){w in i&&(s[w]=A.serverDefault({auth:a}));continue}A.onUpdateFn&&!(w in i)&&(s[w]=A.onUpdateFn())}},Yt=5,Xt=(n,i)=>{for(const r of Object.keys(i))if(i[r]===void 0)throw new y("INTERNAL",`Cannot ${n} field '${r}' to undefined — use null to clear a nullable field, or omit the key to leave it unchanged.`)},Zt=["_commitSeq","_creationTime","_id"],Ue=n=>Zt.some(i=>i in n)?Object.fromEntries(Object.entries(n).filter(([i])=>!Zt.includes(i))):n,lo=/unique constraint failed/i,uo=n=>n instanceof Error&&lo.test(n.message),fo=/string or blob too big/iu,ho=(n,i)=>{if(!(!(n instanceof Error)||!fo.test(n.message)))throw new y("PAYLOAD_TOO_LARGE",`document is too large to store in "${i}": a single row cannot exceed the storage engine's per-row ceiling (2 MB on a Durable Object's SQLite). The limit is on the STORED bytes, which are UTF-8, and v.bytes()/v.bigint() columns are stored twice on a shard-local table. Keep the payload in R2 (ctx.storage) and store a reference on the row.`)},dt=(n,i,r,a)=>{try{we(n,r,...a)}catch(s){throw uo(s)?new ae(`unique constraint violation on "${i}"`,"unique"):(ho(s,i),s)}},Oe=(n,i,r,a)=>{if(dt(n,i,r,a),we(n,Gr).one().changed===0)throw new ae(`optimistic concurrency conflict on "${i}" — the row changed during this mutation; refetch and retry`,"occ")},en=(n,i,r,a,s,w,A)=>{const T=[];for(let v=0;v<r.length+1;v+=1){const C=r[v],x=a[v],U=x?.direction==="desc"?"desc":"asc",q=C===void 0||x===void 0?c`${c.identifier(nr)} < ${A}`:rr(C,w[v],U,!1);if(q===void 0)continue;const F=[];for(let j=0;j<v;j+=1)F.push(c`${c.identifier(r[j])} IS ${w[j]}`);F.push(q);const[W]=F;T.push(F.length===1&&W!==void 0?W:c`(${c.join(F,c` AND `)})`)}const b=T.length>0?c.join(T,c` OR `):c`1 = 0`,g=G(n,c`SELECT COUNT(*) AS c FROM ${c.identifier(i)} WHERE ${c.identifier("__partition__")} = ${s} AND (${b})`).one(),k=G(n,c`SELECT COUNT(*) AS c FROM ${c.identifier(i)} WHERE ${c.identifier("__partition__")} = ${s}`).one();return{before:g.c,total:k.c}},Zo=n=>{const{baselineSeq:i,onStalePatchDropped:r}=n,{sql:a}=n,{schema:s}=n,w=n.broadcast??(()=>{}),A=ar(s),T=fr(s,n.inTransaction);let b;const g=()=>n.inTransaction?.()===!0,k=e=>s.tables[e]?.commitOrderedMode!==!0?{}:((b===void 0||!g())&&(b=kn(a)),{[Ln]:b}),v=(e,...t)=>{const o=s.tables[e]?.indexes;if(!o||o.length===0)return;const u=[];for(const h of t)h&&u.push(...or(o,h,Ae));return u.length>0?u:void 0},{headroom:C}=n;let x=!1;const U=async e=>{const t=x;x=!0;try{return await e()}finally{x=t}},q=n.onRead??(()=>{}),F=e=>{xt(s.tables[e])&&q(Bt,Bt)},W=n.onReadRange??(e=>{q(e.table,O)}),j=e=>{F(e.table),W(e)},L=(e,t)=>{t!==void 0&&t!==O&&!x&&C?.recordRead(1),F(e),q(e,t)},J=n.onIndexUse??(()=>{}),$=n.onWrite??(()=>{}),I=e=>{x||C?.recordWrite(e)},M=async e=>{I(e.doc),await $(e)},{cache:D}=n,Q=n.clock??(()=>Date.now()),ge=n.idGenerator??(()=>crypto.randomUUID()),ie=n.scheduler??Tn,{globalDb:re}=n,se=n.auth??{identity:null,userId:null},ht=n.cdc??!1,Qe=ie,hn=yr({scheduler:typeof Qe.list=="function"&&typeof Qe.get=="function"?Qe:void 0,storage:n.storage}),ye=(e,t,o,u)=>{ht&&!xt(s.tables[e])&&Mn(a,Q(),e,t,o,u)},wt=(e,t,o,u)=>{const h=s.tables[e];if(h?.dropStalePatchesMode!==!0||!ht)return!1;const f=i?.();if(f===void 0)return!1;const d=Dn(a,e,t,f);if(d===void 0)return!1;const l=Vn(h,o);return Object.keys(Ue(o)).some(p=>!l.has(p)&&Ct(Dt(d,p))!==Ct(Dt(u,p)))},ce=e=>s.tables[e]?.shardMode?.kind==="global",pt=(e,t)=>{if(ce(e)){if(!re)throw new y("INTERNAL",`cross-backend ${t} for global table '${e}' requires a globalDb writer — pass one to createShardCtxDb({ globalDb })`);return re}return B},Ve=e=>pt(e,"cascade"),K=(e,t)=>{if(ce(e)){if(!re)throw new y("INTERNAL",`${t} on global table '${e}' requires a globalDb writer — pass one to createShardCtxDb({ globalDb })`);return re}},gt=async(e,t,o,u,h)=>{h&&I(o);const f=await e.insert(t,o,u);return w({key:f,op:"insert",row:{...o,_id:f},table:t}),f},Je=(e,t)=>pt(e,"relation load").findMany(e,t),yt=(e,t)=>(ce(e)&&L(e,O),Je(e,t)),wn=e=>!ce(e.table),$t=n.relationExistsPushDown??"auto",Et=$t!=="never",{maxRelationKeys:mt}=n,Ce=(e,t,o)=>lr(e,{fetcher:yt,maxRelationKeys:mt,relationBaseWhere:o,schema:s,tableName:t}),St=async(e,t,o,u)=>{const h=K(e,"relation grouped count");if(h)return L(e,O),wr((_,H)=>h.count(_,H),e,t,o,u);const f=s.tables[e];if(!f)throw new y("INTERNAL",`unknown table: ${e}`);L(e,O);const d=Re(f.softDeleteMode,void 0),l={[t]:{in:o}},p=N(N(l,u),d),R=await Ce(p,e,void 0),E=X(R,fe),S=he(t);let m=c`SELECT ${S} AS __fk__, COUNT(*) AS count FROM ${c.identifier(e)}`;E&&(m=c`${m} WHERE ${E}`),m=c`${m} GROUP BY ${S}`;const P=G(a,m).toArray();return new Map(P.map(_=>[_.__fk__,_.count]))};let xe=0;const _t=new Set;for(const[e,t]of Object.entries(s.tables))for(const o of Object.values(t.triggerMap??{}))_t.add(`${e} ${o.timing} ${o.op}`);const Z=(e,t,o)=>_t.has(`${e} ${t} ${o}`),ee=async(e,t,o)=>{if(xe+=1,xe>Nt)throw xe-=1,new ae(`trigger recursion exceeded ${String(Nt)} levels on "${o.table}" — check for a self-triggering write`,"trigger");try{await $r({ctx:En,event:o,op:t,schema:s,tableName:o.table,timing:e})}finally{xe-=1}},{ensureBackfilledForTable:$e,ensureBackfilledIndex:ze,ensureRankBackfilled:Ye,ensureRankBackfilledForTable:Ee,syncAggregates:be,syncCompanionsForInsert:Rt,syncGeo:Me,syncRanks:me,syncSearch:De}=Fn({broadcast:w,indexKeysFor:(e,t)=>v(e,t),invalidateCache:(e,t,o)=>D?.invalidate(e,t,v(e,o)),recordCdc:ye,schema:s,sql:a}),Tt=(e,t,o)=>{const{shardMode:u}=t;if(u?.kind==="shardBy"&&!(u.field!==void 0&&(o.partitionBy??[]).includes(u.field)))throw Object.assign(new Error(`rank index "${o.name}" on "${e}" partitions across shards (shard key "${u.field??"?"}" is not in partitionBy) — a shard-local rank()/rankPage() would be wrong; roll it up through the Query Coordinator instead`),{code:"CROSS_SHARD_RANK_UNSUPPORTED",name:"LunoraError",status:400})},vt=e=>Object.entries(s.tables).filter(([,t])=>t.shardMode?.kind!=="global").map(([t])=>t).filter(t=>e===void 0||t===e),Se=e=>e===void 0||ce(e)?re:void 0,te=(e,t)=>{const o=vt(t);for(let u=0;u<o.length;u+=_e){const h=o.slice(u,u+_e),[f]=we(a,Kr(h),...Nr(e,h)).toArray();if(!f)continue;const d=f.__t__,l=Te(f);if(typeof d!="string"||!l)return;const p=f[oe];return{docJson:typeof p=="string"?p:le(p??{}),row:l,tableName:d}}},pn=(e,t)=>{const o=[...new Set(e)],u=new Map;if(o.length===0)return u;const h=vt(t);for(let f=0;f<h.length;f+=_e){const d=h.slice(f,f+_e),l=Math.floor(_e/d.length),p=Un(c`${c.identifier("id")}`,o,!1,l),R=d.map(E=>c`SELECT ${c.raw(`'${E.replaceAll("'","''")}'`)} AS __t__, id FROM ${c.identifier(E)} WHERE ${p}`);for(const E of G(a,ut(R))){const{id:S,__t__:m}=E;typeof m=="string"&&typeof S=="string"&&u.set(S,m)}}return u},At={assertRankPartitionLocal:Tt,ensureRankBackfilled:Ye,onRead:L,rowToDocument:Te,schema:s,sql:a},gn=(e,t,o)=>{const u=X(o,fe);return u===void 0||G(a,c`SELECT 1 FROM ${c.identifier(e)} WHERE ${c.identifier("id")} = ${t} AND ${u}`).toArray().length>0},yn=(e,t,o,u)=>wt(e,t,o,u)?(r?.({fields:Object.keys(Ue(o)),id:t,table:e}),!0):!1,$n=async(e,t,o,u,h)=>{const f=te(t,e);if(!f)return{applied:!1,doc:null};if(L(e,t),!gn(e,t,o.where)||yn(e,t,o.patch,f.row))return{applied:!1,doc:f.row};try{await h(o.patch)}catch(d){if(d instanceof ae&&d.kind==="occ"&&u)return;throw d}return{applied:!0,doc:te(t,e)?.row??null}},It=async(e,t,o,u)=>{const{fetchLimit:h,limit:f,orderKeys:d,predicate:l}=await ur(t,o,{canPushExists:Et?wn:void 0,existsPushMode:$t==="always"?"always":"auto",fetcher:yt,maxRelationKeys:mt,schema:s,tableName:e}),p=Et?io(u):Ke,R=X(l,p,je),E=sn(e,R,cn(d),h);return{limit:f,orderKeys:d,statement:E}},B={system:hn,async aggregate(e,t){const o=K(e,"aggregate");if(o)return L(e,O),o.aggregate(e,t);const u=s.tables[e];if(!u)throw new y("INTERNAL",`unknown table: ${e}`);if(qe(t.op),t.op==="count")return B.count(e,{baseWhere:t.baseWhere,relationBaseWhere:t.relationBaseWhere,restrictsCounts:t.restrictsCounts,where:t.where});if(!t.field)throw new y("INTERNAL",`aggregate(${e}, { op: "${t.op}" }): "field" is required for non-count reducers`);L(e,O);const h=Re(u.softDeleteMode,void 0),f=N(N(t.baseWhere,t.where),h),d=await Ce(f,e,t.relationBaseWhere),l=d!==f;if(u.aggregateIndexes&&!t.baseWhere&&!l){const _=Cn(u.aggregateIndexes,t.op,t.field,t.where);if(_){ze(e,_.index);const H=Ze(_.index.by??[],_.key),ne=Xe(e,_.index.name),Y=G(a,c`SELECT ${We} AS value, ${nt} AS count FROM ${c.identifier(ne)} WHERE ${Be} = ${H}`).toArray()[0];return et(t.op,Y)}}Vt(u,t.field,`aggregate(${e}, { op: "${t.op}", field: "${t.field}" })`);const p=X(d,fe),R=qe(t.op),E=he(t.field);let S=c`SELECT ${c.raw(R)}(${E}) AS value FROM ${c.identifier(e)}`;p&&(S=c`${S} WHERE ${p}`);const P=G(a,S).toArray()[0]?.value;return P??null},asId(e,t){const o=Jt(s,e,t);if(o===null)throw new y("BAD_REQUEST",`asId("${e}", …): "${t}" is not a valid id for table "${e}"`,{status:400});return o},async count(e,t){const o=K(e,"count");if(o)return L(e,O),o.count(e,t);const u=s.tables[e];if(!u)throw new y("INTERNAL",`unknown table: ${e}`);const h=vn(t);if(h.restrictsCounts)throw new tt(e);L(e,O);const f=Re(u.softDeleteMode,void 0),d=N(N(h.baseWhere,h.where),f),l=await Ce(d,e,h.relationBaseWhere),p=l!==d;if(u.aggregateIndexes&&!h.baseWhere&&!p){const m=In(u.aggregateIndexes,h.where);if(m){ze(e,m.index);const P=Ze(m.index.by??[],m.key),_=Xe(e,m.index.name),H=G(a,c`SELECT ${We} AS value FROM ${c.identifier(_)} WHERE ${Be} = ${P}`).toArray();return H[0]===void 0?0:H[0].value??0}}const R=X(l,fe);let E=c`SELECT COUNT(*) AS count FROM ${c.identifier(e)}`;return R&&(E=c`${E} WHERE ${R}`),G(a,E).one().count},async delete(e,t,o){const u=te(e,t);if(!u){const S=Se(t);S&&(I(void 0),await S.delete(e,t,o));return}const{docJson:h,row:f,tableName:d}=u,l=s.tables[d],p=o?.hard===!0,R=!p&&l?.softDeleteMode?l:void 0,E=R?.softDeleteMode?.field;if(!(E&&f[E]!==null&&f[E]!==void 0)){if(Z(d,"before","delete")&&await ee("before","delete",{id:e,op:"delete",previous:f,table:d}),await hr({deletedId:e,deletedReference:S=>f[S],findHolders:async(S,m,P)=>(await Ve(S).findMany(S,{includeDeleted:p,where:{[m]:P}})).page,onCascade:(S,m)=>Ve(S).delete(m,void 0,o),onRestrict:S=>{throw new ae(S,"restrict")},onSetNull:(S,m,P)=>Ve(S).patch(m,{[P]:null}),schema:s,tableName:d}),$e(d),Ee(d),R&&E){const S={[E]:Q()},m={...f,...k(d),...S,_id:e};st(R,S,m,se),Oe(a,d,jt(d),[le(m),e,h]),De(d,e,m,f),Me(d,e,void 0),be(d,f,m),me(d,e,f,void 0),D?.invalidate(d,e,v(d,f,m)),ye(d,e,"update",m),w({indexKeys:v(d,f,m),key:e,op:"update",row:m,table:d}),Z(d,"after","delete")&&await ee("after","delete",{id:e,op:"delete",previous:f,table:d}),await M({id:e,op:"delete",table:d});return}Oe(a,d,Hr(d),[e,h]),De(d,e,void 0),Me(d,e,void 0),be(d,f,void 0),me(d,e,f,void 0),D?.invalidate(d,e,v(d,f)),ye(d,e,"delete"),w({indexKeys:v(d,f),key:e,op:"delete",table:d}),Z(d,"after","delete")&&await ee("after","delete",{id:e,op:"delete",previous:f,table:d}),await M({id:e,op:"delete",table:d})}},async deleteAll(e,t){if(!s.tables[e])throw new y("INTERNAL",`unknown table: ${e}`);const o=Math.max(1,t?.chunkSize??dn),u=t?.hard===void 0?void 0:{hard:t.hard},h=ce(e)?void 0:e;let f=0;return await U(async()=>{for(;;){const l=(await B.findMany(e,{limit:o})).page.map(p=>String(p._id));if(l.length===0)break;for(const p of l)await B.delete(p,h,u),f+=1;if(l.length<o)break}}),{deleted:f}},async deleteMany(e,t,o){ue(e.length,t?.limit,"deleteMany");for(const u of e)await B.delete(u,o);return{deleted:e.length}},async deleteWhere(e,t,o){const f=(await(K(e,"deleteWhere")??B).findMany(e,{where:t})).page.map(d=>String(d._id));if(ue(f.length,o?.limit,"deleteWhere"),B.deleteMany===void 0)throw new y("INTERNAL",`ctx.db.${e}.deleteMany is unavailable: this writer has no batch delete`);return B.deleteMany(f,o)},async findFirst(e,t={}){return(await B.findMany(e,{...t,limit:1,omitContinueCursor:!0})).page[0]??null},async findFirstOrThrow(e,t={}){const o=await B.findFirst(e,t);if(o===null)throw new Kn(`findFirstOrThrow: no "${e}" document matched`);return o},async findMany(e,t={}){const o=K(e,"findMany");if(o)return L(e,O),o.findMany(e,t);const u=s.tables[e];if(!u)throw new y("INTERNAL",`unknown table: ${e}`);const h=!t.where&&!t.baseWhere;h?L(e,O):L(e);const{limit:f,orderKeys:d,statement:l}=await It(e,u,t,L),p=we(a,l.text,...l.params).toArray();h&&!x&&C?.recordRead(p.length);const R=[];for(const P of p){const _=Te(P);_&&(R.push(_),!h&&typeof _._id=="string"&&L(e,_._id))}if(f===void 0)return t.with&&await Ut({groupedCounter:St,fetcher:Je,parents:R,...Ot(t),schema:s,tableName:e,with:t.with}),{continueCursor:null,isDone:!0,page:Ft(R,t.select,t.with)};const E=R.length>f,S=E?R.slice(0,f):R,m=S.at(-1);return t.with&&await Ut({fetcher:Je,groupedCounter:St,parents:S,...Ot(t),schema:s,tableName:e,with:t.with}),{continueCursor:E&&m&&t.omitContinueCursor!==!0?He(m,d):null,isDone:!E,page:Ft(S,t.select,t.with)}},async explain(e,t={}){const o=K(e,"explain");if(o)return o.explain(e,t);const u=s.tables[e];if(!u)throw new y("INTERNAL",`unknown table: ${e}`);const{statement:h}=await It(e,u,t,()=>{}),f=we(a,`EXPLAIN QUERY PLAN ${h.text}`,...h.params).toArray();return{params:h.params,plan:f.map(d=>String(d.detail)),sql:h.text}},async get(e,t){const o=te(e,t);if(!o){const u=Se(t);return u?u.get(e,t):null}return L(o.tableName,e),o.row},async lookupById(e,t){const o=te(e,t);return o?(L(o.tableName,e),{row:o.row,tableName:o.tableName}):null},async groupBy(e,t){const o=K(e,"groupBy");if(o)return L(e,O),o.groupBy(e,t);const u=s.tables[e];if(!u)throw new y("INTERNAL",`unknown table: ${e}`);L(e,O);const h=t.agg??{op:"count"};if(qe(h.op),h.op!=="count"&&!h.field)throw new y("INTERNAL",`groupBy(${e}, { agg: { op: "${h.op}" } }): "field" is required for non-count reducers`);const f=Re(u.softDeleteMode,void 0),d=N(N(t.baseWhere,t.where),f),l=await Ce(d,e,t.relationBaseWhere),p=l!==d;if(u.aggregateIndexes&&!t.baseWhere&&!p){const _=An(u.aggregateIndexes,h.op,h.field,t.by,t.where),H=_===void 0?0:Object.keys(_.partial).length,ne=_?.index.by?.length??0;if(_&&(H===0||H===ne)){ze(e,_.index);const Y=Xe(e,_.index.name),V=Object.keys(_.partial),de=[];if(V.length===(_.index.by??[]).length&&V.length>0){const ke=Ze(_.index.by??[],_.partial),Le=G(a,c`SELECT ${We} AS value, ${nt} AS count FROM ${c.identifier(Y)} WHERE ${Be} = ${ke}`).toArray();return Le.length>0&&de.push({key:{..._.partial},value:et(h.op,Le[0])}),de}const mn=G(a,c`SELECT ${Be} AS key, ${We} AS value, ${nt} AS count FROM ${c.identifier(Y)}`).toArray();for(const ke of mn){const Le=Rn(JSON.parse(ke.key));de.push({key:Le,value:et(h.op,ke)})}return de}}for(const _ of[...t.by,h.field]){if(_===void 0)continue;const H=_===h.field?`groupBy(${e}, { agg: { op: "${h.op}", field: "${_}" } })`:`groupBy(${e}, { by: [..."${_}"] })`;Vt(u,_,H)}const R=X(l,fe),E=t.by.map(_=>c`${he(_)} AS ${c.identifier(_)}`);if(h.op==="count")E.push(c`COUNT(*) AS value`);else{const{field:_}=h;if(_===void 0)throw new y("INTERNAL",`groupBy(${e}, { agg: { op: "${h.op}" } }): "field" is required for non-count reducers`);E.push(c`${c.raw(qe(h.op))}(${he(_)}) AS value`)}let S=c`SELECT ${c.join(E,c`, `)} FROM ${c.identifier(e)}`;R&&(S=c`${S} WHERE ${R}`),S=c`${S} GROUP BY ${c.join(t.by.map(_=>he(_)),c`, `)}`;const m=G(a,S).toArray(),P=[];for(const _ of m){const H={};for(const Y of t.by)H[Y]=Wn(u.shape[Y],_[Y]??null);const{value:ne}=_;P.push({key:H,value:ne==null?null:Number(ne)})}return P},async insert(e,t,o){const u=K(e,"insert");if(u)return gt(u,e,t,o,!0);const h=s.tables[e];if(!h)throw new y("INTERNAL",`unknown table: ${e}`);const f=zt(h,t,se);ot(h,f);let d;o?.clientId!==void 0?(Vr(o.clientId),d=o.clientId):o?.allowExplicitId&&typeof f._id=="string"?d=f._id:d=ge();const l=o?.allowExplicitId&&typeof f._creationTime=="number"?f._creationTime:Q(),p={...f,...k(e),_creationTime:l,_id:d};return Z(e,"before","insert")&&await ee("before","insert",{doc:{...p},id:d,op:"insert",table:e}),$e(e),Ee(e),dt(a,e,Ur(e),[d,l,le(p)]),Rt(e,d,p),Z(e,"after","insert")&&await ee("after","insert",{doc:p,id:d,op:"insert",table:e}),await M({doc:p,id:d,op:"insert",table:e}),d},async insertManyUnsafe(e,t,o){if(ue(t.length,o?.limit,"insertManyUnsafe"),t.length===0)return[];const u=K(e,"insert");if(u){const l=[];for(const p of t)I(p);for(const p of t){const R=await u.insert(e,p,{allowExplicitId:o?.allowExplicitId});w({key:R,op:"insert",row:{...p,_id:R},table:e}),l.push(R)}return l}const h=s.tables[e];if(!h)throw new y("INTERNAL",`unknown table: ${e}`);$e(e),Ee(e);const f=[];for(let l=0;l<t.length;l+=Pe)f.push(k(e));const d=t.map((l,p)=>{const R=zt(h,l,se),E=o?.allowExplicitId===!0&&typeof R._id=="string"?R._id:ge(),S=o?.allowExplicitId===!0&&typeof R._creationTime=="number"?R._creationTime:Q(),m={...R,...f[Math.floor(p/Pe)],_creationTime:S,_id:E};return{creationTime:S,document:m,id:E}});for(const l of d)I(l.document);for(let l=0;l<d.length;l+=Pe){const p=c.join(d.slice(l,l+Pe).map(E=>c`(${E.id}, ${E.creationTime}, ${le(E.document)})`),c`, `),R=rn("sqlite",c`INSERT INTO ${c.identifier(e)} (id, _creationTime, ${c.identifier(oe)}) VALUES ${p}`);dt(a,e,R.sql,R.params)}for(const{document:l,id:p}of d)Rt(e,p,l),await $({doc:l,id:p,op:"insert",table:e});return d.map(l=>l.id)},async insertMany(e,t,o){ue(t.length,o?.limit,"insertMany");const u=o?.skipDuplicates===!0,h=[],f=K(e,"insert");if(f)for(const l of t)I(l);const d=async l=>f?gt(f,e,l,void 0,!1):B.insert(e,l);for(const l of t)try{h.push(await d(l))}catch(p){if(u&&p instanceof ae&&p.kind==="unique")h.push(null);else throw p}return h},normalizeId(e,t){return Jt(s,e,t)},async patch(e,t,o,u){const h=te(e,o);if(!h){const S=Se(o);if(S){I(t),await S.patch(e,t,o,u);return}throw new y("NOT_FOUND",`document not found: ${e}`)}const{docJson:f,row:d,tableName:l}=h,p=s.tables[l];if(!p)throw new y("INTERNAL",`unknown table: ${l}`);if(L(l,e),Xt("patch",t),wt(l,e,t,d)){r?.({fields:Object.keys(Ue(t)),id:e,table:l});return}const R=Nn(p,t,d),E={...d,...Ue(R),...k(l),_id:e};st(p,R,E,se),Qn(u,d,E),ot(p,E,!0),Z(l,"before","update")&&await ee("before","update",{doc:{...E},id:e,op:"update",previous:d,table:l}),$e(l),Ee(l),Oe(a,l,jt(l),[le(E),e,f]),De(l,e,E,d),Me(l,e,E),be(l,d,E),me(l,e,d,E),D?.invalidate(l,e,v(l,d,E)),ye(l,e,"update",E),w({indexKeys:v(l,d,E),key:e,op:"update",row:E,table:l}),Z(l,"after","update")&&await ee("after","update",{doc:E,id:e,op:"update",previous:d,table:l}),await M({doc:E,id:e,op:"update",table:l})},async patchIf(e,t,o){const u=K(e,"patchIf");if(u){if(u.patchIf===void 0)throw new y("INTERNAL",`ctx.db.patchIf on global table '${e}' is unsupported: its backend has no conditional write`);return I(o.patch),u.patchIf(e,t,o)}if(!s.tables[e])throw new y("INTERNAL",`unknown table: ${e}`);for(let h=1;h<=Yt;h+=1){const f=await $n(e,t,o,h<Yt,d=>B.patch(t,d,e,{verify:o.verify}));if(f!==void 0)return f}throw new ae(`patchIf on "${e}" kept conflicting; the row changed on every attempt`,"occ")},async patchMany(e,t,o){ue(e.length,t?.limit,"patchMany");for(const u of e)await B.patch(u.id,u.patch,o);return{patched:e.length}},async patchWhere(e,t,o){const f=(await(K(e,"patchWhere")??B).findMany(e,{where:t.where})).page.map(d=>({id:String(d._id),patch:t.patch}));if(ue(f.length,o?.limit,"patchWhere"),B.patchMany===void 0)throw new y("INTERNAL",`ctx.db.${e}.patchMany is unavailable: this writer has no batch patch`);return await B.patchMany(f,o),{patched:f.length}},async related(e,t){return dr(B,A,e,t)},relationEdges:A,relationWrites:T,query(e){const t=K(e,"query");return t?(L(e,O),t.query(e)):fn(a,s,e,J,o=>{o?j(o):L(e,O)},o=>{x||C?.recordRead(o)})},async rank(e,t,o){const u=K(e,"rank");if(u)return L(e,O),u.rank(e,t,o);J(e,t,"rank");const h=s.tables[e];if(!h)throw new y("INTERNAL",`unknown table: ${e}`);const f=h.rankIndexes?.find(V=>V.name===t);if(!f)throw new y("INTERNAL",`unknown rankIndex "${t}" on table "${e}"`);if(Tt(e,h,f),o.restrictsCounts)throw new tt(e);L(e,O),Ye(e,f);const d=typeof o.row=="string"?o.row:o.row._id;if(!d)return null;const l=qt(e,f.name),p=f.sortBy.map((V,de)=>Wt(de)),R=p.map(V=>Ie(V)).join(", "),E=G(a,c`SELECT ${c.identifier("__partition__")}, ${c.raw(R)} FROM ${c.identifier(l)} WHERE ${c.identifier("__id__")} = ${d}`).toArray(),[S]=E;if(S===void 0)return null;let m=S.__partition__;const P=N(o.baseWhere,o.where);rt(P,s,e,"rank");const _=er(f,P);if(_){const V=tr(f.partitionBy??[],_);if(V!==m)return null;m=V}const H=p.map(V=>S[V]),{before:ne,total:Y}=en(a,l,p,f.sortBy,m,H,d);return{position:ne+1,total:Y}},async rankBefore(e,t,o){if(ce(e))throw new y("INTERNAL",`rankBefore is not supported on the global (.global()) table '${e}' — cross-shard rank cursors apply only to sharded tables`);const u=s.tables[e];if(!u)throw new y("INTERNAL",`unknown table: ${e}`);const h=u.rankIndexes?.find(p=>p.name===t);if(!h)throw new y("INTERNAL",`unknown rankIndex "${t}" on table "${e}"`);if(o.restrictsCounts)throw new tt(e);L(e,O),Ye(e,h);const f=qt(e,h.name),d=h.sortBy.map((p,R)=>Wt(R)),l=h.sortBy.map((p,R)=>Ae(o.sortValues[R]??null));return en(a,f,d,h.sortBy,o.partitionKey,l,o.rowId)},async rankPage(e,t,o={}){rt(N(o.baseWhere,o.where),s,e,"rankPage");const u=K(e,"rankPage");if(u)return L(e,O),u.rankPage(e,t,o);J(e,t,"rank");const{continueCursor:h,hasMore:f,rows:d}=bt(At,e,t,o);return{continueCursor:h,isDone:!f,page:d.map(l=>l.doc)}},async rankPageRows(e,t,o={}){rt(N(o.baseWhere,o.where),s,e,"rankPage"),J(e,t,"rank");const{directions:u,hasMore:h,rows:f}=bt(At,e,t,o);return{directions:u,hasMore:h,rows:f}},async restore(e,t){const o=te(e,t);if(!o){const f=Se(t);if(f?.restore){await f.restore(e,t);return}throw new y("NOT_FOUND",`document not found: ${e}`)}const u=s.tables[o.tableName]?.softDeleteMode?.field;if(!u)throw new y("INTERNAL",`ctx.db.restore: table "${o.tableName}" is not a .softDelete() table`);const h=o.row[u]!==null&&o.row[u]!==void 0;await B.patch(e,{[u]:null},t),h&&me(o.tableName,e,void 0,o.row)},async replace(e,t,o,u){const h=te(e,o);if(!h){const P=Se(o);if(P){I(t),await P.replace(e,t,o,u);return}throw new y("NOT_FOUND",`document not found: ${e}`)}const{docJson:f,row:d,tableName:l}=h,p=s.tables[l];if(!p)throw new y("INTERNAL",`unknown table: ${l}`);Xt("replace",t);const R=u?.allowExplicitId&&typeof t._creationTime=="number"?t._creationTime:void 0,E=typeof d._creationTime=="number"?d._creationTime:void 0,S=R??E??Q(),m={...t,...k(l),_creationTime:S,_id:e};st(p,t,m,se),ot(p,m),Z(l,"before","update")&&await ee("before","update",{doc:{...m},id:e,op:"update",previous:d,table:l}),$e(l),Ee(l),Oe(a,l,Or(l),[S,le(m),e,f]),De(l,e,m,d),Me(l,e,m),be(l,d,m),me(l,e,d,m),D?.invalidate(l,e,v(l,d,m)),ye(l,e,"update",m),w({indexKeys:v(l,d,m),key:e,op:"update",row:m,table:l}),Z(l,"after","update")&&await ee("after","update",{doc:m,id:e,op:"update",previous:d,table:l}),await M({doc:m,id:e,op:"update",table:l})},async wipeShard(e){const t=new Set(e?.exclude),o=e?.tables,u=Object.entries(s.tables).filter(([l,p])=>t.has(l)||o!==void 0&&!o.includes(l)?!1:p.shardMode?.kind!=="global").map(([l])=>l);if(o!==void 0){for(const l of o)if(!s.tables[l])throw new y("INTERNAL",`wipeShard: unknown table: ${l}`)}const h={};let f=0;const{deleteAll:d}=B;if(d===void 0)throw new y("INTERNAL","wipeShard: this writer has no deleteAll");for(const l of u){const p=await d(l,{...e?.chunkSize===void 0?{}:{chunkSize:e.chunkSize},hard:!0});h[l]=p.deleted,f+=p.deleted}return{deleted:f,tables:h}}},En={db:B,scheduler:ie};return n.enforceRls===!0?pr(B,s,(e,t)=>te(e,t)?.tableName,(e,t)=>pn(e,t),A):B};export{si as CDC_LOG_TABLE,Ci as IDEMPOTENCY_TABLE,so as NotUniqueError,Ti as advanceClientWatermark,ci as applyCdcChanges,Xt as assertNoExplicitUndefined,Vr as assertValidClientId,ni as backfillAggregateIndexes,ri as backfillRankIndexes,oi as backfillSearchIndexes,ai as bumpCdcEpoch,di as cdcCanVouchFor,li as cdcForkedError,ui as cdcSeqLeavingRows,fi as cdcTouchesTables,hi as cdcTrimmedError,wi as compactCdcDocs,Zo as createShardCtxDb,pi as cursorBelowRetainedFloor,vi as migrateClientWatermark,gi as minCdcReplayableSeq,yi as minCdcSeq,Jt as normalizeIdStructurally,$i as readCdcChangeKeys,Ei as readCdcChanges,mi as readCdcCursor,Si as readCdcEpoch,Ai as readClientWatermark,xi as readIdempotent,ki as runShardMigrations,Fi as selectShapeMembers,qi as selectShapeRows,Ue as stripReservedPatchFields,_i as trimCdcChanges,bi as trimIdempotent,Mi as writeIdempotent};
|
|
1
|
+
import{LunoraError as y}from"@lunora/errors";import{D as lt}from"./MAX_TOKEN_LENGTH-BakL9FUy-B3VwYY8C.mjs";import{S as Sn,l as Fe,h as _n}from"./fts-companion-pUdD6kF-.mjs";import{sql as c}from"drizzle-orm";import{d as Rn}from"./wire-codec-BYCSiazv.mjs";import{stableWireKey as Ct}from"./stableWireKey-Bdh5JSdg.mjs";import{throwingScheduler as Tn,aggregateSqlFunction as qe,normalizeCountArgument as vn}from"./AGGREGATE_SQL_FUNCTION-BMtvQHac.mjs";import{aggregateTableName as Xe,encodeAggregateKey as Ze,readAggregateValue as et}from"./aggregateTableName-DbAttCNH.mjs";import{mergeWhere as N,CountRlsUnsupportedError as tt,selectIndexForGroupBy as An,selectIndexForCount as In,selectIndexForAggregate as Cn}from"./CountRlsUnsupportedError-BvsDqfO2.mjs";import{backfillSearchIndexesForTable as xn,searchIndexCoversTable as bn}from"./backfillAggregateIndexes-CJrtolQ9.mjs";import{backfillAggregateIndexes as ni,backfillRankIndexes as ri,backfillSearchIndexes as oi}from"./backfillAggregateIndexes-CJrtolQ9.mjs";import{appendCdcChange as Mn,readCdcDocAtOrBefore as Dn}from"./CDC_LOG_TABLE-BPEzVAil.mjs";import{CDC_LOG_TABLE as si,applyCdcChanges as ci,bumpCdcEpoch as ai,cdcCanVouchFor as di,cdcForkedError as li,cdcSeqLeavingRows as ui,cdcTouchesTables as fi,cdcTrimmedError as hi,compactCdcDocs as wi,cursorBelowRetainedFloor as pi,minCdcReplayableSeq as gi,minCdcSeq as yi,readCdcChangeKeys as $i,readCdcChanges as Ei,readCdcCursor as mi,readCdcEpoch as Si,trimCdcChanges as _i}from"./CDC_LOG_TABLE-BPEzVAil.mjs";import{allocateCommitSeq as kn,COMMIT_SEQ_FIELD as Ln}from"./COMMIT_SEQ_FIELD-BY_vc9bw.mjs";import{createCompanionSync as Fn}from"./createCompanionSync-B7dV2y4L.mjs";import{isMemoryTable as xt}from"./clearMemoryTables-CogAvVHR.mjs";import{computeRankPage as bt}from"./computeRankPage-CFeFkZ_k.mjs";import{SCAN_DEP as O}from"./SCAN_DEP-D7qE3iUe.mjs";import{runSql as we,runDrizzle as G}from"./runDrizzle-Du5HLitO.mjs";import{p as qn,j as ct,D as oe,r as Te,k as le,b as We,A as nt,a as Be,m as fe,e as he,s as Wn,t as tn,i as Bn,q as Mt,h as nn,g as Pn}from"./do-sql-Cg3zXJpF.mjs";import{renderSql as rn,unionAll as ut,WORKERD_SQLITE_LIMITS as on,sqliteInList as Un}from"./WORKERD_SQLITE_LIMITS-DBH23L_S.mjs";import{coveringGeohashes as On,boundingBoxGeohashes as Hn,haversineMeters as Gn,pointInBoundingBox as jn}from"./GEO_DEFAULT_PRECISION-CqpQZ-J_.mjs";import{NotFoundError as Kn}from"./NotFoundError-BhF7FeFr.mjs";import{resolvePatch as Nn,assertPatchAllowed as Qn,operatorFields as Vn,readPatchField as Dt}from"./assertPatchAllowed-BJ_2LgkQ.mjs";import{tiebreakDirectionFor as Jn,encodeCursor as He,nullsOrderSuffix as zn,normalizeOrderKeys as kt,uniqueIndexFields as Yn,buildSeekWhere as Xn,decodeCursor as Lt,buildSeekBeforeWhere as Zn,softDeleteScope as Re,applySelect as Ft}from"./CURSOR_PREFIX-BztyXqNP.mjs";import{rankTableName as qt,sortColumnName as Wt,resolveRankPartition as er,encodePartitionKey as tr,RANK_TIEBREAK as nr,rankPivotConditionSql as rr}from"./RANK_TIEBREAK-BKugKf70.mjs";import{UNVOUCHABLE_DEP as Bt}from"./UNVOUCHABLE_DEP-C68htACn.mjs";import{indexKeysForRow as or,buildIndexRange as ir}from"./buildIndexRange-6nIZDf4m.mjs";import{r as Ge,j as ve,c as X,t as je,i as Pt}from"./where-sql-Dn9trjRu.mjs";import{serializeSqlValue as Ae}from"./serializeSqlValue-BbZ5hKM7.mjs";import{quoteIdentifier as Ie}from"./quoteIdentifier-CObIFRhb.mjs";import{whereOfFilter as sr,isPushableWhere as cr}from"./isPushableWhere-BeYAOjUb.mjs";import{deriveRelationEdges as ar,findRelated as dr}from"./RELATED_DEFAULT_LIMIT-Me5elP-K.mjs";import{assertFlatPredicate as rt,resolveRelationPredicates as lr,composeReadPredicate as ur}from"./DEFAULT_MAX_RELATION_KEYS-Bk8B9GIQ.mjs";import{describeRelationWrites as fr}from"./describeRelationWrites-omar6-u9.mjs";import{runRowValidators as ot,resolveWith as Ut,relationHooks as Ot,applyOnDelete as hr,fanOutScalarCounts as wr}from"./applyOnDelete-CGVYKtaW.mjs";import{guardWriter as pr}from"./RLS_UNWRAP_SYMBOL-qYcAxjuk.mjs";import{mayHoldProjectedValue as gr}from"./BIGINT_KEY_DIGITS-C9a7Ix7k.mjs";import{createSystemReader as yr}from"./createSystemReader-DcDLFfC-.mjs";import{ConflictError as ae}from"./ConflictError-C8GtJmjS.mjs";import{runTriggers as $r}from"./hasTrigger-CjlwI4le.mjs";import{advanceClientWatermark as Ti,migrateClientWatermark as vi,readClientWatermark as Ai}from"./CLIENT_WATERMARK_TABLE-vLjfNhBR.mjs";import{IDEMPOTENCY_TABLE as Ci,readIdempotent as xi,trimIdempotent as bi,writeIdempotent as Mi}from"./IDEMPOTENCY_TABLE-AOJCuq5U.mjs";import{runShardMigrations as ki}from"./runShardMigrations-eqHNBW6S.mjs";import{selectShapeMembers as Fi,selectShapeRows as qi}from"./selectShapeMembers-CU8Kl2Bq.mjs";const Er=n=>{const i=atob(n),r=Uint8Array.from(i,a=>a.codePointAt(0)??0);return new TextDecoder().decode(r)},mr=()=>new y("BAD_REQUEST","invalid cursor"),Ht=16,Gt=8,z=1024,ft=(n,i)=>i.query(n),Sr=(n,i)=>{if(n.length===0)return 0;let r=0;for(const[a,s]of i.entries()){const w=a===i.length-1;let A=0;for(const T of n)(w?T.startsWith(s):T===s)&&(A+=1);if(A===0)return 0;r+=A}return r},_r=(n,i)=>{if(!i)return{exact:!0,lower:n,upper:n};const r=[...n].at(-1)??"",a=(r.codePointAt(0)??0)+1;if(a>=55296&&a<=57343||a>1114111)return{exact:!0,lower:n,upper:n};const s=n.slice(0,n.length-r.length);return{exact:!1,lower:n,upper:s+String.fromCodePoint(a)}},Rr=(n,i,r)=>{const a={eq:(s,w)=>{if(!n.definition.filterFields?.includes(s))throw new y("INTERNAL",`field "${s}" is not a filter field of search index "${n.indexName}" on table "${i}"`);if(n.filters.length>=Gt)throw new y("BAD_REQUEST",`search index "${n.indexName}" on table "${i}": at most ${String(Gt)} .eq() filters are supported per search query`);return n.filters.push({field:s,value:w}),a},search:(s,w)=>{const A=n;if(s!==A.definition.field)throw new y("INTERNAL",`search index "${A.indexName}" on table "${i}" indexes "${A.definition.field}", not "${s}"`);const T=ft(w,r).length;if(T>Ht)throw new y("BAD_REQUEST",`search index "${A.indexName}" on table "${i}": at most ${String(Ht)} search terms are supported (got ${String(T)})`);return A.field=s,A.query=w,A.hasQuery=!0,a}};return a},Tr=n=>{if(n.length>z)throw new y("BAD_REQUEST",`more than ${String(z)} documents match this search — narrow it with filters or read it a page at a time with .paginate()`)},vr=n=>Math.min(n.offset+n.numItems+1,z),Ar=n=>btoa(`search:${String(n)}`),Ir=n=>{let i;try{i=Er(n)}catch{return}if(!i.startsWith("search:"))return;const r=Number(i.slice(7));return Number.isInteger(r)&&r>=0?r:void 0},Cr=n=>{if(typeof n.endCursor=="string")throw new y("BAD_REQUEST","bounded (endCursor) pagination is not supported on search queries — relevance order has no stable range boundary");if(!Number.isFinite(n.numItems))throw new y("BAD_REQUEST",`search pagination needs a finite numItems, got ${String(n.numItems)}`);const i=Math.max(0,Math.floor(n.numItems)),r=n.cursor?Ir(n.cursor):0;if(r===void 0)throw mr();if(r+i>=z)throw new y("BAD_REQUEST",`search pagination reaches the ${String(z)}-document limit (offset ${String(r)} + ${String(i)} requested) — a page must end below the cap so the probe row that answers \`hasMore\` still fits: retry with numItems ${String(Math.max(1,z-r-1))} or fewer, or narrow the query or the filters instead`);return{numItems:i,offset:r}},xr=(n,i)=>{const r=i.offset+i.numItems,a=i.numItems>0&&n.length>r;return{continueCursor:a?Ar(r):null,isDone:!a,page:n.slice(i.offset,r)}},br=n=>{if(n===void 0)return z+1;if(!Number.isFinite(n))return z;const i=Math.max(0,Math.floor(n));if(i>z)throw new y("BAD_REQUEST",`search returns at most ${String(z)} documents (asked for ${String(i)}) — narrow the query or paginate instead`);return i},Mr=32,Dr=1024,sn=(n,i,r,a)=>{const s=`SELECT id, _creationTime, ${Ie(oe)} FROM ${Ie(n)}`,w=`ORDER BY ${r}${a===void 0?"":` LIMIT ${String(a)}`}`;return i===void 0?Ge(`${s} ${w}`):ve(`${s} WHERE `,i,` ${w}`)},Ke={fieldRef:n=>Ge(ct(n)),rangeTypeGuard:(n,i)=>Ge(qn(n,i)),serialize:Ae},kr=n=>n===void 0?"":zn(n==="first"),cn=n=>{const i=n.map(r=>`${ct(r.field)} ${r.direction==="desc"?"DESC":"ASC"}${kr(r.nulls)}`);return n.some(r=>r.field==="_id"||r.field==="id")||i.push(`${ct("id")} ${Jn(n)==="desc"?"DESC":"ASC"}`),i.join(", ")},Lr={"<":"lt","<=":"lte","=":"eq",">":"gt",">=":"gte"},an=n=>new Set(n.sqlConditions.filter(i=>i.comparator==="=").map(i=>i.field)),Fr=n=>{const i=an(n);let r=0;for(;r<n.indexFields.length&&i.has(n.indexFields[r]??"");)r+=1;return n.indexFields.slice(r)},qr=(n,i)=>{const r=n.order,a=Fr(n),{shape:s}=i;return a.length>0?kt(a.map(w=>({[w]:r})),s,{pinned:an(n),uniqueBy:Yn(i.indexes,s)}):kt([{_creationTime:r}],s)},Wr=(n,i,r,a)=>{const s=n.sqlConditions.map(w=>({[w.field]:{[Lr[w.comparator]??"eq"]:w.value}}));if(r&&s.push(Xn(i,Lt(r))),a&&s.push(Zn(i,Lt(a))),s.length!==0)return s.length===1?s[0]:{AND:s}},Br=n=>{if(n.want!==void 0)return n.selective?Math.max(n.want,Mr):n.want},at=(n,i,r,a,s,w,A)=>{const T=qr(a,r),b=cn(T),g=[],{filters:k,want:v}=w;let C=w.cursor??void 0,x=Br(w);if(v===0)return{documents:g,orderKeys:T};for(;;){const U=X(Wr(a,T,C,w.endCursor),Ke,je),q=sn(i,s&&U?ve(U," AND ",s):s??U,b,x),F=we(n,q.text,...q.params).toArray();let W={};A(F.length);for(const j of F)if(W=Te(j),k.every(L=>L(W))&&g.push(W)===v)return{documents:g,orderKeys:T};if(x===void 0||F.length<x)return{documents:g,orderKeys:T};C=He(W,T),x=Math.max(x,Math.min(x*2,Dr))}},Pr=(n,i,r,a,s,w,A,T)=>{const b=Math.max(0,Math.floor(s.numItems));if(typeof s.endCursor=="string"){const{documents:U,orderKeys:q}=at(n,i,r,a,w,{cursor:s.cursor,endCursor:s.endCursor,filters:A.all,selective:A.selective,want:void 0},T),F=U.length>=2?U[Math.floor(U.length/2)-1]:void 0;return{continueCursor:s.endCursor,isDone:!0,page:U,splitCursor:F?He(F,q):null}}const{documents:g,orderKeys:k}=at(n,i,r,a,w,{cursor:s.cursor,filters:A.all,selective:A.selective,want:b+1},T),v=g.length>b,C=v?g.slice(0,b):g,x=C.at(-1);return{continueCursor:v&&x?He(x,k):null,isDone:!v,page:C}},Ne=n=>{const i=new Map;return r=>{const a=i.get(r);if(a!==void 0)return a;const s=n(Ie(r));return i.set(r,s),s}},pe=Ie(oe),Ur=Ne(n=>`INSERT INTO ${n} (id, _creationTime, ${pe}) VALUES (?, ?, ?)`),jt=Ne(n=>`UPDATE ${n} SET ${pe} = ? WHERE id = ? AND ${pe} = ?`),Or=Ne(n=>`UPDATE ${n} SET _creationTime = ?, ${pe} = ? WHERE id = ? AND ${pe} = ?`),Hr=Ne(n=>`DELETE FROM ${n} WHERE id = ? AND ${pe} = ?`),Gr="SELECT changes() AS changed",Kt=new Map,jr="",Kr=n=>{const i=JSON.stringify(n),r=Kt.get(i);if(r!==void 0)return r;const a=n.map(w=>c`SELECT ${c.raw(`'${w.replaceAll("'","''")}'`)} AS __t__, id, _creationTime, ${c.identifier(oe)} FROM ${c.identifier(w)} WHERE id = ${jr}`),{sql:s}=rn("sqlite",c`${ut(a)} LIMIT 1`);return Kt.set(i,s),s},Nr=(n,i)=>i.map(()=>n),Qr=/^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/iu,Vr=n=>{if(!Qr.test(n))throw new y("INTERNAL",`invalid clientId ${JSON.stringify(n)}: a client-supplied row id must be a UUID`)},Nt=50,dn=500,Pe=Math.floor(on.boundParams/3),_e=on.boundParams,Jr=128,ue=(n,i,r)=>{const a=i??dn;if(n>a)throw new y("BATCH_LIMIT_EXCEEDED",`${r}: batch of ${String(n)} exceeds the limit of ${String(a)} (raise options.limit or chunk the call)`,{status:400})},zr=n=>{const i={eq:(r,a)=>(n.sqlConditions.push({comparator:"=",field:r,value:a}),i),gt:(r,a)=>(n.sqlConditions.push({comparator:">",field:r,value:a}),i),gte:(r,a)=>(n.sqlConditions.push({comparator:">=",field:r,value:a}),i),lt:(r,a)=>(n.sqlConditions.push({comparator:"<",field:r,value:a}),i),lte:(r,a)=>(n.sqlConditions.push({comparator:"<=",field:r,value:a}),i)};return i},Yr=n=>Math.max(n,z),ln=(n,i)=>{const r=n.filters.map(a=>c`${he(a.field)} = ${Ae(a.value)}`);return i&&r.push(i),r},Xr=(n,i,r,a,s)=>{const w=ft(r.query,lt(r.definition.language));if(w.length===0)return[];const A=Sn(i,r.indexName),T=`${A}__vocab`,b=w.length-1,g=w.map((q,F)=>{const W=_r(q,F===b),j=W.exact?c`${c.identifier("term")} = ${W.lower}`:c`${c.identifier("term")} >= ${W.lower} AND ${c.identifier("term")} < ${W.upper}`;return c`SELECT ${c.identifier("doc")}, ${c.raw(String(F))} AS ${c.identifier("__term__")}, COUNT(*) AS ${c.identifier("__n__")} FROM ${c.identifier(T)} WHERE ${j} GROUP BY ${c.identifier("doc")}`}),k=w.map((q,F)=>c`SUM(CASE WHEN u.${c.identifier("__term__")} = ${c.raw(String(F))} THEN u.${c.identifier("__n__")} ELSE 0 END)`),v=c`SELECT f.${c.identifier(Fe)} AS ${c.identifier(Fe)}, ${c.join(k,c` + `)} AS ${c.identifier("__score__")} FROM (${ut(g)}) u JOIN ${c.identifier(A)} f ON f.rowid = u.${c.identifier("doc")} GROUP BY f.${c.identifier(Fe)} HAVING ${c.join(k.map(q=>c`${q} > 0`),c` AND `)}`,C=ln(r,s);let x=c`SELECT m.id, m._creationTime, m.${c.identifier(oe)}, s.${c.identifier("__score__")} AS ${c.identifier("__score__")} FROM (${v}) s JOIN ${c.identifier(i)} m ON m.id = s.${c.identifier(Fe)}`;C.length>0&&(x=c`${x} WHERE ${c.join(C,c` AND `)}`),x=c`${x} ORDER BY s.${c.identifier("__score__")} DESC, m._creationTime DESC, m.id ASC LIMIT ${c.raw(String(a))}`;const U=[];for(const q of G(n,x)){const F=nn(q);if(F){const W=q.__score__;U.push({document:F,score:typeof W=="number"?W:Number(W??0)})}}return U},Zr=(n,i,r,a,s)=>{const w=lt(r.definition.language),A=ft(r.query,w);if(A.length===0)return[];const T=ln(r,s);let b=c`SELECT id, _creationTime, ${c.identifier(oe)} FROM ${c.identifier(i)}`;T.length>0&&(b=c`${b} WHERE ${c.join(T,c` AND `)}`),b=c`${b} ORDER BY _creationTime DESC, id ASC LIMIT ${c.raw(String(Yr(a)))}`;const g=G(n,b).toArray(),k=[];for(const v of g){const C=nn(v);if(!C)continue;const x=Sr(_n(C,r.definition),A);x>0&&k.push({creationTime:typeof C._creationTime=="number"?C._creationTime:0,doc:C,id:typeof C._id=="string"?C._id:"",score:x})}return k.sort((v,C)=>C.score-v.score||C.creationTime-v.creationTime||v.id.localeCompare(C.id)),k.slice(0,a).map(v=>({document:v.doc,score:v.score}))},it=(n,i,r,a)=>{if(!Number.isFinite(n.lat)||n.lat<-90||n.lat>90||!Number.isFinite(n.lng)||n.lng<-180||n.lng>180)throw new y("BAD_REQUEST",`geo index "${a}" on table "${r}": ${i} must have a finite lat in [-90, 90] and lng in [-180, 180]`)},eo=(n,i)=>{const r=n,a={near:(s,w)=>{if(r.within)throw new y("INTERNAL",`geo index "${r.indexName}" on table "${i}": call .near() or .within(), not both`);if(it(s,".near() point",i,r.indexName),!Number.isFinite(w)||w<=0)throw new y("BAD_REQUEST",`geo index "${r.indexName}" on table "${i}": .near() radiusMeters must be a finite number > 0, got ${String(w)}`);return r.near={point:{lat:s.lat,lng:s.lng},radiusMeters:w},a},within:s=>{if(r.near)throw new y("INTERNAL",`geo index "${r.indexName}" on table "${i}": call .near() or .within(), not both`);if(it(s.sw,".within() sw corner",i,r.indexName),it(s.ne,".within() ne corner",i,r.indexName),s.sw.lat>s.ne.lat)throw new y("BAD_REQUEST",`geo index "${r.indexName}" on table "${i}": .within() corners are transposed (sw.lat > ne.lat)`);if(s.sw.lng>s.ne.lng)throw new y("BAD_REQUEST",`geo index "${r.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 r.within={ne:{lat:s.ne.lat,lng:s.ne.lng},sw:{lat:s.sw.lat,lng:s.sw.lng}},a}};return a},to=(n,i)=>{const r=n[i];if(r===null||typeof r!="object")return;const{lat:a,lng:s}=r;return typeof a=="number"&&typeof s=="number"?{lat:a,lng:s}:void 0},no=(n,i)=>{const r=to(n,i.definition.field);if(!r)return;const a=typeof n._creationTime=="number"?n._creationTime:0;if(i.near){const s=Gn(i.near.point,r);return s<=i.near.radiusMeters?{creationTime:a,distance:s}:void 0}return jn(r,i.within)?{creationTime:a,distance:0}:void 0},ro=(n,i,r,a)=>{if(!r.near&&!r.within)throw new y("INTERNAL",`geo index "${r.indexName}" on table "${i}": call .near(point, radius) or .within(box)`);const s=r.near?On(r.near.point,r.near.radiusMeters):Hn(r.within),w=Pn(i,r.indexName),A=s.map(v=>c`(g.${c.identifier("__geohash__")} >= ${v} AND g.${c.identifier("__geohash__")} < ${`${v}{`})`),T=[c`(${c.join(A,c` OR `)})`];a&&T.push(a);const b=c`SELECT m.id, m._creationTime, m.${c.identifier(oe)} FROM ${c.identifier(w)} g JOIN ${c.identifier(i)} m ON m.id = g.${c.identifier("__id__")} WHERE ${c.join(T,c` AND `)}`,g=G(n,b).toArray(),k=[];for(const v of g){const C=Te(v),x=C?no(C,r):void 0;C&&x&&k.push({creationTime:x.creationTime,distance:x.distance,doc:C})}return k.sort((v,C)=>v.distance-C.distance||C.creationTime-v.creationTime),k},un=(n,i,r,a)=>{const s=[];for(const w of n)if(i.every(A=>A(a(w)))&&(s.push(w),typeof r=="number"&&s.length>=r))break;return s},oo=(n,i,r,a,s,w=()=>{})=>{const A=r.within!==void 0,T=ro(n,i,r,s).map(b=>({distanceMeters:A?null:b.distance,document:b.doc}));return w(T.length),typeof a=="number"?T.slice(0,Math.max(0,Math.floor(a))):T},Qt=(n,i,r,a,s,w,A=()=>{})=>{const{geo:T}=r;if(!T)throw new y("INTERNAL","runGeoTerminalScored called without a staged geo query");const b=s.length>0,g=oo(n,i,T,b?void 0:w,a,A);return b?un(g,s,w,k=>k.document):g},Vt=(n,i,r)=>{const a=n.shape[i];if(a!==void 0&&gr(a))throw new y("BAD_REQUEST",`${r}: "${i}" may hold an order-preserving key rather than a value SQL can reduce or group — declare an aggregateIndex covering this (by, field, op) so the maintained companion answers it instead (its running total is a REAL, so it stays exact only while the total is inside 2^53)`)},io=n=>{let i=0;const r=[],a={...Ke,relationExists:s=>{const{childWhere:w,negated:A,parentTable:T,relation:b}=s,g=`__rel_${String(i)}`,k=r.at(-1)??T;i+=1,n(b.table,O);const v=b.kind==="one"?b.field:b.references,C=b.kind==="one"?b.references:b.field,x=Ge(`${Mt(g,C)} = ${Mt(k,v)}`);r.push(g);const U=X(w,a,je);r.pop();const q=U===void 0?x:ve(x," AND ",U),F=ve("EXISTS (SELECT 1 FROM ",Pt(b.table)," AS ",Pt(g)," WHERE ",q,")");return A?ve("NOT ",F):F}};return a};class so extends y{constructor(i="unique() found more than one matching document"){super("NOT_UNIQUE",i,{name:"NotUniqueError"})}}const co=/\s/u,ao=String.fromCodePoint(0),Jt=(n,i,r)=>{if(!n.tables[i])throw new y("INTERNAL",`unknown table: ${i}`);return typeof r!="string"||r.length===0||co.test(r)||r.includes(ao)?null:r},fn=(n,i,r,a=()=>{},s=()=>{},w=()=>{},A)=>{const T=i.tables[r];if(!T)throw new y("INTERNAL",`unknown table: ${r}`);const b=Re(T.softDeleteMode,void 0),g=A??{indexFields:[],indexName:void 0,inMemoryFilters:[],order:"asc",sqlConditions:[],verifyFilters:[]},k=()=>{const $=N(b,g.pushedWhere);return $?X($,fe):void 0},v=()=>{const $=N(b,g.pushedWhere);return $?X($,Ke,je):void 0},C=()=>[...g.inMemoryFilters,...g.verifyFilters];let x=0;const U=$=>{const{search:I}=g;if(!I)throw new y("INTERNAL","runSearchFetch called without a staged search");xn(n,r,T);const M=g.inMemoryFilters.length>0,D=br(M?void 0:$),Q=Bn(n);if(Q&&!bn(n,r,I.definition))throw new y("SEARCH_INDEX_BUILDING",`search index "${I.indexName}" on table "${r}" is still backfilling and currently covers only part of the table — retry once it finishes, or run the backfillSearch admin operation to complete it now`);const ge=k(),ie=Q?Xr(n,r,I,D,ge):Zr(n,r,I,D,ge);!M&&$===void 0&&Tr(ie);const re=C();return x=ie.length,re.length>0?un(ie,re,$,se=>se.document):ie},q=$=>U($).map(I=>I.document),F=$=>{const I=Cr($);return xr(q(vr(I)),I)},W=()=>{if(g.search||g.geo||g.indexName===void 0){s(void 0);return}s(ir(r,g.indexName,g.indexFields,g.sqlConditions,Ae))},j=$=>{W();let I=0;const M=(()=>{if(g.search){const D=q($);return I=x,D}return g.geo?Qt(n,r,g,k(),C(),$,D=>{I=D}).map(D=>D.document):at(n,r,T,g,v(),{filters:C(),selective:g.inMemoryFilters.length>0,want:$===void 0?void 0:Math.max(0,Math.floor($))},D=>{I+=D}).documents})();return w(Math.max(I,M.length)),M},L=()=>{if(!g.search&&!g.geo)throw new y("INTERNAL",`ctx.db.query("${r}").collectWithScores() requires a staged .withSearchIndex(...) or .withGeoIndex(...)`);W();let $=0;const I=(()=>{if(g.search){const M=U(void 0);return $=x,M}return Qt(n,r,g,k(),C(),void 0,M=>{$=M})})();return w(Math.max($,I.length)),I},J={async*[Symbol.asyncIterator](){const $=fn(n,i,r,a,s,w,{...g,indexFields:[...g.indexFields],inMemoryFilters:[...g.inMemoryFilters],sqlConditions:[...g.sqlConditions],verifyFilters:[...g.verifyFilters]});if(g.search){yield*await $.collect();return}let I;for(;;){const M=await $.paginate({cursor:I??null,numItems:Jr});if(yield*M.page,M.isDone||M.continueCursor===null)return;I=M.continueCursor}},async collect(){return j(void 0)},async collectWithScores(){return L()},filter($){const I=sr($);return I!==void 0&&cr(I,T.shape)?(g.pushedWhere=N(g.pushedWhere,I),g.verifyFilters.push($)):g.inMemoryFilters.push($),J},async first(){return j(1)[0]??null},order($){return g.order=$==="desc"?"desc":"asc",J},async paginate($){let I=0;if(W(),g.search){const D=F($);return w(D.page.length),D}if(g.geo)throw new y("INTERNAL","pagination is not supported on geo queries; use .take(n) or .collect()");const M=Pr(n,r,T,g,$,v(),{all:C(),selective:g.inMemoryFilters.length>0},D=>{I+=D});return w(Math.max(I,M.page.length)),M},async take($){return j($)},async unique(){const $=j(2);if($.length>1)throw new so(`unique() on table "${r}" matched ${String($.length)} documents; expected at most one`);return $[0]??null},withGeoIndex($,I){const M=(T.geoIndexes??[]).find(Q=>Q.name===$);if(!M)throw new y("INTERNAL",`unknown geo index "${$}" on table "${r}"`);a(r,$,"geo");const D={definition:M,indexName:$};if(g.geo=D,I(eo(D,r)),!D.near&&!D.within)throw new y("INTERNAL",`geo index "${$}" on table "${r}" requires a .near(point, radius) or .within(box) call`);return J},withIndex($,I){const M=T.indexes.find(D=>D.name===$);if(!M)throw new y("INTERNAL",`unknown index "${$}" on table "${r}"`);return a(r,$,"index"),g.indexName=$,g.indexFields=M.fields,I&&I(zr(g)),J},withSearchIndex($,I){const M=(T.searchIndexes??[]).find(Q=>Q.name===$);if(!M)throw new y("INTERNAL",`unknown search index "${$}" on table "${r}"`);a(r,$,"search");const D={definition:M,field:M.field,filters:[],hasQuery:!1,indexName:$,query:""};if(g.search=D,I(Rr(D,r,lt(M.language))),!D.hasQuery)throw new y("INTERNAL",`search index "${$}" on table "${r}" requires a .search(field, query) call`);return J}};return J},zt=(n,i,r)=>{const a={...i};for(const[s,w]of tn(n)){if(w.serverDefault){a[s]=w.serverDefault({auth:r});continue}a[s]===void 0&&(w.defaultFn?a[s]=w.defaultFn():"defaultValue"in w&&(a[s]=w.defaultValue))}return a},st=(n,i,r,a)=>{const s=r;for(const[w,A]of tn(n)){if(A.serverDefault){w in i&&(s[w]=A.serverDefault({auth:a}));continue}A.onUpdateFn&&!(w in i)&&(s[w]=A.onUpdateFn())}},Yt=5,Xt=(n,i)=>{for(const r of Object.keys(i))if(i[r]===void 0)throw new y("INTERNAL",`Cannot ${n} field '${r}' to undefined — use null to clear a nullable field, or omit the key to leave it unchanged.`)},Zt=["_commitSeq","_creationTime","_id"],Ue=n=>Zt.some(i=>i in n)?Object.fromEntries(Object.entries(n).filter(([i])=>!Zt.includes(i))):n,lo=/unique constraint failed/i,uo=n=>n instanceof Error&&lo.test(n.message),fo=/string or blob too big/iu,ho=(n,i)=>{if(!(!(n instanceof Error)||!fo.test(n.message)))throw new y("PAYLOAD_TOO_LARGE",`document is too large to store in "${i}": a single row cannot exceed the storage engine's per-row ceiling (2 MB on a Durable Object's SQLite). The limit is on the STORED bytes, which are UTF-8, and v.bytes()/v.bigint() columns are stored twice on a shard-local table. Keep the payload in R2 (ctx.storage) and store a reference on the row.`)},dt=(n,i,r,a)=>{try{we(n,r,...a)}catch(s){throw uo(s)?new ae(`unique constraint violation on "${i}"`,"unique"):(ho(s,i),s)}},Oe=(n,i,r,a)=>{if(dt(n,i,r,a),we(n,Gr).one().changed===0)throw new ae(`optimistic concurrency conflict on "${i}" — the row changed during this mutation; refetch and retry`,"occ")},en=(n,i,r,a,s,w,A)=>{const T=[];for(let v=0;v<r.length+1;v+=1){const C=r[v],x=a[v],U=x?.direction==="desc"?"desc":"asc",q=C===void 0||x===void 0?c`${c.identifier(nr)} < ${A}`:rr(C,w[v],U,!1);if(q===void 0)continue;const F=[];for(let j=0;j<v;j+=1)F.push(c`${c.identifier(r[j])} IS ${w[j]}`);F.push(q);const[W]=F;T.push(F.length===1&&W!==void 0?W:c`(${c.join(F,c` AND `)})`)}const b=T.length>0?c.join(T,c` OR `):c`1 = 0`,g=G(n,c`SELECT COUNT(*) AS c FROM ${c.identifier(i)} WHERE ${c.identifier("__partition__")} = ${s} AND (${b})`).one(),k=G(n,c`SELECT COUNT(*) AS c FROM ${c.identifier(i)} WHERE ${c.identifier("__partition__")} = ${s}`).one();return{before:g.c,total:k.c}},Zo=n=>{const{baselineSeq:i,onStalePatchDropped:r}=n,{sql:a}=n,{schema:s}=n,w=n.broadcast??(()=>{}),A=ar(s),T=fr(s,n.inTransaction);let b;const g=()=>n.inTransaction?.()===!0,k=e=>s.tables[e]?.commitOrderedMode!==!0?{}:((b===void 0||!g())&&(b=kn(a)),{[Ln]:b}),v=(e,...t)=>{const o=s.tables[e]?.indexes;if(!o||o.length===0)return;const u=[];for(const h of t)h&&u.push(...or(o,h,Ae));return u.length>0?u:void 0},{headroom:C}=n;let x=!1;const U=async e=>{const t=x;x=!0;try{return await e()}finally{x=t}},q=n.onRead??(()=>{}),F=e=>{xt(s.tables[e])&&q(Bt,Bt)},W=n.onReadRange??(e=>{q(e.table,O)}),j=e=>{F(e.table),W(e)},L=(e,t)=>{t!==void 0&&t!==O&&!x&&C?.recordRead(1),F(e),q(e,t)},J=n.onIndexUse??(()=>{}),$=n.onWrite??(()=>{}),I=e=>{x||C?.recordWrite(e)},M=async e=>{I(e.doc),await $(e)},{cache:D}=n,Q=n.clock??(()=>Date.now()),ge=n.idGenerator??(()=>crypto.randomUUID()),ie=n.scheduler??Tn,{globalDb:re}=n,se=n.auth??{identity:null,userId:null},ht=n.cdc??!1,Qe=ie,hn=yr({scheduler:typeof Qe.list=="function"&&typeof Qe.get=="function"?Qe:void 0,storage:n.storage}),ye=(e,t,o,u)=>{ht&&!xt(s.tables[e])&&Mn(a,Q(),e,t,o,u)},wt=(e,t,o,u)=>{const h=s.tables[e];if(h?.dropStalePatchesMode!==!0||!ht)return!1;const f=i?.();if(f===void 0)return!1;const d=Dn(a,e,t,f);if(d===void 0)return!1;const l=Vn(h,o);return Object.keys(Ue(o)).some(p=>!l.has(p)&&Ct(Dt(d,p))!==Ct(Dt(u,p)))},ce=e=>s.tables[e]?.shardMode?.kind==="global",pt=(e,t)=>{if(ce(e)){if(!re)throw new y("INTERNAL",`cross-backend ${t} for global table '${e}' requires a globalDb writer — pass one to createShardCtxDb({ globalDb })`);return re}return B},Ve=e=>pt(e,"cascade"),K=(e,t)=>{if(ce(e)){if(!re)throw new y("INTERNAL",`${t} on global table '${e}' requires a globalDb writer — pass one to createShardCtxDb({ globalDb })`);return re}},gt=async(e,t,o,u,h)=>{h&&I(o);const f=await e.insert(t,o,u);return w({key:f,op:"insert",row:{...o,_id:f},table:t}),f},Je=(e,t)=>pt(e,"relation load").findMany(e,t),yt=(e,t)=>(ce(e)&&L(e,O),Je(e,t)),wn=e=>!ce(e.table),$t=n.relationExistsPushDown??"auto",Et=$t!=="never",{maxRelationKeys:mt}=n,Ce=(e,t,o)=>lr(e,{fetcher:yt,maxRelationKeys:mt,relationBaseWhere:o,schema:s,tableName:t}),St=async(e,t,o,u)=>{const h=K(e,"relation grouped count");if(h)return L(e,O),wr((_,H)=>h.count(_,H),e,t,o,u);const f=s.tables[e];if(!f)throw new y("INTERNAL",`unknown table: ${e}`);L(e,O);const d=Re(f.softDeleteMode,void 0),l={[t]:{in:o}},p=N(N(l,u),d),R=await Ce(p,e,void 0),E=X(R,fe),S=he(t);let m=c`SELECT ${S} AS __fk__, COUNT(*) AS count FROM ${c.identifier(e)}`;E&&(m=c`${m} WHERE ${E}`),m=c`${m} GROUP BY ${S}`;const P=G(a,m).toArray();return new Map(P.map(_=>[_.__fk__,_.count]))};let xe=0;const _t=new Set;for(const[e,t]of Object.entries(s.tables))for(const o of Object.values(t.triggerMap??{}))_t.add(`${e} ${o.timing} ${o.op}`);const Z=(e,t,o)=>_t.has(`${e} ${t} ${o}`),ee=async(e,t,o)=>{if(xe+=1,xe>Nt)throw xe-=1,new ae(`trigger recursion exceeded ${String(Nt)} levels on "${o.table}" — check for a self-triggering write`,"trigger");try{await $r({ctx:En,event:o,op:t,schema:s,tableName:o.table,timing:e})}finally{xe-=1}},{ensureBackfilledForTable:$e,ensureBackfilledIndex:ze,ensureRankBackfilled:Ye,ensureRankBackfilledForTable:Ee,syncAggregates:be,syncCompanionsForInsert:Rt,syncGeo:Me,syncRanks:me,syncSearch:De}=Fn({broadcast:w,indexKeysFor:(e,t)=>v(e,t),invalidateCache:(e,t,o)=>D?.invalidate(e,t,v(e,o)),recordCdc:ye,schema:s,sql:a}),Tt=(e,t,o)=>{const{shardMode:u}=t;if(u?.kind==="shardBy"&&!(u.field!==void 0&&(o.partitionBy??[]).includes(u.field)))throw Object.assign(new Error(`rank index "${o.name}" on "${e}" partitions across shards (shard key "${u.field??"?"}" is not in partitionBy) — a shard-local rank()/rankPage() would be wrong; roll it up through the Query Coordinator instead`),{code:"CROSS_SHARD_RANK_UNSUPPORTED",name:"LunoraError",status:400})},vt=e=>Object.entries(s.tables).filter(([,t])=>t.shardMode?.kind!=="global").map(([t])=>t).filter(t=>e===void 0||t===e),Se=e=>e===void 0||ce(e)?re:void 0,te=(e,t)=>{const o=vt(t);for(let u=0;u<o.length;u+=_e){const h=o.slice(u,u+_e),[f]=we(a,Kr(h),...Nr(e,h)).toArray();if(!f)continue;const d=f.__t__,l=Te(f);if(typeof d!="string"||!l)return;const p=f[oe];return{docJson:typeof p=="string"?p:le(p??{}),row:l,tableName:d}}},pn=(e,t)=>{const o=[...new Set(e)],u=new Map;if(o.length===0)return u;const h=vt(t);for(let f=0;f<h.length;f+=_e){const d=h.slice(f,f+_e),l=Math.floor(_e/d.length),p=Un(c`${c.identifier("id")}`,o,!1,l),R=d.map(E=>c`SELECT ${c.raw(`'${E.replaceAll("'","''")}'`)} AS __t__, id FROM ${c.identifier(E)} WHERE ${p}`);for(const E of G(a,ut(R))){const{id:S,__t__:m}=E;typeof m=="string"&&typeof S=="string"&&u.set(S,m)}}return u},At={assertRankPartitionLocal:Tt,ensureRankBackfilled:Ye,onRead:L,rowToDocument:Te,schema:s,sql:a},gn=(e,t,o)=>{const u=X(o,fe);return u===void 0||G(a,c`SELECT 1 FROM ${c.identifier(e)} WHERE ${c.identifier("id")} = ${t} AND ${u}`).toArray().length>0},yn=(e,t,o,u)=>wt(e,t,o,u)?(r?.({fields:Object.keys(Ue(o)),id:t,table:e}),!0):!1,$n=async(e,t,o,u,h)=>{const f=te(t,e);if(!f)return{applied:!1,doc:null};if(L(e,t),!gn(e,t,o.where)||yn(e,t,o.patch,f.row))return{applied:!1,doc:f.row};try{await h(o.patch)}catch(d){if(d instanceof ae&&d.kind==="occ"&&u)return;throw d}return{applied:!0,doc:te(t,e)?.row??null}},It=async(e,t,o,u)=>{const{fetchLimit:h,limit:f,orderKeys:d,predicate:l}=await ur(t,o,{canPushExists:Et?wn:void 0,existsPushMode:$t==="always"?"always":"auto",fetcher:yt,maxRelationKeys:mt,schema:s,tableName:e}),p=Et?io(u):Ke,R=X(l,p,je),E=sn(e,R,cn(d),h);return{limit:f,orderKeys:d,statement:E}},B={system:hn,async aggregate(e,t){const o=K(e,"aggregate");if(o)return L(e,O),o.aggregate(e,t);const u=s.tables[e];if(!u)throw new y("INTERNAL",`unknown table: ${e}`);if(qe(t.op),t.op==="count")return B.count(e,{baseWhere:t.baseWhere,relationBaseWhere:t.relationBaseWhere,restrictsCounts:t.restrictsCounts,where:t.where});if(!t.field)throw new y("INTERNAL",`aggregate(${e}, { op: "${t.op}" }): "field" is required for non-count reducers`);L(e,O);const h=Re(u.softDeleteMode,void 0),f=N(N(t.baseWhere,t.where),h),d=await Ce(f,e,t.relationBaseWhere),l=d!==f;if(u.aggregateIndexes&&!t.baseWhere&&!l){const _=Cn(u.aggregateIndexes,t.op,t.field,t.where);if(_){ze(e,_.index);const H=Ze(_.index.by??[],_.key),ne=Xe(e,_.index.name),Y=G(a,c`SELECT ${We} AS value, ${nt} AS count FROM ${c.identifier(ne)} WHERE ${Be} = ${H}`).toArray()[0];return et(t.op,Y)}}Vt(u,t.field,`aggregate(${e}, { op: "${t.op}", field: "${t.field}" })`);const p=X(d,fe),R=qe(t.op),E=he(t.field);let S=c`SELECT ${c.raw(R)}(${E}) AS value FROM ${c.identifier(e)}`;p&&(S=c`${S} WHERE ${p}`);const P=G(a,S).toArray()[0]?.value;return P??null},asId(e,t){const o=Jt(s,e,t);if(o===null)throw new y("BAD_REQUEST",`asId("${e}", …): "${t}" is not a valid id for table "${e}"`,{status:400});return o},async count(e,t){const o=K(e,"count");if(o)return L(e,O),o.count(e,t);const u=s.tables[e];if(!u)throw new y("INTERNAL",`unknown table: ${e}`);const h=vn(t);if(h.restrictsCounts)throw new tt(e);L(e,O);const f=Re(u.softDeleteMode,void 0),d=N(N(h.baseWhere,h.where),f),l=await Ce(d,e,h.relationBaseWhere),p=l!==d;if(u.aggregateIndexes&&!h.baseWhere&&!p){const m=In(u.aggregateIndexes,h.where);if(m){ze(e,m.index);const P=Ze(m.index.by??[],m.key),_=Xe(e,m.index.name),H=G(a,c`SELECT ${We} AS value FROM ${c.identifier(_)} WHERE ${Be} = ${P}`).toArray();return H[0]===void 0?0:H[0].value??0}}const R=X(l,fe);let E=c`SELECT COUNT(*) AS count FROM ${c.identifier(e)}`;return R&&(E=c`${E} WHERE ${R}`),G(a,E).one().count},async delete(e,t,o){const u=te(e,t);if(!u){const S=Se(t);S&&(I(void 0),await S.delete(e,t,o));return}const{docJson:h,row:f,tableName:d}=u,l=s.tables[d],p=o?.hard===!0,R=!p&&l?.softDeleteMode?l:void 0,E=R?.softDeleteMode?.field;if(!(E&&f[E]!==null&&f[E]!==void 0)){if(Z(d,"before","delete")&&await ee("before","delete",{id:e,op:"delete",previous:f,table:d}),await hr({deletedId:e,deletedReference:S=>f[S],findHolders:async(S,m,P)=>(await Ve(S).findMany(S,{includeDeleted:p,where:{[m]:P}})).page,onCascade:(S,m)=>Ve(S).delete(m,void 0,o),onRestrict:S=>{throw new ae(S,"restrict")},onSetNull:(S,m,P)=>Ve(S).patch(m,{[P]:null}),schema:s,tableName:d}),$e(d),Ee(d),R&&E){const S={[E]:Q()},m={...f,...k(d),...S,_id:e};st(R,S,m,se),Oe(a,d,jt(d),[le(m),e,h]),De(d,e,m,f),Me(d,e,void 0),be(d,f,m),me(d,e,f,void 0),D?.invalidate(d,e,v(d,f,m)),ye(d,e,"update",m),w({indexKeys:v(d,f,m),key:e,op:"update",row:m,table:d}),Z(d,"after","delete")&&await ee("after","delete",{id:e,op:"delete",previous:f,table:d}),await M({id:e,op:"delete",table:d});return}Oe(a,d,Hr(d),[e,h]),De(d,e,void 0),Me(d,e,void 0),be(d,f,void 0),me(d,e,f,void 0),D?.invalidate(d,e,v(d,f)),ye(d,e,"delete"),w({indexKeys:v(d,f),key:e,op:"delete",table:d}),Z(d,"after","delete")&&await ee("after","delete",{id:e,op:"delete",previous:f,table:d}),await M({id:e,op:"delete",table:d})}},async deleteAll(e,t){if(!s.tables[e])throw new y("INTERNAL",`unknown table: ${e}`);const o=Math.max(1,t?.chunkSize??dn),u=t?.hard===void 0?void 0:{hard:t.hard},h=ce(e)?void 0:e;let f=0;return await U(async()=>{for(;;){const l=(await B.findMany(e,{limit:o})).page.map(p=>String(p._id));if(l.length===0)break;for(const p of l)await B.delete(p,h,u),f+=1;if(l.length<o)break}}),{deleted:f}},async deleteMany(e,t,o){ue(e.length,t?.limit,"deleteMany");for(const u of e)await B.delete(u,o);return{deleted:e.length}},async deleteWhere(e,t,o){const f=(await(K(e,"deleteWhere")??B).findMany(e,{where:t})).page.map(d=>String(d._id));if(ue(f.length,o?.limit,"deleteWhere"),B.deleteMany===void 0)throw new y("INTERNAL",`ctx.db.${e}.deleteMany is unavailable: this writer has no batch delete`);return B.deleteMany(f,o)},async findFirst(e,t={}){return(await B.findMany(e,{...t,limit:1,omitContinueCursor:!0})).page[0]??null},async findFirstOrThrow(e,t={}){const o=await B.findFirst(e,t);if(o===null)throw new Kn(`findFirstOrThrow: no "${e}" document matched`);return o},async findMany(e,t={}){const o=K(e,"findMany");if(o)return L(e,O),o.findMany(e,t);const u=s.tables[e];if(!u)throw new y("INTERNAL",`unknown table: ${e}`);const h=!t.where&&!t.baseWhere;h?L(e,O):L(e);const{limit:f,orderKeys:d,statement:l}=await It(e,u,t,L),p=we(a,l.text,...l.params).toArray();h&&!x&&C?.recordRead(p.length);const R=[];for(const P of p){const _=Te(P);_&&(R.push(_),!h&&typeof _._id=="string"&&L(e,_._id))}if(f===void 0)return t.with&&await Ut({groupedCounter:St,fetcher:Je,parents:R,...Ot(t),schema:s,tableName:e,with:t.with}),{continueCursor:null,isDone:!0,page:Ft(R,t.select,t.with)};const E=R.length>f,S=E?R.slice(0,f):R,m=S.at(-1);return t.with&&await Ut({fetcher:Je,groupedCounter:St,parents:S,...Ot(t),schema:s,tableName:e,with:t.with}),{continueCursor:E&&m&&t.omitContinueCursor!==!0?He(m,d):null,isDone:!E,page:Ft(S,t.select,t.with)}},async explain(e,t={}){const o=K(e,"explain");if(o)return o.explain(e,t);const u=s.tables[e];if(!u)throw new y("INTERNAL",`unknown table: ${e}`);const{statement:h}=await It(e,u,t,()=>{}),f=we(a,`EXPLAIN QUERY PLAN ${h.text}`,...h.params).toArray();return{params:h.params,plan:f.map(d=>String(d.detail)),sql:h.text}},async get(e,t){const o=te(e,t);if(!o){const u=Se(t);return u?u.get(e,t):null}return L(o.tableName,e),o.row},async lookupById(e,t){const o=te(e,t);return o?(L(o.tableName,e),{row:o.row,tableName:o.tableName}):null},async groupBy(e,t){const o=K(e,"groupBy");if(o)return L(e,O),o.groupBy(e,t);const u=s.tables[e];if(!u)throw new y("INTERNAL",`unknown table: ${e}`);L(e,O);const h=t.agg??{op:"count"};if(qe(h.op),h.op!=="count"&&!h.field)throw new y("INTERNAL",`groupBy(${e}, { agg: { op: "${h.op}" } }): "field" is required for non-count reducers`);const f=Re(u.softDeleteMode,void 0),d=N(N(t.baseWhere,t.where),f),l=await Ce(d,e,t.relationBaseWhere),p=l!==d;if(u.aggregateIndexes&&!t.baseWhere&&!p){const _=An(u.aggregateIndexes,h.op,h.field,t.by,t.where),H=_===void 0?0:Object.keys(_.partial).length,ne=_?.index.by?.length??0;if(_&&(H===0||H===ne)){ze(e,_.index);const Y=Xe(e,_.index.name),V=Object.keys(_.partial),de=[];if(V.length===(_.index.by??[]).length&&V.length>0){const ke=Ze(_.index.by??[],_.partial),Le=G(a,c`SELECT ${We} AS value, ${nt} AS count FROM ${c.identifier(Y)} WHERE ${Be} = ${ke}`).toArray();return Le.length>0&&de.push({key:{..._.partial},value:et(h.op,Le[0])}),de}const mn=G(a,c`SELECT ${Be} AS key, ${We} AS value, ${nt} AS count FROM ${c.identifier(Y)}`).toArray();for(const ke of mn){const Le=Rn(JSON.parse(ke.key));de.push({key:Le,value:et(h.op,ke)})}return de}}for(const _ of[...t.by,h.field]){if(_===void 0)continue;const H=_===h.field?`groupBy(${e}, { agg: { op: "${h.op}", field: "${_}" } })`:`groupBy(${e}, { by: [..."${_}"] })`;Vt(u,_,H)}const R=X(l,fe),E=t.by.map(_=>c`${he(_)} AS ${c.identifier(_)}`);if(h.op==="count")E.push(c`COUNT(*) AS value`);else{const{field:_}=h;if(_===void 0)throw new y("INTERNAL",`groupBy(${e}, { agg: { op: "${h.op}" } }): "field" is required for non-count reducers`);E.push(c`${c.raw(qe(h.op))}(${he(_)}) AS value`)}let S=c`SELECT ${c.join(E,c`, `)} FROM ${c.identifier(e)}`;R&&(S=c`${S} WHERE ${R}`),S=c`${S} GROUP BY ${c.join(t.by.map(_=>he(_)),c`, `)}`;const m=G(a,S).toArray(),P=[];for(const _ of m){const H={};for(const Y of t.by)H[Y]=Wn(u.shape[Y],_[Y]??null);const{value:ne}=_;P.push({key:H,value:ne==null?null:Number(ne)})}return P},async insert(e,t,o){const u=K(e,"insert");if(u)return gt(u,e,t,o,!0);const h=s.tables[e];if(!h)throw new y("INTERNAL",`unknown table: ${e}`);const f=zt(h,t,se);ot(h,f);let d;o?.clientId!==void 0?(Vr(o.clientId),d=o.clientId):o?.allowExplicitId&&typeof f._id=="string"?d=f._id:d=ge();const l=o?.allowExplicitId&&typeof f._creationTime=="number"?f._creationTime:Q(),p={...f,...k(e),_creationTime:l,_id:d};return Z(e,"before","insert")&&await ee("before","insert",{doc:{...p},id:d,op:"insert",table:e}),$e(e),Ee(e),dt(a,e,Ur(e),[d,l,le(p)]),Rt(e,d,p),Z(e,"after","insert")&&await ee("after","insert",{doc:p,id:d,op:"insert",table:e}),await M({doc:p,id:d,op:"insert",table:e}),d},async insertManyUnsafe(e,t,o){if(ue(t.length,o?.limit,"insertManyUnsafe"),t.length===0)return[];const u=K(e,"insert");if(u){const l=[];for(const p of t)I(p);for(const p of t){const R=await u.insert(e,p,{allowExplicitId:o?.allowExplicitId});w({key:R,op:"insert",row:{...p,_id:R},table:e}),l.push(R)}return l}const h=s.tables[e];if(!h)throw new y("INTERNAL",`unknown table: ${e}`);$e(e),Ee(e);const f=[];for(let l=0;l<t.length;l+=Pe)f.push(k(e));const d=t.map((l,p)=>{const R=zt(h,l,se),E=o?.allowExplicitId===!0&&typeof R._id=="string"?R._id:ge(),S=o?.allowExplicitId===!0&&typeof R._creationTime=="number"?R._creationTime:Q(),m={...R,...f[Math.floor(p/Pe)],_creationTime:S,_id:E};return{creationTime:S,document:m,id:E}});for(const l of d)I(l.document);for(let l=0;l<d.length;l+=Pe){const p=c.join(d.slice(l,l+Pe).map(E=>c`(${E.id}, ${E.creationTime}, ${le(E.document)})`),c`, `),R=rn("sqlite",c`INSERT INTO ${c.identifier(e)} (id, _creationTime, ${c.identifier(oe)}) VALUES ${p}`);dt(a,e,R.sql,R.params)}for(const{document:l,id:p}of d)Rt(e,p,l),await $({doc:l,id:p,op:"insert",table:e});return d.map(l=>l.id)},async insertMany(e,t,o){ue(t.length,o?.limit,"insertMany");const u=o?.skipDuplicates===!0,h=[],f=K(e,"insert");if(f)for(const l of t)I(l);const d=async l=>f?gt(f,e,l,void 0,!1):B.insert(e,l);for(const l of t)try{h.push(await d(l))}catch(p){if(u&&p instanceof ae&&p.kind==="unique")h.push(null);else throw p}return h},normalizeId(e,t){return Jt(s,e,t)},async patch(e,t,o,u){const h=te(e,o);if(!h){const S=Se(o);if(S){I(t),await S.patch(e,t,o,u);return}throw new y("NOT_FOUND",`document not found: ${e}`)}const{docJson:f,row:d,tableName:l}=h,p=s.tables[l];if(!p)throw new y("INTERNAL",`unknown table: ${l}`);if(L(l,e),Xt("patch",t),wt(l,e,t,d)){r?.({fields:Object.keys(Ue(t)),id:e,table:l});return}const R=Nn(p,t,d),E={...d,...Ue(R),...k(l),_id:e};st(p,R,E,se),Qn(u,d,E),ot(p,E,!0),Z(l,"before","update")&&await ee("before","update",{doc:{...E},id:e,op:"update",previous:d,table:l}),$e(l),Ee(l),Oe(a,l,jt(l),[le(E),e,f]),De(l,e,E,d),Me(l,e,E),be(l,d,E),me(l,e,d,E),D?.invalidate(l,e,v(l,d,E)),ye(l,e,"update",E),w({indexKeys:v(l,d,E),key:e,op:"update",row:E,table:l}),Z(l,"after","update")&&await ee("after","update",{doc:E,id:e,op:"update",previous:d,table:l}),await M({doc:E,id:e,op:"update",table:l})},async patchIf(e,t,o){const u=K(e,"patchIf");if(u){if(u.patchIf===void 0)throw new y("INTERNAL",`ctx.db.patchIf on global table '${e}' is unsupported: its backend has no conditional write`);return I(o.patch),u.patchIf(e,t,o)}if(!s.tables[e])throw new y("INTERNAL",`unknown table: ${e}`);for(let h=1;h<=Yt;h+=1){const f=await $n(e,t,o,h<Yt,d=>B.patch(t,d,e,{verify:o.verify}));if(f!==void 0)return f}throw new ae(`patchIf on "${e}" kept conflicting; the row changed on every attempt`,"occ")},async patchMany(e,t,o){ue(e.length,t?.limit,"patchMany");for(const u of e)await B.patch(u.id,u.patch,o);return{patched:e.length}},async patchWhere(e,t,o){const f=(await(K(e,"patchWhere")??B).findMany(e,{where:t.where})).page.map(d=>({id:String(d._id),patch:t.patch}));if(ue(f.length,o?.limit,"patchWhere"),B.patchMany===void 0)throw new y("INTERNAL",`ctx.db.${e}.patchMany is unavailable: this writer has no batch patch`);return await B.patchMany(f,o),{patched:f.length}},async related(e,t){return dr(B,A,e,t)},relationEdges:A,relationWrites:T,query(e){const t=K(e,"query");return t?(L(e,O),t.query(e)):fn(a,s,e,J,o=>{o?j(o):L(e,O)},o=>{x||C?.recordRead(o)})},async rank(e,t,o){const u=K(e,"rank");if(u)return L(e,O),u.rank(e,t,o);J(e,t,"rank");const h=s.tables[e];if(!h)throw new y("INTERNAL",`unknown table: ${e}`);const f=h.rankIndexes?.find(V=>V.name===t);if(!f)throw new y("INTERNAL",`unknown rankIndex "${t}" on table "${e}"`);if(Tt(e,h,f),o.restrictsCounts)throw new tt(e);L(e,O),Ye(e,f);const d=typeof o.row=="string"?o.row:o.row._id;if(!d)return null;const l=qt(e,f.name),p=f.sortBy.map((V,de)=>Wt(de)),R=p.map(V=>Ie(V)).join(", "),E=G(a,c`SELECT ${c.identifier("__partition__")}, ${c.raw(R)} FROM ${c.identifier(l)} WHERE ${c.identifier("__id__")} = ${d}`).toArray(),[S]=E;if(S===void 0)return null;let m=S.__partition__;const P=N(o.baseWhere,o.where);rt(P,s,e,"rank");const _=er(f,P);if(_){const V=tr(f.partitionBy??[],_);if(V!==m)return null;m=V}const H=p.map(V=>S[V]),{before:ne,total:Y}=en(a,l,p,f.sortBy,m,H,d);return{position:ne+1,total:Y}},async rankBefore(e,t,o){if(ce(e))throw new y("INTERNAL",`rankBefore is not supported on the global (.global()) table '${e}' — cross-shard rank cursors apply only to sharded tables`);const u=s.tables[e];if(!u)throw new y("INTERNAL",`unknown table: ${e}`);const h=u.rankIndexes?.find(p=>p.name===t);if(!h)throw new y("INTERNAL",`unknown rankIndex "${t}" on table "${e}"`);if(o.restrictsCounts)throw new tt(e);L(e,O),Ye(e,h);const f=qt(e,h.name),d=h.sortBy.map((p,R)=>Wt(R)),l=h.sortBy.map((p,R)=>Ae(o.sortValues[R]??null));return en(a,f,d,h.sortBy,o.partitionKey,l,o.rowId)},async rankPage(e,t,o={}){rt(N(o.baseWhere,o.where),s,e,"rankPage");const u=K(e,"rankPage");if(u)return L(e,O),u.rankPage(e,t,o);J(e,t,"rank");const{continueCursor:h,hasMore:f,rows:d}=bt(At,e,t,o);return{continueCursor:h,isDone:!f,page:d.map(l=>l.doc)}},async rankPageRows(e,t,o={}){rt(N(o.baseWhere,o.where),s,e,"rankPage"),J(e,t,"rank");const{directions:u,hasMore:h,rows:f}=bt(At,e,t,o);return{directions:u,hasMore:h,rows:f}},async restore(e,t){const o=te(e,t);if(!o){const f=Se(t);if(f?.restore){await f.restore(e,t);return}throw new y("NOT_FOUND",`document not found: ${e}`)}const u=s.tables[o.tableName]?.softDeleteMode?.field;if(!u)throw new y("INTERNAL",`ctx.db.restore: table "${o.tableName}" is not a .softDelete() table`);const h=o.row[u]!==null&&o.row[u]!==void 0;await B.patch(e,{[u]:null},t),h&&me(o.tableName,e,void 0,o.row)},async replace(e,t,o,u){const h=te(e,o);if(!h){const P=Se(o);if(P){I(t),await P.replace(e,t,o,u);return}throw new y("NOT_FOUND",`document not found: ${e}`)}const{docJson:f,row:d,tableName:l}=h,p=s.tables[l];if(!p)throw new y("INTERNAL",`unknown table: ${l}`);Xt("replace",t);const R=u?.allowExplicitId&&typeof t._creationTime=="number"?t._creationTime:void 0,E=typeof d._creationTime=="number"?d._creationTime:void 0,S=R??E??Q(),m={...t,...k(l),_creationTime:S,_id:e};st(p,t,m,se),ot(p,m),Z(l,"before","update")&&await ee("before","update",{doc:{...m},id:e,op:"update",previous:d,table:l}),$e(l),Ee(l),Oe(a,l,Or(l),[S,le(m),e,f]),De(l,e,m,d),Me(l,e,m),be(l,d,m),me(l,e,d,m),D?.invalidate(l,e,v(l,d,m)),ye(l,e,"update",m),w({indexKeys:v(l,d,m),key:e,op:"update",row:m,table:l}),Z(l,"after","update")&&await ee("after","update",{doc:m,id:e,op:"update",previous:d,table:l}),await M({doc:m,id:e,op:"update",table:l})},async wipeShard(e){const t=new Set(e?.exclude),o=e?.tables,u=Object.entries(s.tables).filter(([l,p])=>t.has(l)||o!==void 0&&!o.includes(l)?!1:p.shardMode?.kind!=="global").map(([l])=>l);if(o!==void 0){for(const l of o)if(!s.tables[l])throw new y("INTERNAL",`wipeShard: unknown table: ${l}`)}const h={};let f=0;const{deleteAll:d}=B;if(d===void 0)throw new y("INTERNAL","wipeShard: this writer has no deleteAll");for(const l of u){const p=await d(l,{...e?.chunkSize===void 0?{}:{chunkSize:e.chunkSize},hard:!0});h[l]=p.deleted,f+=p.deleted}return{deleted:f,tables:h}}},En={db:B,scheduler:ie};return n.enforceRls===!0?pr(B,s,(e,t)=>te(e,t)?.tableName,(e,t)=>pn(e,t),A):B};export{si as CDC_LOG_TABLE,Ci as IDEMPOTENCY_TABLE,so as NotUniqueError,Ti as advanceClientWatermark,ci as applyCdcChanges,Xt as assertNoExplicitUndefined,Vr as assertValidClientId,ni as backfillAggregateIndexes,ri as backfillRankIndexes,oi as backfillSearchIndexes,ai as bumpCdcEpoch,di as cdcCanVouchFor,li as cdcForkedError,ui as cdcSeqLeavingRows,fi as cdcTouchesTables,hi as cdcTrimmedError,wi as compactCdcDocs,Zo as createShardCtxDb,pi as cursorBelowRetainedFloor,vi as migrateClientWatermark,gi as minCdcReplayableSeq,yi as minCdcSeq,Jt as normalizeIdStructurally,$i as readCdcChangeKeys,Ei as readCdcChanges,mi as readCdcCursor,Si as readCdcEpoch,Ai as readClientWatermark,xi as readIdempotent,ki as runShardMigrations,Fi as selectShapeMembers,qi as selectShapeRows,Ue as stripReservedPatchFields,_i as trimCdcChanges,bi as trimIdempotent,Mi as writeIdempotent};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{createShardCtxDb as _}from"./NotUniqueError-
|
|
1
|
+
import{createShardCtxDb as _}from"./NotUniqueError-BXDZxdAt.mjs";import{createRelayLink as I}from"./DEFAULT_MAX_RELAYS-BqSpObEl.mjs";import{ConflictError as q}from"./ConflictError-C8GtJmjS.mjs";import{runShardMigrations as E}from"./runShardMigrations-eqHNBW6S.mjs";import{relayName as F}from"./DEFAULT_PROMOTION_THRESHOLDS-DEURXMvk.mjs";const S=(O,m={})=>({_meta:{column:{notNull:!0,...m}},kind:O}),A=(O,m,x)=>{const{describe:v,expect:d,it:b}=x;v(`engine contract: ${O}`,()=>{v("optimistic concurrency",()=>{const w=u=>({tables:{items:{indexes:[],shape:{title:S("string"),version:S("number",{notNull:!1})},triggerMap:{clobber:{handler:()=>{u.exec(`UPDATE "items" SET "__doc__" = json_set("__doc__", '$.version', 99) WHERE "id" = 'i1'`)},op:"update",timing:"before"}}}}});b("raises a CONFLICT of kind `occ` when a write's snapshot is clobbered",async()=>{const{close:u,host:h}=m();try{const c=h.sql,p=w(c);E(c,p);const s=_({schema:p,sql:c});await s.insert("items",{_id:"i1",title:"first",version:1},{allowExplicitId:!0}),await d(s.patch("i1",{title:"second"})).rejects.toBeInstanceOf(q)}finally{u?.()}}),b("reports the conflict as CONFLICT/409 rather than retrying it away",async()=>{const{close:u,host:h}=m();try{const c=h.sql,p=w(c);E(c,p);const s=_({schema:p,sql:c});await s.insert("items",{_id:"i1",title:"first",version:1},{allowExplicitId:!0});let a;try{await s.patch("i1",{title:"second"})}catch(t){a=t}const e=a;d(e.code).toBe("CONFLICT"),d(e.kind).toBe("occ")}finally{u?.()}}),b("leaves the row readable and unchanged after a conflict",async()=>{const{close:u,host:h}=m();try{const c=h.sql,p=w(c);E(c,p);const s=_({schema:p,sql:c});await s.insert("items",{_id:"i1",title:"first",version:1},{allowExplicitId:!0});try{await s.patch("i1",{title:"second"})}catch{}const a=await s.get("i1");d(a?.title).toBe("first"),d(a?.version).toBe(99)}finally{u?.()}}),b("raises a CONFLICT of kind `trigger` when a trigger writes its own row through the db",async()=>{const{close:u,host:h}=m();try{const c=h.sql,p={tables:{items:{indexes:[],shape:{title:S("string"),version:S("number",{notNull:!1})},triggerMap:{recurse:{handler:async(t,o)=>{await t.db.patch(o.doc._id,{version:99})},op:"update",timing:"before"}}}}};E(c,p);const s=_({schema:p,sql:c});await s.insert("items",{_id:"i1",title:"first",version:1},{allowExplicitId:!0});let a;try{await s.patch("i1",{title:"second"})}catch(t){a=t}const e=a;d(e).toBeInstanceOf(q),d(e.code).toBe("CONFLICT"),d(e.kind).toBe("trigger")}finally{u?.()}})}),v("shape-poke ordering",()=>{const w="shard-a",u={args:{},name:"messages"},h=(e,t,o,n)=>e.accept(t?.()??{},{connectionId:o,shapes:{[n]:u}}),c=(e,t,o)=>{let n=0,l=0;const r=k=>()=>{throw new Error(`the relay poke path must not reach RelayHost.${k}`)},i={fetch:(k,C)=>{if(JSON.parse(C?.body??"{}").type!=="relay_shape_subscribe")return Promise.resolve(new Response(void 0,{status:204}));const N=o[l];if(l+=1,N===void 0)throw new Error("the relay asked for more seeds than this fixture supplies");return Promise.resolve(Response.json(N))}},f={get:()=>i,getByName:()=>i,idFromName:k=>k},g={buildShapeDiff:r("buildShapeDiff"),computeOpLogShapeSeed:r("computeOpLogShapeSeed"),currentCdcEpoch:r("currentCdcEpoch"),deliverWhisperLocal:r("deliverWhisperLocal"),doName:()=>F(w,0),env:()=>({SHARD:f}),getWebSockets:()=>e.getSockets(),maskMetadata:r("maskMetadata"),nextPokeId:()=>(n+=1,`poke-${String(n)}`),readAttachment:k=>k.deserializeAttachment?.(),recordShapePokeFanout:()=>{},resolveShape:r("resolveShape"),rlsMetadata:r("rlsMetadata"),shardBinding:()=>"SHARD",shardJurisdiction:()=>{},sql:()=>t},y=I(g);if(y===void 0)throw new Error("expected a relay link for a `…::relay::N` name");return y},p=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 n=await e.seedRelayShape(t,o,u,{identity:void 0,userId:void 0});if(n!=="ok")throw new Error(`seed failed: ${JSON.stringify(n)}`)},a=(e={})=>p({...u,checkpoint:20,epoch:"e1",fromCursor:10,rowsPatch:[{id:"r1",op:"upsert",value:{title:"hello"}}],type:"relay_shape_poke",...e});b("frames a poke as pokeStart → pokePart per shape → pokeEnd, under one poke id",async()=>{const{close:e,createSocket:t,host:o,readFrames:n,sockets:l}=m();try{const r=c(l,o.sql,[{cursor:10,epoch:"e1",frames:[]}]),i=h(l,t,"c-alice","s1");await s(r,i,"s1"),await r.handleControl(a());const g=(await n(i)).map(y=>JSON.parse(y));d(g.map(y=>y.type)).toStrictEqual(["pokeStart","pokePart","pokeEnd"]),d(new Set(g.map(y=>y.pokeId)).size).toBe(1),d(g[1]?.shapeId).toBe("s1"),d(g[2]?.checkpoint).toBe(20)}finally{e?.()}}),b("delivers a poke only to sockets whose cursor matches, and advances them past it",async()=>{const{close:e,createSocket:t,host:o,readFrames:n,sockets:l}=m();try{const r=c(l,o.sql,[{cursor:10,epoch:"e1",frames:[]},{cursor:7,epoch:"e1",frames:[]}]),i=h(l,t,"c-alice","s1"),f=h(l,t,"c-bob","s2");await s(r,i,"s1"),await s(r,f,"s2"),await r.handleControl(a());const g=await n(i);d(g.length).toBe(3);const y=await n(f);d(y.length).toBe(0),await r.handleControl(a());const k=await n(i);d(k.length).toBe(3)}finally{e?.()}}),b("skips a socket whose cursor matches under a different CDC epoch",async()=>{const{close:e,createSocket:t,host:o,readFrames:n,sockets:l}=m();try{const r=c(l,o.sql,[{cursor:10,epoch:"e1",frames:[]}]),i=h(l,t,"c-alice","s1");await s(r,i,"s1"),await r.handleControl(a({epoch:"e2"}));const f=await n(i);d(f.length).toBe(0),await r.handleControl(a());const g=await n(i);d(g.length).toBe(3)}finally{e?.()}})}),v("orderBy null placement",()=>{const w=[["a",void 0],["b",3],["c",void 0],["d",1],["e",void 0],["f",3],["g",2],["h",void 0]],u=[{nulls:"first",sort:"asc"},{nulls:"last",sort:"asc"},{nulls:"first",sort:"desc"},{nulls:"last",sort:"desc"}],h=({nulls:p,sort:s})=>{const a=new Map(w.map(([t],o)=>[t,o])),e=s==="asc"?1:-1;return w.toSorted(([t,o],[n,l])=>o!==l?o===void 0?p==="first"?-1:1:l===void 0?p==="first"?1:-1:(o-l)*e:((a.get(t)??0)-(a.get(n)??0))*e).map(([t])=>t)},c=p=>p.map(s=>String(s.label));b("pages every placement in threes with no row skipped or repeated",async()=>{const{close:p,host:s}=m();try{const a=s.sql,e=u.map((r,i)=>`items_${String(i)}`),t={label:S("string"),score:S("number",{notNull:!1})},o={tables:Object.fromEntries(e.map(r=>[r,{indexes:[{fields:["score"],name:"by_score"}],shape:t}]))};E(a,o);let n=17e11;const l=_({clock:()=>(n+=1e3,n),schema:o,sql:a});for(const r of e)for(const[i,f]of w)await l.insert(r,f===void 0?{label:i}:{label:i,score:f});for(const[r,i]of u.entries()){const f=e[r]??"",g=await l.findMany(f,{orderBy:[{score:i}]});d(c(g.page)).toStrictEqual(h(i));const y=[];let k;for(let C=0;C<w.length+2;C+=1){const B=await l.findMany(f,{cursor:k,limit:3,orderBy:[{score:i}]});if(y.push(...c(B.page)),B.isDone)break;k=B.continueCursor}d(y).toStrictEqual(h(i))}}finally{p?.()}})}),v("RLS identity under live subscription",()=>{const w="shard-a",u={args:{},name:"lobby-messages"},h={args:{},name:"my-orders"},c=s=>{const a=[],e=[],t={fetch:(l,r)=>(a.push(JSON.parse(r?.body??"{}")),Promise.resolve(new Response(void 0,{status:204})))},n=I({buildShapeDiff:()=>[{id:"r1",op:"upsert",value:{}}],computeOpLogShapeSeed:()=>({baseCheckpoint:void 0,cursor:10,epoch:"e1",reset:!0,rowsPatch:[]}),currentCdcEpoch:()=>"e1",deliverWhisperLocal:()=>0,doName:()=>w,env:()=>({SHARD:{get:()=>t,getByName:()=>t,idFromName:l=>l}}),getWebSockets:()=>[],maskMetadata:()=>({columns:[]}),nextPokeId:()=>"poke-1",readAttachment:()=>({}),recordShapePokeFanout:()=>{},resolveShape:(l,r,i)=>(e.push(i),l===h.name?{columns:["id"],effectiveWhere:{org:i?.identity?.org??"anonymous"},global:!1,table:"orders"}:{columns:["id"],effectiveWhere:{room:"lobby"},global:!1,table:"messages"}),rlsMetadata:()=>({policies:[]}),shardBinding:()=>"SHARD",shardJurisdiction:()=>{},sql:()=>s});if(n===void 0)throw new Error("expected an owner link for an un-suffixed DO name");return{owner:n,posts:a,resolvedUnder:e}},p=async(s,a)=>{await s.handleControl(new Request("https://owner.internal/_lunora/relay",{body:JSON.stringify({...a,connectionId:"c-alice",identity:{org:"acme"},relayIndex:0,subId:"s1",type:"relay_shape_subscribe",userId:"u1"}),headers:{"content-type":"application/json"},method:"POST"}))};b("seeds a subscriber under its own forwarded identity, never the anonymous one",async()=>{const{close:s,host:a}=m();try{const{owner:e,resolvedUnder:t}=c(a.sql);await p(e,h),d(t.some(o=>o?.userId==="u1"&&o.identity?.org==="acme")).toBe(!0)}finally{s?.()}}),b("routes an identity-scoped shape to a per-socket poke, not the cohort multicast",async()=>{const{close:s,host:a}=m();try{const{owner:e,posts:t}=c(a.sql);await p(e,h),t.length=0,await e.onFlush(new Set(["orders"]),20);const o=t.filter(n=>n.type==="relay_shape_poke");d(o.length).toBe(1),d(o[0]?.targetConnectionId).toBe("c-alice")}finally{s?.()}}),b("still multicasts an identity-blind shape to the whole cohort",async()=>{const{close:s,host:a}=m();try{const{owner:e,posts:t}=c(a.sql);await p(e,u),t.length=0,await e.onFlush(new Set(["messages"]),20);const o=t.filter(n=>n.type==="relay_shape_poke");d(o.length).toBe(1),d(o[0]?.targetConnectionId).toBeUndefined()}finally{s?.()}})})})};export{A as defineEngineContractSuite};
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@lunora/shard-engine",
|
|
3
|
-
"version": "1.0.0-alpha.
|
|
3
|
+
"version": "1.0.0-alpha.127",
|
|
4
4
|
"description": "Host-neutral reactive engine for Lunora: per-shard state, OCC, CDC, reactive subscriptions, and the poke protocol. Consumes @lunora/platform host contracts and can be mounted on any platform host.",
|
|
5
5
|
"keywords": [
|
|
6
6
|
"cloudflare",
|
|
@@ -49,7 +49,7 @@
|
|
|
49
49
|
},
|
|
50
50
|
"dependencies": {
|
|
51
51
|
"@lunora/errors": ">=1.0.0-alpha.51 <2.0.0-0",
|
|
52
|
-
"@lunora/platform": "1.0.0-alpha.
|
|
52
|
+
"@lunora/platform": "1.0.0-alpha.64",
|
|
53
53
|
"drizzle-orm": "^0.45.3"
|
|
54
54
|
},
|
|
55
55
|
"engines": {
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{LunoraError as f}from"@lunora/errors";import{i as M,R as P}from"./relation-operators-BEg-CvCH.mjs";import{mergeWhere as b}from"./CountRlsUnsupportedError-BvsDqfO2.mjs";import{isMemoryTable as O}from"./clearMemoryTables-CogAvVHR.mjs";import{normalizeOrderKeys as S,uniqueIndexFields as _,equalityPinnedFields as L,buildSeekWhere as k,decodeCursor as K,softDeleteScope as D}from"./CURSOR_PREFIX-BztyXqNP.mjs";import{distinctValues as I}from"./applyOnDelete-CGVYKtaW.mjs";import{RELATION_EXISTS_KEY as B}from"./RELATION_EXISTS_KEY-wxgj6rSL.mjs";const R={every:{kind:"many",negateChild:!0,negated:!0},is:{kind:"one",negated:!1},isNot:{kind:"one",negated:!0,nullDisjunct:!0},none:{kind:"many",negated:!0},some:{kind:"many",negated:!1}},v=e=>P.has(e)?e:void 0,y=e=>{const t=v(e),r=t===void 0?void 0:R[t];if(!r)throw new f("INTERNAL",`unknown relation operator "${e}"`);return r},C=e=>e.kind==="one"?{clause:e.field,project:e.references}:{clause:e.references,project:e.field},F=5e3,u=Symbol("relation-key-overflow"),g=e=>Array.isArray(e)?e.map(t=>t??{}):[],A=e=>{if(e.length===1){const[t]=e;return t??{}}return e.length===0?{}:{AND:e}},p=e=>M(e),h=(e,t,r)=>{const n=t.tables[r]?.relationMap??{};return Object.keys(e).some(o=>{const s=e[o];return o==="AND"||o==="OR"?g(s).some(a=>h(a,t,r)):o==="NOT"?h(s??{},t,r):!!n[o]&&p(s)})},ne=(e,t,r,n)=>{if(e&&h(e,t,r))throw new f("INTERNAL",`relation-crossing predicates are not supported in ${n}() — use them in findMany/findFirst or an RLS read policy`)},T=async(e,t,r,n,o)=>{const s=await l(t,e.table,n),{page:a}=await n.fetcher(e.table,{baseWhere:n.relationBaseWhere?.(e.table),limit:o,relationBaseWhere:n.relationBaseWhere,where:s});return{keys:I(a,r),rows:a.length}},N=(e,t,r,n=!1)=>{throw new f("INTERNAL",`relation predicate on "${e.table}" matched ${n?"at least ":""}${String(t)} rows, exceeding the ${String(r.maxRelationKeys)}-key limit; narrow the predicate (a same-shard EXISTS push-down lifts this cap)`)},W=async(e,t,r,n,o)=>{const{keys:s}=await T(e,t,r,n);return s.length<=n.maxRelationKeys?s:o?u:N(e,s.length,n)},w=async(e,t,r,n)=>{const{keys:o,rows:s}=await T(e,t,r,n,n.maxRelationKeys+1);return s>n.maxRelationKeys?N(e,s,n,!0):o},q=async(e,t,r,n,o)=>{const s=y(e),{clause:a,project:d}=C(t),i=await W(t,s.negateChild?{NOT:r}:r,d,n,o);return i===u?u:s.negated?s.nullDisjunct?{OR:[{[a]:{notIn:i}},{[a]:{isNull:!0}}]}:{[a]:{notIn:i}}:{[a]:{in:i}}},H=async(e,t,r,n)=>{const o=y(e),{from:s,table:a,to:d}=t.through,i=await w(t,o.negateChild?{NOT:r}:r,"_id",n),c=i.length===0?[]:await w({table:a},{[d]:{in:i}},s,n);return{_id:o.negated?{notIn:c}:{in:c}}},E=async(e,t,r,n,o)=>{const s=y(e),a=o.relationBaseWhere?.(t.table),d=s.negateChild?{NOT:r}:r,j={childWhere:await l(a?{AND:[a,d]}:d,t.table,o),negated:s.negated,parentTable:n,relation:t};return{[B]:j}},Y=(e,t,r)=>{const n=v(e),o=n===void 0?void 0:R[n];if(o&&o.kind!==r.kind)throw new f("INTERNAL",`relation operator "${e}" requires a to-${o.kind} relation, but "${t}" is to-${r.kind}`)},x=async(e,t,r,n,o)=>{const s=[];for(const a of Object.keys(r)){Y(a,e,t);const d=r[a]??{};if(t.through!==void 0){s.push(await H(a,t,d,o));continue}const i=o.canPushExists?.(t)??!1;if(i&&o.existsPushMode==="always"){s.push(await E(a,t,d,n,o));continue}const c=await q(a,t,d,o,i);c===u?s.push(await E(a,t,d,n,o)):s.push(c)}return A(s)},z=async(e,t,r,n)=>{if(e==="AND"||e==="OR"){const s=[];for(const a of g(t))s.push(await l(a,r,n));return{[e]:s}}if(e==="NOT")return{NOT:await l(t??{},r,n)};const o=n.schema.tables[r]?.relationMap?.[e];return o&&p(t)?x(e,o,t,r,n):{[e]:t}},l=async(e,t,r)=>{const n=[];for(const o of Object.keys(e))n.push(await z(o,e[o],t,r));return A(n)},Q=async(e,t)=>!e||!h(e,t.schema,t.tableName)?e:l(e,t.tableName,{canPushExists:t.canPushExists,existsPushMode:t.existsPushMode??"auto",fetcher:t.fetcher,maxRelationKeys:t.maxRelationKeys??F,relationBaseWhere:t.relationBaseWhere,schema:t.schema}),oe=async(e,t,r)=>{const n=S(t.orderBy,e.shape,{pinned:L(t.where),uniqueBy:_(e.indexes,e.shape)}),o=t.cursor?k(n,K(t.cursor)):void 0;let s=b(t.baseWhere,t.where);s=b(s,D(e.softDeleteMode,t.includeDeleted)),s=await Q(s,{...r,relationBaseWhere:t.relationBaseWhere}),o&&(s=s?{AND:[s,o]}:o);const a=typeof t.limit=="number"?Math.max(0,Math.floor(t.limit)):void 0;return{fetchLimit:a===void 0?void 0:a+1,limit:a,orderKeys:n,predicate:s}},m=(e,t,r)=>{for(const n of e){const o=$(n,t,r);if(o)return o}},X=(e,t,r,n)=>{if(e==="AND"||e==="OR")return m(g(t),r,n);if(e==="NOT")return m([t??{}],r,n);const o=r.tables[n]?.relationMap?.[e];if(!o||!p(t))return;const s=o.through===void 0?[o.table]:[o.table,o.through.table],a=s.find(i=>r.tables[i]?.shardMode?.kind==="shardBy");if(a!==void 0)return{kind:"shard",relation:e,target:a};const d=s.find(i=>O(r.tables[i]));return d!==void 0?{kind:"memory",relation:e,target:d}:m(Object.values(t),r,o.table)},$=(e,t,r)=>{for(const n of Object.keys(e)){const o=X(n,e[n],t,r);if(o)return o}},U=(e,t,r)=>{if(!(t.tables[r]?.shardMode?.kind==="global"||!h(e,t,r)))throw Object.assign(new Error(`shape on "${r}" filters by a relation, which a shard-local shape cannot replicate: its seed and membership probe read "${r}" alone, so the relation never matches, and a write that only touches the related table never moves the shape. Fix it by (a) denormalizing the related columns into "${r}" and filtering on those, (b) moving "${r}" to .global() so it is served through the latency-tiered D1 shape tier, or (c) reading it through a live query (\`useQuery\`), which does resolve relations.`),{code:"SHAPE_RELATION_PREDICATE",name:"LunoraError",status:400})},se=(e,t,r)=>{if(O(t.tables[r]))throw Object.assign(new Error(`shape on "${r}" replicates from the changelog, which never records a .memory() table — the shape would seed once and never update again. Fix it by (a) dropping .memory() from "${r}" so its writes reach the changelog, or (b) reading it through a live query (\`useQuery\`), which refreshes off the changed-table set rather than the log.`),{code:"SHAPE_MEMORY_TABLE",name:"LunoraError",status:400});if(!e)return;const n=$(e,t,r);if(!n){U(e,t,r);return}throw n.kind==="memory"?Object.assign(new Error(`shape on "${r}" joins the .memory() table "${n.target}" via relation "${n.relation}" — writes to a .memory() table never reach the changelog, so the shape is never told its membership changed and would serve stale rows indefinitely. Fix it by (a) dropping .memory() from "${n.target}", or (b) reading it through a live query (\`useQuery\`), which refreshes off the changed-table set rather than the log.`),{code:"SHAPE_MEMORY_TABLE",name:"LunoraError",status:400}):Object.assign(new Error(`shape on "${r}" joins the sharded table "${n.target}" via relation "${n.relation}" — a live shape cannot replicate rows that live in another shard's Durable Object. Fix it by (a) denormalizing the joined columns into "${r}", or (b) moving "${n.target}" to .global() so it is served through the latency-tiered D1 shape tier.`),{code:"SHAPE_CROSS_SHARD_JOIN",name:"LunoraError",status:400})};export{F as DEFAULT_MAX_RELATION_KEYS,ne as assertFlatPredicate,se as assertShapeShardable,oe as composeReadPredicate,h as containsRelationPredicate,p as isRelationPredicate,Q as resolveRelationPredicates};
|