@lunora/shard-engine 1.0.0-alpha.162 → 1.0.0-alpha.164

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.
Files changed (23) hide show
  1. package/dist/conformance/index.mjs +1 -1
  2. package/dist/index.d.mts +10 -11
  3. package/dist/index.d.ts +10 -11
  4. package/dist/index.mjs +1 -1
  5. package/dist/packem_shared/{CDC_LOG_TABLE-CwEMKX-0.mjs → CDC_LOG_TABLE-oPp25hdi.mjs} +1 -1
  6. package/dist/packem_shared/{DATA_MIGRATION_STATE_TABLE-DTOKJcGY.mjs → DATA_MIGRATION_STATE_TABLE-CFvBS9-M.mjs} +1 -1
  7. package/dist/packem_shared/DEFAULT_MAX_RELAYS-B1jshtuE.mjs +8 -0
  8. package/dist/packem_shared/NotUniqueError-DvGeO5_k.mjs +1 -0
  9. package/dist/packem_shared/RELAY_SIGNATURE_HEADER-DNzVQxbZ.mjs +1 -0
  10. package/dist/packem_shared/RLS_UNWRAP_SYMBOL-H6J96vgK.mjs +1 -0
  11. package/dist/packem_shared/{buildShapeDiff-oiv4ZHqB.mjs → buildShapeDiff-BfTX-roE.mjs} +1 -1
  12. package/dist/packem_shared/{createReplicaLink-CtUDWLK5.mjs → createReplicaLink-CxVPj3iC.mjs} +3 -3
  13. package/dist/packem_shared/defineEngineContractSuite-CXFPVXgc.mjs +1 -0
  14. package/dist/packem_shared/{isSoftDeleted-Dfk5F4Kc.mjs → isSoftDeleted-BYZ0sPyu.mjs} +1 -1
  15. package/dist/packem_shared/{materializeExternalRows-DE8zhD1x.mjs → materializeExternalRows-DzUChRJ-.mjs} +1 -1
  16. package/dist/packem_shared/{runShardMigrations-C-0ec-sY.mjs → runShardMigrations-BXGBfJU1.mjs} +1 -1
  17. package/dist/packem_shared/stubByName-DLPoppDc.mjs +1 -0
  18. package/package.json +1 -1
  19. package/dist/packem_shared/DEFAULT_MAX_RELAYS-B6rnl_9a.mjs +0 -8
  20. package/dist/packem_shared/NotUniqueError-DU8p6_p8.mjs +0 -1
  21. package/dist/packem_shared/RELAY_SIGNATURE_HEADER-C_P73AOx.mjs +0 -1
  22. package/dist/packem_shared/RLS_UNWRAP_SYMBOL-BjV34hfH.mjs +0 -1
  23. package/dist/packem_shared/defineEngineContractSuite-BNY5-Bz-.mjs +0 -1
@@ -1 +1 @@
1
- import{defineEngineContractSuite as t}from"../packem_shared/defineEngineContractSuite-BNY5-Bz-.mjs";export{t as defineEngineContractSuite};
1
+ import{defineEngineContractSuite as t}from"../packem_shared/defineEngineContractSuite-CXFPVXgc.mjs";export{t as defineEngineContractSuite};
package/dist/index.d.mts CHANGED
@@ -600,7 +600,7 @@ interface MutationDelta {
600
600
  interface DatabaseWriterLike {
601
601
  aggregate: (tableName: string, options: AggregateOptions) => Promise<AggregateResult>;
602
602
  asId?: (tableName: string, id: string) => string;
603
- assertPatchAllowed?: (id: string, expectedTable?: string) => Promise<void>;
603
+ assertPatchAllowed?: (table: string, id: string) => Promise<void>;
604
604
  cdcChangedTables?: (sinceSeq: number, options?: {
605
605
  cursorOnly?: boolean;
606
606
  }) => Promise<{
@@ -609,7 +609,7 @@ interface DatabaseWriterLike {
609
609
  tables: string[];
610
610
  } | undefined>;
611
611
  count: (tableName: string, where?: RestrictableQueryOptions | WhereInput) => Promise<number>;
612
- delete: (id: string, expectedTable?: string, options?: {
612
+ delete: (table: string, id: string, options?: {
613
613
  hard?: boolean;
614
614
  }) => Promise<void>;
615
615
  deleteAll?: (tableName: string, options?: {
@@ -618,9 +618,9 @@ interface DatabaseWriterLike {
618
618
  }) => Promise<{
619
619
  deleted: number;
620
620
  }>;
621
- deleteMany?: (ids: ReadonlyArray<string>, options?: {
621
+ deleteMany?: (table: string, ids: ReadonlyArray<string>, options?: {
622
622
  limit?: number;
623
- }, expectedTable?: string) => Promise<{
623
+ }) => Promise<{
624
624
  deleted: number;
625
625
  }>;
626
626
  deleteRereadTables?: ReadonlySet<string>;
@@ -653,7 +653,7 @@ interface DatabaseWriterLike {
653
653
  tableName: string;
654
654
  }>;
655
655
  normalizeId: (tableName: string, id: string) => null | string;
656
- patch: (id: string, patch: Record<string, unknown>, expectedTable?: string, options?: PatchWriteOptions) => Promise<void>;
656
+ patch: (table: string, id: string, patch: Record<string, unknown>, options?: PatchWriteOptions) => Promise<void>;
657
657
  patchIf?: (tableName: string, id: string, args: {
658
658
  patch: Record<string, unknown>;
659
659
  verify?: PatchVerifier;
@@ -662,12 +662,12 @@ interface DatabaseWriterLike {
662
662
  applied: boolean;
663
663
  doc: Record<string, unknown> | null;
664
664
  }>;
665
- patchMany?: (patches: ReadonlyArray<{
665
+ patchMany?: (table: string, patches: ReadonlyArray<{
666
666
  id: string;
667
667
  patch: Record<string, unknown>;
668
668
  }>, options?: {
669
669
  limit?: number;
670
- }, expectedTable?: string) => Promise<{
670
+ }) => Promise<{
671
671
  patched: number;
672
672
  }>;
673
673
  patchWhere?: (tableName: string, args: {
@@ -686,10 +686,10 @@ interface DatabaseWriterLike {
686
686
  related?: (start: RelatedStart, options?: RelatedOptions) => Promise<RelatedPage>;
687
687
  relationEdges?: ReadonlyArray<RelationEdge>;
688
688
  relationWrites?: RelationWriteMap;
689
- replace: (id: string, document: Record<string, unknown>, expectedTable?: string, options?: {
689
+ replace: (table: string, id: string, document: Record<string, unknown>, options?: {
690
690
  allowExplicitId?: boolean;
691
691
  }) => Promise<void>;
692
- restore?: (id: string, expectedTable?: string) => Promise<void>;
692
+ restore?: (table: string, id: string) => Promise<void>;
693
693
  softDeleteFields?: ReadonlyMap<string, string>;
694
694
  system?: SystemDatabaseReader;
695
695
  wipeShard?: (options?: {
@@ -2566,8 +2566,7 @@ interface GuardableSchema {
2566
2566
  }>;
2567
2567
  }
2568
2568
  type TableOfId = (id: string, expectedTable?: string) => Promise<string | undefined> | string | undefined;
2569
- type TablesOfIds = (ids: ReadonlyArray<string>, expectedTable?: string) => Promise<ReadonlyMap<string, string>> | ReadonlyMap<string, string>;
2570
- declare const guardWriter: <W>(raw: W, schema: GuardableSchema, tableOfId: TableOfId, tablesOfIds?: TablesOfIds, relationEdges?: ReadonlyArray<RelationEdge>) => W;
2569
+ declare const guardWriter: <W>(raw: W, schema: GuardableSchema, tableOfId: TableOfId, relationEdges?: ReadonlyArray<RelationEdge>) => W;
2571
2570
  declare const SCHEMA_HISTORY_MAX_VERSIONS = 50;
2572
2571
  interface SchemaVersionRow {
2573
2572
  appliedAt: number;
package/dist/index.d.ts CHANGED
@@ -600,7 +600,7 @@ interface MutationDelta {
600
600
  interface DatabaseWriterLike {
601
601
  aggregate: (tableName: string, options: AggregateOptions) => Promise<AggregateResult>;
602
602
  asId?: (tableName: string, id: string) => string;
603
- assertPatchAllowed?: (id: string, expectedTable?: string) => Promise<void>;
603
+ assertPatchAllowed?: (table: string, id: string) => Promise<void>;
604
604
  cdcChangedTables?: (sinceSeq: number, options?: {
605
605
  cursorOnly?: boolean;
606
606
  }) => Promise<{
@@ -609,7 +609,7 @@ interface DatabaseWriterLike {
609
609
  tables: string[];
610
610
  } | undefined>;
611
611
  count: (tableName: string, where?: RestrictableQueryOptions | WhereInput) => Promise<number>;
612
- delete: (id: string, expectedTable?: string, options?: {
612
+ delete: (table: string, id: string, options?: {
613
613
  hard?: boolean;
614
614
  }) => Promise<void>;
615
615
  deleteAll?: (tableName: string, options?: {
@@ -618,9 +618,9 @@ interface DatabaseWriterLike {
618
618
  }) => Promise<{
619
619
  deleted: number;
620
620
  }>;
621
- deleteMany?: (ids: ReadonlyArray<string>, options?: {
621
+ deleteMany?: (table: string, ids: ReadonlyArray<string>, options?: {
622
622
  limit?: number;
623
- }, expectedTable?: string) => Promise<{
623
+ }) => Promise<{
624
624
  deleted: number;
625
625
  }>;
626
626
  deleteRereadTables?: ReadonlySet<string>;
@@ -653,7 +653,7 @@ interface DatabaseWriterLike {
653
653
  tableName: string;
654
654
  }>;
655
655
  normalizeId: (tableName: string, id: string) => null | string;
656
- patch: (id: string, patch: Record<string, unknown>, expectedTable?: string, options?: PatchWriteOptions) => Promise<void>;
656
+ patch: (table: string, id: string, patch: Record<string, unknown>, options?: PatchWriteOptions) => Promise<void>;
657
657
  patchIf?: (tableName: string, id: string, args: {
658
658
  patch: Record<string, unknown>;
659
659
  verify?: PatchVerifier;
@@ -662,12 +662,12 @@ interface DatabaseWriterLike {
662
662
  applied: boolean;
663
663
  doc: Record<string, unknown> | null;
664
664
  }>;
665
- patchMany?: (patches: ReadonlyArray<{
665
+ patchMany?: (table: string, patches: ReadonlyArray<{
666
666
  id: string;
667
667
  patch: Record<string, unknown>;
668
668
  }>, options?: {
669
669
  limit?: number;
670
- }, expectedTable?: string) => Promise<{
670
+ }) => Promise<{
671
671
  patched: number;
672
672
  }>;
673
673
  patchWhere?: (tableName: string, args: {
@@ -686,10 +686,10 @@ interface DatabaseWriterLike {
686
686
  related?: (start: RelatedStart, options?: RelatedOptions) => Promise<RelatedPage>;
687
687
  relationEdges?: ReadonlyArray<RelationEdge>;
688
688
  relationWrites?: RelationWriteMap;
689
- replace: (id: string, document: Record<string, unknown>, expectedTable?: string, options?: {
689
+ replace: (table: string, id: string, document: Record<string, unknown>, options?: {
690
690
  allowExplicitId?: boolean;
691
691
  }) => Promise<void>;
692
- restore?: (id: string, expectedTable?: string) => Promise<void>;
692
+ restore?: (table: string, id: string) => Promise<void>;
693
693
  softDeleteFields?: ReadonlyMap<string, string>;
694
694
  system?: SystemDatabaseReader;
695
695
  wipeShard?: (options?: {
@@ -2566,8 +2566,7 @@ interface GuardableSchema {
2566
2566
  }>;
2567
2567
  }
2568
2568
  type TableOfId = (id: string, expectedTable?: string) => Promise<string | undefined> | string | undefined;
2569
- type TablesOfIds = (ids: ReadonlyArray<string>, expectedTable?: string) => Promise<ReadonlyMap<string, string>> | ReadonlyMap<string, string>;
2570
- declare const guardWriter: <W>(raw: W, schema: GuardableSchema, tableOfId: TableOfId, tablesOfIds?: TablesOfIds, relationEdges?: ReadonlyArray<RelationEdge>) => W;
2569
+ declare const guardWriter: <W>(raw: W, schema: GuardableSchema, tableOfId: TableOfId, relationEdges?: ReadonlyArray<RelationEdge>) => W;
2571
2570
  declare const SCHEMA_HISTORY_MAX_VERSIONS = 50;
2572
2571
  interface SchemaVersionRow {
2573
2572
  appliedAt: number;
package/dist/index.mjs CHANGED
@@ -1 +1 @@
1
- import{exportShardRows as o,importShardRows as a,parseExportShardArgs as t,parseImportShardArgs as i,selectExportTables as s,validateImportRow as l}from"./packem_shared/exportShardRows-6NxY9jMV.mjs";import{AGGREGATE_SQL_FUNCTION as d,aggregateSqlFunction as c,matchesStaticWhere as m,normalizeCountArgument as p,throwingScheduler as S}from"./packem_shared/AGGREGATE_SQL_FUNCTION-C_ZipS9R.mjs";import{aggregateTableName as f,coerceAggregateNumber as E,encodeAggregateKey as x,foldAggregateTally as h,readAggregateValue as T}from"./packem_shared/aggregateTableName-B_CtIQCS.mjs";import{CountRlsUnsupportedError as A,mergeWhere as C,planAggregateLookup as g,selectIndexForAggregate as _,selectIndexForCount as I,selectIndexForGroupBy as b}from"./packem_shared/CountRlsUnsupportedError-BvsDqfO2.mjs";import{AUDIT_LOG_TABLE as D,appendAuditEntry as P,ensureAuditTable as O,readAuditLog as M}from"./packem_shared/AUDIT_LOG_TABLE-BFJ65SRS.mjs";import{NotUniqueError as F,assertNoExplicitUndefined as N,assertStorableRowId as k,assertValidClientId as B,createShardCtxDb as U,normalizeIdStructurally as G,stripReservedPatchFields as w}from"./packem_shared/NotUniqueError-DU8p6_p8.mjs";import{backfillAggregateIndexes as v,backfillRankIndexes as K,backfillSearchIndexes as W,backfillSearchIndexesForTable as X}from"./packem_shared/backfillAggregateIndexes-BN0NwXQk.mjs";import{CDC_LOG_TABLE as V,CDC_LOG_TABLE_SEQ_INDEX as z,CDC_META_TABLE as Q,appendCdcChange as Y,applyCdcChanges as j,bumpCdcEpoch as J,cdcCanVouchFor as Z,cdcForkedError as $,cdcSeqLeavingRows as ee,cdcTouchesTables as re,cdcTrimmedError as oe,compactCdcDocs as ae,cursorBelowRetainedFloor as te,migrateCdcLog as ie,migrateCdcMeta as se,minCdcReplayableSeq as le,minCdcSeq as ne,readCdcChangeKeys as de,readCdcChanges as ce,readCdcCursor as me,readCdcEpoch as pe,trimCdcChanges as Se}from"./packem_shared/CDC_LOG_TABLE-CwEMKX-0.mjs";import{archiveCdcSegment as fe,cdcArchiveRewound as Ee,readArchivedCdcChanges as xe,readCdcArchivedThrough as he,writeCdcArchivedThrough as Te}from"./packem_shared/archiveCdcSegment-Cr8oGLfB.mjs";import{CLIENT_WATERMARK_TABLE as Ae,advanceClientWatermark as Ce,migrateClientWatermark as ge,readClientWatermark as _e}from"./packem_shared/CLIENT_WATERMARK_TABLE-De7z_OHV.mjs";import{COMMIT_SEQ_FIELD as be,COMMIT_SEQ_TABLE as Le,allocateCommitSeq as De,migrateCommitSeq as Pe,readCommitSeq as Oe}from"./packem_shared/COMMIT_SEQ_FIELD-Da1DjGqo.mjs";import{CompanionMemo as ye,clearCompanionSignatures as Fe}from"./packem_shared/CompanionMemo-BXU5vfak.mjs";import{createCompanionSync as ke}from"./packem_shared/createCompanionSync-zIF_F4oD.mjs";import{GLOBAL_SHAPE_SNAPSHOT_TABLE as Ue,deleteGlobalShapeSnapshot as Ge,deleteGlobalShapeSnapshotsForConnection as we,migrateGlobalShapeSnapshot as qe,readGlobalShapeSnapshot as ve,writeGlobalShapeSnapshot as Ke}from"./packem_shared/GLOBAL_SHAPE_SNAPSHOT_TABLE-Bb6-aZuH.mjs";import{IDEMPOTENCY_TABLE as Xe,migrateIdempotency as He,readIdempotent as Ve,trimIdempotent as ze,writeIdempotent as Qe}from"./packem_shared/IDEMPOTENCY_TABLE-COrgeP3O.mjs";import{clearMemoryTables as je,isMemoryTable as Je,memoryTableNames as Ze}from"./packem_shared/clearMemoryTables-aMRERF0w.mjs";import{computeRankPage as er,resolveRankSeekTuple as rr}from"./packem_shared/computeRankPage-BZIpATcs.mjs";import{SCHEDULE_OUTBOX_TABLE as ar,deferScheduleOutbox as tr,forgetScheduleOutbox as ir,migrateScheduleOutbox as sr,parkScheduleOutbox as lr,probeScheduleOutbox as nr,readDueScheduleOutbox as dr,recordScheduleOutbox as cr,trimScheduleOutbox as mr}from"./packem_shared/SCHEDULE_OUTBOX_TABLE-DcZI7Yhl.mjs";import{S as Sr,m as ur,r as fr,w as Er}from"./packem_shared/ctx-db-search-state-FjgzTFok.mjs";import{SHAPE_POKE_CURSOR_TABLE as hr,deleteShapePokeCursor as Tr,deleteShapePokeCursorsForConnection as Rr,migrateShapePokeCursor as Ar,minShapePokeCursor as Cr,readShapePokeCursor as gr,writeShapePokeCursor as _r,writeShapePokeCursors as Ir}from"./packem_shared/SHAPE_POKE_CURSOR_TABLE-BGvY3sFI.mjs";import{selectShapeMembers as Lr,selectShapeRows as Dr}from"./packem_shared/selectShapeMembers-BCfKypfN.mjs";import{DATA_MIGRATION_STATE_TABLE as Or,readMigrationStatus as Mr,runDataMigration as yr}from"./packem_shared/DATA_MIGRATION_STATE_TABLE-DTOKJcGY.mjs";import{SCAN_DEP as Nr,createDependencyTracker as kr,depKey as Br,tableFromDepKey as Ur}from"./packem_shared/SCAN_DEP-D7qE3iUe.mjs";import{runDrizzle as wr,runSql as qr}from"./packem_shared/runDrizzle-RC09zZrh.mjs";import{A as Kr,a as Wr,b as Xr,D as Hr,c as Vr,d as zr,g as Qr,i as Yr,j as jr,e as Jr,q as Zr,f as $r,r as eo,t as ro,h as oo}from"./packem_shared/do-sql-BWrJQAOh.mjs";import{WORKERD_SQLITE_LIMITS as to,param as io,renderSql as so,sqliteInList as lo,unionAll as no}from"./packem_shared/WORKERD_SQLITE_LIMITS-B_4w7tzY.mjs";import{appendStreamChunk as mo,claimStreamRun as po,deleteStreamRun as So,finishStreamRun as uo,migrateDurableStreams as fo,readStreamChunks as Eo,readStreamRun as xo,trimStreamRuns as ho}from"./packem_shared/appendStreamChunk-BZYgGE9Y.mjs";import{DurableStreamRunner as Ro,MAX_DURABLE_STREAM_BYTES as Ao,MAX_DURABLE_STREAM_CHUNKS as Co,decideDurableAttach as go}from"./packem_shared/DurableStreamRunner-MMlV5qKQ.mjs";import{envOptionalPositiveInt as Io,envPositiveInt as bo}from"./packem_shared/envOptionalPositiveInt-D2pY-c64.mjs";import{diffExternalSource as Do}from"./packem_shared/diffExternalSource-B0FZlDoL.mjs";import{liftSourceId as Oo,normalizeSourceDocument as Mo,normalizeSourceValue as yo}from"./packem_shared/liftSourceId-CA3ENhXj.mjs";import{materializeExternalRows as No,materializeExternalRowsIncremental as ko,readExternalSourceBaseline as Bo,runExternalSourceTick as Uo}from"./packem_shared/materializeExternalRows-DE8zhD1x.mjs";import{isSoftDeleted as wo,isSourceDue as qo,pullExternalSourceIncrementalTick as vo,pullExternalSourceTick as Ko}from"./packem_shared/isSoftDeleted-Dfk5F4Kc.mjs";import{f as Xo,a as Ho,b as Vo,c as zo,d as Qo,g as Yo}from"./packem_shared/fts-companion-CA8mLJWq.mjs";import{GEO_DEFAULT_PRECISION as Jo,boundingBoxCenter as Zo,boundingBoxGeohashes as $o,coveringGeohashes as ea,encodeGeohash as ra,haversineMeters as oa,pointInBoundingBox as aa}from"./packem_shared/GEO_DEFAULT_PRECISION-CqpQZ-J_.mjs";import{default as ia}from"./packem_shared/GlobalPollTick-BNK4o-XT.mjs";import{ADMIN_FUNCTIONS as la,ADMIN_FUNCTION_PREFIX as na,DEFAULT_FANOUT_TOPIC_LIMIT as da,FLAGS_FUNCTION_PREFIX as ca,MAX_PAGE_SIZE as ma,RELATION_FUNCTION_PREFIX as pa,createFanoutCounters as Sa,createGlobalPollCounters as ua,createShapeProbeCounters as fa,facetColumn as Ea,findStorageReferences as xa,isVacuousFilterClause as ha,listTables as Ta,readTablePage as Ra,recordFanoutPass as Aa,recordGlobalPollPass as Ca,recordShapeProbePass as ga,selectMatchingIds as _a,summarizeFanoutTopics as Ia,summarizeSubscriptions as ba}from"./packem_shared/ADMIN_FUNCTIONS-zJra0V3L.mjs";import{MAIL_RETENTION as Da,MAIL_TABLE as Pa,clearCapturedMail as Oa,ensureMailTable as Ma,readCapturedMail as ya,recordCapturedMail as Fa}from"./packem_shared/MAIL_RETENTION-DMolrLYt.mjs";import{NotFoundError as ka}from"./packem_shared/NotFoundError-BhF7FeFr.mjs";import{assertPatchAllowed as Ua,operatorFields as Ga,patchDependsOnRow as wa,readPatchField as qa,resolvePatch as va}from"./packem_shared/assertPatchAllowed-CA_H466g.mjs";import{armRestore as Wa,readBookmark as Xa}from"./packem_shared/armRestore-Bu1_8SUa.mjs";import{CURSOR_PREFIX as Va,applySelect as za,buildSeekBeforeWhere as Qa,buildSeekWhere as Ya,decodeCursor as ja,encodeCursor as Ja,equalityPinnedFields as Za,normalizeOrderKeys as $a,nullsFirstOf as et,nullsOrderSuffix as rt,softDeleteScope as ot,tiebreakDirectionFor as at,uniqueIndexFields as tt}from"./packem_shared/CURSOR_PREFIX-6offuG6M.mjs";import{QUEUE_TABLE as st,clearQueueMessages as lt,isLossyBody as nt,readQueueMessageById as dt,readQueueMessages as ct,recordQueueMessages as mt}from"./packem_shared/QUEUE_TABLE-C-goXtGd.mjs";import{RANK_TIEBREAK as St,encodePartitionKey as ut,matchesRankStaticWhere as ft,rankKeyFromDoc as Et,rankPivotConditionSql as xt,rankTableName as ht,resolveRankPartition as Tt,sortColumnName as Rt}from"./packem_shared/RANK_TIEBREAK-D3ye2GsL.mjs";import{ReactiveCache as Ct,reactiveCacheKey as gt}from"./packem_shared/ReactiveCache-DHhhLJtN.mjs";import{REACTOR_STATE_TABLE as It,listReactorStates as bt,migrateReactorState as Lt,reactorNeedsRun as Dt,readReactorState as Pt,writeReactorState as Ot}from"./packem_shared/REACTOR_STATE_TABLE-D2Mn204f.mjs";import{UNVOUCHABLE_DEP as yt,createReadFootprint as Ft,markUnvouchableReads as Nt}from"./packem_shared/UNVOUCHABLE_DEP-C68htACn.mjs";import{buildIndexRange as Bt,indexKeysForRow as Ut,keysTouchRanges as Gt}from"./packem_shared/buildIndexRange-DQ3eWAGd.mjs";import{isPushableWhere as qt,whereFilter as vt,whereOfFilter as Kt}from"./packem_shared/isPushableWhere-BeYAOjUb.mjs";import{RELATED_DEFAULT_LIMIT as Xt,RELATED_DEPTH_DECAY as Ht,RELATED_MAX_DEPTH as Vt,RELATED_MAX_LIMIT as zt,deriveRelationEdges as Qt,findRelated as Yt}from"./packem_shared/RELATED_DEFAULT_LIMIT-CVqN4JEu.mjs";import{DEFAULT_MAX_RELATION_KEYS as Jt,assertFlatPredicate as Zt,assertShapeShardable as $t,composeReadPredicate as ei,containsRelationPredicate as ri,isRelationPredicate as oi,resolveRelationPredicates as ai}from"./packem_shared/DEFAULT_MAX_RELATION_KEYS-9eOkadE4.mjs";import{describeRelationWrites as ii}from"./packem_shared/describeRelationWrites-omar6-u9.mjs";import{applyInsertDefaults as li,applyOnDelete as ni,distinctValues as di,fanOutScalarCounts as ci,relationHooks as mi,resolveWith as pi,runRowValidators as Si}from"./packem_shared/applyInsertDefaults-B0NXPs2x.mjs";import{DEFAULT_PROMOTION_THRESHOLDS as fi,clampPromotionThresholds as Ei,nextPromotionState as xi,relayCountFor as hi,shapeRoutingKey as Ti}from"./packem_shared/DEFAULT_PROMOTION_THRESHOLDS-B3pRMuqb.mjs";import{DEFAULT_MAX_RELAYS as Ai,OwnerRelay as Ci,RelayMember as gi,createRelayLink as _i}from"./packem_shared/DEFAULT_MAX_RELAYS-B6rnl_9a.mjs";import{createReplicaLink as bi,gateReplicaDispatch as Li,handleReplicaControl as Di}from"./packem_shared/createReplicaLink-CtUDWLK5.mjs";import{buildReprojectionMigration as Oi,countLegacyRows as Mi,reprojectableFields as yi,reprojectionTables as Fi}from"./packem_shared/buildReprojectionMigration-Ds2JaFo7.mjs";import{RLS_UNWRAP_SYMBOL as ki,RlsRequiredError as Bi,guardWriter as Ui}from"./packem_shared/RLS_UNWRAP_SYMBOL-BjV34hfH.mjs";import{SCHEMA_HISTORY_MAX_VERSIONS as wi,readSchemaHistory as qi,readSchemaVersion as vi,recordSchemaVersion as Ki}from"./packem_shared/SCHEMA_HISTORY_MAX_VERSIONS-CEwFjj-O.mjs";import{serializeSqlValue as Xi}from"./packem_shared/serializeSqlValue-DeoBMpZ2.mjs";import{buildSettings as Vi,isDevEnvironment as zi,readDeployInfo as Qi}from"./packem_shared/buildSettings-BRkZd6_E.mjs";import{buildShapeDiff as ji}from"./packem_shared/buildShapeDiff-oiv4ZHqB.mjs";import{ShapeDiffCache as Zi,createShapeDiffCache as $i,globalShapeReadKey as es}from"./packem_shared/ShapeDiffCache-iNO-hUiy.mjs";import{buildPokeFrames as os,diffGlobalMembership as as,encodeRowsPatch as ts,projectColumns as is}from"./packem_shared/buildPokeFrames-WR-hp0mX.mjs";import{ShardRunner as ls}from"./packem_shared/ShardRunner-CrveaPId.mjs";import{RELAY_SIGNATURE_HEADER as ds,siblingSecretOf as cs,signSiblingBody as ms,stubByName as ps,verifySiblingBody as Ss}from"./packem_shared/RELAY_SIGNATURE_HEADER-C_P73AOx.mjs";import{runSocketPool as fs}from"./packem_shared/runSocketPool-CZJ2X9cF.mjs";import{MAX_SQL_ROWS as xs,assertReadonly as hs,lintReadonlySql as Ts,runReadonlySql as Rs}from"./packem_shared/MAX_SQL_ROWS-eRignWyO.mjs";import{BIGINT_KEY_DIGITS as Cs,bigintSqlKey as gs,decodeBigintSqlKey as _s,decodeFloat64SqlKey as Is,float64SqlKey as bs}from"./packem_shared/BIGINT_KEY_DIGITS-DE6yshOt.mjs";import{awaitWsDrain as Ds,subscriptionFrames as Ps,subscriptionListDeltas as Os,trySendFrame as Ms}from"./packem_shared/awaitWsDrain-e88vUNdj.mjs";import{mergeChangedKeys as Fs,recordChangedKeys as Ns,writeTouchesMemo as ks}from"./packem_shared/mergeChangedKeys-BHUURyp6.mjs";import{createSystemReader as Us}from"./packem_shared/createSystemReader-DcDLFfC-.mjs";import{ConflictError as ws}from"./packem_shared/ConflictError-C8GtJmjS.mjs";import{DEFAULT_TRANSACTION_LIMITS as vs,TransactionHeadroomTracker as Ks}from"./packem_shared/DEFAULT_TRANSACTION_LIMITS-Dmj5VBrV.mjs";import{hasTrigger as Xs,runTriggers as Hs}from"./packem_shared/hasTrigger-CjlwI4le.mjs";import{nextTtlExpiry as zs,selectExpiredIds as Qs}from"./packem_shared/nextTtlExpiry-DhKO_OpO.mjs";import{VECTOR_BACKFILL_MAX_PAGES as js,backfillVectorIndexes as Js}from"./packem_shared/VECTOR_BACKFILL_MAX_PAGES-loOUGfzw.mjs";import{c as $s,s as el}from"./packem_shared/where-sql-BjY4rnqb.mjs";import{RELATION_EXISTS_KEY as ol}from"./packem_shared/RELATION_EXISTS_KEY-wxgj6rSL.mjs";import{REPROJECTION_MIGRATION_PREFIX as tl,reprojectionMigrationId as il}from"./packem_shared/REPROJECTION_MIGRATION_PREFIX-Czcb6_mO.mjs";import{isInternalTableName as ll}from"./packem_shared/isInternalTableName-BoljO2tP.mjs";import{quoteIdentifier as dl}from"./packem_shared/quoteIdentifier-CObIFRhb.mjs";import{runShardMigrations as ml}from"./packem_shared/runShardMigrations-C-0ec-sY.mjs";import{stableStringify as Sl,stableWireKey as ul}from"@lunora/wire";export{la as ADMIN_FUNCTIONS,na as ADMIN_FUNCTION_PREFIX,d as AGGREGATE_SQL_FUNCTION,Kr as AGG_COUNT,Wr as AGG_KEY,Xr as AGG_VALUE,D as AUDIT_LOG_TABLE,Cs as BIGINT_KEY_DIGITS,V as CDC_LOG_TABLE,z as CDC_LOG_TABLE_SEQ_INDEX,Q as CDC_META_TABLE,Ae as CLIENT_WATERMARK_TABLE,be as COMMIT_SEQ_FIELD,Le as COMMIT_SEQ_TABLE,Va as CURSOR_PREFIX,ye as CompanionMemo,ws as ConflictError,A as CountRlsUnsupportedError,Or as DATA_MIGRATION_STATE_TABLE,da as DEFAULT_FANOUT_TOPIC_LIMIT,Jt as DEFAULT_MAX_RELATION_KEYS,Ai as DEFAULT_MAX_RELAYS,fi as DEFAULT_PROMOTION_THRESHOLDS,vs as DEFAULT_TRANSACTION_LIMITS,Hr as DOC_COLUMN,Ro as DurableStreamRunner,ca as FLAGS_FUNCTION_PREFIX,Jo as GEO_DEFAULT_PRECISION,Ue as GLOBAL_SHAPE_SNAPSHOT_TABLE,ia as GlobalPollTick,Xe as IDEMPOTENCY_TABLE,Da as MAIL_RETENTION,Pa as MAIL_TABLE,Ao as MAX_DURABLE_STREAM_BYTES,Co as MAX_DURABLE_STREAM_CHUNKS,ma as MAX_PAGE_SIZE,xs as MAX_SQL_ROWS,ka as NotFoundError,F as NotUniqueError,Ci as OwnerRelay,st as QUEUE_TABLE,St as RANK_TIEBREAK,It as REACTOR_STATE_TABLE,Xt as RELATED_DEFAULT_LIMIT,Ht as RELATED_DEPTH_DECAY,Vt as RELATED_MAX_DEPTH,zt as RELATED_MAX_LIMIT,ol as RELATION_EXISTS_KEY,pa as RELATION_FUNCTION_PREFIX,ds as RELAY_SIGNATURE_HEADER,tl as REPROJECTION_MIGRATION_PREFIX,ki as RLS_UNWRAP_SYMBOL,Ct as ReactiveCache,gi as RelayMember,Bi as RlsRequiredError,Nr as SCAN_DEP,ar as SCHEDULE_OUTBOX_TABLE,wi as SCHEMA_HISTORY_MAX_VERSIONS,Sr as SEARCH_STATE_TABLE,hr as SHAPE_POKE_CURSOR_TABLE,Zi as ShapeDiffCache,ls as ShardRunner,Ks as TransactionHeadroomTracker,yt as UNVOUCHABLE_DEP,js as VECTOR_BACKFILL_MAX_PAGES,to as WORKERD_SQLITE_LIMITS,Ce as advanceClientWatermark,Vr as aggUpsertSql,c as aggregateSqlFunction,f as aggregateTableName,De as allocateCommitSeq,P as appendAuditEntry,Y as appendCdcChange,mo as appendStreamChunk,j as applyCdcChanges,li as applyInsertDefaults,ni as applyOnDelete,za as applySelect,fe as archiveCdcSegment,Wa as armRestore,Zt as assertFlatPredicate,N as assertNoExplicitUndefined,Ua as assertPatchAllowed,hs as assertReadonly,$t as assertShapeShardable,k as assertStorableRowId,B as assertValidClientId,Ds as awaitWsDrain,v as backfillAggregateIndexes,K as backfillRankIndexes,W as backfillSearchIndexes,X as backfillSearchIndexesForTable,Js as backfillVectorIndexes,gs as bigintSqlKey,Zo as boundingBoxCenter,$o as boundingBoxGeohashes,Bt as buildIndexRange,os as buildPokeFrames,Oi as buildReprojectionMigration,Qa as buildSeekBeforeWhere,Ya as buildSeekWhere,Vi as buildSettings,ji as buildShapeDiff,J as bumpCdcEpoch,Ee as cdcArchiveRewound,Z as cdcCanVouchFor,$ as cdcForkedError,ee as cdcSeqLeavingRows,re as cdcTouchesTables,oe as cdcTrimmedError,po as claimStreamRun,Ei as clampPromotionThresholds,Oa as clearCapturedMail,Fe as clearCompanionSignatures,je as clearMemoryTables,lt as clearQueueMessages,E as coerceAggregateNumber,ae as compactCdcDocs,$s as compileWhereSql,ei as composeReadPredicate,er as computeRankPage,ri as containsRelationPredicate,Mi as countLegacyRows,ea as coveringGeohashes,ke as createCompanionSync,kr as createDependencyTracker,Sa as createFanoutCounters,ua as createGlobalPollCounters,zr as createIndexSql,Ft as createReadFootprint,_i as createRelayLink,bi as createReplicaLink,$i as createShapeDiffCache,fa as createShapeProbeCounters,U as createShardCtxDb,Us as createSystemReader,te as cursorBelowRetainedFloor,go as decideDurableAttach,_s as decodeBigintSqlKey,ja as decodeCursor,Is as decodeFloat64SqlKey,tr as deferScheduleOutbox,Ge as deleteGlobalShapeSnapshot,we as deleteGlobalShapeSnapshotsForConnection,Tr as deleteShapePokeCursor,Rr as deleteShapePokeCursorsForConnection,So as deleteStreamRun,Br as depKey,Qt as deriveRelationEdges,ii as describeRelationWrites,Do as diffExternalSource,as as diffGlobalMembership,di as distinctValues,x as encodeAggregateKey,Ja as encodeCursor,ra as encodeGeohash,ut as encodePartitionKey,ts as encodeRowsPatch,O as ensureAuditTable,Ma as ensureMailTable,Io as envOptionalPositiveInt,bo as envPositiveInt,Za as equalityPinnedFields,o as exportShardRows,Ea as facetColumn,ci as fanOutScalarCounts,Yt as findRelated,xa as findStorageReferences,uo as finishStreamRun,bs as float64SqlKey,h as foldAggregateTally,ir as forgetScheduleOutbox,Xo as ftsCompanionDdl,Ho as ftsPurgeDocument,Vo as ftsRowidMapName,zo as ftsUnmappedPage,Qo as ftsWriteDocument,Li as gateReplicaDispatch,Qr as geoTableName,es as globalShapeReadKey,Yo as groupUnmappedRows,Ui as guardWriter,Di as handleReplicaControl,Xs as hasTrigger,oa as haversineMeters,a as importShardRows,Ut as indexKeysForRow,zi as isDevEnvironment,Yr as isFtsAvailable,ll as isInternalTableName,nt as isLossyBody,Je as isMemoryTable,qt as isPushableWhere,oi as isRelationPredicate,wo as isSoftDeleted,qo as isSourceDue,ha as isVacuousFilterClause,jr as jsonPath,Jr as jsonPathSql,Gt as keysTouchRanges,Oo as liftSourceId,Ts as lintReadonlySql,bt as listReactorStates,Ta as listTables,Nt as markUnvouchableReads,ft as matchesRankStaticWhere,m as matchesStaticWhere,No as materializeExternalRows,ko as materializeExternalRowsIncremental,Ze as memoryTableNames,Fs as mergeChangedKeys,C as mergeWhere,ie as migrateCdcLog,se as migrateCdcMeta,ge as migrateClientWatermark,Pe as migrateCommitSeq,fo as migrateDurableStreams,qe as migrateGlobalShapeSnapshot,He as migrateIdempotency,Lt as migrateReactorState,sr as migrateScheduleOutbox,ur as migrateSearchState,Ar as migrateShapePokeCursor,le as minCdcReplayableSeq,ne as minCdcSeq,Cr as minShapePokeCursor,xi as nextPromotionState,zs as nextTtlExpiry,p as normalizeCountArgument,G as normalizeIdStructurally,$a as normalizeOrderKeys,Mo as normalizeSourceDocument,yo as normalizeSourceValue,et as nullsFirstOf,rt as nullsOrderSuffix,Ga as operatorFields,io as param,lr as parkScheduleOutbox,t as parseExportShardArgs,i as parseImportShardArgs,wa as patchDependsOnRow,g as planAggregateLookup,aa as pointInBoundingBox,nr as probeScheduleOutbox,is as projectColumns,vo as pullExternalSourceIncrementalTick,Ko as pullExternalSourceTick,Zr as qualifiedJsonPath,$r as qualifiedJsonPathSql,dl as quoteIdentifier,Et as rankKeyFromDoc,xt as rankPivotConditionSql,ht as rankTableName,gt as reactiveCacheKey,Dt as reactorNeedsRun,T as readAggregateValue,xe as readArchivedCdcChanges,M as readAuditLog,Xa as readBookmark,ya as readCapturedMail,he as readCdcArchivedThrough,de as readCdcChangeKeys,ce as readCdcChanges,me as readCdcCursor,pe as readCdcEpoch,_e as readClientWatermark,Oe as readCommitSeq,Qi as readDeployInfo,dr as readDueScheduleOutbox,Bo as readExternalSourceBaseline,ve as readGlobalShapeSnapshot,Ve as readIdempotent,Mr as readMigrationStatus,qa as readPatchField,dt as readQueueMessageById,ct as readQueueMessages,Pt as readReactorState,qi as readSchemaHistory,vi as readSchemaVersion,fr as readSearchBackfillState,gr as readShapePokeCursor,Eo as readStreamChunks,xo as readStreamRun,Ra as readTablePage,Fa as recordCapturedMail,Ns as recordChangedKeys,Aa as recordFanoutPass,Ca as recordGlobalPollPass,mt as recordQueueMessages,cr as recordScheduleOutbox,Ki as recordSchemaVersion,ga as recordShapeProbePass,mi as relationHooks,hi as relayCountFor,so as renderSql,yi as reprojectableFields,il as reprojectionMigrationId,Fi as reprojectionTables,va as resolvePatch,Tt as resolveRankPartition,rr as resolveRankSeekTuple,ai as resolveRelationPredicates,pi as resolveWith,eo as rowToDocument,yr as runDataMigration,wr as runDrizzle,Uo as runExternalSourceTick,Rs as runReadonlySql,Si as runRowValidators,ml as runShardMigrations,fs as runSocketPool,qr as runSql,Hs as runTriggers,Qs as selectExpiredIds,s as selectExportTables,_ as selectIndexForAggregate,I as selectIndexForCount,b as selectIndexForGroupBy,_a as selectMatchingIds,Lr as selectShapeMembers,Dr as selectShapeRows,Xi as serializeSqlValue,el as serverInList,Ti as shapeRoutingKey,cs as siblingSecretOf,ms as signSiblingBody,ot as softDeleteScope,Rt as sortColumnName,lo as sqliteInList,Sl as stableStringify,ul as stableWireKey,w as stripReservedPatchFields,ps as stubByName,Ps as subscriptionFrames,Os as subscriptionListDeltas,Ia as summarizeFanoutTopics,ba as summarizeSubscriptions,ro as tableColumns,Ur as tableFromDepKey,S as throwingScheduler,at as tiebreakDirectionFor,Se as trimCdcChanges,ze as trimIdempotent,mr as trimScheduleOutbox,ho as trimStreamRuns,oo as tryRowToDocument,Ms as trySendFrame,no as unionAll,tt as uniqueIndexFields,l as validateImportRow,Ss as verifySiblingBody,vt as whereFilter,Kt as whereOfFilter,Te as writeCdcArchivedThrough,Ke as writeGlobalShapeSnapshot,Qe as writeIdempotent,Ot as writeReactorState,Er as writeSearchBackfillState,_r as writeShapePokeCursor,Ir as writeShapePokeCursors,ks as writeTouchesMemo};
1
+ import{exportShardRows as o,importShardRows as a,parseExportShardArgs as t,parseImportShardArgs as i,selectExportTables as s,validateImportRow as l}from"./packem_shared/exportShardRows-6NxY9jMV.mjs";import{AGGREGATE_SQL_FUNCTION as d,aggregateSqlFunction as c,matchesStaticWhere as m,normalizeCountArgument as p,throwingScheduler as S}from"./packem_shared/AGGREGATE_SQL_FUNCTION-C_ZipS9R.mjs";import{aggregateTableName as f,coerceAggregateNumber as x,encodeAggregateKey as E,foldAggregateTally as h,readAggregateValue as T}from"./packem_shared/aggregateTableName-B_CtIQCS.mjs";import{CountRlsUnsupportedError as A,mergeWhere as C,planAggregateLookup as g,selectIndexForAggregate as _,selectIndexForCount as I,selectIndexForGroupBy as b}from"./packem_shared/CountRlsUnsupportedError-BvsDqfO2.mjs";import{AUDIT_LOG_TABLE as D,appendAuditEntry as P,ensureAuditTable as O,readAuditLog as M}from"./packem_shared/AUDIT_LOG_TABLE-BFJ65SRS.mjs";import{NotUniqueError as F,assertNoExplicitUndefined as N,assertStorableRowId as k,assertValidClientId as B,createShardCtxDb as U,normalizeIdStructurally as G,stripReservedPatchFields as w}from"./packem_shared/NotUniqueError-DvGeO5_k.mjs";import{backfillAggregateIndexes as v,backfillRankIndexes as K,backfillSearchIndexes as W,backfillSearchIndexesForTable as X}from"./packem_shared/backfillAggregateIndexes-BN0NwXQk.mjs";import{CDC_LOG_TABLE as V,CDC_LOG_TABLE_SEQ_INDEX as z,CDC_META_TABLE as Q,appendCdcChange as Y,applyCdcChanges as j,bumpCdcEpoch as J,cdcCanVouchFor as Z,cdcForkedError as $,cdcSeqLeavingRows as ee,cdcTouchesTables as re,cdcTrimmedError as oe,compactCdcDocs as ae,cursorBelowRetainedFloor as te,migrateCdcLog as ie,migrateCdcMeta as se,minCdcReplayableSeq as le,minCdcSeq as ne,readCdcChangeKeys as de,readCdcChanges as ce,readCdcCursor as me,readCdcEpoch as pe,trimCdcChanges as Se}from"./packem_shared/CDC_LOG_TABLE-oPp25hdi.mjs";import{archiveCdcSegment as fe,cdcArchiveRewound as xe,readArchivedCdcChanges as Ee,readCdcArchivedThrough as he,writeCdcArchivedThrough as Te}from"./packem_shared/archiveCdcSegment-Cr8oGLfB.mjs";import{CLIENT_WATERMARK_TABLE as Ae,advanceClientWatermark as Ce,migrateClientWatermark as ge,readClientWatermark as _e}from"./packem_shared/CLIENT_WATERMARK_TABLE-De7z_OHV.mjs";import{COMMIT_SEQ_FIELD as be,COMMIT_SEQ_TABLE as Le,allocateCommitSeq as De,migrateCommitSeq as Pe,readCommitSeq as Oe}from"./packem_shared/COMMIT_SEQ_FIELD-Da1DjGqo.mjs";import{CompanionMemo as ye,clearCompanionSignatures as Fe}from"./packem_shared/CompanionMemo-BXU5vfak.mjs";import{createCompanionSync as ke}from"./packem_shared/createCompanionSync-zIF_F4oD.mjs";import{GLOBAL_SHAPE_SNAPSHOT_TABLE as Ue,deleteGlobalShapeSnapshot as Ge,deleteGlobalShapeSnapshotsForConnection as we,migrateGlobalShapeSnapshot as qe,readGlobalShapeSnapshot as ve,writeGlobalShapeSnapshot as Ke}from"./packem_shared/GLOBAL_SHAPE_SNAPSHOT_TABLE-Bb6-aZuH.mjs";import{IDEMPOTENCY_TABLE as Xe,migrateIdempotency as He,readIdempotent as Ve,trimIdempotent as ze,writeIdempotent as Qe}from"./packem_shared/IDEMPOTENCY_TABLE-COrgeP3O.mjs";import{clearMemoryTables as je,isMemoryTable as Je,memoryTableNames as Ze}from"./packem_shared/clearMemoryTables-aMRERF0w.mjs";import{computeRankPage as er,resolveRankSeekTuple as rr}from"./packem_shared/computeRankPage-BZIpATcs.mjs";import{SCHEDULE_OUTBOX_TABLE as ar,deferScheduleOutbox as tr,forgetScheduleOutbox as ir,migrateScheduleOutbox as sr,parkScheduleOutbox as lr,probeScheduleOutbox as nr,readDueScheduleOutbox as dr,recordScheduleOutbox as cr,trimScheduleOutbox as mr}from"./packem_shared/SCHEDULE_OUTBOX_TABLE-DcZI7Yhl.mjs";import{S as Sr,m as ur,r as fr,w as xr}from"./packem_shared/ctx-db-search-state-FjgzTFok.mjs";import{SHAPE_POKE_CURSOR_TABLE as hr,deleteShapePokeCursor as Tr,deleteShapePokeCursorsForConnection as Rr,migrateShapePokeCursor as Ar,minShapePokeCursor as Cr,readShapePokeCursor as gr,writeShapePokeCursor as _r,writeShapePokeCursors as Ir}from"./packem_shared/SHAPE_POKE_CURSOR_TABLE-BGvY3sFI.mjs";import{selectShapeMembers as Lr,selectShapeRows as Dr}from"./packem_shared/selectShapeMembers-BCfKypfN.mjs";import{DATA_MIGRATION_STATE_TABLE as Or,readMigrationStatus as Mr,runDataMigration as yr}from"./packem_shared/DATA_MIGRATION_STATE_TABLE-CFvBS9-M.mjs";import{SCAN_DEP as Nr,createDependencyTracker as kr,depKey as Br,tableFromDepKey as Ur}from"./packem_shared/SCAN_DEP-D7qE3iUe.mjs";import{runDrizzle as wr,runSql as qr}from"./packem_shared/runDrizzle-RC09zZrh.mjs";import{A as Kr,a as Wr,b as Xr,D as Hr,c as Vr,d as zr,g as Qr,i as Yr,j as jr,e as Jr,q as Zr,f as $r,r as eo,t as ro,h as oo}from"./packem_shared/do-sql-BWrJQAOh.mjs";import{WORKERD_SQLITE_LIMITS as to,param as io,renderSql as so,sqliteInList as lo,unionAll as no}from"./packem_shared/WORKERD_SQLITE_LIMITS-B_4w7tzY.mjs";import{appendStreamChunk as mo,claimStreamRun as po,deleteStreamRun as So,finishStreamRun as uo,migrateDurableStreams as fo,readStreamChunks as xo,readStreamRun as Eo,trimStreamRuns as ho}from"./packem_shared/appendStreamChunk-BZYgGE9Y.mjs";import{DurableStreamRunner as Ro,MAX_DURABLE_STREAM_BYTES as Ao,MAX_DURABLE_STREAM_CHUNKS as Co,decideDurableAttach as go}from"./packem_shared/DurableStreamRunner-MMlV5qKQ.mjs";import{envOptionalPositiveInt as Io,envPositiveInt as bo}from"./packem_shared/envOptionalPositiveInt-D2pY-c64.mjs";import{diffExternalSource as Do}from"./packem_shared/diffExternalSource-B0FZlDoL.mjs";import{liftSourceId as Oo,normalizeSourceDocument as Mo,normalizeSourceValue as yo}from"./packem_shared/liftSourceId-CA3ENhXj.mjs";import{materializeExternalRows as No,materializeExternalRowsIncremental as ko,readExternalSourceBaseline as Bo,runExternalSourceTick as Uo}from"./packem_shared/materializeExternalRows-DzUChRJ-.mjs";import{isSoftDeleted as wo,isSourceDue as qo,pullExternalSourceIncrementalTick as vo,pullExternalSourceTick as Ko}from"./packem_shared/isSoftDeleted-BYZ0sPyu.mjs";import{f as Xo,a as Ho,b as Vo,c as zo,d as Qo,g as Yo}from"./packem_shared/fts-companion-CA8mLJWq.mjs";import{GEO_DEFAULT_PRECISION as Jo,boundingBoxCenter as Zo,boundingBoxGeohashes as $o,coveringGeohashes as ea,encodeGeohash as ra,haversineMeters as oa,pointInBoundingBox as aa}from"./packem_shared/GEO_DEFAULT_PRECISION-CqpQZ-J_.mjs";import{default as ia}from"./packem_shared/GlobalPollTick-BNK4o-XT.mjs";import{ADMIN_FUNCTIONS as la,ADMIN_FUNCTION_PREFIX as na,DEFAULT_FANOUT_TOPIC_LIMIT as da,FLAGS_FUNCTION_PREFIX as ca,MAX_PAGE_SIZE as ma,RELATION_FUNCTION_PREFIX as pa,createFanoutCounters as Sa,createGlobalPollCounters as ua,createShapeProbeCounters as fa,facetColumn as xa,findStorageReferences as Ea,isVacuousFilterClause as ha,listTables as Ta,readTablePage as Ra,recordFanoutPass as Aa,recordGlobalPollPass as Ca,recordShapeProbePass as ga,selectMatchingIds as _a,summarizeFanoutTopics as Ia,summarizeSubscriptions as ba}from"./packem_shared/ADMIN_FUNCTIONS-zJra0V3L.mjs";import{MAIL_RETENTION as Da,MAIL_TABLE as Pa,clearCapturedMail as Oa,ensureMailTable as Ma,readCapturedMail as ya,recordCapturedMail as Fa}from"./packem_shared/MAIL_RETENTION-DMolrLYt.mjs";import{NotFoundError as ka}from"./packem_shared/NotFoundError-BhF7FeFr.mjs";import{assertPatchAllowed as Ua,operatorFields as Ga,patchDependsOnRow as wa,readPatchField as qa,resolvePatch as va}from"./packem_shared/assertPatchAllowed-CA_H466g.mjs";import{armRestore as Wa,readBookmark as Xa}from"./packem_shared/armRestore-Bu1_8SUa.mjs";import{CURSOR_PREFIX as Va,applySelect as za,buildSeekBeforeWhere as Qa,buildSeekWhere as Ya,decodeCursor as ja,encodeCursor as Ja,equalityPinnedFields as Za,normalizeOrderKeys as $a,nullsFirstOf as et,nullsOrderSuffix as rt,softDeleteScope as ot,tiebreakDirectionFor as at,uniqueIndexFields as tt}from"./packem_shared/CURSOR_PREFIX-6offuG6M.mjs";import{QUEUE_TABLE as st,clearQueueMessages as lt,isLossyBody as nt,readQueueMessageById as dt,readQueueMessages as ct,recordQueueMessages as mt}from"./packem_shared/QUEUE_TABLE-C-goXtGd.mjs";import{RANK_TIEBREAK as St,encodePartitionKey as ut,matchesRankStaticWhere as ft,rankKeyFromDoc as xt,rankPivotConditionSql as Et,rankTableName as ht,resolveRankPartition as Tt,sortColumnName as Rt}from"./packem_shared/RANK_TIEBREAK-D3ye2GsL.mjs";import{ReactiveCache as Ct,reactiveCacheKey as gt}from"./packem_shared/ReactiveCache-DHhhLJtN.mjs";import{REACTOR_STATE_TABLE as It,listReactorStates as bt,migrateReactorState as Lt,reactorNeedsRun as Dt,readReactorState as Pt,writeReactorState as Ot}from"./packem_shared/REACTOR_STATE_TABLE-D2Mn204f.mjs";import{UNVOUCHABLE_DEP as yt,createReadFootprint as Ft,markUnvouchableReads as Nt}from"./packem_shared/UNVOUCHABLE_DEP-C68htACn.mjs";import{buildIndexRange as Bt,indexKeysForRow as Ut,keysTouchRanges as Gt}from"./packem_shared/buildIndexRange-DQ3eWAGd.mjs";import{isPushableWhere as qt,whereFilter as vt,whereOfFilter as Kt}from"./packem_shared/isPushableWhere-BeYAOjUb.mjs";import{RELATED_DEFAULT_LIMIT as Xt,RELATED_DEPTH_DECAY as Ht,RELATED_MAX_DEPTH as Vt,RELATED_MAX_LIMIT as zt,deriveRelationEdges as Qt,findRelated as Yt}from"./packem_shared/RELATED_DEFAULT_LIMIT-CVqN4JEu.mjs";import{DEFAULT_MAX_RELATION_KEYS as Jt,assertFlatPredicate as Zt,assertShapeShardable as $t,composeReadPredicate as ei,containsRelationPredicate as ri,isRelationPredicate as oi,resolveRelationPredicates as ai}from"./packem_shared/DEFAULT_MAX_RELATION_KEYS-9eOkadE4.mjs";import{describeRelationWrites as ii}from"./packem_shared/describeRelationWrites-omar6-u9.mjs";import{applyInsertDefaults as li,applyOnDelete as ni,distinctValues as di,fanOutScalarCounts as ci,relationHooks as mi,resolveWith as pi,runRowValidators as Si}from"./packem_shared/applyInsertDefaults-B0NXPs2x.mjs";import{DEFAULT_PROMOTION_THRESHOLDS as fi,clampPromotionThresholds as xi,nextPromotionState as Ei,relayCountFor as hi,shapeRoutingKey as Ti}from"./packem_shared/DEFAULT_PROMOTION_THRESHOLDS-B3pRMuqb.mjs";import{DEFAULT_MAX_RELAYS as Ai,OwnerRelay as Ci,RelayMember as gi,createRelayLink as _i}from"./packem_shared/DEFAULT_MAX_RELAYS-B1jshtuE.mjs";import{createReplicaLink as bi,gateReplicaDispatch as Li,handleReplicaControl as Di}from"./packem_shared/createReplicaLink-CxVPj3iC.mjs";import{buildReprojectionMigration as Oi,countLegacyRows as Mi,reprojectableFields as yi,reprojectionTables as Fi}from"./packem_shared/buildReprojectionMigration-Ds2JaFo7.mjs";import{RLS_UNWRAP_SYMBOL as ki,RlsRequiredError as Bi,guardWriter as Ui}from"./packem_shared/RLS_UNWRAP_SYMBOL-H6J96vgK.mjs";import{SCHEMA_HISTORY_MAX_VERSIONS as wi,readSchemaHistory as qi,readSchemaVersion as vi,recordSchemaVersion as Ki}from"./packem_shared/SCHEMA_HISTORY_MAX_VERSIONS-CEwFjj-O.mjs";import{serializeSqlValue as Xi}from"./packem_shared/serializeSqlValue-DeoBMpZ2.mjs";import{buildSettings as Vi,isDevEnvironment as zi,readDeployInfo as Qi}from"./packem_shared/buildSettings-BRkZd6_E.mjs";import{buildShapeDiff as ji}from"./packem_shared/buildShapeDiff-BfTX-roE.mjs";import{ShapeDiffCache as Zi,createShapeDiffCache as $i,globalShapeReadKey as es}from"./packem_shared/ShapeDiffCache-iNO-hUiy.mjs";import{buildPokeFrames as os,diffGlobalMembership as as,encodeRowsPatch as ts,projectColumns as is}from"./packem_shared/buildPokeFrames-WR-hp0mX.mjs";import{ShardRunner as ls}from"./packem_shared/ShardRunner-CrveaPId.mjs";import{stubByName as ds}from"./packem_shared/stubByName-DLPoppDc.mjs";import{runSocketPool as ms}from"./packem_shared/runSocketPool-CZJ2X9cF.mjs";import{MAX_SQL_ROWS as Ss,assertReadonly as us,lintReadonlySql as fs,runReadonlySql as xs}from"./packem_shared/MAX_SQL_ROWS-eRignWyO.mjs";import{BIGINT_KEY_DIGITS as hs,bigintSqlKey as Ts,decodeBigintSqlKey as Rs,decodeFloat64SqlKey as As,float64SqlKey as Cs}from"./packem_shared/BIGINT_KEY_DIGITS-DE6yshOt.mjs";import{awaitWsDrain as _s,subscriptionFrames as Is,subscriptionListDeltas as bs,trySendFrame as Ls}from"./packem_shared/awaitWsDrain-e88vUNdj.mjs";import{mergeChangedKeys as Ps,recordChangedKeys as Os,writeTouchesMemo as Ms}from"./packem_shared/mergeChangedKeys-BHUURyp6.mjs";import{createSystemReader as Fs}from"./packem_shared/createSystemReader-DcDLFfC-.mjs";import{ConflictError as ks}from"./packem_shared/ConflictError-C8GtJmjS.mjs";import{DEFAULT_TRANSACTION_LIMITS as Us,TransactionHeadroomTracker as Gs}from"./packem_shared/DEFAULT_TRANSACTION_LIMITS-Dmj5VBrV.mjs";import{hasTrigger as qs,runTriggers as vs}from"./packem_shared/hasTrigger-CjlwI4le.mjs";import{nextTtlExpiry as Ws,selectExpiredIds as Xs}from"./packem_shared/nextTtlExpiry-DhKO_OpO.mjs";import{VECTOR_BACKFILL_MAX_PAGES as Vs,backfillVectorIndexes as zs}from"./packem_shared/VECTOR_BACKFILL_MAX_PAGES-loOUGfzw.mjs";import{c as Ys,s as js}from"./packem_shared/where-sql-BjY4rnqb.mjs";import{RELATION_EXISTS_KEY as Zs}from"./packem_shared/RELATION_EXISTS_KEY-wxgj6rSL.mjs";import{RELAY_SIGNATURE_HEADER as el,siblingSecretOf as rl,signSiblingBody as ol,verifySiblingBody as al}from"./packem_shared/RELAY_SIGNATURE_HEADER-DNzVQxbZ.mjs";import{REPROJECTION_MIGRATION_PREFIX as il,reprojectionMigrationId as sl}from"./packem_shared/REPROJECTION_MIGRATION_PREFIX-Czcb6_mO.mjs";import{isInternalTableName as nl}from"./packem_shared/isInternalTableName-BoljO2tP.mjs";import{quoteIdentifier as cl}from"./packem_shared/quoteIdentifier-CObIFRhb.mjs";import{runShardMigrations as pl}from"./packem_shared/runShardMigrations-BXGBfJU1.mjs";import{stableStringify as ul,stableWireKey as fl}from"@lunora/wire";export{la as ADMIN_FUNCTIONS,na as ADMIN_FUNCTION_PREFIX,d as AGGREGATE_SQL_FUNCTION,Kr as AGG_COUNT,Wr as AGG_KEY,Xr as AGG_VALUE,D as AUDIT_LOG_TABLE,hs as BIGINT_KEY_DIGITS,V as CDC_LOG_TABLE,z as CDC_LOG_TABLE_SEQ_INDEX,Q as CDC_META_TABLE,Ae as CLIENT_WATERMARK_TABLE,be as COMMIT_SEQ_FIELD,Le as COMMIT_SEQ_TABLE,Va as CURSOR_PREFIX,ye as CompanionMemo,ks as ConflictError,A as CountRlsUnsupportedError,Or as DATA_MIGRATION_STATE_TABLE,da as DEFAULT_FANOUT_TOPIC_LIMIT,Jt as DEFAULT_MAX_RELATION_KEYS,Ai as DEFAULT_MAX_RELAYS,fi as DEFAULT_PROMOTION_THRESHOLDS,Us as DEFAULT_TRANSACTION_LIMITS,Hr as DOC_COLUMN,Ro as DurableStreamRunner,ca as FLAGS_FUNCTION_PREFIX,Jo as GEO_DEFAULT_PRECISION,Ue as GLOBAL_SHAPE_SNAPSHOT_TABLE,ia as GlobalPollTick,Xe as IDEMPOTENCY_TABLE,Da as MAIL_RETENTION,Pa as MAIL_TABLE,Ao as MAX_DURABLE_STREAM_BYTES,Co as MAX_DURABLE_STREAM_CHUNKS,ma as MAX_PAGE_SIZE,Ss as MAX_SQL_ROWS,ka as NotFoundError,F as NotUniqueError,Ci as OwnerRelay,st as QUEUE_TABLE,St as RANK_TIEBREAK,It as REACTOR_STATE_TABLE,Xt as RELATED_DEFAULT_LIMIT,Ht as RELATED_DEPTH_DECAY,Vt as RELATED_MAX_DEPTH,zt as RELATED_MAX_LIMIT,Zs as RELATION_EXISTS_KEY,pa as RELATION_FUNCTION_PREFIX,el as RELAY_SIGNATURE_HEADER,il as REPROJECTION_MIGRATION_PREFIX,ki as RLS_UNWRAP_SYMBOL,Ct as ReactiveCache,gi as RelayMember,Bi as RlsRequiredError,Nr as SCAN_DEP,ar as SCHEDULE_OUTBOX_TABLE,wi as SCHEMA_HISTORY_MAX_VERSIONS,Sr as SEARCH_STATE_TABLE,hr as SHAPE_POKE_CURSOR_TABLE,Zi as ShapeDiffCache,ls as ShardRunner,Gs as TransactionHeadroomTracker,yt as UNVOUCHABLE_DEP,Vs as VECTOR_BACKFILL_MAX_PAGES,to as WORKERD_SQLITE_LIMITS,Ce as advanceClientWatermark,Vr as aggUpsertSql,c as aggregateSqlFunction,f as aggregateTableName,De as allocateCommitSeq,P as appendAuditEntry,Y as appendCdcChange,mo as appendStreamChunk,j as applyCdcChanges,li as applyInsertDefaults,ni as applyOnDelete,za as applySelect,fe as archiveCdcSegment,Wa as armRestore,Zt as assertFlatPredicate,N as assertNoExplicitUndefined,Ua as assertPatchAllowed,us as assertReadonly,$t as assertShapeShardable,k as assertStorableRowId,B as assertValidClientId,_s as awaitWsDrain,v as backfillAggregateIndexes,K as backfillRankIndexes,W as backfillSearchIndexes,X as backfillSearchIndexesForTable,zs as backfillVectorIndexes,Ts as bigintSqlKey,Zo as boundingBoxCenter,$o as boundingBoxGeohashes,Bt as buildIndexRange,os as buildPokeFrames,Oi as buildReprojectionMigration,Qa as buildSeekBeforeWhere,Ya as buildSeekWhere,Vi as buildSettings,ji as buildShapeDiff,J as bumpCdcEpoch,xe as cdcArchiveRewound,Z as cdcCanVouchFor,$ as cdcForkedError,ee as cdcSeqLeavingRows,re as cdcTouchesTables,oe as cdcTrimmedError,po as claimStreamRun,xi as clampPromotionThresholds,Oa as clearCapturedMail,Fe as clearCompanionSignatures,je as clearMemoryTables,lt as clearQueueMessages,x as coerceAggregateNumber,ae as compactCdcDocs,Ys as compileWhereSql,ei as composeReadPredicate,er as computeRankPage,ri as containsRelationPredicate,Mi as countLegacyRows,ea as coveringGeohashes,ke as createCompanionSync,kr as createDependencyTracker,Sa as createFanoutCounters,ua as createGlobalPollCounters,zr as createIndexSql,Ft as createReadFootprint,_i as createRelayLink,bi as createReplicaLink,$i as createShapeDiffCache,fa as createShapeProbeCounters,U as createShardCtxDb,Fs as createSystemReader,te as cursorBelowRetainedFloor,go as decideDurableAttach,Rs as decodeBigintSqlKey,ja as decodeCursor,As as decodeFloat64SqlKey,tr as deferScheduleOutbox,Ge as deleteGlobalShapeSnapshot,we as deleteGlobalShapeSnapshotsForConnection,Tr as deleteShapePokeCursor,Rr as deleteShapePokeCursorsForConnection,So as deleteStreamRun,Br as depKey,Qt as deriveRelationEdges,ii as describeRelationWrites,Do as diffExternalSource,as as diffGlobalMembership,di as distinctValues,E as encodeAggregateKey,Ja as encodeCursor,ra as encodeGeohash,ut as encodePartitionKey,ts as encodeRowsPatch,O as ensureAuditTable,Ma as ensureMailTable,Io as envOptionalPositiveInt,bo as envPositiveInt,Za as equalityPinnedFields,o as exportShardRows,xa as facetColumn,ci as fanOutScalarCounts,Yt as findRelated,Ea as findStorageReferences,uo as finishStreamRun,Cs as float64SqlKey,h as foldAggregateTally,ir as forgetScheduleOutbox,Xo as ftsCompanionDdl,Ho as ftsPurgeDocument,Vo as ftsRowidMapName,zo as ftsUnmappedPage,Qo as ftsWriteDocument,Li as gateReplicaDispatch,Qr as geoTableName,es as globalShapeReadKey,Yo as groupUnmappedRows,Ui as guardWriter,Di as handleReplicaControl,qs as hasTrigger,oa as haversineMeters,a as importShardRows,Ut as indexKeysForRow,zi as isDevEnvironment,Yr as isFtsAvailable,nl as isInternalTableName,nt as isLossyBody,Je as isMemoryTable,qt as isPushableWhere,oi as isRelationPredicate,wo as isSoftDeleted,qo as isSourceDue,ha as isVacuousFilterClause,jr as jsonPath,Jr as jsonPathSql,Gt as keysTouchRanges,Oo as liftSourceId,fs as lintReadonlySql,bt as listReactorStates,Ta as listTables,Nt as markUnvouchableReads,ft as matchesRankStaticWhere,m as matchesStaticWhere,No as materializeExternalRows,ko as materializeExternalRowsIncremental,Ze as memoryTableNames,Ps as mergeChangedKeys,C as mergeWhere,ie as migrateCdcLog,se as migrateCdcMeta,ge as migrateClientWatermark,Pe as migrateCommitSeq,fo as migrateDurableStreams,qe as migrateGlobalShapeSnapshot,He as migrateIdempotency,Lt as migrateReactorState,sr as migrateScheduleOutbox,ur as migrateSearchState,Ar as migrateShapePokeCursor,le as minCdcReplayableSeq,ne as minCdcSeq,Cr as minShapePokeCursor,Ei as nextPromotionState,Ws as nextTtlExpiry,p as normalizeCountArgument,G as normalizeIdStructurally,$a as normalizeOrderKeys,Mo as normalizeSourceDocument,yo as normalizeSourceValue,et as nullsFirstOf,rt as nullsOrderSuffix,Ga as operatorFields,io as param,lr as parkScheduleOutbox,t as parseExportShardArgs,i as parseImportShardArgs,wa as patchDependsOnRow,g as planAggregateLookup,aa as pointInBoundingBox,nr as probeScheduleOutbox,is as projectColumns,vo as pullExternalSourceIncrementalTick,Ko as pullExternalSourceTick,Zr as qualifiedJsonPath,$r as qualifiedJsonPathSql,cl as quoteIdentifier,xt as rankKeyFromDoc,Et as rankPivotConditionSql,ht as rankTableName,gt as reactiveCacheKey,Dt as reactorNeedsRun,T as readAggregateValue,Ee as readArchivedCdcChanges,M as readAuditLog,Xa as readBookmark,ya as readCapturedMail,he as readCdcArchivedThrough,de as readCdcChangeKeys,ce as readCdcChanges,me as readCdcCursor,pe as readCdcEpoch,_e as readClientWatermark,Oe as readCommitSeq,Qi as readDeployInfo,dr as readDueScheduleOutbox,Bo as readExternalSourceBaseline,ve as readGlobalShapeSnapshot,Ve as readIdempotent,Mr as readMigrationStatus,qa as readPatchField,dt as readQueueMessageById,ct as readQueueMessages,Pt as readReactorState,qi as readSchemaHistory,vi as readSchemaVersion,fr as readSearchBackfillState,gr as readShapePokeCursor,xo as readStreamChunks,Eo as readStreamRun,Ra as readTablePage,Fa as recordCapturedMail,Os as recordChangedKeys,Aa as recordFanoutPass,Ca as recordGlobalPollPass,mt as recordQueueMessages,cr as recordScheduleOutbox,Ki as recordSchemaVersion,ga as recordShapeProbePass,mi as relationHooks,hi as relayCountFor,so as renderSql,yi as reprojectableFields,sl as reprojectionMigrationId,Fi as reprojectionTables,va as resolvePatch,Tt as resolveRankPartition,rr as resolveRankSeekTuple,ai as resolveRelationPredicates,pi as resolveWith,eo as rowToDocument,yr as runDataMigration,wr as runDrizzle,Uo as runExternalSourceTick,xs as runReadonlySql,Si as runRowValidators,pl as runShardMigrations,ms as runSocketPool,qr as runSql,vs as runTriggers,Xs as selectExpiredIds,s as selectExportTables,_ as selectIndexForAggregate,I as selectIndexForCount,b as selectIndexForGroupBy,_a as selectMatchingIds,Lr as selectShapeMembers,Dr as selectShapeRows,Xi as serializeSqlValue,js as serverInList,Ti as shapeRoutingKey,rl as siblingSecretOf,ol as signSiblingBody,ot as softDeleteScope,Rt as sortColumnName,lo as sqliteInList,ul as stableStringify,fl as stableWireKey,w as stripReservedPatchFields,ds as stubByName,Is as subscriptionFrames,bs as subscriptionListDeltas,Ia as summarizeFanoutTopics,ba as summarizeSubscriptions,ro as tableColumns,Ur as tableFromDepKey,S as throwingScheduler,at as tiebreakDirectionFor,Se as trimCdcChanges,ze as trimIdempotent,mr as trimScheduleOutbox,ho as trimStreamRuns,oo as tryRowToDocument,Ls as trySendFrame,no as unionAll,tt as uniqueIndexFields,l as validateImportRow,al as verifySiblingBody,vt as whereFilter,Kt as whereOfFilter,Te as writeCdcArchivedThrough,Ke as writeGlobalShapeSnapshot,Qe as writeIdempotent,Ot as writeReactorState,xr as writeSearchBackfillState,_r as writeShapePokeCursor,Ir as writeShapePokeCursors,Ms as writeTouchesMemo};
@@ -15,4 +15,4 @@ import{LunoraError as R}from"@lunora/errors";import{sql as t}from"drizzle-orm";i
15
15
  SELECT seq FROM ${t.identifier(c)} WHERE seq <= ${o} ORDER BY seq ASC LIMIT ${i}
16
16
  )`)},P=(e,o,i)=>{n(e,t`UPDATE ${t.identifier(c)} SET doc = NULL WHERE seq IN (
17
17
  SELECT seq FROM ${t.identifier(c)} WHERE seq <= ${o} AND doc IS NOT NULL ORDER BY seq ASC LIMIT ${i}
18
- )`)},G=(e,o)=>{if(o<=0)return n(e,t`SELECT MAX(seq) AS seq FROM ${t.identifier(c)}`).toArray()[0]?.seq??void 0;const r=n(e,t`SELECT seq FROM ${t.identifier(c)} ORDER BY seq DESC LIMIT 1 OFFSET ${o-1}`).toArray()[0]?.seq;return r===void 0?void 0:r-1},K=e=>{const i=n(e,t`SELECT seq FROM sqlite_sequence WHERE name = ${c}`).toArray()[0]?.seq;return typeof i=="number"?i:n(e,t`SELECT MAX(seq) AS seq FROM ${t.identifier(c)}`).toArray()[0]?.seq??0},k=(e,o)=>e!==void 0&&e>o+1,V=(e,o,i)=>new R("CDC_LOG_TRIMMED",`${i==="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}),z=(e,o,i,r)=>new R("CDC_TIMELINE_FORKED",`${i==="global"?"global cdc":"cdc"} cursor ${String(o)} is above ${i==="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${r===void 0?"":` at epoch ${r}`}`,{data:{cursor:e,...r===void 0?{}:{epoch:r}},status:409}),D=e=>n(e,t`SELECT MIN(seq) AS seq FROM ${t.identifier(c)}`).toArray()[0]?.seq??void 0,Q=e=>{const i=n(e,t`SELECT MAX(seq) AS seq FROM ${t.identifier(c)} WHERE ${u}`).toArray()[0]?.seq??void 0,r=D(e);return i===void 0?r:Math.max(i+1,r??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)`)},J=e=>{L(e);const i=n(e,t`SELECT epoch FROM ${t.identifier(E)} WHERE id = 1`).toArray()[0]?.epoch;if(typeof i=="string"&&i.length>0)return i;const r=crypto.randomUUID();return n(e,t`INSERT INTO ${t.identifier(E)} (id, epoch) VALUES (1, ${r})`),r},j=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 i=o.doc??{},r=async()=>{const s={...i};delete s._id,await e.replace(o.id,s,o.table,{allowExplicitId:!0})};if(o.id.includes("\0")&&await e.get(o.table,o.id)!==null){await r();return}try{await e.insert(o.table,i,{allowExplicitId:!0})}catch(s){if(!(s instanceof p))throw s;await r()}},Z=async(e,o)=>{for(const i of o)await h(e,i)};export{N as CDC_APPEND_SQL,c as CDC_LOG_TABLE,$ as CDC_LOG_TABLE_SEQ_INDEX,E as CDC_META_TABLE,X as appendCdcChange,Z as applyCdcChanges,j as bumpCdcEpoch,H as cdcCanVouchFor,z as cdcForkedError,G as cdcSeqLeavingRows,B as cdcTouchesTables,V as cdcTrimmedError,P as compactCdcDocs,k as cursorBelowRetainedFloor,U as migrateCdcLog,L as migrateCdcMeta,Q as minCdcReplayableSeq,D as minCdcSeq,W as readCdcChangeKeys,v as readCdcChanges,K as readCdcCursor,x as readCdcDocAtOrBefore,J as readCdcEpoch,Y as trimCdcChanges};
18
+ )`)},G=(e,o)=>{if(o<=0)return n(e,t`SELECT MAX(seq) AS seq FROM ${t.identifier(c)}`).toArray()[0]?.seq??void 0;const r=n(e,t`SELECT seq FROM ${t.identifier(c)} ORDER BY seq DESC LIMIT 1 OFFSET ${o-1}`).toArray()[0]?.seq;return r===void 0?void 0:r-1},K=e=>{const i=n(e,t`SELECT seq FROM sqlite_sequence WHERE name = ${c}`).toArray()[0]?.seq;return typeof i=="number"?i:n(e,t`SELECT MAX(seq) AS seq FROM ${t.identifier(c)}`).toArray()[0]?.seq??0},k=(e,o)=>e!==void 0&&e>o+1,V=(e,o,i)=>new R("CDC_LOG_TRIMMED",`${i==="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}),z=(e,o,i,r)=>new R("CDC_TIMELINE_FORKED",`${i==="global"?"global cdc":"cdc"} cursor ${String(o)} is above ${i==="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${r===void 0?"":` at epoch ${r}`}`,{data:{cursor:e,...r===void 0?{}:{epoch:r}},status:409}),D=e=>n(e,t`SELECT MIN(seq) AS seq FROM ${t.identifier(c)}`).toArray()[0]?.seq??void 0,Q=e=>{const i=n(e,t`SELECT MAX(seq) AS seq FROM ${t.identifier(c)} WHERE ${u}`).toArray()[0]?.seq??void 0,r=D(e);return i===void 0?r:Math.max(i+1,r??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)`)},J=e=>{L(e);const i=n(e,t`SELECT epoch FROM ${t.identifier(E)} WHERE id = 1`).toArray()[0]?.epoch;if(typeof i=="string"&&i.length>0)return i;const r=crypto.randomUUID();return n(e,t`INSERT INTO ${t.identifier(E)} (id, epoch) VALUES (1, ${r})`),r},j=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.table,o.id);return}const i=o.doc??{},r=async()=>{const s={...i};delete s._id,await e.replace(o.table,o.id,s,{allowExplicitId:!0})};if(o.id.includes("\0")&&await e.get(o.table,o.id)!==null){await r();return}try{await e.insert(o.table,i,{allowExplicitId:!0})}catch(s){if(!(s instanceof p))throw s;await r()}},Z=async(e,o)=>{for(const i of o)await h(e,i)};export{N as CDC_APPEND_SQL,c as CDC_LOG_TABLE,$ as CDC_LOG_TABLE_SEQ_INDEX,E as CDC_META_TABLE,X as appendCdcChange,Z as applyCdcChanges,j as bumpCdcEpoch,H as cdcCanVouchFor,z as cdcForkedError,G as cdcSeqLeavingRows,B as cdcTouchesTables,V as cdcTrimmedError,P as compactCdcDocs,k as cursorBelowRetainedFloor,U as migrateCdcLog,L as migrateCdcMeta,Q as minCdcReplayableSeq,D as minCdcSeq,W as readCdcChangeKeys,v as readCdcChanges,K as readCdcCursor,x as readCdcDocAtOrBefore,J as readCdcEpoch,Y as trimCdcChanges};
@@ -28,4 +28,4 @@ import{LunoraError as D}from"@lunora/errors";import{stableWireKey as S}from"@lun
28
28
  WHERE
29
29
  "${i}".status <> 'in_progress'
30
30
  OR "${i}".updated_at IS NULL
31
- OR "${i}".updated_at <= excluded.updated_at - ${String(y)}`,t,a,r,r),E(e,"SELECT changes() AS changed").one().changed>0),H=(e,t,a)=>{E(e,`UPDATE "${i}" SET updated_at = ? WHERE id = ? AND status = 'in_progress'`,a,t)},P=(e,t)=>{E(e,`UPDATE "${i}" SET updated_at = 0 WHERE id = ? AND status = 'in_progress'`,t)},j=(e,t)=>{if(E(e,"SELECT name FROM sqlite_master WHERE type = 'table' AND name = ? LIMIT 1",i).toArray().length===0)return[];const r=t===void 0?" ORDER BY id":" WHERE id = ?",d=t===void 0?[]:[t];return E(e,`SELECT * FROM "${i}"${r}`,...d).toArray().map(n=>({...b(n),error:typeof n.error=="string"?n.error:null,id:n.id,startedAt:typeof n.started_at=="number"?n.started_at:null,updatedAt:typeof n.updated_at=="number"?n.updated_at:null}))},W=[{direction:"asc",field:"_creationTime",nullable:!1}],X=/^~[23]/u,B=e=>{if(typeof e!="string")return e;const t=X.exec(e);return t===null?e:C+e.slice(t[0].length)},Y=async e=>{const{document:t,id:a,onSettled:r,previous:d,table:o,writer:n}=e;try{await n.replace(a,t,void 0,{allowExplicitId:!0})}catch(f){const p=await n.get(o,a);throw p!==null&&S(p)!==S(d)&&r("changed"),f}r("changed")},G=3,V=async e=>{const{context:t,document:a,dryRun:r,onSettled:d,table:o,transform:n,writer:f}=e,p=String(a._id);let T=a;for(let h=0;h<G;h+=1){const c=await n(T,t);if(c===void 0){d("unchanged");return}if(r){d("changed");return}const u=await f.get(o,p);if(u===null){d("unchanged");return}if(S(u)===S(T)){await Y({document:{...c,_creationTime:T._creationTime,_id:T._id},id:p,onSettled:d,previous:u,table:o,writer:f});return}T=u}throw new x(`data migration could not rewrite row ${p}: it was modified by concurrent traffic on every attempt`,"occ")},J=async e=>{const{migration:t,sql:a,writer:r}=e,d=e.direction??"up",o=e.dryRun??!1,n=e.clock??(()=>Date.now()),f=e.maxBatches??Number.POSITIVE_INFINITY,p=e.batchSize??t.batchSize??M,T=d==="up"?t.up:t.down;if(!T)throw new D("INTERNAL",`data migration "${t.id}" has no \`${d}\` transform`);const h={db:{count:r.count.bind(r),findFirst:r.findFirst.bind(r),findMany:r.findMany.bind(r),get:r.get.bind(r)}};let c=null,u=0,g=0,A=n();if(!o){$(a);const s=I(a,t.id);if(s?.direction===d&&s.status==="completed")return{changed:s.changed,cursor:null,direction:d,dryRun:o,id:t.id,processed:s.processed,status:"completed"};if(s&&s.direction!==d&&F(a,t.id,n()-y),!v(a,t.id,d,n())){const R=I(a,t.id);return{changed:R?.changed??0,cursor:R?.cursor??c,direction:R?.direction??d,dryRun:o,id:t.id,processed:R?.processed??0,status:R?.status??"in_progress"}}const l=s?.direction===d?s:void 0;l&&(c=B(l.cursor),u=l.processed,g=l.changed,A=l.startedAt??A)}let _=!1,L=0,N=A;try{for(;!_&&L<f;){const s=await r.findMany(t.table,{cursor:c,includeDeleted:!0,limit:p});for(const m of s.page)if(await V({context:h,document:m,dryRun:o,onSettled:l=>{l==="changed"&&(g+=1),u+=1,c=w(m,W)},table:t.table,transform:T,writer:r}),!o){const l=n();l-N>=U&&(H(a,t.id,l),N=l)}if(c=s.continueCursor,_=s.isDone,L+=1,!o){const m=n();O(a,{changed:g,cursor:_?null:c,direction:d,error:null,id:t.id,processed:u,startedAt:A,status:_?"completed":"in_progress",updatedAt:m}),N=m;try{await e.onBatch?.({batches:L,changed:g,processed:u})}catch{}}}}catch(s){throw o||O(a,{changed:g,cursor:c,direction:d,error:s instanceof Error?s.message:String(s),id:t.id,processed:u,startedAt:A,status:"failed",updatedAt:n()}),s}if(!o&&!_)try{P(a,t.id)}catch(s){console.warn(`data migration "${t.id}": releaseClaim failed`,s)}return{changed:g,cursor:_?null:c,direction:d,dryRun:o,id:t.id,processed:u,status:_?"completed":"in_progress"}};export{i as DATA_MIGRATION_STATE_TABLE,j as readMigrationStatus,J as runDataMigration};
31
+ OR "${i}".updated_at <= excluded.updated_at - ${String(y)}`,t,a,r,r),E(e,"SELECT changes() AS changed").one().changed>0),H=(e,t,a)=>{E(e,`UPDATE "${i}" SET updated_at = ? WHERE id = ? AND status = 'in_progress'`,a,t)},P=(e,t)=>{E(e,`UPDATE "${i}" SET updated_at = 0 WHERE id = ? AND status = 'in_progress'`,t)},j=(e,t)=>{if(E(e,"SELECT name FROM sqlite_master WHERE type = 'table' AND name = ? LIMIT 1",i).toArray().length===0)return[];const r=t===void 0?" ORDER BY id":" WHERE id = ?",d=t===void 0?[]:[t];return E(e,`SELECT * FROM "${i}"${r}`,...d).toArray().map(n=>({...b(n),error:typeof n.error=="string"?n.error:null,id:n.id,startedAt:typeof n.started_at=="number"?n.started_at:null,updatedAt:typeof n.updated_at=="number"?n.updated_at:null}))},W=[{direction:"asc",field:"_creationTime",nullable:!1}],X=/^~[23]/u,B=e=>{if(typeof e!="string")return e;const t=X.exec(e);return t===null?e:C+e.slice(t[0].length)},Y=async e=>{const{document:t,id:a,onSettled:r,previous:d,table:o,writer:n}=e;try{await n.replace(o,a,t,{allowExplicitId:!0})}catch(f){const p=await n.get(o,a);throw p!==null&&S(p)!==S(d)&&r("changed"),f}r("changed")},G=3,V=async e=>{const{context:t,document:a,dryRun:r,onSettled:d,table:o,transform:n,writer:f}=e,p=String(a._id);let T=a;for(let h=0;h<G;h+=1){const c=await n(T,t);if(c===void 0){d("unchanged");return}if(r){d("changed");return}const u=await f.get(o,p);if(u===null){d("unchanged");return}if(S(u)===S(T)){await Y({document:{...c,_creationTime:T._creationTime,_id:T._id},id:p,onSettled:d,previous:u,table:o,writer:f});return}T=u}throw new x(`data migration could not rewrite row ${p}: it was modified by concurrent traffic on every attempt`,"occ")},J=async e=>{const{migration:t,sql:a,writer:r}=e,d=e.direction??"up",o=e.dryRun??!1,n=e.clock??(()=>Date.now()),f=e.maxBatches??Number.POSITIVE_INFINITY,p=e.batchSize??t.batchSize??M,T=d==="up"?t.up:t.down;if(!T)throw new D("INTERNAL",`data migration "${t.id}" has no \`${d}\` transform`);const h={db:{count:r.count.bind(r),findFirst:r.findFirst.bind(r),findMany:r.findMany.bind(r),get:r.get.bind(r)}};let c=null,u=0,g=0,A=n();if(!o){$(a);const s=I(a,t.id);if(s?.direction===d&&s.status==="completed")return{changed:s.changed,cursor:null,direction:d,dryRun:o,id:t.id,processed:s.processed,status:"completed"};if(s&&s.direction!==d&&F(a,t.id,n()-y),!v(a,t.id,d,n())){const R=I(a,t.id);return{changed:R?.changed??0,cursor:R?.cursor??c,direction:R?.direction??d,dryRun:o,id:t.id,processed:R?.processed??0,status:R?.status??"in_progress"}}const l=s?.direction===d?s:void 0;l&&(c=B(l.cursor),u=l.processed,g=l.changed,A=l.startedAt??A)}let _=!1,L=0,N=A;try{for(;!_&&L<f;){const s=await r.findMany(t.table,{cursor:c,includeDeleted:!0,limit:p});for(const m of s.page)if(await V({context:h,document:m,dryRun:o,onSettled:l=>{l==="changed"&&(g+=1),u+=1,c=w(m,W)},table:t.table,transform:T,writer:r}),!o){const l=n();l-N>=U&&(H(a,t.id,l),N=l)}if(c=s.continueCursor,_=s.isDone,L+=1,!o){const m=n();O(a,{changed:g,cursor:_?null:c,direction:d,error:null,id:t.id,processed:u,startedAt:A,status:_?"completed":"in_progress",updatedAt:m}),N=m;try{await e.onBatch?.({batches:L,changed:g,processed:u})}catch{}}}}catch(s){throw o||O(a,{changed:g,cursor:c,direction:d,error:s instanceof Error?s.message:String(s),id:t.id,processed:u,startedAt:A,status:"failed",updatedAt:n()}),s}if(!o&&!_)try{P(a,t.id)}catch(s){console.warn(`data migration "${t.id}": releaseClaim failed`,s)}return{changed:g,cursor:_?null:c,direction:d,dryRun:o,id:t.id,processed:u,status:_?"completed":"in_progress"}};export{i as DATA_MIGRATION_STATE_TABLE,j as readMigrationStatus,J as runDataMigration};
@@ -0,0 +1,8 @@
1
+ import{toErrorBody as Y,LunoraError as G}from"@lunora/errors";import{encodeWire as q,stableWireKey as _,decodeWire as g}from"@lunora/wire";import{sql as u}from"drizzle-orm";import{runDrizzle as m}from"./runDrizzle-RC09zZrh.mjs";import{WORKERD_SQLITE_LIMITS as W}from"./WORKERD_SQLITE_LIMITS-B_4w7tzY.mjs";import{d as $,w as I,a as A,m as B,r as K,b as H,c as j}from"./ctx-db-relay-shapes-DV0VO4HG.mjs";import{envPositiveInt as v}from"./envOptionalPositiveInt-D2pY-c64.mjs";import{DEFAULT_PROMOTION_THRESHOLDS as T,nextPromotionState as X,shapeRoutingKey as E,relayProxyKey as w,relayName as M,parseRelayName as z,clampPromotionThresholds as V}from"./DEFAULT_PROMOTION_THRESHOLDS-B3pRMuqb.mjs";import{encodeRowsPatch as J,buildPokeFrames as D}from"./buildPokeFrames-WR-hp0mX.mjs";import{siblingStub as Q}from"./stubByName-DLPoppDc.mjs";import{awaitWsDrain as Z,trySendFrame as L}from"./awaitWsDrain-e88vUNdj.mjs";import{verifySiblingBody as ee,RELAY_SIGNATURE_HEADER as C,siblingSecretOf as te,signSiblingBody as se}from"./RELAY_SIGNATURE_HEADER-DNzVQxbZ.mjs";const S="__lunora_relay_memos",re=i=>{m(i,u`CREATE TABLE IF NOT EXISTS ${u.identifier(S)} (
2
+ connection_id TEXT NOT NULL,
3
+ sub_id TEXT NOT NULL,
4
+ cursor INTEGER NOT NULL,
5
+ epoch TEXT,
6
+ PRIMARY KEY (connection_id, sub_id)
7
+ )`)},oe=i=>{const e=m(i,u`SELECT connection_id, sub_id, cursor, epoch FROM ${u.identifier(S)}`).toArray(),s=new Map;for(const t of e){let r=s.get(t.connection_id);r===void 0&&(r=new Map,s.set(t.connection_id,r)),r.set(t.sub_id,{cursor:Number(t.cursor),epoch:t.epoch??void 0})}return s},ne=4,N=(i,e)=>{const s=Math.floor(W.boundParams/ne);for(let t=0;t<e.length;t+=s){const r=e.slice(t,t+s),o=u.join(r.map(n=>u`(${n.connectionId}, ${n.subId}, ${n.cursor}, ${n.epoch??null})`),u`, `);m(i,u`INSERT INTO ${u.identifier(S)} (connection_id, sub_id, cursor, epoch) VALUES ${o}
8
+ ON CONFLICT(connection_id, sub_id) DO UPDATE SET cursor = excluded.cursor, epoch = excluded.epoch`)}},ae=(i,e,s)=>{m(i,u`DELETE FROM ${u.identifier(S)} WHERE connection_id = ${e} AND sub_id = ${s}`)},ie=(i,e)=>{m(i,u`DELETE FROM ${u.identifier(S)} WHERE connection_id = ${e}`)},le=i=>{m(i,u`DELETE FROM ${u.identifier(S)}`)},ce=2,he=i=>{const e=i?.LUNORA_WS_BEARER;return typeof e=="string"&&e.length>0},de=8,ue=2e3,ye=2e3,O=async i=>{let e;const s=new Promise(t=>{e=setTimeout(()=>{t(void 0)},ye)});return Promise.race([i,s]).finally(()=>{clearTimeout(e)})},b={},pe=i=>{throw new G("INTERNAL",`unhandled relay frame: ${JSON.stringify(i)}`)},fe=(i,e)=>i===void 0||i.epoch!==e.epoch?!1:i.cursor>=e.fromCursor&&i.cursor<e.checkpoint,k=i=>Response.json(i,{headers:{"content-type":"application/json"}}),me=new Set(["relay_attach","relay_detach","relay_room_event","relay_shape_unsubscribe"]),Se=new Set(["relay_attach","relay_shape_subscribe"]),Re=(i,e)=>{let s;try{s=JSON.parse(i)}catch{return}if(typeof s!="object"||s===null)return;const t=s,{relayIndex:r}=t;if(r===void 0?!me.has(t.type):Number.isSafeInteger(r)&&r>=0&&(!Se.has(t.type)||r<e))return t},f=()=>new Response(null,{status:204}),x=(i,e)=>{i.then(async s=>s===e?void 0:s?.body?.cancel()).catch(()=>{})},_e=3e4,F=410,P=()=>new Response("stale relay frame",{status:409}),ve=i=>Math.max(Date.now()*1e3,i+1);class U{constructor(e,s){this.host=e,this.roleId=s}host;roleId;lastSequence=0;async handleControl(e){let s;try{s=await e.text()}catch{return new Response("bad request",{status:400})}if(!await ee(this.host.env(),e.headers.get(C),s))return new Response("forbidden",{status:403});const t=Re(s,this.maxRelays());if(t===void 0)return new Response("bad request",{status:400});if((t.type==="relay_frame"||t.type==="relay_live_frame"||t.type==="relay_shape_poke")&&this.refusesAsIdle())return new Response(void 0,{status:F});switch(t.type){case"relay_attach":return this.onAttach(t.relayIndex,t.seq)?f():P();case"relay_detach":return this.onDetach(t.relayIndex,t.seq)?f():P();case"relay_frame":{const{exceptConnectionId:r}=t,o=r===void 0?void 0:this.host.getWebSockets().find(n=>this.host.readAttachment(n).connectionId===r);return this.host.deliverWhisperLocal(t.topic,t.frame,o),await this.onWhisperFrame(t),f()}case"relay_live_control":return this.onLiveControl(t.control);case"relay_live_frame":return this.host.deliverLiveLocal(t.topic,t.key,t.frame),f();case"relay_room_event":return k(await this.host.relayRoomEvent(t));case"relay_shape_poke":{const r=this.host.getWebSockets().length,o=Date.now(),{delivered:n,matched:a}=this.onShapePoke({...t,args:g(t.args)});return this.host.recordShapePokeFanout(r,n,Date.now()-o),n<a?Response.json({delivered:n,matched:a},{status:503}):f()}case"relay_shape_subscribe":return k(this.onShapeSubscribe({...t,args:g(t.args)}));case"relay_shape_unsubscribe":return this.onShapeUnsubscribe(t),f();default:return pe(t)}}maxRelays(){return v(this.host.env(),"LUNORA_MAX_RELAYS",de)}canAddressSiblings(){return this.siblingStub(this.roleId.ownerKey)!==void 0}isAdmitted(e){return this.host.readAttachment(e).authenticated!==!1}siblingStub(e){return Q(this.host.env(),this.bindingName(),e,this.host.shardJurisdiction())}bindingName(){return this.host.shardBinding()}nextRelaySeq(){return this.lastSequence=ve(this.lastSequence),this.lastSequence}async postRelayMessage(e,s){await this.requestRelayMessage(e,s)}async requestRelayMessage(e,s){const t=this.siblingStub(e);if(t===void 0)return;const r=JSON.stringify(s),o={"content-type":"application/json","x-lunora-shard-binding":this.host.shardBinding()??""},n=te(this.host.env());n!==void 0&&(o[C]=await se(n,r));try{return await t.fetch("https://relay.internal/_lunora/relay",{body:r,headers:o,method:"POST"})}catch{return}}}class Ee extends U{shapeUniformCache=new Map;relaySetCache;liveGrantRelayCache;relayTablesReady=!1;relaySeqMarks=new Map;pendingSubscribeRelays=new Map;registryCache;recordedBinding;promotionState="owned";constructor(e,s){super(e,{ownerKey:s})}async forwardWhisper(e,s,t){if(!this.canAddressSiblings())return;const r=this.ownerRelaySet();r.size!==0&&await Promise.all([...r].map(o=>this.forwardToRelay(o,{exceptConnectionId:t,frame:s,topic:e,type:"relay_frame"})))}forwardLiveControl(e){if(!this.canAddressSiblings())return Promise.resolve(void 0);const s={...e,seq:this.nextRelaySeq()},t=s.action==="unsubscribe"?new Set([...this.liveGrantRelaySet(),...this.pendingSubscribeRelays.keys()]):this.ownerRelaySet();if(t.size===0)return Promise.resolve(void 0);const r=[...t].map(o=>this.liveControlAnswer(o,s));return Promise.any(r.map(async o=>{const n=await o;if(n===void 0||n.status===404)throw new Error("relay does not hold the socket");return n})).catch(()=>{}).then(o=>{for(const n of r)x(n,o);return o})}async forwardLiveFrame(e,s,t){if(!this.canAddressSiblings())return;const r=this.liveGrantRelaySet();r.size!==0&&await Promise.all([...r].map(o=>this.forwardToRelay(o,{frame:t,key:s,topic:e,type:"relay_live_frame"})))}async onFlush(e,s){this.canAddressSiblings()&&await Promise.all([this.multicastShapePokes(e,s),this.proxyShapePokes(e,s)])}seedRelayShape(){return Promise.resolve(void 0)}announce(){return Promise.resolve(!0)}announceDrain(){return Promise.resolve()}releaseRelayShapes(){return Promise.resolve()}relayCount(){const e=this.host.getWebSockets(),s=he(this.host.env())?e.filter(n=>this.isAdmitted(n)).length:e.length,t=v(this.host.env(),"LUNORA_RELAY_THRESHOLD",T.tUp),r=v(this.host.env(),"LUNORA_RELAY_COLLAPSE_THRESHOLD",T.tDown);if(this.promotionState=X(this.promotionState,s,V(t,r)),this.promotionState==="owned")return 0;const o=v(this.host.env(),"LUNORA_RELAY_FAN",ce);return Math.min(this.maxRelays(),Math.max(1,o))}minShapeCursor(){const{cohort:e,proxies:s}=this.relayShapes();let t;for(const r of[...e.values(),...s.values()])t=t===void 0?r.cursor:Math.min(t,r.cursor);return t}isShapeRelayUniform(e,s){const t=E(e,s),r=this.shapeUniformCache.get(t);if(r!==void 0)return r;const o=this.probeShapeRelayUniform(e,s);return this.shapeUniformCache.set(t,o),o}onShapeUnsubscribe(e){const{proxies:s}=this.relayShapes(),t=e.subId===void 0?void 0:w(e.relayIndex,e.connectionId,e.subId);for(const[r,o]of s)o.relayIndex!==e.relayIndex||o.connectionId!==e.connectionId||(t===void 0||r===t)&&s.delete(r);$(this.host.sql(),e.relayIndex,e.connectionId,e.subId)}onAttach(e,s){return this.recordRelaySeq(e,s),this.addRelayToSet(e),!0}onDetach(e,s){return this.acceptRelaySeq(e,s)?(this.removeRelayFromSet(e),!0):!1}refusesAsIdle(){return!1}onLiveControl(e){return this.host.liveControl(e)}async onWhisperFrame(e){await Promise.all([...this.ownerRelaySet()].filter(s=>s!==e.originRelay).map(s=>this.forwardToRelay(s,{frame:e.frame,topic:e.topic,type:"relay_frame"})))}onShapeSubscribe(e){return this.buildShapeSeedFrames(e)}onShapePoke(){return{delivered:0,matched:0}}relaySeqMark(e){if(this.relaySeqMarks.has(e))return this.relaySeqMarks.get(e);this.ensureRelayTables();const[s]=this.host.sql().exec("SELECT seq FROM __lunora_relay_seqs WHERE idx = ?",e).toArray(),t=s===void 0?void 0:Number(s.seq);return this.relaySeqMarks.set(e,t),t}recordRelaySeq(e,s){if(s===void 0)return;const t=this.relaySeqMark(e);(t===void 0||s>t)&&(this.host.sql().exec("INSERT OR REPLACE INTO __lunora_relay_seqs (idx, seq) VALUES (?, ?)",e,s),this.relaySeqMarks.set(e,s))}acceptRelaySeq(e,s){if(s===void 0)return!0;const t=this.relaySeqMark(e);return t!==void 0&&s<t?!1:(this.recordRelaySeq(e,s),!0)}buildShapePoke(e,s,t,r,o){if(e.table!==void 0&&!t.has(e.table))return;let n;try{n=this.host.resolveShape(e.name,e.args,s)}catch{return}if(n===void 0||n.global===!0)return;const a=e;if(a.table=n.table,!t.has(n.table))return;const c=a.cursor,l=this.host.buildShapeDiff(n,c,r);if(l.length!==0)return a.cursor=r,I(this.host.sql(),a.key,r),{args:q(e.args),checkpoint:r,epoch:o,fromCursor:c,name:e.name,rowsPatch:J(l),type:"relay_shape_poke"}}async multicastShapePokes(e,s){const t=this.ownerRelaySet();if(t.size===0)return;const{cohort:r}=this.relayShapes();if(r.size===0)return;const o=this.host.currentCdcEpoch(),n=[];for(const a of r.values()){const c=this.buildShapePoke(a,b,e,s,o);c&&n.push(this.multicastToRelays(t,c,a))}await Promise.all(n)}async multicastToRelays(e,s,t){(await Promise.all([...e].map(async o=>{const{dropped:n,response:a}=await this.requestDroppingIdle(o,s);return n||a?.ok===!0}))).includes(!1)&&this.rewindShapeCursor(t,s.fromCursor)}async proxyShapePokes(e,s){if(this.ownerRelaySet().size===0)return;const{proxies:t}=this.relayShapes();if(t.size===0)return;const r=this.host.currentCdcEpoch(),o=[];for(const n of t.values()){const a=this.buildShapePoke(n,n.identity,e,s,r);a&&o.push(this.proxyToRelay(a,n))}await Promise.all(o)}async proxyToRelay(e,s){const{dropped:t,response:r}=await this.requestDroppingIdle(s.relayIndex,{...e,targetConnectionId:s.connectionId});!t&&r?.ok!==!0&&this.rewindShapeCursor(s,e.fromCursor)}buildShapeSeedFrames(e){const s={identity:e.identity,userId:e.userId};let t;try{t=this.host.resolveShape(e.name,e.args,s)}catch(h){const{body:p}=Y(h,{fallbackCode:"SHAPE_RESOLVE_FAILED",redactedMessage:"shape resolution failed"});return{error:{code:p.code,message:p.message}}}if(t===void 0||t.global===!0)return{error:{code:"SHAPE_NOT_FOUND",message:`shape not relayable: ${e.name}`}};e.relayIndex!==void 0&&this.addRelayToSet(e.relayIndex);const{baseCheckpoint:r,cursor:o,epoch:n,reset:a,rowsPatch:c}=this.host.computeOpLogShapeSeed({args:e.args,name:e.name,sinceEpoch:e.sinceEpoch,sinceSeq:e.sinceSeq},t);let l=o;const{cohort:d,proxies:R}=this.relayShapes();if(this.isShapeRelayUniform(e.name,e.args)){const h=E(e.name,e.args);let p=d.get(h);p===void 0&&(p={args:e.args,cursor:o,key:h,name:e.name,table:t.table},d.set(h,p),A(this.host.sql(),p)),l=p.cursor}else if(e.relayIndex!==void 0&&e.connectionId!==void 0){const h=w(e.relayIndex,e.connectionId,e.subId),p={args:e.args,connectionId:e.connectionId,cursor:o,identity:s,key:h,name:e.name,relayIndex:e.relayIndex,table:t.table};R.set(h,p),A(this.host.sql(),p)}else return{error:{code:"RELAY_SHAPE_UNROUTABLE",message:`shape ${e.name} is per-socket on a relay, but the subscribe carries no ${e.relayIndex===void 0?"relay index":"connection id"}`}};const y=D([{reset:a,rowsPatch:c,shapeId:e.subId}],{baseCheckpoint:r,checkpoint:l,epoch:n,lastMutationId:void 0,pokeId:this.host.nextPokeId()});return{cursor:l,epoch:n,frames:y}}ensureRelayTables(){this.relayTablesReady||(this.relayTablesReady=!0,this.host.sql().exec("CREATE TABLE IF NOT EXISTS __lunora_relays (idx INTEGER PRIMARY KEY)"),this.host.sql().exec("CREATE TABLE IF NOT EXISTS __lunora_relay_grants (idx INTEGER PRIMARY KEY)"),this.host.sql().exec("CREATE TABLE IF NOT EXISTS __lunora_relay_seqs (idx INTEGER PRIMARY KEY, seq INTEGER NOT NULL)"),this.host.sql().exec("CREATE TABLE IF NOT EXISTS __lunora_relay_binding (id INTEGER PRIMARY KEY, binding TEXT NOT NULL)"),B(this.host.sql()))}bindingName(){const e=this.host.shardBinding();if(e!==void 0&&e!=="")return e!==this.recordedBinding&&(this.recordedBinding=e,this.ensureRelayTables(),this.host.sql().exec("INSERT INTO __lunora_relay_binding (id, binding) VALUES (1, ?) ON CONFLICT(id) DO UPDATE SET binding = excluded.binding",e)),e;if(this.recordedBinding!==void 0)return this.recordedBinding;try{const s=this.host.sql().exec("SELECT binding FROM __lunora_relay_binding WHERE id = 1").toArray();this.recordedBinding=s[0]?.binding}catch{this.recordedBinding=void 0}return this.recordedBinding}relayShapes(){const e=this.registryCache;if(e!==void 0)return e;this.ensureRelayTables();const s={cohort:new Map,proxies:new Map};for(const t of K(this.host.sql()))t.relayIndex===void 0||t.connectionId===void 0?s.cohort.set(t.key,{args:t.args,cursor:t.cursor,key:t.key,name:t.name}):s.proxies.set(t.key,{args:t.args,connectionId:t.connectionId,cursor:t.cursor,identity:t.identity??{},key:t.key,name:t.name,relayIndex:t.relayIndex});return this.registryCache=s,s}rewindShapeCursor(e,s){const t=e;t.cursor<=s||(t.cursor=s,I(this.host.sql(),t.key,s))}ownerRelaySet(){if(this.relaySetCache===void 0){this.ensureRelayTables();const e=this.host.sql().exec("SELECT idx FROM __lunora_relays").toArray();this.relaySetCache=new Set(e.map(s=>Number(s.idx)))}return this.relaySetCache}liveGrantRelaySet(){if(this.liveGrantRelayCache===void 0){this.ensureRelayTables();const e=this.host.sql().exec("SELECT idx FROM __lunora_relay_grants").toArray();this.liveGrantRelayCache=new Set(e.map(s=>Number(s.idx)))}return this.liveGrantRelayCache}recordLiveGrantRelay(e){const s=this.liveGrantRelaySet();s.has(e)||(this.host.sql().exec("INSERT OR IGNORE INTO __lunora_relay_grants (idx) VALUES (?)",e),s.add(e))}addRelayToSet(e){this.ensureRelayTables(),this.host.sql().exec("INSERT OR IGNORE INTO __lunora_relays (idx) VALUES (?)",e),this.ownerRelaySet().add(e)}async forwardToRelay(e,s){await this.requestDroppingIdle(e,s)}async requestDroppingIdle(e,s){const t=this.relaySeqMark(e),r=await this.requestRelayMessage(M(this.roleId.ownerKey,e),s);return r?.status!==F||this.relaySeqMark(e)!==t?{dropped:!1,response:r}:(this.removeRelayFromSet(e),{dropped:!0,response:r})}removeRelayFromSet(e){this.ensureRelayTables(),this.host.sql().exec("DELETE FROM __lunora_relays WHERE idx = ?",e);const s=this.ownerRelaySet();s.delete(e),this.host.sql().exec("DELETE FROM __lunora_relay_grants WHERE idx = ?",e),this.liveGrantRelaySet().delete(e);const{cohort:t,proxies:r}=this.relayShapes();for(const[o,n]of r)n.relayIndex===e&&r.delete(o);H(this.host.sql(),e),s.size===0&&(t.clear(),this.shapeUniformCache.clear(),j(this.host.sql()))}probeShapeRelayUniform(e,s){let t;try{t=this.host.resolveShape(e,s,b)}catch{return!1}if(t===void 0||t.global===!0||this.host.rlsMetadata().policies.some(l=>l.on==="read"&&l.table===t.table)||this.tableHasAnyMask(t.table))return!1;const r=_(t.effectiveWhere),o=_(t.columns);let n=!1;const a=l=>{const d={groups:[`grp_${l}`],roles:[l],sub:`__lunora_probe_${l}__`};return{identity:new Proxy(d,{get:(y,h)=>typeof h=="symbol"||h in y?Reflect.get(y,h):`${l}:${h}`,getOwnPropertyDescriptor:(y,h)=>(n=!0,Reflect.getOwnPropertyDescriptor(y,h)),has:(y,h)=>typeof h=="symbol"?Reflect.has(y,h):!0,ownKeys:y=>(n=!0,Reflect.ownKeys(y))}),ip:`__lunora_probe_${l}__`,userId:`__lunora_probe_${l}__`}};return[b,a("a"),a("b")].every(l=>{let d;try{d=this.host.resolveShape(e,s,l)}catch{return!1}return d!==void 0&&d.global!==!0&&d.table===t.table&&_(d.effectiveWhere)===r&&_(d.columns)===o})&&!n}tableHasAnyMask(e){return this.host.maskMetadata().columns.some(s=>s.table===e)}async liveControlAnswer(e,s){const t=s.action==="subscribe";t&&this.pendingSubscribeRelays.set(e,(this.pendingSubscribeRelays.get(e)??0)+1);const r=this.requestRelayMessage(M(this.roleId.ownerKey,e),{control:s,type:"relay_live_control"}).then(a=>(t&&a?.ok===!0&&this.recordLiveGrantRelay(e),a)).finally(()=>{if(!t)return;const a=(this.pendingSubscribeRelays.get(e)??1)-1;a===0?this.pendingSubscribeRelays.delete(e):this.pendingSubscribeRelays.set(e,a)});let o;const n=new Promise(a=>{o=setTimeout(()=>{a(void 0)},ue)});return Promise.race([r,n]).then(a=>(a===void 0&&x(r,void 0),a)).finally(()=>{clearTimeout(o)})}}class be extends U{relayAnnounced=!1;liveControlSeqs=new Map;pendingAnnounce;announceGeneration=0;pendingDetach;relayMemoCache;shapeControl=new Map;constructor(e,s,t){super(e,{ownerKey:s,relayIndex:t})}async forwardWhisper(e,s){this.canAddressSiblings()&&await this.postRelayMessage(this.roleId.ownerKey,{frame:s,originRelay:this.roleId.relayIndex,topic:e,type:"relay_frame"})}async forwardRoomEvent(e){const s=await this.requestRelayMessage(this.roleId.ownerKey,{...e,relayIndex:this.roleId.relayIndex,type:"relay_room_event"});if(!s?.ok)return!1;try{return(await s.json()).admitted}catch{return!1}}onFlush(){return Promise.resolve()}async seedRelayShape(e,s,t,r){if(!this.canAddressSiblings())return{code:"RELAY_MISCONFIGURED",message:"relay cannot address its owner"};const{connectionId:o}=this.host.readAttachment(e),n={args:q(t.args??{}),connectionId:o,identity:r.identity,name:t.name,relayIndex:this.roleId.relayIndex,sinceEpoch:t.sinceEpoch,sinceSeq:t.sinceSeq,subId:s,type:"relay_shape_subscribe",userId:r.userId},a=await this.queueShapeControl(o,async()=>(await this.announce(),this.requestRelayMessage(this.roleId.ownerKey,n)));if(a===void 0)return{code:"RELAY_SEED_FAILED",message:"owner did not answer the shape seed"};let c;try{c=await a.json()}catch{return{code:"RELAY_SEED_FAILED",message:"malformed shape seed from owner"}}if(c.error!==void 0)return c.error;if(c.frames===void 0)return{code:"RELAY_SEED_FAILED",message:"owner returned no shape frames"};await Z(e);for(const l of c.frames)L(e,l);return this.recordRelayShapeMemo(e,s,c.cursor??0,c.epoch),"ok"}announce(){if(this.relayAnnounced||!this.canAddressSiblings())return Promise.resolve(!0);if(this.pendingAnnounce===void 0){const e=this.announceGeneration;this.pendingAnnounce=(this.pendingDetach??Promise.resolve()).then(async()=>O(this.requestRelayMessage(this.roleId.ownerKey,{relayIndex:this.roleId.relayIndex,seq:this.nextRelaySeq(),type:"relay_attach"}))).then(s=>{const t=s?.ok===!0;return e===this.announceGeneration&&(this.relayAnnounced=t),t}).finally(()=>{e===this.announceGeneration&&(this.pendingAnnounce=void 0)})}return this.pendingAnnounce}async announceDrain(e){if(this.host.getWebSockets().some(o=>o!==e&&this.isAdmitted(o))||(this.relayMemos().clear(),le(this.host.sql()),this.liveControlSeqs.clear(),!this.canAddressSiblings()))return;this.relayAnnounced=!1,this.announceGeneration+=1;const s=this.pendingAnnounce;this.pendingAnnounce=void 0;const t=this.pendingDetach,r=Promise.all([s?.catch(()=>!1),t]).then(async()=>O(this.postRelayMessage(this.roleId.ownerKey,{relayIndex:this.roleId.relayIndex,seq:this.nextRelaySeq(),type:"relay_detach"}))).catch(()=>{}).finally(()=>{this.pendingDetach===r&&(this.pendingDetach=void 0)});this.pendingDetach=r,await r}async releaseRelayShapes(e,s){const{connectionId:t}=this.host.readAttachment(e);t!==void 0&&this.forgetRelayShapeMemos(t,s),!(t===void 0||!this.canAddressSiblings())&&await this.queueShapeControl(t,async()=>this.postRelayMessage(this.roleId.ownerKey,{connectionId:t,relayIndex:this.roleId.relayIndex,...s===void 0?{}:{subId:s},type:"relay_shape_unsubscribe"}))}relayCount(){return 0}isShapeRelayUniform(){return!1}minShapeCursor(){}onAttach(){return!0}refusesAsIdle(){return this.host.getWebSockets().some(e=>this.isAdmitted(e))?!1:(this.relayAnnounced=!1,this.announceGeneration+=1,this.pendingAnnounce=void 0,!0)}onDetach(){return!0}async onLiveControl(e){const{connectionId:s,seq:t,subscriptionId:r}=e;if(t===void 0)return this.host.liveControl(e);const o=Date.now();for(const[d,R]of this.liveControlSeqs){if(o-R.appliedAt<=_e)break;this.liveControlSeqs.delete(d)}const n=`${s}\0${r}`,a=this.liveControlSeqs.get(n);if(a!==void 0&&t<a.seq)return Response.json({error:{code:"LIVE_CONTROL_SUPERSEDED",message:"a later live control call already applied"}},{status:409});const c={appliedAt:o,seq:t};this.liveControlSeqs.delete(n),this.liveControlSeqs.set(n,c);const l=await this.host.liveControl(e);return l.status===404&&this.liveControlSeqs.get(n)===c&&this.liveControlSeqs.delete(n),l}onWhisperFrame(){return Promise.resolve()}onShapeSubscribe(){return{error:{code:"RELAY_CANNOT_SEED",message:"a relay has no op-log to seed from"}}}onShapeUnsubscribe(){}onShapePoke(e){return this.deliverShapePoke(e)}async queueShapeControl(e,s){if(e===void 0)return s();const t=(this.shapeControl.get(e)??Promise.resolve()).then(s,s),r={},o=()=>{this.shapeControl.get(e)===r.chain&&this.shapeControl.delete(e)},n=t.then(o,o);return r.chain=n,this.shapeControl.set(e,n),t}relayMemos(){return this.relayMemoCache===void 0&&(re(this.host.sql()),this.relayMemoCache=oe(this.host.sql())),this.relayMemoCache}connectionMemos(e){const s=this.relayMemos();let t=s.get(e);return t===void 0&&(t=new Map,s.set(e,t)),t}recordRelayShapeMemo(e,s,t,r){const{connectionId:o}=this.host.readAttachment(e);o!==void 0&&(this.connectionMemos(o).set(s,{cursor:t,epoch:r}),N(this.host.sql(),[{connectionId:o,cursor:t,epoch:r,subId:s}]))}forgetRelayShapeMemos(e,s){if(s===void 0){this.relayMemos().delete(e),ie(this.host.sql(),e);return}this.relayMemos().get(e)?.delete(s),ae(this.host.sql(),e,s)}deliverShapePoke(e){const s=E(e.name,e.args),t=[];let r=0,o=0;for(const n of this.host.getWebSockets()){const{connectionId:a,shapes:c}=this.host.readAttachment(n);if(c===void 0||a===void 0||e.targetConnectionId!==void 0&&a!==e.targetConnectionId)continue;const l=this.pokeSocketShapes(n,c,this.connectionMemos(a),e,s);o+=l.matched.length,r+=l.sent;for(const d of l.matched)t.push({connectionId:a,cursor:e.checkpoint,epoch:e.epoch,subId:d})}return N(this.host.sql(),t),{delivered:r,matched:o}}pokeSocketShapes(e,s,t,r,o){const n=[];let a=0;for(const[c,l]of Object.entries(s)){const d=t.get(c);if(E(l.name,l.args)!==o||!fe(d,r))continue;const y=D([{baseCheckpoint:d?.cursor,rowsPatch:r.rowsPatch,shapeId:c}],{baseCheckpoint:void 0,checkpoint:r.checkpoint,epoch:r.epoch,lastMutationId:void 0,pokeId:this.host.nextPokeId()},{preEncoded:!0}).map(h=>L(e,h)).every(Boolean);t.set(c,{cursor:r.checkpoint,epoch:r.epoch}),n.push(c),y&&(a+=1)}return{matched:n,sent:a}}}const Pe=i=>{const e=i.doName();if(e===void 0)return;const s=z(e);return s===void 0?new Ee(i,e):new be(i,s.ownerKey,s.relayIndex)};export{de as DEFAULT_MAX_RELAYS,Ee as OwnerRelay,be as RelayMember,Pe as createRelayLink};
@@ -0,0 +1 @@
1
+ import{LunoraError as y}from"@lunora/errors";import{D as gt}from"./MAX_TOKEN_LENGTH-BakL9FUy-B3VwYY8C.mjs";import{S as Mn,l as qe,h as Dn}from"./fts-companion-CA8mLJWq.mjs";import{decodeWire as kn,stableWireKey as Lt}from"@lunora/wire";import{sql as a}from"drizzle-orm";import{throwingScheduler as Ln,aggregateSqlFunction as We,normalizeCountArgument as Fn}from"./AGGREGATE_SQL_FUNCTION-C_ZipS9R.mjs";import{aggregateTableName as ot,encodeAggregateKey as rt,readAggregateValue as it}from"./aggregateTableName-B_CtIQCS.mjs";import{mergeWhere as N,CountRlsUnsupportedError as st,selectIndexForGroupBy as qn,selectIndexForCount as Wn,selectIndexForAggregate as Bn}from"./CountRlsUnsupportedError-BvsDqfO2.mjs";import{backfillSearchIndexesForTable as Pn,searchIndexCoversTable as Un}from"./backfillAggregateIndexes-BN0NwXQk.mjs";import{backfillAggregateIndexes as pi,backfillRankIndexes as gi,backfillSearchIndexes as yi}from"./backfillAggregateIndexes-BN0NwXQk.mjs";import{appendCdcChange as On,readCdcDocAtOrBefore as Hn}from"./CDC_LOG_TABLE-oPp25hdi.mjs";import{CDC_LOG_TABLE as Ei,applyCdcChanges as mi,bumpCdcEpoch as Si,cdcCanVouchFor as Ti,cdcForkedError as Ri,cdcSeqLeavingRows as vi,cdcTouchesTables as _i,cdcTrimmedError as Ii,compactCdcDocs as Ai,cursorBelowRetainedFloor as xi,minCdcReplayableSeq as Ci,minCdcSeq as bi,readCdcChangeKeys as Mi,readCdcChanges as Di,readCdcCursor as ki,readCdcEpoch as Li,trimCdcChanges as Fi}from"./CDC_LOG_TABLE-oPp25hdi.mjs";import{allocateCommitSeq as Gn,COMMIT_SEQ_FIELD as jn}from"./COMMIT_SEQ_FIELD-Da1DjGqo.mjs";import{createCompanionSync as Kn}from"./createCompanionSync-zIF_F4oD.mjs";import{isMemoryTable as Ft}from"./clearMemoryTables-aMRERF0w.mjs";import{computeRankPage as qt}from"./computeRankPage-BZIpATcs.mjs";import{SCAN_DEP as H}from"./SCAN_DEP-D7qE3iUe.mjs";import{runSql as he,runDrizzle as j}from"./runDrizzle-RC09zZrh.mjs";import{p as Nn,j as ut,D as re,r as _e,k as le,b as Be,A as ct,a as Pe,m as ue,e as fe,s as Qn,t as Vn,i as Jn,q as Wt,h as ln,g as zn}from"./do-sql-BWrJQAOh.mjs";import{renderSql as un,unionAll as fn,WORKERD_SQLITE_LIMITS as hn}from"./WORKERD_SQLITE_LIMITS-B_4w7tzY.mjs";import{coveringGeohashes as Yn,boundingBoxGeohashes as Xn,haversineMeters as Zn,pointInBoundingBox as eo}from"./GEO_DEFAULT_PRECISION-CqpQZ-J_.mjs";import{NotFoundError as to}from"./NotFoundError-BhF7FeFr.mjs";import{resolvePatch as no,assertPatchAllowed as oo,operatorFields as ro,readPatchField as Bt}from"./assertPatchAllowed-CA_H466g.mjs";import{tiebreakDirectionFor as io,encodeCursor as Ke,nullsOrderSuffix as so,normalizeOrderKeys as Pt,uniqueIndexFields as co,buildSeekWhere as ao,decodeCursor as Ut,buildSeekBeforeWhere as lo,softDeleteScope as ve,applySelect as Ot}from"./CURSOR_PREFIX-6offuG6M.mjs";import{rankTableName as Ht,sortColumnName as Gt,resolveRankPartition as uo,encodePartitionKey as fo,RANK_TIEBREAK as ho,rankPivotConditionSql as wo}from"./RANK_TIEBREAK-D3ye2GsL.mjs";import{UNVOUCHABLE_DEP as jt}from"./UNVOUCHABLE_DEP-C68htACn.mjs";import{indexKeysForRow as po,buildIndexRange as go}from"./buildIndexRange-DQ3eWAGd.mjs";import{r as Ne,j as Ie,c as Z,t as Ve,i as Kt}from"./where-sql-BjY4rnqb.mjs";import{serializeSqlValue as Ae}from"./serializeSqlValue-DeoBMpZ2.mjs";import{quoteIdentifier as xe}from"./quoteIdentifier-CObIFRhb.mjs";import{whereOfFilter as yo,isPushableWhere as $o}from"./isPushableWhere-BeYAOjUb.mjs";import{deriveRelationEdges as Eo,findRelated as mo}from"./RELATED_DEFAULT_LIMIT-CVqN4JEu.mjs";import{assertFlatPredicate as at,resolveRelationPredicates as So,composeReadPredicate as To}from"./DEFAULT_MAX_RELATION_KEYS-9eOkadE4.mjs";import{describeRelationWrites as Ro}from"./describeRelationWrites-omar6-u9.mjs";import{runRowValidators as Ue,transformOnlyDefinition as vo,applyInsertDefaults as ft,resolveWith as Nt,relationHooks as Qt,applyOnDelete as _o,fanOutScalarCounts as Io}from"./applyInsertDefaults-B0NXPs2x.mjs";import{guardWriter as Ao}from"./RLS_UNWRAP_SYMBOL-H6J96vgK.mjs";import{mayHoldProjectedValue as xo}from"./BIGINT_KEY_DIGITS-DE6yshOt.mjs";import{createSystemReader as Co}from"./createSystemReader-DcDLFfC-.mjs";import{ConflictError as se}from"./ConflictError-C8GtJmjS.mjs";import{hasTrigger as Vt,runTriggers as bo}from"./hasTrigger-CjlwI4le.mjs";import{advanceClientWatermark as Wi,migrateClientWatermark as Bi,readClientWatermark as Pi}from"./CLIENT_WATERMARK_TABLE-De7z_OHV.mjs";import{IDEMPOTENCY_TABLE as Oi,readIdempotent as Hi,trimIdempotent as Gi,writeIdempotent as ji}from"./IDEMPOTENCY_TABLE-COrgeP3O.mjs";import{runShardMigrations as Ni}from"./runShardMigrations-BXGBfJU1.mjs";import{selectShapeMembers as Vi,selectShapeRows as Ji}from"./selectShapeMembers-BCfKypfN.mjs";const Mo=n=>{const i=atob(n),o=Uint8Array.from(i,c=>c.codePointAt(0)??0);return new TextDecoder().decode(o)},Do=()=>new y("BAD_REQUEST","invalid cursor"),Jt=16,zt=8,J=1024,yt=(n,i)=>i.query(n),ko=(n,i)=>{if(n.length===0)return 0;let o=0;for(const[c,s]of i.entries()){const w=c===i.length-1;let E=0;for(const S of n)(w?S.startsWith(s):S===s)&&(E+=1);if(E===0)return 0;o+=E}return o},Lo=(n,i)=>{if(!i)return{exact:!0,lower:n,upper:n};const o=[...n].at(-1)??"",c=(o.codePointAt(0)??0)+1;if(c>=55296&&c<=57343||c>1114111)return{exact:!0,lower:n,upper:n};const s=n.slice(0,n.length-o.length);return{exact:!1,lower:n,upper:s+String.fromCodePoint(c)}},Fo=(n,i,o)=>{const c={eq:(s,w)=>{if(!n.definition.filterFields?.includes(s))throw new y("INTERNAL",`field "${s}" is not a filter field of search index "${n.indexName}" on table "${i}"`);if(n.filters.length>=zt)throw new y("BAD_REQUEST",`search index "${n.indexName}" on table "${i}": at most ${String(zt)} .eq() filters are supported per search query`);return n.filters.push({field:s,value:w}),c},search:(s,w)=>{const E=n;if(s!==E.definition.field)throw new y("INTERNAL",`search index "${E.indexName}" on table "${i}" indexes "${E.definition.field}", not "${s}"`);const S=yt(w,o).length;if(S>Jt)throw new y("BAD_REQUEST",`search index "${E.indexName}" on table "${i}": at most ${String(Jt)} search terms are supported (got ${String(S)})`);return E.field=s,E.query=w,E.hasQuery=!0,c}};return c},qo=n=>{if(n.length>J)throw new y("BAD_REQUEST",`more than ${String(J)} documents match this search — narrow it with filters or read it a page at a time with .paginate()`)},Wo=n=>Math.min(n.offset+n.numItems+1,J),Bo=n=>btoa(`search:${String(n)}`),Po=n=>{let i;try{i=Mo(n)}catch{return}if(!i.startsWith("search:"))return;const o=Number(i.slice(7));return Number.isInteger(o)&&o>=0?o:void 0},Uo=n=>{if(typeof n.endCursor=="string")throw new y("BAD_REQUEST","bounded (endCursor) pagination is not supported on search queries — relevance order has no stable range boundary");if(!Number.isFinite(n.numItems))throw new y("BAD_REQUEST",`search pagination needs a finite numItems, got ${String(n.numItems)}`);const i=Math.max(0,Math.floor(n.numItems)),o=n.cursor?Po(n.cursor):0;if(o===void 0)throw Do();if(o+i>=J)throw new y("BAD_REQUEST",`search pagination reaches the ${String(J)}-document limit (offset ${String(o)} + ${String(i)} requested) — a page must end below the cap so the probe row that answers \`hasMore\` still fits: retry with numItems ${String(Math.max(1,J-o-1))} or fewer, or narrow the query or the filters instead`);return{numItems:i,offset:o}},Oo=(n,i)=>{const o=i.offset+i.numItems,c=i.numItems>0&&n.length>o;return{continueCursor:c?Bo(o):null,isDone:!c,page:n.slice(i.offset,o)}},Ho=n=>{if(n===void 0)return J+1;if(!Number.isFinite(n))return J;const i=Math.max(0,Math.floor(n));if(i>J)throw new y("BAD_REQUEST",`search returns at most ${String(J)} documents (asked for ${String(i)}) — narrow the query or paginate instead`);return i},wn=500,pn=(n,i,o)=>{if(n!==void 0&&n!==Number.POSITIVE_INFINITY&&(!Number.isInteger(n)||n<0))throw o(`${i}: batch limit must be a non-negative integer`);return n??wn},gn=(n,i,o,c)=>{if(n>i)throw c(`${o}: batch of ${String(n)} exceeds the limit of ${String(i)} (raise options.limit or chunk the call)`)},Go=32,jo=1024,yn=(n,i,o,c)=>{const s=`SELECT id, _creationTime, ${xe(re)} FROM ${xe(n)}`,w=`ORDER BY ${o}${c===void 0?"":` LIMIT ${String(c)}`}`;return i===void 0?Ne(`${s} ${w}`):Ie(`${s} WHERE `,i,` ${w}`)},Je={fieldRef:n=>Ne(ut(n)),rangeTypeGuard:(n,i)=>Ne(Nn(n,i)),serialize:Ae},Ko=n=>n===void 0?"":so(n==="first"),$n=n=>{const i=n.map(o=>`${ut(o.field)} ${o.direction==="desc"?"DESC":"ASC"}${Ko(o.nulls)}`);return n.some(o=>o.field==="_id"||o.field==="id")||i.push(`${ut("id")} ${io(n)==="desc"?"DESC":"ASC"}`),i.join(", ")},No={"<":"lt","<=":"lte","=":"eq",">":"gt",">=":"gte"},En=n=>new Set(n.sqlConditions.filter(i=>i.comparator==="=").map(i=>i.field)),Qo=n=>{const i=En(n);let o=0;for(;o<n.indexFields.length&&i.has(n.indexFields[o]??"");)o+=1;return n.indexFields.slice(o)},Vo=(n,i)=>{const o=n.order,c=Qo(n),{shape:s}=i;return c.length>0?Pt(c.map(w=>({[w]:o})),s,{pinned:En(n),uniqueBy:co(i.indexes,s)}):Pt([{_creationTime:o}],s)},Jo=(n,i,o,c)=>{const s=n.sqlConditions.map(w=>({[w.field]:{[No[w.comparator]??"eq"]:w.value}}));if(o&&s.push(ao(i,Ut(o))),c&&s.push(lo(i,Ut(c))),s.length!==0)return s.length===1?s[0]:{AND:s}},zo=n=>{if(n.want!==void 0)return n.selective?Math.max(n.want,Go):n.want},ht=(n,i,o,c,s,w,E)=>{const S=Vo(c,o),I=$n(S),$=[],{filters:F,want:C}=w;let A=w.cursor??void 0,D=zo(w);if(C===0)return{documents:$,orderKeys:S};for(;;){const P=Z(Jo(c,S,A,w.endCursor),Je,Ve),q=yn(i,s&&P?Ie(P," AND ",s):s??P,I,D),k=he(n,q.text,...q.params).toArray();let W={};E(k.length);for(const O of k)if(W=_e(O),F.every(pe=>pe(W))&&$.push(W)===C)return{documents:$,orderKeys:S};if(D===void 0||k.length<D)return{documents:$,orderKeys:S};A=Ke(W,S),D=Math.max(D,Math.min(D*2,jo))}},Yo=(n,i,o,c,s,w,E,S)=>{const I=Math.max(0,Math.floor(s.numItems));if(typeof s.endCursor=="string"){const{documents:P,orderKeys:q}=ht(n,i,o,c,w,{cursor:s.cursor,endCursor:s.endCursor,filters:E.all,selective:E.selective,want:void 0},S),k=P.length>=2?P[Math.floor(P.length/2)-1]:void 0;return{continueCursor:s.endCursor,isDone:!0,page:P,splitCursor:k?Ke(k,q):null}}const{documents:$,orderKeys:F}=ht(n,i,o,c,w,{cursor:s.cursor,filters:E.all,selective:E.selective,want:I+1},S),C=$.length>I,A=C?$.slice(0,I):$,D=A.at(-1);return{continueCursor:C&&D?Ke(D,F):null,isDone:!C,page:A}},ze=n=>{const i=new Map;return o=>{const c=i.get(o);if(c!==void 0)return c;const s=n(xe(o));return i.set(o,s),s}},we=xe(re),Xo=ze(n=>`INSERT INTO ${n} (id, _creationTime, ${we}) VALUES (?, ?, ?)`),Yt=ze(n=>`UPDATE ${n} SET ${we} = ? WHERE id = ? AND ${we} = ?`),Zo=ze(n=>`UPDATE ${n} SET _creationTime = ?, ${we} = ? WHERE id = ? AND ${we} = ?`),er=ze(n=>`DELETE FROM ${n} WHERE id = ? AND ${we} = ?`),tr="SELECT changes() AS changed",Xt=new Map,nr="",or=n=>{const i=JSON.stringify(n),o=Xt.get(i);if(o!==void 0)return o;const c=n.map(w=>a`SELECT ${a.raw(`'${w.replaceAll("'","''")}'`)} AS __t__, id, _creationTime, ${a.identifier(re)} FROM ${a.identifier(w)} WHERE id = ${nr}`),{sql:s}=un("sqlite",a`${fn(c)} LIMIT 1`);return Xt.set(i,s),s},rr=(n,i)=>i.map(()=>n),ir=/^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/iu,sr=n=>{if(!ir.test(n))throw new y("INTERNAL",`invalid clientId ${JSON.stringify(n)}: a client-supplied row id must be a UUID`)},wt=n=>{if(n.includes("\0"))throw new y("BAD_REQUEST",`invalid row id ${JSON.stringify(n)}: a row id cannot hold a NUL character (U+0000)`)},cr=(n,i,o,c)=>{if(o!==!0)return;const s=n!==void 0&&"serverDefault"in(n.shape._id?._meta?.column??{});for(const w of i){const E=s?ft(n,w,c)._id:w._id;typeof E=="string"&&wt(E)}},Zt=50,Oe=Math.floor(hn.boundParams/3),en=hn.boundParams,ar=128,Qe=n=>new y("BATCH_LIMIT_EXCEEDED",n,{status:400}),He=(n,i,o)=>{gn(n,pn(i,o,Qe),o,Qe)},tn=async(n,i,o,c,s)=>{const w=pn(c,s,Qe),{page:E}=await n.findMany(i,Number.isFinite(w)?{limit:w+1,omitContinueCursor:!0,where:o}:{where:o});return E.length>w&&gn(Math.max(await n.count(i,{where:o}),E.length),w,s,Qe),E},dr=n=>{const i={eq:(o,c)=>(n.sqlConditions.push({comparator:"=",field:o,value:c}),i),gt:(o,c)=>(n.sqlConditions.push({comparator:">",field:o,value:c}),i),gte:(o,c)=>(n.sqlConditions.push({comparator:">=",field:o,value:c}),i),lt:(o,c)=>(n.sqlConditions.push({comparator:"<",field:o,value:c}),i),lte:(o,c)=>(n.sqlConditions.push({comparator:"<=",field:o,value:c}),i)};return i},lr=n=>Math.max(n,J),mn=(n,i)=>{const o=n.filters.map(c=>a`${fe(c.field)} = ${Ae(c.value)}`);return i&&o.push(i),o},ur=(n,i,o,c,s)=>{const w=yt(o.query,gt(o.definition.language));if(w.length===0)return[];const E=Mn(i,o.indexName),S=`${E}__vocab`,I=w.length-1,$=w.map((q,k)=>{const W=Lo(q,k===I),O=W.exact?a`${a.identifier("term")} = ${W.lower}`:a`${a.identifier("term")} >= ${W.lower} AND ${a.identifier("term")} < ${W.upper}`;return a`SELECT ${a.identifier("doc")}, ${a.raw(String(k))} AS ${a.identifier("__term__")}, COUNT(*) AS ${a.identifier("__n__")} FROM ${a.identifier(S)} WHERE ${O} GROUP BY ${a.identifier("doc")}`}),F=w.map((q,k)=>a`SUM(CASE WHEN u.${a.identifier("__term__")} = ${a.raw(String(k))} THEN u.${a.identifier("__n__")} ELSE 0 END)`),C=a`SELECT f.${a.identifier(qe)} AS ${a.identifier(qe)}, ${a.join(F,a` + `)} AS ${a.identifier("__score__")} FROM (${fn($)}) u JOIN ${a.identifier(E)} f ON f.rowid = u.${a.identifier("doc")} GROUP BY f.${a.identifier(qe)} HAVING ${a.join(F.map(q=>a`${q} > 0`),a` AND `)}`,A=mn(o,s);let D=a`SELECT m.id, m._creationTime, m.${a.identifier(re)}, s.${a.identifier("__score__")} AS ${a.identifier("__score__")} FROM (${C}) s JOIN ${a.identifier(i)} m ON m.id = s.${a.identifier(qe)}`;A.length>0&&(D=a`${D} WHERE ${a.join(A,a` AND `)}`),D=a`${D} ORDER BY s.${a.identifier("__score__")} DESC, m._creationTime DESC, m.id ASC LIMIT ${a.raw(String(c))}`;const P=[];for(const q of j(n,D)){const k=ln(q);if(k){const W=q.__score__;P.push({document:k,score:typeof W=="number"?W:Number(W??0)})}}return P},fr=(n,i,o,c,s)=>{const w=gt(o.definition.language),E=yt(o.query,w);if(E.length===0)return[];const S=mn(o,s);let I=a`SELECT id, _creationTime, ${a.identifier(re)} FROM ${a.identifier(i)}`;S.length>0&&(I=a`${I} WHERE ${a.join(S,a` AND `)}`),I=a`${I} ORDER BY _creationTime DESC, id ASC LIMIT ${a.raw(String(lr(c)))}`;const $=j(n,I).toArray(),F=[];for(const C of $){const A=ln(C);if(!A)continue;const D=ko(Dn(A,o.definition),E);D>0&&F.push({creationTime:typeof A._creationTime=="number"?A._creationTime:0,doc:A,id:typeof A._id=="string"?A._id:"",score:D})}return F.sort((C,A)=>A.score-C.score||A.creationTime-C.creationTime||C.id.localeCompare(A.id)),F.slice(0,c).map(C=>({document:C.doc,score:C.score}))},dt=(n,i,o,c)=>{if(!Number.isFinite(n.lat)||n.lat<-90||n.lat>90||!Number.isFinite(n.lng)||n.lng<-180||n.lng>180)throw new y("BAD_REQUEST",`geo index "${c}" on table "${o}": ${i} must have a finite lat in [-90, 90] and lng in [-180, 180]`)},hr=(n,i)=>{const o=n,c={near:(s,w)=>{if(o.within)throw new y("INTERNAL",`geo index "${o.indexName}" on table "${i}": call .near() or .within(), not both`);if(dt(s,".near() point",i,o.indexName),!Number.isFinite(w)||w<=0)throw new y("BAD_REQUEST",`geo index "${o.indexName}" on table "${i}": .near() radiusMeters must be a finite number > 0, got ${String(w)}`);return o.near={point:{lat:s.lat,lng:s.lng},radiusMeters:w},c},within:s=>{if(o.near)throw new y("INTERNAL",`geo index "${o.indexName}" on table "${i}": call .near() or .within(), not both`);if(dt(s.sw,".within() sw corner",i,o.indexName),dt(s.ne,".within() ne corner",i,o.indexName),s.sw.lat>s.ne.lat)throw new y("BAD_REQUEST",`geo index "${o.indexName}" on table "${i}": .within() corners are transposed (sw.lat > ne.lat)`);if(s.sw.lng>s.ne.lng)throw new y("BAD_REQUEST",`geo index "${o.indexName}" on table "${i}": .within() box crosses the antimeridian (sw.lng > ne.lng), which is not supported — split it into two boxes at ±180 and union the results`);return o.within={ne:{lat:s.ne.lat,lng:s.ne.lng},sw:{lat:s.sw.lat,lng:s.sw.lng}},c}};return c},wr=(n,i)=>{const o=n[i];if(o===null||typeof o!="object")return;const{lat:c,lng:s}=o;return typeof c=="number"&&typeof s=="number"?{lat:c,lng:s}:void 0},pr=(n,i)=>{const o=wr(n,i.definition.field);if(!o)return;const c=typeof n._creationTime=="number"?n._creationTime:0;if(i.near){const s=Zn(i.near.point,o);return s<=i.near.radiusMeters?{creationTime:c,distance:s}:void 0}return eo(o,i.within)?{creationTime:c,distance:0}:void 0},gr=(n,i,o,c)=>{if(!o.near&&!o.within)throw new y("INTERNAL",`geo index "${o.indexName}" on table "${i}": call .near(point, radius) or .within(box)`);const s=o.near?Yn(o.near.point,o.near.radiusMeters):Xn(o.within),w=zn(i,o.indexName),E=s.map(C=>a`(g.${a.identifier("__geohash__")} >= ${C} AND g.${a.identifier("__geohash__")} < ${`${C}{`})`),S=[a`(${a.join(E,a` OR `)})`];c&&S.push(c);const I=a`SELECT m.id, m._creationTime, m.${a.identifier(re)} FROM ${a.identifier(w)} g JOIN ${a.identifier(i)} m ON m.id = g.${a.identifier("__id__")} WHERE ${a.join(S,a` AND `)}`,$=j(n,I).toArray(),F=[];for(const C of $){const A=_e(C),D=A?pr(A,o):void 0;A&&D&&F.push({creationTime:D.creationTime,distance:D.distance,doc:A})}return F.sort((C,A)=>C.distance-A.distance||A.creationTime-C.creationTime),F},Sn=(n,i,o,c)=>{const s=[];for(const w of n)if(i.every(E=>E(c(w)))&&(s.push(w),typeof o=="number"&&s.length>=o))break;return s},yr=(n,i,o,c,s,w=()=>{})=>{const E=o.within!==void 0,S=gr(n,i,o,s).map(I=>({distanceMeters:E?null:I.distance,document:I.doc}));return w(S.length),typeof c=="number"?S.slice(0,Math.max(0,Math.floor(c))):S},nn=(n,i,o,c,s,w,E=()=>{})=>{const{geo:S}=o;if(!S)throw new y("INTERNAL","runGeoTerminalScored called without a staged geo query");const I=s.length>0,$=yr(n,i,S,I?void 0:w,c,E);return I?Sn($,s,w,F=>F.document):$},on=(n,i,o)=>{const c=n.shape[i];if(c!==void 0&&xo(c))throw new y("BAD_REQUEST",`${o}: "${i}" may hold an order-preserving key rather than a value SQL can reduce or group — declare an aggregateIndex covering this (by, field, op) so the maintained companion answers it instead (its running total is a REAL, so it stays exact only while the total is inside 2^53)`)},$r=n=>{let i=0;const o=[],c={...Je,relationExists:s=>{const{childWhere:w,negated:E,parentTable:S,relation:I}=s,$=`__rel_${String(i)}`,F=o.at(-1)??S;i+=1,n(I.table,H);const C=I.kind==="one"?I.field:I.references,A=I.kind==="one"?I.references:I.field,D=Ne(`${Wt($,A)} = ${Wt(F,C)}`);o.push($);const P=Z(w,c,Ve);o.pop();const q=P===void 0?D:Ie(D," AND ",P),k=Ie("EXISTS (SELECT 1 FROM ",Kt(I.table)," AS ",Kt($)," WHERE ",q,")");return E?Ie("NOT ",k):k}};return c};class Er extends y{constructor(i="unique() found more than one matching document"){super("NOT_UNIQUE",i,{name:"NotUniqueError"})}}const mr=/\s/u,Sr=String.fromCodePoint(0),rn=(n,i,o)=>{if(!n.tables[i])throw new y("INTERNAL",`unknown table: ${i}`);return typeof o!="string"||o.length===0||mr.test(o)||o.includes(Sr)?null:o},Tn=(n,i,o,c=()=>{},s=()=>{},w=()=>{},E)=>{const S=i.tables[o];if(!S)throw new y("INTERNAL",`unknown table: ${o}`);const I=ve(S.softDeleteMode,void 0),$=E??{indexFields:[],indexName:void 0,inMemoryFilters:[],order:"asc",sqlConditions:[],verifyFilters:[]},F=()=>{const m=N(I,$.pushedWhere);return m?Z(m,ue):void 0},C=()=>{const m=N(I,$.pushedWhere);return m?Z(m,Je,Ve):void 0},A=()=>[...$.inMemoryFilters,...$.verifyFilters];let D=0;const P=m=>{const{search:M}=$;if(!M)throw new y("INTERNAL","runSearchFetch called without a staged search");Pn(n,o,S);const L=$.inMemoryFilters.length>0,R=Ho(L?void 0:m),V=Jn(n);if(V&&!Un(n,o,M.definition))throw new y("SEARCH_INDEX_BUILDING",`search index "${M.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 ge=F(),K=V?ur(n,o,M,R,ge):fr(n,o,M,R,ge);!L&&m===void 0&&qo(K);const oe=A();return D=K.length,oe.length>0?Sn(K,oe,m,ie=>ie.document):K},q=m=>P(m).map(M=>M.document),k=m=>{const M=Uo(m);return Oo(q(Wo(M)),M)},W=()=>{if($.search||$.geo||$.indexName===void 0){s(void 0);return}s(go(o,$.indexName,$.indexFields,$.sqlConditions,Ae))},O=m=>{W();let M=0;const L=(()=>{if($.search){const R=q(m);return M=D,R}return $.geo?nn(n,o,$,F(),A(),m,R=>{M=R}).map(R=>R.document):ht(n,o,S,$,C(),{filters:A(),selective:$.inMemoryFilters.length>0,want:m===void 0?void 0:Math.max(0,Math.floor(m))},R=>{M+=R}).documents})();return w(Math.max(M,L.length)),L},pe=()=>{if(!$.search&&!$.geo)throw new y("INTERNAL",`ctx.db.query("${o}").collectWithScores() requires a staged .withSearchIndex(...) or .withGeoIndex(...)`);W();let m=0;const M=(()=>{if($.search){const L=P(void 0);return m=D,L}return nn(n,o,$,F(),A(),void 0,L=>{m=L})})();return w(Math.max(m,M.length)),M},z={async*[Symbol.asyncIterator](){const m=Tn(n,i,o,c,s,w,{...$,indexFields:[...$.indexFields],inMemoryFilters:[...$.inMemoryFilters],sqlConditions:[...$.sqlConditions],verifyFilters:[...$.verifyFilters]});if($.search){yield*await m.collect();return}let M;for(;;){const L=await m.paginate({cursor:M??null,numItems:ar});if(yield*L.page,L.isDone||L.continueCursor===null)return;M=L.continueCursor}},async collect(){return O(void 0)},async collectWithScores(){return pe()},filter(m){const M=yo(m);return M!==void 0&&$o(M,S.shape)?($.pushedWhere=N($.pushedWhere,M),$.verifyFilters.push(m)):$.inMemoryFilters.push(m),z},async first(){return O(1)[0]??null},order(m){return $.order=m==="desc"?"desc":"asc",z},async paginate(m){let M=0;if(W(),$.search){const R=k(m);return w(R.page.length),R}if($.geo)throw new y("INTERNAL","pagination is not supported on geo queries; use .take(n) or .collect()");const L=Yo(n,o,S,$,m,C(),{all:A(),selective:$.inMemoryFilters.length>0},R=>{M+=R});return w(Math.max(M,L.page.length)),L},async take(m){return O(m)},async unique(){const m=O(2);if(m.length>1)throw new Er(`unique() on table "${o}" matched ${String(m.length)} documents; expected at most one`);return m[0]??null},withGeoIndex(m,M){const L=(S.geoIndexes??[]).find(V=>V.name===m);if(!L)throw new y("INTERNAL",`unknown geo index "${m}" on table "${o}"`);c(o,m,"geo");const R={definition:L,indexName:m};if($.geo=R,M(hr(R,o)),!R.near&&!R.within)throw new y("INTERNAL",`geo index "${m}" on table "${o}" requires a .near(point, radius) or .within(box) call`);return z},withIndex(m,M){const L=S.indexes.find(R=>R.name===m);if(!L)throw new y("INTERNAL",`unknown index "${m}" on table "${o}"`);return c(o,m,"index"),$.indexName=m,$.indexFields=L.fields,M&&M(dr($)),z},withSearchIndex(m,M){const L=(S.searchIndexes??[]).find(V=>V.name===m);if(!L)throw new y("INTERNAL",`unknown search index "${m}" on table "${o}"`);c(o,m,"search");const R={definition:L,field:L.field,filters:[],hasQuery:!1,indexName:m,query:""};if($.search=R,M(Fo(R,o,gt(L.language))),!R.hasQuery)throw new y("INTERNAL",`search index "${m}" on table "${o}" requires a .search(field, query) call`);return z}};return z},lt=(n,i,o,c)=>{const s=o;for(const[w,E]of Vn(n)){if(E.serverDefault){w in i&&(s[w]=E.serverDefault({auth:c}));continue}E.onUpdateFn&&!(w in i)&&(s[w]=E.onUpdateFn())}},sn=5,cn=(n,i)=>{for(const o of Object.keys(i))if(i[o]===void 0)throw new y("INTERNAL",`Cannot ${n} field '${o}' to undefined — use null to clear a nullable field, or omit the key to leave it unchanged.`)},an=["_commitSeq","_creationTime","_id"],Ge=n=>an.some(i=>i in n)?Object.fromEntries(Object.entries(n).filter(([i])=>!an.includes(i))):n,Tr=/unique constraint failed/i,Rr=n=>n instanceof Error&&Tr.test(n.message),vr=/string or blob too big/iu,_r=(n,i)=>{if(!(!(n instanceof Error)||!vr.test(n.message)))throw new y("PAYLOAD_TOO_LARGE",`document is too large to store in "${i}": a single row cannot exceed the storage engine's per-row ceiling (2 MB on a Durable Object's SQLite). The limit is on the STORED bytes, which are UTF-8, and v.bytes()/v.bigint() columns are stored twice on a shard-local table. Keep the payload in R2 (ctx.storage) and store a reference on the row.`)},pt=(n,i,o,c)=>{try{he(n,o,...c)}catch(s){throw Rr(s)?new se(`unique constraint violation on "${i}"`,"unique"):(_r(s,i),s)}},je=(n,i,o,c)=>{if(pt(n,i,o,c),he(n,tr).one().changed===0)throw new se(`optimistic concurrency conflict on "${i}" — the row changed during this mutation; refetch and retry`,"occ")},dn=(n,i,o,c,s,w,E)=>{const S=[];for(let C=0;C<o.length+1;C+=1){const A=o[C],D=c[C],P=D?.direction==="desc"?"desc":"asc",q=A===void 0||D===void 0?a`${a.identifier(ho)} < ${E}`:wo(A,w[C],P,!1);if(q===void 0)continue;const k=[];for(let O=0;O<C;O+=1)k.push(a`${a.identifier(o[O])} IS ${w[O]}`);k.push(q);const[W]=k;S.push(k.length===1&&W!==void 0?W:a`(${a.join(k,a` AND `)})`)}const I=S.length>0?a.join(S,a` OR `):a`1 = 0`,$=j(n,a`SELECT COUNT(*) AS c FROM ${a.identifier(i)} WHERE ${a.identifier("__partition__")} = ${s} AND (${I})`).one(),F=j(n,a`SELECT COUNT(*) AS c FROM ${a.identifier(i)} WHERE ${a.identifier("__partition__")} = ${s}`).one();return{before:$.c,total:F.c}},Ir=n=>{const i=new Map;for(const[c,s]of Object.entries(n.tables))for(const w of Object.values(s.relationMap??{}))w.kind==="one"&&(w.onDelete==="cascade"||w.onDelete==="set null")&&i.set(w.table,[...i.get(w.table)??[],{holder:c,op:w.onDelete==="cascade"?"delete":"update"}]);const o=c=>{const s=new Set,w=[c];for(let E=w.pop();E!==void 0;E=w.pop())for(const{holder:S,op:I}of i.get(E)??[]){if(S===c||Vt(n,S,I))return!0;s.has(S)||(s.add(S),w.push(S))}return!1};return new Set(Object.entries(n.tables).filter(([c,s])=>s.shardMode?.kind==="global"||Vt(n,c,"delete")||o(c)).map(([c])=>c))},Ar=n=>{const i=new Map;for(const[o,c]of Object.entries(n.tables))c.softDeleteMode&&i.set(o,c.softDeleteMode.field);return i},fi=n=>{const{baselineSeq:i,onStalePatchDropped:o}=n,{sql:c}=n,{schema:s}=n,w=n.broadcast??(()=>{}),E=(e,t)=>{if(!Object.hasOwn(s.tables,e))throw new y("BAD_REQUEST",`${t}: "${e}" is not a table in this schema`)},S=Eo(s),I=new Map;for(const e of S){const t=r=>(s.tables[r]?.shardMode?.kind??"root")==="root";!e.array&&t(e.sourceTable)&&t(e.targetTable)&&I.set(e.sourceTable,[...I.get(e.sourceTable)??[],e])}const $=(e,t,r)=>{for(const d of I.get(e)??[]){const f=t[d.column];if(typeof f!="string"||r?.[d.column]===f||d.targetTable===e&&t._id===f)continue;if(j(c,a`SELECT 1 FROM ${a.identifier(d.targetTable)} WHERE id = ${f} LIMIT 1`).toArray().length===0)throw new y("VALIDATION_ERROR",`${d.name} references ${d.targetTable} row "${f}", which does not exist`)}},F=Ro(s,n.inTransaction),C=Ir(s),A=Ar(s);let D;const P=()=>n.inTransaction?.()===!0,q=e=>s.tables[e]?.commitOrderedMode!==!0?{}:((D===void 0||!P())&&(D=Gn(c)),{[jn]:D}),k=(e,...t)=>{const r=s.tables[e]?.indexes;if(!r||r.length===0)return;const d=[];for(const f of t)f&&d.push(...po(r,f,Ae));return d.length>0?d:void 0},{headroom:W}=n;let O=!1;const pe=async e=>{const t=O;O=!0;try{return await e()}finally{O=t}},z=n.onRead??(()=>{}),m=e=>{Ft(s.tables[e])&&z(jt,jt)},M=n.onReadRange??(e=>{z(e.table,H)}),L=e=>{m(e.table),M(e)},R=(e,t)=>{t!==void 0&&t!==H&&!O&&W?.recordRead(1),m(e),z(e,t)},V=n.onIndexUse??(()=>{}),ge=n.onWrite??(()=>{}),K=e=>{O||W?.recordWrite(e)},oe=async e=>{K(e.doc),await ge(e)},{cache:ie}=n,ye=n.clock??(()=>Date.now()),$t=n.idGenerator??(()=>crypto.randomUUID()),Et=n.scheduler??Ln,{globalDb:$e}=n,ce=n.auth??{identity:null,userId:null},mt=n.cdc??!1,Ye=Et,Rn=Co({scheduler:typeof Ye.list=="function"&&typeof Ye.get=="function"?Ye:void 0,storage:n.storage}),Ee=(e,t,r,d)=>{mt&&!Ft(s.tables[e])&&On(c,ye(),e,t,r,d)},St=(e,t,r,d)=>{const f=s.tables[e];if(f?.dropStalePatchesMode!==!0||!mt)return!1;const h=i?.();if(h===void 0)return!1;const l=Hn(c,e,t,h);if(l===void 0)return!1;const u=ro(f,r);return Object.keys(Ge(r)).some(p=>!u.has(p)&&Lt(Bt(l,p))!==Lt(Bt(d,p)))},ae=e=>s.tables[e]?.shardMode?.kind==="global",Tt=(e,t)=>{if(ae(e)){if(!$e)throw new y("INTERNAL",`cross-backend ${t} for global table '${e}' requires a globalDb writer — pass one to createShardCtxDb({ globalDb })`);return $e}return U},Xe=e=>Tt(e,"cascade"),G=(e,t)=>{if(ae(e)){if(!$e)throw new y("INTERNAL",`${t} on global table '${e}' requires a globalDb writer — pass one to createShardCtxDb({ globalDb })`);return $e}},Rt=async(e,t,r,d,f)=>{f&&K(r);const h=await e.insert(t,r,d);return w({key:h,op:"insert",row:{...r,_id:h},table:t}),h},Ze=(e,t)=>Tt(e,"relation load").findMany(e,t),vt=(e,t)=>(ae(e)&&R(e,H),Ze(e,t)),vn=e=>!ae(e.table),_t=n.relationExistsPushDown??"auto",It=_t!=="never",{maxRelationKeys:At}=n,Ce=(e,t,r)=>So(e,{fetcher:vt,maxRelationKeys:At,relationBaseWhere:r,schema:s,tableName:t}),xt=async(e,t,r,d)=>{const f=G(e,"relation grouped count");if(f)return R(e,H),Io((g,B)=>f.count(g,B),e,t,r,d);const h=s.tables[e];if(!h)throw new y("INTERNAL",`unknown table: ${e}`);R(e,H);const l=ve(h.softDeleteMode,void 0),u={[t]:{in:r}},p=N(N(u,d),l),T=await Ce(p,e,void 0),x=Z(T,ue),v=fe(t);let _=a`SELECT ${v} AS __fk__, COUNT(*) AS count FROM ${a.identifier(e)}`;x&&(_=a`${_} WHERE ${x}`),_=a`${_} GROUP BY ${v}`;const b=j(c,_).toArray();return new Map(b.map(g=>[g.__fk__,g.count]))};let be=0;const Ct=new Set;for(const[e,t]of Object.entries(s.tables))for(const r of Object.values(t.triggerMap??{}))Ct.add(`${e} ${r.timing} ${r.op}`);const ee=(e,t,r)=>Ct.has(`${e} ${t} ${r}`),te=async(e,t,r)=>{if(be+=1,be>Zt)throw be-=1,new se(`trigger recursion exceeded ${String(Zt)} levels on "${r.table}" — check for a self-triggering write`,"trigger");try{await bo({ctx:Cn,event:r,op:t,schema:s,tableName:r.table,timing:e})}finally{be-=1}},{ensureBackfilledForTable:me,ensureBackfilledIndex:et,ensureRankBackfilled:tt,ensureRankBackfilledForTable:Se,syncAggregates:Me,syncCompanionsForInsert:bt,syncGeo:De,syncRanks:Te,syncSearch:ke}=Kn({broadcast:w,indexKeysFor:(e,t)=>k(e,t),invalidateCache:(e,t,r)=>ie?.invalidate(e,t,k(e,r)),recordCdc:Ee,schema:s,sql:c,verified:n.companionMemo?.verified}),Mt=(e,t,r)=>{const{shardMode:d}=t;if(d?.kind==="shardBy"&&!(d.field!==void 0&&(r.partitionBy??[]).includes(d.field)))throw Object.assign(new Error(`rank index "${r.name}" on "${e}" partitions across shards (shard key "${d.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})},_n=e=>Object.entries(s.tables).filter(([,t])=>t.shardMode?.kind!=="global").map(([t])=>t).filter(t=>e===void 0||t===e),Re=e=>e===void 0||ae(e)?$e:void 0,nt=async(e,t,r,d,f)=>{for(let h=0;h<r.length;h+=1)K(void 0);if(f!==void 0&&e.deleteMany!==void 0)return e.deleteMany(t,r,f.options);for(const h of r)await e.delete(t,h,d);return{deleted:r.length}},ne=(e,t)=>{const r=_n(t);for(let d=0;d<r.length;d+=en){const f=r.slice(d,d+en),[h]=he(c,or(f),...rr(e,f)).toArray();if(!h)continue;const l=h.__t__,u=_e(h);if(typeof l!="string"||!u)return;const p=h[re];return{docJson:typeof p=="string"?p:le(p??{}),row:u,tableName:l}}},Dt={assertRankPartitionLocal:Mt,ensureRankBackfilled:tt,onRead:R,rowToDocument:_e,schema:s,sql:c},In=(e,t,r)=>{const d=Z(r,ue);return d===void 0||j(c,a`SELECT 1 FROM ${a.identifier(e)} WHERE ${a.identifier("id")} = ${t} AND ${d}`).toArray().length>0},An=(e,t,r,d)=>St(e,t,r,d)?(o?.({fields:Object.keys(Ge(r)),id:t,table:e}),!0):!1,xn=async(e,t,r,d,f)=>{const h=ne(t,e);if(!h)return{applied:!1,doc:null};if(R(e,t),!In(e,t,r.where)||An(e,t,r.patch,h.row))return{applied:!1,doc:h.row};try{await f(r.patch)}catch(l){if(l instanceof se&&l.kind==="occ"&&d)return;throw l}return{applied:!0,doc:ne(t,e)?.row??null}},kt=async(e,t,r,d)=>{const{fetchLimit:f,limit:h,orderKeys:l,predicate:u}=await To(t,r,{canPushExists:It?vn:void 0,existsPushMode:_t==="always"?"always":"auto",fetcher:vt,maxRelationKeys:At,schema:s,tableName:e}),p=It?$r(d):Je,T=Z(u,p,Ve),x=yn(e,T,$n(l),f);return{limit:h,orderKeys:l,statement:x}},U={system:Rn,async aggregate(e,t){const r=G(e,"aggregate");if(r)return R(e,H),r.aggregate(e,t);const d=s.tables[e];if(!d)throw new y("INTERNAL",`unknown table: ${e}`);if(We(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 y("INTERNAL",`aggregate(${e}, { op: "${t.op}" }): "field" is required for non-count reducers`);R(e,H);const f=ve(d.softDeleteMode,void 0),h=N(N(t.baseWhere,t.where),f),l=await Ce(h,e,t.relationBaseWhere),u=l!==h;if(d.aggregateIndexes&&!t.baseWhere&&!u){const g=Bn(d.aggregateIndexes,t.op,t.field,t.where);if(g){et(e,g.index);const B=rt(g.index.by??[],g.key),Y=ot(e,g.index.name),X=j(c,a`SELECT ${Be} AS value, ${ct} AS count FROM ${a.identifier(Y)} WHERE ${Pe} = ${B}`).toArray()[0];return it(t.op,X)}}on(d,t.field,`aggregate(${e}, { op: "${t.op}", field: "${t.field}" })`);const p=Z(l,ue),T=We(t.op),x=fe(t.field);let v=a`SELECT ${a.raw(T)}(${x}) AS value FROM ${a.identifier(e)}`;p&&(v=a`${v} WHERE ${p}`);const b=j(c,v).toArray()[0]?.value;return b??null},asId(e,t){const r=rn(s,e,t);if(r===null)throw new y("BAD_REQUEST",`asId("${e}", …): "${t}" is not a valid id for table "${e}"`,{status:400});return r},async count(e,t){const r=G(e,"count");if(r)return R(e,H),r.count(e,t);const d=s.tables[e];if(!d)throw new y("INTERNAL",`unknown table: ${e}`);const f=Fn(t);if(f.restrictsCounts)throw new st(e);R(e,H);const h=ve(d.softDeleteMode,void 0),l=N(N(f.baseWhere,f.where),h),u=await Ce(l,e,f.relationBaseWhere),p=u!==l;if(d.aggregateIndexes&&!f.baseWhere&&!p){const _=Wn(d.aggregateIndexes,f.where);if(_){et(e,_.index);const b=rt(_.index.by??[],_.key),g=ot(e,_.index.name),B=j(c,a`SELECT ${Be} AS value FROM ${a.identifier(g)} WHERE ${Pe} = ${b}`).toArray();return B[0]===void 0?0:B[0].value??0}}const T=Z(u,ue);let x=a`SELECT COUNT(*) AS count FROM ${a.identifier(e)}`;return T&&(x=a`${x} WHERE ${T}`),j(c,x).one().count},async delete(e,t,r){E(e,"ctx.db.delete(table, id)");const d=ne(t,e);if(!d){const _=Re(e);_&&await nt(_,e,[t],r);return}const{docJson:f,row:h,tableName:l}=d,u=s.tables[l],p=r?.hard===!0,T=!p&&u?.softDeleteMode?u:void 0,x=T?.softDeleteMode?.field;if(x&&h[x]!==null&&h[x]!==void 0)return;if(ee(l,"before","delete")&&await te("before","delete",{id:t,op:"delete",previous:h,table:l}),await _o({deletedId:t,deletedReference:_=>h[_],findHolders:async(_,b,g,B)=>(await Xe(_).findMany(_,{...B,includeDeleted:p,where:{[b]:g}})).page,onCascade:(_,b)=>Xe(_).delete(_,b,r),onRestrict:_=>{throw new se(_,"restrict")},onSetNull:(_,b,g)=>Xe(_).patch(_,b,{[g]:null}),schema:s,tableName:l}),me(l),Se(l),T&&x){const _={[x]:ye()},b={...h,...q(l),..._,_id:t};lt(T,_,b,ce),je(c,l,Yt(l),[le(b),t,f]),ke(l,t,b,h),De(l,t,void 0),Me(l,h,b),Te(l,t,h,void 0);const g=k(l,h,b);ie?.invalidate(l,t,g),Ee(l,t,"update",b),w({indexKeys:g,key:t,op:"update",row:b,table:l}),ee(l,"after","delete")&&await te("after","delete",{id:t,op:"delete",previous:h,table:l}),await oe({id:t,op:"delete",table:l});return}je(c,l,er(l),[t,f]),ke(l,t,void 0),De(l,t,void 0),Me(l,h,void 0),Te(l,t,h,void 0);const v=k(l,h);ie?.invalidate(l,t,v),Ee(l,t,"delete"),w({indexKeys:v,key:t,op:"delete",table:l}),ee(l,"after","delete")&&await te("after","delete",{id:t,op:"delete",previous:h,table:l}),await oe({id:t,op:"delete",table:l})},async deleteAll(e,t){if(!s.tables[e])throw new y("INTERNAL",`unknown table: ${e}`);const r=Math.max(1,t?.chunkSize??wn),d=t?.hard===void 0?void 0:{hard:t.hard},f=G(e,"deleteAll");let h=0;return await pe(async()=>{for(;;){const u=(await U.findMany(e,{limit:r})).page.map(p=>String(p._id));if(u.length===0)break;for(const p of u)await(f===void 0?U.delete(e,p,d):nt(f,e,[p],d)),h+=1;if(u.length<r)break}}),{deleted:h}},async deleteMany(e,t,r){E(e,"ctx.db.deleteMany(table, ids)"),He(t.length,r?.limit,"deleteMany");for(const d of t)await U.delete(e,d);return{deleted:t.length}},async deleteWhere(e,t,r){const d=G(e,"deleteWhere"),h=(await tn(d??U,e,t,r?.limit,"deleteWhere")).map(l=>String(l._id));if(d)return nt(d,e,h,void 0,{options:r});if(U.deleteMany===void 0)throw new y("INTERNAL",`ctx.db.${e}.deleteMany is unavailable: this writer has no batch delete`);return U.deleteMany(e,h,r)},async findFirst(e,t={}){return(await U.findMany(e,{...t,limit:1,omitContinueCursor:!0})).page[0]??null},async findFirstOrThrow(e,t={}){const r=await U.findFirst(e,t);if(r===null)throw new to(`findFirstOrThrow: no "${e}" document matched`);return r},async findMany(e,t={}){const r=G(e,"findMany");if(r)return R(e,H),r.findMany(e,t);const d=s.tables[e];if(!d)throw new y("INTERNAL",`unknown table: ${e}`);const f=!t.where&&!t.baseWhere;f?R(e,H):R(e);const{limit:h,orderKeys:l,statement:u}=await kt(e,d,t,R),p=he(c,u.text,...u.params).toArray();f&&!O&&W?.recordRead(p.length);const T=[];for(const b of p){const g=_e(b);g&&(T.push(g),!f&&typeof g._id=="string"&&R(e,g._id))}if(h===void 0)return t.with&&await Nt({groupedCounter:xt,fetcher:Ze,parents:T,...Qt(t),schema:s,tableName:e,with:t.with}),{continueCursor:null,isDone:!0,page:Ot(T,t.select,t.with)};const x=T.length>h,v=x?T.slice(0,h):T,_=v.at(-1);return t.with&&await Nt({fetcher:Ze,groupedCounter:xt,parents:v,...Qt(t),schema:s,tableName:e,with:t.with}),{continueCursor:x&&_&&t.omitContinueCursor!==!0?Ke(_,l):null,isDone:!x,page:Ot(v,t.select,t.with)}},async explain(e,t={}){const r=G(e,"explain");if(r)return r.explain(e,t);const d=s.tables[e];if(!d)throw new y("INTERNAL",`unknown table: ${e}`);const{statement:f}=await kt(e,d,t,()=>{}),h=he(c,`EXPLAIN QUERY PLAN ${f.text}`,...f.params).toArray();return{params:f.params,plan:h.map(l=>String(l.detail)),sql:f.text}},async get(e,t){E(e,"ctx.db.get(table, id)");const r=ne(t,e);if(!r){const d=Re(e);return d?d.get(e,t):null}return R(r.tableName,t),r.row},async lookupById(e,t){const r=ne(e,t);return r?(R(r.tableName,e),{row:r.row,tableName:r.tableName}):null},async groupBy(e,t){const r=G(e,"groupBy");if(r)return R(e,H),r.groupBy(e,t);const d=s.tables[e];if(!d)throw new y("INTERNAL",`unknown table: ${e}`);R(e,H);const f=t.agg??{op:"count"};if(We(f.op),f.op!=="count"&&!f.field)throw new y("INTERNAL",`groupBy(${e}, { agg: { op: "${f.op}" } }): "field" is required for non-count reducers`);const h=ve(d.softDeleteMode,void 0),l=N(N(t.baseWhere,t.where),h),u=await Ce(l,e,t.relationBaseWhere),p=u!==l;if(d.aggregateIndexes&&!t.baseWhere&&!p){const g=qn(d.aggregateIndexes,f.op,f.field,t.by,t.where),B=g===void 0?0:Object.keys(g.partial).length,Y=g?.index.by?.length??0;if(g&&(B===0||B===Y)){et(e,g.index);const X=ot(e,g.index.name),Q=Object.keys(g.partial),de=[];if(Q.length===(g.index.by??[]).length&&Q.length>0){const Le=rt(g.index.by??[],g.partial),Fe=j(c,a`SELECT ${Be} AS value, ${ct} AS count FROM ${a.identifier(X)} WHERE ${Pe} = ${Le}`).toArray();return Fe.length>0&&de.push({key:{...g.partial},value:it(f.op,Fe[0])}),de}const bn=j(c,a`SELECT ${Pe} AS key, ${Be} AS value, ${ct} AS count FROM ${a.identifier(X)}`).toArray();for(const Le of bn){const Fe=kn(JSON.parse(Le.key));de.push({key:Fe,value:it(f.op,Le)})}return de}}for(const g of[...t.by,f.field]){if(g===void 0)continue;const B=g===f.field?`groupBy(${e}, { agg: { op: "${f.op}", field: "${g}" } })`:`groupBy(${e}, { by: [..."${g}"] })`;on(d,g,B)}const T=Z(u,ue),x=t.by.map(g=>a`${fe(g)} AS ${a.identifier(g)}`);if(f.op==="count")x.push(a`COUNT(*) AS value`);else{const{field:g}=f;if(g===void 0)throw new y("INTERNAL",`groupBy(${e}, { agg: { op: "${f.op}" } }): "field" is required for non-count reducers`);x.push(a`${a.raw(We(f.op))}(${fe(g)}) AS value`)}let v=a`SELECT ${a.join(x,a`, `)} FROM ${a.identifier(e)}`;T&&(v=a`${v} WHERE ${T}`),v=a`${v} GROUP BY ${a.join(t.by.map(g=>fe(g)),a`, `)}`;const _=j(c,v).toArray(),b=[];for(const g of _){const B={};for(const X of t.by)B[X]=Qn(d.shape[X],g[X]??null);const{value:Y}=g;b.push({key:B,value:Y==null?null:Number(Y)})}return b},async insert(e,t,r){const d=G(e,"insert");if(d)return Rt(d,e,t,r,!0);const f=s.tables[e];if(!f)throw new y("INTERNAL",`unknown table: ${e}`);const h=r?.allowExplicitId===!0,l=Ue(f,ft(f,t,ce),{supplied:t,trusted:h});let u;r?.clientId!==void 0?(sr(r.clientId),u=r.clientId):r?.allowExplicitId&&typeof l._id=="string"?(wt(l._id),u=l._id):u=$t();const p=r?.allowExplicitId&&typeof l._creationTime=="number"?l._creationTime:ye(),T={...l,...q(e),_creationTime:p,_id:u};return ee(e,"before","insert")&&await te("before","insert",{doc:{...T},id:u,op:"insert",table:e}),h||$(e,T),me(e),Se(e),pt(c,e,Xo(e),[u,p,le(T)]),bt(e,u,T),ee(e,"after","insert")&&await te("after","insert",{doc:T,id:u,op:"insert",table:e}),await oe({doc:T,id:u,op:"insert",table:e}),u},async insertManyUnsafe(e,t,r){if(He(t.length,r?.limit,"insertManyUnsafe"),t.length===0)return[];const d=G(e,"insert");if(d){const p=[];cr(s.tables[e],t,r?.allowExplicitId,ce);for(const T of t)K(T);for(const T of t){const x=await d.insert(e,T,{allowExplicitId:r?.allowExplicitId});w({key:x,op:"insert",row:{...T,_id:x},table:e}),p.push(x)}return p}const f=s.tables[e];if(!f)throw new y("INTERNAL",`unknown table: ${e}`);me(e),Se(e);const h=[];for(let p=0;p<t.length;p+=Oe)h.push(q(e));const l=r?.allowExplicitId===!0?void 0:vo(f),u=t.map((p,T)=>{const x=ft(f,p,ce),v=l===void 0?x:Ue(l,x,{supplied:p}),_=r?.allowExplicitId===!0&&typeof v._id=="string"?v._id:void 0;_!==void 0&&wt(_);const b=_??$t(),g=r?.allowExplicitId===!0&&typeof v._creationTime=="number"?v._creationTime:ye(),B={...v,...h[Math.floor(T/Oe)],_creationTime:g,_id:b};return{creationTime:g,document:B,id:b}});for(const p of u)K(p.document);for(let p=0;p<u.length;p+=Oe){const T=a.join(u.slice(p,p+Oe).map(v=>a`(${v.id}, ${v.creationTime}, ${le(v.document)})`),a`, `),x=un("sqlite",a`INSERT INTO ${a.identifier(e)} (id, _creationTime, ${a.identifier(re)}) VALUES ${T}`);pt(c,e,x.sql,x.params)}for(const{document:p,id:T}of u)bt(e,T,p),await ge({doc:p,id:T,op:"insert",table:e});return u.map(p=>p.id)},async insertMany(e,t,r){He(t.length,r?.limit,"insertMany");const d=r?.skipDuplicates===!0,f=[],h=G(e,"insert");if(h)for(const u of t)K(u);const l=async u=>h?Rt(h,e,u,void 0,!1):U.insert(e,u);for(const u of t)try{f.push(await l(u))}catch(p){if(d&&p instanceof se&&p.kind==="unique")f.push(null);else throw p}return f},normalizeId(e,t){return rn(s,e,t)},async patch(e,t,r,d){E(e,"ctx.db.patch(table, id, values)");const f=ne(t,e);if(!f){const b=Re(e);if(b){K(r),await b.patch(e,t,r,d);return}throw new y("NOT_FOUND",`document not found: ${t}`)}const{docJson:h,row:l,tableName:u}=f,p=s.tables[u];if(!p)throw new y("INTERNAL",`unknown table: ${u}`);if(R(u,t),cn("patch",r),St(u,t,r,l)){o?.({fields:Object.keys(Ge(r)),id:t,table:u});return}const T=no(p,r,l),x={...l,...Ge(T),...q(u),_id:t};lt(p,T,x,ce);const v=Ue(p,x,{only:new Set(Object.keys(T)),previous:()=>l,tolerateStoredNull:!0});oo(d,l,v),ee(u,"before","update")&&await te("before","update",{doc:{...v},id:t,op:"update",previous:l,table:u}),$(u,v,l),me(u),Se(u),je(c,u,Yt(u),[le(v),t,h]),ke(u,t,v,l),De(u,t,v),Me(u,l,v),Te(u,t,l,v);const _=k(u,l,v);ie?.invalidate(u,t,_),Ee(u,t,"update",v),w({indexKeys:_,key:t,op:"update",row:v,table:u}),ee(u,"after","update")&&await te("after","update",{doc:v,id:t,op:"update",previous:l,table:u}),await oe({doc:v,id:t,op:"update",table:u})},async patchIf(e,t,r){const d=G(e,"patchIf");if(d){if(d.patchIf===void 0)throw new y("INTERNAL",`ctx.db.patchIf on global table '${e}' is unsupported: its backend has no conditional write`);return K(r.patch),d.patchIf(e,t,r)}if(!s.tables[e])throw new y("INTERNAL",`unknown table: ${e}`);for(let f=1;f<=sn;f+=1){const h=await xn(e,t,r,f<sn,l=>U.patch(e,t,l,{verify:r.verify}));if(h!==void 0)return h}throw new se(`patchIf on "${e}" kept conflicting; the row changed on every attempt`,"occ")},async patchMany(e,t,r){E(e,"ctx.db.patchMany(table, patches)"),He(t.length,r?.limit,"patchMany");for(const d of t)await U.patch(e,d.id,d.patch);return{patched:t.length}},async patchWhere(e,t,r){const d=G(e,"patchWhere")??U,h=(await tn(d,e,t.where,r?.limit,"patchWhere")).map(l=>({id:String(l._id),patch:t.patch}));if(U.patchMany===void 0)throw new y("INTERNAL",`ctx.db.${e}.patchMany is unavailable: this writer has no batch patch`);return await U.patchMany(e,h,r),{patched:h.length}},async related(e,t){return mo(U,S,e,t)},relationEdges:S,deleteRereadTables:C,inTransaction:P,softDeleteFields:A,relationWrites:F,query(e){const t=G(e,"query");return t?(R(e,H),t.query(e)):Tn(c,s,e,V,r=>{r?L(r):R(e,H)},r=>{O||W?.recordRead(r)})},async rank(e,t,r){const d=G(e,"rank");if(d)return R(e,H),d.rank(e,t,r);V(e,t,"rank");const f=s.tables[e];if(!f)throw new y("INTERNAL",`unknown table: ${e}`);const h=f.rankIndexes?.find(Q=>Q.name===t);if(!h)throw new y("INTERNAL",`unknown rankIndex "${t}" on table "${e}"`);if(Mt(e,f,h),r.restrictsCounts)throw new st(e);R(e,H),tt(e,h);const l=typeof r.row=="string"?r.row:r.row._id;if(!l)return null;const u=Ht(e,h.name),p=h.sortBy.map((Q,de)=>Gt(de)),T=p.map(Q=>xe(Q)).join(", "),x=j(c,a`SELECT ${a.identifier("__partition__")}, ${a.raw(T)} FROM ${a.identifier(u)} WHERE ${a.identifier("__id__")} = ${l}`).toArray(),[v]=x;if(v===void 0)return null;let _=v.__partition__;const b=N(r.baseWhere,r.where);at(b,s,e,"rank");const g=uo(h,b);if(g){const Q=fo(h.partitionBy??[],g);if(Q!==_)return null;_=Q}const B=p.map(Q=>v[Q]),{before:Y,total:X}=dn(c,u,p,h.sortBy,_,B,l);return{position:Y+1,total:X}},async rankBefore(e,t,r){if(ae(e))throw new y("INTERNAL",`rankBefore is not supported on the global (.global()) table '${e}' — cross-shard rank cursors apply only to sharded tables`);const d=s.tables[e];if(!d)throw new y("INTERNAL",`unknown table: ${e}`);const f=d.rankIndexes?.find(p=>p.name===t);if(!f)throw new y("INTERNAL",`unknown rankIndex "${t}" on table "${e}"`);if(r.restrictsCounts)throw new st(e);R(e,H),tt(e,f);const h=Ht(e,f.name),l=f.sortBy.map((p,T)=>Gt(T)),u=f.sortBy.map((p,T)=>Ae(r.sortValues[T]??null));return dn(c,h,l,f.sortBy,r.partitionKey,u,r.rowId)},async rankPage(e,t,r={}){at(N(r.baseWhere,r.where),s,e,"rankPage");const d=G(e,"rankPage");if(d)return R(e,H),d.rankPage(e,t,r);V(e,t,"rank");const{continueCursor:f,hasMore:h,rows:l}=qt(Dt,e,t,r);return{continueCursor:f,isDone:!h,page:l.map(u=>u.doc)}},async rankPageRows(e,t,r={}){at(N(r.baseWhere,r.where),s,e,"rankPage"),V(e,t,"rank");const{directions:d,hasMore:f,rows:h}=qt(Dt,e,t,r);return{directions:d,hasMore:f,rows:h}},async restore(e,t){E(e,"ctx.db.restore(table, id)");const r=ne(t,e);if(!r){const h=Re(e);if(h?.restore){await h.restore(e,t);return}throw new y("NOT_FOUND",`document not found: ${t}`)}const d=s.tables[r.tableName]?.softDeleteMode?.field;if(!d)throw new y("INTERNAL",`ctx.db.restore: table "${r.tableName}" is not a .softDelete() table`);const f=r.row[d]!==null&&r.row[d]!==void 0;await U.patch(e,t,{[d]:null}),f&&Te(r.tableName,t,void 0,r.row)},async replace(e,t,r,d){E(e,"ctx.db.replace(table, id, document)");const f=ne(t,e);if(!f){const B=Re(e);if(B){K(r),await B.replace(e,t,r,d);return}throw new y("NOT_FOUND",`document not found: ${t}`)}const{docJson:h,row:l,tableName:u}=f,p=s.tables[u];if(!p)throw new y("INTERNAL",`unknown table: ${u}`);cn("replace",r);const T=d?.allowExplicitId&&typeof r._creationTime=="number"?r._creationTime:void 0,x=typeof l._creationTime=="number"?l._creationTime:void 0,v=T??x??ye(),_={...r,...q(u),_creationTime:v,_id:t};lt(p,r,_,ce);const b=d?.allowExplicitId===!0,g=Ue(p,_,{previous:()=>l,supplied:r,trusted:b});ee(u,"before","update")&&await te("before","update",{doc:{...g},id:t,op:"update",previous:l,table:u}),b||$(u,g,l),me(u),Se(u),je(c,u,Zo(u),[v,le(g),t,h]),ke(u,t,g,l),De(u,t,g),Me(u,l,g),Te(u,t,l,g),ie?.invalidate(u,t,k(u,l,g)),Ee(u,t,"update",g),w({indexKeys:k(u,l,g),key:t,op:"update",row:g,table:u}),ee(u,"after","update")&&await te("after","update",{doc:g,id:t,op:"update",previous:l,table:u}),await oe({doc:g,id:t,op:"update",table:u})},async wipeShard(e){const t=new Set(e?.exclude),r=e?.tables,d=Object.entries(s.tables).filter(([u,p])=>t.has(u)||r!==void 0&&!r.includes(u)?!1:p.shardMode?.kind!=="global").map(([u])=>u);if(r!==void 0){for(const u of r)if(!s.tables[u])throw new y("INTERNAL",`wipeShard: unknown table: ${u}`)}const f={};let h=0;const{deleteAll:l}=U;if(l===void 0)throw new y("INTERNAL","wipeShard: this writer has no deleteAll");for(const u of d){const p=await l(u,{...e?.chunkSize===void 0?{}:{chunkSize:e.chunkSize},hard:!0});f[u]=p.deleted,h+=p.deleted}return{deleted:h,tables:f}}},Cn={db:U,scheduler:Et};return n.enforceRls===!0?Ao(U,s,(e,t)=>ne(e,t)?.tableName,S):U};export{Ei as CDC_LOG_TABLE,Oi as IDEMPOTENCY_TABLE,Er as NotUniqueError,Wi as advanceClientWatermark,mi as applyCdcChanges,cn as assertNoExplicitUndefined,wt as assertStorableRowId,sr as assertValidClientId,pi as backfillAggregateIndexes,gi as backfillRankIndexes,yi as backfillSearchIndexes,Si as bumpCdcEpoch,Ti as cdcCanVouchFor,Ri as cdcForkedError,vi as cdcSeqLeavingRows,_i as cdcTouchesTables,Ii as cdcTrimmedError,Ai as compactCdcDocs,fi as createShardCtxDb,xi as cursorBelowRetainedFloor,Bi as migrateClientWatermark,Ci as minCdcReplayableSeq,bi as minCdcSeq,rn as normalizeIdStructurally,Mi as readCdcChangeKeys,Di as readCdcChanges,ki as readCdcCursor,Li as readCdcEpoch,Pi as readClientWatermark,Hi as readIdempotent,Ni as runShardMigrations,Vi as selectShapeMembers,Ji as selectShapeRows,Ge as stripReservedPatchFields,Fi as trimCdcChanges,Gi as trimIdempotent,ji as writeIdempotent};
@@ -0,0 +1 @@
1
+ const a=(n,t)=>{const o=Math.max(n.length,t.length);let r=n.length^t.length;for(let e=0;e<o;e+=1){const c=e<n.length?n.charCodeAt(e):0,s=e<t.length?t.charCodeAt(e):0;r|=c^s}return r===0},i="LUNORA_RELAY_SECRET",h="x-lunora-relay-sig",l=n=>{const t=n?.[i];return typeof t=="string"&&t.length>0?t:void 0},g=async(n,t)=>{const o=new TextEncoder,r=await crypto.subtle.importKey("raw",o.encode(n),{hash:"SHA-256",name:"HMAC"},!1,["sign"]),e=await crypto.subtle.sign("HMAC",r,o.encode(t));return[...new Uint8Array(e)].map(c=>c.toString(16).padStart(2,"0")).join("")},u=async(n,t,o)=>{const r=l(n);return r===void 0?!0:t===null?!1:a(t,await g(r,o))};export{h as RELAY_SIGNATURE_HEADER,l as siblingSecretOf,g as signSiblingBody,u as verifySiblingBody};
@@ -0,0 +1 @@
1
+ import{LunoraError as f}from"@lunora/errors";import{findRelated as y}from"./RELATED_DEFAULT_LIMIT-CVqN4JEu.mjs";const w=Symbol.for("lunora.ctxdb.rls-unwrap");class b extends f{table;constructor(o){super("RLS_REQUIRED",`ctx.db access to "${o}" is denied: the schema is marked .rls("required"), so this table is protected. Apply RLS with .use(rls(policies)) in the procedure, or mark the table .public() to opt it out.`,{name:"RlsRequiredError"}),this.table=o}}const R=n=>Object.entries(n.tables).filter(([,o])=>o.shardMode?.kind!=="global").map(([o])=>o),m=(n,o,l)=>{const i=o?.tables,a=new Set(o?.exclude);for(const s of n)(i===void 0||i.includes(s))&&!a.has(s)&&l(s)},g={aggregate:"loop-gated",asId:"ungated",assertPatchAllowed:"inline-table-gated",cdcChangedTables:"ungated",count:"loop-gated",delete:"inline-table-gated",deleteAll:"loop-gated",deleteMany:"inline-table-gated",deleteWhere:"inline-table-gated",explain:"loop-gated",findFirst:"loop-gated",findFirstOrThrow:"loop-gated",findMany:"loop-gated",get:"inline-table-gated",groupBy:"loop-gated",insert:"loop-gated",insertMany:"loop-gated",insertManyUnsafe:"loop-gated",inTransaction:"ungated",lookupById:"id-gated",normalizeId:"ungated",patch:"inline-table-gated",patchIf:"loop-gated",patchMany:"inline-table-gated",patchWhere:"inline-table-gated",query:"loop-gated",rank:"loop-gated",rankBefore:"loop-gated",rankPage:"loop-gated",rankPageRows:"loop-gated",related:"rebound",relationEdges:"ungated",deleteRereadTables:"ungated",relationWrites:"ungated",softDeleteFields:"ungated",replace:"inline-table-gated",restore:"inline-table-gated",system:"ungated",wipeShard:"sweep-gated"},M=Object.entries(g).filter(([,n])=>n==="loop-gated").map(([n])=>n),S={related:(n,o)=>(...l)=>{const[i,a]=l;return y(n,o,i,a)}},E=Object.entries(g).filter(([,n])=>n==="rebound").map(([n])=>n),O=(n,o,l)=>{for(const i of E)typeof o[i]=="function"&&(n[i]=S[i](n,l))},k=(n,o,l,i=[])=>{if(o.rlsMode!=="required")return n;const a=n,s=e=>{const t=o.tables[e];return t!==void 0&&t.isPublic!==!0},d=e=>{if(s(e))throw new b(e)},p=async(e,t)=>{if(t!==void 0){d(t);return}const r=await l(e);r!==void 0&&d(r)},c={...n,delete:async(e,t,r)=>(d(e),await a.delete(e,t,r)),deleteMany:async(e,t,r)=>(d(e),await a.deleteMany(e,t,r)),deleteWhere:a.deleteWhere?async(e,t,r)=>(d(e),await a.deleteWhere?.(e,t,r)):void 0,get:async(e,t)=>(d(e),await a.get(e,t)),lookupById:async(e,t)=>(await p(e,t),a.lookupById?.(e,t)??null),patch:async(e,t,r,u)=>(d(e),await a.patch(e,t,r,u)),patchMany:async(e,t,r)=>(d(e),await a.patchMany(e,t,r)),assertPatchAllowed:async(e,t)=>(d(e),await a.assertPatchAllowed?.(e,t)),patchWhere:a.patchWhere?async(e,t,r)=>(d(e),await a.patchWhere?.(e,t,r)):void 0,replace:async(e,t,r,u)=>(d(e),await a.replace(e,t,r,u)),restore:async(e,t)=>(d(e),await a.restore?.(e,t))},h=a;for(const e of M){const t=h[e];typeof t=="function"&&(c[e]=(r,...u)=>(d(r),t.call(a,r,...u)))}if(O(c,a,i),a.wipeShard){const{wipeShard:e}=a;c.wipeShard=t=>(m(R(o),t,d),e.call(a,t))}return Object.defineProperty(c,w,{configurable:!0,enumerable:!1,value:n,writable:!1}),c};export{M as LOOP_GATED_METHODS,w as RLS_UNWRAP_SYMBOL,b as RlsRequiredError,g as WRITER_METHOD_GATING,k as guardWriter};
@@ -1 +1 @@
1
- import{readCdcChangeKeys as s}from"./CDC_LOG_TABLE-CwEMKX-0.mjs";import{selectShapeMembers as h}from"./selectShapeMembers-BCfKypfN.mjs";import{shapeRangeKey as u}from"./ShapeDiffCache-iNO-hUiy.mjs";import{projectColumns as g}from"./buildPokeFrames-WR-hp0mX.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-oPp25hdi.mjs";import{selectShapeMembers as h}from"./selectShapeMembers-BCfKypfN.mjs";import{shapeRangeKey as u}from"./ShapeDiffCache-iNO-hUiy.mjs";import{projectColumns as g}from"./buildPokeFrames-WR-hp0mX.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,7 +1,7 @@
1
- import{LunoraError as m}from"@lunora/errors";import{decodeWire as v,encodeWire as N}from"@lunora/wire";import{cursorBelowRetainedFloor as b}from"./CDC_LOG_TABLE-CwEMKX-0.mjs";import{envPositiveInt as E}from"./envOptionalPositiveInt-D2pY-c64.mjs";import{e as I}from"./estimate-bytes-_k74s6LZ.mjs";import{verifySiblingBody as L,RELAY_SIGNATURE_HEADER as S,siblingStub as O,siblingSecretOf as R,signSiblingBody as C}from"./RELAY_SIGNATURE_HEADER-C_P73AOx.mjs";import{DEFAULT_TRANSACTION_LIMITS as U}from"./DEFAULT_TRANSACTION_LIMITS-Dmj5VBrV.mjs";const q=["wnam","enam","sam","weur","eeur","apac","apac-ne","apac-se","oc","afr","me"],x=new Set(q),F=r=>typeof r=="string"&&x.has(r),w="::replica::",_=r=>{const e=r.lastIndexOf(w);if(e===-1)return;const t=r.slice(0,e),s=r.slice(e+w.length);if(!(t.length===0||!F(s)))return{ownerKey:t,region:s}},M=r=>{if(r==null||!/^\d+$/.test(r))return;const e=Number.parseInt(r,10);return Number.isSafeInteger(e)&&e>0?e:void 0},P=1e3,A=1e3,B=10,D=5e4,W=r=>E(r,"LUNORA_REPLICA_MAX_BOOTSTRAP_ROWS",D),f="__replica_state",g=new WeakSet,T=r=>{g.has(r)||(r.exec(`CREATE TABLE IF NOT EXISTS ${f} (
1
+ import{LunoraError as T}from"@lunora/errors";import{decodeWire as v,encodeWire as N}from"@lunora/wire";import{cursorBelowRetainedFloor as b}from"./CDC_LOG_TABLE-oPp25hdi.mjs";import{envPositiveInt as E}from"./envOptionalPositiveInt-D2pY-c64.mjs";import{e as I}from"./estimate-bytes-_k74s6LZ.mjs";import{siblingStub as L}from"./stubByName-DLPoppDc.mjs";import{DEFAULT_TRANSACTION_LIMITS as O}from"./DEFAULT_TRANSACTION_LIMITS-Dmj5VBrV.mjs";import{verifySiblingBody as C,RELAY_SIGNATURE_HEADER as S,siblingSecretOf as R,signSiblingBody as U}from"./RELAY_SIGNATURE_HEADER-DNzVQxbZ.mjs";const q=["wnam","enam","sam","weur","eeur","apac","apac-ne","apac-se","oc","afr","me"],x=new Set(q),F=r=>typeof r=="string"&&x.has(r),w="::replica::",_=r=>{const e=r.lastIndexOf(w);if(e===-1)return;const t=r.slice(0,e),s=r.slice(e+w.length);if(!(t.length===0||!F(s)))return{ownerKey:t,region:s}},M=r=>{if(r==null||!/^\d+$/.test(r))return;const e=Number.parseInt(r,10);return Number.isSafeInteger(e)&&e>0?e:void 0},P=1e3,A=1e3,B=10,D=5e4,W=r=>E(r,"LUNORA_REPLICA_MAX_BOOTSTRAP_ROWS",D),f="__replica_state",g=new WeakSet,m=r=>{g.has(r)||(r.exec(`CREATE TABLE IF NOT EXISTS ${f} (
2
2
  id INTEGER PRIMARY KEY CHECK (id = 1),
3
3
  epoch TEXT NOT NULL,
4
4
  applied_seq INTEGER NOT NULL,
5
5
  synced_at REAL NOT NULL
6
- )`),g.add(r))},h=r=>(T(r),r.exec(`SELECT epoch, applied_seq AS appliedSeq, synced_at AS syncedAtMs FROM ${f} WHERE id = 1`).toArray()[0]),l=(r,e)=>{T(r),r.exec(`INSERT INTO ${f} (id, epoch, applied_seq, synced_at) VALUES (1, ?, ?, ?)
7
- ON CONFLICT(id) DO UPDATE SET epoch = excluded.epoch, applied_seq = excluded.applied_seq, synced_at = excluded.synced_at`,e.epoch,e.appliedSeq,e.syncedAtMs)},$=r=>{const e=r.doName();if(e!==void 0&&_(e)!==void 0)return new Response("replica cannot serve replicas",{status:409});if(r.ownerEpoch()===void 0)return new Response("shard has no changelog to replicate",{status:409});if(R(r.env())===void 0)return new Response("replica control requires LUNORA_RELAY_SECRET",{status:403})},p=r=>Response.json(N(r)),X=async(r,e)=>{if(r.rowCount()>W(r.env()))return p({cursor:0,epoch:e,rows:[],truncated:!0});const t=r.ownerCursor()??0,s=await r.exportRows();return p({cursor:t,epoch:e,rows:s})},k=(r,e,t)=>{const s=r.ownerFloor();if(b(s,t))return p({changes:[],cursor:r.ownerCursor()??t,epoch:e,floor:s});const n=r.ownerCursor()??0;if(t>n)return p({changes:[],cursor:n,epoch:e,...s===void 0?{}:{floor:s}});const{changes:o,cursor:i}=r.readChanges(t,A);return p({changes:o,cursor:i,epoch:e,...s===void 0?{}:{floor:s}})},ee=async(r,e)=>{const t=$(r);if(t!==void 0)return t;const s=r.ownerEpoch();let n;try{n=await e.text()}catch{return new Response("bad request",{status:400})}if(!await L(r.env(),e.headers.get(S),n))return new Response("forbidden",{status:403});let o;try{o=JSON.parse(n)}catch{return new Response("bad request",{status:400})}if(o.type==="replica_bootstrap")return X(r,s);if(o.type==="replica_pull"){const i=typeof o.sinceSeq=="number"&&Number.isInteger(o.sinceSeq)&&o.sinceSeq>=0?o.sinceSeq:0;return k(r,s,i)}return new Response("unknown replica frame",{status:400})},K=r=>{const e=r;return typeof r=="object"&&(e?.retryable===!0||e?.overloaded===!0)},j=(r,e)=>{const t=e.changes.length===0&&e.cursor>r.appliedSeq,s=e.floor??(t?e.cursor:0),n=s>0&&s>r.appliedSeq+1,o=e.cursor<r.appliedSeq;return e.epoch!==r.epoch||o?"fork":n?"compacted":void 0},y=(r,e)=>`${r}\0${e}`;class H{constructor(e,t,s){this.host=e,this.ownerKey=t,this.region=s}host;ownerKey;region;divergent=!1;inFlight;async ensureFresh(e){if(this.divergent)return"unavailable";if(this.isCaughtUp(e))return"fresh";this.inFlight??=this.advance(e).finally(()=>{this.inFlight=void 0});const t=await this.inFlight;return t==="fresh"&&!this.isCaughtUp(e)?"stale":t}appliedSeq(){return h(this.host.sql())?.appliedSeq??0}isDivergent(){return this.divergent}async advance(e){let t=h(this.host.sql());if(t===void 0){const s=await this.bootstrap();if(s===void 0)return"unavailable";t=s}return this.catchUp(t,e)}isCaughtUp(e){const t=h(this.host.sql());return t!==void 0&&this.isFreshEnough(t,e)}async catchUp(e,t){let s=e,n=!1;for(let o=0;o<B;o+=1){const i=await this.pull(s.appliedSeq);if(i===void 0)return this.whenOwnerUnreachable(s,t);const c=j(s,i);if(c!==void 0){const a=await this.recover(s,c,n);if(typeof a=="string")return a;n=!0,s=a;continue}const d=i.changes.length<A,u=await this.applyPage(i,s,d);if(u===void 0)return"unavailable";if(s=u,d||this.isFreshEnough(s,t))return this.verdict(s,t)}return this.verdict(s,t)}verdict(e,t){return this.isFreshEnough(e,t)?"fresh":"stale"}async recover(e,t,s){return t==="fork"?(this.divergent=!0,"unavailable"):s?"unavailable":await this.resnapshot(e)??"unavailable"}whenOwnerUnreachable(e,t){return t===void 0&&this.isFreshEnough(e,void 0)?"fresh":"unavailable"}async applyPage(e,t,s){if(!await this.applyAtomically("replica.applyPage",e.changes))return;const n={appliedSeq:e.cursor,epoch:e.epoch,syncedAtMs:s?Date.now():t.syncedAtMs};return l(this.host.sql(),n),n}async applyAtomically(e,t){if(t.length===0)return!0;try{return await this.host.applyChanges(t),!0}catch(s){return K(s)||(this.divergent=!0),this.host.reportError?.(e,s),!1}}async fetchSnapshot(){const e=await this.request({type:"replica_bootstrap"});if(e===void 0)return;const t=v(await e.json());if(t.truncated===!0){this.divergent=!0;return}return t}async resnapshot(e){const t=await this.fetchSnapshot();if(t===void 0)return;const s={...U,...this.host.transactionLimits()},n=[],o=new Set;let i=0;for(const{doc:d,table:u}of t.rows){const a=String(d._id);o.add(y(u,a)),i+=I(d)??Number.POSITIVE_INFINITY,n.push({doc:d,id:a,op:"insert",seq:t.cursor,table:u,ts:0})}if(this.overWriteBudget(n.length,i,s))return;for(const{doc:d,table:u}of await this.host.exportRows()){const a=String(d._id);o.has(y(u,a))||n.push({id:a,op:"delete",seq:t.cursor,table:u,ts:0})}if(this.overWriteBudget(n.length,i,s)||!await this.applyAtomically("replica.resnapshot",n))return;const c={appliedSeq:t.cursor,epoch:t.epoch,syncedAtMs:e.syncedAtMs};return l(this.host.sql(),c),c}overWriteBudget(e,t,s){return e<=s.maxWrittenRows&&t<=s.maxWrittenBytes?!1:(this.host.reportError?.("replica.resnapshot",new m("TRANSACTION_LIMIT_EXCEEDED",`a re-snapshot would write ${String(e)} documents and ${String(t)} bytes, over the ${String(s.maxWrittenRows)}-document / ${String(s.maxWrittenBytes)}-byte transaction limit`)),!0)}async bootstrap(){const e=await this.fetchSnapshot();if(e===void 0)return;const{errors:t}=await this.host.importRows(e.rows);if(t.length>0){this.divergent=!0;return}const s={appliedSeq:e.cursor,epoch:e.epoch,syncedAtMs:Date.now()};return l(this.host.sql(),s),s}isFreshEnough(e,t){return t!==void 0?e.appliedSeq>=t:Date.now()-e.syncedAtMs<=E(this.host.env(),"LUNORA_REPLICA_MAX_STALENESS_MS",P)}async pull(e){const t=await this.request({sinceSeq:e,type:"replica_pull"});return t===void 0?void 0:v(await t.json())}async request(e){const t=this.host.shardBinding(),s=O(this.host.env(),t,this.ownerKey,this.host.shardJurisdiction());if(s===void 0)return;const n=JSON.stringify(e),o={"content-type":"application/json","x-lunora-shard-binding":t??""},i=R(this.host.env());i!==void 0&&(o[S]=await C(i,n));try{const c=await s.fetch("https://replica.internal/_lunora/replica",{body:n,headers:o,method:"POST"});return c.ok?c:void 0}catch{return}}}const te=r=>{const e=r.doName();if(e===void 0)return;const t=_(e);return t===void 0?void 0:new H(r,t.ownerKey,t.region)},re=async(r,e,t)=>{if(e.headers.get("x-lunora-replica-read")!=="1")return Response.json({error:{code:"REPLICA_READ_ONLY",message:`"${t}" is a write and cannot run on a read replica`}},{status:421});const s=await r.ensureFresh(M(e.headers.get("x-lunora-min-seq")));if(s!=="fresh")return Response.json({error:{code:"REPLICA_NOT_READY",message:`replica is ${s} for this read`}},{headers:{"x-lunora-replica-fallback":s},status:421})};export{te as createReplicaLink,re as gateReplicaDispatch,ee as handleReplicaControl};
6
+ )`),g.add(r))},h=r=>(m(r),r.exec(`SELECT epoch, applied_seq AS appliedSeq, synced_at AS syncedAtMs FROM ${f} WHERE id = 1`).toArray()[0]),l=(r,e)=>{m(r),r.exec(`INSERT INTO ${f} (id, epoch, applied_seq, synced_at) VALUES (1, ?, ?, ?)
7
+ ON CONFLICT(id) DO UPDATE SET epoch = excluded.epoch, applied_seq = excluded.applied_seq, synced_at = excluded.synced_at`,e.epoch,e.appliedSeq,e.syncedAtMs)},$=r=>{const e=r.doName();if(e!==void 0&&_(e)!==void 0)return new Response("replica cannot serve replicas",{status:409});if(r.ownerEpoch()===void 0)return new Response("shard has no changelog to replicate",{status:409});if(R(r.env())===void 0)return new Response("replica control requires LUNORA_RELAY_SECRET",{status:403})},p=r=>Response.json(N(r)),X=async(r,e)=>{if(r.rowCount()>W(r.env()))return p({cursor:0,epoch:e,rows:[],truncated:!0});const t=r.ownerCursor()??0,s=await r.exportRows();return p({cursor:t,epoch:e,rows:s})},k=(r,e,t)=>{const s=r.ownerFloor();if(b(s,t))return p({changes:[],cursor:r.ownerCursor()??t,epoch:e,floor:s});const n=r.ownerCursor()??0;if(t>n)return p({changes:[],cursor:n,epoch:e,...s===void 0?{}:{floor:s}});const{changes:o,cursor:i}=r.readChanges(t,A);return p({changes:o,cursor:i,epoch:e,...s===void 0?{}:{floor:s}})},te=async(r,e)=>{const t=$(r);if(t!==void 0)return t;const s=r.ownerEpoch();let n;try{n=await e.text()}catch{return new Response("bad request",{status:400})}if(!await C(r.env(),e.headers.get(S),n))return new Response("forbidden",{status:403});let o;try{o=JSON.parse(n)}catch{return new Response("bad request",{status:400})}if(o.type==="replica_bootstrap")return X(r,s);if(o.type==="replica_pull"){const i=typeof o.sinceSeq=="number"&&Number.isInteger(o.sinceSeq)&&o.sinceSeq>=0?o.sinceSeq:0;return k(r,s,i)}return new Response("unknown replica frame",{status:400})},K=r=>{const e=r;return typeof r=="object"&&(e?.retryable===!0||e?.overloaded===!0)},j=(r,e)=>{const t=e.changes.length===0&&e.cursor>r.appliedSeq,s=e.floor??(t?e.cursor:0),n=s>0&&s>r.appliedSeq+1,o=e.cursor<r.appliedSeq;return e.epoch!==r.epoch||o?"fork":n?"compacted":void 0},y=(r,e)=>`${r}\0${e}`;class H{constructor(e,t,s){this.host=e,this.ownerKey=t,this.region=s}host;ownerKey;region;divergent=!1;inFlight;async ensureFresh(e){if(this.divergent)return"unavailable";if(this.isCaughtUp(e))return"fresh";this.inFlight??=this.advance(e).finally(()=>{this.inFlight=void 0});const t=await this.inFlight;return t==="fresh"&&!this.isCaughtUp(e)?"stale":t}appliedSeq(){return h(this.host.sql())?.appliedSeq??0}isDivergent(){return this.divergent}async advance(e){let t=h(this.host.sql());if(t===void 0){const s=await this.bootstrap();if(s===void 0)return"unavailable";t=s}return this.catchUp(t,e)}isCaughtUp(e){const t=h(this.host.sql());return t!==void 0&&this.isFreshEnough(t,e)}async catchUp(e,t){let s=e,n=!1;for(let o=0;o<B;o+=1){const i=await this.pull(s.appliedSeq);if(i===void 0)return this.whenOwnerUnreachable(s,t);const c=j(s,i);if(c!==void 0){const a=await this.recover(s,c,n);if(typeof a=="string")return a;n=!0,s=a;continue}const d=i.changes.length<A,u=await this.applyPage(i,s,d);if(u===void 0)return"unavailable";if(s=u,d||this.isFreshEnough(s,t))return this.verdict(s,t)}return this.verdict(s,t)}verdict(e,t){return this.isFreshEnough(e,t)?"fresh":"stale"}async recover(e,t,s){return t==="fork"?(this.divergent=!0,"unavailable"):s?"unavailable":await this.resnapshot(e)??"unavailable"}whenOwnerUnreachable(e,t){return t===void 0&&this.isFreshEnough(e,void 0)?"fresh":"unavailable"}async applyPage(e,t,s){if(!await this.applyAtomically("replica.applyPage",e.changes))return;const n={appliedSeq:e.cursor,epoch:e.epoch,syncedAtMs:s?Date.now():t.syncedAtMs};return l(this.host.sql(),n),n}async applyAtomically(e,t){if(t.length===0)return!0;try{return await this.host.applyChanges(t),!0}catch(s){return K(s)||(this.divergent=!0),this.host.reportError?.(e,s),!1}}async fetchSnapshot(){const e=await this.request({type:"replica_bootstrap"});if(e===void 0)return;const t=v(await e.json());if(t.truncated===!0){this.divergent=!0;return}return t}async resnapshot(e){const t=await this.fetchSnapshot();if(t===void 0)return;const s={...O,...this.host.transactionLimits()},n=[],o=new Set;let i=0;for(const{doc:d,table:u}of t.rows){const a=String(d._id);o.add(y(u,a)),i+=I(d)??Number.POSITIVE_INFINITY,n.push({doc:d,id:a,op:"insert",seq:t.cursor,table:u,ts:0})}if(this.overWriteBudget(n.length,i,s))return;for(const{doc:d,table:u}of await this.host.exportRows()){const a=String(d._id);o.has(y(u,a))||n.push({id:a,op:"delete",seq:t.cursor,table:u,ts:0})}if(this.overWriteBudget(n.length,i,s)||!await this.applyAtomically("replica.resnapshot",n))return;const c={appliedSeq:t.cursor,epoch:t.epoch,syncedAtMs:e.syncedAtMs};return l(this.host.sql(),c),c}overWriteBudget(e,t,s){return e<=s.maxWrittenRows&&t<=s.maxWrittenBytes?!1:(this.host.reportError?.("replica.resnapshot",new T("TRANSACTION_LIMIT_EXCEEDED",`a re-snapshot would write ${String(e)} documents and ${String(t)} bytes, over the ${String(s.maxWrittenRows)}-document / ${String(s.maxWrittenBytes)}-byte transaction limit`)),!0)}async bootstrap(){const e=await this.fetchSnapshot();if(e===void 0)return;const{errors:t}=await this.host.importRows(e.rows);if(t.length>0){this.divergent=!0;return}const s={appliedSeq:e.cursor,epoch:e.epoch,syncedAtMs:Date.now()};return l(this.host.sql(),s),s}isFreshEnough(e,t){return t!==void 0?e.appliedSeq>=t:Date.now()-e.syncedAtMs<=E(this.host.env(),"LUNORA_REPLICA_MAX_STALENESS_MS",P)}async pull(e){const t=await this.request({sinceSeq:e,type:"replica_pull"});return t===void 0?void 0:v(await t.json())}async request(e){const t=this.host.shardBinding(),s=L(this.host.env(),t,this.ownerKey,this.host.shardJurisdiction());if(s===void 0)return;const n=JSON.stringify(e),o={"content-type":"application/json","x-lunora-shard-binding":t??""},i=R(this.host.env());i!==void 0&&(o[S]=await U(i,n));try{const c=await s.fetch("https://replica.internal/_lunora/replica",{body:n,headers:o,method:"POST"});return c.ok?c:void 0}catch{return}}}const re=r=>{const e=r.doName();if(e===void 0)return;const t=_(e);return t===void 0?void 0:new H(r,t.ownerKey,t.region)},se=async(r,e,t)=>{if(e.headers.get("x-lunora-replica-read")!=="1")return Response.json({error:{code:"REPLICA_READ_ONLY",message:`"${t}" is a write and cannot run on a read replica`}},{status:421});const s=await r.ensureFresh(M(e.headers.get("x-lunora-min-seq")));if(s!=="fresh")return Response.json({error:{code:"REPLICA_NOT_READY",message:`replica is ${s} for this read`}},{headers:{"x-lunora-replica-fallback":s},status:421})};export{re as createReplicaLink,se as gateReplicaDispatch,te as handleReplicaControl};
@@ -0,0 +1 @@
1
+ import{createShardCtxDb as _}from"./NotUniqueError-DvGeO5_k.mjs";import{createRelayLink as I}from"./DEFAULT_MAX_RELAYS-B1jshtuE.mjs";import{ConflictError as q}from"./ConflictError-C8GtJmjS.mjs";import{runShardMigrations as E}from"./runShardMigrations-BXGBfJU1.mjs";import{relayName as F}from"./DEFAULT_PROMOTION_THRESHOLDS-B3pRMuqb.mjs";const S=(O,m={})=>({_meta:{column:{notNull:!0,...m}},kind:O}),A=(O,m,x)=>{const{describe:v,expect:d,it:b}=x;v(`engine contract: ${O}`,()=>{v("optimistic concurrency",()=>{const w=u=>({tables:{items:{indexes:[],shape:{title:S("string"),version:S("number",{notNull:!1})},triggerMap:{clobber:{handler:()=>{u.exec(`UPDATE "items" SET "__doc__" = json_set("__doc__", '$.version', 99) WHERE "id" = 'i1'`)},op:"update",timing:"before"}}}}});b("raises a CONFLICT of kind `occ` when a write's snapshot is clobbered",async()=>{const{close:u,host:h}=m();try{const c=h.sql,p=w(c);E(c,p);const s=_({schema:p,sql:c});await s.insert("items",{_id:"i1",title:"first",version:1},{allowExplicitId:!0}),await d(s.patch("items","i1",{title:"second"})).rejects.toBeInstanceOf(q)}finally{u?.()}}),b("reports the conflict as CONFLICT/409 rather than retrying it away",async()=>{const{close:u,host:h}=m();try{const c=h.sql,p=w(c);E(c,p);const s=_({schema:p,sql:c});await s.insert("items",{_id:"i1",title:"first",version:1},{allowExplicitId:!0});let a;try{await s.patch("items","i1",{title:"second"})}catch(t){a=t}const e=a;d(e.code).toBe("CONFLICT"),d(e.kind).toBe("occ")}finally{u?.()}}),b("leaves the row readable and unchanged after a conflict",async()=>{const{close:u,host:h}=m();try{const c=h.sql,p=w(c);E(c,p);const s=_({schema:p,sql:c});await s.insert("items",{_id:"i1",title:"first",version:1},{allowExplicitId:!0});try{await s.patch("items","i1",{title:"second"})}catch{}const a=await s.get("items","i1");d(a?.title).toBe("first"),d(a?.version).toBe(99)}finally{u?.()}}),b("raises a CONFLICT of kind `trigger` when a trigger writes its own row through the db",async()=>{const{close:u,host:h}=m();try{const c=h.sql,p={tables:{items:{indexes:[],shape:{title:S("string"),version:S("number",{notNull:!1})},triggerMap:{recurse:{handler:async(t,o)=>{await t.db.patch("items",o.doc._id,{version:99})},op:"update",timing:"before"}}}}};E(c,p);const s=_({schema:p,sql:c});await s.insert("items",{_id:"i1",title:"first",version:1},{allowExplicitId:!0});let a;try{await s.patch("items","i1",{title:"second"})}catch(t){a=t}const e=a;d(e).toBeInstanceOf(q),d(e.code).toBe("CONFLICT"),d(e.kind).toBe("trigger")}finally{u?.()}})}),v("shape-poke ordering",()=>{const w="shard-a",u={args:{},name:"messages"},h=(e,t,o,n)=>e.accept(t?.()??{},{connectionId:o,shapes:{[n]:u}}),c=(e,t,o)=>{let n=0,l=0;const r=k=>()=>{throw new Error(`the relay poke path must not reach RelayHost.${k}`)},i={fetch:(k,C)=>{if(JSON.parse(C?.body??"{}").type!=="relay_shape_subscribe")return Promise.resolve(new Response(void 0,{status:204}));const N=o[l];if(l+=1,N===void 0)throw new Error("the relay asked for more seeds than this fixture supplies");return Promise.resolve(Response.json(N))}},f={get:()=>i,getByName:()=>i,idFromName:k=>k},g={buildShapeDiff:r("buildShapeDiff"),computeOpLogShapeSeed:r("computeOpLogShapeSeed"),currentCdcEpoch:r("currentCdcEpoch"),deliverWhisperLocal:r("deliverWhisperLocal"),doName:()=>F(w,0),env:()=>({SHARD:f}),getWebSockets:()=>e.getSockets(),maskMetadata:r("maskMetadata"),nextPokeId:()=>(n+=1,`poke-${String(n)}`),readAttachment:k=>k.deserializeAttachment?.(),recordShapePokeFanout:()=>{},resolveShape:r("resolveShape"),rlsMetadata:r("rlsMetadata"),shardBinding:()=>"SHARD",shardJurisdiction:()=>{},sql:()=>t},y=I(g);if(y===void 0)throw new Error("expected a relay link for a `…::relay::N` name");return y},p=e=>new Request("https://relay.internal/_lunora/relay",{body:JSON.stringify(e),headers:{"content-type":"application/json"},method:"POST"}),s=async(e,t,o)=>{const n=await e.seedRelayShape(t,o,u,{identity:void 0,userId:void 0});if(n!=="ok")throw new Error(`seed failed: ${JSON.stringify(n)}`)},a=(e={})=>p({...u,checkpoint:20,epoch:"e1",fromCursor:10,rowsPatch:[{id:"r1",op:"upsert",value:{title:"hello"}}],type:"relay_shape_poke",...e});b("frames a poke as pokeStart → pokePart per shape → pokeEnd, under one poke id",async()=>{const{close:e,createSocket:t,host:o,readFrames:n,sockets:l}=m();try{const r=c(l,o.sql,[{cursor:10,epoch:"e1",frames:[]}]),i=h(l,t,"c-alice","s1");await s(r,i,"s1"),await r.handleControl(a());const g=(await n(i)).map(y=>JSON.parse(y));d(g.map(y=>y.type)).toStrictEqual(["pokeStart","pokePart","pokeEnd"]),d(new Set(g.map(y=>y.pokeId)).size).toBe(1),d(g[1]?.shapeId).toBe("s1"),d(g[2]?.checkpoint).toBe(20)}finally{e?.()}}),b("delivers a poke only to sockets whose cursor matches, and advances them past it",async()=>{const{close:e,createSocket:t,host:o,readFrames:n,sockets:l}=m();try{const r=c(l,o.sql,[{cursor:10,epoch:"e1",frames:[]},{cursor:7,epoch:"e1",frames:[]}]),i=h(l,t,"c-alice","s1"),f=h(l,t,"c-bob","s2");await s(r,i,"s1"),await s(r,f,"s2"),await r.handleControl(a());const g=await n(i);d(g.length).toBe(3);const y=await n(f);d(y.length).toBe(0),await r.handleControl(a());const k=await n(i);d(k.length).toBe(3)}finally{e?.()}}),b("skips a socket whose cursor matches under a different CDC epoch",async()=>{const{close:e,createSocket:t,host:o,readFrames:n,sockets:l}=m();try{const r=c(l,o.sql,[{cursor:10,epoch:"e1",frames:[]}]),i=h(l,t,"c-alice","s1");await s(r,i,"s1"),await r.handleControl(a({epoch:"e2"}));const f=await n(i);d(f.length).toBe(0),await r.handleControl(a());const g=await n(i);d(g.length).toBe(3)}finally{e?.()}})}),v("orderBy null placement",()=>{const w=[["a",void 0],["b",3],["c",void 0],["d",1],["e",void 0],["f",3],["g",2],["h",void 0]],u=[{nulls:"first",sort:"asc"},{nulls:"last",sort:"asc"},{nulls:"first",sort:"desc"},{nulls:"last",sort:"desc"}],h=({nulls:p,sort:s})=>{const a=new Map(w.map(([t],o)=>[t,o])),e=s==="asc"?1:-1;return w.toSorted(([t,o],[n,l])=>o!==l?o===void 0?p==="first"?-1:1:l===void 0?p==="first"?1:-1:(o-l)*e:((a.get(t)??0)-(a.get(n)??0))*e).map(([t])=>t)},c=p=>p.map(s=>String(s.label));b("pages every placement in threes with no row skipped or repeated",async()=>{const{close:p,host:s}=m();try{const a=s.sql,e=u.map((r,i)=>`items_${String(i)}`),t={label:S("string"),score:S("number",{notNull:!1})},o={tables:Object.fromEntries(e.map(r=>[r,{indexes:[{fields:["score"],name:"by_score"}],shape:t}]))};E(a,o);let n=17e11;const l=_({clock:()=>(n+=1e3,n),schema:o,sql:a});for(const r of e)for(const[i,f]of w)await l.insert(r,f===void 0?{label:i}:{label:i,score:f});for(const[r,i]of u.entries()){const f=e[r]??"",g=await l.findMany(f,{orderBy:[{score:i}]});d(c(g.page)).toStrictEqual(h(i));const y=[];let k;for(let C=0;C<w.length+2;C+=1){const B=await l.findMany(f,{cursor:k,limit:3,orderBy:[{score:i}]});if(y.push(...c(B.page)),B.isDone)break;k=B.continueCursor}d(y).toStrictEqual(h(i))}}finally{p?.()}})}),v("RLS identity under live subscription",()=>{const w="shard-a",u={args:{},name:"lobby-messages"},h={args:{},name:"my-orders"},c=s=>{const a=[],e=[],t={fetch:(l,r)=>(a.push(JSON.parse(r?.body??"{}")),Promise.resolve(new Response(void 0,{status:204})))},n=I({buildShapeDiff:()=>[{id:"r1",op:"upsert",value:{}}],computeOpLogShapeSeed:()=>({baseCheckpoint:void 0,cursor:10,epoch:"e1",reset:!0,rowsPatch:[]}),currentCdcEpoch:()=>"e1",deliverWhisperLocal:()=>0,doName:()=>w,env:()=>({SHARD:{get:()=>t,getByName:()=>t,idFromName:l=>l}}),getWebSockets:()=>[],maskMetadata:()=>({columns:[]}),nextPokeId:()=>"poke-1",readAttachment:()=>({}),recordShapePokeFanout:()=>{},resolveShape:(l,r,i)=>(e.push(i),l===h.name?{columns:["id"],effectiveWhere:{org:i?.identity?.org??"anonymous"},global:!1,table:"orders"}:{columns:["id"],effectiveWhere:{room:"lobby"},global:!1,table:"messages"}),rlsMetadata:()=>({policies:[]}),shardBinding:()=>"SHARD",shardJurisdiction:()=>{},sql:()=>s});if(n===void 0)throw new Error("expected an owner link for an un-suffixed DO name");return{owner:n,posts:a,resolvedUnder:e}},p=async(s,a)=>{await s.handleControl(new Request("https://owner.internal/_lunora/relay",{body:JSON.stringify({...a,connectionId:"c-alice",identity:{org:"acme"},relayIndex:0,subId:"s1",type:"relay_shape_subscribe",userId:"u1"}),headers:{"content-type":"application/json"},method:"POST"}))};b("seeds a subscriber under its own forwarded identity, never the anonymous one",async()=>{const{close:s,host:a}=m();try{const{owner:e,resolvedUnder:t}=c(a.sql);await p(e,h),d(t.some(o=>o?.userId==="u1"&&o.identity?.org==="acme")).toBe(!0)}finally{s?.()}}),b("routes an identity-scoped shape to a per-socket poke, not the cohort multicast",async()=>{const{close:s,host:a}=m();try{const{owner:e,posts:t}=c(a.sql);await p(e,h),t.length=0,await e.onFlush(new Set(["orders"]),20);const o=t.filter(n=>n.type==="relay_shape_poke");d(o.length).toBe(1),d(o[0]?.targetConnectionId).toBe("c-alice")}finally{s?.()}}),b("still multicasts an identity-blind shape to the whole cohort",async()=>{const{close:s,host:a}=m();try{const{owner:e,posts:t}=c(a.sql);await p(e,u),t.length=0,await e.onFlush(new Set(["messages"]),20);const o=t.filter(n=>n.type==="relay_shape_poke");d(o.length).toBe(1),d(o[0]?.targetConnectionId).toBeUndefined()}finally{s?.()}})})})};export{A as defineEngineContractSuite};
@@ -1,4 +1,4 @@
1
- import{LunoraError as T}from"@lunora/errors";import{sql as m}from"drizzle-orm";import{runDrizzle as S}from"./runDrizzle-RC09zZrh.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-DE8zhD1x.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-RC09zZrh.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-DzUChRJ-.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-CwEMKX-0.mjs";import{selectShapeRows as m}from"./selectShapeMembers-BCfKypfN.mjs";import{diffExternalSource as g,projectExternalSourceRow as l}from"./diffExternalSource-B0FZlDoL.mjs";import{stableStringify as d}from"@lunora/wire";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(n,c)&&r.push({id:c,op:"delete",seq:0,table:n,ts:0});continue}const u=await t.get(n,c);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-oPp25hdi.mjs";import{selectShapeRows as m}from"./selectShapeMembers-BCfKypfN.mjs";import{diffExternalSource as g,projectExternalSourceRow as l}from"./diffExternalSource-B0FZlDoL.mjs";import{stableStringify as d}from"@lunora/wire";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(n,c)&&r.push({id:c,op:"delete",seq:0,table:n,ts:0});continue}const u=await t.get(n,c);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,4 +1,4 @@
1
- import{LunoraError as U}from"@lunora/errors";import{f as M,S as X}from"./fts-companion-CA8mLJWq.mjs";import{sql as t}from"drizzle-orm";import{aggregateTableName as h}from"./aggregateTableName-B_CtIQCS.mjs";import{backfillSearchIndexesForTable as y}from"./backfillAggregateIndexes-BN0NwXQk.mjs";import{migrateCdcLog as b,migrateCdcMeta as k}from"./CDC_LOG_TABLE-CwEMKX-0.mjs";import{migrateClientWatermark as w}from"./CLIENT_WATERMARK_TABLE-De7z_OHV.mjs";import{migrateCommitSeq as B}from"./COMMIT_SEQ_FIELD-Da1DjGqo.mjs";import{migrateCompanionState as G}from"./CompanionMemo-BXU5vfak.mjs";import{migrateGlobalShapeSnapshot as P}from"./GLOBAL_SHAPE_SNAPSHOT_TABLE-Bb6-aZuH.mjs";import{migrateIdempotency as Y}from"./IDEMPOTENCY_TABLE-COrgeP3O.mjs";import{m as v}from"./ctx-db-relay-shapes-DV0VO4HG.mjs";import{migrateScheduleOutbox as j}from"./SCHEDULE_OUTBOX_TABLE-DcZI7Yhl.mjs";import{m as W}from"./ctx-db-search-state-FjgzTFok.mjs";import{migrateShapePokeCursor as H}from"./SHAPE_POKE_CURSOR_TABLE-BGvY3sFI.mjs";import{runDrizzle as d,runAll as K}from"./runDrizzle-RC09zZrh.mjs";import{D as V,d as I,e as g,t as z,i as Z,g as J,a as Q,b as q,A as p}from"./do-sql-BWrJQAOh.mjs";import{renderSql as R}from"./WORKERD_SQLITE_LIMITS-B_4w7tzY.mjs";import{migrateDurableStreams as ee}from"./appendStreamChunk-BZYgGE9Y.mjs";import{rankTableName as N,sortColumnName as te}from"./RANK_TIEBREAK-D3ye2GsL.mjs";import{migrateReactorState as re}from"./REACTOR_STATE_TABLE-D2Mn204f.mjs";import{recordSchemaVersion as ne}from"./SCHEMA_HISTORY_MAX_VERSIONS-CEwFjj-O.mjs";import{ttlIndexColumns as oe}from"./nextTtlExpiry-DhKO_OpO.mjs";const u=t`_creationTime, id`,x="__by_creation",ie="__ttl",ae=`, ${R("sqlite",u).sql})`,l="__lunora_framework_indexes",T=e=>e.replaceAll(/[A-Z]/gu,r=>r.toLowerCase());class D extends U{}const $=(e,r,n,a,i,o)=>{const s=t.join(i.map(m=>t`${m} IS NOT NULL`),t` AND `);if(d(e,t`SELECT 1 FROM ${t.identifier(n)} WHERE ${s} GROUP BY ${a} HAVING COUNT(*) > 1 LIMIT 1`).toArray().length>0)throw new D("INTERNAL",`unique index "${r}" on "${n}" ${o}: existing rows are duplicates under it. De-duplicate the table with a data migration first; the previous index is left in place.`)},L=(e,r,n,a,i,o)=>{const c=d(e,t`SELECT sql FROM sqlite_master WHERE type = 'index' AND name = ${r} COLLATE NOCASE AND tbl_name = ${n} COLLATE NOCASE`).toArray()[0]?.sql;if(c==null)return;const m=f=>{const A=f.indexOf("(");return A===-1?void 0:f.slice(A,f.lastIndexOf(")")+1)},E=m(R("sqlite",I(r,n,a,i)).sql),_=m(c);E===void 0||_===void 0||E===_||(i&&$(e,r,n,a,o,"cannot be re-created with its new column list"),d(e,t`DROP INDEX IF EXISTS ${t.identifier(r)}`))},se=(e,r,n)=>d(e,t`SELECT 1 FROM sqlite_master WHERE type = 'index' AND name = ${r} COLLATE NOCASE AND tbl_name = ${n} COLLATE NOCASE LIMIT 1`).toArray().length>0,O=(e,r,n,a,i,o)=>{i&&!se(e,r,n)&&$(e,r,n,a,o,"cannot be created"),d(e,I(r,n,a,i))},C=(e,r)=>{try{r()}catch(n){if(e===void 0||!(n instanceof D))throw n;e.push(n.message)}},de=(e,r,n)=>T(r).startsWith(`${T(e)}_`)&&T(r)!==T(`${e}${x}`)&&n!==null&&(n.includes("json_extract(")||n.trimEnd().endsWith(ae)),S=(e,r,n)=>{d(e,t`INSERT OR IGNORE INTO ${t.identifier(l)} (name, table_name) VALUES (${r}, ${n})`)},ce=(e,r)=>{const n=d(e,t`SELECT 1 FROM sqlite_master WHERE type = 'table' AND name = ${l} COLLATE NOCASE`).toArray().length>0;if(d(e,t`CREATE TABLE IF NOT EXISTS ${t.identifier(l)} (name TEXT PRIMARY KEY COLLATE NOCASE, table_name TEXT NOT NULL)`),!n)for(const a of r){const i=d(e,t`SELECT name, sql FROM sqlite_master WHERE type = 'index' AND tbl_name = ${a} COLLATE NOCASE AND sql IS NOT NULL`).toArray();for(const{name:o,sql:s}of i)de(a,o,s)&&S(e,o,a)}},me=(e,r,n)=>{const a=new Set([...n].map(o=>T(o))),i=d(e,t`SELECT "l"."name" FROM ${t.identifier(l)} AS "l" WHERE "l"."table_name" = ${r} COLLATE NOCASE`).toArray();for(const{name:o}of i)a.has(T(o))||(d(e,t`DROP INDEX IF EXISTS ${t.identifier(o)}`),d(e,t`DELETE FROM ${t.identifier(l)} WHERE ${t.identifier(l)}."name" = ${o}`))},fe=(e,r,n,a)=>{const i=`${r}${ie}`,o=new Set([...a].map(c=>T(c)));if(n.ttlPolicy===void 0||o.has(T(i)))return;const s=oe(n.ttlPolicy.field,n.softDeleteMode?.field);a.add(i);try{L(e,i,r,s,!1,[]),d(e,I(i,r,s,!1)),S(e,i,r)}catch{}},Ee=(e,r,n,a)=>{const i=new Set;for(const o of n.indexes){const s=`${r}_${o.name}`,c=o.unique??!1,m=o.fields.map(f=>g(f)),E=t.join(m,t`, `),_=c?E:t`${E}, ${u}`;i.add(s),C(a,()=>{L(e,s,r,_,c,m),O(e,s,r,_,c,m),S(e,s,r)})}for(const[o,s]of z(n)){if(!s.unique)continue;const c=g(o),m=`${r}_unique_${o}`;i.add(m),C(a,()=>{L(e,m,r,c,!0,[c]),O(e,m,r,c,!0,[c]),S(e,m,r)})}fe(e,r,n,i),me(e,r,i)},_e=(e,r,n)=>{if(!(!n.searchIndexes||n.searchIndexes.length===0||!Z(e))){for(const a of n.searchIndexes)K(e,M(X(r,a.name)));y(e,r,n)}},Te=(e,r,n)=>{if(n.geoIndexes)for(const a of n.geoIndexes){const i=J(r,a.name);d(e,t`CREATE TABLE IF NOT EXISTS ${t.identifier(i)} (${t.identifier("__id__")} TEXT PRIMARY KEY, ${t.identifier("__geohash__")} TEXT NOT NULL, ${t.identifier("__lat__")} REAL NOT NULL, ${t.identifier("__lng__")} REAL NOT NULL)`);const o=`${r}__geo_${a.name}__btree`;d(e,I(o,i,t`${t.identifier("__geohash__")} ASC, ${t.identifier("__id__")} ASC`,!1))}},Ae=(e,r,n)=>{if(n.aggregateIndexes)for(const a of n.aggregateIndexes){const i=h(r,a.name);d(e,t`CREATE TABLE IF NOT EXISTS ${t.identifier(i)} (${Q} TEXT PRIMARY KEY, ${q} REAL, ${p} INTEGER NOT NULL DEFAULT 0)`),d(e,t`PRAGMA table_info(${t.identifier(i)})`).toArray().some(s=>s.name==="__count__")||d(e,t`ALTER TABLE ${t.identifier(i)} ADD COLUMN ${p} INTEGER NOT NULL DEFAULT 0`)}},le=(e,r,n)=>{const a=d(e,t`PRAGMA table_info(${t.identifier(r)})`).toArray().map(i=>i.name).filter(i=>i.startsWith("__sort_k"));a.length>0&&(a.length!==n.length||a.some((i,o)=>i!==n[o]))&&d(e,t`DROP TABLE ${t.identifier(r)}`)},Ie=(e,r,n)=>{if(n.rankIndexes)for(const a of n.rankIndexes){const i=N(r,a.name),o=a.sortBy.map((f,A)=>te(A)),s=o.map(f=>t`${t.identifier(f)} BLOB`),c=s.length>0?t`, ${t.join(s,t`, `)}`:t``;le(e,i,o),d(e,t`CREATE TABLE IF NOT EXISTS ${t.identifier(i)} (${t.identifier("__id__")} TEXT PRIMARY KEY, ${t.identifier("__partition__")} TEXT NOT NULL${c})`);const m=[t`${t.identifier("__partition__")} ASC`];for(const[f,A]of o.entries()){const F=a.sortBy[f]?.direction;m.push(t`${t.identifier(A)} ${t.raw(F==="desc"?"DESC":"ASC")}`)}m.push(t`${t.identifier("__id__")} ASC`);const E=`${r}__rank_${a.name}__btree`,_=t.join(m,t`, `);L(e,E,i,_,!1,[]),d(e,I(E,i,_,!1))}},Pe=(e,r,n={})=>{const a=n.deferBlockedUniqueIndexes?[]:void 0;n.schemaSnapshot!==void 0&&ne(e,n.schemaSnapshot.hash,n.schemaSnapshot.json),W(e),ce(e,Object.entries(r.tables).filter(([,o])=>o.shardMode?.kind!=="global").map(([o])=>o));const i=[];for(const[o,s]of Object.entries(r.tables))s.shardMode?.kind!=="global"&&(d(e,t`CREATE TABLE IF NOT EXISTS ${t.identifier(o)} (
1
+ import{LunoraError as U}from"@lunora/errors";import{f as M,S as X}from"./fts-companion-CA8mLJWq.mjs";import{sql as t}from"drizzle-orm";import{aggregateTableName as h}from"./aggregateTableName-B_CtIQCS.mjs";import{backfillSearchIndexesForTable as y}from"./backfillAggregateIndexes-BN0NwXQk.mjs";import{migrateCdcLog as b,migrateCdcMeta as k}from"./CDC_LOG_TABLE-oPp25hdi.mjs";import{migrateClientWatermark as w}from"./CLIENT_WATERMARK_TABLE-De7z_OHV.mjs";import{migrateCommitSeq as B}from"./COMMIT_SEQ_FIELD-Da1DjGqo.mjs";import{migrateCompanionState as G}from"./CompanionMemo-BXU5vfak.mjs";import{migrateGlobalShapeSnapshot as P}from"./GLOBAL_SHAPE_SNAPSHOT_TABLE-Bb6-aZuH.mjs";import{migrateIdempotency as Y}from"./IDEMPOTENCY_TABLE-COrgeP3O.mjs";import{m as v}from"./ctx-db-relay-shapes-DV0VO4HG.mjs";import{migrateScheduleOutbox as j}from"./SCHEDULE_OUTBOX_TABLE-DcZI7Yhl.mjs";import{m as W}from"./ctx-db-search-state-FjgzTFok.mjs";import{migrateShapePokeCursor as H}from"./SHAPE_POKE_CURSOR_TABLE-BGvY3sFI.mjs";import{runDrizzle as d,runAll as K}from"./runDrizzle-RC09zZrh.mjs";import{D as V,d as I,e as g,t as z,i as Z,g as J,a as Q,b as q,A as p}from"./do-sql-BWrJQAOh.mjs";import{renderSql as R}from"./WORKERD_SQLITE_LIMITS-B_4w7tzY.mjs";import{migrateDurableStreams as ee}from"./appendStreamChunk-BZYgGE9Y.mjs";import{rankTableName as N,sortColumnName as te}from"./RANK_TIEBREAK-D3ye2GsL.mjs";import{migrateReactorState as re}from"./REACTOR_STATE_TABLE-D2Mn204f.mjs";import{recordSchemaVersion as ne}from"./SCHEMA_HISTORY_MAX_VERSIONS-CEwFjj-O.mjs";import{ttlIndexColumns as oe}from"./nextTtlExpiry-DhKO_OpO.mjs";const u=t`_creationTime, id`,x="__by_creation",ie="__ttl",ae=`, ${R("sqlite",u).sql})`,l="__lunora_framework_indexes",T=e=>e.replaceAll(/[A-Z]/gu,r=>r.toLowerCase());class D extends U{}const $=(e,r,n,a,i,o)=>{const s=t.join(i.map(m=>t`${m} IS NOT NULL`),t` AND `);if(d(e,t`SELECT 1 FROM ${t.identifier(n)} WHERE ${s} GROUP BY ${a} HAVING COUNT(*) > 1 LIMIT 1`).toArray().length>0)throw new D("INTERNAL",`unique index "${r}" on "${n}" ${o}: existing rows are duplicates under it. De-duplicate the table with a data migration first; the previous index is left in place.`)},L=(e,r,n,a,i,o)=>{const c=d(e,t`SELECT sql FROM sqlite_master WHERE type = 'index' AND name = ${r} COLLATE NOCASE AND tbl_name = ${n} COLLATE NOCASE`).toArray()[0]?.sql;if(c==null)return;const m=f=>{const A=f.indexOf("(");return A===-1?void 0:f.slice(A,f.lastIndexOf(")")+1)},E=m(R("sqlite",I(r,n,a,i)).sql),_=m(c);E===void 0||_===void 0||E===_||(i&&$(e,r,n,a,o,"cannot be re-created with its new column list"),d(e,t`DROP INDEX IF EXISTS ${t.identifier(r)}`))},se=(e,r,n)=>d(e,t`SELECT 1 FROM sqlite_master WHERE type = 'index' AND name = ${r} COLLATE NOCASE AND tbl_name = ${n} COLLATE NOCASE LIMIT 1`).toArray().length>0,O=(e,r,n,a,i,o)=>{i&&!se(e,r,n)&&$(e,r,n,a,o,"cannot be created"),d(e,I(r,n,a,i))},C=(e,r)=>{try{r()}catch(n){if(e===void 0||!(n instanceof D))throw n;e.push(n.message)}},de=(e,r,n)=>T(r).startsWith(`${T(e)}_`)&&T(r)!==T(`${e}${x}`)&&n!==null&&(n.includes("json_extract(")||n.trimEnd().endsWith(ae)),S=(e,r,n)=>{d(e,t`INSERT OR IGNORE INTO ${t.identifier(l)} (name, table_name) VALUES (${r}, ${n})`)},ce=(e,r)=>{const n=d(e,t`SELECT 1 FROM sqlite_master WHERE type = 'table' AND name = ${l} COLLATE NOCASE`).toArray().length>0;if(d(e,t`CREATE TABLE IF NOT EXISTS ${t.identifier(l)} (name TEXT PRIMARY KEY COLLATE NOCASE, table_name TEXT NOT NULL)`),!n)for(const a of r){const i=d(e,t`SELECT name, sql FROM sqlite_master WHERE type = 'index' AND tbl_name = ${a} COLLATE NOCASE AND sql IS NOT NULL`).toArray();for(const{name:o,sql:s}of i)de(a,o,s)&&S(e,o,a)}},me=(e,r,n)=>{const a=new Set([...n].map(o=>T(o))),i=d(e,t`SELECT "l"."name" FROM ${t.identifier(l)} AS "l" WHERE "l"."table_name" = ${r} COLLATE NOCASE`).toArray();for(const{name:o}of i)a.has(T(o))||(d(e,t`DROP INDEX IF EXISTS ${t.identifier(o)}`),d(e,t`DELETE FROM ${t.identifier(l)} WHERE ${t.identifier(l)}."name" = ${o}`))},fe=(e,r,n,a)=>{const i=`${r}${ie}`,o=new Set([...a].map(c=>T(c)));if(n.ttlPolicy===void 0||o.has(T(i)))return;const s=oe(n.ttlPolicy.field,n.softDeleteMode?.field);a.add(i);try{L(e,i,r,s,!1,[]),d(e,I(i,r,s,!1)),S(e,i,r)}catch{}},Ee=(e,r,n,a)=>{const i=new Set;for(const o of n.indexes){const s=`${r}_${o.name}`,c=o.unique??!1,m=o.fields.map(f=>g(f)),E=t.join(m,t`, `),_=c?E:t`${E}, ${u}`;i.add(s),C(a,()=>{L(e,s,r,_,c,m),O(e,s,r,_,c,m),S(e,s,r)})}for(const[o,s]of z(n)){if(!s.unique)continue;const c=g(o),m=`${r}_unique_${o}`;i.add(m),C(a,()=>{L(e,m,r,c,!0,[c]),O(e,m,r,c,!0,[c]),S(e,m,r)})}fe(e,r,n,i),me(e,r,i)},_e=(e,r,n)=>{if(!(!n.searchIndexes||n.searchIndexes.length===0||!Z(e))){for(const a of n.searchIndexes)K(e,M(X(r,a.name)));y(e,r,n)}},Te=(e,r,n)=>{if(n.geoIndexes)for(const a of n.geoIndexes){const i=J(r,a.name);d(e,t`CREATE TABLE IF NOT EXISTS ${t.identifier(i)} (${t.identifier("__id__")} TEXT PRIMARY KEY, ${t.identifier("__geohash__")} TEXT NOT NULL, ${t.identifier("__lat__")} REAL NOT NULL, ${t.identifier("__lng__")} REAL NOT NULL)`);const o=`${r}__geo_${a.name}__btree`;d(e,I(o,i,t`${t.identifier("__geohash__")} ASC, ${t.identifier("__id__")} ASC`,!1))}},Ae=(e,r,n)=>{if(n.aggregateIndexes)for(const a of n.aggregateIndexes){const i=h(r,a.name);d(e,t`CREATE TABLE IF NOT EXISTS ${t.identifier(i)} (${Q} TEXT PRIMARY KEY, ${q} REAL, ${p} INTEGER NOT NULL DEFAULT 0)`),d(e,t`PRAGMA table_info(${t.identifier(i)})`).toArray().some(s=>s.name==="__count__")||d(e,t`ALTER TABLE ${t.identifier(i)} ADD COLUMN ${p} INTEGER NOT NULL DEFAULT 0`)}},le=(e,r,n)=>{const a=d(e,t`PRAGMA table_info(${t.identifier(r)})`).toArray().map(i=>i.name).filter(i=>i.startsWith("__sort_k"));a.length>0&&(a.length!==n.length||a.some((i,o)=>i!==n[o]))&&d(e,t`DROP TABLE ${t.identifier(r)}`)},Ie=(e,r,n)=>{if(n.rankIndexes)for(const a of n.rankIndexes){const i=N(r,a.name),o=a.sortBy.map((f,A)=>te(A)),s=o.map(f=>t`${t.identifier(f)} BLOB`),c=s.length>0?t`, ${t.join(s,t`, `)}`:t``;le(e,i,o),d(e,t`CREATE TABLE IF NOT EXISTS ${t.identifier(i)} (${t.identifier("__id__")} TEXT PRIMARY KEY, ${t.identifier("__partition__")} TEXT NOT NULL${c})`);const m=[t`${t.identifier("__partition__")} ASC`];for(const[f,A]of o.entries()){const F=a.sortBy[f]?.direction;m.push(t`${t.identifier(A)} ${t.raw(F==="desc"?"DESC":"ASC")}`)}m.push(t`${t.identifier("__id__")} ASC`);const E=`${r}__rank_${a.name}__btree`,_=t.join(m,t`, `);L(e,E,i,_,!1,[]),d(e,I(E,i,_,!1))}},Pe=(e,r,n={})=>{const a=n.deferBlockedUniqueIndexes?[]:void 0;n.schemaSnapshot!==void 0&&ne(e,n.schemaSnapshot.hash,n.schemaSnapshot.json),W(e),ce(e,Object.entries(r.tables).filter(([,o])=>o.shardMode?.kind!=="global").map(([o])=>o));const i=[];for(const[o,s]of Object.entries(r.tables))s.shardMode?.kind!=="global"&&(d(e,t`CREATE TABLE IF NOT EXISTS ${t.identifier(o)} (
2
2
  id TEXT PRIMARY KEY,
3
3
  _creationTime REAL NOT NULL,
4
4
  ${t.identifier(V)} TEXT NOT NULL
@@ -0,0 +1 @@
1
+ import{RELAY_SIGNATURE_HEADER as u,siblingSecretOf as y,signSiblingBody as a,verifySiblingBody as g}from"./RELAY_SIGNATURE_HEADER-DNzVQxbZ.mjs";const r=t=>{if(t===null||typeof t!="object")return;const o=t;return typeof o.idFromName=="function"&&typeof o.get=="function"?o:void 0},d=(t,o,n)=>{const i=r(t);if(i===void 0)return;const e=n===void 0?i:r(i.jurisdiction?.(n));if(e!==void 0)return typeof e.getByName=="function"?e.getByName(o):e.get(e.idFromName(o))},c=(t,o,n,i)=>o===void 0?void 0:d(t?.[o],n,i);export{u as RELAY_SIGNATURE_HEADER,y as siblingSecretOf,c as siblingStub,a as signSiblingBody,d as stubByName,g as verifySiblingBody};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@lunora/shard-engine",
3
- "version": "1.0.0-alpha.162",
3
+ "version": "1.0.0-alpha.164",
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,8 +0,0 @@
1
- import{toErrorBody as Y,LunoraError as G}from"@lunora/errors";import{encodeWire as q,stableWireKey as _,decodeWire as g}from"@lunora/wire";import{sql as u}from"drizzle-orm";import{runDrizzle as m}from"./runDrizzle-RC09zZrh.mjs";import{WORKERD_SQLITE_LIMITS as W}from"./WORKERD_SQLITE_LIMITS-B_4w7tzY.mjs";import{d as $,w as I,a as A,m as B,r as K,b as H,c as j}from"./ctx-db-relay-shapes-DV0VO4HG.mjs";import{envPositiveInt as v}from"./envOptionalPositiveInt-D2pY-c64.mjs";import{DEFAULT_PROMOTION_THRESHOLDS as T,nextPromotionState as X,shapeRoutingKey as E,relayProxyKey as w,relayName as M,parseRelayName as z,clampPromotionThresholds as V}from"./DEFAULT_PROMOTION_THRESHOLDS-B3pRMuqb.mjs";import{encodeRowsPatch as J,buildPokeFrames as D}from"./buildPokeFrames-WR-hp0mX.mjs";import{verifySiblingBody as Q,RELAY_SIGNATURE_HEADER as L,siblingStub as Z,siblingSecretOf as ee,signSiblingBody as te}from"./RELAY_SIGNATURE_HEADER-C_P73AOx.mjs";import{awaitWsDrain as se,trySendFrame as C}from"./awaitWsDrain-e88vUNdj.mjs";const S="__lunora_relay_memos",re=i=>{m(i,u`CREATE TABLE IF NOT EXISTS ${u.identifier(S)} (
2
- connection_id TEXT NOT NULL,
3
- sub_id TEXT NOT NULL,
4
- cursor INTEGER NOT NULL,
5
- epoch TEXT,
6
- PRIMARY KEY (connection_id, sub_id)
7
- )`)},oe=i=>{const e=m(i,u`SELECT connection_id, sub_id, cursor, epoch FROM ${u.identifier(S)}`).toArray(),s=new Map;for(const t of e){let r=s.get(t.connection_id);r===void 0&&(r=new Map,s.set(t.connection_id,r)),r.set(t.sub_id,{cursor:Number(t.cursor),epoch:t.epoch??void 0})}return s},ne=4,N=(i,e)=>{const s=Math.floor(W.boundParams/ne);for(let t=0;t<e.length;t+=s){const r=e.slice(t,t+s),o=u.join(r.map(n=>u`(${n.connectionId}, ${n.subId}, ${n.cursor}, ${n.epoch??null})`),u`, `);m(i,u`INSERT INTO ${u.identifier(S)} (connection_id, sub_id, cursor, epoch) VALUES ${o}
8
- ON CONFLICT(connection_id, sub_id) DO UPDATE SET cursor = excluded.cursor, epoch = excluded.epoch`)}},ae=(i,e,s)=>{m(i,u`DELETE FROM ${u.identifier(S)} WHERE connection_id = ${e} AND sub_id = ${s}`)},ie=(i,e)=>{m(i,u`DELETE FROM ${u.identifier(S)} WHERE connection_id = ${e}`)},le=i=>{m(i,u`DELETE FROM ${u.identifier(S)}`)},ce=2,he=i=>{const e=i?.LUNORA_WS_BEARER;return typeof e=="string"&&e.length>0},de=8,ue=2e3,ye=2e3,O=async i=>{let e;const s=new Promise(t=>{e=setTimeout(()=>{t(void 0)},ye)});return Promise.race([i,s]).finally(()=>{clearTimeout(e)})},b={},pe=i=>{throw new G("INTERNAL",`unhandled relay frame: ${JSON.stringify(i)}`)},fe=(i,e)=>i===void 0||i.epoch!==e.epoch?!1:i.cursor>=e.fromCursor&&i.cursor<e.checkpoint,k=i=>Response.json(i,{headers:{"content-type":"application/json"}}),me=new Set(["relay_attach","relay_detach","relay_room_event","relay_shape_unsubscribe"]),Se=new Set(["relay_attach","relay_shape_subscribe"]),Re=(i,e)=>{let s;try{s=JSON.parse(i)}catch{return}if(typeof s!="object"||s===null)return;const t=s,{relayIndex:r}=t;if(r===void 0?!me.has(t.type):Number.isSafeInteger(r)&&r>=0&&(!Se.has(t.type)||r<e))return t},f=()=>new Response(null,{status:204}),x=(i,e)=>{i.then(async s=>s===e?void 0:s?.body?.cancel()).catch(()=>{})},_e=3e4,F=410,P=()=>new Response("stale relay frame",{status:409}),ve=i=>Math.max(Date.now()*1e3,i+1);class U{constructor(e,s){this.host=e,this.roleId=s}host;roleId;lastSequence=0;async handleControl(e){let s;try{s=await e.text()}catch{return new Response("bad request",{status:400})}if(!await Q(this.host.env(),e.headers.get(L),s))return new Response("forbidden",{status:403});const t=Re(s,this.maxRelays());if(t===void 0)return new Response("bad request",{status:400});if((t.type==="relay_frame"||t.type==="relay_live_frame"||t.type==="relay_shape_poke")&&this.refusesAsIdle())return new Response(void 0,{status:F});switch(t.type){case"relay_attach":return this.onAttach(t.relayIndex,t.seq)?f():P();case"relay_detach":return this.onDetach(t.relayIndex,t.seq)?f():P();case"relay_frame":{const{exceptConnectionId:r}=t,o=r===void 0?void 0:this.host.getWebSockets().find(n=>this.host.readAttachment(n).connectionId===r);return this.host.deliverWhisperLocal(t.topic,t.frame,o),await this.onWhisperFrame(t),f()}case"relay_live_control":return this.onLiveControl(t.control);case"relay_live_frame":return this.host.deliverLiveLocal(t.topic,t.key,t.frame),f();case"relay_room_event":return k(await this.host.relayRoomEvent(t));case"relay_shape_poke":{const r=this.host.getWebSockets().length,o=Date.now(),{delivered:n,matched:a}=this.onShapePoke({...t,args:g(t.args)});return this.host.recordShapePokeFanout(r,n,Date.now()-o),n<a?Response.json({delivered:n,matched:a},{status:503}):f()}case"relay_shape_subscribe":return k(this.onShapeSubscribe({...t,args:g(t.args)}));case"relay_shape_unsubscribe":return this.onShapeUnsubscribe(t),f();default:return pe(t)}}maxRelays(){return v(this.host.env(),"LUNORA_MAX_RELAYS",de)}canAddressSiblings(){return this.siblingStub(this.roleId.ownerKey)!==void 0}isAdmitted(e){return this.host.readAttachment(e).authenticated!==!1}siblingStub(e){return Z(this.host.env(),this.bindingName(),e,this.host.shardJurisdiction())}bindingName(){return this.host.shardBinding()}nextRelaySeq(){return this.lastSequence=ve(this.lastSequence),this.lastSequence}async postRelayMessage(e,s){await this.requestRelayMessage(e,s)}async requestRelayMessage(e,s){const t=this.siblingStub(e);if(t===void 0)return;const r=JSON.stringify(s),o={"content-type":"application/json","x-lunora-shard-binding":this.host.shardBinding()??""},n=ee(this.host.env());n!==void 0&&(o[L]=await te(n,r));try{return await t.fetch("https://relay.internal/_lunora/relay",{body:r,headers:o,method:"POST"})}catch{return}}}class Ee extends U{shapeUniformCache=new Map;relaySetCache;liveGrantRelayCache;relayTablesReady=!1;relaySeqMarks=new Map;pendingSubscribeRelays=new Map;registryCache;recordedBinding;promotionState="owned";constructor(e,s){super(e,{ownerKey:s})}async forwardWhisper(e,s,t){if(!this.canAddressSiblings())return;const r=this.ownerRelaySet();r.size!==0&&await Promise.all([...r].map(o=>this.forwardToRelay(o,{exceptConnectionId:t,frame:s,topic:e,type:"relay_frame"})))}forwardLiveControl(e){if(!this.canAddressSiblings())return Promise.resolve(void 0);const s={...e,seq:this.nextRelaySeq()},t=s.action==="unsubscribe"?new Set([...this.liveGrantRelaySet(),...this.pendingSubscribeRelays.keys()]):this.ownerRelaySet();if(t.size===0)return Promise.resolve(void 0);const r=[...t].map(o=>this.liveControlAnswer(o,s));return Promise.any(r.map(async o=>{const n=await o;if(n===void 0||n.status===404)throw new Error("relay does not hold the socket");return n})).catch(()=>{}).then(o=>{for(const n of r)x(n,o);return o})}async forwardLiveFrame(e,s,t){if(!this.canAddressSiblings())return;const r=this.liveGrantRelaySet();r.size!==0&&await Promise.all([...r].map(o=>this.forwardToRelay(o,{frame:t,key:s,topic:e,type:"relay_live_frame"})))}async onFlush(e,s){this.canAddressSiblings()&&await Promise.all([this.multicastShapePokes(e,s),this.proxyShapePokes(e,s)])}seedRelayShape(){return Promise.resolve(void 0)}announce(){return Promise.resolve(!0)}announceDrain(){return Promise.resolve()}releaseRelayShapes(){return Promise.resolve()}relayCount(){const e=this.host.getWebSockets(),s=he(this.host.env())?e.filter(n=>this.isAdmitted(n)).length:e.length,t=v(this.host.env(),"LUNORA_RELAY_THRESHOLD",T.tUp),r=v(this.host.env(),"LUNORA_RELAY_COLLAPSE_THRESHOLD",T.tDown);if(this.promotionState=X(this.promotionState,s,V(t,r)),this.promotionState==="owned")return 0;const o=v(this.host.env(),"LUNORA_RELAY_FAN",ce);return Math.min(this.maxRelays(),Math.max(1,o))}minShapeCursor(){const{cohort:e,proxies:s}=this.relayShapes();let t;for(const r of[...e.values(),...s.values()])t=t===void 0?r.cursor:Math.min(t,r.cursor);return t}isShapeRelayUniform(e,s){const t=E(e,s),r=this.shapeUniformCache.get(t);if(r!==void 0)return r;const o=this.probeShapeRelayUniform(e,s);return this.shapeUniformCache.set(t,o),o}onShapeUnsubscribe(e){const{proxies:s}=this.relayShapes(),t=e.subId===void 0?void 0:w(e.relayIndex,e.connectionId,e.subId);for(const[r,o]of s)o.relayIndex!==e.relayIndex||o.connectionId!==e.connectionId||(t===void 0||r===t)&&s.delete(r);$(this.host.sql(),e.relayIndex,e.connectionId,e.subId)}onAttach(e,s){return this.recordRelaySeq(e,s),this.addRelayToSet(e),!0}onDetach(e,s){return this.acceptRelaySeq(e,s)?(this.removeRelayFromSet(e),!0):!1}refusesAsIdle(){return!1}onLiveControl(e){return this.host.liveControl(e)}async onWhisperFrame(e){await Promise.all([...this.ownerRelaySet()].filter(s=>s!==e.originRelay).map(s=>this.forwardToRelay(s,{frame:e.frame,topic:e.topic,type:"relay_frame"})))}onShapeSubscribe(e){return this.buildShapeSeedFrames(e)}onShapePoke(){return{delivered:0,matched:0}}relaySeqMark(e){if(this.relaySeqMarks.has(e))return this.relaySeqMarks.get(e);this.ensureRelayTables();const[s]=this.host.sql().exec("SELECT seq FROM __lunora_relay_seqs WHERE idx = ?",e).toArray(),t=s===void 0?void 0:Number(s.seq);return this.relaySeqMarks.set(e,t),t}recordRelaySeq(e,s){if(s===void 0)return;const t=this.relaySeqMark(e);(t===void 0||s>t)&&(this.host.sql().exec("INSERT OR REPLACE INTO __lunora_relay_seqs (idx, seq) VALUES (?, ?)",e,s),this.relaySeqMarks.set(e,s))}acceptRelaySeq(e,s){if(s===void 0)return!0;const t=this.relaySeqMark(e);return t!==void 0&&s<t?!1:(this.recordRelaySeq(e,s),!0)}buildShapePoke(e,s,t,r,o){if(e.table!==void 0&&!t.has(e.table))return;let n;try{n=this.host.resolveShape(e.name,e.args,s)}catch{return}if(n===void 0||n.global===!0)return;const a=e;if(a.table=n.table,!t.has(n.table))return;const c=a.cursor,l=this.host.buildShapeDiff(n,c,r);if(l.length!==0)return a.cursor=r,I(this.host.sql(),a.key,r),{args:q(e.args),checkpoint:r,epoch:o,fromCursor:c,name:e.name,rowsPatch:J(l),type:"relay_shape_poke"}}async multicastShapePokes(e,s){const t=this.ownerRelaySet();if(t.size===0)return;const{cohort:r}=this.relayShapes();if(r.size===0)return;const o=this.host.currentCdcEpoch(),n=[];for(const a of r.values()){const c=this.buildShapePoke(a,b,e,s,o);c&&n.push(this.multicastToRelays(t,c,a))}await Promise.all(n)}async multicastToRelays(e,s,t){(await Promise.all([...e].map(async o=>{const{dropped:n,response:a}=await this.requestDroppingIdle(o,s);return n||a?.ok===!0}))).includes(!1)&&this.rewindShapeCursor(t,s.fromCursor)}async proxyShapePokes(e,s){if(this.ownerRelaySet().size===0)return;const{proxies:t}=this.relayShapes();if(t.size===0)return;const r=this.host.currentCdcEpoch(),o=[];for(const n of t.values()){const a=this.buildShapePoke(n,n.identity,e,s,r);a&&o.push(this.proxyToRelay(a,n))}await Promise.all(o)}async proxyToRelay(e,s){const{dropped:t,response:r}=await this.requestDroppingIdle(s.relayIndex,{...e,targetConnectionId:s.connectionId});!t&&r?.ok!==!0&&this.rewindShapeCursor(s,e.fromCursor)}buildShapeSeedFrames(e){const s={identity:e.identity,userId:e.userId};let t;try{t=this.host.resolveShape(e.name,e.args,s)}catch(h){const{body:p}=Y(h,{fallbackCode:"SHAPE_RESOLVE_FAILED",redactedMessage:"shape resolution failed"});return{error:{code:p.code,message:p.message}}}if(t===void 0||t.global===!0)return{error:{code:"SHAPE_NOT_FOUND",message:`shape not relayable: ${e.name}`}};e.relayIndex!==void 0&&this.addRelayToSet(e.relayIndex);const{baseCheckpoint:r,cursor:o,epoch:n,reset:a,rowsPatch:c}=this.host.computeOpLogShapeSeed({args:e.args,name:e.name,sinceEpoch:e.sinceEpoch,sinceSeq:e.sinceSeq},t);let l=o;const{cohort:d,proxies:R}=this.relayShapes();if(this.isShapeRelayUniform(e.name,e.args)){const h=E(e.name,e.args);let p=d.get(h);p===void 0&&(p={args:e.args,cursor:o,key:h,name:e.name,table:t.table},d.set(h,p),A(this.host.sql(),p)),l=p.cursor}else if(e.relayIndex!==void 0&&e.connectionId!==void 0){const h=w(e.relayIndex,e.connectionId,e.subId),p={args:e.args,connectionId:e.connectionId,cursor:o,identity:s,key:h,name:e.name,relayIndex:e.relayIndex,table:t.table};R.set(h,p),A(this.host.sql(),p)}else return{error:{code:"RELAY_SHAPE_UNROUTABLE",message:`shape ${e.name} is per-socket on a relay, but the subscribe carries no ${e.relayIndex===void 0?"relay index":"connection id"}`}};const y=D([{reset:a,rowsPatch:c,shapeId:e.subId}],{baseCheckpoint:r,checkpoint:l,epoch:n,lastMutationId:void 0,pokeId:this.host.nextPokeId()});return{cursor:l,epoch:n,frames:y}}ensureRelayTables(){this.relayTablesReady||(this.relayTablesReady=!0,this.host.sql().exec("CREATE TABLE IF NOT EXISTS __lunora_relays (idx INTEGER PRIMARY KEY)"),this.host.sql().exec("CREATE TABLE IF NOT EXISTS __lunora_relay_grants (idx INTEGER PRIMARY KEY)"),this.host.sql().exec("CREATE TABLE IF NOT EXISTS __lunora_relay_seqs (idx INTEGER PRIMARY KEY, seq INTEGER NOT NULL)"),this.host.sql().exec("CREATE TABLE IF NOT EXISTS __lunora_relay_binding (id INTEGER PRIMARY KEY, binding TEXT NOT NULL)"),B(this.host.sql()))}bindingName(){const e=this.host.shardBinding();if(e!==void 0&&e!=="")return e!==this.recordedBinding&&(this.recordedBinding=e,this.ensureRelayTables(),this.host.sql().exec("INSERT INTO __lunora_relay_binding (id, binding) VALUES (1, ?) ON CONFLICT(id) DO UPDATE SET binding = excluded.binding",e)),e;if(this.recordedBinding!==void 0)return this.recordedBinding;try{const s=this.host.sql().exec("SELECT binding FROM __lunora_relay_binding WHERE id = 1").toArray();this.recordedBinding=s[0]?.binding}catch{this.recordedBinding=void 0}return this.recordedBinding}relayShapes(){const e=this.registryCache;if(e!==void 0)return e;this.ensureRelayTables();const s={cohort:new Map,proxies:new Map};for(const t of K(this.host.sql()))t.relayIndex===void 0||t.connectionId===void 0?s.cohort.set(t.key,{args:t.args,cursor:t.cursor,key:t.key,name:t.name}):s.proxies.set(t.key,{args:t.args,connectionId:t.connectionId,cursor:t.cursor,identity:t.identity??{},key:t.key,name:t.name,relayIndex:t.relayIndex});return this.registryCache=s,s}rewindShapeCursor(e,s){const t=e;t.cursor<=s||(t.cursor=s,I(this.host.sql(),t.key,s))}ownerRelaySet(){if(this.relaySetCache===void 0){this.ensureRelayTables();const e=this.host.sql().exec("SELECT idx FROM __lunora_relays").toArray();this.relaySetCache=new Set(e.map(s=>Number(s.idx)))}return this.relaySetCache}liveGrantRelaySet(){if(this.liveGrantRelayCache===void 0){this.ensureRelayTables();const e=this.host.sql().exec("SELECT idx FROM __lunora_relay_grants").toArray();this.liveGrantRelayCache=new Set(e.map(s=>Number(s.idx)))}return this.liveGrantRelayCache}recordLiveGrantRelay(e){const s=this.liveGrantRelaySet();s.has(e)||(this.host.sql().exec("INSERT OR IGNORE INTO __lunora_relay_grants (idx) VALUES (?)",e),s.add(e))}addRelayToSet(e){this.ensureRelayTables(),this.host.sql().exec("INSERT OR IGNORE INTO __lunora_relays (idx) VALUES (?)",e),this.ownerRelaySet().add(e)}async forwardToRelay(e,s){await this.requestDroppingIdle(e,s)}async requestDroppingIdle(e,s){const t=this.relaySeqMark(e),r=await this.requestRelayMessage(M(this.roleId.ownerKey,e),s);return r?.status!==F||this.relaySeqMark(e)!==t?{dropped:!1,response:r}:(this.removeRelayFromSet(e),{dropped:!0,response:r})}removeRelayFromSet(e){this.ensureRelayTables(),this.host.sql().exec("DELETE FROM __lunora_relays WHERE idx = ?",e);const s=this.ownerRelaySet();s.delete(e),this.host.sql().exec("DELETE FROM __lunora_relay_grants WHERE idx = ?",e),this.liveGrantRelaySet().delete(e);const{cohort:t,proxies:r}=this.relayShapes();for(const[o,n]of r)n.relayIndex===e&&r.delete(o);H(this.host.sql(),e),s.size===0&&(t.clear(),this.shapeUniformCache.clear(),j(this.host.sql()))}probeShapeRelayUniform(e,s){let t;try{t=this.host.resolveShape(e,s,b)}catch{return!1}if(t===void 0||t.global===!0||this.host.rlsMetadata().policies.some(l=>l.on==="read"&&l.table===t.table)||this.tableHasAnyMask(t.table))return!1;const r=_(t.effectiveWhere),o=_(t.columns);let n=!1;const a=l=>{const d={groups:[`grp_${l}`],roles:[l],sub:`__lunora_probe_${l}__`};return{identity:new Proxy(d,{get:(y,h)=>typeof h=="symbol"||h in y?Reflect.get(y,h):`${l}:${h}`,getOwnPropertyDescriptor:(y,h)=>(n=!0,Reflect.getOwnPropertyDescriptor(y,h)),has:(y,h)=>typeof h=="symbol"?Reflect.has(y,h):!0,ownKeys:y=>(n=!0,Reflect.ownKeys(y))}),ip:`__lunora_probe_${l}__`,userId:`__lunora_probe_${l}__`}};return[b,a("a"),a("b")].every(l=>{let d;try{d=this.host.resolveShape(e,s,l)}catch{return!1}return d!==void 0&&d.global!==!0&&d.table===t.table&&_(d.effectiveWhere)===r&&_(d.columns)===o})&&!n}tableHasAnyMask(e){return this.host.maskMetadata().columns.some(s=>s.table===e)}async liveControlAnswer(e,s){const t=s.action==="subscribe";t&&this.pendingSubscribeRelays.set(e,(this.pendingSubscribeRelays.get(e)??0)+1);const r=this.requestRelayMessage(M(this.roleId.ownerKey,e),{control:s,type:"relay_live_control"}).then(a=>(t&&a?.ok===!0&&this.recordLiveGrantRelay(e),a)).finally(()=>{if(!t)return;const a=(this.pendingSubscribeRelays.get(e)??1)-1;a===0?this.pendingSubscribeRelays.delete(e):this.pendingSubscribeRelays.set(e,a)});let o;const n=new Promise(a=>{o=setTimeout(()=>{a(void 0)},ue)});return Promise.race([r,n]).then(a=>(a===void 0&&x(r,void 0),a)).finally(()=>{clearTimeout(o)})}}class be extends U{relayAnnounced=!1;liveControlSeqs=new Map;pendingAnnounce;announceGeneration=0;pendingDetach;relayMemoCache;shapeControl=new Map;constructor(e,s,t){super(e,{ownerKey:s,relayIndex:t})}async forwardWhisper(e,s){this.canAddressSiblings()&&await this.postRelayMessage(this.roleId.ownerKey,{frame:s,originRelay:this.roleId.relayIndex,topic:e,type:"relay_frame"})}async forwardRoomEvent(e){const s=await this.requestRelayMessage(this.roleId.ownerKey,{...e,relayIndex:this.roleId.relayIndex,type:"relay_room_event"});if(!s?.ok)return!1;try{return(await s.json()).admitted}catch{return!1}}onFlush(){return Promise.resolve()}async seedRelayShape(e,s,t,r){if(!this.canAddressSiblings())return{code:"RELAY_MISCONFIGURED",message:"relay cannot address its owner"};const{connectionId:o}=this.host.readAttachment(e),n={args:q(t.args??{}),connectionId:o,identity:r.identity,name:t.name,relayIndex:this.roleId.relayIndex,sinceEpoch:t.sinceEpoch,sinceSeq:t.sinceSeq,subId:s,type:"relay_shape_subscribe",userId:r.userId},a=await this.queueShapeControl(o,async()=>(await this.announce(),this.requestRelayMessage(this.roleId.ownerKey,n)));if(a===void 0)return{code:"RELAY_SEED_FAILED",message:"owner did not answer the shape seed"};let c;try{c=await a.json()}catch{return{code:"RELAY_SEED_FAILED",message:"malformed shape seed from owner"}}if(c.error!==void 0)return c.error;if(c.frames===void 0)return{code:"RELAY_SEED_FAILED",message:"owner returned no shape frames"};await se(e);for(const l of c.frames)C(e,l);return this.recordRelayShapeMemo(e,s,c.cursor??0,c.epoch),"ok"}announce(){if(this.relayAnnounced||!this.canAddressSiblings())return Promise.resolve(!0);if(this.pendingAnnounce===void 0){const e=this.announceGeneration;this.pendingAnnounce=(this.pendingDetach??Promise.resolve()).then(async()=>O(this.requestRelayMessage(this.roleId.ownerKey,{relayIndex:this.roleId.relayIndex,seq:this.nextRelaySeq(),type:"relay_attach"}))).then(s=>{const t=s?.ok===!0;return e===this.announceGeneration&&(this.relayAnnounced=t),t}).finally(()=>{e===this.announceGeneration&&(this.pendingAnnounce=void 0)})}return this.pendingAnnounce}async announceDrain(e){if(this.host.getWebSockets().some(o=>o!==e&&this.isAdmitted(o))||(this.relayMemos().clear(),le(this.host.sql()),this.liveControlSeqs.clear(),!this.canAddressSiblings()))return;this.relayAnnounced=!1,this.announceGeneration+=1;const s=this.pendingAnnounce;this.pendingAnnounce=void 0;const t=this.pendingDetach,r=Promise.all([s?.catch(()=>!1),t]).then(async()=>O(this.postRelayMessage(this.roleId.ownerKey,{relayIndex:this.roleId.relayIndex,seq:this.nextRelaySeq(),type:"relay_detach"}))).catch(()=>{}).finally(()=>{this.pendingDetach===r&&(this.pendingDetach=void 0)});this.pendingDetach=r,await r}async releaseRelayShapes(e,s){const{connectionId:t}=this.host.readAttachment(e);t!==void 0&&this.forgetRelayShapeMemos(t,s),!(t===void 0||!this.canAddressSiblings())&&await this.queueShapeControl(t,async()=>this.postRelayMessage(this.roleId.ownerKey,{connectionId:t,relayIndex:this.roleId.relayIndex,...s===void 0?{}:{subId:s},type:"relay_shape_unsubscribe"}))}relayCount(){return 0}isShapeRelayUniform(){return!1}minShapeCursor(){}onAttach(){return!0}refusesAsIdle(){return this.host.getWebSockets().some(e=>this.isAdmitted(e))?!1:(this.relayAnnounced=!1,this.announceGeneration+=1,this.pendingAnnounce=void 0,!0)}onDetach(){return!0}async onLiveControl(e){const{connectionId:s,seq:t,subscriptionId:r}=e;if(t===void 0)return this.host.liveControl(e);const o=Date.now();for(const[d,R]of this.liveControlSeqs){if(o-R.appliedAt<=_e)break;this.liveControlSeqs.delete(d)}const n=`${s}\0${r}`,a=this.liveControlSeqs.get(n);if(a!==void 0&&t<a.seq)return Response.json({error:{code:"LIVE_CONTROL_SUPERSEDED",message:"a later live control call already applied"}},{status:409});const c={appliedAt:o,seq:t};this.liveControlSeqs.delete(n),this.liveControlSeqs.set(n,c);const l=await this.host.liveControl(e);return l.status===404&&this.liveControlSeqs.get(n)===c&&this.liveControlSeqs.delete(n),l}onWhisperFrame(){return Promise.resolve()}onShapeSubscribe(){return{error:{code:"RELAY_CANNOT_SEED",message:"a relay has no op-log to seed from"}}}onShapeUnsubscribe(){}onShapePoke(e){return this.deliverShapePoke(e)}async queueShapeControl(e,s){if(e===void 0)return s();const t=(this.shapeControl.get(e)??Promise.resolve()).then(s,s),r={},o=()=>{this.shapeControl.get(e)===r.chain&&this.shapeControl.delete(e)},n=t.then(o,o);return r.chain=n,this.shapeControl.set(e,n),t}relayMemos(){return this.relayMemoCache===void 0&&(re(this.host.sql()),this.relayMemoCache=oe(this.host.sql())),this.relayMemoCache}connectionMemos(e){const s=this.relayMemos();let t=s.get(e);return t===void 0&&(t=new Map,s.set(e,t)),t}recordRelayShapeMemo(e,s,t,r){const{connectionId:o}=this.host.readAttachment(e);o!==void 0&&(this.connectionMemos(o).set(s,{cursor:t,epoch:r}),N(this.host.sql(),[{connectionId:o,cursor:t,epoch:r,subId:s}]))}forgetRelayShapeMemos(e,s){if(s===void 0){this.relayMemos().delete(e),ie(this.host.sql(),e);return}this.relayMemos().get(e)?.delete(s),ae(this.host.sql(),e,s)}deliverShapePoke(e){const s=E(e.name,e.args),t=[];let r=0,o=0;for(const n of this.host.getWebSockets()){const{connectionId:a,shapes:c}=this.host.readAttachment(n);if(c===void 0||a===void 0||e.targetConnectionId!==void 0&&a!==e.targetConnectionId)continue;const l=this.pokeSocketShapes(n,c,this.connectionMemos(a),e,s);o+=l.matched.length,r+=l.sent;for(const d of l.matched)t.push({connectionId:a,cursor:e.checkpoint,epoch:e.epoch,subId:d})}return N(this.host.sql(),t),{delivered:r,matched:o}}pokeSocketShapes(e,s,t,r,o){const n=[];let a=0;for(const[c,l]of Object.entries(s)){const d=t.get(c);if(E(l.name,l.args)!==o||!fe(d,r))continue;const y=D([{baseCheckpoint:d?.cursor,rowsPatch:r.rowsPatch,shapeId:c}],{baseCheckpoint:void 0,checkpoint:r.checkpoint,epoch:r.epoch,lastMutationId:void 0,pokeId:this.host.nextPokeId()},{preEncoded:!0}).map(h=>C(e,h)).every(Boolean);t.set(c,{cursor:r.checkpoint,epoch:r.epoch}),n.push(c),y&&(a+=1)}return{matched:n,sent:a}}}const xe=i=>{const e=i.doName();if(e===void 0)return;const s=z(e);return s===void 0?new Ee(i,e):new be(i,s.ownerKey,s.relayIndex)};export{de as DEFAULT_MAX_RELAYS,Ee as OwnerRelay,be as RelayMember,xe as createRelayLink};
@@ -1 +0,0 @@
1
- import{LunoraError as y}from"@lunora/errors";import{D as gt}from"./MAX_TOKEN_LENGTH-BakL9FUy-B3VwYY8C.mjs";import{S as Mn,l as qe,h as Dn}from"./fts-companion-CA8mLJWq.mjs";import{decodeWire as kn,stableWireKey as qt}from"@lunora/wire";import{sql as a}from"drizzle-orm";import{throwingScheduler as Ln,aggregateSqlFunction as We,normalizeCountArgument as Fn}from"./AGGREGATE_SQL_FUNCTION-C_ZipS9R.mjs";import{aggregateTableName as ot,encodeAggregateKey as rt,readAggregateValue as it}from"./aggregateTableName-B_CtIQCS.mjs";import{mergeWhere as K,CountRlsUnsupportedError as st,selectIndexForGroupBy as qn,selectIndexForCount as Wn,selectIndexForAggregate as Bn}from"./CountRlsUnsupportedError-BvsDqfO2.mjs";import{backfillSearchIndexesForTable as Pn,searchIndexCoversTable as Un}from"./backfillAggregateIndexes-BN0NwXQk.mjs";import{backfillAggregateIndexes as gi,backfillRankIndexes as yi,backfillSearchIndexes as $i}from"./backfillAggregateIndexes-BN0NwXQk.mjs";import{appendCdcChange as On,readCdcDocAtOrBefore as Hn}from"./CDC_LOG_TABLE-CwEMKX-0.mjs";import{CDC_LOG_TABLE as mi,applyCdcChanges as Si,bumpCdcEpoch as _i,cdcCanVouchFor as Ri,cdcForkedError as Ti,cdcSeqLeavingRows as vi,cdcTouchesTables as Ii,cdcTrimmedError as Ai,compactCdcDocs as Ci,cursorBelowRetainedFloor as xi,minCdcReplayableSeq as bi,minCdcSeq as Mi,readCdcChangeKeys as Di,readCdcChanges as ki,readCdcCursor as Li,readCdcEpoch as Fi,trimCdcChanges as qi}from"./CDC_LOG_TABLE-CwEMKX-0.mjs";import{allocateCommitSeq as Gn,COMMIT_SEQ_FIELD as jn}from"./COMMIT_SEQ_FIELD-Da1DjGqo.mjs";import{createCompanionSync as Kn}from"./createCompanionSync-zIF_F4oD.mjs";import{isMemoryTable as Wt}from"./clearMemoryTables-aMRERF0w.mjs";import{computeRankPage as Bt}from"./computeRankPage-BZIpATcs.mjs";import{SCAN_DEP as O}from"./SCAN_DEP-D7qE3iUe.mjs";import{runSql as pe,runDrizzle as H}from"./runDrizzle-RC09zZrh.mjs";import{p as Nn,j as ut,D as ie,r as ve,k as fe,b as Be,A as ct,a as Pe,m as he,e as we,s as Qn,t as Vn,i as Jn,q as Pt,h as un,g as zn}from"./do-sql-BWrJQAOh.mjs";import{renderSql as fn,unionAll as yt,WORKERD_SQLITE_LIMITS as hn,sqliteInList as Yn}from"./WORKERD_SQLITE_LIMITS-B_4w7tzY.mjs";import{coveringGeohashes as Xn,boundingBoxGeohashes as Zn,haversineMeters as eo,pointInBoundingBox as to}from"./GEO_DEFAULT_PRECISION-CqpQZ-J_.mjs";import{NotFoundError as no}from"./NotFoundError-BhF7FeFr.mjs";import{resolvePatch as oo,assertPatchAllowed as ro,operatorFields as io,readPatchField as Ut}from"./assertPatchAllowed-CA_H466g.mjs";import{tiebreakDirectionFor as so,encodeCursor as Ke,nullsOrderSuffix as co,normalizeOrderKeys as Ot,uniqueIndexFields as ao,buildSeekWhere as lo,decodeCursor as Ht,buildSeekBeforeWhere as uo,softDeleteScope as Te,applySelect as Gt}from"./CURSOR_PREFIX-6offuG6M.mjs";import{rankTableName as jt,sortColumnName as Kt,resolveRankPartition as fo,encodePartitionKey as ho,RANK_TIEBREAK as wo,rankPivotConditionSql as po}from"./RANK_TIEBREAK-D3ye2GsL.mjs";import{UNVOUCHABLE_DEP as Nt}from"./UNVOUCHABLE_DEP-C68htACn.mjs";import{indexKeysForRow as go,buildIndexRange as yo}from"./buildIndexRange-DQ3eWAGd.mjs";import{r as Ne,j as Ie,c as X,t as Ve,i as Qt}from"./where-sql-BjY4rnqb.mjs";import{serializeSqlValue as Ae}from"./serializeSqlValue-DeoBMpZ2.mjs";import{quoteIdentifier as Ce}from"./quoteIdentifier-CObIFRhb.mjs";import{whereOfFilter as $o,isPushableWhere as Eo}from"./isPushableWhere-BeYAOjUb.mjs";import{deriveRelationEdges as mo,findRelated as So}from"./RELATED_DEFAULT_LIMIT-CVqN4JEu.mjs";import{assertFlatPredicate as at,resolveRelationPredicates as _o,composeReadPredicate as Ro}from"./DEFAULT_MAX_RELATION_KEYS-9eOkadE4.mjs";import{describeRelationWrites as To}from"./describeRelationWrites-omar6-u9.mjs";import{runRowValidators as Ue,transformOnlyDefinition as vo,applyInsertDefaults as ft,resolveWith as Vt,relationHooks as Jt,applyOnDelete as Io,fanOutScalarCounts as Ao}from"./applyInsertDefaults-B0NXPs2x.mjs";import{guardWriter as Co}from"./RLS_UNWRAP_SYMBOL-BjV34hfH.mjs";import{mayHoldProjectedValue as xo}from"./BIGINT_KEY_DIGITS-DE6yshOt.mjs";import{createSystemReader as bo}from"./createSystemReader-DcDLFfC-.mjs";import{ConflictError as ae}from"./ConflictError-C8GtJmjS.mjs";import{hasTrigger as zt,runTriggers as Mo}from"./hasTrigger-CjlwI4le.mjs";import{advanceClientWatermark as Bi,migrateClientWatermark as Pi,readClientWatermark as Ui}from"./CLIENT_WATERMARK_TABLE-De7z_OHV.mjs";import{IDEMPOTENCY_TABLE as Hi,readIdempotent as Gi,trimIdempotent as ji,writeIdempotent as Ki}from"./IDEMPOTENCY_TABLE-COrgeP3O.mjs";import{runShardMigrations as Qi}from"./runShardMigrations-C-0ec-sY.mjs";import{selectShapeMembers as Ji,selectShapeRows as zi}from"./selectShapeMembers-BCfKypfN.mjs";const Do=t=>{const i=atob(t),o=Uint8Array.from(i,c=>c.codePointAt(0)??0);return new TextDecoder().decode(o)},ko=()=>new y("BAD_REQUEST","invalid cursor"),Yt=16,Xt=8,V=1024,$t=(t,i)=>i.query(t),Lo=(t,i)=>{if(t.length===0)return 0;let o=0;for(const[c,s]of i.entries()){const w=c===i.length-1;let m=0;for(const S of t)(w?S.startsWith(s):S===s)&&(m+=1);if(m===0)return 0;o+=m}return o},Fo=(t,i)=>{if(!i)return{exact:!0,lower:t,upper:t};const o=[...t].at(-1)??"",c=(o.codePointAt(0)??0)+1;if(c>=55296&&c<=57343||c>1114111)return{exact:!0,lower:t,upper:t};const s=t.slice(0,t.length-o.length);return{exact:!1,lower:t,upper:s+String.fromCodePoint(c)}},qo=(t,i,o)=>{const c={eq:(s,w)=>{if(!t.definition.filterFields?.includes(s))throw new y("INTERNAL",`field "${s}" is not a filter field of search index "${t.indexName}" on table "${i}"`);if(t.filters.length>=Xt)throw new y("BAD_REQUEST",`search index "${t.indexName}" on table "${i}": at most ${String(Xt)} .eq() filters are supported per search query`);return t.filters.push({field:s,value:w}),c},search:(s,w)=>{const m=t;if(s!==m.definition.field)throw new y("INTERNAL",`search index "${m.indexName}" on table "${i}" indexes "${m.definition.field}", not "${s}"`);const S=$t(w,o).length;if(S>Yt)throw new y("BAD_REQUEST",`search index "${m.indexName}" on table "${i}": at most ${String(Yt)} search terms are supported (got ${String(S)})`);return m.field=s,m.query=w,m.hasQuery=!0,c}};return c},Wo=t=>{if(t.length>V)throw new y("BAD_REQUEST",`more than ${String(V)} documents match this search — narrow it with filters or read it a page at a time with .paginate()`)},Bo=t=>Math.min(t.offset+t.numItems+1,V),Po=t=>btoa(`search:${String(t)}`),Uo=t=>{let i;try{i=Do(t)}catch{return}if(!i.startsWith("search:"))return;const o=Number(i.slice(7));return Number.isInteger(o)&&o>=0?o:void 0},Oo=t=>{if(typeof t.endCursor=="string")throw new y("BAD_REQUEST","bounded (endCursor) pagination is not supported on search queries — relevance order has no stable range boundary");if(!Number.isFinite(t.numItems))throw new y("BAD_REQUEST",`search pagination needs a finite numItems, got ${String(t.numItems)}`);const i=Math.max(0,Math.floor(t.numItems)),o=t.cursor?Uo(t.cursor):0;if(o===void 0)throw ko();if(o+i>=V)throw new y("BAD_REQUEST",`search pagination reaches the ${String(V)}-document limit (offset ${String(o)} + ${String(i)} requested) — a page must end below the cap so the probe row that answers \`hasMore\` still fits: retry with numItems ${String(Math.max(1,V-o-1))} or fewer, or narrow the query or the filters instead`);return{numItems:i,offset:o}},Ho=(t,i)=>{const o=i.offset+i.numItems,c=i.numItems>0&&t.length>o;return{continueCursor:c?Po(o):null,isDone:!c,page:t.slice(i.offset,o)}},Go=t=>{if(t===void 0)return V+1;if(!Number.isFinite(t))return V;const i=Math.max(0,Math.floor(t));if(i>V)throw new y("BAD_REQUEST",`search returns at most ${String(V)} documents (asked for ${String(i)}) — narrow the query or paginate instead`);return i},wn=500,pn=(t,i,o)=>{if(t!==void 0&&t!==Number.POSITIVE_INFINITY&&(!Number.isInteger(t)||t<0))throw o(`${i}: batch limit must be a non-negative integer`);return t??wn},gn=(t,i,o,c)=>{if(t>i)throw c(`${o}: batch of ${String(t)} exceeds the limit of ${String(i)} (raise options.limit or chunk the call)`)},jo=32,Ko=1024,yn=(t,i,o,c)=>{const s=`SELECT id, _creationTime, ${Ce(ie)} FROM ${Ce(t)}`,w=`ORDER BY ${o}${c===void 0?"":` LIMIT ${String(c)}`}`;return i===void 0?Ne(`${s} ${w}`):Ie(`${s} WHERE `,i,` ${w}`)},Je={fieldRef:t=>Ne(ut(t)),rangeTypeGuard:(t,i)=>Ne(Nn(t,i)),serialize:Ae},No=t=>t===void 0?"":co(t==="first"),$n=t=>{const i=t.map(o=>`${ut(o.field)} ${o.direction==="desc"?"DESC":"ASC"}${No(o.nulls)}`);return t.some(o=>o.field==="_id"||o.field==="id")||i.push(`${ut("id")} ${so(t)==="desc"?"DESC":"ASC"}`),i.join(", ")},Qo={"<":"lt","<=":"lte","=":"eq",">":"gt",">=":"gte"},En=t=>new Set(t.sqlConditions.filter(i=>i.comparator==="=").map(i=>i.field)),Vo=t=>{const i=En(t);let o=0;for(;o<t.indexFields.length&&i.has(t.indexFields[o]??"");)o+=1;return t.indexFields.slice(o)},Jo=(t,i)=>{const o=t.order,c=Vo(t),{shape:s}=i;return c.length>0?Ot(c.map(w=>({[w]:o})),s,{pinned:En(t),uniqueBy:ao(i.indexes,s)}):Ot([{_creationTime:o}],s)},zo=(t,i,o,c)=>{const s=t.sqlConditions.map(w=>({[w.field]:{[Qo[w.comparator]??"eq"]:w.value}}));if(o&&s.push(lo(i,Ht(o))),c&&s.push(uo(i,Ht(c))),s.length!==0)return s.length===1?s[0]:{AND:s}},Yo=t=>{if(t.want!==void 0)return t.selective?Math.max(t.want,jo):t.want},ht=(t,i,o,c,s,w,m)=>{const S=Jo(c,o),C=$n(S),$=[],{filters:W,want:x}=w;let A=w.cursor??void 0,D=Yo(w);if(x===0)return{documents:$,orderKeys:S};for(;;){const B=X(zo(c,S,A,w.endCursor),Je,Ve),F=yn(i,s&&B?Ie(B," AND ",s):s??B,C,D),L=pe(t,F.text,...F.params).toArray();let q={};m(L.length);for(const j of L)if(q=ve(j),W.every(se=>se(q))&&$.push(q)===x)return{documents:$,orderKeys:S};if(D===void 0||L.length<D)return{documents:$,orderKeys:S};A=Ke(q,S),D=Math.max(D,Math.min(D*2,Ko))}},Xo=(t,i,o,c,s,w,m,S)=>{const C=Math.max(0,Math.floor(s.numItems));if(typeof s.endCursor=="string"){const{documents:B,orderKeys:F}=ht(t,i,o,c,w,{cursor:s.cursor,endCursor:s.endCursor,filters:m.all,selective:m.selective,want:void 0},S),L=B.length>=2?B[Math.floor(B.length/2)-1]:void 0;return{continueCursor:s.endCursor,isDone:!0,page:B,splitCursor:L?Ke(L,F):null}}const{documents:$,orderKeys:W}=ht(t,i,o,c,w,{cursor:s.cursor,filters:m.all,selective:m.selective,want:C+1},S),x=$.length>C,A=x?$.slice(0,C):$,D=A.at(-1);return{continueCursor:x&&D?Ke(D,W):null,isDone:!x,page:A}},ze=t=>{const i=new Map;return o=>{const c=i.get(o);if(c!==void 0)return c;const s=t(Ce(o));return i.set(o,s),s}},ge=Ce(ie),Zo=ze(t=>`INSERT INTO ${t} (id, _creationTime, ${ge}) VALUES (?, ?, ?)`),Zt=ze(t=>`UPDATE ${t} SET ${ge} = ? WHERE id = ? AND ${ge} = ?`),er=ze(t=>`UPDATE ${t} SET _creationTime = ?, ${ge} = ? WHERE id = ? AND ${ge} = ?`),tr=ze(t=>`DELETE FROM ${t} WHERE id = ? AND ${ge} = ?`),nr="SELECT changes() AS changed",en=new Map,or="",rr=t=>{const i=JSON.stringify(t),o=en.get(i);if(o!==void 0)return o;const c=t.map(w=>a`SELECT ${a.raw(`'${w.replaceAll("'","''")}'`)} AS __t__, id, _creationTime, ${a.identifier(ie)} FROM ${a.identifier(w)} WHERE id = ${or}`),{sql:s}=fn("sqlite",a`${yt(c)} LIMIT 1`);return en.set(i,s),s},ir=(t,i)=>i.map(()=>t),sr=/^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/iu,cr=t=>{if(!sr.test(t))throw new y("INTERNAL",`invalid clientId ${JSON.stringify(t)}: a client-supplied row id must be a UUID`)},wt=t=>{if(t.includes("\0"))throw new y("BAD_REQUEST",`invalid row id ${JSON.stringify(t)}: a row id cannot hold a NUL character (U+0000)`)},ar=(t,i,o,c)=>{if(o!==!0)return;const s=t!==void 0&&"serverDefault"in(t.shape._id?._meta?.column??{});for(const w of i){const m=s?ft(t,w,c)._id:w._id;typeof m=="string"&&wt(m)}},tn=50,Oe=Math.floor(hn.boundParams/3),Re=hn.boundParams,dr=128,Qe=t=>new y("BATCH_LIMIT_EXCEEDED",t,{status:400}),He=(t,i,o)=>{gn(t,pn(i,o,Qe),o,Qe)},nn=async(t,i,o,c,s)=>{const w=pn(c,s,Qe),{page:m}=await t.findMany(i,Number.isFinite(w)?{limit:w+1,omitContinueCursor:!0,where:o}:{where:o});return m.length>w&&gn(Math.max(await t.count(i,{where:o}),m.length),w,s,Qe),m},lr=t=>{const i={eq:(o,c)=>(t.sqlConditions.push({comparator:"=",field:o,value:c}),i),gt:(o,c)=>(t.sqlConditions.push({comparator:">",field:o,value:c}),i),gte:(o,c)=>(t.sqlConditions.push({comparator:">=",field:o,value:c}),i),lt:(o,c)=>(t.sqlConditions.push({comparator:"<",field:o,value:c}),i),lte:(o,c)=>(t.sqlConditions.push({comparator:"<=",field:o,value:c}),i)};return i},ur=t=>Math.max(t,V),mn=(t,i)=>{const o=t.filters.map(c=>a`${we(c.field)} = ${Ae(c.value)}`);return i&&o.push(i),o},fr=(t,i,o,c,s)=>{const w=$t(o.query,gt(o.definition.language));if(w.length===0)return[];const m=Mn(i,o.indexName),S=`${m}__vocab`,C=w.length-1,$=w.map((F,L)=>{const q=Fo(F,L===C),j=q.exact?a`${a.identifier("term")} = ${q.lower}`:a`${a.identifier("term")} >= ${q.lower} AND ${a.identifier("term")} < ${q.upper}`;return a`SELECT ${a.identifier("doc")}, ${a.raw(String(L))} AS ${a.identifier("__term__")}, COUNT(*) AS ${a.identifier("__n__")} FROM ${a.identifier(S)} WHERE ${j} GROUP BY ${a.identifier("doc")}`}),W=w.map((F,L)=>a`SUM(CASE WHEN u.${a.identifier("__term__")} = ${a.raw(String(L))} THEN u.${a.identifier("__n__")} ELSE 0 END)`),x=a`SELECT f.${a.identifier(qe)} AS ${a.identifier(qe)}, ${a.join(W,a` + `)} AS ${a.identifier("__score__")} FROM (${yt($)}) u JOIN ${a.identifier(m)} f ON f.rowid = u.${a.identifier("doc")} GROUP BY f.${a.identifier(qe)} HAVING ${a.join(W.map(F=>a`${F} > 0`),a` AND `)}`,A=mn(o,s);let D=a`SELECT m.id, m._creationTime, m.${a.identifier(ie)}, s.${a.identifier("__score__")} AS ${a.identifier("__score__")} FROM (${x}) s JOIN ${a.identifier(i)} m ON m.id = s.${a.identifier(qe)}`;A.length>0&&(D=a`${D} WHERE ${a.join(A,a` AND `)}`),D=a`${D} ORDER BY s.${a.identifier("__score__")} DESC, m._creationTime DESC, m.id ASC LIMIT ${a.raw(String(c))}`;const B=[];for(const F of H(t,D)){const L=un(F);if(L){const q=F.__score__;B.push({document:L,score:typeof q=="number"?q:Number(q??0)})}}return B},hr=(t,i,o,c,s)=>{const w=gt(o.definition.language),m=$t(o.query,w);if(m.length===0)return[];const S=mn(o,s);let C=a`SELECT id, _creationTime, ${a.identifier(ie)} FROM ${a.identifier(i)}`;S.length>0&&(C=a`${C} WHERE ${a.join(S,a` AND `)}`),C=a`${C} ORDER BY _creationTime DESC, id ASC LIMIT ${a.raw(String(ur(c)))}`;const $=H(t,C).toArray(),W=[];for(const x of $){const A=un(x);if(!A)continue;const D=Lo(Dn(A,o.definition),m);D>0&&W.push({creationTime:typeof A._creationTime=="number"?A._creationTime:0,doc:A,id:typeof A._id=="string"?A._id:"",score:D})}return W.sort((x,A)=>A.score-x.score||A.creationTime-x.creationTime||x.id.localeCompare(A.id)),W.slice(0,c).map(x=>({document:x.doc,score:x.score}))},dt=(t,i,o,c)=>{if(!Number.isFinite(t.lat)||t.lat<-90||t.lat>90||!Number.isFinite(t.lng)||t.lng<-180||t.lng>180)throw new y("BAD_REQUEST",`geo index "${c}" on table "${o}": ${i} must have a finite lat in [-90, 90] and lng in [-180, 180]`)},wr=(t,i)=>{const o=t,c={near:(s,w)=>{if(o.within)throw new y("INTERNAL",`geo index "${o.indexName}" on table "${i}": call .near() or .within(), not both`);if(dt(s,".near() point",i,o.indexName),!Number.isFinite(w)||w<=0)throw new y("BAD_REQUEST",`geo index "${o.indexName}" on table "${i}": .near() radiusMeters must be a finite number > 0, got ${String(w)}`);return o.near={point:{lat:s.lat,lng:s.lng},radiusMeters:w},c},within:s=>{if(o.near)throw new y("INTERNAL",`geo index "${o.indexName}" on table "${i}": call .near() or .within(), not both`);if(dt(s.sw,".within() sw corner",i,o.indexName),dt(s.ne,".within() ne corner",i,o.indexName),s.sw.lat>s.ne.lat)throw new y("BAD_REQUEST",`geo index "${o.indexName}" on table "${i}": .within() corners are transposed (sw.lat > ne.lat)`);if(s.sw.lng>s.ne.lng)throw new y("BAD_REQUEST",`geo index "${o.indexName}" on table "${i}": .within() box crosses the antimeridian (sw.lng > ne.lng), which is not supported — split it into two boxes at ±180 and union the results`);return o.within={ne:{lat:s.ne.lat,lng:s.ne.lng},sw:{lat:s.sw.lat,lng:s.sw.lng}},c}};return c},pr=(t,i)=>{const o=t[i];if(o===null||typeof o!="object")return;const{lat:c,lng:s}=o;return typeof c=="number"&&typeof s=="number"?{lat:c,lng:s}:void 0},gr=(t,i)=>{const o=pr(t,i.definition.field);if(!o)return;const c=typeof t._creationTime=="number"?t._creationTime:0;if(i.near){const s=eo(i.near.point,o);return s<=i.near.radiusMeters?{creationTime:c,distance:s}:void 0}return to(o,i.within)?{creationTime:c,distance:0}:void 0},yr=(t,i,o,c)=>{if(!o.near&&!o.within)throw new y("INTERNAL",`geo index "${o.indexName}" on table "${i}": call .near(point, radius) or .within(box)`);const s=o.near?Xn(o.near.point,o.near.radiusMeters):Zn(o.within),w=zn(i,o.indexName),m=s.map(x=>a`(g.${a.identifier("__geohash__")} >= ${x} AND g.${a.identifier("__geohash__")} < ${`${x}{`})`),S=[a`(${a.join(m,a` OR `)})`];c&&S.push(c);const C=a`SELECT m.id, m._creationTime, m.${a.identifier(ie)} FROM ${a.identifier(w)} g JOIN ${a.identifier(i)} m ON m.id = g.${a.identifier("__id__")} WHERE ${a.join(S,a` AND `)}`,$=H(t,C).toArray(),W=[];for(const x of $){const A=ve(x),D=A?gr(A,o):void 0;A&&D&&W.push({creationTime:D.creationTime,distance:D.distance,doc:A})}return W.sort((x,A)=>x.distance-A.distance||A.creationTime-x.creationTime),W},Sn=(t,i,o,c)=>{const s=[];for(const w of t)if(i.every(m=>m(c(w)))&&(s.push(w),typeof o=="number"&&s.length>=o))break;return s},$r=(t,i,o,c,s,w=()=>{})=>{const m=o.within!==void 0,S=yr(t,i,o,s).map(C=>({distanceMeters:m?null:C.distance,document:C.doc}));return w(S.length),typeof c=="number"?S.slice(0,Math.max(0,Math.floor(c))):S},on=(t,i,o,c,s,w,m=()=>{})=>{const{geo:S}=o;if(!S)throw new y("INTERNAL","runGeoTerminalScored called without a staged geo query");const C=s.length>0,$=$r(t,i,S,C?void 0:w,c,m);return C?Sn($,s,w,W=>W.document):$},rn=(t,i,o)=>{const c=t.shape[i];if(c!==void 0&&xo(c))throw new y("BAD_REQUEST",`${o}: "${i}" may hold an order-preserving key rather than a value SQL can reduce or group — declare an aggregateIndex covering this (by, field, op) so the maintained companion answers it instead (its running total is a REAL, so it stays exact only while the total is inside 2^53)`)},Er=t=>{let i=0;const o=[],c={...Je,relationExists:s=>{const{childWhere:w,negated:m,parentTable:S,relation:C}=s,$=`__rel_${String(i)}`,W=o.at(-1)??S;i+=1,t(C.table,O);const x=C.kind==="one"?C.field:C.references,A=C.kind==="one"?C.references:C.field,D=Ne(`${Pt($,A)} = ${Pt(W,x)}`);o.push($);const B=X(w,c,Ve);o.pop();const F=B===void 0?D:Ie(D," AND ",B),L=Ie("EXISTS (SELECT 1 FROM ",Qt(C.table)," AS ",Qt($)," WHERE ",F,")");return m?Ie("NOT ",L):L}};return c};class mr extends y{constructor(i="unique() found more than one matching document"){super("NOT_UNIQUE",i,{name:"NotUniqueError"})}}const Sr=/\s/u,_r=String.fromCodePoint(0),sn=(t,i,o)=>{if(!t.tables[i])throw new y("INTERNAL",`unknown table: ${i}`);return typeof o!="string"||o.length===0||Sr.test(o)||o.includes(_r)?null:o},_n=(t,i,o,c=()=>{},s=()=>{},w=()=>{},m)=>{const S=i.tables[o];if(!S)throw new y("INTERNAL",`unknown table: ${o}`);const C=Te(S.softDeleteMode,void 0),$=m??{indexFields:[],indexName:void 0,inMemoryFilters:[],order:"asc",sqlConditions:[],verifyFilters:[]},W=()=>{const E=K(C,$.pushedWhere);return E?X(E,he):void 0},x=()=>{const E=K(C,$.pushedWhere);return E?X(E,Je,Ve):void 0},A=()=>[...$.inMemoryFilters,...$.verifyFilters];let D=0;const B=E=>{const{search:M}=$;if(!M)throw new y("INTERNAL","runSearchFetch called without a staged search");Pn(t,o,S);const R=$.inMemoryFilters.length>0,k=Go(R?void 0:E),ee=Jn(t);if(ee&&!Un(t,o,M.definition))throw new y("SEARCH_INDEX_BUILDING",`search index "${M.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 N=W(),J=ee?fr(t,o,M,k,N):hr(t,o,M,k,N);!R&&E===void 0&&Wo(J);const re=A();return D=J.length,re.length>0?Sn(J,re,E,ce=>ce.document):J},F=E=>B(E).map(M=>M.document),L=E=>{const M=Oo(E);return Ho(F(Bo(M)),M)},q=()=>{if($.search||$.geo||$.indexName===void 0){s(void 0);return}s(yo(o,$.indexName,$.indexFields,$.sqlConditions,Ae))},j=E=>{q();let M=0;const R=(()=>{if($.search){const k=F(E);return M=D,k}return $.geo?on(t,o,$,W(),A(),E,k=>{M=k}).map(k=>k.document):ht(t,o,S,$,x(),{filters:A(),selective:$.inMemoryFilters.length>0,want:E===void 0?void 0:Math.max(0,Math.floor(E))},k=>{M+=k}).documents})();return w(Math.max(M,R.length)),R},se=()=>{if(!$.search&&!$.geo)throw new y("INTERNAL",`ctx.db.query("${o}").collectWithScores() requires a staged .withSearchIndex(...) or .withGeoIndex(...)`);q();let E=0;const M=(()=>{if($.search){const R=B(void 0);return E=D,R}return on(t,o,$,W(),A(),void 0,R=>{E=R})})();return w(Math.max(E,M.length)),M},Z={async*[Symbol.asyncIterator](){const E=_n(t,i,o,c,s,w,{...$,indexFields:[...$.indexFields],inMemoryFilters:[...$.inMemoryFilters],sqlConditions:[...$.sqlConditions],verifyFilters:[...$.verifyFilters]});if($.search){yield*await E.collect();return}let M;for(;;){const R=await E.paginate({cursor:M??null,numItems:dr});if(yield*R.page,R.isDone||R.continueCursor===null)return;M=R.continueCursor}},async collect(){return j(void 0)},async collectWithScores(){return se()},filter(E){const M=$o(E);return M!==void 0&&Eo(M,S.shape)?($.pushedWhere=K($.pushedWhere,M),$.verifyFilters.push(E)):$.inMemoryFilters.push(E),Z},async first(){return j(1)[0]??null},order(E){return $.order=E==="desc"?"desc":"asc",Z},async paginate(E){let M=0;if(q(),$.search){const k=L(E);return w(k.page.length),k}if($.geo)throw new y("INTERNAL","pagination is not supported on geo queries; use .take(n) or .collect()");const R=Xo(t,o,S,$,E,x(),{all:A(),selective:$.inMemoryFilters.length>0},k=>{M+=k});return w(Math.max(M,R.page.length)),R},async take(E){return j(E)},async unique(){const E=j(2);if(E.length>1)throw new mr(`unique() on table "${o}" matched ${String(E.length)} documents; expected at most one`);return E[0]??null},withGeoIndex(E,M){const R=(S.geoIndexes??[]).find(ee=>ee.name===E);if(!R)throw new y("INTERNAL",`unknown geo index "${E}" on table "${o}"`);c(o,E,"geo");const k={definition:R,indexName:E};if($.geo=k,M(wr(k,o)),!k.near&&!k.within)throw new y("INTERNAL",`geo index "${E}" on table "${o}" requires a .near(point, radius) or .within(box) call`);return Z},withIndex(E,M){const R=S.indexes.find(k=>k.name===E);if(!R)throw new y("INTERNAL",`unknown index "${E}" on table "${o}"`);return c(o,E,"index"),$.indexName=E,$.indexFields=R.fields,M&&M(lr($)),Z},withSearchIndex(E,M){const R=(S.searchIndexes??[]).find(ee=>ee.name===E);if(!R)throw new y("INTERNAL",`unknown search index "${E}" on table "${o}"`);c(o,E,"search");const k={definition:R,field:R.field,filters:[],hasQuery:!1,indexName:E,query:""};if($.search=k,M(qo(k,o,gt(R.language))),!k.hasQuery)throw new y("INTERNAL",`search index "${E}" on table "${o}" requires a .search(field, query) call`);return Z}};return Z},lt=(t,i,o,c)=>{const s=o;for(const[w,m]of Vn(t)){if(m.serverDefault){w in i&&(s[w]=m.serverDefault({auth:c}));continue}m.onUpdateFn&&!(w in i)&&(s[w]=m.onUpdateFn())}},cn=5,an=(t,i)=>{for(const o of Object.keys(i))if(i[o]===void 0)throw new y("INTERNAL",`Cannot ${t} field '${o}' to undefined — use null to clear a nullable field, or omit the key to leave it unchanged.`)},dn=["_commitSeq","_creationTime","_id"],Ge=t=>dn.some(i=>i in t)?Object.fromEntries(Object.entries(t).filter(([i])=>!dn.includes(i))):t,Rr=/unique constraint failed/i,Tr=t=>t instanceof Error&&Rr.test(t.message),vr=/string or blob too big/iu,Ir=(t,i)=>{if(!(!(t instanceof Error)||!vr.test(t.message)))throw new y("PAYLOAD_TOO_LARGE",`document is too large to store in "${i}": a single row cannot exceed the storage engine's per-row ceiling (2 MB on a Durable Object's SQLite). The limit is on the STORED bytes, which are UTF-8, and v.bytes()/v.bigint() columns are stored twice on a shard-local table. Keep the payload in R2 (ctx.storage) and store a reference on the row.`)},pt=(t,i,o,c)=>{try{pe(t,o,...c)}catch(s){throw Tr(s)?new ae(`unique constraint violation on "${i}"`,"unique"):(Ir(s,i),s)}},je=(t,i,o,c)=>{if(pt(t,i,o,c),pe(t,nr).one().changed===0)throw new ae(`optimistic concurrency conflict on "${i}" — the row changed during this mutation; refetch and retry`,"occ")},ln=(t,i,o,c,s,w,m)=>{const S=[];for(let x=0;x<o.length+1;x+=1){const A=o[x],D=c[x],B=D?.direction==="desc"?"desc":"asc",F=A===void 0||D===void 0?a`${a.identifier(wo)} < ${m}`:po(A,w[x],B,!1);if(F===void 0)continue;const L=[];for(let j=0;j<x;j+=1)L.push(a`${a.identifier(o[j])} IS ${w[j]}`);L.push(F);const[q]=L;S.push(L.length===1&&q!==void 0?q:a`(${a.join(L,a` AND `)})`)}const C=S.length>0?a.join(S,a` OR `):a`1 = 0`,$=H(t,a`SELECT COUNT(*) AS c FROM ${a.identifier(i)} WHERE ${a.identifier("__partition__")} = ${s} AND (${C})`).one(),W=H(t,a`SELECT COUNT(*) AS c FROM ${a.identifier(i)} WHERE ${a.identifier("__partition__")} = ${s}`).one();return{before:$.c,total:W.c}},Ar=t=>{const i=new Map;for(const[c,s]of Object.entries(t.tables))for(const w of Object.values(s.relationMap??{}))w.kind==="one"&&(w.onDelete==="cascade"||w.onDelete==="set null")&&i.set(w.table,[...i.get(w.table)??[],{holder:c,op:w.onDelete==="cascade"?"delete":"update"}]);const o=c=>{const s=new Set,w=[c];for(let m=w.pop();m!==void 0;m=w.pop())for(const{holder:S,op:C}of i.get(m)??[]){if(S===c||zt(t,S,C))return!0;s.has(S)||(s.add(S),w.push(S))}return!1};return new Set(Object.entries(t.tables).filter(([c,s])=>s.shardMode?.kind==="global"||zt(t,c,"delete")||o(c)).map(([c])=>c))},Cr=t=>{const i=new Map;for(const[o,c]of Object.entries(t.tables))c.softDeleteMode&&i.set(o,c.softDeleteMode.field);return i},hi=t=>{const{baselineSeq:i,onStalePatchDropped:o}=t,{sql:c}=t,{schema:s}=t,w=t.broadcast??(()=>{}),m=mo(s),S=new Map;for(const e of m){const n=r=>(s.tables[r]?.shardMode?.kind??"root")==="root";!e.array&&n(e.sourceTable)&&n(e.targetTable)&&S.set(e.sourceTable,[...S.get(e.sourceTable)??[],e])}const C=(e,n,r)=>{for(const d of S.get(e)??[]){const f=n[d.column];if(typeof f!="string"||r?.[d.column]===f||d.targetTable===e&&n._id===f)continue;if(H(c,a`SELECT 1 FROM ${a.identifier(d.targetTable)} WHERE id = ${f} LIMIT 1`).toArray().length===0)throw new y("VALIDATION_ERROR",`${d.name} references ${d.targetTable} row "${f}", which does not exist`)}},$=To(s,t.inTransaction),W=Ar(s),x=Cr(s);let A;const D=()=>t.inTransaction?.()===!0,B=e=>s.tables[e]?.commitOrderedMode!==!0?{}:((A===void 0||!D())&&(A=Gn(c)),{[jn]:A}),F=(e,...n)=>{const r=s.tables[e]?.indexes;if(!r||r.length===0)return;const d=[];for(const f of n)f&&d.push(...go(r,f,Ae));return d.length>0?d:void 0},{headroom:L}=t;let q=!1;const j=async e=>{const n=q;q=!0;try{return await e()}finally{q=n}},se=t.onRead??(()=>{}),Z=e=>{Wt(s.tables[e])&&se(Nt,Nt)},E=t.onReadRange??(e=>{se(e.table,O)}),M=e=>{Z(e.table),E(e)},R=(e,n)=>{n!==void 0&&n!==O&&!q&&L?.recordRead(1),Z(e),se(e,n)},k=t.onIndexUse??(()=>{}),ee=t.onWrite??(()=>{}),N=e=>{q||L?.recordWrite(e)},J=async e=>{N(e.doc),await ee(e)},{cache:re}=t,ce=t.clock??(()=>Date.now()),Et=t.idGenerator??(()=>crypto.randomUUID()),mt=t.scheduler??Ln,{globalDb:ye}=t,de=t.auth??{identity:null,userId:null},St=t.cdc??!1,Ye=mt,Rn=bo({scheduler:typeof Ye.list=="function"&&typeof Ye.get=="function"?Ye:void 0,storage:t.storage}),$e=(e,n,r,d)=>{St&&!Wt(s.tables[e])&&On(c,ce(),e,n,r,d)},_t=(e,n,r,d)=>{const f=s.tables[e];if(f?.dropStalePatchesMode!==!0||!St)return!1;const h=i?.();if(h===void 0)return!1;const l=Hn(c,e,n,h);if(l===void 0)return!1;const u=io(f,r);return Object.keys(Ge(r)).some(p=>!u.has(p)&&qt(Ut(l,p))!==qt(Ut(d,p)))},le=e=>s.tables[e]?.shardMode?.kind==="global",Rt=(e,n)=>{if(le(e)){if(!ye)throw new y("INTERNAL",`cross-backend ${n} for global table '${e}' requires a globalDb writer — pass one to createShardCtxDb({ globalDb })`);return ye}return U},Xe=e=>Rt(e,"cascade"),G=(e,n)=>{if(le(e)){if(!ye)throw new y("INTERNAL",`${n} on global table '${e}' requires a globalDb writer — pass one to createShardCtxDb({ globalDb })`);return ye}},Tt=async(e,n,r,d,f)=>{f&&N(r);const h=await e.insert(n,r,d);return w({key:h,op:"insert",row:{...r,_id:h},table:n}),h},Ze=(e,n)=>Rt(e,"relation load").findMany(e,n),vt=(e,n)=>(le(e)&&R(e,O),Ze(e,n)),Tn=e=>!le(e.table),It=t.relationExistsPushDown??"auto",At=It!=="never",{maxRelationKeys:Ct}=t,xe=(e,n,r)=>_o(e,{fetcher:vt,maxRelationKeys:Ct,relationBaseWhere:r,schema:s,tableName:n}),xt=async(e,n,r,d)=>{const f=G(e,"relation grouped count");if(f)return R(e,O),Ao((g,P)=>f.count(g,P),e,n,r,d);const h=s.tables[e];if(!h)throw new y("INTERNAL",`unknown table: ${e}`);R(e,O);const l=Te(h.softDeleteMode,void 0),u={[n]:{in:r}},p=K(K(u,d),l),_=await xe(p,e,void 0),I=X(_,he),T=we(n);let v=a`SELECT ${T} AS __fk__, COUNT(*) AS count FROM ${a.identifier(e)}`;I&&(v=a`${v} WHERE ${I}`),v=a`${v} GROUP BY ${T}`;const b=H(c,v).toArray();return new Map(b.map(g=>[g.__fk__,g.count]))};let be=0;const bt=new Set;for(const[e,n]of Object.entries(s.tables))for(const r of Object.values(n.triggerMap??{}))bt.add(`${e} ${r.timing} ${r.op}`);const te=(e,n,r)=>bt.has(`${e} ${n} ${r}`),ne=async(e,n,r)=>{if(be+=1,be>tn)throw be-=1,new ae(`trigger recursion exceeded ${String(tn)} levels on "${r.table}" — check for a self-triggering write`,"trigger");try{await Mo({ctx:xn,event:r,op:n,schema:s,tableName:r.table,timing:e})}finally{be-=1}},{ensureBackfilledForTable:Ee,ensureBackfilledIndex:et,ensureRankBackfilled:tt,ensureRankBackfilledForTable:me,syncAggregates:Me,syncCompanionsForInsert:Mt,syncGeo:De,syncRanks:Se,syncSearch:ke}=Kn({broadcast:w,indexKeysFor:(e,n)=>F(e,n),invalidateCache:(e,n,r)=>re?.invalidate(e,n,F(e,r)),recordCdc:$e,schema:s,sql:c,verified:t.companionMemo?.verified}),Dt=(e,n,r)=>{const{shardMode:d}=n;if(d?.kind==="shardBy"&&!(d.field!==void 0&&(r.partitionBy??[]).includes(d.field)))throw Object.assign(new Error(`rank index "${r.name}" on "${e}" partitions across shards (shard key "${d.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})},kt=e=>Object.entries(s.tables).filter(([,n])=>n.shardMode?.kind!=="global").map(([n])=>n).filter(n=>e===void 0||n===e),_e=e=>e===void 0||le(e)?ye:void 0,nt=async(e,n,r,d,f)=>{for(let h=0;h<r.length;h+=1)N(void 0);if(f!==void 0&&e.deleteMany!==void 0)return e.deleteMany(r,f.options,n);for(const h of r)await e.delete(h,n,d);return{deleted:r.length}},oe=(e,n)=>{const r=kt(n);for(let d=0;d<r.length;d+=Re){const f=r.slice(d,d+Re),[h]=pe(c,rr(f),...ir(e,f)).toArray();if(!h)continue;const l=h.__t__,u=ve(h);if(typeof l!="string"||!u)return;const p=h[ie];return{docJson:typeof p=="string"?p:fe(p??{}),row:u,tableName:l}}},vn=(e,n)=>{const r=[...new Set(e)],d=new Map;if(r.length===0)return d;const f=kt(n);for(let h=0;h<f.length;h+=Re){const l=f.slice(h,h+Re),u=Math.floor(Re/l.length),p=Yn(a`${a.identifier("id")}`,r,!1,u),_=l.map(I=>a`SELECT ${a.raw(`'${I.replaceAll("'","''")}'`)} AS __t__, id FROM ${a.identifier(I)} WHERE ${p}`);for(const I of H(c,yt(_))){const{id:T,__t__:v}=I;typeof v=="string"&&typeof T=="string"&&d.set(T,v)}}return d},Lt={assertRankPartitionLocal:Dt,ensureRankBackfilled:tt,onRead:R,rowToDocument:ve,schema:s,sql:c},In=(e,n,r)=>{const d=X(r,he);return d===void 0||H(c,a`SELECT 1 FROM ${a.identifier(e)} WHERE ${a.identifier("id")} = ${n} AND ${d}`).toArray().length>0},An=(e,n,r,d)=>_t(e,n,r,d)?(o?.({fields:Object.keys(Ge(r)),id:n,table:e}),!0):!1,Cn=async(e,n,r,d,f)=>{const h=oe(n,e);if(!h)return{applied:!1,doc:null};if(R(e,n),!In(e,n,r.where)||An(e,n,r.patch,h.row))return{applied:!1,doc:h.row};try{await f(r.patch)}catch(l){if(l instanceof ae&&l.kind==="occ"&&d)return;throw l}return{applied:!0,doc:oe(n,e)?.row??null}},Ft=async(e,n,r,d)=>{const{fetchLimit:f,limit:h,orderKeys:l,predicate:u}=await Ro(n,r,{canPushExists:At?Tn:void 0,existsPushMode:It==="always"?"always":"auto",fetcher:vt,maxRelationKeys:Ct,schema:s,tableName:e}),p=At?Er(d):Je,_=X(u,p,Ve),I=yn(e,_,$n(l),f);return{limit:h,orderKeys:l,statement:I}},U={system:Rn,async aggregate(e,n){const r=G(e,"aggregate");if(r)return R(e,O),r.aggregate(e,n);const d=s.tables[e];if(!d)throw new y("INTERNAL",`unknown table: ${e}`);if(We(n.op),n.op==="count")return U.count(e,{baseWhere:n.baseWhere,relationBaseWhere:n.relationBaseWhere,restrictsCounts:n.restrictsCounts,where:n.where});if(!n.field)throw new y("INTERNAL",`aggregate(${e}, { op: "${n.op}" }): "field" is required for non-count reducers`);R(e,O);const f=Te(d.softDeleteMode,void 0),h=K(K(n.baseWhere,n.where),f),l=await xe(h,e,n.relationBaseWhere),u=l!==h;if(d.aggregateIndexes&&!n.baseWhere&&!u){const g=Bn(d.aggregateIndexes,n.op,n.field,n.where);if(g){et(e,g.index);const P=rt(g.index.by??[],g.key),z=ot(e,g.index.name),Y=H(c,a`SELECT ${Be} AS value, ${ct} AS count FROM ${a.identifier(z)} WHERE ${Pe} = ${P}`).toArray()[0];return it(n.op,Y)}}rn(d,n.field,`aggregate(${e}, { op: "${n.op}", field: "${n.field}" })`);const p=X(l,he),_=We(n.op),I=we(n.field);let T=a`SELECT ${a.raw(_)}(${I}) AS value FROM ${a.identifier(e)}`;p&&(T=a`${T} WHERE ${p}`);const b=H(c,T).toArray()[0]?.value;return b??null},asId(e,n){const r=sn(s,e,n);if(r===null)throw new y("BAD_REQUEST",`asId("${e}", …): "${n}" is not a valid id for table "${e}"`,{status:400});return r},async count(e,n){const r=G(e,"count");if(r)return R(e,O),r.count(e,n);const d=s.tables[e];if(!d)throw new y("INTERNAL",`unknown table: ${e}`);const f=Fn(n);if(f.restrictsCounts)throw new st(e);R(e,O);const h=Te(d.softDeleteMode,void 0),l=K(K(f.baseWhere,f.where),h),u=await xe(l,e,f.relationBaseWhere),p=u!==l;if(d.aggregateIndexes&&!f.baseWhere&&!p){const v=Wn(d.aggregateIndexes,f.where);if(v){et(e,v.index);const b=rt(v.index.by??[],v.key),g=ot(e,v.index.name),P=H(c,a`SELECT ${Be} AS value FROM ${a.identifier(g)} WHERE ${Pe} = ${b}`).toArray();return P[0]===void 0?0:P[0].value??0}}const _=X(u,he);let I=a`SELECT COUNT(*) AS count FROM ${a.identifier(e)}`;return _&&(I=a`${I} WHERE ${_}`),H(c,I).one().count},async delete(e,n,r){const d=oe(e,n);if(!d){const v=_e(n);v&&await nt(v,n,[e],r);return}const{docJson:f,row:h,tableName:l}=d,u=s.tables[l],p=r?.hard===!0,_=!p&&u?.softDeleteMode?u:void 0,I=_?.softDeleteMode?.field;if(I&&h[I]!==null&&h[I]!==void 0)return;if(te(l,"before","delete")&&await ne("before","delete",{id:e,op:"delete",previous:h,table:l}),await Io({deletedId:e,deletedReference:v=>h[v],findHolders:async(v,b,g,P)=>(await Xe(v).findMany(v,{...P,includeDeleted:p,where:{[b]:g}})).page,onCascade:(v,b)=>Xe(v).delete(b,void 0,r),onRestrict:v=>{throw new ae(v,"restrict")},onSetNull:(v,b,g)=>Xe(v).patch(b,{[g]:null}),schema:s,tableName:l}),Ee(l),me(l),_&&I){const v={[I]:ce()},b={...h,...B(l),...v,_id:e};lt(_,v,b,de),je(c,l,Zt(l),[fe(b),e,f]),ke(l,e,b,h),De(l,e,void 0),Me(l,h,b),Se(l,e,h,void 0);const g=F(l,h,b);re?.invalidate(l,e,g),$e(l,e,"update",b),w({indexKeys:g,key:e,op:"update",row:b,table:l}),te(l,"after","delete")&&await ne("after","delete",{id:e,op:"delete",previous:h,table:l}),await J({id:e,op:"delete",table:l});return}je(c,l,tr(l),[e,f]),ke(l,e,void 0),De(l,e,void 0),Me(l,h,void 0),Se(l,e,h,void 0);const T=F(l,h);re?.invalidate(l,e,T),$e(l,e,"delete"),w({indexKeys:T,key:e,op:"delete",table:l}),te(l,"after","delete")&&await ne("after","delete",{id:e,op:"delete",previous:h,table:l}),await J({id:e,op:"delete",table:l})},async deleteAll(e,n){if(!s.tables[e])throw new y("INTERNAL",`unknown table: ${e}`);const r=Math.max(1,n?.chunkSize??wn),d=n?.hard===void 0?void 0:{hard:n.hard},f=G(e,"deleteAll");let h=0;return await j(async()=>{for(;;){const u=(await U.findMany(e,{limit:r})).page.map(p=>String(p._id));if(u.length===0)break;for(const p of u)await(f===void 0?U.delete(p,e,d):nt(f,e,[p],d)),h+=1;if(u.length<r)break}}),{deleted:h}},async deleteMany(e,n,r){He(e.length,n?.limit,"deleteMany");for(const d of e)await U.delete(d,r);return{deleted:e.length}},async deleteWhere(e,n,r){const d=G(e,"deleteWhere"),h=(await nn(d??U,e,n,r?.limit,"deleteWhere")).map(l=>String(l._id));if(d)return nt(d,e,h,void 0,{options:r});if(U.deleteMany===void 0)throw new y("INTERNAL",`ctx.db.${e}.deleteMany is unavailable: this writer has no batch delete`);return U.deleteMany(h,r,e)},async findFirst(e,n={}){return(await U.findMany(e,{...n,limit:1,omitContinueCursor:!0})).page[0]??null},async findFirstOrThrow(e,n={}){const r=await U.findFirst(e,n);if(r===null)throw new no(`findFirstOrThrow: no "${e}" document matched`);return r},async findMany(e,n={}){const r=G(e,"findMany");if(r)return R(e,O),r.findMany(e,n);const d=s.tables[e];if(!d)throw new y("INTERNAL",`unknown table: ${e}`);const f=!n.where&&!n.baseWhere;f?R(e,O):R(e);const{limit:h,orderKeys:l,statement:u}=await Ft(e,d,n,R),p=pe(c,u.text,...u.params).toArray();f&&!q&&L?.recordRead(p.length);const _=[];for(const b of p){const g=ve(b);g&&(_.push(g),!f&&typeof g._id=="string"&&R(e,g._id))}if(h===void 0)return n.with&&await Vt({groupedCounter:xt,fetcher:Ze,parents:_,...Jt(n),schema:s,tableName:e,with:n.with}),{continueCursor:null,isDone:!0,page:Gt(_,n.select,n.with)};const I=_.length>h,T=I?_.slice(0,h):_,v=T.at(-1);return n.with&&await Vt({fetcher:Ze,groupedCounter:xt,parents:T,...Jt(n),schema:s,tableName:e,with:n.with}),{continueCursor:I&&v&&n.omitContinueCursor!==!0?Ke(v,l):null,isDone:!I,page:Gt(T,n.select,n.with)}},async explain(e,n={}){const r=G(e,"explain");if(r)return r.explain(e,n);const d=s.tables[e];if(!d)throw new y("INTERNAL",`unknown table: ${e}`);const{statement:f}=await Ft(e,d,n,()=>{}),h=pe(c,`EXPLAIN QUERY PLAN ${f.text}`,...f.params).toArray();return{params:f.params,plan:h.map(l=>String(l.detail)),sql:f.text}},async get(e,n){if(!Object.hasOwn(s.tables,e))throw new y("BAD_REQUEST",`ctx.db.get(table, id): "${e}" is not a table in this schema`);const r=oe(n,e);if(!r){const d=_e(e);return d?d.get(e,n):null}return R(r.tableName,n),r.row},async lookupById(e,n){const r=oe(e,n);return r?(R(r.tableName,e),{row:r.row,tableName:r.tableName}):null},async groupBy(e,n){const r=G(e,"groupBy");if(r)return R(e,O),r.groupBy(e,n);const d=s.tables[e];if(!d)throw new y("INTERNAL",`unknown table: ${e}`);R(e,O);const f=n.agg??{op:"count"};if(We(f.op),f.op!=="count"&&!f.field)throw new y("INTERNAL",`groupBy(${e}, { agg: { op: "${f.op}" } }): "field" is required for non-count reducers`);const h=Te(d.softDeleteMode,void 0),l=K(K(n.baseWhere,n.where),h),u=await xe(l,e,n.relationBaseWhere),p=u!==l;if(d.aggregateIndexes&&!n.baseWhere&&!p){const g=qn(d.aggregateIndexes,f.op,f.field,n.by,n.where),P=g===void 0?0:Object.keys(g.partial).length,z=g?.index.by?.length??0;if(g&&(P===0||P===z)){et(e,g.index);const Y=ot(e,g.index.name),Q=Object.keys(g.partial),ue=[];if(Q.length===(g.index.by??[]).length&&Q.length>0){const Le=rt(g.index.by??[],g.partial),Fe=H(c,a`SELECT ${Be} AS value, ${ct} AS count FROM ${a.identifier(Y)} WHERE ${Pe} = ${Le}`).toArray();return Fe.length>0&&ue.push({key:{...g.partial},value:it(f.op,Fe[0])}),ue}const bn=H(c,a`SELECT ${Pe} AS key, ${Be} AS value, ${ct} AS count FROM ${a.identifier(Y)}`).toArray();for(const Le of bn){const Fe=kn(JSON.parse(Le.key));ue.push({key:Fe,value:it(f.op,Le)})}return ue}}for(const g of[...n.by,f.field]){if(g===void 0)continue;const P=g===f.field?`groupBy(${e}, { agg: { op: "${f.op}", field: "${g}" } })`:`groupBy(${e}, { by: [..."${g}"] })`;rn(d,g,P)}const _=X(u,he),I=n.by.map(g=>a`${we(g)} AS ${a.identifier(g)}`);if(f.op==="count")I.push(a`COUNT(*) AS value`);else{const{field:g}=f;if(g===void 0)throw new y("INTERNAL",`groupBy(${e}, { agg: { op: "${f.op}" } }): "field" is required for non-count reducers`);I.push(a`${a.raw(We(f.op))}(${we(g)}) AS value`)}let T=a`SELECT ${a.join(I,a`, `)} FROM ${a.identifier(e)}`;_&&(T=a`${T} WHERE ${_}`),T=a`${T} GROUP BY ${a.join(n.by.map(g=>we(g)),a`, `)}`;const v=H(c,T).toArray(),b=[];for(const g of v){const P={};for(const Y of n.by)P[Y]=Qn(d.shape[Y],g[Y]??null);const{value:z}=g;b.push({key:P,value:z==null?null:Number(z)})}return b},async insert(e,n,r){const d=G(e,"insert");if(d)return Tt(d,e,n,r,!0);const f=s.tables[e];if(!f)throw new y("INTERNAL",`unknown table: ${e}`);const h=r?.allowExplicitId===!0,l=Ue(f,ft(f,n,de),{supplied:n,trusted:h});let u;r?.clientId!==void 0?(cr(r.clientId),u=r.clientId):r?.allowExplicitId&&typeof l._id=="string"?(wt(l._id),u=l._id):u=Et();const p=r?.allowExplicitId&&typeof l._creationTime=="number"?l._creationTime:ce(),_={...l,...B(e),_creationTime:p,_id:u};return te(e,"before","insert")&&await ne("before","insert",{doc:{..._},id:u,op:"insert",table:e}),h||C(e,_),Ee(e),me(e),pt(c,e,Zo(e),[u,p,fe(_)]),Mt(e,u,_),te(e,"after","insert")&&await ne("after","insert",{doc:_,id:u,op:"insert",table:e}),await J({doc:_,id:u,op:"insert",table:e}),u},async insertManyUnsafe(e,n,r){if(He(n.length,r?.limit,"insertManyUnsafe"),n.length===0)return[];const d=G(e,"insert");if(d){const p=[];ar(s.tables[e],n,r?.allowExplicitId,de);for(const _ of n)N(_);for(const _ of n){const I=await d.insert(e,_,{allowExplicitId:r?.allowExplicitId});w({key:I,op:"insert",row:{..._,_id:I},table:e}),p.push(I)}return p}const f=s.tables[e];if(!f)throw new y("INTERNAL",`unknown table: ${e}`);Ee(e),me(e);const h=[];for(let p=0;p<n.length;p+=Oe)h.push(B(e));const l=r?.allowExplicitId===!0?void 0:vo(f),u=n.map((p,_)=>{const I=ft(f,p,de),T=l===void 0?I:Ue(l,I,{supplied:p}),v=r?.allowExplicitId===!0&&typeof T._id=="string"?T._id:void 0;v!==void 0&&wt(v);const b=v??Et(),g=r?.allowExplicitId===!0&&typeof T._creationTime=="number"?T._creationTime:ce(),P={...T,...h[Math.floor(_/Oe)],_creationTime:g,_id:b};return{creationTime:g,document:P,id:b}});for(const p of u)N(p.document);for(let p=0;p<u.length;p+=Oe){const _=a.join(u.slice(p,p+Oe).map(T=>a`(${T.id}, ${T.creationTime}, ${fe(T.document)})`),a`, `),I=fn("sqlite",a`INSERT INTO ${a.identifier(e)} (id, _creationTime, ${a.identifier(ie)}) VALUES ${_}`);pt(c,e,I.sql,I.params)}for(const{document:p,id:_}of u)Mt(e,_,p),await ee({doc:p,id:_,op:"insert",table:e});return u.map(p=>p.id)},async insertMany(e,n,r){He(n.length,r?.limit,"insertMany");const d=r?.skipDuplicates===!0,f=[],h=G(e,"insert");if(h)for(const u of n)N(u);const l=async u=>h?Tt(h,e,u,void 0,!1):U.insert(e,u);for(const u of n)try{f.push(await l(u))}catch(p){if(d&&p instanceof ae&&p.kind==="unique")f.push(null);else throw p}return f},normalizeId(e,n){return sn(s,e,n)},async patch(e,n,r,d){const f=oe(e,r);if(!f){const b=_e(r);if(b){N(n),await b.patch(e,n,r,d);return}throw new y("NOT_FOUND",`document not found: ${e}`)}const{docJson:h,row:l,tableName:u}=f,p=s.tables[u];if(!p)throw new y("INTERNAL",`unknown table: ${u}`);if(R(u,e),an("patch",n),_t(u,e,n,l)){o?.({fields:Object.keys(Ge(n)),id:e,table:u});return}const _=oo(p,n,l),I={...l,...Ge(_),...B(u),_id:e};lt(p,_,I,de);const T=Ue(p,I,{only:new Set(Object.keys(_)),previous:()=>l,tolerateStoredNull:!0});ro(d,l,T),te(u,"before","update")&&await ne("before","update",{doc:{...T},id:e,op:"update",previous:l,table:u}),C(u,T,l),Ee(u),me(u),je(c,u,Zt(u),[fe(T),e,h]),ke(u,e,T,l),De(u,e,T),Me(u,l,T),Se(u,e,l,T);const v=F(u,l,T);re?.invalidate(u,e,v),$e(u,e,"update",T),w({indexKeys:v,key:e,op:"update",row:T,table:u}),te(u,"after","update")&&await ne("after","update",{doc:T,id:e,op:"update",previous:l,table:u}),await J({doc:T,id:e,op:"update",table:u})},async patchIf(e,n,r){const d=G(e,"patchIf");if(d){if(d.patchIf===void 0)throw new y("INTERNAL",`ctx.db.patchIf on global table '${e}' is unsupported: its backend has no conditional write`);return N(r.patch),d.patchIf(e,n,r)}if(!s.tables[e])throw new y("INTERNAL",`unknown table: ${e}`);for(let f=1;f<=cn;f+=1){const h=await Cn(e,n,r,f<cn,l=>U.patch(n,l,e,{verify:r.verify}));if(h!==void 0)return h}throw new ae(`patchIf on "${e}" kept conflicting; the row changed on every attempt`,"occ")},async patchMany(e,n,r){He(e.length,n?.limit,"patchMany");for(const d of e)await U.patch(d.id,d.patch,r);return{patched:e.length}},async patchWhere(e,n,r){const d=G(e,"patchWhere")??U,h=(await nn(d,e,n.where,r?.limit,"patchWhere")).map(l=>({id:String(l._id),patch:n.patch}));if(U.patchMany===void 0)throw new y("INTERNAL",`ctx.db.${e}.patchMany is unavailable: this writer has no batch patch`);return await U.patchMany(h,r,e),{patched:h.length}},async related(e,n){return So(U,m,e,n)},relationEdges:m,deleteRereadTables:W,inTransaction:D,softDeleteFields:x,relationWrites:$,query(e){const n=G(e,"query");return n?(R(e,O),n.query(e)):_n(c,s,e,k,r=>{r?M(r):R(e,O)},r=>{q||L?.recordRead(r)})},async rank(e,n,r){const d=G(e,"rank");if(d)return R(e,O),d.rank(e,n,r);k(e,n,"rank");const f=s.tables[e];if(!f)throw new y("INTERNAL",`unknown table: ${e}`);const h=f.rankIndexes?.find(Q=>Q.name===n);if(!h)throw new y("INTERNAL",`unknown rankIndex "${n}" on table "${e}"`);if(Dt(e,f,h),r.restrictsCounts)throw new st(e);R(e,O),tt(e,h);const l=typeof r.row=="string"?r.row:r.row._id;if(!l)return null;const u=jt(e,h.name),p=h.sortBy.map((Q,ue)=>Kt(ue)),_=p.map(Q=>Ce(Q)).join(", "),I=H(c,a`SELECT ${a.identifier("__partition__")}, ${a.raw(_)} FROM ${a.identifier(u)} WHERE ${a.identifier("__id__")} = ${l}`).toArray(),[T]=I;if(T===void 0)return null;let v=T.__partition__;const b=K(r.baseWhere,r.where);at(b,s,e,"rank");const g=fo(h,b);if(g){const Q=ho(h.partitionBy??[],g);if(Q!==v)return null;v=Q}const P=p.map(Q=>T[Q]),{before:z,total:Y}=ln(c,u,p,h.sortBy,v,P,l);return{position:z+1,total:Y}},async rankBefore(e,n,r){if(le(e))throw new y("INTERNAL",`rankBefore is not supported on the global (.global()) table '${e}' — cross-shard rank cursors apply only to sharded tables`);const d=s.tables[e];if(!d)throw new y("INTERNAL",`unknown table: ${e}`);const f=d.rankIndexes?.find(p=>p.name===n);if(!f)throw new y("INTERNAL",`unknown rankIndex "${n}" on table "${e}"`);if(r.restrictsCounts)throw new st(e);R(e,O),tt(e,f);const h=jt(e,f.name),l=f.sortBy.map((p,_)=>Kt(_)),u=f.sortBy.map((p,_)=>Ae(r.sortValues[_]??null));return ln(c,h,l,f.sortBy,r.partitionKey,u,r.rowId)},async rankPage(e,n,r={}){at(K(r.baseWhere,r.where),s,e,"rankPage");const d=G(e,"rankPage");if(d)return R(e,O),d.rankPage(e,n,r);k(e,n,"rank");const{continueCursor:f,hasMore:h,rows:l}=Bt(Lt,e,n,r);return{continueCursor:f,isDone:!h,page:l.map(u=>u.doc)}},async rankPageRows(e,n,r={}){at(K(r.baseWhere,r.where),s,e,"rankPage"),k(e,n,"rank");const{directions:d,hasMore:f,rows:h}=Bt(Lt,e,n,r);return{directions:d,hasMore:f,rows:h}},async restore(e,n){const r=oe(e,n);if(!r){const h=_e(n);if(h?.restore){await h.restore(e,n);return}throw new y("NOT_FOUND",`document not found: ${e}`)}const d=s.tables[r.tableName]?.softDeleteMode?.field;if(!d)throw new y("INTERNAL",`ctx.db.restore: table "${r.tableName}" is not a .softDelete() table`);const f=r.row[d]!==null&&r.row[d]!==void 0;await U.patch(e,{[d]:null},n),f&&Se(r.tableName,e,void 0,r.row)},async replace(e,n,r,d){const f=oe(e,r);if(!f){const P=_e(r);if(P){N(n),await P.replace(e,n,r,d);return}throw new y("NOT_FOUND",`document not found: ${e}`)}const{docJson:h,row:l,tableName:u}=f,p=s.tables[u];if(!p)throw new y("INTERNAL",`unknown table: ${u}`);an("replace",n);const _=d?.allowExplicitId&&typeof n._creationTime=="number"?n._creationTime:void 0,I=typeof l._creationTime=="number"?l._creationTime:void 0,T=_??I??ce(),v={...n,...B(u),_creationTime:T,_id:e};lt(p,n,v,de);const b=d?.allowExplicitId===!0,g=Ue(p,v,{previous:()=>l,supplied:n,trusted:b});te(u,"before","update")&&await ne("before","update",{doc:{...g},id:e,op:"update",previous:l,table:u}),b||C(u,g,l),Ee(u),me(u),je(c,u,er(u),[T,fe(g),e,h]),ke(u,e,g,l),De(u,e,g),Me(u,l,g),Se(u,e,l,g),re?.invalidate(u,e,F(u,l,g)),$e(u,e,"update",g),w({indexKeys:F(u,l,g),key:e,op:"update",row:g,table:u}),te(u,"after","update")&&await ne("after","update",{doc:g,id:e,op:"update",previous:l,table:u}),await J({doc:g,id:e,op:"update",table:u})},async wipeShard(e){const n=new Set(e?.exclude),r=e?.tables,d=Object.entries(s.tables).filter(([u,p])=>n.has(u)||r!==void 0&&!r.includes(u)?!1:p.shardMode?.kind!=="global").map(([u])=>u);if(r!==void 0){for(const u of r)if(!s.tables[u])throw new y("INTERNAL",`wipeShard: unknown table: ${u}`)}const f={};let h=0;const{deleteAll:l}=U;if(l===void 0)throw new y("INTERNAL","wipeShard: this writer has no deleteAll");for(const u of d){const p=await l(u,{...e?.chunkSize===void 0?{}:{chunkSize:e.chunkSize},hard:!0});f[u]=p.deleted,h+=p.deleted}return{deleted:h,tables:f}}},xn={db:U,scheduler:mt};return t.enforceRls===!0?Co(U,s,(e,n)=>oe(e,n)?.tableName,(e,n)=>vn(e,n),m):U};export{mi as CDC_LOG_TABLE,Hi as IDEMPOTENCY_TABLE,mr as NotUniqueError,Bi as advanceClientWatermark,Si as applyCdcChanges,an as assertNoExplicitUndefined,wt as assertStorableRowId,cr as assertValidClientId,gi as backfillAggregateIndexes,yi as backfillRankIndexes,$i as backfillSearchIndexes,_i as bumpCdcEpoch,Ri as cdcCanVouchFor,Ti as cdcForkedError,vi as cdcSeqLeavingRows,Ii as cdcTouchesTables,Ai as cdcTrimmedError,Ci as compactCdcDocs,hi as createShardCtxDb,xi as cursorBelowRetainedFloor,Pi as migrateClientWatermark,bi as minCdcReplayableSeq,Mi as minCdcSeq,sn as normalizeIdStructurally,Di as readCdcChangeKeys,ki as readCdcChanges,Li as readCdcCursor,Fi as readCdcEpoch,Ui as readClientWatermark,Gi as readIdempotent,Qi as runShardMigrations,Ji as selectShapeMembers,zi as selectShapeRows,Ge as stripReservedPatchFields,qi as trimCdcChanges,ji as trimIdempotent,Ki as writeIdempotent};
@@ -1 +0,0 @@
1
- const a=(n,t)=>{const r=Math.max(n.length,t.length);let o=n.length^t.length;for(let e=0;e<r;e+=1){const i=e<n.length?n.charCodeAt(e):0,s=e<t.length?t.charCodeAt(e):0;o|=i^s}return o===0},d="LUNORA_RELAY_SECRET",f="x-lunora-relay-sig",l=n=>{const t=n?.[d];return typeof t=="string"&&t.length>0?t:void 0},u=async(n,t)=>{const r=new TextEncoder,o=await crypto.subtle.importKey("raw",r.encode(n),{hash:"SHA-256",name:"HMAC"},!1,["sign"]),e=await crypto.subtle.sign("HMAC",o,r.encode(t));return[...new Uint8Array(e)].map(i=>i.toString(16).padStart(2,"0")).join("")},y=async(n,t,r)=>{const o=l(n);return o===void 0?!0:t===null?!1:a(t,await u(o,r))},c=n=>{if(n===null||typeof n!="object")return;const t=n;return typeof t.idFromName=="function"&&typeof t.get=="function"?t:void 0},g=(n,t,r)=>{const o=c(n);if(o===void 0)return;const e=r===void 0?o:c(o.jurisdiction?.(r));if(e!==void 0)return typeof e.getByName=="function"?e.getByName(t):e.get(e.idFromName(t))},h=(n,t,r,o)=>t===void 0?void 0:g(n?.[t],r,o);export{f as RELAY_SIGNATURE_HEADER,l as siblingSecretOf,h as siblingStub,u as signSiblingBody,g as stubByName,y as verifySiblingBody};
@@ -1 +0,0 @@
1
- import{LunoraError as R}from"@lunora/errors";import{findRelated as m}from"./RELATED_DEFAULT_LIMIT-CVqN4JEu.mjs";const M=Symbol.for("lunora.ctxdb.rls-unwrap");class S extends R{table;constructor(n){super("RLS_REQUIRED",`ctx.db access to "${n}" is denied: the schema is marked .rls("required"), so this table is protected. Apply RLS with .use(rls(policies)) in the procedure, or mark the table .public() to opt it out.`,{name:"RlsRequiredError"}),this.table=n}}const b=o=>Object.entries(o.tables).filter(([,n])=>n.shardMode?.kind!=="global").map(([n])=>n),E=(o,n,l)=>{const d=n?.tables,u=new Set(n?.exclude);for(const r of o)(d===void 0||d.includes(r))&&!u.has(r)&&l(r)},y={aggregate:"loop-gated",asId:"ungated",assertPatchAllowed:"id-gated",cdcChangedTables:"ungated",count:"loop-gated",delete:"id-gated",deleteAll:"loop-gated",deleteMany:"id-gated",deleteWhere:"inline-table-gated",explain:"loop-gated",findFirst:"loop-gated",findFirstOrThrow:"loop-gated",findMany:"loop-gated",get:"inline-table-gated",groupBy:"loop-gated",insert:"loop-gated",insertMany:"loop-gated",insertManyUnsafe:"loop-gated",inTransaction:"ungated",lookupById:"id-gated",normalizeId:"ungated",patch:"id-gated",patchIf:"loop-gated",patchMany:"id-gated",patchWhere:"inline-table-gated",query:"loop-gated",rank:"loop-gated",rankBefore:"loop-gated",rankPage:"loop-gated",rankPageRows:"loop-gated",related:"rebound",relationEdges:"ungated",deleteRereadTables:"ungated",relationWrites:"ungated",softDeleteFields:"ungated",replace:"id-gated",restore:"id-gated",system:"ungated",wipeShard:"sweep-gated"},W=Object.entries(y).filter(([,o])=>o==="loop-gated").map(([o])=>o),I={related:(o,n)=>(...l)=>{const[d,u]=l;return m(o,n,d,u)}},O=Object.entries(y).filter(([,o])=>o==="rebound").map(([o])=>o),k=(o,n,l)=>{for(const d of O)typeof n[d]=="function"&&(o[d]=I[d](o,l))},P=(o,n,l,d,u=[])=>{if(n.rlsMode!=="required")return o;const r=o,p=e=>{const t=n.tables[e];return t!==void 0&&t.isPublic!==!0},i=e=>{if(p(e))throw new S(e)},c=async(e,t)=>{if(t!==void 0){i(t);return}const a=await l(e);a!==void 0&&i(a)},f=async(e,t)=>{if(t!==void 0){i(t);return}if(!d){for(const s of e)await c(s,t);return}const a=await d([...new Set(e)],t);for(const s of e){const h=a.get(s);h!==void 0&&i(h)}},g={...o,delete:async(e,t,a)=>(await c(e,t),r.delete(e,t,a)),deleteMany:async(e,t,a)=>(await f(e,a),r.deleteMany(e,t,a)),deleteWhere:r.deleteWhere?async(e,t,a)=>(i(e),await r.deleteWhere?.(e,t,a)):void 0,get:async(e,t)=>(i(e),await r.get(e,t)),lookupById:async(e,t)=>(await c(e,t),r.lookupById?.(e,t)??null),patch:async(e,t,a,s)=>(await c(e,a),r.patch(e,t,a,s)),patchMany:async(e,t,a)=>(await f(e.map(s=>s.id),a),r.patchMany(e,t,a)),assertPatchAllowed:async(e,t)=>(await c(e,t),r.assertPatchAllowed?.(e,t)),patchWhere:r.patchWhere?async(e,t,a)=>(i(e),await r.patchWhere?.(e,t,a)):void 0,replace:async(e,t,a,s)=>(await c(e,a),r.replace(e,t,a,s)),restore:async(e,t)=>(await c(e,t),r.restore?.(e,t))},w=r;for(const e of W){const t=w[e];typeof t=="function"&&(g[e]=(a,...s)=>(i(a),t.call(r,a,...s)))}if(k(g,r,u),r.wipeShard){const{wipeShard:e}=r;g.wipeShard=t=>(E(b(n),t,i),e.call(r,t))}return Object.defineProperty(g,M,{configurable:!0,enumerable:!1,value:o,writable:!1}),g};export{W as LOOP_GATED_METHODS,M as RLS_UNWRAP_SYMBOL,S as RlsRequiredError,y as WRITER_METHOD_GATING,P as guardWriter};
@@ -1 +0,0 @@
1
- import{createShardCtxDb as _}from"./NotUniqueError-DU8p6_p8.mjs";import{createRelayLink as I}from"./DEFAULT_MAX_RELAYS-B6rnl_9a.mjs";import{ConflictError as q}from"./ConflictError-C8GtJmjS.mjs";import{runShardMigrations as E}from"./runShardMigrations-C-0ec-sY.mjs";import{relayName as F}from"./DEFAULT_PROMOTION_THRESHOLDS-B3pRMuqb.mjs";const S=(O,m={})=>({_meta:{column:{notNull:!0,...m}},kind:O}),A=(O,m,x)=>{const{describe:v,expect:d,it:b}=x;v(`engine contract: ${O}`,()=>{v("optimistic concurrency",()=>{const w=u=>({tables:{items:{indexes:[],shape:{title:S("string"),version:S("number",{notNull:!1})},triggerMap:{clobber:{handler:()=>{u.exec(`UPDATE "items" SET "__doc__" = json_set("__doc__", '$.version', 99) WHERE "id" = 'i1'`)},op:"update",timing:"before"}}}}});b("raises a CONFLICT of kind `occ` when a write's snapshot is clobbered",async()=>{const{close:u,host:h}=m();try{const c=h.sql,p=w(c);E(c,p);const s=_({schema:p,sql:c});await s.insert("items",{_id:"i1",title:"first",version:1},{allowExplicitId:!0}),await d(s.patch("i1",{title:"second"})).rejects.toBeInstanceOf(q)}finally{u?.()}}),b("reports the conflict as CONFLICT/409 rather than retrying it away",async()=>{const{close:u,host:h}=m();try{const c=h.sql,p=w(c);E(c,p);const s=_({schema:p,sql:c});await s.insert("items",{_id:"i1",title:"first",version:1},{allowExplicitId:!0});let a;try{await s.patch("i1",{title:"second"})}catch(t){a=t}const e=a;d(e.code).toBe("CONFLICT"),d(e.kind).toBe("occ")}finally{u?.()}}),b("leaves the row readable and unchanged after a conflict",async()=>{const{close:u,host:h}=m();try{const c=h.sql,p=w(c);E(c,p);const s=_({schema:p,sql:c});await s.insert("items",{_id:"i1",title:"first",version:1},{allowExplicitId:!0});try{await s.patch("i1",{title:"second"})}catch{}const a=await s.get("items","i1");d(a?.title).toBe("first"),d(a?.version).toBe(99)}finally{u?.()}}),b("raises a CONFLICT of kind `trigger` when a trigger writes its own row through the db",async()=>{const{close:u,host:h}=m();try{const c=h.sql,p={tables:{items:{indexes:[],shape:{title:S("string"),version:S("number",{notNull:!1})},triggerMap:{recurse:{handler:async(t,o)=>{await t.db.patch(o.doc._id,{version:99})},op:"update",timing:"before"}}}}};E(c,p);const s=_({schema:p,sql:c});await s.insert("items",{_id:"i1",title:"first",version:1},{allowExplicitId:!0});let a;try{await s.patch("i1",{title:"second"})}catch(t){a=t}const e=a;d(e).toBeInstanceOf(q),d(e.code).toBe("CONFLICT"),d(e.kind).toBe("trigger")}finally{u?.()}})}),v("shape-poke ordering",()=>{const w="shard-a",u={args:{},name:"messages"},h=(e,t,o,n)=>e.accept(t?.()??{},{connectionId:o,shapes:{[n]:u}}),c=(e,t,o)=>{let n=0,l=0;const r=k=>()=>{throw new Error(`the relay poke path must not reach RelayHost.${k}`)},i={fetch:(k,C)=>{if(JSON.parse(C?.body??"{}").type!=="relay_shape_subscribe")return Promise.resolve(new Response(void 0,{status:204}));const N=o[l];if(l+=1,N===void 0)throw new Error("the relay asked for more seeds than this fixture supplies");return Promise.resolve(Response.json(N))}},f={get:()=>i,getByName:()=>i,idFromName:k=>k},g={buildShapeDiff:r("buildShapeDiff"),computeOpLogShapeSeed:r("computeOpLogShapeSeed"),currentCdcEpoch:r("currentCdcEpoch"),deliverWhisperLocal:r("deliverWhisperLocal"),doName:()=>F(w,0),env:()=>({SHARD:f}),getWebSockets:()=>e.getSockets(),maskMetadata:r("maskMetadata"),nextPokeId:()=>(n+=1,`poke-${String(n)}`),readAttachment:k=>k.deserializeAttachment?.(),recordShapePokeFanout:()=>{},resolveShape:r("resolveShape"),rlsMetadata:r("rlsMetadata"),shardBinding:()=>"SHARD",shardJurisdiction:()=>{},sql:()=>t},y=I(g);if(y===void 0)throw new Error("expected a relay link for a `…::relay::N` name");return y},p=e=>new Request("https://relay.internal/_lunora/relay",{body:JSON.stringify(e),headers:{"content-type":"application/json"},method:"POST"}),s=async(e,t,o)=>{const n=await e.seedRelayShape(t,o,u,{identity:void 0,userId:void 0});if(n!=="ok")throw new Error(`seed failed: ${JSON.stringify(n)}`)},a=(e={})=>p({...u,checkpoint:20,epoch:"e1",fromCursor:10,rowsPatch:[{id:"r1",op:"upsert",value:{title:"hello"}}],type:"relay_shape_poke",...e});b("frames a poke as pokeStart → pokePart per shape → pokeEnd, under one poke id",async()=>{const{close:e,createSocket:t,host:o,readFrames:n,sockets:l}=m();try{const r=c(l,o.sql,[{cursor:10,epoch:"e1",frames:[]}]),i=h(l,t,"c-alice","s1");await s(r,i,"s1"),await r.handleControl(a());const g=(await n(i)).map(y=>JSON.parse(y));d(g.map(y=>y.type)).toStrictEqual(["pokeStart","pokePart","pokeEnd"]),d(new Set(g.map(y=>y.pokeId)).size).toBe(1),d(g[1]?.shapeId).toBe("s1"),d(g[2]?.checkpoint).toBe(20)}finally{e?.()}}),b("delivers a poke only to sockets whose cursor matches, and advances them past it",async()=>{const{close:e,createSocket:t,host:o,readFrames:n,sockets:l}=m();try{const r=c(l,o.sql,[{cursor:10,epoch:"e1",frames:[]},{cursor:7,epoch:"e1",frames:[]}]),i=h(l,t,"c-alice","s1"),f=h(l,t,"c-bob","s2");await s(r,i,"s1"),await s(r,f,"s2"),await r.handleControl(a());const g=await n(i);d(g.length).toBe(3);const y=await n(f);d(y.length).toBe(0),await r.handleControl(a());const k=await n(i);d(k.length).toBe(3)}finally{e?.()}}),b("skips a socket whose cursor matches under a different CDC epoch",async()=>{const{close:e,createSocket:t,host:o,readFrames:n,sockets:l}=m();try{const r=c(l,o.sql,[{cursor:10,epoch:"e1",frames:[]}]),i=h(l,t,"c-alice","s1");await s(r,i,"s1"),await r.handleControl(a({epoch:"e2"}));const f=await n(i);d(f.length).toBe(0),await r.handleControl(a());const g=await n(i);d(g.length).toBe(3)}finally{e?.()}})}),v("orderBy null placement",()=>{const w=[["a",void 0],["b",3],["c",void 0],["d",1],["e",void 0],["f",3],["g",2],["h",void 0]],u=[{nulls:"first",sort:"asc"},{nulls:"last",sort:"asc"},{nulls:"first",sort:"desc"},{nulls:"last",sort:"desc"}],h=({nulls:p,sort:s})=>{const a=new Map(w.map(([t],o)=>[t,o])),e=s==="asc"?1:-1;return w.toSorted(([t,o],[n,l])=>o!==l?o===void 0?p==="first"?-1:1:l===void 0?p==="first"?1:-1:(o-l)*e:((a.get(t)??0)-(a.get(n)??0))*e).map(([t])=>t)},c=p=>p.map(s=>String(s.label));b("pages every placement in threes with no row skipped or repeated",async()=>{const{close:p,host:s}=m();try{const a=s.sql,e=u.map((r,i)=>`items_${String(i)}`),t={label:S("string"),score:S("number",{notNull:!1})},o={tables:Object.fromEntries(e.map(r=>[r,{indexes:[{fields:["score"],name:"by_score"}],shape:t}]))};E(a,o);let n=17e11;const l=_({clock:()=>(n+=1e3,n),schema:o,sql:a});for(const r of e)for(const[i,f]of w)await l.insert(r,f===void 0?{label:i}:{label:i,score:f});for(const[r,i]of u.entries()){const f=e[r]??"",g=await l.findMany(f,{orderBy:[{score:i}]});d(c(g.page)).toStrictEqual(h(i));const y=[];let k;for(let C=0;C<w.length+2;C+=1){const B=await l.findMany(f,{cursor:k,limit:3,orderBy:[{score:i}]});if(y.push(...c(B.page)),B.isDone)break;k=B.continueCursor}d(y).toStrictEqual(h(i))}}finally{p?.()}})}),v("RLS identity under live subscription",()=>{const w="shard-a",u={args:{},name:"lobby-messages"},h={args:{},name:"my-orders"},c=s=>{const a=[],e=[],t={fetch:(l,r)=>(a.push(JSON.parse(r?.body??"{}")),Promise.resolve(new Response(void 0,{status:204})))},n=I({buildShapeDiff:()=>[{id:"r1",op:"upsert",value:{}}],computeOpLogShapeSeed:()=>({baseCheckpoint:void 0,cursor:10,epoch:"e1",reset:!0,rowsPatch:[]}),currentCdcEpoch:()=>"e1",deliverWhisperLocal:()=>0,doName:()=>w,env:()=>({SHARD:{get:()=>t,getByName:()=>t,idFromName:l=>l}}),getWebSockets:()=>[],maskMetadata:()=>({columns:[]}),nextPokeId:()=>"poke-1",readAttachment:()=>({}),recordShapePokeFanout:()=>{},resolveShape:(l,r,i)=>(e.push(i),l===h.name?{columns:["id"],effectiveWhere:{org:i?.identity?.org??"anonymous"},global:!1,table:"orders"}:{columns:["id"],effectiveWhere:{room:"lobby"},global:!1,table:"messages"}),rlsMetadata:()=>({policies:[]}),shardBinding:()=>"SHARD",shardJurisdiction:()=>{},sql:()=>s});if(n===void 0)throw new Error("expected an owner link for an un-suffixed DO name");return{owner:n,posts:a,resolvedUnder:e}},p=async(s,a)=>{await s.handleControl(new Request("https://owner.internal/_lunora/relay",{body:JSON.stringify({...a,connectionId:"c-alice",identity:{org:"acme"},relayIndex:0,subId:"s1",type:"relay_shape_subscribe",userId:"u1"}),headers:{"content-type":"application/json"},method:"POST"}))};b("seeds a subscriber under its own forwarded identity, never the anonymous one",async()=>{const{close:s,host:a}=m();try{const{owner:e,resolvedUnder:t}=c(a.sql);await p(e,h),d(t.some(o=>o?.userId==="u1"&&o.identity?.org==="acme")).toBe(!0)}finally{s?.()}}),b("routes an identity-scoped shape to a per-socket poke, not the cohort multicast",async()=>{const{close:s,host:a}=m();try{const{owner:e,posts:t}=c(a.sql);await p(e,h),t.length=0,await e.onFlush(new Set(["orders"]),20);const o=t.filter(n=>n.type==="relay_shape_poke");d(o.length).toBe(1),d(o[0]?.targetConnectionId).toBe("c-alice")}finally{s?.()}}),b("still multicasts an identity-blind shape to the whole cohort",async()=>{const{close:s,host:a}=m();try{const{owner:e,posts:t}=c(a.sql);await p(e,u),t.length=0,await e.onFlush(new Set(["messages"]),20);const o=t.filter(n=>n.type==="relay_shape_poke");d(o.length).toBe(1),d(o[0]?.targetConnectionId).toBeUndefined()}finally{s?.()}})})})};export{A as defineEngineContractSuite};