@lunora/shard-engine 1.0.0-alpha.130 → 1.0.0-alpha.131

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.
@@ -1 +1 @@
1
- import{defineEngineContractSuite as t}from"../packem_shared/defineEngineContractSuite-CMbAZiZB.mjs";export{t as defineEngineContractSuite};
1
+ import{defineEngineContractSuite as t}from"../packem_shared/defineEngineContractSuite-DdD3QXbx.mjs";export{t as defineEngineContractSuite};
package/dist/index.d.mts CHANGED
@@ -637,6 +637,7 @@ interface DatabaseWriterLike {
637
637
  allowExplicitId?: boolean;
638
638
  limit?: number;
639
639
  }) => Promise<string[]>;
640
+ inTransaction?: () => boolean;
640
641
  lookupById?: (id: string, expectedTable?: string) => Promise<null | {
641
642
  row: Record<string, unknown>;
642
643
  tableName: string;
@@ -679,6 +680,7 @@ interface DatabaseWriterLike {
679
680
  allowExplicitId?: boolean;
680
681
  }) => Promise<void>;
681
682
  restore?: (id: string, expectedTable?: string) => Promise<void>;
683
+ softDeleteFields?: ReadonlyMap<string, string>;
682
684
  system?: SystemDatabaseReader;
683
685
  wipeShard?: (options?: {
684
686
  chunkSize?: number;
package/dist/index.d.ts CHANGED
@@ -637,6 +637,7 @@ interface DatabaseWriterLike {
637
637
  allowExplicitId?: boolean;
638
638
  limit?: number;
639
639
  }) => Promise<string[]>;
640
+ inTransaction?: () => boolean;
640
641
  lookupById?: (id: string, expectedTable?: string) => Promise<null | {
641
642
  row: Record<string, unknown>;
642
643
  tableName: string;
@@ -679,6 +680,7 @@ interface DatabaseWriterLike {
679
680
  allowExplicitId?: boolean;
680
681
  }) => Promise<void>;
681
682
  restore?: (id: string, expectedTable?: string) => Promise<void>;
683
+ softDeleteFields?: ReadonlyMap<string, string>;
682
684
  system?: SystemDatabaseReader;
683
685
  wipeShard?: (options?: {
684
686
  chunkSize?: number;
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-yxw7vFf9.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-C_ZipS9R.mjs";import{aggregateTableName as f,coerceAggregateNumber as h,encodeAggregateKey as x,foldAggregateTally as E,readAggregateValue as T}from"./packem_shared/aggregateTableName-B_CtIQCS.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-CuIP7PJ0.mjs";import{NotUniqueError as y,assertNoExplicitUndefined as N,assertValidClientId as k,createShardCtxDb as B,normalizeIdStructurally as U,stripReservedPatchFields as G}from"./packem_shared/NotUniqueError-CApXRyGS.mjs";import{backfillAggregateIndexes as q,backfillRankIndexes as v,backfillSearchIndexes as K,backfillSearchIndexesForTable as W}from"./packem_shared/backfillAggregateIndexes-Dw4Azd33.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-DsCz-DAV.mjs";import{archiveCdcSegment as ue,cdcArchiveRewound as fe,readArchivedCdcChanges as he,readCdcArchivedThrough as xe,writeCdcArchivedThrough as Ee}from"./packem_shared/archiveCdcSegment-CIiYU1FU.mjs";import{CLIENT_WATERMARK_TABLE as Re,advanceClientWatermark as Ce,migrateClientWatermark as Ae,readClientWatermark as ge}from"./packem_shared/CLIENT_WATERMARK_TABLE-_CkdMnT2.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-BcUO15fR.mjs";import{clearCompanionSignatures as Fe}from"./packem_shared/clearCompanionSignatures-8uVX84aT.mjs";import{createCompanionSync as ye}from"./packem_shared/createCompanionSync-DhYLePyV.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-Du0PbPdS.mjs";import{IDEMPOTENCY_TABLE as Ke,migrateIdempotency as We,readIdempotent as Xe,trimIdempotent as He,writeIdempotent as Ve}from"./packem_shared/IDEMPOTENCY_TABLE-CymJf4r0.mjs";import{clearMemoryTables as Qe,isMemoryTable as Ye,memoryTableNames as je}from"./packem_shared/clearMemoryTables-Lu0S2GOb.mjs";import{computeRankPage as Ze,resolveRankSeekTuple as $e}from"./packem_shared/computeRankPage-DLSi_oBt.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-C_Me442c.mjs";import{S as mr,m as pr,r as Sr,w as ur}from"./packem_shared/ctx-db-search-state-CrTLPmFN.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-B6MXBH-p.mjs";import{selectShapeMembers as Ir,selectShapeRows as br}from"./packem_shared/selectShapeMembers-B1MIaRkE.mjs";import{DATA_MIGRATION_STATE_TABLE as Dr,readMigrationStatus as Pr,runDataMigration as Or}from"./packem_shared/DATA_MIGRATION_STATE_TABLE-CmsAKy5V.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-B2GG3IJa.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-DqU-17Fs.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-BdNnnMj0.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-DF_Jrgpy.mjs";import{DurableStreamRunner as Eo,MAX_DURABLE_STREAM_BYTES as To,MAX_DURABLE_STREAM_CHUNKS as Ro,decideDurableAttach as Co}from"./packem_shared/DurableStreamRunner-Dzge_ywD.mjs";import{envOptionalPositiveInt as go,envPositiveInt as _o}from"./packem_shared/envOptionalPositiveInt-D2pY-c64.mjs";import{diffExternalSource as bo}from"./packem_shared/diffExternalSource-B0FZlDoL.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-D2zEvCAa.mjs";import{isSoftDeleted as Uo,isSourceDue as Go,pullExternalSourceIncrementalTick as wo,pullExternalSourceTick as qo}from"./packem_shared/isSoftDeleted-D5MeQSk0.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-DzfEHonU.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-B0QCN3HM.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-BP1GSXQ0.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-CA_H466g.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-6offuG6M.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-jEc6-2wm.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-D3ye2GsL.mjs";import{ReactiveCache as Rt,reactiveCacheKey as Ct}from"./packem_shared/ReactiveCache-DHhhLJtN.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-DHaBP_vb.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-DQ3eWAGd.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-CVqN4JEu.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-BYfAkNAH.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-BwxDC4lU.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-B3pRMuqb.mjs";import{DEFAULT_MAX_RELAYS as Es,OwnerRelay as Ts,RelayMember as Rs,createRelayLink as Cs}from"./packem_shared/DEFAULT_MAX_RELAYS-ZRhh4qpX.mjs";import{createReplicaLink as gs,gateReplicaDispatch as _s,handleReplicaControl as Is}from"./packem_shared/createReplicaLink-Bd7jCjDt.mjs";import{buildReprojectionMigration as Ls,countLegacyRows as Ds,reprojectableFields as Ps,reprojectionTables as Os}from"./packem_shared/buildReprojectionMigration-DQV0q3w9.mjs";import{RLS_UNWRAP_SYMBOL as Ms,RlsRequiredError as ys,guardWriter as Ns}from"./packem_shared/RLS_UNWRAP_SYMBOL-DQt9luIF.mjs";import{SCHEMA_HISTORY_MAX_VERSIONS as Bs,readSchemaHistory as Us,readSchemaVersion as Gs,recordSchemaVersion as ws}from"./packem_shared/SCHEMA_HISTORY_MAX_VERSIONS-SQVxBlum.mjs";import{serializeSqlValue as vs}from"./packem_shared/serializeSqlValue-DeoBMpZ2.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-BHr3i1m6.mjs";import{ShapeDiffCache as Ys,createShapeDiffCache as js,globalShapeReadKey as Js}from"./packem_shared/ShapeDiffCache-iNO-hUiy.mjs";import{buildPokeFrames as $s,diffGlobalMembership as ei,encodeRowsPatch as ri,projectColumns as oi}from"./packem_shared/buildPokeFrames-WR-hp0mX.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-DE6yshOt.mjs";import{awaitWsDrain as Ci,subscriptionFrames as Ai,subscriptionListDeltas as gi,trySendFrame as _i}from"./packem_shared/awaitWsDrain-N-oR29RI.mjs";import{mergeChangedKeys as bi,recordChangedKeys as Li,writeTouchesMemo as Di}from"./packem_shared/mergeChangedKeys-CF2mjYuy.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-Dmj5VBrV.mjs";import{hasTrigger as Ui,runTriggers as Gi}from"./packem_shared/hasTrigger-CjlwI4le.mjs";import{selectExpiredIds as qi}from"./packem_shared/selectExpiredIds-B8PxwbIr.mjs";import{VECTOR_BACKFILL_MAX_PAGES as Ki,backfillVectorIndexes as Wi}from"./packem_shared/VECTOR_BACKFILL_MAX_PAGES-DY_3FYts.mjs";import{c as Hi,s as Vi}from"./packem_shared/where-sql-DO1vOrhc.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-BeqUbznb.mjs";import{stableStringify as sl,stableWireKey as il}from"@lunora/wire";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,il 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-yxw7vFf9.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-C_ZipS9R.mjs";import{aggregateTableName as f,coerceAggregateNumber as h,encodeAggregateKey as x,foldAggregateTally as E,readAggregateValue as T}from"./packem_shared/aggregateTableName-B_CtIQCS.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-CuIP7PJ0.mjs";import{NotUniqueError as y,assertNoExplicitUndefined as N,assertValidClientId as k,createShardCtxDb as B,normalizeIdStructurally as U,stripReservedPatchFields as G}from"./packem_shared/NotUniqueError-CNXsYOSU.mjs";import{backfillAggregateIndexes as q,backfillRankIndexes as v,backfillSearchIndexes as K,backfillSearchIndexesForTable as W}from"./packem_shared/backfillAggregateIndexes-Dw4Azd33.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-DsCz-DAV.mjs";import{archiveCdcSegment as ue,cdcArchiveRewound as fe,readArchivedCdcChanges as he,readCdcArchivedThrough as xe,writeCdcArchivedThrough as Ee}from"./packem_shared/archiveCdcSegment-CIiYU1FU.mjs";import{CLIENT_WATERMARK_TABLE as Re,advanceClientWatermark as Ce,migrateClientWatermark as Ae,readClientWatermark as ge}from"./packem_shared/CLIENT_WATERMARK_TABLE-_CkdMnT2.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-BcUO15fR.mjs";import{clearCompanionSignatures as Fe}from"./packem_shared/clearCompanionSignatures-8uVX84aT.mjs";import{createCompanionSync as ye}from"./packem_shared/createCompanionSync-DhYLePyV.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-Du0PbPdS.mjs";import{IDEMPOTENCY_TABLE as Ke,migrateIdempotency as We,readIdempotent as Xe,trimIdempotent as He,writeIdempotent as Ve}from"./packem_shared/IDEMPOTENCY_TABLE-CymJf4r0.mjs";import{clearMemoryTables as Qe,isMemoryTable as Ye,memoryTableNames as je}from"./packem_shared/clearMemoryTables-Lu0S2GOb.mjs";import{computeRankPage as Ze,resolveRankSeekTuple as $e}from"./packem_shared/computeRankPage-DLSi_oBt.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-C_Me442c.mjs";import{S as mr,m as pr,r as Sr,w as ur}from"./packem_shared/ctx-db-search-state-CrTLPmFN.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-B6MXBH-p.mjs";import{selectShapeMembers as Ir,selectShapeRows as br}from"./packem_shared/selectShapeMembers-B1MIaRkE.mjs";import{DATA_MIGRATION_STATE_TABLE as Dr,readMigrationStatus as Pr,runDataMigration as Or}from"./packem_shared/DATA_MIGRATION_STATE_TABLE-CmsAKy5V.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-B2GG3IJa.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-DqU-17Fs.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-BdNnnMj0.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-DF_Jrgpy.mjs";import{DurableStreamRunner as Eo,MAX_DURABLE_STREAM_BYTES as To,MAX_DURABLE_STREAM_CHUNKS as Ro,decideDurableAttach as Co}from"./packem_shared/DurableStreamRunner-Dzge_ywD.mjs";import{envOptionalPositiveInt as go,envPositiveInt as _o}from"./packem_shared/envOptionalPositiveInt-D2pY-c64.mjs";import{diffExternalSource as bo}from"./packem_shared/diffExternalSource-B0FZlDoL.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-D2zEvCAa.mjs";import{isSoftDeleted as Uo,isSourceDue as Go,pullExternalSourceIncrementalTick as wo,pullExternalSourceTick as qo}from"./packem_shared/isSoftDeleted-D5MeQSk0.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-DzfEHonU.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-B0QCN3HM.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-BP1GSXQ0.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-CA_H466g.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-6offuG6M.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-jEc6-2wm.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-D3ye2GsL.mjs";import{ReactiveCache as Rt,reactiveCacheKey as Ct}from"./packem_shared/ReactiveCache-DHhhLJtN.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-DHaBP_vb.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-DQ3eWAGd.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-CVqN4JEu.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-BYfAkNAH.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-BwxDC4lU.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-B3pRMuqb.mjs";import{DEFAULT_MAX_RELAYS as Es,OwnerRelay as Ts,RelayMember as Rs,createRelayLink as Cs}from"./packem_shared/DEFAULT_MAX_RELAYS-ZRhh4qpX.mjs";import{createReplicaLink as gs,gateReplicaDispatch as _s,handleReplicaControl as Is}from"./packem_shared/createReplicaLink-Bd7jCjDt.mjs";import{buildReprojectionMigration as Ls,countLegacyRows as Ds,reprojectableFields as Ps,reprojectionTables as Os}from"./packem_shared/buildReprojectionMigration-DQV0q3w9.mjs";import{RLS_UNWRAP_SYMBOL as Ms,RlsRequiredError as ys,guardWriter as Ns}from"./packem_shared/RLS_UNWRAP_SYMBOL-J1tiBtRj.mjs";import{SCHEMA_HISTORY_MAX_VERSIONS as Bs,readSchemaHistory as Us,readSchemaVersion as Gs,recordSchemaVersion as ws}from"./packem_shared/SCHEMA_HISTORY_MAX_VERSIONS-SQVxBlum.mjs";import{serializeSqlValue as vs}from"./packem_shared/serializeSqlValue-DeoBMpZ2.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-BHr3i1m6.mjs";import{ShapeDiffCache as Ys,createShapeDiffCache as js,globalShapeReadKey as Js}from"./packem_shared/ShapeDiffCache-iNO-hUiy.mjs";import{buildPokeFrames as $s,diffGlobalMembership as ei,encodeRowsPatch as ri,projectColumns as oi}from"./packem_shared/buildPokeFrames-WR-hp0mX.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-DE6yshOt.mjs";import{awaitWsDrain as Ci,subscriptionFrames as Ai,subscriptionListDeltas as gi,trySendFrame as _i}from"./packem_shared/awaitWsDrain-N-oR29RI.mjs";import{mergeChangedKeys as bi,recordChangedKeys as Li,writeTouchesMemo as Di}from"./packem_shared/mergeChangedKeys-CF2mjYuy.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-Dmj5VBrV.mjs";import{hasTrigger as Ui,runTriggers as Gi}from"./packem_shared/hasTrigger-CjlwI4le.mjs";import{selectExpiredIds as qi}from"./packem_shared/selectExpiredIds-B8PxwbIr.mjs";import{VECTOR_BACKFILL_MAX_PAGES as Ki,backfillVectorIndexes as Wi}from"./packem_shared/VECTOR_BACKFILL_MAX_PAGES-DY_3FYts.mjs";import{c as Hi,s as Vi}from"./packem_shared/where-sql-DO1vOrhc.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-BeqUbznb.mjs";import{stableStringify as sl,stableWireKey as il}from"@lunora/wire";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,il 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 $}from"@lunora/errors";import{D as ft}from"./MAX_TOKEN_LENGTH-BakL9FUy-B3VwYY8C.mjs";import{S as Tn,l as We,h as vn}from"./fts-companion-DzfEHonU.mjs";import{decodeWire as An,stableWireKey as bt}from"@lunora/wire";import{sql as a}from"drizzle-orm";import{throwingScheduler as In,aggregateSqlFunction as Be,normalizeCountArgument as Cn}from"./AGGREGATE_SQL_FUNCTION-C_ZipS9R.mjs";import{aggregateTableName as et,encodeAggregateKey as tt,readAggregateValue as nt}from"./aggregateTableName-B_CtIQCS.mjs";import{mergeWhere as K,CountRlsUnsupportedError as ot,selectIndexForGroupBy as xn,selectIndexForCount as bn,selectIndexForAggregate as Mn}from"./CountRlsUnsupportedError-BvsDqfO2.mjs";import{backfillSearchIndexesForTable as Dn,searchIndexCoversTable as kn}from"./backfillAggregateIndexes-Dw4Azd33.mjs";import{backfillAggregateIndexes as si,backfillRankIndexes as ci,backfillSearchIndexes as ai}from"./backfillAggregateIndexes-Dw4Azd33.mjs";import{appendCdcChange as Fn,readCdcDocAtOrBefore as Ln}from"./CDC_LOG_TABLE-DsCz-DAV.mjs";import{CDC_LOG_TABLE as li,applyCdcChanges as ui,bumpCdcEpoch as fi,cdcCanVouchFor as hi,cdcForkedError as wi,cdcSeqLeavingRows as pi,cdcTouchesTables as gi,cdcTrimmedError as yi,compactCdcDocs as $i,cursorBelowRetainedFloor as Ei,minCdcReplayableSeq as mi,minCdcSeq as Si,readCdcChangeKeys as _i,readCdcChanges as Ri,readCdcCursor as Ti,readCdcEpoch as vi,trimCdcChanges as Ai}from"./CDC_LOG_TABLE-DsCz-DAV.mjs";import{allocateCommitSeq as qn,COMMIT_SEQ_FIELD as Wn}from"./COMMIT_SEQ_FIELD-BcUO15fR.mjs";import{createCompanionSync as Bn}from"./createCompanionSync-DhYLePyV.mjs";import{isMemoryTable as Mt}from"./clearMemoryTables-Lu0S2GOb.mjs";import{computeRankPage as Dt}from"./computeRankPage-DLSi_oBt.mjs";import{SCAN_DEP as U}from"./SCAN_DEP-D7qE3iUe.mjs";import{runSql as fe,runDrizzle as G}from"./runDrizzle-B2GG3IJa.mjs";import{p as Pn,j as dt,D as re,r as ve,k as ae,b as Pe,A as rt,a as Ue,m as le,e as ue,s as Un,t as rn,i as On,q as kt,h as sn,g as Hn}from"./do-sql-DqU-17Fs.mjs";import{renderSql as cn,unionAll as ht,WORKERD_SQLITE_LIMITS as an,sqliteInList as Gn}from"./WORKERD_SQLITE_LIMITS-BdNnnMj0.mjs";import{coveringGeohashes as jn,boundingBoxGeohashes as Kn,haversineMeters as Nn,pointInBoundingBox as Qn}from"./GEO_DEFAULT_PRECISION-CqpQZ-J_.mjs";import{NotFoundError as Vn}from"./NotFoundError-BhF7FeFr.mjs";import{resolvePatch as Jn,assertPatchAllowed as zn,operatorFields as Yn,readPatchField as Ft}from"./assertPatchAllowed-CA_H466g.mjs";import{tiebreakDirectionFor as Xn,encodeCursor as je,nullsOrderSuffix as Zn,normalizeOrderKeys as Lt,uniqueIndexFields as eo,buildSeekWhere as to,decodeCursor as qt,buildSeekBeforeWhere as no,softDeleteScope as Te,applySelect as Wt}from"./CURSOR_PREFIX-6offuG6M.mjs";import{rankTableName as Bt,sortColumnName as Pt,resolveRankPartition as oo,encodePartitionKey as ro,RANK_TIEBREAK as io,rankPivotConditionSql as so}from"./RANK_TIEBREAK-D3ye2GsL.mjs";import{UNVOUCHABLE_DEP as Ut}from"./UNVOUCHABLE_DEP-C68htACn.mjs";import{indexKeysForRow as co,buildIndexRange as ao}from"./buildIndexRange-DQ3eWAGd.mjs";import{r as Ke,j as Ae,c as Y,t as Ne,i as Ot}from"./where-sql-DO1vOrhc.mjs";import{serializeSqlValue as Ie}from"./serializeSqlValue-DeoBMpZ2.mjs";import{quoteIdentifier as Ce}from"./quoteIdentifier-CObIFRhb.mjs";import{whereOfFilter as lo,isPushableWhere as uo}from"./isPushableWhere-BeYAOjUb.mjs";import{deriveRelationEdges as fo,findRelated as ho}from"./RELATED_DEFAULT_LIMIT-CVqN4JEu.mjs";import{assertFlatPredicate as it,resolveRelationPredicates as wo,composeReadPredicate as po}from"./DEFAULT_MAX_RELATION_KEYS-BYfAkNAH.mjs";import{describeRelationWrites as go}from"./describeRelationWrites-omar6-u9.mjs";import{runRowValidators as st,resolveWith as Ht,relationHooks as Gt,applyOnDelete as yo,fanOutScalarCounts as $o}from"./applyOnDelete-BwxDC4lU.mjs";import{guardWriter as Eo}from"./RLS_UNWRAP_SYMBOL-J1tiBtRj.mjs";import{mayHoldProjectedValue as mo}from"./BIGINT_KEY_DIGITS-DE6yshOt.mjs";import{createSystemReader as So}from"./createSystemReader-DcDLFfC-.mjs";import{ConflictError as se}from"./ConflictError-C8GtJmjS.mjs";import{hasTrigger as jt,runTriggers as _o}from"./hasTrigger-CjlwI4le.mjs";import{advanceClientWatermark as Ci,migrateClientWatermark as xi,readClientWatermark as bi}from"./CLIENT_WATERMARK_TABLE-_CkdMnT2.mjs";import{IDEMPOTENCY_TABLE as Di,readIdempotent as ki,trimIdempotent as Fi,writeIdempotent as Li}from"./IDEMPOTENCY_TABLE-CymJf4r0.mjs";import{runShardMigrations as Wi}from"./runShardMigrations-BeqUbznb.mjs";import{selectShapeMembers as Pi,selectShapeRows as Ui}from"./selectShapeMembers-B1MIaRkE.mjs";const Ro=n=>{const i=atob(n),o=Uint8Array.from(i,c=>c.codePointAt(0)??0);return new TextDecoder().decode(o)},To=()=>new $("BAD_REQUEST","invalid cursor"),Kt=16,Nt=8,V=1024,wt=(n,i)=>i.query(n),vo=(n,i)=>{if(n.length===0)return 0;let o=0;for(const[c,s]of i.entries()){const w=c===i.length-1;let _=0;for(const S of n)(w?S.startsWith(s):S===s)&&(_+=1);if(_===0)return 0;o+=_}return o},Ao=(n,i)=>{if(!i)return{exact:!0,lower:n,upper:n};const o=[...n].at(-1)??"",c=(o.codePointAt(0)??0)+1;if(c>=55296&&c<=57343||c>1114111)return{exact:!0,lower:n,upper:n};const s=n.slice(0,n.length-o.length);return{exact:!1,lower:n,upper:s+String.fromCodePoint(c)}},Io=(n,i,o)=>{const c={eq:(s,w)=>{if(!n.definition.filterFields?.includes(s))throw new $("INTERNAL",`field "${s}" is not a filter field of search index "${n.indexName}" on table "${i}"`);if(n.filters.length>=Nt)throw new $("BAD_REQUEST",`search index "${n.indexName}" on table "${i}": at most ${String(Nt)} .eq() filters are supported per search query`);return n.filters.push({field:s,value:w}),c},search:(s,w)=>{const _=n;if(s!==_.definition.field)throw new $("INTERNAL",`search index "${_.indexName}" on table "${i}" indexes "${_.definition.field}", not "${s}"`);const S=wt(w,o).length;if(S>Kt)throw new $("BAD_REQUEST",`search index "${_.indexName}" on table "${i}": at most ${String(Kt)} search terms are supported (got ${String(S)})`);return _.field=s,_.query=w,_.hasQuery=!0,c}};return c},Co=n=>{if(n.length>V)throw new $("BAD_REQUEST",`more than ${String(V)} documents match this search — narrow it with filters or read it a page at a time with .paginate()`)},xo=n=>Math.min(n.offset+n.numItems+1,V),bo=n=>btoa(`search:${String(n)}`),Mo=n=>{let i;try{i=Ro(n)}catch{return}if(!i.startsWith("search:"))return;const o=Number(i.slice(7));return Number.isInteger(o)&&o>=0?o:void 0},Do=n=>{if(typeof n.endCursor=="string")throw new $("BAD_REQUEST","bounded (endCursor) pagination is not supported on search queries — relevance order has no stable range boundary");if(!Number.isFinite(n.numItems))throw new $("BAD_REQUEST",`search pagination needs a finite numItems, got ${String(n.numItems)}`);const i=Math.max(0,Math.floor(n.numItems)),o=n.cursor?Mo(n.cursor):0;if(o===void 0)throw To();if(o+i>=V)throw new $("BAD_REQUEST",`search pagination reaches the ${String(V)}-document limit (offset ${String(o)} + ${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,V-o-1))} or fewer, or narrow the query or the filters instead`);return{numItems:i,offset:o}},ko=(n,i)=>{const o=i.offset+i.numItems,c=i.numItems>0&&n.length>o;return{continueCursor:c?bo(o):null,isDone:!c,page:n.slice(i.offset,o)}},Fo=n=>{if(n===void 0)return V+1;if(!Number.isFinite(n))return V;const i=Math.max(0,Math.floor(n));if(i>V)throw new $("BAD_REQUEST",`search returns at most ${String(V)} documents (asked for ${String(i)}) — narrow the query or paginate instead`);return i},Lo=32,qo=1024,dn=(n,i,o,c)=>{const s=`SELECT id, _creationTime, ${Ce(re)} FROM ${Ce(n)}`,w=`ORDER BY ${o}${c===void 0?"":` LIMIT ${String(c)}`}`;return i===void 0?Ke(`${s} ${w}`):Ae(`${s} WHERE `,i,` ${w}`)},Qe={fieldRef:n=>Ke(dt(n)),rangeTypeGuard:(n,i)=>Ke(Pn(n,i)),serialize:Ie},Wo=n=>n===void 0?"":Zn(n==="first"),ln=n=>{const i=n.map(o=>`${dt(o.field)} ${o.direction==="desc"?"DESC":"ASC"}${Wo(o.nulls)}`);return n.some(o=>o.field==="_id"||o.field==="id")||i.push(`${dt("id")} ${Xn(n)==="desc"?"DESC":"ASC"}`),i.join(", ")},Bo={"<":"lt","<=":"lte","=":"eq",">":"gt",">=":"gte"},un=n=>new Set(n.sqlConditions.filter(i=>i.comparator==="=").map(i=>i.field)),Po=n=>{const i=un(n);let o=0;for(;o<n.indexFields.length&&i.has(n.indexFields[o]??"");)o+=1;return n.indexFields.slice(o)},Uo=(n,i)=>{const o=n.order,c=Po(n),{shape:s}=i;return c.length>0?Lt(c.map(w=>({[w]:o})),s,{pinned:un(n),uniqueBy:eo(i.indexes,s)}):Lt([{_creationTime:o}],s)},Oo=(n,i,o,c)=>{const s=n.sqlConditions.map(w=>({[w.field]:{[Bo[w.comparator]??"eq"]:w.value}}));if(o&&s.push(to(i,qt(o))),c&&s.push(no(i,qt(c))),s.length!==0)return s.length===1?s[0]:{AND:s}},Ho=n=>{if(n.want!==void 0)return n.selective?Math.max(n.want,Lo):n.want},lt=(n,i,o,c,s,w,_)=>{const S=Uo(c,o),b=ln(S),y=[],{filters:k,want:C}=w;let A=w.cursor??void 0,I=Ho(w);if(C===0)return{documents:y,orderKeys:S};for(;;){const q=Y(Oo(c,S,A,w.endCursor),Qe,Ne),F=dn(i,s&&q?Ae(q," AND ",s):s??q,b,I),L=fe(n,F.text,...F.params).toArray();let W={};_(L.length);for(const O of L)if(W=ve(O),k.every(we=>we(W))&&y.push(W)===C)return{documents:y,orderKeys:S};if(I===void 0||L.length<I)return{documents:y,orderKeys:S};A=je(W,S),I=Math.max(I,Math.min(I*2,qo))}},Go=(n,i,o,c,s,w,_,S)=>{const b=Math.max(0,Math.floor(s.numItems));if(typeof s.endCursor=="string"){const{documents:q,orderKeys:F}=lt(n,i,o,c,w,{cursor:s.cursor,endCursor:s.endCursor,filters:_.all,selective:_.selective,want:void 0},S),L=q.length>=2?q[Math.floor(q.length/2)-1]:void 0;return{continueCursor:s.endCursor,isDone:!0,page:q,splitCursor:L?je(L,F):null}}const{documents:y,orderKeys:k}=lt(n,i,o,c,w,{cursor:s.cursor,filters:_.all,selective:_.selective,want:b+1},S),C=y.length>b,A=C?y.slice(0,b):y,I=A.at(-1);return{continueCursor:C&&I?je(I,k):null,isDone:!C,page:A}},Ve=n=>{const i=new Map;return o=>{const c=i.get(o);if(c!==void 0)return c;const s=n(Ce(o));return i.set(o,s),s}},he=Ce(re),jo=Ve(n=>`INSERT INTO ${n} (id, _creationTime, ${he}) VALUES (?, ?, ?)`),Qt=Ve(n=>`UPDATE ${n} SET ${he} = ? WHERE id = ? AND ${he} = ?`),Ko=Ve(n=>`UPDATE ${n} SET _creationTime = ?, ${he} = ? WHERE id = ? AND ${he} = ?`),No=Ve(n=>`DELETE FROM ${n} WHERE id = ? AND ${he} = ?`),Qo="SELECT changes() AS changed",Vt=new Map,Vo="",Jo=n=>{const i=JSON.stringify(n),o=Vt.get(i);if(o!==void 0)return o;const c=n.map(w=>a`SELECT ${a.raw(`'${w.replaceAll("'","''")}'`)} AS __t__, id, _creationTime, ${a.identifier(re)} FROM ${a.identifier(w)} WHERE id = ${Vo}`),{sql:s}=cn("sqlite",a`${ht(c)} LIMIT 1`);return Vt.set(i,s),s},zo=(n,i)=>i.map(()=>n),Yo=/^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/iu,Xo=n=>{if(!Yo.test(n))throw new $("INTERNAL",`invalid clientId ${JSON.stringify(n)}: a client-supplied row id must be a UUID`)},Jt=50,fn=500,Oe=Math.floor(an.boundParams/3),Re=an.boundParams,Zo=128,de=(n,i,o)=>{const c=i??fn;if(n>c)throw new $("BATCH_LIMIT_EXCEEDED",`${o}: batch of ${String(n)} exceeds the limit of ${String(c)} (raise options.limit or chunk the call)`,{status:400})},er=n=>{const i={eq:(o,c)=>(n.sqlConditions.push({comparator:"=",field:o,value:c}),i),gt:(o,c)=>(n.sqlConditions.push({comparator:">",field:o,value:c}),i),gte:(o,c)=>(n.sqlConditions.push({comparator:">=",field:o,value:c}),i),lt:(o,c)=>(n.sqlConditions.push({comparator:"<",field:o,value:c}),i),lte:(o,c)=>(n.sqlConditions.push({comparator:"<=",field:o,value:c}),i)};return i},tr=n=>Math.max(n,V),hn=(n,i)=>{const o=n.filters.map(c=>a`${ue(c.field)} = ${Ie(c.value)}`);return i&&o.push(i),o},nr=(n,i,o,c,s)=>{const w=wt(o.query,ft(o.definition.language));if(w.length===0)return[];const _=Tn(i,o.indexName),S=`${_}__vocab`,b=w.length-1,y=w.map((F,L)=>{const W=Ao(F,L===b),O=W.exact?a`${a.identifier("term")} = ${W.lower}`:a`${a.identifier("term")} >= ${W.lower} AND ${a.identifier("term")} < ${W.upper}`;return a`SELECT ${a.identifier("doc")}, ${a.raw(String(L))} AS ${a.identifier("__term__")}, COUNT(*) AS ${a.identifier("__n__")} FROM ${a.identifier(S)} WHERE ${O} GROUP BY ${a.identifier("doc")}`}),k=w.map((F,L)=>a`SUM(CASE WHEN u.${a.identifier("__term__")} = ${a.raw(String(L))} THEN u.${a.identifier("__n__")} ELSE 0 END)`),C=a`SELECT f.${a.identifier(We)} AS ${a.identifier(We)}, ${a.join(k,a` + `)} AS ${a.identifier("__score__")} FROM (${ht(y)}) u JOIN ${a.identifier(_)} f ON f.rowid = u.${a.identifier("doc")} GROUP BY f.${a.identifier(We)} HAVING ${a.join(k.map(F=>a`${F} > 0`),a` AND `)}`,A=hn(o,s);let I=a`SELECT m.id, m._creationTime, m.${a.identifier(re)}, s.${a.identifier("__score__")} AS ${a.identifier("__score__")} FROM (${C}) s JOIN ${a.identifier(i)} m ON m.id = s.${a.identifier(We)}`;A.length>0&&(I=a`${I} WHERE ${a.join(A,a` AND `)}`),I=a`${I} ORDER BY s.${a.identifier("__score__")} DESC, m._creationTime DESC, m.id ASC LIMIT ${a.raw(String(c))}`;const q=[];for(const F of G(n,I)){const L=sn(F);if(L){const W=F.__score__;q.push({document:L,score:typeof W=="number"?W:Number(W??0)})}}return q},or=(n,i,o,c,s)=>{const w=ft(o.definition.language),_=wt(o.query,w);if(_.length===0)return[];const S=hn(o,s);let b=a`SELECT id, _creationTime, ${a.identifier(re)} FROM ${a.identifier(i)}`;S.length>0&&(b=a`${b} WHERE ${a.join(S,a` AND `)}`),b=a`${b} ORDER BY _creationTime DESC, id ASC LIMIT ${a.raw(String(tr(c)))}`;const y=G(n,b).toArray(),k=[];for(const C of y){const A=sn(C);if(!A)continue;const I=vo(vn(A,o.definition),_);I>0&&k.push({creationTime:typeof A._creationTime=="number"?A._creationTime:0,doc:A,id:typeof A._id=="string"?A._id:"",score:I})}return k.sort((C,A)=>A.score-C.score||A.creationTime-C.creationTime||C.id.localeCompare(A.id)),k.slice(0,c).map(C=>({document:C.doc,score:C.score}))},ct=(n,i,o,c)=>{if(!Number.isFinite(n.lat)||n.lat<-90||n.lat>90||!Number.isFinite(n.lng)||n.lng<-180||n.lng>180)throw new $("BAD_REQUEST",`geo index "${c}" on table "${o}": ${i} must have a finite lat in [-90, 90] and lng in [-180, 180]`)},rr=(n,i)=>{const o=n,c={near:(s,w)=>{if(o.within)throw new $("INTERNAL",`geo index "${o.indexName}" on table "${i}": call .near() or .within(), not both`);if(ct(s,".near() point",i,o.indexName),!Number.isFinite(w)||w<=0)throw new $("BAD_REQUEST",`geo index "${o.indexName}" on table "${i}": .near() radiusMeters must be a finite number > 0, got ${String(w)}`);return o.near={point:{lat:s.lat,lng:s.lng},radiusMeters:w},c},within:s=>{if(o.near)throw new $("INTERNAL",`geo index "${o.indexName}" on table "${i}": call .near() or .within(), not both`);if(ct(s.sw,".within() sw corner",i,o.indexName),ct(s.ne,".within() ne corner",i,o.indexName),s.sw.lat>s.ne.lat)throw new $("BAD_REQUEST",`geo index "${o.indexName}" on table "${i}": .within() corners are transposed (sw.lat > ne.lat)`);if(s.sw.lng>s.ne.lng)throw new $("BAD_REQUEST",`geo index "${o.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 o.within={ne:{lat:s.ne.lat,lng:s.ne.lng},sw:{lat:s.sw.lat,lng:s.sw.lng}},c}};return c},ir=(n,i)=>{const o=n[i];if(o===null||typeof o!="object")return;const{lat:c,lng:s}=o;return typeof c=="number"&&typeof s=="number"?{lat:c,lng:s}:void 0},sr=(n,i)=>{const o=ir(n,i.definition.field);if(!o)return;const c=typeof n._creationTime=="number"?n._creationTime:0;if(i.near){const s=Nn(i.near.point,o);return s<=i.near.radiusMeters?{creationTime:c,distance:s}:void 0}return Qn(o,i.within)?{creationTime:c,distance:0}:void 0},cr=(n,i,o,c)=>{if(!o.near&&!o.within)throw new $("INTERNAL",`geo index "${o.indexName}" on table "${i}": call .near(point, radius) or .within(box)`);const s=o.near?jn(o.near.point,o.near.radiusMeters):Kn(o.within),w=Hn(i,o.indexName),_=s.map(C=>a`(g.${a.identifier("__geohash__")} >= ${C} AND g.${a.identifier("__geohash__")} < ${`${C}{`})`),S=[a`(${a.join(_,a` OR `)})`];c&&S.push(c);const b=a`SELECT m.id, m._creationTime, m.${a.identifier(re)} FROM ${a.identifier(w)} g JOIN ${a.identifier(i)} m ON m.id = g.${a.identifier("__id__")} WHERE ${a.join(S,a` AND `)}`,y=G(n,b).toArray(),k=[];for(const C of y){const A=ve(C),I=A?sr(A,o):void 0;A&&I&&k.push({creationTime:I.creationTime,distance:I.distance,doc:A})}return k.sort((C,A)=>C.distance-A.distance||A.creationTime-C.creationTime),k},wn=(n,i,o,c)=>{const s=[];for(const w of n)if(i.every(_=>_(c(w)))&&(s.push(w),typeof o=="number"&&s.length>=o))break;return s},ar=(n,i,o,c,s,w=()=>{})=>{const _=o.within!==void 0,S=cr(n,i,o,s).map(b=>({distanceMeters:_?null:b.distance,document:b.doc}));return w(S.length),typeof c=="number"?S.slice(0,Math.max(0,Math.floor(c))):S},zt=(n,i,o,c,s,w,_=()=>{})=>{const{geo:S}=o;if(!S)throw new $("INTERNAL","runGeoTerminalScored called without a staged geo query");const b=s.length>0,y=ar(n,i,S,b?void 0:w,c,_);return b?wn(y,s,w,k=>k.document):y},Yt=(n,i,o)=>{const c=n.shape[i];if(c!==void 0&&mo(c))throw new $("BAD_REQUEST",`${o}: "${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)`)},dr=n=>{let i=0;const o=[],c={...Qe,relationExists:s=>{const{childWhere:w,negated:_,parentTable:S,relation:b}=s,y=`__rel_${String(i)}`,k=o.at(-1)??S;i+=1,n(b.table,U);const C=b.kind==="one"?b.field:b.references,A=b.kind==="one"?b.references:b.field,I=Ke(`${kt(y,A)} = ${kt(k,C)}`);o.push(y);const q=Y(w,c,Ne);o.pop();const F=q===void 0?I:Ae(I," AND ",q),L=Ae("EXISTS (SELECT 1 FROM ",Ot(b.table)," AS ",Ot(y)," WHERE ",F,")");return _?Ae("NOT ",L):L}};return c};class lr extends ${constructor(i="unique() found more than one matching document"){super("NOT_UNIQUE",i,{name:"NotUniqueError"})}}const ur=/\s/u,fr=String.fromCodePoint(0),Xt=(n,i,o)=>{if(!n.tables[i])throw new $("INTERNAL",`unknown table: ${i}`);return typeof o!="string"||o.length===0||ur.test(o)||o.includes(fr)?null:o},pn=(n,i,o,c=()=>{},s=()=>{},w=()=>{},_)=>{const S=i.tables[o];if(!S)throw new $("INTERNAL",`unknown table: ${o}`);const b=Te(S.softDeleteMode,void 0),y=_??{indexFields:[],indexName:void 0,inMemoryFilters:[],order:"asc",sqlConditions:[],verifyFilters:[]},k=()=>{const p=K(b,y.pushedWhere);return p?Y(p,le):void 0},C=()=>{const p=K(b,y.pushedWhere);return p?Y(p,Qe,Ne):void 0},A=()=>[...y.inMemoryFilters,...y.verifyFilters];let I=0;const q=p=>{const{search:x}=y;if(!x)throw new $("INTERNAL","runSearchFetch called without a staged search");Dn(n,o,S);const D=y.inMemoryFilters.length>0,M=Fo(D?void 0:p),N=On(n);if(N&&!kn(n,o,x.definition))throw new $("SEARCH_INDEX_BUILDING",`search index "${x.indexName}" on table "${o}" is still backfilling and currently covers only part of the table — retry once it finishes, or run the backfillSearch admin operation to complete it now`);const oe=k(),J=N?nr(n,o,x,M,oe):or(n,o,x,M,oe);!D&&p===void 0&&Co(J);const pe=A();return I=J.length,pe.length>0?wn(J,pe,p,xe=>xe.document):J},F=p=>q(p).map(x=>x.document),L=p=>{const x=Do(p);return ko(F(xo(x)),x)},W=()=>{if(y.search||y.geo||y.indexName===void 0){s(void 0);return}s(ao(o,y.indexName,y.indexFields,y.sqlConditions,Ie))},O=p=>{W();let x=0;const D=(()=>{if(y.search){const M=F(p);return x=I,M}return y.geo?zt(n,o,y,k(),A(),p,M=>{x=M}).map(M=>M.document):lt(n,o,S,y,C(),{filters:A(),selective:y.inMemoryFilters.length>0,want:p===void 0?void 0:Math.max(0,Math.floor(p))},M=>{x+=M}).documents})();return w(Math.max(x,D.length)),D},we=()=>{if(!y.search&&!y.geo)throw new $("INTERNAL",`ctx.db.query("${o}").collectWithScores() requires a staged .withSearchIndex(...) or .withGeoIndex(...)`);W();let p=0;const x=(()=>{if(y.search){const D=q(void 0);return p=I,D}return zt(n,o,y,k(),A(),void 0,D=>{p=D})})();return w(Math.max(p,x.length)),x},ne={async*[Symbol.asyncIterator](){const p=pn(n,i,o,c,s,w,{...y,indexFields:[...y.indexFields],inMemoryFilters:[...y.inMemoryFilters],sqlConditions:[...y.sqlConditions],verifyFilters:[...y.verifyFilters]});if(y.search){yield*await p.collect();return}let x;for(;;){const D=await p.paginate({cursor:x??null,numItems:Zo});if(yield*D.page,D.isDone||D.continueCursor===null)return;x=D.continueCursor}},async collect(){return O(void 0)},async collectWithScores(){return we()},filter(p){const x=lo(p);return x!==void 0&&uo(x,S.shape)?(y.pushedWhere=K(y.pushedWhere,x),y.verifyFilters.push(p)):y.inMemoryFilters.push(p),ne},async first(){return O(1)[0]??null},order(p){return y.order=p==="desc"?"desc":"asc",ne},async paginate(p){let x=0;if(W(),y.search){const M=L(p);return w(M.page.length),M}if(y.geo)throw new $("INTERNAL","pagination is not supported on geo queries; use .take(n) or .collect()");const D=Go(n,o,S,y,p,C(),{all:A(),selective:y.inMemoryFilters.length>0},M=>{x+=M});return w(Math.max(x,D.page.length)),D},async take(p){return O(p)},async unique(){const p=O(2);if(p.length>1)throw new lr(`unique() on table "${o}" matched ${String(p.length)} documents; expected at most one`);return p[0]??null},withGeoIndex(p,x){const D=(S.geoIndexes??[]).find(N=>N.name===p);if(!D)throw new $("INTERNAL",`unknown geo index "${p}" on table "${o}"`);c(o,p,"geo");const M={definition:D,indexName:p};if(y.geo=M,x(rr(M,o)),!M.near&&!M.within)throw new $("INTERNAL",`geo index "${p}" on table "${o}" requires a .near(point, radius) or .within(box) call`);return ne},withIndex(p,x){const D=S.indexes.find(M=>M.name===p);if(!D)throw new $("INTERNAL",`unknown index "${p}" on table "${o}"`);return c(o,p,"index"),y.indexName=p,y.indexFields=D.fields,x&&x(er(y)),ne},withSearchIndex(p,x){const D=(S.searchIndexes??[]).find(N=>N.name===p);if(!D)throw new $("INTERNAL",`unknown search index "${p}" on table "${o}"`);c(o,p,"search");const M={definition:D,field:D.field,filters:[],hasQuery:!1,indexName:p,query:""};if(y.search=M,x(Io(M,o,ft(D.language))),!M.hasQuery)throw new $("INTERNAL",`search index "${p}" on table "${o}" requires a .search(field, query) call`);return ne}};return ne},Zt=(n,i,o)=>{const c={...i};for(const[s,w]of rn(n)){if(w.serverDefault){c[s]=w.serverDefault({auth:o});continue}c[s]===void 0&&(w.defaultFn?c[s]=w.defaultFn():"defaultValue"in w&&(c[s]=w.defaultValue))}return c},at=(n,i,o,c)=>{const s=o;for(const[w,_]of rn(n)){if(_.serverDefault){w in i&&(s[w]=_.serverDefault({auth:c}));continue}_.onUpdateFn&&!(w in i)&&(s[w]=_.onUpdateFn())}},en=5,tn=(n,i)=>{for(const o of Object.keys(i))if(i[o]===void 0)throw new $("INTERNAL",`Cannot ${n} field '${o}' to undefined — use null to clear a nullable field, or omit the key to leave it unchanged.`)},nn=["_commitSeq","_creationTime","_id"],He=n=>nn.some(i=>i in n)?Object.fromEntries(Object.entries(n).filter(([i])=>!nn.includes(i))):n,hr=/unique constraint failed/i,wr=n=>n instanceof Error&&hr.test(n.message),pr=/string or blob too big/iu,gr=(n,i)=>{if(!(!(n instanceof Error)||!pr.test(n.message)))throw new $("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.`)},ut=(n,i,o,c)=>{try{fe(n,o,...c)}catch(s){throw wr(s)?new se(`unique constraint violation on "${i}"`,"unique"):(gr(s,i),s)}},Ge=(n,i,o,c)=>{if(ut(n,i,o,c),fe(n,Qo).one().changed===0)throw new se(`optimistic concurrency conflict on "${i}" — the row changed during this mutation; refetch and retry`,"occ")},on=(n,i,o,c,s,w,_)=>{const S=[];for(let C=0;C<o.length+1;C+=1){const A=o[C],I=c[C],q=I?.direction==="desc"?"desc":"asc",F=A===void 0||I===void 0?a`${a.identifier(io)} < ${_}`:so(A,w[C],q,!1);if(F===void 0)continue;const L=[];for(let O=0;O<C;O+=1)L.push(a`${a.identifier(o[O])} IS ${w[O]}`);L.push(F);const[W]=L;S.push(L.length===1&&W!==void 0?W:a`(${a.join(L,a` AND `)})`)}const b=S.length>0?a.join(S,a` OR `):a`1 = 0`,y=G(n,a`SELECT COUNT(*) AS c FROM ${a.identifier(i)} WHERE ${a.identifier("__partition__")} = ${s} AND (${b})`).one(),k=G(n,a`SELECT COUNT(*) AS c FROM ${a.identifier(i)} WHERE ${a.identifier("__partition__")} = ${s}`).one();return{before:y.c,total:k.c}},yr=n=>{const i=new Map;for(const[c,s]of Object.entries(n.tables))for(const w of Object.values(s.relationMap??{}))w.kind==="one"&&(w.onDelete==="cascade"||w.onDelete==="set null")&&i.set(w.table,[...i.get(w.table)??[],{holder:c,op:w.onDelete==="cascade"?"delete":"update"}]);const o=c=>{const s=new Set,w=[c];for(let _=w.pop();_!==void 0;_=w.pop())for(const{holder:S,op:b}of i.get(_)??[]){if(S===c||jt(n,S,b))return!0;s.has(S)||(s.add(S),w.push(S))}return!1};return new Set(Object.entries(n.tables).filter(([c,s])=>s.shardMode?.kind==="global"||jt(n,c,"delete")||o(c)).map(([c])=>c))},$r=n=>{const i=new Map;for(const[o,c]of Object.entries(n.tables))c.softDeleteMode&&i.set(o,c.softDeleteMode.field);return i},oi=n=>{const{baselineSeq:i,onStalePatchDropped:o}=n,{sql:c}=n,{schema:s}=n,w=n.broadcast??(()=>{}),_=fo(s),S=go(s,n.inTransaction),b=yr(s),y=$r(s);let k;const C=()=>n.inTransaction?.()===!0,A=e=>s.tables[e]?.commitOrderedMode!==!0?{}:((k===void 0||!C())&&(k=qn(c)),{[Wn]:k}),I=(e,...t)=>{const r=s.tables[e]?.indexes;if(!r||r.length===0)return;const u=[];for(const h of t)h&&u.push(...co(r,h,Ie));return u.length>0?u:void 0},{headroom:q}=n;let F=!1;const L=async e=>{const t=F;F=!0;try{return await e()}finally{F=t}},W=n.onRead??(()=>{}),O=e=>{Mt(s.tables[e])&&W(Ut,Ut)},we=n.onReadRange??(e=>{W(e.table,U)}),ne=e=>{O(e.table),we(e)},p=(e,t)=>{t!==void 0&&t!==U&&!F&&q?.recordRead(1),O(e),W(e,t)},x=n.onIndexUse??(()=>{}),D=n.onWrite??(()=>{}),M=e=>{F||q?.recordWrite(e)},N=async e=>{M(e.doc),await D(e)},{cache:oe}=n,J=n.clock??(()=>Date.now()),pe=n.idGenerator??(()=>crypto.randomUUID()),xe=n.scheduler??In,{globalDb:ge}=n,ye=n.auth??{identity:null,userId:null},pt=n.cdc??!1,Je=xe,gn=So({scheduler:typeof Je.list=="function"&&typeof Je.get=="function"?Je:void 0,storage:n.storage}),$e=(e,t,r,u)=>{pt&&!Mt(s.tables[e])&&Fn(c,J(),e,t,r,u)},gt=(e,t,r,u)=>{const h=s.tables[e];if(h?.dropStalePatchesMode!==!0||!pt)return!1;const f=i?.();if(f===void 0)return!1;const d=Ln(c,e,t,f);if(d===void 0)return!1;const l=Yn(h,r);return Object.keys(He(r)).some(g=>!l.has(g)&&bt(Ft(d,g))!==bt(Ft(u,g)))},ie=e=>s.tables[e]?.shardMode?.kind==="global",yt=(e,t)=>{if(ie(e)){if(!ge)throw new $("INTERNAL",`cross-backend ${t} for global table '${e}' requires a globalDb writer — pass one to createShardCtxDb({ globalDb })`);return ge}return B},ze=e=>yt(e,"cascade"),j=(e,t)=>{if(ie(e)){if(!ge)throw new $("INTERNAL",`${t} on global table '${e}' requires a globalDb writer — pass one to createShardCtxDb({ globalDb })`);return ge}},$t=async(e,t,r,u,h)=>{h&&M(r);const f=await e.insert(t,r,u);return w({key:f,op:"insert",row:{...r,_id:f},table:t}),f},Ye=(e,t)=>yt(e,"relation load").findMany(e,t),Et=(e,t)=>(ie(e)&&p(e,U),Ye(e,t)),yn=e=>!ie(e.table),mt=n.relationExistsPushDown??"auto",St=mt!=="never",{maxRelationKeys:_t}=n,be=(e,t,r)=>wo(e,{fetcher:Et,maxRelationKeys:_t,relationBaseWhere:r,schema:s,tableName:t}),Rt=async(e,t,r,u)=>{const h=j(e,"relation grouped count");if(h)return p(e,U),$o((T,H)=>h.count(T,H),e,t,r,u);const f=s.tables[e];if(!f)throw new $("INTERNAL",`unknown table: ${e}`);p(e,U);const d=Te(f.softDeleteMode,void 0),l={[t]:{in:r}},g=K(K(l,u),d),v=await be(g,e,void 0),E=Y(v,le),R=ue(t);let m=a`SELECT ${R} AS __fk__, COUNT(*) AS count FROM ${a.identifier(e)}`;E&&(m=a`${m} WHERE ${E}`),m=a`${m} GROUP BY ${R}`;const P=G(c,m).toArray();return new Map(P.map(T=>[T.__fk__,T.count]))};let Me=0;const Tt=new Set;for(const[e,t]of Object.entries(s.tables))for(const r of Object.values(t.triggerMap??{}))Tt.add(`${e} ${r.timing} ${r.op}`);const X=(e,t,r)=>Tt.has(`${e} ${t} ${r}`),Z=async(e,t,r)=>{if(Me+=1,Me>Jt)throw Me-=1,new se(`trigger recursion exceeded ${String(Jt)} levels on "${r.table}" — check for a self-triggering write`,"trigger");try{await _o({ctx:_n,event:r,op:t,schema:s,tableName:r.table,timing:e})}finally{Me-=1}},{ensureBackfilledForTable:Ee,ensureBackfilledIndex:Xe,ensureRankBackfilled:Ze,ensureRankBackfilledForTable:me,syncAggregates:De,syncCompanionsForInsert:vt,syncGeo:ke,syncRanks:Se,syncSearch:Fe}=Bn({broadcast:w,indexKeysFor:(e,t)=>I(e,t),invalidateCache:(e,t,r)=>oe?.invalidate(e,t,I(e,r)),recordCdc:$e,schema:s,sql:c}),At=(e,t,r)=>{const{shardMode:u}=t;if(u?.kind==="shardBy"&&!(u.field!==void 0&&(r.partitionBy??[]).includes(u.field)))throw Object.assign(new Error(`rank index "${r.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})},It=e=>Object.entries(s.tables).filter(([,t])=>t.shardMode?.kind!=="global").map(([t])=>t).filter(t=>e===void 0||t===e),_e=e=>e===void 0||ie(e)?ge:void 0,ee=(e,t)=>{const r=It(t);for(let u=0;u<r.length;u+=Re){const h=r.slice(u,u+Re),[f]=fe(c,Jo(h),...zo(e,h)).toArray();if(!f)continue;const d=f.__t__,l=ve(f);if(typeof d!="string"||!l)return;const g=f[re];return{docJson:typeof g=="string"?g:ae(g??{}),row:l,tableName:d}}},$n=(e,t)=>{const r=[...new Set(e)],u=new Map;if(r.length===0)return u;const h=It(t);for(let f=0;f<h.length;f+=Re){const d=h.slice(f,f+Re),l=Math.floor(Re/d.length),g=Gn(a`${a.identifier("id")}`,r,!1,l),v=d.map(E=>a`SELECT ${a.raw(`'${E.replaceAll("'","''")}'`)} AS __t__, id FROM ${a.identifier(E)} WHERE ${g}`);for(const E of G(c,ht(v))){const{id:R,__t__:m}=E;typeof m=="string"&&typeof R=="string"&&u.set(R,m)}}return u},Ct={assertRankPartitionLocal:At,ensureRankBackfilled:Ze,onRead:p,rowToDocument:ve,schema:s,sql:c},En=(e,t,r)=>{const u=Y(r,le);return u===void 0||G(c,a`SELECT 1 FROM ${a.identifier(e)} WHERE ${a.identifier("id")} = ${t} AND ${u}`).toArray().length>0},mn=(e,t,r,u)=>gt(e,t,r,u)?(o?.({fields:Object.keys(He(r)),id:t,table:e}),!0):!1,Sn=async(e,t,r,u,h)=>{const f=ee(t,e);if(!f)return{applied:!1,doc:null};if(p(e,t),!En(e,t,r.where)||mn(e,t,r.patch,f.row))return{applied:!1,doc:f.row};try{await h(r.patch)}catch(d){if(d instanceof se&&d.kind==="occ"&&u)return;throw d}return{applied:!0,doc:ee(t,e)?.row??null}},xt=async(e,t,r,u)=>{const{fetchLimit:h,limit:f,orderKeys:d,predicate:l}=await po(t,r,{canPushExists:St?yn:void 0,existsPushMode:mt==="always"?"always":"auto",fetcher:Et,maxRelationKeys:_t,schema:s,tableName:e}),g=St?dr(u):Qe,v=Y(l,g,Ne),E=dn(e,v,ln(d),h);return{limit:f,orderKeys:d,statement:E}},B={system:gn,async aggregate(e,t){const r=j(e,"aggregate");if(r)return p(e,U),r.aggregate(e,t);const u=s.tables[e];if(!u)throw new $("INTERNAL",`unknown table: ${e}`);if(Be(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 $("INTERNAL",`aggregate(${e}, { op: "${t.op}" }): "field" is required for non-count reducers`);p(e,U);const h=Te(u.softDeleteMode,void 0),f=K(K(t.baseWhere,t.where),h),d=await be(f,e,t.relationBaseWhere),l=d!==f;if(u.aggregateIndexes&&!t.baseWhere&&!l){const T=Mn(u.aggregateIndexes,t.op,t.field,t.where);if(T){Xe(e,T.index);const H=tt(T.index.by??[],T.key),te=et(e,T.index.name),z=G(c,a`SELECT ${Pe} AS value, ${rt} AS count FROM ${a.identifier(te)} WHERE ${Ue} = ${H}`).toArray()[0];return nt(t.op,z)}}Yt(u,t.field,`aggregate(${e}, { op: "${t.op}", field: "${t.field}" })`);const g=Y(d,le),v=Be(t.op),E=ue(t.field);let R=a`SELECT ${a.raw(v)}(${E}) AS value FROM ${a.identifier(e)}`;g&&(R=a`${R} WHERE ${g}`);const P=G(c,R).toArray()[0]?.value;return P??null},asId(e,t){const r=Xt(s,e,t);if(r===null)throw new $("BAD_REQUEST",`asId("${e}", …): "${t}" is not a valid id for table "${e}"`,{status:400});return r},async count(e,t){const r=j(e,"count");if(r)return p(e,U),r.count(e,t);const u=s.tables[e];if(!u)throw new $("INTERNAL",`unknown table: ${e}`);const h=Cn(t);if(h.restrictsCounts)throw new ot(e);p(e,U);const f=Te(u.softDeleteMode,void 0),d=K(K(h.baseWhere,h.where),f),l=await be(d,e,h.relationBaseWhere),g=l!==d;if(u.aggregateIndexes&&!h.baseWhere&&!g){const m=bn(u.aggregateIndexes,h.where);if(m){Xe(e,m.index);const P=tt(m.index.by??[],m.key),T=et(e,m.index.name),H=G(c,a`SELECT ${Pe} AS value FROM ${a.identifier(T)} WHERE ${Ue} = ${P}`).toArray();return H[0]===void 0?0:H[0].value??0}}const v=Y(l,le);let E=a`SELECT COUNT(*) AS count FROM ${a.identifier(e)}`;return v&&(E=a`${E} WHERE ${v}`),G(c,E).one().count},async delete(e,t,r){const u=ee(e,t);if(!u){const R=_e(t);R&&(M(void 0),await R.delete(e,t,r));return}const{docJson:h,row:f,tableName:d}=u,l=s.tables[d],g=r?.hard===!0,v=!g&&l?.softDeleteMode?l:void 0,E=v?.softDeleteMode?.field;if(!(E&&f[E]!==null&&f[E]!==void 0)){if(X(d,"before","delete")&&await Z("before","delete",{id:e,op:"delete",previous:f,table:d}),await yo({deletedId:e,deletedReference:R=>f[R],findHolders:async(R,m,P)=>(await ze(R).findMany(R,{includeDeleted:g,where:{[m]:P}})).page,onCascade:(R,m)=>ze(R).delete(m,void 0,r),onRestrict:R=>{throw new se(R,"restrict")},onSetNull:(R,m,P)=>ze(R).patch(m,{[P]:null}),schema:s,tableName:d}),Ee(d),me(d),v&&E){const R={[E]:J()},m={...f,...A(d),...R,_id:e};at(v,R,m,ye),Ge(c,d,Qt(d),[ae(m),e,h]),Fe(d,e,m,f),ke(d,e,void 0),De(d,f,m),Se(d,e,f,void 0),oe?.invalidate(d,e,I(d,f,m)),$e(d,e,"update",m),w({indexKeys:I(d,f,m),key:e,op:"update",row:m,table:d}),X(d,"after","delete")&&await Z("after","delete",{id:e,op:"delete",previous:f,table:d}),await N({id:e,op:"delete",table:d});return}Ge(c,d,No(d),[e,h]),Fe(d,e,void 0),ke(d,e,void 0),De(d,f,void 0),Se(d,e,f,void 0),oe?.invalidate(d,e,I(d,f)),$e(d,e,"delete"),w({indexKeys:I(d,f),key:e,op:"delete",table:d}),X(d,"after","delete")&&await Z("after","delete",{id:e,op:"delete",previous:f,table:d}),await N({id:e,op:"delete",table:d})}},async deleteAll(e,t){if(!s.tables[e])throw new $("INTERNAL",`unknown table: ${e}`);const r=Math.max(1,t?.chunkSize??fn),u=t?.hard===void 0?void 0:{hard:t.hard},h=ie(e)?void 0:e;let f=0;return await L(async()=>{for(;;){const l=(await B.findMany(e,{limit:r})).page.map(g=>String(g._id));if(l.length===0)break;for(const g of l)await B.delete(g,h,u),f+=1;if(l.length<r)break}}),{deleted:f}},async deleteMany(e,t,r){de(e.length,t?.limit,"deleteMany");for(const u of e)await B.delete(u,r);return{deleted:e.length}},async deleteWhere(e,t,r){const f=(await(j(e,"deleteWhere")??B).findMany(e,{where:t})).page.map(d=>String(d._id));if(de(f.length,r?.limit,"deleteWhere"),B.deleteMany===void 0)throw new $("INTERNAL",`ctx.db.${e}.deleteMany is unavailable: this writer has no batch delete`);return B.deleteMany(f,r)},async findFirst(e,t={}){return(await B.findMany(e,{...t,limit:1,omitContinueCursor:!0})).page[0]??null},async findFirstOrThrow(e,t={}){const r=await B.findFirst(e,t);if(r===null)throw new Vn(`findFirstOrThrow: no "${e}" document matched`);return r},async findMany(e,t={}){const r=j(e,"findMany");if(r)return p(e,U),r.findMany(e,t);const u=s.tables[e];if(!u)throw new $("INTERNAL",`unknown table: ${e}`);const h=!t.where&&!t.baseWhere;h?p(e,U):p(e);const{limit:f,orderKeys:d,statement:l}=await xt(e,u,t,p),g=fe(c,l.text,...l.params).toArray();h&&!F&&q?.recordRead(g.length);const v=[];for(const P of g){const T=ve(P);T&&(v.push(T),!h&&typeof T._id=="string"&&p(e,T._id))}if(f===void 0)return t.with&&await Ht({groupedCounter:Rt,fetcher:Ye,parents:v,...Gt(t),schema:s,tableName:e,with:t.with}),{continueCursor:null,isDone:!0,page:Wt(v,t.select,t.with)};const E=v.length>f,R=E?v.slice(0,f):v,m=R.at(-1);return t.with&&await Ht({fetcher:Ye,groupedCounter:Rt,parents:R,...Gt(t),schema:s,tableName:e,with:t.with}),{continueCursor:E&&m&&t.omitContinueCursor!==!0?je(m,d):null,isDone:!E,page:Wt(R,t.select,t.with)}},async explain(e,t={}){const r=j(e,"explain");if(r)return r.explain(e,t);const u=s.tables[e];if(!u)throw new $("INTERNAL",`unknown table: ${e}`);const{statement:h}=await xt(e,u,t,()=>{}),f=fe(c,`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 r=ee(e,t);if(!r){const u=_e(t);return u?u.get(e,t):null}return p(r.tableName,e),r.row},async lookupById(e,t){const r=ee(e,t);return r?(p(r.tableName,e),{row:r.row,tableName:r.tableName}):null},async groupBy(e,t){const r=j(e,"groupBy");if(r)return p(e,U),r.groupBy(e,t);const u=s.tables[e];if(!u)throw new $("INTERNAL",`unknown table: ${e}`);p(e,U);const h=t.agg??{op:"count"};if(Be(h.op),h.op!=="count"&&!h.field)throw new $("INTERNAL",`groupBy(${e}, { agg: { op: "${h.op}" } }): "field" is required for non-count reducers`);const f=Te(u.softDeleteMode,void 0),d=K(K(t.baseWhere,t.where),f),l=await be(d,e,t.relationBaseWhere),g=l!==d;if(u.aggregateIndexes&&!t.baseWhere&&!g){const T=xn(u.aggregateIndexes,h.op,h.field,t.by,t.where),H=T===void 0?0:Object.keys(T.partial).length,te=T?.index.by?.length??0;if(T&&(H===0||H===te)){Xe(e,T.index);const z=et(e,T.index.name),Q=Object.keys(T.partial),ce=[];if(Q.length===(T.index.by??[]).length&&Q.length>0){const Le=tt(T.index.by??[],T.partial),qe=G(c,a`SELECT ${Pe} AS value, ${rt} AS count FROM ${a.identifier(z)} WHERE ${Ue} = ${Le}`).toArray();return qe.length>0&&ce.push({key:{...T.partial},value:nt(h.op,qe[0])}),ce}const Rn=G(c,a`SELECT ${Ue} AS key, ${Pe} AS value, ${rt} AS count FROM ${a.identifier(z)}`).toArray();for(const Le of Rn){const qe=An(JSON.parse(Le.key));ce.push({key:qe,value:nt(h.op,Le)})}return ce}}for(const T of[...t.by,h.field]){if(T===void 0)continue;const H=T===h.field?`groupBy(${e}, { agg: { op: "${h.op}", field: "${T}" } })`:`groupBy(${e}, { by: [..."${T}"] })`;Yt(u,T,H)}const v=Y(l,le),E=t.by.map(T=>a`${ue(T)} AS ${a.identifier(T)}`);if(h.op==="count")E.push(a`COUNT(*) AS value`);else{const{field:T}=h;if(T===void 0)throw new $("INTERNAL",`groupBy(${e}, { agg: { op: "${h.op}" } }): "field" is required for non-count reducers`);E.push(a`${a.raw(Be(h.op))}(${ue(T)}) AS value`)}let R=a`SELECT ${a.join(E,a`, `)} FROM ${a.identifier(e)}`;v&&(R=a`${R} WHERE ${v}`),R=a`${R} GROUP BY ${a.join(t.by.map(T=>ue(T)),a`, `)}`;const m=G(c,R).toArray(),P=[];for(const T of m){const H={};for(const z of t.by)H[z]=Un(u.shape[z],T[z]??null);const{value:te}=T;P.push({key:H,value:te==null?null:Number(te)})}return P},async insert(e,t,r){const u=j(e,"insert");if(u)return $t(u,e,t,r,!0);const h=s.tables[e];if(!h)throw new $("INTERNAL",`unknown table: ${e}`);const f=Zt(h,t,ye);st(h,f);let d;r?.clientId!==void 0?(Xo(r.clientId),d=r.clientId):r?.allowExplicitId&&typeof f._id=="string"?d=f._id:d=pe();const l=r?.allowExplicitId&&typeof f._creationTime=="number"?f._creationTime:J(),g={...f,...A(e),_creationTime:l,_id:d};return X(e,"before","insert")&&await Z("before","insert",{doc:{...g},id:d,op:"insert",table:e}),Ee(e),me(e),ut(c,e,jo(e),[d,l,ae(g)]),vt(e,d,g),X(e,"after","insert")&&await Z("after","insert",{doc:g,id:d,op:"insert",table:e}),await N({doc:g,id:d,op:"insert",table:e}),d},async insertManyUnsafe(e,t,r){if(de(t.length,r?.limit,"insertManyUnsafe"),t.length===0)return[];const u=j(e,"insert");if(u){const l=[];for(const g of t)M(g);for(const g of t){const v=await u.insert(e,g,{allowExplicitId:r?.allowExplicitId});w({key:v,op:"insert",row:{...g,_id:v},table:e}),l.push(v)}return l}const h=s.tables[e];if(!h)throw new $("INTERNAL",`unknown table: ${e}`);Ee(e),me(e);const f=[];for(let l=0;l<t.length;l+=Oe)f.push(A(e));const d=t.map((l,g)=>{const v=Zt(h,l,ye),E=r?.allowExplicitId===!0&&typeof v._id=="string"?v._id:pe(),R=r?.allowExplicitId===!0&&typeof v._creationTime=="number"?v._creationTime:J(),m={...v,...f[Math.floor(g/Oe)],_creationTime:R,_id:E};return{creationTime:R,document:m,id:E}});for(const l of d)M(l.document);for(let l=0;l<d.length;l+=Oe){const g=a.join(d.slice(l,l+Oe).map(E=>a`(${E.id}, ${E.creationTime}, ${ae(E.document)})`),a`, `),v=cn("sqlite",a`INSERT INTO ${a.identifier(e)} (id, _creationTime, ${a.identifier(re)}) VALUES ${g}`);ut(c,e,v.sql,v.params)}for(const{document:l,id:g}of d)vt(e,g,l),await D({doc:l,id:g,op:"insert",table:e});return d.map(l=>l.id)},async insertMany(e,t,r){de(t.length,r?.limit,"insertMany");const u=r?.skipDuplicates===!0,h=[],f=j(e,"insert");if(f)for(const l of t)M(l);const d=async l=>f?$t(f,e,l,void 0,!1):B.insert(e,l);for(const l of t)try{h.push(await d(l))}catch(g){if(u&&g instanceof se&&g.kind==="unique")h.push(null);else throw g}return h},normalizeId(e,t){return Xt(s,e,t)},async patch(e,t,r,u){const h=ee(e,r);if(!h){const R=_e(r);if(R){M(t),await R.patch(e,t,r,u);return}throw new $("NOT_FOUND",`document not found: ${e}`)}const{docJson:f,row:d,tableName:l}=h,g=s.tables[l];if(!g)throw new $("INTERNAL",`unknown table: ${l}`);if(p(l,e),tn("patch",t),gt(l,e,t,d)){o?.({fields:Object.keys(He(t)),id:e,table:l});return}const v=Jn(g,t,d),E={...d,...He(v),...A(l),_id:e};at(g,v,E,ye),zn(u,d,E),st(g,E,!0),X(l,"before","update")&&await Z("before","update",{doc:{...E},id:e,op:"update",previous:d,table:l}),Ee(l),me(l),Ge(c,l,Qt(l),[ae(E),e,f]),Fe(l,e,E,d),ke(l,e,E),De(l,d,E),Se(l,e,d,E),oe?.invalidate(l,e,I(l,d,E)),$e(l,e,"update",E),w({indexKeys:I(l,d,E),key:e,op:"update",row:E,table:l}),X(l,"after","update")&&await Z("after","update",{doc:E,id:e,op:"update",previous:d,table:l}),await N({doc:E,id:e,op:"update",table:l})},async patchIf(e,t,r){const u=j(e,"patchIf");if(u){if(u.patchIf===void 0)throw new $("INTERNAL",`ctx.db.patchIf on global table '${e}' is unsupported: its backend has no conditional write`);return M(r.patch),u.patchIf(e,t,r)}if(!s.tables[e])throw new $("INTERNAL",`unknown table: ${e}`);for(let h=1;h<=en;h+=1){const f=await Sn(e,t,r,h<en,d=>B.patch(t,d,e,{verify:r.verify}));if(f!==void 0)return f}throw new se(`patchIf on "${e}" kept conflicting; the row changed on every attempt`,"occ")},async patchMany(e,t,r){de(e.length,t?.limit,"patchMany");for(const u of e)await B.patch(u.id,u.patch,r);return{patched:e.length}},async patchWhere(e,t,r){const f=(await(j(e,"patchWhere")??B).findMany(e,{where:t.where})).page.map(d=>({id:String(d._id),patch:t.patch}));if(de(f.length,r?.limit,"patchWhere"),B.patchMany===void 0)throw new $("INTERNAL",`ctx.db.${e}.patchMany is unavailable: this writer has no batch patch`);return await B.patchMany(f,r),{patched:f.length}},async related(e,t){return ho(B,_,e,t)},relationEdges:_,deleteRereadTables:b,inTransaction:C,softDeleteFields:y,relationWrites:S,query(e){const t=j(e,"query");return t?(p(e,U),t.query(e)):pn(c,s,e,x,r=>{r?ne(r):p(e,U)},r=>{F||q?.recordRead(r)})},async rank(e,t,r){const u=j(e,"rank");if(u)return p(e,U),u.rank(e,t,r);x(e,t,"rank");const h=s.tables[e];if(!h)throw new $("INTERNAL",`unknown table: ${e}`);const f=h.rankIndexes?.find(Q=>Q.name===t);if(!f)throw new $("INTERNAL",`unknown rankIndex "${t}" on table "${e}"`);if(At(e,h,f),r.restrictsCounts)throw new ot(e);p(e,U),Ze(e,f);const d=typeof r.row=="string"?r.row:r.row._id;if(!d)return null;const l=Bt(e,f.name),g=f.sortBy.map((Q,ce)=>Pt(ce)),v=g.map(Q=>Ce(Q)).join(", "),E=G(c,a`SELECT ${a.identifier("__partition__")}, ${a.raw(v)} FROM ${a.identifier(l)} WHERE ${a.identifier("__id__")} = ${d}`).toArray(),[R]=E;if(R===void 0)return null;let m=R.__partition__;const P=K(r.baseWhere,r.where);it(P,s,e,"rank");const T=oo(f,P);if(T){const Q=ro(f.partitionBy??[],T);if(Q!==m)return null;m=Q}const H=g.map(Q=>R[Q]),{before:te,total:z}=on(c,l,g,f.sortBy,m,H,d);return{position:te+1,total:z}},async rankBefore(e,t,r){if(ie(e))throw new $("INTERNAL",`rankBefore is not supported on the global (.global()) table '${e}' — cross-shard rank cursors apply only to sharded tables`);const u=s.tables[e];if(!u)throw new $("INTERNAL",`unknown table: ${e}`);const h=u.rankIndexes?.find(g=>g.name===t);if(!h)throw new $("INTERNAL",`unknown rankIndex "${t}" on table "${e}"`);if(r.restrictsCounts)throw new ot(e);p(e,U),Ze(e,h);const f=Bt(e,h.name),d=h.sortBy.map((g,v)=>Pt(v)),l=h.sortBy.map((g,v)=>Ie(r.sortValues[v]??null));return on(c,f,d,h.sortBy,r.partitionKey,l,r.rowId)},async rankPage(e,t,r={}){it(K(r.baseWhere,r.where),s,e,"rankPage");const u=j(e,"rankPage");if(u)return p(e,U),u.rankPage(e,t,r);x(e,t,"rank");const{continueCursor:h,hasMore:f,rows:d}=Dt(Ct,e,t,r);return{continueCursor:h,isDone:!f,page:d.map(l=>l.doc)}},async rankPageRows(e,t,r={}){it(K(r.baseWhere,r.where),s,e,"rankPage"),x(e,t,"rank");const{directions:u,hasMore:h,rows:f}=Dt(Ct,e,t,r);return{directions:u,hasMore:h,rows:f}},async restore(e,t){const r=ee(e,t);if(!r){const f=_e(t);if(f?.restore){await f.restore(e,t);return}throw new $("NOT_FOUND",`document not found: ${e}`)}const u=s.tables[r.tableName]?.softDeleteMode?.field;if(!u)throw new $("INTERNAL",`ctx.db.restore: table "${r.tableName}" is not a .softDelete() table`);const h=r.row[u]!==null&&r.row[u]!==void 0;await B.patch(e,{[u]:null},t),h&&Se(r.tableName,e,void 0,r.row)},async replace(e,t,r,u){const h=ee(e,r);if(!h){const P=_e(r);if(P){M(t),await P.replace(e,t,r,u);return}throw new $("NOT_FOUND",`document not found: ${e}`)}const{docJson:f,row:d,tableName:l}=h,g=s.tables[l];if(!g)throw new $("INTERNAL",`unknown table: ${l}`);tn("replace",t);const v=u?.allowExplicitId&&typeof t._creationTime=="number"?t._creationTime:void 0,E=typeof d._creationTime=="number"?d._creationTime:void 0,R=v??E??J(),m={...t,...A(l),_creationTime:R,_id:e};at(g,t,m,ye),st(g,m),X(l,"before","update")&&await Z("before","update",{doc:{...m},id:e,op:"update",previous:d,table:l}),Ee(l),me(l),Ge(c,l,Ko(l),[R,ae(m),e,f]),Fe(l,e,m,d),ke(l,e,m),De(l,d,m),Se(l,e,d,m),oe?.invalidate(l,e,I(l,d,m)),$e(l,e,"update",m),w({indexKeys:I(l,d,m),key:e,op:"update",row:m,table:l}),X(l,"after","update")&&await Z("after","update",{doc:m,id:e,op:"update",previous:d,table:l}),await N({doc:m,id:e,op:"update",table:l})},async wipeShard(e){const t=new Set(e?.exclude),r=e?.tables,u=Object.entries(s.tables).filter(([l,g])=>t.has(l)||r!==void 0&&!r.includes(l)?!1:g.shardMode?.kind!=="global").map(([l])=>l);if(r!==void 0){for(const l of r)if(!s.tables[l])throw new $("INTERNAL",`wipeShard: unknown table: ${l}`)}const h={};let f=0;const{deleteAll:d}=B;if(d===void 0)throw new $("INTERNAL","wipeShard: this writer has no deleteAll");for(const l of u){const g=await d(l,{...e?.chunkSize===void 0?{}:{chunkSize:e.chunkSize},hard:!0});h[l]=g.deleted,f+=g.deleted}return{deleted:f,tables:h}}},_n={db:B,scheduler:xe};return n.enforceRls===!0?Eo(B,s,(e,t)=>ee(e,t)?.tableName,(e,t)=>$n(e,t),_):B};export{li as CDC_LOG_TABLE,Di as IDEMPOTENCY_TABLE,lr as NotUniqueError,Ci as advanceClientWatermark,ui as applyCdcChanges,tn as assertNoExplicitUndefined,Xo as assertValidClientId,si as backfillAggregateIndexes,ci as backfillRankIndexes,ai as backfillSearchIndexes,fi as bumpCdcEpoch,hi as cdcCanVouchFor,wi as cdcForkedError,pi as cdcSeqLeavingRows,gi as cdcTouchesTables,yi as cdcTrimmedError,$i as compactCdcDocs,oi as createShardCtxDb,Ei as cursorBelowRetainedFloor,xi as migrateClientWatermark,mi as minCdcReplayableSeq,Si as minCdcSeq,Xt as normalizeIdStructurally,_i as readCdcChangeKeys,Ri as readCdcChanges,Ti as readCdcCursor,vi as readCdcEpoch,bi as readClientWatermark,ki as readIdempotent,Wi as runShardMigrations,Pi as selectShapeMembers,Ui as selectShapeRows,He as stripReservedPatchFields,Ai as trimCdcChanges,Fi as trimIdempotent,Li as writeIdempotent};
@@ -0,0 +1 @@
1
+ import{LunoraError as R}from"@lunora/errors";import{findRelated as m}from"./RELATED_DEFAULT_LIMIT-CVqN4JEu.mjs";const M=Symbol.for("lunora.ctxdb.rls-unwrap");class S extends R{table;constructor(n){super("RLS_REQUIRED",`ctx.db access to "${n}" is denied: the schema is marked .rls("required"), so this table is protected. Apply RLS with .use(rls(policies)) in the procedure, or mark the table .public() to opt it out.`,{name:"RlsRequiredError"}),this.table=n}}const b=o=>Object.entries(o.tables).filter(([,n])=>n.shardMode?.kind!=="global").map(([n])=>n),E=(o,n,c)=>{const d=n?.tables,u=new Set(n?.exclude);for(const r of o)(d===void 0||d.includes(r))&&!u.has(r)&&c(r)},y={aggregate:"loop-gated",asId:"ungated",assertPatchAllowed:"id-gated",cdcChangedTables:"ungated",count:"loop-gated",delete:"id-gated",deleteAll:"loop-gated",deleteMany:"id-gated",deleteWhere:"inline-table-gated",explain:"loop-gated",findFirst:"loop-gated",findFirstOrThrow:"loop-gated",findMany:"loop-gated",get:"id-gated",groupBy:"loop-gated",insert:"loop-gated",insertMany:"loop-gated",insertManyUnsafe:"loop-gated",inTransaction:"ungated",lookupById:"id-gated",normalizeId:"ungated",patch:"id-gated",patchIf:"loop-gated",patchMany:"id-gated",patchWhere:"inline-table-gated",query:"loop-gated",rank:"loop-gated",rankBefore:"loop-gated",rankPage:"loop-gated",rankPageRows:"loop-gated",related:"rebound",relationEdges:"ungated",deleteRereadTables:"ungated",relationWrites:"ungated",softDeleteFields:"ungated",replace:"id-gated",restore:"id-gated",system:"ungated",wipeShard:"sweep-gated"},W=Object.entries(y).filter(([,o])=>o==="loop-gated").map(([o])=>o),I={related:(o,n)=>(...c)=>{const[d,u]=c;return m(o,n,d,u)}},O=Object.entries(y).filter(([,o])=>o==="rebound").map(([o])=>o),k=(o,n,c)=>{for(const d of O)typeof n[d]=="function"&&(o[d]=I[d](o,c))},P=(o,n,c,d,u=[])=>{if(n.rlsMode!=="required")return o;const r=o,p=e=>{const t=n.tables[e];return t!==void 0&&t.isPublic!==!0},i=e=>{if(p(e))throw new S(e)},l=async(e,t)=>{if(t!==void 0){i(t);return}const a=await c(e);a!==void 0&&i(a)},f=async(e,t)=>{if(t!==void 0){i(t);return}if(!d){for(const s of e)await l(s,t);return}const a=await d([...new Set(e)],t);for(const s of e){const h=a.get(s);h!==void 0&&i(h)}},g={...o,delete:async(e,t,a)=>(await l(e,t),r.delete(e,t,a)),deleteMany:async(e,t,a)=>(await f(e,a),r.deleteMany(e,t,a)),deleteWhere:r.deleteWhere?async(e,t,a)=>(i(e),await r.deleteWhere?.(e,t,a)):void 0,get:async(e,t)=>(await l(e,t),r.get(e,t)),lookupById:async(e,t)=>(await l(e,t),r.lookupById?.(e,t)??null),patch:async(e,t,a,s)=>(await l(e,a),r.patch(e,t,a,s)),patchMany:async(e,t,a)=>(await f(e.map(s=>s.id),a),r.patchMany(e,t,a)),assertPatchAllowed:async(e,t)=>(await l(e,t),r.assertPatchAllowed?.(e,t)),patchWhere:r.patchWhere?async(e,t,a)=>(i(e),await r.patchWhere?.(e,t,a)):void 0,replace:async(e,t,a,s)=>(await l(e,a),r.replace(e,t,a,s)),restore:async(e,t)=>(await l(e,t),r.restore?.(e,t))},w=r;for(const e of W){const t=w[e];typeof t=="function"&&(g[e]=(a,...s)=>(i(a),t.call(r,a,...s)))}if(k(g,r,u),r.wipeShard){const{wipeShard:e}=r;g.wipeShard=t=>(E(b(n),t,i),e.call(r,t))}return Object.defineProperty(g,M,{configurable:!0,enumerable:!1,value:o,writable:!1}),g};export{W as LOOP_GATED_METHODS,M as RLS_UNWRAP_SYMBOL,S as RlsRequiredError,y as WRITER_METHOD_GATING,P as guardWriter};
@@ -1 +1 @@
1
- import{createShardCtxDb as _}from"./NotUniqueError-CApXRyGS.mjs";import{createRelayLink as I}from"./DEFAULT_MAX_RELAYS-ZRhh4qpX.mjs";import{ConflictError as q}from"./ConflictError-C8GtJmjS.mjs";import{runShardMigrations as E}from"./runShardMigrations-BeqUbznb.mjs";import{relayName as F}from"./DEFAULT_PROMOTION_THRESHOLDS-B3pRMuqb.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};
1
+ import{createShardCtxDb as _}from"./NotUniqueError-CNXsYOSU.mjs";import{createRelayLink as I}from"./DEFAULT_MAX_RELAYS-ZRhh4qpX.mjs";import{ConflictError as q}from"./ConflictError-C8GtJmjS.mjs";import{runShardMigrations as E}from"./runShardMigrations-BeqUbznb.mjs";import{relayName as F}from"./DEFAULT_PROMOTION_THRESHOLDS-B3pRMuqb.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.130",
3
+ "version": "1.0.0-alpha.131",
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",
@@ -1 +0,0 @@
1
- import{LunoraError as y}from"@lunora/errors";import{D as ut}from"./MAX_TOKEN_LENGTH-BakL9FUy-B3VwYY8C.mjs";import{S as Rn,l as qe,h as Tn}from"./fts-companion-DzfEHonU.mjs";import{decodeWire as vn,stableWireKey as xt}from"@lunora/wire";import{sql as a}from"drizzle-orm";import{throwingScheduler as An,aggregateSqlFunction as We,normalizeCountArgument as In}from"./AGGREGATE_SQL_FUNCTION-C_ZipS9R.mjs";import{aggregateTableName as Ze,encodeAggregateKey as et,readAggregateValue as tt}from"./aggregateTableName-B_CtIQCS.mjs";import{mergeWhere as N,CountRlsUnsupportedError as nt,selectIndexForGroupBy as Cn,selectIndexForCount as xn,selectIndexForAggregate as bn}from"./CountRlsUnsupportedError-BvsDqfO2.mjs";import{backfillSearchIndexesForTable as Mn,searchIndexCoversTable as Dn}from"./backfillAggregateIndexes-Dw4Azd33.mjs";import{backfillAggregateIndexes as oi,backfillRankIndexes as ii,backfillSearchIndexes as si}from"./backfillAggregateIndexes-Dw4Azd33.mjs";import{appendCdcChange as kn,readCdcDocAtOrBefore as Ln}from"./CDC_LOG_TABLE-DsCz-DAV.mjs";import{CDC_LOG_TABLE as ai,applyCdcChanges as di,bumpCdcEpoch as li,cdcCanVouchFor as ui,cdcForkedError as fi,cdcSeqLeavingRows as hi,cdcTouchesTables as wi,cdcTrimmedError as pi,compactCdcDocs as gi,cursorBelowRetainedFloor as yi,minCdcReplayableSeq as $i,minCdcSeq as Ei,readCdcChangeKeys as mi,readCdcChanges as Si,readCdcCursor as _i,readCdcEpoch as Ri,trimCdcChanges as Ti}from"./CDC_LOG_TABLE-DsCz-DAV.mjs";import{allocateCommitSeq as Fn,COMMIT_SEQ_FIELD as qn}from"./COMMIT_SEQ_FIELD-BcUO15fR.mjs";import{createCompanionSync as Wn}from"./createCompanionSync-DhYLePyV.mjs";import{isMemoryTable as bt}from"./clearMemoryTables-Lu0S2GOb.mjs";import{computeRankPage as Mt}from"./computeRankPage-DLSi_oBt.mjs";import{SCAN_DEP as O}from"./SCAN_DEP-D7qE3iUe.mjs";import{runSql as he,runDrizzle as G}from"./runDrizzle-B2GG3IJa.mjs";import{p as Bn,j as at,D as re,r as ve,k as de,b as Be,A as rt,a as Pe,m as ue,e as fe,s as Pn,t as rn,i as Un,q as Dt,h as on,g as On}from"./do-sql-DqU-17Fs.mjs";import{renderSql as sn,unionAll as ft,WORKERD_SQLITE_LIMITS as cn,sqliteInList as Hn}from"./WORKERD_SQLITE_LIMITS-BdNnnMj0.mjs";import{coveringGeohashes as Gn,boundingBoxGeohashes as jn,haversineMeters as Kn,pointInBoundingBox as Nn}from"./GEO_DEFAULT_PRECISION-CqpQZ-J_.mjs";import{NotFoundError as Qn}from"./NotFoundError-BhF7FeFr.mjs";import{resolvePatch as Vn,assertPatchAllowed as Jn,operatorFields as zn,readPatchField as kt}from"./assertPatchAllowed-CA_H466g.mjs";import{tiebreakDirectionFor as Yn,encodeCursor as Ge,nullsOrderSuffix as Xn,normalizeOrderKeys as Lt,uniqueIndexFields as Zn,buildSeekWhere as er,decodeCursor as Ft,buildSeekBeforeWhere as tr,softDeleteScope as Te,applySelect as qt}from"./CURSOR_PREFIX-6offuG6M.mjs";import{rankTableName as Wt,sortColumnName as Bt,resolveRankPartition as nr,encodePartitionKey as rr,RANK_TIEBREAK as or,rankPivotConditionSql as ir}from"./RANK_TIEBREAK-D3ye2GsL.mjs";import{UNVOUCHABLE_DEP as Pt}from"./UNVOUCHABLE_DEP-C68htACn.mjs";import{indexKeysForRow as sr,buildIndexRange as cr}from"./buildIndexRange-DQ3eWAGd.mjs";import{r as je,j as Ae,c as Y,t as Ke,i as Ut}from"./where-sql-DO1vOrhc.mjs";import{serializeSqlValue as Ie}from"./serializeSqlValue-DeoBMpZ2.mjs";import{quoteIdentifier as Ce}from"./quoteIdentifier-CObIFRhb.mjs";import{whereOfFilter as ar,isPushableWhere as dr}from"./isPushableWhere-BeYAOjUb.mjs";import{deriveRelationEdges as lr,findRelated as ur}from"./RELATED_DEFAULT_LIMIT-CVqN4JEu.mjs";import{assertFlatPredicate as ot,resolveRelationPredicates as fr,composeReadPredicate as hr}from"./DEFAULT_MAX_RELATION_KEYS-BYfAkNAH.mjs";import{describeRelationWrites as wr}from"./describeRelationWrites-omar6-u9.mjs";import{runRowValidators as it,resolveWith as Ot,relationHooks as Ht,applyOnDelete as pr,fanOutScalarCounts as gr}from"./applyOnDelete-BwxDC4lU.mjs";import{guardWriter as yr}from"./RLS_UNWRAP_SYMBOL-DQt9luIF.mjs";import{mayHoldProjectedValue as $r}from"./BIGINT_KEY_DIGITS-DE6yshOt.mjs";import{createSystemReader as Er}from"./createSystemReader-DcDLFfC-.mjs";import{ConflictError as ce}from"./ConflictError-C8GtJmjS.mjs";import{hasTrigger as Gt,runTriggers as mr}from"./hasTrigger-CjlwI4le.mjs";import{advanceClientWatermark as Ai,migrateClientWatermark as Ii,readClientWatermark as Ci}from"./CLIENT_WATERMARK_TABLE-_CkdMnT2.mjs";import{IDEMPOTENCY_TABLE as bi,readIdempotent as Mi,trimIdempotent as Di,writeIdempotent as ki}from"./IDEMPOTENCY_TABLE-CymJf4r0.mjs";import{runShardMigrations as Fi}from"./runShardMigrations-BeqUbznb.mjs";import{selectShapeMembers as Wi,selectShapeRows as Bi}from"./selectShapeMembers-B1MIaRkE.mjs";const Sr=n=>{const s=atob(n),r=Uint8Array.from(s,c=>c.codePointAt(0)??0);return new TextDecoder().decode(r)},_r=()=>new y("BAD_REQUEST","invalid cursor"),jt=16,Kt=8,J=1024,ht=(n,s)=>s.query(n),Rr=(n,s)=>{if(n.length===0)return 0;let r=0;for(const[c,i]of s.entries()){const w=c===s.length-1;let _=0;for(const S of n)(w?S.startsWith(i):S===i)&&(_+=1);if(_===0)return 0;r+=_}return r},Tr=(n,s)=>{if(!s)return{exact:!0,lower:n,upper:n};const r=[...n].at(-1)??"",c=(r.codePointAt(0)??0)+1;if(c>=55296&&c<=57343||c>1114111)return{exact:!0,lower:n,upper:n};const i=n.slice(0,n.length-r.length);return{exact:!1,lower:n,upper:i+String.fromCodePoint(c)}},vr=(n,s,r)=>{const c={eq:(i,w)=>{if(!n.definition.filterFields?.includes(i))throw new y("INTERNAL",`field "${i}" is not a filter field of search index "${n.indexName}" on table "${s}"`);if(n.filters.length>=Kt)throw new y("BAD_REQUEST",`search index "${n.indexName}" on table "${s}": at most ${String(Kt)} .eq() filters are supported per search query`);return n.filters.push({field:i,value:w}),c},search:(i,w)=>{const _=n;if(i!==_.definition.field)throw new y("INTERNAL",`search index "${_.indexName}" on table "${s}" indexes "${_.definition.field}", not "${i}"`);const S=ht(w,r).length;if(S>jt)throw new y("BAD_REQUEST",`search index "${_.indexName}" on table "${s}": at most ${String(jt)} search terms are supported (got ${String(S)})`);return _.field=i,_.query=w,_.hasQuery=!0,c}};return c},Ar=n=>{if(n.length>J)throw new y("BAD_REQUEST",`more than ${String(J)} documents match this search — narrow it with filters or read it a page at a time with .paginate()`)},Ir=n=>Math.min(n.offset+n.numItems+1,J),Cr=n=>btoa(`search:${String(n)}`),xr=n=>{let s;try{s=Sr(n)}catch{return}if(!s.startsWith("search:"))return;const r=Number(s.slice(7));return Number.isInteger(r)&&r>=0?r:void 0},br=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 s=Math.max(0,Math.floor(n.numItems)),r=n.cursor?xr(n.cursor):0;if(r===void 0)throw _r();if(r+s>=J)throw new y("BAD_REQUEST",`search pagination reaches the ${String(J)}-document limit (offset ${String(r)} + ${String(s)} requested) — a page must end below the cap so the probe row that answers \`hasMore\` still fits: retry with numItems ${String(Math.max(1,J-r-1))} or fewer, or narrow the query or the filters instead`);return{numItems:s,offset:r}},Mr=(n,s)=>{const r=s.offset+s.numItems,c=s.numItems>0&&n.length>r;return{continueCursor:c?Cr(r):null,isDone:!c,page:n.slice(s.offset,r)}},Dr=n=>{if(n===void 0)return J+1;if(!Number.isFinite(n))return J;const s=Math.max(0,Math.floor(n));if(s>J)throw new y("BAD_REQUEST",`search returns at most ${String(J)} documents (asked for ${String(s)}) — narrow the query or paginate instead`);return s},kr=32,Lr=1024,an=(n,s,r,c)=>{const i=`SELECT id, _creationTime, ${Ce(re)} FROM ${Ce(n)}`,w=`ORDER BY ${r}${c===void 0?"":` LIMIT ${String(c)}`}`;return s===void 0?je(`${i} ${w}`):Ae(`${i} WHERE `,s,` ${w}`)},Ne={fieldRef:n=>je(at(n)),rangeTypeGuard:(n,s)=>je(Bn(n,s)),serialize:Ie},Fr=n=>n===void 0?"":Xn(n==="first"),dn=n=>{const s=n.map(r=>`${at(r.field)} ${r.direction==="desc"?"DESC":"ASC"}${Fr(r.nulls)}`);return n.some(r=>r.field==="_id"||r.field==="id")||s.push(`${at("id")} ${Yn(n)==="desc"?"DESC":"ASC"}`),s.join(", ")},qr={"<":"lt","<=":"lte","=":"eq",">":"gt",">=":"gte"},ln=n=>new Set(n.sqlConditions.filter(s=>s.comparator==="=").map(s=>s.field)),Wr=n=>{const s=ln(n);let r=0;for(;r<n.indexFields.length&&s.has(n.indexFields[r]??"");)r+=1;return n.indexFields.slice(r)},Br=(n,s)=>{const r=n.order,c=Wr(n),{shape:i}=s;return c.length>0?Lt(c.map(w=>({[w]:r})),i,{pinned:ln(n),uniqueBy:Zn(s.indexes,i)}):Lt([{_creationTime:r}],i)},Pr=(n,s,r,c)=>{const i=n.sqlConditions.map(w=>({[w.field]:{[qr[w.comparator]??"eq"]:w.value}}));if(r&&i.push(er(s,Ft(r))),c&&i.push(tr(s,Ft(c))),i.length!==0)return i.length===1?i[0]:{AND:i}},Ur=n=>{if(n.want!==void 0)return n.selective?Math.max(n.want,kr):n.want},dt=(n,s,r,c,i,w,_)=>{const S=Br(c,r),C=dn(S),g=[],{filters:q,want:I}=w;let R=w.cursor??void 0,M=Ur(w);if(I===0)return{documents:g,orderKeys:S};for(;;){const F=Y(Pr(c,S,R,w.endCursor),Ne,Ke),B=an(s,i&&F?Ae(F," AND ",i):i??F,C,M),L=he(n,B.text,...B.params).toArray();let W={};_(L.length);for(const j of L)if(W=ve(j),q.every(pe=>pe(W))&&g.push(W)===I)return{documents:g,orderKeys:S};if(M===void 0||L.length<M)return{documents:g,orderKeys:S};R=Ge(W,S),M=Math.max(M,Math.min(M*2,Lr))}},Or=(n,s,r,c,i,w,_,S)=>{const C=Math.max(0,Math.floor(i.numItems));if(typeof i.endCursor=="string"){const{documents:F,orderKeys:B}=dt(n,s,r,c,w,{cursor:i.cursor,endCursor:i.endCursor,filters:_.all,selective:_.selective,want:void 0},S),L=F.length>=2?F[Math.floor(F.length/2)-1]:void 0;return{continueCursor:i.endCursor,isDone:!0,page:F,splitCursor:L?Ge(L,B):null}}const{documents:g,orderKeys:q}=dt(n,s,r,c,w,{cursor:i.cursor,filters:_.all,selective:_.selective,want:C+1},S),I=g.length>C,R=I?g.slice(0,C):g,M=R.at(-1);return{continueCursor:I&&M?Ge(M,q):null,isDone:!I,page:R}},Qe=n=>{const s=new Map;return r=>{const c=s.get(r);if(c!==void 0)return c;const i=n(Ce(r));return s.set(r,i),i}},we=Ce(re),Hr=Qe(n=>`INSERT INTO ${n} (id, _creationTime, ${we}) VALUES (?, ?, ?)`),Nt=Qe(n=>`UPDATE ${n} SET ${we} = ? WHERE id = ? AND ${we} = ?`),Gr=Qe(n=>`UPDATE ${n} SET _creationTime = ?, ${we} = ? WHERE id = ? AND ${we} = ?`),jr=Qe(n=>`DELETE FROM ${n} WHERE id = ? AND ${we} = ?`),Kr="SELECT changes() AS changed",Qt=new Map,Nr="",Qr=n=>{const s=JSON.stringify(n),r=Qt.get(s);if(r!==void 0)return r;const c=n.map(w=>a`SELECT ${a.raw(`'${w.replaceAll("'","''")}'`)} AS __t__, id, _creationTime, ${a.identifier(re)} FROM ${a.identifier(w)} WHERE id = ${Nr}`),{sql:i}=sn("sqlite",a`${ft(c)} LIMIT 1`);return Qt.set(s,i),i},Vr=(n,s)=>s.map(()=>n),Jr=/^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/iu,zr=n=>{if(!Jr.test(n))throw new y("INTERNAL",`invalid clientId ${JSON.stringify(n)}: a client-supplied row id must be a UUID`)},Vt=50,un=500,Ue=Math.floor(cn.boundParams/3),Re=cn.boundParams,Yr=128,le=(n,s,r)=>{const c=s??un;if(n>c)throw new y("BATCH_LIMIT_EXCEEDED",`${r}: batch of ${String(n)} exceeds the limit of ${String(c)} (raise options.limit or chunk the call)`,{status:400})},Xr=n=>{const s={eq:(r,c)=>(n.sqlConditions.push({comparator:"=",field:r,value:c}),s),gt:(r,c)=>(n.sqlConditions.push({comparator:">",field:r,value:c}),s),gte:(r,c)=>(n.sqlConditions.push({comparator:">=",field:r,value:c}),s),lt:(r,c)=>(n.sqlConditions.push({comparator:"<",field:r,value:c}),s),lte:(r,c)=>(n.sqlConditions.push({comparator:"<=",field:r,value:c}),s)};return s},Zr=n=>Math.max(n,J),fn=(n,s)=>{const r=n.filters.map(c=>a`${fe(c.field)} = ${Ie(c.value)}`);return s&&r.push(s),r},eo=(n,s,r,c,i)=>{const w=ht(r.query,ut(r.definition.language));if(w.length===0)return[];const _=Rn(s,r.indexName),S=`${_}__vocab`,C=w.length-1,g=w.map((B,L)=>{const W=Tr(B,L===C),j=W.exact?a`${a.identifier("term")} = ${W.lower}`:a`${a.identifier("term")} >= ${W.lower} AND ${a.identifier("term")} < ${W.upper}`;return a`SELECT ${a.identifier("doc")}, ${a.raw(String(L))} AS ${a.identifier("__term__")}, COUNT(*) AS ${a.identifier("__n__")} FROM ${a.identifier(S)} WHERE ${j} GROUP BY ${a.identifier("doc")}`}),q=w.map((B,L)=>a`SUM(CASE WHEN u.${a.identifier("__term__")} = ${a.raw(String(L))} THEN u.${a.identifier("__n__")} ELSE 0 END)`),I=a`SELECT f.${a.identifier(qe)} AS ${a.identifier(qe)}, ${a.join(q,a` + `)} AS ${a.identifier("__score__")} FROM (${ft(g)}) u JOIN ${a.identifier(_)} f ON f.rowid = u.${a.identifier("doc")} GROUP BY f.${a.identifier(qe)} HAVING ${a.join(q.map(B=>a`${B} > 0`),a` AND `)}`,R=fn(r,i);let M=a`SELECT m.id, m._creationTime, m.${a.identifier(re)}, s.${a.identifier("__score__")} AS ${a.identifier("__score__")} FROM (${I}) s JOIN ${a.identifier(s)} m ON m.id = s.${a.identifier(qe)}`;R.length>0&&(M=a`${M} WHERE ${a.join(R,a` AND `)}`),M=a`${M} ORDER BY s.${a.identifier("__score__")} DESC, m._creationTime DESC, m.id ASC LIMIT ${a.raw(String(c))}`;const F=[];for(const B of G(n,M)){const L=on(B);if(L){const W=B.__score__;F.push({document:L,score:typeof W=="number"?W:Number(W??0)})}}return F},to=(n,s,r,c,i)=>{const w=ut(r.definition.language),_=ht(r.query,w);if(_.length===0)return[];const S=fn(r,i);let C=a`SELECT id, _creationTime, ${a.identifier(re)} FROM ${a.identifier(s)}`;S.length>0&&(C=a`${C} WHERE ${a.join(S,a` AND `)}`),C=a`${C} ORDER BY _creationTime DESC, id ASC LIMIT ${a.raw(String(Zr(c)))}`;const g=G(n,C).toArray(),q=[];for(const I of g){const R=on(I);if(!R)continue;const M=Rr(Tn(R,r.definition),_);M>0&&q.push({creationTime:typeof R._creationTime=="number"?R._creationTime:0,doc:R,id:typeof R._id=="string"?R._id:"",score:M})}return q.sort((I,R)=>R.score-I.score||R.creationTime-I.creationTime||I.id.localeCompare(R.id)),q.slice(0,c).map(I=>({document:I.doc,score:I.score}))},st=(n,s,r,c)=>{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 "${c}" on table "${r}": ${s} must have a finite lat in [-90, 90] and lng in [-180, 180]`)},no=(n,s)=>{const r=n,c={near:(i,w)=>{if(r.within)throw new y("INTERNAL",`geo index "${r.indexName}" on table "${s}": call .near() or .within(), not both`);if(st(i,".near() point",s,r.indexName),!Number.isFinite(w)||w<=0)throw new y("BAD_REQUEST",`geo index "${r.indexName}" on table "${s}": .near() radiusMeters must be a finite number > 0, got ${String(w)}`);return r.near={point:{lat:i.lat,lng:i.lng},radiusMeters:w},c},within:i=>{if(r.near)throw new y("INTERNAL",`geo index "${r.indexName}" on table "${s}": call .near() or .within(), not both`);if(st(i.sw,".within() sw corner",s,r.indexName),st(i.ne,".within() ne corner",s,r.indexName),i.sw.lat>i.ne.lat)throw new y("BAD_REQUEST",`geo index "${r.indexName}" on table "${s}": .within() corners are transposed (sw.lat > ne.lat)`);if(i.sw.lng>i.ne.lng)throw new y("BAD_REQUEST",`geo index "${r.indexName}" on table "${s}": .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:i.ne.lat,lng:i.ne.lng},sw:{lat:i.sw.lat,lng:i.sw.lng}},c}};return c},ro=(n,s)=>{const r=n[s];if(r===null||typeof r!="object")return;const{lat:c,lng:i}=r;return typeof c=="number"&&typeof i=="number"?{lat:c,lng:i}:void 0},oo=(n,s)=>{const r=ro(n,s.definition.field);if(!r)return;const c=typeof n._creationTime=="number"?n._creationTime:0;if(s.near){const i=Kn(s.near.point,r);return i<=s.near.radiusMeters?{creationTime:c,distance:i}:void 0}return Nn(r,s.within)?{creationTime:c,distance:0}:void 0},io=(n,s,r,c)=>{if(!r.near&&!r.within)throw new y("INTERNAL",`geo index "${r.indexName}" on table "${s}": call .near(point, radius) or .within(box)`);const i=r.near?Gn(r.near.point,r.near.radiusMeters):jn(r.within),w=On(s,r.indexName),_=i.map(I=>a`(g.${a.identifier("__geohash__")} >= ${I} AND g.${a.identifier("__geohash__")} < ${`${I}{`})`),S=[a`(${a.join(_,a` OR `)})`];c&&S.push(c);const C=a`SELECT m.id, m._creationTime, m.${a.identifier(re)} FROM ${a.identifier(w)} g JOIN ${a.identifier(s)} m ON m.id = g.${a.identifier("__id__")} WHERE ${a.join(S,a` AND `)}`,g=G(n,C).toArray(),q=[];for(const I of g){const R=ve(I),M=R?oo(R,r):void 0;R&&M&&q.push({creationTime:M.creationTime,distance:M.distance,doc:R})}return q.sort((I,R)=>I.distance-R.distance||R.creationTime-I.creationTime),q},hn=(n,s,r,c)=>{const i=[];for(const w of n)if(s.every(_=>_(c(w)))&&(i.push(w),typeof r=="number"&&i.length>=r))break;return i},so=(n,s,r,c,i,w=()=>{})=>{const _=r.within!==void 0,S=io(n,s,r,i).map(C=>({distanceMeters:_?null:C.distance,document:C.doc}));return w(S.length),typeof c=="number"?S.slice(0,Math.max(0,Math.floor(c))):S},Jt=(n,s,r,c,i,w,_=()=>{})=>{const{geo:S}=r;if(!S)throw new y("INTERNAL","runGeoTerminalScored called without a staged geo query");const C=i.length>0,g=so(n,s,S,C?void 0:w,c,_);return C?hn(g,i,w,q=>q.document):g},zt=(n,s,r)=>{const c=n.shape[s];if(c!==void 0&&$r(c))throw new y("BAD_REQUEST",`${r}: "${s}" 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)`)},co=n=>{let s=0;const r=[],c={...Ne,relationExists:i=>{const{childWhere:w,negated:_,parentTable:S,relation:C}=i,g=`__rel_${String(s)}`,q=r.at(-1)??S;s+=1,n(C.table,O);const I=C.kind==="one"?C.field:C.references,R=C.kind==="one"?C.references:C.field,M=je(`${Dt(g,R)} = ${Dt(q,I)}`);r.push(g);const F=Y(w,c,Ke);r.pop();const B=F===void 0?M:Ae(M," AND ",F),L=Ae("EXISTS (SELECT 1 FROM ",Ut(C.table)," AS ",Ut(g)," WHERE ",B,")");return _?Ae("NOT ",L):L}};return c};class ao extends y{constructor(s="unique() found more than one matching document"){super("NOT_UNIQUE",s,{name:"NotUniqueError"})}}const lo=/\s/u,uo=String.fromCodePoint(0),Yt=(n,s,r)=>{if(!n.tables[s])throw new y("INTERNAL",`unknown table: ${s}`);return typeof r!="string"||r.length===0||lo.test(r)||r.includes(uo)?null:r},wn=(n,s,r,c=()=>{},i=()=>{},w=()=>{},_)=>{const S=s.tables[r];if(!S)throw new y("INTERNAL",`unknown table: ${r}`);const C=Te(S.softDeleteMode,void 0),g=_??{indexFields:[],indexName:void 0,inMemoryFilters:[],order:"asc",sqlConditions:[],verifyFilters:[]},q=()=>{const $=N(C,g.pushedWhere);return $?Y($,ue):void 0},I=()=>{const $=N(C,g.pushedWhere);return $?Y($,Ne,Ke):void 0},R=()=>[...g.inMemoryFilters,...g.verifyFilters];let M=0;const F=$=>{const{search:x}=g;if(!x)throw new y("INTERNAL","runSearchFetch called without a staged search");Mn(n,r,S);const b=g.inMemoryFilters.length>0,k=Dr(b?void 0:$),Q=Un(n);if(Q&&!Dn(n,r,x.definition))throw new y("SEARCH_INDEX_BUILDING",`search index "${x.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 ne=q(),oe=Q?eo(n,r,x,k,ne):to(n,r,x,k,ne);!b&&$===void 0&&Ar(oe);const ge=R();return M=oe.length,ge.length>0?hn(oe,ge,$,ie=>ie.document):oe},B=$=>F($).map(x=>x.document),L=$=>{const x=br($);return Mr(B(Ir(x)),x)},W=()=>{if(g.search||g.geo||g.indexName===void 0){i(void 0);return}i(cr(r,g.indexName,g.indexFields,g.sqlConditions,Ie))},j=$=>{W();let x=0;const b=(()=>{if(g.search){const k=B($);return x=M,k}return g.geo?Jt(n,r,g,q(),R(),$,k=>{x=k}).map(k=>k.document):dt(n,r,S,g,I(),{filters:R(),selective:g.inMemoryFilters.length>0,want:$===void 0?void 0:Math.max(0,Math.floor($))},k=>{x+=k}).documents})();return w(Math.max(x,b.length)),b},pe=()=>{if(!g.search&&!g.geo)throw new y("INTERNAL",`ctx.db.query("${r}").collectWithScores() requires a staged .withSearchIndex(...) or .withGeoIndex(...)`);W();let $=0;const x=(()=>{if(g.search){const b=F(void 0);return $=M,b}return Jt(n,r,g,q(),R(),void 0,b=>{$=b})})();return w(Math.max($,x.length)),x},D={async*[Symbol.asyncIterator](){const $=wn(n,s,r,c,i,w,{...g,indexFields:[...g.indexFields],inMemoryFilters:[...g.inMemoryFilters],sqlConditions:[...g.sqlConditions],verifyFilters:[...g.verifyFilters]});if(g.search){yield*await $.collect();return}let x;for(;;){const b=await $.paginate({cursor:x??null,numItems:Yr});if(yield*b.page,b.isDone||b.continueCursor===null)return;x=b.continueCursor}},async collect(){return j(void 0)},async collectWithScores(){return pe()},filter($){const x=ar($);return x!==void 0&&dr(x,S.shape)?(g.pushedWhere=N(g.pushedWhere,x),g.verifyFilters.push($)):g.inMemoryFilters.push($),D},async first(){return j(1)[0]??null},order($){return g.order=$==="desc"?"desc":"asc",D},async paginate($){let x=0;if(W(),g.search){const k=L($);return w(k.page.length),k}if(g.geo)throw new y("INTERNAL","pagination is not supported on geo queries; use .take(n) or .collect()");const b=Or(n,r,S,g,$,I(),{all:R(),selective:g.inMemoryFilters.length>0},k=>{x+=k});return w(Math.max(x,b.page.length)),b},async take($){return j($)},async unique(){const $=j(2);if($.length>1)throw new ao(`unique() on table "${r}" matched ${String($.length)} documents; expected at most one`);return $[0]??null},withGeoIndex($,x){const b=(S.geoIndexes??[]).find(Q=>Q.name===$);if(!b)throw new y("INTERNAL",`unknown geo index "${$}" on table "${r}"`);c(r,$,"geo");const k={definition:b,indexName:$};if(g.geo=k,x(no(k,r)),!k.near&&!k.within)throw new y("INTERNAL",`geo index "${$}" on table "${r}" requires a .near(point, radius) or .within(box) call`);return D},withIndex($,x){const b=S.indexes.find(k=>k.name===$);if(!b)throw new y("INTERNAL",`unknown index "${$}" on table "${r}"`);return c(r,$,"index"),g.indexName=$,g.indexFields=b.fields,x&&x(Xr(g)),D},withSearchIndex($,x){const b=(S.searchIndexes??[]).find(Q=>Q.name===$);if(!b)throw new y("INTERNAL",`unknown search index "${$}" on table "${r}"`);c(r,$,"search");const k={definition:b,field:b.field,filters:[],hasQuery:!1,indexName:$,query:""};if(g.search=k,x(vr(k,r,ut(b.language))),!k.hasQuery)throw new y("INTERNAL",`search index "${$}" on table "${r}" requires a .search(field, query) call`);return D}};return D},Xt=(n,s,r)=>{const c={...s};for(const[i,w]of rn(n)){if(w.serverDefault){c[i]=w.serverDefault({auth:r});continue}c[i]===void 0&&(w.defaultFn?c[i]=w.defaultFn():"defaultValue"in w&&(c[i]=w.defaultValue))}return c},ct=(n,s,r,c)=>{const i=r;for(const[w,_]of rn(n)){if(_.serverDefault){w in s&&(i[w]=_.serverDefault({auth:c}));continue}_.onUpdateFn&&!(w in s)&&(i[w]=_.onUpdateFn())}},Zt=5,en=(n,s)=>{for(const r of Object.keys(s))if(s[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.`)},tn=["_commitSeq","_creationTime","_id"],Oe=n=>tn.some(s=>s in n)?Object.fromEntries(Object.entries(n).filter(([s])=>!tn.includes(s))):n,fo=/unique constraint failed/i,ho=n=>n instanceof Error&&fo.test(n.message),wo=/string or blob too big/iu,po=(n,s)=>{if(!(!(n instanceof Error)||!wo.test(n.message)))throw new y("PAYLOAD_TOO_LARGE",`document is too large to store in "${s}": 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.`)},lt=(n,s,r,c)=>{try{he(n,r,...c)}catch(i){throw ho(i)?new ce(`unique constraint violation on "${s}"`,"unique"):(po(i,s),i)}},He=(n,s,r,c)=>{if(lt(n,s,r,c),he(n,Kr).one().changed===0)throw new ce(`optimistic concurrency conflict on "${s}" — the row changed during this mutation; refetch and retry`,"occ")},nn=(n,s,r,c,i,w,_)=>{const S=[];for(let I=0;I<r.length+1;I+=1){const R=r[I],M=c[I],F=M?.direction==="desc"?"desc":"asc",B=R===void 0||M===void 0?a`${a.identifier(or)} < ${_}`:ir(R,w[I],F,!1);if(B===void 0)continue;const L=[];for(let j=0;j<I;j+=1)L.push(a`${a.identifier(r[j])} IS ${w[j]}`);L.push(B);const[W]=L;S.push(L.length===1&&W!==void 0?W:a`(${a.join(L,a` AND `)})`)}const C=S.length>0?a.join(S,a` OR `):a`1 = 0`,g=G(n,a`SELECT COUNT(*) AS c FROM ${a.identifier(s)} WHERE ${a.identifier("__partition__")} = ${i} AND (${C})`).one(),q=G(n,a`SELECT COUNT(*) AS c FROM ${a.identifier(s)} WHERE ${a.identifier("__partition__")} = ${i}`).one();return{before:g.c,total:q.c}},go=n=>{const s=new Map;for(const[c,i]of Object.entries(n.tables))for(const w of Object.values(i.relationMap??{}))w.kind==="one"&&(w.onDelete==="cascade"||w.onDelete==="set null")&&s.set(w.table,[...s.get(w.table)??[],{holder:c,op:w.onDelete==="cascade"?"delete":"update"}]);const r=c=>{const i=new Set,w=[c];for(let _=w.pop();_!==void 0;_=w.pop())for(const{holder:S,op:C}of s.get(_)??[]){if(S===c||Gt(n,S,C))return!0;i.has(S)||(i.add(S),w.push(S))}return!1};return new Set(Object.entries(n.tables).filter(([c,i])=>i.shardMode?.kind==="global"||Gt(n,c,"delete")||r(c)).map(([c])=>c))},ti=n=>{const{baselineSeq:s,onStalePatchDropped:r}=n,{sql:c}=n,{schema:i}=n,w=n.broadcast??(()=>{}),_=lr(i),S=wr(i,n.inTransaction),C=go(i);let g;const q=()=>n.inTransaction?.()===!0,I=e=>i.tables[e]?.commitOrderedMode!==!0?{}:((g===void 0||!q())&&(g=Fn(c)),{[qn]:g}),R=(e,...t)=>{const o=i.tables[e]?.indexes;if(!o||o.length===0)return;const u=[];for(const h of t)h&&u.push(...sr(o,h,Ie));return u.length>0?u:void 0},{headroom:M}=n;let F=!1;const B=async e=>{const t=F;F=!0;try{return await e()}finally{F=t}},L=n.onRead??(()=>{}),W=e=>{bt(i.tables[e])&&L(Pt,Pt)},j=n.onReadRange??(e=>{L(e.table,O)}),pe=e=>{W(e.table),j(e)},D=(e,t)=>{t!==void 0&&t!==O&&!F&&M?.recordRead(1),W(e),L(e,t)},$=n.onIndexUse??(()=>{}),x=n.onWrite??(()=>{}),b=e=>{F||M?.recordWrite(e)},k=async e=>{b(e.doc),await x(e)},{cache:Q}=n,ne=n.clock??(()=>Date.now()),oe=n.idGenerator??(()=>crypto.randomUUID()),ge=n.scheduler??An,{globalDb:ie}=n,ye=n.auth??{identity:null,userId:null},wt=n.cdc??!1,Ve=ge,pn=Er({scheduler:typeof Ve.list=="function"&&typeof Ve.get=="function"?Ve:void 0,storage:n.storage}),$e=(e,t,o,u)=>{wt&&!bt(i.tables[e])&&kn(c,ne(),e,t,o,u)},pt=(e,t,o,u)=>{const h=i.tables[e];if(h?.dropStalePatchesMode!==!0||!wt)return!1;const f=s?.();if(f===void 0)return!1;const d=Ln(c,e,t,f);if(d===void 0)return!1;const l=zn(h,o);return Object.keys(Oe(o)).some(p=>!l.has(p)&&xt(kt(d,p))!==xt(kt(u,p)))},se=e=>i.tables[e]?.shardMode?.kind==="global",gt=(e,t)=>{if(se(e)){if(!ie)throw new y("INTERNAL",`cross-backend ${t} for global table '${e}' requires a globalDb writer — pass one to createShardCtxDb({ globalDb })`);return ie}return P},Je=e=>gt(e,"cascade"),K=(e,t)=>{if(se(e)){if(!ie)throw new y("INTERNAL",`${t} on global table '${e}' requires a globalDb writer — pass one to createShardCtxDb({ globalDb })`);return ie}},yt=async(e,t,o,u,h)=>{h&&b(o);const f=await e.insert(t,o,u);return w({key:f,op:"insert",row:{...o,_id:f},table:t}),f},ze=(e,t)=>gt(e,"relation load").findMany(e,t),$t=(e,t)=>(se(e)&&D(e,O),ze(e,t)),gn=e=>!se(e.table),Et=n.relationExistsPushDown??"auto",mt=Et!=="never",{maxRelationKeys:St}=n,xe=(e,t,o)=>fr(e,{fetcher:$t,maxRelationKeys:St,relationBaseWhere:o,schema:i,tableName:t}),_t=async(e,t,o,u)=>{const h=K(e,"relation grouped count");if(h)return D(e,O),gr((v,H)=>h.count(v,H),e,t,o,u);const f=i.tables[e];if(!f)throw new y("INTERNAL",`unknown table: ${e}`);D(e,O);const d=Te(f.softDeleteMode,void 0),l={[t]:{in:o}},p=N(N(l,u),d),A=await xe(p,e,void 0),E=Y(A,ue),T=fe(t);let m=a`SELECT ${T} AS __fk__, COUNT(*) AS count FROM ${a.identifier(e)}`;E&&(m=a`${m} WHERE ${E}`),m=a`${m} GROUP BY ${T}`;const U=G(c,m).toArray();return new Map(U.map(v=>[v.__fk__,v.count]))};let be=0;const Rt=new Set;for(const[e,t]of Object.entries(i.tables))for(const o of Object.values(t.triggerMap??{}))Rt.add(`${e} ${o.timing} ${o.op}`);const X=(e,t,o)=>Rt.has(`${e} ${t} ${o}`),Z=async(e,t,o)=>{if(be+=1,be>Vt)throw be-=1,new ce(`trigger recursion exceeded ${String(Vt)} levels on "${o.table}" — check for a self-triggering write`,"trigger");try{await mr({ctx:Sn,event:o,op:t,schema:i,tableName:o.table,timing:e})}finally{be-=1}},{ensureBackfilledForTable:Ee,ensureBackfilledIndex:Ye,ensureRankBackfilled:Xe,ensureRankBackfilledForTable:me,syncAggregates:Me,syncCompanionsForInsert:Tt,syncGeo:De,syncRanks:Se,syncSearch:ke}=Wn({broadcast:w,indexKeysFor:(e,t)=>R(e,t),invalidateCache:(e,t,o)=>Q?.invalidate(e,t,R(e,o)),recordCdc:$e,schema:i,sql:c}),vt=(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})},At=e=>Object.entries(i.tables).filter(([,t])=>t.shardMode?.kind!=="global").map(([t])=>t).filter(t=>e===void 0||t===e),_e=e=>e===void 0||se(e)?ie:void 0,ee=(e,t)=>{const o=At(t);for(let u=0;u<o.length;u+=Re){const h=o.slice(u,u+Re),[f]=he(c,Qr(h),...Vr(e,h)).toArray();if(!f)continue;const d=f.__t__,l=ve(f);if(typeof d!="string"||!l)return;const p=f[re];return{docJson:typeof p=="string"?p:de(p??{}),row:l,tableName:d}}},yn=(e,t)=>{const o=[...new Set(e)],u=new Map;if(o.length===0)return u;const h=At(t);for(let f=0;f<h.length;f+=Re){const d=h.slice(f,f+Re),l=Math.floor(Re/d.length),p=Hn(a`${a.identifier("id")}`,o,!1,l),A=d.map(E=>a`SELECT ${a.raw(`'${E.replaceAll("'","''")}'`)} AS __t__, id FROM ${a.identifier(E)} WHERE ${p}`);for(const E of G(c,ft(A))){const{id:T,__t__:m}=E;typeof m=="string"&&typeof T=="string"&&u.set(T,m)}}return u},It={assertRankPartitionLocal:vt,ensureRankBackfilled:Xe,onRead:D,rowToDocument:ve,schema:i,sql:c},$n=(e,t,o)=>{const u=Y(o,ue);return u===void 0||G(c,a`SELECT 1 FROM ${a.identifier(e)} WHERE ${a.identifier("id")} = ${t} AND ${u}`).toArray().length>0},En=(e,t,o,u)=>pt(e,t,o,u)?(r?.({fields:Object.keys(Oe(o)),id:t,table:e}),!0):!1,mn=async(e,t,o,u,h)=>{const f=ee(t,e);if(!f)return{applied:!1,doc:null};if(D(e,t),!$n(e,t,o.where)||En(e,t,o.patch,f.row))return{applied:!1,doc:f.row};try{await h(o.patch)}catch(d){if(d instanceof ce&&d.kind==="occ"&&u)return;throw d}return{applied:!0,doc:ee(t,e)?.row??null}},Ct=async(e,t,o,u)=>{const{fetchLimit:h,limit:f,orderKeys:d,predicate:l}=await hr(t,o,{canPushExists:mt?gn:void 0,existsPushMode:Et==="always"?"always":"auto",fetcher:$t,maxRelationKeys:St,schema:i,tableName:e}),p=mt?co(u):Ne,A=Y(l,p,Ke),E=an(e,A,dn(d),h);return{limit:f,orderKeys:d,statement:E}},P={system:pn,async aggregate(e,t){const o=K(e,"aggregate");if(o)return D(e,O),o.aggregate(e,t);const u=i.tables[e];if(!u)throw new y("INTERNAL",`unknown table: ${e}`);if(We(t.op),t.op==="count")return P.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`);D(e,O);const h=Te(u.softDeleteMode,void 0),f=N(N(t.baseWhere,t.where),h),d=await xe(f,e,t.relationBaseWhere),l=d!==f;if(u.aggregateIndexes&&!t.baseWhere&&!l){const v=bn(u.aggregateIndexes,t.op,t.field,t.where);if(v){Ye(e,v.index);const H=et(v.index.by??[],v.key),te=Ze(e,v.index.name),z=G(c,a`SELECT ${Be} AS value, ${rt} AS count FROM ${a.identifier(te)} WHERE ${Pe} = ${H}`).toArray()[0];return tt(t.op,z)}}zt(u,t.field,`aggregate(${e}, { op: "${t.op}", field: "${t.field}" })`);const p=Y(d,ue),A=We(t.op),E=fe(t.field);let T=a`SELECT ${a.raw(A)}(${E}) AS value FROM ${a.identifier(e)}`;p&&(T=a`${T} WHERE ${p}`);const U=G(c,T).toArray()[0]?.value;return U??null},asId(e,t){const o=Yt(i,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 D(e,O),o.count(e,t);const u=i.tables[e];if(!u)throw new y("INTERNAL",`unknown table: ${e}`);const h=In(t);if(h.restrictsCounts)throw new nt(e);D(e,O);const f=Te(u.softDeleteMode,void 0),d=N(N(h.baseWhere,h.where),f),l=await xe(d,e,h.relationBaseWhere),p=l!==d;if(u.aggregateIndexes&&!h.baseWhere&&!p){const m=xn(u.aggregateIndexes,h.where);if(m){Ye(e,m.index);const U=et(m.index.by??[],m.key),v=Ze(e,m.index.name),H=G(c,a`SELECT ${Be} AS value FROM ${a.identifier(v)} WHERE ${Pe} = ${U}`).toArray();return H[0]===void 0?0:H[0].value??0}}const A=Y(l,ue);let E=a`SELECT COUNT(*) AS count FROM ${a.identifier(e)}`;return A&&(E=a`${E} WHERE ${A}`),G(c,E).one().count},async delete(e,t,o){const u=ee(e,t);if(!u){const T=_e(t);T&&(b(void 0),await T.delete(e,t,o));return}const{docJson:h,row:f,tableName:d}=u,l=i.tables[d],p=o?.hard===!0,A=!p&&l?.softDeleteMode?l:void 0,E=A?.softDeleteMode?.field;if(!(E&&f[E]!==null&&f[E]!==void 0)){if(X(d,"before","delete")&&await Z("before","delete",{id:e,op:"delete",previous:f,table:d}),await pr({deletedId:e,deletedReference:T=>f[T],findHolders:async(T,m,U)=>(await Je(T).findMany(T,{includeDeleted:p,where:{[m]:U}})).page,onCascade:(T,m)=>Je(T).delete(m,void 0,o),onRestrict:T=>{throw new ce(T,"restrict")},onSetNull:(T,m,U)=>Je(T).patch(m,{[U]:null}),schema:i,tableName:d}),Ee(d),me(d),A&&E){const T={[E]:ne()},m={...f,...I(d),...T,_id:e};ct(A,T,m,ye),He(c,d,Nt(d),[de(m),e,h]),ke(d,e,m,f),De(d,e,void 0),Me(d,f,m),Se(d,e,f,void 0),Q?.invalidate(d,e,R(d,f,m)),$e(d,e,"update",m),w({indexKeys:R(d,f,m),key:e,op:"update",row:m,table:d}),X(d,"after","delete")&&await Z("after","delete",{id:e,op:"delete",previous:f,table:d}),await k({id:e,op:"delete",table:d});return}He(c,d,jr(d),[e,h]),ke(d,e,void 0),De(d,e,void 0),Me(d,f,void 0),Se(d,e,f,void 0),Q?.invalidate(d,e,R(d,f)),$e(d,e,"delete"),w({indexKeys:R(d,f),key:e,op:"delete",table:d}),X(d,"after","delete")&&await Z("after","delete",{id:e,op:"delete",previous:f,table:d}),await k({id:e,op:"delete",table:d})}},async deleteAll(e,t){if(!i.tables[e])throw new y("INTERNAL",`unknown table: ${e}`);const o=Math.max(1,t?.chunkSize??un),u=t?.hard===void 0?void 0:{hard:t.hard},h=se(e)?void 0:e;let f=0;return await B(async()=>{for(;;){const l=(await P.findMany(e,{limit:o})).page.map(p=>String(p._id));if(l.length===0)break;for(const p of l)await P.delete(p,h,u),f+=1;if(l.length<o)break}}),{deleted:f}},async deleteMany(e,t,o){le(e.length,t?.limit,"deleteMany");for(const u of e)await P.delete(u,o);return{deleted:e.length}},async deleteWhere(e,t,o){const f=(await(K(e,"deleteWhere")??P).findMany(e,{where:t})).page.map(d=>String(d._id));if(le(f.length,o?.limit,"deleteWhere"),P.deleteMany===void 0)throw new y("INTERNAL",`ctx.db.${e}.deleteMany is unavailable: this writer has no batch delete`);return P.deleteMany(f,o)},async findFirst(e,t={}){return(await P.findMany(e,{...t,limit:1,omitContinueCursor:!0})).page[0]??null},async findFirstOrThrow(e,t={}){const o=await P.findFirst(e,t);if(o===null)throw new Qn(`findFirstOrThrow: no "${e}" document matched`);return o},async findMany(e,t={}){const o=K(e,"findMany");if(o)return D(e,O),o.findMany(e,t);const u=i.tables[e];if(!u)throw new y("INTERNAL",`unknown table: ${e}`);const h=!t.where&&!t.baseWhere;h?D(e,O):D(e);const{limit:f,orderKeys:d,statement:l}=await Ct(e,u,t,D),p=he(c,l.text,...l.params).toArray();h&&!F&&M?.recordRead(p.length);const A=[];for(const U of p){const v=ve(U);v&&(A.push(v),!h&&typeof v._id=="string"&&D(e,v._id))}if(f===void 0)return t.with&&await Ot({groupedCounter:_t,fetcher:ze,parents:A,...Ht(t),schema:i,tableName:e,with:t.with}),{continueCursor:null,isDone:!0,page:qt(A,t.select,t.with)};const E=A.length>f,T=E?A.slice(0,f):A,m=T.at(-1);return t.with&&await Ot({fetcher:ze,groupedCounter:_t,parents:T,...Ht(t),schema:i,tableName:e,with:t.with}),{continueCursor:E&&m&&t.omitContinueCursor!==!0?Ge(m,d):null,isDone:!E,page:qt(T,t.select,t.with)}},async explain(e,t={}){const o=K(e,"explain");if(o)return o.explain(e,t);const u=i.tables[e];if(!u)throw new y("INTERNAL",`unknown table: ${e}`);const{statement:h}=await Ct(e,u,t,()=>{}),f=he(c,`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=ee(e,t);if(!o){const u=_e(t);return u?u.get(e,t):null}return D(o.tableName,e),o.row},async lookupById(e,t){const o=ee(e,t);return o?(D(o.tableName,e),{row:o.row,tableName:o.tableName}):null},async groupBy(e,t){const o=K(e,"groupBy");if(o)return D(e,O),o.groupBy(e,t);const u=i.tables[e];if(!u)throw new y("INTERNAL",`unknown table: ${e}`);D(e,O);const h=t.agg??{op:"count"};if(We(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=Te(u.softDeleteMode,void 0),d=N(N(t.baseWhere,t.where),f),l=await xe(d,e,t.relationBaseWhere),p=l!==d;if(u.aggregateIndexes&&!t.baseWhere&&!p){const v=Cn(u.aggregateIndexes,h.op,h.field,t.by,t.where),H=v===void 0?0:Object.keys(v.partial).length,te=v?.index.by?.length??0;if(v&&(H===0||H===te)){Ye(e,v.index);const z=Ze(e,v.index.name),V=Object.keys(v.partial),ae=[];if(V.length===(v.index.by??[]).length&&V.length>0){const Le=et(v.index.by??[],v.partial),Fe=G(c,a`SELECT ${Be} AS value, ${rt} AS count FROM ${a.identifier(z)} WHERE ${Pe} = ${Le}`).toArray();return Fe.length>0&&ae.push({key:{...v.partial},value:tt(h.op,Fe[0])}),ae}const _n=G(c,a`SELECT ${Pe} AS key, ${Be} AS value, ${rt} AS count FROM ${a.identifier(z)}`).toArray();for(const Le of _n){const Fe=vn(JSON.parse(Le.key));ae.push({key:Fe,value:tt(h.op,Le)})}return ae}}for(const v of[...t.by,h.field]){if(v===void 0)continue;const H=v===h.field?`groupBy(${e}, { agg: { op: "${h.op}", field: "${v}" } })`:`groupBy(${e}, { by: [..."${v}"] })`;zt(u,v,H)}const A=Y(l,ue),E=t.by.map(v=>a`${fe(v)} AS ${a.identifier(v)}`);if(h.op==="count")E.push(a`COUNT(*) AS value`);else{const{field:v}=h;if(v===void 0)throw new y("INTERNAL",`groupBy(${e}, { agg: { op: "${h.op}" } }): "field" is required for non-count reducers`);E.push(a`${a.raw(We(h.op))}(${fe(v)}) AS value`)}let T=a`SELECT ${a.join(E,a`, `)} FROM ${a.identifier(e)}`;A&&(T=a`${T} WHERE ${A}`),T=a`${T} GROUP BY ${a.join(t.by.map(v=>fe(v)),a`, `)}`;const m=G(c,T).toArray(),U=[];for(const v of m){const H={};for(const z of t.by)H[z]=Pn(u.shape[z],v[z]??null);const{value:te}=v;U.push({key:H,value:te==null?null:Number(te)})}return U},async insert(e,t,o){const u=K(e,"insert");if(u)return yt(u,e,t,o,!0);const h=i.tables[e];if(!h)throw new y("INTERNAL",`unknown table: ${e}`);const f=Xt(h,t,ye);it(h,f);let d;o?.clientId!==void 0?(zr(o.clientId),d=o.clientId):o?.allowExplicitId&&typeof f._id=="string"?d=f._id:d=oe();const l=o?.allowExplicitId&&typeof f._creationTime=="number"?f._creationTime:ne(),p={...f,...I(e),_creationTime:l,_id:d};return X(e,"before","insert")&&await Z("before","insert",{doc:{...p},id:d,op:"insert",table:e}),Ee(e),me(e),lt(c,e,Hr(e),[d,l,de(p)]),Tt(e,d,p),X(e,"after","insert")&&await Z("after","insert",{doc:p,id:d,op:"insert",table:e}),await k({doc:p,id:d,op:"insert",table:e}),d},async insertManyUnsafe(e,t,o){if(le(t.length,o?.limit,"insertManyUnsafe"),t.length===0)return[];const u=K(e,"insert");if(u){const l=[];for(const p of t)b(p);for(const p of t){const A=await u.insert(e,p,{allowExplicitId:o?.allowExplicitId});w({key:A,op:"insert",row:{...p,_id:A},table:e}),l.push(A)}return l}const h=i.tables[e];if(!h)throw new y("INTERNAL",`unknown table: ${e}`);Ee(e),me(e);const f=[];for(let l=0;l<t.length;l+=Ue)f.push(I(e));const d=t.map((l,p)=>{const A=Xt(h,l,ye),E=o?.allowExplicitId===!0&&typeof A._id=="string"?A._id:oe(),T=o?.allowExplicitId===!0&&typeof A._creationTime=="number"?A._creationTime:ne(),m={...A,...f[Math.floor(p/Ue)],_creationTime:T,_id:E};return{creationTime:T,document:m,id:E}});for(const l of d)b(l.document);for(let l=0;l<d.length;l+=Ue){const p=a.join(d.slice(l,l+Ue).map(E=>a`(${E.id}, ${E.creationTime}, ${de(E.document)})`),a`, `),A=sn("sqlite",a`INSERT INTO ${a.identifier(e)} (id, _creationTime, ${a.identifier(re)}) VALUES ${p}`);lt(c,e,A.sql,A.params)}for(const{document:l,id:p}of d)Tt(e,p,l),await x({doc:l,id:p,op:"insert",table:e});return d.map(l=>l.id)},async insertMany(e,t,o){le(t.length,o?.limit,"insertMany");const u=o?.skipDuplicates===!0,h=[],f=K(e,"insert");if(f)for(const l of t)b(l);const d=async l=>f?yt(f,e,l,void 0,!1):P.insert(e,l);for(const l of t)try{h.push(await d(l))}catch(p){if(u&&p instanceof ce&&p.kind==="unique")h.push(null);else throw p}return h},normalizeId(e,t){return Yt(i,e,t)},async patch(e,t,o,u){const h=ee(e,o);if(!h){const T=_e(o);if(T){b(t),await T.patch(e,t,o,u);return}throw new y("NOT_FOUND",`document not found: ${e}`)}const{docJson:f,row:d,tableName:l}=h,p=i.tables[l];if(!p)throw new y("INTERNAL",`unknown table: ${l}`);if(D(l,e),en("patch",t),pt(l,e,t,d)){r?.({fields:Object.keys(Oe(t)),id:e,table:l});return}const A=Vn(p,t,d),E={...d,...Oe(A),...I(l),_id:e};ct(p,A,E,ye),Jn(u,d,E),it(p,E,!0),X(l,"before","update")&&await Z("before","update",{doc:{...E},id:e,op:"update",previous:d,table:l}),Ee(l),me(l),He(c,l,Nt(l),[de(E),e,f]),ke(l,e,E,d),De(l,e,E),Me(l,d,E),Se(l,e,d,E),Q?.invalidate(l,e,R(l,d,E)),$e(l,e,"update",E),w({indexKeys:R(l,d,E),key:e,op:"update",row:E,table:l}),X(l,"after","update")&&await Z("after","update",{doc:E,id:e,op:"update",previous:d,table:l}),await k({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 b(o.patch),u.patchIf(e,t,o)}if(!i.tables[e])throw new y("INTERNAL",`unknown table: ${e}`);for(let h=1;h<=Zt;h+=1){const f=await mn(e,t,o,h<Zt,d=>P.patch(t,d,e,{verify:o.verify}));if(f!==void 0)return f}throw new ce(`patchIf on "${e}" kept conflicting; the row changed on every attempt`,"occ")},async patchMany(e,t,o){le(e.length,t?.limit,"patchMany");for(const u of e)await P.patch(u.id,u.patch,o);return{patched:e.length}},async patchWhere(e,t,o){const f=(await(K(e,"patchWhere")??P).findMany(e,{where:t.where})).page.map(d=>({id:String(d._id),patch:t.patch}));if(le(f.length,o?.limit,"patchWhere"),P.patchMany===void 0)throw new y("INTERNAL",`ctx.db.${e}.patchMany is unavailable: this writer has no batch patch`);return await P.patchMany(f,o),{patched:f.length}},async related(e,t){return ur(P,_,e,t)},relationEdges:_,deleteRereadTables:C,relationWrites:S,query(e){const t=K(e,"query");return t?(D(e,O),t.query(e)):wn(c,i,e,$,o=>{o?pe(o):D(e,O)},o=>{F||M?.recordRead(o)})},async rank(e,t,o){const u=K(e,"rank");if(u)return D(e,O),u.rank(e,t,o);$(e,t,"rank");const h=i.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(vt(e,h,f),o.restrictsCounts)throw new nt(e);D(e,O),Xe(e,f);const d=typeof o.row=="string"?o.row:o.row._id;if(!d)return null;const l=Wt(e,f.name),p=f.sortBy.map((V,ae)=>Bt(ae)),A=p.map(V=>Ce(V)).join(", "),E=G(c,a`SELECT ${a.identifier("__partition__")}, ${a.raw(A)} FROM ${a.identifier(l)} WHERE ${a.identifier("__id__")} = ${d}`).toArray(),[T]=E;if(T===void 0)return null;let m=T.__partition__;const U=N(o.baseWhere,o.where);ot(U,i,e,"rank");const v=nr(f,U);if(v){const V=rr(f.partitionBy??[],v);if(V!==m)return null;m=V}const H=p.map(V=>T[V]),{before:te,total:z}=nn(c,l,p,f.sortBy,m,H,d);return{position:te+1,total:z}},async rankBefore(e,t,o){if(se(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=i.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 nt(e);D(e,O),Xe(e,h);const f=Wt(e,h.name),d=h.sortBy.map((p,A)=>Bt(A)),l=h.sortBy.map((p,A)=>Ie(o.sortValues[A]??null));return nn(c,f,d,h.sortBy,o.partitionKey,l,o.rowId)},async rankPage(e,t,o={}){ot(N(o.baseWhere,o.where),i,e,"rankPage");const u=K(e,"rankPage");if(u)return D(e,O),u.rankPage(e,t,o);$(e,t,"rank");const{continueCursor:h,hasMore:f,rows:d}=Mt(It,e,t,o);return{continueCursor:h,isDone:!f,page:d.map(l=>l.doc)}},async rankPageRows(e,t,o={}){ot(N(o.baseWhere,o.where),i,e,"rankPage"),$(e,t,"rank");const{directions:u,hasMore:h,rows:f}=Mt(It,e,t,o);return{directions:u,hasMore:h,rows:f}},async restore(e,t){const o=ee(e,t);if(!o){const f=_e(t);if(f?.restore){await f.restore(e,t);return}throw new y("NOT_FOUND",`document not found: ${e}`)}const u=i.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 P.patch(e,{[u]:null},t),h&&Se(o.tableName,e,void 0,o.row)},async replace(e,t,o,u){const h=ee(e,o);if(!h){const U=_e(o);if(U){b(t),await U.replace(e,t,o,u);return}throw new y("NOT_FOUND",`document not found: ${e}`)}const{docJson:f,row:d,tableName:l}=h,p=i.tables[l];if(!p)throw new y("INTERNAL",`unknown table: ${l}`);en("replace",t);const A=u?.allowExplicitId&&typeof t._creationTime=="number"?t._creationTime:void 0,E=typeof d._creationTime=="number"?d._creationTime:void 0,T=A??E??ne(),m={...t,...I(l),_creationTime:T,_id:e};ct(p,t,m,ye),it(p,m),X(l,"before","update")&&await Z("before","update",{doc:{...m},id:e,op:"update",previous:d,table:l}),Ee(l),me(l),He(c,l,Gr(l),[T,de(m),e,f]),ke(l,e,m,d),De(l,e,m),Me(l,d,m),Se(l,e,d,m),Q?.invalidate(l,e,R(l,d,m)),$e(l,e,"update",m),w({indexKeys:R(l,d,m),key:e,op:"update",row:m,table:l}),X(l,"after","update")&&await Z("after","update",{doc:m,id:e,op:"update",previous:d,table:l}),await k({doc:m,id:e,op:"update",table:l})},async wipeShard(e){const t=new Set(e?.exclude),o=e?.tables,u=Object.entries(i.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(!i.tables[l])throw new y("INTERNAL",`wipeShard: unknown table: ${l}`)}const h={};let f=0;const{deleteAll:d}=P;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}}},Sn={db:P,scheduler:ge};return n.enforceRls===!0?yr(P,i,(e,t)=>ee(e,t)?.tableName,(e,t)=>yn(e,t),_):P};export{ai as CDC_LOG_TABLE,bi as IDEMPOTENCY_TABLE,ao as NotUniqueError,Ai as advanceClientWatermark,di as applyCdcChanges,en as assertNoExplicitUndefined,zr as assertValidClientId,oi as backfillAggregateIndexes,ii as backfillRankIndexes,si as backfillSearchIndexes,li as bumpCdcEpoch,ui as cdcCanVouchFor,fi as cdcForkedError,hi as cdcSeqLeavingRows,wi as cdcTouchesTables,pi as cdcTrimmedError,gi as compactCdcDocs,ti as createShardCtxDb,yi as cursorBelowRetainedFloor,Ii as migrateClientWatermark,$i as minCdcReplayableSeq,Ei as minCdcSeq,Yt as normalizeIdStructurally,mi as readCdcChangeKeys,Si as readCdcChanges,_i as readCdcCursor,Ri as readCdcEpoch,Ci as readClientWatermark,Mi as readIdempotent,Fi as runShardMigrations,Wi as selectShapeMembers,Bi as selectShapeRows,Oe as stripReservedPatchFields,Ti as trimCdcChanges,Di as trimIdempotent,ki as writeIdempotent};
@@ -1 +0,0 @@
1
- import{LunoraError as R}from"@lunora/errors";import{findRelated as m}from"./RELATED_DEFAULT_LIMIT-CVqN4JEu.mjs";const M=Symbol.for("lunora.ctxdb.rls-unwrap");class S extends R{table;constructor(n){super("RLS_REQUIRED",`ctx.db access to "${n}" is denied: the schema is marked .rls("required"), so this table is protected. Apply RLS with .use(rls(policies)) in the procedure, or mark the table .public() to opt it out.`,{name:"RlsRequiredError"}),this.table=n}}const b=o=>Object.entries(o.tables).filter(([,n])=>n.shardMode?.kind!=="global").map(([n])=>n),E=(o,n,c)=>{const d=n?.tables,u=new Set(n?.exclude);for(const r of o)(d===void 0||d.includes(r))&&!u.has(r)&&c(r)},y={aggregate:"loop-gated",asId:"ungated",assertPatchAllowed:"id-gated",cdcChangedTables:"ungated",count:"loop-gated",delete:"id-gated",deleteAll:"loop-gated",deleteMany:"id-gated",deleteWhere:"inline-table-gated",explain:"loop-gated",findFirst:"loop-gated",findFirstOrThrow:"loop-gated",findMany:"loop-gated",get:"id-gated",groupBy:"loop-gated",insert:"loop-gated",insertMany:"loop-gated",insertManyUnsafe:"loop-gated",lookupById:"id-gated",normalizeId:"ungated",patch:"id-gated",patchIf:"loop-gated",patchMany:"id-gated",patchWhere:"inline-table-gated",query:"loop-gated",rank:"loop-gated",rankBefore:"loop-gated",rankPage:"loop-gated",rankPageRows:"loop-gated",related:"rebound",relationEdges:"ungated",deleteRereadTables:"ungated",relationWrites:"ungated",replace:"id-gated",restore:"id-gated",system:"ungated",wipeShard:"sweep-gated"},W=Object.entries(y).filter(([,o])=>o==="loop-gated").map(([o])=>o),I={related:(o,n)=>(...c)=>{const[d,u]=c;return m(o,n,d,u)}},O=Object.entries(y).filter(([,o])=>o==="rebound").map(([o])=>o),k=(o,n,c)=>{for(const d of O)typeof n[d]=="function"&&(o[d]=I[d](o,c))},P=(o,n,c,d,u=[])=>{if(n.rlsMode!=="required")return o;const r=o,p=e=>{const t=n.tables[e];return t!==void 0&&t.isPublic!==!0},i=e=>{if(p(e))throw new S(e)},l=async(e,t)=>{if(t!==void 0){i(t);return}const a=await c(e);a!==void 0&&i(a)},f=async(e,t)=>{if(t!==void 0){i(t);return}if(!d){for(const s of e)await l(s,t);return}const a=await d([...new Set(e)],t);for(const s of e){const h=a.get(s);h!==void 0&&i(h)}},g={...o,delete:async(e,t,a)=>(await l(e,t),r.delete(e,t,a)),deleteMany:async(e,t,a)=>(await f(e,a),r.deleteMany(e,t,a)),deleteWhere:r.deleteWhere?async(e,t,a)=>(i(e),await r.deleteWhere?.(e,t,a)):void 0,get:async(e,t)=>(await l(e,t),r.get(e,t)),lookupById:async(e,t)=>(await l(e,t),r.lookupById?.(e,t)??null),patch:async(e,t,a,s)=>(await l(e,a),r.patch(e,t,a,s)),patchMany:async(e,t,a)=>(await f(e.map(s=>s.id),a),r.patchMany(e,t,a)),assertPatchAllowed:async(e,t)=>(await l(e,t),r.assertPatchAllowed?.(e,t)),patchWhere:r.patchWhere?async(e,t,a)=>(i(e),await r.patchWhere?.(e,t,a)):void 0,replace:async(e,t,a,s)=>(await l(e,a),r.replace(e,t,a,s)),restore:async(e,t)=>(await l(e,t),r.restore?.(e,t))},w=r;for(const e of W){const t=w[e];typeof t=="function"&&(g[e]=(a,...s)=>(i(a),t.call(r,a,...s)))}if(k(g,r,u),r.wipeShard){const{wipeShard:e}=r;g.wipeShard=t=>(E(b(n),t,i),e.call(r,t))}return Object.defineProperty(g,M,{configurable:!0,enumerable:!1,value:o,writable:!1}),g};export{W as LOOP_GATED_METHODS,M as RLS_UNWRAP_SYMBOL,S as RlsRequiredError,y as WRITER_METHOD_GATING,P as guardWriter};