@lunora/shard-engine 1.0.0-alpha.82 → 1.0.0-alpha.84
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 +7 -1
- package/dist/index.d.ts +7 -1
- package/dist/index.mjs +1 -1
- package/dist/packem_shared/{ADMIN_FUNCTIONS-BdZ3gTHm.mjs → ADMIN_FUNCTIONS-5o1gzcJV.mjs} +1 -1
- package/dist/packem_shared/AGG_COUNT-B_w7MnCY.mjs +1 -0
- package/dist/packem_shared/BIGINT_KEY_DIGITS-C9a7Ix7k.mjs +1 -0
- package/dist/packem_shared/{CDC_LOG_TABLE-BFbP2eiJ.mjs → CDC_LOG_TABLE-C5XCNb2J.mjs} +1 -1
- package/dist/packem_shared/DEFAULT_MAX_RELATION_KEYS-fYrcrp5Z.mjs +1 -0
- package/dist/packem_shared/{DEFAULT_TRANSACTION_LIMITS-CTHQQgDC.mjs → DEFAULT_TRANSACTION_LIMITS-DiR5z5EX.mjs} +1 -1
- package/dist/packem_shared/NotUniqueError-2vJ9edyE.mjs +1 -0
- package/dist/packem_shared/{RANK_TIEBREAK-D5xNdzB3.mjs → RANK_TIEBREAK-B0_x8iev.mjs} +1 -1
- package/dist/packem_shared/{ReactiveCache-CU_NoCMR.mjs → ReactiveCache-D8ccaO6f.mjs} +1 -1
- package/dist/packem_shared/{VECTOR_BACKFILL_MAX_PAGES-C-KZJbgA.mjs → VECTOR_BACKFILL_MAX_PAGES-CWDvq1RK.mjs} +1 -1
- package/dist/packem_shared/{backfillAggregateIndexes-D-S4qiCu.mjs → backfillAggregateIndexes-yFyVVEHD.mjs} +1 -1
- package/dist/packem_shared/buildIndexRange-6nIZDf4m.mjs +1 -0
- package/dist/packem_shared/buildReprojectionMigration-DYjcBhki.mjs +1 -0
- package/dist/packem_shared/{buildShapeDiff-Bd5nLaY8.mjs → buildShapeDiff-BMe0ktEG.mjs} +1 -1
- package/dist/packem_shared/{computeRankPage-CQewnemg.mjs → computeRankPage-Bg1_6fPP.mjs} +1 -1
- package/dist/packem_shared/createCompanionSync-CGVFf7GK.mjs +1 -0
- package/dist/packem_shared/{createReplicaLink-CTyOjpjh.mjs → createReplicaLink-S5xtsySX.mjs} +1 -1
- package/dist/packem_shared/{defineEngineContractSuite-BD9v9a97.mjs → defineEngineContractSuite-Bi_xWgJR.mjs} +1 -1
- package/dist/packem_shared/do-sql-C7TkRQqw.mjs +1 -0
- package/dist/packem_shared/effective-kind-BmG_zCAy.mjs +1 -0
- package/dist/packem_shared/estimate-bytes-CTuiPWMD.mjs +1 -0
- package/dist/packem_shared/{isSoftDeleted-CCDHCtX3.mjs → isSoftDeleted-DDKwGeyk.mjs} +1 -1
- package/dist/packem_shared/{materializeExternalRows-j_8glxcE.mjs → materializeExternalRows-N-f9jaQE.mjs} +1 -1
- package/dist/packem_shared/{mergeChangedKeys-BA3YxaLE.mjs → mergeChangedKeys-DH9RAARR.mjs} +1 -1
- package/dist/packem_shared/relation-operators-BEg-CvCH.mjs +1 -0
- package/dist/packem_shared/{runShardMigrations-o-qjyKt5.mjs → runShardMigrations-HaS2tHTS.mjs} +1 -1
- package/dist/packem_shared/{selectExpiredIds-Do1q2HQr.mjs → selectExpiredIds-BuLDf-k0.mjs} +1 -1
- package/dist/packem_shared/{selectShapeMembers-Cp98I-ot.mjs → selectShapeMembers-CIfYJUcu.mjs} +1 -1
- package/dist/packem_shared/serializeSqlValue-BbZ5hKM7.mjs +1 -0
- package/dist/packem_shared/whereFilter-CLmm3TFe.mjs +1 -0
- package/package.json +2 -2
- package/dist/packem_shared/AGG_COUNT-B7izQELK.mjs +0 -1
- package/dist/packem_shared/BIGINT_KEY_DIGITS-Bnqj9CYQ.mjs +0 -1
- package/dist/packem_shared/DEFAULT_MAX_RELATION_KEYS-BfAQvZT8.mjs +0 -1
- package/dist/packem_shared/NotUniqueError-D0LwVtXI.mjs +0 -1
- package/dist/packem_shared/buildIndexRange-DvN8Qj8e.mjs +0 -1
- package/dist/packem_shared/buildReprojectionMigration-DDZhSO95.mjs +0 -1
- package/dist/packem_shared/createCompanionSync-BwWcSwvy.mjs +0 -1
- package/dist/packem_shared/do-sql-BSoH-O04.mjs +0 -1
- package/dist/packem_shared/estimate-bytes-DM1UZj_m.mjs +0 -1
- package/dist/packem_shared/serializeSqlValue-BEMMYX1n.mjs +0 -1
- package/dist/packem_shared/sql-projection-D3qdaItY.mjs +0 -1
|
@@ -1 +1 @@
|
|
|
1
|
-
import{defineEngineContractSuite as t}from"../packem_shared/defineEngineContractSuite-
|
|
1
|
+
import{defineEngineContractSuite as t}from"../packem_shared/defineEngineContractSuite-Bi_xWgJR.mjs";export{t as defineEngineContractSuite};
|
package/dist/index.d.mts
CHANGED
|
@@ -1961,6 +1961,12 @@ interface ReadFootprint {
|
|
|
1961
1961
|
declare const createReadFootprint: () => ReadFootprint;
|
|
1962
1962
|
declare const UNVOUCHABLE_DEP = "!unvouchable";
|
|
1963
1963
|
declare const markUnvouchableReads: <T extends object>(facade: T, onRead: ReadFootprint["onRead"] | undefined, methods: ReadonlyArray<string>) => T;
|
|
1964
|
+
declare const WHERE_FILTER: unique symbol;
|
|
1965
|
+
type RowPredicate = (document: Record<string, unknown>) => boolean;
|
|
1966
|
+
type WhereFilter = RowPredicate & {
|
|
1967
|
+
readonly [WHERE_FILTER]: WhereInput;
|
|
1968
|
+
};
|
|
1969
|
+
declare const whereFilter: (where: WhereInput, predicate: RowPredicate) => WhereFilter;
|
|
1964
1970
|
declare const RELATED_MAX_DEPTH = 4;
|
|
1965
1971
|
declare const RELATED_DEFAULT_LIMIT = 50;
|
|
1966
1972
|
declare const RELATED_MAX_LIMIT = 200;
|
|
@@ -2496,4 +2502,4 @@ interface WhereSqlStrategy<T = SQL> {
|
|
|
2496
2502
|
}
|
|
2497
2503
|
declare const literalInList: (reference: SQL, items: ReadonlyArray<unknown>, negated: boolean) => SQL;
|
|
2498
2504
|
declare const compileWhereSql: <T = SQL>(where: WhereInput | undefined, strategy: WhereSqlStrategy<T>, fragments?: WhereFragments<T>) => T | undefined;
|
|
2499
|
-
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 FtsWriteOptions, type FunctionCallStat, type FunctionScanAttribution, type FunctionStatsResult, GEO_DEFAULT_PRECISION, GLOBAL_SHAPE_SNAPSHOT_TABLE, type GeoBoundingBox, type GeoFilterBuilderLike, type GeoIndexDefinitionLike, type GeoPoint, type GeoScoredDocument, type GlobalPollCounters, GlobalPollTick, type GroupByEntry, type GroupByOptions, type GuardableSchema$1 as GuardableSchema, IDEMPOTENCY_TABLE, type IdGenerator, type IdempotentRecord, type ImportError, type ImportShardAdminArgs, type ImportShardArgs, type ImportShardResult, type IncrementalMaterializeResult, type IndexDefinitionLike, type IndexKeyEntry, type IndexRangeBuilderLike, type KeyRange, type LifecycleDispatchInfo, type LifecycleEvent, MAIL_RETENTION, MAIL_TABLE, MAX_DURABLE_STREAM_BYTES, MAX_DURABLE_STREAM_CHUNKS, MAX_PAGE_SIZE, MAX_SQL_ROWS, type MaskColumnMetadata, type MaskPoliciesResult, type MaterializeResult, type MigrationDirection, type MigrationRunResult, type MigrationStatus, type MigrationStatusRow, type MutationDelta, type NestedWith, NotFoundError, NotUniqueError, type OnDeleteActionLike, type OrderByClause, type OrderByInput, type OrderKey, type OrderKeyConstraints, OwnerRelay, type OwnerRelayFrame, type PaginationOptions, type PitrBookmarkResult, type PitrRestoreArgs, type PitrRestoreResult, type PitrStorage, type PokeFrameMeta, type PromotionState, type PromotionThresholds, QUEUE_TABLE, type QueryArgs, type QueryPage, type QueueMessageOutcome, type QueueMessageRow, type QueueMetadata, type QueuesResult, RANK_TIEBREAK, REACTOR_STATE_TABLE, RELATED_DEFAULT_LIMIT, RELATED_DEPTH_DECAY, RELATED_MAX_DEPTH, RELATED_MAX_LIMIT, RELATION_EXISTS_KEY, RELATION_FUNCTION_PREFIX, REPROJECTION_MIGRATION_PREFIX, RLS_UNWRAP_SYMBOL, type RankBeforeOptions, type RankBeforeResult, type RankDirection, type RankIndexDefinitionLike, type RankOptions, type RankPage, type RankPageComputation, type RankPageDeps, type RankPageOptions, type RankPageRow, type RankPageRowKey, type RankResult, type RankSortKeyLike, ReactiveCache, type ReactiveCacheOptions, type ReactorDispatchResult, type ReactorMetadata, type ReactorState, type ReactorStats, type ReactorsResult, type ReadFootprint, type ReadHook, type ReadTablePageOptions, type RecordMailInput, type RecordQueueMessageInput, type RelatedDirection, type RelatedNode, type RelatedOptions, type RelatedPage, type RelatedStart, type RelatedStartReference, type RelationDefinitionLike, type RelationEdge, type RelationExistsMarker, type RelationGraphReader, type RelayAttach, type RelayDetach, type RelayFrame, type RelayHost, RelayMember, type RelayPokeDelivery, type RelayShapePoke, type RelayShapeSeed, type RelayShapeSubscribe, type RelayShapeUnsubscribe, type RenderedSql, type ReplicaFollowerHost, type ReplicaOwnerHost, type ReplicaReadiness, type ResolveRelationPredicatesOptions, type ResolveWithOptions, type ResolveWithResult, type ResolvedShape, type RestrictableQueryOptions, type RlsPoliciesResult, type RlsPolicyMetadata, RlsRequiredError, type RlsRoleMetadata, type RpcRequest, type RunDataMigrationOptions, type RunTriggersOptions, SCAN_DEP, SCHEDULE_OUTBOX_TABLE, SCHEMA_HISTORY_MAX_VERSIONS, SEARCH_STATE_TABLE, SHAPE_POKE_CURSOR_TABLE, type SchedulableWorkflowReferenceLike, type ScheduleOutbox, type ScheduleOutboxEnvelope, type ScheduleOutboxRow, type ScheduledFunctionDoc, type SchedulerLike, type SchemaLike, type ScoredDocument, type SearchBackfillProgress, type SearchFilterBuilderLike, type SearchIndexDefinitionLike, type SearchScoredDocument, type SelectMatchingIdsOptions, type ServerDefaultContextLike, type SettingEntry, type SettingKind, type SettingsResult, ShapeDiffCache, type ShapePokeCursorRow, type ShapePokePart, type ShapeProbeCounters, type ShapeRow, type ShapeRowOp, type ShapeSubscriptionQuery, type ShardRankPageResult, ShardRunner, type ShardRunnerOptions, type ShardSiblingHost, type ShardSocketLike, type SocketAttachment, type SortDirection, type SourceClientLike, type SourceCursorLike, type SourceRefresh, type SqlConsoleResult, type SqlCursor, type SqlEngine, type SqlExec, type SqlLintResult, type StorageMetadata, type StorageReference, type StorageReferenceResult, type StorageRuleMetadata, type StorageRulesResult, type StudioFeaturesResult, type SubscriptionConnection, type SubscriptionEnvelope, type SubscriptionIdentity, type SubscriptionInfo, type SubscriptionQuery, type SubscriptionReadFootprint, type SubscriptionsResult, type SystemDatabaseReader, type SystemDoc, type SystemQuery, type SystemReaderOptions, type SystemReaderSchedulerLike, type SystemReaderStorageLike, type SystemTableName, type TableColumnsResult, type TableDefinitionLike, type TableIndexInfo, type TableIndexesResult, type TableInfo, type TablePage, type TableReaderLike, type TablesColumnsResult, type TablesIndexesResult, type TransactionHeadroom, TransactionHeadroomTracker, type TransactionLimits, type TransactionSqlLike, type TriggerContextLike, type TriggerDefinitionLike, type TriggerEventLike, type TriggerOpLike, type TriggerTimingLike, type TtlSweepSpec, UNVOUCHABLE_DEP, VECTOR_BACKFILL_MAX_PAGES, type ValidatorLike, type VectorBackfillProgress, type WhereInput, type WhereSqlStrategy, type WithInput, type WorkflowInstanceState, type WorkflowInstanceStatusResult, type WorkflowMetadata, type WorkflowsResult, type WriteEvent, type WriteHook, advanceClientWatermark, aggUpsertSql, aggregateSqlFunction, aggregateTableName, allocateCommitSeq, appendAuditEntry, appendCdcChange, appendStreamChunk, applyCdcChanges, applyOnDelete, applySelect, archiveCdcSegment, armRestore, assertFlatPredicate, assertNoExplicitUndefined, assertReadonly, assertShapeShardable, assertValidClientId, awaitWsDrain, backfillAggregateIndexes, backfillRankIndexes, backfillSearchIndexes, backfillSearchIndexesForTable, backfillVectorIndexes, bigintSqlKey, boundingBoxCenter, boundingBoxGeohashes, buildIndexRange, buildPokeFrames, buildReprojectionMigration, buildSeekBeforeWhere, buildSeekWhere, buildSettings, buildShapeDiff, bumpCdcEpoch, cdcArchiveRewound, cdcCanVouchFor, cdcForkedError, cdcSeqLeavingRows, cdcTouchesTables, cdcTrimmedError, claimStreamRun, clampPromotionThresholds, clearCapturedMail, clearMemoryTables, clearQueueMessages, coerceAggregateNumber, compactCdcDocs, compileWhereSql, computeRankPage, containsRelationPredicate, countLegacyRows, coveringGeohashes, createCompanionSync, createDependencyTracker, createFanoutCounters, createGlobalPollCounters, createIndexSql, createReadFootprint, createRelayLink, createReplicaLink, createShapeDiffCache, createShapeProbeCounters, createShardCtxDb, createSystemReader, cursorBelowRetainedFloor, decideDurableAttach, decodeBigintSqlKey, decodeCursor, decodeFloat64SqlKey, deferScheduleOutbox, deleteGlobalShapeSnapshot, deleteGlobalShapeSnapshotsForConnection, deleteShapePokeCursor, deleteShapePokeCursorsForConnection, deleteStreamRun, depKey, deriveRelationEdges, diffExternalSource, diffGlobalMembership, distinctValues, encodeAggregateKey, encodeCursor, encodeGeohash, encodePartitionKey, encodeRowsPatch, ensureAuditTable, ensureMailTable, envOptionalPositiveInt, envPositiveInt, equalityPinnedFields, exportShardRows, facetColumn, fanOutScalarCounts, findRelated, findStorageReferences, finishStreamRun, float64SqlKey, foldAggregateTally, forgetScheduleOutbox, ftsCompanionDdl, ftsPurgeDocument, ftsRowidMapName, ftsUnmappedPage, ftsWriteDocument, gateReplicaDispatch, geoTableName, globalShapeReadKey, groupUnmappedRows, guardWriter, handleReplicaControl, hasTrigger, haversineMeters, importShardRows, indexKeysForRow, isDevEnvironment, isFtsAvailable, 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 };
|
|
2505
|
+
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 FtsWriteOptions, type FunctionCallStat, type FunctionScanAttribution, type FunctionStatsResult, GEO_DEFAULT_PRECISION, GLOBAL_SHAPE_SNAPSHOT_TABLE, type GeoBoundingBox, type GeoFilterBuilderLike, type GeoIndexDefinitionLike, type GeoPoint, type GeoScoredDocument, type GlobalPollCounters, GlobalPollTick, type GroupByEntry, type GroupByOptions, type GuardableSchema$1 as GuardableSchema, IDEMPOTENCY_TABLE, type IdGenerator, type IdempotentRecord, type ImportError, type ImportShardAdminArgs, type ImportShardArgs, type ImportShardResult, type IncrementalMaterializeResult, type IndexDefinitionLike, type IndexKeyEntry, type IndexRangeBuilderLike, type KeyRange, type LifecycleDispatchInfo, type LifecycleEvent, MAIL_RETENTION, MAIL_TABLE, MAX_DURABLE_STREAM_BYTES, MAX_DURABLE_STREAM_CHUNKS, MAX_PAGE_SIZE, MAX_SQL_ROWS, type MaskColumnMetadata, type MaskPoliciesResult, type MaterializeResult, type MigrationDirection, type MigrationRunResult, type MigrationStatus, type MigrationStatusRow, type MutationDelta, type NestedWith, NotFoundError, NotUniqueError, type OnDeleteActionLike, type OrderByClause, type OrderByInput, type OrderKey, type OrderKeyConstraints, OwnerRelay, type OwnerRelayFrame, type PaginationOptions, type PitrBookmarkResult, type PitrRestoreArgs, type PitrRestoreResult, type PitrStorage, type PokeFrameMeta, type PromotionState, type PromotionThresholds, QUEUE_TABLE, type QueryArgs, type QueryPage, type QueueMessageOutcome, type QueueMessageRow, type QueueMetadata, type QueuesResult, RANK_TIEBREAK, REACTOR_STATE_TABLE, RELATED_DEFAULT_LIMIT, RELATED_DEPTH_DECAY, RELATED_MAX_DEPTH, RELATED_MAX_LIMIT, RELATION_EXISTS_KEY, RELATION_FUNCTION_PREFIX, REPROJECTION_MIGRATION_PREFIX, RLS_UNWRAP_SYMBOL, type RankBeforeOptions, type RankBeforeResult, type RankDirection, type RankIndexDefinitionLike, type RankOptions, type RankPage, type RankPageComputation, type RankPageDeps, type RankPageOptions, type RankPageRow, type RankPageRowKey, type RankResult, type RankSortKeyLike, ReactiveCache, type ReactiveCacheOptions, type ReactorDispatchResult, type ReactorMetadata, type ReactorState, type ReactorStats, type ReactorsResult, type ReadFootprint, type ReadHook, type ReadTablePageOptions, type RecordMailInput, type RecordQueueMessageInput, type RelatedDirection, type RelatedNode, type RelatedOptions, type RelatedPage, type RelatedStart, type RelatedStartReference, type RelationDefinitionLike, type RelationEdge, type RelationExistsMarker, type RelationGraphReader, type RelayAttach, type RelayDetach, type RelayFrame, type RelayHost, RelayMember, type RelayPokeDelivery, type RelayShapePoke, type RelayShapeSeed, type RelayShapeSubscribe, type RelayShapeUnsubscribe, type RenderedSql, type ReplicaFollowerHost, type ReplicaOwnerHost, type ReplicaReadiness, type ResolveRelationPredicatesOptions, type ResolveWithOptions, type ResolveWithResult, type ResolvedShape, type RestrictableQueryOptions, type RlsPoliciesResult, type RlsPolicyMetadata, RlsRequiredError, type RlsRoleMetadata, type RpcRequest, type RunDataMigrationOptions, type RunTriggersOptions, SCAN_DEP, SCHEDULE_OUTBOX_TABLE, SCHEMA_HISTORY_MAX_VERSIONS, SEARCH_STATE_TABLE, SHAPE_POKE_CURSOR_TABLE, type SchedulableWorkflowReferenceLike, type ScheduleOutbox, type ScheduleOutboxEnvelope, type ScheduleOutboxRow, type ScheduledFunctionDoc, type SchedulerLike, type SchemaLike, type ScoredDocument, type SearchBackfillProgress, type SearchFilterBuilderLike, type SearchIndexDefinitionLike, type SearchScoredDocument, type SelectMatchingIdsOptions, type ServerDefaultContextLike, type SettingEntry, type SettingKind, type SettingsResult, ShapeDiffCache, type ShapePokeCursorRow, type ShapePokePart, type ShapeProbeCounters, type ShapeRow, type ShapeRowOp, type ShapeSubscriptionQuery, type ShardRankPageResult, ShardRunner, type ShardRunnerOptions, type ShardSiblingHost, type ShardSocketLike, type SocketAttachment, type SortDirection, type SourceClientLike, type SourceCursorLike, type SourceRefresh, type SqlConsoleResult, type SqlCursor, type SqlEngine, type SqlExec, type SqlLintResult, type StorageMetadata, type StorageReference, type StorageReferenceResult, type StorageRuleMetadata, type StorageRulesResult, type StudioFeaturesResult, type SubscriptionConnection, type SubscriptionEnvelope, type SubscriptionIdentity, type SubscriptionInfo, type SubscriptionQuery, type SubscriptionReadFootprint, type SubscriptionsResult, type SystemDatabaseReader, type SystemDoc, type SystemQuery, type SystemReaderOptions, type SystemReaderSchedulerLike, type SystemReaderStorageLike, type SystemTableName, type TableColumnsResult, type TableDefinitionLike, type TableIndexInfo, type TableIndexesResult, type TableInfo, type TablePage, type TableReaderLike, type TablesColumnsResult, type TablesIndexesResult, type TransactionHeadroom, TransactionHeadroomTracker, type TransactionLimits, type TransactionSqlLike, type TriggerContextLike, type TriggerDefinitionLike, type TriggerEventLike, type TriggerOpLike, type TriggerTimingLike, type TtlSweepSpec, UNVOUCHABLE_DEP, VECTOR_BACKFILL_MAX_PAGES, type ValidatorLike, type VectorBackfillProgress, type WhereFilter, type WhereInput, type WhereSqlStrategy, type WithInput, type WorkflowInstanceState, type WorkflowInstanceStatusResult, type WorkflowMetadata, type WorkflowsResult, type WriteEvent, type WriteHook, advanceClientWatermark, aggUpsertSql, aggregateSqlFunction, aggregateTableName, allocateCommitSeq, appendAuditEntry, appendCdcChange, appendStreamChunk, applyCdcChanges, applyOnDelete, applySelect, archiveCdcSegment, armRestore, assertFlatPredicate, assertNoExplicitUndefined, assertReadonly, assertShapeShardable, assertValidClientId, awaitWsDrain, backfillAggregateIndexes, backfillRankIndexes, backfillSearchIndexes, backfillSearchIndexesForTable, backfillVectorIndexes, bigintSqlKey, boundingBoxCenter, boundingBoxGeohashes, buildIndexRange, buildPokeFrames, buildReprojectionMigration, buildSeekBeforeWhere, buildSeekWhere, buildSettings, buildShapeDiff, bumpCdcEpoch, cdcArchiveRewound, cdcCanVouchFor, cdcForkedError, cdcSeqLeavingRows, cdcTouchesTables, cdcTrimmedError, claimStreamRun, clampPromotionThresholds, clearCapturedMail, clearMemoryTables, clearQueueMessages, coerceAggregateNumber, compactCdcDocs, compileWhereSql, computeRankPage, containsRelationPredicate, countLegacyRows, coveringGeohashes, createCompanionSync, createDependencyTracker, createFanoutCounters, createGlobalPollCounters, createIndexSql, createReadFootprint, createRelayLink, createReplicaLink, createShapeDiffCache, createShapeProbeCounters, createShardCtxDb, createSystemReader, cursorBelowRetainedFloor, decideDurableAttach, decodeBigintSqlKey, decodeCursor, decodeFloat64SqlKey, deferScheduleOutbox, deleteGlobalShapeSnapshot, deleteGlobalShapeSnapshotsForConnection, deleteShapePokeCursor, deleteShapePokeCursorsForConnection, deleteStreamRun, depKey, deriveRelationEdges, diffExternalSource, diffGlobalMembership, distinctValues, encodeAggregateKey, encodeCursor, encodeGeohash, encodePartitionKey, encodeRowsPatch, ensureAuditTable, ensureMailTable, envOptionalPositiveInt, envPositiveInt, equalityPinnedFields, exportShardRows, facetColumn, fanOutScalarCounts, findRelated, findStorageReferences, finishStreamRun, float64SqlKey, foldAggregateTally, forgetScheduleOutbox, ftsCompanionDdl, ftsPurgeDocument, ftsRowidMapName, ftsUnmappedPage, ftsWriteDocument, gateReplicaDispatch, geoTableName, globalShapeReadKey, groupUnmappedRows, guardWriter, handleReplicaControl, hasTrigger, haversineMeters, importShardRows, indexKeysForRow, isDevEnvironment, isFtsAvailable, 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, whereFilter, writeCdcArchivedThrough, writeGlobalShapeSnapshot, writeIdempotent, writeReactorState, writeSearchBackfillState, writeShapePokeCursor, writeShapePokeCursors, writeTouchesMemo };
|
package/dist/index.d.ts
CHANGED
|
@@ -1961,6 +1961,12 @@ interface ReadFootprint {
|
|
|
1961
1961
|
declare const createReadFootprint: () => ReadFootprint;
|
|
1962
1962
|
declare const UNVOUCHABLE_DEP = "!unvouchable";
|
|
1963
1963
|
declare const markUnvouchableReads: <T extends object>(facade: T, onRead: ReadFootprint["onRead"] | undefined, methods: ReadonlyArray<string>) => T;
|
|
1964
|
+
declare const WHERE_FILTER: unique symbol;
|
|
1965
|
+
type RowPredicate = (document: Record<string, unknown>) => boolean;
|
|
1966
|
+
type WhereFilter = RowPredicate & {
|
|
1967
|
+
readonly [WHERE_FILTER]: WhereInput;
|
|
1968
|
+
};
|
|
1969
|
+
declare const whereFilter: (where: WhereInput, predicate: RowPredicate) => WhereFilter;
|
|
1964
1970
|
declare const RELATED_MAX_DEPTH = 4;
|
|
1965
1971
|
declare const RELATED_DEFAULT_LIMIT = 50;
|
|
1966
1972
|
declare const RELATED_MAX_LIMIT = 200;
|
|
@@ -2496,4 +2502,4 @@ interface WhereSqlStrategy<T = SQL> {
|
|
|
2496
2502
|
}
|
|
2497
2503
|
declare const literalInList: (reference: SQL, items: ReadonlyArray<unknown>, negated: boolean) => SQL;
|
|
2498
2504
|
declare const compileWhereSql: <T = SQL>(where: WhereInput | undefined, strategy: WhereSqlStrategy<T>, fragments?: WhereFragments<T>) => T | undefined;
|
|
2499
|
-
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 FtsWriteOptions, type FunctionCallStat, type FunctionScanAttribution, type FunctionStatsResult, GEO_DEFAULT_PRECISION, GLOBAL_SHAPE_SNAPSHOT_TABLE, type GeoBoundingBox, type GeoFilterBuilderLike, type GeoIndexDefinitionLike, type GeoPoint, type GeoScoredDocument, type GlobalPollCounters, GlobalPollTick, type GroupByEntry, type GroupByOptions, type GuardableSchema$1 as GuardableSchema, IDEMPOTENCY_TABLE, type IdGenerator, type IdempotentRecord, type ImportError, type ImportShardAdminArgs, type ImportShardArgs, type ImportShardResult, type IncrementalMaterializeResult, type IndexDefinitionLike, type IndexKeyEntry, type IndexRangeBuilderLike, type KeyRange, type LifecycleDispatchInfo, type LifecycleEvent, MAIL_RETENTION, MAIL_TABLE, MAX_DURABLE_STREAM_BYTES, MAX_DURABLE_STREAM_CHUNKS, MAX_PAGE_SIZE, MAX_SQL_ROWS, type MaskColumnMetadata, type MaskPoliciesResult, type MaterializeResult, type MigrationDirection, type MigrationRunResult, type MigrationStatus, type MigrationStatusRow, type MutationDelta, type NestedWith, NotFoundError, NotUniqueError, type OnDeleteActionLike, type OrderByClause, type OrderByInput, type OrderKey, type OrderKeyConstraints, OwnerRelay, type OwnerRelayFrame, type PaginationOptions, type PitrBookmarkResult, type PitrRestoreArgs, type PitrRestoreResult, type PitrStorage, type PokeFrameMeta, type PromotionState, type PromotionThresholds, QUEUE_TABLE, type QueryArgs, type QueryPage, type QueueMessageOutcome, type QueueMessageRow, type QueueMetadata, type QueuesResult, RANK_TIEBREAK, REACTOR_STATE_TABLE, RELATED_DEFAULT_LIMIT, RELATED_DEPTH_DECAY, RELATED_MAX_DEPTH, RELATED_MAX_LIMIT, RELATION_EXISTS_KEY, RELATION_FUNCTION_PREFIX, REPROJECTION_MIGRATION_PREFIX, RLS_UNWRAP_SYMBOL, type RankBeforeOptions, type RankBeforeResult, type RankDirection, type RankIndexDefinitionLike, type RankOptions, type RankPage, type RankPageComputation, type RankPageDeps, type RankPageOptions, type RankPageRow, type RankPageRowKey, type RankResult, type RankSortKeyLike, ReactiveCache, type ReactiveCacheOptions, type ReactorDispatchResult, type ReactorMetadata, type ReactorState, type ReactorStats, type ReactorsResult, type ReadFootprint, type ReadHook, type ReadTablePageOptions, type RecordMailInput, type RecordQueueMessageInput, type RelatedDirection, type RelatedNode, type RelatedOptions, type RelatedPage, type RelatedStart, type RelatedStartReference, type RelationDefinitionLike, type RelationEdge, type RelationExistsMarker, type RelationGraphReader, type RelayAttach, type RelayDetach, type RelayFrame, type RelayHost, RelayMember, type RelayPokeDelivery, type RelayShapePoke, type RelayShapeSeed, type RelayShapeSubscribe, type RelayShapeUnsubscribe, type RenderedSql, type ReplicaFollowerHost, type ReplicaOwnerHost, type ReplicaReadiness, type ResolveRelationPredicatesOptions, type ResolveWithOptions, type ResolveWithResult, type ResolvedShape, type RestrictableQueryOptions, type RlsPoliciesResult, type RlsPolicyMetadata, RlsRequiredError, type RlsRoleMetadata, type RpcRequest, type RunDataMigrationOptions, type RunTriggersOptions, SCAN_DEP, SCHEDULE_OUTBOX_TABLE, SCHEMA_HISTORY_MAX_VERSIONS, SEARCH_STATE_TABLE, SHAPE_POKE_CURSOR_TABLE, type SchedulableWorkflowReferenceLike, type ScheduleOutbox, type ScheduleOutboxEnvelope, type ScheduleOutboxRow, type ScheduledFunctionDoc, type SchedulerLike, type SchemaLike, type ScoredDocument, type SearchBackfillProgress, type SearchFilterBuilderLike, type SearchIndexDefinitionLike, type SearchScoredDocument, type SelectMatchingIdsOptions, type ServerDefaultContextLike, type SettingEntry, type SettingKind, type SettingsResult, ShapeDiffCache, type ShapePokeCursorRow, type ShapePokePart, type ShapeProbeCounters, type ShapeRow, type ShapeRowOp, type ShapeSubscriptionQuery, type ShardRankPageResult, ShardRunner, type ShardRunnerOptions, type ShardSiblingHost, type ShardSocketLike, type SocketAttachment, type SortDirection, type SourceClientLike, type SourceCursorLike, type SourceRefresh, type SqlConsoleResult, type SqlCursor, type SqlEngine, type SqlExec, type SqlLintResult, type StorageMetadata, type StorageReference, type StorageReferenceResult, type StorageRuleMetadata, type StorageRulesResult, type StudioFeaturesResult, type SubscriptionConnection, type SubscriptionEnvelope, type SubscriptionIdentity, type SubscriptionInfo, type SubscriptionQuery, type SubscriptionReadFootprint, type SubscriptionsResult, type SystemDatabaseReader, type SystemDoc, type SystemQuery, type SystemReaderOptions, type SystemReaderSchedulerLike, type SystemReaderStorageLike, type SystemTableName, type TableColumnsResult, type TableDefinitionLike, type TableIndexInfo, type TableIndexesResult, type TableInfo, type TablePage, type TableReaderLike, type TablesColumnsResult, type TablesIndexesResult, type TransactionHeadroom, TransactionHeadroomTracker, type TransactionLimits, type TransactionSqlLike, type TriggerContextLike, type TriggerDefinitionLike, type TriggerEventLike, type TriggerOpLike, type TriggerTimingLike, type TtlSweepSpec, UNVOUCHABLE_DEP, VECTOR_BACKFILL_MAX_PAGES, type ValidatorLike, type VectorBackfillProgress, type WhereInput, type WhereSqlStrategy, type WithInput, type WorkflowInstanceState, type WorkflowInstanceStatusResult, type WorkflowMetadata, type WorkflowsResult, type WriteEvent, type WriteHook, advanceClientWatermark, aggUpsertSql, aggregateSqlFunction, aggregateTableName, allocateCommitSeq, appendAuditEntry, appendCdcChange, appendStreamChunk, applyCdcChanges, applyOnDelete, applySelect, archiveCdcSegment, armRestore, assertFlatPredicate, assertNoExplicitUndefined, assertReadonly, assertShapeShardable, assertValidClientId, awaitWsDrain, backfillAggregateIndexes, backfillRankIndexes, backfillSearchIndexes, backfillSearchIndexesForTable, backfillVectorIndexes, bigintSqlKey, boundingBoxCenter, boundingBoxGeohashes, buildIndexRange, buildPokeFrames, buildReprojectionMigration, buildSeekBeforeWhere, buildSeekWhere, buildSettings, buildShapeDiff, bumpCdcEpoch, cdcArchiveRewound, cdcCanVouchFor, cdcForkedError, cdcSeqLeavingRows, cdcTouchesTables, cdcTrimmedError, claimStreamRun, clampPromotionThresholds, clearCapturedMail, clearMemoryTables, clearQueueMessages, coerceAggregateNumber, compactCdcDocs, compileWhereSql, computeRankPage, containsRelationPredicate, countLegacyRows, coveringGeohashes, createCompanionSync, createDependencyTracker, createFanoutCounters, createGlobalPollCounters, createIndexSql, createReadFootprint, createRelayLink, createReplicaLink, createShapeDiffCache, createShapeProbeCounters, createShardCtxDb, createSystemReader, cursorBelowRetainedFloor, decideDurableAttach, decodeBigintSqlKey, decodeCursor, decodeFloat64SqlKey, deferScheduleOutbox, deleteGlobalShapeSnapshot, deleteGlobalShapeSnapshotsForConnection, deleteShapePokeCursor, deleteShapePokeCursorsForConnection, deleteStreamRun, depKey, deriveRelationEdges, diffExternalSource, diffGlobalMembership, distinctValues, encodeAggregateKey, encodeCursor, encodeGeohash, encodePartitionKey, encodeRowsPatch, ensureAuditTable, ensureMailTable, envOptionalPositiveInt, envPositiveInt, equalityPinnedFields, exportShardRows, facetColumn, fanOutScalarCounts, findRelated, findStorageReferences, finishStreamRun, float64SqlKey, foldAggregateTally, forgetScheduleOutbox, ftsCompanionDdl, ftsPurgeDocument, ftsRowidMapName, ftsUnmappedPage, ftsWriteDocument, gateReplicaDispatch, geoTableName, globalShapeReadKey, groupUnmappedRows, guardWriter, handleReplicaControl, hasTrigger, haversineMeters, importShardRows, indexKeysForRow, isDevEnvironment, isFtsAvailable, 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 };
|
|
2505
|
+
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 FtsWriteOptions, type FunctionCallStat, type FunctionScanAttribution, type FunctionStatsResult, GEO_DEFAULT_PRECISION, GLOBAL_SHAPE_SNAPSHOT_TABLE, type GeoBoundingBox, type GeoFilterBuilderLike, type GeoIndexDefinitionLike, type GeoPoint, type GeoScoredDocument, type GlobalPollCounters, GlobalPollTick, type GroupByEntry, type GroupByOptions, type GuardableSchema$1 as GuardableSchema, IDEMPOTENCY_TABLE, type IdGenerator, type IdempotentRecord, type ImportError, type ImportShardAdminArgs, type ImportShardArgs, type ImportShardResult, type IncrementalMaterializeResult, type IndexDefinitionLike, type IndexKeyEntry, type IndexRangeBuilderLike, type KeyRange, type LifecycleDispatchInfo, type LifecycleEvent, MAIL_RETENTION, MAIL_TABLE, MAX_DURABLE_STREAM_BYTES, MAX_DURABLE_STREAM_CHUNKS, MAX_PAGE_SIZE, MAX_SQL_ROWS, type MaskColumnMetadata, type MaskPoliciesResult, type MaterializeResult, type MigrationDirection, type MigrationRunResult, type MigrationStatus, type MigrationStatusRow, type MutationDelta, type NestedWith, NotFoundError, NotUniqueError, type OnDeleteActionLike, type OrderByClause, type OrderByInput, type OrderKey, type OrderKeyConstraints, OwnerRelay, type OwnerRelayFrame, type PaginationOptions, type PitrBookmarkResult, type PitrRestoreArgs, type PitrRestoreResult, type PitrStorage, type PokeFrameMeta, type PromotionState, type PromotionThresholds, QUEUE_TABLE, type QueryArgs, type QueryPage, type QueueMessageOutcome, type QueueMessageRow, type QueueMetadata, type QueuesResult, RANK_TIEBREAK, REACTOR_STATE_TABLE, RELATED_DEFAULT_LIMIT, RELATED_DEPTH_DECAY, RELATED_MAX_DEPTH, RELATED_MAX_LIMIT, RELATION_EXISTS_KEY, RELATION_FUNCTION_PREFIX, REPROJECTION_MIGRATION_PREFIX, RLS_UNWRAP_SYMBOL, type RankBeforeOptions, type RankBeforeResult, type RankDirection, type RankIndexDefinitionLike, type RankOptions, type RankPage, type RankPageComputation, type RankPageDeps, type RankPageOptions, type RankPageRow, type RankPageRowKey, type RankResult, type RankSortKeyLike, ReactiveCache, type ReactiveCacheOptions, type ReactorDispatchResult, type ReactorMetadata, type ReactorState, type ReactorStats, type ReactorsResult, type ReadFootprint, type ReadHook, type ReadTablePageOptions, type RecordMailInput, type RecordQueueMessageInput, type RelatedDirection, type RelatedNode, type RelatedOptions, type RelatedPage, type RelatedStart, type RelatedStartReference, type RelationDefinitionLike, type RelationEdge, type RelationExistsMarker, type RelationGraphReader, type RelayAttach, type RelayDetach, type RelayFrame, type RelayHost, RelayMember, type RelayPokeDelivery, type RelayShapePoke, type RelayShapeSeed, type RelayShapeSubscribe, type RelayShapeUnsubscribe, type RenderedSql, type ReplicaFollowerHost, type ReplicaOwnerHost, type ReplicaReadiness, type ResolveRelationPredicatesOptions, type ResolveWithOptions, type ResolveWithResult, type ResolvedShape, type RestrictableQueryOptions, type RlsPoliciesResult, type RlsPolicyMetadata, RlsRequiredError, type RlsRoleMetadata, type RpcRequest, type RunDataMigrationOptions, type RunTriggersOptions, SCAN_DEP, SCHEDULE_OUTBOX_TABLE, SCHEMA_HISTORY_MAX_VERSIONS, SEARCH_STATE_TABLE, SHAPE_POKE_CURSOR_TABLE, type SchedulableWorkflowReferenceLike, type ScheduleOutbox, type ScheduleOutboxEnvelope, type ScheduleOutboxRow, type ScheduledFunctionDoc, type SchedulerLike, type SchemaLike, type ScoredDocument, type SearchBackfillProgress, type SearchFilterBuilderLike, type SearchIndexDefinitionLike, type SearchScoredDocument, type SelectMatchingIdsOptions, type ServerDefaultContextLike, type SettingEntry, type SettingKind, type SettingsResult, ShapeDiffCache, type ShapePokeCursorRow, type ShapePokePart, type ShapeProbeCounters, type ShapeRow, type ShapeRowOp, type ShapeSubscriptionQuery, type ShardRankPageResult, ShardRunner, type ShardRunnerOptions, type ShardSiblingHost, type ShardSocketLike, type SocketAttachment, type SortDirection, type SourceClientLike, type SourceCursorLike, type SourceRefresh, type SqlConsoleResult, type SqlCursor, type SqlEngine, type SqlExec, type SqlLintResult, type StorageMetadata, type StorageReference, type StorageReferenceResult, type StorageRuleMetadata, type StorageRulesResult, type StudioFeaturesResult, type SubscriptionConnection, type SubscriptionEnvelope, type SubscriptionIdentity, type SubscriptionInfo, type SubscriptionQuery, type SubscriptionReadFootprint, type SubscriptionsResult, type SystemDatabaseReader, type SystemDoc, type SystemQuery, type SystemReaderOptions, type SystemReaderSchedulerLike, type SystemReaderStorageLike, type SystemTableName, type TableColumnsResult, type TableDefinitionLike, type TableIndexInfo, type TableIndexesResult, type TableInfo, type TablePage, type TableReaderLike, type TablesColumnsResult, type TablesIndexesResult, type TransactionHeadroom, TransactionHeadroomTracker, type TransactionLimits, type TransactionSqlLike, type TriggerContextLike, type TriggerDefinitionLike, type TriggerEventLike, type TriggerOpLike, type TriggerTimingLike, type TtlSweepSpec, UNVOUCHABLE_DEP, VECTOR_BACKFILL_MAX_PAGES, type ValidatorLike, type VectorBackfillProgress, type WhereFilter, type WhereInput, type WhereSqlStrategy, type WithInput, type WorkflowInstanceState, type WorkflowInstanceStatusResult, type WorkflowMetadata, type WorkflowsResult, type WriteEvent, type WriteHook, advanceClientWatermark, aggUpsertSql, aggregateSqlFunction, aggregateTableName, allocateCommitSeq, appendAuditEntry, appendCdcChange, appendStreamChunk, applyCdcChanges, applyOnDelete, applySelect, archiveCdcSegment, armRestore, assertFlatPredicate, assertNoExplicitUndefined, assertReadonly, assertShapeShardable, assertValidClientId, awaitWsDrain, backfillAggregateIndexes, backfillRankIndexes, backfillSearchIndexes, backfillSearchIndexesForTable, backfillVectorIndexes, bigintSqlKey, boundingBoxCenter, boundingBoxGeohashes, buildIndexRange, buildPokeFrames, buildReprojectionMigration, buildSeekBeforeWhere, buildSeekWhere, buildSettings, buildShapeDiff, bumpCdcEpoch, cdcArchiveRewound, cdcCanVouchFor, cdcForkedError, cdcSeqLeavingRows, cdcTouchesTables, cdcTrimmedError, claimStreamRun, clampPromotionThresholds, clearCapturedMail, clearMemoryTables, clearQueueMessages, coerceAggregateNumber, compactCdcDocs, compileWhereSql, computeRankPage, containsRelationPredicate, countLegacyRows, coveringGeohashes, createCompanionSync, createDependencyTracker, createFanoutCounters, createGlobalPollCounters, createIndexSql, createReadFootprint, createRelayLink, createReplicaLink, createShapeDiffCache, createShapeProbeCounters, createShardCtxDb, createSystemReader, cursorBelowRetainedFloor, decideDurableAttach, decodeBigintSqlKey, decodeCursor, decodeFloat64SqlKey, deferScheduleOutbox, deleteGlobalShapeSnapshot, deleteGlobalShapeSnapshotsForConnection, deleteShapePokeCursor, deleteShapePokeCursorsForConnection, deleteStreamRun, depKey, deriveRelationEdges, diffExternalSource, diffGlobalMembership, distinctValues, encodeAggregateKey, encodeCursor, encodeGeohash, encodePartitionKey, encodeRowsPatch, ensureAuditTable, ensureMailTable, envOptionalPositiveInt, envPositiveInt, equalityPinnedFields, exportShardRows, facetColumn, fanOutScalarCounts, findRelated, findStorageReferences, finishStreamRun, float64SqlKey, foldAggregateTally, forgetScheduleOutbox, ftsCompanionDdl, ftsPurgeDocument, ftsRowidMapName, ftsUnmappedPage, ftsWriteDocument, gateReplicaDispatch, geoTableName, globalShapeReadKey, groupUnmappedRows, guardWriter, handleReplicaControl, hasTrigger, haversineMeters, importShardRows, indexKeysForRow, isDevEnvironment, isFtsAvailable, 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, whereFilter, writeCdcArchivedThrough, writeGlobalShapeSnapshot, writeIdempotent, writeReactorState, writeSearchBackfillState, writeShapePokeCursor, writeShapePokeCursors, writeTouchesMemo };
|
package/dist/index.mjs
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{exportShardRows as o,importShardRows as a,parseExportShardArgs as t,parseImportShardArgs as n,selectExportTables as s,validateImportRow as i}from"./packem_shared/exportShardRows-DmFKSzLZ.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 x,foldAggregateTally as h,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 P,ensureAuditTable as O,readAuditLog as M}from"./packem_shared/AUDIT_LOG_TABLE-CEdsC6vT.mjs";import{NotUniqueError as F,assertNoExplicitUndefined as k,assertValidClientId as N,createShardCtxDb as B,normalizeIdStructurally as U,stripReservedPatchFields as G}from"./packem_shared/NotUniqueError-D0LwVtXI.mjs";import{backfillAggregateIndexes as w,backfillRankIndexes as K,backfillSearchIndexes as v,backfillSearchIndexesForTable as X}from"./packem_shared/backfillAggregateIndexes-D-S4qiCu.mjs";import{CDC_LOG_TABLE as H,CDC_LOG_TABLE_SEQ_INDEX as V,CDC_META_TABLE as z,appendCdcChange as Q,applyCdcChanges as Y,bumpCdcEpoch as j,cdcCanVouchFor as J,cdcForkedError as Z,cdcSeqLeavingRows as $,cdcTouchesTables as ee,cdcTrimmedError as re,compactCdcDocs as oe,cursorBelowRetainedFloor as ae,migrateCdcLog as te,migrateCdcMeta as ne,minCdcReplayableSeq as se,minCdcSeq as ie,readCdcChangeKeys as le,readCdcChanges as de,readCdcCursor as ce,readCdcEpoch as me,trimCdcChanges as pe}from"./packem_shared/CDC_LOG_TABLE-BFbP2eiJ.mjs";import{archiveCdcSegment as ue,cdcArchiveRewound as fe,readArchivedCdcChanges as Ee,readCdcArchivedThrough as xe,writeCdcArchivedThrough as he}from"./packem_shared/archiveCdcSegment-C7taIEpg.mjs";import{CLIENT_WATERMARK_TABLE as Ce,advanceClientWatermark as Re,migrateClientWatermark as Ae,readClientWatermark as ge}from"./packem_shared/CLIENT_WATERMARK_TABLE-BdKYbah0.mjs";import{COMMIT_SEQ_FIELD as Ie,COMMIT_SEQ_TABLE as be,allocateCommitSeq as Le,migrateCommitSeq as De,readCommitSeq as Pe}from"./packem_shared/COMMIT_SEQ_FIELD-D6uMUaiR.mjs";import{createCompanionSync as Me}from"./packem_shared/createCompanionSync-BwWcSwvy.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-wWaEWj5f.mjs";import{IDEMPOTENCY_TABLE as we,migrateIdempotency as Ke,readIdempotent as ve,trimIdempotent as Xe,writeIdempotent as We}from"./packem_shared/IDEMPOTENCY_TABLE-DKrXVEUe.mjs";import{clearMemoryTables as Ve,isMemoryTable as ze,memoryTableNames as Qe}from"./packem_shared/clearMemoryTables-C5Wivufe.mjs";import{computeRankPage as je,resolveRankSeekTuple as Je}from"./packem_shared/computeRankPage-CQewnemg.mjs";import{SCHEDULE_OUTBOX_TABLE as $e,deferScheduleOutbox as er,forgetScheduleOutbox as rr,migrateScheduleOutbox as or,parkScheduleOutbox as ar,probeScheduleOutbox as tr,readDueScheduleOutbox as nr,recordScheduleOutbox as sr,trimScheduleOutbox as ir}from"./packem_shared/SCHEDULE_OUTBOX_TABLE-BHpxtEy4.mjs";import{S as dr,m as cr,r as mr,w as pr}from"./packem_shared/ctx-db-search-state-fIiMVPXO.mjs";import{SHAPE_POKE_CURSOR_TABLE as ur,deleteShapePokeCursor as fr,deleteShapePokeCursorsForConnection as Er,migrateShapePokeCursor as xr,minShapePokeCursor as hr,readShapePokeCursor as Tr,writeShapePokeCursor as Cr,writeShapePokeCursors as Rr}from"./packem_shared/SHAPE_POKE_CURSOR_TABLE-Bbpou9XZ.mjs";import{selectShapeMembers as gr,selectShapeRows as _r}from"./packem_shared/selectShapeMembers-Cp98I-ot.mjs";import{DATA_MIGRATION_STATE_TABLE as br,readMigrationStatus as Lr,runDataMigration as Dr}from"./packem_shared/DATA_MIGRATION_STATE_TABLE-BbDr6pc7.mjs";import{SCAN_DEP as Or,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-CfKnGpV2.mjs";import{A as Gr,a as qr,b as wr,D as Kr,c as vr,d as Xr,g as Wr,i as Hr,j as Vr,e as zr,q as Qr,f as Yr,r as jr,t as Jr,h as Zr}from"./packem_shared/do-sql-BSoH-O04.mjs";import{param as eo,renderSql as ro,sqliteInList as oo,unionAll as ao}from"./packem_shared/param-DlozcSQu.mjs";import{appendStreamChunk as no,claimStreamRun as so,deleteStreamRun as io,finishStreamRun as lo,migrateDurableStreams as co,readStreamChunks as mo,readStreamRun as po,trimStreamRuns as So}from"./packem_shared/appendStreamChunk-pPeR5nbF.mjs";import{DurableStreamRunner as fo,MAX_DURABLE_STREAM_BYTES as Eo,MAX_DURABLE_STREAM_CHUNKS as xo,decideDurableAttach as ho}from"./packem_shared/DurableStreamRunner-Cliu09-j.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 Po,materializeExternalRowsIncremental as Oo,readExternalSourceBaseline as Mo,runExternalSourceTick as yo}from"./packem_shared/materializeExternalRows-j_8glxcE.mjs";import{isSoftDeleted as ko,isSourceDue as No,pullExternalSourceIncrementalTick as Bo,pullExternalSourceTick as Uo}from"./packem_shared/isSoftDeleted-CCDHCtX3.mjs";import{f as qo,a as wo,b as Ko,c as vo,d as Xo,g as Wo}from"./packem_shared/fts-companion-B7jllLhZ.mjs";import{GEO_DEFAULT_PRECISION as Vo,boundingBoxCenter as zo,boundingBoxGeohashes as Qo,coveringGeohashes as Yo,encodeGeohash as jo,haversineMeters as Jo,pointInBoundingBox as Zo}from"./packem_shared/GEO_DEFAULT_PRECISION-CqpQZ-J_.mjs";import{default as ea}from"./packem_shared/GlobalPollTick-BNK4o-XT.mjs";import{ADMIN_FUNCTIONS as oa,ADMIN_FUNCTION_PREFIX as aa,DEFAULT_FANOUT_TOPIC_LIMIT as ta,FLAGS_FUNCTION_PREFIX as na,MAX_PAGE_SIZE as sa,RELATION_FUNCTION_PREFIX as ia,createFanoutCounters as la,createGlobalPollCounters as da,createShapeProbeCounters as ca,facetColumn as ma,findStorageReferences as pa,listTables as Sa,readTablePage as ua,recordFanoutPass as fa,recordGlobalPollPass as Ea,recordShapeProbePass as xa,selectMatchingIds as ha,summarizeFanoutTopics as Ta,summarizeSubscriptions as Ca}from"./packem_shared/ADMIN_FUNCTIONS-BdZ3gTHm.mjs";import{MAIL_RETENTION as Aa,MAIL_TABLE as ga,clearCapturedMail as _a,ensureMailTable as Ia,readCapturedMail as ba,recordCapturedMail as La}from"./packem_shared/MAIL_RETENTION-DXpGFjOt.mjs";import{NotFoundError as Pa}from"./packem_shared/NotFoundError-BhF7FeFr.mjs";import{armRestore as Ma,readBookmark as ya}from"./packem_shared/armRestore-Bu1_8SUa.mjs";import{CURSOR_PREFIX as ka,applySelect as Na,buildSeekBeforeWhere as Ba,buildSeekWhere as Ua,decodeCursor as Ga,encodeCursor as qa,equalityPinnedFields as wa,normalizeOrderKeys as Ka,softDeleteScope as va,tiebreakDirectionFor as Xa,uniqueIndexFields as Wa}from"./packem_shared/CURSOR_PREFIX-Bn8SFoGd.mjs";import{QUEUE_TABLE as Va,clearQueueMessages as za,isLossyBody as Qa,readQueueMessageById as Ya,readQueueMessages as ja,recordQueueMessages as Ja}from"./packem_shared/QUEUE_TABLE-D-cL1NPj.mjs";import{RANK_TIEBREAK as $a,encodePartitionKey as et,matchesRankStaticWhere as rt,rankKeyFromDoc as ot,rankPivotConditionSql as at,rankTableName as tt,resolveRankPartition as nt,sortColumnName as st}from"./packem_shared/RANK_TIEBREAK-D5xNdzB3.mjs";import{ReactiveCache as lt,reactiveCacheKey as dt}from"./packem_shared/ReactiveCache-CU_NoCMR.mjs";import{REACTOR_STATE_TABLE as mt,listReactorStates as pt,migrateReactorState as St,reactorNeedsRun as ut,readReactorState as ft,writeReactorState as Et}from"./packem_shared/REACTOR_STATE_TABLE-CBHASjH9.mjs";import{UNVOUCHABLE_DEP as ht,createReadFootprint as Tt,markUnvouchableReads as Ct}from"./packem_shared/UNVOUCHABLE_DEP-C68htACn.mjs";import{buildIndexRange as At,indexKeysForRow as gt,keysTouchRanges as _t}from"./packem_shared/buildIndexRange-DvN8Qj8e.mjs";import{RELATED_DEFAULT_LIMIT as bt,RELATED_DEPTH_DECAY as Lt,RELATED_MAX_DEPTH as Dt,RELATED_MAX_LIMIT as Pt,deriveRelationEdges as Ot,findRelated as Mt}from"./packem_shared/RELATED_DEFAULT_LIMIT-B9PH28Pn.mjs";import{DEFAULT_MAX_RELATION_KEYS as Ft,assertFlatPredicate as kt,assertShapeShardable as Nt,containsRelationPredicate as Bt,isRelationPredicate as Ut,resolveRelationPredicates as Gt}from"./packem_shared/DEFAULT_MAX_RELATION_KEYS-BfAQvZT8.mjs";import{applyOnDelete as wt,distinctValues as Kt,fanOutScalarCounts as vt,relationHooks as Xt,resolveWith as Wt,runRowValidators as Ht}from"./packem_shared/applyOnDelete-7JZ4vR9r.mjs";import{DEFAULT_PROMOTION_THRESHOLDS as zt,clampPromotionThresholds as Qt,nextPromotionState as Yt,relayCountFor as jt,shapeRoutingKey as Jt}from"./packem_shared/DEFAULT_PROMOTION_THRESHOLDS-Bfx7KakS.mjs";import{DEFAULT_MAX_RELAYS as $t,OwnerRelay as en,RelayMember as rn,createRelayLink as on}from"./packem_shared/DEFAULT_MAX_RELAYS-DG9iXjzF.mjs";import{createReplicaLink as tn,gateReplicaDispatch as nn,handleReplicaControl as sn}from"./packem_shared/createReplicaLink-CTyOjpjh.mjs";import{buildReprojectionMigration as dn,countLegacyRows as cn,reprojectableFields as mn,reprojectionTables as pn}from"./packem_shared/buildReprojectionMigration-DDZhSO95.mjs";import{RLS_UNWRAP_SYMBOL as un,RlsRequiredError as fn,guardWriter as En}from"./packem_shared/RLS_UNWRAP_SYMBOL-BwwTbz3Q.mjs";import{SCHEMA_HISTORY_MAX_VERSIONS as hn,readSchemaHistory as Tn,readSchemaVersion as Cn,recordSchemaVersion as Rn}from"./packem_shared/SCHEMA_HISTORY_MAX_VERSIONS-CXznJRUG.mjs";import{serializeSqlValue as gn}from"./packem_shared/serializeSqlValue-BEMMYX1n.mjs";import{buildSettings as In,isDevEnvironment as bn,readDeployInfo as Ln}from"./packem_shared/buildSettings-DC3VeQ0H.mjs";import{buildShapeDiff as Pn}from"./packem_shared/buildShapeDiff-Bd5nLaY8.mjs";import{ShapeDiffCache as Mn,createShapeDiffCache as yn,globalShapeReadKey as Fn}from"./packem_shared/ShapeDiffCache-gdaILV5E.mjs";import{buildPokeFrames as Nn,diffGlobalMembership as Bn,encodeRowsPatch as Un,projectColumns as Gn}from"./packem_shared/buildPokeFrames-BBE6J91z.mjs";import{ShardRunner as wn}from"./packem_shared/ShardRunner-CrveaPId.mjs";import{runSocketPool as vn}from"./packem_shared/runSocketPool-CZJ2X9cF.mjs";import{MAX_SQL_ROWS as Wn,assertReadonly as Hn,lintReadonlySql as Vn,runReadonlySql as zn}from"./packem_shared/MAX_SQL_ROWS-Dh_Ty0Zo.mjs";import{B as Yn,b as jn,d as Jn,a as Zn,f as $n}from"./packem_shared/sql-projection-D3qdaItY.mjs";import{awaitWsDrain as rs,subscriptionFrames as os,subscriptionListDeltas as as,trySendFrame as ts}from"./packem_shared/awaitWsDrain-apizgmKY.mjs";import{mergeChangedKeys as ss,recordChangedKeys as is,writeTouchesMemo as ls}from"./packem_shared/mergeChangedKeys-BA3YxaLE.mjs";import{createSystemReader as cs}from"./packem_shared/createSystemReader-DcDLFfC-.mjs";import{ConflictError as ps}from"./packem_shared/ConflictError-C8GtJmjS.mjs";import{DEFAULT_TRANSACTION_LIMITS as us,TransactionHeadroomTracker as fs}from"./packem_shared/DEFAULT_TRANSACTION_LIMITS-CTHQQgDC.mjs";import{hasTrigger as xs,runTriggers as hs}from"./packem_shared/hasTrigger-CjlwI4le.mjs";import{selectExpiredIds as Cs}from"./packem_shared/selectExpiredIds-Do1q2HQr.mjs";import{VECTOR_BACKFILL_MAX_PAGES as As,backfillVectorIndexes as gs}from"./packem_shared/VECTOR_BACKFILL_MAX_PAGES-C-KZJbgA.mjs";import{c as Is,l as bs}from"./packem_shared/where-sql-x1YKldcq.mjs";import{RELATION_EXISTS_KEY as Ds}from"./packem_shared/RELATION_EXISTS_KEY-CFUhnZSZ.mjs";import{REPROJECTION_MIGRATION_PREFIX as Os,reprojectionMigrationId as Ms}from"./packem_shared/REPROJECTION_MIGRATION_PREFIX-Czcb6_mO.mjs";import{quoteIdentifier as Fs}from"./packem_shared/quoteIdentifier-CObIFRhb.mjs";import{runShardMigrations as Ns}from"./packem_shared/runShardMigrations-o-qjyKt5.mjs";import{stableStringify as Us}from"./packem_shared/stableStringify-DibjylKD.mjs";import{stableWireKey as qs}from"./packem_shared/stableWireKey-D2US4k_J.mjs";export{oa as ADMIN_FUNCTIONS,aa as ADMIN_FUNCTION_PREFIX,d as AGGREGATE_SQL_FUNCTION,Gr as AGG_COUNT,qr as AGG_KEY,wr as AGG_VALUE,D as AUDIT_LOG_TABLE,Yn as BIGINT_KEY_DIGITS,H as CDC_LOG_TABLE,V as CDC_LOG_TABLE_SEQ_INDEX,z as CDC_META_TABLE,Ce as CLIENT_WATERMARK_TABLE,Ie as COMMIT_SEQ_FIELD,be as COMMIT_SEQ_TABLE,ka as CURSOR_PREFIX,ps as ConflictError,R as CountRlsUnsupportedError,br as DATA_MIGRATION_STATE_TABLE,ta as DEFAULT_FANOUT_TOPIC_LIMIT,Ft as DEFAULT_MAX_RELATION_KEYS,$t as DEFAULT_MAX_RELAYS,zt as DEFAULT_PROMOTION_THRESHOLDS,us as DEFAULT_TRANSACTION_LIMITS,Kr as DOC_COLUMN,fo as DurableStreamRunner,na as FLAGS_FUNCTION_PREFIX,Vo as GEO_DEFAULT_PRECISION,Fe as GLOBAL_SHAPE_SNAPSHOT_TABLE,ea as GlobalPollTick,we as IDEMPOTENCY_TABLE,Aa as MAIL_RETENTION,ga as MAIL_TABLE,Eo as MAX_DURABLE_STREAM_BYTES,xo as MAX_DURABLE_STREAM_CHUNKS,sa as MAX_PAGE_SIZE,Wn as MAX_SQL_ROWS,Pa as NotFoundError,F as NotUniqueError,en as OwnerRelay,Va as QUEUE_TABLE,$a as RANK_TIEBREAK,mt as REACTOR_STATE_TABLE,bt as RELATED_DEFAULT_LIMIT,Lt as RELATED_DEPTH_DECAY,Dt as RELATED_MAX_DEPTH,Pt as RELATED_MAX_LIMIT,Ds as RELATION_EXISTS_KEY,ia as RELATION_FUNCTION_PREFIX,Os as REPROJECTION_MIGRATION_PREFIX,un as RLS_UNWRAP_SYMBOL,lt as ReactiveCache,rn as RelayMember,fn as RlsRequiredError,Or as SCAN_DEP,$e as SCHEDULE_OUTBOX_TABLE,hn as SCHEMA_HISTORY_MAX_VERSIONS,dr as SEARCH_STATE_TABLE,ur as SHAPE_POKE_CURSOR_TABLE,Mn as ShapeDiffCache,wn as ShardRunner,fs as TransactionHeadroomTracker,ht as UNVOUCHABLE_DEP,As as VECTOR_BACKFILL_MAX_PAGES,Re as advanceClientWatermark,vr as aggUpsertSql,c as aggregateSqlFunction,f as aggregateTableName,Le as allocateCommitSeq,P as appendAuditEntry,Q as appendCdcChange,no as appendStreamChunk,Y as applyCdcChanges,wt as applyOnDelete,Na as applySelect,ue as archiveCdcSegment,Ma as armRestore,kt as assertFlatPredicate,k as assertNoExplicitUndefined,Hn as assertReadonly,Nt as assertShapeShardable,N as assertValidClientId,rs as awaitWsDrain,w as backfillAggregateIndexes,K as backfillRankIndexes,v as backfillSearchIndexes,X as backfillSearchIndexesForTable,gs as backfillVectorIndexes,jn as bigintSqlKey,zo as boundingBoxCenter,Qo as boundingBoxGeohashes,At as buildIndexRange,Nn as buildPokeFrames,dn as buildReprojectionMigration,Ba as buildSeekBeforeWhere,Ua as buildSeekWhere,In as buildSettings,Pn as buildShapeDiff,j as bumpCdcEpoch,fe as cdcArchiveRewound,J as cdcCanVouchFor,Z as cdcForkedError,$ as cdcSeqLeavingRows,ee as cdcTouchesTables,re as cdcTrimmedError,so as claimStreamRun,Qt as clampPromotionThresholds,_a as clearCapturedMail,Ve as clearMemoryTables,za as clearQueueMessages,E as coerceAggregateNumber,oe as compactCdcDocs,Is as compileWhereSql,je as computeRankPage,Bt as containsRelationPredicate,cn as countLegacyRows,Yo as coveringGeohashes,Me as createCompanionSync,Mr as createDependencyTracker,la as createFanoutCounters,da as createGlobalPollCounters,Xr as createIndexSql,Tt as createReadFootprint,on as createRelayLink,tn as createReplicaLink,yn as createShapeDiffCache,ca as createShapeProbeCounters,B as createShardCtxDb,cs as createSystemReader,ae as cursorBelowRetainedFloor,ho as decideDurableAttach,Jn as decodeBigintSqlKey,Ga as decodeCursor,Zn as decodeFloat64SqlKey,er as deferScheduleOutbox,ke as deleteGlobalShapeSnapshot,Ne as deleteGlobalShapeSnapshotsForConnection,fr as deleteShapePokeCursor,Er as deleteShapePokeCursorsForConnection,io as deleteStreamRun,yr as depKey,Ot as deriveRelationEdges,go as diffExternalSource,Bn as diffGlobalMembership,Kt as distinctValues,x as encodeAggregateKey,qa as encodeCursor,jo as encodeGeohash,et as encodePartitionKey,Un as encodeRowsPatch,O as ensureAuditTable,Ia as ensureMailTable,Co as envOptionalPositiveInt,Ro as envPositiveInt,wa as equalityPinnedFields,o as exportShardRows,ma as facetColumn,vt as fanOutScalarCounts,Mt as findRelated,pa as findStorageReferences,lo as finishStreamRun,$n as float64SqlKey,h as foldAggregateTally,rr as forgetScheduleOutbox,qo as ftsCompanionDdl,wo as ftsPurgeDocument,Ko as ftsRowidMapName,vo as ftsUnmappedPage,Xo as ftsWriteDocument,nn as gateReplicaDispatch,Wr as geoTableName,Fn as globalShapeReadKey,Wo as groupUnmappedRows,En as guardWriter,sn as handleReplicaControl,xs as hasTrigger,Jo as haversineMeters,a as importShardRows,gt as indexKeysForRow,bn as isDevEnvironment,Hr as isFtsAvailable,Qa as isLossyBody,ze as isMemoryTable,Ut as isRelationPredicate,ko as isSoftDeleted,No as isSourceDue,Vr as jsonPath,zr as jsonPathSql,_t as keysTouchRanges,Io as liftSourceId,Vn as lintReadonlySql,pt as listReactorStates,Sa as listTables,bs as literalInList,Ct as markUnvouchableReads,rt as matchesRankStaticWhere,m as matchesStaticWhere,Po as materializeExternalRows,Oo as materializeExternalRowsIncremental,Qe as memoryTableNames,ss as mergeChangedKeys,A as mergeWhere,te as migrateCdcLog,ne as migrateCdcMeta,Ae as migrateClientWatermark,De as migrateCommitSeq,co as migrateDurableStreams,Be as migrateGlobalShapeSnapshot,Ke as migrateIdempotency,St as migrateReactorState,or as migrateScheduleOutbox,cr as migrateSearchState,xr as migrateShapePokeCursor,se as minCdcReplayableSeq,ie as minCdcSeq,hr as minShapePokeCursor,Yt 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,n as parseImportShardArgs,g as planAggregateLookup,Zo as pointInBoundingBox,tr as probeScheduleOutbox,Gn as projectColumns,Bo as pullExternalSourceIncrementalTick,Uo as pullExternalSourceTick,Qr as qualifiedJsonPath,Yr as qualifiedJsonPathSql,Fs as quoteIdentifier,ot as rankKeyFromDoc,at as rankPivotConditionSql,tt as rankTableName,dt as reactiveCacheKey,ut as reactorNeedsRun,T as readAggregateValue,Ee as readArchivedCdcChanges,M as readAuditLog,ya as readBookmark,ba as readCapturedMail,xe as readCdcArchivedThrough,le as readCdcChangeKeys,de as readCdcChanges,ce as readCdcCursor,me as readCdcEpoch,ge as readClientWatermark,Pe as readCommitSeq,Ln as readDeployInfo,nr as readDueScheduleOutbox,Mo as readExternalSourceBaseline,Ue as readGlobalShapeSnapshot,ve as readIdempotent,Lr as readMigrationStatus,Ya as readQueueMessageById,ja as readQueueMessages,ft as readReactorState,Tn as readSchemaHistory,Cn as readSchemaVersion,mr as readSearchBackfillState,Tr as readShapePokeCursor,mo as readStreamChunks,po as readStreamRun,ua as readTablePage,La as recordCapturedMail,is as recordChangedKeys,fa as recordFanoutPass,Ea as recordGlobalPollPass,Ja as recordQueueMessages,sr as recordScheduleOutbox,Rn as recordSchemaVersion,xa as recordShapeProbePass,Xt as relationHooks,jt as relayCountFor,ro as renderSql,mn as reprojectableFields,Ms as reprojectionMigrationId,pn as reprojectionTables,nt as resolveRankPartition,Je as resolveRankSeekTuple,Gt as resolveRelationPredicates,Wt as resolveWith,jr as rowToDocument,Dr as runDataMigration,Nr as runDrizzle,yo as runExternalSourceTick,zn as runReadonlySql,Ht as runRowValidators,Ns as runShardMigrations,vn as runSocketPool,Br as runSql,hs as runTriggers,Cs as selectExpiredIds,s as selectExportTables,_ as selectIndexForAggregate,I as selectIndexForCount,b as selectIndexForGroupBy,ha as selectMatchingIds,gr as selectShapeMembers,_r as selectShapeRows,gn as serializeSqlValue,Jt as shapeRoutingKey,va as softDeleteScope,st as sortColumnName,oo as sqliteInList,Us as stableStringify,qs as stableWireKey,G as stripReservedPatchFields,os as subscriptionFrames,as as subscriptionListDeltas,Ta as summarizeFanoutTopics,Ca as summarizeSubscriptions,Jr as tableColumns,Fr as tableFromDepKey,S as throwingScheduler,Xa as tiebreakDirectionFor,pe as trimCdcChanges,Xe as trimIdempotent,ir as trimScheduleOutbox,So as trimStreamRuns,Zr as tryRowToDocument,ts as trySendFrame,ao as unionAll,Wa as uniqueIndexFields,i as validateImportRow,he as writeCdcArchivedThrough,Ge as writeGlobalShapeSnapshot,We as writeIdempotent,Et as writeReactorState,pr as writeSearchBackfillState,Cr as writeShapePokeCursor,Rr as writeShapePokeCursors,ls as writeTouchesMemo};
|
|
1
|
+
import{exportShardRows as o,importShardRows as a,parseExportShardArgs as t,parseImportShardArgs as n,selectExportTables as i,validateImportRow as l}from"./packem_shared/exportShardRows-DmFKSzLZ.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 x,foldAggregateTally as h,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 P,ensureAuditTable as O,readAuditLog as M}from"./packem_shared/AUDIT_LOG_TABLE-CEdsC6vT.mjs";import{NotUniqueError as y,assertNoExplicitUndefined as k,assertValidClientId as N,createShardCtxDb as B,normalizeIdStructurally as U,stripReservedPatchFields as G}from"./packem_shared/NotUniqueError-2vJ9edyE.mjs";import{backfillAggregateIndexes as w,backfillRankIndexes as K,backfillSearchIndexes as v,backfillSearchIndexesForTable as X}from"./packem_shared/backfillAggregateIndexes-yFyVVEHD.mjs";import{CDC_LOG_TABLE as H,CDC_LOG_TABLE_SEQ_INDEX as V,CDC_META_TABLE as z,appendCdcChange as Q,applyCdcChanges as Y,bumpCdcEpoch as j,cdcCanVouchFor as J,cdcForkedError as Z,cdcSeqLeavingRows as $,cdcTouchesTables as ee,cdcTrimmedError as re,compactCdcDocs as oe,cursorBelowRetainedFloor as ae,migrateCdcLog as te,migrateCdcMeta as ne,minCdcReplayableSeq as ie,minCdcSeq as le,readCdcChangeKeys as se,readCdcChanges as de,readCdcCursor as ce,readCdcEpoch as me,trimCdcChanges as pe}from"./packem_shared/CDC_LOG_TABLE-C5XCNb2J.mjs";import{archiveCdcSegment as ue,cdcArchiveRewound as fe,readArchivedCdcChanges as Ee,readCdcArchivedThrough as xe,writeCdcArchivedThrough as he}from"./packem_shared/archiveCdcSegment-C7taIEpg.mjs";import{CLIENT_WATERMARK_TABLE as Ce,advanceClientWatermark as Re,migrateClientWatermark as Ae,readClientWatermark as ge}from"./packem_shared/CLIENT_WATERMARK_TABLE-BdKYbah0.mjs";import{COMMIT_SEQ_FIELD as Ie,COMMIT_SEQ_TABLE as be,allocateCommitSeq as Le,migrateCommitSeq as De,readCommitSeq as Pe}from"./packem_shared/COMMIT_SEQ_FIELD-D6uMUaiR.mjs";import{createCompanionSync as Me}from"./packem_shared/createCompanionSync-CGVFf7GK.mjs";import{GLOBAL_SHAPE_SNAPSHOT_TABLE as ye,deleteGlobalShapeSnapshot as ke,deleteGlobalShapeSnapshotsForConnection as Ne,migrateGlobalShapeSnapshot as Be,readGlobalShapeSnapshot as Ue,writeGlobalShapeSnapshot as Ge}from"./packem_shared/GLOBAL_SHAPE_SNAPSHOT_TABLE-wWaEWj5f.mjs";import{IDEMPOTENCY_TABLE as we,migrateIdempotency as Ke,readIdempotent as ve,trimIdempotent as Xe,writeIdempotent as We}from"./packem_shared/IDEMPOTENCY_TABLE-DKrXVEUe.mjs";import{clearMemoryTables as Ve,isMemoryTable as ze,memoryTableNames as Qe}from"./packem_shared/clearMemoryTables-C5Wivufe.mjs";import{computeRankPage as je,resolveRankSeekTuple as Je}from"./packem_shared/computeRankPage-Bg1_6fPP.mjs";import{SCHEDULE_OUTBOX_TABLE as $e,deferScheduleOutbox as er,forgetScheduleOutbox as rr,migrateScheduleOutbox as or,parkScheduleOutbox as ar,probeScheduleOutbox as tr,readDueScheduleOutbox as nr,recordScheduleOutbox as ir,trimScheduleOutbox as lr}from"./packem_shared/SCHEDULE_OUTBOX_TABLE-BHpxtEy4.mjs";import{S as dr,m as cr,r as mr,w as pr}from"./packem_shared/ctx-db-search-state-fIiMVPXO.mjs";import{SHAPE_POKE_CURSOR_TABLE as ur,deleteShapePokeCursor as fr,deleteShapePokeCursorsForConnection as Er,migrateShapePokeCursor as xr,minShapePokeCursor as hr,readShapePokeCursor as Tr,writeShapePokeCursor as Cr,writeShapePokeCursors as Rr}from"./packem_shared/SHAPE_POKE_CURSOR_TABLE-Bbpou9XZ.mjs";import{selectShapeMembers as gr,selectShapeRows as _r}from"./packem_shared/selectShapeMembers-CIfYJUcu.mjs";import{DATA_MIGRATION_STATE_TABLE as br,readMigrationStatus as Lr,runDataMigration as Dr}from"./packem_shared/DATA_MIGRATION_STATE_TABLE-BbDr6pc7.mjs";import{SCAN_DEP as Or,createDependencyTracker as Mr,depKey as Fr,tableFromDepKey as yr}from"./packem_shared/SCAN_DEP-D7qE3iUe.mjs";import{runDrizzle as Nr,runSql as Br}from"./packem_shared/runDrizzle-CfKnGpV2.mjs";import{A as Gr,a as qr,b as wr,D as Kr,c as vr,d as Xr,g as Wr,i as Hr,j as Vr,e as zr,q as Qr,f as Yr,r as jr,t as Jr,h as Zr}from"./packem_shared/do-sql-C7TkRQqw.mjs";import{param as eo,renderSql as ro,sqliteInList as oo,unionAll as ao}from"./packem_shared/param-DlozcSQu.mjs";import{appendStreamChunk as no,claimStreamRun as io,deleteStreamRun as lo,finishStreamRun as so,migrateDurableStreams as co,readStreamChunks as mo,readStreamRun as po,trimStreamRuns as So}from"./packem_shared/appendStreamChunk-pPeR5nbF.mjs";import{DurableStreamRunner as fo,MAX_DURABLE_STREAM_BYTES as Eo,MAX_DURABLE_STREAM_CHUNKS as xo,decideDurableAttach as ho}from"./packem_shared/DurableStreamRunner-Cliu09-j.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 Po,materializeExternalRowsIncremental as Oo,readExternalSourceBaseline as Mo,runExternalSourceTick as Fo}from"./packem_shared/materializeExternalRows-N-f9jaQE.mjs";import{isSoftDeleted as ko,isSourceDue as No,pullExternalSourceIncrementalTick as Bo,pullExternalSourceTick as Uo}from"./packem_shared/isSoftDeleted-DDKwGeyk.mjs";import{f as qo,a as wo,b as Ko,c as vo,d as Xo,g as Wo}from"./packem_shared/fts-companion-B7jllLhZ.mjs";import{GEO_DEFAULT_PRECISION as Vo,boundingBoxCenter as zo,boundingBoxGeohashes as Qo,coveringGeohashes as Yo,encodeGeohash as jo,haversineMeters as Jo,pointInBoundingBox as Zo}from"./packem_shared/GEO_DEFAULT_PRECISION-CqpQZ-J_.mjs";import{default as ea}from"./packem_shared/GlobalPollTick-BNK4o-XT.mjs";import{ADMIN_FUNCTIONS as oa,ADMIN_FUNCTION_PREFIX as aa,DEFAULT_FANOUT_TOPIC_LIMIT as ta,FLAGS_FUNCTION_PREFIX as na,MAX_PAGE_SIZE as ia,RELATION_FUNCTION_PREFIX as la,createFanoutCounters as sa,createGlobalPollCounters as da,createShapeProbeCounters as ca,facetColumn as ma,findStorageReferences as pa,listTables as Sa,readTablePage as ua,recordFanoutPass as fa,recordGlobalPollPass as Ea,recordShapeProbePass as xa,selectMatchingIds as ha,summarizeFanoutTopics as Ta,summarizeSubscriptions as Ca}from"./packem_shared/ADMIN_FUNCTIONS-5o1gzcJV.mjs";import{MAIL_RETENTION as Aa,MAIL_TABLE as ga,clearCapturedMail as _a,ensureMailTable as Ia,readCapturedMail as ba,recordCapturedMail as La}from"./packem_shared/MAIL_RETENTION-DXpGFjOt.mjs";import{NotFoundError as Pa}from"./packem_shared/NotFoundError-BhF7FeFr.mjs";import{armRestore as Ma,readBookmark as Fa}from"./packem_shared/armRestore-Bu1_8SUa.mjs";import{CURSOR_PREFIX as ka,applySelect as Na,buildSeekBeforeWhere as Ba,buildSeekWhere as Ua,decodeCursor as Ga,encodeCursor as qa,equalityPinnedFields as wa,normalizeOrderKeys as Ka,softDeleteScope as va,tiebreakDirectionFor as Xa,uniqueIndexFields as Wa}from"./packem_shared/CURSOR_PREFIX-Bn8SFoGd.mjs";import{QUEUE_TABLE as Va,clearQueueMessages as za,isLossyBody as Qa,readQueueMessageById as Ya,readQueueMessages as ja,recordQueueMessages as Ja}from"./packem_shared/QUEUE_TABLE-D-cL1NPj.mjs";import{RANK_TIEBREAK as $a,encodePartitionKey as et,matchesRankStaticWhere as rt,rankKeyFromDoc as ot,rankPivotConditionSql as at,rankTableName as tt,resolveRankPartition as nt,sortColumnName as it}from"./packem_shared/RANK_TIEBREAK-B0_x8iev.mjs";import{ReactiveCache as st,reactiveCacheKey as dt}from"./packem_shared/ReactiveCache-D8ccaO6f.mjs";import{REACTOR_STATE_TABLE as mt,listReactorStates as pt,migrateReactorState as St,reactorNeedsRun as ut,readReactorState as ft,writeReactorState as Et}from"./packem_shared/REACTOR_STATE_TABLE-CBHASjH9.mjs";import{UNVOUCHABLE_DEP as ht,createReadFootprint as Tt,markUnvouchableReads as Ct}from"./packem_shared/UNVOUCHABLE_DEP-C68htACn.mjs";import{buildIndexRange as At,indexKeysForRow as gt,keysTouchRanges as _t}from"./packem_shared/buildIndexRange-6nIZDf4m.mjs";import{whereFilter as bt}from"./packem_shared/whereFilter-CLmm3TFe.mjs";import{RELATED_DEFAULT_LIMIT as Dt,RELATED_DEPTH_DECAY as Pt,RELATED_MAX_DEPTH as Ot,RELATED_MAX_LIMIT as Mt,deriveRelationEdges as Ft,findRelated as yt}from"./packem_shared/RELATED_DEFAULT_LIMIT-B9PH28Pn.mjs";import{DEFAULT_MAX_RELATION_KEYS as Nt,assertFlatPredicate as Bt,assertShapeShardable as Ut,containsRelationPredicate as Gt,isRelationPredicate as qt,resolveRelationPredicates as wt}from"./packem_shared/DEFAULT_MAX_RELATION_KEYS-fYrcrp5Z.mjs";import{applyOnDelete as vt,distinctValues as Xt,fanOutScalarCounts as Wt,relationHooks as Ht,resolveWith as Vt,runRowValidators as zt}from"./packem_shared/applyOnDelete-7JZ4vR9r.mjs";import{DEFAULT_PROMOTION_THRESHOLDS as Yt,clampPromotionThresholds as jt,nextPromotionState as Jt,relayCountFor as Zt,shapeRoutingKey as $t}from"./packem_shared/DEFAULT_PROMOTION_THRESHOLDS-Bfx7KakS.mjs";import{DEFAULT_MAX_RELAYS as rn,OwnerRelay as on,RelayMember as an,createRelayLink as tn}from"./packem_shared/DEFAULT_MAX_RELAYS-DG9iXjzF.mjs";import{createReplicaLink as ln,gateReplicaDispatch as sn,handleReplicaControl as dn}from"./packem_shared/createReplicaLink-S5xtsySX.mjs";import{buildReprojectionMigration as mn,countLegacyRows as pn,reprojectableFields as Sn,reprojectionTables as un}from"./packem_shared/buildReprojectionMigration-DYjcBhki.mjs";import{RLS_UNWRAP_SYMBOL as En,RlsRequiredError as xn,guardWriter as hn}from"./packem_shared/RLS_UNWRAP_SYMBOL-BwwTbz3Q.mjs";import{SCHEMA_HISTORY_MAX_VERSIONS as Cn,readSchemaHistory as Rn,readSchemaVersion as An,recordSchemaVersion as gn}from"./packem_shared/SCHEMA_HISTORY_MAX_VERSIONS-CXznJRUG.mjs";import{serializeSqlValue as In}from"./packem_shared/serializeSqlValue-BbZ5hKM7.mjs";import{buildSettings as Ln,isDevEnvironment as Dn,readDeployInfo as Pn}from"./packem_shared/buildSettings-DC3VeQ0H.mjs";import{buildShapeDiff as Mn}from"./packem_shared/buildShapeDiff-BMe0ktEG.mjs";import{ShapeDiffCache as yn,createShapeDiffCache as kn,globalShapeReadKey as Nn}from"./packem_shared/ShapeDiffCache-gdaILV5E.mjs";import{buildPokeFrames as Un,diffGlobalMembership as Gn,encodeRowsPatch as qn,projectColumns as wn}from"./packem_shared/buildPokeFrames-BBE6J91z.mjs";import{ShardRunner as vn}from"./packem_shared/ShardRunner-CrveaPId.mjs";import{runSocketPool as Wn}from"./packem_shared/runSocketPool-CZJ2X9cF.mjs";import{MAX_SQL_ROWS as Vn,assertReadonly as zn,lintReadonlySql as Qn,runReadonlySql as Yn}from"./packem_shared/MAX_SQL_ROWS-Dh_Ty0Zo.mjs";import{BIGINT_KEY_DIGITS as Jn,bigintSqlKey as Zn,decodeBigintSqlKey as $n,decodeFloat64SqlKey as ei,float64SqlKey as ri}from"./packem_shared/BIGINT_KEY_DIGITS-C9a7Ix7k.mjs";import{awaitWsDrain as ai,subscriptionFrames as ti,subscriptionListDeltas as ni,trySendFrame as ii}from"./packem_shared/awaitWsDrain-apizgmKY.mjs";import{mergeChangedKeys as si,recordChangedKeys as di,writeTouchesMemo as ci}from"./packem_shared/mergeChangedKeys-DH9RAARR.mjs";import{createSystemReader as pi}from"./packem_shared/createSystemReader-DcDLFfC-.mjs";import{ConflictError as ui}from"./packem_shared/ConflictError-C8GtJmjS.mjs";import{DEFAULT_TRANSACTION_LIMITS as Ei,TransactionHeadroomTracker as xi}from"./packem_shared/DEFAULT_TRANSACTION_LIMITS-DiR5z5EX.mjs";import{hasTrigger as Ti,runTriggers as Ci}from"./packem_shared/hasTrigger-CjlwI4le.mjs";import{selectExpiredIds as Ai}from"./packem_shared/selectExpiredIds-BuLDf-k0.mjs";import{VECTOR_BACKFILL_MAX_PAGES as _i,backfillVectorIndexes as Ii}from"./packem_shared/VECTOR_BACKFILL_MAX_PAGES-CWDvq1RK.mjs";import{c as Li,l as Di}from"./packem_shared/where-sql-x1YKldcq.mjs";import{RELATION_EXISTS_KEY as Oi}from"./packem_shared/RELATION_EXISTS_KEY-CFUhnZSZ.mjs";import{REPROJECTION_MIGRATION_PREFIX as Fi,reprojectionMigrationId as yi}from"./packem_shared/REPROJECTION_MIGRATION_PREFIX-Czcb6_mO.mjs";import{quoteIdentifier as Ni}from"./packem_shared/quoteIdentifier-CObIFRhb.mjs";import{runShardMigrations as Ui}from"./packem_shared/runShardMigrations-HaS2tHTS.mjs";import{stableStringify as qi}from"./packem_shared/stableStringify-DibjylKD.mjs";import{stableWireKey as Ki}from"./packem_shared/stableWireKey-D2US4k_J.mjs";export{oa as ADMIN_FUNCTIONS,aa as ADMIN_FUNCTION_PREFIX,d as AGGREGATE_SQL_FUNCTION,Gr as AGG_COUNT,qr as AGG_KEY,wr as AGG_VALUE,D as AUDIT_LOG_TABLE,Jn as BIGINT_KEY_DIGITS,H as CDC_LOG_TABLE,V as CDC_LOG_TABLE_SEQ_INDEX,z as CDC_META_TABLE,Ce as CLIENT_WATERMARK_TABLE,Ie as COMMIT_SEQ_FIELD,be as COMMIT_SEQ_TABLE,ka as CURSOR_PREFIX,ui as ConflictError,R as CountRlsUnsupportedError,br as DATA_MIGRATION_STATE_TABLE,ta as DEFAULT_FANOUT_TOPIC_LIMIT,Nt as DEFAULT_MAX_RELATION_KEYS,rn as DEFAULT_MAX_RELAYS,Yt as DEFAULT_PROMOTION_THRESHOLDS,Ei as DEFAULT_TRANSACTION_LIMITS,Kr as DOC_COLUMN,fo as DurableStreamRunner,na as FLAGS_FUNCTION_PREFIX,Vo as GEO_DEFAULT_PRECISION,ye as GLOBAL_SHAPE_SNAPSHOT_TABLE,ea as GlobalPollTick,we as IDEMPOTENCY_TABLE,Aa as MAIL_RETENTION,ga as MAIL_TABLE,Eo as MAX_DURABLE_STREAM_BYTES,xo as MAX_DURABLE_STREAM_CHUNKS,ia as MAX_PAGE_SIZE,Vn as MAX_SQL_ROWS,Pa as NotFoundError,y as NotUniqueError,on as OwnerRelay,Va as QUEUE_TABLE,$a as RANK_TIEBREAK,mt as REACTOR_STATE_TABLE,Dt as RELATED_DEFAULT_LIMIT,Pt as RELATED_DEPTH_DECAY,Ot as RELATED_MAX_DEPTH,Mt as RELATED_MAX_LIMIT,Oi as RELATION_EXISTS_KEY,la as RELATION_FUNCTION_PREFIX,Fi as REPROJECTION_MIGRATION_PREFIX,En as RLS_UNWRAP_SYMBOL,st as ReactiveCache,an as RelayMember,xn as RlsRequiredError,Or as SCAN_DEP,$e as SCHEDULE_OUTBOX_TABLE,Cn as SCHEMA_HISTORY_MAX_VERSIONS,dr as SEARCH_STATE_TABLE,ur as SHAPE_POKE_CURSOR_TABLE,yn as ShapeDiffCache,vn as ShardRunner,xi as TransactionHeadroomTracker,ht as UNVOUCHABLE_DEP,_i as VECTOR_BACKFILL_MAX_PAGES,Re as advanceClientWatermark,vr as aggUpsertSql,c as aggregateSqlFunction,f as aggregateTableName,Le as allocateCommitSeq,P as appendAuditEntry,Q as appendCdcChange,no as appendStreamChunk,Y as applyCdcChanges,vt as applyOnDelete,Na as applySelect,ue as archiveCdcSegment,Ma as armRestore,Bt as assertFlatPredicate,k as assertNoExplicitUndefined,zn as assertReadonly,Ut as assertShapeShardable,N as assertValidClientId,ai as awaitWsDrain,w as backfillAggregateIndexes,K as backfillRankIndexes,v as backfillSearchIndexes,X as backfillSearchIndexesForTable,Ii as backfillVectorIndexes,Zn as bigintSqlKey,zo as boundingBoxCenter,Qo as boundingBoxGeohashes,At as buildIndexRange,Un as buildPokeFrames,mn as buildReprojectionMigration,Ba as buildSeekBeforeWhere,Ua as buildSeekWhere,Ln as buildSettings,Mn as buildShapeDiff,j as bumpCdcEpoch,fe as cdcArchiveRewound,J as cdcCanVouchFor,Z as cdcForkedError,$ as cdcSeqLeavingRows,ee as cdcTouchesTables,re as cdcTrimmedError,io as claimStreamRun,jt as clampPromotionThresholds,_a as clearCapturedMail,Ve as clearMemoryTables,za as clearQueueMessages,E as coerceAggregateNumber,oe as compactCdcDocs,Li as compileWhereSql,je as computeRankPage,Gt as containsRelationPredicate,pn as countLegacyRows,Yo as coveringGeohashes,Me as createCompanionSync,Mr as createDependencyTracker,sa as createFanoutCounters,da as createGlobalPollCounters,Xr as createIndexSql,Tt as createReadFootprint,tn as createRelayLink,ln as createReplicaLink,kn as createShapeDiffCache,ca as createShapeProbeCounters,B as createShardCtxDb,pi as createSystemReader,ae as cursorBelowRetainedFloor,ho as decideDurableAttach,$n as decodeBigintSqlKey,Ga as decodeCursor,ei as decodeFloat64SqlKey,er as deferScheduleOutbox,ke as deleteGlobalShapeSnapshot,Ne as deleteGlobalShapeSnapshotsForConnection,fr as deleteShapePokeCursor,Er as deleteShapePokeCursorsForConnection,lo as deleteStreamRun,Fr as depKey,Ft as deriveRelationEdges,go as diffExternalSource,Gn as diffGlobalMembership,Xt as distinctValues,x as encodeAggregateKey,qa as encodeCursor,jo as encodeGeohash,et as encodePartitionKey,qn as encodeRowsPatch,O as ensureAuditTable,Ia as ensureMailTable,Co as envOptionalPositiveInt,Ro as envPositiveInt,wa as equalityPinnedFields,o as exportShardRows,ma as facetColumn,Wt as fanOutScalarCounts,yt as findRelated,pa as findStorageReferences,so as finishStreamRun,ri as float64SqlKey,h as foldAggregateTally,rr as forgetScheduleOutbox,qo as ftsCompanionDdl,wo as ftsPurgeDocument,Ko as ftsRowidMapName,vo as ftsUnmappedPage,Xo as ftsWriteDocument,sn as gateReplicaDispatch,Wr as geoTableName,Nn as globalShapeReadKey,Wo as groupUnmappedRows,hn as guardWriter,dn as handleReplicaControl,Ti as hasTrigger,Jo as haversineMeters,a as importShardRows,gt as indexKeysForRow,Dn as isDevEnvironment,Hr as isFtsAvailable,Qa as isLossyBody,ze as isMemoryTable,qt as isRelationPredicate,ko as isSoftDeleted,No as isSourceDue,Vr as jsonPath,zr as jsonPathSql,_t as keysTouchRanges,Io as liftSourceId,Qn as lintReadonlySql,pt as listReactorStates,Sa as listTables,Di as literalInList,Ct as markUnvouchableReads,rt as matchesRankStaticWhere,m as matchesStaticWhere,Po as materializeExternalRows,Oo as materializeExternalRowsIncremental,Qe as memoryTableNames,si as mergeChangedKeys,A as mergeWhere,te as migrateCdcLog,ne as migrateCdcMeta,Ae as migrateClientWatermark,De as migrateCommitSeq,co as migrateDurableStreams,Be as migrateGlobalShapeSnapshot,Ke as migrateIdempotency,St as migrateReactorState,or as migrateScheduleOutbox,cr as migrateSearchState,xr as migrateShapePokeCursor,ie as minCdcReplayableSeq,le as minCdcSeq,hr as minShapePokeCursor,Jt 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,n as parseImportShardArgs,g as planAggregateLookup,Zo as pointInBoundingBox,tr as probeScheduleOutbox,wn as projectColumns,Bo as pullExternalSourceIncrementalTick,Uo as pullExternalSourceTick,Qr as qualifiedJsonPath,Yr as qualifiedJsonPathSql,Ni as quoteIdentifier,ot as rankKeyFromDoc,at as rankPivotConditionSql,tt as rankTableName,dt as reactiveCacheKey,ut as reactorNeedsRun,T as readAggregateValue,Ee as readArchivedCdcChanges,M as readAuditLog,Fa as readBookmark,ba as readCapturedMail,xe as readCdcArchivedThrough,se as readCdcChangeKeys,de as readCdcChanges,ce as readCdcCursor,me as readCdcEpoch,ge as readClientWatermark,Pe as readCommitSeq,Pn as readDeployInfo,nr as readDueScheduleOutbox,Mo as readExternalSourceBaseline,Ue as readGlobalShapeSnapshot,ve as readIdempotent,Lr as readMigrationStatus,Ya as readQueueMessageById,ja as readQueueMessages,ft as readReactorState,Rn as readSchemaHistory,An as readSchemaVersion,mr as readSearchBackfillState,Tr as readShapePokeCursor,mo as readStreamChunks,po as readStreamRun,ua as readTablePage,La as recordCapturedMail,di as recordChangedKeys,fa as recordFanoutPass,Ea as recordGlobalPollPass,Ja as recordQueueMessages,ir as recordScheduleOutbox,gn as recordSchemaVersion,xa as recordShapeProbePass,Ht as relationHooks,Zt as relayCountFor,ro as renderSql,Sn as reprojectableFields,yi as reprojectionMigrationId,un as reprojectionTables,nt as resolveRankPartition,Je as resolveRankSeekTuple,wt as resolveRelationPredicates,Vt as resolveWith,jr as rowToDocument,Dr as runDataMigration,Nr as runDrizzle,Fo as runExternalSourceTick,Yn as runReadonlySql,zt as runRowValidators,Ui as runShardMigrations,Wn as runSocketPool,Br as runSql,Ci as runTriggers,Ai as selectExpiredIds,i as selectExportTables,_ as selectIndexForAggregate,I as selectIndexForCount,b as selectIndexForGroupBy,ha as selectMatchingIds,gr as selectShapeMembers,_r as selectShapeRows,In as serializeSqlValue,$t as shapeRoutingKey,va as softDeleteScope,it as sortColumnName,oo as sqliteInList,qi as stableStringify,Ki as stableWireKey,G as stripReservedPatchFields,ti as subscriptionFrames,ni as subscriptionListDeltas,Ta as summarizeFanoutTopics,Ca as summarizeSubscriptions,Jr as tableColumns,yr as tableFromDepKey,S as throwingScheduler,Xa as tiebreakDirectionFor,pe as trimCdcChanges,Xe as trimIdempotent,lr as trimScheduleOutbox,So as trimStreamRuns,Zr as tryRowToDocument,ii as trySendFrame,ao as unionAll,Wa as uniqueIndexFields,l as validateImportRow,bt as whereFilter,he as writeCdcArchivedThrough,Ge as writeGlobalShapeSnapshot,We as writeIdempotent,Et as writeReactorState,pr as writeSearchBackfillState,Cr as writeShapePokeCursor,Rr as writeShapePokeCursors,ci as writeTouchesMemo};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{LunoraError as I}from"@lunora/errors";import{m as x,n as y}from"./do-sql-BSoH-O04.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",backfillVectors:"__lunora_admin__:backfillVectors",backRelationCounts:"__lunora_admin__:backRelationCounts",cdcSync:"__lunora_admin__:cdcSync",clearCapturedMail:"__lunora_admin__:clearCapturedMail",clearQueueMessages:"__lunora_admin__:clearQueueMessages",clearTable:"__lunora_admin__:clearTable",createWorkflowInstance:"__lunora_admin__:createWorkflowInstance",deleteRows:"__lunora_admin__:deleteRows",describeTable:"__lunora_admin__:describeTable",describeTables:"__lunora_admin__:describeTables",explainIssue:"__lunora_admin__:explainIssue",exportShard:"__lunora_admin__:exportShard",facetColumn:"__lunora_admin__:facetColumn",findRelated:"__lunora_admin__:findRelated",getAdvisories:"__lunora_admin__:getAdvisories",getAdvisorProcedures:"__lunora_admin__:getAdvisorProcedures",getAuditLog:"__lunora_admin__:getAuditLog",getAuthMetrics:"__lunora_admin__:getAuthMetrics",getCapturedMail:"__lunora_admin__:getCapturedMail",getFanoutMetrics:"__lunora_admin__:getFanoutMetrics",getFunctionStats:"__lunora_admin__:getFunctionStats",getIssues:"__lunora_admin__:getIssues",getMetricHistory:"__lunora_admin__:getMetricHistory",getMetricSeries:"__lunora_admin__:getMetricSeries",listSubscriptions:"__lunora_admin__:listSubscriptions",listTableIndexes:"__lunora_admin__:listTableIndexes",listTablesIndexes:"__lunora_admin__:listTablesIndexes",getLogs:"__lunora_admin__:getLogs",getMetrics:"__lunora_admin__:getMetrics",getPitrBookmark:"__lunora_admin__:getPitrBookmark",getQueryInsights:"__lunora_admin__:getQueryInsights",getQueueMessages:"__lunora_admin__:getQueueMessages",getRequestLog:"__lunora_admin__:getRequestLog",getSecurityAudit:"__lunora_admin__:getSecurityAudit",getSettings:"__lunora_admin__:getSettings",getTraces:"__lunora_admin__:getTraces",getWorkflowInstanceStatus:"__lunora_admin__:getWorkflowInstanceStatus",ignoreIssue:"__lunora_admin__:ignoreIssue",importShard:"__lunora_admin__:importShard",listFlags:"__lunora_admin__:listFlags",listReactors:"__lunora_admin__:listReactors",listQueues:"__lunora_admin__:listQueues",lintSql:"__lunora_admin__:lintSql",listTables:"__lunora_admin__:listTables",listWorkflows:"__lunora_admin__:listWorkflows",maskPolicies:"__lunora_admin__:maskPolicies",migrationStatus:"__lunora_admin__:migrationStatus",patchRows:"__lunora_admin__:patchRows",pitrRestore:"__lunora_admin__:pitrRestore",rankBefore:"__lunora_admin__:rankBefore",rankPage:"__lunora_admin__:rankPage",readTablePage:"__lunora_admin__:readTablePage",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 o=s[f],i=typeof o=="string"?O(o):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),a=[],_=new Set(n);for(const s of r)for(const o of Object.keys(s))_.has(o)||(_.add(o),a.push(o));return{columns:[...n,...a],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)},ae=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:a}=r;return e.operator==="contains"?{params:[...a,B(e.value)],sql:N(n)}:e.value===null&&(e.operator==="eq"||e.operator==="ne")?{params:a,sql:`${n} IS ${e.operator==="ne"?"NOT ":""}NULL`}:{params:[...a,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]),a=t[3]===void 0?void 0:Number(t[3]);if(n!==void 0&&(n<1||n>12)||a!==void 0&&(a<1||a>31)||r<100)return;const _=Date.UTC(r,(n??1)-1,a??1);if(a!==void 0&&new Date(_).getUTCDate()!==a)return;let s;return a!==void 0?s=Date.UTC(r,(n??1)-1,a+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=[],a=[];if(t!==""&&e.length>0){const _=e.map(o=>N(d(o)));a.push(...e.map(()=>t));const s=X(t);if(s!==void 0)for(const o of e)_.push(`(${d(o)} >= ? AND ${d(o)} < ?)`),a.push(s.from,s.to);n.push(`(${_.join(" OR ")})`)}for(const _ of r??[]){const s=G(_,e);s!==void 0&&(n.push(`(${s.sql})`),a.push(...s.params))}return n.length===0?void 0:{parameters:a,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}`}},oe=(e,t)=>{const{table:r}=t;A(e,r);const n=C(Math.trunc(t.limit??D),1,h),a=Math.max(0,Math.trunc(t.offset??0)),_=d(r),s=M(e,_),o=t.search?.trim()??"",i=S=>{if(t.refs===void 0)return S;const T={};for(const k of S.columns){const w=t.refs[k];w!==void 0&&(T[k]=w)}return Object.keys(T).length>0?{...S,refs:T}:S},c=R(s,o,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 b;t.skipCount||(b=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,a).toArray();return i({...q(s,$),sqlColumns:s,total:b})},_e=(e,t)=>{const{table:r}=t;A(e,r);const n=C(Math.trunc(t.limit??h),1,h),a=d(r),_=M(e,a),s=t.search?.trim()??"",o=R(_,s,t.filters),i=[],c=[];o!==void 0&&(i.push(o.where),c.push(...o.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 ${a}${u}${l} LIMIT ?`,...c,n+1).toArray(),p=m.length>n,g=m.slice(0,n).map(b=>b.id);return{hasMore:p,ids:g}},K=(e,t,r)=>{const n=new Set(r.filter(_=>_!==f));if(!r.includes(f))return n;const a=e.exec(`SELECT ${d(f)} AS doc FROM ${t} LIMIT ?`,h).toArray();for(const{doc:_}of a){const s=typeof _=="string"?O(_):void 0;if(s!==void 0)for(const o of Object.keys(s))n.add(o)}return n},ie=(e,t)=>{const{column:r,table:n}=t;A(e,n);const a=d(n),_=M(e,a);if(!K(e,a,_).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 o=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 ${a}${u} GROUP BY ${s.expression} ORDER BY count DESC LIMIT ?`,...s.params,...l,...s.params,o+1).toArray();return{truncated:m.length>o,values:m.slice(0,o).map(g=>({count:Number(g.count),value:g.value}))}},ce=(e,t,r)=>{const n={},a=r.slice(0,h);for(const s of a)n[s]=[];if(a.length===0)return{references:n,storageColumns:t};const _=a.map(()=>"?").join(", ");for(const[s,o]of Object.entries(t)){if(E(s)||!P(e,s))continue;const i=d(s),c=M(e,i);for(const u of o){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,...a).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,a)=>{const _=Object.values(n.subs??{}).map(s=>({args:s.args,functionPath:s.functionPath,table:s.table}));return{admin:n.admin===!0,id:a,subscriptions:_}}),r=t.reduce((n,a)=>n+a.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 o of Object.values(s.shapes??{})){const i=o.name??"(unknown shape)";r.set(i,(r.get(i)??0)+1)}for(const o of s.whispers??[])n.set(o,(n.get(o)??0)+1)}const a=[...[...r].map(([s,o])=>({kind:"shape",subscribers:o,topic:s})),...[...n].map(([s,o])=>({kind:"whisper",subscribers:o,topic:s}))];return a.sort((s,o)=>o.subscribers-s.subscribers||s.topic.localeCompare(o.topic)),{peakSubscribers:a[0]?.subscribers??0,topics:a.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,ae as listTables,oe 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-C7TkRQqw.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",backfillVectors:"__lunora_admin__:backfillVectors",backRelationCounts:"__lunora_admin__:backRelationCounts",cdcSync:"__lunora_admin__:cdcSync",clearCapturedMail:"__lunora_admin__:clearCapturedMail",clearQueueMessages:"__lunora_admin__:clearQueueMessages",clearTable:"__lunora_admin__:clearTable",createWorkflowInstance:"__lunora_admin__:createWorkflowInstance",deleteRows:"__lunora_admin__:deleteRows",describeTable:"__lunora_admin__:describeTable",describeTables:"__lunora_admin__:describeTables",explainIssue:"__lunora_admin__:explainIssue",exportShard:"__lunora_admin__:exportShard",facetColumn:"__lunora_admin__:facetColumn",findRelated:"__lunora_admin__:findRelated",getAdvisories:"__lunora_admin__:getAdvisories",getAdvisorProcedures:"__lunora_admin__:getAdvisorProcedures",getAuditLog:"__lunora_admin__:getAuditLog",getAuthMetrics:"__lunora_admin__:getAuthMetrics",getCapturedMail:"__lunora_admin__:getCapturedMail",getFanoutMetrics:"__lunora_admin__:getFanoutMetrics",getFunctionStats:"__lunora_admin__:getFunctionStats",getIssues:"__lunora_admin__:getIssues",getMetricHistory:"__lunora_admin__:getMetricHistory",getMetricSeries:"__lunora_admin__:getMetricSeries",listSubscriptions:"__lunora_admin__:listSubscriptions",listTableIndexes:"__lunora_admin__:listTableIndexes",listTablesIndexes:"__lunora_admin__:listTablesIndexes",getLogs:"__lunora_admin__:getLogs",getMetrics:"__lunora_admin__:getMetrics",getPitrBookmark:"__lunora_admin__:getPitrBookmark",getQueryInsights:"__lunora_admin__:getQueryInsights",getQueueMessages:"__lunora_admin__:getQueueMessages",getRequestLog:"__lunora_admin__:getRequestLog",getSecurityAudit:"__lunora_admin__:getSecurityAudit",getSettings:"__lunora_admin__:getSettings",getTraces:"__lunora_admin__:getTraces",getWorkflowInstanceStatus:"__lunora_admin__:getWorkflowInstanceStatus",ignoreIssue:"__lunora_admin__:ignoreIssue",importShard:"__lunora_admin__:importShard",listFlags:"__lunora_admin__:listFlags",listReactors:"__lunora_admin__:listReactors",listQueues:"__lunora_admin__:listQueues",lintSql:"__lunora_admin__:lintSql",listTables:"__lunora_admin__:listTables",listWorkflows:"__lunora_admin__:listWorkflows",maskPolicies:"__lunora_admin__:maskPolicies",migrationStatus:"__lunora_admin__:migrationStatus",patchRows:"__lunora_admin__:patchRows",pitrRestore:"__lunora_admin__:pitrRestore",rankBefore:"__lunora_admin__:rankBefore",rankPage:"__lunora_admin__:rankPage",readTablePage:"__lunora_admin__:readTablePage",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 o=s[f],i=typeof o=="string"?O(o):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),a=[],_=new Set(n);for(const s of r)for(const o of Object.keys(s))_.has(o)||(_.add(o),a.push(o));return{columns:[...n,...a],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)},ae=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:a}=r;return e.operator==="contains"?{params:[...a,B(e.value)],sql:N(n)}:e.value===null&&(e.operator==="eq"||e.operator==="ne")?{params:a,sql:`${n} IS ${e.operator==="ne"?"NOT ":""}NULL`}:{params:[...a,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]),a=t[3]===void 0?void 0:Number(t[3]);if(n!==void 0&&(n<1||n>12)||a!==void 0&&(a<1||a>31)||r<100)return;const _=Date.UTC(r,(n??1)-1,a??1);if(a!==void 0&&new Date(_).getUTCDate()!==a)return;let s;return a!==void 0?s=Date.UTC(r,(n??1)-1,a+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=[],a=[];if(t!==""&&e.length>0){const _=e.map(o=>N(d(o)));a.push(...e.map(()=>t));const s=X(t);if(s!==void 0)for(const o of e)_.push(`(${d(o)} >= ? AND ${d(o)} < ?)`),a.push(s.from,s.to);n.push(`(${_.join(" OR ")})`)}for(const _ of r??[]){const s=G(_,e);s!==void 0&&(n.push(`(${s.sql})`),a.push(...s.params))}return n.length===0?void 0:{parameters:a,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}`}},oe=(e,t)=>{const{table:r}=t;A(e,r);const n=C(Math.trunc(t.limit??D),1,h),a=Math.max(0,Math.trunc(t.offset??0)),_=d(r),s=M(e,_),o=t.search?.trim()??"",i=S=>{if(t.refs===void 0)return S;const T={};for(const k of S.columns){const w=t.refs[k];w!==void 0&&(T[k]=w)}return Object.keys(T).length>0?{...S,refs:T}:S},c=R(s,o,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 b;t.skipCount||(b=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,a).toArray();return i({...q(s,$),sqlColumns:s,total:b})},_e=(e,t)=>{const{table:r}=t;A(e,r);const n=C(Math.trunc(t.limit??h),1,h),a=d(r),_=M(e,a),s=t.search?.trim()??"",o=R(_,s,t.filters),i=[],c=[];o!==void 0&&(i.push(o.where),c.push(...o.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 ${a}${u}${l} LIMIT ?`,...c,n+1).toArray(),p=m.length>n,g=m.slice(0,n).map(b=>b.id);return{hasMore:p,ids:g}},K=(e,t,r)=>{const n=new Set(r.filter(_=>_!==f));if(!r.includes(f))return n;const a=e.exec(`SELECT ${d(f)} AS doc FROM ${t} LIMIT ?`,h).toArray();for(const{doc:_}of a){const s=typeof _=="string"?O(_):void 0;if(s!==void 0)for(const o of Object.keys(s))n.add(o)}return n},ie=(e,t)=>{const{column:r,table:n}=t;A(e,n);const a=d(n),_=M(e,a);if(!K(e,a,_).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 o=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 ${a}${u} GROUP BY ${s.expression} ORDER BY count DESC LIMIT ?`,...s.params,...l,...s.params,o+1).toArray();return{truncated:m.length>o,values:m.slice(0,o).map(g=>({count:Number(g.count),value:g.value}))}},ce=(e,t,r)=>{const n={},a=r.slice(0,h);for(const s of a)n[s]=[];if(a.length===0)return{references:n,storageColumns:t};const _=a.map(()=>"?").join(", ");for(const[s,o]of Object.entries(t)){if(E(s)||!P(e,s))continue;const i=d(s),c=M(e,i);for(const u of o){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,...a).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,a)=>{const _=Object.values(n.subs??{}).map(s=>({args:s.args,functionPath:s.functionPath,table:s.table}));return{admin:n.admin===!0,id:a,subscriptions:_}}),r=t.reduce((n,a)=>n+a.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 o of Object.values(s.shapes??{})){const i=o.name??"(unknown shape)";r.set(i,(r.get(i)??0)+1)}for(const o of s.whispers??[])n.set(o,(n.get(o)??0)+1)}const a=[...[...r].map(([s,o])=>({kind:"shape",subscribers:o,topic:s})),...[...n].map(([s,o])=>({kind:"whisper",subscribers:o,topic:s}))];return a.sort((s,o)=>o.subscribers-s.subscribers||s.topic.localeCompare(o.topic)),{peakSubscribers:a[0]?.subscribers??0,topics:a.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,ae as listTables,oe as readTablePage,ge as recordFanoutPass,fe as recordGlobalPollPass,pe as recordShapeProbePass,_e as selectMatchingIds,he as summarizeFanoutTopics,ue as summarizeSubscriptions};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import"./effective-kind-BmG_zCAy.mjs";import{A as l,a as i,b as n,D as m,n as d,c,d as p,l as q,o as u,k as G,g as f,i as A,j as D,e as S,q as _,f as h,r as C,t as O,h as b}from"./do-sql-C7TkRQqw.mjs";import{quoteIdentifier as x}from"./quoteIdentifier-CObIFRhb.mjs";import"./wire-codec-C-FpWm52.mjs";import"./runDrizzle-CfKnGpV2.mjs";import"./BIGINT_KEY_DIGITS-C9a7Ix7k.mjs";import{serializeSqlValue as J}from"./serializeSqlValue-BbZ5hKM7.mjs";export{l as AGG_COUNT,i as AGG_KEY,n as AGG_VALUE,m as DOC_COLUMN,d as DOC_ORIGINALS_KEY,c as aggUpsertSql,p as createIndexSql,q as decodeDocJson,u as decodeGroupKeyValue,G as encodeDocJson,f as geoTableName,A as isFtsAvailable,D as jsonPath,S as jsonPathSql,_ as qualifiedJsonPath,h as qualifiedJsonPathSql,x as quoteIdentifier,C as rowToDocument,J as serializeSqlValue,O as tableColumns,b as tryRowToDocument};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{LunoraError as g}from"@lunora/errors";import{t as o}from"./base64-DfpzS4o_.mjs";import{e as s}from"./effective-kind-BmG_zCAy.mjs";const i=39,f="0",c="1",a=t=>Array.from(t,e=>String(9-Number(e))).join(""),d=t=>{const e=t<0n,n=(e?-t:t).toString();if(n.length>i)throw new g("BAD_REQUEST",`bigint ${t.toString()} has ${String(n.length)} digits, over the ${String(i)}-digit limit for a queryable column`);const r=n.padStart(i,"0");return e?f+a(r):c+r},l=/^\d+$/u,b=t=>{if(t.length!==i+1)return;const e=t.slice(0,1),n=t.slice(1);if(l.test(n))return e===c?BigInt(n):e===f?-BigInt(a(n)):void 0},m=/^[\da-f]{16}$/u,p=t=>{const e=new DataView(new ArrayBuffer(8));e.setFloat64(0,t===0?0:t,!1);let n=e.getUint32(0,!1),r=e.getUint32(4,!1);return(n&2147483648)===0?n=(n^2147483648)>>>0:(n=~n>>>0,r=~r>>>0),n.toString(16).padStart(8,"0")+r.toString(16).padStart(8,"0")},E=t=>{if(!m.test(t))return;let e=Number.parseInt(t.slice(0,8),16),n=Number.parseInt(t.slice(8),16);(e&2147483648)===0?(e=~e>>>0,n=~n>>>0):e=(e^2147483648)>>>0;const r=new DataView(new ArrayBuffer(8));return r.setUint32(0,e,!1),r.setUint32(4,n,!1),r.getFloat64(0,!1)},h=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,u=t=>{const e=s(t);return e==="bigint"||e==="bytes"},w=t=>{const e=s(t);return u(t)||e==="any"||e==="union"||e==="from"};export{i as BIGINT_KEY_DIGITS,d as bigintSqlKey,b as decodeBigintSqlKey,E as decodeFloat64SqlKey,p as float64SqlKey,u as isProjectedKind,w as mayHoldProjectedValue,h as sqlComparableProjection};
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{LunoraError as R}from"@lunora/errors";import{sql as t}from"drizzle-orm";import{quoteIdentifier as C}from"./quoteIdentifier-CObIFRhb.mjs";import{runSql as A,runDrizzle as n}from"./runDrizzle-CfKnGpV2.mjs";import{k as m,l as u}from"./do-sql-
|
|
1
|
+
import{LunoraError as R}from"@lunora/errors";import{sql as t}from"drizzle-orm";import{quoteIdentifier as C}from"./quoteIdentifier-CObIFRhb.mjs";import{runSql as A,runDrizzle as n}from"./runDrizzle-CfKnGpV2.mjs";import{k as m,l as u}from"./do-sql-C7TkRQqw.mjs";import{ConflictError as I}from"./ConflictError-C8GtJmjS.mjs";const s="__cdc_log",p=`INSERT INTO ${C(s)} (ts, ${C("table")}, id, op, doc) VALUES (?, ?, ?, ?, ?)`,$="__cdc_log_table_seq",N="__cdc_log_table_id_seq",y=(e,o={})=>{n(e,t`CREATE TABLE IF NOT EXISTS ${t.identifier(s)} (
|
|
2
2
|
seq INTEGER PRIMARY KEY AUTOINCREMENT,
|
|
3
3
|
ts REAL NOT NULL,
|
|
4
4
|
${t.identifier("table")} TEXT NOT NULL,
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{LunoraError as u}from"@lunora/errors";import{i as v,R as N}from"./relation-operators-BEg-CvCH.mjs";import{isMemoryTable as y}from"./clearMemoryTables-C5Wivufe.mjs";import{distinctValues as $}from"./applyOnDelete-7JZ4vR9r.mjs";import{RELATION_EXISTS_KEY as j}from"./RELATION_EXISTS_KEY-CFUhnZSZ.mjs";const E={every:{kind:"many",negateChild:!0,negated:!0},is:{kind:"one",negated:!1},isNot:{kind:"one",negated:!0,nullDisjunct:!0},none:{kind:"many",negated:!0},some:{kind:"many",negated:!1}},O=e=>N.has(e)?e:void 0,R=e=>{const t=O(e),r=t===void 0?void 0:E[t];if(!r)throw new u("INTERNAL",`unknown relation operator "${e}"`);return r},S=e=>e.kind==="one"?{clause:e.field,project:e.references}:{clause:e.references,project:e.field},M=5e3,h=Symbol("relation-key-overflow"),m=e=>Array.isArray(e)?e.map(t=>t??{}):[],w=e=>{if(e.length===1){const[t]=e;return t??{}}return e.length===0?{}:{AND:e}},b=e=>v(e),l=(e,t,r)=>{const n=t.tables[r]?.relationMap??{};return Object.keys(e).some(s=>{const a=e[s];return s==="AND"||s==="OR"?m(a).some(o=>l(o,t,r)):s==="NOT"?l(a??{},t,r):!!n[s]&&b(a)})},H=(e,t,r,n)=>{if(e&&l(e,t,r))throw new u("INTERNAL",`relation-crossing predicates are not supported in ${n}() — use them in findMany/findFirst or an RLS read policy`)},L=async(e,t,r,n,s)=>{const a=await d(t,e.table,n),{page:o}=await n.fetcher(e.table,{baseWhere:n.relationBaseWhere?.(e.table),relationBaseWhere:n.relationBaseWhere,where:a}),i=$(o,r);if(i.length>n.maxRelationKeys){if(s)return h;throw new u("INTERNAL",`relation predicate on "${e.table}" matched ${String(i.length)} rows, exceeding the ${String(n.maxRelationKeys)}-key limit; narrow the predicate (a same-shard EXISTS push-down lifts this cap)`)}return i},P=async(e,t,r,n,s)=>{const a=R(e),{clause:o,project:i}=S(t),c=await L(t,a.negateChild?{NOT:r}:r,i,n,s);return c===h?h:a.negated?a.nullDisjunct?{OR:[{[o]:{notIn:c}},{[o]:{isNull:!0}}]}:{[o]:{notIn:c}}:{[o]:{in:c}}},p=async(e,t,r,n,s)=>{const a=R(e),o=s.relationBaseWhere?.(t.table),i=a.negateChild?{NOT:r}:r,T={childWhere:await d(o?{AND:[o,i]}:i,t.table,s),negated:a.negated,parentTable:n,relation:t};return{[j]:T}},_=(e,t,r)=>{const n=O(e),s=n===void 0?void 0:E[n];if(s&&s.kind!==r.kind)throw new u("INTERNAL",`relation operator "${e}" requires a to-${s.kind} relation, but "${t}" is to-${r.kind}`)},k=async(e,t,r,n,s)=>{const a=[];for(const o of Object.keys(r)){_(o,e,t);const i=r[o]??{},c=s.canPushExists?.(t)??!1;if(c&&s.existsPushMode==="always"){a.push(await p(o,t,i,n,s));continue}const f=await P(o,t,i,s,c);f===h?a.push(await p(o,t,i,n,s)):a.push(f)}return w(a)},I=async(e,t,r,n)=>{if(e==="AND"||e==="OR"){const a=[];for(const o of m(t))a.push(await d(o,r,n));return{[e]:a}}if(e==="NOT")return{NOT:await d(t??{},r,n)};const s=n.schema.tables[r]?.relationMap?.[e];return s&&b(t)?k(e,s,t,r,n):{[e]:t}},d=async(e,t,r)=>{const n=[];for(const s of Object.keys(e))n.push(await I(s,e[s],t,r));return w(n)},Y=async(e,t)=>!e||!l(e,t.schema,t.tableName)?e:d(e,t.tableName,{canPushExists:t.canPushExists,existsPushMode:t.existsPushMode??"auto",fetcher:t.fetcher,maxRelationKeys:t.maxRelationKeys??M,relationBaseWhere:t.relationBaseWhere,schema:t.schema}),g=(e,t,r)=>{for(const n of e){const s=A(n,t,r);if(s)return s}},D=(e,t,r,n)=>{if(e==="AND"||e==="OR")return g(m(t),r,n);if(e==="NOT")return g([t??{}],r,n);const s=r.tables[n]?.relationMap?.[e];if(!(!s||!b(t)))return r.tables[s.table]?.shardMode?.kind==="shardBy"?{kind:"shard",relation:e,target:s.table}:y(r.tables[s.table])?{kind:"memory",relation:e,target:s.table}:g(Object.values(t),r,s.table)},A=(e,t,r)=>{for(const n of Object.keys(e)){const s=D(n,e[n],t,r);if(s)return s}},q=(e,t,r)=>{if(y(t.tables[r]))throw Object.assign(new Error(`shape on "${r}" replicates from the changelog, which never records a .memory() table — the shape would seed once and never update again. Fix it by (a) dropping .memory() from "${r}" so its writes reach the changelog, or (b) reading it through a live query (\`useQuery\`), which refreshes off the changed-table set rather than the log.`),{code:"SHAPE_MEMORY_TABLE",name:"LunoraError",status:400});if(!e)return;const n=A(e,t,r);if(n)throw n.kind==="memory"?Object.assign(new Error(`shape on "${r}" joins the .memory() table "${n.target}" via relation "${n.relation}" — writes to a .memory() table never reach the changelog, so the shape is never told its membership changed and would serve stale rows indefinitely. Fix it by (a) dropping .memory() from "${n.target}", or (b) reading it through a live query (\`useQuery\`), which refreshes off the changed-table set rather than the log.`),{code:"SHAPE_MEMORY_TABLE",name:"LunoraError",status:400}):Object.assign(new Error(`shape on "${r}" joins the sharded table "${n.target}" via relation "${n.relation}" — a live shape cannot replicate rows that live in another shard's Durable Object. Fix it by (a) denormalizing the joined columns into "${r}", or (b) moving "${n.target}" to .global() so it is served through the latency-tiered D1 shape tier.`),{code:"SHAPE_CROSS_SHARD_JOIN",name:"LunoraError",status:400})};export{M as DEFAULT_MAX_RELATION_KEYS,H as assertFlatPredicate,q as assertShapeShardable,l as containsRelationPredicate,b as isRelationPredicate,Y as resolveRelationPredicates};
|
|
@@ -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-CTuiPWMD.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 lt}from"./MAX_TOKEN_LENGTH-BakL9FUy-B3VwYY8C.mjs";import{S as En,l as Fe,h as mn}from"./fts-companion-B7jllLhZ.mjs";import{sql as c}from"drizzle-orm";import{d as Sn}from"./wire-codec-C-FpWm52.mjs";import{stableWireKey as It}from"./stableWireKey-D2US4k_J.mjs";import{throwingScheduler as _n,aggregateSqlFunction as qe,normalizeCountArgument as Rn}from"./AGGREGATE_SQL_FUNCTION-DDEoMnJR.mjs";import{aggregateTableName as Ye,encodeAggregateKey as Xe,readAggregateValue as Ze}from"./aggregateTableName-C7o-gpms.mjs";import{mergeWhere as N,CountRlsUnsupportedError as et,selectIndexForGroupBy as Tn,selectIndexForCount as vn,selectIndexForAggregate as An}from"./CountRlsUnsupportedError-BvsDqfO2.mjs";import{backfillSearchIndexesForTable as In,searchIndexCoversTable as Cn}from"./backfillAggregateIndexes-yFyVVEHD.mjs";import{backfillAggregateIndexes as Or,backfillRankIndexes as Nr,backfillSearchIndexes as jr}from"./backfillAggregateIndexes-yFyVVEHD.mjs";import{appendCdcChange as xn,readCdcDocAtOrBefore as bn}from"./CDC_LOG_TABLE-C5XCNb2J.mjs";import{CDC_LOG_TABLE as Qr,applyCdcChanges as Vr,bumpCdcEpoch as zr,cdcCanVouchFor as Jr,cdcForkedError as Yr,cdcSeqLeavingRows as Xr,cdcTouchesTables as Zr,cdcTrimmedError as ei,compactCdcDocs as ti,cursorBelowRetainedFloor as ni,minCdcReplayableSeq as oi,minCdcSeq as ri,readCdcChangeKeys as ii,readCdcChanges as si,readCdcCursor as ci,readCdcEpoch as ai,trimCdcChanges as di}from"./CDC_LOG_TABLE-C5XCNb2J.mjs";import{allocateCommitSeq as Mn,COMMIT_SEQ_FIELD as Dn}from"./COMMIT_SEQ_FIELD-D6uMUaiR.mjs";import{createCompanionSync as kn}from"./createCompanionSync-CGVFf7GK.mjs";import{isMemoryTable as Ct}from"./clearMemoryTables-C5Wivufe.mjs";import{computeRankPage as xt}from"./computeRankPage-Bg1_6fPP.mjs";import{SCAN_DEP as O}from"./SCAN_DEP-D7qE3iUe.mjs";import{runSql as Te,runDrizzle as j}from"./runDrizzle-CfKnGpV2.mjs";import{j as Ge,D as ne,r as Se,k as de,b as Be,A as tt,a as We,e as se,o as Ln,t as Zt,q as bt,i as Fn,h as en,g as qn}from"./do-sql-C7TkRQqw.mjs";import{renderSql as tn,unionAll as ut,WORKERD_SQLITE_LIMITS as nn,sqliteInList as Bn}from"./param-DlozcSQu.mjs";import{coveringGeohashes as Wn,boundingBoxGeohashes as Pn,haversineMeters as Un,pointInBoundingBox as Gn}from"./GEO_DEFAULT_PRECISION-CqpQZ-J_.mjs";import{NotFoundError as Hn}from"./NotFoundError-BhF7FeFr.mjs";import{tiebreakDirectionFor as On,encodeCursor as He,normalizeOrderKeys as st,uniqueIndexFields as on,buildSeekWhere as rn,decodeCursor as ct,buildSeekBeforeWhere as Nn,softDeleteScope as ue,equalityPinnedFields as jn,applySelect as Mt}from"./CURSOR_PREFIX-Bn8SFoGd.mjs";import{rankTableName as Dt,sortColumnName as kt,resolveRankPartition as Kn,encodePartitionKey as Qn,RANK_TIEBREAK as Vn,rankPivotConditionSql as zn}from"./RANK_TIEBREAK-B0_x8iev.mjs";import{UNVOUCHABLE_DEP as Lt}from"./UNVOUCHABLE_DEP-C68htACn.mjs";import{indexKeysForRow as Jn,buildIndexRange as Yn}from"./buildIndexRange-6nIZDf4m.mjs";import{r as Oe,j as _e,c as ee,t as Ne,i as Ft}from"./where-sql-x1YKldcq.mjs";import{serializeSqlValue as ce}from"./serializeSqlValue-BbZ5hKM7.mjs";import{quoteIdentifier as ve}from"./quoteIdentifier-CObIFRhb.mjs";import{whereOfFilter as Xn,isPushableWhere as Zn}from"./whereFilter-CLmm3TFe.mjs";import{deriveRelationEdges as eo,findRelated as to}from"./RELATED_DEFAULT_LIMIT-B9PH28Pn.mjs";import{assertFlatPredicate as nt,resolveRelationPredicates as qt}from"./DEFAULT_MAX_RELATION_KEYS-fYrcrp5Z.mjs";import{runRowValidators as ot,resolveWith as Bt,relationHooks as Wt,applyOnDelete as no,fanOutScalarCounts as oo}from"./applyOnDelete-7JZ4vR9r.mjs";import{guardWriter as ro}from"./RLS_UNWRAP_SYMBOL-BwwTbz3Q.mjs";import{mayHoldProjectedValue as io}from"./BIGINT_KEY_DIGITS-C9a7Ix7k.mjs";import{createSystemReader as so}from"./createSystemReader-DcDLFfC-.mjs";import{ConflictError as Re}from"./ConflictError-C8GtJmjS.mjs";import{runTriggers as co}from"./hasTrigger-CjlwI4le.mjs";import{CLIENT_WATERMARK_TABLE as ui,advanceClientWatermark as fi,migrateClientWatermark as hi,readClientWatermark as wi}from"./CLIENT_WATERMARK_TABLE-BdKYbah0.mjs";import{GLOBAL_SHAPE_SNAPSHOT_TABLE as gi,deleteGlobalShapeSnapshot as $i,deleteGlobalShapeSnapshotsForConnection as yi,migrateGlobalShapeSnapshot as Ei,readGlobalShapeSnapshot as mi,writeGlobalShapeSnapshot as Si}from"./GLOBAL_SHAPE_SNAPSHOT_TABLE-wWaEWj5f.mjs";import{IDEMPOTENCY_TABLE as Ri,readIdempotent as Ti,trimIdempotent as vi,writeIdempotent as Ai}from"./IDEMPOTENCY_TABLE-DKrXVEUe.mjs";import{runShardMigrations as Ci}from"./runShardMigrations-HaS2tHTS.mjs";import{S as bi}from"./ctx-db-search-state-fIiMVPXO.mjs";import{selectShapeMembers as Di,selectShapeRows as ki}from"./selectShapeMembers-CIfYJUcu.mjs";const ao=n=>{const r=atob(n),o=Uint8Array.from(r,d=>d.codePointAt(0)??0);return new TextDecoder().decode(o)},lo=()=>new $("BAD_REQUEST","invalid cursor"),Pt=16,Ut=8,Y=1024,ft=(n,r)=>r.query(n),uo=(n,r)=>{if(n.length===0)return 0;let o=0;for(const[d,s]of r.entries()){const w=d===r.length-1;let E=0;for(const A of n)(w?A.startsWith(s):A===s)&&(E+=1);if(E===0)return 0;o+=E}return o},fo=(n,r)=>{if(!r)return{exact:!0,lower:n,upper:n};const o=[...n].at(-1)??"",d=(o.codePointAt(0)??0)+1;if(d>=55296&&d<=57343||d>1114111)return{exact:!0,lower:n,upper:n};const s=n.slice(0,n.length-o.length);return{exact:!1,lower:n,upper:s+String.fromCodePoint(d)}},ho=(n,r,o)=>{const d={eq:(s,w)=>{if(!n.definition.filterFields?.includes(s))throw new $("INTERNAL",`field "${s}" is not a filter field of search index "${n.indexName}" on table "${r}"`);if(n.filters.length>=Ut)throw new $("BAD_REQUEST",`search index "${n.indexName}" on table "${r}": at most ${String(Ut)} .eq() filters are supported per search query`);return n.filters.push({field:s,value:w}),d},search:(s,w)=>{const E=n;if(s!==E.definition.field)throw new $("INTERNAL",`search index "${E.indexName}" on table "${r}" indexes "${E.definition.field}", not "${s}"`);const A=ft(w,o).length;if(A>Pt)throw new $("BAD_REQUEST",`search index "${E.indexName}" on table "${r}": at most ${String(Pt)} search terms are supported (got ${String(A)})`);return E.field=s,E.query=w,E.hasQuery=!0,d}};return d},wo=n=>{if(n.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()`)},po=n=>Math.min(n.offset+n.numItems+1,Y),go=n=>btoa(`search:${String(n)}`),$o=n=>{let r;try{r=ao(n)}catch{return}if(!r.startsWith("search:"))return;const o=Number(r.slice(7));return Number.isInteger(o)&&o>=0?o:void 0},yo=n=>{if(typeof n.endCursor=="string")throw new $("BAD_REQUEST","bounded (endCursor) pagination is not supported on search queries — relevance order has no stable range boundary");if(!Number.isFinite(n.numItems))throw new $("BAD_REQUEST",`search pagination needs a finite numItems, got ${String(n.numItems)}`);const r=Math.max(0,Math.floor(n.numItems)),o=n.cursor?$o(n.cursor):0;if(o===void 0)throw lo();if(o+r>=Y)throw new $("BAD_REQUEST",`search pagination reaches the ${String(Y)}-document limit (offset ${String(o)} + ${String(r)} requested) — a page must end below the cap so the probe row that answers \`hasMore\` still fits: retry with numItems ${String(Math.max(1,Y-o-1))} or fewer, or narrow the query or the filters instead`);return{numItems:r,offset:o}},Eo=(n,r)=>{const o=r.offset+r.numItems,d=r.numItems>0&&n.length>o;return{continueCursor:d?go(o):null,isDone:!d,page:n.slice(r.offset,o)}},mo=n=>{if(n===void 0)return Y+1;if(!Number.isFinite(n))return Y;const r=Math.max(0,Math.floor(n));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},So=32,_o=1024,sn=(n,r,o,d)=>{const s=`SELECT id, _creationTime, ${ve(ne)} FROM ${ve(n)}`,w=`ORDER BY ${o}${d===void 0?"":` LIMIT ${String(d)}`}`;return r===void 0?Oe(`${s} ${w}`):_e(`${s} WHERE `,r,` ${w}`)},ht={fieldRef:n=>Oe(Ge(n)),serialize:ce},cn=n=>{const r=n.map(o=>`${Ge(o.field)} ${o.direction==="desc"?"DESC":"ASC"}`);return n.some(o=>o.field==="_id"||o.field==="id")||r.push(`${Ge("id")} ${On(n)==="desc"?"DESC":"ASC"}`),r.join(", ")},Ro={"<":"lt","<=":"lte","=":"eq",">":"gt",">=":"gte"},an=n=>new Set(n.sqlConditions.filter(r=>r.comparator==="=").map(r=>r.field)),To=n=>{const r=an(n);let o=0;for(;o<n.indexFields.length&&r.has(n.indexFields[o]??"");)o+=1;return n.indexFields.slice(o)},vo=(n,r)=>{const o=n.order,d=To(n),{shape:s}=r;return d.length>0?st(d.map(w=>({[w]:o})),s,{pinned:an(n),uniqueBy:on(r.indexes,s)}):st([{_creationTime:o}],s)},Ao=(n,r,o,d)=>{const s=n.sqlConditions.map(w=>({[w.field]:{[Ro[w.comparator]??"eq"]:w.value}}));if(o&&s.push(rn(r,ct(o))),d&&s.push(Nn(r,ct(d))),s.length!==0)return s.length===1?s[0]:{AND:s}},Io=n=>{if(n.want!==void 0)return n.selective?Math.max(n.want,So):n.want},at=(n,r,o,d,s,w,E)=>{const A=vo(d,o),g=cn(A),b=[],{filters:x,want:R}=w;let T=w.cursor??void 0,M=Io(w);if(R===0)return{documents:b,orderKeys:A};for(;;){const B=ee(Ao(d,A,T,w.endCursor),ht,Ne),P=sn(r,s&&B?_e(B," AND ",s):s??B,g,M),L=Te(n,P.text,...P.params).toArray();let q={};E(L.length);for(const C of L)if(q=Se(C),x.every(K=>K(q))&&b.push(q)===R)return{documents:b,orderKeys:A};if(M===void 0||L.length<M)return{documents:b,orderKeys:A};T=He(q,A),M=Math.max(M,Math.min(M*2,_o))}},Co=(n,r,o,d,s,w,E,A)=>{const g=Math.max(0,Math.floor(s.numItems));if(typeof s.endCursor=="string"){const{documents:B,orderKeys:P}=at(n,r,o,d,w,{cursor:s.cursor,endCursor:s.endCursor,filters:E.all,selective:E.selective,want:void 0},A),L=B.length>=2?B[Math.floor(B.length/2)-1]:void 0;return{continueCursor:s.endCursor,isDone:!0,page:B,splitCursor:L?He(L,P):null}}const{documents:b,orderKeys:x}=at(n,r,o,d,w,{cursor:s.cursor,filters:E.all,selective:E.selective,want:g+1},A),R=b.length>g,T=R?b.slice(0,g):b,M=T.at(-1);return{continueCursor:R&&M?He(M,x):null,isDone:!R,page:T}},je=n=>{const r=new Map;return o=>{const d=r.get(o);if(d!==void 0)return d;const s=n(ve(o));return r.set(o,s),s}},fe=ve(ne),xo=je(n=>`INSERT INTO ${n} (id, _creationTime, ${fe}) VALUES (?, ?, ?)`),Gt=je(n=>`UPDATE ${n} SET ${fe} = ? WHERE id = ? AND ${fe} = ?`),bo=je(n=>`UPDATE ${n} SET _creationTime = ?, ${fe} = ? WHERE id = ? AND ${fe} = ?`),Mo=je(n=>`DELETE FROM ${n} WHERE id = ? AND ${fe} = ?`),Do="SELECT changes() AS changed",Ht=new Map,ko="",Lo=n=>{const r=JSON.stringify(n),o=Ht.get(r);if(o!==void 0)return o;const d=n.map(w=>c`SELECT ${c.raw(`'${w.replaceAll("'","''")}'`)} AS __t__, id, _creationTime, ${c.identifier(ne)} FROM ${c.identifier(w)} WHERE id = ${ko}`),{sql:s}=tn("sqlite",c`${ut(d)} LIMIT 1`);return Ht.set(r,s),s},Fo=(n,r)=>r.map(()=>n),qo=/^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/iu,Bo=n=>{if(!qo.test(n))throw new $("INTERNAL",`invalid clientId ${JSON.stringify(n)}: a client-supplied row id must be a UUID`)},Ot=50,dn=500,Pe=Math.floor(nn.boundParams/3),Ee=nn.boundParams,Wo=128,le=(n,r,o)=>{const d=r??dn;if(n>d)throw new $("BATCH_LIMIT_EXCEEDED",`${o}: batch of ${String(n)} exceeds the limit of ${String(d)} (raise options.limit or chunk the call)`,{status:400})},Po=n=>{const r={eq:(o,d)=>(n.sqlConditions.push({comparator:"=",field:o,value:d}),r),gt:(o,d)=>(n.sqlConditions.push({comparator:">",field:o,value:d}),r),gte:(o,d)=>(n.sqlConditions.push({comparator:">=",field:o,value:d}),r),lt:(o,d)=>(n.sqlConditions.push({comparator:"<",field:o,value:d}),r),lte:(o,d)=>(n.sqlConditions.push({comparator:"<=",field:o,value:d}),r)};return r},Uo=n=>Math.max(n,Y),ln=(n,r)=>{const o=n.filters.map(d=>c`${se(d.field)} = ${ce(d.value)}`);return r&&o.push(r),o},Go=(n,r,o,d,s)=>{const w=ft(o.query,lt(o.definition.language));if(w.length===0)return[];const E=En(r,o.indexName),A=`${E}__vocab`,g=w.length-1,b=w.map((P,L)=>{const q=fo(P,L===g),C=q.exact?c`${c.identifier("term")} = ${q.lower}`:c`${c.identifier("term")} >= ${q.lower} AND ${c.identifier("term")} < ${q.upper}`;return c`SELECT ${c.identifier("doc")}, ${c.raw(String(L))} AS ${c.identifier("__term__")}, COUNT(*) AS ${c.identifier("__n__")} FROM ${c.identifier(A)} WHERE ${C} GROUP BY ${c.identifier("doc")}`}),x=w.map((P,L)=>c`SUM(CASE WHEN u.${c.identifier("__term__")} = ${c.raw(String(L))} THEN u.${c.identifier("__n__")} ELSE 0 END)`),R=c`SELECT f.${c.identifier(Fe)} AS ${c.identifier(Fe)}, ${c.join(x,c` + `)} AS ${c.identifier("__score__")} FROM (${ut(b)}) u JOIN ${c.identifier(E)} f ON f.rowid = u.${c.identifier("doc")} GROUP BY f.${c.identifier(Fe)} HAVING ${c.join(x.map(P=>c`${P} > 0`),c` AND `)}`,T=ln(o,s);let M=c`SELECT m.id, m._creationTime, m.${c.identifier(ne)}, s.${c.identifier("__score__")} AS ${c.identifier("__score__")} FROM (${R}) s JOIN ${c.identifier(r)} m ON m.id = s.${c.identifier(Fe)}`;T.length>0&&(M=c`${M} WHERE ${c.join(T,c` AND `)}`),M=c`${M} ORDER BY s.${c.identifier("__score__")} DESC, m._creationTime DESC, m.id ASC LIMIT ${c.raw(String(d))}`;const B=[];for(const P of j(n,M)){const L=en(P);if(L){const q=P.__score__;B.push({document:L,score:typeof q=="number"?q:Number(q??0)})}}return B},Ho=(n,r,o,d,s)=>{const w=lt(o.definition.language),E=ft(o.query,w);if(E.length===0)return[];const A=ln(o,s);let g=c`SELECT id, _creationTime, ${c.identifier(ne)} FROM ${c.identifier(r)}`;A.length>0&&(g=c`${g} WHERE ${c.join(A,c` AND `)}`),g=c`${g} ORDER BY _creationTime DESC, id ASC LIMIT ${c.raw(String(Uo(d)))}`;const b=j(n,g).toArray(),x=[];for(const R of b){const T=en(R);if(!T)continue;const M=uo(mn(T,o.definition),E);M>0&&x.push({creationTime:typeof T._creationTime=="number"?T._creationTime:0,doc:T,id:typeof T._id=="string"?T._id:"",score:M})}return x.sort((R,T)=>T.score-R.score||T.creationTime-R.creationTime||R.id.localeCompare(T.id)),x.slice(0,d).map(R=>({document:R.doc,score:R.score}))},rt=(n,r,o,d)=>{if(!Number.isFinite(n.lat)||n.lat<-90||n.lat>90||!Number.isFinite(n.lng)||n.lng<-180||n.lng>180)throw new $("BAD_REQUEST",`geo index "${d}" on table "${o}": ${r} must have a finite lat in [-90, 90] and lng in [-180, 180]`)},Oo=(n,r)=>{const o=n,d={near:(s,w)=>{if(o.within)throw new $("INTERNAL",`geo index "${o.indexName}" on table "${r}": call .near() or .within(), not both`);if(rt(s,".near() point",r,o.indexName),!Number.isFinite(w)||w<=0)throw new $("BAD_REQUEST",`geo index "${o.indexName}" on table "${r}": .near() radiusMeters must be a finite number > 0, got ${String(w)}`);return o.near={point:{lat:s.lat,lng:s.lng},radiusMeters:w},d},within:s=>{if(o.near)throw new $("INTERNAL",`geo index "${o.indexName}" on table "${r}": call .near() or .within(), not both`);if(rt(s.sw,".within() sw corner",r,o.indexName),rt(s.ne,".within() ne corner",r,o.indexName),s.sw.lat>s.ne.lat)throw new $("BAD_REQUEST",`geo index "${o.indexName}" on table "${r}": .within() corners are transposed (sw.lat > ne.lat)`);if(s.sw.lng>s.ne.lng)throw new $("BAD_REQUEST",`geo index "${o.indexName}" on table "${r}": .within() box crosses the antimeridian (sw.lng > ne.lng), which is not supported — split it into two boxes at ±180 and union the results`);return o.within={ne:{lat:s.ne.lat,lng:s.ne.lng},sw:{lat:s.sw.lat,lng:s.sw.lng}},d}};return d},No=(n,r)=>{const o=n[r];if(o===null||typeof o!="object")return;const{lat:d,lng:s}=o;return typeof d=="number"&&typeof s=="number"?{lat:d,lng:s}:void 0},jo=(n,r)=>{const o=No(n,r.definition.field);if(!o)return;const d=typeof n._creationTime=="number"?n._creationTime:0;if(r.near){const s=Un(r.near.point,o);return s<=r.near.radiusMeters?{creationTime:d,distance:s}:void 0}return Gn(o,r.within)?{creationTime:d,distance:0}:void 0},Ko=(n,r,o,d)=>{if(!o.near&&!o.within)throw new $("INTERNAL",`geo index "${o.indexName}" on table "${r}": call .near(point, radius) or .within(box)`);const s=o.near?Wn(o.near.point,o.near.radiusMeters):Pn(o.within),w=qn(r,o.indexName),E=s.map(R=>c`(g.${c.identifier("__geohash__")} >= ${R} AND g.${c.identifier("__geohash__")} < ${`${R}{`})`),A=[c`(${c.join(E,c` OR `)})`];d&&A.push(d);const g=c`SELECT m.id, m._creationTime, m.${c.identifier(ne)} FROM ${c.identifier(w)} g JOIN ${c.identifier(r)} m ON m.id = g.${c.identifier("__id__")} WHERE ${c.join(A,c` AND `)}`,b=j(n,g).toArray(),x=[];for(const R of b){const T=Se(R),M=T?jo(T,o):void 0;T&&M&&x.push({creationTime:M.creationTime,distance:M.distance,doc:T})}return x.sort((R,T)=>R.distance-T.distance||T.creationTime-R.creationTime),x},un=(n,r,o,d)=>{const s=[];for(const w of n)if(r.every(E=>E(d(w)))&&(s.push(w),typeof o=="number"&&s.length>=o))break;return s},Qo=(n,r,o,d,s,w=()=>{})=>{const E=o.within!==void 0,A=Ko(n,r,o,s).map(g=>({distanceMeters:E?null:g.distance,document:g.doc}));return w(A.length),typeof d=="number"?A.slice(0,Math.max(0,Math.floor(d))):A},Nt=(n,r,o,d,s,w,E=()=>{})=>{const{geo:A}=o;if(!A)throw new $("INTERNAL","runGeoTerminalScored called without a staged geo query");const g=s.length>0,b=Qo(n,r,A,g?void 0:w,d,E);return g?un(b,s,w,x=>x.document):b},me={fieldRef:se,serialize:ce},fn=(n,r)=>{const o=r===void 0?void 0:n.shape[r];return o!==void 0&&io(o)},jt=(n,r)=>r.some(o=>fn(n,o)),Kt=(n,r,o)=>{if(fn(n,r))throw new $("BAD_REQUEST",`${o}: "${r}" may hold an order-preserving key rather than a value SQL can reduce or group — declare an aggregateIndex covering this (by, field, op) so the maintained companion answers it instead (its running total is a REAL, so it stays exact only while the total is inside 2^53)`)},Vo=n=>{let r=0;const o=[],d={fieldRef:s=>Oe(Ge(s)),relationExists:s=>{const{childWhere:w,negated:E,parentTable:A,relation:g}=s,b=`__rel_${String(r)}`,x=o.at(-1)??A;r+=1,n(g.table,O);const R=g.kind==="one"?g.field:g.references,T=g.kind==="one"?g.references:g.field,M=Oe(`${bt(b,T)} = ${bt(x,R)}`);o.push(b);const B=ee(w,d,Ne);o.pop();const P=B===void 0?M:_e(M," AND ",B),L=_e("EXISTS (SELECT 1 FROM ",Ft(g.table)," AS ",Ft(b)," WHERE ",P,")");return E?_e("NOT ",L):L},serialize:ce};return d};class zo extends ${constructor(r="unique() found more than one matching document"){super("NOT_UNIQUE",r,{name:"NotUniqueError"})}}const Jo=/\s/u,Yo=String.fromCodePoint(0),Qt=(n,r,o)=>{if(!n.tables[r])throw new $("INTERNAL",`unknown table: ${r}`);return typeof o!="string"||o.length===0||Jo.test(o)||o.includes(Yo)?null:o},Xo=(n,r,o,d=()=>{},s=()=>{},w=()=>{})=>{const E=r.tables[o];if(!E)throw new $("INTERNAL",`unknown table: ${o}`);const A=ue(E.softDeleteMode,void 0),g={indexFields:[],indexName:void 0,inMemoryFilters:[],order:"asc",sqlConditions:[],verifyFilters:[]},b=()=>{const y=N(A,g.pushedWhere);return y?ee(y,me):void 0},x=()=>{const y=N(A,g.pushedWhere);return y?ee(y,ht,Ne):void 0},R=()=>[...g.inMemoryFilters,...g.verifyFilters];let T=0;const M=y=>{const{search:_}=g;if(!_)throw new $("INTERNAL","runSearchFetch called without a staged search");In(n,o,E);const F=g.inMemoryFilters.length>0,k=mo(F?void 0:y),z=Fn(n);if(z&&!Cn(n,o,_.definition))throw new $("SEARCH_INDEX_BUILDING",`search index "${_.indexName}" on table "${o}" is still backfilling and currently covers only part of the table — retry once it finishes, or run the backfillSearch admin operation to complete it now`);const he=b(),oe=z?Go(n,o,_,k,he):Ho(n,o,_,k,he);!F&&y===void 0&&wo(oe);const te=R();return T=oe.length,te.length>0?un(oe,te,y,ae=>ae.document):oe},B=y=>M(y).map(_=>_.document),P=y=>{const _=yo(y);return Eo(B(po(_)),_)},L=()=>{if(g.search||g.geo||g.indexName===void 0){s(void 0);return}s(Yn(o,g.indexName,g.indexFields,g.sqlConditions,ce))},q=y=>{L();let _=0;const F=(()=>{if(g.search){const k=B(y);return _=T,k}return g.geo?Nt(n,o,g,b(),R(),y,k=>{_=k}).map(k=>k.document):at(n,o,E,g,x(),{filters:R(),selective:g.inMemoryFilters.length>0,want:y===void 0?void 0:Math.max(0,Math.floor(y))},k=>{_+=k}).documents})();return w(Math.max(_,F.length)),F},C=()=>{if(!g.search&&!g.geo)throw new $("INTERNAL",`ctx.db.query("${o}").collectWithScores() requires a staged .withSearchIndex(...) or .withGeoIndex(...)`);L();let y=0;const _=(()=>{if(g.search){const F=M(void 0);return y=T,F}return Nt(n,o,g,b(),R(),void 0,F=>{y=F})})();return w(Math.max(y,_.length)),_},K={async*[Symbol.asyncIterator](){if(g.search){yield*q(void 0);return}let y;for(;;){const _=await K.paginate({cursor:y??null,numItems:Wo});if(yield*_.page,_.isDone||_.continueCursor===null)return;y=_.continueCursor}},async collect(){return q(void 0)},async collectWithScores(){return C()},filter(y){const _=Xn(y);return _!==void 0&&Zn(_,E.shape)?(g.pushedWhere=N(g.pushedWhere,_),g.verifyFilters.push(y)):g.inMemoryFilters.push(y),K},async first(){return q(1)[0]??null},order(y){return g.order=y==="desc"?"desc":"asc",K},async paginate(y){let _=0;if(L(),g.search){const k=P(y);return w(k.page.length),k}if(g.geo)throw new $("INTERNAL","pagination is not supported on geo queries; use .take(n) or .collect()");const F=Co(n,o,E,g,y,x(),{all:R(),selective:g.inMemoryFilters.length>0},k=>{_+=k});return w(Math.max(_,F.page.length)),F},async take(y){return q(y)},async unique(){const y=q(2);if(y.length>1)throw new zo(`unique() on table "${o}" matched ${String(y.length)} documents; expected at most one`);return y[0]??null},withGeoIndex(y,_){const F=(E.geoIndexes??[]).find(z=>z.name===y);if(!F)throw new $("INTERNAL",`unknown geo index "${y}" on table "${o}"`);d(o,y,"geo");const k={definition:F,indexName:y};if(g.geo=k,_(Oo(k,o)),!k.near&&!k.within)throw new $("INTERNAL",`geo index "${y}" on table "${o}" requires a .near(point, radius) or .within(box) call`);return K},withIndex(y,_){const F=E.indexes.find(k=>k.name===y);if(!F)throw new $("INTERNAL",`unknown index "${y}" on table "${o}"`);return d(o,y,"index"),g.indexName=y,g.indexFields=F.fields,_&&_(Po(g)),K},withSearchIndex(y,_){const F=(E.searchIndexes??[]).find(z=>z.name===y);if(!F)throw new $("INTERNAL",`unknown search index "${y}" on table "${o}"`);d(o,y,"search");const k={definition:F,field:F.field,filters:[],hasQuery:!1,indexName:y,query:""};if(g.search=k,_(ho(k,o,lt(F.language))),!k.hasQuery)throw new $("INTERNAL",`search index "${y}" on table "${o}" requires a .search(field, query) call`);return K}};return K},Vt=(n,r,o)=>{const d={...r};for(const[s,w]of Zt(n)){if(w.serverDefault){d[s]=w.serverDefault({auth:o});continue}d[s]===void 0&&(w.defaultFn?d[s]=w.defaultFn():"defaultValue"in w&&(d[s]=w.defaultValue))}return d},zt=(n,r,o,d)=>{const s=o;for(const[w,E]of Zt(n)){if(E.serverDefault){w in r&&(s[w]=E.serverDefault({auth:d}));continue}E.onUpdateFn&&!(w in r)&&(s[w]=E.onUpdateFn())}},Jt=(n,r)=>{for(const o of Object.keys(r))if(r[o]===void 0)throw new $("INTERNAL",`Cannot ${n} field '${o}' to undefined — use null to clear a nullable field, or omit the key to leave it unchanged.`)},Yt=["_commitSeq","_creationTime","_id"],it=n=>Yt.some(r=>r in n)?Object.fromEntries(Object.entries(n).filter(([r])=>!Yt.includes(r))):n,Zo=/unique constraint failed/i,er=n=>n instanceof Error&&Zo.test(n.message),tr=/string or blob too big/iu,nr=(n,r)=>{if(!(!(n instanceof Error)||!tr.test(n.message)))throw new $("PAYLOAD_TOO_LARGE",`document is too large to store in "${r}": a single row cannot exceed the storage engine's per-row ceiling (2 MB on a Durable Object's SQLite). The limit is on the STORED bytes, which are UTF-8, and v.bytes()/v.bigint() columns are stored twice on a shard-local table. Keep the payload in R2 (ctx.storage) and store a reference on the row.`)},dt=(n,r,o,d)=>{try{Te(n,o,...d)}catch(s){throw er(s)?new Re(`unique constraint violation on "${r}"`,"unique"):(nr(s,r),s)}},Ue=(n,r,o,d)=>{if(dt(n,r,o,d),Te(n,Do).one().changed===0)throw new Re(`optimistic concurrency conflict on "${r}" — the row changed during this mutation; refetch and retry`,"occ")},Xt=(n,r,o,d,s,w,E)=>{const A=[];for(let R=0;R<o.length+1;R+=1){const T=o[R],M=d[R],B=M?.direction==="desc"?"desc":"asc",P=T===void 0||M===void 0?c`${c.identifier(Vn)} < ${E}`:zn(T,w[R],B,!1);if(P===void 0)continue;const L=[];for(let C=0;C<R;C+=1)L.push(c`${c.identifier(o[C])} IS ${w[C]}`);L.push(P);const[q]=L;A.push(L.length===1&&q!==void 0?q:c`(${c.join(L,c` AND `)})`)}const g=A.length>0?c.join(A,c` OR `):c`1 = 0`,b=j(n,c`SELECT COUNT(*) AS c FROM ${c.identifier(r)} WHERE ${c.identifier("__partition__")} = ${s} AND (${g})`).one(),x=j(n,c`SELECT COUNT(*) AS c FROM ${c.identifier(r)} WHERE ${c.identifier("__partition__")} = ${s}`).one();return{before:b.c,total:x.c}},Ur=n=>{const{baselineSeq:r,onStalePatchDropped:o}=n,{sql:d}=n,{schema:s}=n,w=n.broadcast??(()=>{}),E=eo(s);let A;const g=()=>n.inTransaction?.()===!0,b=e=>s.tables[e]?.commitOrderedMode!==!0?{}:((A===void 0||!g())&&(A=Mn(d)),{[Dn]:A}),x=(e,...t)=>{const i=s.tables[e]?.indexes;if(!i||i.length===0)return;const f=[];for(const h of t)h&&f.push(...Jn(i,h,ce));return f.length>0?f:void 0},{headroom:R}=n;let T=!1;const M=async e=>{const t=T;T=!0;try{return await e()}finally{T=t}},B=n.onRead??(()=>{}),P=e=>{Ct(s.tables[e])&&B(Lt,Lt)},L=n.onReadRange??(e=>{B(e.table,O)}),q=e=>{P(e.table),L(e)},C=(e,t)=>{t!==void 0&&t!==O&&!T&&R?.recordRead(1),P(e),B(e,t)},K=n.onIndexUse??(()=>{}),y=n.onWrite??(()=>{}),_=e=>{T||R?.recordWrite(e)},F=async e=>{_(e.doc),await y(e)},{cache:k}=n,z=n.clock??(()=>Date.now()),he=n.idGenerator??(()=>crypto.randomUUID()),oe=n.scheduler??_n,{globalDb:te}=n,ae=n.auth??{identity:null,userId:null},wt=n.cdc??!1,Ke=oe,hn=so({scheduler:typeof Ke.list=="function"&&typeof Ke.get=="function"?Ke:void 0,storage:n.storage}),we=(e,t,i,f)=>{wt&&!Ct(s.tables[e])&&xn(d,z(),e,t,i,f)},wn=(e,t,i,f)=>{if(s.tables[e]?.dropStalePatchesMode!==!0||!wt)return!1;const h=r?.();if(h===void 0)return!1;const l=bn(d,e,t,h);return l===void 0?!1:Object.keys(it(i)).some(a=>It(l[a])!==It(f[a]))},re=e=>s.tables[e]?.shardMode?.kind==="global",pt=(e,t)=>{if(re(e)){if(!te)throw new $("INTERNAL",`cross-backend ${t} for global table '${e}' requires a globalDb writer — pass one to createShardCtxDb({ globalDb })`);return te}return G},Qe=e=>pt(e,"cascade"),V=(e,t)=>{if(re(e)){if(!te)throw new $("INTERNAL",`${t} on global table '${e}' requires a globalDb writer — pass one to createShardCtxDb({ globalDb })`);return te}},gt=async(e,t,i,f,h)=>{h&&_(i);const l=await e.insert(t,i,f);return w({key:l,op:"insert",row:{...i,_id:l},table:t}),l},Ve=(e,t)=>pt(e,"relation load").findMany(e,t),$t=(e,t)=>(re(e)&&C(e,O),Ve(e,t)),pn=e=>!re(e.table),yt=n.relationExistsPushDown??"auto",Et=yt!=="never",{maxRelationKeys:mt}=n,Ae=(e,t,i)=>qt(e,{fetcher:$t,maxRelationKeys:mt,relationBaseWhere:i,schema:s,tableName:t}),St=async(e,t,i,f)=>{const h=V(e,"relation grouped count");if(h)return C(e,O),oo((U,I)=>h.count(U,I),e,t,i,f);const l=s.tables[e];if(!l)throw new $("INTERNAL",`unknown table: ${e}`);C(e,O);const a=ue(l.softDeleteMode,void 0),u={[t]:{in:i}},p=N(N(u,f),a),v=await Ae(p,e,void 0),m=ee(v,me),D=se(t);let S=c`SELECT ${D} AS __fk__, COUNT(*) AS count FROM ${c.identifier(e)}`;m&&(S=c`${S} WHERE ${m}`),S=c`${S} GROUP BY ${D}`;const W=j(d,S).toArray();return new Map(W.map(U=>[U.__fk__,U.count]))};let Ie=0;const _t=new Set;for(const[e,t]of Object.entries(s.tables))for(const i of Object.values(t.triggerMap??{}))_t.add(`${e} ${i.timing} ${i.op}`);const X=(e,t,i)=>_t.has(`${e} ${t} ${i}`),Z=async(e,t,i)=>{if(Ie+=1,Ie>Ot)throw Ie-=1,new Re(`trigger recursion exceeded ${String(Ot)} levels on "${i.table}" — check for a self-triggering write`,"trigger");try{await co({ctx:$n,event:i,op:t,schema:s,tableName:i.table,timing:e})}finally{Ie-=1}},{ensureBackfilledForTable:pe,ensureBackfilledIndex:ze,ensureRankBackfilled:Je,ensureRankBackfilledForTable:ge,syncAggregates:Ce,syncCompanionsForInsert:Rt,syncGeo:xe,syncRanks:$e,syncSearch:be}=kn({broadcast:w,indexKeysFor:(e,t)=>x(e,t),invalidateCache:(e,t,i)=>k?.invalidate(e,t,x(e,i)),recordCdc:we,schema:s,sql:d}),Tt=(e,t,i)=>{const{shardMode:f}=t;if(f?.kind==="shardBy"&&!(f.field!==void 0&&(i.partitionBy??[]).includes(f.field)))throw Object.assign(new Error(`rank index "${i.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})},vt=e=>Object.entries(s.tables).filter(([,t])=>t.shardMode?.kind!=="global").map(([t])=>t).filter(t=>e===void 0||t===e),ye=e=>e===void 0||re(e)?te:void 0,ie=(e,t)=>{const i=vt(t);for(let f=0;f<i.length;f+=Ee){const h=i.slice(f,f+Ee),[l]=Te(d,Lo(h),...Fo(e,h)).toArray();if(!l)continue;const a=l.__t__,u=Se(l);if(typeof a!="string"||!u)return;const p=l[ne];return{docJson:typeof p=="string"?p:de(p??{}),row:u,tableName:a}}},gn=(e,t)=>{const i=[...new Set(e)],f=new Map;if(i.length===0)return f;const h=vt(t);for(let l=0;l<h.length;l+=Ee){const a=h.slice(l,l+Ee),u=Math.floor(Ee/a.length),p=Bn(c`${c.identifier("id")}`,i,!1,u),v=a.map(m=>c`SELECT ${c.raw(`'${m.replaceAll("'","''")}'`)} AS __t__, id FROM ${c.identifier(m)} WHERE ${p}`);for(const m of j(d,ut(v))){const{id:D,__t__:S}=m;typeof S=="string"&&typeof D=="string"&&f.set(D,S)}}return f},At={assertRankPartitionLocal:Tt,ensureRankBackfilled:Je,onRead:C,rowToDocument:Se,schema:s,sql:d},G={system:hn,async aggregate(e,t){const i=V(e,"aggregate");if(i)return C(e,O),i.aggregate(e,t);const f=s.tables[e];if(!f)throw new $("INTERNAL",`unknown table: ${e}`);if(qe(t.op),t.op==="count")return G.count(e,{baseWhere:t.baseWhere,relationBaseWhere:t.relationBaseWhere,restrictsCounts:t.restrictsCounts,where:t.where});if(!t.field)throw new $("INTERNAL",`aggregate(${e}, { op: "${t.op}" }): "field" is required for non-count reducers`);C(e,O);const h=ue(f.softDeleteMode,void 0),l=N(N(t.baseWhere,t.where),h),a=await Ae(l,e,t.relationBaseWhere),u=a!==l;if(f.aggregateIndexes&&!t.baseWhere&&!u&&(!h||jt(f,[t.field]))){const U=An(f.aggregateIndexes,t.op,t.field,t.where);if(U){ze(e,U.index);const I=Xe(U.index.by??[],U.key),Q=Ye(e,U.index.name),J=j(d,c`SELECT ${Be} AS value, ${tt} AS count FROM ${c.identifier(Q)} WHERE ${We} = ${I}`).toArray()[0];return Ze(t.op,J)}}Kt(f,t.field,`aggregate(${e}, { op: "${t.op}", field: "${t.field}" })`);const p=ee(a,me),v=qe(t.op),m=se(t.field);let D=c`SELECT ${c.raw(v)}(${m}) AS value FROM ${c.identifier(e)}`;p&&(D=c`${D} WHERE ${p}`);const W=j(d,D).toArray()[0]?.value;return W??null},asId(e,t){const i=Qt(s,e,t);if(i===null)throw new $("BAD_REQUEST",`asId("${e}", …): "${t}" is not a valid id for table "${e}"`,{status:400});return i},async count(e,t){const i=V(e,"count");if(i)return C(e,O),i.count(e,t);const f=s.tables[e];if(!f)throw new $("INTERNAL",`unknown table: ${e}`);const h=Rn(t);if(h.restrictsCounts)throw new et(e);C(e,O);const l=ue(f.softDeleteMode,void 0),a=N(N(h.baseWhere,h.where),l),u=await Ae(a,e,h.relationBaseWhere),p=u!==a;if(f.aggregateIndexes&&!h.baseWhere&&!p&&!l){const S=vn(f.aggregateIndexes,h.where);if(S){ze(e,S.index);const W=Xe(S.index.by??[],S.key),U=Ye(e,S.index.name),I=j(d,c`SELECT ${Be} AS value FROM ${c.identifier(U)} WHERE ${We} = ${W}`).toArray();return I[0]===void 0?0:I[0].value??0}}const v=ee(u,me);let m=c`SELECT COUNT(*) AS count FROM ${c.identifier(e)}`;return v&&(m=c`${m} WHERE ${v}`),j(d,m).one().count},async delete(e,t,i){const f=ie(e,t);if(!f){const m=ye(t);m&&(_(void 0),await m.delete(e,t,i));return}const{docJson:h,row:l,tableName:a}=f,u=s.tables[a],p=i?.hard===!0,v=!p&&u?.softDeleteMode?u.softDeleteMode.field:void 0;if(!(v&&l[v]!==null&&l[v]!==void 0)){if(X(a,"before","delete")&&await Z("before","delete",{id:e,op:"delete",previous:l,table:a}),await no({deletedId:e,deletedReference:m=>l[m],findHolders:async(m,D,S)=>(await Qe(m).findMany(m,{includeDeleted:p,where:{[D]:S}})).page,onCascade:(m,D)=>Qe(m).delete(D,void 0,i),onRestrict:m=>{throw new Re(m,"restrict")},onSetNull:(m,D,S)=>Qe(m).patch(D,{[S]:null}),schema:s,tableName:a}),pe(a),ge(a),v){const m={...l,...b(a),[v]:z(),_id:e};Ue(d,a,Gt(a),[de(m),e,h]),be(a,e,m,l),xe(a,e,void 0),Ce(a,l,m),$e(a,e,l,void 0),k?.invalidate(a,e,x(a,l,m)),we(a,e,"update",m),w({indexKeys:x(a,l,m),key:e,op:"update",row:m,table:a}),X(a,"after","delete")&&await Z("after","delete",{id:e,op:"delete",previous:l,table:a}),await F({id:e,op:"delete",table:a});return}Ue(d,a,Mo(a),[e,h]),be(a,e,void 0),xe(a,e,void 0),Ce(a,l,void 0),$e(a,e,l,void 0),k?.invalidate(a,e,x(a,l)),we(a,e,"delete"),w({indexKeys:x(a,l),key:e,op:"delete",table:a}),X(a,"after","delete")&&await Z("after","delete",{id:e,op:"delete",previous:l,table:a}),await F({id:e,op:"delete",table:a})}},async deleteAll(e,t){if(!s.tables[e])throw new $("INTERNAL",`unknown table: ${e}`);const i=Math.max(1,t?.chunkSize??dn),f=t?.hard===void 0?void 0:{hard:t.hard},h=re(e)?void 0:e;let l=0;return await M(async()=>{for(;;){const u=(await G.findMany(e,{limit:i})).page.map(p=>String(p._id));if(u.length===0)break;for(const p of u)await G.delete(p,h,f),l+=1;if(u.length<i)break}}),{deleted:l}},async deleteMany(e,t,i){le(e.length,t?.limit,"deleteMany");for(const f of e)await G.delete(f,i);return{deleted:e.length}},async deleteWhere(e,t,i){const l=(await(V(e,"deleteWhere")??G).findMany(e,{where:t})).page.map(a=>String(a._id));if(le(l.length,i?.limit,"deleteWhere"),G.deleteMany===void 0)throw new $("INTERNAL",`ctx.db.${e}.deleteMany is unavailable: this writer has no batch delete`);return G.deleteMany(l,i)},async findFirst(e,t={}){return(await G.findMany(e,{...t,limit:1,omitContinueCursor:!0})).page[0]??null},async findFirstOrThrow(e,t={}){const i=await G.findFirst(e,t);if(i===null)throw new Hn(`findFirstOrThrow: no "${e}" document matched`);return i},async findMany(e,t={}){const i=V(e,"findMany");if(i)return C(e,O),i.findMany(e,t);const f=s.tables[e];if(!f)throw new $("INTERNAL",`unknown table: ${e}`);const h=!t.where&&!t.baseWhere;h?C(e,O):C(e);const l=st(t.orderBy,f.shape,{pinned:jn(t.where),uniqueBy:on(f.indexes,f.shape)}),a=t.cursor?rn(l,ct(t.cursor)):void 0;let u=N(t.baseWhere,t.where);u=N(u,ue(f.softDeleteMode,t.includeDeleted)),u=await qt(u,{canPushExists:Et?pn:void 0,existsPushMode:yt==="always"?"always":"auto",fetcher:$t,maxRelationKeys:mt,relationBaseWhere:t.relationBaseWhere,schema:s,tableName:e}),a&&(u=u?{AND:[u,a]}:a);const p=Et?Vo(C):ht,v=ee(u,p,Ne),m=typeof t.limit=="number"?Math.max(0,Math.floor(t.limit)):void 0,D=sn(e,v,cn(l),m===void 0?void 0:m+1),S=Te(d,D.text,...D.params).toArray();h&&!T&&R?.recordRead(S.length);const W=[];for(const J of S){const H=Se(J);H&&(W.push(H),!h&&typeof H._id=="string"&&C(e,H._id))}if(m===void 0)return t.with&&await Bt({groupedCounter:St,fetcher:Ve,parents:W,...Wt(t),schema:s,tableName:e,with:t.with}),{continueCursor:null,isDone:!0,page:Mt(W,t.select,t.with)};const U=W.length>m,I=U?W.slice(0,m):W,Q=I.at(-1);return t.with&&await Bt({fetcher:Ve,groupedCounter:St,parents:I,...Wt(t),schema:s,tableName:e,with:t.with}),{continueCursor:U&&Q&&t.omitContinueCursor!==!0?He(Q,l):null,isDone:!U,page:Mt(I,t.select,t.with)}},async get(e,t){const i=ie(e,t);if(!i){const f=ye(t);return f?f.get(e,t):null}return C(i.tableName,e),i.row},async lookupById(e,t){const i=ie(e,t);return i?(C(i.tableName,e),{row:i.row,tableName:i.tableName}):null},async groupBy(e,t){const i=V(e,"groupBy");if(i)return C(e,O),i.groupBy(e,t);const f=s.tables[e];if(!f)throw new $("INTERNAL",`unknown table: ${e}`);C(e,O);const h=t.agg??{op:"count"};if(qe(h.op),h.op!=="count"&&!h.field)throw new $("INTERNAL",`groupBy(${e}, { agg: { op: "${h.op}" } }): "field" is required for non-count reducers`);const l=ue(f.softDeleteMode,void 0),a=N(N(t.baseWhere,t.where),l),u=await Ae(a,e,t.relationBaseWhere),p=u!==a,v=[...t.by,h.field];if(f.aggregateIndexes&&!t.baseWhere&&!p&&(!l||jt(f,v))){const I=Tn(f.aggregateIndexes,h.op,h.field,t.by,t.where),Q=I===void 0?0:Object.keys(I.partial).length,J=I?.index.by?.length??0;if(I&&(Q===0||Q===J)){ze(e,I.index);const H=Ye(e,I.index.name),Me=Object.keys(I.partial),De=[];if(Me.length===(I.index.by??[]).length&&Me.length>0){const ke=Xe(I.index.by??[],I.partial),Le=j(d,c`SELECT ${Be} AS value, ${tt} AS count FROM ${c.identifier(H)} WHERE ${We} = ${ke}`).toArray();return Le.length>0&&De.push({key:{...I.partial},value:Ze(h.op,Le[0])}),De}const yn=j(d,c`SELECT ${We} AS key, ${Be} AS value, ${tt} AS count FROM ${c.identifier(H)}`).toArray();for(const ke of yn){const Le=Sn(JSON.parse(ke.key));De.push({key:Le,value:Ze(h.op,ke)})}return De}}for(const I of v){if(I===void 0)continue;const Q=I===h.field?`groupBy(${e}, { agg: { op: "${h.op}", field: "${I}" } })`:`groupBy(${e}, { by: [..."${I}"] })`;Kt(f,I,Q)}const m=ee(u,me),D=t.by.map(I=>c`${se(I)} AS ${c.identifier(I)}`);if(h.op==="count")D.push(c`COUNT(*) AS value`);else{const{field:I}=h;if(I===void 0)throw new $("INTERNAL",`groupBy(${e}, { agg: { op: "${h.op}" } }): "field" is required for non-count reducers`);D.push(c`${c.raw(qe(h.op))}(${se(I)}) AS value`)}let S=c`SELECT ${c.join(D,c`, `)} FROM ${c.identifier(e)}`;m&&(S=c`${S} WHERE ${m}`),S=c`${S} GROUP BY ${c.join(t.by.map(I=>se(I)),c`, `)}`;const W=j(d,S).toArray(),U=[];for(const I of W){const Q={};for(const H of t.by)Q[H]=Ln(f.shape[H],I[H]??null);const{value:J}=I;U.push({key:Q,value:J==null?null:Number(J)})}return U},async insert(e,t,i){const f=V(e,"insert");if(f)return gt(f,e,t,i,!0);const h=s.tables[e];if(!h)throw new $("INTERNAL",`unknown table: ${e}`);const l=Vt(h,t,ae);ot(h,l);let a;i?.clientId!==void 0?(Bo(i.clientId),a=i.clientId):i?.allowExplicitId&&typeof l._id=="string"?a=l._id:a=he();const u=i?.allowExplicitId&&typeof l._creationTime=="number"?l._creationTime:z(),p={...l,...b(e),_creationTime:u,_id:a};return X(e,"before","insert")&&await Z("before","insert",{doc:{...p},id:a,op:"insert",table:e}),pe(e),ge(e),dt(d,e,xo(e),[a,u,de(p)]),Rt(e,a,p),X(e,"after","insert")&&await Z("after","insert",{doc:p,id:a,op:"insert",table:e}),await F({doc:p,id:a,op:"insert",table:e}),a},async insertManyUnsafe(e,t,i){if(le(t.length,i?.limit,"insertManyUnsafe"),t.length===0)return[];const f=V(e,"insert");if(f){const u=[];for(const p of t)_(p);for(const p of t){const v=await f.insert(e,p,{allowExplicitId:i?.allowExplicitId});w({key:v,op:"insert",row:{...p,_id:v},table:e}),u.push(v)}return u}const h=s.tables[e];if(!h)throw new $("INTERNAL",`unknown table: ${e}`);pe(e),ge(e);const l=[];for(let u=0;u<t.length;u+=Pe)l.push(b(e));const a=t.map((u,p)=>{const v=Vt(h,u,ae),m=i?.allowExplicitId===!0&&typeof v._id=="string"?v._id:he(),D=i?.allowExplicitId===!0&&typeof v._creationTime=="number"?v._creationTime:z(),S={...v,...l[Math.floor(p/Pe)],_creationTime:D,_id:m};return{creationTime:D,document:S,id:m}});for(const u of a)_(u.document);for(let u=0;u<a.length;u+=Pe){const p=c.join(a.slice(u,u+Pe).map(m=>c`(${m.id}, ${m.creationTime}, ${de(m.document)})`),c`, `),v=tn("sqlite",c`INSERT INTO ${c.identifier(e)} (id, _creationTime, ${c.identifier(ne)}) VALUES ${p}`);dt(d,e,v.sql,v.params)}for(const{document:u,id:p}of a)Rt(e,p,u),await y({doc:u,id:p,op:"insert",table:e});return a.map(u=>u.id)},async insertMany(e,t,i){le(t.length,i?.limit,"insertMany");const f=i?.skipDuplicates===!0,h=[],l=V(e,"insert");if(l)for(const u of t)_(u);const a=async u=>l?gt(l,e,u,void 0,!1):G.insert(e,u);for(const u of t)try{h.push(await a(u))}catch(p){if(f&&p instanceof Re&&p.kind==="unique")h.push(null);else throw p}return h},normalizeId(e,t){return Qt(s,e,t)},async patch(e,t,i){const f=ie(e,i);if(!f){const v=ye(i);if(v){_(t),await v.patch(e,t,i);return}throw new $("NOT_FOUND",`document not found: ${e}`)}const{docJson:h,row:l,tableName:a}=f,u=s.tables[a];if(!u)throw new $("INTERNAL",`unknown table: ${a}`);if(C(a,e),Jt("patch",t),wn(a,e,t,l)){o?.({fields:Object.keys(it(t)),id:e,table:a});return}const p={...l,...it(t),...b(a),_id:e};zt(u,t,p,ae),ot(u,p,!0),X(a,"before","update")&&await Z("before","update",{doc:{...p},id:e,op:"update",previous:l,table:a}),pe(a),ge(a),Ue(d,a,Gt(a),[de(p),e,h]),be(a,e,p,l),xe(a,e,p),Ce(a,l,p),$e(a,e,l,p),k?.invalidate(a,e,x(a,l,p)),we(a,e,"update",p),w({indexKeys:x(a,l,p),key:e,op:"update",row:p,table:a}),X(a,"after","update")&&await Z("after","update",{doc:p,id:e,op:"update",previous:l,table:a}),await F({doc:p,id:e,op:"update",table:a})},async patchMany(e,t,i){le(e.length,t?.limit,"patchMany");for(const f of e)await G.patch(f.id,f.patch,i);return{patched:e.length}},async patchWhere(e,t,i){const l=(await(V(e,"patchWhere")??G).findMany(e,{where:t.where})).page.map(a=>({id:String(a._id),patch:t.patch}));if(le(l.length,i?.limit,"patchWhere"),G.patchMany===void 0)throw new $("INTERNAL",`ctx.db.${e}.patchMany is unavailable: this writer has no batch patch`);return await G.patchMany(l,i),{patched:l.length}},async related(e,t){return to(G,E,e,t)},relationEdges:E,query(e){const t=V(e,"query");return t?(C(e,O),t.query(e)):Xo(d,s,e,K,i=>{i?q(i):C(e,O)},i=>{T||R?.recordRead(i)})},async rank(e,t,i){const f=V(e,"rank");if(f)return C(e,O),f.rank(e,t,i);K(e,t,"rank");const h=s.tables[e];if(!h)throw new $("INTERNAL",`unknown table: ${e}`);const l=h.rankIndexes?.find(H=>H.name===t);if(!l)throw new $("INTERNAL",`unknown rankIndex "${t}" on table "${e}"`);if(Tt(e,h,l),i.restrictsCounts)throw new et(e);C(e,O),Je(e,l);const a=typeof i.row=="string"?i.row:i.row._id;if(!a)return null;const u=Dt(e,l.name),p=l.sortBy.map((H,Me)=>kt(Me)),v=p.map(H=>ve(H)).join(", "),m=j(d,c`SELECT ${c.identifier("__partition__")}, ${c.raw(v)} FROM ${c.identifier(u)} WHERE ${c.identifier("__id__")} = ${a}`).toArray(),[D]=m;if(D===void 0)return null;let S=D.__partition__;const W=N(i.baseWhere,i.where);nt(W,s,e,"rank");const U=Kn(l,W);if(U){const H=Qn(l.partitionBy??[],U);if(H!==S)return null;S=H}const I=p.map(H=>D[H]),{before:Q,total:J}=Xt(d,u,p,l.sortBy,S,I,a);return{position:Q+1,total:J}},async rankBefore(e,t,i){if(re(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=s.tables[e];if(!f)throw new $("INTERNAL",`unknown table: ${e}`);const h=f.rankIndexes?.find(p=>p.name===t);if(!h)throw new $("INTERNAL",`unknown rankIndex "${t}" on table "${e}"`);if(i.restrictsCounts)throw new et(e);C(e,O),Je(e,h);const l=Dt(e,h.name),a=h.sortBy.map((p,v)=>kt(v)),u=h.sortBy.map((p,v)=>ce(i.sortValues[v]??null));return Xt(d,l,a,h.sortBy,i.partitionKey,u,i.rowId)},async rankPage(e,t,i={}){nt(N(i.baseWhere,i.where),s,e,"rankPage");const f=V(e,"rankPage");if(f)return C(e,O),f.rankPage(e,t,i);K(e,t,"rank");const{continueCursor:h,hasMore:l,rows:a}=xt(At,e,t,i);return{continueCursor:h,isDone:!l,page:a.map(u=>u.doc)}},async rankPageRows(e,t,i={}){nt(N(i.baseWhere,i.where),s,e,"rankPage"),K(e,t,"rank");const{directions:f,hasMore:h,rows:l}=xt(At,e,t,i);return{directions:f,hasMore:h,rows:l}},async restore(e,t){const i=ie(e,t);if(!i){const l=ye(t);if(l?.restore){await l.restore(e,t);return}throw new $("NOT_FOUND",`document not found: ${e}`)}const f=s.tables[i.tableName]?.softDeleteMode?.field;if(!f)throw new $("INTERNAL",`ctx.db.restore: table "${i.tableName}" is not a .softDelete() table`);const h=i.row[f]!==null&&i.row[f]!==void 0;await G.patch(e,{[f]:null},t),h&&$e(i.tableName,e,void 0,i.row)},async replace(e,t,i,f){const h=ie(e,i);if(!h){const W=ye(i);if(W){_(t),await W.replace(e,t,i,f);return}throw new $("NOT_FOUND",`document not found: ${e}`)}const{docJson:l,row:a,tableName:u}=h,p=s.tables[u];if(!p)throw new $("INTERNAL",`unknown table: ${u}`);Jt("replace",t);const v=f?.allowExplicitId&&typeof t._creationTime=="number"?t._creationTime:void 0,m=typeof a._creationTime=="number"?a._creationTime:void 0,D=v??m??z(),S={...t,...b(u),_creationTime:D,_id:e};zt(p,t,S,ae),ot(p,S),X(u,"before","update")&&await Z("before","update",{doc:{...S},id:e,op:"update",previous:a,table:u}),pe(u),ge(u),Ue(d,u,bo(u),[D,de(S),e,l]),be(u,e,S,a),xe(u,e,S),Ce(u,a,S),$e(u,e,a,S),k?.invalidate(u,e,x(u,a,S)),we(u,e,"update",S),w({indexKeys:x(u,a,S),key:e,op:"update",row:S,table:u}),X(u,"after","update")&&await Z("after","update",{doc:S,id:e,op:"update",previous:a,table:u}),await F({doc:S,id:e,op:"update",table:u})},async wipeShard(e){const t=new Set(e?.exclude),i=e?.tables,f=Object.entries(s.tables).filter(([u,p])=>t.has(u)||i!==void 0&&!i.includes(u)?!1:p.shardMode?.kind!=="global").map(([u])=>u);if(i!==void 0){for(const u of i)if(!s.tables[u])throw new $("INTERNAL",`wipeShard: unknown table: ${u}`)}const h={};let l=0;const{deleteAll:a}=G;if(a===void 0)throw new $("INTERNAL","wipeShard: this writer has no deleteAll");for(const u of f){const p=await a(u,{...e?.chunkSize===void 0?{}:{chunkSize:e.chunkSize},hard:!0});h[u]=p.deleted,l+=p.deleted}return{deleted:l,tables:h}}},$n={db:G,scheduler:oe};return n.enforceRls===!0?ro(G,s,(e,t)=>ie(e,t)?.tableName,(e,t)=>gn(e,t),E):G};export{Qr as CDC_LOG_TABLE,ui as CLIENT_WATERMARK_TABLE,gi as GLOBAL_SHAPE_SNAPSHOT_TABLE,Ri as IDEMPOTENCY_TABLE,zo as NotUniqueError,bi as SEARCH_STATE_TABLE,fi as advanceClientWatermark,Vr as applyCdcChanges,Jt as assertNoExplicitUndefined,Bo as assertValidClientId,Or as backfillAggregateIndexes,Nr as backfillRankIndexes,jr as backfillSearchIndexes,zr as bumpCdcEpoch,Jr as cdcCanVouchFor,Yr as cdcForkedError,Xr as cdcSeqLeavingRows,Zr as cdcTouchesTables,ei as cdcTrimmedError,ti as compactCdcDocs,Ur as createShardCtxDb,ni as cursorBelowRetainedFloor,$i as deleteGlobalShapeSnapshot,yi as deleteGlobalShapeSnapshotsForConnection,hi as migrateClientWatermark,Ei as migrateGlobalShapeSnapshot,oi as minCdcReplayableSeq,ri as minCdcSeq,Qt as normalizeIdStructurally,ii as readCdcChangeKeys,si as readCdcChanges,ci as readCdcCursor,ai as readCdcEpoch,wi as readClientWatermark,mi as readGlobalShapeSnapshot,Ti as readIdempotent,Ci as runShardMigrations,Di as selectShapeMembers,ki as selectShapeRows,it as stripReservedPatchFields,di as trimCdcChanges,vi as trimIdempotent,Si as writeGlobalShapeSnapshot,Ai 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-BbZ5hKM7.mjs";const a=Symbol("not-resolvable"),m=r=>{if(r!==null&&typeof r=="object"&&!Array.isArray(r)){const t=Object.keys(r);return t.length===1&&t[0]==="eq"?r.eq:a}return r},y=(r,t)=>{if(r.length===0)return"";const e={};for(const n of r.toSorted(l))e[n]=t[n]??null;return JSON.stringify(e)},k="__id__",N=r=>`__sort_k${String(r)}__`,h=(r,t)=>{const e=r.partitionBy??[],n=t??{};for(const o of Object.keys(n))if(o==="AND"||o==="OR"||o==="NOT")return;const i={};for(const o of e)if(o in n){const c=m(n[o]);if(c===a)return;i[o]=c}else if(r.where&&o in r.where)i[o]=r.where[o];else return;return i},O=(r,t)=>`${r}__rank_${t}`,$=(r,t)=>({partitionKey:y(r.partitionBy??[],t),rowId:t._id,sortValues:r.sortBy.map(e=>d(t[e.field]??null))}),K=(r,t,e,n)=>{const i=e!=="desc"===n;if(t==null)return i?s`${s.identifier(r)} IS NOT NULL`:void 0;const o=s`${s.identifier(r)} ${s.raw(i?">":"<")} ${t}`;return i?o:s`(${o} OR ${s.identifier(r)} IS NULL)`},R=f;export{k as RANK_TIEBREAK,y as encodePartitionKey,R as matchesRankStaticWhere,$ as rankKeyFromDoc,K as rankPivotConditionSql,O as rankTableName,h as resolveRankPartition,N as sortColumnName};
|
|
@@ -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-CTuiPWMD.mjs";import{keysTouchRanges as x}from"./buildIndexRange-6nIZDf4m.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};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{l as A,b as _}from"./ctx-db-search-state-fIiMVPXO.mjs";import{sql as r}from"drizzle-orm";import{readKeysetPage as h}from"./backfillAggregateIndexes-
|
|
1
|
+
import{l as A,b as _}from"./ctx-db-search-state-fIiMVPXO.mjs";import{sql as r}from"drizzle-orm";import{readKeysetPage as h}from"./backfillAggregateIndexes-yFyVVEHD.mjs";import{runDrizzle as $}from"./runDrizzle-CfKnGpV2.mjs";import{h as L}from"./do-sql-C7TkRQqw.mjs";const m="__lunora_vector_backfill",p=50,S=20,w=20,R=i=>{$(i,r`CREATE TABLE IF NOT EXISTS ${r.identifier(m)} (${r.identifier("companion")} TEXT PRIMARY KEY, ${r.identifier("cursor")} TEXT, ${r.identifier("done")} INTEGER NOT NULL DEFAULT 0, ${r.identifier("profile")} TEXT)`)},I=(i,t,d,n,o)=>{const e=d??null;$(i,r`INSERT INTO ${r.identifier(m)} (${r.identifier("companion")}, ${r.identifier("cursor")}, ${r.identifier("done")}, ${r.identifier("profile")}) VALUES (${t}, ${e}, ${n?1:0}, ${o}) ON CONFLICT (${r.identifier("companion")}) DO UPDATE SET ${r.identifier("cursor")} = excluded.${r.identifier("cursor")}, ${r.identifier("done")} = excluded.${r.identifier("done")}, ${r.identifier("profile")} = excluded.${r.identifier("profile")}`)},O=(i,t,d)=>{const n=h(i,t,d,p+1),o={documents:[],lastId:d,more:n.length>p,unparseable:[]};for(const e of n.slice(0,p)){if(typeof e.id!="string")continue;o.lastId=e.id;const s=L(e);s?o.documents.push({doc:s,id:o.lastId}):o.unparseable.push(o.lastId)}return o},P=async(i,t,d,n,o)=>{try{const{failures:e,page:s}=await o(()=>O(i,t,d),async a=>({failures:await n(t,a.documents),page:a}));return e.length>0&&console.warn(`[@lunora/shard-engine] vector backfill: ${String(e.length)} row(s) of "${t}" could not be indexed:`,e),{failedIds:[...s.unparseable,...e.map(a=>a.id)],page:s}}catch(e){return{error:e instanceof Error?e.message:String(e)}}},y=async(i,t,d,n)=>{if(R(i),n.restart===!0)for(const{profile:s,table:a}of t)I(i,a,void 0,!1,s);const o=Math.min(n.maxPages??1,S),e={done:!1,failed:0,failedIds:[],pages:0,rows:0};for(const{profile:s,table:a}of t){const E=A(_(i,m,a),s);let{cursor:f}=E,l=E.finished;for(;!l;){if(e.pages>=o)return e;const u=await P(i,a,f,d,n.ordered);if("error"in u)return{...e,error:u.error};const{failedIds:T,page:c}=u,g=c.documents.length+c.unparseable.length;e.pages+=g>0?1:0,e.rows+=g,e.failed+=T.length,e.failedIds=[...e.failedIds,...T].slice(0,w),f=c.lastId,l=!c.more,I(i,a,f,l,s)}}return{...e,done:!0}};export{S as VECTOR_BACKFILL_MAX_PAGES,p as VECTOR_BACKFILL_PAGE_ROWS,y as backfillVectorIndexes};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{m as x,c as T,l as R,r as E,a as P,w as D}from"./ctx-db-search-state-fIiMVPXO.mjs";import{S,c as U,g as v,d as A,e as k,a as b}from"./fts-companion-B7jllLhZ.mjs";import{sql as s}from"drizzle-orm";import{matchesStaticWhere as G}from"./AGGREGATE_SQL_FUNCTION-DDEoMnJR.mjs";import{aggregateTableName as W,encodeAggregateKey as B,foldAggregateTally as H}from"./aggregateTableName-C7o-gpms.mjs";import{rankColumnsSql as N,insertRankRow as K}from"./createCompanionSync-
|
|
1
|
+
import{m as x,c as T,l as R,r as E,a as P,w as D}from"./ctx-db-search-state-fIiMVPXO.mjs";import{S,c as U,g as v,d as A,e as k,a as b}from"./fts-companion-B7jllLhZ.mjs";import{sql as s}from"drizzle-orm";import{matchesStaticWhere as G}from"./AGGREGATE_SQL_FUNCTION-DDEoMnJR.mjs";import{aggregateTableName as W,encodeAggregateKey as B,foldAggregateTally as H}from"./aggregateTableName-C7o-gpms.mjs";import{rankColumnsSql as N,insertRankRow as K}from"./createCompanionSync-CGVFf7GK.mjs";import{runDrizzle as l,runAll as $}from"./runDrizzle-CfKnGpV2.mjs";import{i as C,h as O,D as p,r as M,a as Y,b as j,A as z}from"./do-sql-C7TkRQqw.mjs";import{sqliteInList as V}from"./param-DlozcSQu.mjs";import{isLiveForCompanion as J}from"./CURSOR_PREFIX-Bn8SFoGd.mjs";import{rankTableName as Q,matchesRankStaticWhere as X}from"./RANK_TIEBREAK-B0_x8iev.mjs";const L=(e,o)=>l(e,s`SELECT COUNT(*) AS count FROM ${s.identifier(o)}`).one().count>0,Z=(e,o)=>l(e,s`SELECT 1 FROM ${s.identifier(o)} LIMIT 1`).toArray().length>0,_=(e,o)=>l(e,s`SELECT id, _creationTime, ${s.identifier(p)} FROM ${s.identifier(o)}`).toArray(),q=(e,o,r,n)=>{const t=W(o,r.name);if(L(e,t))return;const a=r.by??[],c=new Map,i=_(e,o);for(const d of i){const f=M(d);if(!f||!J(f,n)||r.where&&!G(f,r.where))continue;const g=B(a,f);H(c,g,r,f)}for(const[d,f]of c)l(e,s`INSERT INTO ${s.identifier(t)} (${Y}, ${j}, ${z}) VALUES (${d}, ${f.value}, ${f.count})`)},pe=(e,o)=>{for(const[r,n]of Object.entries(o.tables))if(!(n.shardMode?.kind==="global"||!n.aggregateIndexes))for(const t of n.aggregateIndexes)q(e,r,t,n.softDeleteMode?.field)},ee=(e,o,r)=>{const n=Q(o,r.name);if(L(e,n))return;const t=N(r),a=_(e,o);for(const c of a){const i=M(c);!i||r.where&&!X(i,r.where)||K(e,n,r,t,i._id,i)}},Se=(e,o)=>{for(const[r,n]of Object.entries(o.tables))if(!(n.shardMode?.kind==="global"||!n.rankIndexes))for(const t of n.rankIndexes)ee(e,r,t)},oe=(e,o,r,n)=>l(e,r===void 0?s`SELECT id, _creationTime, ${s.identifier(p)} FROM ${s.identifier(o)} ORDER BY id ASC LIMIT ${s.raw(String(n))}`:s`SELECT id, _creationTime, ${s.identifier(p)} FROM ${s.identifier(o)} WHERE id > ${r} ORDER BY id ASC LIMIT ${s.raw(String(n))}`).toArray(),h=500,y=(e,o,r)=>{const n=S(o,r.name),t=T(r),a=R(E(e,n),t);if(a.finished)return{done:!0,rows:0};const{cursor:c}=a,i=oe(e,o,c,h);let d=c;for(const g of i){const{id:u}=g;if(typeof u!="string")continue;d=u;const I=O(g);$(e,I?A(n,u,k(I,r)):b(n,u))}const f=i.length<h;return D(e,n,d,f,t),{done:f,rows:i.length}},m=(e,o)=>s`${s.identifier(e)}.${s.identifier(o)}`,w=500,F=(e,o,r)=>{const n=S(o,r.name),t=l(e,U(n,w)).toArray(),a=v(t);if(a.size===0)return!0;const c=new Map;for(const i of l(e,s`SELECT ${m(o,"id")}, ${m(o,"_creationTime")}, ${m(o,p)} FROM ${s.identifier(o)} WHERE ${V(m(o,"id"),[...a.keys()],!1)}`))c.set(String(i.id),i);for(const[i,d]of a){const f=c.get(i),g=f?O(f):void 0;$(e,g?A(n,i,k(g,r),{unmappedRowids:d}):b(n,i,{unmappedRowids:d}))}return t.length<w},ne=(e,o,r,n)=>{let t=0;for(;t<n&&!F(e,o,r);)t+=1;return t},Ie=(e,o,r)=>{const n=S(o,r.name),t=T(r);return R(E(e,n),t).finished?!0:P(e,n)},he=(e,o,r)=>{if(C(e))for(const n of r.searchIndexes??[])F(e,o,n),!(n.staged&&Z(e,o))&&y(e,o,n)},re=(e,o,r,n)=>{let t=0;for(;;){if(t>=n)return{done:!1,pages:t};const a=y(e,o,r);if(a.rows>0&&(t+=1),a.done)return{done:!0,pages:t}}},we=(e,o,r={})=>{if(!C(e))return{done:!0,pages:0};x(e);const n=r.maxPages??Number.POSITIVE_INFINITY;let t=0;for(const[a,c]of Object.entries(o.tables))if(!(c.shardMode?.kind==="global"||!c.searchIndexes))for(const i of c.searchIndexes){if(t+=ne(e,a,i,n-t),t>=n)return{done:!1,pages:t};const d=re(e,a,i,n-t);if(t+=d.pages,!d.done)return{done:!1,pages:t}}return{done:!0,pages:t}};export{pe as backfillAggregateIndexes,Se as backfillRankIndexes,we as backfillSearchIndexes,he as backfillSearchIndexesForTable,F as drainUnmappedFtsRows,oe as readKeysetPage,Ie as searchIndexCoversTable};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{float64SqlKey as m}from"./BIGINT_KEY_DIGITS-C9a7Ix7k.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};
|
|
@@ -0,0 +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 d}from"./wire-codec-C-FpWm52.mjs";import{runSql as p}from"./runDrizzle-CfKnGpV2.mjs";import{k as m,D as E}from"./do-sql-C7TkRQqw.mjs";import{mayHoldProjectedValue as g}from"./BIGINT_KEY_DIGITS-C9a7Ix7k.mjs";const b=d(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{m(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-C5XCNb2J.mjs";import{selectShapeMembers as h}from"./selectShapeMembers-CIfYJUcu.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-CfKnGpV2.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-CfKnGpV2.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-B0_x8iev.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};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{N as re,S as se,d as ie,e as ce,a as ae}from"./fts-companion-B7jllLhZ.mjs";import{sql as e}from"drizzle-orm";import{matchesStaticWhere as V,aggregateSqlFunction as fe}from"./AGGREGATE_SQL_FUNCTION-DDEoMnJR.mjs";import{aggregateTableName as P,encodeAggregateKey as v,foldAggregateTally as z,coerceAggregateNumber as D}from"./aggregateTableName-C7o-gpms.mjs";import{runDrizzle as $,runAll as le}from"./runDrizzle-CfKnGpV2.mjs";import{i as $e,g as de,D as b,r as q,a as O,b as m,A as g,c as M,e as W}from"./do-sql-C7TkRQqw.mjs";import{param as ue,WORKERD_SQLITE_LIMITS as Ee}from"./param-DlozcSQu.mjs";import{encodeGeohash as ge,GEO_DEFAULT_PRECISION as pe}from"./GEO_DEFAULT_PRECISION-CqpQZ-J_.mjs";import{isLiveForCompanion as Q}from"./CURSOR_PREFIX-Bn8SFoGd.mjs";import{encodePartitionKey as ye,sortColumnName as _e,rankTableName as X,matchesRankStaticWhere as Y}from"./RANK_TIEBREAK-B0_x8iev.mjs";import{mayHoldProjectedValue as me}from"./BIGINT_KEY_DIGITS-C9a7Ix7k.mjs";import{serializeSqlValue as J}from"./serializeSqlValue-BbZ5hKM7.mjs";const he=(_,R,p)=>[..._.partitionBy??[],..._.sortBy.map(h=>h.field),..._.where?Object.keys(_.where):[]].every(h=>R[h]===p[h]),Z=_=>e.join(["__id__","__partition__",..._.sortBy.map((R,p)=>_e(p))].map(R=>e.identifier(R)),e`, `),N=(_,R,p,F,h,u)=>{const s=ye(p.partitionBy??[],u),C=p.sortBy.map(I=>J(u[I.field]??null)),L=e.join([h,s,...C].map(I=>ue(I)),e`, `);$(_,e`INSERT INTO ${e.identifier(R)} (${F}) VALUES (${L})`)},Te=(_,R,p,F,h,u)=>{if(h&&u&&he(p,h,u))return;const s=X(R,p.name);h&&$(_,e`DELETE FROM ${e.identifier(s)} WHERE ${e.identifier("__id__")} = ${F}`),!(!u||p.where&&!Y(u,p.where))&&N(_,s,p,Z(p),F,u)},be=_=>{const{broadcast:R,indexKeysFor:p,invalidateCache:F,recordCdc:h,schema:u,sql:s}=_,C=new Set,L=n=>u.tables[n]?.softDeleteMode?.field,I=new Set,U=(n,o)=>{const r=`${n}::${o.name}`;if(C.has(r))return;const c=P(n,o.name),a=o.by??[],f=L(n),d=new Map,y=$(s,e`SELECT id, _creationTime, ${e.identifier(b)} FROM ${e.identifier(n)}`).toArray();for(const T of y){const l=q(T);if(!l||!Q(l,f)||o.where&&!V(l,o.where))continue;const S=v(a,l);z(d,S,o,l)}$(s,e`DELETE FROM ${e.identifier(c)}`);const A=Math.floor(Ee.boundParams/3),w=[...d];for(let T=0;T<w.length;T+=A){const l=w.slice(T,T+A),S=e.join(l.map(([t,i])=>e`(${t}, ${i.value}, ${i.count})`),e`, `);$(s,e`INSERT INTO ${e.identifier(c)} (${O}, ${m}, ${g}) VALUES ${S}`)}C.add(r)},x=(n,o,r)=>{const c=o.by??[],a=o.field??"",f=[],d=(t,i)=>{const E=J(i);E===null?f.push(e`${W(t)} IS NULL`):f.push(e`${W(t)} = ${E}`)};for(const t of c)d(t,r[t]??null);const y=L(n);y!==void 0&&d(y,null);for(const[t,i]of Object.entries(o.where??{}))d(t,i!==null&&typeof i=="object"&&!Array.isArray(i)?i.eq:i);const A=f.length>0?e` WHERE ${e.join(f,e` AND `)}`:e``,w=u.tables[n]?.shape[a];if(w&&me(w)){const t=$(s,e`SELECT id, _creationTime, ${e.identifier(b)} FROM ${e.identifier(n)}${A}`).toArray(),i=new Map;for(const E of t){const k=q(E);k&&z(i,"",o,k)}return{value:i.get("")?.value??null}}const T=fe(o.op),l=W(a);return{value:$(s,e`SELECT ${e.raw(T)}(${l}) AS value FROM ${e.identifier(n)}${A}`).one().value??null}},ee=(n,o,r,c)=>{const a=P(n,o.name),{op:f}=o,d=o.field??"",y=t=>{$(s,e`DELETE FROM ${e.identifier(a)} WHERE ${O} = ${t} AND ${g} <= 0`)},A=L(n),w=t=>!o.where||V(t,o.where),T=t=>Q(t,A)&&w(t);c!==void 0&&f!=="count"&&w(c)&&D(c[d]);const l=r&&T(r)?r:void 0,S=c&&T(c)?c:void 0;if(!(!l&&!S)){if(f==="count"){for(const[t,i]of[[l,-1],[S,1]]){if(!t)continue;const E=v(o.by??[],t);$(s,M(a,E,i,i,e`${m} = ${m} + excluded.${m}, ${g} = ${g} + excluded.${g}`))}l&&y(v(o.by??[],l));return}if(f==="sum"||f==="avg"){for(const[t,i]of[[l,-1],[S,1]]){if(!t)continue;const E=D(t[d]);if(E===void 0)continue;const k=v(o.by??[],t);$(s,M(a,k,i*E,i,e`${m} = COALESCE(${m}, 0) + excluded.${m}, ${g} = ${g} + excluded.${g}`))}l&&y(v(o.by??[],l));return}if(l){const t=v(o.by??[],l),i=D(l[d]),E=$(s,e`SELECT ${m} AS value, ${g} AS count FROM ${e.identifier(a)} WHERE ${O} = ${t}`).toArray()[0],k=(E?.count??0)-1;if(k<=0)$(s,e`DELETE FROM ${e.identifier(a)} WHERE ${O} = ${t}`);else if(E&&i!==void 0&&E.value!==null&&i===E.value){const te=x(n,o,l);$(s,e`UPDATE ${e.identifier(a)} SET ${m} = ${te.value}, ${g} = ${k} WHERE ${O} = ${t}`)}else $(s,e`UPDATE ${e.identifier(a)} SET ${g} = ${g} - 1 WHERE ${O} = ${t}`)}if(S){const t=v(o.by??[],S),i=D(S[d]);if(i===void 0)$(s,M(a,t,null,1,e`${g} = ${g} + 1`));else{const E=f==="min"?"MIN":"MAX";$(s,M(a,t,i,1,e`${m} = ${e.raw(E)}(COALESCE(${m}, excluded.${m}), excluded.${m}), ${g} = ${g} + 1`))}}}},oe=n=>{for(const o of u.tables[n]?.aggregateIndexes??[])U(n,o)},j=(n,o,r)=>{for(const c of u.tables[n]?.aggregateIndexes??[])ee(n,c,o,r)},B=(n,o)=>{const r=`${n}::rank::${o.name}`;if(I.has(r))return;const c=X(n,o.name),a=$(s,e`SELECT id, _creationTime, ${e.identifier(b)} FROM ${e.identifier(n)}`).toArray();$(s,e`DELETE FROM ${e.identifier(c)}`);const f=Z(o);for(const d of a){const y=q(d);!y||o.where&&!Y(y,o.where)||N(s,c,o,f,y._id,y)}I.add(r)},ne=n=>{for(const o of u.tables[n]?.rankIndexes??[])B(n,o)},H=(n,o,r,c)=>{for(const a of u.tables[n]?.rankIndexes??[])Te(s,n,a,o,r,c)},K=(n,o,r,c)=>{const a=u.tables[n]?.searchIndexes??[];if(!(a.length===0||!$e(s)))for(const f of a){if(re(c,r,f))continue;const d=se(n,f.name);le(s,r?ie(d,o,ce(r,f)):ae(d,o))}},G=(n,o,r)=>{for(const c of u.tables[n]?.geoIndexes??[]){const a=de(n,c.name);$(s,e`DELETE FROM ${e.identifier(a)} WHERE ${e.identifier("__id__")} = ${o}`);const f=r?.[c.field];if(f!==null&&typeof f=="object"&&typeof f.lat=="number"&&typeof f.lng=="number"){const{lat:d,lng:y}=f,A=ge({lat:d,lng:y},c.precision??pe);$(s,e`INSERT INTO ${e.identifier(a)} (${e.identifier("__id__")}, ${e.identifier("__geohash__")}, ${e.identifier("__lat__")}, ${e.identifier("__lng__")}) VALUES (${o}, ${A}, ${d}, ${y})`)}}};return{ensureBackfilledForTable:oe,ensureBackfilledIndex:U,ensureRankBackfilled:B,ensureRankBackfilledForTable:ne,syncAggregates:j,syncCompanionsForInsert:(n,o,r)=>{K(n,o,r),G(n,o,r),j(n,void 0,r),H(n,o,void 0,r),F(n,o,r),h(n,o,"insert",r),R({indexKeys:p(n,r),key:o,op:"insert",row:r,table:n})},syncGeo:G,syncRanks:H,syncSearch:K}};export{be as createCompanionSync,N as insertRankRow,Z as rankColumnsSql};
|
package/dist/packem_shared/{createReplicaLink-CTyOjpjh.mjs → createReplicaLink-S5xtsySX.mjs}
RENAMED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{d as p,e as S}from"./wire-codec-C-FpWm52.mjs";import{cursorBelowRetainedFloor as y}from"./CDC_LOG_TABLE-
|
|
1
|
+
import{d as p,e as S}from"./wire-codec-C-FpWm52.mjs";import{cursorBelowRetainedFloor as y}from"./CDC_LOG_TABLE-C5XCNb2J.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
2
|
id INTEGER PRIMARY KEY CHECK (id = 1),
|
|
3
3
|
epoch TEXT NOT NULL,
|
|
4
4
|
applied_seq INTEGER NOT NULL,
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{createShardCtxDb as v}from"./NotUniqueError-
|
|
1
|
+
import{createShardCtxDb as v}from"./NotUniqueError-2vJ9edyE.mjs";import{createRelayLink as I}from"./DEFAULT_MAX_RELAYS-DG9iXjzF.mjs";import{ConflictError as N}from"./ConflictError-C8GtJmjS.mjs";import{runShardMigrations as _}from"./runShardMigrations-HaS2tHTS.mjs";import{relayName as F}from"./DEFAULT_PROMOTION_THRESHOLDS-Bfx7KakS.mjs";const E=(C,m={})=>({_meta:{column:{notNull:!0,...m}},kind:C}),W=(C,m,O)=>{const{describe:S,expect:n,it:y}=O;S(`engine contract: ${C}`,()=>{S("optimistic concurrency",()=>{const b=u=>({tables:{items:{indexes:[],shape:{title:E("string"),version:E("number",{notNull:!1})},triggerMap:{clobber:{handler:()=>{u.exec(`UPDATE "items" SET "__doc__" = json_set("__doc__", '$.version', 99) WHERE "id" = 'i1'`)},op:"update",timing:"before"}}}}});y("raises a CONFLICT of kind `occ` when a write's snapshot is clobbered",async()=>{const{close:u,host:h}=m();try{const i=h.sql,l=b(i);_(i,l);const s=v({schema:l,sql:i});await s.insert("items",{_id:"i1",title:"first",version:1},{allowExplicitId:!0}),await n(s.patch("i1",{title:"second"})).rejects.toBeInstanceOf(N)}finally{u?.()}}),y("reports the conflict as CONFLICT/409 rather than retrying it away",async()=>{const{close:u,host:h}=m();try{const i=h.sql,l=b(i);_(i,l);const s=v({schema:l,sql:i});await s.insert("items",{_id:"i1",title:"first",version:1},{allowExplicitId:!0});let o;try{await s.patch("i1",{title:"second"})}catch(t){o=t}const e=o;n(e.code).toBe("CONFLICT"),n(e.kind).toBe("occ")}finally{u?.()}}),y("leaves the row readable and unchanged after a conflict",async()=>{const{close:u,host:h}=m();try{const i=h.sql,l=b(i);_(i,l);const s=v({schema:l,sql:i});await s.insert("items",{_id:"i1",title:"first",version:1},{allowExplicitId:!0});try{await s.patch("i1",{title:"second"})}catch{}const o=await s.get("i1");n(o?.title).toBe("first"),n(o?.version).toBe(99)}finally{u?.()}}),y("raises a CONFLICT of kind `trigger` when a trigger writes its own row through the db",async()=>{const{close:u,host:h}=m();try{const i=h.sql,l={tables:{items:{indexes:[],shape:{title:E("string"),version:E("number",{notNull:!1})},triggerMap:{recurse:{handler:async(t,a)=>{await t.db.patch(a.doc._id,{version:99})},op:"update",timing:"before"}}}}};_(i,l);const s=v({schema:l,sql:i});await s.insert("items",{_id:"i1",title:"first",version:1},{allowExplicitId:!0});let o;try{await s.patch("i1",{title:"second"})}catch(t){o=t}const e=o;n(e).toBeInstanceOf(N),n(e.code).toBe("CONFLICT"),n(e.kind).toBe("trigger")}finally{u?.()}})}),S("shape-poke ordering",()=>{const b="shard-a",u={args:{},name:"messages"},h=(e,t,a,r)=>e.accept(t?.()??{},{connectionId:a,shapes:{[r]:u}}),i=(e,t,a)=>{let r=0,d=0;const c=g=>()=>{throw new Error(`the relay poke path must not reach RelayHost.${g}`)},p={fetch:(g,q)=>{if(JSON.parse(q?.body??"{}").type!=="relay_shape_subscribe")return Promise.resolve(new Response(void 0,{status:204}));const B=a[d];if(d+=1,B===void 0)throw new Error("the relay asked for more seeds than this fixture supplies");return Promise.resolve(Response.json(B))}},k={get:()=>p,getByName:()=>p,idFromName:g=>g},w={buildShapeDiff:c("buildShapeDiff"),computeOpLogShapeSeed:c("computeOpLogShapeSeed"),currentCdcEpoch:c("currentCdcEpoch"),deliverWhisperLocal:c("deliverWhisperLocal"),doName:()=>F(b,0),env:()=>({SHARD:k}),getWebSockets:()=>e.getSockets(),maskMetadata:c("maskMetadata"),nextPokeId:()=>(r+=1,`poke-${String(r)}`),readAttachment:g=>g.deserializeAttachment?.(),recordShapePokeFanout:()=>{},resolveShape:c("resolveShape"),rlsMetadata:c("rlsMetadata"),shardBinding:()=>"SHARD",shardJurisdiction:()=>{},sql:()=>t},f=I(w);if(f===void 0)throw new Error("expected a relay link for a `…::relay::N` name");return f},l=e=>new Request("https://relay.internal/_lunora/relay",{body:JSON.stringify(e),headers:{"content-type":"application/json"},method:"POST"}),s=async(e,t,a)=>{const r=await e.seedRelayShape(t,a,u,{identity:void 0,userId:void 0});if(r!=="ok")throw new Error(`seed failed: ${JSON.stringify(r)}`)},o=(e={})=>l({...u,checkpoint:20,epoch:"e1",fromCursor:10,rowsPatch:[{id:"r1",op:"upsert",value:{title:"hello"}}],type:"relay_shape_poke",...e});y("frames a poke as pokeStart → pokePart per shape → pokeEnd, under one poke id",async()=>{const{close:e,createSocket:t,host:a,readFrames:r,sockets:d}=m();try{const c=i(d,a.sql,[{cursor:10,epoch:"e1",frames:[]}]),p=h(d,t,"c-alice","s1");await s(c,p,"s1"),await c.handleControl(o());const w=(await r(p)).map(f=>JSON.parse(f));n(w.map(f=>f.type)).toStrictEqual(["pokeStart","pokePart","pokeEnd"]),n(new Set(w.map(f=>f.pokeId)).size).toBe(1),n(w[1]?.shapeId).toBe("s1"),n(w[2]?.checkpoint).toBe(20)}finally{e?.()}}),y("delivers a poke only to sockets whose cursor matches, and advances them past it",async()=>{const{close:e,createSocket:t,host:a,readFrames:r,sockets:d}=m();try{const c=i(d,a.sql,[{cursor:10,epoch:"e1",frames:[]},{cursor:7,epoch:"e1",frames:[]}]),p=h(d,t,"c-alice","s1"),k=h(d,t,"c-bob","s2");await s(c,p,"s1"),await s(c,k,"s2"),await c.handleControl(o());const w=await r(p);n(w.length).toBe(3);const f=await r(k);n(f.length).toBe(0),await c.handleControl(o());const g=await r(p);n(g.length).toBe(3)}finally{e?.()}}),y("skips a socket whose cursor matches under a different CDC epoch",async()=>{const{close:e,createSocket:t,host:a,readFrames:r,sockets:d}=m();try{const c=i(d,a.sql,[{cursor:10,epoch:"e1",frames:[]}]),p=h(d,t,"c-alice","s1");await s(c,p,"s1"),await c.handleControl(o({epoch:"e2"}));const k=await r(p);n(k.length).toBe(0),await c.handleControl(o());const w=await r(p);n(w.length).toBe(3)}finally{e?.()}})}),S("RLS identity under live subscription",()=>{const b="shard-a",u={args:{},name:"lobby-messages"},h={args:{},name:"my-orders"},i=s=>{const o=[],e=[],t={fetch:(d,c)=>(o.push(JSON.parse(c?.body??"{}")),Promise.resolve(new Response(void 0,{status:204})))},r=I({buildShapeDiff:()=>[{id:"r1",op:"upsert",value:{}}],computeOpLogShapeSeed:()=>({baseCheckpoint:void 0,cursor:10,epoch:"e1",reset:!0,rowsPatch:[]}),currentCdcEpoch:()=>"e1",deliverWhisperLocal:()=>0,doName:()=>b,env:()=>({SHARD:{get:()=>t,getByName:()=>t,idFromName:d=>d}}),getWebSockets:()=>[],maskMetadata:()=>({columns:[]}),nextPokeId:()=>"poke-1",readAttachment:()=>({}),recordShapePokeFanout:()=>{},resolveShape:(d,c,p)=>(e.push(p),d===h.name?{columns:["id"],effectiveWhere:{org:p?.identity?.org??"anonymous"},global:!1,table:"orders"}:{columns:["id"],effectiveWhere:{room:"lobby"},global:!1,table:"messages"}),rlsMetadata:()=>({policies:[]}),shardBinding:()=>"SHARD",shardJurisdiction:()=>{},sql:()=>s});if(r===void 0)throw new Error("expected an owner link for an un-suffixed DO name");return{owner:r,posts:o,resolvedUnder:e}},l=async(s,o)=>{await s.handleControl(new Request("https://owner.internal/_lunora/relay",{body:JSON.stringify({...o,connectionId:"c-alice",identity:{org:"acme"},relayIndex:0,subId:"s1",type:"relay_shape_subscribe",userId:"u1"}),headers:{"content-type":"application/json"},method:"POST"}))};y("seeds a subscriber under its own forwarded identity, never the anonymous one",async()=>{const{close:s,host:o}=m();try{const{owner:e,resolvedUnder:t}=i(o.sql);await l(e,h),n(t.some(a=>a?.userId==="u1"&&a.identity?.org==="acme")).toBe(!0)}finally{s?.()}}),y("routes an identity-scoped shape to a per-socket poke, not the cohort multicast",async()=>{const{close:s,host:o}=m();try{const{owner:e,posts:t}=i(o.sql);await l(e,h),t.length=0,await e.onFlush(new Set(["orders"]),20);const a=t.filter(r=>r.type==="relay_shape_poke");n(a.length).toBe(1),n(a[0]?.targetConnectionId).toBe("c-alice")}finally{s?.()}}),y("still multicasts an identity-blind shape to the whole cohort",async()=>{const{close:s,host:o}=m();try{const{owner:e,posts:t}=i(o.sql);await l(e,u),t.length=0,await e.onFlush(new Set(["messages"]),20);const a=t.filter(r=>r.type==="relay_shape_poke");n(a.length).toBe(1),n(a[0]?.targetConnectionId).toBeUndefined()}finally{s?.()}})})})};export{W as defineEngineContractSuite};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{LunoraError as _}from"@lunora/errors";import{sql as r}from"drizzle-orm";import{e as p}from"./effective-kind-BmG_zCAy.mjs";import{quoteIdentifier as A}from"./quoteIdentifier-CObIFRhb.mjs";import{d as T,n as $,e as S}from"./wire-codec-C-FpWm52.mjs";import{runDrizzle as f}from"./runDrizzle-CfKnGpV2.mjs";import{sqlComparableProjection as O}from"./BIGINT_KEY_DIGITS-C9a7Ix7k.mjs";import"./serializeSqlValue-BbZ5hKM7.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__",J=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=O(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 $(n)?JSON.stringify(S(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=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}},q=(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),B=e=>r.raw(y(e)),N=(e,t)=>E(`${A(e)}.`,t),z=(e,t)=>r.raw(N(e,t)),F=(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__"),W=(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}`,k=(e,t)=>e===void 0||t!==0&&t!==1||p(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},M=e=>{try{return C(e)}catch{return}},u=new WeakMap,V=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,W as c,F as d,B as e,z as f,q as g,M as h,V as i,y as j,J as k,g as l,h as m,a as n,k as o,N as q,C as r,K as t};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
const t=n=>{const{value:e}=n._meta??{};if(e===null)return"null";switch(typeof e){case"bigint":case"boolean":case"number":case"string":return typeof e;default:return n.kind}},i=n=>{if(n.kind==="literal")return t(n);if(n.kind!=="optional")return n.kind;const e=n._meta?.inner;return e?i(e):n.kind};export{i as e};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{BIGINT_KEY_DIGITS as c}from"./BIGINT_KEY_DIGITS-C9a7Ix7k.mjs";const n=40,s=i=>{let e=0;const o=(r,t)=>typeof t=="bigint"?(e+=c+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{s 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-CfKnGpV2.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-CfKnGpV2.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-N-f9jaQE.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-C5XCNb2J.mjs";import{selectShapeRows as m}from"./selectShapeMembers-CIfYJUcu.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-6nIZDf4m.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};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
const n=["every","is","isNot","none","some"],r=new Set(n),o=e=>{if(e===null||typeof e!="object"||Array.isArray(e))return!1;const s=Object.keys(e);return s.length>0&&s.every(t=>r.has(t))};export{r as R,o as i};
|
package/dist/packem_shared/{runShardMigrations-o-qjyKt5.mjs → runShardMigrations-HaS2tHTS.mjs}
RENAMED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{LunoraError as l}from"@lunora/errors";import{f as L,S as h}from"./fts-companion-B7jllLhZ.mjs";import{sql as r}from"drizzle-orm";import{aggregateTableName as O}from"./aggregateTableName-C7o-gpms.mjs";import{backfillSearchIndexesForTable as R}from"./backfillAggregateIndexes-
|
|
1
|
+
import{LunoraError as l}from"@lunora/errors";import{f as L,S as h}from"./fts-companion-B7jllLhZ.mjs";import{sql as r}from"drizzle-orm";import{aggregateTableName as O}from"./aggregateTableName-C7o-gpms.mjs";import{backfillSearchIndexesForTable as R}from"./backfillAggregateIndexes-yFyVVEHD.mjs";import{migrateCdcLog as x,migrateCdcMeta as N}from"./CDC_LOG_TABLE-C5XCNb2J.mjs";import{migrateClientWatermark as C}from"./CLIENT_WATERMARK_TABLE-BdKYbah0.mjs";import{migrateCommitSeq as $}from"./COMMIT_SEQ_FIELD-D6uMUaiR.mjs";import{migrateGlobalShapeSnapshot as b}from"./GLOBAL_SHAPE_SNAPSHOT_TABLE-wWaEWj5f.mjs";import{migrateIdempotency as D}from"./IDEMPOTENCY_TABLE-DKrXVEUe.mjs";import{m as U}from"./ctx-db-relay-shapes-BcgjOtG1.mjs";import{migrateScheduleOutbox as M}from"./SCHEDULE_OUTBOX_TABLE-BHpxtEy4.mjs";import{m as G}from"./ctx-db-search-state-fIiMVPXO.mjs";import{migrateShapePokeCursor as X}from"./SHAPE_POKE_CURSOR_TABLE-Bbpou9XZ.mjs";import{runDrizzle as s,runAll as y}from"./runDrizzle-CfKnGpV2.mjs";import{D as F,d as E,e as g,t as P,i as Y,g as k,a as B,b as j,A as p}from"./do-sql-C7TkRQqw.mjs";import{renderSql as v}from"./param-DlozcSQu.mjs";import{migrateDurableStreams as w}from"./appendStreamChunk-pPeR5nbF.mjs";import{rankTableName as H,sortColumnName as K}from"./RANK_TIEBREAK-B0_x8iev.mjs";import{migrateReactorState as W}from"./REACTOR_STATE_TABLE-CBHASjH9.mjs";import{recordSchemaVersion as V}from"./SCHEMA_HISTORY_MAX_VERSIONS-CXznJRUG.mjs";const A=r`_creationTime, id`,S=(e,i,o,t,n,a)=>{const c=r.join(n.map(d=>r`${d} IS NOT NULL`),r` AND `);if(s(e,r`SELECT 1 FROM ${r.identifier(o)} WHERE ${c} GROUP BY ${t} HAVING COUNT(*) > 1 LIMIT 1`).toArray().length>0)throw new l("INTERNAL",`unique index "${i}" on "${o}" ${a}: existing rows are duplicates under it. De-duplicate the table with a data migration first; the previous index is left in place.`)},z=(e,i,o,t,n,a)=>{const m=s(e,r`SELECT sql FROM sqlite_master WHERE type = 'index' AND name = ${i} AND tbl_name = ${o}`).toArray()[0]?.sql;if(m==null)return;const d=_=>{const u=_.indexOf("(");return u===-1?void 0:_.slice(u,_.lastIndexOf(")")+1)},T=d(v("sqlite",E(i,o,t,n)).sql),f=d(m);T===void 0||f===void 0||T===f||(n&&S(e,i,o,t,a,"cannot be re-created with its new column list"),s(e,r`DROP INDEX IF EXISTS ${r.identifier(i)}`))},J=(e,i,o)=>s(e,r`SELECT 1 FROM sqlite_master WHERE type = 'index' AND name = ${i} AND tbl_name = ${o} LIMIT 1`).toArray().length>0,I=(e,i,o,t,n,a)=>{n&&!J(e,i,o)&&S(e,i,o,t,a,"cannot be created"),s(e,E(i,o,t,n))},Q=(e,i,o)=>{for(const t of o.indexes){const n=`${i}_${t.name}`,a=t.unique??!1,c=t.fields.map(T=>g(T)),m=r.join(c,r`, `),d=a?m:r`${m}, ${A}`;z(e,n,i,d,a,c),I(e,n,i,d,a,c)}for(const[t,n]of P(o)){if(!n.unique)continue;const a=g(t);I(e,`${i}_unique_${t}`,i,a,!0,[a])}},Z=(e,i,o)=>{if(!(!o.searchIndexes||o.searchIndexes.length===0||!Y(e))){for(const t of o.searchIndexes)y(e,L(h(i,t.name)));R(e,i,o)}},q=(e,i,o)=>{if(o.geoIndexes)for(const t of o.geoIndexes){const n=k(i,t.name);s(e,r`CREATE TABLE IF NOT EXISTS ${r.identifier(n)} (${r.identifier("__id__")} TEXT PRIMARY KEY, ${r.identifier("__geohash__")} TEXT NOT NULL, ${r.identifier("__lat__")} REAL NOT NULL, ${r.identifier("__lng__")} REAL NOT NULL)`);const a=`${i}__geo_${t.name}__btree`;s(e,E(a,n,r`${r.identifier("__geohash__")} ASC, ${r.identifier("__id__")} ASC`,!1))}},ee=(e,i,o)=>{if(o.aggregateIndexes)for(const t of o.aggregateIndexes){const n=O(i,t.name);s(e,r`CREATE TABLE IF NOT EXISTS ${r.identifier(n)} (${B} TEXT PRIMARY KEY, ${j} REAL, ${p} INTEGER NOT NULL DEFAULT 0)`),s(e,r`PRAGMA table_info(${r.identifier(n)})`).toArray().some(c=>c.name==="__count__")||s(e,r`ALTER TABLE ${r.identifier(n)} ADD COLUMN ${p} INTEGER NOT NULL DEFAULT 0`)}},re=(e,i,o)=>{if(o.rankIndexes)for(const t of o.rankIndexes){const n=H(i,t.name),a=t.sortBy.map((f,_)=>K(_)),c=a.map(f=>r`${r.identifier(f)} BLOB`),m=c.length>0?r`, ${r.join(c,r`, `)}`:r``;s(e,r`CREATE TABLE IF NOT EXISTS ${r.identifier(n)} (${r.identifier("__id__")} TEXT PRIMARY KEY, ${r.identifier("__partition__")} TEXT NOT NULL${m})`);const d=[r`${r.identifier("__partition__")} ASC`];for(const[f,_]of a.entries()){const u=t.sortBy[f]?.direction;d.push(r`${r.identifier(_)} ${r.raw(u==="desc"?"DESC":"ASC")}`)}d.push(r`${r.identifier("__id__")} ASC`);const T=`${i}__rank_${t.name}__btree`;s(e,E(T,n,r.join(d,r`, `),!1))}},he=(e,i,o={})=>{o.schemaSnapshot!==void 0&&V(e,o.schemaSnapshot.hash,o.schemaSnapshot.json),G(e);for(const[t,n]of Object.entries(i.tables))n.shardMode?.kind!=="global"&&(s(e,r`CREATE TABLE IF NOT EXISTS ${r.identifier(t)} (
|
|
2
2
|
id TEXT PRIMARY KEY,
|
|
3
3
|
_creationTime REAL NOT NULL,
|
|
4
4
|
${r.identifier(F)} TEXT NOT NULL
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{sql as o}from"drizzle-orm";import{runDrizzle as h}from"./runDrizzle-CfKnGpV2.mjs";import{e}from"./do-sql-
|
|
1
|
+
import{sql as o}from"drizzle-orm";import{runDrizzle as h}from"./runDrizzle-CfKnGpV2.mjs";import{e}from"./do-sql-C7TkRQqw.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-Cp98I-ot.mjs → selectShapeMembers-CIfYJUcu.mjs}
RENAMED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{sql as e}from"drizzle-orm";import{runDrizzle as m}from"./runDrizzle-CfKnGpV2.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-CfKnGpV2.mjs";import{D as p,r as d,e as h}from"./do-sql-C7TkRQqw.mjs";import{sqliteInList as w}from"./param-DlozcSQu.mjs";import{c as S}from"./where-sql-x1YKldcq.mjs";import{serializeSqlValue as $}from"./serializeSqlValue-BbZ5hKM7.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};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{sqlComparableProjection as o}from"./BIGINT_KEY_DIGITS-C9a7Ix7k.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{e as O}from"./effective-kind-BmG_zCAy.mjs";import{i as a}from"./relation-operators-BEg-CvCH.mjs";const u=Symbol.for("lunora.reader.whereFilter"),A=(e,r)=>Object.assign(t=>r(t),{[u]:e}),R=e=>e[u],m=new Set(["eq","in","isNull","ne","notIn"]),b=e=>e!==null&&typeof e=="object"&&Object.getPrototypeOf(e)===Object.prototype,l=(e,r)=>{if(e==="_id")return"string";if(e==="_creationTime")return"number";const t=e==="id"||!Object.hasOwn(r,e)?void 0:r[e];switch(t===void 0?void 0:O(t)){case"boolean":return"boolean";case"id":case"string":return"string";case"number":return"number";default:return}},c=(e,r)=>e===null||(r==="number"?typeof e=="number"&&Number.isFinite(e):typeof e===r),d=(e,r)=>Object.entries(e).every(([t,i])=>{if(t==="AND"||t==="OR")return Array.isArray(i)&&i.every(n=>b(n)&&d(n,r));if(t==="NOT"||a(i))return!1;const o=l(t,r);if(o===void 0)return!1;if(!b(i))return c(i,o);const f=Object.entries(i);return f.length>0&&f.every(([n,s])=>m.has(n)?n==="isNull"?typeof s=="boolean":n==="in"||n==="notIn"?Array.isArray(s)&&s.every(y=>c(y,o)):c(s,o):!1)});export{d as isPushableWhere,A as whereFilter,R as whereOfFilter};
|
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.84",
|
|
4
4
|
"description": "Host-neutral reactive engine for Lunora: per-shard state, OCC, CDC, reactive subscriptions, and the poke protocol. Consumes @lunora/platform host contracts and can be mounted on any platform host.",
|
|
5
5
|
"keywords": [
|
|
6
6
|
"cloudflare",
|
|
@@ -49,7 +49,7 @@
|
|
|
49
49
|
},
|
|
50
50
|
"dependencies": {
|
|
51
51
|
"@lunora/errors": "1.0.0-alpha.41",
|
|
52
|
-
"@lunora/platform": "1.0.0-alpha.
|
|
52
|
+
"@lunora/platform": "1.0.0-alpha.37",
|
|
53
53
|
"drizzle-orm": "^0.45.2"
|
|
54
54
|
},
|
|
55
55
|
"engines": {
|
|
@@ -1 +0,0 @@
|
|
|
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-BSoH-O04.mjs";import{quoteIdentifier as g}from"./quoteIdentifier-CObIFRhb.mjs";import"./wire-codec-C-FpWm52.mjs";import"./runDrizzle-CfKnGpV2.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};
|
|
@@ -1 +0,0 @@
|
|
|
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};
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{LunoraError as u}from"@lunora/errors";import{isMemoryTable as p}from"./clearMemoryTables-C5Wivufe.mjs";import{distinctValues as v}from"./applyOnDelete-7JZ4vR9r.mjs";import{RELATION_EXISTS_KEY as j}from"./RELATION_EXISTS_KEY-CFUhnZSZ.mjs";const S=["every","is","isNot","none","some"],O=new Set(S),$=e=>{if(e===null||typeof e!="object"||Array.isArray(e))return!1;const t=Object.keys(e);return t.length>0&&t.every(r=>O.has(r))},E={every:{kind:"many",negateChild:!0,negated:!0},is:{kind:"one",negated:!1},isNot:{kind:"one",negated:!0,nullDisjunct:!0},none:{kind:"many",negated:!0},some:{kind:"many",negated:!1}},R=e=>O.has(e)?e:void 0,w=e=>{const t=R(e),r=t===void 0?void 0:E[t];if(!r)throw new u("INTERNAL",`unknown relation operator "${e}"`);return r},_=e=>e.kind==="one"?{clause:e.field,project:e.references}:{clause:e.references,project:e.field},L=5e3,h=Symbol("relation-key-overflow"),m=e=>Array.isArray(e)?e.map(t=>t??{}):[],A=e=>{if(e.length===1){const[t]=e;return t??{}}return e.length===0?{}:{AND:e}},y=e=>$(e),l=(e,t,r)=>{const n=t.tables[r]?.relationMap??{};return Object.keys(e).some(s=>{const o=e[s];return s==="AND"||s==="OR"?m(o).some(a=>l(a,t,r)):s==="NOT"?l(o??{},t,r):!!n[s]&&y(o)})},Y=(e,t,r,n)=>{if(e&&l(e,t,r))throw new u("INTERNAL",`relation-crossing predicates are not supported in ${n}() — use them in findMany/findFirst or an RLS read policy`)},M=async(e,t,r,n,s)=>{const o=await d(t,e.table,n),{page:a}=await n.fetcher(e.table,{baseWhere:n.relationBaseWhere?.(e.table),relationBaseWhere:n.relationBaseWhere,where:o}),i=v(a,r);if(i.length>n.maxRelationKeys){if(s)return h;throw new u("INTERNAL",`relation predicate on "${e.table}" matched ${String(i.length)} rows, exceeding the ${String(n.maxRelationKeys)}-key limit; narrow the predicate (a same-shard EXISTS push-down lifts this cap)`)}return i},P=async(e,t,r,n,s)=>{const o=w(e),{clause:a,project:i}=_(t),c=await M(t,o.negateChild?{NOT:r}:r,i,n,s);return c===h?h:o.negated?o.nullDisjunct?{OR:[{[a]:{notIn:c}},{[a]:{isNull:!0}}]}:{[a]:{notIn:c}}:{[a]:{in:c}}},b=async(e,t,r,n,s)=>{const o=w(e),a=s.relationBaseWhere?.(t.table),i=o.negateChild?{NOT:r}:r,N={childWhere:await d(a?{AND:[a,i]}:i,t.table,s),negated:o.negated,parentTable:n,relation:t};return{[j]:N}},k=(e,t,r)=>{const n=R(e),s=n===void 0?void 0:E[n];if(s&&s.kind!==r.kind)throw new u("INTERNAL",`relation operator "${e}" requires a to-${s.kind} relation, but "${t}" is to-${r.kind}`)},I=async(e,t,r,n,s)=>{const o=[];for(const a of Object.keys(r)){k(a,e,t);const i=r[a]??{},c=s.canPushExists?.(t)??!1;if(c&&s.existsPushMode==="always"){o.push(await b(a,t,i,n,s));continue}const f=await P(a,t,i,s,c);f===h?o.push(await b(a,t,i,n,s)):o.push(f)}return A(o)},D=async(e,t,r,n)=>{if(e==="AND"||e==="OR"){const o=[];for(const a of m(t))o.push(await d(a,r,n));return{[e]:o}}if(e==="NOT")return{NOT:await d(t??{},r,n)};const s=n.schema.tables[r]?.relationMap?.[e];return s&&y(t)?I(e,s,t,r,n):{[e]:t}},d=async(e,t,r)=>{const n=[];for(const s of Object.keys(e))n.push(await D(s,e[s],t,r));return A(n)},H=async(e,t)=>!e||!l(e,t.schema,t.tableName)?e:d(e,t.tableName,{canPushExists:t.canPushExists,existsPushMode:t.existsPushMode??"auto",fetcher:t.fetcher,maxRelationKeys:t.maxRelationKeys??L,relationBaseWhere:t.relationBaseWhere,schema:t.schema}),g=(e,t,r)=>{for(const n of e){const s=T(n,t,r);if(s)return s}},K=(e,t,r,n)=>{if(e==="AND"||e==="OR")return g(m(t),r,n);if(e==="NOT")return g([t??{}],r,n);const s=r.tables[n]?.relationMap?.[e];if(!(!s||!y(t)))return r.tables[s.table]?.shardMode?.kind==="shardBy"?{kind:"shard",relation:e,target:s.table}:p(r.tables[s.table])?{kind:"memory",relation:e,target:s.table}:g(Object.values(t),r,s.table)},T=(e,t,r)=>{for(const n of Object.keys(e)){const s=K(n,e[n],t,r);if(s)return s}},q=(e,t,r)=>{if(p(t.tables[r]))throw Object.assign(new Error(`shape on "${r}" replicates from the changelog, which never records a .memory() table — the shape would seed once and never update again. Fix it by (a) dropping .memory() from "${r}" so its writes reach the changelog, or (b) reading it through a live query (\`useQuery\`), which refreshes off the changed-table set rather than the log.`),{code:"SHAPE_MEMORY_TABLE",name:"LunoraError",status:400});if(!e)return;const n=T(e,t,r);if(n)throw n.kind==="memory"?Object.assign(new Error(`shape on "${r}" joins the .memory() table "${n.target}" via relation "${n.relation}" — writes to a .memory() table never reach the changelog, so the shape is never told its membership changed and would serve stale rows indefinitely. Fix it by (a) dropping .memory() from "${n.target}", or (b) reading it through a live query (\`useQuery\`), which refreshes off the changed-table set rather than the log.`),{code:"SHAPE_MEMORY_TABLE",name:"LunoraError",status:400}):Object.assign(new Error(`shape on "${r}" joins the sharded table "${n.target}" via relation "${n.relation}" — a live shape cannot replicate rows that live in another shard's Durable Object. Fix it by (a) denormalizing the joined columns into "${r}", or (b) moving "${n.target}" to .global() so it is served through the latency-tiered D1 shape tier.`),{code:"SHAPE_CROSS_SHARD_JOIN",name:"LunoraError",status:400})};export{L as DEFAULT_MAX_RELATION_KEYS,Y as assertFlatPredicate,q as assertShapeShardable,l as containsRelationPredicate,y as isRelationPredicate,H as resolveRelationPredicates};
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{LunoraError as $}from"@lunora/errors";import{D as dt}from"./MAX_TOKEN_LENGTH-BakL9FUy-B3VwYY8C.mjs";import{S as En,l as Fe,h as Sn}from"./fts-companion-B7jllLhZ.mjs";import{sql as i}from"drizzle-orm";import{d as _n}from"./wire-codec-C-FpWm52.mjs";import{stableWireKey as At}from"./stableWireKey-D2US4k_J.mjs";import{throwingScheduler as Rn,aggregateSqlFunction as qe,normalizeCountArgument as Tn}from"./AGGREGATE_SQL_FUNCTION-DDEoMnJR.mjs";import{aggregateTableName as Je,encodeAggregateKey as Ye,readAggregateValue as Xe}from"./aggregateTableName-C7o-gpms.mjs";import{mergeWhere as z,CountRlsUnsupportedError as Ze,selectIndexForGroupBy as vn,selectIndexForCount as An,selectIndexForAggregate as In}from"./CountRlsUnsupportedError-BvsDqfO2.mjs";import{backfillSearchIndexesForTable as Cn,searchIndexCoversTable as xn}from"./backfillAggregateIndexes-D-S4qiCu.mjs";import{backfillAggregateIndexes as Ur,backfillRankIndexes as Gr,backfillSearchIndexes as Or}from"./backfillAggregateIndexes-D-S4qiCu.mjs";import{appendCdcChange as bn,readCdcDocAtOrBefore as Mn}from"./CDC_LOG_TABLE-BFbP2eiJ.mjs";import{CDC_LOG_TABLE as Nr,applyCdcChanges as jr,bumpCdcEpoch as Kr,cdcCanVouchFor as Qr,cdcForkedError as Vr,cdcSeqLeavingRows as zr,cdcTouchesTables as Jr,cdcTrimmedError as Yr,compactCdcDocs as Xr,cursorBelowRetainedFloor as Zr,minCdcReplayableSeq as ei,minCdcSeq as ti,readCdcChangeKeys as ni,readCdcChanges as oi,readCdcCursor as ri,readCdcEpoch as ii,trimCdcChanges as si}from"./CDC_LOG_TABLE-BFbP2eiJ.mjs";import{allocateCommitSeq as Dn,COMMIT_SEQ_FIELD as kn}from"./COMMIT_SEQ_FIELD-D6uMUaiR.mjs";import{createCompanionSync as Ln}from"./createCompanionSync-BwWcSwvy.mjs";import{isMemoryTable as It}from"./clearMemoryTables-C5Wivufe.mjs";import{computeRankPage as Ct}from"./computeRankPage-CQewnemg.mjs";import{SCAN_DEP as O}from"./SCAN_DEP-D7qE3iUe.mjs";import{runDrizzle as N,runSql as _e}from"./runDrizzle-CfKnGpV2.mjs";import{D as ne,k as ce,r as le,b as Be,A as et,a as We,e as X,o as Fn,t as Yt,j as Ge,q as xt,i as qn,h as Xt,g as Bn}from"./do-sql-BSoH-O04.mjs";import{renderSql as Zt,unionAll as lt,WORKERD_SQLITE_LIMITS as en,sqliteInList as Wn}from"./param-DlozcSQu.mjs";import{coveringGeohashes as Pn,boundingBoxGeohashes as Un,haversineMeters as Gn,pointInBoundingBox as On}from"./GEO_DEFAULT_PRECISION-CqpQZ-J_.mjs";import{NotFoundError as Hn}from"./NotFoundError-BhF7FeFr.mjs";import{softDeleteScope as de,normalizeOrderKeys as it,uniqueIndexFields as tn,equalityPinnedFields as Nn,buildSeekWhere as nn,decodeCursor as st,applySelect as bt,encodeCursor as ct,tiebreakDirectionFor as on,buildSeekBeforeWhere as jn}from"./CURSOR_PREFIX-Bn8SFoGd.mjs";import{rankTableName as Mt,sortColumnName as Dt,resolveRankPartition as Kn,encodePartitionKey as Qn,RANK_TIEBREAK as Vn,rankPivotConditionSql as zn}from"./RANK_TIEBREAK-D5xNdzB3.mjs";import{UNVOUCHABLE_DEP as kt}from"./UNVOUCHABLE_DEP-C68htACn.mjs";import{indexKeysForRow as Jn,buildIndexRange as Yn}from"./buildIndexRange-DvN8Qj8e.mjs";import{deriveRelationEdges as Xn,findRelated as Zn}from"./RELATED_DEFAULT_LIMIT-B9PH28Pn.mjs";import{assertFlatPredicate as tt,resolveRelationPredicates as Lt}from"./DEFAULT_MAX_RELATION_KEYS-BfAQvZT8.mjs";import{runRowValidators as nt,resolveWith as Ft,relationHooks as qt,applyOnDelete as eo,fanOutScalarCounts as to}from"./applyOnDelete-7JZ4vR9r.mjs";import{guardWriter as no}from"./RLS_UNWRAP_SYMBOL-BwwTbz3Q.mjs";import{quoteIdentifier as Re}from"./quoteIdentifier-CObIFRhb.mjs";import{m as oo}from"./sql-projection-D3qdaItY.mjs";import{createSystemReader as ro}from"./createSystemReader-DcDLFfC-.mjs";import{ConflictError as Ee}from"./ConflictError-C8GtJmjS.mjs";import{runTriggers as io}from"./hasTrigger-CjlwI4le.mjs";import{c as te,t as He,r as Oe,j as Se,i as Bt}from"./where-sql-x1YKldcq.mjs";import{CLIENT_WATERMARK_TABLE as ai,advanceClientWatermark as di,migrateClientWatermark as li,readClientWatermark as ui}from"./CLIENT_WATERMARK_TABLE-BdKYbah0.mjs";import{GLOBAL_SHAPE_SNAPSHOT_TABLE as hi,deleteGlobalShapeSnapshot as wi,deleteGlobalShapeSnapshotsForConnection as pi,migrateGlobalShapeSnapshot as gi,readGlobalShapeSnapshot as $i,writeGlobalShapeSnapshot as yi}from"./GLOBAL_SHAPE_SNAPSHOT_TABLE-wWaEWj5f.mjs";import{IDEMPOTENCY_TABLE as Ei,readIdempotent as Si,trimIdempotent as _i,writeIdempotent as Ri}from"./IDEMPOTENCY_TABLE-DKrXVEUe.mjs";import{runShardMigrations as vi}from"./runShardMigrations-o-qjyKt5.mjs";import{S as Ii}from"./ctx-db-search-state-fIiMVPXO.mjs";import{selectShapeMembers as xi,selectShapeRows as bi}from"./selectShapeMembers-Cp98I-ot.mjs";import{serializeSqlValue as oe}from"./serializeSqlValue-BEMMYX1n.mjs";const so=n=>{const r=atob(n),o=Uint8Array.from(r,a=>a.codePointAt(0)??0);return new TextDecoder().decode(o)},co=()=>new $("BAD_REQUEST","invalid cursor"),Wt=16,Pt=8,Y=1024,ut=(n,r)=>r.query(n),ao=(n,r)=>{if(n.length===0)return 0;let o=0;for(const[a,s]of r.entries()){const w=a===r.length-1;let y=0;for(const R of n)(w?R.startsWith(s):R===s)&&(y+=1);if(y===0)return 0;o+=y}return o},lo=(n,r)=>{if(!r)return{exact:!0,lower:n,upper:n};const o=[...n].at(-1)??"",a=(o.codePointAt(0)??0)+1;if(a>=55296&&a<=57343||a>1114111)return{exact:!0,lower:n,upper:n};const s=n.slice(0,n.length-o.length);return{exact:!1,lower:n,upper:s+String.fromCodePoint(a)}},uo=(n,r,o)=>{const a={eq:(s,w)=>{if(!n.definition.filterFields?.includes(s))throw new $("INTERNAL",`field "${s}" is not a filter field of search index "${n.indexName}" on table "${r}"`);if(n.filters.length>=Pt)throw new $("BAD_REQUEST",`search index "${n.indexName}" on table "${r}": at most ${String(Pt)} .eq() filters are supported per search query`);return n.filters.push({field:s,value:w}),a},search:(s,w)=>{const y=n;if(s!==y.definition.field)throw new $("INTERNAL",`search index "${y.indexName}" on table "${r}" indexes "${y.definition.field}", not "${s}"`);const R=ut(w,o).length;if(R>Wt)throw new $("BAD_REQUEST",`search index "${y.indexName}" on table "${r}": at most ${String(Wt)} search terms are supported (got ${String(R)})`);return y.field=s,y.query=w,y.hasQuery=!0,a}};return a},fo=n=>{if(n.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()`)},ho=n=>Math.min(n.offset+n.numItems+1,Y),wo=n=>btoa(`search:${String(n)}`),po=n=>{let r;try{r=so(n)}catch{return}if(!r.startsWith("search:"))return;const o=Number(r.slice(7));return Number.isInteger(o)&&o>=0?o:void 0},go=n=>{if(typeof n.endCursor=="string")throw new $("BAD_REQUEST","bounded (endCursor) pagination is not supported on search queries — relevance order has no stable range boundary");if(!Number.isFinite(n.numItems))throw new $("BAD_REQUEST",`search pagination needs a finite numItems, got ${String(n.numItems)}`);const r=Math.max(0,Math.floor(n.numItems)),o=n.cursor?po(n.cursor):0;if(o===void 0)throw co();if(o+r>=Y)throw new $("BAD_REQUEST",`search pagination reaches the ${String(Y)}-document limit (offset ${String(o)} + ${String(r)} requested) — a page must end below the cap so the probe row that answers \`hasMore\` still fits: retry with numItems ${String(Math.max(1,Y-o-1))} or fewer, or narrow the query or the filters instead`);return{numItems:r,offset:o}},$o=(n,r)=>{const o=r.offset+r.numItems,a=r.numItems>0&&n.length>o;return{continueCursor:a?wo(o):null,isDone:!a,page:n.slice(r.offset,o)}},yo=n=>{if(n===void 0)return Y+1;if(!Number.isFinite(n))return Y;const r=Math.max(0,Math.floor(n));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},Ne=n=>{const r=new Map;return o=>{const a=r.get(o);if(a!==void 0)return a;const s=n(Re(o));return r.set(o,s),s}},ue=Re(ne),mo=Ne(n=>`INSERT INTO ${n} (id, _creationTime, ${ue}) VALUES (?, ?, ?)`),Ut=Ne(n=>`UPDATE ${n} SET ${ue} = ? WHERE id = ? AND ${ue} = ?`),Eo=Ne(n=>`UPDATE ${n} SET _creationTime = ?, ${ue} = ? WHERE id = ? AND ${ue} = ?`),So=Ne(n=>`DELETE FROM ${n} WHERE id = ? AND ${ue} = ?`),_o="SELECT changes() AS changed",Gt=new Map,Ro="",To=n=>{const r=JSON.stringify(n),o=Gt.get(r);if(o!==void 0)return o;const a=n.map(w=>i`SELECT ${i.raw(`'${w.replaceAll("'","''")}'`)} AS __t__, id, _creationTime, ${i.identifier(ne)} FROM ${i.identifier(w)} WHERE id = ${Ro}`),{sql:s}=Zt("sqlite",i`${lt(a)} LIMIT 1`);return Gt.set(r,s),s},vo=(n,r)=>r.map(()=>n),Ao=/^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/iu,Io=n=>{if(!Ao.test(n))throw new $("INTERNAL",`invalid clientId ${JSON.stringify(n)}: a client-supplied row id must be a UUID`)},Ot=50,rn=500,Pe=Math.floor(en.boundParams/3),ye=en.boundParams,Co=128,ae=(n,r,o)=>{const a=r??rn;if(n>a)throw new $("BATCH_LIMIT_EXCEEDED",`${o}: batch of ${String(n)} exceeds the limit of ${String(a)} (raise options.limit or chunk the call)`,{status:400})},xo=n=>{const r={eq:(o,a)=>(n.sqlConditions.push({comparator:"=",field:o,value:a}),r),gt:(o,a)=>(n.sqlConditions.push({comparator:">",field:o,value:a}),r),gte:(o,a)=>(n.sqlConditions.push({comparator:">=",field:o,value:a}),r),lt:(o,a)=>(n.sqlConditions.push({comparator:"<",field:o,value:a}),r),lte:(o,a)=>(n.sqlConditions.push({comparator:"<=",field:o,value:a}),r)};return r},bo=n=>Math.max(n,Y),sn=(n,r)=>{const o=n.filters.map(a=>i`${X(a.field)} = ${oe(a.value)}`);return r&&o.push(r),o},Mo=(n,r,o,a,s)=>{const w=ut(o.query,dt(o.definition.language));if(w.length===0)return[];const y=En(r,o.indexName),R=`${y}__vocab`,_=w.length-1,k=w.map((q,F)=>{const W=lo(q,F===_),x=W.exact?i`${i.identifier("term")} = ${W.lower}`:i`${i.identifier("term")} >= ${W.lower} AND ${i.identifier("term")} < ${W.upper}`;return i`SELECT ${i.identifier("doc")}, ${i.raw(String(F))} AS ${i.identifier("__term__")}, COUNT(*) AS ${i.identifier("__n__")} FROM ${i.identifier(R)} WHERE ${x} GROUP BY ${i.identifier("doc")}`}),g=w.map((q,F)=>i`SUM(CASE WHEN u.${i.identifier("__term__")} = ${i.raw(String(F))} THEN u.${i.identifier("__n__")} ELSE 0 END)`),v=i`SELECT f.${i.identifier(Fe)} AS ${i.identifier(Fe)}, ${i.join(g,i` + `)} AS ${i.identifier("__score__")} FROM (${lt(k)}) u JOIN ${i.identifier(y)} f ON f.rowid = u.${i.identifier("doc")} GROUP BY f.${i.identifier(Fe)} HAVING ${i.join(g.map(q=>i`${q} > 0`),i` AND `)}`,T=sn(o,s);let L=i`SELECT m.id, m._creationTime, m.${i.identifier(ne)}, s.${i.identifier("__score__")} AS ${i.identifier("__score__")} FROM (${v}) s JOIN ${i.identifier(r)} m ON m.id = s.${i.identifier(Fe)}`;T.length>0&&(L=i`${L} WHERE ${i.join(T,i` AND `)}`),L=i`${L} ORDER BY s.${i.identifier("__score__")} DESC, m._creationTime DESC, m.id ASC LIMIT ${i.raw(String(a))}`;const H=[];for(const q of N(n,L)){const F=Xt(q);if(F){const W=q.__score__;H.push({document:F,score:typeof W=="number"?W:Number(W??0)})}}return H},Do=(n,r,o,a,s)=>{const w=dt(o.definition.language),y=ut(o.query,w);if(y.length===0)return[];const R=sn(o,s);let _=i`SELECT id, _creationTime, ${i.identifier(ne)} FROM ${i.identifier(r)}`;R.length>0&&(_=i`${_} WHERE ${i.join(R,i` AND `)}`),_=i`${_} ORDER BY _creationTime DESC, id ASC LIMIT ${i.raw(String(bo(a)))}`;const k=N(n,_).toArray(),g=[];for(const v of k){const T=Xt(v);if(!T)continue;const L=ao(Sn(T,o.definition),y);L>0&&g.push({creationTime:typeof T._creationTime=="number"?T._creationTime:0,doc:T,id:typeof T._id=="string"?T._id:"",score:L})}return g.sort((v,T)=>T.score-v.score||T.creationTime-v.creationTime||v.id.localeCompare(T.id)),g.slice(0,a).map(v=>({document:v.doc,score:v.score}))},ot=(n,r,o,a)=>{if(!Number.isFinite(n.lat)||n.lat<-90||n.lat>90||!Number.isFinite(n.lng)||n.lng<-180||n.lng>180)throw new $("BAD_REQUEST",`geo index "${a}" on table "${o}": ${r} must have a finite lat in [-90, 90] and lng in [-180, 180]`)},ko=(n,r)=>{const o=n,a={near:(s,w)=>{if(o.within)throw new $("INTERNAL",`geo index "${o.indexName}" on table "${r}": call .near() or .within(), not both`);if(ot(s,".near() point",r,o.indexName),!Number.isFinite(w)||w<=0)throw new $("BAD_REQUEST",`geo index "${o.indexName}" on table "${r}": .near() radiusMeters must be a finite number > 0, got ${String(w)}`);return o.near={point:{lat:s.lat,lng:s.lng},radiusMeters:w},a},within:s=>{if(o.near)throw new $("INTERNAL",`geo index "${o.indexName}" on table "${r}": call .near() or .within(), not both`);if(ot(s.sw,".within() sw corner",r,o.indexName),ot(s.ne,".within() ne corner",r,o.indexName),s.sw.lat>s.ne.lat)throw new $("BAD_REQUEST",`geo index "${o.indexName}" on table "${r}": .within() corners are transposed (sw.lat > ne.lat)`);if(s.sw.lng>s.ne.lng)throw new $("BAD_REQUEST",`geo index "${o.indexName}" on table "${r}": .within() box crosses the antimeridian (sw.lng > ne.lng), which is not supported — split it into two boxes at ±180 and union the results`);return o.within={ne:{lat:s.ne.lat,lng:s.ne.lng},sw:{lat:s.sw.lat,lng:s.sw.lng}},a}};return a},Lo=(n,r)=>{const o=n[r];if(o===null||typeof o!="object")return;const{lat:a,lng:s}=o;return typeof a=="number"&&typeof s=="number"?{lat:a,lng:s}:void 0},Fo=(n,r)=>{const o=Lo(n,r.definition.field);if(!o)return;const a=typeof n._creationTime=="number"?n._creationTime:0;if(r.near){const s=Gn(r.near.point,o);return s<=r.near.radiusMeters?{creationTime:a,distance:s}:void 0}return On(o,r.within)?{creationTime:a,distance:0}:void 0},qo=(n,r,o,a)=>{if(!o.near&&!o.within)throw new $("INTERNAL",`geo index "${o.indexName}" on table "${r}": call .near(point, radius) or .within(box)`);const s=o.near?Pn(o.near.point,o.near.radiusMeters):Un(o.within),w=Bn(r,o.indexName),y=s.map(v=>i`(g.${i.identifier("__geohash__")} >= ${v} AND g.${i.identifier("__geohash__")} < ${`${v}{`})`),R=[i`(${i.join(y,i` OR `)})`];a&&R.push(a);const _=i`SELECT m.id, m._creationTime, m.${i.identifier(ne)} FROM ${i.identifier(w)} g JOIN ${i.identifier(r)} m ON m.id = g.${i.identifier("__id__")} WHERE ${i.join(R,i` AND `)}`,k=N(n,_).toArray(),g=[];for(const v of k){const T=le(v),L=T?Fo(T,o):void 0;T&&L&&g.push({creationTime:L.creationTime,distance:L.distance,doc:T})}return g.sort((v,T)=>v.distance-T.distance||T.creationTime-v.creationTime),g},cn=(n,r,o,a)=>{const s=[];for(const w of n)if(r.every(y=>y(a(w)))&&(s.push(w),typeof o=="number"&&s.length>=o))break;return s},Bo=(n,r,o,a,s,w=()=>{})=>{const y=o.within!==void 0,R=qo(n,r,o,s).map(_=>({distanceMeters:y?null:_.distance,document:_.doc}));return w(R.length),typeof a=="number"?R.slice(0,Math.max(0,Math.floor(a))):R},an=(n,r,o,a,s,w=()=>{})=>{const{geo:y}=o;if(!y)throw new $("INTERNAL","runGeoTerminalScored called without a staged geo query");const R=o.inMemoryFilters.length>0,_=Bo(n,r,y,R?void 0:s,a,w);return R?cn(_,o.inMemoryFilters,s,k=>k.document):_},dn=(n,r,o,a)=>{const s=`SELECT id, _creationTime, ${Re(ne)} FROM ${Re(n)}`,w=`ORDER BY ${o}${a===void 0?"":` LIMIT ${String(a)}`}`;return r===void 0?Oe(`${s} ${w}`):Se(`${s} WHERE `,r,` ${w}`)},Wo=(n,r,o,a,s,w=()=>{})=>an(n,r,o,a,s,w).map(y=>y.document),Po=(n,r,o,a,s,w,y=()=>{})=>{const R=[];for(const v of o.sqlConditions)R.push(i`${X(v.field)} ${i.raw(v.comparator)} ${oe(v.value)}`);a&&R.push(a);let _=i`SELECT id, _creationTime, ${i.identifier(ne)} FROM ${i.identifier(r)}`;R.length>0&&(_=i`${_} WHERE ${i.join(R,i` AND `)}`),_=i`${_} ORDER BY ${s}`,typeof w=="number"&&o.inMemoryFilters.length===0&&(_=i`${_} LIMIT ${i.raw(String(Math.max(0,Math.floor(w))))}`);const k=N(n,_).toArray();y(k.length);const g=[];for(const v of k){const T=le(v);if(T&&o.inMemoryFilters.every(L=>L(T))&&(g.push(T),typeof w=="number"&&g.length>=w))break}return g},me={fieldRef:X,serialize:oe},ln=(n,r)=>{const o=r===void 0?void 0:n.shape[r];return o!==void 0&&oo(o)},Ht=(n,r)=>r.some(o=>ln(n,o)),Nt=(n,r,o)=>{if(ln(n,r))throw new $("BAD_REQUEST",`${o}: "${r}" may hold an order-preserving key rather than a value SQL can reduce or group — declare an aggregateIndex covering this (by, field, op) so the maintained companion answers it instead (its running total is a REAL, so it stays exact only while the total is inside 2^53)`)},ft={fieldRef:n=>Oe(Ge(n)),serialize:oe},Uo=n=>{let r=0;const o=[],a={fieldRef:s=>Oe(Ge(s)),relationExists:s=>{const{childWhere:w,negated:y,parentTable:R,relation:_}=s,k=`__rel_${String(r)}`,g=o.at(-1)??R;r+=1,n(_.table,O);const v=_.kind==="one"?_.field:_.references,T=_.kind==="one"?_.references:_.field,L=Oe(`${xt(k,T)} = ${xt(g,v)}`);o.push(k);const H=te(w,a,He);o.pop();const q=H===void 0?L:Se(L," AND ",H),F=Se("EXISTS (SELECT 1 FROM ",Bt(_.table)," AS ",Bt(k)," WHERE ",q,")");return y?Se("NOT ",F):F},serialize:oe};return a},un=n=>{const r=n.map(o=>`${Ge(o.field)} ${o.direction==="desc"?"DESC":"ASC"}`);return n.some(o=>o.field==="_id"||o.field==="id")||r.push(`${Ge("id")} ${on(n)==="desc"?"DESC":"ASC"}`),r.join(", ")},Go=n=>{const r=n.map(o=>i`${X(o.field)} ${i.raw(o.direction==="desc"?"DESC":"ASC")}`);return n.some(o=>o.field==="_id"||o.field==="id")||r.push(i`${X("id")} ${i.raw(on(n)==="desc"?"DESC":"ASC")}`),i.join(r,i`, `)},Oo={"<":"lt","<=":"lte","=":"eq",">":"gt",">=":"gte"},fn=n=>new Set(n.sqlConditions.filter(r=>r.comparator==="=").map(r=>r.field)),Ho=n=>{const r=fn(n);let o=0;for(;o<n.indexFields.length&&r.has(n.indexFields[o]??"");)o+=1;return n.indexFields.slice(o)},hn=(n,r)=>{const o=n.order,a=Ho(n),{shape:s}=r;return a.length>0?it(a.map(w=>({[w]:o})),s,{pinned:fn(n),uniqueBy:tn(r.indexes,s)}):it([{_creationTime:o}],s)},No=(n,r,o,a)=>{const s=n.sqlConditions.map(w=>({[w.field]:{[Oo[w.comparator]??"eq"]:w.value}}));if(o&&s.push(nn(r,st(o))),a&&s.push(jn(r,st(a))),s.length!==0)return s.length===1?s[0]:{AND:s}},jo=(n,r,o)=>{const a=[];for(const s of n){const w=le(s);if(w&&r.every(y=>y(w))&&(a.push(w),o!==void 0&&a.length>o))break}return a},Ko=(n,r,o,a,s,w,y=()=>{})=>{const R=Math.max(0,Math.floor(s.numItems)),_=hn(a,o),k=typeof s.endCursor=="string",g=te(No(a,_,s.cursor,s.endCursor),ft,He),v=w&&g?Se(g," AND ",w):w??g,T=a.inMemoryFilters.length>0,L=dn(r,v,un(_),T||k?void 0:R+1),H=_e(n,L.text,...L.params).toArray();y(H.length);const q=jo(H,a.inMemoryFilters,T||k?void 0:R);if(k){const j=q.length>=2?q[Math.floor(q.length/2)-1]:void 0;return{continueCursor:s.endCursor??null,isDone:!0,page:q,splitCursor:j?ct(j,_):null}}const F=q.length>R,W=F?q.slice(0,R):q,x=W.at(-1);return{continueCursor:F&&x?ct(x,_):null,isDone:!F,page:W}};class Qo extends ${constructor(r="unique() found more than one matching document"){super("NOT_UNIQUE",r,{name:"NotUniqueError"})}}const Vo=/\s/u,zo=String.fromCodePoint(0),jt=(n,r,o)=>{if(!n.tables[r])throw new $("INTERNAL",`unknown table: ${r}`);return typeof o!="string"||o.length===0||Vo.test(o)||o.includes(zo)?null:o},Jo=(n,r,o,a=()=>{},s=()=>{},w=()=>{})=>{const y=r.tables[o];if(!y)throw new $("INTERNAL",`unknown table: ${o}`);const R=de(y.softDeleteMode,void 0),_=R?te(R,me):void 0,k=R?te(R,ft,He):void 0,g={indexFields:[],indexName:void 0,inMemoryFilters:[],order:"asc",sqlConditions:[]};let v=0;const T=E=>{const{search:C}=g;if(!C)throw new $("INTERNAL","runSearchFetch called without a staged search");Cn(n,o,y);const b=g.inMemoryFilters.length>0,M=yo(b?void 0:E),K=qn(n);if(K&&!xn(n,o,C.definition))throw new $("SEARCH_INDEX_BUILDING",`search index "${C.indexName}" on table "${o}" is still backfilling and currently covers only part of the table — retry once it finishes, or run the backfillSearch admin operation to complete it now`);const re=K?Mo(n,o,C,M,_):Do(n,o,C,M,_);return b?(v=re.length,cn(re,g.inMemoryFilters,E,Te=>Te.document)):(E===void 0&&fo(re),re)},L=E=>T(E).map(C=>C.document),H=E=>{const C=go(E);return $o(L(ho(C)),C)},q=()=>Go(hn(g,y)),F=()=>{if(g.search||g.geo||g.indexName===void 0){s(void 0);return}s(Yn(o,g.indexName,g.indexFields,g.sqlConditions,oe))},W=E=>{F();let C=0;const b=(()=>{if(g.search){const M=L(E);return C=v,M}return g.geo?Wo(n,o,g,_,E,M=>{C=M}):Po(n,o,g,_,q(),E,M=>{C=M})})();return w(Math.max(C,b.length)),b},x=()=>{if(!g.search&&!g.geo)throw new $("INTERNAL",`ctx.db.query("${o}").collectWithScores() requires a staged .withSearchIndex(...) or .withGeoIndex(...)`);F();let E=0;const C=(()=>{if(g.search){const b=T(void 0);return E=v,b}return an(n,o,g,_,void 0,b=>{E=b})})();return w(Math.max(E,C.length)),C},j={async*[Symbol.asyncIterator](){if(g.search){yield*W(void 0);return}const E=[...g.inMemoryFilters];let C;g.inMemoryFilters=[];try{for(;;){const b=await j.paginate({cursor:C??null,numItems:Co});for(const M of b.page)E.every(K=>K(M))&&(yield M);if(b.isDone||b.continueCursor===null)return;C=b.continueCursor}}finally{g.inMemoryFilters=E}},async collect(){return W(void 0)},async collectWithScores(){return x()},filter(E){return g.inMemoryFilters.push(E),j},async first(){return W(g.inMemoryFilters.length>0?void 0:1)[0]??null},order(E){return g.order=E==="desc"?"desc":"asc",j},async paginate(E){let C=0;if(F(),g.search){const M=H(E);return w(M.page.length),M}if(g.geo)throw new $("INTERNAL","pagination is not supported on geo queries; use .take(n) or .collect()");const b=Ko(n,o,y,g,E,k,M=>{C=M});return w(Math.max(C,b.page.length)),b},async take(E){return W(E)},async unique(){const E=W(g.inMemoryFilters.length>0?void 0:2);if(E.length>1)throw new Qo(`unique() on table "${o}" matched ${String(E.length)} documents; expected at most one`);return E[0]??null},withGeoIndex(E,C){const b=(y.geoIndexes??[]).find(K=>K.name===E);if(!b)throw new $("INTERNAL",`unknown geo index "${E}" on table "${o}"`);a(o,E,"geo");const M={definition:b,indexName:E};if(g.geo=M,C(ko(M,o)),!M.near&&!M.within)throw new $("INTERNAL",`geo index "${E}" on table "${o}" requires a .near(point, radius) or .within(box) call`);return j},withIndex(E,C){const b=y.indexes.find(M=>M.name===E);if(!b)throw new $("INTERNAL",`unknown index "${E}" on table "${o}"`);return a(o,E,"index"),g.indexName=E,g.indexFields=b.fields,C&&C(xo(g)),j},withSearchIndex(E,C){const b=(y.searchIndexes??[]).find(K=>K.name===E);if(!b)throw new $("INTERNAL",`unknown search index "${E}" on table "${o}"`);a(o,E,"search");const M={definition:b,field:b.field,filters:[],hasQuery:!1,indexName:E,query:""};if(g.search=M,C(uo(M,o,dt(b.language))),!M.hasQuery)throw new $("INTERNAL",`search index "${E}" on table "${o}" requires a .search(field, query) call`);return j}};return j},Kt=(n,r,o)=>{const a={...r};for(const[s,w]of Yt(n)){if(w.serverDefault){a[s]=w.serverDefault({auth:o});continue}a[s]===void 0&&(w.defaultFn?a[s]=w.defaultFn():"defaultValue"in w&&(a[s]=w.defaultValue))}return a},Qt=(n,r,o,a)=>{const s=o;for(const[w,y]of Yt(n)){if(y.serverDefault){w in r&&(s[w]=y.serverDefault({auth:a}));continue}y.onUpdateFn&&!(w in r)&&(s[w]=y.onUpdateFn())}},Vt=(n,r)=>{for(const o of Object.keys(r))if(r[o]===void 0)throw new $("INTERNAL",`Cannot ${n} field '${o}' to undefined — use null to clear a nullable field, or omit the key to leave it unchanged.`)},zt=["_commitSeq","_creationTime","_id"],rt=n=>zt.some(r=>r in n)?Object.fromEntries(Object.entries(n).filter(([r])=>!zt.includes(r))):n,Yo=/unique constraint failed/i,Xo=n=>n instanceof Error&&Yo.test(n.message),Zo=/string or blob too big/iu,er=(n,r)=>{if(!(!(n instanceof Error)||!Zo.test(n.message)))throw new $("PAYLOAD_TOO_LARGE",`document is too large to store in "${r}": a single row cannot exceed the storage engine's per-row ceiling (2 MB on a Durable Object's SQLite). The limit is on the STORED bytes, which are UTF-8, and v.bytes()/v.bigint() columns are stored twice on a shard-local table. Keep the payload in R2 (ctx.storage) and store a reference on the row.`)},at=(n,r,o,a)=>{try{_e(n,o,...a)}catch(s){throw Xo(s)?new Ee(`unique constraint violation on "${r}"`,"unique"):(er(s,r),s)}},Ue=(n,r,o,a)=>{if(at(n,r,o,a),_e(n,_o).one().changed===0)throw new Ee(`optimistic concurrency conflict on "${r}" — the row changed during this mutation; refetch and retry`,"occ")},Jt=(n,r,o,a,s,w,y)=>{const R=[];for(let v=0;v<o.length+1;v+=1){const T=o[v],L=a[v],H=L?.direction==="desc"?"desc":"asc",q=T===void 0||L===void 0?i`${i.identifier(Vn)} < ${y}`:zn(T,w[v],H,!1);if(q===void 0)continue;const F=[];for(let x=0;x<v;x+=1)F.push(i`${i.identifier(o[x])} IS ${w[x]}`);F.push(q);const[W]=F;R.push(F.length===1&&W!==void 0?W:i`(${i.join(F,i` AND `)})`)}const _=R.length>0?i.join(R,i` OR `):i`1 = 0`,k=N(n,i`SELECT COUNT(*) AS c FROM ${i.identifier(r)} WHERE ${i.identifier("__partition__")} = ${s} AND (${_})`).one(),g=N(n,i`SELECT COUNT(*) AS c FROM ${i.identifier(r)} WHERE ${i.identifier("__partition__")} = ${s}`).one();return{before:k.c,total:g.c}},Br=n=>{const{baselineSeq:r,onStalePatchDropped:o}=n,{sql:a}=n,{schema:s}=n,w=n.broadcast??(()=>{}),y=Xn(s);let R;const _=()=>n.inTransaction?.()===!0,k=e=>s.tables[e]?.commitOrderedMode!==!0?{}:((R===void 0||!_())&&(R=Dn(a)),{[kn]:R}),g=(e,...t)=>{const c=s.tables[e]?.indexes;if(!c||c.length===0)return;const f=[];for(const h of t)h&&f.push(...Jn(c,h,oe));return f.length>0?f:void 0},{headroom:v}=n;let T=!1;const L=async e=>{const t=T;T=!0;try{return await e()}finally{T=t}},H=n.onRead??(()=>{}),q=e=>{It(s.tables[e])&&H(kt,kt)},F=n.onReadRange??(e=>{H(e.table,O)}),W=e=>{q(e.table),F(e)},x=(e,t)=>{t!==void 0&&t!==O&&!T&&v?.recordRead(1),q(e),H(e,t)},j=n.onIndexUse??(()=>{}),E=n.onWrite??(()=>{}),C=e=>{T||v?.recordWrite(e)},b=async e=>{C(e.doc),await E(e)},{cache:M}=n,K=n.clock??(()=>Date.now()),re=n.idGenerator??(()=>crypto.randomUUID()),Te=n.scheduler??Rn,{globalDb:fe}=n,ve=n.auth??{identity:null,userId:null},ht=n.cdc??!1,je=Te,wn=ro({scheduler:typeof je.list=="function"&&typeof je.get=="function"?je:void 0,storage:n.storage}),he=(e,t,c,f)=>{ht&&!It(s.tables[e])&&bn(a,K(),e,t,c,f)},pn=(e,t,c,f)=>{if(s.tables[e]?.dropStalePatchesMode!==!0||!ht)return!1;const h=r?.();if(h===void 0)return!1;const l=Mn(a,e,t,h);return l===void 0?!1:Object.keys(rt(c)).some(d=>At(l[d])!==At(f[d]))},ie=e=>s.tables[e]?.shardMode?.kind==="global",wt=(e,t)=>{if(ie(e)){if(!fe)throw new $("INTERNAL",`cross-backend ${t} for global table '${e}' requires a globalDb writer — pass one to createShardCtxDb({ globalDb })`);return fe}return U},Ke=e=>wt(e,"cascade"),V=(e,t)=>{if(ie(e)){if(!fe)throw new $("INTERNAL",`${t} on global table '${e}' requires a globalDb writer — pass one to createShardCtxDb({ globalDb })`);return fe}},pt=async(e,t,c,f,h)=>{h&&C(c);const l=await e.insert(t,c,f);return w({key:l,op:"insert",row:{...c,_id:l},table:t}),l},Qe=(e,t)=>wt(e,"relation load").findMany(e,t),gt=(e,t)=>(ie(e)&&x(e,O),Qe(e,t)),gn=e=>!ie(e.table),$t=n.relationExistsPushDown??"auto",yt=$t!=="never",{maxRelationKeys:mt}=n,Ae=(e,t,c)=>Lt(e,{fetcher:gt,maxRelationKeys:mt,relationBaseWhere:c,schema:s,tableName:t}),Et=async(e,t,c,f)=>{const h=V(e,"relation grouped count");if(h)return x(e,O),to((P,I)=>h.count(P,I),e,t,c,f);const l=s.tables[e];if(!l)throw new $("INTERNAL",`unknown table: ${e}`);x(e,O);const d=de(l.softDeleteMode,void 0),u={[t]:{in:c}},p=z(z(u,f),d),A=await Ae(p,e,void 0),m=te(A,me),D=X(t);let S=i`SELECT ${D} AS __fk__, COUNT(*) AS count FROM ${i.identifier(e)}`;m&&(S=i`${S} WHERE ${m}`),S=i`${S} GROUP BY ${D}`;const B=N(a,S).toArray();return new Map(B.map(P=>[P.__fk__,P.count]))};let Ie=0;const St=new Set;for(const[e,t]of Object.entries(s.tables))for(const c of Object.values(t.triggerMap??{}))St.add(`${e} ${c.timing} ${c.op}`);const Z=(e,t,c)=>St.has(`${e} ${t} ${c}`),ee=async(e,t,c)=>{if(Ie+=1,Ie>Ot)throw Ie-=1,new Ee(`trigger recursion exceeded ${String(Ot)} levels on "${c.table}" — check for a self-triggering write`,"trigger");try{await io({ctx:yn,event:c,op:t,schema:s,tableName:c.table,timing:e})}finally{Ie-=1}},{ensureBackfilledForTable:we,ensureBackfilledIndex:Ve,ensureRankBackfilled:ze,ensureRankBackfilledForTable:pe,syncAggregates:Ce,syncCompanionsForInsert:_t,syncGeo:xe,syncRanks:ge,syncSearch:be}=Ln({broadcast:w,indexKeysFor:(e,t)=>g(e,t),invalidateCache:(e,t,c)=>M?.invalidate(e,t,g(e,c)),recordCdc:he,schema:s,sql:a}),Rt=(e,t,c)=>{const{shardMode:f}=t;if(f?.kind==="shardBy"&&!(f.field!==void 0&&(c.partitionBy??[]).includes(f.field)))throw Object.assign(new Error(`rank index "${c.name}" on "${e}" partitions across shards (shard key "${f.field??"?"}" is not in partitionBy) — a shard-local rank()/rankPage() would be wrong; roll it up through the Query Coordinator instead`),{code:"CROSS_SHARD_RANK_UNSUPPORTED",name:"LunoraError",status:400})},Tt=e=>Object.entries(s.tables).filter(([,t])=>t.shardMode?.kind!=="global").map(([t])=>t).filter(t=>e===void 0||t===e),$e=e=>e===void 0||ie(e)?fe:void 0,se=(e,t)=>{const c=Tt(t);for(let f=0;f<c.length;f+=ye){const h=c.slice(f,f+ye),[l]=_e(a,To(h),...vo(e,h)).toArray();if(!l)continue;const d=l.__t__,u=le(l);if(typeof d!="string"||!u)return;const p=l[ne];return{docJson:typeof p=="string"?p:ce(p??{}),row:u,tableName:d}}},$n=(e,t)=>{const c=[...new Set(e)],f=new Map;if(c.length===0)return f;const h=Tt(t);for(let l=0;l<h.length;l+=ye){const d=h.slice(l,l+ye),u=Math.floor(ye/d.length),p=Wn(i`${i.identifier("id")}`,c,!1,u),A=d.map(m=>i`SELECT ${i.raw(`'${m.replaceAll("'","''")}'`)} AS __t__, id FROM ${i.identifier(m)} WHERE ${p}`);for(const m of N(a,lt(A))){const{id:D,__t__:S}=m;typeof S=="string"&&typeof D=="string"&&f.set(D,S)}}return f},vt={assertRankPartitionLocal:Rt,ensureRankBackfilled:ze,onRead:x,rowToDocument:le,schema:s,sql:a},U={system:wn,async aggregate(e,t){const c=V(e,"aggregate");if(c)return x(e,O),c.aggregate(e,t);const f=s.tables[e];if(!f)throw new $("INTERNAL",`unknown table: ${e}`);if(qe(t.op),t.op==="count")return U.count(e,{baseWhere:t.baseWhere,relationBaseWhere:t.relationBaseWhere,restrictsCounts:t.restrictsCounts,where:t.where});if(!t.field)throw new $("INTERNAL",`aggregate(${e}, { op: "${t.op}" }): "field" is required for non-count reducers`);x(e,O);const h=de(f.softDeleteMode,void 0),l=z(z(t.baseWhere,t.where),h),d=await Ae(l,e,t.relationBaseWhere),u=d!==l;if(f.aggregateIndexes&&!t.baseWhere&&!u&&(!h||Ht(f,[t.field]))){const P=In(f.aggregateIndexes,t.op,t.field,t.where);if(P){Ve(e,P.index);const I=Ye(P.index.by??[],P.key),Q=Je(e,P.index.name),J=N(a,i`SELECT ${Be} AS value, ${et} AS count FROM ${i.identifier(Q)} WHERE ${We} = ${I}`).toArray()[0];return Xe(t.op,J)}}Nt(f,t.field,`aggregate(${e}, { op: "${t.op}", field: "${t.field}" })`);const p=te(d,me),A=qe(t.op),m=X(t.field);let D=i`SELECT ${i.raw(A)}(${m}) AS value FROM ${i.identifier(e)}`;p&&(D=i`${D} WHERE ${p}`);const B=N(a,D).toArray()[0]?.value;return B??null},asId(e,t){const c=jt(s,e,t);if(c===null)throw new $("BAD_REQUEST",`asId("${e}", …): "${t}" is not a valid id for table "${e}"`,{status:400});return c},async count(e,t){const c=V(e,"count");if(c)return x(e,O),c.count(e,t);const f=s.tables[e];if(!f)throw new $("INTERNAL",`unknown table: ${e}`);const h=Tn(t);if(h.restrictsCounts)throw new Ze(e);x(e,O);const l=de(f.softDeleteMode,void 0),d=z(z(h.baseWhere,h.where),l),u=await Ae(d,e,h.relationBaseWhere),p=u!==d;if(f.aggregateIndexes&&!h.baseWhere&&!p&&!l){const S=An(f.aggregateIndexes,h.where);if(S){Ve(e,S.index);const B=Ye(S.index.by??[],S.key),P=Je(e,S.index.name),I=N(a,i`SELECT ${Be} AS value FROM ${i.identifier(P)} WHERE ${We} = ${B}`).toArray();return I[0]===void 0?0:I[0].value??0}}const A=te(u,me);let m=i`SELECT COUNT(*) AS count FROM ${i.identifier(e)}`;return A&&(m=i`${m} WHERE ${A}`),N(a,m).one().count},async delete(e,t,c){const f=se(e,t);if(!f){const m=$e(t);m&&(C(void 0),await m.delete(e,t,c));return}const{docJson:h,row:l,tableName:d}=f,u=s.tables[d],p=c?.hard===!0,A=!p&&u?.softDeleteMode?u.softDeleteMode.field:void 0;if(!(A&&l[A]!==null&&l[A]!==void 0)){if(Z(d,"before","delete")&&await ee("before","delete",{id:e,op:"delete",previous:l,table:d}),await eo({deletedId:e,deletedReference:m=>l[m],findHolders:async(m,D,S)=>(await Ke(m).findMany(m,{includeDeleted:p,where:{[D]:S}})).page,onCascade:(m,D)=>Ke(m).delete(D,void 0,c),onRestrict:m=>{throw new Ee(m,"restrict")},onSetNull:(m,D,S)=>Ke(m).patch(D,{[S]:null}),schema:s,tableName:d}),we(d),pe(d),A){const m={...l,...k(d),[A]:K(),_id:e};Ue(a,d,Ut(d),[ce(m),e,h]),be(d,e,m,l),xe(d,e,void 0),Ce(d,l,m),ge(d,e,l,void 0),M?.invalidate(d,e,g(d,l,m)),he(d,e,"update",m),w({indexKeys:g(d,l,m),key:e,op:"update",row:m,table:d}),Z(d,"after","delete")&&await ee("after","delete",{id:e,op:"delete",previous:l,table:d}),await b({id:e,op:"delete",table:d});return}Ue(a,d,So(d),[e,h]),be(d,e,void 0),xe(d,e,void 0),Ce(d,l,void 0),ge(d,e,l,void 0),M?.invalidate(d,e,g(d,l)),he(d,e,"delete"),w({indexKeys:g(d,l),key:e,op:"delete",table:d}),Z(d,"after","delete")&&await ee("after","delete",{id:e,op:"delete",previous:l,table:d}),await b({id:e,op:"delete",table:d})}},async deleteAll(e,t){if(!s.tables[e])throw new $("INTERNAL",`unknown table: ${e}`);const c=Math.max(1,t?.chunkSize??rn),f=t?.hard===void 0?void 0:{hard:t.hard},h=ie(e)?void 0:e;let l=0;return await L(async()=>{for(;;){const u=(await U.findMany(e,{limit:c})).page.map(p=>String(p._id));if(u.length===0)break;for(const p of u)await U.delete(p,h,f),l+=1;if(u.length<c)break}}),{deleted:l}},async deleteMany(e,t,c){ae(e.length,t?.limit,"deleteMany");for(const f of e)await U.delete(f,c);return{deleted:e.length}},async deleteWhere(e,t,c){const l=(await(V(e,"deleteWhere")??U).findMany(e,{where:t})).page.map(d=>String(d._id));if(ae(l.length,c?.limit,"deleteWhere"),U.deleteMany===void 0)throw new $("INTERNAL",`ctx.db.${e}.deleteMany is unavailable: this writer has no batch delete`);return U.deleteMany(l,c)},async findFirst(e,t={}){return(await U.findMany(e,{...t,limit:1,omitContinueCursor:!0})).page[0]??null},async findFirstOrThrow(e,t={}){const c=await U.findFirst(e,t);if(c===null)throw new Hn(`findFirstOrThrow: no "${e}" document matched`);return c},async findMany(e,t={}){const c=V(e,"findMany");if(c)return x(e,O),c.findMany(e,t);const f=s.tables[e];if(!f)throw new $("INTERNAL",`unknown table: ${e}`);const h=!t.where&&!t.baseWhere;h?x(e,O):x(e);const l=it(t.orderBy,f.shape,{pinned:Nn(t.where),uniqueBy:tn(f.indexes,f.shape)}),d=t.cursor?nn(l,st(t.cursor)):void 0;let u=z(t.baseWhere,t.where);u=z(u,de(f.softDeleteMode,t.includeDeleted)),u=await Lt(u,{canPushExists:yt?gn:void 0,existsPushMode:$t==="always"?"always":"auto",fetcher:gt,maxRelationKeys:mt,relationBaseWhere:t.relationBaseWhere,schema:s,tableName:e}),d&&(u=u?{AND:[u,d]}:d);const p=yt?Uo(x):ft,A=te(u,p,He),m=typeof t.limit=="number"?Math.max(0,Math.floor(t.limit)):void 0,D=dn(e,A,un(l),m===void 0?void 0:m+1),S=_e(a,D.text,...D.params).toArray();h&&!T&&v?.recordRead(S.length);const B=[];for(const J of S){const G=le(J);G&&(B.push(G),!h&&typeof G._id=="string"&&x(e,G._id))}if(m===void 0)return t.with&&await Ft({groupedCounter:Et,fetcher:Qe,parents:B,...qt(t),schema:s,tableName:e,with:t.with}),{continueCursor:null,isDone:!0,page:bt(B,t.select,t.with)};const P=B.length>m,I=P?B.slice(0,m):B,Q=I.at(-1);return t.with&&await Ft({fetcher:Qe,groupedCounter:Et,parents:I,...qt(t),schema:s,tableName:e,with:t.with}),{continueCursor:P&&Q&&t.omitContinueCursor!==!0?ct(Q,l):null,isDone:!P,page:bt(I,t.select,t.with)}},async get(e,t){const c=se(e,t);if(!c){const f=$e(t);return f?f.get(e,t):null}return x(c.tableName,e),c.row},async lookupById(e,t){const c=se(e,t);return c?(x(c.tableName,e),{row:c.row,tableName:c.tableName}):null},async groupBy(e,t){const c=V(e,"groupBy");if(c)return x(e,O),c.groupBy(e,t);const f=s.tables[e];if(!f)throw new $("INTERNAL",`unknown table: ${e}`);x(e,O);const h=t.agg??{op:"count"};if(qe(h.op),h.op!=="count"&&!h.field)throw new $("INTERNAL",`groupBy(${e}, { agg: { op: "${h.op}" } }): "field" is required for non-count reducers`);const l=de(f.softDeleteMode,void 0),d=z(z(t.baseWhere,t.where),l),u=await Ae(d,e,t.relationBaseWhere),p=u!==d,A=[...t.by,h.field];if(f.aggregateIndexes&&!t.baseWhere&&!p&&(!l||Ht(f,A))){const I=vn(f.aggregateIndexes,h.op,h.field,t.by,t.where),Q=I===void 0?0:Object.keys(I.partial).length,J=I?.index.by?.length??0;if(I&&(Q===0||Q===J)){Ve(e,I.index);const G=Je(e,I.index.name),Me=Object.keys(I.partial),De=[];if(Me.length===(I.index.by??[]).length&&Me.length>0){const ke=Ye(I.index.by??[],I.partial),Le=N(a,i`SELECT ${Be} AS value, ${et} AS count FROM ${i.identifier(G)} WHERE ${We} = ${ke}`).toArray();return Le.length>0&&De.push({key:{...I.partial},value:Xe(h.op,Le[0])}),De}const mn=N(a,i`SELECT ${We} AS key, ${Be} AS value, ${et} AS count FROM ${i.identifier(G)}`).toArray();for(const ke of mn){const Le=_n(JSON.parse(ke.key));De.push({key:Le,value:Xe(h.op,ke)})}return De}}for(const I of A){if(I===void 0)continue;const Q=I===h.field?`groupBy(${e}, { agg: { op: "${h.op}", field: "${I}" } })`:`groupBy(${e}, { by: [..."${I}"] })`;Nt(f,I,Q)}const m=te(u,me),D=t.by.map(I=>i`${X(I)} AS ${i.identifier(I)}`);if(h.op==="count")D.push(i`COUNT(*) AS value`);else{const{field:I}=h;if(I===void 0)throw new $("INTERNAL",`groupBy(${e}, { agg: { op: "${h.op}" } }): "field" is required for non-count reducers`);D.push(i`${i.raw(qe(h.op))}(${X(I)}) AS value`)}let S=i`SELECT ${i.join(D,i`, `)} FROM ${i.identifier(e)}`;m&&(S=i`${S} WHERE ${m}`),S=i`${S} GROUP BY ${i.join(t.by.map(I=>X(I)),i`, `)}`;const B=N(a,S).toArray(),P=[];for(const I of B){const Q={};for(const G of t.by)Q[G]=Fn(f.shape[G],I[G]??null);const{value:J}=I;P.push({key:Q,value:J==null?null:Number(J)})}return P},async insert(e,t,c){const f=V(e,"insert");if(f)return pt(f,e,t,c,!0);const h=s.tables[e];if(!h)throw new $("INTERNAL",`unknown table: ${e}`);const l=Kt(h,t,ve);nt(h,l);let d;c?.clientId!==void 0?(Io(c.clientId),d=c.clientId):c?.allowExplicitId&&typeof l._id=="string"?d=l._id:d=re();const u=c?.allowExplicitId&&typeof l._creationTime=="number"?l._creationTime:K(),p={...l,...k(e),_creationTime:u,_id:d};return Z(e,"before","insert")&&await ee("before","insert",{doc:{...p},id:d,op:"insert",table:e}),we(e),pe(e),at(a,e,mo(e),[d,u,ce(p)]),_t(e,d,p),Z(e,"after","insert")&&await ee("after","insert",{doc:p,id:d,op:"insert",table:e}),await b({doc:p,id:d,op:"insert",table:e}),d},async insertManyUnsafe(e,t,c){if(ae(t.length,c?.limit,"insertManyUnsafe"),t.length===0)return[];const f=V(e,"insert");if(f){const u=[];for(const p of t)C(p);for(const p of t){const A=await f.insert(e,p,{allowExplicitId:c?.allowExplicitId});w({key:A,op:"insert",row:{...p,_id:A},table:e}),u.push(A)}return u}const h=s.tables[e];if(!h)throw new $("INTERNAL",`unknown table: ${e}`);we(e),pe(e);const l=[];for(let u=0;u<t.length;u+=Pe)l.push(k(e));const d=t.map((u,p)=>{const A=Kt(h,u,ve),m=c?.allowExplicitId===!0&&typeof A._id=="string"?A._id:re(),D=c?.allowExplicitId===!0&&typeof A._creationTime=="number"?A._creationTime:K(),S={...A,...l[Math.floor(p/Pe)],_creationTime:D,_id:m};return{creationTime:D,document:S,id:m}});for(const u of d)C(u.document);for(let u=0;u<d.length;u+=Pe){const p=i.join(d.slice(u,u+Pe).map(m=>i`(${m.id}, ${m.creationTime}, ${ce(m.document)})`),i`, `),A=Zt("sqlite",i`INSERT INTO ${i.identifier(e)} (id, _creationTime, ${i.identifier(ne)}) VALUES ${p}`);at(a,e,A.sql,A.params)}for(const{document:u,id:p}of d)_t(e,p,u),await E({doc:u,id:p,op:"insert",table:e});return d.map(u=>u.id)},async insertMany(e,t,c){ae(t.length,c?.limit,"insertMany");const f=c?.skipDuplicates===!0,h=[],l=V(e,"insert");if(l)for(const u of t)C(u);const d=async u=>l?pt(l,e,u,void 0,!1):U.insert(e,u);for(const u of t)try{h.push(await d(u))}catch(p){if(f&&p instanceof Ee&&p.kind==="unique")h.push(null);else throw p}return h},normalizeId(e,t){return jt(s,e,t)},async patch(e,t,c){const f=se(e,c);if(!f){const A=$e(c);if(A){C(t),await A.patch(e,t,c);return}throw new $("NOT_FOUND",`document not found: ${e}`)}const{docJson:h,row:l,tableName:d}=f,u=s.tables[d];if(!u)throw new $("INTERNAL",`unknown table: ${d}`);if(x(d,e),Vt("patch",t),pn(d,e,t,l)){o?.({fields:Object.keys(rt(t)),id:e,table:d});return}const p={...l,...rt(t),...k(d),_id:e};Qt(u,t,p,ve),nt(u,p,!0),Z(d,"before","update")&&await ee("before","update",{doc:{...p},id:e,op:"update",previous:l,table:d}),we(d),pe(d),Ue(a,d,Ut(d),[ce(p),e,h]),be(d,e,p,l),xe(d,e,p),Ce(d,l,p),ge(d,e,l,p),M?.invalidate(d,e,g(d,l,p)),he(d,e,"update",p),w({indexKeys:g(d,l,p),key:e,op:"update",row:p,table:d}),Z(d,"after","update")&&await ee("after","update",{doc:p,id:e,op:"update",previous:l,table:d}),await b({doc:p,id:e,op:"update",table:d})},async patchMany(e,t,c){ae(e.length,t?.limit,"patchMany");for(const f of e)await U.patch(f.id,f.patch,c);return{patched:e.length}},async patchWhere(e,t,c){const l=(await(V(e,"patchWhere")??U).findMany(e,{where:t.where})).page.map(d=>({id:String(d._id),patch:t.patch}));if(ae(l.length,c?.limit,"patchWhere"),U.patchMany===void 0)throw new $("INTERNAL",`ctx.db.${e}.patchMany is unavailable: this writer has no batch patch`);return await U.patchMany(l,c),{patched:l.length}},async related(e,t){return Zn(U,y,e,t)},relationEdges:y,query(e){const t=V(e,"query");return t?(x(e,O),t.query(e)):Jo(a,s,e,j,c=>{c?W(c):x(e,O)},c=>{T||v?.recordRead(c)})},async rank(e,t,c){const f=V(e,"rank");if(f)return x(e,O),f.rank(e,t,c);j(e,t,"rank");const h=s.tables[e];if(!h)throw new $("INTERNAL",`unknown table: ${e}`);const l=h.rankIndexes?.find(G=>G.name===t);if(!l)throw new $("INTERNAL",`unknown rankIndex "${t}" on table "${e}"`);if(Rt(e,h,l),c.restrictsCounts)throw new Ze(e);x(e,O),ze(e,l);const d=typeof c.row=="string"?c.row:c.row._id;if(!d)return null;const u=Mt(e,l.name),p=l.sortBy.map((G,Me)=>Dt(Me)),A=p.map(G=>Re(G)).join(", "),m=N(a,i`SELECT ${i.identifier("__partition__")}, ${i.raw(A)} FROM ${i.identifier(u)} WHERE ${i.identifier("__id__")} = ${d}`).toArray(),[D]=m;if(D===void 0)return null;let S=D.__partition__;const B=z(c.baseWhere,c.where);tt(B,s,e,"rank");const P=Kn(l,B);if(P){const G=Qn(l.partitionBy??[],P);if(G!==S)return null;S=G}const I=p.map(G=>D[G]),{before:Q,total:J}=Jt(a,u,p,l.sortBy,S,I,d);return{position:Q+1,total:J}},async rankBefore(e,t,c){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=s.tables[e];if(!f)throw new $("INTERNAL",`unknown table: ${e}`);const h=f.rankIndexes?.find(p=>p.name===t);if(!h)throw new $("INTERNAL",`unknown rankIndex "${t}" on table "${e}"`);if(c.restrictsCounts)throw new Ze(e);x(e,O),ze(e,h);const l=Mt(e,h.name),d=h.sortBy.map((p,A)=>Dt(A)),u=h.sortBy.map((p,A)=>oe(c.sortValues[A]??null));return Jt(a,l,d,h.sortBy,c.partitionKey,u,c.rowId)},async rankPage(e,t,c={}){tt(z(c.baseWhere,c.where),s,e,"rankPage");const f=V(e,"rankPage");if(f)return x(e,O),f.rankPage(e,t,c);j(e,t,"rank");const{continueCursor:h,hasMore:l,rows:d}=Ct(vt,e,t,c);return{continueCursor:h,isDone:!l,page:d.map(u=>u.doc)}},async rankPageRows(e,t,c={}){tt(z(c.baseWhere,c.where),s,e,"rankPage"),j(e,t,"rank");const{directions:f,hasMore:h,rows:l}=Ct(vt,e,t,c);return{directions:f,hasMore:h,rows:l}},async restore(e,t){const c=se(e,t);if(!c){const l=$e(t);if(l?.restore){await l.restore(e,t);return}throw new $("NOT_FOUND",`document not found: ${e}`)}const f=s.tables[c.tableName]?.softDeleteMode?.field;if(!f)throw new $("INTERNAL",`ctx.db.restore: table "${c.tableName}" is not a .softDelete() table`);const h=c.row[f]!==null&&c.row[f]!==void 0;await U.patch(e,{[f]:null},t),h&&ge(c.tableName,e,void 0,c.row)},async replace(e,t,c,f){const h=se(e,c);if(!h){const B=$e(c);if(B){C(t),await B.replace(e,t,c,f);return}throw new $("NOT_FOUND",`document not found: ${e}`)}const{docJson:l,row:d,tableName:u}=h,p=s.tables[u];if(!p)throw new $("INTERNAL",`unknown table: ${u}`);Vt("replace",t);const A=f?.allowExplicitId&&typeof t._creationTime=="number"?t._creationTime:void 0,m=typeof d._creationTime=="number"?d._creationTime:void 0,D=A??m??K(),S={...t,...k(u),_creationTime:D,_id:e};Qt(p,t,S,ve),nt(p,S),Z(u,"before","update")&&await ee("before","update",{doc:{...S},id:e,op:"update",previous:d,table:u}),we(u),pe(u),Ue(a,u,Eo(u),[D,ce(S),e,l]),be(u,e,S,d),xe(u,e,S),Ce(u,d,S),ge(u,e,d,S),M?.invalidate(u,e,g(u,d,S)),he(u,e,"update",S),w({indexKeys:g(u,d,S),key:e,op:"update",row:S,table:u}),Z(u,"after","update")&&await ee("after","update",{doc:S,id:e,op:"update",previous:d,table:u}),await b({doc:S,id:e,op:"update",table:u})},async wipeShard(e){const t=new Set(e?.exclude),c=e?.tables,f=Object.entries(s.tables).filter(([u,p])=>t.has(u)||c!==void 0&&!c.includes(u)?!1:p.shardMode?.kind!=="global").map(([u])=>u);if(c!==void 0){for(const u of c)if(!s.tables[u])throw new $("INTERNAL",`wipeShard: unknown table: ${u}`)}const h={};let l=0;const{deleteAll:d}=U;if(d===void 0)throw new $("INTERNAL","wipeShard: this writer has no deleteAll");for(const u of f){const p=await d(u,{...e?.chunkSize===void 0?{}:{chunkSize:e.chunkSize},hard:!0});h[u]=p.deleted,l+=p.deleted}return{deleted:l,tables:h}}},yn={db:U,scheduler:Te};return n.enforceRls===!0?no(U,s,(e,t)=>se(e,t)?.tableName,(e,t)=>$n(e,t),y):U};export{Nr as CDC_LOG_TABLE,ai as CLIENT_WATERMARK_TABLE,hi as GLOBAL_SHAPE_SNAPSHOT_TABLE,Ei as IDEMPOTENCY_TABLE,Qo as NotUniqueError,Ii as SEARCH_STATE_TABLE,di as advanceClientWatermark,jr as applyCdcChanges,Vt as assertNoExplicitUndefined,Io as assertValidClientId,Ur as backfillAggregateIndexes,Gr as backfillRankIndexes,Or as backfillSearchIndexes,Kr as bumpCdcEpoch,Qr as cdcCanVouchFor,Vr as cdcForkedError,zr as cdcSeqLeavingRows,Jr as cdcTouchesTables,Yr as cdcTrimmedError,Xr as compactCdcDocs,Br as createShardCtxDb,Zr as cursorBelowRetainedFloor,wi as deleteGlobalShapeSnapshot,pi as deleteGlobalShapeSnapshotsForConnection,li as migrateClientWatermark,gi as migrateGlobalShapeSnapshot,ei as minCdcReplayableSeq,ti as minCdcSeq,jt as normalizeIdStructurally,ni as readCdcChangeKeys,oi as readCdcChanges,ri as readCdcCursor,ii as readCdcEpoch,ui as readClientWatermark,$i as readGlobalShapeSnapshot,Si as readIdempotent,vi as runShardMigrations,xi as selectShapeMembers,bi as selectShapeRows,rt as stripReservedPatchFields,si as trimCdcChanges,_i as trimIdempotent,yi as writeGlobalShapeSnapshot,Ri as writeIdempotent};
|
|
@@ -1 +0,0 @@
|
|
|
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 +0,0 @@
|
|
|
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-CfKnGpV2.mjs";import{k as d,D as E}from"./do-sql-BSoH-O04.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 +0,0 @@
|
|
|
1
|
-
import{N as re,S as se,d as ie,e as ce,a as ae}from"./fts-companion-B7jllLhZ.mjs";import{sql as e}from"drizzle-orm";import{matchesStaticWhere as V,aggregateSqlFunction as fe}from"./AGGREGATE_SQL_FUNCTION-DDEoMnJR.mjs";import{aggregateTableName as P,encodeAggregateKey as v,foldAggregateTally as z,coerceAggregateNumber as D}from"./aggregateTableName-C7o-gpms.mjs";import{runDrizzle as $,runAll as le}from"./runDrizzle-CfKnGpV2.mjs";import{i as $e,g as de,D as b,r as q,a as O,b as _,A as g,c as M,e as W}from"./do-sql-BSoH-O04.mjs";import{param as ue,WORKERD_SQLITE_LIMITS as Ee}from"./param-DlozcSQu.mjs";import{encodeGeohash as ge,GEO_DEFAULT_PRECISION as pe}from"./GEO_DEFAULT_PRECISION-CqpQZ-J_.mjs";import{isLiveForCompanion as Q}from"./CURSOR_PREFIX-Bn8SFoGd.mjs";import{encodePartitionKey as ye,sortColumnName as me,rankTableName as X,matchesRankStaticWhere as Y}from"./RANK_TIEBREAK-D5xNdzB3.mjs";import{m as _e}from"./sql-projection-D3qdaItY.mjs";import{serializeSqlValue as J}from"./serializeSqlValue-BEMMYX1n.mjs";const he=(m,R,p)=>[...m.partitionBy??[],...m.sortBy.map(h=>h.field),...m.where?Object.keys(m.where):[]].every(h=>R[h]===p[h]),Z=m=>e.join(["__id__","__partition__",...m.sortBy.map((R,p)=>me(p))].map(R=>e.identifier(R)),e`, `),N=(m,R,p,F,h,u)=>{const s=ye(p.partitionBy??[],u),C=p.sortBy.map(I=>J(u[I.field]??null)),L=e.join([h,s,...C].map(I=>ue(I)),e`, `);$(m,e`INSERT INTO ${e.identifier(R)} (${F}) VALUES (${L})`)},Te=(m,R,p,F,h,u)=>{if(h&&u&&he(p,h,u))return;const s=X(R,p.name);h&&$(m,e`DELETE FROM ${e.identifier(s)} WHERE ${e.identifier("__id__")} = ${F}`),!(!u||p.where&&!Y(u,p.where))&&N(m,s,p,Z(p),F,u)},be=m=>{const{broadcast:R,indexKeysFor:p,invalidateCache:F,recordCdc:h,schema:u,sql:s}=m,C=new Set,L=n=>u.tables[n]?.softDeleteMode?.field,I=new Set,U=(n,o)=>{const r=`${n}::${o.name}`;if(C.has(r))return;const c=P(n,o.name),a=o.by??[],f=L(n),d=new Map,y=$(s,e`SELECT id, _creationTime, ${e.identifier(b)} FROM ${e.identifier(n)}`).toArray();for(const T of y){const l=q(T);if(!l||!Q(l,f)||o.where&&!V(l,o.where))continue;const S=v(a,l);z(d,S,o,l)}$(s,e`DELETE FROM ${e.identifier(c)}`);const A=Math.floor(Ee.boundParams/3),w=[...d];for(let T=0;T<w.length;T+=A){const l=w.slice(T,T+A),S=e.join(l.map(([t,i])=>e`(${t}, ${i.value}, ${i.count})`),e`, `);$(s,e`INSERT INTO ${e.identifier(c)} (${O}, ${_}, ${g}) VALUES ${S}`)}C.add(r)},x=(n,o,r)=>{const c=o.by??[],a=o.field??"",f=[],d=(t,i)=>{const E=J(i);E===null?f.push(e`${W(t)} IS NULL`):f.push(e`${W(t)} = ${E}`)};for(const t of c)d(t,r[t]??null);const y=L(n);y!==void 0&&d(y,null);for(const[t,i]of Object.entries(o.where??{}))d(t,i!==null&&typeof i=="object"&&!Array.isArray(i)?i.eq:i);const A=f.length>0?e` WHERE ${e.join(f,e` AND `)}`:e``,w=u.tables[n]?.shape[a];if(w&&_e(w)){const t=$(s,e`SELECT id, _creationTime, ${e.identifier(b)} FROM ${e.identifier(n)}${A}`).toArray(),i=new Map;for(const E of t){const k=q(E);k&&z(i,"",o,k)}return{value:i.get("")?.value??null}}const T=fe(o.op),l=W(a);return{value:$(s,e`SELECT ${e.raw(T)}(${l}) AS value FROM ${e.identifier(n)}${A}`).one().value??null}},ee=(n,o,r,c)=>{const a=P(n,o.name),{op:f}=o,d=o.field??"",y=t=>{$(s,e`DELETE FROM ${e.identifier(a)} WHERE ${O} = ${t} AND ${g} <= 0`)},A=L(n),w=t=>!o.where||V(t,o.where),T=t=>Q(t,A)&&w(t);c!==void 0&&f!=="count"&&w(c)&&D(c[d]);const l=r&&T(r)?r:void 0,S=c&&T(c)?c:void 0;if(!(!l&&!S)){if(f==="count"){for(const[t,i]of[[l,-1],[S,1]]){if(!t)continue;const E=v(o.by??[],t);$(s,M(a,E,i,i,e`${_} = ${_} + excluded.${_}, ${g} = ${g} + excluded.${g}`))}l&&y(v(o.by??[],l));return}if(f==="sum"||f==="avg"){for(const[t,i]of[[l,-1],[S,1]]){if(!t)continue;const E=D(t[d]);if(E===void 0)continue;const k=v(o.by??[],t);$(s,M(a,k,i*E,i,e`${_} = COALESCE(${_}, 0) + excluded.${_}, ${g} = ${g} + excluded.${g}`))}l&&y(v(o.by??[],l));return}if(l){const t=v(o.by??[],l),i=D(l[d]),E=$(s,e`SELECT ${_} AS value, ${g} AS count FROM ${e.identifier(a)} WHERE ${O} = ${t}`).toArray()[0],k=(E?.count??0)-1;if(k<=0)$(s,e`DELETE FROM ${e.identifier(a)} WHERE ${O} = ${t}`);else if(E&&i!==void 0&&E.value!==null&&i===E.value){const te=x(n,o,l);$(s,e`UPDATE ${e.identifier(a)} SET ${_} = ${te.value}, ${g} = ${k} WHERE ${O} = ${t}`)}else $(s,e`UPDATE ${e.identifier(a)} SET ${g} = ${g} - 1 WHERE ${O} = ${t}`)}if(S){const t=v(o.by??[],S),i=D(S[d]);if(i===void 0)$(s,M(a,t,null,1,e`${g} = ${g} + 1`));else{const E=f==="min"?"MIN":"MAX";$(s,M(a,t,i,1,e`${_} = ${e.raw(E)}(COALESCE(${_}, excluded.${_}), excluded.${_}), ${g} = ${g} + 1`))}}}},oe=n=>{for(const o of u.tables[n]?.aggregateIndexes??[])U(n,o)},j=(n,o,r)=>{for(const c of u.tables[n]?.aggregateIndexes??[])ee(n,c,o,r)},B=(n,o)=>{const r=`${n}::rank::${o.name}`;if(I.has(r))return;const c=X(n,o.name),a=$(s,e`SELECT id, _creationTime, ${e.identifier(b)} FROM ${e.identifier(n)}`).toArray();$(s,e`DELETE FROM ${e.identifier(c)}`);const f=Z(o);for(const d of a){const y=q(d);!y||o.where&&!Y(y,o.where)||N(s,c,o,f,y._id,y)}I.add(r)},ne=n=>{for(const o of u.tables[n]?.rankIndexes??[])B(n,o)},H=(n,o,r,c)=>{for(const a of u.tables[n]?.rankIndexes??[])Te(s,n,a,o,r,c)},K=(n,o,r,c)=>{const a=u.tables[n]?.searchIndexes??[];if(!(a.length===0||!$e(s)))for(const f of a){if(re(c,r,f))continue;const d=se(n,f.name);le(s,r?ie(d,o,ce(r,f)):ae(d,o))}},G=(n,o,r)=>{for(const c of u.tables[n]?.geoIndexes??[]){const a=de(n,c.name);$(s,e`DELETE FROM ${e.identifier(a)} WHERE ${e.identifier("__id__")} = ${o}`);const f=r?.[c.field];if(f!==null&&typeof f=="object"&&typeof f.lat=="number"&&typeof f.lng=="number"){const{lat:d,lng:y}=f,A=ge({lat:d,lng:y},c.precision??pe);$(s,e`INSERT INTO ${e.identifier(a)} (${e.identifier("__id__")}, ${e.identifier("__geohash__")}, ${e.identifier("__lat__")}, ${e.identifier("__lng__")}) VALUES (${o}, ${A}, ${d}, ${y})`)}}};return{ensureBackfilledForTable:oe,ensureBackfilledIndex:U,ensureRankBackfilled:B,ensureRankBackfilledForTable:ne,syncAggregates:j,syncCompanionsForInsert:(n,o,r)=>{K(n,o,r),G(n,o,r),j(n,void 0,r),H(n,o,void 0,r),F(n,o,r),h(n,o,"insert",r),R({indexKeys:p(n,r),key:o,op:"insert",row:r,table:n})},syncGeo:G,syncRanks:H,syncSearch:K}};export{be as createCompanionSync,N as insertRankRow,Z as rankColumnsSql};
|
|
@@ -1 +0,0 @@
|
|
|
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-CfKnGpV2.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 +0,0 @@
|
|
|
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 +0,0 @@
|
|
|
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};
|
|
@@ -1 +0,0 @@
|
|
|
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};
|