@lunora/shard-engine 1.0.0-alpha.23 → 1.0.0-alpha.25
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 +66 -1
- package/dist/index.d.ts +66 -1
- package/dist/index.mjs +1 -1
- package/dist/packem_shared/{ADMIN_FUNCTIONS-BFYAiahG.mjs → ADMIN_FUNCTIONS-B5HZoizX.mjs} +1 -1
- package/dist/packem_shared/{AGG_COUNT-DjIzJ7nc.mjs → AGG_COUNT-DmQFpsDX.mjs} +1 -1
- package/dist/packem_shared/{AUDIT_LOG_TABLE-0FKs74RO.mjs → AUDIT_LOG_TABLE-Bl2mYtAQ.mjs} +1 -1
- package/dist/packem_shared/{CDC_LOG_TABLE-CIfexI1y.mjs → CDC_LOG_TABLE-DH-KHUfU.mjs} +1 -1
- package/dist/packem_shared/{CLIENT_WATERMARK_TABLE-BogWgD2Q.mjs → CLIENT_WATERMARK_TABLE-LrKfdxyt.mjs} +1 -1
- package/dist/packem_shared/{DATA_MIGRATION_STATE_TABLE-BcmXmY5q.mjs → DATA_MIGRATION_STATE_TABLE-DIQTu___.mjs} +1 -1
- package/dist/packem_shared/DurableStreamRunner-C-OSu02s.mjs +1 -0
- package/dist/packem_shared/{GLOBAL_SHAPE_SNAPSHOT_TABLE-T5smo6RP.mjs → GLOBAL_SHAPE_SNAPSHOT_TABLE-B2LKe4KU.mjs} +1 -1
- package/dist/packem_shared/{IDEMPOTENCY_TABLE-DPFwgQbE.mjs → IDEMPOTENCY_TABLE-tQ5mnqvw.mjs} +1 -1
- package/dist/packem_shared/{MAIL_RETENTION-Cp9LWzM4.mjs → MAIL_RETENTION-CzZuX9bd.mjs} +1 -1
- package/dist/packem_shared/NotUniqueError-BeTJrgRe.mjs +1 -0
- package/dist/packem_shared/{QUEUE_TABLE-C1mp0Du0.mjs → QUEUE_TABLE-BX0nopuT.mjs} +1 -1
- package/dist/packem_shared/{SCHEMA_HISTORY_MAX_VERSIONS-CGlXjXRT.mjs → SCHEMA_HISTORY_MAX_VERSIONS-CEK7b_7v.mjs} +1 -1
- package/dist/packem_shared/{SEARCH_STATE_TABLE-MDlr30EJ.mjs → SEARCH_STATE_TABLE-DRk_SB72.mjs} +1 -1
- package/dist/packem_shared/appendStreamChunk-ksZYy1hZ.mjs +19 -0
- package/dist/packem_shared/{backfillAggregateIndexes-Czk8MQ3M.mjs → backfillAggregateIndexes-BEMWTEq1.mjs} +1 -1
- package/dist/packem_shared/buildReprojectionMigration-YQSJX2cC.mjs +1 -0
- package/dist/packem_shared/compileWhereSql-B3hq_v98.mjs +1 -0
- package/dist/packem_shared/{computeRankPage-CPVNOrM5.mjs → computeRankPage-D1ygctSC.mjs} +1 -1
- package/dist/packem_shared/{createCompanionSync-BPQ1EJ06.mjs → createCompanionSync-D7DEvUvt.mjs} +1 -1
- package/dist/packem_shared/{ctx-db-companions-D2ZMFBrP.mjs → ctx-db-companions-c12P7dbv.mjs} +1 -1
- package/dist/packem_shared/{defineEngineContractSuite-eFffNiTW.mjs → defineEngineContractSuite-CYR4BaIk.mjs} +1 -1
- package/dist/packem_shared/{do-sql-Cg_QiQYA.mjs → do-sql-C7qrlm6-.mjs} +1 -1
- package/dist/packem_shared/{isSoftDeleted-ZosHVk5V.mjs → isSoftDeleted-Tr2to2aw.mjs} +1 -1
- package/dist/packem_shared/{materializeExternalRows-CUrDeD82.mjs → materializeExternalRows-D53xwGfY.mjs} +1 -1
- package/dist/packem_shared/param-CYxL68V-.mjs +1 -0
- package/dist/packem_shared/runDrizzle-C3n5gJsk.mjs +1 -0
- package/dist/packem_shared/runShardMigrations-BAtfEXbB.mjs +5 -0
- package/dist/packem_shared/{selectExpiredIds-DLKts8V0.mjs → selectExpiredIds-C3Vv1gPm.mjs} +1 -1
- package/dist/packem_shared/{selectShapeMemberIds-EPo0xxs_.mjs → selectShapeMemberIds-WzxOG62k.mjs} +1 -1
- package/package.json +3 -3
- package/dist/packem_shared/NotUniqueError-DJf3W9gG.mjs +0 -1
- package/dist/packem_shared/buildReprojectionMigration-DMMWPqvy.mjs +0 -1
- package/dist/packem_shared/compileWhereSql-DxD5mzDy.mjs +0 -1
- package/dist/packem_shared/param-C68MV3DD.mjs +0 -1
- package/dist/packem_shared/runDrizzle-CgYGDEeB.mjs +0 -1
- package/dist/packem_shared/runShardMigrations-CtlcSZ3r.mjs +0 -5
|
@@ -1 +1 @@
|
|
|
1
|
-
import{defineEngineContractSuite as t}from"../packem_shared/defineEngineContractSuite-
|
|
1
|
+
import{defineEngineContractSuite as t}from"../packem_shared/defineEngineContractSuite-CYR4BaIk.mjs";export{t as defineEngineContractSuite};
|
package/dist/index.d.mts
CHANGED
|
@@ -849,6 +849,7 @@ interface SubscriptionEnvelope {
|
|
|
849
849
|
name: string;
|
|
850
850
|
};
|
|
851
851
|
sinceCheckpoint?: number;
|
|
852
|
+
sinceChunk?: number;
|
|
852
853
|
sinceEpoch?: string;
|
|
853
854
|
topic?: string;
|
|
854
855
|
type: "ack" | "connect" | "shape_subscribe" | "shape_unsubscribe" | "stream" | "subscribe" | "unsubscribe" | "whisper" | "whisper_subscribe" | "whisper_unsubscribe";
|
|
@@ -1018,6 +1019,70 @@ declare const renderSql: (engine: SqlEngine, query: SQL) => RenderedSql;
|
|
|
1018
1019
|
declare const param: (value: unknown) => SQL;
|
|
1019
1020
|
declare const unionAll: (branches: ReadonlyArray<SQL>) => SQL;
|
|
1020
1021
|
declare const sqliteInList: (reference: SQL, items: ReadonlyArray<unknown>, negated: boolean, budget?: number) => SQL;
|
|
1022
|
+
type DurableStreamStatus = "complete" | "error" | "running";
|
|
1023
|
+
interface DurableStreamRun {
|
|
1024
|
+
error?: string;
|
|
1025
|
+
errorCode?: string;
|
|
1026
|
+
lastSeq: number;
|
|
1027
|
+
startedAt: number;
|
|
1028
|
+
status: DurableStreamStatus;
|
|
1029
|
+
}
|
|
1030
|
+
interface DurableStreamChunk {
|
|
1031
|
+
dataJson: string;
|
|
1032
|
+
seq: number;
|
|
1033
|
+
}
|
|
1034
|
+
declare const migrateDurableStreams: (sql: SqlExec) => void;
|
|
1035
|
+
declare const readStreamRun: (sql: SqlExec, runKey: string) => DurableStreamRun | undefined;
|
|
1036
|
+
declare const claimStreamRun: (sql: SqlExec, runKey: string, startedAt: number, ttlMs: number) => boolean;
|
|
1037
|
+
declare const deleteStreamRun: (sql: SqlExec, runKey: string) => void;
|
|
1038
|
+
declare const appendStreamChunk: (sql: SqlExec, runKey: string, seq: number, dataJson: string) => void;
|
|
1039
|
+
declare const readStreamChunks: (sql: SqlExec, runKey: string, sinceSeq: number) => DurableStreamChunk[];
|
|
1040
|
+
declare const finishStreamRun: (sql: SqlExec, runKey: string, status: "complete" | "error", lastSeq: number, failure?: {
|
|
1041
|
+
code: string;
|
|
1042
|
+
message: string;
|
|
1043
|
+
}) => void;
|
|
1044
|
+
declare const trimStreamRuns: (sql: SqlExec, now: number) => void;
|
|
1045
|
+
declare const MAX_DURABLE_STREAM_CHUNKS = 50000;
|
|
1046
|
+
declare const MAX_DURABLE_STREAM_BYTES: number;
|
|
1047
|
+
interface DurableStreamSink {
|
|
1048
|
+
readonly chunk: (chunk: {
|
|
1049
|
+
data: unknown;
|
|
1050
|
+
seq: number;
|
|
1051
|
+
}) => boolean;
|
|
1052
|
+
readonly complete: () => void;
|
|
1053
|
+
readonly fail: (failure: {
|
|
1054
|
+
code: string;
|
|
1055
|
+
message: string;
|
|
1056
|
+
}) => void;
|
|
1057
|
+
}
|
|
1058
|
+
type DurableAttachDecision = "attach" | "interrupted" | "reclaim" | "replay-terminal";
|
|
1059
|
+
declare const decideDurableAttach: (run: DurableStreamRun | undefined, context: {
|
|
1060
|
+
live: boolean;
|
|
1061
|
+
resuming: boolean;
|
|
1062
|
+
}) => DurableAttachDecision;
|
|
1063
|
+
interface DurableStreamAttach {
|
|
1064
|
+
readonly iterator: (signal: AbortSignal) => AsyncIterable<unknown>;
|
|
1065
|
+
readonly runKey: string;
|
|
1066
|
+
readonly sinceChunk: number;
|
|
1067
|
+
readonly sink: DurableStreamSink;
|
|
1068
|
+
readonly ttlMs?: number;
|
|
1069
|
+
}
|
|
1070
|
+
declare class DurableStreamRunner {
|
|
1071
|
+
private lastTrimAt;
|
|
1072
|
+
private readonly runs;
|
|
1073
|
+
private readonly sql;
|
|
1074
|
+
private readonly waitUntil;
|
|
1075
|
+
constructor(dependencies: {
|
|
1076
|
+
sql: () => SqlExec;
|
|
1077
|
+
waitUntil?: (promise: Promise<unknown>) => void;
|
|
1078
|
+
});
|
|
1079
|
+
attach(request: DurableStreamAttach): Promise<void>;
|
|
1080
|
+
detach(runKey: string, sink: DurableStreamSink): void;
|
|
1081
|
+
isLive(runKey: string): boolean;
|
|
1082
|
+
private attachOrThrow;
|
|
1083
|
+
private produce;
|
|
1084
|
+
private trim;
|
|
1085
|
+
}
|
|
1021
1086
|
interface ExternalSourceDiffResult {
|
|
1022
1087
|
changes: CdcChange[];
|
|
1023
1088
|
nextBaseline: Map<string, string>;
|
|
@@ -2061,4 +2126,4 @@ interface WhereSqlStrategy {
|
|
|
2061
2126
|
}
|
|
2062
2127
|
declare const literalInList: (reference: SQL, items: ReadonlyArray<unknown>, negated: boolean) => SQL;
|
|
2063
2128
|
declare const compileWhereSql: (where: WhereInput | undefined, strategy: WhereSqlStrategy) => SQL | undefined;
|
|
2064
|
-
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 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_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, 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, applyCdcChanges, applyOnDelete, applySelect, armRestore, assertFlatPredicate, assertReadonly, assertShapeShardable, assertValidClientId, awaitWsDrain, backfillAggregateIndexes, backfillRankIndexes, backfillSearchIndexes, backfillSearchIndexesForTable, boundingBoxCenter, boundingBoxGeohashes, buildIndexRange, buildPokeFrames, buildReprojectionMigration, buildSeekBeforeWhere, buildSeekWhere, buildSettings, bumpCdcEpoch, clampPromotionThresholds, clearCapturedMail, clearQueueMessages, coerceAggregateNumber, compileWhereSql, computeRankPage, containsRelationPredicate, countLegacyRows, coveringGeohashes, createCompanionSync, createDependencyTracker, createFanoutCounters, createIndexSql, createReadFootprint, createRelayLink, createReplicaLink, createShardCtxDb, createSystemReader, decodeCursor, deleteGlobalShapeSnapshot, deleteGlobalShapeSnapshotsForConnection, depKey, diffExternalSource, diffGlobalMembership, distinctValues, encodeAggregateKey, encodeCursor, encodeGeohash, encodePartitionKey, encodeRowsPatch, ensureAuditTable, ensureMailTable, exportShardRows, exportShardTable, facetColumn, fanOutScalarCounts, findStorageReferences, 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, migrateGlobalShapeSnapshot, migrateIdempotency, migrateSearchState, 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, 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, sendDeltaFrames, serializeSqlValue, shapeRoutingKey, softDeleteScope, sortColumnName, sqliteInList, stableStringify, stableWireKey, subscriptionListDeltas, summarizeFanoutTopics, summarizeSubscriptions, tableColumns, tableFromDepKey, throwingScheduler, trimCdcChanges, trimIdempotent, tryRowToDocument, trySendFrame, unionAll, validateImportRow, writeGlobalShapeSnapshot, writeIdempotent, writeSearchBackfillState, writeTouchesMemo };
|
|
2129
|
+
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, 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, 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, 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, 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, sendDeltaFrames, serializeSqlValue, shapeRoutingKey, softDeleteScope, sortColumnName, sqliteInList, stableStringify, stableWireKey, subscriptionListDeltas, summarizeFanoutTopics, summarizeSubscriptions, tableColumns, tableFromDepKey, throwingScheduler, trimCdcChanges, trimIdempotent, trimStreamRuns, tryRowToDocument, trySendFrame, unionAll, validateImportRow, writeGlobalShapeSnapshot, writeIdempotent, writeSearchBackfillState, writeTouchesMemo };
|
package/dist/index.d.ts
CHANGED
|
@@ -849,6 +849,7 @@ interface SubscriptionEnvelope {
|
|
|
849
849
|
name: string;
|
|
850
850
|
};
|
|
851
851
|
sinceCheckpoint?: number;
|
|
852
|
+
sinceChunk?: number;
|
|
852
853
|
sinceEpoch?: string;
|
|
853
854
|
topic?: string;
|
|
854
855
|
type: "ack" | "connect" | "shape_subscribe" | "shape_unsubscribe" | "stream" | "subscribe" | "unsubscribe" | "whisper" | "whisper_subscribe" | "whisper_unsubscribe";
|
|
@@ -1018,6 +1019,70 @@ declare const renderSql: (engine: SqlEngine, query: SQL) => RenderedSql;
|
|
|
1018
1019
|
declare const param: (value: unknown) => SQL;
|
|
1019
1020
|
declare const unionAll: (branches: ReadonlyArray<SQL>) => SQL;
|
|
1020
1021
|
declare const sqliteInList: (reference: SQL, items: ReadonlyArray<unknown>, negated: boolean, budget?: number) => SQL;
|
|
1022
|
+
type DurableStreamStatus = "complete" | "error" | "running";
|
|
1023
|
+
interface DurableStreamRun {
|
|
1024
|
+
error?: string;
|
|
1025
|
+
errorCode?: string;
|
|
1026
|
+
lastSeq: number;
|
|
1027
|
+
startedAt: number;
|
|
1028
|
+
status: DurableStreamStatus;
|
|
1029
|
+
}
|
|
1030
|
+
interface DurableStreamChunk {
|
|
1031
|
+
dataJson: string;
|
|
1032
|
+
seq: number;
|
|
1033
|
+
}
|
|
1034
|
+
declare const migrateDurableStreams: (sql: SqlExec) => void;
|
|
1035
|
+
declare const readStreamRun: (sql: SqlExec, runKey: string) => DurableStreamRun | undefined;
|
|
1036
|
+
declare const claimStreamRun: (sql: SqlExec, runKey: string, startedAt: number, ttlMs: number) => boolean;
|
|
1037
|
+
declare const deleteStreamRun: (sql: SqlExec, runKey: string) => void;
|
|
1038
|
+
declare const appendStreamChunk: (sql: SqlExec, runKey: string, seq: number, dataJson: string) => void;
|
|
1039
|
+
declare const readStreamChunks: (sql: SqlExec, runKey: string, sinceSeq: number) => DurableStreamChunk[];
|
|
1040
|
+
declare const finishStreamRun: (sql: SqlExec, runKey: string, status: "complete" | "error", lastSeq: number, failure?: {
|
|
1041
|
+
code: string;
|
|
1042
|
+
message: string;
|
|
1043
|
+
}) => void;
|
|
1044
|
+
declare const trimStreamRuns: (sql: SqlExec, now: number) => void;
|
|
1045
|
+
declare const MAX_DURABLE_STREAM_CHUNKS = 50000;
|
|
1046
|
+
declare const MAX_DURABLE_STREAM_BYTES: number;
|
|
1047
|
+
interface DurableStreamSink {
|
|
1048
|
+
readonly chunk: (chunk: {
|
|
1049
|
+
data: unknown;
|
|
1050
|
+
seq: number;
|
|
1051
|
+
}) => boolean;
|
|
1052
|
+
readonly complete: () => void;
|
|
1053
|
+
readonly fail: (failure: {
|
|
1054
|
+
code: string;
|
|
1055
|
+
message: string;
|
|
1056
|
+
}) => void;
|
|
1057
|
+
}
|
|
1058
|
+
type DurableAttachDecision = "attach" | "interrupted" | "reclaim" | "replay-terminal";
|
|
1059
|
+
declare const decideDurableAttach: (run: DurableStreamRun | undefined, context: {
|
|
1060
|
+
live: boolean;
|
|
1061
|
+
resuming: boolean;
|
|
1062
|
+
}) => DurableAttachDecision;
|
|
1063
|
+
interface DurableStreamAttach {
|
|
1064
|
+
readonly iterator: (signal: AbortSignal) => AsyncIterable<unknown>;
|
|
1065
|
+
readonly runKey: string;
|
|
1066
|
+
readonly sinceChunk: number;
|
|
1067
|
+
readonly sink: DurableStreamSink;
|
|
1068
|
+
readonly ttlMs?: number;
|
|
1069
|
+
}
|
|
1070
|
+
declare class DurableStreamRunner {
|
|
1071
|
+
private lastTrimAt;
|
|
1072
|
+
private readonly runs;
|
|
1073
|
+
private readonly sql;
|
|
1074
|
+
private readonly waitUntil;
|
|
1075
|
+
constructor(dependencies: {
|
|
1076
|
+
sql: () => SqlExec;
|
|
1077
|
+
waitUntil?: (promise: Promise<unknown>) => void;
|
|
1078
|
+
});
|
|
1079
|
+
attach(request: DurableStreamAttach): Promise<void>;
|
|
1080
|
+
detach(runKey: string, sink: DurableStreamSink): void;
|
|
1081
|
+
isLive(runKey: string): boolean;
|
|
1082
|
+
private attachOrThrow;
|
|
1083
|
+
private produce;
|
|
1084
|
+
private trim;
|
|
1085
|
+
}
|
|
1021
1086
|
interface ExternalSourceDiffResult {
|
|
1022
1087
|
changes: CdcChange[];
|
|
1023
1088
|
nextBaseline: Map<string, string>;
|
|
@@ -2061,4 +2126,4 @@ interface WhereSqlStrategy {
|
|
|
2061
2126
|
}
|
|
2062
2127
|
declare const literalInList: (reference: SQL, items: ReadonlyArray<unknown>, negated: boolean) => SQL;
|
|
2063
2128
|
declare const compileWhereSql: (where: WhereInput | undefined, strategy: WhereSqlStrategy) => SQL | undefined;
|
|
2064
|
-
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 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_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, 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, applyCdcChanges, applyOnDelete, applySelect, armRestore, assertFlatPredicate, assertReadonly, assertShapeShardable, assertValidClientId, awaitWsDrain, backfillAggregateIndexes, backfillRankIndexes, backfillSearchIndexes, backfillSearchIndexesForTable, boundingBoxCenter, boundingBoxGeohashes, buildIndexRange, buildPokeFrames, buildReprojectionMigration, buildSeekBeforeWhere, buildSeekWhere, buildSettings, bumpCdcEpoch, clampPromotionThresholds, clearCapturedMail, clearQueueMessages, coerceAggregateNumber, compileWhereSql, computeRankPage, containsRelationPredicate, countLegacyRows, coveringGeohashes, createCompanionSync, createDependencyTracker, createFanoutCounters, createIndexSql, createReadFootprint, createRelayLink, createReplicaLink, createShardCtxDb, createSystemReader, decodeCursor, deleteGlobalShapeSnapshot, deleteGlobalShapeSnapshotsForConnection, depKey, diffExternalSource, diffGlobalMembership, distinctValues, encodeAggregateKey, encodeCursor, encodeGeohash, encodePartitionKey, encodeRowsPatch, ensureAuditTable, ensureMailTable, exportShardRows, exportShardTable, facetColumn, fanOutScalarCounts, findStorageReferences, 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, migrateGlobalShapeSnapshot, migrateIdempotency, migrateSearchState, 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, 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, sendDeltaFrames, serializeSqlValue, shapeRoutingKey, softDeleteScope, sortColumnName, sqliteInList, stableStringify, stableWireKey, subscriptionListDeltas, summarizeFanoutTopics, summarizeSubscriptions, tableColumns, tableFromDepKey, throwingScheduler, trimCdcChanges, trimIdempotent, tryRowToDocument, trySendFrame, unionAll, validateImportRow, writeGlobalShapeSnapshot, writeIdempotent, writeSearchBackfillState, writeTouchesMemo };
|
|
2129
|
+
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, 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, 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, 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, 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, sendDeltaFrames, serializeSqlValue, shapeRoutingKey, softDeleteScope, sortColumnName, sqliteInList, stableStringify, stableWireKey, subscriptionListDeltas, summarizeFanoutTopics, summarizeSubscriptions, tableColumns, tableFromDepKey, throwingScheduler, trimCdcChanges, trimIdempotent, trimStreamRuns, tryRowToDocument, trySendFrame, unionAll, validateImportRow, writeGlobalShapeSnapshot, writeIdempotent, writeSearchBackfillState, writeTouchesMemo };
|
package/dist/index.mjs
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{exportShardRows as o,exportShardTable as a,importShardRows as t,parseExportShardArgs as n,parseImportShardArgs as l,selectExportTables as s,validateImportRow as i}from"./packem_shared/exportShardRows-Bbi_JGfn.mjs";import{AGGREGATE_SQL_FUNCTION as m,aggregateSqlFunction as d,matchesStaticWhere as c,normalizeCountArgument as S,throwingScheduler as u}from"./packem_shared/AGGREGATE_SQL_FUNCTION-CTo0-9iZ.mjs";import{aggregateTableName as f,coerceAggregateNumber as T,encodeAggregateKey as g,foldAggregateTally as E,readAggregateValue as h}from"./packem_shared/aggregateTableName-DgYMC5tr.mjs";import{CountRlsUnsupportedError as I,mergeWhere as R,planAggregateLookup as C,selectIndexForAggregate as _,selectIndexForCount as L,selectIndexForGroupBy as b}from"./packem_shared/CountRlsUnsupportedError-8BqPYQoP.mjs";import{AUDIT_LOG_TABLE as N,appendAuditEntry as M,ensureAuditTable as O,readAuditLog as F}from"./packem_shared/AUDIT_LOG_TABLE-0FKs74RO.mjs";import{NotUniqueError as P,assertValidClientId as k,createShardCtxDb as G,normalizeIdStructurally as B}from"./packem_shared/NotUniqueError-DJf3W9gG.mjs";import{backfillAggregateIndexes as w,backfillRankIndexes as q,backfillSearchIndexes as K,backfillSearchIndexesForTable as W}from"./packem_shared/backfillAggregateIndexes-Czk8MQ3M.mjs";import{CDC_LOG_TABLE as z,CDC_META_TABLE as H,appendCdcChange as V,applyCdcChanges as X,bumpCdcEpoch as j,migrateCdcLog as Q,migrateCdcMeta as Y,minCdcSeq as J,readCdcChanges as Z,readCdcCursor as $,readCdcEpoch as ee,trimCdcChanges as re}from"./packem_shared/CDC_LOG_TABLE-CIfexI1y.mjs";import{CLIENT_WATERMARK_TABLE as ae,advanceClientWatermark as te,migrateClientWatermark as ne,readClientWatermark as le}from"./packem_shared/CLIENT_WATERMARK_TABLE-BogWgD2Q.mjs";import{S as ie}from"./packem_shared/ctx-db-companions-D2ZMFBrP.mjs";import{GLOBAL_SHAPE_SNAPSHOT_TABLE as me,deleteGlobalShapeSnapshot as de,deleteGlobalShapeSnapshotsForConnection as ce,migrateGlobalShapeSnapshot as Se,readGlobalShapeSnapshot as ue,writeGlobalShapeSnapshot as xe}from"./packem_shared/GLOBAL_SHAPE_SNAPSHOT_TABLE-T5smo6RP.mjs";import{IDEMPOTENCY_TABLE as Te,migrateIdempotency as ge,readIdempotent as Ee,trimIdempotent as he,writeIdempotent as Ae}from"./packem_shared/IDEMPOTENCY_TABLE-DPFwgQbE.mjs";import{computeRankPage as Re,hydrateDocsById as Ce}from"./packem_shared/computeRankPage-CPVNOrM5.mjs";import{SEARCH_STATE_TABLE as Le,migrateSearchState as be,readSearchBackfillState as ye,writeSearchBackfillState as Ne}from"./packem_shared/SEARCH_STATE_TABLE-MDlr30EJ.mjs";import{selectShapeMemberIds as Oe,selectShapeRows as Fe}from"./packem_shared/selectShapeMemberIds-EPo0xxs_.mjs";import{DATA_MIGRATION_STATE_TABLE as Pe,readMigrationStatus as ke,runDataMigration as Ge}from"./packem_shared/DATA_MIGRATION_STATE_TABLE-BcmXmY5q.mjs";import{SCAN_DEP as Ue,createDependencyTracker as we,depKey as qe,tableFromDepKey as Ke}from"./packem_shared/SCAN_DEP-D_yR9EeV.mjs";import{runDrizzle as ve,runSql as ze}from"./packem_shared/runDrizzle-CgYGDEeB.mjs";import{T as Ve,c as Xe,p as je,a as Qe,A as Ye,y as Je,h as Ze,C as $e,_ as er,N as rr,S as or,O as ar,E as tr,I as nr,D as lr}from"./packem_shared/do-sql-Cg_QiQYA.mjs";import{param as ir,renderSql as pr,sqliteInList as mr,unionAll as dr}from"./packem_shared/param-C68MV3DD.mjs";import{diffExternalSource as Sr}from"./packem_shared/diffExternalSource-DMpkJta1.mjs";import{liftSourceId as xr,normalizeSourceDocument as fr,normalizeSourceValue as Tr}from"./packem_shared/liftSourceId-DApAbu7Q.mjs";import{materializeExternalRows as Er,materializeExternalRowsIncremental as hr,readExternalSourceBaseline as Ar,runExternalSourceTick as Ir}from"./packem_shared/materializeExternalRows-CUrDeD82.mjs";import{isSoftDeleted as Cr,isSourceDue as _r,pullExternalSourceIncrementalTick as Lr,pullExternalSourceTick as br}from"./packem_shared/isSoftDeleted-ZosHVk5V.mjs";import{GEO_DEFAULT_PRECISION as Nr,boundingBoxCenter as Mr,boundingBoxGeohashes as Or,coveringGeohashes as Fr,encodeGeohash as Dr,haversineMeters as Pr,pointInBoundingBox as kr}from"./packem_shared/GEO_DEFAULT_PRECISION-DyI5zggj.mjs";import{ADMIN_FUNCTIONS as Br,ADMIN_FUNCTION_PREFIX as Ur,DEFAULT_FANOUT_TOPIC_LIMIT as wr,FLAGS_FUNCTION_PREFIX as qr,MAX_PAGE_SIZE as Kr,RELATION_FUNCTION_PREFIX as Wr,createFanoutCounters as vr,facetColumn as zr,findStorageReferences as Hr,listTables as Vr,readTablePage as Xr,recordFanoutPass as jr,selectMatchingIds as Qr,summarizeFanoutTopics as Yr,summarizeSubscriptions as Jr}from"./packem_shared/ADMIN_FUNCTIONS-BFYAiahG.mjs";import{MAIL_RETENTION as $r,MAIL_TABLE as eo,clearCapturedMail as ro,ensureMailTable as oo,readCapturedMail as ao,recordCapturedMail as to}from"./packem_shared/MAIL_RETENTION-Cp9LWzM4.mjs";import{NotFoundError as lo}from"./packem_shared/NotFoundError-BhF7FeFr.mjs";import{armRestore as io,readBookmark as po}from"./packem_shared/armRestore-BNzdvQ_o.mjs";import{applySelect as co,buildSeekBeforeWhere as So,buildSeekWhere as uo,decodeCursor as xo,encodeCursor as fo,normalizeOrderKeys as To,softDeleteScope as go}from"./packem_shared/applySelect-UY-o13Ia.mjs";import{QUEUE_TABLE as ho,clearQueueMessages as Ao,isLossyBody as Io,readQueueMessageById as Ro,readQueueMessages as Co,recordQueueMessages as _o}from"./packem_shared/QUEUE_TABLE-C1mp0Du0.mjs";import{RANK_TIEBREAK as bo,encodePartitionKey as yo,matchesRankStaticWhere as No,rankKeyFromDoc as Mo,rankTableName as Oo,resolveRankPartition as Fo,sortColumnName as Do}from"./packem_shared/RANK_TIEBREAK-DDtST3gN.mjs";import{ReactiveCache as ko,reactiveCacheKey as Go}from"./packem_shared/ReactiveCache-Cu8IfE1M.mjs";import{createReadFootprint as Uo}from"./packem_shared/createReadFootprint-DIrrxRTE.mjs";import{buildIndexRange as qo,indexKeysForRow as Ko,keysTouchRanges as Wo}from"./packem_shared/buildIndexRange-DFsdtPjD.mjs";import{DEFAULT_MAX_RELATION_KEYS as zo,assertFlatPredicate as Ho,assertShapeShardable as Vo,containsRelationPredicate as Xo,isRelationPredicate as jo,resolveRelationPredicates as Qo}from"./packem_shared/DEFAULT_MAX_RELATION_KEYS-DjKka36Z.mjs";import{applyOnDelete as Jo,distinctValues as Zo,fanOutScalarCounts as $o,relationHooks as ea,resolveWith as ra,runRowValidators as oa}from"./packem_shared/applyOnDelete-By23GK-k.mjs";import{DEFAULT_PROMOTION_THRESHOLDS as ta,clampPromotionThresholds as na,nextPromotionState as la,relayCountFor as sa,shapeRoutingKey as ia}from"./packem_shared/DEFAULT_PROMOTION_THRESHOLDS-B2rUe1bg.mjs";import{DEFAULT_MAX_RELAYS as ma,OwnerRelay as da,RelayMember as ca,createRelayLink as Sa}from"./packem_shared/DEFAULT_MAX_RELAYS-B19vrJxP.mjs";import{createReplicaLink as xa,gateReplicaDispatch as fa,handleReplicaControl as Ta}from"./packem_shared/createReplicaLink-BMNW0SX6.mjs";import{buildReprojectionMigration as Ea,countLegacyRows as ha,reprojectableFields as Aa,reprojectionTables as Ia}from"./packem_shared/buildReprojectionMigration-DMMWPqvy.mjs";import{RLS_UNWRAP_SYMBOL as Ca,RlsRequiredError as _a,guardWriter as La}from"./packem_shared/RLS_UNWRAP_SYMBOL-DcqORh2s.mjs";import{SCHEMA_HISTORY_MAX_VERSIONS as ya,readSchemaHistory as Na,readSchemaVersion as Ma,recordSchemaVersion as Oa}from"./packem_shared/SCHEMA_HISTORY_MAX_VERSIONS-CGlXjXRT.mjs";import{serializeSqlValue as Da}from"./packem_shared/serializeSqlValue-BR4UOWoP.mjs";import{buildSettings as ka,isDevEnvironment as Ga}from"./packem_shared/buildSettings-COIJsw7a.mjs";import{buildPokeFrames as Ua,diffGlobalMembership as wa,encodeRowsPatch as qa,projectColumns as Ka}from"./packem_shared/buildPokeFrames-CqxaN8_H.mjs";import{ShardRunner as va}from"./packem_shared/ShardRunner-DIqVdWtk.mjs";import{runSocketPool as Ha}from"./packem_shared/runSocketPool-DPQLVyWF.mjs";import{MAX_SQL_ROWS as Xa,assertReadonly as ja,lintReadonlySql as Qa,runReadonlySql as Ya}from"./packem_shared/MAX_SQL_ROWS-nMwkxv5f.mjs";import{awaitWsDrain as Za,sendDeltaFrames as $a,subscriptionListDeltas as et,trySendFrame as rt}from"./packem_shared/awaitWsDrain-Bp2jKzIb.mjs";import{mergeChangedKeys as at,recordChangedKeys as tt,writeTouchesMemo as nt}from"./packem_shared/mergeChangedKeys-BXtUgIPW.mjs";import{createSystemReader as st}from"./packem_shared/createSystemReader-DcDcrtM3.mjs";import{ConflictError as pt}from"./packem_shared/ConflictError-C8GtJmjS.mjs";import{DEFAULT_TRANSACTION_LIMITS as dt,TransactionHeadroomTracker as ct}from"./packem_shared/DEFAULT_TRANSACTION_LIMITS-DLUzZbta.mjs";import{hasTrigger as ut,runTriggers as xt}from"./packem_shared/hasTrigger-CbkOHExZ.mjs";import{selectExpiredIds as Tt}from"./packem_shared/selectExpiredIds-DLKts8V0.mjs";import{compileWhereSql as Et,literalInList as ht}from"./packem_shared/compileWhereSql-DxD5mzDy.mjs";import{RELATION_EXISTS_KEY as It}from"./packem_shared/RELATION_EXISTS_KEY-BaqSIFU1.mjs";import{REPROJECTION_MIGRATION_PREFIX as Ct,reprojectionMigrationId as _t}from"./packem_shared/REPROJECTION_MIGRATION_PREFIX-D2dltRFC.mjs";import{quoteIdentifier as bt}from"./packem_shared/quoteIdentifier-CObIFRhb.mjs";import{runShardMigrations as Nt}from"./packem_shared/runShardMigrations-CtlcSZ3r.mjs";import{stableStringify as Ot}from"./packem_shared/stableStringify-BjLh4gvA.mjs";import{stableWireKey as Dt}from"./packem_shared/stableWireKey-l3cjIt-9.mjs";export{Br as ADMIN_FUNCTIONS,Ur as ADMIN_FUNCTION_PREFIX,m as AGGREGATE_SQL_FUNCTION,Ve as AGG_COUNT,Xe as AGG_KEY,je as AGG_VALUE,N as AUDIT_LOG_TABLE,z as CDC_LOG_TABLE,H as CDC_META_TABLE,ae as CLIENT_WATERMARK_TABLE,pt as ConflictError,I as CountRlsUnsupportedError,Pe as DATA_MIGRATION_STATE_TABLE,wr as DEFAULT_FANOUT_TOPIC_LIMIT,zo as DEFAULT_MAX_RELATION_KEYS,ma as DEFAULT_MAX_RELAYS,ta as DEFAULT_PROMOTION_THRESHOLDS,dt as DEFAULT_TRANSACTION_LIMITS,Qe as DOC_COLUMN,qr as FLAGS_FUNCTION_PREFIX,Nr as GEO_DEFAULT_PRECISION,me as GLOBAL_SHAPE_SNAPSHOT_TABLE,Te as IDEMPOTENCY_TABLE,$r as MAIL_RETENTION,eo as MAIL_TABLE,Kr as MAX_PAGE_SIZE,Xa as MAX_SQL_ROWS,lo as NotFoundError,P as NotUniqueError,da as OwnerRelay,ho as QUEUE_TABLE,bo as RANK_TIEBREAK,It as RELATION_EXISTS_KEY,Wr as RELATION_FUNCTION_PREFIX,Ct as REPROJECTION_MIGRATION_PREFIX,Ca as RLS_UNWRAP_SYMBOL,ko as ReactiveCache,ca as RelayMember,_a as RlsRequiredError,Ue as SCAN_DEP,ya as SCHEMA_HISTORY_MAX_VERSIONS,Le as SEARCH_STATE_TABLE,va as ShardRunner,ct as TransactionHeadroomTracker,te as advanceClientWatermark,Ye as aggUpsertSql,d as aggregateSqlFunction,f as aggregateTableName,M as appendAuditEntry,V as appendCdcChange,X as applyCdcChanges,Jo as applyOnDelete,co as applySelect,io as armRestore,Ho as assertFlatPredicate,ja as assertReadonly,Vo as assertShapeShardable,k as assertValidClientId,Za as awaitWsDrain,w as backfillAggregateIndexes,q as backfillRankIndexes,K as backfillSearchIndexes,W as backfillSearchIndexesForTable,Mr as boundingBoxCenter,Or as boundingBoxGeohashes,qo as buildIndexRange,Ua as buildPokeFrames,Ea as buildReprojectionMigration,So as buildSeekBeforeWhere,uo as buildSeekWhere,ka as buildSettings,j as bumpCdcEpoch,na as clampPromotionThresholds,ro as clearCapturedMail,Ao as clearQueueMessages,T as coerceAggregateNumber,Et as compileWhereSql,Re as computeRankPage,Xo as containsRelationPredicate,ha as countLegacyRows,Fr as coveringGeohashes,ie as createCompanionSync,we as createDependencyTracker,vr as createFanoutCounters,Je as createIndexSql,Uo as createReadFootprint,Sa as createRelayLink,xa as createReplicaLink,G as createShardCtxDb,st as createSystemReader,xo as decodeCursor,de as deleteGlobalShapeSnapshot,ce as deleteGlobalShapeSnapshotsForConnection,qe as depKey,Sr as diffExternalSource,wa as diffGlobalMembership,Zo as distinctValues,g as encodeAggregateKey,fo as encodeCursor,Dr as encodeGeohash,yo as encodePartitionKey,qa as encodeRowsPatch,O as ensureAuditTable,oo as ensureMailTable,o as exportShardRows,a as exportShardTable,zr as facetColumn,$o as fanOutScalarCounts,Hr as findStorageReferences,E as foldAggregateTally,fa as gateReplicaDispatch,Ze as geoTableName,La as guardWriter,Ta as handleReplicaControl,ut as hasTrigger,Pr as haversineMeters,Ce as hydrateDocsById,t as importShardRows,Ko as indexKeysForRow,Ga as isDevEnvironment,$e as isFtsAvailable,Io as isLossyBody,jo as isRelationPredicate,Cr as isSoftDeleted,_r as isSourceDue,er as jsonPath,rr as jsonPathSql,Wo as keysTouchRanges,xr as liftSourceId,Qa as lintReadonlySql,Vr as listTables,ht as literalInList,No as matchesRankStaticWhere,c as matchesStaticWhere,Er as materializeExternalRows,hr as materializeExternalRowsIncremental,at as mergeChangedKeys,R as mergeWhere,Q as migrateCdcLog,Y as migrateCdcMeta,ne as migrateClientWatermark,Se as migrateGlobalShapeSnapshot,ge as migrateIdempotency,be as migrateSearchState,J as minCdcSeq,la as nextPromotionState,S as normalizeCountArgument,B as normalizeIdStructurally,To as normalizeOrderKeys,fr as normalizeSourceDocument,Tr as normalizeSourceValue,ir as param,n as parseExportShardArgs,l as parseImportShardArgs,C as planAggregateLookup,kr as pointInBoundingBox,Ka as projectColumns,Lr as pullExternalSourceIncrementalTick,br as pullExternalSourceTick,or as qualifiedJsonPath,ar as qualifiedJsonPathSql,bt as quoteIdentifier,Mo as rankKeyFromDoc,Oo as rankTableName,Go as reactiveCacheKey,h as readAggregateValue,F as readAuditLog,po as readBookmark,ao as readCapturedMail,Z as readCdcChanges,$ as readCdcCursor,ee as readCdcEpoch,le as readClientWatermark,Ar as readExternalSourceBaseline,ue as readGlobalShapeSnapshot,Ee as readIdempotent,ke as readMigrationStatus,Ro as readQueueMessageById,Co as readQueueMessages,Na as readSchemaHistory,Ma as readSchemaVersion,ye as readSearchBackfillState,Xr as readTablePage,to as recordCapturedMail,tt as recordChangedKeys,jr as recordFanoutPass,_o as recordQueueMessages,Oa as recordSchemaVersion,ea as relationHooks,sa as relayCountFor,pr as renderSql,Aa as reprojectableFields,_t as reprojectionMigrationId,Ia as reprojectionTables,Fo as resolveRankPartition,Qo as resolveRelationPredicates,ra as resolveWith,tr as rowToDocument,Ge as runDataMigration,ve as runDrizzle,Ir as runExternalSourceTick,Ya as runReadonlySql,oa as runRowValidators,Nt as runShardMigrations,Ha as runSocketPool,ze as runSql,xt as runTriggers,Tt as selectExpiredIds,s as selectExportTables,_ as selectIndexForAggregate,L as selectIndexForCount,b as selectIndexForGroupBy,Qr as selectMatchingIds,Oe as selectShapeMemberIds,Fe as selectShapeRows,$a as sendDeltaFrames,Da as serializeSqlValue,ia as shapeRoutingKey,go as softDeleteScope,Do as sortColumnName,mr as sqliteInList,Ot as stableStringify,Dt as stableWireKey,et as subscriptionListDeltas,Yr as summarizeFanoutTopics,Jr as summarizeSubscriptions,nr as tableColumns,Ke as tableFromDepKey,u as throwingScheduler,re as trimCdcChanges,he as trimIdempotent,lr as tryRowToDocument,rt as trySendFrame,dr as unionAll,i as validateImportRow,xe as writeGlobalShapeSnapshot,Ae as writeIdempotent,Ne as writeSearchBackfillState,nt as writeTouchesMemo};
|
|
1
|
+
import{exportShardRows as o,exportShardTable as a,importShardRows as t,parseExportShardArgs as n,parseImportShardArgs as l,selectExportTables as s,validateImportRow as i}from"./packem_shared/exportShardRows-Bbi_JGfn.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-CTo0-9iZ.mjs";import{aggregateTableName as f,coerceAggregateNumber as T,encodeAggregateKey as A,foldAggregateTally as E,readAggregateValue as g}from"./packem_shared/aggregateTableName-DgYMC5tr.mjs";import{CountRlsUnsupportedError as R,mergeWhere as I,planAggregateLookup as C,selectIndexForAggregate as _,selectIndexForCount as L,selectIndexForGroupBy as b}from"./packem_shared/CountRlsUnsupportedError-8BqPYQoP.mjs";import{AUDIT_LOG_TABLE as N,appendAuditEntry as y,ensureAuditTable as D,readAuditLog as O}from"./packem_shared/AUDIT_LOG_TABLE-Bl2mYtAQ.mjs";import{NotUniqueError as k,assertValidClientId as P,createShardCtxDb as B,normalizeIdStructurally as G}from"./packem_shared/NotUniqueError-BeTJrgRe.mjs";import{backfillAggregateIndexes as w,backfillRankIndexes as K,backfillSearchIndexes as q,backfillSearchIndexesForTable as W}from"./packem_shared/backfillAggregateIndexes-BEMWTEq1.mjs";import{CDC_LOG_TABLE as z,CDC_META_TABLE as X,appendCdcChange as H,applyCdcChanges as V,bumpCdcEpoch as Y,migrateCdcLog as j,migrateCdcMeta as Q,minCdcSeq as J,readCdcChanges as Z,readCdcCursor as $,readCdcEpoch as ee,trimCdcChanges as re}from"./packem_shared/CDC_LOG_TABLE-DH-KHUfU.mjs";import{CLIENT_WATERMARK_TABLE as ae,advanceClientWatermark as te,migrateClientWatermark as ne,readClientWatermark as le}from"./packem_shared/CLIENT_WATERMARK_TABLE-LrKfdxyt.mjs";import{S as ie}from"./packem_shared/ctx-db-companions-c12P7dbv.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-B2LKe4KU.mjs";import{IDEMPOTENCY_TABLE as Te,migrateIdempotency as Ae,readIdempotent as Ee,trimIdempotent as ge,writeIdempotent as he}from"./packem_shared/IDEMPOTENCY_TABLE-tQ5mnqvw.mjs";import{computeRankPage as Ie,hydrateDocsById as Ce}from"./packem_shared/computeRankPage-D1ygctSC.mjs";import{SEARCH_STATE_TABLE as Le,migrateSearchState as be,readSearchBackfillState as Me,writeSearchBackfillState as Ne}from"./packem_shared/SEARCH_STATE_TABLE-DRk_SB72.mjs";import{selectShapeMemberIds as De,selectShapeRows as Oe}from"./packem_shared/selectShapeMemberIds-WzxOG62k.mjs";import{DATA_MIGRATION_STATE_TABLE as ke,readMigrationStatus as Pe,runDataMigration as Be}from"./packem_shared/DATA_MIGRATION_STATE_TABLE-DIQTu___.mjs";import{SCAN_DEP as Ue,createDependencyTracker as we,depKey as Ke,tableFromDepKey as qe}from"./packem_shared/SCAN_DEP-D_yR9EeV.mjs";import{runDrizzle as ve,runSql as ze}from"./packem_shared/runDrizzle-C3n5gJsk.mjs";import{T as He,c as Ve,p as Ye,a as je,A as Qe,y as Je,h as Ze,C as $e,_ as er,N as rr,S as or,O as ar,E as tr,I as nr,D as lr}from"./packem_shared/do-sql-C7qrlm6-.mjs";import{param as ir,renderSql as mr,sqliteInList as pr,unionAll as dr}from"./packem_shared/param-CYxL68V-.mjs";import{appendStreamChunk as Sr,claimStreamRun as ur,deleteStreamRun as xr,finishStreamRun as fr,migrateDurableStreams as Tr,readStreamChunks as Ar,readStreamRun as Er,trimStreamRuns as gr}from"./packem_shared/appendStreamChunk-ksZYy1hZ.mjs";import{DurableStreamRunner as Rr,MAX_DURABLE_STREAM_BYTES as Ir,MAX_DURABLE_STREAM_CHUNKS as Cr,decideDurableAttach as _r}from"./packem_shared/DurableStreamRunner-C-OSu02s.mjs";import{diffExternalSource as br}from"./packem_shared/diffExternalSource-DMpkJta1.mjs";import{liftSourceId as Nr,normalizeSourceDocument as yr,normalizeSourceValue as Dr}from"./packem_shared/liftSourceId-DApAbu7Q.mjs";import{materializeExternalRows as Fr,materializeExternalRowsIncremental as kr,readExternalSourceBaseline as Pr,runExternalSourceTick as Br}from"./packem_shared/materializeExternalRows-D53xwGfY.mjs";import{isSoftDeleted as Ur,isSourceDue as wr,pullExternalSourceIncrementalTick as Kr,pullExternalSourceTick as qr}from"./packem_shared/isSoftDeleted-Tr2to2aw.mjs";import{GEO_DEFAULT_PRECISION as vr,boundingBoxCenter as zr,boundingBoxGeohashes as Xr,coveringGeohashes as Hr,encodeGeohash as Vr,haversineMeters as Yr,pointInBoundingBox as jr}from"./packem_shared/GEO_DEFAULT_PRECISION-DyI5zggj.mjs";import{ADMIN_FUNCTIONS as Jr,ADMIN_FUNCTION_PREFIX as Zr,DEFAULT_FANOUT_TOPIC_LIMIT as $r,FLAGS_FUNCTION_PREFIX as eo,MAX_PAGE_SIZE as ro,RELATION_FUNCTION_PREFIX as oo,createFanoutCounters as ao,facetColumn as to,findStorageReferences as no,listTables as lo,readTablePage as so,recordFanoutPass as io,selectMatchingIds as mo,summarizeFanoutTopics as po,summarizeSubscriptions as co}from"./packem_shared/ADMIN_FUNCTIONS-B5HZoizX.mjs";import{MAIL_RETENTION as uo,MAIL_TABLE as xo,clearCapturedMail as fo,ensureMailTable as To,readCapturedMail as Ao,recordCapturedMail as Eo}from"./packem_shared/MAIL_RETENTION-CzZuX9bd.mjs";import{NotFoundError as ho}from"./packem_shared/NotFoundError-BhF7FeFr.mjs";import{armRestore as Io,readBookmark as Co}from"./packem_shared/armRestore-BNzdvQ_o.mjs";import{applySelect as Lo,buildSeekBeforeWhere as bo,buildSeekWhere as Mo,decodeCursor as No,encodeCursor as yo,normalizeOrderKeys as Do,softDeleteScope as Oo}from"./packem_shared/applySelect-UY-o13Ia.mjs";import{QUEUE_TABLE as ko,clearQueueMessages as Po,isLossyBody as Bo,readQueueMessageById as Go,readQueueMessages as Uo,recordQueueMessages as wo}from"./packem_shared/QUEUE_TABLE-BX0nopuT.mjs";import{RANK_TIEBREAK as qo,encodePartitionKey as Wo,matchesRankStaticWhere as vo,rankKeyFromDoc as zo,rankTableName as Xo,resolveRankPartition as Ho,sortColumnName as Vo}from"./packem_shared/RANK_TIEBREAK-DDtST3gN.mjs";import{ReactiveCache as jo,reactiveCacheKey as Qo}from"./packem_shared/ReactiveCache-Cu8IfE1M.mjs";import{createReadFootprint as Zo}from"./packem_shared/createReadFootprint-DIrrxRTE.mjs";import{buildIndexRange as ea,indexKeysForRow as ra,keysTouchRanges as oa}from"./packem_shared/buildIndexRange-DFsdtPjD.mjs";import{DEFAULT_MAX_RELATION_KEYS as ta,assertFlatPredicate as na,assertShapeShardable as la,containsRelationPredicate as sa,isRelationPredicate as ia,resolveRelationPredicates as ma}from"./packem_shared/DEFAULT_MAX_RELATION_KEYS-DjKka36Z.mjs";import{applyOnDelete as da,distinctValues as ca,fanOutScalarCounts as Sa,relationHooks as ua,resolveWith as xa,runRowValidators as fa}from"./packem_shared/applyOnDelete-By23GK-k.mjs";import{DEFAULT_PROMOTION_THRESHOLDS as Aa,clampPromotionThresholds as Ea,nextPromotionState as ga,relayCountFor as ha,shapeRoutingKey as Ra}from"./packem_shared/DEFAULT_PROMOTION_THRESHOLDS-B2rUe1bg.mjs";import{DEFAULT_MAX_RELAYS as Ca,OwnerRelay as _a,RelayMember as La,createRelayLink as ba}from"./packem_shared/DEFAULT_MAX_RELAYS-B19vrJxP.mjs";import{createReplicaLink as Na,gateReplicaDispatch as ya,handleReplicaControl as Da}from"./packem_shared/createReplicaLink-BMNW0SX6.mjs";import{buildReprojectionMigration as Fa,countLegacyRows as ka,reprojectableFields as Pa,reprojectionTables as Ba}from"./packem_shared/buildReprojectionMigration-YQSJX2cC.mjs";import{RLS_UNWRAP_SYMBOL as Ua,RlsRequiredError as wa,guardWriter as Ka}from"./packem_shared/RLS_UNWRAP_SYMBOL-DcqORh2s.mjs";import{SCHEMA_HISTORY_MAX_VERSIONS as Wa,readSchemaHistory as va,readSchemaVersion as za,recordSchemaVersion as Xa}from"./packem_shared/SCHEMA_HISTORY_MAX_VERSIONS-CEK7b_7v.mjs";import{serializeSqlValue as Va}from"./packem_shared/serializeSqlValue-BR4UOWoP.mjs";import{buildSettings as ja,isDevEnvironment as Qa}from"./packem_shared/buildSettings-COIJsw7a.mjs";import{buildPokeFrames as Za,diffGlobalMembership as $a,encodeRowsPatch as et,projectColumns as rt}from"./packem_shared/buildPokeFrames-CqxaN8_H.mjs";import{ShardRunner as at}from"./packem_shared/ShardRunner-DIqVdWtk.mjs";import{runSocketPool as nt}from"./packem_shared/runSocketPool-DPQLVyWF.mjs";import{MAX_SQL_ROWS as st,assertReadonly as it,lintReadonlySql as mt,runReadonlySql as pt}from"./packem_shared/MAX_SQL_ROWS-nMwkxv5f.mjs";import{awaitWsDrain as ct,sendDeltaFrames as St,subscriptionListDeltas as ut,trySendFrame as xt}from"./packem_shared/awaitWsDrain-Bp2jKzIb.mjs";import{mergeChangedKeys as Tt,recordChangedKeys as At,writeTouchesMemo as Et}from"./packem_shared/mergeChangedKeys-BXtUgIPW.mjs";import{createSystemReader as ht}from"./packem_shared/createSystemReader-DcDcrtM3.mjs";import{ConflictError as It}from"./packem_shared/ConflictError-C8GtJmjS.mjs";import{DEFAULT_TRANSACTION_LIMITS as _t,TransactionHeadroomTracker as Lt}from"./packem_shared/DEFAULT_TRANSACTION_LIMITS-DLUzZbta.mjs";import{hasTrigger as Mt,runTriggers as Nt}from"./packem_shared/hasTrigger-CbkOHExZ.mjs";import{selectExpiredIds as Dt}from"./packem_shared/selectExpiredIds-C3Vv1gPm.mjs";import{compileWhereSql as Ft,literalInList as kt}from"./packem_shared/compileWhereSql-B3hq_v98.mjs";import{RELATION_EXISTS_KEY as Bt}from"./packem_shared/RELATION_EXISTS_KEY-BaqSIFU1.mjs";import{REPROJECTION_MIGRATION_PREFIX as Ut,reprojectionMigrationId as wt}from"./packem_shared/REPROJECTION_MIGRATION_PREFIX-D2dltRFC.mjs";import{quoteIdentifier as qt}from"./packem_shared/quoteIdentifier-CObIFRhb.mjs";import{runShardMigrations as vt}from"./packem_shared/runShardMigrations-BAtfEXbB.mjs";import{stableStringify as Xt}from"./packem_shared/stableStringify-BjLh4gvA.mjs";import{stableWireKey as Vt}from"./packem_shared/stableWireKey-l3cjIt-9.mjs";export{Jr as ADMIN_FUNCTIONS,Zr as ADMIN_FUNCTION_PREFIX,p as AGGREGATE_SQL_FUNCTION,He as AGG_COUNT,Ve as AGG_KEY,Ye as AGG_VALUE,N as AUDIT_LOG_TABLE,z as CDC_LOG_TABLE,X as CDC_META_TABLE,ae as CLIENT_WATERMARK_TABLE,It as ConflictError,R as CountRlsUnsupportedError,ke as DATA_MIGRATION_STATE_TABLE,$r as DEFAULT_FANOUT_TOPIC_LIMIT,ta as DEFAULT_MAX_RELATION_KEYS,Ca as DEFAULT_MAX_RELAYS,Aa as DEFAULT_PROMOTION_THRESHOLDS,_t as DEFAULT_TRANSACTION_LIMITS,je as DOC_COLUMN,Rr as DurableStreamRunner,eo as FLAGS_FUNCTION_PREFIX,vr as GEO_DEFAULT_PRECISION,pe as GLOBAL_SHAPE_SNAPSHOT_TABLE,Te as IDEMPOTENCY_TABLE,uo as MAIL_RETENTION,xo as MAIL_TABLE,Ir as MAX_DURABLE_STREAM_BYTES,Cr as MAX_DURABLE_STREAM_CHUNKS,ro as MAX_PAGE_SIZE,st as MAX_SQL_ROWS,ho as NotFoundError,k as NotUniqueError,_a as OwnerRelay,ko as QUEUE_TABLE,qo as RANK_TIEBREAK,Bt as RELATION_EXISTS_KEY,oo as RELATION_FUNCTION_PREFIX,Ut as REPROJECTION_MIGRATION_PREFIX,Ua as RLS_UNWRAP_SYMBOL,jo as ReactiveCache,La as RelayMember,wa as RlsRequiredError,Ue as SCAN_DEP,Wa as SCHEMA_HISTORY_MAX_VERSIONS,Le as SEARCH_STATE_TABLE,at as ShardRunner,Lt as TransactionHeadroomTracker,te as advanceClientWatermark,Qe as aggUpsertSql,d as aggregateSqlFunction,f as aggregateTableName,y as appendAuditEntry,H as appendCdcChange,Sr as appendStreamChunk,V as applyCdcChanges,da as applyOnDelete,Lo as applySelect,Io as armRestore,na as assertFlatPredicate,it as assertReadonly,la as assertShapeShardable,P as assertValidClientId,ct as awaitWsDrain,w as backfillAggregateIndexes,K as backfillRankIndexes,q as backfillSearchIndexes,W as backfillSearchIndexesForTable,zr as boundingBoxCenter,Xr as boundingBoxGeohashes,ea as buildIndexRange,Za as buildPokeFrames,Fa as buildReprojectionMigration,bo as buildSeekBeforeWhere,Mo as buildSeekWhere,ja as buildSettings,Y as bumpCdcEpoch,ur as claimStreamRun,Ea as clampPromotionThresholds,fo as clearCapturedMail,Po as clearQueueMessages,T as coerceAggregateNumber,Ft as compileWhereSql,Ie as computeRankPage,sa as containsRelationPredicate,ka as countLegacyRows,Hr as coveringGeohashes,ie as createCompanionSync,we as createDependencyTracker,ao as createFanoutCounters,Je as createIndexSql,Zo as createReadFootprint,ba as createRelayLink,Na as createReplicaLink,B as createShardCtxDb,ht as createSystemReader,_r as decideDurableAttach,No as decodeCursor,de as deleteGlobalShapeSnapshot,ce as deleteGlobalShapeSnapshotsForConnection,xr as deleteStreamRun,Ke as depKey,br as diffExternalSource,$a as diffGlobalMembership,ca as distinctValues,A as encodeAggregateKey,yo as encodeCursor,Vr as encodeGeohash,Wo as encodePartitionKey,et as encodeRowsPatch,D as ensureAuditTable,To as ensureMailTable,o as exportShardRows,a as exportShardTable,to as facetColumn,Sa as fanOutScalarCounts,no as findStorageReferences,fr as finishStreamRun,E as foldAggregateTally,ya as gateReplicaDispatch,Ze as geoTableName,Ka as guardWriter,Da as handleReplicaControl,Mt as hasTrigger,Yr as haversineMeters,Ce as hydrateDocsById,t as importShardRows,ra as indexKeysForRow,Qa as isDevEnvironment,$e as isFtsAvailable,Bo as isLossyBody,ia as isRelationPredicate,Ur as isSoftDeleted,wr as isSourceDue,er as jsonPath,rr as jsonPathSql,oa as keysTouchRanges,Nr as liftSourceId,mt as lintReadonlySql,lo as listTables,kt as literalInList,vo as matchesRankStaticWhere,c as matchesStaticWhere,Fr as materializeExternalRows,kr as materializeExternalRowsIncremental,Tt as mergeChangedKeys,I as mergeWhere,j as migrateCdcLog,Q as migrateCdcMeta,ne as migrateClientWatermark,Tr as migrateDurableStreams,Se as migrateGlobalShapeSnapshot,Ae as migrateIdempotency,be as migrateSearchState,J as minCdcSeq,ga as nextPromotionState,S as normalizeCountArgument,G as normalizeIdStructurally,Do as normalizeOrderKeys,yr as normalizeSourceDocument,Dr as normalizeSourceValue,ir as param,n as parseExportShardArgs,l as parseImportShardArgs,C as planAggregateLookup,jr as pointInBoundingBox,rt as projectColumns,Kr as pullExternalSourceIncrementalTick,qr as pullExternalSourceTick,or as qualifiedJsonPath,ar as qualifiedJsonPathSql,qt as quoteIdentifier,zo as rankKeyFromDoc,Xo as rankTableName,Qo as reactiveCacheKey,g as readAggregateValue,O as readAuditLog,Co as readBookmark,Ao as readCapturedMail,Z as readCdcChanges,$ as readCdcCursor,ee as readCdcEpoch,le as readClientWatermark,Pr as readExternalSourceBaseline,ue as readGlobalShapeSnapshot,Ee as readIdempotent,Pe as readMigrationStatus,Go as readQueueMessageById,Uo as readQueueMessages,va as readSchemaHistory,za as readSchemaVersion,Me as readSearchBackfillState,Ar as readStreamChunks,Er as readStreamRun,so as readTablePage,Eo as recordCapturedMail,At as recordChangedKeys,io as recordFanoutPass,wo as recordQueueMessages,Xa as recordSchemaVersion,ua as relationHooks,ha as relayCountFor,mr as renderSql,Pa as reprojectableFields,wt as reprojectionMigrationId,Ba as reprojectionTables,Ho as resolveRankPartition,ma as resolveRelationPredicates,xa as resolveWith,tr as rowToDocument,Be as runDataMigration,ve as runDrizzle,Br as runExternalSourceTick,pt as runReadonlySql,fa as runRowValidators,vt as runShardMigrations,nt as runSocketPool,ze as runSql,Nt as runTriggers,Dt as selectExpiredIds,s as selectExportTables,_ as selectIndexForAggregate,L as selectIndexForCount,b as selectIndexForGroupBy,mo as selectMatchingIds,De as selectShapeMemberIds,Oe as selectShapeRows,St as sendDeltaFrames,Va as serializeSqlValue,Ra as shapeRoutingKey,Oo as softDeleteScope,Vo as sortColumnName,pr as sqliteInList,Xt as stableStringify,Vt as stableWireKey,ut as subscriptionListDeltas,po as summarizeFanoutTopics,co as summarizeSubscriptions,nr as tableColumns,qe as tableFromDepKey,u as throwingScheduler,re as trimCdcChanges,ge as trimIdempotent,gr as trimStreamRuns,lr as tryRowToDocument,xt as trySendFrame,dr as unionAll,i as validateImportRow,xe as writeGlobalShapeSnapshot,he as writeIdempotent,Ne as writeSearchBackfillState,Et as writeTouchesMemo};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{LunoraError as T}from"@lunora/errors";import{j as L,s as k}from"./do-sql-Cg_QiQYA.mjs";import{quoteIdentifier as d}from"./quoteIdentifier-CObIFRhb.mjs";import{s as P}from"./wire-codec-Dsy70M3Q.mjs";const te="__lunora_admin__:",ae="__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,f=500,U=30,q=200,m="__doc__",R=e=>{try{const t=JSON.parse(e);return t!==null&&typeof t=="object"&&!Array.isArray(t)?t:void 0}catch{return}},W=e=>{const{[k]:t,...a}=e;return t===void 0?a:t===null||typeof t!="object"||Array.isArray(t)?{[k]:t,...a}:{...a,...P(t)}},j=(e,t)=>{if(!e.includes(m))return{columns:e,rows:t};const a=[];for(const s of t){const _=s[m],u=typeof _=="string"?R(_):void 0;if(u===void 0)return{columns:e,rows:t};const i=Object.fromEntries(Object.entries(s).filter(([l])=>l!==m));a.push({...i,...W(u)})}const r=e.filter(s=>s!==m),o=[],n=new Set(r);for(const s of a)for(const _ of Object.keys(s))n.has(_)||(n.add(_),o.push(_));return{columns:[...r,...o],rows:a}},w=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_"),v=(e,t,a)=>Math.min(Math.max(e,t),a),$=(e,t)=>{const a=e.exec(`SELECT COUNT(*) AS c FROM ${t}`).one();return Number(a.c)},oe=e=>{const t=e.exec("SELECT name FROM sqlite_master WHERE type = 'table' ORDER BY name").toArray(),a=[];for(const{name:r}of t)I(r)||a.push({name:r,rowCount:$(e,d(r))});return a},x=(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)||!x(e,t))throw new T("UNKNOWN_TABLE",`unknown table: ${t}`,{status:404})},b=(e,t)=>e.exec(`PRAGMA table_info(${t})`).toArray().map(a=>a.name),Q={eq:"=",gt:">",gte:">=",lt:"<",lte:"<=",ne:"<>"},B=e=>typeof e=="string"?e:typeof e=="number"||typeof e=="boolean"?String(e):"",M=(e,t)=>{const a=t.includes(e),r=t.includes(m);if(!(!a&&!r))return a?{expression:d(e),params:[]}:{expression:`json_extract(${d(m)}, ?)`,params:[`$.${L(e)}`]}},H=(e,t)=>{const a=M(e.column,t);if(a===void 0)return;const{expression:r,params:o}=a;return e.operator==="contains"?{params:[...o,B(e.value)],sql:w(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 a=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)||a<100)return;const n=Date.UTC(a,(r??1)-1,o??1);if(o!==void 0&&new Date(n).getUTCDate()!==o)return;let s;return o!==void 0?s=Date.UTC(a,(r??1)-1,o+1):r===void 0?s=Date.UTC(a+1,0,1):s=Date.UTC(a,r,1),{from:n,to:s}},E=(e,t,a)=>{const r=[],o=[];if(t!==""&&e.length>0){const n=e.map(_=>w(d(_)));o.push(...e.map(()=>t));const s=X(t);if(s!==void 0)for(const _ of e)n.push(`(${d(_)} >= ? AND ${d(_)} < ?)`),o.push(s.from,s.to);r.push(`(${n.join(" OR ")})`)}for(const n of a??[]){const s=H(n,e);s!==void 0&&(r.push(`(${s.sql})`),o.push(...s.params))}return r.length===0?void 0:{parameters:o,where:r.join(" AND ")}},Y=(e,t)=>{if(e===void 0)return;const a=M(e.column,t);if(a===void 0)return;const r=e.direction==="desc"?"DESC":"ASC";return{params:a.params,sql:`${a.expression} ${r}`}},ne=(e,t)=>{const{table:a}=t;C(e,a);const r=v(Math.trunc(t.limit??D),1,f),o=Math.max(0,Math.trunc(t.offset??0)),n=d(a),s=b(e,n),_=t.search?.trim()??"",u=h=>{if(t.refs===void 0)return h;const S={};for(const y of h.columns){const O=t.refs[y];O!==void 0&&(S[y]=O)}return Object.keys(S).length>0?{...h,refs:S}:h},i=E(s,_,t.filters),l=Y(t.orderBy,s),c=i===void 0?"":` WHERE ${i.where}`,p=l===void 0?"":` ORDER BY ${l.sql}`,g=i?.parameters??[],N=l?.params??[];let A;t.skipCount||(A=i===void 0?$(e,n):Number(e.exec(`SELECT COUNT(*) AS c FROM ${n}${c}`,...g).one().c));const F=e.exec(`SELECT * FROM ${n}${c}${p} LIMIT ? OFFSET ?`,...g,...N,r,o).toArray();return u({...j(s,F),total:A})},_e=(e,t)=>{const{table:a}=t;C(e,a);const r=v(Math.trunc(t.limit??f),1,f),o=d(a),n=b(e,o),s=t.search?.trim()??"",_=E(n,s,t.filters),u=_===void 0?e.exec(`SELECT id FROM ${o} LIMIT ?`,r+1).toArray():e.exec(`SELECT id FROM ${o} WHERE ${_.where} LIMIT ?`,..._.parameters,r+1).toArray(),i=u.length>r,l=u.slice(0,r).map(c=>c.id);return{hasMore:i,ids:l}},K=(e,t,a)=>{const r=new Set(a.filter(n=>n!==m));if(!a.includes(m))return r;const o=e.exec(`SELECT ${d(m)} AS doc FROM ${t} LIMIT ?`,f).toArray();for(const{doc:n}of o){const s=typeof n=="string"?R(n):void 0;if(s!==void 0)for(const _ of Object.keys(s))r.add(_)}return r},ie=(e,t)=>{const{column:a,table:r}=t;C(e,r);const o=d(r),n=b(e,o);if(!K(e,o,n).has(a))throw new T("UNKNOWN_COLUMN",`unknown column: ${a}`,{status:404});const s=M(a,n);if(s===void 0)throw new T("UNKNOWN_COLUMN",`unknown column: ${a}`,{status:404});const _=v(Math.trunc(t.limit??U),1,q),u=t.search?.trim()??"",i=E(n,u,t.filters),l=i===void 0?"":` WHERE ${i.where}`,c=i?.parameters??[],p=e.exec(`SELECT ${s.expression} AS value, COUNT(*) AS count FROM ${o}${l} GROUP BY ${s.expression} ORDER BY count DESC LIMIT ?`,...s.params,...c,...s.params,_+1).toArray();return{truncated:p.length>_,values:p.slice(0,_).map(g=>({count:Number(g.count),value:g.value}))}},ue=(e,t,a)=>{const r={},o=a.slice(0,f);for(const s of o)r[s]=[];if(o.length===0)return{references:r,storageColumns:t};const n=o.map(()=>"?").join(", ");for(const[s,_]of Object.entries(t)){if(I(s)||!x(e,s))continue;const u=d(s),i=b(e,u);for(const l of _){const c=M(l,i);if(c===void 0)continue;const p=e.exec(`SELECT id, ${c.expression} AS ref FROM ${u} WHERE ${c.expression} IN (${n})`,...c.params,...c.params,...o).toArray();for(const g of p)r[g.ref]?.push({column:l,id:g.id,table:s})}}return{references:r,storageColumns:t}},le=e=>{const t=e.map((r,o)=>{const n=Object.values(r.subs??{}).map(s=>({args:s.args,functionPath:s.functionPath,table:s.table}));return{admin:r.admin===!0,id:o,subscriptions:n}}),a=t.reduce((r,o)=>r+o.subscriptions.length,0);return{connections:t,totalConnections:t.length,totalSubscriptions:a}},z=20,ce=()=>({maxMs:0,passes:0,peakSocketsIterated:0,socketsDelivered:0,socketsIterated:0,totalMs:0}),de=(e,t,a,r)=>({maxMs:Math.max(e.maxMs,r),passes:e.passes+1,peakSocketsIterated:Math.max(e.peakSocketsIterated,t),socketsDelivered:e.socketsDelivered+a,socketsIterated:e.socketsIterated+t,totalMs:e.totalMs+r}),me=(e,t=z)=>{const a=new Map,r=new Map;for(const n of e){for(const s of Object.values(n.shapes??{})){const _=s.name??"(unknown shape)";a.set(_,(a.get(_)??0)+1)}for(const s of n.whispers??[])r.set(s,(r.get(s)??0)+1)}const o=[...[...a].map(([n,s])=>({kind:"shape",subscribers:s,topic:n})),...[...r].map(([n,s])=>({kind:"whisper",subscribers:s,topic:n}))];return o.sort((n,s)=>s.subscribers-n.subscribers||n.topic.localeCompare(s.topic)),{peakSubscribers:o[0]?.subscribers??0,topics:o.slice(0,t),totalConnections:e.length}};export{se as ADMIN_FUNCTIONS,te as ADMIN_FUNCTION_PREFIX,z as DEFAULT_FANOUT_TOPIC_LIMIT,re as FLAGS_FUNCTION_PREFIX,f as MAX_PAGE_SIZE,ae as RELATION_FUNCTION_PREFIX,ce as createFanoutCounters,X as datePrefixRange,ie as facetColumn,ue as findStorageReferences,oe as listTables,ne as readTablePage,de as recordFanoutPass,_e as selectMatchingIds,me as summarizeFanoutTopics,le as summarizeSubscriptions};
|
|
1
|
+
import{LunoraError as T}from"@lunora/errors";import{j as L,s as k}from"./do-sql-C7qrlm6-.mjs";import{quoteIdentifier as d}from"./quoteIdentifier-CObIFRhb.mjs";import{s as P}from"./wire-codec-Dsy70M3Q.mjs";const te="__lunora_admin__:",ae="__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,f=500,U=30,q=200,m="__doc__",R=e=>{try{const t=JSON.parse(e);return t!==null&&typeof t=="object"&&!Array.isArray(t)?t:void 0}catch{return}},W=e=>{const{[k]:t,...a}=e;return t===void 0?a:t===null||typeof t!="object"||Array.isArray(t)?{[k]:t,...a}:{...a,...P(t)}},j=(e,t)=>{if(!e.includes(m))return{columns:e,rows:t};const a=[];for(const s of t){const _=s[m],u=typeof _=="string"?R(_):void 0;if(u===void 0)return{columns:e,rows:t};const i=Object.fromEntries(Object.entries(s).filter(([l])=>l!==m));a.push({...i,...W(u)})}const r=e.filter(s=>s!==m),o=[],n=new Set(r);for(const s of a)for(const _ of Object.keys(s))n.has(_)||(n.add(_),o.push(_));return{columns:[...r,...o],rows:a}},w=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_"),v=(e,t,a)=>Math.min(Math.max(e,t),a),$=(e,t)=>{const a=e.exec(`SELECT COUNT(*) AS c FROM ${t}`).one();return Number(a.c)},oe=e=>{const t=e.exec("SELECT name FROM sqlite_master WHERE type = 'table' ORDER BY name").toArray(),a=[];for(const{name:r}of t)I(r)||a.push({name:r,rowCount:$(e,d(r))});return a},x=(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)||!x(e,t))throw new T("UNKNOWN_TABLE",`unknown table: ${t}`,{status:404})},b=(e,t)=>e.exec(`PRAGMA table_info(${t})`).toArray().map(a=>a.name),Q={eq:"=",gt:">",gte:">=",lt:"<",lte:"<=",ne:"<>"},B=e=>typeof e=="string"?e:typeof e=="number"||typeof e=="boolean"?String(e):"",M=(e,t)=>{const a=t.includes(e),r=t.includes(m);if(!(!a&&!r))return a?{expression:d(e),params:[]}:{expression:`json_extract(${d(m)}, ?)`,params:[`$.${L(e)}`]}},H=(e,t)=>{const a=M(e.column,t);if(a===void 0)return;const{expression:r,params:o}=a;return e.operator==="contains"?{params:[...o,B(e.value)],sql:w(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 a=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)||a<100)return;const n=Date.UTC(a,(r??1)-1,o??1);if(o!==void 0&&new Date(n).getUTCDate()!==o)return;let s;return o!==void 0?s=Date.UTC(a,(r??1)-1,o+1):r===void 0?s=Date.UTC(a+1,0,1):s=Date.UTC(a,r,1),{from:n,to:s}},E=(e,t,a)=>{const r=[],o=[];if(t!==""&&e.length>0){const n=e.map(_=>w(d(_)));o.push(...e.map(()=>t));const s=X(t);if(s!==void 0)for(const _ of e)n.push(`(${d(_)} >= ? AND ${d(_)} < ?)`),o.push(s.from,s.to);r.push(`(${n.join(" OR ")})`)}for(const n of a??[]){const s=H(n,e);s!==void 0&&(r.push(`(${s.sql})`),o.push(...s.params))}return r.length===0?void 0:{parameters:o,where:r.join(" AND ")}},Y=(e,t)=>{if(e===void 0)return;const a=M(e.column,t);if(a===void 0)return;const r=e.direction==="desc"?"DESC":"ASC";return{params:a.params,sql:`${a.expression} ${r}`}},ne=(e,t)=>{const{table:a}=t;C(e,a);const r=v(Math.trunc(t.limit??D),1,f),o=Math.max(0,Math.trunc(t.offset??0)),n=d(a),s=b(e,n),_=t.search?.trim()??"",u=h=>{if(t.refs===void 0)return h;const S={};for(const y of h.columns){const O=t.refs[y];O!==void 0&&(S[y]=O)}return Object.keys(S).length>0?{...h,refs:S}:h},i=E(s,_,t.filters),l=Y(t.orderBy,s),c=i===void 0?"":` WHERE ${i.where}`,p=l===void 0?"":` ORDER BY ${l.sql}`,g=i?.parameters??[],N=l?.params??[];let A;t.skipCount||(A=i===void 0?$(e,n):Number(e.exec(`SELECT COUNT(*) AS c FROM ${n}${c}`,...g).one().c));const F=e.exec(`SELECT * FROM ${n}${c}${p} LIMIT ? OFFSET ?`,...g,...N,r,o).toArray();return u({...j(s,F),total:A})},_e=(e,t)=>{const{table:a}=t;C(e,a);const r=v(Math.trunc(t.limit??f),1,f),o=d(a),n=b(e,o),s=t.search?.trim()??"",_=E(n,s,t.filters),u=_===void 0?e.exec(`SELECT id FROM ${o} LIMIT ?`,r+1).toArray():e.exec(`SELECT id FROM ${o} WHERE ${_.where} LIMIT ?`,..._.parameters,r+1).toArray(),i=u.length>r,l=u.slice(0,r).map(c=>c.id);return{hasMore:i,ids:l}},K=(e,t,a)=>{const r=new Set(a.filter(n=>n!==m));if(!a.includes(m))return r;const o=e.exec(`SELECT ${d(m)} AS doc FROM ${t} LIMIT ?`,f).toArray();for(const{doc:n}of o){const s=typeof n=="string"?R(n):void 0;if(s!==void 0)for(const _ of Object.keys(s))r.add(_)}return r},ie=(e,t)=>{const{column:a,table:r}=t;C(e,r);const o=d(r),n=b(e,o);if(!K(e,o,n).has(a))throw new T("UNKNOWN_COLUMN",`unknown column: ${a}`,{status:404});const s=M(a,n);if(s===void 0)throw new T("UNKNOWN_COLUMN",`unknown column: ${a}`,{status:404});const _=v(Math.trunc(t.limit??U),1,q),u=t.search?.trim()??"",i=E(n,u,t.filters),l=i===void 0?"":` WHERE ${i.where}`,c=i?.parameters??[],p=e.exec(`SELECT ${s.expression} AS value, COUNT(*) AS count FROM ${o}${l} GROUP BY ${s.expression} ORDER BY count DESC LIMIT ?`,...s.params,...c,...s.params,_+1).toArray();return{truncated:p.length>_,values:p.slice(0,_).map(g=>({count:Number(g.count),value:g.value}))}},ue=(e,t,a)=>{const r={},o=a.slice(0,f);for(const s of o)r[s]=[];if(o.length===0)return{references:r,storageColumns:t};const n=o.map(()=>"?").join(", ");for(const[s,_]of Object.entries(t)){if(I(s)||!x(e,s))continue;const u=d(s),i=b(e,u);for(const l of _){const c=M(l,i);if(c===void 0)continue;const p=e.exec(`SELECT id, ${c.expression} AS ref FROM ${u} WHERE ${c.expression} IN (${n})`,...c.params,...c.params,...o).toArray();for(const g of p)r[g.ref]?.push({column:l,id:g.id,table:s})}}return{references:r,storageColumns:t}},le=e=>{const t=e.map((r,o)=>{const n=Object.values(r.subs??{}).map(s=>({args:s.args,functionPath:s.functionPath,table:s.table}));return{admin:r.admin===!0,id:o,subscriptions:n}}),a=t.reduce((r,o)=>r+o.subscriptions.length,0);return{connections:t,totalConnections:t.length,totalSubscriptions:a}},z=20,ce=()=>({maxMs:0,passes:0,peakSocketsIterated:0,socketsDelivered:0,socketsIterated:0,totalMs:0}),de=(e,t,a,r)=>({maxMs:Math.max(e.maxMs,r),passes:e.passes+1,peakSocketsIterated:Math.max(e.peakSocketsIterated,t),socketsDelivered:e.socketsDelivered+a,socketsIterated:e.socketsIterated+t,totalMs:e.totalMs+r}),me=(e,t=z)=>{const a=new Map,r=new Map;for(const n of e){for(const s of Object.values(n.shapes??{})){const _=s.name??"(unknown shape)";a.set(_,(a.get(_)??0)+1)}for(const s of n.whispers??[])r.set(s,(r.get(s)??0)+1)}const o=[...[...a].map(([n,s])=>({kind:"shape",subscribers:s,topic:n})),...[...r].map(([n,s])=>({kind:"whisper",subscribers:s,topic:n}))];return o.sort((n,s)=>s.subscribers-n.subscribers||n.topic.localeCompare(s.topic)),{peakSubscribers:o[0]?.subscribers??0,topics:o.slice(0,t),totalConnections:e.length}};export{se as ADMIN_FUNCTIONS,te as ADMIN_FUNCTION_PREFIX,z as DEFAULT_FANOUT_TOPIC_LIMIT,re as FLAGS_FUNCTION_PREFIX,f as MAX_PAGE_SIZE,ae as RELATION_FUNCTION_PREFIX,ce as createFanoutCounters,X as datePrefixRange,ie as facetColumn,ue as findStorageReferences,oe as listTables,ne as readTablePage,de as recordFanoutPass,_e as selectMatchingIds,me as summarizeFanoutTopics,le as summarizeSubscriptions};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import"@lunora/errors";import"drizzle-orm";import{T as l,c as m,p as n,a as p,s as c,A as q,y as d,g as u,L as A,h as D,C as G,_ as S,N as _,S as f,O as C,E as O,I as h,D as I}from"./do-sql-
|
|
1
|
+
import"@lunora/errors";import"drizzle-orm";import{T as l,c as m,p as n,a as p,s as c,A as q,y as d,g as u,L as A,h as D,C as G,_ as S,N as _,S as f,O as C,E as O,I as h,D as I}from"./do-sql-C7qrlm6-.mjs";import{quoteIdentifier as T}from"./quoteIdentifier-CObIFRhb.mjs";import"./wire-codec-Dsy70M3Q.mjs";import"./runDrizzle-C3n5gJsk.mjs";import"./sql-projection-jfoe331H.mjs";import{serializeSqlValue as x}from"./serializeSqlValue-BR4UOWoP.mjs";export{l as AGG_COUNT,m as AGG_KEY,n as AGG_VALUE,p as DOC_COLUMN,c as DOC_ORIGINALS_KEY,q as aggUpsertSql,d as createIndexSql,u as decodeDocJson,A as encodeDocJson,D as geoTableName,G as isFtsAvailable,S as jsonPath,_ as jsonPathSql,f as qualifiedJsonPath,C as qualifiedJsonPathSql,T as quoteIdentifier,O as rowToDocument,x as serializeSqlValue,h as tableColumns,I as tryRowToDocument};
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{runSql as i}from"./runDrizzle-
|
|
1
|
+
import{runSql as i}from"./runDrizzle-C3n5gJsk.mjs";const a="__lunora_audit__",T=1e3,s=E=>{i(E,`CREATE TABLE IF NOT EXISTS "${a}" (
|
|
2
2
|
seq INTEGER PRIMARY KEY AUTOINCREMENT,
|
|
3
3
|
ts REAL NOT NULL,
|
|
4
4
|
op TEXT NOT NULL,
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{sql as e}from"drizzle-orm";import{runDrizzle as a}from"./runDrizzle-
|
|
1
|
+
import{sql as e}from"drizzle-orm";import{runDrizzle as a}from"./runDrizzle-C3n5gJsk.mjs";import{L as C,g as l}from"./do-sql-C7qrlm6-.mjs";import{ConflictError as L}from"./ConflictError-C8GtJmjS.mjs";const d="__cdc_log",I=t=>{a(t,e`CREATE TABLE IF NOT EXISTS ${e.identifier(d)} (
|
|
2
2
|
seq INTEGER PRIMARY KEY AUTOINCREMENT,
|
|
3
3
|
ts REAL NOT NULL,
|
|
4
4
|
${e.identifier("table")} TEXT NOT NULL,
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{sql as t}from"drizzle-orm";import{runDrizzle as n}from"./runDrizzle-
|
|
1
|
+
import{sql as t}from"drizzle-orm";import{runDrizzle as n}from"./runDrizzle-C3n5gJsk.mjs";const _="__client_watermark",l=i=>{n(i,t`CREATE TABLE IF NOT EXISTS ${t.identifier(_)} (
|
|
2
2
|
identity TEXT NOT NULL,
|
|
3
3
|
client_id TEXT NOT NULL,
|
|
4
4
|
last_mutation_id INTEGER NOT NULL,
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{LunoraError as y}from"@lunora/errors";import{runSql as n}from"./runDrizzle-
|
|
1
|
+
import{LunoraError as y}from"@lunora/errors";import{runSql as n}from"./runDrizzle-C3n5gJsk.mjs";const o="__lunora_migrations",D=100,$=3e4,U=1e4,b=r=>{n(r,`CREATE TABLE IF NOT EXISTS "${o}" (
|
|
2
2
|
id TEXT PRIMARY KEY,
|
|
3
3
|
direction TEXT NOT NULL,
|
|
4
4
|
status TEXT NOT NULL,
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{toErrorBody as f,LunoraError as S}from"@lunora/errors";import{a as p}from"./wire-codec-Dsy70M3Q.mjs";import{readStreamRun as k,deleteStreamRun as T,claimStreamRun as w,appendStreamChunk as y,finishStreamRun as R,trimStreamRuns as A,readStreamChunks as _}from"./appendStreamChunk-ksZYy1hZ.mjs";const g=5e4,E=64*1024*1024,b=864e5,N=36e5,M=(d,e)=>d===void 0||e.live?"attach":d.status==="complete"||d.status==="error"?e.resuming?"replay-terminal":"reclaim":e.resuming?"interrupted":"reclaim";class v{lastTrimAt=0;runs=new Map;sql;waitUntil;constructor(e){this.sql=e.sql,this.waitUntil=e.waitUntil}async attach(e){try{await this.attachOrThrow(e)}catch(r){const{body:t,redacted:i}=f(r,{fallbackCode:"INTERNAL_SERVER_ERROR",redactedMessage:"internal error"});i&&console.error("[@lunora/shard-engine] durable stream attach failed:",r),e.sink.fail({code:t.code,message:t.message})}}detach(e,r){this.runs.get(e)?.sinks.delete(r)}isLive(e){return this.runs.has(e)}async attachOrThrow(e){const r=this.sql(),{runKey:t,sinceChunk:i,sink:o}=e,s=k(r,t),u=i>0,n=this.runs.get(t),a=M(s,{live:n!==void 0,resuming:u}),c=()=>{for(const h of _(r,t,i))if(!o.chunk({data:JSON.parse(h.dataJson),seq:h.seq}))return!1;return!0};if(a==="replay-terminal"){c()&&(s?.status==="error"?o.fail({code:s.errorCode??"INTERNAL_SERVER_ERROR",message:s.error??"stream failed"}):o.complete());return}if(a==="interrupted"){c()&&o.fail({code:"STREAM_INTERRUPTED",message:"the producer for this durable stream did not survive; start a new run"});return}if(n){c()&&n.sinks.add(o);return}a==="reclaim"&&T(r,t),this.trim(r),w(r,t,Date.now(),e.ttlMs??b);const l={sinks:new Set([o])};this.runs.set(t,l);const m=this.produce(t,e.iterator,l);this.waitUntil?.(m),await m}async produce(e,r,t){const i=this.sql(),o=new AbortController;let s=0,u=0;try{for await(const n of r(o.signal)){const a=p(n),c=JSON.stringify(a);if(s+=1,u+=c.length,s>g||u>E)throw new S("STREAM_TOO_LONG",`durable stream exceeded its ceiling (${String(g)} chunks / ${String(E)} bytes); yield less, or drop \`durable\``,{status:507});y(i,e,s,c);for(const l of t.sinks)l.chunk({data:a,seq:s})||t.sinks.delete(l)}R(i,e,"complete",s);for(const n of t.sinks)n.complete()}catch(n){const{body:a,redacted:c}=f(n,{fallbackCode:"INTERNAL_SERVER_ERROR",redactedMessage:"internal error"});c&&console.error("[@lunora/shard-engine] unhandled durable stream error:",n),R(i,e,"error",s,{code:a.code,message:a.message});for(const l of t.sinks)l.fail({code:a.code,message:a.message})}finally{this.runs.delete(e)}}trim(e){const r=Date.now();if(!(r-this.lastTrimAt<=N)){this.lastTrimAt=r;try{A(e,r)}catch{}}}}export{v as DurableStreamRunner,E as MAX_DURABLE_STREAM_BYTES,g as MAX_DURABLE_STREAM_CHUNKS,M as decideDurableAttach};
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{sql as e}from"drizzle-orm";import{runDrizzle as r}from"./runDrizzle-
|
|
1
|
+
import{sql as e}from"drizzle-orm";import{runDrizzle as r}from"./runDrizzle-C3n5gJsk.mjs";const s="__global_shape_snapshot",d=n=>{r(n,e`CREATE TABLE IF NOT EXISTS ${e.identifier(s)} (
|
|
2
2
|
connection_id TEXT NOT NULL,
|
|
3
3
|
sub_id TEXT NOT NULL,
|
|
4
4
|
members TEXT NOT NULL,
|
package/dist/packem_shared/{IDEMPOTENCY_TABLE-DPFwgQbE.mjs → IDEMPOTENCY_TABLE-tQ5mnqvw.mjs}
RENAMED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{sql as t}from"drizzle-orm";import{runDrizzle as r}from"./runDrizzle-
|
|
1
|
+
import{sql as t}from"drizzle-orm";import{runDrizzle as r}from"./runDrizzle-C3n5gJsk.mjs";const E="__idempotency",m=i=>{r(i,t`CREATE TABLE IF NOT EXISTS ${t.identifier(E)} (
|
|
2
2
|
identity TEXT NOT NULL,
|
|
3
3
|
mutation_id TEXT NOT NULL,
|
|
4
4
|
result_json TEXT NOT NULL,
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{runSql as e,decodeJsonColumn as c,orNull as T}from"./runDrizzle-
|
|
1
|
+
import{runSql as e,decodeJsonColumn as c,orNull as T}from"./runDrizzle-C3n5gJsk.mjs";const r="__lunora_mail",l=500,_=256*1024,i=d=>d!==void 0&&d.length>_?`${d.slice(0,_)}
|
|
2
2
|
… [truncated by the dev mail catcher]`:d,E=d=>d===void 0?null:JSON.stringify(d),s=d=>{e(d,`CREATE TABLE IF NOT EXISTS "${r}" (
|
|
3
3
|
id TEXT PRIMARY KEY,
|
|
4
4
|
captured_at INTEGER NOT NULL,
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{LunoraError as g}from"@lunora/errors";import{n as Bt,S as qt,x as Qe,T as Se,y as Ut,c as Pt}from"./ctx-db-companions-c12P7dbv.mjs";import{sql as r}from"drizzle-orm";import{s as Ht}from"./wire-codec-Dsy70M3Q.mjs";import{aggregateSqlFunction as Re,normalizeCountArgument as Gt,throwingScheduler as jt}from"./AGGREGATE_SQL_FUNCTION-CTo0-9iZ.mjs";import{encodeAggregateKey as De,readAggregateValue as Le,aggregateTableName as Oe}from"./aggregateTableName-DgYMC5tr.mjs";import{mergeWhere as Y,CountRlsUnsupportedError as Fe,selectIndexForGroupBy as Qt,selectIndexForCount as Kt,selectIndexForAggregate as Yt}from"./CountRlsUnsupportedError-8BqPYQoP.mjs";import{backfillSearchIndexesForTable as zt}from"./backfillAggregateIndexes-BEMWTEq1.mjs";import{backfillAggregateIndexes as Fr,backfillRankIndexes as Wr,backfillSearchIndexes as Br}from"./backfillAggregateIndexes-BEMWTEq1.mjs";import{appendCdcChange as Jt}from"./CDC_LOG_TABLE-DH-KHUfU.mjs";import{CDC_LOG_TABLE as Ur,applyCdcChanges as Pr,bumpCdcEpoch as Hr,minCdcSeq as Gr,readCdcChanges as jr,readCdcCursor as Qr,readCdcEpoch as Kr,trimCdcChanges as Yr}from"./CDC_LOG_TABLE-DH-KHUfU.mjs";import{computeRankPage as at}from"./computeRankPage-D1ygctSC.mjs";import{SCAN_DEP as U}from"./SCAN_DEP-D_yR9EeV.mjs";import{runDrizzle as W}from"./runDrizzle-C3n5gJsk.mjs";import{a as H,L as se,p as Ae,T as We,c as xe,N as J,E as ce,I as St,C as Vt,D as Rt,h as Xt,O as st}from"./do-sql-C7qrlm6-.mjs";import{WORKERD_SQLITE_LIMITS as At,unionAll as Pe,sqliteInList as Zt}from"./param-CYxL68V-.mjs";import{coveringGeohashes as en,boundingBoxGeohashes as tn,pointInBoundingBox as nn,haversineMeters as rn}from"./GEO_DEFAULT_PRECISION-DyI5zggj.mjs";import{NotFoundError as on}from"./NotFoundError-BhF7FeFr.mjs";import{normalizeOrderKeys as an,buildSeekWhere as xt,decodeCursor as He,applySelect as dt,encodeCursor as Ge,softDeleteScope as le,buildSeekBeforeWhere as sn}from"./applySelect-UY-o13Ia.mjs";import{sortColumnName as lt,resolveRankPartition as dn,encodePartitionKey as ln,RANK_TIEBREAK as cn,rankTableName as ct}from"./RANK_TIEBREAK-DDtST3gN.mjs";import{indexKeysForRow as un,buildIndexRange as fn}from"./buildIndexRange-DFsdtPjD.mjs";import{assertFlatPredicate as Be,resolveRelationPredicates as ut}from"./DEFAULT_MAX_RELATION_KEYS-DjKka36Z.mjs";import{runRowValidators as qe,resolveWith as ft,relationHooks as ht,applyOnDelete as hn,fanOutScalarCounts as mn}from"./applyOnDelete-By23GK-k.mjs";import{guardWriter as pn}from"./RLS_UNWRAP_SYMBOL-DcqORh2s.mjs";import{f as $n}from"./sql-projection-jfoe331H.mjs";import{createSystemReader as wn}from"./createSystemReader-DcDcrtM3.mjs";import{ConflictError as pe}from"./ConflictError-C8GtJmjS.mjs";import{runTriggers as gn}from"./hasTrigger-CbkOHExZ.mjs";import{compileWhereSql as te}from"./compileWhereSql-B3hq_v98.mjs";import{CLIENT_WATERMARK_TABLE as Jr,advanceClientWatermark as Vr,migrateClientWatermark as Xr,readClientWatermark as Zr}from"./CLIENT_WATERMARK_TABLE-LrKfdxyt.mjs";import{GLOBAL_SHAPE_SNAPSHOT_TABLE as to,deleteGlobalShapeSnapshot as no,deleteGlobalShapeSnapshotsForConnection as ro,migrateGlobalShapeSnapshot as oo,readGlobalShapeSnapshot as io,writeGlobalShapeSnapshot as ao}from"./GLOBAL_SHAPE_SNAPSHOT_TABLE-B2LKe4KU.mjs";import{IDEMPOTENCY_TABLE as lo,readIdempotent as co,trimIdempotent as uo,writeIdempotent as fo}from"./IDEMPOTENCY_TABLE-tQ5mnqvw.mjs";import{runShardMigrations as mo}from"./runShardMigrations-BAtfEXbB.mjs";import{SEARCH_STATE_TABLE as $o}from"./SEARCH_STATE_TABLE-DRk_SB72.mjs";import{selectShapeMemberIds as go,selectShapeRows as bo}from"./selectShapeMemberIds-WzxOG62k.mjs";import{serializeSqlValue as ie}from"./serializeSqlValue-BR4UOWoP.mjs";import{quoteIdentifier as bn}from"./quoteIdentifier-CObIFRhb.mjs";const En=o=>{const i=new TextEncoder().encode(o);let t="";for(const d of i)t+=String.fromCodePoint(d);return btoa(t)},yn=o=>{const i=atob(o),t=Uint8Array.from(i,d=>d.codePointAt(0)??0);return new TextDecoder().decode(t)},Nn=()=>new g("BAD_REQUEST","invalid cursor"),mt=16,pt=8,V=1024,Ke=(o,i)=>i.query(o),_n=(o,i,t)=>{const d=Bt(o,t);if(d.length===0)return 0;let f=0;for(const[m,b]of i.entries()){const S=m===i.length-1;let y=0;for(const w of d)(S?w.startsWith(b):w===b)&&(y+=1);if(y===0)return 0;f+=y}return f},Tn=(o,i)=>{if(!i)return{exact:!0,lower:o,upper:o};const t=[...o].at(-1)??"",d=(t.codePointAt(0)??0)+1;if(d>=55296&&d<=57343||d>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(d)}},Sn=(o,i,t)=>{const d={eq:(f,m)=>{if(!o.definition.filterFields?.includes(f))throw new g("INTERNAL",`field "${f}" is not a filter field of search index "${o.indexName}" on table "${i}"`);if(o.filters.length>=pt)throw new g("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:m}),d},search:(f,m)=>{const b=o;if(f!==b.definition.field)throw new g("INTERNAL",`search index "${b.indexName}" on table "${i}" indexes "${b.definition.field}", not "${f}"`);const S=Ke(m,t).length;if(S>mt)throw new g("BAD_REQUEST",`search index "${b.indexName}" on table "${i}": at most ${String(mt)} search terms are supported (got ${String(S)})`);return b.field=f,b.query=m,b.hasQuery=!0,d}};return d},Rn=o=>{if(o.length>V)throw new g("BAD_REQUEST",`more than ${String(V)} documents match this search — narrow it with filters or read it a page at a time with .paginate()`)},An=o=>Math.min(o.offset+o.numItems+1,V),xn=o=>En(`search:${String(o)}`),In=o=>{let i;try{i=yn(o)}catch{return}if(!i.startsWith("search:"))return;const t=Number(i.slice(7));return Number.isInteger(t)&&t>=0?t:void 0},vn=o=>{if(typeof o.endCursor=="string")throw new g("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?In(o.cursor):0;if(t===void 0)throw Nn();if(t+i>V)throw new g("BAD_REQUEST",`search pagination reaches past the ${String(V)}-document limit (offset ${String(t)} + ${String(i)} requested) — narrow the query or the filters instead`);return{numItems:i,offset:t}},Cn=(o,i)=>{const t=i.offset+i.numItems,d=i.numItems>0&&o.length>t;return{continueCursor:d?xn(t):null,isDone:!d,page:o.slice(i.offset,t)}},Mn=o=>{if(o===void 0)return V+1;if(!Number.isFinite(o))return V;const i=Math.max(0,Math.floor(o));if(i>V)throw new g("BAD_REQUEST",`search returns at most ${String(V)} 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,Dn=o=>{if(!kn.test(o))throw new g("INTERNAL",`invalid clientId ${JSON.stringify(o)}: a client-supplied row id must be a UUID`)},$t=50,It=500,wt=Math.floor(At.boundParams/3),me=At.boundParams,Ln=128,de=(o,i,t)=>{const d=i??It;if(o>d)throw new g("BATCH_LIMIT_EXCEEDED",`${t}: batch of ${String(o)} exceeds the limit of ${String(d)} (raise options.limit or chunk the call)`,{status:400})},On=o=>{const i={eq:(t,d)=>(o.sqlConditions.push({comparator:"=",field:t,value:d}),i),gt:(t,d)=>(o.sqlConditions.push({comparator:">",field:t,value:d}),i),gte:(t,d)=>(o.sqlConditions.push({comparator:">=",field:t,value:d}),i),lt:(t,d)=>(o.sqlConditions.push({comparator:"<",field:t,value:d}),i),lte:(t,d)=>(o.sqlConditions.push({comparator:"<=",field:t,value:d}),i)};return i},Fn=o=>Math.max(o,V),vt=(o,i)=>{const t=o.filters.map(d=>r`${J(d.field)} = ${ie(d.value)}`);return i&&t.push(i),t},Wn=(o,i,t,d,f)=>{const m=Ke(t.query,Qe(t.definition.language));if(m.length===0)return[];const b=Pt(i,t.indexName),S=`${b}__vocab`,y=m.length-1,w=m.map((L,M)=>{const G=Tn(L,M===y),j=G.exact?r`${r.identifier("term")} = ${G.lower}`:r`${r.identifier("term")} >= ${G.lower} AND ${r.identifier("term")} < ${G.upper}`;return r`SELECT ${r.identifier("doc")}, ${r.raw(String(M))} AS ${r.identifier("__term__")}, COUNT(*) AS ${r.identifier("__n__")} FROM ${r.identifier(S)} WHERE ${j} GROUP BY ${r.identifier("doc")}`}),N=m.map((L,M)=>r`SUM(CASE WHEN u.${r.identifier("__term__")} = ${r.raw(String(M))} THEN u.${r.identifier("__n__")} ELSE 0 END)`),_=r`SELECT f.${r.identifier(Se)} AS ${r.identifier(Se)}, ${r.join(N,r` + `)} AS ${r.identifier("__score__")} FROM (${Pe(w)}) u JOIN ${r.identifier(b)} f ON f.rowid = u.${r.identifier("doc")} GROUP BY f.${r.identifier(Se)} HAVING ${r.join(N.map(L=>r`${L} > 0`),r` AND `)}`,T=vt(t,f);let v=r`SELECT m.id, m._creationTime, m.${r.identifier(H)}, s.${r.identifier("__score__")} AS ${r.identifier("__score__")} FROM (${_}) s JOIN ${r.identifier(i)} m ON m.id = s.${r.identifier(Se)}`;T.length>0&&(v=r`${v} WHERE ${r.join(T,r` AND `)}`),v=r`${v} ORDER BY s.${r.identifier("__score__")} DESC, m._creationTime DESC, m.id ASC LIMIT ${r.raw(String(d))}`;const O=[];for(const L of W(o,v)){const M=Rt(L);if(M){const G=L.__score__;O.push({document:M,score:typeof G=="number"?G:Number(G??0)})}}return O},Bn=(o,i,t,d,f)=>{const m=Qe(t.definition.language),b=Ke(t.query,m);if(b.length===0)return[];const S=vt(t,f);let y=r`SELECT id, _creationTime, ${r.identifier(H)} FROM ${r.identifier(i)}`;S.length>0&&(y=r`${y} WHERE ${r.join(S,r` AND `)}`),y=r`${y} ORDER BY _creationTime DESC, id ASC LIMIT ${r.raw(String(Fn(d)))}`;const w=W(o,y).toArray(),N=[];for(const _ of w){const T=Rt(_);if(!T)continue;const v=_n(Ut(T,t.definition),b,m);v>0&&N.push({creationTime:typeof T._creationTime=="number"?T._creationTime:0,doc:T,id:typeof T._id=="string"?T._id:"",score:v})}return N.sort((_,T)=>T.score-_.score||T.creationTime-_.creationTime||_.id.localeCompare(T.id)),N.slice(0,d).map(_=>({document:_.doc,score:_.score}))},Ue=(o,i,t,d)=>{if(!Number.isFinite(o.lat)||o.lat<-90||o.lat>90||!Number.isFinite(o.lng)||o.lng<-180||o.lng>180)throw new g("BAD_REQUEST",`geo index "${d}" on table "${t}": ${i} must have a finite lat in [-90, 90] and lng in [-180, 180]`)},qn=(o,i)=>{const t=o,d={near:(f,m)=>{if(t.within)throw new g("INTERNAL",`geo index "${t.indexName}" on table "${i}": call .near() or .within(), not both`);if(Ue(f,".near() point",i,t.indexName),!Number.isFinite(m)||m<=0)throw new g("BAD_REQUEST",`geo index "${t.indexName}" on table "${i}": .near() radiusMeters must be a finite number > 0, got ${String(m)}`);return t.near={point:{lat:f.lat,lng:f.lng},radiusMeters:m},d},within:f=>{if(t.near)throw new g("INTERNAL",`geo index "${t.indexName}" on table "${i}": call .near() or .within(), not both`);if(Ue(f.sw,".within() sw corner",i,t.indexName),Ue(f.ne,".within() ne corner",i,t.indexName),f.sw.lat>f.ne.lat)throw new g("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 g("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}},d}};return d},Un=(o,i)=>{const t=o[i];if(t===null||typeof t!="object")return;const{lat:d,lng:f}=t;return typeof d=="number"&&typeof f=="number"?{lat:d,lng:f}:void 0},Pn=(o,i)=>{const t=Un(o,i.definition.field);if(!t)return;const d=typeof o._creationTime=="number"?o._creationTime:0;if(i.near){const f=rn(i.near.point,t);return f<=i.near.radiusMeters?{creationTime:d,distance:f}:void 0}return nn(t,i.within)?{creationTime:d,distance:0}:void 0},Hn=(o,i,t,d)=>{if(!t.near&&!t.within)throw new g("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),m=Xt(i,t.indexName),b=f.map(_=>r`(g.${r.identifier("__geohash__")} >= ${_} AND g.${r.identifier("__geohash__")} < ${`${_}{`})`),S=[r`(${r.join(b,r` OR `)})`];d&&S.push(d);const y=r`SELECT m.id, m._creationTime, m.${r.identifier(H)} FROM ${r.identifier(m)} g JOIN ${r.identifier(i)} m ON m.id = g.${r.identifier("__id__")} WHERE ${r.join(S,r` AND `)}`,w=W(o,y).toArray(),N=[];for(const _ of w){const T=ce(_),v=T?Pn(T,t):void 0;T&&v&&N.push({creationTime:v.creationTime,distance:v.distance,doc:T})}return N.sort((_,T)=>_.distance-T.distance||T.creationTime-_.creationTime),N},Ct=(o,i,t,d)=>{const f=[];for(const m of o)if(i.every(b=>b(d(m)))&&(f.push(m),typeof t=="number"&&f.length>=t))break;return f},Gn=(o,i,t,d,f,m=()=>{})=>{const b=t.within!==void 0,S=Hn(o,i,t,f).map(y=>({distanceMeters:b?null:y.distance,document:y.doc}));return m(S.length),typeof d=="number"?S.slice(0,Math.max(0,Math.floor(d))):S},Mt=(o,i,t,d,f,m=()=>{})=>{const{geo:b}=t;if(!b)throw new g("INTERNAL","runGeoTerminalScored called without a staged geo query");const S=t.inMemoryFilters.length>0,y=Gn(o,i,b,S?void 0:f,d,m);return S?Ct(y,t.inMemoryFilters,f,w=>w.document):y},jn=(o,i,t,d,f,m=()=>{})=>Mt(o,i,t,d,f,m).map(b=>b.document),Qn=(o,i,t,d,f,m,b=()=>{})=>{const S=[];for(const _ of t.sqlConditions)S.push(r`${J(_.field)} ${r.raw(_.comparator)} ${ie(_.value)}`);d&&S.push(d);let y=r`SELECT id, _creationTime, ${r.identifier(H)} FROM ${r.identifier(i)}`;S.length>0&&(y=r`${y} WHERE ${r.join(S,r` AND `)}`),y=r`${y} ORDER BY ${f}`,typeof m=="number"&&t.inMemoryFilters.length===0&&(y=r`${y} LIMIT ${r.raw(String(Math.max(0,Math.floor(m))))}`);const w=W(o,y).toArray();b(w.length);const N=[];for(const _ of w){const T=ce(_);if(T&&t.inMemoryFilters.every(v=>v(T))&&(N.push(T),typeof m=="number"&&N.length>=m))break}return N},oe={fieldRef:J,serialize:ie},kt=(o,i)=>{const t=i===void 0?void 0:o.shape[i];return t!==void 0&&$n(t)},gt=(o,i)=>i.some(t=>kt(o,t)),bt=(o,i,t)=>{if(kt(o,i))throw new g("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`)},Kn=o=>{let i=0;const t=[],d={fieldRef:J,relationExists:f=>{const{childWhere:m,negated:b,parentTable:S,relation:y}=f,w=`__rel_${String(i)}`,N=t.at(-1)??S;i+=1,o(y.table,U);const _=y.kind==="one"?y.field:y.references,T=y.kind==="one"?y.references:y.field,v=r`${st(w,T)} = ${st(N,_)}`;t.push(w);const O=te(m,d);t.pop();const L=O?r`${v} AND ${O}`:v,M=r`EXISTS (SELECT 1 FROM ${r.identifier(y.table)} AS ${r.identifier(w)} WHERE ${L})`;return b?r`NOT ${M}`:M},serialize:ie};return d},Dt=o=>{const i=o.map(t=>r`${J(t.field)} ${r.raw(t.direction==="desc"?"DESC":"ASC")}`);return o.some(t=>t.field==="_id"||t.field==="id")||i.push(r`${J("id")} ASC`),r.join(i,r`, `)},Yn={"<":"lt","<=":"lte","=":"eq",">":"gt",">=":"gte"},zn=o=>{const i=o.order;return o.indexFields.length>0?o.indexFields.map(t=>({direction:i,field:t})):[{direction:i,field:"_creationTime"}]},Jn=(o,i,t,d)=>{const f=o.sqlConditions.map(m=>({[m.field]:{[Yn[m.comparator]??"eq"]:m.value}}));if(t&&f.push(xt(i,He(t))),d&&f.push(sn(i,He(d))),f.length!==0)return f.length===1?f[0]:{AND:f}},Vn=(o,i,t)=>{const d=[];for(const f of o){const m=ce(f);if(m&&i.every(b=>b(m))&&(d.push(m),t!==void 0&&d.length>t))break}return d},Xn=(o,i,t,d,f,m=()=>{})=>{const b=Math.max(0,Math.floor(d.numItems)),S=zn(t),y=typeof d.endCursor=="string",w=te(Jn(t,S,d.cursor,d.endCursor),oe),N=f&&w?r`${w} AND ${f}`:f??w;let _=r`SELECT id, _creationTime, ${r.identifier(H)} FROM ${r.identifier(i)}`;N&&(_=r`${_} WHERE ${N}`),_=r`${_} ORDER BY ${Dt(S)}`;const T=t.inMemoryFilters.length>0;!T&&!y&&(_=r`${_} LIMIT ${r.raw(String(b+1))}`);const v=W(o,_).toArray();m(v.length);const O=Vn(v,t.inMemoryFilters,T||y?void 0:b);if(y){const j=O.length>=2?O[Math.floor(O.length/2)-1]:void 0;return{continueCursor:d.endCursor??null,isDone:!0,page:O,splitCursor:j?Ge(j,S):null}}const L=O.length>b,M=L?O.slice(0,b):O,G=M.at(-1);return{continueCursor:L&&G?Ge(G,S):null,isDone:!L,page:M}};class Zn extends g{constructor(i="unique() found more than one matching document"){super("NOT_UNIQUE",i,{name:"NotUniqueError"})}}const er=/\s/u,tr=String.fromCodePoint(0),Et=(o,i,t)=>{if(!o.tables[i])throw new g("INTERNAL",`unknown table: ${i}`);return typeof t!="string"||t.length===0||er.test(t)||t.includes(tr)?null:t},nr=(o,i,t,d=()=>{},f=()=>{},m=()=>{})=>{const b=i.tables[t];if(!b)throw new g("INTERNAL",`unknown table: ${t}`);const S=le(b.softDeleteMode,void 0),y=S?te(S,oe):void 0,w={indexFields:[],indexName:void 0,inMemoryFilters:[],order:"asc",sqlConditions:[]};let N=0;const _=E=>{const{search:I}=w;if(!I)throw new g("INTERNAL","runSearchFetch called without a staged search");zt(o,t,b);const C=w.inMemoryFilters.length>0,k=Mn(C?void 0:E),z=Vt(o)?Wn(o,t,I,k,y):Bn(o,t,I,k,y);return C?(N=z.length,Ct(z,w.inMemoryFilters,E,ne=>ne.document)):(E===void 0&&Rn(z),z)},T=E=>_(E).map(I=>I.document),v=E=>{const I=vn(E);return Cn(T(An(I)),I)},O=()=>{const E=w.indexFields.length>0?w.indexFields:["_creationTime"],I=w.order==="desc"?"DESC":"ASC";return r.join(E.map(C=>r`${J(C)} ${r.raw(I)}`),r`, `)},L=()=>{if(w.search||w.geo||w.indexName===void 0){f(void 0);return}f(fn(t,w.indexName,w.indexFields,w.sqlConditions,ie))},M=E=>{L();let I=0;const C=(()=>{if(w.search){const k=T(E);return I=N,k}return w.geo?jn(o,t,w,y,E,k=>{I=k}):Qn(o,t,w,y,O(),E,k=>{I=k})})();return m(Math.max(I,C.length)),C},G=()=>{if(!w.search&&!w.geo)throw new g("INTERNAL",`ctx.db.query("${t}").collectWithScores() requires a staged .withSearchIndex(...) or .withGeoIndex(...)`);L();let E=0;const I=(()=>{if(w.search){const C=_(void 0);return E=N,C}return Mt(o,t,w,y,void 0,C=>{E=C})})();return m(Math.max(E,I.length)),I},j={async*[Symbol.asyncIterator](){const E=[...w.inMemoryFilters];let I;w.inMemoryFilters=[];try{for(;;){const C=await j.paginate({cursor:I??null,numItems:Ln});for(const k of C.page)E.every(z=>z(k))&&(yield k);if(C.isDone||C.continueCursor===null)return;I=C.continueCursor}}finally{w.inMemoryFilters=E}},async collect(){return M(void 0)},async collectWithScores(){return G()},filter(E){return w.inMemoryFilters.push(E),j},async first(){return M(w.inMemoryFilters.length>0?void 0:1)[0]??null},order(E){return w.order=E==="desc"?"desc":"asc",j},async paginate(E){let I=0;if(L(),w.search){const k=v(E);return m(k.page.length),k}if(w.geo)throw new g("INTERNAL","pagination is not supported on geo queries; use .take(n) or .collect()");const C=Xn(o,t,w,E,y,k=>{I=k});return m(Math.max(I,C.page.length)),C},async take(E){return M(E)},async unique(){const E=M(w.inMemoryFilters.length>0?void 0:2);if(E.length>1)throw new Zn(`unique() on table "${t}" matched ${String(E.length)} documents; expected at most one`);return E[0]??null},withGeoIndex(E,I){const C=(b.geoIndexes??[]).find(z=>z.name===E);if(!C)throw new g("INTERNAL",`unknown geo index "${E}" on table "${t}"`);d(t,E,"geo");const k={definition:C,indexName:E};if(w.geo=k,I(qn(k,t)),!k.near&&!k.within)throw new g("INTERNAL",`geo index "${E}" on table "${t}" requires a .near(point, radius) or .within(box) call`);return j},withIndex(E,I){const C=b.indexes.find(k=>k.name===E);if(!C)throw new g("INTERNAL",`unknown index "${E}" on table "${t}"`);return d(t,E,"index"),w.indexName=E,w.indexFields=C.fields,I&&I(On(w)),j},withSearchIndex(E,I){const C=(b.searchIndexes??[]).find(z=>z.name===E);if(!C)throw new g("INTERNAL",`unknown search index "${E}" on table "${t}"`);d(t,E,"search");const k={definition:C,field:C.field,filters:[],hasQuery:!1,indexName:E,query:""};if(w.search=k,I(Sn(k,t,Qe(C.language))),!k.hasQuery)throw new g("INTERNAL",`search index "${E}" on table "${t}" requires a .search(field, query) call`);return j}};return j},yt=(o,i,t)=>{const d={...i};for(const[f,m]of St(o)){if(m.serverDefault){d[f]=m.serverDefault({auth:t});continue}d[f]===void 0&&(m.defaultFn?d[f]=m.defaultFn():"defaultValue"in m&&(d[f]=m.defaultValue))}return d},Nt=(o,i,t,d)=>{const f=t;for(const[m,b]of St(o)){if(b.serverDefault){m in i&&(f[m]=b.serverDefault({auth:d}));continue}b.onUpdateFn&&!(m in i)&&(f[m]=b.onUpdateFn())}},_t=(o,i)=>{for(const t of Object.keys(i))if(i[t]===void 0)throw new g("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),je=(o,i,t)=>{try{W(o,t)}catch(d){throw or(d)?new pe(`unique constraint violation on "${i}"`,"unique"):d}},Ie=(o,i,t)=>{if(je(o,i,t),W(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,d,f,m,b)=>{const S=[];for(let _=0;_<t.length+1;_+=1){const T=[];for(let M=0;M<_;M+=1)T.push(r`${r.identifier(t[M])} IS ${m[M]}`);const v=t[_],O=d[_];if(v!==void 0&&O!==void 0){const M=O.direction==="desc"?">":"<";T.push(r`${r.identifier(v)} ${r.raw(M)} ${m[_]}`)}else T.push(r`${r.identifier(cn)} < ${b}`);const[L]=T;S.push(T.length===1&&L!==void 0?L:r`(${r.join(T,r` AND `)})`)}const y=r.join(S,r` OR `),w=W(o,r`SELECT COUNT(*) AS c FROM ${r.identifier(i)} WHERE ${r.identifier("__partition__")} = ${f} AND (${y})`).one(),N=W(o,r`SELECT COUNT(*) AS c FROM ${r.identifier(i)} WHERE ${r.identifier("__partition__")} = ${f}`).one();return{before:w.c,total:N.c}},Dr=o=>{const{sql:i}=o,{schema:t}=o,d=o.broadcast??(()=>{}),f=(e,...n)=>{const a=t.tables[e]?.indexes;if(!a||a.length===0)return;const c=[];for(const h of n)h&&c.push(...un(a,h,ie));return c.length>0?c:void 0},{headroom:m}=o;let b=!1;const S=async e=>{const n=b;b=!0;try{return await e()}finally{b=n}},y=o.onRead??(()=>{}),w=o.onReadRange??(e=>{y(e.table,U)}),N=(e,n)=>{n!==void 0&&n!==U&&!b&&m?.recordRead(1),y(e,n)},_=o.onIndexUse??(()=>{}),T=o.onWrite??(()=>{}),v=e=>{b||m?.recordWrite(e)},O=async e=>{v(e.doc),await T(e)},{cache:L}=o,M=o.clock??(()=>Date.now()),G=o.idGenerator??(()=>crypto.randomUUID()),j=o.scheduler??jt,{globalDb:E}=o,I=o.auth??{identity:null,userId:null},C=o.cdc??!1,k=j,z=wn({scheduler:typeof k.list=="function"&&typeof k.get=="function"?k:void 0,storage:o.storage}),ne=(e,n,a,c)=>{C&&Jt(i,M(),e,n,a,c)},ae=e=>t.tables[e]?.shardMode?.kind==="global",Ye=(e,n)=>{if(ae(e)){if(!E)throw new g("INTERNAL",`cross-backend ${n} for global table '${e}' requires a globalDb writer — pass one to createShardCtxDb({ globalDb })`);return E}return B},ve=e=>Ye(e,"cascade"),K=(e,n)=>{if(ae(e)){if(!E)throw new g("INTERNAL",`${n} on global table '${e}' requires a globalDb writer — pass one to createShardCtxDb({ globalDb })`);return E}},ze=async(e,n,a,c,h)=>{h&&v(a);const u=await e.insert(n,a,c);return d({key:u,op:"insert",row:{...a,_id:u},table:n}),u},Ce=(e,n)=>Ye(e,"relation load").findMany(e,n),Je=(e,n)=>(ae(e)&&N(e,U),Ce(e,n)),Lt=e=>!ae(e.table),Ve=o.relationExistsPushDown??"auto",Xe=Ve!=="never",{maxRelationKeys:Ze}=o,$e=(e,n,a)=>ut(e,{fetcher:Je,maxRelationKeys:Ze,relationBaseWhere:a,schema:t,tableName:n}),et=async(e,n,a,c)=>{const h=K(e,"relation grouped count");if(h)return N(e,U),mn((P,x)=>h.count(P,x),e,n,a,c);const u=t.tables[e];if(!u)throw new g("INTERNAL",`unknown table: ${e}`);N(e,U);const s=le(u.softDeleteMode,void 0),l={[n]:{in:a}},p=Y(Y(l,c),s),R=await $e(p,e,void 0),$=te(R,oe),A=J(n);let D=r`SELECT ${A} AS __fk__, COUNT(*) AS count FROM ${r.identifier(e)}`;$&&(D=r`${D} WHERE ${$}`),D=r`${D} GROUP BY ${A}`;const F=W(i,D).toArray();return new Map(F.map(P=>[P.__fk__,P.count]))};let we=0;const tt=new Set;for(const[e,n]of Object.entries(t.tables))for(const a of Object.values(n.triggerMap??{}))tt.add(`${e} ${a.timing} ${a.op}`);const X=(e,n,a)=>tt.has(`${e} ${n} ${a}`),Z=async(e,n,a)=>{if(we+=1,we>$t)throw we-=1,new pe(`trigger recursion exceeded ${String($t)} levels on "${a.table}" — check for a self-triggering write`,"trigger");try{await gn({ctx:Ft,event:a,op:n,schema:t,tableName:a.table,timing:e})}finally{we-=1}},{ensureBackfilledForTable:ue,ensureBackfilledIndex:Me,ensureRankBackfilled:ke,ensureRankBackfilledForTable:fe,syncAggregates:ge,syncCompanionsForInsert:nt,syncGeo:be,syncRanks:he,syncSearch:Ee}=qt({broadcast:d,indexKeysFor:(e,n)=>f(e,n),invalidateCache:(e,n,a)=>L?.invalidate(e,n,f(e,a)),recordCdc:ne,schema:t,sql:i}),rt=(e,n,a)=>{const{shardMode:c}=n;if(c?.kind==="shardBy"&&!(c.field!==void 0&&(a.partitionBy??[]).includes(c.field)))throw Object.assign(new Error(`rank index "${a.name}" on "${e}" partitions across shards (shard key "${c.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 a=ot(n);for(let c=0;c<a.length;c+=me){const h=a.slice(c,c+me).map(R=>r`SELECT ${r.raw(`'${R.replaceAll("'","''")}'`)} AS __t__, id, _creationTime, ${r.identifier(H)} FROM ${r.identifier(R)} WHERE id = ${e}`),[u]=W(i,r`${Pe(h)} LIMIT 1`).toArray();if(!u)continue;const s=u.__t__,l=ce(u);if(typeof s!="string"||!l)return;const p=u[H];return{docJson:typeof p=="string"?p:se(p??{}),row:l,tableName:s}}},Ot=(e,n)=>{const a=[...new Set(e)],c=new Map;if(a.length===0)return c;const h=ot(n);for(let u=0;u<h.length;u+=me){const s=h.slice(u,u+me),l=Math.floor(me/s.length),p=Zt(r`${r.identifier("id")}`,a,!1,l),R=s.map($=>r`SELECT ${r.raw(`'${$.replaceAll("'","''")}'`)} AS __t__, id FROM ${r.identifier($)} WHERE ${p}`);for(const $ of W(i,Pe(R))){const{id:A,__t__:D}=$;typeof D=="string"&&typeof A=="string"&&c.set(A,D)}}return c},it={assertRankPartitionLocal:rt,ensureRankBackfilled:ke,onRead:N,rowToDocument:ce,schema:t,sql:i},B={system:z,async aggregate(e,n){const a=K(e,"aggregate");if(a)return N(e,U),a.aggregate(e,n);const c=t.tables[e];if(!c)throw new g("INTERNAL",`unknown table: ${e}`);if(Re(n.op),n.op==="count")return B.count(e,{baseWhere:n.baseWhere,relationBaseWhere:n.relationBaseWhere,restrictsCounts:n.restrictsCounts,where:n.where});if(!n.field)throw new g("INTERNAL",`aggregate(${e}, { op: "${n.op}" }): "field" is required for non-count reducers`);N(e,U);const h=le(c.softDeleteMode,void 0),u=Y(Y(n.baseWhere,n.where),h),s=await $e(u,e,n.relationBaseWhere),l=s!==u;if(c.aggregateIndexes&&!n.baseWhere&&!l&&(!h||gt(c,[n.field]))){const F=Yt(c.aggregateIndexes,n.op,n.field,n.where);if(F){Me(e,F.index);const P=De(F.index.by??[],F.key),x=Oe(e,F.index.name),Q=W(i,r`SELECT ${Ae} AS value, ${We} AS count FROM ${r.identifier(x)} WHERE ${xe} = ${P}`).toArray()[0];return Le(n.op,Q)}}bt(c,n.field,`aggregate(${e}, { op: "${n.op}", field: "${n.field}" })`);const p=te(s,oe),R=Re(n.op),$=J(n.field);let A=r`SELECT ${r.raw(R)}(${$}) AS value FROM ${r.identifier(e)}`;return p&&(A=r`${A} WHERE ${p}`),W(i,A).toArray()[0]?.value??null},asId(e,n){const a=Et(t,e,n);if(a===null)throw new g("BAD_REQUEST",`asId("${e}", …): "${n}" is not a valid id for table "${e}"`,{status:400});return a},async count(e,n){const a=K(e,"count");if(a)return N(e,U),a.count(e,n);const c=t.tables[e];if(!c)throw new g("INTERNAL",`unknown table: ${e}`);const h=Gt(n);if(h.restrictsCounts)throw new Fe(e);N(e,U);const u=le(c.softDeleteMode,void 0),s=Y(Y(h.baseWhere,h.where),u),l=await $e(s,e,h.relationBaseWhere),p=l!==s;if(c.aggregateIndexes&&!h.baseWhere&&!p&&!u){const A=Kt(c.aggregateIndexes,h.where);if(A){Me(e,A.index);const D=De(A.index.by??[],A.key),F=Oe(e,A.index.name),P=W(i,r`SELECT ${Ae} AS value FROM ${r.identifier(F)} WHERE ${xe} = ${D}`).toArray();return P[0]===void 0?0:P[0].value??0}}const R=te(l,oe);let $=r`SELECT COUNT(*) AS count FROM ${r.identifier(e)}`;return R&&($=r`${$} WHERE ${R}`),W(i,$).one().count},async delete(e,n,a){const c=re(e,n);if(!c){const $=n===void 0?E:void 0;$&&(v(void 0),await $.delete(e,void 0,a));return}const{docJson:h,row:u,tableName:s}=c,l=t.tables[s],p=a?.hard===!0,R=!p&&l?.softDeleteMode?l.softDeleteMode.field:void 0;if(!(R&&u[R]!==null&&u[R]!==void 0)){if(X(s,"before","delete")&&await Z("before","delete",{id:e,op:"delete",previous:u,table:s}),await hn({deletedId:e,deletedReference:$=>u[$],findHolders:async($,A,D)=>(await ve($).findMany($,{includeDeleted:p,where:{[A]:D}})).page,onCascade:($,A)=>ve($).delete(A,void 0,a),onRestrict:$=>{throw new pe($,"restrict")},onSetNull:($,A,D)=>ve($).patch(A,{[D]:null}),schema:t,tableName:s}),ue(s),fe(s),R){const $={...u,[R]:M(),_id:e};Ie(i,s,r`UPDATE ${r.identifier(s)} SET ${r.identifier(H)} = ${se($)} WHERE id = ${e} AND ${r.identifier(H)} = ${h}`),Ee(s,e,$,u),be(s,e,void 0),ge(s,u,$),he(s,e,u,void 0),L?.invalidate(s,e,f(s,u,$)),ne(s,e,"update",$),d({indexKeys:f(s,u,$),key:e,op:"update",row:$,table:s}),X(s,"after","delete")&&await Z("after","delete",{id:e,op:"delete",previous:u,table:s}),await O({id:e,op:"delete",table:s});return}Ie(i,s,r`DELETE FROM ${r.identifier(s)} WHERE id = ${e} AND ${r.identifier(H)} = ${h}`),Ee(s,e,void 0),be(s,e,void 0),ge(s,u,void 0),he(s,e,u,void 0),L?.invalidate(s,e,f(s,u)),ne(s,e,"delete"),d({indexKeys:f(s,u),key:e,op:"delete",table:s}),X(s,"after","delete")&&await Z("after","delete",{id:e,op:"delete",previous:u,table:s}),await O({id:e,op:"delete",table:s})}},async deleteAll(e,n){if(!t.tables[e])throw new g("INTERNAL",`unknown table: ${e}`);const a=Math.max(1,n?.chunkSize??It),c=n?.hard===void 0?void 0:{hard:n.hard},h=ae(e)?void 0:e;let u=0;return await S(async()=>{for(;;){const s=(await B.findMany(e,{limit:a})).page.map(l=>String(l._id));if(s.length===0)break;for(const l of s)await B.delete(l,h,c),u+=1;if(s.length<a)break}}),{deleted:u}},async deleteMany(e,n,a){de(e.length,n?.limit,"deleteMany");for(const c of e)await B.delete(c,a);return{deleted:e.length}},async deleteWhere(e,n,a){const c=(await(K(e,"deleteWhere")??B).findMany(e,{where:n})).page.map(h=>String(h._id));if(de(c.length,a?.limit,"deleteWhere"),B.deleteMany===void 0)throw new g("INTERNAL",`ctx.db.${e}.deleteMany is unavailable: this writer has no batch delete`);return B.deleteMany(c,a)},async findFirst(e,n={}){return(await B.findMany(e,{...n,limit:1})).page[0]??null},async findFirstOrThrow(e,n={}){const a=await B.findFirst(e,n);if(a===null)throw new on(`findFirstOrThrow: no "${e}" document matched`);return a},async findMany(e,n={}){const a=K(e,"findMany");if(a)return N(e,U),a.findMany(e,n);const c=t.tables[e];if(!c)throw new g("INTERNAL",`unknown table: ${e}`);const h=!n.where&&!n.baseWhere;h?N(e,U):N(e);const u=an(n.orderBy),s=n.cursor?xt(u,He(n.cursor)):void 0;let l=Y(n.baseWhere,n.where);l=Y(l,le(c.softDeleteMode,n.includeDeleted)),l=await ut(l,{canPushExists:Xe?Lt:void 0,existsPushMode:Ve==="always"?"always":"auto",fetcher:Je,maxRelationKeys:Ze,relationBaseWhere:n.relationBaseWhere,schema:t,tableName:e}),s&&(l=l?{AND:[l,s]}:s);const p=Xe?Kn(N):oe,R=te(l,p);let $=r`SELECT id, _creationTime, ${r.identifier(H)} FROM ${r.identifier(e)}`;R&&($=r`${$} WHERE ${R}`),$=r`${$} ORDER BY ${Dt(u)}`;const A=typeof n.limit=="number"?Math.max(0,Math.floor(n.limit)):void 0;A!==void 0&&($=r`${$} LIMIT ${r.raw(String(A+1))}`);const D=W(i,$).toArray();h&&!b&&m?.recordRead(D.length);const F=[];for(const ee of D){const q=ce(ee);q&&(F.push(q),!h&&typeof q._id=="string"&&N(e,q._id))}if(A===void 0)return n.with&&await ft({groupedCounter:et,fetcher:Ce,parents:F,...ht(n),schema:t,tableName:e,with:n.with}),{continueCursor:null,isDone:!0,page:dt(F,n.select,n.with)};const P=F.length>A,x=P?F.slice(0,A):F,Q=x.at(-1);return n.with&&await ft({fetcher:Ce,groupedCounter:et,parents:x,...ht(n),schema:t,tableName:e,with:n.with}),{continueCursor:P&&Q?Ge(Q,u):null,isDone:!P,page:dt(x,n.select,n.with)}},async get(e,n){const a=re(e,n);if(!a){const c=n===void 0?E:void 0;return c?c.get(e):null}return N(a.tableName,e),a.row},async lookupById(e,n){const a=re(e,n);return a?(N(a.tableName,e),{row:a.row,tableName:a.tableName}):null},async groupBy(e,n){const a=K(e,"groupBy");if(a)return N(e,U),a.groupBy(e,n);const c=t.tables[e];if(!c)throw new g("INTERNAL",`unknown table: ${e}`);N(e,U);const h=n.agg??{op:"count"};if(Re(h.op),h.op!=="count"&&!h.field)throw new g("INTERNAL",`groupBy(${e}, { agg: { op: "${h.op}" } }): "field" is required for non-count reducers`);const u=le(c.softDeleteMode,void 0),s=Y(Y(n.baseWhere,n.where),u),l=await $e(s,e,n.relationBaseWhere),p=l!==s,R=[...n.by,h.field];if(c.aggregateIndexes&&!n.baseWhere&&!p&&(!u||gt(c,R))){const x=Qt(c.aggregateIndexes,h.op,h.field,n.by,n.where),Q=x===void 0?0:Object.keys(x.partial).length,ee=x?.index.by?.length??0;if(x&&(Q===0||Q===ee)){Me(e,x.index);const q=Oe(e,x.index.name),ye=Object.keys(x.partial),Ne=[];if(ye.length===(x.index.by??[]).length&&ye.length>0){const _e=De(x.index.by??[],x.partial),Te=W(i,r`SELECT ${Ae} AS value, ${We} AS count FROM ${r.identifier(q)} WHERE ${xe} = ${_e}`).toArray();return Te.length>0&&Ne.push({key:{...x.partial},value:Le(h.op,Te[0])}),Ne}const Wt=W(i,r`SELECT ${xe} AS key, ${Ae} AS value, ${We} AS count FROM ${r.identifier(q)}`).toArray();for(const _e of Wt){const Te=Ht(JSON.parse(_e.key));Ne.push({key:Te,value:Le(h.op,_e)})}return Ne}}for(const x of R){if(x===void 0)continue;const Q=x===h.field?`groupBy(${e}, { agg: { op: "${h.op}", field: "${x}" } })`:`groupBy(${e}, { by: [..."${x}"] })`;bt(c,x,Q)}const $=te(l,oe),A=n.by.map(x=>r`${J(x)} AS ${r.identifier(x)}`);if(h.op==="count")A.push(r`COUNT(*) AS value`);else{const{field:x}=h;if(x===void 0)throw new g("INTERNAL",`groupBy(${e}, { agg: { op: "${h.op}" } }): "field" is required for non-count reducers`);A.push(r`${r.raw(Re(h.op))}(${J(x)}) AS value`)}let D=r`SELECT ${r.join(A,r`, `)} FROM ${r.identifier(e)}`;$&&(D=r`${D} WHERE ${$}`),D=r`${D} GROUP BY ${r.join(n.by.map(x=>J(x)),r`, `)}`;const F=W(i,D).toArray(),P=[];for(const x of F){const Q={};for(const q of n.by)Q[q]=x[q]??null;const{value:ee}=x;P.push({key:Q,value:ee==null?null:Number(ee)})}return P},async insert(e,n,a){const c=K(e,"insert");if(c)return ze(c,e,n,a,!0);const h=t.tables[e];if(!h)throw new g("INTERNAL",`unknown table: ${e}`);const u=yt(h,n,I);qe(h,u);let s;a?.clientId!==void 0?(Dn(a.clientId),s=a.clientId):a?.allowExplicitId&&typeof u._id=="string"?s=u._id:s=G();const l=a?.allowExplicitId&&typeof u._creationTime=="number"?u._creationTime:M(),p={...u,_creationTime:l,_id:s};return X(e,"before","insert")&&await Z("before","insert",{doc:{...p},id:s,op:"insert",table:e}),ue(e),fe(e),je(i,e,r`INSERT INTO ${r.identifier(e)} (id, _creationTime, ${r.identifier(H)}) VALUES (${s}, ${l}, ${se(p)})`),nt(e,s,p),X(e,"after","insert")&&await Z("after","insert",{doc:p,id:s,op:"insert",table:e}),await O({doc:p,id:s,op:"insert",table:e}),s},async insertManyUnsafe(e,n,a){if(de(n.length,a?.limit,"insertManyUnsafe"),n.length===0)return[];const c=K(e,"insert");if(c){const s=[];for(const l of n)v(l);for(const l of n){const p=await c.insert(e,l,{allowExplicitId:a?.allowExplicitId});d({key:p,op:"insert",row:{...l,_id:p},table:e}),s.push(p)}return s}const h=t.tables[e];if(!h)throw new g("INTERNAL",`unknown table: ${e}`);ue(e),fe(e);const u=n.map(s=>{const l=yt(h,s,I),p=a?.allowExplicitId===!0&&typeof l._id=="string"?l._id:G(),R=a?.allowExplicitId===!0&&typeof l._creationTime=="number"?l._creationTime:M();return{creationTime:R,document:{...l,_creationTime:R,_id:p},id:p}});for(const s of u)v(s.document);for(let s=0;s<u.length;s+=wt){const l=r.join(u.slice(s,s+wt).map(p=>r`(${p.id}, ${p.creationTime}, ${se(p.document)})`),r`, `);je(i,e,r`INSERT INTO ${r.identifier(e)} (id, _creationTime, ${r.identifier(H)}) VALUES ${l}`)}for(const{document:s,id:l}of u)nt(e,l,s),await T({doc:s,id:l,op:"insert",table:e});return u.map(s=>s.id)},async insertMany(e,n,a){de(n.length,a?.limit,"insertMany");const c=a?.skipDuplicates===!0,h=[],u=K(e,"insert");if(u)for(const l of n)v(l);const s=async l=>u?ze(u,e,l,void 0,!1):B.insert(e,l);for(const l of n)try{h.push(await s(l))}catch(p){if(c&&p instanceof pe&&p.kind==="unique")h.push(null);else throw p}return h},normalizeId(e,n){return Et(t,e,n)},async patch(e,n,a){const c=re(e,a);if(!c){const R=a===void 0?E:void 0;if(R){v(n),await R.patch(e,n);return}throw new g("INTERNAL",`document not found: ${e}`)}const{docJson:h,row:u,tableName:s}=c,l=t.tables[s];if(!l)throw new g("INTERNAL",`unknown table: ${s}`);N(s,e),_t("patch",n);const p={...u,...n,_id:e};Nt(l,n,p,I),qe(l,p,!0),X(s,"before","update")&&await Z("before","update",{doc:{...p},id:e,op:"update",previous:u,table:s}),ue(s),fe(s),Ie(i,s,r`UPDATE ${r.identifier(s)} SET ${r.identifier(H)} = ${se(p)} WHERE id = ${e} AND ${r.identifier(H)} = ${h}`),Ee(s,e,p,u),be(s,e,p),ge(s,u,p),he(s,e,u,p),L?.invalidate(s,e,f(s,u,p)),ne(s,e,"update",p),d({indexKeys:f(s,u,p),key:e,op:"update",row:p,table:s}),X(s,"after","update")&&await Z("after","update",{doc:p,id:e,op:"update",previous:u,table:s}),await O({doc:p,id:e,op:"update",table:s})},async patchMany(e,n,a){de(e.length,n?.limit,"patchMany");for(const c of e)await B.patch(c.id,c.patch,a);return{patched:e.length}},async patchWhere(e,n,a){const c=(await(K(e,"patchWhere")??B).findMany(e,{where:n.where})).page.map(h=>({id:String(h._id),patch:n.patch}));if(de(c.length,a?.limit,"patchWhere"),B.patchMany===void 0)throw new g("INTERNAL",`ctx.db.${e}.patchMany is unavailable: this writer has no batch patch`);return await B.patchMany(c,a),{patched:c.length}},query(e){const n=K(e,"query");return n?(N(e,U),n.query(e)):nr(i,t,e,_,a=>{a?w(a):N(e,U)},a=>{b||m?.recordRead(a)})},async rank(e,n,a){const c=K(e,"rank");if(c)return N(e,U),c.rank(e,n,a);_(e,n,"rank");const h=t.tables[e];if(!h)throw new g("INTERNAL",`unknown table: ${e}`);const u=h.rankIndexes?.find(q=>q.name===n);if(!u)throw new g("INTERNAL",`unknown rankIndex "${n}" on table "${e}"`);if(rt(e,h,u),a.restrictsCounts)throw new Fe(e);N(e,U),ke(e,u);const s=typeof a.row=="string"?a.row:a.row._id;if(!s)return null;const l=ct(e,u.name),p=u.sortBy.map((q,ye)=>lt(ye)),R=p.map(q=>bn(q)).join(", "),$=W(i,r`SELECT ${r.identifier("__partition__")}, ${r.raw(R)} FROM ${r.identifier(l)} WHERE ${r.identifier("__id__")} = ${s}`).toArray(),[A]=$;if(A===void 0)return null;let D=A.__partition__;const F=Y(a.baseWhere,a.where);Be(F,t,e,"rank");const P=dn(u,F);if(P){const q=ln(u.partitionBy??[],P);if(q!==D)return null;D=q}const x=p.map(q=>A[q]),{before:Q,total:ee}=Tt(i,l,p,u.sortBy,D,x,s);return{position:Q+1,total:ee}},async rankBefore(e,n,a){if(ae(e))throw new g("INTERNAL",`rankBefore is not supported on the global (.global()) table '${e}' — cross-shard rank cursors apply only to sharded tables`);const c=t.tables[e];if(!c)throw new g("INTERNAL",`unknown table: ${e}`);const h=c.rankIndexes?.find(p=>p.name===n);if(!h)throw new g("INTERNAL",`unknown rankIndex "${n}" on table "${e}"`);if(a.restrictsCounts)throw new Fe(e);N(e,U),ke(e,h);const u=ct(e,h.name),s=h.sortBy.map((p,R)=>lt(R)),l=h.sortBy.map((p,R)=>ie(a.sortValues[R]??null));return Tt(i,u,s,h.sortBy,a.partitionKey,l,a.rowId)},async rankPage(e,n,a={}){Be(Y(a.baseWhere,a.where),t,e,"rankPage");const c=K(e,"rankPage");if(c)return N(e,U),c.rankPage(e,n,a);_(e,n,"rank");const{continueCursor:h,hasMore:u,rows:s}=at(it,e,n,a);return{continueCursor:h,isDone:!u,page:s.map(l=>l.doc)}},async rankPageRows(e,n,a={}){Be(Y(a.baseWhere,a.where),t,e,"rankPage"),_(e,n,"rank");const{directions:c,hasMore:h,rows:u}=at(it,e,n,a);return{directions:c,hasMore:h,rows:u}},async restore(e,n){const a=re(e,n);if(!a){const u=n===void 0?E:void 0;if(u?.restore){await u.restore(e);return}throw new g("INTERNAL",`document not found: ${e}`)}const c=t.tables[a.tableName]?.softDeleteMode?.field;if(!c)throw new g("INTERNAL",`ctx.db.restore: table "${a.tableName}" is not a .softDelete() table`);const h=a.row[c]!==null&&a.row[c]!==void 0;await B.patch(e,{[c]:null},n),h&&he(a.tableName,e,void 0,a.row)},async replace(e,n,a,c){const h=re(e,a);if(!h){const A=a===void 0?E:void 0;if(A){v(n),await A.replace(e,n,void 0,c);return}throw new g("INTERNAL",`document not found: ${e}`)}const{docJson:u,row:s,tableName:l}=h,p=t.tables[l];if(!p)throw new g("INTERNAL",`unknown table: ${l}`);_t("replace",n);const R=c?.allowExplicitId&&typeof n._creationTime=="number"?n._creationTime:M(),$={...n,_creationTime:R,_id:e};Nt(p,n,$,I),qe(p,$),X(l,"before","update")&&await Z("before","update",{doc:{...$},id:e,op:"update",previous:s,table:l}),ue(l),fe(l),Ie(i,l,r`UPDATE ${r.identifier(l)} SET _creationTime = ${R}, ${r.identifier(H)} = ${se($)} WHERE id = ${e} AND ${r.identifier(H)} = ${u}`),Ee(l,e,$,s),be(l,e,$),ge(l,s,$),he(l,e,s,$),L?.invalidate(l,e,f(l,s,$)),ne(l,e,"update",$),d({indexKeys:f(l,s,$),key:e,op:"update",row:$,table:l}),X(l,"after","update")&&await Z("after","update",{doc:$,id:e,op:"update",previous:s,table:l}),await O({doc:$,id:e,op:"update",table:l})},async wipeShard(e){const n=new Set(e?.exclude),a=e?.tables,c=Object.entries(t.tables).filter(([l,p])=>n.has(l)||a!==void 0&&!a.includes(l)?!1:p.shardMode?.kind!=="global").map(([l])=>l);if(a!==void 0){for(const l of a)if(!t.tables[l])throw new g("INTERNAL",`wipeShard: unknown table: ${l}`)}const h={};let u=0;const{deleteAll:s}=B;if(s===void 0)throw new g("INTERNAL","wipeShard: this writer has no deleteAll");for(const l of c){const p=await s(l,{...e?.chunkSize===void 0?{}:{chunkSize:e.chunkSize},hard:!0});h[l]=p.deleted,u+=p.deleted}return{deleted:u,tables:h}}},Ft={db:B,scheduler:j};return o.enforceRls===!0?pn(B,t,(e,n)=>re(e,n)?.tableName,(e,n)=>Ot(e,n)):B};export{Ur as CDC_LOG_TABLE,Jr as CLIENT_WATERMARK_TABLE,to as GLOBAL_SHAPE_SNAPSHOT_TABLE,lo as IDEMPOTENCY_TABLE,Zn as NotUniqueError,$o as SEARCH_STATE_TABLE,Vr as advanceClientWatermark,Pr as applyCdcChanges,Dn as assertValidClientId,Fr as backfillAggregateIndexes,Wr as backfillRankIndexes,Br as backfillSearchIndexes,Hr as bumpCdcEpoch,Dr as createShardCtxDb,no as deleteGlobalShapeSnapshot,ro as deleteGlobalShapeSnapshotsForConnection,Xr as migrateClientWatermark,oo as migrateGlobalShapeSnapshot,Gr as minCdcSeq,Et as normalizeIdStructurally,jr as readCdcChanges,Qr as readCdcCursor,Kr as readCdcEpoch,Zr as readClientWatermark,io as readGlobalShapeSnapshot,co as readIdempotent,mo as runShardMigrations,go as selectShapeMemberIds,bo as selectShapeRows,Yr as trimCdcChanges,uo as trimIdempotent,ao as writeGlobalShapeSnapshot,fo as writeIdempotent};
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{runSql as d,orNull as u,decodeJsonColumn as _}from"./runDrizzle-
|
|
1
|
+
import{runSql as d,orNull as u,decodeJsonColumn as _}from"./runDrizzle-C3n5gJsk.mjs";const s="__lunora_queue_messages",T=500,E=128*1024,i="… [truncated by the dev queue catcher]",m="[unserializable message body]",p=e=>{if(e===void 0)return"null";try{const t=JSON.stringify(e);return t.length>E?JSON.stringify(`${t.slice(0,E)}${i}`):t}catch{return JSON.stringify(m)}},g=e=>typeof e=="string"&&(e===m||e.endsWith(i)),o=e=>{d(e,`CREATE TABLE IF NOT EXISTS "${s}" (
|
|
2
2
|
id TEXT PRIMARY KEY,
|
|
3
3
|
captured_at INTEGER NOT NULL,
|
|
4
4
|
message_id TEXT NOT NULL,
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{quoteIdentifier as T}from"./quoteIdentifier-CObIFRhb.mjs";import{runSql as e}from"./runDrizzle-
|
|
1
|
+
import{quoteIdentifier as T}from"./quoteIdentifier-CObIFRhb.mjs";import{runSql as e}from"./runDrizzle-C3n5gJsk.mjs";const i="__lunora_schema_history",R=50,a=T(i),n=s=>({appliedAt:typeof s.applied_at=="number"?s.applied_at:0,hash:typeof s.hash=="string"?s.hash:"",seq:typeof s.seq=="number"?s.seq:0}),h=s=>{e(s,`CREATE TABLE IF NOT EXISTS ${a} (
|
|
2
2
|
hash TEXT PRIMARY KEY,
|
|
3
3
|
seq INTEGER NOT NULL,
|
|
4
4
|
snapshot_json TEXT NOT NULL,
|
package/dist/packem_shared/{SEARCH_STATE_TABLE-MDlr30EJ.mjs → SEARCH_STATE_TABLE-DRk_SB72.mjs}
RENAMED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{sql as i}from"drizzle-orm";import{runDrizzle as n}from"./runDrizzle-
|
|
1
|
+
import{sql as i}from"drizzle-orm";import{runDrizzle as n}from"./runDrizzle-C3n5gJsk.mjs";const o="__lunora_search_state",a=e=>{n(e,i`CREATE TABLE IF NOT EXISTS ${i.identifier(o)} (${i.identifier("companion")} TEXT PRIMARY KEY, ${i.identifier("cursor")} TEXT, ${i.identifier("done")} INTEGER NOT NULL DEFAULT 0, ${i.identifier("profile")} TEXT)`);try{n(e,i`ALTER TABLE ${i.identifier(o)} ADD COLUMN ${i.identifier("profile")} TEXT`)}catch{}},c=e=>e===1||e===!0||e==="1",l=(e,t)=>{const r=n(e,i`SELECT ${i.identifier("cursor")}, ${i.identifier("done")}, ${i.identifier("profile")} FROM ${i.identifier(o)} WHERE ${i.identifier("companion")} = ${t}`).toArray()[0];return r?{cursor:r.cursor??void 0,done:c(r.done),profile:r.profile??void 0}:{cursor:void 0,done:!1,profile:void 0}},s=(e,t,r,d,f)=>{const $=r??null;n(e,i`INSERT INTO ${i.identifier(o)} (${i.identifier("companion")}, ${i.identifier("cursor")}, ${i.identifier("done")}, ${i.identifier("profile")}) VALUES (${t}, ${$}, ${d?1:0}, ${f}) ON CONFLICT (${i.identifier("companion")}) DO UPDATE SET ${i.identifier("cursor")} = excluded.${i.identifier("cursor")}, ${i.identifier("done")} = excluded.${i.identifier("done")}, ${i.identifier("profile")} = excluded.${i.identifier("profile")}`)};export{o as SEARCH_STATE_TABLE,a as migrateSearchState,l as readSearchBackfillState,s as writeSearchBackfillState};
|
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
import{sql as e}from"drizzle-orm";import{runDrizzle as E}from"./runDrizzle-C3n5gJsk.mjs";const n="__stream_runs",T="__stream_chunks",L=r=>{E(r,e`CREATE TABLE IF NOT EXISTS ${e.identifier(n)} (
|
|
2
|
+
run_key TEXT PRIMARY KEY,
|
|
3
|
+
status TEXT NOT NULL,
|
|
4
|
+
last_seq INTEGER NOT NULL DEFAULT 0,
|
|
5
|
+
error_code TEXT,
|
|
6
|
+
error TEXT,
|
|
7
|
+
started_at REAL NOT NULL,
|
|
8
|
+
ttl_ms REAL NOT NULL
|
|
9
|
+
)`),E(r,e`CREATE TABLE IF NOT EXISTS ${e.identifier(T)} (
|
|
10
|
+
run_key TEXT NOT NULL,
|
|
11
|
+
seq INTEGER NOT NULL,
|
|
12
|
+
data_json TEXT NOT NULL,
|
|
13
|
+
PRIMARY KEY (run_key, seq)
|
|
14
|
+
)`)},d=(r,t)=>{const s=E(r,e`SELECT status, last_seq, error_code, error, started_at FROM ${e.identifier(n)} WHERE run_key = ${t} LIMIT 1`).toArray()[0];if(s!==void 0)return{...s.error===null?{}:{error:s.error},...s.error_code===null?{}:{errorCode:s.error_code},lastSeq:s.last_seq,startedAt:s.started_at,status:s.status}},$=(r,t,s,a)=>d(r,t)!==void 0?!1:(E(r,e`INSERT INTO ${e.identifier(n)} (run_key, status, last_seq, started_at, ttl_ms)
|
|
15
|
+
VALUES (${t}, ${"running"}, 0, ${s}, ${a})`),!0),N=(r,t)=>{E(r,e`DELETE FROM ${e.identifier(T)} WHERE run_key = ${t}`),E(r,e`DELETE FROM ${e.identifier(n)} WHERE run_key = ${t}`)},S=(r,t,s,a)=>{E(r,e`INSERT OR IGNORE INTO ${e.identifier(T)} (run_key, seq, data_json) VALUES (${t}, ${s}, ${a})`)},l=(r,t,s)=>E(r,e`SELECT seq, data_json FROM ${e.identifier(T)} WHERE run_key = ${t} AND seq > ${s} ORDER BY seq ASC`).toArray().map(a=>({dataJson:a.data_json,seq:a.seq})),m=(r,t,s,a,i)=>{const _=i?.code??null,R=i?.message??null;E(r,e`UPDATE ${e.identifier(n)}
|
|
16
|
+
SET status = ${s}, last_seq = ${a}, error_code = ${_}, error = ${R}
|
|
17
|
+
WHERE run_key = ${t}`)},A=(r,t)=>{E(r,e`DELETE FROM ${e.identifier(T)} WHERE run_key IN (
|
|
18
|
+
SELECT run_key FROM ${e.identifier(n)} WHERE started_at + ttl_ms < ${t}
|
|
19
|
+
)`),E(r,e`DELETE FROM ${e.identifier(n)} WHERE started_at + ttl_ms < ${t}`)};export{T as STREAM_CHUNKS_TABLE,n as STREAM_RUNS_TABLE,S as appendStreamChunk,$ as claimStreamRun,N as deleteStreamRun,m as finishStreamRun,L as migrateDurableStreams,l as readStreamChunks,d as readStreamRun,A as trimStreamRuns};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{B as R,W as x,x as k,T as S,l as O,y as M,c as w}from"./ctx-db-companions-
|
|
1
|
+
import{B as R,W as x,x as k,T as S,l as O,y as M,c as w}from"./ctx-db-companions-c12P7dbv.mjs";import"@lunora/errors";import{sql as r}from"drizzle-orm";import{matchesStaticWhere as A}from"./AGGREGATE_SQL_FUNCTION-CTo0-9iZ.mjs";import{encodeAggregateKey as L,foldAggregateTally as C,aggregateTableName as F}from"./aggregateTableName-DgYMC5tr.mjs";import{migrateSearchState as y,readSearchBackfillState as D,writeSearchBackfillState as N}from"./SEARCH_STATE_TABLE-DRk_SB72.mjs";import{runDrizzle as d}from"./runDrizzle-C3n5gJsk.mjs";import{C as T,E as p,c as v,p as B,T as W,a as E,D as j}from"./do-sql-C7qrlm6-.mjs";import{isLiveForCompanion as _}from"./applySelect-UY-o13Ia.mjs";import{matchesRankStaticWhere as U,rankTableName as V}from"./RANK_TIEBREAK-DDtST3gN.mjs";const Y=(e,o)=>e.profile!==o?{cursor:void 0,finished:!1,wipe:e.cursor!==void 0||e.done}:{cursor:e.cursor,finished:e.done,wipe:!1},u=(e,o)=>d(e,r`SELECT COUNT(*) AS count FROM ${r.identifier(o)}`).one().count>0,I=(e,o)=>d(e,r`SELECT id, _creationTime, ${r.identifier(E)} FROM ${r.identifier(o)}`).toArray(),q=(e,o,n,i)=>{const t=F(o,n.name);if(u(e,t))return;const s=n.by??[],c=new Map,f=I(e,o);for(const l of f){const a=p(l);if(!a||!_(a,i)||n.where&&!A(a,n.where))continue;const $=L(s,a);C(c,$,n,a)}for(const[l,a]of c)d(e,r`INSERT INTO ${r.identifier(t)} (${v}, ${B}, ${W}) VALUES (${l}, ${a.value}, ${a.count})`)},re=(e,o)=>{for(const[n,i]of Object.entries(o.tables))if(!(i.shardMode?.kind==="global"||!i.aggregateIndexes))for(const t of i.aggregateIndexes)q(e,n,t,i.softDeleteMode?.field)},z=(e,o,n)=>{const i=V(o,n.name);if(u(e,i))return;const t=R(n),s=I(e,o);for(const c of s){const f=p(c);!f||n.where&&!U(f,n.where)||x(e,i,n,t,f._id,f)}},oe=(e,o)=>{for(const[n,i]of Object.entries(o.tables))if(!(i.shardMode?.kind==="global"||!i.rankIndexes))for(const t of i.rankIndexes)z(e,n,t)},g=500,b=(e,o,n)=>{const i=w(o,n.name),{profile:t}=k(n.language),s=Y(D(e,i),t);if(s.finished)return!0;s.wipe&&d(e,r`DELETE FROM ${r.identifier(i)}`);const{cursor:c}=s,f=d(e,c===void 0?r`SELECT id, _creationTime, ${r.identifier(E)} FROM ${r.identifier(o)} ORDER BY id ASC LIMIT ${r.raw(String(g))}`:r`SELECT id, _creationTime, ${r.identifier(E)} FROM ${r.identifier(o)} WHERE id > ${c} ORDER BY id ASC LIMIT ${r.raw(String(g))}`).toArray();let l=c;for(const $ of f){const{id:m}=$;if(typeof m!="string")continue;l=m,d(e,r`DELETE FROM ${r.identifier(i)} WHERE ${r.identifier(S)} = ${m}`);const h=j($);h&&d(e,r`INSERT INTO ${r.identifier(i)} (${r.identifier(O)}, ${r.identifier(S)}) VALUES (${M(h,n)}, ${m})`)}const a=f.length<g;return N(e,i,l,a,t),a},ne=(e,o,n)=>{if(T(e))for(const i of n.searchIndexes??[])i.staged||b(e,o,i)},te=(e,o)=>{if(T(e)){y(e);for(const[n,i]of Object.entries(o.tables))if(!(i.shardMode?.kind==="global"||!i.searchIndexes))for(const t of i.searchIndexes){let s=!1;for(;!s;)s=b(e,n,t)}}};export{re as backfillAggregateIndexes,oe as backfillRankIndexes,te as backfillSearchIndexes,ne as backfillSearchIndexesForTable};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{quoteIdentifier as _}from"./quoteIdentifier-CObIFRhb.mjs";import{reprojectionMigrationTable as u}from"./REPROJECTION_MIGRATION_PREFIX-D2dltRFC.mjs";import{REPROJECTION_MIGRATION_PREFIX as L,reprojectionMigrationId as C}from"./REPROJECTION_MIGRATION_PREFIX-D2dltRFC.mjs";import{a as m}from"./wire-codec-Dsy70M3Q.mjs";import{runSql as p}from"./runDrizzle-C3n5gJsk.mjs";import{L as E,a as g}from"./do-sql-C7qrlm6-.mjs";import{y as b}from"./sql-projection-jfoe331H.mjs";const R=m(0n)[0],l=t=>t.shardMode?.kind==="global"?[]:Object.entries(t.shape).filter(([,r])=>b(r)).map(([r])=>r),T=t=>Object.entries(t.tables).filter(([,r])=>l(r).length>0).map(([r])=>r),f=t=>{const r=`json_each(${_(g)}) AS __f__`;return{params:[JSON.stringify(t),R,"bigint","bytes"],sql:`EXISTS (SELECT 1 FROM ${r} WHERE __f__.type = 'array' AND __f__.key IN (SELECT value FROM json_each(?)) AND json_extract(__f__.value, '$[0]') = ? AND json_extract(__f__.value, '$[1]') IN (?, ?))`}},M=(t,r,o)=>{if(o.length===0)return 0;const{params:e,sql:n}=f(o);return p(t,`SELECT COUNT(*) AS count FROM ${_(r)} WHERE ${n}`,...e).toArray()[0]?.count??0},$=(t,r,o,e)=>{const{params:n,sql:i}=f(o);return p(t,`SELECT 1 FROM ${_(r)} WHERE id = ? AND (${i}) LIMIT 1`,e,...n).toArray().length>0},N=(t,r,o)=>{const e=u(t);if(e===void 0)return;const n=r.tables[e];if(!n)return;const i=l(n);if(i.length!==0)return{id:t,table:e,up:a=>{const s=a._id;if(!(typeof s!="string"||!$(o,e,i,s))){try{E(a)}catch(c){console.warn(`${t}: skipping row ${s} — it cannot be re-projected: ${c instanceof Error?c.message:String(c)}`);return}return a}}}};export{L as REPROJECTION_MIGRATION_PREFIX,N as buildReprojectionMigration,M as countLegacyRows,l as reprojectableFields,C as reprojectionMigrationId,T as reprojectionTables};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{LunoraError as $}from"@lunora/errors";import{sql as o}from"drizzle-orm";import{sqliteInList as N,WORKERD_SQLITE_LIMITS as p}from"./param-CYxL68V-.mjs";import{RELATION_EXISTS_KEY as I}from"./RELATION_EXISTS_KEY-BaqSIFU1.mjs";const h=["eq","ne","lt","lte","gt","gte","in","notIn","isNull","contains"],O=new Set(h),T={eq:"=",gt:">",gte:">=",lt:"<",lte:"<=",ne:"<>"},L=r=>{if(r===null||typeof r!="object"||Array.isArray(r))return!1;const e=Object.keys(r);return e.length>0&&e.every(t=>O.has(t))},y=(r,e,t)=>{const s=o`${t.serialize(e)}`;return t.containsExpr?t.containsExpr(r,s):o`instr(lower(${r}), lower(${s})) > 0`},S=(r,e,t,s,i)=>s===null?e==="ne"?o`${r} IS NOT NULL`:o`${r} IS NULL`:o`${r} ${o.raw(t)} ${i.serialize(s)}`,m=(r,e,t,s)=>{const i=Array.isArray(t)?t:[];if(i.length===0)return e==="IN"?o`0 = 1`:o`1 = 1`;const n=i.map(a=>s.serialize(a)),l=e==="NOT IN";return(s.inList??N)(r,n,l)},U=(r,e,t)=>{const s=o.join(e.map(i=>o`${i}`),o`, `);return t?o`${r} NOT IN (${s})`:o`${r} IN (${s})`},A=(r,e,t)=>{const s=e,i=[];for(const n of h){if(!(n in s))continue;const l=s[n],a=T[n];a?i.push(S(r,n,a,l,t)):n==="isNull"?i.push(l?o`${r} IS NULL`:o`${r} IS NOT NULL`):n==="contains"?i.push(y(r,l,t)):i.push(m(r,n==="in"?"IN":"NOT IN",l,t))}return i},E=(r,e,t)=>{const s=t.fieldRef(r);return L(e)?A(s,e,t):e===null?[o`${s} IS NULL`]:[o`${s} = ${t.serialize(e)}`]},u=(r,e)=>{if(r.length<=1)return r[0];const t=Math.floor(r.length/2);return o`(${u(r.slice(0,t),e)}) ${o.raw(e)} (${u(r.slice(t),e)})`},g=(r,e,t)=>{const s=Array.isArray(r)?r:[],i=[];for(const n of s){const l=c(n??{},t);l&&i.push(l)}return i.length===0?e==="OR"?o`0 = 1`:void 0:u(i,e)},w=new Set(["AND","NOT","OR",I]),R=(r,e,t)=>{if(r===I){if(!t.relationExists)throw new $("INTERNAL","encountered a relation EXISTS marker without a relationExists strategy hook");return t.relationExists(e)}if(r==="NOT"){const s=c(e??{},t);return s?o`NOT (${s})`:void 0}return g(e,r,t)},c=(r,e)=>{const t=[];for(const[s,i]of Object.entries(r))if(w.has(s)){const n=R(s,i,e);n&&t.push(n)}else t.push(...E(s,i,e));return u(t,"AND")},b=p.boundParams/2,f=r=>{if(Array.isArray(r))return r.reduce((t,s)=>t+f(s),0);if(r===null||typeof r!="object")return 0;let e=0;for(const[t,s]of Object.entries(r))t==="in"||t==="notIn"?e+=1:(t==="AND"||t==="NOT"||t==="OR"||L(s))&&(e+=f(s));return e},k=(r,e)=>{if(!r||Object.keys(r).length===0)return;const t=e.inList??N,s=f(r);if(s===0)return c(r,e);const i=Math.max(1,Math.floor(b/s));return c(r,{...e,inList:(n,l,a)=>t(n,l,a,i)})};export{k as compileWhereSql,U as literalInList};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{LunoraError as N}from"@lunora/errors";import{sql as t}from"drizzle-orm";import{mergeWhere as v}from"./CountRlsUnsupportedError-8BqPYQoP.mjs";import{SCAN_DEP as x}from"./SCAN_DEP-D_yR9EeV.mjs";import{runDrizzle as B}from"./runDrizzle-
|
|
1
|
+
import{LunoraError as N}from"@lunora/errors";import{sql as t}from"drizzle-orm";import{mergeWhere as v}from"./CountRlsUnsupportedError-8BqPYQoP.mjs";import{SCAN_DEP as x}from"./SCAN_DEP-D_yR9EeV.mjs";import{runDrizzle as B}from"./runDrizzle-C3n5gJsk.mjs";import{sqliteInList as O}from"./param-CYxL68V-.mjs";import{decodeCursor as W,toBase64 as z}from"./applySelect-UY-o13Ia.mjs";import{sortColumnName as F,resolveRankPartition as H,RANK_TIEBREAK as m,encodePartitionKey as J,rankTableName as V}from"./RANK_TIEBREAK-DDtST3gN.mjs";const Y="__doc__",G=n=>z(JSON.stringify(n)),X=n=>n.after?[n.after.partitionKey,...n.after.sortValues,n.after.rowId]:n.cursor?W(n.cursor):void 0,Z=(n,o,f)=>{if(n?.length!==1+o.length+1)return;const r=[{column:"__partition__",direction:"asc"}];for(const[s,a]of o.entries())r.push({column:a,direction:f[s]?.direction??"asc"});r.push({column:m,direction:"asc"});const e=[];for(const[s,a]of r.entries()){const c=[];for(const[i,l]of r.slice(0,s).entries())c.push(t`${t.identifier(l.column)} IS ${n[i]}`);c.push(t`${t.identifier(a.column)} ${t.raw(a.direction==="desc"?"<":">")} ${n[s]}`);const[p]=c;e.push(c.length===1&&p!==void 0?p:t`(${t.join(c,t` AND `)})`)}return t`(${t.join(e,t` OR `)})`},C=null,Q=(n,o)=>{if(n===void 0)return C;const f=[n.__partition__,...o.map(r=>n[r]),n[m]];return G(f)},U=(n,o,f)=>{const r=[];for(const e of n){const s=e[m];if(typeof s!="string")continue;const a=o.get(s);if(!a)continue;const c=typeof e.__partition__=="string"?e.__partition__:"",p=f.map(i=>e[i]??null);r.push({doc:a,key:{partitionKey:c,rowId:s,sortValues:p}})}return r},tt=t`${t.identifier("id")}`,nt=(n,o,f)=>{const{rowToDocument:r}=n,e=new Map;if(f.length===0)return e;const s=B(n.sql,t`SELECT id, _creationTime, ${t.identifier(Y)} FROM ${t.identifier(o)} WHERE ${O(tt,f,!1)}`).toArray();for(const a of s){const c=r(a),p=a.id;c&&typeof p=="string"&&e.set(p,c)}return e},pt=(n,o,f,r)=>{const{assertRankPartitionLocal:e,ensureRankBackfilled:s,onRead:a,schema:c}=n,p=c.tables[o];if(!p)throw new N("INTERNAL",`unknown table: ${o}`);const i=p.rankIndexes?.find(u=>u.name===f);if(!i)throw new N("INTERNAL",`unknown rankIndex "${f}" on table "${o}"`);e(o,p,i),a(o,x),s(o,i);const l=V(o,i.name),d=i.sortBy.map((u,w)=>F(w)),$=Math.max(1,Math.min(1e3,Math.floor(r.take??100))),S=v(r.baseWhere,r.where),R=H(i,S),h=[t`${t.identifier("__partition__")} ASC`];for(const[u,w]of d.entries()){const q=i.sortBy[u]?.direction;h.push(t`${t.identifier(w)} ${t.raw(q==="desc"?"DESC":"ASC")}`)}h.push(t`${t.identifier(m)} ASC`);const _=[];typeof r.partitionKey=="string"?_.push(t`${t.identifier("__partition__")} = ${r.partitionKey}`):R&&_.push(t`${t.identifier("__partition__")} = ${J(i.partitionBy??[],R)}`);const T=X(r),k=Z(T,d,i.sortBy);k&&_.push(k);const I=t.identifier(m),A=t.identifier("__partition__"),L=_.length>0?t` WHERE ${t.join(_,t` AND `)}`:t``,M=d.length>0?t`${I}, ${A}, ${t.join(d.map(u=>t.identifier(u)),t`, `)}`:t`${I}, ${A}`,D=t`SELECT ${M} FROM ${t.identifier(l)}${L} ORDER BY ${t.join(h,t`, `)} LIMIT ${t.raw(String($+1))}`,y=B(n.sql,D).toArray(),g=y.length>$,E=g?y.slice(0,$):y,K=E.map(u=>u[m]),b=U(E,nt(n,o,K),d),P=g?Q(E.at(-1),d):C,j=i.sortBy.map(u=>u.direction==="desc"?"desc":"asc");return{continueCursor:P,directions:j,hasMore:g,rows:b}};export{pt as computeRankPage,nt as hydrateDocsById};
|
package/dist/packem_shared/{createCompanionSync-BPQ1EJ06.mjs → createCompanionSync-D7DEvUvt.mjs}
RENAMED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{S as C,W as R,B as f}from"./ctx-db-companions-
|
|
1
|
+
import{S as C,W as R,B as f}from"./ctx-db-companions-c12P7dbv.mjs";import"@lunora/errors";import"drizzle-orm";import"./AGGREGATE_SQL_FUNCTION-CTo0-9iZ.mjs";import"./aggregateTableName-DgYMC5tr.mjs";import"./runDrizzle-C3n5gJsk.mjs";import"./do-sql-C7qrlm6-.mjs";import"./param-CYxL68V-.mjs";import"./GEO_DEFAULT_PRECISION-DyI5zggj.mjs";import"./applySelect-UY-o13Ia.mjs";import"./RANK_TIEBREAK-DDtST3gN.mjs";import"./sql-projection-jfoe331H.mjs";import"./serializeSqlValue-BR4UOWoP.mjs";export{C as createCompanionSync,R as insertRankRow,f as rankColumnsSql};
|
package/dist/packem_shared/{ctx-db-companions-D2ZMFBrP.mjs → ctx-db-companions-c12P7dbv.mjs}
RENAMED
|
@@ -1 +1 @@
|
|
|
1
|
-
import"@lunora/errors";import{sql as e}from"drizzle-orm";import{matchesStaticWhere as P,aggregateSqlFunction as de}from"./AGGREGATE_SQL_FUNCTION-CTo0-9iZ.mjs";import{encodeAggregateKey as N,foldAggregateTally as V,coerceAggregateNumber as F,aggregateTableName as G}from"./aggregateTableName-DgYMC5tr.mjs";import{runDrizzle as u}from"./runDrizzle-
|
|
1
|
+
import"@lunora/errors";import{sql as e}from"drizzle-orm";import{matchesStaticWhere as P,aggregateSqlFunction as de}from"./AGGREGATE_SQL_FUNCTION-CTo0-9iZ.mjs";import{encodeAggregateKey as N,foldAggregateTally as V,coerceAggregateNumber as F,aggregateTableName as G}from"./aggregateTableName-DgYMC5tr.mjs";import{runDrizzle as u}from"./runDrizzle-C3n5gJsk.mjs";import{C as ce,a as M,E as D,c as j,p as S,T as _,h as fe,A as C,N as k}from"./do-sql-C7qrlm6-.mjs";import{param as ue,WORKERD_SQLITE_LIMITS as $e}from"./param-CYxL68V-.mjs";import{encodeGeohash as me,GEO_DEFAULT_PRECISION as Ee}from"./GEO_DEFAULT_PRECISION-DyI5zggj.mjs";import{isLiveForCompanion as J}from"./applySelect-UY-o13Ia.mjs";import{encodePartitionKey as he,sortColumnName as pe,matchesRankStaticWhere as Y,rankTableName as Z}from"./RANK_TIEBREAK-DDtST3gN.mjs";import{y as ge}from"./sql-projection-jfoe331H.mjs";import{serializeSqlValue as ee}from"./serializeSqlValue-BR4UOWoP.mjs";const _e=["de","en","es","fr","it","nl","none","pt"],ye=o=>_e.includes(o),be="a an and are as at be but by for if in into is it no not of on or such that the their then there these they this to was will with",Se="aber als am an auch auf aus bei bin bis bist da dass der den des dem die das denn dir du ein eine für hat ich im in ist mit nicht noch nur oder sich sie sind über und von vor war wie wir zu zum zur",Te="a al como con de del el en es la las lo los mas no o para pero por que se su sus un una uno y ya",ve="au aux avec ce ces dans de des du elle en et eux il je la le les leur lui ma mais me même mes moi mon ne nos notre nous on ou par pas pour qu que qui sa se ses son sur ta te tes toi ton tu un une vos votre vous y",we="a ai al alla anche che chi ci coi col come con da dal degli dei del della di do e ed gli ha hai hanno i il in la le lo ma mi ne nei nel non o per più quale quanto se si sono su sul tra un una uno vi",Ae="aan al als bij dan dat de der deze die dit door een en er het hij ij in is je kan me men met mij na naar niet nog nu of om ons ook op over te tot uit van voor was wat we wij zij zijn zo",Re="a ao aos as até com como da das de do dos e em entre era essa esse esta este eu foi há isso já mais mas me mesmo meu na nas no nos num numa o os ou para pela pelo por qual que quem se sem seu só sua também te tem um uma você",Le=/[\u0300-\u036F]/gu,ne=o=>o.normalize("NFD").replaceAll(Le,"").normalize("NFC").toLowerCase(),O=o=>new Set(ne(o).split(" ")),Ie={de:O(Se),en:O(be),es:O(Te),fr:O(ve),it:O(we),nl:O(Ae),none:new Set,pt:O(Re)},Ne=2,Oe=256,Q=new Map,je=o=>{const a=o!==void 0&&ye(o)?o:"none",l=Q.get(a);if(l)return l;const g=Ie[a],w=r=>{const A=(ne(r).match(/[\p{L}\p{N}]+/gu)??[]).filter(T=>T.length<=Oe);return g.size===0?A:A.filter(T=>!g.has(T))},m={document:w,profile:`${a}-v${String(Ne)}`,query:r=>{const A=w(r);return A.filter((T,L)=>A.lastIndexOf(T)===L)}};return Q.set(a,m),m},xe=(o,a)=>{if(!a.includes("."))return o[a];let l=o;for(const g of a.split(".")){if(l===null||typeof l!="object"||Array.isArray(l))return;l=l[g]}return l},Fe=(o,a)=>`${o}__fts_${a}`,Ce="__text__",X="__id__",Me=1e3,De=(o,a)=>a.document(o),q=(o,a)=>xe(o,a),ke=o=>typeof o=="string"?o:o==null?"":typeof o=="number"||typeof o=="bigint"||typeof o=="boolean"?String(o):JSON.stringify(o)??"",qe=(o,a,l)=>o!==void 0&&a!==void 0&&q(o,l.field)===q(a,l.field),ze=(o,a)=>De(ke(q(o,a.field)),je(a.language)).slice(0,Me).join(" "),We=(o,a,l)=>[...o.partitionBy??[],...o.sortBy.map(g=>g.field),...o.where?Object.keys(o.where):[]].every(g=>a[g]===l[g]),oe=o=>e.join(["__id__","__partition__",...o.sortBy.map((a,l)=>pe(l))].map(a=>e.identifier(a)),e`, `),te=(o,a,l,g,w,m)=>{const r=he(l.partitionBy??[],m),A=l.sortBy.map(L=>ee(m[L.field]??null)),T=e.join([w,r,...A].map(L=>ue(L)),e`, `);u(o,e`INSERT INTO ${e.identifier(a)} (${g}) VALUES (${T})`)},Be=(o,a,l,g,w,m)=>{if(w&&m&&We(l,w,m))return;const r=Z(a,l.name);w&&u(o,e`DELETE FROM ${e.identifier(r)} WHERE ${e.identifier("__id__")} = ${g}`),!(!m||l.where&&!Y(m,l.where))&&te(o,r,l,oe(l),g,m)},nn=o=>{const{broadcast:a,indexKeysFor:l,invalidateCache:g,recordCdc:w,schema:m,sql:r}=o,A=new Set,T=t=>m.tables[t]?.softDeleteMode?.field,L=new Set,z=(t,n)=>{const s=`${t}::${n.name}`;if(A.has(s))return;const d=G(t,n.name),c=n.by??[],f=T(t),h=new Map,y=u(r,e`SELECT id, _creationTime, ${e.identifier(M)} FROM ${e.identifier(t)}`).toArray();for(const v of y){const $=D(v);if(!$||!J($,f)||n.where&&!P($,n.where))continue;const E=N(c,$);V(h,E,n,$)}u(r,e`DELETE FROM ${e.identifier(d)}`);const R=Math.floor($e.boundParams/3),I=[...h];for(let v=0;v<I.length;v+=R){const $=I.slice(v,v+R),E=e.join($.map(([i,p])=>e`(${i}, ${p.value}, ${p.count})`),e`, `);u(r,e`INSERT INTO ${e.identifier(d)} (${j}, ${S}, ${_}) VALUES ${E}`)}A.add(s)},ie=(t,n,s)=>{const d=n.by??[],c=n.field??"",f=[],h=(E,i)=>{const p=ee(i);p===null?f.push(e`${k(E)} IS NULL`):f.push(e`${k(E)} = ${p}`)};for(const E of d)h(E,s[E]??null);const y=T(t);y!==void 0&&h(y,null);for(const[E,i]of Object.entries(n.where??{}))h(E,i!==null&&typeof i=="object"&&!Array.isArray(i)?i.eq:i);const R=f.length>0?e` WHERE ${e.join(f,e` AND `)}`:e``,I=m.tables[t]?.shape[c];if(I&&ge(I)){const E=u(r,e`SELECT id, _creationTime, ${e.identifier(M)} FROM ${e.identifier(t)}${R}`).toArray(),i=new Map;for(const p of E){const b=D(p);b&&V(i,"",n,b)}return{value:i.get("")?.value??null}}const v=de(n.op),$=k(c);return{value:u(r,e`SELECT ${e.raw(v)}(${$}) AS value FROM ${e.identifier(t)}${R}`).one().value??null}},re=(t,n,s,d)=>{const c=G(t,n.name),{op:f}=n,h=n.field??"",y=i=>{u(r,e`DELETE FROM ${e.identifier(c)} WHERE ${j} = ${i} AND ${_} <= 0`)},R=T(t),I=i=>!n.where||P(i,n.where),v=i=>J(i,R)&&I(i);d!==void 0&&f!=="count"&&I(d)&&F(d[h]);const $=s&&v(s)?s:void 0,E=d&&v(d)?d:void 0;if(!(!$&&!E)){if(f==="count"){for(const[i,p]of[[$,-1],[E,1]]){if(!i)continue;const b=N(n.by??[],i);u(r,C(c,b,p,p,e`${S} = ${S} + excluded.${S}, ${_} = ${_} + excluded.${_}`))}$&&y(N(n.by??[],$));return}if(f==="sum"||f==="avg"){for(const[i,p]of[[$,-1],[E,1]]){if(!i)continue;const b=F(i[h]);if(b===void 0)continue;const x=N(n.by??[],i);u(r,C(c,x,p*b,p,e`${S} = COALESCE(${S}, 0) + excluded.${S}, ${_} = ${_} + excluded.${_}`))}$&&y(N(n.by??[],$));return}if($){const i=N(n.by??[],$),p=F($[h]),b=u(r,e`SELECT ${S} AS value, ${_} AS count FROM ${e.identifier(c)} WHERE ${j} = ${i}`).toArray()[0],x=(b?.count??0)-1;if(x<=0)u(r,e`DELETE FROM ${e.identifier(c)} WHERE ${j} = ${i}`);else if(b&&p!==void 0&&b.value!==null&&p===b.value){const le=ie(t,n,$);u(r,e`UPDATE ${e.identifier(c)} SET ${S} = ${le.value}, ${_} = ${x} WHERE ${j} = ${i}`)}else u(r,e`UPDATE ${e.identifier(c)} SET ${_} = ${_} - 1 WHERE ${j} = ${i}`)}if(E){const i=N(n.by??[],E),p=F(E[h]);if(p===void 0)u(r,C(c,i,null,1,e`${_} = ${_} + 1`));else{const b=f==="min"?"MIN":"MAX";u(r,C(c,i,p,1,e`${S} = ${e.raw(b)}(COALESCE(${S}, excluded.${S}), excluded.${S}), ${_} = ${_} + 1`))}}}},ae=t=>{for(const n of m.tables[t]?.aggregateIndexes??[])z(t,n)},W=(t,n,s)=>{for(const d of m.tables[t]?.aggregateIndexes??[])re(t,d,n,s)},B=(t,n)=>{const s=`${t}::rank::${n.name}`;if(L.has(s))return;const d=Z(t,n.name),c=u(r,e`SELECT id, _creationTime, ${e.identifier(M)} FROM ${e.identifier(t)}`).toArray();u(r,e`DELETE FROM ${e.identifier(d)}`);const f=oe(n);for(const h of c){const y=D(h);!y||n.where&&!Y(y,n.where)||te(r,d,n,f,y._id,y)}L.add(s)},se=t=>{for(const n of m.tables[t]?.rankIndexes??[])B(t,n)},H=(t,n,s,d)=>{for(const c of m.tables[t]?.rankIndexes??[])Be(r,t,c,n,s,d)},U=(t,n,s,d)=>{const c=m.tables[t]?.searchIndexes??[];if(!(c.length===0||!ce(r)))for(const f of c){if(qe(d,s,f))continue;const h=Fe(t,f.name);u(r,e`DELETE FROM ${e.identifier(h)} WHERE ${e.identifier(X)} = ${n}`),s&&u(r,e`INSERT INTO ${e.identifier(h)} (${e.identifier(Ce)}, ${e.identifier(X)}) VALUES (${ze(s,f)}, ${n})`)}},K=(t,n,s)=>{for(const d of m.tables[t]?.geoIndexes??[]){const c=fe(t,d.name);u(r,e`DELETE FROM ${e.identifier(c)} WHERE ${e.identifier("__id__")} = ${n}`);const f=s?.[d.field];if(f!==null&&typeof f=="object"&&typeof f.lat=="number"&&typeof f.lng=="number"){const{lat:h,lng:y}=f,R=me({lat:h,lng:y},d.precision??Ee);u(r,e`INSERT INTO ${e.identifier(c)} (${e.identifier("__id__")}, ${e.identifier("__geohash__")}, ${e.identifier("__lat__")}, ${e.identifier("__lng__")}) VALUES (${n}, ${R}, ${h}, ${y})`)}}};return{ensureBackfilledForTable:ae,ensureBackfilledIndex:z,ensureRankBackfilled:B,ensureRankBackfilledForTable:se,syncAggregates:W,syncCompanionsForInsert:(t,n,s)=>{U(t,n,s),K(t,n,s),W(t,void 0,s),H(t,n,void 0,s),g(t,n,s),w(t,n,"insert",s),a({indexKeys:l(t,s),key:n,op:"insert",row:s,table:t})},syncGeo:K,syncRanks:H,syncSearch:U}};export{oe as B,nn as S,X as T,te as W,Fe as c,Ce as l,De as n,je as x,ze as y};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{createShardCtxDb as b}from"./NotUniqueError-
|
|
1
|
+
import{createShardCtxDb as b}from"./NotUniqueError-BeTJrgRe.mjs";import{createRelayLink as I}from"./DEFAULT_MAX_RELAYS-B19vrJxP.mjs";import{ConflictError as N}from"./ConflictError-C8GtJmjS.mjs";import{runShardMigrations as v}from"./runShardMigrations-BAtfEXbB.mjs";import{relayName as q}from"./DEFAULT_PROMOTION_THRESHOLDS-B2rUe1bg.mjs";const C=(_,m={})=>({_meta:{column:{notNull:!0,...m}},kind:_}),D=(_,m,E)=>{const{describe:k,expect:i,it:f}=E;k(`engine contract: ${_}`,()=>{k("optimistic concurrency",()=>{const g=p=>({tables:{items:{indexes:[],shape:{title:C("string"),version:C("number",{notNull:!1})},triggerMap:{clobber:{handler:()=>{p.exec(`UPDATE "items" SET "__doc__" = json_set("__doc__", '$.version', 99) WHERE "id" = 'i1'`)},op:"update",timing:"before"}}}}});f("raises a CONFLICT of kind `occ` when a write's snapshot is clobbered",async()=>{const{close:p,host:d}=m();try{const c=d.sql,l=g(c);v(c,l);const s=b({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(N)}finally{p?.()}}),f("reports the conflict as CONFLICT/409 rather than retrying it away",async()=>{const{close:p,host:d}=m();try{const c=d.sql,l=g(c);v(c,l);const s=b({schema:l,sql:c});await s.insert("items",{_id:"i1",title:"first",version:1},{allowExplicitId:!0});let r;try{await s.patch("i1",{title:"second"})}catch(t){r=t}const e=r;i(e.code).toBe("CONFLICT"),i(e.kind).toBe("occ")}finally{p?.()}}),f("leaves the row readable and unchanged after a conflict",async()=>{const{close:p,host:d}=m();try{const c=d.sql,l=g(c);v(c,l);const s=b({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 r=await s.get("i1");i(r?.title).toBe("first"),i(r?.version).toBe(99)}finally{p?.()}}),f("raises a CONFLICT of kind `trigger` when a trigger writes its own row through the db",async()=>{const{close:p,host:d}=m();try{const c=d.sql,l={tables:{items:{indexes:[],shape:{title:C("string"),version:C("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=b({schema:l,sql:c});await s.insert("items",{_id:"i1",title:"first",version:1},{allowExplicitId:!0});let r;try{await s.patch("i1",{title:"second"})}catch(t){r=t}const e=r;i(e).toBeInstanceOf(N),i(e.code).toBe("CONFLICT"),i(e.kind).toBe("trigger")}finally{p?.()}})}),k("shape-poke ordering",()=>{const g="shard-a",p={args:{},name:"messages"},d=(e,t,o,a)=>e.accept(t?.()??{},{connectionId:o,shapes:{[a]:p}}),c=(e,t)=>{let o=0,a=0;const n=u=>()=>{throw new Error(`the relay poke path must not reach RelayHost.${u}`)},h={fetch:(u,O)=>{if(JSON.parse(O?.body??"{}").type!=="relay_shape_subscribe")return Promise.resolve(new Response(void 0,{status:204}));const B=t[a];if(a+=1,B===void 0)throw new Error("the relay asked for more seeds than this fixture supplies");return Promise.resolve(Response.json(B))}},y={get:()=>h,getByName:()=>h,idFromName:u=>u},w={buildShapeDiff:n("buildShapeDiff"),computeOpLogShapeSeed:n("computeOpLogShapeSeed"),currentCdcEpoch:n("currentCdcEpoch"),deliverWhisperLocal:n("deliverWhisperLocal"),doName:()=>q(g,0),env:()=>({SHARD:y}),getWebSockets:()=>e.getSockets(),maskMetadata:n("maskMetadata"),nextPokeId:()=>(o+=1,`poke-${String(o)}`),readAttachment:u=>u.deserializeAttachment?.(),recordShapePokeFanout:()=>{},resolveShape:n("resolveShape"),rlsMetadata:n("rlsMetadata"),shardBinding:()=>"SHARD",sql:n("sql")},S=I(w);if(S===void 0)throw new Error("expected a relay link for a `…::relay::N` name");return S},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 a=await e.seedRelayShape(t,o,p,{identity:void 0,userId:void 0});if(a!=="ok")throw new Error(`seed failed: ${JSON.stringify(a)}`)},r=(e={})=>l({...p,checkpoint:20,epoch:"e1",fromCursor:10,rowsPatch:[{id:"r1",op:"upsert",value:{title:"hello"}}],type:"relay_shape_poke",...e});f("frames a poke as pokeStart → pokePart per shape → pokeEnd, under one poke id",async()=>{const{close:e,createSocket:t,readFrames:o,sockets:a}=m();try{const n=c(a,[{cursor:10,epoch:"e1",frames:[]}]),h=d(a,t,"c-alice","s1");await s(n,h,"s1"),await n.handleControl(r());const y=(await o(h)).map(w=>JSON.parse(w));i(y.map(w=>w.type)).toStrictEqual(["pokeStart","pokePart","pokeEnd"]),i(new Set(y.map(w=>w.pokeId)).size).toBe(1),i(y[1]?.shapeId).toBe("s1"),i(y[2]?.checkpoint).toBe(20)}finally{e?.()}}),f("delivers a poke only to sockets whose cursor matches, and advances them past it",async()=>{const{close:e,createSocket:t,readFrames:o,sockets:a}=m();try{const n=c(a,[{cursor:10,epoch:"e1",frames:[]},{cursor:7,epoch:"e1",frames:[]}]),h=d(a,t,"c-alice","s1"),y=d(a,t,"c-bob","s2");await s(n,h,"s1"),await s(n,y,"s2"),await n.handleControl(r());const w=await o(h);i(w.length).toBe(3);const S=await o(y);i(S.length).toBe(0),await n.handleControl(r());const u=await o(h);i(u.length).toBe(3)}finally{e?.()}}),f("skips a socket whose cursor matches under a different CDC epoch",async()=>{const{close:e,createSocket:t,readFrames:o,sockets:a}=m();try{const n=c(a,[{cursor:10,epoch:"e1",frames:[]}]),h=d(a,t,"c-alice","s1");await s(n,h,"s1"),await n.handleControl(r({epoch:"e2"}));const y=await o(h);i(y.length).toBe(0),await n.handleControl(r());const w=await o(h);i(w.length).toBe(3)}finally{e?.()}})}),k("RLS identity under live subscription",()=>{const g="shard-a",p={args:{},name:"lobby-messages"},d={args:{},name:"my-orders"},c=s=>{const r=[],e=[],t={fetch:(a,n)=>(r.push(JSON.parse(n?.body??"{}")),Promise.resolve(new Response(void 0,{status:204})))},o=I({buildShapeDiff:()=>[{id:"r1",op:"upsert",value:{}}],computeOpLogShapeSeed:()=>({baseCheckpoint:void 0,cursor:10,epoch:"e1",rowsPatch:[]}),currentCdcEpoch:()=>"e1",deliverWhisperLocal:()=>0,doName:()=>g,env:()=>({SHARD:{get:()=>t,getByName:()=>t,idFromName:a=>a}}),getWebSockets:()=>[],maskMetadata:()=>({columns:[]}),nextPokeId:()=>"poke-1",readAttachment:()=>({}),recordShapePokeFanout:()=>{},resolveShape:(a,n,h)=>(e.push(h),a===d.name?{columns:["id"],effectiveWhere:{org:h?.identity?.org??"anonymous"},global:!1,table:"orders"}:{columns:["id"],effectiveWhere:{room:"lobby"},global:!1,table:"messages"}),rlsMetadata:()=>({policies:[]}),shardBinding:()=>"SHARD",sql:()=>s});if(o===void 0)throw new Error("expected an owner link for an un-suffixed DO name");return{owner:o,posts:r,resolvedUnder:e}},l=async(s,r)=>{await s.handleControl(new Request("https://owner.internal/_lunora/relay",{body:JSON.stringify({...r,connectionId:"c-alice",identity:{org:"acme"},relayIndex:0,subId:"s1",type:"relay_shape_subscribe",userId:"u1"}),headers:{"content-type":"application/json"},method:"POST"}))};f("seeds a subscriber under its own forwarded identity, never the anonymous one",async()=>{const{close:s,host:r}=m();try{const{owner:e,resolvedUnder:t}=c(r.sql);await l(e,d),i(t.some(o=>o?.userId==="u1"&&o.identity?.org==="acme")).toBe(!0)}finally{s?.()}}),f("routes an identity-scoped shape to a per-socket poke, not the cohort multicast",async()=>{const{close:s,host:r}=m();try{const{owner:e,posts:t}=c(r.sql);await l(e,d),t.length=0,await e.onFlush(new Set(["orders"]),20);const o=t.filter(a=>a.type==="relay_shape_poke");i(o.length).toBe(1),i(o[0]?.targetConnectionId).toBe("c-alice")}finally{s?.()}}),f("still multicasts an identity-blind shape to the whole cohort",async()=>{const{close:s,host:r}=m();try{const{owner:e,posts:t}=c(r.sql);await l(e,p),t.length=0,await e.onFlush(new Set(["messages"]),20);const o=t.filter(a=>a.type==="relay_shape_poke");i(o.length).toBe(1),i(o[0]?.targetConnectionId).toBeUndefined()}finally{s?.()}})})})};export{D as defineEngineContractSuite};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{LunoraError as c}from"@lunora/errors";import{sql as o}from"drizzle-orm";import{quoteIdentifier as m}from"./quoteIdentifier-CObIFRhb.mjs";import{s as u,a as p}from"./wire-codec-Dsy70M3Q.mjs";import{runDrizzle as _}from"./runDrizzle-
|
|
1
|
+
import{LunoraError as c}from"@lunora/errors";import{sql as o}from"drizzle-orm";import{quoteIdentifier as m}from"./quoteIdentifier-CObIFRhb.mjs";import{s as u,a as p}from"./wire-codec-Dsy70M3Q.mjs";import{runDrizzle as _}from"./runDrizzle-C3n5gJsk.mjs";import{b as E}from"./sql-projection-jfoe331H.mjs";import"./serializeSqlValue-BR4UOWoP.mjs";const T=/^[A-Za-z_$][\w$]*$/u,S=e=>T.test(e)?e:`"${e.replaceAll("\\",String.raw`\\`).replaceAll('"',String.raw`\"`)}"`,l="__doc__",s="__originals__",R=e=>{if(Object.hasOwn(e,s))throw new c("BAD_REQUEST",`"${s}" is reserved by the row store's document encoding and cannot be used as a field name — rename the field`);let t,r;for(const[i,n]of Object.entries(e)){const a=E(n);a!==void 0&&(t??={...e},r??=Object.create(null),t[i]=a,r[i]=n)}t&&r&&(t[s]=r);try{return JSON.stringify(p(t??e))}catch(i){throw new c("BAD_REQUEST",`this document cannot be stored: ${i instanceof Error?i.message:String(i)}`)}},y=e=>{const t=u(JSON.parse(e)),{[s]:r,...i}=t;return r===null||typeof r!="object"||Array.isArray(r)?t:{...i,...r}},C=(e,t)=>`${e}__geo_${t}`,d=(e,t)=>t==="_id"||t==="id"?`${e}id`:t==="_creationTime"?`${e}_creationTime`:`json_extract(${e}${l}, '$.${S(t).replaceAll("'","''")}')`,A=e=>d("",e),v=e=>o.raw(A(e)),O=(e,t)=>d(`${m(e)}.`,t),B=(e,t)=>o.raw(O(e,t)),F=(e,t,r,i)=>o`CREATE ${i?o`UNIQUE `:o``}INDEX IF NOT EXISTS ${o.identifier(e)} ON ${o.identifier(t)} (${r})`,f=o.identifier("__key__"),I=o.identifier("__value__"),h=o.identifier("__count__"),X=(e,t,r,i,n)=>o`INSERT INTO ${o.identifier(e)} (${f}, ${I}, ${h}) VALUES (${t}, ${r}, ${i}) ON CONFLICT(${f}) DO UPDATE SET ${n}`,x=e=>{const t=[];for(const[r,i]of Object.entries(e.shape)){const n=i._meta?.column;n&&t.push([r,n])}return t},b=e=>{if(!e)return;const t=e[l];let r;typeof t=="string"?r=y(t):t&&typeof t=="object"?r=t:r={};const{id:i}=e;typeof i=="string"&&(r._id=i);const n=e._creationTime;return typeof n=="number"&&(r._creationTime=n),r},z=e=>{try{return b(e)}catch{return}},$=new WeakMap,P=e=>{const t=$.get(e);if(t!==void 0)return t;let r;try{_(e,o`CREATE VIRTUAL TABLE IF NOT EXISTS ${o.identifier("__lunora_fts_probe")} USING fts5(x)`),r=!0}catch{r=!1}finally{try{_(e,o`DROP TABLE IF EXISTS ${o.identifier("__lunora_fts_probe")}`)}catch{}}return $.set(e,r),r};export{X as A,P as C,z as D,b as E,x as I,R as L,v as N,B as O,O as S,h as T,A as _,l as a,f as c,y as g,C as h,S as j,I as p,s,F as y};
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{LunoraError as E}from"@lunora/errors";import{sql as m}from"drizzle-orm";import{runDrizzle as h}from"./runDrizzle-
|
|
1
|
+
import{LunoraError as E}from"@lunora/errors";import{sql as m}from"drizzle-orm";import{runDrizzle as h}from"./runDrizzle-C3n5gJsk.mjs";import{liftSourceId as x}from"./liftSourceId-DApAbu7Q.mjs";import{normalizeSourceValue as K}from"./liftSourceId-DApAbu7Q.mjs";import{runExternalSourceTick as v,materializeExternalRowsIncremental as M}from"./materializeExternalRows-D53xwGfY.mjs";const _="__lunora_source_cursor",D=e=>e instanceof Date?`d:${e.toISOString()}`:typeof e=="bigint"?`b:${e.toString()}`:typeof e=="number"?`n:${e.toString()}`:`s:${e}`,R=e=>{const t=e.slice(2);switch(e[0]){case"b":return BigInt(t);case"d":return new Date(t);case"n":return Number(t);default:return t}},k=/^-?\d+$/,I=/^-?\d+(?:\.\d+)?$/,A=(e,t)=>e instanceof Date&&t instanceof Date?e.getTime()>t.getTime():typeof e=="bigint"&&typeof t=="bigint"||typeof e=="number"&&typeof t=="number"?e>t:typeof e=="string"&&typeof t=="string"&&I.test(e)&&I.test(t)?k.test(e)&&k.test(t)?BigInt(e)>BigInt(t):Number(e)>Number(t):String(e)>String(t),q=(e,t,a)=>{let n=a===null?void 0:R(a);for(const r of e){const s=r[t];if(s==null)continue;const i=s;(n===void 0||A(i,n))&&(n=i)}return n===void 0?null:D(n)},O=e=>{h(e,m`CREATE TABLE IF NOT EXISTS ${m.identifier(_)} (
|
|
2
2
|
table_name TEXT NOT NULL,
|
|
3
3
|
shard_key TEXT NOT NULL,
|
|
4
4
|
watermark TEXT,
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{applyCdcChanges as m}from"./CDC_LOG_TABLE-
|
|
1
|
+
import{applyCdcChanges as m}from"./CDC_LOG_TABLE-DH-KHUfU.mjs";import{selectShapeRows as f}from"./selectShapeMemberIds-WzxOG62k.mjs";import{diffExternalSource as g,projectExternalSourceRow as c}from"./diffExternalSource-DMpkJta1.mjs";import{stableStringify as p}from"./stableStringify-BjLh4gvA.mjs";const x=async(t,s,r,e)=>{const{changes:n,nextBaseline:a}=g(s,r,e);return await m(t,n),{applied:n.length,nextBaseline:a}},E=async(t,s,r)=>{const{columns:e,deletedIds:n,table:a}=r,i=[];for(const u of s){const l=c(u,e),o=String(l._id);if(n?.has(o)){await t.get(o,a)&&i.push({id:o,op:"delete",seq:0,table:a,ts:0});continue}const d=await t.get(o,a);d&&p(c({...d,_id:o},e))===p(l)||i.push({doc:l,id:o,op:"insert",seq:0,table:a,ts:0})}return await m(t,i),{applied:i.length}},h=(t,s,r)=>{const e=new Map;for(const{doc:n,id:a}of f(t,s,void 0))e.set(a,p(c({...n,_id:a},r)));return e},R=async(t,s,r,e)=>{const n=h(t,e.table,e.columns);return x(s,r,n,e)};export{x as materializeExternalRows,E as materializeExternalRowsIncremental,h as readExternalSourceBaseline,R as runExternalSourceTick};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{LunoraError as m}from"@lunora/errors";import{sql as r}from"drizzle-orm";import{MySqlDialect as c}from"drizzle-orm/mysql-core";import{PgDialect as u}from"drizzle-orm/pg-core";import{SQLiteSyncDialect as p}from"drizzle-orm/sqlite-core";const f=new u,d=new c,S=new p,g={mysql:d,postgres:f,sqlite:S},a={boundParams:100,compoundSelect:5,likePattern:50,sqlTextLength:1e5},h=a.boundParams/2,L=e=>e===null||typeof e=="boolean"?!0:typeof e=="number"?Number.isFinite(e):typeof e=="string"&&e.isWellFormed(),w=(e,t)=>{const{params:n,sql:o}=g[e].sqlToQuery(t);return{params:n,sql:o}},$=e=>r`${e}`,O=e=>{if(e.length===0)throw new Error("unionAll: expected at least one branch");let t=[...e];for(;t.length>a.compoundSelect;){const n=[];for(let o=0;o<t.length;o+=a.compoundSelect){const l=r.join(t.slice(o,o+a.compoundSelect),r` UNION ALL `);n.push(r`SELECT * FROM (${l}) ${r.identifier("__u__")}`)}t=n}return r.join(t,r` UNION ALL `)},I=(e,t,n,o=h)=>{const l=n?r` NOT IN `:r` IN `,s=t.every(i=>L(i));if(t.length>o&&!s)throw new m("BAD_REQUEST",`an "in" list of ${String(t.length)} values holds a value JSON cannot carry (bytes, a non-finite number, or malformed text), so it cannot be bound as one parameter — and ${String(t.length)} placeholders exceed SQLite's per-statement cap of 100 on Durable Objects and D1. Narrow the list to ${String(o)} values or fewer.`);return t.length<=o?r`${e}${l}(${r.join(t.map(i=>$(i)),r`, `)})`:r`${e}${l}(SELECT ${r.identifier("value")} FROM json_each(${JSON.stringify(t)}))`};export{a as WORKERD_SQLITE_LIMITS,$ as param,w as renderSql,I as sqliteInList,O as unionAll};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{LunoraError as l}from"@lunora/errors";import{renderSql as o,WORKERD_SQLITE_LIMITS as n}from"./param-CYxL68V-.mjs";const i=(t,e,...r)=>{if(e.length*3>n.sqlTextLength){const s=new TextEncoder().encode(e).length;if(s>n.sqlTextLength)throw new l("INTERNAL",`SQL statement is ${String(s)} bytes, over this runtime's ${String(n.sqlTextLength)}-byte limit`)}if(r.length>n.boundParams)throw new l("INTERNAL",`SQL statement binds ${String(r.length)} parameters, over this runtime's limit of ${String(n.boundParams)}`);return t.exec.call(t,e,...r)},u=(t,e)=>{const{params:r,sql:s}=o("sqlite",e);return i(t,s,...r)},h=t=>t??null,g=t=>{if(!(t==null||t===""))try{return JSON.parse(t)}catch{return}};export{g as decodeJsonColumn,h as orNull,u as runDrizzle,i as runSql};
|
|
@@ -0,0 +1,5 @@
|
|
|
1
|
+
import{l as I,T as N,c as S}from"./ctx-db-companions-c12P7dbv.mjs";import"@lunora/errors";import{sql as e}from"drizzle-orm";import{aggregateTableName as p}from"./aggregateTableName-DgYMC5tr.mjs";import{backfillSearchIndexesForTable as g}from"./backfillAggregateIndexes-BEMWTEq1.mjs";import{migrateCdcLog as l,migrateCdcMeta as h}from"./CDC_LOG_TABLE-DH-KHUfU.mjs";import{migrateClientWatermark as R}from"./CLIENT_WATERMARK_TABLE-LrKfdxyt.mjs";import{migrateGlobalShapeSnapshot as C}from"./GLOBAL_SHAPE_SNAPSHOT_TABLE-B2LKe4KU.mjs";import{migrateIdempotency as O}from"./IDEMPOTENCY_TABLE-tQ5mnqvw.mjs";import{migrateSearchState as u}from"./SEARCH_STATE_TABLE-DRk_SB72.mjs";import{runDrizzle as a}from"./runDrizzle-C3n5gJsk.mjs";import{a as U,N as E,y as _,I as b,C as X,c as x,p as B,T as c,h as D}from"./do-sql-C7qrlm6-.mjs";import{migrateDurableStreams as F}from"./appendStreamChunk-ksZYy1hZ.mjs";import{sortColumnName as M,rankTableName as Y}from"./RANK_TIEBREAK-DDtST3gN.mjs";import{recordSchemaVersion as k}from"./SCHEMA_HISTORY_MAX_VERSIONS-CEK7b_7v.mjs";const y=(r,t,o)=>{for(const i of o.indexes){const n=`${t}_${i.name}`,s=e.join(i.fields.map(f=>E(f)),e`, `);a(r,_(n,t,s,i.unique??!1))}for(const[i,n]of b(o)){if(!n.unique)continue;const s=`${t}_unique_${i}`;a(r,_(s,t,E(i),!0))}},j=(r,t,o)=>{if(!(!o.searchIndexes||o.searchIndexes.length===0||!X(r))){for(const i of o.searchIndexes){const n=S(t,i.name);a(r,e`CREATE VIRTUAL TABLE IF NOT EXISTS ${e.identifier(n)} USING fts5(${e.identifier(I)}, ${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")})`)}g(r,t,o)}},q=(r,t,o)=>{if(o.geoIndexes)for(const i of o.geoIndexes){const n=D(t,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=`${t}__geo_${i.name}__btree`;a(r,_(s,n,e`${e.identifier("__geohash__")} ASC, ${e.identifier("__id__")} ASC`,!1))}},G=(r,t,o)=>{if(o.aggregateIndexes)for(const i of o.aggregateIndexes){const n=p(t,i.name);a(r,e`CREATE TABLE IF NOT EXISTS ${e.identifier(n)} (${x} TEXT PRIMARY KEY, ${B} REAL, ${c} INTEGER NOT NULL DEFAULT 0)`),a(r,e`PRAGMA table_info(${e.identifier(n)})`).toArray().some(s=>s.name==="__count__")||a(r,e`ALTER TABLE ${e.identifier(n)} ADD COLUMN ${c} INTEGER NOT NULL DEFAULT 0`)}},P=(r,t,o)=>{if(o.rankIndexes)for(const i of o.rankIndexes){const n=Y(t,i.name),s=i.sortBy.map((T,d)=>M(d)),f=s.map(T=>e`${e.identifier(T)} BLOB`),$=f.length>0?e`, ${e.join(f,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${$})`);const m=[e`${e.identifier("__partition__")} ASC`];for(const[T,d]of s.entries()){const A=i.sortBy[T]?.direction;m.push(e`${e.identifier(d)} ${e.raw(A==="desc"?"DESC":"ASC")}`)}m.push(e`${e.identifier("__id__")} ASC`);const L=`${t}__rank_${i.name}__btree`;a(r,_(L,n,e.join(m,e`, `),!1))}},te=(r,t,o={})=>{o.schemaSnapshot!==void 0&&k(r,o.schemaSnapshot.hash,o.schemaSnapshot.json),u(r);for(const[i,n]of Object.entries(t.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(U)} TEXT NOT NULL
|
|
5
|
+
)`),y(r,i,n),j(r,i,n),q(r,i,n),G(r,i,n),P(r,i,n));o.cdc&&(l(r),h(r),R(r)),O(r),C(r),F(r)};export{te as runShardMigrations};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{sql as e}from"drizzle-orm";import{runDrizzle as $}from"./runDrizzle-
|
|
1
|
+
import{sql as e}from"drizzle-orm";import{runDrizzle as $}from"./runDrizzle-C3n5gJsk.mjs";import{N as r}from"./do-sql-C7qrlm6-.mjs";const E=(d,i,s,o)=>{const f=s-(i.after??0),t=[e`${r(i.field)} IS NOT NULL`,e`${r(i.field)} < ${f}`];i.softDeleteField!==void 0&&t.push(e`${r(i.softDeleteField)} IS NULL`);const a=e`SELECT id FROM ${e.identifier(i.table)} WHERE ${e.join(t,e` AND `)} LIMIT ${e.raw(String(Math.max(0,Math.floor(o))+1))}`,l=$(d,a).toArray(),n=l.length>o,m=l.slice(0,o).map(p=>p.id);return{hasMore:n,ids:m}};export{E as selectExpiredIds};
|
package/dist/packem_shared/{selectShapeMemberIds-EPo0xxs_.mjs → selectShapeMemberIds-WzxOG62k.mjs}
RENAMED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{sql as e}from"drizzle-orm";import{runDrizzle as m}from"./runDrizzle-
|
|
1
|
+
import{sql as e}from"drizzle-orm";import{runDrizzle as m}from"./runDrizzle-C3n5gJsk.mjs";import{a as c,E as a,N as u}from"./do-sql-C7qrlm6-.mjs";import{sqliteInList as h}from"./param-CYxL68V-.mjs";import{compileWhereSql as S}from"./compileWhereSql-B3hq_v98.mjs";import{serializeSqlValue as E}from"./serializeSqlValue-BR4UOWoP.mjs";const $={fieldRef:u,serialize:E},R=i=>{if(i.length!==0)return h(e`${e.identifier("id")}`,i,!1)},p=(i,o)=>{const r=[];o&&r.push(o);const t=S(i,$);return t&&r.push(t),r.length===0?e``:e` WHERE ${e.join(r,e` AND `)}`},L=(i,o,r)=>{const t=p(r,void 0),f=m(i,e`SELECT id, _creationTime, ${e.identifier(c)} FROM ${e.identifier(o)}${t}`).toArray(),n=[];for(const s of f){const d=a(s),{id:l}=s;d!==void 0&&typeof l=="string"&&n.push({doc:d,id:l})}return n},M=(i,o,r,t)=>{if(t.length===0)return new Set;const f=p(r,R(t)),n=m(i,e`SELECT id FROM ${e.identifier(o)}${f}`).toArray();return new Set(n.map(s=>s.id))};export{M as selectShapeMemberIds,L as selectShapeRows};
|
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.25",
|
|
4
4
|
"description": "Host-neutral reactive engine for Lunora: per-shard state, OCC, CDC, reactive subscriptions, and the poke protocol. Consumes @lunora/platform host contracts and can be mounted on any platform host.",
|
|
5
5
|
"keywords": [
|
|
6
6
|
"cloudflare",
|
|
@@ -48,8 +48,8 @@
|
|
|
48
48
|
"access": "public"
|
|
49
49
|
},
|
|
50
50
|
"dependencies": {
|
|
51
|
-
"@lunora/errors": "1.0.0-alpha.
|
|
52
|
-
"@lunora/platform": "1.0.0-alpha.
|
|
51
|
+
"@lunora/errors": "1.0.0-alpha.21",
|
|
52
|
+
"@lunora/platform": "1.0.0-alpha.10",
|
|
53
53
|
"drizzle-orm": "^0.45.2"
|
|
54
54
|
},
|
|
55
55
|
"engines": {
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{LunoraError as b}from"@lunora/errors";import{n as Ft,S as Ot,x as Qe,T as _e,y as Bt,c as qt}from"./ctx-db-companions-D2ZMFBrP.mjs";import{sql as n}from"drizzle-orm";import{s as Ut}from"./wire-codec-Dsy70M3Q.mjs";import{aggregateSqlFunction as Te,normalizeCountArgument as Ht,throwingScheduler as Pt}from"./AGGREGATE_SQL_FUNCTION-CTo0-9iZ.mjs";import{encodeAggregateKey as ke,readAggregateValue as Le,aggregateTableName as De}from"./aggregateTableName-DgYMC5tr.mjs";import{mergeWhere as Y,CountRlsUnsupportedError as We,selectIndexForGroupBy as jt,selectIndexForCount as Qt,selectIndexForAggregate as Kt}from"./CountRlsUnsupportedError-8BqPYQoP.mjs";import{backfillSearchIndexesForTable as Gt}from"./backfillAggregateIndexes-Czk8MQ3M.mjs";import{backfillAggregateIndexes as Dr,backfillRankIndexes as Wr,backfillSearchIndexes as Fr}from"./backfillAggregateIndexes-Czk8MQ3M.mjs";import{appendCdcChange as Yt}from"./CDC_LOG_TABLE-CIfexI1y.mjs";import{CDC_LOG_TABLE as Br,applyCdcChanges as qr,bumpCdcEpoch as Ur,minCdcSeq as Hr,readCdcChanges as Pr,readCdcCursor as jr,readCdcEpoch as Qr,trimCdcChanges as Kr}from"./CDC_LOG_TABLE-CIfexI1y.mjs";import{computeRankPage as ot}from"./computeRankPage-CPVNOrM5.mjs";import{SCAN_DEP as H}from"./SCAN_DEP-D_yR9EeV.mjs";import{runDrizzle as B}from"./runDrizzle-CgYGDEeB.mjs";import{a as j,L as ae,p as Re,T as Fe,c as Ae,N as J,E as le,I as St,C as zt,D as _t,h as Jt,O as it}from"./do-sql-Cg_QiQYA.mjs";import{WORKERD_SQLITE_LIMITS as Tt,unionAll as Ue,sqliteInList as Vt}from"./param-C68MV3DD.mjs";import{coveringGeohashes as Xt,boundingBoxGeohashes as Zt,pointInBoundingBox as en,haversineMeters as tn}from"./GEO_DEFAULT_PRECISION-DyI5zggj.mjs";import{NotFoundError as nn}from"./NotFoundError-BhF7FeFr.mjs";import{normalizeOrderKeys as rn,buildSeekWhere as Rt,decodeCursor as He,applySelect as at,encodeCursor as Pe,softDeleteScope as de,buildSeekBeforeWhere as on}from"./applySelect-UY-o13Ia.mjs";import{sortColumnName as st,resolveRankPartition as an,encodePartitionKey as sn,RANK_TIEBREAK as dn,rankTableName as dt}from"./RANK_TIEBREAK-DDtST3gN.mjs";import{indexKeysForRow as ln,buildIndexRange as cn}from"./buildIndexRange-DFsdtPjD.mjs";import{assertFlatPredicate as Oe,resolveRelationPredicates as lt}from"./DEFAULT_MAX_RELATION_KEYS-DjKka36Z.mjs";import{runRowValidators as Be,resolveWith as ct,relationHooks as ut,applyOnDelete as un,fanOutScalarCounts as fn}from"./applyOnDelete-By23GK-k.mjs";import{guardWriter as hn}from"./RLS_UNWRAP_SYMBOL-DcqORh2s.mjs";import{f as pn}from"./sql-projection-jfoe331H.mjs";import{createSystemReader as mn}from"./createSystemReader-DcDcrtM3.mjs";import{ConflictError as pe}from"./ConflictError-C8GtJmjS.mjs";import{runTriggers as $n}from"./hasTrigger-CbkOHExZ.mjs";import{compileWhereSql as ne}from"./compileWhereSql-DxD5mzDy.mjs";import{CLIENT_WATERMARK_TABLE as Yr,advanceClientWatermark as zr,migrateClientWatermark as Jr,readClientWatermark as Vr}from"./CLIENT_WATERMARK_TABLE-BogWgD2Q.mjs";import{GLOBAL_SHAPE_SNAPSHOT_TABLE as Zr,deleteGlobalShapeSnapshot as eo,deleteGlobalShapeSnapshotsForConnection as to,migrateGlobalShapeSnapshot as no,readGlobalShapeSnapshot as ro,writeGlobalShapeSnapshot as oo}from"./GLOBAL_SHAPE_SNAPSHOT_TABLE-T5smo6RP.mjs";import{IDEMPOTENCY_TABLE as ao,readIdempotent as so,trimIdempotent as lo,writeIdempotent as co}from"./IDEMPOTENCY_TABLE-DPFwgQbE.mjs";import{runShardMigrations as fo}from"./runShardMigrations-CtlcSZ3r.mjs";import{SEARCH_STATE_TABLE as po}from"./SEARCH_STATE_TABLE-MDlr30EJ.mjs";import{selectShapeMemberIds as $o,selectShapeRows as wo}from"./selectShapeMemberIds-EPo0xxs_.mjs";import{serializeSqlValue as ie}from"./serializeSqlValue-BR4UOWoP.mjs";import{quoteIdentifier as wn}from"./quoteIdentifier-CObIFRhb.mjs";const gn=o=>{const i=new TextEncoder().encode(o);let t="";for(const d of i)t+=String.fromCodePoint(d);return btoa(t)},bn=o=>{const i=atob(o),t=Uint8Array.from(i,d=>d.codePointAt(0)??0);return new TextDecoder().decode(t)},En=()=>new b("BAD_REQUEST","invalid cursor"),ft=16,ht=8,V=1024,Ke=(o,i)=>i.query(o),yn=(o,i,t)=>{const d=Ft(o,t);if(d.length===0)return 0;let c=0;for(const[p,$]of i.entries()){const R=p===i.length-1;let y=0;for(const g of d)(R?g.startsWith($):g===$)&&(y+=1);if(y===0)return 0;c+=y}return c},Nn=(o,i)=>{if(!i)return{exact:!0,lower:o,upper:o};const t=[...o].at(-1)??"",d=(t.codePointAt(0)??0)+1;if(d>=55296&&d<=57343||d>1114111)return{exact:!0,lower:o,upper:o};const c=o.slice(0,o.length-t.length);return{exact:!1,lower:o,upper:c+String.fromCodePoint(d)}},Sn=(o,i,t)=>{const d={eq:(c,p)=>{if(!o.definition.filterFields?.includes(c))throw new b("INTERNAL",`field "${c}" is not a filter field of search index "${o.indexName}" on table "${i}"`);if(o.filters.length>=ht)throw new b("BAD_REQUEST",`search index "${o.indexName}" on table "${i}": at most ${String(ht)} .eq() filters are supported per search query`);return o.filters.push({field:c,value:p}),d},search:(c,p)=>{const $=o;if(c!==$.definition.field)throw new b("INTERNAL",`search index "${$.indexName}" on table "${i}" indexes "${$.definition.field}", not "${c}"`);const R=Ke(p,t).length;if(R>ft)throw new b("BAD_REQUEST",`search index "${$.indexName}" on table "${i}": at most ${String(ft)} search terms are supported (got ${String(R)})`);return $.field=c,$.query=p,$.hasQuery=!0,d}};return d},_n=o=>{if(o.length>V)throw new b("BAD_REQUEST",`more than ${String(V)} documents match this search — narrow it with filters or read it a page at a time with .paginate()`)},Tn=o=>Math.min(o.offset+o.numItems+1,V),Rn=o=>gn(`search:${String(o)}`),An=o=>{let i;try{i=bn(o)}catch{return}if(!i.startsWith("search:"))return;const t=Number(i.slice(7));return Number.isInteger(t)&&t>=0?t:void 0},xn=o=>{if(typeof o.endCursor=="string")throw new b("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?An(o.cursor):0;if(t===void 0)throw En();if(t+i>V)throw new b("BAD_REQUEST",`search pagination reaches past the ${String(V)}-document limit (offset ${String(t)} + ${String(i)} requested) — narrow the query or the filters instead`);return{numItems:i,offset:t}},In=(o,i)=>{const t=i.offset+i.numItems,d=i.numItems>0&&o.length>t;return{continueCursor:d?Rn(t):null,isDone:!d,page:o.slice(i.offset,t)}},vn=o=>{if(o===void 0)return V+1;if(!Number.isFinite(o))return V;const i=Math.max(0,Math.floor(o));if(i>V)throw new b("BAD_REQUEST",`search returns at most ${String(V)} documents (asked for ${String(i)}) — narrow the query or paginate instead`);return i},Cn=/^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/iu,Mn=o=>{if(!Cn.test(o))throw new b("INTERNAL",`invalid clientId ${JSON.stringify(o)}: a client-supplied row id must be a UUID`)},pt=50,At=500,mt=Math.floor(Tt.boundParams/3),he=Tt.boundParams,kn=128,se=(o,i,t)=>{const d=i??At;if(o>d)throw new b("BATCH_LIMIT_EXCEEDED",`${t}: batch of ${String(o)} exceeds the limit of ${String(d)} (raise options.limit or chunk the call)`,{status:400})},Ln=o=>{const i={eq:(t,d)=>(o.sqlConditions.push({comparator:"=",field:t,value:d}),i),gt:(t,d)=>(o.sqlConditions.push({comparator:">",field:t,value:d}),i),gte:(t,d)=>(o.sqlConditions.push({comparator:">=",field:t,value:d}),i),lt:(t,d)=>(o.sqlConditions.push({comparator:"<",field:t,value:d}),i),lte:(t,d)=>(o.sqlConditions.push({comparator:"<=",field:t,value:d}),i)};return i},Dn=o=>Math.max(o,V),xt=(o,i)=>{const t=o.filters.map(d=>n`${J(d.field)} = ${ie(d.value)}`);return i&&t.push(i),t},Wn=(o,i,t,d,c)=>{const p=Ke(t.query,Qe(t.definition.language));if(p.length===0)return[];const $=qt(i,t.indexName),R=`${$}__vocab`,y=p.length-1,g=p.map((D,k)=>{const Q=Nn(D,k===y),F=Q.exact?n`${n.identifier("term")} = ${Q.lower}`:n`${n.identifier("term")} >= ${Q.lower} AND ${n.identifier("term")} < ${Q.upper}`;return n`SELECT ${n.identifier("doc")}, ${n.raw(String(k))} AS ${n.identifier("__term__")}, COUNT(*) AS ${n.identifier("__n__")} FROM ${n.identifier(R)} WHERE ${F} GROUP BY ${n.identifier("doc")}`}),N=p.map((D,k)=>n`SUM(CASE WHEN u.${n.identifier("__term__")} = ${n.raw(String(k))} THEN u.${n.identifier("__n__")} ELSE 0 END)`),S=n`SELECT f.${n.identifier(_e)} AS ${n.identifier(_e)}, ${n.join(N,n` + `)} AS ${n.identifier("__score__")} FROM (${Ue(g)}) u JOIN ${n.identifier($)} f ON f.rowid = u.${n.identifier("doc")} GROUP BY f.${n.identifier(_e)} HAVING ${n.join(N.map(D=>n`${D} > 0`),n` AND `)}`,_=xt(t,c);let C=n`SELECT m.id, m._creationTime, m.${n.identifier(j)}, s.${n.identifier("__score__")} AS ${n.identifier("__score__")} FROM (${S}) s JOIN ${n.identifier(i)} m ON m.id = s.${n.identifier(_e)}`;_.length>0&&(C=n`${C} WHERE ${n.join(_,n` AND `)}`),C=n`${C} ORDER BY s.${n.identifier("__score__")} DESC, m._creationTime DESC, m.id ASC LIMIT ${n.raw(String(d))}`;const W=[];for(const D of B(o,C)){const k=_t(D);if(k){const Q=D.__score__;W.push({document:k,score:typeof Q=="number"?Q:Number(Q??0)})}}return W},Fn=(o,i,t,d,c)=>{const p=Qe(t.definition.language),$=Ke(t.query,p);if($.length===0)return[];const R=xt(t,c);let y=n`SELECT id, _creationTime, ${n.identifier(j)} FROM ${n.identifier(i)}`;R.length>0&&(y=n`${y} WHERE ${n.join(R,n` AND `)}`),y=n`${y} ORDER BY _creationTime DESC, id ASC LIMIT ${n.raw(String(Dn(d)))}`;const g=B(o,y).toArray(),N=[];for(const S of g){const _=_t(S);if(!_)continue;const C=yn(Bt(_,t.definition),$,p);C>0&&N.push({creationTime:typeof _._creationTime=="number"?_._creationTime:0,doc:_,id:typeof _._id=="string"?_._id:"",score:C})}return N.sort((S,_)=>_.score-S.score||_.creationTime-S.creationTime||S.id.localeCompare(_.id)),N.slice(0,d).map(S=>({document:S.doc,score:S.score}))},qe=(o,i,t,d)=>{if(!Number.isFinite(o.lat)||o.lat<-90||o.lat>90||!Number.isFinite(o.lng)||o.lng<-180||o.lng>180)throw new b("BAD_REQUEST",`geo index "${d}" on table "${t}": ${i} must have a finite lat in [-90, 90] and lng in [-180, 180]`)},On=(o,i)=>{const t=o,d={near:(c,p)=>{if(t.within)throw new b("INTERNAL",`geo index "${t.indexName}" on table "${i}": call .near() or .within(), not both`);if(qe(c,".near() point",i,t.indexName),!Number.isFinite(p)||p<=0)throw new b("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:c.lat,lng:c.lng},radiusMeters:p},d},within:c=>{if(t.near)throw new b("INTERNAL",`geo index "${t.indexName}" on table "${i}": call .near() or .within(), not both`);if(qe(c.sw,".within() sw corner",i,t.indexName),qe(c.ne,".within() ne corner",i,t.indexName),c.sw.lat>c.ne.lat)throw new b("BAD_REQUEST",`geo index "${t.indexName}" on table "${i}": .within() corners are transposed (sw.lat > ne.lat)`);if(c.sw.lng>c.ne.lng)throw new b("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:c.ne.lat,lng:c.ne.lng},sw:{lat:c.sw.lat,lng:c.sw.lng}},d}};return d},Bn=(o,i)=>{const t=o[i];if(t===null||typeof t!="object")return;const{lat:d,lng:c}=t;return typeof d=="number"&&typeof c=="number"?{lat:d,lng:c}:void 0},qn=(o,i)=>{const t=Bn(o,i.definition.field);if(!t)return;const d=typeof o._creationTime=="number"?o._creationTime:0;if(i.near){const c=tn(i.near.point,t);return c<=i.near.radiusMeters?{creationTime:d,distance:c}:void 0}return en(t,i.within)?{creationTime:d,distance:0}:void 0},Un=(o,i,t,d)=>{if(!t.near&&!t.within)throw new b("INTERNAL",`geo index "${t.indexName}" on table "${i}": call .near(point, radius) or .within(box)`);const c=t.near?Xt(t.near.point,t.near.radiusMeters):Zt(t.within),p=Jt(i,t.indexName),$=c.map(S=>n`(g.${n.identifier("__geohash__")} >= ${S} AND g.${n.identifier("__geohash__")} < ${`${S}{`})`),R=[n`(${n.join($,n` OR `)})`];d&&R.push(d);const y=n`SELECT m.id, m._creationTime, m.${n.identifier(j)} FROM ${n.identifier(p)} g JOIN ${n.identifier(i)} m ON m.id = g.${n.identifier("__id__")} WHERE ${n.join(R,n` AND `)}`,g=B(o,y).toArray(),N=[];for(const S of g){const _=le(S),C=_?qn(_,t):void 0;_&&C&&N.push({creationTime:C.creationTime,distance:C.distance,doc:_})}return N.sort((S,_)=>S.distance-_.distance||_.creationTime-S.creationTime),N},It=(o,i,t,d)=>{const c=[];for(const p of o)if(i.every($=>$(d(p)))&&(c.push(p),typeof t=="number"&&c.length>=t))break;return c},Hn=(o,i,t,d,c,p=()=>{})=>{const $=t.within!==void 0,R=Un(o,i,t,c).map(y=>({distanceMeters:$?null:y.distance,document:y.doc}));return p(R.length),typeof d=="number"?R.slice(0,Math.max(0,Math.floor(d))):R},vt=(o,i,t,d,c,p=()=>{})=>{const{geo:$}=t;if(!$)throw new b("INTERNAL","runGeoTerminalScored called without a staged geo query");const R=t.inMemoryFilters.length>0,y=Hn(o,i,$,R?void 0:c,d,p);return R?It(y,t.inMemoryFilters,c,g=>g.document):y},Pn=(o,i,t,d,c,p=()=>{})=>vt(o,i,t,d,c,p).map($=>$.document),jn=(o,i,t,d,c,p,$=()=>{})=>{const R=[];for(const S of t.sqlConditions)R.push(n`${J(S.field)} ${n.raw(S.comparator)} ${ie(S.value)}`);d&&R.push(d);let y=n`SELECT id, _creationTime, ${n.identifier(j)} FROM ${n.identifier(i)}`;R.length>0&&(y=n`${y} WHERE ${n.join(R,n` AND `)}`),y=n`${y} ORDER BY ${c}`,typeof p=="number"&&t.inMemoryFilters.length===0&&(y=n`${y} LIMIT ${n.raw(String(Math.max(0,Math.floor(p))))}`);const g=B(o,y).toArray();$(g.length);const N=[];for(const S of g){const _=le(S);if(_&&t.inMemoryFilters.every(C=>C(_))&&(N.push(_),typeof p=="number"&&N.length>=p))break}return N},oe={fieldRef:J,serialize:ie},Ct=(o,i)=>{const t=i===void 0?void 0:o.shape[i];return t!==void 0&&pn(t)},$t=(o,i)=>i.some(t=>Ct(o,t)),wt=(o,i,t)=>{if(Ct(o,i))throw new b("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=[],d={fieldRef:J,relationExists:c=>{const{childWhere:p,negated:$,parentTable:R,relation:y}=c,g=`__rel_${String(i)}`,N=t.at(-1)??R;i+=1,o(y.table,H);const S=y.kind==="one"?y.field:y.references,_=y.kind==="one"?y.references:y.field,C=n`${it(g,_)} = ${it(N,S)}`;t.push(g);const W=ne(p,d);t.pop();const D=W?n`${C} AND ${W}`:C,k=n`EXISTS (SELECT 1 FROM ${n.identifier(y.table)} AS ${n.identifier(g)} WHERE ${D})`;return $?n`NOT ${k}`:k},serialize:ie};return d},Mt=o=>{const i=o.map(t=>n`${J(t.field)} ${n.raw(t.direction==="desc"?"DESC":"ASC")}`);return o.some(t=>t.field==="_id"||t.field==="id")||i.push(n`${J("id")} ASC`),n.join(i,n`, `)},Kn={"<":"lt","<=":"lte","=":"eq",">":"gt",">=":"gte"},Gn=o=>{const i=o.order;return o.indexFields.length>0?o.indexFields.map(t=>({direction:i,field:t})):[{direction:i,field:"_creationTime"}]},Yn=(o,i,t,d)=>{const c=o.sqlConditions.map(p=>({[p.field]:{[Kn[p.comparator]??"eq"]:p.value}}));if(t&&c.push(Rt(i,He(t))),d&&c.push(on(i,He(d))),c.length!==0)return c.length===1?c[0]:{AND:c}},zn=(o,i,t)=>{const d=[];for(const c of o){const p=le(c);if(p&&i.every($=>$(p))&&(d.push(p),t!==void 0&&d.length>t))break}return d},Jn=(o,i,t,d,c,p=()=>{})=>{const $=Math.max(0,Math.floor(d.numItems)),R=Gn(t),y=typeof d.endCursor=="string",g=ne(Yn(t,R,d.cursor,d.endCursor),oe),N=c&&g?n`${g} AND ${c}`:c??g;let S=n`SELECT id, _creationTime, ${n.identifier(j)} FROM ${n.identifier(i)}`;N&&(S=n`${S} WHERE ${N}`),S=n`${S} ORDER BY ${Mt(R)}`;const _=t.inMemoryFilters.length>0;!_&&!y&&(S=n`${S} LIMIT ${n.raw(String($+1))}`);const C=B(o,S).toArray();p(C.length);const W=zn(C,t.inMemoryFilters,_||y?void 0:$);if(y){const F=W.length>=2?W[Math.floor(W.length/2)-1]:void 0;return{continueCursor:d.endCursor??null,isDone:!0,page:W,splitCursor:F?Pe(F,R):null}}const D=W.length>$,k=D?W.slice(0,$):W,Q=k.at(-1);return{continueCursor:D&&Q?Pe(Q,R):null,isDone:!D,page:k}};class Vn extends b{constructor(i="unique() found more than one matching document"){super("NOT_UNIQUE",i,{name:"NotUniqueError"})}}const Xn=/\s/u,Zn=String.fromCodePoint(0),gt=(o,i,t)=>{if(!o.tables[i])throw new b("INTERNAL",`unknown table: ${i}`);return typeof t!="string"||t.length===0||Xn.test(t)||t.includes(Zn)?null:t},er=(o,i,t,d=()=>{},c=()=>{},p=()=>{})=>{const $=i.tables[t];if(!$)throw new b("INTERNAL",`unknown table: ${t}`);const R=de($.softDeleteMode,void 0),y=R?ne(R,oe):void 0,g={indexFields:[],indexName:void 0,inMemoryFilters:[],order:"asc",sqlConditions:[]};let N=0;const S=E=>{const{search:v}=g;if(!v)throw new b("INTERNAL","runSearchFetch called without a staged search");Gt(o,t,$);const I=g.inMemoryFilters.length>0,M=vn(I?void 0:E),K=zt(o)?Wn(o,t,v,M,y):Fn(o,t,v,M,y);return I?(N=K.length,It(K,g.inMemoryFilters,E,ee=>ee.document)):(E===void 0&&_n(K),K)},_=E=>S(E).map(v=>v.document),C=E=>{const v=xn(E);return In(_(Tn(v)),v)},W=()=>{const E=g.indexFields.length>0?g.indexFields:["_creationTime"],v=g.order==="desc"?"DESC":"ASC";return n.join(E.map(I=>n`${J(I)} ${n.raw(v)}`),n`, `)},D=()=>{if(g.search||g.geo||g.indexName===void 0){c(void 0);return}c(cn(t,g.indexName,g.indexFields,g.sqlConditions,ie))},k=E=>{D();let v=0;const I=(()=>{if(g.search){const M=_(E);return v=N,M}return g.geo?Pn(o,t,g,y,E,M=>{v=M}):jn(o,t,g,y,W(),E,M=>{v=M})})();return p(Math.max(v,I.length)),I},Q=()=>{if(!g.search&&!g.geo)throw new b("INTERNAL",`ctx.db.query("${t}").collectWithScores() requires a staged .withSearchIndex(...) or .withGeoIndex(...)`);D();let E=0;const v=(()=>{if(g.search){const I=S(void 0);return E=N,I}return vt(o,t,g,y,void 0,I=>{E=I})})();return p(Math.max(E,v.length)),v},F={async*[Symbol.asyncIterator](){const E=[...g.inMemoryFilters];let v;g.inMemoryFilters=[];try{for(;;){const I=await F.paginate({cursor:v??null,numItems:kn});for(const M of I.page)E.every(K=>K(M))&&(yield M);if(I.isDone||I.continueCursor===null)return;v=I.continueCursor}}finally{g.inMemoryFilters=E}},async collect(){return k(void 0)},async collectWithScores(){return Q()},filter(E){return g.inMemoryFilters.push(E),F},async first(){return k(g.inMemoryFilters.length>0?void 0:1)[0]??null},order(E){return g.order=E==="desc"?"desc":"asc",F},async paginate(E){let v=0;if(D(),g.search){const M=C(E);return p(M.page.length),M}if(g.geo)throw new b("INTERNAL","pagination is not supported on geo queries; use .take(n) or .collect()");const I=Jn(o,t,g,E,y,M=>{v=M});return p(Math.max(v,I.page.length)),I},async take(E){return k(E)},async unique(){const E=k(g.inMemoryFilters.length>0?void 0:2);if(E.length>1)throw new Vn(`unique() on table "${t}" matched ${String(E.length)} documents; expected at most one`);return E[0]??null},withGeoIndex(E,v){const I=($.geoIndexes??[]).find(K=>K.name===E);if(!I)throw new b("INTERNAL",`unknown geo index "${E}" on table "${t}"`);d(t,E,"geo");const M={definition:I,indexName:E};if(g.geo=M,v(On(M,t)),!M.near&&!M.within)throw new b("INTERNAL",`geo index "${E}" on table "${t}" requires a .near(point, radius) or .within(box) call`);return F},withIndex(E,v){const I=$.indexes.find(M=>M.name===E);if(!I)throw new b("INTERNAL",`unknown index "${E}" on table "${t}"`);return d(t,E,"index"),g.indexName=E,g.indexFields=I.fields,v&&v(Ln(g)),F},withSearchIndex(E,v){const I=($.searchIndexes??[]).find(K=>K.name===E);if(!I)throw new b("INTERNAL",`unknown search index "${E}" on table "${t}"`);d(t,E,"search");const M={definition:I,field:I.field,filters:[],hasQuery:!1,indexName:E,query:""};if(g.search=M,v(Sn(M,t,Qe(I.language))),!M.hasQuery)throw new b("INTERNAL",`search index "${E}" on table "${t}" requires a .search(field, query) call`);return F}};return F},bt=(o,i,t)=>{const d={...i};for(const[c,p]of St(o)){if(p.serverDefault){d[c]=p.serverDefault({auth:t});continue}d[c]===void 0&&(p.defaultFn?d[c]=p.defaultFn():"defaultValue"in p&&(d[c]=p.defaultValue))}return d},Et=(o,i,t,d)=>{const c=t;for(const[p,$]of St(o)){if($.serverDefault){p in i&&(c[p]=$.serverDefault({auth:d}));continue}$.onUpdateFn&&!(p in i)&&(c[p]=$.onUpdateFn())}},yt=(o,i)=>{for(const t of Object.keys(i))if(i[t]===void 0)throw new b("INTERNAL",`Cannot ${o} field '${t}' to undefined — use null to clear a nullable field, or omit the key to leave it unchanged.`)},tr=/unique constraint failed/i,nr=o=>o instanceof Error&&tr.test(o.message),je=(o,i,t)=>{try{B(o,t)}catch(d){throw nr(d)?new pe(`unique constraint violation on "${i}"`,"unique"):d}},xe=(o,i,t)=>{if(je(o,i,t),B(o,n`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")},Nt=(o,i,t,d,c,p,$)=>{const R=[];for(let S=0;S<t.length+1;S+=1){const _=[];for(let k=0;k<S;k+=1)_.push(n`${n.identifier(t[k])} IS ${p[k]}`);const C=t[S],W=d[S];if(C!==void 0&&W!==void 0){const k=W.direction==="desc"?">":"<";_.push(n`${n.identifier(C)} ${n.raw(k)} ${p[S]}`)}else _.push(n`${n.identifier(dn)} < ${$}`);const[D]=_;R.push(_.length===1&&D!==void 0?D:n`(${n.join(_,n` AND `)})`)}const y=n.join(R,n` OR `),g=B(o,n`SELECT COUNT(*) AS c FROM ${n.identifier(i)} WHERE ${n.identifier("__partition__")} = ${c} AND (${y})`).one(),N=B(o,n`SELECT COUNT(*) AS c FROM ${n.identifier(i)} WHERE ${n.identifier("__partition__")} = ${c}`).one();return{before:g.c,total:N.c}},Mr=o=>{const{sql:i}=o,{schema:t}=o,d=o.broadcast??(()=>{}),c=(e,...r)=>{const a=t.tables[e]?.indexes;if(!a||a.length===0)return;const l=[];for(const h of r)h&&l.push(...ln(a,h,ie));return l.length>0?l:void 0},{headroom:p}=o;let $=!1;const R=async e=>{const r=$;$=!0;try{return await e()}finally{$=r}},y=o.onRead??(()=>{}),g=o.onReadRange??(e=>{y(e.table,H)}),N=(e,r)=>{r!==void 0&&r!==H&&!$&&p?.recordRead(1),y(e,r)},S=o.onIndexUse??(()=>{}),_=o.onWrite??(()=>{}),C=async e=>{$||p?.recordWrite(e.doc),await _(e)},{cache:W}=o,D=o.clock??(()=>Date.now()),k=o.idGenerator??(()=>crypto.randomUUID()),Q=o.scheduler??Pt,{globalDb:F}=o,E=o.auth??{identity:null,userId:null},v=o.cdc??!1,I=Q,M=mn({scheduler:typeof I.list=="function"&&typeof I.get=="function"?I:void 0,storage:o.storage}),K=(e,r,a,l)=>{v&&Yt(i,D(),e,r,a,l)},ee=e=>t.tables[e]?.shardMode?.kind==="global",Ge=(e,r)=>{if(ee(e)){if(!F)throw new b("INTERNAL",`cross-backend ${r} for global table '${e}' requires a globalDb writer — pass one to createShardCtxDb({ globalDb })`);return F}return q},Ie=e=>Ge(e,"cascade"),z=(e,r)=>{if(ee(e)){if(!F)throw new b("INTERNAL",`${r} on global table '${e}' requires a globalDb writer — pass one to createShardCtxDb({ globalDb })`);return F}},ve=(e,r)=>Ge(e,"relation load").findMany(e,r),Ye=(e,r)=>(ee(e)&&N(e,H),ve(e,r)),kt=e=>!ee(e.table),ze=o.relationExistsPushDown??"auto",Je=ze!=="never",{maxRelationKeys:Ve}=o,me=(e,r,a)=>lt(e,{fetcher:Ye,maxRelationKeys:Ve,relationBaseWhere:a,schema:t,tableName:r}),Xe=async(e,r,a,l)=>{const h=z(e,"relation grouped count");if(h)return N(e,H),fn((P,x)=>h.count(P,x),e,r,a,l);const u=t.tables[e];if(!u)throw new b("INTERNAL",`unknown table: ${e}`);N(e,H);const s=de(u.softDeleteMode,void 0),f={[r]:{in:a}},m=Y(Y(f,l),s),T=await me(m,e,void 0),w=ne(T,oe),A=J(r);let L=n`SELECT ${A} AS __fk__, COUNT(*) AS count FROM ${n.identifier(e)}`;w&&(L=n`${L} WHERE ${w}`),L=n`${L} GROUP BY ${A}`;const O=B(i,L).toArray();return new Map(O.map(P=>[P.__fk__,P.count]))};let $e=0;const Ze=new Set;for(const[e,r]of Object.entries(t.tables))for(const a of Object.values(r.triggerMap??{}))Ze.add(`${e} ${a.timing} ${a.op}`);const X=(e,r,a)=>Ze.has(`${e} ${r} ${a}`),Z=async(e,r,a)=>{if($e+=1,$e>pt)throw $e-=1,new pe(`trigger recursion exceeded ${String(pt)} levels on "${a.table}" — check for a self-triggering write`,"trigger");try{await $n({ctx:Dt,event:a,op:r,schema:t,tableName:a.table,timing:e})}finally{$e-=1}},{ensureBackfilledForTable:ce,ensureBackfilledIndex:Ce,ensureRankBackfilled:Me,ensureRankBackfilledForTable:ue,syncAggregates:we,syncCompanionsForInsert:et,syncGeo:ge,syncRanks:fe,syncSearch:be}=Ot({broadcast:d,indexKeysFor:(e,r)=>c(e,r),invalidateCache:(e,r,a)=>W?.invalidate(e,r,c(e,a)),recordCdc:K,schema:t,sql:i}),tt=(e,r,a)=>{const{shardMode:l}=r;if(l?.kind==="shardBy"&&!(l.field!==void 0&&(a.partitionBy??[]).includes(l.field)))throw Object.assign(new Error(`rank index "${a.name}" on "${e}" partitions across shards (shard key "${l.field??"?"}" is not in partitionBy) — a shard-local rank()/rankPage() would be wrong; roll it up through the Query Coordinator instead`),{code:"CROSS_SHARD_RANK_UNSUPPORTED",name:"LunoraError",status:400})},nt=e=>Object.entries(t.tables).filter(([,r])=>r.shardMode?.kind!=="global").map(([r])=>r).filter(r=>e===void 0||r===e),re=(e,r)=>{const a=nt(r);for(let l=0;l<a.length;l+=he){const h=a.slice(l,l+he).map(T=>n`SELECT ${n.raw(`'${T.replaceAll("'","''")}'`)} AS __t__, id, _creationTime, ${n.identifier(j)} FROM ${n.identifier(T)} WHERE id = ${e}`),[u]=B(i,n`${Ue(h)} LIMIT 1`).toArray();if(!u)continue;const s=u.__t__,f=le(u);if(typeof s!="string"||!f)return;const m=u[j];return{docJson:typeof m=="string"?m:ae(m??{}),row:f,tableName:s}}},Lt=(e,r)=>{const a=[...new Set(e)],l=new Map;if(a.length===0)return l;const h=nt(r);for(let u=0;u<h.length;u+=he){const s=h.slice(u,u+he),f=Math.floor(he/s.length),m=Vt(n`${n.identifier("id")}`,a,!1,f),T=s.map(w=>n`SELECT ${n.raw(`'${w.replaceAll("'","''")}'`)} AS __t__, id FROM ${n.identifier(w)} WHERE ${m}`);for(const w of B(i,Ue(T))){const{id:A,__t__:L}=w;typeof L=="string"&&typeof A=="string"&&l.set(A,L)}}return l},rt={assertRankPartitionLocal:tt,ensureRankBackfilled:Me,onRead:N,rowToDocument:le,schema:t,sql:i},q={system:M,async aggregate(e,r){const a=z(e,"aggregate");if(a)return N(e,H),a.aggregate(e,r);const l=t.tables[e];if(!l)throw new b("INTERNAL",`unknown table: ${e}`);if(Te(r.op),r.op==="count")return q.count(e,{baseWhere:r.baseWhere,relationBaseWhere:r.relationBaseWhere,restrictsCounts:r.restrictsCounts,where:r.where});if(!r.field)throw new b("INTERNAL",`aggregate(${e}, { op: "${r.op}" }): "field" is required for non-count reducers`);N(e,H);const h=de(l.softDeleteMode,void 0),u=Y(Y(r.baseWhere,r.where),h),s=await me(u,e,r.relationBaseWhere),f=s!==u;if(l.aggregateIndexes&&!r.baseWhere&&!f&&(!h||$t(l,[r.field]))){const O=Kt(l.aggregateIndexes,r.op,r.field,r.where);if(O){Ce(e,O.index);const P=ke(O.index.by??[],O.key),x=De(e,O.index.name),G=B(i,n`SELECT ${Re} AS value, ${Fe} AS count FROM ${n.identifier(x)} WHERE ${Ae} = ${P}`).toArray()[0];return Le(r.op,G)}}wt(l,r.field,`aggregate(${e}, { op: "${r.op}", field: "${r.field}" })`);const m=ne(s,oe),T=Te(r.op),w=J(r.field);let A=n`SELECT ${n.raw(T)}(${w}) AS value FROM ${n.identifier(e)}`;return m&&(A=n`${A} WHERE ${m}`),B(i,A).toArray()[0]?.value??null},asId(e,r){const a=gt(t,e,r);if(a===null)throw new b("BAD_REQUEST",`asId("${e}", …): "${r}" is not a valid id for table "${e}"`,{status:400});return a},async count(e,r){const a=z(e,"count");if(a)return N(e,H),a.count(e,r);const l=t.tables[e];if(!l)throw new b("INTERNAL",`unknown table: ${e}`);const h=Ht(r);if(h.restrictsCounts)throw new We(e);N(e,H);const u=de(l.softDeleteMode,void 0),s=Y(Y(h.baseWhere,h.where),u),f=await me(s,e,h.relationBaseWhere),m=f!==s;if(l.aggregateIndexes&&!h.baseWhere&&!m&&!u){const A=Qt(l.aggregateIndexes,h.where);if(A){Ce(e,A.index);const L=ke(A.index.by??[],A.key),O=De(e,A.index.name),P=B(i,n`SELECT ${Re} AS value FROM ${n.identifier(O)} WHERE ${Ae} = ${L}`).toArray();return P[0]===void 0?0:P[0].value??0}}const T=ne(f,oe);let w=n`SELECT COUNT(*) AS count FROM ${n.identifier(e)}`;return T&&(w=n`${w} WHERE ${T}`),B(i,w).one().count},async delete(e,r,a){const l=re(e,r);if(!l){const w=r===void 0?F:void 0;w&&await w.delete(e,void 0,a);return}const{docJson:h,row:u,tableName:s}=l,f=t.tables[s],m=a?.hard===!0,T=!m&&f?.softDeleteMode?f.softDeleteMode.field:void 0;if(!(T&&u[T]!==null&&u[T]!==void 0)){if(X(s,"before","delete")&&await Z("before","delete",{id:e,op:"delete",previous:u,table:s}),await un({deletedId:e,deletedReference:w=>u[w],findHolders:async(w,A,L)=>(await Ie(w).findMany(w,{includeDeleted:m,where:{[A]:L}})).page,onCascade:(w,A)=>Ie(w).delete(A,void 0,a),onRestrict:w=>{throw new pe(w,"restrict")},onSetNull:(w,A,L)=>Ie(w).patch(A,{[L]:null}),schema:t,tableName:s}),ce(s),ue(s),T){const w={...u,[T]:D(),_id:e};xe(i,s,n`UPDATE ${n.identifier(s)} SET ${n.identifier(j)} = ${ae(w)} WHERE id = ${e} AND ${n.identifier(j)} = ${h}`),be(s,e,w,u),ge(s,e,void 0),we(s,u,w),fe(s,e,u,void 0),W?.invalidate(s,e,c(s,u,w)),K(s,e,"update",w),d({indexKeys:c(s,u,w),key:e,op:"update",row:w,table:s}),X(s,"after","delete")&&await Z("after","delete",{id:e,op:"delete",previous:u,table:s}),await C({id:e,op:"delete",table:s});return}xe(i,s,n`DELETE FROM ${n.identifier(s)} WHERE id = ${e} AND ${n.identifier(j)} = ${h}`),be(s,e,void 0),ge(s,e,void 0),we(s,u,void 0),fe(s,e,u,void 0),W?.invalidate(s,e,c(s,u)),K(s,e,"delete"),d({indexKeys:c(s,u),key:e,op:"delete",table:s}),X(s,"after","delete")&&await Z("after","delete",{id:e,op:"delete",previous:u,table:s}),await C({id:e,op:"delete",table:s})}},async deleteAll(e,r){if(!t.tables[e])throw new b("INTERNAL",`unknown table: ${e}`);const a=Math.max(1,r?.chunkSize??At),l=r?.hard===void 0?void 0:{hard:r.hard},h=ee(e)?void 0:e;let u=0;return await R(async()=>{for(;;){const s=(await q.findMany(e,{limit:a})).page.map(f=>String(f._id));if(s.length===0)break;for(const f of s)await q.delete(f,h,l),u+=1;if(s.length<a)break}}),{deleted:u}},async deleteMany(e,r,a){se(e.length,r?.limit,"deleteMany");for(const l of e)await q.delete(l,a);return{deleted:e.length}},async deleteWhere(e,r,a){const l=(await(z(e,"deleteWhere")??q).findMany(e,{where:r})).page.map(h=>String(h._id));if(se(l.length,a?.limit,"deleteWhere"),q.deleteMany===void 0)throw new b("INTERNAL",`ctx.db.${e}.deleteMany is unavailable: this writer has no batch delete`);return q.deleteMany(l,a)},async findFirst(e,r={}){return(await q.findMany(e,{...r,limit:1})).page[0]??null},async findFirstOrThrow(e,r={}){const a=await q.findFirst(e,r);if(a===null)throw new nn(`findFirstOrThrow: no "${e}" document matched`);return a},async findMany(e,r={}){const a=z(e,"findMany");if(a)return N(e,H),a.findMany(e,r);const l=t.tables[e];if(!l)throw new b("INTERNAL",`unknown table: ${e}`);const h=!r.where&&!r.baseWhere;h?N(e,H):N(e);const u=rn(r.orderBy),s=r.cursor?Rt(u,He(r.cursor)):void 0;let f=Y(r.baseWhere,r.where);f=Y(f,de(l.softDeleteMode,r.includeDeleted)),f=await lt(f,{canPushExists:Je?kt:void 0,existsPushMode:ze==="always"?"always":"auto",fetcher:Ye,maxRelationKeys:Ve,relationBaseWhere:r.relationBaseWhere,schema:t,tableName:e}),s&&(f=f?{AND:[f,s]}:s);const m=Je?Qn(N):oe,T=ne(f,m);let w=n`SELECT id, _creationTime, ${n.identifier(j)} FROM ${n.identifier(e)}`;T&&(w=n`${w} WHERE ${T}`),w=n`${w} ORDER BY ${Mt(u)}`;const A=typeof r.limit=="number"?Math.max(0,Math.floor(r.limit)):void 0;A!==void 0&&(w=n`${w} LIMIT ${n.raw(String(A+1))}`);const L=B(i,w).toArray();h&&!$&&p?.recordRead(L.length);const O=[];for(const te of L){const U=le(te);U&&(O.push(U),!h&&typeof U._id=="string"&&N(e,U._id))}if(A===void 0)return r.with&&await ct({groupedCounter:Xe,fetcher:ve,parents:O,...ut(r),schema:t,tableName:e,with:r.with}),{continueCursor:null,isDone:!0,page:at(O,r.select,r.with)};const P=O.length>A,x=P?O.slice(0,A):O,G=x.at(-1);return r.with&&await ct({fetcher:ve,groupedCounter:Xe,parents:x,...ut(r),schema:t,tableName:e,with:r.with}),{continueCursor:P&&G?Pe(G,u):null,isDone:!P,page:at(x,r.select,r.with)}},async get(e,r){const a=re(e,r);if(!a){const l=r===void 0?F:void 0;return l?l.get(e):null}return N(a.tableName,e),a.row},async lookupById(e,r){const a=re(e,r);return a?(N(a.tableName,e),{row:a.row,tableName:a.tableName}):null},async groupBy(e,r){const a=z(e,"groupBy");if(a)return N(e,H),a.groupBy(e,r);const l=t.tables[e];if(!l)throw new b("INTERNAL",`unknown table: ${e}`);N(e,H);const h=r.agg??{op:"count"};if(Te(h.op),h.op!=="count"&&!h.field)throw new b("INTERNAL",`groupBy(${e}, { agg: { op: "${h.op}" } }): "field" is required for non-count reducers`);const u=de(l.softDeleteMode,void 0),s=Y(Y(r.baseWhere,r.where),u),f=await me(s,e,r.relationBaseWhere),m=f!==s,T=[...r.by,h.field];if(l.aggregateIndexes&&!r.baseWhere&&!m&&(!u||$t(l,T))){const x=jt(l.aggregateIndexes,h.op,h.field,r.by,r.where),G=x===void 0?0:Object.keys(x.partial).length,te=x?.index.by?.length??0;if(x&&(G===0||G===te)){Ce(e,x.index);const U=De(e,x.index.name),Ee=Object.keys(x.partial),ye=[];if(Ee.length===(x.index.by??[]).length&&Ee.length>0){const Ne=ke(x.index.by??[],x.partial),Se=B(i,n`SELECT ${Re} AS value, ${Fe} AS count FROM ${n.identifier(U)} WHERE ${Ae} = ${Ne}`).toArray();return Se.length>0&&ye.push({key:{...x.partial},value:Le(h.op,Se[0])}),ye}const Wt=B(i,n`SELECT ${Ae} AS key, ${Re} AS value, ${Fe} AS count FROM ${n.identifier(U)}`).toArray();for(const Ne of Wt){const Se=Ut(JSON.parse(Ne.key));ye.push({key:Se,value:Le(h.op,Ne)})}return ye}}for(const x of T){if(x===void 0)continue;const G=x===h.field?`groupBy(${e}, { agg: { op: "${h.op}", field: "${x}" } })`:`groupBy(${e}, { by: [..."${x}"] })`;wt(l,x,G)}const w=ne(f,oe),A=r.by.map(x=>n`${J(x)} AS ${n.identifier(x)}`);if(h.op==="count")A.push(n`COUNT(*) AS value`);else{const{field:x}=h;if(x===void 0)throw new b("INTERNAL",`groupBy(${e}, { agg: { op: "${h.op}" } }): "field" is required for non-count reducers`);A.push(n`${n.raw(Te(h.op))}(${J(x)}) AS value`)}let L=n`SELECT ${n.join(A,n`, `)} FROM ${n.identifier(e)}`;w&&(L=n`${L} WHERE ${w}`),L=n`${L} GROUP BY ${n.join(r.by.map(x=>J(x)),n`, `)}`;const O=B(i,L).toArray(),P=[];for(const x of O){const G={};for(const U of r.by)G[U]=x[U]??null;const{value:te}=x;P.push({key:G,value:te==null?null:Number(te)})}return P},async insert(e,r,a){const l=z(e,"insert");if(l){const T=await l.insert(e,r,a);return $||p?.recordWrite(r),d({key:T,op:"insert",row:{...r,_id:T},table:e}),T}const h=t.tables[e];if(!h)throw new b("INTERNAL",`unknown table: ${e}`);const u=bt(h,r,E);Be(h,u);let s;a?.clientId!==void 0?(Mn(a.clientId),s=a.clientId):a?.allowExplicitId&&typeof u._id=="string"?s=u._id:s=k();const f=a?.allowExplicitId&&typeof u._creationTime=="number"?u._creationTime:D(),m={...u,_creationTime:f,_id:s};return X(e,"before","insert")&&await Z("before","insert",{doc:{...m},id:s,op:"insert",table:e}),ce(e),ue(e),je(i,e,n`INSERT INTO ${n.identifier(e)} (id, _creationTime, ${n.identifier(j)}) VALUES (${s}, ${f}, ${ae(m)})`),et(e,s,m),X(e,"after","insert")&&await Z("after","insert",{doc:m,id:s,op:"insert",table:e}),await C({doc:m,id:s,op:"insert",table:e}),s},async insertManyUnsafe(e,r,a){if(se(r.length,a?.limit,"insertManyUnsafe"),r.length===0)return[];const l=z(e,"insert");if(l){const s=[];for(const f of r){const m=await l.insert(e,f,{allowExplicitId:a?.allowExplicitId});$||p?.recordWrite(f),d({key:m,op:"insert",row:{...f,_id:m},table:e}),s.push(m)}return s}const h=t.tables[e];if(!h)throw new b("INTERNAL",`unknown table: ${e}`);ce(e),ue(e);const u=r.map(s=>{const f=bt(h,s,E),m=a?.allowExplicitId===!0&&typeof f._id=="string"?f._id:k(),T=a?.allowExplicitId===!0&&typeof f._creationTime=="number"?f._creationTime:D();return{creationTime:T,document:{...f,_creationTime:T,_id:m},id:m}});if(!$)for(const s of u)p?.recordWrite(s.document);for(let s=0;s<u.length;s+=mt){const f=n.join(u.slice(s,s+mt).map(m=>n`(${m.id}, ${m.creationTime}, ${ae(m.document)})`),n`, `);je(i,e,n`INSERT INTO ${n.identifier(e)} (id, _creationTime, ${n.identifier(j)}) VALUES ${f}`)}for(const{document:s,id:f}of u)et(e,f,s),await _({doc:s,id:f,op:"insert",table:e});return u.map(s=>s.id)},async insertMany(e,r,a){se(r.length,a?.limit,"insertMany");const l=a?.skipDuplicates===!0,h=[];for(const u of r)try{h.push(await q.insert(e,u))}catch(s){if(l&&s instanceof pe&&s.kind==="unique")h.push(null);else throw s}return h},normalizeId(e,r){return gt(t,e,r)},async patch(e,r,a){const l=re(e,a);if(!l){const T=a===void 0?F:void 0;if(T){await T.patch(e,r);return}throw new b("INTERNAL",`document not found: ${e}`)}const{docJson:h,row:u,tableName:s}=l,f=t.tables[s];if(!f)throw new b("INTERNAL",`unknown table: ${s}`);N(s,e),yt("patch",r);const m={...u,...r,_id:e};Et(f,r,m,E),Be(f,m,!0),X(s,"before","update")&&await Z("before","update",{doc:{...m},id:e,op:"update",previous:u,table:s}),ce(s),ue(s),xe(i,s,n`UPDATE ${n.identifier(s)} SET ${n.identifier(j)} = ${ae(m)} WHERE id = ${e} AND ${n.identifier(j)} = ${h}`),be(s,e,m,u),ge(s,e,m),we(s,u,m),fe(s,e,u,m),W?.invalidate(s,e,c(s,u,m)),K(s,e,"update",m),d({indexKeys:c(s,u,m),key:e,op:"update",row:m,table:s}),X(s,"after","update")&&await Z("after","update",{doc:m,id:e,op:"update",previous:u,table:s}),await C({doc:m,id:e,op:"update",table:s})},async patchMany(e,r,a){se(e.length,r?.limit,"patchMany");for(const l of e)await q.patch(l.id,l.patch,a);return{patched:e.length}},async patchWhere(e,r,a){const l=(await(z(e,"patchWhere")??q).findMany(e,{where:r.where})).page.map(h=>({id:String(h._id),patch:r.patch}));if(se(l.length,a?.limit,"patchWhere"),q.patchMany===void 0)throw new b("INTERNAL",`ctx.db.${e}.patchMany is unavailable: this writer has no batch patch`);return await q.patchMany(l,a),{patched:l.length}},query(e){const r=z(e,"query");return r?(N(e,H),r.query(e)):er(i,t,e,S,a=>{a?g(a):N(e,H)},a=>{$||p?.recordRead(a)})},async rank(e,r,a){const l=z(e,"rank");if(l)return N(e,H),l.rank(e,r,a);S(e,r,"rank");const h=t.tables[e];if(!h)throw new b("INTERNAL",`unknown table: ${e}`);const u=h.rankIndexes?.find(U=>U.name===r);if(!u)throw new b("INTERNAL",`unknown rankIndex "${r}" on table "${e}"`);if(tt(e,h,u),a.restrictsCounts)throw new We(e);N(e,H),Me(e,u);const s=typeof a.row=="string"?a.row:a.row._id;if(!s)return null;const f=dt(e,u.name),m=u.sortBy.map((U,Ee)=>st(Ee)),T=m.map(U=>wn(U)).join(", "),w=B(i,n`SELECT ${n.identifier("__partition__")}, ${n.raw(T)} FROM ${n.identifier(f)} WHERE ${n.identifier("__id__")} = ${s}`).toArray(),[A]=w;if(A===void 0)return null;let L=A.__partition__;const O=Y(a.baseWhere,a.where);Oe(O,t,e,"rank");const P=an(u,O);if(P){const U=sn(u.partitionBy??[],P);if(U!==L)return null;L=U}const x=m.map(U=>A[U]),{before:G,total:te}=Nt(i,f,m,u.sortBy,L,x,s);return{position:G+1,total:te}},async rankBefore(e,r,a){if(ee(e))throw new b("INTERNAL",`rankBefore is not supported on the global (.global()) table '${e}' — cross-shard rank cursors apply only to sharded tables`);const l=t.tables[e];if(!l)throw new b("INTERNAL",`unknown table: ${e}`);const h=l.rankIndexes?.find(m=>m.name===r);if(!h)throw new b("INTERNAL",`unknown rankIndex "${r}" on table "${e}"`);if(a.restrictsCounts)throw new We(e);N(e,H),Me(e,h);const u=dt(e,h.name),s=h.sortBy.map((m,T)=>st(T)),f=h.sortBy.map((m,T)=>ie(a.sortValues[T]??null));return Nt(i,u,s,h.sortBy,a.partitionKey,f,a.rowId)},async rankPage(e,r,a={}){Oe(Y(a.baseWhere,a.where),t,e,"rankPage");const l=z(e,"rankPage");if(l)return N(e,H),l.rankPage(e,r,a);S(e,r,"rank");const{continueCursor:h,hasMore:u,rows:s}=ot(rt,e,r,a);return{continueCursor:h,isDone:!u,page:s.map(f=>f.doc)}},async rankPageRows(e,r,a={}){Oe(Y(a.baseWhere,a.where),t,e,"rankPage"),S(e,r,"rank");const{directions:l,hasMore:h,rows:u}=ot(rt,e,r,a);return{directions:l,hasMore:h,rows:u}},async restore(e,r){const a=re(e,r);if(!a){const u=r===void 0?F:void 0;if(u?.restore){await u.restore(e);return}throw new b("INTERNAL",`document not found: ${e}`)}const l=t.tables[a.tableName]?.softDeleteMode?.field;if(!l)throw new b("INTERNAL",`ctx.db.restore: table "${a.tableName}" is not a .softDelete() table`);const h=a.row[l]!==null&&a.row[l]!==void 0;await q.patch(e,{[l]:null},r),h&&fe(a.tableName,e,void 0,a.row)},async replace(e,r,a,l){const h=re(e,a);if(!h){const A=a===void 0?F:void 0;if(A){await A.replace(e,r,void 0,l);return}throw new b("INTERNAL",`document not found: ${e}`)}const{docJson:u,row:s,tableName:f}=h,m=t.tables[f];if(!m)throw new b("INTERNAL",`unknown table: ${f}`);yt("replace",r);const T=l?.allowExplicitId&&typeof r._creationTime=="number"?r._creationTime:D(),w={...r,_creationTime:T,_id:e};Et(m,r,w,E),Be(m,w),X(f,"before","update")&&await Z("before","update",{doc:{...w},id:e,op:"update",previous:s,table:f}),ce(f),ue(f),xe(i,f,n`UPDATE ${n.identifier(f)} SET _creationTime = ${T}, ${n.identifier(j)} = ${ae(w)} WHERE id = ${e} AND ${n.identifier(j)} = ${u}`),be(f,e,w,s),ge(f,e,w),we(f,s,w),fe(f,e,s,w),W?.invalidate(f,e,c(f,s,w)),K(f,e,"update",w),d({indexKeys:c(f,s,w),key:e,op:"update",row:w,table:f}),X(f,"after","update")&&await Z("after","update",{doc:w,id:e,op:"update",previous:s,table:f}),await C({doc:w,id:e,op:"update",table:f})},async wipeShard(e){const r=new Set(e?.exclude),a=e?.tables,l=Object.entries(t.tables).filter(([f,m])=>r.has(f)||a!==void 0&&!a.includes(f)?!1:m.shardMode?.kind!=="global").map(([f])=>f);if(a!==void 0){for(const f of a)if(!t.tables[f])throw new b("INTERNAL",`wipeShard: unknown table: ${f}`)}const h={};let u=0;const{deleteAll:s}=q;if(s===void 0)throw new b("INTERNAL","wipeShard: this writer has no deleteAll");for(const f of l){const m=await s(f,{...e?.chunkSize===void 0?{}:{chunkSize:e.chunkSize},hard:!0});h[f]=m.deleted,u+=m.deleted}return{deleted:u,tables:h}}},Dt={db:q,scheduler:Q};return o.enforceRls===!0?hn(q,t,(e,r)=>re(e,r)?.tableName,(e,r)=>Lt(e,r)):q};export{Br as CDC_LOG_TABLE,Yr as CLIENT_WATERMARK_TABLE,Zr as GLOBAL_SHAPE_SNAPSHOT_TABLE,ao as IDEMPOTENCY_TABLE,Vn as NotUniqueError,po as SEARCH_STATE_TABLE,zr as advanceClientWatermark,qr as applyCdcChanges,Mn as assertValidClientId,Dr as backfillAggregateIndexes,Wr as backfillRankIndexes,Fr as backfillSearchIndexes,Ur as bumpCdcEpoch,Mr as createShardCtxDb,eo as deleteGlobalShapeSnapshot,to as deleteGlobalShapeSnapshotsForConnection,Jr as migrateClientWatermark,no as migrateGlobalShapeSnapshot,Hr as minCdcSeq,gt as normalizeIdStructurally,Pr as readCdcChanges,jr as readCdcCursor,Qr as readCdcEpoch,Vr as readClientWatermark,ro as readGlobalShapeSnapshot,so as readIdempotent,fo as runShardMigrations,$o as selectShapeMemberIds,wo as selectShapeRows,Kr as trimCdcChanges,lo as trimIdempotent,oo as writeGlobalShapeSnapshot,co as writeIdempotent};
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{L as u,a as l,j as m}from"./do-sql-Cg_QiQYA.mjs";import{quoteIdentifier as a}from"./quoteIdentifier-CObIFRhb.mjs";import{reprojectionMigrationTable as j}from"./REPROJECTION_MIGRATION_PREFIX-D2dltRFC.mjs";import{REPROJECTION_MIGRATION_PREFIX as _,reprojectionMigrationId as x}from"./REPROJECTION_MIGRATION_PREFIX-D2dltRFC.mjs";import{a as b}from"./wire-codec-Dsy70M3Q.mjs";import{runSql as f}from"./runDrizzle-CgYGDEeB.mjs";import{y as d}from"./sql-projection-jfoe331H.mjs";const E=b(0n)[0],$=r=>r.shardMode?.kind==="global"?[]:Object.entries(r.shape).filter(([,t])=>d(t)).map(([t])=>t),L=r=>Object.entries(r.tables).filter(([,t])=>$(t).length>0).map(([t])=>t),g=r=>{const t=r.map(()=>`(json_extract(${a(l)}, ?) = ? AND json_extract(${a(l)}, ?) IN (?, ?))`);return{params:r.flatMap(o=>[`$.${m(o)}[0]`,E,`$.${m(o)}[1]`,"bigint","bytes"]),sql:t.join(" OR ")}},S=(r,t,o)=>{if(o.length===0)return 0;const{params:e,sql:n}=g(o);return f(r,`SELECT COUNT(*) AS count FROM ${a(t)} WHERE ${n}`,...e).toArray()[0]?.count??0},R=(r,t,o,e)=>{const{params:n,sql:i}=g(o);return f(r,`SELECT 1 FROM ${a(t)} WHERE id = ? AND (${i}) LIMIT 1`,e,...n).toArray().length>0},A=(r,t,o)=>{const e=j(r);if(e===void 0)return;const n=t.tables[e];if(!n)return;const i=$(n);if(i.length!==0)return{id:r,table:e,up:s=>{const c=s._id;if(!(typeof c!="string"||!R(o,e,i,c))){try{u(s)}catch(p){console.warn(`${r}: skipping row ${c} — it cannot be re-projected: ${p instanceof Error?p.message:String(p)}`);return}return s}}}};export{_ as REPROJECTION_MIGRATION_PREFIX,A as buildReprojectionMigration,S as countLegacyRows,$ as reprojectableFields,x as reprojectionMigrationId,L as reprojectionTables};
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{LunoraError as p}from"@lunora/errors";import{sql as s}from"drizzle-orm";import{sqliteInList as f,WORKERD_SQLITE_LIMITS as $}from"./param-C68MV3DD.mjs";import{RELATION_EXISTS_KEY as N}from"./RELATION_EXISTS_KEY-BaqSIFU1.mjs";const I=["eq","ne","lt","lte","gt","gte","in","notIn","isNull","contains"],O=new Set(I),T={eq:"=",gt:">",gte:">=",lt:"<",lte:"<=",ne:"<>"},h=r=>{if(r===null||typeof r!="object"||Array.isArray(r))return!1;const e=Object.keys(r);return e.length>0&&e.every(t=>O.has(t))},m=(r,e,t)=>{const o=s`${t.serialize(e)}`;return t.containsExpr?t.containsExpr(r,o):s`instr(lower(${r}), lower(${o})) > 0`},y=(r,e,t,o,n)=>o===null?e==="ne"?s`${r} IS NOT NULL`:s`${r} IS NULL`:s`${r} ${s.raw(t)} ${n.serialize(o)}`,S=(r,e,t,o)=>{const n=Array.isArray(t)?t:[];if(n.length===0)return e==="IN"?s`0 = 1`:s`1 = 1`;const i=n.map(a=>o.serialize(a)),l=e==="NOT IN";return(o.inList??f)(r,i,l)},U=(r,e,t)=>{const o=s.join(e.map(n=>s`${n}`),s`, `);return t?s`${r} NOT IN (${o})`:s`${r} IN (${o})`},A=(r,e,t)=>{const o=e,n=[];for(const i of I){if(!(i in o))continue;const l=o[i],a=T[i];a?n.push(y(r,i,a,l,t)):i==="isNull"?n.push(l?s`${r} IS NULL`:s`${r} IS NOT NULL`):i==="contains"?n.push(m(r,l,t)):n.push(S(r,i==="in"?"IN":"NOT IN",l,t))}return n},E=(r,e,t)=>{const o=t.fieldRef(r);return h(e)?A(o,e,t):e===null?[s`${o} IS NULL`]:[s`${o} = ${t.serialize(e)}`]},L=(r,e)=>{if(r.length!==0)return r.length===1?r[0]:s.join(r.map(t=>s`(${t})`),s` ${s.raw(e)} `)},g=(r,e,t)=>{const o=Array.isArray(r)?r:[],n=[];for(const i of o){const l=u(i??{},t);l&&n.push(l)}return n.length===0?e==="OR"?s`0 = 1`:void 0:L(n,e)},w=new Set(["AND","NOT","OR",N]),R=(r,e,t)=>{if(r===N){if(!t.relationExists)throw new p("INTERNAL","encountered a relation EXISTS marker without a relationExists strategy hook");return t.relationExists(e)}if(r==="NOT"){const o=u(e??{},t);return o?s`NOT (${o})`:void 0}return g(e,r,t)},u=(r,e)=>{const t=[];for(const[o,n]of Object.entries(r))if(w.has(o)){const i=R(o,n,e);i&&t.push(i)}else t.push(...E(o,n,e));return L(t,"AND")},j=$.boundParams/2,c=r=>{if(Array.isArray(r))return r.reduce((t,o)=>t+c(o),0);if(r===null||typeof r!="object")return 0;let e=0;for(const[t,o]of Object.entries(r))t==="in"||t==="notIn"?e+=1:(t==="AND"||t==="NOT"||t==="OR"||h(o))&&(e+=c(o));return e},k=(r,e)=>{if(!r||Object.keys(r).length===0)return;const t=e.inList??f,o=c(r);if(o===0)return u(r,e);const n=Math.max(1,Math.floor(j/o));return u(r,{...e,inList:(i,l,a)=>t(i,l,a,n)})};export{k as compileWhereSql,U as literalInList};
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{LunoraError as m}from"@lunora/errors";import{sql as r}from"drizzle-orm";import{MySqlDialect as c}from"drizzle-orm/mysql-core";import{PgDialect as u}from"drizzle-orm/pg-core";import{SQLiteSyncDialect as p}from"drizzle-orm/sqlite-core";const f=new u,d=new c,S=new p,h={mysql:d,postgres:f,sqlite:S},a={boundParams:100,compoundSelect:5,likePattern:50},g=a.boundParams/2,L=e=>e===null||typeof e=="boolean"?!0:typeof e=="number"?Number.isFinite(e):typeof e=="string"&&e.isWellFormed(),w=(e,t)=>{const{params:n,sql:o}=h[e].sqlToQuery(t);return{params:n,sql:o}},$=e=>r`${e}`,O=e=>{if(e.length===0)throw new Error("unionAll: expected at least one branch");let t=[...e];for(;t.length>a.compoundSelect;){const n=[];for(let o=0;o<t.length;o+=a.compoundSelect){const l=r.join(t.slice(o,o+a.compoundSelect),r` UNION ALL `);n.push(r`SELECT * FROM (${l}) ${r.identifier("__u__")}`)}t=n}return r.join(t,r` UNION ALL `)},I=(e,t,n,o=g)=>{const l=n?r` NOT IN `:r` IN `,s=t.every(i=>L(i));if(t.length>o&&!s)throw new m("BAD_REQUEST",`an "in" list of ${String(t.length)} values holds a value JSON cannot carry (bytes, a non-finite number, or malformed text), so it cannot be bound as one parameter — and ${String(t.length)} placeholders exceed SQLite's per-statement cap of 100 on Durable Objects and D1. Narrow the list to ${String(o)} values or fewer.`);return t.length<=o?r`${e}${l}(${r.join(t.map(i=>$(i)),r`, `)})`:r`${e}${l}(SELECT ${r.identifier("value")} FROM json_each(${JSON.stringify(t)}))`};export{a as WORKERD_SQLITE_LIMITS,$ as param,w as renderSql,I as sqliteInList,O as unionAll};
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{renderSql as t}from"./param-C68MV3DD.mjs";const n=(r,e,...l)=>r.exec.call(r,e,...l),c=(r,e)=>{const{params:l,sql:o}=t("sqlite",e);return n(r,o,...l)},s=r=>r??null,a=r=>{if(!(r==null||r===""))try{return JSON.parse(r)}catch{return}};export{a as decodeJsonColumn,s as orNull,c as runDrizzle,n as runSql};
|
|
@@ -1,5 +0,0 @@
|
|
|
1
|
-
import{l as I,T as N,c as S}from"./ctx-db-companions-D2ZMFBrP.mjs";import"@lunora/errors";import{sql as e}from"drizzle-orm";import{aggregateTableName as p}from"./aggregateTableName-DgYMC5tr.mjs";import{backfillSearchIndexesForTable as g}from"./backfillAggregateIndexes-Czk8MQ3M.mjs";import{migrateCdcLog as h,migrateCdcMeta as l}from"./CDC_LOG_TABLE-CIfexI1y.mjs";import{migrateClientWatermark as R}from"./CLIENT_WATERMARK_TABLE-BogWgD2Q.mjs";import{migrateGlobalShapeSnapshot as C}from"./GLOBAL_SHAPE_SNAPSHOT_TABLE-T5smo6RP.mjs";import{migrateIdempotency as O}from"./IDEMPOTENCY_TABLE-DPFwgQbE.mjs";import{migrateSearchState as U}from"./SEARCH_STATE_TABLE-MDlr30EJ.mjs";import{runDrizzle as a}from"./runDrizzle-CgYGDEeB.mjs";import{a as u,N as E,y as _,I as X,C as b,c as x,p as B,T as c,h as F}from"./do-sql-Cg_QiQYA.mjs";import{sortColumnName as M,rankTableName as Y}from"./RANK_TIEBREAK-DDtST3gN.mjs";import{recordSchemaVersion as D}from"./SCHEMA_HISTORY_MAX_VERSIONS-CGlXjXRT.mjs";const k=(r,t,o)=>{for(const i of o.indexes){const n=`${t}_${i.name}`,s=e.join(i.fields.map(f=>E(f)),e`, `);a(r,_(n,t,s,i.unique??!1))}for(const[i,n]of X(o)){if(!n.unique)continue;const s=`${t}_unique_${i}`;a(r,_(s,t,E(i),!0))}},y=(r,t,o)=>{if(!(!o.searchIndexes||o.searchIndexes.length===0||!b(r))){for(const i of o.searchIndexes){const n=S(t,i.name);a(r,e`CREATE VIRTUAL TABLE IF NOT EXISTS ${e.identifier(n)} USING fts5(${e.identifier(I)}, ${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")})`)}g(r,t,o)}},j=(r,t,o)=>{if(o.geoIndexes)for(const i of o.geoIndexes){const n=F(t,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=`${t}__geo_${i.name}__btree`;a(r,_(s,n,e`${e.identifier("__geohash__")} ASC, ${e.identifier("__id__")} ASC`,!1))}},q=(r,t,o)=>{if(o.aggregateIndexes)for(const i of o.aggregateIndexes){const n=p(t,i.name);a(r,e`CREATE TABLE IF NOT EXISTS ${e.identifier(n)} (${x} TEXT PRIMARY KEY, ${B} REAL, ${c} INTEGER NOT NULL DEFAULT 0)`),a(r,e`PRAGMA table_info(${e.identifier(n)})`).toArray().some(s=>s.name==="__count__")||a(r,e`ALTER TABLE ${e.identifier(n)} ADD COLUMN ${c} INTEGER NOT NULL DEFAULT 0`)}},G=(r,t,o)=>{if(o.rankIndexes)for(const i of o.rankIndexes){const n=Y(t,i.name),s=i.sortBy.map((T,d)=>M(d)),f=s.map(T=>e`${e.identifier(T)} BLOB`),$=f.length>0?e`, ${e.join(f,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${$})`);const m=[e`${e.identifier("__partition__")} ASC`];for(const[T,d]of s.entries()){const A=i.sortBy[T]?.direction;m.push(e`${e.identifier(d)} ${e.raw(A==="desc"?"DESC":"ASC")}`)}m.push(e`${e.identifier("__id__")} ASC`);const L=`${t}__rank_${i.name}__btree`;a(r,_(L,n,e.join(m,e`, `),!1))}},ne=(r,t,o={})=>{o.schemaSnapshot!==void 0&&D(r,o.schemaSnapshot.hash,o.schemaSnapshot.json),U(r);for(const[i,n]of Object.entries(t.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(u)} TEXT NOT NULL
|
|
5
|
-
)`),k(r,i,n),y(r,i,n),j(r,i,n),q(r,i,n),G(r,i,n));o.cdc&&(h(r),l(r),R(r)),O(r),C(r)};export{ne as runShardMigrations};
|