@lunora/shard-engine 1.0.0-alpha.66 → 1.0.0-alpha.68

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-BFT_djtN.mjs";export{t as defineEngineContractSuite};
1
+ import{defineEngineContractSuite as t}from"../packem_shared/defineEngineContractSuite-ybvzhAPu.mjs";export{t as defineEngineContractSuite};
package/dist/index.d.mts CHANGED
@@ -1022,6 +1022,35 @@ interface RankPageComputation {
1022
1022
  }[];
1023
1023
  }
1024
1024
  declare const computeRankPage: (deps: RankPageDeps, tableName: string, indexName: string, rankPageOptions: RankPageOptions) => RankPageComputation;
1025
+ declare const SCHEDULE_OUTBOX_TABLE = "__schedule_outbox";
1026
+ interface ScheduleOutboxRow {
1027
+ attempts: number;
1028
+ envelopeJson: string;
1029
+ id: string;
1030
+ nextAttemptAt: number;
1031
+ }
1032
+ interface ScheduleOutboxEnvelope {
1033
+ args: unknown;
1034
+ options: Record<string, unknown> | undefined;
1035
+ target: unknown;
1036
+ when: number;
1037
+ }
1038
+ interface ScheduleOutbox {
1039
+ forget: (id: string) => void;
1040
+ record: (id: string, envelope: ScheduleOutboxEnvelope) => void;
1041
+ wake: () => void;
1042
+ }
1043
+ declare const migrateScheduleOutbox: (sql: SqlExec) => void;
1044
+ declare const recordScheduleOutbox: (sql: SqlExec, id: string, envelopeJson: string, now: number) => void;
1045
+ declare const forgetScheduleOutbox: (sql: SqlExec, id: string) => void;
1046
+ declare const readDueScheduleOutbox: (sql: SqlExec, nowMs: number, limit: number) => ScheduleOutboxRow[];
1047
+ declare const deferScheduleOutbox: (sql: SqlExec, id: string, attempts: number, nextAttemptAt: number) => void;
1048
+ declare const parkScheduleOutbox: (sql: SqlExec, id: string, attempts: number) => void;
1049
+ declare const probeScheduleOutbox: (sql: SqlExec) => {
1050
+ dueAt: number | undefined;
1051
+ populated: boolean;
1052
+ };
1053
+ declare const trimScheduleOutbox: (sql: SqlExec, olderThanTs: number) => void;
1025
1054
  declare const SHAPE_POKE_CURSOR_TABLE = "__shape_poke_cursor";
1026
1055
  declare const migrateShapePokeCursor: (sql: SqlExec) => void;
1027
1056
  declare const readShapePokeCursor: (sql: SqlExec, connectionId: string, subId: string) => number | undefined;
@@ -2416,4 +2445,4 @@ interface WhereSqlStrategy<T = SQL> {
2416
2445
  }
2417
2446
  declare const literalInList: (reference: SQL, items: ReadonlyArray<unknown>, negated: boolean) => SQL;
2418
2447
  declare const compileWhereSql: <T = SQL>(where: WhereInput | undefined, strategy: WhereSqlStrategy<T>, fragments?: WhereFragments<T>) => T | undefined;
2419
- 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, BIGINT_KEY_DIGITS, type BroadcastDelta, CDC_LOG_TABLE, CDC_LOG_TABLE_SEQ_INDEX, CDC_META_TABLE, CLIENT_WATERMARK_TABLE, COMMIT_SEQ_FIELD, COMMIT_SEQ_TABLE, CURSOR_PREFIX, type CacheEntry, type CapturedMailRow, type CdcArchiveScope, type CdcChange, type CdcChangeKey, 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 FanOutBudget, 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 GlobalPollCounters, GlobalPollTick, 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, type OrderKeyConstraints, 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, REACTOR_STATE_TABLE, RELATED_DEFAULT_LIMIT, RELATED_DEPTH_DECAY, RELATED_MAX_DEPTH, RELATED_MAX_LIMIT, 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 ReactorDispatchResult, type ReactorMetadata, type ReactorState, type ReactorStats, type ReactorsResult, type ReadFootprint, type ReadHook, type ReadTablePageOptions, type RecordMailInput, type RecordQueueMessageInput, type RelatedDirection, type RelatedNode, type RelatedOptions, type RelatedPage, type RelatedStart, type RelatedStartReference, type RelationDefinitionLike, type RelationEdge, type RelationExistsMarker, type RelationGraphReader, type RelayAttach, type RelayDetach, type RelayFrame, type RelayHost, RelayMember, type RelayPokeDelivery, type RelayShapePoke, type RelayShapeSeed, type RelayShapeSubscribe, type RelayShapeUnsubscribe, 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 SearchBackfillProgress, type SearchFilterBuilderLike, type SearchIndexDefinitionLike, type SearchScoredDocument, type SelectMatchingIdsOptions, type ServerDefaultContextLike, type SettingEntry, type SettingKind, type SettingsResult, ShapeDiffCache, type ShapePokeCursorRow, type ShapePokePart, type ShapeProbeCounters, 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, UNVOUCHABLE_DEP, type ValidatorLike, type WhereInput, type WhereSqlStrategy, type WithInput, type WorkflowInstanceState, type WorkflowInstanceStatusResult, type WorkflowMetadata, type WorkflowsResult, type WriteEvent, type WriteHook, advanceClientWatermark, aggUpsertSql, aggregateSqlFunction, aggregateTableName, allocateCommitSeq, appendAuditEntry, appendCdcChange, appendStreamChunk, applyCdcChanges, applyOnDelete, applySelect, archiveCdcSegment, armRestore, assertFlatPredicate, assertNoExplicitUndefined, assertReadonly, assertShapeShardable, assertValidClientId, awaitWsDrain, backfillAggregateIndexes, backfillRankIndexes, backfillSearchIndexes, backfillSearchIndexesForTable, bigintSqlKey, boundingBoxCenter, boundingBoxGeohashes, buildIndexRange, buildPokeFrames, buildReprojectionMigration, buildSeekBeforeWhere, buildSeekWhere, buildSettings, buildShapeDiff, bumpCdcEpoch, cdcCanVouchFor, cdcSeqLeavingRows, cdcTouchesTables, cdcTrimmedError, claimStreamRun, clampPromotionThresholds, clearCapturedMail, clearMemoryTables, clearQueueMessages, coerceAggregateNumber, compactCdcDocs, compileWhereSql, computeRankPage, containsRelationPredicate, countLegacyRows, coveringGeohashes, createCompanionSync, createDependencyTracker, createFanoutCounters, createGlobalPollCounters, createIndexSql, createReadFootprint, createRelayLink, createReplicaLink, createShapeDiffCache, createShapeProbeCounters, createShardCtxDb, createSystemReader, cursorBelowRetainedFloor, decideDurableAttach, decodeBigintSqlKey, decodeCursor, decodeFloat64SqlKey, deleteGlobalShapeSnapshot, deleteGlobalShapeSnapshotsForConnection, deleteShapePokeCursor, deleteShapePokeCursorsForConnection, deleteStreamRun, depKey, deriveRelationEdges, diffExternalSource, diffGlobalMembership, distinctValues, encodeAggregateKey, encodeCursor, encodeGeohash, encodePartitionKey, encodeRowsPatch, ensureAuditTable, ensureMailTable, envOptionalPositiveInt, envPositiveInt, equalityPinnedFields, exportShardRows, facetColumn, fanOutScalarCounts, findRelated, findStorageReferences, finishStreamRun, float64SqlKey, foldAggregateTally, gateReplicaDispatch, geoTableName, globalShapeReadKey, guardWriter, handleReplicaControl, hasTrigger, haversineMeters, importShardRows, indexKeysForRow, isDevEnvironment, isFtsAvailable, isLossyBody, isMemoryTable, isRelationPredicate, isSoftDeleted, isSourceDue, jsonPath, jsonPathSql, keysTouchRanges, liftSourceId, lintReadonlySql, listReactorStates, listTables, literalInList, markUnvouchableReads, matchesRankStaticWhere, matchesStaticWhere, materializeExternalRows, materializeExternalRowsIncremental, memoryTableNames, mergeChangedKeys, mergeWhere, migrateCdcLog, migrateCdcMeta, migrateClientWatermark, migrateCommitSeq, migrateDurableStreams, migrateGlobalShapeSnapshot, migrateIdempotency, migrateReactorState, migrateSearchState, migrateShapePokeCursor, minCdcReplayableSeq, minCdcSeq, minShapePokeCursor, nextPromotionState, normalizeCountArgument, normalizeIdStructurally, normalizeOrderKeys, normalizeSourceDocument, normalizeSourceValue, param, parseExportShardArgs, parseImportShardArgs, planAggregateLookup, pointInBoundingBox, projectColumns, pullExternalSourceIncrementalTick, pullExternalSourceTick, qualifiedJsonPath, qualifiedJsonPathSql, quoteIdentifier, rankKeyFromDocument as rankKeyFromDoc, rankPivotConditionSql, rankTableName, reactiveCacheKey, reactorNeedsRun, readAggregateValue, readArchivedCdcChanges, readAuditLog, readBookmark, readCapturedMail, readCdcArchivedThrough, readCdcChangeKeys, readCdcChanges, readCdcCursor, readCdcEpoch, readClientWatermark, readCommitSeq, readDeployInfo, readExternalSourceBaseline, readGlobalShapeSnapshot, readIdempotent, readMigrationStatus, readQueueMessageById, readQueueMessages, readReactorState, readSchemaHistory, readSchemaVersion, readSearchBackfillState, readShapePokeCursor, readStreamChunks, readStreamRun, readTablePage, recordCapturedMail, recordChangedKeys, recordFanoutPass, recordGlobalPollPass, recordQueueMessages, recordSchemaVersion, recordShapeProbePass, relationHooks, relayCountFor, renderSql, reprojectableFields, reprojectionMigrationId, reprojectionTables, resolveRankPartition, resolveRankSeekTuple, resolveRelationPredicates, resolveWith, rowToDocument, runDataMigration, runDrizzle, runExternalSourceTick, runReadonlySql, runRowValidators, runShardMigrations, runSocketPool, runSql, runTriggers, selectExpiredIds, selectExportTables, selectIndexForAggregate, selectIndexForCount, selectIndexForGroupBy, selectMatchingIds, selectShapeMembers, selectShapeRows, serializeSqlValue, shapeRoutingKey, softDeleteScope, sortColumnName, sqliteInList, stableStringify, stableWireKey, subscriptionFrames, subscriptionListDeltas, summarizeFanoutTopics, summarizeSubscriptions, tableColumns, tableFromDepKey, throwingScheduler, tiebreakDirectionFor, trimCdcChanges, trimIdempotent, trimStreamRuns, tryRowToDocument, trySendFrame, unionAll, uniqueIndexFields, validateImportRow, writeCdcArchivedThrough, writeGlobalShapeSnapshot, writeIdempotent, writeReactorState, writeSearchBackfillState, writeShapePokeCursor, writeShapePokeCursors, writeTouchesMemo };
2448
+ 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, BIGINT_KEY_DIGITS, type BroadcastDelta, CDC_LOG_TABLE, CDC_LOG_TABLE_SEQ_INDEX, CDC_META_TABLE, CLIENT_WATERMARK_TABLE, COMMIT_SEQ_FIELD, COMMIT_SEQ_TABLE, CURSOR_PREFIX, type CacheEntry, type CapturedMailRow, type CdcArchiveScope, type CdcChange, type CdcChangeKey, 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 FanOutBudget, 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 GlobalPollCounters, GlobalPollTick, 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, type OrderKeyConstraints, 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, REACTOR_STATE_TABLE, RELATED_DEFAULT_LIMIT, RELATED_DEPTH_DECAY, RELATED_MAX_DEPTH, RELATED_MAX_LIMIT, 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 ReactorDispatchResult, type ReactorMetadata, type ReactorState, type ReactorStats, type ReactorsResult, type ReadFootprint, type ReadHook, type ReadTablePageOptions, type RecordMailInput, type RecordQueueMessageInput, type RelatedDirection, type RelatedNode, type RelatedOptions, type RelatedPage, type RelatedStart, type RelatedStartReference, type RelationDefinitionLike, type RelationEdge, type RelationExistsMarker, type RelationGraphReader, type RelayAttach, type RelayDetach, type RelayFrame, type RelayHost, RelayMember, type RelayPokeDelivery, type RelayShapePoke, type RelayShapeSeed, type RelayShapeSubscribe, type RelayShapeUnsubscribe, 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, SCHEDULE_OUTBOX_TABLE, SCHEMA_HISTORY_MAX_VERSIONS, SEARCH_STATE_TABLE, SHAPE_POKE_CURSOR_TABLE, type SchedulableWorkflowReferenceLike, type ScheduleOutbox, type ScheduleOutboxEnvelope, type ScheduleOutboxRow, type ScheduledFunctionDoc, type SchedulerLike, type SchemaLike, type ScoredDocument, type SearchBackfillProgress, type SearchFilterBuilderLike, type SearchIndexDefinitionLike, type SearchScoredDocument, type SelectMatchingIdsOptions, type ServerDefaultContextLike, type SettingEntry, type SettingKind, type SettingsResult, ShapeDiffCache, type ShapePokeCursorRow, type ShapePokePart, type ShapeProbeCounters, 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, UNVOUCHABLE_DEP, type ValidatorLike, type WhereInput, type WhereSqlStrategy, type WithInput, type WorkflowInstanceState, type WorkflowInstanceStatusResult, type WorkflowMetadata, type WorkflowsResult, type WriteEvent, type WriteHook, advanceClientWatermark, aggUpsertSql, aggregateSqlFunction, aggregateTableName, allocateCommitSeq, appendAuditEntry, appendCdcChange, appendStreamChunk, applyCdcChanges, applyOnDelete, applySelect, archiveCdcSegment, armRestore, assertFlatPredicate, assertNoExplicitUndefined, assertReadonly, assertShapeShardable, assertValidClientId, awaitWsDrain, backfillAggregateIndexes, backfillRankIndexes, backfillSearchIndexes, backfillSearchIndexesForTable, bigintSqlKey, boundingBoxCenter, boundingBoxGeohashes, buildIndexRange, buildPokeFrames, buildReprojectionMigration, buildSeekBeforeWhere, buildSeekWhere, buildSettings, buildShapeDiff, bumpCdcEpoch, cdcCanVouchFor, cdcSeqLeavingRows, cdcTouchesTables, cdcTrimmedError, claimStreamRun, clampPromotionThresholds, clearCapturedMail, clearMemoryTables, clearQueueMessages, coerceAggregateNumber, compactCdcDocs, compileWhereSql, computeRankPage, containsRelationPredicate, countLegacyRows, coveringGeohashes, createCompanionSync, createDependencyTracker, createFanoutCounters, createGlobalPollCounters, createIndexSql, createReadFootprint, createRelayLink, createReplicaLink, createShapeDiffCache, createShapeProbeCounters, createShardCtxDb, createSystemReader, cursorBelowRetainedFloor, decideDurableAttach, decodeBigintSqlKey, decodeCursor, decodeFloat64SqlKey, deferScheduleOutbox, deleteGlobalShapeSnapshot, deleteGlobalShapeSnapshotsForConnection, deleteShapePokeCursor, deleteShapePokeCursorsForConnection, deleteStreamRun, depKey, deriveRelationEdges, diffExternalSource, diffGlobalMembership, distinctValues, encodeAggregateKey, encodeCursor, encodeGeohash, encodePartitionKey, encodeRowsPatch, ensureAuditTable, ensureMailTable, envOptionalPositiveInt, envPositiveInt, equalityPinnedFields, exportShardRows, facetColumn, fanOutScalarCounts, findRelated, findStorageReferences, finishStreamRun, float64SqlKey, foldAggregateTally, forgetScheduleOutbox, gateReplicaDispatch, geoTableName, globalShapeReadKey, guardWriter, handleReplicaControl, hasTrigger, haversineMeters, importShardRows, indexKeysForRow, isDevEnvironment, isFtsAvailable, isLossyBody, isMemoryTable, isRelationPredicate, isSoftDeleted, isSourceDue, jsonPath, jsonPathSql, keysTouchRanges, liftSourceId, lintReadonlySql, listReactorStates, listTables, literalInList, markUnvouchableReads, matchesRankStaticWhere, matchesStaticWhere, materializeExternalRows, materializeExternalRowsIncremental, memoryTableNames, mergeChangedKeys, mergeWhere, migrateCdcLog, migrateCdcMeta, migrateClientWatermark, migrateCommitSeq, migrateDurableStreams, migrateGlobalShapeSnapshot, migrateIdempotency, migrateReactorState, migrateScheduleOutbox, migrateSearchState, migrateShapePokeCursor, minCdcReplayableSeq, minCdcSeq, minShapePokeCursor, nextPromotionState, normalizeCountArgument, normalizeIdStructurally, normalizeOrderKeys, normalizeSourceDocument, normalizeSourceValue, param, parkScheduleOutbox, parseExportShardArgs, parseImportShardArgs, planAggregateLookup, pointInBoundingBox, probeScheduleOutbox, projectColumns, pullExternalSourceIncrementalTick, pullExternalSourceTick, qualifiedJsonPath, qualifiedJsonPathSql, quoteIdentifier, rankKeyFromDocument as rankKeyFromDoc, rankPivotConditionSql, rankTableName, reactiveCacheKey, reactorNeedsRun, readAggregateValue, readArchivedCdcChanges, readAuditLog, readBookmark, readCapturedMail, readCdcArchivedThrough, readCdcChangeKeys, readCdcChanges, readCdcCursor, readCdcEpoch, readClientWatermark, readCommitSeq, readDeployInfo, readDueScheduleOutbox, readExternalSourceBaseline, readGlobalShapeSnapshot, readIdempotent, readMigrationStatus, readQueueMessageById, readQueueMessages, readReactorState, readSchemaHistory, readSchemaVersion, readSearchBackfillState, readShapePokeCursor, readStreamChunks, readStreamRun, readTablePage, recordCapturedMail, recordChangedKeys, recordFanoutPass, recordGlobalPollPass, recordQueueMessages, recordScheduleOutbox, recordSchemaVersion, recordShapeProbePass, relationHooks, relayCountFor, renderSql, reprojectableFields, reprojectionMigrationId, reprojectionTables, resolveRankPartition, resolveRankSeekTuple, resolveRelationPredicates, resolveWith, rowToDocument, runDataMigration, runDrizzle, runExternalSourceTick, runReadonlySql, runRowValidators, runShardMigrations, runSocketPool, runSql, runTriggers, selectExpiredIds, selectExportTables, selectIndexForAggregate, selectIndexForCount, selectIndexForGroupBy, selectMatchingIds, selectShapeMembers, selectShapeRows, serializeSqlValue, shapeRoutingKey, softDeleteScope, sortColumnName, sqliteInList, stableStringify, stableWireKey, subscriptionFrames, subscriptionListDeltas, summarizeFanoutTopics, summarizeSubscriptions, tableColumns, tableFromDepKey, throwingScheduler, tiebreakDirectionFor, trimCdcChanges, trimIdempotent, trimScheduleOutbox, trimStreamRuns, tryRowToDocument, trySendFrame, unionAll, uniqueIndexFields, validateImportRow, writeCdcArchivedThrough, writeGlobalShapeSnapshot, writeIdempotent, writeReactorState, writeSearchBackfillState, writeShapePokeCursor, writeShapePokeCursors, writeTouchesMemo };
package/dist/index.d.ts CHANGED
@@ -1022,6 +1022,35 @@ interface RankPageComputation {
1022
1022
  }[];
1023
1023
  }
1024
1024
  declare const computeRankPage: (deps: RankPageDeps, tableName: string, indexName: string, rankPageOptions: RankPageOptions) => RankPageComputation;
1025
+ declare const SCHEDULE_OUTBOX_TABLE = "__schedule_outbox";
1026
+ interface ScheduleOutboxRow {
1027
+ attempts: number;
1028
+ envelopeJson: string;
1029
+ id: string;
1030
+ nextAttemptAt: number;
1031
+ }
1032
+ interface ScheduleOutboxEnvelope {
1033
+ args: unknown;
1034
+ options: Record<string, unknown> | undefined;
1035
+ target: unknown;
1036
+ when: number;
1037
+ }
1038
+ interface ScheduleOutbox {
1039
+ forget: (id: string) => void;
1040
+ record: (id: string, envelope: ScheduleOutboxEnvelope) => void;
1041
+ wake: () => void;
1042
+ }
1043
+ declare const migrateScheduleOutbox: (sql: SqlExec) => void;
1044
+ declare const recordScheduleOutbox: (sql: SqlExec, id: string, envelopeJson: string, now: number) => void;
1045
+ declare const forgetScheduleOutbox: (sql: SqlExec, id: string) => void;
1046
+ declare const readDueScheduleOutbox: (sql: SqlExec, nowMs: number, limit: number) => ScheduleOutboxRow[];
1047
+ declare const deferScheduleOutbox: (sql: SqlExec, id: string, attempts: number, nextAttemptAt: number) => void;
1048
+ declare const parkScheduleOutbox: (sql: SqlExec, id: string, attempts: number) => void;
1049
+ declare const probeScheduleOutbox: (sql: SqlExec) => {
1050
+ dueAt: number | undefined;
1051
+ populated: boolean;
1052
+ };
1053
+ declare const trimScheduleOutbox: (sql: SqlExec, olderThanTs: number) => void;
1025
1054
  declare const SHAPE_POKE_CURSOR_TABLE = "__shape_poke_cursor";
1026
1055
  declare const migrateShapePokeCursor: (sql: SqlExec) => void;
1027
1056
  declare const readShapePokeCursor: (sql: SqlExec, connectionId: string, subId: string) => number | undefined;
@@ -2416,4 +2445,4 @@ interface WhereSqlStrategy<T = SQL> {
2416
2445
  }
2417
2446
  declare const literalInList: (reference: SQL, items: ReadonlyArray<unknown>, negated: boolean) => SQL;
2418
2447
  declare const compileWhereSql: <T = SQL>(where: WhereInput | undefined, strategy: WhereSqlStrategy<T>, fragments?: WhereFragments<T>) => T | undefined;
2419
- 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, BIGINT_KEY_DIGITS, type BroadcastDelta, CDC_LOG_TABLE, CDC_LOG_TABLE_SEQ_INDEX, CDC_META_TABLE, CLIENT_WATERMARK_TABLE, COMMIT_SEQ_FIELD, COMMIT_SEQ_TABLE, CURSOR_PREFIX, type CacheEntry, type CapturedMailRow, type CdcArchiveScope, type CdcChange, type CdcChangeKey, 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 FanOutBudget, 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 GlobalPollCounters, GlobalPollTick, 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, type OrderKeyConstraints, 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, REACTOR_STATE_TABLE, RELATED_DEFAULT_LIMIT, RELATED_DEPTH_DECAY, RELATED_MAX_DEPTH, RELATED_MAX_LIMIT, 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 ReactorDispatchResult, type ReactorMetadata, type ReactorState, type ReactorStats, type ReactorsResult, type ReadFootprint, type ReadHook, type ReadTablePageOptions, type RecordMailInput, type RecordQueueMessageInput, type RelatedDirection, type RelatedNode, type RelatedOptions, type RelatedPage, type RelatedStart, type RelatedStartReference, type RelationDefinitionLike, type RelationEdge, type RelationExistsMarker, type RelationGraphReader, type RelayAttach, type RelayDetach, type RelayFrame, type RelayHost, RelayMember, type RelayPokeDelivery, type RelayShapePoke, type RelayShapeSeed, type RelayShapeSubscribe, type RelayShapeUnsubscribe, 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 SearchBackfillProgress, type SearchFilterBuilderLike, type SearchIndexDefinitionLike, type SearchScoredDocument, type SelectMatchingIdsOptions, type ServerDefaultContextLike, type SettingEntry, type SettingKind, type SettingsResult, ShapeDiffCache, type ShapePokeCursorRow, type ShapePokePart, type ShapeProbeCounters, 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, UNVOUCHABLE_DEP, type ValidatorLike, type WhereInput, type WhereSqlStrategy, type WithInput, type WorkflowInstanceState, type WorkflowInstanceStatusResult, type WorkflowMetadata, type WorkflowsResult, type WriteEvent, type WriteHook, advanceClientWatermark, aggUpsertSql, aggregateSqlFunction, aggregateTableName, allocateCommitSeq, appendAuditEntry, appendCdcChange, appendStreamChunk, applyCdcChanges, applyOnDelete, applySelect, archiveCdcSegment, armRestore, assertFlatPredicate, assertNoExplicitUndefined, assertReadonly, assertShapeShardable, assertValidClientId, awaitWsDrain, backfillAggregateIndexes, backfillRankIndexes, backfillSearchIndexes, backfillSearchIndexesForTable, bigintSqlKey, boundingBoxCenter, boundingBoxGeohashes, buildIndexRange, buildPokeFrames, buildReprojectionMigration, buildSeekBeforeWhere, buildSeekWhere, buildSettings, buildShapeDiff, bumpCdcEpoch, cdcCanVouchFor, cdcSeqLeavingRows, cdcTouchesTables, cdcTrimmedError, claimStreamRun, clampPromotionThresholds, clearCapturedMail, clearMemoryTables, clearQueueMessages, coerceAggregateNumber, compactCdcDocs, compileWhereSql, computeRankPage, containsRelationPredicate, countLegacyRows, coveringGeohashes, createCompanionSync, createDependencyTracker, createFanoutCounters, createGlobalPollCounters, createIndexSql, createReadFootprint, createRelayLink, createReplicaLink, createShapeDiffCache, createShapeProbeCounters, createShardCtxDb, createSystemReader, cursorBelowRetainedFloor, decideDurableAttach, decodeBigintSqlKey, decodeCursor, decodeFloat64SqlKey, deleteGlobalShapeSnapshot, deleteGlobalShapeSnapshotsForConnection, deleteShapePokeCursor, deleteShapePokeCursorsForConnection, deleteStreamRun, depKey, deriveRelationEdges, diffExternalSource, diffGlobalMembership, distinctValues, encodeAggregateKey, encodeCursor, encodeGeohash, encodePartitionKey, encodeRowsPatch, ensureAuditTable, ensureMailTable, envOptionalPositiveInt, envPositiveInt, equalityPinnedFields, exportShardRows, facetColumn, fanOutScalarCounts, findRelated, findStorageReferences, finishStreamRun, float64SqlKey, foldAggregateTally, gateReplicaDispatch, geoTableName, globalShapeReadKey, guardWriter, handleReplicaControl, hasTrigger, haversineMeters, importShardRows, indexKeysForRow, isDevEnvironment, isFtsAvailable, isLossyBody, isMemoryTable, isRelationPredicate, isSoftDeleted, isSourceDue, jsonPath, jsonPathSql, keysTouchRanges, liftSourceId, lintReadonlySql, listReactorStates, listTables, literalInList, markUnvouchableReads, matchesRankStaticWhere, matchesStaticWhere, materializeExternalRows, materializeExternalRowsIncremental, memoryTableNames, mergeChangedKeys, mergeWhere, migrateCdcLog, migrateCdcMeta, migrateClientWatermark, migrateCommitSeq, migrateDurableStreams, migrateGlobalShapeSnapshot, migrateIdempotency, migrateReactorState, migrateSearchState, migrateShapePokeCursor, minCdcReplayableSeq, minCdcSeq, minShapePokeCursor, nextPromotionState, normalizeCountArgument, normalizeIdStructurally, normalizeOrderKeys, normalizeSourceDocument, normalizeSourceValue, param, parseExportShardArgs, parseImportShardArgs, planAggregateLookup, pointInBoundingBox, projectColumns, pullExternalSourceIncrementalTick, pullExternalSourceTick, qualifiedJsonPath, qualifiedJsonPathSql, quoteIdentifier, rankKeyFromDocument as rankKeyFromDoc, rankPivotConditionSql, rankTableName, reactiveCacheKey, reactorNeedsRun, readAggregateValue, readArchivedCdcChanges, readAuditLog, readBookmark, readCapturedMail, readCdcArchivedThrough, readCdcChangeKeys, readCdcChanges, readCdcCursor, readCdcEpoch, readClientWatermark, readCommitSeq, readDeployInfo, readExternalSourceBaseline, readGlobalShapeSnapshot, readIdempotent, readMigrationStatus, readQueueMessageById, readQueueMessages, readReactorState, readSchemaHistory, readSchemaVersion, readSearchBackfillState, readShapePokeCursor, readStreamChunks, readStreamRun, readTablePage, recordCapturedMail, recordChangedKeys, recordFanoutPass, recordGlobalPollPass, recordQueueMessages, recordSchemaVersion, recordShapeProbePass, relationHooks, relayCountFor, renderSql, reprojectableFields, reprojectionMigrationId, reprojectionTables, resolveRankPartition, resolveRankSeekTuple, resolveRelationPredicates, resolveWith, rowToDocument, runDataMigration, runDrizzle, runExternalSourceTick, runReadonlySql, runRowValidators, runShardMigrations, runSocketPool, runSql, runTriggers, selectExpiredIds, selectExportTables, selectIndexForAggregate, selectIndexForCount, selectIndexForGroupBy, selectMatchingIds, selectShapeMembers, selectShapeRows, serializeSqlValue, shapeRoutingKey, softDeleteScope, sortColumnName, sqliteInList, stableStringify, stableWireKey, subscriptionFrames, subscriptionListDeltas, summarizeFanoutTopics, summarizeSubscriptions, tableColumns, tableFromDepKey, throwingScheduler, tiebreakDirectionFor, trimCdcChanges, trimIdempotent, trimStreamRuns, tryRowToDocument, trySendFrame, unionAll, uniqueIndexFields, validateImportRow, writeCdcArchivedThrough, writeGlobalShapeSnapshot, writeIdempotent, writeReactorState, writeSearchBackfillState, writeShapePokeCursor, writeShapePokeCursors, writeTouchesMemo };
2448
+ 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, BIGINT_KEY_DIGITS, type BroadcastDelta, CDC_LOG_TABLE, CDC_LOG_TABLE_SEQ_INDEX, CDC_META_TABLE, CLIENT_WATERMARK_TABLE, COMMIT_SEQ_FIELD, COMMIT_SEQ_TABLE, CURSOR_PREFIX, type CacheEntry, type CapturedMailRow, type CdcArchiveScope, type CdcChange, type CdcChangeKey, 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 FanOutBudget, 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 GlobalPollCounters, GlobalPollTick, 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, type OrderKeyConstraints, 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, REACTOR_STATE_TABLE, RELATED_DEFAULT_LIMIT, RELATED_DEPTH_DECAY, RELATED_MAX_DEPTH, RELATED_MAX_LIMIT, 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 ReactorDispatchResult, type ReactorMetadata, type ReactorState, type ReactorStats, type ReactorsResult, type ReadFootprint, type ReadHook, type ReadTablePageOptions, type RecordMailInput, type RecordQueueMessageInput, type RelatedDirection, type RelatedNode, type RelatedOptions, type RelatedPage, type RelatedStart, type RelatedStartReference, type RelationDefinitionLike, type RelationEdge, type RelationExistsMarker, type RelationGraphReader, type RelayAttach, type RelayDetach, type RelayFrame, type RelayHost, RelayMember, type RelayPokeDelivery, type RelayShapePoke, type RelayShapeSeed, type RelayShapeSubscribe, type RelayShapeUnsubscribe, 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, SCHEDULE_OUTBOX_TABLE, SCHEMA_HISTORY_MAX_VERSIONS, SEARCH_STATE_TABLE, SHAPE_POKE_CURSOR_TABLE, type SchedulableWorkflowReferenceLike, type ScheduleOutbox, type ScheduleOutboxEnvelope, type ScheduleOutboxRow, type ScheduledFunctionDoc, type SchedulerLike, type SchemaLike, type ScoredDocument, type SearchBackfillProgress, type SearchFilterBuilderLike, type SearchIndexDefinitionLike, type SearchScoredDocument, type SelectMatchingIdsOptions, type ServerDefaultContextLike, type SettingEntry, type SettingKind, type SettingsResult, ShapeDiffCache, type ShapePokeCursorRow, type ShapePokePart, type ShapeProbeCounters, 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, UNVOUCHABLE_DEP, type ValidatorLike, type WhereInput, type WhereSqlStrategy, type WithInput, type WorkflowInstanceState, type WorkflowInstanceStatusResult, type WorkflowMetadata, type WorkflowsResult, type WriteEvent, type WriteHook, advanceClientWatermark, aggUpsertSql, aggregateSqlFunction, aggregateTableName, allocateCommitSeq, appendAuditEntry, appendCdcChange, appendStreamChunk, applyCdcChanges, applyOnDelete, applySelect, archiveCdcSegment, armRestore, assertFlatPredicate, assertNoExplicitUndefined, assertReadonly, assertShapeShardable, assertValidClientId, awaitWsDrain, backfillAggregateIndexes, backfillRankIndexes, backfillSearchIndexes, backfillSearchIndexesForTable, bigintSqlKey, boundingBoxCenter, boundingBoxGeohashes, buildIndexRange, buildPokeFrames, buildReprojectionMigration, buildSeekBeforeWhere, buildSeekWhere, buildSettings, buildShapeDiff, bumpCdcEpoch, cdcCanVouchFor, cdcSeqLeavingRows, cdcTouchesTables, cdcTrimmedError, claimStreamRun, clampPromotionThresholds, clearCapturedMail, clearMemoryTables, clearQueueMessages, coerceAggregateNumber, compactCdcDocs, compileWhereSql, computeRankPage, containsRelationPredicate, countLegacyRows, coveringGeohashes, createCompanionSync, createDependencyTracker, createFanoutCounters, createGlobalPollCounters, createIndexSql, createReadFootprint, createRelayLink, createReplicaLink, createShapeDiffCache, createShapeProbeCounters, createShardCtxDb, createSystemReader, cursorBelowRetainedFloor, decideDurableAttach, decodeBigintSqlKey, decodeCursor, decodeFloat64SqlKey, deferScheduleOutbox, deleteGlobalShapeSnapshot, deleteGlobalShapeSnapshotsForConnection, deleteShapePokeCursor, deleteShapePokeCursorsForConnection, deleteStreamRun, depKey, deriveRelationEdges, diffExternalSource, diffGlobalMembership, distinctValues, encodeAggregateKey, encodeCursor, encodeGeohash, encodePartitionKey, encodeRowsPatch, ensureAuditTable, ensureMailTable, envOptionalPositiveInt, envPositiveInt, equalityPinnedFields, exportShardRows, facetColumn, fanOutScalarCounts, findRelated, findStorageReferences, finishStreamRun, float64SqlKey, foldAggregateTally, forgetScheduleOutbox, gateReplicaDispatch, geoTableName, globalShapeReadKey, guardWriter, handleReplicaControl, hasTrigger, haversineMeters, importShardRows, indexKeysForRow, isDevEnvironment, isFtsAvailable, isLossyBody, isMemoryTable, isRelationPredicate, isSoftDeleted, isSourceDue, jsonPath, jsonPathSql, keysTouchRanges, liftSourceId, lintReadonlySql, listReactorStates, listTables, literalInList, markUnvouchableReads, matchesRankStaticWhere, matchesStaticWhere, materializeExternalRows, materializeExternalRowsIncremental, memoryTableNames, mergeChangedKeys, mergeWhere, migrateCdcLog, migrateCdcMeta, migrateClientWatermark, migrateCommitSeq, migrateDurableStreams, migrateGlobalShapeSnapshot, migrateIdempotency, migrateReactorState, migrateScheduleOutbox, migrateSearchState, migrateShapePokeCursor, minCdcReplayableSeq, minCdcSeq, minShapePokeCursor, nextPromotionState, normalizeCountArgument, normalizeIdStructurally, normalizeOrderKeys, normalizeSourceDocument, normalizeSourceValue, param, parkScheduleOutbox, parseExportShardArgs, parseImportShardArgs, planAggregateLookup, pointInBoundingBox, probeScheduleOutbox, projectColumns, pullExternalSourceIncrementalTick, pullExternalSourceTick, qualifiedJsonPath, qualifiedJsonPathSql, quoteIdentifier, rankKeyFromDocument as rankKeyFromDoc, rankPivotConditionSql, rankTableName, reactiveCacheKey, reactorNeedsRun, readAggregateValue, readArchivedCdcChanges, readAuditLog, readBookmark, readCapturedMail, readCdcArchivedThrough, readCdcChangeKeys, readCdcChanges, readCdcCursor, readCdcEpoch, readClientWatermark, readCommitSeq, readDeployInfo, readDueScheduleOutbox, readExternalSourceBaseline, readGlobalShapeSnapshot, readIdempotent, readMigrationStatus, readQueueMessageById, readQueueMessages, readReactorState, readSchemaHistory, readSchemaVersion, readSearchBackfillState, readShapePokeCursor, readStreamChunks, readStreamRun, readTablePage, recordCapturedMail, recordChangedKeys, recordFanoutPass, recordGlobalPollPass, recordQueueMessages, recordScheduleOutbox, recordSchemaVersion, recordShapeProbePass, relationHooks, relayCountFor, renderSql, reprojectableFields, reprojectionMigrationId, reprojectionTables, resolveRankPartition, resolveRankSeekTuple, resolveRelationPredicates, resolveWith, rowToDocument, runDataMigration, runDrizzle, runExternalSourceTick, runReadonlySql, runRowValidators, runShardMigrations, runSocketPool, runSql, runTriggers, selectExpiredIds, selectExportTables, selectIndexForAggregate, selectIndexForCount, selectIndexForGroupBy, selectMatchingIds, selectShapeMembers, selectShapeRows, serializeSqlValue, shapeRoutingKey, softDeleteScope, sortColumnName, sqliteInList, stableStringify, stableWireKey, subscriptionFrames, subscriptionListDeltas, summarizeFanoutTopics, summarizeSubscriptions, tableColumns, tableFromDepKey, throwingScheduler, tiebreakDirectionFor, trimCdcChanges, trimIdempotent, trimScheduleOutbox, trimStreamRuns, tryRowToDocument, trySendFrame, unionAll, uniqueIndexFields, validateImportRow, writeCdcArchivedThrough, writeGlobalShapeSnapshot, writeIdempotent, writeReactorState, writeSearchBackfillState, writeShapePokeCursor, writeShapePokeCursors, writeTouchesMemo };
package/dist/index.mjs CHANGED
@@ -1 +1 @@
1
- import{exportShardRows as o,importShardRows as a,parseExportShardArgs as t,parseImportShardArgs as n,selectExportTables as i,validateImportRow as l}from"./packem_shared/exportShardRows-D_upYHRQ.mjs";import{AGGREGATE_SQL_FUNCTION as m,aggregateSqlFunction as c,matchesStaticWhere as d,normalizeCountArgument as p,throwingScheduler as S}from"./packem_shared/AGGREGATE_SQL_FUNCTION-DDEoMnJR.mjs";import{aggregateTableName as f,coerceAggregateNumber as E,encodeAggregateKey as T,foldAggregateTally as h,readAggregateValue as x}from"./packem_shared/aggregateTableName-C7o-gpms.mjs";import{CountRlsUnsupportedError as R,mergeWhere as A,planAggregateLookup as g,selectIndexForAggregate as _,selectIndexForCount as I,selectIndexForGroupBy as b}from"./packem_shared/CountRlsUnsupportedError-BvsDqfO2.mjs";import{AUDIT_LOG_TABLE as D,appendAuditEntry as P,ensureAuditTable as M,readAuditLog as y}from"./packem_shared/AUDIT_LOG_TABLE-ONxmEAIz.mjs";import{NotUniqueError as N,assertNoExplicitUndefined as O,assertValidClientId as k,createShardCtxDb as B,normalizeIdStructurally as G}from"./packem_shared/NotUniqueError-BMom69SD.mjs";import{backfillAggregateIndexes as q,backfillRankIndexes as K,backfillSearchIndexes as w,backfillSearchIndexesForTable as v}from"./packem_shared/backfillAggregateIndexes-BG5-SC1q.mjs";import{CDC_LOG_TABLE as X,CDC_LOG_TABLE_SEQ_INDEX as H,CDC_META_TABLE as z,appendCdcChange as V,applyCdcChanges as Q,bumpCdcEpoch as Y,cdcCanVouchFor as j,cdcSeqLeavingRows as J,cdcTouchesTables as Z,cdcTrimmedError as $,compactCdcDocs as ee,cursorBelowRetainedFloor as re,migrateCdcLog as oe,migrateCdcMeta as ae,minCdcReplayableSeq as te,minCdcSeq as ne,readCdcChangeKeys as ie,readCdcChanges as le,readCdcCursor as se,readCdcEpoch as me,trimCdcChanges as ce}from"./packem_shared/CDC_LOG_TABLE-vVheEulD.mjs";import{archiveCdcSegment as pe,readArchivedCdcChanges as Se,readCdcArchivedThrough as ue,writeCdcArchivedThrough as fe}from"./packem_shared/archiveCdcSegment-DU4uzDFQ.mjs";import{CLIENT_WATERMARK_TABLE as Te,advanceClientWatermark as he,migrateClientWatermark as xe,readClientWatermark as Ce}from"./packem_shared/CLIENT_WATERMARK_TABLE-CRnrAnJ2.mjs";import{COMMIT_SEQ_FIELD as Ae,COMMIT_SEQ_TABLE as ge,allocateCommitSeq as _e,migrateCommitSeq as Ie,readCommitSeq as be}from"./packem_shared/COMMIT_SEQ_FIELD-BUdOMG5y.mjs";import{c as De}from"./packem_shared/ctx-db-companions-w-CfeOda.mjs";import{GLOBAL_SHAPE_SNAPSHOT_TABLE as Me,deleteGlobalShapeSnapshot as ye,deleteGlobalShapeSnapshotsForConnection as Fe,migrateGlobalShapeSnapshot as Ne,readGlobalShapeSnapshot as Oe,writeGlobalShapeSnapshot as ke}from"./packem_shared/GLOBAL_SHAPE_SNAPSHOT_TABLE-DSA6mzyx.mjs";import{IDEMPOTENCY_TABLE as Ge,migrateIdempotency as Ue,readIdempotent as qe,trimIdempotent as Ke,writeIdempotent as we}from"./packem_shared/IDEMPOTENCY_TABLE-DOpm_oMF.mjs";import{clearMemoryTables as We,isMemoryTable as Xe,memoryTableNames as He}from"./packem_shared/clearMemoryTables-BGbmag2i.mjs";import{computeRankPage as Ve,resolveRankSeekTuple as Qe}from"./packem_shared/computeRankPage-DsQ16o1z.mjs";import{S as je,m as Je,r as Ze,w as $e}from"./packem_shared/ctx-db-search-state-ruTuCsxa.mjs";import{SHAPE_POKE_CURSOR_TABLE as rr,deleteShapePokeCursor as or,deleteShapePokeCursorsForConnection as ar,migrateShapePokeCursor as tr,minShapePokeCursor as nr,readShapePokeCursor as ir,writeShapePokeCursor as lr,writeShapePokeCursors as sr}from"./packem_shared/SHAPE_POKE_CURSOR_TABLE-ByJVDHds.mjs";import{selectShapeMembers as cr,selectShapeRows as dr}from"./packem_shared/selectShapeMembers-CCZyZggM.mjs";import{DATA_MIGRATION_STATE_TABLE as Sr,readMigrationStatus as ur,runDataMigration as fr}from"./packem_shared/DATA_MIGRATION_STATE_TABLE-BNMWxRzv.mjs";import{SCAN_DEP as Tr,createDependencyTracker as hr,depKey as xr,tableFromDepKey as Cr}from"./packem_shared/SCAN_DEP-D7qE3iUe.mjs";import{runDrizzle as Ar,runSql as gr}from"./packem_shared/runDrizzle-2ULFQR_k.mjs";import{A as Ir,a as br,b as Lr,D as Dr,c as Pr,d as Mr,g as yr,i as Fr,j as Nr,e as Or,q as kr,f as Br,r as Gr,t as Ur,h as qr}from"./packem_shared/do-sql-Dvj8Yl5N.mjs";import{param as wr,renderSql as vr,sqliteInList as Wr,unionAll as Xr}from"./packem_shared/param-DlozcSQu.mjs";import{appendStreamChunk as zr,claimStreamRun as Vr,deleteStreamRun as Qr,finishStreamRun as Yr,migrateDurableStreams as jr,readStreamChunks as Jr,readStreamRun as Zr,trimStreamRuns as $r}from"./packem_shared/appendStreamChunk-C1Ok4b6J.mjs";import{DurableStreamRunner as ro,MAX_DURABLE_STREAM_BYTES as oo,MAX_DURABLE_STREAM_CHUNKS as ao,decideDurableAttach as to}from"./packem_shared/DurableStreamRunner-rTYp4v03.mjs";import{envOptionalPositiveInt as io,envPositiveInt as lo}from"./packem_shared/envOptionalPositiveInt-D2pY-c64.mjs";import{diffExternalSource as mo}from"./packem_shared/diffExternalSource-DgDJhslq.mjs";import{liftSourceId as po,normalizeSourceDocument as So,normalizeSourceValue as uo}from"./packem_shared/liftSourceId-CA3ENhXj.mjs";import{materializeExternalRows as Eo,materializeExternalRowsIncremental as To,readExternalSourceBaseline as ho,runExternalSourceTick as xo}from"./packem_shared/materializeExternalRows-iEVQKOKT.mjs";import{isSoftDeleted as Ro,isSourceDue as Ao,pullExternalSourceIncrementalTick as go,pullExternalSourceTick as _o}from"./packem_shared/isSoftDeleted-CYf6ijO3.mjs";import{GEO_DEFAULT_PRECISION as bo,boundingBoxCenter as Lo,boundingBoxGeohashes as Do,coveringGeohashes as Po,encodeGeohash as Mo,haversineMeters as yo,pointInBoundingBox as Fo}from"./packem_shared/GEO_DEFAULT_PRECISION-CqpQZ-J_.mjs";import{default as Oo}from"./packem_shared/GlobalPollTick-BNK4o-XT.mjs";import{ADMIN_FUNCTIONS as Bo,ADMIN_FUNCTION_PREFIX as Go,DEFAULT_FANOUT_TOPIC_LIMIT as Uo,FLAGS_FUNCTION_PREFIX as qo,MAX_PAGE_SIZE as Ko,RELATION_FUNCTION_PREFIX as wo,createFanoutCounters as vo,createGlobalPollCounters as Wo,createShapeProbeCounters as Xo,facetColumn as Ho,findStorageReferences as zo,listTables as Vo,readTablePage as Qo,recordFanoutPass as Yo,recordGlobalPollPass as jo,recordShapeProbePass as Jo,selectMatchingIds as Zo,summarizeFanoutTopics as $o,summarizeSubscriptions as ea}from"./packem_shared/ADMIN_FUNCTIONS-INdhzK8S.mjs";import{MAIL_RETENTION as oa,MAIL_TABLE as aa,clearCapturedMail as ta,ensureMailTable as na,readCapturedMail as ia,recordCapturedMail as la}from"./packem_shared/MAIL_RETENTION-DGAQTHHs.mjs";import{NotFoundError as ma}from"./packem_shared/NotFoundError-BhF7FeFr.mjs";import{armRestore as da,readBookmark as pa}from"./packem_shared/armRestore-Bu1_8SUa.mjs";import{CURSOR_PREFIX as ua,applySelect as fa,buildSeekBeforeWhere as Ea,buildSeekWhere as Ta,decodeCursor as ha,encodeCursor as xa,equalityPinnedFields as Ca,normalizeOrderKeys as Ra,softDeleteScope as Aa,tiebreakDirectionFor as ga,uniqueIndexFields as _a}from"./packem_shared/CURSOR_PREFIX-Bn8SFoGd.mjs";import{QUEUE_TABLE as ba,clearQueueMessages as La,isLossyBody as Da,readQueueMessageById as Pa,readQueueMessages as Ma,recordQueueMessages as ya}from"./packem_shared/QUEUE_TABLE-s7QJZvBz.mjs";import{RANK_TIEBREAK as Na,encodePartitionKey as Oa,matchesRankStaticWhere as ka,rankKeyFromDoc as Ba,rankPivotConditionSql as Ga,rankTableName as Ua,resolveRankPartition as qa,sortColumnName as Ka}from"./packem_shared/RANK_TIEBREAK-BXDiMmkH.mjs";import{ReactiveCache as va,reactiveCacheKey as Wa}from"./packem_shared/ReactiveCache-CzeUmTTN.mjs";import{REACTOR_STATE_TABLE as Ha,listReactorStates as za,migrateReactorState as Va,reactorNeedsRun as Qa,readReactorState as Ya,writeReactorState as ja}from"./packem_shared/REACTOR_STATE_TABLE-QPRFyxMS.mjs";import{UNVOUCHABLE_DEP as Za,createReadFootprint as $a,markUnvouchableReads as et}from"./packem_shared/UNVOUCHABLE_DEP-C68htACn.mjs";import{buildIndexRange as ot,indexKeysForRow as at,keysTouchRanges as tt}from"./packem_shared/buildIndexRange-NtciKq3M.mjs";import{RELATED_DEFAULT_LIMIT as it,RELATED_DEPTH_DECAY as lt,RELATED_MAX_DEPTH as st,RELATED_MAX_LIMIT as mt,deriveRelationEdges as ct,findRelated as dt}from"./packem_shared/RELATED_DEFAULT_LIMIT-B9PH28Pn.mjs";import{DEFAULT_MAX_RELATION_KEYS as St,assertFlatPredicate as ut,assertShapeShardable as ft,containsRelationPredicate as Et,isRelationPredicate as Tt,resolveRelationPredicates as ht}from"./packem_shared/DEFAULT_MAX_RELATION_KEYS-XESc7TiB.mjs";import{applyOnDelete as Ct,distinctValues as Rt,fanOutScalarCounts as At,relationHooks as gt,resolveWith as _t,runRowValidators as It}from"./packem_shared/applyOnDelete-7JZ4vR9r.mjs";import{DEFAULT_PROMOTION_THRESHOLDS as Lt,clampPromotionThresholds as Dt,nextPromotionState as Pt,relayCountFor as Mt,shapeRoutingKey as yt}from"./packem_shared/DEFAULT_PROMOTION_THRESHOLDS-Bfx7KakS.mjs";import{DEFAULT_MAX_RELAYS as Nt,OwnerRelay as Ot,RelayMember as kt,createRelayLink as Bt}from"./packem_shared/DEFAULT_MAX_RELAYS-Ng4SyJ7k.mjs";import{createReplicaLink as Ut,gateReplicaDispatch as qt,handleReplicaControl as Kt}from"./packem_shared/createReplicaLink-Bo4IWADY.mjs";import{buildReprojectionMigration as vt,countLegacyRows as Wt,reprojectableFields as Xt,reprojectionTables as Ht}from"./packem_shared/buildReprojectionMigration-Coeg-J0M.mjs";import{RLS_UNWRAP_SYMBOL as Vt,RlsRequiredError as Qt,guardWriter as Yt}from"./packem_shared/RLS_UNWRAP_SYMBOL-BwwTbz3Q.mjs";import{SCHEMA_HISTORY_MAX_VERSIONS as Jt,readSchemaHistory as Zt,readSchemaVersion as $t,recordSchemaVersion as en}from"./packem_shared/SCHEMA_HISTORY_MAX_VERSIONS-BluIj2s-.mjs";import{serializeSqlValue as on}from"./packem_shared/serializeSqlValue-CjbhIHjJ.mjs";import{buildSettings as tn,isDevEnvironment as nn,readDeployInfo as ln}from"./packem_shared/buildSettings-DC3VeQ0H.mjs";import{buildShapeDiff as mn}from"./packem_shared/buildShapeDiff-WSoMs1_h.mjs";import{ShapeDiffCache as dn,createShapeDiffCache as pn,globalShapeReadKey as Sn}from"./packem_shared/ShapeDiffCache-gdaILV5E.mjs";import{buildPokeFrames as fn,diffGlobalMembership as En,encodeRowsPatch as Tn,projectColumns as hn}from"./packem_shared/buildPokeFrames-BBE6J91z.mjs";import{ShardRunner as Cn}from"./packem_shared/ShardRunner-C9p5DVOx.mjs";import{runSocketPool as An}from"./packem_shared/runSocketPool-CZJ2X9cF.mjs";import{MAX_SQL_ROWS as _n,assertReadonly as In,lintReadonlySql as bn,runReadonlySql as Ln}from"./packem_shared/MAX_SQL_ROWS-Dh_Ty0Zo.mjs";import{B as Pn,b as Mn,d as yn,a as Fn,f as Nn}from"./packem_shared/sql-projection-BB2lCbYV.mjs";import{awaitWsDrain as kn,subscriptionFrames as Bn,subscriptionListDeltas as Gn,trySendFrame as Un}from"./packem_shared/awaitWsDrain-apizgmKY.mjs";import{mergeChangedKeys as Kn,recordChangedKeys as wn,writeTouchesMemo as vn}from"./packem_shared/mergeChangedKeys-CPw4EamV.mjs";import{createSystemReader as Xn}from"./packem_shared/createSystemReader-DcDLFfC-.mjs";import{ConflictError as zn}from"./packem_shared/ConflictError-C8GtJmjS.mjs";import{DEFAULT_TRANSACTION_LIMITS as Qn,TransactionHeadroomTracker as Yn}from"./packem_shared/DEFAULT_TRANSACTION_LIMITS-DDGk9ebh.mjs";import{hasTrigger as Jn,runTriggers as Zn}from"./packem_shared/hasTrigger-CjlwI4le.mjs";import{selectExpiredIds as ei}from"./packem_shared/selectExpiredIds-CKOUTIHn.mjs";import{c as oi,l as ai}from"./packem_shared/where-sql-x1YKldcq.mjs";import{RELATION_EXISTS_KEY as ni}from"./packem_shared/RELATION_EXISTS_KEY-CFUhnZSZ.mjs";import{REPROJECTION_MIGRATION_PREFIX as li,reprojectionMigrationId as si}from"./packem_shared/REPROJECTION_MIGRATION_PREFIX-Czcb6_mO.mjs";import{quoteIdentifier as ci}from"./packem_shared/quoteIdentifier-CObIFRhb.mjs";import{runShardMigrations as pi}from"./packem_shared/runShardMigrations-CeT_SVrI.mjs";import{stableStringify as ui}from"./packem_shared/stableStringify-DibjylKD.mjs";import{stableWireKey as Ei}from"./packem_shared/stableWireKey-D2US4k_J.mjs";export{Bo as ADMIN_FUNCTIONS,Go as ADMIN_FUNCTION_PREFIX,m as AGGREGATE_SQL_FUNCTION,Ir as AGG_COUNT,br as AGG_KEY,Lr as AGG_VALUE,D as AUDIT_LOG_TABLE,Pn as BIGINT_KEY_DIGITS,X as CDC_LOG_TABLE,H as CDC_LOG_TABLE_SEQ_INDEX,z as CDC_META_TABLE,Te as CLIENT_WATERMARK_TABLE,Ae as COMMIT_SEQ_FIELD,ge as COMMIT_SEQ_TABLE,ua as CURSOR_PREFIX,zn as ConflictError,R as CountRlsUnsupportedError,Sr as DATA_MIGRATION_STATE_TABLE,Uo as DEFAULT_FANOUT_TOPIC_LIMIT,St as DEFAULT_MAX_RELATION_KEYS,Nt as DEFAULT_MAX_RELAYS,Lt as DEFAULT_PROMOTION_THRESHOLDS,Qn as DEFAULT_TRANSACTION_LIMITS,Dr as DOC_COLUMN,ro as DurableStreamRunner,qo as FLAGS_FUNCTION_PREFIX,bo as GEO_DEFAULT_PRECISION,Me as GLOBAL_SHAPE_SNAPSHOT_TABLE,Oo as GlobalPollTick,Ge as IDEMPOTENCY_TABLE,oa as MAIL_RETENTION,aa as MAIL_TABLE,oo as MAX_DURABLE_STREAM_BYTES,ao as MAX_DURABLE_STREAM_CHUNKS,Ko as MAX_PAGE_SIZE,_n as MAX_SQL_ROWS,ma as NotFoundError,N as NotUniqueError,Ot as OwnerRelay,ba as QUEUE_TABLE,Na as RANK_TIEBREAK,Ha as REACTOR_STATE_TABLE,it as RELATED_DEFAULT_LIMIT,lt as RELATED_DEPTH_DECAY,st as RELATED_MAX_DEPTH,mt as RELATED_MAX_LIMIT,ni as RELATION_EXISTS_KEY,wo as RELATION_FUNCTION_PREFIX,li as REPROJECTION_MIGRATION_PREFIX,Vt as RLS_UNWRAP_SYMBOL,va as ReactiveCache,kt as RelayMember,Qt as RlsRequiredError,Tr as SCAN_DEP,Jt as SCHEMA_HISTORY_MAX_VERSIONS,je as SEARCH_STATE_TABLE,rr as SHAPE_POKE_CURSOR_TABLE,dn as ShapeDiffCache,Cn as ShardRunner,Yn as TransactionHeadroomTracker,Za as UNVOUCHABLE_DEP,he as advanceClientWatermark,Pr as aggUpsertSql,c as aggregateSqlFunction,f as aggregateTableName,_e as allocateCommitSeq,P as appendAuditEntry,V as appendCdcChange,zr as appendStreamChunk,Q as applyCdcChanges,Ct as applyOnDelete,fa as applySelect,pe as archiveCdcSegment,da as armRestore,ut as assertFlatPredicate,O as assertNoExplicitUndefined,In as assertReadonly,ft as assertShapeShardable,k as assertValidClientId,kn as awaitWsDrain,q as backfillAggregateIndexes,K as backfillRankIndexes,w as backfillSearchIndexes,v as backfillSearchIndexesForTable,Mn as bigintSqlKey,Lo as boundingBoxCenter,Do as boundingBoxGeohashes,ot as buildIndexRange,fn as buildPokeFrames,vt as buildReprojectionMigration,Ea as buildSeekBeforeWhere,Ta as buildSeekWhere,tn as buildSettings,mn as buildShapeDiff,Y as bumpCdcEpoch,j as cdcCanVouchFor,J as cdcSeqLeavingRows,Z as cdcTouchesTables,$ as cdcTrimmedError,Vr as claimStreamRun,Dt as clampPromotionThresholds,ta as clearCapturedMail,We as clearMemoryTables,La as clearQueueMessages,E as coerceAggregateNumber,ee as compactCdcDocs,oi as compileWhereSql,Ve as computeRankPage,Et as containsRelationPredicate,Wt as countLegacyRows,Po as coveringGeohashes,De as createCompanionSync,hr as createDependencyTracker,vo as createFanoutCounters,Wo as createGlobalPollCounters,Mr as createIndexSql,$a as createReadFootprint,Bt as createRelayLink,Ut as createReplicaLink,pn as createShapeDiffCache,Xo as createShapeProbeCounters,B as createShardCtxDb,Xn as createSystemReader,re as cursorBelowRetainedFloor,to as decideDurableAttach,yn as decodeBigintSqlKey,ha as decodeCursor,Fn as decodeFloat64SqlKey,ye as deleteGlobalShapeSnapshot,Fe as deleteGlobalShapeSnapshotsForConnection,or as deleteShapePokeCursor,ar as deleteShapePokeCursorsForConnection,Qr as deleteStreamRun,xr as depKey,ct as deriveRelationEdges,mo as diffExternalSource,En as diffGlobalMembership,Rt as distinctValues,T as encodeAggregateKey,xa as encodeCursor,Mo as encodeGeohash,Oa as encodePartitionKey,Tn as encodeRowsPatch,M as ensureAuditTable,na as ensureMailTable,io as envOptionalPositiveInt,lo as envPositiveInt,Ca as equalityPinnedFields,o as exportShardRows,Ho as facetColumn,At as fanOutScalarCounts,dt as findRelated,zo as findStorageReferences,Yr as finishStreamRun,Nn as float64SqlKey,h as foldAggregateTally,qt as gateReplicaDispatch,yr as geoTableName,Sn as globalShapeReadKey,Yt as guardWriter,Kt as handleReplicaControl,Jn as hasTrigger,yo as haversineMeters,a as importShardRows,at as indexKeysForRow,nn as isDevEnvironment,Fr as isFtsAvailable,Da as isLossyBody,Xe as isMemoryTable,Tt as isRelationPredicate,Ro as isSoftDeleted,Ao as isSourceDue,Nr as jsonPath,Or as jsonPathSql,tt as keysTouchRanges,po as liftSourceId,bn as lintReadonlySql,za as listReactorStates,Vo as listTables,ai as literalInList,et as markUnvouchableReads,ka as matchesRankStaticWhere,d as matchesStaticWhere,Eo as materializeExternalRows,To as materializeExternalRowsIncremental,He as memoryTableNames,Kn as mergeChangedKeys,A as mergeWhere,oe as migrateCdcLog,ae as migrateCdcMeta,xe as migrateClientWatermark,Ie as migrateCommitSeq,jr as migrateDurableStreams,Ne as migrateGlobalShapeSnapshot,Ue as migrateIdempotency,Va as migrateReactorState,Je as migrateSearchState,tr as migrateShapePokeCursor,te as minCdcReplayableSeq,ne as minCdcSeq,nr as minShapePokeCursor,Pt as nextPromotionState,p as normalizeCountArgument,G as normalizeIdStructurally,Ra as normalizeOrderKeys,So as normalizeSourceDocument,uo as normalizeSourceValue,wr as param,t as parseExportShardArgs,n as parseImportShardArgs,g as planAggregateLookup,Fo as pointInBoundingBox,hn as projectColumns,go as pullExternalSourceIncrementalTick,_o as pullExternalSourceTick,kr as qualifiedJsonPath,Br as qualifiedJsonPathSql,ci as quoteIdentifier,Ba as rankKeyFromDoc,Ga as rankPivotConditionSql,Ua as rankTableName,Wa as reactiveCacheKey,Qa as reactorNeedsRun,x as readAggregateValue,Se as readArchivedCdcChanges,y as readAuditLog,pa as readBookmark,ia as readCapturedMail,ue as readCdcArchivedThrough,ie as readCdcChangeKeys,le as readCdcChanges,se as readCdcCursor,me as readCdcEpoch,Ce as readClientWatermark,be as readCommitSeq,ln as readDeployInfo,ho as readExternalSourceBaseline,Oe as readGlobalShapeSnapshot,qe as readIdempotent,ur as readMigrationStatus,Pa as readQueueMessageById,Ma as readQueueMessages,Ya as readReactorState,Zt as readSchemaHistory,$t as readSchemaVersion,Ze as readSearchBackfillState,ir as readShapePokeCursor,Jr as readStreamChunks,Zr as readStreamRun,Qo as readTablePage,la as recordCapturedMail,wn as recordChangedKeys,Yo as recordFanoutPass,jo as recordGlobalPollPass,ya as recordQueueMessages,en as recordSchemaVersion,Jo as recordShapeProbePass,gt as relationHooks,Mt as relayCountFor,vr as renderSql,Xt as reprojectableFields,si as reprojectionMigrationId,Ht as reprojectionTables,qa as resolveRankPartition,Qe as resolveRankSeekTuple,ht as resolveRelationPredicates,_t as resolveWith,Gr as rowToDocument,fr as runDataMigration,Ar as runDrizzle,xo as runExternalSourceTick,Ln as runReadonlySql,It as runRowValidators,pi as runShardMigrations,An as runSocketPool,gr as runSql,Zn as runTriggers,ei as selectExpiredIds,i as selectExportTables,_ as selectIndexForAggregate,I as selectIndexForCount,b as selectIndexForGroupBy,Zo as selectMatchingIds,cr as selectShapeMembers,dr as selectShapeRows,on as serializeSqlValue,yt as shapeRoutingKey,Aa as softDeleteScope,Ka as sortColumnName,Wr as sqliteInList,ui as stableStringify,Ei as stableWireKey,Bn as subscriptionFrames,Gn as subscriptionListDeltas,$o as summarizeFanoutTopics,ea as summarizeSubscriptions,Ur as tableColumns,Cr as tableFromDepKey,S as throwingScheduler,ga as tiebreakDirectionFor,ce as trimCdcChanges,Ke as trimIdempotent,$r as trimStreamRuns,qr as tryRowToDocument,Un as trySendFrame,Xr as unionAll,_a as uniqueIndexFields,l as validateImportRow,fe as writeCdcArchivedThrough,ke as writeGlobalShapeSnapshot,we as writeIdempotent,ja as writeReactorState,$e as writeSearchBackfillState,lr as writeShapePokeCursor,sr as writeShapePokeCursors,vn as writeTouchesMemo};
1
+ import{exportShardRows as o,importShardRows as a,parseExportShardArgs as t,parseImportShardArgs as l,selectExportTables as n,validateImportRow as i}from"./packem_shared/exportShardRows-D_upYHRQ.mjs";import{AGGREGATE_SQL_FUNCTION as d,aggregateSqlFunction as c,matchesStaticWhere as m,normalizeCountArgument as p,throwingScheduler as S}from"./packem_shared/AGGREGATE_SQL_FUNCTION-DDEoMnJR.mjs";import{aggregateTableName as f,coerceAggregateNumber as E,encodeAggregateKey as h,foldAggregateTally as x,readAggregateValue as T}from"./packem_shared/aggregateTableName-C7o-gpms.mjs";import{CountRlsUnsupportedError as A,mergeWhere as R,planAggregateLookup as g,selectIndexForAggregate as _,selectIndexForCount as I,selectIndexForGroupBy as b}from"./packem_shared/CountRlsUnsupportedError-BvsDqfO2.mjs";import{AUDIT_LOG_TABLE as D,appendAuditEntry as O,ensureAuditTable as P,readAuditLog as M}from"./packem_shared/AUDIT_LOG_TABLE-ONxmEAIz.mjs";import{NotUniqueError as F,assertNoExplicitUndefined as N,assertValidClientId as k,createShardCtxDb as B,normalizeIdStructurally as U}from"./packem_shared/NotUniqueError-BA2p0rlT.mjs";import{backfillAggregateIndexes as q,backfillRankIndexes as K,backfillSearchIndexes as w,backfillSearchIndexesForTable as v}from"./packem_shared/backfillAggregateIndexes-BG5-SC1q.mjs";import{CDC_LOG_TABLE as H,CDC_LOG_TABLE_SEQ_INDEX as W,CDC_META_TABLE as z,appendCdcChange as V,applyCdcChanges as Q,bumpCdcEpoch as Y,cdcCanVouchFor as j,cdcSeqLeavingRows as J,cdcTouchesTables as Z,cdcTrimmedError as $,compactCdcDocs as ee,cursorBelowRetainedFloor as re,migrateCdcLog as oe,migrateCdcMeta as ae,minCdcReplayableSeq as te,minCdcSeq as le,readCdcChangeKeys as ne,readCdcChanges as ie,readCdcCursor as se,readCdcEpoch as de,trimCdcChanges as ce}from"./packem_shared/CDC_LOG_TABLE-vVheEulD.mjs";import{archiveCdcSegment as pe,readArchivedCdcChanges as Se,readCdcArchivedThrough as ue,writeCdcArchivedThrough as fe}from"./packem_shared/archiveCdcSegment-DU4uzDFQ.mjs";import{CLIENT_WATERMARK_TABLE as he,advanceClientWatermark as xe,migrateClientWatermark as Te,readClientWatermark as Ce}from"./packem_shared/CLIENT_WATERMARK_TABLE-CRnrAnJ2.mjs";import{COMMIT_SEQ_FIELD as Re,COMMIT_SEQ_TABLE as ge,allocateCommitSeq as _e,migrateCommitSeq as Ie,readCommitSeq as be}from"./packem_shared/COMMIT_SEQ_FIELD-BUdOMG5y.mjs";import{c as De}from"./packem_shared/ctx-db-companions-w-CfeOda.mjs";import{GLOBAL_SHAPE_SNAPSHOT_TABLE as Pe,deleteGlobalShapeSnapshot as Me,deleteGlobalShapeSnapshotsForConnection as ye,migrateGlobalShapeSnapshot as Fe,readGlobalShapeSnapshot as Ne,writeGlobalShapeSnapshot as ke}from"./packem_shared/GLOBAL_SHAPE_SNAPSHOT_TABLE-DSA6mzyx.mjs";import{IDEMPOTENCY_TABLE as Ue,migrateIdempotency as Ge,readIdempotent as qe,trimIdempotent as Ke,writeIdempotent as we}from"./packem_shared/IDEMPOTENCY_TABLE-DOpm_oMF.mjs";import{clearMemoryTables as Xe,isMemoryTable as He,memoryTableNames as We}from"./packem_shared/clearMemoryTables-BGbmag2i.mjs";import{computeRankPage as Ve,resolveRankSeekTuple as Qe}from"./packem_shared/computeRankPage-DsQ16o1z.mjs";import{SCHEDULE_OUTBOX_TABLE as je,deferScheduleOutbox as Je,forgetScheduleOutbox as Ze,migrateScheduleOutbox as $e,parkScheduleOutbox as er,probeScheduleOutbox as rr,readDueScheduleOutbox as or,recordScheduleOutbox as ar,trimScheduleOutbox as tr}from"./packem_shared/SCHEDULE_OUTBOX_TABLE-CD_UjYVx.mjs";import{S as nr,m as ir,r as sr,w as dr}from"./packem_shared/ctx-db-search-state-ruTuCsxa.mjs";import{SHAPE_POKE_CURSOR_TABLE as mr,deleteShapePokeCursor as pr,deleteShapePokeCursorsForConnection as Sr,migrateShapePokeCursor as ur,minShapePokeCursor as fr,readShapePokeCursor as Er,writeShapePokeCursor as hr,writeShapePokeCursors as xr}from"./packem_shared/SHAPE_POKE_CURSOR_TABLE-ByJVDHds.mjs";import{selectShapeMembers as Cr,selectShapeRows as Ar}from"./packem_shared/selectShapeMembers-CCZyZggM.mjs";import{DATA_MIGRATION_STATE_TABLE as gr,readMigrationStatus as _r,runDataMigration as Ir}from"./packem_shared/DATA_MIGRATION_STATE_TABLE-BNMWxRzv.mjs";import{SCAN_DEP as Lr,createDependencyTracker as Dr,depKey as Or,tableFromDepKey as Pr}from"./packem_shared/SCAN_DEP-D7qE3iUe.mjs";import{runDrizzle as yr,runSql as Fr}from"./packem_shared/runDrizzle-2ULFQR_k.mjs";import{A as kr,a as Br,b as Ur,D as Gr,c as qr,d as Kr,g as wr,i as vr,j as Xr,e as Hr,q as Wr,f as zr,r as Vr,t as Qr,h as Yr}from"./packem_shared/do-sql-Dvj8Yl5N.mjs";import{param as Jr,renderSql as Zr,sqliteInList as $r,unionAll as eo}from"./packem_shared/param-DlozcSQu.mjs";import{appendStreamChunk as oo,claimStreamRun as ao,deleteStreamRun as to,finishStreamRun as lo,migrateDurableStreams as no,readStreamChunks as io,readStreamRun as so,trimStreamRuns as co}from"./packem_shared/appendStreamChunk-C1Ok4b6J.mjs";import{DurableStreamRunner as po,MAX_DURABLE_STREAM_BYTES as So,MAX_DURABLE_STREAM_CHUNKS as uo,decideDurableAttach as fo}from"./packem_shared/DurableStreamRunner-rTYp4v03.mjs";import{envOptionalPositiveInt as ho,envPositiveInt as xo}from"./packem_shared/envOptionalPositiveInt-D2pY-c64.mjs";import{diffExternalSource as Co}from"./packem_shared/diffExternalSource-DgDJhslq.mjs";import{liftSourceId as Ro,normalizeSourceDocument as go,normalizeSourceValue as _o}from"./packem_shared/liftSourceId-CA3ENhXj.mjs";import{materializeExternalRows as bo,materializeExternalRowsIncremental as Lo,readExternalSourceBaseline as Do,runExternalSourceTick as Oo}from"./packem_shared/materializeExternalRows-iEVQKOKT.mjs";import{isSoftDeleted as Mo,isSourceDue as yo,pullExternalSourceIncrementalTick as Fo,pullExternalSourceTick as No}from"./packem_shared/isSoftDeleted-CYf6ijO3.mjs";import{GEO_DEFAULT_PRECISION as Bo,boundingBoxCenter as Uo,boundingBoxGeohashes as Go,coveringGeohashes as qo,encodeGeohash as Ko,haversineMeters as wo,pointInBoundingBox as vo}from"./packem_shared/GEO_DEFAULT_PRECISION-CqpQZ-J_.mjs";import{default as Ho}from"./packem_shared/GlobalPollTick-BNK4o-XT.mjs";import{ADMIN_FUNCTIONS as zo,ADMIN_FUNCTION_PREFIX as Vo,DEFAULT_FANOUT_TOPIC_LIMIT as Qo,FLAGS_FUNCTION_PREFIX as Yo,MAX_PAGE_SIZE as jo,RELATION_FUNCTION_PREFIX as Jo,createFanoutCounters as Zo,createGlobalPollCounters as $o,createShapeProbeCounters as ea,facetColumn as ra,findStorageReferences as oa,listTables as aa,readTablePage as ta,recordFanoutPass as la,recordGlobalPollPass as na,recordShapeProbePass as ia,selectMatchingIds as sa,summarizeFanoutTopics as da,summarizeSubscriptions as ca}from"./packem_shared/ADMIN_FUNCTIONS-INdhzK8S.mjs";import{MAIL_RETENTION as pa,MAIL_TABLE as Sa,clearCapturedMail as ua,ensureMailTable as fa,readCapturedMail as Ea,recordCapturedMail as ha}from"./packem_shared/MAIL_RETENTION-DGAQTHHs.mjs";import{NotFoundError as Ta}from"./packem_shared/NotFoundError-BhF7FeFr.mjs";import{armRestore as Aa,readBookmark as Ra}from"./packem_shared/armRestore-Bu1_8SUa.mjs";import{CURSOR_PREFIX as _a,applySelect as Ia,buildSeekBeforeWhere as ba,buildSeekWhere as La,decodeCursor as Da,encodeCursor as Oa,equalityPinnedFields as Pa,normalizeOrderKeys as Ma,softDeleteScope as ya,tiebreakDirectionFor as Fa,uniqueIndexFields as Na}from"./packem_shared/CURSOR_PREFIX-Bn8SFoGd.mjs";import{QUEUE_TABLE as Ba,clearQueueMessages as Ua,isLossyBody as Ga,readQueueMessageById as qa,readQueueMessages as Ka,recordQueueMessages as wa}from"./packem_shared/QUEUE_TABLE-s7QJZvBz.mjs";import{RANK_TIEBREAK as Xa,encodePartitionKey as Ha,matchesRankStaticWhere as Wa,rankKeyFromDoc as za,rankPivotConditionSql as Va,rankTableName as Qa,resolveRankPartition as Ya,sortColumnName as ja}from"./packem_shared/RANK_TIEBREAK-BXDiMmkH.mjs";import{ReactiveCache as Za,reactiveCacheKey as $a}from"./packem_shared/ReactiveCache-CzeUmTTN.mjs";import{REACTOR_STATE_TABLE as rt,listReactorStates as ot,migrateReactorState as at,reactorNeedsRun as tt,readReactorState as lt,writeReactorState as nt}from"./packem_shared/REACTOR_STATE_TABLE-QPRFyxMS.mjs";import{UNVOUCHABLE_DEP as st,createReadFootprint as dt,markUnvouchableReads as ct}from"./packem_shared/UNVOUCHABLE_DEP-C68htACn.mjs";import{buildIndexRange as pt,indexKeysForRow as St,keysTouchRanges as ut}from"./packem_shared/buildIndexRange-NtciKq3M.mjs";import{RELATED_DEFAULT_LIMIT as Et,RELATED_DEPTH_DECAY as ht,RELATED_MAX_DEPTH as xt,RELATED_MAX_LIMIT as Tt,deriveRelationEdges as Ct,findRelated as At}from"./packem_shared/RELATED_DEFAULT_LIMIT-B9PH28Pn.mjs";import{DEFAULT_MAX_RELATION_KEYS as gt,assertFlatPredicate as _t,assertShapeShardable as It,containsRelationPredicate as bt,isRelationPredicate as Lt,resolveRelationPredicates as Dt}from"./packem_shared/DEFAULT_MAX_RELATION_KEYS-XESc7TiB.mjs";import{applyOnDelete as Pt,distinctValues as Mt,fanOutScalarCounts as yt,relationHooks as Ft,resolveWith as Nt,runRowValidators as kt}from"./packem_shared/applyOnDelete-7JZ4vR9r.mjs";import{DEFAULT_PROMOTION_THRESHOLDS as Ut,clampPromotionThresholds as Gt,nextPromotionState as qt,relayCountFor as Kt,shapeRoutingKey as wt}from"./packem_shared/DEFAULT_PROMOTION_THRESHOLDS-Bfx7KakS.mjs";import{DEFAULT_MAX_RELAYS as Xt,OwnerRelay as Ht,RelayMember as Wt,createRelayLink as zt}from"./packem_shared/DEFAULT_MAX_RELAYS-Ng4SyJ7k.mjs";import{createReplicaLink as Qt,gateReplicaDispatch as Yt,handleReplicaControl as jt}from"./packem_shared/createReplicaLink-Bo4IWADY.mjs";import{buildReprojectionMigration as Zt,countLegacyRows as $t,reprojectableFields as el,reprojectionTables as rl}from"./packem_shared/buildReprojectionMigration-Coeg-J0M.mjs";import{RLS_UNWRAP_SYMBOL as al,RlsRequiredError as tl,guardWriter as ll}from"./packem_shared/RLS_UNWRAP_SYMBOL-BwwTbz3Q.mjs";import{SCHEMA_HISTORY_MAX_VERSIONS as il,readSchemaHistory as sl,readSchemaVersion as dl,recordSchemaVersion as cl}from"./packem_shared/SCHEMA_HISTORY_MAX_VERSIONS-BluIj2s-.mjs";import{serializeSqlValue as pl}from"./packem_shared/serializeSqlValue-CjbhIHjJ.mjs";import{buildSettings as ul,isDevEnvironment as fl,readDeployInfo as El}from"./packem_shared/buildSettings-DC3VeQ0H.mjs";import{buildShapeDiff as xl}from"./packem_shared/buildShapeDiff-WSoMs1_h.mjs";import{ShapeDiffCache as Cl,createShapeDiffCache as Al,globalShapeReadKey as Rl}from"./packem_shared/ShapeDiffCache-gdaILV5E.mjs";import{buildPokeFrames as _l,diffGlobalMembership as Il,encodeRowsPatch as bl,projectColumns as Ll}from"./packem_shared/buildPokeFrames-BBE6J91z.mjs";import{ShardRunner as Ol}from"./packem_shared/ShardRunner-C9p5DVOx.mjs";import{runSocketPool as Ml}from"./packem_shared/runSocketPool-CZJ2X9cF.mjs";import{MAX_SQL_ROWS as Fl,assertReadonly as Nl,lintReadonlySql as kl,runReadonlySql as Bl}from"./packem_shared/MAX_SQL_ROWS-Dh_Ty0Zo.mjs";import{B as Gl,b as ql,d as Kl,a as wl,f as vl}from"./packem_shared/sql-projection-BB2lCbYV.mjs";import{awaitWsDrain as Hl,subscriptionFrames as Wl,subscriptionListDeltas as zl,trySendFrame as Vl}from"./packem_shared/awaitWsDrain-apizgmKY.mjs";import{mergeChangedKeys as Yl,recordChangedKeys as jl,writeTouchesMemo as Jl}from"./packem_shared/mergeChangedKeys-CPw4EamV.mjs";import{createSystemReader as $l}from"./packem_shared/createSystemReader-DcDLFfC-.mjs";import{ConflictError as rn}from"./packem_shared/ConflictError-C8GtJmjS.mjs";import{DEFAULT_TRANSACTION_LIMITS as an,TransactionHeadroomTracker as tn}from"./packem_shared/DEFAULT_TRANSACTION_LIMITS-DDGk9ebh.mjs";import{hasTrigger as nn,runTriggers as sn}from"./packem_shared/hasTrigger-CjlwI4le.mjs";import{selectExpiredIds as cn}from"./packem_shared/selectExpiredIds-CKOUTIHn.mjs";import{c as pn,l as Sn}from"./packem_shared/where-sql-x1YKldcq.mjs";import{RELATION_EXISTS_KEY as fn}from"./packem_shared/RELATION_EXISTS_KEY-CFUhnZSZ.mjs";import{REPROJECTION_MIGRATION_PREFIX as hn,reprojectionMigrationId as xn}from"./packem_shared/REPROJECTION_MIGRATION_PREFIX-Czcb6_mO.mjs";import{quoteIdentifier as Cn}from"./packem_shared/quoteIdentifier-CObIFRhb.mjs";import{runShardMigrations as Rn}from"./packem_shared/runShardMigrations-DNFOFJe-.mjs";import{stableStringify as _n}from"./packem_shared/stableStringify-DibjylKD.mjs";import{stableWireKey as bn}from"./packem_shared/stableWireKey-D2US4k_J.mjs";export{zo as ADMIN_FUNCTIONS,Vo as ADMIN_FUNCTION_PREFIX,d as AGGREGATE_SQL_FUNCTION,kr as AGG_COUNT,Br as AGG_KEY,Ur as AGG_VALUE,D as AUDIT_LOG_TABLE,Gl as BIGINT_KEY_DIGITS,H as CDC_LOG_TABLE,W as CDC_LOG_TABLE_SEQ_INDEX,z as CDC_META_TABLE,he as CLIENT_WATERMARK_TABLE,Re as COMMIT_SEQ_FIELD,ge as COMMIT_SEQ_TABLE,_a as CURSOR_PREFIX,rn as ConflictError,A as CountRlsUnsupportedError,gr as DATA_MIGRATION_STATE_TABLE,Qo as DEFAULT_FANOUT_TOPIC_LIMIT,gt as DEFAULT_MAX_RELATION_KEYS,Xt as DEFAULT_MAX_RELAYS,Ut as DEFAULT_PROMOTION_THRESHOLDS,an as DEFAULT_TRANSACTION_LIMITS,Gr as DOC_COLUMN,po as DurableStreamRunner,Yo as FLAGS_FUNCTION_PREFIX,Bo as GEO_DEFAULT_PRECISION,Pe as GLOBAL_SHAPE_SNAPSHOT_TABLE,Ho as GlobalPollTick,Ue as IDEMPOTENCY_TABLE,pa as MAIL_RETENTION,Sa as MAIL_TABLE,So as MAX_DURABLE_STREAM_BYTES,uo as MAX_DURABLE_STREAM_CHUNKS,jo as MAX_PAGE_SIZE,Fl as MAX_SQL_ROWS,Ta as NotFoundError,F as NotUniqueError,Ht as OwnerRelay,Ba as QUEUE_TABLE,Xa as RANK_TIEBREAK,rt as REACTOR_STATE_TABLE,Et as RELATED_DEFAULT_LIMIT,ht as RELATED_DEPTH_DECAY,xt as RELATED_MAX_DEPTH,Tt as RELATED_MAX_LIMIT,fn as RELATION_EXISTS_KEY,Jo as RELATION_FUNCTION_PREFIX,hn as REPROJECTION_MIGRATION_PREFIX,al as RLS_UNWRAP_SYMBOL,Za as ReactiveCache,Wt as RelayMember,tl as RlsRequiredError,Lr as SCAN_DEP,je as SCHEDULE_OUTBOX_TABLE,il as SCHEMA_HISTORY_MAX_VERSIONS,nr as SEARCH_STATE_TABLE,mr as SHAPE_POKE_CURSOR_TABLE,Cl as ShapeDiffCache,Ol as ShardRunner,tn as TransactionHeadroomTracker,st as UNVOUCHABLE_DEP,xe as advanceClientWatermark,qr as aggUpsertSql,c as aggregateSqlFunction,f as aggregateTableName,_e as allocateCommitSeq,O as appendAuditEntry,V as appendCdcChange,oo as appendStreamChunk,Q as applyCdcChanges,Pt as applyOnDelete,Ia as applySelect,pe as archiveCdcSegment,Aa as armRestore,_t as assertFlatPredicate,N as assertNoExplicitUndefined,Nl as assertReadonly,It as assertShapeShardable,k as assertValidClientId,Hl as awaitWsDrain,q as backfillAggregateIndexes,K as backfillRankIndexes,w as backfillSearchIndexes,v as backfillSearchIndexesForTable,ql as bigintSqlKey,Uo as boundingBoxCenter,Go as boundingBoxGeohashes,pt as buildIndexRange,_l as buildPokeFrames,Zt as buildReprojectionMigration,ba as buildSeekBeforeWhere,La as buildSeekWhere,ul as buildSettings,xl as buildShapeDiff,Y as bumpCdcEpoch,j as cdcCanVouchFor,J as cdcSeqLeavingRows,Z as cdcTouchesTables,$ as cdcTrimmedError,ao as claimStreamRun,Gt as clampPromotionThresholds,ua as clearCapturedMail,Xe as clearMemoryTables,Ua as clearQueueMessages,E as coerceAggregateNumber,ee as compactCdcDocs,pn as compileWhereSql,Ve as computeRankPage,bt as containsRelationPredicate,$t as countLegacyRows,qo as coveringGeohashes,De as createCompanionSync,Dr as createDependencyTracker,Zo as createFanoutCounters,$o as createGlobalPollCounters,Kr as createIndexSql,dt as createReadFootprint,zt as createRelayLink,Qt as createReplicaLink,Al as createShapeDiffCache,ea as createShapeProbeCounters,B as createShardCtxDb,$l as createSystemReader,re as cursorBelowRetainedFloor,fo as decideDurableAttach,Kl as decodeBigintSqlKey,Da as decodeCursor,wl as decodeFloat64SqlKey,Je as deferScheduleOutbox,Me as deleteGlobalShapeSnapshot,ye as deleteGlobalShapeSnapshotsForConnection,pr as deleteShapePokeCursor,Sr as deleteShapePokeCursorsForConnection,to as deleteStreamRun,Or as depKey,Ct as deriveRelationEdges,Co as diffExternalSource,Il as diffGlobalMembership,Mt as distinctValues,h as encodeAggregateKey,Oa as encodeCursor,Ko as encodeGeohash,Ha as encodePartitionKey,bl as encodeRowsPatch,P as ensureAuditTable,fa as ensureMailTable,ho as envOptionalPositiveInt,xo as envPositiveInt,Pa as equalityPinnedFields,o as exportShardRows,ra as facetColumn,yt as fanOutScalarCounts,At as findRelated,oa as findStorageReferences,lo as finishStreamRun,vl as float64SqlKey,x as foldAggregateTally,Ze as forgetScheduleOutbox,Yt as gateReplicaDispatch,wr as geoTableName,Rl as globalShapeReadKey,ll as guardWriter,jt as handleReplicaControl,nn as hasTrigger,wo as haversineMeters,a as importShardRows,St as indexKeysForRow,fl as isDevEnvironment,vr as isFtsAvailable,Ga as isLossyBody,He as isMemoryTable,Lt as isRelationPredicate,Mo as isSoftDeleted,yo as isSourceDue,Xr as jsonPath,Hr as jsonPathSql,ut as keysTouchRanges,Ro as liftSourceId,kl as lintReadonlySql,ot as listReactorStates,aa as listTables,Sn as literalInList,ct as markUnvouchableReads,Wa as matchesRankStaticWhere,m as matchesStaticWhere,bo as materializeExternalRows,Lo as materializeExternalRowsIncremental,We as memoryTableNames,Yl as mergeChangedKeys,R as mergeWhere,oe as migrateCdcLog,ae as migrateCdcMeta,Te as migrateClientWatermark,Ie as migrateCommitSeq,no as migrateDurableStreams,Fe as migrateGlobalShapeSnapshot,Ge as migrateIdempotency,at as migrateReactorState,$e as migrateScheduleOutbox,ir as migrateSearchState,ur as migrateShapePokeCursor,te as minCdcReplayableSeq,le as minCdcSeq,fr as minShapePokeCursor,qt as nextPromotionState,p as normalizeCountArgument,U as normalizeIdStructurally,Ma as normalizeOrderKeys,go as normalizeSourceDocument,_o as normalizeSourceValue,Jr as param,er as parkScheduleOutbox,t as parseExportShardArgs,l as parseImportShardArgs,g as planAggregateLookup,vo as pointInBoundingBox,rr as probeScheduleOutbox,Ll as projectColumns,Fo as pullExternalSourceIncrementalTick,No as pullExternalSourceTick,Wr as qualifiedJsonPath,zr as qualifiedJsonPathSql,Cn as quoteIdentifier,za as rankKeyFromDoc,Va as rankPivotConditionSql,Qa as rankTableName,$a as reactiveCacheKey,tt as reactorNeedsRun,T as readAggregateValue,Se as readArchivedCdcChanges,M as readAuditLog,Ra as readBookmark,Ea as readCapturedMail,ue as readCdcArchivedThrough,ne as readCdcChangeKeys,ie as readCdcChanges,se as readCdcCursor,de as readCdcEpoch,Ce as readClientWatermark,be as readCommitSeq,El as readDeployInfo,or as readDueScheduleOutbox,Do as readExternalSourceBaseline,Ne as readGlobalShapeSnapshot,qe as readIdempotent,_r as readMigrationStatus,qa as readQueueMessageById,Ka as readQueueMessages,lt as readReactorState,sl as readSchemaHistory,dl as readSchemaVersion,sr as readSearchBackfillState,Er as readShapePokeCursor,io as readStreamChunks,so as readStreamRun,ta as readTablePage,ha as recordCapturedMail,jl as recordChangedKeys,la as recordFanoutPass,na as recordGlobalPollPass,wa as recordQueueMessages,ar as recordScheduleOutbox,cl as recordSchemaVersion,ia as recordShapeProbePass,Ft as relationHooks,Kt as relayCountFor,Zr as renderSql,el as reprojectableFields,xn as reprojectionMigrationId,rl as reprojectionTables,Ya as resolveRankPartition,Qe as resolveRankSeekTuple,Dt as resolveRelationPredicates,Nt as resolveWith,Vr as rowToDocument,Ir as runDataMigration,yr as runDrizzle,Oo as runExternalSourceTick,Bl as runReadonlySql,kt as runRowValidators,Rn as runShardMigrations,Ml as runSocketPool,Fr as runSql,sn as runTriggers,cn as selectExpiredIds,n as selectExportTables,_ as selectIndexForAggregate,I as selectIndexForCount,b as selectIndexForGroupBy,sa as selectMatchingIds,Cr as selectShapeMembers,Ar as selectShapeRows,pl as serializeSqlValue,wt as shapeRoutingKey,ya as softDeleteScope,ja as sortColumnName,$r as sqliteInList,_n as stableStringify,bn as stableWireKey,Wl as subscriptionFrames,zl as subscriptionListDeltas,da as summarizeFanoutTopics,ca as summarizeSubscriptions,Qr as tableColumns,Pr as tableFromDepKey,S as throwingScheduler,Fa as tiebreakDirectionFor,ce as trimCdcChanges,Ke as trimIdempotent,tr as trimScheduleOutbox,co as trimStreamRuns,Yr as tryRowToDocument,Vl as trySendFrame,eo as unionAll,Na as uniqueIndexFields,i as validateImportRow,fe as writeCdcArchivedThrough,ke as writeGlobalShapeSnapshot,we as writeIdempotent,nt as writeReactorState,dr as writeSearchBackfillState,hr as writeShapePokeCursor,xr as writeShapePokeCursors,Jl as writeTouchesMemo};
@@ -1 +1 @@
1
- import{LunoraError as y}from"@lunora/errors";import{D as st}from"./MAX_TOKEN_LENGTH-BakL9FUy-B3VwYY8C.mjs";import{c as wn,S as pn,l as Le,a as gn}from"./ctx-db-companions-w-CfeOda.mjs";import{sql as i}from"drizzle-orm";import{d as $n}from"./wire-codec-C-FpWm52.mjs";import{throwingScheduler as yn,aggregateSqlFunction as ke,normalizeCountArgument as En}from"./AGGREGATE_SQL_FUNCTION-DDEoMnJR.mjs";import{aggregateTableName as Ve,encodeAggregateKey as ze,readAggregateValue as Je}from"./aggregateTableName-C7o-gpms.mjs";import{mergeWhere as V,CountRlsUnsupportedError as Ye,selectIndexForGroupBy as mn,selectIndexForCount as Sn,selectIndexForAggregate as _n}from"./CountRlsUnsupportedError-BvsDqfO2.mjs";import{backfillSearchIndexesForTable as Rn,searchIndexCoversTable as Tn}from"./backfillAggregateIndexes-BG5-SC1q.mjs";import{backfillAggregateIndexes as Mr,backfillRankIndexes as Dr,backfillSearchIndexes as Lr}from"./backfillAggregateIndexes-BG5-SC1q.mjs";import{appendCdcChange as vn}from"./CDC_LOG_TABLE-vVheEulD.mjs";import{CDC_LOG_TABLE as Fr,applyCdcChanges as qr,bumpCdcEpoch as Br,cdcCanVouchFor as Wr,cdcSeqLeavingRows as Ur,cdcTouchesTables as Pr,cdcTrimmedError as Gr,compactCdcDocs as Hr,cursorBelowRetainedFloor as Or,minCdcReplayableSeq as Nr,minCdcSeq as jr,readCdcChangeKeys as Kr,readCdcChanges as Qr,readCdcCursor as Vr,readCdcEpoch as zr,trimCdcChanges as Jr}from"./CDC_LOG_TABLE-vVheEulD.mjs";import{allocateCommitSeq as An,COMMIT_SEQ_FIELD as In}from"./COMMIT_SEQ_FIELD-BUdOMG5y.mjs";import{isMemoryTable as _t}from"./clearMemoryTables-BGbmag2i.mjs";import{computeRankPage as Rt}from"./computeRankPage-DsQ16o1z.mjs";import{SCAN_DEP as G}from"./SCAN_DEP-D7qE3iUe.mjs";import{runDrizzle as O,runSql as _e}from"./runDrizzle-2ULFQR_k.mjs";import{D as oe,k as ae,r as ue,b as Fe,A as Xe,a as qe,e as Z,o as Cn,t as jt,j as Ue,q as Tt,i as xn,h as Kt,g as bn}from"./do-sql-Dvj8Yl5N.mjs";import{renderSql as Qt,unionAll as ct,WORKERD_SQLITE_LIMITS as Vt,sqliteInList as Mn}from"./param-DlozcSQu.mjs";import{coveringGeohashes as Dn,boundingBoxGeohashes as Ln,haversineMeters as kn,pointInBoundingBox as Fn}from"./GEO_DEFAULT_PRECISION-CqpQZ-J_.mjs";import{NotFoundError as qn}from"./NotFoundError-BhF7FeFr.mjs";import{softDeleteScope as le,normalizeOrderKeys as nt,uniqueIndexFields as zt,equalityPinnedFields as Bn,buildSeekWhere as Jt,decodeCursor as ot,applySelect as vt,encodeCursor as rt,tiebreakDirectionFor as Yt,buildSeekBeforeWhere as Wn}from"./CURSOR_PREFIX-Bn8SFoGd.mjs";import{rankTableName as At,sortColumnName as It,resolveRankPartition as Un,encodePartitionKey as Pn,RANK_TIEBREAK as Gn,rankPivotConditionSql as Hn}from"./RANK_TIEBREAK-BXDiMmkH.mjs";import{UNVOUCHABLE_DEP as Ct}from"./UNVOUCHABLE_DEP-C68htACn.mjs";import{indexKeysForRow as On,buildIndexRange as Nn}from"./buildIndexRange-NtciKq3M.mjs";import{deriveRelationEdges as jn,findRelated as Kn}from"./RELATED_DEFAULT_LIMIT-B9PH28Pn.mjs";import{assertFlatPredicate as Ze,resolveRelationPredicates as xt}from"./DEFAULT_MAX_RELATION_KEYS-XESc7TiB.mjs";import{runRowValidators as et,resolveWith as bt,relationHooks as Mt,applyOnDelete as Qn,fanOutScalarCounts as Vn}from"./applyOnDelete-7JZ4vR9r.mjs";import{guardWriter as zn}from"./RLS_UNWRAP_SYMBOL-BwwTbz3Q.mjs";import{quoteIdentifier as Re}from"./quoteIdentifier-CObIFRhb.mjs";import{m as Jn}from"./sql-projection-BB2lCbYV.mjs";import{createSystemReader as Yn}from"./createSystemReader-DcDLFfC-.mjs";import{ConflictError as me}from"./ConflictError-C8GtJmjS.mjs";import{runTriggers as Xn}from"./hasTrigger-CjlwI4le.mjs";import{c as ne,t as Ge,r as Pe,j as Se,i as Dt}from"./where-sql-x1YKldcq.mjs";import{CLIENT_WATERMARK_TABLE as Xr,advanceClientWatermark as Zr,migrateClientWatermark as ei,readClientWatermark as ti}from"./CLIENT_WATERMARK_TABLE-CRnrAnJ2.mjs";import{GLOBAL_SHAPE_SNAPSHOT_TABLE as oi,deleteGlobalShapeSnapshot as ri,deleteGlobalShapeSnapshotsForConnection as ii,migrateGlobalShapeSnapshot as si,readGlobalShapeSnapshot as ci,writeGlobalShapeSnapshot as ai}from"./GLOBAL_SHAPE_SNAPSHOT_TABLE-DSA6mzyx.mjs";import{IDEMPOTENCY_TABLE as li,readIdempotent as ui,trimIdempotent as fi,writeIdempotent as hi}from"./IDEMPOTENCY_TABLE-DOpm_oMF.mjs";import{runShardMigrations as pi}from"./runShardMigrations-CeT_SVrI.mjs";import{S as $i}from"./ctx-db-search-state-ruTuCsxa.mjs";import{selectShapeMembers as Ei,selectShapeRows as mi}from"./selectShapeMembers-CCZyZggM.mjs";import{serializeSqlValue as re}from"./serializeSqlValue-CjbhIHjJ.mjs";const Zn=o=>{const r=atob(o),t=Uint8Array.from(r,a=>a.codePointAt(0)??0);return new TextDecoder().decode(t)},eo=()=>new y("BAD_REQUEST","invalid cursor"),Lt=16,kt=8,Y=1024,at=(o,r)=>r.query(o),to=(o,r)=>{if(o.length===0)return 0;let t=0;for(const[a,d]of r.entries()){const w=a===r.length-1;let S=0;for(const R of o)(w?R.startsWith(d):R===d)&&(S+=1);if(S===0)return 0;t+=S}return t},no=(o,r)=>{if(!r)return{exact:!0,lower:o,upper:o};const t=[...o].at(-1)??"",a=(t.codePointAt(0)??0)+1;if(a>=55296&&a<=57343||a>1114111)return{exact:!0,lower:o,upper:o};const d=o.slice(0,o.length-t.length);return{exact:!1,lower:o,upper:d+String.fromCodePoint(a)}},oo=(o,r,t)=>{const a={eq:(d,w)=>{if(!o.definition.filterFields?.includes(d))throw new y("INTERNAL",`field "${d}" is not a filter field of search index "${o.indexName}" on table "${r}"`);if(o.filters.length>=kt)throw new y("BAD_REQUEST",`search index "${o.indexName}" on table "${r}": at most ${String(kt)} .eq() filters are supported per search query`);return o.filters.push({field:d,value:w}),a},search:(d,w)=>{const S=o;if(d!==S.definition.field)throw new y("INTERNAL",`search index "${S.indexName}" on table "${r}" indexes "${S.definition.field}", not "${d}"`);const R=at(w,t).length;if(R>Lt)throw new y("BAD_REQUEST",`search index "${S.indexName}" on table "${r}": at most ${String(Lt)} search terms are supported (got ${String(R)})`);return S.field=d,S.query=w,S.hasQuery=!0,a}};return a},ro=o=>{if(o.length>Y)throw new y("BAD_REQUEST",`more than ${String(Y)} documents match this search — narrow it with filters or read it a page at a time with .paginate()`)},io=o=>Math.min(o.offset+o.numItems+1,Y),so=o=>btoa(`search:${String(o)}`),co=o=>{let r;try{r=Zn(o)}catch{return}if(!r.startsWith("search:"))return;const t=Number(r.slice(7));return Number.isInteger(t)&&t>=0?t:void 0},ao=o=>{if(typeof o.endCursor=="string")throw new y("BAD_REQUEST","bounded (endCursor) pagination is not supported on search queries — relevance order has no stable range boundary");if(!Number.isFinite(o.numItems))throw new y("BAD_REQUEST",`search pagination needs a finite numItems, got ${String(o.numItems)}`);const r=Math.max(0,Math.floor(o.numItems)),t=o.cursor?co(o.cursor):0;if(t===void 0)throw eo();if(t+r>=Y)throw new y("BAD_REQUEST",`search pagination reaches the ${String(Y)}-document limit (offset ${String(t)} + ${String(r)} requested) — a page must end below the cap so the probe row that answers \`hasMore\` still fits: retry with numItems ${String(Math.max(1,Y-t-1))} or fewer, or narrow the query or the filters instead`);return{numItems:r,offset:t}},lo=(o,r)=>{const t=r.offset+r.numItems,a=r.numItems>0&&o.length>t;return{continueCursor:a?so(t):null,isDone:!a,page:o.slice(r.offset,t)}},uo=o=>{if(o===void 0)return Y+1;if(!Number.isFinite(o))return Y;const r=Math.max(0,Math.floor(o));if(r>Y)throw new y("BAD_REQUEST",`search returns at most ${String(Y)} documents (asked for ${String(r)}) — narrow the query or paginate instead`);return r},He=o=>{const r=new Map;return t=>{const a=r.get(t);if(a!==void 0)return a;const d=o(Re(t));return r.set(t,d),d}},fe=Re(oe),fo=He(o=>`INSERT INTO ${o} (id, _creationTime, ${fe}) VALUES (?, ?, ?)`),Ft=He(o=>`UPDATE ${o} SET ${fe} = ? WHERE id = ? AND ${fe} = ?`),ho=He(o=>`UPDATE ${o} SET _creationTime = ?, ${fe} = ? WHERE id = ? AND ${fe} = ?`),wo=He(o=>`DELETE FROM ${o} WHERE id = ? AND ${fe} = ?`),po="SELECT changes() AS changed",qt=new Map,go="",$o=o=>{const r=JSON.stringify(o),t=qt.get(r);if(t!==void 0)return t;const a=o.map(w=>i`SELECT ${i.raw(`'${w.replaceAll("'","''")}'`)} AS __t__, id, _creationTime, ${i.identifier(oe)} FROM ${i.identifier(w)} WHERE id = ${go}`),{sql:d}=Qt("sqlite",i`${ct(a)} LIMIT 1`);return qt.set(r,d),d},yo=(o,r)=>r.map(()=>o),Eo=/^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/iu,mo=o=>{if(!Eo.test(o))throw new y("INTERNAL",`invalid clientId ${JSON.stringify(o)}: a client-supplied row id must be a UUID`)},Bt=50,Xt=500,Be=Math.floor(Vt.boundParams/3),ye=Vt.boundParams,So=128,de=(o,r,t)=>{const a=r??Xt;if(o>a)throw new y("BATCH_LIMIT_EXCEEDED",`${t}: batch of ${String(o)} exceeds the limit of ${String(a)} (raise options.limit or chunk the call)`,{status:400})},_o=o=>{const r={eq:(t,a)=>(o.sqlConditions.push({comparator:"=",field:t,value:a}),r),gt:(t,a)=>(o.sqlConditions.push({comparator:">",field:t,value:a}),r),gte:(t,a)=>(o.sqlConditions.push({comparator:">=",field:t,value:a}),r),lt:(t,a)=>(o.sqlConditions.push({comparator:"<",field:t,value:a}),r),lte:(t,a)=>(o.sqlConditions.push({comparator:"<=",field:t,value:a}),r)};return r},Ro=o=>Math.max(o,Y),Zt=(o,r)=>{const t=o.filters.map(a=>i`${Z(a.field)} = ${re(a.value)}`);return r&&t.push(r),t},To=(o,r,t,a,d)=>{const w=at(t.query,st(t.definition.language));if(w.length===0)return[];const S=pn(r,t.indexName),R=`${S}__vocab`,E=w.length-1,k=w.map((q,_)=>{const F=no(q,_===E),j=F.exact?i`${i.identifier("term")} = ${F.lower}`:i`${i.identifier("term")} >= ${F.lower} AND ${i.identifier("term")} < ${F.upper}`;return i`SELECT ${i.identifier("doc")}, ${i.raw(String(_))} AS ${i.identifier("__term__")}, COUNT(*) AS ${i.identifier("__n__")} FROM ${i.identifier(R)} WHERE ${j} GROUP BY ${i.identifier("doc")}`}),$=w.map((q,_)=>i`SUM(CASE WHEN u.${i.identifier("__term__")} = ${i.raw(String(_))} THEN u.${i.identifier("__n__")} ELSE 0 END)`),v=i`SELECT f.${i.identifier(Le)} AS ${i.identifier(Le)}, ${i.join($,i` + `)} AS ${i.identifier("__score__")} FROM (${ct(k)}) u JOIN ${i.identifier(S)} f ON f.rowid = u.${i.identifier("doc")} GROUP BY f.${i.identifier(Le)} HAVING ${i.join($.map(q=>i`${q} > 0`),i` AND `)}`,A=Zt(t,d);let L=i`SELECT m.id, m._creationTime, m.${i.identifier(oe)}, s.${i.identifier("__score__")} AS ${i.identifier("__score__")} FROM (${v}) s JOIN ${i.identifier(r)} m ON m.id = s.${i.identifier(Le)}`;A.length>0&&(L=i`${L} WHERE ${i.join(A,i` AND `)}`),L=i`${L} ORDER BY s.${i.identifier("__score__")} DESC, m._creationTime DESC, m.id ASC LIMIT ${i.raw(String(a))}`;const N=[];for(const q of O(o,L)){const _=Kt(q);if(_){const F=q.__score__;N.push({document:_,score:typeof F=="number"?F:Number(F??0)})}}return N},vo=(o,r,t,a,d)=>{const w=st(t.definition.language),S=at(t.query,w);if(S.length===0)return[];const R=Zt(t,d);let E=i`SELECT id, _creationTime, ${i.identifier(oe)} FROM ${i.identifier(r)}`;R.length>0&&(E=i`${E} WHERE ${i.join(R,i` AND `)}`),E=i`${E} ORDER BY _creationTime DESC, id ASC LIMIT ${i.raw(String(Ro(a)))}`;const k=O(o,E).toArray(),$=[];for(const v of k){const A=Kt(v);if(!A)continue;const L=to(gn(A,t.definition),S);L>0&&$.push({creationTime:typeof A._creationTime=="number"?A._creationTime:0,doc:A,id:typeof A._id=="string"?A._id:"",score:L})}return $.sort((v,A)=>A.score-v.score||A.creationTime-v.creationTime||v.id.localeCompare(A.id)),$.slice(0,a).map(v=>({document:v.doc,score:v.score}))},tt=(o,r,t,a)=>{if(!Number.isFinite(o.lat)||o.lat<-90||o.lat>90||!Number.isFinite(o.lng)||o.lng<-180||o.lng>180)throw new y("BAD_REQUEST",`geo index "${a}" on table "${t}": ${r} must have a finite lat in [-90, 90] and lng in [-180, 180]`)},Ao=(o,r)=>{const t=o,a={near:(d,w)=>{if(t.within)throw new y("INTERNAL",`geo index "${t.indexName}" on table "${r}": call .near() or .within(), not both`);if(tt(d,".near() point",r,t.indexName),!Number.isFinite(w)||w<=0)throw new y("BAD_REQUEST",`geo index "${t.indexName}" on table "${r}": .near() radiusMeters must be a finite number > 0, got ${String(w)}`);return t.near={point:{lat:d.lat,lng:d.lng},radiusMeters:w},a},within:d=>{if(t.near)throw new y("INTERNAL",`geo index "${t.indexName}" on table "${r}": call .near() or .within(), not both`);if(tt(d.sw,".within() sw corner",r,t.indexName),tt(d.ne,".within() ne corner",r,t.indexName),d.sw.lat>d.ne.lat)throw new y("BAD_REQUEST",`geo index "${t.indexName}" on table "${r}": .within() corners are transposed (sw.lat > ne.lat)`);if(d.sw.lng>d.ne.lng)throw new y("BAD_REQUEST",`geo index "${t.indexName}" on table "${r}": .within() box crosses the antimeridian (sw.lng > ne.lng), which is not supported — split it into two boxes at ±180 and union the results`);return t.within={ne:{lat:d.ne.lat,lng:d.ne.lng},sw:{lat:d.sw.lat,lng:d.sw.lng}},a}};return a},Io=(o,r)=>{const t=o[r];if(t===null||typeof t!="object")return;const{lat:a,lng:d}=t;return typeof a=="number"&&typeof d=="number"?{lat:a,lng:d}:void 0},Co=(o,r)=>{const t=Io(o,r.definition.field);if(!t)return;const a=typeof o._creationTime=="number"?o._creationTime:0;if(r.near){const d=kn(r.near.point,t);return d<=r.near.radiusMeters?{creationTime:a,distance:d}:void 0}return Fn(t,r.within)?{creationTime:a,distance:0}:void 0},xo=(o,r,t,a)=>{if(!t.near&&!t.within)throw new y("INTERNAL",`geo index "${t.indexName}" on table "${r}": call .near(point, radius) or .within(box)`);const d=t.near?Dn(t.near.point,t.near.radiusMeters):Ln(t.within),w=bn(r,t.indexName),S=d.map(v=>i`(g.${i.identifier("__geohash__")} >= ${v} AND g.${i.identifier("__geohash__")} < ${`${v}{`})`),R=[i`(${i.join(S,i` OR `)})`];a&&R.push(a);const E=i`SELECT m.id, m._creationTime, m.${i.identifier(oe)} FROM ${i.identifier(w)} g JOIN ${i.identifier(r)} m ON m.id = g.${i.identifier("__id__")} WHERE ${i.join(R,i` AND `)}`,k=O(o,E).toArray(),$=[];for(const v of k){const A=ue(v),L=A?Co(A,t):void 0;A&&L&&$.push({creationTime:L.creationTime,distance:L.distance,doc:A})}return $.sort((v,A)=>v.distance-A.distance||A.creationTime-v.creationTime),$},en=(o,r,t,a)=>{const d=[];for(const w of o)if(r.every(S=>S(a(w)))&&(d.push(w),typeof t=="number"&&d.length>=t))break;return d},bo=(o,r,t,a,d,w=()=>{})=>{const S=t.within!==void 0,R=xo(o,r,t,d).map(E=>({distanceMeters:S?null:E.distance,document:E.doc}));return w(R.length),typeof a=="number"?R.slice(0,Math.max(0,Math.floor(a))):R},tn=(o,r,t,a,d,w=()=>{})=>{const{geo:S}=t;if(!S)throw new y("INTERNAL","runGeoTerminalScored called without a staged geo query");const R=t.inMemoryFilters.length>0,E=bo(o,r,S,R?void 0:d,a,w);return R?en(E,t.inMemoryFilters,d,k=>k.document):E},nn=(o,r,t,a)=>{const d=`SELECT id, _creationTime, ${Re(oe)} FROM ${Re(o)}`,w=`ORDER BY ${t}${a===void 0?"":` LIMIT ${String(a)}`}`;return r===void 0?Pe(`${d} ${w}`):Se(`${d} WHERE `,r,` ${w}`)},Mo=(o,r,t,a,d,w=()=>{})=>tn(o,r,t,a,d,w).map(S=>S.document),Do=(o,r,t,a,d,w,S=()=>{})=>{const R=[];for(const v of t.sqlConditions)R.push(i`${Z(v.field)} ${i.raw(v.comparator)} ${re(v.value)}`);a&&R.push(a);let E=i`SELECT id, _creationTime, ${i.identifier(oe)} FROM ${i.identifier(r)}`;R.length>0&&(E=i`${E} WHERE ${i.join(R,i` AND `)}`),E=i`${E} ORDER BY ${d}`,typeof w=="number"&&t.inMemoryFilters.length===0&&(E=i`${E} LIMIT ${i.raw(String(Math.max(0,Math.floor(w))))}`);const k=O(o,E).toArray();S(k.length);const $=[];for(const v of k){const A=ue(v);if(A&&t.inMemoryFilters.every(L=>L(A))&&($.push(A),typeof w=="number"&&$.length>=w))break}return $},Ee={fieldRef:Z,serialize:re},on=(o,r)=>{const t=r===void 0?void 0:o.shape[r];return t!==void 0&&Jn(t)},Wt=(o,r)=>r.some(t=>on(o,t)),Ut=(o,r,t)=>{if(on(o,r))throw new y("BAD_REQUEST",`${t}: "${r}" may hold an order-preserving key rather than a value SQL can reduce or group — declare an aggregateIndex covering this (by, field, op) so the maintained companion answers it instead (its running total is a REAL, so it stays exact only while the total is inside 2^53)`)},dt={fieldRef:o=>Pe(Ue(o)),serialize:re},Lo=o=>{let r=0;const t=[],a={fieldRef:d=>Pe(Ue(d)),relationExists:d=>{const{childWhere:w,negated:S,parentTable:R,relation:E}=d,k=`__rel_${String(r)}`,$=t.at(-1)??R;r+=1,o(E.table,G);const v=E.kind==="one"?E.field:E.references,A=E.kind==="one"?E.references:E.field,L=Pe(`${Tt(k,A)} = ${Tt($,v)}`);t.push(k);const N=ne(w,a,Ge);t.pop();const q=N===void 0?L:Se(L," AND ",N),_=Se("EXISTS (SELECT 1 FROM ",Dt(E.table)," AS ",Dt(k)," WHERE ",q,")");return S?Se("NOT ",_):_},serialize:re};return a},rn=o=>{const r=o.map(t=>`${Ue(t.field)} ${t.direction==="desc"?"DESC":"ASC"}`);return o.some(t=>t.field==="_id"||t.field==="id")||r.push(`${Ue("id")} ${Yt(o)==="desc"?"DESC":"ASC"}`),r.join(", ")},ko=o=>{const r=o.map(t=>i`${Z(t.field)} ${i.raw(t.direction==="desc"?"DESC":"ASC")}`);return o.some(t=>t.field==="_id"||t.field==="id")||r.push(i`${Z("id")} ${i.raw(Yt(o)==="desc"?"DESC":"ASC")}`),i.join(r,i`, `)},Fo={"<":"lt","<=":"lte","=":"eq",">":"gt",">=":"gte"},sn=o=>new Set(o.sqlConditions.filter(r=>r.comparator==="=").map(r=>r.field)),qo=o=>{const r=sn(o);let t=0;for(;t<o.indexFields.length&&r.has(o.indexFields[t]??"");)t+=1;return o.indexFields.slice(t)},cn=(o,r)=>{const t=o.order,a=qo(o),{shape:d}=r;return a.length>0?nt(a.map(w=>({[w]:t})),d,{pinned:sn(o),uniqueBy:zt(r.indexes,d)}):nt([{_creationTime:t}],d)},Bo=(o,r,t,a)=>{const d=o.sqlConditions.map(w=>({[w.field]:{[Fo[w.comparator]??"eq"]:w.value}}));if(t&&d.push(Jt(r,ot(t))),a&&d.push(Wn(r,ot(a))),d.length!==0)return d.length===1?d[0]:{AND:d}},Wo=(o,r,t)=>{const a=[];for(const d of o){const w=ue(d);if(w&&r.every(S=>S(w))&&(a.push(w),t!==void 0&&a.length>t))break}return a},Uo=(o,r,t,a,d,w,S=()=>{})=>{const R=Math.max(0,Math.floor(d.numItems)),E=cn(a,t),k=typeof d.endCursor=="string",$=ne(Bo(a,E,d.cursor,d.endCursor),dt,Ge),v=w&&$?Se($," AND ",w):w??$,A=a.inMemoryFilters.length>0,L=nn(r,v,rn(E),A||k?void 0:R+1),N=_e(o,L.text,...L.params).toArray();S(N.length);const q=Wo(N,a.inMemoryFilters,A||k?void 0:R);if(k){const H=q.length>=2?q[Math.floor(q.length/2)-1]:void 0;return{continueCursor:d.endCursor??null,isDone:!0,page:q,splitCursor:H?rt(H,E):null}}const _=q.length>R,F=_?q.slice(0,R):q,j=F.at(-1);return{continueCursor:_&&j?rt(j,E):null,isDone:!_,page:F}};class Po extends y{constructor(r="unique() found more than one matching document"){super("NOT_UNIQUE",r,{name:"NotUniqueError"})}}const Go=/\s/u,Ho=String.fromCodePoint(0),Pt=(o,r,t)=>{if(!o.tables[r])throw new y("INTERNAL",`unknown table: ${r}`);return typeof t!="string"||t.length===0||Go.test(t)||t.includes(Ho)?null:t},Oo=(o,r,t,a=()=>{},d=()=>{},w=()=>{})=>{const S=r.tables[t];if(!S)throw new y("INTERNAL",`unknown table: ${t}`);const R=le(S.softDeleteMode,void 0),E=R?ne(R,Ee):void 0,k=R?ne(R,dt,Ge):void 0,$={indexFields:[],indexName:void 0,inMemoryFilters:[],order:"asc",sqlConditions:[]};let v=0;const A=m=>{const{search:C}=$;if(!C)throw new y("INTERNAL","runSearchFetch called without a staged search");Rn(o,t,S);const x=$.inMemoryFilters.length>0,D=uo(x?void 0:m),z=xn(o);if(z&&!Tn(o,t,C.definition))throw new y("SEARCH_INDEX_BUILDING",`search index "${C.indexName}" on table "${t}" is still backfilling and currently covers only part of the table — retry once it finishes, or run the backfillSearch admin operation to complete it now`);const X=z?To(o,t,C,D,E):vo(o,t,C,D,E);return x?(v=X.length,en(X,$.inMemoryFilters,m,ce=>ce.document)):(m===void 0&&ro(X),X)},L=m=>A(m).map(C=>C.document),N=m=>{const C=ao(m);return lo(L(io(C)),C)},q=()=>ko(cn($,S)),_=()=>{if($.search||$.geo||$.indexName===void 0){d(void 0);return}d(Nn(t,$.indexName,$.indexFields,$.sqlConditions,re))},F=m=>{_();let C=0;const x=(()=>{if($.search){const D=L(m);return C=v,D}return $.geo?Mo(o,t,$,E,m,D=>{C=D}):Do(o,t,$,E,q(),m,D=>{C=D})})();return w(Math.max(C,x.length)),x},j=()=>{if(!$.search&&!$.geo)throw new y("INTERNAL",`ctx.db.query("${t}").collectWithScores() requires a staged .withSearchIndex(...) or .withGeoIndex(...)`);_();let m=0;const C=(()=>{if($.search){const x=A(void 0);return m=v,x}return tn(o,t,$,E,void 0,x=>{m=x})})();return w(Math.max(m,C.length)),C},H={async*[Symbol.asyncIterator](){if($.search){yield*F(void 0);return}const m=[...$.inMemoryFilters];let C;$.inMemoryFilters=[];try{for(;;){const x=await H.paginate({cursor:C??null,numItems:So});for(const D of x.page)m.every(z=>z(D))&&(yield D);if(x.isDone||x.continueCursor===null)return;C=x.continueCursor}}finally{$.inMemoryFilters=m}},async collect(){return F(void 0)},async collectWithScores(){return j()},filter(m){return $.inMemoryFilters.push(m),H},async first(){return F($.inMemoryFilters.length>0?void 0:1)[0]??null},order(m){return $.order=m==="desc"?"desc":"asc",H},async paginate(m){let C=0;if(_(),$.search){const D=N(m);return w(D.page.length),D}if($.geo)throw new y("INTERNAL","pagination is not supported on geo queries; use .take(n) or .collect()");const x=Uo(o,t,S,$,m,k,D=>{C=D});return w(Math.max(C,x.page.length)),x},async take(m){return F(m)},async unique(){const m=F($.inMemoryFilters.length>0?void 0:2);if(m.length>1)throw new Po(`unique() on table "${t}" matched ${String(m.length)} documents; expected at most one`);return m[0]??null},withGeoIndex(m,C){const x=(S.geoIndexes??[]).find(z=>z.name===m);if(!x)throw new y("INTERNAL",`unknown geo index "${m}" on table "${t}"`);a(t,m,"geo");const D={definition:x,indexName:m};if($.geo=D,C(Ao(D,t)),!D.near&&!D.within)throw new y("INTERNAL",`geo index "${m}" on table "${t}" requires a .near(point, radius) or .within(box) call`);return H},withIndex(m,C){const x=S.indexes.find(D=>D.name===m);if(!x)throw new y("INTERNAL",`unknown index "${m}" on table "${t}"`);return a(t,m,"index"),$.indexName=m,$.indexFields=x.fields,C&&C(_o($)),H},withSearchIndex(m,C){const x=(S.searchIndexes??[]).find(z=>z.name===m);if(!x)throw new y("INTERNAL",`unknown search index "${m}" on table "${t}"`);a(t,m,"search");const D={definition:x,field:x.field,filters:[],hasQuery:!1,indexName:m,query:""};if($.search=D,C(oo(D,t,st(x.language))),!D.hasQuery)throw new y("INTERNAL",`search index "${m}" on table "${t}" requires a .search(field, query) call`);return H}};return H},Gt=(o,r,t)=>{const a={...r};for(const[d,w]of jt(o)){if(w.serverDefault){a[d]=w.serverDefault({auth:t});continue}a[d]===void 0&&(w.defaultFn?a[d]=w.defaultFn():"defaultValue"in w&&(a[d]=w.defaultValue))}return a},Ht=(o,r,t,a)=>{const d=t;for(const[w,S]of jt(o)){if(S.serverDefault){w in r&&(d[w]=S.serverDefault({auth:a}));continue}S.onUpdateFn&&!(w in r)&&(d[w]=S.onUpdateFn())}},Ot=(o,r)=>{for(const t of Object.keys(r))if(r[t]===void 0)throw new y("INTERNAL",`Cannot ${o} field '${t}' to undefined — use null to clear a nullable field, or omit the key to leave it unchanged.`)},No=/unique constraint failed/i,jo=o=>o instanceof Error&&No.test(o.message),Ko=/string or blob too big/iu,Qo=(o,r)=>{if(!(!(o instanceof Error)||!Ko.test(o.message)))throw new y("PAYLOAD_TOO_LARGE",`document is too large to store in "${r}": a single row cannot exceed the storage engine's per-row ceiling (2 MB on a Durable Object's SQLite). The limit is on the STORED bytes, which are UTF-8, and v.bytes()/v.bigint() columns are stored twice on a shard-local table. Keep the payload in R2 (ctx.storage) and store a reference on the row.`)},it=(o,r,t,a)=>{try{_e(o,t,...a)}catch(d){throw jo(d)?new me(`unique constraint violation on "${r}"`,"unique"):(Qo(d,r),d)}},We=(o,r,t,a)=>{if(it(o,r,t,a),_e(o,po).one().changed===0)throw new me(`optimistic concurrency conflict on "${r}" — the row changed during this mutation; refetch and retry`,"occ")},Nt=(o,r,t,a,d,w,S)=>{const R=[];for(let v=0;v<t.length+1;v+=1){const A=t[v],L=a[v],N=L?.direction==="desc"?"desc":"asc",q=A===void 0||L===void 0?i`${i.identifier(Gn)} < ${S}`:Hn(A,w[v],N,!1);if(q===void 0)continue;const _=[];for(let j=0;j<v;j+=1)_.push(i`${i.identifier(t[j])} IS ${w[j]}`);_.push(q);const[F]=_;R.push(_.length===1&&F!==void 0?F:i`(${i.join(_,i` AND `)})`)}const E=R.length>0?i.join(R,i` OR `):i`1 = 0`,k=O(o,i`SELECT COUNT(*) AS c FROM ${i.identifier(r)} WHERE ${i.identifier("__partition__")} = ${d} AND (${E})`).one(),$=O(o,i`SELECT COUNT(*) AS c FROM ${i.identifier(r)} WHERE ${i.identifier("__partition__")} = ${d}`).one();return{before:k.c,total:$.c}},Cr=o=>{const{sql:r}=o,{schema:t}=o,a=o.broadcast??(()=>{}),d=jn(t);let w;const S=()=>o.inTransaction?.()===!0,R=e=>t.tables[e]?.commitOrderedMode!==!0?{}:((w===void 0||!S())&&(w=An(r)),{[In]:w}),E=(e,...n)=>{const s=t.tables[e]?.indexes;if(!s||s.length===0)return;const f=[];for(const h of n)h&&f.push(...On(s,h,re));return f.length>0?f:void 0},{headroom:k}=o;let $=!1;const v=async e=>{const n=$;$=!0;try{return await e()}finally{$=n}},A=o.onRead??(()=>{}),L=e=>{_t(t.tables[e])&&A(Ct,Ct)},N=o.onReadRange??(e=>{A(e.table,G)}),q=e=>{L(e.table),N(e)},_=(e,n)=>{n!==void 0&&n!==G&&!$&&k?.recordRead(1),L(e),A(e,n)},F=o.onIndexUse??(()=>{}),j=o.onWrite??(()=>{}),H=e=>{$||k?.recordWrite(e)},m=async e=>{H(e.doc),await j(e)},{cache:C}=o,x=o.clock??(()=>Date.now()),D=o.idGenerator??(()=>crypto.randomUUID()),z=o.scheduler??yn,{globalDb:X}=o,ce=o.auth??{identity:null,userId:null},an=o.cdc??!1,Oe=z,dn=Yn({scheduler:typeof Oe.list=="function"&&typeof Oe.get=="function"?Oe:void 0,storage:o.storage}),he=(e,n,s,f)=>{an&&!_t(t.tables[e])&&vn(r,x(),e,n,s,f)},ie=e=>t.tables[e]?.shardMode?.kind==="global",lt=(e,n)=>{if(ie(e)){if(!X)throw new y("INTERNAL",`cross-backend ${n} for global table '${e}' requires a globalDb writer — pass one to createShardCtxDb({ globalDb })`);return X}return W},Ne=e=>lt(e,"cascade"),Q=(e,n)=>{if(ie(e)){if(!X)throw new y("INTERNAL",`${n} on global table '${e}' requires a globalDb writer — pass one to createShardCtxDb({ globalDb })`);return X}},ut=async(e,n,s,f,h)=>{h&&H(s);const u=await e.insert(n,s,f);return a({key:u,op:"insert",row:{...s,_id:u},table:n}),u},je=(e,n)=>lt(e,"relation load").findMany(e,n),ft=(e,n)=>(ie(e)&&_(e,G),je(e,n)),ln=e=>!ie(e.table),ht=o.relationExistsPushDown??"auto",wt=ht!=="never",{maxRelationKeys:pt}=o,Te=(e,n,s)=>xt(e,{fetcher:ft,maxRelationKeys:pt,relationBaseWhere:s,schema:t,tableName:n}),gt=async(e,n,s,f)=>{const h=Q(e,"relation grouped count");if(h)return _(e,G),Vn((B,I)=>h.count(B,I),e,n,s,f);const u=t.tables[e];if(!u)throw new y("INTERNAL",`unknown table: ${e}`);_(e,G);const c=le(u.softDeleteMode,void 0),l={[n]:{in:s}},p=V(V(l,f),c),T=await Te(p,e,void 0),g=ne(T,Ee),M=Z(n);let b=i`SELECT ${M} AS __fk__, COUNT(*) AS count FROM ${i.identifier(e)}`;g&&(b=i`${b} WHERE ${g}`),b=i`${b} GROUP BY ${M}`;const P=O(r,b).toArray();return new Map(P.map(B=>[B.__fk__,B.count]))};let ve=0;const $t=new Set;for(const[e,n]of Object.entries(t.tables))for(const s of Object.values(n.triggerMap??{}))$t.add(`${e} ${s.timing} ${s.op}`);const ee=(e,n,s)=>$t.has(`${e} ${n} ${s}`),te=async(e,n,s)=>{if(ve+=1,ve>Bt)throw ve-=1,new me(`trigger recursion exceeded ${String(Bt)} levels on "${s.table}" — check for a self-triggering write`,"trigger");try{await Xn({ctx:fn,event:s,op:n,schema:t,tableName:s.table,timing:e})}finally{ve-=1}},{ensureBackfilledForTable:we,ensureBackfilledIndex:Ke,ensureRankBackfilled:Qe,ensureRankBackfilledForTable:pe,syncAggregates:Ae,syncCompanionsForInsert:yt,syncGeo:Ie,syncRanks:ge,syncSearch:Ce}=wn({broadcast:a,indexKeysFor:(e,n)=>E(e,n),invalidateCache:(e,n,s)=>C?.invalidate(e,n,E(e,s)),recordCdc:he,schema:t,sql:r}),Et=(e,n,s)=>{const{shardMode:f}=n;if(f?.kind==="shardBy"&&!(f.field!==void 0&&(s.partitionBy??[]).includes(f.field)))throw Object.assign(new Error(`rank index "${s.name}" on "${e}" partitions across shards (shard key "${f.field??"?"}" is not in partitionBy) — a shard-local rank()/rankPage() would be wrong; roll it up through the Query Coordinator instead`),{code:"CROSS_SHARD_RANK_UNSUPPORTED",name:"LunoraError",status:400})},mt=e=>Object.entries(t.tables).filter(([,n])=>n.shardMode?.kind!=="global").map(([n])=>n).filter(n=>e===void 0||n===e),$e=e=>e===void 0||ie(e)?X:void 0,se=(e,n)=>{const s=mt(n);for(let f=0;f<s.length;f+=ye){const h=s.slice(f,f+ye),[u]=_e(r,$o(h),...yo(e,h)).toArray();if(!u)continue;const c=u.__t__,l=ue(u);if(typeof c!="string"||!l)return;const p=u[oe];return{docJson:typeof p=="string"?p:ae(p??{}),row:l,tableName:c}}},un=(e,n)=>{const s=[...new Set(e)],f=new Map;if(s.length===0)return f;const h=mt(n);for(let u=0;u<h.length;u+=ye){const c=h.slice(u,u+ye),l=Math.floor(ye/c.length),p=Mn(i`${i.identifier("id")}`,s,!1,l),T=c.map(g=>i`SELECT ${i.raw(`'${g.replaceAll("'","''")}'`)} AS __t__, id FROM ${i.identifier(g)} WHERE ${p}`);for(const g of O(r,ct(T))){const{id:M,__t__:b}=g;typeof b=="string"&&typeof M=="string"&&f.set(M,b)}}return f},St={assertRankPartitionLocal:Et,ensureRankBackfilled:Qe,onRead:_,rowToDocument:ue,schema:t,sql:r},W={system:dn,async aggregate(e,n){const s=Q(e,"aggregate");if(s)return _(e,G),s.aggregate(e,n);const f=t.tables[e];if(!f)throw new y("INTERNAL",`unknown table: ${e}`);if(ke(n.op),n.op==="count")return W.count(e,{baseWhere:n.baseWhere,relationBaseWhere:n.relationBaseWhere,restrictsCounts:n.restrictsCounts,where:n.where});if(!n.field)throw new y("INTERNAL",`aggregate(${e}, { op: "${n.op}" }): "field" is required for non-count reducers`);_(e,G);const h=le(f.softDeleteMode,void 0),u=V(V(n.baseWhere,n.where),h),c=await Te(u,e,n.relationBaseWhere),l=c!==u;if(f.aggregateIndexes&&!n.baseWhere&&!l&&(!h||Wt(f,[n.field]))){const B=_n(f.aggregateIndexes,n.op,n.field,n.where);if(B){Ke(e,B.index);const I=ze(B.index.by??[],B.key),K=Ve(e,B.index.name),J=O(r,i`SELECT ${Fe} AS value, ${Xe} AS count FROM ${i.identifier(K)} WHERE ${qe} = ${I}`).toArray()[0];return Je(n.op,J)}}Ut(f,n.field,`aggregate(${e}, { op: "${n.op}", field: "${n.field}" })`);const p=ne(c,Ee),T=ke(n.op),g=Z(n.field);let M=i`SELECT ${i.raw(T)}(${g}) AS value FROM ${i.identifier(e)}`;p&&(M=i`${M} WHERE ${p}`);const P=O(r,M).toArray()[0]?.value;return P??null},asId(e,n){const s=Pt(t,e,n);if(s===null)throw new y("BAD_REQUEST",`asId("${e}", …): "${n}" is not a valid id for table "${e}"`,{status:400});return s},async count(e,n){const s=Q(e,"count");if(s)return _(e,G),s.count(e,n);const f=t.tables[e];if(!f)throw new y("INTERNAL",`unknown table: ${e}`);const h=En(n);if(h.restrictsCounts)throw new Ye(e);_(e,G);const u=le(f.softDeleteMode,void 0),c=V(V(h.baseWhere,h.where),u),l=await Te(c,e,h.relationBaseWhere),p=l!==c;if(f.aggregateIndexes&&!h.baseWhere&&!p&&!u){const b=Sn(f.aggregateIndexes,h.where);if(b){Ke(e,b.index);const P=ze(b.index.by??[],b.key),B=Ve(e,b.index.name),I=O(r,i`SELECT ${Fe} AS value FROM ${i.identifier(B)} WHERE ${qe} = ${P}`).toArray();return I[0]===void 0?0:I[0].value??0}}const T=ne(l,Ee);let g=i`SELECT COUNT(*) AS count FROM ${i.identifier(e)}`;return T&&(g=i`${g} WHERE ${T}`),O(r,g).one().count},async delete(e,n,s){const f=se(e,n);if(!f){const g=$e(n);g&&(H(void 0),await g.delete(e,n,s));return}const{docJson:h,row:u,tableName:c}=f,l=t.tables[c],p=s?.hard===!0,T=!p&&l?.softDeleteMode?l.softDeleteMode.field:void 0;if(!(T&&u[T]!==null&&u[T]!==void 0)){if(ee(c,"before","delete")&&await te("before","delete",{id:e,op:"delete",previous:u,table:c}),await Qn({deletedId:e,deletedReference:g=>u[g],findHolders:async(g,M,b)=>(await Ne(g).findMany(g,{includeDeleted:p,where:{[M]:b}})).page,onCascade:(g,M)=>Ne(g).delete(M,void 0,s),onRestrict:g=>{throw new me(g,"restrict")},onSetNull:(g,M,b)=>Ne(g).patch(M,{[b]:null}),schema:t,tableName:c}),we(c),pe(c),T){const g={...u,...R(c),[T]:x(),_id:e};We(r,c,Ft(c),[ae(g),e,h]),Ce(c,e,g,u),Ie(c,e,void 0),Ae(c,u,g),ge(c,e,u,void 0),C?.invalidate(c,e,E(c,u,g)),he(c,e,"update",g),a({indexKeys:E(c,u,g),key:e,op:"update",row:g,table:c}),ee(c,"after","delete")&&await te("after","delete",{id:e,op:"delete",previous:u,table:c}),await m({id:e,op:"delete",table:c});return}We(r,c,wo(c),[e,h]),Ce(c,e,void 0),Ie(c,e,void 0),Ae(c,u,void 0),ge(c,e,u,void 0),C?.invalidate(c,e,E(c,u)),he(c,e,"delete"),a({indexKeys:E(c,u),key:e,op:"delete",table:c}),ee(c,"after","delete")&&await te("after","delete",{id:e,op:"delete",previous:u,table:c}),await m({id:e,op:"delete",table:c})}},async deleteAll(e,n){if(!t.tables[e])throw new y("INTERNAL",`unknown table: ${e}`);const s=Math.max(1,n?.chunkSize??Xt),f=n?.hard===void 0?void 0:{hard:n.hard},h=ie(e)?void 0:e;let u=0;return await v(async()=>{for(;;){const l=(await W.findMany(e,{limit:s})).page.map(p=>String(p._id));if(l.length===0)break;for(const p of l)await W.delete(p,h,f),u+=1;if(l.length<s)break}}),{deleted:u}},async deleteMany(e,n,s){de(e.length,n?.limit,"deleteMany");for(const f of e)await W.delete(f,s);return{deleted:e.length}},async deleteWhere(e,n,s){const u=(await(Q(e,"deleteWhere")??W).findMany(e,{where:n})).page.map(c=>String(c._id));if(de(u.length,s?.limit,"deleteWhere"),W.deleteMany===void 0)throw new y("INTERNAL",`ctx.db.${e}.deleteMany is unavailable: this writer has no batch delete`);return W.deleteMany(u,s)},async findFirst(e,n={}){return(await W.findMany(e,{...n,limit:1,omitContinueCursor:!0})).page[0]??null},async findFirstOrThrow(e,n={}){const s=await W.findFirst(e,n);if(s===null)throw new qn(`findFirstOrThrow: no "${e}" document matched`);return s},async findMany(e,n={}){const s=Q(e,"findMany");if(s)return _(e,G),s.findMany(e,n);const f=t.tables[e];if(!f)throw new y("INTERNAL",`unknown table: ${e}`);const h=!n.where&&!n.baseWhere;h?_(e,G):_(e);const u=nt(n.orderBy,f.shape,{pinned:Bn(n.where),uniqueBy:zt(f.indexes,f.shape)}),c=n.cursor?Jt(u,ot(n.cursor)):void 0;let l=V(n.baseWhere,n.where);l=V(l,le(f.softDeleteMode,n.includeDeleted)),l=await xt(l,{canPushExists:wt?ln:void 0,existsPushMode:ht==="always"?"always":"auto",fetcher:ft,maxRelationKeys:pt,relationBaseWhere:n.relationBaseWhere,schema:t,tableName:e}),c&&(l=l?{AND:[l,c]}:c);const p=wt?Lo(_):dt,T=ne(l,p,Ge),g=typeof n.limit=="number"?Math.max(0,Math.floor(n.limit)):void 0,M=nn(e,T,rn(u),g===void 0?void 0:g+1),b=_e(r,M.text,...M.params).toArray();h&&!$&&k?.recordRead(b.length);const P=[];for(const J of b){const U=ue(J);U&&(P.push(U),!h&&typeof U._id=="string"&&_(e,U._id))}if(g===void 0)return n.with&&await bt({groupedCounter:gt,fetcher:je,parents:P,...Mt(n),schema:t,tableName:e,with:n.with}),{continueCursor:null,isDone:!0,page:vt(P,n.select,n.with)};const B=P.length>g,I=B?P.slice(0,g):P,K=I.at(-1);return n.with&&await bt({fetcher:je,groupedCounter:gt,parents:I,...Mt(n),schema:t,tableName:e,with:n.with}),{continueCursor:B&&K&&n.omitContinueCursor!==!0?rt(K,u):null,isDone:!B,page:vt(I,n.select,n.with)}},async get(e,n){const s=se(e,n);if(!s){const f=$e(n);return f?f.get(e,n):null}return _(s.tableName,e),s.row},async lookupById(e,n){const s=se(e,n);return s?(_(s.tableName,e),{row:s.row,tableName:s.tableName}):null},async groupBy(e,n){const s=Q(e,"groupBy");if(s)return _(e,G),s.groupBy(e,n);const f=t.tables[e];if(!f)throw new y("INTERNAL",`unknown table: ${e}`);_(e,G);const h=n.agg??{op:"count"};if(ke(h.op),h.op!=="count"&&!h.field)throw new y("INTERNAL",`groupBy(${e}, { agg: { op: "${h.op}" } }): "field" is required for non-count reducers`);const u=le(f.softDeleteMode,void 0),c=V(V(n.baseWhere,n.where),u),l=await Te(c,e,n.relationBaseWhere),p=l!==c,T=[...n.by,h.field];if(f.aggregateIndexes&&!n.baseWhere&&!p&&(!u||Wt(f,T))){const I=mn(f.aggregateIndexes,h.op,h.field,n.by,n.where),K=I===void 0?0:Object.keys(I.partial).length,J=I?.index.by?.length??0;if(I&&(K===0||K===J)){Ke(e,I.index);const U=Ve(e,I.index.name),xe=Object.keys(I.partial),be=[];if(xe.length===(I.index.by??[]).length&&xe.length>0){const Me=ze(I.index.by??[],I.partial),De=O(r,i`SELECT ${Fe} AS value, ${Xe} AS count FROM ${i.identifier(U)} WHERE ${qe} = ${Me}`).toArray();return De.length>0&&be.push({key:{...I.partial},value:Je(h.op,De[0])}),be}const hn=O(r,i`SELECT ${qe} AS key, ${Fe} AS value, ${Xe} AS count FROM ${i.identifier(U)}`).toArray();for(const Me of hn){const De=$n(JSON.parse(Me.key));be.push({key:De,value:Je(h.op,Me)})}return be}}for(const I of T){if(I===void 0)continue;const K=I===h.field?`groupBy(${e}, { agg: { op: "${h.op}", field: "${I}" } })`:`groupBy(${e}, { by: [..."${I}"] })`;Ut(f,I,K)}const g=ne(l,Ee),M=n.by.map(I=>i`${Z(I)} AS ${i.identifier(I)}`);if(h.op==="count")M.push(i`COUNT(*) AS value`);else{const{field:I}=h;if(I===void 0)throw new y("INTERNAL",`groupBy(${e}, { agg: { op: "${h.op}" } }): "field" is required for non-count reducers`);M.push(i`${i.raw(ke(h.op))}(${Z(I)}) AS value`)}let b=i`SELECT ${i.join(M,i`, `)} FROM ${i.identifier(e)}`;g&&(b=i`${b} WHERE ${g}`),b=i`${b} GROUP BY ${i.join(n.by.map(I=>Z(I)),i`, `)}`;const P=O(r,b).toArray(),B=[];for(const I of P){const K={};for(const U of n.by)K[U]=Cn(f.shape[U],I[U]??null);const{value:J}=I;B.push({key:K,value:J==null?null:Number(J)})}return B},async insert(e,n,s){const f=Q(e,"insert");if(f)return ut(f,e,n,s,!0);const h=t.tables[e];if(!h)throw new y("INTERNAL",`unknown table: ${e}`);const u=Gt(h,n,ce);et(h,u);let c;s?.clientId!==void 0?(mo(s.clientId),c=s.clientId):s?.allowExplicitId&&typeof u._id=="string"?c=u._id:c=D();const l=s?.allowExplicitId&&typeof u._creationTime=="number"?u._creationTime:x(),p={...u,...R(e),_creationTime:l,_id:c};return ee(e,"before","insert")&&await te("before","insert",{doc:{...p},id:c,op:"insert",table:e}),we(e),pe(e),it(r,e,fo(e),[c,l,ae(p)]),yt(e,c,p),ee(e,"after","insert")&&await te("after","insert",{doc:p,id:c,op:"insert",table:e}),await m({doc:p,id:c,op:"insert",table:e}),c},async insertManyUnsafe(e,n,s){if(de(n.length,s?.limit,"insertManyUnsafe"),n.length===0)return[];const f=Q(e,"insert");if(f){const l=[];for(const p of n)H(p);for(const p of n){const T=await f.insert(e,p,{allowExplicitId:s?.allowExplicitId});a({key:T,op:"insert",row:{...p,_id:T},table:e}),l.push(T)}return l}const h=t.tables[e];if(!h)throw new y("INTERNAL",`unknown table: ${e}`);we(e),pe(e);const u=[];for(let l=0;l<n.length;l+=Be)u.push(R(e));const c=n.map((l,p)=>{const T=Gt(h,l,ce),g=s?.allowExplicitId===!0&&typeof T._id=="string"?T._id:D(),M=s?.allowExplicitId===!0&&typeof T._creationTime=="number"?T._creationTime:x(),b={...T,...u[Math.floor(p/Be)],_creationTime:M,_id:g};return{creationTime:M,document:b,id:g}});for(const l of c)H(l.document);for(let l=0;l<c.length;l+=Be){const p=i.join(c.slice(l,l+Be).map(g=>i`(${g.id}, ${g.creationTime}, ${ae(g.document)})`),i`, `),T=Qt("sqlite",i`INSERT INTO ${i.identifier(e)} (id, _creationTime, ${i.identifier(oe)}) VALUES ${p}`);it(r,e,T.sql,T.params)}for(const{document:l,id:p}of c)yt(e,p,l),await j({doc:l,id:p,op:"insert",table:e});return c.map(l=>l.id)},async insertMany(e,n,s){de(n.length,s?.limit,"insertMany");const f=s?.skipDuplicates===!0,h=[],u=Q(e,"insert");if(u)for(const l of n)H(l);const c=async l=>u?ut(u,e,l,void 0,!1):W.insert(e,l);for(const l of n)try{h.push(await c(l))}catch(p){if(f&&p instanceof me&&p.kind==="unique")h.push(null);else throw p}return h},normalizeId(e,n){return Pt(t,e,n)},async patch(e,n,s){const f=se(e,s);if(!f){const T=$e(s);if(T){H(n),await T.patch(e,n,s);return}throw new y("NOT_FOUND",`document not found: ${e}`)}const{docJson:h,row:u,tableName:c}=f,l=t.tables[c];if(!l)throw new y("INTERNAL",`unknown table: ${c}`);_(c,e),Ot("patch",n);const p={...u,...n,...R(c),_id:e};Ht(l,n,p,ce),et(l,p,!0),ee(c,"before","update")&&await te("before","update",{doc:{...p},id:e,op:"update",previous:u,table:c}),we(c),pe(c),We(r,c,Ft(c),[ae(p),e,h]),Ce(c,e,p,u),Ie(c,e,p),Ae(c,u,p),ge(c,e,u,p),C?.invalidate(c,e,E(c,u,p)),he(c,e,"update",p),a({indexKeys:E(c,u,p),key:e,op:"update",row:p,table:c}),ee(c,"after","update")&&await te("after","update",{doc:p,id:e,op:"update",previous:u,table:c}),await m({doc:p,id:e,op:"update",table:c})},async patchMany(e,n,s){de(e.length,n?.limit,"patchMany");for(const f of e)await W.patch(f.id,f.patch,s);return{patched:e.length}},async patchWhere(e,n,s){const u=(await(Q(e,"patchWhere")??W).findMany(e,{where:n.where})).page.map(c=>({id:String(c._id),patch:n.patch}));if(de(u.length,s?.limit,"patchWhere"),W.patchMany===void 0)throw new y("INTERNAL",`ctx.db.${e}.patchMany is unavailable: this writer has no batch patch`);return await W.patchMany(u,s),{patched:u.length}},async related(e,n){return Kn(W,d,e,n)},relationEdges:d,query(e){const n=Q(e,"query");return n?(_(e,G),n.query(e)):Oo(r,t,e,F,s=>{s?q(s):_(e,G)},s=>{$||k?.recordRead(s)})},async rank(e,n,s){const f=Q(e,"rank");if(f)return _(e,G),f.rank(e,n,s);F(e,n,"rank");const h=t.tables[e];if(!h)throw new y("INTERNAL",`unknown table: ${e}`);const u=h.rankIndexes?.find(U=>U.name===n);if(!u)throw new y("INTERNAL",`unknown rankIndex "${n}" on table "${e}"`);if(Et(e,h,u),s.restrictsCounts)throw new Ye(e);_(e,G),Qe(e,u);const c=typeof s.row=="string"?s.row:s.row._id;if(!c)return null;const l=At(e,u.name),p=u.sortBy.map((U,xe)=>It(xe)),T=p.map(U=>Re(U)).join(", "),g=O(r,i`SELECT ${i.identifier("__partition__")}, ${i.raw(T)} FROM ${i.identifier(l)} WHERE ${i.identifier("__id__")} = ${c}`).toArray(),[M]=g;if(M===void 0)return null;let b=M.__partition__;const P=V(s.baseWhere,s.where);Ze(P,t,e,"rank");const B=Un(u,P);if(B){const U=Pn(u.partitionBy??[],B);if(U!==b)return null;b=U}const I=p.map(U=>M[U]),{before:K,total:J}=Nt(r,l,p,u.sortBy,b,I,c);return{position:K+1,total:J}},async rankBefore(e,n,s){if(ie(e))throw new y("INTERNAL",`rankBefore is not supported on the global (.global()) table '${e}' — cross-shard rank cursors apply only to sharded tables`);const f=t.tables[e];if(!f)throw new y("INTERNAL",`unknown table: ${e}`);const h=f.rankIndexes?.find(p=>p.name===n);if(!h)throw new y("INTERNAL",`unknown rankIndex "${n}" on table "${e}"`);if(s.restrictsCounts)throw new Ye(e);_(e,G),Qe(e,h);const u=At(e,h.name),c=h.sortBy.map((p,T)=>It(T)),l=h.sortBy.map((p,T)=>re(s.sortValues[T]??null));return Nt(r,u,c,h.sortBy,s.partitionKey,l,s.rowId)},async rankPage(e,n,s={}){Ze(V(s.baseWhere,s.where),t,e,"rankPage");const f=Q(e,"rankPage");if(f)return _(e,G),f.rankPage(e,n,s);F(e,n,"rank");const{continueCursor:h,hasMore:u,rows:c}=Rt(St,e,n,s);return{continueCursor:h,isDone:!u,page:c.map(l=>l.doc)}},async rankPageRows(e,n,s={}){Ze(V(s.baseWhere,s.where),t,e,"rankPage"),F(e,n,"rank");const{directions:f,hasMore:h,rows:u}=Rt(St,e,n,s);return{directions:f,hasMore:h,rows:u}},async restore(e,n){const s=se(e,n);if(!s){const u=$e(n);if(u?.restore){await u.restore(e,n);return}throw new y("NOT_FOUND",`document not found: ${e}`)}const f=t.tables[s.tableName]?.softDeleteMode?.field;if(!f)throw new y("INTERNAL",`ctx.db.restore: table "${s.tableName}" is not a .softDelete() table`);const h=s.row[f]!==null&&s.row[f]!==void 0;await W.patch(e,{[f]:null},n),h&&ge(s.tableName,e,void 0,s.row)},async replace(e,n,s,f){const h=se(e,s);if(!h){const M=$e(s);if(M){H(n),await M.replace(e,n,s,f);return}throw new y("NOT_FOUND",`document not found: ${e}`)}const{docJson:u,row:c,tableName:l}=h,p=t.tables[l];if(!p)throw new y("INTERNAL",`unknown table: ${l}`);Ot("replace",n);const T=f?.allowExplicitId&&typeof n._creationTime=="number"?n._creationTime:x(),g={...n,...R(l),_creationTime:T,_id:e};Ht(p,n,g,ce),et(p,g),ee(l,"before","update")&&await te("before","update",{doc:{...g},id:e,op:"update",previous:c,table:l}),we(l),pe(l),We(r,l,ho(l),[T,ae(g),e,u]),Ce(l,e,g,c),Ie(l,e,g),Ae(l,c,g),ge(l,e,c,g),C?.invalidate(l,e,E(l,c,g)),he(l,e,"update",g),a({indexKeys:E(l,c,g),key:e,op:"update",row:g,table:l}),ee(l,"after","update")&&await te("after","update",{doc:g,id:e,op:"update",previous:c,table:l}),await m({doc:g,id:e,op:"update",table:l})},async wipeShard(e){const n=new Set(e?.exclude),s=e?.tables,f=Object.entries(t.tables).filter(([l,p])=>n.has(l)||s!==void 0&&!s.includes(l)?!1:p.shardMode?.kind!=="global").map(([l])=>l);if(s!==void 0){for(const l of s)if(!t.tables[l])throw new y("INTERNAL",`wipeShard: unknown table: ${l}`)}const h={};let u=0;const{deleteAll:c}=W;if(c===void 0)throw new y("INTERNAL","wipeShard: this writer has no deleteAll");for(const l of f){const p=await c(l,{...e?.chunkSize===void 0?{}:{chunkSize:e.chunkSize},hard:!0});h[l]=p.deleted,u+=p.deleted}return{deleted:u,tables:h}}},fn={db:W,scheduler:z};return o.enforceRls===!0?zn(W,t,(e,n)=>se(e,n)?.tableName,(e,n)=>un(e,n),d):W};export{Fr as CDC_LOG_TABLE,Xr as CLIENT_WATERMARK_TABLE,oi as GLOBAL_SHAPE_SNAPSHOT_TABLE,li as IDEMPOTENCY_TABLE,Po as NotUniqueError,$i as SEARCH_STATE_TABLE,Zr as advanceClientWatermark,qr as applyCdcChanges,Ot as assertNoExplicitUndefined,mo as assertValidClientId,Mr as backfillAggregateIndexes,Dr as backfillRankIndexes,Lr as backfillSearchIndexes,Br as bumpCdcEpoch,Wr as cdcCanVouchFor,Ur as cdcSeqLeavingRows,Pr as cdcTouchesTables,Gr as cdcTrimmedError,Hr as compactCdcDocs,Cr as createShardCtxDb,Or as cursorBelowRetainedFloor,ri as deleteGlobalShapeSnapshot,ii as deleteGlobalShapeSnapshotsForConnection,ei as migrateClientWatermark,si as migrateGlobalShapeSnapshot,Nr as minCdcReplayableSeq,jr as minCdcSeq,Pt as normalizeIdStructurally,Kr as readCdcChangeKeys,Qr as readCdcChanges,Vr as readCdcCursor,zr as readCdcEpoch,ti as readClientWatermark,ci as readGlobalShapeSnapshot,ui as readIdempotent,pi as runShardMigrations,Ei as selectShapeMembers,mi as selectShapeRows,Jr as trimCdcChanges,fi as trimIdempotent,ai as writeGlobalShapeSnapshot,hi as writeIdempotent};
1
+ import{LunoraError as y}from"@lunora/errors";import{D as st}from"./MAX_TOKEN_LENGTH-BakL9FUy-B3VwYY8C.mjs";import{c as wn,S as pn,l as Le,a as gn}from"./ctx-db-companions-w-CfeOda.mjs";import{sql as i}from"drizzle-orm";import{d as $n}from"./wire-codec-C-FpWm52.mjs";import{throwingScheduler as yn,aggregateSqlFunction as ke,normalizeCountArgument as En}from"./AGGREGATE_SQL_FUNCTION-DDEoMnJR.mjs";import{aggregateTableName as Ve,encodeAggregateKey as ze,readAggregateValue as Je}from"./aggregateTableName-C7o-gpms.mjs";import{mergeWhere as V,CountRlsUnsupportedError as Ye,selectIndexForGroupBy as mn,selectIndexForCount as Sn,selectIndexForAggregate as _n}from"./CountRlsUnsupportedError-BvsDqfO2.mjs";import{backfillSearchIndexesForTable as Rn,searchIndexCoversTable as Tn}from"./backfillAggregateIndexes-BG5-SC1q.mjs";import{backfillAggregateIndexes as Mr,backfillRankIndexes as Dr,backfillSearchIndexes as Lr}from"./backfillAggregateIndexes-BG5-SC1q.mjs";import{appendCdcChange as vn}from"./CDC_LOG_TABLE-vVheEulD.mjs";import{CDC_LOG_TABLE as Fr,applyCdcChanges as qr,bumpCdcEpoch as Br,cdcCanVouchFor as Wr,cdcSeqLeavingRows as Ur,cdcTouchesTables as Pr,cdcTrimmedError as Gr,compactCdcDocs as Hr,cursorBelowRetainedFloor as Or,minCdcReplayableSeq as Nr,minCdcSeq as jr,readCdcChangeKeys as Kr,readCdcChanges as Qr,readCdcCursor as Vr,readCdcEpoch as zr,trimCdcChanges as Jr}from"./CDC_LOG_TABLE-vVheEulD.mjs";import{allocateCommitSeq as An,COMMIT_SEQ_FIELD as In}from"./COMMIT_SEQ_FIELD-BUdOMG5y.mjs";import{isMemoryTable as _t}from"./clearMemoryTables-BGbmag2i.mjs";import{computeRankPage as Rt}from"./computeRankPage-DsQ16o1z.mjs";import{SCAN_DEP as G}from"./SCAN_DEP-D7qE3iUe.mjs";import{runDrizzle as O,runSql as _e}from"./runDrizzle-2ULFQR_k.mjs";import{D as oe,k as ae,r as ue,b as Fe,A as Xe,a as qe,e as Z,o as Cn,t as jt,j as Ue,q as Tt,i as xn,h as Kt,g as bn}from"./do-sql-Dvj8Yl5N.mjs";import{renderSql as Qt,unionAll as ct,WORKERD_SQLITE_LIMITS as Vt,sqliteInList as Mn}from"./param-DlozcSQu.mjs";import{coveringGeohashes as Dn,boundingBoxGeohashes as Ln,haversineMeters as kn,pointInBoundingBox as Fn}from"./GEO_DEFAULT_PRECISION-CqpQZ-J_.mjs";import{NotFoundError as qn}from"./NotFoundError-BhF7FeFr.mjs";import{softDeleteScope as le,normalizeOrderKeys as nt,uniqueIndexFields as zt,equalityPinnedFields as Bn,buildSeekWhere as Jt,decodeCursor as ot,applySelect as vt,encodeCursor as rt,tiebreakDirectionFor as Yt,buildSeekBeforeWhere as Wn}from"./CURSOR_PREFIX-Bn8SFoGd.mjs";import{rankTableName as At,sortColumnName as It,resolveRankPartition as Un,encodePartitionKey as Pn,RANK_TIEBREAK as Gn,rankPivotConditionSql as Hn}from"./RANK_TIEBREAK-BXDiMmkH.mjs";import{UNVOUCHABLE_DEP as Ct}from"./UNVOUCHABLE_DEP-C68htACn.mjs";import{indexKeysForRow as On,buildIndexRange as Nn}from"./buildIndexRange-NtciKq3M.mjs";import{deriveRelationEdges as jn,findRelated as Kn}from"./RELATED_DEFAULT_LIMIT-B9PH28Pn.mjs";import{assertFlatPredicate as Ze,resolveRelationPredicates as xt}from"./DEFAULT_MAX_RELATION_KEYS-XESc7TiB.mjs";import{runRowValidators as et,resolveWith as bt,relationHooks as Mt,applyOnDelete as Qn,fanOutScalarCounts as Vn}from"./applyOnDelete-7JZ4vR9r.mjs";import{guardWriter as zn}from"./RLS_UNWRAP_SYMBOL-BwwTbz3Q.mjs";import{quoteIdentifier as Re}from"./quoteIdentifier-CObIFRhb.mjs";import{m as Jn}from"./sql-projection-BB2lCbYV.mjs";import{createSystemReader as Yn}from"./createSystemReader-DcDLFfC-.mjs";import{ConflictError as me}from"./ConflictError-C8GtJmjS.mjs";import{runTriggers as Xn}from"./hasTrigger-CjlwI4le.mjs";import{c as ne,t as Ge,r as Pe,j as Se,i as Dt}from"./where-sql-x1YKldcq.mjs";import{CLIENT_WATERMARK_TABLE as Xr,advanceClientWatermark as Zr,migrateClientWatermark as ei,readClientWatermark as ti}from"./CLIENT_WATERMARK_TABLE-CRnrAnJ2.mjs";import{GLOBAL_SHAPE_SNAPSHOT_TABLE as oi,deleteGlobalShapeSnapshot as ri,deleteGlobalShapeSnapshotsForConnection as ii,migrateGlobalShapeSnapshot as si,readGlobalShapeSnapshot as ci,writeGlobalShapeSnapshot as ai}from"./GLOBAL_SHAPE_SNAPSHOT_TABLE-DSA6mzyx.mjs";import{IDEMPOTENCY_TABLE as li,readIdempotent as ui,trimIdempotent as fi,writeIdempotent as hi}from"./IDEMPOTENCY_TABLE-DOpm_oMF.mjs";import{runShardMigrations as pi}from"./runShardMigrations-DNFOFJe-.mjs";import{S as $i}from"./ctx-db-search-state-ruTuCsxa.mjs";import{selectShapeMembers as Ei,selectShapeRows as mi}from"./selectShapeMembers-CCZyZggM.mjs";import{serializeSqlValue as re}from"./serializeSqlValue-CjbhIHjJ.mjs";const Zn=o=>{const r=atob(o),t=Uint8Array.from(r,a=>a.codePointAt(0)??0);return new TextDecoder().decode(t)},eo=()=>new y("BAD_REQUEST","invalid cursor"),Lt=16,kt=8,Y=1024,at=(o,r)=>r.query(o),to=(o,r)=>{if(o.length===0)return 0;let t=0;for(const[a,d]of r.entries()){const w=a===r.length-1;let S=0;for(const R of o)(w?R.startsWith(d):R===d)&&(S+=1);if(S===0)return 0;t+=S}return t},no=(o,r)=>{if(!r)return{exact:!0,lower:o,upper:o};const t=[...o].at(-1)??"",a=(t.codePointAt(0)??0)+1;if(a>=55296&&a<=57343||a>1114111)return{exact:!0,lower:o,upper:o};const d=o.slice(0,o.length-t.length);return{exact:!1,lower:o,upper:d+String.fromCodePoint(a)}},oo=(o,r,t)=>{const a={eq:(d,w)=>{if(!o.definition.filterFields?.includes(d))throw new y("INTERNAL",`field "${d}" is not a filter field of search index "${o.indexName}" on table "${r}"`);if(o.filters.length>=kt)throw new y("BAD_REQUEST",`search index "${o.indexName}" on table "${r}": at most ${String(kt)} .eq() filters are supported per search query`);return o.filters.push({field:d,value:w}),a},search:(d,w)=>{const S=o;if(d!==S.definition.field)throw new y("INTERNAL",`search index "${S.indexName}" on table "${r}" indexes "${S.definition.field}", not "${d}"`);const R=at(w,t).length;if(R>Lt)throw new y("BAD_REQUEST",`search index "${S.indexName}" on table "${r}": at most ${String(Lt)} search terms are supported (got ${String(R)})`);return S.field=d,S.query=w,S.hasQuery=!0,a}};return a},ro=o=>{if(o.length>Y)throw new y("BAD_REQUEST",`more than ${String(Y)} documents match this search — narrow it with filters or read it a page at a time with .paginate()`)},io=o=>Math.min(o.offset+o.numItems+1,Y),so=o=>btoa(`search:${String(o)}`),co=o=>{let r;try{r=Zn(o)}catch{return}if(!r.startsWith("search:"))return;const t=Number(r.slice(7));return Number.isInteger(t)&&t>=0?t:void 0},ao=o=>{if(typeof o.endCursor=="string")throw new y("BAD_REQUEST","bounded (endCursor) pagination is not supported on search queries — relevance order has no stable range boundary");if(!Number.isFinite(o.numItems))throw new y("BAD_REQUEST",`search pagination needs a finite numItems, got ${String(o.numItems)}`);const r=Math.max(0,Math.floor(o.numItems)),t=o.cursor?co(o.cursor):0;if(t===void 0)throw eo();if(t+r>=Y)throw new y("BAD_REQUEST",`search pagination reaches the ${String(Y)}-document limit (offset ${String(t)} + ${String(r)} requested) — a page must end below the cap so the probe row that answers \`hasMore\` still fits: retry with numItems ${String(Math.max(1,Y-t-1))} or fewer, or narrow the query or the filters instead`);return{numItems:r,offset:t}},lo=(o,r)=>{const t=r.offset+r.numItems,a=r.numItems>0&&o.length>t;return{continueCursor:a?so(t):null,isDone:!a,page:o.slice(r.offset,t)}},uo=o=>{if(o===void 0)return Y+1;if(!Number.isFinite(o))return Y;const r=Math.max(0,Math.floor(o));if(r>Y)throw new y("BAD_REQUEST",`search returns at most ${String(Y)} documents (asked for ${String(r)}) — narrow the query or paginate instead`);return r},He=o=>{const r=new Map;return t=>{const a=r.get(t);if(a!==void 0)return a;const d=o(Re(t));return r.set(t,d),d}},fe=Re(oe),fo=He(o=>`INSERT INTO ${o} (id, _creationTime, ${fe}) VALUES (?, ?, ?)`),Ft=He(o=>`UPDATE ${o} SET ${fe} = ? WHERE id = ? AND ${fe} = ?`),ho=He(o=>`UPDATE ${o} SET _creationTime = ?, ${fe} = ? WHERE id = ? AND ${fe} = ?`),wo=He(o=>`DELETE FROM ${o} WHERE id = ? AND ${fe} = ?`),po="SELECT changes() AS changed",qt=new Map,go="",$o=o=>{const r=JSON.stringify(o),t=qt.get(r);if(t!==void 0)return t;const a=o.map(w=>i`SELECT ${i.raw(`'${w.replaceAll("'","''")}'`)} AS __t__, id, _creationTime, ${i.identifier(oe)} FROM ${i.identifier(w)} WHERE id = ${go}`),{sql:d}=Qt("sqlite",i`${ct(a)} LIMIT 1`);return qt.set(r,d),d},yo=(o,r)=>r.map(()=>o),Eo=/^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/iu,mo=o=>{if(!Eo.test(o))throw new y("INTERNAL",`invalid clientId ${JSON.stringify(o)}: a client-supplied row id must be a UUID`)},Bt=50,Xt=500,Be=Math.floor(Vt.boundParams/3),ye=Vt.boundParams,So=128,de=(o,r,t)=>{const a=r??Xt;if(o>a)throw new y("BATCH_LIMIT_EXCEEDED",`${t}: batch of ${String(o)} exceeds the limit of ${String(a)} (raise options.limit or chunk the call)`,{status:400})},_o=o=>{const r={eq:(t,a)=>(o.sqlConditions.push({comparator:"=",field:t,value:a}),r),gt:(t,a)=>(o.sqlConditions.push({comparator:">",field:t,value:a}),r),gte:(t,a)=>(o.sqlConditions.push({comparator:">=",field:t,value:a}),r),lt:(t,a)=>(o.sqlConditions.push({comparator:"<",field:t,value:a}),r),lte:(t,a)=>(o.sqlConditions.push({comparator:"<=",field:t,value:a}),r)};return r},Ro=o=>Math.max(o,Y),Zt=(o,r)=>{const t=o.filters.map(a=>i`${Z(a.field)} = ${re(a.value)}`);return r&&t.push(r),t},To=(o,r,t,a,d)=>{const w=at(t.query,st(t.definition.language));if(w.length===0)return[];const S=pn(r,t.indexName),R=`${S}__vocab`,E=w.length-1,k=w.map((q,_)=>{const F=no(q,_===E),j=F.exact?i`${i.identifier("term")} = ${F.lower}`:i`${i.identifier("term")} >= ${F.lower} AND ${i.identifier("term")} < ${F.upper}`;return i`SELECT ${i.identifier("doc")}, ${i.raw(String(_))} AS ${i.identifier("__term__")}, COUNT(*) AS ${i.identifier("__n__")} FROM ${i.identifier(R)} WHERE ${j} GROUP BY ${i.identifier("doc")}`}),$=w.map((q,_)=>i`SUM(CASE WHEN u.${i.identifier("__term__")} = ${i.raw(String(_))} THEN u.${i.identifier("__n__")} ELSE 0 END)`),v=i`SELECT f.${i.identifier(Le)} AS ${i.identifier(Le)}, ${i.join($,i` + `)} AS ${i.identifier("__score__")} FROM (${ct(k)}) u JOIN ${i.identifier(S)} f ON f.rowid = u.${i.identifier("doc")} GROUP BY f.${i.identifier(Le)} HAVING ${i.join($.map(q=>i`${q} > 0`),i` AND `)}`,A=Zt(t,d);let L=i`SELECT m.id, m._creationTime, m.${i.identifier(oe)}, s.${i.identifier("__score__")} AS ${i.identifier("__score__")} FROM (${v}) s JOIN ${i.identifier(r)} m ON m.id = s.${i.identifier(Le)}`;A.length>0&&(L=i`${L} WHERE ${i.join(A,i` AND `)}`),L=i`${L} ORDER BY s.${i.identifier("__score__")} DESC, m._creationTime DESC, m.id ASC LIMIT ${i.raw(String(a))}`;const N=[];for(const q of O(o,L)){const _=Kt(q);if(_){const F=q.__score__;N.push({document:_,score:typeof F=="number"?F:Number(F??0)})}}return N},vo=(o,r,t,a,d)=>{const w=st(t.definition.language),S=at(t.query,w);if(S.length===0)return[];const R=Zt(t,d);let E=i`SELECT id, _creationTime, ${i.identifier(oe)} FROM ${i.identifier(r)}`;R.length>0&&(E=i`${E} WHERE ${i.join(R,i` AND `)}`),E=i`${E} ORDER BY _creationTime DESC, id ASC LIMIT ${i.raw(String(Ro(a)))}`;const k=O(o,E).toArray(),$=[];for(const v of k){const A=Kt(v);if(!A)continue;const L=to(gn(A,t.definition),S);L>0&&$.push({creationTime:typeof A._creationTime=="number"?A._creationTime:0,doc:A,id:typeof A._id=="string"?A._id:"",score:L})}return $.sort((v,A)=>A.score-v.score||A.creationTime-v.creationTime||v.id.localeCompare(A.id)),$.slice(0,a).map(v=>({document:v.doc,score:v.score}))},tt=(o,r,t,a)=>{if(!Number.isFinite(o.lat)||o.lat<-90||o.lat>90||!Number.isFinite(o.lng)||o.lng<-180||o.lng>180)throw new y("BAD_REQUEST",`geo index "${a}" on table "${t}": ${r} must have a finite lat in [-90, 90] and lng in [-180, 180]`)},Ao=(o,r)=>{const t=o,a={near:(d,w)=>{if(t.within)throw new y("INTERNAL",`geo index "${t.indexName}" on table "${r}": call .near() or .within(), not both`);if(tt(d,".near() point",r,t.indexName),!Number.isFinite(w)||w<=0)throw new y("BAD_REQUEST",`geo index "${t.indexName}" on table "${r}": .near() radiusMeters must be a finite number > 0, got ${String(w)}`);return t.near={point:{lat:d.lat,lng:d.lng},radiusMeters:w},a},within:d=>{if(t.near)throw new y("INTERNAL",`geo index "${t.indexName}" on table "${r}": call .near() or .within(), not both`);if(tt(d.sw,".within() sw corner",r,t.indexName),tt(d.ne,".within() ne corner",r,t.indexName),d.sw.lat>d.ne.lat)throw new y("BAD_REQUEST",`geo index "${t.indexName}" on table "${r}": .within() corners are transposed (sw.lat > ne.lat)`);if(d.sw.lng>d.ne.lng)throw new y("BAD_REQUEST",`geo index "${t.indexName}" on table "${r}": .within() box crosses the antimeridian (sw.lng > ne.lng), which is not supported — split it into two boxes at ±180 and union the results`);return t.within={ne:{lat:d.ne.lat,lng:d.ne.lng},sw:{lat:d.sw.lat,lng:d.sw.lng}},a}};return a},Io=(o,r)=>{const t=o[r];if(t===null||typeof t!="object")return;const{lat:a,lng:d}=t;return typeof a=="number"&&typeof d=="number"?{lat:a,lng:d}:void 0},Co=(o,r)=>{const t=Io(o,r.definition.field);if(!t)return;const a=typeof o._creationTime=="number"?o._creationTime:0;if(r.near){const d=kn(r.near.point,t);return d<=r.near.radiusMeters?{creationTime:a,distance:d}:void 0}return Fn(t,r.within)?{creationTime:a,distance:0}:void 0},xo=(o,r,t,a)=>{if(!t.near&&!t.within)throw new y("INTERNAL",`geo index "${t.indexName}" on table "${r}": call .near(point, radius) or .within(box)`);const d=t.near?Dn(t.near.point,t.near.radiusMeters):Ln(t.within),w=bn(r,t.indexName),S=d.map(v=>i`(g.${i.identifier("__geohash__")} >= ${v} AND g.${i.identifier("__geohash__")} < ${`${v}{`})`),R=[i`(${i.join(S,i` OR `)})`];a&&R.push(a);const E=i`SELECT m.id, m._creationTime, m.${i.identifier(oe)} FROM ${i.identifier(w)} g JOIN ${i.identifier(r)} m ON m.id = g.${i.identifier("__id__")} WHERE ${i.join(R,i` AND `)}`,k=O(o,E).toArray(),$=[];for(const v of k){const A=ue(v),L=A?Co(A,t):void 0;A&&L&&$.push({creationTime:L.creationTime,distance:L.distance,doc:A})}return $.sort((v,A)=>v.distance-A.distance||A.creationTime-v.creationTime),$},en=(o,r,t,a)=>{const d=[];for(const w of o)if(r.every(S=>S(a(w)))&&(d.push(w),typeof t=="number"&&d.length>=t))break;return d},bo=(o,r,t,a,d,w=()=>{})=>{const S=t.within!==void 0,R=xo(o,r,t,d).map(E=>({distanceMeters:S?null:E.distance,document:E.doc}));return w(R.length),typeof a=="number"?R.slice(0,Math.max(0,Math.floor(a))):R},tn=(o,r,t,a,d,w=()=>{})=>{const{geo:S}=t;if(!S)throw new y("INTERNAL","runGeoTerminalScored called without a staged geo query");const R=t.inMemoryFilters.length>0,E=bo(o,r,S,R?void 0:d,a,w);return R?en(E,t.inMemoryFilters,d,k=>k.document):E},nn=(o,r,t,a)=>{const d=`SELECT id, _creationTime, ${Re(oe)} FROM ${Re(o)}`,w=`ORDER BY ${t}${a===void 0?"":` LIMIT ${String(a)}`}`;return r===void 0?Pe(`${d} ${w}`):Se(`${d} WHERE `,r,` ${w}`)},Mo=(o,r,t,a,d,w=()=>{})=>tn(o,r,t,a,d,w).map(S=>S.document),Do=(o,r,t,a,d,w,S=()=>{})=>{const R=[];for(const v of t.sqlConditions)R.push(i`${Z(v.field)} ${i.raw(v.comparator)} ${re(v.value)}`);a&&R.push(a);let E=i`SELECT id, _creationTime, ${i.identifier(oe)} FROM ${i.identifier(r)}`;R.length>0&&(E=i`${E} WHERE ${i.join(R,i` AND `)}`),E=i`${E} ORDER BY ${d}`,typeof w=="number"&&t.inMemoryFilters.length===0&&(E=i`${E} LIMIT ${i.raw(String(Math.max(0,Math.floor(w))))}`);const k=O(o,E).toArray();S(k.length);const $=[];for(const v of k){const A=ue(v);if(A&&t.inMemoryFilters.every(L=>L(A))&&($.push(A),typeof w=="number"&&$.length>=w))break}return $},Ee={fieldRef:Z,serialize:re},on=(o,r)=>{const t=r===void 0?void 0:o.shape[r];return t!==void 0&&Jn(t)},Wt=(o,r)=>r.some(t=>on(o,t)),Ut=(o,r,t)=>{if(on(o,r))throw new y("BAD_REQUEST",`${t}: "${r}" may hold an order-preserving key rather than a value SQL can reduce or group — declare an aggregateIndex covering this (by, field, op) so the maintained companion answers it instead (its running total is a REAL, so it stays exact only while the total is inside 2^53)`)},dt={fieldRef:o=>Pe(Ue(o)),serialize:re},Lo=o=>{let r=0;const t=[],a={fieldRef:d=>Pe(Ue(d)),relationExists:d=>{const{childWhere:w,negated:S,parentTable:R,relation:E}=d,k=`__rel_${String(r)}`,$=t.at(-1)??R;r+=1,o(E.table,G);const v=E.kind==="one"?E.field:E.references,A=E.kind==="one"?E.references:E.field,L=Pe(`${Tt(k,A)} = ${Tt($,v)}`);t.push(k);const N=ne(w,a,Ge);t.pop();const q=N===void 0?L:Se(L," AND ",N),_=Se("EXISTS (SELECT 1 FROM ",Dt(E.table)," AS ",Dt(k)," WHERE ",q,")");return S?Se("NOT ",_):_},serialize:re};return a},rn=o=>{const r=o.map(t=>`${Ue(t.field)} ${t.direction==="desc"?"DESC":"ASC"}`);return o.some(t=>t.field==="_id"||t.field==="id")||r.push(`${Ue("id")} ${Yt(o)==="desc"?"DESC":"ASC"}`),r.join(", ")},ko=o=>{const r=o.map(t=>i`${Z(t.field)} ${i.raw(t.direction==="desc"?"DESC":"ASC")}`);return o.some(t=>t.field==="_id"||t.field==="id")||r.push(i`${Z("id")} ${i.raw(Yt(o)==="desc"?"DESC":"ASC")}`),i.join(r,i`, `)},Fo={"<":"lt","<=":"lte","=":"eq",">":"gt",">=":"gte"},sn=o=>new Set(o.sqlConditions.filter(r=>r.comparator==="=").map(r=>r.field)),qo=o=>{const r=sn(o);let t=0;for(;t<o.indexFields.length&&r.has(o.indexFields[t]??"");)t+=1;return o.indexFields.slice(t)},cn=(o,r)=>{const t=o.order,a=qo(o),{shape:d}=r;return a.length>0?nt(a.map(w=>({[w]:t})),d,{pinned:sn(o),uniqueBy:zt(r.indexes,d)}):nt([{_creationTime:t}],d)},Bo=(o,r,t,a)=>{const d=o.sqlConditions.map(w=>({[w.field]:{[Fo[w.comparator]??"eq"]:w.value}}));if(t&&d.push(Jt(r,ot(t))),a&&d.push(Wn(r,ot(a))),d.length!==0)return d.length===1?d[0]:{AND:d}},Wo=(o,r,t)=>{const a=[];for(const d of o){const w=ue(d);if(w&&r.every(S=>S(w))&&(a.push(w),t!==void 0&&a.length>t))break}return a},Uo=(o,r,t,a,d,w,S=()=>{})=>{const R=Math.max(0,Math.floor(d.numItems)),E=cn(a,t),k=typeof d.endCursor=="string",$=ne(Bo(a,E,d.cursor,d.endCursor),dt,Ge),v=w&&$?Se($," AND ",w):w??$,A=a.inMemoryFilters.length>0,L=nn(r,v,rn(E),A||k?void 0:R+1),N=_e(o,L.text,...L.params).toArray();S(N.length);const q=Wo(N,a.inMemoryFilters,A||k?void 0:R);if(k){const H=q.length>=2?q[Math.floor(q.length/2)-1]:void 0;return{continueCursor:d.endCursor??null,isDone:!0,page:q,splitCursor:H?rt(H,E):null}}const _=q.length>R,F=_?q.slice(0,R):q,j=F.at(-1);return{continueCursor:_&&j?rt(j,E):null,isDone:!_,page:F}};class Po extends y{constructor(r="unique() found more than one matching document"){super("NOT_UNIQUE",r,{name:"NotUniqueError"})}}const Go=/\s/u,Ho=String.fromCodePoint(0),Pt=(o,r,t)=>{if(!o.tables[r])throw new y("INTERNAL",`unknown table: ${r}`);return typeof t!="string"||t.length===0||Go.test(t)||t.includes(Ho)?null:t},Oo=(o,r,t,a=()=>{},d=()=>{},w=()=>{})=>{const S=r.tables[t];if(!S)throw new y("INTERNAL",`unknown table: ${t}`);const R=le(S.softDeleteMode,void 0),E=R?ne(R,Ee):void 0,k=R?ne(R,dt,Ge):void 0,$={indexFields:[],indexName:void 0,inMemoryFilters:[],order:"asc",sqlConditions:[]};let v=0;const A=m=>{const{search:C}=$;if(!C)throw new y("INTERNAL","runSearchFetch called without a staged search");Rn(o,t,S);const x=$.inMemoryFilters.length>0,D=uo(x?void 0:m),z=xn(o);if(z&&!Tn(o,t,C.definition))throw new y("SEARCH_INDEX_BUILDING",`search index "${C.indexName}" on table "${t}" is still backfilling and currently covers only part of the table — retry once it finishes, or run the backfillSearch admin operation to complete it now`);const X=z?To(o,t,C,D,E):vo(o,t,C,D,E);return x?(v=X.length,en(X,$.inMemoryFilters,m,ce=>ce.document)):(m===void 0&&ro(X),X)},L=m=>A(m).map(C=>C.document),N=m=>{const C=ao(m);return lo(L(io(C)),C)},q=()=>ko(cn($,S)),_=()=>{if($.search||$.geo||$.indexName===void 0){d(void 0);return}d(Nn(t,$.indexName,$.indexFields,$.sqlConditions,re))},F=m=>{_();let C=0;const x=(()=>{if($.search){const D=L(m);return C=v,D}return $.geo?Mo(o,t,$,E,m,D=>{C=D}):Do(o,t,$,E,q(),m,D=>{C=D})})();return w(Math.max(C,x.length)),x},j=()=>{if(!$.search&&!$.geo)throw new y("INTERNAL",`ctx.db.query("${t}").collectWithScores() requires a staged .withSearchIndex(...) or .withGeoIndex(...)`);_();let m=0;const C=(()=>{if($.search){const x=A(void 0);return m=v,x}return tn(o,t,$,E,void 0,x=>{m=x})})();return w(Math.max(m,C.length)),C},H={async*[Symbol.asyncIterator](){if($.search){yield*F(void 0);return}const m=[...$.inMemoryFilters];let C;$.inMemoryFilters=[];try{for(;;){const x=await H.paginate({cursor:C??null,numItems:So});for(const D of x.page)m.every(z=>z(D))&&(yield D);if(x.isDone||x.continueCursor===null)return;C=x.continueCursor}}finally{$.inMemoryFilters=m}},async collect(){return F(void 0)},async collectWithScores(){return j()},filter(m){return $.inMemoryFilters.push(m),H},async first(){return F($.inMemoryFilters.length>0?void 0:1)[0]??null},order(m){return $.order=m==="desc"?"desc":"asc",H},async paginate(m){let C=0;if(_(),$.search){const D=N(m);return w(D.page.length),D}if($.geo)throw new y("INTERNAL","pagination is not supported on geo queries; use .take(n) or .collect()");const x=Uo(o,t,S,$,m,k,D=>{C=D});return w(Math.max(C,x.page.length)),x},async take(m){return F(m)},async unique(){const m=F($.inMemoryFilters.length>0?void 0:2);if(m.length>1)throw new Po(`unique() on table "${t}" matched ${String(m.length)} documents; expected at most one`);return m[0]??null},withGeoIndex(m,C){const x=(S.geoIndexes??[]).find(z=>z.name===m);if(!x)throw new y("INTERNAL",`unknown geo index "${m}" on table "${t}"`);a(t,m,"geo");const D={definition:x,indexName:m};if($.geo=D,C(Ao(D,t)),!D.near&&!D.within)throw new y("INTERNAL",`geo index "${m}" on table "${t}" requires a .near(point, radius) or .within(box) call`);return H},withIndex(m,C){const x=S.indexes.find(D=>D.name===m);if(!x)throw new y("INTERNAL",`unknown index "${m}" on table "${t}"`);return a(t,m,"index"),$.indexName=m,$.indexFields=x.fields,C&&C(_o($)),H},withSearchIndex(m,C){const x=(S.searchIndexes??[]).find(z=>z.name===m);if(!x)throw new y("INTERNAL",`unknown search index "${m}" on table "${t}"`);a(t,m,"search");const D={definition:x,field:x.field,filters:[],hasQuery:!1,indexName:m,query:""};if($.search=D,C(oo(D,t,st(x.language))),!D.hasQuery)throw new y("INTERNAL",`search index "${m}" on table "${t}" requires a .search(field, query) call`);return H}};return H},Gt=(o,r,t)=>{const a={...r};for(const[d,w]of jt(o)){if(w.serverDefault){a[d]=w.serverDefault({auth:t});continue}a[d]===void 0&&(w.defaultFn?a[d]=w.defaultFn():"defaultValue"in w&&(a[d]=w.defaultValue))}return a},Ht=(o,r,t,a)=>{const d=t;for(const[w,S]of jt(o)){if(S.serverDefault){w in r&&(d[w]=S.serverDefault({auth:a}));continue}S.onUpdateFn&&!(w in r)&&(d[w]=S.onUpdateFn())}},Ot=(o,r)=>{for(const t of Object.keys(r))if(r[t]===void 0)throw new y("INTERNAL",`Cannot ${o} field '${t}' to undefined — use null to clear a nullable field, or omit the key to leave it unchanged.`)},No=/unique constraint failed/i,jo=o=>o instanceof Error&&No.test(o.message),Ko=/string or blob too big/iu,Qo=(o,r)=>{if(!(!(o instanceof Error)||!Ko.test(o.message)))throw new y("PAYLOAD_TOO_LARGE",`document is too large to store in "${r}": a single row cannot exceed the storage engine's per-row ceiling (2 MB on a Durable Object's SQLite). The limit is on the STORED bytes, which are UTF-8, and v.bytes()/v.bigint() columns are stored twice on a shard-local table. Keep the payload in R2 (ctx.storage) and store a reference on the row.`)},it=(o,r,t,a)=>{try{_e(o,t,...a)}catch(d){throw jo(d)?new me(`unique constraint violation on "${r}"`,"unique"):(Qo(d,r),d)}},We=(o,r,t,a)=>{if(it(o,r,t,a),_e(o,po).one().changed===0)throw new me(`optimistic concurrency conflict on "${r}" — the row changed during this mutation; refetch and retry`,"occ")},Nt=(o,r,t,a,d,w,S)=>{const R=[];for(let v=0;v<t.length+1;v+=1){const A=t[v],L=a[v],N=L?.direction==="desc"?"desc":"asc",q=A===void 0||L===void 0?i`${i.identifier(Gn)} < ${S}`:Hn(A,w[v],N,!1);if(q===void 0)continue;const _=[];for(let j=0;j<v;j+=1)_.push(i`${i.identifier(t[j])} IS ${w[j]}`);_.push(q);const[F]=_;R.push(_.length===1&&F!==void 0?F:i`(${i.join(_,i` AND `)})`)}const E=R.length>0?i.join(R,i` OR `):i`1 = 0`,k=O(o,i`SELECT COUNT(*) AS c FROM ${i.identifier(r)} WHERE ${i.identifier("__partition__")} = ${d} AND (${E})`).one(),$=O(o,i`SELECT COUNT(*) AS c FROM ${i.identifier(r)} WHERE ${i.identifier("__partition__")} = ${d}`).one();return{before:k.c,total:$.c}},Cr=o=>{const{sql:r}=o,{schema:t}=o,a=o.broadcast??(()=>{}),d=jn(t);let w;const S=()=>o.inTransaction?.()===!0,R=e=>t.tables[e]?.commitOrderedMode!==!0?{}:((w===void 0||!S())&&(w=An(r)),{[In]:w}),E=(e,...n)=>{const s=t.tables[e]?.indexes;if(!s||s.length===0)return;const f=[];for(const h of n)h&&f.push(...On(s,h,re));return f.length>0?f:void 0},{headroom:k}=o;let $=!1;const v=async e=>{const n=$;$=!0;try{return await e()}finally{$=n}},A=o.onRead??(()=>{}),L=e=>{_t(t.tables[e])&&A(Ct,Ct)},N=o.onReadRange??(e=>{A(e.table,G)}),q=e=>{L(e.table),N(e)},_=(e,n)=>{n!==void 0&&n!==G&&!$&&k?.recordRead(1),L(e),A(e,n)},F=o.onIndexUse??(()=>{}),j=o.onWrite??(()=>{}),H=e=>{$||k?.recordWrite(e)},m=async e=>{H(e.doc),await j(e)},{cache:C}=o,x=o.clock??(()=>Date.now()),D=o.idGenerator??(()=>crypto.randomUUID()),z=o.scheduler??yn,{globalDb:X}=o,ce=o.auth??{identity:null,userId:null},an=o.cdc??!1,Oe=z,dn=Yn({scheduler:typeof Oe.list=="function"&&typeof Oe.get=="function"?Oe:void 0,storage:o.storage}),he=(e,n,s,f)=>{an&&!_t(t.tables[e])&&vn(r,x(),e,n,s,f)},ie=e=>t.tables[e]?.shardMode?.kind==="global",lt=(e,n)=>{if(ie(e)){if(!X)throw new y("INTERNAL",`cross-backend ${n} for global table '${e}' requires a globalDb writer — pass one to createShardCtxDb({ globalDb })`);return X}return W},Ne=e=>lt(e,"cascade"),Q=(e,n)=>{if(ie(e)){if(!X)throw new y("INTERNAL",`${n} on global table '${e}' requires a globalDb writer — pass one to createShardCtxDb({ globalDb })`);return X}},ut=async(e,n,s,f,h)=>{h&&H(s);const u=await e.insert(n,s,f);return a({key:u,op:"insert",row:{...s,_id:u},table:n}),u},je=(e,n)=>lt(e,"relation load").findMany(e,n),ft=(e,n)=>(ie(e)&&_(e,G),je(e,n)),ln=e=>!ie(e.table),ht=o.relationExistsPushDown??"auto",wt=ht!=="never",{maxRelationKeys:pt}=o,Te=(e,n,s)=>xt(e,{fetcher:ft,maxRelationKeys:pt,relationBaseWhere:s,schema:t,tableName:n}),gt=async(e,n,s,f)=>{const h=Q(e,"relation grouped count");if(h)return _(e,G),Vn((B,I)=>h.count(B,I),e,n,s,f);const u=t.tables[e];if(!u)throw new y("INTERNAL",`unknown table: ${e}`);_(e,G);const c=le(u.softDeleteMode,void 0),l={[n]:{in:s}},p=V(V(l,f),c),T=await Te(p,e,void 0),g=ne(T,Ee),M=Z(n);let b=i`SELECT ${M} AS __fk__, COUNT(*) AS count FROM ${i.identifier(e)}`;g&&(b=i`${b} WHERE ${g}`),b=i`${b} GROUP BY ${M}`;const P=O(r,b).toArray();return new Map(P.map(B=>[B.__fk__,B.count]))};let ve=0;const $t=new Set;for(const[e,n]of Object.entries(t.tables))for(const s of Object.values(n.triggerMap??{}))$t.add(`${e} ${s.timing} ${s.op}`);const ee=(e,n,s)=>$t.has(`${e} ${n} ${s}`),te=async(e,n,s)=>{if(ve+=1,ve>Bt)throw ve-=1,new me(`trigger recursion exceeded ${String(Bt)} levels on "${s.table}" — check for a self-triggering write`,"trigger");try{await Xn({ctx:fn,event:s,op:n,schema:t,tableName:s.table,timing:e})}finally{ve-=1}},{ensureBackfilledForTable:we,ensureBackfilledIndex:Ke,ensureRankBackfilled:Qe,ensureRankBackfilledForTable:pe,syncAggregates:Ae,syncCompanionsForInsert:yt,syncGeo:Ie,syncRanks:ge,syncSearch:Ce}=wn({broadcast:a,indexKeysFor:(e,n)=>E(e,n),invalidateCache:(e,n,s)=>C?.invalidate(e,n,E(e,s)),recordCdc:he,schema:t,sql:r}),Et=(e,n,s)=>{const{shardMode:f}=n;if(f?.kind==="shardBy"&&!(f.field!==void 0&&(s.partitionBy??[]).includes(f.field)))throw Object.assign(new Error(`rank index "${s.name}" on "${e}" partitions across shards (shard key "${f.field??"?"}" is not in partitionBy) — a shard-local rank()/rankPage() would be wrong; roll it up through the Query Coordinator instead`),{code:"CROSS_SHARD_RANK_UNSUPPORTED",name:"LunoraError",status:400})},mt=e=>Object.entries(t.tables).filter(([,n])=>n.shardMode?.kind!=="global").map(([n])=>n).filter(n=>e===void 0||n===e),$e=e=>e===void 0||ie(e)?X:void 0,se=(e,n)=>{const s=mt(n);for(let f=0;f<s.length;f+=ye){const h=s.slice(f,f+ye),[u]=_e(r,$o(h),...yo(e,h)).toArray();if(!u)continue;const c=u.__t__,l=ue(u);if(typeof c!="string"||!l)return;const p=u[oe];return{docJson:typeof p=="string"?p:ae(p??{}),row:l,tableName:c}}},un=(e,n)=>{const s=[...new Set(e)],f=new Map;if(s.length===0)return f;const h=mt(n);for(let u=0;u<h.length;u+=ye){const c=h.slice(u,u+ye),l=Math.floor(ye/c.length),p=Mn(i`${i.identifier("id")}`,s,!1,l),T=c.map(g=>i`SELECT ${i.raw(`'${g.replaceAll("'","''")}'`)} AS __t__, id FROM ${i.identifier(g)} WHERE ${p}`);for(const g of O(r,ct(T))){const{id:M,__t__:b}=g;typeof b=="string"&&typeof M=="string"&&f.set(M,b)}}return f},St={assertRankPartitionLocal:Et,ensureRankBackfilled:Qe,onRead:_,rowToDocument:ue,schema:t,sql:r},W={system:dn,async aggregate(e,n){const s=Q(e,"aggregate");if(s)return _(e,G),s.aggregate(e,n);const f=t.tables[e];if(!f)throw new y("INTERNAL",`unknown table: ${e}`);if(ke(n.op),n.op==="count")return W.count(e,{baseWhere:n.baseWhere,relationBaseWhere:n.relationBaseWhere,restrictsCounts:n.restrictsCounts,where:n.where});if(!n.field)throw new y("INTERNAL",`aggregate(${e}, { op: "${n.op}" }): "field" is required for non-count reducers`);_(e,G);const h=le(f.softDeleteMode,void 0),u=V(V(n.baseWhere,n.where),h),c=await Te(u,e,n.relationBaseWhere),l=c!==u;if(f.aggregateIndexes&&!n.baseWhere&&!l&&(!h||Wt(f,[n.field]))){const B=_n(f.aggregateIndexes,n.op,n.field,n.where);if(B){Ke(e,B.index);const I=ze(B.index.by??[],B.key),K=Ve(e,B.index.name),J=O(r,i`SELECT ${Fe} AS value, ${Xe} AS count FROM ${i.identifier(K)} WHERE ${qe} = ${I}`).toArray()[0];return Je(n.op,J)}}Ut(f,n.field,`aggregate(${e}, { op: "${n.op}", field: "${n.field}" })`);const p=ne(c,Ee),T=ke(n.op),g=Z(n.field);let M=i`SELECT ${i.raw(T)}(${g}) AS value FROM ${i.identifier(e)}`;p&&(M=i`${M} WHERE ${p}`);const P=O(r,M).toArray()[0]?.value;return P??null},asId(e,n){const s=Pt(t,e,n);if(s===null)throw new y("BAD_REQUEST",`asId("${e}", …): "${n}" is not a valid id for table "${e}"`,{status:400});return s},async count(e,n){const s=Q(e,"count");if(s)return _(e,G),s.count(e,n);const f=t.tables[e];if(!f)throw new y("INTERNAL",`unknown table: ${e}`);const h=En(n);if(h.restrictsCounts)throw new Ye(e);_(e,G);const u=le(f.softDeleteMode,void 0),c=V(V(h.baseWhere,h.where),u),l=await Te(c,e,h.relationBaseWhere),p=l!==c;if(f.aggregateIndexes&&!h.baseWhere&&!p&&!u){const b=Sn(f.aggregateIndexes,h.where);if(b){Ke(e,b.index);const P=ze(b.index.by??[],b.key),B=Ve(e,b.index.name),I=O(r,i`SELECT ${Fe} AS value FROM ${i.identifier(B)} WHERE ${qe} = ${P}`).toArray();return I[0]===void 0?0:I[0].value??0}}const T=ne(l,Ee);let g=i`SELECT COUNT(*) AS count FROM ${i.identifier(e)}`;return T&&(g=i`${g} WHERE ${T}`),O(r,g).one().count},async delete(e,n,s){const f=se(e,n);if(!f){const g=$e(n);g&&(H(void 0),await g.delete(e,n,s));return}const{docJson:h,row:u,tableName:c}=f,l=t.tables[c],p=s?.hard===!0,T=!p&&l?.softDeleteMode?l.softDeleteMode.field:void 0;if(!(T&&u[T]!==null&&u[T]!==void 0)){if(ee(c,"before","delete")&&await te("before","delete",{id:e,op:"delete",previous:u,table:c}),await Qn({deletedId:e,deletedReference:g=>u[g],findHolders:async(g,M,b)=>(await Ne(g).findMany(g,{includeDeleted:p,where:{[M]:b}})).page,onCascade:(g,M)=>Ne(g).delete(M,void 0,s),onRestrict:g=>{throw new me(g,"restrict")},onSetNull:(g,M,b)=>Ne(g).patch(M,{[b]:null}),schema:t,tableName:c}),we(c),pe(c),T){const g={...u,...R(c),[T]:x(),_id:e};We(r,c,Ft(c),[ae(g),e,h]),Ce(c,e,g,u),Ie(c,e,void 0),Ae(c,u,g),ge(c,e,u,void 0),C?.invalidate(c,e,E(c,u,g)),he(c,e,"update",g),a({indexKeys:E(c,u,g),key:e,op:"update",row:g,table:c}),ee(c,"after","delete")&&await te("after","delete",{id:e,op:"delete",previous:u,table:c}),await m({id:e,op:"delete",table:c});return}We(r,c,wo(c),[e,h]),Ce(c,e,void 0),Ie(c,e,void 0),Ae(c,u,void 0),ge(c,e,u,void 0),C?.invalidate(c,e,E(c,u)),he(c,e,"delete"),a({indexKeys:E(c,u),key:e,op:"delete",table:c}),ee(c,"after","delete")&&await te("after","delete",{id:e,op:"delete",previous:u,table:c}),await m({id:e,op:"delete",table:c})}},async deleteAll(e,n){if(!t.tables[e])throw new y("INTERNAL",`unknown table: ${e}`);const s=Math.max(1,n?.chunkSize??Xt),f=n?.hard===void 0?void 0:{hard:n.hard},h=ie(e)?void 0:e;let u=0;return await v(async()=>{for(;;){const l=(await W.findMany(e,{limit:s})).page.map(p=>String(p._id));if(l.length===0)break;for(const p of l)await W.delete(p,h,f),u+=1;if(l.length<s)break}}),{deleted:u}},async deleteMany(e,n,s){de(e.length,n?.limit,"deleteMany");for(const f of e)await W.delete(f,s);return{deleted:e.length}},async deleteWhere(e,n,s){const u=(await(Q(e,"deleteWhere")??W).findMany(e,{where:n})).page.map(c=>String(c._id));if(de(u.length,s?.limit,"deleteWhere"),W.deleteMany===void 0)throw new y("INTERNAL",`ctx.db.${e}.deleteMany is unavailable: this writer has no batch delete`);return W.deleteMany(u,s)},async findFirst(e,n={}){return(await W.findMany(e,{...n,limit:1,omitContinueCursor:!0})).page[0]??null},async findFirstOrThrow(e,n={}){const s=await W.findFirst(e,n);if(s===null)throw new qn(`findFirstOrThrow: no "${e}" document matched`);return s},async findMany(e,n={}){const s=Q(e,"findMany");if(s)return _(e,G),s.findMany(e,n);const f=t.tables[e];if(!f)throw new y("INTERNAL",`unknown table: ${e}`);const h=!n.where&&!n.baseWhere;h?_(e,G):_(e);const u=nt(n.orderBy,f.shape,{pinned:Bn(n.where),uniqueBy:zt(f.indexes,f.shape)}),c=n.cursor?Jt(u,ot(n.cursor)):void 0;let l=V(n.baseWhere,n.where);l=V(l,le(f.softDeleteMode,n.includeDeleted)),l=await xt(l,{canPushExists:wt?ln:void 0,existsPushMode:ht==="always"?"always":"auto",fetcher:ft,maxRelationKeys:pt,relationBaseWhere:n.relationBaseWhere,schema:t,tableName:e}),c&&(l=l?{AND:[l,c]}:c);const p=wt?Lo(_):dt,T=ne(l,p,Ge),g=typeof n.limit=="number"?Math.max(0,Math.floor(n.limit)):void 0,M=nn(e,T,rn(u),g===void 0?void 0:g+1),b=_e(r,M.text,...M.params).toArray();h&&!$&&k?.recordRead(b.length);const P=[];for(const J of b){const U=ue(J);U&&(P.push(U),!h&&typeof U._id=="string"&&_(e,U._id))}if(g===void 0)return n.with&&await bt({groupedCounter:gt,fetcher:je,parents:P,...Mt(n),schema:t,tableName:e,with:n.with}),{continueCursor:null,isDone:!0,page:vt(P,n.select,n.with)};const B=P.length>g,I=B?P.slice(0,g):P,K=I.at(-1);return n.with&&await bt({fetcher:je,groupedCounter:gt,parents:I,...Mt(n),schema:t,tableName:e,with:n.with}),{continueCursor:B&&K&&n.omitContinueCursor!==!0?rt(K,u):null,isDone:!B,page:vt(I,n.select,n.with)}},async get(e,n){const s=se(e,n);if(!s){const f=$e(n);return f?f.get(e,n):null}return _(s.tableName,e),s.row},async lookupById(e,n){const s=se(e,n);return s?(_(s.tableName,e),{row:s.row,tableName:s.tableName}):null},async groupBy(e,n){const s=Q(e,"groupBy");if(s)return _(e,G),s.groupBy(e,n);const f=t.tables[e];if(!f)throw new y("INTERNAL",`unknown table: ${e}`);_(e,G);const h=n.agg??{op:"count"};if(ke(h.op),h.op!=="count"&&!h.field)throw new y("INTERNAL",`groupBy(${e}, { agg: { op: "${h.op}" } }): "field" is required for non-count reducers`);const u=le(f.softDeleteMode,void 0),c=V(V(n.baseWhere,n.where),u),l=await Te(c,e,n.relationBaseWhere),p=l!==c,T=[...n.by,h.field];if(f.aggregateIndexes&&!n.baseWhere&&!p&&(!u||Wt(f,T))){const I=mn(f.aggregateIndexes,h.op,h.field,n.by,n.where),K=I===void 0?0:Object.keys(I.partial).length,J=I?.index.by?.length??0;if(I&&(K===0||K===J)){Ke(e,I.index);const U=Ve(e,I.index.name),xe=Object.keys(I.partial),be=[];if(xe.length===(I.index.by??[]).length&&xe.length>0){const Me=ze(I.index.by??[],I.partial),De=O(r,i`SELECT ${Fe} AS value, ${Xe} AS count FROM ${i.identifier(U)} WHERE ${qe} = ${Me}`).toArray();return De.length>0&&be.push({key:{...I.partial},value:Je(h.op,De[0])}),be}const hn=O(r,i`SELECT ${qe} AS key, ${Fe} AS value, ${Xe} AS count FROM ${i.identifier(U)}`).toArray();for(const Me of hn){const De=$n(JSON.parse(Me.key));be.push({key:De,value:Je(h.op,Me)})}return be}}for(const I of T){if(I===void 0)continue;const K=I===h.field?`groupBy(${e}, { agg: { op: "${h.op}", field: "${I}" } })`:`groupBy(${e}, { by: [..."${I}"] })`;Ut(f,I,K)}const g=ne(l,Ee),M=n.by.map(I=>i`${Z(I)} AS ${i.identifier(I)}`);if(h.op==="count")M.push(i`COUNT(*) AS value`);else{const{field:I}=h;if(I===void 0)throw new y("INTERNAL",`groupBy(${e}, { agg: { op: "${h.op}" } }): "field" is required for non-count reducers`);M.push(i`${i.raw(ke(h.op))}(${Z(I)}) AS value`)}let b=i`SELECT ${i.join(M,i`, `)} FROM ${i.identifier(e)}`;g&&(b=i`${b} WHERE ${g}`),b=i`${b} GROUP BY ${i.join(n.by.map(I=>Z(I)),i`, `)}`;const P=O(r,b).toArray(),B=[];for(const I of P){const K={};for(const U of n.by)K[U]=Cn(f.shape[U],I[U]??null);const{value:J}=I;B.push({key:K,value:J==null?null:Number(J)})}return B},async insert(e,n,s){const f=Q(e,"insert");if(f)return ut(f,e,n,s,!0);const h=t.tables[e];if(!h)throw new y("INTERNAL",`unknown table: ${e}`);const u=Gt(h,n,ce);et(h,u);let c;s?.clientId!==void 0?(mo(s.clientId),c=s.clientId):s?.allowExplicitId&&typeof u._id=="string"?c=u._id:c=D();const l=s?.allowExplicitId&&typeof u._creationTime=="number"?u._creationTime:x(),p={...u,...R(e),_creationTime:l,_id:c};return ee(e,"before","insert")&&await te("before","insert",{doc:{...p},id:c,op:"insert",table:e}),we(e),pe(e),it(r,e,fo(e),[c,l,ae(p)]),yt(e,c,p),ee(e,"after","insert")&&await te("after","insert",{doc:p,id:c,op:"insert",table:e}),await m({doc:p,id:c,op:"insert",table:e}),c},async insertManyUnsafe(e,n,s){if(de(n.length,s?.limit,"insertManyUnsafe"),n.length===0)return[];const f=Q(e,"insert");if(f){const l=[];for(const p of n)H(p);for(const p of n){const T=await f.insert(e,p,{allowExplicitId:s?.allowExplicitId});a({key:T,op:"insert",row:{...p,_id:T},table:e}),l.push(T)}return l}const h=t.tables[e];if(!h)throw new y("INTERNAL",`unknown table: ${e}`);we(e),pe(e);const u=[];for(let l=0;l<n.length;l+=Be)u.push(R(e));const c=n.map((l,p)=>{const T=Gt(h,l,ce),g=s?.allowExplicitId===!0&&typeof T._id=="string"?T._id:D(),M=s?.allowExplicitId===!0&&typeof T._creationTime=="number"?T._creationTime:x(),b={...T,...u[Math.floor(p/Be)],_creationTime:M,_id:g};return{creationTime:M,document:b,id:g}});for(const l of c)H(l.document);for(let l=0;l<c.length;l+=Be){const p=i.join(c.slice(l,l+Be).map(g=>i`(${g.id}, ${g.creationTime}, ${ae(g.document)})`),i`, `),T=Qt("sqlite",i`INSERT INTO ${i.identifier(e)} (id, _creationTime, ${i.identifier(oe)}) VALUES ${p}`);it(r,e,T.sql,T.params)}for(const{document:l,id:p}of c)yt(e,p,l),await j({doc:l,id:p,op:"insert",table:e});return c.map(l=>l.id)},async insertMany(e,n,s){de(n.length,s?.limit,"insertMany");const f=s?.skipDuplicates===!0,h=[],u=Q(e,"insert");if(u)for(const l of n)H(l);const c=async l=>u?ut(u,e,l,void 0,!1):W.insert(e,l);for(const l of n)try{h.push(await c(l))}catch(p){if(f&&p instanceof me&&p.kind==="unique")h.push(null);else throw p}return h},normalizeId(e,n){return Pt(t,e,n)},async patch(e,n,s){const f=se(e,s);if(!f){const T=$e(s);if(T){H(n),await T.patch(e,n,s);return}throw new y("NOT_FOUND",`document not found: ${e}`)}const{docJson:h,row:u,tableName:c}=f,l=t.tables[c];if(!l)throw new y("INTERNAL",`unknown table: ${c}`);_(c,e),Ot("patch",n);const p={...u,...n,...R(c),_id:e};Ht(l,n,p,ce),et(l,p,!0),ee(c,"before","update")&&await te("before","update",{doc:{...p},id:e,op:"update",previous:u,table:c}),we(c),pe(c),We(r,c,Ft(c),[ae(p),e,h]),Ce(c,e,p,u),Ie(c,e,p),Ae(c,u,p),ge(c,e,u,p),C?.invalidate(c,e,E(c,u,p)),he(c,e,"update",p),a({indexKeys:E(c,u,p),key:e,op:"update",row:p,table:c}),ee(c,"after","update")&&await te("after","update",{doc:p,id:e,op:"update",previous:u,table:c}),await m({doc:p,id:e,op:"update",table:c})},async patchMany(e,n,s){de(e.length,n?.limit,"patchMany");for(const f of e)await W.patch(f.id,f.patch,s);return{patched:e.length}},async patchWhere(e,n,s){const u=(await(Q(e,"patchWhere")??W).findMany(e,{where:n.where})).page.map(c=>({id:String(c._id),patch:n.patch}));if(de(u.length,s?.limit,"patchWhere"),W.patchMany===void 0)throw new y("INTERNAL",`ctx.db.${e}.patchMany is unavailable: this writer has no batch patch`);return await W.patchMany(u,s),{patched:u.length}},async related(e,n){return Kn(W,d,e,n)},relationEdges:d,query(e){const n=Q(e,"query");return n?(_(e,G),n.query(e)):Oo(r,t,e,F,s=>{s?q(s):_(e,G)},s=>{$||k?.recordRead(s)})},async rank(e,n,s){const f=Q(e,"rank");if(f)return _(e,G),f.rank(e,n,s);F(e,n,"rank");const h=t.tables[e];if(!h)throw new y("INTERNAL",`unknown table: ${e}`);const u=h.rankIndexes?.find(U=>U.name===n);if(!u)throw new y("INTERNAL",`unknown rankIndex "${n}" on table "${e}"`);if(Et(e,h,u),s.restrictsCounts)throw new Ye(e);_(e,G),Qe(e,u);const c=typeof s.row=="string"?s.row:s.row._id;if(!c)return null;const l=At(e,u.name),p=u.sortBy.map((U,xe)=>It(xe)),T=p.map(U=>Re(U)).join(", "),g=O(r,i`SELECT ${i.identifier("__partition__")}, ${i.raw(T)} FROM ${i.identifier(l)} WHERE ${i.identifier("__id__")} = ${c}`).toArray(),[M]=g;if(M===void 0)return null;let b=M.__partition__;const P=V(s.baseWhere,s.where);Ze(P,t,e,"rank");const B=Un(u,P);if(B){const U=Pn(u.partitionBy??[],B);if(U!==b)return null;b=U}const I=p.map(U=>M[U]),{before:K,total:J}=Nt(r,l,p,u.sortBy,b,I,c);return{position:K+1,total:J}},async rankBefore(e,n,s){if(ie(e))throw new y("INTERNAL",`rankBefore is not supported on the global (.global()) table '${e}' — cross-shard rank cursors apply only to sharded tables`);const f=t.tables[e];if(!f)throw new y("INTERNAL",`unknown table: ${e}`);const h=f.rankIndexes?.find(p=>p.name===n);if(!h)throw new y("INTERNAL",`unknown rankIndex "${n}" on table "${e}"`);if(s.restrictsCounts)throw new Ye(e);_(e,G),Qe(e,h);const u=At(e,h.name),c=h.sortBy.map((p,T)=>It(T)),l=h.sortBy.map((p,T)=>re(s.sortValues[T]??null));return Nt(r,u,c,h.sortBy,s.partitionKey,l,s.rowId)},async rankPage(e,n,s={}){Ze(V(s.baseWhere,s.where),t,e,"rankPage");const f=Q(e,"rankPage");if(f)return _(e,G),f.rankPage(e,n,s);F(e,n,"rank");const{continueCursor:h,hasMore:u,rows:c}=Rt(St,e,n,s);return{continueCursor:h,isDone:!u,page:c.map(l=>l.doc)}},async rankPageRows(e,n,s={}){Ze(V(s.baseWhere,s.where),t,e,"rankPage"),F(e,n,"rank");const{directions:f,hasMore:h,rows:u}=Rt(St,e,n,s);return{directions:f,hasMore:h,rows:u}},async restore(e,n){const s=se(e,n);if(!s){const u=$e(n);if(u?.restore){await u.restore(e,n);return}throw new y("NOT_FOUND",`document not found: ${e}`)}const f=t.tables[s.tableName]?.softDeleteMode?.field;if(!f)throw new y("INTERNAL",`ctx.db.restore: table "${s.tableName}" is not a .softDelete() table`);const h=s.row[f]!==null&&s.row[f]!==void 0;await W.patch(e,{[f]:null},n),h&&ge(s.tableName,e,void 0,s.row)},async replace(e,n,s,f){const h=se(e,s);if(!h){const M=$e(s);if(M){H(n),await M.replace(e,n,s,f);return}throw new y("NOT_FOUND",`document not found: ${e}`)}const{docJson:u,row:c,tableName:l}=h,p=t.tables[l];if(!p)throw new y("INTERNAL",`unknown table: ${l}`);Ot("replace",n);const T=f?.allowExplicitId&&typeof n._creationTime=="number"?n._creationTime:x(),g={...n,...R(l),_creationTime:T,_id:e};Ht(p,n,g,ce),et(p,g),ee(l,"before","update")&&await te("before","update",{doc:{...g},id:e,op:"update",previous:c,table:l}),we(l),pe(l),We(r,l,ho(l),[T,ae(g),e,u]),Ce(l,e,g,c),Ie(l,e,g),Ae(l,c,g),ge(l,e,c,g),C?.invalidate(l,e,E(l,c,g)),he(l,e,"update",g),a({indexKeys:E(l,c,g),key:e,op:"update",row:g,table:l}),ee(l,"after","update")&&await te("after","update",{doc:g,id:e,op:"update",previous:c,table:l}),await m({doc:g,id:e,op:"update",table:l})},async wipeShard(e){const n=new Set(e?.exclude),s=e?.tables,f=Object.entries(t.tables).filter(([l,p])=>n.has(l)||s!==void 0&&!s.includes(l)?!1:p.shardMode?.kind!=="global").map(([l])=>l);if(s!==void 0){for(const l of s)if(!t.tables[l])throw new y("INTERNAL",`wipeShard: unknown table: ${l}`)}const h={};let u=0;const{deleteAll:c}=W;if(c===void 0)throw new y("INTERNAL","wipeShard: this writer has no deleteAll");for(const l of f){const p=await c(l,{...e?.chunkSize===void 0?{}:{chunkSize:e.chunkSize},hard:!0});h[l]=p.deleted,u+=p.deleted}return{deleted:u,tables:h}}},fn={db:W,scheduler:z};return o.enforceRls===!0?zn(W,t,(e,n)=>se(e,n)?.tableName,(e,n)=>un(e,n),d):W};export{Fr as CDC_LOG_TABLE,Xr as CLIENT_WATERMARK_TABLE,oi as GLOBAL_SHAPE_SNAPSHOT_TABLE,li as IDEMPOTENCY_TABLE,Po as NotUniqueError,$i as SEARCH_STATE_TABLE,Zr as advanceClientWatermark,qr as applyCdcChanges,Ot as assertNoExplicitUndefined,mo as assertValidClientId,Mr as backfillAggregateIndexes,Dr as backfillRankIndexes,Lr as backfillSearchIndexes,Br as bumpCdcEpoch,Wr as cdcCanVouchFor,Ur as cdcSeqLeavingRows,Pr as cdcTouchesTables,Gr as cdcTrimmedError,Hr as compactCdcDocs,Cr as createShardCtxDb,Or as cursorBelowRetainedFloor,ri as deleteGlobalShapeSnapshot,ii as deleteGlobalShapeSnapshotsForConnection,ei as migrateClientWatermark,si as migrateGlobalShapeSnapshot,Nr as minCdcReplayableSeq,jr as minCdcSeq,Pt as normalizeIdStructurally,Kr as readCdcChangeKeys,Qr as readCdcChanges,Vr as readCdcCursor,zr as readCdcEpoch,ti as readClientWatermark,ci as readGlobalShapeSnapshot,ui as readIdempotent,pi as runShardMigrations,Ei as selectShapeMembers,mi as selectShapeRows,Jr as trimCdcChanges,fi as trimIdempotent,ai as writeGlobalShapeSnapshot,hi as writeIdempotent};
@@ -0,0 +1,11 @@
1
+ import{sql as t}from"drizzle-orm";import{runDrizzle as a}from"./runDrizzle-2ULFQR_k.mjs";const o="__schedule_outbox",_=e=>{a(e,t`CREATE TABLE IF NOT EXISTS ${t.identifier(o)} (
2
+ id TEXT PRIMARY KEY,
3
+ envelope_json TEXT NOT NULL,
4
+ attempts INTEGER NOT NULL,
5
+ next_attempt_at REAL NOT NULL,
6
+ created_at REAL NOT NULL,
7
+ dead INTEGER NOT NULL DEFAULT 0
8
+ )`),a(e,t`CREATE INDEX IF NOT EXISTS ${t.identifier(`${o}_due`)} ON ${t.identifier(o)} (dead, next_attempt_at)`)},p=(e,d,E,n)=>{a(e,t`INSERT OR REPLACE INTO ${t.identifier(o)} (id, envelope_json, attempts, next_attempt_at, created_at, dead)
9
+ VALUES (${d}, ${E}, 0, ${n}, ${n}, 0)`)},s=(e,d)=>{a(e,t`DELETE FROM ${t.identifier(o)} WHERE id = ${d}`)},u=(e,d,E)=>a(e,t`SELECT id, envelope_json, attempts, next_attempt_at FROM ${t.identifier(o)}
10
+ WHERE dead = 0 AND next_attempt_at <= ${d}
11
+ ORDER BY next_attempt_at ASC LIMIT ${E}`).toArray().map(i=>({attempts:i.attempts,envelopeJson:i.envelope_json,id:i.id,nextAttemptAt:i.next_attempt_at})),c=(e,d,E,n)=>{a(e,t`UPDATE ${t.identifier(o)} SET attempts = ${E}, next_attempt_at = ${n} WHERE id = ${d}`)},O=(e,d,E)=>{a(e,t`UPDATE ${t.identifier(o)} SET attempts = ${E}, dead = 1 WHERE id = ${d}`)},N=e=>{const E=a(e,t`SELECT MIN(CASE WHEN dead = 0 THEN next_attempt_at END) AS due, COUNT(*) AS total FROM ${t.identifier(o)}`).toArray()[0];return{dueAt:E?.due??void 0,populated:(E?.total??0)>0}},m=(e,d)=>{a(e,t`DELETE FROM ${t.identifier(o)} WHERE dead = 1 AND created_at < ${d}`)};export{o as SCHEDULE_OUTBOX_TABLE,c as deferScheduleOutbox,s as forgetScheduleOutbox,_ as migrateScheduleOutbox,O as parkScheduleOutbox,N as probeScheduleOutbox,u as readDueScheduleOutbox,p as recordScheduleOutbox,m as trimScheduleOutbox};
@@ -1 +1 @@
1
- import{createShardCtxDb as v}from"./NotUniqueError-BMom69SD.mjs";import{createRelayLink as I}from"./DEFAULT_MAX_RELAYS-Ng4SyJ7k.mjs";import{ConflictError as N}from"./ConflictError-C8GtJmjS.mjs";import{runShardMigrations as _}from"./runShardMigrations-CeT_SVrI.mjs";import{relayName as F}from"./DEFAULT_PROMOTION_THRESHOLDS-Bfx7KakS.mjs";const E=(C,m={})=>({_meta:{column:{notNull:!0,...m}},kind:C}),W=(C,m,O)=>{const{describe:S,expect:n,it:y}=O;S(`engine contract: ${C}`,()=>{S("optimistic concurrency",()=>{const b=u=>({tables:{items:{indexes:[],shape:{title:E("string"),version:E("number",{notNull:!1})},triggerMap:{clobber:{handler:()=>{u.exec(`UPDATE "items" SET "__doc__" = json_set("__doc__", '$.version', 99) WHERE "id" = 'i1'`)},op:"update",timing:"before"}}}}});y("raises a CONFLICT of kind `occ` when a write's snapshot is clobbered",async()=>{const{close:u,host:h}=m();try{const i=h.sql,l=b(i);_(i,l);const s=v({schema:l,sql:i});await s.insert("items",{_id:"i1",title:"first",version:1},{allowExplicitId:!0}),await n(s.patch("i1",{title:"second"})).rejects.toBeInstanceOf(N)}finally{u?.()}}),y("reports the conflict as CONFLICT/409 rather than retrying it away",async()=>{const{close:u,host:h}=m();try{const i=h.sql,l=b(i);_(i,l);const s=v({schema:l,sql:i});await s.insert("items",{_id:"i1",title:"first",version:1},{allowExplicitId:!0});let o;try{await s.patch("i1",{title:"second"})}catch(t){o=t}const e=o;n(e.code).toBe("CONFLICT"),n(e.kind).toBe("occ")}finally{u?.()}}),y("leaves the row readable and unchanged after a conflict",async()=>{const{close:u,host:h}=m();try{const i=h.sql,l=b(i);_(i,l);const s=v({schema:l,sql:i});await s.insert("items",{_id:"i1",title:"first",version:1},{allowExplicitId:!0});try{await s.patch("i1",{title:"second"})}catch{}const o=await s.get("i1");n(o?.title).toBe("first"),n(o?.version).toBe(99)}finally{u?.()}}),y("raises a CONFLICT of kind `trigger` when a trigger writes its own row through the db",async()=>{const{close:u,host:h}=m();try{const i=h.sql,l={tables:{items:{indexes:[],shape:{title:E("string"),version:E("number",{notNull:!1})},triggerMap:{recurse:{handler:async(t,a)=>{await t.db.patch(a.doc._id,{version:99})},op:"update",timing:"before"}}}}};_(i,l);const s=v({schema:l,sql:i});await s.insert("items",{_id:"i1",title:"first",version:1},{allowExplicitId:!0});let o;try{await s.patch("i1",{title:"second"})}catch(t){o=t}const e=o;n(e).toBeInstanceOf(N),n(e.code).toBe("CONFLICT"),n(e.kind).toBe("trigger")}finally{u?.()}})}),S("shape-poke ordering",()=>{const b="shard-a",u={args:{},name:"messages"},h=(e,t,a,r)=>e.accept(t?.()??{},{connectionId:a,shapes:{[r]:u}}),i=(e,t,a)=>{let r=0,d=0;const c=g=>()=>{throw new Error(`the relay poke path must not reach RelayHost.${g}`)},p={fetch:(g,q)=>{if(JSON.parse(q?.body??"{}").type!=="relay_shape_subscribe")return Promise.resolve(new Response(void 0,{status:204}));const B=a[d];if(d+=1,B===void 0)throw new Error("the relay asked for more seeds than this fixture supplies");return Promise.resolve(Response.json(B))}},k={get:()=>p,getByName:()=>p,idFromName:g=>g},w={buildShapeDiff:c("buildShapeDiff"),computeOpLogShapeSeed:c("computeOpLogShapeSeed"),currentCdcEpoch:c("currentCdcEpoch"),deliverWhisperLocal:c("deliverWhisperLocal"),doName:()=>F(b,0),env:()=>({SHARD:k}),getWebSockets:()=>e.getSockets(),maskMetadata:c("maskMetadata"),nextPokeId:()=>(r+=1,`poke-${String(r)}`),readAttachment:g=>g.deserializeAttachment?.(),recordShapePokeFanout:()=>{},resolveShape:c("resolveShape"),rlsMetadata:c("rlsMetadata"),shardBinding:()=>"SHARD",shardJurisdiction:()=>{},sql:()=>t},f=I(w);if(f===void 0)throw new Error("expected a relay link for a `…::relay::N` name");return f},l=e=>new Request("https://relay.internal/_lunora/relay",{body:JSON.stringify(e),headers:{"content-type":"application/json"},method:"POST"}),s=async(e,t,a)=>{const r=await e.seedRelayShape(t,a,u,{identity:void 0,userId:void 0});if(r!=="ok")throw new Error(`seed failed: ${JSON.stringify(r)}`)},o=(e={})=>l({...u,checkpoint:20,epoch:"e1",fromCursor:10,rowsPatch:[{id:"r1",op:"upsert",value:{title:"hello"}}],type:"relay_shape_poke",...e});y("frames a poke as pokeStart → pokePart per shape → pokeEnd, under one poke id",async()=>{const{close:e,createSocket:t,host:a,readFrames:r,sockets:d}=m();try{const c=i(d,a.sql,[{cursor:10,epoch:"e1",frames:[]}]),p=h(d,t,"c-alice","s1");await s(c,p,"s1"),await c.handleControl(o());const w=(await r(p)).map(f=>JSON.parse(f));n(w.map(f=>f.type)).toStrictEqual(["pokeStart","pokePart","pokeEnd"]),n(new Set(w.map(f=>f.pokeId)).size).toBe(1),n(w[1]?.shapeId).toBe("s1"),n(w[2]?.checkpoint).toBe(20)}finally{e?.()}}),y("delivers a poke only to sockets whose cursor matches, and advances them past it",async()=>{const{close:e,createSocket:t,host:a,readFrames:r,sockets:d}=m();try{const c=i(d,a.sql,[{cursor:10,epoch:"e1",frames:[]},{cursor:7,epoch:"e1",frames:[]}]),p=h(d,t,"c-alice","s1"),k=h(d,t,"c-bob","s2");await s(c,p,"s1"),await s(c,k,"s2"),await c.handleControl(o());const w=await r(p);n(w.length).toBe(3);const f=await r(k);n(f.length).toBe(0),await c.handleControl(o());const g=await r(p);n(g.length).toBe(3)}finally{e?.()}}),y("skips a socket whose cursor matches under a different CDC epoch",async()=>{const{close:e,createSocket:t,host:a,readFrames:r,sockets:d}=m();try{const c=i(d,a.sql,[{cursor:10,epoch:"e1",frames:[]}]),p=h(d,t,"c-alice","s1");await s(c,p,"s1"),await c.handleControl(o({epoch:"e2"}));const k=await r(p);n(k.length).toBe(0),await c.handleControl(o());const w=await r(p);n(w.length).toBe(3)}finally{e?.()}})}),S("RLS identity under live subscription",()=>{const b="shard-a",u={args:{},name:"lobby-messages"},h={args:{},name:"my-orders"},i=s=>{const o=[],e=[],t={fetch:(d,c)=>(o.push(JSON.parse(c?.body??"{}")),Promise.resolve(new Response(void 0,{status:204})))},r=I({buildShapeDiff:()=>[{id:"r1",op:"upsert",value:{}}],computeOpLogShapeSeed:()=>({baseCheckpoint:void 0,cursor:10,epoch:"e1",reset:!0,rowsPatch:[]}),currentCdcEpoch:()=>"e1",deliverWhisperLocal:()=>0,doName:()=>b,env:()=>({SHARD:{get:()=>t,getByName:()=>t,idFromName:d=>d}}),getWebSockets:()=>[],maskMetadata:()=>({columns:[]}),nextPokeId:()=>"poke-1",readAttachment:()=>({}),recordShapePokeFanout:()=>{},resolveShape:(d,c,p)=>(e.push(p),d===h.name?{columns:["id"],effectiveWhere:{org:p?.identity?.org??"anonymous"},global:!1,table:"orders"}:{columns:["id"],effectiveWhere:{room:"lobby"},global:!1,table:"messages"}),rlsMetadata:()=>({policies:[]}),shardBinding:()=>"SHARD",shardJurisdiction:()=>{},sql:()=>s});if(r===void 0)throw new Error("expected an owner link for an un-suffixed DO name");return{owner:r,posts:o,resolvedUnder:e}},l=async(s,o)=>{await s.handleControl(new Request("https://owner.internal/_lunora/relay",{body:JSON.stringify({...o,connectionId:"c-alice",identity:{org:"acme"},relayIndex:0,subId:"s1",type:"relay_shape_subscribe",userId:"u1"}),headers:{"content-type":"application/json"},method:"POST"}))};y("seeds a subscriber under its own forwarded identity, never the anonymous one",async()=>{const{close:s,host:o}=m();try{const{owner:e,resolvedUnder:t}=i(o.sql);await l(e,h),n(t.some(a=>a?.userId==="u1"&&a.identity?.org==="acme")).toBe(!0)}finally{s?.()}}),y("routes an identity-scoped shape to a per-socket poke, not the cohort multicast",async()=>{const{close:s,host:o}=m();try{const{owner:e,posts:t}=i(o.sql);await l(e,h),t.length=0,await e.onFlush(new Set(["orders"]),20);const a=t.filter(r=>r.type==="relay_shape_poke");n(a.length).toBe(1),n(a[0]?.targetConnectionId).toBe("c-alice")}finally{s?.()}}),y("still multicasts an identity-blind shape to the whole cohort",async()=>{const{close:s,host:o}=m();try{const{owner:e,posts:t}=i(o.sql);await l(e,u),t.length=0,await e.onFlush(new Set(["messages"]),20);const a=t.filter(r=>r.type==="relay_shape_poke");n(a.length).toBe(1),n(a[0]?.targetConnectionId).toBeUndefined()}finally{s?.()}})})})};export{W as defineEngineContractSuite};
1
+ import{createShardCtxDb as v}from"./NotUniqueError-BA2p0rlT.mjs";import{createRelayLink as I}from"./DEFAULT_MAX_RELAYS-Ng4SyJ7k.mjs";import{ConflictError as N}from"./ConflictError-C8GtJmjS.mjs";import{runShardMigrations as _}from"./runShardMigrations-DNFOFJe-.mjs";import{relayName as F}from"./DEFAULT_PROMOTION_THRESHOLDS-Bfx7KakS.mjs";const E=(C,m={})=>({_meta:{column:{notNull:!0,...m}},kind:C}),W=(C,m,O)=>{const{describe:S,expect:n,it:y}=O;S(`engine contract: ${C}`,()=>{S("optimistic concurrency",()=>{const b=u=>({tables:{items:{indexes:[],shape:{title:E("string"),version:E("number",{notNull:!1})},triggerMap:{clobber:{handler:()=>{u.exec(`UPDATE "items" SET "__doc__" = json_set("__doc__", '$.version', 99) WHERE "id" = 'i1'`)},op:"update",timing:"before"}}}}});y("raises a CONFLICT of kind `occ` when a write's snapshot is clobbered",async()=>{const{close:u,host:h}=m();try{const i=h.sql,l=b(i);_(i,l);const s=v({schema:l,sql:i});await s.insert("items",{_id:"i1",title:"first",version:1},{allowExplicitId:!0}),await n(s.patch("i1",{title:"second"})).rejects.toBeInstanceOf(N)}finally{u?.()}}),y("reports the conflict as CONFLICT/409 rather than retrying it away",async()=>{const{close:u,host:h}=m();try{const i=h.sql,l=b(i);_(i,l);const s=v({schema:l,sql:i});await s.insert("items",{_id:"i1",title:"first",version:1},{allowExplicitId:!0});let o;try{await s.patch("i1",{title:"second"})}catch(t){o=t}const e=o;n(e.code).toBe("CONFLICT"),n(e.kind).toBe("occ")}finally{u?.()}}),y("leaves the row readable and unchanged after a conflict",async()=>{const{close:u,host:h}=m();try{const i=h.sql,l=b(i);_(i,l);const s=v({schema:l,sql:i});await s.insert("items",{_id:"i1",title:"first",version:1},{allowExplicitId:!0});try{await s.patch("i1",{title:"second"})}catch{}const o=await s.get("i1");n(o?.title).toBe("first"),n(o?.version).toBe(99)}finally{u?.()}}),y("raises a CONFLICT of kind `trigger` when a trigger writes its own row through the db",async()=>{const{close:u,host:h}=m();try{const i=h.sql,l={tables:{items:{indexes:[],shape:{title:E("string"),version:E("number",{notNull:!1})},triggerMap:{recurse:{handler:async(t,a)=>{await t.db.patch(a.doc._id,{version:99})},op:"update",timing:"before"}}}}};_(i,l);const s=v({schema:l,sql:i});await s.insert("items",{_id:"i1",title:"first",version:1},{allowExplicitId:!0});let o;try{await s.patch("i1",{title:"second"})}catch(t){o=t}const e=o;n(e).toBeInstanceOf(N),n(e.code).toBe("CONFLICT"),n(e.kind).toBe("trigger")}finally{u?.()}})}),S("shape-poke ordering",()=>{const b="shard-a",u={args:{},name:"messages"},h=(e,t,a,r)=>e.accept(t?.()??{},{connectionId:a,shapes:{[r]:u}}),i=(e,t,a)=>{let r=0,d=0;const c=g=>()=>{throw new Error(`the relay poke path must not reach RelayHost.${g}`)},p={fetch:(g,q)=>{if(JSON.parse(q?.body??"{}").type!=="relay_shape_subscribe")return Promise.resolve(new Response(void 0,{status:204}));const B=a[d];if(d+=1,B===void 0)throw new Error("the relay asked for more seeds than this fixture supplies");return Promise.resolve(Response.json(B))}},k={get:()=>p,getByName:()=>p,idFromName:g=>g},w={buildShapeDiff:c("buildShapeDiff"),computeOpLogShapeSeed:c("computeOpLogShapeSeed"),currentCdcEpoch:c("currentCdcEpoch"),deliverWhisperLocal:c("deliverWhisperLocal"),doName:()=>F(b,0),env:()=>({SHARD:k}),getWebSockets:()=>e.getSockets(),maskMetadata:c("maskMetadata"),nextPokeId:()=>(r+=1,`poke-${String(r)}`),readAttachment:g=>g.deserializeAttachment?.(),recordShapePokeFanout:()=>{},resolveShape:c("resolveShape"),rlsMetadata:c("rlsMetadata"),shardBinding:()=>"SHARD",shardJurisdiction:()=>{},sql:()=>t},f=I(w);if(f===void 0)throw new Error("expected a relay link for a `…::relay::N` name");return f},l=e=>new Request("https://relay.internal/_lunora/relay",{body:JSON.stringify(e),headers:{"content-type":"application/json"},method:"POST"}),s=async(e,t,a)=>{const r=await e.seedRelayShape(t,a,u,{identity:void 0,userId:void 0});if(r!=="ok")throw new Error(`seed failed: ${JSON.stringify(r)}`)},o=(e={})=>l({...u,checkpoint:20,epoch:"e1",fromCursor:10,rowsPatch:[{id:"r1",op:"upsert",value:{title:"hello"}}],type:"relay_shape_poke",...e});y("frames a poke as pokeStart → pokePart per shape → pokeEnd, under one poke id",async()=>{const{close:e,createSocket:t,host:a,readFrames:r,sockets:d}=m();try{const c=i(d,a.sql,[{cursor:10,epoch:"e1",frames:[]}]),p=h(d,t,"c-alice","s1");await s(c,p,"s1"),await c.handleControl(o());const w=(await r(p)).map(f=>JSON.parse(f));n(w.map(f=>f.type)).toStrictEqual(["pokeStart","pokePart","pokeEnd"]),n(new Set(w.map(f=>f.pokeId)).size).toBe(1),n(w[1]?.shapeId).toBe("s1"),n(w[2]?.checkpoint).toBe(20)}finally{e?.()}}),y("delivers a poke only to sockets whose cursor matches, and advances them past it",async()=>{const{close:e,createSocket:t,host:a,readFrames:r,sockets:d}=m();try{const c=i(d,a.sql,[{cursor:10,epoch:"e1",frames:[]},{cursor:7,epoch:"e1",frames:[]}]),p=h(d,t,"c-alice","s1"),k=h(d,t,"c-bob","s2");await s(c,p,"s1"),await s(c,k,"s2"),await c.handleControl(o());const w=await r(p);n(w.length).toBe(3);const f=await r(k);n(f.length).toBe(0),await c.handleControl(o());const g=await r(p);n(g.length).toBe(3)}finally{e?.()}}),y("skips a socket whose cursor matches under a different CDC epoch",async()=>{const{close:e,createSocket:t,host:a,readFrames:r,sockets:d}=m();try{const c=i(d,a.sql,[{cursor:10,epoch:"e1",frames:[]}]),p=h(d,t,"c-alice","s1");await s(c,p,"s1"),await c.handleControl(o({epoch:"e2"}));const k=await r(p);n(k.length).toBe(0),await c.handleControl(o());const w=await r(p);n(w.length).toBe(3)}finally{e?.()}})}),S("RLS identity under live subscription",()=>{const b="shard-a",u={args:{},name:"lobby-messages"},h={args:{},name:"my-orders"},i=s=>{const o=[],e=[],t={fetch:(d,c)=>(o.push(JSON.parse(c?.body??"{}")),Promise.resolve(new Response(void 0,{status:204})))},r=I({buildShapeDiff:()=>[{id:"r1",op:"upsert",value:{}}],computeOpLogShapeSeed:()=>({baseCheckpoint:void 0,cursor:10,epoch:"e1",reset:!0,rowsPatch:[]}),currentCdcEpoch:()=>"e1",deliverWhisperLocal:()=>0,doName:()=>b,env:()=>({SHARD:{get:()=>t,getByName:()=>t,idFromName:d=>d}}),getWebSockets:()=>[],maskMetadata:()=>({columns:[]}),nextPokeId:()=>"poke-1",readAttachment:()=>({}),recordShapePokeFanout:()=>{},resolveShape:(d,c,p)=>(e.push(p),d===h.name?{columns:["id"],effectiveWhere:{org:p?.identity?.org??"anonymous"},global:!1,table:"orders"}:{columns:["id"],effectiveWhere:{room:"lobby"},global:!1,table:"messages"}),rlsMetadata:()=>({policies:[]}),shardBinding:()=>"SHARD",shardJurisdiction:()=>{},sql:()=>s});if(r===void 0)throw new Error("expected an owner link for an un-suffixed DO name");return{owner:r,posts:o,resolvedUnder:e}},l=async(s,o)=>{await s.handleControl(new Request("https://owner.internal/_lunora/relay",{body:JSON.stringify({...o,connectionId:"c-alice",identity:{org:"acme"},relayIndex:0,subId:"s1",type:"relay_shape_subscribe",userId:"u1"}),headers:{"content-type":"application/json"},method:"POST"}))};y("seeds a subscriber under its own forwarded identity, never the anonymous one",async()=>{const{close:s,host:o}=m();try{const{owner:e,resolvedUnder:t}=i(o.sql);await l(e,h),n(t.some(a=>a?.userId==="u1"&&a.identity?.org==="acme")).toBe(!0)}finally{s?.()}}),y("routes an identity-scoped shape to a per-socket poke, not the cohort multicast",async()=>{const{close:s,host:o}=m();try{const{owner:e,posts:t}=i(o.sql);await l(e,h),t.length=0,await e.onFlush(new Set(["orders"]),20);const a=t.filter(r=>r.type==="relay_shape_poke");n(a.length).toBe(1),n(a[0]?.targetConnectionId).toBe("c-alice")}finally{s?.()}}),y("still multicasts an identity-blind shape to the whole cohort",async()=>{const{close:s,host:o}=m();try{const{owner:e,posts:t}=i(o.sql);await l(e,u),t.length=0,await e.onFlush(new Set(["messages"]),20);const a=t.filter(r=>r.type==="relay_shape_poke");n(a.length).toBe(1),n(a[0]?.targetConnectionId).toBeUndefined()}finally{s?.()}})})})};export{W as defineEngineContractSuite};
@@ -0,0 +1,5 @@
1
+ import{LunoraError as p}from"@lunora/errors";import{S as L,y as N,l as h}from"./ctx-db-companions-w-CfeOda.mjs";import{sql as e}from"drizzle-orm";import{aggregateTableName as l}from"./aggregateTableName-C7o-gpms.mjs";import{backfillSearchIndexesForTable as R}from"./backfillAggregateIndexes-BG5-SC1q.mjs";import{migrateCdcLog as O,migrateCdcMeta as x}from"./CDC_LOG_TABLE-vVheEulD.mjs";import{migrateClientWatermark as C}from"./CLIENT_WATERMARK_TABLE-CRnrAnJ2.mjs";import{migrateCommitSeq as $}from"./COMMIT_SEQ_FIELD-BUdOMG5y.mjs";import{migrateGlobalShapeSnapshot as U}from"./GLOBAL_SHAPE_SNAPSHOT_TABLE-DSA6mzyx.mjs";import{migrateIdempotency as b}from"./IDEMPOTENCY_TABLE-DOpm_oMF.mjs";import{m as D}from"./ctx-db-relay-shapes-Bg5YYnmN.mjs";import{migrateScheduleOutbox as X}from"./SCHEDULE_OUTBOX_TABLE-CD_UjYVx.mjs";import{m as G}from"./ctx-db-search-state-ruTuCsxa.mjs";import{migrateShapePokeCursor as M}from"./SHAPE_POKE_CURSOR_TABLE-ByJVDHds.mjs";import{runDrizzle as a}from"./runDrizzle-2ULFQR_k.mjs";import{D as F,d as E,e as g,t as B,i as y,g as Y,a as k,b as v,A as u}from"./do-sql-Dvj8Yl5N.mjs";import{renderSql as P}from"./param-DlozcSQu.mjs";import{migrateDurableStreams as w}from"./appendStreamChunk-C1Ok4b6J.mjs";import{rankTableName as j,sortColumnName as K}from"./RANK_TIEBREAK-BXDiMmkH.mjs";import{migrateReactorState as V}from"./REACTOR_STATE_TABLE-QPRFyxMS.mjs";import{recordSchemaVersion as H}from"./SCHEMA_HISTORY_MAX_VERSIONS-BluIj2s-.mjs";const S=e`_creationTime, id`,W=(i,o,n,r,t,s)=>{const f=a(i,e`SELECT sql FROM sqlite_master WHERE type = 'index' AND name = ${o} AND tbl_name = ${n}`).toArray()[0]?.sql;if(f==null)return;const m=c=>{const I=c.indexOf("(");return I===-1?void 0:c.slice(I,c.lastIndexOf(")")+1)},T=m(P("sqlite",E(o,n,r,t)).sql),_=m(f);if(!(T===void 0||_===void 0||T===_)){if(t){const c=e.join(s.map(A=>e`${A} IS NOT NULL`),e` AND `);if(a(i,e`SELECT 1 FROM ${e.identifier(n)} WHERE ${c} GROUP BY ${r} HAVING COUNT(*) > 1 LIMIT 1`).toArray().length>0)throw new p("INTERNAL",`unique index "${o}" on "${n}" cannot be re-created with its new column list: existing rows are duplicates under it. De-duplicate the table with a data migration first; the previous index is left in place.`)}a(i,e`DROP INDEX IF EXISTS ${e.identifier(o)}`)}},z=(i,o,n)=>{for(const r of n.indexes){const t=`${o}_${r.name}`,s=r.unique??!1,d=r.fields.map(T=>g(T)),f=e.join(d,e`, `),m=s?f:e`${f}, ${S}`;W(i,t,o,m,s,d),a(i,E(t,o,m,s))}for(const[r,t]of B(n)){if(!t.unique)continue;const s=`${o}_unique_${r}`;a(i,E(s,o,g(r),!0))}},J=(i,o,n)=>{if(!(!n.searchIndexes||n.searchIndexes.length===0||!y(i))){for(const r of n.searchIndexes){const t=L(o,r.name);a(i,e`CREATE VIRTUAL TABLE IF NOT EXISTS ${e.identifier(t)} USING fts5(${e.identifier(N)}, ${e.identifier(h)} UNINDEXED)`),a(i,e`CREATE VIRTUAL TABLE IF NOT EXISTS ${e.identifier(`${t}__vocab`)} USING fts5vocab(${e.identifier(t)}, ${e.raw("instance")})`)}R(i,o,n)}},Q=(i,o,n)=>{if(n.geoIndexes)for(const r of n.geoIndexes){const t=Y(o,r.name);a(i,e`CREATE TABLE IF NOT EXISTS ${e.identifier(t)} (${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=`${o}__geo_${r.name}__btree`;a(i,E(s,t,e`${e.identifier("__geohash__")} ASC, ${e.identifier("__id__")} ASC`,!1))}},Z=(i,o,n)=>{if(n.aggregateIndexes)for(const r of n.aggregateIndexes){const t=l(o,r.name);a(i,e`CREATE TABLE IF NOT EXISTS ${e.identifier(t)} (${k} TEXT PRIMARY KEY, ${v} REAL, ${u} INTEGER NOT NULL DEFAULT 0)`),a(i,e`PRAGMA table_info(${e.identifier(t)})`).toArray().some(d=>d.name==="__count__")||a(i,e`ALTER TABLE ${e.identifier(t)} ADD COLUMN ${u} INTEGER NOT NULL DEFAULT 0`)}},q=(i,o,n)=>{if(n.rankIndexes)for(const r of n.rankIndexes){const t=j(o,r.name),s=r.sortBy.map((_,c)=>K(c)),d=s.map(_=>e`${e.identifier(_)} BLOB`),f=d.length>0?e`, ${e.join(d,e`, `)}`:e``;a(i,e`CREATE TABLE IF NOT EXISTS ${e.identifier(t)} (${e.identifier("__id__")} TEXT PRIMARY KEY, ${e.identifier("__partition__")} TEXT NOT NULL${f})`);const m=[e`${e.identifier("__partition__")} ASC`];for(const[_,c]of s.entries()){const I=r.sortBy[_]?.direction;m.push(e`${e.identifier(c)} ${e.raw(I==="desc"?"DESC":"ASC")}`)}m.push(e`${e.identifier("__id__")} ASC`);const T=`${o}__rank_${r.name}__btree`;a(i,E(T,t,e.join(m,e`, `),!1))}},Le=(i,o,n={})=>{n.schemaSnapshot!==void 0&&H(i,n.schemaSnapshot.hash,n.schemaSnapshot.json),G(i);for(const[r,t]of Object.entries(o.tables))t.shardMode?.kind!=="global"&&(a(i,e`CREATE TABLE IF NOT EXISTS ${e.identifier(r)} (
2
+ id TEXT PRIMARY KEY,
3
+ _creationTime REAL NOT NULL,
4
+ ${e.identifier(F)} TEXT NOT NULL
5
+ )`),a(i,E(`${r}__by_creation`,r,S,!1)),z(i,r,t),J(i,r,t),Q(i,r,t),Z(i,r,t),q(i,r,t));n.cdc&&(O(i),x(i),C(i),M(i),D(i)),Object.values(o.tables).some(r=>r.commitOrderedMode===!0)&&$(i),V(i),b(i),X(i),U(i),w(i)};export{Le as runShardMigrations};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@lunora/shard-engine",
3
- "version": "1.0.0-alpha.66",
3
+ "version": "1.0.0-alpha.68",
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",
@@ -49,7 +49,7 @@
49
49
  },
50
50
  "dependencies": {
51
51
  "@lunora/errors": "1.0.0-alpha.36",
52
- "@lunora/platform": "1.0.0-alpha.31",
52
+ "@lunora/platform": "1.0.0-alpha.32",
53
53
  "drizzle-orm": "^0.45.2"
54
54
  },
55
55
  "engines": {
@@ -1,5 +0,0 @@
1
- import{LunoraError as p}from"@lunora/errors";import{S as L,y as N,l as h}from"./ctx-db-companions-w-CfeOda.mjs";import{sql as e}from"drizzle-orm";import{aggregateTableName as l}from"./aggregateTableName-C7o-gpms.mjs";import{backfillSearchIndexesForTable as R}from"./backfillAggregateIndexes-BG5-SC1q.mjs";import{migrateCdcLog as O,migrateCdcMeta as x}from"./CDC_LOG_TABLE-vVheEulD.mjs";import{migrateClientWatermark as C}from"./CLIENT_WATERMARK_TABLE-CRnrAnJ2.mjs";import{migrateCommitSeq as $}from"./COMMIT_SEQ_FIELD-BUdOMG5y.mjs";import{migrateGlobalShapeSnapshot as U}from"./GLOBAL_SHAPE_SNAPSHOT_TABLE-DSA6mzyx.mjs";import{migrateIdempotency as b}from"./IDEMPOTENCY_TABLE-DOpm_oMF.mjs";import{m as D}from"./ctx-db-relay-shapes-Bg5YYnmN.mjs";import{m as X}from"./ctx-db-search-state-ruTuCsxa.mjs";import{migrateShapePokeCursor as G}from"./SHAPE_POKE_CURSOR_TABLE-ByJVDHds.mjs";import{runDrizzle as a}from"./runDrizzle-2ULFQR_k.mjs";import{D as M,d as E,e as g,t as F,i as B,g as y,a as Y,b as k,A as u}from"./do-sql-Dvj8Yl5N.mjs";import{renderSql as v}from"./param-DlozcSQu.mjs";import{migrateDurableStreams as P}from"./appendStreamChunk-C1Ok4b6J.mjs";import{rankTableName as w,sortColumnName as j}from"./RANK_TIEBREAK-BXDiMmkH.mjs";import{migrateReactorState as K}from"./REACTOR_STATE_TABLE-QPRFyxMS.mjs";import{recordSchemaVersion as V}from"./SCHEMA_HISTORY_MAX_VERSIONS-BluIj2s-.mjs";const A=e`_creationTime, id`,H=(i,o,n,r,t,s)=>{const f=a(i,e`SELECT sql FROM sqlite_master WHERE type = 'index' AND name = ${o} AND tbl_name = ${n}`).toArray()[0]?.sql;if(f==null)return;const m=c=>{const I=c.indexOf("(");return I===-1?void 0:c.slice(I,c.lastIndexOf(")")+1)},T=m(v("sqlite",E(o,n,r,t)).sql),_=m(f);if(!(T===void 0||_===void 0||T===_)){if(t){const c=e.join(s.map(S=>e`${S} IS NOT NULL`),e` AND `);if(a(i,e`SELECT 1 FROM ${e.identifier(n)} WHERE ${c} GROUP BY ${r} HAVING COUNT(*) > 1 LIMIT 1`).toArray().length>0)throw new p("INTERNAL",`unique index "${o}" on "${n}" cannot be re-created with its new column list: existing rows are duplicates under it. De-duplicate the table with a data migration first; the previous index is left in place.`)}a(i,e`DROP INDEX IF EXISTS ${e.identifier(o)}`)}},W=(i,o,n)=>{for(const r of n.indexes){const t=`${o}_${r.name}`,s=r.unique??!1,d=r.fields.map(T=>g(T)),f=e.join(d,e`, `),m=s?f:e`${f}, ${A}`;H(i,t,o,m,s,d),a(i,E(t,o,m,s))}for(const[r,t]of F(n)){if(!t.unique)continue;const s=`${o}_unique_${r}`;a(i,E(s,o,g(r),!0))}},z=(i,o,n)=>{if(!(!n.searchIndexes||n.searchIndexes.length===0||!B(i))){for(const r of n.searchIndexes){const t=L(o,r.name);a(i,e`CREATE VIRTUAL TABLE IF NOT EXISTS ${e.identifier(t)} USING fts5(${e.identifier(N)}, ${e.identifier(h)} UNINDEXED)`),a(i,e`CREATE VIRTUAL TABLE IF NOT EXISTS ${e.identifier(`${t}__vocab`)} USING fts5vocab(${e.identifier(t)}, ${e.raw("instance")})`)}R(i,o,n)}},J=(i,o,n)=>{if(n.geoIndexes)for(const r of n.geoIndexes){const t=y(o,r.name);a(i,e`CREATE TABLE IF NOT EXISTS ${e.identifier(t)} (${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=`${o}__geo_${r.name}__btree`;a(i,E(s,t,e`${e.identifier("__geohash__")} ASC, ${e.identifier("__id__")} ASC`,!1))}},Q=(i,o,n)=>{if(n.aggregateIndexes)for(const r of n.aggregateIndexes){const t=l(o,r.name);a(i,e`CREATE TABLE IF NOT EXISTS ${e.identifier(t)} (${Y} TEXT PRIMARY KEY, ${k} REAL, ${u} INTEGER NOT NULL DEFAULT 0)`),a(i,e`PRAGMA table_info(${e.identifier(t)})`).toArray().some(d=>d.name==="__count__")||a(i,e`ALTER TABLE ${e.identifier(t)} ADD COLUMN ${u} INTEGER NOT NULL DEFAULT 0`)}},Z=(i,o,n)=>{if(n.rankIndexes)for(const r of n.rankIndexes){const t=w(o,r.name),s=r.sortBy.map((_,c)=>j(c)),d=s.map(_=>e`${e.identifier(_)} BLOB`),f=d.length>0?e`, ${e.join(d,e`, `)}`:e``;a(i,e`CREATE TABLE IF NOT EXISTS ${e.identifier(t)} (${e.identifier("__id__")} TEXT PRIMARY KEY, ${e.identifier("__partition__")} TEXT NOT NULL${f})`);const m=[e`${e.identifier("__partition__")} ASC`];for(const[_,c]of s.entries()){const I=r.sortBy[_]?.direction;m.push(e`${e.identifier(c)} ${e.raw(I==="desc"?"DESC":"ASC")}`)}m.push(e`${e.identifier("__id__")} ASC`);const T=`${o}__rank_${r.name}__btree`;a(i,E(T,t,e.join(m,e`, `),!1))}},Se=(i,o,n={})=>{n.schemaSnapshot!==void 0&&V(i,n.schemaSnapshot.hash,n.schemaSnapshot.json),X(i);for(const[r,t]of Object.entries(o.tables))t.shardMode?.kind!=="global"&&(a(i,e`CREATE TABLE IF NOT EXISTS ${e.identifier(r)} (
2
- id TEXT PRIMARY KEY,
3
- _creationTime REAL NOT NULL,
4
- ${e.identifier(M)} TEXT NOT NULL
5
- )`),a(i,E(`${r}__by_creation`,r,A,!1)),W(i,r,t),z(i,r,t),J(i,r,t),Q(i,r,t),Z(i,r,t));n.cdc&&(O(i),x(i),C(i),G(i),D(i)),Object.values(o.tables).some(r=>r.commitOrderedMode===!0)&&$(i),K(i),b(i),U(i),P(i)};export{Se as runShardMigrations};