@lunora/shard-engine 1.0.0-alpha.190 → 1.0.0-alpha.191
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 +9 -1
- package/dist/index.d.ts +9 -1
- package/dist/index.mjs +1 -1
- package/dist/packem_shared/DEFAULT_MAX_RELATION_KEYS-BBtZ_jRj.mjs +1 -0
- package/dist/packem_shared/NotUniqueError-vJf9tj6U.mjs +1 -0
- package/dist/packem_shared/{defineEngineContractSuite-CF6x3w-O.mjs → defineEngineContractSuite-Bap9eB0W.mjs} +1 -1
- package/package.json +1 -1
- package/dist/packem_shared/DEFAULT_MAX_RELATION_KEYS-DfrMi_eE.mjs +0 -1
- package/dist/packem_shared/NotUniqueError-DGCd3Cph.mjs +0 -1
|
@@ -1 +1 @@
|
|
|
1
|
-
import{defineEngineContractSuite as t}from"../packem_shared/defineEngineContractSuite-
|
|
1
|
+
import{defineEngineContractSuite as t}from"../packem_shared/defineEngineContractSuite-Bap9eB0W.mjs";export{t as defineEngineContractSuite};
|
package/dist/index.d.mts
CHANGED
|
@@ -389,6 +389,7 @@ interface QueryArgs {
|
|
|
389
389
|
baseWhere?: WhereInput;
|
|
390
390
|
consistency?: "primary";
|
|
391
391
|
cursor?: null | string;
|
|
392
|
+
endCursor?: null | string;
|
|
392
393
|
includeDeleted?: boolean;
|
|
393
394
|
limit?: number;
|
|
394
395
|
omitContinueCursor?: boolean;
|
|
@@ -417,6 +418,7 @@ interface QueryPage {
|
|
|
417
418
|
isDone: boolean;
|
|
418
419
|
page: Record<string, unknown>[];
|
|
419
420
|
splitCursor?: null | string;
|
|
421
|
+
splitRequired?: boolean;
|
|
420
422
|
}
|
|
421
423
|
interface RelationEdge {
|
|
422
424
|
readonly array: boolean;
|
|
@@ -2237,6 +2239,12 @@ declare const composeReadPredicate: (definition: TableDefinitionLike, args: Quer
|
|
|
2237
2239
|
orderKeys: OrderKey[];
|
|
2238
2240
|
predicate: WhereInput | undefined;
|
|
2239
2241
|
}>;
|
|
2242
|
+
declare const findManyPage: (documents: Record<string, unknown>[], read: {
|
|
2243
|
+
endCursor?: null | string;
|
|
2244
|
+
limit: number | undefined;
|
|
2245
|
+
omitContinueCursor?: boolean;
|
|
2246
|
+
orderKeys: OrderKey[];
|
|
2247
|
+
}) => QueryPage;
|
|
2240
2248
|
declare const assertShapeShardable: (effectiveWhere: WhereInput | undefined, schema: ResolveContext["schema"], table: string) => void;
|
|
2241
2249
|
declare const relationHooks: (args: Pick<QueryArgs, "relationBaseWhere" | "relationMask">) => Pick<QueryArgs, "relationBaseWhere" | "relationMask"> & Pick<ResolveWithOptions, "fanOutBudget">;
|
|
2242
2250
|
declare const fanOutScalarCounts: (counter: (tableName: string, where?: WhereInput) => Promise<number>, tableName: string, whereField: string, values: unknown[], policyWhere: WhereInput | undefined) => Promise<Map<unknown, number>>;
|
|
@@ -2806,4 +2814,4 @@ declare const backfillVectorIndexes: (sql: SqlExec, targets: ReadonlyArray<Vecto
|
|
|
2806
2814
|
ordered: OrderedAfterWrites;
|
|
2807
2815
|
restart?: boolean;
|
|
2808
2816
|
}) => Promise<VectorBackfillProgress>;
|
|
2809
|
-
export { ADMIN_FUNCTIONS, ADMIN_FUNCTION_PREFIX, ADMIN_TOKEN_TABLE, AGGREGATE_SQL_FUNCTION, AGG_COUNT, AGG_KEY, AGG_VALUE, AUDIT_LOG_TABLE, type AdminTokenSummary, type AdvisorProcedure, 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 ImportConflictMode, type ImportError, type ImportRow, 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 ScheduleOutboxEntry, 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 TransactionLimitKind, type TransactionLimitWarning, 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, adminTokenExists, 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, createAdminTokenRecord, 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, dropScheduleOutbox, 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, hasScheduleOutboxEntry, hasTrigger, haversineMeters, importShardRows, indexKeysForRow, isDevEnvironment, isFtsAvailable, isInternalTableName, isLossyBody, isMemoryTable, isPushableWhere, isRelationPredicate, isSoftDeleted, isSourceDue, isTtlExpired, isVacuousFilterClause, jsonPath, jsonPathSql, keysTouchRanges, liftSourceId, lintReadonlySql, listAdminTokens, 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, readDueScheduleOutboxEntry, readExternalSourceBaseline, readGlobalShapeSnapshot, readIdempotent, readMigrationStatus, readPatchField, readQueueMessageById, readQueueMessages, readReactorState, readScheduleOutbox, readScheduleOutboxState, readSchemaHistory, readSchemaVersion, readSearchBackfillState, readShapePokeCursor, readStreamChunks, readStreamRun, readTablePage, recordCapturedMail, recordChangedKeys, recordFanoutPass, recordGlobalPollPass, recordQueueMessages, recordScheduleOutbox, recordSchemaVersion, recordShapeProbePass, relationHooks, relayCountFor, renderSql, reprojectableFields, reprojectionMigrationId, reprojectionTables, requeueScheduleOutbox, resolvePatch, resolveRankPartition, resolveRankSeekTuple, resolveRelationPredicates, resolveWith, revokeAdminTokenRecord, 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, verifyAdminTokenDigest, verifySiblingBody, whereFilter, whereOfFilter, writeCdcArchivedThrough, writeGlobalShapeSnapshot, writeIdempotent, writeReactorState, writeSearchBackfillState, writeShapePokeCursor, writeShapePokeCursors, writeTouchesMemo };
|
|
2817
|
+
export { ADMIN_FUNCTIONS, ADMIN_FUNCTION_PREFIX, ADMIN_TOKEN_TABLE, AGGREGATE_SQL_FUNCTION, AGG_COUNT, AGG_KEY, AGG_VALUE, AUDIT_LOG_TABLE, type AdminTokenSummary, type AdvisorProcedure, 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 ImportConflictMode, type ImportError, type ImportRow, 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 ScheduleOutboxEntry, 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 TransactionLimitKind, type TransactionLimitWarning, 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, adminTokenExists, 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, createAdminTokenRecord, 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, dropScheduleOutbox, encodeAggregateKey, encodeCursor, encodeGeohash, encodePartitionKey, encodeRowsPatch, ensureAuditTable, ensureMailTable, envOptionalPositiveInt, envPositiveInt, equalityPinnedFields, exportShardRows, facetColumn, fanOutScalarCounts, findManyPage, findRelated, findStorageReferences, finishStreamRun, float64SqlKey, foldAggregateTally, forgetScheduleOutbox, ftsCompanionDdl, ftsPurgeDocument, ftsRowidMapName, ftsUnmappedPage, ftsWriteDocument, gateReplicaDispatch, geoTableName, globalShapeReadKey, groupUnmappedRows, guardWriter, handleReplicaControl, hasScheduleOutboxEntry, hasTrigger, haversineMeters, importShardRows, indexKeysForRow, isDevEnvironment, isFtsAvailable, isInternalTableName, isLossyBody, isMemoryTable, isPushableWhere, isRelationPredicate, isSoftDeleted, isSourceDue, isTtlExpired, isVacuousFilterClause, jsonPath, jsonPathSql, keysTouchRanges, liftSourceId, lintReadonlySql, listAdminTokens, 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, readDueScheduleOutboxEntry, readExternalSourceBaseline, readGlobalShapeSnapshot, readIdempotent, readMigrationStatus, readPatchField, readQueueMessageById, readQueueMessages, readReactorState, readScheduleOutbox, readScheduleOutboxState, readSchemaHistory, readSchemaVersion, readSearchBackfillState, readShapePokeCursor, readStreamChunks, readStreamRun, readTablePage, recordCapturedMail, recordChangedKeys, recordFanoutPass, recordGlobalPollPass, recordQueueMessages, recordScheduleOutbox, recordSchemaVersion, recordShapeProbePass, relationHooks, relayCountFor, renderSql, reprojectableFields, reprojectionMigrationId, reprojectionTables, requeueScheduleOutbox, resolvePatch, resolveRankPartition, resolveRankSeekTuple, resolveRelationPredicates, resolveWith, revokeAdminTokenRecord, 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, verifyAdminTokenDigest, verifySiblingBody, whereFilter, whereOfFilter, writeCdcArchivedThrough, writeGlobalShapeSnapshot, writeIdempotent, writeReactorState, writeSearchBackfillState, writeShapePokeCursor, writeShapePokeCursors, writeTouchesMemo };
|
package/dist/index.d.ts
CHANGED
|
@@ -389,6 +389,7 @@ interface QueryArgs {
|
|
|
389
389
|
baseWhere?: WhereInput;
|
|
390
390
|
consistency?: "primary";
|
|
391
391
|
cursor?: null | string;
|
|
392
|
+
endCursor?: null | string;
|
|
392
393
|
includeDeleted?: boolean;
|
|
393
394
|
limit?: number;
|
|
394
395
|
omitContinueCursor?: boolean;
|
|
@@ -417,6 +418,7 @@ interface QueryPage {
|
|
|
417
418
|
isDone: boolean;
|
|
418
419
|
page: Record<string, unknown>[];
|
|
419
420
|
splitCursor?: null | string;
|
|
421
|
+
splitRequired?: boolean;
|
|
420
422
|
}
|
|
421
423
|
interface RelationEdge {
|
|
422
424
|
readonly array: boolean;
|
|
@@ -2237,6 +2239,12 @@ declare const composeReadPredicate: (definition: TableDefinitionLike, args: Quer
|
|
|
2237
2239
|
orderKeys: OrderKey[];
|
|
2238
2240
|
predicate: WhereInput | undefined;
|
|
2239
2241
|
}>;
|
|
2242
|
+
declare const findManyPage: (documents: Record<string, unknown>[], read: {
|
|
2243
|
+
endCursor?: null | string;
|
|
2244
|
+
limit: number | undefined;
|
|
2245
|
+
omitContinueCursor?: boolean;
|
|
2246
|
+
orderKeys: OrderKey[];
|
|
2247
|
+
}) => QueryPage;
|
|
2240
2248
|
declare const assertShapeShardable: (effectiveWhere: WhereInput | undefined, schema: ResolveContext["schema"], table: string) => void;
|
|
2241
2249
|
declare const relationHooks: (args: Pick<QueryArgs, "relationBaseWhere" | "relationMask">) => Pick<QueryArgs, "relationBaseWhere" | "relationMask"> & Pick<ResolveWithOptions, "fanOutBudget">;
|
|
2242
2250
|
declare const fanOutScalarCounts: (counter: (tableName: string, where?: WhereInput) => Promise<number>, tableName: string, whereField: string, values: unknown[], policyWhere: WhereInput | undefined) => Promise<Map<unknown, number>>;
|
|
@@ -2806,4 +2814,4 @@ declare const backfillVectorIndexes: (sql: SqlExec, targets: ReadonlyArray<Vecto
|
|
|
2806
2814
|
ordered: OrderedAfterWrites;
|
|
2807
2815
|
restart?: boolean;
|
|
2808
2816
|
}) => Promise<VectorBackfillProgress>;
|
|
2809
|
-
export { ADMIN_FUNCTIONS, ADMIN_FUNCTION_PREFIX, ADMIN_TOKEN_TABLE, AGGREGATE_SQL_FUNCTION, AGG_COUNT, AGG_KEY, AGG_VALUE, AUDIT_LOG_TABLE, type AdminTokenSummary, type AdvisorProcedure, 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 ImportConflictMode, type ImportError, type ImportRow, 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 ScheduleOutboxEntry, 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 TransactionLimitKind, type TransactionLimitWarning, 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, adminTokenExists, 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, createAdminTokenRecord, 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, dropScheduleOutbox, 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, hasScheduleOutboxEntry, hasTrigger, haversineMeters, importShardRows, indexKeysForRow, isDevEnvironment, isFtsAvailable, isInternalTableName, isLossyBody, isMemoryTable, isPushableWhere, isRelationPredicate, isSoftDeleted, isSourceDue, isTtlExpired, isVacuousFilterClause, jsonPath, jsonPathSql, keysTouchRanges, liftSourceId, lintReadonlySql, listAdminTokens, 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, readDueScheduleOutboxEntry, readExternalSourceBaseline, readGlobalShapeSnapshot, readIdempotent, readMigrationStatus, readPatchField, readQueueMessageById, readQueueMessages, readReactorState, readScheduleOutbox, readScheduleOutboxState, readSchemaHistory, readSchemaVersion, readSearchBackfillState, readShapePokeCursor, readStreamChunks, readStreamRun, readTablePage, recordCapturedMail, recordChangedKeys, recordFanoutPass, recordGlobalPollPass, recordQueueMessages, recordScheduleOutbox, recordSchemaVersion, recordShapeProbePass, relationHooks, relayCountFor, renderSql, reprojectableFields, reprojectionMigrationId, reprojectionTables, requeueScheduleOutbox, resolvePatch, resolveRankPartition, resolveRankSeekTuple, resolveRelationPredicates, resolveWith, revokeAdminTokenRecord, 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, verifyAdminTokenDigest, verifySiblingBody, whereFilter, whereOfFilter, writeCdcArchivedThrough, writeGlobalShapeSnapshot, writeIdempotent, writeReactorState, writeSearchBackfillState, writeShapePokeCursor, writeShapePokeCursors, writeTouchesMemo };
|
|
2817
|
+
export { ADMIN_FUNCTIONS, ADMIN_FUNCTION_PREFIX, ADMIN_TOKEN_TABLE, AGGREGATE_SQL_FUNCTION, AGG_COUNT, AGG_KEY, AGG_VALUE, AUDIT_LOG_TABLE, type AdminTokenSummary, type AdvisorProcedure, 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 ImportConflictMode, type ImportError, type ImportRow, 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 ScheduleOutboxEntry, 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 TransactionLimitKind, type TransactionLimitWarning, 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, adminTokenExists, 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, createAdminTokenRecord, 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, dropScheduleOutbox, encodeAggregateKey, encodeCursor, encodeGeohash, encodePartitionKey, encodeRowsPatch, ensureAuditTable, ensureMailTable, envOptionalPositiveInt, envPositiveInt, equalityPinnedFields, exportShardRows, facetColumn, fanOutScalarCounts, findManyPage, findRelated, findStorageReferences, finishStreamRun, float64SqlKey, foldAggregateTally, forgetScheduleOutbox, ftsCompanionDdl, ftsPurgeDocument, ftsRowidMapName, ftsUnmappedPage, ftsWriteDocument, gateReplicaDispatch, geoTableName, globalShapeReadKey, groupUnmappedRows, guardWriter, handleReplicaControl, hasScheduleOutboxEntry, hasTrigger, haversineMeters, importShardRows, indexKeysForRow, isDevEnvironment, isFtsAvailable, isInternalTableName, isLossyBody, isMemoryTable, isPushableWhere, isRelationPredicate, isSoftDeleted, isSourceDue, isTtlExpired, isVacuousFilterClause, jsonPath, jsonPathSql, keysTouchRanges, liftSourceId, lintReadonlySql, listAdminTokens, 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, readDueScheduleOutboxEntry, readExternalSourceBaseline, readGlobalShapeSnapshot, readIdempotent, readMigrationStatus, readPatchField, readQueueMessageById, readQueueMessages, readReactorState, readScheduleOutbox, readScheduleOutboxState, readSchemaHistory, readSchemaVersion, readSearchBackfillState, readShapePokeCursor, readStreamChunks, readStreamRun, readTablePage, recordCapturedMail, recordChangedKeys, recordFanoutPass, recordGlobalPollPass, recordQueueMessages, recordScheduleOutbox, recordSchemaVersion, recordShapeProbePass, relationHooks, relayCountFor, renderSql, reprojectableFields, reprojectionMigrationId, reprojectionTables, requeueScheduleOutbox, resolvePatch, resolveRankPartition, resolveRankSeekTuple, resolveRelationPredicates, resolveWith, revokeAdminTokenRecord, 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, verifyAdminTokenDigest, 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 n}from"./packem_shared/exportShardRows-CZh4wrvI.mjs";import{adminTokenExists as d,createAdminTokenRecord as c,listAdminTokens as m,revokeAdminTokenRecord as p,verifyAdminTokenDigest as u}from"./packem_shared/adminTokenExists-CjKKZzfY.mjs";import{AGGREGATE_SQL_FUNCTION as f,aggregateSqlFunction as x,matchesStaticWhere as E,normalizeCountArgument as h,throwingScheduler as T}from"./packem_shared/AGGREGATE_SQL_FUNCTION-C_ZipS9R.mjs";import{aggregateTableName as A,coerceAggregateNumber as C,encodeAggregateKey as g,foldAggregateTally as _,readAggregateValue as I}from"./packem_shared/aggregateTableName-B_CtIQCS.mjs";import{CountRlsUnsupportedError as L,mergeWhere as D,planAggregateLookup as O,selectIndexForAggregate as P,selectIndexForCount as y,selectIndexForGroupBy as M}from"./packem_shared/CountRlsUnsupportedError-BvsDqfO2.mjs";import{AUDIT_LOG_TABLE as k,appendAuditEntry as N,ensureAuditTable as B,readAuditLog as U}from"./packem_shared/AUDIT_LOG_TABLE-BFJ65SRS.mjs";import{NotUniqueError as w,assertNoExplicitUndefined as q,assertStorableRowId as v,assertValidClientId as K,createShardCtxDb as W,normalizeIdStructurally as X,stripReservedPatchFields as H}from"./packem_shared/NotUniqueError-DGCd3Cph.mjs";import{backfillAggregateIndexes as z,backfillRankIndexes as Q,backfillSearchIndexes as Y,backfillSearchIndexesForTable as j}from"./packem_shared/backfillAggregateIndexes-Pk0KLrfk.mjs";import{CDC_LOG_TABLE as Z,CDC_LOG_TABLE_SEQ_INDEX as $,CDC_META_TABLE as ee,appendCdcChange as re,applyCdcChanges as oe,bumpCdcEpoch as ae,cdcCanVouchFor as te,cdcForkedError as ie,cdcSeqLeavingRows as se,cdcTouchesTables as ne,cdcTrimmedError as le,compactCdcDocs as de,cursorBelowRetainedFloor as ce,migrateCdcLog as me,migrateCdcMeta as pe,minCdcReplayableSeq as ue,minCdcSeq as Se,readCdcChangeKeys as fe,readCdcChanges as xe,readCdcCursor as Ee,readCdcEpoch as he,trimCdcChanges as Te}from"./packem_shared/CDC_LOG_TABLE-BFGgqai8.mjs";import{archiveCdcSegment as Ae,cdcArchiveRewound as Ce,readArchivedCdcChanges as ge,readCdcArchivedThrough as _e,writeCdcArchivedThrough as Ie}from"./packem_shared/archiveCdcSegment-Cr8oGLfB.mjs";import{CLIENT_WATERMARK_TABLE as Le,advanceClientWatermark as De,migrateClientWatermark as Oe,readClientWatermark as Pe}from"./packem_shared/CLIENT_WATERMARK_TABLE-De7z_OHV.mjs";import{COMMIT_SEQ_FIELD as Me,COMMIT_SEQ_TABLE as Fe,allocateCommitSeq as ke,migrateCommitSeq as Ne,readCommitSeq as Be}from"./packem_shared/COMMIT_SEQ_FIELD-Da1DjGqo.mjs";import{CompanionMemo as Ge,clearCompanionSignatures as we}from"./packem_shared/CompanionMemo-BXU5vfak.mjs";import{createCompanionSync as ve}from"./packem_shared/createCompanionSync-CEht4hXX.mjs";import{GLOBAL_SHAPE_SNAPSHOT_TABLE as We,deleteGlobalShapeSnapshot as Xe,deleteGlobalShapeSnapshotsForConnection as He,migrateGlobalShapeSnapshot as Ve,readGlobalShapeSnapshot as ze,writeGlobalShapeSnapshot as Qe}from"./packem_shared/GLOBAL_SHAPE_SNAPSHOT_TABLE-Bb6-aZuH.mjs";import{IDEMPOTENCY_TABLE as je,migrateIdempotency as Je,readIdempotent as Ze,trimIdempotent as $e,writeIdempotent as er}from"./packem_shared/IDEMPOTENCY_TABLE-COrgeP3O.mjs";import{clearMemoryTables as or,isMemoryTable as ar,memoryTableNames as tr}from"./packem_shared/clearMemoryTables-aMRERF0w.mjs";import{computeRankPage as sr,resolveRankSeekTuple as nr}from"./packem_shared/computeRankPage-xm-70mLy.mjs";import{SCHEDULE_OUTBOX_TABLE as dr,deferScheduleOutbox as cr,dropScheduleOutbox as mr,forgetScheduleOutbox as pr,hasScheduleOutboxEntry as ur,migrateScheduleOutbox as Sr,parkScheduleOutbox as fr,probeScheduleOutbox as xr,readDueScheduleOutbox as Er,readDueScheduleOutboxEntry as hr,readScheduleOutbox as Tr,readScheduleOutboxState as Rr,recordScheduleOutbox as Ar,requeueScheduleOutbox as Cr,trimScheduleOutbox as gr}from"./packem_shared/SCHEDULE_OUTBOX_TABLE-iyyiSjsO.mjs";import{S as Ir,m as br,r as Lr,w as Dr}from"./packem_shared/ctx-db-search-state-CPKPy8N6.mjs";import{SHAPE_POKE_CURSOR_TABLE as Pr,deleteShapePokeCursor as yr,deleteShapePokeCursorsForConnection as Mr,migrateShapePokeCursor as Fr,minShapePokeCursor as kr,readShapePokeCursor as Nr,writeShapePokeCursor as Br,writeShapePokeCursors as Ur}from"./packem_shared/SHAPE_POKE_CURSOR_TABLE-BGvY3sFI.mjs";import{selectShapeMembers as wr,selectShapeRows as qr}from"./packem_shared/selectShapeMembers-Dqx_m7BF.mjs";import{DATA_MIGRATION_STATE_TABLE as Kr,readMigrationStatus as Wr,runDataMigration as Xr}from"./packem_shared/DATA_MIGRATION_STATE_TABLE-CFvBS9-M.mjs";import{SCAN_DEP as Vr,createDependencyTracker as zr,depKey as Qr,tableFromDepKey as Yr}from"./packem_shared/SCAN_DEP-B4Uu4g7l.mjs";import{runDrizzle as Jr,runSql as Zr}from"./packem_shared/runDrizzle-RC09zZrh.mjs";import{A as eo,a as ro,b as oo,D as ao,c as to,d as io,g as so,i as no,j as lo,e as co,q as mo,f as po,r as uo,t as So,h as fo}from"./packem_shared/do-sql-105TONaE.mjs";import{WORKERD_SQLITE_LIMITS as Eo,param as ho,renderSql as To,sqliteInList as Ro,unionAll as Ao}from"./packem_shared/WORKERD_SQLITE_LIMITS-B_4w7tzY.mjs";import{appendStreamChunk as go,claimStreamRun as _o,deleteStreamRun as Io,finishStreamRun as bo,migrateDurableStreams as Lo,readStreamChunks as Do,readStreamRun as Oo,trimStreamRuns as Po}from"./packem_shared/appendStreamChunk-BZYgGE9Y.mjs";import{DurableStreamRunner as Mo,MAX_DURABLE_STREAM_BYTES as Fo,MAX_DURABLE_STREAM_CHUNKS as ko,decideDurableAttach as No}from"./packem_shared/DurableStreamRunner-MMlV5qKQ.mjs";import{envOptionalPositiveInt as Uo,envPositiveInt as Go}from"./packem_shared/envOptionalPositiveInt-D2pY-c64.mjs";import{diffExternalSource as qo}from"./packem_shared/diffExternalSource-B0FZlDoL.mjs";import{liftSourceId as Ko,normalizeSourceDocument as Wo,normalizeSourceValue as Xo}from"./packem_shared/liftSourceId-CA3ENhXj.mjs";import{materializeExternalRows as Vo,materializeExternalRowsIncremental as zo,readExternalSourceBaseline as Qo,runExternalSourceTick as Yo}from"./packem_shared/materializeExternalRows-CHPRx8fu.mjs";import{isSoftDeleted as Jo,isSourceDue as Zo,pullExternalSourceIncrementalTick as $o,pullExternalSourceTick as ea}from"./packem_shared/isSoftDeleted-BBWKE0Sm.mjs";import{f as oa,a as aa,b as ta,c as ia,d as sa,g as na}from"./packem_shared/fts-companion-CE3EmIjk.mjs";import{GEO_DEFAULT_PRECISION as da,boundingBoxCenter as ca,boundingBoxGeohashes as ma,coveringGeohashes as pa,encodeGeohash as ua,haversineMeters as Sa,pointInBoundingBox as fa}from"./packem_shared/GEO_DEFAULT_PRECISION-CqpQZ-J_.mjs";import{default as Ea}from"./packem_shared/GlobalPollTick-BNK4o-XT.mjs";import{ADMIN_FUNCTIONS as Ta,ADMIN_FUNCTION_PREFIX as Ra,DEFAULT_FANOUT_TOPIC_LIMIT as Aa,FLAGS_FUNCTION_PREFIX as Ca,MAX_PAGE_SIZE as ga,RELATION_FUNCTION_PREFIX as _a,createFanoutCounters as Ia,createGlobalPollCounters as ba,createShapeProbeCounters as La,facetColumn as Da,findStorageReferences as Oa,isVacuousFilterClause as Pa,listTables as ya,readTablePage as Ma,recordFanoutPass as Fa,recordGlobalPollPass as ka,recordShapeProbePass as Na,selectMatchingIds as Ba,summarizeFanoutTopics as Ua,summarizeSubscriptions as Ga}from"./packem_shared/ADMIN_FUNCTIONS-CSz3ZK2d.mjs";import{MAIL_RETENTION as qa,MAIL_TABLE as va,clearCapturedMail as Ka,ensureMailTable as Wa,readCapturedMail as Xa,recordCapturedMail as Ha}from"./packem_shared/MAIL_RETENTION-DMolrLYt.mjs";import{NotFoundError as za}from"./packem_shared/NotFoundError-BhF7FeFr.mjs";import{assertPatchAllowed as Ya,operatorFields as ja,patchDependsOnRow as Ja,readPatchField as Za,resolvePatch as $a}from"./packem_shared/assertPatchAllowed-CA_H466g.mjs";import{armRestore as rt,readBookmark as ot}from"./packem_shared/armRestore-Bu1_8SUa.mjs";import{CURSOR_PREFIX as tt,applySelect as it,buildSeekBeforeWhere as st,buildSeekWhere as nt,decodeCursor as lt,encodeCursor as dt,equalityPinnedFields as ct,normalizeOrderKeys as mt,nullsFirstOf as pt,nullsOrderSuffix as ut,softDeleteScope as St,tiebreakDirectionFor as ft,uniqueIndexFields as xt}from"./packem_shared/CURSOR_PREFIX-6offuG6M.mjs";import{QUEUE_TABLE as ht,clearQueueMessages as Tt,isLossyBody as Rt,readQueueMessageById as At,readQueueMessages as Ct,recordQueueMessages as gt}from"./packem_shared/QUEUE_TABLE-C-goXtGd.mjs";import{RANK_TIEBREAK as It,encodePartitionKey as bt,matchesRankStaticWhere as Lt,rankKeyFromDoc as Dt,rankPivotConditionSql as Ot,rankTableName as Pt,resolveRankPartition as yt,sortColumnName as Mt}from"./packem_shared/RANK_TIEBREAK-D3ye2GsL.mjs";import{ReactiveCache as kt,reactiveCacheKey as Nt}from"./packem_shared/ReactiveCache-BG9z3FE9.mjs";import{REACTOR_STATE_TABLE as Ut,listReactorStates as Gt,migrateReactorState as wt,reactorNeedsRun as qt,readReactorState as vt,writeReactorState as Kt}from"./packem_shared/REACTOR_STATE_TABLE-D2Mn204f.mjs";import{UNVOUCHABLE_DEP as Xt,createReadFootprint as Ht,markUnvouchableReads as Vt}from"./packem_shared/UNVOUCHABLE_DEP-Ds9gxVqs.mjs";import{buildIndexRange as Qt,indexKeysForRow as Yt,keysTouchRanges as jt}from"./packem_shared/buildIndexRange-BTChxh3k.mjs";import{isPushableWhere as Zt,whereFilter as $t,whereOfFilter as ei}from"./packem_shared/isPushableWhere-BeYAOjUb.mjs";import{RELATED_DEFAULT_LIMIT as oi,RELATED_DEPTH_DECAY as ai,RELATED_MAX_DEPTH as ti,RELATED_MAX_LIMIT as ii,deriveRelationEdges as si,findRelated as ni}from"./packem_shared/RELATED_DEFAULT_LIMIT-CVqN4JEu.mjs";import{DEFAULT_MAX_RELATION_KEYS as di,assertFlatPredicate as ci,assertShapeShardable as mi,composeReadPredicate as pi,containsRelationPredicate as ui,isRelationPredicate as Si,resolveRelationPredicates as fi}from"./packem_shared/DEFAULT_MAX_RELATION_KEYS-DfrMi_eE.mjs";import{describeRelationWrites as Ei}from"./packem_shared/describeRelationWrites-omar6-u9.mjs";import{applyInsertDefaults as Ti,applyOnDelete as Ri,distinctValues as Ai,fanOutScalarCounts as Ci,relationHooks as gi,resolveWith as _i,runRowValidators as Ii}from"./packem_shared/applyInsertDefaults-CVukTkQ5.mjs";import{D as Li,c as Di,n as Oi,r as Pi,s as yi}from"./packem_shared/relay-CKEdfUjH.mjs";import{DEFAULT_MAX_RELAYS as Fi,OwnerRelay as ki,RelayMember as Ni,createRelayLink as Bi}from"./packem_shared/DEFAULT_MAX_RELAYS-Bc6PI-xy.mjs";import{createReplicaLink as Gi,gateReplicaDispatch as wi,handleReplicaControl as qi}from"./packem_shared/createReplicaLink-DtqXBi-0.mjs";import{buildReprojectionMigration as Ki,countLegacyRows as Wi,reprojectableFields as Xi,reprojectionTables as Hi}from"./packem_shared/buildReprojectionMigration-B8aEpETD.mjs";import{RLS_UNWRAP_SYMBOL as zi,RlsRequiredError as Qi,guardWriter as Yi}from"./packem_shared/RLS_UNWRAP_SYMBOL-H6J96vgK.mjs";import{SCHEMA_HISTORY_MAX_VERSIONS as Ji,readSchemaHistory as Zi,readSchemaVersion as $i,recordSchemaVersion as es}from"./packem_shared/SCHEMA_HISTORY_MAX_VERSIONS-CEwFjj-O.mjs";import{serializeSqlValue as os}from"./packem_shared/serializeSqlValue-DeoBMpZ2.mjs";import{buildSettings as ts,isDevEnvironment as is,readDeployInfo as ss}from"./packem_shared/buildSettings-CFkvTaHx.mjs";import{buildShapeDiff as ls}from"./packem_shared/buildShapeDiff-CdLJTijm.mjs";import{ShapeDiffCache as cs,createShapeDiffCache as ms,globalShapeReadKey as ps}from"./packem_shared/ShapeDiffCache-iNO-hUiy.mjs";import{buildPokeFrames as Ss,diffGlobalMembership as fs,encodeRowsPatch as xs,projectColumns as Es}from"./packem_shared/buildPokeFrames-WR-hp0mX.mjs";import{ShardRunner as Ts}from"./packem_shared/ShardRunner-CrveaPId.mjs";import{stubByName as As}from"./packem_shared/stubByName-DQSivmvb.mjs";import{runSocketPool as gs}from"./packem_shared/runSocketPool-CZJ2X9cF.mjs";import{MAX_SQL_ROWS as Is,assertReadonly as bs,lintReadonlySql as Ls,runReadonlySql as Ds}from"./packem_shared/MAX_SQL_ROWS-B4WlVI-e.mjs";import{BIGINT_KEY_DIGITS as Ps,bigintSqlKey as ys,decodeBigintSqlKey as Ms,decodeFloat64SqlKey as Fs,float64SqlKey as ks}from"./packem_shared/BIGINT_KEY_DIGITS-DE6yshOt.mjs";import{awaitWsDrain as Bs,subscriptionFrames as Us,subscriptionListDeltas as Gs,trySendFrame as ws}from"./packem_shared/awaitWsDrain-DMcWBQ7I.mjs";import{mergeChangedKeys as vs,recordChangedKeys as Ks,writeTouchesMemo as Ws}from"./packem_shared/mergeChangedKeys-DPKhen6e.mjs";import{createSystemReader as Hs}from"./packem_shared/createSystemReader-BSCxr8Qs.mjs";import{ConflictError as zs}from"./packem_shared/ConflictError-C8GtJmjS.mjs";import{DEFAULT_TRANSACTION_LIMITS as Ys,TransactionHeadroomTracker as js}from"./packem_shared/DEFAULT_TRANSACTION_LIMITS-D7p7Ys0M.mjs";import{hasTrigger as Zs,runTriggers as $s}from"./packem_shared/hasTrigger-CjlwI4le.mjs";import{isTtlExpired as rn,nextTtlExpiry as on,selectExpiredIds as an}from"./packem_shared/isTtlExpired-DNxmZA6e.mjs";import{VECTOR_BACKFILL_MAX_PAGES as sn,backfillVectorIndexes as nn}from"./packem_shared/VECTOR_BACKFILL_MAX_PAGES-DcQpf83n.mjs";import{c as dn,s as cn}from"./packem_shared/where-sql-BjY4rnqb.mjs";import{RELATION_EXISTS_KEY as pn}from"./packem_shared/RELATION_EXISTS_KEY-wxgj6rSL.mjs";import{ADMIN_TOKEN_TABLE as Sn}from"./packem_shared/ADMIN_TOKEN_TABLE-DfQ5osdI.mjs";import{RELAY_SIGNATURE_HEADER as xn,siblingSecretOf as En,signSiblingBody as hn,verifySiblingBody as Tn}from"./packem_shared/RELAY_SIGNATURE_HEADER-CAfC4tqg.mjs";import{REPROJECTION_MIGRATION_PREFIX as An,reprojectionMigrationId as Cn}from"./packem_shared/REPROJECTION_MIGRATION_PREFIX-Czcb6_mO.mjs";import{isInternalTableName as _n}from"./packem_shared/isInternalTableName-BoljO2tP.mjs";import{quoteIdentifier as bn}from"./packem_shared/quoteIdentifier-CObIFRhb.mjs";import{runShardMigrations as Dn}from"./packem_shared/runShardMigrations-BPFg3Ht6.mjs";import{stableStringify as Pn,stableWireKey as yn}from"@lunora/wire";export{Ta as ADMIN_FUNCTIONS,Ra as ADMIN_FUNCTION_PREFIX,Sn as ADMIN_TOKEN_TABLE,f as AGGREGATE_SQL_FUNCTION,eo as AGG_COUNT,ro as AGG_KEY,oo as AGG_VALUE,k as AUDIT_LOG_TABLE,Ps as BIGINT_KEY_DIGITS,Z as CDC_LOG_TABLE,$ as CDC_LOG_TABLE_SEQ_INDEX,ee as CDC_META_TABLE,Le as CLIENT_WATERMARK_TABLE,Me as COMMIT_SEQ_FIELD,Fe as COMMIT_SEQ_TABLE,tt as CURSOR_PREFIX,Ge as CompanionMemo,zs as ConflictError,L as CountRlsUnsupportedError,Kr as DATA_MIGRATION_STATE_TABLE,Aa as DEFAULT_FANOUT_TOPIC_LIMIT,di as DEFAULT_MAX_RELATION_KEYS,Fi as DEFAULT_MAX_RELAYS,Li as DEFAULT_PROMOTION_THRESHOLDS,Ys as DEFAULT_TRANSACTION_LIMITS,ao as DOC_COLUMN,Mo as DurableStreamRunner,Ca as FLAGS_FUNCTION_PREFIX,da as GEO_DEFAULT_PRECISION,We as GLOBAL_SHAPE_SNAPSHOT_TABLE,Ea as GlobalPollTick,je as IDEMPOTENCY_TABLE,qa as MAIL_RETENTION,va as MAIL_TABLE,Fo as MAX_DURABLE_STREAM_BYTES,ko as MAX_DURABLE_STREAM_CHUNKS,ga as MAX_PAGE_SIZE,Is as MAX_SQL_ROWS,za as NotFoundError,w as NotUniqueError,ki as OwnerRelay,ht as QUEUE_TABLE,It as RANK_TIEBREAK,Ut as REACTOR_STATE_TABLE,oi as RELATED_DEFAULT_LIMIT,ai as RELATED_DEPTH_DECAY,ti as RELATED_MAX_DEPTH,ii as RELATED_MAX_LIMIT,pn as RELATION_EXISTS_KEY,_a as RELATION_FUNCTION_PREFIX,xn as RELAY_SIGNATURE_HEADER,An as REPROJECTION_MIGRATION_PREFIX,zi as RLS_UNWRAP_SYMBOL,kt as ReactiveCache,Ni as RelayMember,Qi as RlsRequiredError,Vr as SCAN_DEP,dr as SCHEDULE_OUTBOX_TABLE,Ji as SCHEMA_HISTORY_MAX_VERSIONS,Ir as SEARCH_STATE_TABLE,Pr as SHAPE_POKE_CURSOR_TABLE,cs as ShapeDiffCache,Ts as ShardRunner,js as TransactionHeadroomTracker,Xt as UNVOUCHABLE_DEP,sn as VECTOR_BACKFILL_MAX_PAGES,Eo as WORKERD_SQLITE_LIMITS,d as adminTokenExists,De as advanceClientWatermark,to as aggUpsertSql,x as aggregateSqlFunction,A as aggregateTableName,ke as allocateCommitSeq,N as appendAuditEntry,re as appendCdcChange,go as appendStreamChunk,oe as applyCdcChanges,Ti as applyInsertDefaults,Ri as applyOnDelete,it as applySelect,Ae as archiveCdcSegment,rt as armRestore,ci as assertFlatPredicate,q as assertNoExplicitUndefined,Ya as assertPatchAllowed,bs as assertReadonly,mi as assertShapeShardable,v as assertStorableRowId,K as assertValidClientId,Bs as awaitWsDrain,z as backfillAggregateIndexes,Q as backfillRankIndexes,Y as backfillSearchIndexes,j as backfillSearchIndexesForTable,nn as backfillVectorIndexes,ys as bigintSqlKey,ca as boundingBoxCenter,ma as boundingBoxGeohashes,Qt as buildIndexRange,Ss as buildPokeFrames,Ki as buildReprojectionMigration,st as buildSeekBeforeWhere,nt as buildSeekWhere,ts as buildSettings,ls as buildShapeDiff,ae as bumpCdcEpoch,Ce as cdcArchiveRewound,te as cdcCanVouchFor,ie as cdcForkedError,se as cdcSeqLeavingRows,ne as cdcTouchesTables,le as cdcTrimmedError,_o as claimStreamRun,Di as clampPromotionThresholds,Ka as clearCapturedMail,we as clearCompanionSignatures,or as clearMemoryTables,Tt as clearQueueMessages,C as coerceAggregateNumber,de as compactCdcDocs,dn as compileWhereSql,pi as composeReadPredicate,sr as computeRankPage,ui as containsRelationPredicate,Wi as countLegacyRows,pa as coveringGeohashes,c as createAdminTokenRecord,ve as createCompanionSync,zr as createDependencyTracker,Ia as createFanoutCounters,ba as createGlobalPollCounters,io as createIndexSql,Ht as createReadFootprint,Bi as createRelayLink,Gi as createReplicaLink,ms as createShapeDiffCache,La as createShapeProbeCounters,W as createShardCtxDb,Hs as createSystemReader,ce as cursorBelowRetainedFloor,No as decideDurableAttach,Ms as decodeBigintSqlKey,lt as decodeCursor,Fs as decodeFloat64SqlKey,cr as deferScheduleOutbox,Xe as deleteGlobalShapeSnapshot,He as deleteGlobalShapeSnapshotsForConnection,yr as deleteShapePokeCursor,Mr as deleteShapePokeCursorsForConnection,Io as deleteStreamRun,Qr as depKey,si as deriveRelationEdges,Ei as describeRelationWrites,qo as diffExternalSource,fs as diffGlobalMembership,Ai as distinctValues,mr as dropScheduleOutbox,g as encodeAggregateKey,dt as encodeCursor,ua as encodeGeohash,bt as encodePartitionKey,xs as encodeRowsPatch,B as ensureAuditTable,Wa as ensureMailTable,Uo as envOptionalPositiveInt,Go as envPositiveInt,ct as equalityPinnedFields,o as exportShardRows,Da as facetColumn,Ci as fanOutScalarCounts,ni as findRelated,Oa as findStorageReferences,bo as finishStreamRun,ks as float64SqlKey,_ as foldAggregateTally,pr as forgetScheduleOutbox,oa as ftsCompanionDdl,aa as ftsPurgeDocument,ta as ftsRowidMapName,ia as ftsUnmappedPage,sa as ftsWriteDocument,wi as gateReplicaDispatch,so as geoTableName,ps as globalShapeReadKey,na as groupUnmappedRows,Yi as guardWriter,qi as handleReplicaControl,ur as hasScheduleOutboxEntry,Zs as hasTrigger,Sa as haversineMeters,a as importShardRows,Yt as indexKeysForRow,is as isDevEnvironment,no as isFtsAvailable,_n as isInternalTableName,Rt as isLossyBody,ar as isMemoryTable,Zt as isPushableWhere,Si as isRelationPredicate,Jo as isSoftDeleted,Zo as isSourceDue,rn as isTtlExpired,Pa as isVacuousFilterClause,lo as jsonPath,co as jsonPathSql,jt as keysTouchRanges,Ko as liftSourceId,Ls as lintReadonlySql,m as listAdminTokens,Gt as listReactorStates,ya as listTables,Vt as markUnvouchableReads,Lt as matchesRankStaticWhere,E as matchesStaticWhere,Vo as materializeExternalRows,zo as materializeExternalRowsIncremental,tr as memoryTableNames,vs as mergeChangedKeys,D as mergeWhere,me as migrateCdcLog,pe as migrateCdcMeta,Oe as migrateClientWatermark,Ne as migrateCommitSeq,Lo as migrateDurableStreams,Ve as migrateGlobalShapeSnapshot,Je as migrateIdempotency,wt as migrateReactorState,Sr as migrateScheduleOutbox,br as migrateSearchState,Fr as migrateShapePokeCursor,ue as minCdcReplayableSeq,Se as minCdcSeq,kr as minShapePokeCursor,Oi as nextPromotionState,on as nextTtlExpiry,h as normalizeCountArgument,X as normalizeIdStructurally,mt as normalizeOrderKeys,Wo as normalizeSourceDocument,Xo as normalizeSourceValue,pt as nullsFirstOf,ut as nullsOrderSuffix,ja as operatorFields,ho as param,fr as parkScheduleOutbox,t as parseExportShardArgs,i as parseImportShardArgs,Ja as patchDependsOnRow,O as planAggregateLookup,fa as pointInBoundingBox,xr as probeScheduleOutbox,Es as projectColumns,$o as pullExternalSourceIncrementalTick,ea as pullExternalSourceTick,mo as qualifiedJsonPath,po as qualifiedJsonPathSql,bn as quoteIdentifier,Dt as rankKeyFromDoc,Ot as rankPivotConditionSql,Pt as rankTableName,Nt as reactiveCacheKey,qt as reactorNeedsRun,I as readAggregateValue,ge as readArchivedCdcChanges,U as readAuditLog,ot as readBookmark,Xa as readCapturedMail,_e as readCdcArchivedThrough,fe as readCdcChangeKeys,xe as readCdcChanges,Ee as readCdcCursor,he as readCdcEpoch,Pe as readClientWatermark,Be as readCommitSeq,ss as readDeployInfo,Er as readDueScheduleOutbox,hr as readDueScheduleOutboxEntry,Qo as readExternalSourceBaseline,ze as readGlobalShapeSnapshot,Ze as readIdempotent,Wr as readMigrationStatus,Za as readPatchField,At as readQueueMessageById,Ct as readQueueMessages,vt as readReactorState,Tr as readScheduleOutbox,Rr as readScheduleOutboxState,Zi as readSchemaHistory,$i as readSchemaVersion,Lr as readSearchBackfillState,Nr as readShapePokeCursor,Do as readStreamChunks,Oo as readStreamRun,Ma as readTablePage,Ha as recordCapturedMail,Ks as recordChangedKeys,Fa as recordFanoutPass,ka as recordGlobalPollPass,gt as recordQueueMessages,Ar as recordScheduleOutbox,es as recordSchemaVersion,Na as recordShapeProbePass,gi as relationHooks,Pi as relayCountFor,To as renderSql,Xi as reprojectableFields,Cn as reprojectionMigrationId,Hi as reprojectionTables,Cr as requeueScheduleOutbox,$a as resolvePatch,yt as resolveRankPartition,nr as resolveRankSeekTuple,fi as resolveRelationPredicates,_i as resolveWith,p as revokeAdminTokenRecord,uo as rowToDocument,Xr as runDataMigration,Jr as runDrizzle,Yo as runExternalSourceTick,Ds as runReadonlySql,Ii as runRowValidators,Dn as runShardMigrations,gs as runSocketPool,Zr as runSql,$s as runTriggers,an as selectExpiredIds,s as selectExportTables,P as selectIndexForAggregate,y as selectIndexForCount,M as selectIndexForGroupBy,Ba as selectMatchingIds,wr as selectShapeMembers,qr as selectShapeRows,os as serializeSqlValue,cn as serverInList,yi as shapeRoutingKey,En as siblingSecretOf,hn as signSiblingBody,St as softDeleteScope,Mt as sortColumnName,Ro as sqliteInList,Pn as stableStringify,yn as stableWireKey,H as stripReservedPatchFields,As as stubByName,Us as subscriptionFrames,Gs as subscriptionListDeltas,Ua as summarizeFanoutTopics,Ga as summarizeSubscriptions,So as tableColumns,Yr as tableFromDepKey,T as throwingScheduler,ft as tiebreakDirectionFor,Te as trimCdcChanges,$e as trimIdempotent,gr as trimScheduleOutbox,Po as trimStreamRuns,fo as tryRowToDocument,ws as trySendFrame,Ao as unionAll,xt as uniqueIndexFields,n as validateImportRow,u as verifyAdminTokenDigest,Tn as verifySiblingBody,$t as whereFilter,ei as whereOfFilter,Ie as writeCdcArchivedThrough,Qe as writeGlobalShapeSnapshot,er as writeIdempotent,Kt as writeReactorState,Dr as writeSearchBackfillState,Br as writeShapePokeCursor,Ur as writeShapePokeCursors,Ws as writeTouchesMemo};
|
|
1
|
+
import{exportShardRows as o,importShardRows as a,parseExportShardArgs as t,parseImportShardArgs as i,selectExportTables as s,validateImportRow as n}from"./packem_shared/exportShardRows-CZh4wrvI.mjs";import{adminTokenExists as d,createAdminTokenRecord as c,listAdminTokens as m,revokeAdminTokenRecord as p,verifyAdminTokenDigest as u}from"./packem_shared/adminTokenExists-CjKKZzfY.mjs";import{AGGREGATE_SQL_FUNCTION as f,aggregateSqlFunction as x,matchesStaticWhere as E,normalizeCountArgument as h,throwingScheduler as T}from"./packem_shared/AGGREGATE_SQL_FUNCTION-C_ZipS9R.mjs";import{aggregateTableName as A,coerceAggregateNumber as C,encodeAggregateKey as g,foldAggregateTally as _,readAggregateValue as I}from"./packem_shared/aggregateTableName-B_CtIQCS.mjs";import{CountRlsUnsupportedError as L,mergeWhere as D,planAggregateLookup as O,selectIndexForAggregate as P,selectIndexForCount as y,selectIndexForGroupBy as M}from"./packem_shared/CountRlsUnsupportedError-BvsDqfO2.mjs";import{AUDIT_LOG_TABLE as k,appendAuditEntry as N,ensureAuditTable as B,readAuditLog as U}from"./packem_shared/AUDIT_LOG_TABLE-BFJ65SRS.mjs";import{NotUniqueError as w,assertNoExplicitUndefined as q,assertStorableRowId as v,assertValidClientId as K,createShardCtxDb as W,normalizeIdStructurally as X,stripReservedPatchFields as H}from"./packem_shared/NotUniqueError-vJf9tj6U.mjs";import{backfillAggregateIndexes as z,backfillRankIndexes as Q,backfillSearchIndexes as Y,backfillSearchIndexesForTable as j}from"./packem_shared/backfillAggregateIndexes-Pk0KLrfk.mjs";import{CDC_LOG_TABLE as Z,CDC_LOG_TABLE_SEQ_INDEX as $,CDC_META_TABLE as ee,appendCdcChange as re,applyCdcChanges as oe,bumpCdcEpoch as ae,cdcCanVouchFor as te,cdcForkedError as ie,cdcSeqLeavingRows as se,cdcTouchesTables as ne,cdcTrimmedError as le,compactCdcDocs as de,cursorBelowRetainedFloor as ce,migrateCdcLog as me,migrateCdcMeta as pe,minCdcReplayableSeq as ue,minCdcSeq as Se,readCdcChangeKeys as fe,readCdcChanges as xe,readCdcCursor as Ee,readCdcEpoch as he,trimCdcChanges as Te}from"./packem_shared/CDC_LOG_TABLE-BFGgqai8.mjs";import{archiveCdcSegment as Ae,cdcArchiveRewound as Ce,readArchivedCdcChanges as ge,readCdcArchivedThrough as _e,writeCdcArchivedThrough as Ie}from"./packem_shared/archiveCdcSegment-Cr8oGLfB.mjs";import{CLIENT_WATERMARK_TABLE as Le,advanceClientWatermark as De,migrateClientWatermark as Oe,readClientWatermark as Pe}from"./packem_shared/CLIENT_WATERMARK_TABLE-De7z_OHV.mjs";import{COMMIT_SEQ_FIELD as Me,COMMIT_SEQ_TABLE as Fe,allocateCommitSeq as ke,migrateCommitSeq as Ne,readCommitSeq as Be}from"./packem_shared/COMMIT_SEQ_FIELD-Da1DjGqo.mjs";import{CompanionMemo as Ge,clearCompanionSignatures as we}from"./packem_shared/CompanionMemo-BXU5vfak.mjs";import{createCompanionSync as ve}from"./packem_shared/createCompanionSync-CEht4hXX.mjs";import{GLOBAL_SHAPE_SNAPSHOT_TABLE as We,deleteGlobalShapeSnapshot as Xe,deleteGlobalShapeSnapshotsForConnection as He,migrateGlobalShapeSnapshot as Ve,readGlobalShapeSnapshot as ze,writeGlobalShapeSnapshot as Qe}from"./packem_shared/GLOBAL_SHAPE_SNAPSHOT_TABLE-Bb6-aZuH.mjs";import{IDEMPOTENCY_TABLE as je,migrateIdempotency as Je,readIdempotent as Ze,trimIdempotent as $e,writeIdempotent as er}from"./packem_shared/IDEMPOTENCY_TABLE-COrgeP3O.mjs";import{clearMemoryTables as or,isMemoryTable as ar,memoryTableNames as tr}from"./packem_shared/clearMemoryTables-aMRERF0w.mjs";import{computeRankPage as sr,resolveRankSeekTuple as nr}from"./packem_shared/computeRankPage-xm-70mLy.mjs";import{SCHEDULE_OUTBOX_TABLE as dr,deferScheduleOutbox as cr,dropScheduleOutbox as mr,forgetScheduleOutbox as pr,hasScheduleOutboxEntry as ur,migrateScheduleOutbox as Sr,parkScheduleOutbox as fr,probeScheduleOutbox as xr,readDueScheduleOutbox as Er,readDueScheduleOutboxEntry as hr,readScheduleOutbox as Tr,readScheduleOutboxState as Rr,recordScheduleOutbox as Ar,requeueScheduleOutbox as Cr,trimScheduleOutbox as gr}from"./packem_shared/SCHEDULE_OUTBOX_TABLE-iyyiSjsO.mjs";import{S as Ir,m as br,r as Lr,w as Dr}from"./packem_shared/ctx-db-search-state-CPKPy8N6.mjs";import{SHAPE_POKE_CURSOR_TABLE as Pr,deleteShapePokeCursor as yr,deleteShapePokeCursorsForConnection as Mr,migrateShapePokeCursor as Fr,minShapePokeCursor as kr,readShapePokeCursor as Nr,writeShapePokeCursor as Br,writeShapePokeCursors as Ur}from"./packem_shared/SHAPE_POKE_CURSOR_TABLE-BGvY3sFI.mjs";import{selectShapeMembers as wr,selectShapeRows as qr}from"./packem_shared/selectShapeMembers-Dqx_m7BF.mjs";import{DATA_MIGRATION_STATE_TABLE as Kr,readMigrationStatus as Wr,runDataMigration as Xr}from"./packem_shared/DATA_MIGRATION_STATE_TABLE-CFvBS9-M.mjs";import{SCAN_DEP as Vr,createDependencyTracker as zr,depKey as Qr,tableFromDepKey as Yr}from"./packem_shared/SCAN_DEP-B4Uu4g7l.mjs";import{runDrizzle as Jr,runSql as Zr}from"./packem_shared/runDrizzle-RC09zZrh.mjs";import{A as eo,a as ro,b as oo,D as ao,c as to,d as io,g as so,i as no,j as lo,e as co,q as mo,f as po,r as uo,t as So,h as fo}from"./packem_shared/do-sql-105TONaE.mjs";import{WORKERD_SQLITE_LIMITS as Eo,param as ho,renderSql as To,sqliteInList as Ro,unionAll as Ao}from"./packem_shared/WORKERD_SQLITE_LIMITS-B_4w7tzY.mjs";import{appendStreamChunk as go,claimStreamRun as _o,deleteStreamRun as Io,finishStreamRun as bo,migrateDurableStreams as Lo,readStreamChunks as Do,readStreamRun as Oo,trimStreamRuns as Po}from"./packem_shared/appendStreamChunk-BZYgGE9Y.mjs";import{DurableStreamRunner as Mo,MAX_DURABLE_STREAM_BYTES as Fo,MAX_DURABLE_STREAM_CHUNKS as ko,decideDurableAttach as No}from"./packem_shared/DurableStreamRunner-MMlV5qKQ.mjs";import{envOptionalPositiveInt as Uo,envPositiveInt as Go}from"./packem_shared/envOptionalPositiveInt-D2pY-c64.mjs";import{diffExternalSource as qo}from"./packem_shared/diffExternalSource-B0FZlDoL.mjs";import{liftSourceId as Ko,normalizeSourceDocument as Wo,normalizeSourceValue as Xo}from"./packem_shared/liftSourceId-CA3ENhXj.mjs";import{materializeExternalRows as Vo,materializeExternalRowsIncremental as zo,readExternalSourceBaseline as Qo,runExternalSourceTick as Yo}from"./packem_shared/materializeExternalRows-CHPRx8fu.mjs";import{isSoftDeleted as Jo,isSourceDue as Zo,pullExternalSourceIncrementalTick as $o,pullExternalSourceTick as ea}from"./packem_shared/isSoftDeleted-BBWKE0Sm.mjs";import{f as oa,a as aa,b as ta,c as ia,d as sa,g as na}from"./packem_shared/fts-companion-CE3EmIjk.mjs";import{GEO_DEFAULT_PRECISION as da,boundingBoxCenter as ca,boundingBoxGeohashes as ma,coveringGeohashes as pa,encodeGeohash as ua,haversineMeters as Sa,pointInBoundingBox as fa}from"./packem_shared/GEO_DEFAULT_PRECISION-CqpQZ-J_.mjs";import{default as Ea}from"./packem_shared/GlobalPollTick-BNK4o-XT.mjs";import{ADMIN_FUNCTIONS as Ta,ADMIN_FUNCTION_PREFIX as Ra,DEFAULT_FANOUT_TOPIC_LIMIT as Aa,FLAGS_FUNCTION_PREFIX as Ca,MAX_PAGE_SIZE as ga,RELATION_FUNCTION_PREFIX as _a,createFanoutCounters as Ia,createGlobalPollCounters as ba,createShapeProbeCounters as La,facetColumn as Da,findStorageReferences as Oa,isVacuousFilterClause as Pa,listTables as ya,readTablePage as Ma,recordFanoutPass as Fa,recordGlobalPollPass as ka,recordShapeProbePass as Na,selectMatchingIds as Ba,summarizeFanoutTopics as Ua,summarizeSubscriptions as Ga}from"./packem_shared/ADMIN_FUNCTIONS-CSz3ZK2d.mjs";import{MAIL_RETENTION as qa,MAIL_TABLE as va,clearCapturedMail as Ka,ensureMailTable as Wa,readCapturedMail as Xa,recordCapturedMail as Ha}from"./packem_shared/MAIL_RETENTION-DMolrLYt.mjs";import{NotFoundError as za}from"./packem_shared/NotFoundError-BhF7FeFr.mjs";import{assertPatchAllowed as Ya,operatorFields as ja,patchDependsOnRow as Ja,readPatchField as Za,resolvePatch as $a}from"./packem_shared/assertPatchAllowed-CA_H466g.mjs";import{armRestore as rt,readBookmark as ot}from"./packem_shared/armRestore-Bu1_8SUa.mjs";import{CURSOR_PREFIX as tt,applySelect as it,buildSeekBeforeWhere as st,buildSeekWhere as nt,decodeCursor as lt,encodeCursor as dt,equalityPinnedFields as ct,normalizeOrderKeys as mt,nullsFirstOf as pt,nullsOrderSuffix as ut,softDeleteScope as St,tiebreakDirectionFor as ft,uniqueIndexFields as xt}from"./packem_shared/CURSOR_PREFIX-6offuG6M.mjs";import{QUEUE_TABLE as ht,clearQueueMessages as Tt,isLossyBody as Rt,readQueueMessageById as At,readQueueMessages as Ct,recordQueueMessages as gt}from"./packem_shared/QUEUE_TABLE-C-goXtGd.mjs";import{RANK_TIEBREAK as It,encodePartitionKey as bt,matchesRankStaticWhere as Lt,rankKeyFromDoc as Dt,rankPivotConditionSql as Ot,rankTableName as Pt,resolveRankPartition as yt,sortColumnName as Mt}from"./packem_shared/RANK_TIEBREAK-D3ye2GsL.mjs";import{ReactiveCache as kt,reactiveCacheKey as Nt}from"./packem_shared/ReactiveCache-BG9z3FE9.mjs";import{REACTOR_STATE_TABLE as Ut,listReactorStates as Gt,migrateReactorState as wt,reactorNeedsRun as qt,readReactorState as vt,writeReactorState as Kt}from"./packem_shared/REACTOR_STATE_TABLE-D2Mn204f.mjs";import{UNVOUCHABLE_DEP as Xt,createReadFootprint as Ht,markUnvouchableReads as Vt}from"./packem_shared/UNVOUCHABLE_DEP-Ds9gxVqs.mjs";import{buildIndexRange as Qt,indexKeysForRow as Yt,keysTouchRanges as jt}from"./packem_shared/buildIndexRange-BTChxh3k.mjs";import{isPushableWhere as Zt,whereFilter as $t,whereOfFilter as ei}from"./packem_shared/isPushableWhere-BeYAOjUb.mjs";import{RELATED_DEFAULT_LIMIT as oi,RELATED_DEPTH_DECAY as ai,RELATED_MAX_DEPTH as ti,RELATED_MAX_LIMIT as ii,deriveRelationEdges as si,findRelated as ni}from"./packem_shared/RELATED_DEFAULT_LIMIT-CVqN4JEu.mjs";import{DEFAULT_MAX_RELATION_KEYS as di,assertFlatPredicate as ci,assertShapeShardable as mi,composeReadPredicate as pi,containsRelationPredicate as ui,findManyPage as Si,isRelationPredicate as fi,resolveRelationPredicates as xi}from"./packem_shared/DEFAULT_MAX_RELATION_KEYS-BBtZ_jRj.mjs";import{describeRelationWrites as hi}from"./packem_shared/describeRelationWrites-omar6-u9.mjs";import{applyInsertDefaults as Ri,applyOnDelete as Ai,distinctValues as Ci,fanOutScalarCounts as gi,relationHooks as _i,resolveWith as Ii,runRowValidators as bi}from"./packem_shared/applyInsertDefaults-CVukTkQ5.mjs";import{D as Di,c as Oi,n as Pi,r as yi,s as Mi}from"./packem_shared/relay-CKEdfUjH.mjs";import{DEFAULT_MAX_RELAYS as ki,OwnerRelay as Ni,RelayMember as Bi,createRelayLink as Ui}from"./packem_shared/DEFAULT_MAX_RELAYS-Bc6PI-xy.mjs";import{createReplicaLink as wi,gateReplicaDispatch as qi,handleReplicaControl as vi}from"./packem_shared/createReplicaLink-DtqXBi-0.mjs";import{buildReprojectionMigration as Wi,countLegacyRows as Xi,reprojectableFields as Hi,reprojectionTables as Vi}from"./packem_shared/buildReprojectionMigration-B8aEpETD.mjs";import{RLS_UNWRAP_SYMBOL as Qi,RlsRequiredError as Yi,guardWriter as ji}from"./packem_shared/RLS_UNWRAP_SYMBOL-H6J96vgK.mjs";import{SCHEMA_HISTORY_MAX_VERSIONS as Zi,readSchemaHistory as $i,readSchemaVersion as es,recordSchemaVersion as rs}from"./packem_shared/SCHEMA_HISTORY_MAX_VERSIONS-CEwFjj-O.mjs";import{serializeSqlValue as as}from"./packem_shared/serializeSqlValue-DeoBMpZ2.mjs";import{buildSettings as is,isDevEnvironment as ss,readDeployInfo as ns}from"./packem_shared/buildSettings-CFkvTaHx.mjs";import{buildShapeDiff as ds}from"./packem_shared/buildShapeDiff-CdLJTijm.mjs";import{ShapeDiffCache as ms,createShapeDiffCache as ps,globalShapeReadKey as us}from"./packem_shared/ShapeDiffCache-iNO-hUiy.mjs";import{buildPokeFrames as fs,diffGlobalMembership as xs,encodeRowsPatch as Es,projectColumns as hs}from"./packem_shared/buildPokeFrames-WR-hp0mX.mjs";import{ShardRunner as Rs}from"./packem_shared/ShardRunner-CrveaPId.mjs";import{stubByName as Cs}from"./packem_shared/stubByName-DQSivmvb.mjs";import{runSocketPool as _s}from"./packem_shared/runSocketPool-CZJ2X9cF.mjs";import{MAX_SQL_ROWS as bs,assertReadonly as Ls,lintReadonlySql as Ds,runReadonlySql as Os}from"./packem_shared/MAX_SQL_ROWS-B4WlVI-e.mjs";import{BIGINT_KEY_DIGITS as ys,bigintSqlKey as Ms,decodeBigintSqlKey as Fs,decodeFloat64SqlKey as ks,float64SqlKey as Ns}from"./packem_shared/BIGINT_KEY_DIGITS-DE6yshOt.mjs";import{awaitWsDrain as Us,subscriptionFrames as Gs,subscriptionListDeltas as ws,trySendFrame as qs}from"./packem_shared/awaitWsDrain-DMcWBQ7I.mjs";import{mergeChangedKeys as Ks,recordChangedKeys as Ws,writeTouchesMemo as Xs}from"./packem_shared/mergeChangedKeys-DPKhen6e.mjs";import{createSystemReader as Vs}from"./packem_shared/createSystemReader-BSCxr8Qs.mjs";import{ConflictError as Qs}from"./packem_shared/ConflictError-C8GtJmjS.mjs";import{DEFAULT_TRANSACTION_LIMITS as js,TransactionHeadroomTracker as Js}from"./packem_shared/DEFAULT_TRANSACTION_LIMITS-D7p7Ys0M.mjs";import{hasTrigger as $s,runTriggers as en}from"./packem_shared/hasTrigger-CjlwI4le.mjs";import{isTtlExpired as on,nextTtlExpiry as an,selectExpiredIds as tn}from"./packem_shared/isTtlExpired-DNxmZA6e.mjs";import{VECTOR_BACKFILL_MAX_PAGES as nn,backfillVectorIndexes as ln}from"./packem_shared/VECTOR_BACKFILL_MAX_PAGES-DcQpf83n.mjs";import{c as cn,s as mn}from"./packem_shared/where-sql-BjY4rnqb.mjs";import{RELATION_EXISTS_KEY as un}from"./packem_shared/RELATION_EXISTS_KEY-wxgj6rSL.mjs";import{ADMIN_TOKEN_TABLE as fn}from"./packem_shared/ADMIN_TOKEN_TABLE-DfQ5osdI.mjs";import{RELAY_SIGNATURE_HEADER as En,siblingSecretOf as hn,signSiblingBody as Tn,verifySiblingBody as Rn}from"./packem_shared/RELAY_SIGNATURE_HEADER-CAfC4tqg.mjs";import{REPROJECTION_MIGRATION_PREFIX as Cn,reprojectionMigrationId as gn}from"./packem_shared/REPROJECTION_MIGRATION_PREFIX-Czcb6_mO.mjs";import{isInternalTableName as In}from"./packem_shared/isInternalTableName-BoljO2tP.mjs";import{quoteIdentifier as Ln}from"./packem_shared/quoteIdentifier-CObIFRhb.mjs";import{runShardMigrations as On}from"./packem_shared/runShardMigrations-BPFg3Ht6.mjs";import{stableStringify as yn,stableWireKey as Mn}from"@lunora/wire";export{Ta as ADMIN_FUNCTIONS,Ra as ADMIN_FUNCTION_PREFIX,fn as ADMIN_TOKEN_TABLE,f as AGGREGATE_SQL_FUNCTION,eo as AGG_COUNT,ro as AGG_KEY,oo as AGG_VALUE,k as AUDIT_LOG_TABLE,ys as BIGINT_KEY_DIGITS,Z as CDC_LOG_TABLE,$ as CDC_LOG_TABLE_SEQ_INDEX,ee as CDC_META_TABLE,Le as CLIENT_WATERMARK_TABLE,Me as COMMIT_SEQ_FIELD,Fe as COMMIT_SEQ_TABLE,tt as CURSOR_PREFIX,Ge as CompanionMemo,Qs as ConflictError,L as CountRlsUnsupportedError,Kr as DATA_MIGRATION_STATE_TABLE,Aa as DEFAULT_FANOUT_TOPIC_LIMIT,di as DEFAULT_MAX_RELATION_KEYS,ki as DEFAULT_MAX_RELAYS,Di as DEFAULT_PROMOTION_THRESHOLDS,js as DEFAULT_TRANSACTION_LIMITS,ao as DOC_COLUMN,Mo as DurableStreamRunner,Ca as FLAGS_FUNCTION_PREFIX,da as GEO_DEFAULT_PRECISION,We as GLOBAL_SHAPE_SNAPSHOT_TABLE,Ea as GlobalPollTick,je as IDEMPOTENCY_TABLE,qa as MAIL_RETENTION,va as MAIL_TABLE,Fo as MAX_DURABLE_STREAM_BYTES,ko as MAX_DURABLE_STREAM_CHUNKS,ga as MAX_PAGE_SIZE,bs as MAX_SQL_ROWS,za as NotFoundError,w as NotUniqueError,Ni as OwnerRelay,ht as QUEUE_TABLE,It as RANK_TIEBREAK,Ut as REACTOR_STATE_TABLE,oi as RELATED_DEFAULT_LIMIT,ai as RELATED_DEPTH_DECAY,ti as RELATED_MAX_DEPTH,ii as RELATED_MAX_LIMIT,un as RELATION_EXISTS_KEY,_a as RELATION_FUNCTION_PREFIX,En as RELAY_SIGNATURE_HEADER,Cn as REPROJECTION_MIGRATION_PREFIX,Qi as RLS_UNWRAP_SYMBOL,kt as ReactiveCache,Bi as RelayMember,Yi as RlsRequiredError,Vr as SCAN_DEP,dr as SCHEDULE_OUTBOX_TABLE,Zi as SCHEMA_HISTORY_MAX_VERSIONS,Ir as SEARCH_STATE_TABLE,Pr as SHAPE_POKE_CURSOR_TABLE,ms as ShapeDiffCache,Rs as ShardRunner,Js as TransactionHeadroomTracker,Xt as UNVOUCHABLE_DEP,nn as VECTOR_BACKFILL_MAX_PAGES,Eo as WORKERD_SQLITE_LIMITS,d as adminTokenExists,De as advanceClientWatermark,to as aggUpsertSql,x as aggregateSqlFunction,A as aggregateTableName,ke as allocateCommitSeq,N as appendAuditEntry,re as appendCdcChange,go as appendStreamChunk,oe as applyCdcChanges,Ri as applyInsertDefaults,Ai as applyOnDelete,it as applySelect,Ae as archiveCdcSegment,rt as armRestore,ci as assertFlatPredicate,q as assertNoExplicitUndefined,Ya as assertPatchAllowed,Ls as assertReadonly,mi as assertShapeShardable,v as assertStorableRowId,K as assertValidClientId,Us as awaitWsDrain,z as backfillAggregateIndexes,Q as backfillRankIndexes,Y as backfillSearchIndexes,j as backfillSearchIndexesForTable,ln as backfillVectorIndexes,Ms as bigintSqlKey,ca as boundingBoxCenter,ma as boundingBoxGeohashes,Qt as buildIndexRange,fs as buildPokeFrames,Wi as buildReprojectionMigration,st as buildSeekBeforeWhere,nt as buildSeekWhere,is as buildSettings,ds as buildShapeDiff,ae as bumpCdcEpoch,Ce as cdcArchiveRewound,te as cdcCanVouchFor,ie as cdcForkedError,se as cdcSeqLeavingRows,ne as cdcTouchesTables,le as cdcTrimmedError,_o as claimStreamRun,Oi as clampPromotionThresholds,Ka as clearCapturedMail,we as clearCompanionSignatures,or as clearMemoryTables,Tt as clearQueueMessages,C as coerceAggregateNumber,de as compactCdcDocs,cn as compileWhereSql,pi as composeReadPredicate,sr as computeRankPage,ui as containsRelationPredicate,Xi as countLegacyRows,pa as coveringGeohashes,c as createAdminTokenRecord,ve as createCompanionSync,zr as createDependencyTracker,Ia as createFanoutCounters,ba as createGlobalPollCounters,io as createIndexSql,Ht as createReadFootprint,Ui as createRelayLink,wi as createReplicaLink,ps as createShapeDiffCache,La as createShapeProbeCounters,W as createShardCtxDb,Vs as createSystemReader,ce as cursorBelowRetainedFloor,No as decideDurableAttach,Fs as decodeBigintSqlKey,lt as decodeCursor,ks as decodeFloat64SqlKey,cr as deferScheduleOutbox,Xe as deleteGlobalShapeSnapshot,He as deleteGlobalShapeSnapshotsForConnection,yr as deleteShapePokeCursor,Mr as deleteShapePokeCursorsForConnection,Io as deleteStreamRun,Qr as depKey,si as deriveRelationEdges,hi as describeRelationWrites,qo as diffExternalSource,xs as diffGlobalMembership,Ci as distinctValues,mr as dropScheduleOutbox,g as encodeAggregateKey,dt as encodeCursor,ua as encodeGeohash,bt as encodePartitionKey,Es as encodeRowsPatch,B as ensureAuditTable,Wa as ensureMailTable,Uo as envOptionalPositiveInt,Go as envPositiveInt,ct as equalityPinnedFields,o as exportShardRows,Da as facetColumn,gi as fanOutScalarCounts,Si as findManyPage,ni as findRelated,Oa as findStorageReferences,bo as finishStreamRun,Ns as float64SqlKey,_ as foldAggregateTally,pr as forgetScheduleOutbox,oa as ftsCompanionDdl,aa as ftsPurgeDocument,ta as ftsRowidMapName,ia as ftsUnmappedPage,sa as ftsWriteDocument,qi as gateReplicaDispatch,so as geoTableName,us as globalShapeReadKey,na as groupUnmappedRows,ji as guardWriter,vi as handleReplicaControl,ur as hasScheduleOutboxEntry,$s as hasTrigger,Sa as haversineMeters,a as importShardRows,Yt as indexKeysForRow,ss as isDevEnvironment,no as isFtsAvailable,In as isInternalTableName,Rt as isLossyBody,ar as isMemoryTable,Zt as isPushableWhere,fi as isRelationPredicate,Jo as isSoftDeleted,Zo as isSourceDue,on as isTtlExpired,Pa as isVacuousFilterClause,lo as jsonPath,co as jsonPathSql,jt as keysTouchRanges,Ko as liftSourceId,Ds as lintReadonlySql,m as listAdminTokens,Gt as listReactorStates,ya as listTables,Vt as markUnvouchableReads,Lt as matchesRankStaticWhere,E as matchesStaticWhere,Vo as materializeExternalRows,zo as materializeExternalRowsIncremental,tr as memoryTableNames,Ks as mergeChangedKeys,D as mergeWhere,me as migrateCdcLog,pe as migrateCdcMeta,Oe as migrateClientWatermark,Ne as migrateCommitSeq,Lo as migrateDurableStreams,Ve as migrateGlobalShapeSnapshot,Je as migrateIdempotency,wt as migrateReactorState,Sr as migrateScheduleOutbox,br as migrateSearchState,Fr as migrateShapePokeCursor,ue as minCdcReplayableSeq,Se as minCdcSeq,kr as minShapePokeCursor,Pi as nextPromotionState,an as nextTtlExpiry,h as normalizeCountArgument,X as normalizeIdStructurally,mt as normalizeOrderKeys,Wo as normalizeSourceDocument,Xo as normalizeSourceValue,pt as nullsFirstOf,ut as nullsOrderSuffix,ja as operatorFields,ho as param,fr as parkScheduleOutbox,t as parseExportShardArgs,i as parseImportShardArgs,Ja as patchDependsOnRow,O as planAggregateLookup,fa as pointInBoundingBox,xr as probeScheduleOutbox,hs as projectColumns,$o as pullExternalSourceIncrementalTick,ea as pullExternalSourceTick,mo as qualifiedJsonPath,po as qualifiedJsonPathSql,Ln as quoteIdentifier,Dt as rankKeyFromDoc,Ot as rankPivotConditionSql,Pt as rankTableName,Nt as reactiveCacheKey,qt as reactorNeedsRun,I as readAggregateValue,ge as readArchivedCdcChanges,U as readAuditLog,ot as readBookmark,Xa as readCapturedMail,_e as readCdcArchivedThrough,fe as readCdcChangeKeys,xe as readCdcChanges,Ee as readCdcCursor,he as readCdcEpoch,Pe as readClientWatermark,Be as readCommitSeq,ns as readDeployInfo,Er as readDueScheduleOutbox,hr as readDueScheduleOutboxEntry,Qo as readExternalSourceBaseline,ze as readGlobalShapeSnapshot,Ze as readIdempotent,Wr as readMigrationStatus,Za as readPatchField,At as readQueueMessageById,Ct as readQueueMessages,vt as readReactorState,Tr as readScheduleOutbox,Rr as readScheduleOutboxState,$i as readSchemaHistory,es as readSchemaVersion,Lr as readSearchBackfillState,Nr as readShapePokeCursor,Do as readStreamChunks,Oo as readStreamRun,Ma as readTablePage,Ha as recordCapturedMail,Ws as recordChangedKeys,Fa as recordFanoutPass,ka as recordGlobalPollPass,gt as recordQueueMessages,Ar as recordScheduleOutbox,rs as recordSchemaVersion,Na as recordShapeProbePass,_i as relationHooks,yi as relayCountFor,To as renderSql,Hi as reprojectableFields,gn as reprojectionMigrationId,Vi as reprojectionTables,Cr as requeueScheduleOutbox,$a as resolvePatch,yt as resolveRankPartition,nr as resolveRankSeekTuple,xi as resolveRelationPredicates,Ii as resolveWith,p as revokeAdminTokenRecord,uo as rowToDocument,Xr as runDataMigration,Jr as runDrizzle,Yo as runExternalSourceTick,Os as runReadonlySql,bi as runRowValidators,On as runShardMigrations,_s as runSocketPool,Zr as runSql,en as runTriggers,tn as selectExpiredIds,s as selectExportTables,P as selectIndexForAggregate,y as selectIndexForCount,M as selectIndexForGroupBy,Ba as selectMatchingIds,wr as selectShapeMembers,qr as selectShapeRows,as as serializeSqlValue,mn as serverInList,Mi as shapeRoutingKey,hn as siblingSecretOf,Tn as signSiblingBody,St as softDeleteScope,Mt as sortColumnName,Ro as sqliteInList,yn as stableStringify,Mn as stableWireKey,H as stripReservedPatchFields,Cs as stubByName,Gs as subscriptionFrames,ws as subscriptionListDeltas,Ua as summarizeFanoutTopics,Ga as summarizeSubscriptions,So as tableColumns,Yr as tableFromDepKey,T as throwingScheduler,ft as tiebreakDirectionFor,Te as trimCdcChanges,$e as trimIdempotent,gr as trimScheduleOutbox,Po as trimStreamRuns,fo as tryRowToDocument,qs as trySendFrame,Ao as unionAll,xt as uniqueIndexFields,n as validateImportRow,u as verifyAdminTokenDigest,Rn as verifySiblingBody,$t as whereFilter,ei as whereOfFilter,Ie as writeCdcArchivedThrough,Qe as writeGlobalShapeSnapshot,er as writeIdempotent,Kt as writeReactorState,Dr as writeSearchBackfillState,Br as writeShapePokeCursor,Ur as writeShapePokeCursors,Xs as writeTouchesMemo};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{LunoraError as l}from"@lunora/errors";import{i as j,R as k}from"./relation-operators-BEg-CvCH.mjs";import{mergeWhere as w}from"./CountRlsUnsupportedError-BvsDqfO2.mjs";import{isMemoryTable as N}from"./clearMemoryTables-aMRERF0w.mjs";import{normalizeOrderKeys as P,uniqueIndexFields as _,equalityPinnedFields as D,buildSeekWhere as K,decodeCursor as E,buildSeekBeforeWhere as B,softDeleteScope as I,encodeCursor as R}from"./CURSOR_PREFIX-6offuG6M.mjs";import{distinctValues as T}from"./applyInsertDefaults-CVukTkQ5.mjs";import{RELATION_EXISTS_KEY as W}from"./RELATION_EXISTS_KEY-wxgj6rSL.mjs";const $={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}},S=e=>k.has(e)?e:void 0,p=e=>{const t=S(e),r=t===void 0?void 0:$[t];if(!r)throw new l("INTERNAL",`unknown relation operator "${e}"`);return r},F=e=>e.kind==="one"?{clause:e.field,project:e.references}:{clause:e.references,project:e.field},q=5e3,m=Symbol("relation-key-overflow"),y=e=>Array.isArray(e)?e.map(t=>t??{}):[],C=e=>{if(e.length===1){const[t]=e;return t??{}}return e.length===0?{}:{AND:e}},b=e=>j(e),f=(e,t,r)=>{const n=t.tables[r]?.relationMap??{};return Object.keys(e).some(o=>{const s=e[o];return o==="AND"||o==="OR"?y(s).some(i=>f(i,t,r)):o==="NOT"?f(s??{},t,r):!!n[o]&&b(s)})},de=(e,t,r,n)=>{if(e&&f(e,t,r))throw new l("INTERNAL",`relation-crossing predicates are not supported in ${n}() — use them in findMany/findFirst or an RLS read policy`)},H=async(e,t,r,n)=>{const o=await u(t,e.table,n),{page:s}=await n.fetcher(e.table,{baseWhere:n.relationBaseWhere?.(e.table),relationBaseWhere:n.relationBaseWhere,where:o});return T(s,r)},z=(e,t,r)=>{throw new l("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)`)},Y=(e,t,r)=>{throw new l("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 s=await H(e,t,r,n);return s.length<=n.maxRelationKeys?s:o?m:z(e,s.length,n)},v=async(e,t,r,n)=>{const o=await u(t,e.table,n),s=n.maxRelationKeys+1,i=new Set;let a;for(;;){const d=await n.fetcher(e.table,{baseWhere:n.relationBaseWhere?.(e.table),cursor:a,limit:s,relationBaseWhere:n.relationBaseWhere,where:o});if(d.page.length>s)throw new l("INTERNAL",`relation predicate on "${e.table}" read ${String(d.page.length)} rows for a page of at most ${String(s)}; the fetcher did not honour the page limit`);for(const c of T(d.page,r))i.add(c);if(i.size>n.maxRelationKeys&&Y(e,i.size,n),d.isDone)return[...i];if(typeof d.continueCursor!="string")throw new l("INTERNAL",`relation predicate on "${e.table}" returned a page that is not final but has no cursor to continue from`);if(d.continueCursor===a)throw new l("INTERNAL",`relation predicate on "${e.table}" paged with a cursor that did not advance`);a=d.continueCursor}},X=async(e,t,r,n,o)=>{const s=p(e),{clause:i,project:a}=F(t),d=await Q(t,s.negateChild?{NOT:r}:r,a,n,o);return d===m?m:s.negated?s.nullDisjunct?{OR:[{[i]:{notIn:d}},{[i]:{isNull:!0}}]}:{[i]:{notIn:d}}:{[i]:{in:d}}},x=async(e,t,r,n)=>{const o=p(e),{from:s,table:i,to:a}=t.through,d=await v(t,o.negateChild?{NOT:r}:r,"_id",n),c=d.length===0?[]:await v({table:i},{[a]:{in:d}},s,n);return{_id:o.negated?{notIn:c}:{in:c}}},O=async(e,t,r,n,o)=>{const s=p(e),i=o.relationBaseWhere?.(t.table),a=s.negateChild?{NOT:r}:r,L={childWhere:await u(i?{AND:[i,a]}:a,t.table,o),negated:s.negated,parentTable:n,relation:t};return{[W]:L}},U=(e,t,r)=>{const n=S(e),o=n===void 0?void 0:$[n];if(o&&o.kind!==r.kind)throw new l("INTERNAL",`relation operator "${e}" requires a to-${o.kind} relation, but "${t}" is to-${r.kind}`)},V=async(e,t,r,n,o)=>{const s=[];for(const i of Object.keys(r)){U(i,e,t);const a=r[i]??{};if(t.through!==void 0){s.push(await x(i,t,a,o));continue}const d=o.canPushExists?.(t)??!1;if(d&&o.existsPushMode==="always"){s.push(await O(i,t,a,n,o));continue}const c=await X(i,t,a,o,d);c===m?s.push(await O(i,t,a,n,o)):s.push(c)}return C(s)},J=async(e,t,r,n)=>{if(e==="AND"||e==="OR"){const s=[];for(const i of y(t))s.push(await u(i,r,n));return{[e]:s}}if(e==="NOT")return{NOT:await u(t??{},r,n)};const o=n.schema.tables[r]?.relationMap?.[e];return o&&b(t)?V(e,o,t,r,n):{[e]:t}},u=async(e,t,r)=>{const n=[];for(const o of Object.keys(e))n.push(await J(o,e[o],t,r));return C(n)},G=async(e,t)=>!e||!f(e,t.schema,t.tableName)?e:u(e,t.tableName,{canPushExists:t.canPushExists,existsPushMode:t.existsPushMode??"auto",fetcher:t.fetcher,maxRelationKeys:t.maxRelationKeys??q,relationBaseWhere:t.relationBaseWhere,schema:t.schema}),A=100,h=e=>{if(e===void 0)return 0;let t=0;for(const[r,n]of Object.entries(e))r==="AND"||r==="OR"?t+=n.reduce((o,s)=>o+h(s),0):r==="NOT"?t+=h(n):typeof n=="object"&&n!==null?t+=Object.keys(n).filter(o=>o!=="isNull").length:t+=1;return t},ce=async(e,t,r)=>{const n=P(t.orderBy,e.shape,{pinned:D(t.where),uniqueBy:_(e.indexes,e.shape)}),o=typeof t.cursor=="string"?K(n,E(t.cursor)):void 0,s=typeof t.endCursor=="string"?B(n,E(t.endCursor)):void 0;if(s!==void 0&&h(o)+h(s)>A)throw new l("BAD_REQUEST",`findMany: an endCursor read with this orderBy binds ${String(h(o)+h(s))} cursor parameters, and a statement takes at most ${String(A)} — order by fewer fields`);let i=w(t.baseWhere,t.where);i=w(i,I(e.softDeleteMode,t.includeDeleted)),i=await G(i,{...r,relationBaseWhere:t.relationBaseWhere});for(const d of[o,s])d&&(i=i?{AND:[i,d]}:d);const a=typeof t.limit=="number"?Math.max(0,Math.floor(t.limit)):void 0;return{fetchLimit:a===void 0?void 0:a+1,limit:a,orderKeys:n,predicate:i}},le=(e,t)=>{const{endCursor:r,limit:n,omitContinueCursor:o,orderKeys:s}=t,i=n!==void 0&&e.length>n,a=i?e.slice(0,n):e;if(typeof r=="string"){let c;return a.length>=2?c=a[Math.floor(a.length/2)-1]:i&&([c]=a),{continueCursor:r,isDone:!0,page:a,splitCursor:c&&o!==!0?R(c,s):null,...i?{splitRequired:!0}:{}}}const d=a.at(-1);return{continueCursor:i&&d&&o!==!0?R(d,s):null,isDone:!i,page:a}},g=(e,t,r)=>{for(const n of e){const o=M(n,t,r);if(o)return o}},Z=(e,t,r,n)=>{if(e==="AND"||e==="OR")return g(y(t),r,n);if(e==="NOT")return g([t??{}],r,n);const o=r.tables[n]?.relationMap?.[e];if(!o||!b(t))return;const s=o.through===void 0?[o.table]:[o.table,o.through.table],i=s.find(d=>r.tables[d]?.shardMode?.kind==="shardBy");if(i!==void 0)return{kind:"shard",relation:e,target:i};const a=s.find(d=>N(r.tables[d]));return a!==void 0?{kind:"memory",relation:e,target:a}:g(Object.values(t),r,o.table)},M=(e,t,r)=>{for(const n of Object.keys(e)){const o=Z(n,e[n],t,r);if(o)return o}},ee=(e,t,r)=>{if(!(t.tables[r]?.shardMode?.kind==="global"||!f(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})},he=(e,t,r)=>{if(N(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=M(e,t,r);if(!n){ee(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{q as DEFAULT_MAX_RELATION_KEYS,de as assertFlatPredicate,he as assertShapeShardable,ce as composeReadPredicate,f as containsRelationPredicate,le as findManyPage,b as isRelationPredicate,G as resolveRelationPredicates};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{LunoraError as $}from"@lunora/errors";import{q as $t}from"./MAX_TOKEN_LENGTH-iFEGEcDL-DBPC6ZWl.mjs";import{S as qn,l as qe,s as Pn}from"./fts-companion-CE3EmIjk.mjs";import{decodeWire as Un,stableWireKey as Pt}from"@lunora/wire";import{sql as a}from"drizzle-orm";import{throwingScheduler as On,aggregateSqlFunction as Pe,normalizeCountArgument as Gn}from"./AGGREGATE_SQL_FUNCTION-C_ZipS9R.mjs";import{aggregateTableName as rt,encodeAggregateKey as it,readAggregateValue as st}from"./aggregateTableName-B_CtIQCS.mjs";import{mergeWhere as Q,CountRlsUnsupportedError as ct,selectIndexForGroupBy as jn,selectIndexForCount as Hn,selectIndexForAggregate as Kn}from"./CountRlsUnsupportedError-BvsDqfO2.mjs";import{backfillSearchIndexesForTable as Nn,searchIndexCoversTable as Qn}from"./backfillAggregateIndexes-Pk0KLrfk.mjs";import{backfillAggregateIndexes as ji,backfillRankIndexes as Hi,backfillSearchIndexes as Ki}from"./backfillAggregateIndexes-Pk0KLrfk.mjs";import{appendCdcChange as Vn,readCdcDocAtOrBefore as Jn}from"./CDC_LOG_TABLE-BFGgqai8.mjs";import{CDC_LOG_TABLE as Qi,applyCdcChanges as Vi,bumpCdcEpoch as Ji,cdcCanVouchFor as zi,cdcForkedError as Yi,cdcSeqLeavingRows as Xi,cdcTouchesTables as Zi,cdcTrimmedError as es,compactCdcDocs as ts,cursorBelowRetainedFloor as ns,minCdcReplayableSeq as os,minCdcSeq as rs,readCdcChangeKeys as is,readCdcChanges as ss,readCdcCursor as cs,readCdcEpoch as as,trimCdcChanges as ds}from"./CDC_LOG_TABLE-BFGgqai8.mjs";import{allocateCommitSeq as zn,COMMIT_SEQ_FIELD as Yn}from"./COMMIT_SEQ_FIELD-Da1DjGqo.mjs";import{createCompanionSync as Xn}from"./createCompanionSync-CEht4hXX.mjs";import{isMemoryTable as Ut}from"./clearMemoryTables-aMRERF0w.mjs";import{computeRankPage as Ot}from"./computeRankPage-xm-70mLy.mjs";import{SCAN_DEP as G,PRIMARY_READ as Zn}from"./SCAN_DEP-B4Uu4g7l.mjs";import{runSql as he,runDrizzle as K}from"./runDrizzle-RC09zZrh.mjs";import{p as eo,j as ht,D as ie,r as xe,W as to,k as le,b as Ue,A as at,a as Oe,m as ue,e as fe,s as no,t as oo,u as ro,i as io,q as Gt,h as pn,g as so}from"./do-sql-105TONaE.mjs";import{renderSql as gn,unionAll as yn,WORKERD_SQLITE_LIMITS as En}from"./WORKERD_SQLITE_LIMITS-B_4w7tzY.mjs";import{a as co,u as ao}from"./estimate-bytes-C-C35VXL.mjs";import{coveringGeohashes as lo,boundingBoxGeohashes as uo,haversineMeters as fo,pointInBoundingBox as ho}from"./GEO_DEFAULT_PRECISION-CqpQZ-J_.mjs";import{NotFoundError as wo}from"./NotFoundError-BhF7FeFr.mjs";import{resolvePatch as po,assertPatchAllowed as go,operatorFields as yo,readPatchField as jt}from"./assertPatchAllowed-CA_H466g.mjs";import{tiebreakDirectionFor as Eo,encodeCursor as wt,nullsOrderSuffix as mo,normalizeOrderKeys as Ht,uniqueIndexFields as $o,buildSeekWhere as Ro,decodeCursor as Kt,buildSeekBeforeWhere as So,softDeleteScope as Ae,applySelect as mn}from"./CURSOR_PREFIX-6offuG6M.mjs";import{rankTableName as Nt,sortColumnName as Qt,resolveRankPartition as vo,encodePartitionKey as _o,RANK_TIEBREAK as To,rankPivotConditionSql as Ao}from"./RANK_TIEBREAK-D3ye2GsL.mjs";import{UNVOUCHABLE_DEP as Vt}from"./UNVOUCHABLE_DEP-Ds9gxVqs.mjs";import{idIndexKey as Io,withUnknownIndexKeys as xo,indexKeysForRow as bo,buildIndexRange as Co}from"./buildIndexRange-BTChxh3k.mjs";import{r as Qe,j as be,c as Z,t as ze,i as Jt}from"./where-sql-BjY4rnqb.mjs";import{serializeSqlValue as Ce}from"./serializeSqlValue-DeoBMpZ2.mjs";import{quoteIdentifier as Me}from"./quoteIdentifier-CObIFRhb.mjs";import{whereOfFilter as Mo,isPushableWhere as Do}from"./isPushableWhere-BeYAOjUb.mjs";import{deriveRelationEdges as ko,findRelated as Lo}from"./RELATED_DEFAULT_LIMIT-CVqN4JEu.mjs";import{assertFlatPredicate as dt,findManyPage as Fo,resolveRelationPredicates as Bo,composeReadPredicate as Wo}from"./DEFAULT_MAX_RELATION_KEYS-BBtZ_jRj.mjs";import{describeRelationWrites as qo}from"./describeRelationWrites-omar6-u9.mjs";import{runRowValidators as Ge,transformOnlyDefinition as Po,applyInsertDefaults as pt,resolveWith as Uo,relationHooks as Oo,applyOnDelete as Go,fanOutScalarCounts as jo}from"./applyInsertDefaults-CVukTkQ5.mjs";import{guardWriter as Ho}from"./RLS_UNWRAP_SYMBOL-H6J96vgK.mjs";import{mayHoldProjectedValue as Ko}from"./BIGINT_KEY_DIGITS-DE6yshOt.mjs";import{createSystemReader as No}from"./createSystemReader-BSCxr8Qs.mjs";import{ConflictError as se}from"./ConflictError-C8GtJmjS.mjs";import{hasTrigger as zt,runTriggers as Qo}from"./hasTrigger-CjlwI4le.mjs";import{advanceClientWatermark as us,migrateClientWatermark as fs,readClientWatermark as hs}from"./CLIENT_WATERMARK_TABLE-De7z_OHV.mjs";import{IDEMPOTENCY_TABLE as ps,readIdempotent as gs,trimIdempotent as ys,writeIdempotent as Es}from"./IDEMPOTENCY_TABLE-COrgeP3O.mjs";import{runShardMigrations as $s}from"./runShardMigrations-BPFg3Ht6.mjs";import{selectShapeMembers as Ss,selectShapeRows as vs}from"./selectShapeMembers-Dqx_m7BF.mjs";const Vo=n=>{const r=atob(n),o=Uint8Array.from(r,s=>s.codePointAt(0)??0);return new TextDecoder().decode(o)},Jo=()=>new $("BAD_REQUEST","invalid cursor"),Yt=16,Xt=8,z=1024,Rt=(n,r)=>r.query(n),zo=(n,r)=>{if(n.length===0)return 0;let o=0;for(const[s,c]of r.entries()){const u=s===r.length-1;let g=0;for(const m of n)(u?m.startsWith(c):m===c)&&(g+=1);if(g===0)return 0;o+=g}return o},Yo=(n,r)=>{if(!r)return{exact:!0,lower:n,upper:n};const o=[...n].at(-1)??"",s=(o.codePointAt(0)??0)+1;if(s>=55296&&s<=57343||s>1114111)return{exact:!0,lower:n,upper:n};const c=n.slice(0,n.length-o.length);return{exact:!1,lower:n,upper:c+String.fromCodePoint(s)}},Xo=(n,r,o)=>{const s={eq:(c,u)=>{if(!n.definition.filterFields?.includes(c))throw new $("INTERNAL",`field "${c}" is not a filter field of search index "${n.indexName}" on table "${r}"`);if(n.filters.length>=Xt)throw new $("BAD_REQUEST",`search index "${n.indexName}" on table "${r}": at most ${String(Xt)} .eq() filters are supported per search query`);return n.filters.push({field:c,value:u}),s},search:(c,u)=>{const g=n;if(c!==g.definition.field)throw new $("INTERNAL",`search index "${g.indexName}" on table "${r}" indexes "${g.definition.field}", not "${c}"`);const m=Rt(u,o).length;if(m>Yt)throw new $("BAD_REQUEST",`search index "${g.indexName}" on table "${r}": at most ${String(Yt)} search terms are supported (got ${String(m)})`);return g.field=c,g.query=u,g.hasQuery=!0,s}};return s},Zo=n=>{if(n.length>z)throw new $("BAD_REQUEST",`more than ${String(z)} documents match this search — narrow it with filters or read it a page at a time with .paginate()`)},er=n=>Math.min(n.offset+n.numItems+1,z),tr=n=>btoa(`search:${String(n)}`),nr=n=>{let r;try{r=Vo(n)}catch{return}if(!r.startsWith("search:"))return;const o=Number(r.slice(7));return Number.isInteger(o)&&o>=0?o:void 0},or=n=>{if(typeof n.endCursor=="string")throw new $("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 $("BAD_REQUEST",`search pagination needs a finite numItems, got ${String(n.numItems)}`);const r=Math.max(0,Math.floor(n.numItems)),o=n.cursor?nr(n.cursor):0;if(o===void 0)throw Jo();if(o+r>=z)throw new $("BAD_REQUEST",`search pagination reaches the ${String(z)}-document limit (offset ${String(o)} + ${String(r)} requested) — a page must end below the cap so the probe row that answers \`hasMore\` still fits: retry with numItems ${String(Math.max(1,z-o-1))} or fewer, or narrow the query or the filters instead`);return{numItems:r,offset:o}},rr=(n,r)=>{const o=r.offset+r.numItems,s=r.numItems>0&&n.length>o;return{continueCursor:s?tr(o):null,isDone:!s,page:n.slice(r.offset,o)}},ir=n=>{if(n===void 0)return z+1;if(!Number.isFinite(n))return z;const r=Math.max(0,Math.floor(n));if(r>z)throw new $("BAD_REQUEST",`search returns at most ${String(z)} documents (asked for ${String(r)}) — narrow the query or paginate instead`);return r},$n=500,Rn=(n,r,o)=>{if(n!==void 0&&n!==Number.POSITIVE_INFINITY&&(!Number.isInteger(n)||n<0))throw o(`${r}: batch limit must be a non-negative integer`);return n??$n},Sn=(n,r,o,s)=>{if(n>r)throw s(`${o}: batch of ${String(n)} exceeds the limit of ${String(r)} (raise options.limit or chunk the call)`)},sr=32,cr=1024,vn=(n,r,o,s)=>{const c=`SELECT id, _creationTime, ${Me(ie)} FROM ${Me(n)}`,u=`ORDER BY ${o}${s===void 0?"":` LIMIT ${String(s)}`}`;return r===void 0?Qe(`${c} ${u}`):be(`${c} WHERE `,r,` ${u}`)},Ye={fieldRef:n=>Qe(ht(n)),rangeTypeGuard:(n,r)=>Qe(eo(n,r)),serialize:Ce},ar=n=>n===void 0?"":mo(n==="first"),_n=n=>{const r=n.map(o=>`${ht(o.field)} ${o.direction==="desc"?"DESC":"ASC"}${ar(o.nulls)}`);return n.some(o=>o.field==="_id"||o.field==="id")||r.push(`${ht("id")} ${Eo(n)==="desc"?"DESC":"ASC"}`),r.join(", ")},dr={"<":"lt","<=":"lte","=":"eq",">":"gt",">=":"gte"},Tn=n=>new Set(n.sqlConditions.filter(r=>r.comparator==="=").map(r=>r.field)),lr=n=>{const r=Tn(n);let o=0;for(;o<n.indexFields.length&&r.has(n.indexFields[o]??"");)o+=1;return n.indexFields.slice(o)},ur=(n,r)=>{const o=n.order,s=lr(n),{shape:c}=r;return s.length>0?Ht(s.map(u=>({[u]:o})),c,{pinned:Tn(n),uniqueBy:$o(r.indexes,c)}):Ht([{_creationTime:o}],c)},fr=(n,r,o,s)=>{const c=n.sqlConditions.map(u=>({[u.field]:{[dr[u.comparator]??"eq"]:u.value}}));if(o&&c.push(Ro(r,Kt(o))),s&&c.push(So(r,Kt(s))),c.length!==0)return c.length===1?c[0]:{AND:c}},hr=n=>{if(n.want!==void 0)return n.selective?Math.max(n.want,sr):n.want},gt=(n,r,o,s,c,u,g)=>{const m=ur(s,o),y=_n(m),d=[],{filters:b,want:_}=u;let v=u.cursor??void 0,x=hr(u);if(_===0)return{documents:d,orderKeys:m};for(;;){const W=Z(fr(s,m,v,u.endCursor),Ye,ze),q=vn(r,c&&W?be(W," AND ",c):c??W,y,x),B=he(n,q.text,...q.params).toArray();let U={};g(B.length);for(const j of B)if(U=xe(j),b.every(ee=>ee(U))&&d.push(U)===_)return{documents:d,orderKeys:m};if(x===void 0||B.length<x)return{documents:d,orderKeys:m};v=wt(U,m),x=Math.max(x,Math.min(x*2,cr))}},wr=(n,r,o,s,c,u,g,m)=>{const y=Math.max(0,Math.floor(c.numItems));if(typeof c.endCursor=="string"){const{documents:W,orderKeys:q}=gt(n,r,o,s,u,{cursor:c.cursor,endCursor:c.endCursor,filters:g.all,selective:g.selective,want:void 0},m),B=W.length>=2?W[Math.floor(W.length/2)-1]:void 0;return{continueCursor:c.endCursor,isDone:!0,page:W,splitCursor:B?wt(B,q):null}}const{documents:d,orderKeys:b}=gt(n,r,o,s,u,{cursor:c.cursor,filters:g.all,selective:g.selective,want:y+1},m),_=d.length>y,v=_?d.slice(0,y):d,x=v.at(-1);return{continueCursor:_&&x?wt(x,b):null,isDone:!_,page:v}},Xe=n=>{const r=new Map;return o=>{const s=r.get(o);if(s!==void 0)return s;const c=n(Me(o));return r.set(o,c),c}},we=Me(ie),pr=Xe(n=>`INSERT INTO ${n} (id, _creationTime, ${we}) VALUES (?, ?, ?)`),Zt=Xe(n=>`UPDATE ${n} SET ${we} = ? WHERE id = ? AND ${we} = ?`),gr=Xe(n=>`UPDATE ${n} SET _creationTime = ?, ${we} = ? WHERE id = ? AND ${we} = ?`),yr=Xe(n=>`DELETE FROM ${n} WHERE id = ? AND ${we} = ?`),Er="SELECT changes() AS changed",en=new Map,mr="",$r=n=>{const r=JSON.stringify(n),o=en.get(r);if(o!==void 0)return o;const s=n.map(u=>a`SELECT ${a.raw(`'${u.replaceAll("'","''")}'`)} AS __t__, id, _creationTime, ${a.identifier(ie)} FROM ${a.identifier(u)} WHERE id = ${mr}`),{sql:c}=gn("sqlite",a`${yn(s)} LIMIT 1`);return en.set(r,c),c},Rr=(n,r)=>r.map(()=>n),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,vr=n=>{if(!Sr.test(n))throw new $("INTERNAL",`invalid clientId ${JSON.stringify(n)}: a client-supplied row id must be a UUID`)},yt=n=>{if(n.includes("\0"))throw new $("BAD_REQUEST",`invalid row id ${JSON.stringify(n)}: a row id cannot hold a NUL character (U+0000)`)},_r=(n,r,o,s)=>{if(o!==!0)return;const c=n!==void 0&&"serverDefault"in(n.shape._id?._meta?.column??{});for(const u of r){const g=c?pt(n,u,s)._id:u._id;typeof g=="string"&&yt(g)}},tn=50,je=Math.floor(En.boundParams/3),nn=En.boundParams,Tr=128,Ve=n=>new $("BATCH_LIMIT_EXCEEDED",n,{status:400}),He=(n,r,o)=>{Sn(n,Rn(r,o,Ve),o,Ve)},on=async(n,r,o,s,c)=>{const u=Rn(s,c,Ve),{page:g}=await n.findMany(r,Number.isFinite(u)?{limit:u+1,omitContinueCursor:!0,where:o}:{where:o});return g.length>u&&Sn(Math.max(await n.count(r,{where:o}),g.length),u,c,Ve),g},Ar=n=>{const r={eq:(o,s)=>(n.sqlConditions.push({comparator:"=",field:o,value:s}),r),gt:(o,s)=>(n.sqlConditions.push({comparator:">",field:o,value:s}),r),gte:(o,s)=>(n.sqlConditions.push({comparator:">=",field:o,value:s}),r),lt:(o,s)=>(n.sqlConditions.push({comparator:"<",field:o,value:s}),r),lte:(o,s)=>(n.sqlConditions.push({comparator:"<=",field:o,value:s}),r)};return r},Ir=n=>Math.max(n,z),An=(n,r)=>{const o=n.filters.map(s=>a`${fe(s.field)} = ${Ce(s.value)}`);return r&&o.push(r),o},xr=(n,r,o,s,c)=>{const u=Rt(o.query,$t(o.definition.language));if(u.length===0)return[];const g=qn(r,o.indexName),m=`${g}__vocab`,y=u.length-1,d=u.map((q,B)=>{const U=Yo(q,B===y),j=U.exact?a`${a.identifier("term")} = ${U.lower}`:a`${a.identifier("term")} >= ${U.lower} AND ${a.identifier("term")} < ${U.upper}`;return a`SELECT ${a.identifier("doc")}, ${a.raw(String(B))} AS ${a.identifier("__term__")}, COUNT(*) AS ${a.identifier("__n__")} FROM ${a.identifier(m)} WHERE ${j} GROUP BY ${a.identifier("doc")}`}),b=u.map((q,B)=>a`SUM(CASE WHEN u.${a.identifier("__term__")} = ${a.raw(String(B))} THEN u.${a.identifier("__n__")} ELSE 0 END)`),_=a`SELECT f.${a.identifier(qe)} AS ${a.identifier(qe)}, ${a.join(b,a` + `)} AS ${a.identifier("__score__")} FROM (${yn(d)}) u JOIN ${a.identifier(g)} f ON f.rowid = u.${a.identifier("doc")} GROUP BY f.${a.identifier(qe)} HAVING ${a.join(b.map(q=>a`${q} > 0`),a` AND `)}`,v=An(o,c);let x=a`SELECT m.id, m._creationTime, m.${a.identifier(ie)}, s.${a.identifier("__score__")} AS ${a.identifier("__score__")} FROM (${_}) s JOIN ${a.identifier(r)} m ON m.id = s.${a.identifier(qe)}`;v.length>0&&(x=a`${x} WHERE ${a.join(v,a` AND `)}`),x=a`${x} ORDER BY s.${a.identifier("__score__")} DESC, m._creationTime DESC, m.id ASC LIMIT ${a.raw(String(s))}`;const W=[];for(const q of K(n,x)){const B=pn(q);if(B){const U=q.__score__;W.push({document:B,score:typeof U=="number"?U:Number(U??0)})}}return W},br=(n,r,o,s,c)=>{const u=$t(o.definition.language),g=Rt(o.query,u);if(g.length===0)return[];const m=An(o,c);let y=a`SELECT id, _creationTime, ${a.identifier(ie)} FROM ${a.identifier(r)}`;m.length>0&&(y=a`${y} WHERE ${a.join(m,a` AND `)}`),y=a`${y} ORDER BY _creationTime DESC, id ASC LIMIT ${a.raw(String(Ir(s)))}`;const d=K(n,y).toArray(),b=[];for(const _ of d){const v=pn(_);if(!v)continue;const x=zo(Pn(v,o.definition),g);x>0&&b.push({creationTime:typeof v._creationTime=="number"?v._creationTime:0,doc:v,id:typeof v._id=="string"?v._id:"",score:x})}return b.sort((_,v)=>v.score-_.score||v.creationTime-_.creationTime||_.id.localeCompare(v.id)),b.slice(0,s).map(_=>({document:_.doc,score:_.score}))},lt=(n,r,o,s)=>{if(!Number.isFinite(n.lat)||n.lat<-90||n.lat>90||!Number.isFinite(n.lng)||n.lng<-180||n.lng>180)throw new $("BAD_REQUEST",`geo index "${s}" on table "${o}": ${r} must have a finite lat in [-90, 90] and lng in [-180, 180]`)},Cr=(n,r)=>{const o=n,s={near:(c,u)=>{if(o.within)throw new $("INTERNAL",`geo index "${o.indexName}" on table "${r}": call .near() or .within(), not both`);if(lt(c,".near() point",r,o.indexName),!Number.isFinite(u)||u<=0)throw new $("BAD_REQUEST",`geo index "${o.indexName}" on table "${r}": .near() radiusMeters must be a finite number > 0, got ${String(u)}`);return o.near={point:{lat:c.lat,lng:c.lng},radiusMeters:u},s},within:c=>{if(o.near)throw new $("INTERNAL",`geo index "${o.indexName}" on table "${r}": call .near() or .within(), not both`);if(lt(c.sw,".within() sw corner",r,o.indexName),lt(c.ne,".within() ne corner",r,o.indexName),c.sw.lat>c.ne.lat)throw new $("BAD_REQUEST",`geo index "${o.indexName}" on table "${r}": .within() corners are transposed (sw.lat > ne.lat)`);if(c.sw.lng>c.ne.lng)throw new $("BAD_REQUEST",`geo index "${o.indexName}" on table "${r}": .within() box crosses the antimeridian (sw.lng > ne.lng), which is not supported — split it into two boxes at ±180 and union the results`);return o.within={ne:{lat:c.ne.lat,lng:c.ne.lng},sw:{lat:c.sw.lat,lng:c.sw.lng}},s}};return s},Mr=(n,r)=>{const o=n[r];if(o===null||typeof o!="object")return;const{lat:s,lng:c}=o;return typeof s=="number"&&typeof c=="number"?{lat:s,lng:c}:void 0},Dr=(n,r)=>{const o=Mr(n,r.definition.field);if(!o)return;const s=typeof n._creationTime=="number"?n._creationTime:0;if(r.near){const c=fo(r.near.point,o);return c<=r.near.radiusMeters?{creationTime:s,distance:c}:void 0}return ho(o,r.within)?{creationTime:s,distance:0}:void 0},kr=(n,r,o,s)=>{if(!o.near&&!o.within)throw new $("INTERNAL",`geo index "${o.indexName}" on table "${r}": call .near(point, radius) or .within(box)`);const c=o.near?lo(o.near.point,o.near.radiusMeters):uo(o.within),u=so(r,o.indexName),g=c.map(_=>a`(g.${a.identifier("__geohash__")} >= ${_} AND g.${a.identifier("__geohash__")} < ${`${_}{`})`),m=[a`(${a.join(g,a` OR `)})`];s&&m.push(s);const y=a`SELECT m.id, m._creationTime, m.${a.identifier(ie)} FROM ${a.identifier(u)} g JOIN ${a.identifier(r)} m ON m.id = g.${a.identifier("__id__")} WHERE ${a.join(m,a` AND `)}`,d=K(n,y).toArray(),b=[];for(const _ of d){const v=xe(_),x=v?Dr(v,o):void 0;v&&x&&b.push({creationTime:x.creationTime,distance:x.distance,doc:v})}return b.sort((_,v)=>_.distance-v.distance||v.creationTime-_.creationTime),b},In=(n,r,o,s)=>{const c=[];for(const u of n)if(r.every(g=>g(s(u)))&&(c.push(u),typeof o=="number"&&c.length>=o))break;return c},Lr=(n,r,o,s,c,u=()=>{})=>{const g=o.within!==void 0,m=kr(n,r,o,c).map(y=>({distanceMeters:g?null:y.distance,document:y.doc}));return u(m.length),typeof s=="number"?m.slice(0,Math.max(0,Math.floor(s))):m},rn=(n,r,o,s,c,u,g=()=>{})=>{const{geo:m}=o;if(!m)throw new $("INTERNAL","runGeoTerminalScored called without a staged geo query");const y=c.length>0,d=Lr(n,r,m,y?void 0:u,s,g);return y?In(d,c,u,b=>b.document):d},sn=(n,r,o)=>{const s=n.shape[r];if(s!==void 0&&Ko(s))throw new $("BAD_REQUEST",`${o}: "${r}" may hold an order-preserving key rather than a value SQL can reduce or group — declare an aggregateIndex covering this (by, field, op) so the maintained companion answers it instead (its running total is a REAL, so it stays exact only while the total is inside 2^53)`)},Fr=n=>{let r=0;const o=[],s={...Ye,relationExists:c=>{const{childWhere:u,negated:g,parentTable:m,relation:y}=c,d=`__rel_${String(r)}`,b=o.at(-1)??m;r+=1,n(y.table,G);const _=y.kind==="one"?y.field:y.references,v=y.kind==="one"?y.references:y.field,x=Qe(`${Gt(d,v)} = ${Gt(b,_)}`);o.push(d);const W=Z(u,s,ze);o.pop();const q=W===void 0?x:be(x," AND ",W),B=be("EXISTS (SELECT 1 FROM ",Jt(y.table)," AS ",Jt(d)," WHERE ",q,")");return g?be("NOT ",B):B}};return s};class Br extends ${constructor(r="unique() found more than one matching document"){super("NOT_UNIQUE",r,{name:"NotUniqueError"})}}const Wr=/\s/u,qr=String.fromCodePoint(0),cn=(n,r,o)=>{if(!n.tables[r])throw new $("INTERNAL",`unknown table: ${r}`);return typeof o!="string"||o.length===0||Wr.test(o)||o.includes(qr)?null:o},xn=(n,r,o,s=()=>{},c=()=>{},u=()=>{},g)=>{const m=r.tables[o];if(!m)throw new $("INTERNAL",`unknown table: ${o}`);const y=Ae(m.softDeleteMode,void 0),d=g??{indexFields:[],indexName:void 0,inMemoryFilters:[],order:"asc",sqlConditions:[],verifyFilters:[]},b=()=>{const S=Q(y,d.pushedWhere);return S?Z(S,ue):void 0},_=()=>{const S=Q(y,d.pushedWhere);return S?Z(S,Ye,ze):void 0},v=()=>[...d.inMemoryFilters,...d.verifyFilters];let x=0;const W=S=>{const{search:M}=d;if(!M)throw new $("INTERNAL","runSearchFetch called without a staged search");Nn(ro(n),o,m);const L=d.inMemoryFilters.length>0,F=ir(L?void 0:S),k=io(n);if(k&&!Qn(n,o,M.definition))throw new $("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 pe=b(),te=k?xr(n,o,M,F,pe):br(n,o,M,F,pe);!L&&S===void 0&&Zo(te);const ge=v();return x=te.length,ge.length>0?In(te,ge,S,J=>J.document):te},q=S=>W(S).map(M=>M.document),B=S=>{const M=or(S);return rr(q(er(M)),M)},U=()=>{if(d.search||d.geo||d.indexName===void 0){c(void 0);return}c(Co(o,d.indexName,d.indexFields,d.sqlConditions,Ce))},j=S=>{U();let M=0;const L=(()=>{if(d.search){const F=q(S);return M=x,F}return d.geo?rn(n,o,d,b(),v(),S,F=>{M=F}).map(F=>F.document):gt(n,o,m,d,_(),{filters:v(),selective:d.inMemoryFilters.length>0,want:S===void 0?void 0:Math.max(0,Math.floor(S))},F=>{M+=F}).documents})();return u(Math.max(M,L.length)),L},ee=()=>{if(!d.search&&!d.geo)throw new $("INTERNAL",`ctx.db.query("${o}").collectWithScores() requires a staged .withSearchIndex(...) or .withGeoIndex(...)`);U();let S=0;const M=(()=>{if(d.search){const L=W(void 0);return S=x,L}return rn(n,o,d,b(),v(),void 0,L=>{S=L})})();return u(Math.max(S,M.length)),M},N={async*[Symbol.asyncIterator](){const S=xn(n,r,o,s,c,u,{...d,indexFields:[...d.indexFields],inMemoryFilters:[...d.inMemoryFilters],sqlConditions:[...d.sqlConditions],verifyFilters:[...d.verifyFilters]});if(d.search){yield*await S.collect();return}let M;for(;;){const L=await S.paginate({cursor:M??null,numItems:Tr});if(yield*L.page,L.isDone||L.continueCursor===null)return;M=L.continueCursor}},async collect(){return j(void 0)},async collectWithScores(){return ee()},filter(S){const M=Mo(S);return M!==void 0&&Do(M,m.shape)?(d.pushedWhere=Q(d.pushedWhere,M),d.verifyFilters.push(S)):d.inMemoryFilters.push(S),N},async first(){return j(1)[0]??null},order(S){return d.order=S==="desc"?"desc":"asc",N},async paginate(S){let M=0;if(U(),d.search){const F=B(S);return u(F.page.length),F}if(d.geo)throw new $("INTERNAL","pagination is not supported on geo queries; use .take(n) or .collect()");const L=wr(n,o,m,d,S,_(),{all:v(),selective:d.inMemoryFilters.length>0},F=>{M+=F});return u(Math.max(M,L.page.length)),L},async take(S){return j(S)},async unique(){const S=j(2);if(S.length>1)throw new Br(`unique() on table "${o}" matched ${String(S.length)} documents; expected at most one`);return S[0]??null},withGeoIndex(S,M){const L=(m.geoIndexes??[]).find(k=>k.name===S);if(!L)throw new $("INTERNAL",`unknown geo index "${S}" on table "${o}"`);s(o,S,"geo");const F={definition:L,indexName:S};if(d.geo=F,M(Cr(F,o)),!F.near&&!F.within)throw new $("INTERNAL",`geo index "${S}" on table "${o}" requires a .near(point, radius) or .within(box) call`);return N},withIndex(S,M){const L=m.indexes.find(F=>F.name===S);if(!L)throw new $("INTERNAL",`unknown index "${S}" on table "${o}"`);return s(o,S,"index"),d.indexName=S,d.indexFields=L.fields,M&&M(Ar(d)),N},withSearchIndex(S,M){const L=(m.searchIndexes??[]).find(k=>k.name===S);if(!L)throw new $("INTERNAL",`unknown search index "${S}" on table "${o}"`);s(o,S,"search");const F={definition:L,field:L.field,filters:[],hasQuery:!1,indexName:S,query:""};if(d.search=F,M(Xo(F,o,$t(L.language))),!F.hasQuery)throw new $("INTERNAL",`search index "${S}" on table "${o}" requires a .search(field, query) call`);return N}};return N},ut=(n,r,o,s)=>{const c=o;for(const[u,g]of oo(n)){if(g.serverDefault){u in r&&(c[u]=g.serverDefault({auth:s}));continue}g.onUpdateFn&&!(u in r)&&(c[u]=g.onUpdateFn())}},an=5,dn=(n,r)=>{for(const o of Object.keys(r))if(r[o]===void 0)throw new $("INTERNAL",`Cannot ${n} field '${o}' to undefined — use null to clear a nullable field, or omit the key to leave it unchanged.`)},ln=["_commitSeq","_creationTime","_id"],Ke=n=>ln.some(r=>r in n)?Object.fromEntries(Object.entries(n).filter(([r])=>!ln.includes(r))):n,Pr=/unique constraint failed/i,Ur=n=>n instanceof Error&&Pr.test(n.message),Or=/string or blob too big/iu,Gr=(n,r)=>{if(!(!(n instanceof Error)||!Or.test(n.message)))throw new $("PAYLOAD_TOO_LARGE",`document is too large to store in "${r}": a single row cannot exceed the storage engine's per-row ceiling (2 MB on a Durable Object's SQLite). The limit is on the STORED bytes, which are UTF-8, and v.bytes()/v.bigint() columns are stored twice on a shard-local table. Keep the payload in R2 (ctx.storage) and store a reference on the row.`)},Et=(n,r,o,s)=>{try{he(n,o,...s)}catch(c){throw Ur(c)?new se(`unique constraint violation on "${r}"`,"unique"):(Gr(c,r),c)}},Ne=(n,r,o,s)=>{if(Et(n,r,o,s),he(n,Er).one().changed===0)throw new se(`optimistic concurrency conflict on "${r}" — the row changed during this mutation; refetch and retry`,"occ")},un=(n,r,o,s,c,u,g)=>{const m=[];for(let _=0;_<o.length+1;_+=1){const v=o[_],x=s[_],W=x?.direction==="desc"?"desc":"asc",q=v===void 0||x===void 0?a`${a.identifier(To)} < ${g}`:Ao(v,u[_],W,!1);if(q===void 0)continue;const B=[];for(let j=0;j<_;j+=1)B.push(a`${a.identifier(o[j])} IS ${u[j]}`);B.push(q);const[U]=B;m.push(B.length===1&&U!==void 0?U:a`(${a.join(B,a` AND `)})`)}const y=m.length>0?a.join(m,a` OR `):a`1 = 0`,d=K(n,a`SELECT COUNT(*) AS c FROM ${a.identifier(r)} WHERE ${a.identifier("__partition__")} = ${c} AND (${y})`).one(),b=K(n,a`SELECT COUNT(*) AS c FROM ${a.identifier(r)} WHERE ${a.identifier("__partition__")} = ${c}`).one();return{before:d.c,total:b.c}},jr=n=>{const r=new Map;for(const[s,c]of Object.entries(n.tables))for(const u of Object.values(c.relationMap??{}))u.kind==="one"&&(u.onDelete==="cascade"||u.onDelete==="set null")&&r.set(u.table,[...r.get(u.table)??[],{holder:s,op:u.onDelete==="cascade"?"delete":"update"}]);const o=s=>{const c=new Set,u=[s];for(let g=u.pop();g!==void 0;g=u.pop())for(const{holder:m,op:y}of r.get(g)??[]){if(m===s||zt(n,m,y))return!0;c.has(m)||(c.add(m),u.push(m))}return!1};return new Set(Object.entries(n.tables).filter(([s,c])=>c.shardMode?.kind==="global"||zt(n,s,"delete")||o(s)).map(([s])=>s))},Hr=n=>{const r=new Map;for(const[o,s]of Object.entries(n.tables))s.softDeleteMode&&r.set(o,s.softDeleteMode.field);return r},ft=new WeakMap,Kr=(n,r)=>{let o=ft.get(r.tables);if(!ft.has(r.tables)){const c=Object.keys(r.tables).map(u=>u.replaceAll(/[$()*+.?[\\\]^{|}]/gu,String.raw`\$&`));o=c.length===0?void 0:new RegExp(`"(${c.join("|")})"`,"gu"),ft.set(r.tables,o)}if(o===void 0)return;const s=new Set;for(const c of n.matchAll(o))s.add(c[1]);return s.size===1?[...s][0]:void 0},Nr=(n,r,o)=>{for(const s of n){const c=s,u=c?.[ie];if(typeof u=="string"){const g=c?.id,m=ao(u);typeof g!="string"?r.recordReadBytes(m):o===void 0?r.recordDocumentRead(`${g}\0${String(m)}`,m):r.recordDocumentRead(`${o}\0${g}`,m)}}},Qr=(n,r,o)=>{if(r===void 0)return n;const s=(c,...u)=>{const g=n.exec(c,...u),m=g.one.bind(g),y=g[Symbol.iterator].bind(g),d=o===void 0?void 0:Kr(c,o);let b=!1;const _=v=>{Nr(v,r,d)};return g.toArray=()=>{const v=[];for(const x of{[Symbol.iterator]:y})_([x]),v.push(x);return v},g.one=()=>{b=!0;try{const v=m();return _([v]),v}finally{b=!1}},g[Symbol.iterator]=function*(){for(const x of{[Symbol.iterator]:y})b||_([x]),yield x},g};return new Proxy(n,{get:(c,u)=>u==="exec"?s:u===to?c:Reflect.get(c,u,c)})},Vr=new Map([["findFirst","rows"],["findFirstOrThrow","rows"],["findMany","page"],["get","rows"],["lookupById","lookup"],["rankPage","page"]]),Jr=new Map([["collect","rows"],["collectWithScores","scored"],["first","rows"],["paginate","page"],["take","rows"],["unique","rows"]]),Ie=(n,r,o)=>{if(typeof n!="object"||n===null)return;const s=co(n);if(s===void 0)return;const c=n._id;typeof c=="string"?o.recordDocumentRead(`global\0${r}\0${c}`,s):o.recordReadBytes(s)},Je=(n,r,o,s)=>{if(typeof n!="object"||n===null)return;const c=n;switch(r){case"lookup":{Ie(c.row,typeof c.tableName=="string"?c.tableName:o,s);return}case"page":{for(const u of c.page??[])Ie(u,o,s);return}case"rows":{for(const u of Array.isArray(n)?n:[n])Ie(u,o,s);return}default:for(const u of Array.isArray(n)?n:[])Ie(u.document,o,s)}},bn=(n,r,o)=>new Proxy(n,{get:(s,c)=>{const u=Reflect.get(s,c,s);if(typeof u!="function")return u;if(c===Symbol.asyncIterator)return async function*(){for await(const y of Reflect.apply(u,s,[]))Ie(y,r,o),yield y};const g=Jr.get(c);return(...m)=>{const y=Reflect.apply(u,s,m);return g!==void 0?Promise.resolve(y).then(d=>(Je(d,g,r,o),d)):typeof y=="object"&&y!==null&&!(y instanceof Promise)?bn(y,r,o):y}}}),zr=new Set(["findFirst","findFirstOrThrow","findMany"]),Yr=n=>{const r=n[1],o=r?.select;if(!Array.isArray(o))return;const s=Object.fromEntries(Object.entries(r).filter(([g])=>g!=="select")),c=s.with,u=g=>mn(g,o,c);return{args:[n[0],s,...n.slice(2)],project:(g,m)=>typeof g!="object"||g===null?g:m==="page"?{...g,page:u(g.page)}:u([g])[0]}},fn=256,mt=4096,Xr=1024*1024,Zr=async(n,r,o,s)=>{const c=r[1]??{},u=[];let{cursor:g}=c,m=fn,y=0;for(;;){const d=await n([r[0],{...c,cursor:g,limit:m},...r.slice(2)]);if(Array.isArray(d))return Je(d,"rows",o,s),[...u,...d];const b=s.headroom().readBytes;if(Je(d,"page",o,s),u.push(...d.page),d.isDone||typeof d.continueCursor!="string")return{continueCursor:null,isDone:!0,page:u};g=d.continueCursor,y+=s.headroom().readBytes-b,m=y>0?Math.min(mt,Math.max(fn,Math.floor(Xr*u.length/y))):mt}},ei=(n,r)=>n===void 0||r===void 0?n:new Proxy(n,{get:(o,s)=>{const c=Reflect.get(o,s,o);if(typeof c!="function")return c;if(s==="query")return(...g)=>bn(Reflect.apply(c,o,g),String(g[0]),r);const u=Vr.get(s);return u===void 0?c:async(...g)=>{const m=zr.has(s)?Yr(g):void 0;let y=m?.args??g;const d=String(g[0]),b=y[1],_=s==="findMany"&&typeof b?.endCursor=="string",v=s==="findMany"&&typeof b?.limit!="number"&&!_;if(_&&typeof b.limit!="number"&&(y=[y[0],{...b,limit:mt},...y.slice(2)]),v){const W=await Zr(q=>Reflect.apply(c,o,q),y,d,r);return m===void 0?W:m.project(W,u)}const x=await Reflect.apply(c,o,y);return Je(x,u,d,r),m===void 0?x:m.project(x,u)}}}),hn=new WeakMap,wn=new WeakMap,ti=n=>{const{baselineSeq:r,onStalePatchDropped:o}=n,{headroom:s}=n,c=hn.get(n)??{value:void 0},u=wn.get(n)??{value:0};let g;const m=()=>{if(g===void 0){const e={...n,enforceRls:!1,headroom:void 0};hn.set(e,c),wn.set(e,u),g=ti(e)}return g},y=Qr(n.sql,s,n.schema),{schema:d}=n,b=n.broadcast??(()=>{}),_=(e,t)=>{if(!Object.hasOwn(d.tables,e))throw new $("BAD_REQUEST",`${t}: "${e}" is not a table in this schema`)},v=ko(d),x=new Map;for(const e of v){const t=i=>(d.tables[i]?.shardMode?.kind??"root")==="root";!e.array&&t(e.sourceTable)&&t(e.targetTable)&&x.set(e.sourceTable,[...x.get(e.sourceTable)??[],e])}const W=(e,t,i)=>{for(const l of x.get(e)??[]){const w=t[l.column];if(typeof w!="string"||i?.[l.column]===w||l.targetTable===e&&t._id===w)continue;if(K(y,a`SELECT 1 FROM ${a.identifier(l.targetTable)} WHERE id = ${w} LIMIT 1`).toArray().length===0)throw new $("VALIDATION_ERROR",`${l.name} references ${l.targetTable} row "${w}", which does not exist`)}},q=qo(d,n.inTransaction),B=jr(d),U=Hr(d),j=()=>n.inTransaction?.()===!0,ee=e=>d.tables[e]?.commitOrderedMode!==!0?{}:((c.value===void 0||!j())&&(c.value=zn(y)),{[Yn]:c.value}),N=(e,...t)=>{const i=d.tables[e]?.indexes??[],l=[];let w;for(const p of t)p&&(typeof p._id=="string"&&p._id!==w&&(w=p._id,l.push(Io(w))),l.push(...xo(i,bo(i,p,Ce))));return l.length>0?l:void 0},S=n.onRead??(()=>{}),M=e=>{Ut(d.tables[e])&&S(Vt,Vt)},L=n.onReadRange??(e=>{S(e.table,G)}),F=e=>{M(e.table),L(e)},k=(e,t,i)=>{t!==void 0&&(i===!0||t!==G)&&s?.recordRead(1),M(e),S(e,t,i)},pe=(e,t)=>{const i=e.row._id;k(e.tableName,typeof i=="string"?i:t,typeof i=="string")},te=n.onIndexUse??(()=>{}),ge=n.onWrite??(()=>{}),J=e=>{s?.recordWrite(e)},ye=async e=>{J(e.doc),await ge(e)},{cache:Ee}=n,me=n.clock??(()=>Date.now()),St=n.idGenerator??(()=>crypto.randomUUID()),vt=n.scheduler??On,$e=ei(n.globalDb,s),ce=n.auth??{identity:null,userId:null},_t=n.cdc??!1,Ze=vt,Cn=No({scheduler:typeof Ze.list=="function"&&typeof Ze.get=="function"?Ze:void 0,storage:n.storage}),Re=(e,t,i,l)=>{_t&&!Ut(d.tables[e])&&Vn(y,me(),e,t,i,l)},Tt=(e,t,i,l)=>{const w=d.tables[e];if(w?.dropStalePatchesMode!==!0||!_t)return!1;const p=r?.();if(p===void 0)return!1;const f=Jn(y,e,t,p);if(f===void 0)return!1;const h=yo(w,i);return Object.keys(Ke(i)).some(E=>!h.has(E)&&Pt(jt(f,E))!==Pt(jt(l,E)))},ae=e=>d.tables[e]?.shardMode?.kind==="global",At=(e,t)=>{if(ae(e)){if(!$e)throw new $("INTERNAL",`cross-backend ${t} for global table '${e}' requires a globalDb writer — pass one to createShardCtxDb({ globalDb })`);return $e}return O},et=e=>At(e,"cascade"),H=(e,t)=>{if(ae(e)){if(!$e)throw new $("INTERNAL",`${t} on global table '${e}' requires a globalDb writer — pass one to createShardCtxDb({ globalDb })`);return $e}},It=async(e,t,i,l,w)=>{w&&J(i);const p=await e.insert(t,i,l);return b({key:p,op:"insert",row:{...i,_id:p},table:t}),p},xt=(e,t)=>At(e,"relation load").findMany(e,t),bt=(e,t)=>(ae(e)&&k(e,G),xt(e,t)),Mn=e=>!ae(e.table),Ct=n.relationExistsPushDown??"auto",Mt=Ct!=="never",{maxRelationKeys:Dt}=n,De=(e,t,i)=>Bo(e,{fetcher:bt,maxRelationKeys:Dt,relationBaseWhere:i,schema:d,tableName:t}),Dn=async(e,t,i,l)=>{const w=H(e,"relation grouped count");if(w)return k(e,G),jo((R,P)=>w.count(R,P),e,t,i,l);const p=d.tables[e];if(!p)throw new $("INTERNAL",`unknown table: ${e}`);k(e,G);const f=Ae(p.softDeleteMode,void 0),h={[t]:{in:i}},E=Q(Q(h,l),f),A=await De(E,e,void 0),C=Z(A,ue),I=fe(t);let T=a`SELECT ${I} AS __fk__, COUNT(*) AS count FROM ${a.identifier(e)}`;C&&(T=a`${T} WHERE ${C}`),T=a`${T} GROUP BY ${I}`;const D=K(y,T).toArray();return new Map(D.map(R=>[R.__fk__,R.count]))},kt=new Set;for(const[e,t]of Object.entries(d.tables))for(const i of Object.values(t.triggerMap??{}))kt.add(`${e} ${i.timing} ${i.op}`);const ne=(e,t,i)=>kt.has(`${e} ${t} ${i}`),oe=async(e,t,i)=>{if(u.value+=1,u.value>tn)throw u.value-=1,new se(`trigger recursion exceeded ${String(tn)} levels on "${i.table}" — check for a self-triggering write`,"trigger");try{await Qo({ctx:Bn,event:i,op:t,schema:d,tableName:i.table,timing:e})}finally{u.value-=1}},{ensureBackfilledForTable:Se,ensureBackfilledIndex:tt,ensureRankBackfilled:nt,ensureRankBackfilledForTable:ve,syncAggregates:ke,syncCompanionsForInsert:Lt,syncGeo:Le,syncRanks:_e,syncSearch:Fe}=Xn({broadcast:b,indexKeysFor:(e,t)=>N(e,t),invalidateCache:(e,t,i)=>Ee?.invalidate(e,t,N(e,i)),recordCdc:Re,schema:d,sql:y,verified:n.companionMemo?.verified}),Ft=(e,t,i)=>{const{shardMode:l}=t;if(l?.kind==="shardBy"&&!(l.field!==void 0&&(i.partitionBy??[]).includes(l.field)))throw Object.assign(new Error(`rank index "${i.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})},Bt=e=>Object.entries(d.tables).filter(([,t])=>t.shardMode?.kind!=="global").map(([t])=>t).filter(t=>e===void 0||t===e),Te=e=>e===void 0||ae(e)?$e:void 0,ot=async(e,t,i,l,w)=>{for(let p=0;p<i.length;p+=1)J(void 0);if(w!==void 0&&e.deleteMany!==void 0)return e.deleteMany(t,i,w.options);for(const p of i)await e.delete(t,p,l);return{deleted:i.length}},re=(e,t)=>{const i=Bt(t);for(let l=0;l<i.length;l+=nn){const w=i.slice(l,l+nn),[p]=he(y,$r(w),...Rr(e,w)).toArray();if(!p)continue;const f=p.__t__,h=xe(p);if(typeof f!="string"||!h)return;const E=p[ie];return{docJson:typeof E=="string"?E:le(E??{}),row:h,tableName:f}}},Wt={assertRankPartitionLocal:Ft,ensureRankBackfilled:nt,onRead:k,rowToDocument:xe,schema:d,sql:y},kn=(e,t,i)=>{const l=Z(i,ue);return l===void 0||K(y,a`SELECT 1 FROM ${a.identifier(e)} WHERE ${a.identifier("id")} = ${t} AND ${l}`).toArray().length>0},Ln=(e,t,i,l)=>Tt(e,t,i,l)?(o?.({fields:Object.keys(Ke(i)),id:t,table:e}),!0):!1,Fn=async(e,t,i,l,w)=>{const p=re(t,e);if(!p)return{applied:!1,doc:null};if(k(e,t),!kn(e,t,i.where)||Ln(e,t,i.patch,p.row))return{applied:!1,doc:p.row};try{await w(i.patch)}catch(f){if(f instanceof se&&f.kind==="occ"&&l)return;throw f}return{applied:!0,doc:re(t,e)?.row??null}},qt=async(e,t,i,l)=>{const{fetchLimit:w,limit:p,orderKeys:f,predicate:h}=await Wo(t,i,{canPushExists:Mt?Mn:void 0,existsPushMode:Ct==="always"?"always":"auto",fetcher:bt,maxRelationKeys:Dt,schema:d,tableName:e}),E=Mt?Fr(l):Ye,A=Z(h,E,ze),C=vn(e,A,_n(f),w);return{limit:p,orderKeys:f,statement:C}},O={system:Cn,async aggregate(e,t){const i=H(e,"aggregate");if(i)return k(e,G),i.aggregate(e,t);const l=d.tables[e];if(!l)throw new $("INTERNAL",`unknown table: ${e}`);if(Pe(t.op),t.op==="count")return O.count(e,{baseWhere:t.baseWhere,relationBaseWhere:t.relationBaseWhere,restrictsCounts:t.restrictsCounts,where:t.where});if(!t.field)throw new $("INTERNAL",`aggregate(${e}, { op: "${t.op}" }): "field" is required for non-count reducers`);k(e,G);const w=Ae(l.softDeleteMode,void 0),p=Q(Q(t.baseWhere,t.where),w),f=await De(p,e,t.relationBaseWhere),h=f!==p;if(l.aggregateIndexes&&!t.baseWhere&&!h){const R=Kn(l.aggregateIndexes,t.op,t.field,t.where);if(R){tt(e,R.index);const P=it(R.index.by??[],R.key),Y=rt(e,R.index.name),X=K(y,a`SELECT ${Ue} AS value, ${at} AS count FROM ${a.identifier(Y)} WHERE ${Oe} = ${P}`).toArray()[0];return st(t.op,X)}}sn(l,t.field,`aggregate(${e}, { op: "${t.op}", field: "${t.field}" })`);const E=Z(f,ue),A=Pe(t.op),C=fe(t.field);let I=a`SELECT ${a.raw(A)}(${C}) AS value FROM ${a.identifier(e)}`;E&&(I=a`${I} WHERE ${E}`);const D=K(y,I).toArray()[0]?.value;return D??null},asId(e,t){const i=cn(d,e,t);if(i===null)throw new $("BAD_REQUEST",`asId("${e}", …): "${t}" is not a valid id for table "${e}"`,{status:400});return i},async count(e,t){const i=H(e,"count");if(i)return k(e,G),i.count(e,t);const l=d.tables[e];if(!l)throw new $("INTERNAL",`unknown table: ${e}`);const w=Gn(t);if(w.restrictsCounts)throw new ct(e);k(e,G);const p=Ae(l.softDeleteMode,void 0),f=Q(Q(w.baseWhere,w.where),p),h=await De(f,e,w.relationBaseWhere),E=h!==f;if(l.aggregateIndexes&&!w.baseWhere&&!E){const T=Hn(l.aggregateIndexes,w.where);if(T){tt(e,T.index);const D=it(T.index.by??[],T.key),R=rt(e,T.index.name),P=K(y,a`SELECT ${Ue} AS value FROM ${a.identifier(R)} WHERE ${Oe} = ${D}`).toArray();return P[0]===void 0?0:P[0].value??0}}const A=Z(h,ue);let C=a`SELECT COUNT(*) AS count FROM ${a.identifier(e)}`;return A&&(C=a`${C} WHERE ${A}`),K(y,C).one().count},async delete(e,t,i){_(e,"ctx.db.delete(table, id)");const l=re(t,e);if(!l){const T=Te(e);T&&await ot(T,e,[t],i);return}const{docJson:w,row:p,tableName:f}=l,h=d.tables[f],E=i?.hard===!0,A=!E&&h?.softDeleteMode?h:void 0,C=A?.softDeleteMode?.field;if(C&&p[C]!==null&&p[C]!==void 0)return;if(ne(f,"before","delete")&&await oe("before","delete",{id:t,op:"delete",previous:p,table:f}),i?.skipOnDelete!==!0&&await Go({deletedId:t,deletedReference:T=>p[T],findHolders:async(T,D,R,P)=>(await et(T).findMany(T,{...P,includeDeleted:E,where:{[D]:R}})).page,onCascade:(T,D)=>et(T).delete(T,D,i),onRestrict:T=>{throw new se(T,"restrict")},onSetNull:(T,D,R)=>et(T).patch(T,D,{[R]:null}),schema:d,tableName:f}),Se(f),ve(f),A&&C){const T={[C]:me()},D={...p,...ee(f),...T,_id:t};ut(A,T,D,ce),Ne(y,f,Zt(f),[le(D),t,w]),Fe(f,t,D,p),Le(f,t,void 0),ke(f,p,D),_e(f,t,p,void 0);const R=N(f,p,D);Ee?.invalidate(f,t,R),Re(f,t,"update",D),b({indexKeys:R,key:t,op:"update",row:D,table:f}),ne(f,"after","delete")&&await oe("after","delete",{id:t,op:"delete",previous:p,table:f}),await ye({id:t,op:"delete",table:f});return}Ne(y,f,yr(f),[t,w]),Fe(f,t,void 0),Le(f,t,void 0),ke(f,p,void 0),_e(f,t,p,void 0);const I=N(f,p);Ee?.invalidate(f,t,I),Re(f,t,"delete"),b({indexKeys:I,key:t,op:"delete",table:f}),ne(f,"after","delete")&&await oe("after","delete",{id:t,op:"delete",previous:p,table:f}),await ye({id:t,op:"delete",table:f})},async deleteAll(e,t){if(!d.tables[e])throw new $("INTERNAL",`unknown table: ${e}`);if(s!==void 0)return m().deleteAll(e,t);const i=Math.max(1,t?.chunkSize??$n),l=t?.hard===void 0?void 0:{hard:t.hard},w=H(e,"deleteAll");let p=0;for(;;){const h=(await O.findMany(e,{limit:i})).page.map(E=>String(E._id));if(h.length===0)break;for(const E of h)await(w===void 0?O.delete(e,E,l):ot(w,e,[E],l)),p+=1;if(h.length<i)break}return{deleted:p}},async deleteMany(e,t,i){_(e,"ctx.db.deleteMany(table, ids)"),He(t.length,i?.limit,"deleteMany");for(const l of t)await O.delete(e,l);return{deleted:t.length}},async deleteWhere(e,t,i){const l=H(e,"deleteWhere"),p=(await on(l??O,e,t,i?.limit,"deleteWhere")).map(f=>String(f._id));if(l)return ot(l,e,p,void 0,{options:i});if(O.deleteMany===void 0)throw new $("INTERNAL",`ctx.db.${e}.deleteMany is unavailable: this writer has no batch delete`);return O.deleteMany(e,p,i)},async findFirst(e,t={}){return(await O.findMany(e,{...t,limit:1,omitContinueCursor:!0})).page[0]??null},async findFirstOrThrow(e,t={}){const i=await O.findFirst(e,t);if(i===null)throw new wo(`findFirstOrThrow: no "${e}" document matched`);return i},async findMany(e,t={}){const i=H(e,"findMany");if(i)return k(e,G),t.consistency==="primary"&&S(e,Zn),i.findMany(e,t);const l=d.tables[e];if(!l)throw new $("INTERNAL",`unknown table: ${e}`);const w=!t.where&&!t.baseWhere;w?k(e,G):k(e);const{limit:p,orderKeys:f,statement:h}=await qt(e,l,t,k),E=he(y,h.text,...h.params).toArray();w&&s?.recordRead(E.length);const A=[];for(const I of E){const T=xe(I);T&&(A.push(T),!w&&typeof T._id=="string"&&k(e,T._id))}const C=Fo(A,{endCursor:t.endCursor,limit:p,omitContinueCursor:t.omitContinueCursor,orderKeys:f});return t.with&&await Uo({fetcher:xt,groupedCounter:Dn,parents:C.page,...Oo(t),schema:d,tableName:e,with:t.with}),{...C,page:mn(C.page,t.select,t.with)}},async explain(e,t={}){const i=H(e,"explain");if(i)return i.explain(e,t);const l=d.tables[e];if(!l)throw new $("INTERNAL",`unknown table: ${e}`);const{statement:w}=await qt(e,l,t,()=>{}),p=he(y,`EXPLAIN QUERY PLAN ${w.text}`,...w.params).toArray();return{params:w.params,plan:p.map(f=>String(f.detail)),sql:w.text}},async get(e,t){_(e,"ctx.db.get(table, id)");const i=re(t,e);if(!i){const l=Te(e);return l?l.get(e,t):(M(e),S(e,t,!0),null)}return pe(i,t),i.row},async lookupById(e,t){const i=re(e,t);if(!i){for(const l of Bt(t))M(l),S(l,e,!0);return null}return pe(i,e),{row:i.row,tableName:i.tableName}},async groupBy(e,t){const i=H(e,"groupBy");if(i)return k(e,G),i.groupBy(e,t);const l=d.tables[e];if(!l)throw new $("INTERNAL",`unknown table: ${e}`);k(e,G);const w=t.agg??{op:"count"};if(Pe(w.op),w.op!=="count"&&!w.field)throw new $("INTERNAL",`groupBy(${e}, { agg: { op: "${w.op}" } }): "field" is required for non-count reducers`);const p=Ae(l.softDeleteMode,void 0),f=Q(Q(t.baseWhere,t.where),p),h=await De(f,e,t.relationBaseWhere),E=h!==f;if(l.aggregateIndexes&&!t.baseWhere&&!E){const R=jn(l.aggregateIndexes,w.op,w.field,t.by,t.where),P=R===void 0?0:Object.keys(R.partial).length,Y=R?.index.by?.length??0;if(R&&(P===0||P===Y)){tt(e,R.index);const X=rt(e,R.index.name),V=Object.keys(R.partial),de=[];if(V.length===(R.index.by??[]).length&&V.length>0){const Be=it(R.index.by??[],R.partial),We=K(y,a`SELECT ${Ue} AS value, ${at} AS count FROM ${a.identifier(X)} WHERE ${Oe} = ${Be}`).toArray();return We.length>0&&de.push({key:{...R.partial},value:st(w.op,We[0])}),de}const Wn=K(y,a`SELECT ${Oe} AS key, ${Ue} AS value, ${at} AS count FROM ${a.identifier(X)}`).toArray();for(const Be of Wn){const We=Un(JSON.parse(Be.key));de.push({key:We,value:st(w.op,Be)})}return de}}for(const R of[...t.by,w.field]){if(R===void 0)continue;const P=R===w.field?`groupBy(${e}, { agg: { op: "${w.op}", field: "${R}" } })`:`groupBy(${e}, { by: [..."${R}"] })`;sn(l,R,P)}const A=Z(h,ue),C=t.by.map(R=>a`${fe(R)} AS ${a.identifier(R)}`);if(w.op==="count")C.push(a`COUNT(*) AS value`);else{const{field:R}=w;if(R===void 0)throw new $("INTERNAL",`groupBy(${e}, { agg: { op: "${w.op}" } }): "field" is required for non-count reducers`);C.push(a`${a.raw(Pe(w.op))}(${fe(R)}) AS value`)}let I=a`SELECT ${a.join(C,a`, `)} FROM ${a.identifier(e)}`;A&&(I=a`${I} WHERE ${A}`),I=a`${I} GROUP BY ${a.join(t.by.map(R=>fe(R)),a`, `)}`;const T=K(y,I).toArray(),D=[];for(const R of T){const P={};for(const X of t.by)P[X]=no(l.shape[X],R[X]??null);const{value:Y}=R;D.push({key:P,value:Y==null?null:Number(Y)})}return D},async insert(e,t,i){const l=H(e,"insert");if(l)return It(l,e,t,i,!0);const w=d.tables[e];if(!w)throw new $("INTERNAL",`unknown table: ${e}`);const p=i?.allowExplicitId===!0,f=Ge(w,pt(w,t,ce),{supplied:t,trusted:p});let h;i?.clientId!==void 0?(vr(i.clientId),h=i.clientId):i?.allowExplicitId&&typeof f._id=="string"?(yt(f._id),h=f._id):h=St();const E=i?.allowExplicitId&&typeof f._creationTime=="number"?f._creationTime:me(),A={...f,...ee(e),_creationTime:E,_id:h};return ne(e,"before","insert")&&await oe("before","insert",{doc:{...A},id:h,op:"insert",table:e}),p||W(e,A),Se(e),ve(e),Et(y,e,pr(e),[h,E,le(A)]),Lt(e,h,A),ne(e,"after","insert")&&await oe("after","insert",{doc:A,id:h,op:"insert",table:e}),await ye({doc:A,id:h,op:"insert",table:e}),h},async insertManyUnsafe(e,t,i){if(He(t.length,i?.limit,"insertManyUnsafe"),t.length===0)return[];const l=H(e,"insert");if(l){const E=[];_r(d.tables[e],t,i?.allowExplicitId,ce);for(const A of t)J(A);for(const A of t){const C=await l.insert(e,A,{allowExplicitId:i?.allowExplicitId});b({key:C,op:"insert",row:{...A,_id:C},table:e}),E.push(C)}return E}const w=d.tables[e];if(!w)throw new $("INTERNAL",`unknown table: ${e}`);Se(e),ve(e);const p=[];for(let E=0;E<t.length;E+=je)p.push(ee(e));const f=i?.allowExplicitId===!0?void 0:Po(w),h=t.map((E,A)=>{const C=pt(w,E,ce),I=f===void 0?C:Ge(f,C,{supplied:E}),T=i?.allowExplicitId===!0&&typeof I._id=="string"?I._id:void 0;T!==void 0&&yt(T);const D=T??St(),R=i?.allowExplicitId===!0&&typeof I._creationTime=="number"?I._creationTime:me(),P={...I,...p[Math.floor(A/je)],_creationTime:R,_id:D};return{creationTime:R,document:P,id:D}});for(const E of h)J(E.document);for(let E=0;E<h.length;E+=je){const A=a.join(h.slice(E,E+je).map(I=>a`(${I.id}, ${I.creationTime}, ${le(I.document)})`),a`, `),C=gn("sqlite",a`INSERT INTO ${a.identifier(e)} (id, _creationTime, ${a.identifier(ie)}) VALUES ${A}`);Et(y,e,C.sql,C.params)}for(const{document:E,id:A}of h)Lt(e,A,E),await ge({doc:E,id:A,op:"insert",table:e});return h.map(E=>E.id)},async insertMany(e,t,i){He(t.length,i?.limit,"insertMany");const l=i?.skipDuplicates===!0,w=[],p=H(e,"insert");if(p)for(const h of t)J(h);const f=async h=>p?It(p,e,h,void 0,!1):O.insert(e,h);for(const h of t)try{w.push(await f(h))}catch(E){if(l&&E instanceof se&&E.kind==="unique")w.push(null);else throw E}return w},normalizeId(e,t){return cn(d,e,t)},async patch(e,t,i,l){_(e,"ctx.db.patch(table, id, values)");const w=re(t,e);if(!w){const D=Te(e);if(D){J(i),await D.patch(e,t,i,l);return}throw new $("NOT_FOUND",`document not found: ${t}`)}const{docJson:p,row:f,tableName:h}=w,E=d.tables[h];if(!E)throw new $("INTERNAL",`unknown table: ${h}`);if(k(h,t),dn("patch",i),Tt(h,t,i,f)){o?.({fields:Object.keys(Ke(i)),id:t,table:h});return}const A=po(E,i,f),C={...f,...Ke(A),...ee(h),_id:t};ut(E,A,C,ce);const I=Ge(E,C,{only:new Set(Object.keys(A)),previous:()=>f,tolerateStoredNull:!0});go(l,f,I),ne(h,"before","update")&&await oe("before","update",{doc:{...I},id:t,op:"update",previous:f,table:h}),W(h,I,f),Se(h),ve(h),Ne(y,h,Zt(h),[le(I),t,p]),Fe(h,t,I,f),Le(h,t,I),ke(h,f,I),_e(h,t,f,I);const T=N(h,f,I);Ee?.invalidate(h,t,T),Re(h,t,"update",I),b({indexKeys:T,key:t,op:"update",row:I,table:h}),ne(h,"after","update")&&await oe("after","update",{doc:I,id:t,op:"update",previous:f,table:h}),await ye({doc:I,id:t,op:"update",table:h})},async patchIf(e,t,i){const l=H(e,"patchIf");if(l){if(l.patchIf===void 0)throw new $("INTERNAL",`ctx.db.patchIf on global table '${e}' is unsupported: its backend has no conditional write`);return J(i.patch),l.patchIf(e,t,i)}if(!d.tables[e])throw new $("INTERNAL",`unknown table: ${e}`);for(let w=1;w<=an;w+=1){const p=await Fn(e,t,i,w<an,f=>O.patch(e,t,f,{verify:i.verify}));if(p!==void 0)return p}throw new se(`patchIf on "${e}" kept conflicting; the row changed on every attempt`,"occ")},async patchMany(e,t,i){_(e,"ctx.db.patchMany(table, patches)"),He(t.length,i?.limit,"patchMany");for(const l of t)await O.patch(e,l.id,l.patch);return{patched:t.length}},async patchWhere(e,t,i){const l=H(e,"patchWhere")??O,p=(await on(l,e,t.where,i?.limit,"patchWhere")).map(f=>({id:String(f._id),patch:t.patch}));if(O.patchMany===void 0)throw new $("INTERNAL",`ctx.db.${e}.patchMany is unavailable: this writer has no batch patch`);return await O.patchMany(e,p,i),{patched:p.length}},async related(e,t){return Lo(O,v,e,t)},relationEdges:v,deleteRereadTables:B,inTransaction:j,softDeleteFields:U,relationWrites:q,query(e){const t=H(e,"query");return t?(k(e,G),t.query(e)):xn(y,d,e,te,i=>{i?F(i):k(e,G)},i=>{s?.recordRead(i)})},async rank(e,t,i){const l=H(e,"rank");if(l)return k(e,G),l.rank(e,t,i);te(e,t,"rank");const w=d.tables[e];if(!w)throw new $("INTERNAL",`unknown table: ${e}`);const p=w.rankIndexes?.find(V=>V.name===t);if(!p)throw new $("INTERNAL",`unknown rankIndex "${t}" on table "${e}"`);if(Ft(e,w,p),i.restrictsCounts)throw new ct(e);k(e,G),nt(e,p);const f=typeof i.row=="string"?i.row:i.row._id;if(!f)return null;const h=Nt(e,p.name),E=p.sortBy.map((V,de)=>Qt(de)),A=E.map(V=>Me(V)).join(", "),C=K(y,a`SELECT ${a.identifier("__partition__")}, ${a.raw(A)} FROM ${a.identifier(h)} WHERE ${a.identifier("__id__")} = ${f}`).toArray(),[I]=C;if(I===void 0)return null;let T=I.__partition__;const D=Q(i.baseWhere,i.where);dt(D,d,e,"rank");const R=vo(p,D);if(R){const V=_o(p.partitionBy??[],R);if(V!==T)return null;T=V}const P=E.map(V=>I[V]),{before:Y,total:X}=un(y,h,E,p.sortBy,T,P,f);return{position:Y+1,total:X}},async rankBefore(e,t,i){if(ae(e))throw new $("INTERNAL",`rankBefore is not supported on the global (.global()) table '${e}' — cross-shard rank cursors apply only to sharded tables`);const l=d.tables[e];if(!l)throw new $("INTERNAL",`unknown table: ${e}`);const w=l.rankIndexes?.find(E=>E.name===t);if(!w)throw new $("INTERNAL",`unknown rankIndex "${t}" on table "${e}"`);if(i.restrictsCounts)throw new ct(e);k(e,G),nt(e,w);const p=Nt(e,w.name),f=w.sortBy.map((E,A)=>Qt(A)),h=w.sortBy.map((E,A)=>Ce(i.sortValues[A]??null));return un(y,p,f,w.sortBy,i.partitionKey,h,i.rowId)},async rankPage(e,t,i={}){dt(Q(i.baseWhere,i.where),d,e,"rankPage");const l=H(e,"rankPage");if(l)return k(e,G),l.rankPage(e,t,i);te(e,t,"rank");const{continueCursor:w,hasMore:p,rows:f}=Ot(Wt,e,t,i);return{continueCursor:w,isDone:!p,page:f.map(h=>h.doc)}},async rankPageRows(e,t,i={}){dt(Q(i.baseWhere,i.where),d,e,"rankPage"),te(e,t,"rank");const{directions:l,hasMore:w,rows:p}=Ot(Wt,e,t,i);return{directions:l,hasMore:w,rows:p}},async restore(e,t){_(e,"ctx.db.restore(table, id)");const i=re(t,e);if(!i){const p=Te(e);if(p?.restore){await p.restore(e,t);return}throw new $("NOT_FOUND",`document not found: ${t}`)}const l=d.tables[i.tableName]?.softDeleteMode?.field;if(!l)throw new $("INTERNAL",`ctx.db.restore: table "${i.tableName}" is not a .softDelete() table`);const w=i.row[l]!==null&&i.row[l]!==void 0;await O.patch(e,t,{[l]:null}),w&&_e(i.tableName,t,void 0,i.row)},async replace(e,t,i,l){_(e,"ctx.db.replace(table, id, document)");const w=re(t,e);if(!w){const P=Te(e);if(P){J(i),await P.replace(e,t,i,l);return}throw new $("NOT_FOUND",`document not found: ${t}`)}const{docJson:p,row:f,tableName:h}=w,E=d.tables[h];if(!E)throw new $("INTERNAL",`unknown table: ${h}`);dn("replace",i);const A=l?.allowExplicitId&&typeof i._creationTime=="number"?i._creationTime:void 0,C=typeof f._creationTime=="number"?f._creationTime:void 0,I=A??C??me(),T={...i,...ee(h),_creationTime:I,_id:t};ut(E,i,T,ce);const D=l?.allowExplicitId===!0,R=Ge(E,T,{previous:()=>f,supplied:i,trusted:D});ne(h,"before","update")&&await oe("before","update",{doc:{...R},id:t,op:"update",previous:f,table:h}),D||W(h,R,f),Se(h),ve(h),Ne(y,h,gr(h),[I,le(R),t,p]),Fe(h,t,R,f),Le(h,t,R),ke(h,f,R),_e(h,t,f,R),Ee?.invalidate(h,t,N(h,f,R)),Re(h,t,"update",R),b({indexKeys:N(h,f,R),key:t,op:"update",row:R,table:h}),ne(h,"after","update")&&await oe("after","update",{doc:R,id:t,op:"update",previous:f,table:h}),await ye({doc:R,id:t,op:"update",table:h})},async wipeShard(e){const t=new Set(e?.exclude),i=e?.tables,l=Object.entries(d.tables).filter(([h,E])=>t.has(h)||i!==void 0&&!i.includes(h)?!1:E.shardMode?.kind!=="global").map(([h])=>h);if(i!==void 0){for(const h of i)if(!d.tables[h])throw new $("INTERNAL",`wipeShard: unknown table: ${h}`)}const w={};let p=0;const{deleteAll:f}=O;if(f===void 0)throw new $("INTERNAL","wipeShard: this writer has no deleteAll");for(const h of l){const E=await f(h,{...e?.chunkSize===void 0?{}:{chunkSize:e.chunkSize},hard:!0});w[h]=E.deleted,p+=E.deleted}return{deleted:p,tables:w}}},Bn={db:O,scheduler:vt};return n.enforceRls===!0?Ho(O,d,(e,t)=>re(e,t)?.tableName,v):O};export{Qi as CDC_LOG_TABLE,ps as IDEMPOTENCY_TABLE,Br as NotUniqueError,us as advanceClientWatermark,Vi as applyCdcChanges,dn as assertNoExplicitUndefined,yt as assertStorableRowId,vr as assertValidClientId,ji as backfillAggregateIndexes,Hi as backfillRankIndexes,Ki as backfillSearchIndexes,Ji as bumpCdcEpoch,zi as cdcCanVouchFor,Yi as cdcForkedError,Xi as cdcSeqLeavingRows,Zi as cdcTouchesTables,es as cdcTrimmedError,ts as compactCdcDocs,ti as createShardCtxDb,ns as cursorBelowRetainedFloor,Qr as meterReadBytes,fs as migrateClientWatermark,os as minCdcReplayableSeq,rs as minCdcSeq,cn as normalizeIdStructurally,is as readCdcChangeKeys,ss as readCdcChanges,cs as readCdcCursor,as as readCdcEpoch,hs as readClientWatermark,gs as readIdempotent,$s as runShardMigrations,Ss as selectShapeMembers,vs as selectShapeRows,Ke as stripReservedPatchFields,ds as trimCdcChanges,ys as trimIdempotent,Es as writeIdempotent};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{createShardCtxDb as C}from"./NotUniqueError-
|
|
1
|
+
import{createShardCtxDb as C}from"./NotUniqueError-vJf9tj6U.mjs";import{createRelayLink as N}from"./DEFAULT_MAX_RELAYS-Bc6PI-xy.mjs";import{ConflictError as q}from"./ConflictError-C8GtJmjS.mjs";import{runShardMigrations as B}from"./runShardMigrations-BPFg3Ht6.mjs";import{d as x}from"./relay-CKEdfUjH.mjs";const v=(O,y={})=>({_meta:{column:{notNull:!0,...y}},kind:O}),W=(O,y,F)=>{const{describe:_,expect:l,it:b}=F;_(`engine contract: ${O}`,()=>{_("optimistic concurrency",()=>{const g=u=>({tables:{items:{indexes:[],shape:{title:v("string"),version:v("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}=y();try{const d=h.sql,p=g(d);B(d,p);const s=C({schema:p,sql:d});await s.insert("items",{_id:"i1",title:"first",version:1},{allowExplicitId:!0}),await l(s.patch("items","i1",{title:"second"})).rejects.toBeInstanceOf(q)}finally{u?.()}}),b("reports the conflict as CONFLICT/409 rather than retrying it away",async()=>{const{close:u,host:h}=y();try{const d=h.sql,p=g(d);B(d,p);const s=C({schema:p,sql:d});await s.insert("items",{_id:"i1",title:"first",version:1},{allowExplicitId:!0});let r;try{await s.patch("items","i1",{title:"second"})}catch(t){r=t}const e=r;l(e.code).toBe("CONFLICT"),l(e.kind).toBe("occ")}finally{u?.()}}),b("leaves the row readable and unchanged after a conflict",async()=>{const{close:u,host:h}=y();try{const d=h.sql,p=g(d);B(d,p);const s=C({schema:p,sql:d});await s.insert("items",{_id:"i1",title:"first",version:1},{allowExplicitId:!0});try{await s.patch("items","i1",{title:"second"})}catch{}const r=await s.get("items","i1");l(r?.title).toBe("first"),l(r?.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}=y();try{const d=h.sql,p={tables:{items:{indexes:[],shape:{title:v("string"),version:v("number",{notNull:!1})},triggerMap:{recurse:{handler:async(t,a)=>{await t.db.patch("items",a.doc._id,{version:99})},op:"update",timing:"before"}}}}};B(d,p);const s=C({schema:p,sql:d});await s.insert("items",{_id:"i1",title:"first",version:1},{allowExplicitId:!0});let r;try{await s.patch("items","i1",{title:"second"})}catch(t){r=t}const e=r;l(e).toBeInstanceOf(q),l(e.code).toBe("CONFLICT"),l(e.kind).toBe("trigger")}finally{u?.()}})}),_("shape-poke ordering",()=>{const g="shard-a",u={args:{},name:"messages"},h=(e,t,a,n)=>e.accept(t?.()??{},{connectionId:a,shapes:{[n]:u}}),d=(e,t,a,n=new Set)=>{let c=0,i=0;const o=k=>()=>{throw new Error(`the relay poke path must not reach RelayHost.${k}`)},m={fetch:(k,E)=>{if(JSON.parse(E?.body??"{}").type!=="relay_shape_subscribe")return Promise.resolve(new Response(void 0,{status:204}));const I=a[i];if(i+=1,I===void 0)throw new Error("the relay asked for more seeds than this fixture supplies");return Promise.resolve(Response.json(I))}},f={get:()=>m,getByName:()=>m,idFromName:k=>k},w={buildShapeDiff:o("buildShapeDiff"),computeOpLogShapeSeed:o("computeOpLogShapeSeed"),currentCdcEpoch:o("currentCdcEpoch"),deliverWhisperLocal:o("deliverWhisperLocal"),dropIfLapsed:k=>n.has((k.deserializeAttachment?.()).connectionId??""),doName:()=>x(g,0),env:()=>({SHARD:f}),getWebSockets:()=>e.getSockets(),maskMetadata:o("maskMetadata"),nextPokeId:()=>(c+=1,`poke-${String(c)}`),readAttachment:k=>k.deserializeAttachment?.(),recordShapePokeFanout:()=>{},resolveShape:o("resolveShape"),rlsMetadata:o("rlsMetadata"),shardBinding:()=>"SHARD",shardJurisdiction:()=>{},sql:()=>t},S=N(w);if(S===void 0)throw new Error("expected a relay link for a `…::relay::N` name");return S},p=e=>new Request("https://relay.internal/_lunora/relay",{body:JSON.stringify(e),headers:{"content-type":"application/json"},method:"POST"}),s=async(e,t,a)=>{const n=await e.seedRelayShape(t,a,u,{identity:void 0,userId:void 0});if(n!=="ok")throw new Error(`seed failed: ${JSON.stringify(n)}`)},r=(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:a,readFrames:n,sockets:c}=y();try{const i=d(c,a.sql,[{cursor:10,epoch:"e1",frames:[]}]),o=h(c,t,"c-alice","s1");await s(i,o,"s1"),await i.handleControl(r());const f=(await n(o)).map(w=>JSON.parse(w));l(f.map(w=>w.type)).toStrictEqual(["pokeStart","pokePart","pokeEnd"]),l(new Set(f.map(w=>w.pokeId)).size).toBe(1),l(f[1]?.shapeId).toBe("s1"),l(f[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:a,readFrames:n,sockets:c}=y();try{const i=d(c,a.sql,[{cursor:10,epoch:"e1",frames:[]},{cursor:7,epoch:"e1",frames:[]}]),o=h(c,t,"c-alice","s1"),m=h(c,t,"c-bob","s2");await s(i,o,"s1"),await s(i,m,"s2"),await i.handleControl(r());const f=await n(o);l(f.length).toBe(3);const w=await n(m);l(w.length).toBe(0),await i.handleControl(r());const S=await n(o);l(S.length).toBe(3)}finally{e?.()}}),b("pokes no subscriber the host reports lapsed, and still pokes the others",async()=>{const{close:e,createSocket:t,host:a,readFrames:n,sockets:c}=y();try{const i=new Set,o=d(c,a.sql,[{cursor:10,epoch:"e1",frames:[]},{cursor:10,epoch:"e1",frames:[]}],i),m=h(c,t,"c-alice","s1"),f=h(c,t,"c-bob","s2");await s(o,m,"s1"),await s(o,f,"s2"),i.add("c-bob"),await o.handleControl(r());const w=await n(m),S=await n(f);l(w.length).toBe(3),l(S.length).toBe(0)}finally{e?.()}}),b("skips a socket whose cursor matches under a different CDC epoch",async()=>{const{close:e,createSocket:t,host:a,readFrames:n,sockets:c}=y();try{const i=d(c,a.sql,[{cursor:10,epoch:"e1",frames:[]}]),o=h(c,t,"c-alice","s1");await s(i,o,"s1"),await i.handleControl(r({epoch:"e2"}));const m=await n(o);l(m.length).toBe(0),await i.handleControl(r());const f=await n(o);l(f.length).toBe(3)}finally{e?.()}})}),_("orderBy null placement",()=>{const g=[["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 r=new Map(g.map(([t],a)=>[t,a])),e=s==="asc"?1:-1;return g.toSorted(([t,a],[n,c])=>a!==c?a===void 0?p==="first"?-1:1:c===void 0?p==="first"?1:-1:(a-c)*e:((r.get(t)??0)-(r.get(n)??0))*e).map(([t])=>t)},d=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}=y();try{const r=s.sql,e=u.map((i,o)=>`items_${String(o)}`),t={label:v("string"),score:v("number",{notNull:!1})},a={tables:Object.fromEntries(e.map(i=>[i,{indexes:[{fields:["score"],name:"by_score"}],shape:t}]))};B(r,a);let n=17e11;const c=C({clock:()=>(n+=1e3,n),schema:a,sql:r});for(const i of e)for(const[o,m]of g)await c.insert(i,m===void 0?{label:o}:{label:o,score:m});for(const[i,o]of u.entries()){const m=e[i]??"",f=await c.findMany(m,{orderBy:[{score:o}]});l(d(f.page)).toStrictEqual(h(o));const w=[];let S;for(let k=0;k<g.length+2;k+=1){const E=await c.findMany(m,{cursor:S,limit:3,orderBy:[{score:o}]});if(w.push(...d(E.page)),E.isDone)break;S=E.continueCursor}l(w).toStrictEqual(h(o))}}finally{p?.()}})}),_("RLS identity under live subscription",()=>{const g="shard-a",u={args:{},name:"lobby-messages"},h={args:{},name:"my-orders"},d=s=>{const r=[],e=[],t={fetch:(c,i)=>(r.push(JSON.parse(i?.body??"{}")),Promise.resolve(new Response(void 0,{status:204})))},n=N({buildShapeDiff:()=>[{id:"r1",op:"upsert",value:{}}],computeOpLogShapeSeed:()=>({baseCheckpoint:void 0,cursor:10,epoch:"e1",reset:!0,rowsPatch:[]}),currentCdcEpoch:()=>"e1",deliverWhisperLocal:()=>0,dropIfLapsed:()=>!1,doName:()=>g,env:()=>({SHARD:{get:()=>t,getByName:()=>t,idFromName:c=>c}}),getWebSockets:()=>[],maskMetadata:()=>({columns:[]}),nextPokeId:()=>"poke-1",readAttachment:()=>({}),recordShapePokeFanout:()=>{},resolveShape:(c,i,o)=>(e.push(o),c===h.name?{columns:["id"],effectiveWhere:{org:o?.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:r,resolvedUnder:e}},p=async(s,r)=>{await s.handleControl(new Request("https://owner.internal/_lunora/relay",{body:JSON.stringify({...r,connectionId:"c-alice",identity:{org:"acme"},relayIndex:0,subId:"s1",type:"relay_shape_subscribe",userId:"u1"}),headers:{"content-type":"application/json"},method:"POST"}))};b("seeds a subscriber under its own forwarded identity, never the anonymous one",async()=>{const{close:s,host:r}=y();try{const{owner:e,resolvedUnder:t}=d(r.sql);await p(e,h),l(t.some(a=>a?.userId==="u1"&&a.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:r}=y();try{const{owner:e,posts:t}=d(r.sql);await p(e,h),t.length=0,await e.onFlush(new Set(["orders"]),20);const a=t.filter(n=>n.type==="relay_shape_poke");l(a.length).toBe(1),l(a[0]?.targetConnectionId).toBe("c-alice")}finally{s?.()}}),b("still multicasts an identity-blind shape to the whole cohort",async()=>{const{close:s,host:r}=y();try{const{owner:e,posts:t}=d(r.sql);await p(e,u),t.length=0,await e.onFlush(new Set(["messages"]),20);const a=t.filter(n=>n.type==="relay_shape_poke");l(a.length).toBe(1),l(a[0]?.targetConnectionId).toBeUndefined()}finally{s?.()}})})})};export{W as defineEngineContractSuite};
|
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.191",
|
|
4
4
|
"description": "Host-neutral reactive engine for Lunora: per-shard state, OCC, CDC, reactive subscriptions, and the poke protocol. Consumes @lunora/platform host contracts and can be mounted on any platform host.",
|
|
5
5
|
"keywords": [
|
|
6
6
|
"cloudflare",
|
|
@@ -1 +0,0 @@
|
|
|
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-CVukTkQ5.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};
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{LunoraError as R}from"@lunora/errors";import{q as Rt}from"./MAX_TOKEN_LENGTH-iFEGEcDL-DBPC6ZWl.mjs";import{S as Un,l as qe,s as On}from"./fts-companion-CE3EmIjk.mjs";import{decodeWire as Gn,stableWireKey as Ut}from"@lunora/wire";import{sql as d}from"drizzle-orm";import{throwingScheduler as jn,aggregateSqlFunction as Pe,normalizeCountArgument as Hn}from"./AGGREGATE_SQL_FUNCTION-C_ZipS9R.mjs";import{aggregateTableName as st,encodeAggregateKey as ct,readAggregateValue as at}from"./aggregateTableName-B_CtIQCS.mjs";import{mergeWhere as Q,CountRlsUnsupportedError as dt,selectIndexForGroupBy as Kn,selectIndexForCount as Nn,selectIndexForAggregate as Qn}from"./CountRlsUnsupportedError-BvsDqfO2.mjs";import{backfillSearchIndexesForTable as Vn,searchIndexCoversTable as Jn}from"./backfillAggregateIndexes-Pk0KLrfk.mjs";import{backfillAggregateIndexes as Gi,backfillRankIndexes as ji,backfillSearchIndexes as Hi}from"./backfillAggregateIndexes-Pk0KLrfk.mjs";import{appendCdcChange as zn,readCdcDocAtOrBefore as Yn}from"./CDC_LOG_TABLE-BFGgqai8.mjs";import{CDC_LOG_TABLE as Ni,applyCdcChanges as Qi,bumpCdcEpoch as Vi,cdcCanVouchFor as Ji,cdcForkedError as zi,cdcSeqLeavingRows as Yi,cdcTouchesTables as Xi,cdcTrimmedError as Zi,compactCdcDocs as es,cursorBelowRetainedFloor as ts,minCdcReplayableSeq as ns,minCdcSeq as os,readCdcChangeKeys as rs,readCdcChanges as is,readCdcCursor as ss,readCdcEpoch as cs,trimCdcChanges as as}from"./CDC_LOG_TABLE-BFGgqai8.mjs";import{allocateCommitSeq as Xn,COMMIT_SEQ_FIELD as Zn}from"./COMMIT_SEQ_FIELD-Da1DjGqo.mjs";import{createCompanionSync as eo}from"./createCompanionSync-CEht4hXX.mjs";import{isMemoryTable as Ot}from"./clearMemoryTables-aMRERF0w.mjs";import{computeRankPage as Gt}from"./computeRankPage-xm-70mLy.mjs";import{SCAN_DEP as G,PRIMARY_READ as to}from"./SCAN_DEP-B4Uu4g7l.mjs";import{runSql as he,runDrizzle as K}from"./runDrizzle-RC09zZrh.mjs";import{p as no,j as pt,D as ie,r as xe,W as oo,k as le,b as Ue,A as lt,a as Oe,m as ue,e as fe,s as ro,t as io,u as so,i as co,q as jt,h as $n,g as ao}from"./do-sql-105TONaE.mjs";import{renderSql as mn,unionAll as Rn,WORKERD_SQLITE_LIMITS as Sn}from"./WORKERD_SQLITE_LIMITS-B_4w7tzY.mjs";import{a as lo,u as uo}from"./estimate-bytes-C-C35VXL.mjs";import{coveringGeohashes as fo,boundingBoxGeohashes as ho,haversineMeters as wo,pointInBoundingBox as po}from"./GEO_DEFAULT_PRECISION-CqpQZ-J_.mjs";import{NotFoundError as go}from"./NotFoundError-BhF7FeFr.mjs";import{resolvePatch as yo,assertPatchAllowed as Eo,operatorFields as $o,readPatchField as Ht}from"./assertPatchAllowed-CA_H466g.mjs";import{tiebreakDirectionFor as mo,encodeCursor as Qe,nullsOrderSuffix as Ro,normalizeOrderKeys as Kt,uniqueIndexFields as So,buildSeekWhere as vo,decodeCursor as Nt,buildSeekBeforeWhere as _o,softDeleteScope as Ae,applySelect as gt}from"./CURSOR_PREFIX-6offuG6M.mjs";import{rankTableName as Qt,sortColumnName as Vt,resolveRankPartition as To,encodePartitionKey as Ao,RANK_TIEBREAK as Io,rankPivotConditionSql as xo}from"./RANK_TIEBREAK-D3ye2GsL.mjs";import{UNVOUCHABLE_DEP as Jt}from"./UNVOUCHABLE_DEP-Ds9gxVqs.mjs";import{idIndexKey as bo,withUnknownIndexKeys as Co,indexKeysForRow as Mo,buildIndexRange as Do}from"./buildIndexRange-BTChxh3k.mjs";import{r as Ve,j as be,c as Z,t as Ye,i as zt}from"./where-sql-BjY4rnqb.mjs";import{serializeSqlValue as Ce}from"./serializeSqlValue-DeoBMpZ2.mjs";import{quoteIdentifier as Me}from"./quoteIdentifier-CObIFRhb.mjs";import{whereOfFilter as ko,isPushableWhere as Lo}from"./isPushableWhere-BeYAOjUb.mjs";import{deriveRelationEdges as Fo,findRelated as Bo}from"./RELATED_DEFAULT_LIMIT-CVqN4JEu.mjs";import{assertFlatPredicate as ut,resolveRelationPredicates as Wo,composeReadPredicate as qo}from"./DEFAULT_MAX_RELATION_KEYS-DfrMi_eE.mjs";import{describeRelationWrites as Po}from"./describeRelationWrites-omar6-u9.mjs";import{runRowValidators as Ge,transformOnlyDefinition as Uo,applyInsertDefaults as yt,resolveWith as Yt,relationHooks as Xt,applyOnDelete as Oo,fanOutScalarCounts as Go}from"./applyInsertDefaults-CVukTkQ5.mjs";import{guardWriter as jo}from"./RLS_UNWRAP_SYMBOL-H6J96vgK.mjs";import{mayHoldProjectedValue as Ho}from"./BIGINT_KEY_DIGITS-DE6yshOt.mjs";import{createSystemReader as Ko}from"./createSystemReader-BSCxr8Qs.mjs";import{ConflictError as se}from"./ConflictError-C8GtJmjS.mjs";import{hasTrigger as Zt,runTriggers as No}from"./hasTrigger-CjlwI4le.mjs";import{advanceClientWatermark as ls,migrateClientWatermark as us,readClientWatermark as fs}from"./CLIENT_WATERMARK_TABLE-De7z_OHV.mjs";import{IDEMPOTENCY_TABLE as ws,readIdempotent as ps,trimIdempotent as gs,writeIdempotent as ys}from"./IDEMPOTENCY_TABLE-COrgeP3O.mjs";import{runShardMigrations as $s}from"./runShardMigrations-BPFg3Ht6.mjs";import{selectShapeMembers as Rs,selectShapeRows as Ss}from"./selectShapeMembers-Dqx_m7BF.mjs";const Qo=n=>{const r=atob(n),o=Uint8Array.from(r,s=>s.codePointAt(0)??0);return new TextDecoder().decode(o)},Vo=()=>new R("BAD_REQUEST","invalid cursor"),en=16,tn=8,z=1024,St=(n,r)=>r.query(n),Jo=(n,r)=>{if(n.length===0)return 0;let o=0;for(const[s,c]of r.entries()){const u=s===r.length-1;let g=0;for(const $ of n)(u?$.startsWith(c):$===c)&&(g+=1);if(g===0)return 0;o+=g}return o},zo=(n,r)=>{if(!r)return{exact:!0,lower:n,upper:n};const o=[...n].at(-1)??"",s=(o.codePointAt(0)??0)+1;if(s>=55296&&s<=57343||s>1114111)return{exact:!0,lower:n,upper:n};const c=n.slice(0,n.length-o.length);return{exact:!1,lower:n,upper:c+String.fromCodePoint(s)}},Yo=(n,r,o)=>{const s={eq:(c,u)=>{if(!n.definition.filterFields?.includes(c))throw new R("INTERNAL",`field "${c}" is not a filter field of search index "${n.indexName}" on table "${r}"`);if(n.filters.length>=tn)throw new R("BAD_REQUEST",`search index "${n.indexName}" on table "${r}": at most ${String(tn)} .eq() filters are supported per search query`);return n.filters.push({field:c,value:u}),s},search:(c,u)=>{const g=n;if(c!==g.definition.field)throw new R("INTERNAL",`search index "${g.indexName}" on table "${r}" indexes "${g.definition.field}", not "${c}"`);const $=St(u,o).length;if($>en)throw new R("BAD_REQUEST",`search index "${g.indexName}" on table "${r}": at most ${String(en)} search terms are supported (got ${String($)})`);return g.field=c,g.query=u,g.hasQuery=!0,s}};return s},Xo=n=>{if(n.length>z)throw new R("BAD_REQUEST",`more than ${String(z)} documents match this search — narrow it with filters or read it a page at a time with .paginate()`)},Zo=n=>Math.min(n.offset+n.numItems+1,z),er=n=>btoa(`search:${String(n)}`),tr=n=>{let r;try{r=Qo(n)}catch{return}if(!r.startsWith("search:"))return;const o=Number(r.slice(7));return Number.isInteger(o)&&o>=0?o:void 0},nr=n=>{if(typeof n.endCursor=="string")throw new R("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 R("BAD_REQUEST",`search pagination needs a finite numItems, got ${String(n.numItems)}`);const r=Math.max(0,Math.floor(n.numItems)),o=n.cursor?tr(n.cursor):0;if(o===void 0)throw Vo();if(o+r>=z)throw new R("BAD_REQUEST",`search pagination reaches the ${String(z)}-document limit (offset ${String(o)} + ${String(r)} requested) — a page must end below the cap so the probe row that answers \`hasMore\` still fits: retry with numItems ${String(Math.max(1,z-o-1))} or fewer, or narrow the query or the filters instead`);return{numItems:r,offset:o}},or=(n,r)=>{const o=r.offset+r.numItems,s=r.numItems>0&&n.length>o;return{continueCursor:s?er(o):null,isDone:!s,page:n.slice(r.offset,o)}},rr=n=>{if(n===void 0)return z+1;if(!Number.isFinite(n))return z;const r=Math.max(0,Math.floor(n));if(r>z)throw new R("BAD_REQUEST",`search returns at most ${String(z)} documents (asked for ${String(r)}) — narrow the query or paginate instead`);return r},vn=500,_n=(n,r,o)=>{if(n!==void 0&&n!==Number.POSITIVE_INFINITY&&(!Number.isInteger(n)||n<0))throw o(`${r}: batch limit must be a non-negative integer`);return n??vn},Tn=(n,r,o,s)=>{if(n>r)throw s(`${o}: batch of ${String(n)} exceeds the limit of ${String(r)} (raise options.limit or chunk the call)`)},ir=32,sr=1024,An=(n,r,o,s)=>{const c=`SELECT id, _creationTime, ${Me(ie)} FROM ${Me(n)}`,u=`ORDER BY ${o}${s===void 0?"":` LIMIT ${String(s)}`}`;return r===void 0?Ve(`${c} ${u}`):be(`${c} WHERE `,r,` ${u}`)},Xe={fieldRef:n=>Ve(pt(n)),rangeTypeGuard:(n,r)=>Ve(no(n,r)),serialize:Ce},cr=n=>n===void 0?"":Ro(n==="first"),In=n=>{const r=n.map(o=>`${pt(o.field)} ${o.direction==="desc"?"DESC":"ASC"}${cr(o.nulls)}`);return n.some(o=>o.field==="_id"||o.field==="id")||r.push(`${pt("id")} ${mo(n)==="desc"?"DESC":"ASC"}`),r.join(", ")},ar={"<":"lt","<=":"lte","=":"eq",">":"gt",">=":"gte"},xn=n=>new Set(n.sqlConditions.filter(r=>r.comparator==="=").map(r=>r.field)),dr=n=>{const r=xn(n);let o=0;for(;o<n.indexFields.length&&r.has(n.indexFields[o]??"");)o+=1;return n.indexFields.slice(o)},lr=(n,r)=>{const o=n.order,s=dr(n),{shape:c}=r;return s.length>0?Kt(s.map(u=>({[u]:o})),c,{pinned:xn(n),uniqueBy:So(r.indexes,c)}):Kt([{_creationTime:o}],c)},ur=(n,r,o,s)=>{const c=n.sqlConditions.map(u=>({[u.field]:{[ar[u.comparator]??"eq"]:u.value}}));if(o&&c.push(vo(r,Nt(o))),s&&c.push(_o(r,Nt(s))),c.length!==0)return c.length===1?c[0]:{AND:c}},fr=n=>{if(n.want!==void 0)return n.selective?Math.max(n.want,ir):n.want},Et=(n,r,o,s,c,u,g)=>{const $=lr(s,o),y=In($),a=[],{filters:M,want:T}=u;let v=u.cursor??void 0,x=fr(u);if(T===0)return{documents:a,orderKeys:$};for(;;){const W=Z(ur(s,$,v,u.endCursor),Xe,Ye),P=An(r,c&&W?be(W," AND ",c):c??W,y,x),B=he(n,P.text,...P.params).toArray();let U={};g(B.length);for(const j of B)if(U=xe(j),M.every(ee=>ee(U))&&a.push(U)===T)return{documents:a,orderKeys:$};if(x===void 0||B.length<x)return{documents:a,orderKeys:$};v=Qe(U,$),x=Math.max(x,Math.min(x*2,sr))}},hr=(n,r,o,s,c,u,g,$)=>{const y=Math.max(0,Math.floor(c.numItems));if(typeof c.endCursor=="string"){const{documents:W,orderKeys:P}=Et(n,r,o,s,u,{cursor:c.cursor,endCursor:c.endCursor,filters:g.all,selective:g.selective,want:void 0},$),B=W.length>=2?W[Math.floor(W.length/2)-1]:void 0;return{continueCursor:c.endCursor,isDone:!0,page:W,splitCursor:B?Qe(B,P):null}}const{documents:a,orderKeys:M}=Et(n,r,o,s,u,{cursor:c.cursor,filters:g.all,selective:g.selective,want:y+1},$),T=a.length>y,v=T?a.slice(0,y):a,x=v.at(-1);return{continueCursor:T&&x?Qe(x,M):null,isDone:!T,page:v}},Ze=n=>{const r=new Map;return o=>{const s=r.get(o);if(s!==void 0)return s;const c=n(Me(o));return r.set(o,c),c}},we=Me(ie),wr=Ze(n=>`INSERT INTO ${n} (id, _creationTime, ${we}) VALUES (?, ?, ?)`),nn=Ze(n=>`UPDATE ${n} SET ${we} = ? WHERE id = ? AND ${we} = ?`),pr=Ze(n=>`UPDATE ${n} SET _creationTime = ?, ${we} = ? WHERE id = ? AND ${we} = ?`),gr=Ze(n=>`DELETE FROM ${n} WHERE id = ? AND ${we} = ?`),yr="SELECT changes() AS changed",on=new Map,Er="",$r=n=>{const r=JSON.stringify(n),o=on.get(r);if(o!==void 0)return o;const s=n.map(u=>d`SELECT ${d.raw(`'${u.replaceAll("'","''")}'`)} AS __t__, id, _creationTime, ${d.identifier(ie)} FROM ${d.identifier(u)} WHERE id = ${Er}`),{sql:c}=mn("sqlite",d`${Rn(s)} LIMIT 1`);return on.set(r,c),c},mr=(n,r)=>r.map(()=>n),Rr=/^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/iu,Sr=n=>{if(!Rr.test(n))throw new R("INTERNAL",`invalid clientId ${JSON.stringify(n)}: a client-supplied row id must be a UUID`)},$t=n=>{if(n.includes("\0"))throw new R("BAD_REQUEST",`invalid row id ${JSON.stringify(n)}: a row id cannot hold a NUL character (U+0000)`)},vr=(n,r,o,s)=>{if(o!==!0)return;const c=n!==void 0&&"serverDefault"in(n.shape._id?._meta?.column??{});for(const u of r){const g=c?yt(n,u,s)._id:u._id;typeof g=="string"&&$t(g)}},rn=50,je=Math.floor(Sn.boundParams/3),sn=Sn.boundParams,_r=128,Je=n=>new R("BATCH_LIMIT_EXCEEDED",n,{status:400}),He=(n,r,o)=>{Tn(n,_n(r,o,Je),o,Je)},cn=async(n,r,o,s,c)=>{const u=_n(s,c,Je),{page:g}=await n.findMany(r,Number.isFinite(u)?{limit:u+1,omitContinueCursor:!0,where:o}:{where:o});return g.length>u&&Tn(Math.max(await n.count(r,{where:o}),g.length),u,c,Je),g},Tr=n=>{const r={eq:(o,s)=>(n.sqlConditions.push({comparator:"=",field:o,value:s}),r),gt:(o,s)=>(n.sqlConditions.push({comparator:">",field:o,value:s}),r),gte:(o,s)=>(n.sqlConditions.push({comparator:">=",field:o,value:s}),r),lt:(o,s)=>(n.sqlConditions.push({comparator:"<",field:o,value:s}),r),lte:(o,s)=>(n.sqlConditions.push({comparator:"<=",field:o,value:s}),r)};return r},Ar=n=>Math.max(n,z),bn=(n,r)=>{const o=n.filters.map(s=>d`${fe(s.field)} = ${Ce(s.value)}`);return r&&o.push(r),o},Ir=(n,r,o,s,c)=>{const u=St(o.query,Rt(o.definition.language));if(u.length===0)return[];const g=Un(r,o.indexName),$=`${g}__vocab`,y=u.length-1,a=u.map((P,B)=>{const U=zo(P,B===y),j=U.exact?d`${d.identifier("term")} = ${U.lower}`:d`${d.identifier("term")} >= ${U.lower} AND ${d.identifier("term")} < ${U.upper}`;return d`SELECT ${d.identifier("doc")}, ${d.raw(String(B))} AS ${d.identifier("__term__")}, COUNT(*) AS ${d.identifier("__n__")} FROM ${d.identifier($)} WHERE ${j} GROUP BY ${d.identifier("doc")}`}),M=u.map((P,B)=>d`SUM(CASE WHEN u.${d.identifier("__term__")} = ${d.raw(String(B))} THEN u.${d.identifier("__n__")} ELSE 0 END)`),T=d`SELECT f.${d.identifier(qe)} AS ${d.identifier(qe)}, ${d.join(M,d` + `)} AS ${d.identifier("__score__")} FROM (${Rn(a)}) u JOIN ${d.identifier(g)} f ON f.rowid = u.${d.identifier("doc")} GROUP BY f.${d.identifier(qe)} HAVING ${d.join(M.map(P=>d`${P} > 0`),d` AND `)}`,v=bn(o,c);let x=d`SELECT m.id, m._creationTime, m.${d.identifier(ie)}, s.${d.identifier("__score__")} AS ${d.identifier("__score__")} FROM (${T}) s JOIN ${d.identifier(r)} m ON m.id = s.${d.identifier(qe)}`;v.length>0&&(x=d`${x} WHERE ${d.join(v,d` AND `)}`),x=d`${x} ORDER BY s.${d.identifier("__score__")} DESC, m._creationTime DESC, m.id ASC LIMIT ${d.raw(String(s))}`;const W=[];for(const P of K(n,x)){const B=$n(P);if(B){const U=P.__score__;W.push({document:B,score:typeof U=="number"?U:Number(U??0)})}}return W},xr=(n,r,o,s,c)=>{const u=Rt(o.definition.language),g=St(o.query,u);if(g.length===0)return[];const $=bn(o,c);let y=d`SELECT id, _creationTime, ${d.identifier(ie)} FROM ${d.identifier(r)}`;$.length>0&&(y=d`${y} WHERE ${d.join($,d` AND `)}`),y=d`${y} ORDER BY _creationTime DESC, id ASC LIMIT ${d.raw(String(Ar(s)))}`;const a=K(n,y).toArray(),M=[];for(const T of a){const v=$n(T);if(!v)continue;const x=Jo(On(v,o.definition),g);x>0&&M.push({creationTime:typeof v._creationTime=="number"?v._creationTime:0,doc:v,id:typeof v._id=="string"?v._id:"",score:x})}return M.sort((T,v)=>v.score-T.score||v.creationTime-T.creationTime||T.id.localeCompare(v.id)),M.slice(0,s).map(T=>({document:T.doc,score:T.score}))},ft=(n,r,o,s)=>{if(!Number.isFinite(n.lat)||n.lat<-90||n.lat>90||!Number.isFinite(n.lng)||n.lng<-180||n.lng>180)throw new R("BAD_REQUEST",`geo index "${s}" on table "${o}": ${r} must have a finite lat in [-90, 90] and lng in [-180, 180]`)},br=(n,r)=>{const o=n,s={near:(c,u)=>{if(o.within)throw new R("INTERNAL",`geo index "${o.indexName}" on table "${r}": call .near() or .within(), not both`);if(ft(c,".near() point",r,o.indexName),!Number.isFinite(u)||u<=0)throw new R("BAD_REQUEST",`geo index "${o.indexName}" on table "${r}": .near() radiusMeters must be a finite number > 0, got ${String(u)}`);return o.near={point:{lat:c.lat,lng:c.lng},radiusMeters:u},s},within:c=>{if(o.near)throw new R("INTERNAL",`geo index "${o.indexName}" on table "${r}": call .near() or .within(), not both`);if(ft(c.sw,".within() sw corner",r,o.indexName),ft(c.ne,".within() ne corner",r,o.indexName),c.sw.lat>c.ne.lat)throw new R("BAD_REQUEST",`geo index "${o.indexName}" on table "${r}": .within() corners are transposed (sw.lat > ne.lat)`);if(c.sw.lng>c.ne.lng)throw new R("BAD_REQUEST",`geo index "${o.indexName}" on table "${r}": .within() box crosses the antimeridian (sw.lng > ne.lng), which is not supported — split it into two boxes at ±180 and union the results`);return o.within={ne:{lat:c.ne.lat,lng:c.ne.lng},sw:{lat:c.sw.lat,lng:c.sw.lng}},s}};return s},Cr=(n,r)=>{const o=n[r];if(o===null||typeof o!="object")return;const{lat:s,lng:c}=o;return typeof s=="number"&&typeof c=="number"?{lat:s,lng:c}:void 0},Mr=(n,r)=>{const o=Cr(n,r.definition.field);if(!o)return;const s=typeof n._creationTime=="number"?n._creationTime:0;if(r.near){const c=wo(r.near.point,o);return c<=r.near.radiusMeters?{creationTime:s,distance:c}:void 0}return po(o,r.within)?{creationTime:s,distance:0}:void 0},Dr=(n,r,o,s)=>{if(!o.near&&!o.within)throw new R("INTERNAL",`geo index "${o.indexName}" on table "${r}": call .near(point, radius) or .within(box)`);const c=o.near?fo(o.near.point,o.near.radiusMeters):ho(o.within),u=ao(r,o.indexName),g=c.map(T=>d`(g.${d.identifier("__geohash__")} >= ${T} AND g.${d.identifier("__geohash__")} < ${`${T}{`})`),$=[d`(${d.join(g,d` OR `)})`];s&&$.push(s);const y=d`SELECT m.id, m._creationTime, m.${d.identifier(ie)} FROM ${d.identifier(u)} g JOIN ${d.identifier(r)} m ON m.id = g.${d.identifier("__id__")} WHERE ${d.join($,d` AND `)}`,a=K(n,y).toArray(),M=[];for(const T of a){const v=xe(T),x=v?Mr(v,o):void 0;v&&x&&M.push({creationTime:x.creationTime,distance:x.distance,doc:v})}return M.sort((T,v)=>T.distance-v.distance||v.creationTime-T.creationTime),M},Cn=(n,r,o,s)=>{const c=[];for(const u of n)if(r.every(g=>g(s(u)))&&(c.push(u),typeof o=="number"&&c.length>=o))break;return c},kr=(n,r,o,s,c,u=()=>{})=>{const g=o.within!==void 0,$=Dr(n,r,o,c).map(y=>({distanceMeters:g?null:y.distance,document:y.doc}));return u($.length),typeof s=="number"?$.slice(0,Math.max(0,Math.floor(s))):$},an=(n,r,o,s,c,u,g=()=>{})=>{const{geo:$}=o;if(!$)throw new R("INTERNAL","runGeoTerminalScored called without a staged geo query");const y=c.length>0,a=kr(n,r,$,y?void 0:u,s,g);return y?Cn(a,c,u,M=>M.document):a},dn=(n,r,o)=>{const s=n.shape[r];if(s!==void 0&&Ho(s))throw new R("BAD_REQUEST",`${o}: "${r}" may hold an order-preserving key rather than a value SQL can reduce or group — declare an aggregateIndex covering this (by, field, op) so the maintained companion answers it instead (its running total is a REAL, so it stays exact only while the total is inside 2^53)`)},Lr=n=>{let r=0;const o=[],s={...Xe,relationExists:c=>{const{childWhere:u,negated:g,parentTable:$,relation:y}=c,a=`__rel_${String(r)}`,M=o.at(-1)??$;r+=1,n(y.table,G);const T=y.kind==="one"?y.field:y.references,v=y.kind==="one"?y.references:y.field,x=Ve(`${jt(a,v)} = ${jt(M,T)}`);o.push(a);const W=Z(u,s,Ye);o.pop();const P=W===void 0?x:be(x," AND ",W),B=be("EXISTS (SELECT 1 FROM ",zt(y.table)," AS ",zt(a)," WHERE ",P,")");return g?be("NOT ",B):B}};return s};class Fr extends R{constructor(r="unique() found more than one matching document"){super("NOT_UNIQUE",r,{name:"NotUniqueError"})}}const Br=/\s/u,Wr=String.fromCodePoint(0),ln=(n,r,o)=>{if(!n.tables[r])throw new R("INTERNAL",`unknown table: ${r}`);return typeof o!="string"||o.length===0||Br.test(o)||o.includes(Wr)?null:o},Mn=(n,r,o,s=()=>{},c=()=>{},u=()=>{},g)=>{const $=r.tables[o];if(!$)throw new R("INTERNAL",`unknown table: ${o}`);const y=Ae($.softDeleteMode,void 0),a=g??{indexFields:[],indexName:void 0,inMemoryFilters:[],order:"asc",sqlConditions:[],verifyFilters:[]},M=()=>{const S=Q(y,a.pushedWhere);return S?Z(S,ue):void 0},T=()=>{const S=Q(y,a.pushedWhere);return S?Z(S,Xe,Ye):void 0},v=()=>[...a.inMemoryFilters,...a.verifyFilters];let x=0;const W=S=>{const{search:C}=a;if(!C)throw new R("INTERNAL","runSearchFetch called without a staged search");Vn(so(n),o,$);const L=a.inMemoryFilters.length>0,F=rr(L?void 0:S),k=co(n);if(k&&!Jn(n,o,C.definition))throw new R("SEARCH_INDEX_BUILDING",`search index "${C.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 pe=M(),te=k?Ir(n,o,C,F,pe):xr(n,o,C,F,pe);!L&&S===void 0&&Xo(te);const ge=v();return x=te.length,ge.length>0?Cn(te,ge,S,J=>J.document):te},P=S=>W(S).map(C=>C.document),B=S=>{const C=nr(S);return or(P(Zo(C)),C)},U=()=>{if(a.search||a.geo||a.indexName===void 0){c(void 0);return}c(Do(o,a.indexName,a.indexFields,a.sqlConditions,Ce))},j=S=>{U();let C=0;const L=(()=>{if(a.search){const F=P(S);return C=x,F}return a.geo?an(n,o,a,M(),v(),S,F=>{C=F}).map(F=>F.document):Et(n,o,$,a,T(),{filters:v(),selective:a.inMemoryFilters.length>0,want:S===void 0?void 0:Math.max(0,Math.floor(S))},F=>{C+=F}).documents})();return u(Math.max(C,L.length)),L},ee=()=>{if(!a.search&&!a.geo)throw new R("INTERNAL",`ctx.db.query("${o}").collectWithScores() requires a staged .withSearchIndex(...) or .withGeoIndex(...)`);U();let S=0;const C=(()=>{if(a.search){const L=W(void 0);return S=x,L}return an(n,o,a,M(),v(),void 0,L=>{S=L})})();return u(Math.max(S,C.length)),C},N={async*[Symbol.asyncIterator](){const S=Mn(n,r,o,s,c,u,{...a,indexFields:[...a.indexFields],inMemoryFilters:[...a.inMemoryFilters],sqlConditions:[...a.sqlConditions],verifyFilters:[...a.verifyFilters]});if(a.search){yield*await S.collect();return}let C;for(;;){const L=await S.paginate({cursor:C??null,numItems:_r});if(yield*L.page,L.isDone||L.continueCursor===null)return;C=L.continueCursor}},async collect(){return j(void 0)},async collectWithScores(){return ee()},filter(S){const C=ko(S);return C!==void 0&&Lo(C,$.shape)?(a.pushedWhere=Q(a.pushedWhere,C),a.verifyFilters.push(S)):a.inMemoryFilters.push(S),N},async first(){return j(1)[0]??null},order(S){return a.order=S==="desc"?"desc":"asc",N},async paginate(S){let C=0;if(U(),a.search){const F=B(S);return u(F.page.length),F}if(a.geo)throw new R("INTERNAL","pagination is not supported on geo queries; use .take(n) or .collect()");const L=hr(n,o,$,a,S,T(),{all:v(),selective:a.inMemoryFilters.length>0},F=>{C+=F});return u(Math.max(C,L.page.length)),L},async take(S){return j(S)},async unique(){const S=j(2);if(S.length>1)throw new Fr(`unique() on table "${o}" matched ${String(S.length)} documents; expected at most one`);return S[0]??null},withGeoIndex(S,C){const L=($.geoIndexes??[]).find(k=>k.name===S);if(!L)throw new R("INTERNAL",`unknown geo index "${S}" on table "${o}"`);s(o,S,"geo");const F={definition:L,indexName:S};if(a.geo=F,C(br(F,o)),!F.near&&!F.within)throw new R("INTERNAL",`geo index "${S}" on table "${o}" requires a .near(point, radius) or .within(box) call`);return N},withIndex(S,C){const L=$.indexes.find(F=>F.name===S);if(!L)throw new R("INTERNAL",`unknown index "${S}" on table "${o}"`);return s(o,S,"index"),a.indexName=S,a.indexFields=L.fields,C&&C(Tr(a)),N},withSearchIndex(S,C){const L=($.searchIndexes??[]).find(k=>k.name===S);if(!L)throw new R("INTERNAL",`unknown search index "${S}" on table "${o}"`);s(o,S,"search");const F={definition:L,field:L.field,filters:[],hasQuery:!1,indexName:S,query:""};if(a.search=F,C(Yo(F,o,Rt(L.language))),!F.hasQuery)throw new R("INTERNAL",`search index "${S}" on table "${o}" requires a .search(field, query) call`);return N}};return N},ht=(n,r,o,s)=>{const c=o;for(const[u,g]of io(n)){if(g.serverDefault){u in r&&(c[u]=g.serverDefault({auth:s}));continue}g.onUpdateFn&&!(u in r)&&(c[u]=g.onUpdateFn())}},un=5,fn=(n,r)=>{for(const o of Object.keys(r))if(r[o]===void 0)throw new R("INTERNAL",`Cannot ${n} field '${o}' to undefined — use null to clear a nullable field, or omit the key to leave it unchanged.`)},hn=["_commitSeq","_creationTime","_id"],Ke=n=>hn.some(r=>r in n)?Object.fromEntries(Object.entries(n).filter(([r])=>!hn.includes(r))):n,qr=/unique constraint failed/i,Pr=n=>n instanceof Error&&qr.test(n.message),Ur=/string or blob too big/iu,Or=(n,r)=>{if(!(!(n instanceof Error)||!Ur.test(n.message)))throw new R("PAYLOAD_TOO_LARGE",`document is too large to store in "${r}": a single row cannot exceed the storage engine's per-row ceiling (2 MB on a Durable Object's SQLite). The limit is on the STORED bytes, which are UTF-8, and v.bytes()/v.bigint() columns are stored twice on a shard-local table. Keep the payload in R2 (ctx.storage) and store a reference on the row.`)},mt=(n,r,o,s)=>{try{he(n,o,...s)}catch(c){throw Pr(c)?new se(`unique constraint violation on "${r}"`,"unique"):(Or(c,r),c)}},Ne=(n,r,o,s)=>{if(mt(n,r,o,s),he(n,yr).one().changed===0)throw new se(`optimistic concurrency conflict on "${r}" — the row changed during this mutation; refetch and retry`,"occ")},wn=(n,r,o,s,c,u,g)=>{const $=[];for(let T=0;T<o.length+1;T+=1){const v=o[T],x=s[T],W=x?.direction==="desc"?"desc":"asc",P=v===void 0||x===void 0?d`${d.identifier(Io)} < ${g}`:xo(v,u[T],W,!1);if(P===void 0)continue;const B=[];for(let j=0;j<T;j+=1)B.push(d`${d.identifier(o[j])} IS ${u[j]}`);B.push(P);const[U]=B;$.push(B.length===1&&U!==void 0?U:d`(${d.join(B,d` AND `)})`)}const y=$.length>0?d.join($,d` OR `):d`1 = 0`,a=K(n,d`SELECT COUNT(*) AS c FROM ${d.identifier(r)} WHERE ${d.identifier("__partition__")} = ${c} AND (${y})`).one(),M=K(n,d`SELECT COUNT(*) AS c FROM ${d.identifier(r)} WHERE ${d.identifier("__partition__")} = ${c}`).one();return{before:a.c,total:M.c}},Gr=n=>{const r=new Map;for(const[s,c]of Object.entries(n.tables))for(const u of Object.values(c.relationMap??{}))u.kind==="one"&&(u.onDelete==="cascade"||u.onDelete==="set null")&&r.set(u.table,[...r.get(u.table)??[],{holder:s,op:u.onDelete==="cascade"?"delete":"update"}]);const o=s=>{const c=new Set,u=[s];for(let g=u.pop();g!==void 0;g=u.pop())for(const{holder:$,op:y}of r.get(g)??[]){if($===s||Zt(n,$,y))return!0;c.has($)||(c.add($),u.push($))}return!1};return new Set(Object.entries(n.tables).filter(([s,c])=>c.shardMode?.kind==="global"||Zt(n,s,"delete")||o(s)).map(([s])=>s))},jr=n=>{const r=new Map;for(const[o,s]of Object.entries(n.tables))s.softDeleteMode&&r.set(o,s.softDeleteMode.field);return r},wt=new WeakMap,Hr=(n,r)=>{let o=wt.get(r.tables);if(!wt.has(r.tables)){const c=Object.keys(r.tables).map(u=>u.replaceAll(/[$()*+.?[\\\]^{|}]/gu,String.raw`\$&`));o=c.length===0?void 0:new RegExp(`"(${c.join("|")})"`,"gu"),wt.set(r.tables,o)}if(o===void 0)return;const s=new Set;for(const c of n.matchAll(o))s.add(c[1]);return s.size===1?[...s][0]:void 0},Kr=(n,r,o)=>{for(const s of n){const c=s,u=c?.[ie];if(typeof u=="string"){const g=c?.id,$=uo(u);typeof g!="string"?r.recordReadBytes($):o===void 0?r.recordDocumentRead(`${g}\0${String($)}`,$):r.recordDocumentRead(`${o}\0${g}`,$)}}},Nr=(n,r,o)=>{if(r===void 0)return n;const s=(c,...u)=>{const g=n.exec(c,...u),$=g.one.bind(g),y=g[Symbol.iterator].bind(g),a=o===void 0?void 0:Hr(c,o);let M=!1;const T=v=>{Kr(v,r,a)};return g.toArray=()=>{const v=[];for(const x of{[Symbol.iterator]:y})T([x]),v.push(x);return v},g.one=()=>{M=!0;try{const v=$();return T([v]),v}finally{M=!1}},g[Symbol.iterator]=function*(){for(const x of{[Symbol.iterator]:y})M||T([x]),yield x},g};return new Proxy(n,{get:(c,u)=>u==="exec"?s:u===oo?c:Reflect.get(c,u,c)})},Qr=new Map([["findFirst","rows"],["findFirstOrThrow","rows"],["findMany","page"],["get","rows"],["lookupById","lookup"],["rankPage","page"]]),Vr=new Map([["collect","rows"],["collectWithScores","scored"],["first","rows"],["paginate","page"],["take","rows"],["unique","rows"]]),Ie=(n,r,o)=>{if(typeof n!="object"||n===null)return;const s=lo(n);if(s===void 0)return;const c=n._id;typeof c=="string"?o.recordDocumentRead(`global\0${r}\0${c}`,s):o.recordReadBytes(s)},ze=(n,r,o,s)=>{if(typeof n!="object"||n===null)return;const c=n;switch(r){case"lookup":{Ie(c.row,typeof c.tableName=="string"?c.tableName:o,s);return}case"page":{for(const u of c.page??[])Ie(u,o,s);return}case"rows":{for(const u of Array.isArray(n)?n:[n])Ie(u,o,s);return}default:for(const u of Array.isArray(n)?n:[])Ie(u.document,o,s)}},Dn=(n,r,o)=>new Proxy(n,{get:(s,c)=>{const u=Reflect.get(s,c,s);if(typeof u!="function")return u;if(c===Symbol.asyncIterator)return async function*(){for await(const y of Reflect.apply(u,s,[]))Ie(y,r,o),yield y};const g=Vr.get(c);return(...$)=>{const y=Reflect.apply(u,s,$);return g!==void 0?Promise.resolve(y).then(a=>(ze(a,g,r,o),a)):typeof y=="object"&&y!==null&&!(y instanceof Promise)?Dn(y,r,o):y}}}),Jr=new Set(["findFirst","findFirstOrThrow","findMany"]),zr=n=>{const r=n[1],o=r?.select;if(!Array.isArray(o))return;const s=Object.fromEntries(Object.entries(r).filter(([g])=>g!=="select")),c=s.with,u=g=>gt(g,o,c);return{args:[n[0],s,...n.slice(2)],project:(g,$)=>typeof g!="object"||g===null?g:$==="page"?{...g,page:u(g.page)}:u([g])[0]}},pn=256,gn=4096,Yr=1024*1024,Xr=async(n,r,o,s)=>{const c=r[1]??{},u=[];let{cursor:g}=c,$=pn,y=0;for(;;){const a=await n([r[0],{...c,cursor:g,limit:$},...r.slice(2)]);if(Array.isArray(a))return ze(a,"rows",o,s),[...u,...a];const M=s.headroom().readBytes;if(ze(a,"page",o,s),u.push(...a.page),a.isDone||typeof a.continueCursor!="string")return{continueCursor:null,isDone:!0,page:u};g=a.continueCursor,y+=s.headroom().readBytes-M,$=y>0?Math.min(gn,Math.max(pn,Math.floor(Yr*u.length/y))):gn}},Zr=(n,r)=>n===void 0||r===void 0?n:new Proxy(n,{get:(o,s)=>{const c=Reflect.get(o,s,o);if(typeof c!="function")return c;if(s==="query")return(...g)=>Dn(Reflect.apply(c,o,g),String(g[0]),r);const u=Qr.get(s);return u===void 0?c:async(...g)=>{const $=Jr.has(s)?zr(g):void 0,y=$?.args??g,a=String(g[0]);if(s==="findMany"&&typeof y[1]?.limit!="number"){const v=await Xr(x=>Reflect.apply(c,o,x),y,a,r);return $===void 0?v:$.project(v,u)}const T=await Reflect.apply(c,o,y);return ze(T,u,a,r),$===void 0?T:$.project(T,u)}}}),yn=new WeakMap,En=new WeakMap,ei=n=>{const{baselineSeq:r,onStalePatchDropped:o}=n,{headroom:s}=n,c=yn.get(n)??{value:void 0},u=En.get(n)??{value:0};let g;const $=()=>{if(g===void 0){const e={...n,enforceRls:!1,headroom:void 0};yn.set(e,c),En.set(e,u),g=ei(e)}return g},y=Nr(n.sql,s,n.schema),{schema:a}=n,M=n.broadcast??(()=>{}),T=(e,t)=>{if(!Object.hasOwn(a.tables,e))throw new R("BAD_REQUEST",`${t}: "${e}" is not a table in this schema`)},v=Fo(a),x=new Map;for(const e of v){const t=i=>(a.tables[i]?.shardMode?.kind??"root")==="root";!e.array&&t(e.sourceTable)&&t(e.targetTable)&&x.set(e.sourceTable,[...x.get(e.sourceTable)??[],e])}const W=(e,t,i)=>{for(const l of x.get(e)??[]){const w=t[l.column];if(typeof w!="string"||i?.[l.column]===w||l.targetTable===e&&t._id===w)continue;if(K(y,d`SELECT 1 FROM ${d.identifier(l.targetTable)} WHERE id = ${w} LIMIT 1`).toArray().length===0)throw new R("VALIDATION_ERROR",`${l.name} references ${l.targetTable} row "${w}", which does not exist`)}},P=Po(a,n.inTransaction),B=Gr(a),U=jr(a),j=()=>n.inTransaction?.()===!0,ee=e=>a.tables[e]?.commitOrderedMode!==!0?{}:((c.value===void 0||!j())&&(c.value=Xn(y)),{[Zn]:c.value}),N=(e,...t)=>{const i=a.tables[e]?.indexes??[],l=[];let w;for(const p of t)p&&(typeof p._id=="string"&&p._id!==w&&(w=p._id,l.push(bo(w))),l.push(...Co(i,Mo(i,p,Ce))));return l.length>0?l:void 0},S=n.onRead??(()=>{}),C=e=>{Ot(a.tables[e])&&S(Jt,Jt)},L=n.onReadRange??(e=>{S(e.table,G)}),F=e=>{C(e.table),L(e)},k=(e,t,i)=>{t!==void 0&&(i===!0||t!==G)&&s?.recordRead(1),C(e),S(e,t,i)},pe=(e,t)=>{const i=e.row._id;k(e.tableName,typeof i=="string"?i:t,typeof i=="string")},te=n.onIndexUse??(()=>{}),ge=n.onWrite??(()=>{}),J=e=>{s?.recordWrite(e)},ye=async e=>{J(e.doc),await ge(e)},{cache:Ee}=n,$e=n.clock??(()=>Date.now()),vt=n.idGenerator??(()=>crypto.randomUUID()),_t=n.scheduler??jn,me=Zr(n.globalDb,s),ce=n.auth??{identity:null,userId:null},Tt=n.cdc??!1,et=_t,kn=Ko({scheduler:typeof et.list=="function"&&typeof et.get=="function"?et:void 0,storage:n.storage}),Re=(e,t,i,l)=>{Tt&&!Ot(a.tables[e])&&zn(y,$e(),e,t,i,l)},At=(e,t,i,l)=>{const w=a.tables[e];if(w?.dropStalePatchesMode!==!0||!Tt)return!1;const p=r?.();if(p===void 0)return!1;const f=Yn(y,e,t,p);if(f===void 0)return!1;const h=$o(w,i);return Object.keys(Ke(i)).some(E=>!h.has(E)&&Ut(Ht(f,E))!==Ut(Ht(l,E)))},ae=e=>a.tables[e]?.shardMode?.kind==="global",It=(e,t)=>{if(ae(e)){if(!me)throw new R("INTERNAL",`cross-backend ${t} for global table '${e}' requires a globalDb writer — pass one to createShardCtxDb({ globalDb })`);return me}return O},tt=e=>It(e,"cascade"),H=(e,t)=>{if(ae(e)){if(!me)throw new R("INTERNAL",`${t} on global table '${e}' requires a globalDb writer — pass one to createShardCtxDb({ globalDb })`);return me}},xt=async(e,t,i,l,w)=>{w&&J(i);const p=await e.insert(t,i,l);return M({key:p,op:"insert",row:{...i,_id:p},table:t}),p},nt=(e,t)=>It(e,"relation load").findMany(e,t),bt=(e,t)=>(ae(e)&&k(e,G),nt(e,t)),Ln=e=>!ae(e.table),Ct=n.relationExistsPushDown??"auto",Mt=Ct!=="never",{maxRelationKeys:Dt}=n,De=(e,t,i)=>Wo(e,{fetcher:bt,maxRelationKeys:Dt,relationBaseWhere:i,schema:a,tableName:t}),kt=async(e,t,i,l)=>{const w=H(e,"relation grouped count");if(w)return k(e,G),Go((m,q)=>w.count(m,q),e,t,i,l);const p=a.tables[e];if(!p)throw new R("INTERNAL",`unknown table: ${e}`);k(e,G);const f=Ae(p.softDeleteMode,void 0),h={[t]:{in:i}},E=Q(Q(h,l),f),_=await De(E,e,void 0),b=Z(_,ue),A=fe(t);let I=d`SELECT ${A} AS __fk__, COUNT(*) AS count FROM ${d.identifier(e)}`;b&&(I=d`${I} WHERE ${b}`),I=d`${I} GROUP BY ${A}`;const D=K(y,I).toArray();return new Map(D.map(m=>[m.__fk__,m.count]))},Lt=new Set;for(const[e,t]of Object.entries(a.tables))for(const i of Object.values(t.triggerMap??{}))Lt.add(`${e} ${i.timing} ${i.op}`);const ne=(e,t,i)=>Lt.has(`${e} ${t} ${i}`),oe=async(e,t,i)=>{if(u.value+=1,u.value>rn)throw u.value-=1,new se(`trigger recursion exceeded ${String(rn)} levels on "${i.table}" — check for a self-triggering write`,"trigger");try{await No({ctx:qn,event:i,op:t,schema:a,tableName:i.table,timing:e})}finally{u.value-=1}},{ensureBackfilledForTable:Se,ensureBackfilledIndex:ot,ensureRankBackfilled:rt,ensureRankBackfilledForTable:ve,syncAggregates:ke,syncCompanionsForInsert:Ft,syncGeo:Le,syncRanks:_e,syncSearch:Fe}=eo({broadcast:M,indexKeysFor:(e,t)=>N(e,t),invalidateCache:(e,t,i)=>Ee?.invalidate(e,t,N(e,i)),recordCdc:Re,schema:a,sql:y,verified:n.companionMemo?.verified}),Bt=(e,t,i)=>{const{shardMode:l}=t;if(l?.kind==="shardBy"&&!(l.field!==void 0&&(i.partitionBy??[]).includes(l.field)))throw Object.assign(new Error(`rank index "${i.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})},Wt=e=>Object.entries(a.tables).filter(([,t])=>t.shardMode?.kind!=="global").map(([t])=>t).filter(t=>e===void 0||t===e),Te=e=>e===void 0||ae(e)?me:void 0,it=async(e,t,i,l,w)=>{for(let p=0;p<i.length;p+=1)J(void 0);if(w!==void 0&&e.deleteMany!==void 0)return e.deleteMany(t,i,w.options);for(const p of i)await e.delete(t,p,l);return{deleted:i.length}},re=(e,t)=>{const i=Wt(t);for(let l=0;l<i.length;l+=sn){const w=i.slice(l,l+sn),[p]=he(y,$r(w),...mr(e,w)).toArray();if(!p)continue;const f=p.__t__,h=xe(p);if(typeof f!="string"||!h)return;const E=p[ie];return{docJson:typeof E=="string"?E:le(E??{}),row:h,tableName:f}}},qt={assertRankPartitionLocal:Bt,ensureRankBackfilled:rt,onRead:k,rowToDocument:xe,schema:a,sql:y},Fn=(e,t,i)=>{const l=Z(i,ue);return l===void 0||K(y,d`SELECT 1 FROM ${d.identifier(e)} WHERE ${d.identifier("id")} = ${t} AND ${l}`).toArray().length>0},Bn=(e,t,i,l)=>At(e,t,i,l)?(o?.({fields:Object.keys(Ke(i)),id:t,table:e}),!0):!1,Wn=async(e,t,i,l,w)=>{const p=re(t,e);if(!p)return{applied:!1,doc:null};if(k(e,t),!Fn(e,t,i.where)||Bn(e,t,i.patch,p.row))return{applied:!1,doc:p.row};try{await w(i.patch)}catch(f){if(f instanceof se&&f.kind==="occ"&&l)return;throw f}return{applied:!0,doc:re(t,e)?.row??null}},Pt=async(e,t,i,l)=>{const{fetchLimit:w,limit:p,orderKeys:f,predicate:h}=await qo(t,i,{canPushExists:Mt?Ln:void 0,existsPushMode:Ct==="always"?"always":"auto",fetcher:bt,maxRelationKeys:Dt,schema:a,tableName:e}),E=Mt?Lr(l):Xe,_=Z(h,E,Ye),b=An(e,_,In(f),w);return{limit:p,orderKeys:f,statement:b}},O={system:kn,async aggregate(e,t){const i=H(e,"aggregate");if(i)return k(e,G),i.aggregate(e,t);const l=a.tables[e];if(!l)throw new R("INTERNAL",`unknown table: ${e}`);if(Pe(t.op),t.op==="count")return O.count(e,{baseWhere:t.baseWhere,relationBaseWhere:t.relationBaseWhere,restrictsCounts:t.restrictsCounts,where:t.where});if(!t.field)throw new R("INTERNAL",`aggregate(${e}, { op: "${t.op}" }): "field" is required for non-count reducers`);k(e,G);const w=Ae(l.softDeleteMode,void 0),p=Q(Q(t.baseWhere,t.where),w),f=await De(p,e,t.relationBaseWhere),h=f!==p;if(l.aggregateIndexes&&!t.baseWhere&&!h){const m=Qn(l.aggregateIndexes,t.op,t.field,t.where);if(m){ot(e,m.index);const q=ct(m.index.by??[],m.key),Y=st(e,m.index.name),X=K(y,d`SELECT ${Ue} AS value, ${lt} AS count FROM ${d.identifier(Y)} WHERE ${Oe} = ${q}`).toArray()[0];return at(t.op,X)}}dn(l,t.field,`aggregate(${e}, { op: "${t.op}", field: "${t.field}" })`);const E=Z(f,ue),_=Pe(t.op),b=fe(t.field);let A=d`SELECT ${d.raw(_)}(${b}) AS value FROM ${d.identifier(e)}`;E&&(A=d`${A} WHERE ${E}`);const D=K(y,A).toArray()[0]?.value;return D??null},asId(e,t){const i=ln(a,e,t);if(i===null)throw new R("BAD_REQUEST",`asId("${e}", …): "${t}" is not a valid id for table "${e}"`,{status:400});return i},async count(e,t){const i=H(e,"count");if(i)return k(e,G),i.count(e,t);const l=a.tables[e];if(!l)throw new R("INTERNAL",`unknown table: ${e}`);const w=Hn(t);if(w.restrictsCounts)throw new dt(e);k(e,G);const p=Ae(l.softDeleteMode,void 0),f=Q(Q(w.baseWhere,w.where),p),h=await De(f,e,w.relationBaseWhere),E=h!==f;if(l.aggregateIndexes&&!w.baseWhere&&!E){const I=Nn(l.aggregateIndexes,w.where);if(I){ot(e,I.index);const D=ct(I.index.by??[],I.key),m=st(e,I.index.name),q=K(y,d`SELECT ${Ue} AS value FROM ${d.identifier(m)} WHERE ${Oe} = ${D}`).toArray();return q[0]===void 0?0:q[0].value??0}}const _=Z(h,ue);let b=d`SELECT COUNT(*) AS count FROM ${d.identifier(e)}`;return _&&(b=d`${b} WHERE ${_}`),K(y,b).one().count},async delete(e,t,i){T(e,"ctx.db.delete(table, id)");const l=re(t,e);if(!l){const I=Te(e);I&&await it(I,e,[t],i);return}const{docJson:w,row:p,tableName:f}=l,h=a.tables[f],E=i?.hard===!0,_=!E&&h?.softDeleteMode?h:void 0,b=_?.softDeleteMode?.field;if(b&&p[b]!==null&&p[b]!==void 0)return;if(ne(f,"before","delete")&&await oe("before","delete",{id:t,op:"delete",previous:p,table:f}),i?.skipOnDelete!==!0&&await Oo({deletedId:t,deletedReference:I=>p[I],findHolders:async(I,D,m,q)=>(await tt(I).findMany(I,{...q,includeDeleted:E,where:{[D]:m}})).page,onCascade:(I,D)=>tt(I).delete(I,D,i),onRestrict:I=>{throw new se(I,"restrict")},onSetNull:(I,D,m)=>tt(I).patch(I,D,{[m]:null}),schema:a,tableName:f}),Se(f),ve(f),_&&b){const I={[b]:$e()},D={...p,...ee(f),...I,_id:t};ht(_,I,D,ce),Ne(y,f,nn(f),[le(D),t,w]),Fe(f,t,D,p),Le(f,t,void 0),ke(f,p,D),_e(f,t,p,void 0);const m=N(f,p,D);Ee?.invalidate(f,t,m),Re(f,t,"update",D),M({indexKeys:m,key:t,op:"update",row:D,table:f}),ne(f,"after","delete")&&await oe("after","delete",{id:t,op:"delete",previous:p,table:f}),await ye({id:t,op:"delete",table:f});return}Ne(y,f,gr(f),[t,w]),Fe(f,t,void 0),Le(f,t,void 0),ke(f,p,void 0),_e(f,t,p,void 0);const A=N(f,p);Ee?.invalidate(f,t,A),Re(f,t,"delete"),M({indexKeys:A,key:t,op:"delete",table:f}),ne(f,"after","delete")&&await oe("after","delete",{id:t,op:"delete",previous:p,table:f}),await ye({id:t,op:"delete",table:f})},async deleteAll(e,t){if(!a.tables[e])throw new R("INTERNAL",`unknown table: ${e}`);if(s!==void 0)return $().deleteAll(e,t);const i=Math.max(1,t?.chunkSize??vn),l=t?.hard===void 0?void 0:{hard:t.hard},w=H(e,"deleteAll");let p=0;for(;;){const h=(await O.findMany(e,{limit:i})).page.map(E=>String(E._id));if(h.length===0)break;for(const E of h)await(w===void 0?O.delete(e,E,l):it(w,e,[E],l)),p+=1;if(h.length<i)break}return{deleted:p}},async deleteMany(e,t,i){T(e,"ctx.db.deleteMany(table, ids)"),He(t.length,i?.limit,"deleteMany");for(const l of t)await O.delete(e,l);return{deleted:t.length}},async deleteWhere(e,t,i){const l=H(e,"deleteWhere"),p=(await cn(l??O,e,t,i?.limit,"deleteWhere")).map(f=>String(f._id));if(l)return it(l,e,p,void 0,{options:i});if(O.deleteMany===void 0)throw new R("INTERNAL",`ctx.db.${e}.deleteMany is unavailable: this writer has no batch delete`);return O.deleteMany(e,p,i)},async findFirst(e,t={}){return(await O.findMany(e,{...t,limit:1,omitContinueCursor:!0})).page[0]??null},async findFirstOrThrow(e,t={}){const i=await O.findFirst(e,t);if(i===null)throw new go(`findFirstOrThrow: no "${e}" document matched`);return i},async findMany(e,t={}){const i=H(e,"findMany");if(i)return k(e,G),t.consistency==="primary"&&S(e,to),i.findMany(e,t);const l=a.tables[e];if(!l)throw new R("INTERNAL",`unknown table: ${e}`);const w=!t.where&&!t.baseWhere;w?k(e,G):k(e);const{limit:p,orderKeys:f,statement:h}=await Pt(e,l,t,k),E=he(y,h.text,...h.params).toArray();w&&s?.recordRead(E.length);const _=[];for(const D of E){const m=xe(D);m&&(_.push(m),!w&&typeof m._id=="string"&&k(e,m._id))}if(p===void 0)return t.with&&await Yt({groupedCounter:kt,fetcher:nt,parents:_,...Xt(t),schema:a,tableName:e,with:t.with}),{continueCursor:null,isDone:!0,page:gt(_,t.select,t.with)};const b=_.length>p,A=b?_.slice(0,p):_,I=A.at(-1);return t.with&&await Yt({fetcher:nt,groupedCounter:kt,parents:A,...Xt(t),schema:a,tableName:e,with:t.with}),{continueCursor:b&&I&&t.omitContinueCursor!==!0?Qe(I,f):null,isDone:!b,page:gt(A,t.select,t.with)}},async explain(e,t={}){const i=H(e,"explain");if(i)return i.explain(e,t);const l=a.tables[e];if(!l)throw new R("INTERNAL",`unknown table: ${e}`);const{statement:w}=await Pt(e,l,t,()=>{}),p=he(y,`EXPLAIN QUERY PLAN ${w.text}`,...w.params).toArray();return{params:w.params,plan:p.map(f=>String(f.detail)),sql:w.text}},async get(e,t){T(e,"ctx.db.get(table, id)");const i=re(t,e);if(!i){const l=Te(e);return l?l.get(e,t):(C(e),S(e,t,!0),null)}return pe(i,t),i.row},async lookupById(e,t){const i=re(e,t);if(!i){for(const l of Wt(t))C(l),S(l,e,!0);return null}return pe(i,e),{row:i.row,tableName:i.tableName}},async groupBy(e,t){const i=H(e,"groupBy");if(i)return k(e,G),i.groupBy(e,t);const l=a.tables[e];if(!l)throw new R("INTERNAL",`unknown table: ${e}`);k(e,G);const w=t.agg??{op:"count"};if(Pe(w.op),w.op!=="count"&&!w.field)throw new R("INTERNAL",`groupBy(${e}, { agg: { op: "${w.op}" } }): "field" is required for non-count reducers`);const p=Ae(l.softDeleteMode,void 0),f=Q(Q(t.baseWhere,t.where),p),h=await De(f,e,t.relationBaseWhere),E=h!==f;if(l.aggregateIndexes&&!t.baseWhere&&!E){const m=Kn(l.aggregateIndexes,w.op,w.field,t.by,t.where),q=m===void 0?0:Object.keys(m.partial).length,Y=m?.index.by?.length??0;if(m&&(q===0||q===Y)){ot(e,m.index);const X=st(e,m.index.name),V=Object.keys(m.partial),de=[];if(V.length===(m.index.by??[]).length&&V.length>0){const Be=ct(m.index.by??[],m.partial),We=K(y,d`SELECT ${Ue} AS value, ${lt} AS count FROM ${d.identifier(X)} WHERE ${Oe} = ${Be}`).toArray();return We.length>0&&de.push({key:{...m.partial},value:at(w.op,We[0])}),de}const Pn=K(y,d`SELECT ${Oe} AS key, ${Ue} AS value, ${lt} AS count FROM ${d.identifier(X)}`).toArray();for(const Be of Pn){const We=Gn(JSON.parse(Be.key));de.push({key:We,value:at(w.op,Be)})}return de}}for(const m of[...t.by,w.field]){if(m===void 0)continue;const q=m===w.field?`groupBy(${e}, { agg: { op: "${w.op}", field: "${m}" } })`:`groupBy(${e}, { by: [..."${m}"] })`;dn(l,m,q)}const _=Z(h,ue),b=t.by.map(m=>d`${fe(m)} AS ${d.identifier(m)}`);if(w.op==="count")b.push(d`COUNT(*) AS value`);else{const{field:m}=w;if(m===void 0)throw new R("INTERNAL",`groupBy(${e}, { agg: { op: "${w.op}" } }): "field" is required for non-count reducers`);b.push(d`${d.raw(Pe(w.op))}(${fe(m)}) AS value`)}let A=d`SELECT ${d.join(b,d`, `)} FROM ${d.identifier(e)}`;_&&(A=d`${A} WHERE ${_}`),A=d`${A} GROUP BY ${d.join(t.by.map(m=>fe(m)),d`, `)}`;const I=K(y,A).toArray(),D=[];for(const m of I){const q={};for(const X of t.by)q[X]=ro(l.shape[X],m[X]??null);const{value:Y}=m;D.push({key:q,value:Y==null?null:Number(Y)})}return D},async insert(e,t,i){const l=H(e,"insert");if(l)return xt(l,e,t,i,!0);const w=a.tables[e];if(!w)throw new R("INTERNAL",`unknown table: ${e}`);const p=i?.allowExplicitId===!0,f=Ge(w,yt(w,t,ce),{supplied:t,trusted:p});let h;i?.clientId!==void 0?(Sr(i.clientId),h=i.clientId):i?.allowExplicitId&&typeof f._id=="string"?($t(f._id),h=f._id):h=vt();const E=i?.allowExplicitId&&typeof f._creationTime=="number"?f._creationTime:$e(),_={...f,...ee(e),_creationTime:E,_id:h};return ne(e,"before","insert")&&await oe("before","insert",{doc:{..._},id:h,op:"insert",table:e}),p||W(e,_),Se(e),ve(e),mt(y,e,wr(e),[h,E,le(_)]),Ft(e,h,_),ne(e,"after","insert")&&await oe("after","insert",{doc:_,id:h,op:"insert",table:e}),await ye({doc:_,id:h,op:"insert",table:e}),h},async insertManyUnsafe(e,t,i){if(He(t.length,i?.limit,"insertManyUnsafe"),t.length===0)return[];const l=H(e,"insert");if(l){const E=[];vr(a.tables[e],t,i?.allowExplicitId,ce);for(const _ of t)J(_);for(const _ of t){const b=await l.insert(e,_,{allowExplicitId:i?.allowExplicitId});M({key:b,op:"insert",row:{..._,_id:b},table:e}),E.push(b)}return E}const w=a.tables[e];if(!w)throw new R("INTERNAL",`unknown table: ${e}`);Se(e),ve(e);const p=[];for(let E=0;E<t.length;E+=je)p.push(ee(e));const f=i?.allowExplicitId===!0?void 0:Uo(w),h=t.map((E,_)=>{const b=yt(w,E,ce),A=f===void 0?b:Ge(f,b,{supplied:E}),I=i?.allowExplicitId===!0&&typeof A._id=="string"?A._id:void 0;I!==void 0&&$t(I);const D=I??vt(),m=i?.allowExplicitId===!0&&typeof A._creationTime=="number"?A._creationTime:$e(),q={...A,...p[Math.floor(_/je)],_creationTime:m,_id:D};return{creationTime:m,document:q,id:D}});for(const E of h)J(E.document);for(let E=0;E<h.length;E+=je){const _=d.join(h.slice(E,E+je).map(A=>d`(${A.id}, ${A.creationTime}, ${le(A.document)})`),d`, `),b=mn("sqlite",d`INSERT INTO ${d.identifier(e)} (id, _creationTime, ${d.identifier(ie)}) VALUES ${_}`);mt(y,e,b.sql,b.params)}for(const{document:E,id:_}of h)Ft(e,_,E),await ge({doc:E,id:_,op:"insert",table:e});return h.map(E=>E.id)},async insertMany(e,t,i){He(t.length,i?.limit,"insertMany");const l=i?.skipDuplicates===!0,w=[],p=H(e,"insert");if(p)for(const h of t)J(h);const f=async h=>p?xt(p,e,h,void 0,!1):O.insert(e,h);for(const h of t)try{w.push(await f(h))}catch(E){if(l&&E instanceof se&&E.kind==="unique")w.push(null);else throw E}return w},normalizeId(e,t){return ln(a,e,t)},async patch(e,t,i,l){T(e,"ctx.db.patch(table, id, values)");const w=re(t,e);if(!w){const D=Te(e);if(D){J(i),await D.patch(e,t,i,l);return}throw new R("NOT_FOUND",`document not found: ${t}`)}const{docJson:p,row:f,tableName:h}=w,E=a.tables[h];if(!E)throw new R("INTERNAL",`unknown table: ${h}`);if(k(h,t),fn("patch",i),At(h,t,i,f)){o?.({fields:Object.keys(Ke(i)),id:t,table:h});return}const _=yo(E,i,f),b={...f,...Ke(_),...ee(h),_id:t};ht(E,_,b,ce);const A=Ge(E,b,{only:new Set(Object.keys(_)),previous:()=>f,tolerateStoredNull:!0});Eo(l,f,A),ne(h,"before","update")&&await oe("before","update",{doc:{...A},id:t,op:"update",previous:f,table:h}),W(h,A,f),Se(h),ve(h),Ne(y,h,nn(h),[le(A),t,p]),Fe(h,t,A,f),Le(h,t,A),ke(h,f,A),_e(h,t,f,A);const I=N(h,f,A);Ee?.invalidate(h,t,I),Re(h,t,"update",A),M({indexKeys:I,key:t,op:"update",row:A,table:h}),ne(h,"after","update")&&await oe("after","update",{doc:A,id:t,op:"update",previous:f,table:h}),await ye({doc:A,id:t,op:"update",table:h})},async patchIf(e,t,i){const l=H(e,"patchIf");if(l){if(l.patchIf===void 0)throw new R("INTERNAL",`ctx.db.patchIf on global table '${e}' is unsupported: its backend has no conditional write`);return J(i.patch),l.patchIf(e,t,i)}if(!a.tables[e])throw new R("INTERNAL",`unknown table: ${e}`);for(let w=1;w<=un;w+=1){const p=await Wn(e,t,i,w<un,f=>O.patch(e,t,f,{verify:i.verify}));if(p!==void 0)return p}throw new se(`patchIf on "${e}" kept conflicting; the row changed on every attempt`,"occ")},async patchMany(e,t,i){T(e,"ctx.db.patchMany(table, patches)"),He(t.length,i?.limit,"patchMany");for(const l of t)await O.patch(e,l.id,l.patch);return{patched:t.length}},async patchWhere(e,t,i){const l=H(e,"patchWhere")??O,p=(await cn(l,e,t.where,i?.limit,"patchWhere")).map(f=>({id:String(f._id),patch:t.patch}));if(O.patchMany===void 0)throw new R("INTERNAL",`ctx.db.${e}.patchMany is unavailable: this writer has no batch patch`);return await O.patchMany(e,p,i),{patched:p.length}},async related(e,t){return Bo(O,v,e,t)},relationEdges:v,deleteRereadTables:B,inTransaction:j,softDeleteFields:U,relationWrites:P,query(e){const t=H(e,"query");return t?(k(e,G),t.query(e)):Mn(y,a,e,te,i=>{i?F(i):k(e,G)},i=>{s?.recordRead(i)})},async rank(e,t,i){const l=H(e,"rank");if(l)return k(e,G),l.rank(e,t,i);te(e,t,"rank");const w=a.tables[e];if(!w)throw new R("INTERNAL",`unknown table: ${e}`);const p=w.rankIndexes?.find(V=>V.name===t);if(!p)throw new R("INTERNAL",`unknown rankIndex "${t}" on table "${e}"`);if(Bt(e,w,p),i.restrictsCounts)throw new dt(e);k(e,G),rt(e,p);const f=typeof i.row=="string"?i.row:i.row._id;if(!f)return null;const h=Qt(e,p.name),E=p.sortBy.map((V,de)=>Vt(de)),_=E.map(V=>Me(V)).join(", "),b=K(y,d`SELECT ${d.identifier("__partition__")}, ${d.raw(_)} FROM ${d.identifier(h)} WHERE ${d.identifier("__id__")} = ${f}`).toArray(),[A]=b;if(A===void 0)return null;let I=A.__partition__;const D=Q(i.baseWhere,i.where);ut(D,a,e,"rank");const m=To(p,D);if(m){const V=Ao(p.partitionBy??[],m);if(V!==I)return null;I=V}const q=E.map(V=>A[V]),{before:Y,total:X}=wn(y,h,E,p.sortBy,I,q,f);return{position:Y+1,total:X}},async rankBefore(e,t,i){if(ae(e))throw new R("INTERNAL",`rankBefore is not supported on the global (.global()) table '${e}' — cross-shard rank cursors apply only to sharded tables`);const l=a.tables[e];if(!l)throw new R("INTERNAL",`unknown table: ${e}`);const w=l.rankIndexes?.find(E=>E.name===t);if(!w)throw new R("INTERNAL",`unknown rankIndex "${t}" on table "${e}"`);if(i.restrictsCounts)throw new dt(e);k(e,G),rt(e,w);const p=Qt(e,w.name),f=w.sortBy.map((E,_)=>Vt(_)),h=w.sortBy.map((E,_)=>Ce(i.sortValues[_]??null));return wn(y,p,f,w.sortBy,i.partitionKey,h,i.rowId)},async rankPage(e,t,i={}){ut(Q(i.baseWhere,i.where),a,e,"rankPage");const l=H(e,"rankPage");if(l)return k(e,G),l.rankPage(e,t,i);te(e,t,"rank");const{continueCursor:w,hasMore:p,rows:f}=Gt(qt,e,t,i);return{continueCursor:w,isDone:!p,page:f.map(h=>h.doc)}},async rankPageRows(e,t,i={}){ut(Q(i.baseWhere,i.where),a,e,"rankPage"),te(e,t,"rank");const{directions:l,hasMore:w,rows:p}=Gt(qt,e,t,i);return{directions:l,hasMore:w,rows:p}},async restore(e,t){T(e,"ctx.db.restore(table, id)");const i=re(t,e);if(!i){const p=Te(e);if(p?.restore){await p.restore(e,t);return}throw new R("NOT_FOUND",`document not found: ${t}`)}const l=a.tables[i.tableName]?.softDeleteMode?.field;if(!l)throw new R("INTERNAL",`ctx.db.restore: table "${i.tableName}" is not a .softDelete() table`);const w=i.row[l]!==null&&i.row[l]!==void 0;await O.patch(e,t,{[l]:null}),w&&_e(i.tableName,t,void 0,i.row)},async replace(e,t,i,l){T(e,"ctx.db.replace(table, id, document)");const w=re(t,e);if(!w){const q=Te(e);if(q){J(i),await q.replace(e,t,i,l);return}throw new R("NOT_FOUND",`document not found: ${t}`)}const{docJson:p,row:f,tableName:h}=w,E=a.tables[h];if(!E)throw new R("INTERNAL",`unknown table: ${h}`);fn("replace",i);const _=l?.allowExplicitId&&typeof i._creationTime=="number"?i._creationTime:void 0,b=typeof f._creationTime=="number"?f._creationTime:void 0,A=_??b??$e(),I={...i,...ee(h),_creationTime:A,_id:t};ht(E,i,I,ce);const D=l?.allowExplicitId===!0,m=Ge(E,I,{previous:()=>f,supplied:i,trusted:D});ne(h,"before","update")&&await oe("before","update",{doc:{...m},id:t,op:"update",previous:f,table:h}),D||W(h,m,f),Se(h),ve(h),Ne(y,h,pr(h),[A,le(m),t,p]),Fe(h,t,m,f),Le(h,t,m),ke(h,f,m),_e(h,t,f,m),Ee?.invalidate(h,t,N(h,f,m)),Re(h,t,"update",m),M({indexKeys:N(h,f,m),key:t,op:"update",row:m,table:h}),ne(h,"after","update")&&await oe("after","update",{doc:m,id:t,op:"update",previous:f,table:h}),await ye({doc:m,id:t,op:"update",table:h})},async wipeShard(e){const t=new Set(e?.exclude),i=e?.tables,l=Object.entries(a.tables).filter(([h,E])=>t.has(h)||i!==void 0&&!i.includes(h)?!1:E.shardMode?.kind!=="global").map(([h])=>h);if(i!==void 0){for(const h of i)if(!a.tables[h])throw new R("INTERNAL",`wipeShard: unknown table: ${h}`)}const w={};let p=0;const{deleteAll:f}=O;if(f===void 0)throw new R("INTERNAL","wipeShard: this writer has no deleteAll");for(const h of l){const E=await f(h,{...e?.chunkSize===void 0?{}:{chunkSize:e.chunkSize},hard:!0});w[h]=E.deleted,p+=E.deleted}return{deleted:p,tables:w}}},qn={db:O,scheduler:_t};return n.enforceRls===!0?jo(O,a,(e,t)=>re(e,t)?.tableName,v):O};export{Ni as CDC_LOG_TABLE,ws as IDEMPOTENCY_TABLE,Fr as NotUniqueError,ls as advanceClientWatermark,Qi as applyCdcChanges,fn as assertNoExplicitUndefined,$t as assertStorableRowId,Sr as assertValidClientId,Gi as backfillAggregateIndexes,ji as backfillRankIndexes,Hi as backfillSearchIndexes,Vi as bumpCdcEpoch,Ji as cdcCanVouchFor,zi as cdcForkedError,Yi as cdcSeqLeavingRows,Xi as cdcTouchesTables,Zi as cdcTrimmedError,es as compactCdcDocs,ei as createShardCtxDb,ts as cursorBelowRetainedFloor,Nr as meterReadBytes,us as migrateClientWatermark,ns as minCdcReplayableSeq,os as minCdcSeq,ln as normalizeIdStructurally,rs as readCdcChangeKeys,is as readCdcChanges,ss as readCdcCursor,cs as readCdcEpoch,fs as readClientWatermark,ps as readIdempotent,$s as runShardMigrations,Rs as selectShapeMembers,Ss as selectShapeRows,Ke as stripReservedPatchFields,as as trimCdcChanges,gs as trimIdempotent,ys as writeIdempotent};
|