@lunora/shard-engine 1.0.0-alpha.70 → 1.0.0-alpha.72
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 +5 -1
- package/dist/index.d.ts +5 -1
- package/dist/index.mjs +1 -1
- package/dist/packem_shared/{ADMIN_FUNCTIONS-INdhzK8S.mjs → ADMIN_FUNCTIONS-BjpFlIz5.mjs} +1 -1
- package/dist/packem_shared/{AGG_COUNT-D2FdUJOa.mjs → AGG_COUNT-TzzFAsyw.mjs} +1 -1
- package/dist/packem_shared/{BIGINT_KEY_DIGITS-Dp0GtURc.mjs → BIGINT_KEY_DIGITS-Bnqj9CYQ.mjs} +1 -1
- package/dist/packem_shared/CDC_LOG_TABLE-CfILante.mjs +15 -0
- package/dist/packem_shared/{DEFAULT_TRANSACTION_LIMITS-DDGk9ebh.mjs → DEFAULT_TRANSACTION_LIMITS-CTHQQgDC.mjs} +1 -1
- package/dist/packem_shared/NotUniqueError-DpTK0ULs.mjs +1 -0
- package/dist/packem_shared/{RANK_TIEBREAK-BXDiMmkH.mjs → RANK_TIEBREAK-D5xNdzB3.mjs} +1 -1
- package/dist/packem_shared/{ReactiveCache-CzeUmTTN.mjs → ReactiveCache-CU_NoCMR.mjs} +1 -1
- package/dist/packem_shared/archiveCdcSegment-E_R_b5Qz.mjs +4 -0
- package/dist/packem_shared/{backfillAggregateIndexes-BG5-SC1q.mjs → backfillAggregateIndexes-DTemznr7.mjs} +1 -1
- package/dist/packem_shared/{buildIndexRange-NtciKq3M.mjs → buildIndexRange-DvN8Qj8e.mjs} +1 -1
- package/dist/packem_shared/{buildReprojectionMigration-Coeg-J0M.mjs → buildReprojectionMigration-DNjOe6AP.mjs} +1 -1
- package/dist/packem_shared/{buildShapeDiff-WSoMs1_h.mjs → buildShapeDiff-CK5vViD5.mjs} +1 -1
- package/dist/packem_shared/{computeRankPage-DsQ16o1z.mjs → computeRankPage-pTaG_r9F.mjs} +1 -1
- package/dist/packem_shared/{createCompanionSync-C6fV10Dq.mjs → createCompanionSync-Cb567rkq.mjs} +1 -1
- package/dist/packem_shared/createReplicaLink-BZvoscLq.mjs +7 -0
- package/dist/packem_shared/{ctx-db-companions-w-CfeOda.mjs → ctx-db-companions-DsNfXSbb.mjs} +1 -1
- package/dist/packem_shared/{defineEngineContractSuite-BSa7TDql.mjs → defineEngineContractSuite-Celpamkj.mjs} +1 -1
- package/dist/packem_shared/{do-sql-Dvj8Yl5N.mjs → do-sql-kpl5Kt1j.mjs} +1 -1
- package/dist/packem_shared/{estimate-bytes-BuXtnbW2.mjs → estimate-bytes-DM1UZj_m.mjs} +1 -1
- package/dist/packem_shared/{isSoftDeleted-CYf6ijO3.mjs → isSoftDeleted-BXWqZxA-.mjs} +1 -1
- package/dist/packem_shared/{materializeExternalRows-iEVQKOKT.mjs → materializeExternalRows-xQWkrJqp.mjs} +1 -1
- package/dist/packem_shared/{mergeChangedKeys-CPw4EamV.mjs → mergeChangedKeys-BA3YxaLE.mjs} +1 -1
- package/dist/packem_shared/{runShardMigrations-DbQJdY1X.mjs → runShardMigrations-BLl8xFGK.mjs} +1 -1
- package/dist/packem_shared/{selectExpiredIds-CKOUTIHn.mjs → selectExpiredIds-D5DEpBbi.mjs} +1 -1
- package/dist/packem_shared/{selectShapeMembers-CCZyZggM.mjs → selectShapeMembers-B8gTOeOB.mjs} +1 -1
- package/dist/packem_shared/{serializeSqlValue-CjbhIHjJ.mjs → serializeSqlValue-BEMMYX1n.mjs} +1 -1
- package/dist/packem_shared/sql-projection-D3qdaItY.mjs +1 -0
- package/package.json +2 -2
- package/dist/packem_shared/CDC_LOG_TABLE-vVheEulD.mjs +0 -15
- package/dist/packem_shared/NotUniqueError-CzcG-VF9.mjs +0 -1
- package/dist/packem_shared/archiveCdcSegment-DU4uzDFQ.mjs +0 -4
- package/dist/packem_shared/createReplicaLink-Bo4IWADY.mjs +0 -7
- package/dist/packem_shared/sql-projection-BB2lCbYV.mjs +0 -1
|
@@ -1 +1 @@
|
|
|
1
|
-
import{defineEngineContractSuite as t}from"../packem_shared/defineEngineContractSuite-
|
|
1
|
+
import{defineEngineContractSuite as t}from"../packem_shared/defineEngineContractSuite-Celpamkj.mjs";export{t as defineEngineContractSuite};
|
package/dist/index.d.mts
CHANGED
|
@@ -209,7 +209,9 @@ interface ValidatorLike {
|
|
|
209
209
|
readonly _meta?: {
|
|
210
210
|
readonly column?: ColumnMetaLike;
|
|
211
211
|
readonly inner?: ValidatorLike;
|
|
212
|
+
readonly members?: ReadonlyArray<ValidatorLike>;
|
|
212
213
|
readonly tableName?: string;
|
|
214
|
+
readonly value?: unknown;
|
|
213
215
|
};
|
|
214
216
|
readonly kind?: string;
|
|
215
217
|
readonly parse?: (value: unknown) => unknown;
|
|
@@ -830,6 +832,7 @@ declare const cdcSeqLeavingRows: (sql: SqlExec, keep: number) => number | undefi
|
|
|
830
832
|
declare const readCdcCursor: (sql: SqlExec) => number;
|
|
831
833
|
declare const cursorBelowRetainedFloor: (floor: number | undefined, sinceSeq: number) => boolean;
|
|
832
834
|
declare const cdcTrimmedError: (floor: number, sinceSeq: number, scope: "global" | "shard") => LunoraError;
|
|
835
|
+
declare const cdcForkedError: (cursor: number, sinceSeq: number, epoch: string) => LunoraError;
|
|
833
836
|
declare const minCdcSeq: (sql: SqlExec) => number | undefined;
|
|
834
837
|
declare const minCdcReplayableSeq: (sql: SqlExec) => number | undefined;
|
|
835
838
|
declare const CDC_META_TABLE = "__cdc_meta";
|
|
@@ -966,6 +969,7 @@ interface CdcArchiveScope {
|
|
|
966
969
|
declare const readCdcArchivedThrough: (sql: SqlExec) => number;
|
|
967
970
|
declare const writeCdcArchivedThrough: (sql: SqlExec, seq: number) => void;
|
|
968
971
|
declare const archiveCdcSegment: (bucket: R2BucketLike, scope: CdcArchiveScope, changes: CdcChange[]) => Promise<void>;
|
|
972
|
+
declare const cdcArchiveRewound: (bucket: R2BucketLike, scope: CdcArchiveScope, archivedThrough: number) => Promise<boolean>;
|
|
969
973
|
declare const readArchivedCdcChanges: (bucket: R2BucketLike, scope: CdcArchiveScope, sinceSeq: number, limit: number | undefined) => Promise<{
|
|
970
974
|
changes: CdcChange[];
|
|
971
975
|
cursor: number;
|
|
@@ -2446,4 +2450,4 @@ interface WhereSqlStrategy<T = SQL> {
|
|
|
2446
2450
|
}
|
|
2447
2451
|
declare const literalInList: (reference: SQL, items: ReadonlyArray<unknown>, negated: boolean) => SQL;
|
|
2448
2452
|
declare const compileWhereSql: <T = SQL>(where: WhereInput | undefined, strategy: WhereSqlStrategy<T>, fragments?: WhereFragments<T>) => T | undefined;
|
|
2449
|
-
export { ADMIN_FUNCTIONS, ADMIN_FUNCTION_PREFIX, AGGREGATE_SQL_FUNCTION, AGG_COUNT, AGG_KEY, AGG_VALUE, AUDIT_LOG_TABLE, type AdvisorProcedure, type AdvisorProceduresResult, type AdvisoriesResult, type AdvisoryFinding, type AggregateIndexDefinitionLike, type AggregateOp, type AggregateOptions, type AggregateResult, type AggregateTally, type AppendAuditEntry, type ApplyOnDeleteOptions$1 as ApplyOnDeleteOptions, type AuditEntry, type AuditLogResult, BIGINT_KEY_DIGITS, type BroadcastDelta, CDC_LOG_TABLE, CDC_LOG_TABLE_SEQ_INDEX, CDC_META_TABLE, CLIENT_WATERMARK_TABLE, COMMIT_SEQ_FIELD, COMMIT_SEQ_TABLE, CURSOR_PREFIX, type CacheEntry, type CapturedMailRow, type CdcArchiveScope, type CdcChange, type CdcChangeKey, type ChangedKeys, type Clock, type ColumnMeta, type ColumnMetaLike, type CompanionSync, type CompanionSyncDeps, ConflictError, type ConflictKind, type CountArgs, CountRlsUnsupportedError, type CreateWorkflowInstanceResult, type CrossShardReadArgs, type CtxDbOptions, DATA_MIGRATION_STATE_TABLE, DEFAULT_FANOUT_TOPIC_LIMIT, DEFAULT_MAX_RELATION_KEYS, DEFAULT_MAX_RELAYS, DEFAULT_PROMOTION_THRESHOLDS, DEFAULT_TRANSACTION_LIMITS, DOC_COLUMN, type DataMigrationDocument, type DataMigrationLike, type DataMigrationTransform, type DatabaseWriterLike, type DependencyTracker, type DeployInfo, type DurableAttachDecision, type DurableStreamAttach, type DurableStreamRun, DurableStreamRunner, type DurableStreamSink, type ExportRow, type ExportShardAdminArgs, type ExportShardArgs, type ExternalSourceDiffResult, type ExternalSourceLike, FLAGS_FUNCTION_PREFIX, type FacetColumnOptions, type FacetColumnResult, type FacetValue, type FanOutBudget, type FanoutMetricsResult, type FanoutPathCounters, type FanoutTopicStat, type FieldOperators, type FilterClause, type FilterOperator, type FlagEvaluation, type FlagsResult, type FunctionCallStat, type FunctionScanAttribution, type FunctionStatsResult, GEO_DEFAULT_PRECISION, GLOBAL_SHAPE_SNAPSHOT_TABLE, type GeoBoundingBox, type GeoFilterBuilderLike, type GeoIndexDefinitionLike, type GeoPoint, type GeoScoredDocument, type GlobalPollCounters, GlobalPollTick, type GroupByEntry, type GroupByOptions, type GuardableSchema$1 as GuardableSchema, IDEMPOTENCY_TABLE, type IdGenerator, type IdempotentRecord, type ImportError, type ImportShardAdminArgs, type ImportShardArgs, type ImportShardResult, type IncrementalMaterializeResult, type IndexDefinitionLike, type IndexKeyEntry, type IndexRangeBuilderLike, type KeyRange, type LifecycleDispatchInfo, type LifecycleEvent, MAIL_RETENTION, MAIL_TABLE, MAX_DURABLE_STREAM_BYTES, MAX_DURABLE_STREAM_CHUNKS, MAX_PAGE_SIZE, MAX_SQL_ROWS, type MaskColumnMetadata, type MaskPoliciesResult, type MaterializeResult, type MigrationDirection, type MigrationRunResult, type MigrationStatus, type MigrationStatusRow, type MutationDelta, type NestedWith, NotFoundError, NotUniqueError, type OnDeleteActionLike, type OrderByClause, type OrderByInput, type OrderKey, type OrderKeyConstraints, OwnerRelay, type OwnerRelayFrame, type PaginationOptions, type PitrBookmarkResult, type PitrRestoreArgs, type PitrRestoreResult, type PitrStorage, type PokeFrameMeta, type PromotionState, type PromotionThresholds, QUEUE_TABLE, type QueryArgs, type QueryPage, type QueueMessageOutcome, type QueueMessageRow, type QueueMetadata, type QueuesResult, RANK_TIEBREAK, REACTOR_STATE_TABLE, RELATED_DEFAULT_LIMIT, RELATED_DEPTH_DECAY, RELATED_MAX_DEPTH, RELATED_MAX_LIMIT, RELATION_EXISTS_KEY, RELATION_FUNCTION_PREFIX, REPROJECTION_MIGRATION_PREFIX, RLS_UNWRAP_SYMBOL, type RankBeforeOptions, type RankBeforeResult, type RankDirection, type RankIndexDefinitionLike, type RankOptions, type RankPage, type RankPageComputation, type RankPageDeps, type RankPageOptions, type RankPageRow, type RankPageRowKey, type RankResult, type RankSortKeyLike, ReactiveCache, type ReactiveCacheOptions, type ReactorDispatchResult, type ReactorMetadata, type ReactorState, type ReactorStats, type ReactorsResult, type ReadFootprint, type ReadHook, type ReadTablePageOptions, type RecordMailInput, type RecordQueueMessageInput, type RelatedDirection, type RelatedNode, type RelatedOptions, type RelatedPage, type RelatedStart, type RelatedStartReference, type RelationDefinitionLike, type RelationEdge, type RelationExistsMarker, type RelationGraphReader, type RelayAttach, type RelayDetach, type RelayFrame, type RelayHost, RelayMember, type RelayPokeDelivery, type RelayShapePoke, type RelayShapeSeed, type RelayShapeSubscribe, type RelayShapeUnsubscribe, type RenderedSql, type ReplicaFollowerHost, type ReplicaOwnerHost, type ReplicaReadiness, type ResolveRelationPredicatesOptions, type ResolveWithOptions, type ResolveWithResult, type ResolvedShape, type RestrictableQueryOptions, type RlsPoliciesResult, type RlsPolicyMetadata, RlsRequiredError, type RlsRoleMetadata, type RpcRequest, type RunDataMigrationOptions, type RunTriggersOptions, SCAN_DEP, SCHEDULE_OUTBOX_TABLE, SCHEMA_HISTORY_MAX_VERSIONS, SEARCH_STATE_TABLE, SHAPE_POKE_CURSOR_TABLE, type SchedulableWorkflowReferenceLike, type ScheduleOutbox, type ScheduleOutboxEnvelope, type ScheduleOutboxRow, type ScheduledFunctionDoc, type SchedulerLike, type SchemaLike, type ScoredDocument, type SearchBackfillProgress, type SearchFilterBuilderLike, type SearchIndexDefinitionLike, type SearchScoredDocument, type SelectMatchingIdsOptions, type ServerDefaultContextLike, type SettingEntry, type SettingKind, type SettingsResult, ShapeDiffCache, type ShapePokeCursorRow, type ShapePokePart, type ShapeProbeCounters, type ShapeRow, type ShapeRowOp, type ShapeSubscriptionQuery, type ShardRankPageResult, ShardRunner, type ShardRunnerOptions, type ShardSiblingHost, type ShardSocketLike, type SocketAttachment, type SortDirection, type SourceClientLike, type SourceCursorLike, type SourceRefresh, type SqlConsoleResult, type SqlCursor, type SqlEngine, type SqlExec, type SqlLintResult, type StorageMetadata, type StorageReference, type StorageReferenceResult, type StorageRuleMetadata, type StorageRulesResult, type StudioFeaturesResult, type SubscriptionConnection, type SubscriptionEnvelope, type SubscriptionIdentity, type SubscriptionInfo, type SubscriptionQuery, type SubscriptionReadFootprint, type SubscriptionsResult, type SystemDatabaseReader, type SystemDoc, type SystemQuery, type SystemReaderOptions, type SystemReaderSchedulerLike, type SystemReaderStorageLike, type SystemTableName, type TableColumnsResult, type TableDefinitionLike, type TableIndexInfo, type TableIndexesResult, type TableInfo, type TablePage, type TableReaderLike, type TablesColumnsResult, type TablesIndexesResult, type TransactionHeadroom, TransactionHeadroomTracker, type TransactionLimits, type TransactionSqlLike, type TriggerContextLike, type TriggerDefinitionLike, type TriggerEventLike, type TriggerOpLike, type TriggerTimingLike, type TtlSweepSpec, UNVOUCHABLE_DEP, type ValidatorLike, type WhereInput, type WhereSqlStrategy, type WithInput, type WorkflowInstanceState, type WorkflowInstanceStatusResult, type WorkflowMetadata, type WorkflowsResult, type WriteEvent, type WriteHook, advanceClientWatermark, aggUpsertSql, aggregateSqlFunction, aggregateTableName, allocateCommitSeq, appendAuditEntry, appendCdcChange, appendStreamChunk, applyCdcChanges, applyOnDelete, applySelect, archiveCdcSegment, armRestore, assertFlatPredicate, assertNoExplicitUndefined, assertReadonly, assertShapeShardable, assertValidClientId, awaitWsDrain, backfillAggregateIndexes, backfillRankIndexes, backfillSearchIndexes, backfillSearchIndexesForTable, bigintSqlKey, boundingBoxCenter, boundingBoxGeohashes, buildIndexRange, buildPokeFrames, buildReprojectionMigration, buildSeekBeforeWhere, buildSeekWhere, buildSettings, buildShapeDiff, bumpCdcEpoch, cdcCanVouchFor, cdcSeqLeavingRows, cdcTouchesTables, cdcTrimmedError, claimStreamRun, clampPromotionThresholds, clearCapturedMail, clearMemoryTables, clearQueueMessages, coerceAggregateNumber, compactCdcDocs, compileWhereSql, computeRankPage, containsRelationPredicate, countLegacyRows, coveringGeohashes, createCompanionSync, createDependencyTracker, createFanoutCounters, createGlobalPollCounters, createIndexSql, createReadFootprint, createRelayLink, createReplicaLink, createShapeDiffCache, createShapeProbeCounters, createShardCtxDb, createSystemReader, cursorBelowRetainedFloor, decideDurableAttach, decodeBigintSqlKey, decodeCursor, decodeFloat64SqlKey, deferScheduleOutbox, deleteGlobalShapeSnapshot, deleteGlobalShapeSnapshotsForConnection, deleteShapePokeCursor, deleteShapePokeCursorsForConnection, deleteStreamRun, depKey, deriveRelationEdges, diffExternalSource, diffGlobalMembership, distinctValues, encodeAggregateKey, encodeCursor, encodeGeohash, encodePartitionKey, encodeRowsPatch, ensureAuditTable, ensureMailTable, envOptionalPositiveInt, envPositiveInt, equalityPinnedFields, exportShardRows, facetColumn, fanOutScalarCounts, findRelated, findStorageReferences, finishStreamRun, float64SqlKey, foldAggregateTally, forgetScheduleOutbox, gateReplicaDispatch, geoTableName, globalShapeReadKey, guardWriter, handleReplicaControl, hasTrigger, haversineMeters, importShardRows, indexKeysForRow, isDevEnvironment, isFtsAvailable, isLossyBody, isMemoryTable, isRelationPredicate, isSoftDeleted, isSourceDue, jsonPath, jsonPathSql, keysTouchRanges, liftSourceId, lintReadonlySql, listReactorStates, listTables, literalInList, markUnvouchableReads, matchesRankStaticWhere, matchesStaticWhere, materializeExternalRows, materializeExternalRowsIncremental, memoryTableNames, mergeChangedKeys, mergeWhere, migrateCdcLog, migrateCdcMeta, migrateClientWatermark, migrateCommitSeq, migrateDurableStreams, migrateGlobalShapeSnapshot, migrateIdempotency, migrateReactorState, migrateScheduleOutbox, migrateSearchState, migrateShapePokeCursor, minCdcReplayableSeq, minCdcSeq, minShapePokeCursor, nextPromotionState, normalizeCountArgument, normalizeIdStructurally, normalizeOrderKeys, normalizeSourceDocument, normalizeSourceValue, param, parkScheduleOutbox, parseExportShardArgs, parseImportShardArgs, planAggregateLookup, pointInBoundingBox, probeScheduleOutbox, projectColumns, pullExternalSourceIncrementalTick, pullExternalSourceTick, qualifiedJsonPath, qualifiedJsonPathSql, quoteIdentifier, rankKeyFromDocument as rankKeyFromDoc, rankPivotConditionSql, rankTableName, reactiveCacheKey, reactorNeedsRun, readAggregateValue, readArchivedCdcChanges, readAuditLog, readBookmark, readCapturedMail, readCdcArchivedThrough, readCdcChangeKeys, readCdcChanges, readCdcCursor, readCdcEpoch, readClientWatermark, readCommitSeq, readDeployInfo, readDueScheduleOutbox, readExternalSourceBaseline, readGlobalShapeSnapshot, readIdempotent, readMigrationStatus, readQueueMessageById, readQueueMessages, readReactorState, readSchemaHistory, readSchemaVersion, readSearchBackfillState, readShapePokeCursor, readStreamChunks, readStreamRun, readTablePage, recordCapturedMail, recordChangedKeys, recordFanoutPass, recordGlobalPollPass, recordQueueMessages, recordScheduleOutbox, recordSchemaVersion, recordShapeProbePass, relationHooks, relayCountFor, renderSql, reprojectableFields, reprojectionMigrationId, reprojectionTables, resolveRankPartition, resolveRankSeekTuple, resolveRelationPredicates, resolveWith, rowToDocument, runDataMigration, runDrizzle, runExternalSourceTick, runReadonlySql, runRowValidators, runShardMigrations, runSocketPool, runSql, runTriggers, selectExpiredIds, selectExportTables, selectIndexForAggregate, selectIndexForCount, selectIndexForGroupBy, selectMatchingIds, selectShapeMembers, selectShapeRows, serializeSqlValue, shapeRoutingKey, softDeleteScope, sortColumnName, sqliteInList, stableStringify, stableWireKey, stripReservedPatchFields, subscriptionFrames, subscriptionListDeltas, summarizeFanoutTopics, summarizeSubscriptions, tableColumns, tableFromDepKey, throwingScheduler, tiebreakDirectionFor, trimCdcChanges, trimIdempotent, trimScheduleOutbox, trimStreamRuns, tryRowToDocument, trySendFrame, unionAll, uniqueIndexFields, validateImportRow, writeCdcArchivedThrough, writeGlobalShapeSnapshot, writeIdempotent, writeReactorState, writeSearchBackfillState, writeShapePokeCursor, writeShapePokeCursors, writeTouchesMemo };
|
|
2453
|
+
export { ADMIN_FUNCTIONS, ADMIN_FUNCTION_PREFIX, AGGREGATE_SQL_FUNCTION, AGG_COUNT, AGG_KEY, AGG_VALUE, AUDIT_LOG_TABLE, type AdvisorProcedure, type AdvisorProceduresResult, type AdvisoriesResult, type AdvisoryFinding, type AggregateIndexDefinitionLike, type AggregateOp, type AggregateOptions, type AggregateResult, type AggregateTally, type AppendAuditEntry, type ApplyOnDeleteOptions$1 as ApplyOnDeleteOptions, type AuditEntry, type AuditLogResult, BIGINT_KEY_DIGITS, type BroadcastDelta, CDC_LOG_TABLE, CDC_LOG_TABLE_SEQ_INDEX, CDC_META_TABLE, CLIENT_WATERMARK_TABLE, COMMIT_SEQ_FIELD, COMMIT_SEQ_TABLE, CURSOR_PREFIX, type CacheEntry, type CapturedMailRow, type CdcArchiveScope, type CdcChange, type CdcChangeKey, type ChangedKeys, type Clock, type ColumnMeta, type ColumnMetaLike, type CompanionSync, type CompanionSyncDeps, ConflictError, type ConflictKind, type CountArgs, CountRlsUnsupportedError, type CreateWorkflowInstanceResult, type CrossShardReadArgs, type CtxDbOptions, DATA_MIGRATION_STATE_TABLE, DEFAULT_FANOUT_TOPIC_LIMIT, DEFAULT_MAX_RELATION_KEYS, DEFAULT_MAX_RELAYS, DEFAULT_PROMOTION_THRESHOLDS, DEFAULT_TRANSACTION_LIMITS, DOC_COLUMN, type DataMigrationDocument, type DataMigrationLike, type DataMigrationTransform, type DatabaseWriterLike, type DependencyTracker, type DeployInfo, type DurableAttachDecision, type DurableStreamAttach, type DurableStreamRun, DurableStreamRunner, type DurableStreamSink, type ExportRow, type ExportShardAdminArgs, type ExportShardArgs, type ExternalSourceDiffResult, type ExternalSourceLike, FLAGS_FUNCTION_PREFIX, type FacetColumnOptions, type FacetColumnResult, type FacetValue, type FanOutBudget, type FanoutMetricsResult, type FanoutPathCounters, type FanoutTopicStat, type FieldOperators, type FilterClause, type FilterOperator, type FlagEvaluation, type FlagsResult, type FunctionCallStat, type FunctionScanAttribution, type FunctionStatsResult, GEO_DEFAULT_PRECISION, GLOBAL_SHAPE_SNAPSHOT_TABLE, type GeoBoundingBox, type GeoFilterBuilderLike, type GeoIndexDefinitionLike, type GeoPoint, type GeoScoredDocument, type GlobalPollCounters, GlobalPollTick, type GroupByEntry, type GroupByOptions, type GuardableSchema$1 as GuardableSchema, IDEMPOTENCY_TABLE, type IdGenerator, type IdempotentRecord, type ImportError, type ImportShardAdminArgs, type ImportShardArgs, type ImportShardResult, type IncrementalMaterializeResult, type IndexDefinitionLike, type IndexKeyEntry, type IndexRangeBuilderLike, type KeyRange, type LifecycleDispatchInfo, type LifecycleEvent, MAIL_RETENTION, MAIL_TABLE, MAX_DURABLE_STREAM_BYTES, MAX_DURABLE_STREAM_CHUNKS, MAX_PAGE_SIZE, MAX_SQL_ROWS, type MaskColumnMetadata, type MaskPoliciesResult, type MaterializeResult, type MigrationDirection, type MigrationRunResult, type MigrationStatus, type MigrationStatusRow, type MutationDelta, type NestedWith, NotFoundError, NotUniqueError, type OnDeleteActionLike, type OrderByClause, type OrderByInput, type OrderKey, type OrderKeyConstraints, OwnerRelay, type OwnerRelayFrame, type PaginationOptions, type PitrBookmarkResult, type PitrRestoreArgs, type PitrRestoreResult, type PitrStorage, type PokeFrameMeta, type PromotionState, type PromotionThresholds, QUEUE_TABLE, type QueryArgs, type QueryPage, type QueueMessageOutcome, type QueueMessageRow, type QueueMetadata, type QueuesResult, RANK_TIEBREAK, REACTOR_STATE_TABLE, RELATED_DEFAULT_LIMIT, RELATED_DEPTH_DECAY, RELATED_MAX_DEPTH, RELATED_MAX_LIMIT, RELATION_EXISTS_KEY, RELATION_FUNCTION_PREFIX, REPROJECTION_MIGRATION_PREFIX, RLS_UNWRAP_SYMBOL, type RankBeforeOptions, type RankBeforeResult, type RankDirection, type RankIndexDefinitionLike, type RankOptions, type RankPage, type RankPageComputation, type RankPageDeps, type RankPageOptions, type RankPageRow, type RankPageRowKey, type RankResult, type RankSortKeyLike, ReactiveCache, type ReactiveCacheOptions, type ReactorDispatchResult, type ReactorMetadata, type ReactorState, type ReactorStats, type ReactorsResult, type ReadFootprint, type ReadHook, type ReadTablePageOptions, type RecordMailInput, type RecordQueueMessageInput, type RelatedDirection, type RelatedNode, type RelatedOptions, type RelatedPage, type RelatedStart, type RelatedStartReference, type RelationDefinitionLike, type RelationEdge, type RelationExistsMarker, type RelationGraphReader, type RelayAttach, type RelayDetach, type RelayFrame, type RelayHost, RelayMember, type RelayPokeDelivery, type RelayShapePoke, type RelayShapeSeed, type RelayShapeSubscribe, type RelayShapeUnsubscribe, type RenderedSql, type ReplicaFollowerHost, type ReplicaOwnerHost, type ReplicaReadiness, type ResolveRelationPredicatesOptions, type ResolveWithOptions, type ResolveWithResult, type ResolvedShape, type RestrictableQueryOptions, type RlsPoliciesResult, type RlsPolicyMetadata, RlsRequiredError, type RlsRoleMetadata, type RpcRequest, type RunDataMigrationOptions, type RunTriggersOptions, SCAN_DEP, SCHEDULE_OUTBOX_TABLE, SCHEMA_HISTORY_MAX_VERSIONS, SEARCH_STATE_TABLE, SHAPE_POKE_CURSOR_TABLE, type SchedulableWorkflowReferenceLike, type ScheduleOutbox, type ScheduleOutboxEnvelope, type ScheduleOutboxRow, type ScheduledFunctionDoc, type SchedulerLike, type SchemaLike, type ScoredDocument, type SearchBackfillProgress, type SearchFilterBuilderLike, type SearchIndexDefinitionLike, type SearchScoredDocument, type SelectMatchingIdsOptions, type ServerDefaultContextLike, type SettingEntry, type SettingKind, type SettingsResult, ShapeDiffCache, type ShapePokeCursorRow, type ShapePokePart, type ShapeProbeCounters, type ShapeRow, type ShapeRowOp, type ShapeSubscriptionQuery, type ShardRankPageResult, ShardRunner, type ShardRunnerOptions, type ShardSiblingHost, type ShardSocketLike, type SocketAttachment, type SortDirection, type SourceClientLike, type SourceCursorLike, type SourceRefresh, type SqlConsoleResult, type SqlCursor, type SqlEngine, type SqlExec, type SqlLintResult, type StorageMetadata, type StorageReference, type StorageReferenceResult, type StorageRuleMetadata, type StorageRulesResult, type StudioFeaturesResult, type SubscriptionConnection, type SubscriptionEnvelope, type SubscriptionIdentity, type SubscriptionInfo, type SubscriptionQuery, type SubscriptionReadFootprint, type SubscriptionsResult, type SystemDatabaseReader, type SystemDoc, type SystemQuery, type SystemReaderOptions, type SystemReaderSchedulerLike, type SystemReaderStorageLike, type SystemTableName, type TableColumnsResult, type TableDefinitionLike, type TableIndexInfo, type TableIndexesResult, type TableInfo, type TablePage, type TableReaderLike, type TablesColumnsResult, type TablesIndexesResult, type TransactionHeadroom, TransactionHeadroomTracker, type TransactionLimits, type TransactionSqlLike, type TriggerContextLike, type TriggerDefinitionLike, type TriggerEventLike, type TriggerOpLike, type TriggerTimingLike, type TtlSweepSpec, UNVOUCHABLE_DEP, type ValidatorLike, type WhereInput, type WhereSqlStrategy, type WithInput, type WorkflowInstanceState, type WorkflowInstanceStatusResult, type WorkflowMetadata, type WorkflowsResult, type WriteEvent, type WriteHook, advanceClientWatermark, aggUpsertSql, aggregateSqlFunction, aggregateTableName, allocateCommitSeq, appendAuditEntry, appendCdcChange, appendStreamChunk, applyCdcChanges, applyOnDelete, applySelect, archiveCdcSegment, armRestore, assertFlatPredicate, assertNoExplicitUndefined, assertReadonly, assertShapeShardable, assertValidClientId, awaitWsDrain, backfillAggregateIndexes, backfillRankIndexes, backfillSearchIndexes, backfillSearchIndexesForTable, bigintSqlKey, boundingBoxCenter, boundingBoxGeohashes, buildIndexRange, buildPokeFrames, buildReprojectionMigration, buildSeekBeforeWhere, buildSeekWhere, buildSettings, buildShapeDiff, bumpCdcEpoch, 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, gateReplicaDispatch, geoTableName, globalShapeReadKey, guardWriter, handleReplicaControl, hasTrigger, haversineMeters, importShardRows, indexKeysForRow, isDevEnvironment, isFtsAvailable, isLossyBody, isMemoryTable, isRelationPredicate, isSoftDeleted, isSourceDue, jsonPath, jsonPathSql, keysTouchRanges, liftSourceId, lintReadonlySql, listReactorStates, listTables, literalInList, markUnvouchableReads, matchesRankStaticWhere, matchesStaticWhere, materializeExternalRows, materializeExternalRowsIncremental, memoryTableNames, mergeChangedKeys, mergeWhere, migrateCdcLog, migrateCdcMeta, migrateClientWatermark, migrateCommitSeq, migrateDurableStreams, migrateGlobalShapeSnapshot, migrateIdempotency, migrateReactorState, migrateScheduleOutbox, migrateSearchState, migrateShapePokeCursor, minCdcReplayableSeq, minCdcSeq, minShapePokeCursor, nextPromotionState, normalizeCountArgument, normalizeIdStructurally, normalizeOrderKeys, normalizeSourceDocument, normalizeSourceValue, param, parkScheduleOutbox, parseExportShardArgs, parseImportShardArgs, planAggregateLookup, pointInBoundingBox, probeScheduleOutbox, projectColumns, pullExternalSourceIncrementalTick, pullExternalSourceTick, qualifiedJsonPath, qualifiedJsonPathSql, quoteIdentifier, rankKeyFromDocument as rankKeyFromDoc, rankPivotConditionSql, rankTableName, reactiveCacheKey, reactorNeedsRun, readAggregateValue, readArchivedCdcChanges, readAuditLog, readBookmark, readCapturedMail, readCdcArchivedThrough, readCdcChangeKeys, readCdcChanges, readCdcCursor, readCdcEpoch, readClientWatermark, readCommitSeq, readDeployInfo, readDueScheduleOutbox, readExternalSourceBaseline, readGlobalShapeSnapshot, readIdempotent, readMigrationStatus, readQueueMessageById, readQueueMessages, readReactorState, readSchemaHistory, readSchemaVersion, readSearchBackfillState, readShapePokeCursor, readStreamChunks, readStreamRun, readTablePage, recordCapturedMail, recordChangedKeys, recordFanoutPass, recordGlobalPollPass, recordQueueMessages, recordScheduleOutbox, recordSchemaVersion, recordShapeProbePass, relationHooks, relayCountFor, renderSql, reprojectableFields, reprojectionMigrationId, reprojectionTables, resolveRankPartition, resolveRankSeekTuple, resolveRelationPredicates, resolveWith, rowToDocument, runDataMigration, runDrizzle, runExternalSourceTick, runReadonlySql, runRowValidators, runShardMigrations, runSocketPool, runSql, runTriggers, selectExpiredIds, selectExportTables, selectIndexForAggregate, selectIndexForCount, selectIndexForGroupBy, selectMatchingIds, selectShapeMembers, selectShapeRows, serializeSqlValue, shapeRoutingKey, softDeleteScope, sortColumnName, sqliteInList, stableStringify, stableWireKey, stripReservedPatchFields, subscriptionFrames, subscriptionListDeltas, summarizeFanoutTopics, summarizeSubscriptions, tableColumns, tableFromDepKey, throwingScheduler, tiebreakDirectionFor, trimCdcChanges, trimIdempotent, trimScheduleOutbox, trimStreamRuns, tryRowToDocument, trySendFrame, unionAll, uniqueIndexFields, validateImportRow, writeCdcArchivedThrough, writeGlobalShapeSnapshot, writeIdempotent, writeReactorState, writeSearchBackfillState, writeShapePokeCursor, writeShapePokeCursors, writeTouchesMemo };
|
package/dist/index.d.ts
CHANGED
|
@@ -209,7 +209,9 @@ interface ValidatorLike {
|
|
|
209
209
|
readonly _meta?: {
|
|
210
210
|
readonly column?: ColumnMetaLike;
|
|
211
211
|
readonly inner?: ValidatorLike;
|
|
212
|
+
readonly members?: ReadonlyArray<ValidatorLike>;
|
|
212
213
|
readonly tableName?: string;
|
|
214
|
+
readonly value?: unknown;
|
|
213
215
|
};
|
|
214
216
|
readonly kind?: string;
|
|
215
217
|
readonly parse?: (value: unknown) => unknown;
|
|
@@ -830,6 +832,7 @@ declare const cdcSeqLeavingRows: (sql: SqlExec, keep: number) => number | undefi
|
|
|
830
832
|
declare const readCdcCursor: (sql: SqlExec) => number;
|
|
831
833
|
declare const cursorBelowRetainedFloor: (floor: number | undefined, sinceSeq: number) => boolean;
|
|
832
834
|
declare const cdcTrimmedError: (floor: number, sinceSeq: number, scope: "global" | "shard") => LunoraError;
|
|
835
|
+
declare const cdcForkedError: (cursor: number, sinceSeq: number, epoch: string) => LunoraError;
|
|
833
836
|
declare const minCdcSeq: (sql: SqlExec) => number | undefined;
|
|
834
837
|
declare const minCdcReplayableSeq: (sql: SqlExec) => number | undefined;
|
|
835
838
|
declare const CDC_META_TABLE = "__cdc_meta";
|
|
@@ -966,6 +969,7 @@ interface CdcArchiveScope {
|
|
|
966
969
|
declare const readCdcArchivedThrough: (sql: SqlExec) => number;
|
|
967
970
|
declare const writeCdcArchivedThrough: (sql: SqlExec, seq: number) => void;
|
|
968
971
|
declare const archiveCdcSegment: (bucket: R2BucketLike, scope: CdcArchiveScope, changes: CdcChange[]) => Promise<void>;
|
|
972
|
+
declare const cdcArchiveRewound: (bucket: R2BucketLike, scope: CdcArchiveScope, archivedThrough: number) => Promise<boolean>;
|
|
969
973
|
declare const readArchivedCdcChanges: (bucket: R2BucketLike, scope: CdcArchiveScope, sinceSeq: number, limit: number | undefined) => Promise<{
|
|
970
974
|
changes: CdcChange[];
|
|
971
975
|
cursor: number;
|
|
@@ -2446,4 +2450,4 @@ interface WhereSqlStrategy<T = SQL> {
|
|
|
2446
2450
|
}
|
|
2447
2451
|
declare const literalInList: (reference: SQL, items: ReadonlyArray<unknown>, negated: boolean) => SQL;
|
|
2448
2452
|
declare const compileWhereSql: <T = SQL>(where: WhereInput | undefined, strategy: WhereSqlStrategy<T>, fragments?: WhereFragments<T>) => T | undefined;
|
|
2449
|
-
export { ADMIN_FUNCTIONS, ADMIN_FUNCTION_PREFIX, AGGREGATE_SQL_FUNCTION, AGG_COUNT, AGG_KEY, AGG_VALUE, AUDIT_LOG_TABLE, type AdvisorProcedure, type AdvisorProceduresResult, type AdvisoriesResult, type AdvisoryFinding, type AggregateIndexDefinitionLike, type AggregateOp, type AggregateOptions, type AggregateResult, type AggregateTally, type AppendAuditEntry, type ApplyOnDeleteOptions$1 as ApplyOnDeleteOptions, type AuditEntry, type AuditLogResult, BIGINT_KEY_DIGITS, type BroadcastDelta, CDC_LOG_TABLE, CDC_LOG_TABLE_SEQ_INDEX, CDC_META_TABLE, CLIENT_WATERMARK_TABLE, COMMIT_SEQ_FIELD, COMMIT_SEQ_TABLE, CURSOR_PREFIX, type CacheEntry, type CapturedMailRow, type CdcArchiveScope, type CdcChange, type CdcChangeKey, type ChangedKeys, type Clock, type ColumnMeta, type ColumnMetaLike, type CompanionSync, type CompanionSyncDeps, ConflictError, type ConflictKind, type CountArgs, CountRlsUnsupportedError, type CreateWorkflowInstanceResult, type CrossShardReadArgs, type CtxDbOptions, DATA_MIGRATION_STATE_TABLE, DEFAULT_FANOUT_TOPIC_LIMIT, DEFAULT_MAX_RELATION_KEYS, DEFAULT_MAX_RELAYS, DEFAULT_PROMOTION_THRESHOLDS, DEFAULT_TRANSACTION_LIMITS, DOC_COLUMN, type DataMigrationDocument, type DataMigrationLike, type DataMigrationTransform, type DatabaseWriterLike, type DependencyTracker, type DeployInfo, type DurableAttachDecision, type DurableStreamAttach, type DurableStreamRun, DurableStreamRunner, type DurableStreamSink, type ExportRow, type ExportShardAdminArgs, type ExportShardArgs, type ExternalSourceDiffResult, type ExternalSourceLike, FLAGS_FUNCTION_PREFIX, type FacetColumnOptions, type FacetColumnResult, type FacetValue, type FanOutBudget, type FanoutMetricsResult, type FanoutPathCounters, type FanoutTopicStat, type FieldOperators, type FilterClause, type FilterOperator, type FlagEvaluation, type FlagsResult, type FunctionCallStat, type FunctionScanAttribution, type FunctionStatsResult, GEO_DEFAULT_PRECISION, GLOBAL_SHAPE_SNAPSHOT_TABLE, type GeoBoundingBox, type GeoFilterBuilderLike, type GeoIndexDefinitionLike, type GeoPoint, type GeoScoredDocument, type GlobalPollCounters, GlobalPollTick, type GroupByEntry, type GroupByOptions, type GuardableSchema$1 as GuardableSchema, IDEMPOTENCY_TABLE, type IdGenerator, type IdempotentRecord, type ImportError, type ImportShardAdminArgs, type ImportShardArgs, type ImportShardResult, type IncrementalMaterializeResult, type IndexDefinitionLike, type IndexKeyEntry, type IndexRangeBuilderLike, type KeyRange, type LifecycleDispatchInfo, type LifecycleEvent, MAIL_RETENTION, MAIL_TABLE, MAX_DURABLE_STREAM_BYTES, MAX_DURABLE_STREAM_CHUNKS, MAX_PAGE_SIZE, MAX_SQL_ROWS, type MaskColumnMetadata, type MaskPoliciesResult, type MaterializeResult, type MigrationDirection, type MigrationRunResult, type MigrationStatus, type MigrationStatusRow, type MutationDelta, type NestedWith, NotFoundError, NotUniqueError, type OnDeleteActionLike, type OrderByClause, type OrderByInput, type OrderKey, type OrderKeyConstraints, OwnerRelay, type OwnerRelayFrame, type PaginationOptions, type PitrBookmarkResult, type PitrRestoreArgs, type PitrRestoreResult, type PitrStorage, type PokeFrameMeta, type PromotionState, type PromotionThresholds, QUEUE_TABLE, type QueryArgs, type QueryPage, type QueueMessageOutcome, type QueueMessageRow, type QueueMetadata, type QueuesResult, RANK_TIEBREAK, REACTOR_STATE_TABLE, RELATED_DEFAULT_LIMIT, RELATED_DEPTH_DECAY, RELATED_MAX_DEPTH, RELATED_MAX_LIMIT, RELATION_EXISTS_KEY, RELATION_FUNCTION_PREFIX, REPROJECTION_MIGRATION_PREFIX, RLS_UNWRAP_SYMBOL, type RankBeforeOptions, type RankBeforeResult, type RankDirection, type RankIndexDefinitionLike, type RankOptions, type RankPage, type RankPageComputation, type RankPageDeps, type RankPageOptions, type RankPageRow, type RankPageRowKey, type RankResult, type RankSortKeyLike, ReactiveCache, type ReactiveCacheOptions, type ReactorDispatchResult, type ReactorMetadata, type ReactorState, type ReactorStats, type ReactorsResult, type ReadFootprint, type ReadHook, type ReadTablePageOptions, type RecordMailInput, type RecordQueueMessageInput, type RelatedDirection, type RelatedNode, type RelatedOptions, type RelatedPage, type RelatedStart, type RelatedStartReference, type RelationDefinitionLike, type RelationEdge, type RelationExistsMarker, type RelationGraphReader, type RelayAttach, type RelayDetach, type RelayFrame, type RelayHost, RelayMember, type RelayPokeDelivery, type RelayShapePoke, type RelayShapeSeed, type RelayShapeSubscribe, type RelayShapeUnsubscribe, type RenderedSql, type ReplicaFollowerHost, type ReplicaOwnerHost, type ReplicaReadiness, type ResolveRelationPredicatesOptions, type ResolveWithOptions, type ResolveWithResult, type ResolvedShape, type RestrictableQueryOptions, type RlsPoliciesResult, type RlsPolicyMetadata, RlsRequiredError, type RlsRoleMetadata, type RpcRequest, type RunDataMigrationOptions, type RunTriggersOptions, SCAN_DEP, SCHEDULE_OUTBOX_TABLE, SCHEMA_HISTORY_MAX_VERSIONS, SEARCH_STATE_TABLE, SHAPE_POKE_CURSOR_TABLE, type SchedulableWorkflowReferenceLike, type ScheduleOutbox, type ScheduleOutboxEnvelope, type ScheduleOutboxRow, type ScheduledFunctionDoc, type SchedulerLike, type SchemaLike, type ScoredDocument, type SearchBackfillProgress, type SearchFilterBuilderLike, type SearchIndexDefinitionLike, type SearchScoredDocument, type SelectMatchingIdsOptions, type ServerDefaultContextLike, type SettingEntry, type SettingKind, type SettingsResult, ShapeDiffCache, type ShapePokeCursorRow, type ShapePokePart, type ShapeProbeCounters, type ShapeRow, type ShapeRowOp, type ShapeSubscriptionQuery, type ShardRankPageResult, ShardRunner, type ShardRunnerOptions, type ShardSiblingHost, type ShardSocketLike, type SocketAttachment, type SortDirection, type SourceClientLike, type SourceCursorLike, type SourceRefresh, type SqlConsoleResult, type SqlCursor, type SqlEngine, type SqlExec, type SqlLintResult, type StorageMetadata, type StorageReference, type StorageReferenceResult, type StorageRuleMetadata, type StorageRulesResult, type StudioFeaturesResult, type SubscriptionConnection, type SubscriptionEnvelope, type SubscriptionIdentity, type SubscriptionInfo, type SubscriptionQuery, type SubscriptionReadFootprint, type SubscriptionsResult, type SystemDatabaseReader, type SystemDoc, type SystemQuery, type SystemReaderOptions, type SystemReaderSchedulerLike, type SystemReaderStorageLike, type SystemTableName, type TableColumnsResult, type TableDefinitionLike, type TableIndexInfo, type TableIndexesResult, type TableInfo, type TablePage, type TableReaderLike, type TablesColumnsResult, type TablesIndexesResult, type TransactionHeadroom, TransactionHeadroomTracker, type TransactionLimits, type TransactionSqlLike, type TriggerContextLike, type TriggerDefinitionLike, type TriggerEventLike, type TriggerOpLike, type TriggerTimingLike, type TtlSweepSpec, UNVOUCHABLE_DEP, type ValidatorLike, type WhereInput, type WhereSqlStrategy, type WithInput, type WorkflowInstanceState, type WorkflowInstanceStatusResult, type WorkflowMetadata, type WorkflowsResult, type WriteEvent, type WriteHook, advanceClientWatermark, aggUpsertSql, aggregateSqlFunction, aggregateTableName, allocateCommitSeq, appendAuditEntry, appendCdcChange, appendStreamChunk, applyCdcChanges, applyOnDelete, applySelect, archiveCdcSegment, armRestore, assertFlatPredicate, assertNoExplicitUndefined, assertReadonly, assertShapeShardable, assertValidClientId, awaitWsDrain, backfillAggregateIndexes, backfillRankIndexes, backfillSearchIndexes, backfillSearchIndexesForTable, bigintSqlKey, boundingBoxCenter, boundingBoxGeohashes, buildIndexRange, buildPokeFrames, buildReprojectionMigration, buildSeekBeforeWhere, buildSeekWhere, buildSettings, buildShapeDiff, bumpCdcEpoch, cdcCanVouchFor, cdcSeqLeavingRows, cdcTouchesTables, cdcTrimmedError, claimStreamRun, clampPromotionThresholds, clearCapturedMail, clearMemoryTables, clearQueueMessages, coerceAggregateNumber, compactCdcDocs, compileWhereSql, computeRankPage, containsRelationPredicate, countLegacyRows, coveringGeohashes, createCompanionSync, createDependencyTracker, createFanoutCounters, createGlobalPollCounters, createIndexSql, createReadFootprint, createRelayLink, createReplicaLink, createShapeDiffCache, createShapeProbeCounters, createShardCtxDb, createSystemReader, cursorBelowRetainedFloor, decideDurableAttach, decodeBigintSqlKey, decodeCursor, decodeFloat64SqlKey, deferScheduleOutbox, deleteGlobalShapeSnapshot, deleteGlobalShapeSnapshotsForConnection, deleteShapePokeCursor, deleteShapePokeCursorsForConnection, deleteStreamRun, depKey, deriveRelationEdges, diffExternalSource, diffGlobalMembership, distinctValues, encodeAggregateKey, encodeCursor, encodeGeohash, encodePartitionKey, encodeRowsPatch, ensureAuditTable, ensureMailTable, envOptionalPositiveInt, envPositiveInt, equalityPinnedFields, exportShardRows, facetColumn, fanOutScalarCounts, findRelated, findStorageReferences, finishStreamRun, float64SqlKey, foldAggregateTally, forgetScheduleOutbox, gateReplicaDispatch, geoTableName, globalShapeReadKey, guardWriter, handleReplicaControl, hasTrigger, haversineMeters, importShardRows, indexKeysForRow, isDevEnvironment, isFtsAvailable, isLossyBody, isMemoryTable, isRelationPredicate, isSoftDeleted, isSourceDue, jsonPath, jsonPathSql, keysTouchRanges, liftSourceId, lintReadonlySql, listReactorStates, listTables, literalInList, markUnvouchableReads, matchesRankStaticWhere, matchesStaticWhere, materializeExternalRows, materializeExternalRowsIncremental, memoryTableNames, mergeChangedKeys, mergeWhere, migrateCdcLog, migrateCdcMeta, migrateClientWatermark, migrateCommitSeq, migrateDurableStreams, migrateGlobalShapeSnapshot, migrateIdempotency, migrateReactorState, migrateScheduleOutbox, migrateSearchState, migrateShapePokeCursor, minCdcReplayableSeq, minCdcSeq, minShapePokeCursor, nextPromotionState, normalizeCountArgument, normalizeIdStructurally, normalizeOrderKeys, normalizeSourceDocument, normalizeSourceValue, param, parkScheduleOutbox, parseExportShardArgs, parseImportShardArgs, planAggregateLookup, pointInBoundingBox, probeScheduleOutbox, projectColumns, pullExternalSourceIncrementalTick, pullExternalSourceTick, qualifiedJsonPath, qualifiedJsonPathSql, quoteIdentifier, rankKeyFromDocument as rankKeyFromDoc, rankPivotConditionSql, rankTableName, reactiveCacheKey, reactorNeedsRun, readAggregateValue, readArchivedCdcChanges, readAuditLog, readBookmark, readCapturedMail, readCdcArchivedThrough, readCdcChangeKeys, readCdcChanges, readCdcCursor, readCdcEpoch, readClientWatermark, readCommitSeq, readDeployInfo, readDueScheduleOutbox, readExternalSourceBaseline, readGlobalShapeSnapshot, readIdempotent, readMigrationStatus, readQueueMessageById, readQueueMessages, readReactorState, readSchemaHistory, readSchemaVersion, readSearchBackfillState, readShapePokeCursor, readStreamChunks, readStreamRun, readTablePage, recordCapturedMail, recordChangedKeys, recordFanoutPass, recordGlobalPollPass, recordQueueMessages, recordScheduleOutbox, recordSchemaVersion, recordShapeProbePass, relationHooks, relayCountFor, renderSql, reprojectableFields, reprojectionMigrationId, reprojectionTables, resolveRankPartition, resolveRankSeekTuple, resolveRelationPredicates, resolveWith, rowToDocument, runDataMigration, runDrizzle, runExternalSourceTick, runReadonlySql, runRowValidators, runShardMigrations, runSocketPool, runSql, runTriggers, selectExpiredIds, selectExportTables, selectIndexForAggregate, selectIndexForCount, selectIndexForGroupBy, selectMatchingIds, selectShapeMembers, selectShapeRows, serializeSqlValue, shapeRoutingKey, softDeleteScope, sortColumnName, sqliteInList, stableStringify, stableWireKey, stripReservedPatchFields, subscriptionFrames, subscriptionListDeltas, summarizeFanoutTopics, summarizeSubscriptions, tableColumns, tableFromDepKey, throwingScheduler, tiebreakDirectionFor, trimCdcChanges, trimIdempotent, trimScheduleOutbox, trimStreamRuns, tryRowToDocument, trySendFrame, unionAll, uniqueIndexFields, validateImportRow, writeCdcArchivedThrough, writeGlobalShapeSnapshot, writeIdempotent, writeReactorState, writeSearchBackfillState, writeShapePokeCursor, writeShapePokeCursors, writeTouchesMemo };
|
|
2453
|
+
export { ADMIN_FUNCTIONS, ADMIN_FUNCTION_PREFIX, AGGREGATE_SQL_FUNCTION, AGG_COUNT, AGG_KEY, AGG_VALUE, AUDIT_LOG_TABLE, type AdvisorProcedure, type AdvisorProceduresResult, type AdvisoriesResult, type AdvisoryFinding, type AggregateIndexDefinitionLike, type AggregateOp, type AggregateOptions, type AggregateResult, type AggregateTally, type AppendAuditEntry, type ApplyOnDeleteOptions$1 as ApplyOnDeleteOptions, type AuditEntry, type AuditLogResult, BIGINT_KEY_DIGITS, type BroadcastDelta, CDC_LOG_TABLE, CDC_LOG_TABLE_SEQ_INDEX, CDC_META_TABLE, CLIENT_WATERMARK_TABLE, COMMIT_SEQ_FIELD, COMMIT_SEQ_TABLE, CURSOR_PREFIX, type CacheEntry, type CapturedMailRow, type CdcArchiveScope, type CdcChange, type CdcChangeKey, type ChangedKeys, type Clock, type ColumnMeta, type ColumnMetaLike, type CompanionSync, type CompanionSyncDeps, ConflictError, type ConflictKind, type CountArgs, CountRlsUnsupportedError, type CreateWorkflowInstanceResult, type CrossShardReadArgs, type CtxDbOptions, DATA_MIGRATION_STATE_TABLE, DEFAULT_FANOUT_TOPIC_LIMIT, DEFAULT_MAX_RELATION_KEYS, DEFAULT_MAX_RELAYS, DEFAULT_PROMOTION_THRESHOLDS, DEFAULT_TRANSACTION_LIMITS, DOC_COLUMN, type DataMigrationDocument, type DataMigrationLike, type DataMigrationTransform, type DatabaseWriterLike, type DependencyTracker, type DeployInfo, type DurableAttachDecision, type DurableStreamAttach, type DurableStreamRun, DurableStreamRunner, type DurableStreamSink, type ExportRow, type ExportShardAdminArgs, type ExportShardArgs, type ExternalSourceDiffResult, type ExternalSourceLike, FLAGS_FUNCTION_PREFIX, type FacetColumnOptions, type FacetColumnResult, type FacetValue, type FanOutBudget, type FanoutMetricsResult, type FanoutPathCounters, type FanoutTopicStat, type FieldOperators, type FilterClause, type FilterOperator, type FlagEvaluation, type FlagsResult, type FunctionCallStat, type FunctionScanAttribution, type FunctionStatsResult, GEO_DEFAULT_PRECISION, GLOBAL_SHAPE_SNAPSHOT_TABLE, type GeoBoundingBox, type GeoFilterBuilderLike, type GeoIndexDefinitionLike, type GeoPoint, type GeoScoredDocument, type GlobalPollCounters, GlobalPollTick, type GroupByEntry, type GroupByOptions, type GuardableSchema$1 as GuardableSchema, IDEMPOTENCY_TABLE, type IdGenerator, type IdempotentRecord, type ImportError, type ImportShardAdminArgs, type ImportShardArgs, type ImportShardResult, type IncrementalMaterializeResult, type IndexDefinitionLike, type IndexKeyEntry, type IndexRangeBuilderLike, type KeyRange, type LifecycleDispatchInfo, type LifecycleEvent, MAIL_RETENTION, MAIL_TABLE, MAX_DURABLE_STREAM_BYTES, MAX_DURABLE_STREAM_CHUNKS, MAX_PAGE_SIZE, MAX_SQL_ROWS, type MaskColumnMetadata, type MaskPoliciesResult, type MaterializeResult, type MigrationDirection, type MigrationRunResult, type MigrationStatus, type MigrationStatusRow, type MutationDelta, type NestedWith, NotFoundError, NotUniqueError, type OnDeleteActionLike, type OrderByClause, type OrderByInput, type OrderKey, type OrderKeyConstraints, OwnerRelay, type OwnerRelayFrame, type PaginationOptions, type PitrBookmarkResult, type PitrRestoreArgs, type PitrRestoreResult, type PitrStorage, type PokeFrameMeta, type PromotionState, type PromotionThresholds, QUEUE_TABLE, type QueryArgs, type QueryPage, type QueueMessageOutcome, type QueueMessageRow, type QueueMetadata, type QueuesResult, RANK_TIEBREAK, REACTOR_STATE_TABLE, RELATED_DEFAULT_LIMIT, RELATED_DEPTH_DECAY, RELATED_MAX_DEPTH, RELATED_MAX_LIMIT, RELATION_EXISTS_KEY, RELATION_FUNCTION_PREFIX, REPROJECTION_MIGRATION_PREFIX, RLS_UNWRAP_SYMBOL, type RankBeforeOptions, type RankBeforeResult, type RankDirection, type RankIndexDefinitionLike, type RankOptions, type RankPage, type RankPageComputation, type RankPageDeps, type RankPageOptions, type RankPageRow, type RankPageRowKey, type RankResult, type RankSortKeyLike, ReactiveCache, type ReactiveCacheOptions, type ReactorDispatchResult, type ReactorMetadata, type ReactorState, type ReactorStats, type ReactorsResult, type ReadFootprint, type ReadHook, type ReadTablePageOptions, type RecordMailInput, type RecordQueueMessageInput, type RelatedDirection, type RelatedNode, type RelatedOptions, type RelatedPage, type RelatedStart, type RelatedStartReference, type RelationDefinitionLike, type RelationEdge, type RelationExistsMarker, type RelationGraphReader, type RelayAttach, type RelayDetach, type RelayFrame, type RelayHost, RelayMember, type RelayPokeDelivery, type RelayShapePoke, type RelayShapeSeed, type RelayShapeSubscribe, type RelayShapeUnsubscribe, type RenderedSql, type ReplicaFollowerHost, type ReplicaOwnerHost, type ReplicaReadiness, type ResolveRelationPredicatesOptions, type ResolveWithOptions, type ResolveWithResult, type ResolvedShape, type RestrictableQueryOptions, type RlsPoliciesResult, type RlsPolicyMetadata, RlsRequiredError, type RlsRoleMetadata, type RpcRequest, type RunDataMigrationOptions, type RunTriggersOptions, SCAN_DEP, SCHEDULE_OUTBOX_TABLE, SCHEMA_HISTORY_MAX_VERSIONS, SEARCH_STATE_TABLE, SHAPE_POKE_CURSOR_TABLE, type SchedulableWorkflowReferenceLike, type ScheduleOutbox, type ScheduleOutboxEnvelope, type ScheduleOutboxRow, type ScheduledFunctionDoc, type SchedulerLike, type SchemaLike, type ScoredDocument, type SearchBackfillProgress, type SearchFilterBuilderLike, type SearchIndexDefinitionLike, type SearchScoredDocument, type SelectMatchingIdsOptions, type ServerDefaultContextLike, type SettingEntry, type SettingKind, type SettingsResult, ShapeDiffCache, type ShapePokeCursorRow, type ShapePokePart, type ShapeProbeCounters, type ShapeRow, type ShapeRowOp, type ShapeSubscriptionQuery, type ShardRankPageResult, ShardRunner, type ShardRunnerOptions, type ShardSiblingHost, type ShardSocketLike, type SocketAttachment, type SortDirection, type SourceClientLike, type SourceCursorLike, type SourceRefresh, type SqlConsoleResult, type SqlCursor, type SqlEngine, type SqlExec, type SqlLintResult, type StorageMetadata, type StorageReference, type StorageReferenceResult, type StorageRuleMetadata, type StorageRulesResult, type StudioFeaturesResult, type SubscriptionConnection, type SubscriptionEnvelope, type SubscriptionIdentity, type SubscriptionInfo, type SubscriptionQuery, type SubscriptionReadFootprint, type SubscriptionsResult, type SystemDatabaseReader, type SystemDoc, type SystemQuery, type SystemReaderOptions, type SystemReaderSchedulerLike, type SystemReaderStorageLike, type SystemTableName, type TableColumnsResult, type TableDefinitionLike, type TableIndexInfo, type TableIndexesResult, type TableInfo, type TablePage, type TableReaderLike, type TablesColumnsResult, type TablesIndexesResult, type TransactionHeadroom, TransactionHeadroomTracker, type TransactionLimits, type TransactionSqlLike, type TriggerContextLike, type TriggerDefinitionLike, type TriggerEventLike, type TriggerOpLike, type TriggerTimingLike, type TtlSweepSpec, UNVOUCHABLE_DEP, type ValidatorLike, type WhereInput, type WhereSqlStrategy, type WithInput, type WorkflowInstanceState, type WorkflowInstanceStatusResult, type WorkflowMetadata, type WorkflowsResult, type WriteEvent, type WriteHook, advanceClientWatermark, aggUpsertSql, aggregateSqlFunction, aggregateTableName, allocateCommitSeq, appendAuditEntry, appendCdcChange, appendStreamChunk, applyCdcChanges, applyOnDelete, applySelect, archiveCdcSegment, armRestore, assertFlatPredicate, assertNoExplicitUndefined, assertReadonly, assertShapeShardable, assertValidClientId, awaitWsDrain, backfillAggregateIndexes, backfillRankIndexes, backfillSearchIndexes, backfillSearchIndexesForTable, bigintSqlKey, boundingBoxCenter, boundingBoxGeohashes, buildIndexRange, buildPokeFrames, buildReprojectionMigration, buildSeekBeforeWhere, buildSeekWhere, buildSettings, buildShapeDiff, bumpCdcEpoch, 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, gateReplicaDispatch, geoTableName, globalShapeReadKey, guardWriter, handleReplicaControl, hasTrigger, haversineMeters, importShardRows, indexKeysForRow, isDevEnvironment, isFtsAvailable, isLossyBody, isMemoryTable, isRelationPredicate, isSoftDeleted, isSourceDue, jsonPath, jsonPathSql, keysTouchRanges, liftSourceId, lintReadonlySql, listReactorStates, listTables, literalInList, markUnvouchableReads, matchesRankStaticWhere, matchesStaticWhere, materializeExternalRows, materializeExternalRowsIncremental, memoryTableNames, mergeChangedKeys, mergeWhere, migrateCdcLog, migrateCdcMeta, migrateClientWatermark, migrateCommitSeq, migrateDurableStreams, migrateGlobalShapeSnapshot, migrateIdempotency, migrateReactorState, migrateScheduleOutbox, migrateSearchState, migrateShapePokeCursor, minCdcReplayableSeq, minCdcSeq, minShapePokeCursor, nextPromotionState, normalizeCountArgument, normalizeIdStructurally, normalizeOrderKeys, normalizeSourceDocument, normalizeSourceValue, param, parkScheduleOutbox, parseExportShardArgs, parseImportShardArgs, planAggregateLookup, pointInBoundingBox, probeScheduleOutbox, projectColumns, pullExternalSourceIncrementalTick, pullExternalSourceTick, qualifiedJsonPath, qualifiedJsonPathSql, quoteIdentifier, rankKeyFromDocument as rankKeyFromDoc, rankPivotConditionSql, rankTableName, reactiveCacheKey, reactorNeedsRun, readAggregateValue, readArchivedCdcChanges, readAuditLog, readBookmark, readCapturedMail, readCdcArchivedThrough, readCdcChangeKeys, readCdcChanges, readCdcCursor, readCdcEpoch, readClientWatermark, readCommitSeq, readDeployInfo, readDueScheduleOutbox, readExternalSourceBaseline, readGlobalShapeSnapshot, readIdempotent, readMigrationStatus, readQueueMessageById, readQueueMessages, readReactorState, readSchemaHistory, readSchemaVersion, readSearchBackfillState, readShapePokeCursor, readStreamChunks, readStreamRun, readTablePage, recordCapturedMail, recordChangedKeys, recordFanoutPass, recordGlobalPollPass, recordQueueMessages, recordScheduleOutbox, recordSchemaVersion, recordShapeProbePass, relationHooks, relayCountFor, renderSql, reprojectableFields, reprojectionMigrationId, reprojectionTables, resolveRankPartition, resolveRankSeekTuple, resolveRelationPredicates, resolveWith, rowToDocument, runDataMigration, runDrizzle, runExternalSourceTick, runReadonlySql, runRowValidators, runShardMigrations, runSocketPool, runSql, runTriggers, selectExpiredIds, selectExportTables, selectIndexForAggregate, selectIndexForCount, selectIndexForGroupBy, selectMatchingIds, selectShapeMembers, selectShapeRows, serializeSqlValue, shapeRoutingKey, softDeleteScope, sortColumnName, sqliteInList, stableStringify, stableWireKey, stripReservedPatchFields, subscriptionFrames, subscriptionListDeltas, summarizeFanoutTopics, summarizeSubscriptions, tableColumns, tableFromDepKey, throwingScheduler, tiebreakDirectionFor, trimCdcChanges, trimIdempotent, trimScheduleOutbox, trimStreamRuns, tryRowToDocument, trySendFrame, unionAll, uniqueIndexFields, validateImportRow, writeCdcArchivedThrough, writeGlobalShapeSnapshot, writeIdempotent, writeReactorState, writeSearchBackfillState, writeShapePokeCursor, writeShapePokeCursors, writeTouchesMemo };
|
package/dist/index.mjs
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{exportShardRows as o,importShardRows as a,parseExportShardArgs as t,parseImportShardArgs as i,selectExportTables as l,validateImportRow as n}from"./packem_shared/exportShardRows-1TkeNJI6.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 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 O,ensureAuditTable as P,readAuditLog as M}from"./packem_shared/AUDIT_LOG_TABLE-ONxmEAIz.mjs";import{NotUniqueError as F,assertNoExplicitUndefined as N,assertValidClientId as k,createShardCtxDb as B,normalizeIdStructurally as U,stripReservedPatchFields as G}from"./packem_shared/NotUniqueError-CzcG-VF9.mjs";import{backfillAggregateIndexes as K,backfillRankIndexes as v,backfillSearchIndexes as w,backfillSearchIndexesForTable as X}from"./packem_shared/backfillAggregateIndexes-BG5-SC1q.mjs";import{CDC_LOG_TABLE as W,CDC_LOG_TABLE_SEQ_INDEX as z,CDC_META_TABLE as V,appendCdcChange as Q,applyCdcChanges as Y,bumpCdcEpoch as j,cdcCanVouchFor as J,cdcSeqLeavingRows as Z,cdcTouchesTables as $,cdcTrimmedError as ee,compactCdcDocs as re,cursorBelowRetainedFloor as oe,migrateCdcLog as ae,migrateCdcMeta as te,minCdcReplayableSeq as ie,minCdcSeq as le,readCdcChangeKeys as ne,readCdcChanges as se,readCdcCursor as de,readCdcEpoch as ce,trimCdcChanges as me}from"./packem_shared/CDC_LOG_TABLE-vVheEulD.mjs";import{archiveCdcSegment as Se,readArchivedCdcChanges as ue,readCdcArchivedThrough as fe,writeCdcArchivedThrough as Ee}from"./packem_shared/archiveCdcSegment-DU4uzDFQ.mjs";import{CLIENT_WATERMARK_TABLE as xe,advanceClientWatermark as Te,migrateClientWatermark as Ce,readClientWatermark as Re}from"./packem_shared/CLIENT_WATERMARK_TABLE-CRnrAnJ2.mjs";import{COMMIT_SEQ_FIELD as ge,COMMIT_SEQ_TABLE as _e,allocateCommitSeq as Ie,migrateCommitSeq as be,readCommitSeq as Le}from"./packem_shared/COMMIT_SEQ_FIELD-BUdOMG5y.mjs";import{c as Oe}from"./packem_shared/ctx-db-companions-w-CfeOda.mjs";import{GLOBAL_SHAPE_SNAPSHOT_TABLE as Me,deleteGlobalShapeSnapshot as ye,deleteGlobalShapeSnapshotsForConnection as Fe,migrateGlobalShapeSnapshot as Ne,readGlobalShapeSnapshot as ke,writeGlobalShapeSnapshot as Be}from"./packem_shared/GLOBAL_SHAPE_SNAPSHOT_TABLE-DSA6mzyx.mjs";import{IDEMPOTENCY_TABLE as Ge,migrateIdempotency as qe,readIdempotent as Ke,trimIdempotent as ve,writeIdempotent as we}from"./packem_shared/IDEMPOTENCY_TABLE-DOpm_oMF.mjs";import{clearMemoryTables as He,isMemoryTable as We,memoryTableNames as ze}from"./packem_shared/clearMemoryTables-BGbmag2i.mjs";import{computeRankPage as Qe,resolveRankSeekTuple as Ye}from"./packem_shared/computeRankPage-DsQ16o1z.mjs";import{SCHEDULE_OUTBOX_TABLE as Je,deferScheduleOutbox as Ze,forgetScheduleOutbox as $e,migrateScheduleOutbox as er,parkScheduleOutbox as rr,probeScheduleOutbox as or,readDueScheduleOutbox as ar,recordScheduleOutbox as tr,trimScheduleOutbox as ir}from"./packem_shared/SCHEDULE_OUTBOX_TABLE-CD_UjYVx.mjs";import{S as nr,m as sr,r as dr,w as cr}from"./packem_shared/ctx-db-search-state-ruTuCsxa.mjs";import{SHAPE_POKE_CURSOR_TABLE as pr,deleteShapePokeCursor as Sr,deleteShapePokeCursorsForConnection as ur,migrateShapePokeCursor as fr,minShapePokeCursor as Er,readShapePokeCursor as hr,writeShapePokeCursor as xr,writeShapePokeCursors as Tr}from"./packem_shared/SHAPE_POKE_CURSOR_TABLE-ByJVDHds.mjs";import{selectShapeMembers as Rr,selectShapeRows as Ar}from"./packem_shared/selectShapeMembers-CCZyZggM.mjs";import{DATA_MIGRATION_STATE_TABLE as _r,readMigrationStatus as Ir,runDataMigration as br}from"./packem_shared/DATA_MIGRATION_STATE_TABLE-BwFz6NTT.mjs";import{SCAN_DEP as Dr,createDependencyTracker as Or,depKey as Pr,tableFromDepKey as Mr}from"./packem_shared/SCAN_DEP-D7qE3iUe.mjs";import{runDrizzle as Fr,runSql as Nr}from"./packem_shared/runDrizzle-2ULFQR_k.mjs";import{A as Br,a as Ur,b as Gr,D as qr,c as Kr,d as vr,g as wr,i as Xr,j as Hr,e as Wr,q as zr,f as Vr,r as Qr,t as Yr,h as jr}from"./packem_shared/do-sql-Dvj8Yl5N.mjs";import{param as Zr,renderSql as $r,sqliteInList as eo,unionAll as ro}from"./packem_shared/param-DlozcSQu.mjs";import{appendStreamChunk as ao,claimStreamRun as to,deleteStreamRun as io,finishStreamRun as lo,migrateDurableStreams as no,readStreamChunks as so,readStreamRun as co,trimStreamRuns as mo}from"./packem_shared/appendStreamChunk-C1Ok4b6J.mjs";import{DurableStreamRunner as So,MAX_DURABLE_STREAM_BYTES as uo,MAX_DURABLE_STREAM_CHUNKS as fo,decideDurableAttach as Eo}from"./packem_shared/DurableStreamRunner-rTYp4v03.mjs";import{envOptionalPositiveInt as xo,envPositiveInt as To}from"./packem_shared/envOptionalPositiveInt-D2pY-c64.mjs";import{diffExternalSource as Ro}from"./packem_shared/diffExternalSource-DgDJhslq.mjs";import{liftSourceId as go,normalizeSourceDocument as _o,normalizeSourceValue as Io}from"./packem_shared/liftSourceId-CA3ENhXj.mjs";import{materializeExternalRows as Lo,materializeExternalRowsIncremental as Do,readExternalSourceBaseline as Oo,runExternalSourceTick as Po}from"./packem_shared/materializeExternalRows-iEVQKOKT.mjs";import{isSoftDeleted as yo,isSourceDue as Fo,pullExternalSourceIncrementalTick as No,pullExternalSourceTick as ko}from"./packem_shared/isSoftDeleted-CYf6ijO3.mjs";import{GEO_DEFAULT_PRECISION as Uo,boundingBoxCenter as Go,boundingBoxGeohashes as qo,coveringGeohashes as Ko,encodeGeohash as vo,haversineMeters as wo,pointInBoundingBox as Xo}from"./packem_shared/GEO_DEFAULT_PRECISION-CqpQZ-J_.mjs";import{default as Wo}from"./packem_shared/GlobalPollTick-BNK4o-XT.mjs";import{ADMIN_FUNCTIONS as Vo,ADMIN_FUNCTION_PREFIX as Qo,DEFAULT_FANOUT_TOPIC_LIMIT as Yo,FLAGS_FUNCTION_PREFIX as jo,MAX_PAGE_SIZE as Jo,RELATION_FUNCTION_PREFIX as Zo,createFanoutCounters as $o,createGlobalPollCounters as ea,createShapeProbeCounters as ra,facetColumn as oa,findStorageReferences as aa,listTables as ta,readTablePage as ia,recordFanoutPass as la,recordGlobalPollPass as na,recordShapeProbePass as sa,selectMatchingIds as da,summarizeFanoutTopics as ca,summarizeSubscriptions as ma}from"./packem_shared/ADMIN_FUNCTIONS-INdhzK8S.mjs";import{MAIL_RETENTION as Sa,MAIL_TABLE as ua,clearCapturedMail as fa,ensureMailTable as Ea,readCapturedMail as ha,recordCapturedMail as xa}from"./packem_shared/MAIL_RETENTION-DGAQTHHs.mjs";import{NotFoundError as Ca}from"./packem_shared/NotFoundError-BhF7FeFr.mjs";import{armRestore as Aa,readBookmark as ga}from"./packem_shared/armRestore-Bu1_8SUa.mjs";import{CURSOR_PREFIX as Ia,applySelect as ba,buildSeekBeforeWhere as La,buildSeekWhere as Da,decodeCursor as Oa,encodeCursor as Pa,equalityPinnedFields as Ma,normalizeOrderKeys as ya,softDeleteScope as Fa,tiebreakDirectionFor as Na,uniqueIndexFields as ka}from"./packem_shared/CURSOR_PREFIX-Bn8SFoGd.mjs";import{QUEUE_TABLE as Ua,clearQueueMessages as Ga,isLossyBody as qa,readQueueMessageById as Ka,readQueueMessages as va,recordQueueMessages as wa}from"./packem_shared/QUEUE_TABLE-s7QJZvBz.mjs";import{RANK_TIEBREAK as Ha,encodePartitionKey as Wa,matchesRankStaticWhere as za,rankKeyFromDoc as Va,rankPivotConditionSql as Qa,rankTableName as Ya,resolveRankPartition as ja,sortColumnName as Ja}from"./packem_shared/RANK_TIEBREAK-BXDiMmkH.mjs";import{ReactiveCache as $a,reactiveCacheKey as et}from"./packem_shared/ReactiveCache-CzeUmTTN.mjs";import{REACTOR_STATE_TABLE as ot,listReactorStates as at,migrateReactorState as tt,reactorNeedsRun as it,readReactorState as lt,writeReactorState as nt}from"./packem_shared/REACTOR_STATE_TABLE-QPRFyxMS.mjs";import{UNVOUCHABLE_DEP as dt,createReadFootprint as ct,markUnvouchableReads as mt}from"./packem_shared/UNVOUCHABLE_DEP-C68htACn.mjs";import{buildIndexRange as St,indexKeysForRow as ut,keysTouchRanges as ft}from"./packem_shared/buildIndexRange-NtciKq3M.mjs";import{RELATED_DEFAULT_LIMIT as ht,RELATED_DEPTH_DECAY as xt,RELATED_MAX_DEPTH as Tt,RELATED_MAX_LIMIT as Ct,deriveRelationEdges as Rt,findRelated as At}from"./packem_shared/RELATED_DEFAULT_LIMIT-B9PH28Pn.mjs";import{DEFAULT_MAX_RELATION_KEYS as _t,assertFlatPredicate as It,assertShapeShardable as bt,containsRelationPredicate as Lt,isRelationPredicate as Dt,resolveRelationPredicates as Ot}from"./packem_shared/DEFAULT_MAX_RELATION_KEYS-XESc7TiB.mjs";import{applyOnDelete as Mt,distinctValues as yt,fanOutScalarCounts as Ft,relationHooks as Nt,resolveWith as kt,runRowValidators as Bt}from"./packem_shared/applyOnDelete-7JZ4vR9r.mjs";import{DEFAULT_PROMOTION_THRESHOLDS as Gt,clampPromotionThresholds as qt,nextPromotionState as Kt,relayCountFor as vt,shapeRoutingKey as wt}from"./packem_shared/DEFAULT_PROMOTION_THRESHOLDS-Bfx7KakS.mjs";import{DEFAULT_MAX_RELAYS as Ht,OwnerRelay as Wt,RelayMember as zt,createRelayLink as Vt}from"./packem_shared/DEFAULT_MAX_RELAYS-Ng4SyJ7k.mjs";import{createReplicaLink as Yt,gateReplicaDispatch as jt,handleReplicaControl as Jt}from"./packem_shared/createReplicaLink-Bo4IWADY.mjs";import{buildReprojectionMigration as $t,countLegacyRows as ei,reprojectableFields as ri,reprojectionTables as oi}from"./packem_shared/buildReprojectionMigration-Coeg-J0M.mjs";import{RLS_UNWRAP_SYMBOL as ti,RlsRequiredError as ii,guardWriter as li}from"./packem_shared/RLS_UNWRAP_SYMBOL-BwwTbz3Q.mjs";import{SCHEMA_HISTORY_MAX_VERSIONS as si,readSchemaHistory as di,readSchemaVersion as ci,recordSchemaVersion as mi}from"./packem_shared/SCHEMA_HISTORY_MAX_VERSIONS-BluIj2s-.mjs";import{serializeSqlValue as Si}from"./packem_shared/serializeSqlValue-CjbhIHjJ.mjs";import{buildSettings as fi,isDevEnvironment as Ei,readDeployInfo as hi}from"./packem_shared/buildSettings-DC3VeQ0H.mjs";import{buildShapeDiff as Ti}from"./packem_shared/buildShapeDiff-WSoMs1_h.mjs";import{ShapeDiffCache as Ri,createShapeDiffCache as Ai,globalShapeReadKey as gi}from"./packem_shared/ShapeDiffCache-gdaILV5E.mjs";import{buildPokeFrames as Ii,diffGlobalMembership as bi,encodeRowsPatch as Li,projectColumns as Di}from"./packem_shared/buildPokeFrames-BBE6J91z.mjs";import{ShardRunner as Pi}from"./packem_shared/ShardRunner-C9p5DVOx.mjs";import{runSocketPool as yi}from"./packem_shared/runSocketPool-CZJ2X9cF.mjs";import{MAX_SQL_ROWS as Ni,assertReadonly as ki,lintReadonlySql as Bi,runReadonlySql as Ui}from"./packem_shared/MAX_SQL_ROWS-Dh_Ty0Zo.mjs";import{B as qi,b as Ki,d as vi,a as wi,f as Xi}from"./packem_shared/sql-projection-BB2lCbYV.mjs";import{awaitWsDrain as Wi,subscriptionFrames as zi,subscriptionListDeltas as Vi,trySendFrame as Qi}from"./packem_shared/awaitWsDrain-apizgmKY.mjs";import{mergeChangedKeys as ji,recordChangedKeys as Ji,writeTouchesMemo as Zi}from"./packem_shared/mergeChangedKeys-CPw4EamV.mjs";import{createSystemReader as el}from"./packem_shared/createSystemReader-DcDLFfC-.mjs";import{ConflictError as ol}from"./packem_shared/ConflictError-C8GtJmjS.mjs";import{DEFAULT_TRANSACTION_LIMITS as tl,TransactionHeadroomTracker as il}from"./packem_shared/DEFAULT_TRANSACTION_LIMITS-DDGk9ebh.mjs";import{hasTrigger as nl,runTriggers as sl}from"./packem_shared/hasTrigger-CjlwI4le.mjs";import{selectExpiredIds as cl}from"./packem_shared/selectExpiredIds-CKOUTIHn.mjs";import{c as pl,l as Sl}from"./packem_shared/where-sql-x1YKldcq.mjs";import{RELATION_EXISTS_KEY as fl}from"./packem_shared/RELATION_EXISTS_KEY-CFUhnZSZ.mjs";import{REPROJECTION_MIGRATION_PREFIX as hl,reprojectionMigrationId as xl}from"./packem_shared/REPROJECTION_MIGRATION_PREFIX-Czcb6_mO.mjs";import{quoteIdentifier as Cl}from"./packem_shared/quoteIdentifier-CObIFRhb.mjs";import{runShardMigrations as Al}from"./packem_shared/runShardMigrations-DbQJdY1X.mjs";import{stableStringify as _l}from"./packem_shared/stableStringify-DibjylKD.mjs";import{stableWireKey as bl}from"./packem_shared/stableWireKey-D2US4k_J.mjs";export{Vo as ADMIN_FUNCTIONS,Qo as ADMIN_FUNCTION_PREFIX,d as AGGREGATE_SQL_FUNCTION,Br as AGG_COUNT,Ur as AGG_KEY,Gr as AGG_VALUE,D as AUDIT_LOG_TABLE,qi as BIGINT_KEY_DIGITS,W as CDC_LOG_TABLE,z as CDC_LOG_TABLE_SEQ_INDEX,V as CDC_META_TABLE,xe as CLIENT_WATERMARK_TABLE,ge as COMMIT_SEQ_FIELD,_e as COMMIT_SEQ_TABLE,Ia as CURSOR_PREFIX,ol as ConflictError,R as CountRlsUnsupportedError,_r as DATA_MIGRATION_STATE_TABLE,Yo as DEFAULT_FANOUT_TOPIC_LIMIT,_t as DEFAULT_MAX_RELATION_KEYS,Ht as DEFAULT_MAX_RELAYS,Gt as DEFAULT_PROMOTION_THRESHOLDS,tl as DEFAULT_TRANSACTION_LIMITS,qr as DOC_COLUMN,So as DurableStreamRunner,jo as FLAGS_FUNCTION_PREFIX,Uo as GEO_DEFAULT_PRECISION,Me as GLOBAL_SHAPE_SNAPSHOT_TABLE,Wo as GlobalPollTick,Ge as IDEMPOTENCY_TABLE,Sa as MAIL_RETENTION,ua as MAIL_TABLE,uo as MAX_DURABLE_STREAM_BYTES,fo as MAX_DURABLE_STREAM_CHUNKS,Jo as MAX_PAGE_SIZE,Ni as MAX_SQL_ROWS,Ca as NotFoundError,F as NotUniqueError,Wt as OwnerRelay,Ua as QUEUE_TABLE,Ha as RANK_TIEBREAK,ot as REACTOR_STATE_TABLE,ht as RELATED_DEFAULT_LIMIT,xt as RELATED_DEPTH_DECAY,Tt as RELATED_MAX_DEPTH,Ct as RELATED_MAX_LIMIT,fl as RELATION_EXISTS_KEY,Zo as RELATION_FUNCTION_PREFIX,hl as REPROJECTION_MIGRATION_PREFIX,ti as RLS_UNWRAP_SYMBOL,$a as ReactiveCache,zt as RelayMember,ii as RlsRequiredError,Dr as SCAN_DEP,Je as SCHEDULE_OUTBOX_TABLE,si as SCHEMA_HISTORY_MAX_VERSIONS,nr as SEARCH_STATE_TABLE,pr as SHAPE_POKE_CURSOR_TABLE,Ri as ShapeDiffCache,Pi as ShardRunner,il as TransactionHeadroomTracker,dt as UNVOUCHABLE_DEP,Te as advanceClientWatermark,Kr as aggUpsertSql,c as aggregateSqlFunction,f as aggregateTableName,Ie as allocateCommitSeq,O as appendAuditEntry,Q as appendCdcChange,ao as appendStreamChunk,Y as applyCdcChanges,Mt as applyOnDelete,ba as applySelect,Se as archiveCdcSegment,Aa as armRestore,It as assertFlatPredicate,N as assertNoExplicitUndefined,ki as assertReadonly,bt as assertShapeShardable,k as assertValidClientId,Wi as awaitWsDrain,K as backfillAggregateIndexes,v as backfillRankIndexes,w as backfillSearchIndexes,X as backfillSearchIndexesForTable,Ki as bigintSqlKey,Go as boundingBoxCenter,qo as boundingBoxGeohashes,St as buildIndexRange,Ii as buildPokeFrames,$t as buildReprojectionMigration,La as buildSeekBeforeWhere,Da as buildSeekWhere,fi as buildSettings,Ti as buildShapeDiff,j as bumpCdcEpoch,J as cdcCanVouchFor,Z as cdcSeqLeavingRows,$ as cdcTouchesTables,ee as cdcTrimmedError,to as claimStreamRun,qt as clampPromotionThresholds,fa as clearCapturedMail,He as clearMemoryTables,Ga as clearQueueMessages,E as coerceAggregateNumber,re as compactCdcDocs,pl as compileWhereSql,Qe as computeRankPage,Lt as containsRelationPredicate,ei as countLegacyRows,Ko as coveringGeohashes,Oe as createCompanionSync,Or as createDependencyTracker,$o as createFanoutCounters,ea as createGlobalPollCounters,vr as createIndexSql,ct as createReadFootprint,Vt as createRelayLink,Yt as createReplicaLink,Ai as createShapeDiffCache,ra as createShapeProbeCounters,B as createShardCtxDb,el as createSystemReader,oe as cursorBelowRetainedFloor,Eo as decideDurableAttach,vi as decodeBigintSqlKey,Oa as decodeCursor,wi as decodeFloat64SqlKey,Ze as deferScheduleOutbox,ye as deleteGlobalShapeSnapshot,Fe as deleteGlobalShapeSnapshotsForConnection,Sr as deleteShapePokeCursor,ur as deleteShapePokeCursorsForConnection,io as deleteStreamRun,Pr as depKey,Rt as deriveRelationEdges,Ro as diffExternalSource,bi as diffGlobalMembership,yt as distinctValues,h as encodeAggregateKey,Pa as encodeCursor,vo as encodeGeohash,Wa as encodePartitionKey,Li as encodeRowsPatch,P as ensureAuditTable,Ea as ensureMailTable,xo as envOptionalPositiveInt,To as envPositiveInt,Ma as equalityPinnedFields,o as exportShardRows,oa as facetColumn,Ft as fanOutScalarCounts,At as findRelated,aa as findStorageReferences,lo as finishStreamRun,Xi as float64SqlKey,x as foldAggregateTally,$e as forgetScheduleOutbox,jt as gateReplicaDispatch,wr as geoTableName,gi as globalShapeReadKey,li as guardWriter,Jt as handleReplicaControl,nl as hasTrigger,wo as haversineMeters,a as importShardRows,ut as indexKeysForRow,Ei as isDevEnvironment,Xr as isFtsAvailable,qa as isLossyBody,We as isMemoryTable,Dt as isRelationPredicate,yo as isSoftDeleted,Fo as isSourceDue,Hr as jsonPath,Wr as jsonPathSql,ft as keysTouchRanges,go as liftSourceId,Bi as lintReadonlySql,at as listReactorStates,ta as listTables,Sl as literalInList,mt as markUnvouchableReads,za as matchesRankStaticWhere,m as matchesStaticWhere,Lo as materializeExternalRows,Do as materializeExternalRowsIncremental,ze as memoryTableNames,ji as mergeChangedKeys,A as mergeWhere,ae as migrateCdcLog,te as migrateCdcMeta,Ce as migrateClientWatermark,be as migrateCommitSeq,no as migrateDurableStreams,Ne as migrateGlobalShapeSnapshot,qe as migrateIdempotency,tt as migrateReactorState,er as migrateScheduleOutbox,sr as migrateSearchState,fr as migrateShapePokeCursor,ie as minCdcReplayableSeq,le as minCdcSeq,Er as minShapePokeCursor,Kt as nextPromotionState,p as normalizeCountArgument,U as normalizeIdStructurally,ya as normalizeOrderKeys,_o as normalizeSourceDocument,Io as normalizeSourceValue,Zr as param,rr as parkScheduleOutbox,t as parseExportShardArgs,i as parseImportShardArgs,g as planAggregateLookup,Xo as pointInBoundingBox,or as probeScheduleOutbox,Di as projectColumns,No as pullExternalSourceIncrementalTick,ko as pullExternalSourceTick,zr as qualifiedJsonPath,Vr as qualifiedJsonPathSql,Cl as quoteIdentifier,Va as rankKeyFromDoc,Qa as rankPivotConditionSql,Ya as rankTableName,et as reactiveCacheKey,it as reactorNeedsRun,T as readAggregateValue,ue as readArchivedCdcChanges,M as readAuditLog,ga as readBookmark,ha as readCapturedMail,fe as readCdcArchivedThrough,ne as readCdcChangeKeys,se as readCdcChanges,de as readCdcCursor,ce as readCdcEpoch,Re as readClientWatermark,Le as readCommitSeq,hi as readDeployInfo,ar as readDueScheduleOutbox,Oo as readExternalSourceBaseline,ke as readGlobalShapeSnapshot,Ke as readIdempotent,Ir as readMigrationStatus,Ka as readQueueMessageById,va as readQueueMessages,lt as readReactorState,di as readSchemaHistory,ci as readSchemaVersion,dr as readSearchBackfillState,hr as readShapePokeCursor,so as readStreamChunks,co as readStreamRun,ia as readTablePage,xa as recordCapturedMail,Ji as recordChangedKeys,la as recordFanoutPass,na as recordGlobalPollPass,wa as recordQueueMessages,tr as recordScheduleOutbox,mi as recordSchemaVersion,sa as recordShapeProbePass,Nt as relationHooks,vt as relayCountFor,$r as renderSql,ri as reprojectableFields,xl as reprojectionMigrationId,oi as reprojectionTables,ja as resolveRankPartition,Ye as resolveRankSeekTuple,Ot as resolveRelationPredicates,kt as resolveWith,Qr as rowToDocument,br as runDataMigration,Fr as runDrizzle,Po as runExternalSourceTick,Ui as runReadonlySql,Bt as runRowValidators,Al as runShardMigrations,yi as runSocketPool,Nr as runSql,sl as runTriggers,cl as selectExpiredIds,l as selectExportTables,_ as selectIndexForAggregate,I as selectIndexForCount,b as selectIndexForGroupBy,da as selectMatchingIds,Rr as selectShapeMembers,Ar as selectShapeRows,Si as serializeSqlValue,wt as shapeRoutingKey,Fa as softDeleteScope,Ja as sortColumnName,eo as sqliteInList,_l as stableStringify,bl as stableWireKey,G as stripReservedPatchFields,zi as subscriptionFrames,Vi as subscriptionListDeltas,ca as summarizeFanoutTopics,ma as summarizeSubscriptions,Yr as tableColumns,Mr as tableFromDepKey,S as throwingScheduler,Na as tiebreakDirectionFor,me as trimCdcChanges,ve as trimIdempotent,ir as trimScheduleOutbox,mo as trimStreamRuns,jr as tryRowToDocument,Qi as trySendFrame,ro as unionAll,ka as uniqueIndexFields,n as validateImportRow,Ee as writeCdcArchivedThrough,Be as writeGlobalShapeSnapshot,we as writeIdempotent,nt as writeReactorState,cr as writeSearchBackfillState,xr as writeShapePokeCursor,Tr as writeShapePokeCursors,Zi as writeTouchesMemo};
|
|
1
|
+
import{exportShardRows as o,importShardRows as a,parseExportShardArgs as t,parseImportShardArgs as i,selectExportTables as l,validateImportRow as n}from"./packem_shared/exportShardRows-1TkeNJI6.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 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 O,ensureAuditTable as P,readAuditLog as M}from"./packem_shared/AUDIT_LOG_TABLE-ONxmEAIz.mjs";import{NotUniqueError as F,assertNoExplicitUndefined as k,assertValidClientId as N,createShardCtxDb as B,normalizeIdStructurally as U,stripReservedPatchFields as G}from"./packem_shared/NotUniqueError-DpTK0ULs.mjs";import{backfillAggregateIndexes as v,backfillRankIndexes as w,backfillSearchIndexes as K,backfillSearchIndexesForTable as X}from"./packem_shared/backfillAggregateIndexes-DTemznr7.mjs";import{CDC_LOG_TABLE as W,CDC_LOG_TABLE_SEQ_INDEX as z,CDC_META_TABLE as V,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 le,minCdcSeq as ne,readCdcChangeKeys as se,readCdcChanges as de,readCdcCursor as ce,readCdcEpoch as me,trimCdcChanges as pe}from"./packem_shared/CDC_LOG_TABLE-CfILante.mjs";import{archiveCdcSegment as ue,cdcArchiveRewound as fe,readArchivedCdcChanges as Ee,readCdcArchivedThrough as he,writeCdcArchivedThrough as xe}from"./packem_shared/archiveCdcSegment-E_R_b5Qz.mjs";import{CLIENT_WATERMARK_TABLE as Ce,advanceClientWatermark as Re,migrateClientWatermark as Ae,readClientWatermark as ge}from"./packem_shared/CLIENT_WATERMARK_TABLE-CRnrAnJ2.mjs";import{COMMIT_SEQ_FIELD as Ie,COMMIT_SEQ_TABLE as be,allocateCommitSeq as Le,migrateCommitSeq as De,readCommitSeq as Oe}from"./packem_shared/COMMIT_SEQ_FIELD-BUdOMG5y.mjs";import{c as Me}from"./packem_shared/ctx-db-companions-DsNfXSbb.mjs";import{GLOBAL_SHAPE_SNAPSHOT_TABLE as Fe,deleteGlobalShapeSnapshot as ke,deleteGlobalShapeSnapshotsForConnection as Ne,migrateGlobalShapeSnapshot as Be,readGlobalShapeSnapshot as Ue,writeGlobalShapeSnapshot as Ge}from"./packem_shared/GLOBAL_SHAPE_SNAPSHOT_TABLE-DSA6mzyx.mjs";import{IDEMPOTENCY_TABLE as ve,migrateIdempotency as we,readIdempotent as Ke,trimIdempotent as Xe,writeIdempotent as He}from"./packem_shared/IDEMPOTENCY_TABLE-DOpm_oMF.mjs";import{clearMemoryTables as ze,isMemoryTable as Ve,memoryTableNames as Qe}from"./packem_shared/clearMemoryTables-BGbmag2i.mjs";import{computeRankPage as je,resolveRankSeekTuple as Je}from"./packem_shared/computeRankPage-pTaG_r9F.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 lr,trimScheduleOutbox as nr}from"./packem_shared/SCHEDULE_OUTBOX_TABLE-CD_UjYVx.mjs";import{S as dr,m as cr,r as mr,w as pr}from"./packem_shared/ctx-db-search-state-ruTuCsxa.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 Cr,writeShapePokeCursors as Rr}from"./packem_shared/SHAPE_POKE_CURSOR_TABLE-ByJVDHds.mjs";import{selectShapeMembers as gr,selectShapeRows as _r}from"./packem_shared/selectShapeMembers-B8gTOeOB.mjs";import{DATA_MIGRATION_STATE_TABLE as br,readMigrationStatus as Lr,runDataMigration as Dr}from"./packem_shared/DATA_MIGRATION_STATE_TABLE-BwFz6NTT.mjs";import{SCAN_DEP as Pr,createDependencyTracker as Mr,depKey as yr,tableFromDepKey as Fr}from"./packem_shared/SCAN_DEP-D7qE3iUe.mjs";import{runDrizzle as Nr,runSql as Br}from"./packem_shared/runDrizzle-2ULFQR_k.mjs";import{A as Gr,a as qr,b as vr,D as wr,c as Kr,d as Xr,g as Hr,i as Wr,j as zr,e as Vr,q as Qr,f as Yr,r as jr,t as Jr,h as Zr}from"./packem_shared/do-sql-kpl5Kt1j.mjs";import{param as eo,renderSql as ro,sqliteInList as oo,unionAll as ao}from"./packem_shared/param-DlozcSQu.mjs";import{appendStreamChunk as io,claimStreamRun as lo,deleteStreamRun as no,finishStreamRun as so,migrateDurableStreams as co,readStreamChunks as mo,readStreamRun as po,trimStreamRuns as So}from"./packem_shared/appendStreamChunk-C1Ok4b6J.mjs";import{DurableStreamRunner as fo,MAX_DURABLE_STREAM_BYTES as Eo,MAX_DURABLE_STREAM_CHUNKS as ho,decideDurableAttach as xo}from"./packem_shared/DurableStreamRunner-rTYp4v03.mjs";import{envOptionalPositiveInt as Co,envPositiveInt as Ro}from"./packem_shared/envOptionalPositiveInt-D2pY-c64.mjs";import{diffExternalSource as go}from"./packem_shared/diffExternalSource-DgDJhslq.mjs";import{liftSourceId as Io,normalizeSourceDocument as bo,normalizeSourceValue as Lo}from"./packem_shared/liftSourceId-CA3ENhXj.mjs";import{materializeExternalRows as Oo,materializeExternalRowsIncremental as Po,readExternalSourceBaseline as Mo,runExternalSourceTick as yo}from"./packem_shared/materializeExternalRows-xQWkrJqp.mjs";import{isSoftDeleted as ko,isSourceDue as No,pullExternalSourceIncrementalTick as Bo,pullExternalSourceTick as Uo}from"./packem_shared/isSoftDeleted-BXWqZxA-.mjs";import{GEO_DEFAULT_PRECISION as qo,boundingBoxCenter as vo,boundingBoxGeohashes as wo,coveringGeohashes as Ko,encodeGeohash as Xo,haversineMeters as Ho,pointInBoundingBox as Wo}from"./packem_shared/GEO_DEFAULT_PRECISION-CqpQZ-J_.mjs";import{default as Vo}from"./packem_shared/GlobalPollTick-BNK4o-XT.mjs";import{ADMIN_FUNCTIONS as Yo,ADMIN_FUNCTION_PREFIX as jo,DEFAULT_FANOUT_TOPIC_LIMIT as Jo,FLAGS_FUNCTION_PREFIX as Zo,MAX_PAGE_SIZE as $o,RELATION_FUNCTION_PREFIX as ea,createFanoutCounters as ra,createGlobalPollCounters as oa,createShapeProbeCounters as aa,facetColumn as ta,findStorageReferences as ia,listTables as la,readTablePage as na,recordFanoutPass as sa,recordGlobalPollPass as da,recordShapeProbePass as ca,selectMatchingIds as ma,summarizeFanoutTopics as pa,summarizeSubscriptions as Sa}from"./packem_shared/ADMIN_FUNCTIONS-BjpFlIz5.mjs";import{MAIL_RETENTION as fa,MAIL_TABLE as Ea,clearCapturedMail as ha,ensureMailTable as xa,readCapturedMail as Ta,recordCapturedMail as Ca}from"./packem_shared/MAIL_RETENTION-DGAQTHHs.mjs";import{NotFoundError as Aa}from"./packem_shared/NotFoundError-BhF7FeFr.mjs";import{armRestore as _a,readBookmark as Ia}from"./packem_shared/armRestore-Bu1_8SUa.mjs";import{CURSOR_PREFIX as La,applySelect as Da,buildSeekBeforeWhere as Oa,buildSeekWhere as Pa,decodeCursor as Ma,encodeCursor as ya,equalityPinnedFields as Fa,normalizeOrderKeys as ka,softDeleteScope as Na,tiebreakDirectionFor as Ba,uniqueIndexFields as Ua}from"./packem_shared/CURSOR_PREFIX-Bn8SFoGd.mjs";import{QUEUE_TABLE as qa,clearQueueMessages as va,isLossyBody as wa,readQueueMessageById as Ka,readQueueMessages as Xa,recordQueueMessages as Ha}from"./packem_shared/QUEUE_TABLE-s7QJZvBz.mjs";import{RANK_TIEBREAK as za,encodePartitionKey as Va,matchesRankStaticWhere as Qa,rankKeyFromDoc as Ya,rankPivotConditionSql as ja,rankTableName as Ja,resolveRankPartition as Za,sortColumnName as $a}from"./packem_shared/RANK_TIEBREAK-D5xNdzB3.mjs";import{ReactiveCache as rt,reactiveCacheKey as ot}from"./packem_shared/ReactiveCache-CU_NoCMR.mjs";import{REACTOR_STATE_TABLE as tt,listReactorStates as it,migrateReactorState as lt,reactorNeedsRun as nt,readReactorState as st,writeReactorState as dt}from"./packem_shared/REACTOR_STATE_TABLE-QPRFyxMS.mjs";import{UNVOUCHABLE_DEP as mt,createReadFootprint as pt,markUnvouchableReads as St}from"./packem_shared/UNVOUCHABLE_DEP-C68htACn.mjs";import{buildIndexRange as ft,indexKeysForRow as Et,keysTouchRanges as ht}from"./packem_shared/buildIndexRange-DvN8Qj8e.mjs";import{RELATED_DEFAULT_LIMIT as Tt,RELATED_DEPTH_DECAY as Ct,RELATED_MAX_DEPTH as Rt,RELATED_MAX_LIMIT as At,deriveRelationEdges as gt,findRelated as _t}from"./packem_shared/RELATED_DEFAULT_LIMIT-B9PH28Pn.mjs";import{DEFAULT_MAX_RELATION_KEYS as bt,assertFlatPredicate as Lt,assertShapeShardable as Dt,containsRelationPredicate as Ot,isRelationPredicate as Pt,resolveRelationPredicates as Mt}from"./packem_shared/DEFAULT_MAX_RELATION_KEYS-XESc7TiB.mjs";import{applyOnDelete as Ft,distinctValues as kt,fanOutScalarCounts as Nt,relationHooks as Bt,resolveWith as Ut,runRowValidators as Gt}from"./packem_shared/applyOnDelete-7JZ4vR9r.mjs";import{DEFAULT_PROMOTION_THRESHOLDS as vt,clampPromotionThresholds as wt,nextPromotionState as Kt,relayCountFor as Xt,shapeRoutingKey as Ht}from"./packem_shared/DEFAULT_PROMOTION_THRESHOLDS-Bfx7KakS.mjs";import{DEFAULT_MAX_RELAYS as zt,OwnerRelay as Vt,RelayMember as Qt,createRelayLink as Yt}from"./packem_shared/DEFAULT_MAX_RELAYS-Ng4SyJ7k.mjs";import{createReplicaLink as Jt,gateReplicaDispatch as Zt,handleReplicaControl as $t}from"./packem_shared/createReplicaLink-BZvoscLq.mjs";import{buildReprojectionMigration as ri,countLegacyRows as oi,reprojectableFields as ai,reprojectionTables as ti}from"./packem_shared/buildReprojectionMigration-DNjOe6AP.mjs";import{RLS_UNWRAP_SYMBOL as li,RlsRequiredError as ni,guardWriter as si}from"./packem_shared/RLS_UNWRAP_SYMBOL-BwwTbz3Q.mjs";import{SCHEMA_HISTORY_MAX_VERSIONS as ci,readSchemaHistory as mi,readSchemaVersion as pi,recordSchemaVersion as Si}from"./packem_shared/SCHEMA_HISTORY_MAX_VERSIONS-BluIj2s-.mjs";import{serializeSqlValue as fi}from"./packem_shared/serializeSqlValue-BEMMYX1n.mjs";import{buildSettings as hi,isDevEnvironment as xi,readDeployInfo as Ti}from"./packem_shared/buildSettings-DC3VeQ0H.mjs";import{buildShapeDiff as Ri}from"./packem_shared/buildShapeDiff-CK5vViD5.mjs";import{ShapeDiffCache as gi,createShapeDiffCache as _i,globalShapeReadKey as Ii}from"./packem_shared/ShapeDiffCache-gdaILV5E.mjs";import{buildPokeFrames as Li,diffGlobalMembership as Di,encodeRowsPatch as Oi,projectColumns as Pi}from"./packem_shared/buildPokeFrames-BBE6J91z.mjs";import{ShardRunner as yi}from"./packem_shared/ShardRunner-C9p5DVOx.mjs";import{runSocketPool as ki}from"./packem_shared/runSocketPool-CZJ2X9cF.mjs";import{MAX_SQL_ROWS as Bi,assertReadonly as Ui,lintReadonlySql as Gi,runReadonlySql as qi}from"./packem_shared/MAX_SQL_ROWS-Dh_Ty0Zo.mjs";import{B as wi,b as Ki,d as Xi,a as Hi,f as Wi}from"./packem_shared/sql-projection-D3qdaItY.mjs";import{awaitWsDrain as Vi,subscriptionFrames as Qi,subscriptionListDeltas as Yi,trySendFrame as ji}from"./packem_shared/awaitWsDrain-apizgmKY.mjs";import{mergeChangedKeys as Zi,recordChangedKeys as $i,writeTouchesMemo as el}from"./packem_shared/mergeChangedKeys-BA3YxaLE.mjs";import{createSystemReader as ol}from"./packem_shared/createSystemReader-DcDLFfC-.mjs";import{ConflictError as tl}from"./packem_shared/ConflictError-C8GtJmjS.mjs";import{DEFAULT_TRANSACTION_LIMITS as ll,TransactionHeadroomTracker as nl}from"./packem_shared/DEFAULT_TRANSACTION_LIMITS-CTHQQgDC.mjs";import{hasTrigger as dl,runTriggers as cl}from"./packem_shared/hasTrigger-CjlwI4le.mjs";import{selectExpiredIds as pl}from"./packem_shared/selectExpiredIds-D5DEpBbi.mjs";import{c as ul,l as fl}from"./packem_shared/where-sql-x1YKldcq.mjs";import{RELATION_EXISTS_KEY as hl}from"./packem_shared/RELATION_EXISTS_KEY-CFUhnZSZ.mjs";import{REPROJECTION_MIGRATION_PREFIX as Tl,reprojectionMigrationId as Cl}from"./packem_shared/REPROJECTION_MIGRATION_PREFIX-Czcb6_mO.mjs";import{quoteIdentifier as Al}from"./packem_shared/quoteIdentifier-CObIFRhb.mjs";import{runShardMigrations as _l}from"./packem_shared/runShardMigrations-BLl8xFGK.mjs";import{stableStringify as bl}from"./packem_shared/stableStringify-DibjylKD.mjs";import{stableWireKey as Dl}from"./packem_shared/stableWireKey-D2US4k_J.mjs";export{Yo as ADMIN_FUNCTIONS,jo as ADMIN_FUNCTION_PREFIX,d as AGGREGATE_SQL_FUNCTION,Gr as AGG_COUNT,qr as AGG_KEY,vr as AGG_VALUE,D as AUDIT_LOG_TABLE,wi as BIGINT_KEY_DIGITS,W as CDC_LOG_TABLE,z as CDC_LOG_TABLE_SEQ_INDEX,V as CDC_META_TABLE,Ce as CLIENT_WATERMARK_TABLE,Ie as COMMIT_SEQ_FIELD,be as COMMIT_SEQ_TABLE,La as CURSOR_PREFIX,tl as ConflictError,R as CountRlsUnsupportedError,br as DATA_MIGRATION_STATE_TABLE,Jo as DEFAULT_FANOUT_TOPIC_LIMIT,bt as DEFAULT_MAX_RELATION_KEYS,zt as DEFAULT_MAX_RELAYS,vt as DEFAULT_PROMOTION_THRESHOLDS,ll as DEFAULT_TRANSACTION_LIMITS,wr as DOC_COLUMN,fo as DurableStreamRunner,Zo as FLAGS_FUNCTION_PREFIX,qo as GEO_DEFAULT_PRECISION,Fe as GLOBAL_SHAPE_SNAPSHOT_TABLE,Vo as GlobalPollTick,ve as IDEMPOTENCY_TABLE,fa as MAIL_RETENTION,Ea as MAIL_TABLE,Eo as MAX_DURABLE_STREAM_BYTES,ho as MAX_DURABLE_STREAM_CHUNKS,$o as MAX_PAGE_SIZE,Bi as MAX_SQL_ROWS,Aa as NotFoundError,F as NotUniqueError,Vt as OwnerRelay,qa as QUEUE_TABLE,za as RANK_TIEBREAK,tt as REACTOR_STATE_TABLE,Tt as RELATED_DEFAULT_LIMIT,Ct as RELATED_DEPTH_DECAY,Rt as RELATED_MAX_DEPTH,At as RELATED_MAX_LIMIT,hl as RELATION_EXISTS_KEY,ea as RELATION_FUNCTION_PREFIX,Tl as REPROJECTION_MIGRATION_PREFIX,li as RLS_UNWRAP_SYMBOL,rt as ReactiveCache,Qt as RelayMember,ni as RlsRequiredError,Pr as SCAN_DEP,$e as SCHEDULE_OUTBOX_TABLE,ci as SCHEMA_HISTORY_MAX_VERSIONS,dr as SEARCH_STATE_TABLE,ur as SHAPE_POKE_CURSOR_TABLE,gi as ShapeDiffCache,yi as ShardRunner,nl as TransactionHeadroomTracker,mt as UNVOUCHABLE_DEP,Re as advanceClientWatermark,Kr as aggUpsertSql,c as aggregateSqlFunction,f as aggregateTableName,Le as allocateCommitSeq,O as appendAuditEntry,Q as appendCdcChange,io as appendStreamChunk,Y as applyCdcChanges,Ft as applyOnDelete,Da as applySelect,ue as archiveCdcSegment,_a as armRestore,Lt as assertFlatPredicate,k as assertNoExplicitUndefined,Ui as assertReadonly,Dt as assertShapeShardable,N as assertValidClientId,Vi as awaitWsDrain,v as backfillAggregateIndexes,w as backfillRankIndexes,K as backfillSearchIndexes,X as backfillSearchIndexesForTable,Ki as bigintSqlKey,vo as boundingBoxCenter,wo as boundingBoxGeohashes,ft as buildIndexRange,Li as buildPokeFrames,ri as buildReprojectionMigration,Oa as buildSeekBeforeWhere,Pa as buildSeekWhere,hi as buildSettings,Ri as buildShapeDiff,j as bumpCdcEpoch,fe as cdcArchiveRewound,J as cdcCanVouchFor,Z as cdcForkedError,$ as cdcSeqLeavingRows,ee as cdcTouchesTables,re as cdcTrimmedError,lo as claimStreamRun,wt as clampPromotionThresholds,ha as clearCapturedMail,ze as clearMemoryTables,va as clearQueueMessages,E as coerceAggregateNumber,oe as compactCdcDocs,ul as compileWhereSql,je as computeRankPage,Ot as containsRelationPredicate,oi as countLegacyRows,Ko as coveringGeohashes,Me as createCompanionSync,Mr as createDependencyTracker,ra as createFanoutCounters,oa as createGlobalPollCounters,Xr as createIndexSql,pt as createReadFootprint,Yt as createRelayLink,Jt as createReplicaLink,_i as createShapeDiffCache,aa as createShapeProbeCounters,B as createShardCtxDb,ol as createSystemReader,ae as cursorBelowRetainedFloor,xo as decideDurableAttach,Xi as decodeBigintSqlKey,Ma as decodeCursor,Hi as decodeFloat64SqlKey,er as deferScheduleOutbox,ke as deleteGlobalShapeSnapshot,Ne as deleteGlobalShapeSnapshotsForConnection,fr as deleteShapePokeCursor,Er as deleteShapePokeCursorsForConnection,no as deleteStreamRun,yr as depKey,gt as deriveRelationEdges,go as diffExternalSource,Di as diffGlobalMembership,kt as distinctValues,h as encodeAggregateKey,ya as encodeCursor,Xo as encodeGeohash,Va as encodePartitionKey,Oi as encodeRowsPatch,P as ensureAuditTable,xa as ensureMailTable,Co as envOptionalPositiveInt,Ro as envPositiveInt,Fa as equalityPinnedFields,o as exportShardRows,ta as facetColumn,Nt as fanOutScalarCounts,_t as findRelated,ia as findStorageReferences,so as finishStreamRun,Wi as float64SqlKey,x as foldAggregateTally,rr as forgetScheduleOutbox,Zt as gateReplicaDispatch,Hr as geoTableName,Ii as globalShapeReadKey,si as guardWriter,$t as handleReplicaControl,dl as hasTrigger,Ho as haversineMeters,a as importShardRows,Et as indexKeysForRow,xi as isDevEnvironment,Wr as isFtsAvailable,wa as isLossyBody,Ve as isMemoryTable,Pt as isRelationPredicate,ko as isSoftDeleted,No as isSourceDue,zr as jsonPath,Vr as jsonPathSql,ht as keysTouchRanges,Io as liftSourceId,Gi as lintReadonlySql,it as listReactorStates,la as listTables,fl as literalInList,St as markUnvouchableReads,Qa as matchesRankStaticWhere,m as matchesStaticWhere,Oo as materializeExternalRows,Po as materializeExternalRowsIncremental,Qe as memoryTableNames,Zi as mergeChangedKeys,A as mergeWhere,te as migrateCdcLog,ie as migrateCdcMeta,Ae as migrateClientWatermark,De as migrateCommitSeq,co as migrateDurableStreams,Be as migrateGlobalShapeSnapshot,we as migrateIdempotency,lt as migrateReactorState,or as migrateScheduleOutbox,cr as migrateSearchState,hr as migrateShapePokeCursor,le as minCdcReplayableSeq,ne as minCdcSeq,xr as minShapePokeCursor,Kt as nextPromotionState,p as normalizeCountArgument,U as normalizeIdStructurally,ka as normalizeOrderKeys,bo as normalizeSourceDocument,Lo as normalizeSourceValue,eo as param,ar as parkScheduleOutbox,t as parseExportShardArgs,i as parseImportShardArgs,g as planAggregateLookup,Wo as pointInBoundingBox,tr as probeScheduleOutbox,Pi as projectColumns,Bo as pullExternalSourceIncrementalTick,Uo as pullExternalSourceTick,Qr as qualifiedJsonPath,Yr as qualifiedJsonPathSql,Al as quoteIdentifier,Ya as rankKeyFromDoc,ja as rankPivotConditionSql,Ja as rankTableName,ot as reactiveCacheKey,nt as reactorNeedsRun,T as readAggregateValue,Ee as readArchivedCdcChanges,M as readAuditLog,Ia as readBookmark,Ta as readCapturedMail,he as readCdcArchivedThrough,se as readCdcChangeKeys,de as readCdcChanges,ce as readCdcCursor,me as readCdcEpoch,ge as readClientWatermark,Oe as readCommitSeq,Ti as readDeployInfo,ir as readDueScheduleOutbox,Mo as readExternalSourceBaseline,Ue as readGlobalShapeSnapshot,Ke as readIdempotent,Lr as readMigrationStatus,Ka as readQueueMessageById,Xa as readQueueMessages,st as readReactorState,mi as readSchemaHistory,pi as readSchemaVersion,mr as readSearchBackfillState,Tr as readShapePokeCursor,mo as readStreamChunks,po as readStreamRun,na as readTablePage,Ca as recordCapturedMail,$i as recordChangedKeys,sa as recordFanoutPass,da as recordGlobalPollPass,Ha as recordQueueMessages,lr as recordScheduleOutbox,Si as recordSchemaVersion,ca as recordShapeProbePass,Bt as relationHooks,Xt as relayCountFor,ro as renderSql,ai as reprojectableFields,Cl as reprojectionMigrationId,ti as reprojectionTables,Za as resolveRankPartition,Je as resolveRankSeekTuple,Mt as resolveRelationPredicates,Ut as resolveWith,jr as rowToDocument,Dr as runDataMigration,Nr as runDrizzle,yo as runExternalSourceTick,qi as runReadonlySql,Gt as runRowValidators,_l as runShardMigrations,ki as runSocketPool,Br as runSql,cl as runTriggers,pl as selectExpiredIds,l as selectExportTables,_ as selectIndexForAggregate,I as selectIndexForCount,b as selectIndexForGroupBy,ma as selectMatchingIds,gr as selectShapeMembers,_r as selectShapeRows,fi as serializeSqlValue,Ht as shapeRoutingKey,Na as softDeleteScope,$a as sortColumnName,oo as sqliteInList,bl as stableStringify,Dl as stableWireKey,G as stripReservedPatchFields,Qi as subscriptionFrames,Yi as subscriptionListDeltas,pa as summarizeFanoutTopics,Sa as summarizeSubscriptions,Jr as tableColumns,Fr as tableFromDepKey,S as throwingScheduler,Ba as tiebreakDirectionFor,pe as trimCdcChanges,Xe as trimIdempotent,nr as trimScheduleOutbox,So as trimStreamRuns,Zr as tryRowToDocument,ji as trySendFrame,ao as unionAll,Ua as uniqueIndexFields,n as validateImportRow,xe as writeCdcArchivedThrough,Ge as writeGlobalShapeSnapshot,He as writeIdempotent,dt as writeReactorState,pr as writeSearchBackfillState,Cr as writeShapePokeCursor,Rr as writeShapePokeCursors,el as writeTouchesMemo};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{LunoraError as I}from"@lunora/errors";import{m as x,n as y}from"./do-sql-Dvj8Yl5N.mjs";import{quoteIdentifier as d}from"./quoteIdentifier-CObIFRhb.mjs";import{d as L}from"./wire-codec-C-FpWm52.mjs";const te="__lunora_admin__:",re="__lunora_relation__:",ne="__lunora_flags__:",se={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",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",recordAuthEvent:"__lunora_admin__:recordAuthEvent",recordContainerEvent:"__lunora_admin__:recordContainerEvent",recordMail:"__lunora_admin__:recordMail",recordQueueMessage:"__lunora_admin__:recordQueueMessage",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"},D=50,h=500,U=30,j=200,f="__doc__",O=e=>{try{const t=JSON.parse(e);return t!==null&&typeof t=="object"&&!Array.isArray(t)?t:void 0}catch{return}},W=e=>{const{[y]:t,...r}=e;return t===void 0?r:t===null||typeof t!="object"||Array.isArray(t)?{[y]:t,...r}:{...r,...L(t)}},q=(e,t)=>{if(!e.includes(f))return{columns:e,rows:t};const r=[];for(const s of t){const a=s[f],i=typeof a=="string"?O(a):void 0;if(i===void 0)return{columns:e,rows:t};const c=Object.fromEntries(Object.entries(s).filter(([u])=>u!==f));r.push({...c,...W(i)})}const n=e.filter(s=>s!==f),o=[],_=new Set(n);for(const s of r)for(const a of Object.keys(s))_.has(a)||(_.add(a),o.push(a));return{columns:[...n,...o],rows:r}},N=e=>`instr(lower(CAST(${e} AS TEXT)), lower(?)) > 0`,E=e=>e.startsWith("sqlite_")||e.startsWith("_cf_")||e.startsWith("__miniflare")||e.startsWith("__lunora")||e.includes("__fts_"),C=(e,t,r)=>Math.min(Math.max(e,t),r),F=(e,t)=>{const r=e.exec(`SELECT COUNT(*) AS c FROM ${t}`).one();return Number(r.c)},oe=e=>{const t=e.exec("SELECT name FROM sqlite_master WHERE type = 'table' ORDER BY name").toArray(),r=[];for(const{name:n}of t)E(n)||r.push({name:n,rowCount:F(e,d(n))});return r},P=(e,t)=>e.exec("SELECT name FROM sqlite_master WHERE type = 'table' AND name = ? LIMIT 1",t).toArray().length>0,A=(e,t)=>{if(E(t)||!P(e,t))throw new I("UNKNOWN_TABLE",`unknown table: ${t}`,{status:404})},M=(e,t)=>e.exec(`PRAGMA table_info(${t})`).toArray().map(r=>r.name),Q={eq:"=",gt:">",gte:">=",lt:"<",lte:"<=",ne:"<>"},B=e=>typeof e=="string"?e:typeof e=="number"||typeof e=="boolean"?String(e):"",v=(e,t)=>{const r=t.includes(e),n=t.includes(f);if(!(!r&&!n))return r?{expression:d(e),params:[]}:{expression:`json_extract(${d(f)}, ?)`,params:[`$.${x(e)}`]}},G=(e,t)=>{const r=v(e.column,t);if(r===void 0)return;const{expression:n,params:o}=r;return e.operator==="contains"?{params:[...o,B(e.value)],sql:N(n)}:e.value===null&&(e.operator==="eq"||e.operator==="ne")?{params:o,sql:`${n} IS ${e.operator==="ne"?"NOT ":""}NULL`}:{params:[...o,e.value],sql:`${n} ${Q[e.operator]} ?`}},H=/^(\d{4})(?:-(\d{2}))?(?:-(\d{2}))?$/u,X=e=>{const t=H.exec(e.trim());if(t===null)return;const r=Number(t[1]),n=t[2]===void 0?void 0:Number(t[2]),o=t[3]===void 0?void 0:Number(t[3]);if(n!==void 0&&(n<1||n>12)||o!==void 0&&(o<1||o>31)||r<100)return;const _=Date.UTC(r,(n??1)-1,o??1);if(o!==void 0&&new Date(_).getUTCDate()!==o)return;let s;return o!==void 0?s=Date.UTC(r,(n??1)-1,o+1):n===void 0?s=Date.UTC(r+1,0,1):s=Date.UTC(r,n,1),{from:_,to:s}},R=(e,t,r)=>{const n=[],o=[];if(t!==""&&e.length>0){const _=e.map(a=>N(d(a)));o.push(...e.map(()=>t));const s=X(t);if(s!==void 0)for(const a of e)_.push(`(${d(a)} >= ? AND ${d(a)} < ?)`),o.push(s.from,s.to);n.push(`(${_.join(" OR ")})`)}for(const _ of r??[]){const s=G(_,e);s!==void 0&&(n.push(`(${s.sql})`),o.push(...s.params))}return n.length===0?void 0:{parameters:o,where:n.join(" AND ")}},Y=(e,t)=>{if(e===void 0)return;const r=v(e.column,t);if(r===void 0)return;const n=e.direction==="desc"?"DESC":"ASC";return{params:r.params,sql:`${r.expression} ${n}`}},ae=(e,t)=>{const{table:r}=t;A(e,r);const n=C(Math.trunc(t.limit??D),1,h),o=Math.max(0,Math.trunc(t.offset??0)),_=d(r),s=M(e,_),a=t.search?.trim()??"",i=b=>{if(t.refs===void 0)return b;const T={};for(const w of b.columns){const k=t.refs[w];k!==void 0&&(T[w]=k)}return Object.keys(T).length>0?{...b,refs:T}:b},c=R(s,a,t.filters),u=Y(t.orderBy,s),l=c===void 0?"":` WHERE ${c.where}`,m=u===void 0?"":` ORDER BY ${u.sql}`,p=c?.parameters??[],g=u?.params??[];let S;t.skipCount||(S=c===void 0?F(e,_):Number(e.exec(`SELECT COUNT(*) AS c FROM ${_}${l}`,...p).one().c));const $=e.exec(`SELECT * FROM ${_}${l}${m} LIMIT ? OFFSET ?`,...p,...g,n,o).toArray();return i({...q(s,$),sqlColumns:s,total:S})},_e=(e,t)=>{const{table:r}=t;A(e,r);const n=C(Math.trunc(t.limit??h),1,h),o=d(r),_=M(e,o),s=t.search?.trim()??"",a=R(_,s,t.filters),i=[],c=[];a!==void 0&&(i.push(a.where),c.push(...a.parameters)),t.after!==void 0&&(i.push("id > ?"),c.push(t.after));const u=i.length===0?"":` WHERE ${i.join(" AND ")}`,l=t.after===void 0?"":" ORDER BY id",m=e.exec(`SELECT id FROM ${o}${u}${l} LIMIT ?`,...c,n+1).toArray(),p=m.length>n,g=m.slice(0,n).map(S=>S.id);return{hasMore:p,ids:g}},K=(e,t,r)=>{const n=new Set(r.filter(_=>_!==f));if(!r.includes(f))return n;const o=e.exec(`SELECT ${d(f)} AS doc FROM ${t} LIMIT ?`,h).toArray();for(const{doc:_}of o){const s=typeof _=="string"?O(_):void 0;if(s!==void 0)for(const a of Object.keys(s))n.add(a)}return n},ie=(e,t)=>{const{column:r,table:n}=t;A(e,n);const o=d(n),_=M(e,o);if(!K(e,o,_).has(r))throw new I("UNKNOWN_COLUMN",`unknown column: ${r}`,{status:404});const s=v(r,_);if(s===void 0)throw new I("UNKNOWN_COLUMN",`unknown column: ${r}`,{status:404});const a=C(Math.trunc(t.limit??U),1,j),i=t.search?.trim()??"",c=R(_,i,t.filters),u=c===void 0?"":` WHERE ${c.where}`,l=c?.parameters??[],m=e.exec(`SELECT ${s.expression} AS value, COUNT(*) AS count FROM ${o}${u} GROUP BY ${s.expression} ORDER BY count DESC LIMIT ?`,...s.params,...l,...s.params,a+1).toArray();return{truncated:m.length>a,values:m.slice(0,a).map(g=>({count:Number(g.count),value:g.value}))}},ce=(e,t,r)=>{const n={},o=r.slice(0,h);for(const s of o)n[s]=[];if(o.length===0)return{references:n,storageColumns:t};const _=o.map(()=>"?").join(", ");for(const[s,a]of Object.entries(t)){if(E(s)||!P(e,s))continue;const i=d(s),c=M(e,i);for(const u of a){const l=v(u,c);if(l===void 0)continue;const m=e.exec(`SELECT id, ${l.expression} AS ref FROM ${i} WHERE ${l.expression} IN (${_})`,...l.params,...l.params,...o).toArray();for(const p of m)n[p.ref]?.push({column:u,id:p.id,table:s})}}return{references:n,storageColumns:t}},ue=e=>{const t=e.map((n,o)=>{const _=Object.values(n.subs??{}).map(s=>({args:s.args,functionPath:s.functionPath,table:s.table}));return{admin:n.admin===!0,id:o,subscriptions:_}}),r=t.reduce((n,o)=>n+o.subscriptions.length,0);return{connections:t,totalConnections:t.length,totalSubscriptions:r}},V=20,le=()=>({maxMs:0,passes:0,peakSocketsIterated:0,socketsDelivered:0,socketsIterated:0,totalMs:0}),de=()=>({run:0,served:0}),me=()=>({drains:0,pairsSkipped:0}),fe=(e,t,r)=>({drains:e.drains+t,pairsSkipped:e.pairsSkipped+r}),pe=(e,t,r)=>({run:e.run+t,served:e.served+r}),ge=(e,t,r,n)=>({maxMs:Math.max(e.maxMs,n),passes:e.passes+1,peakSocketsIterated:Math.max(e.peakSocketsIterated,t),socketsDelivered:e.socketsDelivered+r,socketsIterated:e.socketsIterated+t,totalMs:e.totalMs+n}),he=(e,t=V)=>{const r=new Map,n=new Map;for(const s of e){for(const a of Object.values(s.shapes??{})){const i=a.name??"(unknown shape)";r.set(i,(r.get(i)??0)+1)}for(const a of s.whispers??[])n.set(a,(n.get(a)??0)+1)}const o=[...[...r].map(([s,a])=>({kind:"shape",subscribers:a,topic:s})),...[...n].map(([s,a])=>({kind:"whisper",subscribers:a,topic:s}))];return o.sort((s,a)=>a.subscribers-s.subscribers||s.topic.localeCompare(a.topic)),{peakSubscribers:o[0]?.subscribers??0,topics:o.slice(0,t),totalConnections:e.length}};export{se as ADMIN_FUNCTIONS,te as ADMIN_FUNCTION_PREFIX,V as DEFAULT_FANOUT_TOPIC_LIMIT,ne as FLAGS_FUNCTION_PREFIX,h as MAX_PAGE_SIZE,re as RELATION_FUNCTION_PREFIX,le as createFanoutCounters,me as createGlobalPollCounters,de as createShapeProbeCounters,X as datePrefixRange,ie as facetColumn,ce as findStorageReferences,oe as listTables,ae as readTablePage,ge as recordFanoutPass,fe as recordGlobalPollPass,pe as recordShapeProbePass,_e as selectMatchingIds,he as summarizeFanoutTopics,ue as summarizeSubscriptions};
|
|
1
|
+
import{LunoraError as I}from"@lunora/errors";import{m as x,n as y}from"./do-sql-kpl5Kt1j.mjs";import{quoteIdentifier as d}from"./quoteIdentifier-CObIFRhb.mjs";import{d as L}from"./wire-codec-C-FpWm52.mjs";const te="__lunora_admin__:",re="__lunora_relation__:",ne="__lunora_flags__:",se={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",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",recordAuthEvent:"__lunora_admin__:recordAuthEvent",recordContainerEvent:"__lunora_admin__:recordContainerEvent",recordMail:"__lunora_admin__:recordMail",recordQueueMessage:"__lunora_admin__:recordQueueMessage",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"},D=50,h=500,U=30,j=200,f="__doc__",O=e=>{try{const t=JSON.parse(e);return t!==null&&typeof t=="object"&&!Array.isArray(t)?t:void 0}catch{return}},W=e=>{const{[y]:t,...r}=e;return t===void 0?r:t===null||typeof t!="object"||Array.isArray(t)?{[y]:t,...r}:{...r,...L(t)}},q=(e,t)=>{if(!e.includes(f))return{columns:e,rows:t};const r=[];for(const s of t){const a=s[f],i=typeof a=="string"?O(a):void 0;if(i===void 0)return{columns:e,rows:t};const c=Object.fromEntries(Object.entries(s).filter(([u])=>u!==f));r.push({...c,...W(i)})}const n=e.filter(s=>s!==f),o=[],_=new Set(n);for(const s of r)for(const a of Object.keys(s))_.has(a)||(_.add(a),o.push(a));return{columns:[...n,...o],rows:r}},N=e=>`instr(lower(CAST(${e} AS TEXT)), lower(?)) > 0`,E=e=>e.startsWith("sqlite_")||e.startsWith("_cf_")||e.startsWith("__miniflare")||e.startsWith("__lunora")||e.includes("__fts_"),C=(e,t,r)=>Math.min(Math.max(e,t),r),F=(e,t)=>{const r=e.exec(`SELECT COUNT(*) AS c FROM ${t}`).one();return Number(r.c)},oe=e=>{const t=e.exec("SELECT name FROM sqlite_master WHERE type = 'table' ORDER BY name").toArray(),r=[];for(const{name:n}of t)E(n)||r.push({name:n,rowCount:F(e,d(n))});return r},P=(e,t)=>e.exec("SELECT name FROM sqlite_master WHERE type = 'table' AND name = ? LIMIT 1",t).toArray().length>0,A=(e,t)=>{if(E(t)||!P(e,t))throw new I("UNKNOWN_TABLE",`unknown table: ${t}`,{status:404})},M=(e,t)=>e.exec(`PRAGMA table_info(${t})`).toArray().map(r=>r.name),Q={eq:"=",gt:">",gte:">=",lt:"<",lte:"<=",ne:"<>"},B=e=>typeof e=="string"?e:typeof e=="number"||typeof e=="boolean"?String(e):"",v=(e,t)=>{const r=t.includes(e),n=t.includes(f);if(!(!r&&!n))return r?{expression:d(e),params:[]}:{expression:`json_extract(${d(f)}, ?)`,params:[`$.${x(e)}`]}},G=(e,t)=>{const r=v(e.column,t);if(r===void 0)return;const{expression:n,params:o}=r;return e.operator==="contains"?{params:[...o,B(e.value)],sql:N(n)}:e.value===null&&(e.operator==="eq"||e.operator==="ne")?{params:o,sql:`${n} IS ${e.operator==="ne"?"NOT ":""}NULL`}:{params:[...o,e.value],sql:`${n} ${Q[e.operator]} ?`}},H=/^(\d{4})(?:-(\d{2}))?(?:-(\d{2}))?$/u,X=e=>{const t=H.exec(e.trim());if(t===null)return;const r=Number(t[1]),n=t[2]===void 0?void 0:Number(t[2]),o=t[3]===void 0?void 0:Number(t[3]);if(n!==void 0&&(n<1||n>12)||o!==void 0&&(o<1||o>31)||r<100)return;const _=Date.UTC(r,(n??1)-1,o??1);if(o!==void 0&&new Date(_).getUTCDate()!==o)return;let s;return o!==void 0?s=Date.UTC(r,(n??1)-1,o+1):n===void 0?s=Date.UTC(r+1,0,1):s=Date.UTC(r,n,1),{from:_,to:s}},R=(e,t,r)=>{const n=[],o=[];if(t!==""&&e.length>0){const _=e.map(a=>N(d(a)));o.push(...e.map(()=>t));const s=X(t);if(s!==void 0)for(const a of e)_.push(`(${d(a)} >= ? AND ${d(a)} < ?)`),o.push(s.from,s.to);n.push(`(${_.join(" OR ")})`)}for(const _ of r??[]){const s=G(_,e);s!==void 0&&(n.push(`(${s.sql})`),o.push(...s.params))}return n.length===0?void 0:{parameters:o,where:n.join(" AND ")}},Y=(e,t)=>{if(e===void 0)return;const r=v(e.column,t);if(r===void 0)return;const n=e.direction==="desc"?"DESC":"ASC";return{params:r.params,sql:`${r.expression} ${n}`}},ae=(e,t)=>{const{table:r}=t;A(e,r);const n=C(Math.trunc(t.limit??D),1,h),o=Math.max(0,Math.trunc(t.offset??0)),_=d(r),s=M(e,_),a=t.search?.trim()??"",i=b=>{if(t.refs===void 0)return b;const T={};for(const w of b.columns){const k=t.refs[w];k!==void 0&&(T[w]=k)}return Object.keys(T).length>0?{...b,refs:T}:b},c=R(s,a,t.filters),u=Y(t.orderBy,s),l=c===void 0?"":` WHERE ${c.where}`,m=u===void 0?"":` ORDER BY ${u.sql}`,p=c?.parameters??[],g=u?.params??[];let S;t.skipCount||(S=c===void 0?F(e,_):Number(e.exec(`SELECT COUNT(*) AS c FROM ${_}${l}`,...p).one().c));const $=e.exec(`SELECT * FROM ${_}${l}${m} LIMIT ? OFFSET ?`,...p,...g,n,o).toArray();return i({...q(s,$),sqlColumns:s,total:S})},_e=(e,t)=>{const{table:r}=t;A(e,r);const n=C(Math.trunc(t.limit??h),1,h),o=d(r),_=M(e,o),s=t.search?.trim()??"",a=R(_,s,t.filters),i=[],c=[];a!==void 0&&(i.push(a.where),c.push(...a.parameters)),t.after!==void 0&&(i.push("id > ?"),c.push(t.after));const u=i.length===0?"":` WHERE ${i.join(" AND ")}`,l=t.after===void 0?"":" ORDER BY id",m=e.exec(`SELECT id FROM ${o}${u}${l} LIMIT ?`,...c,n+1).toArray(),p=m.length>n,g=m.slice(0,n).map(S=>S.id);return{hasMore:p,ids:g}},K=(e,t,r)=>{const n=new Set(r.filter(_=>_!==f));if(!r.includes(f))return n;const o=e.exec(`SELECT ${d(f)} AS doc FROM ${t} LIMIT ?`,h).toArray();for(const{doc:_}of o){const s=typeof _=="string"?O(_):void 0;if(s!==void 0)for(const a of Object.keys(s))n.add(a)}return n},ie=(e,t)=>{const{column:r,table:n}=t;A(e,n);const o=d(n),_=M(e,o);if(!K(e,o,_).has(r))throw new I("UNKNOWN_COLUMN",`unknown column: ${r}`,{status:404});const s=v(r,_);if(s===void 0)throw new I("UNKNOWN_COLUMN",`unknown column: ${r}`,{status:404});const a=C(Math.trunc(t.limit??U),1,j),i=t.search?.trim()??"",c=R(_,i,t.filters),u=c===void 0?"":` WHERE ${c.where}`,l=c?.parameters??[],m=e.exec(`SELECT ${s.expression} AS value, COUNT(*) AS count FROM ${o}${u} GROUP BY ${s.expression} ORDER BY count DESC LIMIT ?`,...s.params,...l,...s.params,a+1).toArray();return{truncated:m.length>a,values:m.slice(0,a).map(g=>({count:Number(g.count),value:g.value}))}},ce=(e,t,r)=>{const n={},o=r.slice(0,h);for(const s of o)n[s]=[];if(o.length===0)return{references:n,storageColumns:t};const _=o.map(()=>"?").join(", ");for(const[s,a]of Object.entries(t)){if(E(s)||!P(e,s))continue;const i=d(s),c=M(e,i);for(const u of a){const l=v(u,c);if(l===void 0)continue;const m=e.exec(`SELECT id, ${l.expression} AS ref FROM ${i} WHERE ${l.expression} IN (${_})`,...l.params,...l.params,...o).toArray();for(const p of m)n[p.ref]?.push({column:u,id:p.id,table:s})}}return{references:n,storageColumns:t}},ue=e=>{const t=e.map((n,o)=>{const _=Object.values(n.subs??{}).map(s=>({args:s.args,functionPath:s.functionPath,table:s.table}));return{admin:n.admin===!0,id:o,subscriptions:_}}),r=t.reduce((n,o)=>n+o.subscriptions.length,0);return{connections:t,totalConnections:t.length,totalSubscriptions:r}},V=20,le=()=>({maxMs:0,passes:0,peakSocketsIterated:0,socketsDelivered:0,socketsIterated:0,totalMs:0}),de=()=>({run:0,served:0}),me=()=>({drains:0,pairsSkipped:0}),fe=(e,t,r)=>({drains:e.drains+t,pairsSkipped:e.pairsSkipped+r}),pe=(e,t,r)=>({run:e.run+t,served:e.served+r}),ge=(e,t,r,n)=>({maxMs:Math.max(e.maxMs,n),passes:e.passes+1,peakSocketsIterated:Math.max(e.peakSocketsIterated,t),socketsDelivered:e.socketsDelivered+r,socketsIterated:e.socketsIterated+t,totalMs:e.totalMs+n}),he=(e,t=V)=>{const r=new Map,n=new Map;for(const s of e){for(const a of Object.values(s.shapes??{})){const i=a.name??"(unknown shape)";r.set(i,(r.get(i)??0)+1)}for(const a of s.whispers??[])n.set(a,(n.get(a)??0)+1)}const o=[...[...r].map(([s,a])=>({kind:"shape",subscribers:a,topic:s})),...[...n].map(([s,a])=>({kind:"whisper",subscribers:a,topic:s}))];return o.sort((s,a)=>a.subscribers-s.subscribers||s.topic.localeCompare(a.topic)),{peakSubscribers:o[0]?.subscribers??0,topics:o.slice(0,t),totalConnections:e.length}};export{se as ADMIN_FUNCTIONS,te as ADMIN_FUNCTION_PREFIX,V as DEFAULT_FANOUT_TOPIC_LIMIT,ne as FLAGS_FUNCTION_PREFIX,h as MAX_PAGE_SIZE,re as RELATION_FUNCTION_PREFIX,le as createFanoutCounters,me as createGlobalPollCounters,de as createShapeProbeCounters,X as datePrefixRange,ie as facetColumn,ce as findStorageReferences,oe as listTables,ae as readTablePage,ge as recordFanoutPass,fe as recordGlobalPollPass,pe as recordShapeProbePass,_e as selectMatchingIds,he as summarizeFanoutTopics,ue as summarizeSubscriptions};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import"./sql-projection-
|
|
1
|
+
import"./sql-projection-D3qdaItY.mjs";import{A as r,a as l,b as i,D as n,n as d,c as m,d as c,l as q,o as u,k as p,g as G,i as f,j as A,e as D,q as S,f as _,r as h,t as C,h as O}from"./do-sql-kpl5Kt1j.mjs";import{quoteIdentifier as g}from"./quoteIdentifier-CObIFRhb.mjs";import"./wire-codec-C-FpWm52.mjs";import"./runDrizzle-2ULFQR_k.mjs";import{serializeSqlValue as I}from"./serializeSqlValue-BEMMYX1n.mjs";export{r as AGG_COUNT,l as AGG_KEY,i as AGG_VALUE,n as DOC_COLUMN,d as DOC_ORIGINALS_KEY,m as aggUpsertSql,c as createIndexSql,q as decodeDocJson,u as decodeGroupKeyValue,p as encodeDocJson,G as geoTableName,f as isFtsAvailable,A as jsonPath,D as jsonPathSql,S as qualifiedJsonPath,_ as qualifiedJsonPathSql,g as quoteIdentifier,h as rowToDocument,I as serializeSqlValue,C as tableColumns,O as tryRowToDocument};
|
package/dist/packem_shared/{BIGINT_KEY_DIGITS-Dp0GtURc.mjs → BIGINT_KEY_DIGITS-Bnqj9CYQ.mjs}
RENAMED
|
@@ -1 +1 @@
|
|
|
1
|
-
import"./base64-DfpzS4o_.mjs";import{B as s,b as l,d,a as i,f as t,i as r,m as K,s as c}from"./sql-projection-
|
|
1
|
+
import"./base64-DfpzS4o_.mjs";import{B as s,b as l,d,a as i,f as t,i as r,m as K,s as c}from"./sql-projection-D3qdaItY.mjs";export{s as BIGINT_KEY_DIGITS,l as bigintSqlKey,d as decodeBigintSqlKey,i as decodeFloat64SqlKey,t as float64SqlKey,r as isProjectedKind,K as mayHoldProjectedValue,c as sqlComparableProjection};
|
|
@@ -0,0 +1,15 @@
|
|
|
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 u,runDrizzle as s}from"./runDrizzle-2ULFQR_k.mjs";import{k as L,l as p}from"./do-sql-kpl5Kt1j.mjs";import{ConflictError as A}from"./ConflictError-C8GtJmjS.mjs";const n="__cdc_log",q=`INSERT INTO ${C(n)} (ts, ${C("table")}, id, op, doc) VALUES (?, ?, ?, ?, ?)`,I="__cdc_log_table_seq",w=e=>{s(e,t`CREATE TABLE IF NOT EXISTS ${t.identifier(n)} (
|
|
2
|
+
seq INTEGER PRIMARY KEY AUTOINCREMENT,
|
|
3
|
+
ts REAL NOT NULL,
|
|
4
|
+
${t.identifier("table")} TEXT NOT NULL,
|
|
5
|
+
id TEXT NOT NULL,
|
|
6
|
+
op TEXT NOT NULL,
|
|
7
|
+
doc TEXT
|
|
8
|
+
)`);try{s(e,t`CREATE INDEX IF NOT EXISTS ${t.identifier(I)} ON ${t.identifier(n)} (${t.identifier("table")}, seq)`)}catch{}},F=(e,o,r,i,c,d)=>{const a=d===void 0?null:L(d);u(e,q,o,r,i,c,a)},f=90,h=e=>t` AND ${t.identifier("table")} IN (${t.join([...e].map(o=>t`${o}`),t`, `)})`,y=(e,o={})=>{const r=o.sinceSeq??0,i=Math.max(1,Math.min(o.limit??1e3,1e4)),d=s(e,t`SELECT seq, ts, ${t.identifier("table")}, id, op, doc FROM ${t.identifier(n)} WHERE seq > ${r} ORDER BY seq ASC LIMIT ${i}`).toArray().map(a=>{const l={id:a.id,op:a.op,seq:a.seq,table:a.table,ts:a.ts};return a.doc===null?l:{...l,doc:p(a.doc)}});return{changes:d,cursor:d.at(-1)?.seq??r}},U=(e,o,r)=>{if(r.size===0)return!1;const i=[...r];for(let c=0;c<i.length;c+=f){const d=new Set(i.slice(c,c+f));if(s(e,t`SELECT 1 AS hit FROM ${t.identifier(n)} WHERE seq > ${o}${h(d)} LIMIT 1`).toArray().length>0)return!0}return!1},T=new WeakMap,S=e=>new Set(s(e,t`SELECT name FROM sqlite_master WHERE type = 'table'`).toArray().map(o=>o.name)),X=(e,o)=>{if(o.size===0)return!1;let r=T.get(e),i=!1;r===void 0&&(r=S(e),i=!0,T.set(e,r));for(const c of o)if(!r.has(c)&&(i||(r=S(e),i=!0,T.set(e,r),!r.has(c))))return!1;return!0},x=(e,o,r,i)=>s(e,t`SELECT id, op, MAX(seq) AS maxSeq, COUNT(*) AS ops FROM ${t.identifier(n)}
|
|
9
|
+
WHERE ${t.identifier("table")} = ${o} AND seq > ${r} AND seq <= ${i}
|
|
10
|
+
GROUP BY id
|
|
11
|
+
ORDER BY maxSeq ASC`).toArray().map(d=>{const a=d.op;return{id:d.id,op:a==="insert"&&d.ops>1?"update":a,seq:d.maxSeq}}),B=(e,o,r)=>{s(e,t`DELETE FROM ${t.identifier(n)} WHERE seq IN (
|
|
12
|
+
SELECT seq FROM ${t.identifier(n)} WHERE seq <= ${o} ORDER BY seq ASC LIMIT ${r}
|
|
13
|
+
)`)},H=(e,o,r)=>{s(e,t`UPDATE ${t.identifier(n)} SET doc = NULL WHERE seq IN (
|
|
14
|
+
SELECT seq FROM ${t.identifier(n)} WHERE seq <= ${o} AND doc IS NOT NULL ORDER BY seq ASC LIMIT ${r}
|
|
15
|
+
)`)},v=(e,o)=>{if(o<=0)return s(e,t`SELECT MAX(seq) AS seq FROM ${t.identifier(n)}`).toArray()[0]?.seq??void 0;const i=s(e,t`SELECT seq FROM ${t.identifier(n)} ORDER BY seq DESC LIMIT 1 OFFSET ${o-1}`).toArray()[0]?.seq;return i===void 0?void 0:i-1},W=e=>{const r=s(e,t`SELECT seq FROM sqlite_sequence WHERE name = ${n}`).toArray()[0]?.seq;return typeof r=="number"?r:s(e,t`SELECT MAX(seq) AS seq FROM ${t.identifier(n)}`).toArray()[0]?.seq??0},Y=(e,o)=>e!==void 0&&e>o+1,K=(e,o,r)=>new R("CDC_LOG_TRIMMED",`${r==="global"?"global cdc":"cdc"} entries at or below seq ${String(e-1)} have been trimmed; resume from a snapshot (sinceSeq ${String(o)} is below the retained window)`,{status:409}),P=(e,o,r)=>new R("CDC_TIMELINE_FORKED",`cdc cursor ${String(o)} is above this shard's high-watermark ${String(e)}; the changelog rolled back (a point-in-time restore) and the changes you hold are on a timeline that no longer exists — resume from a snapshot at epoch ${r}`,{data:{cursor:e,epoch:r},status:409}),N=e=>s(e,t`SELECT MIN(seq) AS seq FROM ${t.identifier(n)}`).toArray()[0]?.seq??void 0,G=e=>{const r=s(e,t`SELECT MAX(seq) AS seq FROM ${t.identifier(n)} WHERE op <> 'delete' AND doc IS NULL`).toArray()[0]?.seq??void 0,i=N(e);return r===void 0?i:Math.max(r+1,i??0)},E="__cdc_meta",m=e=>{s(e,t`CREATE TABLE IF NOT EXISTS ${t.identifier(E)} (id INTEGER PRIMARY KEY CHECK (id = 1), epoch TEXT NOT NULL)`)},k=e=>{m(e);const r=s(e,t`SELECT epoch FROM ${t.identifier(E)} WHERE id = 1`).toArray()[0]?.epoch;if(typeof r=="string"&&r.length>0)return r;const i=crypto.randomUUID();return s(e,t`INSERT INTO ${t.identifier(E)} (id, epoch) VALUES (1, ${i})`),i},V=e=>{m(e);const o=crypto.randomUUID();return s(e,t`INSERT INTO ${t.identifier(E)} (id, epoch) VALUES (1, ${o}) ON CONFLICT(id) DO UPDATE SET epoch = excluded.epoch`),o},O=async(e,o)=>{if(o.op==="delete"){await e.delete(o.id,o.table);return}const r=o.doc??{};try{await e.insert(o.table,r,{allowExplicitId:!0})}catch(i){if(!(i instanceof A))throw i;const c={...r};delete c._id,await e.replace(o.id,c,o.table,{allowExplicitId:!0})}},z=async(e,o)=>{for(const r of o)await O(e,r)};export{q as CDC_APPEND_SQL,n as CDC_LOG_TABLE,I as CDC_LOG_TABLE_SEQ_INDEX,E as CDC_META_TABLE,F as appendCdcChange,z as applyCdcChanges,V as bumpCdcEpoch,X as cdcCanVouchFor,P as cdcForkedError,v as cdcSeqLeavingRows,U as cdcTouchesTables,K as cdcTrimmedError,H as compactCdcDocs,Y as cursorBelowRetainedFloor,w as migrateCdcLog,m as migrateCdcMeta,G as minCdcReplayableSeq,N as minCdcSeq,x as readCdcChangeKeys,y as readCdcChanges,W as readCdcCursor,k as readCdcEpoch,B as trimCdcChanges};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{LunoraError as i}from"@lunora/errors";import{e}from"./estimate-bytes-
|
|
1
|
+
import{LunoraError as i}from"@lunora/errors";import{e}from"./estimate-bytes-DM1UZj_m.mjs";const r={maxReadRows:1e5,maxWrittenBytes:32*1024*1024,maxWrittenRows:5e4};class w{readRows=0;writtenRows=0;writtenBytes=0;limits;constructor(t={}){this.limits={...r,...t}}recordRead(t){if(this.readRows+=t,this.readRows>this.limits.maxReadRows)throw new i("TRANSACTION_LIMIT_EXCEEDED",`this transaction read ${String(this.readRows)} documents, over the ${String(this.limits.maxReadRows)}-document limit`)}recordWrite(t){const s=e(t);if(s===void 0)throw new i("BAD_REQUEST","this document is not JSON-serializable (cyclic or non-JSON value); it cannot be written");if(this.writtenRows+=1,this.writtenBytes+=s,this.writtenRows>this.limits.maxWrittenRows)throw new i("TRANSACTION_LIMIT_EXCEEDED",`this transaction wrote ${String(this.writtenRows)} documents, over the ${String(this.limits.maxWrittenRows)}-document limit`);if(this.writtenBytes>this.limits.maxWrittenBytes)throw new i("TRANSACTION_LIMIT_EXCEEDED",`this transaction wrote ${String(this.writtenBytes)} bytes, over the ${String(this.limits.maxWrittenBytes)}-byte limit`)}headroom(){return{readRows:this.readRows,remainingReadRows:Math.max(0,this.limits.maxReadRows-this.readRows),remainingWrittenBytes:Math.max(0,this.limits.maxWrittenBytes-this.writtenBytes),remainingWrittenRows:Math.max(0,this.limits.maxWrittenRows-this.writtenRows),writtenBytes:this.writtenBytes,writtenRows:this.writtenRows}}}export{r as DEFAULT_TRANSACTION_LIMITS,w as TransactionHeadroomTracker};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{LunoraError as $}from"@lunora/errors";import{D as st}from"./MAX_TOKEN_LENGTH-BakL9FUy-B3VwYY8C.mjs";import{c as pn,S as gn,l as Le,a as $n}from"./ctx-db-companions-DsNfXSbb.mjs";import{sql as i}from"drizzle-orm";import{d as yn}from"./wire-codec-C-FpWm52.mjs";import{throwingScheduler as En,aggregateSqlFunction as ke,normalizeCountArgument as mn}from"./AGGREGATE_SQL_FUNCTION-DDEoMnJR.mjs";import{aggregateTableName as Ve,encodeAggregateKey as ze,readAggregateValue as Je}from"./aggregateTableName-C7o-gpms.mjs";import{mergeWhere as V,CountRlsUnsupportedError as Ye,selectIndexForGroupBy as Sn,selectIndexForCount as _n,selectIndexForAggregate as Rn}from"./CountRlsUnsupportedError-BvsDqfO2.mjs";import{backfillSearchIndexesForTable as Tn,searchIndexCoversTable as vn}from"./backfillAggregateIndexes-DTemznr7.mjs";import{backfillAggregateIndexes as Lr,backfillRankIndexes as kr,backfillSearchIndexes as Fr}from"./backfillAggregateIndexes-DTemznr7.mjs";import{appendCdcChange as An}from"./CDC_LOG_TABLE-CfILante.mjs";import{CDC_LOG_TABLE as Br,applyCdcChanges as Wr,bumpCdcEpoch as Pr,cdcCanVouchFor as Ur,cdcForkedError as Gr,cdcSeqLeavingRows as Hr,cdcTouchesTables as Or,cdcTrimmedError as Nr,compactCdcDocs as jr,cursorBelowRetainedFloor as Kr,minCdcReplayableSeq as Qr,minCdcSeq as Vr,readCdcChangeKeys as zr,readCdcChanges as Jr,readCdcCursor as Yr,readCdcEpoch as Xr,trimCdcChanges as Zr}from"./CDC_LOG_TABLE-CfILante.mjs";import{allocateCommitSeq as In,COMMIT_SEQ_FIELD as Cn}from"./COMMIT_SEQ_FIELD-BUdOMG5y.mjs";import{isMemoryTable as _t}from"./clearMemoryTables-BGbmag2i.mjs";import{computeRankPage as Rt}from"./computeRankPage-pTaG_r9F.mjs";import{SCAN_DEP as G}from"./SCAN_DEP-D7qE3iUe.mjs";import{runDrizzle as O,runSql as _e}from"./runDrizzle-2ULFQR_k.mjs";import{D as oe,k as ae,r as ue,b as Fe,A as Xe,a as qe,e as Z,o as xn,t as Kt,j as Pe,q as Tt,i as bn,h as Qt,g as Mn}from"./do-sql-kpl5Kt1j.mjs";import{renderSql as Vt,unionAll as ct,WORKERD_SQLITE_LIMITS as zt,sqliteInList as Dn}from"./param-DlozcSQu.mjs";import{coveringGeohashes as Ln,boundingBoxGeohashes as kn,haversineMeters as Fn,pointInBoundingBox as qn}from"./GEO_DEFAULT_PRECISION-CqpQZ-J_.mjs";import{NotFoundError as Bn}from"./NotFoundError-BhF7FeFr.mjs";import{softDeleteScope as le,normalizeOrderKeys as nt,uniqueIndexFields as Jt,equalityPinnedFields as Wn,buildSeekWhere as Yt,decodeCursor as ot,applySelect as vt,encodeCursor as rt,tiebreakDirectionFor as Xt,buildSeekBeforeWhere as Pn}from"./CURSOR_PREFIX-Bn8SFoGd.mjs";import{rankTableName as At,sortColumnName as It,resolveRankPartition as Un,encodePartitionKey as Gn,RANK_TIEBREAK as Hn,rankPivotConditionSql as On}from"./RANK_TIEBREAK-D5xNdzB3.mjs";import{UNVOUCHABLE_DEP as Ct}from"./UNVOUCHABLE_DEP-C68htACn.mjs";import{indexKeysForRow as Nn,buildIndexRange as jn}from"./buildIndexRange-DvN8Qj8e.mjs";import{deriveRelationEdges as Kn,findRelated as Qn}from"./RELATED_DEFAULT_LIMIT-B9PH28Pn.mjs";import{assertFlatPredicate as Ze,resolveRelationPredicates as xt}from"./DEFAULT_MAX_RELATION_KEYS-XESc7TiB.mjs";import{runRowValidators as et,resolveWith as bt,relationHooks as Mt,applyOnDelete as Vn,fanOutScalarCounts as zn}from"./applyOnDelete-7JZ4vR9r.mjs";import{guardWriter as Jn}from"./RLS_UNWRAP_SYMBOL-BwwTbz3Q.mjs";import{quoteIdentifier as Re}from"./quoteIdentifier-CObIFRhb.mjs";import{m as Yn}from"./sql-projection-D3qdaItY.mjs";import{createSystemReader as Xn}from"./createSystemReader-DcDLFfC-.mjs";import{ConflictError as me}from"./ConflictError-C8GtJmjS.mjs";import{runTriggers as Zn}from"./hasTrigger-CjlwI4le.mjs";import{c as ne,t as Ge,r as Ue,j as Se,i as Dt}from"./where-sql-x1YKldcq.mjs";import{CLIENT_WATERMARK_TABLE as ti,advanceClientWatermark as ni,migrateClientWatermark as oi,readClientWatermark as ri}from"./CLIENT_WATERMARK_TABLE-CRnrAnJ2.mjs";import{GLOBAL_SHAPE_SNAPSHOT_TABLE as si,deleteGlobalShapeSnapshot as ci,deleteGlobalShapeSnapshotsForConnection as ai,migrateGlobalShapeSnapshot as di,readGlobalShapeSnapshot as li,writeGlobalShapeSnapshot as ui}from"./GLOBAL_SHAPE_SNAPSHOT_TABLE-DSA6mzyx.mjs";import{IDEMPOTENCY_TABLE as hi,readIdempotent as wi,trimIdempotent as pi,writeIdempotent as gi}from"./IDEMPOTENCY_TABLE-DOpm_oMF.mjs";import{runShardMigrations as yi}from"./runShardMigrations-BLl8xFGK.mjs";import{S as mi}from"./ctx-db-search-state-ruTuCsxa.mjs";import{selectShapeMembers as _i,selectShapeRows as Ri}from"./selectShapeMembers-B8gTOeOB.mjs";import{serializeSqlValue as re}from"./serializeSqlValue-BEMMYX1n.mjs";const eo=o=>{const r=atob(o),t=Uint8Array.from(r,a=>a.codePointAt(0)??0);return new TextDecoder().decode(t)},to=()=>new $("BAD_REQUEST","invalid cursor"),Lt=16,kt=8,Y=1024,at=(o,r)=>r.query(o),no=(o,r)=>{if(o.length===0)return 0;let t=0;for(const[a,d]of r.entries()){const w=a===r.length-1;let S=0;for(const T of o)(w?T.startsWith(d):T===d)&&(S+=1);if(S===0)return 0;t+=S}return t},oo=(o,r)=>{if(!r)return{exact:!0,lower:o,upper:o};const t=[...o].at(-1)??"",a=(t.codePointAt(0)??0)+1;if(a>=55296&&a<=57343||a>1114111)return{exact:!0,lower:o,upper:o};const d=o.slice(0,o.length-t.length);return{exact:!1,lower:o,upper:d+String.fromCodePoint(a)}},ro=(o,r,t)=>{const a={eq:(d,w)=>{if(!o.definition.filterFields?.includes(d))throw new $("INTERNAL",`field "${d}" is not a filter field of search index "${o.indexName}" on table "${r}"`);if(o.filters.length>=kt)throw new $("BAD_REQUEST",`search index "${o.indexName}" on table "${r}": at most ${String(kt)} .eq() filters are supported per search query`);return o.filters.push({field:d,value:w}),a},search:(d,w)=>{const S=o;if(d!==S.definition.field)throw new $("INTERNAL",`search index "${S.indexName}" on table "${r}" indexes "${S.definition.field}", not "${d}"`);const T=at(w,t).length;if(T>Lt)throw new $("BAD_REQUEST",`search index "${S.indexName}" on table "${r}": at most ${String(Lt)} search terms are supported (got ${String(T)})`);return S.field=d,S.query=w,S.hasQuery=!0,a}};return a},io=o=>{if(o.length>Y)throw new $("BAD_REQUEST",`more than ${String(Y)} documents match this search — narrow it with filters or read it a page at a time with .paginate()`)},so=o=>Math.min(o.offset+o.numItems+1,Y),co=o=>btoa(`search:${String(o)}`),ao=o=>{let r;try{r=eo(o)}catch{return}if(!r.startsWith("search:"))return;const t=Number(r.slice(7));return Number.isInteger(t)&&t>=0?t:void 0},lo=o=>{if(typeof o.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(o.numItems))throw new $("BAD_REQUEST",`search pagination needs a finite numItems, got ${String(o.numItems)}`);const r=Math.max(0,Math.floor(o.numItems)),t=o.cursor?ao(o.cursor):0;if(t===void 0)throw to();if(t+r>=Y)throw new $("BAD_REQUEST",`search pagination reaches the ${String(Y)}-document limit (offset ${String(t)} + ${String(r)} requested) — a page must end below the cap so the probe row that answers \`hasMore\` still fits: retry with numItems ${String(Math.max(1,Y-t-1))} or fewer, or narrow the query or the filters instead`);return{numItems:r,offset:t}},uo=(o,r)=>{const t=r.offset+r.numItems,a=r.numItems>0&&o.length>t;return{continueCursor:a?co(t):null,isDone:!a,page:o.slice(r.offset,t)}},fo=o=>{if(o===void 0)return Y+1;if(!Number.isFinite(o))return Y;const r=Math.max(0,Math.floor(o));if(r>Y)throw new $("BAD_REQUEST",`search returns at most ${String(Y)} documents (asked for ${String(r)}) — narrow the query or paginate instead`);return r},He=o=>{const r=new Map;return t=>{const a=r.get(t);if(a!==void 0)return a;const d=o(Re(t));return r.set(t,d),d}},fe=Re(oe),ho=He(o=>`INSERT INTO ${o} (id, _creationTime, ${fe}) VALUES (?, ?, ?)`),Ft=He(o=>`UPDATE ${o} SET ${fe} = ? WHERE id = ? AND ${fe} = ?`),wo=He(o=>`UPDATE ${o} SET _creationTime = ?, ${fe} = ? WHERE id = ? AND ${fe} = ?`),po=He(o=>`DELETE FROM ${o} WHERE id = ? AND ${fe} = ?`),go="SELECT changes() AS changed",qt=new Map,$o="",yo=o=>{const r=JSON.stringify(o),t=qt.get(r);if(t!==void 0)return t;const a=o.map(w=>i`SELECT ${i.raw(`'${w.replaceAll("'","''")}'`)} AS __t__, id, _creationTime, ${i.identifier(oe)} FROM ${i.identifier(w)} WHERE id = ${$o}`),{sql:d}=Vt("sqlite",i`${ct(a)} LIMIT 1`);return qt.set(r,d),d},Eo=(o,r)=>r.map(()=>o),mo=/^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/iu,So=o=>{if(!mo.test(o))throw new $("INTERNAL",`invalid clientId ${JSON.stringify(o)}: a client-supplied row id must be a UUID`)},Bt=50,Zt=500,Be=Math.floor(zt.boundParams/3),ye=zt.boundParams,_o=128,de=(o,r,t)=>{const a=r??Zt;if(o>a)throw new $("BATCH_LIMIT_EXCEEDED",`${t}: batch of ${String(o)} exceeds the limit of ${String(a)} (raise options.limit or chunk the call)`,{status:400})},Ro=o=>{const r={eq:(t,a)=>(o.sqlConditions.push({comparator:"=",field:t,value:a}),r),gt:(t,a)=>(o.sqlConditions.push({comparator:">",field:t,value:a}),r),gte:(t,a)=>(o.sqlConditions.push({comparator:">=",field:t,value:a}),r),lt:(t,a)=>(o.sqlConditions.push({comparator:"<",field:t,value:a}),r),lte:(t,a)=>(o.sqlConditions.push({comparator:"<=",field:t,value:a}),r)};return r},To=o=>Math.max(o,Y),en=(o,r)=>{const t=o.filters.map(a=>i`${Z(a.field)} = ${re(a.value)}`);return r&&t.push(r),t},vo=(o,r,t,a,d)=>{const w=at(t.query,st(t.definition.language));if(w.length===0)return[];const S=gn(r,t.indexName),T=`${S}__vocab`,y=w.length-1,k=w.map((q,_)=>{const F=oo(q,_===y),j=F.exact?i`${i.identifier("term")} = ${F.lower}`:i`${i.identifier("term")} >= ${F.lower} AND ${i.identifier("term")} < ${F.upper}`;return i`SELECT ${i.identifier("doc")}, ${i.raw(String(_))} AS ${i.identifier("__term__")}, COUNT(*) AS ${i.identifier("__n__")} FROM ${i.identifier(T)} WHERE ${j} GROUP BY ${i.identifier("doc")}`}),g=w.map((q,_)=>i`SUM(CASE WHEN u.${i.identifier("__term__")} = ${i.raw(String(_))} THEN u.${i.identifier("__n__")} ELSE 0 END)`),A=i`SELECT f.${i.identifier(Le)} AS ${i.identifier(Le)}, ${i.join(g,i` + `)} AS ${i.identifier("__score__")} FROM (${ct(k)}) u JOIN ${i.identifier(S)} f ON f.rowid = u.${i.identifier("doc")} GROUP BY f.${i.identifier(Le)} HAVING ${i.join(g.map(q=>i`${q} > 0`),i` AND `)}`,I=en(t,d);let L=i`SELECT m.id, m._creationTime, m.${i.identifier(oe)}, s.${i.identifier("__score__")} AS ${i.identifier("__score__")} FROM (${A}) s JOIN ${i.identifier(r)} m ON m.id = s.${i.identifier(Le)}`;I.length>0&&(L=i`${L} WHERE ${i.join(I,i` AND `)}`),L=i`${L} ORDER BY s.${i.identifier("__score__")} DESC, m._creationTime DESC, m.id ASC LIMIT ${i.raw(String(a))}`;const N=[];for(const q of O(o,L)){const _=Qt(q);if(_){const F=q.__score__;N.push({document:_,score:typeof F=="number"?F:Number(F??0)})}}return N},Ao=(o,r,t,a,d)=>{const w=st(t.definition.language),S=at(t.query,w);if(S.length===0)return[];const T=en(t,d);let y=i`SELECT id, _creationTime, ${i.identifier(oe)} FROM ${i.identifier(r)}`;T.length>0&&(y=i`${y} WHERE ${i.join(T,i` AND `)}`),y=i`${y} ORDER BY _creationTime DESC, id ASC LIMIT ${i.raw(String(To(a)))}`;const k=O(o,y).toArray(),g=[];for(const A of k){const I=Qt(A);if(!I)continue;const L=no($n(I,t.definition),S);L>0&&g.push({creationTime:typeof I._creationTime=="number"?I._creationTime:0,doc:I,id:typeof I._id=="string"?I._id:"",score:L})}return g.sort((A,I)=>I.score-A.score||I.creationTime-A.creationTime||A.id.localeCompare(I.id)),g.slice(0,a).map(A=>({document:A.doc,score:A.score}))},tt=(o,r,t,a)=>{if(!Number.isFinite(o.lat)||o.lat<-90||o.lat>90||!Number.isFinite(o.lng)||o.lng<-180||o.lng>180)throw new $("BAD_REQUEST",`geo index "${a}" on table "${t}": ${r} must have a finite lat in [-90, 90] and lng in [-180, 180]`)},Io=(o,r)=>{const t=o,a={near:(d,w)=>{if(t.within)throw new $("INTERNAL",`geo index "${t.indexName}" on table "${r}": call .near() or .within(), not both`);if(tt(d,".near() point",r,t.indexName),!Number.isFinite(w)||w<=0)throw new $("BAD_REQUEST",`geo index "${t.indexName}" on table "${r}": .near() radiusMeters must be a finite number > 0, got ${String(w)}`);return t.near={point:{lat:d.lat,lng:d.lng},radiusMeters:w},a},within:d=>{if(t.near)throw new $("INTERNAL",`geo index "${t.indexName}" on table "${r}": call .near() or .within(), not both`);if(tt(d.sw,".within() sw corner",r,t.indexName),tt(d.ne,".within() ne corner",r,t.indexName),d.sw.lat>d.ne.lat)throw new $("BAD_REQUEST",`geo index "${t.indexName}" on table "${r}": .within() corners are transposed (sw.lat > ne.lat)`);if(d.sw.lng>d.ne.lng)throw new $("BAD_REQUEST",`geo index "${t.indexName}" on table "${r}": .within() box crosses the antimeridian (sw.lng > ne.lng), which is not supported — split it into two boxes at ±180 and union the results`);return t.within={ne:{lat:d.ne.lat,lng:d.ne.lng},sw:{lat:d.sw.lat,lng:d.sw.lng}},a}};return a},Co=(o,r)=>{const t=o[r];if(t===null||typeof t!="object")return;const{lat:a,lng:d}=t;return typeof a=="number"&&typeof d=="number"?{lat:a,lng:d}:void 0},xo=(o,r)=>{const t=Co(o,r.definition.field);if(!t)return;const a=typeof o._creationTime=="number"?o._creationTime:0;if(r.near){const d=Fn(r.near.point,t);return d<=r.near.radiusMeters?{creationTime:a,distance:d}:void 0}return qn(t,r.within)?{creationTime:a,distance:0}:void 0},bo=(o,r,t,a)=>{if(!t.near&&!t.within)throw new $("INTERNAL",`geo index "${t.indexName}" on table "${r}": call .near(point, radius) or .within(box)`);const d=t.near?Ln(t.near.point,t.near.radiusMeters):kn(t.within),w=Mn(r,t.indexName),S=d.map(A=>i`(g.${i.identifier("__geohash__")} >= ${A} AND g.${i.identifier("__geohash__")} < ${`${A}{`})`),T=[i`(${i.join(S,i` OR `)})`];a&&T.push(a);const y=i`SELECT m.id, m._creationTime, m.${i.identifier(oe)} FROM ${i.identifier(w)} g JOIN ${i.identifier(r)} m ON m.id = g.${i.identifier("__id__")} WHERE ${i.join(T,i` AND `)}`,k=O(o,y).toArray(),g=[];for(const A of k){const I=ue(A),L=I?xo(I,t):void 0;I&&L&&g.push({creationTime:L.creationTime,distance:L.distance,doc:I})}return g.sort((A,I)=>A.distance-I.distance||I.creationTime-A.creationTime),g},tn=(o,r,t,a)=>{const d=[];for(const w of o)if(r.every(S=>S(a(w)))&&(d.push(w),typeof t=="number"&&d.length>=t))break;return d},Mo=(o,r,t,a,d,w=()=>{})=>{const S=t.within!==void 0,T=bo(o,r,t,d).map(y=>({distanceMeters:S?null:y.distance,document:y.doc}));return w(T.length),typeof a=="number"?T.slice(0,Math.max(0,Math.floor(a))):T},nn=(o,r,t,a,d,w=()=>{})=>{const{geo:S}=t;if(!S)throw new $("INTERNAL","runGeoTerminalScored called without a staged geo query");const T=t.inMemoryFilters.length>0,y=Mo(o,r,S,T?void 0:d,a,w);return T?tn(y,t.inMemoryFilters,d,k=>k.document):y},on=(o,r,t,a)=>{const d=`SELECT id, _creationTime, ${Re(oe)} FROM ${Re(o)}`,w=`ORDER BY ${t}${a===void 0?"":` LIMIT ${String(a)}`}`;return r===void 0?Ue(`${d} ${w}`):Se(`${d} WHERE `,r,` ${w}`)},Do=(o,r,t,a,d,w=()=>{})=>nn(o,r,t,a,d,w).map(S=>S.document),Lo=(o,r,t,a,d,w,S=()=>{})=>{const T=[];for(const A of t.sqlConditions)T.push(i`${Z(A.field)} ${i.raw(A.comparator)} ${re(A.value)}`);a&&T.push(a);let y=i`SELECT id, _creationTime, ${i.identifier(oe)} FROM ${i.identifier(r)}`;T.length>0&&(y=i`${y} WHERE ${i.join(T,i` AND `)}`),y=i`${y} ORDER BY ${d}`,typeof w=="number"&&t.inMemoryFilters.length===0&&(y=i`${y} LIMIT ${i.raw(String(Math.max(0,Math.floor(w))))}`);const k=O(o,y).toArray();S(k.length);const g=[];for(const A of k){const I=ue(A);if(I&&t.inMemoryFilters.every(L=>L(I))&&(g.push(I),typeof w=="number"&&g.length>=w))break}return g},Ee={fieldRef:Z,serialize:re},rn=(o,r)=>{const t=r===void 0?void 0:o.shape[r];return t!==void 0&&Yn(t)},Wt=(o,r)=>r.some(t=>rn(o,t)),Pt=(o,r,t)=>{if(rn(o,r))throw new $("BAD_REQUEST",`${t}: "${r}" may hold an order-preserving key rather than a value SQL can reduce or group — declare an aggregateIndex covering this (by, field, op) so the maintained companion answers it instead (its running total is a REAL, so it stays exact only while the total is inside 2^53)`)},dt={fieldRef:o=>Ue(Pe(o)),serialize:re},ko=o=>{let r=0;const t=[],a={fieldRef:d=>Ue(Pe(d)),relationExists:d=>{const{childWhere:w,negated:S,parentTable:T,relation:y}=d,k=`__rel_${String(r)}`,g=t.at(-1)??T;r+=1,o(y.table,G);const A=y.kind==="one"?y.field:y.references,I=y.kind==="one"?y.references:y.field,L=Ue(`${Tt(k,I)} = ${Tt(g,A)}`);t.push(k);const N=ne(w,a,Ge);t.pop();const q=N===void 0?L:Se(L," AND ",N),_=Se("EXISTS (SELECT 1 FROM ",Dt(y.table)," AS ",Dt(k)," WHERE ",q,")");return S?Se("NOT ",_):_},serialize:re};return a},sn=o=>{const r=o.map(t=>`${Pe(t.field)} ${t.direction==="desc"?"DESC":"ASC"}`);return o.some(t=>t.field==="_id"||t.field==="id")||r.push(`${Pe("id")} ${Xt(o)==="desc"?"DESC":"ASC"}`),r.join(", ")},Fo=o=>{const r=o.map(t=>i`${Z(t.field)} ${i.raw(t.direction==="desc"?"DESC":"ASC")}`);return o.some(t=>t.field==="_id"||t.field==="id")||r.push(i`${Z("id")} ${i.raw(Xt(o)==="desc"?"DESC":"ASC")}`),i.join(r,i`, `)},qo={"<":"lt","<=":"lte","=":"eq",">":"gt",">=":"gte"},cn=o=>new Set(o.sqlConditions.filter(r=>r.comparator==="=").map(r=>r.field)),Bo=o=>{const r=cn(o);let t=0;for(;t<o.indexFields.length&&r.has(o.indexFields[t]??"");)t+=1;return o.indexFields.slice(t)},an=(o,r)=>{const t=o.order,a=Bo(o),{shape:d}=r;return a.length>0?nt(a.map(w=>({[w]:t})),d,{pinned:cn(o),uniqueBy:Jt(r.indexes,d)}):nt([{_creationTime:t}],d)},Wo=(o,r,t,a)=>{const d=o.sqlConditions.map(w=>({[w.field]:{[qo[w.comparator]??"eq"]:w.value}}));if(t&&d.push(Yt(r,ot(t))),a&&d.push(Pn(r,ot(a))),d.length!==0)return d.length===1?d[0]:{AND:d}},Po=(o,r,t)=>{const a=[];for(const d of o){const w=ue(d);if(w&&r.every(S=>S(w))&&(a.push(w),t!==void 0&&a.length>t))break}return a},Uo=(o,r,t,a,d,w,S=()=>{})=>{const T=Math.max(0,Math.floor(d.numItems)),y=an(a,t),k=typeof d.endCursor=="string",g=ne(Wo(a,y,d.cursor,d.endCursor),dt,Ge),A=w&&g?Se(g," AND ",w):w??g,I=a.inMemoryFilters.length>0,L=on(r,A,sn(y),I||k?void 0:T+1),N=_e(o,L.text,...L.params).toArray();S(N.length);const q=Po(N,a.inMemoryFilters,I||k?void 0:T);if(k){const H=q.length>=2?q[Math.floor(q.length/2)-1]:void 0;return{continueCursor:d.endCursor??null,isDone:!0,page:q,splitCursor:H?rt(H,y):null}}const _=q.length>T,F=_?q.slice(0,T):q,j=F.at(-1);return{continueCursor:_&&j?rt(j,y):null,isDone:!_,page:F}};class Go extends ${constructor(r="unique() found more than one matching document"){super("NOT_UNIQUE",r,{name:"NotUniqueError"})}}const Ho=/\s/u,Oo=String.fromCodePoint(0),Ut=(o,r,t)=>{if(!o.tables[r])throw new $("INTERNAL",`unknown table: ${r}`);return typeof t!="string"||t.length===0||Ho.test(t)||t.includes(Oo)?null:t},No=(o,r,t,a=()=>{},d=()=>{},w=()=>{})=>{const S=r.tables[t];if(!S)throw new $("INTERNAL",`unknown table: ${t}`);const T=le(S.softDeleteMode,void 0),y=T?ne(T,Ee):void 0,k=T?ne(T,dt,Ge):void 0,g={indexFields:[],indexName:void 0,inMemoryFilters:[],order:"asc",sqlConditions:[]};let A=0;const I=E=>{const{search:x}=g;if(!x)throw new $("INTERNAL","runSearchFetch called without a staged search");Tn(o,t,S);const b=g.inMemoryFilters.length>0,D=fo(b?void 0:E),z=bn(o);if(z&&!vn(o,t,x.definition))throw new $("SEARCH_INDEX_BUILDING",`search index "${x.indexName}" on table "${t}" is still backfilling and currently covers only part of the table — retry once it finishes, or run the backfillSearch admin operation to complete it now`);const X=z?vo(o,t,x,D,y):Ao(o,t,x,D,y);return b?(A=X.length,tn(X,g.inMemoryFilters,E,ce=>ce.document)):(E===void 0&&io(X),X)},L=E=>I(E).map(x=>x.document),N=E=>{const x=lo(E);return uo(L(so(x)),x)},q=()=>Fo(an(g,S)),_=()=>{if(g.search||g.geo||g.indexName===void 0){d(void 0);return}d(jn(t,g.indexName,g.indexFields,g.sqlConditions,re))},F=E=>{_();let x=0;const b=(()=>{if(g.search){const D=L(E);return x=A,D}return g.geo?Do(o,t,g,y,E,D=>{x=D}):Lo(o,t,g,y,q(),E,D=>{x=D})})();return w(Math.max(x,b.length)),b},j=()=>{if(!g.search&&!g.geo)throw new $("INTERNAL",`ctx.db.query("${t}").collectWithScores() requires a staged .withSearchIndex(...) or .withGeoIndex(...)`);_();let E=0;const x=(()=>{if(g.search){const b=I(void 0);return E=A,b}return nn(o,t,g,y,void 0,b=>{E=b})})();return w(Math.max(E,x.length)),x},H={async*[Symbol.asyncIterator](){if(g.search){yield*F(void 0);return}const E=[...g.inMemoryFilters];let x;g.inMemoryFilters=[];try{for(;;){const b=await H.paginate({cursor:x??null,numItems:_o});for(const D of b.page)E.every(z=>z(D))&&(yield D);if(b.isDone||b.continueCursor===null)return;x=b.continueCursor}}finally{g.inMemoryFilters=E}},async collect(){return F(void 0)},async collectWithScores(){return j()},filter(E){return g.inMemoryFilters.push(E),H},async first(){return F(g.inMemoryFilters.length>0?void 0:1)[0]??null},order(E){return g.order=E==="desc"?"desc":"asc",H},async paginate(E){let x=0;if(_(),g.search){const D=N(E);return w(D.page.length),D}if(g.geo)throw new $("INTERNAL","pagination is not supported on geo queries; use .take(n) or .collect()");const b=Uo(o,t,S,g,E,k,D=>{x=D});return w(Math.max(x,b.page.length)),b},async take(E){return F(E)},async unique(){const E=F(g.inMemoryFilters.length>0?void 0:2);if(E.length>1)throw new Go(`unique() on table "${t}" matched ${String(E.length)} documents; expected at most one`);return E[0]??null},withGeoIndex(E,x){const b=(S.geoIndexes??[]).find(z=>z.name===E);if(!b)throw new $("INTERNAL",`unknown geo index "${E}" on table "${t}"`);a(t,E,"geo");const D={definition:b,indexName:E};if(g.geo=D,x(Io(D,t)),!D.near&&!D.within)throw new $("INTERNAL",`geo index "${E}" on table "${t}" requires a .near(point, radius) or .within(box) call`);return H},withIndex(E,x){const b=S.indexes.find(D=>D.name===E);if(!b)throw new $("INTERNAL",`unknown index "${E}" on table "${t}"`);return a(t,E,"index"),g.indexName=E,g.indexFields=b.fields,x&&x(Ro(g)),H},withSearchIndex(E,x){const b=(S.searchIndexes??[]).find(z=>z.name===E);if(!b)throw new $("INTERNAL",`unknown search index "${E}" on table "${t}"`);a(t,E,"search");const D={definition:b,field:b.field,filters:[],hasQuery:!1,indexName:E,query:""};if(g.search=D,x(ro(D,t,st(b.language))),!D.hasQuery)throw new $("INTERNAL",`search index "${E}" on table "${t}" requires a .search(field, query) call`);return H}};return H},Gt=(o,r,t)=>{const a={...r};for(const[d,w]of Kt(o)){if(w.serverDefault){a[d]=w.serverDefault({auth:t});continue}a[d]===void 0&&(w.defaultFn?a[d]=w.defaultFn():"defaultValue"in w&&(a[d]=w.defaultValue))}return a},Ht=(o,r,t,a)=>{const d=t;for(const[w,S]of Kt(o)){if(S.serverDefault){w in r&&(d[w]=S.serverDefault({auth:a}));continue}S.onUpdateFn&&!(w in r)&&(d[w]=S.onUpdateFn())}},Ot=(o,r)=>{for(const t of Object.keys(r))if(r[t]===void 0)throw new $("INTERNAL",`Cannot ${o} field '${t}' to undefined — use null to clear a nullable field, or omit the key to leave it unchanged.`)},Nt=["_commitSeq","_creationTime","_id"],jo=o=>Nt.some(r=>r in o)?Object.fromEntries(Object.entries(o).filter(([r])=>!Nt.includes(r))):o,Ko=/unique constraint failed/i,Qo=o=>o instanceof Error&&Ko.test(o.message),Vo=/string or blob too big/iu,zo=(o,r)=>{if(!(!(o instanceof Error)||!Vo.test(o.message)))throw new $("PAYLOAD_TOO_LARGE",`document is too large to store in "${r}": a single row cannot exceed the storage engine's per-row ceiling (2 MB on a Durable Object's SQLite). The limit is on the STORED bytes, which are UTF-8, and v.bytes()/v.bigint() columns are stored twice on a shard-local table. Keep the payload in R2 (ctx.storage) and store a reference on the row.`)},it=(o,r,t,a)=>{try{_e(o,t,...a)}catch(d){throw Qo(d)?new me(`unique constraint violation on "${r}"`,"unique"):(zo(d,r),d)}},We=(o,r,t,a)=>{if(it(o,r,t,a),_e(o,go).one().changed===0)throw new me(`optimistic concurrency conflict on "${r}" — the row changed during this mutation; refetch and retry`,"occ")},jt=(o,r,t,a,d,w,S)=>{const T=[];for(let A=0;A<t.length+1;A+=1){const I=t[A],L=a[A],N=L?.direction==="desc"?"desc":"asc",q=I===void 0||L===void 0?i`${i.identifier(Hn)} < ${S}`:On(I,w[A],N,!1);if(q===void 0)continue;const _=[];for(let j=0;j<A;j+=1)_.push(i`${i.identifier(t[j])} IS ${w[j]}`);_.push(q);const[F]=_;T.push(_.length===1&&F!==void 0?F:i`(${i.join(_,i` AND `)})`)}const y=T.length>0?i.join(T,i` OR `):i`1 = 0`,k=O(o,i`SELECT COUNT(*) AS c FROM ${i.identifier(r)} WHERE ${i.identifier("__partition__")} = ${d} AND (${y})`).one(),g=O(o,i`SELECT COUNT(*) AS c FROM ${i.identifier(r)} WHERE ${i.identifier("__partition__")} = ${d}`).one();return{before:k.c,total:g.c}},br=o=>{const{sql:r}=o,{schema:t}=o,a=o.broadcast??(()=>{}),d=Kn(t);let w;const S=()=>o.inTransaction?.()===!0,T=e=>t.tables[e]?.commitOrderedMode!==!0?{}:((w===void 0||!S())&&(w=In(r)),{[Cn]:w}),y=(e,...n)=>{const s=t.tables[e]?.indexes;if(!s||s.length===0)return;const f=[];for(const h of n)h&&f.push(...Nn(s,h,re));return f.length>0?f:void 0},{headroom:k}=o;let g=!1;const A=async e=>{const n=g;g=!0;try{return await e()}finally{g=n}},I=o.onRead??(()=>{}),L=e=>{_t(t.tables[e])&&I(Ct,Ct)},N=o.onReadRange??(e=>{I(e.table,G)}),q=e=>{L(e.table),N(e)},_=(e,n)=>{n!==void 0&&n!==G&&!g&&k?.recordRead(1),L(e),I(e,n)},F=o.onIndexUse??(()=>{}),j=o.onWrite??(()=>{}),H=e=>{g||k?.recordWrite(e)},E=async e=>{H(e.doc),await j(e)},{cache:x}=o,b=o.clock??(()=>Date.now()),D=o.idGenerator??(()=>crypto.randomUUID()),z=o.scheduler??En,{globalDb:X}=o,ce=o.auth??{identity:null,userId:null},dn=o.cdc??!1,Oe=z,ln=Xn({scheduler:typeof Oe.list=="function"&&typeof Oe.get=="function"?Oe:void 0,storage:o.storage}),he=(e,n,s,f)=>{dn&&!_t(t.tables[e])&&An(r,b(),e,n,s,f)},ie=e=>t.tables[e]?.shardMode?.kind==="global",lt=(e,n)=>{if(ie(e)){if(!X)throw new $("INTERNAL",`cross-backend ${n} for global table '${e}' requires a globalDb writer — pass one to createShardCtxDb({ globalDb })`);return X}return P},Ne=e=>lt(e,"cascade"),Q=(e,n)=>{if(ie(e)){if(!X)throw new $("INTERNAL",`${n} on global table '${e}' requires a globalDb writer — pass one to createShardCtxDb({ globalDb })`);return X}},ut=async(e,n,s,f,h)=>{h&&H(s);const u=await e.insert(n,s,f);return a({key:u,op:"insert",row:{...s,_id:u},table:n}),u},je=(e,n)=>lt(e,"relation load").findMany(e,n),ft=(e,n)=>(ie(e)&&_(e,G),je(e,n)),un=e=>!ie(e.table),ht=o.relationExistsPushDown??"auto",wt=ht!=="never",{maxRelationKeys:pt}=o,Te=(e,n,s)=>xt(e,{fetcher:ft,maxRelationKeys:pt,relationBaseWhere:s,schema:t,tableName:n}),gt=async(e,n,s,f)=>{const h=Q(e,"relation grouped count");if(h)return _(e,G),zn((W,C)=>h.count(W,C),e,n,s,f);const u=t.tables[e];if(!u)throw new $("INTERNAL",`unknown table: ${e}`);_(e,G);const c=le(u.softDeleteMode,void 0),l={[n]:{in:s}},p=V(V(l,f),c),v=await Te(p,e,void 0),m=ne(v,Ee),M=Z(n);let R=i`SELECT ${M} AS __fk__, COUNT(*) AS count FROM ${i.identifier(e)}`;m&&(R=i`${R} WHERE ${m}`),R=i`${R} GROUP BY ${M}`;const B=O(r,R).toArray();return new Map(B.map(W=>[W.__fk__,W.count]))};let ve=0;const $t=new Set;for(const[e,n]of Object.entries(t.tables))for(const s of Object.values(n.triggerMap??{}))$t.add(`${e} ${s.timing} ${s.op}`);const ee=(e,n,s)=>$t.has(`${e} ${n} ${s}`),te=async(e,n,s)=>{if(ve+=1,ve>Bt)throw ve-=1,new me(`trigger recursion exceeded ${String(Bt)} levels on "${s.table}" — check for a self-triggering write`,"trigger");try{await Zn({ctx:hn,event:s,op:n,schema:t,tableName:s.table,timing:e})}finally{ve-=1}},{ensureBackfilledForTable:we,ensureBackfilledIndex:Ke,ensureRankBackfilled:Qe,ensureRankBackfilledForTable:pe,syncAggregates:Ae,syncCompanionsForInsert:yt,syncGeo:Ie,syncRanks:ge,syncSearch:Ce}=pn({broadcast:a,indexKeysFor:(e,n)=>y(e,n),invalidateCache:(e,n,s)=>x?.invalidate(e,n,y(e,s)),recordCdc:he,schema:t,sql:r}),Et=(e,n,s)=>{const{shardMode:f}=n;if(f?.kind==="shardBy"&&!(f.field!==void 0&&(s.partitionBy??[]).includes(f.field)))throw Object.assign(new Error(`rank index "${s.name}" on "${e}" partitions across shards (shard key "${f.field??"?"}" is not in partitionBy) — a shard-local rank()/rankPage() would be wrong; roll it up through the Query Coordinator instead`),{code:"CROSS_SHARD_RANK_UNSUPPORTED",name:"LunoraError",status:400})},mt=e=>Object.entries(t.tables).filter(([,n])=>n.shardMode?.kind!=="global").map(([n])=>n).filter(n=>e===void 0||n===e),$e=e=>e===void 0||ie(e)?X:void 0,se=(e,n)=>{const s=mt(n);for(let f=0;f<s.length;f+=ye){const h=s.slice(f,f+ye),[u]=_e(r,yo(h),...Eo(e,h)).toArray();if(!u)continue;const c=u.__t__,l=ue(u);if(typeof c!="string"||!l)return;const p=u[oe];return{docJson:typeof p=="string"?p:ae(p??{}),row:l,tableName:c}}},fn=(e,n)=>{const s=[...new Set(e)],f=new Map;if(s.length===0)return f;const h=mt(n);for(let u=0;u<h.length;u+=ye){const c=h.slice(u,u+ye),l=Math.floor(ye/c.length),p=Dn(i`${i.identifier("id")}`,s,!1,l),v=c.map(m=>i`SELECT ${i.raw(`'${m.replaceAll("'","''")}'`)} AS __t__, id FROM ${i.identifier(m)} WHERE ${p}`);for(const m of O(r,ct(v))){const{id:M,__t__:R}=m;typeof R=="string"&&typeof M=="string"&&f.set(M,R)}}return f},St={assertRankPartitionLocal:Et,ensureRankBackfilled:Qe,onRead:_,rowToDocument:ue,schema:t,sql:r},P={system:ln,async aggregate(e,n){const s=Q(e,"aggregate");if(s)return _(e,G),s.aggregate(e,n);const f=t.tables[e];if(!f)throw new $("INTERNAL",`unknown table: ${e}`);if(ke(n.op),n.op==="count")return P.count(e,{baseWhere:n.baseWhere,relationBaseWhere:n.relationBaseWhere,restrictsCounts:n.restrictsCounts,where:n.where});if(!n.field)throw new $("INTERNAL",`aggregate(${e}, { op: "${n.op}" }): "field" is required for non-count reducers`);_(e,G);const h=le(f.softDeleteMode,void 0),u=V(V(n.baseWhere,n.where),h),c=await Te(u,e,n.relationBaseWhere),l=c!==u;if(f.aggregateIndexes&&!n.baseWhere&&!l&&(!h||Wt(f,[n.field]))){const W=Rn(f.aggregateIndexes,n.op,n.field,n.where);if(W){Ke(e,W.index);const C=ze(W.index.by??[],W.key),K=Ve(e,W.index.name),J=O(r,i`SELECT ${Fe} AS value, ${Xe} AS count FROM ${i.identifier(K)} WHERE ${qe} = ${C}`).toArray()[0];return Je(n.op,J)}}Pt(f,n.field,`aggregate(${e}, { op: "${n.op}", field: "${n.field}" })`);const p=ne(c,Ee),v=ke(n.op),m=Z(n.field);let M=i`SELECT ${i.raw(v)}(${m}) AS value FROM ${i.identifier(e)}`;p&&(M=i`${M} WHERE ${p}`);const B=O(r,M).toArray()[0]?.value;return B??null},asId(e,n){const s=Ut(t,e,n);if(s===null)throw new $("BAD_REQUEST",`asId("${e}", …): "${n}" is not a valid id for table "${e}"`,{status:400});return s},async count(e,n){const s=Q(e,"count");if(s)return _(e,G),s.count(e,n);const f=t.tables[e];if(!f)throw new $("INTERNAL",`unknown table: ${e}`);const h=mn(n);if(h.restrictsCounts)throw new Ye(e);_(e,G);const u=le(f.softDeleteMode,void 0),c=V(V(h.baseWhere,h.where),u),l=await Te(c,e,h.relationBaseWhere),p=l!==c;if(f.aggregateIndexes&&!h.baseWhere&&!p&&!u){const R=_n(f.aggregateIndexes,h.where);if(R){Ke(e,R.index);const B=ze(R.index.by??[],R.key),W=Ve(e,R.index.name),C=O(r,i`SELECT ${Fe} AS value FROM ${i.identifier(W)} WHERE ${qe} = ${B}`).toArray();return C[0]===void 0?0:C[0].value??0}}const v=ne(l,Ee);let m=i`SELECT COUNT(*) AS count FROM ${i.identifier(e)}`;return v&&(m=i`${m} WHERE ${v}`),O(r,m).one().count},async delete(e,n,s){const f=se(e,n);if(!f){const m=$e(n);m&&(H(void 0),await m.delete(e,n,s));return}const{docJson:h,row:u,tableName:c}=f,l=t.tables[c],p=s?.hard===!0,v=!p&&l?.softDeleteMode?l.softDeleteMode.field:void 0;if(!(v&&u[v]!==null&&u[v]!==void 0)){if(ee(c,"before","delete")&&await te("before","delete",{id:e,op:"delete",previous:u,table:c}),await Vn({deletedId:e,deletedReference:m=>u[m],findHolders:async(m,M,R)=>(await Ne(m).findMany(m,{includeDeleted:p,where:{[M]:R}})).page,onCascade:(m,M)=>Ne(m).delete(M,void 0,s),onRestrict:m=>{throw new me(m,"restrict")},onSetNull:(m,M,R)=>Ne(m).patch(M,{[R]:null}),schema:t,tableName:c}),we(c),pe(c),v){const m={...u,...T(c),[v]:b(),_id:e};We(r,c,Ft(c),[ae(m),e,h]),Ce(c,e,m,u),Ie(c,e,void 0),Ae(c,u,m),ge(c,e,u,void 0),x?.invalidate(c,e,y(c,u,m)),he(c,e,"update",m),a({indexKeys:y(c,u,m),key:e,op:"update",row:m,table:c}),ee(c,"after","delete")&&await te("after","delete",{id:e,op:"delete",previous:u,table:c}),await E({id:e,op:"delete",table:c});return}We(r,c,po(c),[e,h]),Ce(c,e,void 0),Ie(c,e,void 0),Ae(c,u,void 0),ge(c,e,u,void 0),x?.invalidate(c,e,y(c,u)),he(c,e,"delete"),a({indexKeys:y(c,u),key:e,op:"delete",table:c}),ee(c,"after","delete")&&await te("after","delete",{id:e,op:"delete",previous:u,table:c}),await E({id:e,op:"delete",table:c})}},async deleteAll(e,n){if(!t.tables[e])throw new $("INTERNAL",`unknown table: ${e}`);const s=Math.max(1,n?.chunkSize??Zt),f=n?.hard===void 0?void 0:{hard:n.hard},h=ie(e)?void 0:e;let u=0;return await A(async()=>{for(;;){const l=(await P.findMany(e,{limit:s})).page.map(p=>String(p._id));if(l.length===0)break;for(const p of l)await P.delete(p,h,f),u+=1;if(l.length<s)break}}),{deleted:u}},async deleteMany(e,n,s){de(e.length,n?.limit,"deleteMany");for(const f of e)await P.delete(f,s);return{deleted:e.length}},async deleteWhere(e,n,s){const u=(await(Q(e,"deleteWhere")??P).findMany(e,{where:n})).page.map(c=>String(c._id));if(de(u.length,s?.limit,"deleteWhere"),P.deleteMany===void 0)throw new $("INTERNAL",`ctx.db.${e}.deleteMany is unavailable: this writer has no batch delete`);return P.deleteMany(u,s)},async findFirst(e,n={}){return(await P.findMany(e,{...n,limit:1,omitContinueCursor:!0})).page[0]??null},async findFirstOrThrow(e,n={}){const s=await P.findFirst(e,n);if(s===null)throw new Bn(`findFirstOrThrow: no "${e}" document matched`);return s},async findMany(e,n={}){const s=Q(e,"findMany");if(s)return _(e,G),s.findMany(e,n);const f=t.tables[e];if(!f)throw new $("INTERNAL",`unknown table: ${e}`);const h=!n.where&&!n.baseWhere;h?_(e,G):_(e);const u=nt(n.orderBy,f.shape,{pinned:Wn(n.where),uniqueBy:Jt(f.indexes,f.shape)}),c=n.cursor?Yt(u,ot(n.cursor)):void 0;let l=V(n.baseWhere,n.where);l=V(l,le(f.softDeleteMode,n.includeDeleted)),l=await xt(l,{canPushExists:wt?un:void 0,existsPushMode:ht==="always"?"always":"auto",fetcher:ft,maxRelationKeys:pt,relationBaseWhere:n.relationBaseWhere,schema:t,tableName:e}),c&&(l=l?{AND:[l,c]}:c);const p=wt?ko(_):dt,v=ne(l,p,Ge),m=typeof n.limit=="number"?Math.max(0,Math.floor(n.limit)):void 0,M=on(e,v,sn(u),m===void 0?void 0:m+1),R=_e(r,M.text,...M.params).toArray();h&&!g&&k?.recordRead(R.length);const B=[];for(const J of R){const U=ue(J);U&&(B.push(U),!h&&typeof U._id=="string"&&_(e,U._id))}if(m===void 0)return n.with&&await bt({groupedCounter:gt,fetcher:je,parents:B,...Mt(n),schema:t,tableName:e,with:n.with}),{continueCursor:null,isDone:!0,page:vt(B,n.select,n.with)};const W=B.length>m,C=W?B.slice(0,m):B,K=C.at(-1);return n.with&&await bt({fetcher:je,groupedCounter:gt,parents:C,...Mt(n),schema:t,tableName:e,with:n.with}),{continueCursor:W&&K&&n.omitContinueCursor!==!0?rt(K,u):null,isDone:!W,page:vt(C,n.select,n.with)}},async get(e,n){const s=se(e,n);if(!s){const f=$e(n);return f?f.get(e,n):null}return _(s.tableName,e),s.row},async lookupById(e,n){const s=se(e,n);return s?(_(s.tableName,e),{row:s.row,tableName:s.tableName}):null},async groupBy(e,n){const s=Q(e,"groupBy");if(s)return _(e,G),s.groupBy(e,n);const f=t.tables[e];if(!f)throw new $("INTERNAL",`unknown table: ${e}`);_(e,G);const h=n.agg??{op:"count"};if(ke(h.op),h.op!=="count"&&!h.field)throw new $("INTERNAL",`groupBy(${e}, { agg: { op: "${h.op}" } }): "field" is required for non-count reducers`);const u=le(f.softDeleteMode,void 0),c=V(V(n.baseWhere,n.where),u),l=await Te(c,e,n.relationBaseWhere),p=l!==c,v=[...n.by,h.field];if(f.aggregateIndexes&&!n.baseWhere&&!p&&(!u||Wt(f,v))){const C=Sn(f.aggregateIndexes,h.op,h.field,n.by,n.where),K=C===void 0?0:Object.keys(C.partial).length,J=C?.index.by?.length??0;if(C&&(K===0||K===J)){Ke(e,C.index);const U=Ve(e,C.index.name),xe=Object.keys(C.partial),be=[];if(xe.length===(C.index.by??[]).length&&xe.length>0){const Me=ze(C.index.by??[],C.partial),De=O(r,i`SELECT ${Fe} AS value, ${Xe} AS count FROM ${i.identifier(U)} WHERE ${qe} = ${Me}`).toArray();return De.length>0&&be.push({key:{...C.partial},value:Je(h.op,De[0])}),be}const wn=O(r,i`SELECT ${qe} AS key, ${Fe} AS value, ${Xe} AS count FROM ${i.identifier(U)}`).toArray();for(const Me of wn){const De=yn(JSON.parse(Me.key));be.push({key:De,value:Je(h.op,Me)})}return be}}for(const C of v){if(C===void 0)continue;const K=C===h.field?`groupBy(${e}, { agg: { op: "${h.op}", field: "${C}" } })`:`groupBy(${e}, { by: [..."${C}"] })`;Pt(f,C,K)}const m=ne(l,Ee),M=n.by.map(C=>i`${Z(C)} AS ${i.identifier(C)}`);if(h.op==="count")M.push(i`COUNT(*) AS value`);else{const{field:C}=h;if(C===void 0)throw new $("INTERNAL",`groupBy(${e}, { agg: { op: "${h.op}" } }): "field" is required for non-count reducers`);M.push(i`${i.raw(ke(h.op))}(${Z(C)}) AS value`)}let R=i`SELECT ${i.join(M,i`, `)} FROM ${i.identifier(e)}`;m&&(R=i`${R} WHERE ${m}`),R=i`${R} GROUP BY ${i.join(n.by.map(C=>Z(C)),i`, `)}`;const B=O(r,R).toArray(),W=[];for(const C of B){const K={};for(const U of n.by)K[U]=xn(f.shape[U],C[U]??null);const{value:J}=C;W.push({key:K,value:J==null?null:Number(J)})}return W},async insert(e,n,s){const f=Q(e,"insert");if(f)return ut(f,e,n,s,!0);const h=t.tables[e];if(!h)throw new $("INTERNAL",`unknown table: ${e}`);const u=Gt(h,n,ce);et(h,u);let c;s?.clientId!==void 0?(So(s.clientId),c=s.clientId):s?.allowExplicitId&&typeof u._id=="string"?c=u._id:c=D();const l=s?.allowExplicitId&&typeof u._creationTime=="number"?u._creationTime:b(),p={...u,...T(e),_creationTime:l,_id:c};return ee(e,"before","insert")&&await te("before","insert",{doc:{...p},id:c,op:"insert",table:e}),we(e),pe(e),it(r,e,ho(e),[c,l,ae(p)]),yt(e,c,p),ee(e,"after","insert")&&await te("after","insert",{doc:p,id:c,op:"insert",table:e}),await E({doc:p,id:c,op:"insert",table:e}),c},async insertManyUnsafe(e,n,s){if(de(n.length,s?.limit,"insertManyUnsafe"),n.length===0)return[];const f=Q(e,"insert");if(f){const l=[];for(const p of n)H(p);for(const p of n){const v=await f.insert(e,p,{allowExplicitId:s?.allowExplicitId});a({key:v,op:"insert",row:{...p,_id:v},table:e}),l.push(v)}return l}const h=t.tables[e];if(!h)throw new $("INTERNAL",`unknown table: ${e}`);we(e),pe(e);const u=[];for(let l=0;l<n.length;l+=Be)u.push(T(e));const c=n.map((l,p)=>{const v=Gt(h,l,ce),m=s?.allowExplicitId===!0&&typeof v._id=="string"?v._id:D(),M=s?.allowExplicitId===!0&&typeof v._creationTime=="number"?v._creationTime:b(),R={...v,...u[Math.floor(p/Be)],_creationTime:M,_id:m};return{creationTime:M,document:R,id:m}});for(const l of c)H(l.document);for(let l=0;l<c.length;l+=Be){const p=i.join(c.slice(l,l+Be).map(m=>i`(${m.id}, ${m.creationTime}, ${ae(m.document)})`),i`, `),v=Vt("sqlite",i`INSERT INTO ${i.identifier(e)} (id, _creationTime, ${i.identifier(oe)}) VALUES ${p}`);it(r,e,v.sql,v.params)}for(const{document:l,id:p}of c)yt(e,p,l),await j({doc:l,id:p,op:"insert",table:e});return c.map(l=>l.id)},async insertMany(e,n,s){de(n.length,s?.limit,"insertMany");const f=s?.skipDuplicates===!0,h=[],u=Q(e,"insert");if(u)for(const l of n)H(l);const c=async l=>u?ut(u,e,l,void 0,!1):P.insert(e,l);for(const l of n)try{h.push(await c(l))}catch(p){if(f&&p instanceof me&&p.kind==="unique")h.push(null);else throw p}return h},normalizeId(e,n){return Ut(t,e,n)},async patch(e,n,s){const f=se(e,s);if(!f){const v=$e(s);if(v){H(n),await v.patch(e,n,s);return}throw new $("NOT_FOUND",`document not found: ${e}`)}const{docJson:h,row:u,tableName:c}=f,l=t.tables[c];if(!l)throw new $("INTERNAL",`unknown table: ${c}`);_(c,e),Ot("patch",n);const p={...u,...jo(n),...T(c),_id:e};Ht(l,n,p,ce),et(l,p,!0),ee(c,"before","update")&&await te("before","update",{doc:{...p},id:e,op:"update",previous:u,table:c}),we(c),pe(c),We(r,c,Ft(c),[ae(p),e,h]),Ce(c,e,p,u),Ie(c,e,p),Ae(c,u,p),ge(c,e,u,p),x?.invalidate(c,e,y(c,u,p)),he(c,e,"update",p),a({indexKeys:y(c,u,p),key:e,op:"update",row:p,table:c}),ee(c,"after","update")&&await te("after","update",{doc:p,id:e,op:"update",previous:u,table:c}),await E({doc:p,id:e,op:"update",table:c})},async patchMany(e,n,s){de(e.length,n?.limit,"patchMany");for(const f of e)await P.patch(f.id,f.patch,s);return{patched:e.length}},async patchWhere(e,n,s){const u=(await(Q(e,"patchWhere")??P).findMany(e,{where:n.where})).page.map(c=>({id:String(c._id),patch:n.patch}));if(de(u.length,s?.limit,"patchWhere"),P.patchMany===void 0)throw new $("INTERNAL",`ctx.db.${e}.patchMany is unavailable: this writer has no batch patch`);return await P.patchMany(u,s),{patched:u.length}},async related(e,n){return Qn(P,d,e,n)},relationEdges:d,query(e){const n=Q(e,"query");return n?(_(e,G),n.query(e)):No(r,t,e,F,s=>{s?q(s):_(e,G)},s=>{g||k?.recordRead(s)})},async rank(e,n,s){const f=Q(e,"rank");if(f)return _(e,G),f.rank(e,n,s);F(e,n,"rank");const h=t.tables[e];if(!h)throw new $("INTERNAL",`unknown table: ${e}`);const u=h.rankIndexes?.find(U=>U.name===n);if(!u)throw new $("INTERNAL",`unknown rankIndex "${n}" on table "${e}"`);if(Et(e,h,u),s.restrictsCounts)throw new Ye(e);_(e,G),Qe(e,u);const c=typeof s.row=="string"?s.row:s.row._id;if(!c)return null;const l=At(e,u.name),p=u.sortBy.map((U,xe)=>It(xe)),v=p.map(U=>Re(U)).join(", "),m=O(r,i`SELECT ${i.identifier("__partition__")}, ${i.raw(v)} FROM ${i.identifier(l)} WHERE ${i.identifier("__id__")} = ${c}`).toArray(),[M]=m;if(M===void 0)return null;let R=M.__partition__;const B=V(s.baseWhere,s.where);Ze(B,t,e,"rank");const W=Un(u,B);if(W){const U=Gn(u.partitionBy??[],W);if(U!==R)return null;R=U}const C=p.map(U=>M[U]),{before:K,total:J}=jt(r,l,p,u.sortBy,R,C,c);return{position:K+1,total:J}},async rankBefore(e,n,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=t.tables[e];if(!f)throw new $("INTERNAL",`unknown table: ${e}`);const h=f.rankIndexes?.find(p=>p.name===n);if(!h)throw new $("INTERNAL",`unknown rankIndex "${n}" on table "${e}"`);if(s.restrictsCounts)throw new Ye(e);_(e,G),Qe(e,h);const u=At(e,h.name),c=h.sortBy.map((p,v)=>It(v)),l=h.sortBy.map((p,v)=>re(s.sortValues[v]??null));return jt(r,u,c,h.sortBy,s.partitionKey,l,s.rowId)},async rankPage(e,n,s={}){Ze(V(s.baseWhere,s.where),t,e,"rankPage");const f=Q(e,"rankPage");if(f)return _(e,G),f.rankPage(e,n,s);F(e,n,"rank");const{continueCursor:h,hasMore:u,rows:c}=Rt(St,e,n,s);return{continueCursor:h,isDone:!u,page:c.map(l=>l.doc)}},async rankPageRows(e,n,s={}){Ze(V(s.baseWhere,s.where),t,e,"rankPage"),F(e,n,"rank");const{directions:f,hasMore:h,rows:u}=Rt(St,e,n,s);return{directions:f,hasMore:h,rows:u}},async restore(e,n){const s=se(e,n);if(!s){const u=$e(n);if(u?.restore){await u.restore(e,n);return}throw new $("NOT_FOUND",`document not found: ${e}`)}const f=t.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 P.patch(e,{[f]:null},n),h&&ge(s.tableName,e,void 0,s.row)},async replace(e,n,s,f){const h=se(e,s);if(!h){const B=$e(s);if(B){H(n),await B.replace(e,n,s,f);return}throw new $("NOT_FOUND",`document not found: ${e}`)}const{docJson:u,row:c,tableName:l}=h,p=t.tables[l];if(!p)throw new $("INTERNAL",`unknown table: ${l}`);Ot("replace",n);const v=f?.allowExplicitId&&typeof n._creationTime=="number"?n._creationTime:void 0,m=typeof c._creationTime=="number"?c._creationTime:void 0,M=v??m??b(),R={...n,...T(l),_creationTime:M,_id:e};Ht(p,n,R,ce),et(p,R),ee(l,"before","update")&&await te("before","update",{doc:{...R},id:e,op:"update",previous:c,table:l}),we(l),pe(l),We(r,l,wo(l),[M,ae(R),e,u]),Ce(l,e,R,c),Ie(l,e,R),Ae(l,c,R),ge(l,e,c,R),x?.invalidate(l,e,y(l,c,R)),he(l,e,"update",R),a({indexKeys:y(l,c,R),key:e,op:"update",row:R,table:l}),ee(l,"after","update")&&await te("after","update",{doc:R,id:e,op:"update",previous:c,table:l}),await E({doc:R,id:e,op:"update",table:l})},async wipeShard(e){const n=new Set(e?.exclude),s=e?.tables,f=Object.entries(t.tables).filter(([l,p])=>n.has(l)||s!==void 0&&!s.includes(l)?!1:p.shardMode?.kind!=="global").map(([l])=>l);if(s!==void 0){for(const l of s)if(!t.tables[l])throw new $("INTERNAL",`wipeShard: unknown table: ${l}`)}const h={};let u=0;const{deleteAll:c}=P;if(c===void 0)throw new $("INTERNAL","wipeShard: this writer has no deleteAll");for(const l of f){const p=await c(l,{...e?.chunkSize===void 0?{}:{chunkSize:e.chunkSize},hard:!0});h[l]=p.deleted,u+=p.deleted}return{deleted:u,tables:h}}},hn={db:P,scheduler:z};return o.enforceRls===!0?Jn(P,t,(e,n)=>se(e,n)?.tableName,(e,n)=>fn(e,n),d):P};export{Br as CDC_LOG_TABLE,ti as CLIENT_WATERMARK_TABLE,si as GLOBAL_SHAPE_SNAPSHOT_TABLE,hi as IDEMPOTENCY_TABLE,Go as NotUniqueError,mi as SEARCH_STATE_TABLE,ni as advanceClientWatermark,Wr as applyCdcChanges,Ot as assertNoExplicitUndefined,So as assertValidClientId,Lr as backfillAggregateIndexes,kr as backfillRankIndexes,Fr as backfillSearchIndexes,Pr as bumpCdcEpoch,Ur as cdcCanVouchFor,Gr as cdcForkedError,Hr as cdcSeqLeavingRows,Or as cdcTouchesTables,Nr as cdcTrimmedError,jr as compactCdcDocs,br as createShardCtxDb,Kr as cursorBelowRetainedFloor,ci as deleteGlobalShapeSnapshot,ai as deleteGlobalShapeSnapshotsForConnection,oi as migrateClientWatermark,di as migrateGlobalShapeSnapshot,Qr as minCdcReplayableSeq,Vr as minCdcSeq,Ut as normalizeIdStructurally,zr as readCdcChangeKeys,Jr as readCdcChanges,Yr as readCdcCursor,Xr as readCdcEpoch,ri as readClientWatermark,li as readGlobalShapeSnapshot,wi as readIdempotent,yi as runShardMigrations,_i as selectShapeMembers,Ri as selectShapeRows,jo as stripReservedPatchFields,Zr as trimCdcChanges,pi as trimIdempotent,ui as writeGlobalShapeSnapshot,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-C7o-gpms.mjs";import{serializeSqlValue as d}from"./serializeSqlValue-
|
|
1
|
+
import{sql as s}from"drizzle-orm";import{matchesStaticWhere as f}from"./AGGREGATE_SQL_FUNCTION-DDEoMnJR.mjs";import{compareStrings as l}from"./aggregateTableName-C7o-gpms.mjs";import{serializeSqlValue as d}from"./serializeSqlValue-BEMMYX1n.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};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{stableWireKey as y}from"./stableWireKey-D2US4k_J.mjs";import{depKey as b,SCAN_DEP as p}from"./SCAN_DEP-D7qE3iUe.mjs";import{e as m}from"./estimate-bytes-
|
|
1
|
+
import{stableWireKey as y}from"./stableWireKey-D2US4k_J.mjs";import{depKey as b,SCAN_DEP as p}from"./SCAN_DEP-D7qE3iUe.mjs";import{e as m}from"./estimate-bytes-DM1UZj_m.mjs";import{keysTouchRanges as x}from"./buildIndexRange-DvN8Qj8e.mjs";import{stableStringify as K}from"./stableStringify-DibjylKD.mjs";const l=(o,t,s)=>{let e=o.get(t);return e===void 0&&(e=s(),o.set(t,e)),e},v=1e3,E=4*1024*1024;class A{entries=new Map;tableIndex=new Map;rangeIndex=new Map;totalBytes=0;hits=0;misses=0;evictions=0;maxEntries;maxBytes;now;monotonic=0;generation=0;constructor(t={}){this.maxEntries=t.maxEntries??v,this.maxBytes=t.maxBytes??E,this.now=t.now??(()=>(this.monotonic+=1,this.monotonic))}async run(t,s,e,i=()=>[]){const n=this.entries.get(t);if(n)return this.hits+=1,n.lastUsed=this.now(),this.entries.delete(t),this.entries.set(t,n),n.result;this.misses+=1;const c=this.generation,a=await e();if(this.generation!==c)return a;const h=m(a);if(h===void 0)return a;const f=i(),u={bytes:h,deps:s,ranges:f,lastUsed:this.now(),result:a,subscribers:new Set},d=this.entries.get(t);if(d){this.dropEntry(t,d);for(const r of d.subscribers)u.subscribers.add(r)}this.entries.set(t,u),this.totalBytes+=h;for(const r of s)l(this.tableIndex,r,()=>new Set).add(t);for(const r of f){const g=l(this.rangeIndex,r.table,()=>new Map);l(g,r,()=>new Set).add(t)}return this.evict(),a}invalidate(t,s,e){this.generation+=1;const i=[];return this.collectAndDrop(b(t,s),i),this.collectAndDrop(b(t,p),i),this.dropRangeDeps(t,e,i),i}invalidateTable(t){this.generation+=1;const s=[],e=`${t}:`;for(const i of this.tableIndex.keys())i.startsWith(e)&&this.collectAndDrop(i,s);return this.dropRangeDeps(t,void 0,s),s}subscribe(t,s){const e=this.entries.get(t);e&&e.subscribers.add(s)}unsubscribe(t,s){const e=this.entries.get(t);e&&e.subscribers.delete(s)}size(){return{bytes:this.totalBytes,entries:this.entries.size}}clear(){this.generation+=1,this.entries.clear(),this.tableIndex.clear(),this.rangeIndex.clear(),this.totalBytes=0}subscribers(t){const s=this.entries.get(t);return s?[...s.subscribers]:[]}stats(){return{bytes:this.totalBytes,entries:this.entries.size,evictions:this.evictions,hits:this.hits,misses:this.misses}}dropRangeDeps(t,s,e){const i=this.rangeIndex.get(t);if(!(!i||i.size===0))for(const[n,c]of i)x([n],s)&&this.dropKeys(c,e)}collectAndDrop(t,s){const e=this.tableIndex.get(t);e&&this.dropKeys(e,s)}dropKeys(t,s){for(const e of t){const i=this.entries.get(e);i&&(this.dropEntry(e,i),s.push(e))}}dropEntry(t,s){this.entries.delete(t),this.totalBytes-=s.bytes;for(const e of s.deps){const i=this.tableIndex.get(e);i&&(i.delete(t),i.size===0&&this.tableIndex.delete(e))}for(const e of s.ranges){const i=this.rangeIndex.get(e.table),n=i?.get(e);n?.delete(t),i&&n?.size===0&&(i.delete(e),i.size===0&&this.rangeIndex.delete(e.table))}}evict(){if(!(this.entries.size<=this.maxEntries&&this.totalBytes<=this.maxBytes))for(const[t,s]of this.entries){if(this.entries.size<=this.maxEntries&&this.totalBytes<=this.maxBytes)return;s.subscribers.size>0||(this.dropEntry(t,s),this.evictions+=1)}}}const D=(o,t,s)=>`${s??"\0anon"}\0${o}:${y(t)}`;export{A as ReactiveCache,D as reactiveCacheKey,K as stableStringify,y as stableWireKey};
|
|
@@ -0,0 +1,4 @@
|
|
|
1
|
+
import{sql as s}from"drizzle-orm";import{runDrizzle as d}from"./runDrizzle-2ULFQR_k.mjs";const C=16,T=32,v=1e4,R=1e3,h=t=>String(t).padStart(C,"0"),f=t=>`cdc/${encodeURIComponent(t.shard)}/${encodeURIComponent(t.epoch)}/`,y=(t,n)=>`${f(t)}${h(n)}.json`,E="__cdc_archive",g=t=>{d(t,s`CREATE TABLE IF NOT EXISTS ${s.identifier(E)} (
|
|
2
|
+
id INTEGER PRIMARY KEY CHECK (id = 1),
|
|
3
|
+
seq INTEGER NOT NULL
|
|
4
|
+
)`)},$=t=>(g(t),d(t,s`SELECT seq FROM ${s.identifier(E)} WHERE id = 1`).toArray()[0]?.seq??0),w=(t,n)=>{g(t),d(t,s`INSERT INTO ${s.identifier(E)} (id, seq) VALUES (1, ${n}) ON CONFLICT (id) DO UPDATE SET seq = ${n}`)},L=async(t,n,e)=>{const o=e[0]?.seq,r=e.at(-1)?.seq;o===void 0||r===void 0||await t.put(y(n,r),JSON.stringify({changes:e,from:o,to:r}),{httpMetadata:{contentType:"application/json"}})},j=async(t,n,e)=>{const o=f(n);return(await t.list({limit:1,prefix:o,startAfter:`${o}${h(e)}.json`})).objects.length>0},S=t=>{let n;try{n=JSON.parse(t)}catch{return}if(typeof n!="object"||n===null)return;const e=n;return typeof e.from=="number"&&typeof e.to=="number"&&Array.isArray(e.changes)?e:void 0},_=(t,n)=>{const e=[];for(const o of t.changes)if(!(o.seq<=n)){if(o.op!=="delete"&&o.doc===void 0)break;e.push(o)}return e},I=(t,n,e)=>{let o=e;for(const r of n){if(r.seq!==o+1)break;t.push(r),o=r.seq}return o},b=async(t,n)=>{const e=await t.get(n);return e===null?void 0:S(await e.text())},q=async(t,n,e,o)=>{const r=f(n),p=Math.max(1,Math.min(o??R,v)),A=await t.list({limit:T,prefix:r,startAfter:`${r}${h(e)}.json`}),c=[];let i=e;for(const l of A.objects){const a=await b(t,l.key);if(a===void 0)break;const m=_(a,i);if(i=I(c,m,i),c.length>=p||i!==a.to)break}if(c[0]?.seq!==e+1)return;const u=c.slice(0,p);return{changes:u,cursor:u.at(-1)?.seq??e}};export{L as archiveCdcSegment,j as cdcArchiveRewound,q as readArchivedCdcChanges,$ as readCdcArchivedThrough,w as writeCdcArchivedThrough};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{m as O,c as T,l as b,r as E,a as C,w as L}from"./ctx-db-search-state-ruTuCsxa.mjs";import{S as R,r as M,i as x,l as h,y as _,d as y}from"./ctx-db-companions-
|
|
1
|
+
import{m as O,c as T,l as b,r as E,a as C,w as L}from"./ctx-db-search-state-ruTuCsxa.mjs";import{S as R,r as M,i as x,l as h,y as _,d as y}from"./ctx-db-companions-DsNfXSbb.mjs";import{sql as t}from"drizzle-orm";import{matchesStaticWhere as F}from"./AGGREGATE_SQL_FUNCTION-DDEoMnJR.mjs";import{aggregateTableName as N,encodeAggregateKey as D,foldAggregateTally as v}from"./aggregateTableName-C7o-gpms.mjs";import{runDrizzle as l}from"./runDrizzle-2ULFQR_k.mjs";import{i as w,r as p,a as B,b as G,A as U,D as I,h as H}from"./do-sql-kpl5Kt1j.mjs";import{isLiveForCompanion as P}from"./CURSOR_PREFIX-Bn8SFoGd.mjs";import{rankTableName as W,matchesRankStaticWhere as V}from"./RANK_TIEBREAK-D5xNdzB3.mjs";const k=(e,o)=>l(e,t`SELECT COUNT(*) AS count FROM ${t.identifier(o)}`).one().count>0,Y=(e,o)=>l(e,t`SELECT 1 FROM ${t.identifier(o)} LIMIT 1`).toArray().length>0,A=(e,o)=>l(e,t`SELECT id, _creationTime, ${t.identifier(I)} FROM ${t.identifier(o)}`).toArray(),j=(e,o,n,r)=>{const i=N(o,n.name);if(k(e,i))return;const c=n.by??[],a=new Map,s=A(e,o);for(const d of s){const f=p(d);if(!f||!P(f,r)||n.where&&!F(f,n.where))continue;const g=D(c,f);v(a,g,n,f)}for(const[d,f]of a)l(e,t`INSERT INTO ${t.identifier(i)} (${B}, ${G}, ${U}) VALUES (${d}, ${f.value}, ${f.count})`)},te=(e,o)=>{for(const[n,r]of Object.entries(o.tables))if(!(r.shardMode?.kind==="global"||!r.aggregateIndexes))for(const i of r.aggregateIndexes)j(e,n,i,r.softDeleteMode?.field)},K=(e,o,n)=>{const r=W(o,n.name);if(k(e,r))return;const i=M(n),c=A(e,o);for(const a of c){const s=p(a);!s||n.where&&!V(s,n.where)||x(e,r,n,i,s._id,s)}},ie=(e,o)=>{for(const[n,r]of Object.entries(o.tables))if(!(r.shardMode?.kind==="global"||!r.rankIndexes))for(const i of r.rankIndexes)K(e,n,i)},u=500,$=(e,o,n)=>{const r=R(o,n.name),i=T(n),c=b(E(e,r),i);if(c.finished)return{done:!0,rows:0};const{cursor:a}=c,s=l(e,a===void 0?t`SELECT id, _creationTime, ${t.identifier(I)} FROM ${t.identifier(o)} ORDER BY id ASC LIMIT ${t.raw(String(u))}`:t`SELECT id, _creationTime, ${t.identifier(I)} FROM ${t.identifier(o)} WHERE id > ${a} ORDER BY id ASC LIMIT ${t.raw(String(u))}`).toArray();let d=a;for(const g of s){const{id:m}=g;if(typeof m!="string")continue;d=m,l(e,t`DELETE FROM ${t.identifier(r)} WHERE ${t.identifier(h)} = ${m}`);const S=H(g);S&&l(e,t`INSERT INTO ${t.identifier(r)} (${t.identifier(_)}, ${t.identifier(h)}) VALUES (${y(S,n)}, ${m})`)}const f=s.length<u;return L(e,r,d,f,i),{done:f,rows:s.length}},ae=(e,o,n)=>{const r=R(o,n.name),i=T(n);return b(E(e,r),i).finished?!0:C(e,r)},se=(e,o,n)=>{if(w(e))for(const r of n.searchIndexes??[])r.staged&&Y(e,o)||$(e,o,r)},z=(e,o,n,r)=>{let i=0;for(;;){if(i>=r)return{done:!1,pages:i};const c=$(e,o,n);if(c.rows>0&&(i+=1),c.done)return{done:!0,pages:i}}},ce=(e,o,n={})=>{if(!w(e))return{done:!0,pages:0};O(e);const r=n.maxPages??Number.POSITIVE_INFINITY;let i=0;for(const[c,a]of Object.entries(o.tables))if(!(a.shardMode?.kind==="global"||!a.searchIndexes))for(const s of a.searchIndexes){const d=z(e,c,s,r-i);if(i+=d.pages,!d.done)return{done:!1,pages:i}}return{done:!0,pages:i}};export{te as backfillAggregateIndexes,ie as backfillRankIndexes,ce as backfillSearchIndexes,se as backfillSearchIndexesForTable,ae as searchIndexCoversTable};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{f as m}from"./sql-projection-
|
|
1
|
+
import{f as m}from"./sql-projection-D3qdaItY.mjs";const a="!",l="",d=void 0,w=t=>{const o=new TextEncoder().encode(t);let r="";for(const e of o)r+=e.toString(16).padStart(2,"0");return r},v=t=>t===null?"0":typeof t=="number"?Number.isFinite(t)?`1${m(t)}`:d:typeof t=="string"?`2${w(t)}`:d,x=t=>{const o=[];for(const r of t){const e=v(r);if(e===d)return d;o.push(e)}return o.join(a)},E="=",h=new Set([">",">="]),y=new Set(["<","<="]),g=(t,o,r,e)=>{const i=o.comparator===E,n=h.has(o.comparator)||y.has(o.comparator);return!i&&!n||t.indexOf(o.field)!==r?!1:e===void 0?!0:!i&&e===o.field},S=(t,o,r)=>{const e={equalities:[],lowerExclusive:!1,upperExclusive:!1};let i;for(const n of o){const s=n.comparator===E,c=h.has(n.comparator);if(!g(t,n,e.equalities.length,i))return;if(s){e.equalities.push(r(n.value));continue}if(i=n.field,c){if(e.lower!==void 0)return;e.lower=r(n.value),e.lowerExclusive=n.comparator===">"}else{if(e.upper!==void 0)return;e.upper=r(n.value),e.upperExclusive=n.comparator==="<"}}return e},p=(t,o)=>{const r=v(o);if(r!==void 0)return t===""?r:t+a+r},q=(t,o,r,e,i)=>{if(r.length===0)return;const n=S(r,e,i);if(!n)return;const s=x(n.equalities);if(s===void 0)return;let c=s,f=s+l;if(n.lower!==void 0){const u=p(s,n.lower);if(u===void 0)return;c=n.lowerExclusive?u+a+l:u}if(n.upper!==void 0){const u=p(s,n.upper);if(u===void 0)return;f=n.upperExclusive?u:u+l}if(!(c>=f))return{hi:f,index:o,lo:c,table:t}},R=(t,o,r)=>{const e=[];for(const i of t){const n=x(i.fields.map(s=>r(o[s])));n!==void 0&&e.push({index:i.name,key:n})}return e},b=(t,o)=>t.index===o.index&&o.key>=t.lo&&o.key<t.hi,T=(t,o)=>{if(!t||t.length===0||!o||o.length===0)return!0;const r=new Map;for(const e of o){const i=r.get(e.index);i?i.push(e):r.set(e.index,[e])}return t.some(e=>{const i=r.get(e.index);return!i||i.length===0?!0:i.some(n=>b(e,n))})};export{q as buildIndexRange,R as indexKeysForRow,T as keysTouchRanges,b as rangeContains};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{quoteIdentifier as l}from"./quoteIdentifier-CObIFRhb.mjs";import{reprojectionMigrationTable as u}from"./REPROJECTION_MIGRATION_PREFIX-Czcb6_mO.mjs";import{REPROJECTION_MIGRATION_PREFIX as v,reprojectionMigrationId as w}from"./REPROJECTION_MIGRATION_PREFIX-Czcb6_mO.mjs";import{e as m}from"./wire-codec-C-FpWm52.mjs";import{runSql as p}from"./runDrizzle-2ULFQR_k.mjs";import{k as d,D as E}from"./do-sql-
|
|
1
|
+
import{quoteIdentifier as l}from"./quoteIdentifier-CObIFRhb.mjs";import{reprojectionMigrationTable as u}from"./REPROJECTION_MIGRATION_PREFIX-Czcb6_mO.mjs";import{REPROJECTION_MIGRATION_PREFIX as v,reprojectionMigrationId as w}from"./REPROJECTION_MIGRATION_PREFIX-Czcb6_mO.mjs";import{e as m}from"./wire-codec-C-FpWm52.mjs";import{runSql as p}from"./runDrizzle-2ULFQR_k.mjs";import{k as d,D as E}from"./do-sql-kpl5Kt1j.mjs";import{m as g}from"./sql-projection-D3qdaItY.mjs";const b=m(0n)[0],_=e=>e.shardMode?.kind==="global"?[]:Object.entries(e.shape).filter(([,r])=>g(r)).map(([r])=>r),M=e=>Object.entries(e.tables).filter(([,r])=>_(r).length>0).map(([r])=>r),f=e=>{const r=`json_each(${l(E)}) AS __f__`;return{params:[JSON.stringify(e),b,"bigint","bytes"],sql:`EXISTS (SELECT 1 FROM ${r} WHERE __f__.type = 'array' AND __f__.key IN (SELECT value FROM json_each(?)) AND json_extract(__f__.value, '$[0]') = ? AND json_extract(__f__.value, '$[1]') IN (?, ?))`}},N=(e,r,o)=>{if(o.length===0)return 0;const{params:t,sql:n}=f(o);return p(e,`SELECT COUNT(*) AS count FROM ${l(r)} WHERE ${n}`,...t).toArray()[0]?.count??0},R=(e,r,o,t)=>{const{params:n,sql:i}=f(o);return p(e,`SELECT 1 FROM ${l(r)} WHERE id = ? AND (${i}) LIMIT 1`,t,...n).toArray().length>0},S=(e,r,o)=>{const t=u(e);if(t===void 0)return;const n=r.tables[t];if(!n)return;const i=_(n);if(i.length!==0)return{id:e,table:t,up:s=>{const a=s._id;if(!(typeof a!="string"||!R(o,t,i,a))){try{d(s)}catch(c){console.warn(`${e}: skipping row ${a} — it cannot be re-projected: ${c instanceof Error?c.message:String(c)}`);return}return s}}}};export{v as REPROJECTION_MIGRATION_PREFIX,S as buildReprojectionMigration,N as countLegacyRows,_ as reprojectableFields,w as reprojectionMigrationId,M as reprojectionTables};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{readCdcChangeKeys as s}from"./CDC_LOG_TABLE-
|
|
1
|
+
import{readCdcChangeKeys as s}from"./CDC_LOG_TABLE-CfILante.mjs";import{selectShapeMembers as h}from"./selectShapeMembers-B8gTOeOB.mjs";import{shapeRangeKey as u}from"./ShapeDiffCache-gdaILV5E.mjs";import{projectColumns as g}from"./buildPokeFrames-BBE6J91z.mjs";const C=(m,e,a,i,p,f=s)=>{const r=u(e.table,a,i),n=p.changedKeys(r,()=>f(m,e.table,a,i));if(n.length===0)return[];const b=p.members(e,r,()=>h(m,e.table,e.effectiveWhere,n.map(t=>t.id))),o=[];for(const t of n){const c=b.get(t.id);if(c===void 0){t.op!=="insert"&&o.push({key:t.id,op:"delete",table:e.table});continue}o.push({key:t.id,op:t.op,table:e.table,value:g(c,e.columns)})}return o};export{C as buildShapeDiff};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{LunoraError as g}from"@lunora/errors";import{sql as o}from"drizzle-orm";import{mergeWhere as b}from"./CountRlsUnsupportedError-BvsDqfO2.mjs";import{SCAN_DEP as j}from"./SCAN_DEP-D7qE3iUe.mjs";import{runDrizzle as A}from"./runDrizzle-2ULFQR_k.mjs";import{sqliteInList as O}from"./param-DlozcSQu.mjs";import{decodeCursor as F,CURSOR_PREFIX as P,toBase64 as U}from"./CURSOR_PREFIX-Bn8SFoGd.mjs";import{rankTableName as V,sortColumnName as z,resolveRankPartition as H,RANK_TIEBREAK as _,encodePartitionKey as J,rankPivotConditionSql as X}from"./RANK_TIEBREAK-
|
|
1
|
+
import{LunoraError as g}from"@lunora/errors";import{sql as o}from"drizzle-orm";import{mergeWhere as b}from"./CountRlsUnsupportedError-BvsDqfO2.mjs";import{SCAN_DEP as j}from"./SCAN_DEP-D7qE3iUe.mjs";import{runDrizzle as A}from"./runDrizzle-2ULFQR_k.mjs";import{sqliteInList as O}from"./param-DlozcSQu.mjs";import{decodeCursor as F,CURSOR_PREFIX as P,toBase64 as U}from"./CURSOR_PREFIX-Bn8SFoGd.mjs";import{rankTableName as V,sortColumnName as z,resolveRankPartition as H,RANK_TIEBREAK as _,encodePartitionKey as J,rankPivotConditionSql as X}from"./RANK_TIEBREAK-D5xNdzB3.mjs";const Y="__doc__",G=n=>P+U(JSON.stringify(n)),Q=n=>n.after?[n.after.partitionKey,...n.after.sortValues,n.after.rowId]:n.cursor?F(n.cursor):void 0,Z=(n,r,f)=>{if(n?.length!==1+r.length+1)return;const t=[{column:"__partition__",direction:"asc"}];for(const[c,u]of r.entries())t.push({column:u,direction:f[c]?.direction??"asc"});t.push({column:_,direction:"asc"});const e=[];for(const[c,u]of t.entries()){const d=X(u.column,n[c],u.direction,!0);if(d===void 0)continue;const s=[];for(const[m,l]of t.slice(0,c).entries())s.push(o`${o.identifier(l.column)} IS ${n[m]}`);s.push(d);const[i]=s;e.push(s.length===1&&i!==void 0?i:o`(${o.join(s,o` AND `)})`)}return e.length===0?o`(1 = 0)`:o`(${o.join(e,o` OR `)})`},v=null,oo=(n,r)=>{if(n===void 0)return v;const f=[n.__partition__,...r.map(t=>n[t]),n[_]];return G(f)},no=(n,r,f)=>{const t=[];for(const e of n){const c=e[_];if(typeof c!="string")continue;const u=r.get(c);if(!u)continue;const d=typeof e.__partition__=="string"?e.__partition__:"",s=f.map(i=>e[i]??null);t.push({doc:u,key:{partitionKey:d,rowId:c,sortValues:s}})}return t},to=o`${o.identifier("id")}`,ro=(n,r,f)=>{const{rowToDocument:t}=n,e=new Map;if(f.length===0)return e;const c=A(n.sql,o`SELECT id, _creationTime, ${o.identifier(Y)} FROM ${o.identifier(r)} WHERE ${O(to,f,!1)}`).toArray();for(const u of c){const d=t(u),s=u.id;d&&typeof s=="string"&&e.set(s,d)}return e},_o=(n,r,f,t)=>{const{assertRankPartitionLocal:e,ensureRankBackfilled:c,onRead:u,schema:d}=n,s=d.tables[r];if(!s)throw new g("INTERNAL",`unknown table: ${r}`);const i=s.rankIndexes?.find(a=>a.name===f);if(!i)throw new g("INTERNAL",`unknown rankIndex "${f}" on table "${r}"`);e(r,s,i),u(r,j),c(r,i);const m=V(r,i.name),l=i.sortBy.map((a,w)=>z(w)),h=Math.max(1,Math.min(1e3,Math.floor(t.take??100))),T=b(t.baseWhere,t.where),k=H(i,T),R=[o`${o.identifier("__partition__")} ASC`];for(const[a,w]of l.entries()){const W=i.sortBy[a]?.direction;R.push(o`${o.identifier(w)} ${o.raw(W==="desc"?"DESC":"ASC")}`)}R.push(o`${o.identifier(_)} ASC`);const p=[];typeof t.partitionKey=="string"?p.push(o`${o.identifier("__partition__")} = ${t.partitionKey}`):k&&p.push(o`${o.identifier("__partition__")} = ${J(i.partitionBy??[],k)}`);const B=Q(t),E=Z(B,l,i.sortBy);E&&p.push(E);const I=o.identifier(_),S=o.identifier("__partition__"),D=p.length>0?o` WHERE ${o.join(p,o` AND `)}`:o``,L=l.length>0?o`${I}, ${S}, ${o.join(l.map(a=>o.identifier(a)),o`, `)}`:o`${I}, ${S}`,M=o`SELECT ${L} FROM ${o.identifier(m)}${D} ORDER BY ${o.join(R,o`, `)} LIMIT ${o.raw(String(h+1))}`,$=A(n.sql,M).toArray(),C=$.length>h,y=C?$.slice(0,h):$,K=y.map(a=>a[_]),q=no(y,ro(n,r,K),l),x=C?oo(y.at(-1),l):v,N=i.sortBy.map(a=>a.direction==="desc"?"desc":"asc");return{continueCursor:x,directions:N,hasMore:C,rows:q}};export{_o as computeRankPage,Q as resolveRankSeekTuple};
|
package/dist/packem_shared/{createCompanionSync-C6fV10Dq.mjs → createCompanionSync-Cb567rkq.mjs}
RENAMED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{c as l,i as C,r as R}from"./ctx-db-companions-
|
|
1
|
+
import{c as l,i as C,r as R}from"./ctx-db-companions-DsNfXSbb.mjs";import"./AGGREGATE_SQL_FUNCTION-DDEoMnJR.mjs";import"./aggregateTableName-C7o-gpms.mjs";import"./runDrizzle-2ULFQR_k.mjs";import"./do-sql-kpl5Kt1j.mjs";import"./param-DlozcSQu.mjs";import"./GEO_DEFAULT_PRECISION-CqpQZ-J_.mjs";import"./CURSOR_PREFIX-Bn8SFoGd.mjs";import"./RANK_TIEBREAK-D5xNdzB3.mjs";import"./sql-projection-D3qdaItY.mjs";import"./serializeSqlValue-BEMMYX1n.mjs";export{l as createCompanionSync,C as insertRankRow,R as rankColumnsSql};
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
import{d as p,e as S}from"./wire-codec-C-FpWm52.mjs";import{cursorBelowRetainedFloor as y}from"./CDC_LOG_TABLE-CfILante.mjs";import{envPositiveInt as v}from"./envOptionalPositiveInt-D2pY-c64.mjs";import{v as A,R as g,s as N,a as E,b as T}from"./sibling-channel-BkL5cTCc.mjs";const L=["wnam","enam","sam","weur","eeur","apac","apac-ne","apac-se","oc","afr","me"],O=new Set(L),b=s=>typeof s=="string"&&O.has(s),h="::replica::",R=s=>{const e=s.lastIndexOf(h);if(e===-1)return;const t=s.slice(0,e),r=s.slice(e+h.length);if(!(t.length===0||!b(r)))return{ownerKey:t,region:r}},I=s=>{if(s==null||!/^\d+$/.test(s))return;const e=Number.parseInt(s,10);return Number.isSafeInteger(e)&&e>0?e:void 0},m=1e3,w=1e3,C=10,U=5e4,F=s=>v(s,"LUNORA_REPLICA_MAX_BOOTSTRAP_ROWS",U),d="__replica_state",l=new WeakSet,_=s=>{l.has(s)||(s.exec(`CREATE TABLE IF NOT EXISTS ${d} (
|
|
2
|
+
id INTEGER PRIMARY KEY CHECK (id = 1),
|
|
3
|
+
epoch TEXT NOT NULL,
|
|
4
|
+
applied_seq INTEGER NOT NULL,
|
|
5
|
+
synced_at REAL NOT NULL
|
|
6
|
+
)`),l.add(s))},c=s=>(_(s),s.exec(`SELECT epoch, applied_seq AS appliedSeq, synced_at AS syncedAtMs FROM ${d} WHERE id = 1`).toArray()[0]),f=(s,e)=>{_(s),s.exec(`INSERT INTO ${d} (id, epoch, applied_seq, synced_at) VALUES (1, ?, ?, ?)
|
|
7
|
+
ON CONFLICT(id) DO UPDATE SET epoch = excluded.epoch, applied_seq = excluded.applied_seq, synced_at = excluded.synced_at`,e.epoch,e.appliedSeq,e.syncedAtMs)},q=s=>{const e=s.doName();if(e!==void 0&&R(e)!==void 0)return new Response("replica cannot serve replicas",{status:409});if(s.ownerEpoch()===void 0)return new Response("shard has no changelog to replicate",{status:409});if(E(s.env())===void 0)return new Response("replica control requires LUNORA_RELAY_SECRET",{status:403})},a=s=>Response.json(S(s)),P=async(s,e)=>{if(s.rowCount()>F(s.env()))return a({cursor:0,epoch:e,rows:[],truncated:!0});const t=s.ownerCursor()??0,r=await s.exportRows();return a({cursor:t,epoch:e,rows:r})},x=(s,e,t)=>{const r=s.ownerFloor();if(y(r,t))return a({changes:[],cursor:s.ownerCursor()??t,epoch:e,floor:r});const o=s.ownerCursor()??0;if(t>o)return a({changes:[],cursor:o,epoch:e,...r===void 0?{}:{floor:r}});const{changes:n,cursor:i}=s.readChanges(t,w);return a({changes:n,cursor:i,epoch:e,...r===void 0?{}:{floor:r}})},K=async(s,e)=>{const t=q(s);if(t!==void 0)return t;const r=s.ownerEpoch();let o;try{o=await e.text()}catch{return new Response("bad request",{status:400})}if(!await A(s.env(),e.headers.get(g),o))return new Response("forbidden",{status:403});let n;try{n=JSON.parse(o)}catch{return new Response("bad request",{status:400})}if(n.type==="replica_bootstrap")return P(s,r);if(n.type==="replica_pull"){const i=typeof n.sinceSeq=="number"&&Number.isInteger(n.sinceSeq)&&n.sinceSeq>=0?n.sinceSeq:0;return x(s,r,i)}return new Response("unknown replica frame",{status:400})};class M{constructor(e,t,r){this.host=e,this.ownerKey=t,this.region=r}host;ownerKey;region;divergent=!1;inFlight;async ensureFresh(e){if(this.divergent)return"unavailable";if(this.isCaughtUp(e))return"fresh";this.inFlight??=this.advance(e).finally(()=>{this.inFlight=void 0});const t=await this.inFlight;return t==="fresh"&&!this.isCaughtUp(e)?"stale":t}appliedSeq(){return c(this.host.sql())?.appliedSeq??0}isDivergent(){return this.divergent}async advance(e){let t=c(this.host.sql());if(t===void 0){const r=await this.bootstrap();if(r===void 0)return"unavailable";t=r}return this.catchUp(t,e)}isCaughtUp(e){const t=c(this.host.sql());return t!==void 0&&this.isFreshEnough(t,e)}async catchUp(e,t){let r=e;for(let o=0;o<C;o+=1){const n=await this.pull(r.appliedSeq);if(n===void 0)return t===void 0&&this.isFreshEnough(r,void 0)?"fresh":"unavailable";if(this.hasDiverged(r,n))return"unavailable";const i=n.changes.length<w;if(r=await this.applyPage(n),i||this.isFreshEnough(r,t))return this.isFreshEnough(r,t)?"fresh":"stale"}return this.isFreshEnough(r,t)?"fresh":"stale"}async applyPage(e){e.changes.length>0&&await this.host.applyChanges(e.changes);const t={appliedSeq:e.cursor,epoch:e.epoch,syncedAtMs:Date.now()};return f(this.host.sql(),t),t}hasDiverged(e,t){const r=t.changes.length===0&&t.cursor>e.appliedSeq,o=t.floor??(r?t.cursor:0),n=o>0&&o>e.appliedSeq+1,i=t.cursor<e.appliedSeq;return t.epoch===e.epoch&&!n&&!i?!1:(this.divergent=!0,!0)}async bootstrap(){const e=await this.request({type:"replica_bootstrap"});if(e===void 0)return;const t=p(await e.json());if(t.truncated===!0){this.divergent=!0;return}const{errors:r}=await this.host.importRows(t.rows);if(r.length>0){this.divergent=!0;return}const o={appliedSeq:t.cursor,epoch:t.epoch,syncedAtMs:Date.now()};return f(this.host.sql(),o),o}isFreshEnough(e,t){return t!==void 0?e.appliedSeq>=t:Date.now()-e.syncedAtMs<=v(this.host.env(),"LUNORA_REPLICA_MAX_STALENESS_MS",m)}async pull(e){const t=await this.request({sinceSeq:e,type:"replica_pull"});return t===void 0?void 0:p(await t.json())}async request(e){const t=this.host.shardBinding(),r=N(this.host.env(),t,this.ownerKey,this.host.shardJurisdiction());if(r===void 0)return;const o=JSON.stringify(e),n={"content-type":"application/json","x-lunora-shard-binding":t??""},i=E(this.host.env());i!==void 0&&(n[g]=await T(i,o));try{const u=await r.fetch("https://replica.internal/_lunora/replica",{body:o,headers:n,method:"POST"});return u.ok?u:void 0}catch{return}}}const j=s=>{const e=s.doName();if(e===void 0)return;const t=R(e);return t===void 0?void 0:new M(s,t.ownerKey,t.region)},G=async(s,e,t)=>{if(e.headers.get("x-lunora-replica-read")!=="1")return Response.json({error:{code:"REPLICA_READ_ONLY",message:`"${t}" is a write and cannot run on a read replica`}},{status:421});const r=await s.ensureFresh(I(e.headers.get("x-lunora-min-seq")));if(r!=="fresh")return Response.json({error:{code:"REPLICA_NOT_READY",message:`replica is ${r} for this read`}},{headers:{"x-lunora-replica-fallback":r},status:421})};export{j as createReplicaLink,G as gateReplicaDispatch,K as handleReplicaControl};
|
package/dist/packem_shared/{ctx-db-companions-w-CfeOda.mjs → ctx-db-companions-DsNfXSbb.mjs}
RENAMED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{D as ie}from"./MAX_TOKEN_LENGTH-BakL9FUy-B3VwYY8C.mjs";import{sql as e}from"drizzle-orm";import{matchesStaticWhere as P,aggregateSqlFunction as ce}from"./AGGREGATE_SQL_FUNCTION-DDEoMnJR.mjs";import{aggregateTableName as z,encodeAggregateKey as v,foldAggregateTally as J,coerceAggregateNumber as b}from"./aggregateTableName-C7o-gpms.mjs";import{runDrizzle as u}from"./runDrizzle-2ULFQR_k.mjs";import{i as fe,g as ae,D as M,r as q,a as L,b as h,A as p,c as D,e as U}from"./do-sql-
|
|
1
|
+
import{D as ie}from"./MAX_TOKEN_LENGTH-BakL9FUy-B3VwYY8C.mjs";import{sql as e}from"drizzle-orm";import{matchesStaticWhere as P,aggregateSqlFunction as ce}from"./AGGREGATE_SQL_FUNCTION-DDEoMnJR.mjs";import{aggregateTableName as z,encodeAggregateKey as v,foldAggregateTally as J,coerceAggregateNumber as b}from"./aggregateTableName-C7o-gpms.mjs";import{runDrizzle as u}from"./runDrizzle-2ULFQR_k.mjs";import{i as fe,g as ae,D as M,r as q,a as L,b as h,A as p,c as D,e as U}from"./do-sql-kpl5Kt1j.mjs";import{param as le,WORKERD_SQLITE_LIMITS as $e}from"./param-DlozcSQu.mjs";import{encodeGeohash as de,GEO_DEFAULT_PRECISION as ue}from"./GEO_DEFAULT_PRECISION-CqpQZ-J_.mjs";import{isLiveForCompanion as N}from"./CURSOR_PREFIX-Bn8SFoGd.mjs";import{encodePartitionKey as Ee,sortColumnName as _e,rankTableName as X,matchesRankStaticWhere as Y}from"./RANK_TIEBREAK-D5xNdzB3.mjs";import{m as ye}from"./sql-projection-D3qdaItY.mjs";import{serializeSqlValue as Z}from"./serializeSqlValue-BEMMYX1n.mjs";const ge=(t,i)=>{if(!i.includes("."))return t[i];let f=t;for(const A of i.split(".")){if(f===null||typeof f!="object"||Array.isArray(f))return;f=f[A]}return f},pe=(t,i)=>`${t}__fts_${i}`,me="__text__",Q="__id__",he=1e3,Se=(t,i)=>i.document(t),W=(t,i)=>ge(t,i),Te=t=>typeof t=="string"?t:t==null?"":typeof t=="number"||typeof t=="bigint"||typeof t=="boolean"?String(t):JSON.stringify(t)??"",Re=(t,i,f)=>t!==void 0&&i!==void 0&&W(t,f.field)===W(i,f.field),Ae=(t,i)=>Se(Te(W(t,i.field)),ie(i.language)).slice(0,he),we=(t,i)=>Ae(t,i).join(" "),Fe=(t,i,f)=>[...t.partitionBy??[],...t.sortBy.map(S=>S.field),...t.where?Object.keys(t.where):[]].every(S=>i[S]===f[S]),x=t=>e.join(["__id__","__partition__",...t.sortBy.map((i,f)=>_e(f))].map(i=>e.identifier(i)),e`, `),ee=(t,i,f,A,S,y)=>{const c=Ee(f.partitionBy??[],y),C=f.sortBy.map(I=>Z(y[I.field]??null)),k=e.join([S,c,...C].map(I=>le(I)),e`, `);u(t,e`INSERT INTO ${e.identifier(i)} (${A}) VALUES (${k})`)},Oe=(t,i,f,A,S,y)=>{if(S&&y&&Fe(f,S,y))return;const c=X(i,f.name);S&&u(t,e`DELETE FROM ${e.identifier(c)} WHERE ${e.identifier("__id__")} = ${A}`),!(!y||f.where&&!Y(y,f.where))&&ee(t,c,f,x(f),A,y)},Be=t=>{const{broadcast:i,indexKeysFor:f,invalidateCache:A,recordCdc:S,schema:y,sql:c}=t,C=new Set,k=n=>y.tables[n]?.softDeleteMode?.field,I=new Set,j=(n,o)=>{const s=`${n}::${o.name}`;if(C.has(s))return;const l=z(n,o.name),$=o.by??[],d=k(n),_=new Map,m=u(c,e`SELECT id, _creationTime, ${e.identifier(M)} FROM ${e.identifier(n)}`).toArray();for(const T of m){const E=q(T);if(!E||!N(E,d)||o.where&&!P(E,o.where))continue;const R=v($,E);J(_,R,o,E)}u(c,e`DELETE FROM ${e.identifier(l)}`);const w=Math.floor($e.boundParams/3),F=[..._];for(let T=0;T<F.length;T+=w){const E=F.slice(T,T+w),R=e.join(E.map(([r,a])=>e`(${r}, ${a.value}, ${a.count})`),e`, `);u(c,e`INSERT INTO ${e.identifier(l)} (${L}, ${h}, ${p}) VALUES ${R}`)}C.add(s)},oe=(n,o,s)=>{const l=o.by??[],$=o.field??"",d=[],_=(r,a)=>{const g=Z(a);g===null?d.push(e`${U(r)} IS NULL`):d.push(e`${U(r)} = ${g}`)};for(const r of l)_(r,s[r]??null);const m=k(n);m!==void 0&&_(m,null);for(const[r,a]of Object.entries(o.where??{}))_(r,a!==null&&typeof a=="object"&&!Array.isArray(a)?a.eq:a);const w=d.length>0?e` WHERE ${e.join(d,e` AND `)}`:e``,F=y.tables[n]?.shape[$];if(F&&ye(F)){const r=u(c,e`SELECT id, _creationTime, ${e.identifier(M)} FROM ${e.identifier(n)}${w}`).toArray(),a=new Map;for(const g of r){const O=q(g);O&&J(a,"",o,O)}return{value:a.get("")?.value??null}}const T=ce(o.op),E=U($);return{value:u(c,e`SELECT ${e.raw(T)}(${E}) AS value FROM ${e.identifier(n)}${w}`).one().value??null}},ne=(n,o,s,l)=>{const $=z(n,o.name),{op:d}=o,_=o.field??"",m=r=>{u(c,e`DELETE FROM ${e.identifier($)} WHERE ${L} = ${r} AND ${p} <= 0`)},w=k(n),F=r=>!o.where||P(r,o.where),T=r=>N(r,w)&&F(r);l!==void 0&&d!=="count"&&F(l)&&b(l[_]);const E=s&&T(s)?s:void 0,R=l&&T(l)?l:void 0;if(!(!E&&!R)){if(d==="count"){for(const[r,a]of[[E,-1],[R,1]]){if(!r)continue;const g=v(o.by??[],r);u(c,D($,g,a,a,e`${h} = ${h} + excluded.${h}, ${p} = ${p} + excluded.${p}`))}E&&m(v(o.by??[],E));return}if(d==="sum"||d==="avg"){for(const[r,a]of[[E,-1],[R,1]]){if(!r)continue;const g=b(r[_]);if(g===void 0)continue;const O=v(o.by??[],r);u(c,D($,O,a*g,a,e`${h} = COALESCE(${h}, 0) + excluded.${h}, ${p} = ${p} + excluded.${p}`))}E&&m(v(o.by??[],E));return}if(E){const r=v(o.by??[],E),a=b(E[_]),g=u(c,e`SELECT ${h} AS value, ${p} AS count FROM ${e.identifier($)} WHERE ${L} = ${r}`).toArray()[0],O=(g?.count??0)-1;if(O<=0)u(c,e`DELETE FROM ${e.identifier($)} WHERE ${L} = ${r}`);else if(g&&a!==void 0&&g.value!==null&&a===g.value){const se=oe(n,o,E);u(c,e`UPDATE ${e.identifier($)} SET ${h} = ${se.value}, ${p} = ${O} WHERE ${L} = ${r}`)}else u(c,e`UPDATE ${e.identifier($)} SET ${p} = ${p} - 1 WHERE ${L} = ${r}`)}if(R){const r=v(o.by??[],R),a=b(R[_]);if(a===void 0)u(c,D($,r,null,1,e`${p} = ${p} + 1`));else{const g=d==="min"?"MIN":"MAX";u(c,D($,r,a,1,e`${h} = ${e.raw(g)}(COALESCE(${h}, excluded.${h}), excluded.${h}), ${p} = ${p} + 1`))}}}},te=n=>{for(const o of y.tables[n]?.aggregateIndexes??[])j(n,o)},H=(n,o,s)=>{for(const l of y.tables[n]?.aggregateIndexes??[])ne(n,l,o,s)},B=(n,o)=>{const s=`${n}::rank::${o.name}`;if(I.has(s))return;const l=X(n,o.name),$=u(c,e`SELECT id, _creationTime, ${e.identifier(M)} FROM ${e.identifier(n)}`).toArray();u(c,e`DELETE FROM ${e.identifier(l)}`);const d=x(o);for(const _ of $){const m=q(_);!m||o.where&&!Y(m,o.where)||ee(c,l,o,d,m._id,m)}I.add(s)},re=n=>{for(const o of y.tables[n]?.rankIndexes??[])B(n,o)},K=(n,o,s,l)=>{for(const $ of y.tables[n]?.rankIndexes??[])Oe(c,n,$,o,s,l)},V=(n,o,s,l)=>{const $=y.tables[n]?.searchIndexes??[];if(!($.length===0||!fe(c)))for(const d of $){if(Re(l,s,d))continue;const _=pe(n,d.name);u(c,e`DELETE FROM ${e.identifier(_)} WHERE ${e.identifier(Q)} = ${o}`),s&&u(c,e`INSERT INTO ${e.identifier(_)} (${e.identifier(me)}, ${e.identifier(Q)}) VALUES (${we(s,d)}, ${o})`)}},G=(n,o,s)=>{for(const l of y.tables[n]?.geoIndexes??[]){const $=ae(n,l.name);u(c,e`DELETE FROM ${e.identifier($)} WHERE ${e.identifier("__id__")} = ${o}`);const d=s?.[l.field];if(d!==null&&typeof d=="object"&&typeof d.lat=="number"&&typeof d.lng=="number"){const{lat:_,lng:m}=d,w=de({lat:_,lng:m},l.precision??ue);u(c,e`INSERT INTO ${e.identifier($)} (${e.identifier("__id__")}, ${e.identifier("__geohash__")}, ${e.identifier("__lat__")}, ${e.identifier("__lng__")}) VALUES (${o}, ${w}, ${_}, ${m})`)}}};return{ensureBackfilledForTable:te,ensureBackfilledIndex:j,ensureRankBackfilled:B,ensureRankBackfilledForTable:re,syncAggregates:H,syncCompanionsForInsert:(n,o,s)=>{V(n,o,s),G(n,o,s),H(n,void 0,s),K(n,o,void 0,s),A(n,o,s),S(n,o,"insert",s),i({indexKeys:f(n,s),key:o,op:"insert",row:s,table:n})},syncGeo:G,syncRanks:K,syncSearch:V}};export{pe as S,Ae as a,Be as c,we as d,ee as i,Q as l,x as r,me as y};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{createShardCtxDb as v}from"./NotUniqueError-
|
|
1
|
+
import{createShardCtxDb as v}from"./NotUniqueError-DpTK0ULs.mjs";import{createRelayLink as I}from"./DEFAULT_MAX_RELAYS-Ng4SyJ7k.mjs";import{ConflictError as N}from"./ConflictError-C8GtJmjS.mjs";import{runShardMigrations as _}from"./runShardMigrations-BLl8xFGK.mjs";import{relayName as F}from"./DEFAULT_PROMOTION_THRESHOLDS-Bfx7KakS.mjs";const E=(C,m={})=>({_meta:{column:{notNull:!0,...m}},kind:C}),W=(C,m,O)=>{const{describe:S,expect:n,it:y}=O;S(`engine contract: ${C}`,()=>{S("optimistic concurrency",()=>{const b=u=>({tables:{items:{indexes:[],shape:{title:E("string"),version:E("number",{notNull:!1})},triggerMap:{clobber:{handler:()=>{u.exec(`UPDATE "items" SET "__doc__" = json_set("__doc__", '$.version', 99) WHERE "id" = 'i1'`)},op:"update",timing:"before"}}}}});y("raises a CONFLICT of kind `occ` when a write's snapshot is clobbered",async()=>{const{close:u,host:h}=m();try{const i=h.sql,l=b(i);_(i,l);const s=v({schema:l,sql:i});await s.insert("items",{_id:"i1",title:"first",version:1},{allowExplicitId:!0}),await n(s.patch("i1",{title:"second"})).rejects.toBeInstanceOf(N)}finally{u?.()}}),y("reports the conflict as CONFLICT/409 rather than retrying it away",async()=>{const{close:u,host:h}=m();try{const i=h.sql,l=b(i);_(i,l);const s=v({schema:l,sql:i});await s.insert("items",{_id:"i1",title:"first",version:1},{allowExplicitId:!0});let o;try{await s.patch("i1",{title:"second"})}catch(t){o=t}const e=o;n(e.code).toBe("CONFLICT"),n(e.kind).toBe("occ")}finally{u?.()}}),y("leaves the row readable and unchanged after a conflict",async()=>{const{close:u,host:h}=m();try{const i=h.sql,l=b(i);_(i,l);const s=v({schema:l,sql:i});await s.insert("items",{_id:"i1",title:"first",version:1},{allowExplicitId:!0});try{await s.patch("i1",{title:"second"})}catch{}const o=await s.get("i1");n(o?.title).toBe("first"),n(o?.version).toBe(99)}finally{u?.()}}),y("raises a CONFLICT of kind `trigger` when a trigger writes its own row through the db",async()=>{const{close:u,host:h}=m();try{const i=h.sql,l={tables:{items:{indexes:[],shape:{title:E("string"),version:E("number",{notNull:!1})},triggerMap:{recurse:{handler:async(t,a)=>{await t.db.patch(a.doc._id,{version:99})},op:"update",timing:"before"}}}}};_(i,l);const s=v({schema:l,sql:i});await s.insert("items",{_id:"i1",title:"first",version:1},{allowExplicitId:!0});let o;try{await s.patch("i1",{title:"second"})}catch(t){o=t}const e=o;n(e).toBeInstanceOf(N),n(e.code).toBe("CONFLICT"),n(e.kind).toBe("trigger")}finally{u?.()}})}),S("shape-poke ordering",()=>{const b="shard-a",u={args:{},name:"messages"},h=(e,t,a,r)=>e.accept(t?.()??{},{connectionId:a,shapes:{[r]:u}}),i=(e,t,a)=>{let r=0,d=0;const c=g=>()=>{throw new Error(`the relay poke path must not reach RelayHost.${g}`)},p={fetch:(g,q)=>{if(JSON.parse(q?.body??"{}").type!=="relay_shape_subscribe")return Promise.resolve(new Response(void 0,{status:204}));const B=a[d];if(d+=1,B===void 0)throw new Error("the relay asked for more seeds than this fixture supplies");return Promise.resolve(Response.json(B))}},k={get:()=>p,getByName:()=>p,idFromName:g=>g},w={buildShapeDiff:c("buildShapeDiff"),computeOpLogShapeSeed:c("computeOpLogShapeSeed"),currentCdcEpoch:c("currentCdcEpoch"),deliverWhisperLocal:c("deliverWhisperLocal"),doName:()=>F(b,0),env:()=>({SHARD:k}),getWebSockets:()=>e.getSockets(),maskMetadata:c("maskMetadata"),nextPokeId:()=>(r+=1,`poke-${String(r)}`),readAttachment:g=>g.deserializeAttachment?.(),recordShapePokeFanout:()=>{},resolveShape:c("resolveShape"),rlsMetadata:c("rlsMetadata"),shardBinding:()=>"SHARD",shardJurisdiction:()=>{},sql:()=>t},f=I(w);if(f===void 0)throw new Error("expected a relay link for a `…::relay::N` name");return f},l=e=>new Request("https://relay.internal/_lunora/relay",{body:JSON.stringify(e),headers:{"content-type":"application/json"},method:"POST"}),s=async(e,t,a)=>{const r=await e.seedRelayShape(t,a,u,{identity:void 0,userId:void 0});if(r!=="ok")throw new Error(`seed failed: ${JSON.stringify(r)}`)},o=(e={})=>l({...u,checkpoint:20,epoch:"e1",fromCursor:10,rowsPatch:[{id:"r1",op:"upsert",value:{title:"hello"}}],type:"relay_shape_poke",...e});y("frames a poke as pokeStart → pokePart per shape → pokeEnd, under one poke id",async()=>{const{close:e,createSocket:t,host:a,readFrames:r,sockets:d}=m();try{const c=i(d,a.sql,[{cursor:10,epoch:"e1",frames:[]}]),p=h(d,t,"c-alice","s1");await s(c,p,"s1"),await c.handleControl(o());const w=(await r(p)).map(f=>JSON.parse(f));n(w.map(f=>f.type)).toStrictEqual(["pokeStart","pokePart","pokeEnd"]),n(new Set(w.map(f=>f.pokeId)).size).toBe(1),n(w[1]?.shapeId).toBe("s1"),n(w[2]?.checkpoint).toBe(20)}finally{e?.()}}),y("delivers a poke only to sockets whose cursor matches, and advances them past it",async()=>{const{close:e,createSocket:t,host:a,readFrames:r,sockets:d}=m();try{const c=i(d,a.sql,[{cursor:10,epoch:"e1",frames:[]},{cursor:7,epoch:"e1",frames:[]}]),p=h(d,t,"c-alice","s1"),k=h(d,t,"c-bob","s2");await s(c,p,"s1"),await s(c,k,"s2"),await c.handleControl(o());const w=await r(p);n(w.length).toBe(3);const f=await r(k);n(f.length).toBe(0),await c.handleControl(o());const g=await r(p);n(g.length).toBe(3)}finally{e?.()}}),y("skips a socket whose cursor matches under a different CDC epoch",async()=>{const{close:e,createSocket:t,host:a,readFrames:r,sockets:d}=m();try{const c=i(d,a.sql,[{cursor:10,epoch:"e1",frames:[]}]),p=h(d,t,"c-alice","s1");await s(c,p,"s1"),await c.handleControl(o({epoch:"e2"}));const k=await r(p);n(k.length).toBe(0),await c.handleControl(o());const w=await r(p);n(w.length).toBe(3)}finally{e?.()}})}),S("RLS identity under live subscription",()=>{const b="shard-a",u={args:{},name:"lobby-messages"},h={args:{},name:"my-orders"},i=s=>{const o=[],e=[],t={fetch:(d,c)=>(o.push(JSON.parse(c?.body??"{}")),Promise.resolve(new Response(void 0,{status:204})))},r=I({buildShapeDiff:()=>[{id:"r1",op:"upsert",value:{}}],computeOpLogShapeSeed:()=>({baseCheckpoint:void 0,cursor:10,epoch:"e1",reset:!0,rowsPatch:[]}),currentCdcEpoch:()=>"e1",deliverWhisperLocal:()=>0,doName:()=>b,env:()=>({SHARD:{get:()=>t,getByName:()=>t,idFromName:d=>d}}),getWebSockets:()=>[],maskMetadata:()=>({columns:[]}),nextPokeId:()=>"poke-1",readAttachment:()=>({}),recordShapePokeFanout:()=>{},resolveShape:(d,c,p)=>(e.push(p),d===h.name?{columns:["id"],effectiveWhere:{org:p?.identity?.org??"anonymous"},global:!1,table:"orders"}:{columns:["id"],effectiveWhere:{room:"lobby"},global:!1,table:"messages"}),rlsMetadata:()=>({policies:[]}),shardBinding:()=>"SHARD",shardJurisdiction:()=>{},sql:()=>s});if(r===void 0)throw new Error("expected an owner link for an un-suffixed DO name");return{owner:r,posts:o,resolvedUnder:e}},l=async(s,o)=>{await s.handleControl(new Request("https://owner.internal/_lunora/relay",{body:JSON.stringify({...o,connectionId:"c-alice",identity:{org:"acme"},relayIndex:0,subId:"s1",type:"relay_shape_subscribe",userId:"u1"}),headers:{"content-type":"application/json"},method:"POST"}))};y("seeds a subscriber under its own forwarded identity, never the anonymous one",async()=>{const{close:s,host:o}=m();try{const{owner:e,resolvedUnder:t}=i(o.sql);await l(e,h),n(t.some(a=>a?.userId==="u1"&&a.identity?.org==="acme")).toBe(!0)}finally{s?.()}}),y("routes an identity-scoped shape to a per-socket poke, not the cohort multicast",async()=>{const{close:s,host:o}=m();try{const{owner:e,posts:t}=i(o.sql);await l(e,h),t.length=0,await e.onFlush(new Set(["orders"]),20);const a=t.filter(r=>r.type==="relay_shape_poke");n(a.length).toBe(1),n(a[0]?.targetConnectionId).toBe("c-alice")}finally{s?.()}}),y("still multicasts an identity-blind shape to the whole cohort",async()=>{const{close:s,host:o}=m();try{const{owner:e,posts:t}=i(o.sql);await l(e,u),t.length=0,await e.onFlush(new Set(["messages"]),20);const a=t.filter(r=>r.type==="relay_shape_poke");n(a.length).toBe(1),n(a[0]?.targetConnectionId).toBeUndefined()}finally{s?.()}})})})};export{W as defineEngineContractSuite};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{LunoraError as _}from"@lunora/errors";import{sql as r}from"drizzle-orm";import{e as A,s as T}from"./sql-projection-
|
|
1
|
+
import{LunoraError as _}from"@lunora/errors";import{sql as r}from"drizzle-orm";import{e as A,s as T}from"./sql-projection-D3qdaItY.mjs";import{quoteIdentifier as p}from"./quoteIdentifier-CObIFRhb.mjs";import{d as $,n as S,e as O}from"./wire-codec-C-FpWm52.mjs";import{runDrizzle as f}from"./runDrizzle-2ULFQR_k.mjs";import"./serializeSqlValue-BEMMYX1n.mjs";const b=/^[A-Za-z_$][\w$]*$/u,h=e=>b.test(e)?e:`"${e.replaceAll("\\",String.raw`\\`).replaceAll('"',String.raw`\"`)}"`,m="__doc__",a="__originals__",G=e=>{if(Object.hasOwn(e,a))throw new _("BAD_REQUEST",`"${a}" is reserved by the row store's document encoding and cannot be used as a field name — rename the field`);let t,o;for(const[s,i]of Object.entries(e)){const c=T(i);c!==void 0&&(t??={...e},o??=Object.create(null),t[s]=c,o[s]=i)}t&&o&&(t[a]=o);const n=t??e;try{return S(n)?JSON.stringify(O(n)):JSON.stringify(n)}catch(s){throw new _("BAD_REQUEST",`this document cannot be stored: ${s instanceof Error?s.message:String(s)}`)}},g=e=>{const t=$(JSON.parse(e)),o=t[a];if(o===null||typeof o!="object"||Array.isArray(o))return t;const n={...t};return delete n[a],{...n,...o}},J=(e,t)=>`${e}__geo_${t}`,E=(e,t)=>t==="_id"||t==="id"?`${e}id`:t==="_creationTime"?`${e}_creationTime`:`json_extract(${e}${m}, '$.${h(t).replaceAll("'","''")}')`,y=e=>E("",e),q=e=>r.raw(y(e)),N=(e,t)=>E(`${p(e)}.`,t),B=(e,t)=>r.raw(N(e,t)),z=(e,t,o,n)=>r`CREATE ${n?r`UNIQUE `:r``}INDEX IF NOT EXISTS ${r.identifier(e)} ON ${r.identifier(t)} (${o})`,l=r.identifier("__key__"),I=r.identifier("__value__"),j=r.identifier("__count__"),F=(e,t,o,n,s)=>r`INSERT INTO ${r.identifier(e)} (${l}, ${I}, ${j}) VALUES (${t}, ${o}, ${n}) ON CONFLICT(${l}) DO UPDATE SET ${s}`,W=(e,t)=>e===void 0||t!==0&&t!==1||A(e)!=="boolean"?t:t===1,d=new WeakMap,k=e=>{const t=d.get(e);if(t!==void 0)return t;const o=[];for(const[n,s]of Object.entries(e.shape)){const i=s._meta?.column;i&&o.push(Object.freeze([n,i]))}return Object.freeze(o),d.set(e,o),o},C=e=>{if(!e)return;const t=e[m];let o;typeof t=="string"?o=g(t):t&&typeof t=="object"?o=t:o={};const{id:n}=e;typeof n=="string"&&(o._id=n);const s=e._creationTime;return typeof s=="number"&&(o._creationTime=s),o},K=e=>{try{return C(e)}catch{return}},u=new WeakMap,M=e=>{const t=u.get(e);if(t!==void 0)return t;let o;try{f(e,r`CREATE VIRTUAL TABLE IF NOT EXISTS ${r.identifier("__lunora_fts_probe")} USING fts5(x)`),o=!0}catch{o=!1}finally{try{f(e,r`DROP TABLE IF EXISTS ${r.identifier("__lunora_fts_probe")}`)}catch{}}return u.set(e,o),o};export{j as A,m as D,l as a,I as b,F as c,z as d,q as e,B as f,J as g,K as h,M as i,y as j,G as k,g as l,h as m,a as n,W as o,N as q,C as r,k as t};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{B as s}from"./sql-projection-
|
|
1
|
+
import{B as s}from"./sql-projection-D3qdaItY.mjs";const n=40,f=i=>{let e=0;const o=(r,t)=>typeof t=="bigint"?(e+=s+1+n,t.toString()):t instanceof ArrayBuffer||ArrayBuffer.isView(t)?(e+=2*Math.ceil(t.byteLength/3)*4+n,""):t;try{const r=JSON.stringify(i,o);return(r===void 0?0:r.length)+e}catch{return}};export{f as e};
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{LunoraError as T}from"@lunora/errors";import{sql as m}from"drizzle-orm";import{runDrizzle as S}from"./runDrizzle-2ULFQR_k.mjs";import{liftSourceId as A}from"./liftSourceId-CA3ENhXj.mjs";import{normalizeSourceValue as W}from"./liftSourceId-CA3ENhXj.mjs";import{runExternalSourceTick as C,materializeExternalRowsIncremental as D}from"./materializeExternalRows-
|
|
1
|
+
import{LunoraError as T}from"@lunora/errors";import{sql as m}from"drizzle-orm";import{runDrizzle as S}from"./runDrizzle-2ULFQR_k.mjs";import{liftSourceId as A}from"./liftSourceId-CA3ENhXj.mjs";import{normalizeSourceValue as W}from"./liftSourceId-CA3ENhXj.mjs";import{runExternalSourceTick as C,materializeExternalRowsIncremental as D}from"./materializeExternalRows-xQWkrJqp.mjs";const p="__lunora_source_cursor",M=e=>e instanceof Date?`d:${e.toISOString()}`:typeof e=="bigint"?`b:${e.toString()}`:typeof e=="number"?`n:${e.toString()}`:`s:${e}`,v=e=>{const t=e.slice(2);switch(e[0]){case"b":return BigInt(t);case"d":return new Date(t);case"n":return Number(t);default:return t}},h=/^-?\d+$/,N=/^-?\d+(?:\.\d+)?$/,x=(e,t)=>e instanceof Date&&t instanceof Date?e.getTime()>t.getTime():typeof e=="bigint"&&typeof t=="bigint"||typeof e=="number"&&typeof t=="number"?e>t:typeof e=="string"&&typeof t=="string"&&N.test(e)&&N.test(t)?h.test(e)&&h.test(t)?BigInt(e)>BigInt(t):Number(e)>Number(t):String(e)>String(t),O=(e,t,o)=>{let n=o===null?void 0:v(o);for(const r of e){const c=r[t];if(c==null)continue;const a=c;(n===void 0||x(a,n))&&(n=a)}return n===void 0?null:M(n)},B=e=>{S(e,m`CREATE TABLE IF NOT EXISTS ${m.identifier(p)} (
|
|
2
2
|
table_name TEXT NOT NULL,
|
|
3
3
|
shard_key TEXT NOT NULL,
|
|
4
4
|
watermark TEXT,
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{applyCdcChanges as p}from"./CDC_LOG_TABLE-
|
|
1
|
+
import{applyCdcChanges as p}from"./CDC_LOG_TABLE-CfILante.mjs";import{selectShapeRows as m}from"./selectShapeMembers-B8gTOeOB.mjs";import{diffExternalSource as g,projectExternalSourceRow as l}from"./diffExternalSource-DgDJhslq.mjs";import{stableStringify as d}from"./stableStringify-DibjylKD.mjs";const x=async(t,s,a,e)=>{const{changes:o,nextBaseline:n}=g(s,a,e);return await p(t,o),{applied:o.length,nextBaseline:n}},R=async(t,s,a)=>{const{columns:e,deletedIds:o,table:n}=a,r=[];for(const f of s){const i=l(f,e),c=String(i._id);if(o?.has(c)){await t.get(c,n)&&r.push({id:c,op:"delete",seq:0,table:n,ts:0});continue}const u=await t.get(c,n);u&&d(l({...u,_id:c},e))===d(i)||r.push({doc:i,id:c,op:"insert",seq:0,table:n,ts:0})}return await p(t,r),{applied:r.length}},h=(t,s,a)=>{const e=new Map;for(const{doc:o,id:n}of m(t,s,void 0))e.set(n,d(l({...o,_id:n},a)));return e},_=async(t,s,a,e)=>{const o=h(t,e.table,e.columns);return x(s,a,o,e)};export{x as materializeExternalRows,R as materializeExternalRowsIncremental,h as readExternalSourceBaseline,_ as runExternalSourceTick};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{keysTouchRanges as i}from"./buildIndexRange-
|
|
1
|
+
import{keysTouchRanges as i}from"./buildIndexRange-DvN8Qj8e.mjs";const f=(o,r,n)=>{const e=o??new Map;for(const t of n){const s=r?.get(t),u=e.get(t),c=e.has(t)&&u===void 0;if(!r?.has(t)||s===void 0||c){e.set(t,void 0);continue}e.set(t,u?[...u,...s]:s)}return e},a=(o,r,n)=>{const e=o??new Map;if(e.has(r)&&e.get(r)===void 0)return e;if(!n||n.length===0)return e.set(r,void 0),e;const t=e.get(r);return e.set(r,t?[...t,...n]:[...n]),e},h=(o,r,n)=>{if(!n)return!0;for(const e of r){if(!o.tables.has(e))continue;const t=o.ranges?.get(e);if(!t||t.length===0||i(t,n.get(e)))return!0}return!1};export{f as mergeChangedKeys,a as recordChangedKeys,h as writeTouchesMemo};
|
package/dist/packem_shared/{runShardMigrations-DbQJdY1X.mjs → runShardMigrations-BLl8xFGK.mjs}
RENAMED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{LunoraError as L}from"@lunora/errors";import{S as h,y as l,l as N}from"./ctx-db-companions-
|
|
1
|
+
import{LunoraError as L}from"@lunora/errors";import{S as h,y as l,l as N}from"./ctx-db-companions-DsNfXSbb.mjs";import{sql as e}from"drizzle-orm";import{aggregateTableName as R}from"./aggregateTableName-C7o-gpms.mjs";import{backfillSearchIndexesForTable as O}from"./backfillAggregateIndexes-DTemznr7.mjs";import{migrateCdcLog as x,migrateCdcMeta as C}from"./CDC_LOG_TABLE-CfILante.mjs";import{migrateClientWatermark as $}from"./CLIENT_WATERMARK_TABLE-CRnrAnJ2.mjs";import{migrateCommitSeq as U}from"./COMMIT_SEQ_FIELD-BUdOMG5y.mjs";import{migrateGlobalShapeSnapshot as D}from"./GLOBAL_SHAPE_SNAPSHOT_TABLE-DSA6mzyx.mjs";import{migrateIdempotency as b}from"./IDEMPOTENCY_TABLE-DOpm_oMF.mjs";import{m as X}from"./ctx-db-relay-shapes-Bg5YYnmN.mjs";import{migrateScheduleOutbox as G}from"./SCHEDULE_OUTBOX_TABLE-CD_UjYVx.mjs";import{m as M}from"./ctx-db-search-state-ruTuCsxa.mjs";import{migrateShapePokeCursor as F}from"./SHAPE_POKE_CURSOR_TABLE-ByJVDHds.mjs";import{runDrizzle as s}from"./runDrizzle-2ULFQR_k.mjs";import{D as y,d as E,e as g,t as B,i as Y,g as k,a as v,b as P,A}from"./do-sql-kpl5Kt1j.mjs";import{renderSql as w}from"./param-DlozcSQu.mjs";import{migrateDurableStreams as j}from"./appendStreamChunk-C1Ok4b6J.mjs";import{rankTableName as K,sortColumnName as H}from"./RANK_TIEBREAK-D5xNdzB3.mjs";import{migrateReactorState as V}from"./REACTOR_STATE_TABLE-QPRFyxMS.mjs";import{recordSchemaVersion as W}from"./SCHEMA_HISTORY_MAX_VERSIONS-BluIj2s-.mjs";const S=e`_creationTime, id`,p=(r,o,i,t,n,a)=>{const c=e.join(n.map(d=>e`${d} IS NOT NULL`),e` AND `);if(s(r,e`SELECT 1 FROM ${e.identifier(i)} WHERE ${c} GROUP BY ${t} HAVING COUNT(*) > 1 LIMIT 1`).toArray().length>0)throw new L("INTERNAL",`unique index "${o}" on "${i}" ${a}: existing rows are duplicates under it. De-duplicate the table with a data migration first; the previous index is left in place.`)},z=(r,o,i,t,n,a)=>{const m=s(r,e`SELECT sql FROM sqlite_master WHERE type = 'index' AND name = ${o} AND tbl_name = ${i}`).toArray()[0]?.sql;if(m==null)return;const d=_=>{const I=_.indexOf("(");return I===-1?void 0:_.slice(I,_.lastIndexOf(")")+1)},T=d(w("sqlite",E(o,i,t,n)).sql),f=d(m);T===void 0||f===void 0||T===f||(n&&p(r,o,i,t,a,"cannot be re-created with its new column list"),s(r,e`DROP INDEX IF EXISTS ${e.identifier(o)}`))},J=(r,o,i)=>s(r,e`SELECT 1 FROM sqlite_master WHERE type = 'index' AND name = ${o} AND tbl_name = ${i} LIMIT 1`).toArray().length>0,u=(r,o,i,t,n,a)=>{n&&!J(r,o,i)&&p(r,o,i,t,a,"cannot be created"),s(r,E(o,i,t,n))},Q=(r,o,i)=>{for(const t of i.indexes){const n=`${o}_${t.name}`,a=t.unique??!1,c=t.fields.map(T=>g(T)),m=e.join(c,e`, `),d=a?m:e`${m}, ${S}`;z(r,n,o,d,a,c),u(r,n,o,d,a,c)}for(const[t,n]of B(i)){if(!n.unique)continue;const a=g(t);u(r,`${o}_unique_${t}`,o,a,!0,[a])}},Z=(r,o,i)=>{if(!(!i.searchIndexes||i.searchIndexes.length===0||!Y(r))){for(const t of i.searchIndexes){const n=h(o,t.name);s(r,e`CREATE VIRTUAL TABLE IF NOT EXISTS ${e.identifier(n)} USING fts5(${e.identifier(l)}, ${e.identifier(N)} UNINDEXED)`),s(r,e`CREATE VIRTUAL TABLE IF NOT EXISTS ${e.identifier(`${n}__vocab`)} USING fts5vocab(${e.identifier(n)}, ${e.raw("instance")})`)}O(r,o,i)}},q=(r,o,i)=>{if(i.geoIndexes)for(const t of i.geoIndexes){const n=k(o,t.name);s(r,e`CREATE TABLE IF NOT EXISTS ${e.identifier(n)} (${e.identifier("__id__")} TEXT PRIMARY KEY, ${e.identifier("__geohash__")} TEXT NOT NULL, ${e.identifier("__lat__")} REAL NOT NULL, ${e.identifier("__lng__")} REAL NOT NULL)`);const a=`${o}__geo_${t.name}__btree`;s(r,E(a,n,e`${e.identifier("__geohash__")} ASC, ${e.identifier("__id__")} ASC`,!1))}},ee=(r,o,i)=>{if(i.aggregateIndexes)for(const t of i.aggregateIndexes){const n=R(o,t.name);s(r,e`CREATE TABLE IF NOT EXISTS ${e.identifier(n)} (${v} TEXT PRIMARY KEY, ${P} REAL, ${A} INTEGER NOT NULL DEFAULT 0)`),s(r,e`PRAGMA table_info(${e.identifier(n)})`).toArray().some(c=>c.name==="__count__")||s(r,e`ALTER TABLE ${e.identifier(n)} ADD COLUMN ${A} INTEGER NOT NULL DEFAULT 0`)}},re=(r,o,i)=>{if(i.rankIndexes)for(const t of i.rankIndexes){const n=K(o,t.name),a=t.sortBy.map((f,_)=>H(_)),c=a.map(f=>e`${e.identifier(f)} BLOB`),m=c.length>0?e`, ${e.join(c,e`, `)}`:e``;s(r,e`CREATE TABLE IF NOT EXISTS ${e.identifier(n)} (${e.identifier("__id__")} TEXT PRIMARY KEY, ${e.identifier("__partition__")} TEXT NOT NULL${m})`);const d=[e`${e.identifier("__partition__")} ASC`];for(const[f,_]of a.entries()){const I=t.sortBy[f]?.direction;d.push(e`${e.identifier(_)} ${e.raw(I==="desc"?"DESC":"ASC")}`)}d.push(e`${e.identifier("__id__")} ASC`);const T=`${o}__rank_${t.name}__btree`;s(r,E(T,n,e.join(d,e`, `),!1))}},le=(r,o,i={})=>{i.schemaSnapshot!==void 0&&W(r,i.schemaSnapshot.hash,i.schemaSnapshot.json),M(r);for(const[t,n]of Object.entries(o.tables))n.shardMode?.kind!=="global"&&(s(r,e`CREATE TABLE IF NOT EXISTS ${e.identifier(t)} (
|
|
2
2
|
id TEXT PRIMARY KEY,
|
|
3
3
|
_creationTime REAL NOT NULL,
|
|
4
4
|
${e.identifier(y)} TEXT NOT NULL
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{sql as o}from"drizzle-orm";import{runDrizzle as h}from"./runDrizzle-2ULFQR_k.mjs";import{e}from"./do-sql-
|
|
1
|
+
import{sql as o}from"drizzle-orm";import{runDrizzle as h}from"./runDrizzle-2ULFQR_k.mjs";import{e}from"./do-sql-kpl5Kt1j.mjs";const E=(s,t,f,r)=>{const d=f-(t.after??0),i=[o`${e(t.field)} IS NOT NULL`,o`${e(t.field)} < ${d}`];t.softDeleteField!==void 0&&i.push(o`${e(t.softDeleteField)} IS NULL`);const l=o`SELECT id FROM ${o.identifier(t.table)} WHERE ${o.join(i,o` AND `)} LIMIT ${o.raw(String(Math.max(0,Math.floor(r))+1))}`,n=h(s,l).toArray(),a=n.length>r,$=n.slice(0,r).map(c=>c.id);return{hasMore:a,ids:$}};export{E as selectExpiredIds};
|
package/dist/packem_shared/{selectShapeMembers-CCZyZggM.mjs → selectShapeMembers-B8gTOeOB.mjs}
RENAMED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{sql as e}from"drizzle-orm";import{runDrizzle as m}from"./runDrizzle-2ULFQR_k.mjs";import{D as p,r as d,e as h}from"./do-sql-
|
|
1
|
+
import{sql as e}from"drizzle-orm";import{runDrizzle as m}from"./runDrizzle-2ULFQR_k.mjs";import{D as p,r as d,e as h}from"./do-sql-kpl5Kt1j.mjs";import{sqliteInList as w}from"./param-DlozcSQu.mjs";import{c as S}from"./where-sql-x1YKldcq.mjs";import{serializeSqlValue as $}from"./serializeSqlValue-BEMMYX1n.mjs";const C={fieldRef:h,serialize:$},g=o=>{if(o.length!==0)return w(e`${e.identifier("id")}`,o,!1)},u=(o,i)=>{const r=[];i&&r.push(i);const t=S(o,C);return t&&r.push(t),r.length===0?e``:e` WHERE ${e.join(r,e` AND `)}`},v=(o,i,r)=>{const t=u(r,void 0),s=m(o,e`SELECT id, _creationTime, ${e.identifier(p)} FROM ${e.identifier(i)}${t}`).toArray(),f=[];for(const l of s){const n=d(l),{id:c}=l;n!==void 0&&typeof c=="string"&&f.push({doc:n,id:c})}return f},z=(o,i,r,t)=>{const s=new Map;if(t.length===0)return s;const f=u(r,g(t)),l=m(o,e`SELECT id, _creationTime, ${e.identifier(p)} FROM ${e.identifier(i)}${f}`).toArray();for(const n of l){const c=d(n),{id:a}=n;c!==void 0&&typeof a=="string"&&s.set(a,c)}return s};export{z as selectShapeMembers,v as selectShapeRows};
|
package/dist/packem_shared/{serializeSqlValue-CjbhIHjJ.mjs → serializeSqlValue-BEMMYX1n.mjs}
RENAMED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{s as o}from"./sql-projection-
|
|
1
|
+
import{s as o}from"./sql-projection-D3qdaItY.mjs";const n=r=>typeof r=="boolean"?r?1:0:r===null||typeof r=="string"||typeof r=="number"?r:o(r)??JSON.stringify(r);export{n as serializeSqlValue};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{LunoraError as g}from"@lunora/errors";import{t as o}from"./base64-DfpzS4o_.mjs";const l=t=>{const{value:n}=t._meta??{};if(n===null)return"null";switch(typeof n){case"bigint":case"boolean":case"number":case"string":return typeof n;default:return t.kind}},s=t=>{if(t.kind==="literal")return l(t);if(t.kind!=="optional")return t.kind;const n=t._meta?.inner;return n?s(n):t.kind},r=39,f="0",c="1",a=t=>Array.from(t,n=>String(9-Number(n))).join(""),d=t=>{const n=t<0n,e=(n?-t:t).toString();if(e.length>r)throw new g("BAD_REQUEST",`bigint ${t.toString()} has ${String(e.length)} digits, over the ${String(r)}-digit limit for a queryable column`);const i=e.padStart(r,"0");return n?f+a(i):c+i},u=/^\d+$/u,p=t=>{if(t.length!==r+1)return;const n=t.slice(0,1),e=t.slice(1);if(u.test(e))return n===c?BigInt(e):n===f?-BigInt(a(e)):void 0},m=/^[\da-f]{16}$/u,I=t=>{const n=new DataView(new ArrayBuffer(8));n.setFloat64(0,t===0?0:t,!1);let e=n.getUint32(0,!1),i=n.getUint32(4,!1);return(e&2147483648)===0?e=(e^2147483648)>>>0:(e=~e>>>0,i=~i>>>0),e.toString(16).padStart(8,"0")+i.toString(16).padStart(8,"0")},h=t=>{if(!m.test(t))return;let n=Number.parseInt(t.slice(0,8),16),e=Number.parseInt(t.slice(8),16);(n&2147483648)===0?(n=~n>>>0,e=~e>>>0):n=(n^2147483648)>>>0;const i=new DataView(new ArrayBuffer(8));return i.setUint32(0,n,!1),i.setUint32(4,e,!1),i.getFloat64(0,!1)},w=t=>typeof t=="bigint"?d(t):t instanceof ArrayBuffer?o(new Uint8Array(t)):ArrayBuffer.isView(t)?o(new Uint8Array(t.buffer,t.byteOffset,t.byteLength)):void 0,y=t=>{const n=s(t);return n==="bigint"||n==="bytes"},B=t=>{const n=s(t);return y(t)||n==="any"||n==="union"||n==="from"};export{r as B,h as a,d as b,p as d,s as e,I as f,y as i,B as m,w as s};
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@lunora/shard-engine",
|
|
3
|
-
"version": "1.0.0-alpha.
|
|
3
|
+
"version": "1.0.0-alpha.72",
|
|
4
4
|
"description": "Host-neutral reactive engine for Lunora: per-shard state, OCC, CDC, reactive subscriptions, and the poke protocol. Consumes @lunora/platform host contracts and can be mounted on any platform host.",
|
|
5
5
|
"keywords": [
|
|
6
6
|
"cloudflare",
|
|
@@ -48,7 +48,7 @@
|
|
|
48
48
|
"access": "public"
|
|
49
49
|
},
|
|
50
50
|
"dependencies": {
|
|
51
|
-
"@lunora/errors": "1.0.0-alpha.
|
|
51
|
+
"@lunora/errors": "1.0.0-alpha.39",
|
|
52
52
|
"@lunora/platform": "1.0.0-alpha.32",
|
|
53
53
|
"drizzle-orm": "^0.45.2"
|
|
54
54
|
},
|
|
@@ -1,15 +0,0 @@
|
|
|
1
|
-
import{LunoraError as L}from"@lunora/errors";import{sql as t}from"drizzle-orm";import{quoteIdentifier as C}from"./quoteIdentifier-CObIFRhb.mjs";import{runSql as p,runDrizzle as s}from"./runDrizzle-2ULFQR_k.mjs";import{k as u,l as m}from"./do-sql-Dvj8Yl5N.mjs";import{ConflictError as A}from"./ConflictError-C8GtJmjS.mjs";const n="__cdc_log",q=`INSERT INTO ${C(n)} (ts, ${C("table")}, id, op, doc) VALUES (?, ?, ?, ?, ?)`,I="__cdc_log_table_seq",y=e=>{s(e,t`CREATE TABLE IF NOT EXISTS ${t.identifier(n)} (
|
|
2
|
-
seq INTEGER PRIMARY KEY AUTOINCREMENT,
|
|
3
|
-
ts REAL NOT NULL,
|
|
4
|
-
${t.identifier("table")} TEXT NOT NULL,
|
|
5
|
-
id TEXT NOT NULL,
|
|
6
|
-
op TEXT NOT NULL,
|
|
7
|
-
doc TEXT
|
|
8
|
-
)`);try{s(e,t`CREATE INDEX IF NOT EXISTS ${t.identifier(I)} ON ${t.identifier(n)} (${t.identifier("table")}, seq)`)}catch{}},F=(e,o,r,i,c,a)=>{const d=a===void 0?null:u(a);p(e,q,o,r,i,c,d)},f=90,N=e=>t` AND ${t.identifier("table")} IN (${t.join([...e].map(o=>t`${o}`),t`, `)})`,U=(e,o={})=>{const r=o.sinceSeq??0,i=Math.max(1,Math.min(o.limit??1e3,1e4)),a=s(e,t`SELECT seq, ts, ${t.identifier("table")}, id, op, doc FROM ${t.identifier(n)} WHERE seq > ${r} ORDER BY seq ASC LIMIT ${i}`).toArray().map(d=>{const l={id:d.id,op:d.op,seq:d.seq,table:d.table,ts:d.ts};return d.doc===null?l:{...l,doc:m(d.doc)}});return{changes:a,cursor:a.at(-1)?.seq??r}},g=(e,o,r)=>{if(r.size===0)return!1;const i=[...r];for(let c=0;c<i.length;c+=f){const a=new Set(i.slice(c,c+f));if(s(e,t`SELECT 1 AS hit FROM ${t.identifier(n)} WHERE seq > ${o}${N(a)} LIMIT 1`).toArray().length>0)return!0}return!1},T=new WeakMap,S=e=>new Set(s(e,t`SELECT name FROM sqlite_master WHERE type = 'table'`).toArray().map(o=>o.name)),X=(e,o)=>{if(o.size===0)return!1;let r=T.get(e),i=!1;r===void 0&&(r=S(e),i=!0,T.set(e,r));for(const c of o)if(!r.has(c)&&(i||(r=S(e),i=!0,T.set(e,r),!r.has(c))))return!1;return!0},B=(e,o,r,i)=>s(e,t`SELECT id, op, MAX(seq) AS maxSeq, COUNT(*) AS ops FROM ${t.identifier(n)}
|
|
9
|
-
WHERE ${t.identifier("table")} = ${o} AND seq > ${r} AND seq <= ${i}
|
|
10
|
-
GROUP BY id
|
|
11
|
-
ORDER BY maxSeq ASC`).toArray().map(a=>{const d=a.op;return{id:a.id,op:d==="insert"&&a.ops>1?"update":d,seq:a.maxSeq}}),H=(e,o,r)=>{s(e,t`DELETE FROM ${t.identifier(n)} WHERE seq IN (
|
|
12
|
-
SELECT seq FROM ${t.identifier(n)} WHERE seq <= ${o} ORDER BY seq ASC LIMIT ${r}
|
|
13
|
-
)`)},x=(e,o,r)=>{s(e,t`UPDATE ${t.identifier(n)} SET doc = NULL WHERE seq IN (
|
|
14
|
-
SELECT seq FROM ${t.identifier(n)} WHERE seq <= ${o} AND doc IS NOT NULL ORDER BY seq ASC LIMIT ${r}
|
|
15
|
-
)`)},W=(e,o)=>{if(o<=0)return s(e,t`SELECT MAX(seq) AS seq FROM ${t.identifier(n)}`).toArray()[0]?.seq??void 0;const i=s(e,t`SELECT seq FROM ${t.identifier(n)} ORDER BY seq DESC LIMIT 1 OFFSET ${o-1}`).toArray()[0]?.seq;return i===void 0?void 0:i-1},v=e=>{const r=s(e,t`SELECT seq FROM sqlite_sequence WHERE name = ${n}`).toArray()[0]?.seq;return typeof r=="number"?r:s(e,t`SELECT MAX(seq) AS seq FROM ${t.identifier(n)}`).toArray()[0]?.seq??0},Y=(e,o)=>e!==void 0&&e>o+1,P=(e,o,r)=>new L("CDC_LOG_TRIMMED",`${r==="global"?"global cdc":"cdc"} entries at or below seq ${String(e-1)} have been trimmed; resume from a snapshot (sinceSeq ${String(o)} is below the retained window)`,{status:409}),O=e=>s(e,t`SELECT MIN(seq) AS seq FROM ${t.identifier(n)}`).toArray()[0]?.seq??void 0,G=e=>{const r=s(e,t`SELECT MAX(seq) AS seq FROM ${t.identifier(n)} WHERE op <> 'delete' AND doc IS NULL`).toArray()[0]?.seq??void 0,i=O(e);return r===void 0?i:Math.max(r+1,i??0)},E="__cdc_meta",R=e=>{s(e,t`CREATE TABLE IF NOT EXISTS ${t.identifier(E)} (id INTEGER PRIMARY KEY CHECK (id = 1), epoch TEXT NOT NULL)`)},K=e=>{R(e);const r=s(e,t`SELECT epoch FROM ${t.identifier(E)} WHERE id = 1`).toArray()[0]?.epoch;if(typeof r=="string"&&r.length>0)return r;const i=crypto.randomUUID();return s(e,t`INSERT INTO ${t.identifier(E)} (id, epoch) VALUES (1, ${i})`),i},V=e=>{R(e);const o=crypto.randomUUID();return s(e,t`INSERT INTO ${t.identifier(E)} (id, epoch) VALUES (1, ${o}) ON CONFLICT(id) DO UPDATE SET epoch = excluded.epoch`),o},$=async(e,o)=>{if(o.op==="delete"){await e.delete(o.id,o.table);return}const r=o.doc??{};try{await e.insert(o.table,r,{allowExplicitId:!0})}catch(i){if(!(i instanceof A))throw i;const c={...r};delete c._id,await e.replace(o.id,c,o.table,{allowExplicitId:!0})}},z=async(e,o)=>{for(const r of o)await $(e,r)};export{q as CDC_APPEND_SQL,n as CDC_LOG_TABLE,I as CDC_LOG_TABLE_SEQ_INDEX,E as CDC_META_TABLE,F as appendCdcChange,z as applyCdcChanges,V as bumpCdcEpoch,X as cdcCanVouchFor,W as cdcSeqLeavingRows,g as cdcTouchesTables,P as cdcTrimmedError,x as compactCdcDocs,Y as cursorBelowRetainedFloor,y as migrateCdcLog,R as migrateCdcMeta,G as minCdcReplayableSeq,O as minCdcSeq,B as readCdcChangeKeys,U as readCdcChanges,v as readCdcCursor,K as readCdcEpoch,H as trimCdcChanges};
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{LunoraError as $}from"@lunora/errors";import{D as st}from"./MAX_TOKEN_LENGTH-BakL9FUy-B3VwYY8C.mjs";import{c as pn,S as gn,l as Le,a as $n}from"./ctx-db-companions-w-CfeOda.mjs";import{sql as i}from"drizzle-orm";import{d as yn}from"./wire-codec-C-FpWm52.mjs";import{throwingScheduler as En,aggregateSqlFunction as ke,normalizeCountArgument as mn}from"./AGGREGATE_SQL_FUNCTION-DDEoMnJR.mjs";import{aggregateTableName as Ve,encodeAggregateKey as ze,readAggregateValue as Je}from"./aggregateTableName-C7o-gpms.mjs";import{mergeWhere as V,CountRlsUnsupportedError as Ye,selectIndexForGroupBy as Sn,selectIndexForCount as _n,selectIndexForAggregate as Rn}from"./CountRlsUnsupportedError-BvsDqfO2.mjs";import{backfillSearchIndexesForTable as Tn,searchIndexCoversTable as vn}from"./backfillAggregateIndexes-BG5-SC1q.mjs";import{backfillAggregateIndexes as Lr,backfillRankIndexes as kr,backfillSearchIndexes as Fr}from"./backfillAggregateIndexes-BG5-SC1q.mjs";import{appendCdcChange as An}from"./CDC_LOG_TABLE-vVheEulD.mjs";import{CDC_LOG_TABLE as Br,applyCdcChanges as Wr,bumpCdcEpoch as Pr,cdcCanVouchFor as Ur,cdcSeqLeavingRows as Gr,cdcTouchesTables as Hr,cdcTrimmedError as Or,compactCdcDocs as Nr,cursorBelowRetainedFloor as jr,minCdcReplayableSeq as Kr,minCdcSeq as Qr,readCdcChangeKeys as Vr,readCdcChanges as zr,readCdcCursor as Jr,readCdcEpoch as Yr,trimCdcChanges as Xr}from"./CDC_LOG_TABLE-vVheEulD.mjs";import{allocateCommitSeq as In,COMMIT_SEQ_FIELD as Cn}from"./COMMIT_SEQ_FIELD-BUdOMG5y.mjs";import{isMemoryTable as _t}from"./clearMemoryTables-BGbmag2i.mjs";import{computeRankPage as Rt}from"./computeRankPage-DsQ16o1z.mjs";import{SCAN_DEP as G}from"./SCAN_DEP-D7qE3iUe.mjs";import{runDrizzle as O,runSql as _e}from"./runDrizzle-2ULFQR_k.mjs";import{D as oe,k as ae,r as ue,b as Fe,A as Xe,a as qe,e as Z,o as xn,t as Kt,j as Pe,q as Tt,i as bn,h as Qt,g as Mn}from"./do-sql-Dvj8Yl5N.mjs";import{renderSql as Vt,unionAll as ct,WORKERD_SQLITE_LIMITS as zt,sqliteInList as Dn}from"./param-DlozcSQu.mjs";import{coveringGeohashes as Ln,boundingBoxGeohashes as kn,haversineMeters as Fn,pointInBoundingBox as qn}from"./GEO_DEFAULT_PRECISION-CqpQZ-J_.mjs";import{NotFoundError as Bn}from"./NotFoundError-BhF7FeFr.mjs";import{softDeleteScope as le,normalizeOrderKeys as nt,uniqueIndexFields as Jt,equalityPinnedFields as Wn,buildSeekWhere as Yt,decodeCursor as ot,applySelect as vt,encodeCursor as rt,tiebreakDirectionFor as Xt,buildSeekBeforeWhere as Pn}from"./CURSOR_PREFIX-Bn8SFoGd.mjs";import{rankTableName as At,sortColumnName as It,resolveRankPartition as Un,encodePartitionKey as Gn,RANK_TIEBREAK as Hn,rankPivotConditionSql as On}from"./RANK_TIEBREAK-BXDiMmkH.mjs";import{UNVOUCHABLE_DEP as Ct}from"./UNVOUCHABLE_DEP-C68htACn.mjs";import{indexKeysForRow as Nn,buildIndexRange as jn}from"./buildIndexRange-NtciKq3M.mjs";import{deriveRelationEdges as Kn,findRelated as Qn}from"./RELATED_DEFAULT_LIMIT-B9PH28Pn.mjs";import{assertFlatPredicate as Ze,resolveRelationPredicates as xt}from"./DEFAULT_MAX_RELATION_KEYS-XESc7TiB.mjs";import{runRowValidators as et,resolveWith as bt,relationHooks as Mt,applyOnDelete as Vn,fanOutScalarCounts as zn}from"./applyOnDelete-7JZ4vR9r.mjs";import{guardWriter as Jn}from"./RLS_UNWRAP_SYMBOL-BwwTbz3Q.mjs";import{quoteIdentifier as Re}from"./quoteIdentifier-CObIFRhb.mjs";import{m as Yn}from"./sql-projection-BB2lCbYV.mjs";import{createSystemReader as Xn}from"./createSystemReader-DcDLFfC-.mjs";import{ConflictError as me}from"./ConflictError-C8GtJmjS.mjs";import{runTriggers as Zn}from"./hasTrigger-CjlwI4le.mjs";import{c as ne,t as Ge,r as Ue,j as Se,i as Dt}from"./where-sql-x1YKldcq.mjs";import{CLIENT_WATERMARK_TABLE as ei,advanceClientWatermark as ti,migrateClientWatermark as ni,readClientWatermark as oi}from"./CLIENT_WATERMARK_TABLE-CRnrAnJ2.mjs";import{GLOBAL_SHAPE_SNAPSHOT_TABLE as ii,deleteGlobalShapeSnapshot as si,deleteGlobalShapeSnapshotsForConnection as ci,migrateGlobalShapeSnapshot as ai,readGlobalShapeSnapshot as di,writeGlobalShapeSnapshot as li}from"./GLOBAL_SHAPE_SNAPSHOT_TABLE-DSA6mzyx.mjs";import{IDEMPOTENCY_TABLE as fi,readIdempotent as hi,trimIdempotent as wi,writeIdempotent as pi}from"./IDEMPOTENCY_TABLE-DOpm_oMF.mjs";import{runShardMigrations as $i}from"./runShardMigrations-DbQJdY1X.mjs";import{S as Ei}from"./ctx-db-search-state-ruTuCsxa.mjs";import{selectShapeMembers as Si,selectShapeRows as _i}from"./selectShapeMembers-CCZyZggM.mjs";import{serializeSqlValue as re}from"./serializeSqlValue-CjbhIHjJ.mjs";const eo=o=>{const r=atob(o),t=Uint8Array.from(r,a=>a.codePointAt(0)??0);return new TextDecoder().decode(t)},to=()=>new $("BAD_REQUEST","invalid cursor"),Lt=16,kt=8,Y=1024,at=(o,r)=>r.query(o),no=(o,r)=>{if(o.length===0)return 0;let t=0;for(const[a,d]of r.entries()){const w=a===r.length-1;let S=0;for(const T of o)(w?T.startsWith(d):T===d)&&(S+=1);if(S===0)return 0;t+=S}return t},oo=(o,r)=>{if(!r)return{exact:!0,lower:o,upper:o};const t=[...o].at(-1)??"",a=(t.codePointAt(0)??0)+1;if(a>=55296&&a<=57343||a>1114111)return{exact:!0,lower:o,upper:o};const d=o.slice(0,o.length-t.length);return{exact:!1,lower:o,upper:d+String.fromCodePoint(a)}},ro=(o,r,t)=>{const a={eq:(d,w)=>{if(!o.definition.filterFields?.includes(d))throw new $("INTERNAL",`field "${d}" is not a filter field of search index "${o.indexName}" on table "${r}"`);if(o.filters.length>=kt)throw new $("BAD_REQUEST",`search index "${o.indexName}" on table "${r}": at most ${String(kt)} .eq() filters are supported per search query`);return o.filters.push({field:d,value:w}),a},search:(d,w)=>{const S=o;if(d!==S.definition.field)throw new $("INTERNAL",`search index "${S.indexName}" on table "${r}" indexes "${S.definition.field}", not "${d}"`);const T=at(w,t).length;if(T>Lt)throw new $("BAD_REQUEST",`search index "${S.indexName}" on table "${r}": at most ${String(Lt)} search terms are supported (got ${String(T)})`);return S.field=d,S.query=w,S.hasQuery=!0,a}};return a},io=o=>{if(o.length>Y)throw new $("BAD_REQUEST",`more than ${String(Y)} documents match this search — narrow it with filters or read it a page at a time with .paginate()`)},so=o=>Math.min(o.offset+o.numItems+1,Y),co=o=>btoa(`search:${String(o)}`),ao=o=>{let r;try{r=eo(o)}catch{return}if(!r.startsWith("search:"))return;const t=Number(r.slice(7));return Number.isInteger(t)&&t>=0?t:void 0},lo=o=>{if(typeof o.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(o.numItems))throw new $("BAD_REQUEST",`search pagination needs a finite numItems, got ${String(o.numItems)}`);const r=Math.max(0,Math.floor(o.numItems)),t=o.cursor?ao(o.cursor):0;if(t===void 0)throw to();if(t+r>=Y)throw new $("BAD_REQUEST",`search pagination reaches the ${String(Y)}-document limit (offset ${String(t)} + ${String(r)} requested) — a page must end below the cap so the probe row that answers \`hasMore\` still fits: retry with numItems ${String(Math.max(1,Y-t-1))} or fewer, or narrow the query or the filters instead`);return{numItems:r,offset:t}},uo=(o,r)=>{const t=r.offset+r.numItems,a=r.numItems>0&&o.length>t;return{continueCursor:a?co(t):null,isDone:!a,page:o.slice(r.offset,t)}},fo=o=>{if(o===void 0)return Y+1;if(!Number.isFinite(o))return Y;const r=Math.max(0,Math.floor(o));if(r>Y)throw new $("BAD_REQUEST",`search returns at most ${String(Y)} documents (asked for ${String(r)}) — narrow the query or paginate instead`);return r},He=o=>{const r=new Map;return t=>{const a=r.get(t);if(a!==void 0)return a;const d=o(Re(t));return r.set(t,d),d}},fe=Re(oe),ho=He(o=>`INSERT INTO ${o} (id, _creationTime, ${fe}) VALUES (?, ?, ?)`),Ft=He(o=>`UPDATE ${o} SET ${fe} = ? WHERE id = ? AND ${fe} = ?`),wo=He(o=>`UPDATE ${o} SET _creationTime = ?, ${fe} = ? WHERE id = ? AND ${fe} = ?`),po=He(o=>`DELETE FROM ${o} WHERE id = ? AND ${fe} = ?`),go="SELECT changes() AS changed",qt=new Map,$o="",yo=o=>{const r=JSON.stringify(o),t=qt.get(r);if(t!==void 0)return t;const a=o.map(w=>i`SELECT ${i.raw(`'${w.replaceAll("'","''")}'`)} AS __t__, id, _creationTime, ${i.identifier(oe)} FROM ${i.identifier(w)} WHERE id = ${$o}`),{sql:d}=Vt("sqlite",i`${ct(a)} LIMIT 1`);return qt.set(r,d),d},Eo=(o,r)=>r.map(()=>o),mo=/^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/iu,So=o=>{if(!mo.test(o))throw new $("INTERNAL",`invalid clientId ${JSON.stringify(o)}: a client-supplied row id must be a UUID`)},Bt=50,Zt=500,Be=Math.floor(zt.boundParams/3),ye=zt.boundParams,_o=128,de=(o,r,t)=>{const a=r??Zt;if(o>a)throw new $("BATCH_LIMIT_EXCEEDED",`${t}: batch of ${String(o)} exceeds the limit of ${String(a)} (raise options.limit or chunk the call)`,{status:400})},Ro=o=>{const r={eq:(t,a)=>(o.sqlConditions.push({comparator:"=",field:t,value:a}),r),gt:(t,a)=>(o.sqlConditions.push({comparator:">",field:t,value:a}),r),gte:(t,a)=>(o.sqlConditions.push({comparator:">=",field:t,value:a}),r),lt:(t,a)=>(o.sqlConditions.push({comparator:"<",field:t,value:a}),r),lte:(t,a)=>(o.sqlConditions.push({comparator:"<=",field:t,value:a}),r)};return r},To=o=>Math.max(o,Y),en=(o,r)=>{const t=o.filters.map(a=>i`${Z(a.field)} = ${re(a.value)}`);return r&&t.push(r),t},vo=(o,r,t,a,d)=>{const w=at(t.query,st(t.definition.language));if(w.length===0)return[];const S=gn(r,t.indexName),T=`${S}__vocab`,y=w.length-1,k=w.map((q,_)=>{const F=oo(q,_===y),j=F.exact?i`${i.identifier("term")} = ${F.lower}`:i`${i.identifier("term")} >= ${F.lower} AND ${i.identifier("term")} < ${F.upper}`;return i`SELECT ${i.identifier("doc")}, ${i.raw(String(_))} AS ${i.identifier("__term__")}, COUNT(*) AS ${i.identifier("__n__")} FROM ${i.identifier(T)} WHERE ${j} GROUP BY ${i.identifier("doc")}`}),g=w.map((q,_)=>i`SUM(CASE WHEN u.${i.identifier("__term__")} = ${i.raw(String(_))} THEN u.${i.identifier("__n__")} ELSE 0 END)`),A=i`SELECT f.${i.identifier(Le)} AS ${i.identifier(Le)}, ${i.join(g,i` + `)} AS ${i.identifier("__score__")} FROM (${ct(k)}) u JOIN ${i.identifier(S)} f ON f.rowid = u.${i.identifier("doc")} GROUP BY f.${i.identifier(Le)} HAVING ${i.join(g.map(q=>i`${q} > 0`),i` AND `)}`,I=en(t,d);let L=i`SELECT m.id, m._creationTime, m.${i.identifier(oe)}, s.${i.identifier("__score__")} AS ${i.identifier("__score__")} FROM (${A}) s JOIN ${i.identifier(r)} m ON m.id = s.${i.identifier(Le)}`;I.length>0&&(L=i`${L} WHERE ${i.join(I,i` AND `)}`),L=i`${L} ORDER BY s.${i.identifier("__score__")} DESC, m._creationTime DESC, m.id ASC LIMIT ${i.raw(String(a))}`;const N=[];for(const q of O(o,L)){const _=Qt(q);if(_){const F=q.__score__;N.push({document:_,score:typeof F=="number"?F:Number(F??0)})}}return N},Ao=(o,r,t,a,d)=>{const w=st(t.definition.language),S=at(t.query,w);if(S.length===0)return[];const T=en(t,d);let y=i`SELECT id, _creationTime, ${i.identifier(oe)} FROM ${i.identifier(r)}`;T.length>0&&(y=i`${y} WHERE ${i.join(T,i` AND `)}`),y=i`${y} ORDER BY _creationTime DESC, id ASC LIMIT ${i.raw(String(To(a)))}`;const k=O(o,y).toArray(),g=[];for(const A of k){const I=Qt(A);if(!I)continue;const L=no($n(I,t.definition),S);L>0&&g.push({creationTime:typeof I._creationTime=="number"?I._creationTime:0,doc:I,id:typeof I._id=="string"?I._id:"",score:L})}return g.sort((A,I)=>I.score-A.score||I.creationTime-A.creationTime||A.id.localeCompare(I.id)),g.slice(0,a).map(A=>({document:A.doc,score:A.score}))},tt=(o,r,t,a)=>{if(!Number.isFinite(o.lat)||o.lat<-90||o.lat>90||!Number.isFinite(o.lng)||o.lng<-180||o.lng>180)throw new $("BAD_REQUEST",`geo index "${a}" on table "${t}": ${r} must have a finite lat in [-90, 90] and lng in [-180, 180]`)},Io=(o,r)=>{const t=o,a={near:(d,w)=>{if(t.within)throw new $("INTERNAL",`geo index "${t.indexName}" on table "${r}": call .near() or .within(), not both`);if(tt(d,".near() point",r,t.indexName),!Number.isFinite(w)||w<=0)throw new $("BAD_REQUEST",`geo index "${t.indexName}" on table "${r}": .near() radiusMeters must be a finite number > 0, got ${String(w)}`);return t.near={point:{lat:d.lat,lng:d.lng},radiusMeters:w},a},within:d=>{if(t.near)throw new $("INTERNAL",`geo index "${t.indexName}" on table "${r}": call .near() or .within(), not both`);if(tt(d.sw,".within() sw corner",r,t.indexName),tt(d.ne,".within() ne corner",r,t.indexName),d.sw.lat>d.ne.lat)throw new $("BAD_REQUEST",`geo index "${t.indexName}" on table "${r}": .within() corners are transposed (sw.lat > ne.lat)`);if(d.sw.lng>d.ne.lng)throw new $("BAD_REQUEST",`geo index "${t.indexName}" on table "${r}": .within() box crosses the antimeridian (sw.lng > ne.lng), which is not supported — split it into two boxes at ±180 and union the results`);return t.within={ne:{lat:d.ne.lat,lng:d.ne.lng},sw:{lat:d.sw.lat,lng:d.sw.lng}},a}};return a},Co=(o,r)=>{const t=o[r];if(t===null||typeof t!="object")return;const{lat:a,lng:d}=t;return typeof a=="number"&&typeof d=="number"?{lat:a,lng:d}:void 0},xo=(o,r)=>{const t=Co(o,r.definition.field);if(!t)return;const a=typeof o._creationTime=="number"?o._creationTime:0;if(r.near){const d=Fn(r.near.point,t);return d<=r.near.radiusMeters?{creationTime:a,distance:d}:void 0}return qn(t,r.within)?{creationTime:a,distance:0}:void 0},bo=(o,r,t,a)=>{if(!t.near&&!t.within)throw new $("INTERNAL",`geo index "${t.indexName}" on table "${r}": call .near(point, radius) or .within(box)`);const d=t.near?Ln(t.near.point,t.near.radiusMeters):kn(t.within),w=Mn(r,t.indexName),S=d.map(A=>i`(g.${i.identifier("__geohash__")} >= ${A} AND g.${i.identifier("__geohash__")} < ${`${A}{`})`),T=[i`(${i.join(S,i` OR `)})`];a&&T.push(a);const y=i`SELECT m.id, m._creationTime, m.${i.identifier(oe)} FROM ${i.identifier(w)} g JOIN ${i.identifier(r)} m ON m.id = g.${i.identifier("__id__")} WHERE ${i.join(T,i` AND `)}`,k=O(o,y).toArray(),g=[];for(const A of k){const I=ue(A),L=I?xo(I,t):void 0;I&&L&&g.push({creationTime:L.creationTime,distance:L.distance,doc:I})}return g.sort((A,I)=>A.distance-I.distance||I.creationTime-A.creationTime),g},tn=(o,r,t,a)=>{const d=[];for(const w of o)if(r.every(S=>S(a(w)))&&(d.push(w),typeof t=="number"&&d.length>=t))break;return d},Mo=(o,r,t,a,d,w=()=>{})=>{const S=t.within!==void 0,T=bo(o,r,t,d).map(y=>({distanceMeters:S?null:y.distance,document:y.doc}));return w(T.length),typeof a=="number"?T.slice(0,Math.max(0,Math.floor(a))):T},nn=(o,r,t,a,d,w=()=>{})=>{const{geo:S}=t;if(!S)throw new $("INTERNAL","runGeoTerminalScored called without a staged geo query");const T=t.inMemoryFilters.length>0,y=Mo(o,r,S,T?void 0:d,a,w);return T?tn(y,t.inMemoryFilters,d,k=>k.document):y},on=(o,r,t,a)=>{const d=`SELECT id, _creationTime, ${Re(oe)} FROM ${Re(o)}`,w=`ORDER BY ${t}${a===void 0?"":` LIMIT ${String(a)}`}`;return r===void 0?Ue(`${d} ${w}`):Se(`${d} WHERE `,r,` ${w}`)},Do=(o,r,t,a,d,w=()=>{})=>nn(o,r,t,a,d,w).map(S=>S.document),Lo=(o,r,t,a,d,w,S=()=>{})=>{const T=[];for(const A of t.sqlConditions)T.push(i`${Z(A.field)} ${i.raw(A.comparator)} ${re(A.value)}`);a&&T.push(a);let y=i`SELECT id, _creationTime, ${i.identifier(oe)} FROM ${i.identifier(r)}`;T.length>0&&(y=i`${y} WHERE ${i.join(T,i` AND `)}`),y=i`${y} ORDER BY ${d}`,typeof w=="number"&&t.inMemoryFilters.length===0&&(y=i`${y} LIMIT ${i.raw(String(Math.max(0,Math.floor(w))))}`);const k=O(o,y).toArray();S(k.length);const g=[];for(const A of k){const I=ue(A);if(I&&t.inMemoryFilters.every(L=>L(I))&&(g.push(I),typeof w=="number"&&g.length>=w))break}return g},Ee={fieldRef:Z,serialize:re},rn=(o,r)=>{const t=r===void 0?void 0:o.shape[r];return t!==void 0&&Yn(t)},Wt=(o,r)=>r.some(t=>rn(o,t)),Pt=(o,r,t)=>{if(rn(o,r))throw new $("BAD_REQUEST",`${t}: "${r}" may hold an order-preserving key rather than a value SQL can reduce or group — declare an aggregateIndex covering this (by, field, op) so the maintained companion answers it instead (its running total is a REAL, so it stays exact only while the total is inside 2^53)`)},dt={fieldRef:o=>Ue(Pe(o)),serialize:re},ko=o=>{let r=0;const t=[],a={fieldRef:d=>Ue(Pe(d)),relationExists:d=>{const{childWhere:w,negated:S,parentTable:T,relation:y}=d,k=`__rel_${String(r)}`,g=t.at(-1)??T;r+=1,o(y.table,G);const A=y.kind==="one"?y.field:y.references,I=y.kind==="one"?y.references:y.field,L=Ue(`${Tt(k,I)} = ${Tt(g,A)}`);t.push(k);const N=ne(w,a,Ge);t.pop();const q=N===void 0?L:Se(L," AND ",N),_=Se("EXISTS (SELECT 1 FROM ",Dt(y.table)," AS ",Dt(k)," WHERE ",q,")");return S?Se("NOT ",_):_},serialize:re};return a},sn=o=>{const r=o.map(t=>`${Pe(t.field)} ${t.direction==="desc"?"DESC":"ASC"}`);return o.some(t=>t.field==="_id"||t.field==="id")||r.push(`${Pe("id")} ${Xt(o)==="desc"?"DESC":"ASC"}`),r.join(", ")},Fo=o=>{const r=o.map(t=>i`${Z(t.field)} ${i.raw(t.direction==="desc"?"DESC":"ASC")}`);return o.some(t=>t.field==="_id"||t.field==="id")||r.push(i`${Z("id")} ${i.raw(Xt(o)==="desc"?"DESC":"ASC")}`),i.join(r,i`, `)},qo={"<":"lt","<=":"lte","=":"eq",">":"gt",">=":"gte"},cn=o=>new Set(o.sqlConditions.filter(r=>r.comparator==="=").map(r=>r.field)),Bo=o=>{const r=cn(o);let t=0;for(;t<o.indexFields.length&&r.has(o.indexFields[t]??"");)t+=1;return o.indexFields.slice(t)},an=(o,r)=>{const t=o.order,a=Bo(o),{shape:d}=r;return a.length>0?nt(a.map(w=>({[w]:t})),d,{pinned:cn(o),uniqueBy:Jt(r.indexes,d)}):nt([{_creationTime:t}],d)},Wo=(o,r,t,a)=>{const d=o.sqlConditions.map(w=>({[w.field]:{[qo[w.comparator]??"eq"]:w.value}}));if(t&&d.push(Yt(r,ot(t))),a&&d.push(Pn(r,ot(a))),d.length!==0)return d.length===1?d[0]:{AND:d}},Po=(o,r,t)=>{const a=[];for(const d of o){const w=ue(d);if(w&&r.every(S=>S(w))&&(a.push(w),t!==void 0&&a.length>t))break}return a},Uo=(o,r,t,a,d,w,S=()=>{})=>{const T=Math.max(0,Math.floor(d.numItems)),y=an(a,t),k=typeof d.endCursor=="string",g=ne(Wo(a,y,d.cursor,d.endCursor),dt,Ge),A=w&&g?Se(g," AND ",w):w??g,I=a.inMemoryFilters.length>0,L=on(r,A,sn(y),I||k?void 0:T+1),N=_e(o,L.text,...L.params).toArray();S(N.length);const q=Po(N,a.inMemoryFilters,I||k?void 0:T);if(k){const H=q.length>=2?q[Math.floor(q.length/2)-1]:void 0;return{continueCursor:d.endCursor??null,isDone:!0,page:q,splitCursor:H?rt(H,y):null}}const _=q.length>T,F=_?q.slice(0,T):q,j=F.at(-1);return{continueCursor:_&&j?rt(j,y):null,isDone:!_,page:F}};class Go extends ${constructor(r="unique() found more than one matching document"){super("NOT_UNIQUE",r,{name:"NotUniqueError"})}}const Ho=/\s/u,Oo=String.fromCodePoint(0),Ut=(o,r,t)=>{if(!o.tables[r])throw new $("INTERNAL",`unknown table: ${r}`);return typeof t!="string"||t.length===0||Ho.test(t)||t.includes(Oo)?null:t},No=(o,r,t,a=()=>{},d=()=>{},w=()=>{})=>{const S=r.tables[t];if(!S)throw new $("INTERNAL",`unknown table: ${t}`);const T=le(S.softDeleteMode,void 0),y=T?ne(T,Ee):void 0,k=T?ne(T,dt,Ge):void 0,g={indexFields:[],indexName:void 0,inMemoryFilters:[],order:"asc",sqlConditions:[]};let A=0;const I=E=>{const{search:x}=g;if(!x)throw new $("INTERNAL","runSearchFetch called without a staged search");Tn(o,t,S);const b=g.inMemoryFilters.length>0,D=fo(b?void 0:E),z=bn(o);if(z&&!vn(o,t,x.definition))throw new $("SEARCH_INDEX_BUILDING",`search index "${x.indexName}" on table "${t}" is still backfilling and currently covers only part of the table — retry once it finishes, or run the backfillSearch admin operation to complete it now`);const X=z?vo(o,t,x,D,y):Ao(o,t,x,D,y);return b?(A=X.length,tn(X,g.inMemoryFilters,E,ce=>ce.document)):(E===void 0&&io(X),X)},L=E=>I(E).map(x=>x.document),N=E=>{const x=lo(E);return uo(L(so(x)),x)},q=()=>Fo(an(g,S)),_=()=>{if(g.search||g.geo||g.indexName===void 0){d(void 0);return}d(jn(t,g.indexName,g.indexFields,g.sqlConditions,re))},F=E=>{_();let x=0;const b=(()=>{if(g.search){const D=L(E);return x=A,D}return g.geo?Do(o,t,g,y,E,D=>{x=D}):Lo(o,t,g,y,q(),E,D=>{x=D})})();return w(Math.max(x,b.length)),b},j=()=>{if(!g.search&&!g.geo)throw new $("INTERNAL",`ctx.db.query("${t}").collectWithScores() requires a staged .withSearchIndex(...) or .withGeoIndex(...)`);_();let E=0;const x=(()=>{if(g.search){const b=I(void 0);return E=A,b}return nn(o,t,g,y,void 0,b=>{E=b})})();return w(Math.max(E,x.length)),x},H={async*[Symbol.asyncIterator](){if(g.search){yield*F(void 0);return}const E=[...g.inMemoryFilters];let x;g.inMemoryFilters=[];try{for(;;){const b=await H.paginate({cursor:x??null,numItems:_o});for(const D of b.page)E.every(z=>z(D))&&(yield D);if(b.isDone||b.continueCursor===null)return;x=b.continueCursor}}finally{g.inMemoryFilters=E}},async collect(){return F(void 0)},async collectWithScores(){return j()},filter(E){return g.inMemoryFilters.push(E),H},async first(){return F(g.inMemoryFilters.length>0?void 0:1)[0]??null},order(E){return g.order=E==="desc"?"desc":"asc",H},async paginate(E){let x=0;if(_(),g.search){const D=N(E);return w(D.page.length),D}if(g.geo)throw new $("INTERNAL","pagination is not supported on geo queries; use .take(n) or .collect()");const b=Uo(o,t,S,g,E,k,D=>{x=D});return w(Math.max(x,b.page.length)),b},async take(E){return F(E)},async unique(){const E=F(g.inMemoryFilters.length>0?void 0:2);if(E.length>1)throw new Go(`unique() on table "${t}" matched ${String(E.length)} documents; expected at most one`);return E[0]??null},withGeoIndex(E,x){const b=(S.geoIndexes??[]).find(z=>z.name===E);if(!b)throw new $("INTERNAL",`unknown geo index "${E}" on table "${t}"`);a(t,E,"geo");const D={definition:b,indexName:E};if(g.geo=D,x(Io(D,t)),!D.near&&!D.within)throw new $("INTERNAL",`geo index "${E}" on table "${t}" requires a .near(point, radius) or .within(box) call`);return H},withIndex(E,x){const b=S.indexes.find(D=>D.name===E);if(!b)throw new $("INTERNAL",`unknown index "${E}" on table "${t}"`);return a(t,E,"index"),g.indexName=E,g.indexFields=b.fields,x&&x(Ro(g)),H},withSearchIndex(E,x){const b=(S.searchIndexes??[]).find(z=>z.name===E);if(!b)throw new $("INTERNAL",`unknown search index "${E}" on table "${t}"`);a(t,E,"search");const D={definition:b,field:b.field,filters:[],hasQuery:!1,indexName:E,query:""};if(g.search=D,x(ro(D,t,st(b.language))),!D.hasQuery)throw new $("INTERNAL",`search index "${E}" on table "${t}" requires a .search(field, query) call`);return H}};return H},Gt=(o,r,t)=>{const a={...r};for(const[d,w]of Kt(o)){if(w.serverDefault){a[d]=w.serverDefault({auth:t});continue}a[d]===void 0&&(w.defaultFn?a[d]=w.defaultFn():"defaultValue"in w&&(a[d]=w.defaultValue))}return a},Ht=(o,r,t,a)=>{const d=t;for(const[w,S]of Kt(o)){if(S.serverDefault){w in r&&(d[w]=S.serverDefault({auth:a}));continue}S.onUpdateFn&&!(w in r)&&(d[w]=S.onUpdateFn())}},Ot=(o,r)=>{for(const t of Object.keys(r))if(r[t]===void 0)throw new $("INTERNAL",`Cannot ${o} field '${t}' to undefined — use null to clear a nullable field, or omit the key to leave it unchanged.`)},Nt=["_commitSeq","_creationTime","_id"],jo=o=>Nt.some(r=>r in o)?Object.fromEntries(Object.entries(o).filter(([r])=>!Nt.includes(r))):o,Ko=/unique constraint failed/i,Qo=o=>o instanceof Error&&Ko.test(o.message),Vo=/string or blob too big/iu,zo=(o,r)=>{if(!(!(o instanceof Error)||!Vo.test(o.message)))throw new $("PAYLOAD_TOO_LARGE",`document is too large to store in "${r}": a single row cannot exceed the storage engine's per-row ceiling (2 MB on a Durable Object's SQLite). The limit is on the STORED bytes, which are UTF-8, and v.bytes()/v.bigint() columns are stored twice on a shard-local table. Keep the payload in R2 (ctx.storage) and store a reference on the row.`)},it=(o,r,t,a)=>{try{_e(o,t,...a)}catch(d){throw Qo(d)?new me(`unique constraint violation on "${r}"`,"unique"):(zo(d,r),d)}},We=(o,r,t,a)=>{if(it(o,r,t,a),_e(o,go).one().changed===0)throw new me(`optimistic concurrency conflict on "${r}" — the row changed during this mutation; refetch and retry`,"occ")},jt=(o,r,t,a,d,w,S)=>{const T=[];for(let A=0;A<t.length+1;A+=1){const I=t[A],L=a[A],N=L?.direction==="desc"?"desc":"asc",q=I===void 0||L===void 0?i`${i.identifier(Hn)} < ${S}`:On(I,w[A],N,!1);if(q===void 0)continue;const _=[];for(let j=0;j<A;j+=1)_.push(i`${i.identifier(t[j])} IS ${w[j]}`);_.push(q);const[F]=_;T.push(_.length===1&&F!==void 0?F:i`(${i.join(_,i` AND `)})`)}const y=T.length>0?i.join(T,i` OR `):i`1 = 0`,k=O(o,i`SELECT COUNT(*) AS c FROM ${i.identifier(r)} WHERE ${i.identifier("__partition__")} = ${d} AND (${y})`).one(),g=O(o,i`SELECT COUNT(*) AS c FROM ${i.identifier(r)} WHERE ${i.identifier("__partition__")} = ${d}`).one();return{before:k.c,total:g.c}},br=o=>{const{sql:r}=o,{schema:t}=o,a=o.broadcast??(()=>{}),d=Kn(t);let w;const S=()=>o.inTransaction?.()===!0,T=e=>t.tables[e]?.commitOrderedMode!==!0?{}:((w===void 0||!S())&&(w=In(r)),{[Cn]:w}),y=(e,...n)=>{const s=t.tables[e]?.indexes;if(!s||s.length===0)return;const f=[];for(const h of n)h&&f.push(...Nn(s,h,re));return f.length>0?f:void 0},{headroom:k}=o;let g=!1;const A=async e=>{const n=g;g=!0;try{return await e()}finally{g=n}},I=o.onRead??(()=>{}),L=e=>{_t(t.tables[e])&&I(Ct,Ct)},N=o.onReadRange??(e=>{I(e.table,G)}),q=e=>{L(e.table),N(e)},_=(e,n)=>{n!==void 0&&n!==G&&!g&&k?.recordRead(1),L(e),I(e,n)},F=o.onIndexUse??(()=>{}),j=o.onWrite??(()=>{}),H=e=>{g||k?.recordWrite(e)},E=async e=>{H(e.doc),await j(e)},{cache:x}=o,b=o.clock??(()=>Date.now()),D=o.idGenerator??(()=>crypto.randomUUID()),z=o.scheduler??En,{globalDb:X}=o,ce=o.auth??{identity:null,userId:null},dn=o.cdc??!1,Oe=z,ln=Xn({scheduler:typeof Oe.list=="function"&&typeof Oe.get=="function"?Oe:void 0,storage:o.storage}),he=(e,n,s,f)=>{dn&&!_t(t.tables[e])&&An(r,b(),e,n,s,f)},ie=e=>t.tables[e]?.shardMode?.kind==="global",lt=(e,n)=>{if(ie(e)){if(!X)throw new $("INTERNAL",`cross-backend ${n} for global table '${e}' requires a globalDb writer — pass one to createShardCtxDb({ globalDb })`);return X}return P},Ne=e=>lt(e,"cascade"),Q=(e,n)=>{if(ie(e)){if(!X)throw new $("INTERNAL",`${n} on global table '${e}' requires a globalDb writer — pass one to createShardCtxDb({ globalDb })`);return X}},ut=async(e,n,s,f,h)=>{h&&H(s);const u=await e.insert(n,s,f);return a({key:u,op:"insert",row:{...s,_id:u},table:n}),u},je=(e,n)=>lt(e,"relation load").findMany(e,n),ft=(e,n)=>(ie(e)&&_(e,G),je(e,n)),un=e=>!ie(e.table),ht=o.relationExistsPushDown??"auto",wt=ht!=="never",{maxRelationKeys:pt}=o,Te=(e,n,s)=>xt(e,{fetcher:ft,maxRelationKeys:pt,relationBaseWhere:s,schema:t,tableName:n}),gt=async(e,n,s,f)=>{const h=Q(e,"relation grouped count");if(h)return _(e,G),zn((W,C)=>h.count(W,C),e,n,s,f);const u=t.tables[e];if(!u)throw new $("INTERNAL",`unknown table: ${e}`);_(e,G);const c=le(u.softDeleteMode,void 0),l={[n]:{in:s}},p=V(V(l,f),c),v=await Te(p,e,void 0),m=ne(v,Ee),M=Z(n);let R=i`SELECT ${M} AS __fk__, COUNT(*) AS count FROM ${i.identifier(e)}`;m&&(R=i`${R} WHERE ${m}`),R=i`${R} GROUP BY ${M}`;const B=O(r,R).toArray();return new Map(B.map(W=>[W.__fk__,W.count]))};let ve=0;const $t=new Set;for(const[e,n]of Object.entries(t.tables))for(const s of Object.values(n.triggerMap??{}))$t.add(`${e} ${s.timing} ${s.op}`);const ee=(e,n,s)=>$t.has(`${e} ${n} ${s}`),te=async(e,n,s)=>{if(ve+=1,ve>Bt)throw ve-=1,new me(`trigger recursion exceeded ${String(Bt)} levels on "${s.table}" — check for a self-triggering write`,"trigger");try{await Zn({ctx:hn,event:s,op:n,schema:t,tableName:s.table,timing:e})}finally{ve-=1}},{ensureBackfilledForTable:we,ensureBackfilledIndex:Ke,ensureRankBackfilled:Qe,ensureRankBackfilledForTable:pe,syncAggregates:Ae,syncCompanionsForInsert:yt,syncGeo:Ie,syncRanks:ge,syncSearch:Ce}=pn({broadcast:a,indexKeysFor:(e,n)=>y(e,n),invalidateCache:(e,n,s)=>x?.invalidate(e,n,y(e,s)),recordCdc:he,schema:t,sql:r}),Et=(e,n,s)=>{const{shardMode:f}=n;if(f?.kind==="shardBy"&&!(f.field!==void 0&&(s.partitionBy??[]).includes(f.field)))throw Object.assign(new Error(`rank index "${s.name}" on "${e}" partitions across shards (shard key "${f.field??"?"}" is not in partitionBy) — a shard-local rank()/rankPage() would be wrong; roll it up through the Query Coordinator instead`),{code:"CROSS_SHARD_RANK_UNSUPPORTED",name:"LunoraError",status:400})},mt=e=>Object.entries(t.tables).filter(([,n])=>n.shardMode?.kind!=="global").map(([n])=>n).filter(n=>e===void 0||n===e),$e=e=>e===void 0||ie(e)?X:void 0,se=(e,n)=>{const s=mt(n);for(let f=0;f<s.length;f+=ye){const h=s.slice(f,f+ye),[u]=_e(r,yo(h),...Eo(e,h)).toArray();if(!u)continue;const c=u.__t__,l=ue(u);if(typeof c!="string"||!l)return;const p=u[oe];return{docJson:typeof p=="string"?p:ae(p??{}),row:l,tableName:c}}},fn=(e,n)=>{const s=[...new Set(e)],f=new Map;if(s.length===0)return f;const h=mt(n);for(let u=0;u<h.length;u+=ye){const c=h.slice(u,u+ye),l=Math.floor(ye/c.length),p=Dn(i`${i.identifier("id")}`,s,!1,l),v=c.map(m=>i`SELECT ${i.raw(`'${m.replaceAll("'","''")}'`)} AS __t__, id FROM ${i.identifier(m)} WHERE ${p}`);for(const m of O(r,ct(v))){const{id:M,__t__:R}=m;typeof R=="string"&&typeof M=="string"&&f.set(M,R)}}return f},St={assertRankPartitionLocal:Et,ensureRankBackfilled:Qe,onRead:_,rowToDocument:ue,schema:t,sql:r},P={system:ln,async aggregate(e,n){const s=Q(e,"aggregate");if(s)return _(e,G),s.aggregate(e,n);const f=t.tables[e];if(!f)throw new $("INTERNAL",`unknown table: ${e}`);if(ke(n.op),n.op==="count")return P.count(e,{baseWhere:n.baseWhere,relationBaseWhere:n.relationBaseWhere,restrictsCounts:n.restrictsCounts,where:n.where});if(!n.field)throw new $("INTERNAL",`aggregate(${e}, { op: "${n.op}" }): "field" is required for non-count reducers`);_(e,G);const h=le(f.softDeleteMode,void 0),u=V(V(n.baseWhere,n.where),h),c=await Te(u,e,n.relationBaseWhere),l=c!==u;if(f.aggregateIndexes&&!n.baseWhere&&!l&&(!h||Wt(f,[n.field]))){const W=Rn(f.aggregateIndexes,n.op,n.field,n.where);if(W){Ke(e,W.index);const C=ze(W.index.by??[],W.key),K=Ve(e,W.index.name),J=O(r,i`SELECT ${Fe} AS value, ${Xe} AS count FROM ${i.identifier(K)} WHERE ${qe} = ${C}`).toArray()[0];return Je(n.op,J)}}Pt(f,n.field,`aggregate(${e}, { op: "${n.op}", field: "${n.field}" })`);const p=ne(c,Ee),v=ke(n.op),m=Z(n.field);let M=i`SELECT ${i.raw(v)}(${m}) AS value FROM ${i.identifier(e)}`;p&&(M=i`${M} WHERE ${p}`);const B=O(r,M).toArray()[0]?.value;return B??null},asId(e,n){const s=Ut(t,e,n);if(s===null)throw new $("BAD_REQUEST",`asId("${e}", …): "${n}" is not a valid id for table "${e}"`,{status:400});return s},async count(e,n){const s=Q(e,"count");if(s)return _(e,G),s.count(e,n);const f=t.tables[e];if(!f)throw new $("INTERNAL",`unknown table: ${e}`);const h=mn(n);if(h.restrictsCounts)throw new Ye(e);_(e,G);const u=le(f.softDeleteMode,void 0),c=V(V(h.baseWhere,h.where),u),l=await Te(c,e,h.relationBaseWhere),p=l!==c;if(f.aggregateIndexes&&!h.baseWhere&&!p&&!u){const R=_n(f.aggregateIndexes,h.where);if(R){Ke(e,R.index);const B=ze(R.index.by??[],R.key),W=Ve(e,R.index.name),C=O(r,i`SELECT ${Fe} AS value FROM ${i.identifier(W)} WHERE ${qe} = ${B}`).toArray();return C[0]===void 0?0:C[0].value??0}}const v=ne(l,Ee);let m=i`SELECT COUNT(*) AS count FROM ${i.identifier(e)}`;return v&&(m=i`${m} WHERE ${v}`),O(r,m).one().count},async delete(e,n,s){const f=se(e,n);if(!f){const m=$e(n);m&&(H(void 0),await m.delete(e,n,s));return}const{docJson:h,row:u,tableName:c}=f,l=t.tables[c],p=s?.hard===!0,v=!p&&l?.softDeleteMode?l.softDeleteMode.field:void 0;if(!(v&&u[v]!==null&&u[v]!==void 0)){if(ee(c,"before","delete")&&await te("before","delete",{id:e,op:"delete",previous:u,table:c}),await Vn({deletedId:e,deletedReference:m=>u[m],findHolders:async(m,M,R)=>(await Ne(m).findMany(m,{includeDeleted:p,where:{[M]:R}})).page,onCascade:(m,M)=>Ne(m).delete(M,void 0,s),onRestrict:m=>{throw new me(m,"restrict")},onSetNull:(m,M,R)=>Ne(m).patch(M,{[R]:null}),schema:t,tableName:c}),we(c),pe(c),v){const m={...u,...T(c),[v]:b(),_id:e};We(r,c,Ft(c),[ae(m),e,h]),Ce(c,e,m,u),Ie(c,e,void 0),Ae(c,u,m),ge(c,e,u,void 0),x?.invalidate(c,e,y(c,u,m)),he(c,e,"update",m),a({indexKeys:y(c,u,m),key:e,op:"update",row:m,table:c}),ee(c,"after","delete")&&await te("after","delete",{id:e,op:"delete",previous:u,table:c}),await E({id:e,op:"delete",table:c});return}We(r,c,po(c),[e,h]),Ce(c,e,void 0),Ie(c,e,void 0),Ae(c,u,void 0),ge(c,e,u,void 0),x?.invalidate(c,e,y(c,u)),he(c,e,"delete"),a({indexKeys:y(c,u),key:e,op:"delete",table:c}),ee(c,"after","delete")&&await te("after","delete",{id:e,op:"delete",previous:u,table:c}),await E({id:e,op:"delete",table:c})}},async deleteAll(e,n){if(!t.tables[e])throw new $("INTERNAL",`unknown table: ${e}`);const s=Math.max(1,n?.chunkSize??Zt),f=n?.hard===void 0?void 0:{hard:n.hard},h=ie(e)?void 0:e;let u=0;return await A(async()=>{for(;;){const l=(await P.findMany(e,{limit:s})).page.map(p=>String(p._id));if(l.length===0)break;for(const p of l)await P.delete(p,h,f),u+=1;if(l.length<s)break}}),{deleted:u}},async deleteMany(e,n,s){de(e.length,n?.limit,"deleteMany");for(const f of e)await P.delete(f,s);return{deleted:e.length}},async deleteWhere(e,n,s){const u=(await(Q(e,"deleteWhere")??P).findMany(e,{where:n})).page.map(c=>String(c._id));if(de(u.length,s?.limit,"deleteWhere"),P.deleteMany===void 0)throw new $("INTERNAL",`ctx.db.${e}.deleteMany is unavailable: this writer has no batch delete`);return P.deleteMany(u,s)},async findFirst(e,n={}){return(await P.findMany(e,{...n,limit:1,omitContinueCursor:!0})).page[0]??null},async findFirstOrThrow(e,n={}){const s=await P.findFirst(e,n);if(s===null)throw new Bn(`findFirstOrThrow: no "${e}" document matched`);return s},async findMany(e,n={}){const s=Q(e,"findMany");if(s)return _(e,G),s.findMany(e,n);const f=t.tables[e];if(!f)throw new $("INTERNAL",`unknown table: ${e}`);const h=!n.where&&!n.baseWhere;h?_(e,G):_(e);const u=nt(n.orderBy,f.shape,{pinned:Wn(n.where),uniqueBy:Jt(f.indexes,f.shape)}),c=n.cursor?Yt(u,ot(n.cursor)):void 0;let l=V(n.baseWhere,n.where);l=V(l,le(f.softDeleteMode,n.includeDeleted)),l=await xt(l,{canPushExists:wt?un:void 0,existsPushMode:ht==="always"?"always":"auto",fetcher:ft,maxRelationKeys:pt,relationBaseWhere:n.relationBaseWhere,schema:t,tableName:e}),c&&(l=l?{AND:[l,c]}:c);const p=wt?ko(_):dt,v=ne(l,p,Ge),m=typeof n.limit=="number"?Math.max(0,Math.floor(n.limit)):void 0,M=on(e,v,sn(u),m===void 0?void 0:m+1),R=_e(r,M.text,...M.params).toArray();h&&!g&&k?.recordRead(R.length);const B=[];for(const J of R){const U=ue(J);U&&(B.push(U),!h&&typeof U._id=="string"&&_(e,U._id))}if(m===void 0)return n.with&&await bt({groupedCounter:gt,fetcher:je,parents:B,...Mt(n),schema:t,tableName:e,with:n.with}),{continueCursor:null,isDone:!0,page:vt(B,n.select,n.with)};const W=B.length>m,C=W?B.slice(0,m):B,K=C.at(-1);return n.with&&await bt({fetcher:je,groupedCounter:gt,parents:C,...Mt(n),schema:t,tableName:e,with:n.with}),{continueCursor:W&&K&&n.omitContinueCursor!==!0?rt(K,u):null,isDone:!W,page:vt(C,n.select,n.with)}},async get(e,n){const s=se(e,n);if(!s){const f=$e(n);return f?f.get(e,n):null}return _(s.tableName,e),s.row},async lookupById(e,n){const s=se(e,n);return s?(_(s.tableName,e),{row:s.row,tableName:s.tableName}):null},async groupBy(e,n){const s=Q(e,"groupBy");if(s)return _(e,G),s.groupBy(e,n);const f=t.tables[e];if(!f)throw new $("INTERNAL",`unknown table: ${e}`);_(e,G);const h=n.agg??{op:"count"};if(ke(h.op),h.op!=="count"&&!h.field)throw new $("INTERNAL",`groupBy(${e}, { agg: { op: "${h.op}" } }): "field" is required for non-count reducers`);const u=le(f.softDeleteMode,void 0),c=V(V(n.baseWhere,n.where),u),l=await Te(c,e,n.relationBaseWhere),p=l!==c,v=[...n.by,h.field];if(f.aggregateIndexes&&!n.baseWhere&&!p&&(!u||Wt(f,v))){const C=Sn(f.aggregateIndexes,h.op,h.field,n.by,n.where),K=C===void 0?0:Object.keys(C.partial).length,J=C?.index.by?.length??0;if(C&&(K===0||K===J)){Ke(e,C.index);const U=Ve(e,C.index.name),xe=Object.keys(C.partial),be=[];if(xe.length===(C.index.by??[]).length&&xe.length>0){const Me=ze(C.index.by??[],C.partial),De=O(r,i`SELECT ${Fe} AS value, ${Xe} AS count FROM ${i.identifier(U)} WHERE ${qe} = ${Me}`).toArray();return De.length>0&&be.push({key:{...C.partial},value:Je(h.op,De[0])}),be}const wn=O(r,i`SELECT ${qe} AS key, ${Fe} AS value, ${Xe} AS count FROM ${i.identifier(U)}`).toArray();for(const Me of wn){const De=yn(JSON.parse(Me.key));be.push({key:De,value:Je(h.op,Me)})}return be}}for(const C of v){if(C===void 0)continue;const K=C===h.field?`groupBy(${e}, { agg: { op: "${h.op}", field: "${C}" } })`:`groupBy(${e}, { by: [..."${C}"] })`;Pt(f,C,K)}const m=ne(l,Ee),M=n.by.map(C=>i`${Z(C)} AS ${i.identifier(C)}`);if(h.op==="count")M.push(i`COUNT(*) AS value`);else{const{field:C}=h;if(C===void 0)throw new $("INTERNAL",`groupBy(${e}, { agg: { op: "${h.op}" } }): "field" is required for non-count reducers`);M.push(i`${i.raw(ke(h.op))}(${Z(C)}) AS value`)}let R=i`SELECT ${i.join(M,i`, `)} FROM ${i.identifier(e)}`;m&&(R=i`${R} WHERE ${m}`),R=i`${R} GROUP BY ${i.join(n.by.map(C=>Z(C)),i`, `)}`;const B=O(r,R).toArray(),W=[];for(const C of B){const K={};for(const U of n.by)K[U]=xn(f.shape[U],C[U]??null);const{value:J}=C;W.push({key:K,value:J==null?null:Number(J)})}return W},async insert(e,n,s){const f=Q(e,"insert");if(f)return ut(f,e,n,s,!0);const h=t.tables[e];if(!h)throw new $("INTERNAL",`unknown table: ${e}`);const u=Gt(h,n,ce);et(h,u);let c;s?.clientId!==void 0?(So(s.clientId),c=s.clientId):s?.allowExplicitId&&typeof u._id=="string"?c=u._id:c=D();const l=s?.allowExplicitId&&typeof u._creationTime=="number"?u._creationTime:b(),p={...u,...T(e),_creationTime:l,_id:c};return ee(e,"before","insert")&&await te("before","insert",{doc:{...p},id:c,op:"insert",table:e}),we(e),pe(e),it(r,e,ho(e),[c,l,ae(p)]),yt(e,c,p),ee(e,"after","insert")&&await te("after","insert",{doc:p,id:c,op:"insert",table:e}),await E({doc:p,id:c,op:"insert",table:e}),c},async insertManyUnsafe(e,n,s){if(de(n.length,s?.limit,"insertManyUnsafe"),n.length===0)return[];const f=Q(e,"insert");if(f){const l=[];for(const p of n)H(p);for(const p of n){const v=await f.insert(e,p,{allowExplicitId:s?.allowExplicitId});a({key:v,op:"insert",row:{...p,_id:v},table:e}),l.push(v)}return l}const h=t.tables[e];if(!h)throw new $("INTERNAL",`unknown table: ${e}`);we(e),pe(e);const u=[];for(let l=0;l<n.length;l+=Be)u.push(T(e));const c=n.map((l,p)=>{const v=Gt(h,l,ce),m=s?.allowExplicitId===!0&&typeof v._id=="string"?v._id:D(),M=s?.allowExplicitId===!0&&typeof v._creationTime=="number"?v._creationTime:b(),R={...v,...u[Math.floor(p/Be)],_creationTime:M,_id:m};return{creationTime:M,document:R,id:m}});for(const l of c)H(l.document);for(let l=0;l<c.length;l+=Be){const p=i.join(c.slice(l,l+Be).map(m=>i`(${m.id}, ${m.creationTime}, ${ae(m.document)})`),i`, `),v=Vt("sqlite",i`INSERT INTO ${i.identifier(e)} (id, _creationTime, ${i.identifier(oe)}) VALUES ${p}`);it(r,e,v.sql,v.params)}for(const{document:l,id:p}of c)yt(e,p,l),await j({doc:l,id:p,op:"insert",table:e});return c.map(l=>l.id)},async insertMany(e,n,s){de(n.length,s?.limit,"insertMany");const f=s?.skipDuplicates===!0,h=[],u=Q(e,"insert");if(u)for(const l of n)H(l);const c=async l=>u?ut(u,e,l,void 0,!1):P.insert(e,l);for(const l of n)try{h.push(await c(l))}catch(p){if(f&&p instanceof me&&p.kind==="unique")h.push(null);else throw p}return h},normalizeId(e,n){return Ut(t,e,n)},async patch(e,n,s){const f=se(e,s);if(!f){const v=$e(s);if(v){H(n),await v.patch(e,n,s);return}throw new $("NOT_FOUND",`document not found: ${e}`)}const{docJson:h,row:u,tableName:c}=f,l=t.tables[c];if(!l)throw new $("INTERNAL",`unknown table: ${c}`);_(c,e),Ot("patch",n);const p={...u,...jo(n),...T(c),_id:e};Ht(l,n,p,ce),et(l,p,!0),ee(c,"before","update")&&await te("before","update",{doc:{...p},id:e,op:"update",previous:u,table:c}),we(c),pe(c),We(r,c,Ft(c),[ae(p),e,h]),Ce(c,e,p,u),Ie(c,e,p),Ae(c,u,p),ge(c,e,u,p),x?.invalidate(c,e,y(c,u,p)),he(c,e,"update",p),a({indexKeys:y(c,u,p),key:e,op:"update",row:p,table:c}),ee(c,"after","update")&&await te("after","update",{doc:p,id:e,op:"update",previous:u,table:c}),await E({doc:p,id:e,op:"update",table:c})},async patchMany(e,n,s){de(e.length,n?.limit,"patchMany");for(const f of e)await P.patch(f.id,f.patch,s);return{patched:e.length}},async patchWhere(e,n,s){const u=(await(Q(e,"patchWhere")??P).findMany(e,{where:n.where})).page.map(c=>({id:String(c._id),patch:n.patch}));if(de(u.length,s?.limit,"patchWhere"),P.patchMany===void 0)throw new $("INTERNAL",`ctx.db.${e}.patchMany is unavailable: this writer has no batch patch`);return await P.patchMany(u,s),{patched:u.length}},async related(e,n){return Qn(P,d,e,n)},relationEdges:d,query(e){const n=Q(e,"query");return n?(_(e,G),n.query(e)):No(r,t,e,F,s=>{s?q(s):_(e,G)},s=>{g||k?.recordRead(s)})},async rank(e,n,s){const f=Q(e,"rank");if(f)return _(e,G),f.rank(e,n,s);F(e,n,"rank");const h=t.tables[e];if(!h)throw new $("INTERNAL",`unknown table: ${e}`);const u=h.rankIndexes?.find(U=>U.name===n);if(!u)throw new $("INTERNAL",`unknown rankIndex "${n}" on table "${e}"`);if(Et(e,h,u),s.restrictsCounts)throw new Ye(e);_(e,G),Qe(e,u);const c=typeof s.row=="string"?s.row:s.row._id;if(!c)return null;const l=At(e,u.name),p=u.sortBy.map((U,xe)=>It(xe)),v=p.map(U=>Re(U)).join(", "),m=O(r,i`SELECT ${i.identifier("__partition__")}, ${i.raw(v)} FROM ${i.identifier(l)} WHERE ${i.identifier("__id__")} = ${c}`).toArray(),[M]=m;if(M===void 0)return null;let R=M.__partition__;const B=V(s.baseWhere,s.where);Ze(B,t,e,"rank");const W=Un(u,B);if(W){const U=Gn(u.partitionBy??[],W);if(U!==R)return null;R=U}const C=p.map(U=>M[U]),{before:K,total:J}=jt(r,l,p,u.sortBy,R,C,c);return{position:K+1,total:J}},async rankBefore(e,n,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=t.tables[e];if(!f)throw new $("INTERNAL",`unknown table: ${e}`);const h=f.rankIndexes?.find(p=>p.name===n);if(!h)throw new $("INTERNAL",`unknown rankIndex "${n}" on table "${e}"`);if(s.restrictsCounts)throw new Ye(e);_(e,G),Qe(e,h);const u=At(e,h.name),c=h.sortBy.map((p,v)=>It(v)),l=h.sortBy.map((p,v)=>re(s.sortValues[v]??null));return jt(r,u,c,h.sortBy,s.partitionKey,l,s.rowId)},async rankPage(e,n,s={}){Ze(V(s.baseWhere,s.where),t,e,"rankPage");const f=Q(e,"rankPage");if(f)return _(e,G),f.rankPage(e,n,s);F(e,n,"rank");const{continueCursor:h,hasMore:u,rows:c}=Rt(St,e,n,s);return{continueCursor:h,isDone:!u,page:c.map(l=>l.doc)}},async rankPageRows(e,n,s={}){Ze(V(s.baseWhere,s.where),t,e,"rankPage"),F(e,n,"rank");const{directions:f,hasMore:h,rows:u}=Rt(St,e,n,s);return{directions:f,hasMore:h,rows:u}},async restore(e,n){const s=se(e,n);if(!s){const u=$e(n);if(u?.restore){await u.restore(e,n);return}throw new $("NOT_FOUND",`document not found: ${e}`)}const f=t.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 P.patch(e,{[f]:null},n),h&&ge(s.tableName,e,void 0,s.row)},async replace(e,n,s,f){const h=se(e,s);if(!h){const B=$e(s);if(B){H(n),await B.replace(e,n,s,f);return}throw new $("NOT_FOUND",`document not found: ${e}`)}const{docJson:u,row:c,tableName:l}=h,p=t.tables[l];if(!p)throw new $("INTERNAL",`unknown table: ${l}`);Ot("replace",n);const v=f?.allowExplicitId&&typeof n._creationTime=="number"?n._creationTime:void 0,m=typeof c._creationTime=="number"?c._creationTime:void 0,M=v??m??b(),R={...n,...T(l),_creationTime:M,_id:e};Ht(p,n,R,ce),et(p,R),ee(l,"before","update")&&await te("before","update",{doc:{...R},id:e,op:"update",previous:c,table:l}),we(l),pe(l),We(r,l,wo(l),[M,ae(R),e,u]),Ce(l,e,R,c),Ie(l,e,R),Ae(l,c,R),ge(l,e,c,R),x?.invalidate(l,e,y(l,c,R)),he(l,e,"update",R),a({indexKeys:y(l,c,R),key:e,op:"update",row:R,table:l}),ee(l,"after","update")&&await te("after","update",{doc:R,id:e,op:"update",previous:c,table:l}),await E({doc:R,id:e,op:"update",table:l})},async wipeShard(e){const n=new Set(e?.exclude),s=e?.tables,f=Object.entries(t.tables).filter(([l,p])=>n.has(l)||s!==void 0&&!s.includes(l)?!1:p.shardMode?.kind!=="global").map(([l])=>l);if(s!==void 0){for(const l of s)if(!t.tables[l])throw new $("INTERNAL",`wipeShard: unknown table: ${l}`)}const h={};let u=0;const{deleteAll:c}=P;if(c===void 0)throw new $("INTERNAL","wipeShard: this writer has no deleteAll");for(const l of f){const p=await c(l,{...e?.chunkSize===void 0?{}:{chunkSize:e.chunkSize},hard:!0});h[l]=p.deleted,u+=p.deleted}return{deleted:u,tables:h}}},hn={db:P,scheduler:z};return o.enforceRls===!0?Jn(P,t,(e,n)=>se(e,n)?.tableName,(e,n)=>fn(e,n),d):P};export{Br as CDC_LOG_TABLE,ei as CLIENT_WATERMARK_TABLE,ii as GLOBAL_SHAPE_SNAPSHOT_TABLE,fi as IDEMPOTENCY_TABLE,Go as NotUniqueError,Ei as SEARCH_STATE_TABLE,ti as advanceClientWatermark,Wr as applyCdcChanges,Ot as assertNoExplicitUndefined,So as assertValidClientId,Lr as backfillAggregateIndexes,kr as backfillRankIndexes,Fr as backfillSearchIndexes,Pr as bumpCdcEpoch,Ur as cdcCanVouchFor,Gr as cdcSeqLeavingRows,Hr as cdcTouchesTables,Or as cdcTrimmedError,Nr as compactCdcDocs,br as createShardCtxDb,jr as cursorBelowRetainedFloor,si as deleteGlobalShapeSnapshot,ci as deleteGlobalShapeSnapshotsForConnection,ni as migrateClientWatermark,ai as migrateGlobalShapeSnapshot,Kr as minCdcReplayableSeq,Qr as minCdcSeq,Ut as normalizeIdStructurally,Vr as readCdcChangeKeys,zr as readCdcChanges,Jr as readCdcCursor,Yr as readCdcEpoch,oi as readClientWatermark,di as readGlobalShapeSnapshot,hi as readIdempotent,$i as runShardMigrations,Si as selectShapeMembers,_i as selectShapeRows,jo as stripReservedPatchFields,Xr as trimCdcChanges,wi as trimIdempotent,li as writeGlobalShapeSnapshot,pi as writeIdempotent};
|
|
@@ -1,4 +0,0 @@
|
|
|
1
|
-
import{sql as s}from"drizzle-orm";import{runDrizzle as d}from"./runDrizzle-2ULFQR_k.mjs";const m=16,v=32,R=1e4,l=1e3,p=e=>String(e).padStart(m,"0"),u=e=>`cdc/${encodeURIComponent(e.shard)}/${encodeURIComponent(e.epoch)}/`,S=(e,o)=>`${u(e)}${p(o)}.json`,E="__cdc_archive",g=e=>{d(e,s`CREATE TABLE IF NOT EXISTS ${s.identifier(E)} (
|
|
2
|
-
id INTEGER PRIMARY KEY CHECK (id = 1),
|
|
3
|
-
seq INTEGER NOT NULL
|
|
4
|
-
)`)},L=e=>(g(e),d(e,s`SELECT seq FROM ${s.identifier(E)} WHERE id = 1`).toArray()[0]?.seq??0),$=(e,o)=>{g(e),d(e,s`INSERT INTO ${s.identifier(E)} (id, seq) VALUES (1, ${o}) ON CONFLICT (id) DO UPDATE SET seq = ${o}`)},q=async(e,o,t)=>{const n=t[0]?.seq,r=t.at(-1)?.seq;n===void 0||r===void 0||await e.put(S(o,r),JSON.stringify({changes:t,from:n,to:r}),{httpMetadata:{contentType:"application/json"}})},_=e=>{let o;try{o=JSON.parse(e)}catch{return}if(typeof o!="object"||o===null)return;const t=o;return typeof t.from=="number"&&typeof t.to=="number"&&Array.isArray(t.changes)?t:void 0},y=(e,o)=>{const t=[];for(const n of e.changes)if(!(n.seq<=o)){if(n.op!=="delete"&&n.doc===void 0)break;t.push(n)}return t},I=(e,o,t)=>{let n=t;for(const r of o){if(r.seq!==n+1)break;e.push(r),n=r.seq}return n},N=async(e,o)=>{const t=await e.get(o);return t===null?void 0:_(await t.text())},w=async(e,o,t,n)=>{const r=u(o),h=Math.max(1,Math.min(n??l,R)),A=await e.list({limit:v,prefix:r,startAfter:`${r}${p(t)}.json`}),c=[];let i=t;for(const C of A.objects){const a=await N(e,C.key);if(a===void 0)break;const T=y(a,i);if(i=I(c,T,i),c.length>=h||i!==a.to)break}if(c[0]?.seq!==t+1)return;const f=c.slice(0,h);return{changes:f,cursor:f.at(-1)?.seq??t}};export{q as archiveCdcSegment,w as readArchivedCdcChanges,L as readCdcArchivedThrough,$ as writeCdcArchivedThrough};
|
|
@@ -1,7 +0,0 @@
|
|
|
1
|
-
import{d as u,e as S}from"./wire-codec-C-FpWm52.mjs";import{cursorBelowRetainedFloor as y}from"./CDC_LOG_TABLE-vVheEulD.mjs";import{envPositiveInt as v}from"./envOptionalPositiveInt-D2pY-c64.mjs";import{v as A,R as g,s as N,a as E,b as T}from"./sibling-channel-BkL5cTCc.mjs";const L=["wnam","enam","sam","weur","eeur","apac","apac-ne","apac-se","oc","afr","me"],O=new Set(L),b=s=>typeof s=="string"&&O.has(s),h="::replica::",R=s=>{const e=s.lastIndexOf(h);if(e===-1)return;const t=s.slice(0,e),r=s.slice(e+h.length);if(!(t.length===0||!b(r)))return{ownerKey:t,region:r}},I=s=>{if(s==null||!/^\d+$/.test(s))return;const e=Number.parseInt(s,10);return Number.isSafeInteger(e)&&e>0?e:void 0},m=1e3,w=1e3,C=10,F=5e4,U=s=>v(s,"LUNORA_REPLICA_MAX_BOOTSTRAP_ROWS",F),d="__replica_state",l=new WeakSet,_=s=>{l.has(s)||(s.exec(`CREATE TABLE IF NOT EXISTS ${d} (
|
|
2
|
-
id INTEGER PRIMARY KEY CHECK (id = 1),
|
|
3
|
-
epoch TEXT NOT NULL,
|
|
4
|
-
applied_seq INTEGER NOT NULL,
|
|
5
|
-
synced_at REAL NOT NULL
|
|
6
|
-
)`),l.add(s))},c=s=>(_(s),s.exec(`SELECT epoch, applied_seq AS appliedSeq, synced_at AS syncedAtMs FROM ${d} WHERE id = 1`).toArray()[0]),f=(s,e)=>{_(s),s.exec(`INSERT INTO ${d} (id, epoch, applied_seq, synced_at) VALUES (1, ?, ?, ?)
|
|
7
|
-
ON CONFLICT(id) DO UPDATE SET epoch = excluded.epoch, applied_seq = excluded.applied_seq, synced_at = excluded.synced_at`,e.epoch,e.appliedSeq,e.syncedAtMs)},q=s=>{const e=s.doName();if(e!==void 0&&R(e)!==void 0)return new Response("replica cannot serve replicas",{status:409});if(s.ownerEpoch()===void 0)return new Response("shard has no changelog to replicate",{status:409});if(E(s.env())===void 0)return new Response("replica control requires LUNORA_RELAY_SECRET",{status:403})},a=s=>Response.json(S(s)),P=async(s,e)=>{if(s.rowCount()>U(s.env()))return a({cursor:0,epoch:e,rows:[],truncated:!0});const t=s.ownerCursor()??0,r=await s.exportRows();return a({cursor:t,epoch:e,rows:r})},x=(s,e,t)=>{const r=s.ownerFloor();if(y(r,t))return a({changes:[],cursor:s.ownerCursor()??t,epoch:e,floor:r});const{changes:i,cursor:n}=s.readChanges(t,w);return a({changes:i,cursor:n,epoch:e,...r===void 0?{}:{floor:r}})},K=async(s,e)=>{const t=q(s);if(t!==void 0)return t;const r=s.ownerEpoch();let i;try{i=await e.text()}catch{return new Response("bad request",{status:400})}if(!await A(s.env(),e.headers.get(g),i))return new Response("forbidden",{status:403});let n;try{n=JSON.parse(i)}catch{return new Response("bad request",{status:400})}if(n.type==="replica_bootstrap")return P(s,r);if(n.type==="replica_pull"){const o=typeof n.sinceSeq=="number"&&Number.isInteger(n.sinceSeq)&&n.sinceSeq>=0?n.sinceSeq:0;return x(s,r,o)}return new Response("unknown replica frame",{status:400})};class M{constructor(e,t,r){this.host=e,this.ownerKey=t,this.region=r}host;ownerKey;region;divergent=!1;inFlight;async ensureFresh(e){if(this.divergent)return"unavailable";if(this.isCaughtUp(e))return"fresh";this.inFlight??=this.advance(e).finally(()=>{this.inFlight=void 0});const t=await this.inFlight;return t==="fresh"&&!this.isCaughtUp(e)?"stale":t}appliedSeq(){return c(this.host.sql())?.appliedSeq??0}isDivergent(){return this.divergent}async advance(e){let t=c(this.host.sql());if(t===void 0){const r=await this.bootstrap();if(r===void 0)return"unavailable";t=r}return this.catchUp(t,e)}isCaughtUp(e){const t=c(this.host.sql());return t!==void 0&&this.isFreshEnough(t,e)}async catchUp(e,t){let r=e;for(let i=0;i<C;i+=1){const n=await this.pull(r.appliedSeq);if(n===void 0)return t===void 0&&this.isFreshEnough(r,void 0)?"fresh":"unavailable";if(this.hasDiverged(r,n))return"unavailable";const o=n.changes.length<w;if(r=await this.applyPage(n),o||this.isFreshEnough(r,t))return this.isFreshEnough(r,t)?"fresh":"stale"}return this.isFreshEnough(r,t)?"fresh":"stale"}async applyPage(e){e.changes.length>0&&await this.host.applyChanges(e.changes);const t={appliedSeq:e.cursor,epoch:e.epoch,syncedAtMs:Date.now()};return f(this.host.sql(),t),t}hasDiverged(e,t){const r=t.changes.length===0&&t.cursor>e.appliedSeq,i=t.floor??(r?t.cursor:0),n=i>0&&i>e.appliedSeq+1;return t.epoch===e.epoch&&!n?!1:(this.divergent=!0,!0)}async bootstrap(){const e=await this.request({type:"replica_bootstrap"});if(e===void 0)return;const t=u(await e.json());if(t.truncated===!0){this.divergent=!0;return}const{errors:r}=await this.host.importRows(t.rows);if(r.length>0){this.divergent=!0;return}const i={appliedSeq:t.cursor,epoch:t.epoch,syncedAtMs:Date.now()};return f(this.host.sql(),i),i}isFreshEnough(e,t){return t!==void 0?e.appliedSeq>=t:Date.now()-e.syncedAtMs<=v(this.host.env(),"LUNORA_REPLICA_MAX_STALENESS_MS",m)}async pull(e){const t=await this.request({sinceSeq:e,type:"replica_pull"});return t===void 0?void 0:u(await t.json())}async request(e){const t=this.host.shardBinding(),r=N(this.host.env(),t,this.ownerKey,this.host.shardJurisdiction());if(r===void 0)return;const i=JSON.stringify(e),n={"content-type":"application/json","x-lunora-shard-binding":t??""},o=E(this.host.env());o!==void 0&&(n[g]=await T(o,i));try{const p=await r.fetch("https://replica.internal/_lunora/replica",{body:i,headers:n,method:"POST"});return p.ok?p:void 0}catch{return}}}const j=s=>{const e=s.doName();if(e===void 0)return;const t=R(e);return t===void 0?void 0:new M(s,t.ownerKey,t.region)},G=async(s,e,t)=>{if(e.headers.get("x-lunora-replica-read")!=="1")return Response.json({error:{code:"REPLICA_READ_ONLY",message:`"${t}" is a write and cannot run on a read replica`}},{status:421});const r=await s.ensureFresh(I(e.headers.get("x-lunora-min-seq")));if(r!=="fresh")return Response.json({error:{code:"REPLICA_NOT_READY",message:`replica is ${r} for this read`}},{headers:{"x-lunora-replica-fallback":r},status:421})};export{j as createReplicaLink,G as gateReplicaDispatch,K as handleReplicaControl};
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{LunoraError as g}from"@lunora/errors";import{t as o}from"./base64-DfpzS4o_.mjs";const s=t=>{if(t.kind!=="optional")return t.kind;const n=t._meta?.inner;return n?s(n):t.kind},r=39,f="0",c="1",a=t=>Array.from(t,n=>String(9-Number(n))).join(""),d=t=>{const n=t<0n,e=(n?-t:t).toString();if(e.length>r)throw new g("BAD_REQUEST",`bigint ${t.toString()} has ${String(e.length)} digits, over the ${String(r)}-digit limit for a queryable column`);const i=e.padStart(r,"0");return n?f+a(i):c+i},l=/^\d+$/u,b=t=>{if(t.length!==r+1)return;const n=t.slice(0,1),e=t.slice(1);if(l.test(e))return n===c?BigInt(e):n===f?-BigInt(a(e)):void 0},u=/^[\da-f]{16}$/u,I=t=>{const n=new DataView(new ArrayBuffer(8));n.setFloat64(0,t===0?0:t,!1);let e=n.getUint32(0,!1),i=n.getUint32(4,!1);return(e&2147483648)===0?e=(e^2147483648)>>>0:(e=~e>>>0,i=~i>>>0),e.toString(16).padStart(8,"0")+i.toString(16).padStart(8,"0")},p=t=>{if(!u.test(t))return;let n=Number.parseInt(t.slice(0,8),16),e=Number.parseInt(t.slice(8),16);(n&2147483648)===0?(n=~n>>>0,e=~e>>>0):n=(n^2147483648)>>>0;const i=new DataView(new ArrayBuffer(8));return i.setUint32(0,n,!1),i.setUint32(4,e,!1),i.getFloat64(0,!1)},B=t=>typeof t=="bigint"?d(t):t instanceof ArrayBuffer?o(new Uint8Array(t)):ArrayBuffer.isView(t)?o(new Uint8Array(t.buffer,t.byteOffset,t.byteLength)):void 0,m=t=>{const n=s(t);return n==="bigint"||n==="bytes"},E=t=>{const n=s(t);return m(t)||n==="any"||n==="union"||n==="from"};export{r as B,p as a,d as b,b as d,s as e,I as f,m as i,E as m,B as s};
|