@lunora/shard-engine 1.0.0-alpha.32 → 1.0.0-alpha.34
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 +54 -1
- package/dist/index.d.ts +54 -1
- package/dist/index.mjs +1 -1
- package/dist/packem_shared/ADMIN_FUNCTIONS-2mZJ-FQW.mjs +1 -0
- package/dist/packem_shared/COMMIT_SEQ_FIELD-CSe_oNZu.mjs +4 -0
- package/dist/packem_shared/NotUniqueError-THUZXy3C.mjs +1 -0
- package/dist/packem_shared/REACTOR_STATE_TABLE-Cr9Orfp8.mjs +28 -0
- package/dist/packem_shared/clearMemoryTables-CXULwypv.mjs +1 -0
- package/dist/packem_shared/{defineEngineContractSuite-B0Ofch97.mjs → defineEngineContractSuite-iK4MwBOl.mjs} +1 -1
- package/dist/packem_shared/runShardMigrations-DtIbA812.mjs +5 -0
- package/package.json +2 -2
- package/dist/packem_shared/ADMIN_FUNCTIONS-Ddr79XHG.mjs +0 -1
- package/dist/packem_shared/NotUniqueError-BixDiv4O.mjs +0 -1
- package/dist/packem_shared/runShardMigrations-Crppyq1f.mjs +0 -5
|
@@ -1 +1 @@
|
|
|
1
|
-
import{defineEngineContractSuite as t}from"../packem_shared/defineEngineContractSuite-
|
|
1
|
+
import{defineEngineContractSuite as t}from"../packem_shared/defineEngineContractSuite-iK4MwBOl.mjs";export{t as defineEngineContractSuite};
|
package/dist/index.d.mts
CHANGED
|
@@ -180,9 +180,11 @@ interface SchemaLike {
|
|
|
180
180
|
}
|
|
181
181
|
interface TableDefinitionLike {
|
|
182
182
|
readonly aggregateIndexes?: ReadonlyArray<AggregateIndexDefinitionLike>;
|
|
183
|
+
readonly commitOrderedMode?: boolean;
|
|
183
184
|
readonly geoIndexes?: ReadonlyArray<GeoIndexDefinitionLike>;
|
|
184
185
|
readonly indexes: ReadonlyArray<IndexDefinitionLike>;
|
|
185
186
|
readonly isPublic?: boolean;
|
|
187
|
+
readonly memoryMode?: boolean;
|
|
186
188
|
readonly rankIndexes?: ReadonlyArray<RankIndexDefinitionLike>;
|
|
187
189
|
readonly relationMap?: Record<string, RelationDefinitionLike>;
|
|
188
190
|
readonly searchIndexes?: ReadonlyArray<SearchIndexDefinitionLike>;
|
|
@@ -786,6 +788,7 @@ interface CtxDbOptions {
|
|
|
786
788
|
globalDb?: DatabaseWriterLike;
|
|
787
789
|
headroom?: TransactionHeadroomTracker;
|
|
788
790
|
idGenerator?: IdGenerator;
|
|
791
|
+
inTransaction?: () => boolean;
|
|
789
792
|
maxRelationKeys?: number;
|
|
790
793
|
onIndexUse?: IndexUseHook;
|
|
791
794
|
onRead?: ReadHook;
|
|
@@ -825,6 +828,11 @@ declare const readAuditLog: (sql: SqlExec, options?: {
|
|
|
825
828
|
limit?: number;
|
|
826
829
|
sinceSeq?: number;
|
|
827
830
|
}) => AuditEntry[];
|
|
831
|
+
declare const COMMIT_SEQ_TABLE = "__commit_seq";
|
|
832
|
+
declare const COMMIT_SEQ_FIELD = "_commitSeq";
|
|
833
|
+
declare const migrateCommitSeq: (sql: SqlExec) => void;
|
|
834
|
+
declare const readCommitSeq: (sql: SqlExec) => number;
|
|
835
|
+
declare const allocateCommitSeq: (sql: SqlExec) => number;
|
|
828
836
|
interface SubscriptionQuery {
|
|
829
837
|
args?: Record<string, unknown>;
|
|
830
838
|
functionPath?: string;
|
|
@@ -913,6 +921,9 @@ interface CompanionSync {
|
|
|
913
921
|
syncSearch: (tableName: string, id: string, document: Record<string, unknown> | undefined, previous?: Record<string, unknown>) => void;
|
|
914
922
|
}
|
|
915
923
|
declare const createCompanionSync: (deps: CompanionSyncDeps) => CompanionSync;
|
|
924
|
+
declare const isMemoryTable: (definition: TableDefinitionLike | undefined) => boolean;
|
|
925
|
+
declare const memoryTableNames: (schema: SchemaLike) => string[];
|
|
926
|
+
declare const clearMemoryTables: (sql: SqlExec, schema: SchemaLike) => number;
|
|
916
927
|
interface RankPageDeps {
|
|
917
928
|
assertRankPartitionLocal: (tableName: string, definition: TableDefinitionLike, index: RankIndexDefinitionLike) => void;
|
|
918
929
|
ensureRankBackfilled: (tableName: string, index: RankIndexDefinitionLike) => void;
|
|
@@ -1218,6 +1229,7 @@ declare const ADMIN_FUNCTIONS: {
|
|
|
1218
1229
|
readonly ignoreIssue: "__lunora_admin__:ignoreIssue";
|
|
1219
1230
|
readonly importShard: "__lunora_admin__:importShard";
|
|
1220
1231
|
readonly listFlags: "__lunora_admin__:listFlags";
|
|
1232
|
+
readonly listReactors: "__lunora_admin__:listReactors";
|
|
1221
1233
|
readonly listQueues: "__lunora_admin__:listQueues";
|
|
1222
1234
|
readonly lintSql: "__lunora_admin__:lintSql";
|
|
1223
1235
|
readonly listTables: "__lunora_admin__:listTables";
|
|
@@ -1420,6 +1432,19 @@ interface FlagsResult {
|
|
|
1420
1432
|
configured: boolean;
|
|
1421
1433
|
flags: FlagEvaluation[];
|
|
1422
1434
|
}
|
|
1435
|
+
interface ReactorMetadata {
|
|
1436
|
+
errors: number;
|
|
1437
|
+
lastError?: string;
|
|
1438
|
+
lastRanAt?: number;
|
|
1439
|
+
path: string;
|
|
1440
|
+
runs: number;
|
|
1441
|
+
state: "active" | "failing" | "idle";
|
|
1442
|
+
suppressed: number;
|
|
1443
|
+
tables?: ReadonlyArray<string>;
|
|
1444
|
+
}
|
|
1445
|
+
interface ReactorsResult {
|
|
1446
|
+
reactors: ReactorMetadata[];
|
|
1447
|
+
}
|
|
1423
1448
|
interface WorkflowMetadata {
|
|
1424
1449
|
binding: string;
|
|
1425
1450
|
className: string;
|
|
@@ -1705,6 +1730,34 @@ declare const rankKeyFromDocument: (index: RankIndexDefinitionLike, document_: R
|
|
|
1705
1730
|
sortValues: unknown[];
|
|
1706
1731
|
};
|
|
1707
1732
|
declare const matchesRankStaticWhere: (document: Record<string, unknown>, predicate: Record<string, unknown>) => boolean;
|
|
1733
|
+
declare const REACTOR_STATE_TABLE = "__reactor_state";
|
|
1734
|
+
interface ReactorState {
|
|
1735
|
+
digest: string;
|
|
1736
|
+
lastError?: string;
|
|
1737
|
+
lastRanAt: number;
|
|
1738
|
+
stats: ReactorStats;
|
|
1739
|
+
tables?: ReadonlyArray<string>;
|
|
1740
|
+
}
|
|
1741
|
+
interface ReactorStats {
|
|
1742
|
+
errors: number;
|
|
1743
|
+
runs: number;
|
|
1744
|
+
suppressed: number;
|
|
1745
|
+
}
|
|
1746
|
+
declare const migrateReactorState: (sql: SqlExec) => void;
|
|
1747
|
+
declare const readReactorState: (sql: SqlExec, path: string) => ReactorState | undefined;
|
|
1748
|
+
declare const listReactorStates: (sql: SqlExec) => {
|
|
1749
|
+
path: string;
|
|
1750
|
+
state: ReactorState;
|
|
1751
|
+
}[];
|
|
1752
|
+
type ReactorDispatchResult = "error" | "ran" | "suppressed";
|
|
1753
|
+
declare const writeReactorState: (sql: SqlExec, path: string, outcome: {
|
|
1754
|
+
digest?: string;
|
|
1755
|
+
error?: string;
|
|
1756
|
+
now: number;
|
|
1757
|
+
result: ReactorDispatchResult;
|
|
1758
|
+
tables?: ReadonlyArray<string>;
|
|
1759
|
+
}) => void;
|
|
1760
|
+
declare const reactorNeedsRun: (state: Pick<ReactorState, "tables"> | undefined, changed: ReadonlySet<string>) => boolean;
|
|
1708
1761
|
interface ReadFootprint {
|
|
1709
1762
|
onRead: (table: string, idOrScan?: string) => void;
|
|
1710
1763
|
onReadRange: (range: KeyRange) => void;
|
|
@@ -2147,4 +2200,4 @@ interface WhereSqlStrategy {
|
|
|
2147
2200
|
}
|
|
2148
2201
|
declare const literalInList: (reference: SQL, items: ReadonlyArray<unknown>, negated: boolean) => SQL;
|
|
2149
2202
|
declare const compileWhereSql: (where: WhereInput | undefined, strategy: WhereSqlStrategy) => SQL | undefined;
|
|
2150
|
-
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, type BroadcastDelta, CDC_LOG_TABLE, CDC_META_TABLE, CLIENT_WATERMARK_TABLE, type CacheEntry, type CapturedMailRow, type CdcChange, 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 FanoutMetricsResult, type FanoutPathCounters, type FanoutTopicStat, type FieldOperators, type FilterClause, type FilterOperator, type FlagEvaluation, type FlagsResult, type FunctionCallStat, type FunctionScanAttribution, type FunctionStatsResult, GEO_DEFAULT_PRECISION, GLOBAL_SHAPE_SNAPSHOT_TABLE, type GeoBoundingBox, type GeoFilterBuilderLike, type GeoIndexDefinitionLike, type GeoPoint, type GeoScoredDocument, type 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, 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, 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 ReadFootprint, type ReadHook, type ReadTablePageOptions, type RecordMailInput, type RecordQueueMessageInput, type RelationDefinitionLike, type RelationExistsMarker, type RelayAttach, type RelayDetach, type RelayFrame, type RelayHost, RelayMember, type RelayShapePoke, type RelayShapeSeed, type RelayShapeSubscribe, 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, SCHEMA_HISTORY_MAX_VERSIONS, SEARCH_STATE_TABLE, SHAPE_POKE_CURSOR_TABLE, type SchedulableWorkflowReferenceLike, type ScheduledFunctionDoc, type SchedulerLike, type SchemaLike, type ScoredDocument, type SearchFilterBuilderLike, type SearchIndexDefinitionLike, type SearchScoredDocument, type SelectMatchingIdsOptions, type ServerDefaultContextLike, type SettingEntry, type SettingKind, type SettingsResult, type ShapePokePart, 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, type ValidatorLike, type WhereInput, type WhereSqlStrategy, type WithInput, type WorkflowInstanceState, type WorkflowInstanceStatusResult, type WorkflowMetadata, type WorkflowsResult, type WriteEvent, type WriteHook, advanceClientWatermark, aggUpsertSql, aggregateSqlFunction, aggregateTableName, appendAuditEntry, appendCdcChange, appendStreamChunk, applyCdcChanges, applyOnDelete, applySelect, armRestore, assertFlatPredicate, assertReadonly, assertShapeShardable, assertValidClientId, awaitWsDrain, backfillAggregateIndexes, backfillRankIndexes, backfillSearchIndexes, backfillSearchIndexesForTable, boundingBoxCenter, boundingBoxGeohashes, buildIndexRange, buildPokeFrames, buildReprojectionMigration, buildSeekBeforeWhere, buildSeekWhere, buildSettings, bumpCdcEpoch, claimStreamRun, clampPromotionThresholds, clearCapturedMail, clearQueueMessages, coerceAggregateNumber, compileWhereSql, computeRankPage, containsRelationPredicate, countLegacyRows, coveringGeohashes, createCompanionSync, createDependencyTracker, createFanoutCounters, createIndexSql, createReadFootprint, createRelayLink, createReplicaLink, createShardCtxDb, createSystemReader, decideDurableAttach, decodeCursor, deleteGlobalShapeSnapshot, deleteGlobalShapeSnapshotsForConnection, deleteShapePokeCursor, deleteShapePokeCursorsForConnection, deleteStreamRun, depKey, diffExternalSource, diffGlobalMembership, distinctValues, encodeAggregateKey, encodeCursor, encodeGeohash, encodePartitionKey, encodeRowsPatch, ensureAuditTable, ensureMailTable, exportShardRows, exportShardTable, facetColumn, fanOutScalarCounts, findStorageReferences, finishStreamRun, foldAggregateTally, gateReplicaDispatch, geoTableName, guardWriter, handleReplicaControl, hasTrigger, haversineMeters, hydrateDocsById, importShardRows, indexKeysForRow, isDevEnvironment, isFtsAvailable, isLossyBody, isRelationPredicate, isSoftDeleted, isSourceDue, jsonPath, jsonPathSql, keysTouchRanges, liftSourceId, lintReadonlySql, listTables, literalInList, matchesRankStaticWhere, matchesStaticWhere, materializeExternalRows, materializeExternalRowsIncremental, mergeChangedKeys, mergeWhere, migrateCdcLog, migrateCdcMeta, migrateClientWatermark, migrateDurableStreams, migrateGlobalShapeSnapshot, migrateIdempotency, migrateSearchState, migrateShapePokeCursor, minCdcSeq, nextPromotionState, normalizeCountArgument, normalizeIdStructurally, normalizeOrderKeys, normalizeSourceDocument, normalizeSourceValue, param, parseExportShardArgs, parseImportShardArgs, planAggregateLookup, pointInBoundingBox, projectColumns, pullExternalSourceIncrementalTick, pullExternalSourceTick, qualifiedJsonPath, qualifiedJsonPathSql, quoteIdentifier, rankKeyFromDocument as rankKeyFromDoc, rankTableName, reactiveCacheKey, readAggregateValue, readAuditLog, readBookmark, readCapturedMail, readCdcChanges, readCdcCursor, readCdcEpoch, readClientWatermark, readExternalSourceBaseline, readGlobalShapeSnapshot, readIdempotent, readMigrationStatus, readQueueMessageById, readQueueMessages, readSchemaHistory, readSchemaVersion, readSearchBackfillState, readShapePokeCursor, readStreamChunks, readStreamRun, readTablePage, recordCapturedMail, recordChangedKeys, recordFanoutPass, recordQueueMessages, recordSchemaVersion, relationHooks, relayCountFor, renderSql, reprojectableFields, reprojectionMigrationId, reprojectionTables, resolveRankPartition, resolveRelationPredicates, resolveWith, rowToDocument, runDataMigration, runDrizzle, runExternalSourceTick, runReadonlySql, runRowValidators, runShardMigrations, runSocketPool, runSql, runTriggers, selectExpiredIds, selectExportTables, selectIndexForAggregate, selectIndexForCount, selectIndexForGroupBy, selectMatchingIds, selectShapeMemberIds, selectShapeRows, serializeSqlValue, shapeRoutingKey, softDeleteScope, sortColumnName, sqliteInList, stableStringify, stableWireKey, subscriptionFrames, subscriptionListDeltas, summarizeFanoutTopics, summarizeSubscriptions, tableColumns, tableFromDepKey, throwingScheduler, trimCdcChanges, trimIdempotent, trimStreamRuns, tryRowToDocument, trySendFrame, unionAll, validateImportRow, writeGlobalShapeSnapshot, writeIdempotent, writeSearchBackfillState, writeShapePokeCursor, writeTouchesMemo };
|
|
2203
|
+
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, type BroadcastDelta, CDC_LOG_TABLE, CDC_META_TABLE, CLIENT_WATERMARK_TABLE, COMMIT_SEQ_FIELD, COMMIT_SEQ_TABLE, type CacheEntry, type CapturedMailRow, type CdcChange, 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 FanoutMetricsResult, type FanoutPathCounters, type FanoutTopicStat, type FieldOperators, type FilterClause, type FilterOperator, type FlagEvaluation, type FlagsResult, type FunctionCallStat, type FunctionScanAttribution, type FunctionStatsResult, GEO_DEFAULT_PRECISION, GLOBAL_SHAPE_SNAPSHOT_TABLE, type GeoBoundingBox, type GeoFilterBuilderLike, type GeoIndexDefinitionLike, type GeoPoint, type GeoScoredDocument, type 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, 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, 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 RelationDefinitionLike, type RelationExistsMarker, type RelayAttach, type RelayDetach, type RelayFrame, type RelayHost, RelayMember, type RelayShapePoke, type RelayShapeSeed, type RelayShapeSubscribe, 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, SCHEMA_HISTORY_MAX_VERSIONS, SEARCH_STATE_TABLE, SHAPE_POKE_CURSOR_TABLE, type SchedulableWorkflowReferenceLike, type ScheduledFunctionDoc, type SchedulerLike, type SchemaLike, type ScoredDocument, type SearchFilterBuilderLike, type SearchIndexDefinitionLike, type SearchScoredDocument, type SelectMatchingIdsOptions, type ServerDefaultContextLike, type SettingEntry, type SettingKind, type SettingsResult, type ShapePokePart, 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, type ValidatorLike, type WhereInput, type WhereSqlStrategy, type WithInput, type WorkflowInstanceState, type WorkflowInstanceStatusResult, type WorkflowMetadata, type WorkflowsResult, type WriteEvent, type WriteHook, advanceClientWatermark, aggUpsertSql, aggregateSqlFunction, aggregateTableName, allocateCommitSeq, appendAuditEntry, appendCdcChange, appendStreamChunk, applyCdcChanges, applyOnDelete, applySelect, armRestore, assertFlatPredicate, assertReadonly, assertShapeShardable, assertValidClientId, awaitWsDrain, backfillAggregateIndexes, backfillRankIndexes, backfillSearchIndexes, backfillSearchIndexesForTable, boundingBoxCenter, boundingBoxGeohashes, buildIndexRange, buildPokeFrames, buildReprojectionMigration, buildSeekBeforeWhere, buildSeekWhere, buildSettings, bumpCdcEpoch, claimStreamRun, clampPromotionThresholds, clearCapturedMail, clearMemoryTables, clearQueueMessages, coerceAggregateNumber, compileWhereSql, computeRankPage, containsRelationPredicate, countLegacyRows, coveringGeohashes, createCompanionSync, createDependencyTracker, createFanoutCounters, createIndexSql, createReadFootprint, createRelayLink, createReplicaLink, createShardCtxDb, createSystemReader, decideDurableAttach, decodeCursor, deleteGlobalShapeSnapshot, deleteGlobalShapeSnapshotsForConnection, deleteShapePokeCursor, deleteShapePokeCursorsForConnection, deleteStreamRun, depKey, diffExternalSource, diffGlobalMembership, distinctValues, encodeAggregateKey, encodeCursor, encodeGeohash, encodePartitionKey, encodeRowsPatch, ensureAuditTable, ensureMailTable, exportShardRows, exportShardTable, facetColumn, fanOutScalarCounts, findStorageReferences, finishStreamRun, foldAggregateTally, gateReplicaDispatch, geoTableName, guardWriter, handleReplicaControl, hasTrigger, haversineMeters, hydrateDocsById, importShardRows, indexKeysForRow, isDevEnvironment, isFtsAvailable, isLossyBody, isMemoryTable, isRelationPredicate, isSoftDeleted, isSourceDue, jsonPath, jsonPathSql, keysTouchRanges, liftSourceId, lintReadonlySql, listReactorStates, listTables, literalInList, matchesRankStaticWhere, matchesStaticWhere, materializeExternalRows, materializeExternalRowsIncremental, memoryTableNames, mergeChangedKeys, mergeWhere, migrateCdcLog, migrateCdcMeta, migrateClientWatermark, migrateCommitSeq, migrateDurableStreams, migrateGlobalShapeSnapshot, migrateIdempotency, migrateReactorState, migrateSearchState, migrateShapePokeCursor, minCdcSeq, nextPromotionState, normalizeCountArgument, normalizeIdStructurally, normalizeOrderKeys, normalizeSourceDocument, normalizeSourceValue, param, parseExportShardArgs, parseImportShardArgs, planAggregateLookup, pointInBoundingBox, projectColumns, pullExternalSourceIncrementalTick, pullExternalSourceTick, qualifiedJsonPath, qualifiedJsonPathSql, quoteIdentifier, rankKeyFromDocument as rankKeyFromDoc, rankTableName, reactiveCacheKey, reactorNeedsRun, readAggregateValue, readAuditLog, readBookmark, readCapturedMail, readCdcChanges, readCdcCursor, readCdcEpoch, readClientWatermark, readCommitSeq, readExternalSourceBaseline, readGlobalShapeSnapshot, readIdempotent, readMigrationStatus, readQueueMessageById, readQueueMessages, readReactorState, readSchemaHistory, readSchemaVersion, readSearchBackfillState, readShapePokeCursor, readStreamChunks, readStreamRun, readTablePage, recordCapturedMail, recordChangedKeys, recordFanoutPass, recordQueueMessages, recordSchemaVersion, relationHooks, relayCountFor, renderSql, reprojectableFields, reprojectionMigrationId, reprojectionTables, resolveRankPartition, resolveRelationPredicates, resolveWith, rowToDocument, runDataMigration, runDrizzle, runExternalSourceTick, runReadonlySql, runRowValidators, runShardMigrations, runSocketPool, runSql, runTriggers, selectExpiredIds, selectExportTables, selectIndexForAggregate, selectIndexForCount, selectIndexForGroupBy, selectMatchingIds, selectShapeMemberIds, selectShapeRows, serializeSqlValue, shapeRoutingKey, softDeleteScope, sortColumnName, sqliteInList, stableStringify, stableWireKey, subscriptionFrames, subscriptionListDeltas, summarizeFanoutTopics, summarizeSubscriptions, tableColumns, tableFromDepKey, throwingScheduler, trimCdcChanges, trimIdempotent, trimStreamRuns, tryRowToDocument, trySendFrame, unionAll, validateImportRow, writeGlobalShapeSnapshot, writeIdempotent, writeReactorState, writeSearchBackfillState, writeShapePokeCursor, writeTouchesMemo };
|
package/dist/index.d.ts
CHANGED
|
@@ -180,9 +180,11 @@ interface SchemaLike {
|
|
|
180
180
|
}
|
|
181
181
|
interface TableDefinitionLike {
|
|
182
182
|
readonly aggregateIndexes?: ReadonlyArray<AggregateIndexDefinitionLike>;
|
|
183
|
+
readonly commitOrderedMode?: boolean;
|
|
183
184
|
readonly geoIndexes?: ReadonlyArray<GeoIndexDefinitionLike>;
|
|
184
185
|
readonly indexes: ReadonlyArray<IndexDefinitionLike>;
|
|
185
186
|
readonly isPublic?: boolean;
|
|
187
|
+
readonly memoryMode?: boolean;
|
|
186
188
|
readonly rankIndexes?: ReadonlyArray<RankIndexDefinitionLike>;
|
|
187
189
|
readonly relationMap?: Record<string, RelationDefinitionLike>;
|
|
188
190
|
readonly searchIndexes?: ReadonlyArray<SearchIndexDefinitionLike>;
|
|
@@ -786,6 +788,7 @@ interface CtxDbOptions {
|
|
|
786
788
|
globalDb?: DatabaseWriterLike;
|
|
787
789
|
headroom?: TransactionHeadroomTracker;
|
|
788
790
|
idGenerator?: IdGenerator;
|
|
791
|
+
inTransaction?: () => boolean;
|
|
789
792
|
maxRelationKeys?: number;
|
|
790
793
|
onIndexUse?: IndexUseHook;
|
|
791
794
|
onRead?: ReadHook;
|
|
@@ -825,6 +828,11 @@ declare const readAuditLog: (sql: SqlExec, options?: {
|
|
|
825
828
|
limit?: number;
|
|
826
829
|
sinceSeq?: number;
|
|
827
830
|
}) => AuditEntry[];
|
|
831
|
+
declare const COMMIT_SEQ_TABLE = "__commit_seq";
|
|
832
|
+
declare const COMMIT_SEQ_FIELD = "_commitSeq";
|
|
833
|
+
declare const migrateCommitSeq: (sql: SqlExec) => void;
|
|
834
|
+
declare const readCommitSeq: (sql: SqlExec) => number;
|
|
835
|
+
declare const allocateCommitSeq: (sql: SqlExec) => number;
|
|
828
836
|
interface SubscriptionQuery {
|
|
829
837
|
args?: Record<string, unknown>;
|
|
830
838
|
functionPath?: string;
|
|
@@ -913,6 +921,9 @@ interface CompanionSync {
|
|
|
913
921
|
syncSearch: (tableName: string, id: string, document: Record<string, unknown> | undefined, previous?: Record<string, unknown>) => void;
|
|
914
922
|
}
|
|
915
923
|
declare const createCompanionSync: (deps: CompanionSyncDeps) => CompanionSync;
|
|
924
|
+
declare const isMemoryTable: (definition: TableDefinitionLike | undefined) => boolean;
|
|
925
|
+
declare const memoryTableNames: (schema: SchemaLike) => string[];
|
|
926
|
+
declare const clearMemoryTables: (sql: SqlExec, schema: SchemaLike) => number;
|
|
916
927
|
interface RankPageDeps {
|
|
917
928
|
assertRankPartitionLocal: (tableName: string, definition: TableDefinitionLike, index: RankIndexDefinitionLike) => void;
|
|
918
929
|
ensureRankBackfilled: (tableName: string, index: RankIndexDefinitionLike) => void;
|
|
@@ -1218,6 +1229,7 @@ declare const ADMIN_FUNCTIONS: {
|
|
|
1218
1229
|
readonly ignoreIssue: "__lunora_admin__:ignoreIssue";
|
|
1219
1230
|
readonly importShard: "__lunora_admin__:importShard";
|
|
1220
1231
|
readonly listFlags: "__lunora_admin__:listFlags";
|
|
1232
|
+
readonly listReactors: "__lunora_admin__:listReactors";
|
|
1221
1233
|
readonly listQueues: "__lunora_admin__:listQueues";
|
|
1222
1234
|
readonly lintSql: "__lunora_admin__:lintSql";
|
|
1223
1235
|
readonly listTables: "__lunora_admin__:listTables";
|
|
@@ -1420,6 +1432,19 @@ interface FlagsResult {
|
|
|
1420
1432
|
configured: boolean;
|
|
1421
1433
|
flags: FlagEvaluation[];
|
|
1422
1434
|
}
|
|
1435
|
+
interface ReactorMetadata {
|
|
1436
|
+
errors: number;
|
|
1437
|
+
lastError?: string;
|
|
1438
|
+
lastRanAt?: number;
|
|
1439
|
+
path: string;
|
|
1440
|
+
runs: number;
|
|
1441
|
+
state: "active" | "failing" | "idle";
|
|
1442
|
+
suppressed: number;
|
|
1443
|
+
tables?: ReadonlyArray<string>;
|
|
1444
|
+
}
|
|
1445
|
+
interface ReactorsResult {
|
|
1446
|
+
reactors: ReactorMetadata[];
|
|
1447
|
+
}
|
|
1423
1448
|
interface WorkflowMetadata {
|
|
1424
1449
|
binding: string;
|
|
1425
1450
|
className: string;
|
|
@@ -1705,6 +1730,34 @@ declare const rankKeyFromDocument: (index: RankIndexDefinitionLike, document_: R
|
|
|
1705
1730
|
sortValues: unknown[];
|
|
1706
1731
|
};
|
|
1707
1732
|
declare const matchesRankStaticWhere: (document: Record<string, unknown>, predicate: Record<string, unknown>) => boolean;
|
|
1733
|
+
declare const REACTOR_STATE_TABLE = "__reactor_state";
|
|
1734
|
+
interface ReactorState {
|
|
1735
|
+
digest: string;
|
|
1736
|
+
lastError?: string;
|
|
1737
|
+
lastRanAt: number;
|
|
1738
|
+
stats: ReactorStats;
|
|
1739
|
+
tables?: ReadonlyArray<string>;
|
|
1740
|
+
}
|
|
1741
|
+
interface ReactorStats {
|
|
1742
|
+
errors: number;
|
|
1743
|
+
runs: number;
|
|
1744
|
+
suppressed: number;
|
|
1745
|
+
}
|
|
1746
|
+
declare const migrateReactorState: (sql: SqlExec) => void;
|
|
1747
|
+
declare const readReactorState: (sql: SqlExec, path: string) => ReactorState | undefined;
|
|
1748
|
+
declare const listReactorStates: (sql: SqlExec) => {
|
|
1749
|
+
path: string;
|
|
1750
|
+
state: ReactorState;
|
|
1751
|
+
}[];
|
|
1752
|
+
type ReactorDispatchResult = "error" | "ran" | "suppressed";
|
|
1753
|
+
declare const writeReactorState: (sql: SqlExec, path: string, outcome: {
|
|
1754
|
+
digest?: string;
|
|
1755
|
+
error?: string;
|
|
1756
|
+
now: number;
|
|
1757
|
+
result: ReactorDispatchResult;
|
|
1758
|
+
tables?: ReadonlyArray<string>;
|
|
1759
|
+
}) => void;
|
|
1760
|
+
declare const reactorNeedsRun: (state: Pick<ReactorState, "tables"> | undefined, changed: ReadonlySet<string>) => boolean;
|
|
1708
1761
|
interface ReadFootprint {
|
|
1709
1762
|
onRead: (table: string, idOrScan?: string) => void;
|
|
1710
1763
|
onReadRange: (range: KeyRange) => void;
|
|
@@ -2147,4 +2200,4 @@ interface WhereSqlStrategy {
|
|
|
2147
2200
|
}
|
|
2148
2201
|
declare const literalInList: (reference: SQL, items: ReadonlyArray<unknown>, negated: boolean) => SQL;
|
|
2149
2202
|
declare const compileWhereSql: (where: WhereInput | undefined, strategy: WhereSqlStrategy) => SQL | undefined;
|
|
2150
|
-
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, type BroadcastDelta, CDC_LOG_TABLE, CDC_META_TABLE, CLIENT_WATERMARK_TABLE, type CacheEntry, type CapturedMailRow, type CdcChange, 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 FanoutMetricsResult, type FanoutPathCounters, type FanoutTopicStat, type FieldOperators, type FilterClause, type FilterOperator, type FlagEvaluation, type FlagsResult, type FunctionCallStat, type FunctionScanAttribution, type FunctionStatsResult, GEO_DEFAULT_PRECISION, GLOBAL_SHAPE_SNAPSHOT_TABLE, type GeoBoundingBox, type GeoFilterBuilderLike, type GeoIndexDefinitionLike, type GeoPoint, type GeoScoredDocument, type 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, 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, 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 ReadFootprint, type ReadHook, type ReadTablePageOptions, type RecordMailInput, type RecordQueueMessageInput, type RelationDefinitionLike, type RelationExistsMarker, type RelayAttach, type RelayDetach, type RelayFrame, type RelayHost, RelayMember, type RelayShapePoke, type RelayShapeSeed, type RelayShapeSubscribe, 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, SCHEMA_HISTORY_MAX_VERSIONS, SEARCH_STATE_TABLE, SHAPE_POKE_CURSOR_TABLE, type SchedulableWorkflowReferenceLike, type ScheduledFunctionDoc, type SchedulerLike, type SchemaLike, type ScoredDocument, type SearchFilterBuilderLike, type SearchIndexDefinitionLike, type SearchScoredDocument, type SelectMatchingIdsOptions, type ServerDefaultContextLike, type SettingEntry, type SettingKind, type SettingsResult, type ShapePokePart, 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, type ValidatorLike, type WhereInput, type WhereSqlStrategy, type WithInput, type WorkflowInstanceState, type WorkflowInstanceStatusResult, type WorkflowMetadata, type WorkflowsResult, type WriteEvent, type WriteHook, advanceClientWatermark, aggUpsertSql, aggregateSqlFunction, aggregateTableName, appendAuditEntry, appendCdcChange, appendStreamChunk, applyCdcChanges, applyOnDelete, applySelect, armRestore, assertFlatPredicate, assertReadonly, assertShapeShardable, assertValidClientId, awaitWsDrain, backfillAggregateIndexes, backfillRankIndexes, backfillSearchIndexes, backfillSearchIndexesForTable, boundingBoxCenter, boundingBoxGeohashes, buildIndexRange, buildPokeFrames, buildReprojectionMigration, buildSeekBeforeWhere, buildSeekWhere, buildSettings, bumpCdcEpoch, claimStreamRun, clampPromotionThresholds, clearCapturedMail, clearQueueMessages, coerceAggregateNumber, compileWhereSql, computeRankPage, containsRelationPredicate, countLegacyRows, coveringGeohashes, createCompanionSync, createDependencyTracker, createFanoutCounters, createIndexSql, createReadFootprint, createRelayLink, createReplicaLink, createShardCtxDb, createSystemReader, decideDurableAttach, decodeCursor, deleteGlobalShapeSnapshot, deleteGlobalShapeSnapshotsForConnection, deleteShapePokeCursor, deleteShapePokeCursorsForConnection, deleteStreamRun, depKey, diffExternalSource, diffGlobalMembership, distinctValues, encodeAggregateKey, encodeCursor, encodeGeohash, encodePartitionKey, encodeRowsPatch, ensureAuditTable, ensureMailTable, exportShardRows, exportShardTable, facetColumn, fanOutScalarCounts, findStorageReferences, finishStreamRun, foldAggregateTally, gateReplicaDispatch, geoTableName, guardWriter, handleReplicaControl, hasTrigger, haversineMeters, hydrateDocsById, importShardRows, indexKeysForRow, isDevEnvironment, isFtsAvailable, isLossyBody, isRelationPredicate, isSoftDeleted, isSourceDue, jsonPath, jsonPathSql, keysTouchRanges, liftSourceId, lintReadonlySql, listTables, literalInList, matchesRankStaticWhere, matchesStaticWhere, materializeExternalRows, materializeExternalRowsIncremental, mergeChangedKeys, mergeWhere, migrateCdcLog, migrateCdcMeta, migrateClientWatermark, migrateDurableStreams, migrateGlobalShapeSnapshot, migrateIdempotency, migrateSearchState, migrateShapePokeCursor, minCdcSeq, nextPromotionState, normalizeCountArgument, normalizeIdStructurally, normalizeOrderKeys, normalizeSourceDocument, normalizeSourceValue, param, parseExportShardArgs, parseImportShardArgs, planAggregateLookup, pointInBoundingBox, projectColumns, pullExternalSourceIncrementalTick, pullExternalSourceTick, qualifiedJsonPath, qualifiedJsonPathSql, quoteIdentifier, rankKeyFromDocument as rankKeyFromDoc, rankTableName, reactiveCacheKey, readAggregateValue, readAuditLog, readBookmark, readCapturedMail, readCdcChanges, readCdcCursor, readCdcEpoch, readClientWatermark, readExternalSourceBaseline, readGlobalShapeSnapshot, readIdempotent, readMigrationStatus, readQueueMessageById, readQueueMessages, readSchemaHistory, readSchemaVersion, readSearchBackfillState, readShapePokeCursor, readStreamChunks, readStreamRun, readTablePage, recordCapturedMail, recordChangedKeys, recordFanoutPass, recordQueueMessages, recordSchemaVersion, relationHooks, relayCountFor, renderSql, reprojectableFields, reprojectionMigrationId, reprojectionTables, resolveRankPartition, resolveRelationPredicates, resolveWith, rowToDocument, runDataMigration, runDrizzle, runExternalSourceTick, runReadonlySql, runRowValidators, runShardMigrations, runSocketPool, runSql, runTriggers, selectExpiredIds, selectExportTables, selectIndexForAggregate, selectIndexForCount, selectIndexForGroupBy, selectMatchingIds, selectShapeMemberIds, selectShapeRows, serializeSqlValue, shapeRoutingKey, softDeleteScope, sortColumnName, sqliteInList, stableStringify, stableWireKey, subscriptionFrames, subscriptionListDeltas, summarizeFanoutTopics, summarizeSubscriptions, tableColumns, tableFromDepKey, throwingScheduler, trimCdcChanges, trimIdempotent, trimStreamRuns, tryRowToDocument, trySendFrame, unionAll, validateImportRow, writeGlobalShapeSnapshot, writeIdempotent, writeSearchBackfillState, writeShapePokeCursor, writeTouchesMemo };
|
|
2203
|
+
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, type BroadcastDelta, CDC_LOG_TABLE, CDC_META_TABLE, CLIENT_WATERMARK_TABLE, COMMIT_SEQ_FIELD, COMMIT_SEQ_TABLE, type CacheEntry, type CapturedMailRow, type CdcChange, 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 FanoutMetricsResult, type FanoutPathCounters, type FanoutTopicStat, type FieldOperators, type FilterClause, type FilterOperator, type FlagEvaluation, type FlagsResult, type FunctionCallStat, type FunctionScanAttribution, type FunctionStatsResult, GEO_DEFAULT_PRECISION, GLOBAL_SHAPE_SNAPSHOT_TABLE, type GeoBoundingBox, type GeoFilterBuilderLike, type GeoIndexDefinitionLike, type GeoPoint, type GeoScoredDocument, type 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, 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, 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 RelationDefinitionLike, type RelationExistsMarker, type RelayAttach, type RelayDetach, type RelayFrame, type RelayHost, RelayMember, type RelayShapePoke, type RelayShapeSeed, type RelayShapeSubscribe, 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, SCHEMA_HISTORY_MAX_VERSIONS, SEARCH_STATE_TABLE, SHAPE_POKE_CURSOR_TABLE, type SchedulableWorkflowReferenceLike, type ScheduledFunctionDoc, type SchedulerLike, type SchemaLike, type ScoredDocument, type SearchFilterBuilderLike, type SearchIndexDefinitionLike, type SearchScoredDocument, type SelectMatchingIdsOptions, type ServerDefaultContextLike, type SettingEntry, type SettingKind, type SettingsResult, type ShapePokePart, 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, type ValidatorLike, type WhereInput, type WhereSqlStrategy, type WithInput, type WorkflowInstanceState, type WorkflowInstanceStatusResult, type WorkflowMetadata, type WorkflowsResult, type WriteEvent, type WriteHook, advanceClientWatermark, aggUpsertSql, aggregateSqlFunction, aggregateTableName, allocateCommitSeq, appendAuditEntry, appendCdcChange, appendStreamChunk, applyCdcChanges, applyOnDelete, applySelect, armRestore, assertFlatPredicate, assertReadonly, assertShapeShardable, assertValidClientId, awaitWsDrain, backfillAggregateIndexes, backfillRankIndexes, backfillSearchIndexes, backfillSearchIndexesForTable, boundingBoxCenter, boundingBoxGeohashes, buildIndexRange, buildPokeFrames, buildReprojectionMigration, buildSeekBeforeWhere, buildSeekWhere, buildSettings, bumpCdcEpoch, claimStreamRun, clampPromotionThresholds, clearCapturedMail, clearMemoryTables, clearQueueMessages, coerceAggregateNumber, compileWhereSql, computeRankPage, containsRelationPredicate, countLegacyRows, coveringGeohashes, createCompanionSync, createDependencyTracker, createFanoutCounters, createIndexSql, createReadFootprint, createRelayLink, createReplicaLink, createShardCtxDb, createSystemReader, decideDurableAttach, decodeCursor, deleteGlobalShapeSnapshot, deleteGlobalShapeSnapshotsForConnection, deleteShapePokeCursor, deleteShapePokeCursorsForConnection, deleteStreamRun, depKey, diffExternalSource, diffGlobalMembership, distinctValues, encodeAggregateKey, encodeCursor, encodeGeohash, encodePartitionKey, encodeRowsPatch, ensureAuditTable, ensureMailTable, exportShardRows, exportShardTable, facetColumn, fanOutScalarCounts, findStorageReferences, finishStreamRun, foldAggregateTally, gateReplicaDispatch, geoTableName, guardWriter, handleReplicaControl, hasTrigger, haversineMeters, hydrateDocsById, importShardRows, indexKeysForRow, isDevEnvironment, isFtsAvailable, isLossyBody, isMemoryTable, isRelationPredicate, isSoftDeleted, isSourceDue, jsonPath, jsonPathSql, keysTouchRanges, liftSourceId, lintReadonlySql, listReactorStates, listTables, literalInList, matchesRankStaticWhere, matchesStaticWhere, materializeExternalRows, materializeExternalRowsIncremental, memoryTableNames, mergeChangedKeys, mergeWhere, migrateCdcLog, migrateCdcMeta, migrateClientWatermark, migrateCommitSeq, migrateDurableStreams, migrateGlobalShapeSnapshot, migrateIdempotency, migrateReactorState, migrateSearchState, migrateShapePokeCursor, minCdcSeq, nextPromotionState, normalizeCountArgument, normalizeIdStructurally, normalizeOrderKeys, normalizeSourceDocument, normalizeSourceValue, param, parseExportShardArgs, parseImportShardArgs, planAggregateLookup, pointInBoundingBox, projectColumns, pullExternalSourceIncrementalTick, pullExternalSourceTick, qualifiedJsonPath, qualifiedJsonPathSql, quoteIdentifier, rankKeyFromDocument as rankKeyFromDoc, rankTableName, reactiveCacheKey, reactorNeedsRun, readAggregateValue, readAuditLog, readBookmark, readCapturedMail, readCdcChanges, readCdcCursor, readCdcEpoch, readClientWatermark, readCommitSeq, readExternalSourceBaseline, readGlobalShapeSnapshot, readIdempotent, readMigrationStatus, readQueueMessageById, readQueueMessages, readReactorState, readSchemaHistory, readSchemaVersion, readSearchBackfillState, readShapePokeCursor, readStreamChunks, readStreamRun, readTablePage, recordCapturedMail, recordChangedKeys, recordFanoutPass, recordQueueMessages, recordSchemaVersion, relationHooks, relayCountFor, renderSql, reprojectableFields, reprojectionMigrationId, reprojectionTables, resolveRankPartition, resolveRelationPredicates, resolveWith, rowToDocument, runDataMigration, runDrizzle, runExternalSourceTick, runReadonlySql, runRowValidators, runShardMigrations, runSocketPool, runSql, runTriggers, selectExpiredIds, selectExportTables, selectIndexForAggregate, selectIndexForCount, selectIndexForGroupBy, selectMatchingIds, selectShapeMemberIds, selectShapeRows, serializeSqlValue, shapeRoutingKey, softDeleteScope, sortColumnName, sqliteInList, stableStringify, stableWireKey, subscriptionFrames, subscriptionListDeltas, summarizeFanoutTopics, summarizeSubscriptions, tableColumns, tableFromDepKey, throwingScheduler, trimCdcChanges, trimIdempotent, trimStreamRuns, tryRowToDocument, trySendFrame, unionAll, validateImportRow, writeGlobalShapeSnapshot, writeIdempotent, writeReactorState, writeSearchBackfillState, writeShapePokeCursor, writeTouchesMemo };
|
package/dist/index.mjs
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{exportShardRows as o,exportShardTable as a,importShardRows as t,parseExportShardArgs as n,parseImportShardArgs as s,selectExportTables as i,validateImportRow as l}from"./packem_shared/exportShardRows-Cgt3ITwH.mjs";import{AGGREGATE_SQL_FUNCTION as p,aggregateSqlFunction as d,matchesStaticWhere as c,normalizeCountArgument as S,throwingScheduler as u}from"./packem_shared/AGGREGATE_SQL_FUNCTION-m1iUU1rv.mjs";import{aggregateTableName as f,coerceAggregateNumber as h,encodeAggregateKey as A,foldAggregateTally as E,readAggregateValue as T}from"./packem_shared/aggregateTableName-Cy5e03oz.mjs";import{CountRlsUnsupportedError as R,mergeWhere as C,planAggregateLookup as _,selectIndexForAggregate as I,selectIndexForCount as L,selectIndexForGroupBy as b}from"./packem_shared/CountRlsUnsupportedError-Bdfupt3g.mjs";import{AUDIT_LOG_TABLE as N,appendAuditEntry as y,ensureAuditTable as D,readAuditLog as O}from"./packem_shared/AUDIT_LOG_TABLE-uNVU9O1W.mjs";import{NotUniqueError as P,assertValidClientId as k,createShardCtxDb as B,normalizeIdStructurally as G}from"./packem_shared/NotUniqueError-BixDiv4O.mjs";import{backfillAggregateIndexes as w,backfillRankIndexes as K,backfillSearchIndexes as q,backfillSearchIndexesForTable as W}from"./packem_shared/backfillAggregateIndexes-DVQ2sVuV.mjs";import{CDC_LOG_TABLE as z,CDC_META_TABLE as H,appendCdcChange as X,applyCdcChanges as V,bumpCdcEpoch as j,migrateCdcLog as Y,migrateCdcMeta as Q,minCdcSeq as J,readCdcChanges as Z,readCdcCursor as $,readCdcEpoch as ee,trimCdcChanges as re}from"./packem_shared/CDC_LOG_TABLE-B58N8NQO.mjs";import{CLIENT_WATERMARK_TABLE as ae,advanceClientWatermark as te,migrateClientWatermark as ne,readClientWatermark as se}from"./packem_shared/CLIENT_WATERMARK_TABLE-BoS1HEqz.mjs";import{c as le}from"./packem_shared/ctx-db-companions-lTt-rvKG.mjs";import{GLOBAL_SHAPE_SNAPSHOT_TABLE as pe,deleteGlobalShapeSnapshot as de,deleteGlobalShapeSnapshotsForConnection as ce,migrateGlobalShapeSnapshot as Se,readGlobalShapeSnapshot as ue,writeGlobalShapeSnapshot as xe}from"./packem_shared/GLOBAL_SHAPE_SNAPSHOT_TABLE-NWaL77m5.mjs";import{IDEMPOTENCY_TABLE as he,migrateIdempotency as Ae,readIdempotent as Ee,trimIdempotent as Te,writeIdempotent as ge}from"./packem_shared/IDEMPOTENCY_TABLE-DKVe2Ohf.mjs";import{computeRankPage as Ce,hydrateDocsById as _e}from"./packem_shared/computeRankPage-Bby1Npkd.mjs";import{SEARCH_STATE_TABLE as Le,migrateSearchState as be,readSearchBackfillState as Me,writeSearchBackfillState as Ne}from"./packem_shared/SEARCH_STATE_TABLE-Dju8ebbU.mjs";import{SHAPE_POKE_CURSOR_TABLE as De,deleteShapePokeCursor as Oe,deleteShapePokeCursorsForConnection as Fe,migrateShapePokeCursor as Pe,readShapePokeCursor as ke,writeShapePokeCursor as Be}from"./packem_shared/SHAPE_POKE_CURSOR_TABLE-Dh4HfSdC.mjs";import{selectShapeMemberIds as Ue,selectShapeRows as we}from"./packem_shared/selectShapeMemberIds-B-pQJHAu.mjs";import{DATA_MIGRATION_STATE_TABLE as qe,readMigrationStatus as We,runDataMigration as ve}from"./packem_shared/DATA_MIGRATION_STATE_TABLE-4l6aU1Vc.mjs";import{SCAN_DEP as He,createDependencyTracker as Xe,depKey as Ve,tableFromDepKey as je}from"./packem_shared/SCAN_DEP-D7qE3iUe.mjs";import{runDrizzle as Qe,runSql as Je}from"./packem_shared/runDrizzle-it6rL9bR.mjs";import{A as $e,a as er,b as rr,D as or,c as ar,d as tr,g as nr,i as sr,j as ir,e as lr,q as mr,f as pr,r as dr,t as cr,h as Sr}from"./packem_shared/do-sql-Dk_DJxn4.mjs";import{param as xr,renderSql as fr,sqliteInList as hr,unionAll as Ar}from"./packem_shared/param-Ib8WHnrF.mjs";import{appendStreamChunk as Tr,claimStreamRun as gr,deleteStreamRun as Rr,finishStreamRun as Cr,migrateDurableStreams as _r,readStreamChunks as Ir,readStreamRun as Lr,trimStreamRuns as br}from"./packem_shared/appendStreamChunk-CH4e4nJn.mjs";import{DurableStreamRunner as Nr,MAX_DURABLE_STREAM_BYTES as yr,MAX_DURABLE_STREAM_CHUNKS as Dr,decideDurableAttach as Or}from"./packem_shared/DurableStreamRunner-Bm6KDMBU.mjs";import{diffExternalSource as Pr}from"./packem_shared/diffExternalSource-DbHrcoZK.mjs";import{liftSourceId as Br,normalizeSourceDocument as Gr,normalizeSourceValue as Ur}from"./packem_shared/liftSourceId-CA3ENhXj.mjs";import{materializeExternalRows as Kr,materializeExternalRowsIncremental as qr,readExternalSourceBaseline as Wr,runExternalSourceTick as vr}from"./packem_shared/materializeExternalRows-D5tgL1mR.mjs";import{isSoftDeleted as Hr,isSourceDue as Xr,pullExternalSourceIncrementalTick as Vr,pullExternalSourceTick as jr}from"./packem_shared/isSoftDeleted-DR79pnU-.mjs";import{GEO_DEFAULT_PRECISION as Qr,boundingBoxCenter as Jr,boundingBoxGeohashes as Zr,coveringGeohashes as $r,encodeGeohash as eo,haversineMeters as ro,pointInBoundingBox as oo}from"./packem_shared/GEO_DEFAULT_PRECISION-CqpQZ-J_.mjs";import{ADMIN_FUNCTIONS as to,ADMIN_FUNCTION_PREFIX as no,DEFAULT_FANOUT_TOPIC_LIMIT as so,FLAGS_FUNCTION_PREFIX as io,MAX_PAGE_SIZE as lo,RELATION_FUNCTION_PREFIX as mo,createFanoutCounters as po,facetColumn as co,findStorageReferences as So,listTables as uo,readTablePage as xo,recordFanoutPass as fo,selectMatchingIds as ho,summarizeFanoutTopics as Ao,summarizeSubscriptions as Eo}from"./packem_shared/ADMIN_FUNCTIONS-Ddr79XHG.mjs";import{MAIL_RETENTION as go,MAIL_TABLE as Ro,clearCapturedMail as Co,ensureMailTable as _o,readCapturedMail as Io,recordCapturedMail as Lo}from"./packem_shared/MAIL_RETENTION-Cig9Dmc8.mjs";import{NotFoundError as Mo}from"./packem_shared/NotFoundError-BhF7FeFr.mjs";import{armRestore as yo,readBookmark as Do}from"./packem_shared/armRestore-Bu1_8SUa.mjs";import{applySelect as Fo,buildSeekBeforeWhere as Po,buildSeekWhere as ko,decodeCursor as Bo,encodeCursor as Go,normalizeOrderKeys as Uo,softDeleteScope as wo}from"./packem_shared/applySelect-BQbHyo-W.mjs";import{QUEUE_TABLE as qo,clearQueueMessages as Wo,isLossyBody as vo,readQueueMessageById as zo,readQueueMessages as Ho,recordQueueMessages as Xo}from"./packem_shared/QUEUE_TABLE-zj9Tt6tk.mjs";import{RANK_TIEBREAK as jo,encodePartitionKey as Yo,matchesRankStaticWhere as Qo,rankKeyFromDoc as Jo,rankTableName as Zo,resolveRankPartition as $o,sortColumnName as ea}from"./packem_shared/RANK_TIEBREAK-ci3MaM65.mjs";import{ReactiveCache as oa,reactiveCacheKey as aa}from"./packem_shared/ReactiveCache-DlJ38txF.mjs";import{createReadFootprint as na}from"./packem_shared/createReadFootprint-MRH1If3F.mjs";import{buildIndexRange as ia,indexKeysForRow as la,keysTouchRanges as ma}from"./packem_shared/buildIndexRange-CBKQmHSS.mjs";import{DEFAULT_MAX_RELATION_KEYS as da,assertFlatPredicate as ca,assertShapeShardable as Sa,containsRelationPredicate as ua,isRelationPredicate as xa,resolveRelationPredicates as fa}from"./packem_shared/DEFAULT_MAX_RELATION_KEYS-BAWGIEvC.mjs";import{applyOnDelete as Aa,distinctValues as Ea,fanOutScalarCounts as Ta,relationHooks as ga,resolveWith as Ra,runRowValidators as Ca}from"./packem_shared/applyOnDelete-BlcwKjuO.mjs";import{DEFAULT_PROMOTION_THRESHOLDS as Ia,clampPromotionThresholds as La,nextPromotionState as ba,relayCountFor as Ma,shapeRoutingKey as Na}from"./packem_shared/DEFAULT_PROMOTION_THRESHOLDS-H2sHFvlw.mjs";import{DEFAULT_MAX_RELAYS as Da,OwnerRelay as Oa,RelayMember as Fa,createRelayLink as Pa}from"./packem_shared/DEFAULT_MAX_RELAYS-tuHNDUZr.mjs";import{createReplicaLink as Ba,gateReplicaDispatch as Ga,handleReplicaControl as Ua}from"./packem_shared/createReplicaLink-C1JuP_DN.mjs";import{buildReprojectionMigration as Ka,countLegacyRows as qa,reprojectableFields as Wa,reprojectionTables as va}from"./packem_shared/buildReprojectionMigration-8nVn8Qwb.mjs";import{RLS_UNWRAP_SYMBOL as Ha,RlsRequiredError as Xa,guardWriter as Va}from"./packem_shared/RLS_UNWRAP_SYMBOL-BWloGsd3.mjs";import{SCHEMA_HISTORY_MAX_VERSIONS as Ya,readSchemaHistory as Qa,readSchemaVersion as Ja,recordSchemaVersion as Za}from"./packem_shared/SCHEMA_HISTORY_MAX_VERSIONS-DsycDXWm.mjs";import{serializeSqlValue as et}from"./packem_shared/serializeSqlValue-DbI1VQYM.mjs";import{buildSettings as ot,isDevEnvironment as at}from"./packem_shared/buildSettings-B4igo4rJ.mjs";import{buildPokeFrames as nt,diffGlobalMembership as st,encodeRowsPatch as it,projectColumns as lt}from"./packem_shared/buildPokeFrames-BXejpiII.mjs";import{ShardRunner as pt}from"./packem_shared/ShardRunner-C9p5DVOx.mjs";import{runSocketPool as ct}from"./packem_shared/runSocketPool-CZJ2X9cF.mjs";import{MAX_SQL_ROWS as ut,assertReadonly as xt,lintReadonlySql as ft,runReadonlySql as ht}from"./packem_shared/MAX_SQL_ROWS-gsiUV0Eo.mjs";import{awaitWsDrain as Et,subscriptionFrames as Tt,subscriptionListDeltas as gt,trySendFrame as Rt}from"./packem_shared/awaitWsDrain-Cs-1HHP6.mjs";import{mergeChangedKeys as _t,recordChangedKeys as It,writeTouchesMemo as Lt}from"./packem_shared/mergeChangedKeys-D1T-TPUb.mjs";import{createSystemReader as Mt}from"./packem_shared/createSystemReader-BtYeSMDb.mjs";import{ConflictError as yt}from"./packem_shared/ConflictError-C8GtJmjS.mjs";import{DEFAULT_TRANSACTION_LIMITS as Ot,TransactionHeadroomTracker as Ft}from"./packem_shared/DEFAULT_TRANSACTION_LIMITS-Bcoi7Bvf.mjs";import{hasTrigger as kt,runTriggers as Bt}from"./packem_shared/hasTrigger-CjlwI4le.mjs";import{selectExpiredIds as Ut}from"./packem_shared/selectExpiredIds-_5514W_v.mjs";import{compileWhereSql as Kt,literalInList as qt}from"./packem_shared/compileWhereSql-JBpSfQm9.mjs";import{RELATION_EXISTS_KEY as vt}from"./packem_shared/RELATION_EXISTS_KEY-CFUhnZSZ.mjs";import{REPROJECTION_MIGRATION_PREFIX as Ht,reprojectionMigrationId as Xt}from"./packem_shared/REPROJECTION_MIGRATION_PREFIX-Czcb6_mO.mjs";import{quoteIdentifier as jt}from"./packem_shared/quoteIdentifier-CObIFRhb.mjs";import{runShardMigrations as Qt}from"./packem_shared/runShardMigrations-Crppyq1f.mjs";import{stableStringify as Zt}from"./packem_shared/stableStringify-G9OF5wcs.mjs";import{stableWireKey as en}from"./packem_shared/stableWireKey-DSCJB6E7.mjs";export{to as ADMIN_FUNCTIONS,no as ADMIN_FUNCTION_PREFIX,p as AGGREGATE_SQL_FUNCTION,$e as AGG_COUNT,er as AGG_KEY,rr as AGG_VALUE,N as AUDIT_LOG_TABLE,z as CDC_LOG_TABLE,H as CDC_META_TABLE,ae as CLIENT_WATERMARK_TABLE,yt as ConflictError,R as CountRlsUnsupportedError,qe as DATA_MIGRATION_STATE_TABLE,so as DEFAULT_FANOUT_TOPIC_LIMIT,da as DEFAULT_MAX_RELATION_KEYS,Da as DEFAULT_MAX_RELAYS,Ia as DEFAULT_PROMOTION_THRESHOLDS,Ot as DEFAULT_TRANSACTION_LIMITS,or as DOC_COLUMN,Nr as DurableStreamRunner,io as FLAGS_FUNCTION_PREFIX,Qr as GEO_DEFAULT_PRECISION,pe as GLOBAL_SHAPE_SNAPSHOT_TABLE,he as IDEMPOTENCY_TABLE,go as MAIL_RETENTION,Ro as MAIL_TABLE,yr as MAX_DURABLE_STREAM_BYTES,Dr as MAX_DURABLE_STREAM_CHUNKS,lo as MAX_PAGE_SIZE,ut as MAX_SQL_ROWS,Mo as NotFoundError,P as NotUniqueError,Oa as OwnerRelay,qo as QUEUE_TABLE,jo as RANK_TIEBREAK,vt as RELATION_EXISTS_KEY,mo as RELATION_FUNCTION_PREFIX,Ht as REPROJECTION_MIGRATION_PREFIX,Ha as RLS_UNWRAP_SYMBOL,oa as ReactiveCache,Fa as RelayMember,Xa as RlsRequiredError,He as SCAN_DEP,Ya as SCHEMA_HISTORY_MAX_VERSIONS,Le as SEARCH_STATE_TABLE,De as SHAPE_POKE_CURSOR_TABLE,pt as ShardRunner,Ft as TransactionHeadroomTracker,te as advanceClientWatermark,ar as aggUpsertSql,d as aggregateSqlFunction,f as aggregateTableName,y as appendAuditEntry,X as appendCdcChange,Tr as appendStreamChunk,V as applyCdcChanges,Aa as applyOnDelete,Fo as applySelect,yo as armRestore,ca as assertFlatPredicate,xt as assertReadonly,Sa as assertShapeShardable,k as assertValidClientId,Et as awaitWsDrain,w as backfillAggregateIndexes,K as backfillRankIndexes,q as backfillSearchIndexes,W as backfillSearchIndexesForTable,Jr as boundingBoxCenter,Zr as boundingBoxGeohashes,ia as buildIndexRange,nt as buildPokeFrames,Ka as buildReprojectionMigration,Po as buildSeekBeforeWhere,ko as buildSeekWhere,ot as buildSettings,j as bumpCdcEpoch,gr as claimStreamRun,La as clampPromotionThresholds,Co as clearCapturedMail,Wo as clearQueueMessages,h as coerceAggregateNumber,Kt as compileWhereSql,Ce as computeRankPage,ua as containsRelationPredicate,qa as countLegacyRows,$r as coveringGeohashes,le as createCompanionSync,Xe as createDependencyTracker,po as createFanoutCounters,tr as createIndexSql,na as createReadFootprint,Pa as createRelayLink,Ba as createReplicaLink,B as createShardCtxDb,Mt as createSystemReader,Or as decideDurableAttach,Bo as decodeCursor,de as deleteGlobalShapeSnapshot,ce as deleteGlobalShapeSnapshotsForConnection,Oe as deleteShapePokeCursor,Fe as deleteShapePokeCursorsForConnection,Rr as deleteStreamRun,Ve as depKey,Pr as diffExternalSource,st as diffGlobalMembership,Ea as distinctValues,A as encodeAggregateKey,Go as encodeCursor,eo as encodeGeohash,Yo as encodePartitionKey,it as encodeRowsPatch,D as ensureAuditTable,_o as ensureMailTable,o as exportShardRows,a as exportShardTable,co as facetColumn,Ta as fanOutScalarCounts,So as findStorageReferences,Cr as finishStreamRun,E as foldAggregateTally,Ga as gateReplicaDispatch,nr as geoTableName,Va as guardWriter,Ua as handleReplicaControl,kt as hasTrigger,ro as haversineMeters,_e as hydrateDocsById,t as importShardRows,la as indexKeysForRow,at as isDevEnvironment,sr as isFtsAvailable,vo as isLossyBody,xa as isRelationPredicate,Hr as isSoftDeleted,Xr as isSourceDue,ir as jsonPath,lr as jsonPathSql,ma as keysTouchRanges,Br as liftSourceId,ft as lintReadonlySql,uo as listTables,qt as literalInList,Qo as matchesRankStaticWhere,c as matchesStaticWhere,Kr as materializeExternalRows,qr as materializeExternalRowsIncremental,_t as mergeChangedKeys,C as mergeWhere,Y as migrateCdcLog,Q as migrateCdcMeta,ne as migrateClientWatermark,_r as migrateDurableStreams,Se as migrateGlobalShapeSnapshot,Ae as migrateIdempotency,be as migrateSearchState,Pe as migrateShapePokeCursor,J as minCdcSeq,ba as nextPromotionState,S as normalizeCountArgument,G as normalizeIdStructurally,Uo as normalizeOrderKeys,Gr as normalizeSourceDocument,Ur as normalizeSourceValue,xr as param,n as parseExportShardArgs,s as parseImportShardArgs,_ as planAggregateLookup,oo as pointInBoundingBox,lt as projectColumns,Vr as pullExternalSourceIncrementalTick,jr as pullExternalSourceTick,mr as qualifiedJsonPath,pr as qualifiedJsonPathSql,jt as quoteIdentifier,Jo as rankKeyFromDoc,Zo as rankTableName,aa as reactiveCacheKey,T as readAggregateValue,O as readAuditLog,Do as readBookmark,Io as readCapturedMail,Z as readCdcChanges,$ as readCdcCursor,ee as readCdcEpoch,se as readClientWatermark,Wr as readExternalSourceBaseline,ue as readGlobalShapeSnapshot,Ee as readIdempotent,We as readMigrationStatus,zo as readQueueMessageById,Ho as readQueueMessages,Qa as readSchemaHistory,Ja as readSchemaVersion,Me as readSearchBackfillState,ke as readShapePokeCursor,Ir as readStreamChunks,Lr as readStreamRun,xo as readTablePage,Lo as recordCapturedMail,It as recordChangedKeys,fo as recordFanoutPass,Xo as recordQueueMessages,Za as recordSchemaVersion,ga as relationHooks,Ma as relayCountFor,fr as renderSql,Wa as reprojectableFields,Xt as reprojectionMigrationId,va as reprojectionTables,$o as resolveRankPartition,fa as resolveRelationPredicates,Ra as resolveWith,dr as rowToDocument,ve as runDataMigration,Qe as runDrizzle,vr as runExternalSourceTick,ht as runReadonlySql,Ca as runRowValidators,Qt as runShardMigrations,ct as runSocketPool,Je as runSql,Bt as runTriggers,Ut as selectExpiredIds,i as selectExportTables,I as selectIndexForAggregate,L as selectIndexForCount,b as selectIndexForGroupBy,ho as selectMatchingIds,Ue as selectShapeMemberIds,we as selectShapeRows,et as serializeSqlValue,Na as shapeRoutingKey,wo as softDeleteScope,ea as sortColumnName,hr as sqliteInList,Zt as stableStringify,en as stableWireKey,Tt as subscriptionFrames,gt as subscriptionListDeltas,Ao as summarizeFanoutTopics,Eo as summarizeSubscriptions,cr as tableColumns,je as tableFromDepKey,u as throwingScheduler,re as trimCdcChanges,Te as trimIdempotent,br as trimStreamRuns,Sr as tryRowToDocument,Rt as trySendFrame,Ar as unionAll,l as validateImportRow,xe as writeGlobalShapeSnapshot,ge as writeIdempotent,Ne as writeSearchBackfillState,Be as writeShapePokeCursor,Lt as writeTouchesMemo};
|
|
1
|
+
import{exportShardRows as o,exportShardTable as a,importShardRows as t,parseExportShardArgs as n,parseImportShardArgs as s,selectExportTables as i,validateImportRow as l}from"./packem_shared/exportShardRows-Cgt3ITwH.mjs";import{AGGREGATE_SQL_FUNCTION as p,aggregateSqlFunction as c,matchesStaticWhere as d,normalizeCountArgument as S,throwingScheduler as u}from"./packem_shared/AGGREGATE_SQL_FUNCTION-m1iUU1rv.mjs";import{aggregateTableName as f,coerceAggregateNumber as T,encodeAggregateKey as E,foldAggregateTally as A,readAggregateValue as R}from"./packem_shared/aggregateTableName-Cy5e03oz.mjs";import{CountRlsUnsupportedError as h,mergeWhere as C,planAggregateLookup as _,selectIndexForAggregate as I,selectIndexForCount as L,selectIndexForGroupBy as b}from"./packem_shared/CountRlsUnsupportedError-Bdfupt3g.mjs";import{AUDIT_LOG_TABLE as y,appendAuditEntry as N,ensureAuditTable as O,readAuditLog as D}from"./packem_shared/AUDIT_LOG_TABLE-uNVU9O1W.mjs";import{NotUniqueError as P,assertValidClientId as k,createShardCtxDb as B,normalizeIdStructurally as G}from"./packem_shared/NotUniqueError-THUZXy3C.mjs";import{backfillAggregateIndexes as q,backfillRankIndexes as w,backfillSearchIndexes as K,backfillSearchIndexesForTable as W}from"./packem_shared/backfillAggregateIndexes-DVQ2sVuV.mjs";import{CDC_LOG_TABLE as z,CDC_META_TABLE as H,appendCdcChange as X,applyCdcChanges as V,bumpCdcEpoch as Q,migrateCdcLog as j,migrateCdcMeta as Y,minCdcSeq as J,readCdcChanges as Z,readCdcCursor as $,readCdcEpoch as ee,trimCdcChanges as re}from"./packem_shared/CDC_LOG_TABLE-B58N8NQO.mjs";import{CLIENT_WATERMARK_TABLE as ae,advanceClientWatermark as te,migrateClientWatermark as ne,readClientWatermark as se}from"./packem_shared/CLIENT_WATERMARK_TABLE-BoS1HEqz.mjs";import{COMMIT_SEQ_FIELD as le,COMMIT_SEQ_TABLE as me,allocateCommitSeq as pe,migrateCommitSeq as ce,readCommitSeq as de}from"./packem_shared/COMMIT_SEQ_FIELD-CSe_oNZu.mjs";import{c as ue}from"./packem_shared/ctx-db-companions-lTt-rvKG.mjs";import{GLOBAL_SHAPE_SNAPSHOT_TABLE as fe,deleteGlobalShapeSnapshot as Te,deleteGlobalShapeSnapshotsForConnection as Ee,migrateGlobalShapeSnapshot as Ae,readGlobalShapeSnapshot as Re,writeGlobalShapeSnapshot as ge}from"./packem_shared/GLOBAL_SHAPE_SNAPSHOT_TABLE-NWaL77m5.mjs";import{IDEMPOTENCY_TABLE as Ce,migrateIdempotency as _e,readIdempotent as Ie,trimIdempotent as Le,writeIdempotent as be}from"./packem_shared/IDEMPOTENCY_TABLE-DKVe2Ohf.mjs";import{clearMemoryTables as ye,isMemoryTable as Ne,memoryTableNames as Oe}from"./packem_shared/clearMemoryTables-CXULwypv.mjs";import{computeRankPage as Fe,hydrateDocsById as Pe}from"./packem_shared/computeRankPage-Bby1Npkd.mjs";import{SEARCH_STATE_TABLE as Be,migrateSearchState as Ge,readSearchBackfillState as Ue,writeSearchBackfillState as qe}from"./packem_shared/SEARCH_STATE_TABLE-Dju8ebbU.mjs";import{SHAPE_POKE_CURSOR_TABLE as Ke,deleteShapePokeCursor as We,deleteShapePokeCursorsForConnection as ve,migrateShapePokeCursor as ze,readShapePokeCursor as He,writeShapePokeCursor as Xe}from"./packem_shared/SHAPE_POKE_CURSOR_TABLE-Dh4HfSdC.mjs";import{selectShapeMemberIds as Qe,selectShapeRows as je}from"./packem_shared/selectShapeMemberIds-B-pQJHAu.mjs";import{DATA_MIGRATION_STATE_TABLE as Je,readMigrationStatus as Ze,runDataMigration as $e}from"./packem_shared/DATA_MIGRATION_STATE_TABLE-4l6aU1Vc.mjs";import{SCAN_DEP as rr,createDependencyTracker as or,depKey as ar,tableFromDepKey as tr}from"./packem_shared/SCAN_DEP-D7qE3iUe.mjs";import{runDrizzle as sr,runSql as ir}from"./packem_shared/runDrizzle-it6rL9bR.mjs";import{A as mr,a as pr,b as cr,D as dr,c as Sr,d as ur,g as xr,i as fr,j as Tr,e as Er,q as Ar,f as Rr,r as gr,t as hr,h as Cr}from"./packem_shared/do-sql-Dk_DJxn4.mjs";import{param as Ir,renderSql as Lr,sqliteInList as br,unionAll as Mr}from"./packem_shared/param-Ib8WHnrF.mjs";import{appendStreamChunk as Nr,claimStreamRun as Or,deleteStreamRun as Dr,finishStreamRun as Fr,migrateDurableStreams as Pr,readStreamChunks as kr,readStreamRun as Br,trimStreamRuns as Gr}from"./packem_shared/appendStreamChunk-CH4e4nJn.mjs";import{DurableStreamRunner as qr,MAX_DURABLE_STREAM_BYTES as wr,MAX_DURABLE_STREAM_CHUNKS as Kr,decideDurableAttach as Wr}from"./packem_shared/DurableStreamRunner-Bm6KDMBU.mjs";import{diffExternalSource as zr}from"./packem_shared/diffExternalSource-DbHrcoZK.mjs";import{liftSourceId as Xr,normalizeSourceDocument as Vr,normalizeSourceValue as Qr}from"./packem_shared/liftSourceId-CA3ENhXj.mjs";import{materializeExternalRows as Yr,materializeExternalRowsIncremental as Jr,readExternalSourceBaseline as Zr,runExternalSourceTick as $r}from"./packem_shared/materializeExternalRows-D5tgL1mR.mjs";import{isSoftDeleted as ro,isSourceDue as oo,pullExternalSourceIncrementalTick as ao,pullExternalSourceTick as to}from"./packem_shared/isSoftDeleted-DR79pnU-.mjs";import{GEO_DEFAULT_PRECISION as so,boundingBoxCenter as io,boundingBoxGeohashes as lo,coveringGeohashes as mo,encodeGeohash as po,haversineMeters as co,pointInBoundingBox as So}from"./packem_shared/GEO_DEFAULT_PRECISION-CqpQZ-J_.mjs";import{ADMIN_FUNCTIONS as xo,ADMIN_FUNCTION_PREFIX as fo,DEFAULT_FANOUT_TOPIC_LIMIT as To,FLAGS_FUNCTION_PREFIX as Eo,MAX_PAGE_SIZE as Ao,RELATION_FUNCTION_PREFIX as Ro,createFanoutCounters as go,facetColumn as ho,findStorageReferences as Co,listTables as _o,readTablePage as Io,recordFanoutPass as Lo,selectMatchingIds as bo,summarizeFanoutTopics as Mo,summarizeSubscriptions as yo}from"./packem_shared/ADMIN_FUNCTIONS-2mZJ-FQW.mjs";import{MAIL_RETENTION as Oo,MAIL_TABLE as Do,clearCapturedMail as Fo,ensureMailTable as Po,readCapturedMail as ko,recordCapturedMail as Bo}from"./packem_shared/MAIL_RETENTION-Cig9Dmc8.mjs";import{NotFoundError as Uo}from"./packem_shared/NotFoundError-BhF7FeFr.mjs";import{armRestore as wo,readBookmark as Ko}from"./packem_shared/armRestore-Bu1_8SUa.mjs";import{applySelect as vo,buildSeekBeforeWhere as zo,buildSeekWhere as Ho,decodeCursor as Xo,encodeCursor as Vo,normalizeOrderKeys as Qo,softDeleteScope as jo}from"./packem_shared/applySelect-BQbHyo-W.mjs";import{QUEUE_TABLE as Jo,clearQueueMessages as Zo,isLossyBody as $o,readQueueMessageById as ea,readQueueMessages as ra,recordQueueMessages as oa}from"./packem_shared/QUEUE_TABLE-zj9Tt6tk.mjs";import{RANK_TIEBREAK as ta,encodePartitionKey as na,matchesRankStaticWhere as sa,rankKeyFromDoc as ia,rankTableName as la,resolveRankPartition as ma,sortColumnName as pa}from"./packem_shared/RANK_TIEBREAK-ci3MaM65.mjs";import{ReactiveCache as da,reactiveCacheKey as Sa}from"./packem_shared/ReactiveCache-DlJ38txF.mjs";import{REACTOR_STATE_TABLE as xa,listReactorStates as fa,migrateReactorState as Ta,reactorNeedsRun as Ea,readReactorState as Aa,writeReactorState as Ra}from"./packem_shared/REACTOR_STATE_TABLE-Cr9Orfp8.mjs";import{createReadFootprint as ha}from"./packem_shared/createReadFootprint-MRH1If3F.mjs";import{buildIndexRange as _a,indexKeysForRow as Ia,keysTouchRanges as La}from"./packem_shared/buildIndexRange-CBKQmHSS.mjs";import{DEFAULT_MAX_RELATION_KEYS as Ma,assertFlatPredicate as ya,assertShapeShardable as Na,containsRelationPredicate as Oa,isRelationPredicate as Da,resolveRelationPredicates as Fa}from"./packem_shared/DEFAULT_MAX_RELATION_KEYS-BAWGIEvC.mjs";import{applyOnDelete as ka,distinctValues as Ba,fanOutScalarCounts as Ga,relationHooks as Ua,resolveWith as qa,runRowValidators as wa}from"./packem_shared/applyOnDelete-BlcwKjuO.mjs";import{DEFAULT_PROMOTION_THRESHOLDS as Wa,clampPromotionThresholds as va,nextPromotionState as za,relayCountFor as Ha,shapeRoutingKey as Xa}from"./packem_shared/DEFAULT_PROMOTION_THRESHOLDS-H2sHFvlw.mjs";import{DEFAULT_MAX_RELAYS as Qa,OwnerRelay as ja,RelayMember as Ya,createRelayLink as Ja}from"./packem_shared/DEFAULT_MAX_RELAYS-tuHNDUZr.mjs";import{createReplicaLink as $a,gateReplicaDispatch as et,handleReplicaControl as rt}from"./packem_shared/createReplicaLink-C1JuP_DN.mjs";import{buildReprojectionMigration as at,countLegacyRows as tt,reprojectableFields as nt,reprojectionTables as st}from"./packem_shared/buildReprojectionMigration-8nVn8Qwb.mjs";import{RLS_UNWRAP_SYMBOL as lt,RlsRequiredError as mt,guardWriter as pt}from"./packem_shared/RLS_UNWRAP_SYMBOL-BWloGsd3.mjs";import{SCHEMA_HISTORY_MAX_VERSIONS as dt,readSchemaHistory as St,readSchemaVersion as ut,recordSchemaVersion as xt}from"./packem_shared/SCHEMA_HISTORY_MAX_VERSIONS-DsycDXWm.mjs";import{serializeSqlValue as Tt}from"./packem_shared/serializeSqlValue-DbI1VQYM.mjs";import{buildSettings as At,isDevEnvironment as Rt}from"./packem_shared/buildSettings-B4igo4rJ.mjs";import{buildPokeFrames as ht,diffGlobalMembership as Ct,encodeRowsPatch as _t,projectColumns as It}from"./packem_shared/buildPokeFrames-BXejpiII.mjs";import{ShardRunner as bt}from"./packem_shared/ShardRunner-C9p5DVOx.mjs";import{runSocketPool as yt}from"./packem_shared/runSocketPool-CZJ2X9cF.mjs";import{MAX_SQL_ROWS as Ot,assertReadonly as Dt,lintReadonlySql as Ft,runReadonlySql as Pt}from"./packem_shared/MAX_SQL_ROWS-gsiUV0Eo.mjs";import{awaitWsDrain as Bt,subscriptionFrames as Gt,subscriptionListDeltas as Ut,trySendFrame as qt}from"./packem_shared/awaitWsDrain-Cs-1HHP6.mjs";import{mergeChangedKeys as Kt,recordChangedKeys as Wt,writeTouchesMemo as vt}from"./packem_shared/mergeChangedKeys-D1T-TPUb.mjs";import{createSystemReader as Ht}from"./packem_shared/createSystemReader-BtYeSMDb.mjs";import{ConflictError as Vt}from"./packem_shared/ConflictError-C8GtJmjS.mjs";import{DEFAULT_TRANSACTION_LIMITS as jt,TransactionHeadroomTracker as Yt}from"./packem_shared/DEFAULT_TRANSACTION_LIMITS-Bcoi7Bvf.mjs";import{hasTrigger as Zt,runTriggers as $t}from"./packem_shared/hasTrigger-CjlwI4le.mjs";import{selectExpiredIds as rn}from"./packem_shared/selectExpiredIds-_5514W_v.mjs";import{compileWhereSql as an,literalInList as tn}from"./packem_shared/compileWhereSql-JBpSfQm9.mjs";import{RELATION_EXISTS_KEY as sn}from"./packem_shared/RELATION_EXISTS_KEY-CFUhnZSZ.mjs";import{REPROJECTION_MIGRATION_PREFIX as mn,reprojectionMigrationId as pn}from"./packem_shared/REPROJECTION_MIGRATION_PREFIX-Czcb6_mO.mjs";import{quoteIdentifier as dn}from"./packem_shared/quoteIdentifier-CObIFRhb.mjs";import{runShardMigrations as un}from"./packem_shared/runShardMigrations-DtIbA812.mjs";import{stableStringify as fn}from"./packem_shared/stableStringify-G9OF5wcs.mjs";import{stableWireKey as En}from"./packem_shared/stableWireKey-DSCJB6E7.mjs";export{xo as ADMIN_FUNCTIONS,fo as ADMIN_FUNCTION_PREFIX,p as AGGREGATE_SQL_FUNCTION,mr as AGG_COUNT,pr as AGG_KEY,cr as AGG_VALUE,y as AUDIT_LOG_TABLE,z as CDC_LOG_TABLE,H as CDC_META_TABLE,ae as CLIENT_WATERMARK_TABLE,le as COMMIT_SEQ_FIELD,me as COMMIT_SEQ_TABLE,Vt as ConflictError,h as CountRlsUnsupportedError,Je as DATA_MIGRATION_STATE_TABLE,To as DEFAULT_FANOUT_TOPIC_LIMIT,Ma as DEFAULT_MAX_RELATION_KEYS,Qa as DEFAULT_MAX_RELAYS,Wa as DEFAULT_PROMOTION_THRESHOLDS,jt as DEFAULT_TRANSACTION_LIMITS,dr as DOC_COLUMN,qr as DurableStreamRunner,Eo as FLAGS_FUNCTION_PREFIX,so as GEO_DEFAULT_PRECISION,fe as GLOBAL_SHAPE_SNAPSHOT_TABLE,Ce as IDEMPOTENCY_TABLE,Oo as MAIL_RETENTION,Do as MAIL_TABLE,wr as MAX_DURABLE_STREAM_BYTES,Kr as MAX_DURABLE_STREAM_CHUNKS,Ao as MAX_PAGE_SIZE,Ot as MAX_SQL_ROWS,Uo as NotFoundError,P as NotUniqueError,ja as OwnerRelay,Jo as QUEUE_TABLE,ta as RANK_TIEBREAK,xa as REACTOR_STATE_TABLE,sn as RELATION_EXISTS_KEY,Ro as RELATION_FUNCTION_PREFIX,mn as REPROJECTION_MIGRATION_PREFIX,lt as RLS_UNWRAP_SYMBOL,da as ReactiveCache,Ya as RelayMember,mt as RlsRequiredError,rr as SCAN_DEP,dt as SCHEMA_HISTORY_MAX_VERSIONS,Be as SEARCH_STATE_TABLE,Ke as SHAPE_POKE_CURSOR_TABLE,bt as ShardRunner,Yt as TransactionHeadroomTracker,te as advanceClientWatermark,Sr as aggUpsertSql,c as aggregateSqlFunction,f as aggregateTableName,pe as allocateCommitSeq,N as appendAuditEntry,X as appendCdcChange,Nr as appendStreamChunk,V as applyCdcChanges,ka as applyOnDelete,vo as applySelect,wo as armRestore,ya as assertFlatPredicate,Dt as assertReadonly,Na as assertShapeShardable,k as assertValidClientId,Bt as awaitWsDrain,q as backfillAggregateIndexes,w as backfillRankIndexes,K as backfillSearchIndexes,W as backfillSearchIndexesForTable,io as boundingBoxCenter,lo as boundingBoxGeohashes,_a as buildIndexRange,ht as buildPokeFrames,at as buildReprojectionMigration,zo as buildSeekBeforeWhere,Ho as buildSeekWhere,At as buildSettings,Q as bumpCdcEpoch,Or as claimStreamRun,va as clampPromotionThresholds,Fo as clearCapturedMail,ye as clearMemoryTables,Zo as clearQueueMessages,T as coerceAggregateNumber,an as compileWhereSql,Fe as computeRankPage,Oa as containsRelationPredicate,tt as countLegacyRows,mo as coveringGeohashes,ue as createCompanionSync,or as createDependencyTracker,go as createFanoutCounters,ur as createIndexSql,ha as createReadFootprint,Ja as createRelayLink,$a as createReplicaLink,B as createShardCtxDb,Ht as createSystemReader,Wr as decideDurableAttach,Xo as decodeCursor,Te as deleteGlobalShapeSnapshot,Ee as deleteGlobalShapeSnapshotsForConnection,We as deleteShapePokeCursor,ve as deleteShapePokeCursorsForConnection,Dr as deleteStreamRun,ar as depKey,zr as diffExternalSource,Ct as diffGlobalMembership,Ba as distinctValues,E as encodeAggregateKey,Vo as encodeCursor,po as encodeGeohash,na as encodePartitionKey,_t as encodeRowsPatch,O as ensureAuditTable,Po as ensureMailTable,o as exportShardRows,a as exportShardTable,ho as facetColumn,Ga as fanOutScalarCounts,Co as findStorageReferences,Fr as finishStreamRun,A as foldAggregateTally,et as gateReplicaDispatch,xr as geoTableName,pt as guardWriter,rt as handleReplicaControl,Zt as hasTrigger,co as haversineMeters,Pe as hydrateDocsById,t as importShardRows,Ia as indexKeysForRow,Rt as isDevEnvironment,fr as isFtsAvailable,$o as isLossyBody,Ne as isMemoryTable,Da as isRelationPredicate,ro as isSoftDeleted,oo as isSourceDue,Tr as jsonPath,Er as jsonPathSql,La as keysTouchRanges,Xr as liftSourceId,Ft as lintReadonlySql,fa as listReactorStates,_o as listTables,tn as literalInList,sa as matchesRankStaticWhere,d as matchesStaticWhere,Yr as materializeExternalRows,Jr as materializeExternalRowsIncremental,Oe as memoryTableNames,Kt as mergeChangedKeys,C as mergeWhere,j as migrateCdcLog,Y as migrateCdcMeta,ne as migrateClientWatermark,ce as migrateCommitSeq,Pr as migrateDurableStreams,Ae as migrateGlobalShapeSnapshot,_e as migrateIdempotency,Ta as migrateReactorState,Ge as migrateSearchState,ze as migrateShapePokeCursor,J as minCdcSeq,za as nextPromotionState,S as normalizeCountArgument,G as normalizeIdStructurally,Qo as normalizeOrderKeys,Vr as normalizeSourceDocument,Qr as normalizeSourceValue,Ir as param,n as parseExportShardArgs,s as parseImportShardArgs,_ as planAggregateLookup,So as pointInBoundingBox,It as projectColumns,ao as pullExternalSourceIncrementalTick,to as pullExternalSourceTick,Ar as qualifiedJsonPath,Rr as qualifiedJsonPathSql,dn as quoteIdentifier,ia as rankKeyFromDoc,la as rankTableName,Sa as reactiveCacheKey,Ea as reactorNeedsRun,R as readAggregateValue,D as readAuditLog,Ko as readBookmark,ko as readCapturedMail,Z as readCdcChanges,$ as readCdcCursor,ee as readCdcEpoch,se as readClientWatermark,de as readCommitSeq,Zr as readExternalSourceBaseline,Re as readGlobalShapeSnapshot,Ie as readIdempotent,Ze as readMigrationStatus,ea as readQueueMessageById,ra as readQueueMessages,Aa as readReactorState,St as readSchemaHistory,ut as readSchemaVersion,Ue as readSearchBackfillState,He as readShapePokeCursor,kr as readStreamChunks,Br as readStreamRun,Io as readTablePage,Bo as recordCapturedMail,Wt as recordChangedKeys,Lo as recordFanoutPass,oa as recordQueueMessages,xt as recordSchemaVersion,Ua as relationHooks,Ha as relayCountFor,Lr as renderSql,nt as reprojectableFields,pn as reprojectionMigrationId,st as reprojectionTables,ma as resolveRankPartition,Fa as resolveRelationPredicates,qa as resolveWith,gr as rowToDocument,$e as runDataMigration,sr as runDrizzle,$r as runExternalSourceTick,Pt as runReadonlySql,wa as runRowValidators,un as runShardMigrations,yt as runSocketPool,ir as runSql,$t as runTriggers,rn as selectExpiredIds,i as selectExportTables,I as selectIndexForAggregate,L as selectIndexForCount,b as selectIndexForGroupBy,bo as selectMatchingIds,Qe as selectShapeMemberIds,je as selectShapeRows,Tt as serializeSqlValue,Xa as shapeRoutingKey,jo as softDeleteScope,pa as sortColumnName,br as sqliteInList,fn as stableStringify,En as stableWireKey,Gt as subscriptionFrames,Ut as subscriptionListDeltas,Mo as summarizeFanoutTopics,yo as summarizeSubscriptions,hr as tableColumns,tr as tableFromDepKey,u as throwingScheduler,re as trimCdcChanges,Le as trimIdempotent,Gr as trimStreamRuns,Cr as tryRowToDocument,qt as trySendFrame,Mr as unionAll,l as validateImportRow,ge as writeGlobalShapeSnapshot,be as writeIdempotent,Ra as writeReactorState,qe as writeSearchBackfillState,Xe as writeShapePokeCursor,vt as writeTouchesMemo};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{LunoraError as v}from"@lunora/errors";import{m as L,n as O}from"./do-sql-Dk_DJxn4.mjs";import{quoteIdentifier as d}from"./quoteIdentifier-CObIFRhb.mjs";import{d as P}from"./wire-codec-BU9T2xJ7.mjs";const te="__lunora_admin__:",ne="__lunora_relation__:",re="__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",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",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",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,g=500,U=30,W=200,m="__doc__",k=e=>{try{const t=JSON.parse(e);return t!==null&&typeof t=="object"&&!Array.isArray(t)?t:void 0}catch{return}},j=e=>{const{[O]:t,...n}=e;return t===void 0?n:t===null||typeof t!="object"||Array.isArray(t)?{[O]:t,...n}:{...n,...P(t)}},Q=(e,t)=>{if(!e.includes(m))return{columns:e,rows:t};const n=[];for(const s of t){const a=s[m],i=typeof a=="string"?k(a):void 0;if(i===void 0)return{columns:e,rows:t};const c=Object.fromEntries(Object.entries(s).filter(([u])=>u!==m));n.push({...c,...j(i)})}const r=e.filter(s=>s!==m),o=[],_=new Set(r);for(const s of n)for(const a of Object.keys(s))_.has(a)||(_.add(a),o.push(a));return{columns:[...r,...o],rows:n}},F=e=>`instr(lower(CAST(${e} AS TEXT)), lower(?)) > 0`,I=e=>e.startsWith("sqlite_")||e.startsWith("_cf_")||e.startsWith("__miniflare")||e.startsWith("__lunora")||e.includes("__fts_"),E=(e,t,n)=>Math.min(Math.max(e,t),n),x=(e,t)=>{const n=e.exec(`SELECT COUNT(*) AS c FROM ${t}`).one();return Number(n.c)},oe=e=>{const t=e.exec("SELECT name FROM sqlite_master WHERE type = 'table' ORDER BY name").toArray(),n=[];for(const{name:r}of t)I(r)||n.push({name:r,rowCount:x(e,d(r))});return n},N=(e,t)=>e.exec("SELECT name FROM sqlite_master WHERE type = 'table' AND name = ? LIMIT 1",t).toArray().length>0,C=(e,t)=>{if(I(t)||!N(e,t))throw new v("UNKNOWN_TABLE",`unknown table: ${t}`,{status:404})},M=(e,t)=>e.exec(`PRAGMA table_info(${t})`).toArray().map(n=>n.name),q={eq:"=",gt:">",gte:">=",lt:"<",lte:"<=",ne:"<>"},H=e=>typeof e=="string"?e:typeof e=="number"||typeof e=="boolean"?String(e):"",S=(e,t)=>{const n=t.includes(e),r=t.includes(m);if(!(!n&&!r))return n?{expression:d(e),params:[]}:{expression:`json_extract(${d(m)}, ?)`,params:[`$.${L(e)}`]}},B=(e,t)=>{const n=S(e.column,t);if(n===void 0)return;const{expression:r,params:o}=n;return e.operator==="contains"?{params:[...o,H(e.value)],sql:F(r)}:{params:[...o,e.value],sql:`${r} ${q[e.operator]} ?`}},G=/^(\d{4})(?:-(\d{2}))?(?:-(\d{2}))?$/u,X=e=>{const t=G.exec(e.trim());if(t===null)return;const n=Number(t[1]),r=t[2]===void 0?void 0:Number(t[2]),o=t[3]===void 0?void 0:Number(t[3]);if(r!==void 0&&(r<1||r>12)||o!==void 0&&(o<1||o>31)||n<100)return;const _=Date.UTC(n,(r??1)-1,o??1);if(o!==void 0&&new Date(_).getUTCDate()!==o)return;let s;return o!==void 0?s=Date.UTC(n,(r??1)-1,o+1):r===void 0?s=Date.UTC(n+1,0,1):s=Date.UTC(n,r,1),{from:_,to:s}},A=(e,t,n)=>{const r=[],o=[];if(t!==""&&e.length>0){const _=e.map(a=>F(d(a)));o.push(...e.map(()=>t));const s=X(t);if(s!==void 0)for(const a of e)_.push(`(${d(a)} >= ? AND ${d(a)} < ?)`),o.push(s.from,s.to);r.push(`(${_.join(" OR ")})`)}for(const _ of n??[]){const s=B(_,e);s!==void 0&&(r.push(`(${s.sql})`),o.push(...s.params))}return r.length===0?void 0:{parameters:o,where:r.join(" AND ")}},K=(e,t)=>{if(e===void 0)return;const n=S(e.column,t);if(n===void 0)return;const r=e.direction==="desc"?"DESC":"ASC";return{params:n.params,sql:`${n.expression} ${r}`}},ae=(e,t)=>{const{table:n}=t;C(e,n);const r=E(Math.trunc(t.limit??D),1,g),o=Math.max(0,Math.trunc(t.offset??0)),_=d(n),s=M(e,_),a=t.search?.trim()??"",i=b=>{if(t.refs===void 0)return b;const T={};for(const w of b.columns){const y=t.refs[w];y!==void 0&&(T[w]=y)}return Object.keys(T).length>0?{...b,refs:T}:b},c=A(s,a,t.filters),u=K(t.orderBy,s),l=c===void 0?"":` WHERE ${c.where}`,f=u===void 0?"":` ORDER BY ${u.sql}`,p=c?.parameters??[],h=u?.params??[];let R;t.skipCount||(R=c===void 0?x(e,_):Number(e.exec(`SELECT COUNT(*) AS c FROM ${_}${l}`,...p).one().c));const $=e.exec(`SELECT * FROM ${_}${l}${f} LIMIT ? OFFSET ?`,...p,...h,r,o).toArray();return i({...Q(s,$),total:R})},_e=(e,t)=>{const{table:n}=t;C(e,n);const r=E(Math.trunc(t.limit??g),1,g),o=d(n),_=M(e,o),s=t.search?.trim()??"",a=A(_,s,t.filters),i=a===void 0?e.exec(`SELECT id FROM ${o} LIMIT ?`,r+1).toArray():e.exec(`SELECT id FROM ${o} WHERE ${a.where} LIMIT ?`,...a.parameters,r+1).toArray(),c=i.length>r,u=i.slice(0,r).map(l=>l.id);return{hasMore:c,ids:u}},Y=(e,t,n)=>{const r=new Set(n.filter(_=>_!==m));if(!n.includes(m))return r;const o=e.exec(`SELECT ${d(m)} AS doc FROM ${t} LIMIT ?`,g).toArray();for(const{doc:_}of o){const s=typeof _=="string"?k(_):void 0;if(s!==void 0)for(const a of Object.keys(s))r.add(a)}return r},ie=(e,t)=>{const{column:n,table:r}=t;C(e,r);const o=d(r),_=M(e,o);if(!Y(e,o,_).has(n))throw new v("UNKNOWN_COLUMN",`unknown column: ${n}`,{status:404});const s=S(n,_);if(s===void 0)throw new v("UNKNOWN_COLUMN",`unknown column: ${n}`,{status:404});const a=E(Math.trunc(t.limit??U),1,W),i=t.search?.trim()??"",c=A(_,i,t.filters),u=c===void 0?"":` WHERE ${c.where}`,l=c?.parameters??[],f=e.exec(`SELECT ${s.expression} AS value, COUNT(*) AS count FROM ${o}${u} GROUP BY ${s.expression} ORDER BY count DESC LIMIT ?`,...s.params,...l,...s.params,a+1).toArray();return{truncated:f.length>a,values:f.slice(0,a).map(h=>({count:Number(h.count),value:h.value}))}},ce=(e,t,n)=>{const r={},o=n.slice(0,g);for(const s of o)r[s]=[];if(o.length===0)return{references:r,storageColumns:t};const _=o.map(()=>"?").join(", ");for(const[s,a]of Object.entries(t)){if(I(s)||!N(e,s))continue;const i=d(s),c=M(e,i);for(const u of a){const l=S(u,c);if(l===void 0)continue;const f=e.exec(`SELECT id, ${l.expression} AS ref FROM ${i} WHERE ${l.expression} IN (${_})`,...l.params,...l.params,...o).toArray();for(const p of f)r[p.ref]?.push({column:u,id:p.id,table:s})}}return{references:r,storageColumns:t}},ue=e=>{const t=e.map((r,o)=>{const _=Object.values(r.subs??{}).map(s=>({args:s.args,functionPath:s.functionPath,table:s.table}));return{admin:r.admin===!0,id:o,subscriptions:_}}),n=t.reduce((r,o)=>r+o.subscriptions.length,0);return{connections:t,totalConnections:t.length,totalSubscriptions:n}},V=20,le=()=>({maxMs:0,passes:0,peakSocketsIterated:0,socketsDelivered:0,socketsIterated:0,totalMs:0}),de=(e,t,n,r)=>({maxMs:Math.max(e.maxMs,r),passes:e.passes+1,peakSocketsIterated:Math.max(e.peakSocketsIterated,t),socketsDelivered:e.socketsDelivered+n,socketsIterated:e.socketsIterated+t,totalMs:e.totalMs+r}),me=(e,t=V)=>{const n=new Map,r=new Map;for(const s of e){for(const a of Object.values(s.shapes??{})){const i=a.name??"(unknown shape)";n.set(i,(n.get(i)??0)+1)}for(const a of s.whispers??[])r.set(a,(r.get(a)??0)+1)}const o=[...[...n].map(([s,a])=>({kind:"shape",subscribers:a,topic:s})),...[...r].map(([s,a])=>({kind:"whisper",subscribers:a,topic:s}))];return o.sort((s,a)=>a.subscribers-s.subscribers||s.topic.localeCompare(a.topic)),{peakSubscribers:o[0]?.subscribers??0,topics:o.slice(0,t),totalConnections:e.length}};export{se as ADMIN_FUNCTIONS,te as ADMIN_FUNCTION_PREFIX,V as DEFAULT_FANOUT_TOPIC_LIMIT,re as FLAGS_FUNCTION_PREFIX,g as MAX_PAGE_SIZE,ne as RELATION_FUNCTION_PREFIX,le as createFanoutCounters,X as datePrefixRange,ie as facetColumn,ce as findStorageReferences,oe as listTables,ae as readTablePage,de as recordFanoutPass,_e as selectMatchingIds,me as summarizeFanoutTopics,ue as summarizeSubscriptions};
|
|
@@ -0,0 +1,4 @@
|
|
|
1
|
+
import{sql as e}from"drizzle-orm";import{runDrizzle as E}from"./runDrizzle-it6rL9bR.mjs";const t="__commit_seq",n="_commitSeq",S=i=>{E(i,e`CREATE TABLE IF NOT EXISTS ${e.identifier(t)} (
|
|
2
|
+
id INTEGER PRIMARY KEY CHECK (id = 0),
|
|
3
|
+
value INTEGER NOT NULL
|
|
4
|
+
)`),E(i,e`INSERT OR IGNORE INTO ${e.identifier(t)} (id, value) VALUES (0, 0)`)},r=i=>{const[o]=E(i,e`SELECT value FROM ${e.identifier(t)} WHERE id = 0`);return typeof o?.value=="number"?o.value:0},a=i=>(E(i,e`UPDATE ${e.identifier(t)} SET value = value + 1 WHERE id = 0`),r(i));export{n as COMMIT_SEQ_FIELD,t as COMMIT_SEQ_TABLE,a as allocateCommitSeq,S as migrateCommitSeq,r as readCommitSeq};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{LunoraError as y}from"@lunora/errors";import{s as Ht,c as Nt,j as Je,a as jt,y as Ae,h as Kt}from"./ctx-db-companions-lTt-rvKG.mjs";import{sql as r}from"drizzle-orm";import{d as Ot}from"./wire-codec-BU9T2xJ7.mjs";import{throwingScheduler as Qt,aggregateSqlFunction as ve,normalizeCountArgument as zt}from"./AGGREGATE_SQL_FUNCTION-m1iUU1rv.mjs";import{aggregateTableName as Be,encodeAggregateKey as qe,readAggregateValue as Ue}from"./aggregateTableName-Cy5e03oz.mjs";import{mergeWhere as J,CountRlsUnsupportedError as Pe,selectIndexForGroupBy as Jt,selectIndexForCount as Vt,selectIndexForAggregate as Yt}from"./CountRlsUnsupportedError-Bdfupt3g.mjs";import{backfillSearchIndexesForTable as Xt}from"./backfillAggregateIndexes-DVQ2sVuV.mjs";import{backfillAggregateIndexes as Kr,backfillRankIndexes as Or,backfillSearchIndexes as Qr}from"./backfillAggregateIndexes-DVQ2sVuV.mjs";import{appendCdcChange as Zt}from"./CDC_LOG_TABLE-B58N8NQO.mjs";import{CDC_LOG_TABLE as Jr,applyCdcChanges as Vr,bumpCdcEpoch as Yr,minCdcSeq as Xr,readCdcChanges as Zr,readCdcCursor as eo,readCdcEpoch as to,trimCdcChanges as no}from"./CDC_LOG_TABLE-B58N8NQO.mjs";import{allocateCommitSeq as en,COMMIT_SEQ_FIELD as tn}from"./COMMIT_SEQ_FIELD-CSe_oNZu.mjs";import{isMemoryTable as nn}from"./clearMemoryTables-CXULwypv.mjs";import{computeRankPage as dt}from"./computeRankPage-Bby1Npkd.mjs";import{SCAN_DEP as H}from"./SCAN_DEP-D7qE3iUe.mjs";import{runDrizzle as q}from"./runDrizzle-it6rL9bR.mjs";import{D as K,k as se,r as de,b as Ie,A as Ge,a as Ce,e as V,t as It,f as lt,i as rn,h as Ct,g as on}from"./do-sql-Dk_DJxn4.mjs";import{WORKERD_SQLITE_LIMITS as xt,unionAll as Ke,sqliteInList as sn}from"./param-Ib8WHnrF.mjs";import{coveringGeohashes as cn,boundingBoxGeohashes as an,haversineMeters as dn,pointInBoundingBox as ln}from"./GEO_DEFAULT_PRECISION-CqpQZ-J_.mjs";import{NotFoundError as un}from"./NotFoundError-BhF7FeFr.mjs";import{softDeleteScope as ae,normalizeOrderKeys as fn,buildSeekWhere as Mt,decodeCursor as Oe,applySelect as ut,encodeCursor as Qe,buildSeekBeforeWhere as hn}from"./applySelect-BQbHyo-W.mjs";import{rankTableName as ft,sortColumnName as ht,resolveRankPartition as wn,encodePartitionKey as pn,RANK_TIEBREAK as gn}from"./RANK_TIEBREAK-ci3MaM65.mjs";import{indexKeysForRow as $n,buildIndexRange as yn}from"./buildIndexRange-CBKQmHSS.mjs";import{assertFlatPredicate as He,resolveRelationPredicates as wt}from"./DEFAULT_MAX_RELATION_KEYS-BAWGIEvC.mjs";import{runRowValidators as Ne,resolveWith as pt,relationHooks as gt,applyOnDelete as En,fanOutScalarCounts as mn}from"./applyOnDelete-BlcwKjuO.mjs";import{guardWriter as Sn}from"./RLS_UNWRAP_SYMBOL-BWloGsd3.mjs";import{i as _n}from"./sql-projection-BqmxFxQU.mjs";import{createSystemReader as Rn}from"./createSystemReader-BtYeSMDb.mjs";import{ConflictError as pe}from"./ConflictError-C8GtJmjS.mjs";import{runTriggers as Tn}from"./hasTrigger-CjlwI4le.mjs";import{compileWhereSql as te}from"./compileWhereSql-JBpSfQm9.mjs";import{CLIENT_WATERMARK_TABLE as oo,advanceClientWatermark as io,migrateClientWatermark as so,readClientWatermark as co}from"./CLIENT_WATERMARK_TABLE-BoS1HEqz.mjs";import{GLOBAL_SHAPE_SNAPSHOT_TABLE as lo,deleteGlobalShapeSnapshot as uo,deleteGlobalShapeSnapshotsForConnection as fo,migrateGlobalShapeSnapshot as ho,readGlobalShapeSnapshot as wo,writeGlobalShapeSnapshot as po}from"./GLOBAL_SHAPE_SNAPSHOT_TABLE-NWaL77m5.mjs";import{IDEMPOTENCY_TABLE as $o,readIdempotent as yo,trimIdempotent as Eo,writeIdempotent as mo}from"./IDEMPOTENCY_TABLE-DKVe2Ohf.mjs";import{runShardMigrations as _o}from"./runShardMigrations-DtIbA812.mjs";import{SEARCH_STATE_TABLE as To}from"./SEARCH_STATE_TABLE-Dju8ebbU.mjs";import{selectShapeMemberIds as vo,selectShapeRows as Io}from"./selectShapeMemberIds-B-pQJHAu.mjs";import{serializeSqlValue as oe}from"./serializeSqlValue-DbI1VQYM.mjs";import{quoteIdentifier as An}from"./quoteIdentifier-CObIFRhb.mjs";const vn=o=>{const i=new TextEncoder().encode(o);let t="";for(const a of i)t+=String.fromCodePoint(a);return btoa(t)},In=o=>{const i=atob(o),t=Uint8Array.from(i,a=>a.codePointAt(0)??0);return new TextDecoder().decode(t)},Cn=()=>new y("BAD_REQUEST","invalid cursor"),$t=16,yt=8,X=1024,Ve=(o,i)=>i.query(o),xn=(o,i,t)=>{const a=Ht(o,t);if(a.length===0)return 0;let f=0;for(const[p,E]of i.entries()){const R=p===i.length-1;let S=0;for(const $ of a)(R?$.startsWith(E):$===E)&&(S+=1);if(S===0)return 0;f+=S}return f},Mn=(o,i)=>{if(!i)return{exact:!0,lower:o,upper:o};const t=[...o].at(-1)??"",a=(t.codePointAt(0)??0)+1;if(a>=55296&&a<=57343||a>1114111)return{exact:!0,lower:o,upper:o};const f=o.slice(0,o.length-t.length);return{exact:!1,lower:o,upper:f+String.fromCodePoint(a)}},bn=(o,i,t)=>{const a={eq:(f,p)=>{if(!o.definition.filterFields?.includes(f))throw new y("INTERNAL",`field "${f}" is not a filter field of search index "${o.indexName}" on table "${i}"`);if(o.filters.length>=yt)throw new y("BAD_REQUEST",`search index "${o.indexName}" on table "${i}": at most ${String(yt)} .eq() filters are supported per search query`);return o.filters.push({field:f,value:p}),a},search:(f,p)=>{const E=o;if(f!==E.definition.field)throw new y("INTERNAL",`search index "${E.indexName}" on table "${i}" indexes "${E.definition.field}", not "${f}"`);const R=Ve(p,t).length;if(R>$t)throw new y("BAD_REQUEST",`search index "${E.indexName}" on table "${i}": at most ${String($t)} search terms are supported (got ${String(R)})`);return E.field=f,E.query=p,E.hasQuery=!0,a}};return a},Dn=o=>{if(o.length>X)throw new y("BAD_REQUEST",`more than ${String(X)} documents match this search — narrow it with filters or read it a page at a time with .paginate()`)},kn=o=>Math.min(o.offset+o.numItems+1,X),Ln=o=>vn(`search:${String(o)}`),Fn=o=>{let i;try{i=In(o)}catch{return}if(!i.startsWith("search:"))return;const t=Number(i.slice(7));return Number.isInteger(t)&&t>=0?t:void 0},Wn=o=>{if(typeof o.endCursor=="string")throw new y("BAD_REQUEST","bounded (endCursor) pagination is not supported on search queries — relevance order has no stable range boundary");if(!Number.isFinite(o.numItems))throw new y("BAD_REQUEST",`search pagination needs a finite numItems, got ${String(o.numItems)}`);const i=Math.max(0,Math.floor(o.numItems)),t=o.cursor?Fn(o.cursor):0;if(t===void 0)throw Cn();if(t+i>=X)throw new y("BAD_REQUEST",`search pagination reaches the ${String(X)}-document limit (offset ${String(t)} + ${String(i)} requested) — a page must end below the cap so the probe row that answers \`hasMore\` still fits: retry with numItems ${String(Math.max(1,X-t-1))} or fewer, or narrow the query or the filters instead`);return{numItems:i,offset:t}},Bn=(o,i)=>{const t=i.offset+i.numItems,a=i.numItems>0&&o.length>t;return{continueCursor:a?Ln(t):null,isDone:!a,page:o.slice(i.offset,t)}},qn=o=>{if(o===void 0)return X+1;if(!Number.isFinite(o))return X;const i=Math.max(0,Math.floor(o));if(i>X)throw new y("BAD_REQUEST",`search returns at most ${String(X)} documents (asked for ${String(i)}) — narrow the query or paginate instead`);return i},Un=/^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/iu,Pn=o=>{if(!Un.test(o))throw new y("INTERNAL",`invalid clientId ${JSON.stringify(o)}: a client-supplied row id must be a UUID`)},Et=50,bt=500,xe=Math.floor(xt.boundParams/3),we=xt.boundParams,Gn=128,ce=(o,i,t)=>{const a=i??bt;if(o>a)throw new y("BATCH_LIMIT_EXCEEDED",`${t}: batch of ${String(o)} exceeds the limit of ${String(a)} (raise options.limit or chunk the call)`,{status:400})},Hn=o=>{const i={eq:(t,a)=>(o.sqlConditions.push({comparator:"=",field:t,value:a}),i),gt:(t,a)=>(o.sqlConditions.push({comparator:">",field:t,value:a}),i),gte:(t,a)=>(o.sqlConditions.push({comparator:">=",field:t,value:a}),i),lt:(t,a)=>(o.sqlConditions.push({comparator:"<",field:t,value:a}),i),lte:(t,a)=>(o.sqlConditions.push({comparator:"<=",field:t,value:a}),i)};return i},Nn=o=>Math.max(o,X),Dt=(o,i)=>{const t=o.filters.map(a=>r`${V(a.field)} = ${oe(a.value)}`);return i&&t.push(i),t},jn=(o,i,t,a,f)=>{const p=Ve(t.query,Je(t.definition.language));if(p.length===0)return[];const E=jt(i,t.indexName),R=`${E}__vocab`,S=p.length-1,$=p.map((W,M)=>{const N=Mn(W,M===S),j=N.exact?r`${r.identifier("term")} = ${N.lower}`:r`${r.identifier("term")} >= ${N.lower} AND ${r.identifier("term")} < ${N.upper}`;return r`SELECT ${r.identifier("doc")}, ${r.raw(String(M))} AS ${r.identifier("__term__")}, COUNT(*) AS ${r.identifier("__n__")} FROM ${r.identifier(R)} WHERE ${j} GROUP BY ${r.identifier("doc")}`}),L=p.map((W,M)=>r`SUM(CASE WHEN u.${r.identifier("__term__")} = ${r.raw(String(M))} THEN u.${r.identifier("__n__")} ELSE 0 END)`),T=r`SELECT f.${r.identifier(Ae)} AS ${r.identifier(Ae)}, ${r.join(L,r` + `)} AS ${r.identifier("__score__")} FROM (${Ke($)}) u JOIN ${r.identifier(E)} f ON f.rowid = u.${r.identifier("doc")} GROUP BY f.${r.identifier(Ae)} HAVING ${r.join(L.map(W=>r`${W} > 0`),r` AND `)}`,v=Dt(t,f);let _=r`SELECT m.id, m._creationTime, m.${r.identifier(K)}, s.${r.identifier("__score__")} AS ${r.identifier("__score__")} FROM (${T}) s JOIN ${r.identifier(i)} m ON m.id = s.${r.identifier(Ae)}`;v.length>0&&(_=r`${_} WHERE ${r.join(v,r` AND `)}`),_=r`${_} ORDER BY s.${r.identifier("__score__")} DESC, m._creationTime DESC, m.id ASC LIMIT ${r.raw(String(a))}`;const F=[];for(const W of q(o,_)){const M=Ct(W);if(M){const N=W.__score__;F.push({document:M,score:typeof N=="number"?N:Number(N??0)})}}return F},Kn=(o,i,t,a,f)=>{const p=Je(t.definition.language),E=Ve(t.query,p);if(E.length===0)return[];const R=Dt(t,f);let S=r`SELECT id, _creationTime, ${r.identifier(K)} FROM ${r.identifier(i)}`;R.length>0&&(S=r`${S} WHERE ${r.join(R,r` AND `)}`),S=r`${S} ORDER BY _creationTime DESC, id ASC LIMIT ${r.raw(String(Nn(a)))}`;const $=q(o,S).toArray(),L=[];for(const T of $){const v=Ct(T);if(!v)continue;const _=xn(Kt(v,t.definition),E,p);_>0&&L.push({creationTime:typeof v._creationTime=="number"?v._creationTime:0,doc:v,id:typeof v._id=="string"?v._id:"",score:_})}return L.sort((T,v)=>v.score-T.score||v.creationTime-T.creationTime||T.id.localeCompare(v.id)),L.slice(0,a).map(T=>({document:T.doc,score:T.score}))},je=(o,i,t,a)=>{if(!Number.isFinite(o.lat)||o.lat<-90||o.lat>90||!Number.isFinite(o.lng)||o.lng<-180||o.lng>180)throw new y("BAD_REQUEST",`geo index "${a}" on table "${t}": ${i} must have a finite lat in [-90, 90] and lng in [-180, 180]`)},On=(o,i)=>{const t=o,a={near:(f,p)=>{if(t.within)throw new y("INTERNAL",`geo index "${t.indexName}" on table "${i}": call .near() or .within(), not both`);if(je(f,".near() point",i,t.indexName),!Number.isFinite(p)||p<=0)throw new y("BAD_REQUEST",`geo index "${t.indexName}" on table "${i}": .near() radiusMeters must be a finite number > 0, got ${String(p)}`);return t.near={point:{lat:f.lat,lng:f.lng},radiusMeters:p},a},within:f=>{if(t.near)throw new y("INTERNAL",`geo index "${t.indexName}" on table "${i}": call .near() or .within(), not both`);if(je(f.sw,".within() sw corner",i,t.indexName),je(f.ne,".within() ne corner",i,t.indexName),f.sw.lat>f.ne.lat)throw new y("BAD_REQUEST",`geo index "${t.indexName}" on table "${i}": .within() corners are transposed (sw.lat > ne.lat)`);if(f.sw.lng>f.ne.lng)throw new y("BAD_REQUEST",`geo index "${t.indexName}" on table "${i}": .within() box crosses the antimeridian (sw.lng > ne.lng), which is not supported — split it into two boxes at ±180 and union the results`);return t.within={ne:{lat:f.ne.lat,lng:f.ne.lng},sw:{lat:f.sw.lat,lng:f.sw.lng}},a}};return a},Qn=(o,i)=>{const t=o[i];if(t===null||typeof t!="object")return;const{lat:a,lng:f}=t;return typeof a=="number"&&typeof f=="number"?{lat:a,lng:f}:void 0},zn=(o,i)=>{const t=Qn(o,i.definition.field);if(!t)return;const a=typeof o._creationTime=="number"?o._creationTime:0;if(i.near){const f=dn(i.near.point,t);return f<=i.near.radiusMeters?{creationTime:a,distance:f}:void 0}return ln(t,i.within)?{creationTime:a,distance:0}:void 0},Jn=(o,i,t,a)=>{if(!t.near&&!t.within)throw new y("INTERNAL",`geo index "${t.indexName}" on table "${i}": call .near(point, radius) or .within(box)`);const f=t.near?cn(t.near.point,t.near.radiusMeters):an(t.within),p=on(i,t.indexName),E=f.map(T=>r`(g.${r.identifier("__geohash__")} >= ${T} AND g.${r.identifier("__geohash__")} < ${`${T}{`})`),R=[r`(${r.join(E,r` OR `)})`];a&&R.push(a);const S=r`SELECT m.id, m._creationTime, m.${r.identifier(K)} FROM ${r.identifier(p)} g JOIN ${r.identifier(i)} m ON m.id = g.${r.identifier("__id__")} WHERE ${r.join(R,r` AND `)}`,$=q(o,S).toArray(),L=[];for(const T of $){const v=de(T),_=v?zn(v,t):void 0;v&&_&&L.push({creationTime:_.creationTime,distance:_.distance,doc:v})}return L.sort((T,v)=>T.distance-v.distance||v.creationTime-T.creationTime),L},kt=(o,i,t,a)=>{const f=[];for(const p of o)if(i.every(E=>E(a(p)))&&(f.push(p),typeof t=="number"&&f.length>=t))break;return f},Vn=(o,i,t,a,f,p=()=>{})=>{const E=t.within!==void 0,R=Jn(o,i,t,f).map(S=>({distanceMeters:E?null:S.distance,document:S.doc}));return p(R.length),typeof a=="number"?R.slice(0,Math.max(0,Math.floor(a))):R},Lt=(o,i,t,a,f,p=()=>{})=>{const{geo:E}=t;if(!E)throw new y("INTERNAL","runGeoTerminalScored called without a staged geo query");const R=t.inMemoryFilters.length>0,S=Vn(o,i,E,R?void 0:f,a,p);return R?kt(S,t.inMemoryFilters,f,$=>$.document):S},Yn=(o,i,t,a,f,p=()=>{})=>Lt(o,i,t,a,f,p).map(E=>E.document),Xn=(o,i,t,a,f,p,E=()=>{})=>{const R=[];for(const T of t.sqlConditions)R.push(r`${V(T.field)} ${r.raw(T.comparator)} ${oe(T.value)}`);a&&R.push(a);let S=r`SELECT id, _creationTime, ${r.identifier(K)} FROM ${r.identifier(i)}`;R.length>0&&(S=r`${S} WHERE ${r.join(R,r` AND `)}`),S=r`${S} ORDER BY ${f}`,typeof p=="number"&&t.inMemoryFilters.length===0&&(S=r`${S} LIMIT ${r.raw(String(Math.max(0,Math.floor(p))))}`);const $=q(o,S).toArray();E($.length);const L=[];for(const T of $){const v=de(T);if(v&&t.inMemoryFilters.every(_=>_(v))&&(L.push(v),typeof p=="number"&&L.length>=p))break}return L},re={fieldRef:V,serialize:oe},Ft=(o,i)=>{const t=i===void 0?void 0:o.shape[i];return t!==void 0&&_n(t)},mt=(o,i)=>i.some(t=>Ft(o,t)),St=(o,i,t)=>{if(Ft(o,i))throw new y("BAD_REQUEST",`${t}: "${i}" is stored as an order-preserving key, which SQL cannot reduce or group — declare an aggregateIndex covering this (by, field, op) so the maintained companion answers it`)},Zn=o=>{let i=0;const t=[],a={fieldRef:V,relationExists:f=>{const{childWhere:p,negated:E,parentTable:R,relation:S}=f,$=`__rel_${String(i)}`,L=t.at(-1)??R;i+=1,o(S.table,H);const T=S.kind==="one"?S.field:S.references,v=S.kind==="one"?S.references:S.field,_=r`${lt($,v)} = ${lt(L,T)}`;t.push($);const F=te(p,a);t.pop();const W=F?r`${_} AND ${F}`:_,M=r`EXISTS (SELECT 1 FROM ${r.identifier(S.table)} AS ${r.identifier($)} WHERE ${W})`;return E?r`NOT ${M}`:M},serialize:oe};return a},Wt=o=>{const i=o.map(t=>r`${V(t.field)} ${r.raw(t.direction==="desc"?"DESC":"ASC")}`);return o.some(t=>t.field==="_id"||t.field==="id")||i.push(r`${V("id")} ASC`),r.join(i,r`, `)},er={"<":"lt","<=":"lte","=":"eq",">":"gt",">=":"gte"},tr=o=>{const i=o.order;return o.indexFields.length>0?o.indexFields.map(t=>({direction:i,field:t})):[{direction:i,field:"_creationTime"}]},nr=(o,i,t,a)=>{const f=o.sqlConditions.map(p=>({[p.field]:{[er[p.comparator]??"eq"]:p.value}}));if(t&&f.push(Mt(i,Oe(t))),a&&f.push(hn(i,Oe(a))),f.length!==0)return f.length===1?f[0]:{AND:f}},rr=(o,i,t)=>{const a=[];for(const f of o){const p=de(f);if(p&&i.every(E=>E(p))&&(a.push(p),t!==void 0&&a.length>t))break}return a},or=(o,i,t,a,f,p=()=>{})=>{const E=Math.max(0,Math.floor(a.numItems)),R=tr(t),S=typeof a.endCursor=="string",$=te(nr(t,R,a.cursor,a.endCursor),re),L=f&&$?r`${$} AND ${f}`:f??$;let T=r`SELECT id, _creationTime, ${r.identifier(K)} FROM ${r.identifier(i)}`;L&&(T=r`${T} WHERE ${L}`),T=r`${T} ORDER BY ${Wt(R)}`;const v=t.inMemoryFilters.length>0;!v&&!S&&(T=r`${T} LIMIT ${r.raw(String(E+1))}`);const _=q(o,T).toArray();p(_.length);const F=rr(_,t.inMemoryFilters,v||S?void 0:E);if(S){const j=F.length>=2?F[Math.floor(F.length/2)-1]:void 0;return{continueCursor:a.endCursor??null,isDone:!0,page:F,splitCursor:j?Qe(j,R):null}}const W=F.length>E,M=W?F.slice(0,E):F,N=M.at(-1);return{continueCursor:W&&N?Qe(N,R):null,isDone:!W,page:M}};class ir extends y{constructor(i="unique() found more than one matching document"){super("NOT_UNIQUE",i,{name:"NotUniqueError"})}}const sr=/\s/u,cr=String.fromCodePoint(0),_t=(o,i,t)=>{if(!o.tables[i])throw new y("INTERNAL",`unknown table: ${i}`);return typeof t!="string"||t.length===0||sr.test(t)||t.includes(cr)?null:t},ar=(o,i,t,a=()=>{},f=()=>{},p=()=>{})=>{const E=i.tables[t];if(!E)throw new y("INTERNAL",`unknown table: ${t}`);const R=ae(E.softDeleteMode,void 0),S=R?te(R,re):void 0,$={indexFields:[],indexName:void 0,inMemoryFilters:[],order:"asc",sqlConditions:[]};let L=0;const T=m=>{const{search:b}=$;if(!b)throw new y("INTERNAL","runSearchFetch called without a staged search");Xt(o,t,E);const k=$.inMemoryFilters.length>0,C=qn(k?void 0:m),O=rn(o)?jn(o,t,b,C,S):Kn(o,t,b,C,S);return k?(L=O.length,kt(O,$.inMemoryFilters,m,be=>be.document)):(m===void 0&&Dn(O),O)},v=m=>T(m).map(b=>b.document),_=m=>{const b=Wn(m);return Bn(v(kn(b)),b)},F=()=>{const m=$.indexFields.length>0?$.indexFields:["_creationTime"],b=$.order==="desc"?"DESC":"ASC";return r.join(m.map(k=>r`${V(k)} ${r.raw(b)}`),r`, `)},W=()=>{if($.search||$.geo||$.indexName===void 0){f(void 0);return}f(yn(t,$.indexName,$.indexFields,$.sqlConditions,oe))},M=m=>{W();let b=0;const k=(()=>{if($.search){const C=v(m);return b=L,C}return $.geo?Yn(o,t,$,S,m,C=>{b=C}):Xn(o,t,$,S,F(),m,C=>{b=C})})();return p(Math.max(b,k.length)),k},N=()=>{if(!$.search&&!$.geo)throw new y("INTERNAL",`ctx.db.query("${t}").collectWithScores() requires a staged .withSearchIndex(...) or .withGeoIndex(...)`);W();let m=0;const b=(()=>{if($.search){const k=T(void 0);return m=L,k}return Lt(o,t,$,S,void 0,k=>{m=k})})();return p(Math.max(m,b.length)),b},j={async*[Symbol.asyncIterator](){const m=[...$.inMemoryFilters];let b;$.inMemoryFilters=[];try{for(;;){const k=await j.paginate({cursor:b??null,numItems:Gn});for(const C of k.page)m.every(O=>O(C))&&(yield C);if(k.isDone||k.continueCursor===null)return;b=k.continueCursor}}finally{$.inMemoryFilters=m}},async collect(){return M(void 0)},async collectWithScores(){return N()},filter(m){return $.inMemoryFilters.push(m),j},async first(){return M($.inMemoryFilters.length>0?void 0:1)[0]??null},order(m){return $.order=m==="desc"?"desc":"asc",j},async paginate(m){let b=0;if(W(),$.search){const C=_(m);return p(C.page.length),C}if($.geo)throw new y("INTERNAL","pagination is not supported on geo queries; use .take(n) or .collect()");const k=or(o,t,$,m,S,C=>{b=C});return p(Math.max(b,k.page.length)),k},async take(m){return M(m)},async unique(){const m=M($.inMemoryFilters.length>0?void 0:2);if(m.length>1)throw new ir(`unique() on table "${t}" matched ${String(m.length)} documents; expected at most one`);return m[0]??null},withGeoIndex(m,b){const k=(E.geoIndexes??[]).find(O=>O.name===m);if(!k)throw new y("INTERNAL",`unknown geo index "${m}" on table "${t}"`);a(t,m,"geo");const C={definition:k,indexName:m};if($.geo=C,b(On(C,t)),!C.near&&!C.within)throw new y("INTERNAL",`geo index "${m}" on table "${t}" requires a .near(point, radius) or .within(box) call`);return j},withIndex(m,b){const k=E.indexes.find(C=>C.name===m);if(!k)throw new y("INTERNAL",`unknown index "${m}" on table "${t}"`);return a(t,m,"index"),$.indexName=m,$.indexFields=k.fields,b&&b(Hn($)),j},withSearchIndex(m,b){const k=(E.searchIndexes??[]).find(O=>O.name===m);if(!k)throw new y("INTERNAL",`unknown search index "${m}" on table "${t}"`);a(t,m,"search");const C={definition:k,field:k.field,filters:[],hasQuery:!1,indexName:m,query:""};if($.search=C,b(bn(C,t,Je(k.language))),!C.hasQuery)throw new y("INTERNAL",`search index "${m}" on table "${t}" requires a .search(field, query) call`);return j}};return j},Rt=(o,i,t)=>{const a={...i};for(const[f,p]of It(o)){if(p.serverDefault){a[f]=p.serverDefault({auth:t});continue}a[f]===void 0&&(p.defaultFn?a[f]=p.defaultFn():"defaultValue"in p&&(a[f]=p.defaultValue))}return a},Tt=(o,i,t,a)=>{const f=t;for(const[p,E]of It(o)){if(E.serverDefault){p in i&&(f[p]=E.serverDefault({auth:a}));continue}E.onUpdateFn&&!(p in i)&&(f[p]=E.onUpdateFn())}},At=(o,i)=>{for(const t of Object.keys(i))if(i[t]===void 0)throw new y("INTERNAL",`Cannot ${o} field '${t}' to undefined — use null to clear a nullable field, or omit the key to leave it unchanged.`)},dr=/unique constraint failed/i,lr=o=>o instanceof Error&&dr.test(o.message),ze=(o,i,t)=>{try{q(o,t)}catch(a){throw lr(a)?new pe(`unique constraint violation on "${i}"`,"unique"):a}},Me=(o,i,t)=>{if(ze(o,i,t),q(o,r`SELECT changes() AS changed`).one().changed===0)throw new pe(`optimistic concurrency conflict on "${i}" — the row changed during this mutation; refetch and retry`,"occ")},vt=(o,i,t,a,f,p,E)=>{const R=[];for(let T=0;T<t.length+1;T+=1){const v=[];for(let M=0;M<T;M+=1)v.push(r`${r.identifier(t[M])} IS ${p[M]}`);const _=t[T],F=a[T];if(_!==void 0&&F!==void 0){const M=F.direction==="desc"?">":"<";v.push(r`${r.identifier(_)} ${r.raw(M)} ${p[T]}`)}else v.push(r`${r.identifier(gn)} < ${E}`);const[W]=v;R.push(v.length===1&&W!==void 0?W:r`(${r.join(v,r` AND `)})`)}const S=r.join(R,r` OR `),$=q(o,r`SELECT COUNT(*) AS c FROM ${r.identifier(i)} WHERE ${r.identifier("__partition__")} = ${f} AND (${S})`).one(),L=q(o,r`SELECT COUNT(*) AS c FROM ${r.identifier(i)} WHERE ${r.identifier("__partition__")} = ${f}`).one();return{before:$.c,total:L.c}},Hr=o=>{const{sql:i}=o,{schema:t}=o,a=o.broadcast??(()=>{});let f;const p=()=>o.inTransaction?.()===!0,E=e=>t.tables[e]?.commitOrderedMode!==!0?{}:((f===void 0||!p())&&(f=en(i)),{[tn]:f}),R=(e,...n)=>{const s=t.tables[e]?.indexes;if(!s||s.length===0)return;const u=[];for(const h of n)h&&u.push(...$n(s,h,oe));return u.length>0?u:void 0},{headroom:S}=o;let $=!1;const L=async e=>{const n=$;$=!0;try{return await e()}finally{$=n}},T=o.onRead??(()=>{}),v=o.onReadRange??(e=>{T(e.table,H)}),_=(e,n)=>{n!==void 0&&n!==H&&!$&&S?.recordRead(1),T(e,n)},F=o.onIndexUse??(()=>{}),W=o.onWrite??(()=>{}),M=e=>{$||S?.recordWrite(e)},N=async e=>{M(e.doc),await W(e)},{cache:j}=o,m=o.clock??(()=>Date.now()),b=o.idGenerator??(()=>crypto.randomUUID()),k=o.scheduler??Qt,{globalDb:C}=o,O=o.auth??{identity:null,userId:null},be=o.cdc??!1,De=k,Bt=Rn({scheduler:typeof De.list=="function"&&typeof De.get=="function"?De:void 0,storage:o.storage}),le=(e,n,s,u)=>{be&&!nn(t.tables[e])&&Zt(i,m(),e,n,s,u)},ie=e=>t.tables[e]?.shardMode?.kind==="global",Ye=(e,n)=>{if(ie(e)){if(!C)throw new y("INTERNAL",`cross-backend ${n} for global table '${e}' requires a globalDb writer — pass one to createShardCtxDb({ globalDb })`);return C}return U},ke=e=>Ye(e,"cascade"),z=(e,n)=>{if(ie(e)){if(!C)throw new y("INTERNAL",`${n} on global table '${e}' requires a globalDb writer — pass one to createShardCtxDb({ globalDb })`);return C}},Xe=async(e,n,s,u,h)=>{h&&M(s);const l=await e.insert(n,s,u);return a({key:l,op:"insert",row:{...s,_id:l},table:n}),l},Le=(e,n)=>Ye(e,"relation load").findMany(e,n),Ze=(e,n)=>(ie(e)&&_(e,H),Le(e,n)),qt=e=>!ie(e.table),et=o.relationExistsPushDown??"auto",tt=et!=="never",{maxRelationKeys:nt}=o,ge=(e,n,s)=>wt(e,{fetcher:Ze,maxRelationKeys:nt,relationBaseWhere:s,schema:t,tableName:n}),rt=async(e,n,s,u)=>{const h=z(e,"relation grouped count");if(h)return _(e,H),mn((B,I)=>h.count(B,I),e,n,s,u);const l=t.tables[e];if(!l)throw new y("INTERNAL",`unknown table: ${e}`);_(e,H);const c=ae(l.softDeleteMode,void 0),d={[n]:{in:s}},w=J(J(d,u),c),A=await ge(w,e,void 0),g=te(A,re),x=V(n);let D=r`SELECT ${x} AS __fk__, COUNT(*) AS count FROM ${r.identifier(e)}`;g&&(D=r`${D} WHERE ${g}`),D=r`${D} GROUP BY ${x}`;const P=q(i,D).toArray();return new Map(P.map(B=>[B.__fk__,B.count]))};let $e=0;const ot=new Set;for(const[e,n]of Object.entries(t.tables))for(const s of Object.values(n.triggerMap??{}))ot.add(`${e} ${s.timing} ${s.op}`);const Z=(e,n,s)=>ot.has(`${e} ${n} ${s}`),ee=async(e,n,s)=>{if($e+=1,$e>Et)throw $e-=1,new pe(`trigger recursion exceeded ${String(Et)} levels on "${s.table}" — check for a self-triggering write`,"trigger");try{await Tn({ctx:Pt,event:s,op:n,schema:t,tableName:s.table,timing:e})}finally{$e-=1}},{ensureBackfilledForTable:ue,ensureBackfilledIndex:Fe,ensureRankBackfilled:We,ensureRankBackfilledForTable:fe,syncAggregates:ye,syncCompanionsForInsert:it,syncGeo:Ee,syncRanks:he,syncSearch:me}=Nt({broadcast:a,indexKeysFor:(e,n)=>R(e,n),invalidateCache:(e,n,s)=>j?.invalidate(e,n,R(e,s)),recordCdc:le,schema:t,sql:i}),st=(e,n,s)=>{const{shardMode:u}=n;if(u?.kind==="shardBy"&&!(u.field!==void 0&&(s.partitionBy??[]).includes(u.field)))throw Object.assign(new Error(`rank index "${s.name}" on "${e}" partitions across shards (shard key "${u.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})},ct=e=>Object.entries(t.tables).filter(([,n])=>n.shardMode?.kind!=="global").map(([n])=>n).filter(n=>e===void 0||n===e),ne=(e,n)=>{const s=ct(n);for(let u=0;u<s.length;u+=we){const h=s.slice(u,u+we).map(g=>r`SELECT ${r.raw(`'${g.replaceAll("'","''")}'`)} AS __t__, id, _creationTime, ${r.identifier(K)} FROM ${r.identifier(g)} WHERE id = ${e}`),[l]=q(i,r`${Ke(h)} LIMIT 1`).toArray();if(!l)continue;const c=l.__t__,d=de(l);if(typeof c!="string"||!d)return;const w=l[K];return{docJson:typeof w=="string"?w:se(w??{}),row:d,tableName:c}}},Ut=(e,n)=>{const s=[...new Set(e)],u=new Map;if(s.length===0)return u;const h=ct(n);for(let l=0;l<h.length;l+=we){const c=h.slice(l,l+we),d=Math.floor(we/c.length),w=sn(r`${r.identifier("id")}`,s,!1,d),A=c.map(g=>r`SELECT ${r.raw(`'${g.replaceAll("'","''")}'`)} AS __t__, id FROM ${r.identifier(g)} WHERE ${w}`);for(const g of q(i,Ke(A))){const{id:x,__t__:D}=g;typeof D=="string"&&typeof x=="string"&&u.set(x,D)}}return u},at={assertRankPartitionLocal:st,ensureRankBackfilled:We,onRead:_,rowToDocument:de,schema:t,sql:i},U={system:Bt,async aggregate(e,n){const s=z(e,"aggregate");if(s)return _(e,H),s.aggregate(e,n);const u=t.tables[e];if(!u)throw new y("INTERNAL",`unknown table: ${e}`);if(ve(n.op),n.op==="count")return U.count(e,{baseWhere:n.baseWhere,relationBaseWhere:n.relationBaseWhere,restrictsCounts:n.restrictsCounts,where:n.where});if(!n.field)throw new y("INTERNAL",`aggregate(${e}, { op: "${n.op}" }): "field" is required for non-count reducers`);_(e,H);const h=ae(u.softDeleteMode,void 0),l=J(J(n.baseWhere,n.where),h),c=await ge(l,e,n.relationBaseWhere),d=c!==l;if(u.aggregateIndexes&&!n.baseWhere&&!d&&(!h||mt(u,[n.field]))){const B=Yt(u.aggregateIndexes,n.op,n.field,n.where);if(B){Fe(e,B.index);const I=qe(B.index.by??[],B.key),Q=Be(e,B.index.name),Y=q(i,r`SELECT ${Ie} AS value, ${Ge} AS count FROM ${r.identifier(Q)} WHERE ${Ce} = ${I}`).toArray()[0];return Ue(n.op,Y)}}St(u,n.field,`aggregate(${e}, { op: "${n.op}", field: "${n.field}" })`);const w=te(c,re),A=ve(n.op),g=V(n.field);let x=r`SELECT ${r.raw(A)}(${g}) AS value FROM ${r.identifier(e)}`;w&&(x=r`${x} WHERE ${w}`);const P=q(i,x).toArray()[0]?.value;return P??null},asId(e,n){const s=_t(t,e,n);if(s===null)throw new y("BAD_REQUEST",`asId("${e}", …): "${n}" is not a valid id for table "${e}"`,{status:400});return s},async count(e,n){const s=z(e,"count");if(s)return _(e,H),s.count(e,n);const u=t.tables[e];if(!u)throw new y("INTERNAL",`unknown table: ${e}`);const h=zt(n);if(h.restrictsCounts)throw new Pe(e);_(e,H);const l=ae(u.softDeleteMode,void 0),c=J(J(h.baseWhere,h.where),l),d=await ge(c,e,h.relationBaseWhere),w=d!==c;if(u.aggregateIndexes&&!h.baseWhere&&!w&&!l){const D=Vt(u.aggregateIndexes,h.where);if(D){Fe(e,D.index);const P=qe(D.index.by??[],D.key),B=Be(e,D.index.name),I=q(i,r`SELECT ${Ie} AS value FROM ${r.identifier(B)} WHERE ${Ce} = ${P}`).toArray();return I[0]===void 0?0:I[0].value??0}}const A=te(d,re);let g=r`SELECT COUNT(*) AS count FROM ${r.identifier(e)}`;return A&&(g=r`${g} WHERE ${A}`),q(i,g).one().count},async delete(e,n,s){const u=ne(e,n);if(!u){const g=n===void 0?C:void 0;g&&(M(void 0),await g.delete(e,void 0,s));return}const{docJson:h,row:l,tableName:c}=u,d=t.tables[c],w=s?.hard===!0,A=!w&&d?.softDeleteMode?d.softDeleteMode.field:void 0;if(!(A&&l[A]!==null&&l[A]!==void 0)){if(Z(c,"before","delete")&&await ee("before","delete",{id:e,op:"delete",previous:l,table:c}),await En({deletedId:e,deletedReference:g=>l[g],findHolders:async(g,x,D)=>(await ke(g).findMany(g,{includeDeleted:w,where:{[x]:D}})).page,onCascade:(g,x)=>ke(g).delete(x,void 0,s),onRestrict:g=>{throw new pe(g,"restrict")},onSetNull:(g,x,D)=>ke(g).patch(x,{[D]:null}),schema:t,tableName:c}),ue(c),fe(c),A){const g={...l,...E(c),[A]:m(),_id:e};Me(i,c,r`UPDATE ${r.identifier(c)} SET ${r.identifier(K)} = ${se(g)} WHERE id = ${e} AND ${r.identifier(K)} = ${h}`),me(c,e,g,l),Ee(c,e,void 0),ye(c,l,g),he(c,e,l,void 0),j?.invalidate(c,e,R(c,l,g)),le(c,e,"update",g),a({indexKeys:R(c,l,g),key:e,op:"update",row:g,table:c}),Z(c,"after","delete")&&await ee("after","delete",{id:e,op:"delete",previous:l,table:c}),await N({id:e,op:"delete",table:c});return}Me(i,c,r`DELETE FROM ${r.identifier(c)} WHERE id = ${e} AND ${r.identifier(K)} = ${h}`),me(c,e,void 0),Ee(c,e,void 0),ye(c,l,void 0),he(c,e,l,void 0),j?.invalidate(c,e,R(c,l)),le(c,e,"delete"),a({indexKeys:R(c,l),key:e,op:"delete",table:c}),Z(c,"after","delete")&&await ee("after","delete",{id:e,op:"delete",previous:l,table:c}),await N({id:e,op:"delete",table:c})}},async deleteAll(e,n){if(!t.tables[e])throw new y("INTERNAL",`unknown table: ${e}`);const s=Math.max(1,n?.chunkSize??bt),u=n?.hard===void 0?void 0:{hard:n.hard},h=ie(e)?void 0:e;let l=0;return await L(async()=>{for(;;){const d=(await U.findMany(e,{limit:s})).page.map(w=>String(w._id));if(d.length===0)break;for(const w of d)await U.delete(w,h,u),l+=1;if(d.length<s)break}}),{deleted:l}},async deleteMany(e,n,s){ce(e.length,n?.limit,"deleteMany");for(const u of e)await U.delete(u,s);return{deleted:e.length}},async deleteWhere(e,n,s){const l=(await(z(e,"deleteWhere")??U).findMany(e,{where:n})).page.map(c=>String(c._id));if(ce(l.length,s?.limit,"deleteWhere"),U.deleteMany===void 0)throw new y("INTERNAL",`ctx.db.${e}.deleteMany is unavailable: this writer has no batch delete`);return U.deleteMany(l,s)},async findFirst(e,n={}){return(await U.findMany(e,{...n,limit:1})).page[0]??null},async findFirstOrThrow(e,n={}){const s=await U.findFirst(e,n);if(s===null)throw new un(`findFirstOrThrow: no "${e}" document matched`);return s},async findMany(e,n={}){const s=z(e,"findMany");if(s)return _(e,H),s.findMany(e,n);const u=t.tables[e];if(!u)throw new y("INTERNAL",`unknown table: ${e}`);const h=!n.where&&!n.baseWhere;h?_(e,H):_(e);const l=fn(n.orderBy),c=n.cursor?Mt(l,Oe(n.cursor)):void 0;let d=J(n.baseWhere,n.where);d=J(d,ae(u.softDeleteMode,n.includeDeleted)),d=await wt(d,{canPushExists:tt?qt:void 0,existsPushMode:et==="always"?"always":"auto",fetcher:Ze,maxRelationKeys:nt,relationBaseWhere:n.relationBaseWhere,schema:t,tableName:e}),c&&(d=d?{AND:[d,c]}:c);const w=tt?Zn(_):re,A=te(d,w);let g=r`SELECT id, _creationTime, ${r.identifier(K)} FROM ${r.identifier(e)}`;A&&(g=r`${g} WHERE ${A}`),g=r`${g} ORDER BY ${Wt(l)}`;const x=typeof n.limit=="number"?Math.max(0,Math.floor(n.limit)):void 0;x!==void 0&&(g=r`${g} LIMIT ${r.raw(String(x+1))}`);const D=q(i,g).toArray();h&&!$&&S?.recordRead(D.length);const P=[];for(const Y of D){const G=de(Y);G&&(P.push(G),!h&&typeof G._id=="string"&&_(e,G._id))}if(x===void 0)return n.with&&await pt({groupedCounter:rt,fetcher:Le,parents:P,...gt(n),schema:t,tableName:e,with:n.with}),{continueCursor:null,isDone:!0,page:ut(P,n.select,n.with)};const B=P.length>x,I=B?P.slice(0,x):P,Q=I.at(-1);return n.with&&await pt({fetcher:Le,groupedCounter:rt,parents:I,...gt(n),schema:t,tableName:e,with:n.with}),{continueCursor:B&&Q?Qe(Q,l):null,isDone:!B,page:ut(I,n.select,n.with)}},async get(e,n){const s=ne(e,n);if(!s){const u=n===void 0?C:void 0;return u?u.get(e):null}return _(s.tableName,e),s.row},async lookupById(e,n){const s=ne(e,n);return s?(_(s.tableName,e),{row:s.row,tableName:s.tableName}):null},async groupBy(e,n){const s=z(e,"groupBy");if(s)return _(e,H),s.groupBy(e,n);const u=t.tables[e];if(!u)throw new y("INTERNAL",`unknown table: ${e}`);_(e,H);const h=n.agg??{op:"count"};if(ve(h.op),h.op!=="count"&&!h.field)throw new y("INTERNAL",`groupBy(${e}, { agg: { op: "${h.op}" } }): "field" is required for non-count reducers`);const l=ae(u.softDeleteMode,void 0),c=J(J(n.baseWhere,n.where),l),d=await ge(c,e,n.relationBaseWhere),w=d!==c,A=[...n.by,h.field];if(u.aggregateIndexes&&!n.baseWhere&&!w&&(!l||mt(u,A))){const I=Jt(u.aggregateIndexes,h.op,h.field,n.by,n.where),Q=I===void 0?0:Object.keys(I.partial).length,Y=I?.index.by?.length??0;if(I&&(Q===0||Q===Y)){Fe(e,I.index);const G=Be(e,I.index.name),Se=Object.keys(I.partial),_e=[];if(Se.length===(I.index.by??[]).length&&Se.length>0){const Re=qe(I.index.by??[],I.partial),Te=q(i,r`SELECT ${Ie} AS value, ${Ge} AS count FROM ${r.identifier(G)} WHERE ${Ce} = ${Re}`).toArray();return Te.length>0&&_e.push({key:{...I.partial},value:Ue(h.op,Te[0])}),_e}const Gt=q(i,r`SELECT ${Ce} AS key, ${Ie} AS value, ${Ge} AS count FROM ${r.identifier(G)}`).toArray();for(const Re of Gt){const Te=Ot(JSON.parse(Re.key));_e.push({key:Te,value:Ue(h.op,Re)})}return _e}}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}"] })`;St(u,I,Q)}const g=te(d,re),x=n.by.map(I=>r`${V(I)} AS ${r.identifier(I)}`);if(h.op==="count")x.push(r`COUNT(*) AS value`);else{const{field:I}=h;if(I===void 0)throw new y("INTERNAL",`groupBy(${e}, { agg: { op: "${h.op}" } }): "field" is required for non-count reducers`);x.push(r`${r.raw(ve(h.op))}(${V(I)}) AS value`)}let D=r`SELECT ${r.join(x,r`, `)} FROM ${r.identifier(e)}`;g&&(D=r`${D} WHERE ${g}`),D=r`${D} GROUP BY ${r.join(n.by.map(I=>V(I)),r`, `)}`;const P=q(i,D).toArray(),B=[];for(const I of P){const Q={};for(const G of n.by)Q[G]=I[G]??null;const{value:Y}=I;B.push({key:Q,value:Y==null?null:Number(Y)})}return B},async insert(e,n,s){const u=z(e,"insert");if(u)return Xe(u,e,n,s,!0);const h=t.tables[e];if(!h)throw new y("INTERNAL",`unknown table: ${e}`);const l=Rt(h,n,O);Ne(h,l);let c;s?.clientId!==void 0?(Pn(s.clientId),c=s.clientId):s?.allowExplicitId&&typeof l._id=="string"?c=l._id:c=b();const d=s?.allowExplicitId&&typeof l._creationTime=="number"?l._creationTime:m(),w={...l,...E(e),_creationTime:d,_id:c};return Z(e,"before","insert")&&await ee("before","insert",{doc:{...w},id:c,op:"insert",table:e}),ue(e),fe(e),ze(i,e,r`INSERT INTO ${r.identifier(e)} (id, _creationTime, ${r.identifier(K)}) VALUES (${c}, ${d}, ${se(w)})`),it(e,c,w),Z(e,"after","insert")&&await ee("after","insert",{doc:w,id:c,op:"insert",table:e}),await N({doc:w,id:c,op:"insert",table:e}),c},async insertManyUnsafe(e,n,s){if(ce(n.length,s?.limit,"insertManyUnsafe"),n.length===0)return[];const u=z(e,"insert");if(u){const d=[];for(const w of n)M(w);for(const w of n){const A=await u.insert(e,w,{allowExplicitId:s?.allowExplicitId});a({key:A,op:"insert",row:{...w,_id:A},table:e}),d.push(A)}return d}const h=t.tables[e];if(!h)throw new y("INTERNAL",`unknown table: ${e}`);ue(e),fe(e);const l=[];for(let d=0;d<n.length;d+=xe)l.push(E(e));const c=n.map((d,w)=>{const A=Rt(h,d,O),g=s?.allowExplicitId===!0&&typeof A._id=="string"?A._id:b(),x=s?.allowExplicitId===!0&&typeof A._creationTime=="number"?A._creationTime:m(),D={...A,...l[Math.floor(w/xe)],_creationTime:x,_id:g};return{creationTime:x,document:D,id:g}});for(const d of c)M(d.document);for(let d=0;d<c.length;d+=xe){const w=r.join(c.slice(d,d+xe).map(A=>r`(${A.id}, ${A.creationTime}, ${se(A.document)})`),r`, `);ze(i,e,r`INSERT INTO ${r.identifier(e)} (id, _creationTime, ${r.identifier(K)}) VALUES ${w}`)}for(const{document:d,id:w}of c)it(e,w,d),await W({doc:d,id:w,op:"insert",table:e});return c.map(d=>d.id)},async insertMany(e,n,s){ce(n.length,s?.limit,"insertMany");const u=s?.skipDuplicates===!0,h=[],l=z(e,"insert");if(l)for(const d of n)M(d);const c=async d=>l?Xe(l,e,d,void 0,!1):U.insert(e,d);for(const d of n)try{h.push(await c(d))}catch(w){if(u&&w instanceof pe&&w.kind==="unique")h.push(null);else throw w}return h},normalizeId(e,n){return _t(t,e,n)},async patch(e,n,s){const u=ne(e,s);if(!u){const A=s===void 0?C:void 0;if(A){M(n),await A.patch(e,n);return}throw new y("INTERNAL",`document not found: ${e}`)}const{docJson:h,row:l,tableName:c}=u,d=t.tables[c];if(!d)throw new y("INTERNAL",`unknown table: ${c}`);_(c,e),At("patch",n);const w={...l,...n,...E(c),_id:e};Tt(d,n,w,O),Ne(d,w,!0),Z(c,"before","update")&&await ee("before","update",{doc:{...w},id:e,op:"update",previous:l,table:c}),ue(c),fe(c),Me(i,c,r`UPDATE ${r.identifier(c)} SET ${r.identifier(K)} = ${se(w)} WHERE id = ${e} AND ${r.identifier(K)} = ${h}`),me(c,e,w,l),Ee(c,e,w),ye(c,l,w),he(c,e,l,w),j?.invalidate(c,e,R(c,l,w)),le(c,e,"update",w),a({indexKeys:R(c,l,w),key:e,op:"update",row:w,table:c}),Z(c,"after","update")&&await ee("after","update",{doc:w,id:e,op:"update",previous:l,table:c}),await N({doc:w,id:e,op:"update",table:c})},async patchMany(e,n,s){ce(e.length,n?.limit,"patchMany");for(const u of e)await U.patch(u.id,u.patch,s);return{patched:e.length}},async patchWhere(e,n,s){const l=(await(z(e,"patchWhere")??U).findMany(e,{where:n.where})).page.map(c=>({id:String(c._id),patch:n.patch}));if(ce(l.length,s?.limit,"patchWhere"),U.patchMany===void 0)throw new y("INTERNAL",`ctx.db.${e}.patchMany is unavailable: this writer has no batch patch`);return await U.patchMany(l,s),{patched:l.length}},query(e){const n=z(e,"query");return n?(_(e,H),n.query(e)):ar(i,t,e,F,s=>{s?v(s):_(e,H)},s=>{$||S?.recordRead(s)})},async rank(e,n,s){const u=z(e,"rank");if(u)return _(e,H),u.rank(e,n,s);F(e,n,"rank");const h=t.tables[e];if(!h)throw new y("INTERNAL",`unknown table: ${e}`);const l=h.rankIndexes?.find(G=>G.name===n);if(!l)throw new y("INTERNAL",`unknown rankIndex "${n}" on table "${e}"`);if(st(e,h,l),s.restrictsCounts)throw new Pe(e);_(e,H),We(e,l);const c=typeof s.row=="string"?s.row:s.row._id;if(!c)return null;const d=ft(e,l.name),w=l.sortBy.map((G,Se)=>ht(Se)),A=w.map(G=>An(G)).join(", "),g=q(i,r`SELECT ${r.identifier("__partition__")}, ${r.raw(A)} FROM ${r.identifier(d)} WHERE ${r.identifier("__id__")} = ${c}`).toArray(),[x]=g;if(x===void 0)return null;let D=x.__partition__;const P=J(s.baseWhere,s.where);He(P,t,e,"rank");const B=wn(l,P);if(B){const G=pn(l.partitionBy??[],B);if(G!==D)return null;D=G}const I=w.map(G=>x[G]),{before:Q,total:Y}=vt(i,d,w,l.sortBy,D,I,c);return{position:Q+1,total:Y}},async rankBefore(e,n,s){if(ie(e))throw new y("INTERNAL",`rankBefore is not supported on the global (.global()) table '${e}' — cross-shard rank cursors apply only to sharded tables`);const u=t.tables[e];if(!u)throw new y("INTERNAL",`unknown table: ${e}`);const h=u.rankIndexes?.find(w=>w.name===n);if(!h)throw new y("INTERNAL",`unknown rankIndex "${n}" on table "${e}"`);if(s.restrictsCounts)throw new Pe(e);_(e,H),We(e,h);const l=ft(e,h.name),c=h.sortBy.map((w,A)=>ht(A)),d=h.sortBy.map((w,A)=>oe(s.sortValues[A]??null));return vt(i,l,c,h.sortBy,s.partitionKey,d,s.rowId)},async rankPage(e,n,s={}){He(J(s.baseWhere,s.where),t,e,"rankPage");const u=z(e,"rankPage");if(u)return _(e,H),u.rankPage(e,n,s);F(e,n,"rank");const{continueCursor:h,hasMore:l,rows:c}=dt(at,e,n,s);return{continueCursor:h,isDone:!l,page:c.map(d=>d.doc)}},async rankPageRows(e,n,s={}){He(J(s.baseWhere,s.where),t,e,"rankPage"),F(e,n,"rank");const{directions:u,hasMore:h,rows:l}=dt(at,e,n,s);return{directions:u,hasMore:h,rows:l}},async restore(e,n){const s=ne(e,n);if(!s){const l=n===void 0?C:void 0;if(l?.restore){await l.restore(e);return}throw new y("INTERNAL",`document not found: ${e}`)}const u=t.tables[s.tableName]?.softDeleteMode?.field;if(!u)throw new y("INTERNAL",`ctx.db.restore: table "${s.tableName}" is not a .softDelete() table`);const h=s.row[u]!==null&&s.row[u]!==void 0;await U.patch(e,{[u]:null},n),h&&he(s.tableName,e,void 0,s.row)},async replace(e,n,s,u){const h=ne(e,s);if(!h){const x=s===void 0?C:void 0;if(x){M(n),await x.replace(e,n,void 0,u);return}throw new y("INTERNAL",`document not found: ${e}`)}const{docJson:l,row:c,tableName:d}=h,w=t.tables[d];if(!w)throw new y("INTERNAL",`unknown table: ${d}`);At("replace",n);const A=u?.allowExplicitId&&typeof n._creationTime=="number"?n._creationTime:m(),g={...n,...E(d),_creationTime:A,_id:e};Tt(w,n,g,O),Ne(w,g),Z(d,"before","update")&&await ee("before","update",{doc:{...g},id:e,op:"update",previous:c,table:d}),ue(d),fe(d),Me(i,d,r`UPDATE ${r.identifier(d)} SET _creationTime = ${A}, ${r.identifier(K)} = ${se(g)} WHERE id = ${e} AND ${r.identifier(K)} = ${l}`),me(d,e,g,c),Ee(d,e,g),ye(d,c,g),he(d,e,c,g),j?.invalidate(d,e,R(d,c,g)),le(d,e,"update",g),a({indexKeys:R(d,c,g),key:e,op:"update",row:g,table:d}),Z(d,"after","update")&&await ee("after","update",{doc:g,id:e,op:"update",previous:c,table:d}),await N({doc:g,id:e,op:"update",table:d})},async wipeShard(e){const n=new Set(e?.exclude),s=e?.tables,u=Object.entries(t.tables).filter(([d,w])=>n.has(d)||s!==void 0&&!s.includes(d)?!1:w.shardMode?.kind!=="global").map(([d])=>d);if(s!==void 0){for(const d of s)if(!t.tables[d])throw new y("INTERNAL",`wipeShard: unknown table: ${d}`)}const h={};let l=0;const{deleteAll:c}=U;if(c===void 0)throw new y("INTERNAL","wipeShard: this writer has no deleteAll");for(const d of u){const w=await c(d,{...e?.chunkSize===void 0?{}:{chunkSize:e.chunkSize},hard:!0});h[d]=w.deleted,l+=w.deleted}return{deleted:l,tables:h}}},Pt={db:U,scheduler:k};return o.enforceRls===!0?Sn(U,t,(e,n)=>ne(e,n)?.tableName,(e,n)=>Ut(e,n)):U};export{Jr as CDC_LOG_TABLE,oo as CLIENT_WATERMARK_TABLE,lo as GLOBAL_SHAPE_SNAPSHOT_TABLE,$o as IDEMPOTENCY_TABLE,ir as NotUniqueError,To as SEARCH_STATE_TABLE,io as advanceClientWatermark,Vr as applyCdcChanges,Pn as assertValidClientId,Kr as backfillAggregateIndexes,Or as backfillRankIndexes,Qr as backfillSearchIndexes,Yr as bumpCdcEpoch,Hr as createShardCtxDb,uo as deleteGlobalShapeSnapshot,fo as deleteGlobalShapeSnapshotsForConnection,so as migrateClientWatermark,ho as migrateGlobalShapeSnapshot,Xr as minCdcSeq,_t as normalizeIdStructurally,Zr as readCdcChanges,eo as readCdcCursor,to as readCdcEpoch,co as readClientWatermark,wo as readGlobalShapeSnapshot,yo as readIdempotent,_o as runShardMigrations,vo as selectShapeMemberIds,Io as selectShapeRows,no as trimCdcChanges,Eo as trimIdempotent,po as writeGlobalShapeSnapshot,mo as writeIdempotent};
|
|
@@ -0,0 +1,28 @@
|
|
|
1
|
+
import{sql as t}from"drizzle-orm";import{runDrizzle as o}from"./runDrizzle-it6rL9bR.mjs";const a="__reactor_state",c=[["runs","runs INTEGER NOT NULL DEFAULT 0"],["suppressed","suppressed INTEGER NOT NULL DEFAULT 0"],["errors","errors INTEGER NOT NULL DEFAULT 0"],["last_ran_at","last_ran_at INTEGER NOT NULL DEFAULT 0"],["last_error","last_error TEXT"]],O=r=>{o(r,t`CREATE TABLE IF NOT EXISTS ${t.identifier(a)} (
|
|
2
|
+
path TEXT PRIMARY KEY,
|
|
3
|
+
digest TEXT NOT NULL,
|
|
4
|
+
tables TEXT NOT NULL,
|
|
5
|
+
runs INTEGER NOT NULL DEFAULT 0,
|
|
6
|
+
suppressed INTEGER NOT NULL DEFAULT 0,
|
|
7
|
+
errors INTEGER NOT NULL DEFAULT 0,
|
|
8
|
+
last_ran_at INTEGER NOT NULL DEFAULT 0,
|
|
9
|
+
last_error TEXT
|
|
10
|
+
)`);const e=new Set(o(r,t`PRAGMA table_info(${t.identifier(a)})`).toArray().map(s=>s.name));for(const[s,i]of c)e.has(s)||o(r,t`ALTER TABLE ${t.identifier(a)} ADD COLUMN ${t.raw(i)}`)},R=r=>{if(typeof r=="string")try{const e=JSON.parse(r);return Array.isArray(e)&&e.every(s=>typeof s=="string")?e:void 0}catch{return}},T=r=>typeof r=="number"&&Number.isFinite(r)?r:0,d=r=>({digest:r.digest,...typeof r.last_error=="string"&&r.last_error.length>0?{lastError:r.last_error}:{},lastRanAt:T(r.last_ran_at),stats:{errors:T(r.errors),runs:T(r.runs),suppressed:T(r.suppressed)},tables:R(r.tables)}),l="path, digest, tables, runs, suppressed, errors, last_ran_at, last_error",f=(r,e)=>{const[s]=o(r,t`SELECT ${t.raw(l)} FROM ${t.identifier(a)} WHERE path = ${e}`);if(!(s===void 0||typeof s.digest!="string"))return d(s)},U=r=>o(r,t`SELECT ${t.raw(l)} FROM ${t.identifier(a)} ORDER BY path`).toArray().filter(e=>typeof e.digest=="string").map(e=>({path:e.path,state:d(e)})),g=(r,e,s)=>{const{digest:i,error:p,now:u,result:n,tables:E}=s,L=i??"",N=E===void 0?"":JSON.stringify([...E]),_=p??null;o(r,t`INSERT INTO ${t.identifier(a)} (path, digest, tables, runs, suppressed, errors, last_ran_at, last_error)
|
|
11
|
+
VALUES (
|
|
12
|
+
${e},
|
|
13
|
+
${L},
|
|
14
|
+
${N},
|
|
15
|
+
${n==="ran"?1:0},
|
|
16
|
+
${n==="suppressed"?1:0},
|
|
17
|
+
${n==="error"?1:0},
|
|
18
|
+
${u},
|
|
19
|
+
${_}
|
|
20
|
+
)
|
|
21
|
+
ON CONFLICT(path) DO UPDATE SET
|
|
22
|
+
digest = ${i===void 0?t.raw(`${a}.digest`):t`excluded.digest`},
|
|
23
|
+
tables = ${E===void 0?t.raw(`${a}.tables`):t`excluded.tables`},
|
|
24
|
+
runs = ${t.raw(`${a}.runs`)} + ${n==="ran"?1:0},
|
|
25
|
+
suppressed = ${t.raw(`${a}.suppressed`)} + ${n==="suppressed"?1:0},
|
|
26
|
+
errors = ${t.raw(`${a}.errors`)} + ${n==="error"?1:0},
|
|
27
|
+
last_ran_at = excluded.last_ran_at,
|
|
28
|
+
last_error = ${n==="error"?t`excluded.last_error`:t.raw("NULL")}`)},S=(r,e)=>r?.tables===void 0?!0:r.tables.some(s=>e.has(s));export{a as REACTOR_STATE_TABLE,U as listReactorStates,O as migrateReactorState,S as reactorNeedsRun,f as readReactorState,g as writeReactorState};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{sql as t}from"drizzle-orm";import{runDrizzle as s}from"./runDrizzle-it6rL9bR.mjs";const a=r=>r?.memoryMode===!0,l=r=>Object.entries(r.tables).filter(([,e])=>a(e)&&e.shardMode?.kind!=="global").map(([e])=>e),i=(r,e)=>{const o=l(e);for(const m of o)s(r,t`DELETE FROM ${t.identifier(m)}`);return o.length};export{i as clearMemoryTables,a as isMemoryTable,l as memoryTableNames};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{createShardCtxDb as S}from"./NotUniqueError-
|
|
1
|
+
import{createShardCtxDb as S}from"./NotUniqueError-THUZXy3C.mjs";import{createRelayLink as B}from"./DEFAULT_MAX_RELAYS-tuHNDUZr.mjs";import{ConflictError as I}from"./ConflictError-C8GtJmjS.mjs";import{runShardMigrations as v}from"./runShardMigrations-DtIbA812.mjs";import{relayName as F}from"./DEFAULT_PROMOTION_THRESHOLDS-H2sHFvlw.mjs";const _=(E,u={})=>({_meta:{column:{notNull:!0,...u}},kind:E}),D=(E,u,N)=>{const{describe:k,expect:i,it:m}=N;k(`engine contract: ${E}`,()=>{k("optimistic concurrency",()=>{const b=h=>({tables:{items:{indexes:[],shape:{title:_("string"),version:_("number",{notNull:!1})},triggerMap:{clobber:{handler:()=>{h.exec(`UPDATE "items" SET "__doc__" = json_set("__doc__", '$.version', 99) WHERE "id" = 'i1'`)},op:"update",timing:"before"}}}}});m("raises a CONFLICT of kind `occ` when a write's snapshot is clobbered",async()=>{const{close:h,host:d}=u();try{const c=d.sql,l=b(c);v(c,l);const s=S({schema:l,sql:c});await s.insert("items",{_id:"i1",title:"first",version:1},{allowExplicitId:!0}),await i(s.patch("i1",{title:"second"})).rejects.toBeInstanceOf(I)}finally{h?.()}}),m("reports the conflict as CONFLICT/409 rather than retrying it away",async()=>{const{close:h,host:d}=u();try{const c=d.sql,l=b(c);v(c,l);const s=S({schema:l,sql:c});await s.insert("items",{_id:"i1",title:"first",version:1},{allowExplicitId:!0});let a;try{await s.patch("i1",{title:"second"})}catch(t){a=t}const e=a;i(e.code).toBe("CONFLICT"),i(e.kind).toBe("occ")}finally{h?.()}}),m("leaves the row readable and unchanged after a conflict",async()=>{const{close:h,host:d}=u();try{const c=d.sql,l=b(c);v(c,l);const s=S({schema:l,sql:c});await s.insert("items",{_id:"i1",title:"first",version:1},{allowExplicitId:!0});try{await s.patch("i1",{title:"second"})}catch{}const a=await s.get("i1");i(a?.title).toBe("first"),i(a?.version).toBe(99)}finally{h?.()}}),m("raises a CONFLICT of kind `trigger` when a trigger writes its own row through the db",async()=>{const{close:h,host:d}=u();try{const c=d.sql,l={tables:{items:{indexes:[],shape:{title:_("string"),version:_("number",{notNull:!1})},triggerMap:{recurse:{handler:async(t,o)=>{await t.db.patch(o.doc._id,{version:99})},op:"update",timing:"before"}}}}};v(c,l);const s=S({schema:l,sql:c});await s.insert("items",{_id:"i1",title:"first",version:1},{allowExplicitId:!0});let a;try{await s.patch("i1",{title:"second"})}catch(t){a=t}const e=a;i(e).toBeInstanceOf(I),i(e.code).toBe("CONFLICT"),i(e.kind).toBe("trigger")}finally{h?.()}})}),k("shape-poke ordering",()=>{const b="shard-a",h={args:{},name:"messages"},d=(e,t,o,n)=>e.accept(t?.()??{},{connectionId:o,shapes:{[n]:h}}),c=(e,t)=>{let o=0,n=0;const r=g=>()=>{throw new Error(`the relay poke path must not reach RelayHost.${g}`)},p={fetch:(g,O)=>{if(JSON.parse(O?.body??"{}").type!=="relay_shape_subscribe")return Promise.resolve(new Response(void 0,{status:204}));const C=t[n];if(n+=1,C===void 0)throw new Error("the relay asked for more seeds than this fixture supplies");return Promise.resolve(Response.json(C))}},y={get:()=>p,getByName:()=>p,idFromName:g=>g},w={buildShapeDiff:r("buildShapeDiff"),computeOpLogShapeSeed:r("computeOpLogShapeSeed"),currentCdcEpoch:r("currentCdcEpoch"),deliverWhisperLocal:r("deliverWhisperLocal"),doName:()=>F(b,0),env:()=>({SHARD:y}),getWebSockets:()=>e.getSockets(),maskMetadata:r("maskMetadata"),nextPokeId:()=>(o+=1,`poke-${String(o)}`),readAttachment:g=>g.deserializeAttachment?.(),recordShapePokeFanout:()=>{},resolveShape:r("resolveShape"),rlsMetadata:r("rlsMetadata"),shardBinding:()=>"SHARD",sql:r("sql")},f=B(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,o)=>{const n=await e.seedRelayShape(t,o,h,{identity:void 0,userId:void 0});if(n!=="ok")throw new Error(`seed failed: ${JSON.stringify(n)}`)},a=(e={})=>l({...h,checkpoint:20,epoch:"e1",fromCursor:10,rowsPatch:[{id:"r1",op:"upsert",value:{title:"hello"}}],type:"relay_shape_poke",...e});m("frames a poke as pokeStart → pokePart per shape → pokeEnd, under one poke id",async()=>{const{close:e,createSocket:t,readFrames:o,sockets:n}=u();try{const r=c(n,[{cursor:10,epoch:"e1",frames:[]}]),p=d(n,t,"c-alice","s1");await s(r,p,"s1"),await r.handleControl(a());const w=(await o(p)).map(f=>JSON.parse(f));i(w.map(f=>f.type)).toStrictEqual(["pokeStart","pokePart","pokeEnd"]),i(new Set(w.map(f=>f.pokeId)).size).toBe(1),i(w[1]?.shapeId).toBe("s1"),i(w[2]?.checkpoint).toBe(20)}finally{e?.()}}),m("delivers a poke only to sockets whose cursor matches, and advances them past it",async()=>{const{close:e,createSocket:t,readFrames:o,sockets:n}=u();try{const r=c(n,[{cursor:10,epoch:"e1",frames:[]},{cursor:7,epoch:"e1",frames:[]}]),p=d(n,t,"c-alice","s1"),y=d(n,t,"c-bob","s2");await s(r,p,"s1"),await s(r,y,"s2"),await r.handleControl(a());const w=await o(p);i(w.length).toBe(3);const f=await o(y);i(f.length).toBe(0),await r.handleControl(a());const g=await o(p);i(g.length).toBe(3)}finally{e?.()}}),m("skips a socket whose cursor matches under a different CDC epoch",async()=>{const{close:e,createSocket:t,readFrames:o,sockets:n}=u();try{const r=c(n,[{cursor:10,epoch:"e1",frames:[]}]),p=d(n,t,"c-alice","s1");await s(r,p,"s1"),await r.handleControl(a({epoch:"e2"}));const y=await o(p);i(y.length).toBe(0),await r.handleControl(a());const w=await o(p);i(w.length).toBe(3)}finally{e?.()}})}),k("RLS identity under live subscription",()=>{const b="shard-a",h={args:{},name:"lobby-messages"},d={args:{},name:"my-orders"},c=s=>{const a=[],e=[],t={fetch:(r,p)=>(a.push(JSON.parse(p?.body??"{}")),Promise.resolve(new Response(void 0,{status:204})))},n=B({buildShapeDiff:()=>[{id:"r1",op:"upsert",value:{}}],computeOpLogShapeSeed:()=>({baseCheckpoint:void 0,cursor:10,epoch:"e1",rowsPatch:[]}),currentCdcEpoch:()=>"e1",deliverWhisperLocal:()=>0,doName:()=>b,env:()=>({SHARD:{get:()=>t,getByName:()=>t,idFromName:r=>r}}),getWebSockets:()=>[],maskMetadata:()=>({columns:[]}),nextPokeId:()=>"poke-1",readAttachment:()=>({}),recordShapePokeFanout:()=>{},resolveShape:(r,p,y)=>(e.push(y),r===d.name?{columns:["id"],effectiveWhere:{org:y?.identity?.org??"anonymous"},global:!1,table:"orders"}:{columns:["id"],effectiveWhere:{room:"lobby"},global:!1,table:"messages"}),rlsMetadata:()=>({policies:[]}),shardBinding:()=>"SHARD",sql:()=>s});if(n===void 0)throw new Error("expected an owner link for an un-suffixed DO name");return{owner:n,posts:a,resolvedUnder:e}},l=async(s,a)=>{await s.handleControl(new Request("https://owner.internal/_lunora/relay",{body:JSON.stringify({...a,connectionId:"c-alice",identity:{org:"acme"},relayIndex:0,subId:"s1",type:"relay_shape_subscribe",userId:"u1"}),headers:{"content-type":"application/json"},method:"POST"}))};m("seeds a subscriber under its own forwarded identity, never the anonymous one",async()=>{const{close:s,host:a}=u();try{const{owner:e,resolvedUnder:t}=c(a.sql);await l(e,d),i(t.some(o=>o?.userId==="u1"&&o.identity?.org==="acme")).toBe(!0)}finally{s?.()}}),m("routes an identity-scoped shape to a per-socket poke, not the cohort multicast",async()=>{const{close:s,host:a}=u();try{const{owner:e,posts:t}=c(a.sql);await l(e,d),t.length=0,await e.onFlush(new Set(["orders"]),20);const o=t.filter(n=>n.type==="relay_shape_poke");i(o.length).toBe(1),i(o[0]?.targetConnectionId).toBe("c-alice")}finally{s?.()}}),m("still multicasts an identity-blind shape to the whole cohort",async()=>{const{close:s,host:a}=u();try{const{owner:e,posts:t}=c(a.sql);await l(e,h),t.length=0,await e.onFlush(new Set(["messages"]),20);const o=t.filter(n=>n.type==="relay_shape_poke");i(o.length).toBe(1),i(o[0]?.targetConnectionId).toBeUndefined()}finally{s?.()}})})})};export{D as defineEngineContractSuite};
|
|
@@ -0,0 +1,5 @@
|
|
|
1
|
+
import{a as S,S as L,y as N}from"./ctx-db-companions-lTt-rvKG.mjs";import{sql as e}from"drizzle-orm";import{aggregateTableName as u}from"./aggregateTableName-Cy5e03oz.mjs";import{backfillSearchIndexesForTable as p}from"./backfillAggregateIndexes-DVQ2sVuV.mjs";import{migrateCdcLog as h,migrateCdcMeta as x}from"./CDC_LOG_TABLE-B58N8NQO.mjs";import{migrateClientWatermark as R}from"./CLIENT_WATERMARK_TABLE-BoS1HEqz.mjs";import{migrateCommitSeq as C}from"./COMMIT_SEQ_FIELD-CSe_oNZu.mjs";import{migrateGlobalShapeSnapshot as O}from"./GLOBAL_SHAPE_SNAPSHOT_TABLE-NWaL77m5.mjs";import{migrateIdempotency as b}from"./IDEMPOTENCY_TABLE-DKVe2Ohf.mjs";import{migrateSearchState as U}from"./SEARCH_STATE_TABLE-Dju8ebbU.mjs";import{migrateShapePokeCursor as l}from"./SHAPE_POKE_CURSOR_TABLE-Dh4HfSdC.mjs";import{runDrizzle as a}from"./runDrizzle-it6rL9bR.mjs";import{D as $,e as T,d,t as X,i as G,g as D,a as B,b as M,A as E}from"./do-sql-Dk_DJxn4.mjs";import{migrateDurableStreams as k}from"./appendStreamChunk-CH4e4nJn.mjs";import{rankTableName as F,sortColumnName as Y}from"./RANK_TIEBREAK-ci3MaM65.mjs";import{migrateReactorState as P}from"./REACTOR_STATE_TABLE-Cr9Orfp8.mjs";import{recordSchemaVersion as j}from"./SCHEMA_HISTORY_MAX_VERSIONS-DsycDXWm.mjs";const y=(r,n,o)=>{for(const i of o.indexes){const t=`${n}_${i.name}`,m=e.join(i.fields.map(s=>T(s)),e`, `);a(r,d(t,n,m,i.unique??!1))}for(const[i,t]of X(o)){if(!t.unique)continue;const m=`${n}_unique_${i}`;a(r,d(m,n,T(i),!0))}},v=(r,n,o)=>{if(!(!o.searchIndexes||o.searchIndexes.length===0||!G(r))){for(const i of o.searchIndexes){const t=S(n,i.name);a(r,e`CREATE VIRTUAL TABLE IF NOT EXISTS ${e.identifier(t)} USING fts5(${e.identifier(L)}, ${e.identifier(N)} UNINDEXED)`),a(r,e`CREATE VIRTUAL TABLE IF NOT EXISTS ${e.identifier(`${t}__vocab`)} USING fts5vocab(${e.identifier(t)}, ${e.raw("instance")})`)}p(r,n,o)}},K=(r,n,o)=>{if(o.geoIndexes)for(const i of o.geoIndexes){const t=D(n,i.name);a(r,e`CREATE TABLE IF NOT EXISTS ${e.identifier(t)} (${e.identifier("__id__")} TEXT PRIMARY KEY, ${e.identifier("__geohash__")} TEXT NOT NULL, ${e.identifier("__lat__")} REAL NOT NULL, ${e.identifier("__lng__")} REAL NOT NULL)`);const m=`${n}__geo_${i.name}__btree`;a(r,d(m,t,e`${e.identifier("__geohash__")} ASC, ${e.identifier("__id__")} ASC`,!1))}},V=(r,n,o)=>{if(o.aggregateIndexes)for(const i of o.aggregateIndexes){const t=u(n,i.name);a(r,e`CREATE TABLE IF NOT EXISTS ${e.identifier(t)} (${B} TEXT PRIMARY KEY, ${M} REAL, ${E} INTEGER NOT NULL DEFAULT 0)`),a(r,e`PRAGMA table_info(${e.identifier(t)})`).toArray().some(s=>s.name==="__count__")||a(r,e`ALTER TABLE ${e.identifier(t)} ADD COLUMN ${E} INTEGER NOT NULL DEFAULT 0`)}},w=(r,n,o)=>{if(o.rankIndexes)for(const i of o.rankIndexes){const t=F(n,i.name),m=i.sortBy.map((f,_)=>Y(_)),s=m.map(f=>e`${e.identifier(f)} BLOB`),g=s.length>0?e`, ${e.join(s,e`, `)}`:e``;a(r,e`CREATE TABLE IF NOT EXISTS ${e.identifier(t)} (${e.identifier("__id__")} TEXT PRIMARY KEY, ${e.identifier("__partition__")} TEXT NOT NULL${g})`);const c=[e`${e.identifier("__partition__")} ASC`];for(const[f,_]of m.entries()){const I=i.sortBy[f]?.direction;c.push(e`${e.identifier(_)} ${e.raw(I==="desc"?"DESC":"ASC")}`)}c.push(e`${e.identifier("__id__")} ASC`);const A=`${n}__rank_${i.name}__btree`;a(r,d(A,t,e.join(c,e`, `),!1))}},de=(r,n,o={})=>{o.schemaSnapshot!==void 0&&j(r,o.schemaSnapshot.hash,o.schemaSnapshot.json),U(r);for(const[i,t]of Object.entries(n.tables))t.shardMode?.kind!=="global"&&(a(r,e`CREATE TABLE IF NOT EXISTS ${e.identifier(i)} (
|
|
2
|
+
id TEXT PRIMARY KEY,
|
|
3
|
+
_creationTime REAL NOT NULL,
|
|
4
|
+
${e.identifier($)} TEXT NOT NULL
|
|
5
|
+
)`),y(r,i,t),v(r,i,t),K(r,i,t),V(r,i,t),w(r,i,t));o.cdc&&(h(r),x(r),R(r),l(r)),Object.values(n.tables).some(i=>i.commitOrderedMode===!0)&&C(r),P(r),b(r),O(r),k(r)};export{de as runShardMigrations};
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@lunora/shard-engine",
|
|
3
|
-
"version": "1.0.0-alpha.
|
|
3
|
+
"version": "1.0.0-alpha.34",
|
|
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.22",
|
|
52
|
-
"@lunora/platform": "1.0.0-alpha.
|
|
52
|
+
"@lunora/platform": "1.0.0-alpha.15",
|
|
53
53
|
"drizzle-orm": "^0.45.2"
|
|
54
54
|
},
|
|
55
55
|
"engines": {
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{LunoraError as v}from"@lunora/errors";import{m as L,n as O}from"./do-sql-Dk_DJxn4.mjs";import{quoteIdentifier as d}from"./quoteIdentifier-CObIFRhb.mjs";import{d as P}from"./wire-codec-BU9T2xJ7.mjs";const te="__lunora_admin__:",ne="__lunora_relation__:",re="__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",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",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",listQueues:"__lunora_admin__:listQueues",lintSql:"__lunora_admin__:lintSql",listTables:"__lunora_admin__:listTables",listWorkflows:"__lunora_admin__:listWorkflows",maskPolicies:"__lunora_admin__:maskPolicies",migrationStatus:"__lunora_admin__:migrationStatus",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,g=500,U=30,W=200,m="__doc__",k=e=>{try{const t=JSON.parse(e);return t!==null&&typeof t=="object"&&!Array.isArray(t)?t:void 0}catch{return}},j=e=>{const{[O]:t,...n}=e;return t===void 0?n:t===null||typeof t!="object"||Array.isArray(t)?{[O]:t,...n}:{...n,...P(t)}},Q=(e,t)=>{if(!e.includes(m))return{columns:e,rows:t};const n=[];for(const s of t){const a=s[m],i=typeof a=="string"?k(a):void 0;if(i===void 0)return{columns:e,rows:t};const c=Object.fromEntries(Object.entries(s).filter(([u])=>u!==m));n.push({...c,...j(i)})}const r=e.filter(s=>s!==m),o=[],_=new Set(r);for(const s of n)for(const a of Object.keys(s))_.has(a)||(_.add(a),o.push(a));return{columns:[...r,...o],rows:n}},F=e=>`instr(lower(CAST(${e} AS TEXT)), lower(?)) > 0`,I=e=>e.startsWith("sqlite_")||e.startsWith("_cf_")||e.startsWith("__miniflare")||e.startsWith("__lunora")||e.includes("__fts_"),E=(e,t,n)=>Math.min(Math.max(e,t),n),x=(e,t)=>{const n=e.exec(`SELECT COUNT(*) AS c FROM ${t}`).one();return Number(n.c)},oe=e=>{const t=e.exec("SELECT name FROM sqlite_master WHERE type = 'table' ORDER BY name").toArray(),n=[];for(const{name:r}of t)I(r)||n.push({name:r,rowCount:x(e,d(r))});return n},N=(e,t)=>e.exec("SELECT name FROM sqlite_master WHERE type = 'table' AND name = ? LIMIT 1",t).toArray().length>0,C=(e,t)=>{if(I(t)||!N(e,t))throw new v("UNKNOWN_TABLE",`unknown table: ${t}`,{status:404})},M=(e,t)=>e.exec(`PRAGMA table_info(${t})`).toArray().map(n=>n.name),q={eq:"=",gt:">",gte:">=",lt:"<",lte:"<=",ne:"<>"},H=e=>typeof e=="string"?e:typeof e=="number"||typeof e=="boolean"?String(e):"",S=(e,t)=>{const n=t.includes(e),r=t.includes(m);if(!(!n&&!r))return n?{expression:d(e),params:[]}:{expression:`json_extract(${d(m)}, ?)`,params:[`$.${L(e)}`]}},B=(e,t)=>{const n=S(e.column,t);if(n===void 0)return;const{expression:r,params:o}=n;return e.operator==="contains"?{params:[...o,H(e.value)],sql:F(r)}:{params:[...o,e.value],sql:`${r} ${q[e.operator]} ?`}},G=/^(\d{4})(?:-(\d{2}))?(?:-(\d{2}))?$/u,X=e=>{const t=G.exec(e.trim());if(t===null)return;const n=Number(t[1]),r=t[2]===void 0?void 0:Number(t[2]),o=t[3]===void 0?void 0:Number(t[3]);if(r!==void 0&&(r<1||r>12)||o!==void 0&&(o<1||o>31)||n<100)return;const _=Date.UTC(n,(r??1)-1,o??1);if(o!==void 0&&new Date(_).getUTCDate()!==o)return;let s;return o!==void 0?s=Date.UTC(n,(r??1)-1,o+1):r===void 0?s=Date.UTC(n+1,0,1):s=Date.UTC(n,r,1),{from:_,to:s}},A=(e,t,n)=>{const r=[],o=[];if(t!==""&&e.length>0){const _=e.map(a=>F(d(a)));o.push(...e.map(()=>t));const s=X(t);if(s!==void 0)for(const a of e)_.push(`(${d(a)} >= ? AND ${d(a)} < ?)`),o.push(s.from,s.to);r.push(`(${_.join(" OR ")})`)}for(const _ of n??[]){const s=B(_,e);s!==void 0&&(r.push(`(${s.sql})`),o.push(...s.params))}return r.length===0?void 0:{parameters:o,where:r.join(" AND ")}},K=(e,t)=>{if(e===void 0)return;const n=S(e.column,t);if(n===void 0)return;const r=e.direction==="desc"?"DESC":"ASC";return{params:n.params,sql:`${n.expression} ${r}`}},ae=(e,t)=>{const{table:n}=t;C(e,n);const r=E(Math.trunc(t.limit??D),1,g),o=Math.max(0,Math.trunc(t.offset??0)),_=d(n),s=M(e,_),a=t.search?.trim()??"",i=b=>{if(t.refs===void 0)return b;const T={};for(const w of b.columns){const y=t.refs[w];y!==void 0&&(T[w]=y)}return Object.keys(T).length>0?{...b,refs:T}:b},c=A(s,a,t.filters),u=K(t.orderBy,s),l=c===void 0?"":` WHERE ${c.where}`,f=u===void 0?"":` ORDER BY ${u.sql}`,p=c?.parameters??[],h=u?.params??[];let R;t.skipCount||(R=c===void 0?x(e,_):Number(e.exec(`SELECT COUNT(*) AS c FROM ${_}${l}`,...p).one().c));const $=e.exec(`SELECT * FROM ${_}${l}${f} LIMIT ? OFFSET ?`,...p,...h,r,o).toArray();return i({...Q(s,$),total:R})},_e=(e,t)=>{const{table:n}=t;C(e,n);const r=E(Math.trunc(t.limit??g),1,g),o=d(n),_=M(e,o),s=t.search?.trim()??"",a=A(_,s,t.filters),i=a===void 0?e.exec(`SELECT id FROM ${o} LIMIT ?`,r+1).toArray():e.exec(`SELECT id FROM ${o} WHERE ${a.where} LIMIT ?`,...a.parameters,r+1).toArray(),c=i.length>r,u=i.slice(0,r).map(l=>l.id);return{hasMore:c,ids:u}},Y=(e,t,n)=>{const r=new Set(n.filter(_=>_!==m));if(!n.includes(m))return r;const o=e.exec(`SELECT ${d(m)} AS doc FROM ${t} LIMIT ?`,g).toArray();for(const{doc:_}of o){const s=typeof _=="string"?k(_):void 0;if(s!==void 0)for(const a of Object.keys(s))r.add(a)}return r},ie=(e,t)=>{const{column:n,table:r}=t;C(e,r);const o=d(r),_=M(e,o);if(!Y(e,o,_).has(n))throw new v("UNKNOWN_COLUMN",`unknown column: ${n}`,{status:404});const s=S(n,_);if(s===void 0)throw new v("UNKNOWN_COLUMN",`unknown column: ${n}`,{status:404});const a=E(Math.trunc(t.limit??U),1,W),i=t.search?.trim()??"",c=A(_,i,t.filters),u=c===void 0?"":` WHERE ${c.where}`,l=c?.parameters??[],f=e.exec(`SELECT ${s.expression} AS value, COUNT(*) AS count FROM ${o}${u} GROUP BY ${s.expression} ORDER BY count DESC LIMIT ?`,...s.params,...l,...s.params,a+1).toArray();return{truncated:f.length>a,values:f.slice(0,a).map(h=>({count:Number(h.count),value:h.value}))}},ce=(e,t,n)=>{const r={},o=n.slice(0,g);for(const s of o)r[s]=[];if(o.length===0)return{references:r,storageColumns:t};const _=o.map(()=>"?").join(", ");for(const[s,a]of Object.entries(t)){if(I(s)||!N(e,s))continue;const i=d(s),c=M(e,i);for(const u of a){const l=S(u,c);if(l===void 0)continue;const f=e.exec(`SELECT id, ${l.expression} AS ref FROM ${i} WHERE ${l.expression} IN (${_})`,...l.params,...l.params,...o).toArray();for(const p of f)r[p.ref]?.push({column:u,id:p.id,table:s})}}return{references:r,storageColumns:t}},ue=e=>{const t=e.map((r,o)=>{const _=Object.values(r.subs??{}).map(s=>({args:s.args,functionPath:s.functionPath,table:s.table}));return{admin:r.admin===!0,id:o,subscriptions:_}}),n=t.reduce((r,o)=>r+o.subscriptions.length,0);return{connections:t,totalConnections:t.length,totalSubscriptions:n}},V=20,le=()=>({maxMs:0,passes:0,peakSocketsIterated:0,socketsDelivered:0,socketsIterated:0,totalMs:0}),de=(e,t,n,r)=>({maxMs:Math.max(e.maxMs,r),passes:e.passes+1,peakSocketsIterated:Math.max(e.peakSocketsIterated,t),socketsDelivered:e.socketsDelivered+n,socketsIterated:e.socketsIterated+t,totalMs:e.totalMs+r}),me=(e,t=V)=>{const n=new Map,r=new Map;for(const s of e){for(const a of Object.values(s.shapes??{})){const i=a.name??"(unknown shape)";n.set(i,(n.get(i)??0)+1)}for(const a of s.whispers??[])r.set(a,(r.get(a)??0)+1)}const o=[...[...n].map(([s,a])=>({kind:"shape",subscribers:a,topic:s})),...[...r].map(([s,a])=>({kind:"whisper",subscribers:a,topic:s}))];return o.sort((s,a)=>a.subscribers-s.subscribers||s.topic.localeCompare(a.topic)),{peakSubscribers:o[0]?.subscribers??0,topics:o.slice(0,t),totalConnections:e.length}};export{se as ADMIN_FUNCTIONS,te as ADMIN_FUNCTION_PREFIX,V as DEFAULT_FANOUT_TOPIC_LIMIT,re as FLAGS_FUNCTION_PREFIX,g as MAX_PAGE_SIZE,ne as RELATION_FUNCTION_PREFIX,le as createFanoutCounters,X as datePrefixRange,ie as facetColumn,ce as findStorageReferences,oe as listTables,ae as readTablePage,de as recordFanoutPass,_e as selectMatchingIds,me as summarizeFanoutTopics,ue as summarizeSubscriptions};
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{LunoraError as E}from"@lunora/errors";import{s as Ut,c as Pt,j as Oe,a as Gt,y as Ae,h as Ht}from"./ctx-db-companions-lTt-rvKG.mjs";import{sql as r}from"drizzle-orm";import{d as Nt}from"./wire-codec-BU9T2xJ7.mjs";import{throwingScheduler as jt,aggregateSqlFunction as ve,normalizeCountArgument as Kt}from"./AGGREGATE_SQL_FUNCTION-m1iUU1rv.mjs";import{aggregateTableName as Le,encodeAggregateKey as Fe,readAggregateValue as We}from"./aggregateTableName-Cy5e03oz.mjs";import{mergeWhere as z,CountRlsUnsupportedError as Be,selectIndexForGroupBy as Ot,selectIndexForCount as Qt,selectIndexForAggregate as zt}from"./CountRlsUnsupportedError-Bdfupt3g.mjs";import{backfillSearchIndexesForTable as Jt}from"./backfillAggregateIndexes-DVQ2sVuV.mjs";import{backfillAggregateIndexes as Br,backfillRankIndexes as qr,backfillSearchIndexes as Ur}from"./backfillAggregateIndexes-DVQ2sVuV.mjs";import{appendCdcChange as Vt}from"./CDC_LOG_TABLE-B58N8NQO.mjs";import{CDC_LOG_TABLE as Gr,applyCdcChanges as Hr,bumpCdcEpoch as Nr,minCdcSeq as jr,readCdcChanges as Kr,readCdcCursor as Or,readCdcEpoch as Qr,trimCdcChanges as zr}from"./CDC_LOG_TABLE-B58N8NQO.mjs";import{computeRankPage as st}from"./computeRankPage-Bby1Npkd.mjs";import{SCAN_DEP as H}from"./SCAN_DEP-D7qE3iUe.mjs";import{runDrizzle as q}from"./runDrizzle-it6rL9bR.mjs";import{D as N,k as ce,r as le,b as Ie,A as qe,a as Ce,e as V,t as At,f as ct,i as Yt,h as vt,g as Xt}from"./do-sql-Dk_DJxn4.mjs";import{WORKERD_SQLITE_LIMITS as It,unionAll as He,sqliteInList as Zt}from"./param-Ib8WHnrF.mjs";import{coveringGeohashes as en,boundingBoxGeohashes as tn,haversineMeters as nn,pointInBoundingBox as rn}from"./GEO_DEFAULT_PRECISION-CqpQZ-J_.mjs";import{NotFoundError as on}from"./NotFoundError-BhF7FeFr.mjs";import{softDeleteScope as de,normalizeOrderKeys as sn,buildSeekWhere as Ct,decodeCursor as Ne,applySelect as at,encodeCursor as je,buildSeekBeforeWhere as cn}from"./applySelect-BQbHyo-W.mjs";import{rankTableName as dt,sortColumnName as lt,resolveRankPartition as an,encodePartitionKey as dn,RANK_TIEBREAK as ln}from"./RANK_TIEBREAK-ci3MaM65.mjs";import{indexKeysForRow as un,buildIndexRange as fn}from"./buildIndexRange-CBKQmHSS.mjs";import{assertFlatPredicate as Ue,resolveRelationPredicates as ut}from"./DEFAULT_MAX_RELATION_KEYS-BAWGIEvC.mjs";import{runRowValidators as Pe,resolveWith as ft,relationHooks as ht,applyOnDelete as hn,fanOutScalarCounts as wn}from"./applyOnDelete-BlcwKjuO.mjs";import{guardWriter as pn}from"./RLS_UNWRAP_SYMBOL-BWloGsd3.mjs";import{i as gn}from"./sql-projection-BqmxFxQU.mjs";import{createSystemReader as $n}from"./createSystemReader-BtYeSMDb.mjs";import{ConflictError as pe}from"./ConflictError-C8GtJmjS.mjs";import{runTriggers as yn}from"./hasTrigger-CjlwI4le.mjs";import{compileWhereSql as te}from"./compileWhereSql-JBpSfQm9.mjs";import{CLIENT_WATERMARK_TABLE as Vr,advanceClientWatermark as Yr,migrateClientWatermark as Xr,readClientWatermark as Zr}from"./CLIENT_WATERMARK_TABLE-BoS1HEqz.mjs";import{GLOBAL_SHAPE_SNAPSHOT_TABLE as to,deleteGlobalShapeSnapshot as no,deleteGlobalShapeSnapshotsForConnection as ro,migrateGlobalShapeSnapshot as oo,readGlobalShapeSnapshot as io,writeGlobalShapeSnapshot as so}from"./GLOBAL_SHAPE_SNAPSHOT_TABLE-NWaL77m5.mjs";import{IDEMPOTENCY_TABLE as ao,readIdempotent as lo,trimIdempotent as uo,writeIdempotent as fo}from"./IDEMPOTENCY_TABLE-DKVe2Ohf.mjs";import{runShardMigrations as wo}from"./runShardMigrations-Crppyq1f.mjs";import{SEARCH_STATE_TABLE as go}from"./SEARCH_STATE_TABLE-Dju8ebbU.mjs";import{selectShapeMemberIds as yo,selectShapeRows as Eo}from"./selectShapeMemberIds-B-pQJHAu.mjs";import{serializeSqlValue as ie}from"./serializeSqlValue-DbI1VQYM.mjs";import{quoteIdentifier as En}from"./quoteIdentifier-CObIFRhb.mjs";const mn=o=>{const i=new TextEncoder().encode(o);let t="";for(const a of i)t+=String.fromCodePoint(a);return btoa(t)},Sn=o=>{const i=atob(o),t=Uint8Array.from(i,a=>a.codePointAt(0)??0);return new TextDecoder().decode(t)},_n=()=>new E("BAD_REQUEST","invalid cursor"),wt=16,pt=8,X=1024,Qe=(o,i)=>i.query(o),Rn=(o,i,t)=>{const a=Ut(o,t);if(a.length===0)return 0;let f=0;for(const[p,m]of i.entries()){const v=p===i.length-1;let S=0;for(const $ of a)(v?$.startsWith(m):$===m)&&(S+=1);if(S===0)return 0;f+=S}return f},Tn=(o,i)=>{if(!i)return{exact:!0,lower:o,upper:o};const t=[...o].at(-1)??"",a=(t.codePointAt(0)??0)+1;if(a>=55296&&a<=57343||a>1114111)return{exact:!0,lower:o,upper:o};const f=o.slice(0,o.length-t.length);return{exact:!1,lower:o,upper:f+String.fromCodePoint(a)}},An=(o,i,t)=>{const a={eq:(f,p)=>{if(!o.definition.filterFields?.includes(f))throw new E("INTERNAL",`field "${f}" is not a filter field of search index "${o.indexName}" on table "${i}"`);if(o.filters.length>=pt)throw new E("BAD_REQUEST",`search index "${o.indexName}" on table "${i}": at most ${String(pt)} .eq() filters are supported per search query`);return o.filters.push({field:f,value:p}),a},search:(f,p)=>{const m=o;if(f!==m.definition.field)throw new E("INTERNAL",`search index "${m.indexName}" on table "${i}" indexes "${m.definition.field}", not "${f}"`);const v=Qe(p,t).length;if(v>wt)throw new E("BAD_REQUEST",`search index "${m.indexName}" on table "${i}": at most ${String(wt)} search terms are supported (got ${String(v)})`);return m.field=f,m.query=p,m.hasQuery=!0,a}};return a},vn=o=>{if(o.length>X)throw new E("BAD_REQUEST",`more than ${String(X)} documents match this search — narrow it with filters or read it a page at a time with .paginate()`)},In=o=>Math.min(o.offset+o.numItems+1,X),Cn=o=>mn(`search:${String(o)}`),xn=o=>{let i;try{i=Sn(o)}catch{return}if(!i.startsWith("search:"))return;const t=Number(i.slice(7));return Number.isInteger(t)&&t>=0?t:void 0},Mn=o=>{if(typeof o.endCursor=="string")throw new E("BAD_REQUEST","bounded (endCursor) pagination is not supported on search queries — relevance order has no stable range boundary");const i=Math.max(0,Math.floor(o.numItems)),t=o.cursor?xn(o.cursor):0;if(t===void 0)throw _n();if(t+i>X)throw new E("BAD_REQUEST",`search pagination reaches past the ${String(X)}-document limit (offset ${String(t)} + ${String(i)} requested) — narrow the query or the filters instead`);return{numItems:i,offset:t}},bn=(o,i)=>{const t=i.offset+i.numItems,a=i.numItems>0&&o.length>t;return{continueCursor:a?Cn(t):null,isDone:!a,page:o.slice(i.offset,t)}},Dn=o=>{if(o===void 0)return X+1;if(!Number.isFinite(o))return X;const i=Math.max(0,Math.floor(o));if(i>X)throw new E("BAD_REQUEST",`search returns at most ${String(X)} documents (asked for ${String(i)}) — narrow the query or paginate instead`);return i},kn=/^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/iu,Ln=o=>{if(!kn.test(o))throw new E("INTERNAL",`invalid clientId ${JSON.stringify(o)}: a client-supplied row id must be a UUID`)},gt=50,xt=500,$t=Math.floor(It.boundParams/3),we=It.boundParams,Fn=128,ae=(o,i,t)=>{const a=i??xt;if(o>a)throw new E("BATCH_LIMIT_EXCEEDED",`${t}: batch of ${String(o)} exceeds the limit of ${String(a)} (raise options.limit or chunk the call)`,{status:400})},Wn=o=>{const i={eq:(t,a)=>(o.sqlConditions.push({comparator:"=",field:t,value:a}),i),gt:(t,a)=>(o.sqlConditions.push({comparator:">",field:t,value:a}),i),gte:(t,a)=>(o.sqlConditions.push({comparator:">=",field:t,value:a}),i),lt:(t,a)=>(o.sqlConditions.push({comparator:"<",field:t,value:a}),i),lte:(t,a)=>(o.sqlConditions.push({comparator:"<=",field:t,value:a}),i)};return i},Bn=o=>Math.max(o,X),Mt=(o,i)=>{const t=o.filters.map(a=>r`${V(a.field)} = ${ie(a.value)}`);return i&&t.push(i),t},qn=(o,i,t,a,f)=>{const p=Qe(t.query,Oe(t.definition.language));if(p.length===0)return[];const m=Gt(i,t.indexName),v=`${m}__vocab`,S=p.length-1,$=p.map((F,k)=>{const j=Tn(F,k===S),K=j.exact?r`${r.identifier("term")} = ${j.lower}`:r`${r.identifier("term")} >= ${j.lower} AND ${r.identifier("term")} < ${j.upper}`;return r`SELECT ${r.identifier("doc")}, ${r.raw(String(k))} AS ${r.identifier("__term__")}, COUNT(*) AS ${r.identifier("__n__")} FROM ${r.identifier(v)} WHERE ${K} GROUP BY ${r.identifier("doc")}`}),_=p.map((F,k)=>r`SUM(CASE WHEN u.${r.identifier("__term__")} = ${r.raw(String(k))} THEN u.${r.identifier("__n__")} ELSE 0 END)`),R=r`SELECT f.${r.identifier(Ae)} AS ${r.identifier(Ae)}, ${r.join(_,r` + `)} AS ${r.identifier("__score__")} FROM (${He($)}) u JOIN ${r.identifier(m)} f ON f.rowid = u.${r.identifier("doc")} GROUP BY f.${r.identifier(Ae)} HAVING ${r.join(_.map(F=>r`${F} > 0`),r` AND `)}`,T=Mt(t,f);let x=r`SELECT m.id, m._creationTime, m.${r.identifier(N)}, s.${r.identifier("__score__")} AS ${r.identifier("__score__")} FROM (${R}) s JOIN ${r.identifier(i)} m ON m.id = s.${r.identifier(Ae)}`;T.length>0&&(x=r`${x} WHERE ${r.join(T,r` AND `)}`),x=r`${x} ORDER BY s.${r.identifier("__score__")} DESC, m._creationTime DESC, m.id ASC LIMIT ${r.raw(String(a))}`;const W=[];for(const F of q(o,x)){const k=vt(F);if(k){const j=F.__score__;W.push({document:k,score:typeof j=="number"?j:Number(j??0)})}}return W},Un=(o,i,t,a,f)=>{const p=Oe(t.definition.language),m=Qe(t.query,p);if(m.length===0)return[];const v=Mt(t,f);let S=r`SELECT id, _creationTime, ${r.identifier(N)} FROM ${r.identifier(i)}`;v.length>0&&(S=r`${S} WHERE ${r.join(v,r` AND `)}`),S=r`${S} ORDER BY _creationTime DESC, id ASC LIMIT ${r.raw(String(Bn(a)))}`;const $=q(o,S).toArray(),_=[];for(const R of $){const T=vt(R);if(!T)continue;const x=Rn(Ht(T,t.definition),m,p);x>0&&_.push({creationTime:typeof T._creationTime=="number"?T._creationTime:0,doc:T,id:typeof T._id=="string"?T._id:"",score:x})}return _.sort((R,T)=>T.score-R.score||T.creationTime-R.creationTime||R.id.localeCompare(T.id)),_.slice(0,a).map(R=>({document:R.doc,score:R.score}))},Ge=(o,i,t,a)=>{if(!Number.isFinite(o.lat)||o.lat<-90||o.lat>90||!Number.isFinite(o.lng)||o.lng<-180||o.lng>180)throw new E("BAD_REQUEST",`geo index "${a}" on table "${t}": ${i} must have a finite lat in [-90, 90] and lng in [-180, 180]`)},Pn=(o,i)=>{const t=o,a={near:(f,p)=>{if(t.within)throw new E("INTERNAL",`geo index "${t.indexName}" on table "${i}": call .near() or .within(), not both`);if(Ge(f,".near() point",i,t.indexName),!Number.isFinite(p)||p<=0)throw new E("BAD_REQUEST",`geo index "${t.indexName}" on table "${i}": .near() radiusMeters must be a finite number > 0, got ${String(p)}`);return t.near={point:{lat:f.lat,lng:f.lng},radiusMeters:p},a},within:f=>{if(t.near)throw new E("INTERNAL",`geo index "${t.indexName}" on table "${i}": call .near() or .within(), not both`);if(Ge(f.sw,".within() sw corner",i,t.indexName),Ge(f.ne,".within() ne corner",i,t.indexName),f.sw.lat>f.ne.lat)throw new E("BAD_REQUEST",`geo index "${t.indexName}" on table "${i}": .within() corners are transposed (sw.lat > ne.lat)`);if(f.sw.lng>f.ne.lng)throw new E("BAD_REQUEST",`geo index "${t.indexName}" on table "${i}": .within() box crosses the antimeridian (sw.lng > ne.lng), which is not supported — split it into two boxes at ±180 and union the results`);return t.within={ne:{lat:f.ne.lat,lng:f.ne.lng},sw:{lat:f.sw.lat,lng:f.sw.lng}},a}};return a},Gn=(o,i)=>{const t=o[i];if(t===null||typeof t!="object")return;const{lat:a,lng:f}=t;return typeof a=="number"&&typeof f=="number"?{lat:a,lng:f}:void 0},Hn=(o,i)=>{const t=Gn(o,i.definition.field);if(!t)return;const a=typeof o._creationTime=="number"?o._creationTime:0;if(i.near){const f=nn(i.near.point,t);return f<=i.near.radiusMeters?{creationTime:a,distance:f}:void 0}return rn(t,i.within)?{creationTime:a,distance:0}:void 0},Nn=(o,i,t,a)=>{if(!t.near&&!t.within)throw new E("INTERNAL",`geo index "${t.indexName}" on table "${i}": call .near(point, radius) or .within(box)`);const f=t.near?en(t.near.point,t.near.radiusMeters):tn(t.within),p=Xt(i,t.indexName),m=f.map(R=>r`(g.${r.identifier("__geohash__")} >= ${R} AND g.${r.identifier("__geohash__")} < ${`${R}{`})`),v=[r`(${r.join(m,r` OR `)})`];a&&v.push(a);const S=r`SELECT m.id, m._creationTime, m.${r.identifier(N)} FROM ${r.identifier(p)} g JOIN ${r.identifier(i)} m ON m.id = g.${r.identifier("__id__")} WHERE ${r.join(v,r` AND `)}`,$=q(o,S).toArray(),_=[];for(const R of $){const T=le(R),x=T?Hn(T,t):void 0;T&&x&&_.push({creationTime:x.creationTime,distance:x.distance,doc:T})}return _.sort((R,T)=>R.distance-T.distance||T.creationTime-R.creationTime),_},bt=(o,i,t,a)=>{const f=[];for(const p of o)if(i.every(m=>m(a(p)))&&(f.push(p),typeof t=="number"&&f.length>=t))break;return f},jn=(o,i,t,a,f,p=()=>{})=>{const m=t.within!==void 0,v=Nn(o,i,t,f).map(S=>({distanceMeters:m?null:S.distance,document:S.doc}));return p(v.length),typeof a=="number"?v.slice(0,Math.max(0,Math.floor(a))):v},Dt=(o,i,t,a,f,p=()=>{})=>{const{geo:m}=t;if(!m)throw new E("INTERNAL","runGeoTerminalScored called without a staged geo query");const v=t.inMemoryFilters.length>0,S=jn(o,i,m,v?void 0:f,a,p);return v?bt(S,t.inMemoryFilters,f,$=>$.document):S},Kn=(o,i,t,a,f,p=()=>{})=>Dt(o,i,t,a,f,p).map(m=>m.document),On=(o,i,t,a,f,p,m=()=>{})=>{const v=[];for(const R of t.sqlConditions)v.push(r`${V(R.field)} ${r.raw(R.comparator)} ${ie(R.value)}`);a&&v.push(a);let S=r`SELECT id, _creationTime, ${r.identifier(N)} FROM ${r.identifier(i)}`;v.length>0&&(S=r`${S} WHERE ${r.join(v,r` AND `)}`),S=r`${S} ORDER BY ${f}`,typeof p=="number"&&t.inMemoryFilters.length===0&&(S=r`${S} LIMIT ${r.raw(String(Math.max(0,Math.floor(p))))}`);const $=q(o,S).toArray();m($.length);const _=[];for(const R of $){const T=le(R);if(T&&t.inMemoryFilters.every(x=>x(T))&&(_.push(T),typeof p=="number"&&_.length>=p))break}return _},oe={fieldRef:V,serialize:ie},kt=(o,i)=>{const t=i===void 0?void 0:o.shape[i];return t!==void 0&&gn(t)},yt=(o,i)=>i.some(t=>kt(o,t)),Et=(o,i,t)=>{if(kt(o,i))throw new E("BAD_REQUEST",`${t}: "${i}" is stored as an order-preserving key, which SQL cannot reduce or group — declare an aggregateIndex covering this (by, field, op) so the maintained companion answers it`)},Qn=o=>{let i=0;const t=[],a={fieldRef:V,relationExists:f=>{const{childWhere:p,negated:m,parentTable:v,relation:S}=f,$=`__rel_${String(i)}`,_=t.at(-1)??v;i+=1,o(S.table,H);const R=S.kind==="one"?S.field:S.references,T=S.kind==="one"?S.references:S.field,x=r`${ct($,T)} = ${ct(_,R)}`;t.push($);const W=te(p,a);t.pop();const F=W?r`${x} AND ${W}`:x,k=r`EXISTS (SELECT 1 FROM ${r.identifier(S.table)} AS ${r.identifier($)} WHERE ${F})`;return m?r`NOT ${k}`:k},serialize:ie};return a},Lt=o=>{const i=o.map(t=>r`${V(t.field)} ${r.raw(t.direction==="desc"?"DESC":"ASC")}`);return o.some(t=>t.field==="_id"||t.field==="id")||i.push(r`${V("id")} ASC`),r.join(i,r`, `)},zn={"<":"lt","<=":"lte","=":"eq",">":"gt",">=":"gte"},Jn=o=>{const i=o.order;return o.indexFields.length>0?o.indexFields.map(t=>({direction:i,field:t})):[{direction:i,field:"_creationTime"}]},Vn=(o,i,t,a)=>{const f=o.sqlConditions.map(p=>({[p.field]:{[zn[p.comparator]??"eq"]:p.value}}));if(t&&f.push(Ct(i,Ne(t))),a&&f.push(cn(i,Ne(a))),f.length!==0)return f.length===1?f[0]:{AND:f}},Yn=(o,i,t)=>{const a=[];for(const f of o){const p=le(f);if(p&&i.every(m=>m(p))&&(a.push(p),t!==void 0&&a.length>t))break}return a},Xn=(o,i,t,a,f,p=()=>{})=>{const m=Math.max(0,Math.floor(a.numItems)),v=Jn(t),S=typeof a.endCursor=="string",$=te(Vn(t,v,a.cursor,a.endCursor),oe),_=f&&$?r`${$} AND ${f}`:f??$;let R=r`SELECT id, _creationTime, ${r.identifier(N)} FROM ${r.identifier(i)}`;_&&(R=r`${R} WHERE ${_}`),R=r`${R} ORDER BY ${Lt(v)}`;const T=t.inMemoryFilters.length>0;!T&&!S&&(R=r`${R} LIMIT ${r.raw(String(m+1))}`);const x=q(o,R).toArray();p(x.length);const W=Yn(x,t.inMemoryFilters,T||S?void 0:m);if(S){const K=W.length>=2?W[Math.floor(W.length/2)-1]:void 0;return{continueCursor:a.endCursor??null,isDone:!0,page:W,splitCursor:K?je(K,v):null}}const F=W.length>m,k=F?W.slice(0,m):W,j=k.at(-1);return{continueCursor:F&&j?je(j,v):null,isDone:!F,page:k}};class Zn extends E{constructor(i="unique() found more than one matching document"){super("NOT_UNIQUE",i,{name:"NotUniqueError"})}}const er=/\s/u,tr=String.fromCodePoint(0),mt=(o,i,t)=>{if(!o.tables[i])throw new E("INTERNAL",`unknown table: ${i}`);return typeof t!="string"||t.length===0||er.test(t)||t.includes(tr)?null:t},nr=(o,i,t,a=()=>{},f=()=>{},p=()=>{})=>{const m=i.tables[t];if(!m)throw new E("INTERNAL",`unknown table: ${t}`);const v=de(m.softDeleteMode,void 0),S=v?te(v,oe):void 0,$={indexFields:[],indexName:void 0,inMemoryFilters:[],order:"asc",sqlConditions:[]};let _=0;const R=y=>{const{search:I}=$;if(!I)throw new E("INTERNAL","runSearchFetch called without a staged search");Jt(o,t,m);const b=$.inMemoryFilters.length>0,L=Dn(b?void 0:y),J=Yt(o)?qn(o,t,I,L,S):Un(o,t,I,L,S);return b?(_=J.length,bt(J,$.inMemoryFilters,y,ne=>ne.document)):(y===void 0&&vn(J),J)},T=y=>R(y).map(I=>I.document),x=y=>{const I=Mn(y);return bn(T(In(I)),I)},W=()=>{const y=$.indexFields.length>0?$.indexFields:["_creationTime"],I=$.order==="desc"?"DESC":"ASC";return r.join(y.map(b=>r`${V(b)} ${r.raw(I)}`),r`, `)},F=()=>{if($.search||$.geo||$.indexName===void 0){f(void 0);return}f(fn(t,$.indexName,$.indexFields,$.sqlConditions,ie))},k=y=>{F();let I=0;const b=(()=>{if($.search){const L=T(y);return I=_,L}return $.geo?Kn(o,t,$,S,y,L=>{I=L}):On(o,t,$,S,W(),y,L=>{I=L})})();return p(Math.max(I,b.length)),b},j=()=>{if(!$.search&&!$.geo)throw new E("INTERNAL",`ctx.db.query("${t}").collectWithScores() requires a staged .withSearchIndex(...) or .withGeoIndex(...)`);F();let y=0;const I=(()=>{if($.search){const b=R(void 0);return y=_,b}return Dt(o,t,$,S,void 0,b=>{y=b})})();return p(Math.max(y,I.length)),I},K={async*[Symbol.asyncIterator](){const y=[...$.inMemoryFilters];let I;$.inMemoryFilters=[];try{for(;;){const b=await K.paginate({cursor:I??null,numItems:Fn});for(const L of b.page)y.every(J=>J(L))&&(yield L);if(b.isDone||b.continueCursor===null)return;I=b.continueCursor}}finally{$.inMemoryFilters=y}},async collect(){return k(void 0)},async collectWithScores(){return j()},filter(y){return $.inMemoryFilters.push(y),K},async first(){return k($.inMemoryFilters.length>0?void 0:1)[0]??null},order(y){return $.order=y==="desc"?"desc":"asc",K},async paginate(y){let I=0;if(F(),$.search){const L=x(y);return p(L.page.length),L}if($.geo)throw new E("INTERNAL","pagination is not supported on geo queries; use .take(n) or .collect()");const b=Xn(o,t,$,y,S,L=>{I=L});return p(Math.max(I,b.page.length)),b},async take(y){return k(y)},async unique(){const y=k($.inMemoryFilters.length>0?void 0:2);if(y.length>1)throw new Zn(`unique() on table "${t}" matched ${String(y.length)} documents; expected at most one`);return y[0]??null},withGeoIndex(y,I){const b=(m.geoIndexes??[]).find(J=>J.name===y);if(!b)throw new E("INTERNAL",`unknown geo index "${y}" on table "${t}"`);a(t,y,"geo");const L={definition:b,indexName:y};if($.geo=L,I(Pn(L,t)),!L.near&&!L.within)throw new E("INTERNAL",`geo index "${y}" on table "${t}" requires a .near(point, radius) or .within(box) call`);return K},withIndex(y,I){const b=m.indexes.find(L=>L.name===y);if(!b)throw new E("INTERNAL",`unknown index "${y}" on table "${t}"`);return a(t,y,"index"),$.indexName=y,$.indexFields=b.fields,I&&I(Wn($)),K},withSearchIndex(y,I){const b=(m.searchIndexes??[]).find(J=>J.name===y);if(!b)throw new E("INTERNAL",`unknown search index "${y}" on table "${t}"`);a(t,y,"search");const L={definition:b,field:b.field,filters:[],hasQuery:!1,indexName:y,query:""};if($.search=L,I(An(L,t,Oe(b.language))),!L.hasQuery)throw new E("INTERNAL",`search index "${y}" on table "${t}" requires a .search(field, query) call`);return K}};return K},St=(o,i,t)=>{const a={...i};for(const[f,p]of At(o)){if(p.serverDefault){a[f]=p.serverDefault({auth:t});continue}a[f]===void 0&&(p.defaultFn?a[f]=p.defaultFn():"defaultValue"in p&&(a[f]=p.defaultValue))}return a},_t=(o,i,t,a)=>{const f=t;for(const[p,m]of At(o)){if(m.serverDefault){p in i&&(f[p]=m.serverDefault({auth:a}));continue}m.onUpdateFn&&!(p in i)&&(f[p]=m.onUpdateFn())}},Rt=(o,i)=>{for(const t of Object.keys(i))if(i[t]===void 0)throw new E("INTERNAL",`Cannot ${o} field '${t}' to undefined — use null to clear a nullable field, or omit the key to leave it unchanged.`)},rr=/unique constraint failed/i,or=o=>o instanceof Error&&rr.test(o.message),Ke=(o,i,t)=>{try{q(o,t)}catch(a){throw or(a)?new pe(`unique constraint violation on "${i}"`,"unique"):a}},xe=(o,i,t)=>{if(Ke(o,i,t),q(o,r`SELECT changes() AS changed`).one().changed===0)throw new pe(`optimistic concurrency conflict on "${i}" — the row changed during this mutation; refetch and retry`,"occ")},Tt=(o,i,t,a,f,p,m)=>{const v=[];for(let R=0;R<t.length+1;R+=1){const T=[];for(let k=0;k<R;k+=1)T.push(r`${r.identifier(t[k])} IS ${p[k]}`);const x=t[R],W=a[R];if(x!==void 0&&W!==void 0){const k=W.direction==="desc"?">":"<";T.push(r`${r.identifier(x)} ${r.raw(k)} ${p[R]}`)}else T.push(r`${r.identifier(ln)} < ${m}`);const[F]=T;v.push(T.length===1&&F!==void 0?F:r`(${r.join(T,r` AND `)})`)}const S=r.join(v,r` OR `),$=q(o,r`SELECT COUNT(*) AS c FROM ${r.identifier(i)} WHERE ${r.identifier("__partition__")} = ${f} AND (${S})`).one(),_=q(o,r`SELECT COUNT(*) AS c FROM ${r.identifier(i)} WHERE ${r.identifier("__partition__")} = ${f}`).one();return{before:$.c,total:_.c}},Lr=o=>{const{sql:i}=o,{schema:t}=o,a=o.broadcast??(()=>{}),f=(e,...n)=>{const s=t.tables[e]?.indexes;if(!s||s.length===0)return;const u=[];for(const h of n)h&&u.push(...un(s,h,ie));return u.length>0?u:void 0},{headroom:p}=o;let m=!1;const v=async e=>{const n=m;m=!0;try{return await e()}finally{m=n}},S=o.onRead??(()=>{}),$=o.onReadRange??(e=>{S(e.table,H)}),_=(e,n)=>{n!==void 0&&n!==H&&!m&&p?.recordRead(1),S(e,n)},R=o.onIndexUse??(()=>{}),T=o.onWrite??(()=>{}),x=e=>{m||p?.recordWrite(e)},W=async e=>{x(e.doc),await T(e)},{cache:F}=o,k=o.clock??(()=>Date.now()),j=o.idGenerator??(()=>crypto.randomUUID()),K=o.scheduler??jt,{globalDb:y}=o,I=o.auth??{identity:null,userId:null},b=o.cdc??!1,L=K,J=$n({scheduler:typeof L.list=="function"&&typeof L.get=="function"?L:void 0,storage:o.storage}),ne=(e,n,s,u)=>{b&&Vt(i,k(),e,n,s,u)},se=e=>t.tables[e]?.shardMode?.kind==="global",ze=(e,n)=>{if(se(e)){if(!y)throw new E("INTERNAL",`cross-backend ${n} for global table '${e}' requires a globalDb writer — pass one to createShardCtxDb({ globalDb })`);return y}return U},Me=e=>ze(e,"cascade"),Q=(e,n)=>{if(se(e)){if(!y)throw new E("INTERNAL",`${n} on global table '${e}' requires a globalDb writer — pass one to createShardCtxDb({ globalDb })`);return y}},Je=async(e,n,s,u,h)=>{h&&x(s);const d=await e.insert(n,s,u);return a({key:d,op:"insert",row:{...s,_id:d},table:n}),d},be=(e,n)=>ze(e,"relation load").findMany(e,n),Ve=(e,n)=>(se(e)&&_(e,H),be(e,n)),Ft=e=>!se(e.table),Ye=o.relationExistsPushDown??"auto",Xe=Ye!=="never",{maxRelationKeys:Ze}=o,ge=(e,n,s)=>ut(e,{fetcher:Ve,maxRelationKeys:Ze,relationBaseWhere:s,schema:t,tableName:n}),et=async(e,n,s,u)=>{const h=Q(e,"relation grouped count");if(h)return _(e,H),wn((B,A)=>h.count(B,A),e,n,s,u);const d=t.tables[e];if(!d)throw new E("INTERNAL",`unknown table: ${e}`);_(e,H);const c=de(d.softDeleteMode,void 0),l={[n]:{in:s}},w=z(z(l,u),c),C=await ge(w,e,void 0),g=te(C,oe),M=V(n);let D=r`SELECT ${M} AS __fk__, COUNT(*) AS count FROM ${r.identifier(e)}`;g&&(D=r`${D} WHERE ${g}`),D=r`${D} GROUP BY ${M}`;const P=q(i,D).toArray();return new Map(P.map(B=>[B.__fk__,B.count]))};let $e=0;const tt=new Set;for(const[e,n]of Object.entries(t.tables))for(const s of Object.values(n.triggerMap??{}))tt.add(`${e} ${s.timing} ${s.op}`);const Z=(e,n,s)=>tt.has(`${e} ${n} ${s}`),ee=async(e,n,s)=>{if($e+=1,$e>gt)throw $e-=1,new pe(`trigger recursion exceeded ${String(gt)} levels on "${s.table}" — check for a self-triggering write`,"trigger");try{await yn({ctx:Bt,event:s,op:n,schema:t,tableName:s.table,timing:e})}finally{$e-=1}},{ensureBackfilledForTable:ue,ensureBackfilledIndex:De,ensureRankBackfilled:ke,ensureRankBackfilledForTable:fe,syncAggregates:ye,syncCompanionsForInsert:nt,syncGeo:Ee,syncRanks:he,syncSearch:me}=Pt({broadcast:a,indexKeysFor:(e,n)=>f(e,n),invalidateCache:(e,n,s)=>F?.invalidate(e,n,f(e,s)),recordCdc:ne,schema:t,sql:i}),rt=(e,n,s)=>{const{shardMode:u}=n;if(u?.kind==="shardBy"&&!(u.field!==void 0&&(s.partitionBy??[]).includes(u.field)))throw Object.assign(new Error(`rank index "${s.name}" on "${e}" partitions across shards (shard key "${u.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})},ot=e=>Object.entries(t.tables).filter(([,n])=>n.shardMode?.kind!=="global").map(([n])=>n).filter(n=>e===void 0||n===e),re=(e,n)=>{const s=ot(n);for(let u=0;u<s.length;u+=we){const h=s.slice(u,u+we).map(g=>r`SELECT ${r.raw(`'${g.replaceAll("'","''")}'`)} AS __t__, id, _creationTime, ${r.identifier(N)} FROM ${r.identifier(g)} WHERE id = ${e}`),[d]=q(i,r`${He(h)} LIMIT 1`).toArray();if(!d)continue;const c=d.__t__,l=le(d);if(typeof c!="string"||!l)return;const w=d[N];return{docJson:typeof w=="string"?w:ce(w??{}),row:l,tableName:c}}},Wt=(e,n)=>{const s=[...new Set(e)],u=new Map;if(s.length===0)return u;const h=ot(n);for(let d=0;d<h.length;d+=we){const c=h.slice(d,d+we),l=Math.floor(we/c.length),w=Zt(r`${r.identifier("id")}`,s,!1,l),C=c.map(g=>r`SELECT ${r.raw(`'${g.replaceAll("'","''")}'`)} AS __t__, id FROM ${r.identifier(g)} WHERE ${w}`);for(const g of q(i,He(C))){const{id:M,__t__:D}=g;typeof D=="string"&&typeof M=="string"&&u.set(M,D)}}return u},it={assertRankPartitionLocal:rt,ensureRankBackfilled:ke,onRead:_,rowToDocument:le,schema:t,sql:i},U={system:J,async aggregate(e,n){const s=Q(e,"aggregate");if(s)return _(e,H),s.aggregate(e,n);const u=t.tables[e];if(!u)throw new E("INTERNAL",`unknown table: ${e}`);if(ve(n.op),n.op==="count")return U.count(e,{baseWhere:n.baseWhere,relationBaseWhere:n.relationBaseWhere,restrictsCounts:n.restrictsCounts,where:n.where});if(!n.field)throw new E("INTERNAL",`aggregate(${e}, { op: "${n.op}" }): "field" is required for non-count reducers`);_(e,H);const h=de(u.softDeleteMode,void 0),d=z(z(n.baseWhere,n.where),h),c=await ge(d,e,n.relationBaseWhere),l=c!==d;if(u.aggregateIndexes&&!n.baseWhere&&!l&&(!h||yt(u,[n.field]))){const B=zt(u.aggregateIndexes,n.op,n.field,n.where);if(B){De(e,B.index);const A=Fe(B.index.by??[],B.key),O=Le(e,B.index.name),Y=q(i,r`SELECT ${Ie} AS value, ${qe} AS count FROM ${r.identifier(O)} WHERE ${Ce} = ${A}`).toArray()[0];return We(n.op,Y)}}Et(u,n.field,`aggregate(${e}, { op: "${n.op}", field: "${n.field}" })`);const w=te(c,oe),C=ve(n.op),g=V(n.field);let M=r`SELECT ${r.raw(C)}(${g}) AS value FROM ${r.identifier(e)}`;w&&(M=r`${M} WHERE ${w}`);const P=q(i,M).toArray()[0]?.value;return P??null},asId(e,n){const s=mt(t,e,n);if(s===null)throw new E("BAD_REQUEST",`asId("${e}", …): "${n}" is not a valid id for table "${e}"`,{status:400});return s},async count(e,n){const s=Q(e,"count");if(s)return _(e,H),s.count(e,n);const u=t.tables[e];if(!u)throw new E("INTERNAL",`unknown table: ${e}`);const h=Kt(n);if(h.restrictsCounts)throw new Be(e);_(e,H);const d=de(u.softDeleteMode,void 0),c=z(z(h.baseWhere,h.where),d),l=await ge(c,e,h.relationBaseWhere),w=l!==c;if(u.aggregateIndexes&&!h.baseWhere&&!w&&!d){const D=Qt(u.aggregateIndexes,h.where);if(D){De(e,D.index);const P=Fe(D.index.by??[],D.key),B=Le(e,D.index.name),A=q(i,r`SELECT ${Ie} AS value FROM ${r.identifier(B)} WHERE ${Ce} = ${P}`).toArray();return A[0]===void 0?0:A[0].value??0}}const C=te(l,oe);let g=r`SELECT COUNT(*) AS count FROM ${r.identifier(e)}`;return C&&(g=r`${g} WHERE ${C}`),q(i,g).one().count},async delete(e,n,s){const u=re(e,n);if(!u){const g=n===void 0?y:void 0;g&&(x(void 0),await g.delete(e,void 0,s));return}const{docJson:h,row:d,tableName:c}=u,l=t.tables[c],w=s?.hard===!0,C=!w&&l?.softDeleteMode?l.softDeleteMode.field:void 0;if(!(C&&d[C]!==null&&d[C]!==void 0)){if(Z(c,"before","delete")&&await ee("before","delete",{id:e,op:"delete",previous:d,table:c}),await hn({deletedId:e,deletedReference:g=>d[g],findHolders:async(g,M,D)=>(await Me(g).findMany(g,{includeDeleted:w,where:{[M]:D}})).page,onCascade:(g,M)=>Me(g).delete(M,void 0,s),onRestrict:g=>{throw new pe(g,"restrict")},onSetNull:(g,M,D)=>Me(g).patch(M,{[D]:null}),schema:t,tableName:c}),ue(c),fe(c),C){const g={...d,[C]:k(),_id:e};xe(i,c,r`UPDATE ${r.identifier(c)} SET ${r.identifier(N)} = ${ce(g)} WHERE id = ${e} AND ${r.identifier(N)} = ${h}`),me(c,e,g,d),Ee(c,e,void 0),ye(c,d,g),he(c,e,d,void 0),F?.invalidate(c,e,f(c,d,g)),ne(c,e,"update",g),a({indexKeys:f(c,d,g),key:e,op:"update",row:g,table:c}),Z(c,"after","delete")&&await ee("after","delete",{id:e,op:"delete",previous:d,table:c}),await W({id:e,op:"delete",table:c});return}xe(i,c,r`DELETE FROM ${r.identifier(c)} WHERE id = ${e} AND ${r.identifier(N)} = ${h}`),me(c,e,void 0),Ee(c,e,void 0),ye(c,d,void 0),he(c,e,d,void 0),F?.invalidate(c,e,f(c,d)),ne(c,e,"delete"),a({indexKeys:f(c,d),key:e,op:"delete",table:c}),Z(c,"after","delete")&&await ee("after","delete",{id:e,op:"delete",previous:d,table:c}),await W({id:e,op:"delete",table:c})}},async deleteAll(e,n){if(!t.tables[e])throw new E("INTERNAL",`unknown table: ${e}`);const s=Math.max(1,n?.chunkSize??xt),u=n?.hard===void 0?void 0:{hard:n.hard},h=se(e)?void 0:e;let d=0;return await v(async()=>{for(;;){const l=(await U.findMany(e,{limit:s})).page.map(w=>String(w._id));if(l.length===0)break;for(const w of l)await U.delete(w,h,u),d+=1;if(l.length<s)break}}),{deleted:d}},async deleteMany(e,n,s){ae(e.length,n?.limit,"deleteMany");for(const u of e)await U.delete(u,s);return{deleted:e.length}},async deleteWhere(e,n,s){const d=(await(Q(e,"deleteWhere")??U).findMany(e,{where:n})).page.map(c=>String(c._id));if(ae(d.length,s?.limit,"deleteWhere"),U.deleteMany===void 0)throw new E("INTERNAL",`ctx.db.${e}.deleteMany is unavailable: this writer has no batch delete`);return U.deleteMany(d,s)},async findFirst(e,n={}){return(await U.findMany(e,{...n,limit:1})).page[0]??null},async findFirstOrThrow(e,n={}){const s=await U.findFirst(e,n);if(s===null)throw new on(`findFirstOrThrow: no "${e}" document matched`);return s},async findMany(e,n={}){const s=Q(e,"findMany");if(s)return _(e,H),s.findMany(e,n);const u=t.tables[e];if(!u)throw new E("INTERNAL",`unknown table: ${e}`);const h=!n.where&&!n.baseWhere;h?_(e,H):_(e);const d=sn(n.orderBy),c=n.cursor?Ct(d,Ne(n.cursor)):void 0;let l=z(n.baseWhere,n.where);l=z(l,de(u.softDeleteMode,n.includeDeleted)),l=await ut(l,{canPushExists:Xe?Ft:void 0,existsPushMode:Ye==="always"?"always":"auto",fetcher:Ve,maxRelationKeys:Ze,relationBaseWhere:n.relationBaseWhere,schema:t,tableName:e}),c&&(l=l?{AND:[l,c]}:c);const w=Xe?Qn(_):oe,C=te(l,w);let g=r`SELECT id, _creationTime, ${r.identifier(N)} FROM ${r.identifier(e)}`;C&&(g=r`${g} WHERE ${C}`),g=r`${g} ORDER BY ${Lt(d)}`;const M=typeof n.limit=="number"?Math.max(0,Math.floor(n.limit)):void 0;M!==void 0&&(g=r`${g} LIMIT ${r.raw(String(M+1))}`);const D=q(i,g).toArray();h&&!m&&p?.recordRead(D.length);const P=[];for(const Y of D){const G=le(Y);G&&(P.push(G),!h&&typeof G._id=="string"&&_(e,G._id))}if(M===void 0)return n.with&&await ft({groupedCounter:et,fetcher:be,parents:P,...ht(n),schema:t,tableName:e,with:n.with}),{continueCursor:null,isDone:!0,page:at(P,n.select,n.with)};const B=P.length>M,A=B?P.slice(0,M):P,O=A.at(-1);return n.with&&await ft({fetcher:be,groupedCounter:et,parents:A,...ht(n),schema:t,tableName:e,with:n.with}),{continueCursor:B&&O?je(O,d):null,isDone:!B,page:at(A,n.select,n.with)}},async get(e,n){const s=re(e,n);if(!s){const u=n===void 0?y:void 0;return u?u.get(e):null}return _(s.tableName,e),s.row},async lookupById(e,n){const s=re(e,n);return s?(_(s.tableName,e),{row:s.row,tableName:s.tableName}):null},async groupBy(e,n){const s=Q(e,"groupBy");if(s)return _(e,H),s.groupBy(e,n);const u=t.tables[e];if(!u)throw new E("INTERNAL",`unknown table: ${e}`);_(e,H);const h=n.agg??{op:"count"};if(ve(h.op),h.op!=="count"&&!h.field)throw new E("INTERNAL",`groupBy(${e}, { agg: { op: "${h.op}" } }): "field" is required for non-count reducers`);const d=de(u.softDeleteMode,void 0),c=z(z(n.baseWhere,n.where),d),l=await ge(c,e,n.relationBaseWhere),w=l!==c,C=[...n.by,h.field];if(u.aggregateIndexes&&!n.baseWhere&&!w&&(!d||yt(u,C))){const A=Ot(u.aggregateIndexes,h.op,h.field,n.by,n.where),O=A===void 0?0:Object.keys(A.partial).length,Y=A?.index.by?.length??0;if(A&&(O===0||O===Y)){De(e,A.index);const G=Le(e,A.index.name),Se=Object.keys(A.partial),_e=[];if(Se.length===(A.index.by??[]).length&&Se.length>0){const Re=Fe(A.index.by??[],A.partial),Te=q(i,r`SELECT ${Ie} AS value, ${qe} AS count FROM ${r.identifier(G)} WHERE ${Ce} = ${Re}`).toArray();return Te.length>0&&_e.push({key:{...A.partial},value:We(h.op,Te[0])}),_e}const qt=q(i,r`SELECT ${Ce} AS key, ${Ie} AS value, ${qe} AS count FROM ${r.identifier(G)}`).toArray();for(const Re of qt){const Te=Nt(JSON.parse(Re.key));_e.push({key:Te,value:We(h.op,Re)})}return _e}}for(const A of C){if(A===void 0)continue;const O=A===h.field?`groupBy(${e}, { agg: { op: "${h.op}", field: "${A}" } })`:`groupBy(${e}, { by: [..."${A}"] })`;Et(u,A,O)}const g=te(l,oe),M=n.by.map(A=>r`${V(A)} AS ${r.identifier(A)}`);if(h.op==="count")M.push(r`COUNT(*) AS value`);else{const{field:A}=h;if(A===void 0)throw new E("INTERNAL",`groupBy(${e}, { agg: { op: "${h.op}" } }): "field" is required for non-count reducers`);M.push(r`${r.raw(ve(h.op))}(${V(A)}) AS value`)}let D=r`SELECT ${r.join(M,r`, `)} FROM ${r.identifier(e)}`;g&&(D=r`${D} WHERE ${g}`),D=r`${D} GROUP BY ${r.join(n.by.map(A=>V(A)),r`, `)}`;const P=q(i,D).toArray(),B=[];for(const A of P){const O={};for(const G of n.by)O[G]=A[G]??null;const{value:Y}=A;B.push({key:O,value:Y==null?null:Number(Y)})}return B},async insert(e,n,s){const u=Q(e,"insert");if(u)return Je(u,e,n,s,!0);const h=t.tables[e];if(!h)throw new E("INTERNAL",`unknown table: ${e}`);const d=St(h,n,I);Pe(h,d);let c;s?.clientId!==void 0?(Ln(s.clientId),c=s.clientId):s?.allowExplicitId&&typeof d._id=="string"?c=d._id:c=j();const l=s?.allowExplicitId&&typeof d._creationTime=="number"?d._creationTime:k(),w={...d,_creationTime:l,_id:c};return Z(e,"before","insert")&&await ee("before","insert",{doc:{...w},id:c,op:"insert",table:e}),ue(e),fe(e),Ke(i,e,r`INSERT INTO ${r.identifier(e)} (id, _creationTime, ${r.identifier(N)}) VALUES (${c}, ${l}, ${ce(w)})`),nt(e,c,w),Z(e,"after","insert")&&await ee("after","insert",{doc:w,id:c,op:"insert",table:e}),await W({doc:w,id:c,op:"insert",table:e}),c},async insertManyUnsafe(e,n,s){if(ae(n.length,s?.limit,"insertManyUnsafe"),n.length===0)return[];const u=Q(e,"insert");if(u){const c=[];for(const l of n)x(l);for(const l of n){const w=await u.insert(e,l,{allowExplicitId:s?.allowExplicitId});a({key:w,op:"insert",row:{...l,_id:w},table:e}),c.push(w)}return c}const h=t.tables[e];if(!h)throw new E("INTERNAL",`unknown table: ${e}`);ue(e),fe(e);const d=n.map(c=>{const l=St(h,c,I),w=s?.allowExplicitId===!0&&typeof l._id=="string"?l._id:j(),C=s?.allowExplicitId===!0&&typeof l._creationTime=="number"?l._creationTime:k();return{creationTime:C,document:{...l,_creationTime:C,_id:w},id:w}});for(const c of d)x(c.document);for(let c=0;c<d.length;c+=$t){const l=r.join(d.slice(c,c+$t).map(w=>r`(${w.id}, ${w.creationTime}, ${ce(w.document)})`),r`, `);Ke(i,e,r`INSERT INTO ${r.identifier(e)} (id, _creationTime, ${r.identifier(N)}) VALUES ${l}`)}for(const{document:c,id:l}of d)nt(e,l,c),await T({doc:c,id:l,op:"insert",table:e});return d.map(c=>c.id)},async insertMany(e,n,s){ae(n.length,s?.limit,"insertMany");const u=s?.skipDuplicates===!0,h=[],d=Q(e,"insert");if(d)for(const l of n)x(l);const c=async l=>d?Je(d,e,l,void 0,!1):U.insert(e,l);for(const l of n)try{h.push(await c(l))}catch(w){if(u&&w instanceof pe&&w.kind==="unique")h.push(null);else throw w}return h},normalizeId(e,n){return mt(t,e,n)},async patch(e,n,s){const u=re(e,s);if(!u){const C=s===void 0?y:void 0;if(C){x(n),await C.patch(e,n);return}throw new E("INTERNAL",`document not found: ${e}`)}const{docJson:h,row:d,tableName:c}=u,l=t.tables[c];if(!l)throw new E("INTERNAL",`unknown table: ${c}`);_(c,e),Rt("patch",n);const w={...d,...n,_id:e};_t(l,n,w,I),Pe(l,w,!0),Z(c,"before","update")&&await ee("before","update",{doc:{...w},id:e,op:"update",previous:d,table:c}),ue(c),fe(c),xe(i,c,r`UPDATE ${r.identifier(c)} SET ${r.identifier(N)} = ${ce(w)} WHERE id = ${e} AND ${r.identifier(N)} = ${h}`),me(c,e,w,d),Ee(c,e,w),ye(c,d,w),he(c,e,d,w),F?.invalidate(c,e,f(c,d,w)),ne(c,e,"update",w),a({indexKeys:f(c,d,w),key:e,op:"update",row:w,table:c}),Z(c,"after","update")&&await ee("after","update",{doc:w,id:e,op:"update",previous:d,table:c}),await W({doc:w,id:e,op:"update",table:c})},async patchMany(e,n,s){ae(e.length,n?.limit,"patchMany");for(const u of e)await U.patch(u.id,u.patch,s);return{patched:e.length}},async patchWhere(e,n,s){const d=(await(Q(e,"patchWhere")??U).findMany(e,{where:n.where})).page.map(c=>({id:String(c._id),patch:n.patch}));if(ae(d.length,s?.limit,"patchWhere"),U.patchMany===void 0)throw new E("INTERNAL",`ctx.db.${e}.patchMany is unavailable: this writer has no batch patch`);return await U.patchMany(d,s),{patched:d.length}},query(e){const n=Q(e,"query");return n?(_(e,H),n.query(e)):nr(i,t,e,R,s=>{s?$(s):_(e,H)},s=>{m||p?.recordRead(s)})},async rank(e,n,s){const u=Q(e,"rank");if(u)return _(e,H),u.rank(e,n,s);R(e,n,"rank");const h=t.tables[e];if(!h)throw new E("INTERNAL",`unknown table: ${e}`);const d=h.rankIndexes?.find(G=>G.name===n);if(!d)throw new E("INTERNAL",`unknown rankIndex "${n}" on table "${e}"`);if(rt(e,h,d),s.restrictsCounts)throw new Be(e);_(e,H),ke(e,d);const c=typeof s.row=="string"?s.row:s.row._id;if(!c)return null;const l=dt(e,d.name),w=d.sortBy.map((G,Se)=>lt(Se)),C=w.map(G=>En(G)).join(", "),g=q(i,r`SELECT ${r.identifier("__partition__")}, ${r.raw(C)} FROM ${r.identifier(l)} WHERE ${r.identifier("__id__")} = ${c}`).toArray(),[M]=g;if(M===void 0)return null;let D=M.__partition__;const P=z(s.baseWhere,s.where);Ue(P,t,e,"rank");const B=an(d,P);if(B){const G=dn(d.partitionBy??[],B);if(G!==D)return null;D=G}const A=w.map(G=>M[G]),{before:O,total:Y}=Tt(i,l,w,d.sortBy,D,A,c);return{position:O+1,total:Y}},async rankBefore(e,n,s){if(se(e))throw new E("INTERNAL",`rankBefore is not supported on the global (.global()) table '${e}' — cross-shard rank cursors apply only to sharded tables`);const u=t.tables[e];if(!u)throw new E("INTERNAL",`unknown table: ${e}`);const h=u.rankIndexes?.find(w=>w.name===n);if(!h)throw new E("INTERNAL",`unknown rankIndex "${n}" on table "${e}"`);if(s.restrictsCounts)throw new Be(e);_(e,H),ke(e,h);const d=dt(e,h.name),c=h.sortBy.map((w,C)=>lt(C)),l=h.sortBy.map((w,C)=>ie(s.sortValues[C]??null));return Tt(i,d,c,h.sortBy,s.partitionKey,l,s.rowId)},async rankPage(e,n,s={}){Ue(z(s.baseWhere,s.where),t,e,"rankPage");const u=Q(e,"rankPage");if(u)return _(e,H),u.rankPage(e,n,s);R(e,n,"rank");const{continueCursor:h,hasMore:d,rows:c}=st(it,e,n,s);return{continueCursor:h,isDone:!d,page:c.map(l=>l.doc)}},async rankPageRows(e,n,s={}){Ue(z(s.baseWhere,s.where),t,e,"rankPage"),R(e,n,"rank");const{directions:u,hasMore:h,rows:d}=st(it,e,n,s);return{directions:u,hasMore:h,rows:d}},async restore(e,n){const s=re(e,n);if(!s){const d=n===void 0?y:void 0;if(d?.restore){await d.restore(e);return}throw new E("INTERNAL",`document not found: ${e}`)}const u=t.tables[s.tableName]?.softDeleteMode?.field;if(!u)throw new E("INTERNAL",`ctx.db.restore: table "${s.tableName}" is not a .softDelete() table`);const h=s.row[u]!==null&&s.row[u]!==void 0;await U.patch(e,{[u]:null},n),h&&he(s.tableName,e,void 0,s.row)},async replace(e,n,s,u){const h=re(e,s);if(!h){const M=s===void 0?y:void 0;if(M){x(n),await M.replace(e,n,void 0,u);return}throw new E("INTERNAL",`document not found: ${e}`)}const{docJson:d,row:c,tableName:l}=h,w=t.tables[l];if(!w)throw new E("INTERNAL",`unknown table: ${l}`);Rt("replace",n);const C=u?.allowExplicitId&&typeof n._creationTime=="number"?n._creationTime:k(),g={...n,_creationTime:C,_id:e};_t(w,n,g,I),Pe(w,g),Z(l,"before","update")&&await ee("before","update",{doc:{...g},id:e,op:"update",previous:c,table:l}),ue(l),fe(l),xe(i,l,r`UPDATE ${r.identifier(l)} SET _creationTime = ${C}, ${r.identifier(N)} = ${ce(g)} WHERE id = ${e} AND ${r.identifier(N)} = ${d}`),me(l,e,g,c),Ee(l,e,g),ye(l,c,g),he(l,e,c,g),F?.invalidate(l,e,f(l,c,g)),ne(l,e,"update",g),a({indexKeys:f(l,c,g),key:e,op:"update",row:g,table:l}),Z(l,"after","update")&&await ee("after","update",{doc:g,id:e,op:"update",previous:c,table:l}),await W({doc:g,id:e,op:"update",table:l})},async wipeShard(e){const n=new Set(e?.exclude),s=e?.tables,u=Object.entries(t.tables).filter(([l,w])=>n.has(l)||s!==void 0&&!s.includes(l)?!1:w.shardMode?.kind!=="global").map(([l])=>l);if(s!==void 0){for(const l of s)if(!t.tables[l])throw new E("INTERNAL",`wipeShard: unknown table: ${l}`)}const h={};let d=0;const{deleteAll:c}=U;if(c===void 0)throw new E("INTERNAL","wipeShard: this writer has no deleteAll");for(const l of u){const w=await c(l,{...e?.chunkSize===void 0?{}:{chunkSize:e.chunkSize},hard:!0});h[l]=w.deleted,d+=w.deleted}return{deleted:d,tables:h}}},Bt={db:U,scheduler:K};return o.enforceRls===!0?pn(U,t,(e,n)=>re(e,n)?.tableName,(e,n)=>Wt(e,n)):U};export{Gr as CDC_LOG_TABLE,Vr as CLIENT_WATERMARK_TABLE,to as GLOBAL_SHAPE_SNAPSHOT_TABLE,ao as IDEMPOTENCY_TABLE,Zn as NotUniqueError,go as SEARCH_STATE_TABLE,Yr as advanceClientWatermark,Hr as applyCdcChanges,Ln as assertValidClientId,Br as backfillAggregateIndexes,qr as backfillRankIndexes,Ur as backfillSearchIndexes,Nr as bumpCdcEpoch,Lr as createShardCtxDb,no as deleteGlobalShapeSnapshot,ro as deleteGlobalShapeSnapshotsForConnection,Xr as migrateClientWatermark,oo as migrateGlobalShapeSnapshot,jr as minCdcSeq,mt as normalizeIdStructurally,Kr as readCdcChanges,Or as readCdcCursor,Qr as readCdcEpoch,Zr as readClientWatermark,io as readGlobalShapeSnapshot,lo as readIdempotent,wo as runShardMigrations,yo as selectShapeMemberIds,Eo as selectShapeRows,zr as trimCdcChanges,uo as trimIdempotent,so as writeGlobalShapeSnapshot,fo as writeIdempotent};
|
|
@@ -1,5 +0,0 @@
|
|
|
1
|
-
import{a as L,S,y as N}from"./ctx-db-companions-lTt-rvKG.mjs";import{sql as e}from"drizzle-orm";import{aggregateTableName as u}from"./aggregateTableName-Cy5e03oz.mjs";import{backfillSearchIndexesForTable as h}from"./backfillAggregateIndexes-DVQ2sVuV.mjs";import{migrateCdcLog as p,migrateCdcMeta as x}from"./CDC_LOG_TABLE-B58N8NQO.mjs";import{migrateClientWatermark as R}from"./CLIENT_WATERMARK_TABLE-BoS1HEqz.mjs";import{migrateGlobalShapeSnapshot as C}from"./GLOBAL_SHAPE_SNAPSHOT_TABLE-NWaL77m5.mjs";import{migrateIdempotency as O}from"./IDEMPOTENCY_TABLE-DKVe2Ohf.mjs";import{migrateSearchState as U}from"./SEARCH_STATE_TABLE-Dju8ebbU.mjs";import{migrateShapePokeCursor as $}from"./SHAPE_POKE_CURSOR_TABLE-Dh4HfSdC.mjs";import{runDrizzle as a}from"./runDrizzle-it6rL9bR.mjs";import{D as b,e as T,d,t as l,i as X,g as G,a as D,b as B,A as E}from"./do-sql-Dk_DJxn4.mjs";import{migrateDurableStreams as k}from"./appendStreamChunk-CH4e4nJn.mjs";import{rankTableName as F,sortColumnName as M}from"./RANK_TIEBREAK-ci3MaM65.mjs";import{recordSchemaVersion as Y}from"./SCHEMA_HISTORY_MAX_VERSIONS-DsycDXWm.mjs";const P=(r,o,t)=>{for(const i of t.indexes){const n=`${o}_${i.name}`,s=e.join(i.fields.map(m=>T(m)),e`, `);a(r,d(n,o,s,i.unique??!1))}for(const[i,n]of l(t)){if(!n.unique)continue;const s=`${o}_unique_${i}`;a(r,d(s,o,T(i),!0))}},j=(r,o,t)=>{if(!(!t.searchIndexes||t.searchIndexes.length===0||!X(r))){for(const i of t.searchIndexes){const n=L(o,i.name);a(r,e`CREATE VIRTUAL TABLE IF NOT EXISTS ${e.identifier(n)} USING fts5(${e.identifier(S)}, ${e.identifier(N)} UNINDEXED)`),a(r,e`CREATE VIRTUAL TABLE IF NOT EXISTS ${e.identifier(`${n}__vocab`)} USING fts5vocab(${e.identifier(n)}, ${e.raw("instance")})`)}h(r,o,t)}},y=(r,o,t)=>{if(t.geoIndexes)for(const i of t.geoIndexes){const n=G(o,i.name);a(r,e`CREATE TABLE IF NOT EXISTS ${e.identifier(n)} (${e.identifier("__id__")} TEXT PRIMARY KEY, ${e.identifier("__geohash__")} TEXT NOT NULL, ${e.identifier("__lat__")} REAL NOT NULL, ${e.identifier("__lng__")} REAL NOT NULL)`);const s=`${o}__geo_${i.name}__btree`;a(r,d(s,n,e`${e.identifier("__geohash__")} ASC, ${e.identifier("__id__")} ASC`,!1))}},K=(r,o,t)=>{if(t.aggregateIndexes)for(const i of t.aggregateIndexes){const n=u(o,i.name);a(r,e`CREATE TABLE IF NOT EXISTS ${e.identifier(n)} (${D} TEXT PRIMARY KEY, ${B} REAL, ${E} INTEGER NOT NULL DEFAULT 0)`),a(r,e`PRAGMA table_info(${e.identifier(n)})`).toArray().some(m=>m.name==="__count__")||a(r,e`ALTER TABLE ${e.identifier(n)} ADD COLUMN ${E} INTEGER NOT NULL DEFAULT 0`)}},v=(r,o,t)=>{if(t.rankIndexes)for(const i of t.rankIndexes){const n=F(o,i.name),s=i.sortBy.map((f,c)=>M(c)),m=s.map(f=>e`${e.identifier(f)} BLOB`),A=m.length>0?e`, ${e.join(m,e`, `)}`:e``;a(r,e`CREATE TABLE IF NOT EXISTS ${e.identifier(n)} (${e.identifier("__id__")} TEXT PRIMARY KEY, ${e.identifier("__partition__")} TEXT NOT NULL${A})`);const _=[e`${e.identifier("__partition__")} ASC`];for(const[f,c]of s.entries()){const I=i.sortBy[f]?.direction;_.push(e`${e.identifier(c)} ${e.raw(I==="desc"?"DESC":"ASC")}`)}_.push(e`${e.identifier("__id__")} ASC`);const g=`${o}__rank_${i.name}__btree`;a(r,d(g,n,e.join(_,e`, `),!1))}},ae=(r,o,t={})=>{t.schemaSnapshot!==void 0&&Y(r,t.schemaSnapshot.hash,t.schemaSnapshot.json),U(r);for(const[i,n]of Object.entries(o.tables))n.shardMode?.kind!=="global"&&(a(r,e`CREATE TABLE IF NOT EXISTS ${e.identifier(i)} (
|
|
2
|
-
id TEXT PRIMARY KEY,
|
|
3
|
-
_creationTime REAL NOT NULL,
|
|
4
|
-
${e.identifier(b)} TEXT NOT NULL
|
|
5
|
-
)`),P(r,i,n),j(r,i,n),y(r,i,n),K(r,i,n),v(r,i,n));t.cdc&&(p(r),x(r),R(r),$(r)),O(r),C(r),k(r)};export{ae as runShardMigrations};
|