@lunora/shard-engine 1.0.0-alpha.114 → 1.0.0-alpha.116
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 +3 -1
- package/dist/index.d.ts +3 -1
- package/dist/index.mjs +1 -1
- package/dist/packem_shared/ADMIN_FUNCTIONS-BGXP6oxh.mjs +1 -0
- package/dist/packem_shared/{AGG_COUNT-DNnEXtyM.mjs → AGG_COUNT-BIGZgU8U.mjs} +1 -1
- package/dist/packem_shared/{CDC_LOG_TABLE-QaBxSIZM.mjs → CDC_LOG_TABLE-GKlDpuM2.mjs} +1 -1
- package/dist/packem_shared/{CURSOR_PREFIX-BX8jkMJa.mjs → CURSOR_PREFIX-C1jsjAPd.mjs} +1 -1
- package/dist/packem_shared/{DATA_MIGRATION_STATE_TABLE-BMbxLEaN.mjs → DATA_MIGRATION_STATE_TABLE-DfqA-2Dj.mjs} +1 -1
- package/dist/packem_shared/{DEFAULT_MAX_RELATION_KEYS-CYPZfQH9.mjs → DEFAULT_MAX_RELATION_KEYS-CQLms3UG.mjs} +1 -1
- package/dist/packem_shared/{DEFAULT_MAX_RELAYS-B-yt9l6-.mjs → DEFAULT_MAX_RELAYS-BqSpObEl.mjs} +1 -1
- package/dist/packem_shared/{DEFAULT_PROMOTION_THRESHOLDS-91RH_llq.mjs → DEFAULT_PROMOTION_THRESHOLDS-DEURXMvk.mjs} +1 -1
- package/dist/packem_shared/{DurableStreamRunner-Dk9Pn-B8.mjs → DurableStreamRunner-y2CRbfuZ.mjs} +1 -1
- package/dist/packem_shared/NotUniqueError-CP6A9cx3.mjs +1 -0
- package/dist/packem_shared/{RANK_TIEBREAK-B0_x8iev.mjs → RANK_TIEBREAK-DrISKVKe.mjs} +1 -1
- package/dist/packem_shared/{RELATED_DEFAULT_LIMIT-CBYQQIrZ.mjs → RELATED_DEFAULT_LIMIT-e7viSuiO.mjs} +1 -1
- package/dist/packem_shared/{RLS_UNWRAP_SYMBOL-rSxYzw-G.mjs → RLS_UNWRAP_SYMBOL-DY6k6f6W.mjs} +1 -1
- package/dist/packem_shared/{ReactiveCache-D8ccaO6f.mjs → ReactiveCache-Bdzsahf3.mjs} +1 -1
- package/dist/packem_shared/{ShapeDiffCache-gdaILV5E.mjs → ShapeDiffCache-Br3kxusw.mjs} +1 -1
- package/dist/packem_shared/{VECTOR_BACKFILL_MAX_PAGES-B2ZWxshy.mjs → VECTOR_BACKFILL_MAX_PAGES-CO1Ra57t.mjs} +1 -1
- package/dist/packem_shared/{aggregateTableName-C7o-gpms.mjs → aggregateTableName-DbAttCNH.mjs} +1 -1
- package/dist/packem_shared/{applyOnDelete-DJsOG8tz.mjs → applyOnDelete-8n5PzcI0.mjs} +1 -1
- package/dist/packem_shared/{awaitWsDrain-apizgmKY.mjs → awaitWsDrain-D4E7Oiwo.mjs} +1 -1
- package/dist/packem_shared/backfillAggregateIndexes-B1yVAkvK.mjs +1 -0
- package/dist/packem_shared/{buildPokeFrames-BBE6J91z.mjs → buildPokeFrames-CDOP-XYp.mjs} +1 -1
- package/dist/packem_shared/{buildReprojectionMigration-IMrfRdvU.mjs → buildReprojectionMigration-BnUbAUwT.mjs} +1 -1
- package/dist/packem_shared/{buildShapeDiff-D-J_GmC1.mjs → buildShapeDiff-AxUzi_GL.mjs} +1 -1
- package/dist/packem_shared/clearCompanionSignatures-C2CSfkeQ.mjs +1 -0
- package/dist/packem_shared/{computeRankPage-3AiKfT8q.mjs → computeRankPage-BI2lNKPu.mjs} +1 -1
- package/dist/packem_shared/createCompanionSync-hGCzG0O1.mjs +1 -0
- package/dist/packem_shared/{createReplicaLink-CV7SD_b-.mjs → createReplicaLink-CJn5lH0o.mjs} +1 -1
- package/dist/packem_shared/{ctx-db-relay-shapes-DuqhDLw8.mjs → ctx-db-relay-shapes-kGRKSxRs.mjs} +1 -1
- package/dist/packem_shared/{defineEngineContractSuite-CJi11pDP.mjs → defineEngineContractSuite-BsXerAD-.mjs} +1 -1
- package/dist/packem_shared/{do-sql-BEFrJUds.mjs → do-sql-CyWszGdM.mjs} +1 -1
- package/dist/packem_shared/{isSoftDeleted-sGRSPPQq.mjs → isSoftDeleted-BHlFkAsr.mjs} +1 -1
- package/dist/packem_shared/{materializeExternalRows-DhINQHwd.mjs → materializeExternalRows-Csa8ELkU.mjs} +1 -1
- package/dist/packem_shared/runShardMigrations-3BBkjGHs.mjs +5 -0
- package/dist/packem_shared/{selectExpiredIds-DQg6v5Uf.mjs → selectExpiredIds-5bAT7X28.mjs} +1 -1
- package/dist/packem_shared/{selectShapeMembers-BXhvEt4X.mjs → selectShapeMembers-CNpeUQ-H.mjs} +1 -1
- package/dist/packem_shared/{stableWireKey-D2US4k_J.mjs → stableWireKey-Bdh5JSdg.mjs} +1 -1
- package/dist/packem_shared/wire-codec-BYCSiazv.mjs +1 -0
- package/package.json +2 -2
- package/dist/packem_shared/ADMIN_FUNCTIONS-CZiYkV6K.mjs +0 -1
- package/dist/packem_shared/NotUniqueError-D4EV8EzO.mjs +0 -1
- package/dist/packem_shared/backfillAggregateIndexes-B_3xdOgV.mjs +0 -1
- package/dist/packem_shared/createCompanionSync-Rjn0lsT6.mjs +0 -1
- package/dist/packem_shared/runShardMigrations-MXioI81k.mjs +0 -5
- package/dist/packem_shared/wire-codec-C-FpWm52.mjs +0 -1
|
@@ -1 +1 @@
|
|
|
1
|
-
import{defineEngineContractSuite as t}from"../packem_shared/defineEngineContractSuite-
|
|
1
|
+
import{defineEngineContractSuite as t}from"../packem_shared/defineEngineContractSuite-BsXerAD-.mjs";export{t as defineEngineContractSuite};
|
package/dist/index.d.mts
CHANGED
|
@@ -958,6 +958,7 @@ declare const COMMIT_SEQ_FIELD = "_commitSeq";
|
|
|
958
958
|
declare const migrateCommitSeq: (sql: SqlExec) => void;
|
|
959
959
|
declare const readCommitSeq: (sql: SqlExec) => number;
|
|
960
960
|
declare const allocateCommitSeq: (sql: SqlExec) => number;
|
|
961
|
+
declare const clearCompanionSignatures: (sql: SqlExec) => void;
|
|
961
962
|
interface CompanionSyncDeps {
|
|
962
963
|
broadcast: (delta: MutationDelta) => void;
|
|
963
964
|
indexKeysFor: (table: string, document?: Record<string, unknown>) => ReadonlyArray<{
|
|
@@ -1404,6 +1405,7 @@ declare const ADMIN_FUNCTIONS: {
|
|
|
1404
1405
|
readonly rankBefore: "__lunora_admin__:rankBefore";
|
|
1405
1406
|
readonly rankPage: "__lunora_admin__:rankPage";
|
|
1406
1407
|
readonly readTablePage: "__lunora_admin__:readTablePage";
|
|
1408
|
+
readonly rebuildCompanions: "__lunora_admin__:rebuildCompanions";
|
|
1407
1409
|
readonly recordAuthEvent: "__lunora_admin__:recordAuthEvent";
|
|
1408
1410
|
readonly recordContainerEvent: "__lunora_admin__:recordContainerEvent";
|
|
1409
1411
|
readonly recordMail: "__lunora_admin__:recordMail";
|
|
@@ -2517,4 +2519,4 @@ interface WhereSqlStrategy<T = SQL> {
|
|
|
2517
2519
|
}
|
|
2518
2520
|
declare const serverInList: (engine: "mysql" | "postgres") => (reference: SQL, items: ReadonlyArray<unknown>, negated: boolean, budget?: number) => SQL;
|
|
2519
2521
|
declare const compileWhereSql: <T = SQL>(where: WhereInput | undefined, strategy: WhereSqlStrategy<T>, fragments?: WhereFragments<T>, reservedParams?: number) => T | undefined;
|
|
2520
|
-
export { ADMIN_FUNCTIONS, ADMIN_FUNCTION_PREFIX, AGGREGATE_SQL_FUNCTION, AGG_COUNT, AGG_KEY, AGG_VALUE, AUDIT_LOG_TABLE, type AdvisorProcedure, type AdvisorProceduresResult, type AdvisoriesResult, type AdvisoryFinding, type AggregateIndexDefinitionLike, type AggregateOp, type AggregateOptions, type AggregateResult, type AggregateTally, type AppendAuditEntry, type ApplyOnDeleteOptions, type AuditEntry, type AuditLogResult, BIGINT_KEY_DIGITS, type BroadcastDelta, CDC_LOG_TABLE, CDC_LOG_TABLE_SEQ_INDEX, CDC_META_TABLE, CLIENT_WATERMARK_TABLE, COMMIT_SEQ_FIELD, COMMIT_SEQ_TABLE, CURSOR_PREFIX, type CacheEntry, type CapturedMailRow, type CdcArchiveScope, type CdcChange, type CdcChangeKey, type ChangedKeys, type Clock, type ColumnMeta, type ColumnMetaLike, type CompanionSync, type CompanionSyncDeps, ConflictError, type ConflictKind, type CountArgs, CountRlsUnsupportedError, type CreateWorkflowInstanceResult, type CrossShardReadArgs, type CtxDbOptions, DATA_MIGRATION_STATE_TABLE, DEFAULT_FANOUT_TOPIC_LIMIT, DEFAULT_MAX_RELATION_KEYS, DEFAULT_MAX_RELAYS, DEFAULT_PROMOTION_THRESHOLDS, DEFAULT_TRANSACTION_LIMITS, DOC_COLUMN, type DataMigrationDocument, type DataMigrationLike, type DataMigrationTransform, type DatabaseWriterLike, type DependencyTracker, type DeployInfo, type DurableAttachDecision, type DurableStreamAttach, type DurableStreamRun, DurableStreamRunner, type DurableStreamSink, type ExportRow, type ExportShardAdminArgs, type ExportShardArgs, type ExternalSourceDiffResult, type ExternalSourceLike, FLAGS_FUNCTION_PREFIX, type FacetColumnOptions, type FacetColumnResult, type FacetValue, type FanOutBudget, type FanoutMetricsResult, type FanoutPathCounters, type FanoutTopicStat, type FieldOperators, type FilterClause, type FilterOperator, type FlagEvaluation, type FlagsResult, type FtsWriteOptions, type FunctionCallStat, type FunctionScanAttribution, type FunctionStatsResult, GEO_DEFAULT_PRECISION, GLOBAL_SHAPE_SNAPSHOT_TABLE, type GeoBoundingBox, type GeoFilterBuilderLike, type GeoIndexDefinitionLike, type GeoPoint, type GeoScoredDocument, type GlobalPollCounters, GlobalPollTick, type GroupByEntry, type GroupByOptions, type GuardableSchema$1 as GuardableSchema, IDEMPOTENCY_TABLE, type IdGenerator, type IdempotentRecord, type ImportError, type ImportShardAdminArgs, type ImportShardArgs, type ImportShardResult, type IncrementalMaterializeResult, type IndexDefinitionLike, type IndexKeyEntry, type IndexRangeBuilderLike, type KeyRange, type LifecycleDispatchInfo, type LifecycleEvent, MAIL_RETENTION, MAIL_TABLE, MAX_DURABLE_STREAM_BYTES, MAX_DURABLE_STREAM_CHUNKS, MAX_PAGE_SIZE, MAX_SQL_ROWS, type MaskColumnMetadata, type MaskPoliciesResult, type MaterializeResult, type MigrationDirection, type MigrationRunResult, type MigrationStatus, type MigrationStatusRow, type MutationDelta, type NestedWith, NotFoundError, NotUniqueError, type OnDeleteActionLike, type OrderByClause, type OrderByInput, type OrderKey, type OrderKeyConstraints, OwnerRelay, type OwnerRelayFrame, type PaginationOptions, type PitrBookmarkResult, type PitrRestoreArgs, type PitrRestoreResult, type PitrStorage, type PokeFrameMeta, type PromotionState, type PromotionThresholds, QUEUE_TABLE, type QueryArgs, type QueryPage, type QueueMessageOutcome, type QueueMessageRow, type QueueMetadata, type QueuesResult, RANK_TIEBREAK, REACTOR_STATE_TABLE, RELATED_DEFAULT_LIMIT, RELATED_DEPTH_DECAY, RELATED_MAX_DEPTH, RELATED_MAX_LIMIT, RELATION_EXISTS_KEY, RELATION_FUNCTION_PREFIX, REPROJECTION_MIGRATION_PREFIX, RLS_UNWRAP_SYMBOL, type RankBeforeOptions, type RankBeforeResult, type RankDirection, type RankIndexDefinitionLike, type RankOptions, type RankPage, type RankPageComputation, type RankPageDeps, type RankPageOptions, type RankPageRow, type RankPageRowKey, type RankResult, type RankSortKeyLike, ReactiveCache, type ReactiveCacheOptions, type ReactorDispatchResult, type ReactorMetadata, type ReactorState, type ReactorStats, type ReactorsResult, type ReadFootprint, type ReadHook, type ReadTablePageOptions, type RecordMailInput, type RecordQueueMessageInput, type RelatedDirection, type RelatedNode, type RelatedOptions, type RelatedPage, type RelatedStart, type RelatedStartReference, type RelationDefinitionLike, type RelationEdge, type RelationExistsMarker, type RelationGraphReader, type RelayAttach, type RelayDetach, type RelayFrame, type RelayHost, RelayMember, type RelayPokeDelivery, type RelayShapePoke, type RelayShapeSeed, type RelayShapeSubscribe, type RelayShapeUnsubscribe, type RenderedSql, type ReplicaFollowerHost, type ReplicaOwnerHost, type ReplicaReadiness, type ResolveRelationPredicatesOptions, type ResolveWithOptions, type ResolveWithResult, type ResolvedShape, type RestrictableQueryOptions, type RlsPoliciesResult, type RlsPolicyMetadata, RlsRequiredError, type RlsRoleMetadata, type RpcRequest, type RunDataMigrationOptions, type RunTriggersOptions, SCAN_DEP, SCHEDULE_OUTBOX_TABLE, SCHEMA_HISTORY_MAX_VERSIONS, SEARCH_STATE_TABLE, SHAPE_POKE_CURSOR_TABLE, type SchedulableWorkflowReferenceLike, type ScheduleOutbox, type ScheduleOutboxEnvelope, type ScheduleOutboxRow, type ScheduledFunctionDoc, type SchedulerLike, type SchemaLike, type ScoredDocument, type SearchBackfillProgress, type SearchFilterBuilderLike, type SearchIndexDefinitionLike, type SearchScoredDocument, type SelectMatchingIdsOptions, type ServerDefaultContextLike, type SettingEntry, type SettingKind, type SettingsResult, ShapeDiffCache, type ShapePokeCursorRow, type ShapePokePart, type ShapeProbeCounters, type ShapeRow, type ShapeRowOp, type ShapeSubscriptionQuery, type ShardRankPageResult, ShardRunner, type ShardRunnerOptions, type ShardSiblingHost, type ShardSocketLike, type SocketAttachment, type SortDirection, type SourceClientLike, type SourceCursorLike, type SourceRefresh, type SqlConsoleResult, type SqlCursor, type SqlEngine, type SqlExec, type SqlLintResult, type StorageMetadata, type StorageReference, type StorageReferenceResult, type StorageRuleMetadata, type StorageRulesResult, type StudioFeaturesResult, type SubscriptionConnection, type SubscriptionEnvelope, type SubscriptionIdentity, type SubscriptionInfo, type SubscriptionQuery, type SubscriptionReadFootprint, type SubscriptionsResult, type SystemDatabaseReader, type SystemDoc, type SystemQuery, type SystemReaderOptions, type SystemReaderSchedulerLike, type SystemReaderStorageLike, type SystemTableName, type TableColumnsResult, type TableDefinitionLike, type TableIndexInfo, type TableIndexesResult, type TableInfo, type TablePage, type TableReaderLike, type TablesColumnsResult, type TablesIndexesResult, type TransactionHeadroom, TransactionHeadroomTracker, type TransactionLimits, type TransactionSqlLike, type TriggerContextLike, type TriggerDefinitionLike, type TriggerEventLike, type TriggerOpLike, type TriggerTimingLike, type TtlSweepSpec, UNVOUCHABLE_DEP, VECTOR_BACKFILL_MAX_PAGES, type ValidatorLike, type VectorBackfillProgress, WORKERD_SQLITE_LIMITS, type WhereFilter, type WhereInput, type WhereSqlStrategy, type WithInput, type WorkflowInstanceState, type WorkflowInstanceStatusResult, type WorkflowMetadata, type WorkflowsResult, type WriteEvent, type WriteHook, advanceClientWatermark, aggUpsertSql, aggregateSqlFunction, aggregateTableName, allocateCommitSeq, appendAuditEntry, appendCdcChange, appendStreamChunk, applyCdcChanges, applyOnDelete, applySelect, archiveCdcSegment, armRestore, assertFlatPredicate, assertNoExplicitUndefined, assertReadonly, assertShapeShardable, 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, clearMemoryTables, clearQueueMessages, coerceAggregateNumber, compactCdcDocs, compileWhereSql, computeRankPage, containsRelationPredicate, countLegacyRows, coveringGeohashes, createCompanionSync, createDependencyTracker, createFanoutCounters, createGlobalPollCounters, createIndexSql, createReadFootprint, createRelayLink, createReplicaLink, createShapeDiffCache, createShapeProbeCounters, createShardCtxDb, createSystemReader, cursorBelowRetainedFloor, decideDurableAttach, decodeBigintSqlKey, decodeCursor, decodeFloat64SqlKey, deferScheduleOutbox, deleteGlobalShapeSnapshot, deleteGlobalShapeSnapshotsForConnection, deleteShapePokeCursor, deleteShapePokeCursorsForConnection, deleteStreamRun, depKey, deriveRelationEdges, diffExternalSource, diffGlobalMembership, distinctValues, encodeAggregateKey, encodeCursor, encodeGeohash, encodePartitionKey, encodeRowsPatch, ensureAuditTable, ensureMailTable, envOptionalPositiveInt, envPositiveInt, equalityPinnedFields, exportShardRows, facetColumn, fanOutScalarCounts, findRelated, findStorageReferences, finishStreamRun, float64SqlKey, foldAggregateTally, forgetScheduleOutbox, ftsCompanionDdl, ftsPurgeDocument, ftsRowidMapName, ftsUnmappedPage, ftsWriteDocument, gateReplicaDispatch, geoTableName, globalShapeReadKey, groupUnmappedRows, guardWriter, handleReplicaControl, hasTrigger, haversineMeters, importShardRows, indexKeysForRow, isDevEnvironment, isFtsAvailable, isInternalTableName, isLossyBody, isMemoryTable, isPushableWhere, isRelationPredicate, isSoftDeleted, isSourceDue, isVacuousFilterClause, jsonPath, jsonPathSql, keysTouchRanges, liftSourceId, lintReadonlySql, listReactorStates, listTables, markUnvouchableReads, matchesRankStaticWhere, matchesStaticWhere, materializeExternalRows, materializeExternalRowsIncremental, memoryTableNames, mergeChangedKeys, mergeWhere, migrateCdcLog, migrateCdcMeta, migrateClientWatermark, migrateCommitSeq, migrateDurableStreams, migrateGlobalShapeSnapshot, migrateIdempotency, migrateReactorState, migrateScheduleOutbox, migrateSearchState, migrateShapePokeCursor, minCdcReplayableSeq, minCdcSeq, minShapePokeCursor, nextPromotionState, normalizeCountArgument, normalizeIdStructurally, normalizeOrderKeys, normalizeSourceDocument, normalizeSourceValue, param, parkScheduleOutbox, parseExportShardArgs, parseImportShardArgs, planAggregateLookup, pointInBoundingBox, probeScheduleOutbox, projectColumns, pullExternalSourceIncrementalTick, pullExternalSourceTick, qualifiedJsonPath, qualifiedJsonPathSql, quoteIdentifier, rankKeyFromDocument as rankKeyFromDoc, rankPivotConditionSql, rankTableName, reactiveCacheKey, reactorNeedsRun, readAggregateValue, readArchivedCdcChanges, readAuditLog, readBookmark, readCapturedMail, readCdcArchivedThrough, readCdcChangeKeys, readCdcChanges, readCdcCursor, readCdcEpoch, readClientWatermark, readCommitSeq, readDeployInfo, readDueScheduleOutbox, readExternalSourceBaseline, readGlobalShapeSnapshot, readIdempotent, readMigrationStatus, readQueueMessageById, readQueueMessages, readReactorState, readSchemaHistory, readSchemaVersion, readSearchBackfillState, readShapePokeCursor, readStreamChunks, readStreamRun, readTablePage, recordCapturedMail, recordChangedKeys, recordFanoutPass, recordGlobalPollPass, recordQueueMessages, recordScheduleOutbox, recordSchemaVersion, recordShapeProbePass, relationHooks, relayCountFor, renderSql, reprojectableFields, reprojectionMigrationId, reprojectionTables, resolveRankPartition, resolveRankSeekTuple, resolveRelationPredicates, resolveWith, rowToDocument, runDataMigration, runDrizzle, runExternalSourceTick, runReadonlySql, runRowValidators, runShardMigrations, runSocketPool, runSql, runTriggers, selectExpiredIds, selectExportTables, selectIndexForAggregate, selectIndexForCount, selectIndexForGroupBy, selectMatchingIds, selectShapeMembers, selectShapeRows, serializeSqlValue, serverInList, shapeRoutingKey, softDeleteScope, sortColumnName, sqliteInList, stableStringify, stableWireKey, stripReservedPatchFields, stubByName, subscriptionFrames, subscriptionListDeltas, summarizeFanoutTopics, summarizeSubscriptions, tableColumns, tableFromDepKey, throwingScheduler, tiebreakDirectionFor, trimCdcChanges, trimIdempotent, trimScheduleOutbox, trimStreamRuns, tryRowToDocument, trySendFrame, unionAll, uniqueIndexFields, validateImportRow, whereFilter, whereOfFilter, writeCdcArchivedThrough, writeGlobalShapeSnapshot, writeIdempotent, writeReactorState, writeSearchBackfillState, writeShapePokeCursor, writeShapePokeCursors, writeTouchesMemo };
|
|
2522
|
+
export { ADMIN_FUNCTIONS, ADMIN_FUNCTION_PREFIX, AGGREGATE_SQL_FUNCTION, AGG_COUNT, AGG_KEY, AGG_VALUE, AUDIT_LOG_TABLE, type AdvisorProcedure, type AdvisorProceduresResult, type AdvisoriesResult, type AdvisoryFinding, type AggregateIndexDefinitionLike, type AggregateOp, type AggregateOptions, type AggregateResult, type AggregateTally, type AppendAuditEntry, type ApplyOnDeleteOptions, type AuditEntry, type AuditLogResult, BIGINT_KEY_DIGITS, type BroadcastDelta, CDC_LOG_TABLE, CDC_LOG_TABLE_SEQ_INDEX, CDC_META_TABLE, CLIENT_WATERMARK_TABLE, COMMIT_SEQ_FIELD, COMMIT_SEQ_TABLE, CURSOR_PREFIX, type CacheEntry, type CapturedMailRow, type CdcArchiveScope, type CdcChange, type CdcChangeKey, type ChangedKeys, type Clock, type ColumnMeta, type ColumnMetaLike, type CompanionSync, type CompanionSyncDeps, ConflictError, type ConflictKind, type CountArgs, CountRlsUnsupportedError, type CreateWorkflowInstanceResult, type CrossShardReadArgs, type CtxDbOptions, DATA_MIGRATION_STATE_TABLE, DEFAULT_FANOUT_TOPIC_LIMIT, DEFAULT_MAX_RELATION_KEYS, DEFAULT_MAX_RELAYS, DEFAULT_PROMOTION_THRESHOLDS, DEFAULT_TRANSACTION_LIMITS, DOC_COLUMN, type DataMigrationDocument, type DataMigrationLike, type DataMigrationTransform, type DatabaseWriterLike, type DependencyTracker, type DeployInfo, type DurableAttachDecision, type DurableStreamAttach, type DurableStreamRun, DurableStreamRunner, type DurableStreamSink, type ExportRow, type ExportShardAdminArgs, type ExportShardArgs, type ExternalSourceDiffResult, type ExternalSourceLike, FLAGS_FUNCTION_PREFIX, type FacetColumnOptions, type FacetColumnResult, type FacetValue, type FanOutBudget, type FanoutMetricsResult, type FanoutPathCounters, type FanoutTopicStat, type FieldOperators, type FilterClause, type FilterOperator, type FlagEvaluation, type FlagsResult, type FtsWriteOptions, type FunctionCallStat, type FunctionScanAttribution, type FunctionStatsResult, GEO_DEFAULT_PRECISION, GLOBAL_SHAPE_SNAPSHOT_TABLE, type GeoBoundingBox, type GeoFilterBuilderLike, type GeoIndexDefinitionLike, type GeoPoint, type GeoScoredDocument, type GlobalPollCounters, GlobalPollTick, type GroupByEntry, type GroupByOptions, type GuardableSchema$1 as GuardableSchema, IDEMPOTENCY_TABLE, type IdGenerator, type IdempotentRecord, type ImportError, type ImportShardAdminArgs, type ImportShardArgs, type ImportShardResult, type IncrementalMaterializeResult, type IndexDefinitionLike, type IndexKeyEntry, type IndexRangeBuilderLike, type KeyRange, type LifecycleDispatchInfo, type LifecycleEvent, MAIL_RETENTION, MAIL_TABLE, MAX_DURABLE_STREAM_BYTES, MAX_DURABLE_STREAM_CHUNKS, MAX_PAGE_SIZE, MAX_SQL_ROWS, type MaskColumnMetadata, type MaskPoliciesResult, type MaterializeResult, type MigrationDirection, type MigrationRunResult, type MigrationStatus, type MigrationStatusRow, type MutationDelta, type NestedWith, NotFoundError, NotUniqueError, type OnDeleteActionLike, type OrderByClause, type OrderByInput, type OrderKey, type OrderKeyConstraints, OwnerRelay, type OwnerRelayFrame, type PaginationOptions, type PitrBookmarkResult, type PitrRestoreArgs, type PitrRestoreResult, type PitrStorage, type PokeFrameMeta, type PromotionState, type PromotionThresholds, QUEUE_TABLE, type QueryArgs, type QueryPage, type QueueMessageOutcome, type QueueMessageRow, type QueueMetadata, type QueuesResult, RANK_TIEBREAK, REACTOR_STATE_TABLE, RELATED_DEFAULT_LIMIT, RELATED_DEPTH_DECAY, RELATED_MAX_DEPTH, RELATED_MAX_LIMIT, RELATION_EXISTS_KEY, RELATION_FUNCTION_PREFIX, REPROJECTION_MIGRATION_PREFIX, RLS_UNWRAP_SYMBOL, type RankBeforeOptions, type RankBeforeResult, type RankDirection, type RankIndexDefinitionLike, type RankOptions, type RankPage, type RankPageComputation, type RankPageDeps, type RankPageOptions, type RankPageRow, type RankPageRowKey, type RankResult, type RankSortKeyLike, ReactiveCache, type ReactiveCacheOptions, type ReactorDispatchResult, type ReactorMetadata, type ReactorState, type ReactorStats, type ReactorsResult, type ReadFootprint, type ReadHook, type ReadTablePageOptions, type RecordMailInput, type RecordQueueMessageInput, type RelatedDirection, type RelatedNode, type RelatedOptions, type RelatedPage, type RelatedStart, type RelatedStartReference, type RelationDefinitionLike, type RelationEdge, type RelationExistsMarker, type RelationGraphReader, type RelayAttach, type RelayDetach, type RelayFrame, type RelayHost, RelayMember, type RelayPokeDelivery, type RelayShapePoke, type RelayShapeSeed, type RelayShapeSubscribe, type RelayShapeUnsubscribe, type RenderedSql, type ReplicaFollowerHost, type ReplicaOwnerHost, type ReplicaReadiness, type ResolveRelationPredicatesOptions, type ResolveWithOptions, type ResolveWithResult, type ResolvedShape, type RestrictableQueryOptions, type RlsPoliciesResult, type RlsPolicyMetadata, RlsRequiredError, type RlsRoleMetadata, type RpcRequest, type RunDataMigrationOptions, type RunTriggersOptions, SCAN_DEP, SCHEDULE_OUTBOX_TABLE, SCHEMA_HISTORY_MAX_VERSIONS, SEARCH_STATE_TABLE, SHAPE_POKE_CURSOR_TABLE, type SchedulableWorkflowReferenceLike, type ScheduleOutbox, type ScheduleOutboxEnvelope, type ScheduleOutboxRow, type ScheduledFunctionDoc, type SchedulerLike, type SchemaLike, type ScoredDocument, type SearchBackfillProgress, type SearchFilterBuilderLike, type SearchIndexDefinitionLike, type SearchScoredDocument, type SelectMatchingIdsOptions, type ServerDefaultContextLike, type SettingEntry, type SettingKind, type SettingsResult, ShapeDiffCache, type ShapePokeCursorRow, type ShapePokePart, type ShapeProbeCounters, type ShapeRow, type ShapeRowOp, type ShapeSubscriptionQuery, type ShardRankPageResult, ShardRunner, type ShardRunnerOptions, type ShardSiblingHost, type ShardSocketLike, type SocketAttachment, type SortDirection, type SourceClientLike, type SourceCursorLike, type SourceRefresh, type SqlConsoleResult, type SqlCursor, type SqlEngine, type SqlExec, type SqlLintResult, type StorageMetadata, type StorageReference, type StorageReferenceResult, type StorageRuleMetadata, type StorageRulesResult, type StudioFeaturesResult, type SubscriptionConnection, type SubscriptionEnvelope, type SubscriptionIdentity, type SubscriptionInfo, type SubscriptionQuery, type SubscriptionReadFootprint, type SubscriptionsResult, type SystemDatabaseReader, type SystemDoc, type SystemQuery, type SystemReaderOptions, type SystemReaderSchedulerLike, type SystemReaderStorageLike, type SystemTableName, type TableColumnsResult, type TableDefinitionLike, type TableIndexInfo, type TableIndexesResult, type TableInfo, type TablePage, type TableReaderLike, type TablesColumnsResult, type TablesIndexesResult, type TransactionHeadroom, TransactionHeadroomTracker, type TransactionLimits, type TransactionSqlLike, type TriggerContextLike, type TriggerDefinitionLike, type TriggerEventLike, type TriggerOpLike, type TriggerTimingLike, type TtlSweepSpec, UNVOUCHABLE_DEP, VECTOR_BACKFILL_MAX_PAGES, type ValidatorLike, type VectorBackfillProgress, WORKERD_SQLITE_LIMITS, type WhereFilter, type WhereInput, type WhereSqlStrategy, type WithInput, type WorkflowInstanceState, type WorkflowInstanceStatusResult, type WorkflowMetadata, type WorkflowsResult, type WriteEvent, type WriteHook, advanceClientWatermark, aggUpsertSql, aggregateSqlFunction, aggregateTableName, allocateCommitSeq, appendAuditEntry, appendCdcChange, appendStreamChunk, applyCdcChanges, applyOnDelete, applySelect, archiveCdcSegment, armRestore, assertFlatPredicate, assertNoExplicitUndefined, assertReadonly, assertShapeShardable, 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, computeRankPage, containsRelationPredicate, countLegacyRows, coveringGeohashes, createCompanionSync, createDependencyTracker, createFanoutCounters, createGlobalPollCounters, createIndexSql, createReadFootprint, createRelayLink, createReplicaLink, createShapeDiffCache, createShapeProbeCounters, createShardCtxDb, createSystemReader, cursorBelowRetainedFloor, decideDurableAttach, decodeBigintSqlKey, decodeCursor, decodeFloat64SqlKey, deferScheduleOutbox, deleteGlobalShapeSnapshot, deleteGlobalShapeSnapshotsForConnection, deleteShapePokeCursor, deleteShapePokeCursorsForConnection, deleteStreamRun, depKey, deriveRelationEdges, diffExternalSource, diffGlobalMembership, distinctValues, encodeAggregateKey, encodeCursor, encodeGeohash, encodePartitionKey, encodeRowsPatch, ensureAuditTable, ensureMailTable, envOptionalPositiveInt, envPositiveInt, equalityPinnedFields, exportShardRows, facetColumn, fanOutScalarCounts, findRelated, findStorageReferences, finishStreamRun, float64SqlKey, foldAggregateTally, forgetScheduleOutbox, ftsCompanionDdl, ftsPurgeDocument, ftsRowidMapName, ftsUnmappedPage, ftsWriteDocument, gateReplicaDispatch, geoTableName, globalShapeReadKey, groupUnmappedRows, guardWriter, handleReplicaControl, hasTrigger, haversineMeters, importShardRows, indexKeysForRow, isDevEnvironment, isFtsAvailable, isInternalTableName, isLossyBody, isMemoryTable, isPushableWhere, isRelationPredicate, isSoftDeleted, isSourceDue, isVacuousFilterClause, jsonPath, jsonPathSql, keysTouchRanges, liftSourceId, lintReadonlySql, listReactorStates, listTables, markUnvouchableReads, matchesRankStaticWhere, matchesStaticWhere, materializeExternalRows, materializeExternalRowsIncremental, memoryTableNames, mergeChangedKeys, mergeWhere, migrateCdcLog, migrateCdcMeta, migrateClientWatermark, migrateCommitSeq, migrateDurableStreams, migrateGlobalShapeSnapshot, migrateIdempotency, migrateReactorState, migrateScheduleOutbox, migrateSearchState, migrateShapePokeCursor, minCdcReplayableSeq, minCdcSeq, minShapePokeCursor, nextPromotionState, normalizeCountArgument, normalizeIdStructurally, normalizeOrderKeys, normalizeSourceDocument, normalizeSourceValue, param, parkScheduleOutbox, parseExportShardArgs, parseImportShardArgs, planAggregateLookup, pointInBoundingBox, probeScheduleOutbox, projectColumns, pullExternalSourceIncrementalTick, pullExternalSourceTick, qualifiedJsonPath, qualifiedJsonPathSql, quoteIdentifier, rankKeyFromDocument as rankKeyFromDoc, rankPivotConditionSql, rankTableName, reactiveCacheKey, reactorNeedsRun, readAggregateValue, readArchivedCdcChanges, readAuditLog, readBookmark, readCapturedMail, readCdcArchivedThrough, readCdcChangeKeys, readCdcChanges, readCdcCursor, readCdcEpoch, readClientWatermark, readCommitSeq, readDeployInfo, readDueScheduleOutbox, readExternalSourceBaseline, readGlobalShapeSnapshot, readIdempotent, readMigrationStatus, readQueueMessageById, readQueueMessages, readReactorState, readSchemaHistory, readSchemaVersion, readSearchBackfillState, readShapePokeCursor, readStreamChunks, readStreamRun, readTablePage, recordCapturedMail, recordChangedKeys, recordFanoutPass, recordGlobalPollPass, recordQueueMessages, recordScheduleOutbox, recordSchemaVersion, recordShapeProbePass, relationHooks, relayCountFor, renderSql, reprojectableFields, reprojectionMigrationId, reprojectionTables, resolveRankPartition, resolveRankSeekTuple, resolveRelationPredicates, resolveWith, rowToDocument, runDataMigration, runDrizzle, runExternalSourceTick, runReadonlySql, runRowValidators, runShardMigrations, runSocketPool, runSql, runTriggers, selectExpiredIds, selectExportTables, selectIndexForAggregate, selectIndexForCount, selectIndexForGroupBy, selectMatchingIds, selectShapeMembers, selectShapeRows, serializeSqlValue, serverInList, shapeRoutingKey, softDeleteScope, sortColumnName, sqliteInList, stableStringify, stableWireKey, stripReservedPatchFields, stubByName, subscriptionFrames, subscriptionListDeltas, summarizeFanoutTopics, summarizeSubscriptions, tableColumns, tableFromDepKey, throwingScheduler, tiebreakDirectionFor, trimCdcChanges, trimIdempotent, trimScheduleOutbox, trimStreamRuns, tryRowToDocument, trySendFrame, unionAll, uniqueIndexFields, validateImportRow, whereFilter, whereOfFilter, writeCdcArchivedThrough, writeGlobalShapeSnapshot, writeIdempotent, writeReactorState, writeSearchBackfillState, writeShapePokeCursor, writeShapePokeCursors, writeTouchesMemo };
|
package/dist/index.d.ts
CHANGED
|
@@ -958,6 +958,7 @@ declare const COMMIT_SEQ_FIELD = "_commitSeq";
|
|
|
958
958
|
declare const migrateCommitSeq: (sql: SqlExec) => void;
|
|
959
959
|
declare const readCommitSeq: (sql: SqlExec) => number;
|
|
960
960
|
declare const allocateCommitSeq: (sql: SqlExec) => number;
|
|
961
|
+
declare const clearCompanionSignatures: (sql: SqlExec) => void;
|
|
961
962
|
interface CompanionSyncDeps {
|
|
962
963
|
broadcast: (delta: MutationDelta) => void;
|
|
963
964
|
indexKeysFor: (table: string, document?: Record<string, unknown>) => ReadonlyArray<{
|
|
@@ -1404,6 +1405,7 @@ declare const ADMIN_FUNCTIONS: {
|
|
|
1404
1405
|
readonly rankBefore: "__lunora_admin__:rankBefore";
|
|
1405
1406
|
readonly rankPage: "__lunora_admin__:rankPage";
|
|
1406
1407
|
readonly readTablePage: "__lunora_admin__:readTablePage";
|
|
1408
|
+
readonly rebuildCompanions: "__lunora_admin__:rebuildCompanions";
|
|
1407
1409
|
readonly recordAuthEvent: "__lunora_admin__:recordAuthEvent";
|
|
1408
1410
|
readonly recordContainerEvent: "__lunora_admin__:recordContainerEvent";
|
|
1409
1411
|
readonly recordMail: "__lunora_admin__:recordMail";
|
|
@@ -2517,4 +2519,4 @@ interface WhereSqlStrategy<T = SQL> {
|
|
|
2517
2519
|
}
|
|
2518
2520
|
declare const serverInList: (engine: "mysql" | "postgres") => (reference: SQL, items: ReadonlyArray<unknown>, negated: boolean, budget?: number) => SQL;
|
|
2519
2521
|
declare const compileWhereSql: <T = SQL>(where: WhereInput | undefined, strategy: WhereSqlStrategy<T>, fragments?: WhereFragments<T>, reservedParams?: number) => T | undefined;
|
|
2520
|
-
export { ADMIN_FUNCTIONS, ADMIN_FUNCTION_PREFIX, AGGREGATE_SQL_FUNCTION, AGG_COUNT, AGG_KEY, AGG_VALUE, AUDIT_LOG_TABLE, type AdvisorProcedure, type AdvisorProceduresResult, type AdvisoriesResult, type AdvisoryFinding, type AggregateIndexDefinitionLike, type AggregateOp, type AggregateOptions, type AggregateResult, type AggregateTally, type AppendAuditEntry, type ApplyOnDeleteOptions, type AuditEntry, type AuditLogResult, BIGINT_KEY_DIGITS, type BroadcastDelta, CDC_LOG_TABLE, CDC_LOG_TABLE_SEQ_INDEX, CDC_META_TABLE, CLIENT_WATERMARK_TABLE, COMMIT_SEQ_FIELD, COMMIT_SEQ_TABLE, CURSOR_PREFIX, type CacheEntry, type CapturedMailRow, type CdcArchiveScope, type CdcChange, type CdcChangeKey, type ChangedKeys, type Clock, type ColumnMeta, type ColumnMetaLike, type CompanionSync, type CompanionSyncDeps, ConflictError, type ConflictKind, type CountArgs, CountRlsUnsupportedError, type CreateWorkflowInstanceResult, type CrossShardReadArgs, type CtxDbOptions, DATA_MIGRATION_STATE_TABLE, DEFAULT_FANOUT_TOPIC_LIMIT, DEFAULT_MAX_RELATION_KEYS, DEFAULT_MAX_RELAYS, DEFAULT_PROMOTION_THRESHOLDS, DEFAULT_TRANSACTION_LIMITS, DOC_COLUMN, type DataMigrationDocument, type DataMigrationLike, type DataMigrationTransform, type DatabaseWriterLike, type DependencyTracker, type DeployInfo, type DurableAttachDecision, type DurableStreamAttach, type DurableStreamRun, DurableStreamRunner, type DurableStreamSink, type ExportRow, type ExportShardAdminArgs, type ExportShardArgs, type ExternalSourceDiffResult, type ExternalSourceLike, FLAGS_FUNCTION_PREFIX, type FacetColumnOptions, type FacetColumnResult, type FacetValue, type FanOutBudget, type FanoutMetricsResult, type FanoutPathCounters, type FanoutTopicStat, type FieldOperators, type FilterClause, type FilterOperator, type FlagEvaluation, type FlagsResult, type FtsWriteOptions, type FunctionCallStat, type FunctionScanAttribution, type FunctionStatsResult, GEO_DEFAULT_PRECISION, GLOBAL_SHAPE_SNAPSHOT_TABLE, type GeoBoundingBox, type GeoFilterBuilderLike, type GeoIndexDefinitionLike, type GeoPoint, type GeoScoredDocument, type GlobalPollCounters, GlobalPollTick, type GroupByEntry, type GroupByOptions, type GuardableSchema$1 as GuardableSchema, IDEMPOTENCY_TABLE, type IdGenerator, type IdempotentRecord, type ImportError, type ImportShardAdminArgs, type ImportShardArgs, type ImportShardResult, type IncrementalMaterializeResult, type IndexDefinitionLike, type IndexKeyEntry, type IndexRangeBuilderLike, type KeyRange, type LifecycleDispatchInfo, type LifecycleEvent, MAIL_RETENTION, MAIL_TABLE, MAX_DURABLE_STREAM_BYTES, MAX_DURABLE_STREAM_CHUNKS, MAX_PAGE_SIZE, MAX_SQL_ROWS, type MaskColumnMetadata, type MaskPoliciesResult, type MaterializeResult, type MigrationDirection, type MigrationRunResult, type MigrationStatus, type MigrationStatusRow, type MutationDelta, type NestedWith, NotFoundError, NotUniqueError, type OnDeleteActionLike, type OrderByClause, type OrderByInput, type OrderKey, type OrderKeyConstraints, OwnerRelay, type OwnerRelayFrame, type PaginationOptions, type PitrBookmarkResult, type PitrRestoreArgs, type PitrRestoreResult, type PitrStorage, type PokeFrameMeta, type PromotionState, type PromotionThresholds, QUEUE_TABLE, type QueryArgs, type QueryPage, type QueueMessageOutcome, type QueueMessageRow, type QueueMetadata, type QueuesResult, RANK_TIEBREAK, REACTOR_STATE_TABLE, RELATED_DEFAULT_LIMIT, RELATED_DEPTH_DECAY, RELATED_MAX_DEPTH, RELATED_MAX_LIMIT, RELATION_EXISTS_KEY, RELATION_FUNCTION_PREFIX, REPROJECTION_MIGRATION_PREFIX, RLS_UNWRAP_SYMBOL, type RankBeforeOptions, type RankBeforeResult, type RankDirection, type RankIndexDefinitionLike, type RankOptions, type RankPage, type RankPageComputation, type RankPageDeps, type RankPageOptions, type RankPageRow, type RankPageRowKey, type RankResult, type RankSortKeyLike, ReactiveCache, type ReactiveCacheOptions, type ReactorDispatchResult, type ReactorMetadata, type ReactorState, type ReactorStats, type ReactorsResult, type ReadFootprint, type ReadHook, type ReadTablePageOptions, type RecordMailInput, type RecordQueueMessageInput, type RelatedDirection, type RelatedNode, type RelatedOptions, type RelatedPage, type RelatedStart, type RelatedStartReference, type RelationDefinitionLike, type RelationEdge, type RelationExistsMarker, type RelationGraphReader, type RelayAttach, type RelayDetach, type RelayFrame, type RelayHost, RelayMember, type RelayPokeDelivery, type RelayShapePoke, type RelayShapeSeed, type RelayShapeSubscribe, type RelayShapeUnsubscribe, type RenderedSql, type ReplicaFollowerHost, type ReplicaOwnerHost, type ReplicaReadiness, type ResolveRelationPredicatesOptions, type ResolveWithOptions, type ResolveWithResult, type ResolvedShape, type RestrictableQueryOptions, type RlsPoliciesResult, type RlsPolicyMetadata, RlsRequiredError, type RlsRoleMetadata, type RpcRequest, type RunDataMigrationOptions, type RunTriggersOptions, SCAN_DEP, SCHEDULE_OUTBOX_TABLE, SCHEMA_HISTORY_MAX_VERSIONS, SEARCH_STATE_TABLE, SHAPE_POKE_CURSOR_TABLE, type SchedulableWorkflowReferenceLike, type ScheduleOutbox, type ScheduleOutboxEnvelope, type ScheduleOutboxRow, type ScheduledFunctionDoc, type SchedulerLike, type SchemaLike, type ScoredDocument, type SearchBackfillProgress, type SearchFilterBuilderLike, type SearchIndexDefinitionLike, type SearchScoredDocument, type SelectMatchingIdsOptions, type ServerDefaultContextLike, type SettingEntry, type SettingKind, type SettingsResult, ShapeDiffCache, type ShapePokeCursorRow, type ShapePokePart, type ShapeProbeCounters, type ShapeRow, type ShapeRowOp, type ShapeSubscriptionQuery, type ShardRankPageResult, ShardRunner, type ShardRunnerOptions, type ShardSiblingHost, type ShardSocketLike, type SocketAttachment, type SortDirection, type SourceClientLike, type SourceCursorLike, type SourceRefresh, type SqlConsoleResult, type SqlCursor, type SqlEngine, type SqlExec, type SqlLintResult, type StorageMetadata, type StorageReference, type StorageReferenceResult, type StorageRuleMetadata, type StorageRulesResult, type StudioFeaturesResult, type SubscriptionConnection, type SubscriptionEnvelope, type SubscriptionIdentity, type SubscriptionInfo, type SubscriptionQuery, type SubscriptionReadFootprint, type SubscriptionsResult, type SystemDatabaseReader, type SystemDoc, type SystemQuery, type SystemReaderOptions, type SystemReaderSchedulerLike, type SystemReaderStorageLike, type SystemTableName, type TableColumnsResult, type TableDefinitionLike, type TableIndexInfo, type TableIndexesResult, type TableInfo, type TablePage, type TableReaderLike, type TablesColumnsResult, type TablesIndexesResult, type TransactionHeadroom, TransactionHeadroomTracker, type TransactionLimits, type TransactionSqlLike, type TriggerContextLike, type TriggerDefinitionLike, type TriggerEventLike, type TriggerOpLike, type TriggerTimingLike, type TtlSweepSpec, UNVOUCHABLE_DEP, VECTOR_BACKFILL_MAX_PAGES, type ValidatorLike, type VectorBackfillProgress, WORKERD_SQLITE_LIMITS, type WhereFilter, type WhereInput, type WhereSqlStrategy, type WithInput, type WorkflowInstanceState, type WorkflowInstanceStatusResult, type WorkflowMetadata, type WorkflowsResult, type WriteEvent, type WriteHook, advanceClientWatermark, aggUpsertSql, aggregateSqlFunction, aggregateTableName, allocateCommitSeq, appendAuditEntry, appendCdcChange, appendStreamChunk, applyCdcChanges, applyOnDelete, applySelect, archiveCdcSegment, armRestore, assertFlatPredicate, assertNoExplicitUndefined, assertReadonly, assertShapeShardable, 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, clearMemoryTables, clearQueueMessages, coerceAggregateNumber, compactCdcDocs, compileWhereSql, computeRankPage, containsRelationPredicate, countLegacyRows, coveringGeohashes, createCompanionSync, createDependencyTracker, createFanoutCounters, createGlobalPollCounters, createIndexSql, createReadFootprint, createRelayLink, createReplicaLink, createShapeDiffCache, createShapeProbeCounters, createShardCtxDb, createSystemReader, cursorBelowRetainedFloor, decideDurableAttach, decodeBigintSqlKey, decodeCursor, decodeFloat64SqlKey, deferScheduleOutbox, deleteGlobalShapeSnapshot, deleteGlobalShapeSnapshotsForConnection, deleteShapePokeCursor, deleteShapePokeCursorsForConnection, deleteStreamRun, depKey, deriveRelationEdges, diffExternalSource, diffGlobalMembership, distinctValues, encodeAggregateKey, encodeCursor, encodeGeohash, encodePartitionKey, encodeRowsPatch, ensureAuditTable, ensureMailTable, envOptionalPositiveInt, envPositiveInt, equalityPinnedFields, exportShardRows, facetColumn, fanOutScalarCounts, findRelated, findStorageReferences, finishStreamRun, float64SqlKey, foldAggregateTally, forgetScheduleOutbox, ftsCompanionDdl, ftsPurgeDocument, ftsRowidMapName, ftsUnmappedPage, ftsWriteDocument, gateReplicaDispatch, geoTableName, globalShapeReadKey, groupUnmappedRows, guardWriter, handleReplicaControl, hasTrigger, haversineMeters, importShardRows, indexKeysForRow, isDevEnvironment, isFtsAvailable, isInternalTableName, isLossyBody, isMemoryTable, isPushableWhere, isRelationPredicate, isSoftDeleted, isSourceDue, isVacuousFilterClause, jsonPath, jsonPathSql, keysTouchRanges, liftSourceId, lintReadonlySql, listReactorStates, listTables, markUnvouchableReads, matchesRankStaticWhere, matchesStaticWhere, materializeExternalRows, materializeExternalRowsIncremental, memoryTableNames, mergeChangedKeys, mergeWhere, migrateCdcLog, migrateCdcMeta, migrateClientWatermark, migrateCommitSeq, migrateDurableStreams, migrateGlobalShapeSnapshot, migrateIdempotency, migrateReactorState, migrateScheduleOutbox, migrateSearchState, migrateShapePokeCursor, minCdcReplayableSeq, minCdcSeq, minShapePokeCursor, nextPromotionState, normalizeCountArgument, normalizeIdStructurally, normalizeOrderKeys, normalizeSourceDocument, normalizeSourceValue, param, parkScheduleOutbox, parseExportShardArgs, parseImportShardArgs, planAggregateLookup, pointInBoundingBox, probeScheduleOutbox, projectColumns, pullExternalSourceIncrementalTick, pullExternalSourceTick, qualifiedJsonPath, qualifiedJsonPathSql, quoteIdentifier, rankKeyFromDocument as rankKeyFromDoc, rankPivotConditionSql, rankTableName, reactiveCacheKey, reactorNeedsRun, readAggregateValue, readArchivedCdcChanges, readAuditLog, readBookmark, readCapturedMail, readCdcArchivedThrough, readCdcChangeKeys, readCdcChanges, readCdcCursor, readCdcEpoch, readClientWatermark, readCommitSeq, readDeployInfo, readDueScheduleOutbox, readExternalSourceBaseline, readGlobalShapeSnapshot, readIdempotent, readMigrationStatus, readQueueMessageById, readQueueMessages, readReactorState, readSchemaHistory, readSchemaVersion, readSearchBackfillState, readShapePokeCursor, readStreamChunks, readStreamRun, readTablePage, recordCapturedMail, recordChangedKeys, recordFanoutPass, recordGlobalPollPass, recordQueueMessages, recordScheduleOutbox, recordSchemaVersion, recordShapeProbePass, relationHooks, relayCountFor, renderSql, reprojectableFields, reprojectionMigrationId, reprojectionTables, resolveRankPartition, resolveRankSeekTuple, resolveRelationPredicates, resolveWith, rowToDocument, runDataMigration, runDrizzle, runExternalSourceTick, runReadonlySql, runRowValidators, runShardMigrations, runSocketPool, runSql, runTriggers, selectExpiredIds, selectExportTables, selectIndexForAggregate, selectIndexForCount, selectIndexForGroupBy, selectMatchingIds, selectShapeMembers, selectShapeRows, serializeSqlValue, serverInList, shapeRoutingKey, softDeleteScope, sortColumnName, sqliteInList, stableStringify, stableWireKey, stripReservedPatchFields, stubByName, subscriptionFrames, subscriptionListDeltas, summarizeFanoutTopics, summarizeSubscriptions, tableColumns, tableFromDepKey, throwingScheduler, tiebreakDirectionFor, trimCdcChanges, trimIdempotent, trimScheduleOutbox, trimStreamRuns, tryRowToDocument, trySendFrame, unionAll, uniqueIndexFields, validateImportRow, whereFilter, whereOfFilter, writeCdcArchivedThrough, writeGlobalShapeSnapshot, writeIdempotent, writeReactorState, writeSearchBackfillState, writeShapePokeCursor, writeShapePokeCursors, writeTouchesMemo };
|
|
2522
|
+
export { ADMIN_FUNCTIONS, ADMIN_FUNCTION_PREFIX, AGGREGATE_SQL_FUNCTION, AGG_COUNT, AGG_KEY, AGG_VALUE, AUDIT_LOG_TABLE, type AdvisorProcedure, type AdvisorProceduresResult, type AdvisoriesResult, type AdvisoryFinding, type AggregateIndexDefinitionLike, type AggregateOp, type AggregateOptions, type AggregateResult, type AggregateTally, type AppendAuditEntry, type ApplyOnDeleteOptions, type AuditEntry, type AuditLogResult, BIGINT_KEY_DIGITS, type BroadcastDelta, CDC_LOG_TABLE, CDC_LOG_TABLE_SEQ_INDEX, CDC_META_TABLE, CLIENT_WATERMARK_TABLE, COMMIT_SEQ_FIELD, COMMIT_SEQ_TABLE, CURSOR_PREFIX, type CacheEntry, type CapturedMailRow, type CdcArchiveScope, type CdcChange, type CdcChangeKey, type ChangedKeys, type Clock, type ColumnMeta, type ColumnMetaLike, type CompanionSync, type CompanionSyncDeps, ConflictError, type ConflictKind, type CountArgs, CountRlsUnsupportedError, type CreateWorkflowInstanceResult, type CrossShardReadArgs, type CtxDbOptions, DATA_MIGRATION_STATE_TABLE, DEFAULT_FANOUT_TOPIC_LIMIT, DEFAULT_MAX_RELATION_KEYS, DEFAULT_MAX_RELAYS, DEFAULT_PROMOTION_THRESHOLDS, DEFAULT_TRANSACTION_LIMITS, DOC_COLUMN, type DataMigrationDocument, type DataMigrationLike, type DataMigrationTransform, type DatabaseWriterLike, type DependencyTracker, type DeployInfo, type DurableAttachDecision, type DurableStreamAttach, type DurableStreamRun, DurableStreamRunner, type DurableStreamSink, type ExportRow, type ExportShardAdminArgs, type ExportShardArgs, type ExternalSourceDiffResult, type ExternalSourceLike, FLAGS_FUNCTION_PREFIX, type FacetColumnOptions, type FacetColumnResult, type FacetValue, type FanOutBudget, type FanoutMetricsResult, type FanoutPathCounters, type FanoutTopicStat, type FieldOperators, type FilterClause, type FilterOperator, type FlagEvaluation, type FlagsResult, type FtsWriteOptions, type FunctionCallStat, type FunctionScanAttribution, type FunctionStatsResult, GEO_DEFAULT_PRECISION, GLOBAL_SHAPE_SNAPSHOT_TABLE, type GeoBoundingBox, type GeoFilterBuilderLike, type GeoIndexDefinitionLike, type GeoPoint, type GeoScoredDocument, type GlobalPollCounters, GlobalPollTick, type GroupByEntry, type GroupByOptions, type GuardableSchema$1 as GuardableSchema, IDEMPOTENCY_TABLE, type IdGenerator, type IdempotentRecord, type ImportError, type ImportShardAdminArgs, type ImportShardArgs, type ImportShardResult, type IncrementalMaterializeResult, type IndexDefinitionLike, type IndexKeyEntry, type IndexRangeBuilderLike, type KeyRange, type LifecycleDispatchInfo, type LifecycleEvent, MAIL_RETENTION, MAIL_TABLE, MAX_DURABLE_STREAM_BYTES, MAX_DURABLE_STREAM_CHUNKS, MAX_PAGE_SIZE, MAX_SQL_ROWS, type MaskColumnMetadata, type MaskPoliciesResult, type MaterializeResult, type MigrationDirection, type MigrationRunResult, type MigrationStatus, type MigrationStatusRow, type MutationDelta, type NestedWith, NotFoundError, NotUniqueError, type OnDeleteActionLike, type OrderByClause, type OrderByInput, type OrderKey, type OrderKeyConstraints, OwnerRelay, type OwnerRelayFrame, type PaginationOptions, type PitrBookmarkResult, type PitrRestoreArgs, type PitrRestoreResult, type PitrStorage, type PokeFrameMeta, type PromotionState, type PromotionThresholds, QUEUE_TABLE, type QueryArgs, type QueryPage, type QueueMessageOutcome, type QueueMessageRow, type QueueMetadata, type QueuesResult, RANK_TIEBREAK, REACTOR_STATE_TABLE, RELATED_DEFAULT_LIMIT, RELATED_DEPTH_DECAY, RELATED_MAX_DEPTH, RELATED_MAX_LIMIT, RELATION_EXISTS_KEY, RELATION_FUNCTION_PREFIX, REPROJECTION_MIGRATION_PREFIX, RLS_UNWRAP_SYMBOL, type RankBeforeOptions, type RankBeforeResult, type RankDirection, type RankIndexDefinitionLike, type RankOptions, type RankPage, type RankPageComputation, type RankPageDeps, type RankPageOptions, type RankPageRow, type RankPageRowKey, type RankResult, type RankSortKeyLike, ReactiveCache, type ReactiveCacheOptions, type ReactorDispatchResult, type ReactorMetadata, type ReactorState, type ReactorStats, type ReactorsResult, type ReadFootprint, type ReadHook, type ReadTablePageOptions, type RecordMailInput, type RecordQueueMessageInput, type RelatedDirection, type RelatedNode, type RelatedOptions, type RelatedPage, type RelatedStart, type RelatedStartReference, type RelationDefinitionLike, type RelationEdge, type RelationExistsMarker, type RelationGraphReader, type RelayAttach, type RelayDetach, type RelayFrame, type RelayHost, RelayMember, type RelayPokeDelivery, type RelayShapePoke, type RelayShapeSeed, type RelayShapeSubscribe, type RelayShapeUnsubscribe, type RenderedSql, type ReplicaFollowerHost, type ReplicaOwnerHost, type ReplicaReadiness, type ResolveRelationPredicatesOptions, type ResolveWithOptions, type ResolveWithResult, type ResolvedShape, type RestrictableQueryOptions, type RlsPoliciesResult, type RlsPolicyMetadata, RlsRequiredError, type RlsRoleMetadata, type RpcRequest, type RunDataMigrationOptions, type RunTriggersOptions, SCAN_DEP, SCHEDULE_OUTBOX_TABLE, SCHEMA_HISTORY_MAX_VERSIONS, SEARCH_STATE_TABLE, SHAPE_POKE_CURSOR_TABLE, type SchedulableWorkflowReferenceLike, type ScheduleOutbox, type ScheduleOutboxEnvelope, type ScheduleOutboxRow, type ScheduledFunctionDoc, type SchedulerLike, type SchemaLike, type ScoredDocument, type SearchBackfillProgress, type SearchFilterBuilderLike, type SearchIndexDefinitionLike, type SearchScoredDocument, type SelectMatchingIdsOptions, type ServerDefaultContextLike, type SettingEntry, type SettingKind, type SettingsResult, ShapeDiffCache, type ShapePokeCursorRow, type ShapePokePart, type ShapeProbeCounters, type ShapeRow, type ShapeRowOp, type ShapeSubscriptionQuery, type ShardRankPageResult, ShardRunner, type ShardRunnerOptions, type ShardSiblingHost, type ShardSocketLike, type SocketAttachment, type SortDirection, type SourceClientLike, type SourceCursorLike, type SourceRefresh, type SqlConsoleResult, type SqlCursor, type SqlEngine, type SqlExec, type SqlLintResult, type StorageMetadata, type StorageReference, type StorageReferenceResult, type StorageRuleMetadata, type StorageRulesResult, type StudioFeaturesResult, type SubscriptionConnection, type SubscriptionEnvelope, type SubscriptionIdentity, type SubscriptionInfo, type SubscriptionQuery, type SubscriptionReadFootprint, type SubscriptionsResult, type SystemDatabaseReader, type SystemDoc, type SystemQuery, type SystemReaderOptions, type SystemReaderSchedulerLike, type SystemReaderStorageLike, type SystemTableName, type TableColumnsResult, type TableDefinitionLike, type TableIndexInfo, type TableIndexesResult, type TableInfo, type TablePage, type TableReaderLike, type TablesColumnsResult, type TablesIndexesResult, type TransactionHeadroom, TransactionHeadroomTracker, type TransactionLimits, type TransactionSqlLike, type TriggerContextLike, type TriggerDefinitionLike, type TriggerEventLike, type TriggerOpLike, type TriggerTimingLike, type TtlSweepSpec, UNVOUCHABLE_DEP, VECTOR_BACKFILL_MAX_PAGES, type ValidatorLike, type VectorBackfillProgress, WORKERD_SQLITE_LIMITS, type WhereFilter, type WhereInput, type WhereSqlStrategy, type WithInput, type WorkflowInstanceState, type WorkflowInstanceStatusResult, type WorkflowMetadata, type WorkflowsResult, type WriteEvent, type WriteHook, advanceClientWatermark, aggUpsertSql, aggregateSqlFunction, aggregateTableName, allocateCommitSeq, appendAuditEntry, appendCdcChange, appendStreamChunk, applyCdcChanges, applyOnDelete, applySelect, archiveCdcSegment, armRestore, assertFlatPredicate, assertNoExplicitUndefined, assertReadonly, assertShapeShardable, 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, computeRankPage, containsRelationPredicate, countLegacyRows, coveringGeohashes, createCompanionSync, createDependencyTracker, createFanoutCounters, createGlobalPollCounters, createIndexSql, createReadFootprint, createRelayLink, createReplicaLink, createShapeDiffCache, createShapeProbeCounters, createShardCtxDb, createSystemReader, cursorBelowRetainedFloor, decideDurableAttach, decodeBigintSqlKey, decodeCursor, decodeFloat64SqlKey, deferScheduleOutbox, deleteGlobalShapeSnapshot, deleteGlobalShapeSnapshotsForConnection, deleteShapePokeCursor, deleteShapePokeCursorsForConnection, deleteStreamRun, depKey, deriveRelationEdges, diffExternalSource, diffGlobalMembership, distinctValues, encodeAggregateKey, encodeCursor, encodeGeohash, encodePartitionKey, encodeRowsPatch, ensureAuditTable, ensureMailTable, envOptionalPositiveInt, envPositiveInt, equalityPinnedFields, exportShardRows, facetColumn, fanOutScalarCounts, findRelated, findStorageReferences, finishStreamRun, float64SqlKey, foldAggregateTally, forgetScheduleOutbox, ftsCompanionDdl, ftsPurgeDocument, ftsRowidMapName, ftsUnmappedPage, ftsWriteDocument, gateReplicaDispatch, geoTableName, globalShapeReadKey, groupUnmappedRows, guardWriter, handleReplicaControl, hasTrigger, haversineMeters, importShardRows, indexKeysForRow, isDevEnvironment, isFtsAvailable, isInternalTableName, isLossyBody, isMemoryTable, isPushableWhere, isRelationPredicate, isSoftDeleted, isSourceDue, isVacuousFilterClause, jsonPath, jsonPathSql, keysTouchRanges, liftSourceId, lintReadonlySql, listReactorStates, listTables, markUnvouchableReads, matchesRankStaticWhere, matchesStaticWhere, materializeExternalRows, materializeExternalRowsIncremental, memoryTableNames, mergeChangedKeys, mergeWhere, migrateCdcLog, migrateCdcMeta, migrateClientWatermark, migrateCommitSeq, migrateDurableStreams, migrateGlobalShapeSnapshot, migrateIdempotency, migrateReactorState, migrateScheduleOutbox, migrateSearchState, migrateShapePokeCursor, minCdcReplayableSeq, minCdcSeq, minShapePokeCursor, nextPromotionState, normalizeCountArgument, normalizeIdStructurally, normalizeOrderKeys, normalizeSourceDocument, normalizeSourceValue, param, parkScheduleOutbox, parseExportShardArgs, parseImportShardArgs, planAggregateLookup, pointInBoundingBox, probeScheduleOutbox, projectColumns, pullExternalSourceIncrementalTick, pullExternalSourceTick, qualifiedJsonPath, qualifiedJsonPathSql, quoteIdentifier, rankKeyFromDocument as rankKeyFromDoc, rankPivotConditionSql, rankTableName, reactiveCacheKey, reactorNeedsRun, readAggregateValue, readArchivedCdcChanges, readAuditLog, readBookmark, readCapturedMail, readCdcArchivedThrough, readCdcChangeKeys, readCdcChanges, readCdcCursor, readCdcEpoch, readClientWatermark, readCommitSeq, readDeployInfo, readDueScheduleOutbox, readExternalSourceBaseline, readGlobalShapeSnapshot, readIdempotent, readMigrationStatus, readQueueMessageById, readQueueMessages, readReactorState, readSchemaHistory, readSchemaVersion, readSearchBackfillState, readShapePokeCursor, readStreamChunks, readStreamRun, readTablePage, recordCapturedMail, recordChangedKeys, recordFanoutPass, recordGlobalPollPass, recordQueueMessages, recordScheduleOutbox, recordSchemaVersion, recordShapeProbePass, relationHooks, relayCountFor, renderSql, reprojectableFields, reprojectionMigrationId, reprojectionTables, resolveRankPartition, resolveRankSeekTuple, resolveRelationPredicates, resolveWith, rowToDocument, runDataMigration, runDrizzle, runExternalSourceTick, runReadonlySql, runRowValidators, runShardMigrations, runSocketPool, runSql, runTriggers, selectExpiredIds, selectExportTables, selectIndexForAggregate, selectIndexForCount, selectIndexForGroupBy, selectMatchingIds, selectShapeMembers, selectShapeRows, serializeSqlValue, serverInList, shapeRoutingKey, softDeleteScope, sortColumnName, sqliteInList, stableStringify, stableWireKey, stripReservedPatchFields, stubByName, subscriptionFrames, subscriptionListDeltas, summarizeFanoutTopics, summarizeSubscriptions, tableColumns, tableFromDepKey, throwingScheduler, tiebreakDirectionFor, trimCdcChanges, trimIdempotent, trimScheduleOutbox, trimStreamRuns, tryRowToDocument, trySendFrame, unionAll, uniqueIndexFields, validateImportRow, 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-CTDgQEF8.mjs";import{AGGREGATE_SQL_FUNCTION as d,aggregateSqlFunction as c,matchesStaticWhere as m,normalizeCountArgument as p,throwingScheduler as S}from"./packem_shared/AGGREGATE_SQL_FUNCTION-DDEoMnJR.mjs";import{aggregateTableName as f,coerceAggregateNumber as E,encodeAggregateKey as h,foldAggregateTally as x,readAggregateValue as T}from"./packem_shared/aggregateTableName-C7o-gpms.mjs";import{CountRlsUnsupportedError as C,mergeWhere as A,planAggregateLookup as g,selectIndexForAggregate as _,selectIndexForCount as I,selectIndexForGroupBy as b}from"./packem_shared/CountRlsUnsupportedError-BvsDqfO2.mjs";import{AUDIT_LOG_TABLE as D,appendAuditEntry as P,ensureAuditTable as O,readAuditLog as M}from"./packem_shared/AUDIT_LOG_TABLE-CZNxCRLv.mjs";import{NotUniqueError as y,assertNoExplicitUndefined as N,assertValidClientId as k,createShardCtxDb as B,normalizeIdStructurally as U,stripReservedPatchFields as G}from"./packem_shared/NotUniqueError-D4EV8EzO.mjs";import{backfillAggregateIndexes as w,backfillRankIndexes as K,backfillSearchIndexes as v,backfillSearchIndexesForTable as W}from"./packem_shared/backfillAggregateIndexes-B_3xdOgV.mjs";import{CDC_LOG_TABLE as H,CDC_LOG_TABLE_SEQ_INDEX as V,CDC_META_TABLE as z,appendCdcChange as Q,applyCdcChanges as Y,bumpCdcEpoch as j,cdcCanVouchFor as J,cdcForkedError as Z,cdcSeqLeavingRows as $,cdcTouchesTables as ee,cdcTrimmedError as re,compactCdcDocs as oe,cursorBelowRetainedFloor as ae,migrateCdcLog as te,migrateCdcMeta as ie,minCdcReplayableSeq as se,minCdcSeq as ne,readCdcChangeKeys as le,readCdcChanges as de,readCdcCursor as ce,readCdcEpoch as me,trimCdcChanges as pe}from"./packem_shared/CDC_LOG_TABLE-QaBxSIZM.mjs";import{archiveCdcSegment as ue,cdcArchiveRewound as fe,readArchivedCdcChanges as Ee,readCdcArchivedThrough as he,writeCdcArchivedThrough as xe}from"./packem_shared/archiveCdcSegment-BON69Nug.mjs";import{CLIENT_WATERMARK_TABLE as Re,advanceClientWatermark as Ce,migrateClientWatermark as Ae,readClientWatermark as ge}from"./packem_shared/CLIENT_WATERMARK_TABLE-vLjfNhBR.mjs";import{COMMIT_SEQ_FIELD as Ie,COMMIT_SEQ_TABLE as be,allocateCommitSeq as Le,migrateCommitSeq as De,readCommitSeq as Pe}from"./packem_shared/COMMIT_SEQ_FIELD-BY_vc9bw.mjs";import{createCompanionSync as Me}from"./packem_shared/createCompanionSync-Rjn0lsT6.mjs";import{GLOBAL_SHAPE_SNAPSHOT_TABLE as ye,deleteGlobalShapeSnapshot as Ne,deleteGlobalShapeSnapshotsForConnection as ke,migrateGlobalShapeSnapshot as Be,readGlobalShapeSnapshot as Ue,writeGlobalShapeSnapshot as Ge}from"./packem_shared/GLOBAL_SHAPE_SNAPSHOT_TABLE-pMxZ-obU.mjs";import{IDEMPOTENCY_TABLE as we,migrateIdempotency as Ke,readIdempotent as ve,trimIdempotent as We,writeIdempotent as Xe}from"./packem_shared/IDEMPOTENCY_TABLE-AOJCuq5U.mjs";import{clearMemoryTables as Ve,isMemoryTable as ze,memoryTableNames as Qe}from"./packem_shared/clearMemoryTables-CogAvVHR.mjs";import{computeRankPage as je,resolveRankSeekTuple as Je}from"./packem_shared/computeRankPage-3AiKfT8q.mjs";import{SCHEDULE_OUTBOX_TABLE as $e,deferScheduleOutbox as er,forgetScheduleOutbox as rr,migrateScheduleOutbox as or,parkScheduleOutbox as ar,probeScheduleOutbox as tr,readDueScheduleOutbox as ir,recordScheduleOutbox as sr,trimScheduleOutbox as nr}from"./packem_shared/SCHEDULE_OUTBOX_TABLE-CgLvGxpY.mjs";import{S as dr,m as cr,r as mr,w as pr}from"./packem_shared/ctx-db-search-state-DVCp4JQf.mjs";import{SHAPE_POKE_CURSOR_TABLE as ur,deleteShapePokeCursor as fr,deleteShapePokeCursorsForConnection as Er,migrateShapePokeCursor as hr,minShapePokeCursor as xr,readShapePokeCursor as Tr,writeShapePokeCursor as Rr,writeShapePokeCursors as Cr}from"./packem_shared/SHAPE_POKE_CURSOR_TABLE-cn0stGAL.mjs";import{selectShapeMembers as gr,selectShapeRows as _r}from"./packem_shared/selectShapeMembers-BXhvEt4X.mjs";import{DATA_MIGRATION_STATE_TABLE as br,readMigrationStatus as Lr,runDataMigration as Dr}from"./packem_shared/DATA_MIGRATION_STATE_TABLE-BMbxLEaN.mjs";import{SCAN_DEP as Or,createDependencyTracker as Mr,depKey as Fr,tableFromDepKey as yr}from"./packem_shared/SCAN_DEP-D7qE3iUe.mjs";import{runDrizzle as kr,runSql as Br}from"./packem_shared/runDrizzle-Du5HLitO.mjs";import{A as Gr,a as qr,b as wr,D as Kr,c as vr,d as Wr,g as Xr,i as Hr,j as Vr,e as zr,q as Qr,f as Yr,r as jr,t as Jr,h as Zr}from"./packem_shared/do-sql-BEFrJUds.mjs";import{WORKERD_SQLITE_LIMITS as eo,param as ro,renderSql as oo,sqliteInList as ao,unionAll as to}from"./packem_shared/WORKERD_SQLITE_LIMITS-DBH23L_S.mjs";import{appendStreamChunk as so,claimStreamRun as no,deleteStreamRun as lo,finishStreamRun as co,migrateDurableStreams as mo,readStreamChunks as po,readStreamRun as So,trimStreamRuns as uo}from"./packem_shared/appendStreamChunk-7ZyAZGg_.mjs";import{DurableStreamRunner as Eo,MAX_DURABLE_STREAM_BYTES as ho,MAX_DURABLE_STREAM_CHUNKS as xo,decideDurableAttach as To}from"./packem_shared/DurableStreamRunner-Dk9Pn-B8.mjs";import{envOptionalPositiveInt as Co,envPositiveInt as Ao}from"./packem_shared/envOptionalPositiveInt-D2pY-c64.mjs";import{diffExternalSource as _o}from"./packem_shared/diffExternalSource-DgDJhslq.mjs";import{liftSourceId as bo,normalizeSourceDocument as Lo,normalizeSourceValue as Do}from"./packem_shared/liftSourceId-CA3ENhXj.mjs";import{materializeExternalRows as Oo,materializeExternalRowsIncremental as Mo,readExternalSourceBaseline as Fo,runExternalSourceTick as yo}from"./packem_shared/materializeExternalRows-DhINQHwd.mjs";import{isSoftDeleted as ko,isSourceDue as Bo,pullExternalSourceIncrementalTick as Uo,pullExternalSourceTick as Go}from"./packem_shared/isSoftDeleted-sGRSPPQq.mjs";import{f as wo,a as Ko,b as vo,c as Wo,d as Xo,g as Ho}from"./packem_shared/fts-companion-pUdD6kF-.mjs";import{GEO_DEFAULT_PRECISION as zo,boundingBoxCenter as Qo,boundingBoxGeohashes as Yo,coveringGeohashes as jo,encodeGeohash as Jo,haversineMeters as Zo,pointInBoundingBox as $o}from"./packem_shared/GEO_DEFAULT_PRECISION-CqpQZ-J_.mjs";import{default as ra}from"./packem_shared/GlobalPollTick-BNK4o-XT.mjs";import{ADMIN_FUNCTIONS as aa,ADMIN_FUNCTION_PREFIX as ta,DEFAULT_FANOUT_TOPIC_LIMIT as ia,FLAGS_FUNCTION_PREFIX as sa,MAX_PAGE_SIZE as na,RELATION_FUNCTION_PREFIX as la,createFanoutCounters as da,createGlobalPollCounters as ca,createShapeProbeCounters as ma,facetColumn as pa,findStorageReferences as Sa,isVacuousFilterClause as ua,listTables as fa,readTablePage as Ea,recordFanoutPass as ha,recordGlobalPollPass as xa,recordShapeProbePass as Ta,selectMatchingIds as Ra,summarizeFanoutTopics as Ca,summarizeSubscriptions as Aa}from"./packem_shared/ADMIN_FUNCTIONS-CZiYkV6K.mjs";import{MAIL_RETENTION as _a,MAIL_TABLE as Ia,clearCapturedMail as ba,ensureMailTable as La,readCapturedMail as Da,recordCapturedMail as Pa}from"./packem_shared/MAIL_RETENTION-BxAGL3hK.mjs";import{NotFoundError as Ma}from"./packem_shared/NotFoundError-BhF7FeFr.mjs";import{armRestore as ya,readBookmark as Na}from"./packem_shared/armRestore-Bu1_8SUa.mjs";import{CURSOR_PREFIX as Ba,applySelect as Ua,buildSeekBeforeWhere as Ga,buildSeekWhere as qa,decodeCursor as wa,encodeCursor as Ka,equalityPinnedFields as va,normalizeOrderKeys as Wa,softDeleteScope as Xa,tiebreakDirectionFor as Ha,uniqueIndexFields as Va}from"./packem_shared/CURSOR_PREFIX-BX8jkMJa.mjs";import{QUEUE_TABLE as Qa,clearQueueMessages as Ya,isLossyBody as ja,readQueueMessageById as Ja,readQueueMessages as Za,recordQueueMessages as $a}from"./packem_shared/QUEUE_TABLE-DKANxmEZ.mjs";import{RANK_TIEBREAK as rt,encodePartitionKey as ot,matchesRankStaticWhere as at,rankKeyFromDoc as tt,rankPivotConditionSql as it,rankTableName as st,resolveRankPartition as nt,sortColumnName as lt}from"./packem_shared/RANK_TIEBREAK-B0_x8iev.mjs";import{ReactiveCache as ct,reactiveCacheKey as mt}from"./packem_shared/ReactiveCache-D8ccaO6f.mjs";import{REACTOR_STATE_TABLE as St,listReactorStates as ut,migrateReactorState as ft,reactorNeedsRun as Et,readReactorState as ht,writeReactorState as xt}from"./packem_shared/REACTOR_STATE_TABLE-B8IehLv8.mjs";import{UNVOUCHABLE_DEP as Rt,createReadFootprint as Ct,markUnvouchableReads as At}from"./packem_shared/UNVOUCHABLE_DEP-C68htACn.mjs";import{buildIndexRange as _t,indexKeysForRow as It,keysTouchRanges as bt}from"./packem_shared/buildIndexRange-6nIZDf4m.mjs";import{isPushableWhere as Dt,whereFilter as Pt,whereOfFilter as Ot}from"./packem_shared/isPushableWhere-BeYAOjUb.mjs";import{RELATED_DEFAULT_LIMIT as Ft,RELATED_DEPTH_DECAY as yt,RELATED_MAX_DEPTH as Nt,RELATED_MAX_LIMIT as kt,deriveRelationEdges as Bt,findRelated as Ut}from"./packem_shared/RELATED_DEFAULT_LIMIT-CBYQQIrZ.mjs";import{DEFAULT_MAX_RELATION_KEYS as qt,assertFlatPredicate as wt,assertShapeShardable as Kt,containsRelationPredicate as vt,isRelationPredicate as Wt,resolveRelationPredicates as Xt}from"./packem_shared/DEFAULT_MAX_RELATION_KEYS-CYPZfQH9.mjs";import{applyOnDelete as Vt,distinctValues as zt,fanOutScalarCounts as Qt,relationHooks as Yt,resolveWith as jt,runRowValidators as Jt}from"./packem_shared/applyOnDelete-DJsOG8tz.mjs";import{DEFAULT_PROMOTION_THRESHOLDS as $t,clampPromotionThresholds as ei,nextPromotionState as ri,relayCountFor as oi,shapeRoutingKey as ai}from"./packem_shared/DEFAULT_PROMOTION_THRESHOLDS-91RH_llq.mjs";import{DEFAULT_MAX_RELAYS as ii,OwnerRelay as si,RelayMember as ni,createRelayLink as li}from"./packem_shared/DEFAULT_MAX_RELAYS-B-yt9l6-.mjs";import{createReplicaLink as ci,gateReplicaDispatch as mi,handleReplicaControl as pi}from"./packem_shared/createReplicaLink-CV7SD_b-.mjs";import{buildReprojectionMigration as ui,countLegacyRows as fi,reprojectableFields as Ei,reprojectionTables as hi}from"./packem_shared/buildReprojectionMigration-IMrfRdvU.mjs";import{RLS_UNWRAP_SYMBOL as Ti,RlsRequiredError as Ri,guardWriter as Ci}from"./packem_shared/RLS_UNWRAP_SYMBOL-rSxYzw-G.mjs";import{SCHEMA_HISTORY_MAX_VERSIONS as gi,readSchemaHistory as _i,readSchemaVersion as Ii,recordSchemaVersion as bi}from"./packem_shared/SCHEMA_HISTORY_MAX_VERSIONS-BMcUIqBY.mjs";import{serializeSqlValue as Di}from"./packem_shared/serializeSqlValue-BbZ5hKM7.mjs";import{buildSettings as Oi,isDevEnvironment as Mi,readDeployInfo as Fi}from"./packem_shared/buildSettings-BRkZd6_E.mjs";import{buildShapeDiff as Ni}from"./packem_shared/buildShapeDiff-D-J_GmC1.mjs";import{ShapeDiffCache as Bi,createShapeDiffCache as Ui,globalShapeReadKey as Gi}from"./packem_shared/ShapeDiffCache-gdaILV5E.mjs";import{buildPokeFrames as wi,diffGlobalMembership as Ki,encodeRowsPatch as vi,projectColumns as Wi}from"./packem_shared/buildPokeFrames-BBE6J91z.mjs";import{ShardRunner as Hi}from"./packem_shared/ShardRunner-CrveaPId.mjs";import{stubByName as zi}from"./packem_shared/stubByName-C_P73AOx.mjs";import{runSocketPool as Yi}from"./packem_shared/runSocketPool-CZJ2X9cF.mjs";import{MAX_SQL_ROWS as Ji,assertReadonly as Zi,lintReadonlySql as $i,runReadonlySql as es}from"./packem_shared/MAX_SQL_ROWS-Dh_Ty0Zo.mjs";import{BIGINT_KEY_DIGITS as os,bigintSqlKey as as,decodeBigintSqlKey as ts,decodeFloat64SqlKey as is,float64SqlKey as ss}from"./packem_shared/BIGINT_KEY_DIGITS-C9a7Ix7k.mjs";import{awaitWsDrain as ls,subscriptionFrames as ds,subscriptionListDeltas as cs,trySendFrame as ms}from"./packem_shared/awaitWsDrain-apizgmKY.mjs";import{mergeChangedKeys as Ss,recordChangedKeys as us,writeTouchesMemo as fs}from"./packem_shared/mergeChangedKeys-DH9RAARR.mjs";import{createSystemReader as hs}from"./packem_shared/createSystemReader-DcDLFfC-.mjs";import{ConflictError as Ts}from"./packem_shared/ConflictError-C8GtJmjS.mjs";import{DEFAULT_TRANSACTION_LIMITS as Cs,TransactionHeadroomTracker as As}from"./packem_shared/DEFAULT_TRANSACTION_LIMITS-DiR5z5EX.mjs";import{hasTrigger as _s,runTriggers as Is}from"./packem_shared/hasTrigger-CjlwI4le.mjs";import{selectExpiredIds as Ls}from"./packem_shared/selectExpiredIds-DQg6v5Uf.mjs";import{VECTOR_BACKFILL_MAX_PAGES as Ps,backfillVectorIndexes as Os}from"./packem_shared/VECTOR_BACKFILL_MAX_PAGES-B2ZWxshy.mjs";import{c as Fs,s as ys}from"./packem_shared/where-sql-DFs8Zw7-.mjs";import{RELATION_EXISTS_KEY as ks}from"./packem_shared/RELATION_EXISTS_KEY-CFUhnZSZ.mjs";import{REPROJECTION_MIGRATION_PREFIX as Us,reprojectionMigrationId as Gs}from"./packem_shared/REPROJECTION_MIGRATION_PREFIX-Czcb6_mO.mjs";import{isInternalTableName as ws}from"./packem_shared/isInternalTableName-BoljO2tP.mjs";import{quoteIdentifier as vs}from"./packem_shared/quoteIdentifier-CObIFRhb.mjs";import{runShardMigrations as Xs}from"./packem_shared/runShardMigrations-MXioI81k.mjs";import{stableStringify as Vs}from"./packem_shared/stableStringify-DibjylKD.mjs";import{stableWireKey as Qs}from"./packem_shared/stableWireKey-D2US4k_J.mjs";export{aa as ADMIN_FUNCTIONS,ta as ADMIN_FUNCTION_PREFIX,d as AGGREGATE_SQL_FUNCTION,Gr as AGG_COUNT,qr as AGG_KEY,wr as AGG_VALUE,D as AUDIT_LOG_TABLE,os as BIGINT_KEY_DIGITS,H as CDC_LOG_TABLE,V as CDC_LOG_TABLE_SEQ_INDEX,z as CDC_META_TABLE,Re as CLIENT_WATERMARK_TABLE,Ie as COMMIT_SEQ_FIELD,be as COMMIT_SEQ_TABLE,Ba as CURSOR_PREFIX,Ts as ConflictError,C as CountRlsUnsupportedError,br as DATA_MIGRATION_STATE_TABLE,ia as DEFAULT_FANOUT_TOPIC_LIMIT,qt as DEFAULT_MAX_RELATION_KEYS,ii as DEFAULT_MAX_RELAYS,$t as DEFAULT_PROMOTION_THRESHOLDS,Cs as DEFAULT_TRANSACTION_LIMITS,Kr as DOC_COLUMN,Eo as DurableStreamRunner,sa as FLAGS_FUNCTION_PREFIX,zo as GEO_DEFAULT_PRECISION,ye as GLOBAL_SHAPE_SNAPSHOT_TABLE,ra as GlobalPollTick,we as IDEMPOTENCY_TABLE,_a as MAIL_RETENTION,Ia as MAIL_TABLE,ho as MAX_DURABLE_STREAM_BYTES,xo as MAX_DURABLE_STREAM_CHUNKS,na as MAX_PAGE_SIZE,Ji as MAX_SQL_ROWS,Ma as NotFoundError,y as NotUniqueError,si as OwnerRelay,Qa as QUEUE_TABLE,rt as RANK_TIEBREAK,St as REACTOR_STATE_TABLE,Ft as RELATED_DEFAULT_LIMIT,yt as RELATED_DEPTH_DECAY,Nt as RELATED_MAX_DEPTH,kt as RELATED_MAX_LIMIT,ks as RELATION_EXISTS_KEY,la as RELATION_FUNCTION_PREFIX,Us as REPROJECTION_MIGRATION_PREFIX,Ti as RLS_UNWRAP_SYMBOL,ct as ReactiveCache,ni as RelayMember,Ri as RlsRequiredError,Or as SCAN_DEP,$e as SCHEDULE_OUTBOX_TABLE,gi as SCHEMA_HISTORY_MAX_VERSIONS,dr as SEARCH_STATE_TABLE,ur as SHAPE_POKE_CURSOR_TABLE,Bi as ShapeDiffCache,Hi as ShardRunner,As as TransactionHeadroomTracker,Rt as UNVOUCHABLE_DEP,Ps as VECTOR_BACKFILL_MAX_PAGES,eo as WORKERD_SQLITE_LIMITS,Ce as advanceClientWatermark,vr as aggUpsertSql,c as aggregateSqlFunction,f as aggregateTableName,Le as allocateCommitSeq,P as appendAuditEntry,Q as appendCdcChange,so as appendStreamChunk,Y as applyCdcChanges,Vt as applyOnDelete,Ua as applySelect,ue as archiveCdcSegment,ya as armRestore,wt as assertFlatPredicate,N as assertNoExplicitUndefined,Zi as assertReadonly,Kt as assertShapeShardable,k as assertValidClientId,ls as awaitWsDrain,w as backfillAggregateIndexes,K as backfillRankIndexes,v as backfillSearchIndexes,W as backfillSearchIndexesForTable,Os as backfillVectorIndexes,as as bigintSqlKey,Qo as boundingBoxCenter,Yo as boundingBoxGeohashes,_t as buildIndexRange,wi as buildPokeFrames,ui as buildReprojectionMigration,Ga as buildSeekBeforeWhere,qa as buildSeekWhere,Oi as buildSettings,Ni as buildShapeDiff,j as bumpCdcEpoch,fe as cdcArchiveRewound,J as cdcCanVouchFor,Z as cdcForkedError,$ as cdcSeqLeavingRows,ee as cdcTouchesTables,re as cdcTrimmedError,no as claimStreamRun,ei as clampPromotionThresholds,ba as clearCapturedMail,Ve as clearMemoryTables,Ya as clearQueueMessages,E as coerceAggregateNumber,oe as compactCdcDocs,Fs as compileWhereSql,je as computeRankPage,vt as containsRelationPredicate,fi as countLegacyRows,jo as coveringGeohashes,Me as createCompanionSync,Mr as createDependencyTracker,da as createFanoutCounters,ca as createGlobalPollCounters,Wr as createIndexSql,Ct as createReadFootprint,li as createRelayLink,ci as createReplicaLink,Ui as createShapeDiffCache,ma as createShapeProbeCounters,B as createShardCtxDb,hs as createSystemReader,ae as cursorBelowRetainedFloor,To as decideDurableAttach,ts as decodeBigintSqlKey,wa as decodeCursor,is as decodeFloat64SqlKey,er as deferScheduleOutbox,Ne as deleteGlobalShapeSnapshot,ke as deleteGlobalShapeSnapshotsForConnection,fr as deleteShapePokeCursor,Er as deleteShapePokeCursorsForConnection,lo as deleteStreamRun,Fr as depKey,Bt as deriveRelationEdges,_o as diffExternalSource,Ki as diffGlobalMembership,zt as distinctValues,h as encodeAggregateKey,Ka as encodeCursor,Jo as encodeGeohash,ot as encodePartitionKey,vi as encodeRowsPatch,O as ensureAuditTable,La as ensureMailTable,Co as envOptionalPositiveInt,Ao as envPositiveInt,va as equalityPinnedFields,o as exportShardRows,pa as facetColumn,Qt as fanOutScalarCounts,Ut as findRelated,Sa as findStorageReferences,co as finishStreamRun,ss as float64SqlKey,x as foldAggregateTally,rr as forgetScheduleOutbox,wo as ftsCompanionDdl,Ko as ftsPurgeDocument,vo as ftsRowidMapName,Wo as ftsUnmappedPage,Xo as ftsWriteDocument,mi as gateReplicaDispatch,Xr as geoTableName,Gi as globalShapeReadKey,Ho as groupUnmappedRows,Ci as guardWriter,pi as handleReplicaControl,_s as hasTrigger,Zo as haversineMeters,a as importShardRows,It as indexKeysForRow,Mi as isDevEnvironment,Hr as isFtsAvailable,ws as isInternalTableName,ja as isLossyBody,ze as isMemoryTable,Dt as isPushableWhere,Wt as isRelationPredicate,ko as isSoftDeleted,Bo as isSourceDue,ua as isVacuousFilterClause,Vr as jsonPath,zr as jsonPathSql,bt as keysTouchRanges,bo as liftSourceId,$i as lintReadonlySql,ut as listReactorStates,fa as listTables,At as markUnvouchableReads,at as matchesRankStaticWhere,m as matchesStaticWhere,Oo as materializeExternalRows,Mo as materializeExternalRowsIncremental,Qe as memoryTableNames,Ss as mergeChangedKeys,A as mergeWhere,te as migrateCdcLog,ie as migrateCdcMeta,Ae as migrateClientWatermark,De as migrateCommitSeq,mo as migrateDurableStreams,Be as migrateGlobalShapeSnapshot,Ke as migrateIdempotency,ft as migrateReactorState,or as migrateScheduleOutbox,cr as migrateSearchState,hr as migrateShapePokeCursor,se as minCdcReplayableSeq,ne as minCdcSeq,xr as minShapePokeCursor,ri as nextPromotionState,p as normalizeCountArgument,U as normalizeIdStructurally,Wa as normalizeOrderKeys,Lo as normalizeSourceDocument,Do as normalizeSourceValue,ro as param,ar as parkScheduleOutbox,t as parseExportShardArgs,i as parseImportShardArgs,g as planAggregateLookup,$o as pointInBoundingBox,tr as probeScheduleOutbox,Wi as projectColumns,Uo as pullExternalSourceIncrementalTick,Go as pullExternalSourceTick,Qr as qualifiedJsonPath,Yr as qualifiedJsonPathSql,vs as quoteIdentifier,tt as rankKeyFromDoc,it as rankPivotConditionSql,st as rankTableName,mt as reactiveCacheKey,Et as reactorNeedsRun,T as readAggregateValue,Ee as readArchivedCdcChanges,M as readAuditLog,Na as readBookmark,Da as readCapturedMail,he as readCdcArchivedThrough,le as readCdcChangeKeys,de as readCdcChanges,ce as readCdcCursor,me as readCdcEpoch,ge as readClientWatermark,Pe as readCommitSeq,Fi as readDeployInfo,ir as readDueScheduleOutbox,Fo as readExternalSourceBaseline,Ue as readGlobalShapeSnapshot,ve as readIdempotent,Lr as readMigrationStatus,Ja as readQueueMessageById,Za as readQueueMessages,ht as readReactorState,_i as readSchemaHistory,Ii as readSchemaVersion,mr as readSearchBackfillState,Tr as readShapePokeCursor,po as readStreamChunks,So as readStreamRun,Ea as readTablePage,Pa as recordCapturedMail,us as recordChangedKeys,ha as recordFanoutPass,xa as recordGlobalPollPass,$a as recordQueueMessages,sr as recordScheduleOutbox,bi as recordSchemaVersion,Ta as recordShapeProbePass,Yt as relationHooks,oi as relayCountFor,oo as renderSql,Ei as reprojectableFields,Gs as reprojectionMigrationId,hi as reprojectionTables,nt as resolveRankPartition,Je as resolveRankSeekTuple,Xt as resolveRelationPredicates,jt as resolveWith,jr as rowToDocument,Dr as runDataMigration,kr as runDrizzle,yo as runExternalSourceTick,es as runReadonlySql,Jt as runRowValidators,Xs as runShardMigrations,Yi as runSocketPool,Br as runSql,Is as runTriggers,Ls as selectExpiredIds,s as selectExportTables,_ as selectIndexForAggregate,I as selectIndexForCount,b as selectIndexForGroupBy,Ra as selectMatchingIds,gr as selectShapeMembers,_r as selectShapeRows,Di as serializeSqlValue,ys as serverInList,ai as shapeRoutingKey,Xa as softDeleteScope,lt as sortColumnName,ao as sqliteInList,Vs as stableStringify,Qs as stableWireKey,G as stripReservedPatchFields,zi as stubByName,ds as subscriptionFrames,cs as subscriptionListDeltas,Ca as summarizeFanoutTopics,Aa as summarizeSubscriptions,Jr as tableColumns,yr as tableFromDepKey,S as throwingScheduler,Ha as tiebreakDirectionFor,pe as trimCdcChanges,We as trimIdempotent,nr as trimScheduleOutbox,uo as trimStreamRuns,Zr as tryRowToDocument,ms as trySendFrame,to as unionAll,Va as uniqueIndexFields,n as validateImportRow,Pt as whereFilter,Ot as whereOfFilter,xe as writeCdcArchivedThrough,Ge as writeGlobalShapeSnapshot,Xe as writeIdempotent,xt as writeReactorState,pr as writeSearchBackfillState,Rr as writeShapePokeCursor,Cr as writeShapePokeCursors,fs as writeTouchesMemo};
|
|
1
|
+
import{exportShardRows as o,importShardRows as a,parseExportShardArgs as t,parseImportShardArgs as i,selectExportTables as n,validateImportRow as s}from"./packem_shared/exportShardRows-CTDgQEF8.mjs";import{AGGREGATE_SQL_FUNCTION as d,aggregateSqlFunction as c,matchesStaticWhere as m,normalizeCountArgument as p,throwingScheduler as S}from"./packem_shared/AGGREGATE_SQL_FUNCTION-DDEoMnJR.mjs";import{aggregateTableName as f,coerceAggregateNumber as x,encodeAggregateKey as E,foldAggregateTally as h,readAggregateValue as T}from"./packem_shared/aggregateTableName-DbAttCNH.mjs";import{CountRlsUnsupportedError as R,mergeWhere as A,planAggregateLookup as g,selectIndexForAggregate as _,selectIndexForCount as I,selectIndexForGroupBy as b}from"./packem_shared/CountRlsUnsupportedError-BvsDqfO2.mjs";import{AUDIT_LOG_TABLE as D,appendAuditEntry as P,ensureAuditTable as O,readAuditLog as M}from"./packem_shared/AUDIT_LOG_TABLE-CZNxCRLv.mjs";import{NotUniqueError as y,assertNoExplicitUndefined as N,assertValidClientId as k,createShardCtxDb as B,normalizeIdStructurally as U,stripReservedPatchFields as G}from"./packem_shared/NotUniqueError-CP6A9cx3.mjs";import{backfillAggregateIndexes as w,backfillRankIndexes as K,backfillSearchIndexes as v,backfillSearchIndexesForTable as W}from"./packem_shared/backfillAggregateIndexes-B1yVAkvK.mjs";import{CDC_LOG_TABLE as H,CDC_LOG_TABLE_SEQ_INDEX as V,CDC_META_TABLE as z,appendCdcChange as Q,applyCdcChanges as Y,bumpCdcEpoch as j,cdcCanVouchFor as J,cdcForkedError as Z,cdcSeqLeavingRows as $,cdcTouchesTables as ee,cdcTrimmedError as re,compactCdcDocs as oe,cursorBelowRetainedFloor as ae,migrateCdcLog as te,migrateCdcMeta as ie,minCdcReplayableSeq as ne,minCdcSeq as se,readCdcChangeKeys as le,readCdcChanges as de,readCdcCursor as ce,readCdcEpoch as me,trimCdcChanges as pe}from"./packem_shared/CDC_LOG_TABLE-GKlDpuM2.mjs";import{archiveCdcSegment as ue,cdcArchiveRewound as fe,readArchivedCdcChanges as xe,readCdcArchivedThrough as Ee,writeCdcArchivedThrough as he}from"./packem_shared/archiveCdcSegment-BON69Nug.mjs";import{CLIENT_WATERMARK_TABLE as Ce,advanceClientWatermark as Re,migrateClientWatermark as Ae,readClientWatermark as ge}from"./packem_shared/CLIENT_WATERMARK_TABLE-vLjfNhBR.mjs";import{COMMIT_SEQ_FIELD as Ie,COMMIT_SEQ_TABLE as be,allocateCommitSeq as Le,migrateCommitSeq as De,readCommitSeq as Pe}from"./packem_shared/COMMIT_SEQ_FIELD-BY_vc9bw.mjs";import{clearCompanionSignatures as Me}from"./packem_shared/clearCompanionSignatures-C2CSfkeQ.mjs";import{createCompanionSync as ye}from"./packem_shared/createCompanionSync-hGCzG0O1.mjs";import{GLOBAL_SHAPE_SNAPSHOT_TABLE as ke,deleteGlobalShapeSnapshot as Be,deleteGlobalShapeSnapshotsForConnection as Ue,migrateGlobalShapeSnapshot as Ge,readGlobalShapeSnapshot as qe,writeGlobalShapeSnapshot as we}from"./packem_shared/GLOBAL_SHAPE_SNAPSHOT_TABLE-pMxZ-obU.mjs";import{IDEMPOTENCY_TABLE as ve,migrateIdempotency as We,readIdempotent as Xe,trimIdempotent as He,writeIdempotent as Ve}from"./packem_shared/IDEMPOTENCY_TABLE-AOJCuq5U.mjs";import{clearMemoryTables as Qe,isMemoryTable as Ye,memoryTableNames as je}from"./packem_shared/clearMemoryTables-CogAvVHR.mjs";import{computeRankPage as Ze,resolveRankSeekTuple as $e}from"./packem_shared/computeRankPage-BI2lNKPu.mjs";import{SCHEDULE_OUTBOX_TABLE as rr,deferScheduleOutbox as or,forgetScheduleOutbox as ar,migrateScheduleOutbox as tr,parkScheduleOutbox as ir,probeScheduleOutbox as nr,readDueScheduleOutbox as sr,recordScheduleOutbox as lr,trimScheduleOutbox as dr}from"./packem_shared/SCHEDULE_OUTBOX_TABLE-CgLvGxpY.mjs";import{S as mr,m as pr,r as Sr,w as ur}from"./packem_shared/ctx-db-search-state-DVCp4JQf.mjs";import{SHAPE_POKE_CURSOR_TABLE as xr,deleteShapePokeCursor as Er,deleteShapePokeCursorsForConnection as hr,migrateShapePokeCursor as Tr,minShapePokeCursor as Cr,readShapePokeCursor as Rr,writeShapePokeCursor as Ar,writeShapePokeCursors as gr}from"./packem_shared/SHAPE_POKE_CURSOR_TABLE-cn0stGAL.mjs";import{selectShapeMembers as Ir,selectShapeRows as br}from"./packem_shared/selectShapeMembers-CNpeUQ-H.mjs";import{DATA_MIGRATION_STATE_TABLE as Dr,readMigrationStatus as Pr,runDataMigration as Or}from"./packem_shared/DATA_MIGRATION_STATE_TABLE-DfqA-2Dj.mjs";import{SCAN_DEP as Fr,createDependencyTracker as yr,depKey as Nr,tableFromDepKey as kr}from"./packem_shared/SCAN_DEP-D7qE3iUe.mjs";import{runDrizzle as Ur,runSql as Gr}from"./packem_shared/runDrizzle-Du5HLitO.mjs";import{A as wr,a as Kr,b as vr,D as Wr,c as Xr,d as Hr,g as Vr,i as zr,j as Qr,e as Yr,q as jr,f as Jr,r as Zr,t as $r,h as eo}from"./packem_shared/do-sql-CyWszGdM.mjs";import{WORKERD_SQLITE_LIMITS as oo,param as ao,renderSql as to,sqliteInList as io,unionAll as no}from"./packem_shared/WORKERD_SQLITE_LIMITS-DBH23L_S.mjs";import{appendStreamChunk as lo,claimStreamRun as co,deleteStreamRun as mo,finishStreamRun as po,migrateDurableStreams as So,readStreamChunks as uo,readStreamRun as fo,trimStreamRuns as xo}from"./packem_shared/appendStreamChunk-7ZyAZGg_.mjs";import{DurableStreamRunner as ho,MAX_DURABLE_STREAM_BYTES as To,MAX_DURABLE_STREAM_CHUNKS as Co,decideDurableAttach as Ro}from"./packem_shared/DurableStreamRunner-y2CRbfuZ.mjs";import{envOptionalPositiveInt as go,envPositiveInt as _o}from"./packem_shared/envOptionalPositiveInt-D2pY-c64.mjs";import{diffExternalSource as bo}from"./packem_shared/diffExternalSource-DgDJhslq.mjs";import{liftSourceId as Do,normalizeSourceDocument as Po,normalizeSourceValue as Oo}from"./packem_shared/liftSourceId-CA3ENhXj.mjs";import{materializeExternalRows as Fo,materializeExternalRowsIncremental as yo,readExternalSourceBaseline as No,runExternalSourceTick as ko}from"./packem_shared/materializeExternalRows-Csa8ELkU.mjs";import{isSoftDeleted as Uo,isSourceDue as Go,pullExternalSourceIncrementalTick as qo,pullExternalSourceTick as wo}from"./packem_shared/isSoftDeleted-BHlFkAsr.mjs";import{f as vo,a as Wo,b as Xo,c as Ho,d as Vo,g as zo}from"./packem_shared/fts-companion-pUdD6kF-.mjs";import{GEO_DEFAULT_PRECISION as Yo,boundingBoxCenter as jo,boundingBoxGeohashes as Jo,coveringGeohashes as Zo,encodeGeohash as $o,haversineMeters as ea,pointInBoundingBox as ra}from"./packem_shared/GEO_DEFAULT_PRECISION-CqpQZ-J_.mjs";import{default as aa}from"./packem_shared/GlobalPollTick-BNK4o-XT.mjs";import{ADMIN_FUNCTIONS as ia,ADMIN_FUNCTION_PREFIX as na,DEFAULT_FANOUT_TOPIC_LIMIT as sa,FLAGS_FUNCTION_PREFIX as la,MAX_PAGE_SIZE as da,RELATION_FUNCTION_PREFIX as ca,createFanoutCounters as ma,createGlobalPollCounters as pa,createShapeProbeCounters as Sa,facetColumn as ua,findStorageReferences as fa,isVacuousFilterClause as xa,listTables as Ea,readTablePage as ha,recordFanoutPass as Ta,recordGlobalPollPass as Ca,recordShapeProbePass as Ra,selectMatchingIds as Aa,summarizeFanoutTopics as ga,summarizeSubscriptions as _a}from"./packem_shared/ADMIN_FUNCTIONS-BGXP6oxh.mjs";import{MAIL_RETENTION as ba,MAIL_TABLE as La,clearCapturedMail as Da,ensureMailTable as Pa,readCapturedMail as Oa,recordCapturedMail as Ma}from"./packem_shared/MAIL_RETENTION-BxAGL3hK.mjs";import{NotFoundError as ya}from"./packem_shared/NotFoundError-BhF7FeFr.mjs";import{armRestore as ka,readBookmark as Ba}from"./packem_shared/armRestore-Bu1_8SUa.mjs";import{CURSOR_PREFIX as Ga,applySelect as qa,buildSeekBeforeWhere as wa,buildSeekWhere as Ka,decodeCursor as va,encodeCursor as Wa,equalityPinnedFields as Xa,normalizeOrderKeys as Ha,softDeleteScope as Va,tiebreakDirectionFor as za,uniqueIndexFields as Qa}from"./packem_shared/CURSOR_PREFIX-C1jsjAPd.mjs";import{QUEUE_TABLE as ja,clearQueueMessages as Ja,isLossyBody as Za,readQueueMessageById as $a,readQueueMessages as et,recordQueueMessages as rt}from"./packem_shared/QUEUE_TABLE-DKANxmEZ.mjs";import{RANK_TIEBREAK as at,encodePartitionKey as tt,matchesRankStaticWhere as it,rankKeyFromDoc as nt,rankPivotConditionSql as st,rankTableName as lt,resolveRankPartition as dt,sortColumnName as ct}from"./packem_shared/RANK_TIEBREAK-DrISKVKe.mjs";import{ReactiveCache as pt,reactiveCacheKey as St}from"./packem_shared/ReactiveCache-Bdzsahf3.mjs";import{REACTOR_STATE_TABLE as ft,listReactorStates as xt,migrateReactorState as Et,reactorNeedsRun as ht,readReactorState as Tt,writeReactorState as Ct}from"./packem_shared/REACTOR_STATE_TABLE-B8IehLv8.mjs";import{UNVOUCHABLE_DEP as At,createReadFootprint as gt,markUnvouchableReads as _t}from"./packem_shared/UNVOUCHABLE_DEP-C68htACn.mjs";import{buildIndexRange as bt,indexKeysForRow as Lt,keysTouchRanges as Dt}from"./packem_shared/buildIndexRange-6nIZDf4m.mjs";import{isPushableWhere as Ot,whereFilter as Mt,whereOfFilter as Ft}from"./packem_shared/isPushableWhere-BeYAOjUb.mjs";import{RELATED_DEFAULT_LIMIT as Nt,RELATED_DEPTH_DECAY as kt,RELATED_MAX_DEPTH as Bt,RELATED_MAX_LIMIT as Ut,deriveRelationEdges as Gt,findRelated as qt}from"./packem_shared/RELATED_DEFAULT_LIMIT-e7viSuiO.mjs";import{DEFAULT_MAX_RELATION_KEYS as Kt,assertFlatPredicate as vt,assertShapeShardable as Wt,containsRelationPredicate as Xt,isRelationPredicate as Ht,resolveRelationPredicates as Vt}from"./packem_shared/DEFAULT_MAX_RELATION_KEYS-CQLms3UG.mjs";import{applyOnDelete as Qt,distinctValues as Yt,fanOutScalarCounts as jt,relationHooks as Jt,resolveWith as Zt,runRowValidators as $t}from"./packem_shared/applyOnDelete-8n5PzcI0.mjs";import{DEFAULT_PROMOTION_THRESHOLDS as ri,clampPromotionThresholds as oi,nextPromotionState as ai,relayCountFor as ti,shapeRoutingKey as ii}from"./packem_shared/DEFAULT_PROMOTION_THRESHOLDS-DEURXMvk.mjs";import{DEFAULT_MAX_RELAYS as si,OwnerRelay as li,RelayMember as di,createRelayLink as ci}from"./packem_shared/DEFAULT_MAX_RELAYS-BqSpObEl.mjs";import{createReplicaLink as pi,gateReplicaDispatch as Si,handleReplicaControl as ui}from"./packem_shared/createReplicaLink-CJn5lH0o.mjs";import{buildReprojectionMigration as xi,countLegacyRows as Ei,reprojectableFields as hi,reprojectionTables as Ti}from"./packem_shared/buildReprojectionMigration-BnUbAUwT.mjs";import{RLS_UNWRAP_SYMBOL as Ri,RlsRequiredError as Ai,guardWriter as gi}from"./packem_shared/RLS_UNWRAP_SYMBOL-DY6k6f6W.mjs";import{SCHEMA_HISTORY_MAX_VERSIONS as Ii,readSchemaHistory as bi,readSchemaVersion as Li,recordSchemaVersion as Di}from"./packem_shared/SCHEMA_HISTORY_MAX_VERSIONS-BMcUIqBY.mjs";import{serializeSqlValue as Oi}from"./packem_shared/serializeSqlValue-BbZ5hKM7.mjs";import{buildSettings as Fi,isDevEnvironment as yi,readDeployInfo as Ni}from"./packem_shared/buildSettings-BRkZd6_E.mjs";import{buildShapeDiff as Bi}from"./packem_shared/buildShapeDiff-AxUzi_GL.mjs";import{ShapeDiffCache as Gi,createShapeDiffCache as qi,globalShapeReadKey as wi}from"./packem_shared/ShapeDiffCache-Br3kxusw.mjs";import{buildPokeFrames as vi,diffGlobalMembership as Wi,encodeRowsPatch as Xi,projectColumns as Hi}from"./packem_shared/buildPokeFrames-CDOP-XYp.mjs";import{ShardRunner as zi}from"./packem_shared/ShardRunner-CrveaPId.mjs";import{stubByName as Yi}from"./packem_shared/stubByName-C_P73AOx.mjs";import{runSocketPool as Ji}from"./packem_shared/runSocketPool-CZJ2X9cF.mjs";import{MAX_SQL_ROWS as $i,assertReadonly as en,lintReadonlySql as rn,runReadonlySql as on}from"./packem_shared/MAX_SQL_ROWS-Dh_Ty0Zo.mjs";import{BIGINT_KEY_DIGITS as tn,bigintSqlKey as nn,decodeBigintSqlKey as sn,decodeFloat64SqlKey as ln,float64SqlKey as dn}from"./packem_shared/BIGINT_KEY_DIGITS-C9a7Ix7k.mjs";import{awaitWsDrain as mn,subscriptionFrames as pn,subscriptionListDeltas as Sn,trySendFrame as un}from"./packem_shared/awaitWsDrain-D4E7Oiwo.mjs";import{mergeChangedKeys as xn,recordChangedKeys as En,writeTouchesMemo as hn}from"./packem_shared/mergeChangedKeys-DH9RAARR.mjs";import{createSystemReader as Cn}from"./packem_shared/createSystemReader-DcDLFfC-.mjs";import{ConflictError as An}from"./packem_shared/ConflictError-C8GtJmjS.mjs";import{DEFAULT_TRANSACTION_LIMITS as _n,TransactionHeadroomTracker as In}from"./packem_shared/DEFAULT_TRANSACTION_LIMITS-DiR5z5EX.mjs";import{hasTrigger as Ln,runTriggers as Dn}from"./packem_shared/hasTrigger-CjlwI4le.mjs";import{selectExpiredIds as On}from"./packem_shared/selectExpiredIds-5bAT7X28.mjs";import{VECTOR_BACKFILL_MAX_PAGES as Fn,backfillVectorIndexes as yn}from"./packem_shared/VECTOR_BACKFILL_MAX_PAGES-CO1Ra57t.mjs";import{c as kn,s as Bn}from"./packem_shared/where-sql-DFs8Zw7-.mjs";import{RELATION_EXISTS_KEY as Gn}from"./packem_shared/RELATION_EXISTS_KEY-CFUhnZSZ.mjs";import{REPROJECTION_MIGRATION_PREFIX as wn,reprojectionMigrationId as Kn}from"./packem_shared/REPROJECTION_MIGRATION_PREFIX-Czcb6_mO.mjs";import{isInternalTableName as Wn}from"./packem_shared/isInternalTableName-BoljO2tP.mjs";import{quoteIdentifier as Hn}from"./packem_shared/quoteIdentifier-CObIFRhb.mjs";import{runShardMigrations as zn}from"./packem_shared/runShardMigrations-3BBkjGHs.mjs";import{stableStringify as Yn}from"./packem_shared/stableStringify-DibjylKD.mjs";import{stableWireKey as Jn}from"./packem_shared/stableWireKey-Bdh5JSdg.mjs";export{ia as ADMIN_FUNCTIONS,na as ADMIN_FUNCTION_PREFIX,d as AGGREGATE_SQL_FUNCTION,wr as AGG_COUNT,Kr as AGG_KEY,vr as AGG_VALUE,D as AUDIT_LOG_TABLE,tn as BIGINT_KEY_DIGITS,H as CDC_LOG_TABLE,V as CDC_LOG_TABLE_SEQ_INDEX,z as CDC_META_TABLE,Ce as CLIENT_WATERMARK_TABLE,Ie as COMMIT_SEQ_FIELD,be as COMMIT_SEQ_TABLE,Ga as CURSOR_PREFIX,An as ConflictError,R as CountRlsUnsupportedError,Dr as DATA_MIGRATION_STATE_TABLE,sa as DEFAULT_FANOUT_TOPIC_LIMIT,Kt as DEFAULT_MAX_RELATION_KEYS,si as DEFAULT_MAX_RELAYS,ri as DEFAULT_PROMOTION_THRESHOLDS,_n as DEFAULT_TRANSACTION_LIMITS,Wr as DOC_COLUMN,ho as DurableStreamRunner,la as FLAGS_FUNCTION_PREFIX,Yo as GEO_DEFAULT_PRECISION,ke as GLOBAL_SHAPE_SNAPSHOT_TABLE,aa as GlobalPollTick,ve as IDEMPOTENCY_TABLE,ba as MAIL_RETENTION,La as MAIL_TABLE,To as MAX_DURABLE_STREAM_BYTES,Co as MAX_DURABLE_STREAM_CHUNKS,da as MAX_PAGE_SIZE,$i as MAX_SQL_ROWS,ya as NotFoundError,y as NotUniqueError,li as OwnerRelay,ja as QUEUE_TABLE,at as RANK_TIEBREAK,ft as REACTOR_STATE_TABLE,Nt as RELATED_DEFAULT_LIMIT,kt as RELATED_DEPTH_DECAY,Bt as RELATED_MAX_DEPTH,Ut as RELATED_MAX_LIMIT,Gn as RELATION_EXISTS_KEY,ca as RELATION_FUNCTION_PREFIX,wn as REPROJECTION_MIGRATION_PREFIX,Ri as RLS_UNWRAP_SYMBOL,pt as ReactiveCache,di as RelayMember,Ai as RlsRequiredError,Fr as SCAN_DEP,rr as SCHEDULE_OUTBOX_TABLE,Ii as SCHEMA_HISTORY_MAX_VERSIONS,mr as SEARCH_STATE_TABLE,xr as SHAPE_POKE_CURSOR_TABLE,Gi as ShapeDiffCache,zi as ShardRunner,In as TransactionHeadroomTracker,At as UNVOUCHABLE_DEP,Fn as VECTOR_BACKFILL_MAX_PAGES,oo as WORKERD_SQLITE_LIMITS,Re as advanceClientWatermark,Xr as aggUpsertSql,c as aggregateSqlFunction,f as aggregateTableName,Le as allocateCommitSeq,P as appendAuditEntry,Q as appendCdcChange,lo as appendStreamChunk,Y as applyCdcChanges,Qt as applyOnDelete,qa as applySelect,ue as archiveCdcSegment,ka as armRestore,vt as assertFlatPredicate,N as assertNoExplicitUndefined,en as assertReadonly,Wt as assertShapeShardable,k as assertValidClientId,mn as awaitWsDrain,w as backfillAggregateIndexes,K as backfillRankIndexes,v as backfillSearchIndexes,W as backfillSearchIndexesForTable,yn as backfillVectorIndexes,nn as bigintSqlKey,jo as boundingBoxCenter,Jo as boundingBoxGeohashes,bt as buildIndexRange,vi as buildPokeFrames,xi as buildReprojectionMigration,wa as buildSeekBeforeWhere,Ka as buildSeekWhere,Fi as buildSettings,Bi as buildShapeDiff,j as bumpCdcEpoch,fe as cdcArchiveRewound,J as cdcCanVouchFor,Z as cdcForkedError,$ as cdcSeqLeavingRows,ee as cdcTouchesTables,re as cdcTrimmedError,co as claimStreamRun,oi as clampPromotionThresholds,Da as clearCapturedMail,Me as clearCompanionSignatures,Qe as clearMemoryTables,Ja as clearQueueMessages,x as coerceAggregateNumber,oe as compactCdcDocs,kn as compileWhereSql,Ze as computeRankPage,Xt as containsRelationPredicate,Ei as countLegacyRows,Zo as coveringGeohashes,ye as createCompanionSync,yr as createDependencyTracker,ma as createFanoutCounters,pa as createGlobalPollCounters,Hr as createIndexSql,gt as createReadFootprint,ci as createRelayLink,pi as createReplicaLink,qi as createShapeDiffCache,Sa as createShapeProbeCounters,B as createShardCtxDb,Cn as createSystemReader,ae as cursorBelowRetainedFloor,Ro as decideDurableAttach,sn as decodeBigintSqlKey,va as decodeCursor,ln as decodeFloat64SqlKey,or as deferScheduleOutbox,Be as deleteGlobalShapeSnapshot,Ue as deleteGlobalShapeSnapshotsForConnection,Er as deleteShapePokeCursor,hr as deleteShapePokeCursorsForConnection,mo as deleteStreamRun,Nr as depKey,Gt as deriveRelationEdges,bo as diffExternalSource,Wi as diffGlobalMembership,Yt as distinctValues,E as encodeAggregateKey,Wa as encodeCursor,$o as encodeGeohash,tt as encodePartitionKey,Xi as encodeRowsPatch,O as ensureAuditTable,Pa as ensureMailTable,go as envOptionalPositiveInt,_o as envPositiveInt,Xa as equalityPinnedFields,o as exportShardRows,ua as facetColumn,jt as fanOutScalarCounts,qt as findRelated,fa as findStorageReferences,po as finishStreamRun,dn as float64SqlKey,h as foldAggregateTally,ar as forgetScheduleOutbox,vo as ftsCompanionDdl,Wo as ftsPurgeDocument,Xo as ftsRowidMapName,Ho as ftsUnmappedPage,Vo as ftsWriteDocument,Si as gateReplicaDispatch,Vr as geoTableName,wi as globalShapeReadKey,zo as groupUnmappedRows,gi as guardWriter,ui as handleReplicaControl,Ln as hasTrigger,ea as haversineMeters,a as importShardRows,Lt as indexKeysForRow,yi as isDevEnvironment,zr as isFtsAvailable,Wn as isInternalTableName,Za as isLossyBody,Ye as isMemoryTable,Ot as isPushableWhere,Ht as isRelationPredicate,Uo as isSoftDeleted,Go as isSourceDue,xa as isVacuousFilterClause,Qr as jsonPath,Yr as jsonPathSql,Dt as keysTouchRanges,Do as liftSourceId,rn as lintReadonlySql,xt as listReactorStates,Ea as listTables,_t as markUnvouchableReads,it as matchesRankStaticWhere,m as matchesStaticWhere,Fo as materializeExternalRows,yo as materializeExternalRowsIncremental,je as memoryTableNames,xn as mergeChangedKeys,A as mergeWhere,te as migrateCdcLog,ie as migrateCdcMeta,Ae as migrateClientWatermark,De as migrateCommitSeq,So as migrateDurableStreams,Ge as migrateGlobalShapeSnapshot,We as migrateIdempotency,Et as migrateReactorState,tr as migrateScheduleOutbox,pr as migrateSearchState,Tr as migrateShapePokeCursor,ne as minCdcReplayableSeq,se as minCdcSeq,Cr as minShapePokeCursor,ai as nextPromotionState,p as normalizeCountArgument,U as normalizeIdStructurally,Ha as normalizeOrderKeys,Po as normalizeSourceDocument,Oo as normalizeSourceValue,ao as param,ir as parkScheduleOutbox,t as parseExportShardArgs,i as parseImportShardArgs,g as planAggregateLookup,ra as pointInBoundingBox,nr as probeScheduleOutbox,Hi as projectColumns,qo as pullExternalSourceIncrementalTick,wo as pullExternalSourceTick,jr as qualifiedJsonPath,Jr as qualifiedJsonPathSql,Hn as quoteIdentifier,nt as rankKeyFromDoc,st as rankPivotConditionSql,lt as rankTableName,St as reactiveCacheKey,ht as reactorNeedsRun,T as readAggregateValue,xe as readArchivedCdcChanges,M as readAuditLog,Ba as readBookmark,Oa as readCapturedMail,Ee as readCdcArchivedThrough,le as readCdcChangeKeys,de as readCdcChanges,ce as readCdcCursor,me as readCdcEpoch,ge as readClientWatermark,Pe as readCommitSeq,Ni as readDeployInfo,sr as readDueScheduleOutbox,No as readExternalSourceBaseline,qe as readGlobalShapeSnapshot,Xe as readIdempotent,Pr as readMigrationStatus,$a as readQueueMessageById,et as readQueueMessages,Tt as readReactorState,bi as readSchemaHistory,Li as readSchemaVersion,Sr as readSearchBackfillState,Rr as readShapePokeCursor,uo as readStreamChunks,fo as readStreamRun,ha as readTablePage,Ma as recordCapturedMail,En as recordChangedKeys,Ta as recordFanoutPass,Ca as recordGlobalPollPass,rt as recordQueueMessages,lr as recordScheduleOutbox,Di as recordSchemaVersion,Ra as recordShapeProbePass,Jt as relationHooks,ti as relayCountFor,to as renderSql,hi as reprojectableFields,Kn as reprojectionMigrationId,Ti as reprojectionTables,dt as resolveRankPartition,$e as resolveRankSeekTuple,Vt as resolveRelationPredicates,Zt as resolveWith,Zr as rowToDocument,Or as runDataMigration,Ur as runDrizzle,ko as runExternalSourceTick,on as runReadonlySql,$t as runRowValidators,zn as runShardMigrations,Ji as runSocketPool,Gr as runSql,Dn as runTriggers,On as selectExpiredIds,n as selectExportTables,_ as selectIndexForAggregate,I as selectIndexForCount,b as selectIndexForGroupBy,Aa as selectMatchingIds,Ir as selectShapeMembers,br as selectShapeRows,Oi as serializeSqlValue,Bn as serverInList,ii as shapeRoutingKey,Va as softDeleteScope,ct as sortColumnName,io as sqliteInList,Yn as stableStringify,Jn as stableWireKey,G as stripReservedPatchFields,Yi as stubByName,pn as subscriptionFrames,Sn as subscriptionListDeltas,ga as summarizeFanoutTopics,_a as summarizeSubscriptions,$r as tableColumns,kr as tableFromDepKey,S as throwingScheduler,za as tiebreakDirectionFor,pe as trimCdcChanges,He as trimIdempotent,dr as trimScheduleOutbox,xo as trimStreamRuns,eo as tryRowToDocument,un as trySendFrame,no as unionAll,Qa as uniqueIndexFields,s as validateImportRow,Mt as whereFilter,Ft as whereOfFilter,he as writeCdcArchivedThrough,we as writeGlobalShapeSnapshot,Ve as writeIdempotent,Ct as writeReactorState,ur as writeSearchBackfillState,Ar as writeShapePokeCursor,gr as writeShapePokeCursors,hn as writeTouchesMemo};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{LunoraError as S}from"@lunora/errors";import{sql as x}from"drizzle-orm";import{isInternalTableName as M}from"./isInternalTableName-BoljO2tP.mjs";import{m as A,n as j}from"./do-sql-CyWszGdM.mjs";import{quoteIdentifier as u}from"./quoteIdentifier-CObIFRhb.mjs";import{d as U}from"./wire-codec-BYCSiazv.mjs";import{renderSql as q,sqliteInList as B}from"./WORKERD_SQLITE_LIMITS-DBH23L_S.mjs";import{serializeSqlValue as k}from"./serializeSqlValue-BbZ5hKM7.mjs";import{decodeBigintSqlKey as Q}from"./BIGINT_KEY_DIGITS-C9a7Ix7k.mjs";const Te="__lunora_admin__:",Ae="__lunora_relation__:",Ie="__lunora_flags__:",Re={applyCdc:"__lunora_admin__:applyCdc",aiAvailable:"__lunora_admin__:aiAvailable",aiChartConfig:"__lunora_admin__:aiChartConfig",aiGenerateSql:"__lunora_admin__:aiGenerateSql",aiTableFilter:"__lunora_admin__:aiTableFilter",assignIssue:"__lunora_admin__:assignIssue",backfillSearch:"__lunora_admin__:backfillSearch",backfillVectors:"__lunora_admin__:backfillVectors",backRelationCounts:"__lunora_admin__:backRelationCounts",cdcSync:"__lunora_admin__:cdcSync",clearCapturedMail:"__lunora_admin__:clearCapturedMail",clearQueueMessages:"__lunora_admin__:clearQueueMessages",clearTable:"__lunora_admin__:clearTable",createWorkflowInstance:"__lunora_admin__:createWorkflowInstance",deleteRows:"__lunora_admin__:deleteRows",describeTable:"__lunora_admin__:describeTable",describeTables:"__lunora_admin__:describeTables",explainIssue:"__lunora_admin__:explainIssue",exportShard:"__lunora_admin__:exportShard",facetColumn:"__lunora_admin__:facetColumn",findRelated:"__lunora_admin__:findRelated",getAdvisories:"__lunora_admin__:getAdvisories",getAdvisorProcedures:"__lunora_admin__:getAdvisorProcedures",getAuditLog:"__lunora_admin__:getAuditLog",getAuthMetrics:"__lunora_admin__:getAuthMetrics",getCapturedMail:"__lunora_admin__:getCapturedMail",getFanoutMetrics:"__lunora_admin__:getFanoutMetrics",getFunctionStats:"__lunora_admin__:getFunctionStats",getIssues:"__lunora_admin__:getIssues",getMetricHistory:"__lunora_admin__:getMetricHistory",getMetricSeries:"__lunora_admin__:getMetricSeries",listSubscriptions:"__lunora_admin__:listSubscriptions",listTableIndexes:"__lunora_admin__:listTableIndexes",listTablesIndexes:"__lunora_admin__:listTablesIndexes",getLogs:"__lunora_admin__:getLogs",getMetrics:"__lunora_admin__:getMetrics",getPitrBookmark:"__lunora_admin__:getPitrBookmark",getQueryInsights:"__lunora_admin__:getQueryInsights",getQueueMessages:"__lunora_admin__:getQueueMessages",getRequestLog:"__lunora_admin__:getRequestLog",getSecurityAudit:"__lunora_admin__:getSecurityAudit",getSettings:"__lunora_admin__:getSettings",getTraces:"__lunora_admin__:getTraces",getWorkflowInstanceStatus:"__lunora_admin__:getWorkflowInstanceStatus",ignoreIssue:"__lunora_admin__:ignoreIssue",importShard:"__lunora_admin__:importShard",listFlags:"__lunora_admin__:listFlags",listReactors:"__lunora_admin__:listReactors",listQueues:"__lunora_admin__:listQueues",lintSql:"__lunora_admin__:lintSql",listTables:"__lunora_admin__:listTables",listWorkflows:"__lunora_admin__:listWorkflows",maskPolicies:"__lunora_admin__:maskPolicies",migrationStatus:"__lunora_admin__:migrationStatus",patchRows:"__lunora_admin__:patchRows",pitrRestore:"__lunora_admin__:pitrRestore",rankBefore:"__lunora_admin__:rankBefore",rankPage:"__lunora_admin__:rankPage",readTablePage:"__lunora_admin__:readTablePage",rebuildCompanions:"__lunora_admin__:rebuildCompanions",recordAuthEvent:"__lunora_admin__:recordAuthEvent",recordContainerEvent:"__lunora_admin__:recordContainerEvent",recordMail:"__lunora_admin__:recordMail",recordQueueMessage:"__lunora_admin__:recordQueueMessage",releaseShardRegistration:"__lunora_admin__:releaseShardRegistration",replayQueueMessage:"__lunora_admin__:replayQueueMessage",resolveIssue:"__lunora_admin__:resolveIssue",rlsPolicies:"__lunora_admin__:rlsPolicies",schemaHistory:"__lunora_admin__:schemaHistory",schemaVersion:"__lunora_admin__:schemaVersion",runAs:"__lunora_admin__:runAs",runMigration:"__lunora_admin__:runMigration",runSql:"__lunora_admin__:runSql",sendQueueMessage:"__lunora_admin__:sendQueueMessage",sendTestMail:"__lunora_admin__:sendTestMail",setIssueSeverity:"__lunora_admin__:setIssueSeverity",storageOrphans:"__lunora_admin__:storageOrphans",storageReferences:"__lunora_admin__:storageReferences",storageRules:"__lunora_admin__:storageRules",studioFeatures:"__lunora_admin__:studioFeatures",writeRow:"__lunora_admin__:writeRow"},W=50,b=500,H=30,G=200,d="__doc__",$=e=>{try{const t=JSON.parse(e);return t!==null&&typeof t=="object"&&!Array.isArray(t)?t:void 0}catch{return}},K=e=>{const{[A]:t,...n}=e;return t===void 0?n:t===null||typeof t!="object"||Array.isArray(t)?{[A]:t,...n}:{...n,...U(t)}},X=(e,t)=>{if(!e.includes(d))return{columns:e,rows:t};const n=[];for(const o of t){const a=o[d],_=typeof a=="string"?$(a):void 0;if(_===void 0)return{columns:e,rows:t};const c=Object.fromEntries(Object.entries(o).filter(([l])=>l!==d));n.push({...c,...K(_)})}const r=e.filter(o=>o!==d),s=[],i=new Set(r);for(const o of n)for(const a of Object.keys(o))i.has(a)||(i.add(a),s.push(a));return{columns:[...r,...s],rows:n}},I=e=>`instr(lower(CAST(${e} AS TEXT)), lower(?)) > 0`,C=(e,t,n)=>Math.min(Math.max(e,t),n),D=(e,t)=>{const n=e.exec(`SELECT COUNT(*) AS c FROM ${t}`).one();return Number(n.c)},ve=e=>{const t=e.exec("SELECT name FROM sqlite_master WHERE type = 'table' ORDER BY name").toArray(),n=[];for(const{name:r}of t)M(r)||n.push({name:r,rowCount:D(e,u(r))});return n},F=(e,t)=>e.exec("SELECT name FROM sqlite_master WHERE type = 'table' AND name = ? LIMIT 1",t).toArray().length>0,w=(e,t)=>{if(M(t)||!F(e,t))throw new S("UNKNOWN_TABLE",`unknown table: ${t}`,{status:404})},R=(e,t)=>e.exec(`PRAGMA table_info(${t})`).toArray().map(n=>n.name),V={eq:"=",gt:">",gte:">=",lt:"<",lte:"<=",ne:"<>"},L=e=>typeof e=="string"?e:typeof e=="number"||typeof e=="boolean"?String(e):"",Y=new Set(["gt","gte","lt","lte"]),J=e=>e.operator==="contains"?L(e.value)==="":Y.has(e.operator)&&e.value==="",E=(e,t)=>{const n=t.includes(e),r=t.includes(d);if(!(!n&&!r))return n?{expression:u(e),params:[]}:{expression:`json_extract(${u(d)}, ?)`,params:[`$.${j(e)}`]}},z=/^-?\d+$/u,Z=(e,t)=>{const{value:n}=e;if(t==="bigint"&&(typeof n=="number"||typeof n=="string")){const r=typeof n=="number"&&Number.isInteger(n)?BigInt(n).toString():String(n).trim();if(!z.test(r))throw new S("BAD_REQUEST",`bigint column ${e.column} can only be filtered by an integer, got ${JSON.stringify(n)}`);return k(BigInt(r))}if(t==="bigint"&&typeof n!="bigint")throw new S("BAD_REQUEST",`bigint column ${e.column} can only be filtered by an integer, got ${JSON.stringify(n)}`);return k(n)},ee=(e,t)=>t==="bigint"&&typeof e=="string"?Q(e)??e:e,te=(e,t,n)=>{const r=E(e.column,t);if(r===void 0||J(e))return;const{expression:s,params:i}=r,o=t.includes(e.column)?void 0:n?.[e.column];if(e.operator==="contains"){if(o==="bigint")throw new S("BAD_REQUEST",`"contains" is not supported on bigint column ${e.column} — use =, <, > instead`);return{params:[...i,L(e.value)],sql:I(s)}}return e.value===null&&(e.operator==="eq"||e.operator==="ne")?{params:i,sql:`${s} IS ${e.operator==="ne"?"NOT ":""}NULL`}:{params:[...i,Z(e,o)],sql:`${s} ${V[e.operator]} ?`}},ne=new Set(["date","timestamp"]),re=[`$.${A}`,`$."${A}"`].map(e=>`substr(j.fullkey, 1, ${String(e.length+1)}) NOT IN ('${e}.', '${e}[')`).join(" AND "),oe=e=>`(${I(e)} AND EXISTS (SELECT 1 FROM json_tree(${e}) AS j WHERE j.type IN ('text', 'integer', 'real', 'true', 'false') AND ${I("CASE WHEN j.type IN ('true', 'false') THEN j.type ELSE j.value END")} AND ${re}))`,se=/["\\\u0000-\u001F]/u,ae=e=>se.test(e)?"":e,ie=/^(\d{4})(?:-(\d{2}))?(?:-(\d{2}))?$/u,_e=e=>{const t=ie.exec(e.trim());if(t===null)return;const n=Number(t[1]),r=t[2]===void 0?void 0:Number(t[2]),s=t[3]===void 0?void 0:Number(t[3]);if(r!==void 0&&(r<1||r>12)||s!==void 0&&(s<1||s>31)||n<100)return;const i=Date.UTC(n,(r??1)-1,s??1);if(s!==void 0&&new Date(i).getUTCDate()!==s)return;let o;return s!==void 0?o=Date.UTC(n,(r??1)-1,s+1):r===void 0?o=Date.UTC(n+1,0,1):o=Date.UTC(n,r,1),{from:i,to:o}},y=(e,t,n,r)=>{const s=[],i=[];if(t!==""&&e.length>0){const o=e.map(_=>_===d?oe(u(_)):I(u(_)));i.push(...e.flatMap(_=>_===d?[ae(t),t]:[t]));const a=_e(t);if(a!==void 0){for(const c of e)o.push(`(${u(c)} >= ? AND ${u(c)} < ?)`),i.push(a.from,a.to);const _=Object.keys(r??{}).filter(c=>!e.includes(c)&&ne.has(r?.[c]??""));_.length>0&&e.includes(d)&&(o.push(`EXISTS (SELECT 1 FROM json_each(${u(d)}) AS j WHERE j.key IN (SELECT value FROM json_each(?)) AND j.type IN ('integer', 'real') AND j.value >= ? AND j.value < ?)`),i.push(JSON.stringify(_),a.from,a.to))}s.push(`(${o.join(" OR ")})`)}for(const o of n??[]){const a=te(o,e,r);a!==void 0&&(s.push(`(${a.sql})`),i.push(...a.params))}return s.length===0?void 0:{parameters:i,where:s.join(" AND ")}},ce=(e,t)=>{if(e===void 0)return;const n=E(e.column,t);if(n===void 0)return;const r=e.direction==="desc"?"DESC":"ASC";return{params:n.params,sql:`${n.expression} ${r}`}},Me=(e,t)=>{const{table:n}=t;w(e,n);const r=C(Math.trunc(t.limit??W),1,b),s=Math.max(0,Math.trunc(t.offset??0)),i=u(n),o=R(e,i),a=t.search?.trim()??"",_=T=>{if(t.refs===void 0)return T;const v={};for(const N of T.columns){const O=t.refs[N];O!==void 0&&(v[N]=O)}return Object.keys(v).length>0?{...T,refs:v}:T},c=y(o,a,t.filters,t.columnKinds),l=ce(t.orderBy,o),f=c===void 0?"":` WHERE ${c.where}`,g=l===void 0?"":` ORDER BY ${l.sql}`,p=c?.parameters??[],h=l?.params??[];let m;t.skipCount||(m=c===void 0?D(e,i):Number(e.exec(`SELECT COUNT(*) AS c FROM ${i}${f}`,...p).one().c));const P=e.exec(`SELECT * FROM ${i}${f}${g} LIMIT ? OFFSET ?`,...p,...h,r,s).toArray();return _({...X(o,P),sqlColumns:o,total:m})},Ce=(e,t)=>{const{table:n}=t;w(e,n);const r=C(Math.trunc(t.limit??b),1,b),s=u(n),i=R(e,s),o=t.search?.trim()??"";for(const m of t.filters??[])if(E(m.column,i)===void 0)throw new S("BAD_REQUEST",`unknown column: ${m.column}`);const a=y(i,o,t.filters,t.columnKinds);if(a===void 0&&(t.filters?.length??0)>0)throw new S("BAD_REQUEST",`the filters on ${n} are all empty, so the predicate constrains no rows — refusing to select the whole table`);const _=[],c=[];a!==void 0&&(_.push(a.where),c.push(...a.parameters)),t.after!==void 0&&(_.push("id > ?"),c.push(t.after));const l=_.length===0?"":` WHERE ${_.join(" AND ")}`,f=t.after===void 0?"":" ORDER BY id",g=e.exec(`SELECT id FROM ${s}${l}${f} LIMIT ?`,...c,r+1).toArray(),p=g.length>r,h=g.slice(0,r).map(m=>m.id);return{hasMore:p,ids:h}},le=(e,t,n,r)=>{const s=new Set(n.filter(o=>o!==d));if(!n.includes(d))return s;for(const o of Object.keys(r??{}))s.add(o);const i=e.exec(`SELECT ${u(d)} AS doc FROM ${t} LIMIT ?`,b).toArray();for(const{doc:o}of i){const a=typeof o=="string"?$(o):void 0;if(a!==void 0)for(const _ of Object.keys(a))s.add(_)}return s},we=(e,t)=>{const{column:n,table:r}=t;w(e,r);const s=u(r),i=R(e,s);if(!le(e,s,i,t.columnKinds).has(n))throw new S("UNKNOWN_COLUMN",`unknown column: ${n}`,{status:404});const o=E(n,i);if(o===void 0)throw new S("UNKNOWN_COLUMN",`unknown column: ${n}`,{status:404});const a=C(Math.trunc(t.limit??H),1,G),_=t.search?.trim()??"",c=y(i,_,t.filters,t.columnKinds),l=c===void 0?"":` WHERE ${c.where}`,f=c?.parameters??[],g=e.exec(`SELECT ${o.expression} AS value, COUNT(*) AS count FROM ${s}${l} GROUP BY ${o.expression} ORDER BY count DESC LIMIT ?`,...o.params,...f,...o.params,a+1).toArray(),p=g.length>a,h=i.includes(n)?void 0:t.columnKinds?.[n];return{truncated:p,values:g.slice(0,a).map(m=>({count:Number(m.count),value:ee(m.value,h)}))}},ye=(e,t,n)=>{const r={},s=n.slice(0,b);for(const i of s)r[i]=[];if(s.length===0)return{references:r,storageColumns:t};for(const[i,o]of Object.entries(t)){if(M(i)||!F(e,i))continue;const a=u(i),_=R(e,a);for(const c of o){const l=E(c,_);if(l===void 0)continue;const f=q("sqlite",B(x.raw(l.expression),s,!1)),g=e.exec(`SELECT id, ${l.expression} AS ref FROM ${a} WHERE ${f.sql}`,...l.params,...l.params,...f.params).toArray();for(const p of g)r[p.ref]?.push({column:c,id:p.id,table:i})}}return{references:r,storageColumns:t}},Ne=e=>{const t=e.map((r,s)=>{const i=Object.values(r.subs??{}).map(o=>({args:o.args,functionPath:o.functionPath,table:o.table}));return{admin:r.admin===!0,id:s,subscriptions:i}}),n=t.reduce((r,s)=>r+s.subscriptions.length,0);return{connections:t,totalConnections:t.length,totalSubscriptions:n}},ue=20,Oe=()=>({maxMs:0,passes:0,peakSocketsIterated:0,socketsDelivered:0,socketsIterated:0,totalMs:0}),ke=()=>({run:0,served:0}),$e=()=>({drains:0,pairsSkipped:0}),De=(e,t,n)=>({drains:e.drains+t,pairsSkipped:e.pairsSkipped+n}),Fe=(e,t,n)=>({run:e.run+t,served:e.served+n}),Le=(e,t,n,r)=>({maxMs:Math.max(e.maxMs,r),passes:e.passes+1,peakSocketsIterated:Math.max(e.peakSocketsIterated,t),socketsDelivered:e.socketsDelivered+n,socketsIterated:e.socketsIterated+t,totalMs:e.totalMs+r}),Pe=(e,t=ue)=>{const n=new Map,r=new Map;for(const o of e){for(const a of Object.values(o.shapes??{})){const _=a.name??"(unknown shape)";n.set(_,(n.get(_)??0)+1)}for(const a of o.whispers??[])r.set(a,(r.get(a)??0)+1)}const s=[...[...n].map(([o,a])=>({kind:"shape",subscribers:a,topic:o})),...[...r].map(([o,a])=>({kind:"whisper",subscribers:a,topic:o}))];return s.sort((o,a)=>a.subscribers-o.subscribers||o.topic.localeCompare(a.topic)),{peakSubscribers:s[0]?.subscribers??0,topics:s.slice(0,t),totalConnections:e.length}};export{Re as ADMIN_FUNCTIONS,Te as ADMIN_FUNCTION_PREFIX,ue as DEFAULT_FANOUT_TOPIC_LIMIT,Ie as FLAGS_FUNCTION_PREFIX,b as MAX_PAGE_SIZE,Ae as RELATION_FUNCTION_PREFIX,Oe as createFanoutCounters,$e as createGlobalPollCounters,ke as createShapeProbeCounters,_e as datePrefixRange,we as facetColumn,ye as findStorageReferences,M as isInternalTableName,J as isVacuousFilterClause,ve as listTables,Me as readTablePage,Le as recordFanoutPass,De as recordGlobalPollPass,Fe as recordShapeProbePass,Ce as selectMatchingIds,Pe as summarizeFanoutTopics,Ne as summarizeSubscriptions};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import"./effective-kind-BmG_zCAy.mjs";import{A as l,a as i,b as m,D as n,m as d,c,d as p,l as q,o as u,k as G,g as f,i as A,j as D,e as S,q as _,f as h,r as C,t as O,h as b}from"./do-sql-
|
|
1
|
+
import"./effective-kind-BmG_zCAy.mjs";import{A as l,a as i,b as m,D as n,m as d,c,d as p,l as q,o as u,k as G,g as f,i as A,j as D,e as S,q as _,f as h,r as C,t as O,h as b}from"./do-sql-CyWszGdM.mjs";import{quoteIdentifier as x}from"./quoteIdentifier-CObIFRhb.mjs";import"./wire-codec-BYCSiazv.mjs";import"./runDrizzle-Du5HLitO.mjs";import"./BIGINT_KEY_DIGITS-C9a7Ix7k.mjs";import{serializeSqlValue as J}from"./serializeSqlValue-BbZ5hKM7.mjs";export{l as AGG_COUNT,i as AGG_KEY,m as AGG_VALUE,n as DOC_COLUMN,d as DOC_ORIGINALS_KEY,c as aggUpsertSql,p as createIndexSql,q as decodeDocJson,u as decodeGroupKeyValue,G as encodeDocJson,f as geoTableName,A as isFtsAvailable,D as jsonPath,S as jsonPathSql,_ as qualifiedJsonPath,h as qualifiedJsonPathSql,x as quoteIdentifier,C as rowToDocument,J as serializeSqlValue,O as tableColumns,b as tryRowToDocument};
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{LunoraError as R}from"@lunora/errors";import{sql as t}from"drizzle-orm";import{quoteIdentifier as C}from"./quoteIdentifier-CObIFRhb.mjs";import{runSql as A,runDrizzle as n}from"./runDrizzle-Du5HLitO.mjs";import{k as m,l as u}from"./do-sql-
|
|
1
|
+
import{LunoraError as R}from"@lunora/errors";import{sql as t}from"drizzle-orm";import{quoteIdentifier as C}from"./quoteIdentifier-CObIFRhb.mjs";import{runSql as A,runDrizzle as n}from"./runDrizzle-Du5HLitO.mjs";import{k as m,l as u}from"./do-sql-CyWszGdM.mjs";import{ConflictError as I}from"./ConflictError-C8GtJmjS.mjs";const s="__cdc_log",p=`INSERT INTO ${C(s)} (ts, ${C("table")}, id, op, doc) VALUES (?, ?, ?, ?, ?)`,$="__cdc_log_table_seq",N="__cdc_log_table_id_seq",y=(e,o={})=>{n(e,t`CREATE TABLE IF NOT EXISTS ${t.identifier(s)} (
|
|
2
2
|
seq INTEGER PRIMARY KEY AUTOINCREMENT,
|
|
3
3
|
ts REAL NOT NULL,
|
|
4
4
|
${t.identifier("table")} TEXT NOT NULL,
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{LunoraError as p}from"@lunora/errors";import{d as y,e as _}from"./wire-codec-
|
|
1
|
+
import{LunoraError as p}from"@lunora/errors";import{d as y,e as _}from"./wire-codec-BYCSiazv.mjs";const N="id",h=e=>e.at(-1)?.direction==="desc"?"desc":"asc",m=new Set(["_id","id"]),O=new Set(["_creationTime","_id","id"]),E=(e,t)=>{if(O.has(e))return!1;const n=t?.[e];return n===void 0?!0:n.kind==="optional"||n._meta?.column?.notNull===!1},A=new Set(["AND","NOT","OR"]),C=e=>{const t=new Set;if(typeof e!="object"||Array.isArray(e))return t;for(const[n,o]of Object.entries(e)){if(A.has(n))continue;if(o===null||typeof o!="object"||Array.isArray(o)){t.add(n);continue}const r=Object.keys(o);r.length===1&&r[0]==="eq"&&t.add(n)}return t},j=(e,t)=>{const n=[];for(const o of e??[])o.unique===!0&&n.push(o.fields);for(const[o,r]of Object.entries(t??{}))r._meta?.column?.unique===!0&&n.push([o]);return n},g=(e,t)=>(t??[]).some(n=>n.length>0&&n.every(o=>e.has(o))),q=(e,t,n)=>{const o=[],r=new Set(n?.pinned);let s="asc";for(const i of e??[])for(const[l,c]of Object.entries(i))s=c,r.add(l),!n?.pinned?.has(l)&&o.push({direction:c,field:l,nullable:E(l,t)});return o.length===0?[{direction:s,field:"_creationTime",nullable:!1}]:(o.some(i=>m.has(i.field)||i.field==="_creationTime")||g(r,n?.uniqueBy)||o.push({direction:h(o),field:"_creationTime",nullable:!1}),o)},F=/[\u0080-\u{10FFFF}]/u,R=e=>{if(!F.test(e))return btoa(e);const t=new TextEncoder().encode(e);let n="";for(const o of t)n+=String.fromCodePoint(o);return btoa(n)},T=e=>{const t=atob(e),n=Uint8Array.from(t,o=>o.codePointAt(0)??0);return new TextDecoder().decode(n)},a="~4",L=(e,t)=>{const n=t.map(o=>e[o.field]??null);return n.push(e._id),a+R(JSON.stringify(_(n)))},u=()=>new p("BAD_REQUEST","invalid cursor"),k=e=>{if(!e.startsWith(a))throw u();let t;try{t=y(JSON.parse(T(e.slice(a.length))))}catch{throw u()}if(!Array.isArray(t))throw u();return t.map(n=>n??null)},b=(e,t,n,o)=>{const{field:r}=e,s=e.direction!=="desc"===n;if(t===null)return s?o?{OR:[{[r]:{isNull:!1}},{[r]:{isNull:!0}}]}:{[r]:{isNull:!1}}:o?{[r]:{isNull:!0}}:{OR:[]};let i=s?"gt":"lt";o&&(i=s?"gte":"lte");const l={[r]:{[i]:t}};return s||!e.nullable?l:{OR:[l,{[r]:{isNull:!0}}]}},S=(e,t,n,o)=>{const r=e.some(c=>m.has(c.field))?e:[...e,{direction:h(e),field:N,nullable:!1}];if(t.length<r.length)throw u();const s=c=>{const d=r[c];if(d===void 0)throw u();const f=b(d,t[c],n,o&&c===r.length-1);return c===r.length-1?f:{OR:[f,{AND:[{[d.field]:{eq:t[c]}},s(c+1)]}]}},i=s(0),[l]=r;return r.length<2||l===void 0||l.nullable||t[0]===null?i:{AND:[b(l,t[0],n,!0),i]}},v=(e,t)=>S(e,t,!0,!1),B=(e,t)=>S(e,t,!1,!0),D=["_id","_creationTime"],W=(e,t,n)=>{if(!t)return e;const o=new Set([...t,...D,...n?Object.keys(n):[]]);return e.map(r=>{const s={};for(const i of o)i in r&&(s[i]=r[i]);return s})},P=(e,t)=>e&&t!==!0?{[e.field]:{isNull:!0}}:void 0,U=(e,t)=>t===void 0||e[t]===null||e[t]===void 0;export{a as CURSOR_PREFIX,W as applySelect,B as buildSeekBeforeWhere,v as buildSeekWhere,k as decodeCursor,L as encodeCursor,C as equalityPinnedFields,T as fromBase64,U as isLiveForCompanion,q as normalizeOrderKeys,P as softDeleteScope,h as tiebreakDirectionFor,R as toBase64,j as uniqueIndexFields};
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{LunoraError as D}from"@lunora/errors";import{stableWireKey as S}from"./stableWireKey-
|
|
1
|
+
import{LunoraError as D}from"@lunora/errors";import{stableWireKey as S}from"./stableWireKey-Bdh5JSdg.mjs";import{runSql as E}from"./runDrizzle-Du5HLitO.mjs";import{encodeCursor as w,CURSOR_PREFIX as C}from"./CURSOR_PREFIX-C1jsjAPd.mjs";import{ConflictError as x}from"./ConflictError-C8GtJmjS.mjs";const i="__lunora_migrations",M=100,y=3e4,U=1e4,$=e=>{E(e,`CREATE TABLE IF NOT EXISTS "${i}" (
|
|
2
2
|
id TEXT PRIMARY KEY,
|
|
3
3
|
direction TEXT NOT NULL,
|
|
4
4
|
status TEXT NOT NULL,
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{LunoraError as u}from"@lunora/errors";import{i as v,R as N}from"./relation-operators-BEg-CvCH.mjs";import{isMemoryTable as y}from"./clearMemoryTables-CogAvVHR.mjs";import{distinctValues as $}from"./applyOnDelete-
|
|
1
|
+
import{LunoraError as u}from"@lunora/errors";import{i as v,R as N}from"./relation-operators-BEg-CvCH.mjs";import{isMemoryTable as y}from"./clearMemoryTables-CogAvVHR.mjs";import{distinctValues as $}from"./applyOnDelete-8n5PzcI0.mjs";import{RELATION_EXISTS_KEY as j}from"./RELATION_EXISTS_KEY-CFUhnZSZ.mjs";const E={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}},O=e=>N.has(e)?e:void 0,R=e=>{const t=O(e),r=t===void 0?void 0:E[t];if(!r)throw new u("INTERNAL",`unknown relation operator "${e}"`);return r},S=e=>e.kind==="one"?{clause:e.field,project:e.references}:{clause:e.references,project:e.field},M=5e3,h=Symbol("relation-key-overflow"),m=e=>Array.isArray(e)?e.map(t=>t??{}):[],w=e=>{if(e.length===1){const[t]=e;return t??{}}return e.length===0?{}:{AND:e}},b=e=>v(e),l=(e,t,r)=>{const n=t.tables[r]?.relationMap??{};return Object.keys(e).some(s=>{const a=e[s];return s==="AND"||s==="OR"?m(a).some(o=>l(o,t,r)):s==="NOT"?l(a??{},t,r):!!n[s]&&b(a)})},H=(e,t,r,n)=>{if(e&&l(e,t,r))throw new u("INTERNAL",`relation-crossing predicates are not supported in ${n}() — use them in findMany/findFirst or an RLS read policy`)},L=async(e,t,r,n,s)=>{const a=await d(t,e.table,n),{page:o}=await n.fetcher(e.table,{baseWhere:n.relationBaseWhere?.(e.table),relationBaseWhere:n.relationBaseWhere,where:a}),i=$(o,r);if(i.length>n.maxRelationKeys){if(s)return h;throw new u("INTERNAL",`relation predicate on "${e.table}" matched ${String(i.length)} rows, exceeding the ${String(n.maxRelationKeys)}-key limit; narrow the predicate (a same-shard EXISTS push-down lifts this cap)`)}return i},P=async(e,t,r,n,s)=>{const a=R(e),{clause:o,project:i}=S(t),c=await L(t,a.negateChild?{NOT:r}:r,i,n,s);return c===h?h:a.negated?a.nullDisjunct?{OR:[{[o]:{notIn:c}},{[o]:{isNull:!0}}]}:{[o]:{notIn:c}}:{[o]:{in:c}}},p=async(e,t,r,n,s)=>{const a=R(e),o=s.relationBaseWhere?.(t.table),i=a.negateChild?{NOT:r}:r,T={childWhere:await d(o?{AND:[o,i]}:i,t.table,s),negated:a.negated,parentTable:n,relation:t};return{[j]:T}},_=(e,t,r)=>{const n=O(e),s=n===void 0?void 0:E[n];if(s&&s.kind!==r.kind)throw new u("INTERNAL",`relation operator "${e}" requires a to-${s.kind} relation, but "${t}" is to-${r.kind}`)},k=async(e,t,r,n,s)=>{const a=[];for(const o of Object.keys(r)){_(o,e,t);const i=r[o]??{},c=s.canPushExists?.(t)??!1;if(c&&s.existsPushMode==="always"){a.push(await p(o,t,i,n,s));continue}const f=await P(o,t,i,s,c);f===h?a.push(await p(o,t,i,n,s)):a.push(f)}return w(a)},I=async(e,t,r,n)=>{if(e==="AND"||e==="OR"){const a=[];for(const o of m(t))a.push(await d(o,r,n));return{[e]:a}}if(e==="NOT")return{NOT:await d(t??{},r,n)};const s=n.schema.tables[r]?.relationMap?.[e];return s&&b(t)?k(e,s,t,r,n):{[e]:t}},d=async(e,t,r)=>{const n=[];for(const s of Object.keys(e))n.push(await I(s,e[s],t,r));return w(n)},Y=async(e,t)=>!e||!l(e,t.schema,t.tableName)?e:d(e,t.tableName,{canPushExists:t.canPushExists,existsPushMode:t.existsPushMode??"auto",fetcher:t.fetcher,maxRelationKeys:t.maxRelationKeys??M,relationBaseWhere:t.relationBaseWhere,schema:t.schema}),g=(e,t,r)=>{for(const n of e){const s=A(n,t,r);if(s)return s}},D=(e,t,r,n)=>{if(e==="AND"||e==="OR")return g(m(t),r,n);if(e==="NOT")return g([t??{}],r,n);const s=r.tables[n]?.relationMap?.[e];if(!(!s||!b(t)))return r.tables[s.table]?.shardMode?.kind==="shardBy"?{kind:"shard",relation:e,target:s.table}:y(r.tables[s.table])?{kind:"memory",relation:e,target:s.table}:g(Object.values(t),r,s.table)},A=(e,t,r)=>{for(const n of Object.keys(e)){const s=D(n,e[n],t,r);if(s)return s}},q=(e,t,r)=>{if(y(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=A(e,t,r);if(n)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{M as DEFAULT_MAX_RELATION_KEYS,H as assertFlatPredicate,q as assertShapeShardable,l as containsRelationPredicate,b as isRelationPredicate,Y as resolveRelationPredicates};
|
package/dist/packem_shared/{DEFAULT_MAX_RELAYS-B-yt9l6-.mjs → DEFAULT_MAX_RELAYS-BqSpObEl.mjs}
RENAMED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{toErrorBody as k,LunoraError as D}from"@lunora/errors";import{e as N,d as v}from"./wire-codec-
|
|
1
|
+
import{toErrorBody as k,LunoraError as D}from"@lunora/errors";import{e as N,d as v}from"./wire-codec-BYCSiazv.mjs";import{sql as y}from"drizzle-orm";import{runDrizzle as m}from"./runDrizzle-Du5HLitO.mjs";import{WORKERD_SQLITE_LIMITS as F}from"./WORKERD_SQLITE_LIMITS-DBH23L_S.mjs";import{d as U,w,a as A,m as $,r as K,b as Y,c as W}from"./ctx-db-relay-shapes-kGRKSxRs.mjs";import{envPositiveInt as g}from"./envOptionalPositiveInt-D2pY-c64.mjs";import{relayName as R,DEFAULT_PROMOTION_THRESHOLDS as T,nextPromotionState as B,shapeRoutingKey as _,relayProxyKey as M,parseRelayName as H,clampPromotionThresholds as q}from"./DEFAULT_PROMOTION_THRESHOLDS-DEURXMvk.mjs";import{encodeRowsPatch as X,buildPokeFrames as O}from"./buildPokeFrames-CDOP-XYp.mjs";import{verifySiblingBody as j,RELAY_SIGNATURE_HEADER as L,siblingStub as z,siblingSecretOf as G,signSiblingBody as J}from"./stubByName-C_P73AOx.mjs";import{awaitWsDrain as V,trySendFrame as x}from"./awaitWsDrain-D4E7Oiwo.mjs";import{stableWireKey as b}from"./stableWireKey-Bdh5JSdg.mjs";const f="__lunora_relay_memos",Q=i=>{m(i,y`CREATE TABLE IF NOT EXISTS ${y.identifier(f)} (
|
|
2
2
|
connection_id TEXT NOT NULL,
|
|
3
3
|
sub_id TEXT NOT NULL,
|
|
4
4
|
cursor INTEGER NOT NULL,
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{LunoraError as m}from"@lunora/errors";import{stableWireKey as a}from"./stableWireKey-
|
|
1
|
+
import{LunoraError as m}from"@lunora/errors";import{stableWireKey as a}from"./stableWireKey-Bdh5JSdg.mjs";const i="::relay::",w=(t,n)=>`${t}${i}${String(n)}`,f=t=>{const n=t.lastIndexOf(i);if(n===-1)return;const o=t.slice(0,n),e=t.slice(n+i.length),r=Number(e);if(!(o.length===0||!Number.isInteger(r)||r<0||String(r)!==e))return{ownerKey:o,relayIndex:r}},l=(t,n)=>a({args:n??{},name:t}),d=(t,n,o)=>`${String(t)}:${n}:${o}`,c={tDown:4e3,tUp:8e3},g=(t,n,o=c)=>{if(o.tDown>=o.tUp)throw new m("INTERNAL",`invalid promotion thresholds: tDown (${String(o.tDown)}) must be < tUp (${String(o.tUp)})`);return t==="owned"?n>=o.tUp?"promoted":"owned":n<o.tDown?"owned":"promoted"},x=(t,n)=>n<t?{tDown:n,tUp:t}:{tDown:Math.min(Math.max(1,Math.floor(t/2)),t-1),tUp:t},N=(t,n,o)=>{if(t<=n||n<=0)return 0;const e=t-n,r=Math.ceil(e/n);return Math.min(r,Math.max(0,o))};export{c as DEFAULT_PROMOTION_THRESHOLDS,x as clampPromotionThresholds,g as nextPromotionState,f as parseRelayName,N as relayCountFor,w as relayName,d as relayProxyKey,l as shapeRoutingKey};
|
package/dist/packem_shared/{DurableStreamRunner-Dk9Pn-B8.mjs → DurableStreamRunner-y2CRbfuZ.mjs}
RENAMED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{toErrorBody as R,LunoraError as k}from"@lunora/errors";import{e as A}from"./wire-codec-
|
|
1
|
+
import{toErrorBody as R,LunoraError as k}from"@lunora/errors";import{e as A}from"./wire-codec-BYCSiazv.mjs";import{readStreamRun as w,deleteStreamRun as T,claimStreamRun as _,appendStreamChunk as y,finishStreamRun as E,trimStreamRuns as b,readStreamChunks as v}from"./appendStreamChunk-7ZyAZGg_.mjs";const S=5e4,p=64*1024*1024,M=864e5,N=36e5,L=(i,e)=>{const r=i?.startedAt??e.live?.generation;return e.resuming&&e.generation!==void 0&&r!==void 0&&e.generation!==r?"interrupted":e.live!==void 0?"attach":i===void 0?e.resuming?"interrupted":"attach":i.status==="complete"||i.status==="error"?e.resuming?"replay-terminal":"reclaim":e.resuming?"interrupted":"reclaim"},O=(i,e,r)=>{(i||r())&&e.fail({code:"STREAM_INTERRUPTED",message:i?"the run this durable stream resumed from no longer exists; start a new run":"the producer for this durable stream did not survive; start a new run"})};class I{lastTrimAt=0;runs=new Map;sql;waitUntil;constructor(e){this.sql=e.sql,this.waitUntil=e.waitUntil}async attach(e){try{await this.attachOrThrow(e)}catch(r){const{body:t,redacted:o}=R(r,{fallbackCode:"INTERNAL_SERVER_ERROR",redactedMessage:"internal error"});o&&console.error("[@lunora/shard-engine] durable stream attach failed:",r),e.sink.fail({code:t.code,message:t.message})}finally{this.trim(this.sql())}}detach(e,r){this.runs.get(e)?.sinks.delete(r)}isLive(e){return this.runs.has(e)}async attachOrThrow(e){const r=this.sql(),{runKey:t,sinceChunk:o,sink:c}=e,s=w(r,t),u=o>0,n=this.runs.get(t),a=s?.startedAt??n?.generation,l=L(s,{generation:e.generation,live:n,resuming:u}),d=()=>{for(const g of v(r,t,o))if(!c.chunk({data:JSON.parse(g.dataJson),generation:a,seq:g.seq}))return!1;return!0};if(l==="replay-terminal"){d()&&(s?.status==="error"?c.fail({code:s.errorCode??"INTERNAL_SERVER_ERROR",message:s.error??"stream failed"}):c.complete());return}if(l==="interrupted"){O(e.generation!==void 0&&a!==void 0&&e.generation!==a,c,d);return}if(n){d()&&n.sinks.add(c);return}l==="reclaim"&&T(r,t);const m=Math.max(Date.now(),s===void 0?0:s.startedAt+1);_(r,t,m,e.ttlMs??M);const h={generation:m,sinks:new Set([c])};this.runs.set(t,h);const f=this.produce(t,e.iterator,h);this.waitUntil?.(f),await f}async produce(e,r,t){const o=this.sql(),c=new AbortController;let s=0,u=0;try{for await(const n of r(c.signal)){const a=A(n),l=JSON.stringify(a);if(s+=1,u+=l.length,s>S||u>p)throw new k("STREAM_TOO_LONG",`durable stream exceeded its ceiling (${String(S)} chunks / ${String(p)} bytes); yield less, or drop \`durable\``,{status:507});y(o,e,s,l);for(const d of t.sinks)d.chunk({data:a,generation:t.generation,seq:s})||t.sinks.delete(d)}E(o,e,"complete",s);for(const n of t.sinks)n.complete()}catch(n){const{body:a,redacted:l}=R(n,{fallbackCode:"INTERNAL_SERVER_ERROR",redactedMessage:"internal error"});l&&console.error("[@lunora/shard-engine] unhandled durable stream error:",n),E(o,e,"error",s,{code:a.code,message:a.message});for(const d of t.sinks)d.fail({code:a.code,message:a.message})}finally{this.runs.delete(e)}}trim(e){const r=Date.now();if(!(r-this.lastTrimAt<=N)){this.lastTrimAt=r;try{b(e,r,new Set(this.runs.keys()))}catch{}}}}export{I as DurableStreamRunner,p as MAX_DURABLE_STREAM_BYTES,S as MAX_DURABLE_STREAM_CHUNKS,L as decideDurableAttach};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{LunoraError as $}from"@lunora/errors";import{D as lt}from"./MAX_TOKEN_LENGTH-BakL9FUy-B3VwYY8C.mjs";import{S as yn,l as Le,h as $n}from"./fts-companion-pUdD6kF-.mjs";import{sql as c}from"drizzle-orm";import{d as mn}from"./wire-codec-BYCSiazv.mjs";import{stableWireKey as At}from"./stableWireKey-Bdh5JSdg.mjs";import{throwingScheduler as En,aggregateSqlFunction as qe,normalizeCountArgument as Sn}from"./AGGREGATE_SQL_FUNCTION-DDEoMnJR.mjs";import{aggregateTableName as Ye,encodeAggregateKey as Xe,readAggregateValue as Ze}from"./aggregateTableName-DbAttCNH.mjs";import{mergeWhere as N,CountRlsUnsupportedError as et,selectIndexForGroupBy as _n,selectIndexForCount as Rn,selectIndexForAggregate as Tn}from"./CountRlsUnsupportedError-BvsDqfO2.mjs";import{backfillSearchIndexesForTable as vn,searchIndexCoversTable as An}from"./backfillAggregateIndexes-B1yVAkvK.mjs";import{backfillAggregateIndexes as Uo,backfillRankIndexes as Oo,backfillSearchIndexes as Ho}from"./backfillAggregateIndexes-B1yVAkvK.mjs";import{appendCdcChange as In,readCdcDocAtOrBefore as Cn}from"./CDC_LOG_TABLE-GKlDpuM2.mjs";import{CDC_LOG_TABLE as No,applyCdcChanges as jo,bumpCdcEpoch as Ko,cdcCanVouchFor as Qo,cdcForkedError as Vo,cdcSeqLeavingRows as zo,cdcTouchesTables as Jo,cdcTrimmedError as Yo,compactCdcDocs as Xo,cursorBelowRetainedFloor as Zo,minCdcReplayableSeq as ei,minCdcSeq as ti,readCdcChangeKeys as ni,readCdcChanges as ri,readCdcCursor as oi,readCdcEpoch as ii,trimCdcChanges as si}from"./CDC_LOG_TABLE-GKlDpuM2.mjs";import{allocateCommitSeq as xn,COMMIT_SEQ_FIELD as bn}from"./COMMIT_SEQ_FIELD-BY_vc9bw.mjs";import{createCompanionSync as Mn}from"./createCompanionSync-hGCzG0O1.mjs";import{isMemoryTable as It}from"./clearMemoryTables-CogAvVHR.mjs";import{computeRankPage as Ct}from"./computeRankPage-BI2lNKPu.mjs";import{SCAN_DEP as H}from"./SCAN_DEP-D7qE3iUe.mjs";import{runSql as ve,runDrizzle as j}from"./runDrizzle-Du5HLitO.mjs";import{j as Oe,D as re,r as _e,k as le,b as We,A as tt,a as Be,e as ce,o as Dn,t as Yt,q as xt,i as kn,h as Xt,g as Fn}from"./do-sql-CyWszGdM.mjs";import{renderSql as Zt,unionAll as ut,WORKERD_SQLITE_LIMITS as en,sqliteInList as Ln}from"./WORKERD_SQLITE_LIMITS-DBH23L_S.mjs";import{coveringGeohashes as qn,boundingBoxGeohashes as Wn,haversineMeters as Bn,pointInBoundingBox as Pn}from"./GEO_DEFAULT_PRECISION-CqpQZ-J_.mjs";import{NotFoundError as Un}from"./NotFoundError-BhF7FeFr.mjs";import{tiebreakDirectionFor as On,encodeCursor as He,normalizeOrderKeys as st,uniqueIndexFields as tn,buildSeekWhere as nn,decodeCursor as ct,buildSeekBeforeWhere as Hn,softDeleteScope as fe,equalityPinnedFields as Gn,applySelect as bt}from"./CURSOR_PREFIX-C1jsjAPd.mjs";import{rankTableName as Mt,sortColumnName as Dt,resolveRankPartition as Nn,encodePartitionKey as jn,RANK_TIEBREAK as Kn,rankPivotConditionSql as Qn}from"./RANK_TIEBREAK-DrISKVKe.mjs";import{UNVOUCHABLE_DEP as kt}from"./UNVOUCHABLE_DEP-C68htACn.mjs";import{indexKeysForRow as Vn,buildIndexRange as zn}from"./buildIndexRange-6nIZDf4m.mjs";import{r as Ge,j as Re,c as te,t as Ne,i as Ft}from"./where-sql-DFs8Zw7-.mjs";import{serializeSqlValue as ae}from"./serializeSqlValue-BbZ5hKM7.mjs";import{quoteIdentifier as Ae}from"./quoteIdentifier-CObIFRhb.mjs";import{whereOfFilter as Jn,isPushableWhere as Yn}from"./isPushableWhere-BeYAOjUb.mjs";import{deriveRelationEdges as Xn,findRelated as Zn}from"./RELATED_DEFAULT_LIMIT-e7viSuiO.mjs";import{assertFlatPredicate as nt,resolveRelationPredicates as Lt}from"./DEFAULT_MAX_RELATION_KEYS-CQLms3UG.mjs";import{runRowValidators as rt,resolveWith as qt,relationHooks as Wt,applyOnDelete as er,fanOutScalarCounts as tr}from"./applyOnDelete-8n5PzcI0.mjs";import{guardWriter as nr}from"./RLS_UNWRAP_SYMBOL-DY6k6f6W.mjs";import{mayHoldProjectedValue as rr}from"./BIGINT_KEY_DIGITS-C9a7Ix7k.mjs";import{createSystemReader as or}from"./createSystemReader-DcDLFfC-.mjs";import{ConflictError as Te}from"./ConflictError-C8GtJmjS.mjs";import{runTriggers as ir}from"./hasTrigger-CjlwI4le.mjs";import{advanceClientWatermark as ai,migrateClientWatermark as di,readClientWatermark as li}from"./CLIENT_WATERMARK_TABLE-vLjfNhBR.mjs";import{IDEMPOTENCY_TABLE as fi,readIdempotent as hi,trimIdempotent as wi,writeIdempotent as gi}from"./IDEMPOTENCY_TABLE-AOJCuq5U.mjs";import{runShardMigrations as yi}from"./runShardMigrations-3BBkjGHs.mjs";import{selectShapeMembers as mi,selectShapeRows as Ei}from"./selectShapeMembers-CNpeUQ-H.mjs";const sr=n=>{const o=atob(n),r=Uint8Array.from(o,a=>a.codePointAt(0)??0);return new TextDecoder().decode(r)},cr=()=>new $("BAD_REQUEST","invalid cursor"),Bt=16,Pt=8,z=1024,ft=(n,o)=>o.query(n),ar=(n,o)=>{if(n.length===0)return 0;let r=0;for(const[a,i]of o.entries()){const w=a===o.length-1;let _=0;for(const E of n)(w?E.startsWith(i):E===i)&&(_+=1);if(_===0)return 0;r+=_}return r},dr=(n,o)=>{if(!o)return{exact:!0,lower:n,upper:n};const r=[...n].at(-1)??"",a=(r.codePointAt(0)??0)+1;if(a>=55296&&a<=57343||a>1114111)return{exact:!0,lower:n,upper:n};const i=n.slice(0,n.length-r.length);return{exact:!1,lower:n,upper:i+String.fromCodePoint(a)}},lr=(n,o,r)=>{const a={eq:(i,w)=>{if(!n.definition.filterFields?.includes(i))throw new $("INTERNAL",`field "${i}" is not a filter field of search index "${n.indexName}" on table "${o}"`);if(n.filters.length>=Pt)throw new $("BAD_REQUEST",`search index "${n.indexName}" on table "${o}": at most ${String(Pt)} .eq() filters are supported per search query`);return n.filters.push({field:i,value:w}),a},search:(i,w)=>{const _=n;if(i!==_.definition.field)throw new $("INTERNAL",`search index "${_.indexName}" on table "${o}" indexes "${_.definition.field}", not "${i}"`);const E=ft(w,r).length;if(E>Bt)throw new $("BAD_REQUEST",`search index "${_.indexName}" on table "${o}": at most ${String(Bt)} search terms are supported (got ${String(E)})`);return _.field=i,_.query=w,_.hasQuery=!0,a}};return a},ur=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()`)},fr=n=>Math.min(n.offset+n.numItems+1,z),hr=n=>btoa(`search:${String(n)}`),wr=n=>{let o;try{o=sr(n)}catch{return}if(!o.startsWith("search:"))return;const r=Number(o.slice(7));return Number.isInteger(r)&&r>=0?r:void 0},gr=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 o=Math.max(0,Math.floor(n.numItems)),r=n.cursor?wr(n.cursor):0;if(r===void 0)throw cr();if(r+o>=z)throw new $("BAD_REQUEST",`search pagination reaches the ${String(z)}-document limit (offset ${String(r)} + ${String(o)} 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-r-1))} or fewer, or narrow the query or the filters instead`);return{numItems:o,offset:r}},pr=(n,o)=>{const r=o.offset+o.numItems,a=o.numItems>0&&n.length>r;return{continueCursor:a?hr(r):null,isDone:!a,page:n.slice(o.offset,r)}},yr=n=>{if(n===void 0)return z+1;if(!Number.isFinite(n))return z;const o=Math.max(0,Math.floor(n));if(o>z)throw new $("BAD_REQUEST",`search returns at most ${String(z)} documents (asked for ${String(o)}) — narrow the query or paginate instead`);return o},$r=32,mr=1024,rn=(n,o,r,a)=>{const i=`SELECT id, _creationTime, ${Ae(re)} FROM ${Ae(n)}`,w=`ORDER BY ${r}${a===void 0?"":` LIMIT ${String(a)}`}`;return o===void 0?Ge(`${i} ${w}`):Re(`${i} WHERE `,o,` ${w}`)},ht={fieldRef:n=>Ge(Oe(n)),serialize:ae},on=n=>{const o=n.map(r=>`${Oe(r.field)} ${r.direction==="desc"?"DESC":"ASC"}`);return n.some(r=>r.field==="_id"||r.field==="id")||o.push(`${Oe("id")} ${On(n)==="desc"?"DESC":"ASC"}`),o.join(", ")},Er={"<":"lt","<=":"lte","=":"eq",">":"gt",">=":"gte"},sn=n=>new Set(n.sqlConditions.filter(o=>o.comparator==="=").map(o=>o.field)),Sr=n=>{const o=sn(n);let r=0;for(;r<n.indexFields.length&&o.has(n.indexFields[r]??"");)r+=1;return n.indexFields.slice(r)},_r=(n,o)=>{const r=n.order,a=Sr(n),{shape:i}=o;return a.length>0?st(a.map(w=>({[w]:r})),i,{pinned:sn(n),uniqueBy:tn(o.indexes,i)}):st([{_creationTime:r}],i)},Rr=(n,o,r,a)=>{const i=n.sqlConditions.map(w=>({[w.field]:{[Er[w.comparator]??"eq"]:w.value}}));if(r&&i.push(nn(o,ct(r))),a&&i.push(Hn(o,ct(a))),i.length!==0)return i.length===1?i[0]:{AND:i}},Tr=n=>{if(n.want!==void 0)return n.selective?Math.max(n.want,$r):n.want},at=(n,o,r,a,i,w,_)=>{const E=_r(a,r),x=on(E),p=[],{filters:b,want:A}=w;let R=w.cursor??void 0,D=Tr(w);if(A===0)return{documents:p,orderKeys:E};for(;;){const W=te(Rr(a,E,R,w.endCursor),ht,Ne),B=rn(o,i&&W?Re(W," AND ",i):i??W,x,D),L=ve(n,B.text,...B.params).toArray();let P={};_(L.length);for(const C of L)if(P=_e(C),b.every(ne=>ne(P))&&p.push(P)===A)return{documents:p,orderKeys:E};if(D===void 0||L.length<D)return{documents:p,orderKeys:E};R=He(P,E),D=Math.max(D,Math.min(D*2,mr))}},vr=(n,o,r,a,i,w,_,E)=>{const x=Math.max(0,Math.floor(i.numItems));if(typeof i.endCursor=="string"){const{documents:W,orderKeys:B}=at(n,o,r,a,w,{cursor:i.cursor,endCursor:i.endCursor,filters:_.all,selective:_.selective,want:void 0},E),L=W.length>=2?W[Math.floor(W.length/2)-1]:void 0;return{continueCursor:i.endCursor,isDone:!0,page:W,splitCursor:L?He(L,B):null}}const{documents:p,orderKeys:b}=at(n,o,r,a,w,{cursor:i.cursor,filters:_.all,selective:_.selective,want:x+1},E),A=p.length>x,R=A?p.slice(0,x):p,D=R.at(-1);return{continueCursor:A&&D?He(D,b):null,isDone:!A,page:R}},je=n=>{const o=new Map;return r=>{const a=o.get(r);if(a!==void 0)return a;const i=n(Ae(r));return o.set(r,i),i}},he=Ae(re),Ar=je(n=>`INSERT INTO ${n} (id, _creationTime, ${he}) VALUES (?, ?, ?)`),Ut=je(n=>`UPDATE ${n} SET ${he} = ? WHERE id = ? AND ${he} = ?`),Ir=je(n=>`UPDATE ${n} SET _creationTime = ?, ${he} = ? WHERE id = ? AND ${he} = ?`),Cr=je(n=>`DELETE FROM ${n} WHERE id = ? AND ${he} = ?`),xr="SELECT changes() AS changed",Ot=new Map,br="",Mr=n=>{const o=JSON.stringify(n),r=Ot.get(o);if(r!==void 0)return r;const a=n.map(w=>c`SELECT ${c.raw(`'${w.replaceAll("'","''")}'`)} AS __t__, id, _creationTime, ${c.identifier(re)} FROM ${c.identifier(w)} WHERE id = ${br}`),{sql:i}=Zt("sqlite",c`${ut(a)} LIMIT 1`);return Ot.set(o,i),i},Dr=(n,o)=>o.map(()=>n),kr=/^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/iu,Fr=n=>{if(!kr.test(n))throw new $("INTERNAL",`invalid clientId ${JSON.stringify(n)}: a client-supplied row id must be a UUID`)},Ht=50,cn=500,Pe=Math.floor(en.boundParams/3),Ee=en.boundParams,Lr=128,ue=(n,o,r)=>{const a=o??cn;if(n>a)throw new $("BATCH_LIMIT_EXCEEDED",`${r}: batch of ${String(n)} exceeds the limit of ${String(a)} (raise options.limit or chunk the call)`,{status:400})},qr=n=>{const o={eq:(r,a)=>(n.sqlConditions.push({comparator:"=",field:r,value:a}),o),gt:(r,a)=>(n.sqlConditions.push({comparator:">",field:r,value:a}),o),gte:(r,a)=>(n.sqlConditions.push({comparator:">=",field:r,value:a}),o),lt:(r,a)=>(n.sqlConditions.push({comparator:"<",field:r,value:a}),o),lte:(r,a)=>(n.sqlConditions.push({comparator:"<=",field:r,value:a}),o)};return o},Wr=n=>Math.max(n,z),an=(n,o)=>{const r=n.filters.map(a=>c`${ce(a.field)} = ${ae(a.value)}`);return o&&r.push(o),r},Br=(n,o,r,a,i)=>{const w=ft(r.query,lt(r.definition.language));if(w.length===0)return[];const _=yn(o,r.indexName),E=`${_}__vocab`,x=w.length-1,p=w.map((B,L)=>{const P=dr(B,L===x),C=P.exact?c`${c.identifier("term")} = ${P.lower}`:c`${c.identifier("term")} >= ${P.lower} AND ${c.identifier("term")} < ${P.upper}`;return c`SELECT ${c.identifier("doc")}, ${c.raw(String(L))} AS ${c.identifier("__term__")}, COUNT(*) AS ${c.identifier("__n__")} FROM ${c.identifier(E)} WHERE ${C} GROUP BY ${c.identifier("doc")}`}),b=w.map((B,L)=>c`SUM(CASE WHEN u.${c.identifier("__term__")} = ${c.raw(String(L))} THEN u.${c.identifier("__n__")} ELSE 0 END)`),A=c`SELECT f.${c.identifier(Le)} AS ${c.identifier(Le)}, ${c.join(b,c` + `)} AS ${c.identifier("__score__")} FROM (${ut(p)}) u JOIN ${c.identifier(_)} f ON f.rowid = u.${c.identifier("doc")} GROUP BY f.${c.identifier(Le)} HAVING ${c.join(b.map(B=>c`${B} > 0`),c` AND `)}`,R=an(r,i);let D=c`SELECT m.id, m._creationTime, m.${c.identifier(re)}, s.${c.identifier("__score__")} AS ${c.identifier("__score__")} FROM (${A}) s JOIN ${c.identifier(o)} m ON m.id = s.${c.identifier(Le)}`;R.length>0&&(D=c`${D} WHERE ${c.join(R,c` AND `)}`),D=c`${D} ORDER BY s.${c.identifier("__score__")} DESC, m._creationTime DESC, m.id ASC LIMIT ${c.raw(String(a))}`;const W=[];for(const B of j(n,D)){const L=Xt(B);if(L){const P=B.__score__;W.push({document:L,score:typeof P=="number"?P:Number(P??0)})}}return W},Pr=(n,o,r,a,i)=>{const w=lt(r.definition.language),_=ft(r.query,w);if(_.length===0)return[];const E=an(r,i);let x=c`SELECT id, _creationTime, ${c.identifier(re)} FROM ${c.identifier(o)}`;E.length>0&&(x=c`${x} WHERE ${c.join(E,c` AND `)}`),x=c`${x} ORDER BY _creationTime DESC, id ASC LIMIT ${c.raw(String(Wr(a)))}`;const p=j(n,x).toArray(),b=[];for(const A of p){const R=Xt(A);if(!R)continue;const D=ar($n(R,r.definition),_);D>0&&b.push({creationTime:typeof R._creationTime=="number"?R._creationTime:0,doc:R,id:typeof R._id=="string"?R._id:"",score:D})}return b.sort((A,R)=>R.score-A.score||R.creationTime-A.creationTime||A.id.localeCompare(R.id)),b.slice(0,a).map(A=>({document:A.doc,score:A.score}))},ot=(n,o,r,a)=>{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 "${a}" on table "${r}": ${o} must have a finite lat in [-90, 90] and lng in [-180, 180]`)},Ur=(n,o)=>{const r=n,a={near:(i,w)=>{if(r.within)throw new $("INTERNAL",`geo index "${r.indexName}" on table "${o}": call .near() or .within(), not both`);if(ot(i,".near() point",o,r.indexName),!Number.isFinite(w)||w<=0)throw new $("BAD_REQUEST",`geo index "${r.indexName}" on table "${o}": .near() radiusMeters must be a finite number > 0, got ${String(w)}`);return r.near={point:{lat:i.lat,lng:i.lng},radiusMeters:w},a},within:i=>{if(r.near)throw new $("INTERNAL",`geo index "${r.indexName}" on table "${o}": call .near() or .within(), not both`);if(ot(i.sw,".within() sw corner",o,r.indexName),ot(i.ne,".within() ne corner",o,r.indexName),i.sw.lat>i.ne.lat)throw new $("BAD_REQUEST",`geo index "${r.indexName}" on table "${o}": .within() corners are transposed (sw.lat > ne.lat)`);if(i.sw.lng>i.ne.lng)throw new $("BAD_REQUEST",`geo index "${r.indexName}" on table "${o}": .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 r.within={ne:{lat:i.ne.lat,lng:i.ne.lng},sw:{lat:i.sw.lat,lng:i.sw.lng}},a}};return a},Or=(n,o)=>{const r=n[o];if(r===null||typeof r!="object")return;const{lat:a,lng:i}=r;return typeof a=="number"&&typeof i=="number"?{lat:a,lng:i}:void 0},Hr=(n,o)=>{const r=Or(n,o.definition.field);if(!r)return;const a=typeof n._creationTime=="number"?n._creationTime:0;if(o.near){const i=Bn(o.near.point,r);return i<=o.near.radiusMeters?{creationTime:a,distance:i}:void 0}return Pn(r,o.within)?{creationTime:a,distance:0}:void 0},Gr=(n,o,r,a)=>{if(!r.near&&!r.within)throw new $("INTERNAL",`geo index "${r.indexName}" on table "${o}": call .near(point, radius) or .within(box)`);const i=r.near?qn(r.near.point,r.near.radiusMeters):Wn(r.within),w=Fn(o,r.indexName),_=i.map(A=>c`(g.${c.identifier("__geohash__")} >= ${A} AND g.${c.identifier("__geohash__")} < ${`${A}{`})`),E=[c`(${c.join(_,c` OR `)})`];a&&E.push(a);const x=c`SELECT m.id, m._creationTime, m.${c.identifier(re)} FROM ${c.identifier(w)} g JOIN ${c.identifier(o)} m ON m.id = g.${c.identifier("__id__")} WHERE ${c.join(E,c` AND `)}`,p=j(n,x).toArray(),b=[];for(const A of p){const R=_e(A),D=R?Hr(R,r):void 0;R&&D&&b.push({creationTime:D.creationTime,distance:D.distance,doc:R})}return b.sort((A,R)=>A.distance-R.distance||R.creationTime-A.creationTime),b},dn=(n,o,r,a)=>{const i=[];for(const w of n)if(o.every(_=>_(a(w)))&&(i.push(w),typeof r=="number"&&i.length>=r))break;return i},Nr=(n,o,r,a,i,w=()=>{})=>{const _=r.within!==void 0,E=Gr(n,o,r,i).map(x=>({distanceMeters:_?null:x.distance,document:x.doc}));return w(E.length),typeof a=="number"?E.slice(0,Math.max(0,Math.floor(a))):E},Gt=(n,o,r,a,i,w,_=()=>{})=>{const{geo:E}=r;if(!E)throw new $("INTERNAL","runGeoTerminalScored called without a staged geo query");const x=i.length>0,p=Nr(n,o,E,x?void 0:w,a,_);return x?dn(p,i,w,b=>b.document):p},Se={fieldRef:ce,serialize:ae},Nt=(n,o,r)=>{const a=n.shape[o];if(a!==void 0&&rr(a))throw new $("BAD_REQUEST",`${r}: "${o}" 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)`)},jr=n=>{let o=0;const r=[],a={fieldRef:i=>Ge(Oe(i)),relationExists:i=>{const{childWhere:w,negated:_,parentTable:E,relation:x}=i,p=`__rel_${String(o)}`,b=r.at(-1)??E;o+=1,n(x.table,H);const A=x.kind==="one"?x.field:x.references,R=x.kind==="one"?x.references:x.field,D=Ge(`${xt(p,R)} = ${xt(b,A)}`);r.push(p);const W=te(w,a,Ne);r.pop();const B=W===void 0?D:Re(D," AND ",W),L=Re("EXISTS (SELECT 1 FROM ",Ft(x.table)," AS ",Ft(p)," WHERE ",B,")");return _?Re("NOT ",L):L},serialize:ae};return a};class Kr extends ${constructor(o="unique() found more than one matching document"){super("NOT_UNIQUE",o,{name:"NotUniqueError"})}}const Qr=/\s/u,Vr=String.fromCodePoint(0),jt=(n,o,r)=>{if(!n.tables[o])throw new $("INTERNAL",`unknown table: ${o}`);return typeof r!="string"||r.length===0||Qr.test(r)||r.includes(Vr)?null:r},ln=(n,o,r,a=()=>{},i=()=>{},w=()=>{},_)=>{const E=o.tables[r];if(!E)throw new $("INTERNAL",`unknown table: ${r}`);const x=fe(E.softDeleteMode,void 0),p=_??{indexFields:[],indexName:void 0,inMemoryFilters:[],order:"asc",sqlConditions:[],verifyFilters:[]},b=()=>{const y=N(x,p.pushedWhere);return y?te(y,Se):void 0},A=()=>{const y=N(x,p.pushedWhere);return y?te(y,ht,Ne):void 0},R=()=>[...p.inMemoryFilters,...p.verifyFilters];let D=0;const W=y=>{const{search:I}=p;if(!I)throw new $("INTERNAL","runSearchFetch called without a staged search");vn(n,r,E);const k=p.inMemoryFilters.length>0,F=yr(k?void 0:y),X=kn(n);if(X&&!An(n,r,I.definition))throw new $("SEARCH_INDEX_BUILDING",`search index "${I.indexName}" on table "${r}" 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 we=b(),J=X?Br(n,r,I,F,we):Pr(n,r,I,F,we);!k&&y===void 0&&ur(J);const oe=R();return D=J.length,oe.length>0?dn(J,oe,y,Ie=>Ie.document):J},B=y=>W(y).map(I=>I.document),L=y=>{const I=gr(y);return pr(B(fr(I)),I)},P=()=>{if(p.search||p.geo||p.indexName===void 0){i(void 0);return}i(zn(r,p.indexName,p.indexFields,p.sqlConditions,ae))},C=y=>{P();let I=0;const k=(()=>{if(p.search){const F=B(y);return I=D,F}return p.geo?Gt(n,r,p,b(),R(),y,F=>{I=F}).map(F=>F.document):at(n,r,E,p,A(),{filters:R(),selective:p.inMemoryFilters.length>0,want:y===void 0?void 0:Math.max(0,Math.floor(y))},F=>{I+=F}).documents})();return w(Math.max(I,k.length)),k},ne=()=>{if(!p.search&&!p.geo)throw new $("INTERNAL",`ctx.db.query("${r}").collectWithScores() requires a staged .withSearchIndex(...) or .withGeoIndex(...)`);P();let y=0;const I=(()=>{if(p.search){const k=W(void 0);return y=D,k}return Gt(n,r,p,b(),R(),void 0,k=>{y=k})})();return w(Math.max(y,I.length)),I},Y={async*[Symbol.asyncIterator](){const y=ln(n,o,r,a,i,w,{...p,indexFields:[...p.indexFields],inMemoryFilters:[...p.inMemoryFilters],sqlConditions:[...p.sqlConditions],verifyFilters:[...p.verifyFilters]});if(p.search){yield*await y.collect();return}let I;for(;;){const k=await y.paginate({cursor:I??null,numItems:Lr});if(yield*k.page,k.isDone||k.continueCursor===null)return;I=k.continueCursor}},async collect(){return C(void 0)},async collectWithScores(){return ne()},filter(y){const I=Jn(y);return I!==void 0&&Yn(I,E.shape)?(p.pushedWhere=N(p.pushedWhere,I),p.verifyFilters.push(y)):p.inMemoryFilters.push(y),Y},async first(){return C(1)[0]??null},order(y){return p.order=y==="desc"?"desc":"asc",Y},async paginate(y){let I=0;if(P(),p.search){const F=L(y);return w(F.page.length),F}if(p.geo)throw new $("INTERNAL","pagination is not supported on geo queries; use .take(n) or .collect()");const k=vr(n,r,E,p,y,A(),{all:R(),selective:p.inMemoryFilters.length>0},F=>{I+=F});return w(Math.max(I,k.page.length)),k},async take(y){return C(y)},async unique(){const y=C(2);if(y.length>1)throw new Kr(`unique() on table "${r}" matched ${String(y.length)} documents; expected at most one`);return y[0]??null},withGeoIndex(y,I){const k=(E.geoIndexes??[]).find(X=>X.name===y);if(!k)throw new $("INTERNAL",`unknown geo index "${y}" on table "${r}"`);a(r,y,"geo");const F={definition:k,indexName:y};if(p.geo=F,I(Ur(F,r)),!F.near&&!F.within)throw new $("INTERNAL",`geo index "${y}" on table "${r}" requires a .near(point, radius) or .within(box) call`);return Y},withIndex(y,I){const k=E.indexes.find(F=>F.name===y);if(!k)throw new $("INTERNAL",`unknown index "${y}" on table "${r}"`);return a(r,y,"index"),p.indexName=y,p.indexFields=k.fields,I&&I(qr(p)),Y},withSearchIndex(y,I){const k=(E.searchIndexes??[]).find(X=>X.name===y);if(!k)throw new $("INTERNAL",`unknown search index "${y}" on table "${r}"`);a(r,y,"search");const F={definition:k,field:k.field,filters:[],hasQuery:!1,indexName:y,query:""};if(p.search=F,I(lr(F,r,lt(k.language))),!F.hasQuery)throw new $("INTERNAL",`search index "${y}" on table "${r}" requires a .search(field, query) call`);return Y}};return Y},Kt=(n,o,r)=>{const a={...o};for(const[i,w]of Yt(n)){if(w.serverDefault){a[i]=w.serverDefault({auth:r});continue}a[i]===void 0&&(w.defaultFn?a[i]=w.defaultFn():"defaultValue"in w&&(a[i]=w.defaultValue))}return a},Qt=(n,o,r,a)=>{const i=r;for(const[w,_]of Yt(n)){if(_.serverDefault){w in o&&(i[w]=_.serverDefault({auth:a}));continue}_.onUpdateFn&&!(w in o)&&(i[w]=_.onUpdateFn())}},Vt=(n,o)=>{for(const r of Object.keys(o))if(o[r]===void 0)throw new $("INTERNAL",`Cannot ${n} field '${r}' to undefined — use null to clear a nullable field, or omit the key to leave it unchanged.`)},zt=["_commitSeq","_creationTime","_id"],it=n=>zt.some(o=>o in n)?Object.fromEntries(Object.entries(n).filter(([o])=>!zt.includes(o))):n,zr=/unique constraint failed/i,Jr=n=>n instanceof Error&&zr.test(n.message),Yr=/string or blob too big/iu,Xr=(n,o)=>{if(!(!(n instanceof Error)||!Yr.test(n.message)))throw new $("PAYLOAD_TOO_LARGE",`document is too large to store in "${o}": 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.`)},dt=(n,o,r,a)=>{try{ve(n,r,...a)}catch(i){throw Jr(i)?new Te(`unique constraint violation on "${o}"`,"unique"):(Xr(i,o),i)}},Ue=(n,o,r,a)=>{if(dt(n,o,r,a),ve(n,xr).one().changed===0)throw new Te(`optimistic concurrency conflict on "${o}" — the row changed during this mutation; refetch and retry`,"occ")},Jt=(n,o,r,a,i,w,_)=>{const E=[];for(let A=0;A<r.length+1;A+=1){const R=r[A],D=a[A],W=D?.direction==="desc"?"desc":"asc",B=R===void 0||D===void 0?c`${c.identifier(Kn)} < ${_}`:Qn(R,w[A],W,!1);if(B===void 0)continue;const L=[];for(let C=0;C<A;C+=1)L.push(c`${c.identifier(r[C])} IS ${w[C]}`);L.push(B);const[P]=L;E.push(L.length===1&&P!==void 0?P:c`(${c.join(L,c` AND `)})`)}const x=E.length>0?c.join(E,c` OR `):c`1 = 0`,p=j(n,c`SELECT COUNT(*) AS c FROM ${c.identifier(o)} WHERE ${c.identifier("__partition__")} = ${i} AND (${x})`).one(),b=j(n,c`SELECT COUNT(*) AS c FROM ${c.identifier(o)} WHERE ${c.identifier("__partition__")} = ${i}`).one();return{before:p.c,total:b.c}},Wo=n=>{const{baselineSeq:o,onStalePatchDropped:r}=n,{sql:a}=n,{schema:i}=n,w=n.broadcast??(()=>{}),_=Xn(i);let E;const x=()=>n.inTransaction?.()===!0,p=e=>i.tables[e]?.commitOrderedMode!==!0?{}:((E===void 0||!x())&&(E=xn(a)),{[bn]:E}),b=(e,...t)=>{const s=i.tables[e]?.indexes;if(!s||s.length===0)return;const f=[];for(const h of t)h&&f.push(...Vn(s,h,ae));return f.length>0?f:void 0},{headroom:A}=n;let R=!1;const D=async e=>{const t=R;R=!0;try{return await e()}finally{R=t}},W=n.onRead??(()=>{}),B=e=>{It(i.tables[e])&&W(kt,kt)},L=n.onReadRange??(e=>{W(e.table,H)}),P=e=>{B(e.table),L(e)},C=(e,t)=>{t!==void 0&&t!==H&&!R&&A?.recordRead(1),B(e),W(e,t)},ne=n.onIndexUse??(()=>{}),Y=n.onWrite??(()=>{}),y=e=>{R||A?.recordWrite(e)},I=async e=>{y(e.doc),await Y(e)},{cache:k}=n,F=n.clock??(()=>Date.now()),X=n.idGenerator??(()=>crypto.randomUUID()),we=n.scheduler??En,{globalDb:J}=n,oe=n.auth??{identity:null,userId:null},Ie=n.cdc??!1,Ke=we,un=or({scheduler:typeof Ke.list=="function"&&typeof Ke.get=="function"?Ke:void 0,storage:n.storage}),ge=(e,t,s,f)=>{Ie&&!It(i.tables[e])&&In(a,F(),e,t,s,f)},fn=(e,t,s,f)=>{if(i.tables[e]?.dropStalePatchesMode!==!0||!Ie)return!1;const h=o?.();if(h===void 0)return!1;const l=Cn(a,e,t,h);return l===void 0?!1:Object.keys(it(s)).some(d=>At(l[d])!==At(f[d]))},ie=e=>i.tables[e]?.shardMode?.kind==="global",wt=(e,t)=>{if(ie(e)){if(!J)throw new $("INTERNAL",`cross-backend ${t} for global table '${e}' requires a globalDb writer — pass one to createShardCtxDb({ globalDb })`);return J}return U},Qe=e=>wt(e,"cascade"),K=(e,t)=>{if(ie(e)){if(!J)throw new $("INTERNAL",`${t} on global table '${e}' requires a globalDb writer — pass one to createShardCtxDb({ globalDb })`);return J}},gt=async(e,t,s,f,h)=>{h&&y(s);const l=await e.insert(t,s,f);return w({key:l,op:"insert",row:{...s,_id:l},table:t}),l},Ve=(e,t)=>wt(e,"relation load").findMany(e,t),pt=(e,t)=>(ie(e)&&C(e,H),Ve(e,t)),hn=e=>!ie(e.table),yt=n.relationExistsPushDown??"auto",$t=yt!=="never",{maxRelationKeys:mt}=n,Ce=(e,t,s)=>Lt(e,{fetcher:pt,maxRelationKeys:mt,relationBaseWhere:s,schema:i,tableName:t}),Et=async(e,t,s,f)=>{const h=K(e,"relation grouped count");if(h)return C(e,H),tr((S,O)=>h.count(S,O),e,t,s,f);const l=i.tables[e];if(!l)throw new $("INTERNAL",`unknown table: ${e}`);C(e,H);const d=fe(l.softDeleteMode,void 0),u={[t]:{in:s}},g=N(N(u,f),d),v=await Ce(g,e,void 0),m=te(v,Se),M=ce(t);let T=c`SELECT ${M} AS __fk__, COUNT(*) AS count FROM ${c.identifier(e)}`;m&&(T=c`${T} WHERE ${m}`),T=c`${T} GROUP BY ${M}`;const q=j(a,T).toArray();return new Map(q.map(S=>[S.__fk__,S.count]))};let xe=0;const St=new Set;for(const[e,t]of Object.entries(i.tables))for(const s of Object.values(t.triggerMap??{}))St.add(`${e} ${s.timing} ${s.op}`);const Z=(e,t,s)=>St.has(`${e} ${t} ${s}`),ee=async(e,t,s)=>{if(xe+=1,xe>Ht)throw xe-=1,new Te(`trigger recursion exceeded ${String(Ht)} levels on "${s.table}" — check for a self-triggering write`,"trigger");try{await ir({ctx:gn,event:s,op:t,schema:i,tableName:s.table,timing:e})}finally{xe-=1}},{ensureBackfilledForTable:pe,ensureBackfilledIndex:ze,ensureRankBackfilled:Je,ensureRankBackfilledForTable:ye,syncAggregates:be,syncCompanionsForInsert:_t,syncGeo:Me,syncRanks:$e,syncSearch:De}=Mn({broadcast:w,indexKeysFor:(e,t)=>b(e,t),invalidateCache:(e,t,s)=>k?.invalidate(e,t,b(e,s)),recordCdc:ge,schema:i,sql:a}),Rt=(e,t,s)=>{const{shardMode:f}=t;if(f?.kind==="shardBy"&&!(f.field!==void 0&&(s.partitionBy??[]).includes(f.field)))throw Object.assign(new Error(`rank index "${s.name}" on "${e}" partitions across shards (shard key "${f.field??"?"}" is not in partitionBy) — a shard-local rank()/rankPage() would be wrong; roll it up through the Query Coordinator instead`),{code:"CROSS_SHARD_RANK_UNSUPPORTED",name:"LunoraError",status:400})},Tt=e=>Object.entries(i.tables).filter(([,t])=>t.shardMode?.kind!=="global").map(([t])=>t).filter(t=>e===void 0||t===e),me=e=>e===void 0||ie(e)?J:void 0,se=(e,t)=>{const s=Tt(t);for(let f=0;f<s.length;f+=Ee){const h=s.slice(f,f+Ee),[l]=ve(a,Mr(h),...Dr(e,h)).toArray();if(!l)continue;const d=l.__t__,u=_e(l);if(typeof d!="string"||!u)return;const g=l[re];return{docJson:typeof g=="string"?g:le(g??{}),row:u,tableName:d}}},wn=(e,t)=>{const s=[...new Set(e)],f=new Map;if(s.length===0)return f;const h=Tt(t);for(let l=0;l<h.length;l+=Ee){const d=h.slice(l,l+Ee),u=Math.floor(Ee/d.length),g=Ln(c`${c.identifier("id")}`,s,!1,u),v=d.map(m=>c`SELECT ${c.raw(`'${m.replaceAll("'","''")}'`)} AS __t__, id FROM ${c.identifier(m)} WHERE ${g}`);for(const m of j(a,ut(v))){const{id:M,__t__:T}=m;typeof T=="string"&&typeof M=="string"&&f.set(M,T)}}return f},vt={assertRankPartitionLocal:Rt,ensureRankBackfilled:Je,onRead:C,rowToDocument:_e,schema:i,sql:a},U={system:un,async aggregate(e,t){const s=K(e,"aggregate");if(s)return C(e,H),s.aggregate(e,t);const f=i.tables[e];if(!f)throw new $("INTERNAL",`unknown table: ${e}`);if(qe(t.op),t.op==="count")return U.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`);C(e,H);const h=fe(f.softDeleteMode,void 0),l=N(N(t.baseWhere,t.where),h),d=await Ce(l,e,t.relationBaseWhere),u=d!==l;if(f.aggregateIndexes&&!t.baseWhere&&!u){const S=Tn(f.aggregateIndexes,t.op,t.field,t.where);if(S){ze(e,S.index);const O=Xe(S.index.by??[],S.key),Q=Ye(e,S.index.name),V=j(a,c`SELECT ${We} AS value, ${tt} AS count FROM ${c.identifier(Q)} WHERE ${Be} = ${O}`).toArray()[0];return Ze(t.op,V)}}Nt(f,t.field,`aggregate(${e}, { op: "${t.op}", field: "${t.field}" })`);const g=te(d,Se),v=qe(t.op),m=ce(t.field);let M=c`SELECT ${c.raw(v)}(${m}) AS value FROM ${c.identifier(e)}`;g&&(M=c`${M} WHERE ${g}`);const q=j(a,M).toArray()[0]?.value;return q??null},asId(e,t){const s=jt(i,e,t);if(s===null)throw new $("BAD_REQUEST",`asId("${e}", …): "${t}" is not a valid id for table "${e}"`,{status:400});return s},async count(e,t){const s=K(e,"count");if(s)return C(e,H),s.count(e,t);const f=i.tables[e];if(!f)throw new $("INTERNAL",`unknown table: ${e}`);const h=Sn(t);if(h.restrictsCounts)throw new et(e);C(e,H);const l=fe(f.softDeleteMode,void 0),d=N(N(h.baseWhere,h.where),l),u=await Ce(d,e,h.relationBaseWhere),g=u!==d;if(f.aggregateIndexes&&!h.baseWhere&&!g){const T=Rn(f.aggregateIndexes,h.where);if(T){ze(e,T.index);const q=Xe(T.index.by??[],T.key),S=Ye(e,T.index.name),O=j(a,c`SELECT ${We} AS value FROM ${c.identifier(S)} WHERE ${Be} = ${q}`).toArray();return O[0]===void 0?0:O[0].value??0}}const v=te(u,Se);let m=c`SELECT COUNT(*) AS count FROM ${c.identifier(e)}`;return v&&(m=c`${m} WHERE ${v}`),j(a,m).one().count},async delete(e,t,s){const f=se(e,t);if(!f){const m=me(t);m&&(y(void 0),await m.delete(e,t,s));return}const{docJson:h,row:l,tableName:d}=f,u=i.tables[d],g=s?.hard===!0,v=!g&&u?.softDeleteMode?u.softDeleteMode.field:void 0;if(!(v&&l[v]!==null&&l[v]!==void 0)){if(Z(d,"before","delete")&&await ee("before","delete",{id:e,op:"delete",previous:l,table:d}),await er({deletedId:e,deletedReference:m=>l[m],findHolders:async(m,M,T)=>(await Qe(m).findMany(m,{includeDeleted:g,where:{[M]:T}})).page,onCascade:(m,M)=>Qe(m).delete(M,void 0,s),onRestrict:m=>{throw new Te(m,"restrict")},onSetNull:(m,M,T)=>Qe(m).patch(M,{[T]:null}),schema:i,tableName:d}),pe(d),ye(d),v){const m={...l,...p(d),[v]:F(),_id:e};Ue(a,d,Ut(d),[le(m),e,h]),De(d,e,m,l),Me(d,e,void 0),be(d,l,m),$e(d,e,l,void 0),k?.invalidate(d,e,b(d,l,m)),ge(d,e,"update",m),w({indexKeys:b(d,l,m),key:e,op:"update",row:m,table:d}),Z(d,"after","delete")&&await ee("after","delete",{id:e,op:"delete",previous:l,table:d}),await I({id:e,op:"delete",table:d});return}Ue(a,d,Cr(d),[e,h]),De(d,e,void 0),Me(d,e,void 0),be(d,l,void 0),$e(d,e,l,void 0),k?.invalidate(d,e,b(d,l)),ge(d,e,"delete"),w({indexKeys:b(d,l),key:e,op:"delete",table:d}),Z(d,"after","delete")&&await ee("after","delete",{id:e,op:"delete",previous:l,table:d}),await I({id:e,op:"delete",table:d})}},async deleteAll(e,t){if(!i.tables[e])throw new $("INTERNAL",`unknown table: ${e}`);const s=Math.max(1,t?.chunkSize??cn),f=t?.hard===void 0?void 0:{hard:t.hard},h=ie(e)?void 0:e;let l=0;return await D(async()=>{for(;;){const u=(await U.findMany(e,{limit:s})).page.map(g=>String(g._id));if(u.length===0)break;for(const g of u)await U.delete(g,h,f),l+=1;if(u.length<s)break}}),{deleted:l}},async deleteMany(e,t,s){ue(e.length,t?.limit,"deleteMany");for(const f of e)await U.delete(f,s);return{deleted:e.length}},async deleteWhere(e,t,s){const l=(await(K(e,"deleteWhere")??U).findMany(e,{where:t})).page.map(d=>String(d._id));if(ue(l.length,s?.limit,"deleteWhere"),U.deleteMany===void 0)throw new $("INTERNAL",`ctx.db.${e}.deleteMany is unavailable: this writer has no batch delete`);return U.deleteMany(l,s)},async findFirst(e,t={}){return(await U.findMany(e,{...t,limit:1,omitContinueCursor:!0})).page[0]??null},async findFirstOrThrow(e,t={}){const s=await U.findFirst(e,t);if(s===null)throw new Un(`findFirstOrThrow: no "${e}" document matched`);return s},async findMany(e,t={}){const s=K(e,"findMany");if(s)return C(e,H),s.findMany(e,t);const f=i.tables[e];if(!f)throw new $("INTERNAL",`unknown table: ${e}`);const h=!t.where&&!t.baseWhere;h?C(e,H):C(e);const l=st(t.orderBy,f.shape,{pinned:Gn(t.where),uniqueBy:tn(f.indexes,f.shape)}),d=t.cursor?nn(l,ct(t.cursor)):void 0;let u=N(t.baseWhere,t.where);u=N(u,fe(f.softDeleteMode,t.includeDeleted)),u=await Lt(u,{canPushExists:$t?hn:void 0,existsPushMode:yt==="always"?"always":"auto",fetcher:pt,maxRelationKeys:mt,relationBaseWhere:t.relationBaseWhere,schema:i,tableName:e}),d&&(u=u?{AND:[u,d]}:d);const g=$t?jr(C):ht,v=te(u,g,Ne),m=typeof t.limit=="number"?Math.max(0,Math.floor(t.limit)):void 0,M=rn(e,v,on(l),m===void 0?void 0:m+1),T=ve(a,M.text,...M.params).toArray();h&&!R&&A?.recordRead(T.length);const q=[];for(const V of T){const G=_e(V);G&&(q.push(G),!h&&typeof G._id=="string"&&C(e,G._id))}if(m===void 0)return t.with&&await qt({groupedCounter:Et,fetcher:Ve,parents:q,...Wt(t),schema:i,tableName:e,with:t.with}),{continueCursor:null,isDone:!0,page:bt(q,t.select,t.with)};const S=q.length>m,O=S?q.slice(0,m):q,Q=O.at(-1);return t.with&&await qt({fetcher:Ve,groupedCounter:Et,parents:O,...Wt(t),schema:i,tableName:e,with:t.with}),{continueCursor:S&&Q&&t.omitContinueCursor!==!0?He(Q,l):null,isDone:!S,page:bt(O,t.select,t.with)}},async get(e,t){const s=se(e,t);if(!s){const f=me(t);return f?f.get(e,t):null}return C(s.tableName,e),s.row},async lookupById(e,t){const s=se(e,t);return s?(C(s.tableName,e),{row:s.row,tableName:s.tableName}):null},async groupBy(e,t){const s=K(e,"groupBy");if(s)return C(e,H),s.groupBy(e,t);const f=i.tables[e];if(!f)throw new $("INTERNAL",`unknown table: ${e}`);C(e,H);const h=t.agg??{op:"count"};if(qe(h.op),h.op!=="count"&&!h.field)throw new $("INTERNAL",`groupBy(${e}, { agg: { op: "${h.op}" } }): "field" is required for non-count reducers`);const l=fe(f.softDeleteMode,void 0),d=N(N(t.baseWhere,t.where),l),u=await Ce(d,e,t.relationBaseWhere),g=u!==d;if(f.aggregateIndexes&&!t.baseWhere&&!g){const S=_n(f.aggregateIndexes,h.op,h.field,t.by,t.where),O=S===void 0?0:Object.keys(S.partial).length,Q=S?.index.by?.length??0;if(S&&(O===0||O===Q)){ze(e,S.index);const V=Ye(e,S.index.name),G=Object.keys(S.partial),de=[];if(G.length===(S.index.by??[]).length&&G.length>0){const ke=Xe(S.index.by??[],S.partial),Fe=j(a,c`SELECT ${We} AS value, ${tt} AS count FROM ${c.identifier(V)} WHERE ${Be} = ${ke}`).toArray();return Fe.length>0&&de.push({key:{...S.partial},value:Ze(h.op,Fe[0])}),de}const pn=j(a,c`SELECT ${Be} AS key, ${We} AS value, ${tt} AS count FROM ${c.identifier(V)}`).toArray();for(const ke of pn){const Fe=mn(JSON.parse(ke.key));de.push({key:Fe,value:Ze(h.op,ke)})}return de}}for(const S of[...t.by,h.field]){if(S===void 0)continue;const O=S===h.field?`groupBy(${e}, { agg: { op: "${h.op}", field: "${S}" } })`:`groupBy(${e}, { by: [..."${S}"] })`;Nt(f,S,O)}const v=te(u,Se),m=t.by.map(S=>c`${ce(S)} AS ${c.identifier(S)}`);if(h.op==="count")m.push(c`COUNT(*) AS value`);else{const{field:S}=h;if(S===void 0)throw new $("INTERNAL",`groupBy(${e}, { agg: { op: "${h.op}" } }): "field" is required for non-count reducers`);m.push(c`${c.raw(qe(h.op))}(${ce(S)}) AS value`)}let M=c`SELECT ${c.join(m,c`, `)} FROM ${c.identifier(e)}`;v&&(M=c`${M} WHERE ${v}`),M=c`${M} GROUP BY ${c.join(t.by.map(S=>ce(S)),c`, `)}`;const T=j(a,M).toArray(),q=[];for(const S of T){const O={};for(const V of t.by)O[V]=Dn(f.shape[V],S[V]??null);const{value:Q}=S;q.push({key:O,value:Q==null?null:Number(Q)})}return q},async insert(e,t,s){const f=K(e,"insert");if(f)return gt(f,e,t,s,!0);const h=i.tables[e];if(!h)throw new $("INTERNAL",`unknown table: ${e}`);const l=Kt(h,t,oe);rt(h,l);let d;s?.clientId!==void 0?(Fr(s.clientId),d=s.clientId):s?.allowExplicitId&&typeof l._id=="string"?d=l._id:d=X();const u=s?.allowExplicitId&&typeof l._creationTime=="number"?l._creationTime:F(),g={...l,...p(e),_creationTime:u,_id:d};return Z(e,"before","insert")&&await ee("before","insert",{doc:{...g},id:d,op:"insert",table:e}),pe(e),ye(e),dt(a,e,Ar(e),[d,u,le(g)]),_t(e,d,g),Z(e,"after","insert")&&await ee("after","insert",{doc:g,id:d,op:"insert",table:e}),await I({doc:g,id:d,op:"insert",table:e}),d},async insertManyUnsafe(e,t,s){if(ue(t.length,s?.limit,"insertManyUnsafe"),t.length===0)return[];const f=K(e,"insert");if(f){const u=[];for(const g of t)y(g);for(const g of t){const v=await f.insert(e,g,{allowExplicitId:s?.allowExplicitId});w({key:v,op:"insert",row:{...g,_id:v},table:e}),u.push(v)}return u}const h=i.tables[e];if(!h)throw new $("INTERNAL",`unknown table: ${e}`);pe(e),ye(e);const l=[];for(let u=0;u<t.length;u+=Pe)l.push(p(e));const d=t.map((u,g)=>{const v=Kt(h,u,oe),m=s?.allowExplicitId===!0&&typeof v._id=="string"?v._id:X(),M=s?.allowExplicitId===!0&&typeof v._creationTime=="number"?v._creationTime:F(),T={...v,...l[Math.floor(g/Pe)],_creationTime:M,_id:m};return{creationTime:M,document:T,id:m}});for(const u of d)y(u.document);for(let u=0;u<d.length;u+=Pe){const g=c.join(d.slice(u,u+Pe).map(m=>c`(${m.id}, ${m.creationTime}, ${le(m.document)})`),c`, `),v=Zt("sqlite",c`INSERT INTO ${c.identifier(e)} (id, _creationTime, ${c.identifier(re)}) VALUES ${g}`);dt(a,e,v.sql,v.params)}for(const{document:u,id:g}of d)_t(e,g,u),await Y({doc:u,id:g,op:"insert",table:e});return d.map(u=>u.id)},async insertMany(e,t,s){ue(t.length,s?.limit,"insertMany");const f=s?.skipDuplicates===!0,h=[],l=K(e,"insert");if(l)for(const u of t)y(u);const d=async u=>l?gt(l,e,u,void 0,!1):U.insert(e,u);for(const u of t)try{h.push(await d(u))}catch(g){if(f&&g instanceof Te&&g.kind==="unique")h.push(null);else throw g}return h},normalizeId(e,t){return jt(i,e,t)},async patch(e,t,s){const f=se(e,s);if(!f){const v=me(s);if(v){y(t),await v.patch(e,t,s);return}throw new $("NOT_FOUND",`document not found: ${e}`)}const{docJson:h,row:l,tableName:d}=f,u=i.tables[d];if(!u)throw new $("INTERNAL",`unknown table: ${d}`);if(C(d,e),Vt("patch",t),fn(d,e,t,l)){r?.({fields:Object.keys(it(t)),id:e,table:d});return}const g={...l,...it(t),...p(d),_id:e};Qt(u,t,g,oe),rt(u,g,!0),Z(d,"before","update")&&await ee("before","update",{doc:{...g},id:e,op:"update",previous:l,table:d}),pe(d),ye(d),Ue(a,d,Ut(d),[le(g),e,h]),De(d,e,g,l),Me(d,e,g),be(d,l,g),$e(d,e,l,g),k?.invalidate(d,e,b(d,l,g)),ge(d,e,"update",g),w({indexKeys:b(d,l,g),key:e,op:"update",row:g,table:d}),Z(d,"after","update")&&await ee("after","update",{doc:g,id:e,op:"update",previous:l,table:d}),await I({doc:g,id:e,op:"update",table:d})},async patchMany(e,t,s){ue(e.length,t?.limit,"patchMany");for(const f of e)await U.patch(f.id,f.patch,s);return{patched:e.length}},async patchWhere(e,t,s){const l=(await(K(e,"patchWhere")??U).findMany(e,{where:t.where})).page.map(d=>({id:String(d._id),patch:t.patch}));if(ue(l.length,s?.limit,"patchWhere"),U.patchMany===void 0)throw new $("INTERNAL",`ctx.db.${e}.patchMany is unavailable: this writer has no batch patch`);return await U.patchMany(l,s),{patched:l.length}},async related(e,t){return Zn(U,_,e,t)},relationEdges:_,query(e){const t=K(e,"query");return t?(C(e,H),t.query(e)):ln(a,i,e,ne,s=>{s?P(s):C(e,H)},s=>{R||A?.recordRead(s)})},async rank(e,t,s){const f=K(e,"rank");if(f)return C(e,H),f.rank(e,t,s);ne(e,t,"rank");const h=i.tables[e];if(!h)throw new $("INTERNAL",`unknown table: ${e}`);const l=h.rankIndexes?.find(G=>G.name===t);if(!l)throw new $("INTERNAL",`unknown rankIndex "${t}" on table "${e}"`);if(Rt(e,h,l),s.restrictsCounts)throw new et(e);C(e,H),Je(e,l);const d=typeof s.row=="string"?s.row:s.row._id;if(!d)return null;const u=Mt(e,l.name),g=l.sortBy.map((G,de)=>Dt(de)),v=g.map(G=>Ae(G)).join(", "),m=j(a,c`SELECT ${c.identifier("__partition__")}, ${c.raw(v)} FROM ${c.identifier(u)} WHERE ${c.identifier("__id__")} = ${d}`).toArray(),[M]=m;if(M===void 0)return null;let T=M.__partition__;const q=N(s.baseWhere,s.where);nt(q,i,e,"rank");const S=Nn(l,q);if(S){const G=jn(l.partitionBy??[],S);if(G!==T)return null;T=G}const O=g.map(G=>M[G]),{before:Q,total:V}=Jt(a,u,g,l.sortBy,T,O,d);return{position:Q+1,total:V}},async rankBefore(e,t,s){if(ie(e))throw new $("INTERNAL",`rankBefore is not supported on the global (.global()) table '${e}' — cross-shard rank cursors apply only to sharded tables`);const f=i.tables[e];if(!f)throw new $("INTERNAL",`unknown table: ${e}`);const h=f.rankIndexes?.find(g=>g.name===t);if(!h)throw new $("INTERNAL",`unknown rankIndex "${t}" on table "${e}"`);if(s.restrictsCounts)throw new et(e);C(e,H),Je(e,h);const l=Mt(e,h.name),d=h.sortBy.map((g,v)=>Dt(v)),u=h.sortBy.map((g,v)=>ae(s.sortValues[v]??null));return Jt(a,l,d,h.sortBy,s.partitionKey,u,s.rowId)},async rankPage(e,t,s={}){nt(N(s.baseWhere,s.where),i,e,"rankPage");const f=K(e,"rankPage");if(f)return C(e,H),f.rankPage(e,t,s);ne(e,t,"rank");const{continueCursor:h,hasMore:l,rows:d}=Ct(vt,e,t,s);return{continueCursor:h,isDone:!l,page:d.map(u=>u.doc)}},async rankPageRows(e,t,s={}){nt(N(s.baseWhere,s.where),i,e,"rankPage"),ne(e,t,"rank");const{directions:f,hasMore:h,rows:l}=Ct(vt,e,t,s);return{directions:f,hasMore:h,rows:l}},async restore(e,t){const s=se(e,t);if(!s){const l=me(t);if(l?.restore){await l.restore(e,t);return}throw new $("NOT_FOUND",`document not found: ${e}`)}const f=i.tables[s.tableName]?.softDeleteMode?.field;if(!f)throw new $("INTERNAL",`ctx.db.restore: table "${s.tableName}" is not a .softDelete() table`);const h=s.row[f]!==null&&s.row[f]!==void 0;await U.patch(e,{[f]:null},t),h&&$e(s.tableName,e,void 0,s.row)},async replace(e,t,s,f){const h=se(e,s);if(!h){const q=me(s);if(q){y(t),await q.replace(e,t,s,f);return}throw new $("NOT_FOUND",`document not found: ${e}`)}const{docJson:l,row:d,tableName:u}=h,g=i.tables[u];if(!g)throw new $("INTERNAL",`unknown table: ${u}`);Vt("replace",t);const v=f?.allowExplicitId&&typeof t._creationTime=="number"?t._creationTime:void 0,m=typeof d._creationTime=="number"?d._creationTime:void 0,M=v??m??F(),T={...t,...p(u),_creationTime:M,_id:e};Qt(g,t,T,oe),rt(g,T),Z(u,"before","update")&&await ee("before","update",{doc:{...T},id:e,op:"update",previous:d,table:u}),pe(u),ye(u),Ue(a,u,Ir(u),[M,le(T),e,l]),De(u,e,T,d),Me(u,e,T),be(u,d,T),$e(u,e,d,T),k?.invalidate(u,e,b(u,d,T)),ge(u,e,"update",T),w({indexKeys:b(u,d,T),key:e,op:"update",row:T,table:u}),Z(u,"after","update")&&await ee("after","update",{doc:T,id:e,op:"update",previous:d,table:u}),await I({doc:T,id:e,op:"update",table:u})},async wipeShard(e){const t=new Set(e?.exclude),s=e?.tables,f=Object.entries(i.tables).filter(([u,g])=>t.has(u)||s!==void 0&&!s.includes(u)?!1:g.shardMode?.kind!=="global").map(([u])=>u);if(s!==void 0){for(const u of s)if(!i.tables[u])throw new $("INTERNAL",`wipeShard: unknown table: ${u}`)}const h={};let l=0;const{deleteAll:d}=U;if(d===void 0)throw new $("INTERNAL","wipeShard: this writer has no deleteAll");for(const u of f){const g=await d(u,{...e?.chunkSize===void 0?{}:{chunkSize:e.chunkSize},hard:!0});h[u]=g.deleted,l+=g.deleted}return{deleted:l,tables:h}}},gn={db:U,scheduler:we};return n.enforceRls===!0?nr(U,i,(e,t)=>se(e,t)?.tableName,(e,t)=>wn(e,t),_):U};export{No as CDC_LOG_TABLE,fi as IDEMPOTENCY_TABLE,Kr as NotUniqueError,ai as advanceClientWatermark,jo as applyCdcChanges,Vt as assertNoExplicitUndefined,Fr as assertValidClientId,Uo as backfillAggregateIndexes,Oo as backfillRankIndexes,Ho as backfillSearchIndexes,Ko as bumpCdcEpoch,Qo as cdcCanVouchFor,Vo as cdcForkedError,zo as cdcSeqLeavingRows,Jo as cdcTouchesTables,Yo as cdcTrimmedError,Xo as compactCdcDocs,Wo as createShardCtxDb,Zo as cursorBelowRetainedFloor,di as migrateClientWatermark,ei as minCdcReplayableSeq,ti as minCdcSeq,jt as normalizeIdStructurally,ni as readCdcChangeKeys,ri as readCdcChanges,oi as readCdcCursor,ii as readCdcEpoch,li as readClientWatermark,hi as readIdempotent,yi as runShardMigrations,mi as selectShapeMembers,Ei as selectShapeRows,it as stripReservedPatchFields,si as trimCdcChanges,wi as trimIdempotent,gi as writeIdempotent};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{sql as s}from"drizzle-orm";import{matchesStaticWhere as f}from"./AGGREGATE_SQL_FUNCTION-DDEoMnJR.mjs";import{compareStrings as l}from"./aggregateTableName-
|
|
1
|
+
import{sql as s}from"drizzle-orm";import{matchesStaticWhere as f}from"./AGGREGATE_SQL_FUNCTION-DDEoMnJR.mjs";import{compareStrings as l}from"./aggregateTableName-DbAttCNH.mjs";import{serializeSqlValue as d}from"./serializeSqlValue-BbZ5hKM7.mjs";const a=Symbol("not-resolvable"),m=r=>{if(r!==null&&typeof r=="object"&&!Array.isArray(r)){const t=Object.keys(r);return t.length===1&&t[0]==="eq"?r.eq:a}return r},y=(r,t)=>{if(r.length===0)return"";const e={};for(const n of r.toSorted(l))e[n]=t[n]??null;return JSON.stringify(e)},k="__id__",N=r=>`__sort_k${String(r)}__`,h=(r,t)=>{const e=r.partitionBy??[],n=t??{};for(const o of Object.keys(n))if(o==="AND"||o==="OR"||o==="NOT")return;const i={};for(const o of e)if(o in n){const c=m(n[o]);if(c===a)return;i[o]=c}else if(r.where&&o in r.where)i[o]=r.where[o];else return;return i},O=(r,t)=>`${r}__rank_${t}`,$=(r,t)=>({partitionKey:y(r.partitionBy??[],t),rowId:t._id,sortValues:r.sortBy.map(e=>d(t[e.field]??null))}),K=(r,t,e,n)=>{const i=e!=="desc"===n;if(t==null)return i?s`${s.identifier(r)} IS NOT NULL`:void 0;const o=s`${s.identifier(r)} ${s.raw(i?">":"<")} ${t}`;return i?o:s`(${o} OR ${s.identifier(r)} IS NULL)`},R=f;export{k as RANK_TIEBREAK,y as encodePartitionKey,R as matchesRankStaticWhere,$ as rankKeyFromDoc,K as rankPivotConditionSql,O as rankTableName,h as resolveRankPartition,N as sortColumnName};
|
package/dist/packem_shared/{RELATED_DEFAULT_LIMIT-CBYQQIrZ.mjs → RELATED_DEFAULT_LIMIT-e7viSuiO.mjs}
RENAMED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{LunoraError as h}from"@lunora/errors";import{mergeWhere as I}from"./CountRlsUnsupportedError-BvsDqfO2.mjs";import{decodeCursor as S,CURSOR_PREFIX as v,toBase64 as B}from"./CURSOR_PREFIX-
|
|
1
|
+
import{LunoraError as h}from"@lunora/errors";import{mergeWhere as I}from"./CountRlsUnsupportedError-BvsDqfO2.mjs";import{decodeCursor as S,CURSOR_PREFIX as v,toBase64 as B}from"./CURSOR_PREFIX-C1jsjAPd.mjs";const O=4,C=1,L=50,$=200,T=1e4,x=.5,D=t=>{if(t.kind==="id"){const e=t._meta?.tableName;return typeof e=="string"&&e.length>0?{array:!1,targetTable:e}:void 0}if(t.kind!=="array"&&t.kind!=="optional")return;const n=t._meta?.inner,r=n===void 0?void 0:D(n);if(r!==void 0)return{array:r.array||t.kind==="array",targetTable:r.targetTable}},j=t=>{const n=[];for(const[r,e]of Object.entries(t.tables))for(const[s,o]of Object.entries(e.shape)){const a=D(o);a===void 0||t.tables[a.targetTable]===void 0||n.push({array:a.array,column:s,name:`${r}.${s}`,sourceTable:r,targetTable:a.targetTable})}return n},U=t=>v+B(JSON.stringify([t])),M=t=>{const[n]=S(t);if(typeof n!="number"||!Number.isInteger(n)||n<0)throw new h("BAD_REQUEST","invalid cursor");if(n>T)throw new h("BAD_REQUEST",`ctx.db.related: cursor offset ${String(n)} exceeds the maximum of ${String(T)} — narrow the walk with \`edges\` or \`direction\` instead of paging past it`);return n},k=(t,n,r,e)=>{if(t===void 0)return n;if(!Number.isInteger(t)||t<1||t>r)throw new h("BAD_REQUEST",`ctx.db.related: \`${e}\` must be an integer between 1 and ${String(r)}, got ${String(t)}`);return t},N=(t,n)=>{if(n===void 0)return[...t];const r=new Set(t.map(o=>o.name)),e=n.filter(o=>!r.has(o));if(e.length>0)throw new h("BAD_REQUEST",`ctx.db.related: unknown edge ${e.length===1?"name":"names"}: ${e.join(", ")}`);const s=new Set(n);return t.filter(o=>s.has(o.name))},W=(t,n)=>{const r=t[n.column];return n.array?Array.isArray(r)?r.filter(e=>typeof e=="string"&&e.length>0):[]:typeof r=="string"&&r.length>0?[r]:[]},A=async(t,n,r,e)=>{const s=await t.findMany(n,{limit:e.limit,omitContinueCursor:!0,where:I(r,e.relationBaseWhere?.(n))??r});return e.mask?.(n,s.page)??s.page},F={in:{keyColumn:t=>t.column,keysOf:(t,n)=>n.array||t.table!==n.targetTable?[]:[t.id],skipVisitedKeys:!1,table:t=>t.sourceTable},out:{keyColumn:()=>"_id",keysOf:(t,n)=>t.table===n.sourceTable?W(t.document,n):[],skipVisitedKeys:!0,table:t=>t.targetTable}},_=async(t,n,r,e,s)=>{const o=F[s],a=o.keyColumn(r),l=o.table(r),u=new Map;for(const c of n)for(const i of o.keysOf(c,r))!u.has(i)&&!(o.skipVisitedKeys&&e.visited.has(i))&&u.set(i,c);if(u.size===0)return[];const f=await A(t,l,{[a]:{in:[...u.keys()]}},e),m=[];for(const c of f){const i=c._id,g=c[a],d=typeof g=="string"?u.get(g):void 0;typeof i!="string"||d===void 0||e.visited.has(i)||(e.visited.add(i),m.push({document:c,id:i,path:[...d.path,r.name],pathIds:[...d.pathIds,i],table:l}))}return m},Q=async(t,n,r,e)=>{const s=[],o=()=>e.budget-s.length,a=()=>({limit:o(),mask:e.mask,relationBaseWhere:e.relationBaseWhere,visited:e.visited});for(const l of r)e.direction!=="in"&&o()>0&&s.push(...await _(t,n,l,a(),"out")),e.direction!=="out"&&o()>0&&s.push(...await _(t,n,l,a(),"in"));return s},H=async(t,n)=>{const r=n._id;if(typeof r=="string"&&r.length>0){const o=await t.lookupById?.(r);if(!o)throw new h("BAD_REQUEST","ctx.db.related: could not resolve the start document's table from its `_id` — pass `{ table, id }` instead");return{id:r,table:o.tableName}}const{id:e,table:s}=n;if(typeof s!="string"||s.length===0||typeof e!="string"||e.length===0)throw new h("BAD_REQUEST","ctx.db.related: `start` must be a loaded document or `{ table, id }`");return{id:e,table:s}},V=async(t,n,r,e={})=>{const s=k(e.depth,C,O,"depth"),o=k(e.limit,L,$,"limit"),a=e.cursor?M(e.cursor):0,l=e.direction??"both",u=N(n,e.edges),{id:f,table:m}=await H(t,r),[c]=await A(t,m,{_id:f},{limit:1,mask:e.relationMask,relationBaseWhere:e.relationBaseWhere,visited:new Set});if(c===void 0)throw new h("NOT_FOUND",`ctx.db.related: no "${m}" row with id ${f}`);const i=a+o+1,g=new Set([f]),d=[];let w=[{document:c,id:f,path:[],pathIds:[f],table:m}];for(let b=1;b<=s&&w.length>0&&d.length<i;b+=1){const p=await Q(t,w,u,{budget:i-d.length,direction:l,mask:e.relationMask,relationBaseWhere:e.relationBaseWhere,visited:g}),R=x**(b-1);for(const y of p)d.push({depth:b,document:y.document,path:y.path,pathIds:y.pathIds,score:R,table:y.table});w=p}const E=d.length<=a+o;return{continueCursor:E?null:U(a+o),isDone:E,nodes:d.slice(a,a+o)}};export{L as RELATED_DEFAULT_LIMIT,x as RELATED_DEPTH_DECAY,O as RELATED_MAX_DEPTH,$ as RELATED_MAX_LIMIT,T as RELATED_MAX_OFFSET,j as deriveRelationEdges,V as findRelated};
|