@lunora/shard-engine 1.0.0-alpha.72 → 1.0.0-alpha.74

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-Celpamkj.mjs";export{t as defineEngineContractSuite};
1
+ import{defineEngineContractSuite as t}from"../packem_shared/defineEngineContractSuite-BS0T_g0Z.mjs";export{t as defineEngineContractSuite};
package/dist/index.d.mts CHANGED
@@ -256,6 +256,7 @@ interface SchemaLike {
256
256
  interface TableDefinitionLike {
257
257
  readonly aggregateIndexes?: ReadonlyArray<AggregateIndexDefinitionLike>;
258
258
  readonly commitOrderedMode?: boolean;
259
+ readonly dropStalePatchesMode?: boolean;
259
260
  readonly geoIndexes?: ReadonlyArray<GeoIndexDefinitionLike>;
260
261
  readonly indexes: ReadonlyArray<IndexDefinitionLike>;
261
262
  readonly isPublic?: boolean;
@@ -809,7 +810,9 @@ interface CdcChange {
809
810
  ts: number;
810
811
  }
811
812
  declare const CDC_LOG_TABLE_SEQ_INDEX = "__cdc_log_table_seq";
812
- declare const migrateCdcLog: (sql: SqlExec) => void;
813
+ declare const migrateCdcLog: (sql: SqlExec, options?: {
814
+ rowHistoryIndex?: boolean;
815
+ }) => void;
813
816
  declare const appendCdcChange: (sql: SqlExec, ts: number, table: string, id: string, op: CdcChange["op"], doc: Record<string, unknown> | undefined) => void;
814
817
  declare const readCdcChanges: (sql: SqlExec, options?: {
815
818
  limit?: number;
@@ -832,7 +835,7 @@ declare const cdcSeqLeavingRows: (sql: SqlExec, keep: number) => number | undefi
832
835
  declare const readCdcCursor: (sql: SqlExec) => number;
833
836
  declare const cursorBelowRetainedFloor: (floor: number | undefined, sinceSeq: number) => boolean;
834
837
  declare const cdcTrimmedError: (floor: number, sinceSeq: number, scope: "global" | "shard") => LunoraError;
835
- declare const cdcForkedError: (cursor: number, sinceSeq: number, epoch: string) => LunoraError;
838
+ declare const cdcForkedError: (cursor: number, sinceSeq: number, scope: "global" | "shard", epoch?: string) => LunoraError;
836
839
  declare const minCdcSeq: (sql: SqlExec) => number | undefined;
837
840
  declare const minCdcReplayableSeq: (sql: SqlExec) => number | undefined;
838
841
  declare const CDC_META_TABLE = "__cdc_meta";
@@ -912,6 +915,7 @@ interface WriteEvent {
912
915
  type WriteHook = (event: WriteEvent) => Promise<void> | void;
913
916
  interface CtxDbOptions {
914
917
  auth?: ServerDefaultContextLike["auth"];
918
+ baselineSeq?: () => number | undefined;
915
919
  broadcast?: BroadcastDelta;
916
920
  cache?: ReactiveCache;
917
921
  cdc?: boolean;
@@ -925,6 +929,11 @@ interface CtxDbOptions {
925
929
  onIndexUse?: IndexUseHook;
926
930
  onRead?: ReadHook;
927
931
  onReadRange?: (range: KeyRange) => void;
932
+ onStalePatchDropped?: (event: {
933
+ fields: string[];
934
+ id: string;
935
+ table: string;
936
+ }) => void;
928
937
  onWrite?: WriteHook;
929
938
  relationExistsPushDown?: "always" | "auto" | "never";
930
939
  scheduler?: SchedulerLike;
package/dist/index.d.ts CHANGED
@@ -256,6 +256,7 @@ interface SchemaLike {
256
256
  interface TableDefinitionLike {
257
257
  readonly aggregateIndexes?: ReadonlyArray<AggregateIndexDefinitionLike>;
258
258
  readonly commitOrderedMode?: boolean;
259
+ readonly dropStalePatchesMode?: boolean;
259
260
  readonly geoIndexes?: ReadonlyArray<GeoIndexDefinitionLike>;
260
261
  readonly indexes: ReadonlyArray<IndexDefinitionLike>;
261
262
  readonly isPublic?: boolean;
@@ -809,7 +810,9 @@ interface CdcChange {
809
810
  ts: number;
810
811
  }
811
812
  declare const CDC_LOG_TABLE_SEQ_INDEX = "__cdc_log_table_seq";
812
- declare const migrateCdcLog: (sql: SqlExec) => void;
813
+ declare const migrateCdcLog: (sql: SqlExec, options?: {
814
+ rowHistoryIndex?: boolean;
815
+ }) => void;
813
816
  declare const appendCdcChange: (sql: SqlExec, ts: number, table: string, id: string, op: CdcChange["op"], doc: Record<string, unknown> | undefined) => void;
814
817
  declare const readCdcChanges: (sql: SqlExec, options?: {
815
818
  limit?: number;
@@ -832,7 +835,7 @@ declare const cdcSeqLeavingRows: (sql: SqlExec, keep: number) => number | undefi
832
835
  declare const readCdcCursor: (sql: SqlExec) => number;
833
836
  declare const cursorBelowRetainedFloor: (floor: number | undefined, sinceSeq: number) => boolean;
834
837
  declare const cdcTrimmedError: (floor: number, sinceSeq: number, scope: "global" | "shard") => LunoraError;
835
- declare const cdcForkedError: (cursor: number, sinceSeq: number, epoch: string) => LunoraError;
838
+ declare const cdcForkedError: (cursor: number, sinceSeq: number, scope: "global" | "shard", epoch?: string) => LunoraError;
836
839
  declare const minCdcSeq: (sql: SqlExec) => number | undefined;
837
840
  declare const minCdcReplayableSeq: (sql: SqlExec) => number | undefined;
838
841
  declare const CDC_META_TABLE = "__cdc_meta";
@@ -912,6 +915,7 @@ interface WriteEvent {
912
915
  type WriteHook = (event: WriteEvent) => Promise<void> | void;
913
916
  interface CtxDbOptions {
914
917
  auth?: ServerDefaultContextLike["auth"];
918
+ baselineSeq?: () => number | undefined;
915
919
  broadcast?: BroadcastDelta;
916
920
  cache?: ReactiveCache;
917
921
  cdc?: boolean;
@@ -925,6 +929,11 @@ interface CtxDbOptions {
925
929
  onIndexUse?: IndexUseHook;
926
930
  onRead?: ReadHook;
927
931
  onReadRange?: (range: KeyRange) => void;
932
+ onStalePatchDropped?: (event: {
933
+ fields: string[];
934
+ id: string;
935
+ table: string;
936
+ }) => void;
928
937
  onWrite?: WriteHook;
929
938
  relationExistsPushDown?: "always" | "auto" | "never";
930
939
  scheduler?: SchedulerLike;
package/dist/index.mjs CHANGED
@@ -1 +1 @@
1
- import{exportShardRows as o,importShardRows as a,parseExportShardArgs as t,parseImportShardArgs as i,selectExportTables as l,validateImportRow as n}from"./packem_shared/exportShardRows-1TkeNJI6.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-DDEoMnJR.mjs";import{aggregateTableName as f,coerceAggregateNumber as E,encodeAggregateKey as h,foldAggregateTally as x,readAggregateValue as T}from"./packem_shared/aggregateTableName-C7o-gpms.mjs";import{CountRlsUnsupportedError as R,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 O,ensureAuditTable as P,readAuditLog as M}from"./packem_shared/AUDIT_LOG_TABLE-ONxmEAIz.mjs";import{NotUniqueError as F,assertNoExplicitUndefined as k,assertValidClientId as N,createShardCtxDb as B,normalizeIdStructurally as U,stripReservedPatchFields as G}from"./packem_shared/NotUniqueError-DpTK0ULs.mjs";import{backfillAggregateIndexes as v,backfillRankIndexes as w,backfillSearchIndexes as K,backfillSearchIndexesForTable as X}from"./packem_shared/backfillAggregateIndexes-DTemznr7.mjs";import{CDC_LOG_TABLE as W,CDC_LOG_TABLE_SEQ_INDEX as z,CDC_META_TABLE as V,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 ie,minCdcReplayableSeq as le,minCdcSeq as ne,readCdcChangeKeys as se,readCdcChanges as de,readCdcCursor as ce,readCdcEpoch as me,trimCdcChanges as pe}from"./packem_shared/CDC_LOG_TABLE-CfILante.mjs";import{archiveCdcSegment as ue,cdcArchiveRewound as fe,readArchivedCdcChanges as Ee,readCdcArchivedThrough as he,writeCdcArchivedThrough as xe}from"./packem_shared/archiveCdcSegment-E_R_b5Qz.mjs";import{CLIENT_WATERMARK_TABLE as Ce,advanceClientWatermark as Re,migrateClientWatermark as Ae,readClientWatermark as ge}from"./packem_shared/CLIENT_WATERMARK_TABLE-CRnrAnJ2.mjs";import{COMMIT_SEQ_FIELD as Ie,COMMIT_SEQ_TABLE as be,allocateCommitSeq as Le,migrateCommitSeq as De,readCommitSeq as Oe}from"./packem_shared/COMMIT_SEQ_FIELD-BUdOMG5y.mjs";import{c as Me}from"./packem_shared/ctx-db-companions-DsNfXSbb.mjs";import{GLOBAL_SHAPE_SNAPSHOT_TABLE as Fe,deleteGlobalShapeSnapshot as ke,deleteGlobalShapeSnapshotsForConnection as Ne,migrateGlobalShapeSnapshot as Be,readGlobalShapeSnapshot as Ue,writeGlobalShapeSnapshot as Ge}from"./packem_shared/GLOBAL_SHAPE_SNAPSHOT_TABLE-DSA6mzyx.mjs";import{IDEMPOTENCY_TABLE as ve,migrateIdempotency as we,readIdempotent as Ke,trimIdempotent as Xe,writeIdempotent as He}from"./packem_shared/IDEMPOTENCY_TABLE-DOpm_oMF.mjs";import{clearMemoryTables as ze,isMemoryTable as Ve,memoryTableNames as Qe}from"./packem_shared/clearMemoryTables-BGbmag2i.mjs";import{computeRankPage as je,resolveRankSeekTuple as Je}from"./packem_shared/computeRankPage-pTaG_r9F.mjs";import{SCHEDULE_OUTBOX_TABLE as $e,deferScheduleOutbox as er,forgetScheduleOutbox as rr,migrateScheduleOutbox as or,parkScheduleOutbox as ar,probeScheduleOutbox as tr,readDueScheduleOutbox as ir,recordScheduleOutbox as lr,trimScheduleOutbox as nr}from"./packem_shared/SCHEDULE_OUTBOX_TABLE-CD_UjYVx.mjs";import{S as dr,m as cr,r as mr,w as pr}from"./packem_shared/ctx-db-search-state-ruTuCsxa.mjs";import{SHAPE_POKE_CURSOR_TABLE as ur,deleteShapePokeCursor as fr,deleteShapePokeCursorsForConnection as Er,migrateShapePokeCursor as hr,minShapePokeCursor as xr,readShapePokeCursor as Tr,writeShapePokeCursor as Cr,writeShapePokeCursors as Rr}from"./packem_shared/SHAPE_POKE_CURSOR_TABLE-ByJVDHds.mjs";import{selectShapeMembers as gr,selectShapeRows as _r}from"./packem_shared/selectShapeMembers-B8gTOeOB.mjs";import{DATA_MIGRATION_STATE_TABLE as br,readMigrationStatus as Lr,runDataMigration as Dr}from"./packem_shared/DATA_MIGRATION_STATE_TABLE-BwFz6NTT.mjs";import{SCAN_DEP as Pr,createDependencyTracker as Mr,depKey as yr,tableFromDepKey as Fr}from"./packem_shared/SCAN_DEP-D7qE3iUe.mjs";import{runDrizzle as Nr,runSql as Br}from"./packem_shared/runDrizzle-2ULFQR_k.mjs";import{A as Gr,a as qr,b as vr,D as wr,c as Kr,d as Xr,g as Hr,i as Wr,j as zr,e as Vr,q as Qr,f as Yr,r as jr,t as Jr,h as Zr}from"./packem_shared/do-sql-kpl5Kt1j.mjs";import{param as eo,renderSql as ro,sqliteInList as oo,unionAll as ao}from"./packem_shared/param-DlozcSQu.mjs";import{appendStreamChunk as io,claimStreamRun as lo,deleteStreamRun as no,finishStreamRun as so,migrateDurableStreams as co,readStreamChunks as mo,readStreamRun as po,trimStreamRuns as So}from"./packem_shared/appendStreamChunk-C1Ok4b6J.mjs";import{DurableStreamRunner as fo,MAX_DURABLE_STREAM_BYTES as Eo,MAX_DURABLE_STREAM_CHUNKS as ho,decideDurableAttach as xo}from"./packem_shared/DurableStreamRunner-rTYp4v03.mjs";import{envOptionalPositiveInt as Co,envPositiveInt as Ro}from"./packem_shared/envOptionalPositiveInt-D2pY-c64.mjs";import{diffExternalSource as go}from"./packem_shared/diffExternalSource-DgDJhslq.mjs";import{liftSourceId as Io,normalizeSourceDocument as bo,normalizeSourceValue as Lo}from"./packem_shared/liftSourceId-CA3ENhXj.mjs";import{materializeExternalRows as Oo,materializeExternalRowsIncremental as Po,readExternalSourceBaseline as Mo,runExternalSourceTick as yo}from"./packem_shared/materializeExternalRows-xQWkrJqp.mjs";import{isSoftDeleted as ko,isSourceDue as No,pullExternalSourceIncrementalTick as Bo,pullExternalSourceTick as Uo}from"./packem_shared/isSoftDeleted-BXWqZxA-.mjs";import{GEO_DEFAULT_PRECISION as qo,boundingBoxCenter as vo,boundingBoxGeohashes as wo,coveringGeohashes as Ko,encodeGeohash as Xo,haversineMeters as Ho,pointInBoundingBox as Wo}from"./packem_shared/GEO_DEFAULT_PRECISION-CqpQZ-J_.mjs";import{default as Vo}from"./packem_shared/GlobalPollTick-BNK4o-XT.mjs";import{ADMIN_FUNCTIONS as Yo,ADMIN_FUNCTION_PREFIX as jo,DEFAULT_FANOUT_TOPIC_LIMIT as Jo,FLAGS_FUNCTION_PREFIX as Zo,MAX_PAGE_SIZE as $o,RELATION_FUNCTION_PREFIX as ea,createFanoutCounters as ra,createGlobalPollCounters as oa,createShapeProbeCounters as aa,facetColumn as ta,findStorageReferences as ia,listTables as la,readTablePage as na,recordFanoutPass as sa,recordGlobalPollPass as da,recordShapeProbePass as ca,selectMatchingIds as ma,summarizeFanoutTopics as pa,summarizeSubscriptions as Sa}from"./packem_shared/ADMIN_FUNCTIONS-BjpFlIz5.mjs";import{MAIL_RETENTION as fa,MAIL_TABLE as Ea,clearCapturedMail as ha,ensureMailTable as xa,readCapturedMail as Ta,recordCapturedMail as Ca}from"./packem_shared/MAIL_RETENTION-DGAQTHHs.mjs";import{NotFoundError as Aa}from"./packem_shared/NotFoundError-BhF7FeFr.mjs";import{armRestore as _a,readBookmark as Ia}from"./packem_shared/armRestore-Bu1_8SUa.mjs";import{CURSOR_PREFIX as La,applySelect as Da,buildSeekBeforeWhere as Oa,buildSeekWhere as Pa,decodeCursor as Ma,encodeCursor as ya,equalityPinnedFields as Fa,normalizeOrderKeys as ka,softDeleteScope as Na,tiebreakDirectionFor as Ba,uniqueIndexFields as Ua}from"./packem_shared/CURSOR_PREFIX-Bn8SFoGd.mjs";import{QUEUE_TABLE as qa,clearQueueMessages as va,isLossyBody as wa,readQueueMessageById as Ka,readQueueMessages as Xa,recordQueueMessages as Ha}from"./packem_shared/QUEUE_TABLE-s7QJZvBz.mjs";import{RANK_TIEBREAK as za,encodePartitionKey as Va,matchesRankStaticWhere as Qa,rankKeyFromDoc as Ya,rankPivotConditionSql as ja,rankTableName as Ja,resolveRankPartition as Za,sortColumnName as $a}from"./packem_shared/RANK_TIEBREAK-D5xNdzB3.mjs";import{ReactiveCache as rt,reactiveCacheKey as ot}from"./packem_shared/ReactiveCache-CU_NoCMR.mjs";import{REACTOR_STATE_TABLE as tt,listReactorStates as it,migrateReactorState as lt,reactorNeedsRun as nt,readReactorState as st,writeReactorState as dt}from"./packem_shared/REACTOR_STATE_TABLE-QPRFyxMS.mjs";import{UNVOUCHABLE_DEP as mt,createReadFootprint as pt,markUnvouchableReads as St}from"./packem_shared/UNVOUCHABLE_DEP-C68htACn.mjs";import{buildIndexRange as ft,indexKeysForRow as Et,keysTouchRanges as ht}from"./packem_shared/buildIndexRange-DvN8Qj8e.mjs";import{RELATED_DEFAULT_LIMIT as Tt,RELATED_DEPTH_DECAY as Ct,RELATED_MAX_DEPTH as Rt,RELATED_MAX_LIMIT as At,deriveRelationEdges as gt,findRelated as _t}from"./packem_shared/RELATED_DEFAULT_LIMIT-B9PH28Pn.mjs";import{DEFAULT_MAX_RELATION_KEYS as bt,assertFlatPredicate as Lt,assertShapeShardable as Dt,containsRelationPredicate as Ot,isRelationPredicate as Pt,resolveRelationPredicates as Mt}from"./packem_shared/DEFAULT_MAX_RELATION_KEYS-XESc7TiB.mjs";import{applyOnDelete as Ft,distinctValues as kt,fanOutScalarCounts as Nt,relationHooks as Bt,resolveWith as Ut,runRowValidators as Gt}from"./packem_shared/applyOnDelete-7JZ4vR9r.mjs";import{DEFAULT_PROMOTION_THRESHOLDS as vt,clampPromotionThresholds as wt,nextPromotionState as Kt,relayCountFor as Xt,shapeRoutingKey as Ht}from"./packem_shared/DEFAULT_PROMOTION_THRESHOLDS-Bfx7KakS.mjs";import{DEFAULT_MAX_RELAYS as zt,OwnerRelay as Vt,RelayMember as Qt,createRelayLink as Yt}from"./packem_shared/DEFAULT_MAX_RELAYS-Ng4SyJ7k.mjs";import{createReplicaLink as Jt,gateReplicaDispatch as Zt,handleReplicaControl as $t}from"./packem_shared/createReplicaLink-BZvoscLq.mjs";import{buildReprojectionMigration as ri,countLegacyRows as oi,reprojectableFields as ai,reprojectionTables as ti}from"./packem_shared/buildReprojectionMigration-DNjOe6AP.mjs";import{RLS_UNWRAP_SYMBOL as li,RlsRequiredError as ni,guardWriter as si}from"./packem_shared/RLS_UNWRAP_SYMBOL-BwwTbz3Q.mjs";import{SCHEMA_HISTORY_MAX_VERSIONS as ci,readSchemaHistory as mi,readSchemaVersion as pi,recordSchemaVersion as Si}from"./packem_shared/SCHEMA_HISTORY_MAX_VERSIONS-BluIj2s-.mjs";import{serializeSqlValue as fi}from"./packem_shared/serializeSqlValue-BEMMYX1n.mjs";import{buildSettings as hi,isDevEnvironment as xi,readDeployInfo as Ti}from"./packem_shared/buildSettings-DC3VeQ0H.mjs";import{buildShapeDiff as Ri}from"./packem_shared/buildShapeDiff-CK5vViD5.mjs";import{ShapeDiffCache as gi,createShapeDiffCache as _i,globalShapeReadKey as Ii}from"./packem_shared/ShapeDiffCache-gdaILV5E.mjs";import{buildPokeFrames as Li,diffGlobalMembership as Di,encodeRowsPatch as Oi,projectColumns as Pi}from"./packem_shared/buildPokeFrames-BBE6J91z.mjs";import{ShardRunner as yi}from"./packem_shared/ShardRunner-C9p5DVOx.mjs";import{runSocketPool as ki}from"./packem_shared/runSocketPool-CZJ2X9cF.mjs";import{MAX_SQL_ROWS as Bi,assertReadonly as Ui,lintReadonlySql as Gi,runReadonlySql as qi}from"./packem_shared/MAX_SQL_ROWS-Dh_Ty0Zo.mjs";import{B as wi,b as Ki,d as Xi,a as Hi,f as Wi}from"./packem_shared/sql-projection-D3qdaItY.mjs";import{awaitWsDrain as Vi,subscriptionFrames as Qi,subscriptionListDeltas as Yi,trySendFrame as ji}from"./packem_shared/awaitWsDrain-apizgmKY.mjs";import{mergeChangedKeys as Zi,recordChangedKeys as $i,writeTouchesMemo as el}from"./packem_shared/mergeChangedKeys-BA3YxaLE.mjs";import{createSystemReader as ol}from"./packem_shared/createSystemReader-DcDLFfC-.mjs";import{ConflictError as tl}from"./packem_shared/ConflictError-C8GtJmjS.mjs";import{DEFAULT_TRANSACTION_LIMITS as ll,TransactionHeadroomTracker as nl}from"./packem_shared/DEFAULT_TRANSACTION_LIMITS-CTHQQgDC.mjs";import{hasTrigger as dl,runTriggers as cl}from"./packem_shared/hasTrigger-CjlwI4le.mjs";import{selectExpiredIds as pl}from"./packem_shared/selectExpiredIds-D5DEpBbi.mjs";import{c as ul,l as fl}from"./packem_shared/where-sql-x1YKldcq.mjs";import{RELATION_EXISTS_KEY as hl}from"./packem_shared/RELATION_EXISTS_KEY-CFUhnZSZ.mjs";import{REPROJECTION_MIGRATION_PREFIX as Tl,reprojectionMigrationId as Cl}from"./packem_shared/REPROJECTION_MIGRATION_PREFIX-Czcb6_mO.mjs";import{quoteIdentifier as Al}from"./packem_shared/quoteIdentifier-CObIFRhb.mjs";import{runShardMigrations as _l}from"./packem_shared/runShardMigrations-BLl8xFGK.mjs";import{stableStringify as bl}from"./packem_shared/stableStringify-DibjylKD.mjs";import{stableWireKey as Dl}from"./packem_shared/stableWireKey-D2US4k_J.mjs";export{Yo as ADMIN_FUNCTIONS,jo as ADMIN_FUNCTION_PREFIX,d as AGGREGATE_SQL_FUNCTION,Gr as AGG_COUNT,qr as AGG_KEY,vr as AGG_VALUE,D as AUDIT_LOG_TABLE,wi as BIGINT_KEY_DIGITS,W as CDC_LOG_TABLE,z as CDC_LOG_TABLE_SEQ_INDEX,V as CDC_META_TABLE,Ce as CLIENT_WATERMARK_TABLE,Ie as COMMIT_SEQ_FIELD,be as COMMIT_SEQ_TABLE,La as CURSOR_PREFIX,tl as ConflictError,R as CountRlsUnsupportedError,br as DATA_MIGRATION_STATE_TABLE,Jo as DEFAULT_FANOUT_TOPIC_LIMIT,bt as DEFAULT_MAX_RELATION_KEYS,zt as DEFAULT_MAX_RELAYS,vt as DEFAULT_PROMOTION_THRESHOLDS,ll as DEFAULT_TRANSACTION_LIMITS,wr as DOC_COLUMN,fo as DurableStreamRunner,Zo as FLAGS_FUNCTION_PREFIX,qo as GEO_DEFAULT_PRECISION,Fe as GLOBAL_SHAPE_SNAPSHOT_TABLE,Vo as GlobalPollTick,ve as IDEMPOTENCY_TABLE,fa as MAIL_RETENTION,Ea as MAIL_TABLE,Eo as MAX_DURABLE_STREAM_BYTES,ho as MAX_DURABLE_STREAM_CHUNKS,$o as MAX_PAGE_SIZE,Bi as MAX_SQL_ROWS,Aa as NotFoundError,F as NotUniqueError,Vt as OwnerRelay,qa as QUEUE_TABLE,za as RANK_TIEBREAK,tt as REACTOR_STATE_TABLE,Tt as RELATED_DEFAULT_LIMIT,Ct as RELATED_DEPTH_DECAY,Rt as RELATED_MAX_DEPTH,At as RELATED_MAX_LIMIT,hl as RELATION_EXISTS_KEY,ea as RELATION_FUNCTION_PREFIX,Tl as REPROJECTION_MIGRATION_PREFIX,li as RLS_UNWRAP_SYMBOL,rt as ReactiveCache,Qt as RelayMember,ni as RlsRequiredError,Pr as SCAN_DEP,$e as SCHEDULE_OUTBOX_TABLE,ci as SCHEMA_HISTORY_MAX_VERSIONS,dr as SEARCH_STATE_TABLE,ur as SHAPE_POKE_CURSOR_TABLE,gi as ShapeDiffCache,yi as ShardRunner,nl as TransactionHeadroomTracker,mt as UNVOUCHABLE_DEP,Re as advanceClientWatermark,Kr as aggUpsertSql,c as aggregateSqlFunction,f as aggregateTableName,Le as allocateCommitSeq,O as appendAuditEntry,Q as appendCdcChange,io as appendStreamChunk,Y as applyCdcChanges,Ft as applyOnDelete,Da as applySelect,ue as archiveCdcSegment,_a as armRestore,Lt as assertFlatPredicate,k as assertNoExplicitUndefined,Ui as assertReadonly,Dt as assertShapeShardable,N as assertValidClientId,Vi as awaitWsDrain,v as backfillAggregateIndexes,w as backfillRankIndexes,K as backfillSearchIndexes,X as backfillSearchIndexesForTable,Ki as bigintSqlKey,vo as boundingBoxCenter,wo as boundingBoxGeohashes,ft as buildIndexRange,Li as buildPokeFrames,ri as buildReprojectionMigration,Oa as buildSeekBeforeWhere,Pa as buildSeekWhere,hi as buildSettings,Ri as buildShapeDiff,j as bumpCdcEpoch,fe as cdcArchiveRewound,J as cdcCanVouchFor,Z as cdcForkedError,$ as cdcSeqLeavingRows,ee as cdcTouchesTables,re as cdcTrimmedError,lo as claimStreamRun,wt as clampPromotionThresholds,ha as clearCapturedMail,ze as clearMemoryTables,va as clearQueueMessages,E as coerceAggregateNumber,oe as compactCdcDocs,ul as compileWhereSql,je as computeRankPage,Ot as containsRelationPredicate,oi as countLegacyRows,Ko as coveringGeohashes,Me as createCompanionSync,Mr as createDependencyTracker,ra as createFanoutCounters,oa as createGlobalPollCounters,Xr as createIndexSql,pt as createReadFootprint,Yt as createRelayLink,Jt as createReplicaLink,_i as createShapeDiffCache,aa as createShapeProbeCounters,B as createShardCtxDb,ol as createSystemReader,ae as cursorBelowRetainedFloor,xo as decideDurableAttach,Xi as decodeBigintSqlKey,Ma as decodeCursor,Hi as decodeFloat64SqlKey,er as deferScheduleOutbox,ke as deleteGlobalShapeSnapshot,Ne as deleteGlobalShapeSnapshotsForConnection,fr as deleteShapePokeCursor,Er as deleteShapePokeCursorsForConnection,no as deleteStreamRun,yr as depKey,gt as deriveRelationEdges,go as diffExternalSource,Di as diffGlobalMembership,kt as distinctValues,h as encodeAggregateKey,ya as encodeCursor,Xo as encodeGeohash,Va as encodePartitionKey,Oi as encodeRowsPatch,P as ensureAuditTable,xa as ensureMailTable,Co as envOptionalPositiveInt,Ro as envPositiveInt,Fa as equalityPinnedFields,o as exportShardRows,ta as facetColumn,Nt as fanOutScalarCounts,_t as findRelated,ia as findStorageReferences,so as finishStreamRun,Wi as float64SqlKey,x as foldAggregateTally,rr as forgetScheduleOutbox,Zt as gateReplicaDispatch,Hr as geoTableName,Ii as globalShapeReadKey,si as guardWriter,$t as handleReplicaControl,dl as hasTrigger,Ho as haversineMeters,a as importShardRows,Et as indexKeysForRow,xi as isDevEnvironment,Wr as isFtsAvailable,wa as isLossyBody,Ve as isMemoryTable,Pt as isRelationPredicate,ko as isSoftDeleted,No as isSourceDue,zr as jsonPath,Vr as jsonPathSql,ht as keysTouchRanges,Io as liftSourceId,Gi as lintReadonlySql,it as listReactorStates,la as listTables,fl as literalInList,St as markUnvouchableReads,Qa as matchesRankStaticWhere,m as matchesStaticWhere,Oo as materializeExternalRows,Po as materializeExternalRowsIncremental,Qe as memoryTableNames,Zi as mergeChangedKeys,A as mergeWhere,te as migrateCdcLog,ie as migrateCdcMeta,Ae as migrateClientWatermark,De as migrateCommitSeq,co as migrateDurableStreams,Be as migrateGlobalShapeSnapshot,we as migrateIdempotency,lt as migrateReactorState,or as migrateScheduleOutbox,cr as migrateSearchState,hr as migrateShapePokeCursor,le as minCdcReplayableSeq,ne as minCdcSeq,xr as minShapePokeCursor,Kt as nextPromotionState,p as normalizeCountArgument,U as normalizeIdStructurally,ka as normalizeOrderKeys,bo as normalizeSourceDocument,Lo as normalizeSourceValue,eo as param,ar as parkScheduleOutbox,t as parseExportShardArgs,i as parseImportShardArgs,g as planAggregateLookup,Wo as pointInBoundingBox,tr as probeScheduleOutbox,Pi as projectColumns,Bo as pullExternalSourceIncrementalTick,Uo as pullExternalSourceTick,Qr as qualifiedJsonPath,Yr as qualifiedJsonPathSql,Al as quoteIdentifier,Ya as rankKeyFromDoc,ja as rankPivotConditionSql,Ja as rankTableName,ot as reactiveCacheKey,nt as reactorNeedsRun,T as readAggregateValue,Ee as readArchivedCdcChanges,M as readAuditLog,Ia as readBookmark,Ta as readCapturedMail,he as readCdcArchivedThrough,se as readCdcChangeKeys,de as readCdcChanges,ce as readCdcCursor,me as readCdcEpoch,ge as readClientWatermark,Oe as readCommitSeq,Ti as readDeployInfo,ir as readDueScheduleOutbox,Mo as readExternalSourceBaseline,Ue as readGlobalShapeSnapshot,Ke as readIdempotent,Lr as readMigrationStatus,Ka as readQueueMessageById,Xa as readQueueMessages,st as readReactorState,mi as readSchemaHistory,pi as readSchemaVersion,mr as readSearchBackfillState,Tr as readShapePokeCursor,mo as readStreamChunks,po as readStreamRun,na as readTablePage,Ca as recordCapturedMail,$i as recordChangedKeys,sa as recordFanoutPass,da as recordGlobalPollPass,Ha as recordQueueMessages,lr as recordScheduleOutbox,Si as recordSchemaVersion,ca as recordShapeProbePass,Bt as relationHooks,Xt as relayCountFor,ro as renderSql,ai as reprojectableFields,Cl as reprojectionMigrationId,ti as reprojectionTables,Za as resolveRankPartition,Je as resolveRankSeekTuple,Mt as resolveRelationPredicates,Ut as resolveWith,jr as rowToDocument,Dr as runDataMigration,Nr as runDrizzle,yo as runExternalSourceTick,qi as runReadonlySql,Gt as runRowValidators,_l as runShardMigrations,ki as runSocketPool,Br as runSql,cl as runTriggers,pl as selectExpiredIds,l as selectExportTables,_ as selectIndexForAggregate,I as selectIndexForCount,b as selectIndexForGroupBy,ma as selectMatchingIds,gr as selectShapeMembers,_r as selectShapeRows,fi as serializeSqlValue,Ht as shapeRoutingKey,Na as softDeleteScope,$a as sortColumnName,oo as sqliteInList,bl as stableStringify,Dl as stableWireKey,G as stripReservedPatchFields,Qi as subscriptionFrames,Yi as subscriptionListDeltas,pa as summarizeFanoutTopics,Sa as summarizeSubscriptions,Jr as tableColumns,Fr as tableFromDepKey,S as throwingScheduler,Ba as tiebreakDirectionFor,pe as trimCdcChanges,Xe as trimIdempotent,nr as trimScheduleOutbox,So as trimStreamRuns,Zr as tryRowToDocument,ji as trySendFrame,ao as unionAll,Ua as uniqueIndexFields,n as validateImportRow,xe as writeCdcArchivedThrough,Ge as writeGlobalShapeSnapshot,He as writeIdempotent,dt as writeReactorState,pr as writeSearchBackfillState,Cr as writeShapePokeCursor,Rr as writeShapePokeCursors,el as writeTouchesMemo};
1
+ import{exportShardRows as o,importShardRows as a,parseExportShardArgs as t,parseImportShardArgs as i,selectExportTables as l,validateImportRow as n}from"./packem_shared/exportShardRows-1TkeNJI6.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-DDEoMnJR.mjs";import{aggregateTableName as f,coerceAggregateNumber as E,encodeAggregateKey as h,foldAggregateTally as x,readAggregateValue as T}from"./packem_shared/aggregateTableName-C7o-gpms.mjs";import{CountRlsUnsupportedError as R,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 O,ensureAuditTable as P,readAuditLog as M}from"./packem_shared/AUDIT_LOG_TABLE-ONxmEAIz.mjs";import{NotUniqueError as F,assertNoExplicitUndefined as k,assertValidClientId as N,createShardCtxDb as B,normalizeIdStructurally as U,stripReservedPatchFields as G}from"./packem_shared/NotUniqueError-1OMgp1sA.mjs";import{backfillAggregateIndexes as v,backfillRankIndexes as w,backfillSearchIndexes as K,backfillSearchIndexesForTable as X}from"./packem_shared/backfillAggregateIndexes-DTemznr7.mjs";import{CDC_LOG_TABLE as W,CDC_LOG_TABLE_SEQ_INDEX as z,CDC_META_TABLE as V,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 ie,minCdcReplayableSeq as le,minCdcSeq as ne,readCdcChangeKeys as se,readCdcChanges as de,readCdcCursor as ce,readCdcEpoch as me,trimCdcChanges as pe}from"./packem_shared/CDC_LOG_TABLE-DXEAcmsr.mjs";import{archiveCdcSegment as ue,cdcArchiveRewound as fe,readArchivedCdcChanges as Ee,readCdcArchivedThrough as he,writeCdcArchivedThrough as xe}from"./packem_shared/archiveCdcSegment-E_R_b5Qz.mjs";import{CLIENT_WATERMARK_TABLE as Ce,advanceClientWatermark as Re,migrateClientWatermark as Ae,readClientWatermark as ge}from"./packem_shared/CLIENT_WATERMARK_TABLE-CRnrAnJ2.mjs";import{COMMIT_SEQ_FIELD as Ie,COMMIT_SEQ_TABLE as be,allocateCommitSeq as Le,migrateCommitSeq as De,readCommitSeq as Oe}from"./packem_shared/COMMIT_SEQ_FIELD-BUdOMG5y.mjs";import{c as Me}from"./packem_shared/ctx-db-companions-DsNfXSbb.mjs";import{GLOBAL_SHAPE_SNAPSHOT_TABLE as Fe,deleteGlobalShapeSnapshot as ke,deleteGlobalShapeSnapshotsForConnection as Ne,migrateGlobalShapeSnapshot as Be,readGlobalShapeSnapshot as Ue,writeGlobalShapeSnapshot as Ge}from"./packem_shared/GLOBAL_SHAPE_SNAPSHOT_TABLE-DSA6mzyx.mjs";import{IDEMPOTENCY_TABLE as ve,migrateIdempotency as we,readIdempotent as Ke,trimIdempotent as Xe,writeIdempotent as He}from"./packem_shared/IDEMPOTENCY_TABLE-DOpm_oMF.mjs";import{clearMemoryTables as ze,isMemoryTable as Ve,memoryTableNames as Qe}from"./packem_shared/clearMemoryTables-BGbmag2i.mjs";import{computeRankPage as je,resolveRankSeekTuple as Je}from"./packem_shared/computeRankPage-pTaG_r9F.mjs";import{SCHEDULE_OUTBOX_TABLE as $e,deferScheduleOutbox as er,forgetScheduleOutbox as rr,migrateScheduleOutbox as or,parkScheduleOutbox as ar,probeScheduleOutbox as tr,readDueScheduleOutbox as ir,recordScheduleOutbox as lr,trimScheduleOutbox as nr}from"./packem_shared/SCHEDULE_OUTBOX_TABLE-CD_UjYVx.mjs";import{S as dr,m as cr,r as mr,w as pr}from"./packem_shared/ctx-db-search-state-ruTuCsxa.mjs";import{SHAPE_POKE_CURSOR_TABLE as ur,deleteShapePokeCursor as fr,deleteShapePokeCursorsForConnection as Er,migrateShapePokeCursor as hr,minShapePokeCursor as xr,readShapePokeCursor as Tr,writeShapePokeCursor as Cr,writeShapePokeCursors as Rr}from"./packem_shared/SHAPE_POKE_CURSOR_TABLE-ByJVDHds.mjs";import{selectShapeMembers as gr,selectShapeRows as _r}from"./packem_shared/selectShapeMembers-B8gTOeOB.mjs";import{DATA_MIGRATION_STATE_TABLE as br,readMigrationStatus as Lr,runDataMigration as Dr}from"./packem_shared/DATA_MIGRATION_STATE_TABLE-BwFz6NTT.mjs";import{SCAN_DEP as Pr,createDependencyTracker as Mr,depKey as yr,tableFromDepKey as Fr}from"./packem_shared/SCAN_DEP-D7qE3iUe.mjs";import{runDrizzle as Nr,runSql as Br}from"./packem_shared/runDrizzle-2ULFQR_k.mjs";import{A as Gr,a as qr,b as vr,D as wr,c as Kr,d as Xr,g as Hr,i as Wr,j as zr,e as Vr,q as Qr,f as Yr,r as jr,t as Jr,h as Zr}from"./packem_shared/do-sql-kpl5Kt1j.mjs";import{param as eo,renderSql as ro,sqliteInList as oo,unionAll as ao}from"./packem_shared/param-DlozcSQu.mjs";import{appendStreamChunk as io,claimStreamRun as lo,deleteStreamRun as no,finishStreamRun as so,migrateDurableStreams as co,readStreamChunks as mo,readStreamRun as po,trimStreamRuns as So}from"./packem_shared/appendStreamChunk-C1Ok4b6J.mjs";import{DurableStreamRunner as fo,MAX_DURABLE_STREAM_BYTES as Eo,MAX_DURABLE_STREAM_CHUNKS as ho,decideDurableAttach as xo}from"./packem_shared/DurableStreamRunner-rTYp4v03.mjs";import{envOptionalPositiveInt as Co,envPositiveInt as Ro}from"./packem_shared/envOptionalPositiveInt-D2pY-c64.mjs";import{diffExternalSource as go}from"./packem_shared/diffExternalSource-DgDJhslq.mjs";import{liftSourceId as Io,normalizeSourceDocument as bo,normalizeSourceValue as Lo}from"./packem_shared/liftSourceId-CA3ENhXj.mjs";import{materializeExternalRows as Oo,materializeExternalRowsIncremental as Po,readExternalSourceBaseline as Mo,runExternalSourceTick as yo}from"./packem_shared/materializeExternalRows-B1623YXA.mjs";import{isSoftDeleted as ko,isSourceDue as No,pullExternalSourceIncrementalTick as Bo,pullExternalSourceTick as Uo}from"./packem_shared/isSoftDeleted-DIMlSsdB.mjs";import{GEO_DEFAULT_PRECISION as qo,boundingBoxCenter as vo,boundingBoxGeohashes as wo,coveringGeohashes as Ko,encodeGeohash as Xo,haversineMeters as Ho,pointInBoundingBox as Wo}from"./packem_shared/GEO_DEFAULT_PRECISION-CqpQZ-J_.mjs";import{default as Vo}from"./packem_shared/GlobalPollTick-BNK4o-XT.mjs";import{ADMIN_FUNCTIONS as Yo,ADMIN_FUNCTION_PREFIX as jo,DEFAULT_FANOUT_TOPIC_LIMIT as Jo,FLAGS_FUNCTION_PREFIX as Zo,MAX_PAGE_SIZE as $o,RELATION_FUNCTION_PREFIX as ea,createFanoutCounters as ra,createGlobalPollCounters as oa,createShapeProbeCounters as aa,facetColumn as ta,findStorageReferences as ia,listTables as la,readTablePage as na,recordFanoutPass as sa,recordGlobalPollPass as da,recordShapeProbePass as ca,selectMatchingIds as ma,summarizeFanoutTopics as pa,summarizeSubscriptions as Sa}from"./packem_shared/ADMIN_FUNCTIONS-BjpFlIz5.mjs";import{MAIL_RETENTION as fa,MAIL_TABLE as Ea,clearCapturedMail as ha,ensureMailTable as xa,readCapturedMail as Ta,recordCapturedMail as Ca}from"./packem_shared/MAIL_RETENTION-DGAQTHHs.mjs";import{NotFoundError as Aa}from"./packem_shared/NotFoundError-BhF7FeFr.mjs";import{armRestore as _a,readBookmark as Ia}from"./packem_shared/armRestore-Bu1_8SUa.mjs";import{CURSOR_PREFIX as La,applySelect as Da,buildSeekBeforeWhere as Oa,buildSeekWhere as Pa,decodeCursor as Ma,encodeCursor as ya,equalityPinnedFields as Fa,normalizeOrderKeys as ka,softDeleteScope as Na,tiebreakDirectionFor as Ba,uniqueIndexFields as Ua}from"./packem_shared/CURSOR_PREFIX-Bn8SFoGd.mjs";import{QUEUE_TABLE as qa,clearQueueMessages as va,isLossyBody as wa,readQueueMessageById as Ka,readQueueMessages as Xa,recordQueueMessages as Ha}from"./packem_shared/QUEUE_TABLE-s7QJZvBz.mjs";import{RANK_TIEBREAK as za,encodePartitionKey as Va,matchesRankStaticWhere as Qa,rankKeyFromDoc as Ya,rankPivotConditionSql as ja,rankTableName as Ja,resolveRankPartition as Za,sortColumnName as $a}from"./packem_shared/RANK_TIEBREAK-D5xNdzB3.mjs";import{ReactiveCache as rt,reactiveCacheKey as ot}from"./packem_shared/ReactiveCache-CU_NoCMR.mjs";import{REACTOR_STATE_TABLE as tt,listReactorStates as it,migrateReactorState as lt,reactorNeedsRun as nt,readReactorState as st,writeReactorState as dt}from"./packem_shared/REACTOR_STATE_TABLE-QPRFyxMS.mjs";import{UNVOUCHABLE_DEP as mt,createReadFootprint as pt,markUnvouchableReads as St}from"./packem_shared/UNVOUCHABLE_DEP-C68htACn.mjs";import{buildIndexRange as ft,indexKeysForRow as Et,keysTouchRanges as ht}from"./packem_shared/buildIndexRange-DvN8Qj8e.mjs";import{RELATED_DEFAULT_LIMIT as Tt,RELATED_DEPTH_DECAY as Ct,RELATED_MAX_DEPTH as Rt,RELATED_MAX_LIMIT as At,deriveRelationEdges as gt,findRelated as _t}from"./packem_shared/RELATED_DEFAULT_LIMIT-B9PH28Pn.mjs";import{DEFAULT_MAX_RELATION_KEYS as bt,assertFlatPredicate as Lt,assertShapeShardable as Dt,containsRelationPredicate as Ot,isRelationPredicate as Pt,resolveRelationPredicates as Mt}from"./packem_shared/DEFAULT_MAX_RELATION_KEYS-XESc7TiB.mjs";import{applyOnDelete as Ft,distinctValues as kt,fanOutScalarCounts as Nt,relationHooks as Bt,resolveWith as Ut,runRowValidators as Gt}from"./packem_shared/applyOnDelete-7JZ4vR9r.mjs";import{DEFAULT_PROMOTION_THRESHOLDS as vt,clampPromotionThresholds as wt,nextPromotionState as Kt,relayCountFor as Xt,shapeRoutingKey as Ht}from"./packem_shared/DEFAULT_PROMOTION_THRESHOLDS-Bfx7KakS.mjs";import{DEFAULT_MAX_RELAYS as zt,OwnerRelay as Vt,RelayMember as Qt,createRelayLink as Yt}from"./packem_shared/DEFAULT_MAX_RELAYS-Ng4SyJ7k.mjs";import{createReplicaLink as Jt,gateReplicaDispatch as Zt,handleReplicaControl as $t}from"./packem_shared/createReplicaLink-CUnl1y_Q.mjs";import{buildReprojectionMigration as ri,countLegacyRows as oi,reprojectableFields as ai,reprojectionTables as ti}from"./packem_shared/buildReprojectionMigration-DNjOe6AP.mjs";import{RLS_UNWRAP_SYMBOL as li,RlsRequiredError as ni,guardWriter as si}from"./packem_shared/RLS_UNWRAP_SYMBOL-BwwTbz3Q.mjs";import{SCHEMA_HISTORY_MAX_VERSIONS as ci,readSchemaHistory as mi,readSchemaVersion as pi,recordSchemaVersion as Si}from"./packem_shared/SCHEMA_HISTORY_MAX_VERSIONS-BluIj2s-.mjs";import{serializeSqlValue as fi}from"./packem_shared/serializeSqlValue-BEMMYX1n.mjs";import{buildSettings as hi,isDevEnvironment as xi,readDeployInfo as Ti}from"./packem_shared/buildSettings-DC3VeQ0H.mjs";import{buildShapeDiff as Ri}from"./packem_shared/buildShapeDiff-CnCHKdCw.mjs";import{ShapeDiffCache as gi,createShapeDiffCache as _i,globalShapeReadKey as Ii}from"./packem_shared/ShapeDiffCache-gdaILV5E.mjs";import{buildPokeFrames as Li,diffGlobalMembership as Di,encodeRowsPatch as Oi,projectColumns as Pi}from"./packem_shared/buildPokeFrames-BBE6J91z.mjs";import{ShardRunner as yi}from"./packem_shared/ShardRunner-C9p5DVOx.mjs";import{runSocketPool as ki}from"./packem_shared/runSocketPool-CZJ2X9cF.mjs";import{MAX_SQL_ROWS as Bi,assertReadonly as Ui,lintReadonlySql as Gi,runReadonlySql as qi}from"./packem_shared/MAX_SQL_ROWS-Dh_Ty0Zo.mjs";import{B as wi,b as Ki,d as Xi,a as Hi,f as Wi}from"./packem_shared/sql-projection-D3qdaItY.mjs";import{awaitWsDrain as Vi,subscriptionFrames as Qi,subscriptionListDeltas as Yi,trySendFrame as ji}from"./packem_shared/awaitWsDrain-apizgmKY.mjs";import{mergeChangedKeys as Zi,recordChangedKeys as $i,writeTouchesMemo as el}from"./packem_shared/mergeChangedKeys-BA3YxaLE.mjs";import{createSystemReader as ol}from"./packem_shared/createSystemReader-DcDLFfC-.mjs";import{ConflictError as tl}from"./packem_shared/ConflictError-C8GtJmjS.mjs";import{DEFAULT_TRANSACTION_LIMITS as ll,TransactionHeadroomTracker as nl}from"./packem_shared/DEFAULT_TRANSACTION_LIMITS-CTHQQgDC.mjs";import{hasTrigger as dl,runTriggers as cl}from"./packem_shared/hasTrigger-CjlwI4le.mjs";import{selectExpiredIds as pl}from"./packem_shared/selectExpiredIds-D5DEpBbi.mjs";import{c as ul,l as fl}from"./packem_shared/where-sql-x1YKldcq.mjs";import{RELATION_EXISTS_KEY as hl}from"./packem_shared/RELATION_EXISTS_KEY-CFUhnZSZ.mjs";import{REPROJECTION_MIGRATION_PREFIX as Tl,reprojectionMigrationId as Cl}from"./packem_shared/REPROJECTION_MIGRATION_PREFIX-Czcb6_mO.mjs";import{quoteIdentifier as Al}from"./packem_shared/quoteIdentifier-CObIFRhb.mjs";import{runShardMigrations as _l}from"./packem_shared/runShardMigrations-DGlaC68E.mjs";import{stableStringify as bl}from"./packem_shared/stableStringify-DibjylKD.mjs";import{stableWireKey as Dl}from"./packem_shared/stableWireKey-D2US4k_J.mjs";export{Yo as ADMIN_FUNCTIONS,jo as ADMIN_FUNCTION_PREFIX,d as AGGREGATE_SQL_FUNCTION,Gr as AGG_COUNT,qr as AGG_KEY,vr as AGG_VALUE,D as AUDIT_LOG_TABLE,wi as BIGINT_KEY_DIGITS,W as CDC_LOG_TABLE,z as CDC_LOG_TABLE_SEQ_INDEX,V as CDC_META_TABLE,Ce as CLIENT_WATERMARK_TABLE,Ie as COMMIT_SEQ_FIELD,be as COMMIT_SEQ_TABLE,La as CURSOR_PREFIX,tl as ConflictError,R as CountRlsUnsupportedError,br as DATA_MIGRATION_STATE_TABLE,Jo as DEFAULT_FANOUT_TOPIC_LIMIT,bt as DEFAULT_MAX_RELATION_KEYS,zt as DEFAULT_MAX_RELAYS,vt as DEFAULT_PROMOTION_THRESHOLDS,ll as DEFAULT_TRANSACTION_LIMITS,wr as DOC_COLUMN,fo as DurableStreamRunner,Zo as FLAGS_FUNCTION_PREFIX,qo as GEO_DEFAULT_PRECISION,Fe as GLOBAL_SHAPE_SNAPSHOT_TABLE,Vo as GlobalPollTick,ve as IDEMPOTENCY_TABLE,fa as MAIL_RETENTION,Ea as MAIL_TABLE,Eo as MAX_DURABLE_STREAM_BYTES,ho as MAX_DURABLE_STREAM_CHUNKS,$o as MAX_PAGE_SIZE,Bi as MAX_SQL_ROWS,Aa as NotFoundError,F as NotUniqueError,Vt as OwnerRelay,qa as QUEUE_TABLE,za as RANK_TIEBREAK,tt as REACTOR_STATE_TABLE,Tt as RELATED_DEFAULT_LIMIT,Ct as RELATED_DEPTH_DECAY,Rt as RELATED_MAX_DEPTH,At as RELATED_MAX_LIMIT,hl as RELATION_EXISTS_KEY,ea as RELATION_FUNCTION_PREFIX,Tl as REPROJECTION_MIGRATION_PREFIX,li as RLS_UNWRAP_SYMBOL,rt as ReactiveCache,Qt as RelayMember,ni as RlsRequiredError,Pr as SCAN_DEP,$e as SCHEDULE_OUTBOX_TABLE,ci as SCHEMA_HISTORY_MAX_VERSIONS,dr as SEARCH_STATE_TABLE,ur as SHAPE_POKE_CURSOR_TABLE,gi as ShapeDiffCache,yi as ShardRunner,nl as TransactionHeadroomTracker,mt as UNVOUCHABLE_DEP,Re as advanceClientWatermark,Kr as aggUpsertSql,c as aggregateSqlFunction,f as aggregateTableName,Le as allocateCommitSeq,O as appendAuditEntry,Q as appendCdcChange,io as appendStreamChunk,Y as applyCdcChanges,Ft as applyOnDelete,Da as applySelect,ue as archiveCdcSegment,_a as armRestore,Lt as assertFlatPredicate,k as assertNoExplicitUndefined,Ui as assertReadonly,Dt as assertShapeShardable,N as assertValidClientId,Vi as awaitWsDrain,v as backfillAggregateIndexes,w as backfillRankIndexes,K as backfillSearchIndexes,X as backfillSearchIndexesForTable,Ki as bigintSqlKey,vo as boundingBoxCenter,wo as boundingBoxGeohashes,ft as buildIndexRange,Li as buildPokeFrames,ri as buildReprojectionMigration,Oa as buildSeekBeforeWhere,Pa as buildSeekWhere,hi as buildSettings,Ri as buildShapeDiff,j as bumpCdcEpoch,fe as cdcArchiveRewound,J as cdcCanVouchFor,Z as cdcForkedError,$ as cdcSeqLeavingRows,ee as cdcTouchesTables,re as cdcTrimmedError,lo as claimStreamRun,wt as clampPromotionThresholds,ha as clearCapturedMail,ze as clearMemoryTables,va as clearQueueMessages,E as coerceAggregateNumber,oe as compactCdcDocs,ul as compileWhereSql,je as computeRankPage,Ot as containsRelationPredicate,oi as countLegacyRows,Ko as coveringGeohashes,Me as createCompanionSync,Mr as createDependencyTracker,ra as createFanoutCounters,oa as createGlobalPollCounters,Xr as createIndexSql,pt as createReadFootprint,Yt as createRelayLink,Jt as createReplicaLink,_i as createShapeDiffCache,aa as createShapeProbeCounters,B as createShardCtxDb,ol as createSystemReader,ae as cursorBelowRetainedFloor,xo as decideDurableAttach,Xi as decodeBigintSqlKey,Ma as decodeCursor,Hi as decodeFloat64SqlKey,er as deferScheduleOutbox,ke as deleteGlobalShapeSnapshot,Ne as deleteGlobalShapeSnapshotsForConnection,fr as deleteShapePokeCursor,Er as deleteShapePokeCursorsForConnection,no as deleteStreamRun,yr as depKey,gt as deriveRelationEdges,go as diffExternalSource,Di as diffGlobalMembership,kt as distinctValues,h as encodeAggregateKey,ya as encodeCursor,Xo as encodeGeohash,Va as encodePartitionKey,Oi as encodeRowsPatch,P as ensureAuditTable,xa as ensureMailTable,Co as envOptionalPositiveInt,Ro as envPositiveInt,Fa as equalityPinnedFields,o as exportShardRows,ta as facetColumn,Nt as fanOutScalarCounts,_t as findRelated,ia as findStorageReferences,so as finishStreamRun,Wi as float64SqlKey,x as foldAggregateTally,rr as forgetScheduleOutbox,Zt as gateReplicaDispatch,Hr as geoTableName,Ii as globalShapeReadKey,si as guardWriter,$t as handleReplicaControl,dl as hasTrigger,Ho as haversineMeters,a as importShardRows,Et as indexKeysForRow,xi as isDevEnvironment,Wr as isFtsAvailable,wa as isLossyBody,Ve as isMemoryTable,Pt as isRelationPredicate,ko as isSoftDeleted,No as isSourceDue,zr as jsonPath,Vr as jsonPathSql,ht as keysTouchRanges,Io as liftSourceId,Gi as lintReadonlySql,it as listReactorStates,la as listTables,fl as literalInList,St as markUnvouchableReads,Qa as matchesRankStaticWhere,m as matchesStaticWhere,Oo as materializeExternalRows,Po as materializeExternalRowsIncremental,Qe as memoryTableNames,Zi as mergeChangedKeys,A as mergeWhere,te as migrateCdcLog,ie as migrateCdcMeta,Ae as migrateClientWatermark,De as migrateCommitSeq,co as migrateDurableStreams,Be as migrateGlobalShapeSnapshot,we as migrateIdempotency,lt as migrateReactorState,or as migrateScheduleOutbox,cr as migrateSearchState,hr as migrateShapePokeCursor,le as minCdcReplayableSeq,ne as minCdcSeq,xr as minShapePokeCursor,Kt as nextPromotionState,p as normalizeCountArgument,U as normalizeIdStructurally,ka as normalizeOrderKeys,bo as normalizeSourceDocument,Lo as normalizeSourceValue,eo as param,ar as parkScheduleOutbox,t as parseExportShardArgs,i as parseImportShardArgs,g as planAggregateLookup,Wo as pointInBoundingBox,tr as probeScheduleOutbox,Pi as projectColumns,Bo as pullExternalSourceIncrementalTick,Uo as pullExternalSourceTick,Qr as qualifiedJsonPath,Yr as qualifiedJsonPathSql,Al as quoteIdentifier,Ya as rankKeyFromDoc,ja as rankPivotConditionSql,Ja as rankTableName,ot as reactiveCacheKey,nt as reactorNeedsRun,T as readAggregateValue,Ee as readArchivedCdcChanges,M as readAuditLog,Ia as readBookmark,Ta as readCapturedMail,he as readCdcArchivedThrough,se as readCdcChangeKeys,de as readCdcChanges,ce as readCdcCursor,me as readCdcEpoch,ge as readClientWatermark,Oe as readCommitSeq,Ti as readDeployInfo,ir as readDueScheduleOutbox,Mo as readExternalSourceBaseline,Ue as readGlobalShapeSnapshot,Ke as readIdempotent,Lr as readMigrationStatus,Ka as readQueueMessageById,Xa as readQueueMessages,st as readReactorState,mi as readSchemaHistory,pi as readSchemaVersion,mr as readSearchBackfillState,Tr as readShapePokeCursor,mo as readStreamChunks,po as readStreamRun,na as readTablePage,Ca as recordCapturedMail,$i as recordChangedKeys,sa as recordFanoutPass,da as recordGlobalPollPass,Ha as recordQueueMessages,lr as recordScheduleOutbox,Si as recordSchemaVersion,ca as recordShapeProbePass,Bt as relationHooks,Xt as relayCountFor,ro as renderSql,ai as reprojectableFields,Cl as reprojectionMigrationId,ti as reprojectionTables,Za as resolveRankPartition,Je as resolveRankSeekTuple,Mt as resolveRelationPredicates,Ut as resolveWith,jr as rowToDocument,Dr as runDataMigration,Nr as runDrizzle,yo as runExternalSourceTick,qi as runReadonlySql,Gt as runRowValidators,_l as runShardMigrations,ki as runSocketPool,Br as runSql,cl as runTriggers,pl as selectExpiredIds,l as selectExportTables,_ as selectIndexForAggregate,I as selectIndexForCount,b as selectIndexForGroupBy,ma as selectMatchingIds,gr as selectShapeMembers,_r as selectShapeRows,fi as serializeSqlValue,Ht as shapeRoutingKey,Na as softDeleteScope,$a as sortColumnName,oo as sqliteInList,bl as stableStringify,Dl as stableWireKey,G as stripReservedPatchFields,Qi as subscriptionFrames,Yi as subscriptionListDeltas,pa as summarizeFanoutTopics,Sa as summarizeSubscriptions,Jr as tableColumns,Fr as tableFromDepKey,S as throwingScheduler,Ba as tiebreakDirectionFor,pe as trimCdcChanges,Xe as trimIdempotent,nr as trimScheduleOutbox,So as trimStreamRuns,Zr as tryRowToDocument,ji as trySendFrame,ao as unionAll,Ua as uniqueIndexFields,n as validateImportRow,xe as writeCdcArchivedThrough,Ge as writeGlobalShapeSnapshot,He as writeIdempotent,dt as writeReactorState,pr as writeSearchBackfillState,Cr as writeShapePokeCursor,Rr as writeShapePokeCursors,el as writeTouchesMemo};
@@ -0,0 +1,18 @@
1
+ import{LunoraError as R}from"@lunora/errors";import{sql as t}from"drizzle-orm";import{quoteIdentifier as C}from"./quoteIdentifier-CObIFRhb.mjs";import{runSql as A,runDrizzle as n}from"./runDrizzle-2ULFQR_k.mjs";import{k as m,l as u}from"./do-sql-kpl5Kt1j.mjs";import{ConflictError as I}from"./ConflictError-C8GtJmjS.mjs";const s="__cdc_log",p=`INSERT INTO ${C(s)} (ts, ${C("table")}, id, op, doc) VALUES (?, ?, ?, ?, ?)`,$="__cdc_log_table_seq",N="__cdc_log_table_id_seq",y=(e,o={})=>{n(e,t`CREATE TABLE IF NOT EXISTS ${t.identifier(s)} (
2
+ seq INTEGER PRIMARY KEY AUTOINCREMENT,
3
+ ts REAL NOT NULL,
4
+ ${t.identifier("table")} TEXT NOT NULL,
5
+ id TEXT NOT NULL,
6
+ op TEXT NOT NULL,
7
+ doc TEXT
8
+ )`);try{n(e,t`CREATE INDEX IF NOT EXISTS ${t.identifier($)} ON ${t.identifier(s)} (${t.identifier("table")}, seq)`)}catch{}if(o.rowHistoryIndex===!0)try{n(e,t`CREATE INDEX IF NOT EXISTS ${t.identifier(N)} ON ${t.identifier(s)} (${t.identifier("table")}, id, seq)`)}catch{}},F=(e,o,r,i,c,d)=>{const a=d===void 0?null:m(d);A(e,p,o,r,i,c,a)},f=90,q=e=>t` AND ${t.identifier("table")} IN (${t.join([...e].map(o=>t`${o}`),t`, `)})`,U=(e,o={})=>{const r=o.sinceSeq??0,i=Math.max(1,Math.min(o.limit??1e3,1e4)),d=n(e,t`SELECT seq, ts, ${t.identifier("table")}, id, op, doc FROM ${t.identifier(s)} WHERE seq > ${r} ORDER BY seq ASC LIMIT ${i}`).toArray().map(a=>{const T={id:a.id,op:a.op,seq:a.seq,table:a.table,ts:a.ts};return a.doc===null?T:{...T,doc:u(a.doc)}});return{changes:d,cursor:d.at(-1)?.seq??r}},X=(e,o,r)=>{if(r.size===0)return!1;const i=[...r];for(let c=0;c<i.length;c+=f){const d=new Set(i.slice(c,c+f));if(n(e,t`SELECT 1 AS hit FROM ${t.identifier(s)} WHERE seq > ${o}${q(d)} LIMIT 1`).toArray().length>0)return!0}return!1},l=new WeakMap,S=e=>new Set(n(e,t`SELECT name FROM sqlite_master WHERE type = 'table'`).toArray().map(o=>o.name)),v=(e,o)=>{if(o.size===0)return!1;let r=l.get(e),i=!1;r===void 0&&(r=S(e),i=!0,l.set(e,r));for(const c of o)if(!r.has(c)&&(i||(r=S(e),i=!0,l.set(e,r),!r.has(c))))return!1;return!0},B=(e,o,r,i)=>{const d=n(e,t`SELECT doc FROM ${t.identifier(s)}
9
+ WHERE ${t.identifier("table")} = ${o} AND id = ${r} AND seq <= ${i}
10
+ ORDER BY seq DESC
11
+ LIMIT 1`).toArray()[0]?.doc;return d==null?void 0:u(d)},H=(e,o,r,i)=>n(e,t`SELECT id, op, MAX(seq) AS maxSeq, COUNT(*) AS ops FROM ${t.identifier(s)}
12
+ WHERE ${t.identifier("table")} = ${o} AND seq > ${r} AND seq <= ${i}
13
+ GROUP BY id
14
+ ORDER BY maxSeq ASC`).toArray().map(d=>{const a=d.op;return{id:d.id,op:a==="insert"&&d.ops>1?"update":a,seq:d.maxSeq}}),x=(e,o,r)=>{n(e,t`DELETE FROM ${t.identifier(s)} WHERE seq IN (
15
+ SELECT seq FROM ${t.identifier(s)} WHERE seq <= ${o} ORDER BY seq ASC LIMIT ${r}
16
+ )`)},W=(e,o,r)=>{n(e,t`UPDATE ${t.identifier(s)} SET doc = NULL WHERE seq IN (
17
+ SELECT seq FROM ${t.identifier(s)} WHERE seq <= ${o} AND doc IS NOT NULL ORDER BY seq ASC LIMIT ${r}
18
+ )`)},Y=(e,o)=>{if(o<=0)return n(e,t`SELECT MAX(seq) AS seq FROM ${t.identifier(s)}`).toArray()[0]?.seq??void 0;const i=n(e,t`SELECT seq FROM ${t.identifier(s)} ORDER BY seq DESC LIMIT 1 OFFSET ${o-1}`).toArray()[0]?.seq;return i===void 0?void 0:i-1},G=e=>{const r=n(e,t`SELECT seq FROM sqlite_sequence WHERE name = ${s}`).toArray()[0]?.seq;return typeof r=="number"?r:n(e,t`SELECT MAX(seq) AS seq FROM ${t.identifier(s)}`).toArray()[0]?.seq??0},K=(e,o)=>e!==void 0&&e>o+1,P=(e,o,r)=>new R("CDC_LOG_TRIMMED",`${r==="global"?"global cdc":"cdc"} entries at or below seq ${String(e-1)} have been trimmed; resume from a snapshot (sinceSeq ${String(o)} is below the retained window)`,{status:409}),k=(e,o,r,i)=>new R("CDC_TIMELINE_FORKED",`${r==="global"?"global cdc":"cdc"} cursor ${String(o)} is above ${r==="global"?"the changelog's":"this shard's"} high-watermark ${String(e)}; the changelog rolled back (a point-in-time restore) and the changes you hold are on a timeline that no longer exists — resume from a snapshot${i===void 0?"":` at epoch ${i}`}`,{data:{cursor:e,...i===void 0?{}:{epoch:i}},status:409}),O=e=>n(e,t`SELECT MIN(seq) AS seq FROM ${t.identifier(s)}`).toArray()[0]?.seq??void 0,V=e=>{const r=n(e,t`SELECT MAX(seq) AS seq FROM ${t.identifier(s)} WHERE op <> 'delete' AND doc IS NULL`).toArray()[0]?.seq??void 0,i=O(e);return r===void 0?i:Math.max(r+1,i??0)},E="__cdc_meta",L=e=>{n(e,t`CREATE TABLE IF NOT EXISTS ${t.identifier(E)} (id INTEGER PRIMARY KEY CHECK (id = 1), epoch TEXT NOT NULL)`)},z=e=>{L(e);const r=n(e,t`SELECT epoch FROM ${t.identifier(E)} WHERE id = 1`).toArray()[0]?.epoch;if(typeof r=="string"&&r.length>0)return r;const i=crypto.randomUUID();return n(e,t`INSERT INTO ${t.identifier(E)} (id, epoch) VALUES (1, ${i})`),i},Q=e=>{L(e);const o=crypto.randomUUID();return n(e,t`INSERT INTO ${t.identifier(E)} (id, epoch) VALUES (1, ${o}) ON CONFLICT(id) DO UPDATE SET epoch = excluded.epoch`),o},h=async(e,o)=>{if(o.op==="delete"){await e.delete(o.id,o.table);return}const r=o.doc??{};try{await e.insert(o.table,r,{allowExplicitId:!0})}catch(i){if(!(i instanceof I))throw i;const c={...r};delete c._id,await e.replace(o.id,c,o.table,{allowExplicitId:!0})}},J=async(e,o)=>{for(const r of o)await h(e,r)};export{p as CDC_APPEND_SQL,s as CDC_LOG_TABLE,$ as CDC_LOG_TABLE_SEQ_INDEX,E as CDC_META_TABLE,F as appendCdcChange,J as applyCdcChanges,Q as bumpCdcEpoch,v as cdcCanVouchFor,k as cdcForkedError,Y as cdcSeqLeavingRows,X as cdcTouchesTables,P as cdcTrimmedError,W as compactCdcDocs,K as cursorBelowRetainedFloor,y as migrateCdcLog,L as migrateCdcMeta,V as minCdcReplayableSeq,O as minCdcSeq,H as readCdcChangeKeys,U as readCdcChanges,G as readCdcCursor,B as readCdcDocAtOrBefore,z as readCdcEpoch,x as trimCdcChanges};
@@ -0,0 +1 @@
1
+ import{LunoraError as $}from"@lunora/errors";import{D as dt}from"./MAX_TOKEN_LENGTH-BakL9FUy-B3VwYY8C.mjs";import{c as mn,S as Sn,l as Fe,a as _n}from"./ctx-db-companions-DsNfXSbb.mjs";import{sql as i}from"drizzle-orm";import{d as Rn}from"./wire-codec-C-FpWm52.mjs";import{stableWireKey as At}from"./stableWireKey-D2US4k_J.mjs";import{throwingScheduler as Tn,aggregateSqlFunction as qe,normalizeCountArgument as vn}from"./AGGREGATE_SQL_FUNCTION-DDEoMnJR.mjs";import{aggregateTableName as Je,encodeAggregateKey as Ye,readAggregateValue as Xe}from"./aggregateTableName-C7o-gpms.mjs";import{mergeWhere as z,CountRlsUnsupportedError as Ze,selectIndexForGroupBy as An,selectIndexForCount as In,selectIndexForAggregate as Cn}from"./CountRlsUnsupportedError-BvsDqfO2.mjs";import{backfillSearchIndexesForTable as xn,searchIndexCoversTable as bn}from"./backfillAggregateIndexes-DTemznr7.mjs";import{backfillAggregateIndexes as Pr,backfillRankIndexes as Ur,backfillSearchIndexes as Gr}from"./backfillAggregateIndexes-DTemznr7.mjs";import{appendCdcChange as Mn,readCdcDocAtOrBefore as Dn}from"./CDC_LOG_TABLE-DXEAcmsr.mjs";import{CDC_LOG_TABLE as Hr,applyCdcChanges as Nr,bumpCdcEpoch as jr,cdcCanVouchFor as Kr,cdcForkedError as Qr,cdcSeqLeavingRows as Vr,cdcTouchesTables as zr,cdcTrimmedError as Jr,compactCdcDocs as Yr,cursorBelowRetainedFloor as Xr,minCdcReplayableSeq as Zr,minCdcSeq as ei,readCdcChangeKeys as ti,readCdcChanges as ni,readCdcCursor as oi,readCdcEpoch as ri,trimCdcChanges as ii}from"./CDC_LOG_TABLE-DXEAcmsr.mjs";import{allocateCommitSeq as kn,COMMIT_SEQ_FIELD as Ln}from"./COMMIT_SEQ_FIELD-BUdOMG5y.mjs";import{isMemoryTable as It}from"./clearMemoryTables-BGbmag2i.mjs";import{computeRankPage as Ct}from"./computeRankPage-pTaG_r9F.mjs";import{SCAN_DEP as O}from"./SCAN_DEP-D7qE3iUe.mjs";import{runDrizzle as N,runSql as _e}from"./runDrizzle-2ULFQR_k.mjs";import{D as ne,k as ce,r as le,b as Be,A as et,a as We,e as X,o as Fn,t as Yt,j as Ge,q as xt,i as qn,h as Xt,g as Bn}from"./do-sql-kpl5Kt1j.mjs";import{renderSql as Zt,unionAll as lt,WORKERD_SQLITE_LIMITS as en,sqliteInList as Wn}from"./param-DlozcSQu.mjs";import{coveringGeohashes as Pn,boundingBoxGeohashes as Un,haversineMeters as Gn,pointInBoundingBox as On}from"./GEO_DEFAULT_PRECISION-CqpQZ-J_.mjs";import{NotFoundError as Hn}from"./NotFoundError-BhF7FeFr.mjs";import{softDeleteScope as de,normalizeOrderKeys as it,uniqueIndexFields as tn,equalityPinnedFields as Nn,buildSeekWhere as nn,decodeCursor as st,applySelect as bt,encodeCursor as ct,tiebreakDirectionFor as on,buildSeekBeforeWhere as jn}from"./CURSOR_PREFIX-Bn8SFoGd.mjs";import{rankTableName as Mt,sortColumnName as Dt,resolveRankPartition as Kn,encodePartitionKey as Qn,RANK_TIEBREAK as Vn,rankPivotConditionSql as zn}from"./RANK_TIEBREAK-D5xNdzB3.mjs";import{UNVOUCHABLE_DEP as kt}from"./UNVOUCHABLE_DEP-C68htACn.mjs";import{indexKeysForRow as Jn,buildIndexRange as Yn}from"./buildIndexRange-DvN8Qj8e.mjs";import{deriveRelationEdges as Xn,findRelated as Zn}from"./RELATED_DEFAULT_LIMIT-B9PH28Pn.mjs";import{assertFlatPredicate as tt,resolveRelationPredicates as Lt}from"./DEFAULT_MAX_RELATION_KEYS-XESc7TiB.mjs";import{runRowValidators as nt,resolveWith as Ft,relationHooks as qt,applyOnDelete as eo,fanOutScalarCounts as to}from"./applyOnDelete-7JZ4vR9r.mjs";import{guardWriter as no}from"./RLS_UNWRAP_SYMBOL-BwwTbz3Q.mjs";import{quoteIdentifier as Re}from"./quoteIdentifier-CObIFRhb.mjs";import{m as oo}from"./sql-projection-D3qdaItY.mjs";import{createSystemReader as ro}from"./createSystemReader-DcDLFfC-.mjs";import{ConflictError as me}from"./ConflictError-C8GtJmjS.mjs";import{runTriggers as io}from"./hasTrigger-CjlwI4le.mjs";import{c as te,t as He,r as Oe,j as Se,i as Bt}from"./where-sql-x1YKldcq.mjs";import{CLIENT_WATERMARK_TABLE as ci,advanceClientWatermark as ai,migrateClientWatermark as di,readClientWatermark as li}from"./CLIENT_WATERMARK_TABLE-CRnrAnJ2.mjs";import{GLOBAL_SHAPE_SNAPSHOT_TABLE as fi,deleteGlobalShapeSnapshot as hi,deleteGlobalShapeSnapshotsForConnection as wi,migrateGlobalShapeSnapshot as pi,readGlobalShapeSnapshot as gi,writeGlobalShapeSnapshot as $i}from"./GLOBAL_SHAPE_SNAPSHOT_TABLE-DSA6mzyx.mjs";import{IDEMPOTENCY_TABLE as Ei,readIdempotent as mi,trimIdempotent as Si,writeIdempotent as _i}from"./IDEMPOTENCY_TABLE-DOpm_oMF.mjs";import{runShardMigrations as Ti}from"./runShardMigrations-DGlaC68E.mjs";import{S as Ai}from"./ctx-db-search-state-ruTuCsxa.mjs";import{selectShapeMembers as Ci,selectShapeRows as xi}from"./selectShapeMembers-B8gTOeOB.mjs";import{serializeSqlValue as oe}from"./serializeSqlValue-BEMMYX1n.mjs";const so=n=>{const r=atob(n),o=Uint8Array.from(r,a=>a.codePointAt(0)??0);return new TextDecoder().decode(o)},co=()=>new $("BAD_REQUEST","invalid cursor"),Wt=16,Pt=8,Y=1024,ut=(n,r)=>r.query(n),ao=(n,r)=>{if(n.length===0)return 0;let o=0;for(const[a,s]of r.entries()){const w=a===r.length-1;let y=0;for(const R of n)(w?R.startsWith(s):R===s)&&(y+=1);if(y===0)return 0;o+=y}return o},lo=(n,r)=>{if(!r)return{exact:!0,lower:n,upper:n};const o=[...n].at(-1)??"",a=(o.codePointAt(0)??0)+1;if(a>=55296&&a<=57343||a>1114111)return{exact:!0,lower:n,upper:n};const s=n.slice(0,n.length-o.length);return{exact:!1,lower:n,upper:s+String.fromCodePoint(a)}},uo=(n,r,o)=>{const a={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 "${r}"`);if(n.filters.length>=Pt)throw new $("BAD_REQUEST",`search index "${n.indexName}" on table "${r}": at most ${String(Pt)} .eq() filters are supported per search query`);return n.filters.push({field:s,value:w}),a},search:(s,w)=>{const y=n;if(s!==y.definition.field)throw new $("INTERNAL",`search index "${y.indexName}" on table "${r}" indexes "${y.definition.field}", not "${s}"`);const R=ut(w,o).length;if(R>Wt)throw new $("BAD_REQUEST",`search index "${y.indexName}" on table "${r}": at most ${String(Wt)} search terms are supported (got ${String(R)})`);return y.field=s,y.query=w,y.hasQuery=!0,a}};return a},fo=n=>{if(n.length>Y)throw new $("BAD_REQUEST",`more than ${String(Y)} documents match this search — narrow it with filters or read it a page at a time with .paginate()`)},ho=n=>Math.min(n.offset+n.numItems+1,Y),wo=n=>btoa(`search:${String(n)}`),po=n=>{let r;try{r=so(n)}catch{return}if(!r.startsWith("search:"))return;const o=Number(r.slice(7));return Number.isInteger(o)&&o>=0?o:void 0},go=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 r=Math.max(0,Math.floor(n.numItems)),o=n.cursor?po(n.cursor):0;if(o===void 0)throw co();if(o+r>=Y)throw new $("BAD_REQUEST",`search pagination reaches the ${String(Y)}-document limit (offset ${String(o)} + ${String(r)} requested) — a page must end below the cap so the probe row that answers \`hasMore\` still fits: retry with numItems ${String(Math.max(1,Y-o-1))} or fewer, or narrow the query or the filters instead`);return{numItems:r,offset:o}},$o=(n,r)=>{const o=r.offset+r.numItems,a=r.numItems>0&&n.length>o;return{continueCursor:a?wo(o):null,isDone:!a,page:n.slice(r.offset,o)}},yo=n=>{if(n===void 0)return Y+1;if(!Number.isFinite(n))return Y;const r=Math.max(0,Math.floor(n));if(r>Y)throw new $("BAD_REQUEST",`search returns at most ${String(Y)} documents (asked for ${String(r)}) — narrow the query or paginate instead`);return r},Ne=n=>{const r=new Map;return o=>{const a=r.get(o);if(a!==void 0)return a;const s=n(Re(o));return r.set(o,s),s}},ue=Re(ne),Eo=Ne(n=>`INSERT INTO ${n} (id, _creationTime, ${ue}) VALUES (?, ?, ?)`),Ut=Ne(n=>`UPDATE ${n} SET ${ue} = ? WHERE id = ? AND ${ue} = ?`),mo=Ne(n=>`UPDATE ${n} SET _creationTime = ?, ${ue} = ? WHERE id = ? AND ${ue} = ?`),So=Ne(n=>`DELETE FROM ${n} WHERE id = ? AND ${ue} = ?`),_o="SELECT changes() AS changed",Gt=new Map,Ro="",To=n=>{const r=JSON.stringify(n),o=Gt.get(r);if(o!==void 0)return o;const a=n.map(w=>i`SELECT ${i.raw(`'${w.replaceAll("'","''")}'`)} AS __t__, id, _creationTime, ${i.identifier(ne)} FROM ${i.identifier(w)} WHERE id = ${Ro}`),{sql:s}=Zt("sqlite",i`${lt(a)} LIMIT 1`);return Gt.set(r,s),s},vo=(n,r)=>r.map(()=>n),Ao=/^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/iu,Io=n=>{if(!Ao.test(n))throw new $("INTERNAL",`invalid clientId ${JSON.stringify(n)}: a client-supplied row id must be a UUID`)},Ot=50,rn=500,Pe=Math.floor(en.boundParams/3),ye=en.boundParams,Co=128,ae=(n,r,o)=>{const a=r??rn;if(n>a)throw new $("BATCH_LIMIT_EXCEEDED",`${o}: batch of ${String(n)} exceeds the limit of ${String(a)} (raise options.limit or chunk the call)`,{status:400})},xo=n=>{const r={eq:(o,a)=>(n.sqlConditions.push({comparator:"=",field:o,value:a}),r),gt:(o,a)=>(n.sqlConditions.push({comparator:">",field:o,value:a}),r),gte:(o,a)=>(n.sqlConditions.push({comparator:">=",field:o,value:a}),r),lt:(o,a)=>(n.sqlConditions.push({comparator:"<",field:o,value:a}),r),lte:(o,a)=>(n.sqlConditions.push({comparator:"<=",field:o,value:a}),r)};return r},bo=n=>Math.max(n,Y),sn=(n,r)=>{const o=n.filters.map(a=>i`${X(a.field)} = ${oe(a.value)}`);return r&&o.push(r),o},Mo=(n,r,o,a,s)=>{const w=ut(o.query,dt(o.definition.language));if(w.length===0)return[];const y=Sn(r,o.indexName),R=`${y}__vocab`,_=w.length-1,k=w.map((q,F)=>{const W=lo(q,F===_),x=W.exact?i`${i.identifier("term")} = ${W.lower}`:i`${i.identifier("term")} >= ${W.lower} AND ${i.identifier("term")} < ${W.upper}`;return i`SELECT ${i.identifier("doc")}, ${i.raw(String(F))} AS ${i.identifier("__term__")}, COUNT(*) AS ${i.identifier("__n__")} FROM ${i.identifier(R)} WHERE ${x} GROUP BY ${i.identifier("doc")}`}),g=w.map((q,F)=>i`SUM(CASE WHEN u.${i.identifier("__term__")} = ${i.raw(String(F))} THEN u.${i.identifier("__n__")} ELSE 0 END)`),v=i`SELECT f.${i.identifier(Fe)} AS ${i.identifier(Fe)}, ${i.join(g,i` + `)} AS ${i.identifier("__score__")} FROM (${lt(k)}) u JOIN ${i.identifier(y)} f ON f.rowid = u.${i.identifier("doc")} GROUP BY f.${i.identifier(Fe)} HAVING ${i.join(g.map(q=>i`${q} > 0`),i` AND `)}`,T=sn(o,s);let L=i`SELECT m.id, m._creationTime, m.${i.identifier(ne)}, s.${i.identifier("__score__")} AS ${i.identifier("__score__")} FROM (${v}) s JOIN ${i.identifier(r)} m ON m.id = s.${i.identifier(Fe)}`;T.length>0&&(L=i`${L} WHERE ${i.join(T,i` AND `)}`),L=i`${L} ORDER BY s.${i.identifier("__score__")} DESC, m._creationTime DESC, m.id ASC LIMIT ${i.raw(String(a))}`;const H=[];for(const q of N(n,L)){const F=Xt(q);if(F){const W=q.__score__;H.push({document:F,score:typeof W=="number"?W:Number(W??0)})}}return H},Do=(n,r,o,a,s)=>{const w=dt(o.definition.language),y=ut(o.query,w);if(y.length===0)return[];const R=sn(o,s);let _=i`SELECT id, _creationTime, ${i.identifier(ne)} FROM ${i.identifier(r)}`;R.length>0&&(_=i`${_} WHERE ${i.join(R,i` AND `)}`),_=i`${_} ORDER BY _creationTime DESC, id ASC LIMIT ${i.raw(String(bo(a)))}`;const k=N(n,_).toArray(),g=[];for(const v of k){const T=Xt(v);if(!T)continue;const L=ao(_n(T,o.definition),y);L>0&&g.push({creationTime:typeof T._creationTime=="number"?T._creationTime:0,doc:T,id:typeof T._id=="string"?T._id:"",score:L})}return g.sort((v,T)=>T.score-v.score||T.creationTime-v.creationTime||v.id.localeCompare(T.id)),g.slice(0,a).map(v=>({document:v.doc,score:v.score}))},ot=(n,r,o,a)=>{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 "${a}" on table "${o}": ${r} must have a finite lat in [-90, 90] and lng in [-180, 180]`)},ko=(n,r)=>{const o=n,a={near:(s,w)=>{if(o.within)throw new $("INTERNAL",`geo index "${o.indexName}" on table "${r}": call .near() or .within(), not both`);if(ot(s,".near() point",r,o.indexName),!Number.isFinite(w)||w<=0)throw new $("BAD_REQUEST",`geo index "${o.indexName}" on table "${r}": .near() radiusMeters must be a finite number > 0, got ${String(w)}`);return o.near={point:{lat:s.lat,lng:s.lng},radiusMeters:w},a},within:s=>{if(o.near)throw new $("INTERNAL",`geo index "${o.indexName}" on table "${r}": call .near() or .within(), not both`);if(ot(s.sw,".within() sw corner",r,o.indexName),ot(s.ne,".within() ne corner",r,o.indexName),s.sw.lat>s.ne.lat)throw new $("BAD_REQUEST",`geo index "${o.indexName}" on table "${r}": .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 "${r}": .within() box crosses the antimeridian (sw.lng > ne.lng), which is not supported — split it into two boxes at ±180 and union the results`);return o.within={ne:{lat:s.ne.lat,lng:s.ne.lng},sw:{lat:s.sw.lat,lng:s.sw.lng}},a}};return a},Lo=(n,r)=>{const o=n[r];if(o===null||typeof o!="object")return;const{lat:a,lng:s}=o;return typeof a=="number"&&typeof s=="number"?{lat:a,lng:s}:void 0},Fo=(n,r)=>{const o=Lo(n,r.definition.field);if(!o)return;const a=typeof n._creationTime=="number"?n._creationTime:0;if(r.near){const s=Gn(r.near.point,o);return s<=r.near.radiusMeters?{creationTime:a,distance:s}:void 0}return On(o,r.within)?{creationTime:a,distance:0}:void 0},qo=(n,r,o,a)=>{if(!o.near&&!o.within)throw new $("INTERNAL",`geo index "${o.indexName}" on table "${r}": call .near(point, radius) or .within(box)`);const s=o.near?Pn(o.near.point,o.near.radiusMeters):Un(o.within),w=Bn(r,o.indexName),y=s.map(v=>i`(g.${i.identifier("__geohash__")} >= ${v} AND g.${i.identifier("__geohash__")} < ${`${v}{`})`),R=[i`(${i.join(y,i` OR `)})`];a&&R.push(a);const _=i`SELECT m.id, m._creationTime, m.${i.identifier(ne)} FROM ${i.identifier(w)} g JOIN ${i.identifier(r)} m ON m.id = g.${i.identifier("__id__")} WHERE ${i.join(R,i` AND `)}`,k=N(n,_).toArray(),g=[];for(const v of k){const T=le(v),L=T?Fo(T,o):void 0;T&&L&&g.push({creationTime:L.creationTime,distance:L.distance,doc:T})}return g.sort((v,T)=>v.distance-T.distance||T.creationTime-v.creationTime),g},cn=(n,r,o,a)=>{const s=[];for(const w of n)if(r.every(y=>y(a(w)))&&(s.push(w),typeof o=="number"&&s.length>=o))break;return s},Bo=(n,r,o,a,s,w=()=>{})=>{const y=o.within!==void 0,R=qo(n,r,o,s).map(_=>({distanceMeters:y?null:_.distance,document:_.doc}));return w(R.length),typeof a=="number"?R.slice(0,Math.max(0,Math.floor(a))):R},an=(n,r,o,a,s,w=()=>{})=>{const{geo:y}=o;if(!y)throw new $("INTERNAL","runGeoTerminalScored called without a staged geo query");const R=o.inMemoryFilters.length>0,_=Bo(n,r,y,R?void 0:s,a,w);return R?cn(_,o.inMemoryFilters,s,k=>k.document):_},dn=(n,r,o,a)=>{const s=`SELECT id, _creationTime, ${Re(ne)} FROM ${Re(n)}`,w=`ORDER BY ${o}${a===void 0?"":` LIMIT ${String(a)}`}`;return r===void 0?Oe(`${s} ${w}`):Se(`${s} WHERE `,r,` ${w}`)},Wo=(n,r,o,a,s,w=()=>{})=>an(n,r,o,a,s,w).map(y=>y.document),Po=(n,r,o,a,s,w,y=()=>{})=>{const R=[];for(const v of o.sqlConditions)R.push(i`${X(v.field)} ${i.raw(v.comparator)} ${oe(v.value)}`);a&&R.push(a);let _=i`SELECT id, _creationTime, ${i.identifier(ne)} FROM ${i.identifier(r)}`;R.length>0&&(_=i`${_} WHERE ${i.join(R,i` AND `)}`),_=i`${_} ORDER BY ${s}`,typeof w=="number"&&o.inMemoryFilters.length===0&&(_=i`${_} LIMIT ${i.raw(String(Math.max(0,Math.floor(w))))}`);const k=N(n,_).toArray();y(k.length);const g=[];for(const v of k){const T=le(v);if(T&&o.inMemoryFilters.every(L=>L(T))&&(g.push(T),typeof w=="number"&&g.length>=w))break}return g},Ee={fieldRef:X,serialize:oe},ln=(n,r)=>{const o=r===void 0?void 0:n.shape[r];return o!==void 0&&oo(o)},Ht=(n,r)=>r.some(o=>ln(n,o)),Nt=(n,r,o)=>{if(ln(n,r))throw new $("BAD_REQUEST",`${o}: "${r}" may hold an order-preserving key rather than a value SQL can reduce or group — declare an aggregateIndex covering this (by, field, op) so the maintained companion answers it instead (its running total is a REAL, so it stays exact only while the total is inside 2^53)`)},ft={fieldRef:n=>Oe(Ge(n)),serialize:oe},Uo=n=>{let r=0;const o=[],a={fieldRef:s=>Oe(Ge(s)),relationExists:s=>{const{childWhere:w,negated:y,parentTable:R,relation:_}=s,k=`__rel_${String(r)}`,g=o.at(-1)??R;r+=1,n(_.table,O);const v=_.kind==="one"?_.field:_.references,T=_.kind==="one"?_.references:_.field,L=Oe(`${xt(k,T)} = ${xt(g,v)}`);o.push(k);const H=te(w,a,He);o.pop();const q=H===void 0?L:Se(L," AND ",H),F=Se("EXISTS (SELECT 1 FROM ",Bt(_.table)," AS ",Bt(k)," WHERE ",q,")");return y?Se("NOT ",F):F},serialize:oe};return a},un=n=>{const r=n.map(o=>`${Ge(o.field)} ${o.direction==="desc"?"DESC":"ASC"}`);return n.some(o=>o.field==="_id"||o.field==="id")||r.push(`${Ge("id")} ${on(n)==="desc"?"DESC":"ASC"}`),r.join(", ")},Go=n=>{const r=n.map(o=>i`${X(o.field)} ${i.raw(o.direction==="desc"?"DESC":"ASC")}`);return n.some(o=>o.field==="_id"||o.field==="id")||r.push(i`${X("id")} ${i.raw(on(n)==="desc"?"DESC":"ASC")}`),i.join(r,i`, `)},Oo={"<":"lt","<=":"lte","=":"eq",">":"gt",">=":"gte"},fn=n=>new Set(n.sqlConditions.filter(r=>r.comparator==="=").map(r=>r.field)),Ho=n=>{const r=fn(n);let o=0;for(;o<n.indexFields.length&&r.has(n.indexFields[o]??"");)o+=1;return n.indexFields.slice(o)},hn=(n,r)=>{const o=n.order,a=Ho(n),{shape:s}=r;return a.length>0?it(a.map(w=>({[w]:o})),s,{pinned:fn(n),uniqueBy:tn(r.indexes,s)}):it([{_creationTime:o}],s)},No=(n,r,o,a)=>{const s=n.sqlConditions.map(w=>({[w.field]:{[Oo[w.comparator]??"eq"]:w.value}}));if(o&&s.push(nn(r,st(o))),a&&s.push(jn(r,st(a))),s.length!==0)return s.length===1?s[0]:{AND:s}},jo=(n,r,o)=>{const a=[];for(const s of n){const w=le(s);if(w&&r.every(y=>y(w))&&(a.push(w),o!==void 0&&a.length>o))break}return a},Ko=(n,r,o,a,s,w,y=()=>{})=>{const R=Math.max(0,Math.floor(s.numItems)),_=hn(a,o),k=typeof s.endCursor=="string",g=te(No(a,_,s.cursor,s.endCursor),ft,He),v=w&&g?Se(g," AND ",w):w??g,T=a.inMemoryFilters.length>0,L=dn(r,v,un(_),T||k?void 0:R+1),H=_e(n,L.text,...L.params).toArray();y(H.length);const q=jo(H,a.inMemoryFilters,T||k?void 0:R);if(k){const j=q.length>=2?q[Math.floor(q.length/2)-1]:void 0;return{continueCursor:s.endCursor??null,isDone:!0,page:q,splitCursor:j?ct(j,_):null}}const F=q.length>R,W=F?q.slice(0,R):q,x=W.at(-1);return{continueCursor:F&&x?ct(x,_):null,isDone:!F,page:W}};class Qo extends ${constructor(r="unique() found more than one matching document"){super("NOT_UNIQUE",r,{name:"NotUniqueError"})}}const Vo=/\s/u,zo=String.fromCodePoint(0),jt=(n,r,o)=>{if(!n.tables[r])throw new $("INTERNAL",`unknown table: ${r}`);return typeof o!="string"||o.length===0||Vo.test(o)||o.includes(zo)?null:o},Jo=(n,r,o,a=()=>{},s=()=>{},w=()=>{})=>{const y=r.tables[o];if(!y)throw new $("INTERNAL",`unknown table: ${o}`);const R=de(y.softDeleteMode,void 0),_=R?te(R,Ee):void 0,k=R?te(R,ft,He):void 0,g={indexFields:[],indexName:void 0,inMemoryFilters:[],order:"asc",sqlConditions:[]};let v=0;const T=m=>{const{search:C}=g;if(!C)throw new $("INTERNAL","runSearchFetch called without a staged search");xn(n,o,y);const b=g.inMemoryFilters.length>0,M=yo(b?void 0:m),K=qn(n);if(K&&!bn(n,o,C.definition))throw new $("SEARCH_INDEX_BUILDING",`search index "${C.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 re=K?Mo(n,o,C,M,_):Do(n,o,C,M,_);return b?(v=re.length,cn(re,g.inMemoryFilters,m,Te=>Te.document)):(m===void 0&&fo(re),re)},L=m=>T(m).map(C=>C.document),H=m=>{const C=go(m);return $o(L(ho(C)),C)},q=()=>Go(hn(g,y)),F=()=>{if(g.search||g.geo||g.indexName===void 0){s(void 0);return}s(Yn(o,g.indexName,g.indexFields,g.sqlConditions,oe))},W=m=>{F();let C=0;const b=(()=>{if(g.search){const M=L(m);return C=v,M}return g.geo?Wo(n,o,g,_,m,M=>{C=M}):Po(n,o,g,_,q(),m,M=>{C=M})})();return w(Math.max(C,b.length)),b},x=()=>{if(!g.search&&!g.geo)throw new $("INTERNAL",`ctx.db.query("${o}").collectWithScores() requires a staged .withSearchIndex(...) or .withGeoIndex(...)`);F();let m=0;const C=(()=>{if(g.search){const b=T(void 0);return m=v,b}return an(n,o,g,_,void 0,b=>{m=b})})();return w(Math.max(m,C.length)),C},j={async*[Symbol.asyncIterator](){if(g.search){yield*W(void 0);return}const m=[...g.inMemoryFilters];let C;g.inMemoryFilters=[];try{for(;;){const b=await j.paginate({cursor:C??null,numItems:Co});for(const M of b.page)m.every(K=>K(M))&&(yield M);if(b.isDone||b.continueCursor===null)return;C=b.continueCursor}}finally{g.inMemoryFilters=m}},async collect(){return W(void 0)},async collectWithScores(){return x()},filter(m){return g.inMemoryFilters.push(m),j},async first(){return W(g.inMemoryFilters.length>0?void 0:1)[0]??null},order(m){return g.order=m==="desc"?"desc":"asc",j},async paginate(m){let C=0;if(F(),g.search){const M=H(m);return w(M.page.length),M}if(g.geo)throw new $("INTERNAL","pagination is not supported on geo queries; use .take(n) or .collect()");const b=Ko(n,o,y,g,m,k,M=>{C=M});return w(Math.max(C,b.page.length)),b},async take(m){return W(m)},async unique(){const m=W(g.inMemoryFilters.length>0?void 0:2);if(m.length>1)throw new Qo(`unique() on table "${o}" matched ${String(m.length)} documents; expected at most one`);return m[0]??null},withGeoIndex(m,C){const b=(y.geoIndexes??[]).find(K=>K.name===m);if(!b)throw new $("INTERNAL",`unknown geo index "${m}" on table "${o}"`);a(o,m,"geo");const M={definition:b,indexName:m};if(g.geo=M,C(ko(M,o)),!M.near&&!M.within)throw new $("INTERNAL",`geo index "${m}" on table "${o}" requires a .near(point, radius) or .within(box) call`);return j},withIndex(m,C){const b=y.indexes.find(M=>M.name===m);if(!b)throw new $("INTERNAL",`unknown index "${m}" on table "${o}"`);return a(o,m,"index"),g.indexName=m,g.indexFields=b.fields,C&&C(xo(g)),j},withSearchIndex(m,C){const b=(y.searchIndexes??[]).find(K=>K.name===m);if(!b)throw new $("INTERNAL",`unknown search index "${m}" on table "${o}"`);a(o,m,"search");const M={definition:b,field:b.field,filters:[],hasQuery:!1,indexName:m,query:""};if(g.search=M,C(uo(M,o,dt(b.language))),!M.hasQuery)throw new $("INTERNAL",`search index "${m}" on table "${o}" requires a .search(field, query) call`);return j}};return j},Kt=(n,r,o)=>{const a={...r};for(const[s,w]of Yt(n)){if(w.serverDefault){a[s]=w.serverDefault({auth:o});continue}a[s]===void 0&&(w.defaultFn?a[s]=w.defaultFn():"defaultValue"in w&&(a[s]=w.defaultValue))}return a},Qt=(n,r,o,a)=>{const s=o;for(const[w,y]of Yt(n)){if(y.serverDefault){w in r&&(s[w]=y.serverDefault({auth:a}));continue}y.onUpdateFn&&!(w in r)&&(s[w]=y.onUpdateFn())}},Vt=(n,r)=>{for(const o of Object.keys(r))if(r[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.`)},zt=["_commitSeq","_creationTime","_id"],rt=n=>zt.some(r=>r in n)?Object.fromEntries(Object.entries(n).filter(([r])=>!zt.includes(r))):n,Yo=/unique constraint failed/i,Xo=n=>n instanceof Error&&Yo.test(n.message),Zo=/string or blob too big/iu,er=(n,r)=>{if(!(!(n instanceof Error)||!Zo.test(n.message)))throw new $("PAYLOAD_TOO_LARGE",`document is too large to store in "${r}": a single row cannot exceed the storage engine's per-row ceiling (2 MB on a Durable Object's SQLite). The limit is on the STORED bytes, which are UTF-8, and v.bytes()/v.bigint() columns are stored twice on a shard-local table. Keep the payload in R2 (ctx.storage) and store a reference on the row.`)},at=(n,r,o,a)=>{try{_e(n,o,...a)}catch(s){throw Xo(s)?new me(`unique constraint violation on "${r}"`,"unique"):(er(s,r),s)}},Ue=(n,r,o,a)=>{if(at(n,r,o,a),_e(n,_o).one().changed===0)throw new me(`optimistic concurrency conflict on "${r}" — the row changed during this mutation; refetch and retry`,"occ")},Jt=(n,r,o,a,s,w,y)=>{const R=[];for(let v=0;v<o.length+1;v+=1){const T=o[v],L=a[v],H=L?.direction==="desc"?"desc":"asc",q=T===void 0||L===void 0?i`${i.identifier(Vn)} < ${y}`:zn(T,w[v],H,!1);if(q===void 0)continue;const F=[];for(let x=0;x<v;x+=1)F.push(i`${i.identifier(o[x])} IS ${w[x]}`);F.push(q);const[W]=F;R.push(F.length===1&&W!==void 0?W:i`(${i.join(F,i` AND `)})`)}const _=R.length>0?i.join(R,i` OR `):i`1 = 0`,k=N(n,i`SELECT COUNT(*) AS c FROM ${i.identifier(r)} WHERE ${i.identifier("__partition__")} = ${s} AND (${_})`).one(),g=N(n,i`SELECT COUNT(*) AS c FROM ${i.identifier(r)} WHERE ${i.identifier("__partition__")} = ${s}`).one();return{before:k.c,total:g.c}},qr=n=>{const{baselineSeq:r,onStalePatchDropped:o}=n,{sql:a}=n,{schema:s}=n,w=n.broadcast??(()=>{}),y=Xn(s);let R;const _=()=>n.inTransaction?.()===!0,k=e=>s.tables[e]?.commitOrderedMode!==!0?{}:((R===void 0||!_())&&(R=kn(a)),{[Ln]:R}),g=(e,...t)=>{const c=s.tables[e]?.indexes;if(!c||c.length===0)return;const f=[];for(const h of t)h&&f.push(...Jn(c,h,oe));return f.length>0?f:void 0},{headroom:v}=n;let T=!1;const L=async e=>{const t=T;T=!0;try{return await e()}finally{T=t}},H=n.onRead??(()=>{}),q=e=>{It(s.tables[e])&&H(kt,kt)},F=n.onReadRange??(e=>{H(e.table,O)}),W=e=>{q(e.table),F(e)},x=(e,t)=>{t!==void 0&&t!==O&&!T&&v?.recordRead(1),q(e),H(e,t)},j=n.onIndexUse??(()=>{}),m=n.onWrite??(()=>{}),C=e=>{T||v?.recordWrite(e)},b=async e=>{C(e.doc),await m(e)},{cache:M}=n,K=n.clock??(()=>Date.now()),re=n.idGenerator??(()=>crypto.randomUUID()),Te=n.scheduler??Tn,{globalDb:fe}=n,ve=n.auth??{identity:null,userId:null},ht=n.cdc??!1,je=Te,wn=ro({scheduler:typeof je.list=="function"&&typeof je.get=="function"?je:void 0,storage:n.storage}),he=(e,t,c,f)=>{ht&&!It(s.tables[e])&&Mn(a,K(),e,t,c,f)},pn=(e,t,c,f)=>{if(s.tables[e]?.dropStalePatchesMode!==!0||!ht)return!1;const h=r?.();if(h===void 0)return!1;const l=Dn(a,e,t,h);return l===void 0?!1:Object.keys(rt(c)).some(d=>At(l[d])!==At(f[d]))},ie=e=>s.tables[e]?.shardMode?.kind==="global",wt=(e,t)=>{if(ie(e)){if(!fe)throw new $("INTERNAL",`cross-backend ${t} for global table '${e}' requires a globalDb writer — pass one to createShardCtxDb({ globalDb })`);return fe}return U},Ke=e=>wt(e,"cascade"),V=(e,t)=>{if(ie(e)){if(!fe)throw new $("INTERNAL",`${t} on global table '${e}' requires a globalDb writer — pass one to createShardCtxDb({ globalDb })`);return fe}},pt=async(e,t,c,f,h)=>{h&&C(c);const l=await e.insert(t,c,f);return w({key:l,op:"insert",row:{...c,_id:l},table:t}),l},Qe=(e,t)=>wt(e,"relation load").findMany(e,t),gt=(e,t)=>(ie(e)&&x(e,O),Qe(e,t)),gn=e=>!ie(e.table),$t=n.relationExistsPushDown??"auto",yt=$t!=="never",{maxRelationKeys:Et}=n,Ae=(e,t,c)=>Lt(e,{fetcher:gt,maxRelationKeys:Et,relationBaseWhere:c,schema:s,tableName:t}),mt=async(e,t,c,f)=>{const h=V(e,"relation grouped count");if(h)return x(e,O),to((P,I)=>h.count(P,I),e,t,c,f);const l=s.tables[e];if(!l)throw new $("INTERNAL",`unknown table: ${e}`);x(e,O);const d=de(l.softDeleteMode,void 0),u={[t]:{in:c}},p=z(z(u,f),d),A=await Ae(p,e,void 0),E=te(A,Ee),D=X(t);let S=i`SELECT ${D} AS __fk__, COUNT(*) AS count FROM ${i.identifier(e)}`;E&&(S=i`${S} WHERE ${E}`),S=i`${S} GROUP BY ${D}`;const B=N(a,S).toArray();return new Map(B.map(P=>[P.__fk__,P.count]))};let Ie=0;const St=new Set;for(const[e,t]of Object.entries(s.tables))for(const c of Object.values(t.triggerMap??{}))St.add(`${e} ${c.timing} ${c.op}`);const Z=(e,t,c)=>St.has(`${e} ${t} ${c}`),ee=async(e,t,c)=>{if(Ie+=1,Ie>Ot)throw Ie-=1,new me(`trigger recursion exceeded ${String(Ot)} levels on "${c.table}" — check for a self-triggering write`,"trigger");try{await io({ctx:yn,event:c,op:t,schema:s,tableName:c.table,timing:e})}finally{Ie-=1}},{ensureBackfilledForTable:we,ensureBackfilledIndex:Ve,ensureRankBackfilled:ze,ensureRankBackfilledForTable:pe,syncAggregates:Ce,syncCompanionsForInsert:_t,syncGeo:xe,syncRanks:ge,syncSearch:be}=mn({broadcast:w,indexKeysFor:(e,t)=>g(e,t),invalidateCache:(e,t,c)=>M?.invalidate(e,t,g(e,c)),recordCdc:he,schema:s,sql:a}),Rt=(e,t,c)=>{const{shardMode:f}=t;if(f?.kind==="shardBy"&&!(f.field!==void 0&&(c.partitionBy??[]).includes(f.field)))throw Object.assign(new Error(`rank index "${c.name}" on "${e}" partitions across shards (shard key "${f.field??"?"}" is not in partitionBy) — a shard-local rank()/rankPage() would be wrong; roll it up through the Query Coordinator instead`),{code:"CROSS_SHARD_RANK_UNSUPPORTED",name:"LunoraError",status:400})},Tt=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)?fe:void 0,se=(e,t)=>{const c=Tt(t);for(let f=0;f<c.length;f+=ye){const h=c.slice(f,f+ye),[l]=_e(a,To(h),...vo(e,h)).toArray();if(!l)continue;const d=l.__t__,u=le(l);if(typeof d!="string"||!u)return;const p=l[ne];return{docJson:typeof p=="string"?p:ce(p??{}),row:u,tableName:d}}},$n=(e,t)=>{const c=[...new Set(e)],f=new Map;if(c.length===0)return f;const h=Tt(t);for(let l=0;l<h.length;l+=ye){const d=h.slice(l,l+ye),u=Math.floor(ye/d.length),p=Wn(i`${i.identifier("id")}`,c,!1,u),A=d.map(E=>i`SELECT ${i.raw(`'${E.replaceAll("'","''")}'`)} AS __t__, id FROM ${i.identifier(E)} WHERE ${p}`);for(const E of N(a,lt(A))){const{id:D,__t__:S}=E;typeof S=="string"&&typeof D=="string"&&f.set(D,S)}}return f},vt={assertRankPartitionLocal:Rt,ensureRankBackfilled:ze,onRead:x,rowToDocument:le,schema:s,sql:a},U={system:wn,async aggregate(e,t){const c=V(e,"aggregate");if(c)return x(e,O),c.aggregate(e,t);const f=s.tables[e];if(!f)throw new $("INTERNAL",`unknown table: ${e}`);if(qe(t.op),t.op==="count")return U.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`);x(e,O);const h=de(f.softDeleteMode,void 0),l=z(z(t.baseWhere,t.where),h),d=await Ae(l,e,t.relationBaseWhere),u=d!==l;if(f.aggregateIndexes&&!t.baseWhere&&!u&&(!h||Ht(f,[t.field]))){const P=Cn(f.aggregateIndexes,t.op,t.field,t.where);if(P){Ve(e,P.index);const I=Ye(P.index.by??[],P.key),Q=Je(e,P.index.name),J=N(a,i`SELECT ${Be} AS value, ${et} AS count FROM ${i.identifier(Q)} WHERE ${We} = ${I}`).toArray()[0];return Xe(t.op,J)}}Nt(f,t.field,`aggregate(${e}, { op: "${t.op}", field: "${t.field}" })`);const p=te(d,Ee),A=qe(t.op),E=X(t.field);let D=i`SELECT ${i.raw(A)}(${E}) AS value FROM ${i.identifier(e)}`;p&&(D=i`${D} WHERE ${p}`);const B=N(a,D).toArray()[0]?.value;return B??null},asId(e,t){const c=jt(s,e,t);if(c===null)throw new $("BAD_REQUEST",`asId("${e}", …): "${t}" is not a valid id for table "${e}"`,{status:400});return c},async count(e,t){const c=V(e,"count");if(c)return x(e,O),c.count(e,t);const f=s.tables[e];if(!f)throw new $("INTERNAL",`unknown table: ${e}`);const h=vn(t);if(h.restrictsCounts)throw new Ze(e);x(e,O);const l=de(f.softDeleteMode,void 0),d=z(z(h.baseWhere,h.where),l),u=await Ae(d,e,h.relationBaseWhere),p=u!==d;if(f.aggregateIndexes&&!h.baseWhere&&!p&&!l){const S=In(f.aggregateIndexes,h.where);if(S){Ve(e,S.index);const B=Ye(S.index.by??[],S.key),P=Je(e,S.index.name),I=N(a,i`SELECT ${Be} AS value FROM ${i.identifier(P)} WHERE ${We} = ${B}`).toArray();return I[0]===void 0?0:I[0].value??0}}const A=te(u,Ee);let E=i`SELECT COUNT(*) AS count FROM ${i.identifier(e)}`;return A&&(E=i`${E} WHERE ${A}`),N(a,E).one().count},async delete(e,t,c){const f=se(e,t);if(!f){const E=$e(t);E&&(C(void 0),await E.delete(e,t,c));return}const{docJson:h,row:l,tableName:d}=f,u=s.tables[d],p=c?.hard===!0,A=!p&&u?.softDeleteMode?u.softDeleteMode.field:void 0;if(!(A&&l[A]!==null&&l[A]!==void 0)){if(Z(d,"before","delete")&&await ee("before","delete",{id:e,op:"delete",previous:l,table:d}),await eo({deletedId:e,deletedReference:E=>l[E],findHolders:async(E,D,S)=>(await Ke(E).findMany(E,{includeDeleted:p,where:{[D]:S}})).page,onCascade:(E,D)=>Ke(E).delete(D,void 0,c),onRestrict:E=>{throw new me(E,"restrict")},onSetNull:(E,D,S)=>Ke(E).patch(D,{[S]:null}),schema:s,tableName:d}),we(d),pe(d),A){const E={...l,...k(d),[A]:K(),_id:e};Ue(a,d,Ut(d),[ce(E),e,h]),be(d,e,E,l),xe(d,e,void 0),Ce(d,l,E),ge(d,e,l,void 0),M?.invalidate(d,e,g(d,l,E)),he(d,e,"update",E),w({indexKeys:g(d,l,E),key:e,op:"update",row:E,table:d}),Z(d,"after","delete")&&await ee("after","delete",{id:e,op:"delete",previous:l,table:d}),await b({id:e,op:"delete",table:d});return}Ue(a,d,So(d),[e,h]),be(d,e,void 0),xe(d,e,void 0),Ce(d,l,void 0),ge(d,e,l,void 0),M?.invalidate(d,e,g(d,l)),he(d,e,"delete"),w({indexKeys:g(d,l),key:e,op:"delete",table:d}),Z(d,"after","delete")&&await ee("after","delete",{id:e,op:"delete",previous:l,table:d}),await b({id:e,op:"delete",table:d})}},async deleteAll(e,t){if(!s.tables[e])throw new $("INTERNAL",`unknown table: ${e}`);const c=Math.max(1,t?.chunkSize??rn),f=t?.hard===void 0?void 0:{hard:t.hard},h=ie(e)?void 0:e;let l=0;return await L(async()=>{for(;;){const u=(await U.findMany(e,{limit:c})).page.map(p=>String(p._id));if(u.length===0)break;for(const p of u)await U.delete(p,h,f),l+=1;if(u.length<c)break}}),{deleted:l}},async deleteMany(e,t,c){ae(e.length,t?.limit,"deleteMany");for(const f of e)await U.delete(f,c);return{deleted:e.length}},async deleteWhere(e,t,c){const l=(await(V(e,"deleteWhere")??U).findMany(e,{where:t})).page.map(d=>String(d._id));if(ae(l.length,c?.limit,"deleteWhere"),U.deleteMany===void 0)throw new $("INTERNAL",`ctx.db.${e}.deleteMany is unavailable: this writer has no batch delete`);return U.deleteMany(l,c)},async findFirst(e,t={}){return(await U.findMany(e,{...t,limit:1,omitContinueCursor:!0})).page[0]??null},async findFirstOrThrow(e,t={}){const c=await U.findFirst(e,t);if(c===null)throw new Hn(`findFirstOrThrow: no "${e}" document matched`);return c},async findMany(e,t={}){const c=V(e,"findMany");if(c)return x(e,O),c.findMany(e,t);const f=s.tables[e];if(!f)throw new $("INTERNAL",`unknown table: ${e}`);const h=!t.where&&!t.baseWhere;h?x(e,O):x(e);const l=it(t.orderBy,f.shape,{pinned:Nn(t.where),uniqueBy:tn(f.indexes,f.shape)}),d=t.cursor?nn(l,st(t.cursor)):void 0;let u=z(t.baseWhere,t.where);u=z(u,de(f.softDeleteMode,t.includeDeleted)),u=await Lt(u,{canPushExists:yt?gn:void 0,existsPushMode:$t==="always"?"always":"auto",fetcher:gt,maxRelationKeys:Et,relationBaseWhere:t.relationBaseWhere,schema:s,tableName:e}),d&&(u=u?{AND:[u,d]}:d);const p=yt?Uo(x):ft,A=te(u,p,He),E=typeof t.limit=="number"?Math.max(0,Math.floor(t.limit)):void 0,D=dn(e,A,un(l),E===void 0?void 0:E+1),S=_e(a,D.text,...D.params).toArray();h&&!T&&v?.recordRead(S.length);const B=[];for(const J of S){const G=le(J);G&&(B.push(G),!h&&typeof G._id=="string"&&x(e,G._id))}if(E===void 0)return t.with&&await Ft({groupedCounter:mt,fetcher:Qe,parents:B,...qt(t),schema:s,tableName:e,with:t.with}),{continueCursor:null,isDone:!0,page:bt(B,t.select,t.with)};const P=B.length>E,I=P?B.slice(0,E):B,Q=I.at(-1);return t.with&&await Ft({fetcher:Qe,groupedCounter:mt,parents:I,...qt(t),schema:s,tableName:e,with:t.with}),{continueCursor:P&&Q&&t.omitContinueCursor!==!0?ct(Q,l):null,isDone:!P,page:bt(I,t.select,t.with)}},async get(e,t){const c=se(e,t);if(!c){const f=$e(t);return f?f.get(e,t):null}return x(c.tableName,e),c.row},async lookupById(e,t){const c=se(e,t);return c?(x(c.tableName,e),{row:c.row,tableName:c.tableName}):null},async groupBy(e,t){const c=V(e,"groupBy");if(c)return x(e,O),c.groupBy(e,t);const f=s.tables[e];if(!f)throw new $("INTERNAL",`unknown table: ${e}`);x(e,O);const h=t.agg??{op:"count"};if(qe(h.op),h.op!=="count"&&!h.field)throw new $("INTERNAL",`groupBy(${e}, { agg: { op: "${h.op}" } }): "field" is required for non-count reducers`);const l=de(f.softDeleteMode,void 0),d=z(z(t.baseWhere,t.where),l),u=await Ae(d,e,t.relationBaseWhere),p=u!==d,A=[...t.by,h.field];if(f.aggregateIndexes&&!t.baseWhere&&!p&&(!l||Ht(f,A))){const I=An(f.aggregateIndexes,h.op,h.field,t.by,t.where),Q=I===void 0?0:Object.keys(I.partial).length,J=I?.index.by?.length??0;if(I&&(Q===0||Q===J)){Ve(e,I.index);const G=Je(e,I.index.name),Me=Object.keys(I.partial),De=[];if(Me.length===(I.index.by??[]).length&&Me.length>0){const ke=Ye(I.index.by??[],I.partial),Le=N(a,i`SELECT ${Be} AS value, ${et} AS count FROM ${i.identifier(G)} WHERE ${We} = ${ke}`).toArray();return Le.length>0&&De.push({key:{...I.partial},value:Xe(h.op,Le[0])}),De}const En=N(a,i`SELECT ${We} AS key, ${Be} AS value, ${et} AS count FROM ${i.identifier(G)}`).toArray();for(const ke of En){const Le=Rn(JSON.parse(ke.key));De.push({key:Le,value:Xe(h.op,ke)})}return De}}for(const I of A){if(I===void 0)continue;const Q=I===h.field?`groupBy(${e}, { agg: { op: "${h.op}", field: "${I}" } })`:`groupBy(${e}, { by: [..."${I}"] })`;Nt(f,I,Q)}const E=te(u,Ee),D=t.by.map(I=>i`${X(I)} AS ${i.identifier(I)}`);if(h.op==="count")D.push(i`COUNT(*) AS value`);else{const{field:I}=h;if(I===void 0)throw new $("INTERNAL",`groupBy(${e}, { agg: { op: "${h.op}" } }): "field" is required for non-count reducers`);D.push(i`${i.raw(qe(h.op))}(${X(I)}) AS value`)}let S=i`SELECT ${i.join(D,i`, `)} FROM ${i.identifier(e)}`;E&&(S=i`${S} WHERE ${E}`),S=i`${S} GROUP BY ${i.join(t.by.map(I=>X(I)),i`, `)}`;const B=N(a,S).toArray(),P=[];for(const I of B){const Q={};for(const G of t.by)Q[G]=Fn(f.shape[G],I[G]??null);const{value:J}=I;P.push({key:Q,value:J==null?null:Number(J)})}return P},async insert(e,t,c){const f=V(e,"insert");if(f)return pt(f,e,t,c,!0);const h=s.tables[e];if(!h)throw new $("INTERNAL",`unknown table: ${e}`);const l=Kt(h,t,ve);nt(h,l);let d;c?.clientId!==void 0?(Io(c.clientId),d=c.clientId):c?.allowExplicitId&&typeof l._id=="string"?d=l._id:d=re();const u=c?.allowExplicitId&&typeof l._creationTime=="number"?l._creationTime:K(),p={...l,...k(e),_creationTime:u,_id:d};return Z(e,"before","insert")&&await ee("before","insert",{doc:{...p},id:d,op:"insert",table:e}),we(e),pe(e),at(a,e,Eo(e),[d,u,ce(p)]),_t(e,d,p),Z(e,"after","insert")&&await ee("after","insert",{doc:p,id:d,op:"insert",table:e}),await b({doc:p,id:d,op:"insert",table:e}),d},async insertManyUnsafe(e,t,c){if(ae(t.length,c?.limit,"insertManyUnsafe"),t.length===0)return[];const f=V(e,"insert");if(f){const u=[];for(const p of t)C(p);for(const p of t){const A=await f.insert(e,p,{allowExplicitId:c?.allowExplicitId});w({key:A,op:"insert",row:{...p,_id:A},table:e}),u.push(A)}return u}const h=s.tables[e];if(!h)throw new $("INTERNAL",`unknown table: ${e}`);we(e),pe(e);const l=[];for(let u=0;u<t.length;u+=Pe)l.push(k(e));const d=t.map((u,p)=>{const A=Kt(h,u,ve),E=c?.allowExplicitId===!0&&typeof A._id=="string"?A._id:re(),D=c?.allowExplicitId===!0&&typeof A._creationTime=="number"?A._creationTime:K(),S={...A,...l[Math.floor(p/Pe)],_creationTime:D,_id:E};return{creationTime:D,document:S,id:E}});for(const u of d)C(u.document);for(let u=0;u<d.length;u+=Pe){const p=i.join(d.slice(u,u+Pe).map(E=>i`(${E.id}, ${E.creationTime}, ${ce(E.document)})`),i`, `),A=Zt("sqlite",i`INSERT INTO ${i.identifier(e)} (id, _creationTime, ${i.identifier(ne)}) VALUES ${p}`);at(a,e,A.sql,A.params)}for(const{document:u,id:p}of d)_t(e,p,u),await m({doc:u,id:p,op:"insert",table:e});return d.map(u=>u.id)},async insertMany(e,t,c){ae(t.length,c?.limit,"insertMany");const f=c?.skipDuplicates===!0,h=[],l=V(e,"insert");if(l)for(const u of t)C(u);const d=async u=>l?pt(l,e,u,void 0,!1):U.insert(e,u);for(const u of t)try{h.push(await d(u))}catch(p){if(f&&p instanceof me&&p.kind==="unique")h.push(null);else throw p}return h},normalizeId(e,t){return jt(s,e,t)},async patch(e,t,c){const f=se(e,c);if(!f){const A=$e(c);if(A){C(t),await A.patch(e,t,c);return}throw new $("NOT_FOUND",`document not found: ${e}`)}const{docJson:h,row:l,tableName:d}=f,u=s.tables[d];if(!u)throw new $("INTERNAL",`unknown table: ${d}`);if(x(d,e),Vt("patch",t),pn(d,e,t,l)){o?.({fields:Object.keys(rt(t)),id:e,table:d});return}const p={...l,...rt(t),...k(d),_id:e};Qt(u,t,p,ve),nt(u,p,!0),Z(d,"before","update")&&await ee("before","update",{doc:{...p},id:e,op:"update",previous:l,table:d}),we(d),pe(d),Ue(a,d,Ut(d),[ce(p),e,h]),be(d,e,p,l),xe(d,e,p),Ce(d,l,p),ge(d,e,l,p),M?.invalidate(d,e,g(d,l,p)),he(d,e,"update",p),w({indexKeys:g(d,l,p),key:e,op:"update",row:p,table:d}),Z(d,"after","update")&&await ee("after","update",{doc:p,id:e,op:"update",previous:l,table:d}),await b({doc:p,id:e,op:"update",table:d})},async patchMany(e,t,c){ae(e.length,t?.limit,"patchMany");for(const f of e)await U.patch(f.id,f.patch,c);return{patched:e.length}},async patchWhere(e,t,c){const l=(await(V(e,"patchWhere")??U).findMany(e,{where:t.where})).page.map(d=>({id:String(d._id),patch:t.patch}));if(ae(l.length,c?.limit,"patchWhere"),U.patchMany===void 0)throw new $("INTERNAL",`ctx.db.${e}.patchMany is unavailable: this writer has no batch patch`);return await U.patchMany(l,c),{patched:l.length}},async related(e,t){return Zn(U,y,e,t)},relationEdges:y,query(e){const t=V(e,"query");return t?(x(e,O),t.query(e)):Jo(a,s,e,j,c=>{c?W(c):x(e,O)},c=>{T||v?.recordRead(c)})},async rank(e,t,c){const f=V(e,"rank");if(f)return x(e,O),f.rank(e,t,c);j(e,t,"rank");const h=s.tables[e];if(!h)throw new $("INTERNAL",`unknown table: ${e}`);const l=h.rankIndexes?.find(G=>G.name===t);if(!l)throw new $("INTERNAL",`unknown rankIndex "${t}" on table "${e}"`);if(Rt(e,h,l),c.restrictsCounts)throw new Ze(e);x(e,O),ze(e,l);const d=typeof c.row=="string"?c.row:c.row._id;if(!d)return null;const u=Mt(e,l.name),p=l.sortBy.map((G,Me)=>Dt(Me)),A=p.map(G=>Re(G)).join(", "),E=N(a,i`SELECT ${i.identifier("__partition__")}, ${i.raw(A)} FROM ${i.identifier(u)} WHERE ${i.identifier("__id__")} = ${d}`).toArray(),[D]=E;if(D===void 0)return null;let S=D.__partition__;const B=z(c.baseWhere,c.where);tt(B,s,e,"rank");const P=Kn(l,B);if(P){const G=Qn(l.partitionBy??[],P);if(G!==S)return null;S=G}const I=p.map(G=>D[G]),{before:Q,total:J}=Jt(a,u,p,l.sortBy,S,I,d);return{position:Q+1,total:J}},async rankBefore(e,t,c){if(ie(e))throw new $("INTERNAL",`rankBefore is not supported on the global (.global()) table '${e}' — cross-shard rank cursors apply only to sharded tables`);const f=s.tables[e];if(!f)throw new $("INTERNAL",`unknown table: ${e}`);const h=f.rankIndexes?.find(p=>p.name===t);if(!h)throw new $("INTERNAL",`unknown rankIndex "${t}" on table "${e}"`);if(c.restrictsCounts)throw new Ze(e);x(e,O),ze(e,h);const l=Mt(e,h.name),d=h.sortBy.map((p,A)=>Dt(A)),u=h.sortBy.map((p,A)=>oe(c.sortValues[A]??null));return Jt(a,l,d,h.sortBy,c.partitionKey,u,c.rowId)},async rankPage(e,t,c={}){tt(z(c.baseWhere,c.where),s,e,"rankPage");const f=V(e,"rankPage");if(f)return x(e,O),f.rankPage(e,t,c);j(e,t,"rank");const{continueCursor:h,hasMore:l,rows:d}=Ct(vt,e,t,c);return{continueCursor:h,isDone:!l,page:d.map(u=>u.doc)}},async rankPageRows(e,t,c={}){tt(z(c.baseWhere,c.where),s,e,"rankPage"),j(e,t,"rank");const{directions:f,hasMore:h,rows:l}=Ct(vt,e,t,c);return{directions:f,hasMore:h,rows:l}},async restore(e,t){const c=se(e,t);if(!c){const l=$e(t);if(l?.restore){await l.restore(e,t);return}throw new $("NOT_FOUND",`document not found: ${e}`)}const f=s.tables[c.tableName]?.softDeleteMode?.field;if(!f)throw new $("INTERNAL",`ctx.db.restore: table "${c.tableName}" is not a .softDelete() table`);const h=c.row[f]!==null&&c.row[f]!==void 0;await U.patch(e,{[f]:null},t),h&&ge(c.tableName,e,void 0,c.row)},async replace(e,t,c,f){const h=se(e,c);if(!h){const B=$e(c);if(B){C(t),await B.replace(e,t,c,f);return}throw new $("NOT_FOUND",`document not found: ${e}`)}const{docJson:l,row:d,tableName:u}=h,p=s.tables[u];if(!p)throw new $("INTERNAL",`unknown table: ${u}`);Vt("replace",t);const A=f?.allowExplicitId&&typeof t._creationTime=="number"?t._creationTime:void 0,E=typeof d._creationTime=="number"?d._creationTime:void 0,D=A??E??K(),S={...t,...k(u),_creationTime:D,_id:e};Qt(p,t,S,ve),nt(p,S),Z(u,"before","update")&&await ee("before","update",{doc:{...S},id:e,op:"update",previous:d,table:u}),we(u),pe(u),Ue(a,u,mo(u),[D,ce(S),e,l]),be(u,e,S,d),xe(u,e,S),Ce(u,d,S),ge(u,e,d,S),M?.invalidate(u,e,g(u,d,S)),he(u,e,"update",S),w({indexKeys:g(u,d,S),key:e,op:"update",row:S,table:u}),Z(u,"after","update")&&await ee("after","update",{doc:S,id:e,op:"update",previous:d,table:u}),await b({doc:S,id:e,op:"update",table:u})},async wipeShard(e){const t=new Set(e?.exclude),c=e?.tables,f=Object.entries(s.tables).filter(([u,p])=>t.has(u)||c!==void 0&&!c.includes(u)?!1:p.shardMode?.kind!=="global").map(([u])=>u);if(c!==void 0){for(const u of c)if(!s.tables[u])throw new $("INTERNAL",`wipeShard: unknown table: ${u}`)}const h={};let l=0;const{deleteAll:d}=U;if(d===void 0)throw new $("INTERNAL","wipeShard: this writer has no deleteAll");for(const u of f){const p=await d(u,{...e?.chunkSize===void 0?{}:{chunkSize:e.chunkSize},hard:!0});h[u]=p.deleted,l+=p.deleted}return{deleted:l,tables:h}}},yn={db:U,scheduler:Te};return n.enforceRls===!0?no(U,s,(e,t)=>se(e,t)?.tableName,(e,t)=>$n(e,t),y):U};export{Hr as CDC_LOG_TABLE,ci as CLIENT_WATERMARK_TABLE,fi as GLOBAL_SHAPE_SNAPSHOT_TABLE,Ei as IDEMPOTENCY_TABLE,Qo as NotUniqueError,Ai as SEARCH_STATE_TABLE,ai as advanceClientWatermark,Nr as applyCdcChanges,Vt as assertNoExplicitUndefined,Io as assertValidClientId,Pr as backfillAggregateIndexes,Ur as backfillRankIndexes,Gr as backfillSearchIndexes,jr as bumpCdcEpoch,Kr as cdcCanVouchFor,Qr as cdcForkedError,Vr as cdcSeqLeavingRows,zr as cdcTouchesTables,Jr as cdcTrimmedError,Yr as compactCdcDocs,qr as createShardCtxDb,Xr as cursorBelowRetainedFloor,hi as deleteGlobalShapeSnapshot,wi as deleteGlobalShapeSnapshotsForConnection,di as migrateClientWatermark,pi as migrateGlobalShapeSnapshot,Zr as minCdcReplayableSeq,ei as minCdcSeq,jt as normalizeIdStructurally,ti as readCdcChangeKeys,ni as readCdcChanges,oi as readCdcCursor,ri as readCdcEpoch,li as readClientWatermark,gi as readGlobalShapeSnapshot,mi as readIdempotent,Ti as runShardMigrations,Ci as selectShapeMembers,xi as selectShapeRows,rt as stripReservedPatchFields,ii as trimCdcChanges,Si as trimIdempotent,$i as writeGlobalShapeSnapshot,_i as writeIdempotent};
@@ -1 +1 @@
1
- import{readCdcChangeKeys as s}from"./CDC_LOG_TABLE-CfILante.mjs";import{selectShapeMembers as h}from"./selectShapeMembers-B8gTOeOB.mjs";import{shapeRangeKey as u}from"./ShapeDiffCache-gdaILV5E.mjs";import{projectColumns as g}from"./buildPokeFrames-BBE6J91z.mjs";const C=(m,e,a,i,p,f=s)=>{const r=u(e.table,a,i),n=p.changedKeys(r,()=>f(m,e.table,a,i));if(n.length===0)return[];const b=p.members(e,r,()=>h(m,e.table,e.effectiveWhere,n.map(t=>t.id))),o=[];for(const t of n){const c=b.get(t.id);if(c===void 0){t.op!=="insert"&&o.push({key:t.id,op:"delete",table:e.table});continue}o.push({key:t.id,op:t.op,table:e.table,value:g(c,e.columns)})}return o};export{C as buildShapeDiff};
1
+ import{readCdcChangeKeys as s}from"./CDC_LOG_TABLE-DXEAcmsr.mjs";import{selectShapeMembers as h}from"./selectShapeMembers-B8gTOeOB.mjs";import{shapeRangeKey as u}from"./ShapeDiffCache-gdaILV5E.mjs";import{projectColumns as g}from"./buildPokeFrames-BBE6J91z.mjs";const C=(m,e,a,i,p,f=s)=>{const r=u(e.table,a,i),n=p.changedKeys(r,()=>f(m,e.table,a,i));if(n.length===0)return[];const b=p.members(e,r,()=>h(m,e.table,e.effectiveWhere,n.map(t=>t.id))),o=[];for(const t of n){const c=b.get(t.id);if(c===void 0){t.op!=="insert"&&o.push({key:t.id,op:"delete",table:e.table});continue}o.push({key:t.id,op:t.op,table:e.table,value:g(c,e.columns)})}return o};export{C as buildShapeDiff};
@@ -1,4 +1,4 @@
1
- import{d as p,e as S}from"./wire-codec-C-FpWm52.mjs";import{cursorBelowRetainedFloor as y}from"./CDC_LOG_TABLE-CfILante.mjs";import{envPositiveInt as v}from"./envOptionalPositiveInt-D2pY-c64.mjs";import{v as A,R as g,s as N,a as E,b as T}from"./sibling-channel-BkL5cTCc.mjs";const L=["wnam","enam","sam","weur","eeur","apac","apac-ne","apac-se","oc","afr","me"],O=new Set(L),b=s=>typeof s=="string"&&O.has(s),h="::replica::",R=s=>{const e=s.lastIndexOf(h);if(e===-1)return;const t=s.slice(0,e),r=s.slice(e+h.length);if(!(t.length===0||!b(r)))return{ownerKey:t,region:r}},I=s=>{if(s==null||!/^\d+$/.test(s))return;const e=Number.parseInt(s,10);return Number.isSafeInteger(e)&&e>0?e:void 0},m=1e3,w=1e3,C=10,U=5e4,F=s=>v(s,"LUNORA_REPLICA_MAX_BOOTSTRAP_ROWS",U),d="__replica_state",l=new WeakSet,_=s=>{l.has(s)||(s.exec(`CREATE TABLE IF NOT EXISTS ${d} (
1
+ import{d as p,e as S}from"./wire-codec-C-FpWm52.mjs";import{cursorBelowRetainedFloor as y}from"./CDC_LOG_TABLE-DXEAcmsr.mjs";import{envPositiveInt as v}from"./envOptionalPositiveInt-D2pY-c64.mjs";import{v as A,R as g,s as N,a as E,b as T}from"./sibling-channel-BkL5cTCc.mjs";const L=["wnam","enam","sam","weur","eeur","apac","apac-ne","apac-se","oc","afr","me"],O=new Set(L),b=s=>typeof s=="string"&&O.has(s),h="::replica::",R=s=>{const e=s.lastIndexOf(h);if(e===-1)return;const t=s.slice(0,e),r=s.slice(e+h.length);if(!(t.length===0||!b(r)))return{ownerKey:t,region:r}},I=s=>{if(s==null||!/^\d+$/.test(s))return;const e=Number.parseInt(s,10);return Number.isSafeInteger(e)&&e>0?e:void 0},m=1e3,w=1e3,C=10,U=5e4,F=s=>v(s,"LUNORA_REPLICA_MAX_BOOTSTRAP_ROWS",U),d="__replica_state",l=new WeakSet,_=s=>{l.has(s)||(s.exec(`CREATE TABLE IF NOT EXISTS ${d} (
2
2
  id INTEGER PRIMARY KEY CHECK (id = 1),
3
3
  epoch TEXT NOT NULL,
4
4
  applied_seq INTEGER NOT NULL,
@@ -1 +1 @@
1
- import{createShardCtxDb as v}from"./NotUniqueError-DpTK0ULs.mjs";import{createRelayLink as I}from"./DEFAULT_MAX_RELAYS-Ng4SyJ7k.mjs";import{ConflictError as N}from"./ConflictError-C8GtJmjS.mjs";import{runShardMigrations as _}from"./runShardMigrations-BLl8xFGK.mjs";import{relayName as F}from"./DEFAULT_PROMOTION_THRESHOLDS-Bfx7KakS.mjs";const E=(C,m={})=>({_meta:{column:{notNull:!0,...m}},kind:C}),W=(C,m,O)=>{const{describe:S,expect:n,it:y}=O;S(`engine contract: ${C}`,()=>{S("optimistic concurrency",()=>{const b=u=>({tables:{items:{indexes:[],shape:{title:E("string"),version:E("number",{notNull:!1})},triggerMap:{clobber:{handler:()=>{u.exec(`UPDATE "items" SET "__doc__" = json_set("__doc__", '$.version', 99) WHERE "id" = 'i1'`)},op:"update",timing:"before"}}}}});y("raises a CONFLICT of kind `occ` when a write's snapshot is clobbered",async()=>{const{close:u,host:h}=m();try{const i=h.sql,l=b(i);_(i,l);const s=v({schema:l,sql:i});await s.insert("items",{_id:"i1",title:"first",version:1},{allowExplicitId:!0}),await n(s.patch("i1",{title:"second"})).rejects.toBeInstanceOf(N)}finally{u?.()}}),y("reports the conflict as CONFLICT/409 rather than retrying it away",async()=>{const{close:u,host:h}=m();try{const i=h.sql,l=b(i);_(i,l);const s=v({schema:l,sql:i});await s.insert("items",{_id:"i1",title:"first",version:1},{allowExplicitId:!0});let o;try{await s.patch("i1",{title:"second"})}catch(t){o=t}const e=o;n(e.code).toBe("CONFLICT"),n(e.kind).toBe("occ")}finally{u?.()}}),y("leaves the row readable and unchanged after a conflict",async()=>{const{close:u,host:h}=m();try{const i=h.sql,l=b(i);_(i,l);const s=v({schema:l,sql:i});await s.insert("items",{_id:"i1",title:"first",version:1},{allowExplicitId:!0});try{await s.patch("i1",{title:"second"})}catch{}const o=await s.get("i1");n(o?.title).toBe("first"),n(o?.version).toBe(99)}finally{u?.()}}),y("raises a CONFLICT of kind `trigger` when a trigger writes its own row through the db",async()=>{const{close:u,host:h}=m();try{const i=h.sql,l={tables:{items:{indexes:[],shape:{title:E("string"),version:E("number",{notNull:!1})},triggerMap:{recurse:{handler:async(t,a)=>{await t.db.patch(a.doc._id,{version:99})},op:"update",timing:"before"}}}}};_(i,l);const s=v({schema:l,sql:i});await s.insert("items",{_id:"i1",title:"first",version:1},{allowExplicitId:!0});let o;try{await s.patch("i1",{title:"second"})}catch(t){o=t}const e=o;n(e).toBeInstanceOf(N),n(e.code).toBe("CONFLICT"),n(e.kind).toBe("trigger")}finally{u?.()}})}),S("shape-poke ordering",()=>{const b="shard-a",u={args:{},name:"messages"},h=(e,t,a,r)=>e.accept(t?.()??{},{connectionId:a,shapes:{[r]:u}}),i=(e,t,a)=>{let r=0,d=0;const c=g=>()=>{throw new Error(`the relay poke path must not reach RelayHost.${g}`)},p={fetch:(g,q)=>{if(JSON.parse(q?.body??"{}").type!=="relay_shape_subscribe")return Promise.resolve(new Response(void 0,{status:204}));const B=a[d];if(d+=1,B===void 0)throw new Error("the relay asked for more seeds than this fixture supplies");return Promise.resolve(Response.json(B))}},k={get:()=>p,getByName:()=>p,idFromName:g=>g},w={buildShapeDiff:c("buildShapeDiff"),computeOpLogShapeSeed:c("computeOpLogShapeSeed"),currentCdcEpoch:c("currentCdcEpoch"),deliverWhisperLocal:c("deliverWhisperLocal"),doName:()=>F(b,0),env:()=>({SHARD:k}),getWebSockets:()=>e.getSockets(),maskMetadata:c("maskMetadata"),nextPokeId:()=>(r+=1,`poke-${String(r)}`),readAttachment:g=>g.deserializeAttachment?.(),recordShapePokeFanout:()=>{},resolveShape:c("resolveShape"),rlsMetadata:c("rlsMetadata"),shardBinding:()=>"SHARD",shardJurisdiction:()=>{},sql:()=>t},f=I(w);if(f===void 0)throw new Error("expected a relay link for a `…::relay::N` name");return f},l=e=>new Request("https://relay.internal/_lunora/relay",{body:JSON.stringify(e),headers:{"content-type":"application/json"},method:"POST"}),s=async(e,t,a)=>{const r=await e.seedRelayShape(t,a,u,{identity:void 0,userId:void 0});if(r!=="ok")throw new Error(`seed failed: ${JSON.stringify(r)}`)},o=(e={})=>l({...u,checkpoint:20,epoch:"e1",fromCursor:10,rowsPatch:[{id:"r1",op:"upsert",value:{title:"hello"}}],type:"relay_shape_poke",...e});y("frames a poke as pokeStart → pokePart per shape → pokeEnd, under one poke id",async()=>{const{close:e,createSocket:t,host:a,readFrames:r,sockets:d}=m();try{const c=i(d,a.sql,[{cursor:10,epoch:"e1",frames:[]}]),p=h(d,t,"c-alice","s1");await s(c,p,"s1"),await c.handleControl(o());const w=(await r(p)).map(f=>JSON.parse(f));n(w.map(f=>f.type)).toStrictEqual(["pokeStart","pokePart","pokeEnd"]),n(new Set(w.map(f=>f.pokeId)).size).toBe(1),n(w[1]?.shapeId).toBe("s1"),n(w[2]?.checkpoint).toBe(20)}finally{e?.()}}),y("delivers a poke only to sockets whose cursor matches, and advances them past it",async()=>{const{close:e,createSocket:t,host:a,readFrames:r,sockets:d}=m();try{const c=i(d,a.sql,[{cursor:10,epoch:"e1",frames:[]},{cursor:7,epoch:"e1",frames:[]}]),p=h(d,t,"c-alice","s1"),k=h(d,t,"c-bob","s2");await s(c,p,"s1"),await s(c,k,"s2"),await c.handleControl(o());const w=await r(p);n(w.length).toBe(3);const f=await r(k);n(f.length).toBe(0),await c.handleControl(o());const g=await r(p);n(g.length).toBe(3)}finally{e?.()}}),y("skips a socket whose cursor matches under a different CDC epoch",async()=>{const{close:e,createSocket:t,host:a,readFrames:r,sockets:d}=m();try{const c=i(d,a.sql,[{cursor:10,epoch:"e1",frames:[]}]),p=h(d,t,"c-alice","s1");await s(c,p,"s1"),await c.handleControl(o({epoch:"e2"}));const k=await r(p);n(k.length).toBe(0),await c.handleControl(o());const w=await r(p);n(w.length).toBe(3)}finally{e?.()}})}),S("RLS identity under live subscription",()=>{const b="shard-a",u={args:{},name:"lobby-messages"},h={args:{},name:"my-orders"},i=s=>{const o=[],e=[],t={fetch:(d,c)=>(o.push(JSON.parse(c?.body??"{}")),Promise.resolve(new Response(void 0,{status:204})))},r=I({buildShapeDiff:()=>[{id:"r1",op:"upsert",value:{}}],computeOpLogShapeSeed:()=>({baseCheckpoint:void 0,cursor:10,epoch:"e1",reset:!0,rowsPatch:[]}),currentCdcEpoch:()=>"e1",deliverWhisperLocal:()=>0,doName:()=>b,env:()=>({SHARD:{get:()=>t,getByName:()=>t,idFromName:d=>d}}),getWebSockets:()=>[],maskMetadata:()=>({columns:[]}),nextPokeId:()=>"poke-1",readAttachment:()=>({}),recordShapePokeFanout:()=>{},resolveShape:(d,c,p)=>(e.push(p),d===h.name?{columns:["id"],effectiveWhere:{org:p?.identity?.org??"anonymous"},global:!1,table:"orders"}:{columns:["id"],effectiveWhere:{room:"lobby"},global:!1,table:"messages"}),rlsMetadata:()=>({policies:[]}),shardBinding:()=>"SHARD",shardJurisdiction:()=>{},sql:()=>s});if(r===void 0)throw new Error("expected an owner link for an un-suffixed DO name");return{owner:r,posts:o,resolvedUnder:e}},l=async(s,o)=>{await s.handleControl(new Request("https://owner.internal/_lunora/relay",{body:JSON.stringify({...o,connectionId:"c-alice",identity:{org:"acme"},relayIndex:0,subId:"s1",type:"relay_shape_subscribe",userId:"u1"}),headers:{"content-type":"application/json"},method:"POST"}))};y("seeds a subscriber under its own forwarded identity, never the anonymous one",async()=>{const{close:s,host:o}=m();try{const{owner:e,resolvedUnder:t}=i(o.sql);await l(e,h),n(t.some(a=>a?.userId==="u1"&&a.identity?.org==="acme")).toBe(!0)}finally{s?.()}}),y("routes an identity-scoped shape to a per-socket poke, not the cohort multicast",async()=>{const{close:s,host:o}=m();try{const{owner:e,posts:t}=i(o.sql);await l(e,h),t.length=0,await e.onFlush(new Set(["orders"]),20);const a=t.filter(r=>r.type==="relay_shape_poke");n(a.length).toBe(1),n(a[0]?.targetConnectionId).toBe("c-alice")}finally{s?.()}}),y("still multicasts an identity-blind shape to the whole cohort",async()=>{const{close:s,host:o}=m();try{const{owner:e,posts:t}=i(o.sql);await l(e,u),t.length=0,await e.onFlush(new Set(["messages"]),20);const a=t.filter(r=>r.type==="relay_shape_poke");n(a.length).toBe(1),n(a[0]?.targetConnectionId).toBeUndefined()}finally{s?.()}})})})};export{W as defineEngineContractSuite};
1
+ import{createShardCtxDb as v}from"./NotUniqueError-1OMgp1sA.mjs";import{createRelayLink as I}from"./DEFAULT_MAX_RELAYS-Ng4SyJ7k.mjs";import{ConflictError as N}from"./ConflictError-C8GtJmjS.mjs";import{runShardMigrations as _}from"./runShardMigrations-DGlaC68E.mjs";import{relayName as F}from"./DEFAULT_PROMOTION_THRESHOLDS-Bfx7KakS.mjs";const E=(C,m={})=>({_meta:{column:{notNull:!0,...m}},kind:C}),W=(C,m,O)=>{const{describe:S,expect:n,it:y}=O;S(`engine contract: ${C}`,()=>{S("optimistic concurrency",()=>{const b=u=>({tables:{items:{indexes:[],shape:{title:E("string"),version:E("number",{notNull:!1})},triggerMap:{clobber:{handler:()=>{u.exec(`UPDATE "items" SET "__doc__" = json_set("__doc__", '$.version', 99) WHERE "id" = 'i1'`)},op:"update",timing:"before"}}}}});y("raises a CONFLICT of kind `occ` when a write's snapshot is clobbered",async()=>{const{close:u,host:h}=m();try{const i=h.sql,l=b(i);_(i,l);const s=v({schema:l,sql:i});await s.insert("items",{_id:"i1",title:"first",version:1},{allowExplicitId:!0}),await n(s.patch("i1",{title:"second"})).rejects.toBeInstanceOf(N)}finally{u?.()}}),y("reports the conflict as CONFLICT/409 rather than retrying it away",async()=>{const{close:u,host:h}=m();try{const i=h.sql,l=b(i);_(i,l);const s=v({schema:l,sql:i});await s.insert("items",{_id:"i1",title:"first",version:1},{allowExplicitId:!0});let o;try{await s.patch("i1",{title:"second"})}catch(t){o=t}const e=o;n(e.code).toBe("CONFLICT"),n(e.kind).toBe("occ")}finally{u?.()}}),y("leaves the row readable and unchanged after a conflict",async()=>{const{close:u,host:h}=m();try{const i=h.sql,l=b(i);_(i,l);const s=v({schema:l,sql:i});await s.insert("items",{_id:"i1",title:"first",version:1},{allowExplicitId:!0});try{await s.patch("i1",{title:"second"})}catch{}const o=await s.get("i1");n(o?.title).toBe("first"),n(o?.version).toBe(99)}finally{u?.()}}),y("raises a CONFLICT of kind `trigger` when a trigger writes its own row through the db",async()=>{const{close:u,host:h}=m();try{const i=h.sql,l={tables:{items:{indexes:[],shape:{title:E("string"),version:E("number",{notNull:!1})},triggerMap:{recurse:{handler:async(t,a)=>{await t.db.patch(a.doc._id,{version:99})},op:"update",timing:"before"}}}}};_(i,l);const s=v({schema:l,sql:i});await s.insert("items",{_id:"i1",title:"first",version:1},{allowExplicitId:!0});let o;try{await s.patch("i1",{title:"second"})}catch(t){o=t}const e=o;n(e).toBeInstanceOf(N),n(e.code).toBe("CONFLICT"),n(e.kind).toBe("trigger")}finally{u?.()}})}),S("shape-poke ordering",()=>{const b="shard-a",u={args:{},name:"messages"},h=(e,t,a,r)=>e.accept(t?.()??{},{connectionId:a,shapes:{[r]:u}}),i=(e,t,a)=>{let r=0,d=0;const c=g=>()=>{throw new Error(`the relay poke path must not reach RelayHost.${g}`)},p={fetch:(g,q)=>{if(JSON.parse(q?.body??"{}").type!=="relay_shape_subscribe")return Promise.resolve(new Response(void 0,{status:204}));const B=a[d];if(d+=1,B===void 0)throw new Error("the relay asked for more seeds than this fixture supplies");return Promise.resolve(Response.json(B))}},k={get:()=>p,getByName:()=>p,idFromName:g=>g},w={buildShapeDiff:c("buildShapeDiff"),computeOpLogShapeSeed:c("computeOpLogShapeSeed"),currentCdcEpoch:c("currentCdcEpoch"),deliverWhisperLocal:c("deliverWhisperLocal"),doName:()=>F(b,0),env:()=>({SHARD:k}),getWebSockets:()=>e.getSockets(),maskMetadata:c("maskMetadata"),nextPokeId:()=>(r+=1,`poke-${String(r)}`),readAttachment:g=>g.deserializeAttachment?.(),recordShapePokeFanout:()=>{},resolveShape:c("resolveShape"),rlsMetadata:c("rlsMetadata"),shardBinding:()=>"SHARD",shardJurisdiction:()=>{},sql:()=>t},f=I(w);if(f===void 0)throw new Error("expected a relay link for a `…::relay::N` name");return f},l=e=>new Request("https://relay.internal/_lunora/relay",{body:JSON.stringify(e),headers:{"content-type":"application/json"},method:"POST"}),s=async(e,t,a)=>{const r=await e.seedRelayShape(t,a,u,{identity:void 0,userId:void 0});if(r!=="ok")throw new Error(`seed failed: ${JSON.stringify(r)}`)},o=(e={})=>l({...u,checkpoint:20,epoch:"e1",fromCursor:10,rowsPatch:[{id:"r1",op:"upsert",value:{title:"hello"}}],type:"relay_shape_poke",...e});y("frames a poke as pokeStart → pokePart per shape → pokeEnd, under one poke id",async()=>{const{close:e,createSocket:t,host:a,readFrames:r,sockets:d}=m();try{const c=i(d,a.sql,[{cursor:10,epoch:"e1",frames:[]}]),p=h(d,t,"c-alice","s1");await s(c,p,"s1"),await c.handleControl(o());const w=(await r(p)).map(f=>JSON.parse(f));n(w.map(f=>f.type)).toStrictEqual(["pokeStart","pokePart","pokeEnd"]),n(new Set(w.map(f=>f.pokeId)).size).toBe(1),n(w[1]?.shapeId).toBe("s1"),n(w[2]?.checkpoint).toBe(20)}finally{e?.()}}),y("delivers a poke only to sockets whose cursor matches, and advances them past it",async()=>{const{close:e,createSocket:t,host:a,readFrames:r,sockets:d}=m();try{const c=i(d,a.sql,[{cursor:10,epoch:"e1",frames:[]},{cursor:7,epoch:"e1",frames:[]}]),p=h(d,t,"c-alice","s1"),k=h(d,t,"c-bob","s2");await s(c,p,"s1"),await s(c,k,"s2"),await c.handleControl(o());const w=await r(p);n(w.length).toBe(3);const f=await r(k);n(f.length).toBe(0),await c.handleControl(o());const g=await r(p);n(g.length).toBe(3)}finally{e?.()}}),y("skips a socket whose cursor matches under a different CDC epoch",async()=>{const{close:e,createSocket:t,host:a,readFrames:r,sockets:d}=m();try{const c=i(d,a.sql,[{cursor:10,epoch:"e1",frames:[]}]),p=h(d,t,"c-alice","s1");await s(c,p,"s1"),await c.handleControl(o({epoch:"e2"}));const k=await r(p);n(k.length).toBe(0),await c.handleControl(o());const w=await r(p);n(w.length).toBe(3)}finally{e?.()}})}),S("RLS identity under live subscription",()=>{const b="shard-a",u={args:{},name:"lobby-messages"},h={args:{},name:"my-orders"},i=s=>{const o=[],e=[],t={fetch:(d,c)=>(o.push(JSON.parse(c?.body??"{}")),Promise.resolve(new Response(void 0,{status:204})))},r=I({buildShapeDiff:()=>[{id:"r1",op:"upsert",value:{}}],computeOpLogShapeSeed:()=>({baseCheckpoint:void 0,cursor:10,epoch:"e1",reset:!0,rowsPatch:[]}),currentCdcEpoch:()=>"e1",deliverWhisperLocal:()=>0,doName:()=>b,env:()=>({SHARD:{get:()=>t,getByName:()=>t,idFromName:d=>d}}),getWebSockets:()=>[],maskMetadata:()=>({columns:[]}),nextPokeId:()=>"poke-1",readAttachment:()=>({}),recordShapePokeFanout:()=>{},resolveShape:(d,c,p)=>(e.push(p),d===h.name?{columns:["id"],effectiveWhere:{org:p?.identity?.org??"anonymous"},global:!1,table:"orders"}:{columns:["id"],effectiveWhere:{room:"lobby"},global:!1,table:"messages"}),rlsMetadata:()=>({policies:[]}),shardBinding:()=>"SHARD",shardJurisdiction:()=>{},sql:()=>s});if(r===void 0)throw new Error("expected an owner link for an un-suffixed DO name");return{owner:r,posts:o,resolvedUnder:e}},l=async(s,o)=>{await s.handleControl(new Request("https://owner.internal/_lunora/relay",{body:JSON.stringify({...o,connectionId:"c-alice",identity:{org:"acme"},relayIndex:0,subId:"s1",type:"relay_shape_subscribe",userId:"u1"}),headers:{"content-type":"application/json"},method:"POST"}))};y("seeds a subscriber under its own forwarded identity, never the anonymous one",async()=>{const{close:s,host:o}=m();try{const{owner:e,resolvedUnder:t}=i(o.sql);await l(e,h),n(t.some(a=>a?.userId==="u1"&&a.identity?.org==="acme")).toBe(!0)}finally{s?.()}}),y("routes an identity-scoped shape to a per-socket poke, not the cohort multicast",async()=>{const{close:s,host:o}=m();try{const{owner:e,posts:t}=i(o.sql);await l(e,h),t.length=0,await e.onFlush(new Set(["orders"]),20);const a=t.filter(r=>r.type==="relay_shape_poke");n(a.length).toBe(1),n(a[0]?.targetConnectionId).toBe("c-alice")}finally{s?.()}}),y("still multicasts an identity-blind shape to the whole cohort",async()=>{const{close:s,host:o}=m();try{const{owner:e,posts:t}=i(o.sql);await l(e,u),t.length=0,await e.onFlush(new Set(["messages"]),20);const a=t.filter(r=>r.type==="relay_shape_poke");n(a.length).toBe(1),n(a[0]?.targetConnectionId).toBeUndefined()}finally{s?.()}})})})};export{W as defineEngineContractSuite};
@@ -1,4 +1,4 @@
1
- import{LunoraError as T}from"@lunora/errors";import{sql as m}from"drizzle-orm";import{runDrizzle as S}from"./runDrizzle-2ULFQR_k.mjs";import{liftSourceId as A}from"./liftSourceId-CA3ENhXj.mjs";import{normalizeSourceValue as W}from"./liftSourceId-CA3ENhXj.mjs";import{runExternalSourceTick as C,materializeExternalRowsIncremental as D}from"./materializeExternalRows-xQWkrJqp.mjs";const p="__lunora_source_cursor",M=e=>e instanceof Date?`d:${e.toISOString()}`:typeof e=="bigint"?`b:${e.toString()}`:typeof e=="number"?`n:${e.toString()}`:`s:${e}`,v=e=>{const t=e.slice(2);switch(e[0]){case"b":return BigInt(t);case"d":return new Date(t);case"n":return Number(t);default:return t}},h=/^-?\d+$/,N=/^-?\d+(?:\.\d+)?$/,x=(e,t)=>e instanceof Date&&t instanceof Date?e.getTime()>t.getTime():typeof e=="bigint"&&typeof t=="bigint"||typeof e=="number"&&typeof t=="number"?e>t:typeof e=="string"&&typeof t=="string"&&N.test(e)&&N.test(t)?h.test(e)&&h.test(t)?BigInt(e)>BigInt(t):Number(e)>Number(t):String(e)>String(t),O=(e,t,o)=>{let n=o===null?void 0:v(o);for(const r of e){const c=r[t];if(c==null)continue;const a=c;(n===void 0||x(a,n))&&(n=a)}return n===void 0?null:M(n)},B=e=>{S(e,m`CREATE TABLE IF NOT EXISTS ${m.identifier(p)} (
1
+ import{LunoraError as T}from"@lunora/errors";import{sql as m}from"drizzle-orm";import{runDrizzle as S}from"./runDrizzle-2ULFQR_k.mjs";import{liftSourceId as A}from"./liftSourceId-CA3ENhXj.mjs";import{normalizeSourceValue as W}from"./liftSourceId-CA3ENhXj.mjs";import{runExternalSourceTick as C,materializeExternalRowsIncremental as D}from"./materializeExternalRows-B1623YXA.mjs";const p="__lunora_source_cursor",M=e=>e instanceof Date?`d:${e.toISOString()}`:typeof e=="bigint"?`b:${e.toString()}`:typeof e=="number"?`n:${e.toString()}`:`s:${e}`,v=e=>{const t=e.slice(2);switch(e[0]){case"b":return BigInt(t);case"d":return new Date(t);case"n":return Number(t);default:return t}},h=/^-?\d+$/,N=/^-?\d+(?:\.\d+)?$/,x=(e,t)=>e instanceof Date&&t instanceof Date?e.getTime()>t.getTime():typeof e=="bigint"&&typeof t=="bigint"||typeof e=="number"&&typeof t=="number"?e>t:typeof e=="string"&&typeof t=="string"&&N.test(e)&&N.test(t)?h.test(e)&&h.test(t)?BigInt(e)>BigInt(t):Number(e)>Number(t):String(e)>String(t),O=(e,t,o)=>{let n=o===null?void 0:v(o);for(const r of e){const c=r[t];if(c==null)continue;const a=c;(n===void 0||x(a,n))&&(n=a)}return n===void 0?null:M(n)},B=e=>{S(e,m`CREATE TABLE IF NOT EXISTS ${m.identifier(p)} (
2
2
  table_name TEXT NOT NULL,
3
3
  shard_key TEXT NOT NULL,
4
4
  watermark TEXT,
@@ -1 +1 @@
1
- import{applyCdcChanges as p}from"./CDC_LOG_TABLE-CfILante.mjs";import{selectShapeRows as m}from"./selectShapeMembers-B8gTOeOB.mjs";import{diffExternalSource as g,projectExternalSourceRow as l}from"./diffExternalSource-DgDJhslq.mjs";import{stableStringify as d}from"./stableStringify-DibjylKD.mjs";const x=async(t,s,a,e)=>{const{changes:o,nextBaseline:n}=g(s,a,e);return await p(t,o),{applied:o.length,nextBaseline:n}},R=async(t,s,a)=>{const{columns:e,deletedIds:o,table:n}=a,r=[];for(const f of s){const i=l(f,e),c=String(i._id);if(o?.has(c)){await t.get(c,n)&&r.push({id:c,op:"delete",seq:0,table:n,ts:0});continue}const u=await t.get(c,n);u&&d(l({...u,_id:c},e))===d(i)||r.push({doc:i,id:c,op:"insert",seq:0,table:n,ts:0})}return await p(t,r),{applied:r.length}},h=(t,s,a)=>{const e=new Map;for(const{doc:o,id:n}of m(t,s,void 0))e.set(n,d(l({...o,_id:n},a)));return e},_=async(t,s,a,e)=>{const o=h(t,e.table,e.columns);return x(s,a,o,e)};export{x as materializeExternalRows,R as materializeExternalRowsIncremental,h as readExternalSourceBaseline,_ as runExternalSourceTick};
1
+ import{applyCdcChanges as p}from"./CDC_LOG_TABLE-DXEAcmsr.mjs";import{selectShapeRows as m}from"./selectShapeMembers-B8gTOeOB.mjs";import{diffExternalSource as g,projectExternalSourceRow as l}from"./diffExternalSource-DgDJhslq.mjs";import{stableStringify as d}from"./stableStringify-DibjylKD.mjs";const x=async(t,s,a,e)=>{const{changes:o,nextBaseline:n}=g(s,a,e);return await p(t,o),{applied:o.length,nextBaseline:n}},R=async(t,s,a)=>{const{columns:e,deletedIds:o,table:n}=a,r=[];for(const f of s){const i=l(f,e),c=String(i._id);if(o?.has(c)){await t.get(c,n)&&r.push({id:c,op:"delete",seq:0,table:n,ts:0});continue}const u=await t.get(c,n);u&&d(l({...u,_id:c},e))===d(i)||r.push({doc:i,id:c,op:"insert",seq:0,table:n,ts:0})}return await p(t,r),{applied:r.length}},h=(t,s,a)=>{const e=new Map;for(const{doc:o,id:n}of m(t,s,void 0))e.set(n,d(l({...o,_id:n},a)));return e},_=async(t,s,a,e)=>{const o=h(t,e.table,e.columns);return x(s,a,o,e)};export{x as materializeExternalRows,R as materializeExternalRowsIncremental,h as readExternalSourceBaseline,_ as runExternalSourceTick};
@@ -0,0 +1,5 @@
1
+ import{LunoraError as L}from"@lunora/errors";import{S as l,y as h,l as N}from"./ctx-db-companions-DsNfXSbb.mjs";import{sql as e}from"drizzle-orm";import{aggregateTableName as R}from"./aggregateTableName-C7o-gpms.mjs";import{backfillSearchIndexesForTable as O}from"./backfillAggregateIndexes-DTemznr7.mjs";import{migrateCdcLog as x,migrateCdcMeta as C}from"./CDC_LOG_TABLE-DXEAcmsr.mjs";import{migrateClientWatermark as $}from"./CLIENT_WATERMARK_TABLE-CRnrAnJ2.mjs";import{migrateCommitSeq as b}from"./COMMIT_SEQ_FIELD-BUdOMG5y.mjs";import{migrateGlobalShapeSnapshot as U}from"./GLOBAL_SHAPE_SNAPSHOT_TABLE-DSA6mzyx.mjs";import{migrateIdempotency as D}from"./IDEMPOTENCY_TABLE-DOpm_oMF.mjs";import{m as M}from"./ctx-db-relay-shapes-Bg5YYnmN.mjs";import{migrateScheduleOutbox as X}from"./SCHEDULE_OUTBOX_TABLE-CD_UjYVx.mjs";import{m as G}from"./ctx-db-search-state-ruTuCsxa.mjs";import{migrateShapePokeCursor as y}from"./SHAPE_POKE_CURSOR_TABLE-ByJVDHds.mjs";import{runDrizzle as s}from"./runDrizzle-2ULFQR_k.mjs";import{D as F,d as E,e as u,t as B,i as v,g as P,a as Y,b as k,A as g}from"./do-sql-kpl5Kt1j.mjs";import{renderSql as w}from"./param-DlozcSQu.mjs";import{migrateDurableStreams as j}from"./appendStreamChunk-C1Ok4b6J.mjs";import{rankTableName as H,sortColumnName as K}from"./RANK_TIEBREAK-D5xNdzB3.mjs";import{migrateReactorState as V}from"./REACTOR_STATE_TABLE-QPRFyxMS.mjs";import{recordSchemaVersion as W}from"./SCHEMA_HISTORY_MAX_VERSIONS-BluIj2s-.mjs";const S=e`_creationTime, id`,p=(r,n,i,t,o,a)=>{const c=e.join(o.map(d=>e`${d} IS NOT NULL`),e` AND `);if(s(r,e`SELECT 1 FROM ${e.identifier(i)} WHERE ${c} GROUP BY ${t} HAVING COUNT(*) > 1 LIMIT 1`).toArray().length>0)throw new L("INTERNAL",`unique index "${n}" on "${i}" ${a}: existing rows are duplicates under it. De-duplicate the table with a data migration first; the previous index is left in place.`)},z=(r,n,i,t,o,a)=>{const m=s(r,e`SELECT sql FROM sqlite_master WHERE type = 'index' AND name = ${n} AND tbl_name = ${i}`).toArray()[0]?.sql;if(m==null)return;const d=_=>{const I=_.indexOf("(");return I===-1?void 0:_.slice(I,_.lastIndexOf(")")+1)},T=d(w("sqlite",E(n,i,t,o)).sql),f=d(m);T===void 0||f===void 0||T===f||(o&&p(r,n,i,t,a,"cannot be re-created with its new column list"),s(r,e`DROP INDEX IF EXISTS ${e.identifier(n)}`))},J=(r,n,i)=>s(r,e`SELECT 1 FROM sqlite_master WHERE type = 'index' AND name = ${n} AND tbl_name = ${i} LIMIT 1`).toArray().length>0,A=(r,n,i,t,o,a)=>{o&&!J(r,n,i)&&p(r,n,i,t,a,"cannot be created"),s(r,E(n,i,t,o))},Q=(r,n,i)=>{for(const t of i.indexes){const o=`${n}_${t.name}`,a=t.unique??!1,c=t.fields.map(T=>u(T)),m=e.join(c,e`, `),d=a?m:e`${m}, ${S}`;z(r,o,n,d,a,c),A(r,o,n,d,a,c)}for(const[t,o]of B(i)){if(!o.unique)continue;const a=u(t);A(r,`${n}_unique_${t}`,n,a,!0,[a])}},Z=(r,n,i)=>{if(!(!i.searchIndexes||i.searchIndexes.length===0||!v(r))){for(const t of i.searchIndexes){const o=l(n,t.name);s(r,e`CREATE VIRTUAL TABLE IF NOT EXISTS ${e.identifier(o)} USING fts5(${e.identifier(h)}, ${e.identifier(N)} UNINDEXED)`),s(r,e`CREATE VIRTUAL TABLE IF NOT EXISTS ${e.identifier(`${o}__vocab`)} USING fts5vocab(${e.identifier(o)}, ${e.raw("instance")})`)}O(r,n,i)}},q=(r,n,i)=>{if(i.geoIndexes)for(const t of i.geoIndexes){const o=P(n,t.name);s(r,e`CREATE TABLE IF NOT EXISTS ${e.identifier(o)} (${e.identifier("__id__")} TEXT PRIMARY KEY, ${e.identifier("__geohash__")} TEXT NOT NULL, ${e.identifier("__lat__")} REAL NOT NULL, ${e.identifier("__lng__")} REAL NOT NULL)`);const a=`${n}__geo_${t.name}__btree`;s(r,E(a,o,e`${e.identifier("__geohash__")} ASC, ${e.identifier("__id__")} ASC`,!1))}},ee=(r,n,i)=>{if(i.aggregateIndexes)for(const t of i.aggregateIndexes){const o=R(n,t.name);s(r,e`CREATE TABLE IF NOT EXISTS ${e.identifier(o)} (${Y} TEXT PRIMARY KEY, ${k} REAL, ${g} INTEGER NOT NULL DEFAULT 0)`),s(r,e`PRAGMA table_info(${e.identifier(o)})`).toArray().some(c=>c.name==="__count__")||s(r,e`ALTER TABLE ${e.identifier(o)} ADD COLUMN ${g} INTEGER NOT NULL DEFAULT 0`)}},re=(r,n,i)=>{if(i.rankIndexes)for(const t of i.rankIndexes){const o=H(n,t.name),a=t.sortBy.map((f,_)=>K(_)),c=a.map(f=>e`${e.identifier(f)} BLOB`),m=c.length>0?e`, ${e.join(c,e`, `)}`:e``;s(r,e`CREATE TABLE IF NOT EXISTS ${e.identifier(o)} (${e.identifier("__id__")} TEXT PRIMARY KEY, ${e.identifier("__partition__")} TEXT NOT NULL${m})`);const d=[e`${e.identifier("__partition__")} ASC`];for(const[f,_]of a.entries()){const I=t.sortBy[f]?.direction;d.push(e`${e.identifier(_)} ${e.raw(I==="desc"?"DESC":"ASC")}`)}d.push(e`${e.identifier("__id__")} ASC`);const T=`${n}__rank_${t.name}__btree`;s(r,E(T,o,e.join(d,e`, `),!1))}},he=(r,n,i={})=>{i.schemaSnapshot!==void 0&&W(r,i.schemaSnapshot.hash,i.schemaSnapshot.json),G(r);for(const[t,o]of Object.entries(n.tables))o.shardMode?.kind!=="global"&&(s(r,e`CREATE TABLE IF NOT EXISTS ${e.identifier(t)} (
2
+ id TEXT PRIMARY KEY,
3
+ _creationTime REAL NOT NULL,
4
+ ${e.identifier(F)} TEXT NOT NULL
5
+ )`),s(r,E(`${t}__by_creation`,t,S,!1)),Q(r,t,o),Z(r,t,o),q(r,t,o),ee(r,t,o),re(r,t,o));i.cdc&&(x(r,{rowHistoryIndex:Object.values(n.tables).some(t=>t.dropStalePatchesMode===!0)}),C(r),$(r),y(r),M(r)),Object.values(n.tables).some(t=>t.commitOrderedMode===!0)&&b(r),V(r),D(r),X(r),U(r),j(r)};export{he as runShardMigrations};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@lunora/shard-engine",
3
- "version": "1.0.0-alpha.72",
3
+ "version": "1.0.0-alpha.74",
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,15 +0,0 @@
1
- import{LunoraError as R}from"@lunora/errors";import{sql as t}from"drizzle-orm";import{quoteIdentifier as C}from"./quoteIdentifier-CObIFRhb.mjs";import{runSql as u,runDrizzle as s}from"./runDrizzle-2ULFQR_k.mjs";import{k as L,l as p}from"./do-sql-kpl5Kt1j.mjs";import{ConflictError as A}from"./ConflictError-C8GtJmjS.mjs";const n="__cdc_log",q=`INSERT INTO ${C(n)} (ts, ${C("table")}, id, op, doc) VALUES (?, ?, ?, ?, ?)`,I="__cdc_log_table_seq",w=e=>{s(e,t`CREATE TABLE IF NOT EXISTS ${t.identifier(n)} (
2
- seq INTEGER PRIMARY KEY AUTOINCREMENT,
3
- ts REAL NOT NULL,
4
- ${t.identifier("table")} TEXT NOT NULL,
5
- id TEXT NOT NULL,
6
- op TEXT NOT NULL,
7
- doc TEXT
8
- )`);try{s(e,t`CREATE INDEX IF NOT EXISTS ${t.identifier(I)} ON ${t.identifier(n)} (${t.identifier("table")}, seq)`)}catch{}},F=(e,o,r,i,c,d)=>{const a=d===void 0?null:L(d);u(e,q,o,r,i,c,a)},f=90,h=e=>t` AND ${t.identifier("table")} IN (${t.join([...e].map(o=>t`${o}`),t`, `)})`,y=(e,o={})=>{const r=o.sinceSeq??0,i=Math.max(1,Math.min(o.limit??1e3,1e4)),d=s(e,t`SELECT seq, ts, ${t.identifier("table")}, id, op, doc FROM ${t.identifier(n)} WHERE seq > ${r} ORDER BY seq ASC LIMIT ${i}`).toArray().map(a=>{const l={id:a.id,op:a.op,seq:a.seq,table:a.table,ts:a.ts};return a.doc===null?l:{...l,doc:p(a.doc)}});return{changes:d,cursor:d.at(-1)?.seq??r}},U=(e,o,r)=>{if(r.size===0)return!1;const i=[...r];for(let c=0;c<i.length;c+=f){const d=new Set(i.slice(c,c+f));if(s(e,t`SELECT 1 AS hit FROM ${t.identifier(n)} WHERE seq > ${o}${h(d)} LIMIT 1`).toArray().length>0)return!0}return!1},T=new WeakMap,S=e=>new Set(s(e,t`SELECT name FROM sqlite_master WHERE type = 'table'`).toArray().map(o=>o.name)),X=(e,o)=>{if(o.size===0)return!1;let r=T.get(e),i=!1;r===void 0&&(r=S(e),i=!0,T.set(e,r));for(const c of o)if(!r.has(c)&&(i||(r=S(e),i=!0,T.set(e,r),!r.has(c))))return!1;return!0},x=(e,o,r,i)=>s(e,t`SELECT id, op, MAX(seq) AS maxSeq, COUNT(*) AS ops FROM ${t.identifier(n)}
9
- WHERE ${t.identifier("table")} = ${o} AND seq > ${r} AND seq <= ${i}
10
- GROUP BY id
11
- ORDER BY maxSeq ASC`).toArray().map(d=>{const a=d.op;return{id:d.id,op:a==="insert"&&d.ops>1?"update":a,seq:d.maxSeq}}),B=(e,o,r)=>{s(e,t`DELETE FROM ${t.identifier(n)} WHERE seq IN (
12
- SELECT seq FROM ${t.identifier(n)} WHERE seq <= ${o} ORDER BY seq ASC LIMIT ${r}
13
- )`)},H=(e,o,r)=>{s(e,t`UPDATE ${t.identifier(n)} SET doc = NULL WHERE seq IN (
14
- SELECT seq FROM ${t.identifier(n)} WHERE seq <= ${o} AND doc IS NOT NULL ORDER BY seq ASC LIMIT ${r}
15
- )`)},v=(e,o)=>{if(o<=0)return s(e,t`SELECT MAX(seq) AS seq FROM ${t.identifier(n)}`).toArray()[0]?.seq??void 0;const i=s(e,t`SELECT seq FROM ${t.identifier(n)} ORDER BY seq DESC LIMIT 1 OFFSET ${o-1}`).toArray()[0]?.seq;return i===void 0?void 0:i-1},W=e=>{const r=s(e,t`SELECT seq FROM sqlite_sequence WHERE name = ${n}`).toArray()[0]?.seq;return typeof r=="number"?r:s(e,t`SELECT MAX(seq) AS seq FROM ${t.identifier(n)}`).toArray()[0]?.seq??0},Y=(e,o)=>e!==void 0&&e>o+1,K=(e,o,r)=>new R("CDC_LOG_TRIMMED",`${r==="global"?"global cdc":"cdc"} entries at or below seq ${String(e-1)} have been trimmed; resume from a snapshot (sinceSeq ${String(o)} is below the retained window)`,{status:409}),P=(e,o,r)=>new R("CDC_TIMELINE_FORKED",`cdc cursor ${String(o)} is above this shard's high-watermark ${String(e)}; the changelog rolled back (a point-in-time restore) and the changes you hold are on a timeline that no longer exists — resume from a snapshot at epoch ${r}`,{data:{cursor:e,epoch:r},status:409}),N=e=>s(e,t`SELECT MIN(seq) AS seq FROM ${t.identifier(n)}`).toArray()[0]?.seq??void 0,G=e=>{const r=s(e,t`SELECT MAX(seq) AS seq FROM ${t.identifier(n)} WHERE op <> 'delete' AND doc IS NULL`).toArray()[0]?.seq??void 0,i=N(e);return r===void 0?i:Math.max(r+1,i??0)},E="__cdc_meta",m=e=>{s(e,t`CREATE TABLE IF NOT EXISTS ${t.identifier(E)} (id INTEGER PRIMARY KEY CHECK (id = 1), epoch TEXT NOT NULL)`)},k=e=>{m(e);const r=s(e,t`SELECT epoch FROM ${t.identifier(E)} WHERE id = 1`).toArray()[0]?.epoch;if(typeof r=="string"&&r.length>0)return r;const i=crypto.randomUUID();return s(e,t`INSERT INTO ${t.identifier(E)} (id, epoch) VALUES (1, ${i})`),i},V=e=>{m(e);const o=crypto.randomUUID();return s(e,t`INSERT INTO ${t.identifier(E)} (id, epoch) VALUES (1, ${o}) ON CONFLICT(id) DO UPDATE SET epoch = excluded.epoch`),o},O=async(e,o)=>{if(o.op==="delete"){await e.delete(o.id,o.table);return}const r=o.doc??{};try{await e.insert(o.table,r,{allowExplicitId:!0})}catch(i){if(!(i instanceof A))throw i;const c={...r};delete c._id,await e.replace(o.id,c,o.table,{allowExplicitId:!0})}},z=async(e,o)=>{for(const r of o)await O(e,r)};export{q as CDC_APPEND_SQL,n as CDC_LOG_TABLE,I as CDC_LOG_TABLE_SEQ_INDEX,E as CDC_META_TABLE,F as appendCdcChange,z as applyCdcChanges,V as bumpCdcEpoch,X as cdcCanVouchFor,P as cdcForkedError,v as cdcSeqLeavingRows,U as cdcTouchesTables,K as cdcTrimmedError,H as compactCdcDocs,Y as cursorBelowRetainedFloor,w as migrateCdcLog,m as migrateCdcMeta,G as minCdcReplayableSeq,N as minCdcSeq,x as readCdcChangeKeys,y as readCdcChanges,W as readCdcCursor,k as readCdcEpoch,B as trimCdcChanges};
@@ -1 +0,0 @@
1
- import{LunoraError as $}from"@lunora/errors";import{D as st}from"./MAX_TOKEN_LENGTH-BakL9FUy-B3VwYY8C.mjs";import{c as pn,S as gn,l as Le,a as $n}from"./ctx-db-companions-DsNfXSbb.mjs";import{sql as i}from"drizzle-orm";import{d as yn}from"./wire-codec-C-FpWm52.mjs";import{throwingScheduler as En,aggregateSqlFunction as ke,normalizeCountArgument as mn}from"./AGGREGATE_SQL_FUNCTION-DDEoMnJR.mjs";import{aggregateTableName as Ve,encodeAggregateKey as ze,readAggregateValue as Je}from"./aggregateTableName-C7o-gpms.mjs";import{mergeWhere as V,CountRlsUnsupportedError as Ye,selectIndexForGroupBy as Sn,selectIndexForCount as _n,selectIndexForAggregate as Rn}from"./CountRlsUnsupportedError-BvsDqfO2.mjs";import{backfillSearchIndexesForTable as Tn,searchIndexCoversTable as vn}from"./backfillAggregateIndexes-DTemznr7.mjs";import{backfillAggregateIndexes as Lr,backfillRankIndexes as kr,backfillSearchIndexes as Fr}from"./backfillAggregateIndexes-DTemznr7.mjs";import{appendCdcChange as An}from"./CDC_LOG_TABLE-CfILante.mjs";import{CDC_LOG_TABLE as Br,applyCdcChanges as Wr,bumpCdcEpoch as Pr,cdcCanVouchFor as Ur,cdcForkedError as Gr,cdcSeqLeavingRows as Hr,cdcTouchesTables as Or,cdcTrimmedError as Nr,compactCdcDocs as jr,cursorBelowRetainedFloor as Kr,minCdcReplayableSeq as Qr,minCdcSeq as Vr,readCdcChangeKeys as zr,readCdcChanges as Jr,readCdcCursor as Yr,readCdcEpoch as Xr,trimCdcChanges as Zr}from"./CDC_LOG_TABLE-CfILante.mjs";import{allocateCommitSeq as In,COMMIT_SEQ_FIELD as Cn}from"./COMMIT_SEQ_FIELD-BUdOMG5y.mjs";import{isMemoryTable as _t}from"./clearMemoryTables-BGbmag2i.mjs";import{computeRankPage as Rt}from"./computeRankPage-pTaG_r9F.mjs";import{SCAN_DEP as G}from"./SCAN_DEP-D7qE3iUe.mjs";import{runDrizzle as O,runSql as _e}from"./runDrizzle-2ULFQR_k.mjs";import{D as oe,k as ae,r as ue,b as Fe,A as Xe,a as qe,e as Z,o as xn,t as Kt,j as Pe,q as Tt,i as bn,h as Qt,g as Mn}from"./do-sql-kpl5Kt1j.mjs";import{renderSql as Vt,unionAll as ct,WORKERD_SQLITE_LIMITS as zt,sqliteInList as Dn}from"./param-DlozcSQu.mjs";import{coveringGeohashes as Ln,boundingBoxGeohashes as kn,haversineMeters as Fn,pointInBoundingBox as qn}from"./GEO_DEFAULT_PRECISION-CqpQZ-J_.mjs";import{NotFoundError as Bn}from"./NotFoundError-BhF7FeFr.mjs";import{softDeleteScope as le,normalizeOrderKeys as nt,uniqueIndexFields as Jt,equalityPinnedFields as Wn,buildSeekWhere as Yt,decodeCursor as ot,applySelect as vt,encodeCursor as rt,tiebreakDirectionFor as Xt,buildSeekBeforeWhere as Pn}from"./CURSOR_PREFIX-Bn8SFoGd.mjs";import{rankTableName as At,sortColumnName as It,resolveRankPartition as Un,encodePartitionKey as Gn,RANK_TIEBREAK as Hn,rankPivotConditionSql as On}from"./RANK_TIEBREAK-D5xNdzB3.mjs";import{UNVOUCHABLE_DEP as Ct}from"./UNVOUCHABLE_DEP-C68htACn.mjs";import{indexKeysForRow as Nn,buildIndexRange as jn}from"./buildIndexRange-DvN8Qj8e.mjs";import{deriveRelationEdges as Kn,findRelated as Qn}from"./RELATED_DEFAULT_LIMIT-B9PH28Pn.mjs";import{assertFlatPredicate as Ze,resolveRelationPredicates as xt}from"./DEFAULT_MAX_RELATION_KEYS-XESc7TiB.mjs";import{runRowValidators as et,resolveWith as bt,relationHooks as Mt,applyOnDelete as Vn,fanOutScalarCounts as zn}from"./applyOnDelete-7JZ4vR9r.mjs";import{guardWriter as Jn}from"./RLS_UNWRAP_SYMBOL-BwwTbz3Q.mjs";import{quoteIdentifier as Re}from"./quoteIdentifier-CObIFRhb.mjs";import{m as Yn}from"./sql-projection-D3qdaItY.mjs";import{createSystemReader as Xn}from"./createSystemReader-DcDLFfC-.mjs";import{ConflictError as me}from"./ConflictError-C8GtJmjS.mjs";import{runTriggers as Zn}from"./hasTrigger-CjlwI4le.mjs";import{c as ne,t as Ge,r as Ue,j as Se,i as Dt}from"./where-sql-x1YKldcq.mjs";import{CLIENT_WATERMARK_TABLE as ti,advanceClientWatermark as ni,migrateClientWatermark as oi,readClientWatermark as ri}from"./CLIENT_WATERMARK_TABLE-CRnrAnJ2.mjs";import{GLOBAL_SHAPE_SNAPSHOT_TABLE as si,deleteGlobalShapeSnapshot as ci,deleteGlobalShapeSnapshotsForConnection as ai,migrateGlobalShapeSnapshot as di,readGlobalShapeSnapshot as li,writeGlobalShapeSnapshot as ui}from"./GLOBAL_SHAPE_SNAPSHOT_TABLE-DSA6mzyx.mjs";import{IDEMPOTENCY_TABLE as hi,readIdempotent as wi,trimIdempotent as pi,writeIdempotent as gi}from"./IDEMPOTENCY_TABLE-DOpm_oMF.mjs";import{runShardMigrations as yi}from"./runShardMigrations-BLl8xFGK.mjs";import{S as mi}from"./ctx-db-search-state-ruTuCsxa.mjs";import{selectShapeMembers as _i,selectShapeRows as Ri}from"./selectShapeMembers-B8gTOeOB.mjs";import{serializeSqlValue as re}from"./serializeSqlValue-BEMMYX1n.mjs";const eo=o=>{const r=atob(o),t=Uint8Array.from(r,a=>a.codePointAt(0)??0);return new TextDecoder().decode(t)},to=()=>new $("BAD_REQUEST","invalid cursor"),Lt=16,kt=8,Y=1024,at=(o,r)=>r.query(o),no=(o,r)=>{if(o.length===0)return 0;let t=0;for(const[a,d]of r.entries()){const w=a===r.length-1;let S=0;for(const T of o)(w?T.startsWith(d):T===d)&&(S+=1);if(S===0)return 0;t+=S}return t},oo=(o,r)=>{if(!r)return{exact:!0,lower:o,upper:o};const t=[...o].at(-1)??"",a=(t.codePointAt(0)??0)+1;if(a>=55296&&a<=57343||a>1114111)return{exact:!0,lower:o,upper:o};const d=o.slice(0,o.length-t.length);return{exact:!1,lower:o,upper:d+String.fromCodePoint(a)}},ro=(o,r,t)=>{const a={eq:(d,w)=>{if(!o.definition.filterFields?.includes(d))throw new $("INTERNAL",`field "${d}" is not a filter field of search index "${o.indexName}" on table "${r}"`);if(o.filters.length>=kt)throw new $("BAD_REQUEST",`search index "${o.indexName}" on table "${r}": at most ${String(kt)} .eq() filters are supported per search query`);return o.filters.push({field:d,value:w}),a},search:(d,w)=>{const S=o;if(d!==S.definition.field)throw new $("INTERNAL",`search index "${S.indexName}" on table "${r}" indexes "${S.definition.field}", not "${d}"`);const T=at(w,t).length;if(T>Lt)throw new $("BAD_REQUEST",`search index "${S.indexName}" on table "${r}": at most ${String(Lt)} search terms are supported (got ${String(T)})`);return S.field=d,S.query=w,S.hasQuery=!0,a}};return a},io=o=>{if(o.length>Y)throw new $("BAD_REQUEST",`more than ${String(Y)} documents match this search — narrow it with filters or read it a page at a time with .paginate()`)},so=o=>Math.min(o.offset+o.numItems+1,Y),co=o=>btoa(`search:${String(o)}`),ao=o=>{let r;try{r=eo(o)}catch{return}if(!r.startsWith("search:"))return;const t=Number(r.slice(7));return Number.isInteger(t)&&t>=0?t:void 0},lo=o=>{if(typeof o.endCursor=="string")throw new $("BAD_REQUEST","bounded (endCursor) pagination is not supported on search queries — relevance order has no stable range boundary");if(!Number.isFinite(o.numItems))throw new $("BAD_REQUEST",`search pagination needs a finite numItems, got ${String(o.numItems)}`);const r=Math.max(0,Math.floor(o.numItems)),t=o.cursor?ao(o.cursor):0;if(t===void 0)throw to();if(t+r>=Y)throw new $("BAD_REQUEST",`search pagination reaches the ${String(Y)}-document limit (offset ${String(t)} + ${String(r)} requested) — a page must end below the cap so the probe row that answers \`hasMore\` still fits: retry with numItems ${String(Math.max(1,Y-t-1))} or fewer, or narrow the query or the filters instead`);return{numItems:r,offset:t}},uo=(o,r)=>{const t=r.offset+r.numItems,a=r.numItems>0&&o.length>t;return{continueCursor:a?co(t):null,isDone:!a,page:o.slice(r.offset,t)}},fo=o=>{if(o===void 0)return Y+1;if(!Number.isFinite(o))return Y;const r=Math.max(0,Math.floor(o));if(r>Y)throw new $("BAD_REQUEST",`search returns at most ${String(Y)} documents (asked for ${String(r)}) — narrow the query or paginate instead`);return r},He=o=>{const r=new Map;return t=>{const a=r.get(t);if(a!==void 0)return a;const d=o(Re(t));return r.set(t,d),d}},fe=Re(oe),ho=He(o=>`INSERT INTO ${o} (id, _creationTime, ${fe}) VALUES (?, ?, ?)`),Ft=He(o=>`UPDATE ${o} SET ${fe} = ? WHERE id = ? AND ${fe} = ?`),wo=He(o=>`UPDATE ${o} SET _creationTime = ?, ${fe} = ? WHERE id = ? AND ${fe} = ?`),po=He(o=>`DELETE FROM ${o} WHERE id = ? AND ${fe} = ?`),go="SELECT changes() AS changed",qt=new Map,$o="",yo=o=>{const r=JSON.stringify(o),t=qt.get(r);if(t!==void 0)return t;const a=o.map(w=>i`SELECT ${i.raw(`'${w.replaceAll("'","''")}'`)} AS __t__, id, _creationTime, ${i.identifier(oe)} FROM ${i.identifier(w)} WHERE id = ${$o}`),{sql:d}=Vt("sqlite",i`${ct(a)} LIMIT 1`);return qt.set(r,d),d},Eo=(o,r)=>r.map(()=>o),mo=/^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/iu,So=o=>{if(!mo.test(o))throw new $("INTERNAL",`invalid clientId ${JSON.stringify(o)}: a client-supplied row id must be a UUID`)},Bt=50,Zt=500,Be=Math.floor(zt.boundParams/3),ye=zt.boundParams,_o=128,de=(o,r,t)=>{const a=r??Zt;if(o>a)throw new $("BATCH_LIMIT_EXCEEDED",`${t}: batch of ${String(o)} exceeds the limit of ${String(a)} (raise options.limit or chunk the call)`,{status:400})},Ro=o=>{const r={eq:(t,a)=>(o.sqlConditions.push({comparator:"=",field:t,value:a}),r),gt:(t,a)=>(o.sqlConditions.push({comparator:">",field:t,value:a}),r),gte:(t,a)=>(o.sqlConditions.push({comparator:">=",field:t,value:a}),r),lt:(t,a)=>(o.sqlConditions.push({comparator:"<",field:t,value:a}),r),lte:(t,a)=>(o.sqlConditions.push({comparator:"<=",field:t,value:a}),r)};return r},To=o=>Math.max(o,Y),en=(o,r)=>{const t=o.filters.map(a=>i`${Z(a.field)} = ${re(a.value)}`);return r&&t.push(r),t},vo=(o,r,t,a,d)=>{const w=at(t.query,st(t.definition.language));if(w.length===0)return[];const S=gn(r,t.indexName),T=`${S}__vocab`,y=w.length-1,k=w.map((q,_)=>{const F=oo(q,_===y),j=F.exact?i`${i.identifier("term")} = ${F.lower}`:i`${i.identifier("term")} >= ${F.lower} AND ${i.identifier("term")} < ${F.upper}`;return i`SELECT ${i.identifier("doc")}, ${i.raw(String(_))} AS ${i.identifier("__term__")}, COUNT(*) AS ${i.identifier("__n__")} FROM ${i.identifier(T)} WHERE ${j} GROUP BY ${i.identifier("doc")}`}),g=w.map((q,_)=>i`SUM(CASE WHEN u.${i.identifier("__term__")} = ${i.raw(String(_))} THEN u.${i.identifier("__n__")} ELSE 0 END)`),A=i`SELECT f.${i.identifier(Le)} AS ${i.identifier(Le)}, ${i.join(g,i` + `)} AS ${i.identifier("__score__")} FROM (${ct(k)}) u JOIN ${i.identifier(S)} f ON f.rowid = u.${i.identifier("doc")} GROUP BY f.${i.identifier(Le)} HAVING ${i.join(g.map(q=>i`${q} > 0`),i` AND `)}`,I=en(t,d);let L=i`SELECT m.id, m._creationTime, m.${i.identifier(oe)}, s.${i.identifier("__score__")} AS ${i.identifier("__score__")} FROM (${A}) s JOIN ${i.identifier(r)} m ON m.id = s.${i.identifier(Le)}`;I.length>0&&(L=i`${L} WHERE ${i.join(I,i` AND `)}`),L=i`${L} ORDER BY s.${i.identifier("__score__")} DESC, m._creationTime DESC, m.id ASC LIMIT ${i.raw(String(a))}`;const N=[];for(const q of O(o,L)){const _=Qt(q);if(_){const F=q.__score__;N.push({document:_,score:typeof F=="number"?F:Number(F??0)})}}return N},Ao=(o,r,t,a,d)=>{const w=st(t.definition.language),S=at(t.query,w);if(S.length===0)return[];const T=en(t,d);let y=i`SELECT id, _creationTime, ${i.identifier(oe)} FROM ${i.identifier(r)}`;T.length>0&&(y=i`${y} WHERE ${i.join(T,i` AND `)}`),y=i`${y} ORDER BY _creationTime DESC, id ASC LIMIT ${i.raw(String(To(a)))}`;const k=O(o,y).toArray(),g=[];for(const A of k){const I=Qt(A);if(!I)continue;const L=no($n(I,t.definition),S);L>0&&g.push({creationTime:typeof I._creationTime=="number"?I._creationTime:0,doc:I,id:typeof I._id=="string"?I._id:"",score:L})}return g.sort((A,I)=>I.score-A.score||I.creationTime-A.creationTime||A.id.localeCompare(I.id)),g.slice(0,a).map(A=>({document:A.doc,score:A.score}))},tt=(o,r,t,a)=>{if(!Number.isFinite(o.lat)||o.lat<-90||o.lat>90||!Number.isFinite(o.lng)||o.lng<-180||o.lng>180)throw new $("BAD_REQUEST",`geo index "${a}" on table "${t}": ${r} must have a finite lat in [-90, 90] and lng in [-180, 180]`)},Io=(o,r)=>{const t=o,a={near:(d,w)=>{if(t.within)throw new $("INTERNAL",`geo index "${t.indexName}" on table "${r}": call .near() or .within(), not both`);if(tt(d,".near() point",r,t.indexName),!Number.isFinite(w)||w<=0)throw new $("BAD_REQUEST",`geo index "${t.indexName}" on table "${r}": .near() radiusMeters must be a finite number > 0, got ${String(w)}`);return t.near={point:{lat:d.lat,lng:d.lng},radiusMeters:w},a},within:d=>{if(t.near)throw new $("INTERNAL",`geo index "${t.indexName}" on table "${r}": call .near() or .within(), not both`);if(tt(d.sw,".within() sw corner",r,t.indexName),tt(d.ne,".within() ne corner",r,t.indexName),d.sw.lat>d.ne.lat)throw new $("BAD_REQUEST",`geo index "${t.indexName}" on table "${r}": .within() corners are transposed (sw.lat > ne.lat)`);if(d.sw.lng>d.ne.lng)throw new $("BAD_REQUEST",`geo index "${t.indexName}" on table "${r}": .within() box crosses the antimeridian (sw.lng > ne.lng), which is not supported — split it into two boxes at ±180 and union the results`);return t.within={ne:{lat:d.ne.lat,lng:d.ne.lng},sw:{lat:d.sw.lat,lng:d.sw.lng}},a}};return a},Co=(o,r)=>{const t=o[r];if(t===null||typeof t!="object")return;const{lat:a,lng:d}=t;return typeof a=="number"&&typeof d=="number"?{lat:a,lng:d}:void 0},xo=(o,r)=>{const t=Co(o,r.definition.field);if(!t)return;const a=typeof o._creationTime=="number"?o._creationTime:0;if(r.near){const d=Fn(r.near.point,t);return d<=r.near.radiusMeters?{creationTime:a,distance:d}:void 0}return qn(t,r.within)?{creationTime:a,distance:0}:void 0},bo=(o,r,t,a)=>{if(!t.near&&!t.within)throw new $("INTERNAL",`geo index "${t.indexName}" on table "${r}": call .near(point, radius) or .within(box)`);const d=t.near?Ln(t.near.point,t.near.radiusMeters):kn(t.within),w=Mn(r,t.indexName),S=d.map(A=>i`(g.${i.identifier("__geohash__")} >= ${A} AND g.${i.identifier("__geohash__")} < ${`${A}{`})`),T=[i`(${i.join(S,i` OR `)})`];a&&T.push(a);const y=i`SELECT m.id, m._creationTime, m.${i.identifier(oe)} FROM ${i.identifier(w)} g JOIN ${i.identifier(r)} m ON m.id = g.${i.identifier("__id__")} WHERE ${i.join(T,i` AND `)}`,k=O(o,y).toArray(),g=[];for(const A of k){const I=ue(A),L=I?xo(I,t):void 0;I&&L&&g.push({creationTime:L.creationTime,distance:L.distance,doc:I})}return g.sort((A,I)=>A.distance-I.distance||I.creationTime-A.creationTime),g},tn=(o,r,t,a)=>{const d=[];for(const w of o)if(r.every(S=>S(a(w)))&&(d.push(w),typeof t=="number"&&d.length>=t))break;return d},Mo=(o,r,t,a,d,w=()=>{})=>{const S=t.within!==void 0,T=bo(o,r,t,d).map(y=>({distanceMeters:S?null:y.distance,document:y.doc}));return w(T.length),typeof a=="number"?T.slice(0,Math.max(0,Math.floor(a))):T},nn=(o,r,t,a,d,w=()=>{})=>{const{geo:S}=t;if(!S)throw new $("INTERNAL","runGeoTerminalScored called without a staged geo query");const T=t.inMemoryFilters.length>0,y=Mo(o,r,S,T?void 0:d,a,w);return T?tn(y,t.inMemoryFilters,d,k=>k.document):y},on=(o,r,t,a)=>{const d=`SELECT id, _creationTime, ${Re(oe)} FROM ${Re(o)}`,w=`ORDER BY ${t}${a===void 0?"":` LIMIT ${String(a)}`}`;return r===void 0?Ue(`${d} ${w}`):Se(`${d} WHERE `,r,` ${w}`)},Do=(o,r,t,a,d,w=()=>{})=>nn(o,r,t,a,d,w).map(S=>S.document),Lo=(o,r,t,a,d,w,S=()=>{})=>{const T=[];for(const A of t.sqlConditions)T.push(i`${Z(A.field)} ${i.raw(A.comparator)} ${re(A.value)}`);a&&T.push(a);let y=i`SELECT id, _creationTime, ${i.identifier(oe)} FROM ${i.identifier(r)}`;T.length>0&&(y=i`${y} WHERE ${i.join(T,i` AND `)}`),y=i`${y} ORDER BY ${d}`,typeof w=="number"&&t.inMemoryFilters.length===0&&(y=i`${y} LIMIT ${i.raw(String(Math.max(0,Math.floor(w))))}`);const k=O(o,y).toArray();S(k.length);const g=[];for(const A of k){const I=ue(A);if(I&&t.inMemoryFilters.every(L=>L(I))&&(g.push(I),typeof w=="number"&&g.length>=w))break}return g},Ee={fieldRef:Z,serialize:re},rn=(o,r)=>{const t=r===void 0?void 0:o.shape[r];return t!==void 0&&Yn(t)},Wt=(o,r)=>r.some(t=>rn(o,t)),Pt=(o,r,t)=>{if(rn(o,r))throw new $("BAD_REQUEST",`${t}: "${r}" may hold an order-preserving key rather than a value SQL can reduce or group — declare an aggregateIndex covering this (by, field, op) so the maintained companion answers it instead (its running total is a REAL, so it stays exact only while the total is inside 2^53)`)},dt={fieldRef:o=>Ue(Pe(o)),serialize:re},ko=o=>{let r=0;const t=[],a={fieldRef:d=>Ue(Pe(d)),relationExists:d=>{const{childWhere:w,negated:S,parentTable:T,relation:y}=d,k=`__rel_${String(r)}`,g=t.at(-1)??T;r+=1,o(y.table,G);const A=y.kind==="one"?y.field:y.references,I=y.kind==="one"?y.references:y.field,L=Ue(`${Tt(k,I)} = ${Tt(g,A)}`);t.push(k);const N=ne(w,a,Ge);t.pop();const q=N===void 0?L:Se(L," AND ",N),_=Se("EXISTS (SELECT 1 FROM ",Dt(y.table)," AS ",Dt(k)," WHERE ",q,")");return S?Se("NOT ",_):_},serialize:re};return a},sn=o=>{const r=o.map(t=>`${Pe(t.field)} ${t.direction==="desc"?"DESC":"ASC"}`);return o.some(t=>t.field==="_id"||t.field==="id")||r.push(`${Pe("id")} ${Xt(o)==="desc"?"DESC":"ASC"}`),r.join(", ")},Fo=o=>{const r=o.map(t=>i`${Z(t.field)} ${i.raw(t.direction==="desc"?"DESC":"ASC")}`);return o.some(t=>t.field==="_id"||t.field==="id")||r.push(i`${Z("id")} ${i.raw(Xt(o)==="desc"?"DESC":"ASC")}`),i.join(r,i`, `)},qo={"<":"lt","<=":"lte","=":"eq",">":"gt",">=":"gte"},cn=o=>new Set(o.sqlConditions.filter(r=>r.comparator==="=").map(r=>r.field)),Bo=o=>{const r=cn(o);let t=0;for(;t<o.indexFields.length&&r.has(o.indexFields[t]??"");)t+=1;return o.indexFields.slice(t)},an=(o,r)=>{const t=o.order,a=Bo(o),{shape:d}=r;return a.length>0?nt(a.map(w=>({[w]:t})),d,{pinned:cn(o),uniqueBy:Jt(r.indexes,d)}):nt([{_creationTime:t}],d)},Wo=(o,r,t,a)=>{const d=o.sqlConditions.map(w=>({[w.field]:{[qo[w.comparator]??"eq"]:w.value}}));if(t&&d.push(Yt(r,ot(t))),a&&d.push(Pn(r,ot(a))),d.length!==0)return d.length===1?d[0]:{AND:d}},Po=(o,r,t)=>{const a=[];for(const d of o){const w=ue(d);if(w&&r.every(S=>S(w))&&(a.push(w),t!==void 0&&a.length>t))break}return a},Uo=(o,r,t,a,d,w,S=()=>{})=>{const T=Math.max(0,Math.floor(d.numItems)),y=an(a,t),k=typeof d.endCursor=="string",g=ne(Wo(a,y,d.cursor,d.endCursor),dt,Ge),A=w&&g?Se(g," AND ",w):w??g,I=a.inMemoryFilters.length>0,L=on(r,A,sn(y),I||k?void 0:T+1),N=_e(o,L.text,...L.params).toArray();S(N.length);const q=Po(N,a.inMemoryFilters,I||k?void 0:T);if(k){const H=q.length>=2?q[Math.floor(q.length/2)-1]:void 0;return{continueCursor:d.endCursor??null,isDone:!0,page:q,splitCursor:H?rt(H,y):null}}const _=q.length>T,F=_?q.slice(0,T):q,j=F.at(-1);return{continueCursor:_&&j?rt(j,y):null,isDone:!_,page:F}};class Go extends ${constructor(r="unique() found more than one matching document"){super("NOT_UNIQUE",r,{name:"NotUniqueError"})}}const Ho=/\s/u,Oo=String.fromCodePoint(0),Ut=(o,r,t)=>{if(!o.tables[r])throw new $("INTERNAL",`unknown table: ${r}`);return typeof t!="string"||t.length===0||Ho.test(t)||t.includes(Oo)?null:t},No=(o,r,t,a=()=>{},d=()=>{},w=()=>{})=>{const S=r.tables[t];if(!S)throw new $("INTERNAL",`unknown table: ${t}`);const T=le(S.softDeleteMode,void 0),y=T?ne(T,Ee):void 0,k=T?ne(T,dt,Ge):void 0,g={indexFields:[],indexName:void 0,inMemoryFilters:[],order:"asc",sqlConditions:[]};let A=0;const I=E=>{const{search:x}=g;if(!x)throw new $("INTERNAL","runSearchFetch called without a staged search");Tn(o,t,S);const b=g.inMemoryFilters.length>0,D=fo(b?void 0:E),z=bn(o);if(z&&!vn(o,t,x.definition))throw new $("SEARCH_INDEX_BUILDING",`search index "${x.indexName}" on table "${t}" is still backfilling and currently covers only part of the table — retry once it finishes, or run the backfillSearch admin operation to complete it now`);const X=z?vo(o,t,x,D,y):Ao(o,t,x,D,y);return b?(A=X.length,tn(X,g.inMemoryFilters,E,ce=>ce.document)):(E===void 0&&io(X),X)},L=E=>I(E).map(x=>x.document),N=E=>{const x=lo(E);return uo(L(so(x)),x)},q=()=>Fo(an(g,S)),_=()=>{if(g.search||g.geo||g.indexName===void 0){d(void 0);return}d(jn(t,g.indexName,g.indexFields,g.sqlConditions,re))},F=E=>{_();let x=0;const b=(()=>{if(g.search){const D=L(E);return x=A,D}return g.geo?Do(o,t,g,y,E,D=>{x=D}):Lo(o,t,g,y,q(),E,D=>{x=D})})();return w(Math.max(x,b.length)),b},j=()=>{if(!g.search&&!g.geo)throw new $("INTERNAL",`ctx.db.query("${t}").collectWithScores() requires a staged .withSearchIndex(...) or .withGeoIndex(...)`);_();let E=0;const x=(()=>{if(g.search){const b=I(void 0);return E=A,b}return nn(o,t,g,y,void 0,b=>{E=b})})();return w(Math.max(E,x.length)),x},H={async*[Symbol.asyncIterator](){if(g.search){yield*F(void 0);return}const E=[...g.inMemoryFilters];let x;g.inMemoryFilters=[];try{for(;;){const b=await H.paginate({cursor:x??null,numItems:_o});for(const D of b.page)E.every(z=>z(D))&&(yield D);if(b.isDone||b.continueCursor===null)return;x=b.continueCursor}}finally{g.inMemoryFilters=E}},async collect(){return F(void 0)},async collectWithScores(){return j()},filter(E){return g.inMemoryFilters.push(E),H},async first(){return F(g.inMemoryFilters.length>0?void 0:1)[0]??null},order(E){return g.order=E==="desc"?"desc":"asc",H},async paginate(E){let x=0;if(_(),g.search){const D=N(E);return w(D.page.length),D}if(g.geo)throw new $("INTERNAL","pagination is not supported on geo queries; use .take(n) or .collect()");const b=Uo(o,t,S,g,E,k,D=>{x=D});return w(Math.max(x,b.page.length)),b},async take(E){return F(E)},async unique(){const E=F(g.inMemoryFilters.length>0?void 0:2);if(E.length>1)throw new Go(`unique() on table "${t}" matched ${String(E.length)} documents; expected at most one`);return E[0]??null},withGeoIndex(E,x){const b=(S.geoIndexes??[]).find(z=>z.name===E);if(!b)throw new $("INTERNAL",`unknown geo index "${E}" on table "${t}"`);a(t,E,"geo");const D={definition:b,indexName:E};if(g.geo=D,x(Io(D,t)),!D.near&&!D.within)throw new $("INTERNAL",`geo index "${E}" on table "${t}" requires a .near(point, radius) or .within(box) call`);return H},withIndex(E,x){const b=S.indexes.find(D=>D.name===E);if(!b)throw new $("INTERNAL",`unknown index "${E}" on table "${t}"`);return a(t,E,"index"),g.indexName=E,g.indexFields=b.fields,x&&x(Ro(g)),H},withSearchIndex(E,x){const b=(S.searchIndexes??[]).find(z=>z.name===E);if(!b)throw new $("INTERNAL",`unknown search index "${E}" on table "${t}"`);a(t,E,"search");const D={definition:b,field:b.field,filters:[],hasQuery:!1,indexName:E,query:""};if(g.search=D,x(ro(D,t,st(b.language))),!D.hasQuery)throw new $("INTERNAL",`search index "${E}" on table "${t}" requires a .search(field, query) call`);return H}};return H},Gt=(o,r,t)=>{const a={...r};for(const[d,w]of Kt(o)){if(w.serverDefault){a[d]=w.serverDefault({auth:t});continue}a[d]===void 0&&(w.defaultFn?a[d]=w.defaultFn():"defaultValue"in w&&(a[d]=w.defaultValue))}return a},Ht=(o,r,t,a)=>{const d=t;for(const[w,S]of Kt(o)){if(S.serverDefault){w in r&&(d[w]=S.serverDefault({auth:a}));continue}S.onUpdateFn&&!(w in r)&&(d[w]=S.onUpdateFn())}},Ot=(o,r)=>{for(const t of Object.keys(r))if(r[t]===void 0)throw new $("INTERNAL",`Cannot ${o} field '${t}' to undefined — use null to clear a nullable field, or omit the key to leave it unchanged.`)},Nt=["_commitSeq","_creationTime","_id"],jo=o=>Nt.some(r=>r in o)?Object.fromEntries(Object.entries(o).filter(([r])=>!Nt.includes(r))):o,Ko=/unique constraint failed/i,Qo=o=>o instanceof Error&&Ko.test(o.message),Vo=/string or blob too big/iu,zo=(o,r)=>{if(!(!(o instanceof Error)||!Vo.test(o.message)))throw new $("PAYLOAD_TOO_LARGE",`document is too large to store in "${r}": a single row cannot exceed the storage engine's per-row ceiling (2 MB on a Durable Object's SQLite). The limit is on the STORED bytes, which are UTF-8, and v.bytes()/v.bigint() columns are stored twice on a shard-local table. Keep the payload in R2 (ctx.storage) and store a reference on the row.`)},it=(o,r,t,a)=>{try{_e(o,t,...a)}catch(d){throw Qo(d)?new me(`unique constraint violation on "${r}"`,"unique"):(zo(d,r),d)}},We=(o,r,t,a)=>{if(it(o,r,t,a),_e(o,go).one().changed===0)throw new me(`optimistic concurrency conflict on "${r}" — the row changed during this mutation; refetch and retry`,"occ")},jt=(o,r,t,a,d,w,S)=>{const T=[];for(let A=0;A<t.length+1;A+=1){const I=t[A],L=a[A],N=L?.direction==="desc"?"desc":"asc",q=I===void 0||L===void 0?i`${i.identifier(Hn)} < ${S}`:On(I,w[A],N,!1);if(q===void 0)continue;const _=[];for(let j=0;j<A;j+=1)_.push(i`${i.identifier(t[j])} IS ${w[j]}`);_.push(q);const[F]=_;T.push(_.length===1&&F!==void 0?F:i`(${i.join(_,i` AND `)})`)}const y=T.length>0?i.join(T,i` OR `):i`1 = 0`,k=O(o,i`SELECT COUNT(*) AS c FROM ${i.identifier(r)} WHERE ${i.identifier("__partition__")} = ${d} AND (${y})`).one(),g=O(o,i`SELECT COUNT(*) AS c FROM ${i.identifier(r)} WHERE ${i.identifier("__partition__")} = ${d}`).one();return{before:k.c,total:g.c}},br=o=>{const{sql:r}=o,{schema:t}=o,a=o.broadcast??(()=>{}),d=Kn(t);let w;const S=()=>o.inTransaction?.()===!0,T=e=>t.tables[e]?.commitOrderedMode!==!0?{}:((w===void 0||!S())&&(w=In(r)),{[Cn]:w}),y=(e,...n)=>{const s=t.tables[e]?.indexes;if(!s||s.length===0)return;const f=[];for(const h of n)h&&f.push(...Nn(s,h,re));return f.length>0?f:void 0},{headroom:k}=o;let g=!1;const A=async e=>{const n=g;g=!0;try{return await e()}finally{g=n}},I=o.onRead??(()=>{}),L=e=>{_t(t.tables[e])&&I(Ct,Ct)},N=o.onReadRange??(e=>{I(e.table,G)}),q=e=>{L(e.table),N(e)},_=(e,n)=>{n!==void 0&&n!==G&&!g&&k?.recordRead(1),L(e),I(e,n)},F=o.onIndexUse??(()=>{}),j=o.onWrite??(()=>{}),H=e=>{g||k?.recordWrite(e)},E=async e=>{H(e.doc),await j(e)},{cache:x}=o,b=o.clock??(()=>Date.now()),D=o.idGenerator??(()=>crypto.randomUUID()),z=o.scheduler??En,{globalDb:X}=o,ce=o.auth??{identity:null,userId:null},dn=o.cdc??!1,Oe=z,ln=Xn({scheduler:typeof Oe.list=="function"&&typeof Oe.get=="function"?Oe:void 0,storage:o.storage}),he=(e,n,s,f)=>{dn&&!_t(t.tables[e])&&An(r,b(),e,n,s,f)},ie=e=>t.tables[e]?.shardMode?.kind==="global",lt=(e,n)=>{if(ie(e)){if(!X)throw new $("INTERNAL",`cross-backend ${n} for global table '${e}' requires a globalDb writer — pass one to createShardCtxDb({ globalDb })`);return X}return P},Ne=e=>lt(e,"cascade"),Q=(e,n)=>{if(ie(e)){if(!X)throw new $("INTERNAL",`${n} on global table '${e}' requires a globalDb writer — pass one to createShardCtxDb({ globalDb })`);return X}},ut=async(e,n,s,f,h)=>{h&&H(s);const u=await e.insert(n,s,f);return a({key:u,op:"insert",row:{...s,_id:u},table:n}),u},je=(e,n)=>lt(e,"relation load").findMany(e,n),ft=(e,n)=>(ie(e)&&_(e,G),je(e,n)),un=e=>!ie(e.table),ht=o.relationExistsPushDown??"auto",wt=ht!=="never",{maxRelationKeys:pt}=o,Te=(e,n,s)=>xt(e,{fetcher:ft,maxRelationKeys:pt,relationBaseWhere:s,schema:t,tableName:n}),gt=async(e,n,s,f)=>{const h=Q(e,"relation grouped count");if(h)return _(e,G),zn((W,C)=>h.count(W,C),e,n,s,f);const u=t.tables[e];if(!u)throw new $("INTERNAL",`unknown table: ${e}`);_(e,G);const c=le(u.softDeleteMode,void 0),l={[n]:{in:s}},p=V(V(l,f),c),v=await Te(p,e,void 0),m=ne(v,Ee),M=Z(n);let R=i`SELECT ${M} AS __fk__, COUNT(*) AS count FROM ${i.identifier(e)}`;m&&(R=i`${R} WHERE ${m}`),R=i`${R} GROUP BY ${M}`;const B=O(r,R).toArray();return new Map(B.map(W=>[W.__fk__,W.count]))};let ve=0;const $t=new Set;for(const[e,n]of Object.entries(t.tables))for(const s of Object.values(n.triggerMap??{}))$t.add(`${e} ${s.timing} ${s.op}`);const ee=(e,n,s)=>$t.has(`${e} ${n} ${s}`),te=async(e,n,s)=>{if(ve+=1,ve>Bt)throw ve-=1,new me(`trigger recursion exceeded ${String(Bt)} levels on "${s.table}" — check for a self-triggering write`,"trigger");try{await Zn({ctx:hn,event:s,op:n,schema:t,tableName:s.table,timing:e})}finally{ve-=1}},{ensureBackfilledForTable:we,ensureBackfilledIndex:Ke,ensureRankBackfilled:Qe,ensureRankBackfilledForTable:pe,syncAggregates:Ae,syncCompanionsForInsert:yt,syncGeo:Ie,syncRanks:ge,syncSearch:Ce}=pn({broadcast:a,indexKeysFor:(e,n)=>y(e,n),invalidateCache:(e,n,s)=>x?.invalidate(e,n,y(e,s)),recordCdc:he,schema:t,sql:r}),Et=(e,n,s)=>{const{shardMode:f}=n;if(f?.kind==="shardBy"&&!(f.field!==void 0&&(s.partitionBy??[]).includes(f.field)))throw Object.assign(new Error(`rank index "${s.name}" on "${e}" partitions across shards (shard key "${f.field??"?"}" is not in partitionBy) — a shard-local rank()/rankPage() would be wrong; roll it up through the Query Coordinator instead`),{code:"CROSS_SHARD_RANK_UNSUPPORTED",name:"LunoraError",status:400})},mt=e=>Object.entries(t.tables).filter(([,n])=>n.shardMode?.kind!=="global").map(([n])=>n).filter(n=>e===void 0||n===e),$e=e=>e===void 0||ie(e)?X:void 0,se=(e,n)=>{const s=mt(n);for(let f=0;f<s.length;f+=ye){const h=s.slice(f,f+ye),[u]=_e(r,yo(h),...Eo(e,h)).toArray();if(!u)continue;const c=u.__t__,l=ue(u);if(typeof c!="string"||!l)return;const p=u[oe];return{docJson:typeof p=="string"?p:ae(p??{}),row:l,tableName:c}}},fn=(e,n)=>{const s=[...new Set(e)],f=new Map;if(s.length===0)return f;const h=mt(n);for(let u=0;u<h.length;u+=ye){const c=h.slice(u,u+ye),l=Math.floor(ye/c.length),p=Dn(i`${i.identifier("id")}`,s,!1,l),v=c.map(m=>i`SELECT ${i.raw(`'${m.replaceAll("'","''")}'`)} AS __t__, id FROM ${i.identifier(m)} WHERE ${p}`);for(const m of O(r,ct(v))){const{id:M,__t__:R}=m;typeof R=="string"&&typeof M=="string"&&f.set(M,R)}}return f},St={assertRankPartitionLocal:Et,ensureRankBackfilled:Qe,onRead:_,rowToDocument:ue,schema:t,sql:r},P={system:ln,async aggregate(e,n){const s=Q(e,"aggregate");if(s)return _(e,G),s.aggregate(e,n);const f=t.tables[e];if(!f)throw new $("INTERNAL",`unknown table: ${e}`);if(ke(n.op),n.op==="count")return P.count(e,{baseWhere:n.baseWhere,relationBaseWhere:n.relationBaseWhere,restrictsCounts:n.restrictsCounts,where:n.where});if(!n.field)throw new $("INTERNAL",`aggregate(${e}, { op: "${n.op}" }): "field" is required for non-count reducers`);_(e,G);const h=le(f.softDeleteMode,void 0),u=V(V(n.baseWhere,n.where),h),c=await Te(u,e,n.relationBaseWhere),l=c!==u;if(f.aggregateIndexes&&!n.baseWhere&&!l&&(!h||Wt(f,[n.field]))){const W=Rn(f.aggregateIndexes,n.op,n.field,n.where);if(W){Ke(e,W.index);const C=ze(W.index.by??[],W.key),K=Ve(e,W.index.name),J=O(r,i`SELECT ${Fe} AS value, ${Xe} AS count FROM ${i.identifier(K)} WHERE ${qe} = ${C}`).toArray()[0];return Je(n.op,J)}}Pt(f,n.field,`aggregate(${e}, { op: "${n.op}", field: "${n.field}" })`);const p=ne(c,Ee),v=ke(n.op),m=Z(n.field);let M=i`SELECT ${i.raw(v)}(${m}) AS value FROM ${i.identifier(e)}`;p&&(M=i`${M} WHERE ${p}`);const B=O(r,M).toArray()[0]?.value;return B??null},asId(e,n){const s=Ut(t,e,n);if(s===null)throw new $("BAD_REQUEST",`asId("${e}", …): "${n}" is not a valid id for table "${e}"`,{status:400});return s},async count(e,n){const s=Q(e,"count");if(s)return _(e,G),s.count(e,n);const f=t.tables[e];if(!f)throw new $("INTERNAL",`unknown table: ${e}`);const h=mn(n);if(h.restrictsCounts)throw new Ye(e);_(e,G);const u=le(f.softDeleteMode,void 0),c=V(V(h.baseWhere,h.where),u),l=await Te(c,e,h.relationBaseWhere),p=l!==c;if(f.aggregateIndexes&&!h.baseWhere&&!p&&!u){const R=_n(f.aggregateIndexes,h.where);if(R){Ke(e,R.index);const B=ze(R.index.by??[],R.key),W=Ve(e,R.index.name),C=O(r,i`SELECT ${Fe} AS value FROM ${i.identifier(W)} WHERE ${qe} = ${B}`).toArray();return C[0]===void 0?0:C[0].value??0}}const v=ne(l,Ee);let m=i`SELECT COUNT(*) AS count FROM ${i.identifier(e)}`;return v&&(m=i`${m} WHERE ${v}`),O(r,m).one().count},async delete(e,n,s){const f=se(e,n);if(!f){const m=$e(n);m&&(H(void 0),await m.delete(e,n,s));return}const{docJson:h,row:u,tableName:c}=f,l=t.tables[c],p=s?.hard===!0,v=!p&&l?.softDeleteMode?l.softDeleteMode.field:void 0;if(!(v&&u[v]!==null&&u[v]!==void 0)){if(ee(c,"before","delete")&&await te("before","delete",{id:e,op:"delete",previous:u,table:c}),await Vn({deletedId:e,deletedReference:m=>u[m],findHolders:async(m,M,R)=>(await Ne(m).findMany(m,{includeDeleted:p,where:{[M]:R}})).page,onCascade:(m,M)=>Ne(m).delete(M,void 0,s),onRestrict:m=>{throw new me(m,"restrict")},onSetNull:(m,M,R)=>Ne(m).patch(M,{[R]:null}),schema:t,tableName:c}),we(c),pe(c),v){const m={...u,...T(c),[v]:b(),_id:e};We(r,c,Ft(c),[ae(m),e,h]),Ce(c,e,m,u),Ie(c,e,void 0),Ae(c,u,m),ge(c,e,u,void 0),x?.invalidate(c,e,y(c,u,m)),he(c,e,"update",m),a({indexKeys:y(c,u,m),key:e,op:"update",row:m,table:c}),ee(c,"after","delete")&&await te("after","delete",{id:e,op:"delete",previous:u,table:c}),await E({id:e,op:"delete",table:c});return}We(r,c,po(c),[e,h]),Ce(c,e,void 0),Ie(c,e,void 0),Ae(c,u,void 0),ge(c,e,u,void 0),x?.invalidate(c,e,y(c,u)),he(c,e,"delete"),a({indexKeys:y(c,u),key:e,op:"delete",table:c}),ee(c,"after","delete")&&await te("after","delete",{id:e,op:"delete",previous:u,table:c}),await E({id:e,op:"delete",table:c})}},async deleteAll(e,n){if(!t.tables[e])throw new $("INTERNAL",`unknown table: ${e}`);const s=Math.max(1,n?.chunkSize??Zt),f=n?.hard===void 0?void 0:{hard:n.hard},h=ie(e)?void 0:e;let u=0;return await A(async()=>{for(;;){const l=(await P.findMany(e,{limit:s})).page.map(p=>String(p._id));if(l.length===0)break;for(const p of l)await P.delete(p,h,f),u+=1;if(l.length<s)break}}),{deleted:u}},async deleteMany(e,n,s){de(e.length,n?.limit,"deleteMany");for(const f of e)await P.delete(f,s);return{deleted:e.length}},async deleteWhere(e,n,s){const u=(await(Q(e,"deleteWhere")??P).findMany(e,{where:n})).page.map(c=>String(c._id));if(de(u.length,s?.limit,"deleteWhere"),P.deleteMany===void 0)throw new $("INTERNAL",`ctx.db.${e}.deleteMany is unavailable: this writer has no batch delete`);return P.deleteMany(u,s)},async findFirst(e,n={}){return(await P.findMany(e,{...n,limit:1,omitContinueCursor:!0})).page[0]??null},async findFirstOrThrow(e,n={}){const s=await P.findFirst(e,n);if(s===null)throw new Bn(`findFirstOrThrow: no "${e}" document matched`);return s},async findMany(e,n={}){const s=Q(e,"findMany");if(s)return _(e,G),s.findMany(e,n);const f=t.tables[e];if(!f)throw new $("INTERNAL",`unknown table: ${e}`);const h=!n.where&&!n.baseWhere;h?_(e,G):_(e);const u=nt(n.orderBy,f.shape,{pinned:Wn(n.where),uniqueBy:Jt(f.indexes,f.shape)}),c=n.cursor?Yt(u,ot(n.cursor)):void 0;let l=V(n.baseWhere,n.where);l=V(l,le(f.softDeleteMode,n.includeDeleted)),l=await xt(l,{canPushExists:wt?un:void 0,existsPushMode:ht==="always"?"always":"auto",fetcher:ft,maxRelationKeys:pt,relationBaseWhere:n.relationBaseWhere,schema:t,tableName:e}),c&&(l=l?{AND:[l,c]}:c);const p=wt?ko(_):dt,v=ne(l,p,Ge),m=typeof n.limit=="number"?Math.max(0,Math.floor(n.limit)):void 0,M=on(e,v,sn(u),m===void 0?void 0:m+1),R=_e(r,M.text,...M.params).toArray();h&&!g&&k?.recordRead(R.length);const B=[];for(const J of R){const U=ue(J);U&&(B.push(U),!h&&typeof U._id=="string"&&_(e,U._id))}if(m===void 0)return n.with&&await bt({groupedCounter:gt,fetcher:je,parents:B,...Mt(n),schema:t,tableName:e,with:n.with}),{continueCursor:null,isDone:!0,page:vt(B,n.select,n.with)};const W=B.length>m,C=W?B.slice(0,m):B,K=C.at(-1);return n.with&&await bt({fetcher:je,groupedCounter:gt,parents:C,...Mt(n),schema:t,tableName:e,with:n.with}),{continueCursor:W&&K&&n.omitContinueCursor!==!0?rt(K,u):null,isDone:!W,page:vt(C,n.select,n.with)}},async get(e,n){const s=se(e,n);if(!s){const f=$e(n);return f?f.get(e,n):null}return _(s.tableName,e),s.row},async lookupById(e,n){const s=se(e,n);return s?(_(s.tableName,e),{row:s.row,tableName:s.tableName}):null},async groupBy(e,n){const s=Q(e,"groupBy");if(s)return _(e,G),s.groupBy(e,n);const f=t.tables[e];if(!f)throw new $("INTERNAL",`unknown table: ${e}`);_(e,G);const h=n.agg??{op:"count"};if(ke(h.op),h.op!=="count"&&!h.field)throw new $("INTERNAL",`groupBy(${e}, { agg: { op: "${h.op}" } }): "field" is required for non-count reducers`);const u=le(f.softDeleteMode,void 0),c=V(V(n.baseWhere,n.where),u),l=await Te(c,e,n.relationBaseWhere),p=l!==c,v=[...n.by,h.field];if(f.aggregateIndexes&&!n.baseWhere&&!p&&(!u||Wt(f,v))){const C=Sn(f.aggregateIndexes,h.op,h.field,n.by,n.where),K=C===void 0?0:Object.keys(C.partial).length,J=C?.index.by?.length??0;if(C&&(K===0||K===J)){Ke(e,C.index);const U=Ve(e,C.index.name),xe=Object.keys(C.partial),be=[];if(xe.length===(C.index.by??[]).length&&xe.length>0){const Me=ze(C.index.by??[],C.partial),De=O(r,i`SELECT ${Fe} AS value, ${Xe} AS count FROM ${i.identifier(U)} WHERE ${qe} = ${Me}`).toArray();return De.length>0&&be.push({key:{...C.partial},value:Je(h.op,De[0])}),be}const wn=O(r,i`SELECT ${qe} AS key, ${Fe} AS value, ${Xe} AS count FROM ${i.identifier(U)}`).toArray();for(const Me of wn){const De=yn(JSON.parse(Me.key));be.push({key:De,value:Je(h.op,Me)})}return be}}for(const C of v){if(C===void 0)continue;const K=C===h.field?`groupBy(${e}, { agg: { op: "${h.op}", field: "${C}" } })`:`groupBy(${e}, { by: [..."${C}"] })`;Pt(f,C,K)}const m=ne(l,Ee),M=n.by.map(C=>i`${Z(C)} AS ${i.identifier(C)}`);if(h.op==="count")M.push(i`COUNT(*) AS value`);else{const{field:C}=h;if(C===void 0)throw new $("INTERNAL",`groupBy(${e}, { agg: { op: "${h.op}" } }): "field" is required for non-count reducers`);M.push(i`${i.raw(ke(h.op))}(${Z(C)}) AS value`)}let R=i`SELECT ${i.join(M,i`, `)} FROM ${i.identifier(e)}`;m&&(R=i`${R} WHERE ${m}`),R=i`${R} GROUP BY ${i.join(n.by.map(C=>Z(C)),i`, `)}`;const B=O(r,R).toArray(),W=[];for(const C of B){const K={};for(const U of n.by)K[U]=xn(f.shape[U],C[U]??null);const{value:J}=C;W.push({key:K,value:J==null?null:Number(J)})}return W},async insert(e,n,s){const f=Q(e,"insert");if(f)return ut(f,e,n,s,!0);const h=t.tables[e];if(!h)throw new $("INTERNAL",`unknown table: ${e}`);const u=Gt(h,n,ce);et(h,u);let c;s?.clientId!==void 0?(So(s.clientId),c=s.clientId):s?.allowExplicitId&&typeof u._id=="string"?c=u._id:c=D();const l=s?.allowExplicitId&&typeof u._creationTime=="number"?u._creationTime:b(),p={...u,...T(e),_creationTime:l,_id:c};return ee(e,"before","insert")&&await te("before","insert",{doc:{...p},id:c,op:"insert",table:e}),we(e),pe(e),it(r,e,ho(e),[c,l,ae(p)]),yt(e,c,p),ee(e,"after","insert")&&await te("after","insert",{doc:p,id:c,op:"insert",table:e}),await E({doc:p,id:c,op:"insert",table:e}),c},async insertManyUnsafe(e,n,s){if(de(n.length,s?.limit,"insertManyUnsafe"),n.length===0)return[];const f=Q(e,"insert");if(f){const l=[];for(const p of n)H(p);for(const p of n){const v=await f.insert(e,p,{allowExplicitId:s?.allowExplicitId});a({key:v,op:"insert",row:{...p,_id:v},table:e}),l.push(v)}return l}const h=t.tables[e];if(!h)throw new $("INTERNAL",`unknown table: ${e}`);we(e),pe(e);const u=[];for(let l=0;l<n.length;l+=Be)u.push(T(e));const c=n.map((l,p)=>{const v=Gt(h,l,ce),m=s?.allowExplicitId===!0&&typeof v._id=="string"?v._id:D(),M=s?.allowExplicitId===!0&&typeof v._creationTime=="number"?v._creationTime:b(),R={...v,...u[Math.floor(p/Be)],_creationTime:M,_id:m};return{creationTime:M,document:R,id:m}});for(const l of c)H(l.document);for(let l=0;l<c.length;l+=Be){const p=i.join(c.slice(l,l+Be).map(m=>i`(${m.id}, ${m.creationTime}, ${ae(m.document)})`),i`, `),v=Vt("sqlite",i`INSERT INTO ${i.identifier(e)} (id, _creationTime, ${i.identifier(oe)}) VALUES ${p}`);it(r,e,v.sql,v.params)}for(const{document:l,id:p}of c)yt(e,p,l),await j({doc:l,id:p,op:"insert",table:e});return c.map(l=>l.id)},async insertMany(e,n,s){de(n.length,s?.limit,"insertMany");const f=s?.skipDuplicates===!0,h=[],u=Q(e,"insert");if(u)for(const l of n)H(l);const c=async l=>u?ut(u,e,l,void 0,!1):P.insert(e,l);for(const l of n)try{h.push(await c(l))}catch(p){if(f&&p instanceof me&&p.kind==="unique")h.push(null);else throw p}return h},normalizeId(e,n){return Ut(t,e,n)},async patch(e,n,s){const f=se(e,s);if(!f){const v=$e(s);if(v){H(n),await v.patch(e,n,s);return}throw new $("NOT_FOUND",`document not found: ${e}`)}const{docJson:h,row:u,tableName:c}=f,l=t.tables[c];if(!l)throw new $("INTERNAL",`unknown table: ${c}`);_(c,e),Ot("patch",n);const p={...u,...jo(n),...T(c),_id:e};Ht(l,n,p,ce),et(l,p,!0),ee(c,"before","update")&&await te("before","update",{doc:{...p},id:e,op:"update",previous:u,table:c}),we(c),pe(c),We(r,c,Ft(c),[ae(p),e,h]),Ce(c,e,p,u),Ie(c,e,p),Ae(c,u,p),ge(c,e,u,p),x?.invalidate(c,e,y(c,u,p)),he(c,e,"update",p),a({indexKeys:y(c,u,p),key:e,op:"update",row:p,table:c}),ee(c,"after","update")&&await te("after","update",{doc:p,id:e,op:"update",previous:u,table:c}),await E({doc:p,id:e,op:"update",table:c})},async patchMany(e,n,s){de(e.length,n?.limit,"patchMany");for(const f of e)await P.patch(f.id,f.patch,s);return{patched:e.length}},async patchWhere(e,n,s){const u=(await(Q(e,"patchWhere")??P).findMany(e,{where:n.where})).page.map(c=>({id:String(c._id),patch:n.patch}));if(de(u.length,s?.limit,"patchWhere"),P.patchMany===void 0)throw new $("INTERNAL",`ctx.db.${e}.patchMany is unavailable: this writer has no batch patch`);return await P.patchMany(u,s),{patched:u.length}},async related(e,n){return Qn(P,d,e,n)},relationEdges:d,query(e){const n=Q(e,"query");return n?(_(e,G),n.query(e)):No(r,t,e,F,s=>{s?q(s):_(e,G)},s=>{g||k?.recordRead(s)})},async rank(e,n,s){const f=Q(e,"rank");if(f)return _(e,G),f.rank(e,n,s);F(e,n,"rank");const h=t.tables[e];if(!h)throw new $("INTERNAL",`unknown table: ${e}`);const u=h.rankIndexes?.find(U=>U.name===n);if(!u)throw new $("INTERNAL",`unknown rankIndex "${n}" on table "${e}"`);if(Et(e,h,u),s.restrictsCounts)throw new Ye(e);_(e,G),Qe(e,u);const c=typeof s.row=="string"?s.row:s.row._id;if(!c)return null;const l=At(e,u.name),p=u.sortBy.map((U,xe)=>It(xe)),v=p.map(U=>Re(U)).join(", "),m=O(r,i`SELECT ${i.identifier("__partition__")}, ${i.raw(v)} FROM ${i.identifier(l)} WHERE ${i.identifier("__id__")} = ${c}`).toArray(),[M]=m;if(M===void 0)return null;let R=M.__partition__;const B=V(s.baseWhere,s.where);Ze(B,t,e,"rank");const W=Un(u,B);if(W){const U=Gn(u.partitionBy??[],W);if(U!==R)return null;R=U}const C=p.map(U=>M[U]),{before:K,total:J}=jt(r,l,p,u.sortBy,R,C,c);return{position:K+1,total:J}},async rankBefore(e,n,s){if(ie(e))throw new $("INTERNAL",`rankBefore is not supported on the global (.global()) table '${e}' — cross-shard rank cursors apply only to sharded tables`);const f=t.tables[e];if(!f)throw new $("INTERNAL",`unknown table: ${e}`);const h=f.rankIndexes?.find(p=>p.name===n);if(!h)throw new $("INTERNAL",`unknown rankIndex "${n}" on table "${e}"`);if(s.restrictsCounts)throw new Ye(e);_(e,G),Qe(e,h);const u=At(e,h.name),c=h.sortBy.map((p,v)=>It(v)),l=h.sortBy.map((p,v)=>re(s.sortValues[v]??null));return jt(r,u,c,h.sortBy,s.partitionKey,l,s.rowId)},async rankPage(e,n,s={}){Ze(V(s.baseWhere,s.where),t,e,"rankPage");const f=Q(e,"rankPage");if(f)return _(e,G),f.rankPage(e,n,s);F(e,n,"rank");const{continueCursor:h,hasMore:u,rows:c}=Rt(St,e,n,s);return{continueCursor:h,isDone:!u,page:c.map(l=>l.doc)}},async rankPageRows(e,n,s={}){Ze(V(s.baseWhere,s.where),t,e,"rankPage"),F(e,n,"rank");const{directions:f,hasMore:h,rows:u}=Rt(St,e,n,s);return{directions:f,hasMore:h,rows:u}},async restore(e,n){const s=se(e,n);if(!s){const u=$e(n);if(u?.restore){await u.restore(e,n);return}throw new $("NOT_FOUND",`document not found: ${e}`)}const f=t.tables[s.tableName]?.softDeleteMode?.field;if(!f)throw new $("INTERNAL",`ctx.db.restore: table "${s.tableName}" is not a .softDelete() table`);const h=s.row[f]!==null&&s.row[f]!==void 0;await P.patch(e,{[f]:null},n),h&&ge(s.tableName,e,void 0,s.row)},async replace(e,n,s,f){const h=se(e,s);if(!h){const B=$e(s);if(B){H(n),await B.replace(e,n,s,f);return}throw new $("NOT_FOUND",`document not found: ${e}`)}const{docJson:u,row:c,tableName:l}=h,p=t.tables[l];if(!p)throw new $("INTERNAL",`unknown table: ${l}`);Ot("replace",n);const v=f?.allowExplicitId&&typeof n._creationTime=="number"?n._creationTime:void 0,m=typeof c._creationTime=="number"?c._creationTime:void 0,M=v??m??b(),R={...n,...T(l),_creationTime:M,_id:e};Ht(p,n,R,ce),et(p,R),ee(l,"before","update")&&await te("before","update",{doc:{...R},id:e,op:"update",previous:c,table:l}),we(l),pe(l),We(r,l,wo(l),[M,ae(R),e,u]),Ce(l,e,R,c),Ie(l,e,R),Ae(l,c,R),ge(l,e,c,R),x?.invalidate(l,e,y(l,c,R)),he(l,e,"update",R),a({indexKeys:y(l,c,R),key:e,op:"update",row:R,table:l}),ee(l,"after","update")&&await te("after","update",{doc:R,id:e,op:"update",previous:c,table:l}),await E({doc:R,id:e,op:"update",table:l})},async wipeShard(e){const n=new Set(e?.exclude),s=e?.tables,f=Object.entries(t.tables).filter(([l,p])=>n.has(l)||s!==void 0&&!s.includes(l)?!1:p.shardMode?.kind!=="global").map(([l])=>l);if(s!==void 0){for(const l of s)if(!t.tables[l])throw new $("INTERNAL",`wipeShard: unknown table: ${l}`)}const h={};let u=0;const{deleteAll:c}=P;if(c===void 0)throw new $("INTERNAL","wipeShard: this writer has no deleteAll");for(const l of f){const p=await c(l,{...e?.chunkSize===void 0?{}:{chunkSize:e.chunkSize},hard:!0});h[l]=p.deleted,u+=p.deleted}return{deleted:u,tables:h}}},hn={db:P,scheduler:z};return o.enforceRls===!0?Jn(P,t,(e,n)=>se(e,n)?.tableName,(e,n)=>fn(e,n),d):P};export{Br as CDC_LOG_TABLE,ti as CLIENT_WATERMARK_TABLE,si as GLOBAL_SHAPE_SNAPSHOT_TABLE,hi as IDEMPOTENCY_TABLE,Go as NotUniqueError,mi as SEARCH_STATE_TABLE,ni as advanceClientWatermark,Wr as applyCdcChanges,Ot as assertNoExplicitUndefined,So as assertValidClientId,Lr as backfillAggregateIndexes,kr as backfillRankIndexes,Fr as backfillSearchIndexes,Pr as bumpCdcEpoch,Ur as cdcCanVouchFor,Gr as cdcForkedError,Hr as cdcSeqLeavingRows,Or as cdcTouchesTables,Nr as cdcTrimmedError,jr as compactCdcDocs,br as createShardCtxDb,Kr as cursorBelowRetainedFloor,ci as deleteGlobalShapeSnapshot,ai as deleteGlobalShapeSnapshotsForConnection,oi as migrateClientWatermark,di as migrateGlobalShapeSnapshot,Qr as minCdcReplayableSeq,Vr as minCdcSeq,Ut as normalizeIdStructurally,zr as readCdcChangeKeys,Jr as readCdcChanges,Yr as readCdcCursor,Xr as readCdcEpoch,ri as readClientWatermark,li as readGlobalShapeSnapshot,wi as readIdempotent,yi as runShardMigrations,_i as selectShapeMembers,Ri as selectShapeRows,jo as stripReservedPatchFields,Zr as trimCdcChanges,pi as trimIdempotent,ui as writeGlobalShapeSnapshot,gi as writeIdempotent};
@@ -1,5 +0,0 @@
1
- import{LunoraError as L}from"@lunora/errors";import{S as h,y as l,l as N}from"./ctx-db-companions-DsNfXSbb.mjs";import{sql as e}from"drizzle-orm";import{aggregateTableName as R}from"./aggregateTableName-C7o-gpms.mjs";import{backfillSearchIndexesForTable as O}from"./backfillAggregateIndexes-DTemznr7.mjs";import{migrateCdcLog as x,migrateCdcMeta as C}from"./CDC_LOG_TABLE-CfILante.mjs";import{migrateClientWatermark as $}from"./CLIENT_WATERMARK_TABLE-CRnrAnJ2.mjs";import{migrateCommitSeq as U}from"./COMMIT_SEQ_FIELD-BUdOMG5y.mjs";import{migrateGlobalShapeSnapshot as D}from"./GLOBAL_SHAPE_SNAPSHOT_TABLE-DSA6mzyx.mjs";import{migrateIdempotency as b}from"./IDEMPOTENCY_TABLE-DOpm_oMF.mjs";import{m as X}from"./ctx-db-relay-shapes-Bg5YYnmN.mjs";import{migrateScheduleOutbox as G}from"./SCHEDULE_OUTBOX_TABLE-CD_UjYVx.mjs";import{m as M}from"./ctx-db-search-state-ruTuCsxa.mjs";import{migrateShapePokeCursor as F}from"./SHAPE_POKE_CURSOR_TABLE-ByJVDHds.mjs";import{runDrizzle as s}from"./runDrizzle-2ULFQR_k.mjs";import{D as y,d as E,e as g,t as B,i as Y,g as k,a as v,b as P,A}from"./do-sql-kpl5Kt1j.mjs";import{renderSql as w}from"./param-DlozcSQu.mjs";import{migrateDurableStreams as j}from"./appendStreamChunk-C1Ok4b6J.mjs";import{rankTableName as K,sortColumnName as H}from"./RANK_TIEBREAK-D5xNdzB3.mjs";import{migrateReactorState as V}from"./REACTOR_STATE_TABLE-QPRFyxMS.mjs";import{recordSchemaVersion as W}from"./SCHEMA_HISTORY_MAX_VERSIONS-BluIj2s-.mjs";const S=e`_creationTime, id`,p=(r,o,i,t,n,a)=>{const c=e.join(n.map(d=>e`${d} IS NOT NULL`),e` AND `);if(s(r,e`SELECT 1 FROM ${e.identifier(i)} WHERE ${c} GROUP BY ${t} HAVING COUNT(*) > 1 LIMIT 1`).toArray().length>0)throw new L("INTERNAL",`unique index "${o}" on "${i}" ${a}: existing rows are duplicates under it. De-duplicate the table with a data migration first; the previous index is left in place.`)},z=(r,o,i,t,n,a)=>{const m=s(r,e`SELECT sql FROM sqlite_master WHERE type = 'index' AND name = ${o} AND tbl_name = ${i}`).toArray()[0]?.sql;if(m==null)return;const d=_=>{const I=_.indexOf("(");return I===-1?void 0:_.slice(I,_.lastIndexOf(")")+1)},T=d(w("sqlite",E(o,i,t,n)).sql),f=d(m);T===void 0||f===void 0||T===f||(n&&p(r,o,i,t,a,"cannot be re-created with its new column list"),s(r,e`DROP INDEX IF EXISTS ${e.identifier(o)}`))},J=(r,o,i)=>s(r,e`SELECT 1 FROM sqlite_master WHERE type = 'index' AND name = ${o} AND tbl_name = ${i} LIMIT 1`).toArray().length>0,u=(r,o,i,t,n,a)=>{n&&!J(r,o,i)&&p(r,o,i,t,a,"cannot be created"),s(r,E(o,i,t,n))},Q=(r,o,i)=>{for(const t of i.indexes){const n=`${o}_${t.name}`,a=t.unique??!1,c=t.fields.map(T=>g(T)),m=e.join(c,e`, `),d=a?m:e`${m}, ${S}`;z(r,n,o,d,a,c),u(r,n,o,d,a,c)}for(const[t,n]of B(i)){if(!n.unique)continue;const a=g(t);u(r,`${o}_unique_${t}`,o,a,!0,[a])}},Z=(r,o,i)=>{if(!(!i.searchIndexes||i.searchIndexes.length===0||!Y(r))){for(const t of i.searchIndexes){const n=h(o,t.name);s(r,e`CREATE VIRTUAL TABLE IF NOT EXISTS ${e.identifier(n)} USING fts5(${e.identifier(l)}, ${e.identifier(N)} UNINDEXED)`),s(r,e`CREATE VIRTUAL TABLE IF NOT EXISTS ${e.identifier(`${n}__vocab`)} USING fts5vocab(${e.identifier(n)}, ${e.raw("instance")})`)}O(r,o,i)}},q=(r,o,i)=>{if(i.geoIndexes)for(const t of i.geoIndexes){const n=k(o,t.name);s(r,e`CREATE TABLE IF NOT EXISTS ${e.identifier(n)} (${e.identifier("__id__")} TEXT PRIMARY KEY, ${e.identifier("__geohash__")} TEXT NOT NULL, ${e.identifier("__lat__")} REAL NOT NULL, ${e.identifier("__lng__")} REAL NOT NULL)`);const a=`${o}__geo_${t.name}__btree`;s(r,E(a,n,e`${e.identifier("__geohash__")} ASC, ${e.identifier("__id__")} ASC`,!1))}},ee=(r,o,i)=>{if(i.aggregateIndexes)for(const t of i.aggregateIndexes){const n=R(o,t.name);s(r,e`CREATE TABLE IF NOT EXISTS ${e.identifier(n)} (${v} TEXT PRIMARY KEY, ${P} REAL, ${A} INTEGER NOT NULL DEFAULT 0)`),s(r,e`PRAGMA table_info(${e.identifier(n)})`).toArray().some(c=>c.name==="__count__")||s(r,e`ALTER TABLE ${e.identifier(n)} ADD COLUMN ${A} INTEGER NOT NULL DEFAULT 0`)}},re=(r,o,i)=>{if(i.rankIndexes)for(const t of i.rankIndexes){const n=K(o,t.name),a=t.sortBy.map((f,_)=>H(_)),c=a.map(f=>e`${e.identifier(f)} BLOB`),m=c.length>0?e`, ${e.join(c,e`, `)}`:e``;s(r,e`CREATE TABLE IF NOT EXISTS ${e.identifier(n)} (${e.identifier("__id__")} TEXT PRIMARY KEY, ${e.identifier("__partition__")} TEXT NOT NULL${m})`);const d=[e`${e.identifier("__partition__")} ASC`];for(const[f,_]of a.entries()){const I=t.sortBy[f]?.direction;d.push(e`${e.identifier(_)} ${e.raw(I==="desc"?"DESC":"ASC")}`)}d.push(e`${e.identifier("__id__")} ASC`);const T=`${o}__rank_${t.name}__btree`;s(r,E(T,n,e.join(d,e`, `),!1))}},le=(r,o,i={})=>{i.schemaSnapshot!==void 0&&W(r,i.schemaSnapshot.hash,i.schemaSnapshot.json),M(r);for(const[t,n]of Object.entries(o.tables))n.shardMode?.kind!=="global"&&(s(r,e`CREATE TABLE IF NOT EXISTS ${e.identifier(t)} (
2
- id TEXT PRIMARY KEY,
3
- _creationTime REAL NOT NULL,
4
- ${e.identifier(y)} TEXT NOT NULL
5
- )`),s(r,E(`${t}__by_creation`,t,S,!1)),Q(r,t,n),Z(r,t,n),q(r,t,n),ee(r,t,n),re(r,t,n));i.cdc&&(x(r),C(r),$(r),F(r),X(r)),Object.values(o.tables).some(t=>t.commitOrderedMode===!0)&&U(r),V(r),b(r),G(r),D(r),j(r)};export{le as runShardMigrations};