@lunora/shard-engine 1.0.0-alpha.26 → 1.0.0-alpha.27

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-CvdzORsy.mjs";export{t as defineEngineContractSuite};
1
+ import{defineEngineContractSuite as t}from"../packem_shared/defineEngineContractSuite-ClCoUG6r.mjs";export{t as defineEngineContractSuite};
package/dist/index.d.mts CHANGED
@@ -932,6 +932,12 @@ interface RankPageComputation {
932
932
  }
933
933
  declare const hydrateDocsById: (deps: RankPageDeps, tableName: string, ids: ReadonlyArray<string>) => Map<string, Record<string, unknown>>;
934
934
  declare const computeRankPage: (deps: RankPageDeps, tableName: string, indexName: string, rankPageOptions: RankPageOptions) => RankPageComputation;
935
+ declare const SHAPE_POKE_CURSOR_TABLE = "__shape_poke_cursor";
936
+ declare const migrateShapePokeCursor: (sql: SqlExec) => void;
937
+ declare const readShapePokeCursor: (sql: SqlExec, connectionId: string, subId: string) => number | undefined;
938
+ declare const writeShapePokeCursor: (sql: SqlExec, connectionId: string, subId: string, cursor: number) => void;
939
+ declare const deleteShapePokeCursor: (sql: SqlExec, connectionId: string, subId: string) => void;
940
+ declare const deleteShapePokeCursorsForConnection: (sql: SqlExec, connectionId: string) => void;
935
941
  declare const DATA_MIGRATION_STATE_TABLE = "__lunora_migrations";
936
942
  type MigrationDirection = "down" | "up";
937
943
  type MigrationStatus = "completed" | "failed" | "in_progress";
@@ -2138,4 +2144,4 @@ interface WhereSqlStrategy {
2138
2144
  }
2139
2145
  declare const literalInList: (reference: SQL, items: ReadonlyArray<unknown>, negated: boolean) => SQL;
2140
2146
  declare const compileWhereSql: (where: WhereInput | undefined, strategy: WhereSqlStrategy) => SQL | undefined;
2141
- 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 CrossShardReadArgs, 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 DurableAttachDecision, type DurableStreamAttach, type DurableStreamRun, DurableStreamRunner, type DurableStreamSink, 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 GeoScoredDocument, 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_DURABLE_STREAM_BYTES, MAX_DURABLE_STREAM_CHUNKS, 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, REPROJECTION_MIGRATION_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 ReplicaFollowerHost, type ReplicaOwnerHost, type ReplicaReadiness, 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 ScoredDocument, type SearchFilterBuilderLike, type SearchIndexDefinitionLike, type SearchScoredDocument, type SelectMatchingIdsOptions, type ServerDefaultContextLike, type SettingEntry, type SettingKind, type SettingsResult, type ShapePokePart, type ShapeRow, type ShapeRowOp, type ShapeSubscriptionQuery, type ShardRankPageResult, ShardRunner, type ShardRunnerOptions, type ShardSiblingHost, 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 TablesIndexesResult, 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, appendStreamChunk, applyCdcChanges, applyOnDelete, applySelect, armRestore, assertFlatPredicate, assertReadonly, assertShapeShardable, assertValidClientId, awaitWsDrain, backfillAggregateIndexes, backfillRankIndexes, backfillSearchIndexes, backfillSearchIndexesForTable, boundingBoxCenter, boundingBoxGeohashes, buildIndexRange, buildPokeFrames, buildReprojectionMigration, buildSeekBeforeWhere, buildSeekWhere, buildSettings, bumpCdcEpoch, claimStreamRun, clampPromotionThresholds, clearCapturedMail, clearQueueMessages, coerceAggregateNumber, compileWhereSql, computeRankPage, containsRelationPredicate, countLegacyRows, coveringGeohashes, createCompanionSync, createDependencyTracker, createFanoutCounters, createIndexSql, createReadFootprint, createRelayLink, createReplicaLink, createShardCtxDb, createSystemReader, decideDurableAttach, decodeCursor, deleteGlobalShapeSnapshot, deleteGlobalShapeSnapshotsForConnection, deleteStreamRun, depKey, diffExternalSource, diffGlobalMembership, distinctValues, encodeAggregateKey, encodeCursor, encodeGeohash, encodePartitionKey, encodeRowsPatch, ensureAuditTable, ensureMailTable, exportShardRows, exportShardTable, facetColumn, fanOutScalarCounts, findStorageReferences, finishStreamRun, foldAggregateTally, gateReplicaDispatch, geoTableName, guardWriter, handleReplicaControl, hasTrigger, haversineMeters, hydrateDocsById, importShardRows, indexKeysForRow, isDevEnvironment, isFtsAvailable, isLossyBody, isRelationPredicate, isSoftDeleted, isSourceDue, jsonPath, jsonPathSql, keysTouchRanges, liftSourceId, lintReadonlySql, listTables, literalInList, matchesRankStaticWhere, matchesStaticWhere, materializeExternalRows, materializeExternalRowsIncremental, mergeChangedKeys, mergeWhere, migrateCdcLog, migrateCdcMeta, migrateClientWatermark, migrateDurableStreams, 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, readStreamChunks, readStreamRun, readTablePage, recordCapturedMail, recordChangedKeys, recordFanoutPass, recordQueueMessages, recordSchemaVersion, relationHooks, relayCountFor, renderSql, reprojectableFields, reprojectionMigrationId, reprojectionTables, resolveRankPartition, resolveRelationPredicates, resolveWith, rowToDocument, runDataMigration, runDrizzle, runExternalSourceTick, runReadonlySql, runRowValidators, runShardMigrations, runSocketPool, runSql, runTriggers, selectExpiredIds, selectExportTables, selectIndexForAggregate, selectIndexForCount, selectIndexForGroupBy, selectMatchingIds, selectShapeMemberIds, selectShapeRows, serializeSqlValue, shapeRoutingKey, softDeleteScope, sortColumnName, sqliteInList, stableStringify, stableWireKey, subscriptionFrames, subscriptionListDeltas, summarizeFanoutTopics, summarizeSubscriptions, tableColumns, tableFromDepKey, throwingScheduler, trimCdcChanges, trimIdempotent, trimStreamRuns, tryRowToDocument, trySendFrame, unionAll, validateImportRow, writeGlobalShapeSnapshot, writeIdempotent, writeSearchBackfillState, writeTouchesMemo };
2147
+ 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 CrossShardReadArgs, 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 DurableAttachDecision, type DurableStreamAttach, type DurableStreamRun, DurableStreamRunner, type DurableStreamSink, 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 GeoScoredDocument, 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_DURABLE_STREAM_BYTES, MAX_DURABLE_STREAM_CHUNKS, 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, REPROJECTION_MIGRATION_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 ReplicaFollowerHost, type ReplicaOwnerHost, type ReplicaReadiness, 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, SHAPE_POKE_CURSOR_TABLE, type SchedulableWorkflowReferenceLike, type ScheduledFunctionDoc, type SchedulerLike, type SchemaLike, type ScoredDocument, type SearchFilterBuilderLike, type SearchIndexDefinitionLike, type SearchScoredDocument, type SelectMatchingIdsOptions, type ServerDefaultContextLike, type SettingEntry, type SettingKind, type SettingsResult, type ShapePokePart, type ShapeRow, type ShapeRowOp, type ShapeSubscriptionQuery, type ShardRankPageResult, ShardRunner, type ShardRunnerOptions, type ShardSiblingHost, 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 TablesIndexesResult, 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, appendStreamChunk, applyCdcChanges, applyOnDelete, applySelect, armRestore, assertFlatPredicate, assertReadonly, assertShapeShardable, assertValidClientId, awaitWsDrain, backfillAggregateIndexes, backfillRankIndexes, backfillSearchIndexes, backfillSearchIndexesForTable, boundingBoxCenter, boundingBoxGeohashes, buildIndexRange, buildPokeFrames, buildReprojectionMigration, buildSeekBeforeWhere, buildSeekWhere, buildSettings, bumpCdcEpoch, claimStreamRun, clampPromotionThresholds, clearCapturedMail, clearQueueMessages, coerceAggregateNumber, compileWhereSql, computeRankPage, containsRelationPredicate, countLegacyRows, coveringGeohashes, createCompanionSync, createDependencyTracker, createFanoutCounters, createIndexSql, createReadFootprint, createRelayLink, createReplicaLink, createShardCtxDb, createSystemReader, decideDurableAttach, decodeCursor, deleteGlobalShapeSnapshot, deleteGlobalShapeSnapshotsForConnection, deleteShapePokeCursor, deleteShapePokeCursorsForConnection, deleteStreamRun, depKey, diffExternalSource, diffGlobalMembership, distinctValues, encodeAggregateKey, encodeCursor, encodeGeohash, encodePartitionKey, encodeRowsPatch, ensureAuditTable, ensureMailTable, exportShardRows, exportShardTable, facetColumn, fanOutScalarCounts, findStorageReferences, finishStreamRun, foldAggregateTally, gateReplicaDispatch, geoTableName, guardWriter, handleReplicaControl, hasTrigger, haversineMeters, hydrateDocsById, importShardRows, indexKeysForRow, isDevEnvironment, isFtsAvailable, isLossyBody, isRelationPredicate, isSoftDeleted, isSourceDue, jsonPath, jsonPathSql, keysTouchRanges, liftSourceId, lintReadonlySql, listTables, literalInList, matchesRankStaticWhere, matchesStaticWhere, materializeExternalRows, materializeExternalRowsIncremental, mergeChangedKeys, mergeWhere, migrateCdcLog, migrateCdcMeta, migrateClientWatermark, migrateDurableStreams, migrateGlobalShapeSnapshot, migrateIdempotency, migrateSearchState, migrateShapePokeCursor, 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, readShapePokeCursor, readStreamChunks, readStreamRun, readTablePage, recordCapturedMail, recordChangedKeys, recordFanoutPass, recordQueueMessages, recordSchemaVersion, relationHooks, relayCountFor, renderSql, reprojectableFields, reprojectionMigrationId, reprojectionTables, resolveRankPartition, resolveRelationPredicates, resolveWith, rowToDocument, runDataMigration, runDrizzle, runExternalSourceTick, runReadonlySql, runRowValidators, runShardMigrations, runSocketPool, runSql, runTriggers, selectExpiredIds, selectExportTables, selectIndexForAggregate, selectIndexForCount, selectIndexForGroupBy, selectMatchingIds, selectShapeMemberIds, selectShapeRows, serializeSqlValue, shapeRoutingKey, softDeleteScope, sortColumnName, sqliteInList, stableStringify, stableWireKey, subscriptionFrames, subscriptionListDeltas, summarizeFanoutTopics, summarizeSubscriptions, tableColumns, tableFromDepKey, throwingScheduler, trimCdcChanges, trimIdempotent, trimStreamRuns, tryRowToDocument, trySendFrame, unionAll, validateImportRow, writeGlobalShapeSnapshot, writeIdempotent, writeSearchBackfillState, writeShapePokeCursor, writeTouchesMemo };
package/dist/index.d.ts CHANGED
@@ -932,6 +932,12 @@ interface RankPageComputation {
932
932
  }
933
933
  declare const hydrateDocsById: (deps: RankPageDeps, tableName: string, ids: ReadonlyArray<string>) => Map<string, Record<string, unknown>>;
934
934
  declare const computeRankPage: (deps: RankPageDeps, tableName: string, indexName: string, rankPageOptions: RankPageOptions) => RankPageComputation;
935
+ declare const SHAPE_POKE_CURSOR_TABLE = "__shape_poke_cursor";
936
+ declare const migrateShapePokeCursor: (sql: SqlExec) => void;
937
+ declare const readShapePokeCursor: (sql: SqlExec, connectionId: string, subId: string) => number | undefined;
938
+ declare const writeShapePokeCursor: (sql: SqlExec, connectionId: string, subId: string, cursor: number) => void;
939
+ declare const deleteShapePokeCursor: (sql: SqlExec, connectionId: string, subId: string) => void;
940
+ declare const deleteShapePokeCursorsForConnection: (sql: SqlExec, connectionId: string) => void;
935
941
  declare const DATA_MIGRATION_STATE_TABLE = "__lunora_migrations";
936
942
  type MigrationDirection = "down" | "up";
937
943
  type MigrationStatus = "completed" | "failed" | "in_progress";
@@ -2138,4 +2144,4 @@ interface WhereSqlStrategy {
2138
2144
  }
2139
2145
  declare const literalInList: (reference: SQL, items: ReadonlyArray<unknown>, negated: boolean) => SQL;
2140
2146
  declare const compileWhereSql: (where: WhereInput | undefined, strategy: WhereSqlStrategy) => SQL | undefined;
2141
- 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 CrossShardReadArgs, 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 DurableAttachDecision, type DurableStreamAttach, type DurableStreamRun, DurableStreamRunner, type DurableStreamSink, 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 GeoScoredDocument, 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_DURABLE_STREAM_BYTES, MAX_DURABLE_STREAM_CHUNKS, 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, REPROJECTION_MIGRATION_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 ReplicaFollowerHost, type ReplicaOwnerHost, type ReplicaReadiness, 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 ScoredDocument, type SearchFilterBuilderLike, type SearchIndexDefinitionLike, type SearchScoredDocument, type SelectMatchingIdsOptions, type ServerDefaultContextLike, type SettingEntry, type SettingKind, type SettingsResult, type ShapePokePart, type ShapeRow, type ShapeRowOp, type ShapeSubscriptionQuery, type ShardRankPageResult, ShardRunner, type ShardRunnerOptions, type ShardSiblingHost, 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 TablesIndexesResult, 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, appendStreamChunk, applyCdcChanges, applyOnDelete, applySelect, armRestore, assertFlatPredicate, assertReadonly, assertShapeShardable, assertValidClientId, awaitWsDrain, backfillAggregateIndexes, backfillRankIndexes, backfillSearchIndexes, backfillSearchIndexesForTable, boundingBoxCenter, boundingBoxGeohashes, buildIndexRange, buildPokeFrames, buildReprojectionMigration, buildSeekBeforeWhere, buildSeekWhere, buildSettings, bumpCdcEpoch, claimStreamRun, clampPromotionThresholds, clearCapturedMail, clearQueueMessages, coerceAggregateNumber, compileWhereSql, computeRankPage, containsRelationPredicate, countLegacyRows, coveringGeohashes, createCompanionSync, createDependencyTracker, createFanoutCounters, createIndexSql, createReadFootprint, createRelayLink, createReplicaLink, createShardCtxDb, createSystemReader, decideDurableAttach, decodeCursor, deleteGlobalShapeSnapshot, deleteGlobalShapeSnapshotsForConnection, deleteStreamRun, depKey, diffExternalSource, diffGlobalMembership, distinctValues, encodeAggregateKey, encodeCursor, encodeGeohash, encodePartitionKey, encodeRowsPatch, ensureAuditTable, ensureMailTable, exportShardRows, exportShardTable, facetColumn, fanOutScalarCounts, findStorageReferences, finishStreamRun, foldAggregateTally, gateReplicaDispatch, geoTableName, guardWriter, handleReplicaControl, hasTrigger, haversineMeters, hydrateDocsById, importShardRows, indexKeysForRow, isDevEnvironment, isFtsAvailable, isLossyBody, isRelationPredicate, isSoftDeleted, isSourceDue, jsonPath, jsonPathSql, keysTouchRanges, liftSourceId, lintReadonlySql, listTables, literalInList, matchesRankStaticWhere, matchesStaticWhere, materializeExternalRows, materializeExternalRowsIncremental, mergeChangedKeys, mergeWhere, migrateCdcLog, migrateCdcMeta, migrateClientWatermark, migrateDurableStreams, 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, readStreamChunks, readStreamRun, readTablePage, recordCapturedMail, recordChangedKeys, recordFanoutPass, recordQueueMessages, recordSchemaVersion, relationHooks, relayCountFor, renderSql, reprojectableFields, reprojectionMigrationId, reprojectionTables, resolveRankPartition, resolveRelationPredicates, resolveWith, rowToDocument, runDataMigration, runDrizzle, runExternalSourceTick, runReadonlySql, runRowValidators, runShardMigrations, runSocketPool, runSql, runTriggers, selectExpiredIds, selectExportTables, selectIndexForAggregate, selectIndexForCount, selectIndexForGroupBy, selectMatchingIds, selectShapeMemberIds, selectShapeRows, serializeSqlValue, shapeRoutingKey, softDeleteScope, sortColumnName, sqliteInList, stableStringify, stableWireKey, subscriptionFrames, subscriptionListDeltas, summarizeFanoutTopics, summarizeSubscriptions, tableColumns, tableFromDepKey, throwingScheduler, trimCdcChanges, trimIdempotent, trimStreamRuns, tryRowToDocument, trySendFrame, unionAll, validateImportRow, writeGlobalShapeSnapshot, writeIdempotent, writeSearchBackfillState, writeTouchesMemo };
2147
+ 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 CrossShardReadArgs, 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 DurableAttachDecision, type DurableStreamAttach, type DurableStreamRun, DurableStreamRunner, type DurableStreamSink, 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 GeoScoredDocument, 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_DURABLE_STREAM_BYTES, MAX_DURABLE_STREAM_CHUNKS, 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, REPROJECTION_MIGRATION_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 ReplicaFollowerHost, type ReplicaOwnerHost, type ReplicaReadiness, 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, SHAPE_POKE_CURSOR_TABLE, type SchedulableWorkflowReferenceLike, type ScheduledFunctionDoc, type SchedulerLike, type SchemaLike, type ScoredDocument, type SearchFilterBuilderLike, type SearchIndexDefinitionLike, type SearchScoredDocument, type SelectMatchingIdsOptions, type ServerDefaultContextLike, type SettingEntry, type SettingKind, type SettingsResult, type ShapePokePart, type ShapeRow, type ShapeRowOp, type ShapeSubscriptionQuery, type ShardRankPageResult, ShardRunner, type ShardRunnerOptions, type ShardSiblingHost, 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 TablesIndexesResult, 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, appendStreamChunk, applyCdcChanges, applyOnDelete, applySelect, armRestore, assertFlatPredicate, assertReadonly, assertShapeShardable, assertValidClientId, awaitWsDrain, backfillAggregateIndexes, backfillRankIndexes, backfillSearchIndexes, backfillSearchIndexesForTable, boundingBoxCenter, boundingBoxGeohashes, buildIndexRange, buildPokeFrames, buildReprojectionMigration, buildSeekBeforeWhere, buildSeekWhere, buildSettings, bumpCdcEpoch, claimStreamRun, clampPromotionThresholds, clearCapturedMail, clearQueueMessages, coerceAggregateNumber, compileWhereSql, computeRankPage, containsRelationPredicate, countLegacyRows, coveringGeohashes, createCompanionSync, createDependencyTracker, createFanoutCounters, createIndexSql, createReadFootprint, createRelayLink, createReplicaLink, createShardCtxDb, createSystemReader, decideDurableAttach, decodeCursor, deleteGlobalShapeSnapshot, deleteGlobalShapeSnapshotsForConnection, deleteShapePokeCursor, deleteShapePokeCursorsForConnection, deleteStreamRun, depKey, diffExternalSource, diffGlobalMembership, distinctValues, encodeAggregateKey, encodeCursor, encodeGeohash, encodePartitionKey, encodeRowsPatch, ensureAuditTable, ensureMailTable, exportShardRows, exportShardTable, facetColumn, fanOutScalarCounts, findStorageReferences, finishStreamRun, foldAggregateTally, gateReplicaDispatch, geoTableName, guardWriter, handleReplicaControl, hasTrigger, haversineMeters, hydrateDocsById, importShardRows, indexKeysForRow, isDevEnvironment, isFtsAvailable, isLossyBody, isRelationPredicate, isSoftDeleted, isSourceDue, jsonPath, jsonPathSql, keysTouchRanges, liftSourceId, lintReadonlySql, listTables, literalInList, matchesRankStaticWhere, matchesStaticWhere, materializeExternalRows, materializeExternalRowsIncremental, mergeChangedKeys, mergeWhere, migrateCdcLog, migrateCdcMeta, migrateClientWatermark, migrateDurableStreams, migrateGlobalShapeSnapshot, migrateIdempotency, migrateSearchState, migrateShapePokeCursor, 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, readShapePokeCursor, readStreamChunks, readStreamRun, readTablePage, recordCapturedMail, recordChangedKeys, recordFanoutPass, recordQueueMessages, recordSchemaVersion, relationHooks, relayCountFor, renderSql, reprojectableFields, reprojectionMigrationId, reprojectionTables, resolveRankPartition, resolveRelationPredicates, resolveWith, rowToDocument, runDataMigration, runDrizzle, runExternalSourceTick, runReadonlySql, runRowValidators, runShardMigrations, runSocketPool, runSql, runTriggers, selectExpiredIds, selectExportTables, selectIndexForAggregate, selectIndexForCount, selectIndexForGroupBy, selectMatchingIds, selectShapeMemberIds, selectShapeRows, serializeSqlValue, shapeRoutingKey, softDeleteScope, sortColumnName, sqliteInList, stableStringify, stableWireKey, subscriptionFrames, subscriptionListDeltas, summarizeFanoutTopics, summarizeSubscriptions, tableColumns, tableFromDepKey, throwingScheduler, trimCdcChanges, trimIdempotent, trimStreamRuns, tryRowToDocument, trySendFrame, unionAll, validateImportRow, writeGlobalShapeSnapshot, writeIdempotent, writeSearchBackfillState, writeShapePokeCursor, 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 s,validateImportRow as i}from"./packem_shared/exportShardRows-Bbi_JGfn.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-CTo0-9iZ.mjs";import{aggregateTableName as f,coerceAggregateNumber as T,encodeAggregateKey as A,foldAggregateTally as E,readAggregateValue as g}from"./packem_shared/aggregateTableName-DN7gk6uh.mjs";import{CountRlsUnsupportedError as R,mergeWhere as I,planAggregateLookup as C,selectIndexForAggregate as _,selectIndexForCount as L,selectIndexForGroupBy as b}from"./packem_shared/CountRlsUnsupportedError-8BqPYQoP.mjs";import{AUDIT_LOG_TABLE as N,appendAuditEntry as y,ensureAuditTable as D,readAuditLog as O}from"./packem_shared/AUDIT_LOG_TABLE-Bl2mYtAQ.mjs";import{NotUniqueError as k,assertValidClientId as P,createShardCtxDb as B,normalizeIdStructurally as G}from"./packem_shared/NotUniqueError-DYo7r67J.mjs";import{backfillAggregateIndexes as w,backfillRankIndexes as K,backfillSearchIndexes as q,backfillSearchIndexesForTable as W}from"./packem_shared/backfillAggregateIndexes-DTOIsYbi.mjs";import{CDC_LOG_TABLE as z,CDC_META_TABLE as X,appendCdcChange as H,applyCdcChanges as V,bumpCdcEpoch as Y,migrateCdcLog as j,migrateCdcMeta as Q,minCdcSeq as J,readCdcChanges as Z,readCdcCursor as $,readCdcEpoch as ee,trimCdcChanges as re}from"./packem_shared/CDC_LOG_TABLE-DNFFQwF_.mjs";import{CLIENT_WATERMARK_TABLE as ae,advanceClientWatermark as te,migrateClientWatermark as ne,readClientWatermark as le}from"./packem_shared/CLIENT_WATERMARK_TABLE-LrKfdxyt.mjs";import{S as ie}from"./packem_shared/ctx-db-companions-BJlCofon.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-B2LKe4KU.mjs";import{IDEMPOTENCY_TABLE as Te,migrateIdempotency as Ae,readIdempotent as Ee,trimIdempotent as ge,writeIdempotent as he}from"./packem_shared/IDEMPOTENCY_TABLE-tQ5mnqvw.mjs";import{computeRankPage as Ie,hydrateDocsById as Ce}from"./packem_shared/computeRankPage-BU8LXvQs.mjs";import{SEARCH_STATE_TABLE as Le,migrateSearchState as be,readSearchBackfillState as Me,writeSearchBackfillState as Ne}from"./packem_shared/SEARCH_STATE_TABLE-DRk_SB72.mjs";import{selectShapeMemberIds as De,selectShapeRows as Oe}from"./packem_shared/selectShapeMemberIds-Bkkug6vU.mjs";import{DATA_MIGRATION_STATE_TABLE as ke,readMigrationStatus as Pe,runDataMigration as Be}from"./packem_shared/DATA_MIGRATION_STATE_TABLE-DIQTu___.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-C3n5gJsk.mjs";import{T as He,c as Ve,p as Ye,a as je,A as Qe,y as Je,h as Ze,C as $e,_ as er,N as rr,S as or,O as ar,E as tr,I as nr,D as lr}from"./packem_shared/do-sql-DKSFK627.mjs";import{param as ir,renderSql as mr,sqliteInList as pr,unionAll as dr}from"./packem_shared/param-CYxL68V-.mjs";import{appendStreamChunk as Sr,claimStreamRun as ur,deleteStreamRun as xr,finishStreamRun as fr,migrateDurableStreams as Tr,readStreamChunks as Ar,readStreamRun as Er,trimStreamRuns as gr}from"./packem_shared/appendStreamChunk-ksZYy1hZ.mjs";import{DurableStreamRunner as Rr,MAX_DURABLE_STREAM_BYTES as Ir,MAX_DURABLE_STREAM_CHUNKS as Cr,decideDurableAttach as _r}from"./packem_shared/DurableStreamRunner-B54Jt9Iu.mjs";import{diffExternalSource as br}from"./packem_shared/diffExternalSource-DMpkJta1.mjs";import{liftSourceId as Nr,normalizeSourceDocument as yr,normalizeSourceValue as Dr}from"./packem_shared/liftSourceId-DApAbu7Q.mjs";import{materializeExternalRows as Fr,materializeExternalRowsIncremental as kr,readExternalSourceBaseline as Pr,runExternalSourceTick as Br}from"./packem_shared/materializeExternalRows-C-5TKdc1.mjs";import{isSoftDeleted as Ur,isSourceDue as wr,pullExternalSourceIncrementalTick as Kr,pullExternalSourceTick as qr}from"./packem_shared/isSoftDeleted-DyEJueIu.mjs";import{GEO_DEFAULT_PRECISION as vr,boundingBoxCenter as zr,boundingBoxGeohashes as Xr,coveringGeohashes as Hr,encodeGeohash as Vr,haversineMeters as Yr,pointInBoundingBox as jr}from"./packem_shared/GEO_DEFAULT_PRECISION-DyI5zggj.mjs";import{ADMIN_FUNCTIONS as Jr,ADMIN_FUNCTION_PREFIX as Zr,DEFAULT_FANOUT_TOPIC_LIMIT as $r,FLAGS_FUNCTION_PREFIX as eo,MAX_PAGE_SIZE as ro,RELATION_FUNCTION_PREFIX as oo,createFanoutCounters as ao,facetColumn as to,findStorageReferences as no,listTables as lo,readTablePage as so,recordFanoutPass as io,selectMatchingIds as mo,summarizeFanoutTopics as po,summarizeSubscriptions as co}from"./packem_shared/ADMIN_FUNCTIONS-Cj1pJjVg.mjs";import{MAIL_RETENTION as uo,MAIL_TABLE as xo,clearCapturedMail as fo,ensureMailTable as To,readCapturedMail as Ao,recordCapturedMail as Eo}from"./packem_shared/MAIL_RETENTION-CzZuX9bd.mjs";import{NotFoundError as ho}from"./packem_shared/NotFoundError-BhF7FeFr.mjs";import{armRestore as Io,readBookmark as Co}from"./packem_shared/armRestore-BNzdvQ_o.mjs";import{applySelect as Lo,buildSeekBeforeWhere as bo,buildSeekWhere as Mo,decodeCursor as No,encodeCursor as yo,normalizeOrderKeys as Do,softDeleteScope as Oo}from"./packem_shared/applySelect-5w13bMAR.mjs";import{QUEUE_TABLE as ko,clearQueueMessages as Po,isLossyBody as Bo,readQueueMessageById as Go,readQueueMessages as Uo,recordQueueMessages as wo}from"./packem_shared/QUEUE_TABLE-BX0nopuT.mjs";import{RANK_TIEBREAK as qo,encodePartitionKey as Wo,matchesRankStaticWhere as vo,rankKeyFromDoc as zo,rankTableName as Xo,resolveRankPartition as Ho,sortColumnName as Vo}from"./packem_shared/RANK_TIEBREAK-BGk411OR.mjs";import{ReactiveCache as jo,reactiveCacheKey as Qo}from"./packem_shared/ReactiveCache-D_T10KLy.mjs";import{createReadFootprint as Zo}from"./packem_shared/createReadFootprint-DIrrxRTE.mjs";import{buildIndexRange as ea,indexKeysForRow as ra,keysTouchRanges as oa}from"./packem_shared/buildIndexRange-DFsdtPjD.mjs";import{DEFAULT_MAX_RELATION_KEYS as ta,assertFlatPredicate as na,assertShapeShardable as la,containsRelationPredicate as sa,isRelationPredicate as ia,resolveRelationPredicates as ma}from"./packem_shared/DEFAULT_MAX_RELATION_KEYS-BV1RCoat.mjs";import{applyOnDelete as da,distinctValues as ca,fanOutScalarCounts as Sa,relationHooks as ua,resolveWith as xa,runRowValidators as fa}from"./packem_shared/applyOnDelete-crbAzVfE.mjs";import{DEFAULT_PROMOTION_THRESHOLDS as Aa,clampPromotionThresholds as Ea,nextPromotionState as ga,relayCountFor as ha,shapeRoutingKey as Ra}from"./packem_shared/DEFAULT_PROMOTION_THRESHOLDS-DYGNAo1I.mjs";import{DEFAULT_MAX_RELAYS as Ca,OwnerRelay as _a,RelayMember as La,createRelayLink as ba}from"./packem_shared/DEFAULT_MAX_RELAYS-Cinp9pPC.mjs";import{createReplicaLink as Na,gateReplicaDispatch as ya,handleReplicaControl as Da}from"./packem_shared/createReplicaLink-BMNW0SX6.mjs";import{buildReprojectionMigration as Fa,countLegacyRows as ka,reprojectableFields as Pa,reprojectionTables as Ba}from"./packem_shared/buildReprojectionMigration-JUwsTNTB.mjs";import{RLS_UNWRAP_SYMBOL as Ua,RlsRequiredError as wa,guardWriter as Ka}from"./packem_shared/RLS_UNWRAP_SYMBOL-DcqORh2s.mjs";import{SCHEMA_HISTORY_MAX_VERSIONS as Wa,readSchemaHistory as va,readSchemaVersion as za,recordSchemaVersion as Xa}from"./packem_shared/SCHEMA_HISTORY_MAX_VERSIONS-CEK7b_7v.mjs";import{serializeSqlValue as Va}from"./packem_shared/serializeSqlValue-BR4UOWoP.mjs";import{buildSettings as ja,isDevEnvironment as Qa}from"./packem_shared/buildSettings-COIJsw7a.mjs";import{buildPokeFrames as Za,diffGlobalMembership as $a,encodeRowsPatch as et,projectColumns as rt}from"./packem_shared/buildPokeFrames-DmB-FBeQ.mjs";import{ShardRunner as at}from"./packem_shared/ShardRunner-DIqVdWtk.mjs";import{runSocketPool as nt}from"./packem_shared/runSocketPool-DPQLVyWF.mjs";import{MAX_SQL_ROWS as st,assertReadonly as it,lintReadonlySql as mt,runReadonlySql as pt}from"./packem_shared/MAX_SQL_ROWS-nMwkxv5f.mjs";import{awaitWsDrain as ct,subscriptionFrames as St,subscriptionListDeltas as ut,trySendFrame as xt}from"./packem_shared/awaitWsDrain-PT9o0d6J.mjs";import{mergeChangedKeys as Tt,recordChangedKeys as At,writeTouchesMemo as Et}from"./packem_shared/mergeChangedKeys-BXtUgIPW.mjs";import{createSystemReader as ht}from"./packem_shared/createSystemReader-DcDcrtM3.mjs";import{ConflictError as It}from"./packem_shared/ConflictError-C8GtJmjS.mjs";import{DEFAULT_TRANSACTION_LIMITS as _t,TransactionHeadroomTracker as Lt}from"./packem_shared/DEFAULT_TRANSACTION_LIMITS-DLUzZbta.mjs";import{hasTrigger as Mt,runTriggers as Nt}from"./packem_shared/hasTrigger-CbkOHExZ.mjs";import{selectExpiredIds as Dt}from"./packem_shared/selectExpiredIds-C4Ry_NxG.mjs";import{compileWhereSql as Ft,literalInList as kt}from"./packem_shared/compileWhereSql-B3hq_v98.mjs";import{RELATION_EXISTS_KEY as Bt}from"./packem_shared/RELATION_EXISTS_KEY-BaqSIFU1.mjs";import{REPROJECTION_MIGRATION_PREFIX as Ut,reprojectionMigrationId as wt}from"./packem_shared/REPROJECTION_MIGRATION_PREFIX-D2dltRFC.mjs";import{quoteIdentifier as qt}from"./packem_shared/quoteIdentifier-CObIFRhb.mjs";import{runShardMigrations as vt}from"./packem_shared/runShardMigrations-BCuK60KT.mjs";import{stableStringify as Xt}from"./packem_shared/stableStringify-BjLh4gvA.mjs";import{stableWireKey as Vt}from"./packem_shared/stableWireKey-Diuu1gGc.mjs";export{Jr as ADMIN_FUNCTIONS,Zr as ADMIN_FUNCTION_PREFIX,p as AGGREGATE_SQL_FUNCTION,He as AGG_COUNT,Ve as AGG_KEY,Ye as AGG_VALUE,N as AUDIT_LOG_TABLE,z as CDC_LOG_TABLE,X as CDC_META_TABLE,ae as CLIENT_WATERMARK_TABLE,It as ConflictError,R as CountRlsUnsupportedError,ke as DATA_MIGRATION_STATE_TABLE,$r as DEFAULT_FANOUT_TOPIC_LIMIT,ta as DEFAULT_MAX_RELATION_KEYS,Ca as DEFAULT_MAX_RELAYS,Aa as DEFAULT_PROMOTION_THRESHOLDS,_t as DEFAULT_TRANSACTION_LIMITS,je as DOC_COLUMN,Rr as DurableStreamRunner,eo as FLAGS_FUNCTION_PREFIX,vr as GEO_DEFAULT_PRECISION,pe as GLOBAL_SHAPE_SNAPSHOT_TABLE,Te as IDEMPOTENCY_TABLE,uo as MAIL_RETENTION,xo as MAIL_TABLE,Ir as MAX_DURABLE_STREAM_BYTES,Cr as MAX_DURABLE_STREAM_CHUNKS,ro as MAX_PAGE_SIZE,st as MAX_SQL_ROWS,ho as NotFoundError,k as NotUniqueError,_a as OwnerRelay,ko as QUEUE_TABLE,qo as RANK_TIEBREAK,Bt as RELATION_EXISTS_KEY,oo as RELATION_FUNCTION_PREFIX,Ut as REPROJECTION_MIGRATION_PREFIX,Ua as RLS_UNWRAP_SYMBOL,jo as ReactiveCache,La as RelayMember,wa as RlsRequiredError,Ue as SCAN_DEP,Wa as SCHEMA_HISTORY_MAX_VERSIONS,Le as SEARCH_STATE_TABLE,at as ShardRunner,Lt as TransactionHeadroomTracker,te as advanceClientWatermark,Qe as aggUpsertSql,d as aggregateSqlFunction,f as aggregateTableName,y as appendAuditEntry,H as appendCdcChange,Sr as appendStreamChunk,V as applyCdcChanges,da as applyOnDelete,Lo as applySelect,Io as armRestore,na as assertFlatPredicate,it as assertReadonly,la as assertShapeShardable,P as assertValidClientId,ct as awaitWsDrain,w as backfillAggregateIndexes,K as backfillRankIndexes,q as backfillSearchIndexes,W as backfillSearchIndexesForTable,zr as boundingBoxCenter,Xr as boundingBoxGeohashes,ea as buildIndexRange,Za as buildPokeFrames,Fa as buildReprojectionMigration,bo as buildSeekBeforeWhere,Mo as buildSeekWhere,ja as buildSettings,Y as bumpCdcEpoch,ur as claimStreamRun,Ea as clampPromotionThresholds,fo as clearCapturedMail,Po as clearQueueMessages,T as coerceAggregateNumber,Ft as compileWhereSql,Ie as computeRankPage,sa as containsRelationPredicate,ka as countLegacyRows,Hr as coveringGeohashes,ie as createCompanionSync,we as createDependencyTracker,ao as createFanoutCounters,Je as createIndexSql,Zo as createReadFootprint,ba as createRelayLink,Na as createReplicaLink,B as createShardCtxDb,ht as createSystemReader,_r as decideDurableAttach,No as decodeCursor,de as deleteGlobalShapeSnapshot,ce as deleteGlobalShapeSnapshotsForConnection,xr as deleteStreamRun,Ke as depKey,br as diffExternalSource,$a as diffGlobalMembership,ca as distinctValues,A as encodeAggregateKey,yo as encodeCursor,Vr as encodeGeohash,Wo as encodePartitionKey,et as encodeRowsPatch,D as ensureAuditTable,To as ensureMailTable,o as exportShardRows,a as exportShardTable,to as facetColumn,Sa as fanOutScalarCounts,no as findStorageReferences,fr as finishStreamRun,E as foldAggregateTally,ya as gateReplicaDispatch,Ze as geoTableName,Ka as guardWriter,Da as handleReplicaControl,Mt as hasTrigger,Yr as haversineMeters,Ce as hydrateDocsById,t as importShardRows,ra as indexKeysForRow,Qa as isDevEnvironment,$e as isFtsAvailable,Bo as isLossyBody,ia as isRelationPredicate,Ur as isSoftDeleted,wr as isSourceDue,er as jsonPath,rr as jsonPathSql,oa as keysTouchRanges,Nr as liftSourceId,mt as lintReadonlySql,lo as listTables,kt as literalInList,vo as matchesRankStaticWhere,c as matchesStaticWhere,Fr as materializeExternalRows,kr as materializeExternalRowsIncremental,Tt as mergeChangedKeys,I as mergeWhere,j as migrateCdcLog,Q as migrateCdcMeta,ne as migrateClientWatermark,Tr as migrateDurableStreams,Se as migrateGlobalShapeSnapshot,Ae as migrateIdempotency,be as migrateSearchState,J as minCdcSeq,ga as nextPromotionState,S as normalizeCountArgument,G as normalizeIdStructurally,Do as normalizeOrderKeys,yr as normalizeSourceDocument,Dr as normalizeSourceValue,ir as param,n as parseExportShardArgs,l as parseImportShardArgs,C as planAggregateLookup,jr as pointInBoundingBox,rt as projectColumns,Kr as pullExternalSourceIncrementalTick,qr as pullExternalSourceTick,or as qualifiedJsonPath,ar as qualifiedJsonPathSql,qt as quoteIdentifier,zo as rankKeyFromDoc,Xo as rankTableName,Qo as reactiveCacheKey,g as readAggregateValue,O as readAuditLog,Co as readBookmark,Ao as readCapturedMail,Z as readCdcChanges,$ as readCdcCursor,ee as readCdcEpoch,le as readClientWatermark,Pr as readExternalSourceBaseline,ue as readGlobalShapeSnapshot,Ee as readIdempotent,Pe as readMigrationStatus,Go as readQueueMessageById,Uo as readQueueMessages,va as readSchemaHistory,za as readSchemaVersion,Me as readSearchBackfillState,Ar as readStreamChunks,Er as readStreamRun,so as readTablePage,Eo as recordCapturedMail,At as recordChangedKeys,io as recordFanoutPass,wo as recordQueueMessages,Xa as recordSchemaVersion,ua as relationHooks,ha as relayCountFor,mr as renderSql,Pa as reprojectableFields,wt as reprojectionMigrationId,Ba as reprojectionTables,Ho as resolveRankPartition,ma as resolveRelationPredicates,xa as resolveWith,tr as rowToDocument,Be as runDataMigration,ve as runDrizzle,Br as runExternalSourceTick,pt as runReadonlySql,fa as runRowValidators,vt as runShardMigrations,nt as runSocketPool,ze as runSql,Nt as runTriggers,Dt as selectExpiredIds,s as selectExportTables,_ as selectIndexForAggregate,L as selectIndexForCount,b as selectIndexForGroupBy,mo as selectMatchingIds,De as selectShapeMemberIds,Oe as selectShapeRows,Va as serializeSqlValue,Ra as shapeRoutingKey,Oo as softDeleteScope,Vo as sortColumnName,pr as sqliteInList,Xt as stableStringify,Vt as stableWireKey,St as subscriptionFrames,ut as subscriptionListDeltas,po as summarizeFanoutTopics,co as summarizeSubscriptions,nr as tableColumns,qe as tableFromDepKey,u as throwingScheduler,re as trimCdcChanges,ge as trimIdempotent,gr as trimStreamRuns,lr as tryRowToDocument,xt as trySendFrame,dr as unionAll,i as validateImportRow,xe as writeGlobalShapeSnapshot,he as writeIdempotent,Ne as writeSearchBackfillState,Et as writeTouchesMemo};
1
+ import{exportShardRows as o,exportShardTable as a,importShardRows as t,parseExportShardArgs as n,parseImportShardArgs as s,selectExportTables as i,validateImportRow as l}from"./packem_shared/exportShardRows-Bbi_JGfn.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-CTo0-9iZ.mjs";import{aggregateTableName as f,coerceAggregateNumber as h,encodeAggregateKey as A,foldAggregateTally as E,readAggregateValue as T}from"./packem_shared/aggregateTableName-DN7gk6uh.mjs";import{CountRlsUnsupportedError as R,mergeWhere as C,planAggregateLookup as _,selectIndexForAggregate as I,selectIndexForCount as L,selectIndexForGroupBy as b}from"./packem_shared/CountRlsUnsupportedError-8BqPYQoP.mjs";import{AUDIT_LOG_TABLE as N,appendAuditEntry as y,ensureAuditTable as O,readAuditLog as D}from"./packem_shared/AUDIT_LOG_TABLE-Bl2mYtAQ.mjs";import{NotUniqueError as P,assertValidClientId as k,createShardCtxDb as B,normalizeIdStructurally as G}from"./packem_shared/NotUniqueError-BlrEp5pr.mjs";import{backfillAggregateIndexes as w,backfillRankIndexes as K,backfillSearchIndexes as q,backfillSearchIndexesForTable as W}from"./packem_shared/backfillAggregateIndexes-DTOIsYbi.mjs";import{CDC_LOG_TABLE as z,CDC_META_TABLE as H,appendCdcChange as X,applyCdcChanges as V,bumpCdcEpoch as Y,migrateCdcLog as j,migrateCdcMeta as Q,minCdcSeq as J,readCdcChanges as Z,readCdcCursor as $,readCdcEpoch as ee,trimCdcChanges as re}from"./packem_shared/CDC_LOG_TABLE-DNFFQwF_.mjs";import{CLIENT_WATERMARK_TABLE as ae,advanceClientWatermark as te,migrateClientWatermark as ne,readClientWatermark as se}from"./packem_shared/CLIENT_WATERMARK_TABLE-LrKfdxyt.mjs";import{S as le}from"./packem_shared/ctx-db-companions-BJlCofon.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-B2LKe4KU.mjs";import{IDEMPOTENCY_TABLE as he,migrateIdempotency as Ae,readIdempotent as Ee,trimIdempotent as Te,writeIdempotent as ge}from"./packem_shared/IDEMPOTENCY_TABLE-tQ5mnqvw.mjs";import{computeRankPage as Ce,hydrateDocsById as _e}from"./packem_shared/computeRankPage-BU8LXvQs.mjs";import{SEARCH_STATE_TABLE as Le,migrateSearchState as be,readSearchBackfillState as Me,writeSearchBackfillState as Ne}from"./packem_shared/SEARCH_STATE_TABLE-DRk_SB72.mjs";import{SHAPE_POKE_CURSOR_TABLE as Oe,deleteShapePokeCursor as De,deleteShapePokeCursorsForConnection as Fe,migrateShapePokeCursor as Pe,readShapePokeCursor as ke,writeShapePokeCursor as Be}from"./packem_shared/SHAPE_POKE_CURSOR_TABLE-pybVwKps.mjs";import{selectShapeMemberIds as Ue,selectShapeRows as we}from"./packem_shared/selectShapeMemberIds-Bkkug6vU.mjs";import{DATA_MIGRATION_STATE_TABLE as qe,readMigrationStatus as We,runDataMigration as ve}from"./packem_shared/DATA_MIGRATION_STATE_TABLE-DIQTu___.mjs";import{SCAN_DEP as He,createDependencyTracker as Xe,depKey as Ve,tableFromDepKey as Ye}from"./packem_shared/SCAN_DEP-D_yR9EeV.mjs";import{runDrizzle as Qe,runSql as Je}from"./packem_shared/runDrizzle-C3n5gJsk.mjs";import{T as $e,c as er,p as rr,a as or,A as ar,y as tr,h as nr,C as sr,_ as ir,N as lr,S as mr,O as pr,E as dr,I as cr,D as Sr}from"./packem_shared/do-sql-DKSFK627.mjs";import{param as xr,renderSql as fr,sqliteInList as hr,unionAll as Ar}from"./packem_shared/param-CYxL68V-.mjs";import{appendStreamChunk as Tr,claimStreamRun as gr,deleteStreamRun as Rr,finishStreamRun as Cr,migrateDurableStreams as _r,readStreamChunks as Ir,readStreamRun as Lr,trimStreamRuns as br}from"./packem_shared/appendStreamChunk-ksZYy1hZ.mjs";import{DurableStreamRunner as Nr,MAX_DURABLE_STREAM_BYTES as yr,MAX_DURABLE_STREAM_CHUNKS as Or,decideDurableAttach as Dr}from"./packem_shared/DurableStreamRunner-B54Jt9Iu.mjs";import{diffExternalSource as Pr}from"./packem_shared/diffExternalSource-DMpkJta1.mjs";import{liftSourceId as Br,normalizeSourceDocument as Gr,normalizeSourceValue as Ur}from"./packem_shared/liftSourceId-DApAbu7Q.mjs";import{materializeExternalRows as Kr,materializeExternalRowsIncremental as qr,readExternalSourceBaseline as Wr,runExternalSourceTick as vr}from"./packem_shared/materializeExternalRows-C-5TKdc1.mjs";import{isSoftDeleted as Hr,isSourceDue as Xr,pullExternalSourceIncrementalTick as Vr,pullExternalSourceTick as Yr}from"./packem_shared/isSoftDeleted-DyEJueIu.mjs";import{GEO_DEFAULT_PRECISION as Qr,boundingBoxCenter as Jr,boundingBoxGeohashes as Zr,coveringGeohashes as $r,encodeGeohash as eo,haversineMeters as ro,pointInBoundingBox as oo}from"./packem_shared/GEO_DEFAULT_PRECISION-DyI5zggj.mjs";import{ADMIN_FUNCTIONS as to,ADMIN_FUNCTION_PREFIX as no,DEFAULT_FANOUT_TOPIC_LIMIT as so,FLAGS_FUNCTION_PREFIX as io,MAX_PAGE_SIZE as lo,RELATION_FUNCTION_PREFIX as mo,createFanoutCounters as po,facetColumn as co,findStorageReferences as So,listTables as uo,readTablePage as xo,recordFanoutPass as fo,selectMatchingIds as ho,summarizeFanoutTopics as Ao,summarizeSubscriptions as Eo}from"./packem_shared/ADMIN_FUNCTIONS-Cj1pJjVg.mjs";import{MAIL_RETENTION as go,MAIL_TABLE as Ro,clearCapturedMail as Co,ensureMailTable as _o,readCapturedMail as Io,recordCapturedMail as Lo}from"./packem_shared/MAIL_RETENTION-CzZuX9bd.mjs";import{NotFoundError as Mo}from"./packem_shared/NotFoundError-BhF7FeFr.mjs";import{armRestore as yo,readBookmark as Oo}from"./packem_shared/armRestore-BNzdvQ_o.mjs";import{applySelect as Fo,buildSeekBeforeWhere as Po,buildSeekWhere as ko,decodeCursor as Bo,encodeCursor as Go,normalizeOrderKeys as Uo,softDeleteScope as wo}from"./packem_shared/applySelect-5w13bMAR.mjs";import{QUEUE_TABLE as qo,clearQueueMessages as Wo,isLossyBody as vo,readQueueMessageById as zo,readQueueMessages as Ho,recordQueueMessages as Xo}from"./packem_shared/QUEUE_TABLE-BX0nopuT.mjs";import{RANK_TIEBREAK as Yo,encodePartitionKey as jo,matchesRankStaticWhere as Qo,rankKeyFromDoc as Jo,rankTableName as Zo,resolveRankPartition as $o,sortColumnName as ea}from"./packem_shared/RANK_TIEBREAK-BGk411OR.mjs";import{ReactiveCache as oa,reactiveCacheKey as aa}from"./packem_shared/ReactiveCache-D_T10KLy.mjs";import{createReadFootprint as na}from"./packem_shared/createReadFootprint-DIrrxRTE.mjs";import{buildIndexRange as ia,indexKeysForRow as la,keysTouchRanges as ma}from"./packem_shared/buildIndexRange-DFsdtPjD.mjs";import{DEFAULT_MAX_RELATION_KEYS as da,assertFlatPredicate as ca,assertShapeShardable as Sa,containsRelationPredicate as ua,isRelationPredicate as xa,resolveRelationPredicates as fa}from"./packem_shared/DEFAULT_MAX_RELATION_KEYS-BV1RCoat.mjs";import{applyOnDelete as Aa,distinctValues as Ea,fanOutScalarCounts as Ta,relationHooks as ga,resolveWith as Ra,runRowValidators as Ca}from"./packem_shared/applyOnDelete-crbAzVfE.mjs";import{DEFAULT_PROMOTION_THRESHOLDS as Ia,clampPromotionThresholds as La,nextPromotionState as ba,relayCountFor as Ma,shapeRoutingKey as Na}from"./packem_shared/DEFAULT_PROMOTION_THRESHOLDS-DYGNAo1I.mjs";import{DEFAULT_MAX_RELAYS as Oa,OwnerRelay as Da,RelayMember as Fa,createRelayLink as Pa}from"./packem_shared/DEFAULT_MAX_RELAYS-Cinp9pPC.mjs";import{createReplicaLink as Ba,gateReplicaDispatch as Ga,handleReplicaControl as Ua}from"./packem_shared/createReplicaLink-BMNW0SX6.mjs";import{buildReprojectionMigration as Ka,countLegacyRows as qa,reprojectableFields as Wa,reprojectionTables as va}from"./packem_shared/buildReprojectionMigration-JUwsTNTB.mjs";import{RLS_UNWRAP_SYMBOL as Ha,RlsRequiredError as Xa,guardWriter as Va}from"./packem_shared/RLS_UNWRAP_SYMBOL-DcqORh2s.mjs";import{SCHEMA_HISTORY_MAX_VERSIONS as ja,readSchemaHistory as Qa,readSchemaVersion as Ja,recordSchemaVersion as Za}from"./packem_shared/SCHEMA_HISTORY_MAX_VERSIONS-CEK7b_7v.mjs";import{serializeSqlValue as et}from"./packem_shared/serializeSqlValue-BR4UOWoP.mjs";import{buildSettings as ot,isDevEnvironment as at}from"./packem_shared/buildSettings-COIJsw7a.mjs";import{buildPokeFrames as nt,diffGlobalMembership as st,encodeRowsPatch as it,projectColumns as lt}from"./packem_shared/buildPokeFrames-DmB-FBeQ.mjs";import{ShardRunner as pt}from"./packem_shared/ShardRunner-DIqVdWtk.mjs";import{runSocketPool as ct}from"./packem_shared/runSocketPool-DPQLVyWF.mjs";import{MAX_SQL_ROWS as ut,assertReadonly as xt,lintReadonlySql as ft,runReadonlySql as ht}from"./packem_shared/MAX_SQL_ROWS-nMwkxv5f.mjs";import{awaitWsDrain as Et,subscriptionFrames as Tt,subscriptionListDeltas as gt,trySendFrame as Rt}from"./packem_shared/awaitWsDrain-PT9o0d6J.mjs";import{mergeChangedKeys as _t,recordChangedKeys as It,writeTouchesMemo as Lt}from"./packem_shared/mergeChangedKeys-BXtUgIPW.mjs";import{createSystemReader as Mt}from"./packem_shared/createSystemReader-DcDcrtM3.mjs";import{ConflictError as yt}from"./packem_shared/ConflictError-C8GtJmjS.mjs";import{DEFAULT_TRANSACTION_LIMITS as Dt,TransactionHeadroomTracker as Ft}from"./packem_shared/DEFAULT_TRANSACTION_LIMITS-DLUzZbta.mjs";import{hasTrigger as kt,runTriggers as Bt}from"./packem_shared/hasTrigger-CbkOHExZ.mjs";import{selectExpiredIds as Ut}from"./packem_shared/selectExpiredIds-C4Ry_NxG.mjs";import{compileWhereSql as Kt,literalInList as qt}from"./packem_shared/compileWhereSql-B3hq_v98.mjs";import{RELATION_EXISTS_KEY as vt}from"./packem_shared/RELATION_EXISTS_KEY-BaqSIFU1.mjs";import{REPROJECTION_MIGRATION_PREFIX as Ht,reprojectionMigrationId as Xt}from"./packem_shared/REPROJECTION_MIGRATION_PREFIX-D2dltRFC.mjs";import{quoteIdentifier as Yt}from"./packem_shared/quoteIdentifier-CObIFRhb.mjs";import{runShardMigrations as Qt}from"./packem_shared/runShardMigrations-C1mjoJS4.mjs";import{stableStringify as Zt}from"./packem_shared/stableStringify-BjLh4gvA.mjs";import{stableWireKey as en}from"./packem_shared/stableWireKey-Diuu1gGc.mjs";export{to as ADMIN_FUNCTIONS,no as ADMIN_FUNCTION_PREFIX,p as AGGREGATE_SQL_FUNCTION,$e as AGG_COUNT,er as AGG_KEY,rr as AGG_VALUE,N as AUDIT_LOG_TABLE,z as CDC_LOG_TABLE,H as CDC_META_TABLE,ae as CLIENT_WATERMARK_TABLE,yt as ConflictError,R as CountRlsUnsupportedError,qe as DATA_MIGRATION_STATE_TABLE,so as DEFAULT_FANOUT_TOPIC_LIMIT,da as DEFAULT_MAX_RELATION_KEYS,Oa as DEFAULT_MAX_RELAYS,Ia as DEFAULT_PROMOTION_THRESHOLDS,Dt as DEFAULT_TRANSACTION_LIMITS,or as DOC_COLUMN,Nr as DurableStreamRunner,io as FLAGS_FUNCTION_PREFIX,Qr as GEO_DEFAULT_PRECISION,pe as GLOBAL_SHAPE_SNAPSHOT_TABLE,he as IDEMPOTENCY_TABLE,go as MAIL_RETENTION,Ro as MAIL_TABLE,yr as MAX_DURABLE_STREAM_BYTES,Or as MAX_DURABLE_STREAM_CHUNKS,lo as MAX_PAGE_SIZE,ut as MAX_SQL_ROWS,Mo as NotFoundError,P as NotUniqueError,Da as OwnerRelay,qo as QUEUE_TABLE,Yo as RANK_TIEBREAK,vt as RELATION_EXISTS_KEY,mo as RELATION_FUNCTION_PREFIX,Ht as REPROJECTION_MIGRATION_PREFIX,Ha as RLS_UNWRAP_SYMBOL,oa as ReactiveCache,Fa as RelayMember,Xa as RlsRequiredError,He as SCAN_DEP,ja as SCHEMA_HISTORY_MAX_VERSIONS,Le as SEARCH_STATE_TABLE,Oe as SHAPE_POKE_CURSOR_TABLE,pt as ShardRunner,Ft as TransactionHeadroomTracker,te as advanceClientWatermark,ar as aggUpsertSql,d as aggregateSqlFunction,f as aggregateTableName,y as appendAuditEntry,X as appendCdcChange,Tr as appendStreamChunk,V as applyCdcChanges,Aa as applyOnDelete,Fo as applySelect,yo as armRestore,ca as assertFlatPredicate,xt as assertReadonly,Sa as assertShapeShardable,k as assertValidClientId,Et as awaitWsDrain,w as backfillAggregateIndexes,K as backfillRankIndexes,q as backfillSearchIndexes,W as backfillSearchIndexesForTable,Jr as boundingBoxCenter,Zr as boundingBoxGeohashes,ia as buildIndexRange,nt as buildPokeFrames,Ka as buildReprojectionMigration,Po as buildSeekBeforeWhere,ko as buildSeekWhere,ot as buildSettings,Y as bumpCdcEpoch,gr as claimStreamRun,La as clampPromotionThresholds,Co as clearCapturedMail,Wo as clearQueueMessages,h as coerceAggregateNumber,Kt as compileWhereSql,Ce as computeRankPage,ua as containsRelationPredicate,qa as countLegacyRows,$r as coveringGeohashes,le as createCompanionSync,Xe as createDependencyTracker,po as createFanoutCounters,tr as createIndexSql,na as createReadFootprint,Pa as createRelayLink,Ba as createReplicaLink,B as createShardCtxDb,Mt as createSystemReader,Dr as decideDurableAttach,Bo as decodeCursor,de as deleteGlobalShapeSnapshot,ce as deleteGlobalShapeSnapshotsForConnection,De as deleteShapePokeCursor,Fe as deleteShapePokeCursorsForConnection,Rr as deleteStreamRun,Ve as depKey,Pr as diffExternalSource,st as diffGlobalMembership,Ea as distinctValues,A as encodeAggregateKey,Go as encodeCursor,eo as encodeGeohash,jo as encodePartitionKey,it as encodeRowsPatch,O as ensureAuditTable,_o as ensureMailTable,o as exportShardRows,a as exportShardTable,co as facetColumn,Ta as fanOutScalarCounts,So as findStorageReferences,Cr as finishStreamRun,E as foldAggregateTally,Ga as gateReplicaDispatch,nr as geoTableName,Va as guardWriter,Ua as handleReplicaControl,kt as hasTrigger,ro as haversineMeters,_e as hydrateDocsById,t as importShardRows,la as indexKeysForRow,at as isDevEnvironment,sr as isFtsAvailable,vo as isLossyBody,xa as isRelationPredicate,Hr as isSoftDeleted,Xr as isSourceDue,ir as jsonPath,lr as jsonPathSql,ma as keysTouchRanges,Br as liftSourceId,ft as lintReadonlySql,uo as listTables,qt as literalInList,Qo as matchesRankStaticWhere,c as matchesStaticWhere,Kr as materializeExternalRows,qr as materializeExternalRowsIncremental,_t as mergeChangedKeys,C as mergeWhere,j as migrateCdcLog,Q as migrateCdcMeta,ne as migrateClientWatermark,_r as migrateDurableStreams,Se as migrateGlobalShapeSnapshot,Ae as migrateIdempotency,be as migrateSearchState,Pe as migrateShapePokeCursor,J as minCdcSeq,ba as nextPromotionState,S as normalizeCountArgument,G as normalizeIdStructurally,Uo as normalizeOrderKeys,Gr as normalizeSourceDocument,Ur as normalizeSourceValue,xr as param,n as parseExportShardArgs,s as parseImportShardArgs,_ as planAggregateLookup,oo as pointInBoundingBox,lt as projectColumns,Vr as pullExternalSourceIncrementalTick,Yr as pullExternalSourceTick,mr as qualifiedJsonPath,pr as qualifiedJsonPathSql,Yt as quoteIdentifier,Jo as rankKeyFromDoc,Zo as rankTableName,aa as reactiveCacheKey,T as readAggregateValue,D as readAuditLog,Oo as readBookmark,Io as readCapturedMail,Z as readCdcChanges,$ as readCdcCursor,ee as readCdcEpoch,se as readClientWatermark,Wr as readExternalSourceBaseline,ue as readGlobalShapeSnapshot,Ee as readIdempotent,We as readMigrationStatus,zo as readQueueMessageById,Ho as readQueueMessages,Qa as readSchemaHistory,Ja as readSchemaVersion,Me as readSearchBackfillState,ke as readShapePokeCursor,Ir as readStreamChunks,Lr as readStreamRun,xo as readTablePage,Lo as recordCapturedMail,It as recordChangedKeys,fo as recordFanoutPass,Xo as recordQueueMessages,Za as recordSchemaVersion,ga as relationHooks,Ma as relayCountFor,fr as renderSql,Wa as reprojectableFields,Xt as reprojectionMigrationId,va as reprojectionTables,$o as resolveRankPartition,fa as resolveRelationPredicates,Ra as resolveWith,dr as rowToDocument,ve as runDataMigration,Qe as runDrizzle,vr as runExternalSourceTick,ht as runReadonlySql,Ca as runRowValidators,Qt as runShardMigrations,ct as runSocketPool,Je as runSql,Bt as runTriggers,Ut as selectExpiredIds,i as selectExportTables,I as selectIndexForAggregate,L as selectIndexForCount,b as selectIndexForGroupBy,ho as selectMatchingIds,Ue as selectShapeMemberIds,we as selectShapeRows,et as serializeSqlValue,Na as shapeRoutingKey,wo as softDeleteScope,ea as sortColumnName,hr as sqliteInList,Zt as stableStringify,en as stableWireKey,Tt as subscriptionFrames,gt as subscriptionListDeltas,Ao as summarizeFanoutTopics,Eo as summarizeSubscriptions,cr as tableColumns,Ye as tableFromDepKey,u as throwingScheduler,re as trimCdcChanges,Te as trimIdempotent,br as trimStreamRuns,Sr as tryRowToDocument,Rt as trySendFrame,Ar as unionAll,l as validateImportRow,xe as writeGlobalShapeSnapshot,ge as writeIdempotent,Ne as writeSearchBackfillState,Be as writeShapePokeCursor,Lt as writeTouchesMemo};
@@ -1 +1 @@
1
- import{LunoraError as g}from"@lunora/errors";import{n as Bt,S as qt,x as Qe,T as Se,y as Ut,c as Pt}from"./ctx-db-companions-BJlCofon.mjs";import{sql as r}from"drizzle-orm";import{s as Ht}from"./wire-codec-Dh0j-GnY.mjs";import{aggregateSqlFunction as Re,normalizeCountArgument as Gt,throwingScheduler as jt}from"./AGGREGATE_SQL_FUNCTION-CTo0-9iZ.mjs";import{encodeAggregateKey as De,readAggregateValue as Le,aggregateTableName as Oe}from"./aggregateTableName-DN7gk6uh.mjs";import{mergeWhere as Y,CountRlsUnsupportedError as Fe,selectIndexForGroupBy as Qt,selectIndexForCount as Kt,selectIndexForAggregate as Yt}from"./CountRlsUnsupportedError-8BqPYQoP.mjs";import{backfillSearchIndexesForTable as zt}from"./backfillAggregateIndexes-DTOIsYbi.mjs";import{backfillAggregateIndexes as Fr,backfillRankIndexes as Wr,backfillSearchIndexes as Br}from"./backfillAggregateIndexes-DTOIsYbi.mjs";import{appendCdcChange as Jt}from"./CDC_LOG_TABLE-DNFFQwF_.mjs";import{CDC_LOG_TABLE as Ur,applyCdcChanges as Pr,bumpCdcEpoch as Hr,minCdcSeq as Gr,readCdcChanges as jr,readCdcCursor as Qr,readCdcEpoch as Kr,trimCdcChanges as Yr}from"./CDC_LOG_TABLE-DNFFQwF_.mjs";import{computeRankPage as at}from"./computeRankPage-BU8LXvQs.mjs";import{SCAN_DEP as U}from"./SCAN_DEP-D_yR9EeV.mjs";import{runDrizzle as W}from"./runDrizzle-C3n5gJsk.mjs";import{a as H,L as se,p as Ae,T as We,c as xe,N as J,E as ce,I as St,C as Vt,D as Rt,h as Xt,O as st}from"./do-sql-DKSFK627.mjs";import{WORKERD_SQLITE_LIMITS as At,unionAll as Pe,sqliteInList as Zt}from"./param-CYxL68V-.mjs";import{coveringGeohashes as en,boundingBoxGeohashes as tn,pointInBoundingBox as nn,haversineMeters as rn}from"./GEO_DEFAULT_PRECISION-DyI5zggj.mjs";import{NotFoundError as on}from"./NotFoundError-BhF7FeFr.mjs";import{normalizeOrderKeys as an,buildSeekWhere as xt,decodeCursor as He,applySelect as dt,encodeCursor as Ge,softDeleteScope as le,buildSeekBeforeWhere as sn}from"./applySelect-5w13bMAR.mjs";import{sortColumnName as lt,resolveRankPartition as dn,encodePartitionKey as ln,RANK_TIEBREAK as cn,rankTableName as ct}from"./RANK_TIEBREAK-BGk411OR.mjs";import{indexKeysForRow as un,buildIndexRange as fn}from"./buildIndexRange-DFsdtPjD.mjs";import{assertFlatPredicate as Be,resolveRelationPredicates as ut}from"./DEFAULT_MAX_RELATION_KEYS-BV1RCoat.mjs";import{runRowValidators as qe,resolveWith as ft,relationHooks as ht,applyOnDelete as hn,fanOutScalarCounts as mn}from"./applyOnDelete-crbAzVfE.mjs";import{guardWriter as pn}from"./RLS_UNWRAP_SYMBOL-DcqORh2s.mjs";import{f as $n}from"./sql-projection-jfoe331H.mjs";import{createSystemReader as wn}from"./createSystemReader-DcDcrtM3.mjs";import{ConflictError as pe}from"./ConflictError-C8GtJmjS.mjs";import{runTriggers as gn}from"./hasTrigger-CbkOHExZ.mjs";import{compileWhereSql as te}from"./compileWhereSql-B3hq_v98.mjs";import{CLIENT_WATERMARK_TABLE as Jr,advanceClientWatermark as Vr,migrateClientWatermark as Xr,readClientWatermark as Zr}from"./CLIENT_WATERMARK_TABLE-LrKfdxyt.mjs";import{GLOBAL_SHAPE_SNAPSHOT_TABLE as to,deleteGlobalShapeSnapshot as no,deleteGlobalShapeSnapshotsForConnection as ro,migrateGlobalShapeSnapshot as oo,readGlobalShapeSnapshot as io,writeGlobalShapeSnapshot as ao}from"./GLOBAL_SHAPE_SNAPSHOT_TABLE-B2LKe4KU.mjs";import{IDEMPOTENCY_TABLE as lo,readIdempotent as co,trimIdempotent as uo,writeIdempotent as fo}from"./IDEMPOTENCY_TABLE-tQ5mnqvw.mjs";import{runShardMigrations as mo}from"./runShardMigrations-BCuK60KT.mjs";import{SEARCH_STATE_TABLE as $o}from"./SEARCH_STATE_TABLE-DRk_SB72.mjs";import{selectShapeMemberIds as go,selectShapeRows as bo}from"./selectShapeMemberIds-Bkkug6vU.mjs";import{serializeSqlValue as ie}from"./serializeSqlValue-BR4UOWoP.mjs";import{quoteIdentifier as bn}from"./quoteIdentifier-CObIFRhb.mjs";const En=o=>{const i=new TextEncoder().encode(o);let t="";for(const d of i)t+=String.fromCodePoint(d);return btoa(t)},yn=o=>{const i=atob(o),t=Uint8Array.from(i,d=>d.codePointAt(0)??0);return new TextDecoder().decode(t)},Nn=()=>new g("BAD_REQUEST","invalid cursor"),mt=16,pt=8,V=1024,Ke=(o,i)=>i.query(o),_n=(o,i,t)=>{const d=Bt(o,t);if(d.length===0)return 0;let f=0;for(const[m,b]of i.entries()){const S=m===i.length-1;let y=0;for(const w of d)(S?w.startsWith(b):w===b)&&(y+=1);if(y===0)return 0;f+=y}return f},Tn=(o,i)=>{if(!i)return{exact:!0,lower:o,upper:o};const t=[...o].at(-1)??"",d=(t.codePointAt(0)??0)+1;if(d>=55296&&d<=57343||d>1114111)return{exact:!0,lower:o,upper:o};const f=o.slice(0,o.length-t.length);return{exact:!1,lower:o,upper:f+String.fromCodePoint(d)}},Sn=(o,i,t)=>{const d={eq:(f,m)=>{if(!o.definition.filterFields?.includes(f))throw new g("INTERNAL",`field "${f}" is not a filter field of search index "${o.indexName}" on table "${i}"`);if(o.filters.length>=pt)throw new g("BAD_REQUEST",`search index "${o.indexName}" on table "${i}": at most ${String(pt)} .eq() filters are supported per search query`);return o.filters.push({field:f,value:m}),d},search:(f,m)=>{const b=o;if(f!==b.definition.field)throw new g("INTERNAL",`search index "${b.indexName}" on table "${i}" indexes "${b.definition.field}", not "${f}"`);const S=Ke(m,t).length;if(S>mt)throw new g("BAD_REQUEST",`search index "${b.indexName}" on table "${i}": at most ${String(mt)} search terms are supported (got ${String(S)})`);return b.field=f,b.query=m,b.hasQuery=!0,d}};return d},Rn=o=>{if(o.length>V)throw new g("BAD_REQUEST",`more than ${String(V)} documents match this search — narrow it with filters or read it a page at a time with .paginate()`)},An=o=>Math.min(o.offset+o.numItems+1,V),xn=o=>En(`search:${String(o)}`),In=o=>{let i;try{i=yn(o)}catch{return}if(!i.startsWith("search:"))return;const t=Number(i.slice(7));return Number.isInteger(t)&&t>=0?t:void 0},vn=o=>{if(typeof o.endCursor=="string")throw new g("BAD_REQUEST","bounded (endCursor) pagination is not supported on search queries — relevance order has no stable range boundary");const i=Math.max(0,Math.floor(o.numItems)),t=o.cursor?In(o.cursor):0;if(t===void 0)throw Nn();if(t+i>V)throw new g("BAD_REQUEST",`search pagination reaches past the ${String(V)}-document limit (offset ${String(t)} + ${String(i)} requested) — narrow the query or the filters instead`);return{numItems:i,offset:t}},Cn=(o,i)=>{const t=i.offset+i.numItems,d=i.numItems>0&&o.length>t;return{continueCursor:d?xn(t):null,isDone:!d,page:o.slice(i.offset,t)}},Mn=o=>{if(o===void 0)return V+1;if(!Number.isFinite(o))return V;const i=Math.max(0,Math.floor(o));if(i>V)throw new g("BAD_REQUEST",`search returns at most ${String(V)} documents (asked for ${String(i)}) — narrow the query or paginate instead`);return i},kn=/^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/iu,Dn=o=>{if(!kn.test(o))throw new g("INTERNAL",`invalid clientId ${JSON.stringify(o)}: a client-supplied row id must be a UUID`)},$t=50,It=500,wt=Math.floor(At.boundParams/3),me=At.boundParams,Ln=128,de=(o,i,t)=>{const d=i??It;if(o>d)throw new g("BATCH_LIMIT_EXCEEDED",`${t}: batch of ${String(o)} exceeds the limit of ${String(d)} (raise options.limit or chunk the call)`,{status:400})},On=o=>{const i={eq:(t,d)=>(o.sqlConditions.push({comparator:"=",field:t,value:d}),i),gt:(t,d)=>(o.sqlConditions.push({comparator:">",field:t,value:d}),i),gte:(t,d)=>(o.sqlConditions.push({comparator:">=",field:t,value:d}),i),lt:(t,d)=>(o.sqlConditions.push({comparator:"<",field:t,value:d}),i),lte:(t,d)=>(o.sqlConditions.push({comparator:"<=",field:t,value:d}),i)};return i},Fn=o=>Math.max(o,V),vt=(o,i)=>{const t=o.filters.map(d=>r`${J(d.field)} = ${ie(d.value)}`);return i&&t.push(i),t},Wn=(o,i,t,d,f)=>{const m=Ke(t.query,Qe(t.definition.language));if(m.length===0)return[];const b=Pt(i,t.indexName),S=`${b}__vocab`,y=m.length-1,w=m.map((L,M)=>{const G=Tn(L,M===y),j=G.exact?r`${r.identifier("term")} = ${G.lower}`:r`${r.identifier("term")} >= ${G.lower} AND ${r.identifier("term")} < ${G.upper}`;return r`SELECT ${r.identifier("doc")}, ${r.raw(String(M))} AS ${r.identifier("__term__")}, COUNT(*) AS ${r.identifier("__n__")} FROM ${r.identifier(S)} WHERE ${j} GROUP BY ${r.identifier("doc")}`}),N=m.map((L,M)=>r`SUM(CASE WHEN u.${r.identifier("__term__")} = ${r.raw(String(M))} THEN u.${r.identifier("__n__")} ELSE 0 END)`),_=r`SELECT f.${r.identifier(Se)} AS ${r.identifier(Se)}, ${r.join(N,r` + `)} AS ${r.identifier("__score__")} FROM (${Pe(w)}) u JOIN ${r.identifier(b)} f ON f.rowid = u.${r.identifier("doc")} GROUP BY f.${r.identifier(Se)} HAVING ${r.join(N.map(L=>r`${L} > 0`),r` AND `)}`,T=vt(t,f);let v=r`SELECT m.id, m._creationTime, m.${r.identifier(H)}, s.${r.identifier("__score__")} AS ${r.identifier("__score__")} FROM (${_}) s JOIN ${r.identifier(i)} m ON m.id = s.${r.identifier(Se)}`;T.length>0&&(v=r`${v} WHERE ${r.join(T,r` AND `)}`),v=r`${v} ORDER BY s.${r.identifier("__score__")} DESC, m._creationTime DESC, m.id ASC LIMIT ${r.raw(String(d))}`;const O=[];for(const L of W(o,v)){const M=Rt(L);if(M){const G=L.__score__;O.push({document:M,score:typeof G=="number"?G:Number(G??0)})}}return O},Bn=(o,i,t,d,f)=>{const m=Qe(t.definition.language),b=Ke(t.query,m);if(b.length===0)return[];const S=vt(t,f);let y=r`SELECT id, _creationTime, ${r.identifier(H)} FROM ${r.identifier(i)}`;S.length>0&&(y=r`${y} WHERE ${r.join(S,r` AND `)}`),y=r`${y} ORDER BY _creationTime DESC, id ASC LIMIT ${r.raw(String(Fn(d)))}`;const w=W(o,y).toArray(),N=[];for(const _ of w){const T=Rt(_);if(!T)continue;const v=_n(Ut(T,t.definition),b,m);v>0&&N.push({creationTime:typeof T._creationTime=="number"?T._creationTime:0,doc:T,id:typeof T._id=="string"?T._id:"",score:v})}return N.sort((_,T)=>T.score-_.score||T.creationTime-_.creationTime||_.id.localeCompare(T.id)),N.slice(0,d).map(_=>({document:_.doc,score:_.score}))},Ue=(o,i,t,d)=>{if(!Number.isFinite(o.lat)||o.lat<-90||o.lat>90||!Number.isFinite(o.lng)||o.lng<-180||o.lng>180)throw new g("BAD_REQUEST",`geo index "${d}" on table "${t}": ${i} must have a finite lat in [-90, 90] and lng in [-180, 180]`)},qn=(o,i)=>{const t=o,d={near:(f,m)=>{if(t.within)throw new g("INTERNAL",`geo index "${t.indexName}" on table "${i}": call .near() or .within(), not both`);if(Ue(f,".near() point",i,t.indexName),!Number.isFinite(m)||m<=0)throw new g("BAD_REQUEST",`geo index "${t.indexName}" on table "${i}": .near() radiusMeters must be a finite number > 0, got ${String(m)}`);return t.near={point:{lat:f.lat,lng:f.lng},radiusMeters:m},d},within:f=>{if(t.near)throw new g("INTERNAL",`geo index "${t.indexName}" on table "${i}": call .near() or .within(), not both`);if(Ue(f.sw,".within() sw corner",i,t.indexName),Ue(f.ne,".within() ne corner",i,t.indexName),f.sw.lat>f.ne.lat)throw new g("BAD_REQUEST",`geo index "${t.indexName}" on table "${i}": .within() corners are transposed (sw.lat > ne.lat)`);if(f.sw.lng>f.ne.lng)throw new g("BAD_REQUEST",`geo index "${t.indexName}" on table "${i}": .within() box crosses the antimeridian (sw.lng > ne.lng), which is not supported — split it into two boxes at ±180 and union the results`);return t.within={ne:{lat:f.ne.lat,lng:f.ne.lng},sw:{lat:f.sw.lat,lng:f.sw.lng}},d}};return d},Un=(o,i)=>{const t=o[i];if(t===null||typeof t!="object")return;const{lat:d,lng:f}=t;return typeof d=="number"&&typeof f=="number"?{lat:d,lng:f}:void 0},Pn=(o,i)=>{const t=Un(o,i.definition.field);if(!t)return;const d=typeof o._creationTime=="number"?o._creationTime:0;if(i.near){const f=rn(i.near.point,t);return f<=i.near.radiusMeters?{creationTime:d,distance:f}:void 0}return nn(t,i.within)?{creationTime:d,distance:0}:void 0},Hn=(o,i,t,d)=>{if(!t.near&&!t.within)throw new g("INTERNAL",`geo index "${t.indexName}" on table "${i}": call .near(point, radius) or .within(box)`);const f=t.near?en(t.near.point,t.near.radiusMeters):tn(t.within),m=Xt(i,t.indexName),b=f.map(_=>r`(g.${r.identifier("__geohash__")} >= ${_} AND g.${r.identifier("__geohash__")} < ${`${_}{`})`),S=[r`(${r.join(b,r` OR `)})`];d&&S.push(d);const y=r`SELECT m.id, m._creationTime, m.${r.identifier(H)} FROM ${r.identifier(m)} g JOIN ${r.identifier(i)} m ON m.id = g.${r.identifier("__id__")} WHERE ${r.join(S,r` AND `)}`,w=W(o,y).toArray(),N=[];for(const _ of w){const T=ce(_),v=T?Pn(T,t):void 0;T&&v&&N.push({creationTime:v.creationTime,distance:v.distance,doc:T})}return N.sort((_,T)=>_.distance-T.distance||T.creationTime-_.creationTime),N},Ct=(o,i,t,d)=>{const f=[];for(const m of o)if(i.every(b=>b(d(m)))&&(f.push(m),typeof t=="number"&&f.length>=t))break;return f},Gn=(o,i,t,d,f,m=()=>{})=>{const b=t.within!==void 0,S=Hn(o,i,t,f).map(y=>({distanceMeters:b?null:y.distance,document:y.doc}));return m(S.length),typeof d=="number"?S.slice(0,Math.max(0,Math.floor(d))):S},Mt=(o,i,t,d,f,m=()=>{})=>{const{geo:b}=t;if(!b)throw new g("INTERNAL","runGeoTerminalScored called without a staged geo query");const S=t.inMemoryFilters.length>0,y=Gn(o,i,b,S?void 0:f,d,m);return S?Ct(y,t.inMemoryFilters,f,w=>w.document):y},jn=(o,i,t,d,f,m=()=>{})=>Mt(o,i,t,d,f,m).map(b=>b.document),Qn=(o,i,t,d,f,m,b=()=>{})=>{const S=[];for(const _ of t.sqlConditions)S.push(r`${J(_.field)} ${r.raw(_.comparator)} ${ie(_.value)}`);d&&S.push(d);let y=r`SELECT id, _creationTime, ${r.identifier(H)} FROM ${r.identifier(i)}`;S.length>0&&(y=r`${y} WHERE ${r.join(S,r` AND `)}`),y=r`${y} ORDER BY ${f}`,typeof m=="number"&&t.inMemoryFilters.length===0&&(y=r`${y} LIMIT ${r.raw(String(Math.max(0,Math.floor(m))))}`);const w=W(o,y).toArray();b(w.length);const N=[];for(const _ of w){const T=ce(_);if(T&&t.inMemoryFilters.every(v=>v(T))&&(N.push(T),typeof m=="number"&&N.length>=m))break}return N},oe={fieldRef:J,serialize:ie},kt=(o,i)=>{const t=i===void 0?void 0:o.shape[i];return t!==void 0&&$n(t)},gt=(o,i)=>i.some(t=>kt(o,t)),bt=(o,i,t)=>{if(kt(o,i))throw new g("BAD_REQUEST",`${t}: "${i}" is stored as an order-preserving key, which SQL cannot reduce or group — declare an aggregateIndex covering this (by, field, op) so the maintained companion answers it`)},Kn=o=>{let i=0;const t=[],d={fieldRef:J,relationExists:f=>{const{childWhere:m,negated:b,parentTable:S,relation:y}=f,w=`__rel_${String(i)}`,N=t.at(-1)??S;i+=1,o(y.table,U);const _=y.kind==="one"?y.field:y.references,T=y.kind==="one"?y.references:y.field,v=r`${st(w,T)} = ${st(N,_)}`;t.push(w);const O=te(m,d);t.pop();const L=O?r`${v} AND ${O}`:v,M=r`EXISTS (SELECT 1 FROM ${r.identifier(y.table)} AS ${r.identifier(w)} WHERE ${L})`;return b?r`NOT ${M}`:M},serialize:ie};return d},Dt=o=>{const i=o.map(t=>r`${J(t.field)} ${r.raw(t.direction==="desc"?"DESC":"ASC")}`);return o.some(t=>t.field==="_id"||t.field==="id")||i.push(r`${J("id")} ASC`),r.join(i,r`, `)},Yn={"<":"lt","<=":"lte","=":"eq",">":"gt",">=":"gte"},zn=o=>{const i=o.order;return o.indexFields.length>0?o.indexFields.map(t=>({direction:i,field:t})):[{direction:i,field:"_creationTime"}]},Jn=(o,i,t,d)=>{const f=o.sqlConditions.map(m=>({[m.field]:{[Yn[m.comparator]??"eq"]:m.value}}));if(t&&f.push(xt(i,He(t))),d&&f.push(sn(i,He(d))),f.length!==0)return f.length===1?f[0]:{AND:f}},Vn=(o,i,t)=>{const d=[];for(const f of o){const m=ce(f);if(m&&i.every(b=>b(m))&&(d.push(m),t!==void 0&&d.length>t))break}return d},Xn=(o,i,t,d,f,m=()=>{})=>{const b=Math.max(0,Math.floor(d.numItems)),S=zn(t),y=typeof d.endCursor=="string",w=te(Jn(t,S,d.cursor,d.endCursor),oe),N=f&&w?r`${w} AND ${f}`:f??w;let _=r`SELECT id, _creationTime, ${r.identifier(H)} FROM ${r.identifier(i)}`;N&&(_=r`${_} WHERE ${N}`),_=r`${_} ORDER BY ${Dt(S)}`;const T=t.inMemoryFilters.length>0;!T&&!y&&(_=r`${_} LIMIT ${r.raw(String(b+1))}`);const v=W(o,_).toArray();m(v.length);const O=Vn(v,t.inMemoryFilters,T||y?void 0:b);if(y){const j=O.length>=2?O[Math.floor(O.length/2)-1]:void 0;return{continueCursor:d.endCursor??null,isDone:!0,page:O,splitCursor:j?Ge(j,S):null}}const L=O.length>b,M=L?O.slice(0,b):O,G=M.at(-1);return{continueCursor:L&&G?Ge(G,S):null,isDone:!L,page:M}};class Zn extends g{constructor(i="unique() found more than one matching document"){super("NOT_UNIQUE",i,{name:"NotUniqueError"})}}const er=/\s/u,tr=String.fromCodePoint(0),Et=(o,i,t)=>{if(!o.tables[i])throw new g("INTERNAL",`unknown table: ${i}`);return typeof t!="string"||t.length===0||er.test(t)||t.includes(tr)?null:t},nr=(o,i,t,d=()=>{},f=()=>{},m=()=>{})=>{const b=i.tables[t];if(!b)throw new g("INTERNAL",`unknown table: ${t}`);const S=le(b.softDeleteMode,void 0),y=S?te(S,oe):void 0,w={indexFields:[],indexName:void 0,inMemoryFilters:[],order:"asc",sqlConditions:[]};let N=0;const _=E=>{const{search:I}=w;if(!I)throw new g("INTERNAL","runSearchFetch called without a staged search");zt(o,t,b);const C=w.inMemoryFilters.length>0,k=Mn(C?void 0:E),z=Vt(o)?Wn(o,t,I,k,y):Bn(o,t,I,k,y);return C?(N=z.length,Ct(z,w.inMemoryFilters,E,ne=>ne.document)):(E===void 0&&Rn(z),z)},T=E=>_(E).map(I=>I.document),v=E=>{const I=vn(E);return Cn(T(An(I)),I)},O=()=>{const E=w.indexFields.length>0?w.indexFields:["_creationTime"],I=w.order==="desc"?"DESC":"ASC";return r.join(E.map(C=>r`${J(C)} ${r.raw(I)}`),r`, `)},L=()=>{if(w.search||w.geo||w.indexName===void 0){f(void 0);return}f(fn(t,w.indexName,w.indexFields,w.sqlConditions,ie))},M=E=>{L();let I=0;const C=(()=>{if(w.search){const k=T(E);return I=N,k}return w.geo?jn(o,t,w,y,E,k=>{I=k}):Qn(o,t,w,y,O(),E,k=>{I=k})})();return m(Math.max(I,C.length)),C},G=()=>{if(!w.search&&!w.geo)throw new g("INTERNAL",`ctx.db.query("${t}").collectWithScores() requires a staged .withSearchIndex(...) or .withGeoIndex(...)`);L();let E=0;const I=(()=>{if(w.search){const C=_(void 0);return E=N,C}return Mt(o,t,w,y,void 0,C=>{E=C})})();return m(Math.max(E,I.length)),I},j={async*[Symbol.asyncIterator](){const E=[...w.inMemoryFilters];let I;w.inMemoryFilters=[];try{for(;;){const C=await j.paginate({cursor:I??null,numItems:Ln});for(const k of C.page)E.every(z=>z(k))&&(yield k);if(C.isDone||C.continueCursor===null)return;I=C.continueCursor}}finally{w.inMemoryFilters=E}},async collect(){return M(void 0)},async collectWithScores(){return G()},filter(E){return w.inMemoryFilters.push(E),j},async first(){return M(w.inMemoryFilters.length>0?void 0:1)[0]??null},order(E){return w.order=E==="desc"?"desc":"asc",j},async paginate(E){let I=0;if(L(),w.search){const k=v(E);return m(k.page.length),k}if(w.geo)throw new g("INTERNAL","pagination is not supported on geo queries; use .take(n) or .collect()");const C=Xn(o,t,w,E,y,k=>{I=k});return m(Math.max(I,C.page.length)),C},async take(E){return M(E)},async unique(){const E=M(w.inMemoryFilters.length>0?void 0:2);if(E.length>1)throw new Zn(`unique() on table "${t}" matched ${String(E.length)} documents; expected at most one`);return E[0]??null},withGeoIndex(E,I){const C=(b.geoIndexes??[]).find(z=>z.name===E);if(!C)throw new g("INTERNAL",`unknown geo index "${E}" on table "${t}"`);d(t,E,"geo");const k={definition:C,indexName:E};if(w.geo=k,I(qn(k,t)),!k.near&&!k.within)throw new g("INTERNAL",`geo index "${E}" on table "${t}" requires a .near(point, radius) or .within(box) call`);return j},withIndex(E,I){const C=b.indexes.find(k=>k.name===E);if(!C)throw new g("INTERNAL",`unknown index "${E}" on table "${t}"`);return d(t,E,"index"),w.indexName=E,w.indexFields=C.fields,I&&I(On(w)),j},withSearchIndex(E,I){const C=(b.searchIndexes??[]).find(z=>z.name===E);if(!C)throw new g("INTERNAL",`unknown search index "${E}" on table "${t}"`);d(t,E,"search");const k={definition:C,field:C.field,filters:[],hasQuery:!1,indexName:E,query:""};if(w.search=k,I(Sn(k,t,Qe(C.language))),!k.hasQuery)throw new g("INTERNAL",`search index "${E}" on table "${t}" requires a .search(field, query) call`);return j}};return j},yt=(o,i,t)=>{const d={...i};for(const[f,m]of St(o)){if(m.serverDefault){d[f]=m.serverDefault({auth:t});continue}d[f]===void 0&&(m.defaultFn?d[f]=m.defaultFn():"defaultValue"in m&&(d[f]=m.defaultValue))}return d},Nt=(o,i,t,d)=>{const f=t;for(const[m,b]of St(o)){if(b.serverDefault){m in i&&(f[m]=b.serverDefault({auth:d}));continue}b.onUpdateFn&&!(m in i)&&(f[m]=b.onUpdateFn())}},_t=(o,i)=>{for(const t of Object.keys(i))if(i[t]===void 0)throw new g("INTERNAL",`Cannot ${o} field '${t}' to undefined — use null to clear a nullable field, or omit the key to leave it unchanged.`)},rr=/unique constraint failed/i,or=o=>o instanceof Error&&rr.test(o.message),je=(o,i,t)=>{try{W(o,t)}catch(d){throw or(d)?new pe(`unique constraint violation on "${i}"`,"unique"):d}},Ie=(o,i,t)=>{if(je(o,i,t),W(o,r`SELECT changes() AS changed`).one().changed===0)throw new pe(`optimistic concurrency conflict on "${i}" — the row changed during this mutation; refetch and retry`,"occ")},Tt=(o,i,t,d,f,m,b)=>{const S=[];for(let _=0;_<t.length+1;_+=1){const T=[];for(let M=0;M<_;M+=1)T.push(r`${r.identifier(t[M])} IS ${m[M]}`);const v=t[_],O=d[_];if(v!==void 0&&O!==void 0){const M=O.direction==="desc"?">":"<";T.push(r`${r.identifier(v)} ${r.raw(M)} ${m[_]}`)}else T.push(r`${r.identifier(cn)} < ${b}`);const[L]=T;S.push(T.length===1&&L!==void 0?L:r`(${r.join(T,r` AND `)})`)}const y=r.join(S,r` OR `),w=W(o,r`SELECT COUNT(*) AS c FROM ${r.identifier(i)} WHERE ${r.identifier("__partition__")} = ${f} AND (${y})`).one(),N=W(o,r`SELECT COUNT(*) AS c FROM ${r.identifier(i)} WHERE ${r.identifier("__partition__")} = ${f}`).one();return{before:w.c,total:N.c}},Dr=o=>{const{sql:i}=o,{schema:t}=o,d=o.broadcast??(()=>{}),f=(e,...n)=>{const a=t.tables[e]?.indexes;if(!a||a.length===0)return;const c=[];for(const h of n)h&&c.push(...un(a,h,ie));return c.length>0?c:void 0},{headroom:m}=o;let b=!1;const S=async e=>{const n=b;b=!0;try{return await e()}finally{b=n}},y=o.onRead??(()=>{}),w=o.onReadRange??(e=>{y(e.table,U)}),N=(e,n)=>{n!==void 0&&n!==U&&!b&&m?.recordRead(1),y(e,n)},_=o.onIndexUse??(()=>{}),T=o.onWrite??(()=>{}),v=e=>{b||m?.recordWrite(e)},O=async e=>{v(e.doc),await T(e)},{cache:L}=o,M=o.clock??(()=>Date.now()),G=o.idGenerator??(()=>crypto.randomUUID()),j=o.scheduler??jt,{globalDb:E}=o,I=o.auth??{identity:null,userId:null},C=o.cdc??!1,k=j,z=wn({scheduler:typeof k.list=="function"&&typeof k.get=="function"?k:void 0,storage:o.storage}),ne=(e,n,a,c)=>{C&&Jt(i,M(),e,n,a,c)},ae=e=>t.tables[e]?.shardMode?.kind==="global",Ye=(e,n)=>{if(ae(e)){if(!E)throw new g("INTERNAL",`cross-backend ${n} for global table '${e}' requires a globalDb writer — pass one to createShardCtxDb({ globalDb })`);return E}return B},ve=e=>Ye(e,"cascade"),K=(e,n)=>{if(ae(e)){if(!E)throw new g("INTERNAL",`${n} on global table '${e}' requires a globalDb writer — pass one to createShardCtxDb({ globalDb })`);return E}},ze=async(e,n,a,c,h)=>{h&&v(a);const u=await e.insert(n,a,c);return d({key:u,op:"insert",row:{...a,_id:u},table:n}),u},Ce=(e,n)=>Ye(e,"relation load").findMany(e,n),Je=(e,n)=>(ae(e)&&N(e,U),Ce(e,n)),Lt=e=>!ae(e.table),Ve=o.relationExistsPushDown??"auto",Xe=Ve!=="never",{maxRelationKeys:Ze}=o,$e=(e,n,a)=>ut(e,{fetcher:Je,maxRelationKeys:Ze,relationBaseWhere:a,schema:t,tableName:n}),et=async(e,n,a,c)=>{const h=K(e,"relation grouped count");if(h)return N(e,U),mn((P,x)=>h.count(P,x),e,n,a,c);const u=t.tables[e];if(!u)throw new g("INTERNAL",`unknown table: ${e}`);N(e,U);const s=le(u.softDeleteMode,void 0),l={[n]:{in:a}},p=Y(Y(l,c),s),R=await $e(p,e,void 0),$=te(R,oe),A=J(n);let D=r`SELECT ${A} AS __fk__, COUNT(*) AS count FROM ${r.identifier(e)}`;$&&(D=r`${D} WHERE ${$}`),D=r`${D} GROUP BY ${A}`;const F=W(i,D).toArray();return new Map(F.map(P=>[P.__fk__,P.count]))};let we=0;const tt=new Set;for(const[e,n]of Object.entries(t.tables))for(const a of Object.values(n.triggerMap??{}))tt.add(`${e} ${a.timing} ${a.op}`);const X=(e,n,a)=>tt.has(`${e} ${n} ${a}`),Z=async(e,n,a)=>{if(we+=1,we>$t)throw we-=1,new pe(`trigger recursion exceeded ${String($t)} levels on "${a.table}" — check for a self-triggering write`,"trigger");try{await gn({ctx:Ft,event:a,op:n,schema:t,tableName:a.table,timing:e})}finally{we-=1}},{ensureBackfilledForTable:ue,ensureBackfilledIndex:Me,ensureRankBackfilled:ke,ensureRankBackfilledForTable:fe,syncAggregates:ge,syncCompanionsForInsert:nt,syncGeo:be,syncRanks:he,syncSearch:Ee}=qt({broadcast:d,indexKeysFor:(e,n)=>f(e,n),invalidateCache:(e,n,a)=>L?.invalidate(e,n,f(e,a)),recordCdc:ne,schema:t,sql:i}),rt=(e,n,a)=>{const{shardMode:c}=n;if(c?.kind==="shardBy"&&!(c.field!==void 0&&(a.partitionBy??[]).includes(c.field)))throw Object.assign(new Error(`rank index "${a.name}" on "${e}" partitions across shards (shard key "${c.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})},ot=e=>Object.entries(t.tables).filter(([,n])=>n.shardMode?.kind!=="global").map(([n])=>n).filter(n=>e===void 0||n===e),re=(e,n)=>{const a=ot(n);for(let c=0;c<a.length;c+=me){const h=a.slice(c,c+me).map(R=>r`SELECT ${r.raw(`'${R.replaceAll("'","''")}'`)} AS __t__, id, _creationTime, ${r.identifier(H)} FROM ${r.identifier(R)} WHERE id = ${e}`),[u]=W(i,r`${Pe(h)} LIMIT 1`).toArray();if(!u)continue;const s=u.__t__,l=ce(u);if(typeof s!="string"||!l)return;const p=u[H];return{docJson:typeof p=="string"?p:se(p??{}),row:l,tableName:s}}},Ot=(e,n)=>{const a=[...new Set(e)],c=new Map;if(a.length===0)return c;const h=ot(n);for(let u=0;u<h.length;u+=me){const s=h.slice(u,u+me),l=Math.floor(me/s.length),p=Zt(r`${r.identifier("id")}`,a,!1,l),R=s.map($=>r`SELECT ${r.raw(`'${$.replaceAll("'","''")}'`)} AS __t__, id FROM ${r.identifier($)} WHERE ${p}`);for(const $ of W(i,Pe(R))){const{id:A,__t__:D}=$;typeof D=="string"&&typeof A=="string"&&c.set(A,D)}}return c},it={assertRankPartitionLocal:rt,ensureRankBackfilled:ke,onRead:N,rowToDocument:ce,schema:t,sql:i},B={system:z,async aggregate(e,n){const a=K(e,"aggregate");if(a)return N(e,U),a.aggregate(e,n);const c=t.tables[e];if(!c)throw new g("INTERNAL",`unknown table: ${e}`);if(Re(n.op),n.op==="count")return B.count(e,{baseWhere:n.baseWhere,relationBaseWhere:n.relationBaseWhere,restrictsCounts:n.restrictsCounts,where:n.where});if(!n.field)throw new g("INTERNAL",`aggregate(${e}, { op: "${n.op}" }): "field" is required for non-count reducers`);N(e,U);const h=le(c.softDeleteMode,void 0),u=Y(Y(n.baseWhere,n.where),h),s=await $e(u,e,n.relationBaseWhere),l=s!==u;if(c.aggregateIndexes&&!n.baseWhere&&!l&&(!h||gt(c,[n.field]))){const F=Yt(c.aggregateIndexes,n.op,n.field,n.where);if(F){Me(e,F.index);const P=De(F.index.by??[],F.key),x=Oe(e,F.index.name),Q=W(i,r`SELECT ${Ae} AS value, ${We} AS count FROM ${r.identifier(x)} WHERE ${xe} = ${P}`).toArray()[0];return Le(n.op,Q)}}bt(c,n.field,`aggregate(${e}, { op: "${n.op}", field: "${n.field}" })`);const p=te(s,oe),R=Re(n.op),$=J(n.field);let A=r`SELECT ${r.raw(R)}(${$}) AS value FROM ${r.identifier(e)}`;return p&&(A=r`${A} WHERE ${p}`),W(i,A).toArray()[0]?.value??null},asId(e,n){const a=Et(t,e,n);if(a===null)throw new g("BAD_REQUEST",`asId("${e}", …): "${n}" is not a valid id for table "${e}"`,{status:400});return a},async count(e,n){const a=K(e,"count");if(a)return N(e,U),a.count(e,n);const c=t.tables[e];if(!c)throw new g("INTERNAL",`unknown table: ${e}`);const h=Gt(n);if(h.restrictsCounts)throw new Fe(e);N(e,U);const u=le(c.softDeleteMode,void 0),s=Y(Y(h.baseWhere,h.where),u),l=await $e(s,e,h.relationBaseWhere),p=l!==s;if(c.aggregateIndexes&&!h.baseWhere&&!p&&!u){const A=Kt(c.aggregateIndexes,h.where);if(A){Me(e,A.index);const D=De(A.index.by??[],A.key),F=Oe(e,A.index.name),P=W(i,r`SELECT ${Ae} AS value FROM ${r.identifier(F)} WHERE ${xe} = ${D}`).toArray();return P[0]===void 0?0:P[0].value??0}}const R=te(l,oe);let $=r`SELECT COUNT(*) AS count FROM ${r.identifier(e)}`;return R&&($=r`${$} WHERE ${R}`),W(i,$).one().count},async delete(e,n,a){const c=re(e,n);if(!c){const $=n===void 0?E:void 0;$&&(v(void 0),await $.delete(e,void 0,a));return}const{docJson:h,row:u,tableName:s}=c,l=t.tables[s],p=a?.hard===!0,R=!p&&l?.softDeleteMode?l.softDeleteMode.field:void 0;if(!(R&&u[R]!==null&&u[R]!==void 0)){if(X(s,"before","delete")&&await Z("before","delete",{id:e,op:"delete",previous:u,table:s}),await hn({deletedId:e,deletedReference:$=>u[$],findHolders:async($,A,D)=>(await ve($).findMany($,{includeDeleted:p,where:{[A]:D}})).page,onCascade:($,A)=>ve($).delete(A,void 0,a),onRestrict:$=>{throw new pe($,"restrict")},onSetNull:($,A,D)=>ve($).patch(A,{[D]:null}),schema:t,tableName:s}),ue(s),fe(s),R){const $={...u,[R]:M(),_id:e};Ie(i,s,r`UPDATE ${r.identifier(s)} SET ${r.identifier(H)} = ${se($)} WHERE id = ${e} AND ${r.identifier(H)} = ${h}`),Ee(s,e,$,u),be(s,e,void 0),ge(s,u,$),he(s,e,u,void 0),L?.invalidate(s,e,f(s,u,$)),ne(s,e,"update",$),d({indexKeys:f(s,u,$),key:e,op:"update",row:$,table:s}),X(s,"after","delete")&&await Z("after","delete",{id:e,op:"delete",previous:u,table:s}),await O({id:e,op:"delete",table:s});return}Ie(i,s,r`DELETE FROM ${r.identifier(s)} WHERE id = ${e} AND ${r.identifier(H)} = ${h}`),Ee(s,e,void 0),be(s,e,void 0),ge(s,u,void 0),he(s,e,u,void 0),L?.invalidate(s,e,f(s,u)),ne(s,e,"delete"),d({indexKeys:f(s,u),key:e,op:"delete",table:s}),X(s,"after","delete")&&await Z("after","delete",{id:e,op:"delete",previous:u,table:s}),await O({id:e,op:"delete",table:s})}},async deleteAll(e,n){if(!t.tables[e])throw new g("INTERNAL",`unknown table: ${e}`);const a=Math.max(1,n?.chunkSize??It),c=n?.hard===void 0?void 0:{hard:n.hard},h=ae(e)?void 0:e;let u=0;return await S(async()=>{for(;;){const s=(await B.findMany(e,{limit:a})).page.map(l=>String(l._id));if(s.length===0)break;for(const l of s)await B.delete(l,h,c),u+=1;if(s.length<a)break}}),{deleted:u}},async deleteMany(e,n,a){de(e.length,n?.limit,"deleteMany");for(const c of e)await B.delete(c,a);return{deleted:e.length}},async deleteWhere(e,n,a){const c=(await(K(e,"deleteWhere")??B).findMany(e,{where:n})).page.map(h=>String(h._id));if(de(c.length,a?.limit,"deleteWhere"),B.deleteMany===void 0)throw new g("INTERNAL",`ctx.db.${e}.deleteMany is unavailable: this writer has no batch delete`);return B.deleteMany(c,a)},async findFirst(e,n={}){return(await B.findMany(e,{...n,limit:1})).page[0]??null},async findFirstOrThrow(e,n={}){const a=await B.findFirst(e,n);if(a===null)throw new on(`findFirstOrThrow: no "${e}" document matched`);return a},async findMany(e,n={}){const a=K(e,"findMany");if(a)return N(e,U),a.findMany(e,n);const c=t.tables[e];if(!c)throw new g("INTERNAL",`unknown table: ${e}`);const h=!n.where&&!n.baseWhere;h?N(e,U):N(e);const u=an(n.orderBy),s=n.cursor?xt(u,He(n.cursor)):void 0;let l=Y(n.baseWhere,n.where);l=Y(l,le(c.softDeleteMode,n.includeDeleted)),l=await ut(l,{canPushExists:Xe?Lt:void 0,existsPushMode:Ve==="always"?"always":"auto",fetcher:Je,maxRelationKeys:Ze,relationBaseWhere:n.relationBaseWhere,schema:t,tableName:e}),s&&(l=l?{AND:[l,s]}:s);const p=Xe?Kn(N):oe,R=te(l,p);let $=r`SELECT id, _creationTime, ${r.identifier(H)} FROM ${r.identifier(e)}`;R&&($=r`${$} WHERE ${R}`),$=r`${$} ORDER BY ${Dt(u)}`;const A=typeof n.limit=="number"?Math.max(0,Math.floor(n.limit)):void 0;A!==void 0&&($=r`${$} LIMIT ${r.raw(String(A+1))}`);const D=W(i,$).toArray();h&&!b&&m?.recordRead(D.length);const F=[];for(const ee of D){const q=ce(ee);q&&(F.push(q),!h&&typeof q._id=="string"&&N(e,q._id))}if(A===void 0)return n.with&&await ft({groupedCounter:et,fetcher:Ce,parents:F,...ht(n),schema:t,tableName:e,with:n.with}),{continueCursor:null,isDone:!0,page:dt(F,n.select,n.with)};const P=F.length>A,x=P?F.slice(0,A):F,Q=x.at(-1);return n.with&&await ft({fetcher:Ce,groupedCounter:et,parents:x,...ht(n),schema:t,tableName:e,with:n.with}),{continueCursor:P&&Q?Ge(Q,u):null,isDone:!P,page:dt(x,n.select,n.with)}},async get(e,n){const a=re(e,n);if(!a){const c=n===void 0?E:void 0;return c?c.get(e):null}return N(a.tableName,e),a.row},async lookupById(e,n){const a=re(e,n);return a?(N(a.tableName,e),{row:a.row,tableName:a.tableName}):null},async groupBy(e,n){const a=K(e,"groupBy");if(a)return N(e,U),a.groupBy(e,n);const c=t.tables[e];if(!c)throw new g("INTERNAL",`unknown table: ${e}`);N(e,U);const h=n.agg??{op:"count"};if(Re(h.op),h.op!=="count"&&!h.field)throw new g("INTERNAL",`groupBy(${e}, { agg: { op: "${h.op}" } }): "field" is required for non-count reducers`);const u=le(c.softDeleteMode,void 0),s=Y(Y(n.baseWhere,n.where),u),l=await $e(s,e,n.relationBaseWhere),p=l!==s,R=[...n.by,h.field];if(c.aggregateIndexes&&!n.baseWhere&&!p&&(!u||gt(c,R))){const x=Qt(c.aggregateIndexes,h.op,h.field,n.by,n.where),Q=x===void 0?0:Object.keys(x.partial).length,ee=x?.index.by?.length??0;if(x&&(Q===0||Q===ee)){Me(e,x.index);const q=Oe(e,x.index.name),ye=Object.keys(x.partial),Ne=[];if(ye.length===(x.index.by??[]).length&&ye.length>0){const _e=De(x.index.by??[],x.partial),Te=W(i,r`SELECT ${Ae} AS value, ${We} AS count FROM ${r.identifier(q)} WHERE ${xe} = ${_e}`).toArray();return Te.length>0&&Ne.push({key:{...x.partial},value:Le(h.op,Te[0])}),Ne}const Wt=W(i,r`SELECT ${xe} AS key, ${Ae} AS value, ${We} AS count FROM ${r.identifier(q)}`).toArray();for(const _e of Wt){const Te=Ht(JSON.parse(_e.key));Ne.push({key:Te,value:Le(h.op,_e)})}return Ne}}for(const x of R){if(x===void 0)continue;const Q=x===h.field?`groupBy(${e}, { agg: { op: "${h.op}", field: "${x}" } })`:`groupBy(${e}, { by: [..."${x}"] })`;bt(c,x,Q)}const $=te(l,oe),A=n.by.map(x=>r`${J(x)} AS ${r.identifier(x)}`);if(h.op==="count")A.push(r`COUNT(*) AS value`);else{const{field:x}=h;if(x===void 0)throw new g("INTERNAL",`groupBy(${e}, { agg: { op: "${h.op}" } }): "field" is required for non-count reducers`);A.push(r`${r.raw(Re(h.op))}(${J(x)}) AS value`)}let D=r`SELECT ${r.join(A,r`, `)} FROM ${r.identifier(e)}`;$&&(D=r`${D} WHERE ${$}`),D=r`${D} GROUP BY ${r.join(n.by.map(x=>J(x)),r`, `)}`;const F=W(i,D).toArray(),P=[];for(const x of F){const Q={};for(const q of n.by)Q[q]=x[q]??null;const{value:ee}=x;P.push({key:Q,value:ee==null?null:Number(ee)})}return P},async insert(e,n,a){const c=K(e,"insert");if(c)return ze(c,e,n,a,!0);const h=t.tables[e];if(!h)throw new g("INTERNAL",`unknown table: ${e}`);const u=yt(h,n,I);qe(h,u);let s;a?.clientId!==void 0?(Dn(a.clientId),s=a.clientId):a?.allowExplicitId&&typeof u._id=="string"?s=u._id:s=G();const l=a?.allowExplicitId&&typeof u._creationTime=="number"?u._creationTime:M(),p={...u,_creationTime:l,_id:s};return X(e,"before","insert")&&await Z("before","insert",{doc:{...p},id:s,op:"insert",table:e}),ue(e),fe(e),je(i,e,r`INSERT INTO ${r.identifier(e)} (id, _creationTime, ${r.identifier(H)}) VALUES (${s}, ${l}, ${se(p)})`),nt(e,s,p),X(e,"after","insert")&&await Z("after","insert",{doc:p,id:s,op:"insert",table:e}),await O({doc:p,id:s,op:"insert",table:e}),s},async insertManyUnsafe(e,n,a){if(de(n.length,a?.limit,"insertManyUnsafe"),n.length===0)return[];const c=K(e,"insert");if(c){const s=[];for(const l of n)v(l);for(const l of n){const p=await c.insert(e,l,{allowExplicitId:a?.allowExplicitId});d({key:p,op:"insert",row:{...l,_id:p},table:e}),s.push(p)}return s}const h=t.tables[e];if(!h)throw new g("INTERNAL",`unknown table: ${e}`);ue(e),fe(e);const u=n.map(s=>{const l=yt(h,s,I),p=a?.allowExplicitId===!0&&typeof l._id=="string"?l._id:G(),R=a?.allowExplicitId===!0&&typeof l._creationTime=="number"?l._creationTime:M();return{creationTime:R,document:{...l,_creationTime:R,_id:p},id:p}});for(const s of u)v(s.document);for(let s=0;s<u.length;s+=wt){const l=r.join(u.slice(s,s+wt).map(p=>r`(${p.id}, ${p.creationTime}, ${se(p.document)})`),r`, `);je(i,e,r`INSERT INTO ${r.identifier(e)} (id, _creationTime, ${r.identifier(H)}) VALUES ${l}`)}for(const{document:s,id:l}of u)nt(e,l,s),await T({doc:s,id:l,op:"insert",table:e});return u.map(s=>s.id)},async insertMany(e,n,a){de(n.length,a?.limit,"insertMany");const c=a?.skipDuplicates===!0,h=[],u=K(e,"insert");if(u)for(const l of n)v(l);const s=async l=>u?ze(u,e,l,void 0,!1):B.insert(e,l);for(const l of n)try{h.push(await s(l))}catch(p){if(c&&p instanceof pe&&p.kind==="unique")h.push(null);else throw p}return h},normalizeId(e,n){return Et(t,e,n)},async patch(e,n,a){const c=re(e,a);if(!c){const R=a===void 0?E:void 0;if(R){v(n),await R.patch(e,n);return}throw new g("INTERNAL",`document not found: ${e}`)}const{docJson:h,row:u,tableName:s}=c,l=t.tables[s];if(!l)throw new g("INTERNAL",`unknown table: ${s}`);N(s,e),_t("patch",n);const p={...u,...n,_id:e};Nt(l,n,p,I),qe(l,p,!0),X(s,"before","update")&&await Z("before","update",{doc:{...p},id:e,op:"update",previous:u,table:s}),ue(s),fe(s),Ie(i,s,r`UPDATE ${r.identifier(s)} SET ${r.identifier(H)} = ${se(p)} WHERE id = ${e} AND ${r.identifier(H)} = ${h}`),Ee(s,e,p,u),be(s,e,p),ge(s,u,p),he(s,e,u,p),L?.invalidate(s,e,f(s,u,p)),ne(s,e,"update",p),d({indexKeys:f(s,u,p),key:e,op:"update",row:p,table:s}),X(s,"after","update")&&await Z("after","update",{doc:p,id:e,op:"update",previous:u,table:s}),await O({doc:p,id:e,op:"update",table:s})},async patchMany(e,n,a){de(e.length,n?.limit,"patchMany");for(const c of e)await B.patch(c.id,c.patch,a);return{patched:e.length}},async patchWhere(e,n,a){const c=(await(K(e,"patchWhere")??B).findMany(e,{where:n.where})).page.map(h=>({id:String(h._id),patch:n.patch}));if(de(c.length,a?.limit,"patchWhere"),B.patchMany===void 0)throw new g("INTERNAL",`ctx.db.${e}.patchMany is unavailable: this writer has no batch patch`);return await B.patchMany(c,a),{patched:c.length}},query(e){const n=K(e,"query");return n?(N(e,U),n.query(e)):nr(i,t,e,_,a=>{a?w(a):N(e,U)},a=>{b||m?.recordRead(a)})},async rank(e,n,a){const c=K(e,"rank");if(c)return N(e,U),c.rank(e,n,a);_(e,n,"rank");const h=t.tables[e];if(!h)throw new g("INTERNAL",`unknown table: ${e}`);const u=h.rankIndexes?.find(q=>q.name===n);if(!u)throw new g("INTERNAL",`unknown rankIndex "${n}" on table "${e}"`);if(rt(e,h,u),a.restrictsCounts)throw new Fe(e);N(e,U),ke(e,u);const s=typeof a.row=="string"?a.row:a.row._id;if(!s)return null;const l=ct(e,u.name),p=u.sortBy.map((q,ye)=>lt(ye)),R=p.map(q=>bn(q)).join(", "),$=W(i,r`SELECT ${r.identifier("__partition__")}, ${r.raw(R)} FROM ${r.identifier(l)} WHERE ${r.identifier("__id__")} = ${s}`).toArray(),[A]=$;if(A===void 0)return null;let D=A.__partition__;const F=Y(a.baseWhere,a.where);Be(F,t,e,"rank");const P=dn(u,F);if(P){const q=ln(u.partitionBy??[],P);if(q!==D)return null;D=q}const x=p.map(q=>A[q]),{before:Q,total:ee}=Tt(i,l,p,u.sortBy,D,x,s);return{position:Q+1,total:ee}},async rankBefore(e,n,a){if(ae(e))throw new g("INTERNAL",`rankBefore is not supported on the global (.global()) table '${e}' — cross-shard rank cursors apply only to sharded tables`);const c=t.tables[e];if(!c)throw new g("INTERNAL",`unknown table: ${e}`);const h=c.rankIndexes?.find(p=>p.name===n);if(!h)throw new g("INTERNAL",`unknown rankIndex "${n}" on table "${e}"`);if(a.restrictsCounts)throw new Fe(e);N(e,U),ke(e,h);const u=ct(e,h.name),s=h.sortBy.map((p,R)=>lt(R)),l=h.sortBy.map((p,R)=>ie(a.sortValues[R]??null));return Tt(i,u,s,h.sortBy,a.partitionKey,l,a.rowId)},async rankPage(e,n,a={}){Be(Y(a.baseWhere,a.where),t,e,"rankPage");const c=K(e,"rankPage");if(c)return N(e,U),c.rankPage(e,n,a);_(e,n,"rank");const{continueCursor:h,hasMore:u,rows:s}=at(it,e,n,a);return{continueCursor:h,isDone:!u,page:s.map(l=>l.doc)}},async rankPageRows(e,n,a={}){Be(Y(a.baseWhere,a.where),t,e,"rankPage"),_(e,n,"rank");const{directions:c,hasMore:h,rows:u}=at(it,e,n,a);return{directions:c,hasMore:h,rows:u}},async restore(e,n){const a=re(e,n);if(!a){const u=n===void 0?E:void 0;if(u?.restore){await u.restore(e);return}throw new g("INTERNAL",`document not found: ${e}`)}const c=t.tables[a.tableName]?.softDeleteMode?.field;if(!c)throw new g("INTERNAL",`ctx.db.restore: table "${a.tableName}" is not a .softDelete() table`);const h=a.row[c]!==null&&a.row[c]!==void 0;await B.patch(e,{[c]:null},n),h&&he(a.tableName,e,void 0,a.row)},async replace(e,n,a,c){const h=re(e,a);if(!h){const A=a===void 0?E:void 0;if(A){v(n),await A.replace(e,n,void 0,c);return}throw new g("INTERNAL",`document not found: ${e}`)}const{docJson:u,row:s,tableName:l}=h,p=t.tables[l];if(!p)throw new g("INTERNAL",`unknown table: ${l}`);_t("replace",n);const R=c?.allowExplicitId&&typeof n._creationTime=="number"?n._creationTime:M(),$={...n,_creationTime:R,_id:e};Nt(p,n,$,I),qe(p,$),X(l,"before","update")&&await Z("before","update",{doc:{...$},id:e,op:"update",previous:s,table:l}),ue(l),fe(l),Ie(i,l,r`UPDATE ${r.identifier(l)} SET _creationTime = ${R}, ${r.identifier(H)} = ${se($)} WHERE id = ${e} AND ${r.identifier(H)} = ${u}`),Ee(l,e,$,s),be(l,e,$),ge(l,s,$),he(l,e,s,$),L?.invalidate(l,e,f(l,s,$)),ne(l,e,"update",$),d({indexKeys:f(l,s,$),key:e,op:"update",row:$,table:l}),X(l,"after","update")&&await Z("after","update",{doc:$,id:e,op:"update",previous:s,table:l}),await O({doc:$,id:e,op:"update",table:l})},async wipeShard(e){const n=new Set(e?.exclude),a=e?.tables,c=Object.entries(t.tables).filter(([l,p])=>n.has(l)||a!==void 0&&!a.includes(l)?!1:p.shardMode?.kind!=="global").map(([l])=>l);if(a!==void 0){for(const l of a)if(!t.tables[l])throw new g("INTERNAL",`wipeShard: unknown table: ${l}`)}const h={};let u=0;const{deleteAll:s}=B;if(s===void 0)throw new g("INTERNAL","wipeShard: this writer has no deleteAll");for(const l of c){const p=await s(l,{...e?.chunkSize===void 0?{}:{chunkSize:e.chunkSize},hard:!0});h[l]=p.deleted,u+=p.deleted}return{deleted:u,tables:h}}},Ft={db:B,scheduler:j};return o.enforceRls===!0?pn(B,t,(e,n)=>re(e,n)?.tableName,(e,n)=>Ot(e,n)):B};export{Ur as CDC_LOG_TABLE,Jr as CLIENT_WATERMARK_TABLE,to as GLOBAL_SHAPE_SNAPSHOT_TABLE,lo as IDEMPOTENCY_TABLE,Zn as NotUniqueError,$o as SEARCH_STATE_TABLE,Vr as advanceClientWatermark,Pr as applyCdcChanges,Dn as assertValidClientId,Fr as backfillAggregateIndexes,Wr as backfillRankIndexes,Br as backfillSearchIndexes,Hr as bumpCdcEpoch,Dr as createShardCtxDb,no as deleteGlobalShapeSnapshot,ro as deleteGlobalShapeSnapshotsForConnection,Xr as migrateClientWatermark,oo as migrateGlobalShapeSnapshot,Gr as minCdcSeq,Et as normalizeIdStructurally,jr as readCdcChanges,Qr as readCdcCursor,Kr as readCdcEpoch,Zr as readClientWatermark,io as readGlobalShapeSnapshot,co as readIdempotent,mo as runShardMigrations,go as selectShapeMemberIds,bo as selectShapeRows,Yr as trimCdcChanges,uo as trimIdempotent,ao as writeGlobalShapeSnapshot,fo as writeIdempotent};
1
+ import{LunoraError as g}from"@lunora/errors";import{n as Bt,S as qt,x as Qe,T as Se,y as Ut,c as Pt}from"./ctx-db-companions-BJlCofon.mjs";import{sql as r}from"drizzle-orm";import{s as Ht}from"./wire-codec-Dh0j-GnY.mjs";import{aggregateSqlFunction as Re,normalizeCountArgument as Gt,throwingScheduler as jt}from"./AGGREGATE_SQL_FUNCTION-CTo0-9iZ.mjs";import{encodeAggregateKey as De,readAggregateValue as Le,aggregateTableName as Oe}from"./aggregateTableName-DN7gk6uh.mjs";import{mergeWhere as Y,CountRlsUnsupportedError as Fe,selectIndexForGroupBy as Qt,selectIndexForCount as Kt,selectIndexForAggregate as Yt}from"./CountRlsUnsupportedError-8BqPYQoP.mjs";import{backfillSearchIndexesForTable as zt}from"./backfillAggregateIndexes-DTOIsYbi.mjs";import{backfillAggregateIndexes as Fr,backfillRankIndexes as Wr,backfillSearchIndexes as Br}from"./backfillAggregateIndexes-DTOIsYbi.mjs";import{appendCdcChange as Jt}from"./CDC_LOG_TABLE-DNFFQwF_.mjs";import{CDC_LOG_TABLE as Ur,applyCdcChanges as Pr,bumpCdcEpoch as Hr,minCdcSeq as Gr,readCdcChanges as jr,readCdcCursor as Qr,readCdcEpoch as Kr,trimCdcChanges as Yr}from"./CDC_LOG_TABLE-DNFFQwF_.mjs";import{computeRankPage as at}from"./computeRankPage-BU8LXvQs.mjs";import{SCAN_DEP as U}from"./SCAN_DEP-D_yR9EeV.mjs";import{runDrizzle as W}from"./runDrizzle-C3n5gJsk.mjs";import{a as H,L as se,p as Ae,T as We,c as xe,N as J,E as ce,I as St,C as Vt,D as Rt,h as Xt,O as st}from"./do-sql-DKSFK627.mjs";import{WORKERD_SQLITE_LIMITS as At,unionAll as Pe,sqliteInList as Zt}from"./param-CYxL68V-.mjs";import{coveringGeohashes as en,boundingBoxGeohashes as tn,pointInBoundingBox as nn,haversineMeters as rn}from"./GEO_DEFAULT_PRECISION-DyI5zggj.mjs";import{NotFoundError as on}from"./NotFoundError-BhF7FeFr.mjs";import{normalizeOrderKeys as an,buildSeekWhere as xt,decodeCursor as He,applySelect as dt,encodeCursor as Ge,softDeleteScope as le,buildSeekBeforeWhere as sn}from"./applySelect-5w13bMAR.mjs";import{sortColumnName as lt,resolveRankPartition as dn,encodePartitionKey as ln,RANK_TIEBREAK as cn,rankTableName as ct}from"./RANK_TIEBREAK-BGk411OR.mjs";import{indexKeysForRow as un,buildIndexRange as fn}from"./buildIndexRange-DFsdtPjD.mjs";import{assertFlatPredicate as Be,resolveRelationPredicates as ut}from"./DEFAULT_MAX_RELATION_KEYS-BV1RCoat.mjs";import{runRowValidators as qe,resolveWith as ft,relationHooks as ht,applyOnDelete as hn,fanOutScalarCounts as mn}from"./applyOnDelete-crbAzVfE.mjs";import{guardWriter as pn}from"./RLS_UNWRAP_SYMBOL-DcqORh2s.mjs";import{f as $n}from"./sql-projection-jfoe331H.mjs";import{createSystemReader as wn}from"./createSystemReader-DcDcrtM3.mjs";import{ConflictError as pe}from"./ConflictError-C8GtJmjS.mjs";import{runTriggers as gn}from"./hasTrigger-CbkOHExZ.mjs";import{compileWhereSql as te}from"./compileWhereSql-B3hq_v98.mjs";import{CLIENT_WATERMARK_TABLE as Jr,advanceClientWatermark as Vr,migrateClientWatermark as Xr,readClientWatermark as Zr}from"./CLIENT_WATERMARK_TABLE-LrKfdxyt.mjs";import{GLOBAL_SHAPE_SNAPSHOT_TABLE as to,deleteGlobalShapeSnapshot as no,deleteGlobalShapeSnapshotsForConnection as ro,migrateGlobalShapeSnapshot as oo,readGlobalShapeSnapshot as io,writeGlobalShapeSnapshot as ao}from"./GLOBAL_SHAPE_SNAPSHOT_TABLE-B2LKe4KU.mjs";import{IDEMPOTENCY_TABLE as lo,readIdempotent as co,trimIdempotent as uo,writeIdempotent as fo}from"./IDEMPOTENCY_TABLE-tQ5mnqvw.mjs";import{runShardMigrations as mo}from"./runShardMigrations-C1mjoJS4.mjs";import{SEARCH_STATE_TABLE as $o}from"./SEARCH_STATE_TABLE-DRk_SB72.mjs";import{selectShapeMemberIds as go,selectShapeRows as bo}from"./selectShapeMemberIds-Bkkug6vU.mjs";import{serializeSqlValue as ie}from"./serializeSqlValue-BR4UOWoP.mjs";import{quoteIdentifier as bn}from"./quoteIdentifier-CObIFRhb.mjs";const En=o=>{const i=new TextEncoder().encode(o);let t="";for(const d of i)t+=String.fromCodePoint(d);return btoa(t)},yn=o=>{const i=atob(o),t=Uint8Array.from(i,d=>d.codePointAt(0)??0);return new TextDecoder().decode(t)},Nn=()=>new g("BAD_REQUEST","invalid cursor"),mt=16,pt=8,V=1024,Ke=(o,i)=>i.query(o),_n=(o,i,t)=>{const d=Bt(o,t);if(d.length===0)return 0;let f=0;for(const[m,b]of i.entries()){const S=m===i.length-1;let y=0;for(const w of d)(S?w.startsWith(b):w===b)&&(y+=1);if(y===0)return 0;f+=y}return f},Tn=(o,i)=>{if(!i)return{exact:!0,lower:o,upper:o};const t=[...o].at(-1)??"",d=(t.codePointAt(0)??0)+1;if(d>=55296&&d<=57343||d>1114111)return{exact:!0,lower:o,upper:o};const f=o.slice(0,o.length-t.length);return{exact:!1,lower:o,upper:f+String.fromCodePoint(d)}},Sn=(o,i,t)=>{const d={eq:(f,m)=>{if(!o.definition.filterFields?.includes(f))throw new g("INTERNAL",`field "${f}" is not a filter field of search index "${o.indexName}" on table "${i}"`);if(o.filters.length>=pt)throw new g("BAD_REQUEST",`search index "${o.indexName}" on table "${i}": at most ${String(pt)} .eq() filters are supported per search query`);return o.filters.push({field:f,value:m}),d},search:(f,m)=>{const b=o;if(f!==b.definition.field)throw new g("INTERNAL",`search index "${b.indexName}" on table "${i}" indexes "${b.definition.field}", not "${f}"`);const S=Ke(m,t).length;if(S>mt)throw new g("BAD_REQUEST",`search index "${b.indexName}" on table "${i}": at most ${String(mt)} search terms are supported (got ${String(S)})`);return b.field=f,b.query=m,b.hasQuery=!0,d}};return d},Rn=o=>{if(o.length>V)throw new g("BAD_REQUEST",`more than ${String(V)} documents match this search — narrow it with filters or read it a page at a time with .paginate()`)},An=o=>Math.min(o.offset+o.numItems+1,V),xn=o=>En(`search:${String(o)}`),In=o=>{let i;try{i=yn(o)}catch{return}if(!i.startsWith("search:"))return;const t=Number(i.slice(7));return Number.isInteger(t)&&t>=0?t:void 0},vn=o=>{if(typeof o.endCursor=="string")throw new g("BAD_REQUEST","bounded (endCursor) pagination is not supported on search queries — relevance order has no stable range boundary");const i=Math.max(0,Math.floor(o.numItems)),t=o.cursor?In(o.cursor):0;if(t===void 0)throw Nn();if(t+i>V)throw new g("BAD_REQUEST",`search pagination reaches past the ${String(V)}-document limit (offset ${String(t)} + ${String(i)} requested) — narrow the query or the filters instead`);return{numItems:i,offset:t}},Cn=(o,i)=>{const t=i.offset+i.numItems,d=i.numItems>0&&o.length>t;return{continueCursor:d?xn(t):null,isDone:!d,page:o.slice(i.offset,t)}},Mn=o=>{if(o===void 0)return V+1;if(!Number.isFinite(o))return V;const i=Math.max(0,Math.floor(o));if(i>V)throw new g("BAD_REQUEST",`search returns at most ${String(V)} documents (asked for ${String(i)}) — narrow the query or paginate instead`);return i},kn=/^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/iu,Dn=o=>{if(!kn.test(o))throw new g("INTERNAL",`invalid clientId ${JSON.stringify(o)}: a client-supplied row id must be a UUID`)},$t=50,It=500,wt=Math.floor(At.boundParams/3),me=At.boundParams,Ln=128,de=(o,i,t)=>{const d=i??It;if(o>d)throw new g("BATCH_LIMIT_EXCEEDED",`${t}: batch of ${String(o)} exceeds the limit of ${String(d)} (raise options.limit or chunk the call)`,{status:400})},On=o=>{const i={eq:(t,d)=>(o.sqlConditions.push({comparator:"=",field:t,value:d}),i),gt:(t,d)=>(o.sqlConditions.push({comparator:">",field:t,value:d}),i),gte:(t,d)=>(o.sqlConditions.push({comparator:">=",field:t,value:d}),i),lt:(t,d)=>(o.sqlConditions.push({comparator:"<",field:t,value:d}),i),lte:(t,d)=>(o.sqlConditions.push({comparator:"<=",field:t,value:d}),i)};return i},Fn=o=>Math.max(o,V),vt=(o,i)=>{const t=o.filters.map(d=>r`${J(d.field)} = ${ie(d.value)}`);return i&&t.push(i),t},Wn=(o,i,t,d,f)=>{const m=Ke(t.query,Qe(t.definition.language));if(m.length===0)return[];const b=Pt(i,t.indexName),S=`${b}__vocab`,y=m.length-1,w=m.map((L,M)=>{const G=Tn(L,M===y),j=G.exact?r`${r.identifier("term")} = ${G.lower}`:r`${r.identifier("term")} >= ${G.lower} AND ${r.identifier("term")} < ${G.upper}`;return r`SELECT ${r.identifier("doc")}, ${r.raw(String(M))} AS ${r.identifier("__term__")}, COUNT(*) AS ${r.identifier("__n__")} FROM ${r.identifier(S)} WHERE ${j} GROUP BY ${r.identifier("doc")}`}),N=m.map((L,M)=>r`SUM(CASE WHEN u.${r.identifier("__term__")} = ${r.raw(String(M))} THEN u.${r.identifier("__n__")} ELSE 0 END)`),_=r`SELECT f.${r.identifier(Se)} AS ${r.identifier(Se)}, ${r.join(N,r` + `)} AS ${r.identifier("__score__")} FROM (${Pe(w)}) u JOIN ${r.identifier(b)} f ON f.rowid = u.${r.identifier("doc")} GROUP BY f.${r.identifier(Se)} HAVING ${r.join(N.map(L=>r`${L} > 0`),r` AND `)}`,T=vt(t,f);let v=r`SELECT m.id, m._creationTime, m.${r.identifier(H)}, s.${r.identifier("__score__")} AS ${r.identifier("__score__")} FROM (${_}) s JOIN ${r.identifier(i)} m ON m.id = s.${r.identifier(Se)}`;T.length>0&&(v=r`${v} WHERE ${r.join(T,r` AND `)}`),v=r`${v} ORDER BY s.${r.identifier("__score__")} DESC, m._creationTime DESC, m.id ASC LIMIT ${r.raw(String(d))}`;const O=[];for(const L of W(o,v)){const M=Rt(L);if(M){const G=L.__score__;O.push({document:M,score:typeof G=="number"?G:Number(G??0)})}}return O},Bn=(o,i,t,d,f)=>{const m=Qe(t.definition.language),b=Ke(t.query,m);if(b.length===0)return[];const S=vt(t,f);let y=r`SELECT id, _creationTime, ${r.identifier(H)} FROM ${r.identifier(i)}`;S.length>0&&(y=r`${y} WHERE ${r.join(S,r` AND `)}`),y=r`${y} ORDER BY _creationTime DESC, id ASC LIMIT ${r.raw(String(Fn(d)))}`;const w=W(o,y).toArray(),N=[];for(const _ of w){const T=Rt(_);if(!T)continue;const v=_n(Ut(T,t.definition),b,m);v>0&&N.push({creationTime:typeof T._creationTime=="number"?T._creationTime:0,doc:T,id:typeof T._id=="string"?T._id:"",score:v})}return N.sort((_,T)=>T.score-_.score||T.creationTime-_.creationTime||_.id.localeCompare(T.id)),N.slice(0,d).map(_=>({document:_.doc,score:_.score}))},Ue=(o,i,t,d)=>{if(!Number.isFinite(o.lat)||o.lat<-90||o.lat>90||!Number.isFinite(o.lng)||o.lng<-180||o.lng>180)throw new g("BAD_REQUEST",`geo index "${d}" on table "${t}": ${i} must have a finite lat in [-90, 90] and lng in [-180, 180]`)},qn=(o,i)=>{const t=o,d={near:(f,m)=>{if(t.within)throw new g("INTERNAL",`geo index "${t.indexName}" on table "${i}": call .near() or .within(), not both`);if(Ue(f,".near() point",i,t.indexName),!Number.isFinite(m)||m<=0)throw new g("BAD_REQUEST",`geo index "${t.indexName}" on table "${i}": .near() radiusMeters must be a finite number > 0, got ${String(m)}`);return t.near={point:{lat:f.lat,lng:f.lng},radiusMeters:m},d},within:f=>{if(t.near)throw new g("INTERNAL",`geo index "${t.indexName}" on table "${i}": call .near() or .within(), not both`);if(Ue(f.sw,".within() sw corner",i,t.indexName),Ue(f.ne,".within() ne corner",i,t.indexName),f.sw.lat>f.ne.lat)throw new g("BAD_REQUEST",`geo index "${t.indexName}" on table "${i}": .within() corners are transposed (sw.lat > ne.lat)`);if(f.sw.lng>f.ne.lng)throw new g("BAD_REQUEST",`geo index "${t.indexName}" on table "${i}": .within() box crosses the antimeridian (sw.lng > ne.lng), which is not supported — split it into two boxes at ±180 and union the results`);return t.within={ne:{lat:f.ne.lat,lng:f.ne.lng},sw:{lat:f.sw.lat,lng:f.sw.lng}},d}};return d},Un=(o,i)=>{const t=o[i];if(t===null||typeof t!="object")return;const{lat:d,lng:f}=t;return typeof d=="number"&&typeof f=="number"?{lat:d,lng:f}:void 0},Pn=(o,i)=>{const t=Un(o,i.definition.field);if(!t)return;const d=typeof o._creationTime=="number"?o._creationTime:0;if(i.near){const f=rn(i.near.point,t);return f<=i.near.radiusMeters?{creationTime:d,distance:f}:void 0}return nn(t,i.within)?{creationTime:d,distance:0}:void 0},Hn=(o,i,t,d)=>{if(!t.near&&!t.within)throw new g("INTERNAL",`geo index "${t.indexName}" on table "${i}": call .near(point, radius) or .within(box)`);const f=t.near?en(t.near.point,t.near.radiusMeters):tn(t.within),m=Xt(i,t.indexName),b=f.map(_=>r`(g.${r.identifier("__geohash__")} >= ${_} AND g.${r.identifier("__geohash__")} < ${`${_}{`})`),S=[r`(${r.join(b,r` OR `)})`];d&&S.push(d);const y=r`SELECT m.id, m._creationTime, m.${r.identifier(H)} FROM ${r.identifier(m)} g JOIN ${r.identifier(i)} m ON m.id = g.${r.identifier("__id__")} WHERE ${r.join(S,r` AND `)}`,w=W(o,y).toArray(),N=[];for(const _ of w){const T=ce(_),v=T?Pn(T,t):void 0;T&&v&&N.push({creationTime:v.creationTime,distance:v.distance,doc:T})}return N.sort((_,T)=>_.distance-T.distance||T.creationTime-_.creationTime),N},Ct=(o,i,t,d)=>{const f=[];for(const m of o)if(i.every(b=>b(d(m)))&&(f.push(m),typeof t=="number"&&f.length>=t))break;return f},Gn=(o,i,t,d,f,m=()=>{})=>{const b=t.within!==void 0,S=Hn(o,i,t,f).map(y=>({distanceMeters:b?null:y.distance,document:y.doc}));return m(S.length),typeof d=="number"?S.slice(0,Math.max(0,Math.floor(d))):S},Mt=(o,i,t,d,f,m=()=>{})=>{const{geo:b}=t;if(!b)throw new g("INTERNAL","runGeoTerminalScored called without a staged geo query");const S=t.inMemoryFilters.length>0,y=Gn(o,i,b,S?void 0:f,d,m);return S?Ct(y,t.inMemoryFilters,f,w=>w.document):y},jn=(o,i,t,d,f,m=()=>{})=>Mt(o,i,t,d,f,m).map(b=>b.document),Qn=(o,i,t,d,f,m,b=()=>{})=>{const S=[];for(const _ of t.sqlConditions)S.push(r`${J(_.field)} ${r.raw(_.comparator)} ${ie(_.value)}`);d&&S.push(d);let y=r`SELECT id, _creationTime, ${r.identifier(H)} FROM ${r.identifier(i)}`;S.length>0&&(y=r`${y} WHERE ${r.join(S,r` AND `)}`),y=r`${y} ORDER BY ${f}`,typeof m=="number"&&t.inMemoryFilters.length===0&&(y=r`${y} LIMIT ${r.raw(String(Math.max(0,Math.floor(m))))}`);const w=W(o,y).toArray();b(w.length);const N=[];for(const _ of w){const T=ce(_);if(T&&t.inMemoryFilters.every(v=>v(T))&&(N.push(T),typeof m=="number"&&N.length>=m))break}return N},oe={fieldRef:J,serialize:ie},kt=(o,i)=>{const t=i===void 0?void 0:o.shape[i];return t!==void 0&&$n(t)},gt=(o,i)=>i.some(t=>kt(o,t)),bt=(o,i,t)=>{if(kt(o,i))throw new g("BAD_REQUEST",`${t}: "${i}" is stored as an order-preserving key, which SQL cannot reduce or group — declare an aggregateIndex covering this (by, field, op) so the maintained companion answers it`)},Kn=o=>{let i=0;const t=[],d={fieldRef:J,relationExists:f=>{const{childWhere:m,negated:b,parentTable:S,relation:y}=f,w=`__rel_${String(i)}`,N=t.at(-1)??S;i+=1,o(y.table,U);const _=y.kind==="one"?y.field:y.references,T=y.kind==="one"?y.references:y.field,v=r`${st(w,T)} = ${st(N,_)}`;t.push(w);const O=te(m,d);t.pop();const L=O?r`${v} AND ${O}`:v,M=r`EXISTS (SELECT 1 FROM ${r.identifier(y.table)} AS ${r.identifier(w)} WHERE ${L})`;return b?r`NOT ${M}`:M},serialize:ie};return d},Dt=o=>{const i=o.map(t=>r`${J(t.field)} ${r.raw(t.direction==="desc"?"DESC":"ASC")}`);return o.some(t=>t.field==="_id"||t.field==="id")||i.push(r`${J("id")} ASC`),r.join(i,r`, `)},Yn={"<":"lt","<=":"lte","=":"eq",">":"gt",">=":"gte"},zn=o=>{const i=o.order;return o.indexFields.length>0?o.indexFields.map(t=>({direction:i,field:t})):[{direction:i,field:"_creationTime"}]},Jn=(o,i,t,d)=>{const f=o.sqlConditions.map(m=>({[m.field]:{[Yn[m.comparator]??"eq"]:m.value}}));if(t&&f.push(xt(i,He(t))),d&&f.push(sn(i,He(d))),f.length!==0)return f.length===1?f[0]:{AND:f}},Vn=(o,i,t)=>{const d=[];for(const f of o){const m=ce(f);if(m&&i.every(b=>b(m))&&(d.push(m),t!==void 0&&d.length>t))break}return d},Xn=(o,i,t,d,f,m=()=>{})=>{const b=Math.max(0,Math.floor(d.numItems)),S=zn(t),y=typeof d.endCursor=="string",w=te(Jn(t,S,d.cursor,d.endCursor),oe),N=f&&w?r`${w} AND ${f}`:f??w;let _=r`SELECT id, _creationTime, ${r.identifier(H)} FROM ${r.identifier(i)}`;N&&(_=r`${_} WHERE ${N}`),_=r`${_} ORDER BY ${Dt(S)}`;const T=t.inMemoryFilters.length>0;!T&&!y&&(_=r`${_} LIMIT ${r.raw(String(b+1))}`);const v=W(o,_).toArray();m(v.length);const O=Vn(v,t.inMemoryFilters,T||y?void 0:b);if(y){const j=O.length>=2?O[Math.floor(O.length/2)-1]:void 0;return{continueCursor:d.endCursor??null,isDone:!0,page:O,splitCursor:j?Ge(j,S):null}}const L=O.length>b,M=L?O.slice(0,b):O,G=M.at(-1);return{continueCursor:L&&G?Ge(G,S):null,isDone:!L,page:M}};class Zn extends g{constructor(i="unique() found more than one matching document"){super("NOT_UNIQUE",i,{name:"NotUniqueError"})}}const er=/\s/u,tr=String.fromCodePoint(0),Et=(o,i,t)=>{if(!o.tables[i])throw new g("INTERNAL",`unknown table: ${i}`);return typeof t!="string"||t.length===0||er.test(t)||t.includes(tr)?null:t},nr=(o,i,t,d=()=>{},f=()=>{},m=()=>{})=>{const b=i.tables[t];if(!b)throw new g("INTERNAL",`unknown table: ${t}`);const S=le(b.softDeleteMode,void 0),y=S?te(S,oe):void 0,w={indexFields:[],indexName:void 0,inMemoryFilters:[],order:"asc",sqlConditions:[]};let N=0;const _=E=>{const{search:I}=w;if(!I)throw new g("INTERNAL","runSearchFetch called without a staged search");zt(o,t,b);const C=w.inMemoryFilters.length>0,k=Mn(C?void 0:E),z=Vt(o)?Wn(o,t,I,k,y):Bn(o,t,I,k,y);return C?(N=z.length,Ct(z,w.inMemoryFilters,E,ne=>ne.document)):(E===void 0&&Rn(z),z)},T=E=>_(E).map(I=>I.document),v=E=>{const I=vn(E);return Cn(T(An(I)),I)},O=()=>{const E=w.indexFields.length>0?w.indexFields:["_creationTime"],I=w.order==="desc"?"DESC":"ASC";return r.join(E.map(C=>r`${J(C)} ${r.raw(I)}`),r`, `)},L=()=>{if(w.search||w.geo||w.indexName===void 0){f(void 0);return}f(fn(t,w.indexName,w.indexFields,w.sqlConditions,ie))},M=E=>{L();let I=0;const C=(()=>{if(w.search){const k=T(E);return I=N,k}return w.geo?jn(o,t,w,y,E,k=>{I=k}):Qn(o,t,w,y,O(),E,k=>{I=k})})();return m(Math.max(I,C.length)),C},G=()=>{if(!w.search&&!w.geo)throw new g("INTERNAL",`ctx.db.query("${t}").collectWithScores() requires a staged .withSearchIndex(...) or .withGeoIndex(...)`);L();let E=0;const I=(()=>{if(w.search){const C=_(void 0);return E=N,C}return Mt(o,t,w,y,void 0,C=>{E=C})})();return m(Math.max(E,I.length)),I},j={async*[Symbol.asyncIterator](){const E=[...w.inMemoryFilters];let I;w.inMemoryFilters=[];try{for(;;){const C=await j.paginate({cursor:I??null,numItems:Ln});for(const k of C.page)E.every(z=>z(k))&&(yield k);if(C.isDone||C.continueCursor===null)return;I=C.continueCursor}}finally{w.inMemoryFilters=E}},async collect(){return M(void 0)},async collectWithScores(){return G()},filter(E){return w.inMemoryFilters.push(E),j},async first(){return M(w.inMemoryFilters.length>0?void 0:1)[0]??null},order(E){return w.order=E==="desc"?"desc":"asc",j},async paginate(E){let I=0;if(L(),w.search){const k=v(E);return m(k.page.length),k}if(w.geo)throw new g("INTERNAL","pagination is not supported on geo queries; use .take(n) or .collect()");const C=Xn(o,t,w,E,y,k=>{I=k});return m(Math.max(I,C.page.length)),C},async take(E){return M(E)},async unique(){const E=M(w.inMemoryFilters.length>0?void 0:2);if(E.length>1)throw new Zn(`unique() on table "${t}" matched ${String(E.length)} documents; expected at most one`);return E[0]??null},withGeoIndex(E,I){const C=(b.geoIndexes??[]).find(z=>z.name===E);if(!C)throw new g("INTERNAL",`unknown geo index "${E}" on table "${t}"`);d(t,E,"geo");const k={definition:C,indexName:E};if(w.geo=k,I(qn(k,t)),!k.near&&!k.within)throw new g("INTERNAL",`geo index "${E}" on table "${t}" requires a .near(point, radius) or .within(box) call`);return j},withIndex(E,I){const C=b.indexes.find(k=>k.name===E);if(!C)throw new g("INTERNAL",`unknown index "${E}" on table "${t}"`);return d(t,E,"index"),w.indexName=E,w.indexFields=C.fields,I&&I(On(w)),j},withSearchIndex(E,I){const C=(b.searchIndexes??[]).find(z=>z.name===E);if(!C)throw new g("INTERNAL",`unknown search index "${E}" on table "${t}"`);d(t,E,"search");const k={definition:C,field:C.field,filters:[],hasQuery:!1,indexName:E,query:""};if(w.search=k,I(Sn(k,t,Qe(C.language))),!k.hasQuery)throw new g("INTERNAL",`search index "${E}" on table "${t}" requires a .search(field, query) call`);return j}};return j},yt=(o,i,t)=>{const d={...i};for(const[f,m]of St(o)){if(m.serverDefault){d[f]=m.serverDefault({auth:t});continue}d[f]===void 0&&(m.defaultFn?d[f]=m.defaultFn():"defaultValue"in m&&(d[f]=m.defaultValue))}return d},Nt=(o,i,t,d)=>{const f=t;for(const[m,b]of St(o)){if(b.serverDefault){m in i&&(f[m]=b.serverDefault({auth:d}));continue}b.onUpdateFn&&!(m in i)&&(f[m]=b.onUpdateFn())}},_t=(o,i)=>{for(const t of Object.keys(i))if(i[t]===void 0)throw new g("INTERNAL",`Cannot ${o} field '${t}' to undefined — use null to clear a nullable field, or omit the key to leave it unchanged.`)},rr=/unique constraint failed/i,or=o=>o instanceof Error&&rr.test(o.message),je=(o,i,t)=>{try{W(o,t)}catch(d){throw or(d)?new pe(`unique constraint violation on "${i}"`,"unique"):d}},Ie=(o,i,t)=>{if(je(o,i,t),W(o,r`SELECT changes() AS changed`).one().changed===0)throw new pe(`optimistic concurrency conflict on "${i}" — the row changed during this mutation; refetch and retry`,"occ")},Tt=(o,i,t,d,f,m,b)=>{const S=[];for(let _=0;_<t.length+1;_+=1){const T=[];for(let M=0;M<_;M+=1)T.push(r`${r.identifier(t[M])} IS ${m[M]}`);const v=t[_],O=d[_];if(v!==void 0&&O!==void 0){const M=O.direction==="desc"?">":"<";T.push(r`${r.identifier(v)} ${r.raw(M)} ${m[_]}`)}else T.push(r`${r.identifier(cn)} < ${b}`);const[L]=T;S.push(T.length===1&&L!==void 0?L:r`(${r.join(T,r` AND `)})`)}const y=r.join(S,r` OR `),w=W(o,r`SELECT COUNT(*) AS c FROM ${r.identifier(i)} WHERE ${r.identifier("__partition__")} = ${f} AND (${y})`).one(),N=W(o,r`SELECT COUNT(*) AS c FROM ${r.identifier(i)} WHERE ${r.identifier("__partition__")} = ${f}`).one();return{before:w.c,total:N.c}},Dr=o=>{const{sql:i}=o,{schema:t}=o,d=o.broadcast??(()=>{}),f=(e,...n)=>{const a=t.tables[e]?.indexes;if(!a||a.length===0)return;const c=[];for(const h of n)h&&c.push(...un(a,h,ie));return c.length>0?c:void 0},{headroom:m}=o;let b=!1;const S=async e=>{const n=b;b=!0;try{return await e()}finally{b=n}},y=o.onRead??(()=>{}),w=o.onReadRange??(e=>{y(e.table,U)}),N=(e,n)=>{n!==void 0&&n!==U&&!b&&m?.recordRead(1),y(e,n)},_=o.onIndexUse??(()=>{}),T=o.onWrite??(()=>{}),v=e=>{b||m?.recordWrite(e)},O=async e=>{v(e.doc),await T(e)},{cache:L}=o,M=o.clock??(()=>Date.now()),G=o.idGenerator??(()=>crypto.randomUUID()),j=o.scheduler??jt,{globalDb:E}=o,I=o.auth??{identity:null,userId:null},C=o.cdc??!1,k=j,z=wn({scheduler:typeof k.list=="function"&&typeof k.get=="function"?k:void 0,storage:o.storage}),ne=(e,n,a,c)=>{C&&Jt(i,M(),e,n,a,c)},ae=e=>t.tables[e]?.shardMode?.kind==="global",Ye=(e,n)=>{if(ae(e)){if(!E)throw new g("INTERNAL",`cross-backend ${n} for global table '${e}' requires a globalDb writer — pass one to createShardCtxDb({ globalDb })`);return E}return B},ve=e=>Ye(e,"cascade"),K=(e,n)=>{if(ae(e)){if(!E)throw new g("INTERNAL",`${n} on global table '${e}' requires a globalDb writer — pass one to createShardCtxDb({ globalDb })`);return E}},ze=async(e,n,a,c,h)=>{h&&v(a);const u=await e.insert(n,a,c);return d({key:u,op:"insert",row:{...a,_id:u},table:n}),u},Ce=(e,n)=>Ye(e,"relation load").findMany(e,n),Je=(e,n)=>(ae(e)&&N(e,U),Ce(e,n)),Lt=e=>!ae(e.table),Ve=o.relationExistsPushDown??"auto",Xe=Ve!=="never",{maxRelationKeys:Ze}=o,$e=(e,n,a)=>ut(e,{fetcher:Je,maxRelationKeys:Ze,relationBaseWhere:a,schema:t,tableName:n}),et=async(e,n,a,c)=>{const h=K(e,"relation grouped count");if(h)return N(e,U),mn((P,x)=>h.count(P,x),e,n,a,c);const u=t.tables[e];if(!u)throw new g("INTERNAL",`unknown table: ${e}`);N(e,U);const s=le(u.softDeleteMode,void 0),l={[n]:{in:a}},p=Y(Y(l,c),s),R=await $e(p,e,void 0),$=te(R,oe),A=J(n);let D=r`SELECT ${A} AS __fk__, COUNT(*) AS count FROM ${r.identifier(e)}`;$&&(D=r`${D} WHERE ${$}`),D=r`${D} GROUP BY ${A}`;const F=W(i,D).toArray();return new Map(F.map(P=>[P.__fk__,P.count]))};let we=0;const tt=new Set;for(const[e,n]of Object.entries(t.tables))for(const a of Object.values(n.triggerMap??{}))tt.add(`${e} ${a.timing} ${a.op}`);const X=(e,n,a)=>tt.has(`${e} ${n} ${a}`),Z=async(e,n,a)=>{if(we+=1,we>$t)throw we-=1,new pe(`trigger recursion exceeded ${String($t)} levels on "${a.table}" — check for a self-triggering write`,"trigger");try{await gn({ctx:Ft,event:a,op:n,schema:t,tableName:a.table,timing:e})}finally{we-=1}},{ensureBackfilledForTable:ue,ensureBackfilledIndex:Me,ensureRankBackfilled:ke,ensureRankBackfilledForTable:fe,syncAggregates:ge,syncCompanionsForInsert:nt,syncGeo:be,syncRanks:he,syncSearch:Ee}=qt({broadcast:d,indexKeysFor:(e,n)=>f(e,n),invalidateCache:(e,n,a)=>L?.invalidate(e,n,f(e,a)),recordCdc:ne,schema:t,sql:i}),rt=(e,n,a)=>{const{shardMode:c}=n;if(c?.kind==="shardBy"&&!(c.field!==void 0&&(a.partitionBy??[]).includes(c.field)))throw Object.assign(new Error(`rank index "${a.name}" on "${e}" partitions across shards (shard key "${c.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})},ot=e=>Object.entries(t.tables).filter(([,n])=>n.shardMode?.kind!=="global").map(([n])=>n).filter(n=>e===void 0||n===e),re=(e,n)=>{const a=ot(n);for(let c=0;c<a.length;c+=me){const h=a.slice(c,c+me).map(R=>r`SELECT ${r.raw(`'${R.replaceAll("'","''")}'`)} AS __t__, id, _creationTime, ${r.identifier(H)} FROM ${r.identifier(R)} WHERE id = ${e}`),[u]=W(i,r`${Pe(h)} LIMIT 1`).toArray();if(!u)continue;const s=u.__t__,l=ce(u);if(typeof s!="string"||!l)return;const p=u[H];return{docJson:typeof p=="string"?p:se(p??{}),row:l,tableName:s}}},Ot=(e,n)=>{const a=[...new Set(e)],c=new Map;if(a.length===0)return c;const h=ot(n);for(let u=0;u<h.length;u+=me){const s=h.slice(u,u+me),l=Math.floor(me/s.length),p=Zt(r`${r.identifier("id")}`,a,!1,l),R=s.map($=>r`SELECT ${r.raw(`'${$.replaceAll("'","''")}'`)} AS __t__, id FROM ${r.identifier($)} WHERE ${p}`);for(const $ of W(i,Pe(R))){const{id:A,__t__:D}=$;typeof D=="string"&&typeof A=="string"&&c.set(A,D)}}return c},it={assertRankPartitionLocal:rt,ensureRankBackfilled:ke,onRead:N,rowToDocument:ce,schema:t,sql:i},B={system:z,async aggregate(e,n){const a=K(e,"aggregate");if(a)return N(e,U),a.aggregate(e,n);const c=t.tables[e];if(!c)throw new g("INTERNAL",`unknown table: ${e}`);if(Re(n.op),n.op==="count")return B.count(e,{baseWhere:n.baseWhere,relationBaseWhere:n.relationBaseWhere,restrictsCounts:n.restrictsCounts,where:n.where});if(!n.field)throw new g("INTERNAL",`aggregate(${e}, { op: "${n.op}" }): "field" is required for non-count reducers`);N(e,U);const h=le(c.softDeleteMode,void 0),u=Y(Y(n.baseWhere,n.where),h),s=await $e(u,e,n.relationBaseWhere),l=s!==u;if(c.aggregateIndexes&&!n.baseWhere&&!l&&(!h||gt(c,[n.field]))){const F=Yt(c.aggregateIndexes,n.op,n.field,n.where);if(F){Me(e,F.index);const P=De(F.index.by??[],F.key),x=Oe(e,F.index.name),Q=W(i,r`SELECT ${Ae} AS value, ${We} AS count FROM ${r.identifier(x)} WHERE ${xe} = ${P}`).toArray()[0];return Le(n.op,Q)}}bt(c,n.field,`aggregate(${e}, { op: "${n.op}", field: "${n.field}" })`);const p=te(s,oe),R=Re(n.op),$=J(n.field);let A=r`SELECT ${r.raw(R)}(${$}) AS value FROM ${r.identifier(e)}`;return p&&(A=r`${A} WHERE ${p}`),W(i,A).toArray()[0]?.value??null},asId(e,n){const a=Et(t,e,n);if(a===null)throw new g("BAD_REQUEST",`asId("${e}", …): "${n}" is not a valid id for table "${e}"`,{status:400});return a},async count(e,n){const a=K(e,"count");if(a)return N(e,U),a.count(e,n);const c=t.tables[e];if(!c)throw new g("INTERNAL",`unknown table: ${e}`);const h=Gt(n);if(h.restrictsCounts)throw new Fe(e);N(e,U);const u=le(c.softDeleteMode,void 0),s=Y(Y(h.baseWhere,h.where),u),l=await $e(s,e,h.relationBaseWhere),p=l!==s;if(c.aggregateIndexes&&!h.baseWhere&&!p&&!u){const A=Kt(c.aggregateIndexes,h.where);if(A){Me(e,A.index);const D=De(A.index.by??[],A.key),F=Oe(e,A.index.name),P=W(i,r`SELECT ${Ae} AS value FROM ${r.identifier(F)} WHERE ${xe} = ${D}`).toArray();return P[0]===void 0?0:P[0].value??0}}const R=te(l,oe);let $=r`SELECT COUNT(*) AS count FROM ${r.identifier(e)}`;return R&&($=r`${$} WHERE ${R}`),W(i,$).one().count},async delete(e,n,a){const c=re(e,n);if(!c){const $=n===void 0?E:void 0;$&&(v(void 0),await $.delete(e,void 0,a));return}const{docJson:h,row:u,tableName:s}=c,l=t.tables[s],p=a?.hard===!0,R=!p&&l?.softDeleteMode?l.softDeleteMode.field:void 0;if(!(R&&u[R]!==null&&u[R]!==void 0)){if(X(s,"before","delete")&&await Z("before","delete",{id:e,op:"delete",previous:u,table:s}),await hn({deletedId:e,deletedReference:$=>u[$],findHolders:async($,A,D)=>(await ve($).findMany($,{includeDeleted:p,where:{[A]:D}})).page,onCascade:($,A)=>ve($).delete(A,void 0,a),onRestrict:$=>{throw new pe($,"restrict")},onSetNull:($,A,D)=>ve($).patch(A,{[D]:null}),schema:t,tableName:s}),ue(s),fe(s),R){const $={...u,[R]:M(),_id:e};Ie(i,s,r`UPDATE ${r.identifier(s)} SET ${r.identifier(H)} = ${se($)} WHERE id = ${e} AND ${r.identifier(H)} = ${h}`),Ee(s,e,$,u),be(s,e,void 0),ge(s,u,$),he(s,e,u,void 0),L?.invalidate(s,e,f(s,u,$)),ne(s,e,"update",$),d({indexKeys:f(s,u,$),key:e,op:"update",row:$,table:s}),X(s,"after","delete")&&await Z("after","delete",{id:e,op:"delete",previous:u,table:s}),await O({id:e,op:"delete",table:s});return}Ie(i,s,r`DELETE FROM ${r.identifier(s)} WHERE id = ${e} AND ${r.identifier(H)} = ${h}`),Ee(s,e,void 0),be(s,e,void 0),ge(s,u,void 0),he(s,e,u,void 0),L?.invalidate(s,e,f(s,u)),ne(s,e,"delete"),d({indexKeys:f(s,u),key:e,op:"delete",table:s}),X(s,"after","delete")&&await Z("after","delete",{id:e,op:"delete",previous:u,table:s}),await O({id:e,op:"delete",table:s})}},async deleteAll(e,n){if(!t.tables[e])throw new g("INTERNAL",`unknown table: ${e}`);const a=Math.max(1,n?.chunkSize??It),c=n?.hard===void 0?void 0:{hard:n.hard},h=ae(e)?void 0:e;let u=0;return await S(async()=>{for(;;){const s=(await B.findMany(e,{limit:a})).page.map(l=>String(l._id));if(s.length===0)break;for(const l of s)await B.delete(l,h,c),u+=1;if(s.length<a)break}}),{deleted:u}},async deleteMany(e,n,a){de(e.length,n?.limit,"deleteMany");for(const c of e)await B.delete(c,a);return{deleted:e.length}},async deleteWhere(e,n,a){const c=(await(K(e,"deleteWhere")??B).findMany(e,{where:n})).page.map(h=>String(h._id));if(de(c.length,a?.limit,"deleteWhere"),B.deleteMany===void 0)throw new g("INTERNAL",`ctx.db.${e}.deleteMany is unavailable: this writer has no batch delete`);return B.deleteMany(c,a)},async findFirst(e,n={}){return(await B.findMany(e,{...n,limit:1})).page[0]??null},async findFirstOrThrow(e,n={}){const a=await B.findFirst(e,n);if(a===null)throw new on(`findFirstOrThrow: no "${e}" document matched`);return a},async findMany(e,n={}){const a=K(e,"findMany");if(a)return N(e,U),a.findMany(e,n);const c=t.tables[e];if(!c)throw new g("INTERNAL",`unknown table: ${e}`);const h=!n.where&&!n.baseWhere;h?N(e,U):N(e);const u=an(n.orderBy),s=n.cursor?xt(u,He(n.cursor)):void 0;let l=Y(n.baseWhere,n.where);l=Y(l,le(c.softDeleteMode,n.includeDeleted)),l=await ut(l,{canPushExists:Xe?Lt:void 0,existsPushMode:Ve==="always"?"always":"auto",fetcher:Je,maxRelationKeys:Ze,relationBaseWhere:n.relationBaseWhere,schema:t,tableName:e}),s&&(l=l?{AND:[l,s]}:s);const p=Xe?Kn(N):oe,R=te(l,p);let $=r`SELECT id, _creationTime, ${r.identifier(H)} FROM ${r.identifier(e)}`;R&&($=r`${$} WHERE ${R}`),$=r`${$} ORDER BY ${Dt(u)}`;const A=typeof n.limit=="number"?Math.max(0,Math.floor(n.limit)):void 0;A!==void 0&&($=r`${$} LIMIT ${r.raw(String(A+1))}`);const D=W(i,$).toArray();h&&!b&&m?.recordRead(D.length);const F=[];for(const ee of D){const q=ce(ee);q&&(F.push(q),!h&&typeof q._id=="string"&&N(e,q._id))}if(A===void 0)return n.with&&await ft({groupedCounter:et,fetcher:Ce,parents:F,...ht(n),schema:t,tableName:e,with:n.with}),{continueCursor:null,isDone:!0,page:dt(F,n.select,n.with)};const P=F.length>A,x=P?F.slice(0,A):F,Q=x.at(-1);return n.with&&await ft({fetcher:Ce,groupedCounter:et,parents:x,...ht(n),schema:t,tableName:e,with:n.with}),{continueCursor:P&&Q?Ge(Q,u):null,isDone:!P,page:dt(x,n.select,n.with)}},async get(e,n){const a=re(e,n);if(!a){const c=n===void 0?E:void 0;return c?c.get(e):null}return N(a.tableName,e),a.row},async lookupById(e,n){const a=re(e,n);return a?(N(a.tableName,e),{row:a.row,tableName:a.tableName}):null},async groupBy(e,n){const a=K(e,"groupBy");if(a)return N(e,U),a.groupBy(e,n);const c=t.tables[e];if(!c)throw new g("INTERNAL",`unknown table: ${e}`);N(e,U);const h=n.agg??{op:"count"};if(Re(h.op),h.op!=="count"&&!h.field)throw new g("INTERNAL",`groupBy(${e}, { agg: { op: "${h.op}" } }): "field" is required for non-count reducers`);const u=le(c.softDeleteMode,void 0),s=Y(Y(n.baseWhere,n.where),u),l=await $e(s,e,n.relationBaseWhere),p=l!==s,R=[...n.by,h.field];if(c.aggregateIndexes&&!n.baseWhere&&!p&&(!u||gt(c,R))){const x=Qt(c.aggregateIndexes,h.op,h.field,n.by,n.where),Q=x===void 0?0:Object.keys(x.partial).length,ee=x?.index.by?.length??0;if(x&&(Q===0||Q===ee)){Me(e,x.index);const q=Oe(e,x.index.name),ye=Object.keys(x.partial),Ne=[];if(ye.length===(x.index.by??[]).length&&ye.length>0){const _e=De(x.index.by??[],x.partial),Te=W(i,r`SELECT ${Ae} AS value, ${We} AS count FROM ${r.identifier(q)} WHERE ${xe} = ${_e}`).toArray();return Te.length>0&&Ne.push({key:{...x.partial},value:Le(h.op,Te[0])}),Ne}const Wt=W(i,r`SELECT ${xe} AS key, ${Ae} AS value, ${We} AS count FROM ${r.identifier(q)}`).toArray();for(const _e of Wt){const Te=Ht(JSON.parse(_e.key));Ne.push({key:Te,value:Le(h.op,_e)})}return Ne}}for(const x of R){if(x===void 0)continue;const Q=x===h.field?`groupBy(${e}, { agg: { op: "${h.op}", field: "${x}" } })`:`groupBy(${e}, { by: [..."${x}"] })`;bt(c,x,Q)}const $=te(l,oe),A=n.by.map(x=>r`${J(x)} AS ${r.identifier(x)}`);if(h.op==="count")A.push(r`COUNT(*) AS value`);else{const{field:x}=h;if(x===void 0)throw new g("INTERNAL",`groupBy(${e}, { agg: { op: "${h.op}" } }): "field" is required for non-count reducers`);A.push(r`${r.raw(Re(h.op))}(${J(x)}) AS value`)}let D=r`SELECT ${r.join(A,r`, `)} FROM ${r.identifier(e)}`;$&&(D=r`${D} WHERE ${$}`),D=r`${D} GROUP BY ${r.join(n.by.map(x=>J(x)),r`, `)}`;const F=W(i,D).toArray(),P=[];for(const x of F){const Q={};for(const q of n.by)Q[q]=x[q]??null;const{value:ee}=x;P.push({key:Q,value:ee==null?null:Number(ee)})}return P},async insert(e,n,a){const c=K(e,"insert");if(c)return ze(c,e,n,a,!0);const h=t.tables[e];if(!h)throw new g("INTERNAL",`unknown table: ${e}`);const u=yt(h,n,I);qe(h,u);let s;a?.clientId!==void 0?(Dn(a.clientId),s=a.clientId):a?.allowExplicitId&&typeof u._id=="string"?s=u._id:s=G();const l=a?.allowExplicitId&&typeof u._creationTime=="number"?u._creationTime:M(),p={...u,_creationTime:l,_id:s};return X(e,"before","insert")&&await Z("before","insert",{doc:{...p},id:s,op:"insert",table:e}),ue(e),fe(e),je(i,e,r`INSERT INTO ${r.identifier(e)} (id, _creationTime, ${r.identifier(H)}) VALUES (${s}, ${l}, ${se(p)})`),nt(e,s,p),X(e,"after","insert")&&await Z("after","insert",{doc:p,id:s,op:"insert",table:e}),await O({doc:p,id:s,op:"insert",table:e}),s},async insertManyUnsafe(e,n,a){if(de(n.length,a?.limit,"insertManyUnsafe"),n.length===0)return[];const c=K(e,"insert");if(c){const s=[];for(const l of n)v(l);for(const l of n){const p=await c.insert(e,l,{allowExplicitId:a?.allowExplicitId});d({key:p,op:"insert",row:{...l,_id:p},table:e}),s.push(p)}return s}const h=t.tables[e];if(!h)throw new g("INTERNAL",`unknown table: ${e}`);ue(e),fe(e);const u=n.map(s=>{const l=yt(h,s,I),p=a?.allowExplicitId===!0&&typeof l._id=="string"?l._id:G(),R=a?.allowExplicitId===!0&&typeof l._creationTime=="number"?l._creationTime:M();return{creationTime:R,document:{...l,_creationTime:R,_id:p},id:p}});for(const s of u)v(s.document);for(let s=0;s<u.length;s+=wt){const l=r.join(u.slice(s,s+wt).map(p=>r`(${p.id}, ${p.creationTime}, ${se(p.document)})`),r`, `);je(i,e,r`INSERT INTO ${r.identifier(e)} (id, _creationTime, ${r.identifier(H)}) VALUES ${l}`)}for(const{document:s,id:l}of u)nt(e,l,s),await T({doc:s,id:l,op:"insert",table:e});return u.map(s=>s.id)},async insertMany(e,n,a){de(n.length,a?.limit,"insertMany");const c=a?.skipDuplicates===!0,h=[],u=K(e,"insert");if(u)for(const l of n)v(l);const s=async l=>u?ze(u,e,l,void 0,!1):B.insert(e,l);for(const l of n)try{h.push(await s(l))}catch(p){if(c&&p instanceof pe&&p.kind==="unique")h.push(null);else throw p}return h},normalizeId(e,n){return Et(t,e,n)},async patch(e,n,a){const c=re(e,a);if(!c){const R=a===void 0?E:void 0;if(R){v(n),await R.patch(e,n);return}throw new g("INTERNAL",`document not found: ${e}`)}const{docJson:h,row:u,tableName:s}=c,l=t.tables[s];if(!l)throw new g("INTERNAL",`unknown table: ${s}`);N(s,e),_t("patch",n);const p={...u,...n,_id:e};Nt(l,n,p,I),qe(l,p,!0),X(s,"before","update")&&await Z("before","update",{doc:{...p},id:e,op:"update",previous:u,table:s}),ue(s),fe(s),Ie(i,s,r`UPDATE ${r.identifier(s)} SET ${r.identifier(H)} = ${se(p)} WHERE id = ${e} AND ${r.identifier(H)} = ${h}`),Ee(s,e,p,u),be(s,e,p),ge(s,u,p),he(s,e,u,p),L?.invalidate(s,e,f(s,u,p)),ne(s,e,"update",p),d({indexKeys:f(s,u,p),key:e,op:"update",row:p,table:s}),X(s,"after","update")&&await Z("after","update",{doc:p,id:e,op:"update",previous:u,table:s}),await O({doc:p,id:e,op:"update",table:s})},async patchMany(e,n,a){de(e.length,n?.limit,"patchMany");for(const c of e)await B.patch(c.id,c.patch,a);return{patched:e.length}},async patchWhere(e,n,a){const c=(await(K(e,"patchWhere")??B).findMany(e,{where:n.where})).page.map(h=>({id:String(h._id),patch:n.patch}));if(de(c.length,a?.limit,"patchWhere"),B.patchMany===void 0)throw new g("INTERNAL",`ctx.db.${e}.patchMany is unavailable: this writer has no batch patch`);return await B.patchMany(c,a),{patched:c.length}},query(e){const n=K(e,"query");return n?(N(e,U),n.query(e)):nr(i,t,e,_,a=>{a?w(a):N(e,U)},a=>{b||m?.recordRead(a)})},async rank(e,n,a){const c=K(e,"rank");if(c)return N(e,U),c.rank(e,n,a);_(e,n,"rank");const h=t.tables[e];if(!h)throw new g("INTERNAL",`unknown table: ${e}`);const u=h.rankIndexes?.find(q=>q.name===n);if(!u)throw new g("INTERNAL",`unknown rankIndex "${n}" on table "${e}"`);if(rt(e,h,u),a.restrictsCounts)throw new Fe(e);N(e,U),ke(e,u);const s=typeof a.row=="string"?a.row:a.row._id;if(!s)return null;const l=ct(e,u.name),p=u.sortBy.map((q,ye)=>lt(ye)),R=p.map(q=>bn(q)).join(", "),$=W(i,r`SELECT ${r.identifier("__partition__")}, ${r.raw(R)} FROM ${r.identifier(l)} WHERE ${r.identifier("__id__")} = ${s}`).toArray(),[A]=$;if(A===void 0)return null;let D=A.__partition__;const F=Y(a.baseWhere,a.where);Be(F,t,e,"rank");const P=dn(u,F);if(P){const q=ln(u.partitionBy??[],P);if(q!==D)return null;D=q}const x=p.map(q=>A[q]),{before:Q,total:ee}=Tt(i,l,p,u.sortBy,D,x,s);return{position:Q+1,total:ee}},async rankBefore(e,n,a){if(ae(e))throw new g("INTERNAL",`rankBefore is not supported on the global (.global()) table '${e}' — cross-shard rank cursors apply only to sharded tables`);const c=t.tables[e];if(!c)throw new g("INTERNAL",`unknown table: ${e}`);const h=c.rankIndexes?.find(p=>p.name===n);if(!h)throw new g("INTERNAL",`unknown rankIndex "${n}" on table "${e}"`);if(a.restrictsCounts)throw new Fe(e);N(e,U),ke(e,h);const u=ct(e,h.name),s=h.sortBy.map((p,R)=>lt(R)),l=h.sortBy.map((p,R)=>ie(a.sortValues[R]??null));return Tt(i,u,s,h.sortBy,a.partitionKey,l,a.rowId)},async rankPage(e,n,a={}){Be(Y(a.baseWhere,a.where),t,e,"rankPage");const c=K(e,"rankPage");if(c)return N(e,U),c.rankPage(e,n,a);_(e,n,"rank");const{continueCursor:h,hasMore:u,rows:s}=at(it,e,n,a);return{continueCursor:h,isDone:!u,page:s.map(l=>l.doc)}},async rankPageRows(e,n,a={}){Be(Y(a.baseWhere,a.where),t,e,"rankPage"),_(e,n,"rank");const{directions:c,hasMore:h,rows:u}=at(it,e,n,a);return{directions:c,hasMore:h,rows:u}},async restore(e,n){const a=re(e,n);if(!a){const u=n===void 0?E:void 0;if(u?.restore){await u.restore(e);return}throw new g("INTERNAL",`document not found: ${e}`)}const c=t.tables[a.tableName]?.softDeleteMode?.field;if(!c)throw new g("INTERNAL",`ctx.db.restore: table "${a.tableName}" is not a .softDelete() table`);const h=a.row[c]!==null&&a.row[c]!==void 0;await B.patch(e,{[c]:null},n),h&&he(a.tableName,e,void 0,a.row)},async replace(e,n,a,c){const h=re(e,a);if(!h){const A=a===void 0?E:void 0;if(A){v(n),await A.replace(e,n,void 0,c);return}throw new g("INTERNAL",`document not found: ${e}`)}const{docJson:u,row:s,tableName:l}=h,p=t.tables[l];if(!p)throw new g("INTERNAL",`unknown table: ${l}`);_t("replace",n);const R=c?.allowExplicitId&&typeof n._creationTime=="number"?n._creationTime:M(),$={...n,_creationTime:R,_id:e};Nt(p,n,$,I),qe(p,$),X(l,"before","update")&&await Z("before","update",{doc:{...$},id:e,op:"update",previous:s,table:l}),ue(l),fe(l),Ie(i,l,r`UPDATE ${r.identifier(l)} SET _creationTime = ${R}, ${r.identifier(H)} = ${se($)} WHERE id = ${e} AND ${r.identifier(H)} = ${u}`),Ee(l,e,$,s),be(l,e,$),ge(l,s,$),he(l,e,s,$),L?.invalidate(l,e,f(l,s,$)),ne(l,e,"update",$),d({indexKeys:f(l,s,$),key:e,op:"update",row:$,table:l}),X(l,"after","update")&&await Z("after","update",{doc:$,id:e,op:"update",previous:s,table:l}),await O({doc:$,id:e,op:"update",table:l})},async wipeShard(e){const n=new Set(e?.exclude),a=e?.tables,c=Object.entries(t.tables).filter(([l,p])=>n.has(l)||a!==void 0&&!a.includes(l)?!1:p.shardMode?.kind!=="global").map(([l])=>l);if(a!==void 0){for(const l of a)if(!t.tables[l])throw new g("INTERNAL",`wipeShard: unknown table: ${l}`)}const h={};let u=0;const{deleteAll:s}=B;if(s===void 0)throw new g("INTERNAL","wipeShard: this writer has no deleteAll");for(const l of c){const p=await s(l,{...e?.chunkSize===void 0?{}:{chunkSize:e.chunkSize},hard:!0});h[l]=p.deleted,u+=p.deleted}return{deleted:u,tables:h}}},Ft={db:B,scheduler:j};return o.enforceRls===!0?pn(B,t,(e,n)=>re(e,n)?.tableName,(e,n)=>Ot(e,n)):B};export{Ur as CDC_LOG_TABLE,Jr as CLIENT_WATERMARK_TABLE,to as GLOBAL_SHAPE_SNAPSHOT_TABLE,lo as IDEMPOTENCY_TABLE,Zn as NotUniqueError,$o as SEARCH_STATE_TABLE,Vr as advanceClientWatermark,Pr as applyCdcChanges,Dn as assertValidClientId,Fr as backfillAggregateIndexes,Wr as backfillRankIndexes,Br as backfillSearchIndexes,Hr as bumpCdcEpoch,Dr as createShardCtxDb,no as deleteGlobalShapeSnapshot,ro as deleteGlobalShapeSnapshotsForConnection,Xr as migrateClientWatermark,oo as migrateGlobalShapeSnapshot,Gr as minCdcSeq,Et as normalizeIdStructurally,jr as readCdcChanges,Qr as readCdcCursor,Kr as readCdcEpoch,Zr as readClientWatermark,io as readGlobalShapeSnapshot,co as readIdempotent,mo as runShardMigrations,go as selectShapeMemberIds,bo as selectShapeRows,Yr as trimCdcChanges,uo as trimIdempotent,ao as writeGlobalShapeSnapshot,fo as writeIdempotent};
@@ -0,0 +1,7 @@
1
+ import{sql as e}from"drizzle-orm";import{runDrizzle as n}from"./runDrizzle-C3n5gJsk.mjs";const E="__shape_poke_cursor",T=i=>{n(i,e`CREATE TABLE IF NOT EXISTS ${e.identifier(E)} (
2
+ connection_id TEXT NOT NULL,
3
+ sub_id TEXT NOT NULL,
4
+ cursor INTEGER NOT NULL,
5
+ PRIMARY KEY (connection_id, sub_id)
6
+ )`)},t=(i,o,r)=>n(i,e`SELECT cursor FROM ${e.identifier(E)} WHERE connection_id = ${o} AND sub_id = ${r} LIMIT 1`).toArray()[0]?.cursor,u=(i,o,r,s)=>{n(i,e`INSERT INTO ${e.identifier(E)} (connection_id, sub_id, cursor) VALUES (${o}, ${r}, ${s})
7
+ ON CONFLICT(connection_id, sub_id) DO UPDATE SET cursor = excluded.cursor`)},_=(i,o,r)=>{n(i,e`DELETE FROM ${e.identifier(E)} WHERE connection_id = ${o} AND sub_id = ${r}`)},a=(i,o)=>{n(i,e`DELETE FROM ${e.identifier(E)} WHERE connection_id = ${o}`)};export{E as SHAPE_POKE_CURSOR_TABLE,_ as deleteShapePokeCursor,a as deleteShapePokeCursorsForConnection,T as migrateShapePokeCursor,t as readShapePokeCursor,u as writeShapePokeCursor};
@@ -1 +1 @@
1
- import{createShardCtxDb as b}from"./NotUniqueError-DYo7r67J.mjs";import{createRelayLink as I}from"./DEFAULT_MAX_RELAYS-Cinp9pPC.mjs";import{ConflictError as N}from"./ConflictError-C8GtJmjS.mjs";import{runShardMigrations as v}from"./runShardMigrations-BCuK60KT.mjs";import{relayName as q}from"./DEFAULT_PROMOTION_THRESHOLDS-DYGNAo1I.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-BlrEp5pr.mjs";import{createRelayLink as I}from"./DEFAULT_MAX_RELAYS-Cinp9pPC.mjs";import{ConflictError as N}from"./ConflictError-C8GtJmjS.mjs";import{runShardMigrations as v}from"./runShardMigrations-C1mjoJS4.mjs";import{relayName as q}from"./DEFAULT_PROMOTION_THRESHOLDS-DYGNAo1I.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,5 @@
1
+ import{l as I,T as S,c as N}from"./ctx-db-companions-BJlCofon.mjs";import"@lunora/errors";import{sql as e}from"drizzle-orm";import{aggregateTableName as p}from"./aggregateTableName-DN7gk6uh.mjs";import{backfillSearchIndexesForTable as g}from"./backfillAggregateIndexes-DTOIsYbi.mjs";import{migrateCdcLog as h,migrateCdcMeta as l}from"./CDC_LOG_TABLE-DNFFQwF_.mjs";import{migrateClientWatermark as R}from"./CLIENT_WATERMARK_TABLE-LrKfdxyt.mjs";import{migrateGlobalShapeSnapshot as C}from"./GLOBAL_SHAPE_SNAPSHOT_TABLE-B2LKe4KU.mjs";import{migrateIdempotency as u}from"./IDEMPOTENCY_TABLE-tQ5mnqvw.mjs";import{migrateSearchState as O}from"./SEARCH_STATE_TABLE-DRk_SB72.mjs";import{migrateShapePokeCursor as U}from"./SHAPE_POKE_CURSOR_TABLE-pybVwKps.mjs";import{runDrizzle as t}from"./runDrizzle-C3n5gJsk.mjs";import{a as b,N as c,y as T,I as X,C as x,c as B,p as D,T as E,h as F}from"./do-sql-DKSFK627.mjs";import{migrateDurableStreams as M}from"./appendStreamChunk-ksZYy1hZ.mjs";import{sortColumnName as Y,rankTableName as k}from"./RANK_TIEBREAK-BGk411OR.mjs";import{recordSchemaVersion as y}from"./SCHEMA_HISTORY_MAX_VERSIONS-CEK7b_7v.mjs";const P=(r,a,o)=>{for(const i of o.indexes){const n=`${a}_${i.name}`,s=e.join(i.fields.map(f=>c(f)),e`, `);t(r,T(n,a,s,i.unique??!1))}for(const[i,n]of X(o)){if(!n.unique)continue;const s=`${a}_unique_${i}`;t(r,T(s,a,c(i),!0))}},j=(r,a,o)=>{if(!(!o.searchIndexes||o.searchIndexes.length===0||!x(r))){for(const i of o.searchIndexes){const n=N(a,i.name);t(r,e`CREATE VIRTUAL TABLE IF NOT EXISTS ${e.identifier(n)} USING fts5(${e.identifier(I)}, ${e.identifier(S)} UNINDEXED)`),t(r,e`CREATE VIRTUAL TABLE IF NOT EXISTS ${e.identifier(`${n}__vocab`)} USING fts5vocab(${e.identifier(n)}, ${e.raw("instance")})`)}g(r,a,o)}},q=(r,a,o)=>{if(o.geoIndexes)for(const i of o.geoIndexes){const n=F(a,i.name);t(r,e`CREATE TABLE IF NOT EXISTS ${e.identifier(n)} (${e.identifier("__id__")} TEXT PRIMARY KEY, ${e.identifier("__geohash__")} TEXT NOT NULL, ${e.identifier("__lat__")} REAL NOT NULL, ${e.identifier("__lng__")} REAL NOT NULL)`);const s=`${a}__geo_${i.name}__btree`;t(r,T(s,n,e`${e.identifier("__geohash__")} ASC, ${e.identifier("__id__")} ASC`,!1))}},G=(r,a,o)=>{if(o.aggregateIndexes)for(const i of o.aggregateIndexes){const n=p(a,i.name);t(r,e`CREATE TABLE IF NOT EXISTS ${e.identifier(n)} (${B} TEXT PRIMARY KEY, ${D} REAL, ${E} INTEGER NOT NULL DEFAULT 0)`),t(r,e`PRAGMA table_info(${e.identifier(n)})`).toArray().some(s=>s.name==="__count__")||t(r,e`ALTER TABLE ${e.identifier(n)} ADD COLUMN ${E} INTEGER NOT NULL DEFAULT 0`)}},K=(r,a,o)=>{if(o.rankIndexes)for(const i of o.rankIndexes){const n=k(a,i.name),s=i.sortBy.map((m,d)=>Y(d)),f=s.map(m=>e`${e.identifier(m)} BLOB`),$=f.length>0?e`, ${e.join(f,e`, `)}`:e``;t(r,e`CREATE TABLE IF NOT EXISTS ${e.identifier(n)} (${e.identifier("__id__")} TEXT PRIMARY KEY, ${e.identifier("__partition__")} TEXT NOT NULL${$})`);const _=[e`${e.identifier("__partition__")} ASC`];for(const[m,d]of s.entries()){const A=i.sortBy[m]?.direction;_.push(e`${e.identifier(d)} ${e.raw(A==="desc"?"DESC":"ASC")}`)}_.push(e`${e.identifier("__id__")} ASC`);const L=`${a}__rank_${i.name}__btree`;t(r,T(L,n,e.join(_,e`, `),!1))}},se=(r,a,o={})=>{o.schemaSnapshot!==void 0&&y(r,o.schemaSnapshot.hash,o.schemaSnapshot.json),O(r);for(const[i,n]of Object.entries(a.tables))n.shardMode?.kind!=="global"&&(t(r,e`CREATE TABLE IF NOT EXISTS ${e.identifier(i)} (
2
+ id TEXT PRIMARY KEY,
3
+ _creationTime REAL NOT NULL,
4
+ ${e.identifier(b)} TEXT NOT NULL
5
+ )`),P(r,i,n),j(r,i,n),q(r,i,n),G(r,i,n),K(r,i,n));o.cdc&&(h(r),l(r),R(r),U(r)),u(r),C(r),M(r)};export{se as runShardMigrations};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@lunora/shard-engine",
3
- "version": "1.0.0-alpha.26",
3
+ "version": "1.0.0-alpha.27",
4
4
  "description": "Host-neutral reactive engine for Lunora: per-shard state, OCC, CDC, reactive subscriptions, and the poke protocol. Consumes @lunora/platform host contracts and can be mounted on any platform host.",
5
5
  "keywords": [
6
6
  "cloudflare",
@@ -1,5 +0,0 @@
1
- import{l as I,T as N,c as S}from"./ctx-db-companions-BJlCofon.mjs";import"@lunora/errors";import{sql as e}from"drizzle-orm";import{aggregateTableName as p}from"./aggregateTableName-DN7gk6uh.mjs";import{backfillSearchIndexesForTable as g}from"./backfillAggregateIndexes-DTOIsYbi.mjs";import{migrateCdcLog as l,migrateCdcMeta as h}from"./CDC_LOG_TABLE-DNFFQwF_.mjs";import{migrateClientWatermark as R}from"./CLIENT_WATERMARK_TABLE-LrKfdxyt.mjs";import{migrateGlobalShapeSnapshot as C}from"./GLOBAL_SHAPE_SNAPSHOT_TABLE-B2LKe4KU.mjs";import{migrateIdempotency as O}from"./IDEMPOTENCY_TABLE-tQ5mnqvw.mjs";import{migrateSearchState as u}from"./SEARCH_STATE_TABLE-DRk_SB72.mjs";import{runDrizzle as a}from"./runDrizzle-C3n5gJsk.mjs";import{a as U,N as E,y as _,I as b,C as X,c as x,p as B,T as c,h as D}from"./do-sql-DKSFK627.mjs";import{migrateDurableStreams as F}from"./appendStreamChunk-ksZYy1hZ.mjs";import{sortColumnName as M,rankTableName as Y}from"./RANK_TIEBREAK-BGk411OR.mjs";import{recordSchemaVersion as k}from"./SCHEMA_HISTORY_MAX_VERSIONS-CEK7b_7v.mjs";const y=(r,t,o)=>{for(const i of o.indexes){const n=`${t}_${i.name}`,s=e.join(i.fields.map(f=>E(f)),e`, `);a(r,_(n,t,s,i.unique??!1))}for(const[i,n]of b(o)){if(!n.unique)continue;const s=`${t}_unique_${i}`;a(r,_(s,t,E(i),!0))}},j=(r,t,o)=>{if(!(!o.searchIndexes||o.searchIndexes.length===0||!X(r))){for(const i of o.searchIndexes){const n=S(t,i.name);a(r,e`CREATE VIRTUAL TABLE IF NOT EXISTS ${e.identifier(n)} USING fts5(${e.identifier(I)}, ${e.identifier(N)} UNINDEXED)`),a(r,e`CREATE VIRTUAL TABLE IF NOT EXISTS ${e.identifier(`${n}__vocab`)} USING fts5vocab(${e.identifier(n)}, ${e.raw("instance")})`)}g(r,t,o)}},q=(r,t,o)=>{if(o.geoIndexes)for(const i of o.geoIndexes){const n=D(t,i.name);a(r,e`CREATE TABLE IF NOT EXISTS ${e.identifier(n)} (${e.identifier("__id__")} TEXT PRIMARY KEY, ${e.identifier("__geohash__")} TEXT NOT NULL, ${e.identifier("__lat__")} REAL NOT NULL, ${e.identifier("__lng__")} REAL NOT NULL)`);const s=`${t}__geo_${i.name}__btree`;a(r,_(s,n,e`${e.identifier("__geohash__")} ASC, ${e.identifier("__id__")} ASC`,!1))}},G=(r,t,o)=>{if(o.aggregateIndexes)for(const i of o.aggregateIndexes){const n=p(t,i.name);a(r,e`CREATE TABLE IF NOT EXISTS ${e.identifier(n)} (${x} TEXT PRIMARY KEY, ${B} REAL, ${c} INTEGER NOT NULL DEFAULT 0)`),a(r,e`PRAGMA table_info(${e.identifier(n)})`).toArray().some(s=>s.name==="__count__")||a(r,e`ALTER TABLE ${e.identifier(n)} ADD COLUMN ${c} INTEGER NOT NULL DEFAULT 0`)}},P=(r,t,o)=>{if(o.rankIndexes)for(const i of o.rankIndexes){const n=Y(t,i.name),s=i.sortBy.map((T,d)=>M(d)),f=s.map(T=>e`${e.identifier(T)} BLOB`),$=f.length>0?e`, ${e.join(f,e`, `)}`:e``;a(r,e`CREATE TABLE IF NOT EXISTS ${e.identifier(n)} (${e.identifier("__id__")} TEXT PRIMARY KEY, ${e.identifier("__partition__")} TEXT NOT NULL${$})`);const m=[e`${e.identifier("__partition__")} ASC`];for(const[T,d]of s.entries()){const A=i.sortBy[T]?.direction;m.push(e`${e.identifier(d)} ${e.raw(A==="desc"?"DESC":"ASC")}`)}m.push(e`${e.identifier("__id__")} ASC`);const L=`${t}__rank_${i.name}__btree`;a(r,_(L,n,e.join(m,e`, `),!1))}},te=(r,t,o={})=>{o.schemaSnapshot!==void 0&&k(r,o.schemaSnapshot.hash,o.schemaSnapshot.json),u(r);for(const[i,n]of Object.entries(t.tables))n.shardMode?.kind!=="global"&&(a(r,e`CREATE TABLE IF NOT EXISTS ${e.identifier(i)} (
2
- id TEXT PRIMARY KEY,
3
- _creationTime REAL NOT NULL,
4
- ${e.identifier(U)} TEXT NOT NULL
5
- )`),y(r,i,n),j(r,i,n),q(r,i,n),G(r,i,n),P(r,i,n));o.cdc&&(l(r),h(r),R(r)),O(r),C(r),F(r)};export{te as runShardMigrations};