@lunora/shard-engine 1.0.0-alpha.156 → 1.0.0-alpha.158
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.
- package/dist/conformance/index.mjs +1 -1
- package/dist/index.d.mts +12 -3
- package/dist/index.d.ts +12 -3
- package/dist/index.mjs +1 -1
- package/dist/packem_shared/CompanionMemo-BXU5vfak.mjs +1 -0
- package/dist/packem_shared/{DEFAULT_MAX_RELATION_KEYS-BeTWZQ4X.mjs → DEFAULT_MAX_RELATION_KEYS-9eOkadE4.mjs} +1 -1
- package/dist/packem_shared/NotUniqueError-C8ZpTDHV.mjs +1 -0
- package/dist/packem_shared/{VECTOR_BACKFILL_MAX_PAGES-zxItOlPE.mjs → VECTOR_BACKFILL_MAX_PAGES-loOUGfzw.mjs} +1 -1
- package/dist/packem_shared/applyInsertDefaults-B0NXPs2x.mjs +1 -0
- package/dist/packem_shared/{backfillAggregateIndexes-DSplGrR_.mjs → backfillAggregateIndexes-BN0NwXQk.mjs} +1 -1
- package/dist/packem_shared/createCompanionSync-zIF_F4oD.mjs +1 -0
- package/dist/packem_shared/{defineEngineContractSuite-LOthxP0i.mjs → defineEngineContractSuite-Ba9llgfb.mjs} +1 -1
- package/dist/packem_shared/runShardMigrations-DsrVE2Kq.mjs +5 -0
- package/package.json +2 -2
- package/dist/packem_shared/NotUniqueError-UjpHasAz.mjs +0 -1
- package/dist/packem_shared/applyInsertDefaults-vVfUyiJ2.mjs +0 -1
- package/dist/packem_shared/clearCompanionSignatures-3MlVqWZD.mjs +0 -1
- package/dist/packem_shared/createCompanionSync-BMS8yYTx.mjs +0 -1
- package/dist/packem_shared/runShardMigrations-vtuywDTg.mjs +0 -5
|
@@ -1 +1 @@
|
|
|
1
|
-
import{defineEngineContractSuite as t}from"../packem_shared/defineEngineContractSuite-
|
|
1
|
+
import{defineEngineContractSuite as t}from"../packem_shared/defineEngineContractSuite-Ba9llgfb.mjs";export{t as defineEngineContractSuite};
|
package/dist/index.d.mts
CHANGED
|
@@ -772,6 +772,11 @@ declare const selectIndexForGroupBy: (indexes: ReadonlyArray<AggregateIndexDefin
|
|
|
772
772
|
index: AggregateIndexDefinitionLike;
|
|
773
773
|
partial: Record<string, unknown>;
|
|
774
774
|
};
|
|
775
|
+
declare const clearCompanionSignatures: (sql: SqlExec) => void;
|
|
776
|
+
declare class CompanionMemo {
|
|
777
|
+
readonly verified: Set<string>;
|
|
778
|
+
invalidate(): void;
|
|
779
|
+
}
|
|
775
780
|
interface CacheEntry {
|
|
776
781
|
bytes: number;
|
|
777
782
|
deps: Set<string>;
|
|
@@ -968,6 +973,7 @@ interface CtxDbOptions {
|
|
|
968
973
|
cache?: ReactiveCache;
|
|
969
974
|
cdc?: boolean;
|
|
970
975
|
clock?: Clock;
|
|
976
|
+
companionMemo?: CompanionMemo;
|
|
971
977
|
enforceRls?: boolean;
|
|
972
978
|
globalDb?: DatabaseWriterLike;
|
|
973
979
|
headroom?: TransactionHeadroomTracker;
|
|
@@ -1036,7 +1042,6 @@ declare const COMMIT_SEQ_FIELD = "_commitSeq";
|
|
|
1036
1042
|
declare const migrateCommitSeq: (sql: SqlExec) => void;
|
|
1037
1043
|
declare const readCommitSeq: (sql: SqlExec) => number;
|
|
1038
1044
|
declare const allocateCommitSeq: (sql: SqlExec) => number;
|
|
1039
|
-
declare const clearCompanionSignatures: (sql: SqlExec) => void;
|
|
1040
1045
|
interface CompanionSyncDeps {
|
|
1041
1046
|
broadcast: (delta: MutationDelta) => void;
|
|
1042
1047
|
indexKeysFor: (table: string, document?: Record<string, unknown>) => ReadonlyArray<{
|
|
@@ -1047,6 +1052,7 @@ interface CompanionSyncDeps {
|
|
|
1047
1052
|
recordCdc: (table: string, id: string, op: "delete" | "insert" | "update", doc?: Record<string, unknown>) => void;
|
|
1048
1053
|
schema: SchemaLike;
|
|
1049
1054
|
sql: SqlExec;
|
|
1055
|
+
verified?: Set<string>;
|
|
1050
1056
|
}
|
|
1051
1057
|
interface CompanionSync {
|
|
1052
1058
|
ensureBackfilledForTable: (tableName: string) => void;
|
|
@@ -2149,7 +2155,10 @@ declare const resolveWith: (options: ResolveWithOptions) => Promise<void>;
|
|
|
2149
2155
|
interface ApplyOnDeleteOptions {
|
|
2150
2156
|
deletedId: string;
|
|
2151
2157
|
deletedReference: (references: string) => unknown;
|
|
2152
|
-
findHolders: (holderTable: string, field: string, value: unknown
|
|
2158
|
+
findHolders: (holderTable: string, field: string, value: unknown, page: {
|
|
2159
|
+
limit: number;
|
|
2160
|
+
select?: ReadonlyArray<string>;
|
|
2161
|
+
}) => Promise<Record<string, unknown>[]>;
|
|
2153
2162
|
onCascade: (holderTable: string, id: string) => Promise<void>;
|
|
2154
2163
|
onRestrict: (message: string) => never;
|
|
2155
2164
|
onSetNull: (holderTable: string, id: string, field: string) => Promise<void>;
|
|
@@ -2703,4 +2712,4 @@ declare const backfillVectorIndexes: (sql: SqlExec, targets: ReadonlyArray<Vecto
|
|
|
2703
2712
|
ordered: OrderedAfterWrites;
|
|
2704
2713
|
restart?: boolean;
|
|
2705
2714
|
}) => Promise<VectorBackfillProgress>;
|
|
2706
|
-
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, 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 FtsWriteOptions, 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 KeyedRelationWriteInfo, type LifecycleDispatchInfo, type LifecycleEvent, type LiveSocketControlCall, 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 NullPlacement, type OnDeleteActionLike, type OrderByClause, type OrderByInput, type OrderKey, type OrderKeyConstraints, OwnerRelay, type OwnerRelayFrame, type PaginationOptions, type PatchVerifier, type PatchWriteOptions, type PitrBookmarkResult, type PitrRestoreArgs, type PitrRestoreResult, type PitrStorage, type PokeFrameMeta, type PromotionState, type PromotionThresholds, QUEUE_TABLE, type QueryArgs, type QueryPage, type QueryPlan, 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, RELAY_SIGNATURE_HEADER, REPROJECTION_MIGRATION_PREFIX, RLS_UNWRAP_SYMBOL, type RangeOperandType, 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 RelationWriteInfo, type RelationWriteMap, type RelayAttach, type RelayDetach, type RelayFrame, type RelayHost, RelayMember, type RelayPokeDelivery, type RelayRoomEvent, type RelayRoomVerdict, 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 ThroughRelationWriteInfo, type TransactionHeadroom, TransactionHeadroomTracker, type TransactionLimits, type TransactionSqlLike, type TriggerContextLike, type TriggerDefinitionLike, type TriggerEventLike, type TriggerOpLike, type TriggerTimingLike, type TtlSweepSpec, UNVOUCHABLE_DEP, VECTOR_BACKFILL_MAX_PAGES, type ValidatorLike, type VectorBackfillProgress, WORKERD_SQLITE_LIMITS, type WhereFilter, 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, applyInsertDefaults, applyOnDelete, applySelect, archiveCdcSegment, armRestore, assertFlatPredicate, assertNoExplicitUndefined, assertPatchAllowed, assertReadonly, assertShapeShardable, assertStorableRowId, assertValidClientId, awaitWsDrain, backfillAggregateIndexes, backfillRankIndexes, backfillSearchIndexes, backfillSearchIndexesForTable, backfillVectorIndexes, bigintSqlKey, boundingBoxCenter, boundingBoxGeohashes, buildIndexRange, buildPokeFrames, buildReprojectionMigration, buildSeekBeforeWhere, buildSeekWhere, buildSettings, buildShapeDiff, bumpCdcEpoch, cdcArchiveRewound, cdcCanVouchFor, cdcForkedError, cdcSeqLeavingRows, cdcTouchesTables, cdcTrimmedError, claimStreamRun, clampPromotionThresholds, clearCapturedMail, clearCompanionSignatures, clearMemoryTables, clearQueueMessages, coerceAggregateNumber, compactCdcDocs, compileWhereSql, composeReadPredicate, 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, describeRelationWrites, diffExternalSource, diffGlobalMembership, distinctValues, encodeAggregateKey, encodeCursor, encodeGeohash, encodePartitionKey, encodeRowsPatch, ensureAuditTable, ensureMailTable, envOptionalPositiveInt, envPositiveInt, equalityPinnedFields, exportShardRows, facetColumn, fanOutScalarCounts, findRelated, findStorageReferences, finishStreamRun, float64SqlKey, foldAggregateTally, forgetScheduleOutbox, ftsCompanionDdl, ftsPurgeDocument, ftsRowidMapName, ftsUnmappedPage, ftsWriteDocument, gateReplicaDispatch, geoTableName, globalShapeReadKey, groupUnmappedRows, guardWriter, handleReplicaControl, hasTrigger, haversineMeters, importShardRows, indexKeysForRow, isDevEnvironment, isFtsAvailable, isInternalTableName, isLossyBody, isMemoryTable, isPushableWhere, isRelationPredicate, isSoftDeleted, isSourceDue, isVacuousFilterClause, jsonPath, jsonPathSql, keysTouchRanges, liftSourceId, lintReadonlySql, listReactorStates, listTables, markUnvouchableReads, matchesRankStaticWhere, matchesStaticWhere, materializeExternalRows, materializeExternalRowsIncremental, memoryTableNames, mergeChangedKeys, mergeWhere, migrateCdcLog, migrateCdcMeta, migrateClientWatermark, migrateCommitSeq, migrateDurableStreams, migrateGlobalShapeSnapshot, migrateIdempotency, migrateReactorState, migrateScheduleOutbox, migrateSearchState, migrateShapePokeCursor, minCdcReplayableSeq, minCdcSeq, minShapePokeCursor, nextPromotionState, nextTtlExpiry, normalizeCountArgument, normalizeIdStructurally, normalizeOrderKeys, normalizeSourceDocument, normalizeSourceValue, nullsFirstOf, nullsOrderSuffix, operatorFields, param, parkScheduleOutbox, parseExportShardArgs, parseImportShardArgs, patchDependsOnRow, 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, readPatchField, readQueueMessageById, readQueueMessages, readReactorState, readSchemaHistory, readSchemaVersion, readSearchBackfillState, readShapePokeCursor, readStreamChunks, readStreamRun, readTablePage, recordCapturedMail, recordChangedKeys, recordFanoutPass, recordGlobalPollPass, recordQueueMessages, recordScheduleOutbox, recordSchemaVersion, recordShapeProbePass, relationHooks, relayCountFor, renderSql, reprojectableFields, reprojectionMigrationId, reprojectionTables, resolvePatch, resolveRankPartition, resolveRankSeekTuple, resolveRelationPredicates, resolveWith, rowToDocument, runDataMigration, runDrizzle, runExternalSourceTick, runReadonlySql, runRowValidators, runShardMigrations, runSocketPool, runSql, runTriggers, selectExpiredIds, selectExportTables, selectIndexForAggregate, selectIndexForCount, selectIndexForGroupBy, selectMatchingIds, selectShapeMembers, selectShapeRows, serializeSqlValue, serverInList, shapeRoutingKey, siblingSecretOf, signSiblingBody, softDeleteScope, sortColumnName, sqliteInList, stripReservedPatchFields, stubByName, subscriptionFrames, subscriptionListDeltas, summarizeFanoutTopics, summarizeSubscriptions, tableColumns, tableFromDepKey, throwingScheduler, tiebreakDirectionFor, trimCdcChanges, trimIdempotent, trimScheduleOutbox, trimStreamRuns, tryRowToDocument, trySendFrame, unionAll, uniqueIndexFields, validateImportRow, verifySiblingBody, whereFilter, whereOfFilter, writeCdcArchivedThrough, writeGlobalShapeSnapshot, writeIdempotent, writeReactorState, writeSearchBackfillState, writeShapePokeCursor, writeShapePokeCursors, writeTouchesMemo };
|
|
2715
|
+
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, 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, CompanionMemo, 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 FtsWriteOptions, 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 KeyedRelationWriteInfo, type LifecycleDispatchInfo, type LifecycleEvent, type LiveSocketControlCall, 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 NullPlacement, type OnDeleteActionLike, type OrderByClause, type OrderByInput, type OrderKey, type OrderKeyConstraints, OwnerRelay, type OwnerRelayFrame, type PaginationOptions, type PatchVerifier, type PatchWriteOptions, type PitrBookmarkResult, type PitrRestoreArgs, type PitrRestoreResult, type PitrStorage, type PokeFrameMeta, type PromotionState, type PromotionThresholds, QUEUE_TABLE, type QueryArgs, type QueryPage, type QueryPlan, 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, RELAY_SIGNATURE_HEADER, REPROJECTION_MIGRATION_PREFIX, RLS_UNWRAP_SYMBOL, type RangeOperandType, 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 RelationWriteInfo, type RelationWriteMap, type RelayAttach, type RelayDetach, type RelayFrame, type RelayHost, RelayMember, type RelayPokeDelivery, type RelayRoomEvent, type RelayRoomVerdict, 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 ThroughRelationWriteInfo, type TransactionHeadroom, TransactionHeadroomTracker, type TransactionLimits, type TransactionSqlLike, type TriggerContextLike, type TriggerDefinitionLike, type TriggerEventLike, type TriggerOpLike, type TriggerTimingLike, type TtlSweepSpec, UNVOUCHABLE_DEP, VECTOR_BACKFILL_MAX_PAGES, type ValidatorLike, type VectorBackfillProgress, WORKERD_SQLITE_LIMITS, type WhereFilter, 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, applyInsertDefaults, applyOnDelete, applySelect, archiveCdcSegment, armRestore, assertFlatPredicate, assertNoExplicitUndefined, assertPatchAllowed, assertReadonly, assertShapeShardable, assertStorableRowId, assertValidClientId, awaitWsDrain, backfillAggregateIndexes, backfillRankIndexes, backfillSearchIndexes, backfillSearchIndexesForTable, backfillVectorIndexes, bigintSqlKey, boundingBoxCenter, boundingBoxGeohashes, buildIndexRange, buildPokeFrames, buildReprojectionMigration, buildSeekBeforeWhere, buildSeekWhere, buildSettings, buildShapeDiff, bumpCdcEpoch, cdcArchiveRewound, cdcCanVouchFor, cdcForkedError, cdcSeqLeavingRows, cdcTouchesTables, cdcTrimmedError, claimStreamRun, clampPromotionThresholds, clearCapturedMail, clearCompanionSignatures, clearMemoryTables, clearQueueMessages, coerceAggregateNumber, compactCdcDocs, compileWhereSql, composeReadPredicate, 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, describeRelationWrites, diffExternalSource, diffGlobalMembership, distinctValues, encodeAggregateKey, encodeCursor, encodeGeohash, encodePartitionKey, encodeRowsPatch, ensureAuditTable, ensureMailTable, envOptionalPositiveInt, envPositiveInt, equalityPinnedFields, exportShardRows, facetColumn, fanOutScalarCounts, findRelated, findStorageReferences, finishStreamRun, float64SqlKey, foldAggregateTally, forgetScheduleOutbox, ftsCompanionDdl, ftsPurgeDocument, ftsRowidMapName, ftsUnmappedPage, ftsWriteDocument, gateReplicaDispatch, geoTableName, globalShapeReadKey, groupUnmappedRows, guardWriter, handleReplicaControl, hasTrigger, haversineMeters, importShardRows, indexKeysForRow, isDevEnvironment, isFtsAvailable, isInternalTableName, isLossyBody, isMemoryTable, isPushableWhere, isRelationPredicate, isSoftDeleted, isSourceDue, isVacuousFilterClause, jsonPath, jsonPathSql, keysTouchRanges, liftSourceId, lintReadonlySql, listReactorStates, listTables, markUnvouchableReads, matchesRankStaticWhere, matchesStaticWhere, materializeExternalRows, materializeExternalRowsIncremental, memoryTableNames, mergeChangedKeys, mergeWhere, migrateCdcLog, migrateCdcMeta, migrateClientWatermark, migrateCommitSeq, migrateDurableStreams, migrateGlobalShapeSnapshot, migrateIdempotency, migrateReactorState, migrateScheduleOutbox, migrateSearchState, migrateShapePokeCursor, minCdcReplayableSeq, minCdcSeq, minShapePokeCursor, nextPromotionState, nextTtlExpiry, normalizeCountArgument, normalizeIdStructurally, normalizeOrderKeys, normalizeSourceDocument, normalizeSourceValue, nullsFirstOf, nullsOrderSuffix, operatorFields, param, parkScheduleOutbox, parseExportShardArgs, parseImportShardArgs, patchDependsOnRow, 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, readPatchField, readQueueMessageById, readQueueMessages, readReactorState, readSchemaHistory, readSchemaVersion, readSearchBackfillState, readShapePokeCursor, readStreamChunks, readStreamRun, readTablePage, recordCapturedMail, recordChangedKeys, recordFanoutPass, recordGlobalPollPass, recordQueueMessages, recordScheduleOutbox, recordSchemaVersion, recordShapeProbePass, relationHooks, relayCountFor, renderSql, reprojectableFields, reprojectionMigrationId, reprojectionTables, resolvePatch, resolveRankPartition, resolveRankSeekTuple, resolveRelationPredicates, resolveWith, rowToDocument, runDataMigration, runDrizzle, runExternalSourceTick, runReadonlySql, runRowValidators, runShardMigrations, runSocketPool, runSql, runTriggers, selectExpiredIds, selectExportTables, selectIndexForAggregate, selectIndexForCount, selectIndexForGroupBy, selectMatchingIds, selectShapeMembers, selectShapeRows, serializeSqlValue, serverInList, shapeRoutingKey, siblingSecretOf, signSiblingBody, softDeleteScope, sortColumnName, sqliteInList, stripReservedPatchFields, stubByName, subscriptionFrames, subscriptionListDeltas, summarizeFanoutTopics, summarizeSubscriptions, tableColumns, tableFromDepKey, throwingScheduler, tiebreakDirectionFor, trimCdcChanges, trimIdempotent, trimScheduleOutbox, trimStreamRuns, tryRowToDocument, trySendFrame, unionAll, uniqueIndexFields, validateImportRow, verifySiblingBody, whereFilter, whereOfFilter, writeCdcArchivedThrough, writeGlobalShapeSnapshot, writeIdempotent, writeReactorState, writeSearchBackfillState, writeShapePokeCursor, writeShapePokeCursors, writeTouchesMemo };
|
package/dist/index.d.ts
CHANGED
|
@@ -772,6 +772,11 @@ declare const selectIndexForGroupBy: (indexes: ReadonlyArray<AggregateIndexDefin
|
|
|
772
772
|
index: AggregateIndexDefinitionLike;
|
|
773
773
|
partial: Record<string, unknown>;
|
|
774
774
|
};
|
|
775
|
+
declare const clearCompanionSignatures: (sql: SqlExec) => void;
|
|
776
|
+
declare class CompanionMemo {
|
|
777
|
+
readonly verified: Set<string>;
|
|
778
|
+
invalidate(): void;
|
|
779
|
+
}
|
|
775
780
|
interface CacheEntry {
|
|
776
781
|
bytes: number;
|
|
777
782
|
deps: Set<string>;
|
|
@@ -968,6 +973,7 @@ interface CtxDbOptions {
|
|
|
968
973
|
cache?: ReactiveCache;
|
|
969
974
|
cdc?: boolean;
|
|
970
975
|
clock?: Clock;
|
|
976
|
+
companionMemo?: CompanionMemo;
|
|
971
977
|
enforceRls?: boolean;
|
|
972
978
|
globalDb?: DatabaseWriterLike;
|
|
973
979
|
headroom?: TransactionHeadroomTracker;
|
|
@@ -1036,7 +1042,6 @@ declare const COMMIT_SEQ_FIELD = "_commitSeq";
|
|
|
1036
1042
|
declare const migrateCommitSeq: (sql: SqlExec) => void;
|
|
1037
1043
|
declare const readCommitSeq: (sql: SqlExec) => number;
|
|
1038
1044
|
declare const allocateCommitSeq: (sql: SqlExec) => number;
|
|
1039
|
-
declare const clearCompanionSignatures: (sql: SqlExec) => void;
|
|
1040
1045
|
interface CompanionSyncDeps {
|
|
1041
1046
|
broadcast: (delta: MutationDelta) => void;
|
|
1042
1047
|
indexKeysFor: (table: string, document?: Record<string, unknown>) => ReadonlyArray<{
|
|
@@ -1047,6 +1052,7 @@ interface CompanionSyncDeps {
|
|
|
1047
1052
|
recordCdc: (table: string, id: string, op: "delete" | "insert" | "update", doc?: Record<string, unknown>) => void;
|
|
1048
1053
|
schema: SchemaLike;
|
|
1049
1054
|
sql: SqlExec;
|
|
1055
|
+
verified?: Set<string>;
|
|
1050
1056
|
}
|
|
1051
1057
|
interface CompanionSync {
|
|
1052
1058
|
ensureBackfilledForTable: (tableName: string) => void;
|
|
@@ -2149,7 +2155,10 @@ declare const resolveWith: (options: ResolveWithOptions) => Promise<void>;
|
|
|
2149
2155
|
interface ApplyOnDeleteOptions {
|
|
2150
2156
|
deletedId: string;
|
|
2151
2157
|
deletedReference: (references: string) => unknown;
|
|
2152
|
-
findHolders: (holderTable: string, field: string, value: unknown
|
|
2158
|
+
findHolders: (holderTable: string, field: string, value: unknown, page: {
|
|
2159
|
+
limit: number;
|
|
2160
|
+
select?: ReadonlyArray<string>;
|
|
2161
|
+
}) => Promise<Record<string, unknown>[]>;
|
|
2153
2162
|
onCascade: (holderTable: string, id: string) => Promise<void>;
|
|
2154
2163
|
onRestrict: (message: string) => never;
|
|
2155
2164
|
onSetNull: (holderTable: string, id: string, field: string) => Promise<void>;
|
|
@@ -2703,4 +2712,4 @@ declare const backfillVectorIndexes: (sql: SqlExec, targets: ReadonlyArray<Vecto
|
|
|
2703
2712
|
ordered: OrderedAfterWrites;
|
|
2704
2713
|
restart?: boolean;
|
|
2705
2714
|
}) => Promise<VectorBackfillProgress>;
|
|
2706
|
-
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, 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 FtsWriteOptions, 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 KeyedRelationWriteInfo, type LifecycleDispatchInfo, type LifecycleEvent, type LiveSocketControlCall, 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 NullPlacement, type OnDeleteActionLike, type OrderByClause, type OrderByInput, type OrderKey, type OrderKeyConstraints, OwnerRelay, type OwnerRelayFrame, type PaginationOptions, type PatchVerifier, type PatchWriteOptions, type PitrBookmarkResult, type PitrRestoreArgs, type PitrRestoreResult, type PitrStorage, type PokeFrameMeta, type PromotionState, type PromotionThresholds, QUEUE_TABLE, type QueryArgs, type QueryPage, type QueryPlan, 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, RELAY_SIGNATURE_HEADER, REPROJECTION_MIGRATION_PREFIX, RLS_UNWRAP_SYMBOL, type RangeOperandType, 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 RelationWriteInfo, type RelationWriteMap, type RelayAttach, type RelayDetach, type RelayFrame, type RelayHost, RelayMember, type RelayPokeDelivery, type RelayRoomEvent, type RelayRoomVerdict, 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 ThroughRelationWriteInfo, type TransactionHeadroom, TransactionHeadroomTracker, type TransactionLimits, type TransactionSqlLike, type TriggerContextLike, type TriggerDefinitionLike, type TriggerEventLike, type TriggerOpLike, type TriggerTimingLike, type TtlSweepSpec, UNVOUCHABLE_DEP, VECTOR_BACKFILL_MAX_PAGES, type ValidatorLike, type VectorBackfillProgress, WORKERD_SQLITE_LIMITS, type WhereFilter, 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, applyInsertDefaults, applyOnDelete, applySelect, archiveCdcSegment, armRestore, assertFlatPredicate, assertNoExplicitUndefined, assertPatchAllowed, assertReadonly, assertShapeShardable, assertStorableRowId, assertValidClientId, awaitWsDrain, backfillAggregateIndexes, backfillRankIndexes, backfillSearchIndexes, backfillSearchIndexesForTable, backfillVectorIndexes, bigintSqlKey, boundingBoxCenter, boundingBoxGeohashes, buildIndexRange, buildPokeFrames, buildReprojectionMigration, buildSeekBeforeWhere, buildSeekWhere, buildSettings, buildShapeDiff, bumpCdcEpoch, cdcArchiveRewound, cdcCanVouchFor, cdcForkedError, cdcSeqLeavingRows, cdcTouchesTables, cdcTrimmedError, claimStreamRun, clampPromotionThresholds, clearCapturedMail, clearCompanionSignatures, clearMemoryTables, clearQueueMessages, coerceAggregateNumber, compactCdcDocs, compileWhereSql, composeReadPredicate, 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, describeRelationWrites, diffExternalSource, diffGlobalMembership, distinctValues, encodeAggregateKey, encodeCursor, encodeGeohash, encodePartitionKey, encodeRowsPatch, ensureAuditTable, ensureMailTable, envOptionalPositiveInt, envPositiveInt, equalityPinnedFields, exportShardRows, facetColumn, fanOutScalarCounts, findRelated, findStorageReferences, finishStreamRun, float64SqlKey, foldAggregateTally, forgetScheduleOutbox, ftsCompanionDdl, ftsPurgeDocument, ftsRowidMapName, ftsUnmappedPage, ftsWriteDocument, gateReplicaDispatch, geoTableName, globalShapeReadKey, groupUnmappedRows, guardWriter, handleReplicaControl, hasTrigger, haversineMeters, importShardRows, indexKeysForRow, isDevEnvironment, isFtsAvailable, isInternalTableName, isLossyBody, isMemoryTable, isPushableWhere, isRelationPredicate, isSoftDeleted, isSourceDue, isVacuousFilterClause, jsonPath, jsonPathSql, keysTouchRanges, liftSourceId, lintReadonlySql, listReactorStates, listTables, markUnvouchableReads, matchesRankStaticWhere, matchesStaticWhere, materializeExternalRows, materializeExternalRowsIncremental, memoryTableNames, mergeChangedKeys, mergeWhere, migrateCdcLog, migrateCdcMeta, migrateClientWatermark, migrateCommitSeq, migrateDurableStreams, migrateGlobalShapeSnapshot, migrateIdempotency, migrateReactorState, migrateScheduleOutbox, migrateSearchState, migrateShapePokeCursor, minCdcReplayableSeq, minCdcSeq, minShapePokeCursor, nextPromotionState, nextTtlExpiry, normalizeCountArgument, normalizeIdStructurally, normalizeOrderKeys, normalizeSourceDocument, normalizeSourceValue, nullsFirstOf, nullsOrderSuffix, operatorFields, param, parkScheduleOutbox, parseExportShardArgs, parseImportShardArgs, patchDependsOnRow, 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, readPatchField, readQueueMessageById, readQueueMessages, readReactorState, readSchemaHistory, readSchemaVersion, readSearchBackfillState, readShapePokeCursor, readStreamChunks, readStreamRun, readTablePage, recordCapturedMail, recordChangedKeys, recordFanoutPass, recordGlobalPollPass, recordQueueMessages, recordScheduleOutbox, recordSchemaVersion, recordShapeProbePass, relationHooks, relayCountFor, renderSql, reprojectableFields, reprojectionMigrationId, reprojectionTables, resolvePatch, resolveRankPartition, resolveRankSeekTuple, resolveRelationPredicates, resolveWith, rowToDocument, runDataMigration, runDrizzle, runExternalSourceTick, runReadonlySql, runRowValidators, runShardMigrations, runSocketPool, runSql, runTriggers, selectExpiredIds, selectExportTables, selectIndexForAggregate, selectIndexForCount, selectIndexForGroupBy, selectMatchingIds, selectShapeMembers, selectShapeRows, serializeSqlValue, serverInList, shapeRoutingKey, siblingSecretOf, signSiblingBody, softDeleteScope, sortColumnName, sqliteInList, stripReservedPatchFields, stubByName, subscriptionFrames, subscriptionListDeltas, summarizeFanoutTopics, summarizeSubscriptions, tableColumns, tableFromDepKey, throwingScheduler, tiebreakDirectionFor, trimCdcChanges, trimIdempotent, trimScheduleOutbox, trimStreamRuns, tryRowToDocument, trySendFrame, unionAll, uniqueIndexFields, validateImportRow, verifySiblingBody, whereFilter, whereOfFilter, writeCdcArchivedThrough, writeGlobalShapeSnapshot, writeIdempotent, writeReactorState, writeSearchBackfillState, writeShapePokeCursor, writeShapePokeCursors, writeTouchesMemo };
|
|
2715
|
+
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, 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, CompanionMemo, 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 FtsWriteOptions, 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 KeyedRelationWriteInfo, type LifecycleDispatchInfo, type LifecycleEvent, type LiveSocketControlCall, 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 NullPlacement, type OnDeleteActionLike, type OrderByClause, type OrderByInput, type OrderKey, type OrderKeyConstraints, OwnerRelay, type OwnerRelayFrame, type PaginationOptions, type PatchVerifier, type PatchWriteOptions, type PitrBookmarkResult, type PitrRestoreArgs, type PitrRestoreResult, type PitrStorage, type PokeFrameMeta, type PromotionState, type PromotionThresholds, QUEUE_TABLE, type QueryArgs, type QueryPage, type QueryPlan, 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, RELAY_SIGNATURE_HEADER, REPROJECTION_MIGRATION_PREFIX, RLS_UNWRAP_SYMBOL, type RangeOperandType, 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 RelationWriteInfo, type RelationWriteMap, type RelayAttach, type RelayDetach, type RelayFrame, type RelayHost, RelayMember, type RelayPokeDelivery, type RelayRoomEvent, type RelayRoomVerdict, 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 ThroughRelationWriteInfo, type TransactionHeadroom, TransactionHeadroomTracker, type TransactionLimits, type TransactionSqlLike, type TriggerContextLike, type TriggerDefinitionLike, type TriggerEventLike, type TriggerOpLike, type TriggerTimingLike, type TtlSweepSpec, UNVOUCHABLE_DEP, VECTOR_BACKFILL_MAX_PAGES, type ValidatorLike, type VectorBackfillProgress, WORKERD_SQLITE_LIMITS, type WhereFilter, 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, applyInsertDefaults, applyOnDelete, applySelect, archiveCdcSegment, armRestore, assertFlatPredicate, assertNoExplicitUndefined, assertPatchAllowed, assertReadonly, assertShapeShardable, assertStorableRowId, assertValidClientId, awaitWsDrain, backfillAggregateIndexes, backfillRankIndexes, backfillSearchIndexes, backfillSearchIndexesForTable, backfillVectorIndexes, bigintSqlKey, boundingBoxCenter, boundingBoxGeohashes, buildIndexRange, buildPokeFrames, buildReprojectionMigration, buildSeekBeforeWhere, buildSeekWhere, buildSettings, buildShapeDiff, bumpCdcEpoch, cdcArchiveRewound, cdcCanVouchFor, cdcForkedError, cdcSeqLeavingRows, cdcTouchesTables, cdcTrimmedError, claimStreamRun, clampPromotionThresholds, clearCapturedMail, clearCompanionSignatures, clearMemoryTables, clearQueueMessages, coerceAggregateNumber, compactCdcDocs, compileWhereSql, composeReadPredicate, 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, describeRelationWrites, diffExternalSource, diffGlobalMembership, distinctValues, encodeAggregateKey, encodeCursor, encodeGeohash, encodePartitionKey, encodeRowsPatch, ensureAuditTable, ensureMailTable, envOptionalPositiveInt, envPositiveInt, equalityPinnedFields, exportShardRows, facetColumn, fanOutScalarCounts, findRelated, findStorageReferences, finishStreamRun, float64SqlKey, foldAggregateTally, forgetScheduleOutbox, ftsCompanionDdl, ftsPurgeDocument, ftsRowidMapName, ftsUnmappedPage, ftsWriteDocument, gateReplicaDispatch, geoTableName, globalShapeReadKey, groupUnmappedRows, guardWriter, handleReplicaControl, hasTrigger, haversineMeters, importShardRows, indexKeysForRow, isDevEnvironment, isFtsAvailable, isInternalTableName, isLossyBody, isMemoryTable, isPushableWhere, isRelationPredicate, isSoftDeleted, isSourceDue, isVacuousFilterClause, jsonPath, jsonPathSql, keysTouchRanges, liftSourceId, lintReadonlySql, listReactorStates, listTables, markUnvouchableReads, matchesRankStaticWhere, matchesStaticWhere, materializeExternalRows, materializeExternalRowsIncremental, memoryTableNames, mergeChangedKeys, mergeWhere, migrateCdcLog, migrateCdcMeta, migrateClientWatermark, migrateCommitSeq, migrateDurableStreams, migrateGlobalShapeSnapshot, migrateIdempotency, migrateReactorState, migrateScheduleOutbox, migrateSearchState, migrateShapePokeCursor, minCdcReplayableSeq, minCdcSeq, minShapePokeCursor, nextPromotionState, nextTtlExpiry, normalizeCountArgument, normalizeIdStructurally, normalizeOrderKeys, normalizeSourceDocument, normalizeSourceValue, nullsFirstOf, nullsOrderSuffix, operatorFields, param, parkScheduleOutbox, parseExportShardArgs, parseImportShardArgs, patchDependsOnRow, 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, readPatchField, readQueueMessageById, readQueueMessages, readReactorState, readSchemaHistory, readSchemaVersion, readSearchBackfillState, readShapePokeCursor, readStreamChunks, readStreamRun, readTablePage, recordCapturedMail, recordChangedKeys, recordFanoutPass, recordGlobalPollPass, recordQueueMessages, recordScheduleOutbox, recordSchemaVersion, recordShapeProbePass, relationHooks, relayCountFor, renderSql, reprojectableFields, reprojectionMigrationId, reprojectionTables, resolvePatch, resolveRankPartition, resolveRankSeekTuple, resolveRelationPredicates, resolveWith, rowToDocument, runDataMigration, runDrizzle, runExternalSourceTick, runReadonlySql, runRowValidators, runShardMigrations, runSocketPool, runSql, runTriggers, selectExpiredIds, selectExportTables, selectIndexForAggregate, selectIndexForCount, selectIndexForGroupBy, selectMatchingIds, selectShapeMembers, selectShapeRows, serializeSqlValue, serverInList, shapeRoutingKey, siblingSecretOf, signSiblingBody, softDeleteScope, sortColumnName, sqliteInList, stripReservedPatchFields, stubByName, subscriptionFrames, subscriptionListDeltas, summarizeFanoutTopics, summarizeSubscriptions, tableColumns, tableFromDepKey, throwingScheduler, tiebreakDirectionFor, trimCdcChanges, trimIdempotent, trimScheduleOutbox, trimStreamRuns, tryRowToDocument, trySendFrame, unionAll, uniqueIndexFields, validateImportRow, verifySiblingBody, whereFilter, whereOfFilter, 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 i,selectExportTables as s,validateImportRow as l}from"./packem_shared/exportShardRows-b0pfdTXz.mjs";import{AGGREGATE_SQL_FUNCTION as d,aggregateSqlFunction as c,matchesStaticWhere as m,normalizeCountArgument as p,throwingScheduler as S}from"./packem_shared/AGGREGATE_SQL_FUNCTION-C_ZipS9R.mjs";import{aggregateTableName as f,coerceAggregateNumber as E,encodeAggregateKey as x,foldAggregateTally as h,readAggregateValue as T}from"./packem_shared/aggregateTableName-B_CtIQCS.mjs";import{CountRlsUnsupportedError as A,mergeWhere as C,planAggregateLookup as g,selectIndexForAggregate as _,selectIndexForCount as I,selectIndexForGroupBy as b}from"./packem_shared/CountRlsUnsupportedError-BvsDqfO2.mjs";import{AUDIT_LOG_TABLE as D,appendAuditEntry as P,ensureAuditTable as O,readAuditLog as y}from"./packem_shared/AUDIT_LOG_TABLE-BFJ65SRS.mjs";import{NotUniqueError as M,assertNoExplicitUndefined as N,assertStorableRowId as k,assertValidClientId as B,createShardCtxDb as U,normalizeIdStructurally as G,stripReservedPatchFields as w}from"./packem_shared/NotUniqueError-UjpHasAz.mjs";import{backfillAggregateIndexes as v,backfillRankIndexes as K,backfillSearchIndexes as W,backfillSearchIndexesForTable as X}from"./packem_shared/backfillAggregateIndexes-DSplGrR_.mjs";import{CDC_LOG_TABLE as V,CDC_LOG_TABLE_SEQ_INDEX as z,CDC_META_TABLE as Q,appendCdcChange as Y,applyCdcChanges as j,bumpCdcEpoch as J,cdcCanVouchFor as Z,cdcForkedError as $,cdcSeqLeavingRows as ee,cdcTouchesTables as re,cdcTrimmedError as oe,compactCdcDocs as ae,cursorBelowRetainedFloor as te,migrateCdcLog as ie,migrateCdcMeta as se,minCdcReplayableSeq as le,minCdcSeq as ne,readCdcChangeKeys as de,readCdcChanges as ce,readCdcCursor as me,readCdcEpoch as pe,trimCdcChanges as Se}from"./packem_shared/CDC_LOG_TABLE-Dgwxv7yf.mjs";import{archiveCdcSegment as fe,cdcArchiveRewound as Ee,readArchivedCdcChanges as xe,readCdcArchivedThrough as he,writeCdcArchivedThrough as Te}from"./packem_shared/archiveCdcSegment-Cr8oGLfB.mjs";import{CLIENT_WATERMARK_TABLE as Ae,advanceClientWatermark as Ce,migrateClientWatermark as ge,readClientWatermark as _e}from"./packem_shared/CLIENT_WATERMARK_TABLE-De7z_OHV.mjs";import{COMMIT_SEQ_FIELD as be,COMMIT_SEQ_TABLE as Le,allocateCommitSeq as De,migrateCommitSeq as Pe,readCommitSeq as Oe}from"./packem_shared/COMMIT_SEQ_FIELD-Da1DjGqo.mjs";import{clearCompanionSignatures as Fe}from"./packem_shared/clearCompanionSignatures-3MlVqWZD.mjs";import{createCompanionSync as Ne}from"./packem_shared/createCompanionSync-BMS8yYTx.mjs";import{GLOBAL_SHAPE_SNAPSHOT_TABLE as Be,deleteGlobalShapeSnapshot as Ue,deleteGlobalShapeSnapshotsForConnection as Ge,migrateGlobalShapeSnapshot as we,readGlobalShapeSnapshot as qe,writeGlobalShapeSnapshot as ve}from"./packem_shared/GLOBAL_SHAPE_SNAPSHOT_TABLE-Bb6-aZuH.mjs";import{IDEMPOTENCY_TABLE as We,migrateIdempotency as Xe,readIdempotent as He,trimIdempotent as Ve,writeIdempotent as ze}from"./packem_shared/IDEMPOTENCY_TABLE-COrgeP3O.mjs";import{clearMemoryTables as Ye,isMemoryTable as je,memoryTableNames as Je}from"./packem_shared/clearMemoryTables-aMRERF0w.mjs";import{computeRankPage as $e,resolveRankSeekTuple as er}from"./packem_shared/computeRankPage-BZIpATcs.mjs";import{SCHEDULE_OUTBOX_TABLE as or,deferScheduleOutbox as ar,forgetScheduleOutbox as tr,migrateScheduleOutbox as ir,parkScheduleOutbox as sr,probeScheduleOutbox as lr,readDueScheduleOutbox as nr,recordScheduleOutbox as dr,trimScheduleOutbox as cr}from"./packem_shared/SCHEDULE_OUTBOX_TABLE-DcZI7Yhl.mjs";import{S as pr,m as Sr,r as ur,w as fr}from"./packem_shared/ctx-db-search-state-FjgzTFok.mjs";import{SHAPE_POKE_CURSOR_TABLE as xr,deleteShapePokeCursor as hr,deleteShapePokeCursorsForConnection as Tr,migrateShapePokeCursor as Rr,minShapePokeCursor as Ar,readShapePokeCursor as Cr,writeShapePokeCursor as gr,writeShapePokeCursors as _r}from"./packem_shared/SHAPE_POKE_CURSOR_TABLE-BGvY3sFI.mjs";import{selectShapeMembers as br,selectShapeRows as Lr}from"./packem_shared/selectShapeMembers-BCfKypfN.mjs";import{DATA_MIGRATION_STATE_TABLE as Pr,readMigrationStatus as Or,runDataMigration as yr}from"./packem_shared/DATA_MIGRATION_STATE_TABLE-D1FtktFp.mjs";import{SCAN_DEP as Mr,createDependencyTracker as Nr,depKey as kr,tableFromDepKey as Br}from"./packem_shared/SCAN_DEP-D7qE3iUe.mjs";import{runDrizzle as Gr,runSql as wr}from"./packem_shared/runDrizzle-RC09zZrh.mjs";import{A as vr,a as Kr,b as Wr,D as Xr,c as Hr,d as Vr,g as zr,i as Qr,j as Yr,e as jr,q as Jr,f as Zr,r as $r,t as eo,h as ro}from"./packem_shared/do-sql-BWrJQAOh.mjs";import{WORKERD_SQLITE_LIMITS as ao,param as to,renderSql as io,sqliteInList as so,unionAll as lo}from"./packem_shared/WORKERD_SQLITE_LIMITS-B_4w7tzY.mjs";import{appendStreamChunk as co,claimStreamRun as mo,deleteStreamRun as po,finishStreamRun as So,migrateDurableStreams as uo,readStreamChunks as fo,readStreamRun as Eo,trimStreamRuns as xo}from"./packem_shared/appendStreamChunk-BZYgGE9Y.mjs";import{DurableStreamRunner as To,MAX_DURABLE_STREAM_BYTES as Ro,MAX_DURABLE_STREAM_CHUNKS as Ao,decideDurableAttach as Co}from"./packem_shared/DurableStreamRunner-MMlV5qKQ.mjs";import{envOptionalPositiveInt as _o,envPositiveInt as Io}from"./packem_shared/envOptionalPositiveInt-D2pY-c64.mjs";import{diffExternalSource as Lo}from"./packem_shared/diffExternalSource-B0FZlDoL.mjs";import{liftSourceId as Po,normalizeSourceDocument as Oo,normalizeSourceValue as yo}from"./packem_shared/liftSourceId-CA3ENhXj.mjs";import{materializeExternalRows as Mo,materializeExternalRowsIncremental as No,readExternalSourceBaseline as ko,runExternalSourceTick as Bo}from"./packem_shared/materializeExternalRows-DZnatu1U.mjs";import{isSoftDeleted as Go,isSourceDue as wo,pullExternalSourceIncrementalTick as qo,pullExternalSourceTick as vo}from"./packem_shared/isSoftDeleted-kHKo4Oku.mjs";import{f as Wo,a as Xo,b as Ho,c as Vo,d as zo,g as Qo}from"./packem_shared/fts-companion-CA8mLJWq.mjs";import{GEO_DEFAULT_PRECISION as jo,boundingBoxCenter as Jo,boundingBoxGeohashes as Zo,coveringGeohashes as $o,encodeGeohash as ea,haversineMeters as ra,pointInBoundingBox as oa}from"./packem_shared/GEO_DEFAULT_PRECISION-CqpQZ-J_.mjs";import{default as ta}from"./packem_shared/GlobalPollTick-BNK4o-XT.mjs";import{ADMIN_FUNCTIONS as sa,ADMIN_FUNCTION_PREFIX as la,DEFAULT_FANOUT_TOPIC_LIMIT as na,FLAGS_FUNCTION_PREFIX as da,MAX_PAGE_SIZE as ca,RELATION_FUNCTION_PREFIX as ma,createFanoutCounters as pa,createGlobalPollCounters as Sa,createShapeProbeCounters as ua,facetColumn as fa,findStorageReferences as Ea,isVacuousFilterClause as xa,listTables as ha,readTablePage as Ta,recordFanoutPass as Ra,recordGlobalPollPass as Aa,recordShapeProbePass as Ca,selectMatchingIds as ga,summarizeFanoutTopics as _a,summarizeSubscriptions as Ia}from"./packem_shared/ADMIN_FUNCTIONS-CPXCHyOg.mjs";import{MAIL_RETENTION as La,MAIL_TABLE as Da,clearCapturedMail as Pa,ensureMailTable as Oa,readCapturedMail as ya,recordCapturedMail as Fa}from"./packem_shared/MAIL_RETENTION-DMolrLYt.mjs";import{NotFoundError as Na}from"./packem_shared/NotFoundError-BhF7FeFr.mjs";import{assertPatchAllowed as Ba,operatorFields as Ua,patchDependsOnRow as Ga,readPatchField as wa,resolvePatch as qa}from"./packem_shared/assertPatchAllowed-CA_H466g.mjs";import{armRestore as Ka,readBookmark as Wa}from"./packem_shared/armRestore-Bu1_8SUa.mjs";import{CURSOR_PREFIX as Ha,applySelect as Va,buildSeekBeforeWhere as za,buildSeekWhere as Qa,decodeCursor as Ya,encodeCursor as ja,equalityPinnedFields as Ja,normalizeOrderKeys as Za,nullsFirstOf as $a,nullsOrderSuffix as et,softDeleteScope as rt,tiebreakDirectionFor as ot,uniqueIndexFields as at}from"./packem_shared/CURSOR_PREFIX-6offuG6M.mjs";import{QUEUE_TABLE as it,clearQueueMessages as st,isLossyBody as lt,readQueueMessageById as nt,readQueueMessages as dt,recordQueueMessages as ct}from"./packem_shared/QUEUE_TABLE-C-goXtGd.mjs";import{RANK_TIEBREAK as pt,encodePartitionKey as St,matchesRankStaticWhere as ut,rankKeyFromDoc as ft,rankPivotConditionSql as Et,rankTableName as xt,resolveRankPartition as ht,sortColumnName as Tt}from"./packem_shared/RANK_TIEBREAK-D3ye2GsL.mjs";import{ReactiveCache as At,reactiveCacheKey as Ct}from"./packem_shared/ReactiveCache-DHhhLJtN.mjs";import{REACTOR_STATE_TABLE as _t,listReactorStates as It,migrateReactorState as bt,reactorNeedsRun as Lt,readReactorState as Dt,writeReactorState as Pt}from"./packem_shared/REACTOR_STATE_TABLE-D2Mn204f.mjs";import{UNVOUCHABLE_DEP as yt,createReadFootprint as Ft,markUnvouchableReads as Mt}from"./packem_shared/UNVOUCHABLE_DEP-C68htACn.mjs";import{buildIndexRange as kt,indexKeysForRow as Bt,keysTouchRanges as Ut}from"./packem_shared/buildIndexRange-DQ3eWAGd.mjs";import{isPushableWhere as wt,whereFilter as qt,whereOfFilter as vt}from"./packem_shared/isPushableWhere-BeYAOjUb.mjs";import{RELATED_DEFAULT_LIMIT as Wt,RELATED_DEPTH_DECAY as Xt,RELATED_MAX_DEPTH as Ht,RELATED_MAX_LIMIT as Vt,deriveRelationEdges as zt,findRelated as Qt}from"./packem_shared/RELATED_DEFAULT_LIMIT-CVqN4JEu.mjs";import{DEFAULT_MAX_RELATION_KEYS as jt,assertFlatPredicate as Jt,assertShapeShardable as Zt,composeReadPredicate as $t,containsRelationPredicate as ei,isRelationPredicate as ri,resolveRelationPredicates as oi}from"./packem_shared/DEFAULT_MAX_RELATION_KEYS-BeTWZQ4X.mjs";import{describeRelationWrites as ti}from"./packem_shared/describeRelationWrites-omar6-u9.mjs";import{applyInsertDefaults as si,applyOnDelete as li,distinctValues as ni,fanOutScalarCounts as di,relationHooks as ci,resolveWith as mi,runRowValidators as pi}from"./packem_shared/applyInsertDefaults-vVfUyiJ2.mjs";import{DEFAULT_PROMOTION_THRESHOLDS as ui,clampPromotionThresholds as fi,nextPromotionState as Ei,relayCountFor as xi,shapeRoutingKey as hi}from"./packem_shared/DEFAULT_PROMOTION_THRESHOLDS-B3pRMuqb.mjs";import{DEFAULT_MAX_RELAYS as Ri,OwnerRelay as Ai,RelayMember as Ci,createRelayLink as gi}from"./packem_shared/DEFAULT_MAX_RELAYS-B6rnl_9a.mjs";import{createReplicaLink as Ii,gateReplicaDispatch as bi,handleReplicaControl as Li}from"./packem_shared/createReplicaLink-CdFOcpSJ.mjs";import{buildReprojectionMigration as Pi,countLegacyRows as Oi,reprojectableFields as yi,reprojectionTables as Fi}from"./packem_shared/buildReprojectionMigration-Ds2JaFo7.mjs";import{RLS_UNWRAP_SYMBOL as Ni,RlsRequiredError as ki,guardWriter as Bi}from"./packem_shared/RLS_UNWRAP_SYMBOL-J1tiBtRj.mjs";import{SCHEMA_HISTORY_MAX_VERSIONS as Gi,readSchemaHistory as wi,readSchemaVersion as qi,recordSchemaVersion as vi}from"./packem_shared/SCHEMA_HISTORY_MAX_VERSIONS-CEwFjj-O.mjs";import{serializeSqlValue as Wi}from"./packem_shared/serializeSqlValue-DeoBMpZ2.mjs";import{buildSettings as Hi,isDevEnvironment as Vi,readDeployInfo as zi}from"./packem_shared/buildSettings-BRkZd6_E.mjs";import{buildShapeDiff as Yi}from"./packem_shared/buildShapeDiff-Dj4NAfQk.mjs";import{ShapeDiffCache as Ji,createShapeDiffCache as Zi,globalShapeReadKey as $i}from"./packem_shared/ShapeDiffCache-iNO-hUiy.mjs";import{buildPokeFrames as rs,diffGlobalMembership as os,encodeRowsPatch as as,projectColumns as ts}from"./packem_shared/buildPokeFrames-WR-hp0mX.mjs";import{ShardRunner as ss}from"./packem_shared/ShardRunner-CrveaPId.mjs";import{RELAY_SIGNATURE_HEADER as ns,siblingSecretOf as ds,signSiblingBody as cs,stubByName as ms,verifySiblingBody as ps}from"./packem_shared/RELAY_SIGNATURE_HEADER-C_P73AOx.mjs";import{runSocketPool as us}from"./packem_shared/runSocketPool-CZJ2X9cF.mjs";import{MAX_SQL_ROWS as Es,assertReadonly as xs,lintReadonlySql as hs,runReadonlySql as Ts}from"./packem_shared/MAX_SQL_ROWS-eRignWyO.mjs";import{BIGINT_KEY_DIGITS as As,bigintSqlKey as Cs,decodeBigintSqlKey as gs,decodeFloat64SqlKey as _s,float64SqlKey as Is}from"./packem_shared/BIGINT_KEY_DIGITS-DE6yshOt.mjs";import{awaitWsDrain as Ls,subscriptionFrames as Ds,subscriptionListDeltas as Ps,trySendFrame as Os}from"./packem_shared/awaitWsDrain-e88vUNdj.mjs";import{mergeChangedKeys as Fs,recordChangedKeys as Ms,writeTouchesMemo as Ns}from"./packem_shared/mergeChangedKeys-BHUURyp6.mjs";import{createSystemReader as Bs}from"./packem_shared/createSystemReader-DcDLFfC-.mjs";import{ConflictError as Gs}from"./packem_shared/ConflictError-C8GtJmjS.mjs";import{DEFAULT_TRANSACTION_LIMITS as qs,TransactionHeadroomTracker as vs}from"./packem_shared/DEFAULT_TRANSACTION_LIMITS-Dmj5VBrV.mjs";import{hasTrigger as Ws,runTriggers as Xs}from"./packem_shared/hasTrigger-CjlwI4le.mjs";import{nextTtlExpiry as Vs,selectExpiredIds as zs}from"./packem_shared/nextTtlExpiry-DhKO_OpO.mjs";import{VECTOR_BACKFILL_MAX_PAGES as Ys,backfillVectorIndexes as js}from"./packem_shared/VECTOR_BACKFILL_MAX_PAGES-zxItOlPE.mjs";import{c as Zs,s as $s}from"./packem_shared/where-sql-BjY4rnqb.mjs";import{RELATION_EXISTS_KEY as rl}from"./packem_shared/RELATION_EXISTS_KEY-wxgj6rSL.mjs";import{REPROJECTION_MIGRATION_PREFIX as al,reprojectionMigrationId as tl}from"./packem_shared/REPROJECTION_MIGRATION_PREFIX-Czcb6_mO.mjs";import{isInternalTableName as sl}from"./packem_shared/isInternalTableName-BoljO2tP.mjs";import{quoteIdentifier as nl}from"./packem_shared/quoteIdentifier-CObIFRhb.mjs";import{runShardMigrations as cl}from"./packem_shared/runShardMigrations-vtuywDTg.mjs";import{stableStringify as pl,stableWireKey as Sl}from"@lunora/wire";export{sa as ADMIN_FUNCTIONS,la as ADMIN_FUNCTION_PREFIX,d as AGGREGATE_SQL_FUNCTION,vr as AGG_COUNT,Kr as AGG_KEY,Wr as AGG_VALUE,D as AUDIT_LOG_TABLE,As as BIGINT_KEY_DIGITS,V as CDC_LOG_TABLE,z as CDC_LOG_TABLE_SEQ_INDEX,Q as CDC_META_TABLE,Ae as CLIENT_WATERMARK_TABLE,be as COMMIT_SEQ_FIELD,Le as COMMIT_SEQ_TABLE,Ha as CURSOR_PREFIX,Gs as ConflictError,A as CountRlsUnsupportedError,Pr as DATA_MIGRATION_STATE_TABLE,na as DEFAULT_FANOUT_TOPIC_LIMIT,jt as DEFAULT_MAX_RELATION_KEYS,Ri as DEFAULT_MAX_RELAYS,ui as DEFAULT_PROMOTION_THRESHOLDS,qs as DEFAULT_TRANSACTION_LIMITS,Xr as DOC_COLUMN,To as DurableStreamRunner,da as FLAGS_FUNCTION_PREFIX,jo as GEO_DEFAULT_PRECISION,Be as GLOBAL_SHAPE_SNAPSHOT_TABLE,ta as GlobalPollTick,We as IDEMPOTENCY_TABLE,La as MAIL_RETENTION,Da as MAIL_TABLE,Ro as MAX_DURABLE_STREAM_BYTES,Ao as MAX_DURABLE_STREAM_CHUNKS,ca as MAX_PAGE_SIZE,Es as MAX_SQL_ROWS,Na as NotFoundError,M as NotUniqueError,Ai as OwnerRelay,it as QUEUE_TABLE,pt as RANK_TIEBREAK,_t as REACTOR_STATE_TABLE,Wt as RELATED_DEFAULT_LIMIT,Xt as RELATED_DEPTH_DECAY,Ht as RELATED_MAX_DEPTH,Vt as RELATED_MAX_LIMIT,rl as RELATION_EXISTS_KEY,ma as RELATION_FUNCTION_PREFIX,ns as RELAY_SIGNATURE_HEADER,al as REPROJECTION_MIGRATION_PREFIX,Ni as RLS_UNWRAP_SYMBOL,At as ReactiveCache,Ci as RelayMember,ki as RlsRequiredError,Mr as SCAN_DEP,or as SCHEDULE_OUTBOX_TABLE,Gi as SCHEMA_HISTORY_MAX_VERSIONS,pr as SEARCH_STATE_TABLE,xr as SHAPE_POKE_CURSOR_TABLE,Ji as ShapeDiffCache,ss as ShardRunner,vs as TransactionHeadroomTracker,yt as UNVOUCHABLE_DEP,Ys as VECTOR_BACKFILL_MAX_PAGES,ao as WORKERD_SQLITE_LIMITS,Ce as advanceClientWatermark,Hr as aggUpsertSql,c as aggregateSqlFunction,f as aggregateTableName,De as allocateCommitSeq,P as appendAuditEntry,Y as appendCdcChange,co as appendStreamChunk,j as applyCdcChanges,si as applyInsertDefaults,li as applyOnDelete,Va as applySelect,fe as archiveCdcSegment,Ka as armRestore,Jt as assertFlatPredicate,N as assertNoExplicitUndefined,Ba as assertPatchAllowed,xs as assertReadonly,Zt as assertShapeShardable,k as assertStorableRowId,B as assertValidClientId,Ls as awaitWsDrain,v as backfillAggregateIndexes,K as backfillRankIndexes,W as backfillSearchIndexes,X as backfillSearchIndexesForTable,js as backfillVectorIndexes,Cs as bigintSqlKey,Jo as boundingBoxCenter,Zo as boundingBoxGeohashes,kt as buildIndexRange,rs as buildPokeFrames,Pi as buildReprojectionMigration,za as buildSeekBeforeWhere,Qa as buildSeekWhere,Hi as buildSettings,Yi as buildShapeDiff,J as bumpCdcEpoch,Ee as cdcArchiveRewound,Z as cdcCanVouchFor,$ as cdcForkedError,ee as cdcSeqLeavingRows,re as cdcTouchesTables,oe as cdcTrimmedError,mo as claimStreamRun,fi as clampPromotionThresholds,Pa as clearCapturedMail,Fe as clearCompanionSignatures,Ye as clearMemoryTables,st as clearQueueMessages,E as coerceAggregateNumber,ae as compactCdcDocs,Zs as compileWhereSql,$t as composeReadPredicate,$e as computeRankPage,ei as containsRelationPredicate,Oi as countLegacyRows,$o as coveringGeohashes,Ne as createCompanionSync,Nr as createDependencyTracker,pa as createFanoutCounters,Sa as createGlobalPollCounters,Vr as createIndexSql,Ft as createReadFootprint,gi as createRelayLink,Ii as createReplicaLink,Zi as createShapeDiffCache,ua as createShapeProbeCounters,U as createShardCtxDb,Bs as createSystemReader,te as cursorBelowRetainedFloor,Co as decideDurableAttach,gs as decodeBigintSqlKey,Ya as decodeCursor,_s as decodeFloat64SqlKey,ar as deferScheduleOutbox,Ue as deleteGlobalShapeSnapshot,Ge as deleteGlobalShapeSnapshotsForConnection,hr as deleteShapePokeCursor,Tr as deleteShapePokeCursorsForConnection,po as deleteStreamRun,kr as depKey,zt as deriveRelationEdges,ti as describeRelationWrites,Lo as diffExternalSource,os as diffGlobalMembership,ni as distinctValues,x as encodeAggregateKey,ja as encodeCursor,ea as encodeGeohash,St as encodePartitionKey,as as encodeRowsPatch,O as ensureAuditTable,Oa as ensureMailTable,_o as envOptionalPositiveInt,Io as envPositiveInt,Ja as equalityPinnedFields,o as exportShardRows,fa as facetColumn,di as fanOutScalarCounts,Qt as findRelated,Ea as findStorageReferences,So as finishStreamRun,Is as float64SqlKey,h as foldAggregateTally,tr as forgetScheduleOutbox,Wo as ftsCompanionDdl,Xo as ftsPurgeDocument,Ho as ftsRowidMapName,Vo as ftsUnmappedPage,zo as ftsWriteDocument,bi as gateReplicaDispatch,zr as geoTableName,$i as globalShapeReadKey,Qo as groupUnmappedRows,Bi as guardWriter,Li as handleReplicaControl,Ws as hasTrigger,ra as haversineMeters,a as importShardRows,Bt as indexKeysForRow,Vi as isDevEnvironment,Qr as isFtsAvailable,sl as isInternalTableName,lt as isLossyBody,je as isMemoryTable,wt as isPushableWhere,ri as isRelationPredicate,Go as isSoftDeleted,wo as isSourceDue,xa as isVacuousFilterClause,Yr as jsonPath,jr as jsonPathSql,Ut as keysTouchRanges,Po as liftSourceId,hs as lintReadonlySql,It as listReactorStates,ha as listTables,Mt as markUnvouchableReads,ut as matchesRankStaticWhere,m as matchesStaticWhere,Mo as materializeExternalRows,No as materializeExternalRowsIncremental,Je as memoryTableNames,Fs as mergeChangedKeys,C as mergeWhere,ie as migrateCdcLog,se as migrateCdcMeta,ge as migrateClientWatermark,Pe as migrateCommitSeq,uo as migrateDurableStreams,we as migrateGlobalShapeSnapshot,Xe as migrateIdempotency,bt as migrateReactorState,ir as migrateScheduleOutbox,Sr as migrateSearchState,Rr as migrateShapePokeCursor,le as minCdcReplayableSeq,ne as minCdcSeq,Ar as minShapePokeCursor,Ei as nextPromotionState,Vs as nextTtlExpiry,p as normalizeCountArgument,G as normalizeIdStructurally,Za as normalizeOrderKeys,Oo as normalizeSourceDocument,yo as normalizeSourceValue,$a as nullsFirstOf,et as nullsOrderSuffix,Ua as operatorFields,to as param,sr as parkScheduleOutbox,t as parseExportShardArgs,i as parseImportShardArgs,Ga as patchDependsOnRow,g as planAggregateLookup,oa as pointInBoundingBox,lr as probeScheduleOutbox,ts as projectColumns,qo as pullExternalSourceIncrementalTick,vo as pullExternalSourceTick,Jr as qualifiedJsonPath,Zr as qualifiedJsonPathSql,nl as quoteIdentifier,ft as rankKeyFromDoc,Et as rankPivotConditionSql,xt as rankTableName,Ct as reactiveCacheKey,Lt as reactorNeedsRun,T as readAggregateValue,xe as readArchivedCdcChanges,y as readAuditLog,Wa as readBookmark,ya as readCapturedMail,he as readCdcArchivedThrough,de as readCdcChangeKeys,ce as readCdcChanges,me as readCdcCursor,pe as readCdcEpoch,_e as readClientWatermark,Oe as readCommitSeq,zi as readDeployInfo,nr as readDueScheduleOutbox,ko as readExternalSourceBaseline,qe as readGlobalShapeSnapshot,He as readIdempotent,Or as readMigrationStatus,wa as readPatchField,nt as readQueueMessageById,dt as readQueueMessages,Dt as readReactorState,wi as readSchemaHistory,qi as readSchemaVersion,ur as readSearchBackfillState,Cr as readShapePokeCursor,fo as readStreamChunks,Eo as readStreamRun,Ta as readTablePage,Fa as recordCapturedMail,Ms as recordChangedKeys,Ra as recordFanoutPass,Aa as recordGlobalPollPass,ct as recordQueueMessages,dr as recordScheduleOutbox,vi as recordSchemaVersion,Ca as recordShapeProbePass,ci as relationHooks,xi as relayCountFor,io as renderSql,yi as reprojectableFields,tl as reprojectionMigrationId,Fi as reprojectionTables,qa as resolvePatch,ht as resolveRankPartition,er as resolveRankSeekTuple,oi as resolveRelationPredicates,mi as resolveWith,$r as rowToDocument,yr as runDataMigration,Gr as runDrizzle,Bo as runExternalSourceTick,Ts as runReadonlySql,pi as runRowValidators,cl as runShardMigrations,us as runSocketPool,wr as runSql,Xs as runTriggers,zs as selectExpiredIds,s as selectExportTables,_ as selectIndexForAggregate,I as selectIndexForCount,b as selectIndexForGroupBy,ga as selectMatchingIds,br as selectShapeMembers,Lr as selectShapeRows,Wi as serializeSqlValue,$s as serverInList,hi as shapeRoutingKey,ds as siblingSecretOf,cs as signSiblingBody,rt as softDeleteScope,Tt as sortColumnName,so as sqliteInList,pl as stableStringify,Sl as stableWireKey,w as stripReservedPatchFields,ms as stubByName,Ds as subscriptionFrames,Ps as subscriptionListDeltas,_a as summarizeFanoutTopics,Ia as summarizeSubscriptions,eo as tableColumns,Br as tableFromDepKey,S as throwingScheduler,ot as tiebreakDirectionFor,Se as trimCdcChanges,Ve as trimIdempotent,cr as trimScheduleOutbox,xo as trimStreamRuns,ro as tryRowToDocument,Os as trySendFrame,lo as unionAll,at as uniqueIndexFields,l as validateImportRow,ps as verifySiblingBody,qt as whereFilter,vt as whereOfFilter,Te as writeCdcArchivedThrough,ve as writeGlobalShapeSnapshot,ze as writeIdempotent,Pt as writeReactorState,fr as writeSearchBackfillState,gr as writeShapePokeCursor,_r as writeShapePokeCursors,Ns as writeTouchesMemo};
|
|
1
|
+
import{exportShardRows as o,importShardRows as a,parseExportShardArgs as t,parseImportShardArgs as i,selectExportTables as s,validateImportRow as l}from"./packem_shared/exportShardRows-b0pfdTXz.mjs";import{AGGREGATE_SQL_FUNCTION as d,aggregateSqlFunction as c,matchesStaticWhere as m,normalizeCountArgument as p,throwingScheduler as S}from"./packem_shared/AGGREGATE_SQL_FUNCTION-C_ZipS9R.mjs";import{aggregateTableName as f,coerceAggregateNumber as E,encodeAggregateKey as x,foldAggregateTally as h,readAggregateValue as T}from"./packem_shared/aggregateTableName-B_CtIQCS.mjs";import{CountRlsUnsupportedError as A,mergeWhere as C,planAggregateLookup as g,selectIndexForAggregate as _,selectIndexForCount as I,selectIndexForGroupBy as b}from"./packem_shared/CountRlsUnsupportedError-BvsDqfO2.mjs";import{AUDIT_LOG_TABLE as D,appendAuditEntry as P,ensureAuditTable as O,readAuditLog as M}from"./packem_shared/AUDIT_LOG_TABLE-BFJ65SRS.mjs";import{NotUniqueError as F,assertNoExplicitUndefined as N,assertStorableRowId as k,assertValidClientId as B,createShardCtxDb as U,normalizeIdStructurally as G,stripReservedPatchFields as w}from"./packem_shared/NotUniqueError-C8ZpTDHV.mjs";import{backfillAggregateIndexes as v,backfillRankIndexes as K,backfillSearchIndexes as W,backfillSearchIndexesForTable as X}from"./packem_shared/backfillAggregateIndexes-BN0NwXQk.mjs";import{CDC_LOG_TABLE as V,CDC_LOG_TABLE_SEQ_INDEX as z,CDC_META_TABLE as Q,appendCdcChange as Y,applyCdcChanges as j,bumpCdcEpoch as J,cdcCanVouchFor as Z,cdcForkedError as $,cdcSeqLeavingRows as ee,cdcTouchesTables as re,cdcTrimmedError as oe,compactCdcDocs as ae,cursorBelowRetainedFloor as te,migrateCdcLog as ie,migrateCdcMeta as se,minCdcReplayableSeq as le,minCdcSeq as ne,readCdcChangeKeys as de,readCdcChanges as ce,readCdcCursor as me,readCdcEpoch as pe,trimCdcChanges as Se}from"./packem_shared/CDC_LOG_TABLE-Dgwxv7yf.mjs";import{archiveCdcSegment as fe,cdcArchiveRewound as Ee,readArchivedCdcChanges as xe,readCdcArchivedThrough as he,writeCdcArchivedThrough as Te}from"./packem_shared/archiveCdcSegment-Cr8oGLfB.mjs";import{CLIENT_WATERMARK_TABLE as Ae,advanceClientWatermark as Ce,migrateClientWatermark as ge,readClientWatermark as _e}from"./packem_shared/CLIENT_WATERMARK_TABLE-De7z_OHV.mjs";import{COMMIT_SEQ_FIELD as be,COMMIT_SEQ_TABLE as Le,allocateCommitSeq as De,migrateCommitSeq as Pe,readCommitSeq as Oe}from"./packem_shared/COMMIT_SEQ_FIELD-Da1DjGqo.mjs";import{CompanionMemo as ye,clearCompanionSignatures as Fe}from"./packem_shared/CompanionMemo-BXU5vfak.mjs";import{createCompanionSync as ke}from"./packem_shared/createCompanionSync-zIF_F4oD.mjs";import{GLOBAL_SHAPE_SNAPSHOT_TABLE as Ue,deleteGlobalShapeSnapshot as Ge,deleteGlobalShapeSnapshotsForConnection as we,migrateGlobalShapeSnapshot as qe,readGlobalShapeSnapshot as ve,writeGlobalShapeSnapshot as Ke}from"./packem_shared/GLOBAL_SHAPE_SNAPSHOT_TABLE-Bb6-aZuH.mjs";import{IDEMPOTENCY_TABLE as Xe,migrateIdempotency as He,readIdempotent as Ve,trimIdempotent as ze,writeIdempotent as Qe}from"./packem_shared/IDEMPOTENCY_TABLE-COrgeP3O.mjs";import{clearMemoryTables as je,isMemoryTable as Je,memoryTableNames as Ze}from"./packem_shared/clearMemoryTables-aMRERF0w.mjs";import{computeRankPage as er,resolveRankSeekTuple as rr}from"./packem_shared/computeRankPage-BZIpATcs.mjs";import{SCHEDULE_OUTBOX_TABLE as ar,deferScheduleOutbox as tr,forgetScheduleOutbox as ir,migrateScheduleOutbox as sr,parkScheduleOutbox as lr,probeScheduleOutbox as nr,readDueScheduleOutbox as dr,recordScheduleOutbox as cr,trimScheduleOutbox as mr}from"./packem_shared/SCHEDULE_OUTBOX_TABLE-DcZI7Yhl.mjs";import{S as Sr,m as ur,r as fr,w as Er}from"./packem_shared/ctx-db-search-state-FjgzTFok.mjs";import{SHAPE_POKE_CURSOR_TABLE as hr,deleteShapePokeCursor as Tr,deleteShapePokeCursorsForConnection as Rr,migrateShapePokeCursor as Ar,minShapePokeCursor as Cr,readShapePokeCursor as gr,writeShapePokeCursor as _r,writeShapePokeCursors as Ir}from"./packem_shared/SHAPE_POKE_CURSOR_TABLE-BGvY3sFI.mjs";import{selectShapeMembers as Lr,selectShapeRows as Dr}from"./packem_shared/selectShapeMembers-BCfKypfN.mjs";import{DATA_MIGRATION_STATE_TABLE as Or,readMigrationStatus as Mr,runDataMigration as yr}from"./packem_shared/DATA_MIGRATION_STATE_TABLE-D1FtktFp.mjs";import{SCAN_DEP as Nr,createDependencyTracker as kr,depKey as Br,tableFromDepKey as Ur}from"./packem_shared/SCAN_DEP-D7qE3iUe.mjs";import{runDrizzle as wr,runSql as qr}from"./packem_shared/runDrizzle-RC09zZrh.mjs";import{A as Kr,a as Wr,b as Xr,D as Hr,c as Vr,d as zr,g as Qr,i as Yr,j as jr,e as Jr,q as Zr,f as $r,r as eo,t as ro,h as oo}from"./packem_shared/do-sql-BWrJQAOh.mjs";import{WORKERD_SQLITE_LIMITS as to,param as io,renderSql as so,sqliteInList as lo,unionAll as no}from"./packem_shared/WORKERD_SQLITE_LIMITS-B_4w7tzY.mjs";import{appendStreamChunk as mo,claimStreamRun as po,deleteStreamRun as So,finishStreamRun as uo,migrateDurableStreams as fo,readStreamChunks as Eo,readStreamRun as xo,trimStreamRuns as ho}from"./packem_shared/appendStreamChunk-BZYgGE9Y.mjs";import{DurableStreamRunner as Ro,MAX_DURABLE_STREAM_BYTES as Ao,MAX_DURABLE_STREAM_CHUNKS as Co,decideDurableAttach as go}from"./packem_shared/DurableStreamRunner-MMlV5qKQ.mjs";import{envOptionalPositiveInt as Io,envPositiveInt as bo}from"./packem_shared/envOptionalPositiveInt-D2pY-c64.mjs";import{diffExternalSource as Do}from"./packem_shared/diffExternalSource-B0FZlDoL.mjs";import{liftSourceId as Oo,normalizeSourceDocument as Mo,normalizeSourceValue as yo}from"./packem_shared/liftSourceId-CA3ENhXj.mjs";import{materializeExternalRows as No,materializeExternalRowsIncremental as ko,readExternalSourceBaseline as Bo,runExternalSourceTick as Uo}from"./packem_shared/materializeExternalRows-DZnatu1U.mjs";import{isSoftDeleted as wo,isSourceDue as qo,pullExternalSourceIncrementalTick as vo,pullExternalSourceTick as Ko}from"./packem_shared/isSoftDeleted-kHKo4Oku.mjs";import{f as Xo,a as Ho,b as Vo,c as zo,d as Qo,g as Yo}from"./packem_shared/fts-companion-CA8mLJWq.mjs";import{GEO_DEFAULT_PRECISION as Jo,boundingBoxCenter as Zo,boundingBoxGeohashes as $o,coveringGeohashes as ea,encodeGeohash as ra,haversineMeters as oa,pointInBoundingBox as aa}from"./packem_shared/GEO_DEFAULT_PRECISION-CqpQZ-J_.mjs";import{default as ia}from"./packem_shared/GlobalPollTick-BNK4o-XT.mjs";import{ADMIN_FUNCTIONS as la,ADMIN_FUNCTION_PREFIX as na,DEFAULT_FANOUT_TOPIC_LIMIT as da,FLAGS_FUNCTION_PREFIX as ca,MAX_PAGE_SIZE as ma,RELATION_FUNCTION_PREFIX as pa,createFanoutCounters as Sa,createGlobalPollCounters as ua,createShapeProbeCounters as fa,facetColumn as Ea,findStorageReferences as xa,isVacuousFilterClause as ha,listTables as Ta,readTablePage as Ra,recordFanoutPass as Aa,recordGlobalPollPass as Ca,recordShapeProbePass as ga,selectMatchingIds as _a,summarizeFanoutTopics as Ia,summarizeSubscriptions as ba}from"./packem_shared/ADMIN_FUNCTIONS-CPXCHyOg.mjs";import{MAIL_RETENTION as Da,MAIL_TABLE as Pa,clearCapturedMail as Oa,ensureMailTable as Ma,readCapturedMail as ya,recordCapturedMail as Fa}from"./packem_shared/MAIL_RETENTION-DMolrLYt.mjs";import{NotFoundError as ka}from"./packem_shared/NotFoundError-BhF7FeFr.mjs";import{assertPatchAllowed as Ua,operatorFields as Ga,patchDependsOnRow as wa,readPatchField as qa,resolvePatch as va}from"./packem_shared/assertPatchAllowed-CA_H466g.mjs";import{armRestore as Wa,readBookmark as Xa}from"./packem_shared/armRestore-Bu1_8SUa.mjs";import{CURSOR_PREFIX as Va,applySelect as za,buildSeekBeforeWhere as Qa,buildSeekWhere as Ya,decodeCursor as ja,encodeCursor as Ja,equalityPinnedFields as Za,normalizeOrderKeys as $a,nullsFirstOf as et,nullsOrderSuffix as rt,softDeleteScope as ot,tiebreakDirectionFor as at,uniqueIndexFields as tt}from"./packem_shared/CURSOR_PREFIX-6offuG6M.mjs";import{QUEUE_TABLE as st,clearQueueMessages as lt,isLossyBody as nt,readQueueMessageById as dt,readQueueMessages as ct,recordQueueMessages as mt}from"./packem_shared/QUEUE_TABLE-C-goXtGd.mjs";import{RANK_TIEBREAK as St,encodePartitionKey as ut,matchesRankStaticWhere as ft,rankKeyFromDoc as Et,rankPivotConditionSql as xt,rankTableName as ht,resolveRankPartition as Tt,sortColumnName as Rt}from"./packem_shared/RANK_TIEBREAK-D3ye2GsL.mjs";import{ReactiveCache as Ct,reactiveCacheKey as gt}from"./packem_shared/ReactiveCache-DHhhLJtN.mjs";import{REACTOR_STATE_TABLE as It,listReactorStates as bt,migrateReactorState as Lt,reactorNeedsRun as Dt,readReactorState as Pt,writeReactorState as Ot}from"./packem_shared/REACTOR_STATE_TABLE-D2Mn204f.mjs";import{UNVOUCHABLE_DEP as yt,createReadFootprint as Ft,markUnvouchableReads as Nt}from"./packem_shared/UNVOUCHABLE_DEP-C68htACn.mjs";import{buildIndexRange as Bt,indexKeysForRow as Ut,keysTouchRanges as Gt}from"./packem_shared/buildIndexRange-DQ3eWAGd.mjs";import{isPushableWhere as qt,whereFilter as vt,whereOfFilter as Kt}from"./packem_shared/isPushableWhere-BeYAOjUb.mjs";import{RELATED_DEFAULT_LIMIT as Xt,RELATED_DEPTH_DECAY as Ht,RELATED_MAX_DEPTH as Vt,RELATED_MAX_LIMIT as zt,deriveRelationEdges as Qt,findRelated as Yt}from"./packem_shared/RELATED_DEFAULT_LIMIT-CVqN4JEu.mjs";import{DEFAULT_MAX_RELATION_KEYS as Jt,assertFlatPredicate as Zt,assertShapeShardable as $t,composeReadPredicate as ei,containsRelationPredicate as ri,isRelationPredicate as oi,resolveRelationPredicates as ai}from"./packem_shared/DEFAULT_MAX_RELATION_KEYS-9eOkadE4.mjs";import{describeRelationWrites as ii}from"./packem_shared/describeRelationWrites-omar6-u9.mjs";import{applyInsertDefaults as li,applyOnDelete as ni,distinctValues as di,fanOutScalarCounts as ci,relationHooks as mi,resolveWith as pi,runRowValidators as Si}from"./packem_shared/applyInsertDefaults-B0NXPs2x.mjs";import{DEFAULT_PROMOTION_THRESHOLDS as fi,clampPromotionThresholds as Ei,nextPromotionState as xi,relayCountFor as hi,shapeRoutingKey as Ti}from"./packem_shared/DEFAULT_PROMOTION_THRESHOLDS-B3pRMuqb.mjs";import{DEFAULT_MAX_RELAYS as Ai,OwnerRelay as Ci,RelayMember as gi,createRelayLink as _i}from"./packem_shared/DEFAULT_MAX_RELAYS-B6rnl_9a.mjs";import{createReplicaLink as bi,gateReplicaDispatch as Li,handleReplicaControl as Di}from"./packem_shared/createReplicaLink-CdFOcpSJ.mjs";import{buildReprojectionMigration as Oi,countLegacyRows as Mi,reprojectableFields as yi,reprojectionTables as Fi}from"./packem_shared/buildReprojectionMigration-Ds2JaFo7.mjs";import{RLS_UNWRAP_SYMBOL as ki,RlsRequiredError as Bi,guardWriter as Ui}from"./packem_shared/RLS_UNWRAP_SYMBOL-J1tiBtRj.mjs";import{SCHEMA_HISTORY_MAX_VERSIONS as wi,readSchemaHistory as qi,readSchemaVersion as vi,recordSchemaVersion as Ki}from"./packem_shared/SCHEMA_HISTORY_MAX_VERSIONS-CEwFjj-O.mjs";import{serializeSqlValue as Xi}from"./packem_shared/serializeSqlValue-DeoBMpZ2.mjs";import{buildSettings as Vi,isDevEnvironment as zi,readDeployInfo as Qi}from"./packem_shared/buildSettings-BRkZd6_E.mjs";import{buildShapeDiff as ji}from"./packem_shared/buildShapeDiff-Dj4NAfQk.mjs";import{ShapeDiffCache as Zi,createShapeDiffCache as $i,globalShapeReadKey as es}from"./packem_shared/ShapeDiffCache-iNO-hUiy.mjs";import{buildPokeFrames as os,diffGlobalMembership as as,encodeRowsPatch as ts,projectColumns as is}from"./packem_shared/buildPokeFrames-WR-hp0mX.mjs";import{ShardRunner as ls}from"./packem_shared/ShardRunner-CrveaPId.mjs";import{RELAY_SIGNATURE_HEADER as ds,siblingSecretOf as cs,signSiblingBody as ms,stubByName as ps,verifySiblingBody as Ss}from"./packem_shared/RELAY_SIGNATURE_HEADER-C_P73AOx.mjs";import{runSocketPool as fs}from"./packem_shared/runSocketPool-CZJ2X9cF.mjs";import{MAX_SQL_ROWS as xs,assertReadonly as hs,lintReadonlySql as Ts,runReadonlySql as Rs}from"./packem_shared/MAX_SQL_ROWS-eRignWyO.mjs";import{BIGINT_KEY_DIGITS as Cs,bigintSqlKey as gs,decodeBigintSqlKey as _s,decodeFloat64SqlKey as Is,float64SqlKey as bs}from"./packem_shared/BIGINT_KEY_DIGITS-DE6yshOt.mjs";import{awaitWsDrain as Ds,subscriptionFrames as Ps,subscriptionListDeltas as Os,trySendFrame as Ms}from"./packem_shared/awaitWsDrain-e88vUNdj.mjs";import{mergeChangedKeys as Fs,recordChangedKeys as Ns,writeTouchesMemo as ks}from"./packem_shared/mergeChangedKeys-BHUURyp6.mjs";import{createSystemReader as Us}from"./packem_shared/createSystemReader-DcDLFfC-.mjs";import{ConflictError as ws}from"./packem_shared/ConflictError-C8GtJmjS.mjs";import{DEFAULT_TRANSACTION_LIMITS as vs,TransactionHeadroomTracker as Ks}from"./packem_shared/DEFAULT_TRANSACTION_LIMITS-Dmj5VBrV.mjs";import{hasTrigger as Xs,runTriggers as Hs}from"./packem_shared/hasTrigger-CjlwI4le.mjs";import{nextTtlExpiry as zs,selectExpiredIds as Qs}from"./packem_shared/nextTtlExpiry-DhKO_OpO.mjs";import{VECTOR_BACKFILL_MAX_PAGES as js,backfillVectorIndexes as Js}from"./packem_shared/VECTOR_BACKFILL_MAX_PAGES-loOUGfzw.mjs";import{c as $s,s as el}from"./packem_shared/where-sql-BjY4rnqb.mjs";import{RELATION_EXISTS_KEY as ol}from"./packem_shared/RELATION_EXISTS_KEY-wxgj6rSL.mjs";import{REPROJECTION_MIGRATION_PREFIX as tl,reprojectionMigrationId as il}from"./packem_shared/REPROJECTION_MIGRATION_PREFIX-Czcb6_mO.mjs";import{isInternalTableName as ll}from"./packem_shared/isInternalTableName-BoljO2tP.mjs";import{quoteIdentifier as dl}from"./packem_shared/quoteIdentifier-CObIFRhb.mjs";import{runShardMigrations as ml}from"./packem_shared/runShardMigrations-DsrVE2Kq.mjs";import{stableStringify as Sl,stableWireKey as ul}from"@lunora/wire";export{la as ADMIN_FUNCTIONS,na as ADMIN_FUNCTION_PREFIX,d as AGGREGATE_SQL_FUNCTION,Kr as AGG_COUNT,Wr as AGG_KEY,Xr as AGG_VALUE,D as AUDIT_LOG_TABLE,Cs as BIGINT_KEY_DIGITS,V as CDC_LOG_TABLE,z as CDC_LOG_TABLE_SEQ_INDEX,Q as CDC_META_TABLE,Ae as CLIENT_WATERMARK_TABLE,be as COMMIT_SEQ_FIELD,Le as COMMIT_SEQ_TABLE,Va as CURSOR_PREFIX,ye as CompanionMemo,ws as ConflictError,A as CountRlsUnsupportedError,Or as DATA_MIGRATION_STATE_TABLE,da as DEFAULT_FANOUT_TOPIC_LIMIT,Jt as DEFAULT_MAX_RELATION_KEYS,Ai as DEFAULT_MAX_RELAYS,fi as DEFAULT_PROMOTION_THRESHOLDS,vs as DEFAULT_TRANSACTION_LIMITS,Hr as DOC_COLUMN,Ro as DurableStreamRunner,ca as FLAGS_FUNCTION_PREFIX,Jo as GEO_DEFAULT_PRECISION,Ue as GLOBAL_SHAPE_SNAPSHOT_TABLE,ia as GlobalPollTick,Xe as IDEMPOTENCY_TABLE,Da as MAIL_RETENTION,Pa as MAIL_TABLE,Ao as MAX_DURABLE_STREAM_BYTES,Co as MAX_DURABLE_STREAM_CHUNKS,ma as MAX_PAGE_SIZE,xs as MAX_SQL_ROWS,ka as NotFoundError,F as NotUniqueError,Ci as OwnerRelay,st as QUEUE_TABLE,St as RANK_TIEBREAK,It as REACTOR_STATE_TABLE,Xt as RELATED_DEFAULT_LIMIT,Ht as RELATED_DEPTH_DECAY,Vt as RELATED_MAX_DEPTH,zt as RELATED_MAX_LIMIT,ol as RELATION_EXISTS_KEY,pa as RELATION_FUNCTION_PREFIX,ds as RELAY_SIGNATURE_HEADER,tl as REPROJECTION_MIGRATION_PREFIX,ki as RLS_UNWRAP_SYMBOL,Ct as ReactiveCache,gi as RelayMember,Bi as RlsRequiredError,Nr as SCAN_DEP,ar as SCHEDULE_OUTBOX_TABLE,wi as SCHEMA_HISTORY_MAX_VERSIONS,Sr as SEARCH_STATE_TABLE,hr as SHAPE_POKE_CURSOR_TABLE,Zi as ShapeDiffCache,ls as ShardRunner,Ks as TransactionHeadroomTracker,yt as UNVOUCHABLE_DEP,js as VECTOR_BACKFILL_MAX_PAGES,to as WORKERD_SQLITE_LIMITS,Ce as advanceClientWatermark,Vr as aggUpsertSql,c as aggregateSqlFunction,f as aggregateTableName,De as allocateCommitSeq,P as appendAuditEntry,Y as appendCdcChange,mo as appendStreamChunk,j as applyCdcChanges,li as applyInsertDefaults,ni as applyOnDelete,za as applySelect,fe as archiveCdcSegment,Wa as armRestore,Zt as assertFlatPredicate,N as assertNoExplicitUndefined,Ua as assertPatchAllowed,hs as assertReadonly,$t as assertShapeShardable,k as assertStorableRowId,B as assertValidClientId,Ds as awaitWsDrain,v as backfillAggregateIndexes,K as backfillRankIndexes,W as backfillSearchIndexes,X as backfillSearchIndexesForTable,Js as backfillVectorIndexes,gs as bigintSqlKey,Zo as boundingBoxCenter,$o as boundingBoxGeohashes,Bt as buildIndexRange,os as buildPokeFrames,Oi as buildReprojectionMigration,Qa as buildSeekBeforeWhere,Ya as buildSeekWhere,Vi as buildSettings,ji as buildShapeDiff,J as bumpCdcEpoch,Ee as cdcArchiveRewound,Z as cdcCanVouchFor,$ as cdcForkedError,ee as cdcSeqLeavingRows,re as cdcTouchesTables,oe as cdcTrimmedError,po as claimStreamRun,Ei as clampPromotionThresholds,Oa as clearCapturedMail,Fe as clearCompanionSignatures,je as clearMemoryTables,lt as clearQueueMessages,E as coerceAggregateNumber,ae as compactCdcDocs,$s as compileWhereSql,ei as composeReadPredicate,er as computeRankPage,ri as containsRelationPredicate,Mi as countLegacyRows,ea as coveringGeohashes,ke as createCompanionSync,kr as createDependencyTracker,Sa as createFanoutCounters,ua as createGlobalPollCounters,zr as createIndexSql,Ft as createReadFootprint,_i as createRelayLink,bi as createReplicaLink,$i as createShapeDiffCache,fa as createShapeProbeCounters,U as createShardCtxDb,Us as createSystemReader,te as cursorBelowRetainedFloor,go as decideDurableAttach,_s as decodeBigintSqlKey,ja as decodeCursor,Is as decodeFloat64SqlKey,tr as deferScheduleOutbox,Ge as deleteGlobalShapeSnapshot,we as deleteGlobalShapeSnapshotsForConnection,Tr as deleteShapePokeCursor,Rr as deleteShapePokeCursorsForConnection,So as deleteStreamRun,Br as depKey,Qt as deriveRelationEdges,ii as describeRelationWrites,Do as diffExternalSource,as as diffGlobalMembership,di as distinctValues,x as encodeAggregateKey,Ja as encodeCursor,ra as encodeGeohash,ut as encodePartitionKey,ts as encodeRowsPatch,O as ensureAuditTable,Ma as ensureMailTable,Io as envOptionalPositiveInt,bo as envPositiveInt,Za as equalityPinnedFields,o as exportShardRows,Ea as facetColumn,ci as fanOutScalarCounts,Yt as findRelated,xa as findStorageReferences,uo as finishStreamRun,bs as float64SqlKey,h as foldAggregateTally,ir as forgetScheduleOutbox,Xo as ftsCompanionDdl,Ho as ftsPurgeDocument,Vo as ftsRowidMapName,zo as ftsUnmappedPage,Qo as ftsWriteDocument,Li as gateReplicaDispatch,Qr as geoTableName,es as globalShapeReadKey,Yo as groupUnmappedRows,Ui as guardWriter,Di as handleReplicaControl,Xs as hasTrigger,oa as haversineMeters,a as importShardRows,Ut as indexKeysForRow,zi as isDevEnvironment,Yr as isFtsAvailable,ll as isInternalTableName,nt as isLossyBody,Je as isMemoryTable,qt as isPushableWhere,oi as isRelationPredicate,wo as isSoftDeleted,qo as isSourceDue,ha as isVacuousFilterClause,jr as jsonPath,Jr as jsonPathSql,Gt as keysTouchRanges,Oo as liftSourceId,Ts as lintReadonlySql,bt as listReactorStates,Ta as listTables,Nt as markUnvouchableReads,ft as matchesRankStaticWhere,m as matchesStaticWhere,No as materializeExternalRows,ko as materializeExternalRowsIncremental,Ze as memoryTableNames,Fs as mergeChangedKeys,C as mergeWhere,ie as migrateCdcLog,se as migrateCdcMeta,ge as migrateClientWatermark,Pe as migrateCommitSeq,fo as migrateDurableStreams,qe as migrateGlobalShapeSnapshot,He as migrateIdempotency,Lt as migrateReactorState,sr as migrateScheduleOutbox,ur as migrateSearchState,Ar as migrateShapePokeCursor,le as minCdcReplayableSeq,ne as minCdcSeq,Cr as minShapePokeCursor,xi as nextPromotionState,zs as nextTtlExpiry,p as normalizeCountArgument,G as normalizeIdStructurally,$a as normalizeOrderKeys,Mo as normalizeSourceDocument,yo as normalizeSourceValue,et as nullsFirstOf,rt as nullsOrderSuffix,Ga as operatorFields,io as param,lr as parkScheduleOutbox,t as parseExportShardArgs,i as parseImportShardArgs,wa as patchDependsOnRow,g as planAggregateLookup,aa as pointInBoundingBox,nr as probeScheduleOutbox,is as projectColumns,vo as pullExternalSourceIncrementalTick,Ko as pullExternalSourceTick,Zr as qualifiedJsonPath,$r as qualifiedJsonPathSql,dl as quoteIdentifier,Et as rankKeyFromDoc,xt as rankPivotConditionSql,ht as rankTableName,gt as reactiveCacheKey,Dt as reactorNeedsRun,T as readAggregateValue,xe as readArchivedCdcChanges,M as readAuditLog,Xa as readBookmark,ya as readCapturedMail,he as readCdcArchivedThrough,de as readCdcChangeKeys,ce as readCdcChanges,me as readCdcCursor,pe as readCdcEpoch,_e as readClientWatermark,Oe as readCommitSeq,Qi as readDeployInfo,dr as readDueScheduleOutbox,Bo as readExternalSourceBaseline,ve as readGlobalShapeSnapshot,Ve as readIdempotent,Mr as readMigrationStatus,qa as readPatchField,dt as readQueueMessageById,ct as readQueueMessages,Pt as readReactorState,qi as readSchemaHistory,vi as readSchemaVersion,fr as readSearchBackfillState,gr as readShapePokeCursor,Eo as readStreamChunks,xo as readStreamRun,Ra as readTablePage,Fa as recordCapturedMail,Ns as recordChangedKeys,Aa as recordFanoutPass,Ca as recordGlobalPollPass,mt as recordQueueMessages,cr as recordScheduleOutbox,Ki as recordSchemaVersion,ga as recordShapeProbePass,mi as relationHooks,hi as relayCountFor,so as renderSql,yi as reprojectableFields,il as reprojectionMigrationId,Fi as reprojectionTables,va as resolvePatch,Tt as resolveRankPartition,rr as resolveRankSeekTuple,ai as resolveRelationPredicates,pi as resolveWith,eo as rowToDocument,yr as runDataMigration,wr as runDrizzle,Uo as runExternalSourceTick,Rs as runReadonlySql,Si as runRowValidators,ml as runShardMigrations,fs as runSocketPool,qr as runSql,Hs as runTriggers,Qs as selectExpiredIds,s as selectExportTables,_ as selectIndexForAggregate,I as selectIndexForCount,b as selectIndexForGroupBy,_a as selectMatchingIds,Lr as selectShapeMembers,Dr as selectShapeRows,Xi as serializeSqlValue,el as serverInList,Ti as shapeRoutingKey,cs as siblingSecretOf,ms as signSiblingBody,ot as softDeleteScope,Rt as sortColumnName,lo as sqliteInList,Sl as stableStringify,ul as stableWireKey,w as stripReservedPatchFields,ps as stubByName,Ps as subscriptionFrames,Os as subscriptionListDeltas,Ia as summarizeFanoutTopics,ba as summarizeSubscriptions,ro as tableColumns,Ur as tableFromDepKey,S as throwingScheduler,at as tiebreakDirectionFor,Se as trimCdcChanges,ze as trimIdempotent,mr as trimScheduleOutbox,ho as trimStreamRuns,oo as tryRowToDocument,Ms as trySendFrame,no as unionAll,tt as uniqueIndexFields,l as validateImportRow,Ss as verifySiblingBody,vt as whereFilter,Kt as whereOfFilter,Te as writeCdcArchivedThrough,Ke as writeGlobalShapeSnapshot,Qe as writeIdempotent,Ot as writeReactorState,Er as writeSearchBackfillState,_r as writeShapePokeCursor,Ir as writeShapePokeCursors,ks as writeTouchesMemo};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{sql as e}from"drizzle-orm";import{compareStrings as a,encodeAggregateKey as f}from"./aggregateTableName-B_CtIQCS.mjs";import{runDrizzle as r}from"./runDrizzle-RC09zZrh.mjs";import{sqliteInList as T}from"./WORKERD_SQLITE_LIMITS-B_4w7tzY.mjs";const n="__lunora_companion_state",c=1,g=1,E=i=>i?f(Object.keys(i),i):"",O=(i,t)=>JSON.stringify([c,(i.by??[]).toSorted(a),i.field??"",i.op,E(i.where),t??""]),$=(i,t)=>JSON.stringify([g,(i.partitionBy??[]).toSorted(a),i.sortBy.map(o=>o.field),E(i.where),t??""]),s=i=>{r(i,e`CREATE TABLE IF NOT EXISTS ${e.identifier(n)} (${e.identifier("companion")} TEXT PRIMARY KEY, ${e.identifier("signature")} TEXT NOT NULL)`)},u=(i,t)=>{s(i),r(i,t.length===0?e`DELETE FROM ${e.identifier(n)}`:e`DELETE FROM ${e.identifier(n)} WHERE ${T(e.raw('"companion"'),t,!0)}`)},R=(i,t)=>r(i,e`SELECT ${e.identifier("signature")} FROM ${e.identifier(n)} WHERE ${e.identifier("companion")} = ${t}`).toArray()[0]?.signature,A=(i,t,o)=>{r(i,e`INSERT INTO ${e.identifier(n)} (${e.identifier("companion")}, ${e.identifier("signature")}) VALUES (${t}, ${o}) ON CONFLICT (${e.identifier("companion")}) DO UPDATE SET ${e.identifier("signature")} = excluded.${e.identifier("signature")}`)},N=i=>{s(i),r(i,e`DELETE FROM ${e.identifier(n)}`)};class L{verified=new Set;invalidate(){this.verified.clear()}}export{L as CompanionMemo,O as aggregateSignature,N as clearCompanionSignatures,u as migrateCompanionState,$ as rankSignature,R as readCompanionSignature,A as writeCompanionSignature};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{LunoraError as h}from"@lunora/errors";import{i as S,R as L}from"./relation-operators-BEg-CvCH.mjs";import{mergeWhere as w}from"./CountRlsUnsupportedError-BvsDqfO2.mjs";import{isMemoryTable as R}from"./clearMemoryTables-aMRERF0w.mjs";import{normalizeOrderKeys as j,uniqueIndexFields as M,equalityPinnedFields as P,buildSeekWhere as k,decodeCursor as I,softDeleteScope as K}from"./CURSOR_PREFIX-6offuG6M.mjs";import{distinctValues as O}from"./applyInsertDefaults-
|
|
1
|
+
import{LunoraError as h}from"@lunora/errors";import{i as S,R as L}from"./relation-operators-BEg-CvCH.mjs";import{mergeWhere as w}from"./CountRlsUnsupportedError-BvsDqfO2.mjs";import{isMemoryTable as R}from"./clearMemoryTables-aMRERF0w.mjs";import{normalizeOrderKeys as j,uniqueIndexFields as M,equalityPinnedFields as P,buildSeekWhere as k,decodeCursor as I,softDeleteScope as K}from"./CURSOR_PREFIX-6offuG6M.mjs";import{distinctValues as O}from"./applyInsertDefaults-B0NXPs2x.mjs";import{RELATION_EXISTS_KEY as _}from"./RELATION_EXISTS_KEY-wxgj6rSL.mjs";const v={every:{kind:"many",negateChild:!0,negated:!0},is:{kind:"one",negated:!1},isNot:{kind:"one",negated:!0,nullDisjunct:!0},none:{kind:"many",negated:!0},some:{kind:"many",negated:!1}},A=e=>L.has(e)?e:void 0,g=e=>{const t=A(e),r=t===void 0?void 0:v[t];if(!r)throw new h("INTERNAL",`unknown relation operator "${e}"`);return r},C=e=>e.kind==="one"?{clause:e.field,project:e.references}:{clause:e.references,project:e.field},D=5e3,f=Symbol("relation-key-overflow"),p=e=>Array.isArray(e)?e.map(t=>t??{}):[],N=e=>{if(e.length===1){const[t]=e;return t??{}}return e.length===0?{}:{AND:e}},y=e=>S(e),u=(e,t,r)=>{const n=t.tables[r]?.relationMap??{};return Object.keys(e).some(o=>{const a=e[o];return o==="AND"||o==="OR"?p(a).some(s=>u(s,t,r)):o==="NOT"?u(a??{},t,r):!!n[o]&&y(a)})},oe=(e,t,r,n)=>{if(e&&u(e,t,r))throw new h("INTERNAL",`relation-crossing predicates are not supported in ${n}() — use them in findMany/findFirst or an RLS read policy`)},B=async(e,t,r,n)=>{const o=await l(t,e.table,n),{page:a}=await n.fetcher(e.table,{baseWhere:n.relationBaseWhere?.(e.table),relationBaseWhere:n.relationBaseWhere,where:o});return O(a,r)},W=(e,t,r)=>{throw new h("INTERNAL",`relation predicate on "${e.table}" matched ${String(t)} rows, exceeding the ${String(r.maxRelationKeys)}-key limit; narrow the predicate (a same-shard EXISTS push-down lifts this cap)`)},F=(e,t,r)=>{throw new h("INTERNAL",`relation predicate on "${e.table}" matched at least ${String(t)} distinct keys, exceeding the ${String(r.maxRelationKeys)}-key limit; narrow the predicate`)},q=async(e,t,r,n,o)=>{const a=await B(e,t,r,n);return a.length<=n.maxRelationKeys?a:o?f:W(e,a.length,n)},b=async(e,t,r,n)=>{const o=await l(t,e.table,n),a=n.maxRelationKeys+1,s=new Set;let d;for(;;){const i=await n.fetcher(e.table,{baseWhere:n.relationBaseWhere?.(e.table),cursor:d,limit:a,relationBaseWhere:n.relationBaseWhere,where:o});if(i.page.length>a)throw new h("INTERNAL",`relation predicate on "${e.table}" read ${String(i.page.length)} rows for a page of at most ${String(a)}; the fetcher did not honour the page limit`);for(const c of O(i.page,r))s.add(c);if(s.size>n.maxRelationKeys&&F(e,s.size,n),i.isDone)return[...s];if(typeof i.continueCursor!="string")throw new h("INTERNAL",`relation predicate on "${e.table}" returned a page that is not final but has no cursor to continue from`);if(i.continueCursor===d)throw new h("INTERNAL",`relation predicate on "${e.table}" paged with a cursor that did not advance`);d=i.continueCursor}},H=async(e,t,r,n,o)=>{const a=g(e),{clause:s,project:d}=C(t),i=await q(t,a.negateChild?{NOT:r}:r,d,n,o);return i===f?f:a.negated?a.nullDisjunct?{OR:[{[s]:{notIn:i}},{[s]:{isNull:!0}}]}:{[s]:{notIn:i}}:{[s]:{in:i}}},z=async(e,t,r,n)=>{const o=g(e),{from:a,table:s,to:d}=t.through,i=await b(t,o.negateChild?{NOT:r}:r,"_id",n),c=i.length===0?[]:await b({table:s},{[d]:{in:i}},a,n);return{_id:o.negated?{notIn:c}:{in:c}}},E=async(e,t,r,n,o)=>{const a=g(e),s=o.relationBaseWhere?.(t.table),d=a.negateChild?{NOT:r}:r,$={childWhere:await l(s?{AND:[s,d]}:d,t.table,o),negated:a.negated,parentTable:n,relation:t};return{[_]:$}},Y=(e,t,r)=>{const n=A(e),o=n===void 0?void 0:v[n];if(o&&o.kind!==r.kind)throw new h("INTERNAL",`relation operator "${e}" requires a to-${o.kind} relation, but "${t}" is to-${r.kind}`)},x=async(e,t,r,n,o)=>{const a=[];for(const s of Object.keys(r)){Y(s,e,t);const d=r[s]??{};if(t.through!==void 0){a.push(await z(s,t,d,o));continue}const i=o.canPushExists?.(t)??!1;if(i&&o.existsPushMode==="always"){a.push(await E(s,t,d,n,o));continue}const c=await H(s,t,d,o,i);c===f?a.push(await E(s,t,d,n,o)):a.push(c)}return N(a)},Q=async(e,t,r,n)=>{if(e==="AND"||e==="OR"){const a=[];for(const s of p(t))a.push(await l(s,r,n));return{[e]:a}}if(e==="NOT")return{NOT:await l(t??{},r,n)};const o=n.schema.tables[r]?.relationMap?.[e];return o&&y(t)?x(e,o,t,r,n):{[e]:t}},l=async(e,t,r)=>{const n=[];for(const o of Object.keys(e))n.push(await Q(o,e[o],t,r));return N(n)},X=async(e,t)=>!e||!u(e,t.schema,t.tableName)?e:l(e,t.tableName,{canPushExists:t.canPushExists,existsPushMode:t.existsPushMode??"auto",fetcher:t.fetcher,maxRelationKeys:t.maxRelationKeys??D,relationBaseWhere:t.relationBaseWhere,schema:t.schema}),ae=async(e,t,r)=>{const n=j(t.orderBy,e.shape,{pinned:P(t.where),uniqueBy:M(e.indexes,e.shape)}),o=t.cursor?k(n,I(t.cursor)):void 0;let a=w(t.baseWhere,t.where);a=w(a,K(e.softDeleteMode,t.includeDeleted)),a=await X(a,{...r,relationBaseWhere:t.relationBaseWhere}),o&&(a=a?{AND:[a,o]}:o);const s=typeof t.limit=="number"?Math.max(0,Math.floor(t.limit)):void 0;return{fetchLimit:s===void 0?void 0:s+1,limit:s,orderKeys:n,predicate:a}},m=(e,t,r)=>{for(const n of e){const o=T(n,t,r);if(o)return o}},U=(e,t,r,n)=>{if(e==="AND"||e==="OR")return m(p(t),r,n);if(e==="NOT")return m([t??{}],r,n);const o=r.tables[n]?.relationMap?.[e];if(!o||!y(t))return;const a=o.through===void 0?[o.table]:[o.table,o.through.table],s=a.find(i=>r.tables[i]?.shardMode?.kind==="shardBy");if(s!==void 0)return{kind:"shard",relation:e,target:s};const d=a.find(i=>R(r.tables[i]));return d!==void 0?{kind:"memory",relation:e,target:d}:m(Object.values(t),r,o.table)},T=(e,t,r)=>{for(const n of Object.keys(e)){const o=U(n,e[n],t,r);if(o)return o}},V=(e,t,r)=>{if(!(t.tables[r]?.shardMode?.kind==="global"||!u(e,t,r)))throw Object.assign(new Error(`shape on "${r}" filters by a relation, which a shard-local shape cannot replicate: its seed and membership probe read "${r}" alone, so the relation never matches, and a write that only touches the related table never moves the shape. Fix it by (a) denormalizing the related columns into "${r}" and filtering on those, (b) moving "${r}" to .global() so it is served through the latency-tiered D1 shape tier, or (c) reading it through a live query (\`useQuery\`), which does resolve relations.`),{code:"SHAPE_RELATION_PREDICATE",name:"LunoraError",status:400})},se=(e,t,r)=>{if(R(t.tables[r]))throw Object.assign(new Error(`shape on "${r}" replicates from the changelog, which never records a .memory() table — the shape would seed once and never update again. Fix it by (a) dropping .memory() from "${r}" so its writes reach the changelog, or (b) reading it through a live query (\`useQuery\`), which refreshes off the changed-table set rather than the log.`),{code:"SHAPE_MEMORY_TABLE",name:"LunoraError",status:400});if(!e)return;const n=T(e,t,r);if(!n){V(e,t,r);return}throw n.kind==="memory"?Object.assign(new Error(`shape on "${r}" joins the .memory() table "${n.target}" via relation "${n.relation}" — writes to a .memory() table never reach the changelog, so the shape is never told its membership changed and would serve stale rows indefinitely. Fix it by (a) dropping .memory() from "${n.target}", or (b) reading it through a live query (\`useQuery\`), which refreshes off the changed-table set rather than the log.`),{code:"SHAPE_MEMORY_TABLE",name:"LunoraError",status:400}):Object.assign(new Error(`shape on "${r}" joins the sharded table "${n.target}" via relation "${n.relation}" — a live shape cannot replicate rows that live in another shard's Durable Object. Fix it by (a) denormalizing the joined columns into "${r}", or (b) moving "${n.target}" to .global() so it is served through the latency-tiered D1 shape tier.`),{code:"SHAPE_CROSS_SHARD_JOIN",name:"LunoraError",status:400})};export{D as DEFAULT_MAX_RELATION_KEYS,oe as assertFlatPredicate,se as assertShapeShardable,ae as composeReadPredicate,u as containsRelationPredicate,y as isRelationPredicate,X as resolveRelationPredicates};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{LunoraError as y}from"@lunora/errors";import{D as gt}from"./MAX_TOKEN_LENGTH-BakL9FUy-B3VwYY8C.mjs";import{S as Mn,l as qe,h as Dn}from"./fts-companion-CA8mLJWq.mjs";import{decodeWire as kn,stableWireKey as qt}from"@lunora/wire";import{sql as a}from"drizzle-orm";import{throwingScheduler as Ln,aggregateSqlFunction as We,normalizeCountArgument as Fn}from"./AGGREGATE_SQL_FUNCTION-C_ZipS9R.mjs";import{aggregateTableName as ot,encodeAggregateKey as rt,readAggregateValue as it}from"./aggregateTableName-B_CtIQCS.mjs";import{mergeWhere as K,CountRlsUnsupportedError as st,selectIndexForGroupBy as qn,selectIndexForCount as Wn,selectIndexForAggregate as Bn}from"./CountRlsUnsupportedError-BvsDqfO2.mjs";import{backfillSearchIndexesForTable as Pn,searchIndexCoversTable as Un}from"./backfillAggregateIndexes-BN0NwXQk.mjs";import{backfillAggregateIndexes as gi,backfillRankIndexes as yi,backfillSearchIndexes as $i}from"./backfillAggregateIndexes-BN0NwXQk.mjs";import{appendCdcChange as On,readCdcDocAtOrBefore as Hn}from"./CDC_LOG_TABLE-Dgwxv7yf.mjs";import{CDC_LOG_TABLE as mi,applyCdcChanges as Si,bumpCdcEpoch as _i,cdcCanVouchFor as Ri,cdcForkedError as vi,cdcSeqLeavingRows as Ti,cdcTouchesTables as Ii,cdcTrimmedError as Ai,compactCdcDocs as Ci,cursorBelowRetainedFloor as xi,minCdcReplayableSeq as bi,minCdcSeq as Mi,readCdcChangeKeys as Di,readCdcChanges as ki,readCdcCursor as Li,readCdcEpoch as Fi,trimCdcChanges as qi}from"./CDC_LOG_TABLE-Dgwxv7yf.mjs";import{allocateCommitSeq as Gn,COMMIT_SEQ_FIELD as jn}from"./COMMIT_SEQ_FIELD-Da1DjGqo.mjs";import{createCompanionSync as Kn}from"./createCompanionSync-zIF_F4oD.mjs";import{isMemoryTable as Wt}from"./clearMemoryTables-aMRERF0w.mjs";import{computeRankPage as Bt}from"./computeRankPage-BZIpATcs.mjs";import{SCAN_DEP as O}from"./SCAN_DEP-D7qE3iUe.mjs";import{runSql as pe,runDrizzle as H}from"./runDrizzle-RC09zZrh.mjs";import{p as Nn,j as ut,D as ie,r as Te,k as fe,b as Be,A as ct,a as Pe,m as he,e as we,s as Qn,t as Vn,i as Jn,q as Pt,h as un,g as zn}from"./do-sql-BWrJQAOh.mjs";import{renderSql as fn,unionAll as yt,WORKERD_SQLITE_LIMITS as hn,sqliteInList as Yn}from"./WORKERD_SQLITE_LIMITS-B_4w7tzY.mjs";import{coveringGeohashes as Xn,boundingBoxGeohashes as Zn,haversineMeters as eo,pointInBoundingBox as to}from"./GEO_DEFAULT_PRECISION-CqpQZ-J_.mjs";import{NotFoundError as no}from"./NotFoundError-BhF7FeFr.mjs";import{resolvePatch as oo,assertPatchAllowed as ro,operatorFields as io,readPatchField as Ut}from"./assertPatchAllowed-CA_H466g.mjs";import{tiebreakDirectionFor as so,encodeCursor as Ke,nullsOrderSuffix as co,normalizeOrderKeys as Ot,uniqueIndexFields as ao,buildSeekWhere as lo,decodeCursor as Ht,buildSeekBeforeWhere as uo,softDeleteScope as ve,applySelect as Gt}from"./CURSOR_PREFIX-6offuG6M.mjs";import{rankTableName as jt,sortColumnName as Kt,resolveRankPartition as fo,encodePartitionKey as ho,RANK_TIEBREAK as wo,rankPivotConditionSql as po}from"./RANK_TIEBREAK-D3ye2GsL.mjs";import{UNVOUCHABLE_DEP as Nt}from"./UNVOUCHABLE_DEP-C68htACn.mjs";import{indexKeysForRow as go,buildIndexRange as yo}from"./buildIndexRange-DQ3eWAGd.mjs";import{r as Ne,j as Ie,c as X,t as Ve,i as Qt}from"./where-sql-BjY4rnqb.mjs";import{serializeSqlValue as Ae}from"./serializeSqlValue-DeoBMpZ2.mjs";import{quoteIdentifier as Ce}from"./quoteIdentifier-CObIFRhb.mjs";import{whereOfFilter as $o,isPushableWhere as Eo}from"./isPushableWhere-BeYAOjUb.mjs";import{deriveRelationEdges as mo,findRelated as So}from"./RELATED_DEFAULT_LIMIT-CVqN4JEu.mjs";import{assertFlatPredicate as at,resolveRelationPredicates as _o,composeReadPredicate as Ro}from"./DEFAULT_MAX_RELATION_KEYS-9eOkadE4.mjs";import{describeRelationWrites as vo}from"./describeRelationWrites-omar6-u9.mjs";import{runRowValidators as Ue,transformOnlyDefinition as To,applyInsertDefaults as ft,resolveWith as Vt,relationHooks as Jt,applyOnDelete as Io,fanOutScalarCounts as Ao}from"./applyInsertDefaults-B0NXPs2x.mjs";import{guardWriter as Co}from"./RLS_UNWRAP_SYMBOL-J1tiBtRj.mjs";import{mayHoldProjectedValue as xo}from"./BIGINT_KEY_DIGITS-DE6yshOt.mjs";import{createSystemReader as bo}from"./createSystemReader-DcDLFfC-.mjs";import{ConflictError as ae}from"./ConflictError-C8GtJmjS.mjs";import{hasTrigger as zt,runTriggers as Mo}from"./hasTrigger-CjlwI4le.mjs";import{advanceClientWatermark as Bi,migrateClientWatermark as Pi,readClientWatermark as Ui}from"./CLIENT_WATERMARK_TABLE-De7z_OHV.mjs";import{IDEMPOTENCY_TABLE as Hi,readIdempotent as Gi,trimIdempotent as ji,writeIdempotent as Ki}from"./IDEMPOTENCY_TABLE-COrgeP3O.mjs";import{runShardMigrations as Qi}from"./runShardMigrations-DsrVE2Kq.mjs";import{selectShapeMembers as Ji,selectShapeRows as zi}from"./selectShapeMembers-BCfKypfN.mjs";const Do=t=>{const i=atob(t),o=Uint8Array.from(i,c=>c.codePointAt(0)??0);return new TextDecoder().decode(o)},ko=()=>new y("BAD_REQUEST","invalid cursor"),Yt=16,Xt=8,V=1024,$t=(t,i)=>i.query(t),Lo=(t,i)=>{if(t.length===0)return 0;let o=0;for(const[c,s]of i.entries()){const w=c===i.length-1;let m=0;for(const S of t)(w?S.startsWith(s):S===s)&&(m+=1);if(m===0)return 0;o+=m}return o},Fo=(t,i)=>{if(!i)return{exact:!0,lower:t,upper:t};const o=[...t].at(-1)??"",c=(o.codePointAt(0)??0)+1;if(c>=55296&&c<=57343||c>1114111)return{exact:!0,lower:t,upper:t};const s=t.slice(0,t.length-o.length);return{exact:!1,lower:t,upper:s+String.fromCodePoint(c)}},qo=(t,i,o)=>{const c={eq:(s,w)=>{if(!t.definition.filterFields?.includes(s))throw new y("INTERNAL",`field "${s}" is not a filter field of search index "${t.indexName}" on table "${i}"`);if(t.filters.length>=Xt)throw new y("BAD_REQUEST",`search index "${t.indexName}" on table "${i}": at most ${String(Xt)} .eq() filters are supported per search query`);return t.filters.push({field:s,value:w}),c},search:(s,w)=>{const m=t;if(s!==m.definition.field)throw new y("INTERNAL",`search index "${m.indexName}" on table "${i}" indexes "${m.definition.field}", not "${s}"`);const S=$t(w,o).length;if(S>Yt)throw new y("BAD_REQUEST",`search index "${m.indexName}" on table "${i}": at most ${String(Yt)} search terms are supported (got ${String(S)})`);return m.field=s,m.query=w,m.hasQuery=!0,c}};return c},Wo=t=>{if(t.length>V)throw new y("BAD_REQUEST",`more than ${String(V)} documents match this search — narrow it with filters or read it a page at a time with .paginate()`)},Bo=t=>Math.min(t.offset+t.numItems+1,V),Po=t=>btoa(`search:${String(t)}`),Uo=t=>{let i;try{i=Do(t)}catch{return}if(!i.startsWith("search:"))return;const o=Number(i.slice(7));return Number.isInteger(o)&&o>=0?o:void 0},Oo=t=>{if(typeof t.endCursor=="string")throw new y("BAD_REQUEST","bounded (endCursor) pagination is not supported on search queries — relevance order has no stable range boundary");if(!Number.isFinite(t.numItems))throw new y("BAD_REQUEST",`search pagination needs a finite numItems, got ${String(t.numItems)}`);const i=Math.max(0,Math.floor(t.numItems)),o=t.cursor?Uo(t.cursor):0;if(o===void 0)throw ko();if(o+i>=V)throw new y("BAD_REQUEST",`search pagination reaches the ${String(V)}-document limit (offset ${String(o)} + ${String(i)} requested) — a page must end below the cap so the probe row that answers \`hasMore\` still fits: retry with numItems ${String(Math.max(1,V-o-1))} or fewer, or narrow the query or the filters instead`);return{numItems:i,offset:o}},Ho=(t,i)=>{const o=i.offset+i.numItems,c=i.numItems>0&&t.length>o;return{continueCursor:c?Po(o):null,isDone:!c,page:t.slice(i.offset,o)}},Go=t=>{if(t===void 0)return V+1;if(!Number.isFinite(t))return V;const i=Math.max(0,Math.floor(t));if(i>V)throw new y("BAD_REQUEST",`search returns at most ${String(V)} documents (asked for ${String(i)}) — narrow the query or paginate instead`);return i},wn=500,pn=(t,i,o)=>{if(t!==void 0&&t!==Number.POSITIVE_INFINITY&&(!Number.isInteger(t)||t<0))throw o(`${i}: batch limit must be a non-negative integer`);return t??wn},gn=(t,i,o,c)=>{if(t>i)throw c(`${o}: batch of ${String(t)} exceeds the limit of ${String(i)} (raise options.limit or chunk the call)`)},jo=32,Ko=1024,yn=(t,i,o,c)=>{const s=`SELECT id, _creationTime, ${Ce(ie)} FROM ${Ce(t)}`,w=`ORDER BY ${o}${c===void 0?"":` LIMIT ${String(c)}`}`;return i===void 0?Ne(`${s} ${w}`):Ie(`${s} WHERE `,i,` ${w}`)},Je={fieldRef:t=>Ne(ut(t)),rangeTypeGuard:(t,i)=>Ne(Nn(t,i)),serialize:Ae},No=t=>t===void 0?"":co(t==="first"),$n=t=>{const i=t.map(o=>`${ut(o.field)} ${o.direction==="desc"?"DESC":"ASC"}${No(o.nulls)}`);return t.some(o=>o.field==="_id"||o.field==="id")||i.push(`${ut("id")} ${so(t)==="desc"?"DESC":"ASC"}`),i.join(", ")},Qo={"<":"lt","<=":"lte","=":"eq",">":"gt",">=":"gte"},En=t=>new Set(t.sqlConditions.filter(i=>i.comparator==="=").map(i=>i.field)),Vo=t=>{const i=En(t);let o=0;for(;o<t.indexFields.length&&i.has(t.indexFields[o]??"");)o+=1;return t.indexFields.slice(o)},Jo=(t,i)=>{const o=t.order,c=Vo(t),{shape:s}=i;return c.length>0?Ot(c.map(w=>({[w]:o})),s,{pinned:En(t),uniqueBy:ao(i.indexes,s)}):Ot([{_creationTime:o}],s)},zo=(t,i,o,c)=>{const s=t.sqlConditions.map(w=>({[w.field]:{[Qo[w.comparator]??"eq"]:w.value}}));if(o&&s.push(lo(i,Ht(o))),c&&s.push(uo(i,Ht(c))),s.length!==0)return s.length===1?s[0]:{AND:s}},Yo=t=>{if(t.want!==void 0)return t.selective?Math.max(t.want,jo):t.want},ht=(t,i,o,c,s,w,m)=>{const S=Jo(c,o),C=$n(S),$=[],{filters:W,want:x}=w;let A=w.cursor??void 0,D=Yo(w);if(x===0)return{documents:$,orderKeys:S};for(;;){const B=X(zo(c,S,A,w.endCursor),Je,Ve),F=yn(i,s&&B?Ie(B," AND ",s):s??B,C,D),L=pe(t,F.text,...F.params).toArray();let q={};m(L.length);for(const j of L)if(q=Te(j),W.every(se=>se(q))&&$.push(q)===x)return{documents:$,orderKeys:S};if(D===void 0||L.length<D)return{documents:$,orderKeys:S};A=Ke(q,S),D=Math.max(D,Math.min(D*2,Ko))}},Xo=(t,i,o,c,s,w,m,S)=>{const C=Math.max(0,Math.floor(s.numItems));if(typeof s.endCursor=="string"){const{documents:B,orderKeys:F}=ht(t,i,o,c,w,{cursor:s.cursor,endCursor:s.endCursor,filters:m.all,selective:m.selective,want:void 0},S),L=B.length>=2?B[Math.floor(B.length/2)-1]:void 0;return{continueCursor:s.endCursor,isDone:!0,page:B,splitCursor:L?Ke(L,F):null}}const{documents:$,orderKeys:W}=ht(t,i,o,c,w,{cursor:s.cursor,filters:m.all,selective:m.selective,want:C+1},S),x=$.length>C,A=x?$.slice(0,C):$,D=A.at(-1);return{continueCursor:x&&D?Ke(D,W):null,isDone:!x,page:A}},ze=t=>{const i=new Map;return o=>{const c=i.get(o);if(c!==void 0)return c;const s=t(Ce(o));return i.set(o,s),s}},ge=Ce(ie),Zo=ze(t=>`INSERT INTO ${t} (id, _creationTime, ${ge}) VALUES (?, ?, ?)`),Zt=ze(t=>`UPDATE ${t} SET ${ge} = ? WHERE id = ? AND ${ge} = ?`),er=ze(t=>`UPDATE ${t} SET _creationTime = ?, ${ge} = ? WHERE id = ? AND ${ge} = ?`),tr=ze(t=>`DELETE FROM ${t} WHERE id = ? AND ${ge} = ?`),nr="SELECT changes() AS changed",en=new Map,or="",rr=t=>{const i=JSON.stringify(t),o=en.get(i);if(o!==void 0)return o;const c=t.map(w=>a`SELECT ${a.raw(`'${w.replaceAll("'","''")}'`)} AS __t__, id, _creationTime, ${a.identifier(ie)} FROM ${a.identifier(w)} WHERE id = ${or}`),{sql:s}=fn("sqlite",a`${yt(c)} LIMIT 1`);return en.set(i,s),s},ir=(t,i)=>i.map(()=>t),sr=/^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/iu,cr=t=>{if(!sr.test(t))throw new y("INTERNAL",`invalid clientId ${JSON.stringify(t)}: a client-supplied row id must be a UUID`)},wt=t=>{if(t.includes("\0"))throw new y("BAD_REQUEST",`invalid row id ${JSON.stringify(t)}: a row id cannot hold a NUL character (U+0000)`)},ar=(t,i,o,c)=>{if(o!==!0)return;const s=t!==void 0&&"serverDefault"in(t.shape._id?._meta?.column??{});for(const w of i){const m=s?ft(t,w,c)._id:w._id;typeof m=="string"&&wt(m)}},tn=50,Oe=Math.floor(hn.boundParams/3),Re=hn.boundParams,dr=128,Qe=t=>new y("BATCH_LIMIT_EXCEEDED",t,{status:400}),He=(t,i,o)=>{gn(t,pn(i,o,Qe),o,Qe)},nn=async(t,i,o,c,s)=>{const w=pn(c,s,Qe),{page:m}=await t.findMany(i,Number.isFinite(w)?{limit:w+1,omitContinueCursor:!0,where:o}:{where:o});return m.length>w&&gn(Math.max(await t.count(i,{where:o}),m.length),w,s,Qe),m},lr=t=>{const i={eq:(o,c)=>(t.sqlConditions.push({comparator:"=",field:o,value:c}),i),gt:(o,c)=>(t.sqlConditions.push({comparator:">",field:o,value:c}),i),gte:(o,c)=>(t.sqlConditions.push({comparator:">=",field:o,value:c}),i),lt:(o,c)=>(t.sqlConditions.push({comparator:"<",field:o,value:c}),i),lte:(o,c)=>(t.sqlConditions.push({comparator:"<=",field:o,value:c}),i)};return i},ur=t=>Math.max(t,V),mn=(t,i)=>{const o=t.filters.map(c=>a`${we(c.field)} = ${Ae(c.value)}`);return i&&o.push(i),o},fr=(t,i,o,c,s)=>{const w=$t(o.query,gt(o.definition.language));if(w.length===0)return[];const m=Mn(i,o.indexName),S=`${m}__vocab`,C=w.length-1,$=w.map((F,L)=>{const q=Fo(F,L===C),j=q.exact?a`${a.identifier("term")} = ${q.lower}`:a`${a.identifier("term")} >= ${q.lower} AND ${a.identifier("term")} < ${q.upper}`;return a`SELECT ${a.identifier("doc")}, ${a.raw(String(L))} AS ${a.identifier("__term__")}, COUNT(*) AS ${a.identifier("__n__")} FROM ${a.identifier(S)} WHERE ${j} GROUP BY ${a.identifier("doc")}`}),W=w.map((F,L)=>a`SUM(CASE WHEN u.${a.identifier("__term__")} = ${a.raw(String(L))} THEN u.${a.identifier("__n__")} ELSE 0 END)`),x=a`SELECT f.${a.identifier(qe)} AS ${a.identifier(qe)}, ${a.join(W,a` + `)} AS ${a.identifier("__score__")} FROM (${yt($)}) u JOIN ${a.identifier(m)} f ON f.rowid = u.${a.identifier("doc")} GROUP BY f.${a.identifier(qe)} HAVING ${a.join(W.map(F=>a`${F} > 0`),a` AND `)}`,A=mn(o,s);let D=a`SELECT m.id, m._creationTime, m.${a.identifier(ie)}, s.${a.identifier("__score__")} AS ${a.identifier("__score__")} FROM (${x}) s JOIN ${a.identifier(i)} m ON m.id = s.${a.identifier(qe)}`;A.length>0&&(D=a`${D} WHERE ${a.join(A,a` AND `)}`),D=a`${D} ORDER BY s.${a.identifier("__score__")} DESC, m._creationTime DESC, m.id ASC LIMIT ${a.raw(String(c))}`;const B=[];for(const F of H(t,D)){const L=un(F);if(L){const q=F.__score__;B.push({document:L,score:typeof q=="number"?q:Number(q??0)})}}return B},hr=(t,i,o,c,s)=>{const w=gt(o.definition.language),m=$t(o.query,w);if(m.length===0)return[];const S=mn(o,s);let C=a`SELECT id, _creationTime, ${a.identifier(ie)} FROM ${a.identifier(i)}`;S.length>0&&(C=a`${C} WHERE ${a.join(S,a` AND `)}`),C=a`${C} ORDER BY _creationTime DESC, id ASC LIMIT ${a.raw(String(ur(c)))}`;const $=H(t,C).toArray(),W=[];for(const x of $){const A=un(x);if(!A)continue;const D=Lo(Dn(A,o.definition),m);D>0&&W.push({creationTime:typeof A._creationTime=="number"?A._creationTime:0,doc:A,id:typeof A._id=="string"?A._id:"",score:D})}return W.sort((x,A)=>A.score-x.score||A.creationTime-x.creationTime||x.id.localeCompare(A.id)),W.slice(0,c).map(x=>({document:x.doc,score:x.score}))},dt=(t,i,o,c)=>{if(!Number.isFinite(t.lat)||t.lat<-90||t.lat>90||!Number.isFinite(t.lng)||t.lng<-180||t.lng>180)throw new y("BAD_REQUEST",`geo index "${c}" on table "${o}": ${i} must have a finite lat in [-90, 90] and lng in [-180, 180]`)},wr=(t,i)=>{const o=t,c={near:(s,w)=>{if(o.within)throw new y("INTERNAL",`geo index "${o.indexName}" on table "${i}": call .near() or .within(), not both`);if(dt(s,".near() point",i,o.indexName),!Number.isFinite(w)||w<=0)throw new y("BAD_REQUEST",`geo index "${o.indexName}" on table "${i}": .near() radiusMeters must be a finite number > 0, got ${String(w)}`);return o.near={point:{lat:s.lat,lng:s.lng},radiusMeters:w},c},within:s=>{if(o.near)throw new y("INTERNAL",`geo index "${o.indexName}" on table "${i}": call .near() or .within(), not both`);if(dt(s.sw,".within() sw corner",i,o.indexName),dt(s.ne,".within() ne corner",i,o.indexName),s.sw.lat>s.ne.lat)throw new y("BAD_REQUEST",`geo index "${o.indexName}" on table "${i}": .within() corners are transposed (sw.lat > ne.lat)`);if(s.sw.lng>s.ne.lng)throw new y("BAD_REQUEST",`geo index "${o.indexName}" on table "${i}": .within() box crosses the antimeridian (sw.lng > ne.lng), which is not supported — split it into two boxes at ±180 and union the results`);return o.within={ne:{lat:s.ne.lat,lng:s.ne.lng},sw:{lat:s.sw.lat,lng:s.sw.lng}},c}};return c},pr=(t,i)=>{const o=t[i];if(o===null||typeof o!="object")return;const{lat:c,lng:s}=o;return typeof c=="number"&&typeof s=="number"?{lat:c,lng:s}:void 0},gr=(t,i)=>{const o=pr(t,i.definition.field);if(!o)return;const c=typeof t._creationTime=="number"?t._creationTime:0;if(i.near){const s=eo(i.near.point,o);return s<=i.near.radiusMeters?{creationTime:c,distance:s}:void 0}return to(o,i.within)?{creationTime:c,distance:0}:void 0},yr=(t,i,o,c)=>{if(!o.near&&!o.within)throw new y("INTERNAL",`geo index "${o.indexName}" on table "${i}": call .near(point, radius) or .within(box)`);const s=o.near?Xn(o.near.point,o.near.radiusMeters):Zn(o.within),w=zn(i,o.indexName),m=s.map(x=>a`(g.${a.identifier("__geohash__")} >= ${x} AND g.${a.identifier("__geohash__")} < ${`${x}{`})`),S=[a`(${a.join(m,a` OR `)})`];c&&S.push(c);const C=a`SELECT m.id, m._creationTime, m.${a.identifier(ie)} FROM ${a.identifier(w)} g JOIN ${a.identifier(i)} m ON m.id = g.${a.identifier("__id__")} WHERE ${a.join(S,a` AND `)}`,$=H(t,C).toArray(),W=[];for(const x of $){const A=Te(x),D=A?gr(A,o):void 0;A&&D&&W.push({creationTime:D.creationTime,distance:D.distance,doc:A})}return W.sort((x,A)=>x.distance-A.distance||A.creationTime-x.creationTime),W},Sn=(t,i,o,c)=>{const s=[];for(const w of t)if(i.every(m=>m(c(w)))&&(s.push(w),typeof o=="number"&&s.length>=o))break;return s},$r=(t,i,o,c,s,w=()=>{})=>{const m=o.within!==void 0,S=yr(t,i,o,s).map(C=>({distanceMeters:m?null:C.distance,document:C.doc}));return w(S.length),typeof c=="number"?S.slice(0,Math.max(0,Math.floor(c))):S},on=(t,i,o,c,s,w,m=()=>{})=>{const{geo:S}=o;if(!S)throw new y("INTERNAL","runGeoTerminalScored called without a staged geo query");const C=s.length>0,$=$r(t,i,S,C?void 0:w,c,m);return C?Sn($,s,w,W=>W.document):$},rn=(t,i,o)=>{const c=t.shape[i];if(c!==void 0&&xo(c))throw new y("BAD_REQUEST",`${o}: "${i}" may hold an order-preserving key rather than a value SQL can reduce or group — declare an aggregateIndex covering this (by, field, op) so the maintained companion answers it instead (its running total is a REAL, so it stays exact only while the total is inside 2^53)`)},Er=t=>{let i=0;const o=[],c={...Je,relationExists:s=>{const{childWhere:w,negated:m,parentTable:S,relation:C}=s,$=`__rel_${String(i)}`,W=o.at(-1)??S;i+=1,t(C.table,O);const x=C.kind==="one"?C.field:C.references,A=C.kind==="one"?C.references:C.field,D=Ne(`${Pt($,A)} = ${Pt(W,x)}`);o.push($);const B=X(w,c,Ve);o.pop();const F=B===void 0?D:Ie(D," AND ",B),L=Ie("EXISTS (SELECT 1 FROM ",Qt(C.table)," AS ",Qt($)," WHERE ",F,")");return m?Ie("NOT ",L):L}};return c};class mr extends y{constructor(i="unique() found more than one matching document"){super("NOT_UNIQUE",i,{name:"NotUniqueError"})}}const Sr=/\s/u,_r=String.fromCodePoint(0),sn=(t,i,o)=>{if(!t.tables[i])throw new y("INTERNAL",`unknown table: ${i}`);return typeof o!="string"||o.length===0||Sr.test(o)||o.includes(_r)?null:o},_n=(t,i,o,c=()=>{},s=()=>{},w=()=>{},m)=>{const S=i.tables[o];if(!S)throw new y("INTERNAL",`unknown table: ${o}`);const C=ve(S.softDeleteMode,void 0),$=m??{indexFields:[],indexName:void 0,inMemoryFilters:[],order:"asc",sqlConditions:[],verifyFilters:[]},W=()=>{const E=K(C,$.pushedWhere);return E?X(E,he):void 0},x=()=>{const E=K(C,$.pushedWhere);return E?X(E,Je,Ve):void 0},A=()=>[...$.inMemoryFilters,...$.verifyFilters];let D=0;const B=E=>{const{search:M}=$;if(!M)throw new y("INTERNAL","runSearchFetch called without a staged search");Pn(t,o,S);const R=$.inMemoryFilters.length>0,k=Go(R?void 0:E),ee=Jn(t);if(ee&&!Un(t,o,M.definition))throw new y("SEARCH_INDEX_BUILDING",`search index "${M.indexName}" on table "${o}" is still backfilling and currently covers only part of the table — retry once it finishes, or run the backfillSearch admin operation to complete it now`);const N=W(),J=ee?fr(t,o,M,k,N):hr(t,o,M,k,N);!R&&E===void 0&&Wo(J);const re=A();return D=J.length,re.length>0?Sn(J,re,E,ce=>ce.document):J},F=E=>B(E).map(M=>M.document),L=E=>{const M=Oo(E);return Ho(F(Bo(M)),M)},q=()=>{if($.search||$.geo||$.indexName===void 0){s(void 0);return}s(yo(o,$.indexName,$.indexFields,$.sqlConditions,Ae))},j=E=>{q();let M=0;const R=(()=>{if($.search){const k=F(E);return M=D,k}return $.geo?on(t,o,$,W(),A(),E,k=>{M=k}).map(k=>k.document):ht(t,o,S,$,x(),{filters:A(),selective:$.inMemoryFilters.length>0,want:E===void 0?void 0:Math.max(0,Math.floor(E))},k=>{M+=k}).documents})();return w(Math.max(M,R.length)),R},se=()=>{if(!$.search&&!$.geo)throw new y("INTERNAL",`ctx.db.query("${o}").collectWithScores() requires a staged .withSearchIndex(...) or .withGeoIndex(...)`);q();let E=0;const M=(()=>{if($.search){const R=B(void 0);return E=D,R}return on(t,o,$,W(),A(),void 0,R=>{E=R})})();return w(Math.max(E,M.length)),M},Z={async*[Symbol.asyncIterator](){const E=_n(t,i,o,c,s,w,{...$,indexFields:[...$.indexFields],inMemoryFilters:[...$.inMemoryFilters],sqlConditions:[...$.sqlConditions],verifyFilters:[...$.verifyFilters]});if($.search){yield*await E.collect();return}let M;for(;;){const R=await E.paginate({cursor:M??null,numItems:dr});if(yield*R.page,R.isDone||R.continueCursor===null)return;M=R.continueCursor}},async collect(){return j(void 0)},async collectWithScores(){return se()},filter(E){const M=$o(E);return M!==void 0&&Eo(M,S.shape)?($.pushedWhere=K($.pushedWhere,M),$.verifyFilters.push(E)):$.inMemoryFilters.push(E),Z},async first(){return j(1)[0]??null},order(E){return $.order=E==="desc"?"desc":"asc",Z},async paginate(E){let M=0;if(q(),$.search){const k=L(E);return w(k.page.length),k}if($.geo)throw new y("INTERNAL","pagination is not supported on geo queries; use .take(n) or .collect()");const R=Xo(t,o,S,$,E,x(),{all:A(),selective:$.inMemoryFilters.length>0},k=>{M+=k});return w(Math.max(M,R.page.length)),R},async take(E){return j(E)},async unique(){const E=j(2);if(E.length>1)throw new mr(`unique() on table "${o}" matched ${String(E.length)} documents; expected at most one`);return E[0]??null},withGeoIndex(E,M){const R=(S.geoIndexes??[]).find(ee=>ee.name===E);if(!R)throw new y("INTERNAL",`unknown geo index "${E}" on table "${o}"`);c(o,E,"geo");const k={definition:R,indexName:E};if($.geo=k,M(wr(k,o)),!k.near&&!k.within)throw new y("INTERNAL",`geo index "${E}" on table "${o}" requires a .near(point, radius) or .within(box) call`);return Z},withIndex(E,M){const R=S.indexes.find(k=>k.name===E);if(!R)throw new y("INTERNAL",`unknown index "${E}" on table "${o}"`);return c(o,E,"index"),$.indexName=E,$.indexFields=R.fields,M&&M(lr($)),Z},withSearchIndex(E,M){const R=(S.searchIndexes??[]).find(ee=>ee.name===E);if(!R)throw new y("INTERNAL",`unknown search index "${E}" on table "${o}"`);c(o,E,"search");const k={definition:R,field:R.field,filters:[],hasQuery:!1,indexName:E,query:""};if($.search=k,M(qo(k,o,gt(R.language))),!k.hasQuery)throw new y("INTERNAL",`search index "${E}" on table "${o}" requires a .search(field, query) call`);return Z}};return Z},lt=(t,i,o,c)=>{const s=o;for(const[w,m]of Vn(t)){if(m.serverDefault){w in i&&(s[w]=m.serverDefault({auth:c}));continue}m.onUpdateFn&&!(w in i)&&(s[w]=m.onUpdateFn())}},cn=5,an=(t,i)=>{for(const o of Object.keys(i))if(i[o]===void 0)throw new y("INTERNAL",`Cannot ${t} field '${o}' to undefined — use null to clear a nullable field, or omit the key to leave it unchanged.`)},dn=["_commitSeq","_creationTime","_id"],Ge=t=>dn.some(i=>i in t)?Object.fromEntries(Object.entries(t).filter(([i])=>!dn.includes(i))):t,Rr=/unique constraint failed/i,vr=t=>t instanceof Error&&Rr.test(t.message),Tr=/string or blob too big/iu,Ir=(t,i)=>{if(!(!(t instanceof Error)||!Tr.test(t.message)))throw new y("PAYLOAD_TOO_LARGE",`document is too large to store in "${i}": a single row cannot exceed the storage engine's per-row ceiling (2 MB on a Durable Object's SQLite). The limit is on the STORED bytes, which are UTF-8, and v.bytes()/v.bigint() columns are stored twice on a shard-local table. Keep the payload in R2 (ctx.storage) and store a reference on the row.`)},pt=(t,i,o,c)=>{try{pe(t,o,...c)}catch(s){throw vr(s)?new ae(`unique constraint violation on "${i}"`,"unique"):(Ir(s,i),s)}},je=(t,i,o,c)=>{if(pt(t,i,o,c),pe(t,nr).one().changed===0)throw new ae(`optimistic concurrency conflict on "${i}" — the row changed during this mutation; refetch and retry`,"occ")},ln=(t,i,o,c,s,w,m)=>{const S=[];for(let x=0;x<o.length+1;x+=1){const A=o[x],D=c[x],B=D?.direction==="desc"?"desc":"asc",F=A===void 0||D===void 0?a`${a.identifier(wo)} < ${m}`:po(A,w[x],B,!1);if(F===void 0)continue;const L=[];for(let j=0;j<x;j+=1)L.push(a`${a.identifier(o[j])} IS ${w[j]}`);L.push(F);const[q]=L;S.push(L.length===1&&q!==void 0?q:a`(${a.join(L,a` AND `)})`)}const C=S.length>0?a.join(S,a` OR `):a`1 = 0`,$=H(t,a`SELECT COUNT(*) AS c FROM ${a.identifier(i)} WHERE ${a.identifier("__partition__")} = ${s} AND (${C})`).one(),W=H(t,a`SELECT COUNT(*) AS c FROM ${a.identifier(i)} WHERE ${a.identifier("__partition__")} = ${s}`).one();return{before:$.c,total:W.c}},Ar=t=>{const i=new Map;for(const[c,s]of Object.entries(t.tables))for(const w of Object.values(s.relationMap??{}))w.kind==="one"&&(w.onDelete==="cascade"||w.onDelete==="set null")&&i.set(w.table,[...i.get(w.table)??[],{holder:c,op:w.onDelete==="cascade"?"delete":"update"}]);const o=c=>{const s=new Set,w=[c];for(let m=w.pop();m!==void 0;m=w.pop())for(const{holder:S,op:C}of i.get(m)??[]){if(S===c||zt(t,S,C))return!0;s.has(S)||(s.add(S),w.push(S))}return!1};return new Set(Object.entries(t.tables).filter(([c,s])=>s.shardMode?.kind==="global"||zt(t,c,"delete")||o(c)).map(([c])=>c))},Cr=t=>{const i=new Map;for(const[o,c]of Object.entries(t.tables))c.softDeleteMode&&i.set(o,c.softDeleteMode.field);return i},hi=t=>{const{baselineSeq:i,onStalePatchDropped:o}=t,{sql:c}=t,{schema:s}=t,w=t.broadcast??(()=>{}),m=mo(s),S=new Map;for(const e of m){const n=r=>(s.tables[r]?.shardMode?.kind??"root")==="root";!e.array&&n(e.sourceTable)&&n(e.targetTable)&&S.set(e.sourceTable,[...S.get(e.sourceTable)??[],e])}const C=(e,n,r)=>{for(const d of S.get(e)??[]){const f=n[d.column];if(typeof f!="string"||r?.[d.column]===f||d.targetTable===e&&n._id===f)continue;if(H(c,a`SELECT 1 FROM ${a.identifier(d.targetTable)} WHERE id = ${f} LIMIT 1`).toArray().length===0)throw new y("VALIDATION_ERROR",`${d.name} references ${d.targetTable} row "${f}", which does not exist`)}},$=vo(s,t.inTransaction),W=Ar(s),x=Cr(s);let A;const D=()=>t.inTransaction?.()===!0,B=e=>s.tables[e]?.commitOrderedMode!==!0?{}:((A===void 0||!D())&&(A=Gn(c)),{[jn]:A}),F=(e,...n)=>{const r=s.tables[e]?.indexes;if(!r||r.length===0)return;const d=[];for(const f of n)f&&d.push(...go(r,f,Ae));return d.length>0?d:void 0},{headroom:L}=t;let q=!1;const j=async e=>{const n=q;q=!0;try{return await e()}finally{q=n}},se=t.onRead??(()=>{}),Z=e=>{Wt(s.tables[e])&&se(Nt,Nt)},E=t.onReadRange??(e=>{se(e.table,O)}),M=e=>{Z(e.table),E(e)},R=(e,n)=>{n!==void 0&&n!==O&&!q&&L?.recordRead(1),Z(e),se(e,n)},k=t.onIndexUse??(()=>{}),ee=t.onWrite??(()=>{}),N=e=>{q||L?.recordWrite(e)},J=async e=>{N(e.doc),await ee(e)},{cache:re}=t,ce=t.clock??(()=>Date.now()),Et=t.idGenerator??(()=>crypto.randomUUID()),mt=t.scheduler??Ln,{globalDb:ye}=t,de=t.auth??{identity:null,userId:null},St=t.cdc??!1,Ye=mt,Rn=bo({scheduler:typeof Ye.list=="function"&&typeof Ye.get=="function"?Ye:void 0,storage:t.storage}),$e=(e,n,r,d)=>{St&&!Wt(s.tables[e])&&On(c,ce(),e,n,r,d)},_t=(e,n,r,d)=>{const f=s.tables[e];if(f?.dropStalePatchesMode!==!0||!St)return!1;const h=i?.();if(h===void 0)return!1;const l=Hn(c,e,n,h);if(l===void 0)return!1;const u=io(f,r);return Object.keys(Ge(r)).some(p=>!u.has(p)&&qt(Ut(l,p))!==qt(Ut(d,p)))},le=e=>s.tables[e]?.shardMode?.kind==="global",Rt=(e,n)=>{if(le(e)){if(!ye)throw new y("INTERNAL",`cross-backend ${n} for global table '${e}' requires a globalDb writer — pass one to createShardCtxDb({ globalDb })`);return ye}return U},Xe=e=>Rt(e,"cascade"),G=(e,n)=>{if(le(e)){if(!ye)throw new y("INTERNAL",`${n} on global table '${e}' requires a globalDb writer — pass one to createShardCtxDb({ globalDb })`);return ye}},vt=async(e,n,r,d,f)=>{f&&N(r);const h=await e.insert(n,r,d);return w({key:h,op:"insert",row:{...r,_id:h},table:n}),h},Ze=(e,n)=>Rt(e,"relation load").findMany(e,n),Tt=(e,n)=>(le(e)&&R(e,O),Ze(e,n)),vn=e=>!le(e.table),It=t.relationExistsPushDown??"auto",At=It!=="never",{maxRelationKeys:Ct}=t,xe=(e,n,r)=>_o(e,{fetcher:Tt,maxRelationKeys:Ct,relationBaseWhere:r,schema:s,tableName:n}),xt=async(e,n,r,d)=>{const f=G(e,"relation grouped count");if(f)return R(e,O),Ao((g,P)=>f.count(g,P),e,n,r,d);const h=s.tables[e];if(!h)throw new y("INTERNAL",`unknown table: ${e}`);R(e,O);const l=ve(h.softDeleteMode,void 0),u={[n]:{in:r}},p=K(K(u,d),l),_=await xe(p,e,void 0),I=X(_,he),v=we(n);let T=a`SELECT ${v} AS __fk__, COUNT(*) AS count FROM ${a.identifier(e)}`;I&&(T=a`${T} WHERE ${I}`),T=a`${T} GROUP BY ${v}`;const b=H(c,T).toArray();return new Map(b.map(g=>[g.__fk__,g.count]))};let be=0;const bt=new Set;for(const[e,n]of Object.entries(s.tables))for(const r of Object.values(n.triggerMap??{}))bt.add(`${e} ${r.timing} ${r.op}`);const te=(e,n,r)=>bt.has(`${e} ${n} ${r}`),ne=async(e,n,r)=>{if(be+=1,be>tn)throw be-=1,new ae(`trigger recursion exceeded ${String(tn)} levels on "${r.table}" — check for a self-triggering write`,"trigger");try{await Mo({ctx:xn,event:r,op:n,schema:s,tableName:r.table,timing:e})}finally{be-=1}},{ensureBackfilledForTable:Ee,ensureBackfilledIndex:et,ensureRankBackfilled:tt,ensureRankBackfilledForTable:me,syncAggregates:Me,syncCompanionsForInsert:Mt,syncGeo:De,syncRanks:Se,syncSearch:ke}=Kn({broadcast:w,indexKeysFor:(e,n)=>F(e,n),invalidateCache:(e,n,r)=>re?.invalidate(e,n,F(e,r)),recordCdc:$e,schema:s,sql:c,verified:t.companionMemo?.verified}),Dt=(e,n,r)=>{const{shardMode:d}=n;if(d?.kind==="shardBy"&&!(d.field!==void 0&&(r.partitionBy??[]).includes(d.field)))throw Object.assign(new Error(`rank index "${r.name}" on "${e}" partitions across shards (shard key "${d.field??"?"}" is not in partitionBy) — a shard-local rank()/rankPage() would be wrong; roll it up through the Query Coordinator instead`),{code:"CROSS_SHARD_RANK_UNSUPPORTED",name:"LunoraError",status:400})},kt=e=>Object.entries(s.tables).filter(([,n])=>n.shardMode?.kind!=="global").map(([n])=>n).filter(n=>e===void 0||n===e),_e=e=>e===void 0||le(e)?ye:void 0,nt=async(e,n,r,d,f)=>{for(let h=0;h<r.length;h+=1)N(void 0);if(f!==void 0&&e.deleteMany!==void 0)return e.deleteMany(r,f.options,n);for(const h of r)await e.delete(h,n,d);return{deleted:r.length}},oe=(e,n)=>{const r=kt(n);for(let d=0;d<r.length;d+=Re){const f=r.slice(d,d+Re),[h]=pe(c,rr(f),...ir(e,f)).toArray();if(!h)continue;const l=h.__t__,u=Te(h);if(typeof l!="string"||!u)return;const p=h[ie];return{docJson:typeof p=="string"?p:fe(p??{}),row:u,tableName:l}}},Tn=(e,n)=>{const r=[...new Set(e)],d=new Map;if(r.length===0)return d;const f=kt(n);for(let h=0;h<f.length;h+=Re){const l=f.slice(h,h+Re),u=Math.floor(Re/l.length),p=Yn(a`${a.identifier("id")}`,r,!1,u),_=l.map(I=>a`SELECT ${a.raw(`'${I.replaceAll("'","''")}'`)} AS __t__, id FROM ${a.identifier(I)} WHERE ${p}`);for(const I of H(c,yt(_))){const{id:v,__t__:T}=I;typeof T=="string"&&typeof v=="string"&&d.set(v,T)}}return d},Lt={assertRankPartitionLocal:Dt,ensureRankBackfilled:tt,onRead:R,rowToDocument:Te,schema:s,sql:c},In=(e,n,r)=>{const d=X(r,he);return d===void 0||H(c,a`SELECT 1 FROM ${a.identifier(e)} WHERE ${a.identifier("id")} = ${n} AND ${d}`).toArray().length>0},An=(e,n,r,d)=>_t(e,n,r,d)?(o?.({fields:Object.keys(Ge(r)),id:n,table:e}),!0):!1,Cn=async(e,n,r,d,f)=>{const h=oe(n,e);if(!h)return{applied:!1,doc:null};if(R(e,n),!In(e,n,r.where)||An(e,n,r.patch,h.row))return{applied:!1,doc:h.row};try{await f(r.patch)}catch(l){if(l instanceof ae&&l.kind==="occ"&&d)return;throw l}return{applied:!0,doc:oe(n,e)?.row??null}},Ft=async(e,n,r,d)=>{const{fetchLimit:f,limit:h,orderKeys:l,predicate:u}=await Ro(n,r,{canPushExists:At?vn:void 0,existsPushMode:It==="always"?"always":"auto",fetcher:Tt,maxRelationKeys:Ct,schema:s,tableName:e}),p=At?Er(d):Je,_=X(u,p,Ve),I=yn(e,_,$n(l),f);return{limit:h,orderKeys:l,statement:I}},U={system:Rn,async aggregate(e,n){const r=G(e,"aggregate");if(r)return R(e,O),r.aggregate(e,n);const d=s.tables[e];if(!d)throw new y("INTERNAL",`unknown table: ${e}`);if(We(n.op),n.op==="count")return U.count(e,{baseWhere:n.baseWhere,relationBaseWhere:n.relationBaseWhere,restrictsCounts:n.restrictsCounts,where:n.where});if(!n.field)throw new y("INTERNAL",`aggregate(${e}, { op: "${n.op}" }): "field" is required for non-count reducers`);R(e,O);const f=ve(d.softDeleteMode,void 0),h=K(K(n.baseWhere,n.where),f),l=await xe(h,e,n.relationBaseWhere),u=l!==h;if(d.aggregateIndexes&&!n.baseWhere&&!u){const g=Bn(d.aggregateIndexes,n.op,n.field,n.where);if(g){et(e,g.index);const P=rt(g.index.by??[],g.key),z=ot(e,g.index.name),Y=H(c,a`SELECT ${Be} AS value, ${ct} AS count FROM ${a.identifier(z)} WHERE ${Pe} = ${P}`).toArray()[0];return it(n.op,Y)}}rn(d,n.field,`aggregate(${e}, { op: "${n.op}", field: "${n.field}" })`);const p=X(l,he),_=We(n.op),I=we(n.field);let v=a`SELECT ${a.raw(_)}(${I}) AS value FROM ${a.identifier(e)}`;p&&(v=a`${v} WHERE ${p}`);const b=H(c,v).toArray()[0]?.value;return b??null},asId(e,n){const r=sn(s,e,n);if(r===null)throw new y("BAD_REQUEST",`asId("${e}", …): "${n}" is not a valid id for table "${e}"`,{status:400});return r},async count(e,n){const r=G(e,"count");if(r)return R(e,O),r.count(e,n);const d=s.tables[e];if(!d)throw new y("INTERNAL",`unknown table: ${e}`);const f=Fn(n);if(f.restrictsCounts)throw new st(e);R(e,O);const h=ve(d.softDeleteMode,void 0),l=K(K(f.baseWhere,f.where),h),u=await xe(l,e,f.relationBaseWhere),p=u!==l;if(d.aggregateIndexes&&!f.baseWhere&&!p){const T=Wn(d.aggregateIndexes,f.where);if(T){et(e,T.index);const b=rt(T.index.by??[],T.key),g=ot(e,T.index.name),P=H(c,a`SELECT ${Be} AS value FROM ${a.identifier(g)} WHERE ${Pe} = ${b}`).toArray();return P[0]===void 0?0:P[0].value??0}}const _=X(u,he);let I=a`SELECT COUNT(*) AS count FROM ${a.identifier(e)}`;return _&&(I=a`${I} WHERE ${_}`),H(c,I).one().count},async delete(e,n,r){const d=oe(e,n);if(!d){const T=_e(n);T&&await nt(T,n,[e],r);return}const{docJson:f,row:h,tableName:l}=d,u=s.tables[l],p=r?.hard===!0,_=!p&&u?.softDeleteMode?u:void 0,I=_?.softDeleteMode?.field;if(I&&h[I]!==null&&h[I]!==void 0)return;if(te(l,"before","delete")&&await ne("before","delete",{id:e,op:"delete",previous:h,table:l}),await Io({deletedId:e,deletedReference:T=>h[T],findHolders:async(T,b,g,P)=>(await Xe(T).findMany(T,{...P,includeDeleted:p,where:{[b]:g}})).page,onCascade:(T,b)=>Xe(T).delete(b,void 0,r),onRestrict:T=>{throw new ae(T,"restrict")},onSetNull:(T,b,g)=>Xe(T).patch(b,{[g]:null}),schema:s,tableName:l}),Ee(l),me(l),_&&I){const T={[I]:ce()},b={...h,...B(l),...T,_id:e};lt(_,T,b,de),je(c,l,Zt(l),[fe(b),e,f]),ke(l,e,b,h),De(l,e,void 0),Me(l,h,b),Se(l,e,h,void 0);const g=F(l,h,b);re?.invalidate(l,e,g),$e(l,e,"update",b),w({indexKeys:g,key:e,op:"update",row:b,table:l}),te(l,"after","delete")&&await ne("after","delete",{id:e,op:"delete",previous:h,table:l}),await J({id:e,op:"delete",table:l});return}je(c,l,tr(l),[e,f]),ke(l,e,void 0),De(l,e,void 0),Me(l,h,void 0),Se(l,e,h,void 0);const v=F(l,h);re?.invalidate(l,e,v),$e(l,e,"delete"),w({indexKeys:v,key:e,op:"delete",table:l}),te(l,"after","delete")&&await ne("after","delete",{id:e,op:"delete",previous:h,table:l}),await J({id:e,op:"delete",table:l})},async deleteAll(e,n){if(!s.tables[e])throw new y("INTERNAL",`unknown table: ${e}`);const r=Math.max(1,n?.chunkSize??wn),d=n?.hard===void 0?void 0:{hard:n.hard},f=G(e,"deleteAll");let h=0;return await j(async()=>{for(;;){const u=(await U.findMany(e,{limit:r})).page.map(p=>String(p._id));if(u.length===0)break;for(const p of u)await(f===void 0?U.delete(p,e,d):nt(f,e,[p],d)),h+=1;if(u.length<r)break}}),{deleted:h}},async deleteMany(e,n,r){He(e.length,n?.limit,"deleteMany");for(const d of e)await U.delete(d,r);return{deleted:e.length}},async deleteWhere(e,n,r){const d=G(e,"deleteWhere"),h=(await nn(d??U,e,n,r?.limit,"deleteWhere")).map(l=>String(l._id));if(d)return nt(d,e,h,void 0,{options:r});if(U.deleteMany===void 0)throw new y("INTERNAL",`ctx.db.${e}.deleteMany is unavailable: this writer has no batch delete`);return U.deleteMany(h,r,e)},async findFirst(e,n={}){return(await U.findMany(e,{...n,limit:1,omitContinueCursor:!0})).page[0]??null},async findFirstOrThrow(e,n={}){const r=await U.findFirst(e,n);if(r===null)throw new no(`findFirstOrThrow: no "${e}" document matched`);return r},async findMany(e,n={}){const r=G(e,"findMany");if(r)return R(e,O),r.findMany(e,n);const d=s.tables[e];if(!d)throw new y("INTERNAL",`unknown table: ${e}`);const f=!n.where&&!n.baseWhere;f?R(e,O):R(e);const{limit:h,orderKeys:l,statement:u}=await Ft(e,d,n,R),p=pe(c,u.text,...u.params).toArray();f&&!q&&L?.recordRead(p.length);const _=[];for(const b of p){const g=Te(b);g&&(_.push(g),!f&&typeof g._id=="string"&&R(e,g._id))}if(h===void 0)return n.with&&await Vt({groupedCounter:xt,fetcher:Ze,parents:_,...Jt(n),schema:s,tableName:e,with:n.with}),{continueCursor:null,isDone:!0,page:Gt(_,n.select,n.with)};const I=_.length>h,v=I?_.slice(0,h):_,T=v.at(-1);return n.with&&await Vt({fetcher:Ze,groupedCounter:xt,parents:v,...Jt(n),schema:s,tableName:e,with:n.with}),{continueCursor:I&&T&&n.omitContinueCursor!==!0?Ke(T,l):null,isDone:!I,page:Gt(v,n.select,n.with)}},async explain(e,n={}){const r=G(e,"explain");if(r)return r.explain(e,n);const d=s.tables[e];if(!d)throw new y("INTERNAL",`unknown table: ${e}`);const{statement:f}=await Ft(e,d,n,()=>{}),h=pe(c,`EXPLAIN QUERY PLAN ${f.text}`,...f.params).toArray();return{params:f.params,plan:h.map(l=>String(l.detail)),sql:f.text}},async get(e,n){const r=oe(e,n);if(!r){const d=_e(n);return d?d.get(e,n):null}return R(r.tableName,e),r.row},async lookupById(e,n){const r=oe(e,n);return r?(R(r.tableName,e),{row:r.row,tableName:r.tableName}):null},async groupBy(e,n){const r=G(e,"groupBy");if(r)return R(e,O),r.groupBy(e,n);const d=s.tables[e];if(!d)throw new y("INTERNAL",`unknown table: ${e}`);R(e,O);const f=n.agg??{op:"count"};if(We(f.op),f.op!=="count"&&!f.field)throw new y("INTERNAL",`groupBy(${e}, { agg: { op: "${f.op}" } }): "field" is required for non-count reducers`);const h=ve(d.softDeleteMode,void 0),l=K(K(n.baseWhere,n.where),h),u=await xe(l,e,n.relationBaseWhere),p=u!==l;if(d.aggregateIndexes&&!n.baseWhere&&!p){const g=qn(d.aggregateIndexes,f.op,f.field,n.by,n.where),P=g===void 0?0:Object.keys(g.partial).length,z=g?.index.by?.length??0;if(g&&(P===0||P===z)){et(e,g.index);const Y=ot(e,g.index.name),Q=Object.keys(g.partial),ue=[];if(Q.length===(g.index.by??[]).length&&Q.length>0){const Le=rt(g.index.by??[],g.partial),Fe=H(c,a`SELECT ${Be} AS value, ${ct} AS count FROM ${a.identifier(Y)} WHERE ${Pe} = ${Le}`).toArray();return Fe.length>0&&ue.push({key:{...g.partial},value:it(f.op,Fe[0])}),ue}const bn=H(c,a`SELECT ${Pe} AS key, ${Be} AS value, ${ct} AS count FROM ${a.identifier(Y)}`).toArray();for(const Le of bn){const Fe=kn(JSON.parse(Le.key));ue.push({key:Fe,value:it(f.op,Le)})}return ue}}for(const g of[...n.by,f.field]){if(g===void 0)continue;const P=g===f.field?`groupBy(${e}, { agg: { op: "${f.op}", field: "${g}" } })`:`groupBy(${e}, { by: [..."${g}"] })`;rn(d,g,P)}const _=X(u,he),I=n.by.map(g=>a`${we(g)} AS ${a.identifier(g)}`);if(f.op==="count")I.push(a`COUNT(*) AS value`);else{const{field:g}=f;if(g===void 0)throw new y("INTERNAL",`groupBy(${e}, { agg: { op: "${f.op}" } }): "field" is required for non-count reducers`);I.push(a`${a.raw(We(f.op))}(${we(g)}) AS value`)}let v=a`SELECT ${a.join(I,a`, `)} FROM ${a.identifier(e)}`;_&&(v=a`${v} WHERE ${_}`),v=a`${v} GROUP BY ${a.join(n.by.map(g=>we(g)),a`, `)}`;const T=H(c,v).toArray(),b=[];for(const g of T){const P={};for(const Y of n.by)P[Y]=Qn(d.shape[Y],g[Y]??null);const{value:z}=g;b.push({key:P,value:z==null?null:Number(z)})}return b},async insert(e,n,r){const d=G(e,"insert");if(d)return vt(d,e,n,r,!0);const f=s.tables[e];if(!f)throw new y("INTERNAL",`unknown table: ${e}`);const h=r?.allowExplicitId===!0,l=Ue(f,ft(f,n,de),{supplied:n,trusted:h});let u;r?.clientId!==void 0?(cr(r.clientId),u=r.clientId):r?.allowExplicitId&&typeof l._id=="string"?(wt(l._id),u=l._id):u=Et();const p=r?.allowExplicitId&&typeof l._creationTime=="number"?l._creationTime:ce(),_={...l,...B(e),_creationTime:p,_id:u};return te(e,"before","insert")&&await ne("before","insert",{doc:{..._},id:u,op:"insert",table:e}),h||C(e,_),Ee(e),me(e),pt(c,e,Zo(e),[u,p,fe(_)]),Mt(e,u,_),te(e,"after","insert")&&await ne("after","insert",{doc:_,id:u,op:"insert",table:e}),await J({doc:_,id:u,op:"insert",table:e}),u},async insertManyUnsafe(e,n,r){if(He(n.length,r?.limit,"insertManyUnsafe"),n.length===0)return[];const d=G(e,"insert");if(d){const p=[];ar(s.tables[e],n,r?.allowExplicitId,de);for(const _ of n)N(_);for(const _ of n){const I=await d.insert(e,_,{allowExplicitId:r?.allowExplicitId});w({key:I,op:"insert",row:{..._,_id:I},table:e}),p.push(I)}return p}const f=s.tables[e];if(!f)throw new y("INTERNAL",`unknown table: ${e}`);Ee(e),me(e);const h=[];for(let p=0;p<n.length;p+=Oe)h.push(B(e));const l=r?.allowExplicitId===!0?void 0:To(f),u=n.map((p,_)=>{const I=ft(f,p,de),v=l===void 0?I:Ue(l,I,{supplied:p}),T=r?.allowExplicitId===!0&&typeof v._id=="string"?v._id:void 0;T!==void 0&&wt(T);const b=T??Et(),g=r?.allowExplicitId===!0&&typeof v._creationTime=="number"?v._creationTime:ce(),P={...v,...h[Math.floor(_/Oe)],_creationTime:g,_id:b};return{creationTime:g,document:P,id:b}});for(const p of u)N(p.document);for(let p=0;p<u.length;p+=Oe){const _=a.join(u.slice(p,p+Oe).map(v=>a`(${v.id}, ${v.creationTime}, ${fe(v.document)})`),a`, `),I=fn("sqlite",a`INSERT INTO ${a.identifier(e)} (id, _creationTime, ${a.identifier(ie)}) VALUES ${_}`);pt(c,e,I.sql,I.params)}for(const{document:p,id:_}of u)Mt(e,_,p),await ee({doc:p,id:_,op:"insert",table:e});return u.map(p=>p.id)},async insertMany(e,n,r){He(n.length,r?.limit,"insertMany");const d=r?.skipDuplicates===!0,f=[],h=G(e,"insert");if(h)for(const u of n)N(u);const l=async u=>h?vt(h,e,u,void 0,!1):U.insert(e,u);for(const u of n)try{f.push(await l(u))}catch(p){if(d&&p instanceof ae&&p.kind==="unique")f.push(null);else throw p}return f},normalizeId(e,n){return sn(s,e,n)},async patch(e,n,r,d){const f=oe(e,r);if(!f){const b=_e(r);if(b){N(n),await b.patch(e,n,r,d);return}throw new y("NOT_FOUND",`document not found: ${e}`)}const{docJson:h,row:l,tableName:u}=f,p=s.tables[u];if(!p)throw new y("INTERNAL",`unknown table: ${u}`);if(R(u,e),an("patch",n),_t(u,e,n,l)){o?.({fields:Object.keys(Ge(n)),id:e,table:u});return}const _=oo(p,n,l),I={...l,...Ge(_),...B(u),_id:e};lt(p,_,I,de);const v=Ue(p,I,{only:new Set(Object.keys(_)),previous:()=>l,tolerateStoredNull:!0});ro(d,l,v),te(u,"before","update")&&await ne("before","update",{doc:{...v},id:e,op:"update",previous:l,table:u}),C(u,v,l),Ee(u),me(u),je(c,u,Zt(u),[fe(v),e,h]),ke(u,e,v,l),De(u,e,v),Me(u,l,v),Se(u,e,l,v);const T=F(u,l,v);re?.invalidate(u,e,T),$e(u,e,"update",v),w({indexKeys:T,key:e,op:"update",row:v,table:u}),te(u,"after","update")&&await ne("after","update",{doc:v,id:e,op:"update",previous:l,table:u}),await J({doc:v,id:e,op:"update",table:u})},async patchIf(e,n,r){const d=G(e,"patchIf");if(d){if(d.patchIf===void 0)throw new y("INTERNAL",`ctx.db.patchIf on global table '${e}' is unsupported: its backend has no conditional write`);return N(r.patch),d.patchIf(e,n,r)}if(!s.tables[e])throw new y("INTERNAL",`unknown table: ${e}`);for(let f=1;f<=cn;f+=1){const h=await Cn(e,n,r,f<cn,l=>U.patch(n,l,e,{verify:r.verify}));if(h!==void 0)return h}throw new ae(`patchIf on "${e}" kept conflicting; the row changed on every attempt`,"occ")},async patchMany(e,n,r){He(e.length,n?.limit,"patchMany");for(const d of e)await U.patch(d.id,d.patch,r);return{patched:e.length}},async patchWhere(e,n,r){const d=G(e,"patchWhere")??U,h=(await nn(d,e,n.where,r?.limit,"patchWhere")).map(l=>({id:String(l._id),patch:n.patch}));if(U.patchMany===void 0)throw new y("INTERNAL",`ctx.db.${e}.patchMany is unavailable: this writer has no batch patch`);return await U.patchMany(h,r,e),{patched:h.length}},async related(e,n){return So(U,m,e,n)},relationEdges:m,deleteRereadTables:W,inTransaction:D,softDeleteFields:x,relationWrites:$,query(e){const n=G(e,"query");return n?(R(e,O),n.query(e)):_n(c,s,e,k,r=>{r?M(r):R(e,O)},r=>{q||L?.recordRead(r)})},async rank(e,n,r){const d=G(e,"rank");if(d)return R(e,O),d.rank(e,n,r);k(e,n,"rank");const f=s.tables[e];if(!f)throw new y("INTERNAL",`unknown table: ${e}`);const h=f.rankIndexes?.find(Q=>Q.name===n);if(!h)throw new y("INTERNAL",`unknown rankIndex "${n}" on table "${e}"`);if(Dt(e,f,h),r.restrictsCounts)throw new st(e);R(e,O),tt(e,h);const l=typeof r.row=="string"?r.row:r.row._id;if(!l)return null;const u=jt(e,h.name),p=h.sortBy.map((Q,ue)=>Kt(ue)),_=p.map(Q=>Ce(Q)).join(", "),I=H(c,a`SELECT ${a.identifier("__partition__")}, ${a.raw(_)} FROM ${a.identifier(u)} WHERE ${a.identifier("__id__")} = ${l}`).toArray(),[v]=I;if(v===void 0)return null;let T=v.__partition__;const b=K(r.baseWhere,r.where);at(b,s,e,"rank");const g=fo(h,b);if(g){const Q=ho(h.partitionBy??[],g);if(Q!==T)return null;T=Q}const P=p.map(Q=>v[Q]),{before:z,total:Y}=ln(c,u,p,h.sortBy,T,P,l);return{position:z+1,total:Y}},async rankBefore(e,n,r){if(le(e))throw new y("INTERNAL",`rankBefore is not supported on the global (.global()) table '${e}' — cross-shard rank cursors apply only to sharded tables`);const d=s.tables[e];if(!d)throw new y("INTERNAL",`unknown table: ${e}`);const f=d.rankIndexes?.find(p=>p.name===n);if(!f)throw new y("INTERNAL",`unknown rankIndex "${n}" on table "${e}"`);if(r.restrictsCounts)throw new st(e);R(e,O),tt(e,f);const h=jt(e,f.name),l=f.sortBy.map((p,_)=>Kt(_)),u=f.sortBy.map((p,_)=>Ae(r.sortValues[_]??null));return ln(c,h,l,f.sortBy,r.partitionKey,u,r.rowId)},async rankPage(e,n,r={}){at(K(r.baseWhere,r.where),s,e,"rankPage");const d=G(e,"rankPage");if(d)return R(e,O),d.rankPage(e,n,r);k(e,n,"rank");const{continueCursor:f,hasMore:h,rows:l}=Bt(Lt,e,n,r);return{continueCursor:f,isDone:!h,page:l.map(u=>u.doc)}},async rankPageRows(e,n,r={}){at(K(r.baseWhere,r.where),s,e,"rankPage"),k(e,n,"rank");const{directions:d,hasMore:f,rows:h}=Bt(Lt,e,n,r);return{directions:d,hasMore:f,rows:h}},async restore(e,n){const r=oe(e,n);if(!r){const h=_e(n);if(h?.restore){await h.restore(e,n);return}throw new y("NOT_FOUND",`document not found: ${e}`)}const d=s.tables[r.tableName]?.softDeleteMode?.field;if(!d)throw new y("INTERNAL",`ctx.db.restore: table "${r.tableName}" is not a .softDelete() table`);const f=r.row[d]!==null&&r.row[d]!==void 0;await U.patch(e,{[d]:null},n),f&&Se(r.tableName,e,void 0,r.row)},async replace(e,n,r,d){const f=oe(e,r);if(!f){const P=_e(r);if(P){N(n),await P.replace(e,n,r,d);return}throw new y("NOT_FOUND",`document not found: ${e}`)}const{docJson:h,row:l,tableName:u}=f,p=s.tables[u];if(!p)throw new y("INTERNAL",`unknown table: ${u}`);an("replace",n);const _=d?.allowExplicitId&&typeof n._creationTime=="number"?n._creationTime:void 0,I=typeof l._creationTime=="number"?l._creationTime:void 0,v=_??I??ce(),T={...n,...B(u),_creationTime:v,_id:e};lt(p,n,T,de);const b=d?.allowExplicitId===!0,g=Ue(p,T,{previous:()=>l,supplied:n,trusted:b});te(u,"before","update")&&await ne("before","update",{doc:{...g},id:e,op:"update",previous:l,table:u}),b||C(u,g,l),Ee(u),me(u),je(c,u,er(u),[v,fe(g),e,h]),ke(u,e,g,l),De(u,e,g),Me(u,l,g),Se(u,e,l,g),re?.invalidate(u,e,F(u,l,g)),$e(u,e,"update",g),w({indexKeys:F(u,l,g),key:e,op:"update",row:g,table:u}),te(u,"after","update")&&await ne("after","update",{doc:g,id:e,op:"update",previous:l,table:u}),await J({doc:g,id:e,op:"update",table:u})},async wipeShard(e){const n=new Set(e?.exclude),r=e?.tables,d=Object.entries(s.tables).filter(([u,p])=>n.has(u)||r!==void 0&&!r.includes(u)?!1:p.shardMode?.kind!=="global").map(([u])=>u);if(r!==void 0){for(const u of r)if(!s.tables[u])throw new y("INTERNAL",`wipeShard: unknown table: ${u}`)}const f={};let h=0;const{deleteAll:l}=U;if(l===void 0)throw new y("INTERNAL","wipeShard: this writer has no deleteAll");for(const u of d){const p=await l(u,{...e?.chunkSize===void 0?{}:{chunkSize:e.chunkSize},hard:!0});f[u]=p.deleted,h+=p.deleted}return{deleted:h,tables:f}}},xn={db:U,scheduler:mt};return t.enforceRls===!0?Co(U,s,(e,n)=>oe(e,n)?.tableName,(e,n)=>Tn(e,n),m):U};export{mi as CDC_LOG_TABLE,Hi as IDEMPOTENCY_TABLE,mr as NotUniqueError,Bi as advanceClientWatermark,Si as applyCdcChanges,an as assertNoExplicitUndefined,wt as assertStorableRowId,cr as assertValidClientId,gi as backfillAggregateIndexes,yi as backfillRankIndexes,$i as backfillSearchIndexes,_i as bumpCdcEpoch,Ri as cdcCanVouchFor,vi as cdcForkedError,Ti as cdcSeqLeavingRows,Ii as cdcTouchesTables,Ai as cdcTrimmedError,Ci as compactCdcDocs,hi as createShardCtxDb,xi as cursorBelowRetainedFloor,Pi as migrateClientWatermark,bi as minCdcReplayableSeq,Mi as minCdcSeq,sn as normalizeIdStructurally,Di as readCdcChangeKeys,ki as readCdcChanges,Li as readCdcCursor,Fi as readCdcEpoch,Ui as readClientWatermark,Gi as readIdempotent,Qi as runShardMigrations,Ji as selectShapeMembers,zi as selectShapeRows,Ge as stripReservedPatchFields,qi as trimCdcChanges,ji as trimIdempotent,Ki as writeIdempotent};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{isLunoraError as S}from"@lunora/errors";import{l as R,b as L}from"./ctx-db-search-state-FjgzTFok.mjs";import{sql as e}from"drizzle-orm";import{readKeysetPage as _}from"./backfillAggregateIndexes-
|
|
1
|
+
import{isLunoraError as S}from"@lunora/errors";import{l as R,b as L}from"./ctx-db-search-state-FjgzTFok.mjs";import{sql as e}from"drizzle-orm";import{readKeysetPage as _}from"./backfillAggregateIndexes-BN0NwXQk.mjs";import{runDrizzle as p}from"./runDrizzle-RC09zZrh.mjs";import{h}from"./do-sql-BWrJQAOh.mjs";const u="__lunora_vector_backfill",m=50,k=20,w=20,N=3,O=i=>{p(i,e`CREATE TABLE IF NOT EXISTS ${e.identifier(u)} (${e.identifier("companion")} TEXT PRIMARY KEY, ${e.identifier("cursor")} TEXT, ${e.identifier("done")} INTEGER NOT NULL DEFAULT 0, ${e.identifier("profile")} TEXT, ${e.identifier("strikes")} INTEGER NOT NULL DEFAULT 0)`);try{p(i,e`ALTER TABLE ${e.identifier(u)} ADD COLUMN ${e.identifier("strikes")} INTEGER NOT NULL DEFAULT 0`)}catch{}},C=(i,o)=>{const[s]=p(i,e`SELECT ${e.identifier("strikes")} FROM ${e.identifier(u)} WHERE ${e.identifier("companion")} = ${o}`).toArray();return s?.strikes??0},$=(i,o,s,d,t,r=0)=>{const n=s??null;p(i,e`INSERT INTO ${e.identifier(u)} (${e.identifier("companion")}, ${e.identifier("cursor")}, ${e.identifier("done")}, ${e.identifier("profile")}, ${e.identifier("strikes")}) VALUES (${o}, ${n}, ${d?1:0}, ${t}, ${r}) ON CONFLICT (${e.identifier("companion")}) DO UPDATE SET ${e.identifier("cursor")} = excluded.${e.identifier("cursor")}, ${e.identifier("done")} = excluded.${e.identifier("done")}, ${e.identifier("profile")} = excluded.${e.identifier("profile")}, ${e.identifier("strikes")} = excluded.${e.identifier("strikes")}`)},A=(i,o,s)=>{const d=_(i,o,s,m+1),t={documents:[],lastId:s,more:d.length>m,unparseable:[]};for(const r of d.slice(0,m)){if(typeof r.id!="string")continue;t.lastId=r.id;const n=h(r);n?t.documents.push({doc:n,id:t.lastId}):t.unparseable.push(t.lastId)}return t},D=(i,o,s,d,t)=>{const r=t instanceof Error?t.message:String(t),n=L(i,u,o),a=n.profile===d&&n.cursor===s?C(i,o):0;if(S(t)&&t.code==="SERVICE_UNAVAILABLE")return a>0&&$(i,o,s,!1,d,0),{error:r};const f=a+1;if(f<N)return $(i,o,s,!1,d,f),{error:r};const c=A(i,o,s),l=[...c.documents.map(E=>E.id),...c.unparseable];return console.warn(`[@lunora/shard-engine] vector backfill: a page of "${o}" failed ${String(f)} times in a row; its ${String(l.length)} row(s) are recorded as failed:`,t),{failedIds:l,page:c}},F=async(i,o,s,d,t)=>{const{profile:r,table:n}=o;try{const{failures:a,page:f}=await t(()=>A(i,n,s),async c=>({failures:await d(n,c.documents),page:c}));return a.length>0&&console.warn(`[@lunora/shard-engine] vector backfill: ${String(a.length)} row(s) of "${n}" could not be indexed:`,a),{failedIds:[...f.unparseable,...a.map(c=>c.id)],page:f}}catch(a){return D(i,n,s,r,a)}},y=async(i,o,s,d)=>{if(O(i),d.restart===!0)for(const{profile:n,table:a}of o)$(i,a,void 0,!1,n);const t=Math.min(d.maxPages??1,k),r={done:!1,failed:0,failedIds:[],pages:0,rows:0};for(const{profile:n,table:a}of o){const f=R(L(i,u,a),n);let{cursor:c}=f,l=f.finished;for(;!l;){if(r.pages>=t)return r;const E=await F(i,{profile:n,table:a},c,s,d.ordered);if("error"in E)return{...r,error:E.error};const{failedIds:g,page:T}=E,I=T.documents.length+T.unparseable.length;r.pages+=I>0?1:0,r.rows+=I,r.failed+=g.length,r.failedIds=[...r.failedIds,...g].slice(0,w),c=T.lastId,l=!T.more,$(i,a,c,l,n)}}return{...r,done:!0}};export{k as VECTOR_BACKFILL_MAX_PAGES,m as VECTOR_BACKFILL_PAGE_ROWS,y as backfillVectorIndexes};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{LunoraError as S}from"@lunora/errors";import{t as z}from"./do-sql-BWrJQAOh.mjs";import{applySelect as Y}from"./CURSOR_PREFIX-6offuG6M.mjs";const U=Symbol.for("lunora.relations.fanOutBudget"),de=e=>({fanOutBudget:e[U],relationBaseWhere:e.relationBaseWhere,relationMask:e.relationMask}),L=(e,t)=>t.select?Y(e,t.select,t.with):e,pe=async(e,t,n,r,o)=>{const a=await Promise.all(r.map(async c=>{const u=o?{AND:[{[n]:c},o]}:{[n]:c};return[c,await e(t,u)]}));return new Map(a)},ee=32,B=1e4,te=(e,t,n)=>{const r=new Map;for(const o of e)for(const a of n(o)){const c=a[t],u=r.get(c);u?u.push(a):r.set(c,[a])}return r},W=(e,t)=>({...e,[U]:t}),ne=(e,t)=>{const n=new Map;for(const[o,a]of e)for(const c of a){const u=n.get(c);u?u.push(o):n.set(c,[o])}const r=new Map;for(const o of t)for(const a of n.get(o._id)??[]){const c=r.get(a);c?c.push(o):r.set(a,[o])}return r},D=(e,t)=>{const n=new Set;for(const r of e){const o=r[t];o!=null&&n.add(o)}return[...n]},he=async e=>{const{groupedCounter:t,fanOutBudget:n,fetcher:r,parents:o,relationBaseWhere:a,relationMask:c,schema:u,tableName:p,with:b}=e,O=n??{remaining:ee},y=(f,s)=>c?.(f,s)??s;if(o.length===0)return;const M=u.tables[p];if(!M)throw new S("INTERNAL",`unknown table: ${p}`);const _=M.relationMap??{},G=(f,s)=>{const i=d=>u.tables[d]?.shardMode?.kind??"root";return i(f)===i(s)&&i(f)!=="shardBy"},R=f=>{const s=_[f];if(!s)throw new S("INTERNAL",`unknown relation "${f}" on table "${p}"`);return s},X=async(f,s,i)=>{const d=D(o,s.field);if(d.length===0){for(const h of o)h[f]=null;return}const{page:l}=await r(s.table,W({baseWhere:a?.(s.table),relationBaseWhere:a,relationMask:c,where:{[s.references]:{in:d}},with:i.with},O)),w=new Map;for(const h of y(s.table,l))w.set(h[s.references],h);for(const h of o){const A=w.get(h[s.field]);h[f]=A?L([A],i)[0]??null:null}},j=async(f,s,i,d)=>{const{page:l}=await r(f,W({baseWhere:a?.(f),limit:d,orderBy:s.orderBy,relationBaseWhere:a,relationMask:c,where:s.where?{AND:[s.where,i]}:i,with:s.with},O));return l},T=(f,s,i,d,l)=>{for(const w of o){const h=l.get(w[d])??[];w[f]=L(i===void 0?h:h.slice(0,i),s)}},K=async(f,s,i)=>{const d=D(o,s.references);if(d.length===0){for(const g of o)g[f]=[];return}const l=typeof i.limit=="number"?Math.max(0,Math.floor(i.limit)):void 0,w=(g,k)=>j(s.table,i,g,k);if(l===0){for(const g of o)g[f]=[];return}const h=l!==void 0&&d.length<=O.remaining;h&&(O.remaining-=d.length);const A=h?await Promise.all(d.map(async g=>w({[s.field]:g},l))):[await w({[s.field]:{in:d}},void 0)],m=te(A,s.field,g=>y(s.table,g));T(f,i,l,s.references,m)},I=async f=>{const{from:s,table:i,to:d}=f.through,l=new Map,w=D(o,"_id");if(w.length===0)return l;const h=await j(i,{},{[s]:{in:w}},B+1);if(h.length>B)throw new S("INTERNAL",`loading "${p}" relations through "${i}" read more than ${String(B)} join rows for one page; load fewer ${p} rows at a time`);for(const A of y(i,h)){const m=A[s],g=A[d];if(m==null||g===null||g===void 0)continue;const k=l.get(m);k?k.add(g):l.set(m,new Set([g]))}return l},q=async(f,s,i)=>{const d=typeof i.limit=="number"?Math.max(0,Math.floor(i.limit)):void 0,l=d===0?new Map:await I(s),w=(A,m)=>j(s.table,i,{_id:{in:[...A]}},m);let h=new Map;if(l.size>0&&d!==void 0&&l.size<=O.remaining){O.remaining-=l.size;const A=[...l.keys()],m=await Promise.all([...l.values()].map(async g=>w(g,d)));h=new Map(A.map((g,k)=>[g,y(s.table,m[k]??[])]))}else if(l.size>0){const A=new Set([...l.values()].flatMap(m=>[...m]));h=ne(l,y(s.table,await w(A,void 0)))}T(f,i,d,"_id",h)},Z=async(f,s)=>{const i=[...s];if(i.length===0)return new Set;if(G(p,f)){const l=await t(f,"_id",i,a?.(f));return new Set(i.filter(w=>(l.get(w)??0)>0))}const d=await j(f,{},{_id:{in:i}},void 0);return new Set(d.map(l=>l._id))},J=async(f,s)=>{const i=await I(s),d=await Z(s.table,new Set([...i.values()].flatMap(l=>[...l])));for(const l of o){const w=l._count??{};w[f]=[...i.get(l._id)??[]].filter(h=>d.has(h)).length,l._count=w}},Q=async f=>{for(const s of Object.keys(f)){const i=R(s);if(i.through!==void 0){await J(s,i);continue}const[d,l]=i.kind==="many"?[i.field,i.references]:[i.references,i.field],w=a?.(i.table),h=D(o,l),A=h.length===0?new Map:await t(i.table,d,h,w);for(const m of o){const g=m._count??{},k=m[l];g[s]=k==null?0:A.get(k)??0,m._count=g}}};for(const[f,s]of Object.entries(b)){if(s===void 0||s===!1)continue;if(f==="_count"){await Q(s);continue}const i=R(f),d=s===!0?{}:s;i.through===void 0?await(i.kind==="one"?X(f,i,d):K(f,i,d)):await q(f,i,d)}},N=1e4,x=500,oe=async(e,t,n,r,o)=>{const a=new Set;let c=o;for(;;){const u=c!==void 0,p=c??await e();let b=!1;c=void 0;for(const O of p){const y=O._id;if(!(typeof y!="string"||a.has(y))){if(a.add(y),b=!0,a.size>N)throw n();await t(y)}}if(!u){if(p.length<x)return;if(!b)throw new S("INTERNAL",r)}}},H=(e,t,n)=>new S("CASCADE_LIMIT",`cannot delete "${e}" row: more than ${String(N)} ${t} rows reference it (onDelete: ${n}) — delete or re-point them in batches first`,{status:400}),re=async(e,t,n,r)=>{const{deletedId:o,deletedReference:a,findHolders:c,onRestrict:u,tableName:p}=e,b=n.references==="_id"?o:a(n.references);if(b==null)return;const{field:O}=n,y=`"${t}.${O}"`,M=await c(t,O,b,{limit:r==="restrict"?1:N+1,select:["_id"]});if(M.length!==0){if(r==="restrict")return u(`cannot delete "${p}" row: ${y} still references it`);if(M.length>N)throw H(p,y,r);return{action:r,field:O,holderTable:t,label:y,probe:M,referencedValue:b}}},se=async(e,t,n)=>{const{findHolders:r,onCascade:o,onSetNull:a,tableName:c}=e,{action:u,field:p,holderTable:b,label:O,probe:y,referencedValue:M}=t;await oe(()=>r(b,p,M,{limit:x}),_=>u==="cascade"?o(b,_):a(b,_,p),()=>H(c,O,u),`onDelete on "${c}" made no progress: ${O} rows still match after being processed`,n?y:void 0)},we=async e=>{const{schema:t,tableName:n}=e;if(!t.tables[n])throw new S("INTERNAL",`unknown table: ${n}`);const r=[];for(const[o,a]of Object.entries(t.tables)){const c=a.relationMap;if(c)for(const u of Object.values(c)){if(u.kind!=="one"||u.table!==n||!u.onDelete)continue;const p=await re(e,o,u,u.onDelete);p&&r.push(p)}}for(const[o,a]of r.entries())await se(e,a,o===0)},P=new WeakMap,V=e=>{const t=P.get(e);if(t!==void 0)return t;const n=e._meta,r=[n?.inner,n?.keyValidator,n?.valueValidator,...n?.members??[],...Object.values(n?.shape??{})],o=e.kind==="from"||r.some(a=>a!==void 0&&V(a));return P.set(e,o),o},$=e=>{const t=Object.getPrototypeOf(e);return t===Object.prototype||t===null},F=e=>e instanceof ArrayBuffer?new Uint8Array(e):ArrayBuffer.isView(e)?new Uint8Array(e.buffer,e.byteOffset,e.byteLength):void 0,E=(e,t)=>{if(Object.is(e,t))return!0;if(e instanceof Date&&t instanceof Date)return e.getTime()===t.getTime();const n=F(e),r=F(t);if(n!==void 0||r!==void 0)return n!==void 0&&r!==void 0&&Object.getPrototypeOf(e)===Object.getPrototypeOf(t)&&n.length===r.length&&n.every((u,p)=>u===r[p]);if(Array.isArray(e)||Array.isArray(t))return Array.isArray(e)&&Array.isArray(t)&&e.length===t.length&&e.every((u,p)=>E(u,t[p]));if(typeof e!="object"||typeof t!="object"||e===null||t===null||!$(e)||!$(t))return!1;const o=e,a=t,c=Object.keys(o);return c.length===Object.keys(a).length&&c.every(u=>u in a&&E(o[u],a[u]))},C=new WeakMap,ge=e=>{if(C.has(e))return C.get(e);const t=Object.fromEntries(Object.entries(e.shape).filter(([,r])=>V(r))),n=Object.keys(t).length>0?{...e,shape:t}:void 0;return C.set(e,n),n},ie=e=>{let t;return(n,r)=>e===void 0?!1:(t??=e()??{},n in t&&E(r,t[n]))},ae=(e,t)=>{const n=new Set(Object.keys(t).filter(r=>t[r]!==void 0));for(const[r,o]of z(e))o.serverDefault&&n.delete(r);return n},ce=(e,t,n,r,o)=>n.trusted===!0||r!==void 0&&!r.has(e)||o(e,t),v=e=>typeof e!="object"||e===null?e:e instanceof Date?new Date(e):e instanceof ArrayBuffer||ArrayBuffer.isView(e)?structuredClone(e):Array.isArray(e)?e.map(t=>v(t)):e instanceof Map?new Map([...e].map(([t,n])=>[v(t),v(n)])):e instanceof Set?new Set([...e].map(t=>v(t))):$(e)?Object.fromEntries(Object.entries(e).map(([t,n])=>[t,v(n)])):e,ye=(e,t,n)=>{const r={...t};for(const[o,a]of z(e)){if(a.serverDefault){r[o]=a.serverDefault({auth:n});continue}if(r[o]===void 0){if(a.defaultFn)r[o]=a.defaultFn();else if("defaultValue"in a){const{defaultValue:c}=a;r[o]=v(c)}}}return r},me=(e,t,n={})=>{let r;const o=ie(n.previous),a=n.only??(n.supplied===void 0?void 0:ae(e,n.supplied));for(const[c,u]of Object.entries(e.shape)){if(!(c in t)||typeof u.parse!="function")continue;const p=V(u);if(p&&ce(c,t[c],n,a,o)||n.tolerateStoredNull===!0&&t[c]===null&&u.kind==="optional")continue;const b=u.parse(t[c]);p&&(r??={...t},r[c]=b)}return r??t};export{B as MAX_LINK_ROWS,ye as applyInsertDefaults,we as applyOnDelete,D as distinctValues,pe as fanOutScalarCounts,de as relationHooks,he as resolveWith,me as runRowValidators,ge as transformOnlyDefinition};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{m as P,c as E,l as w,r as T,a as D,w as F}from"./ctx-db-search-state-FjgzTFok.mjs";import{S as I,c as L,g as _,d as x,e as b,a as k}from"./fts-companion-CA8mLJWq.mjs";import{sql as i}from"drizzle-orm";import{ensureAggregateCompanion as y,ensureRankCompanion as B}from"./createCompanionSync-
|
|
1
|
+
import{m as P,c as E,l as w,r as T,a as D,w as F}from"./ctx-db-search-state-FjgzTFok.mjs";import{S as I,c as L,g as _,d as x,e as b,a as k}from"./fts-companion-CA8mLJWq.mjs";import{sql as i}from"drizzle-orm";import{ensureAggregateCompanion as y,ensureRankCompanion as B}from"./createCompanionSync-zIF_F4oD.mjs";import{runDrizzle as p,runAll as C}from"./runDrizzle-RC09zZrh.mjs";import{i as M,D as m,h as A}from"./do-sql-BWrJQAOh.mjs";import{sqliteInList as U}from"./WORKERD_SQLITE_LIMITS-B_4w7tzY.mjs";const v=(e,o)=>p(e,i`SELECT 1 FROM ${i.identifier(o)} LIMIT 1`).toArray().length>0,Q=(e,o)=>{for(const[r,n]of Object.entries(o.tables))if(n.shardMode?.kind!=="global")for(const t of n.aggregateIndexes??[])y(e,r,t,n.softDeleteMode?.field)},X=(e,o)=>{for(const[r,n]of Object.entries(o.tables))if(n.shardMode?.kind!=="global")for(const t of n.rankIndexes??[])B(e,r,t,n.softDeleteMode?.field)},H=(e,o,r,n)=>p(e,r===void 0?i`SELECT id, _creationTime, ${i.identifier(m)} FROM ${i.identifier(o)} ORDER BY id ASC LIMIT ${i.raw(String(n))}`:i`SELECT id, _creationTime, ${i.identifier(m)} FROM ${i.identifier(o)} WHERE id > ${r} ORDER BY id ASC LIMIT ${i.raw(String(n))}`).toArray(),h=500,O=(e,o,r)=>{const n=I(o,r.name),t=E(r),a=w(T(e,n),t);if(a.finished)return{done:!0,rows:0};const{cursor:c}=a,s=H(e,o,c,h);let f=c;for(const g of s){const{id:u}=g;if(typeof u!="string")continue;f=u;const S=A(g);C(e,S?x(n,u,b(S,r)):k(n,u))}const d=s.length<h;return F(e,n,f,d,t),{done:d,rows:s.length}},l=(e,o)=>i`${i.identifier(e)}.${i.identifier(o)}`,R=500,$=(e,o,r)=>{const n=I(o,r.name),t=p(e,L(n,R)).toArray(),a=_(t);if(a.size===0)return!0;const c=new Map;for(const s of p(e,i`SELECT ${l(o,"id")}, ${l(o,"_creationTime")}, ${l(o,m)} FROM ${i.identifier(o)} WHERE ${U(l(o,"id"),[...a.keys()],!1)}`))c.set(String(s.id),s);for(const[s,f]of a){const d=c.get(s),g=d?A(d):void 0;C(e,g?x(n,s,b(g,r),{unmappedRowids:f}):k(n,s,{unmappedRowids:f}))}return t.length<R},W=(e,o,r,n)=>{let t=0;for(;t<n&&!$(e,o,r);)t+=1;return t},Z=(e,o,r)=>{const n=I(o,r.name),t=E(r);return w(T(e,n),t).finished?!0:D(e,n)},q=(e,o,r)=>{if(M(e))for(const n of r.searchIndexes??[])$(e,o,n),!(n.staged&&v(e,o))&&O(e,o,n)},j=(e,o,r,n)=>{let t=0;for(;;){if(t>=n)return{done:!1,pages:t};const a=O(e,o,r);if(a.rows>0&&(t+=1),a.done)return{done:!0,pages:t}}},ee=(e,o,r={})=>{if(!M(e))return{done:!0,pages:0};P(e);const n=r.maxPages??Number.POSITIVE_INFINITY;let t=0;for(const[a,c]of Object.entries(o.tables))if(!(c.shardMode?.kind==="global"||!c.searchIndexes))for(const s of c.searchIndexes){if(t+=W(e,a,s,n-t),t>=n)return{done:!1,pages:t};const f=j(e,a,s,n-t);if(t+=f.pages,!f.done)return{done:!1,pages:t}}return{done:!0,pages:t}};export{Q as backfillAggregateIndexes,X as backfillRankIndexes,ee as backfillSearchIndexes,q as backfillSearchIndexesForTable,H as readKeysetPage,Z as searchIndexCoversTable};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{N as lo,S as uo,d as $o,e as Eo,a as go}from"./fts-companion-CA8mLJWq.mjs";import{sql as o}from"drizzle-orm";import{r as Y}from"./json-field-path-DeJW4U9z.mjs";import{matchesStaticWhere as X,aggregateSqlFunction as po}from"./AGGREGATE_SQL_FUNCTION-C_ZipS9R.mjs";import{aggregateTableName as j,foldAggregateTally as J,encodeAggregateKey as k,coerceAggregateNumber as U}from"./aggregateTableName-B_CtIQCS.mjs";import{aggregateSignature as mo,readCompanionSignature as Z,rankSignature as ho,writeCompanionSignature as N}from"./CompanionMemo-BXU5vfak.mjs";import{runAll as So,runDrizzle as g}from"./runDrizzle-RC09zZrh.mjs";import{i as _o,g as yo,a as F,b as A,A as h,c as H,D as x,r as oo,e as V}from"./do-sql-BWrJQAOh.mjs";import{WORKERD_SQLITE_LIMITS as eo,param as G}from"./WORKERD_SQLITE_LIMITS-B_4w7tzY.mjs";import{encodeGeohash as Ro,GEO_DEFAULT_PRECISION as To}from"./GEO_DEFAULT_PRECISION-CqpQZ-J_.mjs";import{isLiveForCompanion as no}from"./CURSOR_PREFIX-6offuG6M.mjs";import{rankTableName as B,matchesRankStaticWhere as to,sortColumnName as Ao,encodePartitionKey as Co}from"./RANK_TIEBREAK-D3ye2GsL.mjs";import{mayHoldProjectedValue as wo}from"./BIGINT_KEY_DIGITS-DE6yshOt.mjs";import{serializeSqlValue as ro}from"./serializeSqlValue-DeoBMpZ2.mjs";const Io=(r,f,t)=>[...r.partitionBy??[],...r.sortBy.map(l=>l.field),...r.where?Object.keys(r.where):[]].every(l=>Y(f,l)===Y(t,l)),so=r=>o.join(["__id__","__partition__",...r.sortBy.map((f,t)=>Ao(t))].map(f=>o.identifier(f)),o`, `),io=(r,f,t)=>{const $=Co(r.partitionBy??[],t),l=r.sortBy.map(s=>ro(t[s.field]??null)),c=o.join([f,$,...l].map(s=>G(s)),o`, `);return o`(${c})`},Oo=(r,f,t,$,l,c)=>{g(r,o`INSERT INTO ${o.identifier(f)} (${$}) VALUES ${io(t,l,c)}`)},Q=1e3,co=function*(f,t,$,l){let c;for(;;){const s=c===void 0?o``:o` WHERE id > ${G(c)}`,y=[...g(f,o`SELECT id, _creationTime, ${o.identifier(x)} FROM ${o.identifier(t)}${s} ORDER BY id LIMIT ${G(Q)}`)];for(const S of y){const R=oo(S);R&&no(R,$)&&l(R)&&(yield R)}if(y.length<Q)return;c=String(y.at(-1)?.id)}},vo=(r,f,t,$,l)=>{const c=j(f,t.name),s=t.by??[],y=new Map;for(const C of co(r,f,$,I=>!t.where||X(I,t.where)))J(y,k(s,C),t,C);g(r,o`DELETE FROM ${o.identifier(c)}`);const S=Math.floor(eo.boundParams/3),R=[...y];for(let C=0;C<R.length;C+=S){const I=R.slice(C,C+S),P=o.join(I.map(([b,D])=>o`(${b}, ${D.value}, ${D.count})`),o`, `);g(r,o`INSERT INTO ${o.identifier(c)} (${F}, ${A}, ${h}) VALUES ${P}`)}N(r,c,l)},ko=(r,f,t,$)=>{const l=mo(t,$);Z(r,j(f,t.name))!==l&&vo(r,f,t,$,l)},Lo=(r,f,t,$,l)=>{const c=B(f,t.name),s=so(t);g(r,o`DELETE FROM ${o.identifier(c)}`);const y=Math.max(1,Math.floor(eo.boundParams/(2+t.sortBy.length)));let S=[];const R=()=>{S.length>0&&(g(r,o`INSERT INTO ${o.identifier(c)} (${s}) VALUES ${o.join(S,o`, `)}`),S=[])};for(const C of co(r,f,$,I=>!t.where||to(I,t.where)))S.push(io(t,C._id,C)),S.length>=y&&R();R(),N(r,c,l)},Fo=(r,f,t,$)=>{const l=ho(t,$);Z(r,B(f,t.name))!==l&&Lo(r,f,t,$,l)},Do=(r,f,t,$,l,c)=>{if(l&&c&&Io(t,l,c))return;const s=B(f,t.name);l&&g(r,o`DELETE FROM ${o.identifier(s)} WHERE ${o.identifier("__id__")} = ${$}`),!(!c||t.where&&!to(c,t.where))&&Oo(r,s,t,so(t),$,c)},Xo=r=>{const{broadcast:f,indexKeysFor:t,invalidateCache:$,recordCdc:l,schema:c,sql:s}=r,y=r.verified??new Set,S=e=>c.tables[e]?.softDeleteMode?.field,R=(e,n)=>{const a=j(e,n.name);y.has(a)||(ko(s,e,n,S(e)),y.add(a))},C=(e,n,a)=>{const p=n.by??[],d=n.field??"",E=[],_=(i,u)=>{const m=ro(u);m===null?E.push(o`${V(i)} IS NULL`):E.push(o`${V(i)} = ${m}`)};for(const i of p)_(i,a[i]??null);const w=S(e);w!==void 0&&_(w,null);for(const[i,u]of Object.entries(n.where??{}))_(i,u!==null&&typeof u=="object"&&!Array.isArray(u)?u.eq:u);const L=E.length>0?o` WHERE ${o.join(E,o` AND `)}`:o``,M=c.tables[e]?.shape[d];if(M&&wo(M)){const i=g(s,o`SELECT id, _creationTime, ${o.identifier(x)} FROM ${o.identifier(e)}${L}`).toArray(),u=new Map;for(const m of i){const v=oo(m);v&&J(u,"",n,v)}return{value:u.get("")?.value??null}}const W=po(n.op),T=V(d);return{value:g(s,o`SELECT ${o.raw(W)}(${T}) AS value FROM ${o.identifier(e)}${L}`).one().value??null}},I=(e,n,a,p)=>{const d=j(e,n.name),{op:E}=n,_=n.field??"",w=i=>{g(s,o`DELETE FROM ${o.identifier(d)} WHERE ${F} = ${i} AND ${h} <= 0`)},L=S(e),M=i=>!n.where||X(i,n.where),W=i=>no(i,L)&&M(i);p!==void 0&&E!=="count"&&M(p)&&U(p[_]);const T=a&&W(a)?a:void 0,O=p&&W(p)?p:void 0;if(!(!T&&!O)){if(E==="count"){for(const[i,u]of[[T,-1],[O,1]]){if(!i)continue;const m=k(n.by??[],i);g(s,H(d,m,u,u,o`${A} = ${A} + excluded.${A}, ${h} = ${h} + excluded.${h}`))}T&&w(k(n.by??[],T));return}if(E==="sum"||E==="avg"){for(const[i,u]of[[T,-1],[O,1]]){if(!i)continue;const m=U(i[_]);if(m===void 0)continue;const v=k(n.by??[],i);g(s,H(d,v,u*m,u,o`${A} = COALESCE(${A}, 0) + excluded.${A}, ${h} = ${h} + excluded.${h}`))}T&&w(k(n.by??[],T));return}if(T){const i=k(n.by??[],T),u=U(T[_]),m=g(s,o`SELECT ${A} AS value, ${h} AS count FROM ${o.identifier(d)} WHERE ${F} = ${i}`).toArray()[0],v=(m?.count??0)-1;if(v<=0)g(s,o`DELETE FROM ${o.identifier(d)} WHERE ${F} = ${i}`);else if(m&&u!==void 0&&m.value!==null&&u===m.value){const fo=C(e,n,T);g(s,o`UPDATE ${o.identifier(d)} SET ${A} = ${fo.value}, ${h} = ${v} WHERE ${F} = ${i}`)}else g(s,o`UPDATE ${o.identifier(d)} SET ${h} = ${h} - 1 WHERE ${F} = ${i}`)}if(O){const i=k(n.by??[],O),u=U(O[_]);if(u===void 0)g(s,H(d,i,null,1,o`${h} = ${h} + 1`));else{const m=E==="min"?"MIN":"MAX";g(s,H(d,i,u,1,o`${A} = ${o.raw(m)}(COALESCE(${A}, excluded.${A}), excluded.${A}), ${h} = ${h} + 1`))}}}},P=e=>{for(const n of c.tables[e]?.aggregateIndexes??[])R(e,n)},b=(e,n,a)=>{for(const p of c.tables[e]?.aggregateIndexes??[])I(e,p,n,a)},D=(e,n)=>{const a=B(e,n.name);y.has(a)||(Fo(s,e,n,S(e)),y.add(a))},ao=e=>{for(const n of c.tables[e]?.rankIndexes??[])D(e,n)},q=(e,n,a,p)=>{for(const d of c.tables[e]?.rankIndexes??[])Do(s,e,d,n,a,p)},K=(e,n,a,p)=>{const d=c.tables[e]?.searchIndexes??[];if(!(d.length===0||!_o(s)))for(const E of d){if(lo(p,a,E))continue;const _=uo(e,E.name);So(s,a?$o(_,n,Eo(a,E)):go(_,n))}},z=(e,n,a)=>{for(const p of c.tables[e]?.geoIndexes??[]){const d=yo(e,p.name);g(s,o`DELETE FROM ${o.identifier(d)} WHERE ${o.identifier("__id__")} = ${n}`);const E=a?.[p.field];if(E!==null&&typeof E=="object"&&typeof E.lat=="number"&&typeof E.lng=="number"){const{lat:_,lng:w}=E,L=Ro({lat:_,lng:w},p.precision??To);g(s,o`INSERT INTO ${o.identifier(d)} (${o.identifier("__id__")}, ${o.identifier("__geohash__")}, ${o.identifier("__lat__")}, ${o.identifier("__lng__")}) VALUES (${n}, ${L}, ${_}, ${w})`)}}};return{ensureBackfilledForTable:P,ensureBackfilledIndex:R,ensureRankBackfilled:D,ensureRankBackfilledForTable:ao,syncAggregates:b,syncCompanionsForInsert:(e,n,a)=>{K(e,n,a),z(e,n,a),b(e,void 0,a),q(e,n,void 0,a),$(e,n,a),l(e,n,"insert",a),f({indexKeys:t(e,a),key:n,op:"insert",row:a,table:e})},syncGeo:z,syncRanks:q,syncSearch:K}};export{Xo as createCompanionSync,ko as ensureAggregateCompanion,Fo as ensureRankCompanion};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{createShardCtxDb as _}from"./NotUniqueError-
|
|
1
|
+
import{createShardCtxDb as _}from"./NotUniqueError-C8ZpTDHV.mjs";import{createRelayLink as I}from"./DEFAULT_MAX_RELAYS-B6rnl_9a.mjs";import{ConflictError as q}from"./ConflictError-C8GtJmjS.mjs";import{runShardMigrations as E}from"./runShardMigrations-DsrVE2Kq.mjs";import{relayName as F}from"./DEFAULT_PROMOTION_THRESHOLDS-B3pRMuqb.mjs";const S=(O,m={})=>({_meta:{column:{notNull:!0,...m}},kind:O}),A=(O,m,x)=>{const{describe:v,expect:d,it:b}=x;v(`engine contract: ${O}`,()=>{v("optimistic concurrency",()=>{const w=u=>({tables:{items:{indexes:[],shape:{title:S("string"),version:S("number",{notNull:!1})},triggerMap:{clobber:{handler:()=>{u.exec(`UPDATE "items" SET "__doc__" = json_set("__doc__", '$.version', 99) WHERE "id" = 'i1'`)},op:"update",timing:"before"}}}}});b("raises a CONFLICT of kind `occ` when a write's snapshot is clobbered",async()=>{const{close:u,host:h}=m();try{const c=h.sql,p=w(c);E(c,p);const s=_({schema:p,sql:c});await s.insert("items",{_id:"i1",title:"first",version:1},{allowExplicitId:!0}),await d(s.patch("i1",{title:"second"})).rejects.toBeInstanceOf(q)}finally{u?.()}}),b("reports the conflict as CONFLICT/409 rather than retrying it away",async()=>{const{close:u,host:h}=m();try{const c=h.sql,p=w(c);E(c,p);const s=_({schema:p,sql:c});await s.insert("items",{_id:"i1",title:"first",version:1},{allowExplicitId:!0});let a;try{await s.patch("i1",{title:"second"})}catch(t){a=t}const e=a;d(e.code).toBe("CONFLICT"),d(e.kind).toBe("occ")}finally{u?.()}}),b("leaves the row readable and unchanged after a conflict",async()=>{const{close:u,host:h}=m();try{const c=h.sql,p=w(c);E(c,p);const s=_({schema:p,sql:c});await s.insert("items",{_id:"i1",title:"first",version:1},{allowExplicitId:!0});try{await s.patch("i1",{title:"second"})}catch{}const a=await s.get("i1");d(a?.title).toBe("first"),d(a?.version).toBe(99)}finally{u?.()}}),b("raises a CONFLICT of kind `trigger` when a trigger writes its own row through the db",async()=>{const{close:u,host:h}=m();try{const c=h.sql,p={tables:{items:{indexes:[],shape:{title:S("string"),version:S("number",{notNull:!1})},triggerMap:{recurse:{handler:async(t,o)=>{await t.db.patch(o.doc._id,{version:99})},op:"update",timing:"before"}}}}};E(c,p);const s=_({schema:p,sql:c});await s.insert("items",{_id:"i1",title:"first",version:1},{allowExplicitId:!0});let a;try{await s.patch("i1",{title:"second"})}catch(t){a=t}const e=a;d(e).toBeInstanceOf(q),d(e.code).toBe("CONFLICT"),d(e.kind).toBe("trigger")}finally{u?.()}})}),v("shape-poke ordering",()=>{const w="shard-a",u={args:{},name:"messages"},h=(e,t,o,n)=>e.accept(t?.()??{},{connectionId:o,shapes:{[n]:u}}),c=(e,t,o)=>{let n=0,l=0;const r=k=>()=>{throw new Error(`the relay poke path must not reach RelayHost.${k}`)},i={fetch:(k,C)=>{if(JSON.parse(C?.body??"{}").type!=="relay_shape_subscribe")return Promise.resolve(new Response(void 0,{status:204}));const N=o[l];if(l+=1,N===void 0)throw new Error("the relay asked for more seeds than this fixture supplies");return Promise.resolve(Response.json(N))}},f={get:()=>i,getByName:()=>i,idFromName:k=>k},g={buildShapeDiff:r("buildShapeDiff"),computeOpLogShapeSeed:r("computeOpLogShapeSeed"),currentCdcEpoch:r("currentCdcEpoch"),deliverWhisperLocal:r("deliverWhisperLocal"),doName:()=>F(w,0),env:()=>({SHARD:f}),getWebSockets:()=>e.getSockets(),maskMetadata:r("maskMetadata"),nextPokeId:()=>(n+=1,`poke-${String(n)}`),readAttachment:k=>k.deserializeAttachment?.(),recordShapePokeFanout:()=>{},resolveShape:r("resolveShape"),rlsMetadata:r("rlsMetadata"),shardBinding:()=>"SHARD",shardJurisdiction:()=>{},sql:()=>t},y=I(g);if(y===void 0)throw new Error("expected a relay link for a `…::relay::N` name");return y},p=e=>new Request("https://relay.internal/_lunora/relay",{body:JSON.stringify(e),headers:{"content-type":"application/json"},method:"POST"}),s=async(e,t,o)=>{const n=await e.seedRelayShape(t,o,u,{identity:void 0,userId:void 0});if(n!=="ok")throw new Error(`seed failed: ${JSON.stringify(n)}`)},a=(e={})=>p({...u,checkpoint:20,epoch:"e1",fromCursor:10,rowsPatch:[{id:"r1",op:"upsert",value:{title:"hello"}}],type:"relay_shape_poke",...e});b("frames a poke as pokeStart → pokePart per shape → pokeEnd, under one poke id",async()=>{const{close:e,createSocket:t,host:o,readFrames:n,sockets:l}=m();try{const r=c(l,o.sql,[{cursor:10,epoch:"e1",frames:[]}]),i=h(l,t,"c-alice","s1");await s(r,i,"s1"),await r.handleControl(a());const g=(await n(i)).map(y=>JSON.parse(y));d(g.map(y=>y.type)).toStrictEqual(["pokeStart","pokePart","pokeEnd"]),d(new Set(g.map(y=>y.pokeId)).size).toBe(1),d(g[1]?.shapeId).toBe("s1"),d(g[2]?.checkpoint).toBe(20)}finally{e?.()}}),b("delivers a poke only to sockets whose cursor matches, and advances them past it",async()=>{const{close:e,createSocket:t,host:o,readFrames:n,sockets:l}=m();try{const r=c(l,o.sql,[{cursor:10,epoch:"e1",frames:[]},{cursor:7,epoch:"e1",frames:[]}]),i=h(l,t,"c-alice","s1"),f=h(l,t,"c-bob","s2");await s(r,i,"s1"),await s(r,f,"s2"),await r.handleControl(a());const g=await n(i);d(g.length).toBe(3);const y=await n(f);d(y.length).toBe(0),await r.handleControl(a());const k=await n(i);d(k.length).toBe(3)}finally{e?.()}}),b("skips a socket whose cursor matches under a different CDC epoch",async()=>{const{close:e,createSocket:t,host:o,readFrames:n,sockets:l}=m();try{const r=c(l,o.sql,[{cursor:10,epoch:"e1",frames:[]}]),i=h(l,t,"c-alice","s1");await s(r,i,"s1"),await r.handleControl(a({epoch:"e2"}));const f=await n(i);d(f.length).toBe(0),await r.handleControl(a());const g=await n(i);d(g.length).toBe(3)}finally{e?.()}})}),v("orderBy null placement",()=>{const w=[["a",void 0],["b",3],["c",void 0],["d",1],["e",void 0],["f",3],["g",2],["h",void 0]],u=[{nulls:"first",sort:"asc"},{nulls:"last",sort:"asc"},{nulls:"first",sort:"desc"},{nulls:"last",sort:"desc"}],h=({nulls:p,sort:s})=>{const a=new Map(w.map(([t],o)=>[t,o])),e=s==="asc"?1:-1;return w.toSorted(([t,o],[n,l])=>o!==l?o===void 0?p==="first"?-1:1:l===void 0?p==="first"?1:-1:(o-l)*e:((a.get(t)??0)-(a.get(n)??0))*e).map(([t])=>t)},c=p=>p.map(s=>String(s.label));b("pages every placement in threes with no row skipped or repeated",async()=>{const{close:p,host:s}=m();try{const a=s.sql,e=u.map((r,i)=>`items_${String(i)}`),t={label:S("string"),score:S("number",{notNull:!1})},o={tables:Object.fromEntries(e.map(r=>[r,{indexes:[{fields:["score"],name:"by_score"}],shape:t}]))};E(a,o);let n=17e11;const l=_({clock:()=>(n+=1e3,n),schema:o,sql:a});for(const r of e)for(const[i,f]of w)await l.insert(r,f===void 0?{label:i}:{label:i,score:f});for(const[r,i]of u.entries()){const f=e[r]??"",g=await l.findMany(f,{orderBy:[{score:i}]});d(c(g.page)).toStrictEqual(h(i));const y=[];let k;for(let C=0;C<w.length+2;C+=1){const B=await l.findMany(f,{cursor:k,limit:3,orderBy:[{score:i}]});if(y.push(...c(B.page)),B.isDone)break;k=B.continueCursor}d(y).toStrictEqual(h(i))}}finally{p?.()}})}),v("RLS identity under live subscription",()=>{const w="shard-a",u={args:{},name:"lobby-messages"},h={args:{},name:"my-orders"},c=s=>{const a=[],e=[],t={fetch:(l,r)=>(a.push(JSON.parse(r?.body??"{}")),Promise.resolve(new Response(void 0,{status:204})))},n=I({buildShapeDiff:()=>[{id:"r1",op:"upsert",value:{}}],computeOpLogShapeSeed:()=>({baseCheckpoint:void 0,cursor:10,epoch:"e1",reset:!0,rowsPatch:[]}),currentCdcEpoch:()=>"e1",deliverWhisperLocal:()=>0,doName:()=>w,env:()=>({SHARD:{get:()=>t,getByName:()=>t,idFromName:l=>l}}),getWebSockets:()=>[],maskMetadata:()=>({columns:[]}),nextPokeId:()=>"poke-1",readAttachment:()=>({}),recordShapePokeFanout:()=>{},resolveShape:(l,r,i)=>(e.push(i),l===h.name?{columns:["id"],effectiveWhere:{org:i?.identity?.org??"anonymous"},global:!1,table:"orders"}:{columns:["id"],effectiveWhere:{room:"lobby"},global:!1,table:"messages"}),rlsMetadata:()=>({policies:[]}),shardBinding:()=>"SHARD",shardJurisdiction:()=>{},sql:()=>s});if(n===void 0)throw new Error("expected an owner link for an un-suffixed DO name");return{owner:n,posts:a,resolvedUnder:e}},p=async(s,a)=>{await s.handleControl(new Request("https://owner.internal/_lunora/relay",{body:JSON.stringify({...a,connectionId:"c-alice",identity:{org:"acme"},relayIndex:0,subId:"s1",type:"relay_shape_subscribe",userId:"u1"}),headers:{"content-type":"application/json"},method:"POST"}))};b("seeds a subscriber under its own forwarded identity, never the anonymous one",async()=>{const{close:s,host:a}=m();try{const{owner:e,resolvedUnder:t}=c(a.sql);await p(e,h),d(t.some(o=>o?.userId==="u1"&&o.identity?.org==="acme")).toBe(!0)}finally{s?.()}}),b("routes an identity-scoped shape to a per-socket poke, not the cohort multicast",async()=>{const{close:s,host:a}=m();try{const{owner:e,posts:t}=c(a.sql);await p(e,h),t.length=0,await e.onFlush(new Set(["orders"]),20);const o=t.filter(n=>n.type==="relay_shape_poke");d(o.length).toBe(1),d(o[0]?.targetConnectionId).toBe("c-alice")}finally{s?.()}}),b("still multicasts an identity-blind shape to the whole cohort",async()=>{const{close:s,host:a}=m();try{const{owner:e,posts:t}=c(a.sql);await p(e,u),t.length=0,await e.onFlush(new Set(["messages"]),20);const o=t.filter(n=>n.type==="relay_shape_poke");d(o.length).toBe(1),d(o[0]?.targetConnectionId).toBeUndefined()}finally{s?.()}})})})};export{A as defineEngineContractSuite};
|
|
@@ -0,0 +1,5 @@
|
|
|
1
|
+
import{LunoraError as U}from"@lunora/errors";import{f as M,S as X}from"./fts-companion-CA8mLJWq.mjs";import{sql as t}from"drizzle-orm";import{aggregateTableName as h}from"./aggregateTableName-B_CtIQCS.mjs";import{backfillSearchIndexesForTable as y}from"./backfillAggregateIndexes-BN0NwXQk.mjs";import{migrateCdcLog as b,migrateCdcMeta as k}from"./CDC_LOG_TABLE-Dgwxv7yf.mjs";import{migrateClientWatermark as w}from"./CLIENT_WATERMARK_TABLE-De7z_OHV.mjs";import{migrateCommitSeq as B}from"./COMMIT_SEQ_FIELD-Da1DjGqo.mjs";import{migrateCompanionState as G}from"./CompanionMemo-BXU5vfak.mjs";import{migrateGlobalShapeSnapshot as P}from"./GLOBAL_SHAPE_SNAPSHOT_TABLE-Bb6-aZuH.mjs";import{migrateIdempotency as Y}from"./IDEMPOTENCY_TABLE-COrgeP3O.mjs";import{m as v}from"./ctx-db-relay-shapes-DV0VO4HG.mjs";import{migrateScheduleOutbox as j}from"./SCHEDULE_OUTBOX_TABLE-DcZI7Yhl.mjs";import{m as W}from"./ctx-db-search-state-FjgzTFok.mjs";import{migrateShapePokeCursor as H}from"./SHAPE_POKE_CURSOR_TABLE-BGvY3sFI.mjs";import{runDrizzle as d,runAll as K}from"./runDrizzle-RC09zZrh.mjs";import{D as V,d as I,e as g,t as z,i as Z,g as J,a as Q,b as q,A as p}from"./do-sql-BWrJQAOh.mjs";import{renderSql as R}from"./WORKERD_SQLITE_LIMITS-B_4w7tzY.mjs";import{migrateDurableStreams as ee}from"./appendStreamChunk-BZYgGE9Y.mjs";import{rankTableName as N,sortColumnName as te}from"./RANK_TIEBREAK-D3ye2GsL.mjs";import{migrateReactorState as re}from"./REACTOR_STATE_TABLE-D2Mn204f.mjs";import{recordSchemaVersion as ne}from"./SCHEMA_HISTORY_MAX_VERSIONS-CEwFjj-O.mjs";import{ttlIndexColumns as oe}from"./nextTtlExpiry-DhKO_OpO.mjs";const u=t`_creationTime, id`,x="__by_creation",ie="__ttl",ae=`, ${R("sqlite",u).sql})`,l="__lunora_framework_indexes",T=e=>e.replaceAll(/[A-Z]/gu,r=>r.toLowerCase());class D extends U{}const $=(e,r,n,a,i,o)=>{const s=t.join(i.map(m=>t`${m} IS NOT NULL`),t` AND `);if(d(e,t`SELECT 1 FROM ${t.identifier(n)} WHERE ${s} GROUP BY ${a} HAVING COUNT(*) > 1 LIMIT 1`).toArray().length>0)throw new D("INTERNAL",`unique index "${r}" on "${n}" ${o}: existing rows are duplicates under it. De-duplicate the table with a data migration first; the previous index is left in place.`)},L=(e,r,n,a,i,o)=>{const c=d(e,t`SELECT sql FROM sqlite_master WHERE type = 'index' AND name = ${r} COLLATE NOCASE AND tbl_name = ${n} COLLATE NOCASE`).toArray()[0]?.sql;if(c==null)return;const m=f=>{const A=f.indexOf("(");return A===-1?void 0:f.slice(A,f.lastIndexOf(")")+1)},E=m(R("sqlite",I(r,n,a,i)).sql),_=m(c);E===void 0||_===void 0||E===_||(i&&$(e,r,n,a,o,"cannot be re-created with its new column list"),d(e,t`DROP INDEX IF EXISTS ${t.identifier(r)}`))},se=(e,r,n)=>d(e,t`SELECT 1 FROM sqlite_master WHERE type = 'index' AND name = ${r} COLLATE NOCASE AND tbl_name = ${n} COLLATE NOCASE LIMIT 1`).toArray().length>0,O=(e,r,n,a,i,o)=>{i&&!se(e,r,n)&&$(e,r,n,a,o,"cannot be created"),d(e,I(r,n,a,i))},C=(e,r)=>{try{r()}catch(n){if(e===void 0||!(n instanceof D))throw n;e.push(n.message)}},de=(e,r,n)=>T(r).startsWith(`${T(e)}_`)&&T(r)!==T(`${e}${x}`)&&n!==null&&(n.includes("json_extract(")||n.trimEnd().endsWith(ae)),S=(e,r,n)=>{d(e,t`INSERT OR IGNORE INTO ${t.identifier(l)} (name, table_name) VALUES (${r}, ${n})`)},ce=(e,r)=>{const n=d(e,t`SELECT 1 FROM sqlite_master WHERE type = 'table' AND name = ${l} COLLATE NOCASE`).toArray().length>0;if(d(e,t`CREATE TABLE IF NOT EXISTS ${t.identifier(l)} (name TEXT PRIMARY KEY COLLATE NOCASE, table_name TEXT NOT NULL)`),!n)for(const a of r){const i=d(e,t`SELECT name, sql FROM sqlite_master WHERE type = 'index' AND tbl_name = ${a} COLLATE NOCASE AND sql IS NOT NULL`).toArray();for(const{name:o,sql:s}of i)de(a,o,s)&&S(e,o,a)}},me=(e,r,n)=>{const a=new Set([...n].map(o=>T(o))),i=d(e,t`SELECT "l"."name" FROM ${t.identifier(l)} AS "l" WHERE "l"."table_name" = ${r} COLLATE NOCASE`).toArray();for(const{name:o}of i)a.has(T(o))||(d(e,t`DROP INDEX IF EXISTS ${t.identifier(o)}`),d(e,t`DELETE FROM ${t.identifier(l)} WHERE ${t.identifier(l)}."name" = ${o}`))},fe=(e,r,n,a)=>{const i=`${r}${ie}`,o=new Set([...a].map(c=>T(c)));if(n.ttlPolicy===void 0||o.has(T(i)))return;const s=oe(n.ttlPolicy.field,n.softDeleteMode?.field);a.add(i);try{L(e,i,r,s,!1,[]),d(e,I(i,r,s,!1)),S(e,i,r)}catch{}},Ee=(e,r,n,a)=>{const i=new Set;for(const o of n.indexes){const s=`${r}_${o.name}`,c=o.unique??!1,m=o.fields.map(f=>g(f)),E=t.join(m,t`, `),_=c?E:t`${E}, ${u}`;i.add(s),C(a,()=>{L(e,s,r,_,c,m),O(e,s,r,_,c,m),S(e,s,r)})}for(const[o,s]of z(n)){if(!s.unique)continue;const c=g(o),m=`${r}_unique_${o}`;i.add(m),C(a,()=>{L(e,m,r,c,!0,[c]),O(e,m,r,c,!0,[c]),S(e,m,r)})}fe(e,r,n,i),me(e,r,i)},_e=(e,r,n)=>{if(!(!n.searchIndexes||n.searchIndexes.length===0||!Z(e))){for(const a of n.searchIndexes)K(e,M(X(r,a.name)));y(e,r,n)}},Te=(e,r,n)=>{if(n.geoIndexes)for(const a of n.geoIndexes){const i=J(r,a.name);d(e,t`CREATE TABLE IF NOT EXISTS ${t.identifier(i)} (${t.identifier("__id__")} TEXT PRIMARY KEY, ${t.identifier("__geohash__")} TEXT NOT NULL, ${t.identifier("__lat__")} REAL NOT NULL, ${t.identifier("__lng__")} REAL NOT NULL)`);const o=`${r}__geo_${a.name}__btree`;d(e,I(o,i,t`${t.identifier("__geohash__")} ASC, ${t.identifier("__id__")} ASC`,!1))}},Ae=(e,r,n)=>{if(n.aggregateIndexes)for(const a of n.aggregateIndexes){const i=h(r,a.name);d(e,t`CREATE TABLE IF NOT EXISTS ${t.identifier(i)} (${Q} TEXT PRIMARY KEY, ${q} REAL, ${p} INTEGER NOT NULL DEFAULT 0)`),d(e,t`PRAGMA table_info(${t.identifier(i)})`).toArray().some(s=>s.name==="__count__")||d(e,t`ALTER TABLE ${t.identifier(i)} ADD COLUMN ${p} INTEGER NOT NULL DEFAULT 0`)}},le=(e,r,n)=>{const a=d(e,t`PRAGMA table_info(${t.identifier(r)})`).toArray().map(i=>i.name).filter(i=>i.startsWith("__sort_k"));a.length>0&&(a.length!==n.length||a.some((i,o)=>i!==n[o]))&&d(e,t`DROP TABLE ${t.identifier(r)}`)},Ie=(e,r,n)=>{if(n.rankIndexes)for(const a of n.rankIndexes){const i=N(r,a.name),o=a.sortBy.map((f,A)=>te(A)),s=o.map(f=>t`${t.identifier(f)} BLOB`),c=s.length>0?t`, ${t.join(s,t`, `)}`:t``;le(e,i,o),d(e,t`CREATE TABLE IF NOT EXISTS ${t.identifier(i)} (${t.identifier("__id__")} TEXT PRIMARY KEY, ${t.identifier("__partition__")} TEXT NOT NULL${c})`);const m=[t`${t.identifier("__partition__")} ASC`];for(const[f,A]of o.entries()){const F=a.sortBy[f]?.direction;m.push(t`${t.identifier(A)} ${t.raw(F==="desc"?"DESC":"ASC")}`)}m.push(t`${t.identifier("__id__")} ASC`);const E=`${r}__rank_${a.name}__btree`,_=t.join(m,t`, `);L(e,E,i,_,!1,[]),d(e,I(E,i,_,!1))}},Pe=(e,r,n={})=>{const a=n.deferBlockedUniqueIndexes?[]:void 0;n.schemaSnapshot!==void 0&&ne(e,n.schemaSnapshot.hash,n.schemaSnapshot.json),W(e),ce(e,Object.entries(r.tables).filter(([,o])=>o.shardMode?.kind!=="global").map(([o])=>o));const i=[];for(const[o,s]of Object.entries(r.tables))s.shardMode?.kind!=="global"&&(d(e,t`CREATE TABLE IF NOT EXISTS ${t.identifier(o)} (
|
|
2
|
+
id TEXT PRIMARY KEY,
|
|
3
|
+
_creationTime REAL NOT NULL,
|
|
4
|
+
${t.identifier(V)} TEXT NOT NULL
|
|
5
|
+
)`),d(e,I(`${o}${x}`,o,u,!1)),Ee(e,o,s,a),_e(e,o,s),Te(e,o,s),Ae(e,o,s),Ie(e,o,s),i.push(...(s.aggregateIndexes??[]).map(c=>h(o,c.name)),...(s.rankIndexes??[]).map(c=>N(o,c.name))));return G(e,i),n.cdc&&(b(e,{rowHistoryIndex:Object.values(r.tables).some(o=>o.dropStalePatchesMode===!0)}),k(e),w(e),H(e),v(e)),Object.values(r.tables).some(o=>o.commitOrderedMode===!0)&&B(e),re(e),Y(e),j(e),P(e),ee(e),a??[]};export{Pe as runShardMigrations};
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@lunora/shard-engine",
|
|
3
|
-
"version": "1.0.0-alpha.
|
|
3
|
+
"version": "1.0.0-alpha.158",
|
|
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.51 <2.0.0-0",
|
|
52
|
-
"@lunora/platform": "1.0.0-alpha.
|
|
52
|
+
"@lunora/platform": "1.0.0-alpha.75",
|
|
53
53
|
"@lunora/wire": "1.0.0-alpha.2",
|
|
54
54
|
"drizzle-orm": "1.0.0-rc.5"
|
|
55
55
|
},
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{LunoraError as y}from"@lunora/errors";import{D as wt}from"./MAX_TOKEN_LENGTH-BakL9FUy-B3VwYY8C.mjs";import{S as An,l as We,h as Cn}from"./fts-companion-CA8mLJWq.mjs";import{decodeWire as xn,stableWireKey as Ft}from"@lunora/wire";import{sql as a}from"drizzle-orm";import{throwingScheduler as bn,aggregateSqlFunction as Be,normalizeCountArgument as Mn}from"./AGGREGATE_SQL_FUNCTION-C_ZipS9R.mjs";import{aggregateTableName as tt,encodeAggregateKey as nt,readAggregateValue as ot}from"./aggregateTableName-B_CtIQCS.mjs";import{mergeWhere as K,CountRlsUnsupportedError as rt,selectIndexForGroupBy as Dn,selectIndexForCount as kn,selectIndexForAggregate as Ln}from"./CountRlsUnsupportedError-BvsDqfO2.mjs";import{backfillSearchIndexesForTable as Fn,searchIndexCoversTable as qn}from"./backfillAggregateIndexes-DSplGrR_.mjs";import{backfillAggregateIndexes as fi,backfillRankIndexes as hi,backfillSearchIndexes as wi}from"./backfillAggregateIndexes-DSplGrR_.mjs";import{appendCdcChange as Wn,readCdcDocAtOrBefore as Bn}from"./CDC_LOG_TABLE-Dgwxv7yf.mjs";import{CDC_LOG_TABLE as gi,applyCdcChanges as yi,bumpCdcEpoch as $i,cdcCanVouchFor as Ei,cdcForkedError as mi,cdcSeqLeavingRows as Si,cdcTouchesTables as _i,cdcTrimmedError as Ri,compactCdcDocs as Ti,cursorBelowRetainedFloor as vi,minCdcReplayableSeq as Ii,minCdcSeq as Ai,readCdcChangeKeys as Ci,readCdcChanges as xi,readCdcCursor as bi,readCdcEpoch as Mi,trimCdcChanges as Di}from"./CDC_LOG_TABLE-Dgwxv7yf.mjs";import{allocateCommitSeq as Pn,COMMIT_SEQ_FIELD as Un}from"./COMMIT_SEQ_FIELD-Da1DjGqo.mjs";import{createCompanionSync as On}from"./createCompanionSync-BMS8yYTx.mjs";import{isMemoryTable as qt}from"./clearMemoryTables-aMRERF0w.mjs";import{computeRankPage as Wt}from"./computeRankPage-BZIpATcs.mjs";import{SCAN_DEP as O}from"./SCAN_DEP-D7qE3iUe.mjs";import{runSql as pe,runDrizzle as H}from"./runDrizzle-RC09zZrh.mjs";import{p as Hn,j as dt,D as ie,r as Ie,k as fe,b as Pe,A as it,a as Ue,m as he,e as we,s as Gn,t as jn,i as Kn,q as Bt,h as ln,g as Nn}from"./do-sql-BWrJQAOh.mjs";import{renderSql as un,unionAll as pt,WORKERD_SQLITE_LIMITS as fn,sqliteInList as Qn}from"./WORKERD_SQLITE_LIMITS-B_4w7tzY.mjs";import{coveringGeohashes as Vn,boundingBoxGeohashes as Jn,haversineMeters as zn,pointInBoundingBox as Yn}from"./GEO_DEFAULT_PRECISION-CqpQZ-J_.mjs";import{NotFoundError as Xn}from"./NotFoundError-BhF7FeFr.mjs";import{resolvePatch as Zn,assertPatchAllowed as eo,operatorFields as to,readPatchField as Pt}from"./assertPatchAllowed-CA_H466g.mjs";import{tiebreakDirectionFor as no,encodeCursor as Ke,nullsOrderSuffix as oo,normalizeOrderKeys as Ut,uniqueIndexFields as ro,buildSeekWhere as io,decodeCursor as Ot,buildSeekBeforeWhere as so,softDeleteScope as Te,applySelect as Ht}from"./CURSOR_PREFIX-6offuG6M.mjs";import{rankTableName as Gt,sortColumnName as jt,resolveRankPartition as co,encodePartitionKey as ao,RANK_TIEBREAK as lo,rankPivotConditionSql as uo}from"./RANK_TIEBREAK-D3ye2GsL.mjs";import{UNVOUCHABLE_DEP as Kt}from"./UNVOUCHABLE_DEP-C68htACn.mjs";import{indexKeysForRow as fo,buildIndexRange as ho}from"./buildIndexRange-DQ3eWAGd.mjs";import{r as Ne,j as Ae,c as Y,t as Qe,i as Nt}from"./where-sql-BjY4rnqb.mjs";import{serializeSqlValue as Ce}from"./serializeSqlValue-DeoBMpZ2.mjs";import{quoteIdentifier as xe}from"./quoteIdentifier-CObIFRhb.mjs";import{whereOfFilter as wo,isPushableWhere as po}from"./isPushableWhere-BeYAOjUb.mjs";import{deriveRelationEdges as go,findRelated as yo}from"./RELATED_DEFAULT_LIMIT-CVqN4JEu.mjs";import{assertFlatPredicate as st,resolveRelationPredicates as $o,composeReadPredicate as Eo}from"./DEFAULT_MAX_RELATION_KEYS-BeTWZQ4X.mjs";import{describeRelationWrites as mo}from"./describeRelationWrites-omar6-u9.mjs";import{runRowValidators as Oe,transformOnlyDefinition as So,applyInsertDefaults as lt,resolveWith as Qt,relationHooks as Vt,applyOnDelete as _o,fanOutScalarCounts as Ro}from"./applyInsertDefaults-vVfUyiJ2.mjs";import{guardWriter as To}from"./RLS_UNWRAP_SYMBOL-J1tiBtRj.mjs";import{mayHoldProjectedValue as vo}from"./BIGINT_KEY_DIGITS-DE6yshOt.mjs";import{createSystemReader as Io}from"./createSystemReader-DcDLFfC-.mjs";import{ConflictError as de}from"./ConflictError-C8GtJmjS.mjs";import{hasTrigger as Jt,runTriggers as Ao}from"./hasTrigger-CjlwI4le.mjs";import{advanceClientWatermark as Li,migrateClientWatermark as Fi,readClientWatermark as qi}from"./CLIENT_WATERMARK_TABLE-De7z_OHV.mjs";import{IDEMPOTENCY_TABLE as Bi,readIdempotent as Pi,trimIdempotent as Ui,writeIdempotent as Oi}from"./IDEMPOTENCY_TABLE-COrgeP3O.mjs";import{runShardMigrations as Gi}from"./runShardMigrations-vtuywDTg.mjs";import{selectShapeMembers as Ki,selectShapeRows as Ni}from"./selectShapeMembers-BCfKypfN.mjs";const Co=n=>{const i=atob(n),o=Uint8Array.from(i,c=>c.codePointAt(0)??0);return new TextDecoder().decode(o)},xo=()=>new y("BAD_REQUEST","invalid cursor"),zt=16,Yt=8,V=1024,gt=(n,i)=>i.query(n),bo=(n,i)=>{if(n.length===0)return 0;let o=0;for(const[c,s]of i.entries()){const w=c===i.length-1;let _=0;for(const m of n)(w?m.startsWith(s):m===s)&&(_+=1);if(_===0)return 0;o+=_}return o},Mo=(n,i)=>{if(!i)return{exact:!0,lower:n,upper:n};const o=[...n].at(-1)??"",c=(o.codePointAt(0)??0)+1;if(c>=55296&&c<=57343||c>1114111)return{exact:!0,lower:n,upper:n};const s=n.slice(0,n.length-o.length);return{exact:!1,lower:n,upper:s+String.fromCodePoint(c)}},Do=(n,i,o)=>{const c={eq:(s,w)=>{if(!n.definition.filterFields?.includes(s))throw new y("INTERNAL",`field "${s}" is not a filter field of search index "${n.indexName}" on table "${i}"`);if(n.filters.length>=Yt)throw new y("BAD_REQUEST",`search index "${n.indexName}" on table "${i}": at most ${String(Yt)} .eq() filters are supported per search query`);return n.filters.push({field:s,value:w}),c},search:(s,w)=>{const _=n;if(s!==_.definition.field)throw new y("INTERNAL",`search index "${_.indexName}" on table "${i}" indexes "${_.definition.field}", not "${s}"`);const m=gt(w,o).length;if(m>zt)throw new y("BAD_REQUEST",`search index "${_.indexName}" on table "${i}": at most ${String(zt)} search terms are supported (got ${String(m)})`);return _.field=s,_.query=w,_.hasQuery=!0,c}};return c},ko=n=>{if(n.length>V)throw new y("BAD_REQUEST",`more than ${String(V)} documents match this search — narrow it with filters or read it a page at a time with .paginate()`)},Lo=n=>Math.min(n.offset+n.numItems+1,V),Fo=n=>btoa(`search:${String(n)}`),qo=n=>{let i;try{i=Co(n)}catch{return}if(!i.startsWith("search:"))return;const o=Number(i.slice(7));return Number.isInteger(o)&&o>=0?o:void 0},Wo=n=>{if(typeof n.endCursor=="string")throw new y("BAD_REQUEST","bounded (endCursor) pagination is not supported on search queries — relevance order has no stable range boundary");if(!Number.isFinite(n.numItems))throw new y("BAD_REQUEST",`search pagination needs a finite numItems, got ${String(n.numItems)}`);const i=Math.max(0,Math.floor(n.numItems)),o=n.cursor?qo(n.cursor):0;if(o===void 0)throw xo();if(o+i>=V)throw new y("BAD_REQUEST",`search pagination reaches the ${String(V)}-document limit (offset ${String(o)} + ${String(i)} requested) — a page must end below the cap so the probe row that answers \`hasMore\` still fits: retry with numItems ${String(Math.max(1,V-o-1))} or fewer, or narrow the query or the filters instead`);return{numItems:i,offset:o}},Bo=(n,i)=>{const o=i.offset+i.numItems,c=i.numItems>0&&n.length>o;return{continueCursor:c?Fo(o):null,isDone:!c,page:n.slice(i.offset,o)}},Po=n=>{if(n===void 0)return V+1;if(!Number.isFinite(n))return V;const i=Math.max(0,Math.floor(n));if(i>V)throw new y("BAD_REQUEST",`search returns at most ${String(V)} documents (asked for ${String(i)}) — narrow the query or paginate instead`);return i},Uo=32,Oo=1024,hn=(n,i,o,c)=>{const s=`SELECT id, _creationTime, ${xe(ie)} FROM ${xe(n)}`,w=`ORDER BY ${o}${c===void 0?"":` LIMIT ${String(c)}`}`;return i===void 0?Ne(`${s} ${w}`):Ae(`${s} WHERE `,i,` ${w}`)},Ve={fieldRef:n=>Ne(dt(n)),rangeTypeGuard:(n,i)=>Ne(Hn(n,i)),serialize:Ce},Ho=n=>n===void 0?"":oo(n==="first"),wn=n=>{const i=n.map(o=>`${dt(o.field)} ${o.direction==="desc"?"DESC":"ASC"}${Ho(o.nulls)}`);return n.some(o=>o.field==="_id"||o.field==="id")||i.push(`${dt("id")} ${no(n)==="desc"?"DESC":"ASC"}`),i.join(", ")},Go={"<":"lt","<=":"lte","=":"eq",">":"gt",">=":"gte"},pn=n=>new Set(n.sqlConditions.filter(i=>i.comparator==="=").map(i=>i.field)),jo=n=>{const i=pn(n);let o=0;for(;o<n.indexFields.length&&i.has(n.indexFields[o]??"");)o+=1;return n.indexFields.slice(o)},Ko=(n,i)=>{const o=n.order,c=jo(n),{shape:s}=i;return c.length>0?Ut(c.map(w=>({[w]:o})),s,{pinned:pn(n),uniqueBy:ro(i.indexes,s)}):Ut([{_creationTime:o}],s)},No=(n,i,o,c)=>{const s=n.sqlConditions.map(w=>({[w.field]:{[Go[w.comparator]??"eq"]:w.value}}));if(o&&s.push(io(i,Ot(o))),c&&s.push(so(i,Ot(c))),s.length!==0)return s.length===1?s[0]:{AND:s}},Qo=n=>{if(n.want!==void 0)return n.selective?Math.max(n.want,Uo):n.want},ut=(n,i,o,c,s,w,_)=>{const m=Ko(c,o),C=wn(m),$=[],{filters:q,want:x}=w;let A=w.cursor??void 0,M=Qo(w);if(x===0)return{documents:$,orderKeys:m};for(;;){const W=Y(No(c,m,A,w.endCursor),Ve,Qe),D=hn(i,s&&W?Ae(W," AND ",s):s??W,C,M),L=pe(n,D.text,...D.params).toArray();let F={};_(L.length);for(const G of L)if(F=Ie(G),q.every(se=>se(F))&&$.push(F)===x)return{documents:$,orderKeys:m};if(M===void 0||L.length<M)return{documents:$,orderKeys:m};A=Ke(F,m),M=Math.max(M,Math.min(M*2,Oo))}},Vo=(n,i,o,c,s,w,_,m)=>{const C=Math.max(0,Math.floor(s.numItems));if(typeof s.endCursor=="string"){const{documents:W,orderKeys:D}=ut(n,i,o,c,w,{cursor:s.cursor,endCursor:s.endCursor,filters:_.all,selective:_.selective,want:void 0},m),L=W.length>=2?W[Math.floor(W.length/2)-1]:void 0;return{continueCursor:s.endCursor,isDone:!0,page:W,splitCursor:L?Ke(L,D):null}}const{documents:$,orderKeys:q}=ut(n,i,o,c,w,{cursor:s.cursor,filters:_.all,selective:_.selective,want:C+1},m),x=$.length>C,A=x?$.slice(0,C):$,M=A.at(-1);return{continueCursor:x&&M?Ke(M,q):null,isDone:!x,page:A}},Je=n=>{const i=new Map;return o=>{const c=i.get(o);if(c!==void 0)return c;const s=n(xe(o));return i.set(o,s),s}},ge=xe(ie),Jo=Je(n=>`INSERT INTO ${n} (id, _creationTime, ${ge}) VALUES (?, ?, ?)`),Xt=Je(n=>`UPDATE ${n} SET ${ge} = ? WHERE id = ? AND ${ge} = ?`),zo=Je(n=>`UPDATE ${n} SET _creationTime = ?, ${ge} = ? WHERE id = ? AND ${ge} = ?`),Yo=Je(n=>`DELETE FROM ${n} WHERE id = ? AND ${ge} = ?`),Xo="SELECT changes() AS changed",Zt=new Map,Zo="",er=n=>{const i=JSON.stringify(n),o=Zt.get(i);if(o!==void 0)return o;const c=n.map(w=>a`SELECT ${a.raw(`'${w.replaceAll("'","''")}'`)} AS __t__, id, _creationTime, ${a.identifier(ie)} FROM ${a.identifier(w)} WHERE id = ${Zo}`),{sql:s}=un("sqlite",a`${pt(c)} LIMIT 1`);return Zt.set(i,s),s},tr=(n,i)=>i.map(()=>n),nr=/^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/iu,or=n=>{if(!nr.test(n))throw new y("INTERNAL",`invalid clientId ${JSON.stringify(n)}: a client-supplied row id must be a UUID`)},ft=n=>{if(n.includes("\0"))throw new y("BAD_REQUEST",`invalid row id ${JSON.stringify(n)}: a row id cannot hold a NUL character (U+0000)`)},rr=(n,i,o,c)=>{if(o!==!0)return;const s=n!==void 0&&"serverDefault"in(n.shape._id?._meta?.column??{});for(const w of i){const _=s?lt(n,w,c)._id:w._id;typeof _=="string"&&ft(_)}},en=50,yt=500,He=Math.floor(fn.boundParams/3),Re=fn.boundParams,ir=128,ve=(n,i,o)=>{const c=i??yt;if(n>c)throw new y("BATCH_LIMIT_EXCEEDED",`${o}: batch of ${String(n)} exceeds the limit of ${String(c)} (raise options.limit or chunk the call)`,{status:400})},tn=async(n,i,o,c,s)=>{const w=c??yt,_=Number.isFinite(w),{page:m}=await n.findMany(i,_?{limit:w+1,omitContinueCursor:!0,where:o}:{where:o});return _&&m.length>w&&ve(Math.max(await n.count(i,{where:o}),m.length),c,s),m},sr=n=>{const i={eq:(o,c)=>(n.sqlConditions.push({comparator:"=",field:o,value:c}),i),gt:(o,c)=>(n.sqlConditions.push({comparator:">",field:o,value:c}),i),gte:(o,c)=>(n.sqlConditions.push({comparator:">=",field:o,value:c}),i),lt:(o,c)=>(n.sqlConditions.push({comparator:"<",field:o,value:c}),i),lte:(o,c)=>(n.sqlConditions.push({comparator:"<=",field:o,value:c}),i)};return i},cr=n=>Math.max(n,V),gn=(n,i)=>{const o=n.filters.map(c=>a`${we(c.field)} = ${Ce(c.value)}`);return i&&o.push(i),o},ar=(n,i,o,c,s)=>{const w=gt(o.query,wt(o.definition.language));if(w.length===0)return[];const _=An(i,o.indexName),m=`${_}__vocab`,C=w.length-1,$=w.map((D,L)=>{const F=Mo(D,L===C),G=F.exact?a`${a.identifier("term")} = ${F.lower}`:a`${a.identifier("term")} >= ${F.lower} AND ${a.identifier("term")} < ${F.upper}`;return a`SELECT ${a.identifier("doc")}, ${a.raw(String(L))} AS ${a.identifier("__term__")}, COUNT(*) AS ${a.identifier("__n__")} FROM ${a.identifier(m)} WHERE ${G} GROUP BY ${a.identifier("doc")}`}),q=w.map((D,L)=>a`SUM(CASE WHEN u.${a.identifier("__term__")} = ${a.raw(String(L))} THEN u.${a.identifier("__n__")} ELSE 0 END)`),x=a`SELECT f.${a.identifier(We)} AS ${a.identifier(We)}, ${a.join(q,a` + `)} AS ${a.identifier("__score__")} FROM (${pt($)}) u JOIN ${a.identifier(_)} f ON f.rowid = u.${a.identifier("doc")} GROUP BY f.${a.identifier(We)} HAVING ${a.join(q.map(D=>a`${D} > 0`),a` AND `)}`,A=gn(o,s);let M=a`SELECT m.id, m._creationTime, m.${a.identifier(ie)}, s.${a.identifier("__score__")} AS ${a.identifier("__score__")} FROM (${x}) s JOIN ${a.identifier(i)} m ON m.id = s.${a.identifier(We)}`;A.length>0&&(M=a`${M} WHERE ${a.join(A,a` AND `)}`),M=a`${M} ORDER BY s.${a.identifier("__score__")} DESC, m._creationTime DESC, m.id ASC LIMIT ${a.raw(String(c))}`;const W=[];for(const D of H(n,M)){const L=ln(D);if(L){const F=D.__score__;W.push({document:L,score:typeof F=="number"?F:Number(F??0)})}}return W},dr=(n,i,o,c,s)=>{const w=wt(o.definition.language),_=gt(o.query,w);if(_.length===0)return[];const m=gn(o,s);let C=a`SELECT id, _creationTime, ${a.identifier(ie)} FROM ${a.identifier(i)}`;m.length>0&&(C=a`${C} WHERE ${a.join(m,a` AND `)}`),C=a`${C} ORDER BY _creationTime DESC, id ASC LIMIT ${a.raw(String(cr(c)))}`;const $=H(n,C).toArray(),q=[];for(const x of $){const A=ln(x);if(!A)continue;const M=bo(Cn(A,o.definition),_);M>0&&q.push({creationTime:typeof A._creationTime=="number"?A._creationTime:0,doc:A,id:typeof A._id=="string"?A._id:"",score:M})}return q.sort((x,A)=>A.score-x.score||A.creationTime-x.creationTime||x.id.localeCompare(A.id)),q.slice(0,c).map(x=>({document:x.doc,score:x.score}))},ct=(n,i,o,c)=>{if(!Number.isFinite(n.lat)||n.lat<-90||n.lat>90||!Number.isFinite(n.lng)||n.lng<-180||n.lng>180)throw new y("BAD_REQUEST",`geo index "${c}" on table "${o}": ${i} must have a finite lat in [-90, 90] and lng in [-180, 180]`)},lr=(n,i)=>{const o=n,c={near:(s,w)=>{if(o.within)throw new y("INTERNAL",`geo index "${o.indexName}" on table "${i}": call .near() or .within(), not both`);if(ct(s,".near() point",i,o.indexName),!Number.isFinite(w)||w<=0)throw new y("BAD_REQUEST",`geo index "${o.indexName}" on table "${i}": .near() radiusMeters must be a finite number > 0, got ${String(w)}`);return o.near={point:{lat:s.lat,lng:s.lng},radiusMeters:w},c},within:s=>{if(o.near)throw new y("INTERNAL",`geo index "${o.indexName}" on table "${i}": call .near() or .within(), not both`);if(ct(s.sw,".within() sw corner",i,o.indexName),ct(s.ne,".within() ne corner",i,o.indexName),s.sw.lat>s.ne.lat)throw new y("BAD_REQUEST",`geo index "${o.indexName}" on table "${i}": .within() corners are transposed (sw.lat > ne.lat)`);if(s.sw.lng>s.ne.lng)throw new y("BAD_REQUEST",`geo index "${o.indexName}" on table "${i}": .within() box crosses the antimeridian (sw.lng > ne.lng), which is not supported — split it into two boxes at ±180 and union the results`);return o.within={ne:{lat:s.ne.lat,lng:s.ne.lng},sw:{lat:s.sw.lat,lng:s.sw.lng}},c}};return c},ur=(n,i)=>{const o=n[i];if(o===null||typeof o!="object")return;const{lat:c,lng:s}=o;return typeof c=="number"&&typeof s=="number"?{lat:c,lng:s}:void 0},fr=(n,i)=>{const o=ur(n,i.definition.field);if(!o)return;const c=typeof n._creationTime=="number"?n._creationTime:0;if(i.near){const s=zn(i.near.point,o);return s<=i.near.radiusMeters?{creationTime:c,distance:s}:void 0}return Yn(o,i.within)?{creationTime:c,distance:0}:void 0},hr=(n,i,o,c)=>{if(!o.near&&!o.within)throw new y("INTERNAL",`geo index "${o.indexName}" on table "${i}": call .near(point, radius) or .within(box)`);const s=o.near?Vn(o.near.point,o.near.radiusMeters):Jn(o.within),w=Nn(i,o.indexName),_=s.map(x=>a`(g.${a.identifier("__geohash__")} >= ${x} AND g.${a.identifier("__geohash__")} < ${`${x}{`})`),m=[a`(${a.join(_,a` OR `)})`];c&&m.push(c);const C=a`SELECT m.id, m._creationTime, m.${a.identifier(ie)} FROM ${a.identifier(w)} g JOIN ${a.identifier(i)} m ON m.id = g.${a.identifier("__id__")} WHERE ${a.join(m,a` AND `)}`,$=H(n,C).toArray(),q=[];for(const x of $){const A=Ie(x),M=A?fr(A,o):void 0;A&&M&&q.push({creationTime:M.creationTime,distance:M.distance,doc:A})}return q.sort((x,A)=>x.distance-A.distance||A.creationTime-x.creationTime),q},yn=(n,i,o,c)=>{const s=[];for(const w of n)if(i.every(_=>_(c(w)))&&(s.push(w),typeof o=="number"&&s.length>=o))break;return s},wr=(n,i,o,c,s,w=()=>{})=>{const _=o.within!==void 0,m=hr(n,i,o,s).map(C=>({distanceMeters:_?null:C.distance,document:C.doc}));return w(m.length),typeof c=="number"?m.slice(0,Math.max(0,Math.floor(c))):m},nn=(n,i,o,c,s,w,_=()=>{})=>{const{geo:m}=o;if(!m)throw new y("INTERNAL","runGeoTerminalScored called without a staged geo query");const C=s.length>0,$=wr(n,i,m,C?void 0:w,c,_);return C?yn($,s,w,q=>q.document):$},on=(n,i,o)=>{const c=n.shape[i];if(c!==void 0&&vo(c))throw new y("BAD_REQUEST",`${o}: "${i}" may hold an order-preserving key rather than a value SQL can reduce or group — declare an aggregateIndex covering this (by, field, op) so the maintained companion answers it instead (its running total is a REAL, so it stays exact only while the total is inside 2^53)`)},pr=n=>{let i=0;const o=[],c={...Ve,relationExists:s=>{const{childWhere:w,negated:_,parentTable:m,relation:C}=s,$=`__rel_${String(i)}`,q=o.at(-1)??m;i+=1,n(C.table,O);const x=C.kind==="one"?C.field:C.references,A=C.kind==="one"?C.references:C.field,M=Ne(`${Bt($,A)} = ${Bt(q,x)}`);o.push($);const W=Y(w,c,Qe);o.pop();const D=W===void 0?M:Ae(M," AND ",W),L=Ae("EXISTS (SELECT 1 FROM ",Nt(C.table)," AS ",Nt($)," WHERE ",D,")");return _?Ae("NOT ",L):L}};return c};class gr extends y{constructor(i="unique() found more than one matching document"){super("NOT_UNIQUE",i,{name:"NotUniqueError"})}}const yr=/\s/u,$r=String.fromCodePoint(0),rn=(n,i,o)=>{if(!n.tables[i])throw new y("INTERNAL",`unknown table: ${i}`);return typeof o!="string"||o.length===0||yr.test(o)||o.includes($r)?null:o},$n=(n,i,o,c=()=>{},s=()=>{},w=()=>{},_)=>{const m=i.tables[o];if(!m)throw new y("INTERNAL",`unknown table: ${o}`);const C=Te(m.softDeleteMode,void 0),$=_??{indexFields:[],indexName:void 0,inMemoryFilters:[],order:"asc",sqlConditions:[],verifyFilters:[]},q=()=>{const S=K(C,$.pushedWhere);return S?Y(S,he):void 0},x=()=>{const S=K(C,$.pushedWhere);return S?Y(S,Ve,Qe):void 0},A=()=>[...$.inMemoryFilters,...$.verifyFilters];let M=0;const W=S=>{const{search:b}=$;if(!b)throw new y("INTERNAL","runSearchFetch called without a staged search");Fn(n,o,m);const T=$.inMemoryFilters.length>0,k=Po(T?void 0:S),Z=Kn(n);if(Z&&!qn(n,o,b.definition))throw new y("SEARCH_INDEX_BUILDING",`search index "${b.indexName}" on table "${o}" is still backfilling and currently covers only part of the table — retry once it finishes, or run the backfillSearch admin operation to complete it now`);const N=q(),J=Z?ar(n,o,b,k,N):dr(n,o,b,k,N);!T&&S===void 0&&ko(J);const re=A();return M=J.length,re.length>0?yn(J,re,S,ce=>ce.document):J},D=S=>W(S).map(b=>b.document),L=S=>{const b=Wo(S);return Bo(D(Lo(b)),b)},F=()=>{if($.search||$.geo||$.indexName===void 0){s(void 0);return}s(ho(o,$.indexName,$.indexFields,$.sqlConditions,Ce))},G=S=>{F();let b=0;const T=(()=>{if($.search){const k=D(S);return b=M,k}return $.geo?nn(n,o,$,q(),A(),S,k=>{b=k}).map(k=>k.document):ut(n,o,m,$,x(),{filters:A(),selective:$.inMemoryFilters.length>0,want:S===void 0?void 0:Math.max(0,Math.floor(S))},k=>{b+=k}).documents})();return w(Math.max(b,T.length)),T},se=()=>{if(!$.search&&!$.geo)throw new y("INTERNAL",`ctx.db.query("${o}").collectWithScores() requires a staged .withSearchIndex(...) or .withGeoIndex(...)`);F();let S=0;const b=(()=>{if($.search){const T=W(void 0);return S=M,T}return nn(n,o,$,q(),A(),void 0,T=>{S=T})})();return w(Math.max(S,b.length)),b},X={async*[Symbol.asyncIterator](){const S=$n(n,i,o,c,s,w,{...$,indexFields:[...$.indexFields],inMemoryFilters:[...$.inMemoryFilters],sqlConditions:[...$.sqlConditions],verifyFilters:[...$.verifyFilters]});if($.search){yield*await S.collect();return}let b;for(;;){const T=await S.paginate({cursor:b??null,numItems:ir});if(yield*T.page,T.isDone||T.continueCursor===null)return;b=T.continueCursor}},async collect(){return G(void 0)},async collectWithScores(){return se()},filter(S){const b=wo(S);return b!==void 0&&po(b,m.shape)?($.pushedWhere=K($.pushedWhere,b),$.verifyFilters.push(S)):$.inMemoryFilters.push(S),X},async first(){return G(1)[0]??null},order(S){return $.order=S==="desc"?"desc":"asc",X},async paginate(S){let b=0;if(F(),$.search){const k=L(S);return w(k.page.length),k}if($.geo)throw new y("INTERNAL","pagination is not supported on geo queries; use .take(n) or .collect()");const T=Vo(n,o,m,$,S,x(),{all:A(),selective:$.inMemoryFilters.length>0},k=>{b+=k});return w(Math.max(b,T.page.length)),T},async take(S){return G(S)},async unique(){const S=G(2);if(S.length>1)throw new gr(`unique() on table "${o}" matched ${String(S.length)} documents; expected at most one`);return S[0]??null},withGeoIndex(S,b){const T=(m.geoIndexes??[]).find(Z=>Z.name===S);if(!T)throw new y("INTERNAL",`unknown geo index "${S}" on table "${o}"`);c(o,S,"geo");const k={definition:T,indexName:S};if($.geo=k,b(lr(k,o)),!k.near&&!k.within)throw new y("INTERNAL",`geo index "${S}" on table "${o}" requires a .near(point, radius) or .within(box) call`);return X},withIndex(S,b){const T=m.indexes.find(k=>k.name===S);if(!T)throw new y("INTERNAL",`unknown index "${S}" on table "${o}"`);return c(o,S,"index"),$.indexName=S,$.indexFields=T.fields,b&&b(sr($)),X},withSearchIndex(S,b){const T=(m.searchIndexes??[]).find(Z=>Z.name===S);if(!T)throw new y("INTERNAL",`unknown search index "${S}" on table "${o}"`);c(o,S,"search");const k={definition:T,field:T.field,filters:[],hasQuery:!1,indexName:S,query:""};if($.search=k,b(Do(k,o,wt(T.language))),!k.hasQuery)throw new y("INTERNAL",`search index "${S}" on table "${o}" requires a .search(field, query) call`);return X}};return X},at=(n,i,o,c)=>{const s=o;for(const[w,_]of jn(n)){if(_.serverDefault){w in i&&(s[w]=_.serverDefault({auth:c}));continue}_.onUpdateFn&&!(w in i)&&(s[w]=_.onUpdateFn())}},sn=5,cn=(n,i)=>{for(const o of Object.keys(i))if(i[o]===void 0)throw new y("INTERNAL",`Cannot ${n} field '${o}' to undefined — use null to clear a nullable field, or omit the key to leave it unchanged.`)},an=["_commitSeq","_creationTime","_id"],Ge=n=>an.some(i=>i in n)?Object.fromEntries(Object.entries(n).filter(([i])=>!an.includes(i))):n,Er=/unique constraint failed/i,mr=n=>n instanceof Error&&Er.test(n.message),Sr=/string or blob too big/iu,_r=(n,i)=>{if(!(!(n instanceof Error)||!Sr.test(n.message)))throw new y("PAYLOAD_TOO_LARGE",`document is too large to store in "${i}": a single row cannot exceed the storage engine's per-row ceiling (2 MB on a Durable Object's SQLite). The limit is on the STORED bytes, which are UTF-8, and v.bytes()/v.bigint() columns are stored twice on a shard-local table. Keep the payload in R2 (ctx.storage) and store a reference on the row.`)},ht=(n,i,o,c)=>{try{pe(n,o,...c)}catch(s){throw mr(s)?new de(`unique constraint violation on "${i}"`,"unique"):(_r(s,i),s)}},je=(n,i,o,c)=>{if(ht(n,i,o,c),pe(n,Xo).one().changed===0)throw new de(`optimistic concurrency conflict on "${i}" — the row changed during this mutation; refetch and retry`,"occ")},dn=(n,i,o,c,s,w,_)=>{const m=[];for(let x=0;x<o.length+1;x+=1){const A=o[x],M=c[x],W=M?.direction==="desc"?"desc":"asc",D=A===void 0||M===void 0?a`${a.identifier(lo)} < ${_}`:uo(A,w[x],W,!1);if(D===void 0)continue;const L=[];for(let G=0;G<x;G+=1)L.push(a`${a.identifier(o[G])} IS ${w[G]}`);L.push(D);const[F]=L;m.push(L.length===1&&F!==void 0?F:a`(${a.join(L,a` AND `)})`)}const C=m.length>0?a.join(m,a` OR `):a`1 = 0`,$=H(n,a`SELECT COUNT(*) AS c FROM ${a.identifier(i)} WHERE ${a.identifier("__partition__")} = ${s} AND (${C})`).one(),q=H(n,a`SELECT COUNT(*) AS c FROM ${a.identifier(i)} WHERE ${a.identifier("__partition__")} = ${s}`).one();return{before:$.c,total:q.c}},Rr=n=>{const i=new Map;for(const[c,s]of Object.entries(n.tables))for(const w of Object.values(s.relationMap??{}))w.kind==="one"&&(w.onDelete==="cascade"||w.onDelete==="set null")&&i.set(w.table,[...i.get(w.table)??[],{holder:c,op:w.onDelete==="cascade"?"delete":"update"}]);const o=c=>{const s=new Set,w=[c];for(let _=w.pop();_!==void 0;_=w.pop())for(const{holder:m,op:C}of i.get(_)??[]){if(m===c||Jt(n,m,C))return!0;s.has(m)||(s.add(m),w.push(m))}return!1};return new Set(Object.entries(n.tables).filter(([c,s])=>s.shardMode?.kind==="global"||Jt(n,c,"delete")||o(c)).map(([c])=>c))},Tr=n=>{const i=new Map;for(const[o,c]of Object.entries(n.tables))c.softDeleteMode&&i.set(o,c.softDeleteMode.field);return i},di=n=>{const{baselineSeq:i,onStalePatchDropped:o}=n,{sql:c}=n,{schema:s}=n,w=n.broadcast??(()=>{}),_=go(s),m=new Map;for(const e of _){const t=r=>(s.tables[r]?.shardMode?.kind??"root")==="root";!e.array&&t(e.sourceTable)&&t(e.targetTable)&&m.set(e.sourceTable,[...m.get(e.sourceTable)??[],e])}const C=(e,t,r)=>{for(const l of m.get(e)??[]){const f=t[l.column];if(typeof f!="string"||r?.[l.column]===f||l.targetTable===e&&t._id===f)continue;if(H(c,a`SELECT 1 FROM ${a.identifier(l.targetTable)} WHERE id = ${f} LIMIT 1`).toArray().length===0)throw new y("VALIDATION_ERROR",`${l.name} references ${l.targetTable} row "${f}", which does not exist`)}},$=mo(s,n.inTransaction),q=Rr(s),x=Tr(s);let A;const M=()=>n.inTransaction?.()===!0,W=e=>s.tables[e]?.commitOrderedMode!==!0?{}:((A===void 0||!M())&&(A=Pn(c)),{[Un]:A}),D=(e,...t)=>{const r=s.tables[e]?.indexes;if(!r||r.length===0)return;const l=[];for(const f of t)f&&l.push(...fo(r,f,Ce));return l.length>0?l:void 0},{headroom:L}=n;let F=!1;const G=async e=>{const t=F;F=!0;try{return await e()}finally{F=t}},se=n.onRead??(()=>{}),X=e=>{qt(s.tables[e])&&se(Kt,Kt)},S=n.onReadRange??(e=>{se(e.table,O)}),b=e=>{X(e.table),S(e)},T=(e,t)=>{t!==void 0&&t!==O&&!F&&L?.recordRead(1),X(e),se(e,t)},k=n.onIndexUse??(()=>{}),Z=n.onWrite??(()=>{}),N=e=>{F||L?.recordWrite(e)},J=async e=>{N(e.doc),await Z(e)},{cache:re}=n,ce=n.clock??(()=>Date.now()),$t=n.idGenerator??(()=>crypto.randomUUID()),Et=n.scheduler??bn,{globalDb:ye}=n,le=n.auth??{identity:null,userId:null},mt=n.cdc??!1,ze=Et,En=Io({scheduler:typeof ze.list=="function"&&typeof ze.get=="function"?ze:void 0,storage:n.storage}),$e=(e,t,r,l)=>{mt&&!qt(s.tables[e])&&Wn(c,ce(),e,t,r,l)},St=(e,t,r,l)=>{const f=s.tables[e];if(f?.dropStalePatchesMode!==!0||!mt)return!1;const h=i?.();if(h===void 0)return!1;const d=Bn(c,e,t,h);if(d===void 0)return!1;const u=to(f,r);return Object.keys(Ge(r)).some(p=>!u.has(p)&&Ft(Pt(d,p))!==Ft(Pt(l,p)))},ae=e=>s.tables[e]?.shardMode?.kind==="global",_t=(e,t)=>{if(ae(e)){if(!ye)throw new y("INTERNAL",`cross-backend ${t} for global table '${e}' requires a globalDb writer — pass one to createShardCtxDb({ globalDb })`);return ye}return P},Ye=e=>_t(e,"cascade"),j=(e,t)=>{if(ae(e)){if(!ye)throw new y("INTERNAL",`${t} on global table '${e}' requires a globalDb writer — pass one to createShardCtxDb({ globalDb })`);return ye}},Rt=async(e,t,r,l,f)=>{f&&N(r);const h=await e.insert(t,r,l);return w({key:h,op:"insert",row:{...r,_id:h},table:t}),h},Xe=(e,t)=>_t(e,"relation load").findMany(e,t),Tt=(e,t)=>(ae(e)&&T(e,O),Xe(e,t)),mn=e=>!ae(e.table),vt=n.relationExistsPushDown??"auto",It=vt!=="never",{maxRelationKeys:At}=n,be=(e,t,r)=>$o(e,{fetcher:Tt,maxRelationKeys:At,relationBaseWhere:r,schema:s,tableName:t}),Ct=async(e,t,r,l)=>{const f=j(e,"relation grouped count");if(f)return T(e,O),Ro((E,U)=>f.count(E,U),e,t,r,l);const h=s.tables[e];if(!h)throw new y("INTERNAL",`unknown table: ${e}`);T(e,O);const d=Te(h.softDeleteMode,void 0),u={[t]:{in:r}},p=K(K(u,l),d),R=await be(p,e,void 0),I=Y(R,he),g=we(t);let v=a`SELECT ${g} AS __fk__, COUNT(*) AS count FROM ${a.identifier(e)}`;I&&(v=a`${v} WHERE ${I}`),v=a`${v} GROUP BY ${g}`;const B=H(c,v).toArray();return new Map(B.map(E=>[E.__fk__,E.count]))};let Me=0;const xt=new Set;for(const[e,t]of Object.entries(s.tables))for(const r of Object.values(t.triggerMap??{}))xt.add(`${e} ${r.timing} ${r.op}`);const ee=(e,t,r)=>xt.has(`${e} ${t} ${r}`),te=async(e,t,r)=>{if(Me+=1,Me>en)throw Me-=1,new de(`trigger recursion exceeded ${String(en)} levels on "${r.table}" — check for a self-triggering write`,"trigger");try{await Ao({ctx:vn,event:r,op:t,schema:s,tableName:r.table,timing:e})}finally{Me-=1}},{ensureBackfilledForTable:Ee,ensureBackfilledIndex:Ze,ensureRankBackfilled:et,ensureRankBackfilledForTable:me,syncAggregates:De,syncCompanionsForInsert:bt,syncGeo:ke,syncRanks:Se,syncSearch:Le}=On({broadcast:w,indexKeysFor:(e,t)=>D(e,t),invalidateCache:(e,t,r)=>re?.invalidate(e,t,D(e,r)),recordCdc:$e,schema:s,sql:c}),Mt=(e,t,r)=>{const{shardMode:l}=t;if(l?.kind==="shardBy"&&!(l.field!==void 0&&(r.partitionBy??[]).includes(l.field)))throw Object.assign(new Error(`rank index "${r.name}" on "${e}" partitions across shards (shard key "${l.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})},Dt=e=>Object.entries(s.tables).filter(([,t])=>t.shardMode?.kind!=="global").map(([t])=>t).filter(t=>e===void 0||t===e),_e=e=>e===void 0||ae(e)?ye:void 0,ne=(e,t)=>{const r=Dt(t);for(let l=0;l<r.length;l+=Re){const f=r.slice(l,l+Re),[h]=pe(c,er(f),...tr(e,f)).toArray();if(!h)continue;const d=h.__t__,u=Ie(h);if(typeof d!="string"||!u)return;const p=h[ie];return{docJson:typeof p=="string"?p:fe(p??{}),row:u,tableName:d}}},Sn=(e,t)=>{const r=[...new Set(e)],l=new Map;if(r.length===0)return l;const f=Dt(t);for(let h=0;h<f.length;h+=Re){const d=f.slice(h,h+Re),u=Math.floor(Re/d.length),p=Qn(a`${a.identifier("id")}`,r,!1,u),R=d.map(I=>a`SELECT ${a.raw(`'${I.replaceAll("'","''")}'`)} AS __t__, id FROM ${a.identifier(I)} WHERE ${p}`);for(const I of H(c,pt(R))){const{id:g,__t__:v}=I;typeof v=="string"&&typeof g=="string"&&l.set(g,v)}}return l},kt={assertRankPartitionLocal:Mt,ensureRankBackfilled:et,onRead:T,rowToDocument:Ie,schema:s,sql:c},_n=(e,t,r)=>{const l=Y(r,he);return l===void 0||H(c,a`SELECT 1 FROM ${a.identifier(e)} WHERE ${a.identifier("id")} = ${t} AND ${l}`).toArray().length>0},Rn=(e,t,r,l)=>St(e,t,r,l)?(o?.({fields:Object.keys(Ge(r)),id:t,table:e}),!0):!1,Tn=async(e,t,r,l,f)=>{const h=ne(t,e);if(!h)return{applied:!1,doc:null};if(T(e,t),!_n(e,t,r.where)||Rn(e,t,r.patch,h.row))return{applied:!1,doc:h.row};try{await f(r.patch)}catch(d){if(d instanceof de&&d.kind==="occ"&&l)return;throw d}return{applied:!0,doc:ne(t,e)?.row??null}},Lt=async(e,t,r,l)=>{const{fetchLimit:f,limit:h,orderKeys:d,predicate:u}=await Eo(t,r,{canPushExists:It?mn:void 0,existsPushMode:vt==="always"?"always":"auto",fetcher:Tt,maxRelationKeys:At,schema:s,tableName:e}),p=It?pr(l):Ve,R=Y(u,p,Qe),I=hn(e,R,wn(d),f);return{limit:h,orderKeys:d,statement:I}},P={system:En,async aggregate(e,t){const r=j(e,"aggregate");if(r)return T(e,O),r.aggregate(e,t);const l=s.tables[e];if(!l)throw new y("INTERNAL",`unknown table: ${e}`);if(Be(t.op),t.op==="count")return P.count(e,{baseWhere:t.baseWhere,relationBaseWhere:t.relationBaseWhere,restrictsCounts:t.restrictsCounts,where:t.where});if(!t.field)throw new y("INTERNAL",`aggregate(${e}, { op: "${t.op}" }): "field" is required for non-count reducers`);T(e,O);const f=Te(l.softDeleteMode,void 0),h=K(K(t.baseWhere,t.where),f),d=await be(h,e,t.relationBaseWhere),u=d!==h;if(l.aggregateIndexes&&!t.baseWhere&&!u){const E=Ln(l.aggregateIndexes,t.op,t.field,t.where);if(E){Ze(e,E.index);const U=nt(E.index.by??[],E.key),oe=tt(e,E.index.name),z=H(c,a`SELECT ${Pe} AS value, ${it} AS count FROM ${a.identifier(oe)} WHERE ${Ue} = ${U}`).toArray()[0];return ot(t.op,z)}}on(l,t.field,`aggregate(${e}, { op: "${t.op}", field: "${t.field}" })`);const p=Y(d,he),R=Be(t.op),I=we(t.field);let g=a`SELECT ${a.raw(R)}(${I}) AS value FROM ${a.identifier(e)}`;p&&(g=a`${g} WHERE ${p}`);const B=H(c,g).toArray()[0]?.value;return B??null},asId(e,t){const r=rn(s,e,t);if(r===null)throw new y("BAD_REQUEST",`asId("${e}", …): "${t}" is not a valid id for table "${e}"`,{status:400});return r},async count(e,t){const r=j(e,"count");if(r)return T(e,O),r.count(e,t);const l=s.tables[e];if(!l)throw new y("INTERNAL",`unknown table: ${e}`);const f=Mn(t);if(f.restrictsCounts)throw new rt(e);T(e,O);const h=Te(l.softDeleteMode,void 0),d=K(K(f.baseWhere,f.where),h),u=await be(d,e,f.relationBaseWhere),p=u!==d;if(l.aggregateIndexes&&!f.baseWhere&&!p){const v=kn(l.aggregateIndexes,f.where);if(v){Ze(e,v.index);const B=nt(v.index.by??[],v.key),E=tt(e,v.index.name),U=H(c,a`SELECT ${Pe} AS value FROM ${a.identifier(E)} WHERE ${Ue} = ${B}`).toArray();return U[0]===void 0?0:U[0].value??0}}const R=Y(u,he);let I=a`SELECT COUNT(*) AS count FROM ${a.identifier(e)}`;return R&&(I=a`${I} WHERE ${R}`),H(c,I).one().count},async delete(e,t,r){const l=ne(e,t);if(!l){const g=_e(t);g&&(N(void 0),await g.delete(e,t,r));return}const{docJson:f,row:h,tableName:d}=l,u=s.tables[d],p=r?.hard===!0,R=!p&&u?.softDeleteMode?u:void 0,I=R?.softDeleteMode?.field;if(!(I&&h[I]!==null&&h[I]!==void 0)){if(ee(d,"before","delete")&&await te("before","delete",{id:e,op:"delete",previous:h,table:d}),await _o({deletedId:e,deletedReference:g=>h[g],findHolders:async(g,v,B)=>(await Ye(g).findMany(g,{includeDeleted:p,where:{[v]:B}})).page,onCascade:(g,v)=>Ye(g).delete(v,void 0,r),onRestrict:g=>{throw new de(g,"restrict")},onSetNull:(g,v,B)=>Ye(g).patch(v,{[B]:null}),schema:s,tableName:d}),Ee(d),me(d),R&&I){const g={[I]:ce()},v={...h,...W(d),...g,_id:e};at(R,g,v,le),je(c,d,Xt(d),[fe(v),e,f]),Le(d,e,v,h),ke(d,e,void 0),De(d,h,v),Se(d,e,h,void 0),re?.invalidate(d,e,D(d,h,v)),$e(d,e,"update",v),w({indexKeys:D(d,h,v),key:e,op:"update",row:v,table:d}),ee(d,"after","delete")&&await te("after","delete",{id:e,op:"delete",previous:h,table:d}),await J({id:e,op:"delete",table:d});return}je(c,d,Yo(d),[e,f]),Le(d,e,void 0),ke(d,e,void 0),De(d,h,void 0),Se(d,e,h,void 0),re?.invalidate(d,e,D(d,h)),$e(d,e,"delete"),w({indexKeys:D(d,h),key:e,op:"delete",table:d}),ee(d,"after","delete")&&await te("after","delete",{id:e,op:"delete",previous:h,table:d}),await J({id:e,op:"delete",table:d})}},async deleteAll(e,t){if(!s.tables[e])throw new y("INTERNAL",`unknown table: ${e}`);const r=Math.max(1,t?.chunkSize??yt),l=t?.hard===void 0?void 0:{hard:t.hard},f=ae(e)?void 0:e;let h=0;return await G(async()=>{for(;;){const u=(await P.findMany(e,{limit:r})).page.map(p=>String(p._id));if(u.length===0)break;for(const p of u)await P.delete(p,f,l),h+=1;if(u.length<r)break}}),{deleted:h}},async deleteMany(e,t,r){ve(e.length,t?.limit,"deleteMany");for(const l of e)await P.delete(l,r);return{deleted:e.length}},async deleteWhere(e,t,r){const l=j(e,"deleteWhere")??P,h=(await tn(l,e,t,r?.limit,"deleteWhere")).map(d=>String(d._id));if(P.deleteMany===void 0)throw new y("INTERNAL",`ctx.db.${e}.deleteMany is unavailable: this writer has no batch delete`);return P.deleteMany(h,r,e)},async findFirst(e,t={}){return(await P.findMany(e,{...t,limit:1,omitContinueCursor:!0})).page[0]??null},async findFirstOrThrow(e,t={}){const r=await P.findFirst(e,t);if(r===null)throw new Xn(`findFirstOrThrow: no "${e}" document matched`);return r},async findMany(e,t={}){const r=j(e,"findMany");if(r)return T(e,O),r.findMany(e,t);const l=s.tables[e];if(!l)throw new y("INTERNAL",`unknown table: ${e}`);const f=!t.where&&!t.baseWhere;f?T(e,O):T(e);const{limit:h,orderKeys:d,statement:u}=await Lt(e,l,t,T),p=pe(c,u.text,...u.params).toArray();f&&!F&&L?.recordRead(p.length);const R=[];for(const B of p){const E=Ie(B);E&&(R.push(E),!f&&typeof E._id=="string"&&T(e,E._id))}if(h===void 0)return t.with&&await Qt({groupedCounter:Ct,fetcher:Xe,parents:R,...Vt(t),schema:s,tableName:e,with:t.with}),{continueCursor:null,isDone:!0,page:Ht(R,t.select,t.with)};const I=R.length>h,g=I?R.slice(0,h):R,v=g.at(-1);return t.with&&await Qt({fetcher:Xe,groupedCounter:Ct,parents:g,...Vt(t),schema:s,tableName:e,with:t.with}),{continueCursor:I&&v&&t.omitContinueCursor!==!0?Ke(v,d):null,isDone:!I,page:Ht(g,t.select,t.with)}},async explain(e,t={}){const r=j(e,"explain");if(r)return r.explain(e,t);const l=s.tables[e];if(!l)throw new y("INTERNAL",`unknown table: ${e}`);const{statement:f}=await Lt(e,l,t,()=>{}),h=pe(c,`EXPLAIN QUERY PLAN ${f.text}`,...f.params).toArray();return{params:f.params,plan:h.map(d=>String(d.detail)),sql:f.text}},async get(e,t){const r=ne(e,t);if(!r){const l=_e(t);return l?l.get(e,t):null}return T(r.tableName,e),r.row},async lookupById(e,t){const r=ne(e,t);return r?(T(r.tableName,e),{row:r.row,tableName:r.tableName}):null},async groupBy(e,t){const r=j(e,"groupBy");if(r)return T(e,O),r.groupBy(e,t);const l=s.tables[e];if(!l)throw new y("INTERNAL",`unknown table: ${e}`);T(e,O);const f=t.agg??{op:"count"};if(Be(f.op),f.op!=="count"&&!f.field)throw new y("INTERNAL",`groupBy(${e}, { agg: { op: "${f.op}" } }): "field" is required for non-count reducers`);const h=Te(l.softDeleteMode,void 0),d=K(K(t.baseWhere,t.where),h),u=await be(d,e,t.relationBaseWhere),p=u!==d;if(l.aggregateIndexes&&!t.baseWhere&&!p){const E=Dn(l.aggregateIndexes,f.op,f.field,t.by,t.where),U=E===void 0?0:Object.keys(E.partial).length,oe=E?.index.by?.length??0;if(E&&(U===0||U===oe)){Ze(e,E.index);const z=tt(e,E.index.name),Q=Object.keys(E.partial),ue=[];if(Q.length===(E.index.by??[]).length&&Q.length>0){const Fe=nt(E.index.by??[],E.partial),qe=H(c,a`SELECT ${Pe} AS value, ${it} AS count FROM ${a.identifier(z)} WHERE ${Ue} = ${Fe}`).toArray();return qe.length>0&&ue.push({key:{...E.partial},value:ot(f.op,qe[0])}),ue}const In=H(c,a`SELECT ${Ue} AS key, ${Pe} AS value, ${it} AS count FROM ${a.identifier(z)}`).toArray();for(const Fe of In){const qe=xn(JSON.parse(Fe.key));ue.push({key:qe,value:ot(f.op,Fe)})}return ue}}for(const E of[...t.by,f.field]){if(E===void 0)continue;const U=E===f.field?`groupBy(${e}, { agg: { op: "${f.op}", field: "${E}" } })`:`groupBy(${e}, { by: [..."${E}"] })`;on(l,E,U)}const R=Y(u,he),I=t.by.map(E=>a`${we(E)} AS ${a.identifier(E)}`);if(f.op==="count")I.push(a`COUNT(*) AS value`);else{const{field:E}=f;if(E===void 0)throw new y("INTERNAL",`groupBy(${e}, { agg: { op: "${f.op}" } }): "field" is required for non-count reducers`);I.push(a`${a.raw(Be(f.op))}(${we(E)}) AS value`)}let g=a`SELECT ${a.join(I,a`, `)} FROM ${a.identifier(e)}`;R&&(g=a`${g} WHERE ${R}`),g=a`${g} GROUP BY ${a.join(t.by.map(E=>we(E)),a`, `)}`;const v=H(c,g).toArray(),B=[];for(const E of v){const U={};for(const z of t.by)U[z]=Gn(l.shape[z],E[z]??null);const{value:oe}=E;B.push({key:U,value:oe==null?null:Number(oe)})}return B},async insert(e,t,r){const l=j(e,"insert");if(l)return Rt(l,e,t,r,!0);const f=s.tables[e];if(!f)throw new y("INTERNAL",`unknown table: ${e}`);const h=r?.allowExplicitId===!0,d=Oe(f,lt(f,t,le),{supplied:t,trusted:h});let u;r?.clientId!==void 0?(or(r.clientId),u=r.clientId):r?.allowExplicitId&&typeof d._id=="string"?(ft(d._id),u=d._id):u=$t();const p=r?.allowExplicitId&&typeof d._creationTime=="number"?d._creationTime:ce(),R={...d,...W(e),_creationTime:p,_id:u};return ee(e,"before","insert")&&await te("before","insert",{doc:{...R},id:u,op:"insert",table:e}),h||C(e,R),Ee(e),me(e),ht(c,e,Jo(e),[u,p,fe(R)]),bt(e,u,R),ee(e,"after","insert")&&await te("after","insert",{doc:R,id:u,op:"insert",table:e}),await J({doc:R,id:u,op:"insert",table:e}),u},async insertManyUnsafe(e,t,r){if(ve(t.length,r?.limit,"insertManyUnsafe"),t.length===0)return[];const l=j(e,"insert");if(l){const p=[];rr(s.tables[e],t,r?.allowExplicitId,le);for(const R of t)N(R);for(const R of t){const I=await l.insert(e,R,{allowExplicitId:r?.allowExplicitId});w({key:I,op:"insert",row:{...R,_id:I},table:e}),p.push(I)}return p}const f=s.tables[e];if(!f)throw new y("INTERNAL",`unknown table: ${e}`);Ee(e),me(e);const h=[];for(let p=0;p<t.length;p+=He)h.push(W(e));const d=r?.allowExplicitId===!0?void 0:So(f),u=t.map((p,R)=>{const I=lt(f,p,le),g=d===void 0?I:Oe(d,I,{supplied:p}),v=r?.allowExplicitId===!0&&typeof g._id=="string"?g._id:void 0;v!==void 0&&ft(v);const B=v??$t(),E=r?.allowExplicitId===!0&&typeof g._creationTime=="number"?g._creationTime:ce(),U={...g,...h[Math.floor(R/He)],_creationTime:E,_id:B};return{creationTime:E,document:U,id:B}});for(const p of u)N(p.document);for(let p=0;p<u.length;p+=He){const R=a.join(u.slice(p,p+He).map(g=>a`(${g.id}, ${g.creationTime}, ${fe(g.document)})`),a`, `),I=un("sqlite",a`INSERT INTO ${a.identifier(e)} (id, _creationTime, ${a.identifier(ie)}) VALUES ${R}`);ht(c,e,I.sql,I.params)}for(const{document:p,id:R}of u)bt(e,R,p),await Z({doc:p,id:R,op:"insert",table:e});return u.map(p=>p.id)},async insertMany(e,t,r){ve(t.length,r?.limit,"insertMany");const l=r?.skipDuplicates===!0,f=[],h=j(e,"insert");if(h)for(const u of t)N(u);const d=async u=>h?Rt(h,e,u,void 0,!1):P.insert(e,u);for(const u of t)try{f.push(await d(u))}catch(p){if(l&&p instanceof de&&p.kind==="unique")f.push(null);else throw p}return f},normalizeId(e,t){return rn(s,e,t)},async patch(e,t,r,l){const f=ne(e,r);if(!f){const v=_e(r);if(v){N(t),await v.patch(e,t,r,l);return}throw new y("NOT_FOUND",`document not found: ${e}`)}const{docJson:h,row:d,tableName:u}=f,p=s.tables[u];if(!p)throw new y("INTERNAL",`unknown table: ${u}`);if(T(u,e),cn("patch",t),St(u,e,t,d)){o?.({fields:Object.keys(Ge(t)),id:e,table:u});return}const R=Zn(p,t,d),I={...d,...Ge(R),...W(u),_id:e};at(p,R,I,le);const g=Oe(p,I,{only:new Set(Object.keys(R)),previous:()=>d,tolerateStoredNull:!0});eo(l,d,g),ee(u,"before","update")&&await te("before","update",{doc:{...g},id:e,op:"update",previous:d,table:u}),C(u,g,d),Ee(u),me(u),je(c,u,Xt(u),[fe(g),e,h]),Le(u,e,g,d),ke(u,e,g),De(u,d,g),Se(u,e,d,g),re?.invalidate(u,e,D(u,d,g)),$e(u,e,"update",g),w({indexKeys:D(u,d,g),key:e,op:"update",row:g,table:u}),ee(u,"after","update")&&await te("after","update",{doc:g,id:e,op:"update",previous:d,table:u}),await J({doc:g,id:e,op:"update",table:u})},async patchIf(e,t,r){const l=j(e,"patchIf");if(l){if(l.patchIf===void 0)throw new y("INTERNAL",`ctx.db.patchIf on global table '${e}' is unsupported: its backend has no conditional write`);return N(r.patch),l.patchIf(e,t,r)}if(!s.tables[e])throw new y("INTERNAL",`unknown table: ${e}`);for(let f=1;f<=sn;f+=1){const h=await Tn(e,t,r,f<sn,d=>P.patch(t,d,e,{verify:r.verify}));if(h!==void 0)return h}throw new de(`patchIf on "${e}" kept conflicting; the row changed on every attempt`,"occ")},async patchMany(e,t,r){ve(e.length,t?.limit,"patchMany");for(const l of e)await P.patch(l.id,l.patch,r);return{patched:e.length}},async patchWhere(e,t,r){const l=j(e,"patchWhere")??P,h=(await tn(l,e,t.where,r?.limit,"patchWhere")).map(d=>({id:String(d._id),patch:t.patch}));if(P.patchMany===void 0)throw new y("INTERNAL",`ctx.db.${e}.patchMany is unavailable: this writer has no batch patch`);return await P.patchMany(h,r,e),{patched:h.length}},async related(e,t){return yo(P,_,e,t)},relationEdges:_,deleteRereadTables:q,inTransaction:M,softDeleteFields:x,relationWrites:$,query(e){const t=j(e,"query");return t?(T(e,O),t.query(e)):$n(c,s,e,k,r=>{r?b(r):T(e,O)},r=>{F||L?.recordRead(r)})},async rank(e,t,r){const l=j(e,"rank");if(l)return T(e,O),l.rank(e,t,r);k(e,t,"rank");const f=s.tables[e];if(!f)throw new y("INTERNAL",`unknown table: ${e}`);const h=f.rankIndexes?.find(Q=>Q.name===t);if(!h)throw new y("INTERNAL",`unknown rankIndex "${t}" on table "${e}"`);if(Mt(e,f,h),r.restrictsCounts)throw new rt(e);T(e,O),et(e,h);const d=typeof r.row=="string"?r.row:r.row._id;if(!d)return null;const u=Gt(e,h.name),p=h.sortBy.map((Q,ue)=>jt(ue)),R=p.map(Q=>xe(Q)).join(", "),I=H(c,a`SELECT ${a.identifier("__partition__")}, ${a.raw(R)} FROM ${a.identifier(u)} WHERE ${a.identifier("__id__")} = ${d}`).toArray(),[g]=I;if(g===void 0)return null;let v=g.__partition__;const B=K(r.baseWhere,r.where);st(B,s,e,"rank");const E=co(h,B);if(E){const Q=ao(h.partitionBy??[],E);if(Q!==v)return null;v=Q}const U=p.map(Q=>g[Q]),{before:oe,total:z}=dn(c,u,p,h.sortBy,v,U,d);return{position:oe+1,total:z}},async rankBefore(e,t,r){if(ae(e))throw new y("INTERNAL",`rankBefore is not supported on the global (.global()) table '${e}' — cross-shard rank cursors apply only to sharded tables`);const l=s.tables[e];if(!l)throw new y("INTERNAL",`unknown table: ${e}`);const f=l.rankIndexes?.find(p=>p.name===t);if(!f)throw new y("INTERNAL",`unknown rankIndex "${t}" on table "${e}"`);if(r.restrictsCounts)throw new rt(e);T(e,O),et(e,f);const h=Gt(e,f.name),d=f.sortBy.map((p,R)=>jt(R)),u=f.sortBy.map((p,R)=>Ce(r.sortValues[R]??null));return dn(c,h,d,f.sortBy,r.partitionKey,u,r.rowId)},async rankPage(e,t,r={}){st(K(r.baseWhere,r.where),s,e,"rankPage");const l=j(e,"rankPage");if(l)return T(e,O),l.rankPage(e,t,r);k(e,t,"rank");const{continueCursor:f,hasMore:h,rows:d}=Wt(kt,e,t,r);return{continueCursor:f,isDone:!h,page:d.map(u=>u.doc)}},async rankPageRows(e,t,r={}){st(K(r.baseWhere,r.where),s,e,"rankPage"),k(e,t,"rank");const{directions:l,hasMore:f,rows:h}=Wt(kt,e,t,r);return{directions:l,hasMore:f,rows:h}},async restore(e,t){const r=ne(e,t);if(!r){const h=_e(t);if(h?.restore){await h.restore(e,t);return}throw new y("NOT_FOUND",`document not found: ${e}`)}const l=s.tables[r.tableName]?.softDeleteMode?.field;if(!l)throw new y("INTERNAL",`ctx.db.restore: table "${r.tableName}" is not a .softDelete() table`);const f=r.row[l]!==null&&r.row[l]!==void 0;await P.patch(e,{[l]:null},t),f&&Se(r.tableName,e,void 0,r.row)},async replace(e,t,r,l){const f=ne(e,r);if(!f){const U=_e(r);if(U){N(t),await U.replace(e,t,r,l);return}throw new y("NOT_FOUND",`document not found: ${e}`)}const{docJson:h,row:d,tableName:u}=f,p=s.tables[u];if(!p)throw new y("INTERNAL",`unknown table: ${u}`);cn("replace",t);const R=l?.allowExplicitId&&typeof t._creationTime=="number"?t._creationTime:void 0,I=typeof d._creationTime=="number"?d._creationTime:void 0,g=R??I??ce(),v={...t,...W(u),_creationTime:g,_id:e};at(p,t,v,le);const B=l?.allowExplicitId===!0,E=Oe(p,v,{previous:()=>d,supplied:t,trusted:B});ee(u,"before","update")&&await te("before","update",{doc:{...E},id:e,op:"update",previous:d,table:u}),B||C(u,E,d),Ee(u),me(u),je(c,u,zo(u),[g,fe(E),e,h]),Le(u,e,E,d),ke(u,e,E),De(u,d,E),Se(u,e,d,E),re?.invalidate(u,e,D(u,d,E)),$e(u,e,"update",E),w({indexKeys:D(u,d,E),key:e,op:"update",row:E,table:u}),ee(u,"after","update")&&await te("after","update",{doc:E,id:e,op:"update",previous:d,table:u}),await J({doc:E,id:e,op:"update",table:u})},async wipeShard(e){const t=new Set(e?.exclude),r=e?.tables,l=Object.entries(s.tables).filter(([u,p])=>t.has(u)||r!==void 0&&!r.includes(u)?!1:p.shardMode?.kind!=="global").map(([u])=>u);if(r!==void 0){for(const u of r)if(!s.tables[u])throw new y("INTERNAL",`wipeShard: unknown table: ${u}`)}const f={};let h=0;const{deleteAll:d}=P;if(d===void 0)throw new y("INTERNAL","wipeShard: this writer has no deleteAll");for(const u of l){const p=await d(u,{...e?.chunkSize===void 0?{}:{chunkSize:e.chunkSize},hard:!0});f[u]=p.deleted,h+=p.deleted}return{deleted:h,tables:f}}},vn={db:P,scheduler:Et};return n.enforceRls===!0?To(P,s,(e,t)=>ne(e,t)?.tableName,(e,t)=>Sn(e,t),_):P};export{gi as CDC_LOG_TABLE,Bi as IDEMPOTENCY_TABLE,gr as NotUniqueError,Li as advanceClientWatermark,yi as applyCdcChanges,cn as assertNoExplicitUndefined,ft as assertStorableRowId,or as assertValidClientId,fi as backfillAggregateIndexes,hi as backfillRankIndexes,wi as backfillSearchIndexes,$i as bumpCdcEpoch,Ei as cdcCanVouchFor,mi as cdcForkedError,Si as cdcSeqLeavingRows,_i as cdcTouchesTables,Ri as cdcTrimmedError,Ti as compactCdcDocs,di as createShardCtxDb,vi as cursorBelowRetainedFloor,Fi as migrateClientWatermark,Ii as minCdcReplayableSeq,Ai as minCdcSeq,rn as normalizeIdStructurally,Ci as readCdcChangeKeys,xi as readCdcChanges,bi as readCdcCursor,Mi as readCdcEpoch,qi as readClientWatermark,Pi as readIdempotent,Gi as runShardMigrations,Ki as selectShapeMembers,Ni as selectShapeRows,Ge as stripReservedPatchFields,Di as trimCdcChanges,Ui as trimIdempotent,Oi as writeIdempotent};
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{LunoraError as D}from"@lunora/errors";import{t as P}from"./do-sql-BWrJQAOh.mjs";import{applySelect as J}from"./CURSOR_PREFIX-6offuG6M.mjs";const U=Symbol.for("lunora.relations.fanOutBudget"),ce=e=>({fanOutBudget:e[U],relationBaseWhere:e.relationBaseWhere,relationMask:e.relationMask}),$=(e,t)=>t.select?J(e,t.select,t.with):e,ae=async(e,t,n,i,s)=>{const c=await Promise.all(i.map(async l=>{const d=s?{AND:[{[n]:l},s]}:{[n]:l};return[l,await e(t,d)]}));return new Map(c)},Q=32,B=1e4,Y=(e,t,n)=>{const i=new Map;for(const s of e)for(const c of n(s)){const l=c[t],d=i.get(l);d?d.push(c):i.set(l,[c])}return i},E=(e,t)=>({...e,[U]:t}),Z=(e,t)=>{const n=new Map;for(const[s,c]of e)for(const l of c){const d=n.get(l);d?d.push(s):n.set(l,[s])}const i=new Map;for(const s of t)for(const c of n.get(s._id)??[]){const l=i.get(c);l?l.push(s):i.set(c,[s])}return i},_=(e,t)=>{const n=new Set;for(const i of e){const s=i[t];s!=null&&n.add(s)}return[...n]},fe=async e=>{const{groupedCounter:t,fanOutBudget:n,fetcher:i,parents:s,relationBaseWhere:c,relationMask:l,schema:d,tableName:g,with:A}=e,b=n??{remaining:Q},k=(a,o)=>l?.(a,o)??o;if(s.length===0)return;const v=d.tables[g];if(!v)throw new D("INTERNAL",`unknown table: ${g}`);const j=v.relationMap??{},z=(a,o)=>{const r=u=>d.tables[u]?.shardMode?.kind??"root";return r(a)===r(o)&&r(a)!=="shardBy"},I=a=>{const o=j[a];if(!o)throw new D("INTERNAL",`unknown relation "${a}" on table "${g}"`);return o},x=async(a,o,r)=>{const u=_(s,o.field);if(u.length===0){for(const h of s)h[a]=null;return}const{page:f}=await i(o.table,E({baseWhere:c?.(o.table),relationBaseWhere:c,relationMask:l,where:{[o.references]:{in:u}},with:r.with},b)),p=new Map;for(const h of k(o.table,f))p.set(h[o.references],h);for(const h of s){const m=p.get(h[o.field]);h[a]=m?$([m],r)[0]??null:null}},S=async(a,o,r,u)=>{const{page:f}=await i(a,E({baseWhere:c?.(a),limit:u,orderBy:o.orderBy,relationBaseWhere:c,relationMask:l,where:o.where?{AND:[o.where,r]}:r,with:o.with},b));return f},T=(a,o,r,u,f)=>{for(const p of s){const h=f.get(p[u])??[];p[a]=$(r===void 0?h:h.slice(0,r),o)}},G=async(a,o,r)=>{const u=_(s,o.references);if(u.length===0){for(const w of s)w[a]=[];return}const f=typeof r.limit=="number"?Math.max(0,Math.floor(r.limit)):void 0,p=(w,O)=>S(o.table,r,w,O);if(f===0){for(const w of s)w[a]=[];return}const h=f!==void 0&&u.length<=b.remaining;h&&(b.remaining-=u.length);const m=h?await Promise.all(u.map(async w=>p({[o.field]:w},f))):[await p({[o.field]:{in:u}},void 0)],y=Y(m,o.field,w=>k(o.table,w));T(a,r,f,o.references,y)},W=async a=>{const{from:o,table:r,to:u}=a.through,f=new Map,p=_(s,"_id");if(p.length===0)return f;const h=await S(r,{},{[o]:{in:p}},B+1);if(h.length>B)throw new D("INTERNAL",`loading "${g}" relations through "${r}" read more than ${String(B)} join rows for one page; load fewer ${g} rows at a time`);for(const m of k(r,h)){const y=m[o],w=m[u];if(y==null||w===null||w===void 0)continue;const O=f.get(y);O?O.add(w):f.set(y,new Set([w]))}return f},H=async(a,o,r)=>{const u=typeof r.limit=="number"?Math.max(0,Math.floor(r.limit)):void 0,f=u===0?new Map:await W(o),p=(m,y)=>S(o.table,r,{_id:{in:[...m]}},y);let h=new Map;if(f.size>0&&u!==void 0&&f.size<=b.remaining){b.remaining-=f.size;const m=[...f.keys()],y=await Promise.all([...f.values()].map(async w=>p(w,u)));h=new Map(m.map((w,O)=>[w,k(o.table,y[O]??[])]))}else if(f.size>0){const m=new Set([...f.values()].flatMap(y=>[...y]));h=Z(f,k(o.table,await p(m,void 0)))}T(a,r,u,"_id",h)},K=async(a,o)=>{const r=[...o];if(r.length===0)return new Set;if(z(g,a)){const f=await t(a,"_id",r,c?.(a));return new Set(r.filter(p=>(f.get(p)??0)>0))}const u=await S(a,{},{_id:{in:r}},void 0);return new Set(u.map(f=>f._id))},X=async(a,o)=>{const r=await W(o),u=await K(o.table,new Set([...r.values()].flatMap(f=>[...f])));for(const f of s){const p=f._count??{};p[a]=[...r.get(f._id)??[]].filter(h=>u.has(h)).length,f._count=p}},q=async a=>{for(const o of Object.keys(a)){const r=I(o);if(r.through!==void 0){await X(o,r);continue}const[u,f]=r.kind==="many"?[r.field,r.references]:[r.references,r.field],p=c?.(r.table),h=_(s,f),m=h.length===0?new Map:await t(r.table,u,h,p);for(const y of s){const w=y._count??{},O=y[f];w[o]=O==null?0:m.get(O)??0,y._count=w}}};for(const[a,o]of Object.entries(A)){if(o===void 0||o===!1)continue;if(a==="_count"){await q(o);continue}const r=I(a),u=o===!0?{}:o;r.through===void 0?await(r.kind==="one"?x(a,r,u):G(a,r,u)):await H(a,r,u)}},ee=async(e,t,n)=>{const{deletedId:i,deletedReference:s,findHolders:c,onCascade:l,onRestrict:d,onSetNull:g,tableName:A}=e,b=n.references==="_id"?i:s(n.references);if(b==null)return;const k=await c(t,n.field,b);if(k.length!==0){n.onDelete==="restrict"&&d(`cannot delete "${A}" row: "${t}.${n.field}" still references it`);for(const v of k){const j=v._id;typeof j=="string"&&await(n.onDelete==="cascade"?l(t,j):g(t,j,n.field))}}},le=async e=>{const{schema:t,tableName:n}=e;if(!t.tables[n])throw new D("INTERNAL",`unknown table: ${n}`);for(const[i,s]of Object.entries(t.tables)){const c=s.relationMap;if(c)for(const l of Object.values(c))l.kind!=="one"||l.table!==n||!l.onDelete||await ee(e,i,l)}},L=new WeakMap,C=e=>{const t=L.get(e);if(t!==void 0)return t;const n=e._meta,i=[n?.inner,n?.keyValidator,n?.valueValidator,...n?.members??[],...Object.values(n?.shape??{})],s=e.kind==="from"||i.some(c=>c!==void 0&&C(c));return L.set(e,s),s},V=e=>{const t=Object.getPrototypeOf(e);return t===Object.prototype||t===null},F=e=>e instanceof ArrayBuffer?new Uint8Array(e):ArrayBuffer.isView(e)?new Uint8Array(e.buffer,e.byteOffset,e.byteLength):void 0,R=(e,t)=>{if(Object.is(e,t))return!0;if(e instanceof Date&&t instanceof Date)return e.getTime()===t.getTime();const n=F(e),i=F(t);if(n!==void 0||i!==void 0)return n!==void 0&&i!==void 0&&Object.getPrototypeOf(e)===Object.getPrototypeOf(t)&&n.length===i.length&&n.every((d,g)=>d===i[g]);if(Array.isArray(e)||Array.isArray(t))return Array.isArray(e)&&Array.isArray(t)&&e.length===t.length&&e.every((d,g)=>R(d,t[g]));if(typeof e!="object"||typeof t!="object"||e===null||t===null||!V(e)||!V(t))return!1;const s=e,c=t,l=Object.keys(s);return l.length===Object.keys(c).length&&l.every(d=>d in c&&R(s[d],c[d]))},N=new WeakMap,ue=e=>{if(N.has(e))return N.get(e);const t=Object.fromEntries(Object.entries(e.shape).filter(([,i])=>C(i))),n=Object.keys(t).length>0?{...e,shape:t}:void 0;return N.set(e,n),n},te=e=>{let t;return(n,i)=>e===void 0?!1:(t??=e()??{},n in t&&R(i,t[n]))},ne=(e,t)=>{const n=new Set(Object.keys(t).filter(i=>t[i]!==void 0));for(const[i,s]of P(e))s.serverDefault&&n.delete(i);return n},oe=(e,t,n,i,s)=>n.trusted===!0||i!==void 0&&!i.has(e)||s(e,t),M=e=>typeof e!="object"||e===null?e:e instanceof Date?new Date(e):e instanceof ArrayBuffer||ArrayBuffer.isView(e)?structuredClone(e):Array.isArray(e)?e.map(t=>M(t)):e instanceof Map?new Map([...e].map(([t,n])=>[M(t),M(n)])):e instanceof Set?new Set([...e].map(t=>M(t))):V(e)?Object.fromEntries(Object.entries(e).map(([t,n])=>[t,M(n)])):e,de=(e,t,n)=>{const i={...t};for(const[s,c]of P(e)){if(c.serverDefault){i[s]=c.serverDefault({auth:n});continue}if(i[s]===void 0){if(c.defaultFn)i[s]=c.defaultFn();else if("defaultValue"in c){const{defaultValue:l}=c;i[s]=M(l)}}}return i},he=(e,t,n={})=>{let i;const s=te(n.previous),c=n.only??(n.supplied===void 0?void 0:ne(e,n.supplied));for(const[l,d]of Object.entries(e.shape)){if(!(l in t)||typeof d.parse!="function")continue;const g=C(d);if(g&&oe(l,t[l],n,c,s)||n.tolerateStoredNull===!0&&t[l]===null&&d.kind==="optional")continue;const A=d.parse(t[l]);g&&(i??={...t},i[l]=A)}return i??t};export{B as MAX_LINK_ROWS,de as applyInsertDefaults,le as applyOnDelete,_ as distinctValues,ae as fanOutScalarCounts,ce as relationHooks,fe as resolveWith,he as runRowValidators,ue as transformOnlyDefinition};
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{sql as t}from"drizzle-orm";import{compareStrings as a,encodeAggregateKey as T}from"./aggregateTableName-B_CtIQCS.mjs";import{runDrizzle as r}from"./runDrizzle-RC09zZrh.mjs";import{sqliteInList as f}from"./WORKERD_SQLITE_LIMITS-B_4w7tzY.mjs";const n="__lunora_companion_state",g=1,c=1,E=i=>i?T(Object.keys(i),i):"",$=(i,e)=>JSON.stringify([g,(i.by??[]).toSorted(a),i.field??"",i.op,E(i.where),e??""]),d=(i,e)=>JSON.stringify([c,(i.partitionBy??[]).toSorted(a),i.sortBy.map(o=>o.field),E(i.where),e??""]),s=i=>{r(i,t`CREATE TABLE IF NOT EXISTS ${t.identifier(n)} (${t.identifier("companion")} TEXT PRIMARY KEY, ${t.identifier("signature")} TEXT NOT NULL)`)},u=(i,e)=>{s(i),r(i,e.length===0?t`DELETE FROM ${t.identifier(n)}`:t`DELETE FROM ${t.identifier(n)} WHERE ${f(t.raw('"companion"'),e,!0)}`)},R=(i,e)=>r(i,t`SELECT ${t.identifier("signature")} FROM ${t.identifier(n)} WHERE ${t.identifier("companion")} = ${e}`).toArray()[0]?.signature,A=(i,e,o)=>{r(i,t`INSERT INTO ${t.identifier(n)} (${t.identifier("companion")}, ${t.identifier("signature")}) VALUES (${e}, ${o}) ON CONFLICT (${t.identifier("companion")}) DO UPDATE SET ${t.identifier("signature")} = excluded.${t.identifier("signature")}`)},N=i=>{s(i),r(i,t`DELETE FROM ${t.identifier(n)}`)};export{$ as aggregateSignature,N as clearCompanionSignatures,u as migrateCompanionState,d as rankSignature,R as readCompanionSignature,A as writeCompanionSignature};
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{N as co,S as ao,d as fo,e as lo,a as uo}from"./fts-companion-CA8mLJWq.mjs";import{sql as o}from"drizzle-orm";import{r as z}from"./json-field-path-DeJW4U9z.mjs";import{matchesStaticWhere as Q,aggregateSqlFunction as $o}from"./AGGREGATE_SQL_FUNCTION-C_ZipS9R.mjs";import{aggregateTableName as H,foldAggregateTally as X,encodeAggregateKey as k,coerceAggregateNumber as U}from"./aggregateTableName-B_CtIQCS.mjs";import{aggregateSignature as Eo,readCompanionSignature as Y,rankSignature as go,writeCompanionSignature as J}from"./clearCompanionSignatures-3MlVqWZD.mjs";import{runAll as po,runDrizzle as g}from"./runDrizzle-RC09zZrh.mjs";import{i as mo,g as _o,a as O,b as T,A as _,c as j,D as Z,r as N,e as P}from"./do-sql-BWrJQAOh.mjs";import{WORKERD_SQLITE_LIMITS as yo,param as ho}from"./WORKERD_SQLITE_LIMITS-B_4w7tzY.mjs";import{encodeGeohash as So,GEO_DEFAULT_PRECISION as To}from"./GEO_DEFAULT_PRECISION-CqpQZ-J_.mjs";import{isLiveForCompanion as x}from"./CURSOR_PREFIX-6offuG6M.mjs";import{rankTableName as B,matchesRankStaticWhere as oo,sortColumnName as Ro,encodePartitionKey as Ao}from"./RANK_TIEBREAK-D3ye2GsL.mjs";import{mayHoldProjectedValue as wo}from"./BIGINT_KEY_DIGITS-DE6yshOt.mjs";import{serializeSqlValue as eo}from"./serializeSqlValue-DeoBMpZ2.mjs";const Co=(s,l,r)=>[...s.partitionBy??[],...s.sortBy.map(f=>f.field),...s.where?Object.keys(s.where):[]].every(f=>z(l,f)===z(r,f)),no=s=>o.join(["__id__","__partition__",...s.sortBy.map((l,r)=>Ro(r))].map(l=>o.identifier(l)),o`, `),ro=(s,l,r,E,f,a)=>{const t=Ao(r.partitionBy??[],a),R=r.sortBy.map(A=>eo(a[A.field]??null)),y=o.join([f,t,...R].map(A=>ho(A)),o`, `);g(s,o`INSERT INTO ${o.identifier(l)} (${E}) VALUES (${y})`)},to=(s,l,r,E)=>{const f=[];for(const a of g(s,o`SELECT id, _creationTime, ${o.identifier(Z)} FROM ${o.identifier(l)}`)){const t=N(a);t&&x(t,r)&&E(t)&&f.push(t)}return f},vo=(s,l,r,E,f)=>{const a=H(l,r.name),t=r.by??[],R=new Map;for(const w of to(s,l,E,L=>!r.where||Q(L,r.where)))X(R,k(t,w),r,w);g(s,o`DELETE FROM ${o.identifier(a)}`);const y=Math.floor(yo.boundParams/3),A=[...R];for(let w=0;w<A.length;w+=y){const L=A.slice(w,w+y),G=o.join(L.map(([b,D])=>o`(${b}, ${D.value}, ${D.count})`),o`, `);g(s,o`INSERT INTO ${o.identifier(a)} (${O}, ${T}, ${_}) VALUES ${G}`)}J(s,a,f)},Io=(s,l,r,E)=>{const f=Eo(r,E);Y(s,H(l,r.name))!==f&&vo(s,l,r,E,f)},ko=(s,l,r,E,f)=>{const a=B(l,r.name),t=no(r),R=to(s,l,E,y=>!r.where||oo(y,r.where));g(s,o`DELETE FROM ${o.identifier(a)}`);for(const y of R)ro(s,a,r,t,y._id,y);J(s,a,f)},Fo=(s,l,r,E)=>{const f=go(r,E);Y(s,B(l,r.name))!==f&&ko(s,l,r,E,f)},Oo=(s,l,r,E,f,a)=>{if(f&&a&&Co(r,f,a))return;const t=B(l,r.name);f&&g(s,o`DELETE FROM ${o.identifier(t)} WHERE ${o.identifier("__id__")} = ${E}`),!(!a||r.where&&!oo(a,r.where))&&ro(s,t,r,no(r),E,a)},Qo=s=>{const{broadcast:l,indexKeysFor:r,invalidateCache:E,recordCdc:f,schema:a,sql:t}=s,R=new Set,y=e=>a.tables[e]?.softDeleteMode?.field,A=(e,n)=>{const c=H(e,n.name);R.has(c)||(Io(t,e,n,y(e)),R.add(c))},w=(e,n,c)=>{const p=n.by??[],d=n.field??"",$=[],h=(i,u)=>{const m=eo(u);m===null?$.push(o`${P(i)} IS NULL`):$.push(o`${P(i)} = ${m}`)};for(const i of p)h(i,c[i]??null);const C=y(e);C!==void 0&&h(C,null);for(const[i,u]of Object.entries(n.where??{}))h(i,u!==null&&typeof u=="object"&&!Array.isArray(u)?u.eq:u);const F=$.length>0?o` WHERE ${o.join($,o` AND `)}`:o``,M=a.tables[e]?.shape[d];if(M&&wo(M)){const i=g(t,o`SELECT id, _creationTime, ${o.identifier(Z)} FROM ${o.identifier(e)}${F}`).toArray(),u=new Map;for(const m of i){const I=N(m);I&&X(u,"",n,I)}return{value:u.get("")?.value??null}}const W=$o(n.op),S=P(d);return{value:g(t,o`SELECT ${o.raw(W)}(${S}) AS value FROM ${o.identifier(e)}${F}`).one().value??null}},L=(e,n,c,p)=>{const d=H(e,n.name),{op:$}=n,h=n.field??"",C=i=>{g(t,o`DELETE FROM ${o.identifier(d)} WHERE ${O} = ${i} AND ${_} <= 0`)},F=y(e),M=i=>!n.where||Q(i,n.where),W=i=>x(i,F)&&M(i);p!==void 0&&$!=="count"&&M(p)&&U(p[h]);const S=c&&W(c)?c:void 0,v=p&&W(p)?p:void 0;if(!(!S&&!v)){if($==="count"){for(const[i,u]of[[S,-1],[v,1]]){if(!i)continue;const m=k(n.by??[],i);g(t,j(d,m,u,u,o`${T} = ${T} + excluded.${T}, ${_} = ${_} + excluded.${_}`))}S&&C(k(n.by??[],S));return}if($==="sum"||$==="avg"){for(const[i,u]of[[S,-1],[v,1]]){if(!i)continue;const m=U(i[h]);if(m===void 0)continue;const I=k(n.by??[],i);g(t,j(d,I,u*m,u,o`${T} = COALESCE(${T}, 0) + excluded.${T}, ${_} = ${_} + excluded.${_}`))}S&&C(k(n.by??[],S));return}if(S){const i=k(n.by??[],S),u=U(S[h]),m=g(t,o`SELECT ${T} AS value, ${_} AS count FROM ${o.identifier(d)} WHERE ${O} = ${i}`).toArray()[0],I=(m?.count??0)-1;if(I<=0)g(t,o`DELETE FROM ${o.identifier(d)} WHERE ${O} = ${i}`);else if(m&&u!==void 0&&m.value!==null&&u===m.value){const io=w(e,n,S);g(t,o`UPDATE ${o.identifier(d)} SET ${T} = ${io.value}, ${_} = ${I} WHERE ${O} = ${i}`)}else g(t,o`UPDATE ${o.identifier(d)} SET ${_} = ${_} - 1 WHERE ${O} = ${i}`)}if(v){const i=k(n.by??[],v),u=U(v[h]);if(u===void 0)g(t,j(d,i,null,1,o`${_} = ${_} + 1`));else{const m=$==="min"?"MIN":"MAX";g(t,j(d,i,u,1,o`${T} = ${o.raw(m)}(COALESCE(${T}, excluded.${T}), excluded.${T}), ${_} = ${_} + 1`))}}}},G=e=>{for(const n of a.tables[e]?.aggregateIndexes??[])A(e,n)},b=(e,n,c)=>{for(const p of a.tables[e]?.aggregateIndexes??[])L(e,p,n,c)},D=(e,n)=>{const c=B(e,n.name);R.has(c)||(Fo(t,e,n,y(e)),R.add(c))},so=e=>{for(const n of a.tables[e]?.rankIndexes??[])D(e,n)},V=(e,n,c,p)=>{for(const d of a.tables[e]?.rankIndexes??[])Oo(t,e,d,n,c,p)},K=(e,n,c,p)=>{const d=a.tables[e]?.searchIndexes??[];if(!(d.length===0||!mo(t)))for(const $ of d){if(co(p,c,$))continue;const h=ao(e,$.name);po(t,c?fo(h,n,lo(c,$)):uo(h,n))}},q=(e,n,c)=>{for(const p of a.tables[e]?.geoIndexes??[]){const d=_o(e,p.name);g(t,o`DELETE FROM ${o.identifier(d)} WHERE ${o.identifier("__id__")} = ${n}`);const $=c?.[p.field];if($!==null&&typeof $=="object"&&typeof $.lat=="number"&&typeof $.lng=="number"){const{lat:h,lng:C}=$,F=So({lat:h,lng:C},p.precision??To);g(t,o`INSERT INTO ${o.identifier(d)} (${o.identifier("__id__")}, ${o.identifier("__geohash__")}, ${o.identifier("__lat__")}, ${o.identifier("__lng__")}) VALUES (${n}, ${F}, ${h}, ${C})`)}}};return{ensureBackfilledForTable:G,ensureBackfilledIndex:A,ensureRankBackfilled:D,ensureRankBackfilledForTable:so,syncAggregates:b,syncCompanionsForInsert:(e,n,c)=>{K(e,n,c),q(e,n,c),b(e,void 0,c),V(e,n,void 0,c),E(e,n,c),f(e,n,"insert",c),l({indexKeys:r(e,c),key:n,op:"insert",row:c,table:e})},syncGeo:q,syncRanks:V,syncSearch:K}};export{Qo as createCompanionSync,Io as ensureAggregateCompanion,Fo as ensureRankCompanion};
|
|
@@ -1,5 +0,0 @@
|
|
|
1
|
-
import{LunoraError as U}from"@lunora/errors";import{f as M,S as X}from"./fts-companion-CA8mLJWq.mjs";import{sql as t}from"drizzle-orm";import{aggregateTableName as h}from"./aggregateTableName-B_CtIQCS.mjs";import{backfillSearchIndexesForTable as y}from"./backfillAggregateIndexes-DSplGrR_.mjs";import{migrateCdcLog as b,migrateCdcMeta as k}from"./CDC_LOG_TABLE-Dgwxv7yf.mjs";import{migrateClientWatermark as w}from"./CLIENT_WATERMARK_TABLE-De7z_OHV.mjs";import{migrateCommitSeq as B}from"./COMMIT_SEQ_FIELD-Da1DjGqo.mjs";import{migrateCompanionState as G}from"./clearCompanionSignatures-3MlVqWZD.mjs";import{migrateGlobalShapeSnapshot as P}from"./GLOBAL_SHAPE_SNAPSHOT_TABLE-Bb6-aZuH.mjs";import{migrateIdempotency as Y}from"./IDEMPOTENCY_TABLE-COrgeP3O.mjs";import{m as v}from"./ctx-db-relay-shapes-DV0VO4HG.mjs";import{migrateScheduleOutbox as j}from"./SCHEDULE_OUTBOX_TABLE-DcZI7Yhl.mjs";import{m as W}from"./ctx-db-search-state-FjgzTFok.mjs";import{migrateShapePokeCursor as H}from"./SHAPE_POKE_CURSOR_TABLE-BGvY3sFI.mjs";import{runDrizzle as d,runAll as K}from"./runDrizzle-RC09zZrh.mjs";import{D as V,d as I,e as g,t as z,i as Z,g as J,a as Q,b as q,A as p}from"./do-sql-BWrJQAOh.mjs";import{renderSql as R}from"./WORKERD_SQLITE_LIMITS-B_4w7tzY.mjs";import{migrateDurableStreams as ee}from"./appendStreamChunk-BZYgGE9Y.mjs";import{rankTableName as N,sortColumnName as te}from"./RANK_TIEBREAK-D3ye2GsL.mjs";import{migrateReactorState as re}from"./REACTOR_STATE_TABLE-D2Mn204f.mjs";import{recordSchemaVersion as ne}from"./SCHEMA_HISTORY_MAX_VERSIONS-CEwFjj-O.mjs";import{ttlIndexColumns as oe}from"./nextTtlExpiry-DhKO_OpO.mjs";const u=t`_creationTime, id`,x="__by_creation",ie="__ttl",ae=`, ${R("sqlite",u).sql})`,l="__lunora_framework_indexes",T=e=>e.replaceAll(/[A-Z]/gu,r=>r.toLowerCase());class D extends U{}const $=(e,r,n,a,i,o)=>{const s=t.join(i.map(m=>t`${m} IS NOT NULL`),t` AND `);if(d(e,t`SELECT 1 FROM ${t.identifier(n)} WHERE ${s} GROUP BY ${a} HAVING COUNT(*) > 1 LIMIT 1`).toArray().length>0)throw new D("INTERNAL",`unique index "${r}" on "${n}" ${o}: existing rows are duplicates under it. De-duplicate the table with a data migration first; the previous index is left in place.`)},L=(e,r,n,a,i,o)=>{const c=d(e,t`SELECT sql FROM sqlite_master WHERE type = 'index' AND name = ${r} COLLATE NOCASE AND tbl_name = ${n} COLLATE NOCASE`).toArray()[0]?.sql;if(c==null)return;const m=f=>{const A=f.indexOf("(");return A===-1?void 0:f.slice(A,f.lastIndexOf(")")+1)},E=m(R("sqlite",I(r,n,a,i)).sql),_=m(c);E===void 0||_===void 0||E===_||(i&&$(e,r,n,a,o,"cannot be re-created with its new column list"),d(e,t`DROP INDEX IF EXISTS ${t.identifier(r)}`))},se=(e,r,n)=>d(e,t`SELECT 1 FROM sqlite_master WHERE type = 'index' AND name = ${r} COLLATE NOCASE AND tbl_name = ${n} COLLATE NOCASE LIMIT 1`).toArray().length>0,O=(e,r,n,a,i,o)=>{i&&!se(e,r,n)&&$(e,r,n,a,o,"cannot be created"),d(e,I(r,n,a,i))},C=(e,r)=>{try{r()}catch(n){if(e===void 0||!(n instanceof D))throw n;e.push(n.message)}},de=(e,r,n)=>T(r).startsWith(`${T(e)}_`)&&T(r)!==T(`${e}${x}`)&&n!==null&&(n.includes("json_extract(")||n.trimEnd().endsWith(ae)),S=(e,r,n)=>{d(e,t`INSERT OR IGNORE INTO ${t.identifier(l)} (name, table_name) VALUES (${r}, ${n})`)},ce=(e,r)=>{const n=d(e,t`SELECT 1 FROM sqlite_master WHERE type = 'table' AND name = ${l} COLLATE NOCASE`).toArray().length>0;if(d(e,t`CREATE TABLE IF NOT EXISTS ${t.identifier(l)} (name TEXT PRIMARY KEY COLLATE NOCASE, table_name TEXT NOT NULL)`),!n)for(const a of r){const i=d(e,t`SELECT name, sql FROM sqlite_master WHERE type = 'index' AND tbl_name = ${a} COLLATE NOCASE AND sql IS NOT NULL`).toArray();for(const{name:o,sql:s}of i)de(a,o,s)&&S(e,o,a)}},me=(e,r,n)=>{const a=new Set([...n].map(o=>T(o))),i=d(e,t`SELECT "l"."name" FROM ${t.identifier(l)} AS "l" WHERE "l"."table_name" = ${r} COLLATE NOCASE`).toArray();for(const{name:o}of i)a.has(T(o))||(d(e,t`DROP INDEX IF EXISTS ${t.identifier(o)}`),d(e,t`DELETE FROM ${t.identifier(l)} WHERE ${t.identifier(l)}."name" = ${o}`))},fe=(e,r,n,a)=>{const i=`${r}${ie}`,o=new Set([...a].map(c=>T(c)));if(n.ttlPolicy===void 0||o.has(T(i)))return;const s=oe(n.ttlPolicy.field,n.softDeleteMode?.field);a.add(i);try{L(e,i,r,s,!1,[]),d(e,I(i,r,s,!1)),S(e,i,r)}catch{}},Ee=(e,r,n,a)=>{const i=new Set;for(const o of n.indexes){const s=`${r}_${o.name}`,c=o.unique??!1,m=o.fields.map(f=>g(f)),E=t.join(m,t`, `),_=c?E:t`${E}, ${u}`;i.add(s),C(a,()=>{L(e,s,r,_,c,m),O(e,s,r,_,c,m),S(e,s,r)})}for(const[o,s]of z(n)){if(!s.unique)continue;const c=g(o),m=`${r}_unique_${o}`;i.add(m),C(a,()=>{L(e,m,r,c,!0,[c]),O(e,m,r,c,!0,[c]),S(e,m,r)})}fe(e,r,n,i),me(e,r,i)},_e=(e,r,n)=>{if(!(!n.searchIndexes||n.searchIndexes.length===0||!Z(e))){for(const a of n.searchIndexes)K(e,M(X(r,a.name)));y(e,r,n)}},Te=(e,r,n)=>{if(n.geoIndexes)for(const a of n.geoIndexes){const i=J(r,a.name);d(e,t`CREATE TABLE IF NOT EXISTS ${t.identifier(i)} (${t.identifier("__id__")} TEXT PRIMARY KEY, ${t.identifier("__geohash__")} TEXT NOT NULL, ${t.identifier("__lat__")} REAL NOT NULL, ${t.identifier("__lng__")} REAL NOT NULL)`);const o=`${r}__geo_${a.name}__btree`;d(e,I(o,i,t`${t.identifier("__geohash__")} ASC, ${t.identifier("__id__")} ASC`,!1))}},Ae=(e,r,n)=>{if(n.aggregateIndexes)for(const a of n.aggregateIndexes){const i=h(r,a.name);d(e,t`CREATE TABLE IF NOT EXISTS ${t.identifier(i)} (${Q} TEXT PRIMARY KEY, ${q} REAL, ${p} INTEGER NOT NULL DEFAULT 0)`),d(e,t`PRAGMA table_info(${t.identifier(i)})`).toArray().some(s=>s.name==="__count__")||d(e,t`ALTER TABLE ${t.identifier(i)} ADD COLUMN ${p} INTEGER NOT NULL DEFAULT 0`)}},le=(e,r,n)=>{const a=d(e,t`PRAGMA table_info(${t.identifier(r)})`).toArray().map(i=>i.name).filter(i=>i.startsWith("__sort_k"));a.length>0&&(a.length!==n.length||a.some((i,o)=>i!==n[o]))&&d(e,t`DROP TABLE ${t.identifier(r)}`)},Ie=(e,r,n)=>{if(n.rankIndexes)for(const a of n.rankIndexes){const i=N(r,a.name),o=a.sortBy.map((f,A)=>te(A)),s=o.map(f=>t`${t.identifier(f)} BLOB`),c=s.length>0?t`, ${t.join(s,t`, `)}`:t``;le(e,i,o),d(e,t`CREATE TABLE IF NOT EXISTS ${t.identifier(i)} (${t.identifier("__id__")} TEXT PRIMARY KEY, ${t.identifier("__partition__")} TEXT NOT NULL${c})`);const m=[t`${t.identifier("__partition__")} ASC`];for(const[f,A]of o.entries()){const F=a.sortBy[f]?.direction;m.push(t`${t.identifier(A)} ${t.raw(F==="desc"?"DESC":"ASC")}`)}m.push(t`${t.identifier("__id__")} ASC`);const E=`${r}__rank_${a.name}__btree`,_=t.join(m,t`, `);L(e,E,i,_,!1,[]),d(e,I(E,i,_,!1))}},Pe=(e,r,n={})=>{const a=n.deferBlockedUniqueIndexes?[]:void 0;n.schemaSnapshot!==void 0&&ne(e,n.schemaSnapshot.hash,n.schemaSnapshot.json),W(e),ce(e,Object.entries(r.tables).filter(([,o])=>o.shardMode?.kind!=="global").map(([o])=>o));const i=[];for(const[o,s]of Object.entries(r.tables))s.shardMode?.kind!=="global"&&(d(e,t`CREATE TABLE IF NOT EXISTS ${t.identifier(o)} (
|
|
2
|
-
id TEXT PRIMARY KEY,
|
|
3
|
-
_creationTime REAL NOT NULL,
|
|
4
|
-
${t.identifier(V)} TEXT NOT NULL
|
|
5
|
-
)`),d(e,I(`${o}${x}`,o,u,!1)),Ee(e,o,s,a),_e(e,o,s),Te(e,o,s),Ae(e,o,s),Ie(e,o,s),i.push(...(s.aggregateIndexes??[]).map(c=>h(o,c.name)),...(s.rankIndexes??[]).map(c=>N(o,c.name))));return G(e,i),n.cdc&&(b(e,{rowHistoryIndex:Object.values(r.tables).some(o=>o.dropStalePatchesMode===!0)}),k(e),w(e),H(e),v(e)),Object.values(r.tables).some(o=>o.commitOrderedMode===!0)&&B(e),re(e),Y(e),j(e),P(e),ee(e),a??[]};export{Pe as runShardMigrations};
|