@lunora/shard-engine 1.0.0-alpha.1 → 1.0.0-alpha.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1 +1 @@
1
- import{defineEngineContractSuite as t}from"../packem_shared/defineEngineContractSuite-CVwNQvzx.mjs";export{t as defineEngineContractSuite};
1
+ import{defineEngineContractSuite as t}from"../packem_shared/defineEngineContractSuite-BefTibvY.mjs";export{t as defineEngineContractSuite};
package/dist/index.d.mts CHANGED
@@ -1,6 +1,27 @@
1
1
  import { LunoraError } from '@lunora/errors';
2
2
  import { SQL, Name } from 'drizzle-orm';
3
3
  import { ShardHost, SocketHost, SocketHandle } from '@lunora/platform';
4
+ interface KeyRange {
5
+ hi: string;
6
+ index: string;
7
+ lo: string;
8
+ table: string;
9
+ }
10
+ interface IndexKeyEntry {
11
+ index: string;
12
+ key: string;
13
+ }
14
+ interface StagedCondition {
15
+ comparator: string;
16
+ field: string;
17
+ value: unknown;
18
+ }
19
+ declare const buildIndexRange: (table: string, index: string, fields: ReadonlyArray<string>, conditions: ReadonlyArray<StagedCondition>, serialize: (value: unknown) => unknown) => KeyRange | undefined;
20
+ declare const indexKeysForRow: (indexes: ReadonlyArray<{
21
+ fields: ReadonlyArray<string>;
22
+ name: string;
23
+ }>, row: Record<string, unknown>, serialize: (value: unknown) => unknown) => IndexKeyEntry[];
24
+ declare const keysTouchRanges: (ranges: ReadonlyArray<KeyRange> | undefined, keys: ReadonlyArray<IndexKeyEntry> | undefined) => boolean;
4
25
  type SystemTableName = "_scheduled_functions" | "_storage";
5
26
  interface ScheduledFunctionDoc {
6
27
  args: Record<string, unknown>;
@@ -339,6 +360,7 @@ interface GeoFilterBuilderLike {
339
360
  }) => GeoFilterBuilderLike;
340
361
  }
341
362
  interface TableReaderLike {
363
+ [Symbol.asyncIterator]: () => AsyncIterator<Record<string, unknown>>;
342
364
  collect: () => Promise<Record<string, unknown>[]>;
343
365
  filter: (predicate: (document: Record<string, unknown>) => boolean) => TableReaderLike;
344
366
  first: () => Promise<Record<string, unknown> | null>;
@@ -371,6 +393,7 @@ interface LifecycleDispatchInfo {
371
393
  userId: string | undefined;
372
394
  }
373
395
  interface MutationDelta {
396
+ indexKeys?: ReadonlyArray<IndexKeyEntry>;
374
397
  key: string;
375
398
  op: "insert" | "update" | "delete";
376
399
  row?: Record<string, unknown>;
@@ -535,6 +558,7 @@ interface CacheEntry {
535
558
  bytes: number;
536
559
  deps: Set<string>;
537
560
  lastUsed: number;
561
+ ranges: ReadonlyArray<KeyRange>;
538
562
  result: unknown;
539
563
  subscribers: Set<string>;
540
564
  }
@@ -546,6 +570,7 @@ interface ReactiveCacheOptions {
546
570
  declare class ReactiveCache {
547
571
  private readonly entries;
548
572
  private readonly tableIndex;
573
+ private readonly rangeIndex;
549
574
  private totalBytes;
550
575
  private hits;
551
576
  private misses;
@@ -555,8 +580,8 @@ declare class ReactiveCache {
555
580
  private readonly now;
556
581
  private monotonic;
557
582
  constructor(options?: ReactiveCacheOptions);
558
- run<R>(key: string, deps: Set<string>, run: () => Promise<R>): Promise<R>;
559
- invalidate(table: string, id: string): string[];
583
+ run<R>(key: string, deps: Set<string>, run: () => Promise<R>, ranges?: () => ReadonlyArray<KeyRange>): Promise<R>;
584
+ invalidate(table: string, id: string, indexKeys?: ReadonlyArray<IndexKeyEntry>): string[];
560
585
  invalidateTable(table: string): string[];
561
586
  subscribe(key: string, subscriberId: string): void;
562
587
  unsubscribe(key: string, subscriberId: string): void;
@@ -573,11 +598,36 @@ declare class ReactiveCache {
573
598
  hits: number;
574
599
  misses: number;
575
600
  };
601
+ private dropRangeDeps;
576
602
  private collectAndDrop;
577
603
  private dropEntry;
578
604
  private evict;
579
605
  }
580
606
  declare const reactiveCacheKey: (functionPath: string, args: Record<string, unknown>, identity: null | string) => string;
607
+ interface TransactionLimits {
608
+ maxReadRows: number;
609
+ maxWrittenBytes: number;
610
+ maxWrittenRows: number;
611
+ }
612
+ interface TransactionHeadroom {
613
+ readRows: number;
614
+ remainingReadRows: number;
615
+ remainingWrittenBytes: number;
616
+ remainingWrittenRows: number;
617
+ writtenBytes: number;
618
+ writtenRows: number;
619
+ }
620
+ declare const DEFAULT_TRANSACTION_LIMITS: TransactionLimits;
621
+ declare class TransactionHeadroomTracker {
622
+ private readRows;
623
+ private writtenRows;
624
+ private writtenBytes;
625
+ private readonly limits;
626
+ constructor(limits?: Partial<TransactionLimits>);
627
+ recordRead(count: number): void;
628
+ recordWrite(row: unknown): void;
629
+ headroom(): TransactionHeadroom;
630
+ }
581
631
  interface RunTriggersOptions {
582
632
  ctx: TriggerContextLike;
583
633
  event: TriggerEventLike;
@@ -712,10 +762,12 @@ interface CtxDbOptions {
712
762
  clock?: Clock;
713
763
  enforceRls?: boolean;
714
764
  globalDb?: DatabaseWriterLike;
765
+ headroom?: TransactionHeadroomTracker;
715
766
  idGenerator?: IdGenerator;
716
767
  maxRelationKeys?: number;
717
768
  onIndexUse?: IndexUseHook;
718
769
  onRead?: ReadHook;
770
+ onReadRange?: (range: KeyRange) => void;
719
771
  onWrite?: WriteHook;
720
772
  relationExistsPushDown?: "always" | "auto" | "never";
721
773
  scheduler?: SchedulerLike;
@@ -815,7 +867,11 @@ interface ShardSocketLike {
815
867
  }
816
868
  interface CompanionSyncDeps {
817
869
  broadcast: (delta: MutationDelta) => void;
818
- invalidateCache: (table: string, id: string) => void;
870
+ indexKeysFor: (table: string, document?: Record<string, unknown>) => ReadonlyArray<{
871
+ index: string;
872
+ key: string;
873
+ }> | undefined;
874
+ invalidateCache: (table: string, id: string, document?: Record<string, unknown>) => void;
819
875
  recordCdc: (table: string, id: string, op: "delete" | "insert" | "update", doc?: Record<string, unknown>) => void;
820
876
  schema: SchemaLike;
821
877
  sql: SqlExec;
@@ -1540,6 +1596,13 @@ declare const rankKeyFromDocument: (index: RankIndexDefinitionLike, document_: R
1540
1596
  rowId: string;
1541
1597
  sortValues: unknown[];
1542
1598
  };
1599
+ interface ReadFootprint {
1600
+ onRead: (table: string, idOrScan?: string) => void;
1601
+ onReadRange: (range: KeyRange) => void;
1602
+ ranges: () => Map<string, KeyRange[]> | undefined;
1603
+ tables: Set<string>;
1604
+ }
1605
+ declare const createReadFootprint: () => ReadFootprint;
1543
1606
  declare const DEFAULT_MAX_RELATION_KEYS = 5000;
1544
1607
  interface RelationExistsMarker {
1545
1608
  childWhere: WhereInput;
@@ -1875,6 +1938,14 @@ interface DrainableSink {
1875
1938
  declare const trySendFrame: (ws: FrameSink, frame: string) => boolean;
1876
1939
  declare const sendDeltaFrames: (ws: FrameSink, subId: string, deltaFrames: ReadonlyArray<string>, cursorSuffix: string) => boolean;
1877
1940
  declare const awaitWsDrain: (ws: DrainableSink) => Promise<void>;
1941
+ interface SubscriptionReadFootprint {
1942
+ ranges?: Map<string, KeyRange[]>;
1943
+ tables: Set<string>;
1944
+ }
1945
+ type ChangedKeys = Map<string, IndexKeyEntry[] | undefined>;
1946
+ declare const mergeChangedKeys: (pending: ChangedKeys | undefined, incoming: ChangedKeys | undefined, changed: Set<string>) => ChangedKeys;
1947
+ declare const recordChangedKeys: (pending: ChangedKeys | undefined, table: string, indexKeys: ReadonlyArray<IndexKeyEntry> | undefined) => ChangedKeys;
1948
+ declare const writeTouchesMemo: (memo: SubscriptionReadFootprint, changed: Set<string>, changedKeys: ChangedKeys | undefined) => boolean;
1878
1949
  type ConflictKind = "conflict" | "occ" | "restrict" | "trigger" | "unique";
1879
1950
  declare class ConflictError extends LunoraError {
1880
1951
  readonly kind: ConflictKind;
@@ -1902,4 +1973,4 @@ interface WhereSqlStrategy {
1902
1973
  serialize: SerializeValue;
1903
1974
  }
1904
1975
  declare const compileWhereSql: (where: WhereInput | undefined, strategy: WhereSqlStrategy) => SQL | undefined;
1905
- export { ADMIN_FUNCTIONS, ADMIN_FUNCTION_PREFIX, AGGREGATE_SQL_FUNCTION, AGG_COUNT, AGG_KEY, AGG_VALUE, AUDIT_LOG_TABLE, type AdvisorProcedure, type AdvisorProceduresResult, type AdvisoriesResult, type AdvisoryFinding, type AggregateIndexDefinitionLike, type AggregateOp, type AggregateOptions, type AggregateResult, type AggregateTally, type AppendAuditEntry, type ApplyOnDeleteOptions$1 as ApplyOnDeleteOptions, type AuditEntry, type AuditLogResult, type BroadcastDelta, CDC_LOG_TABLE, CDC_META_TABLE, CLIENT_WATERMARK_TABLE, type CacheEntry, type CapturedMailRow, type CdcChange, type Clock, type ColumnMeta, type ColumnMetaLike, type CompanionSync, type CompanionSyncDeps, ConflictError, type ConflictKind, type CountArgs, CountRlsUnsupportedError, type CreateWorkflowInstanceResult, type CtxDbOptions, DATA_MIGRATION_STATE_TABLE, DEFAULT_FANOUT_TOPIC_LIMIT, DEFAULT_MAX_RELATION_KEYS, DEFAULT_MAX_RELAYS, DEFAULT_PROMOTION_THRESHOLDS, DOC_COLUMN, type DataMigrationDocument, type DataMigrationLike, type DataMigrationTransform, type DatabaseWriterLike, type DependencyTracker, type DeployInfo, type ExportRow, type ExportShardAdminArgs, type ExportShardArgs, type ExternalSourceDiffResult, type ExternalSourceLike, FLAGS_FUNCTION_PREFIX, type FacetColumnOptions, type FacetColumnResult, type FacetValue, type FanoutMetricsResult, type FanoutPathCounters, type FanoutTopicStat, type FieldOperators, type FilterClause, type FilterOperator, type FlagEvaluation, type FlagsResult, type FunctionCallStat, type FunctionScanAttribution, type FunctionStatsResult, GEO_DEFAULT_PRECISION, GLOBAL_SHAPE_SNAPSHOT_TABLE, type GeoBoundingBox, type GeoFilterBuilderLike, type GeoIndexDefinitionLike, type GeoPoint, type GroupByEntry, type GroupByOptions, type GuardableSchema$1 as GuardableSchema, IDEMPOTENCY_TABLE, type IdGenerator, type IdempotentRecord, type ImportError, type ImportShardAdminArgs, type ImportShardArgs, type ImportShardResult, type IncrementalMaterializeResult, type IndexDefinitionLike, type IndexRangeBuilderLike, type LifecycleDispatchInfo, type LifecycleEvent, MAIL_RETENTION, MAIL_TABLE, MAX_PAGE_SIZE, MAX_SQL_ROWS, type MaskColumnMetadata, type MaskPoliciesResult, type MaterializeResult, type MigrationDirection, type MigrationRunResult, type MigrationStatus, type MigrationStatusRow, type MutationDelta, type NestedWith, NotFoundError, NotUniqueError, type OnDeleteActionLike, type OrderByClause, type OrderByInput, type OrderKey, OwnerRelay, type OwnerRelayFrame, type PaginationOptions, type PitrBookmarkResult, type PitrRestoreArgs, type PitrRestoreResult, type PitrStorage, type PokeFrameMeta, type PromotionState, type PromotionThresholds, QUEUE_TABLE, type QueryArgs, type QueryPage, type QueueMessageOutcome, type QueueMessageRow, type QueueMetadata, type QueuesResult, RANK_TIEBREAK, RELATION_EXISTS_KEY, RELATION_FUNCTION_PREFIX, RLS_UNWRAP_SYMBOL, type RankBeforeOptions, type RankBeforeResult, type RankDirection, type RankIndexDefinitionLike, type RankOptions, type RankPage, type RankPageComputation, type RankPageDeps, type RankPageOptions, type RankPageRow, type RankPageRowKey, type RankResult, type RankSortKeyLike, ReactiveCache, type ReactiveCacheOptions, type ReadHook, type ReadTablePageOptions, type RecordMailInput, type RecordQueueMessageInput, type RelationDefinitionLike, type RelationExistsMarker, type RelayAttach, type RelayDetach, type RelayFrame, type RelayHost, RelayMember, type RelayShapePoke, type RelayShapeSeed, type RelayShapeSubscribe, type RenderedSql, type ResolveRelationPredicatesOptions, type ResolveWithOptions, type ResolveWithResult, type ResolvedShape, type RestrictableQueryOptions, type RlsPoliciesResult, type RlsPolicyMetadata, RlsRequiredError, type RlsRoleMetadata, type RpcRequest, type RunDataMigrationOptions, type RunTriggersOptions, SCAN_DEP, SCHEMA_HISTORY_MAX_VERSIONS, SEARCH_STATE_TABLE, type SchedulableWorkflowReferenceLike, type ScheduledFunctionDoc, type SchedulerLike, type SchemaLike, type SearchFilterBuilderLike, type SearchIndexDefinitionLike, type SelectMatchingIdsOptions, type ServerDefaultContextLike, type SettingEntry, type SettingKind, type SettingsResult, type ShapePokePart, type ShapeRow, type ShapeRowOp, type ShapeSubscriptionQuery, type ShardRankPageResult, ShardRunner, type ShardRunnerOptions, type ShardSocketLike, type SocketAttachment, type SortDirection, type SourceClientLike, type SourceCursorLike, type SourceRefresh, type SqlConsoleResult, type SqlCursor, type SqlEngine, type SqlExec, type SqlLintResult, type StorageMetadata, type StorageReference, type StorageReferenceResult, type StorageRuleMetadata, type StorageRulesResult, type StudioFeaturesResult, type SubscriptionConnection, type SubscriptionEnvelope, type SubscriptionIdentity, type SubscriptionInfo, type SubscriptionQuery, type SubscriptionsResult, type SystemDatabaseReader, type SystemDoc, type SystemQuery, type SystemReaderOptions, type SystemReaderSchedulerLike, type SystemReaderStorageLike, type SystemTableName, type TableColumnsResult, type TableDefinitionLike, type TableIndexInfo, type TableIndexesResult, type TableInfo, type TablePage, type TableReaderLike, type TablesColumnsResult, type TransactionSqlLike, type TriggerContextLike, type TriggerDefinitionLike, type TriggerEventLike, type TriggerOpLike, type TriggerTimingLike, type TtlSweepSpec, type ValidatorLike, type WhereInput, type WhereSqlStrategy, type WithInput, type WorkflowInstanceState, type WorkflowInstanceStatusResult, type WorkflowMetadata, type WorkflowsResult, type WriteEvent, type WriteHook, advanceClientWatermark, aggUpsertSql, aggregateSqlFunction, aggregateTableName, appendAuditEntry, appendCdcChange, applyCdcChanges, applyOnDelete, applySelect, armRestore, assertFlatPredicate, assertReadonly, assertShapeShardable, assertValidClientId, awaitWsDrain, backfillAggregateIndexes, backfillRankIndexes, backfillSearchIndexes, backfillSearchIndexesForTable, boundingBoxCenter, boundingBoxGeohashes, buildPokeFrames, buildSeekBeforeWhere, buildSeekWhere, buildSettings, bumpCdcEpoch, clampPromotionThresholds, clearCapturedMail, clearQueueMessages, coerceAggregateNumber, compileWhereSql, computeRankPage, containsRelationPredicate, coveringGeohashes, createCompanionSync, createDependencyTracker, createFanoutCounters, createIndexSql, createRelayLink, createShardCtxDb, createSystemReader, decodeCursor, deleteGlobalShapeSnapshot, deleteGlobalShapeSnapshotsForConnection, depKey, diffExternalSource, diffGlobalMembership, distinctValues, encodeAggregateKey, encodeCursor, encodeGeohash, encodePartitionKey, encodeRowsPatch, ensureAuditTable, ensureMailTable, exportShardRows, exportShardTable, facetColumn, fanOutScalarCounts, findStorageReferences, foldAggregateTally, geoTableName, guardWriter, hasTrigger, haversineMeters, hydrateDocsById, importShardRows, isDevEnvironment, isFtsAvailable, isLossyBody, isRelationPredicate, isSoftDeleted, isSourceDue, jsonPath, jsonPathSql, liftSourceId, lintReadonlySql, listTables, matchesRankStaticWhere, matchesStaticWhere, materializeExternalRows, materializeExternalRowsIncremental, mergeWhere, migrateCdcLog, migrateCdcMeta, migrateClientWatermark, migrateGlobalShapeSnapshot, migrateIdempotency, migrateSearchState, minCdcSeq, nextPromotionState, normalizeCountArgument, normalizeIdStructurally, normalizeOrderKeys, normalizeSourceDocument, normalizeSourceValue, param, parseExportShardArgs, parseImportShardArgs, planAggregateLookup, pointInBoundingBox, projectColumns, pullExternalSourceIncrementalTick, pullExternalSourceTick, qualifiedJsonPath, qualifiedJsonPathSql, quoteIdentifier, rankKeyFromDocument as rankKeyFromDoc, rankTableName, reactiveCacheKey, readAggregateValue, readAuditLog, readBookmark, readCapturedMail, readCdcChanges, readCdcCursor, readCdcEpoch, readClientWatermark, readExternalSourceBaseline, readGlobalShapeSnapshot, readIdempotent, readMigrationStatus, readQueueMessageById, readQueueMessages, readSchemaHistory, readSchemaVersion, readSearchBackfillState, readTablePage, recordCapturedMail, recordFanoutPass, recordQueueMessages, recordSchemaVersion, relayCountFor, renderSql, resolveRankPartition, resolveRelationPredicates, resolveWith, rowToDocument, runDataMigration, runDrizzle, runExternalSourceTick, runReadonlySql, runRowValidators, runShardMigrations, runSocketPool, runSql, runTriggers, selectExpiredIds, selectExportTables, selectIndexForAggregate, selectIndexForCount, selectIndexForGroupBy, selectMatchingIds, selectShapeMemberIds, selectShapeRows, sendDeltaFrames, serializeSqlValue, shapeRoutingKey, softDeleteScope, sortColumnName, stableStringify, stableWireKey, subscriptionListDeltas, summarizeFanoutTopics, summarizeSubscriptions, tableColumns, tableFromDepKey, throwingScheduler, trimCdcChanges, trimIdempotent, tryRowToDocument, trySendFrame, validateImportRow, writeGlobalShapeSnapshot, writeIdempotent, writeSearchBackfillState };
1976
+ export { ADMIN_FUNCTIONS, ADMIN_FUNCTION_PREFIX, AGGREGATE_SQL_FUNCTION, AGG_COUNT, AGG_KEY, AGG_VALUE, AUDIT_LOG_TABLE, type AdvisorProcedure, type AdvisorProceduresResult, type AdvisoriesResult, type AdvisoryFinding, type AggregateIndexDefinitionLike, type AggregateOp, type AggregateOptions, type AggregateResult, type AggregateTally, type AppendAuditEntry, type ApplyOnDeleteOptions$1 as ApplyOnDeleteOptions, type AuditEntry, type AuditLogResult, type BroadcastDelta, CDC_LOG_TABLE, CDC_META_TABLE, CLIENT_WATERMARK_TABLE, type CacheEntry, type CapturedMailRow, type CdcChange, type ChangedKeys, type Clock, type ColumnMeta, type ColumnMetaLike, type CompanionSync, type CompanionSyncDeps, ConflictError, type ConflictKind, type CountArgs, CountRlsUnsupportedError, type CreateWorkflowInstanceResult, type CtxDbOptions, DATA_MIGRATION_STATE_TABLE, DEFAULT_FANOUT_TOPIC_LIMIT, DEFAULT_MAX_RELATION_KEYS, DEFAULT_MAX_RELAYS, DEFAULT_PROMOTION_THRESHOLDS, DEFAULT_TRANSACTION_LIMITS, DOC_COLUMN, type DataMigrationDocument, type DataMigrationLike, type DataMigrationTransform, type DatabaseWriterLike, type DependencyTracker, type DeployInfo, type ExportRow, type ExportShardAdminArgs, type ExportShardArgs, type ExternalSourceDiffResult, type ExternalSourceLike, FLAGS_FUNCTION_PREFIX, type FacetColumnOptions, type FacetColumnResult, type FacetValue, type FanoutMetricsResult, type FanoutPathCounters, type FanoutTopicStat, type FieldOperators, type FilterClause, type FilterOperator, type FlagEvaluation, type FlagsResult, type FunctionCallStat, type FunctionScanAttribution, type FunctionStatsResult, GEO_DEFAULT_PRECISION, GLOBAL_SHAPE_SNAPSHOT_TABLE, type GeoBoundingBox, type GeoFilterBuilderLike, type GeoIndexDefinitionLike, type GeoPoint, type GroupByEntry, type GroupByOptions, type GuardableSchema$1 as GuardableSchema, IDEMPOTENCY_TABLE, type IdGenerator, type IdempotentRecord, type ImportError, type ImportShardAdminArgs, type ImportShardArgs, type ImportShardResult, type IncrementalMaterializeResult, type IndexDefinitionLike, type IndexKeyEntry, type IndexRangeBuilderLike, type KeyRange, type LifecycleDispatchInfo, type LifecycleEvent, MAIL_RETENTION, MAIL_TABLE, MAX_PAGE_SIZE, MAX_SQL_ROWS, type MaskColumnMetadata, type MaskPoliciesResult, type MaterializeResult, type MigrationDirection, type MigrationRunResult, type MigrationStatus, type MigrationStatusRow, type MutationDelta, type NestedWith, NotFoundError, NotUniqueError, type OnDeleteActionLike, type OrderByClause, type OrderByInput, type OrderKey, OwnerRelay, type OwnerRelayFrame, type PaginationOptions, type PitrBookmarkResult, type PitrRestoreArgs, type PitrRestoreResult, type PitrStorage, type PokeFrameMeta, type PromotionState, type PromotionThresholds, QUEUE_TABLE, type QueryArgs, type QueryPage, type QueueMessageOutcome, type QueueMessageRow, type QueueMetadata, type QueuesResult, RANK_TIEBREAK, RELATION_EXISTS_KEY, RELATION_FUNCTION_PREFIX, RLS_UNWRAP_SYMBOL, type RankBeforeOptions, type RankBeforeResult, type RankDirection, type RankIndexDefinitionLike, type RankOptions, type RankPage, type RankPageComputation, type RankPageDeps, type RankPageOptions, type RankPageRow, type RankPageRowKey, type RankResult, type RankSortKeyLike, ReactiveCache, type ReactiveCacheOptions, type ReadFootprint, type ReadHook, type ReadTablePageOptions, type RecordMailInput, type RecordQueueMessageInput, type RelationDefinitionLike, type RelationExistsMarker, type RelayAttach, type RelayDetach, type RelayFrame, type RelayHost, RelayMember, type RelayShapePoke, type RelayShapeSeed, type RelayShapeSubscribe, type RenderedSql, type ResolveRelationPredicatesOptions, type ResolveWithOptions, type ResolveWithResult, type ResolvedShape, type RestrictableQueryOptions, type RlsPoliciesResult, type RlsPolicyMetadata, RlsRequiredError, type RlsRoleMetadata, type RpcRequest, type RunDataMigrationOptions, type RunTriggersOptions, SCAN_DEP, SCHEMA_HISTORY_MAX_VERSIONS, SEARCH_STATE_TABLE, type SchedulableWorkflowReferenceLike, type ScheduledFunctionDoc, type SchedulerLike, type SchemaLike, type SearchFilterBuilderLike, type SearchIndexDefinitionLike, type SelectMatchingIdsOptions, type ServerDefaultContextLike, type SettingEntry, type SettingKind, type SettingsResult, type ShapePokePart, type ShapeRow, type ShapeRowOp, type ShapeSubscriptionQuery, type ShardRankPageResult, ShardRunner, type ShardRunnerOptions, type ShardSocketLike, type SocketAttachment, type SortDirection, type SourceClientLike, type SourceCursorLike, type SourceRefresh, type SqlConsoleResult, type SqlCursor, type SqlEngine, type SqlExec, type SqlLintResult, type StorageMetadata, type StorageReference, type StorageReferenceResult, type StorageRuleMetadata, type StorageRulesResult, type StudioFeaturesResult, type SubscriptionConnection, type SubscriptionEnvelope, type SubscriptionIdentity, type SubscriptionInfo, type SubscriptionQuery, type SubscriptionReadFootprint, type SubscriptionsResult, type SystemDatabaseReader, type SystemDoc, type SystemQuery, type SystemReaderOptions, type SystemReaderSchedulerLike, type SystemReaderStorageLike, type SystemTableName, type TableColumnsResult, type TableDefinitionLike, type TableIndexInfo, type TableIndexesResult, type TableInfo, type TablePage, type TableReaderLike, type TablesColumnsResult, type TransactionHeadroom, TransactionHeadroomTracker, type TransactionLimits, type TransactionSqlLike, type TriggerContextLike, type TriggerDefinitionLike, type TriggerEventLike, type TriggerOpLike, type TriggerTimingLike, type TtlSweepSpec, type ValidatorLike, type WhereInput, type WhereSqlStrategy, type WithInput, type WorkflowInstanceState, type WorkflowInstanceStatusResult, type WorkflowMetadata, type WorkflowsResult, type WriteEvent, type WriteHook, advanceClientWatermark, aggUpsertSql, aggregateSqlFunction, aggregateTableName, appendAuditEntry, appendCdcChange, applyCdcChanges, applyOnDelete, applySelect, armRestore, assertFlatPredicate, assertReadonly, assertShapeShardable, assertValidClientId, awaitWsDrain, backfillAggregateIndexes, backfillRankIndexes, backfillSearchIndexes, backfillSearchIndexesForTable, boundingBoxCenter, boundingBoxGeohashes, buildIndexRange, buildPokeFrames, buildSeekBeforeWhere, buildSeekWhere, buildSettings, bumpCdcEpoch, clampPromotionThresholds, clearCapturedMail, clearQueueMessages, coerceAggregateNumber, compileWhereSql, computeRankPage, containsRelationPredicate, coveringGeohashes, createCompanionSync, createDependencyTracker, createFanoutCounters, createIndexSql, createReadFootprint, createRelayLink, createShardCtxDb, createSystemReader, decodeCursor, deleteGlobalShapeSnapshot, deleteGlobalShapeSnapshotsForConnection, depKey, diffExternalSource, diffGlobalMembership, distinctValues, encodeAggregateKey, encodeCursor, encodeGeohash, encodePartitionKey, encodeRowsPatch, ensureAuditTable, ensureMailTable, exportShardRows, exportShardTable, facetColumn, fanOutScalarCounts, findStorageReferences, foldAggregateTally, geoTableName, guardWriter, hasTrigger, haversineMeters, hydrateDocsById, importShardRows, indexKeysForRow, isDevEnvironment, isFtsAvailable, isLossyBody, isRelationPredicate, isSoftDeleted, isSourceDue, jsonPath, jsonPathSql, keysTouchRanges, liftSourceId, lintReadonlySql, listTables, matchesRankStaticWhere, matchesStaticWhere, materializeExternalRows, materializeExternalRowsIncremental, mergeChangedKeys, mergeWhere, migrateCdcLog, migrateCdcMeta, migrateClientWatermark, migrateGlobalShapeSnapshot, migrateIdempotency, migrateSearchState, minCdcSeq, nextPromotionState, normalizeCountArgument, normalizeIdStructurally, normalizeOrderKeys, normalizeSourceDocument, normalizeSourceValue, param, parseExportShardArgs, parseImportShardArgs, planAggregateLookup, pointInBoundingBox, projectColumns, pullExternalSourceIncrementalTick, pullExternalSourceTick, qualifiedJsonPath, qualifiedJsonPathSql, quoteIdentifier, rankKeyFromDocument as rankKeyFromDoc, rankTableName, reactiveCacheKey, readAggregateValue, readAuditLog, readBookmark, readCapturedMail, readCdcChanges, readCdcCursor, readCdcEpoch, readClientWatermark, readExternalSourceBaseline, readGlobalShapeSnapshot, readIdempotent, readMigrationStatus, readQueueMessageById, readQueueMessages, readSchemaHistory, readSchemaVersion, readSearchBackfillState, readTablePage, recordCapturedMail, recordChangedKeys, recordFanoutPass, recordQueueMessages, recordSchemaVersion, relayCountFor, renderSql, resolveRankPartition, resolveRelationPredicates, resolveWith, rowToDocument, runDataMigration, runDrizzle, runExternalSourceTick, runReadonlySql, runRowValidators, runShardMigrations, runSocketPool, runSql, runTriggers, selectExpiredIds, selectExportTables, selectIndexForAggregate, selectIndexForCount, selectIndexForGroupBy, selectMatchingIds, selectShapeMemberIds, selectShapeRows, sendDeltaFrames, serializeSqlValue, shapeRoutingKey, softDeleteScope, sortColumnName, stableStringify, stableWireKey, subscriptionListDeltas, summarizeFanoutTopics, summarizeSubscriptions, tableColumns, tableFromDepKey, throwingScheduler, trimCdcChanges, trimIdempotent, tryRowToDocument, trySendFrame, validateImportRow, writeGlobalShapeSnapshot, writeIdempotent, writeSearchBackfillState, writeTouchesMemo };
package/dist/index.d.ts CHANGED
@@ -1,6 +1,27 @@
1
1
  import { LunoraError } from '@lunora/errors';
2
2
  import { SQL, Name } from 'drizzle-orm';
3
3
  import { ShardHost, SocketHost, SocketHandle } from '@lunora/platform';
4
+ interface KeyRange {
5
+ hi: string;
6
+ index: string;
7
+ lo: string;
8
+ table: string;
9
+ }
10
+ interface IndexKeyEntry {
11
+ index: string;
12
+ key: string;
13
+ }
14
+ interface StagedCondition {
15
+ comparator: string;
16
+ field: string;
17
+ value: unknown;
18
+ }
19
+ declare const buildIndexRange: (table: string, index: string, fields: ReadonlyArray<string>, conditions: ReadonlyArray<StagedCondition>, serialize: (value: unknown) => unknown) => KeyRange | undefined;
20
+ declare const indexKeysForRow: (indexes: ReadonlyArray<{
21
+ fields: ReadonlyArray<string>;
22
+ name: string;
23
+ }>, row: Record<string, unknown>, serialize: (value: unknown) => unknown) => IndexKeyEntry[];
24
+ declare const keysTouchRanges: (ranges: ReadonlyArray<KeyRange> | undefined, keys: ReadonlyArray<IndexKeyEntry> | undefined) => boolean;
4
25
  type SystemTableName = "_scheduled_functions" | "_storage";
5
26
  interface ScheduledFunctionDoc {
6
27
  args: Record<string, unknown>;
@@ -339,6 +360,7 @@ interface GeoFilterBuilderLike {
339
360
  }) => GeoFilterBuilderLike;
340
361
  }
341
362
  interface TableReaderLike {
363
+ [Symbol.asyncIterator]: () => AsyncIterator<Record<string, unknown>>;
342
364
  collect: () => Promise<Record<string, unknown>[]>;
343
365
  filter: (predicate: (document: Record<string, unknown>) => boolean) => TableReaderLike;
344
366
  first: () => Promise<Record<string, unknown> | null>;
@@ -371,6 +393,7 @@ interface LifecycleDispatchInfo {
371
393
  userId: string | undefined;
372
394
  }
373
395
  interface MutationDelta {
396
+ indexKeys?: ReadonlyArray<IndexKeyEntry>;
374
397
  key: string;
375
398
  op: "insert" | "update" | "delete";
376
399
  row?: Record<string, unknown>;
@@ -535,6 +558,7 @@ interface CacheEntry {
535
558
  bytes: number;
536
559
  deps: Set<string>;
537
560
  lastUsed: number;
561
+ ranges: ReadonlyArray<KeyRange>;
538
562
  result: unknown;
539
563
  subscribers: Set<string>;
540
564
  }
@@ -546,6 +570,7 @@ interface ReactiveCacheOptions {
546
570
  declare class ReactiveCache {
547
571
  private readonly entries;
548
572
  private readonly tableIndex;
573
+ private readonly rangeIndex;
549
574
  private totalBytes;
550
575
  private hits;
551
576
  private misses;
@@ -555,8 +580,8 @@ declare class ReactiveCache {
555
580
  private readonly now;
556
581
  private monotonic;
557
582
  constructor(options?: ReactiveCacheOptions);
558
- run<R>(key: string, deps: Set<string>, run: () => Promise<R>): Promise<R>;
559
- invalidate(table: string, id: string): string[];
583
+ run<R>(key: string, deps: Set<string>, run: () => Promise<R>, ranges?: () => ReadonlyArray<KeyRange>): Promise<R>;
584
+ invalidate(table: string, id: string, indexKeys?: ReadonlyArray<IndexKeyEntry>): string[];
560
585
  invalidateTable(table: string): string[];
561
586
  subscribe(key: string, subscriberId: string): void;
562
587
  unsubscribe(key: string, subscriberId: string): void;
@@ -573,11 +598,36 @@ declare class ReactiveCache {
573
598
  hits: number;
574
599
  misses: number;
575
600
  };
601
+ private dropRangeDeps;
576
602
  private collectAndDrop;
577
603
  private dropEntry;
578
604
  private evict;
579
605
  }
580
606
  declare const reactiveCacheKey: (functionPath: string, args: Record<string, unknown>, identity: null | string) => string;
607
+ interface TransactionLimits {
608
+ maxReadRows: number;
609
+ maxWrittenBytes: number;
610
+ maxWrittenRows: number;
611
+ }
612
+ interface TransactionHeadroom {
613
+ readRows: number;
614
+ remainingReadRows: number;
615
+ remainingWrittenBytes: number;
616
+ remainingWrittenRows: number;
617
+ writtenBytes: number;
618
+ writtenRows: number;
619
+ }
620
+ declare const DEFAULT_TRANSACTION_LIMITS: TransactionLimits;
621
+ declare class TransactionHeadroomTracker {
622
+ private readRows;
623
+ private writtenRows;
624
+ private writtenBytes;
625
+ private readonly limits;
626
+ constructor(limits?: Partial<TransactionLimits>);
627
+ recordRead(count: number): void;
628
+ recordWrite(row: unknown): void;
629
+ headroom(): TransactionHeadroom;
630
+ }
581
631
  interface RunTriggersOptions {
582
632
  ctx: TriggerContextLike;
583
633
  event: TriggerEventLike;
@@ -712,10 +762,12 @@ interface CtxDbOptions {
712
762
  clock?: Clock;
713
763
  enforceRls?: boolean;
714
764
  globalDb?: DatabaseWriterLike;
765
+ headroom?: TransactionHeadroomTracker;
715
766
  idGenerator?: IdGenerator;
716
767
  maxRelationKeys?: number;
717
768
  onIndexUse?: IndexUseHook;
718
769
  onRead?: ReadHook;
770
+ onReadRange?: (range: KeyRange) => void;
719
771
  onWrite?: WriteHook;
720
772
  relationExistsPushDown?: "always" | "auto" | "never";
721
773
  scheduler?: SchedulerLike;
@@ -815,7 +867,11 @@ interface ShardSocketLike {
815
867
  }
816
868
  interface CompanionSyncDeps {
817
869
  broadcast: (delta: MutationDelta) => void;
818
- invalidateCache: (table: string, id: string) => void;
870
+ indexKeysFor: (table: string, document?: Record<string, unknown>) => ReadonlyArray<{
871
+ index: string;
872
+ key: string;
873
+ }> | undefined;
874
+ invalidateCache: (table: string, id: string, document?: Record<string, unknown>) => void;
819
875
  recordCdc: (table: string, id: string, op: "delete" | "insert" | "update", doc?: Record<string, unknown>) => void;
820
876
  schema: SchemaLike;
821
877
  sql: SqlExec;
@@ -1540,6 +1596,13 @@ declare const rankKeyFromDocument: (index: RankIndexDefinitionLike, document_: R
1540
1596
  rowId: string;
1541
1597
  sortValues: unknown[];
1542
1598
  };
1599
+ interface ReadFootprint {
1600
+ onRead: (table: string, idOrScan?: string) => void;
1601
+ onReadRange: (range: KeyRange) => void;
1602
+ ranges: () => Map<string, KeyRange[]> | undefined;
1603
+ tables: Set<string>;
1604
+ }
1605
+ declare const createReadFootprint: () => ReadFootprint;
1543
1606
  declare const DEFAULT_MAX_RELATION_KEYS = 5000;
1544
1607
  interface RelationExistsMarker {
1545
1608
  childWhere: WhereInput;
@@ -1875,6 +1938,14 @@ interface DrainableSink {
1875
1938
  declare const trySendFrame: (ws: FrameSink, frame: string) => boolean;
1876
1939
  declare const sendDeltaFrames: (ws: FrameSink, subId: string, deltaFrames: ReadonlyArray<string>, cursorSuffix: string) => boolean;
1877
1940
  declare const awaitWsDrain: (ws: DrainableSink) => Promise<void>;
1941
+ interface SubscriptionReadFootprint {
1942
+ ranges?: Map<string, KeyRange[]>;
1943
+ tables: Set<string>;
1944
+ }
1945
+ type ChangedKeys = Map<string, IndexKeyEntry[] | undefined>;
1946
+ declare const mergeChangedKeys: (pending: ChangedKeys | undefined, incoming: ChangedKeys | undefined, changed: Set<string>) => ChangedKeys;
1947
+ declare const recordChangedKeys: (pending: ChangedKeys | undefined, table: string, indexKeys: ReadonlyArray<IndexKeyEntry> | undefined) => ChangedKeys;
1948
+ declare const writeTouchesMemo: (memo: SubscriptionReadFootprint, changed: Set<string>, changedKeys: ChangedKeys | undefined) => boolean;
1878
1949
  type ConflictKind = "conflict" | "occ" | "restrict" | "trigger" | "unique";
1879
1950
  declare class ConflictError extends LunoraError {
1880
1951
  readonly kind: ConflictKind;
@@ -1902,4 +1973,4 @@ interface WhereSqlStrategy {
1902
1973
  serialize: SerializeValue;
1903
1974
  }
1904
1975
  declare const compileWhereSql: (where: WhereInput | undefined, strategy: WhereSqlStrategy) => SQL | undefined;
1905
- export { ADMIN_FUNCTIONS, ADMIN_FUNCTION_PREFIX, AGGREGATE_SQL_FUNCTION, AGG_COUNT, AGG_KEY, AGG_VALUE, AUDIT_LOG_TABLE, type AdvisorProcedure, type AdvisorProceduresResult, type AdvisoriesResult, type AdvisoryFinding, type AggregateIndexDefinitionLike, type AggregateOp, type AggregateOptions, type AggregateResult, type AggregateTally, type AppendAuditEntry, type ApplyOnDeleteOptions$1 as ApplyOnDeleteOptions, type AuditEntry, type AuditLogResult, type BroadcastDelta, CDC_LOG_TABLE, CDC_META_TABLE, CLIENT_WATERMARK_TABLE, type CacheEntry, type CapturedMailRow, type CdcChange, type Clock, type ColumnMeta, type ColumnMetaLike, type CompanionSync, type CompanionSyncDeps, ConflictError, type ConflictKind, type CountArgs, CountRlsUnsupportedError, type CreateWorkflowInstanceResult, type CtxDbOptions, DATA_MIGRATION_STATE_TABLE, DEFAULT_FANOUT_TOPIC_LIMIT, DEFAULT_MAX_RELATION_KEYS, DEFAULT_MAX_RELAYS, DEFAULT_PROMOTION_THRESHOLDS, DOC_COLUMN, type DataMigrationDocument, type DataMigrationLike, type DataMigrationTransform, type DatabaseWriterLike, type DependencyTracker, type DeployInfo, type ExportRow, type ExportShardAdminArgs, type ExportShardArgs, type ExternalSourceDiffResult, type ExternalSourceLike, FLAGS_FUNCTION_PREFIX, type FacetColumnOptions, type FacetColumnResult, type FacetValue, type FanoutMetricsResult, type FanoutPathCounters, type FanoutTopicStat, type FieldOperators, type FilterClause, type FilterOperator, type FlagEvaluation, type FlagsResult, type FunctionCallStat, type FunctionScanAttribution, type FunctionStatsResult, GEO_DEFAULT_PRECISION, GLOBAL_SHAPE_SNAPSHOT_TABLE, type GeoBoundingBox, type GeoFilterBuilderLike, type GeoIndexDefinitionLike, type GeoPoint, type GroupByEntry, type GroupByOptions, type GuardableSchema$1 as GuardableSchema, IDEMPOTENCY_TABLE, type IdGenerator, type IdempotentRecord, type ImportError, type ImportShardAdminArgs, type ImportShardArgs, type ImportShardResult, type IncrementalMaterializeResult, type IndexDefinitionLike, type IndexRangeBuilderLike, type LifecycleDispatchInfo, type LifecycleEvent, MAIL_RETENTION, MAIL_TABLE, MAX_PAGE_SIZE, MAX_SQL_ROWS, type MaskColumnMetadata, type MaskPoliciesResult, type MaterializeResult, type MigrationDirection, type MigrationRunResult, type MigrationStatus, type MigrationStatusRow, type MutationDelta, type NestedWith, NotFoundError, NotUniqueError, type OnDeleteActionLike, type OrderByClause, type OrderByInput, type OrderKey, OwnerRelay, type OwnerRelayFrame, type PaginationOptions, type PitrBookmarkResult, type PitrRestoreArgs, type PitrRestoreResult, type PitrStorage, type PokeFrameMeta, type PromotionState, type PromotionThresholds, QUEUE_TABLE, type QueryArgs, type QueryPage, type QueueMessageOutcome, type QueueMessageRow, type QueueMetadata, type QueuesResult, RANK_TIEBREAK, RELATION_EXISTS_KEY, RELATION_FUNCTION_PREFIX, RLS_UNWRAP_SYMBOL, type RankBeforeOptions, type RankBeforeResult, type RankDirection, type RankIndexDefinitionLike, type RankOptions, type RankPage, type RankPageComputation, type RankPageDeps, type RankPageOptions, type RankPageRow, type RankPageRowKey, type RankResult, type RankSortKeyLike, ReactiveCache, type ReactiveCacheOptions, type ReadHook, type ReadTablePageOptions, type RecordMailInput, type RecordQueueMessageInput, type RelationDefinitionLike, type RelationExistsMarker, type RelayAttach, type RelayDetach, type RelayFrame, type RelayHost, RelayMember, type RelayShapePoke, type RelayShapeSeed, type RelayShapeSubscribe, type RenderedSql, type ResolveRelationPredicatesOptions, type ResolveWithOptions, type ResolveWithResult, type ResolvedShape, type RestrictableQueryOptions, type RlsPoliciesResult, type RlsPolicyMetadata, RlsRequiredError, type RlsRoleMetadata, type RpcRequest, type RunDataMigrationOptions, type RunTriggersOptions, SCAN_DEP, SCHEMA_HISTORY_MAX_VERSIONS, SEARCH_STATE_TABLE, type SchedulableWorkflowReferenceLike, type ScheduledFunctionDoc, type SchedulerLike, type SchemaLike, type SearchFilterBuilderLike, type SearchIndexDefinitionLike, type SelectMatchingIdsOptions, type ServerDefaultContextLike, type SettingEntry, type SettingKind, type SettingsResult, type ShapePokePart, type ShapeRow, type ShapeRowOp, type ShapeSubscriptionQuery, type ShardRankPageResult, ShardRunner, type ShardRunnerOptions, type ShardSocketLike, type SocketAttachment, type SortDirection, type SourceClientLike, type SourceCursorLike, type SourceRefresh, type SqlConsoleResult, type SqlCursor, type SqlEngine, type SqlExec, type SqlLintResult, type StorageMetadata, type StorageReference, type StorageReferenceResult, type StorageRuleMetadata, type StorageRulesResult, type StudioFeaturesResult, type SubscriptionConnection, type SubscriptionEnvelope, type SubscriptionIdentity, type SubscriptionInfo, type SubscriptionQuery, type SubscriptionsResult, type SystemDatabaseReader, type SystemDoc, type SystemQuery, type SystemReaderOptions, type SystemReaderSchedulerLike, type SystemReaderStorageLike, type SystemTableName, type TableColumnsResult, type TableDefinitionLike, type TableIndexInfo, type TableIndexesResult, type TableInfo, type TablePage, type TableReaderLike, type TablesColumnsResult, type TransactionSqlLike, type TriggerContextLike, type TriggerDefinitionLike, type TriggerEventLike, type TriggerOpLike, type TriggerTimingLike, type TtlSweepSpec, type ValidatorLike, type WhereInput, type WhereSqlStrategy, type WithInput, type WorkflowInstanceState, type WorkflowInstanceStatusResult, type WorkflowMetadata, type WorkflowsResult, type WriteEvent, type WriteHook, advanceClientWatermark, aggUpsertSql, aggregateSqlFunction, aggregateTableName, appendAuditEntry, appendCdcChange, applyCdcChanges, applyOnDelete, applySelect, armRestore, assertFlatPredicate, assertReadonly, assertShapeShardable, assertValidClientId, awaitWsDrain, backfillAggregateIndexes, backfillRankIndexes, backfillSearchIndexes, backfillSearchIndexesForTable, boundingBoxCenter, boundingBoxGeohashes, buildPokeFrames, buildSeekBeforeWhere, buildSeekWhere, buildSettings, bumpCdcEpoch, clampPromotionThresholds, clearCapturedMail, clearQueueMessages, coerceAggregateNumber, compileWhereSql, computeRankPage, containsRelationPredicate, coveringGeohashes, createCompanionSync, createDependencyTracker, createFanoutCounters, createIndexSql, createRelayLink, createShardCtxDb, createSystemReader, decodeCursor, deleteGlobalShapeSnapshot, deleteGlobalShapeSnapshotsForConnection, depKey, diffExternalSource, diffGlobalMembership, distinctValues, encodeAggregateKey, encodeCursor, encodeGeohash, encodePartitionKey, encodeRowsPatch, ensureAuditTable, ensureMailTable, exportShardRows, exportShardTable, facetColumn, fanOutScalarCounts, findStorageReferences, foldAggregateTally, geoTableName, guardWriter, hasTrigger, haversineMeters, hydrateDocsById, importShardRows, isDevEnvironment, isFtsAvailable, isLossyBody, isRelationPredicate, isSoftDeleted, isSourceDue, jsonPath, jsonPathSql, liftSourceId, lintReadonlySql, listTables, matchesRankStaticWhere, matchesStaticWhere, materializeExternalRows, materializeExternalRowsIncremental, mergeWhere, migrateCdcLog, migrateCdcMeta, migrateClientWatermark, migrateGlobalShapeSnapshot, migrateIdempotency, migrateSearchState, minCdcSeq, nextPromotionState, normalizeCountArgument, normalizeIdStructurally, normalizeOrderKeys, normalizeSourceDocument, normalizeSourceValue, param, parseExportShardArgs, parseImportShardArgs, planAggregateLookup, pointInBoundingBox, projectColumns, pullExternalSourceIncrementalTick, pullExternalSourceTick, qualifiedJsonPath, qualifiedJsonPathSql, quoteIdentifier, rankKeyFromDocument as rankKeyFromDoc, rankTableName, reactiveCacheKey, readAggregateValue, readAuditLog, readBookmark, readCapturedMail, readCdcChanges, readCdcCursor, readCdcEpoch, readClientWatermark, readExternalSourceBaseline, readGlobalShapeSnapshot, readIdempotent, readMigrationStatus, readQueueMessageById, readQueueMessages, readSchemaHistory, readSchemaVersion, readSearchBackfillState, readTablePage, recordCapturedMail, recordFanoutPass, recordQueueMessages, recordSchemaVersion, relayCountFor, renderSql, resolveRankPartition, resolveRelationPredicates, resolveWith, rowToDocument, runDataMigration, runDrizzle, runExternalSourceTick, runReadonlySql, runRowValidators, runShardMigrations, runSocketPool, runSql, runTriggers, selectExpiredIds, selectExportTables, selectIndexForAggregate, selectIndexForCount, selectIndexForGroupBy, selectMatchingIds, selectShapeMemberIds, selectShapeRows, sendDeltaFrames, serializeSqlValue, shapeRoutingKey, softDeleteScope, sortColumnName, stableStringify, stableWireKey, subscriptionListDeltas, summarizeFanoutTopics, summarizeSubscriptions, tableColumns, tableFromDepKey, throwingScheduler, trimCdcChanges, trimIdempotent, tryRowToDocument, trySendFrame, validateImportRow, writeGlobalShapeSnapshot, writeIdempotent, writeSearchBackfillState };
1976
+ export { ADMIN_FUNCTIONS, ADMIN_FUNCTION_PREFIX, AGGREGATE_SQL_FUNCTION, AGG_COUNT, AGG_KEY, AGG_VALUE, AUDIT_LOG_TABLE, type AdvisorProcedure, type AdvisorProceduresResult, type AdvisoriesResult, type AdvisoryFinding, type AggregateIndexDefinitionLike, type AggregateOp, type AggregateOptions, type AggregateResult, type AggregateTally, type AppendAuditEntry, type ApplyOnDeleteOptions$1 as ApplyOnDeleteOptions, type AuditEntry, type AuditLogResult, type BroadcastDelta, CDC_LOG_TABLE, CDC_META_TABLE, CLIENT_WATERMARK_TABLE, type CacheEntry, type CapturedMailRow, type CdcChange, type ChangedKeys, type Clock, type ColumnMeta, type ColumnMetaLike, type CompanionSync, type CompanionSyncDeps, ConflictError, type ConflictKind, type CountArgs, CountRlsUnsupportedError, type CreateWorkflowInstanceResult, type CtxDbOptions, DATA_MIGRATION_STATE_TABLE, DEFAULT_FANOUT_TOPIC_LIMIT, DEFAULT_MAX_RELATION_KEYS, DEFAULT_MAX_RELAYS, DEFAULT_PROMOTION_THRESHOLDS, DEFAULT_TRANSACTION_LIMITS, DOC_COLUMN, type DataMigrationDocument, type DataMigrationLike, type DataMigrationTransform, type DatabaseWriterLike, type DependencyTracker, type DeployInfo, type ExportRow, type ExportShardAdminArgs, type ExportShardArgs, type ExternalSourceDiffResult, type ExternalSourceLike, FLAGS_FUNCTION_PREFIX, type FacetColumnOptions, type FacetColumnResult, type FacetValue, type FanoutMetricsResult, type FanoutPathCounters, type FanoutTopicStat, type FieldOperators, type FilterClause, type FilterOperator, type FlagEvaluation, type FlagsResult, type FunctionCallStat, type FunctionScanAttribution, type FunctionStatsResult, GEO_DEFAULT_PRECISION, GLOBAL_SHAPE_SNAPSHOT_TABLE, type GeoBoundingBox, type GeoFilterBuilderLike, type GeoIndexDefinitionLike, type GeoPoint, type GroupByEntry, type GroupByOptions, type GuardableSchema$1 as GuardableSchema, IDEMPOTENCY_TABLE, type IdGenerator, type IdempotentRecord, type ImportError, type ImportShardAdminArgs, type ImportShardArgs, type ImportShardResult, type IncrementalMaterializeResult, type IndexDefinitionLike, type IndexKeyEntry, type IndexRangeBuilderLike, type KeyRange, type LifecycleDispatchInfo, type LifecycleEvent, MAIL_RETENTION, MAIL_TABLE, MAX_PAGE_SIZE, MAX_SQL_ROWS, type MaskColumnMetadata, type MaskPoliciesResult, type MaterializeResult, type MigrationDirection, type MigrationRunResult, type MigrationStatus, type MigrationStatusRow, type MutationDelta, type NestedWith, NotFoundError, NotUniqueError, type OnDeleteActionLike, type OrderByClause, type OrderByInput, type OrderKey, OwnerRelay, type OwnerRelayFrame, type PaginationOptions, type PitrBookmarkResult, type PitrRestoreArgs, type PitrRestoreResult, type PitrStorage, type PokeFrameMeta, type PromotionState, type PromotionThresholds, QUEUE_TABLE, type QueryArgs, type QueryPage, type QueueMessageOutcome, type QueueMessageRow, type QueueMetadata, type QueuesResult, RANK_TIEBREAK, RELATION_EXISTS_KEY, RELATION_FUNCTION_PREFIX, RLS_UNWRAP_SYMBOL, type RankBeforeOptions, type RankBeforeResult, type RankDirection, type RankIndexDefinitionLike, type RankOptions, type RankPage, type RankPageComputation, type RankPageDeps, type RankPageOptions, type RankPageRow, type RankPageRowKey, type RankResult, type RankSortKeyLike, ReactiveCache, type ReactiveCacheOptions, type ReadFootprint, type ReadHook, type ReadTablePageOptions, type RecordMailInput, type RecordQueueMessageInput, type RelationDefinitionLike, type RelationExistsMarker, type RelayAttach, type RelayDetach, type RelayFrame, type RelayHost, RelayMember, type RelayShapePoke, type RelayShapeSeed, type RelayShapeSubscribe, type RenderedSql, type ResolveRelationPredicatesOptions, type ResolveWithOptions, type ResolveWithResult, type ResolvedShape, type RestrictableQueryOptions, type RlsPoliciesResult, type RlsPolicyMetadata, RlsRequiredError, type RlsRoleMetadata, type RpcRequest, type RunDataMigrationOptions, type RunTriggersOptions, SCAN_DEP, SCHEMA_HISTORY_MAX_VERSIONS, SEARCH_STATE_TABLE, type SchedulableWorkflowReferenceLike, type ScheduledFunctionDoc, type SchedulerLike, type SchemaLike, type SearchFilterBuilderLike, type SearchIndexDefinitionLike, type SelectMatchingIdsOptions, type ServerDefaultContextLike, type SettingEntry, type SettingKind, type SettingsResult, type ShapePokePart, type ShapeRow, type ShapeRowOp, type ShapeSubscriptionQuery, type ShardRankPageResult, ShardRunner, type ShardRunnerOptions, type ShardSocketLike, type SocketAttachment, type SortDirection, type SourceClientLike, type SourceCursorLike, type SourceRefresh, type SqlConsoleResult, type SqlCursor, type SqlEngine, type SqlExec, type SqlLintResult, type StorageMetadata, type StorageReference, type StorageReferenceResult, type StorageRuleMetadata, type StorageRulesResult, type StudioFeaturesResult, type SubscriptionConnection, type SubscriptionEnvelope, type SubscriptionIdentity, type SubscriptionInfo, type SubscriptionQuery, type SubscriptionReadFootprint, type SubscriptionsResult, type SystemDatabaseReader, type SystemDoc, type SystemQuery, type SystemReaderOptions, type SystemReaderSchedulerLike, type SystemReaderStorageLike, type SystemTableName, type TableColumnsResult, type TableDefinitionLike, type TableIndexInfo, type TableIndexesResult, type TableInfo, type TablePage, type TableReaderLike, type TablesColumnsResult, type TransactionHeadroom, TransactionHeadroomTracker, type TransactionLimits, type TransactionSqlLike, type TriggerContextLike, type TriggerDefinitionLike, type TriggerEventLike, type TriggerOpLike, type TriggerTimingLike, type TtlSweepSpec, type ValidatorLike, type WhereInput, type WhereSqlStrategy, type WithInput, type WorkflowInstanceState, type WorkflowInstanceStatusResult, type WorkflowMetadata, type WorkflowsResult, type WriteEvent, type WriteHook, advanceClientWatermark, aggUpsertSql, aggregateSqlFunction, aggregateTableName, appendAuditEntry, appendCdcChange, applyCdcChanges, applyOnDelete, applySelect, armRestore, assertFlatPredicate, assertReadonly, assertShapeShardable, assertValidClientId, awaitWsDrain, backfillAggregateIndexes, backfillRankIndexes, backfillSearchIndexes, backfillSearchIndexesForTable, boundingBoxCenter, boundingBoxGeohashes, buildIndexRange, buildPokeFrames, buildSeekBeforeWhere, buildSeekWhere, buildSettings, bumpCdcEpoch, clampPromotionThresholds, clearCapturedMail, clearQueueMessages, coerceAggregateNumber, compileWhereSql, computeRankPage, containsRelationPredicate, coveringGeohashes, createCompanionSync, createDependencyTracker, createFanoutCounters, createIndexSql, createReadFootprint, createRelayLink, createShardCtxDb, createSystemReader, decodeCursor, deleteGlobalShapeSnapshot, deleteGlobalShapeSnapshotsForConnection, depKey, diffExternalSource, diffGlobalMembership, distinctValues, encodeAggregateKey, encodeCursor, encodeGeohash, encodePartitionKey, encodeRowsPatch, ensureAuditTable, ensureMailTable, exportShardRows, exportShardTable, facetColumn, fanOutScalarCounts, findStorageReferences, foldAggregateTally, geoTableName, guardWriter, hasTrigger, haversineMeters, hydrateDocsById, importShardRows, indexKeysForRow, isDevEnvironment, isFtsAvailable, isLossyBody, isRelationPredicate, isSoftDeleted, isSourceDue, jsonPath, jsonPathSql, keysTouchRanges, liftSourceId, lintReadonlySql, listTables, matchesRankStaticWhere, matchesStaticWhere, materializeExternalRows, materializeExternalRowsIncremental, mergeChangedKeys, mergeWhere, migrateCdcLog, migrateCdcMeta, migrateClientWatermark, migrateGlobalShapeSnapshot, migrateIdempotency, migrateSearchState, minCdcSeq, nextPromotionState, normalizeCountArgument, normalizeIdStructurally, normalizeOrderKeys, normalizeSourceDocument, normalizeSourceValue, param, parseExportShardArgs, parseImportShardArgs, planAggregateLookup, pointInBoundingBox, projectColumns, pullExternalSourceIncrementalTick, pullExternalSourceTick, qualifiedJsonPath, qualifiedJsonPathSql, quoteIdentifier, rankKeyFromDocument as rankKeyFromDoc, rankTableName, reactiveCacheKey, readAggregateValue, readAuditLog, readBookmark, readCapturedMail, readCdcChanges, readCdcCursor, readCdcEpoch, readClientWatermark, readExternalSourceBaseline, readGlobalShapeSnapshot, readIdempotent, readMigrationStatus, readQueueMessageById, readQueueMessages, readSchemaHistory, readSchemaVersion, readSearchBackfillState, readTablePage, recordCapturedMail, recordChangedKeys, recordFanoutPass, recordQueueMessages, recordSchemaVersion, relayCountFor, renderSql, resolveRankPartition, resolveRelationPredicates, resolveWith, rowToDocument, runDataMigration, runDrizzle, runExternalSourceTick, runReadonlySql, runRowValidators, runShardMigrations, runSocketPool, runSql, runTriggers, selectExpiredIds, selectExportTables, selectIndexForAggregate, selectIndexForCount, selectIndexForGroupBy, selectMatchingIds, selectShapeMemberIds, selectShapeRows, sendDeltaFrames, serializeSqlValue, shapeRoutingKey, softDeleteScope, sortColumnName, stableStringify, stableWireKey, subscriptionListDeltas, summarizeFanoutTopics, summarizeSubscriptions, tableColumns, tableFromDepKey, throwingScheduler, trimCdcChanges, trimIdempotent, tryRowToDocument, trySendFrame, validateImportRow, writeGlobalShapeSnapshot, writeIdempotent, writeSearchBackfillState, writeTouchesMemo };
package/dist/index.mjs CHANGED
@@ -1 +1 @@
1
- import{exportShardRows as o,exportShardTable as a,importShardRows as t,parseExportShardArgs as n,parseImportShardArgs as l,selectExportTables as i,validateImportRow as s}from"./packem_shared/exportShardRows-kt42wijd.mjs";import{AGGREGATE_SQL_FUNCTION as p,aggregateSqlFunction as d,matchesStaticWhere as c,normalizeCountArgument as S,throwingScheduler as u}from"./packem_shared/AGGREGATE_SQL_FUNCTION-QYaiuty4.mjs";import{aggregateTableName as f,coerceAggregateNumber as E,encodeAggregateKey as g,foldAggregateTally as A,readAggregateValue as h}from"./packem_shared/aggregateTableName-G-eXyjcz.mjs";import{CountRlsUnsupportedError as C,mergeWhere as I,planAggregateLookup as _,selectIndexForAggregate as R,selectIndexForCount as L,selectIndexForGroupBy as b}from"./packem_shared/CountRlsUnsupportedError-B2WKJD9v.mjs";import{AUDIT_LOG_TABLE as y,appendAuditEntry as M,ensureAuditTable as O,readAuditLog as D}from"./packem_shared/AUDIT_LOG_TABLE-CaA0jL0L.mjs";import{NotUniqueError as P,assertValidClientId as k,createShardCtxDb as B,normalizeIdStructurally as G}from"./packem_shared/NotUniqueError-B4piAtjk.mjs";import{backfillAggregateIndexes as q,backfillRankIndexes as w,backfillSearchIndexes as W,backfillSearchIndexesForTable as K}from"./packem_shared/backfillAggregateIndexes-BHiewuB-.mjs";import{CDC_LOG_TABLE as z,CDC_META_TABLE as V,appendCdcChange as X,applyCdcChanges as H,bumpCdcEpoch as Q,migrateCdcLog as Y,migrateCdcMeta as j,minCdcSeq as J,readCdcChanges as Z,readCdcCursor as $,readCdcEpoch as ee,trimCdcChanges as re}from"./packem_shared/CDC_LOG_TABLE-BnqlH2eZ.mjs";import{CLIENT_WATERMARK_TABLE as ae,advanceClientWatermark as te,migrateClientWatermark as ne,readClientWatermark as le}from"./packem_shared/CLIENT_WATERMARK_TABLE-CXsSLU8D.mjs";import{createCompanionSync as se}from"./packem_shared/createCompanionSync-BCBUOnMk.mjs";import{GLOBAL_SHAPE_SNAPSHOT_TABLE as pe,deleteGlobalShapeSnapshot as de,deleteGlobalShapeSnapshotsForConnection as ce,migrateGlobalShapeSnapshot as Se,readGlobalShapeSnapshot as ue,writeGlobalShapeSnapshot as xe}from"./packem_shared/GLOBAL_SHAPE_SNAPSHOT_TABLE-DX-6-gBP.mjs";import{IDEMPOTENCY_TABLE as Ee,migrateIdempotency as ge,readIdempotent as Ae,trimIdempotent as he,writeIdempotent as Te}from"./packem_shared/IDEMPOTENCY_TABLE-DjkEMp6w.mjs";import{computeRankPage as Ie,hydrateDocsById as _e}from"./packem_shared/computeRankPage-IUSS-zIB.mjs";import{SEARCH_STATE_TABLE as Le,migrateSearchState as be,readSearchBackfillState as Ne,writeSearchBackfillState as ye}from"./packem_shared/SEARCH_STATE_TABLE-eLN8U5tz.mjs";import{selectShapeMemberIds as Oe,selectShapeRows as De}from"./packem_shared/selectShapeMemberIds-DvE7K6zG.mjs";import{DATA_MIGRATION_STATE_TABLE as Pe,readMigrationStatus as ke,runDataMigration as Be}from"./packem_shared/DATA_MIGRATION_STATE_TABLE-CaO6L0Ee.mjs";import{SCAN_DEP as Ue,createDependencyTracker as qe,depKey as we,tableFromDepKey as We}from"./packem_shared/SCAN_DEP-D_yR9EeV.mjs";import{runDrizzle as ve,runSql as ze}from"./packem_shared/runDrizzle-GKR3y97k.mjs";import{AGG_COUNT as Xe,AGG_KEY as He,AGG_VALUE as Qe,DOC_COLUMN as Ye,aggUpsertSql as je,createIndexSql as Je,geoTableName as Ze,isFtsAvailable as $e,jsonPath as er,jsonPathSql as rr,qualifiedJsonPath as or,qualifiedJsonPathSql as ar,quoteIdentifier as tr,rowToDocument as nr,tableColumns as lr,tryRowToDocument as ir}from"./packem_shared/AGG_COUNT-BWXe3gtQ.mjs";import{param as mr,renderSql as pr}from"./packem_shared/param-B5lF5Jd9.mjs";import{diffExternalSource as cr}from"./packem_shared/diffExternalSource-DMpkJta1.mjs";import{liftSourceId as ur,normalizeSourceDocument as xr,normalizeSourceValue as fr}from"./packem_shared/liftSourceId-DApAbu7Q.mjs";import{materializeExternalRows as gr,materializeExternalRowsIncremental as Ar,readExternalSourceBaseline as hr,runExternalSourceTick as Tr}from"./packem_shared/materializeExternalRows-DOQJV9p2.mjs";import{isSoftDeleted as Ir,isSourceDue as _r,pullExternalSourceIncrementalTick as Rr,pullExternalSourceTick as Lr}from"./packem_shared/isSoftDeleted-B-SXkGUo.mjs";import{GEO_DEFAULT_PRECISION as Nr,boundingBoxCenter as yr,boundingBoxGeohashes as Mr,coveringGeohashes as Or,encodeGeohash as Dr,haversineMeters as Fr,pointInBoundingBox as Pr}from"./packem_shared/GEO_DEFAULT_PRECISION-okRCkZ6r.mjs";import{ADMIN_FUNCTIONS as Br,ADMIN_FUNCTION_PREFIX as Gr,DEFAULT_FANOUT_TOPIC_LIMIT as Ur,FLAGS_FUNCTION_PREFIX as qr,MAX_PAGE_SIZE as wr,RELATION_FUNCTION_PREFIX as Wr,createFanoutCounters as Kr,facetColumn as vr,findStorageReferences as zr,listTables as Vr,readTablePage as Xr,recordFanoutPass as Hr,selectMatchingIds as Qr,summarizeFanoutTopics as Yr,summarizeSubscriptions as jr}from"./packem_shared/ADMIN_FUNCTIONS-B0xlQJ4w.mjs";import{MAIL_RETENTION as Zr,MAIL_TABLE as $r,clearCapturedMail as eo,ensureMailTable as ro,readCapturedMail as oo,recordCapturedMail as ao}from"./packem_shared/MAIL_RETENTION-KmozO2NQ.mjs";import{NotFoundError as no}from"./packem_shared/NotFoundError-BhF7FeFr.mjs";import{armRestore as io,readBookmark as so}from"./packem_shared/armRestore-BNzdvQ_o.mjs";import{applySelect as po,buildSeekBeforeWhere as co,buildSeekWhere as So,decodeCursor as uo,encodeCursor as xo,normalizeOrderKeys as fo,softDeleteScope as Eo}from"./packem_shared/applySelect-B0CF8T7y.mjs";import{QUEUE_TABLE as Ao,clearQueueMessages as ho,isLossyBody as To,readQueueMessageById as Co,readQueueMessages as Io,recordQueueMessages as _o}from"./packem_shared/QUEUE_TABLE-DYCDvzTG.mjs";import{RANK_TIEBREAK as Lo,encodePartitionKey as bo,matchesRankStaticWhere as No,rankKeyFromDoc as yo,rankTableName as Mo,resolveRankPartition as Oo,sortColumnName as Do}from"./packem_shared/RANK_TIEBREAK-9NU5s_mi.mjs";import{ReactiveCache as Po,reactiveCacheKey as ko}from"./packem_shared/ReactiveCache-1_9Rs7J_.mjs";import{DEFAULT_MAX_RELATION_KEYS as Go,assertFlatPredicate as Uo,assertShapeShardable as qo,containsRelationPredicate as wo,isRelationPredicate as Wo,resolveRelationPredicates as Ko}from"./packem_shared/DEFAULT_MAX_RELATION_KEYS-bq00btqV.mjs";import{applyOnDelete as zo,distinctValues as Vo,fanOutScalarCounts as Xo,resolveWith as Ho,runRowValidators as Qo}from"./packem_shared/applyOnDelete-uFRC5p1d.mjs";import{DEFAULT_PROMOTION_THRESHOLDS as jo,clampPromotionThresholds as Jo,nextPromotionState as Zo,relayCountFor as $o,shapeRoutingKey as ea}from"./packem_shared/DEFAULT_PROMOTION_THRESHOLDS-Dteg0sZF.mjs";import{DEFAULT_MAX_RELAYS as oa,OwnerRelay as aa,RelayMember as ta,createRelayLink as na}from"./packem_shared/DEFAULT_MAX_RELAYS-CnCyh6oX.mjs";import{RLS_UNWRAP_SYMBOL as ia,RlsRequiredError as sa,guardWriter as ma}from"./packem_shared/RLS_UNWRAP_SYMBOL-C6_WX3dG.mjs";import{SCHEMA_HISTORY_MAX_VERSIONS as da,readSchemaHistory as ca,readSchemaVersion as Sa,recordSchemaVersion as ua}from"./packem_shared/SCHEMA_HISTORY_MAX_VERSIONS-CHXz6p_z.mjs";import{serializeSqlValue as fa}from"./packem_shared/serializeSqlValue-DnpyaLcw.mjs";import{buildSettings as ga,isDevEnvironment as Aa}from"./packem_shared/buildSettings-DT18_DkX.mjs";import{buildPokeFrames as Ta,diffGlobalMembership as Ca,encodeRowsPatch as Ia,projectColumns as _a}from"./packem_shared/buildPokeFrames-DaPpm5Ss.mjs";import{ShardRunner as La}from"./packem_shared/ShardRunner-DIqVdWtk.mjs";import{runSocketPool as Na}from"./packem_shared/runSocketPool-DPQLVyWF.mjs";import{MAX_SQL_ROWS as Ma,assertReadonly as Oa,lintReadonlySql as Da,runReadonlySql as Fa}from"./packem_shared/MAX_SQL_ROWS-nMwkxv5f.mjs";import{awaitWsDrain as ka,sendDeltaFrames as Ba,subscriptionListDeltas as Ga,trySendFrame as Ua}from"./packem_shared/awaitWsDrain-Dk50ISgE.mjs";import{createSystemReader as wa}from"./packem_shared/createSystemReader-DcDcrtM3.mjs";import{ConflictError as Ka}from"./packem_shared/ConflictError-C8GtJmjS.mjs";import{hasTrigger as za,runTriggers as Va}from"./packem_shared/hasTrigger-CbkOHExZ.mjs";import{selectExpiredIds as Ha}from"./packem_shared/selectExpiredIds-FzhIEeG1.mjs";import{compileWhereSql as Ya}from"./packem_shared/compileWhereSql-BLcfs4QW.mjs";import{RELATION_EXISTS_KEY as Ja}from"./packem_shared/RELATION_EXISTS_KEY-BaqSIFU1.mjs";import{runShardMigrations as $a}from"./packem_shared/runShardMigrations-CPxqCh3O.mjs";import{stableStringify as rt}from"./packem_shared/stableStringify-BjLh4gvA.mjs";import{stableWireKey as at}from"./packem_shared/stableWireKey-YEHLaX6X.mjs";export{Br as ADMIN_FUNCTIONS,Gr as ADMIN_FUNCTION_PREFIX,p as AGGREGATE_SQL_FUNCTION,Xe as AGG_COUNT,He as AGG_KEY,Qe as AGG_VALUE,y as AUDIT_LOG_TABLE,z as CDC_LOG_TABLE,V as CDC_META_TABLE,ae as CLIENT_WATERMARK_TABLE,Ka as ConflictError,C as CountRlsUnsupportedError,Pe as DATA_MIGRATION_STATE_TABLE,Ur as DEFAULT_FANOUT_TOPIC_LIMIT,Go as DEFAULT_MAX_RELATION_KEYS,oa as DEFAULT_MAX_RELAYS,jo as DEFAULT_PROMOTION_THRESHOLDS,Ye as DOC_COLUMN,qr as FLAGS_FUNCTION_PREFIX,Nr as GEO_DEFAULT_PRECISION,pe as GLOBAL_SHAPE_SNAPSHOT_TABLE,Ee as IDEMPOTENCY_TABLE,Zr as MAIL_RETENTION,$r as MAIL_TABLE,wr as MAX_PAGE_SIZE,Ma as MAX_SQL_ROWS,no as NotFoundError,P as NotUniqueError,aa as OwnerRelay,Ao as QUEUE_TABLE,Lo as RANK_TIEBREAK,Ja as RELATION_EXISTS_KEY,Wr as RELATION_FUNCTION_PREFIX,ia as RLS_UNWRAP_SYMBOL,Po as ReactiveCache,ta as RelayMember,sa as RlsRequiredError,Ue as SCAN_DEP,da as SCHEMA_HISTORY_MAX_VERSIONS,Le as SEARCH_STATE_TABLE,La as ShardRunner,te as advanceClientWatermark,je as aggUpsertSql,d as aggregateSqlFunction,f as aggregateTableName,M as appendAuditEntry,X as appendCdcChange,H as applyCdcChanges,zo as applyOnDelete,po as applySelect,io as armRestore,Uo as assertFlatPredicate,Oa as assertReadonly,qo as assertShapeShardable,k as assertValidClientId,ka as awaitWsDrain,q as backfillAggregateIndexes,w as backfillRankIndexes,W as backfillSearchIndexes,K as backfillSearchIndexesForTable,yr as boundingBoxCenter,Mr as boundingBoxGeohashes,Ta as buildPokeFrames,co as buildSeekBeforeWhere,So as buildSeekWhere,ga as buildSettings,Q as bumpCdcEpoch,Jo as clampPromotionThresholds,eo as clearCapturedMail,ho as clearQueueMessages,E as coerceAggregateNumber,Ya as compileWhereSql,Ie as computeRankPage,wo as containsRelationPredicate,Or as coveringGeohashes,se as createCompanionSync,qe as createDependencyTracker,Kr as createFanoutCounters,Je as createIndexSql,na as createRelayLink,B as createShardCtxDb,wa as createSystemReader,uo as decodeCursor,de as deleteGlobalShapeSnapshot,ce as deleteGlobalShapeSnapshotsForConnection,we as depKey,cr as diffExternalSource,Ca as diffGlobalMembership,Vo as distinctValues,g as encodeAggregateKey,xo as encodeCursor,Dr as encodeGeohash,bo as encodePartitionKey,Ia as encodeRowsPatch,O as ensureAuditTable,ro as ensureMailTable,o as exportShardRows,a as exportShardTable,vr as facetColumn,Xo as fanOutScalarCounts,zr as findStorageReferences,A as foldAggregateTally,Ze as geoTableName,ma as guardWriter,za as hasTrigger,Fr as haversineMeters,_e as hydrateDocsById,t as importShardRows,Aa as isDevEnvironment,$e as isFtsAvailable,To as isLossyBody,Wo as isRelationPredicate,Ir as isSoftDeleted,_r as isSourceDue,er as jsonPath,rr as jsonPathSql,ur as liftSourceId,Da as lintReadonlySql,Vr as listTables,No as matchesRankStaticWhere,c as matchesStaticWhere,gr as materializeExternalRows,Ar as materializeExternalRowsIncremental,I as mergeWhere,Y as migrateCdcLog,j as migrateCdcMeta,ne as migrateClientWatermark,Se as migrateGlobalShapeSnapshot,ge as migrateIdempotency,be as migrateSearchState,J as minCdcSeq,Zo as nextPromotionState,S as normalizeCountArgument,G as normalizeIdStructurally,fo as normalizeOrderKeys,xr as normalizeSourceDocument,fr as normalizeSourceValue,mr as param,n as parseExportShardArgs,l as parseImportShardArgs,_ as planAggregateLookup,Pr as pointInBoundingBox,_a as projectColumns,Rr as pullExternalSourceIncrementalTick,Lr as pullExternalSourceTick,or as qualifiedJsonPath,ar as qualifiedJsonPathSql,tr as quoteIdentifier,yo as rankKeyFromDoc,Mo as rankTableName,ko as reactiveCacheKey,h as readAggregateValue,D as readAuditLog,so as readBookmark,oo as readCapturedMail,Z as readCdcChanges,$ as readCdcCursor,ee as readCdcEpoch,le as readClientWatermark,hr as readExternalSourceBaseline,ue as readGlobalShapeSnapshot,Ae as readIdempotent,ke as readMigrationStatus,Co as readQueueMessageById,Io as readQueueMessages,ca as readSchemaHistory,Sa as readSchemaVersion,Ne as readSearchBackfillState,Xr as readTablePage,ao as recordCapturedMail,Hr as recordFanoutPass,_o as recordQueueMessages,ua as recordSchemaVersion,$o as relayCountFor,pr as renderSql,Oo as resolveRankPartition,Ko as resolveRelationPredicates,Ho as resolveWith,nr as rowToDocument,Be as runDataMigration,ve as runDrizzle,Tr as runExternalSourceTick,Fa as runReadonlySql,Qo as runRowValidators,$a as runShardMigrations,Na as runSocketPool,ze as runSql,Va as runTriggers,Ha as selectExpiredIds,i as selectExportTables,R as selectIndexForAggregate,L as selectIndexForCount,b as selectIndexForGroupBy,Qr as selectMatchingIds,Oe as selectShapeMemberIds,De as selectShapeRows,Ba as sendDeltaFrames,fa as serializeSqlValue,ea as shapeRoutingKey,Eo as softDeleteScope,Do as sortColumnName,rt as stableStringify,at as stableWireKey,Ga as subscriptionListDeltas,Yr as summarizeFanoutTopics,jr as summarizeSubscriptions,lr as tableColumns,We as tableFromDepKey,u as throwingScheduler,re as trimCdcChanges,he as trimIdempotent,ir as tryRowToDocument,Ua as trySendFrame,s as validateImportRow,xe as writeGlobalShapeSnapshot,Te as writeIdempotent,ye as writeSearchBackfillState};
1
+ import{exportShardRows as o,exportShardTable as a,importShardRows as t,parseExportShardArgs as n,parseImportShardArgs as l,selectExportTables as i,validateImportRow as s}from"./packem_shared/exportShardRows-kt42wijd.mjs";import{AGGREGATE_SQL_FUNCTION as d,aggregateSqlFunction as p,matchesStaticWhere as c,normalizeCountArgument as S,throwingScheduler as u}from"./packem_shared/AGGREGATE_SQL_FUNCTION-QYaiuty4.mjs";import{aggregateTableName as f,coerceAggregateNumber as T,encodeAggregateKey as g,foldAggregateTally as h,readAggregateValue as A}from"./packem_shared/aggregateTableName-G-eXyjcz.mjs";import{CountRlsUnsupportedError as C,mergeWhere as I,planAggregateLookup as _,selectIndexForAggregate as R,selectIndexForCount as L,selectIndexForGroupBy as b}from"./packem_shared/CountRlsUnsupportedError-B2WKJD9v.mjs";import{AUDIT_LOG_TABLE as N,appendAuditEntry as M,ensureAuditTable as F,readAuditLog as O}from"./packem_shared/AUDIT_LOG_TABLE-CaA0jL0L.mjs";import{NotUniqueError as P,assertValidClientId as k,createShardCtxDb as B,normalizeIdStructurally as G}from"./packem_shared/NotUniqueError-iGKd9wRR.mjs";import{backfillAggregateIndexes as w,backfillRankIndexes as K,backfillSearchIndexes as q,backfillSearchIndexesForTable as W}from"./packem_shared/backfillAggregateIndexes-BHiewuB-.mjs";import{CDC_LOG_TABLE as z,CDC_META_TABLE as V,appendCdcChange as H,applyCdcChanges as X,bumpCdcEpoch as Q,migrateCdcLog as Y,migrateCdcMeta as j,minCdcSeq as J,readCdcChanges as Z,readCdcCursor as $,readCdcEpoch as ee,trimCdcChanges as re}from"./packem_shared/CDC_LOG_TABLE-BnqlH2eZ.mjs";import{CLIENT_WATERMARK_TABLE as ae,advanceClientWatermark as te,migrateClientWatermark as ne,readClientWatermark as le}from"./packem_shared/CLIENT_WATERMARK_TABLE-CXsSLU8D.mjs";import{createCompanionSync as se}from"./packem_shared/createCompanionSync-DWK0Vlg1.mjs";import{GLOBAL_SHAPE_SNAPSHOT_TABLE as de,deleteGlobalShapeSnapshot as pe,deleteGlobalShapeSnapshotsForConnection as ce,migrateGlobalShapeSnapshot as Se,readGlobalShapeSnapshot as ue,writeGlobalShapeSnapshot as xe}from"./packem_shared/GLOBAL_SHAPE_SNAPSHOT_TABLE-DX-6-gBP.mjs";import{IDEMPOTENCY_TABLE as Te,migrateIdempotency as ge,readIdempotent as he,trimIdempotent as Ae,writeIdempotent as Ee}from"./packem_shared/IDEMPOTENCY_TABLE-DjkEMp6w.mjs";import{computeRankPage as Ie,hydrateDocsById as _e}from"./packem_shared/computeRankPage-IUSS-zIB.mjs";import{SEARCH_STATE_TABLE as Le,migrateSearchState as be,readSearchBackfillState as ye,writeSearchBackfillState as Ne}from"./packem_shared/SEARCH_STATE_TABLE-eLN8U5tz.mjs";import{selectShapeMemberIds as Fe,selectShapeRows as Oe}from"./packem_shared/selectShapeMemberIds-DvE7K6zG.mjs";import{DATA_MIGRATION_STATE_TABLE as Pe,readMigrationStatus as ke,runDataMigration as Be}from"./packem_shared/DATA_MIGRATION_STATE_TABLE-CaO6L0Ee.mjs";import{SCAN_DEP as Ue,createDependencyTracker as we,depKey as Ke,tableFromDepKey as qe}from"./packem_shared/SCAN_DEP-D_yR9EeV.mjs";import{runDrizzle as ve,runSql as ze}from"./packem_shared/runDrizzle-GKR3y97k.mjs";import{AGG_COUNT as He,AGG_KEY as Xe,AGG_VALUE as Qe,DOC_COLUMN as Ye,aggUpsertSql as je,createIndexSql as Je,geoTableName as Ze,isFtsAvailable as $e,jsonPath as er,jsonPathSql as rr,qualifiedJsonPath as or,qualifiedJsonPathSql as ar,quoteIdentifier as tr,rowToDocument as nr,tableColumns as lr,tryRowToDocument as ir}from"./packem_shared/AGG_COUNT-BWXe3gtQ.mjs";import{param as mr,renderSql as dr}from"./packem_shared/param-B5lF5Jd9.mjs";import{diffExternalSource as cr}from"./packem_shared/diffExternalSource-DMpkJta1.mjs";import{liftSourceId as ur,normalizeSourceDocument as xr,normalizeSourceValue as fr}from"./packem_shared/liftSourceId-DApAbu7Q.mjs";import{materializeExternalRows as gr,materializeExternalRowsIncremental as hr,readExternalSourceBaseline as Ar,runExternalSourceTick as Er}from"./packem_shared/materializeExternalRows-DOQJV9p2.mjs";import{isSoftDeleted as Ir,isSourceDue as _r,pullExternalSourceIncrementalTick as Rr,pullExternalSourceTick as Lr}from"./packem_shared/isSoftDeleted-B-SXkGUo.mjs";import{GEO_DEFAULT_PRECISION as yr,boundingBoxCenter as Nr,boundingBoxGeohashes as Mr,coveringGeohashes as Fr,encodeGeohash as Or,haversineMeters as Dr,pointInBoundingBox as Pr}from"./packem_shared/GEO_DEFAULT_PRECISION-okRCkZ6r.mjs";import{ADMIN_FUNCTIONS as Br,ADMIN_FUNCTION_PREFIX as Gr,DEFAULT_FANOUT_TOPIC_LIMIT as Ur,FLAGS_FUNCTION_PREFIX as wr,MAX_PAGE_SIZE as Kr,RELATION_FUNCTION_PREFIX as qr,createFanoutCounters as Wr,facetColumn as vr,findStorageReferences as zr,listTables as Vr,readTablePage as Hr,recordFanoutPass as Xr,selectMatchingIds as Qr,summarizeFanoutTopics as Yr,summarizeSubscriptions as jr}from"./packem_shared/ADMIN_FUNCTIONS-B0xlQJ4w.mjs";import{MAIL_RETENTION as Zr,MAIL_TABLE as $r,clearCapturedMail as eo,ensureMailTable as ro,readCapturedMail as oo,recordCapturedMail as ao}from"./packem_shared/MAIL_RETENTION-KmozO2NQ.mjs";import{NotFoundError as no}from"./packem_shared/NotFoundError-BhF7FeFr.mjs";import{armRestore as io,readBookmark as so}from"./packem_shared/armRestore-BNzdvQ_o.mjs";import{applySelect as po,buildSeekBeforeWhere as co,buildSeekWhere as So,decodeCursor as uo,encodeCursor as xo,normalizeOrderKeys as fo,softDeleteScope as To}from"./packem_shared/applySelect-B0CF8T7y.mjs";import{QUEUE_TABLE as ho,clearQueueMessages as Ao,isLossyBody as Eo,readQueueMessageById as Co,readQueueMessages as Io,recordQueueMessages as _o}from"./packem_shared/QUEUE_TABLE-DYCDvzTG.mjs";import{RANK_TIEBREAK as Lo,encodePartitionKey as bo,matchesRankStaticWhere as yo,rankKeyFromDoc as No,rankTableName as Mo,resolveRankPartition as Fo,sortColumnName as Oo}from"./packem_shared/RANK_TIEBREAK-9NU5s_mi.mjs";import{ReactiveCache as Po,reactiveCacheKey as ko}from"./packem_shared/ReactiveCache-CF21t8IB.mjs";import{createReadFootprint as Go}from"./packem_shared/createReadFootprint-DIrrxRTE.mjs";import{buildIndexRange as wo,indexKeysForRow as Ko,keysTouchRanges as qo}from"./packem_shared/buildIndexRange-DIjFVgeO.mjs";import{DEFAULT_MAX_RELATION_KEYS as vo,assertFlatPredicate as zo,assertShapeShardable as Vo,containsRelationPredicate as Ho,isRelationPredicate as Xo,resolveRelationPredicates as Qo}from"./packem_shared/DEFAULT_MAX_RELATION_KEYS-bq00btqV.mjs";import{applyOnDelete as jo,distinctValues as Jo,fanOutScalarCounts as Zo,resolveWith as $o,runRowValidators as ea}from"./packem_shared/applyOnDelete-uFRC5p1d.mjs";import{DEFAULT_PROMOTION_THRESHOLDS as oa,clampPromotionThresholds as aa,nextPromotionState as ta,relayCountFor as na,shapeRoutingKey as la}from"./packem_shared/DEFAULT_PROMOTION_THRESHOLDS-Dteg0sZF.mjs";import{DEFAULT_MAX_RELAYS as sa,OwnerRelay as ma,RelayMember as da,createRelayLink as pa}from"./packem_shared/DEFAULT_MAX_RELAYS-CnCyh6oX.mjs";import{RLS_UNWRAP_SYMBOL as Sa,RlsRequiredError as ua,guardWriter as xa}from"./packem_shared/RLS_UNWRAP_SYMBOL-C6_WX3dG.mjs";import{SCHEMA_HISTORY_MAX_VERSIONS as Ta,readSchemaHistory as ga,readSchemaVersion as ha,recordSchemaVersion as Aa}from"./packem_shared/SCHEMA_HISTORY_MAX_VERSIONS-CHXz6p_z.mjs";import{serializeSqlValue as Ca}from"./packem_shared/serializeSqlValue-DnpyaLcw.mjs";import{buildSettings as _a,isDevEnvironment as Ra}from"./packem_shared/buildSettings-DT18_DkX.mjs";import{buildPokeFrames as ba,diffGlobalMembership as ya,encodeRowsPatch as Na,projectColumns as Ma}from"./packem_shared/buildPokeFrames-DaPpm5Ss.mjs";import{ShardRunner as Oa}from"./packem_shared/ShardRunner-DIqVdWtk.mjs";import{runSocketPool as Pa}from"./packem_shared/runSocketPool-DPQLVyWF.mjs";import{MAX_SQL_ROWS as Ba,assertReadonly as Ga,lintReadonlySql as Ua,runReadonlySql as wa}from"./packem_shared/MAX_SQL_ROWS-nMwkxv5f.mjs";import{awaitWsDrain as qa,sendDeltaFrames as Wa,subscriptionListDeltas as va,trySendFrame as za}from"./packem_shared/awaitWsDrain-Dk50ISgE.mjs";import{mergeChangedKeys as Ha,recordChangedKeys as Xa,writeTouchesMemo as Qa}from"./packem_shared/mergeChangedKeys-CvSHlkv-.mjs";import{createSystemReader as ja}from"./packem_shared/createSystemReader-DcDcrtM3.mjs";import{ConflictError as Za}from"./packem_shared/ConflictError-C8GtJmjS.mjs";import{DEFAULT_TRANSACTION_LIMITS as et,TransactionHeadroomTracker as rt}from"./packem_shared/DEFAULT_TRANSACTION_LIMITS--TtB8Gpo.mjs";import{hasTrigger as at,runTriggers as tt}from"./packem_shared/hasTrigger-CbkOHExZ.mjs";import{selectExpiredIds as lt}from"./packem_shared/selectExpiredIds-FzhIEeG1.mjs";import{compileWhereSql as st}from"./packem_shared/compileWhereSql-BLcfs4QW.mjs";import{RELATION_EXISTS_KEY as dt}from"./packem_shared/RELATION_EXISTS_KEY-BaqSIFU1.mjs";import{runShardMigrations as ct}from"./packem_shared/runShardMigrations-CPxqCh3O.mjs";import{stableStringify as ut}from"./packem_shared/stableStringify-BjLh4gvA.mjs";import{stableWireKey as ft}from"./packem_shared/stableWireKey-YEHLaX6X.mjs";export{Br as ADMIN_FUNCTIONS,Gr as ADMIN_FUNCTION_PREFIX,d as AGGREGATE_SQL_FUNCTION,He as AGG_COUNT,Xe as AGG_KEY,Qe as AGG_VALUE,N as AUDIT_LOG_TABLE,z as CDC_LOG_TABLE,V as CDC_META_TABLE,ae as CLIENT_WATERMARK_TABLE,Za as ConflictError,C as CountRlsUnsupportedError,Pe as DATA_MIGRATION_STATE_TABLE,Ur as DEFAULT_FANOUT_TOPIC_LIMIT,vo as DEFAULT_MAX_RELATION_KEYS,sa as DEFAULT_MAX_RELAYS,oa as DEFAULT_PROMOTION_THRESHOLDS,et as DEFAULT_TRANSACTION_LIMITS,Ye as DOC_COLUMN,wr as FLAGS_FUNCTION_PREFIX,yr as GEO_DEFAULT_PRECISION,de as GLOBAL_SHAPE_SNAPSHOT_TABLE,Te as IDEMPOTENCY_TABLE,Zr as MAIL_RETENTION,$r as MAIL_TABLE,Kr as MAX_PAGE_SIZE,Ba as MAX_SQL_ROWS,no as NotFoundError,P as NotUniqueError,ma as OwnerRelay,ho as QUEUE_TABLE,Lo as RANK_TIEBREAK,dt as RELATION_EXISTS_KEY,qr as RELATION_FUNCTION_PREFIX,Sa as RLS_UNWRAP_SYMBOL,Po as ReactiveCache,da as RelayMember,ua as RlsRequiredError,Ue as SCAN_DEP,Ta as SCHEMA_HISTORY_MAX_VERSIONS,Le as SEARCH_STATE_TABLE,Oa as ShardRunner,rt as TransactionHeadroomTracker,te as advanceClientWatermark,je as aggUpsertSql,p as aggregateSqlFunction,f as aggregateTableName,M as appendAuditEntry,H as appendCdcChange,X as applyCdcChanges,jo as applyOnDelete,po as applySelect,io as armRestore,zo as assertFlatPredicate,Ga as assertReadonly,Vo as assertShapeShardable,k as assertValidClientId,qa as awaitWsDrain,w as backfillAggregateIndexes,K as backfillRankIndexes,q as backfillSearchIndexes,W as backfillSearchIndexesForTable,Nr as boundingBoxCenter,Mr as boundingBoxGeohashes,wo as buildIndexRange,ba as buildPokeFrames,co as buildSeekBeforeWhere,So as buildSeekWhere,_a as buildSettings,Q as bumpCdcEpoch,aa as clampPromotionThresholds,eo as clearCapturedMail,Ao as clearQueueMessages,T as coerceAggregateNumber,st as compileWhereSql,Ie as computeRankPage,Ho as containsRelationPredicate,Fr as coveringGeohashes,se as createCompanionSync,we as createDependencyTracker,Wr as createFanoutCounters,Je as createIndexSql,Go as createReadFootprint,pa as createRelayLink,B as createShardCtxDb,ja as createSystemReader,uo as decodeCursor,pe as deleteGlobalShapeSnapshot,ce as deleteGlobalShapeSnapshotsForConnection,Ke as depKey,cr as diffExternalSource,ya as diffGlobalMembership,Jo as distinctValues,g as encodeAggregateKey,xo as encodeCursor,Or as encodeGeohash,bo as encodePartitionKey,Na as encodeRowsPatch,F as ensureAuditTable,ro as ensureMailTable,o as exportShardRows,a as exportShardTable,vr as facetColumn,Zo as fanOutScalarCounts,zr as findStorageReferences,h as foldAggregateTally,Ze as geoTableName,xa as guardWriter,at as hasTrigger,Dr as haversineMeters,_e as hydrateDocsById,t as importShardRows,Ko as indexKeysForRow,Ra as isDevEnvironment,$e as isFtsAvailable,Eo as isLossyBody,Xo as isRelationPredicate,Ir as isSoftDeleted,_r as isSourceDue,er as jsonPath,rr as jsonPathSql,qo as keysTouchRanges,ur as liftSourceId,Ua as lintReadonlySql,Vr as listTables,yo as matchesRankStaticWhere,c as matchesStaticWhere,gr as materializeExternalRows,hr as materializeExternalRowsIncremental,Ha as mergeChangedKeys,I as mergeWhere,Y as migrateCdcLog,j as migrateCdcMeta,ne as migrateClientWatermark,Se as migrateGlobalShapeSnapshot,ge as migrateIdempotency,be as migrateSearchState,J as minCdcSeq,ta as nextPromotionState,S as normalizeCountArgument,G as normalizeIdStructurally,fo as normalizeOrderKeys,xr as normalizeSourceDocument,fr as normalizeSourceValue,mr as param,n as parseExportShardArgs,l as parseImportShardArgs,_ as planAggregateLookup,Pr as pointInBoundingBox,Ma as projectColumns,Rr as pullExternalSourceIncrementalTick,Lr as pullExternalSourceTick,or as qualifiedJsonPath,ar as qualifiedJsonPathSql,tr as quoteIdentifier,No as rankKeyFromDoc,Mo as rankTableName,ko as reactiveCacheKey,A as readAggregateValue,O as readAuditLog,so as readBookmark,oo as readCapturedMail,Z as readCdcChanges,$ as readCdcCursor,ee as readCdcEpoch,le as readClientWatermark,Ar as readExternalSourceBaseline,ue as readGlobalShapeSnapshot,he as readIdempotent,ke as readMigrationStatus,Co as readQueueMessageById,Io as readQueueMessages,ga as readSchemaHistory,ha as readSchemaVersion,ye as readSearchBackfillState,Hr as readTablePage,ao as recordCapturedMail,Xa as recordChangedKeys,Xr as recordFanoutPass,_o as recordQueueMessages,Aa as recordSchemaVersion,na as relayCountFor,dr as renderSql,Fo as resolveRankPartition,Qo as resolveRelationPredicates,$o as resolveWith,nr as rowToDocument,Be as runDataMigration,ve as runDrizzle,Er as runExternalSourceTick,wa as runReadonlySql,ea as runRowValidators,ct as runShardMigrations,Pa as runSocketPool,ze as runSql,tt as runTriggers,lt as selectExpiredIds,i as selectExportTables,R as selectIndexForAggregate,L as selectIndexForCount,b as selectIndexForGroupBy,Qr as selectMatchingIds,Fe as selectShapeMemberIds,Oe as selectShapeRows,Wa as sendDeltaFrames,Ca as serializeSqlValue,la as shapeRoutingKey,To as softDeleteScope,Oo as sortColumnName,ut as stableStringify,ft as stableWireKey,va as subscriptionListDeltas,Yr as summarizeFanoutTopics,jr as summarizeSubscriptions,lr as tableColumns,qe as tableFromDepKey,u as throwingScheduler,re as trimCdcChanges,Ae as trimIdempotent,ir as tryRowToDocument,za as trySendFrame,s as validateImportRow,xe as writeGlobalShapeSnapshot,Ee as writeIdempotent,Ne as writeSearchBackfillState,Qa as writeTouchesMemo};
@@ -0,0 +1 @@
1
+ import{LunoraError as i}from"@lunora/errors";import{r as s}from"./estimate-bytes-DzD3PdCc.mjs";const e={maxReadRows:1e5,maxWrittenBytes:32*1024*1024,maxWrittenRows:5e4};class a{readRows=0;writtenRows=0;writtenBytes=0;limits;constructor(t={}){this.limits={...e,...t}}recordRead(t){if(this.readRows+=t,this.readRows>this.limits.maxReadRows)throw new i("TRANSACTION_LIMIT_EXCEEDED",`this transaction read ${String(this.readRows)} documents, over the ${String(this.limits.maxReadRows)}-document limit`)}recordWrite(t){if(this.writtenRows+=1,this.writtenBytes+=s(t,this.limits.maxWrittenBytes),this.writtenRows>this.limits.maxWrittenRows)throw new i("TRANSACTION_LIMIT_EXCEEDED",`this transaction wrote ${String(this.writtenRows)} documents, over the ${String(this.limits.maxWrittenRows)}-document limit`);if(this.writtenBytes>this.limits.maxWrittenBytes)throw new i("TRANSACTION_LIMIT_EXCEEDED",`this transaction wrote ${String(this.writtenBytes)} bytes, over the ${String(this.limits.maxWrittenBytes)}-byte limit`)}headroom(){return{readRows:this.readRows,remainingReadRows:Math.max(0,this.limits.maxReadRows-this.readRows),remainingWrittenBytes:Math.max(0,this.limits.maxWrittenBytes-this.writtenBytes),remainingWrittenRows:Math.max(0,this.limits.maxWrittenRows-this.writtenRows),writtenBytes:this.writtenBytes,writtenRows:this.writtenRows}}}export{e as DEFAULT_TRANSACTION_LIMITS,a as TransactionHeadroomTracker};
@@ -0,0 +1 @@
1
+ import{LunoraError as y}from"@lunora/errors";import{n as gt,A as Be,T as Ee,y as bt,c as yt}from"./FTS_COUNT_COLUMN-D1gY3wwZ-CZHdaRrd.mjs";import{sql as t}from"drizzle-orm";import{aggregateSqlFunction as Ne,normalizeCountArgument as Et,throwingScheduler as Nt}from"./AGGREGATE_SQL_FUNCTION-QYaiuty4.mjs";import{encodeAggregateKey as Ie,readAggregateValue as xe,aggregateTableName as Ce}from"./aggregateTableName-G-eXyjcz.mjs";import{mergeWhere as G,CountRlsUnsupportedError as ke,selectIndexForGroupBy as Tt,selectIndexForCount as At,selectIndexForAggregate as St}from"./CountRlsUnsupportedError-B2WKJD9v.mjs";import{backfillSearchIndexesForTable as _t}from"./backfillAggregateIndexes-BHiewuB-.mjs";import{backfillAggregateIndexes as dr,backfillRankIndexes as cr,backfillSearchIndexes as ur}from"./backfillAggregateIndexes-BHiewuB-.mjs";import{appendCdcChange as Rt}from"./CDC_LOG_TABLE-BnqlH2eZ.mjs";import{CDC_LOG_TABLE as hr,applyCdcChanges as pr,bumpCdcEpoch as mr,minCdcSeq as $r,readCdcChanges as wr,readCdcCursor as gr,readCdcEpoch as br,trimCdcChanges as yr}from"./CDC_LOG_TABLE-BnqlH2eZ.mjs";import{createCompanionSync as vt}from"./createCompanionSync-DWK0Vlg1.mjs";import{computeRankPage as Ve}from"./computeRankPage-IUSS-zIB.mjs";import{SCAN_DEP as B}from"./SCAN_DEP-D_yR9EeV.mjs";import{runDrizzle as q}from"./runDrizzle-GKR3y97k.mjs";import{DOC_COLUMN as U,quoteIdentifier as It,AGG_VALUE as Te,AGG_COUNT as Me,AGG_KEY as Ae,jsonPathSql as K,rowToDocument as se,tableColumns as ut,isFtsAvailable as xt,tryRowToDocument as ft,geoTableName as Ct,qualifiedJsonPathSql as Ye}from"./AGG_COUNT-BWXe3gtQ.mjs";import{coveringGeohashes as kt,boundingBoxGeohashes as Mt,pointInBoundingBox as Lt,haversineMeters as Dt}from"./GEO_DEFAULT_PRECISION-okRCkZ6r.mjs";import{NotFoundError as Ot}from"./NotFoundError-BhF7FeFr.mjs";import{normalizeOrderKeys as Wt,buildSeekWhere as ht,decodeCursor as Oe,applySelect as Xe,encodeCursor as We,softDeleteScope as ae,buildSeekBeforeWhere as Ft}from"./applySelect-B0CF8T7y.mjs";import{sortColumnName as Ze,resolveRankPartition as Bt,encodePartitionKey as qt,RANK_TIEBREAK as Ut,rankTableName as et}from"./RANK_TIEBREAK-9NU5s_mi.mjs";import{indexKeysForRow as Ht,buildIndexRange as Pt}from"./buildIndexRange-DIjFVgeO.mjs";import{assertFlatPredicate as Le,resolveRelationPredicates as tt}from"./DEFAULT_MAX_RELATION_KEYS-bq00btqV.mjs";import{runRowValidators as De,resolveWith as nt,applyOnDelete as jt,fanOutScalarCounts as Gt}from"./applyOnDelete-uFRC5p1d.mjs";import{guardWriter as Kt}from"./RLS_UNWRAP_SYMBOL-C6_WX3dG.mjs";import{createSystemReader as Jt}from"./createSystemReader-DcDcrtM3.mjs";import{ConflictError as pe}from"./ConflictError-C8GtJmjS.mjs";import{runTriggers as Qt}from"./hasTrigger-CbkOHExZ.mjs";import{compileWhereSql as ee}from"./compileWhereSql-BLcfs4QW.mjs";import{CLIENT_WATERMARK_TABLE as Nr,advanceClientWatermark as Tr,migrateClientWatermark as Ar,readClientWatermark as Sr}from"./CLIENT_WATERMARK_TABLE-CXsSLU8D.mjs";import{GLOBAL_SHAPE_SNAPSHOT_TABLE as Rr,deleteGlobalShapeSnapshot as vr,deleteGlobalShapeSnapshotsForConnection as Ir,migrateGlobalShapeSnapshot as xr,readGlobalShapeSnapshot as Cr,writeGlobalShapeSnapshot as kr}from"./GLOBAL_SHAPE_SNAPSHOT_TABLE-DX-6-gBP.mjs";import{IDEMPOTENCY_TABLE as Lr,readIdempotent as Dr,trimIdempotent as Or,writeIdempotent as Wr}from"./IDEMPOTENCY_TABLE-DjkEMp6w.mjs";import{runShardMigrations as Br}from"./runShardMigrations-CPxqCh3O.mjs";import{SEARCH_STATE_TABLE as Ur}from"./SEARCH_STATE_TABLE-eLN8U5tz.mjs";import{selectShapeMemberIds as Pr,selectShapeRows as jr}from"./selectShapeMemberIds-DvE7K6zG.mjs";import{serializeSqlValue as te}from"./serializeSqlValue-DnpyaLcw.mjs";const zt=o=>{const a=new TextEncoder().encode(o);let n="";for(const d of a)n+=String.fromCodePoint(d);return btoa(n)},Vt=o=>{const a=atob(o),n=Uint8Array.from(a,d=>d.codePointAt(0)??0);return new TextDecoder().decode(n)},Yt=()=>new y("BAD_REQUEST","invalid cursor"),rt=16,ot=8,Y=1024,qe=(o,a)=>a.query(o),Xt=(o,a,n)=>{const d=gt(o,n);if(d.length===0)return 0;let h=0;for(const[$,N]of a.entries()){const R=$===a.length-1;let p=0;for(const w of d)(R?w.startsWith(N):w===N)&&(p+=1);if(p===0)return 0;h+=p}return h},Zt=(o,a)=>{if(!a)return{exact:!0,lower:o,upper:o};const n=o.codePointAt(o.length-1)??0,d=o.slice(0,Math.max(0,o.length-String.fromCodePoint(n).length));return{exact:!1,lower:o,upper:d+String.fromCodePoint(n+1)}},en=(o,a,n)=>{const d={eq:(h,$)=>{if(!o.definition.filterFields?.includes(h))throw new y("INTERNAL",`field "${h}" is not a filter field of search index "${o.indexName}" on table "${a}"`);if(o.filters.length>=ot)throw new y("BAD_REQUEST",`search index "${o.indexName}" on table "${a}": at most ${String(ot)} .eq() filters are supported per search query`);return o.filters.push({field:h,value:$}),d},search:(h,$)=>{const N=o;if(h!==N.definition.field)throw new y("INTERNAL",`search index "${N.indexName}" on table "${a}" indexes "${N.definition.field}", not "${h}"`);const R=qe($,n).length;if(R>rt)throw new y("BAD_REQUEST",`search index "${N.indexName}" on table "${a}": at most ${String(rt)} search terms are supported (got ${String(R)})`);return N.field=h,N.query=$,N.hasQuery=!0,d}};return d},tn=o=>{if(o.length>Y)throw new y("BAD_REQUEST",`more than ${String(Y)} documents match this search — narrow it with filters or read it a page at a time with .paginate()`)},nn=o=>Math.min(o.offset+o.numItems+1,Y),rn=o=>zt(`search:${String(o)}`),on=o=>{let a;try{a=Vt(o)}catch{return}if(!a.startsWith("search:"))return;const n=Number(a.slice(7));return Number.isInteger(n)&&n>=0?n:void 0},an=o=>{if(typeof o.endCursor=="string")throw new y("BAD_REQUEST","bounded (endCursor) pagination is not supported on search queries — relevance order has no stable range boundary");const a=Math.max(0,Math.floor(o.numItems)),n=o.cursor?on(o.cursor):0;if(n===void 0)throw Yt();if(n+a>Y)throw new y("BAD_REQUEST",`search pagination reaches past the ${String(Y)}-document limit (offset ${String(n)} + ${String(a)} requested) — narrow the query or the filters instead`);return{numItems:a,offset:n}},sn=(o,a)=>{const n=a.offset+a.numItems,d=a.numItems>0&&o.length>n;return{continueCursor:d?rn(n):null,isDone:!d,page:o.slice(a.offset,n)}},ln=o=>{if(o===void 0)return Y+1;if(!Number.isFinite(o))return Y;const a=Math.max(0,Math.floor(o));if(a>Y)throw new y("BAD_REQUEST",`search returns at most ${String(Y)} documents (asked for ${String(a)}) — narrow the query or paginate instead`);return a},dn=/^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/iu,cn=o=>{if(!dn.test(o))throw new y("INTERNAL",`invalid clientId ${JSON.stringify(o)}: a client-supplied row id must be a UUID`)},it=50,pt=500,un=128,ie=(o,a,n)=>{const d=a??pt;if(o>d)throw new y("BATCH_LIMIT_EXCEEDED",`${n}: batch of ${String(o)} exceeds the limit of ${String(d)} (raise options.limit or chunk the call)`,{status:400})},fn=o=>{const a={eq:(n,d)=>(o.sqlConditions.push({comparator:"=",field:n,value:d}),a),gt:(n,d)=>(o.sqlConditions.push({comparator:">",field:n,value:d}),a),gte:(n,d)=>(o.sqlConditions.push({comparator:">=",field:n,value:d}),a),lt:(n,d)=>(o.sqlConditions.push({comparator:"<",field:n,value:d}),a),lte:(n,d)=>(o.sqlConditions.push({comparator:"<=",field:n,value:d}),a)};return a},hn=o=>Math.max(o,Y),pn=(o,a,n,d,h)=>{const $=qe(n.query,Be(n.definition.language));if($.length===0)return[];const N=yt(a,n.indexName),R=`${N}__vocab`,p=$.length-1,w=$.map((I,S)=>{const b=Zt(I,S===p),x=b.exact?t`${t.identifier("term")} = ${b.lower}`:t`${t.identifier("term")} >= ${b.lower} AND ${t.identifier("term")} < ${b.upper}`;return t`SELECT ${t.identifier("doc")}, ${t.raw(String(S))} AS ${t.identifier("__term__")}, COUNT(*) AS ${t.identifier("__n__")} FROM ${t.identifier(R)} WHERE ${x} GROUP BY ${t.identifier("doc")}`}),D=$.map((I,S)=>t`SUM(CASE WHEN u.${t.identifier("__term__")} = ${t.raw(String(S))} THEN u.${t.identifier("__n__")} ELSE 0 END)`),T=t`SELECT f.${t.identifier(Ee)} AS ${t.identifier(Ee)}, ${t.join(D,t` + `)} AS ${t.identifier("__score__")} FROM (${t.join(w,t` UNION ALL `)}) u JOIN ${t.identifier(N)} f ON f.rowid = u.${t.identifier("doc")} GROUP BY f.${t.identifier(Ee)} HAVING ${t.join(D.map(I=>t`${I} > 0`),t` AND `)}`,A=[];for(const I of n.filters)A.push(t`${K(I.field)} = ${te(I.value)}`);h&&A.push(h);let k=t`SELECT m.id, m._creationTime, m.${t.identifier(U)} FROM (${T}) s JOIN ${t.identifier(a)} m ON m.id = s.${t.identifier(Ee)}`;A.length>0&&(k=t`${k} WHERE ${t.join(A,t` AND `)}`),k=t`${k} ORDER BY s.${t.identifier("__score__")} DESC, m._creationTime DESC, m.id ASC LIMIT ${t.raw(String(d))}`;const C=[];for(const I of q(o,k)){const S=ft(I);S&&C.push(S)}return C},mn=(o,a,n,d,h)=>{const $=Be(n.definition.language),N=qe(n.query,$);if(N.length===0)return[];const R=[];for(const T of n.filters)R.push(t`${K(T.field)} = ${te(T.value)}`);h&&R.push(h);let p=t`SELECT id, _creationTime, ${t.identifier(U)} FROM ${t.identifier(a)}`;R.length>0&&(p=t`${p} WHERE ${t.join(R,t` AND `)}`),p=t`${p} ORDER BY _creationTime DESC, id ASC LIMIT ${t.raw(String(hn(d)))}`;const w=q(o,p).toArray(),D=[];for(const T of w){const A=ft(T);if(!A)continue;const k=Xt(bt(A,n.definition),N,$);k>0&&D.push({creationTime:typeof A._creationTime=="number"?A._creationTime:0,doc:A,id:typeof A._id=="string"?A._id:"",score:k})}return D.sort((T,A)=>A.score-T.score||A.creationTime-T.creationTime||T.id.localeCompare(A.id)),D.slice(0,d).map(T=>T.doc)},$n=(o,a)=>{const n=o,d={near:(h,$)=>{if(n.within)throw new y("INTERNAL",`geo index "${n.indexName}" on table "${a}": call .near() or .within(), not both`);return n.near={point:{lat:h.lat,lng:h.lng},radiusMeters:$},d},within:h=>{if(n.near)throw new y("INTERNAL",`geo index "${n.indexName}" on table "${a}": call .near() or .within(), not both`);return n.within={ne:{lat:h.ne.lat,lng:h.ne.lng},sw:{lat:h.sw.lat,lng:h.sw.lng}},d}};return d},wn=(o,a)=>{const n=o[a];if(n===null||typeof n!="object")return;const{lat:d,lng:h}=n;return typeof d=="number"&&typeof h=="number"?{lat:d,lng:h}:void 0},gn=(o,a)=>{const n=wn(o,a.definition.field);if(!n)return;const d=typeof o._creationTime=="number"?o._creationTime:0;if(a.near){const h=Dt(a.near.point,n);return h<=a.near.radiusMeters?{creationTime:d,distance:h}:void 0}return Lt(n,a.within)?{creationTime:d,distance:0}:void 0},bn=(o,a,n,d,h,$=()=>{})=>{if(!n.near&&!n.within)throw new y("INTERNAL",`geo index "${n.indexName}" on table "${a}": call .near(point, radius) or .within(box)`);const N=n.near?kt(n.near.point,n.near.radiusMeters):Mt(n.within),R=Ct(a,n.indexName),p=N.map(C=>t`(g.${t.identifier("__geohash__")} >= ${C} AND g.${t.identifier("__geohash__")} < ${`${C}{`})`),w=[t`(${t.join(p,t` OR `)})`];h&&w.push(h);const D=t`SELECT m.id, m._creationTime, m.${t.identifier(U)} FROM ${t.identifier(R)} g JOIN ${t.identifier(a)} m ON m.id = g.${t.identifier("__id__")} WHERE ${t.join(w,t` AND `)}`,T=q(o,D).toArray(),A=[];for(const C of T){const I=se(C),S=I?gn(I,n):void 0;I&&S&&A.push({creationTime:S.creationTime,distance:S.distance,doc:I})}A.sort((C,I)=>C.distance-I.distance||I.creationTime-C.creationTime);const k=A.map(C=>C.doc);return $(k.length),typeof d=="number"?k.slice(0,Math.max(0,Math.floor(d))):k},yn=(o,a,n,d,h,$=()=>{})=>{const{geo:N}=n;if(!N)throw new y("INTERNAL","runGeoTerminal called without a staged geo query");const R=n.inMemoryFilters.length>0,p=bn(o,a,N,R?void 0:h,d,$);if(!R)return p;const w=[];for(const D of p)if(n.inMemoryFilters.every(T=>T(D))&&(w.push(D),typeof h=="number"&&w.length>=h))break;return w},En=(o,a,n,d,h,$,N=()=>{})=>{const R=[];for(const T of n.sqlConditions)R.push(t`${K(T.field)} ${t.raw(T.comparator)} ${te(T.value)}`);d&&R.push(d);let p=t`SELECT id, _creationTime, ${t.identifier(U)} FROM ${t.identifier(a)}`;R.length>0&&(p=t`${p} WHERE ${t.join(R,t` AND `)}`),p=t`${p} ORDER BY ${h}`,typeof $=="number"&&n.inMemoryFilters.length===0&&(p=t`${p} LIMIT ${t.raw(String(Math.max(0,Math.floor($))))}`);const w=q(o,p).toArray();N(w.length);const D=[];for(const T of w){const A=se(T);if(A&&n.inMemoryFilters.every(k=>k(A))&&(D.push(A),typeof $=="number"&&D.length>=$))break}return D},re={fieldRef:K,serialize:te},Nn=o=>{let a=0;const n=[],d={fieldRef:K,relationExists:h=>{const{childWhere:$,negated:N,parentTable:R,relation:p}=h,w=`__rel_${String(a)}`,D=n.at(-1)??R;a+=1,o(p.table,B);const T=p.kind==="one"?p.field:p.references,A=p.kind==="one"?p.references:p.field,k=t`${Ye(w,A)} = ${Ye(D,T)}`;n.push(w);const C=ee($,d);n.pop();const I=C?t`${k} AND ${C}`:k,S=t`EXISTS (SELECT 1 FROM ${t.identifier(p.table)} AS ${t.identifier(w)} WHERE ${I})`;return N?t`NOT ${S}`:S},serialize:te};return d},mt=o=>{const a=o.map(n=>t`${K(n.field)} ${t.raw(n.direction==="desc"?"DESC":"ASC")}`);return o.some(n=>n.field==="_id"||n.field==="id")||a.push(t`${K("id")} ASC`),t.join(a,t`, `)},Tn={"<":"lt","<=":"lte","=":"eq",">":"gt",">=":"gte"},An=o=>{const a=o.order;return o.indexFields.length>0?o.indexFields.map(n=>({direction:a,field:n})):[{direction:a,field:"_creationTime"}]},Sn=(o,a,n,d)=>{const h=o.sqlConditions.map($=>({[$.field]:{[Tn[$.comparator]??"eq"]:$.value}}));if(n&&h.push(ht(a,Oe(n))),d&&h.push(Ft(a,Oe(d))),h.length!==0)return h.length===1?h[0]:{AND:h}},_n=(o,a,n)=>{const d=[];for(const h of o){const $=se(h);if($&&a.every(N=>N($))&&(d.push($),n!==void 0&&d.length>n))break}return d},Rn=(o,a,n,d,h,$=()=>{})=>{const N=Math.max(0,Math.floor(d.numItems)),R=An(n),p=typeof d.endCursor=="string",w=ee(Sn(n,R,d.cursor,d.endCursor),re),D=h&&w?t`${w} AND ${h}`:h??w;let T=t`SELECT id, _creationTime, ${t.identifier(U)} FROM ${t.identifier(a)}`;D&&(T=t`${T} WHERE ${D}`),T=t`${T} ORDER BY ${mt(R)}`;const A=n.inMemoryFilters.length>0;!A&&!p&&(T=t`${T} LIMIT ${t.raw(String(N+1))}`);const k=q(o,T).toArray();$(k.length);const C=_n(k,n.inMemoryFilters,A||p?void 0:N);if(p){const x=C.length>=2?C[Math.floor(C.length/2)-1]:void 0;return{continueCursor:d.endCursor??null,isDone:!0,page:C,splitCursor:x?We(x,R):null}}const I=C.length>N,S=I?C.slice(0,N):C,b=S.at(-1);return{continueCursor:I&&b?We(b,R):null,isDone:!I,page:S}};class vn extends y{constructor(a="unique() found more than one matching document"){super("NOT_UNIQUE",a,{name:"NotUniqueError"})}}const In=/\s/u,xn=String.fromCodePoint(0),at=(o,a,n)=>{if(!o.tables[a])throw new y("INTERNAL",`unknown table: ${a}`);return typeof n!="string"||n.length===0||In.test(n)||n.includes(xn)?null:n},Cn=(o,a,n,d=()=>{},h=()=>{},$=()=>{})=>{const N=a.tables[n];if(!N)throw new y("INTERNAL",`unknown table: ${n}`);const R=ae(N.softDeleteMode,void 0),p=R?ee(R,re):void 0,w={indexFields:[],indexName:void 0,inMemoryFilters:[],order:"asc",sqlConditions:[]};let D=0;const T=b=>{const{search:x}=w;if(!x)throw new y("INTERNAL","runSearchFetch called without a staged search");_t(o,n,N);const M=w.inMemoryFilters.length>0,L=ln(M?void 0:b),H=xt(o)?pn(o,n,x,L,p):mn(o,n,x,L,p);if(!M)return b===void 0&&tn(H),H;const V=[];D=H.length;for(const le of H)if(w.inMemoryFilters.every(de=>de(le))&&(V.push(le),typeof b=="number"&&V.length>=b))break;return V},A=b=>{const x=an(b);return sn(T(nn(x)),x)},k=()=>{const b=w.indexFields.length>0?w.indexFields:["_creationTime"],x=w.order==="desc"?"DESC":"ASC";return t.join(b.map(M=>t`${K(M)} ${t.raw(x)}`),t`, `)},C=()=>{if(w.search||w.geo||w.indexName===void 0){h(void 0);return}h(Pt(n,w.indexName,w.indexFields,w.sqlConditions,te))},I=b=>{C();let x=0;const M=(()=>{if(w.search){const L=T(b);return x=D,L}return w.geo?yn(o,n,w,p,b,L=>{x=L}):En(o,n,w,p,k(),b,L=>{x=L})})();return $(Math.max(x,M.length)),M},S={async*[Symbol.asyncIterator](){const b=[...w.inMemoryFilters];let x;w.inMemoryFilters=[];try{for(;;){const M=await S.paginate({cursor:x??null,numItems:un});for(const L of M.page)b.every(H=>H(L))&&(yield L);if(M.isDone||M.continueCursor===null)return;x=M.continueCursor}}finally{w.inMemoryFilters=b}},async collect(){return I(void 0)},filter(b){return w.inMemoryFilters.push(b),S},async first(){return I(w.inMemoryFilters.length>0?void 0:1)[0]??null},order(b){return w.order=b==="desc"?"desc":"asc",S},async paginate(b){let x=0;if(C(),w.search){const L=A(b);return $(L.page.length),L}if(w.geo)throw new y("INTERNAL","pagination is not supported on geo queries; use .take(n) or .collect()");const M=Rn(o,n,w,b,p,L=>{x=L});return $(Math.max(x,M.page.length)),M},async take(b){return I(b)},async unique(){const b=I(w.inMemoryFilters.length>0?void 0:2);if(b.length>1)throw new vn(`unique() on table "${n}" matched ${String(b.length)} documents; expected at most one`);return b[0]??null},withGeoIndex(b,x){const M=(N.geoIndexes??[]).find(H=>H.name===b);if(!M)throw new y("INTERNAL",`unknown geo index "${b}" on table "${n}"`);d(n,b,"geo");const L={definition:M,indexName:b};if(w.geo=L,x($n(L,n)),!L.near&&!L.within)throw new y("INTERNAL",`geo index "${b}" on table "${n}" requires a .near(point, radius) or .within(box) call`);return S},withIndex(b,x){const M=N.indexes.find(L=>L.name===b);if(!M)throw new y("INTERNAL",`unknown index "${b}" on table "${n}"`);return d(n,b,"index"),w.indexName=b,w.indexFields=M.fields,x&&x(fn(w)),S},withSearchIndex(b,x){const M=(N.searchIndexes??[]).find(H=>H.name===b);if(!M)throw new y("INTERNAL",`unknown search index "${b}" on table "${n}"`);d(n,b,"search");const L={definition:M,field:M.field,filters:[],hasQuery:!1,indexName:b,query:""};if(w.search=L,x(en(L,n,Be(M.language))),!L.hasQuery)throw new y("INTERNAL",`search index "${b}" on table "${n}" requires a .search(field, query) call`);return S}};return S},st=(o,a,n)=>{const d={...a};for(const[h,$]of ut(o)){if($.serverDefault){d[h]=$.serverDefault({auth:n});continue}d[h]===void 0&&($.defaultFn?d[h]=$.defaultFn():"defaultValue"in $&&(d[h]=$.defaultValue))}return d},lt=(o,a,n,d)=>{const h=n;for(const[$,N]of ut(o)){if(N.serverDefault){$ in a&&(h[$]=N.serverDefault({auth:d}));continue}N.onUpdateFn&&!($ in a)&&(h[$]=N.onUpdateFn())}},dt=(o,a)=>{for(const n of Object.keys(a))if(a[n]===void 0)throw new y("INTERNAL",`Cannot ${o} field '${n}' to undefined — use null to clear a nullable field, or omit the key to leave it unchanged.`)},kn=/unique constraint failed/i,Mn=o=>o instanceof Error&&kn.test(o.message),Fe=(o,a,n)=>{try{q(o,n)}catch(d){throw Mn(d)?new pe(`unique constraint violation on "${a}"`,"unique"):d}},Se=(o,a,n)=>{if(Fe(o,a,n),q(o,t`SELECT changes() AS changed`).one().changed===0)throw new pe(`optimistic concurrency conflict on "${a}" — the row changed during this mutation; refetch and retry`,"occ")},ct=(o,a,n,d,h,$,N)=>{const R=[];for(let T=0;T<n.length+1;T+=1){const A=[];for(let S=0;S<T;S+=1)A.push(t`${t.identifier(n[S])} IS ${$[S]}`);const k=n[T],C=d[T];if(k!==void 0&&C!==void 0){const S=C.direction==="desc"?">":"<";A.push(t`${t.identifier(k)} ${t.raw(S)} ${$[T]}`)}else A.push(t`${t.identifier(Ut)} < ${N}`);const[I]=A;R.push(A.length===1&&I!==void 0?I:t`(${t.join(A,t` AND `)})`)}const p=t.join(R,t` OR `),w=q(o,t`SELECT COUNT(*) AS c FROM ${t.identifier(a)} WHERE ${t.identifier("__partition__")} = ${h} AND (${p})`).one(),D=q(o,t`SELECT COUNT(*) AS c FROM ${t.identifier(a)} WHERE ${t.identifier("__partition__")} = ${h}`).one();return{before:w.c,total:D.c}},ar=o=>{const{sql:a}=o,{schema:n}=o,d=o.broadcast??(()=>{}),h=(e,...r)=>{const i=n.tables[e]?.indexes;if(!i||i.length===0)return;const f=[];for(const u of r)u&&f.push(...Ht(i,u,te));return f.length>0?f:void 0},{headroom:$}=o,N=o.onRead??(()=>{}),R=o.onReadRange??(e=>{N(e.table,B)}),p=(e,r)=>{r!==void 0&&r!==B&&$?.recordRead(1),N(e,r)},w=o.onIndexUse??(()=>{}),D=o.onWrite??(()=>{}),T=async e=>{$?.recordWrite(e.doc),await D(e)},{cache:A}=o,k=o.clock??(()=>Date.now()),C=o.idGenerator??(()=>crypto.randomUUID()),I=o.scheduler??Nt,{globalDb:S}=o,b=o.auth??{identity:null,userId:null},x=o.cdc??!1,M=I,L=Jt({scheduler:typeof M.list=="function"&&typeof M.get=="function"?M:void 0,storage:o.storage}),H=(e,r,i,f)=>{x&&Rt(a,k(),e,r,i,f)},V=e=>n.tables[e]?.shardMode?.kind==="global",le=(e,r)=>{if(V(e)){if(!S)throw new y("INTERNAL",`cross-backend ${r} for global table '${e}' requires a globalDb writer — pass one to createShardCtxDb({ globalDb })`);return S}return F},de=e=>le(e,"cascade"),J=(e,r)=>{if(V(e)){if(!S)throw new y("INTERNAL",`${r} on global table '${e}' requires a globalDb writer — pass one to createShardCtxDb({ globalDb })`);return S}},ce=()=>S,_e=(e,r)=>le(e,"relation load").findMany(e,r),Ue=(e,r)=>(V(e)&&p(e,B),_e(e,r)),$t=e=>!V(e.table),He=o.relationExistsPushDown??"auto",Pe=He!=="never",{maxRelationKeys:je}=o,me=(e,r,i)=>tt(e,{fetcher:Ue,maxRelationKeys:je,relationBaseWhere:i,schema:n,tableName:r}),Ge=async(e,r,i,f)=>{const u=J(e,"relation grouped count");if(u)return p(e,B),Gt((v,j)=>u.count(v,j),e,r,i,f);const l=n.tables[e];if(!l)throw new y("INTERNAL",`unknown table: ${e}`);p(e,B);const s=ae(l.softDeleteMode,void 0),c={[r]:{in:i}},m=G(G(c,f),s),E=await me(m,e,void 0),g=ee(E,re),_=K(r);let W=t`SELECT ${_} AS __fk__, COUNT(*) AS count FROM ${t.identifier(e)}`;g&&(W=t`${W} WHERE ${g}`),W=t`${W} GROUP BY ${_}`;const O=q(a,W).toArray();return new Map(O.map(v=>[v.__fk__,v.count]))};let $e=0;const Ke=new Set;for(const[e,r]of Object.entries(n.tables))for(const i of Object.values(r.triggerMap??{}))Ke.add(`${e} ${i.timing} ${i.op}`);const X=(e,r,i)=>Ke.has(`${e} ${r} ${i}`),Z=async(e,r,i)=>{if($e+=1,$e>it)throw $e-=1,new pe(`trigger recursion exceeded ${String(it)} levels on "${i.table}" — check for a self-triggering write`,"trigger");try{await Qt({ctx:wt,event:i,op:r,schema:n,tableName:i.table,timing:e})}finally{$e-=1}},{ensureBackfilledForTable:ue,ensureBackfilledIndex:Re,ensureRankBackfilled:ve,ensureRankBackfilledForTable:fe,syncAggregates:we,syncCompanionsForInsert:Je,syncGeo:ge,syncRanks:he,syncSearch:be}=vt({broadcast:d,indexKeysFor:(e,r)=>h(e,r),invalidateCache:(e,r,i)=>A?.invalidate(e,r,h(e,i)),recordCdc:H,schema:n,sql:a}),Qe=(e,r,i)=>{const{shardMode:f}=r;if(f?.kind==="shardBy"&&!(f.field!==void 0&&(i.partitionBy??[]).includes(f.field)))throw Object.assign(new Error(`rank index "${i.name}" on "${e}" partitions across shards (shard key "${f.field??"?"}" is not in partitionBy) — a shard-local rank()/rankPage() would be wrong; roll it up through the Query Coordinator instead`),{code:"CROSS_SHARD_RANK_UNSUPPORTED",name:"LunoraError",status:400})},ne=(e,r)=>{const i=Object.entries(n.tables).filter(([,E])=>E.shardMode?.kind!=="global").map(([E])=>E).filter(E=>r===void 0||E===r);if(i.length===0)return;const f=i.map(E=>t`SELECT ${t.raw(`'${E.replaceAll("'","''")}'`)} AS __t__, id, _creationTime, ${t.identifier(U)} FROM ${t.identifier(E)} WHERE id = ${e}`),u=t`${t.join(f,t` UNION ALL `)} LIMIT 1`,[l]=q(a,u).toArray();if(!l)return;const s=l.__t__,c=se(l);if(typeof s!="string"||!c)return;const m=l[U];return{docJson:typeof m=="string"?m:JSON.stringify(m??{}),row:c,tableName:s}},ze={assertRankPartitionLocal:Qe,ensureRankBackfilled:ve,onRead:p,rowToDocument:se,schema:n,sql:a},F={system:L,async aggregate(e,r){const i=J(e,"aggregate");if(i)return p(e,B),i.aggregate(e,r);const f=n.tables[e];if(!f)throw new y("INTERNAL",`unknown table: ${e}`);if(Ne(r.op),r.op==="count")return F.count(e,{baseWhere:r.baseWhere,relationBaseWhere:r.relationBaseWhere,restrictsCounts:r.restrictsCounts,where:r.where});if(!r.field)throw new y("INTERNAL",`aggregate(${e}, { op: "${r.op}" }): "field" is required for non-count reducers`);p(e,B);const u=ae(f.softDeleteMode,void 0),l=G(G(r.baseWhere,r.where),u),s=await me(l,e,r.relationBaseWhere),c=s!==l;if(f.aggregateIndexes&&!r.baseWhere&&!c&&!u){const O=St(f.aggregateIndexes,r.op,r.field,r.where);if(O){Re(e,O.index);const v=Ie(O.index.by??[],O.key),j=Ce(e,O.index.name),Q=q(a,t`SELECT ${Te} AS value, ${Me} AS count FROM ${t.identifier(j)} WHERE ${Ae} = ${v}`).toArray()[0];return xe(r.op,Q)}}const m=ee(s,re),E=Ne(r.op),g=K(r.field);let _=t`SELECT ${t.raw(E)}(${g}) AS value FROM ${t.identifier(e)}`;return m&&(_=t`${_} WHERE ${m}`),q(a,_).toArray()[0]?.value??null},asId(e,r){const i=at(n,e,r);if(i===null)throw new y("BAD_REQUEST",`asId("${e}", …): "${r}" is not a valid id for table "${e}"`,{status:400});return i},async count(e,r){const i=J(e,"count");if(i)return p(e,B),i.count(e,r);const f=n.tables[e];if(!f)throw new y("INTERNAL",`unknown table: ${e}`);const u=Et(r);if(u.restrictsCounts)throw new ke(e);p(e,B);const l=ae(f.softDeleteMode,void 0),s=G(G(u.baseWhere,u.where),l),c=await me(s,e,u.relationBaseWhere),m=c!==s;if(f.aggregateIndexes&&!u.baseWhere&&!m&&!l){const _=At(f.aggregateIndexes,u.where);if(_){Re(e,_.index);const W=Ie(_.index.by??[],_.key),O=Ce(e,_.index.name),v=q(a,t`SELECT ${Te} AS value FROM ${t.identifier(O)} WHERE ${Ae} = ${W}`).toArray();return v[0]===void 0?0:v[0].value??0}}const E=ee(c,re);let g=t`SELECT COUNT(*) AS count FROM ${t.identifier(e)}`;return E&&(g=t`${g} WHERE ${E}`),q(a,g).one().count},async delete(e,r,i){const f=ne(e,r);if(!f){const g=r===void 0?ce():void 0;g&&await g.delete(e,void 0,i);return}const{docJson:u,row:l,tableName:s}=f,c=n.tables[s],m=i?.hard===!0,E=!m&&c?.softDeleteMode?c.softDeleteMode.field:void 0;if(!(E&&l[E]!==null&&l[E]!==void 0)){if(X(s,"before","delete")&&await Z("before","delete",{id:e,op:"delete",previous:l,table:s}),await jt({deletedId:e,deletedReference:g=>l[g],findHolders:async(g,_,W)=>(await de(g).findMany(g,{includeDeleted:m,where:{[_]:W}})).page,onCascade:(g,_)=>de(g).delete(_,void 0,i),onRestrict:g=>{throw new pe(g,"restrict")},onSetNull:(g,_,W)=>de(g).patch(_,{[W]:null}),schema:n,tableName:s}),ue(s),fe(s),E){const g={...l,[E]:k(),_id:e};Se(a,s,t`UPDATE ${t.identifier(s)} SET ${t.identifier(U)} = ${JSON.stringify(g)} WHERE id = ${e} AND ${t.identifier(U)} = ${u}`),be(s,e,g,l),ge(s,e,void 0),we(s,l,g),he(s,e,l,void 0),A?.invalidate(s,e,h(s,l,g)),H(s,e,"update",g),d({indexKeys:h(s,l,g),key:e,op:"update",row:g,table:s}),X(s,"after","delete")&&await Z("after","delete",{id:e,op:"delete",previous:l,table:s}),await T({id:e,op:"delete",table:s});return}Se(a,s,t`DELETE FROM ${t.identifier(s)} WHERE id = ${e} AND ${t.identifier(U)} = ${u}`),be(s,e,void 0),ge(s,e,void 0),we(s,l,void 0),he(s,e,l,void 0),A?.invalidate(s,e,h(s,l)),H(s,e,"delete"),d({indexKeys:h(s,l),key:e,op:"delete",table:s}),X(s,"after","delete")&&await Z("after","delete",{id:e,op:"delete",previous:l,table:s}),await T({id:e,op:"delete",table:s})}},async deleteAll(e,r){if(!n.tables[e])throw new y("INTERNAL",`unknown table: ${e}`);const i=Math.max(1,r?.chunkSize??pt),f=r?.hard===void 0?void 0:{hard:r.hard},u=V(e)?void 0:e;let l=0;for(;;){const s=(await F.findMany(e,{limit:i})).page.map(c=>String(c._id));if(s.length===0)break;for(const c of s)await F.delete(c,u,f),l+=1;if(s.length<i)break}return{deleted:l}},async deleteMany(e,r,i){ie(e.length,r?.limit,"deleteMany");for(const f of e)await F.delete(f,i);return{deleted:e.length}},async deleteWhere(e,r,i){const f=J(e,"deleteWhere");let u;if(f)u=(await f.findMany(e,{where:r})).page.map(l=>String(l._id));else{if(!n.tables[e])throw new y("INTERNAL",`unknown table: ${e}`);u=(await F.findMany(e,{where:r})).page.map(l=>String(l._id))}if(ie(u.length,i?.limit,"deleteWhere"),F.deleteMany===void 0)throw new y("INTERNAL",`ctx.db.${e}.deleteMany is unavailable: this writer has no batch delete`);return F.deleteMany(u,i)},async findFirst(e,r={}){return(await F.findMany(e,{...r,limit:1})).page[0]??null},async findFirstOrThrow(e,r={}){const i=await F.findFirst(e,r);if(i===null)throw new Ot(`findFirstOrThrow: no "${e}" document matched`);return i},async findMany(e,r={}){const i=J(e,"findMany");if(i)return p(e,B),i.findMany(e,r);const f=n.tables[e];if(!f)throw new y("INTERNAL",`unknown table: ${e}`);const u=!r.where&&!r.baseWhere;u?p(e,B):p(e);const l=Wt(r.orderBy),s=r.cursor?ht(l,Oe(r.cursor)):void 0;let c=G(r.baseWhere,r.where);c=G(c,ae(f.softDeleteMode,r.includeDeleted)),c=await tt(c,{canPushExists:Pe?$t:void 0,existsPushMode:He==="always"?"always":"auto",fetcher:Ue,maxRelationKeys:je,relationBaseWhere:r.relationBaseWhere,schema:n,tableName:e}),s&&(c=c?{AND:[c,s]}:s);const m=Pe?Nn(p):re,E=ee(c,m);let g=t`SELECT id, _creationTime, ${t.identifier(U)} FROM ${t.identifier(e)}`;E&&(g=t`${g} WHERE ${E}`),g=t`${g} ORDER BY ${mt(l)}`;const _=typeof r.limit=="number"?Math.max(0,Math.floor(r.limit)):void 0;_!==void 0&&(g=t`${g} LIMIT ${t.raw(String(_+1))}`);const W=q(a,g).toArray();u&&$?.recordRead(W.length);const O=[];for(const z of W){const P=se(z);P&&(O.push(P),!u&&typeof P._id=="string"&&p(e,P._id))}if(_===void 0)return r.with&&await nt({groupedCounter:Ge,fetcher:_e,parents:O,relationBaseWhere:r.relationBaseWhere,schema:n,tableName:e,with:r.with}),{continueCursor:null,isDone:!0,page:Xe(O,r.select,r.with)};const v=O.length>_,j=v?O.slice(0,_):O,Q=j.at(-1);return r.with&&await nt({fetcher:_e,groupedCounter:Ge,parents:j,relationBaseWhere:r.relationBaseWhere,schema:n,tableName:e,with:r.with}),{continueCursor:v&&Q?We(Q,l):null,isDone:!v,page:Xe(j,r.select,r.with)}},async get(e,r){const i=ne(e,r);if(!i){const f=r===void 0?ce():void 0;return f?f.get(e):null}return p(i.tableName,e),i.row},async lookupById(e,r){const i=ne(e,r);return i?(p(i.tableName,e),{row:i.row,tableName:i.tableName}):null},async groupBy(e,r){const i=J(e,"groupBy");if(i)return p(e,B),i.groupBy(e,r);const f=n.tables[e];if(!f)throw new y("INTERNAL",`unknown table: ${e}`);p(e,B);const u=r.agg??{op:"count"};if(Ne(u.op),u.op!=="count"&&!u.field)throw new y("INTERNAL",`groupBy(${e}, { agg: { op: "${u.op}" } }): "field" is required for non-count reducers`);const l=ae(f.softDeleteMode,void 0),s=G(G(r.baseWhere,r.where),l),c=await me(s,e,r.relationBaseWhere),m=c!==s;if(f.aggregateIndexes&&!r.baseWhere&&!m&&!l){const v=Tt(f.aggregateIndexes,u.op,u.field,r.by,r.where);if(v){Re(e,v.index);const j=Ce(e,v.index.name),Q=Object.keys(v.partial),z=[];if(Q.length===(v.index.by??[]).length&&Q.length>0){const oe=Ie(v.index.by??[],v.partial),ye=q(a,t`SELECT ${Te} AS value, ${Me} AS count FROM ${t.identifier(j)} WHERE ${Ae} = ${oe}`).toArray();return ye.length>0&&z.push({key:{...v.partial},value:xe(u.op,ye[0])}),z}const P=q(a,t`SELECT ${Ae} AS key, ${Te} AS value, ${Me} AS count FROM ${t.identifier(j)}`).toArray();for(const oe of P){const ye=JSON.parse(oe.key);z.push({key:ye,value:xe(u.op,oe)})}return z}}const E=ee(c,re),g=r.by.map(v=>t`${K(v)} AS ${t.identifier(v)}`);if(u.op==="count")g.push(t`COUNT(*) AS value`);else{const{field:v}=u;if(v===void 0)throw new y("INTERNAL",`groupBy(${e}, { agg: { op: "${u.op}" } }): "field" is required for non-count reducers`);g.push(t`${t.raw(Ne(u.op))}(${K(v)}) AS value`)}let _=t`SELECT ${t.join(g,t`, `)} FROM ${t.identifier(e)}`;E&&(_=t`${_} WHERE ${E}`),_=t`${_} GROUP BY ${t.join(r.by.map(v=>K(v)),t`, `)}`;const W=q(a,_).toArray(),O=[];for(const v of W){const j={};for(const z of r.by)j[z]=v[z]??null;const{value:Q}=v;O.push({key:j,value:Q==null?null:Number(Q)})}return O},async insert(e,r,i){const f=J(e,"insert");if(f){const E=await f.insert(e,r,i);return $?.recordWrite(r),d({key:E,op:"insert",row:{...r,_id:E},table:e}),E}const u=n.tables[e];if(!u)throw new y("INTERNAL",`unknown table: ${e}`);const l=st(u,r,b);De(u,l);let s;i?.clientId!==void 0?(cn(i.clientId),s=i.clientId):i?.allowExplicitId&&typeof l._id=="string"?s=l._id:s=C();const c=i?.allowExplicitId&&typeof l._creationTime=="number"?l._creationTime:k(),m={...l,_creationTime:c,_id:s};return X(e,"before","insert")&&await Z("before","insert",{doc:{...m},id:s,op:"insert",table:e}),ue(e),fe(e),Fe(a,e,t`INSERT INTO ${t.identifier(e)} (id, _creationTime, ${t.identifier(U)}) VALUES (${s}, ${c}, ${JSON.stringify(m)})`),Je(e,s,m),X(e,"after","insert")&&await Z("after","insert",{doc:m,id:s,op:"insert",table:e}),await T({doc:m,id:s,op:"insert",table:e}),s},async insertManyUnsafe(e,r,i){if(ie(r.length,i?.limit,"insertManyUnsafe"),r.length===0)return[];const f=J(e,"insert");if(f){const c=[];for(const m of r){const E=await f.insert(e,m,{allowExplicitId:i?.allowExplicitId});$?.recordWrite(m),d({key:E,op:"insert",row:{...m,_id:E},table:e}),c.push(E)}return c}const u=n.tables[e];if(!u)throw new y("INTERNAL",`unknown table: ${e}`);ue(e),fe(e);const l=r.map(c=>{const m=st(u,c,b),E=i?.allowExplicitId===!0&&typeof m._id=="string"?m._id:C(),g=i?.allowExplicitId===!0&&typeof m._creationTime=="number"?m._creationTime:k();return{creationTime:g,document:{...m,_creationTime:g,_id:E},id:E}});for(const c of l)$?.recordWrite(c.document);const s=t.join(l.map(c=>t`(${c.id}, ${c.creationTime}, ${JSON.stringify(c.document)})`),t`, `);Fe(a,e,t`INSERT INTO ${t.identifier(e)} (id, _creationTime, ${t.identifier(U)}) VALUES ${s}`);for(const{document:c,id:m}of l)Je(e,m,c),await D({doc:c,id:m,op:"insert",table:e});return l.map(c=>c.id)},async insertMany(e,r,i){ie(r.length,i?.limit,"insertMany");const f=i?.skipDuplicates===!0,u=[];for(const l of r)try{u.push(await F.insert(e,l))}catch(s){if(f&&s instanceof pe&&s.kind==="unique")u.push(null);else throw s}return u},normalizeId(e,r){return at(n,e,r)},async patch(e,r,i){const f=ne(e,i);if(!f){const E=i===void 0?ce():void 0;if(E){await E.patch(e,r);return}throw new y("INTERNAL",`document not found: ${e}`)}const{docJson:u,row:l,tableName:s}=f,c=n.tables[s];if(!c)throw new y("INTERNAL",`unknown table: ${s}`);p(s,e),dt("patch",r);const m={...l,...r,_id:e};lt(c,r,m,b),De(c,m,!0),X(s,"before","update")&&await Z("before","update",{doc:{...m},id:e,op:"update",previous:l,table:s}),ue(s),fe(s),Se(a,s,t`UPDATE ${t.identifier(s)} SET ${t.identifier(U)} = ${JSON.stringify(m)} WHERE id = ${e} AND ${t.identifier(U)} = ${u}`),be(s,e,m,l),ge(s,e,m),we(s,l,m),he(s,e,l,m),A?.invalidate(s,e,h(s,l,m)),H(s,e,"update",m),d({indexKeys:h(s,l,m),key:e,op:"update",row:m,table:s}),X(s,"after","update")&&await Z("after","update",{doc:m,id:e,op:"update",previous:l,table:s}),await T({doc:m,id:e,op:"update",table:s})},async patchMany(e,r,i){ie(e.length,r?.limit,"patchMany");for(const f of e)await F.patch(f.id,f.patch,i);return{patched:e.length}},async patchWhere(e,r,i){const f=J(e,"patchWhere");let u;if(f)u=(await f.findMany(e,{where:r.where})).page.map(l=>({id:String(l._id),patch:r.patch}));else{if(!n.tables[e])throw new y("INTERNAL",`unknown table: ${e}`);u=(await F.findMany(e,{where:r.where})).page.map(l=>({id:String(l._id),patch:r.patch}))}if(ie(u.length,i?.limit,"patchWhere"),F.patchMany===void 0)throw new y("INTERNAL",`ctx.db.${e}.patchMany is unavailable: this writer has no batch patch`);return await F.patchMany(u,i),{patched:u.length}},query(e){const r=J(e,"query");return r?(p(e,B),r.query(e)):Cn(a,n,e,w,i=>{i?R(i):p(e,B)},i=>$?.recordRead(i))},async rank(e,r,i){const f=J(e,"rank");if(f)return p(e,B),f.rank(e,r,i);w(e,r,"rank");const u=n.tables[e];if(!u)throw new y("INTERNAL",`unknown table: ${e}`);const l=u.rankIndexes?.find(P=>P.name===r);if(!l)throw new y("INTERNAL",`unknown rankIndex "${r}" on table "${e}"`);if(Qe(e,u,l),i.restrictsCounts)throw new ke(e);p(e,B),ve(e,l);const s=typeof i.row=="string"?i.row:i.row._id;if(!s)return null;const c=et(e,l.name),m=l.sortBy.map((P,oe)=>Ze(oe)),E=m.map(P=>It(P)).join(", "),g=q(a,t`SELECT ${t.identifier("__partition__")}, ${t.raw(E)} FROM ${t.identifier(c)} WHERE ${t.identifier("__id__")} = ${s}`).toArray(),[_]=g;if(_===void 0)return null;let W=_.__partition__;const O=G(i.baseWhere,i.where);Le(O,n,e,"rank");const v=Bt(l,O);if(v){const P=qt(l.partitionBy??[],v);if(P!==W)return null;W=P}const j=m.map(P=>_[P]),{before:Q,total:z}=ct(a,c,m,l.sortBy,W,j,s);return{position:Q+1,total:z}},async rankBefore(e,r,i){if(V(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 f=n.tables[e];if(!f)throw new y("INTERNAL",`unknown table: ${e}`);const u=f.rankIndexes?.find(m=>m.name===r);if(!u)throw new y("INTERNAL",`unknown rankIndex "${r}" on table "${e}"`);if(i.restrictsCounts)throw new ke(e);p(e,B),ve(e,u);const l=et(e,u.name),s=u.sortBy.map((m,E)=>Ze(E)),c=u.sortBy.map((m,E)=>te(i.sortValues[E]??null));return ct(a,l,s,u.sortBy,i.partitionKey,c,i.rowId)},async rankPage(e,r,i={}){Le(G(i.baseWhere,i.where),n,e,"rankPage");const f=J(e,"rankPage");if(f)return p(e,B),f.rankPage(e,r,i);w(e,r,"rank");const{continueCursor:u,hasMore:l,rows:s}=Ve(ze,e,r,i);return{continueCursor:u,isDone:!l,page:s.map(c=>c.doc)}},async rankPageRows(e,r,i={}){Le(G(i.baseWhere,i.where),n,e,"rankPage"),w(e,r,"rank");const{directions:f,hasMore:u,rows:l}=Ve(ze,e,r,i);return{directions:f,hasMore:u,rows:l}},async restore(e,r){const i=ne(e,r);if(!i){const l=r===void 0?ce():void 0;if(l?.restore){await l.restore(e);return}throw new y("INTERNAL",`document not found: ${e}`)}const f=n.tables[i.tableName]?.softDeleteMode?.field;if(!f)throw new y("INTERNAL",`ctx.db.restore: table "${i.tableName}" is not a .softDelete() table`);const u=i.row[f]!==null&&i.row[f]!==void 0;await F.patch(e,{[f]:null},r),u&&he(i.tableName,e,void 0,i.row)},async replace(e,r,i,f){const u=ne(e,i);if(!u){const _=i===void 0?ce():void 0;if(_){await _.replace(e,r,void 0,f);return}throw new y("INTERNAL",`document not found: ${e}`)}const{docJson:l,row:s,tableName:c}=u,m=n.tables[c];if(!m)throw new y("INTERNAL",`unknown table: ${c}`);dt("replace",r);const E=f?.allowExplicitId&&typeof r._creationTime=="number"?r._creationTime:k(),g={...r,_creationTime:E,_id:e};lt(m,r,g,b),De(m,g),X(c,"before","update")&&await Z("before","update",{doc:{...g},id:e,op:"update",previous:s,table:c}),ue(c),fe(c),Se(a,c,t`UPDATE ${t.identifier(c)} SET _creationTime = ${E}, ${t.identifier(U)} = ${JSON.stringify(g)} WHERE id = ${e} AND ${t.identifier(U)} = ${l}`),be(c,e,g,s),ge(c,e,g),we(c,s,g),he(c,e,s,g),A?.invalidate(c,e,h(c,s,g)),H(c,e,"update",g),d({indexKeys:h(c,s,g),key:e,op:"update",row:g,table:c}),X(c,"after","update")&&await Z("after","update",{doc:g,id:e,op:"update",previous:s,table:c}),await T({doc:g,id:e,op:"update",table:c})},async wipeShard(e){const r=new Set(e?.exclude),i=e?.tables,f=Object.entries(n.tables).filter(([c,m])=>r.has(c)||i!==void 0&&!i.includes(c)?!1:m.shardMode?.kind!=="global").map(([c])=>c);if(i!==void 0){for(const c of i)if(!n.tables[c])throw new y("INTERNAL",`wipeShard: unknown table: ${c}`)}const u={};let l=0;const{deleteAll:s}=F;if(s===void 0)throw new y("INTERNAL","wipeShard: this writer has no deleteAll");for(const c of f){const m=await s(c,{...e?.chunkSize===void 0?{}:{chunkSize:e.chunkSize},hard:!0});u[c]=m.deleted,l+=m.deleted}return{deleted:l,tables:u}}},wt={db:F,scheduler:I};return o.enforceRls===!0?Kt(F,n,(e,r)=>ne(e,r)?.tableName):F};export{hr as CDC_LOG_TABLE,Nr as CLIENT_WATERMARK_TABLE,Rr as GLOBAL_SHAPE_SNAPSHOT_TABLE,Lr as IDEMPOTENCY_TABLE,vn as NotUniqueError,Ur as SEARCH_STATE_TABLE,Tr as advanceClientWatermark,pr as applyCdcChanges,cn as assertValidClientId,dr as backfillAggregateIndexes,cr as backfillRankIndexes,ur as backfillSearchIndexes,mr as bumpCdcEpoch,ar as createShardCtxDb,vr as deleteGlobalShapeSnapshot,Ir as deleteGlobalShapeSnapshotsForConnection,Ar as migrateClientWatermark,xr as migrateGlobalShapeSnapshot,$r as minCdcSeq,at as normalizeIdStructurally,wr as readCdcChanges,gr as readCdcCursor,br as readCdcEpoch,Sr as readClientWatermark,Cr as readGlobalShapeSnapshot,Dr as readIdempotent,Br as runShardMigrations,Pr as selectShapeMemberIds,jr as selectShapeRows,yr as trimCdcChanges,Or as trimIdempotent,kr as writeGlobalShapeSnapshot,Wr as writeIdempotent};
@@ -0,0 +1 @@
1
+ import{stableWireKey as g}from"./stableWireKey-YEHLaX6X.mjs";import{depKey as b,SCAN_DEP as y}from"./SCAN_DEP-D_yR9EeV.mjs";import{r as p}from"./estimate-bytes-DzD3PdCc.mjs";import{keysTouchRanges as x}from"./buildIndexRange-DIjFVgeO.mjs";import{stableStringify as A}from"./stableStringify-BjLh4gvA.mjs";const m=1e3,u=4*1024*1024;class z{entries=new Map;tableIndex=new Map;rangeIndex=new Map;totalBytes=0;hits=0;misses=0;evictions=0;maxEntries;maxBytes;now;monotonic=0;constructor(t={}){this.maxEntries=t.maxEntries??m,this.maxBytes=t.maxBytes??u,this.now=t.now??(()=>(this.monotonic+=1,this.monotonic))}async run(t,s,i,e=()=>[]){const n=this.entries.get(t);if(n)return this.hits+=1,n.lastUsed=this.now(),this.entries.delete(t),this.entries.set(t,n),n.result;this.misses+=1;const h=await i(),a=e(),c=p(h,this.maxBytes),f={bytes:c,deps:s,ranges:a,lastUsed:this.now(),result:h,subscribers:new Set};this.entries.set(t,f),this.totalBytes+=c;for(const o of s){let r=this.tableIndex.get(o);r||(r=new Set,this.tableIndex.set(o,r)),r.add(t)}for(const o of a){let r=this.rangeIndex.get(o.table);r||(r=new Map,this.rangeIndex.set(o.table,r));let l=r.get(o);l||(l=new Set,r.set(o,l)),l.add(t)}return this.evict(),h}invalidate(t,s,i){const e=[];return this.collectAndDrop(b(t,s),e),this.collectAndDrop(b(t,y),e),this.dropRangeDeps(t,i,e),e}invalidateTable(t){const s=[],i=`${t}:`;for(const e of this.tableIndex.keys())e.startsWith(i)&&this.collectAndDrop(e,s);return this.dropRangeDeps(t,void 0,s),s}subscribe(t,s){const i=this.entries.get(t);i&&i.subscribers.add(s)}unsubscribe(t,s){const i=this.entries.get(t);i&&i.subscribers.delete(s)}size(){return{bytes:this.totalBytes,entries:this.entries.size}}clear(){this.entries.clear(),this.tableIndex.clear(),this.rangeIndex.clear(),this.totalBytes=0}subscribers(t){const s=this.entries.get(t);return s?[...s.subscribers]:[]}stats(){return{bytes:this.totalBytes,entries:this.entries.size,evictions:this.evictions,hits:this.hits,misses:this.misses}}dropRangeDeps(t,s,i){const e=this.rangeIndex.get(t);if(!(!e||e.size===0)){for(const[n,h]of e)if(x([n],s))for(const a of h){const c=this.entries.get(a);c&&(this.dropEntry(a,c),i.push(a))}}}collectAndDrop(t,s){const i=this.tableIndex.get(t);if(i)for(const e of i){const n=this.entries.get(e);n&&(this.dropEntry(e,n),s.push(e))}}dropEntry(t,s){this.entries.delete(t),this.totalBytes-=s.bytes;for(const i of s.deps){const e=this.tableIndex.get(i);e&&(e.delete(t),e.size===0&&this.tableIndex.delete(i))}for(const i of s.ranges){const e=this.rangeIndex.get(i.table),n=e?.get(i);n?.delete(t),e&&n?.size===0&&(e.delete(i),e.size===0&&this.rangeIndex.delete(i.table))}}evict(){if(!(this.entries.size<=this.maxEntries&&this.totalBytes<=this.maxBytes))for(const[t,s]of this.entries){if(this.entries.size<=this.maxEntries&&this.totalBytes<=this.maxBytes)return;s.subscribers.size>0||(this.dropEntry(t,s),this.evictions+=1)}}}const E=(d,t,s)=>`${s??"\0anon"}\0${d}:${g(t)}`;export{z as ReactiveCache,E as reactiveCacheKey,A as stableStringify,g as stableWireKey};
@@ -0,0 +1 @@
1
+ const v=e=>{const r=new DataView(new ArrayBuffer(8));r.setFloat64(0,e,!1);let t=r.getUint32(0,!1),o=r.getUint32(4,!1);return(t&2147483648)===0?t=(t^2147483648)>>>0:(t=~t>>>0,o=~o>>>0),t.toString(16).padStart(8,"0")+o.toString(16).padStart(8,"0")},x=e=>{const r=new TextEncoder().encode(e);let t="";for(const o of r)t+=o.toString(16).padStart(2,"0");return t},c=e=>{if(e===null)return"0";if(typeof e=="number")return Number.isFinite(e)?`1${v(e===0?0:e)}`:void 0;if(typeof e=="string")return`2${x(e)}`},d=e=>{const r=[];for(const t of e){const o=c(t);if(o===void 0)return;r.push(o)}return r.join("!")};const p=new Set([">",">="]),g=new Set(["<","<="]),h=(e,r,t,o)=>{const i=r.comparator==="=",n=p.has(r.comparator)||g.has(r.comparator);return!i&&!n||e.indexOf(r.field)!==t?!1:o===void 0?!0:!i&&o===r.field},m=(e,r,t)=>{const o={equalities:[],lowerExclusive:!1,upperExclusive:!1};let i;for(const n of r){const s=n.comparator==="=",a=p.has(n.comparator);if(!h(e,n,o.equalities.length,i))return;if(s){o.equalities.push(t(n.value));continue}if(i=n.field,a){if(o.lower!==void 0)return;o.lower=t(n.value),o.lowerExclusive=n.comparator===">"}else{if(o.upper!==void 0)return;o.upper=t(n.value),o.upperExclusive=n.comparator==="<"}}return o},f=(e,r)=>{const t=c(r);if(t!==void 0)return e===""?t:e+"!"+t},y=(e,r,t,o,i)=>{if(t.length===0)return;const n=m(t,o,i);if(!n)return;const s=d(n.equalities);if(s===void 0)return;let a=s,l=s+"￿";if(n.lower!==void 0){const u=f(s,n.lower);if(u===void 0)return;a=n.lowerExclusive?u+"￿":u}if(n.upper!==void 0){const u=f(s,n.upper);if(u===void 0)return;l=n.upperExclusive?u:u+"￿"}if(!(a>=l))return{hi:l,index:r,lo:a,table:e}},E=(e,r,t)=>{const o=[];for(const i of e){const n=d(i.fields.map(s=>t(r[s])));n!==void 0&&o.push({index:i.name,key:n})}return o},w=(e,r)=>e.index===r.index&&r.key>=e.lo&&r.key<e.hi,S=(e,r)=>!e||e.length===0||!r||r.length===0?!0:e.some(t=>{const o=r.filter(i=>i.index===t.index);return o.length===0?!0:o.some(i=>w(t,i))});export{y as buildIndexRange,E as indexKeysForRow,S as keysTouchRanges,w as rangeContains};
@@ -0,0 +1 @@
1
+ import{u as ee,T as G,l as ne,y as ie,c as oe}from"./FTS_COUNT_COLUMN-D1gY3wwZ-CZHdaRrd.mjs";import"@lunora/errors";import{sql as e}from"drizzle-orm";import{matchesStaticWhere as U,aggregateSqlFunction as te}from"./AGGREGATE_SQL_FUNCTION-QYaiuty4.mjs";import{encodeAggregateKey as b,foldAggregateTally as re,aggregateTableName as H,coerceAggregateNumber as B}from"./aggregateTableName-G-eXyjcz.mjs";import{runDrizzle as l}from"./runDrizzle-GKR3y97k.mjs";import{isFtsAvailable as ae,DOC_COLUMN as V,rowToDocument as K,AGG_KEY as R,AGG_VALUE as g,AGG_COUNT as m,geoTableName as se,aggUpsertSql as x,jsonPathSql as O}from"./AGG_COUNT-BWXe3gtQ.mjs";import{param as P}from"./param-B5lF5Jd9.mjs";import{encodeGeohash as $e,GEO_DEFAULT_PRECISION as ce}from"./GEO_DEFAULT_PRECISION-okRCkZ6r.mjs";import{sortColumnName as z,matchesRankStaticWhere as J,encodePartitionKey as X,rankTableName as Y}from"./RANK_TIEBREAK-9NU5s_mi.mjs";import{serializeSqlValue as M}from"./serializeSqlValue-DnpyaLcw.mjs";const fe=(y,I,h)=>[...y.partitionBy??[],...y.sortBy.map(T=>T.field),...y.where?Object.keys(y.where):[]].every(T=>I[T]===h[T]),le=(y,I,h,T,L,_)=>{if(L&&_&&fe(h,L,_))return;const s=Y(I,h.name);if(L&&l(y,e`DELETE FROM ${e.identifier(s)} WHERE ${e.identifier("__id__")} = ${T}`),!_||h.where&&!J(_,h.where))return;const N=h.sortBy.map((S,F)=>z(F)),v=e.join(["__id__","__partition__",...N].map(S=>e.identifier(S)),e`, `),C=X(h.partitionBy??[],_),w=h.sortBy.map(S=>M(_[S.field]??null)),D=e.join([T,C,...w].map(S=>P(S)),e`, `);l(y,e`INSERT INTO ${e.identifier(s)} (${v}) VALUES (${D})`)},Ae=y=>{const{broadcast:I,indexKeysFor:h,invalidateCache:T,recordCdc:L,schema:_,sql:s}=y,N=new Set,v=new Set,C=(i,n)=>{const o=`${i}::${n.name}`;if(N.has(o))return;const c=H(i,n.name),r=n.by??[],d=new Map,f=l(s,e`SELECT id, _creationTime, ${e.identifier(V)} FROM ${e.identifier(i)}`).toArray();for(const $ of f){const t=K($);if(!t||n.where&&!U(t,n.where))continue;const E=b(r,t);re(d,E,n,t)}l(s,e`DELETE FROM ${e.identifier(c)}`);const p=32,a=[...d];for(let $=0;$<a.length;$+=p){const t=a.slice($,$+p),E=e.join(t.map(([u,A])=>e`(${u}, ${A.value}, ${A.count})`),e`, `);l(s,e`INSERT INTO ${e.identifier(c)} (${R}, ${g}, ${m}) VALUES ${E}`)}N.add(o)},w=(i,n,o)=>{const c=n.by??[],r=te(n.op),d=n.field??"",f=[];for(const $ of c){const t=M(o[$]??null);t===null?f.push(e`${O($)} IS NULL`):f.push(e`${O($)} = ${t}`)}for(const[$,t]of Object.entries(n.where??{})){const E=t!==null&&typeof t=="object"&&!Array.isArray(t)?t.eq:t,u=M(E);u===null?f.push(e`${O($)} IS NULL`):f.push(e`${O($)} = ${u}`)}const p=f.length>0?e` WHERE ${e.join(f,e` AND `)}`:e``,a=O(d);return{value:l(s,e`SELECT ${e.raw(r)}(${a}) AS value FROM ${e.identifier(i)}${p}`).one().value??null}},D=(i,n,o,c)=>{const r=H(i,n.name),{op:d}=n,f=n.field??"",p=t=>{l(s,e`DELETE FROM ${e.identifier(r)} WHERE ${R} = ${t} AND ${m} <= 0`)},a=o&&(!n.where||U(o,n.where))?o:void 0,$=c&&(!n.where||U(c,n.where))?c:void 0;if(!(!a&&!$)){if(d==="count"){for(const[t,E]of[[a,-1],[$,1]]){if(!t)continue;const u=b(n.by??[],t);l(s,x(r,u,E,E,e`${g} = ${g} + excluded.${g}, ${m} = ${m} + excluded.${m}`))}a&&p(b(n.by??[],a));return}if(d==="sum"||d==="avg"){for(const[t,E]of[[a,-1],[$,1]]){if(!t)continue;const u=B(t[f]);if(u===void 0)continue;const A=b(n.by??[],t);l(s,x(r,A,E*u,E,e`${g} = COALESCE(${g}, 0) + excluded.${g}, ${m} = ${m} + excluded.${m}`))}a&&p(b(n.by??[],a));return}if(a){const t=b(n.by??[],a),E=B(a[f]),u=l(s,e`SELECT ${g} AS value, ${m} AS count FROM ${e.identifier(r)} WHERE ${R} = ${t}`).toArray()[0],A=(u?.count??0)-1;if(A<=0)l(s,e`DELETE FROM ${e.identifier(r)} WHERE ${R} = ${t}`);else if(u&&E!==void 0&&u.value!==null&&E===u.value){const Q=w(i,n,a);l(s,e`UPDATE ${e.identifier(r)} SET ${g} = ${Q.value}, ${m} = ${A} WHERE ${R} = ${t}`)}else l(s,e`UPDATE ${e.identifier(r)} SET ${m} = ${m} - 1 WHERE ${R} = ${t}`)}if($){const t=b(n.by??[],$),E=B($[f]);if(E===void 0)l(s,x(r,t,null,1,e`${m} = ${m} + 1`));else{const u=d==="min"?"MIN":"MAX";l(s,x(r,t,E,1,e`${g} = ${e.raw(u)}(COALESCE(${g}, excluded.${g}), excluded.${g}), ${m} = ${m} + 1`))}}}},S=i=>{const n=_.tables[i]?.aggregateIndexes;if(!(!n||n.length===0))for(const o of n)C(i,o)},F=(i,n,o)=>{const c=_.tables[i]?.aggregateIndexes;if(!(!c||c.length===0))for(const r of c)D(i,r,n,o)},j=(i,n)=>{const o=`${i}::rank::${n.name}`;if(v.has(o))return;const c=Y(i,n.name),r=l(s,e`SELECT id, _creationTime, ${e.identifier(V)} FROM ${e.identifier(i)}`).toArray();l(s,e`DELETE FROM ${e.identifier(c)}`);const d=n.sortBy.map((p,a)=>z(a)),f=e.join(["__id__","__partition__",...d].map(p=>e.identifier(p)),e`, `);for(const p of r){const a=K(p);if(!a||n.where&&!J(a,n.where))continue;const $=X(n.partitionBy??[],a),t=n.sortBy.map(u=>M(a[u.field]??null)),E=e.join([a._id,$,...t].map(u=>P(u)),e`, `);l(s,e`INSERT INTO ${e.identifier(c)} (${f}) VALUES (${E})`)}v.add(o)},Z=i=>{const n=_.tables[i]?.rankIndexes;if(!(!n||n.length===0))for(const o of n)j(i,o)},W=(i,n,o,c)=>{const r=_.tables[i]?.rankIndexes;if(!(!r||r.length===0))for(const d of r)le(s,i,d,n,o,c)},k=(i,n,o,c)=>{const r=_.tables[i]?.searchIndexes;if(!(!r||r.length===0||!ae(s)))for(const d of r){if(ee(c,o,d))continue;const f=oe(i,d.name);l(s,e`DELETE FROM ${e.identifier(f)} WHERE ${e.identifier(G)} = ${n}`),o&&l(s,e`INSERT INTO ${e.identifier(f)} (${e.identifier(ne)}, ${e.identifier(G)}) VALUES (${ie(o,d)}, ${n})`)}},q=(i,n,o)=>{const c=_.tables[i]?.geoIndexes;if(!(!c||c.length===0))for(const r of c){const d=se(i,r.name);l(s,e`DELETE FROM ${e.identifier(d)} WHERE ${e.identifier("__id__")} = ${n}`);const f=o?.[r.field];if(f!==null&&typeof f=="object"&&typeof f.lat=="number"&&typeof f.lng=="number"){const{lat:p,lng:a}=f,$=$e({lat:p,lng:a},r.precision??ce);l(s,e`INSERT INTO ${e.identifier(d)} (${e.identifier("__id__")}, ${e.identifier("__geohash__")}, ${e.identifier("__lat__")}, ${e.identifier("__lng__")}) VALUES (${n}, ${$}, ${p}, ${a})`)}}};return{ensureBackfilledForTable:S,ensureBackfilledIndex:C,ensureRankBackfilled:j,ensureRankBackfilledForTable:Z,syncAggregates:F,syncCompanionsForInsert:(i,n,o)=>{k(i,n,o),q(i,n,o),F(i,void 0,o),W(i,n,void 0,o),T(i,n,o),L(i,n,"insert",o),I({indexKeys:h(i,o),key:n,op:"insert",row:o,table:i})},syncGeo:q,syncRanks:W,syncSearch:k}};export{Ae as createCompanionSync};
@@ -0,0 +1 @@
1
+ const d=()=>{const a=new Set,t=new Map,n=new Set;return{onRead(e){a.add(e),n.add(e)},onReadRange(e){a.add(e.table);const o=t.get(e.table);o?o.push(e):t.set(e.table,[e])},ranges(){for(const e of n)t.delete(e);return t.size>0?t:void 0},tables:a}};export{d as createReadFootprint};
@@ -1 +1 @@
1
- import{createShardCtxDb as b}from"./NotUniqueError-B4piAtjk.mjs";import{createRelayLink as I}from"./DEFAULT_MAX_RELAYS-CnCyh6oX.mjs";import{ConflictError as N}from"./ConflictError-C8GtJmjS.mjs";import{runShardMigrations as v}from"./runShardMigrations-CPxqCh3O.mjs";import{relayName as q}from"./DEFAULT_PROMOTION_THRESHOLDS-Dteg0sZF.mjs";const C=(_,m={})=>({_meta:{column:{notNull:!0,...m}},kind:_}),D=(_,m,E)=>{const{describe:k,expect:i,it:f}=E;k(`engine contract: ${_}`,()=>{k("optimistic concurrency",()=>{const g=p=>({tables:{items:{indexes:[],shape:{title:C("string"),version:C("number",{notNull:!1})},triggerMap:{clobber:{handler:()=>{p.exec(`UPDATE "items" SET "__doc__" = json_set("__doc__", '$.version', 99) WHERE "id" = 'i1'`)},op:"update",timing:"before"}}}}});f("raises a CONFLICT of kind `occ` when a write's snapshot is clobbered",async()=>{const{close:p,host:d}=m();try{const c=d.sql,l=g(c);v(c,l);const s=b({schema:l,sql:c});await s.insert("items",{_id:"i1",title:"first",version:1},{allowExplicitId:!0}),await i(s.patch("i1",{title:"second"})).rejects.toBeInstanceOf(N)}finally{p?.()}}),f("reports the conflict as CONFLICT/409 rather than retrying it away",async()=>{const{close:p,host:d}=m();try{const c=d.sql,l=g(c);v(c,l);const s=b({schema:l,sql:c});await s.insert("items",{_id:"i1",title:"first",version:1},{allowExplicitId:!0});let r;try{await s.patch("i1",{title:"second"})}catch(t){r=t}const e=r;i(e.code).toBe("CONFLICT"),i(e.kind).toBe("occ")}finally{p?.()}}),f("leaves the row readable and unchanged after a conflict",async()=>{const{close:p,host:d}=m();try{const c=d.sql,l=g(c);v(c,l);const s=b({schema:l,sql:c});await s.insert("items",{_id:"i1",title:"first",version:1},{allowExplicitId:!0});try{await s.patch("i1",{title:"second"})}catch{}const r=await s.get("i1");i(r?.title).toBe("first"),i(r?.version).toBe(99)}finally{p?.()}}),f("raises a CONFLICT of kind `trigger` when a trigger writes its own row through the db",async()=>{const{close:p,host:d}=m();try{const c=d.sql,l={tables:{items:{indexes:[],shape:{title:C("string"),version:C("number",{notNull:!1})},triggerMap:{recurse:{handler:async(t,o)=>{await t.db.patch(o.doc._id,{version:99})},op:"update",timing:"before"}}}}};v(c,l);const s=b({schema:l,sql:c});await s.insert("items",{_id:"i1",title:"first",version:1},{allowExplicitId:!0});let r;try{await s.patch("i1",{title:"second"})}catch(t){r=t}const e=r;i(e).toBeInstanceOf(N),i(e.code).toBe("CONFLICT"),i(e.kind).toBe("trigger")}finally{p?.()}})}),k("shape-poke ordering",()=>{const g="shard-a",p={args:{},name:"messages"},d=(e,t,o,a)=>e.accept(t?.()??{},{connectionId:o,shapes:{[a]:p}}),c=(e,t)=>{let o=0,a=0;const n=u=>()=>{throw new Error(`the relay poke path must not reach RelayHost.${u}`)},h={fetch:(u,O)=>{if(JSON.parse(O?.body??"{}").type!=="relay_shape_subscribe")return Promise.resolve(new Response(void 0,{status:204}));const B=t[a];if(a+=1,B===void 0)throw new Error("the relay asked for more seeds than this fixture supplies");return Promise.resolve(Response.json(B))}},y={get:()=>h,getByName:()=>h,idFromName:u=>u},w={buildShapeDiff:n("buildShapeDiff"),computeOpLogShapeSeed:n("computeOpLogShapeSeed"),currentCdcEpoch:n("currentCdcEpoch"),deliverWhisperLocal:n("deliverWhisperLocal"),doName:()=>q(g,0),env:()=>({SHARD:y}),getWebSockets:()=>e.getSockets(),maskMetadata:n("maskMetadata"),nextPokeId:()=>(o+=1,`poke-${String(o)}`),readAttachment:u=>u.deserializeAttachment?.(),recordShapePokeFanout:()=>{},resolveShape:n("resolveShape"),rlsMetadata:n("rlsMetadata"),shardBinding:()=>"SHARD",sql:n("sql")},S=I(w);if(S===void 0)throw new Error("expected a relay link for a `…::relay::N` name");return S},l=e=>new Request("https://relay.internal/_lunora/relay",{body:JSON.stringify(e),headers:{"content-type":"application/json"},method:"POST"}),s=async(e,t,o)=>{const a=await e.seedRelayShape(t,o,p,{identity:void 0,userId:void 0});if(a!=="ok")throw new Error(`seed failed: ${JSON.stringify(a)}`)},r=(e={})=>l({...p,checkpoint:20,epoch:"e1",fromCursor:10,rowsPatch:[{id:"r1",op:"upsert",value:{title:"hello"}}],type:"relay_shape_poke",...e});f("frames a poke as pokeStart → pokePart per shape → pokeEnd, under one poke id",async()=>{const{close:e,createSocket:t,readFrames:o,sockets:a}=m();try{const n=c(a,[{cursor:10,epoch:"e1",frames:[]}]),h=d(a,t,"c-alice","s1");await s(n,h,"s1"),await n.handleControl(r());const y=(await o(h)).map(w=>JSON.parse(w));i(y.map(w=>w.type)).toStrictEqual(["pokeStart","pokePart","pokeEnd"]),i(new Set(y.map(w=>w.pokeId)).size).toBe(1),i(y[1]?.shapeId).toBe("s1"),i(y[2]?.checkpoint).toBe(20)}finally{e?.()}}),f("delivers a poke only to sockets whose cursor matches, and advances them past it",async()=>{const{close:e,createSocket:t,readFrames:o,sockets:a}=m();try{const n=c(a,[{cursor:10,epoch:"e1",frames:[]},{cursor:7,epoch:"e1",frames:[]}]),h=d(a,t,"c-alice","s1"),y=d(a,t,"c-bob","s2");await s(n,h,"s1"),await s(n,y,"s2"),await n.handleControl(r());const w=await o(h);i(w.length).toBe(3);const S=await o(y);i(S.length).toBe(0),await n.handleControl(r());const u=await o(h);i(u.length).toBe(3)}finally{e?.()}}),f("skips a socket whose cursor matches under a different CDC epoch",async()=>{const{close:e,createSocket:t,readFrames:o,sockets:a}=m();try{const n=c(a,[{cursor:10,epoch:"e1",frames:[]}]),h=d(a,t,"c-alice","s1");await s(n,h,"s1"),await n.handleControl(r({epoch:"e2"}));const y=await o(h);i(y.length).toBe(0),await n.handleControl(r());const w=await o(h);i(w.length).toBe(3)}finally{e?.()}})}),k("RLS identity under live subscription",()=>{const g="shard-a",p={args:{},name:"lobby-messages"},d={args:{},name:"my-orders"},c=s=>{const r=[],e=[],t={fetch:(a,n)=>(r.push(JSON.parse(n?.body??"{}")),Promise.resolve(new Response(void 0,{status:204})))},o=I({buildShapeDiff:()=>[{id:"r1",op:"upsert",value:{}}],computeOpLogShapeSeed:()=>({baseCheckpoint:void 0,cursor:10,epoch:"e1",rowsPatch:[]}),currentCdcEpoch:()=>"e1",deliverWhisperLocal:()=>0,doName:()=>g,env:()=>({SHARD:{get:()=>t,getByName:()=>t,idFromName:a=>a}}),getWebSockets:()=>[],maskMetadata:()=>({columns:[]}),nextPokeId:()=>"poke-1",readAttachment:()=>({}),recordShapePokeFanout:()=>{},resolveShape:(a,n,h)=>(e.push(h),a===d.name?{columns:["id"],effectiveWhere:{org:h?.identity?.org??"anonymous"},global:!1,table:"orders"}:{columns:["id"],effectiveWhere:{room:"lobby"},global:!1,table:"messages"}),rlsMetadata:()=>({policies:[]}),shardBinding:()=>"SHARD",sql:()=>s});if(o===void 0)throw new Error("expected an owner link for an un-suffixed DO name");return{owner:o,posts:r,resolvedUnder:e}},l=async(s,r)=>{await s.handleControl(new Request("https://owner.internal/_lunora/relay",{body:JSON.stringify({...r,connectionId:"c-alice",identity:{org:"acme"},relayIndex:0,subId:"s1",type:"relay_shape_subscribe",userId:"u1"}),headers:{"content-type":"application/json"},method:"POST"}))};f("seeds a subscriber under its own forwarded identity, never the anonymous one",async()=>{const{close:s,host:r}=m();try{const{owner:e,resolvedUnder:t}=c(r.sql);await l(e,d),i(t.some(o=>o?.userId==="u1"&&o.identity?.org==="acme")).toBe(!0)}finally{s?.()}}),f("routes an identity-scoped shape to a per-socket poke, not the cohort multicast",async()=>{const{close:s,host:r}=m();try{const{owner:e,posts:t}=c(r.sql);await l(e,d),t.length=0,await e.onFlush(new Set(["orders"]),20);const o=t.filter(a=>a.type==="relay_shape_poke");i(o.length).toBe(1),i(o[0]?.targetConnectionId).toBe("c-alice")}finally{s?.()}}),f("still multicasts an identity-blind shape to the whole cohort",async()=>{const{close:s,host:r}=m();try{const{owner:e,posts:t}=c(r.sql);await l(e,p),t.length=0,await e.onFlush(new Set(["messages"]),20);const o=t.filter(a=>a.type==="relay_shape_poke");i(o.length).toBe(1),i(o[0]?.targetConnectionId).toBeUndefined()}finally{s?.()}})})})};export{D as defineEngineContractSuite};
1
+ import{createShardCtxDb as b}from"./NotUniqueError-iGKd9wRR.mjs";import{createRelayLink as I}from"./DEFAULT_MAX_RELAYS-CnCyh6oX.mjs";import{ConflictError as N}from"./ConflictError-C8GtJmjS.mjs";import{runShardMigrations as v}from"./runShardMigrations-CPxqCh3O.mjs";import{relayName as q}from"./DEFAULT_PROMOTION_THRESHOLDS-Dteg0sZF.mjs";const C=(_,m={})=>({_meta:{column:{notNull:!0,...m}},kind:_}),D=(_,m,E)=>{const{describe:k,expect:i,it:f}=E;k(`engine contract: ${_}`,()=>{k("optimistic concurrency",()=>{const g=p=>({tables:{items:{indexes:[],shape:{title:C("string"),version:C("number",{notNull:!1})},triggerMap:{clobber:{handler:()=>{p.exec(`UPDATE "items" SET "__doc__" = json_set("__doc__", '$.version', 99) WHERE "id" = 'i1'`)},op:"update",timing:"before"}}}}});f("raises a CONFLICT of kind `occ` when a write's snapshot is clobbered",async()=>{const{close:p,host:d}=m();try{const c=d.sql,l=g(c);v(c,l);const s=b({schema:l,sql:c});await s.insert("items",{_id:"i1",title:"first",version:1},{allowExplicitId:!0}),await i(s.patch("i1",{title:"second"})).rejects.toBeInstanceOf(N)}finally{p?.()}}),f("reports the conflict as CONFLICT/409 rather than retrying it away",async()=>{const{close:p,host:d}=m();try{const c=d.sql,l=g(c);v(c,l);const s=b({schema:l,sql:c});await s.insert("items",{_id:"i1",title:"first",version:1},{allowExplicitId:!0});let r;try{await s.patch("i1",{title:"second"})}catch(t){r=t}const e=r;i(e.code).toBe("CONFLICT"),i(e.kind).toBe("occ")}finally{p?.()}}),f("leaves the row readable and unchanged after a conflict",async()=>{const{close:p,host:d}=m();try{const c=d.sql,l=g(c);v(c,l);const s=b({schema:l,sql:c});await s.insert("items",{_id:"i1",title:"first",version:1},{allowExplicitId:!0});try{await s.patch("i1",{title:"second"})}catch{}const r=await s.get("i1");i(r?.title).toBe("first"),i(r?.version).toBe(99)}finally{p?.()}}),f("raises a CONFLICT of kind `trigger` when a trigger writes its own row through the db",async()=>{const{close:p,host:d}=m();try{const c=d.sql,l={tables:{items:{indexes:[],shape:{title:C("string"),version:C("number",{notNull:!1})},triggerMap:{recurse:{handler:async(t,o)=>{await t.db.patch(o.doc._id,{version:99})},op:"update",timing:"before"}}}}};v(c,l);const s=b({schema:l,sql:c});await s.insert("items",{_id:"i1",title:"first",version:1},{allowExplicitId:!0});let r;try{await s.patch("i1",{title:"second"})}catch(t){r=t}const e=r;i(e).toBeInstanceOf(N),i(e.code).toBe("CONFLICT"),i(e.kind).toBe("trigger")}finally{p?.()}})}),k("shape-poke ordering",()=>{const g="shard-a",p={args:{},name:"messages"},d=(e,t,o,a)=>e.accept(t?.()??{},{connectionId:o,shapes:{[a]:p}}),c=(e,t)=>{let o=0,a=0;const n=u=>()=>{throw new Error(`the relay poke path must not reach RelayHost.${u}`)},h={fetch:(u,O)=>{if(JSON.parse(O?.body??"{}").type!=="relay_shape_subscribe")return Promise.resolve(new Response(void 0,{status:204}));const B=t[a];if(a+=1,B===void 0)throw new Error("the relay asked for more seeds than this fixture supplies");return Promise.resolve(Response.json(B))}},y={get:()=>h,getByName:()=>h,idFromName:u=>u},w={buildShapeDiff:n("buildShapeDiff"),computeOpLogShapeSeed:n("computeOpLogShapeSeed"),currentCdcEpoch:n("currentCdcEpoch"),deliverWhisperLocal:n("deliverWhisperLocal"),doName:()=>q(g,0),env:()=>({SHARD:y}),getWebSockets:()=>e.getSockets(),maskMetadata:n("maskMetadata"),nextPokeId:()=>(o+=1,`poke-${String(o)}`),readAttachment:u=>u.deserializeAttachment?.(),recordShapePokeFanout:()=>{},resolveShape:n("resolveShape"),rlsMetadata:n("rlsMetadata"),shardBinding:()=>"SHARD",sql:n("sql")},S=I(w);if(S===void 0)throw new Error("expected a relay link for a `…::relay::N` name");return S},l=e=>new Request("https://relay.internal/_lunora/relay",{body:JSON.stringify(e),headers:{"content-type":"application/json"},method:"POST"}),s=async(e,t,o)=>{const a=await e.seedRelayShape(t,o,p,{identity:void 0,userId:void 0});if(a!=="ok")throw new Error(`seed failed: ${JSON.stringify(a)}`)},r=(e={})=>l({...p,checkpoint:20,epoch:"e1",fromCursor:10,rowsPatch:[{id:"r1",op:"upsert",value:{title:"hello"}}],type:"relay_shape_poke",...e});f("frames a poke as pokeStart → pokePart per shape → pokeEnd, under one poke id",async()=>{const{close:e,createSocket:t,readFrames:o,sockets:a}=m();try{const n=c(a,[{cursor:10,epoch:"e1",frames:[]}]),h=d(a,t,"c-alice","s1");await s(n,h,"s1"),await n.handleControl(r());const y=(await o(h)).map(w=>JSON.parse(w));i(y.map(w=>w.type)).toStrictEqual(["pokeStart","pokePart","pokeEnd"]),i(new Set(y.map(w=>w.pokeId)).size).toBe(1),i(y[1]?.shapeId).toBe("s1"),i(y[2]?.checkpoint).toBe(20)}finally{e?.()}}),f("delivers a poke only to sockets whose cursor matches, and advances them past it",async()=>{const{close:e,createSocket:t,readFrames:o,sockets:a}=m();try{const n=c(a,[{cursor:10,epoch:"e1",frames:[]},{cursor:7,epoch:"e1",frames:[]}]),h=d(a,t,"c-alice","s1"),y=d(a,t,"c-bob","s2");await s(n,h,"s1"),await s(n,y,"s2"),await n.handleControl(r());const w=await o(h);i(w.length).toBe(3);const S=await o(y);i(S.length).toBe(0),await n.handleControl(r());const u=await o(h);i(u.length).toBe(3)}finally{e?.()}}),f("skips a socket whose cursor matches under a different CDC epoch",async()=>{const{close:e,createSocket:t,readFrames:o,sockets:a}=m();try{const n=c(a,[{cursor:10,epoch:"e1",frames:[]}]),h=d(a,t,"c-alice","s1");await s(n,h,"s1"),await n.handleControl(r({epoch:"e2"}));const y=await o(h);i(y.length).toBe(0),await n.handleControl(r());const w=await o(h);i(w.length).toBe(3)}finally{e?.()}})}),k("RLS identity under live subscription",()=>{const g="shard-a",p={args:{},name:"lobby-messages"},d={args:{},name:"my-orders"},c=s=>{const r=[],e=[],t={fetch:(a,n)=>(r.push(JSON.parse(n?.body??"{}")),Promise.resolve(new Response(void 0,{status:204})))},o=I({buildShapeDiff:()=>[{id:"r1",op:"upsert",value:{}}],computeOpLogShapeSeed:()=>({baseCheckpoint:void 0,cursor:10,epoch:"e1",rowsPatch:[]}),currentCdcEpoch:()=>"e1",deliverWhisperLocal:()=>0,doName:()=>g,env:()=>({SHARD:{get:()=>t,getByName:()=>t,idFromName:a=>a}}),getWebSockets:()=>[],maskMetadata:()=>({columns:[]}),nextPokeId:()=>"poke-1",readAttachment:()=>({}),recordShapePokeFanout:()=>{},resolveShape:(a,n,h)=>(e.push(h),a===d.name?{columns:["id"],effectiveWhere:{org:h?.identity?.org??"anonymous"},global:!1,table:"orders"}:{columns:["id"],effectiveWhere:{room:"lobby"},global:!1,table:"messages"}),rlsMetadata:()=>({policies:[]}),shardBinding:()=>"SHARD",sql:()=>s});if(o===void 0)throw new Error("expected an owner link for an un-suffixed DO name");return{owner:o,posts:r,resolvedUnder:e}},l=async(s,r)=>{await s.handleControl(new Request("https://owner.internal/_lunora/relay",{body:JSON.stringify({...r,connectionId:"c-alice",identity:{org:"acme"},relayIndex:0,subId:"s1",type:"relay_shape_subscribe",userId:"u1"}),headers:{"content-type":"application/json"},method:"POST"}))};f("seeds a subscriber under its own forwarded identity, never the anonymous one",async()=>{const{close:s,host:r}=m();try{const{owner:e,resolvedUnder:t}=c(r.sql);await l(e,d),i(t.some(o=>o?.userId==="u1"&&o.identity?.org==="acme")).toBe(!0)}finally{s?.()}}),f("routes an identity-scoped shape to a per-socket poke, not the cohort multicast",async()=>{const{close:s,host:r}=m();try{const{owner:e,posts:t}=c(r.sql);await l(e,d),t.length=0,await e.onFlush(new Set(["orders"]),20);const o=t.filter(a=>a.type==="relay_shape_poke");i(o.length).toBe(1),i(o[0]?.targetConnectionId).toBe("c-alice")}finally{s?.()}}),f("still multicasts an identity-blind shape to the whole cohort",async()=>{const{close:s,host:r}=m();try{const{owner:e,posts:t}=c(r.sql);await l(e,p),t.length=0,await e.onFlush(new Set(["messages"]),20);const o=t.filter(a=>a.type==="relay_shape_poke");i(o.length).toBe(1),i(o[0]?.targetConnectionId).toBeUndefined()}finally{s?.()}})})})};export{D as defineEngineContractSuite};
@@ -0,0 +1 @@
1
+ const c=(r,n)=>{try{const t=JSON.stringify(r);return t===void 0?0:t.length}catch{return n}};export{c as r};
@@ -0,0 +1 @@
1
+ import{keysTouchRanges as g}from"./buildIndexRange-DIjFVgeO.mjs";const c=(s,t,o)=>{const e=s??new Map;for(const n of o){const r=t?.get(n),a=e.get(n),i=e.has(n)&&a===void 0;if(!t?.has(n)||r===void 0||i){e.set(n,void 0);continue}e.set(n,a?[...a,...r]:r)}return e},f=(s,t,o)=>{const e=s??new Map;if(e.has(t)&&e.get(t)===void 0)return e;if(!o||o.length===0)return e.set(t,void 0),e;const n=e.get(t);return e.set(t,n?[...n,...o]:[...o]),e},h=(s,t,o)=>{if(!o)return!0;for(const e of t){if(!s.tables.has(e))continue;const n=s.ranges?.get(e);if(!n||n.length===0||g(n,o.get(e)))return!0}return!1};export{c as mergeChangedKeys,f as recordChangedKeys,h as writeTouchesMemo};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@lunora/shard-engine",
3
- "version": "1.0.0-alpha.1",
3
+ "version": "1.0.0-alpha.3",
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",
@@ -48,7 +48,7 @@
48
48
  "access": "public"
49
49
  },
50
50
  "dependencies": {
51
- "@lunora/errors": "1.0.0-alpha.9",
51
+ "@lunora/errors": "1.0.0-alpha.10",
52
52
  "@lunora/platform": "1.0.0-alpha.1",
53
53
  "drizzle-orm": "^0.45.2"
54
54
  },
@@ -1 +0,0 @@
1
- import{LunoraError as b}from"@lunora/errors";import{n as ht,A as Le,T as we,y as pt,c as mt}from"./FTS_COUNT_COLUMN-D1gY3wwZ-CZHdaRrd.mjs";import{sql as t}from"drizzle-orm";import{aggregateSqlFunction as $e,normalizeCountArgument as wt,throwingScheduler as $t}from"./AGGREGATE_SQL_FUNCTION-QYaiuty4.mjs";import{encodeAggregateKey as Se,readAggregateValue as Ae,aggregateTableName as _e}from"./aggregateTableName-G-eXyjcz.mjs";import{mergeWhere as H,CountRlsUnsupportedError as Re,selectIndexForGroupBy as gt,selectIndexForCount as bt,selectIndexForAggregate as Et}from"./CountRlsUnsupportedError-B2WKJD9v.mjs";import{backfillSearchIndexesForTable as yt}from"./backfillAggregateIndexes-BHiewuB-.mjs";import{backfillAggregateIndexes as er,backfillRankIndexes as tr,backfillSearchIndexes as nr}from"./backfillAggregateIndexes-BHiewuB-.mjs";import{appendCdcChange as Nt}from"./CDC_LOG_TABLE-BnqlH2eZ.mjs";import{CDC_LOG_TABLE as ir,applyCdcChanges as or,bumpCdcEpoch as ar,minCdcSeq as sr,readCdcChanges as lr,readCdcCursor as dr,readCdcEpoch as cr,trimCdcChanges as ur}from"./CDC_LOG_TABLE-BnqlH2eZ.mjs";import{createCompanionSync as Tt}from"./createCompanionSync-BCBUOnMk.mjs";import{computeRankPage as je}from"./computeRankPage-IUSS-zIB.mjs";import{SCAN_DEP as W}from"./SCAN_DEP-D_yR9EeV.mjs";import{runDrizzle as O}from"./runDrizzle-GKR3y97k.mjs";import{DOC_COLUMN as B,quoteIdentifier as St,AGG_VALUE as ge,AGG_COUNT as Ie,AGG_KEY as be,jsonPathSql as P,rowToDocument as re,tableColumns as at,isFtsAvailable as At,tryRowToDocument as st,geoTableName as _t,qualifiedJsonPathSql as Je}from"./AGG_COUNT-BWXe3gtQ.mjs";import{coveringGeohashes as Rt,boundingBoxGeohashes as It,pointInBoundingBox as vt,haversineMeters as xt}from"./GEO_DEFAULT_PRECISION-okRCkZ6r.mjs";import{NotFoundError as Ct}from"./NotFoundError-BhF7FeFr.mjs";import{normalizeOrderKeys as kt,buildSeekWhere as lt,decodeCursor as Ce,applySelect as ze,encodeCursor as ke,softDeleteScope as ne,buildSeekBeforeWhere as Mt}from"./applySelect-B0CF8T7y.mjs";import{sortColumnName as Ye,resolveRankPartition as Lt,encodePartitionKey as Dt,RANK_TIEBREAK as Ot,rankTableName as Ve}from"./RANK_TIEBREAK-9NU5s_mi.mjs";import{assertFlatPredicate as ve,resolveRelationPredicates as Ke}from"./DEFAULT_MAX_RELATION_KEYS-bq00btqV.mjs";import{runRowValidators as xe,resolveWith as Qe,applyOnDelete as Wt,fanOutScalarCounts as Bt}from"./applyOnDelete-uFRC5p1d.mjs";import{guardWriter as qt}from"./RLS_UNWRAP_SYMBOL-C6_WX3dG.mjs";import{createSystemReader as Ft}from"./createSystemReader-DcDcrtM3.mjs";import{ConflictError as de}from"./ConflictError-C8GtJmjS.mjs";import{runTriggers as Ut}from"./hasTrigger-CbkOHExZ.mjs";import{compileWhereSql as K}from"./compileWhereSql-BLcfs4QW.mjs";import{CLIENT_WATERMARK_TABLE as hr,advanceClientWatermark as pr,migrateClientWatermark as mr,readClientWatermark as wr}from"./CLIENT_WATERMARK_TABLE-CXsSLU8D.mjs";import{GLOBAL_SHAPE_SNAPSHOT_TABLE as gr,deleteGlobalShapeSnapshot as br,deleteGlobalShapeSnapshotsForConnection as Er,migrateGlobalShapeSnapshot as yr,readGlobalShapeSnapshot as Nr,writeGlobalShapeSnapshot as Tr}from"./GLOBAL_SHAPE_SNAPSHOT_TABLE-DX-6-gBP.mjs";import{IDEMPOTENCY_TABLE as Ar,readIdempotent as _r,trimIdempotent as Rr,writeIdempotent as Ir}from"./IDEMPOTENCY_TABLE-DjkEMp6w.mjs";import{runShardMigrations as xr}from"./runShardMigrations-CPxqCh3O.mjs";import{SEARCH_STATE_TABLE as kr}from"./SEARCH_STATE_TABLE-eLN8U5tz.mjs";import{selectShapeMemberIds as Lr,selectShapeRows as Dr}from"./selectShapeMemberIds-DvE7K6zG.mjs";import{serializeSqlValue as ie}from"./serializeSqlValue-DnpyaLcw.mjs";const Ht=i=>{const o=new TextEncoder().encode(i);let n="";for(const d of o)n+=String.fromCodePoint(d);return btoa(n)},Pt=i=>{const o=atob(i),n=Uint8Array.from(o,d=>d.codePointAt(0)??0);return new TextDecoder().decode(n)},Gt=()=>new b("BAD_REQUEST","invalid cursor"),Xe=16,Ze=8,J=1024,De=(i,o)=>o.query(i),jt=(i,o,n)=>{const d=ht(i,n);if(d.length===0)return 0;let l=0;for(const[w,E]of o.entries()){const $=w===o.length-1;let N=0;for(const C of d)($?C.startsWith(E):C===E)&&(N+=1);if(N===0)return 0;l+=N}return l},Jt=(i,o)=>{if(!o)return{exact:!0,lower:i,upper:i};const n=i.codePointAt(i.length-1)??0,d=i.slice(0,Math.max(0,i.length-String.fromCodePoint(n).length));return{exact:!1,lower:i,upper:d+String.fromCodePoint(n+1)}},zt=(i,o,n)=>{const d={eq:(l,w)=>{if(!i.definition.filterFields?.includes(l))throw new b("INTERNAL",`field "${l}" is not a filter field of search index "${i.indexName}" on table "${o}"`);if(i.filters.length>=Ze)throw new b("BAD_REQUEST",`search index "${i.indexName}" on table "${o}": at most ${String(Ze)} .eq() filters are supported per search query`);return i.filters.push({field:l,value:w}),d},search:(l,w)=>{const E=i;if(l!==E.definition.field)throw new b("INTERNAL",`search index "${E.indexName}" on table "${o}" indexes "${E.definition.field}", not "${l}"`);const $=De(w,n).length;if($>Xe)throw new b("BAD_REQUEST",`search index "${E.indexName}" on table "${o}": at most ${String(Xe)} search terms are supported (got ${String($)})`);return E.field=l,E.query=w,E.hasQuery=!0,d}};return d},Yt=i=>{if(i.length>J)throw new b("BAD_REQUEST",`more than ${String(J)} documents match this search — narrow it with filters or read it a page at a time with .paginate()`)},Vt=i=>Math.min(i.offset+i.numItems+1,J),Kt=i=>Ht(`search:${String(i)}`),Qt=i=>{let o;try{o=Pt(i)}catch{return}if(!o.startsWith("search:"))return;const n=Number(o.slice(7));return Number.isInteger(n)&&n>=0?n:void 0},Xt=i=>{if(typeof i.endCursor=="string")throw new b("BAD_REQUEST","bounded (endCursor) pagination is not supported on search queries — relevance order has no stable range boundary");const o=Math.max(0,Math.floor(i.numItems)),n=i.cursor?Qt(i.cursor):0;if(n===void 0)throw Gt();if(n+o>J)throw new b("BAD_REQUEST",`search pagination reaches past the ${String(J)}-document limit (offset ${String(n)} + ${String(o)} requested) — narrow the query or the filters instead`);return{numItems:o,offset:n}},Zt=(i,o)=>{const n=o.offset+o.numItems,d=o.numItems>0&&i.length>n;return{continueCursor:d?Kt(n):null,isDone:!d,page:i.slice(o.offset,n)}},en=i=>{if(i===void 0)return J+1;if(!Number.isFinite(i))return J;const o=Math.max(0,Math.floor(i));if(o>J)throw new b("BAD_REQUEST",`search returns at most ${String(J)} documents (asked for ${String(o)}) — narrow the query or paginate instead`);return o},tn=/^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/iu,nn=i=>{if(!tn.test(i))throw new b("INTERNAL",`invalid clientId ${JSON.stringify(i)}: a client-supplied row id must be a UUID`)},et=50,dt=500,te=(i,o,n)=>{const d=o??dt;if(i>d)throw new b("BATCH_LIMIT_EXCEEDED",`${n}: batch of ${String(i)} exceeds the limit of ${String(d)} (raise options.limit or chunk the call)`,{status:400})},rn=i=>{const o={eq:(n,d)=>(i.sqlConditions.push({comparator:"=",field:n,value:d}),o),gt:(n,d)=>(i.sqlConditions.push({comparator:">",field:n,value:d}),o),gte:(n,d)=>(i.sqlConditions.push({comparator:">=",field:n,value:d}),o),lt:(n,d)=>(i.sqlConditions.push({comparator:"<",field:n,value:d}),o),lte:(n,d)=>(i.sqlConditions.push({comparator:"<=",field:n,value:d}),o)};return o},on=i=>Math.max(i,J),an=(i,o,n,d,l)=>{const w=De(n.query,Le(n.definition.language));if(w.length===0)return[];const E=mt(o,n.indexName),$=`${E}__vocab`,N=w.length-1,C=w.map((R,_)=>{const k=Jt(R,_===N),V=k.exact?t`${t.identifier("term")} = ${k.lower}`:t`${t.identifier("term")} >= ${k.lower} AND ${t.identifier("term")} < ${k.upper}`;return t`SELECT ${t.identifier("doc")}, ${t.raw(String(_))} AS ${t.identifier("__term__")}, COUNT(*) AS ${t.identifier("__n__")} FROM ${t.identifier($)} WHERE ${V} GROUP BY ${t.identifier("doc")}`}),x=w.map((R,_)=>t`SUM(CASE WHEN u.${t.identifier("__term__")} = ${t.raw(String(_))} THEN u.${t.identifier("__n__")} ELSE 0 END)`),S=t`SELECT f.${t.identifier(we)} AS ${t.identifier(we)}, ${t.join(x,t` + `)} AS ${t.identifier("__score__")} FROM (${t.join(C,t` UNION ALL `)}) u JOIN ${t.identifier(E)} f ON f.rowid = u.${t.identifier("doc")} GROUP BY f.${t.identifier(we)} HAVING ${t.join(x.map(R=>t`${R} > 0`),t` AND `)}`,T=[];for(const R of n.filters)T.push(t`${P(R.field)} = ${ie(R.value)}`);l&&T.push(l);let p=t`SELECT m.id, m._creationTime, m.${t.identifier(B)} FROM (${S}) s JOIN ${t.identifier(o)} m ON m.id = s.${t.identifier(we)}`;T.length>0&&(p=t`${p} WHERE ${t.join(T,t` AND `)}`),p=t`${p} ORDER BY s.${t.identifier("__score__")} DESC, m._creationTime DESC, m.id ASC LIMIT ${t.raw(String(d))}`;const A=[];for(const R of O(i,p)){const _=st(R);_&&A.push(_)}return A},sn=(i,o,n,d,l)=>{const w=Le(n.definition.language),E=De(n.query,w);if(E.length===0)return[];const $=[];for(const S of n.filters)$.push(t`${P(S.field)} = ${ie(S.value)}`);l&&$.push(l);let N=t`SELECT id, _creationTime, ${t.identifier(B)} FROM ${t.identifier(o)}`;$.length>0&&(N=t`${N} WHERE ${t.join($,t` AND `)}`),N=t`${N} ORDER BY _creationTime DESC, id ASC LIMIT ${t.raw(String(on(d)))}`;const C=O(i,N).toArray(),x=[];for(const S of C){const T=st(S);if(!T)continue;const p=jt(pt(T,n.definition),E,w);p>0&&x.push({creationTime:typeof T._creationTime=="number"?T._creationTime:0,doc:T,id:typeof T._id=="string"?T._id:"",score:p})}return x.sort((S,T)=>T.score-S.score||T.creationTime-S.creationTime||S.id.localeCompare(T.id)),x.slice(0,d).map(S=>S.doc)},ln=(i,o)=>{const n=i,d={near:(l,w)=>{if(n.within)throw new b("INTERNAL",`geo index "${n.indexName}" on table "${o}": call .near() or .within(), not both`);return n.near={point:{lat:l.lat,lng:l.lng},radiusMeters:w},d},within:l=>{if(n.near)throw new b("INTERNAL",`geo index "${n.indexName}" on table "${o}": call .near() or .within(), not both`);return n.within={ne:{lat:l.ne.lat,lng:l.ne.lng},sw:{lat:l.sw.lat,lng:l.sw.lng}},d}};return d},dn=(i,o)=>{const n=i[o];if(n===null||typeof n!="object")return;const{lat:d,lng:l}=n;return typeof d=="number"&&typeof l=="number"?{lat:d,lng:l}:void 0},cn=(i,o)=>{const n=dn(i,o.definition.field);if(!n)return;const d=typeof i._creationTime=="number"?i._creationTime:0;if(o.near){const l=xt(o.near.point,n);return l<=o.near.radiusMeters?{creationTime:d,distance:l}:void 0}return vt(n,o.within)?{creationTime:d,distance:0}:void 0},un=(i,o,n,d,l)=>{if(!n.near&&!n.within)throw new b("INTERNAL",`geo index "${n.indexName}" on table "${o}": call .near(point, radius) or .within(box)`);const w=n.near?Rt(n.near.point,n.near.radiusMeters):It(n.within),E=_t(o,n.indexName),$=w.map(p=>t`(g.${t.identifier("__geohash__")} >= ${p} AND g.${t.identifier("__geohash__")} < ${`${p}{`})`),N=[t`(${t.join($,t` OR `)})`];l&&N.push(l);const C=t`SELECT m.id, m._creationTime, m.${t.identifier(B)} FROM ${t.identifier(E)} g JOIN ${t.identifier(o)} m ON m.id = g.${t.identifier("__id__")} WHERE ${t.join(N,t` AND `)}`,x=O(i,C).toArray(),S=[];for(const p of x){const A=re(p),R=A?cn(A,n):void 0;A&&R&&S.push({creationTime:R.creationTime,distance:R.distance,doc:A})}S.sort((p,A)=>p.distance-A.distance||A.creationTime-p.creationTime);const T=S.map(p=>p.doc);return typeof d=="number"?T.slice(0,Math.max(0,Math.floor(d))):T},fn=(i,o,n,d,l)=>{const{geo:w}=n;if(!w)throw new b("INTERNAL","runGeoTerminal called without a staged geo query");const E=n.inMemoryFilters.length>0,$=un(i,o,w,E?void 0:l,d);if(!E)return $;const N=[];for(const C of $)if(n.inMemoryFilters.every(x=>x(C))&&(N.push(C),typeof l=="number"&&N.length>=l))break;return N},hn=(i,o,n,d,l,w)=>{const E=[];for(const x of n.sqlConditions)E.push(t`${P(x.field)} ${t.raw(x.comparator)} ${ie(x.value)}`);d&&E.push(d);let $=t`SELECT id, _creationTime, ${t.identifier(B)} FROM ${t.identifier(o)}`;E.length>0&&($=t`${$} WHERE ${t.join(E,t` AND `)}`),$=t`${$} ORDER BY ${l}`,typeof w=="number"&&n.inMemoryFilters.length===0&&($=t`${$} LIMIT ${t.raw(String(Math.max(0,Math.floor(w))))}`);const N=O(i,$).toArray(),C=[];for(const x of N){const S=re(x);if(S&&n.inMemoryFilters.every(T=>T(S))&&(C.push(S),typeof w=="number"&&C.length>=w))break}return C},X={fieldRef:P,serialize:ie},pn=i=>{let o=0;const n=[],d={fieldRef:P,relationExists:l=>{const{childWhere:w,negated:E,parentTable:$,relation:N}=l,C=`__rel_${String(o)}`,x=n.at(-1)??$;o+=1,i(N.table,W);const S=N.kind==="one"?N.field:N.references,T=N.kind==="one"?N.references:N.field,p=t`${Je(C,T)} = ${Je(x,S)}`;n.push(C);const A=K(w,d);n.pop();const R=A?t`${p} AND ${A}`:p,_=t`EXISTS (SELECT 1 FROM ${t.identifier(N.table)} AS ${t.identifier(C)} WHERE ${R})`;return E?t`NOT ${_}`:_},serialize:ie};return d},ct=i=>{const o=i.map(n=>t`${P(n.field)} ${t.raw(n.direction==="desc"?"DESC":"ASC")}`);return i.some(n=>n.field==="_id"||n.field==="id")||o.push(t`${P("id")} ASC`),t.join(o,t`, `)},mn={"<":"lt","<=":"lte","=":"eq",">":"gt",">=":"gte"},wn=i=>{const o=i.order;return i.indexFields.length>0?i.indexFields.map(n=>({direction:o,field:n})):[{direction:o,field:"_creationTime"}]},$n=(i,o,n,d)=>{const l=i.sqlConditions.map(w=>({[w.field]:{[mn[w.comparator]??"eq"]:w.value}}));if(n&&l.push(lt(o,Ce(n))),d&&l.push(Mt(o,Ce(d))),l.length!==0)return l.length===1?l[0]:{AND:l}},gn=(i,o,n)=>{const d=[];for(const l of i){const w=re(l);if(w&&o.every(E=>E(w))&&(d.push(w),n!==void 0&&d.length>n))break}return d},bn=(i,o,n,d,l)=>{const w=Math.max(0,Math.floor(d.numItems)),E=wn(n),$=typeof d.endCursor=="string",N=K($n(n,E,d.cursor,d.endCursor),X),C=l&&N?t`${N} AND ${l}`:l??N;let x=t`SELECT id, _creationTime, ${t.identifier(B)} FROM ${t.identifier(o)}`;C&&(x=t`${x} WHERE ${C}`),x=t`${x} ORDER BY ${ct(E)}`;const S=n.inMemoryFilters.length>0;!S&&!$&&(x=t`${x} LIMIT ${t.raw(String(w+1))}`);const T=O(i,x).toArray(),p=gn(T,n.inMemoryFilters,S||$?void 0:w);if($){const k=p.length>=2?p[Math.floor(p.length/2)-1]:void 0;return{continueCursor:d.endCursor??null,isDone:!0,page:p,splitCursor:k?ke(k,E):null}}const A=p.length>w,R=A?p.slice(0,w):p,_=R.at(-1);return{continueCursor:A&&_?ke(_,E):null,isDone:!A,page:R}};class En extends b{constructor(o="unique() found more than one matching document"){super("NOT_UNIQUE",o,{name:"NotUniqueError"})}}const yn=/\s/u,Nn=String.fromCodePoint(0),tt=(i,o,n)=>{if(!i.tables[o])throw new b("INTERNAL",`unknown table: ${o}`);return typeof n!="string"||n.length===0||yn.test(n)||n.includes(Nn)?null:n},Tn=(i,o,n,d=()=>{})=>{const l=o.tables[n];if(!l)throw new b("INTERNAL",`unknown table: ${n}`);const w=ne(l.softDeleteMode,void 0),E=w?K(w,X):void 0,$={indexFields:[],indexName:void 0,inMemoryFilters:[],order:"asc",sqlConditions:[]},N=p=>{const{search:A}=$;if(!A)throw new b("INTERNAL","runSearchFetch called without a staged search");yt(i,n,l);const R=$.inMemoryFilters.length>0,_=en(R?void 0:p),k=At(i)?an(i,n,A,_,E):sn(i,n,A,_,E);if(!R)return p===void 0&&Yt(k),k;const V=[];for(const Z of k)if($.inMemoryFilters.every(U=>U(Z))&&(V.push(Z),typeof p=="number"&&V.length>=p))break;return V},C=p=>{const A=Xt(p);return Zt(N(Vt(A)),A)},x=()=>{const p=$.indexFields.length>0?$.indexFields:["_creationTime"],A=$.order==="desc"?"DESC":"ASC";return t.join(p.map(R=>t`${P(R)} ${t.raw(A)}`),t`, `)},S=p=>$.search?N(p):$.geo?fn(i,n,$,E,p):hn(i,n,$,E,x(),p),T={async collect(){return S(void 0)},filter(p){return $.inMemoryFilters.push(p),T},async first(){return S($.inMemoryFilters.length>0?void 0:1)[0]??null},order(p){return $.order=p==="desc"?"desc":"asc",T},async paginate(p){if($.search)return C(p);if($.geo)throw new b("INTERNAL","pagination is not supported on geo queries; use .take(n) or .collect()");return bn(i,n,$,p,E)},async take(p){return S(p)},async unique(){const p=S($.inMemoryFilters.length>0?void 0:2);if(p.length>1)throw new En(`unique() on table "${n}" matched ${String(p.length)} documents; expected at most one`);return p[0]??null},withGeoIndex(p,A){const R=(l.geoIndexes??[]).find(k=>k.name===p);if(!R)throw new b("INTERNAL",`unknown geo index "${p}" on table "${n}"`);d(n,p,"geo");const _={definition:R,indexName:p};if($.geo=_,A(ln(_,n)),!_.near&&!_.within)throw new b("INTERNAL",`geo index "${p}" on table "${n}" requires a .near(point, radius) or .within(box) call`);return T},withIndex(p,A){const R=l.indexes.find(_=>_.name===p);if(!R)throw new b("INTERNAL",`unknown index "${p}" on table "${n}"`);return d(n,p,"index"),$.indexName=p,$.indexFields=R.fields,A&&A(rn($)),T},withSearchIndex(p,A){const R=(l.searchIndexes??[]).find(k=>k.name===p);if(!R)throw new b("INTERNAL",`unknown search index "${p}" on table "${n}"`);d(n,p,"search");const _={definition:R,field:R.field,filters:[],hasQuery:!1,indexName:p,query:""};if($.search=_,A(zt(_,n,Le(R.language))),!_.hasQuery)throw new b("INTERNAL",`search index "${p}" on table "${n}" requires a .search(field, query) call`);return T}};return T},nt=(i,o,n)=>{const d={...o};for(const[l,w]of at(i)){if(w.serverDefault){d[l]=w.serverDefault({auth:n});continue}d[l]===void 0&&(w.defaultFn?d[l]=w.defaultFn():"defaultValue"in w&&(d[l]=w.defaultValue))}return d},rt=(i,o,n,d)=>{const l=n;for(const[w,E]of at(i)){if(E.serverDefault){w in o&&(l[w]=E.serverDefault({auth:d}));continue}E.onUpdateFn&&!(w in o)&&(l[w]=E.onUpdateFn())}},it=(i,o)=>{for(const n of Object.keys(o))if(o[n]===void 0)throw new b("INTERNAL",`Cannot ${i} field '${n}' to undefined — use null to clear a nullable field, or omit the key to leave it unchanged.`)},Sn=/unique constraint failed/i,An=i=>i instanceof Error&&Sn.test(i.message),Me=(i,o,n)=>{try{O(i,n)}catch(d){throw An(d)?new de(`unique constraint violation on "${o}"`,"unique"):d}},Ee=(i,o,n)=>{if(Me(i,o,n),O(i,t`SELECT changes() AS changed`).one().changed===0)throw new de(`optimistic concurrency conflict on "${o}" — the row changed during this mutation; refetch and retry`,"occ")},ot=(i,o,n,d,l,w,E)=>{const $=[];for(let S=0;S<n.length+1;S+=1){const T=[];for(let _=0;_<S;_+=1)T.push(t`${t.identifier(n[_])} IS ${w[_]}`);const p=n[S],A=d[S];if(p!==void 0&&A!==void 0){const _=A.direction==="desc"?">":"<";T.push(t`${t.identifier(p)} ${t.raw(_)} ${w[S]}`)}else T.push(t`${t.identifier(Ot)} < ${E}`);const[R]=T;$.push(T.length===1&&R!==void 0?R:t`(${t.join(T,t` AND `)})`)}const N=t.join($,t` OR `),C=O(i,t`SELECT COUNT(*) AS c FROM ${t.identifier(o)} WHERE ${t.identifier("__partition__")} = ${l} AND (${N})`).one(),x=O(i,t`SELECT COUNT(*) AS c FROM ${t.identifier(o)} WHERE ${t.identifier("__partition__")} = ${l}`).one();return{before:C.c,total:x.c}},Qn=i=>{const{sql:o}=i,{schema:n}=i,d=i.broadcast??(()=>{}),l=i.onRead??(()=>{}),w=i.onIndexUse??(()=>{}),E=i.onWrite??(()=>{}),{cache:$}=i,N=i.clock??(()=>Date.now()),C=i.idGenerator??(()=>crypto.randomUUID()),x=i.scheduler??$t,{globalDb:S}=i,T=i.auth??{identity:null,userId:null},p=i.cdc??!1,A=x,R=Ft({scheduler:typeof A.list=="function"&&typeof A.get=="function"?A:void 0,storage:i.storage}),_=(e,r,a,h)=>{p&&Nt(o,N(),e,r,a,h)},k=e=>n.tables[e]?.shardMode?.kind==="global",V=(e,r)=>{if(k(e)){if(!S)throw new b("INTERNAL",`cross-backend ${r} for global table '${e}' requires a globalDb writer — pass one to createShardCtxDb({ globalDb })`);return S}return L},Z=e=>V(e,"cascade"),U=(e,r)=>{if(k(e)){if(!S)throw new b("INTERNAL",`${r} on global table '${e}' requires a globalDb writer — pass one to createShardCtxDb({ globalDb })`);return S}},oe=()=>S,ye=(e,r)=>V(e,"relation load").findMany(e,r),Oe=(e,r)=>(k(e)&&l(e,W),ye(e,r)),ut=e=>!k(e.table),We=i.relationExistsPushDown??"auto",Be=We!=="never",{maxRelationKeys:qe}=i,ce=(e,r,a)=>Ke(e,{fetcher:Oe,maxRelationKeys:qe,relationBaseWhere:a,schema:n,tableName:r}),Fe=async(e,r,a,h)=>{const f=U(e,"relation grouped count");if(f)return l(e,W),Bt((v,F)=>f.count(v,F),e,r,a,h);const c=n.tables[e];if(!c)throw new b("INTERNAL",`unknown table: ${e}`);l(e,W);const s=ne(c.softDeleteMode,void 0),u={[r]:{in:a}},m=H(H(u,h),s),y=await ce(m,e,void 0),g=K(y,X),I=P(r);let D=t`SELECT ${I} AS __fk__, COUNT(*) AS count FROM ${t.identifier(e)}`;g&&(D=t`${D} WHERE ${g}`),D=t`${D} GROUP BY ${I}`;const M=O(o,D).toArray();return new Map(M.map(v=>[v.__fk__,v.count]))};let ue=0;const Ue=new Set;for(const[e,r]of Object.entries(n.tables))for(const a of Object.values(r.triggerMap??{}))Ue.add(`${e} ${a.timing} ${a.op}`);const z=(e,r,a)=>Ue.has(`${e} ${r} ${a}`),Y=async(e,r,a)=>{if(ue+=1,ue>et)throw ue-=1,new de(`trigger recursion exceeded ${String(et)} levels on "${a.table}" — check for a self-triggering write`,"trigger");try{await Ut({ctx:ft,event:a,op:r,schema:n,tableName:a.table,timing:e})}finally{ue-=1}},{ensureBackfilledForTable:ae,ensureBackfilledIndex:Ne,ensureRankBackfilled:Te,ensureRankBackfilledForTable:se,syncAggregates:fe,syncCompanionsForInsert:He,syncGeo:he,syncRanks:le,syncSearch:pe}=Tt({broadcast:d,invalidateCache:(e,r)=>$?.invalidate(e,r),recordCdc:_,schema:n,sql:o}),Pe=(e,r,a)=>{const{shardMode:h}=r;if(h?.kind==="shardBy"&&!(h.field!==void 0&&(a.partitionBy??[]).includes(h.field)))throw Object.assign(new Error(`rank index "${a.name}" on "${e}" partitions across shards (shard key "${h.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})},Q=(e,r)=>{const a=Object.entries(n.tables).filter(([,y])=>y.shardMode?.kind!=="global").map(([y])=>y).filter(y=>r===void 0||y===r);if(a.length===0)return;const h=a.map(y=>t`SELECT ${t.raw(`'${y.replaceAll("'","''")}'`)} AS __t__, id, _creationTime, ${t.identifier(B)} FROM ${t.identifier(y)} WHERE id = ${e}`),f=t`${t.join(h,t` UNION ALL `)} LIMIT 1`,[c]=O(o,f).toArray();if(!c)return;const s=c.__t__,u=re(c);if(typeof s!="string"||!u)return;const m=c[B];return{docJson:typeof m=="string"?m:JSON.stringify(m??{}),row:u,tableName:s}},Ge={assertRankPartitionLocal:Pe,ensureRankBackfilled:Te,onRead:l,rowToDocument:re,schema:n,sql:o},L={system:R,async aggregate(e,r){const a=U(e,"aggregate");if(a)return l(e,W),a.aggregate(e,r);const h=n.tables[e];if(!h)throw new b("INTERNAL",`unknown table: ${e}`);if($e(r.op),r.op==="count")return L.count(e,{baseWhere:r.baseWhere,relationBaseWhere:r.relationBaseWhere,restrictsCounts:r.restrictsCounts,where:r.where});if(!r.field)throw new b("INTERNAL",`aggregate(${e}, { op: "${r.op}" }): "field" is required for non-count reducers`);l(e,W);const f=ne(h.softDeleteMode,void 0),c=H(H(r.baseWhere,r.where),f),s=await ce(c,e,r.relationBaseWhere),u=s!==c;if(h.aggregateIndexes&&!r.baseWhere&&!u&&!f){const M=Et(h.aggregateIndexes,r.op,r.field,r.where);if(M){Ne(e,M.index);const v=Se(M.index.by??[],M.key),F=_e(e,M.index.name),G=O(o,t`SELECT ${ge} AS value, ${Ie} AS count FROM ${t.identifier(F)} WHERE ${be} = ${v}`).toArray()[0];return Ae(r.op,G)}}const m=K(s,X),y=$e(r.op),g=P(r.field);let I=t`SELECT ${t.raw(y)}(${g}) AS value FROM ${t.identifier(e)}`;return m&&(I=t`${I} WHERE ${m}`),O(o,I).toArray()[0]?.value??null},asId(e,r){const a=tt(n,e,r);if(a===null)throw new b("BAD_REQUEST",`asId("${e}", …): "${r}" is not a valid id for table "${e}"`,{status:400});return a},async count(e,r){const a=U(e,"count");if(a)return l(e,W),a.count(e,r);const h=n.tables[e];if(!h)throw new b("INTERNAL",`unknown table: ${e}`);const f=wt(r);if(f.restrictsCounts)throw new Re(e);l(e,W);const c=ne(h.softDeleteMode,void 0),s=H(H(f.baseWhere,f.where),c),u=await ce(s,e,f.relationBaseWhere),m=u!==s;if(h.aggregateIndexes&&!f.baseWhere&&!m&&!c){const I=bt(h.aggregateIndexes,f.where);if(I){Ne(e,I.index);const D=Se(I.index.by??[],I.key),M=_e(e,I.index.name),v=O(o,t`SELECT ${ge} AS value FROM ${t.identifier(M)} WHERE ${be} = ${D}`).toArray();return v[0]===void 0?0:v[0].value??0}}const y=K(u,X);let g=t`SELECT COUNT(*) AS count FROM ${t.identifier(e)}`;return y&&(g=t`${g} WHERE ${y}`),O(o,g).one().count},async delete(e,r,a){const h=Q(e,r);if(!h){const g=r===void 0?oe():void 0;g&&await g.delete(e,void 0,a);return}const{docJson:f,row:c,tableName:s}=h,u=n.tables[s],m=a?.hard===!0,y=!m&&u?.softDeleteMode?u.softDeleteMode.field:void 0;if(!(y&&c[y]!==null&&c[y]!==void 0)){if(z(s,"before","delete")&&await Y("before","delete",{id:e,op:"delete",previous:c,table:s}),await Wt({deletedId:e,deletedReference:g=>c[g],findHolders:async(g,I,D)=>(await Z(g).findMany(g,{includeDeleted:m,where:{[I]:D}})).page,onCascade:(g,I)=>Z(g).delete(I,void 0,a),onRestrict:g=>{throw new de(g,"restrict")},onSetNull:(g,I,D)=>Z(g).patch(I,{[D]:null}),schema:n,tableName:s}),ae(s),se(s),y){const g={...c,[y]:N(),_id:e};Ee(o,s,t`UPDATE ${t.identifier(s)} SET ${t.identifier(B)} = ${JSON.stringify(g)} WHERE id = ${e} AND ${t.identifier(B)} = ${f}`),pe(s,e,g,c),he(s,e,void 0),fe(s,c,g),le(s,e,c,void 0),$?.invalidate(s,e),_(s,e,"update",g),d({key:e,op:"update",row:g,table:s}),z(s,"after","delete")&&await Y("after","delete",{id:e,op:"delete",previous:c,table:s}),await E({id:e,op:"delete",table:s});return}Ee(o,s,t`DELETE FROM ${t.identifier(s)} WHERE id = ${e} AND ${t.identifier(B)} = ${f}`),pe(s,e,void 0),he(s,e,void 0),fe(s,c,void 0),le(s,e,c,void 0),$?.invalidate(s,e),_(s,e,"delete"),d({key:e,op:"delete",table:s}),z(s,"after","delete")&&await Y("after","delete",{id:e,op:"delete",previous:c,table:s}),await E({id:e,op:"delete",table:s})}},async deleteAll(e,r){if(!n.tables[e])throw new b("INTERNAL",`unknown table: ${e}`);const a=Math.max(1,r?.chunkSize??dt),h=r?.hard===void 0?void 0:{hard:r.hard},f=k(e)?void 0:e;let c=0;for(;;){const s=(await L.findMany(e,{limit:a})).page.map(u=>String(u._id));if(s.length===0)break;for(const u of s)await L.delete(u,f,h),c+=1;if(s.length<a)break}return{deleted:c}},async deleteMany(e,r,a){te(e.length,r?.limit,"deleteMany");for(const h of e)await L.delete(h,a);return{deleted:e.length}},async deleteWhere(e,r,a){const h=U(e,"deleteWhere");let f;if(h)f=(await h.findMany(e,{where:r})).page.map(c=>String(c._id));else{if(!n.tables[e])throw new b("INTERNAL",`unknown table: ${e}`);f=(await L.findMany(e,{where:r})).page.map(c=>String(c._id))}if(te(f.length,a?.limit,"deleteWhere"),L.deleteMany===void 0)throw new b("INTERNAL",`ctx.db.${e}.deleteMany is unavailable: this writer has no batch delete`);return L.deleteMany(f,a)},async findFirst(e,r={}){return(await L.findMany(e,{...r,limit:1})).page[0]??null},async findFirstOrThrow(e,r={}){const a=await L.findFirst(e,r);if(a===null)throw new Ct(`findFirstOrThrow: no "${e}" document matched`);return a},async findMany(e,r={}){const a=U(e,"findMany");if(a)return l(e,W),a.findMany(e,r);const h=n.tables[e];if(!h)throw new b("INTERNAL",`unknown table: ${e}`);const f=!r.where&&!r.baseWhere;f?l(e,W):l(e);const c=kt(r.orderBy),s=r.cursor?lt(c,Ce(r.cursor)):void 0;let u=H(r.baseWhere,r.where);u=H(u,ne(h.softDeleteMode,r.includeDeleted)),u=await Ke(u,{canPushExists:Be?ut:void 0,existsPushMode:We==="always"?"always":"auto",fetcher:Oe,maxRelationKeys:qe,relationBaseWhere:r.relationBaseWhere,schema:n,tableName:e}),s&&(u=u?{AND:[u,s]}:s);const m=Be?pn(l):X,y=K(u,m);let g=t`SELECT id, _creationTime, ${t.identifier(B)} FROM ${t.identifier(e)}`;y&&(g=t`${g} WHERE ${y}`),g=t`${g} ORDER BY ${ct(c)}`;const I=typeof r.limit=="number"?Math.max(0,Math.floor(r.limit)):void 0;I!==void 0&&(g=t`${g} LIMIT ${t.raw(String(I+1))}`);const D=O(o,g).toArray(),M=[];for(const j of D){const q=re(j);q&&(M.push(q),!f&&typeof q._id=="string"&&l(e,q._id))}if(I===void 0)return r.with&&await Qe({groupedCounter:Fe,fetcher:ye,parents:M,relationBaseWhere:r.relationBaseWhere,schema:n,tableName:e,with:r.with}),{continueCursor:null,isDone:!0,page:ze(M,r.select,r.with)};const v=M.length>I,F=v?M.slice(0,I):M,G=F.at(-1);return r.with&&await Qe({fetcher:ye,groupedCounter:Fe,parents:F,relationBaseWhere:r.relationBaseWhere,schema:n,tableName:e,with:r.with}),{continueCursor:v&&G?ke(G,c):null,isDone:!v,page:ze(F,r.select,r.with)}},async get(e,r){const a=Q(e,r);if(!a){const h=r===void 0?oe():void 0;return h?h.get(e):null}return l(a.tableName,e),a.row},async lookupById(e,r){const a=Q(e,r);return a?(l(a.tableName,e),{row:a.row,tableName:a.tableName}):null},async groupBy(e,r){const a=U(e,"groupBy");if(a)return l(e,W),a.groupBy(e,r);const h=n.tables[e];if(!h)throw new b("INTERNAL",`unknown table: ${e}`);l(e,W);const f=r.agg??{op:"count"};if($e(f.op),f.op!=="count"&&!f.field)throw new b("INTERNAL",`groupBy(${e}, { agg: { op: "${f.op}" } }): "field" is required for non-count reducers`);const c=ne(h.softDeleteMode,void 0),s=H(H(r.baseWhere,r.where),c),u=await ce(s,e,r.relationBaseWhere),m=u!==s;if(h.aggregateIndexes&&!r.baseWhere&&!m&&!c){const v=gt(h.aggregateIndexes,f.op,f.field,r.by,r.where);if(v){Ne(e,v.index);const F=_e(e,v.index.name),G=Object.keys(v.partial),j=[];if(G.length===(v.index.by??[]).length&&G.length>0){const ee=Se(v.index.by??[],v.partial),me=O(o,t`SELECT ${ge} AS value, ${Ie} AS count FROM ${t.identifier(F)} WHERE ${be} = ${ee}`).toArray();return me.length>0&&j.push({key:{...v.partial},value:Ae(f.op,me[0])}),j}const q=O(o,t`SELECT ${be} AS key, ${ge} AS value, ${Ie} AS count FROM ${t.identifier(F)}`).toArray();for(const ee of q){const me=JSON.parse(ee.key);j.push({key:me,value:Ae(f.op,ee)})}return j}}const y=K(u,X),g=r.by.map(v=>t`${P(v)} AS ${t.identifier(v)}`);if(f.op==="count")g.push(t`COUNT(*) AS value`);else{const{field:v}=f;if(v===void 0)throw new b("INTERNAL",`groupBy(${e}, { agg: { op: "${f.op}" } }): "field" is required for non-count reducers`);g.push(t`${t.raw($e(f.op))}(${P(v)}) AS value`)}let I=t`SELECT ${t.join(g,t`, `)} FROM ${t.identifier(e)}`;y&&(I=t`${I} WHERE ${y}`),I=t`${I} GROUP BY ${t.join(r.by.map(v=>P(v)),t`, `)}`;const D=O(o,I).toArray(),M=[];for(const v of D){const F={};for(const j of r.by)F[j]=v[j]??null;const{value:G}=v;M.push({key:F,value:G==null?null:Number(G)})}return M},async insert(e,r,a){const h=U(e,"insert");if(h){const y=await h.insert(e,r,a);return d({key:y,op:"insert",row:{...r,_id:y},table:e}),y}const f=n.tables[e];if(!f)throw new b("INTERNAL",`unknown table: ${e}`);const c=nt(f,r,T);xe(f,c);let s;a?.clientId!==void 0?(nn(a.clientId),s=a.clientId):a?.allowExplicitId&&typeof c._id=="string"?s=c._id:s=C();const u=a?.allowExplicitId&&typeof c._creationTime=="number"?c._creationTime:N(),m={...c,_creationTime:u,_id:s};return z(e,"before","insert")&&await Y("before","insert",{doc:{...m},id:s,op:"insert",table:e}),ae(e),se(e),Me(o,e,t`INSERT INTO ${t.identifier(e)} (id, _creationTime, ${t.identifier(B)}) VALUES (${s}, ${u}, ${JSON.stringify(m)})`),He(e,s,m),z(e,"after","insert")&&await Y("after","insert",{doc:m,id:s,op:"insert",table:e}),await E({doc:m,id:s,op:"insert",table:e}),s},async insertManyUnsafe(e,r,a){if(te(r.length,a?.limit,"insertManyUnsafe"),r.length===0)return[];const h=U(e,"insert");if(h){const u=[];for(const m of r){const y=await h.insert(e,m,{allowExplicitId:a?.allowExplicitId});d({key:y,op:"insert",row:{...m,_id:y},table:e}),u.push(y)}return u}const f=n.tables[e];if(!f)throw new b("INTERNAL",`unknown table: ${e}`);ae(e),se(e);const c=r.map(u=>{const m=nt(f,u,T),y=a?.allowExplicitId===!0&&typeof m._id=="string"?m._id:C(),g=a?.allowExplicitId===!0&&typeof m._creationTime=="number"?m._creationTime:N();return{creationTime:g,document:{...m,_creationTime:g,_id:y},id:y}}),s=t.join(c.map(u=>t`(${u.id}, ${u.creationTime}, ${JSON.stringify(u.document)})`),t`, `);Me(o,e,t`INSERT INTO ${t.identifier(e)} (id, _creationTime, ${t.identifier(B)}) VALUES ${s}`);for(const{document:u,id:m}of c)He(e,m,u),await E({doc:u,id:m,op:"insert",table:e});return c.map(u=>u.id)},async insertMany(e,r,a){te(r.length,a?.limit,"insertMany");const h=a?.skipDuplicates===!0,f=[];for(const c of r)try{f.push(await L.insert(e,c))}catch(s){if(h&&s instanceof de&&s.kind==="unique")f.push(null);else throw s}return f},normalizeId(e,r){return tt(n,e,r)},async patch(e,r,a){const h=Q(e,a);if(!h){const y=a===void 0?oe():void 0;if(y){await y.patch(e,r);return}throw new b("INTERNAL",`document not found: ${e}`)}const{docJson:f,row:c,tableName:s}=h,u=n.tables[s];if(!u)throw new b("INTERNAL",`unknown table: ${s}`);l(s,e),it("patch",r);const m={...c,...r,_id:e};rt(u,r,m,T),xe(u,m,!0),z(s,"before","update")&&await Y("before","update",{doc:{...m},id:e,op:"update",previous:c,table:s}),ae(s),se(s),Ee(o,s,t`UPDATE ${t.identifier(s)} SET ${t.identifier(B)} = ${JSON.stringify(m)} WHERE id = ${e} AND ${t.identifier(B)} = ${f}`),pe(s,e,m,c),he(s,e,m),fe(s,c,m),le(s,e,c,m),$?.invalidate(s,e),_(s,e,"update",m),d({key:e,op:"update",row:m,table:s}),z(s,"after","update")&&await Y("after","update",{doc:m,id:e,op:"update",previous:c,table:s}),await E({doc:m,id:e,op:"update",table:s})},async patchMany(e,r,a){te(e.length,r?.limit,"patchMany");for(const h of e)await L.patch(h.id,h.patch,a);return{patched:e.length}},async patchWhere(e,r,a){const h=U(e,"patchWhere");let f;if(h)f=(await h.findMany(e,{where:r.where})).page.map(c=>({id:String(c._id),patch:r.patch}));else{if(!n.tables[e])throw new b("INTERNAL",`unknown table: ${e}`);f=(await L.findMany(e,{where:r.where})).page.map(c=>({id:String(c._id),patch:r.patch}))}if(te(f.length,a?.limit,"patchWhere"),L.patchMany===void 0)throw new b("INTERNAL",`ctx.db.${e}.patchMany is unavailable: this writer has no batch patch`);return await L.patchMany(f,a),{patched:f.length}},query(e){const r=U(e,"query");return r?(l(e,W),r.query(e)):(l(e,W),Tn(o,n,e,w))},async rank(e,r,a){const h=U(e,"rank");if(h)return l(e,W),h.rank(e,r,a);w(e,r,"rank");const f=n.tables[e];if(!f)throw new b("INTERNAL",`unknown table: ${e}`);const c=f.rankIndexes?.find(q=>q.name===r);if(!c)throw new b("INTERNAL",`unknown rankIndex "${r}" on table "${e}"`);if(Pe(e,f,c),a.restrictsCounts)throw new Re(e);l(e,W),Te(e,c);const s=typeof a.row=="string"?a.row:a.row._id;if(!s)return null;const u=Ve(e,c.name),m=c.sortBy.map((q,ee)=>Ye(ee)),y=m.map(q=>St(q)).join(", "),g=O(o,t`SELECT ${t.identifier("__partition__")}, ${t.raw(y)} FROM ${t.identifier(u)} WHERE ${t.identifier("__id__")} = ${s}`).toArray(),[I]=g;if(I===void 0)return null;let D=I.__partition__;const M=H(a.baseWhere,a.where);ve(M,n,e,"rank");const v=Lt(c,M);if(v){const q=Dt(c.partitionBy??[],v);if(q!==D)return null;D=q}const F=m.map(q=>I[q]),{before:G,total:j}=ot(o,u,m,c.sortBy,D,F,s);return{position:G+1,total:j}},async rankBefore(e,r,a){if(k(e))throw new b("INTERNAL",`rankBefore is not supported on the global (.global()) table '${e}' — cross-shard rank cursors apply only to sharded tables`);const h=n.tables[e];if(!h)throw new b("INTERNAL",`unknown table: ${e}`);const f=h.rankIndexes?.find(m=>m.name===r);if(!f)throw new b("INTERNAL",`unknown rankIndex "${r}" on table "${e}"`);if(a.restrictsCounts)throw new Re(e);l(e,W),Te(e,f);const c=Ve(e,f.name),s=f.sortBy.map((m,y)=>Ye(y)),u=f.sortBy.map((m,y)=>ie(a.sortValues[y]??null));return ot(o,c,s,f.sortBy,a.partitionKey,u,a.rowId)},async rankPage(e,r,a={}){ve(H(a.baseWhere,a.where),n,e,"rankPage");const h=U(e,"rankPage");if(h)return l(e,W),h.rankPage(e,r,a);w(e,r,"rank");const{continueCursor:f,hasMore:c,rows:s}=je(Ge,e,r,a);return{continueCursor:f,isDone:!c,page:s.map(u=>u.doc)}},async rankPageRows(e,r,a={}){ve(H(a.baseWhere,a.where),n,e,"rankPage"),w(e,r,"rank");const{directions:h,hasMore:f,rows:c}=je(Ge,e,r,a);return{directions:h,hasMore:f,rows:c}},async restore(e,r){const a=Q(e,r);if(!a){const c=r===void 0?oe():void 0;if(c?.restore){await c.restore(e);return}throw new b("INTERNAL",`document not found: ${e}`)}const h=n.tables[a.tableName]?.softDeleteMode?.field;if(!h)throw new b("INTERNAL",`ctx.db.restore: table "${a.tableName}" is not a .softDelete() table`);const f=a.row[h]!==null&&a.row[h]!==void 0;await L.patch(e,{[h]:null},r),f&&le(a.tableName,e,void 0,a.row)},async replace(e,r,a,h){const f=Q(e,a);if(!f){const I=a===void 0?oe():void 0;if(I){await I.replace(e,r,void 0,h);return}throw new b("INTERNAL",`document not found: ${e}`)}const{docJson:c,row:s,tableName:u}=f,m=n.tables[u];if(!m)throw new b("INTERNAL",`unknown table: ${u}`);it("replace",r);const y=h?.allowExplicitId&&typeof r._creationTime=="number"?r._creationTime:N(),g={...r,_creationTime:y,_id:e};rt(m,r,g,T),xe(m,g),z(u,"before","update")&&await Y("before","update",{doc:{...g},id:e,op:"update",previous:s,table:u}),ae(u),se(u),Ee(o,u,t`UPDATE ${t.identifier(u)} SET _creationTime = ${y}, ${t.identifier(B)} = ${JSON.stringify(g)} WHERE id = ${e} AND ${t.identifier(B)} = ${c}`),pe(u,e,g,s),he(u,e,g),fe(u,s,g),le(u,e,s,g),$?.invalidate(u,e),_(u,e,"update",g),d({key:e,op:"update",row:g,table:u}),z(u,"after","update")&&await Y("after","update",{doc:g,id:e,op:"update",previous:s,table:u}),await E({doc:g,id:e,op:"update",table:u})},async wipeShard(e){const r=new Set(e?.exclude),a=e?.tables,h=Object.entries(n.tables).filter(([u,m])=>r.has(u)||a!==void 0&&!a.includes(u)?!1:m.shardMode?.kind!=="global").map(([u])=>u);if(a!==void 0){for(const u of a)if(!n.tables[u])throw new b("INTERNAL",`wipeShard: unknown table: ${u}`)}const f={};let c=0;const{deleteAll:s}=L;if(s===void 0)throw new b("INTERNAL","wipeShard: this writer has no deleteAll");for(const u of h){const m=await s(u,{...e?.chunkSize===void 0?{}:{chunkSize:e.chunkSize},hard:!0});f[u]=m.deleted,c+=m.deleted}return{deleted:c,tables:f}}},ft={db:L,scheduler:x};return i.enforceRls===!0?qt(L,n,(e,r)=>Q(e,r)?.tableName):L};export{ir as CDC_LOG_TABLE,hr as CLIENT_WATERMARK_TABLE,gr as GLOBAL_SHAPE_SNAPSHOT_TABLE,Ar as IDEMPOTENCY_TABLE,En as NotUniqueError,kr as SEARCH_STATE_TABLE,pr as advanceClientWatermark,or as applyCdcChanges,nn as assertValidClientId,er as backfillAggregateIndexes,tr as backfillRankIndexes,nr as backfillSearchIndexes,ar as bumpCdcEpoch,Qn as createShardCtxDb,br as deleteGlobalShapeSnapshot,Er as deleteGlobalShapeSnapshotsForConnection,mr as migrateClientWatermark,yr as migrateGlobalShapeSnapshot,sr as minCdcSeq,tt as normalizeIdStructurally,lr as readCdcChanges,dr as readCdcCursor,cr as readCdcEpoch,wr as readClientWatermark,Nr as readGlobalShapeSnapshot,_r as readIdempotent,xr as runShardMigrations,Lr as selectShapeMemberIds,Dr as selectShapeRows,ur as trimCdcChanges,Rr as trimIdempotent,Tr as writeGlobalShapeSnapshot,Ir as writeIdempotent};
@@ -1 +0,0 @@
1
- import{stableWireKey as d}from"./stableWireKey-YEHLaX6X.mjs";import{depKey as c,SCAN_DEP as y}from"./SCAN_DEP-D_yR9EeV.mjs";import{stableStringify as w}from"./stableStringify-BjLh4gvA.mjs";const u=1e3,l=4*1024*1024,m=r=>{if(r==null)return 0;try{return JSON.stringify(r).length}catch{return l}};class p{entries=new Map;tableIndex=new Map;totalBytes=0;hits=0;misses=0;evictions=0;maxEntries;maxBytes;now;monotonic=0;constructor(t={}){this.maxEntries=t.maxEntries??u,this.maxBytes=t.maxBytes??l,this.now=t.now??(()=>(this.monotonic+=1,this.monotonic))}async run(t,s,e){const i=this.entries.get(t);if(i)return this.hits+=1,i.lastUsed=this.now(),this.entries.delete(t),this.entries.set(t,i),i.result;this.misses+=1;const n=await e(),h=m(n),b={bytes:h,deps:s,lastUsed:this.now(),result:n,subscribers:new Set};this.entries.set(t,b),this.totalBytes+=h;for(const a of s){let o=this.tableIndex.get(a);o||(o=new Set,this.tableIndex.set(a,o)),o.add(t)}return this.evict(),n}invalidate(t,s){const e=[];return this.collectAndDrop(c(t,s),e),this.collectAndDrop(c(t,y),e),e}invalidateTable(t){const s=[],e=`${t}:`;for(const i of this.tableIndex.keys())i.startsWith(e)&&this.collectAndDrop(i,s);return s}subscribe(t,s){const e=this.entries.get(t);e&&e.subscribers.add(s)}unsubscribe(t,s){const e=this.entries.get(t);e&&e.subscribers.delete(s)}size(){return{bytes:this.totalBytes,entries:this.entries.size}}clear(){this.entries.clear(),this.tableIndex.clear(),this.totalBytes=0}subscribers(t){const s=this.entries.get(t);return s?[...s.subscribers]:[]}stats(){return{bytes:this.totalBytes,entries:this.entries.size,evictions:this.evictions,hits:this.hits,misses:this.misses}}collectAndDrop(t,s){const e=this.tableIndex.get(t);if(e)for(const i of e){const n=this.entries.get(i);n&&(this.dropEntry(i,n),s.push(i))}}dropEntry(t,s){this.entries.delete(t),this.totalBytes-=s.bytes;for(const e of s.deps){const i=this.tableIndex.get(e);i&&(i.delete(t),i.size===0&&this.tableIndex.delete(e))}}evict(){if(!(this.entries.size<=this.maxEntries&&this.totalBytes<=this.maxBytes))for(const[t,s]of this.entries){if(this.entries.size<=this.maxEntries&&this.totalBytes<=this.maxBytes)return;s.subscribers.size>0||(this.dropEntry(t,s),this.evictions+=1)}}}const B=(r,t,s)=>`${s??"\0anon"}\0${r}:${d(t)}`;export{p as ReactiveCache,B as reactiveCacheKey,w as stableStringify,d as stableWireKey};
@@ -1 +0,0 @@
1
- import{u as Z,T as q,l as ee,y as ne,c as ie}from"./FTS_COUNT_COLUMN-D1gY3wwZ-CZHdaRrd.mjs";import"@lunora/errors";import{sql as e}from"drizzle-orm";import{matchesStaticWhere as x,aggregateSqlFunction as te}from"./AGGREGATE_SQL_FUNCTION-QYaiuty4.mjs";import{encodeAggregateKey as A,foldAggregateTally as oe,aggregateTableName as G,coerceAggregateNumber as U}from"./aggregateTableName-G-eXyjcz.mjs";import{runDrizzle as l}from"./runDrizzle-GKR3y97k.mjs";import{isFtsAvailable as re,DOC_COLUMN as H,rowToDocument as V,AGG_KEY as S,AGG_VALUE as g,AGG_COUNT as m,geoTableName as ae,aggUpsertSql as F,jsonPathSql as N}from"./AGG_COUNT-BWXe3gtQ.mjs";import{param as P}from"./param-B5lF5Jd9.mjs";import{encodeGeohash as se,GEO_DEFAULT_PRECISION as $e}from"./GEO_DEFAULT_PRECISION-okRCkZ6r.mjs";import{sortColumnName as z,matchesRankStaticWhere as K,encodePartitionKey as Y,rankTableName as J}from"./RANK_TIEBREAK-9NU5s_mi.mjs";import{serializeSqlValue as C}from"./serializeSqlValue-DnpyaLcw.mjs";const ce=(T,I,p)=>[...T.partitionBy??[],...T.sortBy.map(y=>y.field),...T.where?Object.keys(T.where):[]].every(y=>I[y]===p[y]),fe=(T,I,p,y,h,r)=>{if(h&&r&&ce(p,h,r))return;const L=J(I,p.name);if(h&&l(T,e`DELETE FROM ${e.identifier(L)} WHERE ${e.identifier("__id__")} = ${y}`),!r||p.where&&!K(r,p.where))return;const O=p.sortBy.map((R,v)=>z(v)),w=e.join(["__id__","__partition__",...O].map(R=>e.identifier(R)),e`, `),D=Y(p.partitionBy??[],r),M=p.sortBy.map(R=>C(r[R.field]??null)),k=e.join([y,D,...M].map(R=>P(R)),e`, `);l(T,e`INSERT INTO ${e.identifier(L)} (${w}) VALUES (${k})`)},Re=T=>{const{broadcast:I,invalidateCache:p,recordCdc:y,schema:h,sql:r}=T,L=new Set,O=new Set,w=(i,n)=>{const o=`${i}::${n.name}`;if(L.has(o))return;const c=G(i,n.name),a=n.by??[],d=new Map,f=l(r,e`SELECT id, _creationTime, ${e.identifier(H)} FROM ${e.identifier(i)}`).toArray();for(const $ of f){const t=V($);if(!t||n.where&&!x(t,n.where))continue;const u=A(a,t);oe(d,u,n,t)}l(r,e`DELETE FROM ${e.identifier(c)}`);const _=32,s=[...d];for(let $=0;$<s.length;$+=_){const t=s.slice($,$+_),u=e.join(t.map(([E,b])=>e`(${E}, ${b.value}, ${b.count})`),e`, `);l(r,e`INSERT INTO ${e.identifier(c)} (${S}, ${g}, ${m}) VALUES ${u}`)}L.add(o)},D=(i,n,o)=>{const c=n.by??[],a=te(n.op),d=n.field??"",f=[];for(const $ of c){const t=C(o[$]??null);t===null?f.push(e`${N($)} IS NULL`):f.push(e`${N($)} = ${t}`)}for(const[$,t]of Object.entries(n.where??{})){const u=t!==null&&typeof t=="object"&&!Array.isArray(t)?t.eq:t,E=C(u);E===null?f.push(e`${N($)} IS NULL`):f.push(e`${N($)} = ${E}`)}const _=f.length>0?e` WHERE ${e.join(f,e` AND `)}`:e``,s=N(d);return{value:l(r,e`SELECT ${e.raw(a)}(${s}) AS value FROM ${e.identifier(i)}${_}`).one().value??null}},M=(i,n,o,c)=>{const a=G(i,n.name),{op:d}=n,f=n.field??"",_=t=>{l(r,e`DELETE FROM ${e.identifier(a)} WHERE ${S} = ${t} AND ${m} <= 0`)},s=o&&(!n.where||x(o,n.where))?o:void 0,$=c&&(!n.where||x(c,n.where))?c:void 0;if(!(!s&&!$)){if(d==="count"){for(const[t,u]of[[s,-1],[$,1]]){if(!t)continue;const E=A(n.by??[],t);l(r,F(a,E,u,u,e`${g} = ${g} + excluded.${g}, ${m} = ${m} + excluded.${m}`))}s&&_(A(n.by??[],s));return}if(d==="sum"||d==="avg"){for(const[t,u]of[[s,-1],[$,1]]){if(!t)continue;const E=U(t[f]);if(E===void 0)continue;const b=A(n.by??[],t);l(r,F(a,b,u*E,u,e`${g} = COALESCE(${g}, 0) + excluded.${g}, ${m} = ${m} + excluded.${m}`))}s&&_(A(n.by??[],s));return}if(s){const t=A(n.by??[],s),u=U(s[f]),E=l(r,e`SELECT ${g} AS value, ${m} AS count FROM ${e.identifier(a)} WHERE ${S} = ${t}`).toArray()[0],b=(E?.count??0)-1;if(b<=0)l(r,e`DELETE FROM ${e.identifier(a)} WHERE ${S} = ${t}`);else if(E&&u!==void 0&&E.value!==null&&u===E.value){const Q=D(i,n,s);l(r,e`UPDATE ${e.identifier(a)} SET ${g} = ${Q.value}, ${m} = ${b} WHERE ${S} = ${t}`)}else l(r,e`UPDATE ${e.identifier(a)} SET ${m} = ${m} - 1 WHERE ${S} = ${t}`)}if($){const t=A(n.by??[],$),u=U($[f]);if(u===void 0)l(r,F(a,t,null,1,e`${m} = ${m} + 1`));else{const E=d==="min"?"MIN":"MAX";l(r,F(a,t,u,1,e`${g} = ${e.raw(E)}(COALESCE(${g}, excluded.${g}), excluded.${g}), ${m} = ${m} + 1`))}}}},k=i=>{const n=h.tables[i]?.aggregateIndexes;if(!(!n||n.length===0))for(const o of n)w(i,o)},R=(i,n,o)=>{const c=h.tables[i]?.aggregateIndexes;if(!(!c||c.length===0))for(const a of c)M(i,a,n,o)},v=(i,n)=>{const o=`${i}::rank::${n.name}`;if(O.has(o))return;const c=J(i,n.name),a=l(r,e`SELECT id, _creationTime, ${e.identifier(H)} FROM ${e.identifier(i)}`).toArray();l(r,e`DELETE FROM ${e.identifier(c)}`);const d=n.sortBy.map((_,s)=>z(s)),f=e.join(["__id__","__partition__",...d].map(_=>e.identifier(_)),e`, `);for(const _ of a){const s=V(_);if(!s||n.where&&!K(s,n.where))continue;const $=Y(n.partitionBy??[],s),t=n.sortBy.map(E=>C(s[E.field]??null)),u=e.join([s._id,$,...t].map(E=>P(E)),e`, `);l(r,e`INSERT INTO ${e.identifier(c)} (${f}) VALUES (${u})`)}O.add(o)},X=i=>{const n=h.tables[i]?.rankIndexes;if(!(!n||n.length===0))for(const o of n)v(i,o)},B=(i,n,o,c)=>{const a=h.tables[i]?.rankIndexes;if(!(!a||a.length===0))for(const d of a)fe(r,i,d,n,o,c)},j=(i,n,o,c)=>{const a=h.tables[i]?.searchIndexes;if(!(!a||a.length===0||!re(r)))for(const d of a){if(Z(c,o,d))continue;const f=ie(i,d.name);l(r,e`DELETE FROM ${e.identifier(f)} WHERE ${e.identifier(q)} = ${n}`),o&&l(r,e`INSERT INTO ${e.identifier(f)} (${e.identifier(ee)}, ${e.identifier(q)}) VALUES (${ne(o,d)}, ${n})`)}},W=(i,n,o)=>{const c=h.tables[i]?.geoIndexes;if(!(!c||c.length===0))for(const a of c){const d=ae(i,a.name);l(r,e`DELETE FROM ${e.identifier(d)} WHERE ${e.identifier("__id__")} = ${n}`);const f=o?.[a.field];if(f!==null&&typeof f=="object"&&typeof f.lat=="number"&&typeof f.lng=="number"){const{lat:_,lng:s}=f,$=se({lat:_,lng:s},a.precision??$e);l(r,e`INSERT INTO ${e.identifier(d)} (${e.identifier("__id__")}, ${e.identifier("__geohash__")}, ${e.identifier("__lat__")}, ${e.identifier("__lng__")}) VALUES (${n}, ${$}, ${_}, ${s})`)}}};return{ensureBackfilledForTable:k,ensureBackfilledIndex:w,ensureRankBackfilled:v,ensureRankBackfilledForTable:X,syncAggregates:R,syncCompanionsForInsert:(i,n,o)=>{j(i,n,o),W(i,n,o),R(i,void 0,o),B(i,n,void 0,o),p(i,n),y(i,n,"insert",o),I({key:n,op:"insert",row:o,table:i})},syncGeo:W,syncRanks:B,syncSearch:j}};export{Re as createCompanionSync};