@lunora/shard-engine 1.0.0-alpha.95 → 1.0.0-alpha.97
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 +25 -31
- package/dist/index.d.ts +25 -31
- package/dist/index.mjs +1 -1
- package/dist/packem_shared/{CURSOR_PREFIX-Bn8SFoGd.mjs → CURSOR_PREFIX-BX8jkMJa.mjs} +1 -1
- package/dist/packem_shared/{DATA_MIGRATION_STATE_TABLE-BS6X-_Uu.mjs → DATA_MIGRATION_STATE_TABLE-BMbxLEaN.mjs} +1 -1
- package/dist/packem_shared/{DEFAULT_MAX_RELATION_KEYS-D_Urjl_L.mjs → DEFAULT_MAX_RELATION_KEYS-CYPZfQH9.mjs} +1 -1
- package/dist/packem_shared/{DEFAULT_MAX_RELAYS-DnAAv8zm.mjs → DEFAULT_MAX_RELAYS-hdowkC2x.mjs} +1 -1
- package/dist/packem_shared/{DEFAULT_PROMOTION_THRESHOLDS-Bfx7KakS.mjs → DEFAULT_PROMOTION_THRESHOLDS-91RH_llq.mjs} +1 -1
- package/dist/packem_shared/{DurableStreamRunner-C4SbxTDz.mjs → DurableStreamRunner-Dk9Pn-B8.mjs} +1 -1
- package/dist/packem_shared/NotUniqueError-D4EV8EzO.mjs +1 -0
- package/dist/packem_shared/{RELATED_DEFAULT_LIMIT-B9PH28Pn.mjs → RELATED_DEFAULT_LIMIT-CBYQQIrZ.mjs} +1 -1
- package/dist/packem_shared/{RLS_UNWRAP_SYMBOL-BwwTbz3Q.mjs → RLS_UNWRAP_SYMBOL-rSxYzw-G.mjs} +1 -1
- package/dist/packem_shared/{VECTOR_BACKFILL_MAX_PAGES-jQVe2NO6.mjs → VECTOR_BACKFILL_MAX_PAGES-B2ZWxshy.mjs} +1 -1
- package/dist/packem_shared/{appendStreamChunk-y5mkpRdi.mjs → appendStreamChunk-7ZyAZGg_.mjs} +1 -1
- package/dist/packem_shared/{applyOnDelete-7JZ4vR9r.mjs → applyOnDelete-DJsOG8tz.mjs} +1 -1
- package/dist/packem_shared/{backfillAggregateIndexes-D5q_pbdY.mjs → backfillAggregateIndexes-B_3xdOgV.mjs} +1 -1
- package/dist/packem_shared/{buildSettings-DC3VeQ0H.mjs → buildSettings-BRkZd6_E.mjs} +1 -1
- package/dist/packem_shared/{computeRankPage-BosAhREj.mjs → computeRankPage-3AiKfT8q.mjs} +1 -1
- package/dist/packem_shared/{createCompanionSync-BpE0xoMp.mjs → createCompanionSync-Rjn0lsT6.mjs} +1 -1
- package/dist/packem_shared/{ctx-db-relay-shapes-CClD3ldv.mjs → ctx-db-relay-shapes-DuqhDLw8.mjs} +1 -1
- package/dist/packem_shared/{defineEngineContractSuite-6k3JzatE.mjs → defineEngineContractSuite-BkVGn8QW.mjs} +1 -1
- package/dist/packem_shared/{runShardMigrations-DvjE3byP.mjs → runShardMigrations-MXioI81k.mjs} +1 -1
- package/package.json +3 -3
- package/dist/packem_shared/NotUniqueError-CYBVrJib.mjs +0 -1
|
@@ -1 +1 @@
|
|
|
1
|
-
import{defineEngineContractSuite as t}from"../packem_shared/defineEngineContractSuite-
|
|
1
|
+
import{defineEngineContractSuite as t}from"../packem_shared/defineEngineContractSuite-BkVGn8QW.mjs";export{t as defineEngineContractSuite};
|
package/dist/index.d.mts
CHANGED
|
@@ -297,12 +297,6 @@ interface WithInput {
|
|
|
297
297
|
[relationName: string]: NestedWith | Record<string, true> | boolean | undefined;
|
|
298
298
|
_count?: Record<string, true>;
|
|
299
299
|
}
|
|
300
|
-
interface ApplyOnDeleteOptions$1 {
|
|
301
|
-
database: DatabaseWriterLike;
|
|
302
|
-
relation: RelationDefinitionLike;
|
|
303
|
-
row: Record<string, unknown>;
|
|
304
|
-
tableName: string;
|
|
305
|
-
}
|
|
306
300
|
interface FanOutBudget {
|
|
307
301
|
remaining: number;
|
|
308
302
|
}
|
|
@@ -847,12 +841,6 @@ declare const CLIENT_WATERMARK_TABLE = "__client_watermark";
|
|
|
847
841
|
declare const migrateClientWatermark: (sql: SqlExec) => void;
|
|
848
842
|
declare const readClientWatermark: (sql: SqlExec, identity: string, clientId: string) => number;
|
|
849
843
|
declare const advanceClientWatermark: (sql: SqlExec, identity: string, clientId: string, mutationId: number) => void;
|
|
850
|
-
declare const GLOBAL_SHAPE_SNAPSHOT_TABLE = "__global_shape_snapshot";
|
|
851
|
-
declare const migrateGlobalShapeSnapshot: (sql: SqlExec) => void;
|
|
852
|
-
declare const readGlobalShapeSnapshot: (sql: SqlExec, connectionId: string, subId: string) => Map<string, string> | undefined;
|
|
853
|
-
declare const writeGlobalShapeSnapshot: (sql: SqlExec, connectionId: string, subId: string, snapshot: Map<string, string>) => void;
|
|
854
|
-
declare const deleteGlobalShapeSnapshot: (sql: SqlExec, connectionId: string, subId: string) => void;
|
|
855
|
-
declare const deleteGlobalShapeSnapshotsForConnection: (sql: SqlExec, connectionId: string) => void;
|
|
856
844
|
declare const IDEMPOTENCY_TABLE = "__idempotency";
|
|
857
845
|
interface IdempotentRecord {
|
|
858
846
|
resultJson: string;
|
|
@@ -869,24 +857,6 @@ declare const runShardMigrations: (sql: SqlExec, schema: SchemaLike, options?: {
|
|
|
869
857
|
json: string;
|
|
870
858
|
};
|
|
871
859
|
}) => void;
|
|
872
|
-
/**
|
|
873
|
-
* How far a companion's backfill has progressed, and under which analysis.
|
|
874
|
-
* Declared here rather than beside either engine's state table: both record the
|
|
875
|
-
* same three facts, and the decisions made from them are the shared policy
|
|
876
|
-
* below.
|
|
877
|
-
*/
|
|
878
|
-
interface BackfillState {
|
|
879
|
-
/** Last `id` indexed, or `undefined` when no page has run yet. */
|
|
880
|
-
cursor: string | undefined;
|
|
881
|
-
/** True once a page came back short — the table is fully indexed. */
|
|
882
|
-
done: boolean;
|
|
883
|
-
/** Analyzer profile the stored rows were built with; `undefined` predates profile tracking. */
|
|
884
|
-
profile: string | undefined;
|
|
885
|
-
}
|
|
886
|
-
declare const SEARCH_STATE_TABLE = "__lunora_search_state";
|
|
887
|
-
declare const migrateSearchState: (sql: SqlExec) => void;
|
|
888
|
-
declare const readSearchBackfillState: (sql: SqlExec, companion: string) => BackfillState;
|
|
889
|
-
declare const writeSearchBackfillState: (sql: SqlExec, companion: string, cursor: string | undefined, done: boolean, profile: string) => void;
|
|
890
860
|
interface ShapeRow {
|
|
891
861
|
doc: Record<string, unknown>;
|
|
892
862
|
id: string;
|
|
@@ -1011,6 +981,12 @@ interface CompanionSync {
|
|
|
1011
981
|
syncSearch: (tableName: string, id: string, document: Record<string, unknown> | undefined, previous?: Record<string, unknown>) => void;
|
|
1012
982
|
}
|
|
1013
983
|
declare const createCompanionSync: (deps: CompanionSyncDeps) => CompanionSync;
|
|
984
|
+
declare const GLOBAL_SHAPE_SNAPSHOT_TABLE = "__global_shape_snapshot";
|
|
985
|
+
declare const migrateGlobalShapeSnapshot: (sql: SqlExec) => void;
|
|
986
|
+
declare const readGlobalShapeSnapshot: (sql: SqlExec, connectionId: string, subId: string) => Map<string, string> | undefined;
|
|
987
|
+
declare const writeGlobalShapeSnapshot: (sql: SqlExec, connectionId: string, subId: string, snapshot: Map<string, string>) => void;
|
|
988
|
+
declare const deleteGlobalShapeSnapshot: (sql: SqlExec, connectionId: string, subId: string) => void;
|
|
989
|
+
declare const deleteGlobalShapeSnapshotsForConnection: (sql: SqlExec, connectionId: string) => void;
|
|
1014
990
|
declare const isMemoryTable: (definition: TableDefinitionLike | undefined) => boolean;
|
|
1015
991
|
declare const memoryTableNames: (schema: SchemaLike) => string[];
|
|
1016
992
|
declare const clearMemoryTables: (sql: SqlExec, schema: SchemaLike) => number;
|
|
@@ -1065,6 +1041,24 @@ declare const probeScheduleOutbox: (sql: SqlExec) => {
|
|
|
1065
1041
|
populated: boolean;
|
|
1066
1042
|
};
|
|
1067
1043
|
declare const trimScheduleOutbox: (sql: SqlExec, olderThanTs: number) => void;
|
|
1044
|
+
/**
|
|
1045
|
+
* How far a companion's backfill has progressed, and under which analysis.
|
|
1046
|
+
* Declared here rather than beside either engine's state table: both record the
|
|
1047
|
+
* same three facts, and the decisions made from them are the shared policy
|
|
1048
|
+
* below.
|
|
1049
|
+
*/
|
|
1050
|
+
interface BackfillState {
|
|
1051
|
+
/** Last `id` indexed, or `undefined` when no page has run yet. */
|
|
1052
|
+
cursor: string | undefined;
|
|
1053
|
+
/** True once a page came back short — the table is fully indexed. */
|
|
1054
|
+
done: boolean;
|
|
1055
|
+
/** Analyzer profile the stored rows were built with; `undefined` predates profile tracking. */
|
|
1056
|
+
profile: string | undefined;
|
|
1057
|
+
}
|
|
1058
|
+
declare const SEARCH_STATE_TABLE = "__lunora_search_state";
|
|
1059
|
+
declare const migrateSearchState: (sql: SqlExec) => void;
|
|
1060
|
+
declare const readSearchBackfillState: (sql: SqlExec, companion: string) => BackfillState;
|
|
1061
|
+
declare const writeSearchBackfillState: (sql: SqlExec, companion: string, cursor: string | undefined, done: boolean, profile: string) => void;
|
|
1068
1062
|
declare const SHAPE_POKE_CURSOR_TABLE = "__shape_poke_cursor";
|
|
1069
1063
|
declare const migrateShapePokeCursor: (sql: SqlExec) => void;
|
|
1070
1064
|
declare const readShapePokeCursor: (sql: SqlExec, connectionId: string, subId: string) => number | undefined;
|
|
@@ -2521,4 +2515,4 @@ interface WhereSqlStrategy<T = SQL> {
|
|
|
2521
2515
|
}
|
|
2522
2516
|
declare const serverInList: (engine: "mysql" | "postgres") => (reference: SQL, items: ReadonlyArray<unknown>, negated: boolean, budget?: number) => SQL;
|
|
2523
2517
|
declare const compileWhereSql: <T = SQL>(where: WhereInput | undefined, strategy: WhereSqlStrategy<T>, fragments?: WhereFragments<T>, reservedParams?: number) => T | undefined;
|
|
2524
|
-
export { ADMIN_FUNCTIONS, ADMIN_FUNCTION_PREFIX, AGGREGATE_SQL_FUNCTION, AGG_COUNT, AGG_KEY, AGG_VALUE, AUDIT_LOG_TABLE, type AdvisorProcedure, type AdvisorProceduresResult, type AdvisoriesResult, type AdvisoryFinding, type AggregateIndexDefinitionLike, type AggregateOp, type AggregateOptions, type AggregateResult, type AggregateTally, type AppendAuditEntry, type ApplyOnDeleteOptions$1 as ApplyOnDeleteOptions, type AuditEntry, type AuditLogResult, BIGINT_KEY_DIGITS, type BroadcastDelta, CDC_LOG_TABLE, CDC_LOG_TABLE_SEQ_INDEX, CDC_META_TABLE, CLIENT_WATERMARK_TABLE, COMMIT_SEQ_FIELD, COMMIT_SEQ_TABLE, CURSOR_PREFIX, type CacheEntry, type CapturedMailRow, type CdcArchiveScope, type CdcChange, type CdcChangeKey, type ChangedKeys, type Clock, type ColumnMeta, type ColumnMetaLike, type CompanionSync, type CompanionSyncDeps, ConflictError, type ConflictKind, type CountArgs, CountRlsUnsupportedError, type CreateWorkflowInstanceResult, type CrossShardReadArgs, type CtxDbOptions, DATA_MIGRATION_STATE_TABLE, DEFAULT_FANOUT_TOPIC_LIMIT, DEFAULT_MAX_RELATION_KEYS, DEFAULT_MAX_RELAYS, DEFAULT_PROMOTION_THRESHOLDS, DEFAULT_TRANSACTION_LIMITS, DOC_COLUMN, type DataMigrationDocument, type DataMigrationLike, type DataMigrationTransform, type DatabaseWriterLike, type DependencyTracker, type DeployInfo, type DurableAttachDecision, type DurableStreamAttach, type DurableStreamRun, DurableStreamRunner, type DurableStreamSink, type ExportRow, type ExportShardAdminArgs, type ExportShardArgs, type ExternalSourceDiffResult, type ExternalSourceLike, FLAGS_FUNCTION_PREFIX, type FacetColumnOptions, type FacetColumnResult, type FacetValue, type FanOutBudget, type FanoutMetricsResult, type FanoutPathCounters, type FanoutTopicStat, type FieldOperators, type FilterClause, type FilterOperator, type FlagEvaluation, type FlagsResult, type FtsWriteOptions, type FunctionCallStat, type FunctionScanAttribution, type FunctionStatsResult, GEO_DEFAULT_PRECISION, GLOBAL_SHAPE_SNAPSHOT_TABLE, type GeoBoundingBox, type GeoFilterBuilderLike, type GeoIndexDefinitionLike, type GeoPoint, type GeoScoredDocument, type GlobalPollCounters, GlobalPollTick, type GroupByEntry, type GroupByOptions, type GuardableSchema$1 as GuardableSchema, IDEMPOTENCY_TABLE, type IdGenerator, type IdempotentRecord, type ImportError, type ImportShardAdminArgs, type ImportShardArgs, type ImportShardResult, type IncrementalMaterializeResult, type IndexDefinitionLike, type IndexKeyEntry, type IndexRangeBuilderLike, type KeyRange, type LifecycleDispatchInfo, type LifecycleEvent, MAIL_RETENTION, MAIL_TABLE, MAX_DURABLE_STREAM_BYTES, MAX_DURABLE_STREAM_CHUNKS, MAX_PAGE_SIZE, MAX_SQL_ROWS, type MaskColumnMetadata, type MaskPoliciesResult, type MaterializeResult, type MigrationDirection, type MigrationRunResult, type MigrationStatus, type MigrationStatusRow, type MutationDelta, type NestedWith, NotFoundError, NotUniqueError, type OnDeleteActionLike, type OrderByClause, type OrderByInput, type OrderKey, type OrderKeyConstraints, OwnerRelay, type OwnerRelayFrame, type PaginationOptions, type PitrBookmarkResult, type PitrRestoreArgs, type PitrRestoreResult, type PitrStorage, type PokeFrameMeta, type PromotionState, type PromotionThresholds, QUEUE_TABLE, type QueryArgs, type QueryPage, type QueueMessageOutcome, type QueueMessageRow, type QueueMetadata, type QueuesResult, RANK_TIEBREAK, REACTOR_STATE_TABLE, RELATED_DEFAULT_LIMIT, RELATED_DEPTH_DECAY, RELATED_MAX_DEPTH, RELATED_MAX_LIMIT, RELATION_EXISTS_KEY, RELATION_FUNCTION_PREFIX, REPROJECTION_MIGRATION_PREFIX, RLS_UNWRAP_SYMBOL, type RankBeforeOptions, type RankBeforeResult, type RankDirection, type RankIndexDefinitionLike, type RankOptions, type RankPage, type RankPageComputation, type RankPageDeps, type RankPageOptions, type RankPageRow, type RankPageRowKey, type RankResult, type RankSortKeyLike, ReactiveCache, type ReactiveCacheOptions, type ReactorDispatchResult, type ReactorMetadata, type ReactorState, type ReactorStats, type ReactorsResult, type ReadFootprint, type ReadHook, type ReadTablePageOptions, type RecordMailInput, type RecordQueueMessageInput, type RelatedDirection, type RelatedNode, type RelatedOptions, type RelatedPage, type RelatedStart, type RelatedStartReference, type RelationDefinitionLike, type RelationEdge, type RelationExistsMarker, type RelationGraphReader, type RelayAttach, type RelayDetach, type RelayFrame, type RelayHost, RelayMember, type RelayPokeDelivery, type RelayShapePoke, type RelayShapeSeed, type RelayShapeSubscribe, type RelayShapeUnsubscribe, type RenderedSql, type ReplicaFollowerHost, type ReplicaOwnerHost, type ReplicaReadiness, type ResolveRelationPredicatesOptions, type ResolveWithOptions, type ResolveWithResult, type ResolvedShape, type RestrictableQueryOptions, type RlsPoliciesResult, type RlsPolicyMetadata, RlsRequiredError, type RlsRoleMetadata, type RpcRequest, type RunDataMigrationOptions, type RunTriggersOptions, SCAN_DEP, SCHEDULE_OUTBOX_TABLE, SCHEMA_HISTORY_MAX_VERSIONS, SEARCH_STATE_TABLE, SHAPE_POKE_CURSOR_TABLE, type SchedulableWorkflowReferenceLike, type ScheduleOutbox, type ScheduleOutboxEnvelope, type ScheduleOutboxRow, type ScheduledFunctionDoc, type SchedulerLike, type SchemaLike, type ScoredDocument, type SearchBackfillProgress, type SearchFilterBuilderLike, type SearchIndexDefinitionLike, type SearchScoredDocument, type SelectMatchingIdsOptions, type ServerDefaultContextLike, type SettingEntry, type SettingKind, type SettingsResult, ShapeDiffCache, type ShapePokeCursorRow, type ShapePokePart, type ShapeProbeCounters, type ShapeRow, type ShapeRowOp, type ShapeSubscriptionQuery, type ShardRankPageResult, ShardRunner, type ShardRunnerOptions, type ShardSiblingHost, type ShardSocketLike, type SocketAttachment, type SortDirection, type SourceClientLike, type SourceCursorLike, type SourceRefresh, type SqlConsoleResult, type SqlCursor, type SqlEngine, type SqlExec, type SqlLintResult, type StorageMetadata, type StorageReference, type StorageReferenceResult, type StorageRuleMetadata, type StorageRulesResult, type StudioFeaturesResult, type SubscriptionConnection, type SubscriptionEnvelope, type SubscriptionIdentity, type SubscriptionInfo, type SubscriptionQuery, type SubscriptionReadFootprint, type SubscriptionsResult, type SystemDatabaseReader, type SystemDoc, type SystemQuery, type SystemReaderOptions, type SystemReaderSchedulerLike, type SystemReaderStorageLike, type SystemTableName, type TableColumnsResult, type TableDefinitionLike, type TableIndexInfo, type TableIndexesResult, type TableInfo, type TablePage, type TableReaderLike, type TablesColumnsResult, type TablesIndexesResult, type TransactionHeadroom, TransactionHeadroomTracker, type TransactionLimits, type TransactionSqlLike, type TriggerContextLike, type TriggerDefinitionLike, type TriggerEventLike, type TriggerOpLike, type TriggerTimingLike, type TtlSweepSpec, UNVOUCHABLE_DEP, VECTOR_BACKFILL_MAX_PAGES, type ValidatorLike, type VectorBackfillProgress, WORKERD_SQLITE_LIMITS, type WhereFilter, type WhereInput, type WhereSqlStrategy, type WithInput, type WorkflowInstanceState, type WorkflowInstanceStatusResult, type WorkflowMetadata, type WorkflowsResult, type WriteEvent, type WriteHook, advanceClientWatermark, aggUpsertSql, aggregateSqlFunction, aggregateTableName, allocateCommitSeq, appendAuditEntry, appendCdcChange, appendStreamChunk, applyCdcChanges, applyOnDelete, applySelect, archiveCdcSegment, armRestore, assertFlatPredicate, assertNoExplicitUndefined, assertReadonly, assertShapeShardable, assertValidClientId, awaitWsDrain, backfillAggregateIndexes, backfillRankIndexes, backfillSearchIndexes, backfillSearchIndexesForTable, backfillVectorIndexes, bigintSqlKey, boundingBoxCenter, boundingBoxGeohashes, buildIndexRange, buildPokeFrames, buildReprojectionMigration, buildSeekBeforeWhere, buildSeekWhere, buildSettings, buildShapeDiff, bumpCdcEpoch, cdcArchiveRewound, cdcCanVouchFor, cdcForkedError, cdcSeqLeavingRows, cdcTouchesTables, cdcTrimmedError, claimStreamRun, clampPromotionThresholds, clearCapturedMail, clearMemoryTables, clearQueueMessages, coerceAggregateNumber, compactCdcDocs, compileWhereSql, computeRankPage, containsRelationPredicate, countLegacyRows, coveringGeohashes, createCompanionSync, createDependencyTracker, createFanoutCounters, createGlobalPollCounters, createIndexSql, createReadFootprint, createRelayLink, createReplicaLink, createShapeDiffCache, createShapeProbeCounters, createShardCtxDb, createSystemReader, cursorBelowRetainedFloor, decideDurableAttach, decodeBigintSqlKey, decodeCursor, decodeFloat64SqlKey, deferScheduleOutbox, deleteGlobalShapeSnapshot, deleteGlobalShapeSnapshotsForConnection, deleteShapePokeCursor, deleteShapePokeCursorsForConnection, deleteStreamRun, depKey, deriveRelationEdges, diffExternalSource, diffGlobalMembership, distinctValues, encodeAggregateKey, encodeCursor, encodeGeohash, encodePartitionKey, encodeRowsPatch, ensureAuditTable, ensureMailTable, envOptionalPositiveInt, envPositiveInt, equalityPinnedFields, exportShardRows, facetColumn, fanOutScalarCounts, findRelated, findStorageReferences, finishStreamRun, float64SqlKey, foldAggregateTally, forgetScheduleOutbox, ftsCompanionDdl, ftsPurgeDocument, ftsRowidMapName, ftsUnmappedPage, ftsWriteDocument, gateReplicaDispatch, geoTableName, globalShapeReadKey, groupUnmappedRows, guardWriter, handleReplicaControl, hasTrigger, haversineMeters, importShardRows, indexKeysForRow, isDevEnvironment, isFtsAvailable, isInternalTableName, isLossyBody, isMemoryTable, isPushableWhere, isRelationPredicate, isSoftDeleted, isSourceDue, isVacuousFilterClause, jsonPath, jsonPathSql, keysTouchRanges, liftSourceId, lintReadonlySql, listReactorStates, listTables, markUnvouchableReads, matchesRankStaticWhere, matchesStaticWhere, materializeExternalRows, materializeExternalRowsIncremental, memoryTableNames, mergeChangedKeys, mergeWhere, migrateCdcLog, migrateCdcMeta, migrateClientWatermark, migrateCommitSeq, migrateDurableStreams, migrateGlobalShapeSnapshot, migrateIdempotency, migrateReactorState, migrateScheduleOutbox, migrateSearchState, migrateShapePokeCursor, minCdcReplayableSeq, minCdcSeq, minShapePokeCursor, nextPromotionState, normalizeCountArgument, normalizeIdStructurally, normalizeOrderKeys, normalizeSourceDocument, normalizeSourceValue, param, parkScheduleOutbox, parseExportShardArgs, parseImportShardArgs, planAggregateLookup, pointInBoundingBox, probeScheduleOutbox, projectColumns, pullExternalSourceIncrementalTick, pullExternalSourceTick, qualifiedJsonPath, qualifiedJsonPathSql, quoteIdentifier, rankKeyFromDocument as rankKeyFromDoc, rankPivotConditionSql, rankTableName, reactiveCacheKey, reactorNeedsRun, readAggregateValue, readArchivedCdcChanges, readAuditLog, readBookmark, readCapturedMail, readCdcArchivedThrough, readCdcChangeKeys, readCdcChanges, readCdcCursor, readCdcEpoch, readClientWatermark, readCommitSeq, readDeployInfo, readDueScheduleOutbox, readExternalSourceBaseline, readGlobalShapeSnapshot, readIdempotent, readMigrationStatus, readQueueMessageById, readQueueMessages, readReactorState, readSchemaHistory, readSchemaVersion, readSearchBackfillState, readShapePokeCursor, readStreamChunks, readStreamRun, readTablePage, recordCapturedMail, recordChangedKeys, recordFanoutPass, recordGlobalPollPass, recordQueueMessages, recordScheduleOutbox, recordSchemaVersion, recordShapeProbePass, relationHooks, relayCountFor, renderSql, reprojectableFields, reprojectionMigrationId, reprojectionTables, resolveRankPartition, resolveRankSeekTuple, resolveRelationPredicates, resolveWith, rowToDocument, runDataMigration, runDrizzle, runExternalSourceTick, runReadonlySql, runRowValidators, runShardMigrations, runSocketPool, runSql, runTriggers, selectExpiredIds, selectExportTables, selectIndexForAggregate, selectIndexForCount, selectIndexForGroupBy, selectMatchingIds, selectShapeMembers, selectShapeRows, serializeSqlValue, serverInList, shapeRoutingKey, softDeleteScope, sortColumnName, sqliteInList, stableStringify, stableWireKey, stripReservedPatchFields, subscriptionFrames, subscriptionListDeltas, summarizeFanoutTopics, summarizeSubscriptions, tableColumns, tableFromDepKey, throwingScheduler, tiebreakDirectionFor, trimCdcChanges, trimIdempotent, trimScheduleOutbox, trimStreamRuns, tryRowToDocument, trySendFrame, unionAll, uniqueIndexFields, validateImportRow, whereFilter, whereOfFilter, writeCdcArchivedThrough, writeGlobalShapeSnapshot, writeIdempotent, writeReactorState, writeSearchBackfillState, writeShapePokeCursor, writeShapePokeCursors, writeTouchesMemo };
|
|
2518
|
+
export { ADMIN_FUNCTIONS, ADMIN_FUNCTION_PREFIX, AGGREGATE_SQL_FUNCTION, AGG_COUNT, AGG_KEY, AGG_VALUE, AUDIT_LOG_TABLE, type AdvisorProcedure, type AdvisorProceduresResult, type AdvisoriesResult, type AdvisoryFinding, type AggregateIndexDefinitionLike, type AggregateOp, type AggregateOptions, type AggregateResult, type AggregateTally, type AppendAuditEntry, type ApplyOnDeleteOptions, type AuditEntry, type AuditLogResult, BIGINT_KEY_DIGITS, type BroadcastDelta, CDC_LOG_TABLE, CDC_LOG_TABLE_SEQ_INDEX, CDC_META_TABLE, CLIENT_WATERMARK_TABLE, COMMIT_SEQ_FIELD, COMMIT_SEQ_TABLE, CURSOR_PREFIX, type CacheEntry, type CapturedMailRow, type CdcArchiveScope, type CdcChange, type CdcChangeKey, type ChangedKeys, type Clock, type ColumnMeta, type ColumnMetaLike, type CompanionSync, type CompanionSyncDeps, ConflictError, type ConflictKind, type CountArgs, CountRlsUnsupportedError, type CreateWorkflowInstanceResult, type CrossShardReadArgs, type CtxDbOptions, DATA_MIGRATION_STATE_TABLE, DEFAULT_FANOUT_TOPIC_LIMIT, DEFAULT_MAX_RELATION_KEYS, DEFAULT_MAX_RELAYS, DEFAULT_PROMOTION_THRESHOLDS, DEFAULT_TRANSACTION_LIMITS, DOC_COLUMN, type DataMigrationDocument, type DataMigrationLike, type DataMigrationTransform, type DatabaseWriterLike, type DependencyTracker, type DeployInfo, type DurableAttachDecision, type DurableStreamAttach, type DurableStreamRun, DurableStreamRunner, type DurableStreamSink, type ExportRow, type ExportShardAdminArgs, type ExportShardArgs, type ExternalSourceDiffResult, type ExternalSourceLike, FLAGS_FUNCTION_PREFIX, type FacetColumnOptions, type FacetColumnResult, type FacetValue, type FanOutBudget, type FanoutMetricsResult, type FanoutPathCounters, type FanoutTopicStat, type FieldOperators, type FilterClause, type FilterOperator, type FlagEvaluation, type FlagsResult, type FtsWriteOptions, type FunctionCallStat, type FunctionScanAttribution, type FunctionStatsResult, GEO_DEFAULT_PRECISION, GLOBAL_SHAPE_SNAPSHOT_TABLE, type GeoBoundingBox, type GeoFilterBuilderLike, type GeoIndexDefinitionLike, type GeoPoint, type GeoScoredDocument, type GlobalPollCounters, GlobalPollTick, type GroupByEntry, type GroupByOptions, type GuardableSchema$1 as GuardableSchema, IDEMPOTENCY_TABLE, type IdGenerator, type IdempotentRecord, type ImportError, type ImportShardAdminArgs, type ImportShardArgs, type ImportShardResult, type IncrementalMaterializeResult, type IndexDefinitionLike, type IndexKeyEntry, type IndexRangeBuilderLike, type KeyRange, type LifecycleDispatchInfo, type LifecycleEvent, MAIL_RETENTION, MAIL_TABLE, MAX_DURABLE_STREAM_BYTES, MAX_DURABLE_STREAM_CHUNKS, MAX_PAGE_SIZE, MAX_SQL_ROWS, type MaskColumnMetadata, type MaskPoliciesResult, type MaterializeResult, type MigrationDirection, type MigrationRunResult, type MigrationStatus, type MigrationStatusRow, type MutationDelta, type NestedWith, NotFoundError, NotUniqueError, type OnDeleteActionLike, type OrderByClause, type OrderByInput, type OrderKey, type OrderKeyConstraints, OwnerRelay, type OwnerRelayFrame, type PaginationOptions, type PitrBookmarkResult, type PitrRestoreArgs, type PitrRestoreResult, type PitrStorage, type PokeFrameMeta, type PromotionState, type PromotionThresholds, QUEUE_TABLE, type QueryArgs, type QueryPage, type QueueMessageOutcome, type QueueMessageRow, type QueueMetadata, type QueuesResult, RANK_TIEBREAK, REACTOR_STATE_TABLE, RELATED_DEFAULT_LIMIT, RELATED_DEPTH_DECAY, RELATED_MAX_DEPTH, RELATED_MAX_LIMIT, RELATION_EXISTS_KEY, RELATION_FUNCTION_PREFIX, REPROJECTION_MIGRATION_PREFIX, RLS_UNWRAP_SYMBOL, type RankBeforeOptions, type RankBeforeResult, type RankDirection, type RankIndexDefinitionLike, type RankOptions, type RankPage, type RankPageComputation, type RankPageDeps, type RankPageOptions, type RankPageRow, type RankPageRowKey, type RankResult, type RankSortKeyLike, ReactiveCache, type ReactiveCacheOptions, type ReactorDispatchResult, type ReactorMetadata, type ReactorState, type ReactorStats, type ReactorsResult, type ReadFootprint, type ReadHook, type ReadTablePageOptions, type RecordMailInput, type RecordQueueMessageInput, type RelatedDirection, type RelatedNode, type RelatedOptions, type RelatedPage, type RelatedStart, type RelatedStartReference, type RelationDefinitionLike, type RelationEdge, type RelationExistsMarker, type RelationGraphReader, type RelayAttach, type RelayDetach, type RelayFrame, type RelayHost, RelayMember, type RelayPokeDelivery, type RelayShapePoke, type RelayShapeSeed, type RelayShapeSubscribe, type RelayShapeUnsubscribe, type RenderedSql, type ReplicaFollowerHost, type ReplicaOwnerHost, type ReplicaReadiness, type ResolveRelationPredicatesOptions, type ResolveWithOptions, type ResolveWithResult, type ResolvedShape, type RestrictableQueryOptions, type RlsPoliciesResult, type RlsPolicyMetadata, RlsRequiredError, type RlsRoleMetadata, type RpcRequest, type RunDataMigrationOptions, type RunTriggersOptions, SCAN_DEP, SCHEDULE_OUTBOX_TABLE, SCHEMA_HISTORY_MAX_VERSIONS, SEARCH_STATE_TABLE, SHAPE_POKE_CURSOR_TABLE, type SchedulableWorkflowReferenceLike, type ScheduleOutbox, type ScheduleOutboxEnvelope, type ScheduleOutboxRow, type ScheduledFunctionDoc, type SchedulerLike, type SchemaLike, type ScoredDocument, type SearchBackfillProgress, type SearchFilterBuilderLike, type SearchIndexDefinitionLike, type SearchScoredDocument, type SelectMatchingIdsOptions, type ServerDefaultContextLike, type SettingEntry, type SettingKind, type SettingsResult, ShapeDiffCache, type ShapePokeCursorRow, type ShapePokePart, type ShapeProbeCounters, type ShapeRow, type ShapeRowOp, type ShapeSubscriptionQuery, type ShardRankPageResult, ShardRunner, type ShardRunnerOptions, type ShardSiblingHost, type ShardSocketLike, type SocketAttachment, type SortDirection, type SourceClientLike, type SourceCursorLike, type SourceRefresh, type SqlConsoleResult, type SqlCursor, type SqlEngine, type SqlExec, type SqlLintResult, type StorageMetadata, type StorageReference, type StorageReferenceResult, type StorageRuleMetadata, type StorageRulesResult, type StudioFeaturesResult, type SubscriptionConnection, type SubscriptionEnvelope, type SubscriptionIdentity, type SubscriptionInfo, type SubscriptionQuery, type SubscriptionReadFootprint, type SubscriptionsResult, type SystemDatabaseReader, type SystemDoc, type SystemQuery, type SystemReaderOptions, type SystemReaderSchedulerLike, type SystemReaderStorageLike, type SystemTableName, type TableColumnsResult, type TableDefinitionLike, type TableIndexInfo, type TableIndexesResult, type TableInfo, type TablePage, type TableReaderLike, type TablesColumnsResult, type TablesIndexesResult, type TransactionHeadroom, TransactionHeadroomTracker, type TransactionLimits, type TransactionSqlLike, type TriggerContextLike, type TriggerDefinitionLike, type TriggerEventLike, type TriggerOpLike, type TriggerTimingLike, type TtlSweepSpec, UNVOUCHABLE_DEP, VECTOR_BACKFILL_MAX_PAGES, type ValidatorLike, type VectorBackfillProgress, WORKERD_SQLITE_LIMITS, type WhereFilter, type WhereInput, type WhereSqlStrategy, type WithInput, type WorkflowInstanceState, type WorkflowInstanceStatusResult, type WorkflowMetadata, type WorkflowsResult, type WriteEvent, type WriteHook, advanceClientWatermark, aggUpsertSql, aggregateSqlFunction, aggregateTableName, allocateCommitSeq, appendAuditEntry, appendCdcChange, appendStreamChunk, applyCdcChanges, applyOnDelete, applySelect, archiveCdcSegment, armRestore, assertFlatPredicate, assertNoExplicitUndefined, assertReadonly, assertShapeShardable, assertValidClientId, awaitWsDrain, backfillAggregateIndexes, backfillRankIndexes, backfillSearchIndexes, backfillSearchIndexesForTable, backfillVectorIndexes, bigintSqlKey, boundingBoxCenter, boundingBoxGeohashes, buildIndexRange, buildPokeFrames, buildReprojectionMigration, buildSeekBeforeWhere, buildSeekWhere, buildSettings, buildShapeDiff, bumpCdcEpoch, cdcArchiveRewound, cdcCanVouchFor, cdcForkedError, cdcSeqLeavingRows, cdcTouchesTables, cdcTrimmedError, claimStreamRun, clampPromotionThresholds, clearCapturedMail, clearMemoryTables, clearQueueMessages, coerceAggregateNumber, compactCdcDocs, compileWhereSql, computeRankPage, containsRelationPredicate, countLegacyRows, coveringGeohashes, createCompanionSync, createDependencyTracker, createFanoutCounters, createGlobalPollCounters, createIndexSql, createReadFootprint, createRelayLink, createReplicaLink, createShapeDiffCache, createShapeProbeCounters, createShardCtxDb, createSystemReader, cursorBelowRetainedFloor, decideDurableAttach, decodeBigintSqlKey, decodeCursor, decodeFloat64SqlKey, deferScheduleOutbox, deleteGlobalShapeSnapshot, deleteGlobalShapeSnapshotsForConnection, deleteShapePokeCursor, deleteShapePokeCursorsForConnection, deleteStreamRun, depKey, deriveRelationEdges, diffExternalSource, diffGlobalMembership, distinctValues, encodeAggregateKey, encodeCursor, encodeGeohash, encodePartitionKey, encodeRowsPatch, ensureAuditTable, ensureMailTable, envOptionalPositiveInt, envPositiveInt, equalityPinnedFields, exportShardRows, facetColumn, fanOutScalarCounts, findRelated, findStorageReferences, finishStreamRun, float64SqlKey, foldAggregateTally, forgetScheduleOutbox, ftsCompanionDdl, ftsPurgeDocument, ftsRowidMapName, ftsUnmappedPage, ftsWriteDocument, gateReplicaDispatch, geoTableName, globalShapeReadKey, groupUnmappedRows, guardWriter, handleReplicaControl, hasTrigger, haversineMeters, importShardRows, indexKeysForRow, isDevEnvironment, isFtsAvailable, isInternalTableName, isLossyBody, isMemoryTable, isPushableWhere, isRelationPredicate, isSoftDeleted, isSourceDue, isVacuousFilterClause, jsonPath, jsonPathSql, keysTouchRanges, liftSourceId, lintReadonlySql, listReactorStates, listTables, markUnvouchableReads, matchesRankStaticWhere, matchesStaticWhere, materializeExternalRows, materializeExternalRowsIncremental, memoryTableNames, mergeChangedKeys, mergeWhere, migrateCdcLog, migrateCdcMeta, migrateClientWatermark, migrateCommitSeq, migrateDurableStreams, migrateGlobalShapeSnapshot, migrateIdempotency, migrateReactorState, migrateScheduleOutbox, migrateSearchState, migrateShapePokeCursor, minCdcReplayableSeq, minCdcSeq, minShapePokeCursor, nextPromotionState, normalizeCountArgument, normalizeIdStructurally, normalizeOrderKeys, normalizeSourceDocument, normalizeSourceValue, param, parkScheduleOutbox, parseExportShardArgs, parseImportShardArgs, planAggregateLookup, pointInBoundingBox, probeScheduleOutbox, projectColumns, pullExternalSourceIncrementalTick, pullExternalSourceTick, qualifiedJsonPath, qualifiedJsonPathSql, quoteIdentifier, rankKeyFromDocument as rankKeyFromDoc, rankPivotConditionSql, rankTableName, reactiveCacheKey, reactorNeedsRun, readAggregateValue, readArchivedCdcChanges, readAuditLog, readBookmark, readCapturedMail, readCdcArchivedThrough, readCdcChangeKeys, readCdcChanges, readCdcCursor, readCdcEpoch, readClientWatermark, readCommitSeq, readDeployInfo, readDueScheduleOutbox, readExternalSourceBaseline, readGlobalShapeSnapshot, readIdempotent, readMigrationStatus, readQueueMessageById, readQueueMessages, readReactorState, readSchemaHistory, readSchemaVersion, readSearchBackfillState, readShapePokeCursor, readStreamChunks, readStreamRun, readTablePage, recordCapturedMail, recordChangedKeys, recordFanoutPass, recordGlobalPollPass, recordQueueMessages, recordScheduleOutbox, recordSchemaVersion, recordShapeProbePass, relationHooks, relayCountFor, renderSql, reprojectableFields, reprojectionMigrationId, reprojectionTables, resolveRankPartition, resolveRankSeekTuple, resolveRelationPredicates, resolveWith, rowToDocument, runDataMigration, runDrizzle, runExternalSourceTick, runReadonlySql, runRowValidators, runShardMigrations, runSocketPool, runSql, runTriggers, selectExpiredIds, selectExportTables, selectIndexForAggregate, selectIndexForCount, selectIndexForGroupBy, selectMatchingIds, selectShapeMembers, selectShapeRows, serializeSqlValue, serverInList, shapeRoutingKey, softDeleteScope, sortColumnName, sqliteInList, stableStringify, stableWireKey, stripReservedPatchFields, subscriptionFrames, subscriptionListDeltas, summarizeFanoutTopics, summarizeSubscriptions, tableColumns, tableFromDepKey, throwingScheduler, tiebreakDirectionFor, trimCdcChanges, trimIdempotent, trimScheduleOutbox, trimStreamRuns, tryRowToDocument, trySendFrame, unionAll, uniqueIndexFields, validateImportRow, whereFilter, whereOfFilter, writeCdcArchivedThrough, writeGlobalShapeSnapshot, writeIdempotent, writeReactorState, writeSearchBackfillState, writeShapePokeCursor, writeShapePokeCursors, writeTouchesMemo };
|
package/dist/index.d.ts
CHANGED
|
@@ -297,12 +297,6 @@ interface WithInput {
|
|
|
297
297
|
[relationName: string]: NestedWith | Record<string, true> | boolean | undefined;
|
|
298
298
|
_count?: Record<string, true>;
|
|
299
299
|
}
|
|
300
|
-
interface ApplyOnDeleteOptions$1 {
|
|
301
|
-
database: DatabaseWriterLike;
|
|
302
|
-
relation: RelationDefinitionLike;
|
|
303
|
-
row: Record<string, unknown>;
|
|
304
|
-
tableName: string;
|
|
305
|
-
}
|
|
306
300
|
interface FanOutBudget {
|
|
307
301
|
remaining: number;
|
|
308
302
|
}
|
|
@@ -847,12 +841,6 @@ declare const CLIENT_WATERMARK_TABLE = "__client_watermark";
|
|
|
847
841
|
declare const migrateClientWatermark: (sql: SqlExec) => void;
|
|
848
842
|
declare const readClientWatermark: (sql: SqlExec, identity: string, clientId: string) => number;
|
|
849
843
|
declare const advanceClientWatermark: (sql: SqlExec, identity: string, clientId: string, mutationId: number) => void;
|
|
850
|
-
declare const GLOBAL_SHAPE_SNAPSHOT_TABLE = "__global_shape_snapshot";
|
|
851
|
-
declare const migrateGlobalShapeSnapshot: (sql: SqlExec) => void;
|
|
852
|
-
declare const readGlobalShapeSnapshot: (sql: SqlExec, connectionId: string, subId: string) => Map<string, string> | undefined;
|
|
853
|
-
declare const writeGlobalShapeSnapshot: (sql: SqlExec, connectionId: string, subId: string, snapshot: Map<string, string>) => void;
|
|
854
|
-
declare const deleteGlobalShapeSnapshot: (sql: SqlExec, connectionId: string, subId: string) => void;
|
|
855
|
-
declare const deleteGlobalShapeSnapshotsForConnection: (sql: SqlExec, connectionId: string) => void;
|
|
856
844
|
declare const IDEMPOTENCY_TABLE = "__idempotency";
|
|
857
845
|
interface IdempotentRecord {
|
|
858
846
|
resultJson: string;
|
|
@@ -869,24 +857,6 @@ declare const runShardMigrations: (sql: SqlExec, schema: SchemaLike, options?: {
|
|
|
869
857
|
json: string;
|
|
870
858
|
};
|
|
871
859
|
}) => void;
|
|
872
|
-
/**
|
|
873
|
-
* How far a companion's backfill has progressed, and under which analysis.
|
|
874
|
-
* Declared here rather than beside either engine's state table: both record the
|
|
875
|
-
* same three facts, and the decisions made from them are the shared policy
|
|
876
|
-
* below.
|
|
877
|
-
*/
|
|
878
|
-
interface BackfillState {
|
|
879
|
-
/** Last `id` indexed, or `undefined` when no page has run yet. */
|
|
880
|
-
cursor: string | undefined;
|
|
881
|
-
/** True once a page came back short — the table is fully indexed. */
|
|
882
|
-
done: boolean;
|
|
883
|
-
/** Analyzer profile the stored rows were built with; `undefined` predates profile tracking. */
|
|
884
|
-
profile: string | undefined;
|
|
885
|
-
}
|
|
886
|
-
declare const SEARCH_STATE_TABLE = "__lunora_search_state";
|
|
887
|
-
declare const migrateSearchState: (sql: SqlExec) => void;
|
|
888
|
-
declare const readSearchBackfillState: (sql: SqlExec, companion: string) => BackfillState;
|
|
889
|
-
declare const writeSearchBackfillState: (sql: SqlExec, companion: string, cursor: string | undefined, done: boolean, profile: string) => void;
|
|
890
860
|
interface ShapeRow {
|
|
891
861
|
doc: Record<string, unknown>;
|
|
892
862
|
id: string;
|
|
@@ -1011,6 +981,12 @@ interface CompanionSync {
|
|
|
1011
981
|
syncSearch: (tableName: string, id: string, document: Record<string, unknown> | undefined, previous?: Record<string, unknown>) => void;
|
|
1012
982
|
}
|
|
1013
983
|
declare const createCompanionSync: (deps: CompanionSyncDeps) => CompanionSync;
|
|
984
|
+
declare const GLOBAL_SHAPE_SNAPSHOT_TABLE = "__global_shape_snapshot";
|
|
985
|
+
declare const migrateGlobalShapeSnapshot: (sql: SqlExec) => void;
|
|
986
|
+
declare const readGlobalShapeSnapshot: (sql: SqlExec, connectionId: string, subId: string) => Map<string, string> | undefined;
|
|
987
|
+
declare const writeGlobalShapeSnapshot: (sql: SqlExec, connectionId: string, subId: string, snapshot: Map<string, string>) => void;
|
|
988
|
+
declare const deleteGlobalShapeSnapshot: (sql: SqlExec, connectionId: string, subId: string) => void;
|
|
989
|
+
declare const deleteGlobalShapeSnapshotsForConnection: (sql: SqlExec, connectionId: string) => void;
|
|
1014
990
|
declare const isMemoryTable: (definition: TableDefinitionLike | undefined) => boolean;
|
|
1015
991
|
declare const memoryTableNames: (schema: SchemaLike) => string[];
|
|
1016
992
|
declare const clearMemoryTables: (sql: SqlExec, schema: SchemaLike) => number;
|
|
@@ -1065,6 +1041,24 @@ declare const probeScheduleOutbox: (sql: SqlExec) => {
|
|
|
1065
1041
|
populated: boolean;
|
|
1066
1042
|
};
|
|
1067
1043
|
declare const trimScheduleOutbox: (sql: SqlExec, olderThanTs: number) => void;
|
|
1044
|
+
/**
|
|
1045
|
+
* How far a companion's backfill has progressed, and under which analysis.
|
|
1046
|
+
* Declared here rather than beside either engine's state table: both record the
|
|
1047
|
+
* same three facts, and the decisions made from them are the shared policy
|
|
1048
|
+
* below.
|
|
1049
|
+
*/
|
|
1050
|
+
interface BackfillState {
|
|
1051
|
+
/** Last `id` indexed, or `undefined` when no page has run yet. */
|
|
1052
|
+
cursor: string | undefined;
|
|
1053
|
+
/** True once a page came back short — the table is fully indexed. */
|
|
1054
|
+
done: boolean;
|
|
1055
|
+
/** Analyzer profile the stored rows were built with; `undefined` predates profile tracking. */
|
|
1056
|
+
profile: string | undefined;
|
|
1057
|
+
}
|
|
1058
|
+
declare const SEARCH_STATE_TABLE = "__lunora_search_state";
|
|
1059
|
+
declare const migrateSearchState: (sql: SqlExec) => void;
|
|
1060
|
+
declare const readSearchBackfillState: (sql: SqlExec, companion: string) => BackfillState;
|
|
1061
|
+
declare const writeSearchBackfillState: (sql: SqlExec, companion: string, cursor: string | undefined, done: boolean, profile: string) => void;
|
|
1068
1062
|
declare const SHAPE_POKE_CURSOR_TABLE = "__shape_poke_cursor";
|
|
1069
1063
|
declare const migrateShapePokeCursor: (sql: SqlExec) => void;
|
|
1070
1064
|
declare const readShapePokeCursor: (sql: SqlExec, connectionId: string, subId: string) => number | undefined;
|
|
@@ -2521,4 +2515,4 @@ interface WhereSqlStrategy<T = SQL> {
|
|
|
2521
2515
|
}
|
|
2522
2516
|
declare const serverInList: (engine: "mysql" | "postgres") => (reference: SQL, items: ReadonlyArray<unknown>, negated: boolean, budget?: number) => SQL;
|
|
2523
2517
|
declare const compileWhereSql: <T = SQL>(where: WhereInput | undefined, strategy: WhereSqlStrategy<T>, fragments?: WhereFragments<T>, reservedParams?: number) => T | undefined;
|
|
2524
|
-
export { ADMIN_FUNCTIONS, ADMIN_FUNCTION_PREFIX, AGGREGATE_SQL_FUNCTION, AGG_COUNT, AGG_KEY, AGG_VALUE, AUDIT_LOG_TABLE, type AdvisorProcedure, type AdvisorProceduresResult, type AdvisoriesResult, type AdvisoryFinding, type AggregateIndexDefinitionLike, type AggregateOp, type AggregateOptions, type AggregateResult, type AggregateTally, type AppendAuditEntry, type ApplyOnDeleteOptions$1 as ApplyOnDeleteOptions, type AuditEntry, type AuditLogResult, BIGINT_KEY_DIGITS, type BroadcastDelta, CDC_LOG_TABLE, CDC_LOG_TABLE_SEQ_INDEX, CDC_META_TABLE, CLIENT_WATERMARK_TABLE, COMMIT_SEQ_FIELD, COMMIT_SEQ_TABLE, CURSOR_PREFIX, type CacheEntry, type CapturedMailRow, type CdcArchiveScope, type CdcChange, type CdcChangeKey, type ChangedKeys, type Clock, type ColumnMeta, type ColumnMetaLike, type CompanionSync, type CompanionSyncDeps, ConflictError, type ConflictKind, type CountArgs, CountRlsUnsupportedError, type CreateWorkflowInstanceResult, type CrossShardReadArgs, type CtxDbOptions, DATA_MIGRATION_STATE_TABLE, DEFAULT_FANOUT_TOPIC_LIMIT, DEFAULT_MAX_RELATION_KEYS, DEFAULT_MAX_RELAYS, DEFAULT_PROMOTION_THRESHOLDS, DEFAULT_TRANSACTION_LIMITS, DOC_COLUMN, type DataMigrationDocument, type DataMigrationLike, type DataMigrationTransform, type DatabaseWriterLike, type DependencyTracker, type DeployInfo, type DurableAttachDecision, type DurableStreamAttach, type DurableStreamRun, DurableStreamRunner, type DurableStreamSink, type ExportRow, type ExportShardAdminArgs, type ExportShardArgs, type ExternalSourceDiffResult, type ExternalSourceLike, FLAGS_FUNCTION_PREFIX, type FacetColumnOptions, type FacetColumnResult, type FacetValue, type FanOutBudget, type FanoutMetricsResult, type FanoutPathCounters, type FanoutTopicStat, type FieldOperators, type FilterClause, type FilterOperator, type FlagEvaluation, type FlagsResult, type FtsWriteOptions, type FunctionCallStat, type FunctionScanAttribution, type FunctionStatsResult, GEO_DEFAULT_PRECISION, GLOBAL_SHAPE_SNAPSHOT_TABLE, type GeoBoundingBox, type GeoFilterBuilderLike, type GeoIndexDefinitionLike, type GeoPoint, type GeoScoredDocument, type GlobalPollCounters, GlobalPollTick, type GroupByEntry, type GroupByOptions, type GuardableSchema$1 as GuardableSchema, IDEMPOTENCY_TABLE, type IdGenerator, type IdempotentRecord, type ImportError, type ImportShardAdminArgs, type ImportShardArgs, type ImportShardResult, type IncrementalMaterializeResult, type IndexDefinitionLike, type IndexKeyEntry, type IndexRangeBuilderLike, type KeyRange, type LifecycleDispatchInfo, type LifecycleEvent, MAIL_RETENTION, MAIL_TABLE, MAX_DURABLE_STREAM_BYTES, MAX_DURABLE_STREAM_CHUNKS, MAX_PAGE_SIZE, MAX_SQL_ROWS, type MaskColumnMetadata, type MaskPoliciesResult, type MaterializeResult, type MigrationDirection, type MigrationRunResult, type MigrationStatus, type MigrationStatusRow, type MutationDelta, type NestedWith, NotFoundError, NotUniqueError, type OnDeleteActionLike, type OrderByClause, type OrderByInput, type OrderKey, type OrderKeyConstraints, OwnerRelay, type OwnerRelayFrame, type PaginationOptions, type PitrBookmarkResult, type PitrRestoreArgs, type PitrRestoreResult, type PitrStorage, type PokeFrameMeta, type PromotionState, type PromotionThresholds, QUEUE_TABLE, type QueryArgs, type QueryPage, type QueueMessageOutcome, type QueueMessageRow, type QueueMetadata, type QueuesResult, RANK_TIEBREAK, REACTOR_STATE_TABLE, RELATED_DEFAULT_LIMIT, RELATED_DEPTH_DECAY, RELATED_MAX_DEPTH, RELATED_MAX_LIMIT, RELATION_EXISTS_KEY, RELATION_FUNCTION_PREFIX, REPROJECTION_MIGRATION_PREFIX, RLS_UNWRAP_SYMBOL, type RankBeforeOptions, type RankBeforeResult, type RankDirection, type RankIndexDefinitionLike, type RankOptions, type RankPage, type RankPageComputation, type RankPageDeps, type RankPageOptions, type RankPageRow, type RankPageRowKey, type RankResult, type RankSortKeyLike, ReactiveCache, type ReactiveCacheOptions, type ReactorDispatchResult, type ReactorMetadata, type ReactorState, type ReactorStats, type ReactorsResult, type ReadFootprint, type ReadHook, type ReadTablePageOptions, type RecordMailInput, type RecordQueueMessageInput, type RelatedDirection, type RelatedNode, type RelatedOptions, type RelatedPage, type RelatedStart, type RelatedStartReference, type RelationDefinitionLike, type RelationEdge, type RelationExistsMarker, type RelationGraphReader, type RelayAttach, type RelayDetach, type RelayFrame, type RelayHost, RelayMember, type RelayPokeDelivery, type RelayShapePoke, type RelayShapeSeed, type RelayShapeSubscribe, type RelayShapeUnsubscribe, type RenderedSql, type ReplicaFollowerHost, type ReplicaOwnerHost, type ReplicaReadiness, type ResolveRelationPredicatesOptions, type ResolveWithOptions, type ResolveWithResult, type ResolvedShape, type RestrictableQueryOptions, type RlsPoliciesResult, type RlsPolicyMetadata, RlsRequiredError, type RlsRoleMetadata, type RpcRequest, type RunDataMigrationOptions, type RunTriggersOptions, SCAN_DEP, SCHEDULE_OUTBOX_TABLE, SCHEMA_HISTORY_MAX_VERSIONS, SEARCH_STATE_TABLE, SHAPE_POKE_CURSOR_TABLE, type SchedulableWorkflowReferenceLike, type ScheduleOutbox, type ScheduleOutboxEnvelope, type ScheduleOutboxRow, type ScheduledFunctionDoc, type SchedulerLike, type SchemaLike, type ScoredDocument, type SearchBackfillProgress, type SearchFilterBuilderLike, type SearchIndexDefinitionLike, type SearchScoredDocument, type SelectMatchingIdsOptions, type ServerDefaultContextLike, type SettingEntry, type SettingKind, type SettingsResult, ShapeDiffCache, type ShapePokeCursorRow, type ShapePokePart, type ShapeProbeCounters, type ShapeRow, type ShapeRowOp, type ShapeSubscriptionQuery, type ShardRankPageResult, ShardRunner, type ShardRunnerOptions, type ShardSiblingHost, type ShardSocketLike, type SocketAttachment, type SortDirection, type SourceClientLike, type SourceCursorLike, type SourceRefresh, type SqlConsoleResult, type SqlCursor, type SqlEngine, type SqlExec, type SqlLintResult, type StorageMetadata, type StorageReference, type StorageReferenceResult, type StorageRuleMetadata, type StorageRulesResult, type StudioFeaturesResult, type SubscriptionConnection, type SubscriptionEnvelope, type SubscriptionIdentity, type SubscriptionInfo, type SubscriptionQuery, type SubscriptionReadFootprint, type SubscriptionsResult, type SystemDatabaseReader, type SystemDoc, type SystemQuery, type SystemReaderOptions, type SystemReaderSchedulerLike, type SystemReaderStorageLike, type SystemTableName, type TableColumnsResult, type TableDefinitionLike, type TableIndexInfo, type TableIndexesResult, type TableInfo, type TablePage, type TableReaderLike, type TablesColumnsResult, type TablesIndexesResult, type TransactionHeadroom, TransactionHeadroomTracker, type TransactionLimits, type TransactionSqlLike, type TriggerContextLike, type TriggerDefinitionLike, type TriggerEventLike, type TriggerOpLike, type TriggerTimingLike, type TtlSweepSpec, UNVOUCHABLE_DEP, VECTOR_BACKFILL_MAX_PAGES, type ValidatorLike, type VectorBackfillProgress, WORKERD_SQLITE_LIMITS, type WhereFilter, type WhereInput, type WhereSqlStrategy, type WithInput, type WorkflowInstanceState, type WorkflowInstanceStatusResult, type WorkflowMetadata, type WorkflowsResult, type WriteEvent, type WriteHook, advanceClientWatermark, aggUpsertSql, aggregateSqlFunction, aggregateTableName, allocateCommitSeq, appendAuditEntry, appendCdcChange, appendStreamChunk, applyCdcChanges, applyOnDelete, applySelect, archiveCdcSegment, armRestore, assertFlatPredicate, assertNoExplicitUndefined, assertReadonly, assertShapeShardable, assertValidClientId, awaitWsDrain, backfillAggregateIndexes, backfillRankIndexes, backfillSearchIndexes, backfillSearchIndexesForTable, backfillVectorIndexes, bigintSqlKey, boundingBoxCenter, boundingBoxGeohashes, buildIndexRange, buildPokeFrames, buildReprojectionMigration, buildSeekBeforeWhere, buildSeekWhere, buildSettings, buildShapeDiff, bumpCdcEpoch, cdcArchiveRewound, cdcCanVouchFor, cdcForkedError, cdcSeqLeavingRows, cdcTouchesTables, cdcTrimmedError, claimStreamRun, clampPromotionThresholds, clearCapturedMail, clearMemoryTables, clearQueueMessages, coerceAggregateNumber, compactCdcDocs, compileWhereSql, computeRankPage, containsRelationPredicate, countLegacyRows, coveringGeohashes, createCompanionSync, createDependencyTracker, createFanoutCounters, createGlobalPollCounters, createIndexSql, createReadFootprint, createRelayLink, createReplicaLink, createShapeDiffCache, createShapeProbeCounters, createShardCtxDb, createSystemReader, cursorBelowRetainedFloor, decideDurableAttach, decodeBigintSqlKey, decodeCursor, decodeFloat64SqlKey, deferScheduleOutbox, deleteGlobalShapeSnapshot, deleteGlobalShapeSnapshotsForConnection, deleteShapePokeCursor, deleteShapePokeCursorsForConnection, deleteStreamRun, depKey, deriveRelationEdges, diffExternalSource, diffGlobalMembership, distinctValues, encodeAggregateKey, encodeCursor, encodeGeohash, encodePartitionKey, encodeRowsPatch, ensureAuditTable, ensureMailTable, envOptionalPositiveInt, envPositiveInt, equalityPinnedFields, exportShardRows, facetColumn, fanOutScalarCounts, findRelated, findStorageReferences, finishStreamRun, float64SqlKey, foldAggregateTally, forgetScheduleOutbox, ftsCompanionDdl, ftsPurgeDocument, ftsRowidMapName, ftsUnmappedPage, ftsWriteDocument, gateReplicaDispatch, geoTableName, globalShapeReadKey, groupUnmappedRows, guardWriter, handleReplicaControl, hasTrigger, haversineMeters, importShardRows, indexKeysForRow, isDevEnvironment, isFtsAvailable, isInternalTableName, isLossyBody, isMemoryTable, isPushableWhere, isRelationPredicate, isSoftDeleted, isSourceDue, isVacuousFilterClause, jsonPath, jsonPathSql, keysTouchRanges, liftSourceId, lintReadonlySql, listReactorStates, listTables, markUnvouchableReads, matchesRankStaticWhere, matchesStaticWhere, materializeExternalRows, materializeExternalRowsIncremental, memoryTableNames, mergeChangedKeys, mergeWhere, migrateCdcLog, migrateCdcMeta, migrateClientWatermark, migrateCommitSeq, migrateDurableStreams, migrateGlobalShapeSnapshot, migrateIdempotency, migrateReactorState, migrateScheduleOutbox, migrateSearchState, migrateShapePokeCursor, minCdcReplayableSeq, minCdcSeq, minShapePokeCursor, nextPromotionState, normalizeCountArgument, normalizeIdStructurally, normalizeOrderKeys, normalizeSourceDocument, normalizeSourceValue, param, parkScheduleOutbox, parseExportShardArgs, parseImportShardArgs, planAggregateLookup, pointInBoundingBox, probeScheduleOutbox, projectColumns, pullExternalSourceIncrementalTick, pullExternalSourceTick, qualifiedJsonPath, qualifiedJsonPathSql, quoteIdentifier, rankKeyFromDocument as rankKeyFromDoc, rankPivotConditionSql, rankTableName, reactiveCacheKey, reactorNeedsRun, readAggregateValue, readArchivedCdcChanges, readAuditLog, readBookmark, readCapturedMail, readCdcArchivedThrough, readCdcChangeKeys, readCdcChanges, readCdcCursor, readCdcEpoch, readClientWatermark, readCommitSeq, readDeployInfo, readDueScheduleOutbox, readExternalSourceBaseline, readGlobalShapeSnapshot, readIdempotent, readMigrationStatus, readQueueMessageById, readQueueMessages, readReactorState, readSchemaHistory, readSchemaVersion, readSearchBackfillState, readShapePokeCursor, readStreamChunks, readStreamRun, readTablePage, recordCapturedMail, recordChangedKeys, recordFanoutPass, recordGlobalPollPass, recordQueueMessages, recordScheduleOutbox, recordSchemaVersion, recordShapeProbePass, relationHooks, relayCountFor, renderSql, reprojectableFields, reprojectionMigrationId, reprojectionTables, resolveRankPartition, resolveRankSeekTuple, resolveRelationPredicates, resolveWith, rowToDocument, runDataMigration, runDrizzle, runExternalSourceTick, runReadonlySql, runRowValidators, runShardMigrations, runSocketPool, runSql, runTriggers, selectExpiredIds, selectExportTables, selectIndexForAggregate, selectIndexForCount, selectIndexForGroupBy, selectMatchingIds, selectShapeMembers, selectShapeRows, serializeSqlValue, serverInList, shapeRoutingKey, softDeleteScope, sortColumnName, sqliteInList, stableStringify, stableWireKey, stripReservedPatchFields, subscriptionFrames, subscriptionListDeltas, summarizeFanoutTopics, summarizeSubscriptions, tableColumns, tableFromDepKey, throwingScheduler, tiebreakDirectionFor, trimCdcChanges, trimIdempotent, trimScheduleOutbox, trimStreamRuns, tryRowToDocument, trySendFrame, unionAll, uniqueIndexFields, validateImportRow, whereFilter, whereOfFilter, writeCdcArchivedThrough, writeGlobalShapeSnapshot, writeIdempotent, writeReactorState, writeSearchBackfillState, writeShapePokeCursor, writeShapePokeCursors, writeTouchesMemo };
|
|
2518
|
+
export { ADMIN_FUNCTIONS, ADMIN_FUNCTION_PREFIX, AGGREGATE_SQL_FUNCTION, AGG_COUNT, AGG_KEY, AGG_VALUE, AUDIT_LOG_TABLE, type AdvisorProcedure, type AdvisorProceduresResult, type AdvisoriesResult, type AdvisoryFinding, type AggregateIndexDefinitionLike, type AggregateOp, type AggregateOptions, type AggregateResult, type AggregateTally, type AppendAuditEntry, type ApplyOnDeleteOptions, type AuditEntry, type AuditLogResult, BIGINT_KEY_DIGITS, type BroadcastDelta, CDC_LOG_TABLE, CDC_LOG_TABLE_SEQ_INDEX, CDC_META_TABLE, CLIENT_WATERMARK_TABLE, COMMIT_SEQ_FIELD, COMMIT_SEQ_TABLE, CURSOR_PREFIX, type CacheEntry, type CapturedMailRow, type CdcArchiveScope, type CdcChange, type CdcChangeKey, type ChangedKeys, type Clock, type ColumnMeta, type ColumnMetaLike, type CompanionSync, type CompanionSyncDeps, ConflictError, type ConflictKind, type CountArgs, CountRlsUnsupportedError, type CreateWorkflowInstanceResult, type CrossShardReadArgs, type CtxDbOptions, DATA_MIGRATION_STATE_TABLE, DEFAULT_FANOUT_TOPIC_LIMIT, DEFAULT_MAX_RELATION_KEYS, DEFAULT_MAX_RELAYS, DEFAULT_PROMOTION_THRESHOLDS, DEFAULT_TRANSACTION_LIMITS, DOC_COLUMN, type DataMigrationDocument, type DataMigrationLike, type DataMigrationTransform, type DatabaseWriterLike, type DependencyTracker, type DeployInfo, type DurableAttachDecision, type DurableStreamAttach, type DurableStreamRun, DurableStreamRunner, type DurableStreamSink, type ExportRow, type ExportShardAdminArgs, type ExportShardArgs, type ExternalSourceDiffResult, type ExternalSourceLike, FLAGS_FUNCTION_PREFIX, type FacetColumnOptions, type FacetColumnResult, type FacetValue, type FanOutBudget, type FanoutMetricsResult, type FanoutPathCounters, type FanoutTopicStat, type FieldOperators, type FilterClause, type FilterOperator, type FlagEvaluation, type FlagsResult, type FtsWriteOptions, type FunctionCallStat, type FunctionScanAttribution, type FunctionStatsResult, GEO_DEFAULT_PRECISION, GLOBAL_SHAPE_SNAPSHOT_TABLE, type GeoBoundingBox, type GeoFilterBuilderLike, type GeoIndexDefinitionLike, type GeoPoint, type GeoScoredDocument, type GlobalPollCounters, GlobalPollTick, type GroupByEntry, type GroupByOptions, type GuardableSchema$1 as GuardableSchema, IDEMPOTENCY_TABLE, type IdGenerator, type IdempotentRecord, type ImportError, type ImportShardAdminArgs, type ImportShardArgs, type ImportShardResult, type IncrementalMaterializeResult, type IndexDefinitionLike, type IndexKeyEntry, type IndexRangeBuilderLike, type KeyRange, type LifecycleDispatchInfo, type LifecycleEvent, MAIL_RETENTION, MAIL_TABLE, MAX_DURABLE_STREAM_BYTES, MAX_DURABLE_STREAM_CHUNKS, MAX_PAGE_SIZE, MAX_SQL_ROWS, type MaskColumnMetadata, type MaskPoliciesResult, type MaterializeResult, type MigrationDirection, type MigrationRunResult, type MigrationStatus, type MigrationStatusRow, type MutationDelta, type NestedWith, NotFoundError, NotUniqueError, type OnDeleteActionLike, type OrderByClause, type OrderByInput, type OrderKey, type OrderKeyConstraints, OwnerRelay, type OwnerRelayFrame, type PaginationOptions, type PitrBookmarkResult, type PitrRestoreArgs, type PitrRestoreResult, type PitrStorage, type PokeFrameMeta, type PromotionState, type PromotionThresholds, QUEUE_TABLE, type QueryArgs, type QueryPage, type QueueMessageOutcome, type QueueMessageRow, type QueueMetadata, type QueuesResult, RANK_TIEBREAK, REACTOR_STATE_TABLE, RELATED_DEFAULT_LIMIT, RELATED_DEPTH_DECAY, RELATED_MAX_DEPTH, RELATED_MAX_LIMIT, RELATION_EXISTS_KEY, RELATION_FUNCTION_PREFIX, REPROJECTION_MIGRATION_PREFIX, RLS_UNWRAP_SYMBOL, type RankBeforeOptions, type RankBeforeResult, type RankDirection, type RankIndexDefinitionLike, type RankOptions, type RankPage, type RankPageComputation, type RankPageDeps, type RankPageOptions, type RankPageRow, type RankPageRowKey, type RankResult, type RankSortKeyLike, ReactiveCache, type ReactiveCacheOptions, type ReactorDispatchResult, type ReactorMetadata, type ReactorState, type ReactorStats, type ReactorsResult, type ReadFootprint, type ReadHook, type ReadTablePageOptions, type RecordMailInput, type RecordQueueMessageInput, type RelatedDirection, type RelatedNode, type RelatedOptions, type RelatedPage, type RelatedStart, type RelatedStartReference, type RelationDefinitionLike, type RelationEdge, type RelationExistsMarker, type RelationGraphReader, type RelayAttach, type RelayDetach, type RelayFrame, type RelayHost, RelayMember, type RelayPokeDelivery, type RelayShapePoke, type RelayShapeSeed, type RelayShapeSubscribe, type RelayShapeUnsubscribe, type RenderedSql, type ReplicaFollowerHost, type ReplicaOwnerHost, type ReplicaReadiness, type ResolveRelationPredicatesOptions, type ResolveWithOptions, type ResolveWithResult, type ResolvedShape, type RestrictableQueryOptions, type RlsPoliciesResult, type RlsPolicyMetadata, RlsRequiredError, type RlsRoleMetadata, type RpcRequest, type RunDataMigrationOptions, type RunTriggersOptions, SCAN_DEP, SCHEDULE_OUTBOX_TABLE, SCHEMA_HISTORY_MAX_VERSIONS, SEARCH_STATE_TABLE, SHAPE_POKE_CURSOR_TABLE, type SchedulableWorkflowReferenceLike, type ScheduleOutbox, type ScheduleOutboxEnvelope, type ScheduleOutboxRow, type ScheduledFunctionDoc, type SchedulerLike, type SchemaLike, type ScoredDocument, type SearchBackfillProgress, type SearchFilterBuilderLike, type SearchIndexDefinitionLike, type SearchScoredDocument, type SelectMatchingIdsOptions, type ServerDefaultContextLike, type SettingEntry, type SettingKind, type SettingsResult, ShapeDiffCache, type ShapePokeCursorRow, type ShapePokePart, type ShapeProbeCounters, type ShapeRow, type ShapeRowOp, type ShapeSubscriptionQuery, type ShardRankPageResult, ShardRunner, type ShardRunnerOptions, type ShardSiblingHost, type ShardSocketLike, type SocketAttachment, type SortDirection, type SourceClientLike, type SourceCursorLike, type SourceRefresh, type SqlConsoleResult, type SqlCursor, type SqlEngine, type SqlExec, type SqlLintResult, type StorageMetadata, type StorageReference, type StorageReferenceResult, type StorageRuleMetadata, type StorageRulesResult, type StudioFeaturesResult, type SubscriptionConnection, type SubscriptionEnvelope, type SubscriptionIdentity, type SubscriptionInfo, type SubscriptionQuery, type SubscriptionReadFootprint, type SubscriptionsResult, type SystemDatabaseReader, type SystemDoc, type SystemQuery, type SystemReaderOptions, type SystemReaderSchedulerLike, type SystemReaderStorageLike, type SystemTableName, type TableColumnsResult, type TableDefinitionLike, type TableIndexInfo, type TableIndexesResult, type TableInfo, type TablePage, type TableReaderLike, type TablesColumnsResult, type TablesIndexesResult, type TransactionHeadroom, TransactionHeadroomTracker, type TransactionLimits, type TransactionSqlLike, type TriggerContextLike, type TriggerDefinitionLike, type TriggerEventLike, type TriggerOpLike, type TriggerTimingLike, type TtlSweepSpec, UNVOUCHABLE_DEP, VECTOR_BACKFILL_MAX_PAGES, type ValidatorLike, type VectorBackfillProgress, WORKERD_SQLITE_LIMITS, type WhereFilter, type WhereInput, type WhereSqlStrategy, type WithInput, type WorkflowInstanceState, type WorkflowInstanceStatusResult, type WorkflowMetadata, type WorkflowsResult, type WriteEvent, type WriteHook, advanceClientWatermark, aggUpsertSql, aggregateSqlFunction, aggregateTableName, allocateCommitSeq, appendAuditEntry, appendCdcChange, appendStreamChunk, applyCdcChanges, applyOnDelete, applySelect, archiveCdcSegment, armRestore, assertFlatPredicate, assertNoExplicitUndefined, assertReadonly, assertShapeShardable, assertValidClientId, awaitWsDrain, backfillAggregateIndexes, backfillRankIndexes, backfillSearchIndexes, backfillSearchIndexesForTable, backfillVectorIndexes, bigintSqlKey, boundingBoxCenter, boundingBoxGeohashes, buildIndexRange, buildPokeFrames, buildReprojectionMigration, buildSeekBeforeWhere, buildSeekWhere, buildSettings, buildShapeDiff, bumpCdcEpoch, cdcArchiveRewound, cdcCanVouchFor, cdcForkedError, cdcSeqLeavingRows, cdcTouchesTables, cdcTrimmedError, claimStreamRun, clampPromotionThresholds, clearCapturedMail, clearMemoryTables, clearQueueMessages, coerceAggregateNumber, compactCdcDocs, compileWhereSql, computeRankPage, containsRelationPredicate, countLegacyRows, coveringGeohashes, createCompanionSync, createDependencyTracker, createFanoutCounters, createGlobalPollCounters, createIndexSql, createReadFootprint, createRelayLink, createReplicaLink, createShapeDiffCache, createShapeProbeCounters, createShardCtxDb, createSystemReader, cursorBelowRetainedFloor, decideDurableAttach, decodeBigintSqlKey, decodeCursor, decodeFloat64SqlKey, deferScheduleOutbox, deleteGlobalShapeSnapshot, deleteGlobalShapeSnapshotsForConnection, deleteShapePokeCursor, deleteShapePokeCursorsForConnection, deleteStreamRun, depKey, deriveRelationEdges, diffExternalSource, diffGlobalMembership, distinctValues, encodeAggregateKey, encodeCursor, encodeGeohash, encodePartitionKey, encodeRowsPatch, ensureAuditTable, ensureMailTable, envOptionalPositiveInt, envPositiveInt, equalityPinnedFields, exportShardRows, facetColumn, fanOutScalarCounts, findRelated, findStorageReferences, finishStreamRun, float64SqlKey, foldAggregateTally, forgetScheduleOutbox, ftsCompanionDdl, ftsPurgeDocument, ftsRowidMapName, ftsUnmappedPage, ftsWriteDocument, gateReplicaDispatch, geoTableName, globalShapeReadKey, groupUnmappedRows, guardWriter, handleReplicaControl, hasTrigger, haversineMeters, importShardRows, indexKeysForRow, isDevEnvironment, isFtsAvailable, isInternalTableName, isLossyBody, isMemoryTable, isPushableWhere, isRelationPredicate, isSoftDeleted, isSourceDue, isVacuousFilterClause, jsonPath, jsonPathSql, keysTouchRanges, liftSourceId, lintReadonlySql, listReactorStates, listTables, markUnvouchableReads, matchesRankStaticWhere, matchesStaticWhere, materializeExternalRows, materializeExternalRowsIncremental, memoryTableNames, mergeChangedKeys, mergeWhere, migrateCdcLog, migrateCdcMeta, migrateClientWatermark, migrateCommitSeq, migrateDurableStreams, migrateGlobalShapeSnapshot, migrateIdempotency, migrateReactorState, migrateScheduleOutbox, migrateSearchState, migrateShapePokeCursor, minCdcReplayableSeq, minCdcSeq, minShapePokeCursor, nextPromotionState, normalizeCountArgument, normalizeIdStructurally, normalizeOrderKeys, normalizeSourceDocument, normalizeSourceValue, param, parkScheduleOutbox, parseExportShardArgs, parseImportShardArgs, planAggregateLookup, pointInBoundingBox, probeScheduleOutbox, projectColumns, pullExternalSourceIncrementalTick, pullExternalSourceTick, qualifiedJsonPath, qualifiedJsonPathSql, quoteIdentifier, rankKeyFromDocument as rankKeyFromDoc, rankPivotConditionSql, rankTableName, reactiveCacheKey, reactorNeedsRun, readAggregateValue, readArchivedCdcChanges, readAuditLog, readBookmark, readCapturedMail, readCdcArchivedThrough, readCdcChangeKeys, readCdcChanges, readCdcCursor, readCdcEpoch, readClientWatermark, readCommitSeq, readDeployInfo, readDueScheduleOutbox, readExternalSourceBaseline, readGlobalShapeSnapshot, readIdempotent, readMigrationStatus, readQueueMessageById, readQueueMessages, readReactorState, readSchemaHistory, readSchemaVersion, readSearchBackfillState, readShapePokeCursor, readStreamChunks, readStreamRun, readTablePage, recordCapturedMail, recordChangedKeys, recordFanoutPass, recordGlobalPollPass, recordQueueMessages, recordScheduleOutbox, recordSchemaVersion, recordShapeProbePass, relationHooks, relayCountFor, renderSql, reprojectableFields, reprojectionMigrationId, reprojectionTables, resolveRankPartition, resolveRankSeekTuple, resolveRelationPredicates, resolveWith, rowToDocument, runDataMigration, runDrizzle, runExternalSourceTick, runReadonlySql, runRowValidators, runShardMigrations, runSocketPool, runSql, runTriggers, selectExpiredIds, selectExportTables, selectIndexForAggregate, selectIndexForCount, selectIndexForGroupBy, selectMatchingIds, selectShapeMembers, selectShapeRows, serializeSqlValue, serverInList, shapeRoutingKey, softDeleteScope, sortColumnName, sqliteInList, stableStringify, stableWireKey, stripReservedPatchFields, subscriptionFrames, subscriptionListDeltas, summarizeFanoutTopics, summarizeSubscriptions, tableColumns, tableFromDepKey, throwingScheduler, tiebreakDirectionFor, trimCdcChanges, trimIdempotent, trimScheduleOutbox, trimStreamRuns, tryRowToDocument, trySendFrame, unionAll, uniqueIndexFields, validateImportRow, whereFilter, whereOfFilter, writeCdcArchivedThrough, writeGlobalShapeSnapshot, writeIdempotent, writeReactorState, writeSearchBackfillState, writeShapePokeCursor, writeShapePokeCursors, writeTouchesMemo };
|
package/dist/index.mjs
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{exportShardRows as o,importShardRows as a,parseExportShardArgs as t,parseImportShardArgs as i,selectExportTables as n,validateImportRow as s}from"./packem_shared/exportShardRows-CTDgQEF8.mjs";import{AGGREGATE_SQL_FUNCTION as d,aggregateSqlFunction as c,matchesStaticWhere as m,normalizeCountArgument as p,throwingScheduler as S}from"./packem_shared/AGGREGATE_SQL_FUNCTION-DDEoMnJR.mjs";import{aggregateTableName as f,coerceAggregateNumber as E,encodeAggregateKey as h,foldAggregateTally as x,readAggregateValue as T}from"./packem_shared/aggregateTableName-C7o-gpms.mjs";import{CountRlsUnsupportedError as C,mergeWhere as A,planAggregateLookup as g,selectIndexForAggregate as _,selectIndexForCount as I,selectIndexForGroupBy as b}from"./packem_shared/CountRlsUnsupportedError-BvsDqfO2.mjs";import{AUDIT_LOG_TABLE as D,appendAuditEntry as P,ensureAuditTable as O,readAuditLog as M}from"./packem_shared/AUDIT_LOG_TABLE-CZNxCRLv.mjs";import{NotUniqueError as y,assertNoExplicitUndefined as N,assertValidClientId as k,createShardCtxDb as B,normalizeIdStructurally as U,stripReservedPatchFields as G}from"./packem_shared/NotUniqueError-CYBVrJib.mjs";import{backfillAggregateIndexes as w,backfillRankIndexes as K,backfillSearchIndexes as v,backfillSearchIndexesForTable as W}from"./packem_shared/backfillAggregateIndexes-D5q_pbdY.mjs";import{CDC_LOG_TABLE as H,CDC_LOG_TABLE_SEQ_INDEX as V,CDC_META_TABLE as z,appendCdcChange as Q,applyCdcChanges as Y,bumpCdcEpoch as j,cdcCanVouchFor as J,cdcForkedError as Z,cdcSeqLeavingRows as $,cdcTouchesTables as ee,cdcTrimmedError as re,compactCdcDocs as oe,cursorBelowRetainedFloor as ae,migrateCdcLog as te,migrateCdcMeta as ie,minCdcReplayableSeq as ne,minCdcSeq as se,readCdcChangeKeys as le,readCdcChanges as de,readCdcCursor as ce,readCdcEpoch as me,trimCdcChanges as pe}from"./packem_shared/CDC_LOG_TABLE-QaBxSIZM.mjs";import{archiveCdcSegment as ue,cdcArchiveRewound as fe,readArchivedCdcChanges as Ee,readCdcArchivedThrough as he,writeCdcArchivedThrough as xe}from"./packem_shared/archiveCdcSegment-BON69Nug.mjs";import{CLIENT_WATERMARK_TABLE as Re,advanceClientWatermark as Ce,migrateClientWatermark as Ae,readClientWatermark as ge}from"./packem_shared/CLIENT_WATERMARK_TABLE-vLjfNhBR.mjs";import{COMMIT_SEQ_FIELD as Ie,COMMIT_SEQ_TABLE as be,allocateCommitSeq as Le,migrateCommitSeq as De,readCommitSeq as Pe}from"./packem_shared/COMMIT_SEQ_FIELD-BY_vc9bw.mjs";import{createCompanionSync as Me}from"./packem_shared/createCompanionSync-BpE0xoMp.mjs";import{GLOBAL_SHAPE_SNAPSHOT_TABLE as ye,deleteGlobalShapeSnapshot as Ne,deleteGlobalShapeSnapshotsForConnection as ke,migrateGlobalShapeSnapshot as Be,readGlobalShapeSnapshot as Ue,writeGlobalShapeSnapshot as Ge}from"./packem_shared/GLOBAL_SHAPE_SNAPSHOT_TABLE-pMxZ-obU.mjs";import{IDEMPOTENCY_TABLE as we,migrateIdempotency as Ke,readIdempotent as ve,trimIdempotent as We,writeIdempotent as Xe}from"./packem_shared/IDEMPOTENCY_TABLE-AOJCuq5U.mjs";import{clearMemoryTables as Ve,isMemoryTable as ze,memoryTableNames as Qe}from"./packem_shared/clearMemoryTables-CogAvVHR.mjs";import{computeRankPage as je,resolveRankSeekTuple as Je}from"./packem_shared/computeRankPage-BosAhREj.mjs";import{SCHEDULE_OUTBOX_TABLE as $e,deferScheduleOutbox as er,forgetScheduleOutbox as rr,migrateScheduleOutbox as or,parkScheduleOutbox as ar,probeScheduleOutbox as tr,readDueScheduleOutbox as ir,recordScheduleOutbox as nr,trimScheduleOutbox as sr}from"./packem_shared/SCHEDULE_OUTBOX_TABLE-CgLvGxpY.mjs";import{S as dr,m as cr,r as mr,w as pr}from"./packem_shared/ctx-db-search-state-DVCp4JQf.mjs";import{SHAPE_POKE_CURSOR_TABLE as ur,deleteShapePokeCursor as fr,deleteShapePokeCursorsForConnection as Er,migrateShapePokeCursor as hr,minShapePokeCursor as xr,readShapePokeCursor as Tr,writeShapePokeCursor as Rr,writeShapePokeCursors as Cr}from"./packem_shared/SHAPE_POKE_CURSOR_TABLE-cn0stGAL.mjs";import{selectShapeMembers as gr,selectShapeRows as _r}from"./packem_shared/selectShapeMembers-BXhvEt4X.mjs";import{DATA_MIGRATION_STATE_TABLE as br,readMigrationStatus as Lr,runDataMigration as Dr}from"./packem_shared/DATA_MIGRATION_STATE_TABLE-BS6X-_Uu.mjs";import{SCAN_DEP as Or,createDependencyTracker as Mr,depKey as Fr,tableFromDepKey as yr}from"./packem_shared/SCAN_DEP-D7qE3iUe.mjs";import{runDrizzle as kr,runSql as Br}from"./packem_shared/runDrizzle-Du5HLitO.mjs";import{A as Gr,a as qr,b as wr,D as Kr,c as vr,d as Wr,g as Xr,i as Hr,j as Vr,e as zr,q as Qr,f as Yr,r as jr,t as Jr,h as Zr}from"./packem_shared/do-sql-BEFrJUds.mjs";import{WORKERD_SQLITE_LIMITS as eo,param as ro,renderSql as oo,sqliteInList as ao,unionAll as to}from"./packem_shared/WORKERD_SQLITE_LIMITS-DBH23L_S.mjs";import{appendStreamChunk as no,claimStreamRun as so,deleteStreamRun as lo,finishStreamRun as co,migrateDurableStreams as mo,readStreamChunks as po,readStreamRun as So,trimStreamRuns as uo}from"./packem_shared/appendStreamChunk-y5mkpRdi.mjs";import{DurableStreamRunner as Eo,MAX_DURABLE_STREAM_BYTES as ho,MAX_DURABLE_STREAM_CHUNKS as xo,decideDurableAttach as To}from"./packem_shared/DurableStreamRunner-C4SbxTDz.mjs";import{envOptionalPositiveInt as Co,envPositiveInt as Ao}from"./packem_shared/envOptionalPositiveInt-D2pY-c64.mjs";import{diffExternalSource as _o}from"./packem_shared/diffExternalSource-DgDJhslq.mjs";import{liftSourceId as bo,normalizeSourceDocument as Lo,normalizeSourceValue as Do}from"./packem_shared/liftSourceId-CA3ENhXj.mjs";import{materializeExternalRows as Oo,materializeExternalRowsIncremental as Mo,readExternalSourceBaseline as Fo,runExternalSourceTick as yo}from"./packem_shared/materializeExternalRows-DhINQHwd.mjs";import{isSoftDeleted as ko,isSourceDue as Bo,pullExternalSourceIncrementalTick as Uo,pullExternalSourceTick as Go}from"./packem_shared/isSoftDeleted-sGRSPPQq.mjs";import{f as wo,a as Ko,b as vo,c as Wo,d as Xo,g as Ho}from"./packem_shared/fts-companion-pUdD6kF-.mjs";import{GEO_DEFAULT_PRECISION as zo,boundingBoxCenter as Qo,boundingBoxGeohashes as Yo,coveringGeohashes as jo,encodeGeohash as Jo,haversineMeters as Zo,pointInBoundingBox as $o}from"./packem_shared/GEO_DEFAULT_PRECISION-CqpQZ-J_.mjs";import{default as ra}from"./packem_shared/GlobalPollTick-BNK4o-XT.mjs";import{ADMIN_FUNCTIONS as aa,ADMIN_FUNCTION_PREFIX as ta,DEFAULT_FANOUT_TOPIC_LIMIT as ia,FLAGS_FUNCTION_PREFIX as na,MAX_PAGE_SIZE as sa,RELATION_FUNCTION_PREFIX as la,createFanoutCounters as da,createGlobalPollCounters as ca,createShapeProbeCounters as ma,facetColumn as pa,findStorageReferences as Sa,isVacuousFilterClause as ua,listTables as fa,readTablePage as Ea,recordFanoutPass as ha,recordGlobalPollPass as xa,recordShapeProbePass as Ta,selectMatchingIds as Ra,summarizeFanoutTopics as Ca,summarizeSubscriptions as Aa}from"./packem_shared/ADMIN_FUNCTIONS-D5mzmLFo.mjs";import{MAIL_RETENTION as _a,MAIL_TABLE as Ia,clearCapturedMail as ba,ensureMailTable as La,readCapturedMail as Da,recordCapturedMail as Pa}from"./packem_shared/MAIL_RETENTION-BxAGL3hK.mjs";import{NotFoundError as Ma}from"./packem_shared/NotFoundError-BhF7FeFr.mjs";import{armRestore as ya,readBookmark as Na}from"./packem_shared/armRestore-Bu1_8SUa.mjs";import{CURSOR_PREFIX as Ba,applySelect as Ua,buildSeekBeforeWhere as Ga,buildSeekWhere as qa,decodeCursor as wa,encodeCursor as Ka,equalityPinnedFields as va,normalizeOrderKeys as Wa,softDeleteScope as Xa,tiebreakDirectionFor as Ha,uniqueIndexFields as Va}from"./packem_shared/CURSOR_PREFIX-Bn8SFoGd.mjs";import{QUEUE_TABLE as Qa,clearQueueMessages as Ya,isLossyBody as ja,readQueueMessageById as Ja,readQueueMessages as Za,recordQueueMessages as $a}from"./packem_shared/QUEUE_TABLE-DKANxmEZ.mjs";import{RANK_TIEBREAK as rt,encodePartitionKey as ot,matchesRankStaticWhere as at,rankKeyFromDoc as tt,rankPivotConditionSql as it,rankTableName as nt,resolveRankPartition as st,sortColumnName as lt}from"./packem_shared/RANK_TIEBREAK-B0_x8iev.mjs";import{ReactiveCache as ct,reactiveCacheKey as mt}from"./packem_shared/ReactiveCache-D8ccaO6f.mjs";import{REACTOR_STATE_TABLE as St,listReactorStates as ut,migrateReactorState as ft,reactorNeedsRun as Et,readReactorState as ht,writeReactorState as xt}from"./packem_shared/REACTOR_STATE_TABLE-B8IehLv8.mjs";import{UNVOUCHABLE_DEP as Rt,createReadFootprint as Ct,markUnvouchableReads as At}from"./packem_shared/UNVOUCHABLE_DEP-C68htACn.mjs";import{buildIndexRange as _t,indexKeysForRow as It,keysTouchRanges as bt}from"./packem_shared/buildIndexRange-6nIZDf4m.mjs";import{isPushableWhere as Dt,whereFilter as Pt,whereOfFilter as Ot}from"./packem_shared/isPushableWhere-BeYAOjUb.mjs";import{RELATED_DEFAULT_LIMIT as Ft,RELATED_DEPTH_DECAY as yt,RELATED_MAX_DEPTH as Nt,RELATED_MAX_LIMIT as kt,deriveRelationEdges as Bt,findRelated as Ut}from"./packem_shared/RELATED_DEFAULT_LIMIT-B9PH28Pn.mjs";import{DEFAULT_MAX_RELATION_KEYS as qt,assertFlatPredicate as wt,assertShapeShardable as Kt,containsRelationPredicate as vt,isRelationPredicate as Wt,resolveRelationPredicates as Xt}from"./packem_shared/DEFAULT_MAX_RELATION_KEYS-D_Urjl_L.mjs";import{applyOnDelete as Vt,distinctValues as zt,fanOutScalarCounts as Qt,relationHooks as Yt,resolveWith as jt,runRowValidators as Jt}from"./packem_shared/applyOnDelete-7JZ4vR9r.mjs";import{DEFAULT_PROMOTION_THRESHOLDS as $t,clampPromotionThresholds as ei,nextPromotionState as ri,relayCountFor as oi,shapeRoutingKey as ai}from"./packem_shared/DEFAULT_PROMOTION_THRESHOLDS-Bfx7KakS.mjs";import{DEFAULT_MAX_RELAYS as ii,OwnerRelay as ni,RelayMember as si,createRelayLink as li}from"./packem_shared/DEFAULT_MAX_RELAYS-DnAAv8zm.mjs";import{createReplicaLink as ci,gateReplicaDispatch as mi,handleReplicaControl as pi}from"./packem_shared/createReplicaLink-Z82FMxvY.mjs";import{buildReprojectionMigration as ui,countLegacyRows as fi,reprojectableFields as Ei,reprojectionTables as hi}from"./packem_shared/buildReprojectionMigration-IMrfRdvU.mjs";import{RLS_UNWRAP_SYMBOL as Ti,RlsRequiredError as Ri,guardWriter as Ci}from"./packem_shared/RLS_UNWRAP_SYMBOL-BwwTbz3Q.mjs";import{SCHEMA_HISTORY_MAX_VERSIONS as gi,readSchemaHistory as _i,readSchemaVersion as Ii,recordSchemaVersion as bi}from"./packem_shared/SCHEMA_HISTORY_MAX_VERSIONS-BMcUIqBY.mjs";import{serializeSqlValue as Di}from"./packem_shared/serializeSqlValue-BbZ5hKM7.mjs";import{buildSettings as Oi,isDevEnvironment as Mi,readDeployInfo as Fi}from"./packem_shared/buildSettings-DC3VeQ0H.mjs";import{buildShapeDiff as Ni}from"./packem_shared/buildShapeDiff-D-J_GmC1.mjs";import{ShapeDiffCache as Bi,createShapeDiffCache as Ui,globalShapeReadKey as Gi}from"./packem_shared/ShapeDiffCache-gdaILV5E.mjs";import{buildPokeFrames as wi,diffGlobalMembership as Ki,encodeRowsPatch as vi,projectColumns as Wi}from"./packem_shared/buildPokeFrames-BBE6J91z.mjs";import{ShardRunner as Hi}from"./packem_shared/ShardRunner-CrveaPId.mjs";import{runSocketPool as zi}from"./packem_shared/runSocketPool-CZJ2X9cF.mjs";import{MAX_SQL_ROWS as Yi,assertReadonly as ji,lintReadonlySql as Ji,runReadonlySql as Zi}from"./packem_shared/MAX_SQL_ROWS-Dh_Ty0Zo.mjs";import{BIGINT_KEY_DIGITS as en,bigintSqlKey as rn,decodeBigintSqlKey as on,decodeFloat64SqlKey as an,float64SqlKey as tn}from"./packem_shared/BIGINT_KEY_DIGITS-C9a7Ix7k.mjs";import{awaitWsDrain as sn,subscriptionFrames as ln,subscriptionListDeltas as dn,trySendFrame as cn}from"./packem_shared/awaitWsDrain-apizgmKY.mjs";import{mergeChangedKeys as pn,recordChangedKeys as Sn,writeTouchesMemo as un}from"./packem_shared/mergeChangedKeys-DH9RAARR.mjs";import{createSystemReader as En}from"./packem_shared/createSystemReader-DcDLFfC-.mjs";import{ConflictError as xn}from"./packem_shared/ConflictError-C8GtJmjS.mjs";import{DEFAULT_TRANSACTION_LIMITS as Rn,TransactionHeadroomTracker as Cn}from"./packem_shared/DEFAULT_TRANSACTION_LIMITS-DiR5z5EX.mjs";import{hasTrigger as gn,runTriggers as _n}from"./packem_shared/hasTrigger-CjlwI4le.mjs";import{selectExpiredIds as bn}from"./packem_shared/selectExpiredIds-DQg6v5Uf.mjs";import{VECTOR_BACKFILL_MAX_PAGES as Dn,backfillVectorIndexes as Pn}from"./packem_shared/VECTOR_BACKFILL_MAX_PAGES-jQVe2NO6.mjs";import{c as Mn,s as Fn}from"./packem_shared/where-sql-DFs8Zw7-.mjs";import{RELATION_EXISTS_KEY as Nn}from"./packem_shared/RELATION_EXISTS_KEY-CFUhnZSZ.mjs";import{REPROJECTION_MIGRATION_PREFIX as Bn,reprojectionMigrationId as Un}from"./packem_shared/REPROJECTION_MIGRATION_PREFIX-Czcb6_mO.mjs";import{isInternalTableName as qn}from"./packem_shared/isInternalTableName-BoljO2tP.mjs";import{quoteIdentifier as Kn}from"./packem_shared/quoteIdentifier-CObIFRhb.mjs";import{runShardMigrations as Wn}from"./packem_shared/runShardMigrations-DvjE3byP.mjs";import{stableStringify as Hn}from"./packem_shared/stableStringify-DibjylKD.mjs";import{stableWireKey as zn}from"./packem_shared/stableWireKey-D2US4k_J.mjs";export{aa as ADMIN_FUNCTIONS,ta as ADMIN_FUNCTION_PREFIX,d as AGGREGATE_SQL_FUNCTION,Gr as AGG_COUNT,qr as AGG_KEY,wr as AGG_VALUE,D as AUDIT_LOG_TABLE,en as BIGINT_KEY_DIGITS,H as CDC_LOG_TABLE,V as CDC_LOG_TABLE_SEQ_INDEX,z as CDC_META_TABLE,Re as CLIENT_WATERMARK_TABLE,Ie as COMMIT_SEQ_FIELD,be as COMMIT_SEQ_TABLE,Ba as CURSOR_PREFIX,xn as ConflictError,C as CountRlsUnsupportedError,br as DATA_MIGRATION_STATE_TABLE,ia as DEFAULT_FANOUT_TOPIC_LIMIT,qt as DEFAULT_MAX_RELATION_KEYS,ii as DEFAULT_MAX_RELAYS,$t as DEFAULT_PROMOTION_THRESHOLDS,Rn as DEFAULT_TRANSACTION_LIMITS,Kr as DOC_COLUMN,Eo as DurableStreamRunner,na as FLAGS_FUNCTION_PREFIX,zo as GEO_DEFAULT_PRECISION,ye as GLOBAL_SHAPE_SNAPSHOT_TABLE,ra as GlobalPollTick,we as IDEMPOTENCY_TABLE,_a as MAIL_RETENTION,Ia as MAIL_TABLE,ho as MAX_DURABLE_STREAM_BYTES,xo as MAX_DURABLE_STREAM_CHUNKS,sa as MAX_PAGE_SIZE,Yi as MAX_SQL_ROWS,Ma as NotFoundError,y as NotUniqueError,ni as OwnerRelay,Qa as QUEUE_TABLE,rt as RANK_TIEBREAK,St as REACTOR_STATE_TABLE,Ft as RELATED_DEFAULT_LIMIT,yt as RELATED_DEPTH_DECAY,Nt as RELATED_MAX_DEPTH,kt as RELATED_MAX_LIMIT,Nn as RELATION_EXISTS_KEY,la as RELATION_FUNCTION_PREFIX,Bn as REPROJECTION_MIGRATION_PREFIX,Ti as RLS_UNWRAP_SYMBOL,ct as ReactiveCache,si as RelayMember,Ri as RlsRequiredError,Or as SCAN_DEP,$e as SCHEDULE_OUTBOX_TABLE,gi as SCHEMA_HISTORY_MAX_VERSIONS,dr as SEARCH_STATE_TABLE,ur as SHAPE_POKE_CURSOR_TABLE,Bi as ShapeDiffCache,Hi as ShardRunner,Cn as TransactionHeadroomTracker,Rt as UNVOUCHABLE_DEP,Dn as VECTOR_BACKFILL_MAX_PAGES,eo as WORKERD_SQLITE_LIMITS,Ce as advanceClientWatermark,vr as aggUpsertSql,c as aggregateSqlFunction,f as aggregateTableName,Le as allocateCommitSeq,P as appendAuditEntry,Q as appendCdcChange,no as appendStreamChunk,Y as applyCdcChanges,Vt as applyOnDelete,Ua as applySelect,ue as archiveCdcSegment,ya as armRestore,wt as assertFlatPredicate,N as assertNoExplicitUndefined,ji as assertReadonly,Kt as assertShapeShardable,k as assertValidClientId,sn as awaitWsDrain,w as backfillAggregateIndexes,K as backfillRankIndexes,v as backfillSearchIndexes,W as backfillSearchIndexesForTable,Pn as backfillVectorIndexes,rn as bigintSqlKey,Qo as boundingBoxCenter,Yo as boundingBoxGeohashes,_t as buildIndexRange,wi as buildPokeFrames,ui as buildReprojectionMigration,Ga as buildSeekBeforeWhere,qa as buildSeekWhere,Oi as buildSettings,Ni as buildShapeDiff,j as bumpCdcEpoch,fe as cdcArchiveRewound,J as cdcCanVouchFor,Z as cdcForkedError,$ as cdcSeqLeavingRows,ee as cdcTouchesTables,re as cdcTrimmedError,so as claimStreamRun,ei as clampPromotionThresholds,ba as clearCapturedMail,Ve as clearMemoryTables,Ya as clearQueueMessages,E as coerceAggregateNumber,oe as compactCdcDocs,Mn as compileWhereSql,je as computeRankPage,vt as containsRelationPredicate,fi as countLegacyRows,jo as coveringGeohashes,Me as createCompanionSync,Mr as createDependencyTracker,da as createFanoutCounters,ca as createGlobalPollCounters,Wr as createIndexSql,Ct as createReadFootprint,li as createRelayLink,ci as createReplicaLink,Ui as createShapeDiffCache,ma as createShapeProbeCounters,B as createShardCtxDb,En as createSystemReader,ae as cursorBelowRetainedFloor,To as decideDurableAttach,on as decodeBigintSqlKey,wa as decodeCursor,an as decodeFloat64SqlKey,er as deferScheduleOutbox,Ne as deleteGlobalShapeSnapshot,ke as deleteGlobalShapeSnapshotsForConnection,fr as deleteShapePokeCursor,Er as deleteShapePokeCursorsForConnection,lo as deleteStreamRun,Fr as depKey,Bt as deriveRelationEdges,_o as diffExternalSource,Ki as diffGlobalMembership,zt as distinctValues,h as encodeAggregateKey,Ka as encodeCursor,Jo as encodeGeohash,ot as encodePartitionKey,vi as encodeRowsPatch,O as ensureAuditTable,La as ensureMailTable,Co as envOptionalPositiveInt,Ao as envPositiveInt,va as equalityPinnedFields,o as exportShardRows,pa as facetColumn,Qt as fanOutScalarCounts,Ut as findRelated,Sa as findStorageReferences,co as finishStreamRun,tn as float64SqlKey,x as foldAggregateTally,rr as forgetScheduleOutbox,wo as ftsCompanionDdl,Ko as ftsPurgeDocument,vo as ftsRowidMapName,Wo as ftsUnmappedPage,Xo as ftsWriteDocument,mi as gateReplicaDispatch,Xr as geoTableName,Gi as globalShapeReadKey,Ho as groupUnmappedRows,Ci as guardWriter,pi as handleReplicaControl,gn as hasTrigger,Zo as haversineMeters,a as importShardRows,It as indexKeysForRow,Mi as isDevEnvironment,Hr as isFtsAvailable,qn as isInternalTableName,ja as isLossyBody,ze as isMemoryTable,Dt as isPushableWhere,Wt as isRelationPredicate,ko as isSoftDeleted,Bo as isSourceDue,ua as isVacuousFilterClause,Vr as jsonPath,zr as jsonPathSql,bt as keysTouchRanges,bo as liftSourceId,Ji as lintReadonlySql,ut as listReactorStates,fa as listTables,At as markUnvouchableReads,at as matchesRankStaticWhere,m as matchesStaticWhere,Oo as materializeExternalRows,Mo as materializeExternalRowsIncremental,Qe as memoryTableNames,pn as mergeChangedKeys,A as mergeWhere,te as migrateCdcLog,ie as migrateCdcMeta,Ae as migrateClientWatermark,De as migrateCommitSeq,mo as migrateDurableStreams,Be as migrateGlobalShapeSnapshot,Ke as migrateIdempotency,ft as migrateReactorState,or as migrateScheduleOutbox,cr as migrateSearchState,hr as migrateShapePokeCursor,ne as minCdcReplayableSeq,se as minCdcSeq,xr as minShapePokeCursor,ri as nextPromotionState,p as normalizeCountArgument,U as normalizeIdStructurally,Wa as normalizeOrderKeys,Lo as normalizeSourceDocument,Do as normalizeSourceValue,ro as param,ar as parkScheduleOutbox,t as parseExportShardArgs,i as parseImportShardArgs,g as planAggregateLookup,$o as pointInBoundingBox,tr as probeScheduleOutbox,Wi as projectColumns,Uo as pullExternalSourceIncrementalTick,Go as pullExternalSourceTick,Qr as qualifiedJsonPath,Yr as qualifiedJsonPathSql,Kn as quoteIdentifier,tt as rankKeyFromDoc,it as rankPivotConditionSql,nt as rankTableName,mt as reactiveCacheKey,Et as reactorNeedsRun,T as readAggregateValue,Ee as readArchivedCdcChanges,M as readAuditLog,Na as readBookmark,Da as readCapturedMail,he as readCdcArchivedThrough,le as readCdcChangeKeys,de as readCdcChanges,ce as readCdcCursor,me as readCdcEpoch,ge as readClientWatermark,Pe as readCommitSeq,Fi as readDeployInfo,ir as readDueScheduleOutbox,Fo as readExternalSourceBaseline,Ue as readGlobalShapeSnapshot,ve as readIdempotent,Lr as readMigrationStatus,Ja as readQueueMessageById,Za as readQueueMessages,ht as readReactorState,_i as readSchemaHistory,Ii as readSchemaVersion,mr as readSearchBackfillState,Tr as readShapePokeCursor,po as readStreamChunks,So as readStreamRun,Ea as readTablePage,Pa as recordCapturedMail,Sn as recordChangedKeys,ha as recordFanoutPass,xa as recordGlobalPollPass,$a as recordQueueMessages,nr as recordScheduleOutbox,bi as recordSchemaVersion,Ta as recordShapeProbePass,Yt as relationHooks,oi as relayCountFor,oo as renderSql,Ei as reprojectableFields,Un as reprojectionMigrationId,hi as reprojectionTables,st as resolveRankPartition,Je as resolveRankSeekTuple,Xt as resolveRelationPredicates,jt as resolveWith,jr as rowToDocument,Dr as runDataMigration,kr as runDrizzle,yo as runExternalSourceTick,Zi as runReadonlySql,Jt as runRowValidators,Wn as runShardMigrations,zi as runSocketPool,Br as runSql,_n as runTriggers,bn as selectExpiredIds,n as selectExportTables,_ as selectIndexForAggregate,I as selectIndexForCount,b as selectIndexForGroupBy,Ra as selectMatchingIds,gr as selectShapeMembers,_r as selectShapeRows,Di as serializeSqlValue,Fn as serverInList,ai as shapeRoutingKey,Xa as softDeleteScope,lt as sortColumnName,ao as sqliteInList,Hn as stableStringify,zn as stableWireKey,G as stripReservedPatchFields,ln as subscriptionFrames,dn as subscriptionListDeltas,Ca as summarizeFanoutTopics,Aa as summarizeSubscriptions,Jr as tableColumns,yr as tableFromDepKey,S as throwingScheduler,Ha as tiebreakDirectionFor,pe as trimCdcChanges,We as trimIdempotent,sr as trimScheduleOutbox,uo as trimStreamRuns,Zr as tryRowToDocument,cn as trySendFrame,to as unionAll,Va as uniqueIndexFields,s as validateImportRow,Pt as whereFilter,Ot as whereOfFilter,xe as writeCdcArchivedThrough,Ge as writeGlobalShapeSnapshot,Xe as writeIdempotent,xt as writeReactorState,pr as writeSearchBackfillState,Rr as writeShapePokeCursor,Cr as writeShapePokeCursors,un as writeTouchesMemo};
|
|
1
|
+
import{exportShardRows as o,importShardRows as a,parseExportShardArgs as t,parseImportShardArgs as i,selectExportTables as n,validateImportRow as s}from"./packem_shared/exportShardRows-CTDgQEF8.mjs";import{AGGREGATE_SQL_FUNCTION as d,aggregateSqlFunction as c,matchesStaticWhere as m,normalizeCountArgument as p,throwingScheduler as S}from"./packem_shared/AGGREGATE_SQL_FUNCTION-DDEoMnJR.mjs";import{aggregateTableName as f,coerceAggregateNumber as E,encodeAggregateKey as h,foldAggregateTally as x,readAggregateValue as T}from"./packem_shared/aggregateTableName-C7o-gpms.mjs";import{CountRlsUnsupportedError as C,mergeWhere as A,planAggregateLookup as g,selectIndexForAggregate as _,selectIndexForCount as I,selectIndexForGroupBy as b}from"./packem_shared/CountRlsUnsupportedError-BvsDqfO2.mjs";import{AUDIT_LOG_TABLE as D,appendAuditEntry as P,ensureAuditTable as O,readAuditLog as M}from"./packem_shared/AUDIT_LOG_TABLE-CZNxCRLv.mjs";import{NotUniqueError as y,assertNoExplicitUndefined as N,assertValidClientId as k,createShardCtxDb as B,normalizeIdStructurally as U,stripReservedPatchFields as G}from"./packem_shared/NotUniqueError-D4EV8EzO.mjs";import{backfillAggregateIndexes as w,backfillRankIndexes as K,backfillSearchIndexes as v,backfillSearchIndexesForTable as W}from"./packem_shared/backfillAggregateIndexes-B_3xdOgV.mjs";import{CDC_LOG_TABLE as H,CDC_LOG_TABLE_SEQ_INDEX as V,CDC_META_TABLE as z,appendCdcChange as Q,applyCdcChanges as Y,bumpCdcEpoch as j,cdcCanVouchFor as J,cdcForkedError as Z,cdcSeqLeavingRows as $,cdcTouchesTables as ee,cdcTrimmedError as re,compactCdcDocs as oe,cursorBelowRetainedFloor as ae,migrateCdcLog as te,migrateCdcMeta as ie,minCdcReplayableSeq as ne,minCdcSeq as se,readCdcChangeKeys as le,readCdcChanges as de,readCdcCursor as ce,readCdcEpoch as me,trimCdcChanges as pe}from"./packem_shared/CDC_LOG_TABLE-QaBxSIZM.mjs";import{archiveCdcSegment as ue,cdcArchiveRewound as fe,readArchivedCdcChanges as Ee,readCdcArchivedThrough as he,writeCdcArchivedThrough as xe}from"./packem_shared/archiveCdcSegment-BON69Nug.mjs";import{CLIENT_WATERMARK_TABLE as Re,advanceClientWatermark as Ce,migrateClientWatermark as Ae,readClientWatermark as ge}from"./packem_shared/CLIENT_WATERMARK_TABLE-vLjfNhBR.mjs";import{COMMIT_SEQ_FIELD as Ie,COMMIT_SEQ_TABLE as be,allocateCommitSeq as Le,migrateCommitSeq as De,readCommitSeq as Pe}from"./packem_shared/COMMIT_SEQ_FIELD-BY_vc9bw.mjs";import{createCompanionSync as Me}from"./packem_shared/createCompanionSync-Rjn0lsT6.mjs";import{GLOBAL_SHAPE_SNAPSHOT_TABLE as ye,deleteGlobalShapeSnapshot as Ne,deleteGlobalShapeSnapshotsForConnection as ke,migrateGlobalShapeSnapshot as Be,readGlobalShapeSnapshot as Ue,writeGlobalShapeSnapshot as Ge}from"./packem_shared/GLOBAL_SHAPE_SNAPSHOT_TABLE-pMxZ-obU.mjs";import{IDEMPOTENCY_TABLE as we,migrateIdempotency as Ke,readIdempotent as ve,trimIdempotent as We,writeIdempotent as Xe}from"./packem_shared/IDEMPOTENCY_TABLE-AOJCuq5U.mjs";import{clearMemoryTables as Ve,isMemoryTable as ze,memoryTableNames as Qe}from"./packem_shared/clearMemoryTables-CogAvVHR.mjs";import{computeRankPage as je,resolveRankSeekTuple as Je}from"./packem_shared/computeRankPage-3AiKfT8q.mjs";import{SCHEDULE_OUTBOX_TABLE as $e,deferScheduleOutbox as er,forgetScheduleOutbox as rr,migrateScheduleOutbox as or,parkScheduleOutbox as ar,probeScheduleOutbox as tr,readDueScheduleOutbox as ir,recordScheduleOutbox as nr,trimScheduleOutbox as sr}from"./packem_shared/SCHEDULE_OUTBOX_TABLE-CgLvGxpY.mjs";import{S as dr,m as cr,r as mr,w as pr}from"./packem_shared/ctx-db-search-state-DVCp4JQf.mjs";import{SHAPE_POKE_CURSOR_TABLE as ur,deleteShapePokeCursor as fr,deleteShapePokeCursorsForConnection as Er,migrateShapePokeCursor as hr,minShapePokeCursor as xr,readShapePokeCursor as Tr,writeShapePokeCursor as Rr,writeShapePokeCursors as Cr}from"./packem_shared/SHAPE_POKE_CURSOR_TABLE-cn0stGAL.mjs";import{selectShapeMembers as gr,selectShapeRows as _r}from"./packem_shared/selectShapeMembers-BXhvEt4X.mjs";import{DATA_MIGRATION_STATE_TABLE as br,readMigrationStatus as Lr,runDataMigration as Dr}from"./packem_shared/DATA_MIGRATION_STATE_TABLE-BMbxLEaN.mjs";import{SCAN_DEP as Or,createDependencyTracker as Mr,depKey as Fr,tableFromDepKey as yr}from"./packem_shared/SCAN_DEP-D7qE3iUe.mjs";import{runDrizzle as kr,runSql as Br}from"./packem_shared/runDrizzle-Du5HLitO.mjs";import{A as Gr,a as qr,b as wr,D as Kr,c as vr,d as Wr,g as Xr,i as Hr,j as Vr,e as zr,q as Qr,f as Yr,r as jr,t as Jr,h as Zr}from"./packem_shared/do-sql-BEFrJUds.mjs";import{WORKERD_SQLITE_LIMITS as eo,param as ro,renderSql as oo,sqliteInList as ao,unionAll as to}from"./packem_shared/WORKERD_SQLITE_LIMITS-DBH23L_S.mjs";import{appendStreamChunk as no,claimStreamRun as so,deleteStreamRun as lo,finishStreamRun as co,migrateDurableStreams as mo,readStreamChunks as po,readStreamRun as So,trimStreamRuns as uo}from"./packem_shared/appendStreamChunk-7ZyAZGg_.mjs";import{DurableStreamRunner as Eo,MAX_DURABLE_STREAM_BYTES as ho,MAX_DURABLE_STREAM_CHUNKS as xo,decideDurableAttach as To}from"./packem_shared/DurableStreamRunner-Dk9Pn-B8.mjs";import{envOptionalPositiveInt as Co,envPositiveInt as Ao}from"./packem_shared/envOptionalPositiveInt-D2pY-c64.mjs";import{diffExternalSource as _o}from"./packem_shared/diffExternalSource-DgDJhslq.mjs";import{liftSourceId as bo,normalizeSourceDocument as Lo,normalizeSourceValue as Do}from"./packem_shared/liftSourceId-CA3ENhXj.mjs";import{materializeExternalRows as Oo,materializeExternalRowsIncremental as Mo,readExternalSourceBaseline as Fo,runExternalSourceTick as yo}from"./packem_shared/materializeExternalRows-DhINQHwd.mjs";import{isSoftDeleted as ko,isSourceDue as Bo,pullExternalSourceIncrementalTick as Uo,pullExternalSourceTick as Go}from"./packem_shared/isSoftDeleted-sGRSPPQq.mjs";import{f as wo,a as Ko,b as vo,c as Wo,d as Xo,g as Ho}from"./packem_shared/fts-companion-pUdD6kF-.mjs";import{GEO_DEFAULT_PRECISION as zo,boundingBoxCenter as Qo,boundingBoxGeohashes as Yo,coveringGeohashes as jo,encodeGeohash as Jo,haversineMeters as Zo,pointInBoundingBox as $o}from"./packem_shared/GEO_DEFAULT_PRECISION-CqpQZ-J_.mjs";import{default as ra}from"./packem_shared/GlobalPollTick-BNK4o-XT.mjs";import{ADMIN_FUNCTIONS as aa,ADMIN_FUNCTION_PREFIX as ta,DEFAULT_FANOUT_TOPIC_LIMIT as ia,FLAGS_FUNCTION_PREFIX as na,MAX_PAGE_SIZE as sa,RELATION_FUNCTION_PREFIX as la,createFanoutCounters as da,createGlobalPollCounters as ca,createShapeProbeCounters as ma,facetColumn as pa,findStorageReferences as Sa,isVacuousFilterClause as ua,listTables as fa,readTablePage as Ea,recordFanoutPass as ha,recordGlobalPollPass as xa,recordShapeProbePass as Ta,selectMatchingIds as Ra,summarizeFanoutTopics as Ca,summarizeSubscriptions as Aa}from"./packem_shared/ADMIN_FUNCTIONS-D5mzmLFo.mjs";import{MAIL_RETENTION as _a,MAIL_TABLE as Ia,clearCapturedMail as ba,ensureMailTable as La,readCapturedMail as Da,recordCapturedMail as Pa}from"./packem_shared/MAIL_RETENTION-BxAGL3hK.mjs";import{NotFoundError as Ma}from"./packem_shared/NotFoundError-BhF7FeFr.mjs";import{armRestore as ya,readBookmark as Na}from"./packem_shared/armRestore-Bu1_8SUa.mjs";import{CURSOR_PREFIX as Ba,applySelect as Ua,buildSeekBeforeWhere as Ga,buildSeekWhere as qa,decodeCursor as wa,encodeCursor as Ka,equalityPinnedFields as va,normalizeOrderKeys as Wa,softDeleteScope as Xa,tiebreakDirectionFor as Ha,uniqueIndexFields as Va}from"./packem_shared/CURSOR_PREFIX-BX8jkMJa.mjs";import{QUEUE_TABLE as Qa,clearQueueMessages as Ya,isLossyBody as ja,readQueueMessageById as Ja,readQueueMessages as Za,recordQueueMessages as $a}from"./packem_shared/QUEUE_TABLE-DKANxmEZ.mjs";import{RANK_TIEBREAK as rt,encodePartitionKey as ot,matchesRankStaticWhere as at,rankKeyFromDoc as tt,rankPivotConditionSql as it,rankTableName as nt,resolveRankPartition as st,sortColumnName as lt}from"./packem_shared/RANK_TIEBREAK-B0_x8iev.mjs";import{ReactiveCache as ct,reactiveCacheKey as mt}from"./packem_shared/ReactiveCache-D8ccaO6f.mjs";import{REACTOR_STATE_TABLE as St,listReactorStates as ut,migrateReactorState as ft,reactorNeedsRun as Et,readReactorState as ht,writeReactorState as xt}from"./packem_shared/REACTOR_STATE_TABLE-B8IehLv8.mjs";import{UNVOUCHABLE_DEP as Rt,createReadFootprint as Ct,markUnvouchableReads as At}from"./packem_shared/UNVOUCHABLE_DEP-C68htACn.mjs";import{buildIndexRange as _t,indexKeysForRow as It,keysTouchRanges as bt}from"./packem_shared/buildIndexRange-6nIZDf4m.mjs";import{isPushableWhere as Dt,whereFilter as Pt,whereOfFilter as Ot}from"./packem_shared/isPushableWhere-BeYAOjUb.mjs";import{RELATED_DEFAULT_LIMIT as Ft,RELATED_DEPTH_DECAY as yt,RELATED_MAX_DEPTH as Nt,RELATED_MAX_LIMIT as kt,deriveRelationEdges as Bt,findRelated as Ut}from"./packem_shared/RELATED_DEFAULT_LIMIT-CBYQQIrZ.mjs";import{DEFAULT_MAX_RELATION_KEYS as qt,assertFlatPredicate as wt,assertShapeShardable as Kt,containsRelationPredicate as vt,isRelationPredicate as Wt,resolveRelationPredicates as Xt}from"./packem_shared/DEFAULT_MAX_RELATION_KEYS-CYPZfQH9.mjs";import{applyOnDelete as Vt,distinctValues as zt,fanOutScalarCounts as Qt,relationHooks as Yt,resolveWith as jt,runRowValidators as Jt}from"./packem_shared/applyOnDelete-DJsOG8tz.mjs";import{DEFAULT_PROMOTION_THRESHOLDS as $t,clampPromotionThresholds as ei,nextPromotionState as ri,relayCountFor as oi,shapeRoutingKey as ai}from"./packem_shared/DEFAULT_PROMOTION_THRESHOLDS-91RH_llq.mjs";import{DEFAULT_MAX_RELAYS as ii,OwnerRelay as ni,RelayMember as si,createRelayLink as li}from"./packem_shared/DEFAULT_MAX_RELAYS-hdowkC2x.mjs";import{createReplicaLink as ci,gateReplicaDispatch as mi,handleReplicaControl as pi}from"./packem_shared/createReplicaLink-Z82FMxvY.mjs";import{buildReprojectionMigration as ui,countLegacyRows as fi,reprojectableFields as Ei,reprojectionTables as hi}from"./packem_shared/buildReprojectionMigration-IMrfRdvU.mjs";import{RLS_UNWRAP_SYMBOL as Ti,RlsRequiredError as Ri,guardWriter as Ci}from"./packem_shared/RLS_UNWRAP_SYMBOL-rSxYzw-G.mjs";import{SCHEMA_HISTORY_MAX_VERSIONS as gi,readSchemaHistory as _i,readSchemaVersion as Ii,recordSchemaVersion as bi}from"./packem_shared/SCHEMA_HISTORY_MAX_VERSIONS-BMcUIqBY.mjs";import{serializeSqlValue as Di}from"./packem_shared/serializeSqlValue-BbZ5hKM7.mjs";import{buildSettings as Oi,isDevEnvironment as Mi,readDeployInfo as Fi}from"./packem_shared/buildSettings-BRkZd6_E.mjs";import{buildShapeDiff as Ni}from"./packem_shared/buildShapeDiff-D-J_GmC1.mjs";import{ShapeDiffCache as Bi,createShapeDiffCache as Ui,globalShapeReadKey as Gi}from"./packem_shared/ShapeDiffCache-gdaILV5E.mjs";import{buildPokeFrames as wi,diffGlobalMembership as Ki,encodeRowsPatch as vi,projectColumns as Wi}from"./packem_shared/buildPokeFrames-BBE6J91z.mjs";import{ShardRunner as Hi}from"./packem_shared/ShardRunner-CrveaPId.mjs";import{runSocketPool as zi}from"./packem_shared/runSocketPool-CZJ2X9cF.mjs";import{MAX_SQL_ROWS as Yi,assertReadonly as ji,lintReadonlySql as Ji,runReadonlySql as Zi}from"./packem_shared/MAX_SQL_ROWS-Dh_Ty0Zo.mjs";import{BIGINT_KEY_DIGITS as en,bigintSqlKey as rn,decodeBigintSqlKey as on,decodeFloat64SqlKey as an,float64SqlKey as tn}from"./packem_shared/BIGINT_KEY_DIGITS-C9a7Ix7k.mjs";import{awaitWsDrain as sn,subscriptionFrames as ln,subscriptionListDeltas as dn,trySendFrame as cn}from"./packem_shared/awaitWsDrain-apizgmKY.mjs";import{mergeChangedKeys as pn,recordChangedKeys as Sn,writeTouchesMemo as un}from"./packem_shared/mergeChangedKeys-DH9RAARR.mjs";import{createSystemReader as En}from"./packem_shared/createSystemReader-DcDLFfC-.mjs";import{ConflictError as xn}from"./packem_shared/ConflictError-C8GtJmjS.mjs";import{DEFAULT_TRANSACTION_LIMITS as Rn,TransactionHeadroomTracker as Cn}from"./packem_shared/DEFAULT_TRANSACTION_LIMITS-DiR5z5EX.mjs";import{hasTrigger as gn,runTriggers as _n}from"./packem_shared/hasTrigger-CjlwI4le.mjs";import{selectExpiredIds as bn}from"./packem_shared/selectExpiredIds-DQg6v5Uf.mjs";import{VECTOR_BACKFILL_MAX_PAGES as Dn,backfillVectorIndexes as Pn}from"./packem_shared/VECTOR_BACKFILL_MAX_PAGES-B2ZWxshy.mjs";import{c as Mn,s as Fn}from"./packem_shared/where-sql-DFs8Zw7-.mjs";import{RELATION_EXISTS_KEY as Nn}from"./packem_shared/RELATION_EXISTS_KEY-CFUhnZSZ.mjs";import{REPROJECTION_MIGRATION_PREFIX as Bn,reprojectionMigrationId as Un}from"./packem_shared/REPROJECTION_MIGRATION_PREFIX-Czcb6_mO.mjs";import{isInternalTableName as qn}from"./packem_shared/isInternalTableName-BoljO2tP.mjs";import{quoteIdentifier as Kn}from"./packem_shared/quoteIdentifier-CObIFRhb.mjs";import{runShardMigrations as Wn}from"./packem_shared/runShardMigrations-MXioI81k.mjs";import{stableStringify as Hn}from"./packem_shared/stableStringify-DibjylKD.mjs";import{stableWireKey as zn}from"./packem_shared/stableWireKey-D2US4k_J.mjs";export{aa as ADMIN_FUNCTIONS,ta as ADMIN_FUNCTION_PREFIX,d as AGGREGATE_SQL_FUNCTION,Gr as AGG_COUNT,qr as AGG_KEY,wr as AGG_VALUE,D as AUDIT_LOG_TABLE,en as BIGINT_KEY_DIGITS,H as CDC_LOG_TABLE,V as CDC_LOG_TABLE_SEQ_INDEX,z as CDC_META_TABLE,Re as CLIENT_WATERMARK_TABLE,Ie as COMMIT_SEQ_FIELD,be as COMMIT_SEQ_TABLE,Ba as CURSOR_PREFIX,xn as ConflictError,C as CountRlsUnsupportedError,br as DATA_MIGRATION_STATE_TABLE,ia as DEFAULT_FANOUT_TOPIC_LIMIT,qt as DEFAULT_MAX_RELATION_KEYS,ii as DEFAULT_MAX_RELAYS,$t as DEFAULT_PROMOTION_THRESHOLDS,Rn as DEFAULT_TRANSACTION_LIMITS,Kr as DOC_COLUMN,Eo as DurableStreamRunner,na as FLAGS_FUNCTION_PREFIX,zo as GEO_DEFAULT_PRECISION,ye as GLOBAL_SHAPE_SNAPSHOT_TABLE,ra as GlobalPollTick,we as IDEMPOTENCY_TABLE,_a as MAIL_RETENTION,Ia as MAIL_TABLE,ho as MAX_DURABLE_STREAM_BYTES,xo as MAX_DURABLE_STREAM_CHUNKS,sa as MAX_PAGE_SIZE,Yi as MAX_SQL_ROWS,Ma as NotFoundError,y as NotUniqueError,ni as OwnerRelay,Qa as QUEUE_TABLE,rt as RANK_TIEBREAK,St as REACTOR_STATE_TABLE,Ft as RELATED_DEFAULT_LIMIT,yt as RELATED_DEPTH_DECAY,Nt as RELATED_MAX_DEPTH,kt as RELATED_MAX_LIMIT,Nn as RELATION_EXISTS_KEY,la as RELATION_FUNCTION_PREFIX,Bn as REPROJECTION_MIGRATION_PREFIX,Ti as RLS_UNWRAP_SYMBOL,ct as ReactiveCache,si as RelayMember,Ri as RlsRequiredError,Or as SCAN_DEP,$e as SCHEDULE_OUTBOX_TABLE,gi as SCHEMA_HISTORY_MAX_VERSIONS,dr as SEARCH_STATE_TABLE,ur as SHAPE_POKE_CURSOR_TABLE,Bi as ShapeDiffCache,Hi as ShardRunner,Cn as TransactionHeadroomTracker,Rt as UNVOUCHABLE_DEP,Dn as VECTOR_BACKFILL_MAX_PAGES,eo as WORKERD_SQLITE_LIMITS,Ce as advanceClientWatermark,vr as aggUpsertSql,c as aggregateSqlFunction,f as aggregateTableName,Le as allocateCommitSeq,P as appendAuditEntry,Q as appendCdcChange,no as appendStreamChunk,Y as applyCdcChanges,Vt as applyOnDelete,Ua as applySelect,ue as archiveCdcSegment,ya as armRestore,wt as assertFlatPredicate,N as assertNoExplicitUndefined,ji as assertReadonly,Kt as assertShapeShardable,k as assertValidClientId,sn as awaitWsDrain,w as backfillAggregateIndexes,K as backfillRankIndexes,v as backfillSearchIndexes,W as backfillSearchIndexesForTable,Pn as backfillVectorIndexes,rn as bigintSqlKey,Qo as boundingBoxCenter,Yo as boundingBoxGeohashes,_t as buildIndexRange,wi as buildPokeFrames,ui as buildReprojectionMigration,Ga as buildSeekBeforeWhere,qa as buildSeekWhere,Oi as buildSettings,Ni as buildShapeDiff,j as bumpCdcEpoch,fe as cdcArchiveRewound,J as cdcCanVouchFor,Z as cdcForkedError,$ as cdcSeqLeavingRows,ee as cdcTouchesTables,re as cdcTrimmedError,so as claimStreamRun,ei as clampPromotionThresholds,ba as clearCapturedMail,Ve as clearMemoryTables,Ya as clearQueueMessages,E as coerceAggregateNumber,oe as compactCdcDocs,Mn as compileWhereSql,je as computeRankPage,vt as containsRelationPredicate,fi as countLegacyRows,jo as coveringGeohashes,Me as createCompanionSync,Mr as createDependencyTracker,da as createFanoutCounters,ca as createGlobalPollCounters,Wr as createIndexSql,Ct as createReadFootprint,li as createRelayLink,ci as createReplicaLink,Ui as createShapeDiffCache,ma as createShapeProbeCounters,B as createShardCtxDb,En as createSystemReader,ae as cursorBelowRetainedFloor,To as decideDurableAttach,on as decodeBigintSqlKey,wa as decodeCursor,an as decodeFloat64SqlKey,er as deferScheduleOutbox,Ne as deleteGlobalShapeSnapshot,ke as deleteGlobalShapeSnapshotsForConnection,fr as deleteShapePokeCursor,Er as deleteShapePokeCursorsForConnection,lo as deleteStreamRun,Fr as depKey,Bt as deriveRelationEdges,_o as diffExternalSource,Ki as diffGlobalMembership,zt as distinctValues,h as encodeAggregateKey,Ka as encodeCursor,Jo as encodeGeohash,ot as encodePartitionKey,vi as encodeRowsPatch,O as ensureAuditTable,La as ensureMailTable,Co as envOptionalPositiveInt,Ao as envPositiveInt,va as equalityPinnedFields,o as exportShardRows,pa as facetColumn,Qt as fanOutScalarCounts,Ut as findRelated,Sa as findStorageReferences,co as finishStreamRun,tn as float64SqlKey,x as foldAggregateTally,rr as forgetScheduleOutbox,wo as ftsCompanionDdl,Ko as ftsPurgeDocument,vo as ftsRowidMapName,Wo as ftsUnmappedPage,Xo as ftsWriteDocument,mi as gateReplicaDispatch,Xr as geoTableName,Gi as globalShapeReadKey,Ho as groupUnmappedRows,Ci as guardWriter,pi as handleReplicaControl,gn as hasTrigger,Zo as haversineMeters,a as importShardRows,It as indexKeysForRow,Mi as isDevEnvironment,Hr as isFtsAvailable,qn as isInternalTableName,ja as isLossyBody,ze as isMemoryTable,Dt as isPushableWhere,Wt as isRelationPredicate,ko as isSoftDeleted,Bo as isSourceDue,ua as isVacuousFilterClause,Vr as jsonPath,zr as jsonPathSql,bt as keysTouchRanges,bo as liftSourceId,Ji as lintReadonlySql,ut as listReactorStates,fa as listTables,At as markUnvouchableReads,at as matchesRankStaticWhere,m as matchesStaticWhere,Oo as materializeExternalRows,Mo as materializeExternalRowsIncremental,Qe as memoryTableNames,pn as mergeChangedKeys,A as mergeWhere,te as migrateCdcLog,ie as migrateCdcMeta,Ae as migrateClientWatermark,De as migrateCommitSeq,mo as migrateDurableStreams,Be as migrateGlobalShapeSnapshot,Ke as migrateIdempotency,ft as migrateReactorState,or as migrateScheduleOutbox,cr as migrateSearchState,hr as migrateShapePokeCursor,ne as minCdcReplayableSeq,se as minCdcSeq,xr as minShapePokeCursor,ri as nextPromotionState,p as normalizeCountArgument,U as normalizeIdStructurally,Wa as normalizeOrderKeys,Lo as normalizeSourceDocument,Do as normalizeSourceValue,ro as param,ar as parkScheduleOutbox,t as parseExportShardArgs,i as parseImportShardArgs,g as planAggregateLookup,$o as pointInBoundingBox,tr as probeScheduleOutbox,Wi as projectColumns,Uo as pullExternalSourceIncrementalTick,Go as pullExternalSourceTick,Qr as qualifiedJsonPath,Yr as qualifiedJsonPathSql,Kn as quoteIdentifier,tt as rankKeyFromDoc,it as rankPivotConditionSql,nt as rankTableName,mt as reactiveCacheKey,Et as reactorNeedsRun,T as readAggregateValue,Ee as readArchivedCdcChanges,M as readAuditLog,Na as readBookmark,Da as readCapturedMail,he as readCdcArchivedThrough,le as readCdcChangeKeys,de as readCdcChanges,ce as readCdcCursor,me as readCdcEpoch,ge as readClientWatermark,Pe as readCommitSeq,Fi as readDeployInfo,ir as readDueScheduleOutbox,Fo as readExternalSourceBaseline,Ue as readGlobalShapeSnapshot,ve as readIdempotent,Lr as readMigrationStatus,Ja as readQueueMessageById,Za as readQueueMessages,ht as readReactorState,_i as readSchemaHistory,Ii as readSchemaVersion,mr as readSearchBackfillState,Tr as readShapePokeCursor,po as readStreamChunks,So as readStreamRun,Ea as readTablePage,Pa as recordCapturedMail,Sn as recordChangedKeys,ha as recordFanoutPass,xa as recordGlobalPollPass,$a as recordQueueMessages,nr as recordScheduleOutbox,bi as recordSchemaVersion,Ta as recordShapeProbePass,Yt as relationHooks,oi as relayCountFor,oo as renderSql,Ei as reprojectableFields,Un as reprojectionMigrationId,hi as reprojectionTables,st as resolveRankPartition,Je as resolveRankSeekTuple,Xt as resolveRelationPredicates,jt as resolveWith,jr as rowToDocument,Dr as runDataMigration,kr as runDrizzle,yo as runExternalSourceTick,Zi as runReadonlySql,Jt as runRowValidators,Wn as runShardMigrations,zi as runSocketPool,Br as runSql,_n as runTriggers,bn as selectExpiredIds,n as selectExportTables,_ as selectIndexForAggregate,I as selectIndexForCount,b as selectIndexForGroupBy,Ra as selectMatchingIds,gr as selectShapeMembers,_r as selectShapeRows,Di as serializeSqlValue,Fn as serverInList,ai as shapeRoutingKey,Xa as softDeleteScope,lt as sortColumnName,ao as sqliteInList,Hn as stableStringify,zn as stableWireKey,G as stripReservedPatchFields,ln as subscriptionFrames,dn as subscriptionListDeltas,Ca as summarizeFanoutTopics,Aa as summarizeSubscriptions,Jr as tableColumns,yr as tableFromDepKey,S as throwingScheduler,Ha as tiebreakDirectionFor,pe as trimCdcChanges,We as trimIdempotent,sr as trimScheduleOutbox,uo as trimStreamRuns,Zr as tryRowToDocument,cn as trySendFrame,to as unionAll,Va as uniqueIndexFields,s as validateImportRow,Pt as whereFilter,Ot as whereOfFilter,xe as writeCdcArchivedThrough,Ge as writeGlobalShapeSnapshot,Xe as writeIdempotent,xt as writeReactorState,pr as writeSearchBackfillState,Rr as writeShapePokeCursor,Cr as writeShapePokeCursors,un as writeTouchesMemo};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{LunoraError as p}from"@lunora/errors";import{d as y,e as _}from"./wire-codec-C-FpWm52.mjs";const N="id",h=e=>e.at(-1)?.direction==="desc"?"desc":"asc",m=new Set(["_id","id"]),O=new Set(["_creationTime","_id","id"]),E=(e,t)=>{if(O.has(e))return!1;const n=t?.[e];return n===void 0?!0:n.kind==="optional"||n._meta?.column?.notNull===!1},A=new Set(["AND","NOT","OR"]),C=e=>{const t=new Set;if(typeof e!="object"||Array.isArray(e))return t;for(const[n,o]of Object.entries(e)){if(A.has(n))continue;if(o===null||typeof o!="object"||Array.isArray(o)){t.add(n);continue}const r=Object.keys(o);r.length===1&&r[0]==="eq"&&t.add(n)}return t},j=(e,t)=>{const n=[];for(const o of e??[])o.unique===!0&&n.push(o.fields);for(const[o,r]of Object.entries(t??{}))r._meta?.column?.unique===!0&&n.push([o]);return n},g=(e,t)=>(t??[]).some(n=>n.length>0&&n.every(o=>e.has(o))),q=(e,t,n)=>{const o=[],r=new Set(n?.pinned);let s="asc";for(const i of e??[])for(const[l,c]of Object.entries(i))s=c,r.add(l),!n?.pinned?.has(l)&&o.push({direction:c,field:l,nullable:E(l,t)});return o.length===0?[{direction:s,field:"_creationTime",nullable:!1}]:(o.some(i=>m.has(i.field)||i.field==="_creationTime")||g(r,n?.uniqueBy)||o.push({direction:h(o),field:"_creationTime",nullable:!1}),o)},F=/[\u0080-\u{10FFFF}]/u,R=e=>{if(!F.test(e))return btoa(e);const t=new TextEncoder().encode(e);let n="";for(const o of t)n+=String.fromCodePoint(o);return btoa(n)},T=e=>{const t=atob(e),n=Uint8Array.from(t,o=>o.codePointAt(0)??0);return new TextDecoder().decode(n)},a="~4",L=(e,t)=>{const n=t.map(o=>e[o.field]??null);return n.push(e._id),a+R(JSON.stringify(_(n)))},u=()=>new p("BAD_REQUEST","invalid cursor"),k=e=>{if(!e.startsWith(a))throw u();let t;try{t=y(JSON.parse(T(e.slice(a.length))))}catch{throw u()}if(!Array.isArray(t))throw u();return t.map(n=>n??null)},b=(e,t,n,o)=>{const{field:r}=e,s=e.direction!=="desc"===n;if(t===null)return s?o?{OR:[{[r]:{isNull:!1}},{[r]:{isNull:!0}}]}:{[r]:{isNull:!1}}:o?{[r]:{isNull:!0}}:{OR:[]};let i=s?"gt":"lt";o&&(i=s?"gte":"lte");const l={[r]:{[i]:t}};return s||!e.nullable?l:{OR:[l,{[r]:{isNull:!0}}]}},S=(e,t,n,o)=>{const r=e.some(c=>m.has(c.field))?e:[...e,{direction:h(e),field:N,nullable:!1}];if(t.length<r.length)throw u();const s=c=>{const d=r[c];if(d===void 0)throw u();const f=b(d,t[c],n,o&&c===r.length-1);return c===r.length-1?f:{OR:[f,{AND:[{[d.field]:{eq:t[c]}},s(c+1)]}]}},i=s(0),[l]=r;return r.length<2||l===void 0||l.nullable||t[0]===null?i:{AND:[b(l,t[0],n,!0),i]}},v=(e,t)=>S(e,t,!0,!1),B=(e,t)=>S(e,t,!1,!0),D=["_id","_creationTime"],W=(e,t,n)=>{if(!t)return e;const o=new Set([...t,...D,...n?Object.keys(n):[]]);return e.map(r=>{const s={};for(const i of o)i in r&&(s[i]=r[i]);return s})},P=(e,t)=>e&&t!==!0?{[e.field]:{isNull:!0}}:void 0,U=(e,t)=>t===void 0||e[t]===null||e[t]===void 0;export{a as CURSOR_PREFIX,W as applySelect,B as buildSeekBeforeWhere,v as buildSeekWhere,k as decodeCursor,L as encodeCursor,C as equalityPinnedFields,T as fromBase64,
|
|
1
|
+
import{LunoraError as p}from"@lunora/errors";import{d as y,e as _}from"./wire-codec-C-FpWm52.mjs";const N="id",h=e=>e.at(-1)?.direction==="desc"?"desc":"asc",m=new Set(["_id","id"]),O=new Set(["_creationTime","_id","id"]),E=(e,t)=>{if(O.has(e))return!1;const n=t?.[e];return n===void 0?!0:n.kind==="optional"||n._meta?.column?.notNull===!1},A=new Set(["AND","NOT","OR"]),C=e=>{const t=new Set;if(typeof e!="object"||Array.isArray(e))return t;for(const[n,o]of Object.entries(e)){if(A.has(n))continue;if(o===null||typeof o!="object"||Array.isArray(o)){t.add(n);continue}const r=Object.keys(o);r.length===1&&r[0]==="eq"&&t.add(n)}return t},j=(e,t)=>{const n=[];for(const o of e??[])o.unique===!0&&n.push(o.fields);for(const[o,r]of Object.entries(t??{}))r._meta?.column?.unique===!0&&n.push([o]);return n},g=(e,t)=>(t??[]).some(n=>n.length>0&&n.every(o=>e.has(o))),q=(e,t,n)=>{const o=[],r=new Set(n?.pinned);let s="asc";for(const i of e??[])for(const[l,c]of Object.entries(i))s=c,r.add(l),!n?.pinned?.has(l)&&o.push({direction:c,field:l,nullable:E(l,t)});return o.length===0?[{direction:s,field:"_creationTime",nullable:!1}]:(o.some(i=>m.has(i.field)||i.field==="_creationTime")||g(r,n?.uniqueBy)||o.push({direction:h(o),field:"_creationTime",nullable:!1}),o)},F=/[\u0080-\u{10FFFF}]/u,R=e=>{if(!F.test(e))return btoa(e);const t=new TextEncoder().encode(e);let n="";for(const o of t)n+=String.fromCodePoint(o);return btoa(n)},T=e=>{const t=atob(e),n=Uint8Array.from(t,o=>o.codePointAt(0)??0);return new TextDecoder().decode(n)},a="~4",L=(e,t)=>{const n=t.map(o=>e[o.field]??null);return n.push(e._id),a+R(JSON.stringify(_(n)))},u=()=>new p("BAD_REQUEST","invalid cursor"),k=e=>{if(!e.startsWith(a))throw u();let t;try{t=y(JSON.parse(T(e.slice(a.length))))}catch{throw u()}if(!Array.isArray(t))throw u();return t.map(n=>n??null)},b=(e,t,n,o)=>{const{field:r}=e,s=e.direction!=="desc"===n;if(t===null)return s?o?{OR:[{[r]:{isNull:!1}},{[r]:{isNull:!0}}]}:{[r]:{isNull:!1}}:o?{[r]:{isNull:!0}}:{OR:[]};let i=s?"gt":"lt";o&&(i=s?"gte":"lte");const l={[r]:{[i]:t}};return s||!e.nullable?l:{OR:[l,{[r]:{isNull:!0}}]}},S=(e,t,n,o)=>{const r=e.some(c=>m.has(c.field))?e:[...e,{direction:h(e),field:N,nullable:!1}];if(t.length<r.length)throw u();const s=c=>{const d=r[c];if(d===void 0)throw u();const f=b(d,t[c],n,o&&c===r.length-1);return c===r.length-1?f:{OR:[f,{AND:[{[d.field]:{eq:t[c]}},s(c+1)]}]}},i=s(0),[l]=r;return r.length<2||l===void 0||l.nullable||t[0]===null?i:{AND:[b(l,t[0],n,!0),i]}},v=(e,t)=>S(e,t,!0,!1),B=(e,t)=>S(e,t,!1,!0),D=["_id","_creationTime"],W=(e,t,n)=>{if(!t)return e;const o=new Set([...t,...D,...n?Object.keys(n):[]]);return e.map(r=>{const s={};for(const i of o)i in r&&(s[i]=r[i]);return s})},P=(e,t)=>e&&t!==!0?{[e.field]:{isNull:!0}}:void 0,U=(e,t)=>t===void 0||e[t]===null||e[t]===void 0;export{a as CURSOR_PREFIX,W as applySelect,B as buildSeekBeforeWhere,v as buildSeekWhere,k as decodeCursor,L as encodeCursor,C as equalityPinnedFields,T as fromBase64,U as isLiveForCompanion,q as normalizeOrderKeys,P as softDeleteScope,h as tiebreakDirectionFor,R as toBase64,j as uniqueIndexFields};
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{LunoraError as D}from"@lunora/errors";import{stableWireKey as S}from"./stableWireKey-D2US4k_J.mjs";import{runSql as E}from"./runDrizzle-Du5HLitO.mjs";import{encodeCursor as w,CURSOR_PREFIX as C}from"./CURSOR_PREFIX-
|
|
1
|
+
import{LunoraError as D}from"@lunora/errors";import{stableWireKey as S}from"./stableWireKey-D2US4k_J.mjs";import{runSql as E}from"./runDrizzle-Du5HLitO.mjs";import{encodeCursor as w,CURSOR_PREFIX as C}from"./CURSOR_PREFIX-BX8jkMJa.mjs";import{ConflictError as x}from"./ConflictError-C8GtJmjS.mjs";const i="__lunora_migrations",M=100,y=3e4,U=1e4,$=e=>{E(e,`CREATE TABLE IF NOT EXISTS "${i}" (
|
|
2
2
|
id TEXT PRIMARY KEY,
|
|
3
3
|
direction TEXT NOT NULL,
|
|
4
4
|
status TEXT NOT NULL,
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{LunoraError as u}from"@lunora/errors";import{i as v,R as N}from"./relation-operators-BEg-CvCH.mjs";import{isMemoryTable as y}from"./clearMemoryTables-CogAvVHR.mjs";import{distinctValues as $}from"./applyOnDelete-
|
|
1
|
+
import{LunoraError as u}from"@lunora/errors";import{i as v,R as N}from"./relation-operators-BEg-CvCH.mjs";import{isMemoryTable as y}from"./clearMemoryTables-CogAvVHR.mjs";import{distinctValues as $}from"./applyOnDelete-DJsOG8tz.mjs";import{RELATION_EXISTS_KEY as j}from"./RELATION_EXISTS_KEY-CFUhnZSZ.mjs";const E={every:{kind:"many",negateChild:!0,negated:!0},is:{kind:"one",negated:!1},isNot:{kind:"one",negated:!0,nullDisjunct:!0},none:{kind:"many",negated:!0},some:{kind:"many",negated:!1}},O=e=>N.has(e)?e:void 0,R=e=>{const t=O(e),r=t===void 0?void 0:E[t];if(!r)throw new u("INTERNAL",`unknown relation operator "${e}"`);return r},S=e=>e.kind==="one"?{clause:e.field,project:e.references}:{clause:e.references,project:e.field},M=5e3,h=Symbol("relation-key-overflow"),m=e=>Array.isArray(e)?e.map(t=>t??{}):[],w=e=>{if(e.length===1){const[t]=e;return t??{}}return e.length===0?{}:{AND:e}},b=e=>v(e),l=(e,t,r)=>{const n=t.tables[r]?.relationMap??{};return Object.keys(e).some(s=>{const a=e[s];return s==="AND"||s==="OR"?m(a).some(o=>l(o,t,r)):s==="NOT"?l(a??{},t,r):!!n[s]&&b(a)})},H=(e,t,r,n)=>{if(e&&l(e,t,r))throw new u("INTERNAL",`relation-crossing predicates are not supported in ${n}() — use them in findMany/findFirst or an RLS read policy`)},L=async(e,t,r,n,s)=>{const a=await d(t,e.table,n),{page:o}=await n.fetcher(e.table,{baseWhere:n.relationBaseWhere?.(e.table),relationBaseWhere:n.relationBaseWhere,where:a}),i=$(o,r);if(i.length>n.maxRelationKeys){if(s)return h;throw new u("INTERNAL",`relation predicate on "${e.table}" matched ${String(i.length)} rows, exceeding the ${String(n.maxRelationKeys)}-key limit; narrow the predicate (a same-shard EXISTS push-down lifts this cap)`)}return i},P=async(e,t,r,n,s)=>{const a=R(e),{clause:o,project:i}=S(t),c=await L(t,a.negateChild?{NOT:r}:r,i,n,s);return c===h?h:a.negated?a.nullDisjunct?{OR:[{[o]:{notIn:c}},{[o]:{isNull:!0}}]}:{[o]:{notIn:c}}:{[o]:{in:c}}},p=async(e,t,r,n,s)=>{const a=R(e),o=s.relationBaseWhere?.(t.table),i=a.negateChild?{NOT:r}:r,T={childWhere:await d(o?{AND:[o,i]}:i,t.table,s),negated:a.negated,parentTable:n,relation:t};return{[j]:T}},_=(e,t,r)=>{const n=O(e),s=n===void 0?void 0:E[n];if(s&&s.kind!==r.kind)throw new u("INTERNAL",`relation operator "${e}" requires a to-${s.kind} relation, but "${t}" is to-${r.kind}`)},k=async(e,t,r,n,s)=>{const a=[];for(const o of Object.keys(r)){_(o,e,t);const i=r[o]??{},c=s.canPushExists?.(t)??!1;if(c&&s.existsPushMode==="always"){a.push(await p(o,t,i,n,s));continue}const f=await P(o,t,i,s,c);f===h?a.push(await p(o,t,i,n,s)):a.push(f)}return w(a)},I=async(e,t,r,n)=>{if(e==="AND"||e==="OR"){const a=[];for(const o of m(t))a.push(await d(o,r,n));return{[e]:a}}if(e==="NOT")return{NOT:await d(t??{},r,n)};const s=n.schema.tables[r]?.relationMap?.[e];return s&&b(t)?k(e,s,t,r,n):{[e]:t}},d=async(e,t,r)=>{const n=[];for(const s of Object.keys(e))n.push(await I(s,e[s],t,r));return w(n)},Y=async(e,t)=>!e||!l(e,t.schema,t.tableName)?e:d(e,t.tableName,{canPushExists:t.canPushExists,existsPushMode:t.existsPushMode??"auto",fetcher:t.fetcher,maxRelationKeys:t.maxRelationKeys??M,relationBaseWhere:t.relationBaseWhere,schema:t.schema}),g=(e,t,r)=>{for(const n of e){const s=A(n,t,r);if(s)return s}},D=(e,t,r,n)=>{if(e==="AND"||e==="OR")return g(m(t),r,n);if(e==="NOT")return g([t??{}],r,n);const s=r.tables[n]?.relationMap?.[e];if(!(!s||!b(t)))return r.tables[s.table]?.shardMode?.kind==="shardBy"?{kind:"shard",relation:e,target:s.table}:y(r.tables[s.table])?{kind:"memory",relation:e,target:s.table}:g(Object.values(t),r,s.table)},A=(e,t,r)=>{for(const n of Object.keys(e)){const s=D(n,e[n],t,r);if(s)return s}},q=(e,t,r)=>{if(y(t.tables[r]))throw Object.assign(new Error(`shape on "${r}" replicates from the changelog, which never records a .memory() table — the shape would seed once and never update again. Fix it by (a) dropping .memory() from "${r}" so its writes reach the changelog, or (b) reading it through a live query (\`useQuery\`), which refreshes off the changed-table set rather than the log.`),{code:"SHAPE_MEMORY_TABLE",name:"LunoraError",status:400});if(!e)return;const n=A(e,t,r);if(n)throw n.kind==="memory"?Object.assign(new Error(`shape on "${r}" joins the .memory() table "${n.target}" via relation "${n.relation}" — writes to a .memory() table never reach the changelog, so the shape is never told its membership changed and would serve stale rows indefinitely. Fix it by (a) dropping .memory() from "${n.target}", or (b) reading it through a live query (\`useQuery\`), which refreshes off the changed-table set rather than the log.`),{code:"SHAPE_MEMORY_TABLE",name:"LunoraError",status:400}):Object.assign(new Error(`shape on "${r}" joins the sharded table "${n.target}" via relation "${n.relation}" — a live shape cannot replicate rows that live in another shard's Durable Object. Fix it by (a) denormalizing the joined columns into "${r}", or (b) moving "${n.target}" to .global() so it is served through the latency-tiered D1 shape tier.`),{code:"SHAPE_CROSS_SHARD_JOIN",name:"LunoraError",status:400})};export{M as DEFAULT_MAX_RELATION_KEYS,H as assertFlatPredicate,q as assertShapeShardable,l as containsRelationPredicate,b as isRelationPredicate,Y as resolveRelationPredicates};
|
package/dist/packem_shared/{DEFAULT_MAX_RELAYS-DnAAv8zm.mjs → DEFAULT_MAX_RELAYS-hdowkC2x.mjs}
RENAMED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{toErrorBody as k,LunoraError as D}from"@lunora/errors";import{e as N,d as v}from"./wire-codec-C-FpWm52.mjs";import{sql as y}from"drizzle-orm";import{runDrizzle as m}from"./runDrizzle-Du5HLitO.mjs";import{WORKERD_SQLITE_LIMITS as F}from"./WORKERD_SQLITE_LIMITS-DBH23L_S.mjs";import{d as U,w,a as A,m as $,r as K,b as Y,c as W}from"./ctx-db-relay-shapes-
|
|
1
|
+
import{toErrorBody as k,LunoraError as D}from"@lunora/errors";import{e as N,d as v}from"./wire-codec-C-FpWm52.mjs";import{sql as y}from"drizzle-orm";import{runDrizzle as m}from"./runDrizzle-Du5HLitO.mjs";import{WORKERD_SQLITE_LIMITS as F}from"./WORKERD_SQLITE_LIMITS-DBH23L_S.mjs";import{d as U,w,a as A,m as $,r as K,b as Y,c as W}from"./ctx-db-relay-shapes-DuqhDLw8.mjs";import{envPositiveInt as g}from"./envOptionalPositiveInt-D2pY-c64.mjs";import{relayName as R,DEFAULT_PROMOTION_THRESHOLDS as T,nextPromotionState as B,shapeRoutingKey as _,relayProxyKey as M,parseRelayName as H,clampPromotionThresholds as q}from"./DEFAULT_PROMOTION_THRESHOLDS-91RH_llq.mjs";import{encodeRowsPatch as X,buildPokeFrames as O}from"./buildPokeFrames-BBE6J91z.mjs";import{v as j,R as L,s as z,a as G,b as J}from"./sibling-channel-BkL5cTCc.mjs";import{awaitWsDrain as V,trySendFrame as x}from"./awaitWsDrain-apizgmKY.mjs";import{stableWireKey as b}from"./stableWireKey-D2US4k_J.mjs";const f="__lunora_relay_memos",Q=i=>{m(i,y`CREATE TABLE IF NOT EXISTS ${y.identifier(f)} (
|
|
2
2
|
connection_id TEXT NOT NULL,
|
|
3
3
|
sub_id TEXT NOT NULL,
|
|
4
4
|
cursor INTEGER NOT NULL,
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{LunoraError as m}from"@lunora/errors";import{stableWireKey as a}from"./stableWireKey-D2US4k_J.mjs";const i="::relay::",w=(t,n)=>`${t}${i}${String(n)}`,f=t=>{const n=t.lastIndexOf(i);if(n===-1)return;const o=t.slice(0,n),e=t.slice(n+i.length),r=Number(e);if(!(o.length===0||!Number.isInteger(r)||r<0||String(r)!==e))return{ownerKey:o,relayIndex:r}},l=(t,n)=>a({args:n??{},name:t}),d=(t,n,o)=>`${String(t)}:${n}:${o}`,c={tDown:4e3,tUp:8e3},g=(t,n,o=c)=>{if(o.tDown>=o.tUp)throw new m("INTERNAL",`invalid promotion thresholds: tDown (${String(o.tDown)}) must be < tUp (${String(o.tUp)})`);return t==="owned"?n>=o.tUp?"promoted":"owned":n<o.tDown?"owned":"promoted"},x=(t,n)=>n<t?{tDown:n,tUp:t}:{tDown:Math.min(Math.max(1,Math.floor(t/2)),t-1),tUp:t},N=(t,n,o)=>{if(t<=n||n<=0)return 0;const e=t-n,r=Math.ceil(e/n);return Math.min(r,Math.max(0,o))};export{c as DEFAULT_PROMOTION_THRESHOLDS,
|
|
1
|
+
import{LunoraError as m}from"@lunora/errors";import{stableWireKey as a}from"./stableWireKey-D2US4k_J.mjs";const i="::relay::",w=(t,n)=>`${t}${i}${String(n)}`,f=t=>{const n=t.lastIndexOf(i);if(n===-1)return;const o=t.slice(0,n),e=t.slice(n+i.length),r=Number(e);if(!(o.length===0||!Number.isInteger(r)||r<0||String(r)!==e))return{ownerKey:o,relayIndex:r}},l=(t,n)=>a({args:n??{},name:t}),d=(t,n,o)=>`${String(t)}:${n}:${o}`,c={tDown:4e3,tUp:8e3},g=(t,n,o=c)=>{if(o.tDown>=o.tUp)throw new m("INTERNAL",`invalid promotion thresholds: tDown (${String(o.tDown)}) must be < tUp (${String(o.tUp)})`);return t==="owned"?n>=o.tUp?"promoted":"owned":n<o.tDown?"owned":"promoted"},x=(t,n)=>n<t?{tDown:n,tUp:t}:{tDown:Math.min(Math.max(1,Math.floor(t/2)),t-1),tUp:t},N=(t,n,o)=>{if(t<=n||n<=0)return 0;const e=t-n,r=Math.ceil(e/n);return Math.min(r,Math.max(0,o))};export{c as DEFAULT_PROMOTION_THRESHOLDS,x as clampPromotionThresholds,g as nextPromotionState,f as parseRelayName,N as relayCountFor,w as relayName,d as relayProxyKey,l as shapeRoutingKey};
|
package/dist/packem_shared/{DurableStreamRunner-C4SbxTDz.mjs → DurableStreamRunner-Dk9Pn-B8.mjs}
RENAMED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{toErrorBody as R,LunoraError as k}from"@lunora/errors";import{e as A}from"./wire-codec-C-FpWm52.mjs";import{readStreamRun as w,deleteStreamRun as T,claimStreamRun as _,appendStreamChunk as y,finishStreamRun as E,trimStreamRuns as b,readStreamChunks as v}from"./appendStreamChunk-
|
|
1
|
+
import{toErrorBody as R,LunoraError as k}from"@lunora/errors";import{e as A}from"./wire-codec-C-FpWm52.mjs";import{readStreamRun as w,deleteStreamRun as T,claimStreamRun as _,appendStreamChunk as y,finishStreamRun as E,trimStreamRuns as b,readStreamChunks as v}from"./appendStreamChunk-7ZyAZGg_.mjs";const S=5e4,p=64*1024*1024,M=864e5,N=36e5,L=(i,e)=>{const r=i?.startedAt??e.live?.generation;return e.resuming&&e.generation!==void 0&&r!==void 0&&e.generation!==r?"interrupted":e.live!==void 0?"attach":i===void 0?e.resuming?"interrupted":"attach":i.status==="complete"||i.status==="error"?e.resuming?"replay-terminal":"reclaim":e.resuming?"interrupted":"reclaim"},O=(i,e,r)=>{(i||r())&&e.fail({code:"STREAM_INTERRUPTED",message:i?"the run this durable stream resumed from no longer exists; start a new run":"the producer for this durable stream did not survive; start a new run"})};class I{lastTrimAt=0;runs=new Map;sql;waitUntil;constructor(e){this.sql=e.sql,this.waitUntil=e.waitUntil}async attach(e){try{await this.attachOrThrow(e)}catch(r){const{body:t,redacted:o}=R(r,{fallbackCode:"INTERNAL_SERVER_ERROR",redactedMessage:"internal error"});o&&console.error("[@lunora/shard-engine] durable stream attach failed:",r),e.sink.fail({code:t.code,message:t.message})}finally{this.trim(this.sql())}}detach(e,r){this.runs.get(e)?.sinks.delete(r)}isLive(e){return this.runs.has(e)}async attachOrThrow(e){const r=this.sql(),{runKey:t,sinceChunk:o,sink:c}=e,s=w(r,t),u=o>0,n=this.runs.get(t),a=s?.startedAt??n?.generation,l=L(s,{generation:e.generation,live:n,resuming:u}),d=()=>{for(const g of v(r,t,o))if(!c.chunk({data:JSON.parse(g.dataJson),generation:a,seq:g.seq}))return!1;return!0};if(l==="replay-terminal"){d()&&(s?.status==="error"?c.fail({code:s.errorCode??"INTERNAL_SERVER_ERROR",message:s.error??"stream failed"}):c.complete());return}if(l==="interrupted"){O(e.generation!==void 0&&a!==void 0&&e.generation!==a,c,d);return}if(n){d()&&n.sinks.add(c);return}l==="reclaim"&&T(r,t);const m=Math.max(Date.now(),s===void 0?0:s.startedAt+1);_(r,t,m,e.ttlMs??M);const h={generation:m,sinks:new Set([c])};this.runs.set(t,h);const f=this.produce(t,e.iterator,h);this.waitUntil?.(f),await f}async produce(e,r,t){const o=this.sql(),c=new AbortController;let s=0,u=0;try{for await(const n of r(c.signal)){const a=A(n),l=JSON.stringify(a);if(s+=1,u+=l.length,s>S||u>p)throw new k("STREAM_TOO_LONG",`durable stream exceeded its ceiling (${String(S)} chunks / ${String(p)} bytes); yield less, or drop \`durable\``,{status:507});y(o,e,s,l);for(const d of t.sinks)d.chunk({data:a,generation:t.generation,seq:s})||t.sinks.delete(d)}E(o,e,"complete",s);for(const n of t.sinks)n.complete()}catch(n){const{body:a,redacted:l}=R(n,{fallbackCode:"INTERNAL_SERVER_ERROR",redactedMessage:"internal error"});l&&console.error("[@lunora/shard-engine] unhandled durable stream error:",n),E(o,e,"error",s,{code:a.code,message:a.message});for(const d of t.sinks)d.fail({code:a.code,message:a.message})}finally{this.runs.delete(e)}}trim(e){const r=Date.now();if(!(r-this.lastTrimAt<=N)){this.lastTrimAt=r;try{b(e,r,new Set(this.runs.keys()))}catch{}}}}export{I as DurableStreamRunner,p as MAX_DURABLE_STREAM_BYTES,S as MAX_DURABLE_STREAM_CHUNKS,L as decideDurableAttach};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{LunoraError as $}from"@lunora/errors";import{D as ut}from"./MAX_TOKEN_LENGTH-BakL9FUy-B3VwYY8C.mjs";import{S as En,l as qe,h as Sn}from"./fts-companion-pUdD6kF-.mjs";import{sql as c}from"drizzle-orm";import{d as _n}from"./wire-codec-C-FpWm52.mjs";import{stableWireKey as It}from"./stableWireKey-D2US4k_J.mjs";import{throwingScheduler as Rn,aggregateSqlFunction as We,normalizeCountArgument as vn}from"./AGGREGATE_SQL_FUNCTION-DDEoMnJR.mjs";import{aggregateTableName as Xe,encodeAggregateKey as Ze,readAggregateValue as et}from"./aggregateTableName-C7o-gpms.mjs";import{mergeWhere as N,CountRlsUnsupportedError as tt,selectIndexForGroupBy as Tn,selectIndexForCount as An,selectIndexForAggregate as In}from"./CountRlsUnsupportedError-BvsDqfO2.mjs";import{backfillSearchIndexesForTable as Cn,searchIndexCoversTable as xn}from"./backfillAggregateIndexes-B_3xdOgV.mjs";import{backfillAggregateIndexes as Gr,backfillRankIndexes as Nr,backfillSearchIndexes as jr}from"./backfillAggregateIndexes-B_3xdOgV.mjs";import{appendCdcChange as bn,readCdcDocAtOrBefore as Mn}from"./CDC_LOG_TABLE-QaBxSIZM.mjs";import{CDC_LOG_TABLE as Qr,applyCdcChanges as Vr,bumpCdcEpoch as zr,cdcCanVouchFor as Jr,cdcForkedError as Yr,cdcSeqLeavingRows as Xr,cdcTouchesTables as Zr,cdcTrimmedError as ei,compactCdcDocs as ti,cursorBelowRetainedFloor as ni,minCdcReplayableSeq as oi,minCdcSeq as ri,readCdcChangeKeys as ii,readCdcChanges as si,readCdcCursor as ci,readCdcEpoch as ai,trimCdcChanges as di}from"./CDC_LOG_TABLE-QaBxSIZM.mjs";import{allocateCommitSeq as Dn,COMMIT_SEQ_FIELD as kn}from"./COMMIT_SEQ_FIELD-BY_vc9bw.mjs";import{createCompanionSync as Fn}from"./createCompanionSync-Rjn0lsT6.mjs";import{isMemoryTable as Ct}from"./clearMemoryTables-CogAvVHR.mjs";import{computeRankPage as xt}from"./computeRankPage-3AiKfT8q.mjs";import{SCAN_DEP as G}from"./SCAN_DEP-D7qE3iUe.mjs";import{runSql as ve,runDrizzle as j}from"./runDrizzle-Du5HLitO.mjs";import{j as Oe,D as oe,r as Se,k as de,b as Be,A as nt,a as Pe,e as ce,o as Ln,t as Zt,q as bt,i as qn,h as en,g as Wn}from"./do-sql-BEFrJUds.mjs";import{renderSql as tn,unionAll as ft,WORKERD_SQLITE_LIMITS as nn,sqliteInList as Bn}from"./WORKERD_SQLITE_LIMITS-DBH23L_S.mjs";import{coveringGeohashes as Pn,boundingBoxGeohashes as Un,haversineMeters as Hn,pointInBoundingBox as On}from"./GEO_DEFAULT_PRECISION-CqpQZ-J_.mjs";import{NotFoundError as Gn}from"./NotFoundError-BhF7FeFr.mjs";import{tiebreakDirectionFor as Nn,encodeCursor as Ge,normalizeOrderKeys as ct,uniqueIndexFields as on,buildSeekWhere as rn,decodeCursor as at,buildSeekBeforeWhere as jn,softDeleteScope as ue,equalityPinnedFields as Kn,applySelect as Mt}from"./CURSOR_PREFIX-BX8jkMJa.mjs";import{rankTableName as Dt,sortColumnName as kt,resolveRankPartition as Qn,encodePartitionKey as Vn,RANK_TIEBREAK as zn,rankPivotConditionSql as Jn}from"./RANK_TIEBREAK-B0_x8iev.mjs";import{UNVOUCHABLE_DEP as Ft}from"./UNVOUCHABLE_DEP-C68htACn.mjs";import{indexKeysForRow as Yn,buildIndexRange as Xn}from"./buildIndexRange-6nIZDf4m.mjs";import{r as Ne,j as _e,c as te,t as je,i as Lt}from"./where-sql-DFs8Zw7-.mjs";import{serializeSqlValue as ae}from"./serializeSqlValue-BbZ5hKM7.mjs";import{quoteIdentifier as Te}from"./quoteIdentifier-CObIFRhb.mjs";import{whereOfFilter as Zn,isPushableWhere as eo}from"./isPushableWhere-BeYAOjUb.mjs";import{deriveRelationEdges as to,findRelated as no}from"./RELATED_DEFAULT_LIMIT-CBYQQIrZ.mjs";import{assertFlatPredicate as ot,resolveRelationPredicates as qt}from"./DEFAULT_MAX_RELATION_KEYS-CYPZfQH9.mjs";import{runRowValidators as rt,resolveWith as Wt,relationHooks as Bt,applyOnDelete as oo,fanOutScalarCounts as ro}from"./applyOnDelete-DJsOG8tz.mjs";import{guardWriter as io}from"./RLS_UNWRAP_SYMBOL-rSxYzw-G.mjs";import{mayHoldProjectedValue as so}from"./BIGINT_KEY_DIGITS-C9a7Ix7k.mjs";import{createSystemReader as co}from"./createSystemReader-DcDLFfC-.mjs";import{ConflictError as Re}from"./ConflictError-C8GtJmjS.mjs";import{runTriggers as ao}from"./hasTrigger-CjlwI4le.mjs";import{advanceClientWatermark as ui,migrateClientWatermark as fi,readClientWatermark as hi}from"./CLIENT_WATERMARK_TABLE-vLjfNhBR.mjs";import{IDEMPOTENCY_TABLE as pi,readIdempotent as gi,trimIdempotent as yi,writeIdempotent as $i}from"./IDEMPOTENCY_TABLE-AOJCuq5U.mjs";import{runShardMigrations as Ei}from"./runShardMigrations-MXioI81k.mjs";import{selectShapeMembers as _i,selectShapeRows as Ri}from"./selectShapeMembers-BXhvEt4X.mjs";const lo=n=>{const r=atob(n),o=Uint8Array.from(r,d=>d.codePointAt(0)??0);return new TextDecoder().decode(o)},uo=()=>new $("BAD_REQUEST","invalid cursor"),Pt=16,Ut=8,z=1024,ht=(n,r)=>r.query(n),fo=(n,r)=>{if(n.length===0)return 0;let o=0;for(const[d,i]of r.entries()){const w=d===r.length-1;let _=0;for(const E of n)(w?E.startsWith(i):E===i)&&(_+=1);if(_===0)return 0;o+=_}return o},ho=(n,r)=>{if(!r)return{exact:!0,lower:n,upper:n};const o=[...n].at(-1)??"",d=(o.codePointAt(0)??0)+1;if(d>=55296&&d<=57343||d>1114111)return{exact:!0,lower:n,upper:n};const i=n.slice(0,n.length-o.length);return{exact:!1,lower:n,upper:i+String.fromCodePoint(d)}},wo=(n,r,o)=>{const d={eq:(i,w)=>{if(!n.definition.filterFields?.includes(i))throw new $("INTERNAL",`field "${i}" is not a filter field of search index "${n.indexName}" on table "${r}"`);if(n.filters.length>=Ut)throw new $("BAD_REQUEST",`search index "${n.indexName}" on table "${r}": at most ${String(Ut)} .eq() filters are supported per search query`);return n.filters.push({field:i,value:w}),d},search:(i,w)=>{const _=n;if(i!==_.definition.field)throw new $("INTERNAL",`search index "${_.indexName}" on table "${r}" indexes "${_.definition.field}", not "${i}"`);const E=ht(w,o).length;if(E>Pt)throw new $("BAD_REQUEST",`search index "${_.indexName}" on table "${r}": at most ${String(Pt)} search terms are supported (got ${String(E)})`);return _.field=i,_.query=w,_.hasQuery=!0,d}};return d},po=n=>{if(n.length>z)throw new $("BAD_REQUEST",`more than ${String(z)} documents match this search — narrow it with filters or read it a page at a time with .paginate()`)},go=n=>Math.min(n.offset+n.numItems+1,z),yo=n=>btoa(`search:${String(n)}`),$o=n=>{let r;try{r=lo(n)}catch{return}if(!r.startsWith("search:"))return;const o=Number(r.slice(7));return Number.isInteger(o)&&o>=0?o:void 0},mo=n=>{if(typeof n.endCursor=="string")throw new $("BAD_REQUEST","bounded (endCursor) pagination is not supported on search queries — relevance order has no stable range boundary");if(!Number.isFinite(n.numItems))throw new $("BAD_REQUEST",`search pagination needs a finite numItems, got ${String(n.numItems)}`);const r=Math.max(0,Math.floor(n.numItems)),o=n.cursor?$o(n.cursor):0;if(o===void 0)throw uo();if(o+r>=z)throw new $("BAD_REQUEST",`search pagination reaches the ${String(z)}-document limit (offset ${String(o)} + ${String(r)} requested) — a page must end below the cap so the probe row that answers \`hasMore\` still fits: retry with numItems ${String(Math.max(1,z-o-1))} or fewer, or narrow the query or the filters instead`);return{numItems:r,offset:o}},Eo=(n,r)=>{const o=r.offset+r.numItems,d=r.numItems>0&&n.length>o;return{continueCursor:d?yo(o):null,isDone:!d,page:n.slice(r.offset,o)}},So=n=>{if(n===void 0)return z+1;if(!Number.isFinite(n))return z;const r=Math.max(0,Math.floor(n));if(r>z)throw new $("BAD_REQUEST",`search returns at most ${String(z)} documents (asked for ${String(r)}) — narrow the query or paginate instead`);return r},_o=32,Ro=1024,sn=(n,r,o,d)=>{const i=`SELECT id, _creationTime, ${Te(oe)} FROM ${Te(n)}`,w=`ORDER BY ${o}${d===void 0?"":` LIMIT ${String(d)}`}`;return r===void 0?Ne(`${i} ${w}`):_e(`${i} WHERE `,r,` ${w}`)},wt={fieldRef:n=>Ne(Oe(n)),serialize:ae},cn=n=>{const r=n.map(o=>`${Oe(o.field)} ${o.direction==="desc"?"DESC":"ASC"}`);return n.some(o=>o.field==="_id"||o.field==="id")||r.push(`${Oe("id")} ${Nn(n)==="desc"?"DESC":"ASC"}`),r.join(", ")},vo={"<":"lt","<=":"lte","=":"eq",">":"gt",">=":"gte"},an=n=>new Set(n.sqlConditions.filter(r=>r.comparator==="=").map(r=>r.field)),To=n=>{const r=an(n);let o=0;for(;o<n.indexFields.length&&r.has(n.indexFields[o]??"");)o+=1;return n.indexFields.slice(o)},Ao=(n,r)=>{const o=n.order,d=To(n),{shape:i}=r;return d.length>0?ct(d.map(w=>({[w]:o})),i,{pinned:an(n),uniqueBy:on(r.indexes,i)}):ct([{_creationTime:o}],i)},Io=(n,r,o,d)=>{const i=n.sqlConditions.map(w=>({[w.field]:{[vo[w.comparator]??"eq"]:w.value}}));if(o&&i.push(rn(r,at(o))),d&&i.push(jn(r,at(d))),i.length!==0)return i.length===1?i[0]:{AND:i}},Co=n=>{if(n.want!==void 0)return n.selective?Math.max(n.want,_o):n.want},dt=(n,r,o,d,i,w,_)=>{const E=Ao(d,o),x=cn(E),g=[],{filters:b,want:T}=w;let R=w.cursor??void 0,M=Co(w);if(T===0)return{documents:g,orderKeys:E};for(;;){const q=te(Io(d,E,R,w.endCursor),wt,je),W=sn(r,i&&q?_e(q," AND ",i):i??q,x,M),L=ve(n,W.text,...W.params).toArray();let P={};_(L.length);for(const C of L)if(P=Se(C),b.every(ne=>ne(P))&&g.push(P)===T)return{documents:g,orderKeys:E};if(M===void 0||L.length<M)return{documents:g,orderKeys:E};R=Ge(P,E),M=Math.max(M,Math.min(M*2,Ro))}},xo=(n,r,o,d,i,w,_,E)=>{const x=Math.max(0,Math.floor(i.numItems));if(typeof i.endCursor=="string"){const{documents:q,orderKeys:W}=dt(n,r,o,d,w,{cursor:i.cursor,endCursor:i.endCursor,filters:_.all,selective:_.selective,want:void 0},E),L=q.length>=2?q[Math.floor(q.length/2)-1]:void 0;return{continueCursor:i.endCursor,isDone:!0,page:q,splitCursor:L?Ge(L,W):null}}const{documents:g,orderKeys:b}=dt(n,r,o,d,w,{cursor:i.cursor,filters:_.all,selective:_.selective,want:x+1},E),T=g.length>x,R=T?g.slice(0,x):g,M=R.at(-1);return{continueCursor:T&&M?Ge(M,b):null,isDone:!T,page:R}},Ke=n=>{const r=new Map;return o=>{const d=r.get(o);if(d!==void 0)return d;const i=n(Te(o));return r.set(o,i),i}},fe=Te(oe),bo=Ke(n=>`INSERT INTO ${n} (id, _creationTime, ${fe}) VALUES (?, ?, ?)`),Ht=Ke(n=>`UPDATE ${n} SET ${fe} = ? WHERE id = ? AND ${fe} = ?`),Mo=Ke(n=>`UPDATE ${n} SET _creationTime = ?, ${fe} = ? WHERE id = ? AND ${fe} = ?`),Do=Ke(n=>`DELETE FROM ${n} WHERE id = ? AND ${fe} = ?`),ko="SELECT changes() AS changed",Ot=new Map,Fo="",Lo=n=>{const r=JSON.stringify(n),o=Ot.get(r);if(o!==void 0)return o;const d=n.map(w=>c`SELECT ${c.raw(`'${w.replaceAll("'","''")}'`)} AS __t__, id, _creationTime, ${c.identifier(oe)} FROM ${c.identifier(w)} WHERE id = ${Fo}`),{sql:i}=tn("sqlite",c`${ft(d)} LIMIT 1`);return Ot.set(r,i),i},qo=(n,r)=>r.map(()=>n),Wo=/^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/iu,Bo=n=>{if(!Wo.test(n))throw new $("INTERNAL",`invalid clientId ${JSON.stringify(n)}: a client-supplied row id must be a UUID`)},Gt=50,dn=500,Ue=Math.floor(nn.boundParams/3),me=nn.boundParams,Po=128,le=(n,r,o)=>{const d=r??dn;if(n>d)throw new $("BATCH_LIMIT_EXCEEDED",`${o}: batch of ${String(n)} exceeds the limit of ${String(d)} (raise options.limit or chunk the call)`,{status:400})},Uo=n=>{const r={eq:(o,d)=>(n.sqlConditions.push({comparator:"=",field:o,value:d}),r),gt:(o,d)=>(n.sqlConditions.push({comparator:">",field:o,value:d}),r),gte:(o,d)=>(n.sqlConditions.push({comparator:">=",field:o,value:d}),r),lt:(o,d)=>(n.sqlConditions.push({comparator:"<",field:o,value:d}),r),lte:(o,d)=>(n.sqlConditions.push({comparator:"<=",field:o,value:d}),r)};return r},Ho=n=>Math.max(n,z),ln=(n,r)=>{const o=n.filters.map(d=>c`${ce(d.field)} = ${ae(d.value)}`);return r&&o.push(r),o},Oo=(n,r,o,d,i)=>{const w=ht(o.query,ut(o.definition.language));if(w.length===0)return[];const _=En(r,o.indexName),E=`${_}__vocab`,x=w.length-1,g=w.map((W,L)=>{const P=ho(W,L===x),C=P.exact?c`${c.identifier("term")} = ${P.lower}`:c`${c.identifier("term")} >= ${P.lower} AND ${c.identifier("term")} < ${P.upper}`;return c`SELECT ${c.identifier("doc")}, ${c.raw(String(L))} AS ${c.identifier("__term__")}, COUNT(*) AS ${c.identifier("__n__")} FROM ${c.identifier(E)} WHERE ${C} GROUP BY ${c.identifier("doc")}`}),b=w.map((W,L)=>c`SUM(CASE WHEN u.${c.identifier("__term__")} = ${c.raw(String(L))} THEN u.${c.identifier("__n__")} ELSE 0 END)`),T=c`SELECT f.${c.identifier(qe)} AS ${c.identifier(qe)}, ${c.join(b,c` + `)} AS ${c.identifier("__score__")} FROM (${ft(g)}) u JOIN ${c.identifier(_)} f ON f.rowid = u.${c.identifier("doc")} GROUP BY f.${c.identifier(qe)} HAVING ${c.join(b.map(W=>c`${W} > 0`),c` AND `)}`,R=ln(o,i);let M=c`SELECT m.id, m._creationTime, m.${c.identifier(oe)}, s.${c.identifier("__score__")} AS ${c.identifier("__score__")} FROM (${T}) s JOIN ${c.identifier(r)} m ON m.id = s.${c.identifier(qe)}`;R.length>0&&(M=c`${M} WHERE ${c.join(R,c` AND `)}`),M=c`${M} ORDER BY s.${c.identifier("__score__")} DESC, m._creationTime DESC, m.id ASC LIMIT ${c.raw(String(d))}`;const q=[];for(const W of j(n,M)){const L=en(W);if(L){const P=W.__score__;q.push({document:L,score:typeof P=="number"?P:Number(P??0)})}}return q},Go=(n,r,o,d,i)=>{const w=ut(o.definition.language),_=ht(o.query,w);if(_.length===0)return[];const E=ln(o,i);let x=c`SELECT id, _creationTime, ${c.identifier(oe)} FROM ${c.identifier(r)}`;E.length>0&&(x=c`${x} WHERE ${c.join(E,c` AND `)}`),x=c`${x} ORDER BY _creationTime DESC, id ASC LIMIT ${c.raw(String(Ho(d)))}`;const g=j(n,x).toArray(),b=[];for(const T of g){const R=en(T);if(!R)continue;const M=fo(Sn(R,o.definition),_);M>0&&b.push({creationTime:typeof R._creationTime=="number"?R._creationTime:0,doc:R,id:typeof R._id=="string"?R._id:"",score:M})}return b.sort((T,R)=>R.score-T.score||R.creationTime-T.creationTime||T.id.localeCompare(R.id)),b.slice(0,d).map(T=>({document:T.doc,score:T.score}))},it=(n,r,o,d)=>{if(!Number.isFinite(n.lat)||n.lat<-90||n.lat>90||!Number.isFinite(n.lng)||n.lng<-180||n.lng>180)throw new $("BAD_REQUEST",`geo index "${d}" on table "${o}": ${r} must have a finite lat in [-90, 90] and lng in [-180, 180]`)},No=(n,r)=>{const o=n,d={near:(i,w)=>{if(o.within)throw new $("INTERNAL",`geo index "${o.indexName}" on table "${r}": call .near() or .within(), not both`);if(it(i,".near() point",r,o.indexName),!Number.isFinite(w)||w<=0)throw new $("BAD_REQUEST",`geo index "${o.indexName}" on table "${r}": .near() radiusMeters must be a finite number > 0, got ${String(w)}`);return o.near={point:{lat:i.lat,lng:i.lng},radiusMeters:w},d},within:i=>{if(o.near)throw new $("INTERNAL",`geo index "${o.indexName}" on table "${r}": call .near() or .within(), not both`);if(it(i.sw,".within() sw corner",r,o.indexName),it(i.ne,".within() ne corner",r,o.indexName),i.sw.lat>i.ne.lat)throw new $("BAD_REQUEST",`geo index "${o.indexName}" on table "${r}": .within() corners are transposed (sw.lat > ne.lat)`);if(i.sw.lng>i.ne.lng)throw new $("BAD_REQUEST",`geo index "${o.indexName}" on table "${r}": .within() box crosses the antimeridian (sw.lng > ne.lng), which is not supported — split it into two boxes at ±180 and union the results`);return o.within={ne:{lat:i.ne.lat,lng:i.ne.lng},sw:{lat:i.sw.lat,lng:i.sw.lng}},d}};return d},jo=(n,r)=>{const o=n[r];if(o===null||typeof o!="object")return;const{lat:d,lng:i}=o;return typeof d=="number"&&typeof i=="number"?{lat:d,lng:i}:void 0},Ko=(n,r)=>{const o=jo(n,r.definition.field);if(!o)return;const d=typeof n._creationTime=="number"?n._creationTime:0;if(r.near){const i=Hn(r.near.point,o);return i<=r.near.radiusMeters?{creationTime:d,distance:i}:void 0}return On(o,r.within)?{creationTime:d,distance:0}:void 0},Qo=(n,r,o,d)=>{if(!o.near&&!o.within)throw new $("INTERNAL",`geo index "${o.indexName}" on table "${r}": call .near(point, radius) or .within(box)`);const i=o.near?Pn(o.near.point,o.near.radiusMeters):Un(o.within),w=Wn(r,o.indexName),_=i.map(T=>c`(g.${c.identifier("__geohash__")} >= ${T} AND g.${c.identifier("__geohash__")} < ${`${T}{`})`),E=[c`(${c.join(_,c` OR `)})`];d&&E.push(d);const x=c`SELECT m.id, m._creationTime, m.${c.identifier(oe)} FROM ${c.identifier(w)} g JOIN ${c.identifier(r)} m ON m.id = g.${c.identifier("__id__")} WHERE ${c.join(E,c` AND `)}`,g=j(n,x).toArray(),b=[];for(const T of g){const R=Se(T),M=R?Ko(R,o):void 0;R&&M&&b.push({creationTime:M.creationTime,distance:M.distance,doc:R})}return b.sort((T,R)=>T.distance-R.distance||R.creationTime-T.creationTime),b},un=(n,r,o,d)=>{const i=[];for(const w of n)if(r.every(_=>_(d(w)))&&(i.push(w),typeof o=="number"&&i.length>=o))break;return i},Vo=(n,r,o,d,i,w=()=>{})=>{const _=o.within!==void 0,E=Qo(n,r,o,i).map(x=>({distanceMeters:_?null:x.distance,document:x.doc}));return w(E.length),typeof d=="number"?E.slice(0,Math.max(0,Math.floor(d))):E},Nt=(n,r,o,d,i,w,_=()=>{})=>{const{geo:E}=o;if(!E)throw new $("INTERNAL","runGeoTerminalScored called without a staged geo query");const x=i.length>0,g=Vo(n,r,E,x?void 0:w,d,_);return x?un(g,i,w,b=>b.document):g},Ee={fieldRef:ce,serialize:ae},fn=(n,r)=>{const o=r===void 0?void 0:n.shape[r];return o!==void 0&&so(o)},jt=(n,r)=>r.some(o=>fn(n,o)),Kt=(n,r,o)=>{if(fn(n,r))throw new $("BAD_REQUEST",`${o}: "${r}" may hold an order-preserving key rather than a value SQL can reduce or group — declare an aggregateIndex covering this (by, field, op) so the maintained companion answers it instead (its running total is a REAL, so it stays exact only while the total is inside 2^53)`)},zo=n=>{let r=0;const o=[],d={fieldRef:i=>Ne(Oe(i)),relationExists:i=>{const{childWhere:w,negated:_,parentTable:E,relation:x}=i,g=`__rel_${String(r)}`,b=o.at(-1)??E;r+=1,n(x.table,G);const T=x.kind==="one"?x.field:x.references,R=x.kind==="one"?x.references:x.field,M=Ne(`${bt(g,R)} = ${bt(b,T)}`);o.push(g);const q=te(w,d,je);o.pop();const W=q===void 0?M:_e(M," AND ",q),L=_e("EXISTS (SELECT 1 FROM ",Lt(x.table)," AS ",Lt(g)," WHERE ",W,")");return _?_e("NOT ",L):L},serialize:ae};return d};class Jo extends ${constructor(r="unique() found more than one matching document"){super("NOT_UNIQUE",r,{name:"NotUniqueError"})}}const Yo=/\s/u,Xo=String.fromCodePoint(0),Qt=(n,r,o)=>{if(!n.tables[r])throw new $("INTERNAL",`unknown table: ${r}`);return typeof o!="string"||o.length===0||Yo.test(o)||o.includes(Xo)?null:o},hn=(n,r,o,d=()=>{},i=()=>{},w=()=>{},_)=>{const E=r.tables[o];if(!E)throw new $("INTERNAL",`unknown table: ${o}`);const x=ue(E.softDeleteMode,void 0),g=_??{indexFields:[],indexName:void 0,inMemoryFilters:[],order:"asc",sqlConditions:[],verifyFilters:[]},b=()=>{const y=N(x,g.pushedWhere);return y?te(y,Ee):void 0},T=()=>{const y=N(x,g.pushedWhere);return y?te(y,wt,je):void 0},R=()=>[...g.inMemoryFilters,...g.verifyFilters];let M=0;const q=y=>{const{search:A}=g;if(!A)throw new $("INTERNAL","runSearchFetch called without a staged search");Cn(n,o,E);const D=g.inMemoryFilters.length>0,F=So(D?void 0:y),X=qn(n);if(X&&!xn(n,o,A.definition))throw new $("SEARCH_INDEX_BUILDING",`search index "${A.indexName}" on table "${o}" is still backfilling and currently covers only part of the table — retry once it finishes, or run the backfillSearch admin operation to complete it now`);const he=b(),J=X?Oo(n,o,A,F,he):Go(n,o,A,F,he);!D&&y===void 0&&po(J);const re=R();return M=J.length,re.length>0?un(J,re,y,Ae=>Ae.document):J},W=y=>q(y).map(A=>A.document),L=y=>{const A=mo(y);return Eo(W(go(A)),A)},P=()=>{if(g.search||g.geo||g.indexName===void 0){i(void 0);return}i(Xn(o,g.indexName,g.indexFields,g.sqlConditions,ae))},C=y=>{P();let A=0;const D=(()=>{if(g.search){const F=W(y);return A=M,F}return g.geo?Nt(n,o,g,b(),R(),y,F=>{A=F}).map(F=>F.document):dt(n,o,E,g,T(),{filters:R(),selective:g.inMemoryFilters.length>0,want:y===void 0?void 0:Math.max(0,Math.floor(y))},F=>{A+=F}).documents})();return w(Math.max(A,D.length)),D},ne=()=>{if(!g.search&&!g.geo)throw new $("INTERNAL",`ctx.db.query("${o}").collectWithScores() requires a staged .withSearchIndex(...) or .withGeoIndex(...)`);P();let y=0;const A=(()=>{if(g.search){const D=q(void 0);return y=M,D}return Nt(n,o,g,b(),R(),void 0,D=>{y=D})})();return w(Math.max(y,A.length)),A},Y={async*[Symbol.asyncIterator](){const y=hn(n,r,o,d,i,w,{...g,indexFields:[...g.indexFields],inMemoryFilters:[...g.inMemoryFilters],sqlConditions:[...g.sqlConditions],verifyFilters:[...g.verifyFilters]});if(g.search){yield*await y.collect();return}let A;for(;;){const D=await y.paginate({cursor:A??null,numItems:Po});if(yield*D.page,D.isDone||D.continueCursor===null)return;A=D.continueCursor}},async collect(){return C(void 0)},async collectWithScores(){return ne()},filter(y){const A=Zn(y);return A!==void 0&&eo(A,E.shape)?(g.pushedWhere=N(g.pushedWhere,A),g.verifyFilters.push(y)):g.inMemoryFilters.push(y),Y},async first(){return C(1)[0]??null},order(y){return g.order=y==="desc"?"desc":"asc",Y},async paginate(y){let A=0;if(P(),g.search){const F=L(y);return w(F.page.length),F}if(g.geo)throw new $("INTERNAL","pagination is not supported on geo queries; use .take(n) or .collect()");const D=xo(n,o,E,g,y,T(),{all:R(),selective:g.inMemoryFilters.length>0},F=>{A+=F});return w(Math.max(A,D.page.length)),D},async take(y){return C(y)},async unique(){const y=C(2);if(y.length>1)throw new Jo(`unique() on table "${o}" matched ${String(y.length)} documents; expected at most one`);return y[0]??null},withGeoIndex(y,A){const D=(E.geoIndexes??[]).find(X=>X.name===y);if(!D)throw new $("INTERNAL",`unknown geo index "${y}" on table "${o}"`);d(o,y,"geo");const F={definition:D,indexName:y};if(g.geo=F,A(No(F,o)),!F.near&&!F.within)throw new $("INTERNAL",`geo index "${y}" on table "${o}" requires a .near(point, radius) or .within(box) call`);return Y},withIndex(y,A){const D=E.indexes.find(F=>F.name===y);if(!D)throw new $("INTERNAL",`unknown index "${y}" on table "${o}"`);return d(o,y,"index"),g.indexName=y,g.indexFields=D.fields,A&&A(Uo(g)),Y},withSearchIndex(y,A){const D=(E.searchIndexes??[]).find(X=>X.name===y);if(!D)throw new $("INTERNAL",`unknown search index "${y}" on table "${o}"`);d(o,y,"search");const F={definition:D,field:D.field,filters:[],hasQuery:!1,indexName:y,query:""};if(g.search=F,A(wo(F,o,ut(D.language))),!F.hasQuery)throw new $("INTERNAL",`search index "${y}" on table "${o}" requires a .search(field, query) call`);return Y}};return Y},Vt=(n,r,o)=>{const d={...r};for(const[i,w]of Zt(n)){if(w.serverDefault){d[i]=w.serverDefault({auth:o});continue}d[i]===void 0&&(w.defaultFn?d[i]=w.defaultFn():"defaultValue"in w&&(d[i]=w.defaultValue))}return d},zt=(n,r,o,d)=>{const i=o;for(const[w,_]of Zt(n)){if(_.serverDefault){w in r&&(i[w]=_.serverDefault({auth:d}));continue}_.onUpdateFn&&!(w in r)&&(i[w]=_.onUpdateFn())}},Jt=(n,r)=>{for(const o of Object.keys(r))if(r[o]===void 0)throw new $("INTERNAL",`Cannot ${n} field '${o}' to undefined — use null to clear a nullable field, or omit the key to leave it unchanged.`)},Yt=["_commitSeq","_creationTime","_id"],st=n=>Yt.some(r=>r in n)?Object.fromEntries(Object.entries(n).filter(([r])=>!Yt.includes(r))):n,Zo=/unique constraint failed/i,er=n=>n instanceof Error&&Zo.test(n.message),tr=/string or blob too big/iu,nr=(n,r)=>{if(!(!(n instanceof Error)||!tr.test(n.message)))throw new $("PAYLOAD_TOO_LARGE",`document is too large to store in "${r}": a single row cannot exceed the storage engine's per-row ceiling (2 MB on a Durable Object's SQLite). The limit is on the STORED bytes, which are UTF-8, and v.bytes()/v.bigint() columns are stored twice on a shard-local table. Keep the payload in R2 (ctx.storage) and store a reference on the row.`)},lt=(n,r,o,d)=>{try{ve(n,o,...d)}catch(i){throw er(i)?new Re(`unique constraint violation on "${r}"`,"unique"):(nr(i,r),i)}},He=(n,r,o,d)=>{if(lt(n,r,o,d),ve(n,ko).one().changed===0)throw new Re(`optimistic concurrency conflict on "${r}" — the row changed during this mutation; refetch and retry`,"occ")},Xt=(n,r,o,d,i,w,_)=>{const E=[];for(let T=0;T<o.length+1;T+=1){const R=o[T],M=d[T],q=M?.direction==="desc"?"desc":"asc",W=R===void 0||M===void 0?c`${c.identifier(zn)} < ${_}`:Jn(R,w[T],q,!1);if(W===void 0)continue;const L=[];for(let C=0;C<T;C+=1)L.push(c`${c.identifier(o[C])} IS ${w[C]}`);L.push(W);const[P]=L;E.push(L.length===1&&P!==void 0?P:c`(${c.join(L,c` AND `)})`)}const x=E.length>0?c.join(E,c` OR `):c`1 = 0`,g=j(n,c`SELECT COUNT(*) AS c FROM ${c.identifier(r)} WHERE ${c.identifier("__partition__")} = ${i} AND (${x})`).one(),b=j(n,c`SELECT COUNT(*) AS c FROM ${c.identifier(r)} WHERE ${c.identifier("__partition__")} = ${i}`).one();return{before:g.c,total:b.c}},Ur=n=>{const{baselineSeq:r,onStalePatchDropped:o}=n,{sql:d}=n,{schema:i}=n,w=n.broadcast??(()=>{}),_=to(i);let E;const x=()=>n.inTransaction?.()===!0,g=e=>i.tables[e]?.commitOrderedMode!==!0?{}:((E===void 0||!x())&&(E=Dn(d)),{[kn]:E}),b=(e,...t)=>{const s=i.tables[e]?.indexes;if(!s||s.length===0)return;const f=[];for(const h of t)h&&f.push(...Yn(s,h,ae));return f.length>0?f:void 0},{headroom:T}=n;let R=!1;const M=async e=>{const t=R;R=!0;try{return await e()}finally{R=t}},q=n.onRead??(()=>{}),W=e=>{Ct(i.tables[e])&&q(Ft,Ft)},L=n.onReadRange??(e=>{q(e.table,G)}),P=e=>{W(e.table),L(e)},C=(e,t)=>{t!==void 0&&t!==G&&!R&&T?.recordRead(1),W(e),q(e,t)},ne=n.onIndexUse??(()=>{}),Y=n.onWrite??(()=>{}),y=e=>{R||T?.recordWrite(e)},A=async e=>{y(e.doc),await Y(e)},{cache:D}=n,F=n.clock??(()=>Date.now()),X=n.idGenerator??(()=>crypto.randomUUID()),he=n.scheduler??Rn,{globalDb:J}=n,re=n.auth??{identity:null,userId:null},Ae=n.cdc??!1,Qe=he,wn=co({scheduler:typeof Qe.list=="function"&&typeof Qe.get=="function"?Qe:void 0,storage:n.storage}),we=(e,t,s,f)=>{Ae&&!Ct(i.tables[e])&&bn(d,F(),e,t,s,f)},pn=(e,t,s,f)=>{if(i.tables[e]?.dropStalePatchesMode!==!0||!Ae)return!1;const h=r?.();if(h===void 0)return!1;const l=Mn(d,e,t,h);return l===void 0?!1:Object.keys(st(s)).some(a=>It(l[a])!==It(f[a]))},ie=e=>i.tables[e]?.shardMode?.kind==="global",pt=(e,t)=>{if(ie(e)){if(!J)throw new $("INTERNAL",`cross-backend ${t} for global table '${e}' requires a globalDb writer — pass one to createShardCtxDb({ globalDb })`);return J}return H},Ve=e=>pt(e,"cascade"),Q=(e,t)=>{if(ie(e)){if(!J)throw new $("INTERNAL",`${t} on global table '${e}' requires a globalDb writer — pass one to createShardCtxDb({ globalDb })`);return J}},gt=async(e,t,s,f,h)=>{h&&y(s);const l=await e.insert(t,s,f);return w({key:l,op:"insert",row:{...s,_id:l},table:t}),l},ze=(e,t)=>pt(e,"relation load").findMany(e,t),yt=(e,t)=>(ie(e)&&C(e,G),ze(e,t)),gn=e=>!ie(e.table),$t=n.relationExistsPushDown??"auto",mt=$t!=="never",{maxRelationKeys:Et}=n,Ie=(e,t,s)=>qt(e,{fetcher:yt,maxRelationKeys:Et,relationBaseWhere:s,schema:i,tableName:t}),St=async(e,t,s,f)=>{const h=Q(e,"relation grouped count");if(h)return C(e,G),ro((U,I)=>h.count(U,I),e,t,s,f);const l=i.tables[e];if(!l)throw new $("INTERNAL",`unknown table: ${e}`);C(e,G);const a=ue(l.softDeleteMode,void 0),u={[t]:{in:s}},p=N(N(u,f),a),v=await Ie(p,e,void 0),m=te(v,Ee),k=ce(t);let S=c`SELECT ${k} AS __fk__, COUNT(*) AS count FROM ${c.identifier(e)}`;m&&(S=c`${S} WHERE ${m}`),S=c`${S} GROUP BY ${k}`;const B=j(d,S).toArray();return new Map(B.map(U=>[U.__fk__,U.count]))};let Ce=0;const _t=new Set;for(const[e,t]of Object.entries(i.tables))for(const s of Object.values(t.triggerMap??{}))_t.add(`${e} ${s.timing} ${s.op}`);const Z=(e,t,s)=>_t.has(`${e} ${t} ${s}`),ee=async(e,t,s)=>{if(Ce+=1,Ce>Gt)throw Ce-=1,new Re(`trigger recursion exceeded ${String(Gt)} levels on "${s.table}" — check for a self-triggering write`,"trigger");try{await ao({ctx:$n,event:s,op:t,schema:i,tableName:s.table,timing:e})}finally{Ce-=1}},{ensureBackfilledForTable:pe,ensureBackfilledIndex:Je,ensureRankBackfilled:Ye,ensureRankBackfilledForTable:ge,syncAggregates:xe,syncCompanionsForInsert:Rt,syncGeo:be,syncRanks:ye,syncSearch:Me}=Fn({broadcast:w,indexKeysFor:(e,t)=>b(e,t),invalidateCache:(e,t,s)=>D?.invalidate(e,t,b(e,s)),recordCdc:we,schema:i,sql:d}),vt=(e,t,s)=>{const{shardMode:f}=t;if(f?.kind==="shardBy"&&!(f.field!==void 0&&(s.partitionBy??[]).includes(f.field)))throw Object.assign(new Error(`rank index "${s.name}" on "${e}" partitions across shards (shard key "${f.field??"?"}" is not in partitionBy) — a shard-local rank()/rankPage() would be wrong; roll it up through the Query Coordinator instead`),{code:"CROSS_SHARD_RANK_UNSUPPORTED",name:"LunoraError",status:400})},Tt=e=>Object.entries(i.tables).filter(([,t])=>t.shardMode?.kind!=="global").map(([t])=>t).filter(t=>e===void 0||t===e),$e=e=>e===void 0||ie(e)?J:void 0,se=(e,t)=>{const s=Tt(t);for(let f=0;f<s.length;f+=me){const h=s.slice(f,f+me),[l]=ve(d,Lo(h),...qo(e,h)).toArray();if(!l)continue;const a=l.__t__,u=Se(l);if(typeof a!="string"||!u)return;const p=l[oe];return{docJson:typeof p=="string"?p:de(p??{}),row:u,tableName:a}}},yn=(e,t)=>{const s=[...new Set(e)],f=new Map;if(s.length===0)return f;const h=Tt(t);for(let l=0;l<h.length;l+=me){const a=h.slice(l,l+me),u=Math.floor(me/a.length),p=Bn(c`${c.identifier("id")}`,s,!1,u),v=a.map(m=>c`SELECT ${c.raw(`'${m.replaceAll("'","''")}'`)} AS __t__, id FROM ${c.identifier(m)} WHERE ${p}`);for(const m of j(d,ft(v))){const{id:k,__t__:S}=m;typeof S=="string"&&typeof k=="string"&&f.set(k,S)}}return f},At={assertRankPartitionLocal:vt,ensureRankBackfilled:Ye,onRead:C,rowToDocument:Se,schema:i,sql:d},H={system:wn,async aggregate(e,t){const s=Q(e,"aggregate");if(s)return C(e,G),s.aggregate(e,t);const f=i.tables[e];if(!f)throw new $("INTERNAL",`unknown table: ${e}`);if(We(t.op),t.op==="count")return H.count(e,{baseWhere:t.baseWhere,relationBaseWhere:t.relationBaseWhere,restrictsCounts:t.restrictsCounts,where:t.where});if(!t.field)throw new $("INTERNAL",`aggregate(${e}, { op: "${t.op}" }): "field" is required for non-count reducers`);C(e,G);const h=ue(f.softDeleteMode,void 0),l=N(N(t.baseWhere,t.where),h),a=await Ie(l,e,t.relationBaseWhere),u=a!==l;if(f.aggregateIndexes&&!t.baseWhere&&!u&&(!h||jt(f,[t.field]))){const U=In(f.aggregateIndexes,t.op,t.field,t.where);if(U){Je(e,U.index);const I=Ze(U.index.by??[],U.key),K=Xe(e,U.index.name),V=j(d,c`SELECT ${Be} AS value, ${nt} AS count FROM ${c.identifier(K)} WHERE ${Pe} = ${I}`).toArray()[0];return et(t.op,V)}}Kt(f,t.field,`aggregate(${e}, { op: "${t.op}", field: "${t.field}" })`);const p=te(a,Ee),v=We(t.op),m=ce(t.field);let k=c`SELECT ${c.raw(v)}(${m}) AS value FROM ${c.identifier(e)}`;p&&(k=c`${k} WHERE ${p}`);const B=j(d,k).toArray()[0]?.value;return B??null},asId(e,t){const s=Qt(i,e,t);if(s===null)throw new $("BAD_REQUEST",`asId("${e}", …): "${t}" is not a valid id for table "${e}"`,{status:400});return s},async count(e,t){const s=Q(e,"count");if(s)return C(e,G),s.count(e,t);const f=i.tables[e];if(!f)throw new $("INTERNAL",`unknown table: ${e}`);const h=vn(t);if(h.restrictsCounts)throw new tt(e);C(e,G);const l=ue(f.softDeleteMode,void 0),a=N(N(h.baseWhere,h.where),l),u=await Ie(a,e,h.relationBaseWhere),p=u!==a;if(f.aggregateIndexes&&!h.baseWhere&&!p&&!l){const S=An(f.aggregateIndexes,h.where);if(S){Je(e,S.index);const B=Ze(S.index.by??[],S.key),U=Xe(e,S.index.name),I=j(d,c`SELECT ${Be} AS value FROM ${c.identifier(U)} WHERE ${Pe} = ${B}`).toArray();return I[0]===void 0?0:I[0].value??0}}const v=te(u,Ee);let m=c`SELECT COUNT(*) AS count FROM ${c.identifier(e)}`;return v&&(m=c`${m} WHERE ${v}`),j(d,m).one().count},async delete(e,t,s){const f=se(e,t);if(!f){const m=$e(t);m&&(y(void 0),await m.delete(e,t,s));return}const{docJson:h,row:l,tableName:a}=f,u=i.tables[a],p=s?.hard===!0,v=!p&&u?.softDeleteMode?u.softDeleteMode.field:void 0;if(!(v&&l[v]!==null&&l[v]!==void 0)){if(Z(a,"before","delete")&&await ee("before","delete",{id:e,op:"delete",previous:l,table:a}),await oo({deletedId:e,deletedReference:m=>l[m],findHolders:async(m,k,S)=>(await Ve(m).findMany(m,{includeDeleted:p,where:{[k]:S}})).page,onCascade:(m,k)=>Ve(m).delete(k,void 0,s),onRestrict:m=>{throw new Re(m,"restrict")},onSetNull:(m,k,S)=>Ve(m).patch(k,{[S]:null}),schema:i,tableName:a}),pe(a),ge(a),v){const m={...l,...g(a),[v]:F(),_id:e};He(d,a,Ht(a),[de(m),e,h]),Me(a,e,m,l),be(a,e,void 0),xe(a,l,m),ye(a,e,l,void 0),D?.invalidate(a,e,b(a,l,m)),we(a,e,"update",m),w({indexKeys:b(a,l,m),key:e,op:"update",row:m,table:a}),Z(a,"after","delete")&&await ee("after","delete",{id:e,op:"delete",previous:l,table:a}),await A({id:e,op:"delete",table:a});return}He(d,a,Do(a),[e,h]),Me(a,e,void 0),be(a,e,void 0),xe(a,l,void 0),ye(a,e,l,void 0),D?.invalidate(a,e,b(a,l)),we(a,e,"delete"),w({indexKeys:b(a,l),key:e,op:"delete",table:a}),Z(a,"after","delete")&&await ee("after","delete",{id:e,op:"delete",previous:l,table:a}),await A({id:e,op:"delete",table:a})}},async deleteAll(e,t){if(!i.tables[e])throw new $("INTERNAL",`unknown table: ${e}`);const s=Math.max(1,t?.chunkSize??dn),f=t?.hard===void 0?void 0:{hard:t.hard},h=ie(e)?void 0:e;let l=0;return await M(async()=>{for(;;){const u=(await H.findMany(e,{limit:s})).page.map(p=>String(p._id));if(u.length===0)break;for(const p of u)await H.delete(p,h,f),l+=1;if(u.length<s)break}}),{deleted:l}},async deleteMany(e,t,s){le(e.length,t?.limit,"deleteMany");for(const f of e)await H.delete(f,s);return{deleted:e.length}},async deleteWhere(e,t,s){const l=(await(Q(e,"deleteWhere")??H).findMany(e,{where:t})).page.map(a=>String(a._id));if(le(l.length,s?.limit,"deleteWhere"),H.deleteMany===void 0)throw new $("INTERNAL",`ctx.db.${e}.deleteMany is unavailable: this writer has no batch delete`);return H.deleteMany(l,s)},async findFirst(e,t={}){return(await H.findMany(e,{...t,limit:1,omitContinueCursor:!0})).page[0]??null},async findFirstOrThrow(e,t={}){const s=await H.findFirst(e,t);if(s===null)throw new Gn(`findFirstOrThrow: no "${e}" document matched`);return s},async findMany(e,t={}){const s=Q(e,"findMany");if(s)return C(e,G),s.findMany(e,t);const f=i.tables[e];if(!f)throw new $("INTERNAL",`unknown table: ${e}`);const h=!t.where&&!t.baseWhere;h?C(e,G):C(e);const l=ct(t.orderBy,f.shape,{pinned:Kn(t.where),uniqueBy:on(f.indexes,f.shape)}),a=t.cursor?rn(l,at(t.cursor)):void 0;let u=N(t.baseWhere,t.where);u=N(u,ue(f.softDeleteMode,t.includeDeleted)),u=await qt(u,{canPushExists:mt?gn:void 0,existsPushMode:$t==="always"?"always":"auto",fetcher:yt,maxRelationKeys:Et,relationBaseWhere:t.relationBaseWhere,schema:i,tableName:e}),a&&(u=u?{AND:[u,a]}:a);const p=mt?zo(C):wt,v=te(u,p,je),m=typeof t.limit=="number"?Math.max(0,Math.floor(t.limit)):void 0,k=sn(e,v,cn(l),m===void 0?void 0:m+1),S=ve(d,k.text,...k.params).toArray();h&&!R&&T?.recordRead(S.length);const B=[];for(const V of S){const O=Se(V);O&&(B.push(O),!h&&typeof O._id=="string"&&C(e,O._id))}if(m===void 0)return t.with&&await Wt({groupedCounter:St,fetcher:ze,parents:B,...Bt(t),schema:i,tableName:e,with:t.with}),{continueCursor:null,isDone:!0,page:Mt(B,t.select,t.with)};const U=B.length>m,I=U?B.slice(0,m):B,K=I.at(-1);return t.with&&await Wt({fetcher:ze,groupedCounter:St,parents:I,...Bt(t),schema:i,tableName:e,with:t.with}),{continueCursor:U&&K&&t.omitContinueCursor!==!0?Ge(K,l):null,isDone:!U,page:Mt(I,t.select,t.with)}},async get(e,t){const s=se(e,t);if(!s){const f=$e(t);return f?f.get(e,t):null}return C(s.tableName,e),s.row},async lookupById(e,t){const s=se(e,t);return s?(C(s.tableName,e),{row:s.row,tableName:s.tableName}):null},async groupBy(e,t){const s=Q(e,"groupBy");if(s)return C(e,G),s.groupBy(e,t);const f=i.tables[e];if(!f)throw new $("INTERNAL",`unknown table: ${e}`);C(e,G);const h=t.agg??{op:"count"};if(We(h.op),h.op!=="count"&&!h.field)throw new $("INTERNAL",`groupBy(${e}, { agg: { op: "${h.op}" } }): "field" is required for non-count reducers`);const l=ue(f.softDeleteMode,void 0),a=N(N(t.baseWhere,t.where),l),u=await Ie(a,e,t.relationBaseWhere),p=u!==a,v=[...t.by,h.field];if(f.aggregateIndexes&&!t.baseWhere&&!p&&(!l||jt(f,v))){const I=Tn(f.aggregateIndexes,h.op,h.field,t.by,t.where),K=I===void 0?0:Object.keys(I.partial).length,V=I?.index.by?.length??0;if(I&&(K===0||K===V)){Je(e,I.index);const O=Xe(e,I.index.name),De=Object.keys(I.partial),ke=[];if(De.length===(I.index.by??[]).length&&De.length>0){const Fe=Ze(I.index.by??[],I.partial),Le=j(d,c`SELECT ${Be} AS value, ${nt} AS count FROM ${c.identifier(O)} WHERE ${Pe} = ${Fe}`).toArray();return Le.length>0&&ke.push({key:{...I.partial},value:et(h.op,Le[0])}),ke}const mn=j(d,c`SELECT ${Pe} AS key, ${Be} AS value, ${nt} AS count FROM ${c.identifier(O)}`).toArray();for(const Fe of mn){const Le=_n(JSON.parse(Fe.key));ke.push({key:Le,value:et(h.op,Fe)})}return ke}}for(const I of v){if(I===void 0)continue;const K=I===h.field?`groupBy(${e}, { agg: { op: "${h.op}", field: "${I}" } })`:`groupBy(${e}, { by: [..."${I}"] })`;Kt(f,I,K)}const m=te(u,Ee),k=t.by.map(I=>c`${ce(I)} AS ${c.identifier(I)}`);if(h.op==="count")k.push(c`COUNT(*) AS value`);else{const{field:I}=h;if(I===void 0)throw new $("INTERNAL",`groupBy(${e}, { agg: { op: "${h.op}" } }): "field" is required for non-count reducers`);k.push(c`${c.raw(We(h.op))}(${ce(I)}) AS value`)}let S=c`SELECT ${c.join(k,c`, `)} FROM ${c.identifier(e)}`;m&&(S=c`${S} WHERE ${m}`),S=c`${S} GROUP BY ${c.join(t.by.map(I=>ce(I)),c`, `)}`;const B=j(d,S).toArray(),U=[];for(const I of B){const K={};for(const O of t.by)K[O]=Ln(f.shape[O],I[O]??null);const{value:V}=I;U.push({key:K,value:V==null?null:Number(V)})}return U},async insert(e,t,s){const f=Q(e,"insert");if(f)return gt(f,e,t,s,!0);const h=i.tables[e];if(!h)throw new $("INTERNAL",`unknown table: ${e}`);const l=Vt(h,t,re);rt(h,l);let a;s?.clientId!==void 0?(Bo(s.clientId),a=s.clientId):s?.allowExplicitId&&typeof l._id=="string"?a=l._id:a=X();const u=s?.allowExplicitId&&typeof l._creationTime=="number"?l._creationTime:F(),p={...l,...g(e),_creationTime:u,_id:a};return Z(e,"before","insert")&&await ee("before","insert",{doc:{...p},id:a,op:"insert",table:e}),pe(e),ge(e),lt(d,e,bo(e),[a,u,de(p)]),Rt(e,a,p),Z(e,"after","insert")&&await ee("after","insert",{doc:p,id:a,op:"insert",table:e}),await A({doc:p,id:a,op:"insert",table:e}),a},async insertManyUnsafe(e,t,s){if(le(t.length,s?.limit,"insertManyUnsafe"),t.length===0)return[];const f=Q(e,"insert");if(f){const u=[];for(const p of t)y(p);for(const p of t){const v=await f.insert(e,p,{allowExplicitId:s?.allowExplicitId});w({key:v,op:"insert",row:{...p,_id:v},table:e}),u.push(v)}return u}const h=i.tables[e];if(!h)throw new $("INTERNAL",`unknown table: ${e}`);pe(e),ge(e);const l=[];for(let u=0;u<t.length;u+=Ue)l.push(g(e));const a=t.map((u,p)=>{const v=Vt(h,u,re),m=s?.allowExplicitId===!0&&typeof v._id=="string"?v._id:X(),k=s?.allowExplicitId===!0&&typeof v._creationTime=="number"?v._creationTime:F(),S={...v,...l[Math.floor(p/Ue)],_creationTime:k,_id:m};return{creationTime:k,document:S,id:m}});for(const u of a)y(u.document);for(let u=0;u<a.length;u+=Ue){const p=c.join(a.slice(u,u+Ue).map(m=>c`(${m.id}, ${m.creationTime}, ${de(m.document)})`),c`, `),v=tn("sqlite",c`INSERT INTO ${c.identifier(e)} (id, _creationTime, ${c.identifier(oe)}) VALUES ${p}`);lt(d,e,v.sql,v.params)}for(const{document:u,id:p}of a)Rt(e,p,u),await Y({doc:u,id:p,op:"insert",table:e});return a.map(u=>u.id)},async insertMany(e,t,s){le(t.length,s?.limit,"insertMany");const f=s?.skipDuplicates===!0,h=[],l=Q(e,"insert");if(l)for(const u of t)y(u);const a=async u=>l?gt(l,e,u,void 0,!1):H.insert(e,u);for(const u of t)try{h.push(await a(u))}catch(p){if(f&&p instanceof Re&&p.kind==="unique")h.push(null);else throw p}return h},normalizeId(e,t){return Qt(i,e,t)},async patch(e,t,s){const f=se(e,s);if(!f){const v=$e(s);if(v){y(t),await v.patch(e,t,s);return}throw new $("NOT_FOUND",`document not found: ${e}`)}const{docJson:h,row:l,tableName:a}=f,u=i.tables[a];if(!u)throw new $("INTERNAL",`unknown table: ${a}`);if(C(a,e),Jt("patch",t),pn(a,e,t,l)){o?.({fields:Object.keys(st(t)),id:e,table:a});return}const p={...l,...st(t),...g(a),_id:e};zt(u,t,p,re),rt(u,p,!0),Z(a,"before","update")&&await ee("before","update",{doc:{...p},id:e,op:"update",previous:l,table:a}),pe(a),ge(a),He(d,a,Ht(a),[de(p),e,h]),Me(a,e,p,l),be(a,e,p),xe(a,l,p),ye(a,e,l,p),D?.invalidate(a,e,b(a,l,p)),we(a,e,"update",p),w({indexKeys:b(a,l,p),key:e,op:"update",row:p,table:a}),Z(a,"after","update")&&await ee("after","update",{doc:p,id:e,op:"update",previous:l,table:a}),await A({doc:p,id:e,op:"update",table:a})},async patchMany(e,t,s){le(e.length,t?.limit,"patchMany");for(const f of e)await H.patch(f.id,f.patch,s);return{patched:e.length}},async patchWhere(e,t,s){const l=(await(Q(e,"patchWhere")??H).findMany(e,{where:t.where})).page.map(a=>({id:String(a._id),patch:t.patch}));if(le(l.length,s?.limit,"patchWhere"),H.patchMany===void 0)throw new $("INTERNAL",`ctx.db.${e}.patchMany is unavailable: this writer has no batch patch`);return await H.patchMany(l,s),{patched:l.length}},async related(e,t){return no(H,_,e,t)},relationEdges:_,query(e){const t=Q(e,"query");return t?(C(e,G),t.query(e)):hn(d,i,e,ne,s=>{s?P(s):C(e,G)},s=>{R||T?.recordRead(s)})},async rank(e,t,s){const f=Q(e,"rank");if(f)return C(e,G),f.rank(e,t,s);ne(e,t,"rank");const h=i.tables[e];if(!h)throw new $("INTERNAL",`unknown table: ${e}`);const l=h.rankIndexes?.find(O=>O.name===t);if(!l)throw new $("INTERNAL",`unknown rankIndex "${t}" on table "${e}"`);if(vt(e,h,l),s.restrictsCounts)throw new tt(e);C(e,G),Ye(e,l);const a=typeof s.row=="string"?s.row:s.row._id;if(!a)return null;const u=Dt(e,l.name),p=l.sortBy.map((O,De)=>kt(De)),v=p.map(O=>Te(O)).join(", "),m=j(d,c`SELECT ${c.identifier("__partition__")}, ${c.raw(v)} FROM ${c.identifier(u)} WHERE ${c.identifier("__id__")} = ${a}`).toArray(),[k]=m;if(k===void 0)return null;let S=k.__partition__;const B=N(s.baseWhere,s.where);ot(B,i,e,"rank");const U=Qn(l,B);if(U){const O=Vn(l.partitionBy??[],U);if(O!==S)return null;S=O}const I=p.map(O=>k[O]),{before:K,total:V}=Xt(d,u,p,l.sortBy,S,I,a);return{position:K+1,total:V}},async rankBefore(e,t,s){if(ie(e))throw new $("INTERNAL",`rankBefore is not supported on the global (.global()) table '${e}' — cross-shard rank cursors apply only to sharded tables`);const f=i.tables[e];if(!f)throw new $("INTERNAL",`unknown table: ${e}`);const h=f.rankIndexes?.find(p=>p.name===t);if(!h)throw new $("INTERNAL",`unknown rankIndex "${t}" on table "${e}"`);if(s.restrictsCounts)throw new tt(e);C(e,G),Ye(e,h);const l=Dt(e,h.name),a=h.sortBy.map((p,v)=>kt(v)),u=h.sortBy.map((p,v)=>ae(s.sortValues[v]??null));return Xt(d,l,a,h.sortBy,s.partitionKey,u,s.rowId)},async rankPage(e,t,s={}){ot(N(s.baseWhere,s.where),i,e,"rankPage");const f=Q(e,"rankPage");if(f)return C(e,G),f.rankPage(e,t,s);ne(e,t,"rank");const{continueCursor:h,hasMore:l,rows:a}=xt(At,e,t,s);return{continueCursor:h,isDone:!l,page:a.map(u=>u.doc)}},async rankPageRows(e,t,s={}){ot(N(s.baseWhere,s.where),i,e,"rankPage"),ne(e,t,"rank");const{directions:f,hasMore:h,rows:l}=xt(At,e,t,s);return{directions:f,hasMore:h,rows:l}},async restore(e,t){const s=se(e,t);if(!s){const l=$e(t);if(l?.restore){await l.restore(e,t);return}throw new $("NOT_FOUND",`document not found: ${e}`)}const f=i.tables[s.tableName]?.softDeleteMode?.field;if(!f)throw new $("INTERNAL",`ctx.db.restore: table "${s.tableName}" is not a .softDelete() table`);const h=s.row[f]!==null&&s.row[f]!==void 0;await H.patch(e,{[f]:null},t),h&&ye(s.tableName,e,void 0,s.row)},async replace(e,t,s,f){const h=se(e,s);if(!h){const B=$e(s);if(B){y(t),await B.replace(e,t,s,f);return}throw new $("NOT_FOUND",`document not found: ${e}`)}const{docJson:l,row:a,tableName:u}=h,p=i.tables[u];if(!p)throw new $("INTERNAL",`unknown table: ${u}`);Jt("replace",t);const v=f?.allowExplicitId&&typeof t._creationTime=="number"?t._creationTime:void 0,m=typeof a._creationTime=="number"?a._creationTime:void 0,k=v??m??F(),S={...t,...g(u),_creationTime:k,_id:e};zt(p,t,S,re),rt(p,S),Z(u,"before","update")&&await ee("before","update",{doc:{...S},id:e,op:"update",previous:a,table:u}),pe(u),ge(u),He(d,u,Mo(u),[k,de(S),e,l]),Me(u,e,S,a),be(u,e,S),xe(u,a,S),ye(u,e,a,S),D?.invalidate(u,e,b(u,a,S)),we(u,e,"update",S),w({indexKeys:b(u,a,S),key:e,op:"update",row:S,table:u}),Z(u,"after","update")&&await ee("after","update",{doc:S,id:e,op:"update",previous:a,table:u}),await A({doc:S,id:e,op:"update",table:u})},async wipeShard(e){const t=new Set(e?.exclude),s=e?.tables,f=Object.entries(i.tables).filter(([u,p])=>t.has(u)||s!==void 0&&!s.includes(u)?!1:p.shardMode?.kind!=="global").map(([u])=>u);if(s!==void 0){for(const u of s)if(!i.tables[u])throw new $("INTERNAL",`wipeShard: unknown table: ${u}`)}const h={};let l=0;const{deleteAll:a}=H;if(a===void 0)throw new $("INTERNAL","wipeShard: this writer has no deleteAll");for(const u of f){const p=await a(u,{...e?.chunkSize===void 0?{}:{chunkSize:e.chunkSize},hard:!0});h[u]=p.deleted,l+=p.deleted}return{deleted:l,tables:h}}},$n={db:H,scheduler:he};return n.enforceRls===!0?io(H,i,(e,t)=>se(e,t)?.tableName,(e,t)=>yn(e,t),_):H};export{Qr as CDC_LOG_TABLE,pi as IDEMPOTENCY_TABLE,Jo as NotUniqueError,ui as advanceClientWatermark,Vr as applyCdcChanges,Jt as assertNoExplicitUndefined,Bo as assertValidClientId,Gr as backfillAggregateIndexes,Nr as backfillRankIndexes,jr as backfillSearchIndexes,zr as bumpCdcEpoch,Jr as cdcCanVouchFor,Yr as cdcForkedError,Xr as cdcSeqLeavingRows,Zr as cdcTouchesTables,ei as cdcTrimmedError,ti as compactCdcDocs,Ur as createShardCtxDb,ni as cursorBelowRetainedFloor,fi as migrateClientWatermark,oi as minCdcReplayableSeq,ri as minCdcSeq,Qt as normalizeIdStructurally,ii as readCdcChangeKeys,si as readCdcChanges,ci as readCdcCursor,ai as readCdcEpoch,hi as readClientWatermark,gi as readIdempotent,Ei as runShardMigrations,_i as selectShapeMembers,Ri as selectShapeRows,st as stripReservedPatchFields,di as trimCdcChanges,yi as trimIdempotent,$i as writeIdempotent};
|
package/dist/packem_shared/{RELATED_DEFAULT_LIMIT-B9PH28Pn.mjs → RELATED_DEFAULT_LIMIT-CBYQQIrZ.mjs}
RENAMED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{LunoraError as h}from"@lunora/errors";import{mergeWhere as I}from"./CountRlsUnsupportedError-BvsDqfO2.mjs";import{decodeCursor as S,CURSOR_PREFIX as v,toBase64 as B}from"./CURSOR_PREFIX-
|
|
1
|
+
import{LunoraError as h}from"@lunora/errors";import{mergeWhere as I}from"./CountRlsUnsupportedError-BvsDqfO2.mjs";import{decodeCursor as S,CURSOR_PREFIX as v,toBase64 as B}from"./CURSOR_PREFIX-BX8jkMJa.mjs";const O=4,C=1,L=50,$=200,T=1e4,x=.5,D=t=>{if(t.kind==="id"){const e=t._meta?.tableName;return typeof e=="string"&&e.length>0?{array:!1,targetTable:e}:void 0}if(t.kind!=="array"&&t.kind!=="optional")return;const n=t._meta?.inner,r=n===void 0?void 0:D(n);if(r!==void 0)return{array:r.array||t.kind==="array",targetTable:r.targetTable}},j=t=>{const n=[];for(const[r,e]of Object.entries(t.tables))for(const[s,o]of Object.entries(e.shape)){const a=D(o);a===void 0||t.tables[a.targetTable]===void 0||n.push({array:a.array,column:s,name:`${r}.${s}`,sourceTable:r,targetTable:a.targetTable})}return n},U=t=>v+B(JSON.stringify([t])),M=t=>{const[n]=S(t);if(typeof n!="number"||!Number.isInteger(n)||n<0)throw new h("BAD_REQUEST","invalid cursor");if(n>T)throw new h("BAD_REQUEST",`ctx.db.related: cursor offset ${String(n)} exceeds the maximum of ${String(T)} — narrow the walk with \`edges\` or \`direction\` instead of paging past it`);return n},k=(t,n,r,e)=>{if(t===void 0)return n;if(!Number.isInteger(t)||t<1||t>r)throw new h("BAD_REQUEST",`ctx.db.related: \`${e}\` must be an integer between 1 and ${String(r)}, got ${String(t)}`);return t},N=(t,n)=>{if(n===void 0)return[...t];const r=new Set(t.map(o=>o.name)),e=n.filter(o=>!r.has(o));if(e.length>0)throw new h("BAD_REQUEST",`ctx.db.related: unknown edge ${e.length===1?"name":"names"}: ${e.join(", ")}`);const s=new Set(n);return t.filter(o=>s.has(o.name))},W=(t,n)=>{const r=t[n.column];return n.array?Array.isArray(r)?r.filter(e=>typeof e=="string"&&e.length>0):[]:typeof r=="string"&&r.length>0?[r]:[]},A=async(t,n,r,e)=>{const s=await t.findMany(n,{limit:e.limit,omitContinueCursor:!0,where:I(r,e.relationBaseWhere?.(n))??r});return e.mask?.(n,s.page)??s.page},F={in:{keyColumn:t=>t.column,keysOf:(t,n)=>n.array||t.table!==n.targetTable?[]:[t.id],skipVisitedKeys:!1,table:t=>t.sourceTable},out:{keyColumn:()=>"_id",keysOf:(t,n)=>t.table===n.sourceTable?W(t.document,n):[],skipVisitedKeys:!0,table:t=>t.targetTable}},_=async(t,n,r,e,s)=>{const o=F[s],a=o.keyColumn(r),l=o.table(r),u=new Map;for(const c of n)for(const i of o.keysOf(c,r))!u.has(i)&&!(o.skipVisitedKeys&&e.visited.has(i))&&u.set(i,c);if(u.size===0)return[];const f=await A(t,l,{[a]:{in:[...u.keys()]}},e),m=[];for(const c of f){const i=c._id,g=c[a],d=typeof g=="string"?u.get(g):void 0;typeof i!="string"||d===void 0||e.visited.has(i)||(e.visited.add(i),m.push({document:c,id:i,path:[...d.path,r.name],pathIds:[...d.pathIds,i],table:l}))}return m},Q=async(t,n,r,e)=>{const s=[],o=()=>e.budget-s.length,a=()=>({limit:o(),mask:e.mask,relationBaseWhere:e.relationBaseWhere,visited:e.visited});for(const l of r)e.direction!=="in"&&o()>0&&s.push(...await _(t,n,l,a(),"out")),e.direction!=="out"&&o()>0&&s.push(...await _(t,n,l,a(),"in"));return s},H=async(t,n)=>{const r=n._id;if(typeof r=="string"&&r.length>0){const o=await t.lookupById?.(r);if(!o)throw new h("BAD_REQUEST","ctx.db.related: could not resolve the start document's table from its `_id` — pass `{ table, id }` instead");return{id:r,table:o.tableName}}const{id:e,table:s}=n;if(typeof s!="string"||s.length===0||typeof e!="string"||e.length===0)throw new h("BAD_REQUEST","ctx.db.related: `start` must be a loaded document or `{ table, id }`");return{id:e,table:s}},V=async(t,n,r,e={})=>{const s=k(e.depth,C,O,"depth"),o=k(e.limit,L,$,"limit"),a=e.cursor?M(e.cursor):0,l=e.direction??"both",u=N(n,e.edges),{id:f,table:m}=await H(t,r),[c]=await A(t,m,{_id:f},{limit:1,mask:e.relationMask,relationBaseWhere:e.relationBaseWhere,visited:new Set});if(c===void 0)throw new h("NOT_FOUND",`ctx.db.related: no "${m}" row with id ${f}`);const i=a+o+1,g=new Set([f]),d=[];let w=[{document:c,id:f,path:[],pathIds:[f],table:m}];for(let b=1;b<=s&&w.length>0&&d.length<i;b+=1){const p=await Q(t,w,u,{budget:i-d.length,direction:l,mask:e.relationMask,relationBaseWhere:e.relationBaseWhere,visited:g}),R=x**(b-1);for(const y of p)d.push({depth:b,document:y.document,path:y.path,pathIds:y.pathIds,score:R,table:y.table});w=p}const E=d.length<=a+o;return{continueCursor:E?null:U(a+o),isDone:E,nodes:d.slice(a,a+o)}};export{L as RELATED_DEFAULT_LIMIT,x as RELATED_DEPTH_DECAY,O as RELATED_MAX_DEPTH,$ as RELATED_MAX_LIMIT,T as RELATED_MAX_OFFSET,j as deriveRelationEdges,V as findRelated};
|
package/dist/packem_shared/{RLS_UNWRAP_SYMBOL-BwwTbz3Q.mjs → RLS_UNWRAP_SYMBOL-rSxYzw-G.mjs}
RENAMED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{LunoraError as R}from"@lunora/errors";import{findRelated as m}from"./RELATED_DEFAULT_LIMIT-
|
|
1
|
+
import{LunoraError as R}from"@lunora/errors";import{findRelated as m}from"./RELATED_DEFAULT_LIMIT-CBYQQIrZ.mjs";const M=Symbol.for("lunora.ctxdb.rls-unwrap");class S extends R{table;constructor(n){super("RLS_REQUIRED",`ctx.db access to "${n}" is denied: the schema is marked .rls("required"), so this table is protected. Apply RLS with .use(rls(policies)) in the procedure, or mark the table .public() to opt it out.`,{name:"RlsRequiredError"}),this.table=n}}const b=a=>Object.entries(a.tables).filter(([,n])=>n.shardMode?.kind!=="global").map(([n])=>n),E=(a,n,l)=>{const d=n?.tables,u=new Set(n?.exclude);for(const o of a)(d===void 0||d.includes(o))&&!u.has(o)&&l(o)},y={aggregate:"loop-gated",asId:"ungated",cdcChangedTables:"ungated",count:"loop-gated",delete:"id-gated",deleteAll:"loop-gated",deleteMany:"id-gated",deleteWhere:"inline-table-gated",findFirst:"loop-gated",findFirstOrThrow:"loop-gated",findMany:"loop-gated",get:"id-gated",groupBy:"loop-gated",insert:"loop-gated",insertMany:"loop-gated",insertManyUnsafe:"loop-gated",lookupById:"id-gated",normalizeId:"ungated",patch:"id-gated",patchMany:"id-gated",patchWhere:"inline-table-gated",query:"loop-gated",rank:"loop-gated",rankBefore:"loop-gated",rankPage:"loop-gated",rankPageRows:"loop-gated",related:"rebound",relationEdges:"ungated",replace:"id-gated",restore:"id-gated",system:"ungated",wipeShard:"sweep-gated"},O=Object.entries(y).filter(([,a])=>a==="loop-gated").map(([a])=>a),W={related:(a,n)=>(...l)=>{const[d,u]=l;return m(a,n,d,u)}},k=Object.entries(y).filter(([,a])=>a==="rebound").map(([a])=>a),v=(a,n,l)=>{for(const d of k)typeof n[d]=="function"&&(a[d]=W[d](a,l))},_=(a,n,l,d,u=[])=>{if(n.rlsMode!=="required")return a;const o=a,p=e=>{const t=n.tables[e];return t!==void 0&&t.isPublic!==!0},i=e=>{if(p(e))throw new S(e)},c=async(e,t)=>{if(t!==void 0){i(t);return}const r=await l(e);r!==void 0&&i(r)},f=async(e,t)=>{if(t!==void 0){i(t);return}if(!d){for(const s of e)await c(s,t);return}const r=await d([...new Set(e)],t);for(const s of e){const h=r.get(s);h!==void 0&&i(h)}},g={...a,delete:async(e,t,r)=>(await c(e,t),o.delete(e,t,r)),deleteMany:async(e,t,r)=>(await f(e,r),o.deleteMany(e,t,r)),deleteWhere:o.deleteWhere?async(e,t,r)=>(i(e),await o.deleteWhere?.(e,t,r)):void 0,get:async(e,t)=>(await c(e,t),o.get(e,t)),lookupById:async(e,t)=>(await c(e,t),o.lookupById?.(e,t)??null),patch:async(e,t,r)=>(await c(e,r),o.patch(e,t,r)),patchMany:async(e,t,r)=>(await f(e.map(s=>s.id),r),o.patchMany(e,t,r)),patchWhere:o.patchWhere?async(e,t,r)=>(i(e),await o.patchWhere?.(e,t,r)):void 0,replace:async(e,t,r,s)=>(await c(e,r),o.replace(e,t,r,s)),restore:async(e,t)=>(await c(e,t),o.restore?.(e,t))},w=o;for(const e of O){const t=w[e];typeof t=="function"&&(g[e]=(r,...s)=>(i(r),t.call(o,r,...s)))}if(v(g,o,u),o.wipeShard){const{wipeShard:e}=o;g.wipeShard=t=>(E(b(n),t,i),e.call(o,t))}return Object.defineProperty(g,M,{configurable:!0,enumerable:!1,value:a,writable:!1}),g};export{O as LOOP_GATED_METHODS,M as RLS_UNWRAP_SYMBOL,S as RlsRequiredError,y as WRITER_METHOD_GATING,_ as guardWriter};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{isLunoraError as S}from"@lunora/errors";import{l as R,b as L}from"./ctx-db-search-state-DVCp4JQf.mjs";import{sql as e}from"drizzle-orm";import{readKeysetPage as _}from"./backfillAggregateIndexes-
|
|
1
|
+
import{isLunoraError as S}from"@lunora/errors";import{l as R,b as L}from"./ctx-db-search-state-DVCp4JQf.mjs";import{sql as e}from"drizzle-orm";import{readKeysetPage as _}from"./backfillAggregateIndexes-B_3xdOgV.mjs";import{runDrizzle as p}from"./runDrizzle-Du5HLitO.mjs";import{h}from"./do-sql-BEFrJUds.mjs";const u="__lunora_vector_backfill",m=50,k=20,w=20,N=3,O=i=>{p(i,e`CREATE TABLE IF NOT EXISTS ${e.identifier(u)} (${e.identifier("companion")} TEXT PRIMARY KEY, ${e.identifier("cursor")} TEXT, ${e.identifier("done")} INTEGER NOT NULL DEFAULT 0, ${e.identifier("profile")} TEXT, ${e.identifier("strikes")} INTEGER NOT NULL DEFAULT 0)`);try{p(i,e`ALTER TABLE ${e.identifier(u)} ADD COLUMN ${e.identifier("strikes")} INTEGER NOT NULL DEFAULT 0`)}catch{}},C=(i,o)=>{const[s]=p(i,e`SELECT ${e.identifier("strikes")} FROM ${e.identifier(u)} WHERE ${e.identifier("companion")} = ${o}`).toArray();return s?.strikes??0},$=(i,o,s,d,t,r=0)=>{const n=s??null;p(i,e`INSERT INTO ${e.identifier(u)} (${e.identifier("companion")}, ${e.identifier("cursor")}, ${e.identifier("done")}, ${e.identifier("profile")}, ${e.identifier("strikes")}) VALUES (${o}, ${n}, ${d?1:0}, ${t}, ${r}) ON CONFLICT (${e.identifier("companion")}) DO UPDATE SET ${e.identifier("cursor")} = excluded.${e.identifier("cursor")}, ${e.identifier("done")} = excluded.${e.identifier("done")}, ${e.identifier("profile")} = excluded.${e.identifier("profile")}, ${e.identifier("strikes")} = excluded.${e.identifier("strikes")}`)},A=(i,o,s)=>{const d=_(i,o,s,m+1),t={documents:[],lastId:s,more:d.length>m,unparseable:[]};for(const r of d.slice(0,m)){if(typeof r.id!="string")continue;t.lastId=r.id;const n=h(r);n?t.documents.push({doc:n,id:t.lastId}):t.unparseable.push(t.lastId)}return t},D=(i,o,s,d,t)=>{const r=t instanceof Error?t.message:String(t),n=L(i,u,o),a=n.profile===d&&n.cursor===s?C(i,o):0;if(S(t)&&t.code==="SERVICE_UNAVAILABLE")return a>0&&$(i,o,s,!1,d,0),{error:r};const f=a+1;if(f<N)return $(i,o,s,!1,d,f),{error:r};const c=A(i,o,s),l=[...c.documents.map(E=>E.id),...c.unparseable];return console.warn(`[@lunora/shard-engine] vector backfill: a page of "${o}" failed ${String(f)} times in a row; its ${String(l.length)} row(s) are recorded as failed:`,t),{failedIds:l,page:c}},F=async(i,o,s,d,t)=>{const{profile:r,table:n}=o;try{const{failures:a,page:f}=await t(()=>A(i,n,s),async c=>({failures:await d(n,c.documents),page:c}));return a.length>0&&console.warn(`[@lunora/shard-engine] vector backfill: ${String(a.length)} row(s) of "${n}" could not be indexed:`,a),{failedIds:[...f.unparseable,...a.map(c=>c.id)],page:f}}catch(a){return D(i,n,s,r,a)}},y=async(i,o,s,d)=>{if(O(i),d.restart===!0)for(const{profile:n,table:a}of o)$(i,a,void 0,!1,n);const t=Math.min(d.maxPages??1,k),r={done:!1,failed:0,failedIds:[],pages:0,rows:0};for(const{profile:n,table:a}of o){const f=R(L(i,u,a),n);let{cursor:c}=f,l=f.finished;for(;!l;){if(r.pages>=t)return r;const E=await F(i,{profile:n,table:a},c,s,d.ordered);if("error"in E)return{...r,error:E.error};const{failedIds:g,page:T}=E,I=T.documents.length+T.unparseable.length;r.pages+=I>0?1:0,r.rows+=I,r.failed+=g.length,r.failedIds=[...r.failedIds,...g].slice(0,w),c=T.lastId,l=!T.more,$(i,a,c,l,n)}}return{...r,done:!0}};export{k as VECTOR_BACKFILL_MAX_PAGES,m as VECTOR_BACKFILL_PAGE_ROWS,y as backfillVectorIndexes};
|
package/dist/packem_shared/{appendStreamChunk-y5mkpRdi.mjs → appendStreamChunk-7ZyAZGg_.mjs}
RENAMED
|
@@ -14,4 +14,4 @@ import{sql as t}from"drizzle-orm";import{runDrizzle as o}from"./runDrizzle-Du5HL
|
|
|
14
14
|
)`)},_=(r,e)=>{const s=o(r,t`SELECT status, last_seq, error_code, error, started_at FROM ${t.identifier(E)} WHERE run_key = ${e} 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}},T=(r,e)=>{o(r,t`DELETE FROM ${t.identifier(i)} WHERE run_key = ${e}`)},c=(r,e,n,s)=>_(r,e)!==void 0?!1:(T(r,e),o(r,t`INSERT INTO ${t.identifier(E)} (run_key, status, last_seq, started_at, ttl_ms)
|
|
15
15
|
VALUES (${e}, ${"running"}, 0, ${n}, ${s})`),!0),R=(r,e)=>{T(r,e),o(r,t`DELETE FROM ${t.identifier(E)} WHERE run_key = ${e}`)},m=(r,e,n,s)=>{o(r,t`INSERT OR IGNORE INTO ${t.identifier(i)} (run_key, seq, data_json) VALUES (${e}, ${n}, ${s})`)},A=(r,e,n)=>o(r,t`SELECT seq, data_json FROM ${t.identifier(i)} WHERE run_key = ${e} AND seq > ${n} ORDER BY seq ASC`).toArray().map(s=>({dataJson:s.data_json,seq:s.seq})),$=(r,e,n,s,a)=>{if(_(r,e)===void 0){T(r,e);return}const d=a?.code??null,u=a?.message??null;o(r,t`UPDATE ${t.identifier(E)}
|
|
16
16
|
SET status = ${n}, last_seq = ${s}, error_code = ${d}, error = ${u}
|
|
17
|
-
WHERE run_key = ${e}`)},f=(r,e,n)=>{const s=o(r,t`SELECT run_key FROM ${t.identifier(E)} WHERE started_at + ttl_ms < ${e}`).toArray();for(const{run_key:a}of s)n.has(a)||R(r,a)};export{
|
|
17
|
+
WHERE run_key = ${e}`)},f=(r,e,n)=>{const s=o(r,t`SELECT run_key FROM ${t.identifier(E)} WHERE started_at + ttl_ms < ${e}`).toArray();for(const{run_key:a}of s)n.has(a)||R(r,a)};export{m as appendStreamChunk,c as claimStreamRun,R as deleteStreamRun,$ as finishStreamRun,N as migrateDurableStreams,A as readStreamChunks,_ as readStreamRun,f as trimStreamRuns};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{LunoraError as D}from"@lunora/errors";import{applySelect as I}from"./CURSOR_PREFIX-
|
|
1
|
+
import{LunoraError as D}from"@lunora/errors";import{applySelect as I}from"./CURSOR_PREFIX-BX8jkMJa.mjs";const W=Symbol.for("lunora.relations.fanOutBudget"),U=o=>({fanOutBudget:o[W],relationBaseWhere:o.relationBaseWhere,relationMask:o.relationMask}),A=(o,n)=>n.select?I(o,n.select,n.with):o,x=async(o,n,r,a,t)=>{const l=await Promise.all(a.map(async i=>{const h=t?{AND:[{[r]:i},t]}:{[r]:i};return[i,await o(n,h)]}));return new Map(l)},S=32,C=(o,n,r)=>{const a=new Map;for(const t of o)for(const l of r(t)){const i=l[n],h=a.get(i);h?h.push(l):a.set(i,[l])}return a},_=(o,n)=>({...o,[W]:n}),B=(o,n)=>{const r=new Set;for(const a of o){const t=a[n];t!=null&&r.add(t)}return[...r]},H=async o=>{const{groupedCounter:n,fanOutBudget:r,fetcher:a,parents:t,relationBaseWhere:l,relationMask:i,schema:h,tableName:m,with:v}=o,w=r??{remaining:S},k=(c,e)=>i?.(c,e)??e;if(t.length===0)return;const N=h.tables[m];if(!N)throw new D("INTERNAL",`unknown table: ${m}`);const O=N.relationMap??{},R=c=>{const e=O[c];if(!e)throw new D("INTERNAL",`unknown relation "${c}" on table "${m}"`);return e},V=async(c,e,s)=>{const u=B(t,e.field);if(u.length===0){for(const d of t)d[c]=null;return}const{page:p}=await a(e.table,_({baseWhere:l?.(e.table),relationBaseWhere:l,relationMask:i,where:{[e.references]:{in:u}},with:s.with},w)),b=new Map;for(const d of k(e.table,p))b.set(d[e.references],d);for(const d of t){const y=b.get(d[e.field]);d[c]=y?A([y],s)[0]??null:null}},$=async(c,e,s)=>{const u=B(t,e.references);if(u.length===0){for(const f of t)f[c]=[];return}const p=typeof s.limit=="number"?Math.max(0,Math.floor(s.limit)):void 0,b=async(f,g)=>{const{page:E}=await a(e.table,_({baseWhere:l?.(e.table),limit:g,orderBy:s.orderBy,relationBaseWhere:l,relationMask:i,where:s.where?{AND:[s.where,f]}:f,with:s.with},w));return E};if(p===0){for(const f of t)f[c]=[];return}const d=p!==void 0&&u.length<=w.remaining;d&&(w.remaining-=u.length);const y=d?await Promise.all(u.map(async f=>b({[e.field]:f},p))):[await b({[e.field]:{in:u}},void 0)],M=C(y,e.field,f=>k(e.table,f));for(const f of t){const g=M.get(f[e.references])??[];f[c]=A(p===void 0?g:g.slice(0,p),s)}},j=async c=>{for(const e of Object.keys(c)){const s=R(e),[u,p]=s.kind==="many"?[s.field,s.references]:[s.references,s.field],b=l?.(s.table),d=B(t,p),y=d.length===0?new Map:await n(s.table,u,d,b);for(const M of t){const f=M._count??{},g=M[p];f[e]=g==null?0:y.get(g)??0,M._count=f}}};for(const[c,e]of Object.entries(v)){if(e===void 0||e===!1)continue;if(c==="_count"){await j(e);continue}const s=R(c),u=e===!0?{}:e;await(s.kind==="one"?V(c,s,u):$(c,s,u))}},F=async(o,n,r)=>{const{deletedId:a,deletedReference:t,findHolders:l,onCascade:i,onRestrict:h,onSetNull:m,tableName:v}=o,w=r.references==="_id"?a:t(r.references);if(w==null)return;const k=await l(n,r.field,w);if(k.length!==0){r.onDelete==="restrict"&&h(`cannot delete "${v}" row: "${n}.${r.field}" still references it`);for(const N of k){const O=N._id;typeof O=="string"&&await(r.onDelete==="cascade"?i(n,O):m(n,O,r.field))}}},P=async o=>{const{schema:n,tableName:r}=o;if(!n.tables[r])throw new D("INTERNAL",`unknown table: ${r}`);for(const[a,t]of Object.entries(n.tables)){const l=t.relationMap;if(l)for(const i of Object.values(l))i.kind!=="one"||i.table!==r||!i.onDelete||await F(o,a,i)}},q=(o,n,r=!1)=>{for(const[a,t]of Object.entries(o.shape))a in n&&typeof t.parse=="function"&&(r&&n[a]===null&&t.kind==="optional"||t.parse(n[a]))};export{P as applyOnDelete,B as distinctValues,x as fanOutScalarCounts,U as relationHooks,H as resolveWith,q as runRowValidators};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{m as x,c as T,l as R,r as E,a as P,w as D}from"./ctx-db-search-state-DVCp4JQf.mjs";import{S,c as U,g as v,d as A,e as k,a as b}from"./fts-companion-pUdD6kF-.mjs";import{sql as s}from"drizzle-orm";import{matchesStaticWhere as G}from"./AGGREGATE_SQL_FUNCTION-DDEoMnJR.mjs";import{aggregateTableName as W,encodeAggregateKey as B,foldAggregateTally as H}from"./aggregateTableName-C7o-gpms.mjs";import{rankColumnsSql as N,insertRankRow as K}from"./createCompanionSync-
|
|
1
|
+
import{m as x,c as T,l as R,r as E,a as P,w as D}from"./ctx-db-search-state-DVCp4JQf.mjs";import{S,c as U,g as v,d as A,e as k,a as b}from"./fts-companion-pUdD6kF-.mjs";import{sql as s}from"drizzle-orm";import{matchesStaticWhere as G}from"./AGGREGATE_SQL_FUNCTION-DDEoMnJR.mjs";import{aggregateTableName as W,encodeAggregateKey as B,foldAggregateTally as H}from"./aggregateTableName-C7o-gpms.mjs";import{rankColumnsSql as N,insertRankRow as K}from"./createCompanionSync-Rjn0lsT6.mjs";import{runDrizzle as l,runAll as $}from"./runDrizzle-Du5HLitO.mjs";import{i as C,D as p,r as O,a as Y,b as j,A as z,h as M}from"./do-sql-BEFrJUds.mjs";import{sqliteInList as V}from"./WORKERD_SQLITE_LIMITS-DBH23L_S.mjs";import{isLiveForCompanion as J}from"./CURSOR_PREFIX-BX8jkMJa.mjs";import{rankTableName as Q,matchesRankStaticWhere as X}from"./RANK_TIEBREAK-B0_x8iev.mjs";const L=(e,o)=>l(e,s`SELECT COUNT(*) AS count FROM ${s.identifier(o)}`).one().count>0,Z=(e,o)=>l(e,s`SELECT 1 FROM ${s.identifier(o)} LIMIT 1`).toArray().length>0,_=(e,o)=>l(e,s`SELECT id, _creationTime, ${s.identifier(p)} FROM ${s.identifier(o)}`).toArray(),q=(e,o,r,n)=>{const t=W(o,r.name);if(L(e,t))return;const a=r.by??[],c=new Map,i=_(e,o);for(const d of i){const f=O(d);if(!f||!J(f,n)||r.where&&!G(f,r.where))continue;const g=B(a,f);H(c,g,r,f)}for(const[d,f]of c)l(e,s`INSERT INTO ${s.identifier(t)} (${Y}, ${j}, ${z}) VALUES (${d}, ${f.value}, ${f.count})`)},pe=(e,o)=>{for(const[r,n]of Object.entries(o.tables))if(!(n.shardMode?.kind==="global"||!n.aggregateIndexes))for(const t of n.aggregateIndexes)q(e,r,t,n.softDeleteMode?.field)},ee=(e,o,r)=>{const n=Q(o,r.name);if(L(e,n))return;const t=N(r),a=_(e,o);for(const c of a){const i=O(c);!i||r.where&&!X(i,r.where)||K(e,n,r,t,i._id,i)}},Se=(e,o)=>{for(const[r,n]of Object.entries(o.tables))if(!(n.shardMode?.kind==="global"||!n.rankIndexes))for(const t of n.rankIndexes)ee(e,r,t)},oe=(e,o,r,n)=>l(e,r===void 0?s`SELECT id, _creationTime, ${s.identifier(p)} FROM ${s.identifier(o)} ORDER BY id ASC LIMIT ${s.raw(String(n))}`:s`SELECT id, _creationTime, ${s.identifier(p)} FROM ${s.identifier(o)} WHERE id > ${r} ORDER BY id ASC LIMIT ${s.raw(String(n))}`).toArray(),h=500,y=(e,o,r)=>{const n=S(o,r.name),t=T(r),a=R(E(e,n),t);if(a.finished)return{done:!0,rows:0};const{cursor:c}=a,i=oe(e,o,c,h);let d=c;for(const g of i){const{id:u}=g;if(typeof u!="string")continue;d=u;const I=M(g);$(e,I?A(n,u,k(I,r)):b(n,u))}const f=i.length<h;return D(e,n,d,f,t),{done:f,rows:i.length}},m=(e,o)=>s`${s.identifier(e)}.${s.identifier(o)}`,w=500,F=(e,o,r)=>{const n=S(o,r.name),t=l(e,U(n,w)).toArray(),a=v(t);if(a.size===0)return!0;const c=new Map;for(const i of l(e,s`SELECT ${m(o,"id")}, ${m(o,"_creationTime")}, ${m(o,p)} FROM ${s.identifier(o)} WHERE ${V(m(o,"id"),[...a.keys()],!1)}`))c.set(String(i.id),i);for(const[i,d]of a){const f=c.get(i),g=f?M(f):void 0;$(e,g?A(n,i,k(g,r),{unmappedRowids:d}):b(n,i,{unmappedRowids:d}))}return t.length<w},ne=(e,o,r,n)=>{let t=0;for(;t<n&&!F(e,o,r);)t+=1;return t},Ie=(e,o,r)=>{const n=S(o,r.name),t=T(r);return R(E(e,n),t).finished?!0:P(e,n)},he=(e,o,r)=>{if(C(e))for(const n of r.searchIndexes??[])F(e,o,n),!(n.staged&&Z(e,o))&&y(e,o,n)},re=(e,o,r,n)=>{let t=0;for(;;){if(t>=n)return{done:!1,pages:t};const a=y(e,o,r);if(a.rows>0&&(t+=1),a.done)return{done:!0,pages:t}}},we=(e,o,r={})=>{if(!C(e))return{done:!0,pages:0};x(e);const n=r.maxPages??Number.POSITIVE_INFINITY;let t=0;for(const[a,c]of Object.entries(o.tables))if(!(c.shardMode?.kind==="global"||!c.searchIndexes))for(const i of c.searchIndexes){if(t+=ne(e,a,i,n-t),t>=n)return{done:!1,pages:t};const d=re(e,a,i,n-t);if(t+=d.pages,!d.done)return{done:!1,pages:t}}return{done:!0,pages:t}};export{pe as backfillAggregateIndexes,Se as backfillRankIndexes,we as backfillSearchIndexes,he as backfillSearchIndexesForTable,oe as readKeysetPage,Ie as searchIndexCoversTable};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
const f=/key|secret|token|password|passwd|credential|private|auth|bearer|session|cookie|salt|signature|dsn|webhook/iu,l=new Set(["LUNORA_ADMIN_TOKEN","LUNORA_WS_BEARER"]),d=["CF_PAGES_URL","WORKER_URL","LUNORA_WORKER_URL"],u=["CF_ENV","ENVIRONMENT","WORKER_ENV","NODE_ENV"],p=n=>n.length<=4?"••••":`${n.slice(0,4)}${"•".repeat(Math.min(8,n.length-4))}`,R=n=>f.test(n),E=n=>{const e=o=>typeof n[o]=="function";return e("idFromName")||e("idFromString")?"durable-object":e("createMultipartUpload")||e("put")&&e("get")&&e("list")&&e("head")?"r2":e("getWithMetadata")?"kv":e("prepare")&&e("dump")?"d1":e("send")&&e("sendBatch")?"queue":e("fetch")&&!e("get")?"service":"object"},N=n=>{if(typeof n!="object"||n===null)return{};const e=n,o=i=>i.map(c=>e[c]).find(c=>typeof c=="string"&&c!==""),t={},r=o(d),s=o(u);r!==void 0&&(t.workerUrl=r),s!==void 0&&(t.environment=s);const a=e.CF_VERSION_METADATA;if(a!==null&&typeof a=="object"){const i=a;typeof i.id=="string"&&(t.deploymentId=i.id),typeof i.tag=="string"&&(t.versionTag=i.tag)}return t},_=/^(?:dev(?:elopment)?|local(?:host)?|test)$/iu,g=n=>{const e=n??{};for(const o of u){const t=e[o];if(typeof t=="string"&&_.test(t))return!0}return!1},v=n=>{const e=n??{},o=[];for(const[t,r]of Object.entries(e))if(!l.has(t)){if(typeof r=="string"){const s=R(t);o.push({kind:s?"secret":"var",name:t,value:p(r)});continue}if(typeof r=="number"||typeof r=="boolean"){o.push({kind:"var",name:t,value:String(r)});continue}if(r!==null&&typeof r=="object"){o.push({bindingType:E(r),kind:"binding",name:t,value:null});continue}o.push({kind:"var",name:t,value:null})}return o.sort((t,r)=>t.name.localeCompare(r.name)),{deploy:N(e),settings:o}};export{
|
|
1
|
+
const f=/key|secret|token|password|passwd|credential|private|auth|bearer|session|cookie|salt|signature|dsn|webhook/iu,l=new Set(["LUNORA_ADMIN_TOKEN","LUNORA_WS_BEARER"]),d=["CF_PAGES_URL","WORKER_URL","LUNORA_WORKER_URL"],u=["CF_ENV","ENVIRONMENT","WORKER_ENV","NODE_ENV"],p=n=>n.length<=4?"••••":`${n.slice(0,4)}${"•".repeat(Math.min(8,n.length-4))}`,R=n=>f.test(n),E=n=>{const e=o=>typeof n[o]=="function";return e("idFromName")||e("idFromString")?"durable-object":e("createMultipartUpload")||e("put")&&e("get")&&e("list")&&e("head")?"r2":e("getWithMetadata")?"kv":e("prepare")&&e("dump")?"d1":e("send")&&e("sendBatch")?"queue":e("fetch")&&!e("get")?"service":"object"},N=n=>{if(typeof n!="object"||n===null)return{};const e=n,o=i=>i.map(c=>e[c]).find(c=>typeof c=="string"&&c!==""),t={},r=o(d),s=o(u);r!==void 0&&(t.workerUrl=r),s!==void 0&&(t.environment=s);const a=e.CF_VERSION_METADATA;if(a!==null&&typeof a=="object"){const i=a;typeof i.id=="string"&&(t.deploymentId=i.id),typeof i.tag=="string"&&(t.versionTag=i.tag)}return t},_=/^(?:dev(?:elopment)?|local(?:host)?|test)$/iu,g=n=>{const e=n??{};for(const o of u){const t=e[o];if(typeof t=="string"&&_.test(t))return!0}return!1},v=n=>{const e=n??{},o=[];for(const[t,r]of Object.entries(e))if(!l.has(t)){if(typeof r=="string"){const s=R(t);o.push({kind:s?"secret":"var",name:t,value:p(r)});continue}if(typeof r=="number"||typeof r=="boolean"){o.push({kind:"var",name:t,value:String(r)});continue}if(r!==null&&typeof r=="object"){o.push({bindingType:E(r),kind:"binding",name:t,value:null});continue}o.push({kind:"var",name:t,value:null})}return o.sort((t,r)=>t.name.localeCompare(r.name)),{deploy:N(e),settings:o}};export{v as buildSettings,g as isDevEnvironment,N as readDeployInfo};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{LunoraError as g}from"@lunora/errors";import{sql as o}from"drizzle-orm";import{mergeWhere as b}from"./CountRlsUnsupportedError-BvsDqfO2.mjs";import{SCAN_DEP as j}from"./SCAN_DEP-D7qE3iUe.mjs";import{runDrizzle as A}from"./runDrizzle-Du5HLitO.mjs";import{sqliteInList as O}from"./WORKERD_SQLITE_LIMITS-DBH23L_S.mjs";import{decodeCursor as F,CURSOR_PREFIX as P,toBase64 as U}from"./CURSOR_PREFIX-
|
|
1
|
+
import{LunoraError as g}from"@lunora/errors";import{sql as o}from"drizzle-orm";import{mergeWhere as b}from"./CountRlsUnsupportedError-BvsDqfO2.mjs";import{SCAN_DEP as j}from"./SCAN_DEP-D7qE3iUe.mjs";import{runDrizzle as A}from"./runDrizzle-Du5HLitO.mjs";import{sqliteInList as O}from"./WORKERD_SQLITE_LIMITS-DBH23L_S.mjs";import{decodeCursor as F,CURSOR_PREFIX as P,toBase64 as U}from"./CURSOR_PREFIX-BX8jkMJa.mjs";import{rankTableName as V,sortColumnName as z,resolveRankPartition as H,RANK_TIEBREAK as _,encodePartitionKey as J,rankPivotConditionSql as X}from"./RANK_TIEBREAK-B0_x8iev.mjs";const Y="__doc__",G=n=>P+U(JSON.stringify(n)),Q=n=>n.after?[n.after.partitionKey,...n.after.sortValues,n.after.rowId]:n.cursor?F(n.cursor):void 0,Z=(n,r,f)=>{if(n?.length!==1+r.length+1)return;const t=[{column:"__partition__",direction:"asc"}];for(const[c,u]of r.entries())t.push({column:u,direction:f[c]?.direction??"asc"});t.push({column:_,direction:"asc"});const e=[];for(const[c,u]of t.entries()){const d=X(u.column,n[c],u.direction,!0);if(d===void 0)continue;const s=[];for(const[m,l]of t.slice(0,c).entries())s.push(o`${o.identifier(l.column)} IS ${n[m]}`);s.push(d);const[i]=s;e.push(s.length===1&&i!==void 0?i:o`(${o.join(s,o` AND `)})`)}return e.length===0?o`(1 = 0)`:o`(${o.join(e,o` OR `)})`},v=null,oo=(n,r)=>{if(n===void 0)return v;const f=[n.__partition__,...r.map(t=>n[t]),n[_]];return G(f)},no=(n,r,f)=>{const t=[];for(const e of n){const c=e[_];if(typeof c!="string")continue;const u=r.get(c);if(!u)continue;const d=typeof e.__partition__=="string"?e.__partition__:"",s=f.map(i=>e[i]??null);t.push({doc:u,key:{partitionKey:d,rowId:c,sortValues:s}})}return t},to=o`${o.identifier("id")}`,ro=(n,r,f)=>{const{rowToDocument:t}=n,e=new Map;if(f.length===0)return e;const c=A(n.sql,o`SELECT id, _creationTime, ${o.identifier(Y)} FROM ${o.identifier(r)} WHERE ${O(to,f,!1)}`).toArray();for(const u of c){const d=t(u),s=u.id;d&&typeof s=="string"&&e.set(s,d)}return e},_o=(n,r,f,t)=>{const{assertRankPartitionLocal:e,ensureRankBackfilled:c,onRead:u,schema:d}=n,s=d.tables[r];if(!s)throw new g("INTERNAL",`unknown table: ${r}`);const i=s.rankIndexes?.find(a=>a.name===f);if(!i)throw new g("INTERNAL",`unknown rankIndex "${f}" on table "${r}"`);e(r,s,i),u(r,j),c(r,i);const m=V(r,i.name),l=i.sortBy.map((a,w)=>z(w)),h=Math.max(1,Math.min(1e3,Math.floor(t.take??100))),T=b(t.baseWhere,t.where),k=H(i,T),R=[o`${o.identifier("__partition__")} ASC`];for(const[a,w]of l.entries()){const W=i.sortBy[a]?.direction;R.push(o`${o.identifier(w)} ${o.raw(W==="desc"?"DESC":"ASC")}`)}R.push(o`${o.identifier(_)} ASC`);const p=[];typeof t.partitionKey=="string"?p.push(o`${o.identifier("__partition__")} = ${t.partitionKey}`):k&&p.push(o`${o.identifier("__partition__")} = ${J(i.partitionBy??[],k)}`);const B=Q(t),E=Z(B,l,i.sortBy);E&&p.push(E);const I=o.identifier(_),S=o.identifier("__partition__"),D=p.length>0?o` WHERE ${o.join(p,o` AND `)}`:o``,L=l.length>0?o`${I}, ${S}, ${o.join(l.map(a=>o.identifier(a)),o`, `)}`:o`${I}, ${S}`,M=o`SELECT ${L} FROM ${o.identifier(m)}${D} ORDER BY ${o.join(R,o`, `)} LIMIT ${o.raw(String(h+1))}`,$=A(n.sql,M).toArray(),C=$.length>h,y=C?$.slice(0,h):$,K=y.map(a=>a[_]),q=no(y,ro(n,r,K),l),x=C?oo(y.at(-1),l):v,N=i.sortBy.map(a=>a.direction==="desc"?"desc":"asc");return{continueCursor:x,directions:N,hasMore:C,rows:q}};export{_o as computeRankPage,Q as resolveRankSeekTuple};
|
package/dist/packem_shared/{createCompanionSync-BpE0xoMp.mjs → createCompanionSync-Rjn0lsT6.mjs}
RENAMED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{N as re,S as se,d as ie,e as ce,a as ae}from"./fts-companion-pUdD6kF-.mjs";import{sql as e}from"drizzle-orm";import{matchesStaticWhere as V,aggregateSqlFunction as fe}from"./AGGREGATE_SQL_FUNCTION-DDEoMnJR.mjs";import{aggregateTableName as P,encodeAggregateKey as v,foldAggregateTally as z,coerceAggregateNumber as D}from"./aggregateTableName-C7o-gpms.mjs";import{runDrizzle as $,runAll as le}from"./runDrizzle-Du5HLitO.mjs";import{i as $e,g as de,D as b,r as q,a as O,b as m,A as g,c as M,e as W}from"./do-sql-BEFrJUds.mjs";import{param as ue,WORKERD_SQLITE_LIMITS as Ee}from"./WORKERD_SQLITE_LIMITS-DBH23L_S.mjs";import{encodeGeohash as ge,GEO_DEFAULT_PRECISION as pe}from"./GEO_DEFAULT_PRECISION-CqpQZ-J_.mjs";import{isLiveForCompanion as Q}from"./CURSOR_PREFIX-
|
|
1
|
+
import{N as re,S as se,d as ie,e as ce,a as ae}from"./fts-companion-pUdD6kF-.mjs";import{sql as e}from"drizzle-orm";import{matchesStaticWhere as V,aggregateSqlFunction as fe}from"./AGGREGATE_SQL_FUNCTION-DDEoMnJR.mjs";import{aggregateTableName as P,encodeAggregateKey as v,foldAggregateTally as z,coerceAggregateNumber as D}from"./aggregateTableName-C7o-gpms.mjs";import{runDrizzle as $,runAll as le}from"./runDrizzle-Du5HLitO.mjs";import{i as $e,g as de,D as b,r as q,a as O,b as m,A as g,c as M,e as W}from"./do-sql-BEFrJUds.mjs";import{param as ue,WORKERD_SQLITE_LIMITS as Ee}from"./WORKERD_SQLITE_LIMITS-DBH23L_S.mjs";import{encodeGeohash as ge,GEO_DEFAULT_PRECISION as pe}from"./GEO_DEFAULT_PRECISION-CqpQZ-J_.mjs";import{isLiveForCompanion as Q}from"./CURSOR_PREFIX-BX8jkMJa.mjs";import{encodePartitionKey as ye,sortColumnName as _e,rankTableName as X,matchesRankStaticWhere as Y}from"./RANK_TIEBREAK-B0_x8iev.mjs";import{mayHoldProjectedValue as me}from"./BIGINT_KEY_DIGITS-C9a7Ix7k.mjs";import{serializeSqlValue as J}from"./serializeSqlValue-BbZ5hKM7.mjs";const he=(_,R,p)=>[..._.partitionBy??[],..._.sortBy.map(h=>h.field),..._.where?Object.keys(_.where):[]].every(h=>R[h]===p[h]),Z=_=>e.join(["__id__","__partition__",..._.sortBy.map((R,p)=>_e(p))].map(R=>e.identifier(R)),e`, `),N=(_,R,p,F,h,u)=>{const s=ye(p.partitionBy??[],u),C=p.sortBy.map(I=>J(u[I.field]??null)),L=e.join([h,s,...C].map(I=>ue(I)),e`, `);$(_,e`INSERT INTO ${e.identifier(R)} (${F}) VALUES (${L})`)},Te=(_,R,p,F,h,u)=>{if(h&&u&&he(p,h,u))return;const s=X(R,p.name);h&&$(_,e`DELETE FROM ${e.identifier(s)} WHERE ${e.identifier("__id__")} = ${F}`),!(!u||p.where&&!Y(u,p.where))&&N(_,s,p,Z(p),F,u)},be=_=>{const{broadcast:R,indexKeysFor:p,invalidateCache:F,recordCdc:h,schema:u,sql:s}=_,C=new Set,L=n=>u.tables[n]?.softDeleteMode?.field,I=new Set,U=(n,o)=>{const r=`${n}::${o.name}`;if(C.has(r))return;const c=P(n,o.name),a=o.by??[],f=L(n),d=new Map,y=$(s,e`SELECT id, _creationTime, ${e.identifier(b)} FROM ${e.identifier(n)}`).toArray();for(const T of y){const l=q(T);if(!l||!Q(l,f)||o.where&&!V(l,o.where))continue;const S=v(a,l);z(d,S,o,l)}$(s,e`DELETE FROM ${e.identifier(c)}`);const A=Math.floor(Ee.boundParams/3),w=[...d];for(let T=0;T<w.length;T+=A){const l=w.slice(T,T+A),S=e.join(l.map(([t,i])=>e`(${t}, ${i.value}, ${i.count})`),e`, `);$(s,e`INSERT INTO ${e.identifier(c)} (${O}, ${m}, ${g}) VALUES ${S}`)}C.add(r)},x=(n,o,r)=>{const c=o.by??[],a=o.field??"",f=[],d=(t,i)=>{const E=J(i);E===null?f.push(e`${W(t)} IS NULL`):f.push(e`${W(t)} = ${E}`)};for(const t of c)d(t,r[t]??null);const y=L(n);y!==void 0&&d(y,null);for(const[t,i]of Object.entries(o.where??{}))d(t,i!==null&&typeof i=="object"&&!Array.isArray(i)?i.eq:i);const A=f.length>0?e` WHERE ${e.join(f,e` AND `)}`:e``,w=u.tables[n]?.shape[a];if(w&&me(w)){const t=$(s,e`SELECT id, _creationTime, ${e.identifier(b)} FROM ${e.identifier(n)}${A}`).toArray(),i=new Map;for(const E of t){const k=q(E);k&&z(i,"",o,k)}return{value:i.get("")?.value??null}}const T=fe(o.op),l=W(a);return{value:$(s,e`SELECT ${e.raw(T)}(${l}) AS value FROM ${e.identifier(n)}${A}`).one().value??null}},ee=(n,o,r,c)=>{const a=P(n,o.name),{op:f}=o,d=o.field??"",y=t=>{$(s,e`DELETE FROM ${e.identifier(a)} WHERE ${O} = ${t} AND ${g} <= 0`)},A=L(n),w=t=>!o.where||V(t,o.where),T=t=>Q(t,A)&&w(t);c!==void 0&&f!=="count"&&w(c)&&D(c[d]);const l=r&&T(r)?r:void 0,S=c&&T(c)?c:void 0;if(!(!l&&!S)){if(f==="count"){for(const[t,i]of[[l,-1],[S,1]]){if(!t)continue;const E=v(o.by??[],t);$(s,M(a,E,i,i,e`${m} = ${m} + excluded.${m}, ${g} = ${g} + excluded.${g}`))}l&&y(v(o.by??[],l));return}if(f==="sum"||f==="avg"){for(const[t,i]of[[l,-1],[S,1]]){if(!t)continue;const E=D(t[d]);if(E===void 0)continue;const k=v(o.by??[],t);$(s,M(a,k,i*E,i,e`${m} = COALESCE(${m}, 0) + excluded.${m}, ${g} = ${g} + excluded.${g}`))}l&&y(v(o.by??[],l));return}if(l){const t=v(o.by??[],l),i=D(l[d]),E=$(s,e`SELECT ${m} AS value, ${g} AS count FROM ${e.identifier(a)} WHERE ${O} = ${t}`).toArray()[0],k=(E?.count??0)-1;if(k<=0)$(s,e`DELETE FROM ${e.identifier(a)} WHERE ${O} = ${t}`);else if(E&&i!==void 0&&E.value!==null&&i===E.value){const te=x(n,o,l);$(s,e`UPDATE ${e.identifier(a)} SET ${m} = ${te.value}, ${g} = ${k} WHERE ${O} = ${t}`)}else $(s,e`UPDATE ${e.identifier(a)} SET ${g} = ${g} - 1 WHERE ${O} = ${t}`)}if(S){const t=v(o.by??[],S),i=D(S[d]);if(i===void 0)$(s,M(a,t,null,1,e`${g} = ${g} + 1`));else{const E=f==="min"?"MIN":"MAX";$(s,M(a,t,i,1,e`${m} = ${e.raw(E)}(COALESCE(${m}, excluded.${m}), excluded.${m}), ${g} = ${g} + 1`))}}}},oe=n=>{for(const o of u.tables[n]?.aggregateIndexes??[])U(n,o)},j=(n,o,r)=>{for(const c of u.tables[n]?.aggregateIndexes??[])ee(n,c,o,r)},B=(n,o)=>{const r=`${n}::rank::${o.name}`;if(I.has(r))return;const c=X(n,o.name),a=$(s,e`SELECT id, _creationTime, ${e.identifier(b)} FROM ${e.identifier(n)}`).toArray();$(s,e`DELETE FROM ${e.identifier(c)}`);const f=Z(o);for(const d of a){const y=q(d);!y||o.where&&!Y(y,o.where)||N(s,c,o,f,y._id,y)}I.add(r)},ne=n=>{for(const o of u.tables[n]?.rankIndexes??[])B(n,o)},H=(n,o,r,c)=>{for(const a of u.tables[n]?.rankIndexes??[])Te(s,n,a,o,r,c)},K=(n,o,r,c)=>{const a=u.tables[n]?.searchIndexes??[];if(!(a.length===0||!$e(s)))for(const f of a){if(re(c,r,f))continue;const d=se(n,f.name);le(s,r?ie(d,o,ce(r,f)):ae(d,o))}},G=(n,o,r)=>{for(const c of u.tables[n]?.geoIndexes??[]){const a=de(n,c.name);$(s,e`DELETE FROM ${e.identifier(a)} WHERE ${e.identifier("__id__")} = ${o}`);const f=r?.[c.field];if(f!==null&&typeof f=="object"&&typeof f.lat=="number"&&typeof f.lng=="number"){const{lat:d,lng:y}=f,A=ge({lat:d,lng:y},c.precision??pe);$(s,e`INSERT INTO ${e.identifier(a)} (${e.identifier("__id__")}, ${e.identifier("__geohash__")}, ${e.identifier("__lat__")}, ${e.identifier("__lng__")}) VALUES (${o}, ${A}, ${d}, ${y})`)}}};return{ensureBackfilledForTable:oe,ensureBackfilledIndex:U,ensureRankBackfilled:B,ensureRankBackfilledForTable:ne,syncAggregates:j,syncCompanionsForInsert:(n,o,r)=>{K(n,o,r),G(n,o,r),j(n,void 0,r),H(n,o,void 0,r),F(n,o,r),h(n,o,"insert",r),R({indexKeys:p(n,r),key:o,op:"insert",row:r,table:n})},syncGeo:G,syncRanks:H,syncSearch:K}};export{be as createCompanionSync,N as insertRankRow,Z as rankColumnsSql};
|
package/dist/packem_shared/{ctx-db-relay-shapes-CClD3ldv.mjs → ctx-db-relay-shapes-DuqhDLw8.mjs}
RENAMED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{sql as i}from"drizzle-orm";import{e as l,d as E}from"./wire-codec-C-FpWm52.mjs";import{runDrizzle as a}from"./runDrizzle-Du5HLitO.mjs";import{relayProxyKey as T}from"./DEFAULT_PROMOTION_THRESHOLDS-
|
|
1
|
+
import{sql as i}from"drizzle-orm";import{e as l,d as E}from"./wire-codec-C-FpWm52.mjs";import{runDrizzle as a}from"./runDrizzle-Du5HLitO.mjs";import{relayProxyKey as T}from"./DEFAULT_PROMOTION_THRESHOLDS-91RH_llq.mjs";const t="__lunora_relay_shapes",o=null,R=e=>{a(e,i`CREATE TABLE IF NOT EXISTS ${i.identifier(t)} (
|
|
2
2
|
key TEXT PRIMARY KEY,
|
|
3
3
|
relay_idx INTEGER,
|
|
4
4
|
connection_id TEXT,
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{createShardCtxDb as v}from"./NotUniqueError-
|
|
1
|
+
import{createShardCtxDb as v}from"./NotUniqueError-D4EV8EzO.mjs";import{createRelayLink as I}from"./DEFAULT_MAX_RELAYS-hdowkC2x.mjs";import{ConflictError as N}from"./ConflictError-C8GtJmjS.mjs";import{runShardMigrations as _}from"./runShardMigrations-MXioI81k.mjs";import{relayName as F}from"./DEFAULT_PROMOTION_THRESHOLDS-91RH_llq.mjs";const E=(C,m={})=>({_meta:{column:{notNull:!0,...m}},kind:C}),W=(C,m,O)=>{const{describe:S,expect:n,it:y}=O;S(`engine contract: ${C}`,()=>{S("optimistic concurrency",()=>{const b=u=>({tables:{items:{indexes:[],shape:{title:E("string"),version:E("number",{notNull:!1})},triggerMap:{clobber:{handler:()=>{u.exec(`UPDATE "items" SET "__doc__" = json_set("__doc__", '$.version', 99) WHERE "id" = 'i1'`)},op:"update",timing:"before"}}}}});y("raises a CONFLICT of kind `occ` when a write's snapshot is clobbered",async()=>{const{close:u,host:h}=m();try{const i=h.sql,l=b(i);_(i,l);const s=v({schema:l,sql:i});await s.insert("items",{_id:"i1",title:"first",version:1},{allowExplicitId:!0}),await n(s.patch("i1",{title:"second"})).rejects.toBeInstanceOf(N)}finally{u?.()}}),y("reports the conflict as CONFLICT/409 rather than retrying it away",async()=>{const{close:u,host:h}=m();try{const i=h.sql,l=b(i);_(i,l);const s=v({schema:l,sql:i});await s.insert("items",{_id:"i1",title:"first",version:1},{allowExplicitId:!0});let o;try{await s.patch("i1",{title:"second"})}catch(t){o=t}const e=o;n(e.code).toBe("CONFLICT"),n(e.kind).toBe("occ")}finally{u?.()}}),y("leaves the row readable and unchanged after a conflict",async()=>{const{close:u,host:h}=m();try{const i=h.sql,l=b(i);_(i,l);const s=v({schema:l,sql:i});await s.insert("items",{_id:"i1",title:"first",version:1},{allowExplicitId:!0});try{await s.patch("i1",{title:"second"})}catch{}const o=await s.get("i1");n(o?.title).toBe("first"),n(o?.version).toBe(99)}finally{u?.()}}),y("raises a CONFLICT of kind `trigger` when a trigger writes its own row through the db",async()=>{const{close:u,host:h}=m();try{const i=h.sql,l={tables:{items:{indexes:[],shape:{title:E("string"),version:E("number",{notNull:!1})},triggerMap:{recurse:{handler:async(t,a)=>{await t.db.patch(a.doc._id,{version:99})},op:"update",timing:"before"}}}}};_(i,l);const s=v({schema:l,sql:i});await s.insert("items",{_id:"i1",title:"first",version:1},{allowExplicitId:!0});let o;try{await s.patch("i1",{title:"second"})}catch(t){o=t}const e=o;n(e).toBeInstanceOf(N),n(e.code).toBe("CONFLICT"),n(e.kind).toBe("trigger")}finally{u?.()}})}),S("shape-poke ordering",()=>{const b="shard-a",u={args:{},name:"messages"},h=(e,t,a,r)=>e.accept(t?.()??{},{connectionId:a,shapes:{[r]:u}}),i=(e,t,a)=>{let r=0,d=0;const c=g=>()=>{throw new Error(`the relay poke path must not reach RelayHost.${g}`)},p={fetch:(g,q)=>{if(JSON.parse(q?.body??"{}").type!=="relay_shape_subscribe")return Promise.resolve(new Response(void 0,{status:204}));const B=a[d];if(d+=1,B===void 0)throw new Error("the relay asked for more seeds than this fixture supplies");return Promise.resolve(Response.json(B))}},k={get:()=>p,getByName:()=>p,idFromName:g=>g},w={buildShapeDiff:c("buildShapeDiff"),computeOpLogShapeSeed:c("computeOpLogShapeSeed"),currentCdcEpoch:c("currentCdcEpoch"),deliverWhisperLocal:c("deliverWhisperLocal"),doName:()=>F(b,0),env:()=>({SHARD:k}),getWebSockets:()=>e.getSockets(),maskMetadata:c("maskMetadata"),nextPokeId:()=>(r+=1,`poke-${String(r)}`),readAttachment:g=>g.deserializeAttachment?.(),recordShapePokeFanout:()=>{},resolveShape:c("resolveShape"),rlsMetadata:c("rlsMetadata"),shardBinding:()=>"SHARD",shardJurisdiction:()=>{},sql:()=>t},f=I(w);if(f===void 0)throw new Error("expected a relay link for a `…::relay::N` name");return f},l=e=>new Request("https://relay.internal/_lunora/relay",{body:JSON.stringify(e),headers:{"content-type":"application/json"},method:"POST"}),s=async(e,t,a)=>{const r=await e.seedRelayShape(t,a,u,{identity:void 0,userId:void 0});if(r!=="ok")throw new Error(`seed failed: ${JSON.stringify(r)}`)},o=(e={})=>l({...u,checkpoint:20,epoch:"e1",fromCursor:10,rowsPatch:[{id:"r1",op:"upsert",value:{title:"hello"}}],type:"relay_shape_poke",...e});y("frames a poke as pokeStart → pokePart per shape → pokeEnd, under one poke id",async()=>{const{close:e,createSocket:t,host:a,readFrames:r,sockets:d}=m();try{const c=i(d,a.sql,[{cursor:10,epoch:"e1",frames:[]}]),p=h(d,t,"c-alice","s1");await s(c,p,"s1"),await c.handleControl(o());const w=(await r(p)).map(f=>JSON.parse(f));n(w.map(f=>f.type)).toStrictEqual(["pokeStart","pokePart","pokeEnd"]),n(new Set(w.map(f=>f.pokeId)).size).toBe(1),n(w[1]?.shapeId).toBe("s1"),n(w[2]?.checkpoint).toBe(20)}finally{e?.()}}),y("delivers a poke only to sockets whose cursor matches, and advances them past it",async()=>{const{close:e,createSocket:t,host:a,readFrames:r,sockets:d}=m();try{const c=i(d,a.sql,[{cursor:10,epoch:"e1",frames:[]},{cursor:7,epoch:"e1",frames:[]}]),p=h(d,t,"c-alice","s1"),k=h(d,t,"c-bob","s2");await s(c,p,"s1"),await s(c,k,"s2"),await c.handleControl(o());const w=await r(p);n(w.length).toBe(3);const f=await r(k);n(f.length).toBe(0),await c.handleControl(o());const g=await r(p);n(g.length).toBe(3)}finally{e?.()}}),y("skips a socket whose cursor matches under a different CDC epoch",async()=>{const{close:e,createSocket:t,host:a,readFrames:r,sockets:d}=m();try{const c=i(d,a.sql,[{cursor:10,epoch:"e1",frames:[]}]),p=h(d,t,"c-alice","s1");await s(c,p,"s1"),await c.handleControl(o({epoch:"e2"}));const k=await r(p);n(k.length).toBe(0),await c.handleControl(o());const w=await r(p);n(w.length).toBe(3)}finally{e?.()}})}),S("RLS identity under live subscription",()=>{const b="shard-a",u={args:{},name:"lobby-messages"},h={args:{},name:"my-orders"},i=s=>{const o=[],e=[],t={fetch:(d,c)=>(o.push(JSON.parse(c?.body??"{}")),Promise.resolve(new Response(void 0,{status:204})))},r=I({buildShapeDiff:()=>[{id:"r1",op:"upsert",value:{}}],computeOpLogShapeSeed:()=>({baseCheckpoint:void 0,cursor:10,epoch:"e1",reset:!0,rowsPatch:[]}),currentCdcEpoch:()=>"e1",deliverWhisperLocal:()=>0,doName:()=>b,env:()=>({SHARD:{get:()=>t,getByName:()=>t,idFromName:d=>d}}),getWebSockets:()=>[],maskMetadata:()=>({columns:[]}),nextPokeId:()=>"poke-1",readAttachment:()=>({}),recordShapePokeFanout:()=>{},resolveShape:(d,c,p)=>(e.push(p),d===h.name?{columns:["id"],effectiveWhere:{org:p?.identity?.org??"anonymous"},global:!1,table:"orders"}:{columns:["id"],effectiveWhere:{room:"lobby"},global:!1,table:"messages"}),rlsMetadata:()=>({policies:[]}),shardBinding:()=>"SHARD",shardJurisdiction:()=>{},sql:()=>s});if(r===void 0)throw new Error("expected an owner link for an un-suffixed DO name");return{owner:r,posts:o,resolvedUnder:e}},l=async(s,o)=>{await s.handleControl(new Request("https://owner.internal/_lunora/relay",{body:JSON.stringify({...o,connectionId:"c-alice",identity:{org:"acme"},relayIndex:0,subId:"s1",type:"relay_shape_subscribe",userId:"u1"}),headers:{"content-type":"application/json"},method:"POST"}))};y("seeds a subscriber under its own forwarded identity, never the anonymous one",async()=>{const{close:s,host:o}=m();try{const{owner:e,resolvedUnder:t}=i(o.sql);await l(e,h),n(t.some(a=>a?.userId==="u1"&&a.identity?.org==="acme")).toBe(!0)}finally{s?.()}}),y("routes an identity-scoped shape to a per-socket poke, not the cohort multicast",async()=>{const{close:s,host:o}=m();try{const{owner:e,posts:t}=i(o.sql);await l(e,h),t.length=0,await e.onFlush(new Set(["orders"]),20);const a=t.filter(r=>r.type==="relay_shape_poke");n(a.length).toBe(1),n(a[0]?.targetConnectionId).toBe("c-alice")}finally{s?.()}}),y("still multicasts an identity-blind shape to the whole cohort",async()=>{const{close:s,host:o}=m();try{const{owner:e,posts:t}=i(o.sql);await l(e,u),t.length=0,await e.onFlush(new Set(["messages"]),20);const a=t.filter(r=>r.type==="relay_shape_poke");n(a.length).toBe(1),n(a[0]?.targetConnectionId).toBeUndefined()}finally{s?.()}})})})};export{W as defineEngineContractSuite};
|
package/dist/packem_shared/{runShardMigrations-DvjE3byP.mjs → runShardMigrations-MXioI81k.mjs}
RENAMED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{LunoraError as l}from"@lunora/errors";import{f as L,S as h}from"./fts-companion-pUdD6kF-.mjs";import{sql as r}from"drizzle-orm";import{aggregateTableName as O}from"./aggregateTableName-C7o-gpms.mjs";import{backfillSearchIndexesForTable as R}from"./backfillAggregateIndexes-
|
|
1
|
+
import{LunoraError as l}from"@lunora/errors";import{f as L,S as h}from"./fts-companion-pUdD6kF-.mjs";import{sql as r}from"drizzle-orm";import{aggregateTableName as O}from"./aggregateTableName-C7o-gpms.mjs";import{backfillSearchIndexesForTable as R}from"./backfillAggregateIndexes-B_3xdOgV.mjs";import{migrateCdcLog as x,migrateCdcMeta as N}from"./CDC_LOG_TABLE-QaBxSIZM.mjs";import{migrateClientWatermark as C}from"./CLIENT_WATERMARK_TABLE-vLjfNhBR.mjs";import{migrateCommitSeq as $}from"./COMMIT_SEQ_FIELD-BY_vc9bw.mjs";import{migrateGlobalShapeSnapshot as b}from"./GLOBAL_SHAPE_SNAPSHOT_TABLE-pMxZ-obU.mjs";import{migrateIdempotency as D}from"./IDEMPOTENCY_TABLE-AOJCuq5U.mjs";import{m as U}from"./ctx-db-relay-shapes-DuqhDLw8.mjs";import{migrateScheduleOutbox as M}from"./SCHEDULE_OUTBOX_TABLE-CgLvGxpY.mjs";import{m as G}from"./ctx-db-search-state-DVCp4JQf.mjs";import{migrateShapePokeCursor as X}from"./SHAPE_POKE_CURSOR_TABLE-cn0stGAL.mjs";import{runDrizzle as s,runAll as y}from"./runDrizzle-Du5HLitO.mjs";import{D as F,d as E,e as g,t as P,i as Y,g as k,a as B,b as j,A as p}from"./do-sql-BEFrJUds.mjs";import{renderSql as v}from"./WORKERD_SQLITE_LIMITS-DBH23L_S.mjs";import{migrateDurableStreams as w}from"./appendStreamChunk-7ZyAZGg_.mjs";import{rankTableName as H,sortColumnName as K}from"./RANK_TIEBREAK-B0_x8iev.mjs";import{migrateReactorState as W}from"./REACTOR_STATE_TABLE-B8IehLv8.mjs";import{recordSchemaVersion as V}from"./SCHEMA_HISTORY_MAX_VERSIONS-BMcUIqBY.mjs";const A=r`_creationTime, id`,S=(e,i,o,t,n,a)=>{const c=r.join(n.map(d=>r`${d} IS NOT NULL`),r` AND `);if(s(e,r`SELECT 1 FROM ${r.identifier(o)} WHERE ${c} GROUP BY ${t} HAVING COUNT(*) > 1 LIMIT 1`).toArray().length>0)throw new l("INTERNAL",`unique index "${i}" on "${o}" ${a}: existing rows are duplicates under it. De-duplicate the table with a data migration first; the previous index is left in place.`)},z=(e,i,o,t,n,a)=>{const m=s(e,r`SELECT sql FROM sqlite_master WHERE type = 'index' AND name = ${i} AND tbl_name = ${o}`).toArray()[0]?.sql;if(m==null)return;const d=_=>{const u=_.indexOf("(");return u===-1?void 0:_.slice(u,_.lastIndexOf(")")+1)},T=d(v("sqlite",E(i,o,t,n)).sql),f=d(m);T===void 0||f===void 0||T===f||(n&&S(e,i,o,t,a,"cannot be re-created with its new column list"),s(e,r`DROP INDEX IF EXISTS ${r.identifier(i)}`))},J=(e,i,o)=>s(e,r`SELECT 1 FROM sqlite_master WHERE type = 'index' AND name = ${i} AND tbl_name = ${o} LIMIT 1`).toArray().length>0,I=(e,i,o,t,n,a)=>{n&&!J(e,i,o)&&S(e,i,o,t,a,"cannot be created"),s(e,E(i,o,t,n))},Q=(e,i,o)=>{for(const t of o.indexes){const n=`${i}_${t.name}`,a=t.unique??!1,c=t.fields.map(T=>g(T)),m=r.join(c,r`, `),d=a?m:r`${m}, ${A}`;z(e,n,i,d,a,c),I(e,n,i,d,a,c)}for(const[t,n]of P(o)){if(!n.unique)continue;const a=g(t);I(e,`${i}_unique_${t}`,i,a,!0,[a])}},Z=(e,i,o)=>{if(!(!o.searchIndexes||o.searchIndexes.length===0||!Y(e))){for(const t of o.searchIndexes)y(e,L(h(i,t.name)));R(e,i,o)}},q=(e,i,o)=>{if(o.geoIndexes)for(const t of o.geoIndexes){const n=k(i,t.name);s(e,r`CREATE TABLE IF NOT EXISTS ${r.identifier(n)} (${r.identifier("__id__")} TEXT PRIMARY KEY, ${r.identifier("__geohash__")} TEXT NOT NULL, ${r.identifier("__lat__")} REAL NOT NULL, ${r.identifier("__lng__")} REAL NOT NULL)`);const a=`${i}__geo_${t.name}__btree`;s(e,E(a,n,r`${r.identifier("__geohash__")} ASC, ${r.identifier("__id__")} ASC`,!1))}},ee=(e,i,o)=>{if(o.aggregateIndexes)for(const t of o.aggregateIndexes){const n=O(i,t.name);s(e,r`CREATE TABLE IF NOT EXISTS ${r.identifier(n)} (${B} TEXT PRIMARY KEY, ${j} REAL, ${p} INTEGER NOT NULL DEFAULT 0)`),s(e,r`PRAGMA table_info(${r.identifier(n)})`).toArray().some(c=>c.name==="__count__")||s(e,r`ALTER TABLE ${r.identifier(n)} ADD COLUMN ${p} INTEGER NOT NULL DEFAULT 0`)}},re=(e,i,o)=>{if(o.rankIndexes)for(const t of o.rankIndexes){const n=H(i,t.name),a=t.sortBy.map((f,_)=>K(_)),c=a.map(f=>r`${r.identifier(f)} BLOB`),m=c.length>0?r`, ${r.join(c,r`, `)}`:r``;s(e,r`CREATE TABLE IF NOT EXISTS ${r.identifier(n)} (${r.identifier("__id__")} TEXT PRIMARY KEY, ${r.identifier("__partition__")} TEXT NOT NULL${m})`);const d=[r`${r.identifier("__partition__")} ASC`];for(const[f,_]of a.entries()){const u=t.sortBy[f]?.direction;d.push(r`${r.identifier(_)} ${r.raw(u==="desc"?"DESC":"ASC")}`)}d.push(r`${r.identifier("__id__")} ASC`);const T=`${i}__rank_${t.name}__btree`;s(e,E(T,n,r.join(d,r`, `),!1))}},he=(e,i,o={})=>{o.schemaSnapshot!==void 0&&V(e,o.schemaSnapshot.hash,o.schemaSnapshot.json),G(e);for(const[t,n]of Object.entries(i.tables))n.shardMode?.kind!=="global"&&(s(e,r`CREATE TABLE IF NOT EXISTS ${r.identifier(t)} (
|
|
2
2
|
id TEXT PRIMARY KEY,
|
|
3
3
|
_creationTime REAL NOT NULL,
|
|
4
4
|
${r.identifier(F)} TEXT NOT NULL
|
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.97",
|
|
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.47",
|
|
52
|
+
"@lunora/platform": "1.0.0-alpha.42",
|
|
53
53
|
"drizzle-orm": "^0.45.2"
|
|
54
54
|
},
|
|
55
55
|
"engines": {
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{LunoraError as $}from"@lunora/errors";import{D as ut}from"./MAX_TOKEN_LENGTH-BakL9FUy-B3VwYY8C.mjs";import{S as mn,l as qe,h as Sn}from"./fts-companion-pUdD6kF-.mjs";import{sql as c}from"drizzle-orm";import{d as _n}from"./wire-codec-C-FpWm52.mjs";import{stableWireKey as It}from"./stableWireKey-D2US4k_J.mjs";import{throwingScheduler as Rn,aggregateSqlFunction as Be,normalizeCountArgument as Tn}from"./AGGREGATE_SQL_FUNCTION-DDEoMnJR.mjs";import{aggregateTableName as Xe,encodeAggregateKey as Ze,readAggregateValue as et}from"./aggregateTableName-C7o-gpms.mjs";import{mergeWhere as N,CountRlsUnsupportedError as tt,selectIndexForGroupBy as vn,selectIndexForCount as An,selectIndexForAggregate as In}from"./CountRlsUnsupportedError-BvsDqfO2.mjs";import{backfillSearchIndexesForTable as Cn,searchIndexCoversTable as xn}from"./backfillAggregateIndexes-D5q_pbdY.mjs";import{backfillAggregateIndexes as Or,backfillRankIndexes as Nr,backfillSearchIndexes as jr}from"./backfillAggregateIndexes-D5q_pbdY.mjs";import{appendCdcChange as bn,readCdcDocAtOrBefore as Mn}from"./CDC_LOG_TABLE-QaBxSIZM.mjs";import{CDC_LOG_TABLE as Qr,applyCdcChanges as Vr,bumpCdcEpoch as zr,cdcCanVouchFor as Jr,cdcForkedError as Yr,cdcSeqLeavingRows as Xr,cdcTouchesTables as Zr,cdcTrimmedError as ei,compactCdcDocs as ti,cursorBelowRetainedFloor as ni,minCdcReplayableSeq as oi,minCdcSeq as ri,readCdcChangeKeys as ii,readCdcChanges as si,readCdcCursor as ci,readCdcEpoch as ai,trimCdcChanges as di}from"./CDC_LOG_TABLE-QaBxSIZM.mjs";import{allocateCommitSeq as Dn,COMMIT_SEQ_FIELD as kn}from"./COMMIT_SEQ_FIELD-BY_vc9bw.mjs";import{createCompanionSync as Ln}from"./createCompanionSync-BpE0xoMp.mjs";import{isMemoryTable as Ct}from"./clearMemoryTables-CogAvVHR.mjs";import{computeRankPage as xt}from"./computeRankPage-BosAhREj.mjs";import{SCAN_DEP as O}from"./SCAN_DEP-D7qE3iUe.mjs";import{runSql as Te,runDrizzle as j}from"./runDrizzle-Du5HLitO.mjs";import{j as He,D as oe,r as Se,k as de,b as We,A as nt,a as Pe,e as ce,o as Fn,t as Zt,q as bt,i as qn,h as en,g as Bn}from"./do-sql-BEFrJUds.mjs";import{renderSql as tn,unionAll as ft,WORKERD_SQLITE_LIMITS as nn,sqliteInList as Wn}from"./WORKERD_SQLITE_LIMITS-DBH23L_S.mjs";import{coveringGeohashes as Pn,boundingBoxGeohashes as Un,haversineMeters as Gn,pointInBoundingBox as Hn}from"./GEO_DEFAULT_PRECISION-CqpQZ-J_.mjs";import{NotFoundError as On}from"./NotFoundError-BhF7FeFr.mjs";import{tiebreakDirectionFor as Nn,encodeCursor as Oe,normalizeOrderKeys as ct,uniqueIndexFields as on,buildSeekWhere as rn,decodeCursor as at,buildSeekBeforeWhere as jn,softDeleteScope as ue,equalityPinnedFields as Kn,applySelect as Mt}from"./CURSOR_PREFIX-Bn8SFoGd.mjs";import{rankTableName as Dt,sortColumnName as kt,resolveRankPartition as Qn,encodePartitionKey as Vn,RANK_TIEBREAK as zn,rankPivotConditionSql as Jn}from"./RANK_TIEBREAK-B0_x8iev.mjs";import{UNVOUCHABLE_DEP as Lt}from"./UNVOUCHABLE_DEP-C68htACn.mjs";import{indexKeysForRow as Yn,buildIndexRange as Xn}from"./buildIndexRange-6nIZDf4m.mjs";import{r as Ne,j as _e,c as te,t as je,i as Ft}from"./where-sql-DFs8Zw7-.mjs";import{serializeSqlValue as ae}from"./serializeSqlValue-BbZ5hKM7.mjs";import{quoteIdentifier as ve}from"./quoteIdentifier-CObIFRhb.mjs";import{whereOfFilter as Zn,isPushableWhere as eo}from"./isPushableWhere-BeYAOjUb.mjs";import{deriveRelationEdges as to,findRelated as no}from"./RELATED_DEFAULT_LIMIT-B9PH28Pn.mjs";import{assertFlatPredicate as ot,resolveRelationPredicates as qt}from"./DEFAULT_MAX_RELATION_KEYS-D_Urjl_L.mjs";import{runRowValidators as rt,resolveWith as Bt,relationHooks as Wt,applyOnDelete as oo,fanOutScalarCounts as ro}from"./applyOnDelete-7JZ4vR9r.mjs";import{guardWriter as io}from"./RLS_UNWRAP_SYMBOL-BwwTbz3Q.mjs";import{mayHoldProjectedValue as so}from"./BIGINT_KEY_DIGITS-C9a7Ix7k.mjs";import{createSystemReader as co}from"./createSystemReader-DcDLFfC-.mjs";import{ConflictError as Re}from"./ConflictError-C8GtJmjS.mjs";import{runTriggers as ao}from"./hasTrigger-CjlwI4le.mjs";import{CLIENT_WATERMARK_TABLE as ui,advanceClientWatermark as fi,migrateClientWatermark as hi,readClientWatermark as wi}from"./CLIENT_WATERMARK_TABLE-vLjfNhBR.mjs";import{GLOBAL_SHAPE_SNAPSHOT_TABLE as gi,deleteGlobalShapeSnapshot as yi,deleteGlobalShapeSnapshotsForConnection as $i,migrateGlobalShapeSnapshot as Ei,readGlobalShapeSnapshot as mi,writeGlobalShapeSnapshot as Si}from"./GLOBAL_SHAPE_SNAPSHOT_TABLE-pMxZ-obU.mjs";import{IDEMPOTENCY_TABLE as Ri,readIdempotent as Ti,trimIdempotent as vi,writeIdempotent as Ai}from"./IDEMPOTENCY_TABLE-AOJCuq5U.mjs";import{runShardMigrations as Ci}from"./runShardMigrations-DvjE3byP.mjs";import{S as bi}from"./ctx-db-search-state-DVCp4JQf.mjs";import{selectShapeMembers as Di,selectShapeRows as ki}from"./selectShapeMembers-BXhvEt4X.mjs";const lo=n=>{const r=atob(n),o=Uint8Array.from(r,d=>d.codePointAt(0)??0);return new TextDecoder().decode(o)},uo=()=>new $("BAD_REQUEST","invalid cursor"),Pt=16,Ut=8,z=1024,ht=(n,r)=>r.query(n),fo=(n,r)=>{if(n.length===0)return 0;let o=0;for(const[d,i]of r.entries()){const w=d===r.length-1;let _=0;for(const m of n)(w?m.startsWith(i):m===i)&&(_+=1);if(_===0)return 0;o+=_}return o},ho=(n,r)=>{if(!r)return{exact:!0,lower:n,upper:n};const o=[...n].at(-1)??"",d=(o.codePointAt(0)??0)+1;if(d>=55296&&d<=57343||d>1114111)return{exact:!0,lower:n,upper:n};const i=n.slice(0,n.length-o.length);return{exact:!1,lower:n,upper:i+String.fromCodePoint(d)}},wo=(n,r,o)=>{const d={eq:(i,w)=>{if(!n.definition.filterFields?.includes(i))throw new $("INTERNAL",`field "${i}" is not a filter field of search index "${n.indexName}" on table "${r}"`);if(n.filters.length>=Ut)throw new $("BAD_REQUEST",`search index "${n.indexName}" on table "${r}": at most ${String(Ut)} .eq() filters are supported per search query`);return n.filters.push({field:i,value:w}),d},search:(i,w)=>{const _=n;if(i!==_.definition.field)throw new $("INTERNAL",`search index "${_.indexName}" on table "${r}" indexes "${_.definition.field}", not "${i}"`);const m=ht(w,o).length;if(m>Pt)throw new $("BAD_REQUEST",`search index "${_.indexName}" on table "${r}": at most ${String(Pt)} search terms are supported (got ${String(m)})`);return _.field=i,_.query=w,_.hasQuery=!0,d}};return d},po=n=>{if(n.length>z)throw new $("BAD_REQUEST",`more than ${String(z)} documents match this search — narrow it with filters or read it a page at a time with .paginate()`)},go=n=>Math.min(n.offset+n.numItems+1,z),yo=n=>btoa(`search:${String(n)}`),$o=n=>{let r;try{r=lo(n)}catch{return}if(!r.startsWith("search:"))return;const o=Number(r.slice(7));return Number.isInteger(o)&&o>=0?o:void 0},Eo=n=>{if(typeof n.endCursor=="string")throw new $("BAD_REQUEST","bounded (endCursor) pagination is not supported on search queries — relevance order has no stable range boundary");if(!Number.isFinite(n.numItems))throw new $("BAD_REQUEST",`search pagination needs a finite numItems, got ${String(n.numItems)}`);const r=Math.max(0,Math.floor(n.numItems)),o=n.cursor?$o(n.cursor):0;if(o===void 0)throw uo();if(o+r>=z)throw new $("BAD_REQUEST",`search pagination reaches the ${String(z)}-document limit (offset ${String(o)} + ${String(r)} requested) — a page must end below the cap so the probe row that answers \`hasMore\` still fits: retry with numItems ${String(Math.max(1,z-o-1))} or fewer, or narrow the query or the filters instead`);return{numItems:r,offset:o}},mo=(n,r)=>{const o=r.offset+r.numItems,d=r.numItems>0&&n.length>o;return{continueCursor:d?yo(o):null,isDone:!d,page:n.slice(r.offset,o)}},So=n=>{if(n===void 0)return z+1;if(!Number.isFinite(n))return z;const r=Math.max(0,Math.floor(n));if(r>z)throw new $("BAD_REQUEST",`search returns at most ${String(z)} documents (asked for ${String(r)}) — narrow the query or paginate instead`);return r},_o=32,Ro=1024,sn=(n,r,o,d)=>{const i=`SELECT id, _creationTime, ${ve(oe)} FROM ${ve(n)}`,w=`ORDER BY ${o}${d===void 0?"":` LIMIT ${String(d)}`}`;return r===void 0?Ne(`${i} ${w}`):_e(`${i} WHERE `,r,` ${w}`)},wt={fieldRef:n=>Ne(He(n)),serialize:ae},cn=n=>{const r=n.map(o=>`${He(o.field)} ${o.direction==="desc"?"DESC":"ASC"}`);return n.some(o=>o.field==="_id"||o.field==="id")||r.push(`${He("id")} ${Nn(n)==="desc"?"DESC":"ASC"}`),r.join(", ")},To={"<":"lt","<=":"lte","=":"eq",">":"gt",">=":"gte"},an=n=>new Set(n.sqlConditions.filter(r=>r.comparator==="=").map(r=>r.field)),vo=n=>{const r=an(n);let o=0;for(;o<n.indexFields.length&&r.has(n.indexFields[o]??"");)o+=1;return n.indexFields.slice(o)},Ao=(n,r)=>{const o=n.order,d=vo(n),{shape:i}=r;return d.length>0?ct(d.map(w=>({[w]:o})),i,{pinned:an(n),uniqueBy:on(r.indexes,i)}):ct([{_creationTime:o}],i)},Io=(n,r,o,d)=>{const i=n.sqlConditions.map(w=>({[w.field]:{[To[w.comparator]??"eq"]:w.value}}));if(o&&i.push(rn(r,at(o))),d&&i.push(jn(r,at(d))),i.length!==0)return i.length===1?i[0]:{AND:i}},Co=n=>{if(n.want!==void 0)return n.selective?Math.max(n.want,_o):n.want},dt=(n,r,o,d,i,w,_)=>{const m=Ao(d,o),x=cn(m),g=[],{filters:b,want:v}=w;let R=w.cursor??void 0,M=Co(w);if(v===0)return{documents:g,orderKeys:m};for(;;){const q=te(Io(d,m,R,w.endCursor),wt,je),B=sn(r,i&&q?_e(q," AND ",i):i??q,x,M),F=Te(n,B.text,...B.params).toArray();let P={};_(F.length);for(const C of F)if(P=Se(C),b.every(ne=>ne(P))&&g.push(P)===v)return{documents:g,orderKeys:m};if(M===void 0||F.length<M)return{documents:g,orderKeys:m};R=Oe(P,m),M=Math.max(M,Math.min(M*2,Ro))}},xo=(n,r,o,d,i,w,_,m)=>{const x=Math.max(0,Math.floor(i.numItems));if(typeof i.endCursor=="string"){const{documents:q,orderKeys:B}=dt(n,r,o,d,w,{cursor:i.cursor,endCursor:i.endCursor,filters:_.all,selective:_.selective,want:void 0},m),F=q.length>=2?q[Math.floor(q.length/2)-1]:void 0;return{continueCursor:i.endCursor,isDone:!0,page:q,splitCursor:F?Oe(F,B):null}}const{documents:g,orderKeys:b}=dt(n,r,o,d,w,{cursor:i.cursor,filters:_.all,selective:_.selective,want:x+1},m),v=g.length>x,R=v?g.slice(0,x):g,M=R.at(-1);return{continueCursor:v&&M?Oe(M,b):null,isDone:!v,page:R}},Ke=n=>{const r=new Map;return o=>{const d=r.get(o);if(d!==void 0)return d;const i=n(ve(o));return r.set(o,i),i}},fe=ve(oe),bo=Ke(n=>`INSERT INTO ${n} (id, _creationTime, ${fe}) VALUES (?, ?, ?)`),Gt=Ke(n=>`UPDATE ${n} SET ${fe} = ? WHERE id = ? AND ${fe} = ?`),Mo=Ke(n=>`UPDATE ${n} SET _creationTime = ?, ${fe} = ? WHERE id = ? AND ${fe} = ?`),Do=Ke(n=>`DELETE FROM ${n} WHERE id = ? AND ${fe} = ?`),ko="SELECT changes() AS changed",Ht=new Map,Lo="",Fo=n=>{const r=JSON.stringify(n),o=Ht.get(r);if(o!==void 0)return o;const d=n.map(w=>c`SELECT ${c.raw(`'${w.replaceAll("'","''")}'`)} AS __t__, id, _creationTime, ${c.identifier(oe)} FROM ${c.identifier(w)} WHERE id = ${Lo}`),{sql:i}=tn("sqlite",c`${ft(d)} LIMIT 1`);return Ht.set(r,i),i},qo=(n,r)=>r.map(()=>n),Bo=/^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/iu,Wo=n=>{if(!Bo.test(n))throw new $("INTERNAL",`invalid clientId ${JSON.stringify(n)}: a client-supplied row id must be a UUID`)},Ot=50,dn=500,Ue=Math.floor(nn.boundParams/3),Ee=nn.boundParams,Po=128,le=(n,r,o)=>{const d=r??dn;if(n>d)throw new $("BATCH_LIMIT_EXCEEDED",`${o}: batch of ${String(n)} exceeds the limit of ${String(d)} (raise options.limit or chunk the call)`,{status:400})},Uo=n=>{const r={eq:(o,d)=>(n.sqlConditions.push({comparator:"=",field:o,value:d}),r),gt:(o,d)=>(n.sqlConditions.push({comparator:">",field:o,value:d}),r),gte:(o,d)=>(n.sqlConditions.push({comparator:">=",field:o,value:d}),r),lt:(o,d)=>(n.sqlConditions.push({comparator:"<",field:o,value:d}),r),lte:(o,d)=>(n.sqlConditions.push({comparator:"<=",field:o,value:d}),r)};return r},Go=n=>Math.max(n,z),ln=(n,r)=>{const o=n.filters.map(d=>c`${ce(d.field)} = ${ae(d.value)}`);return r&&o.push(r),o},Ho=(n,r,o,d,i)=>{const w=ht(o.query,ut(o.definition.language));if(w.length===0)return[];const _=mn(r,o.indexName),m=`${_}__vocab`,x=w.length-1,g=w.map((B,F)=>{const P=ho(B,F===x),C=P.exact?c`${c.identifier("term")} = ${P.lower}`:c`${c.identifier("term")} >= ${P.lower} AND ${c.identifier("term")} < ${P.upper}`;return c`SELECT ${c.identifier("doc")}, ${c.raw(String(F))} AS ${c.identifier("__term__")}, COUNT(*) AS ${c.identifier("__n__")} FROM ${c.identifier(m)} WHERE ${C} GROUP BY ${c.identifier("doc")}`}),b=w.map((B,F)=>c`SUM(CASE WHEN u.${c.identifier("__term__")} = ${c.raw(String(F))} THEN u.${c.identifier("__n__")} ELSE 0 END)`),v=c`SELECT f.${c.identifier(qe)} AS ${c.identifier(qe)}, ${c.join(b,c` + `)} AS ${c.identifier("__score__")} FROM (${ft(g)}) u JOIN ${c.identifier(_)} f ON f.rowid = u.${c.identifier("doc")} GROUP BY f.${c.identifier(qe)} HAVING ${c.join(b.map(B=>c`${B} > 0`),c` AND `)}`,R=ln(o,i);let M=c`SELECT m.id, m._creationTime, m.${c.identifier(oe)}, s.${c.identifier("__score__")} AS ${c.identifier("__score__")} FROM (${v}) s JOIN ${c.identifier(r)} m ON m.id = s.${c.identifier(qe)}`;R.length>0&&(M=c`${M} WHERE ${c.join(R,c` AND `)}`),M=c`${M} ORDER BY s.${c.identifier("__score__")} DESC, m._creationTime DESC, m.id ASC LIMIT ${c.raw(String(d))}`;const q=[];for(const B of j(n,M)){const F=en(B);if(F){const P=B.__score__;q.push({document:F,score:typeof P=="number"?P:Number(P??0)})}}return q},Oo=(n,r,o,d,i)=>{const w=ut(o.definition.language),_=ht(o.query,w);if(_.length===0)return[];const m=ln(o,i);let x=c`SELECT id, _creationTime, ${c.identifier(oe)} FROM ${c.identifier(r)}`;m.length>0&&(x=c`${x} WHERE ${c.join(m,c` AND `)}`),x=c`${x} ORDER BY _creationTime DESC, id ASC LIMIT ${c.raw(String(Go(d)))}`;const g=j(n,x).toArray(),b=[];for(const v of g){const R=en(v);if(!R)continue;const M=fo(Sn(R,o.definition),_);M>0&&b.push({creationTime:typeof R._creationTime=="number"?R._creationTime:0,doc:R,id:typeof R._id=="string"?R._id:"",score:M})}return b.sort((v,R)=>R.score-v.score||R.creationTime-v.creationTime||v.id.localeCompare(R.id)),b.slice(0,d).map(v=>({document:v.doc,score:v.score}))},it=(n,r,o,d)=>{if(!Number.isFinite(n.lat)||n.lat<-90||n.lat>90||!Number.isFinite(n.lng)||n.lng<-180||n.lng>180)throw new $("BAD_REQUEST",`geo index "${d}" on table "${o}": ${r} must have a finite lat in [-90, 90] and lng in [-180, 180]`)},No=(n,r)=>{const o=n,d={near:(i,w)=>{if(o.within)throw new $("INTERNAL",`geo index "${o.indexName}" on table "${r}": call .near() or .within(), not both`);if(it(i,".near() point",r,o.indexName),!Number.isFinite(w)||w<=0)throw new $("BAD_REQUEST",`geo index "${o.indexName}" on table "${r}": .near() radiusMeters must be a finite number > 0, got ${String(w)}`);return o.near={point:{lat:i.lat,lng:i.lng},radiusMeters:w},d},within:i=>{if(o.near)throw new $("INTERNAL",`geo index "${o.indexName}" on table "${r}": call .near() or .within(), not both`);if(it(i.sw,".within() sw corner",r,o.indexName),it(i.ne,".within() ne corner",r,o.indexName),i.sw.lat>i.ne.lat)throw new $("BAD_REQUEST",`geo index "${o.indexName}" on table "${r}": .within() corners are transposed (sw.lat > ne.lat)`);if(i.sw.lng>i.ne.lng)throw new $("BAD_REQUEST",`geo index "${o.indexName}" on table "${r}": .within() box crosses the antimeridian (sw.lng > ne.lng), which is not supported — split it into two boxes at ±180 and union the results`);return o.within={ne:{lat:i.ne.lat,lng:i.ne.lng},sw:{lat:i.sw.lat,lng:i.sw.lng}},d}};return d},jo=(n,r)=>{const o=n[r];if(o===null||typeof o!="object")return;const{lat:d,lng:i}=o;return typeof d=="number"&&typeof i=="number"?{lat:d,lng:i}:void 0},Ko=(n,r)=>{const o=jo(n,r.definition.field);if(!o)return;const d=typeof n._creationTime=="number"?n._creationTime:0;if(r.near){const i=Gn(r.near.point,o);return i<=r.near.radiusMeters?{creationTime:d,distance:i}:void 0}return Hn(o,r.within)?{creationTime:d,distance:0}:void 0},Qo=(n,r,o,d)=>{if(!o.near&&!o.within)throw new $("INTERNAL",`geo index "${o.indexName}" on table "${r}": call .near(point, radius) or .within(box)`);const i=o.near?Pn(o.near.point,o.near.radiusMeters):Un(o.within),w=Bn(r,o.indexName),_=i.map(v=>c`(g.${c.identifier("__geohash__")} >= ${v} AND g.${c.identifier("__geohash__")} < ${`${v}{`})`),m=[c`(${c.join(_,c` OR `)})`];d&&m.push(d);const x=c`SELECT m.id, m._creationTime, m.${c.identifier(oe)} FROM ${c.identifier(w)} g JOIN ${c.identifier(r)} m ON m.id = g.${c.identifier("__id__")} WHERE ${c.join(m,c` AND `)}`,g=j(n,x).toArray(),b=[];for(const v of g){const R=Se(v),M=R?Ko(R,o):void 0;R&&M&&b.push({creationTime:M.creationTime,distance:M.distance,doc:R})}return b.sort((v,R)=>v.distance-R.distance||R.creationTime-v.creationTime),b},un=(n,r,o,d)=>{const i=[];for(const w of n)if(r.every(_=>_(d(w)))&&(i.push(w),typeof o=="number"&&i.length>=o))break;return i},Vo=(n,r,o,d,i,w=()=>{})=>{const _=o.within!==void 0,m=Qo(n,r,o,i).map(x=>({distanceMeters:_?null:x.distance,document:x.doc}));return w(m.length),typeof d=="number"?m.slice(0,Math.max(0,Math.floor(d))):m},Nt=(n,r,o,d,i,w,_=()=>{})=>{const{geo:m}=o;if(!m)throw new $("INTERNAL","runGeoTerminalScored called without a staged geo query");const x=i.length>0,g=Vo(n,r,m,x?void 0:w,d,_);return x?un(g,i,w,b=>b.document):g},me={fieldRef:ce,serialize:ae},fn=(n,r)=>{const o=r===void 0?void 0:n.shape[r];return o!==void 0&&so(o)},jt=(n,r)=>r.some(o=>fn(n,o)),Kt=(n,r,o)=>{if(fn(n,r))throw new $("BAD_REQUEST",`${o}: "${r}" may hold an order-preserving key rather than a value SQL can reduce or group — declare an aggregateIndex covering this (by, field, op) so the maintained companion answers it instead (its running total is a REAL, so it stays exact only while the total is inside 2^53)`)},zo=n=>{let r=0;const o=[],d={fieldRef:i=>Ne(He(i)),relationExists:i=>{const{childWhere:w,negated:_,parentTable:m,relation:x}=i,g=`__rel_${String(r)}`,b=o.at(-1)??m;r+=1,n(x.table,O);const v=x.kind==="one"?x.field:x.references,R=x.kind==="one"?x.references:x.field,M=Ne(`${bt(g,R)} = ${bt(b,v)}`);o.push(g);const q=te(w,d,je);o.pop();const B=q===void 0?M:_e(M," AND ",q),F=_e("EXISTS (SELECT 1 FROM ",Ft(x.table)," AS ",Ft(g)," WHERE ",B,")");return _?_e("NOT ",F):F},serialize:ae};return d};class Jo extends ${constructor(r="unique() found more than one matching document"){super("NOT_UNIQUE",r,{name:"NotUniqueError"})}}const Yo=/\s/u,Xo=String.fromCodePoint(0),Qt=(n,r,o)=>{if(!n.tables[r])throw new $("INTERNAL",`unknown table: ${r}`);return typeof o!="string"||o.length===0||Yo.test(o)||o.includes(Xo)?null:o},hn=(n,r,o,d=()=>{},i=()=>{},w=()=>{},_)=>{const m=r.tables[o];if(!m)throw new $("INTERNAL",`unknown table: ${o}`);const x=ue(m.softDeleteMode,void 0),g=_??{indexFields:[],indexName:void 0,inMemoryFilters:[],order:"asc",sqlConditions:[],verifyFilters:[]},b=()=>{const y=N(x,g.pushedWhere);return y?te(y,me):void 0},v=()=>{const y=N(x,g.pushedWhere);return y?te(y,wt,je):void 0},R=()=>[...g.inMemoryFilters,...g.verifyFilters];let M=0;const q=y=>{const{search:A}=g;if(!A)throw new $("INTERNAL","runSearchFetch called without a staged search");Cn(n,o,m);const D=g.inMemoryFilters.length>0,L=So(D?void 0:y),X=qn(n);if(X&&!xn(n,o,A.definition))throw new $("SEARCH_INDEX_BUILDING",`search index "${A.indexName}" on table "${o}" is still backfilling and currently covers only part of the table — retry once it finishes, or run the backfillSearch admin operation to complete it now`);const he=b(),J=X?Ho(n,o,A,L,he):Oo(n,o,A,L,he);!D&&y===void 0&&po(J);const re=R();return M=J.length,re.length>0?un(J,re,y,Ae=>Ae.document):J},B=y=>q(y).map(A=>A.document),F=y=>{const A=Eo(y);return mo(B(go(A)),A)},P=()=>{if(g.search||g.geo||g.indexName===void 0){i(void 0);return}i(Xn(o,g.indexName,g.indexFields,g.sqlConditions,ae))},C=y=>{P();let A=0;const D=(()=>{if(g.search){const L=B(y);return A=M,L}return g.geo?Nt(n,o,g,b(),R(),y,L=>{A=L}).map(L=>L.document):dt(n,o,m,g,v(),{filters:R(),selective:g.inMemoryFilters.length>0,want:y===void 0?void 0:Math.max(0,Math.floor(y))},L=>{A+=L}).documents})();return w(Math.max(A,D.length)),D},ne=()=>{if(!g.search&&!g.geo)throw new $("INTERNAL",`ctx.db.query("${o}").collectWithScores() requires a staged .withSearchIndex(...) or .withGeoIndex(...)`);P();let y=0;const A=(()=>{if(g.search){const D=q(void 0);return y=M,D}return Nt(n,o,g,b(),R(),void 0,D=>{y=D})})();return w(Math.max(y,A.length)),A},Y={async*[Symbol.asyncIterator](){const y=hn(n,r,o,d,i,w,{...g,indexFields:[...g.indexFields],inMemoryFilters:[...g.inMemoryFilters],sqlConditions:[...g.sqlConditions],verifyFilters:[...g.verifyFilters]});if(g.search){yield*await y.collect();return}let A;for(;;){const D=await y.paginate({cursor:A??null,numItems:Po});if(yield*D.page,D.isDone||D.continueCursor===null)return;A=D.continueCursor}},async collect(){return C(void 0)},async collectWithScores(){return ne()},filter(y){const A=Zn(y);return A!==void 0&&eo(A,m.shape)?(g.pushedWhere=N(g.pushedWhere,A),g.verifyFilters.push(y)):g.inMemoryFilters.push(y),Y},async first(){return C(1)[0]??null},order(y){return g.order=y==="desc"?"desc":"asc",Y},async paginate(y){let A=0;if(P(),g.search){const L=F(y);return w(L.page.length),L}if(g.geo)throw new $("INTERNAL","pagination is not supported on geo queries; use .take(n) or .collect()");const D=xo(n,o,m,g,y,v(),{all:R(),selective:g.inMemoryFilters.length>0},L=>{A+=L});return w(Math.max(A,D.page.length)),D},async take(y){return C(y)},async unique(){const y=C(2);if(y.length>1)throw new Jo(`unique() on table "${o}" matched ${String(y.length)} documents; expected at most one`);return y[0]??null},withGeoIndex(y,A){const D=(m.geoIndexes??[]).find(X=>X.name===y);if(!D)throw new $("INTERNAL",`unknown geo index "${y}" on table "${o}"`);d(o,y,"geo");const L={definition:D,indexName:y};if(g.geo=L,A(No(L,o)),!L.near&&!L.within)throw new $("INTERNAL",`geo index "${y}" on table "${o}" requires a .near(point, radius) or .within(box) call`);return Y},withIndex(y,A){const D=m.indexes.find(L=>L.name===y);if(!D)throw new $("INTERNAL",`unknown index "${y}" on table "${o}"`);return d(o,y,"index"),g.indexName=y,g.indexFields=D.fields,A&&A(Uo(g)),Y},withSearchIndex(y,A){const D=(m.searchIndexes??[]).find(X=>X.name===y);if(!D)throw new $("INTERNAL",`unknown search index "${y}" on table "${o}"`);d(o,y,"search");const L={definition:D,field:D.field,filters:[],hasQuery:!1,indexName:y,query:""};if(g.search=L,A(wo(L,o,ut(D.language))),!L.hasQuery)throw new $("INTERNAL",`search index "${y}" on table "${o}" requires a .search(field, query) call`);return Y}};return Y},Vt=(n,r,o)=>{const d={...r};for(const[i,w]of Zt(n)){if(w.serverDefault){d[i]=w.serverDefault({auth:o});continue}d[i]===void 0&&(w.defaultFn?d[i]=w.defaultFn():"defaultValue"in w&&(d[i]=w.defaultValue))}return d},zt=(n,r,o,d)=>{const i=o;for(const[w,_]of Zt(n)){if(_.serverDefault){w in r&&(i[w]=_.serverDefault({auth:d}));continue}_.onUpdateFn&&!(w in r)&&(i[w]=_.onUpdateFn())}},Jt=(n,r)=>{for(const o of Object.keys(r))if(r[o]===void 0)throw new $("INTERNAL",`Cannot ${n} field '${o}' to undefined — use null to clear a nullable field, or omit the key to leave it unchanged.`)},Yt=["_commitSeq","_creationTime","_id"],st=n=>Yt.some(r=>r in n)?Object.fromEntries(Object.entries(n).filter(([r])=>!Yt.includes(r))):n,Zo=/unique constraint failed/i,er=n=>n instanceof Error&&Zo.test(n.message),tr=/string or blob too big/iu,nr=(n,r)=>{if(!(!(n instanceof Error)||!tr.test(n.message)))throw new $("PAYLOAD_TOO_LARGE",`document is too large to store in "${r}": a single row cannot exceed the storage engine's per-row ceiling (2 MB on a Durable Object's SQLite). The limit is on the STORED bytes, which are UTF-8, and v.bytes()/v.bigint() columns are stored twice on a shard-local table. Keep the payload in R2 (ctx.storage) and store a reference on the row.`)},lt=(n,r,o,d)=>{try{Te(n,o,...d)}catch(i){throw er(i)?new Re(`unique constraint violation on "${r}"`,"unique"):(nr(i,r),i)}},Ge=(n,r,o,d)=>{if(lt(n,r,o,d),Te(n,ko).one().changed===0)throw new Re(`optimistic concurrency conflict on "${r}" — the row changed during this mutation; refetch and retry`,"occ")},Xt=(n,r,o,d,i,w,_)=>{const m=[];for(let v=0;v<o.length+1;v+=1){const R=o[v],M=d[v],q=M?.direction==="desc"?"desc":"asc",B=R===void 0||M===void 0?c`${c.identifier(zn)} < ${_}`:Jn(R,w[v],q,!1);if(B===void 0)continue;const F=[];for(let C=0;C<v;C+=1)F.push(c`${c.identifier(o[C])} IS ${w[C]}`);F.push(B);const[P]=F;m.push(F.length===1&&P!==void 0?P:c`(${c.join(F,c` AND `)})`)}const x=m.length>0?c.join(m,c` OR `):c`1 = 0`,g=j(n,c`SELECT COUNT(*) AS c FROM ${c.identifier(r)} WHERE ${c.identifier("__partition__")} = ${i} AND (${x})`).one(),b=j(n,c`SELECT COUNT(*) AS c FROM ${c.identifier(r)} WHERE ${c.identifier("__partition__")} = ${i}`).one();return{before:g.c,total:b.c}},Ur=n=>{const{baselineSeq:r,onStalePatchDropped:o}=n,{sql:d}=n,{schema:i}=n,w=n.broadcast??(()=>{}),_=to(i);let m;const x=()=>n.inTransaction?.()===!0,g=e=>i.tables[e]?.commitOrderedMode!==!0?{}:((m===void 0||!x())&&(m=Dn(d)),{[kn]:m}),b=(e,...t)=>{const s=i.tables[e]?.indexes;if(!s||s.length===0)return;const f=[];for(const h of t)h&&f.push(...Yn(s,h,ae));return f.length>0?f:void 0},{headroom:v}=n;let R=!1;const M=async e=>{const t=R;R=!0;try{return await e()}finally{R=t}},q=n.onRead??(()=>{}),B=e=>{Ct(i.tables[e])&&q(Lt,Lt)},F=n.onReadRange??(e=>{q(e.table,O)}),P=e=>{B(e.table),F(e)},C=(e,t)=>{t!==void 0&&t!==O&&!R&&v?.recordRead(1),B(e),q(e,t)},ne=n.onIndexUse??(()=>{}),Y=n.onWrite??(()=>{}),y=e=>{R||v?.recordWrite(e)},A=async e=>{y(e.doc),await Y(e)},{cache:D}=n,L=n.clock??(()=>Date.now()),X=n.idGenerator??(()=>crypto.randomUUID()),he=n.scheduler??Rn,{globalDb:J}=n,re=n.auth??{identity:null,userId:null},Ae=n.cdc??!1,Qe=he,wn=co({scheduler:typeof Qe.list=="function"&&typeof Qe.get=="function"?Qe:void 0,storage:n.storage}),we=(e,t,s,f)=>{Ae&&!Ct(i.tables[e])&&bn(d,L(),e,t,s,f)},pn=(e,t,s,f)=>{if(i.tables[e]?.dropStalePatchesMode!==!0||!Ae)return!1;const h=r?.();if(h===void 0)return!1;const l=Mn(d,e,t,h);return l===void 0?!1:Object.keys(st(s)).some(a=>It(l[a])!==It(f[a]))},ie=e=>i.tables[e]?.shardMode?.kind==="global",pt=(e,t)=>{if(ie(e)){if(!J)throw new $("INTERNAL",`cross-backend ${t} for global table '${e}' requires a globalDb writer — pass one to createShardCtxDb({ globalDb })`);return J}return G},Ve=e=>pt(e,"cascade"),Q=(e,t)=>{if(ie(e)){if(!J)throw new $("INTERNAL",`${t} on global table '${e}' requires a globalDb writer — pass one to createShardCtxDb({ globalDb })`);return J}},gt=async(e,t,s,f,h)=>{h&&y(s);const l=await e.insert(t,s,f);return w({key:l,op:"insert",row:{...s,_id:l},table:t}),l},ze=(e,t)=>pt(e,"relation load").findMany(e,t),yt=(e,t)=>(ie(e)&&C(e,O),ze(e,t)),gn=e=>!ie(e.table),$t=n.relationExistsPushDown??"auto",Et=$t!=="never",{maxRelationKeys:mt}=n,Ie=(e,t,s)=>qt(e,{fetcher:yt,maxRelationKeys:mt,relationBaseWhere:s,schema:i,tableName:t}),St=async(e,t,s,f)=>{const h=Q(e,"relation grouped count");if(h)return C(e,O),ro((U,I)=>h.count(U,I),e,t,s,f);const l=i.tables[e];if(!l)throw new $("INTERNAL",`unknown table: ${e}`);C(e,O);const a=ue(l.softDeleteMode,void 0),u={[t]:{in:s}},p=N(N(u,f),a),T=await Ie(p,e,void 0),E=te(T,me),k=ce(t);let S=c`SELECT ${k} AS __fk__, COUNT(*) AS count FROM ${c.identifier(e)}`;E&&(S=c`${S} WHERE ${E}`),S=c`${S} GROUP BY ${k}`;const W=j(d,S).toArray();return new Map(W.map(U=>[U.__fk__,U.count]))};let Ce=0;const _t=new Set;for(const[e,t]of Object.entries(i.tables))for(const s of Object.values(t.triggerMap??{}))_t.add(`${e} ${s.timing} ${s.op}`);const Z=(e,t,s)=>_t.has(`${e} ${t} ${s}`),ee=async(e,t,s)=>{if(Ce+=1,Ce>Ot)throw Ce-=1,new Re(`trigger recursion exceeded ${String(Ot)} levels on "${s.table}" — check for a self-triggering write`,"trigger");try{await ao({ctx:$n,event:s,op:t,schema:i,tableName:s.table,timing:e})}finally{Ce-=1}},{ensureBackfilledForTable:pe,ensureBackfilledIndex:Je,ensureRankBackfilled:Ye,ensureRankBackfilledForTable:ge,syncAggregates:xe,syncCompanionsForInsert:Rt,syncGeo:be,syncRanks:ye,syncSearch:Me}=Ln({broadcast:w,indexKeysFor:(e,t)=>b(e,t),invalidateCache:(e,t,s)=>D?.invalidate(e,t,b(e,s)),recordCdc:we,schema:i,sql:d}),Tt=(e,t,s)=>{const{shardMode:f}=t;if(f?.kind==="shardBy"&&!(f.field!==void 0&&(s.partitionBy??[]).includes(f.field)))throw Object.assign(new Error(`rank index "${s.name}" on "${e}" partitions across shards (shard key "${f.field??"?"}" is not in partitionBy) — a shard-local rank()/rankPage() would be wrong; roll it up through the Query Coordinator instead`),{code:"CROSS_SHARD_RANK_UNSUPPORTED",name:"LunoraError",status:400})},vt=e=>Object.entries(i.tables).filter(([,t])=>t.shardMode?.kind!=="global").map(([t])=>t).filter(t=>e===void 0||t===e),$e=e=>e===void 0||ie(e)?J:void 0,se=(e,t)=>{const s=vt(t);for(let f=0;f<s.length;f+=Ee){const h=s.slice(f,f+Ee),[l]=Te(d,Fo(h),...qo(e,h)).toArray();if(!l)continue;const a=l.__t__,u=Se(l);if(typeof a!="string"||!u)return;const p=l[oe];return{docJson:typeof p=="string"?p:de(p??{}),row:u,tableName:a}}},yn=(e,t)=>{const s=[...new Set(e)],f=new Map;if(s.length===0)return f;const h=vt(t);for(let l=0;l<h.length;l+=Ee){const a=h.slice(l,l+Ee),u=Math.floor(Ee/a.length),p=Wn(c`${c.identifier("id")}`,s,!1,u),T=a.map(E=>c`SELECT ${c.raw(`'${E.replaceAll("'","''")}'`)} AS __t__, id FROM ${c.identifier(E)} WHERE ${p}`);for(const E of j(d,ft(T))){const{id:k,__t__:S}=E;typeof S=="string"&&typeof k=="string"&&f.set(k,S)}}return f},At={assertRankPartitionLocal:Tt,ensureRankBackfilled:Ye,onRead:C,rowToDocument:Se,schema:i,sql:d},G={system:wn,async aggregate(e,t){const s=Q(e,"aggregate");if(s)return C(e,O),s.aggregate(e,t);const f=i.tables[e];if(!f)throw new $("INTERNAL",`unknown table: ${e}`);if(Be(t.op),t.op==="count")return G.count(e,{baseWhere:t.baseWhere,relationBaseWhere:t.relationBaseWhere,restrictsCounts:t.restrictsCounts,where:t.where});if(!t.field)throw new $("INTERNAL",`aggregate(${e}, { op: "${t.op}" }): "field" is required for non-count reducers`);C(e,O);const h=ue(f.softDeleteMode,void 0),l=N(N(t.baseWhere,t.where),h),a=await Ie(l,e,t.relationBaseWhere),u=a!==l;if(f.aggregateIndexes&&!t.baseWhere&&!u&&(!h||jt(f,[t.field]))){const U=In(f.aggregateIndexes,t.op,t.field,t.where);if(U){Je(e,U.index);const I=Ze(U.index.by??[],U.key),K=Xe(e,U.index.name),V=j(d,c`SELECT ${We} AS value, ${nt} AS count FROM ${c.identifier(K)} WHERE ${Pe} = ${I}`).toArray()[0];return et(t.op,V)}}Kt(f,t.field,`aggregate(${e}, { op: "${t.op}", field: "${t.field}" })`);const p=te(a,me),T=Be(t.op),E=ce(t.field);let k=c`SELECT ${c.raw(T)}(${E}) AS value FROM ${c.identifier(e)}`;p&&(k=c`${k} WHERE ${p}`);const W=j(d,k).toArray()[0]?.value;return W??null},asId(e,t){const s=Qt(i,e,t);if(s===null)throw new $("BAD_REQUEST",`asId("${e}", …): "${t}" is not a valid id for table "${e}"`,{status:400});return s},async count(e,t){const s=Q(e,"count");if(s)return C(e,O),s.count(e,t);const f=i.tables[e];if(!f)throw new $("INTERNAL",`unknown table: ${e}`);const h=Tn(t);if(h.restrictsCounts)throw new tt(e);C(e,O);const l=ue(f.softDeleteMode,void 0),a=N(N(h.baseWhere,h.where),l),u=await Ie(a,e,h.relationBaseWhere),p=u!==a;if(f.aggregateIndexes&&!h.baseWhere&&!p&&!l){const S=An(f.aggregateIndexes,h.where);if(S){Je(e,S.index);const W=Ze(S.index.by??[],S.key),U=Xe(e,S.index.name),I=j(d,c`SELECT ${We} AS value FROM ${c.identifier(U)} WHERE ${Pe} = ${W}`).toArray();return I[0]===void 0?0:I[0].value??0}}const T=te(u,me);let E=c`SELECT COUNT(*) AS count FROM ${c.identifier(e)}`;return T&&(E=c`${E} WHERE ${T}`),j(d,E).one().count},async delete(e,t,s){const f=se(e,t);if(!f){const E=$e(t);E&&(y(void 0),await E.delete(e,t,s));return}const{docJson:h,row:l,tableName:a}=f,u=i.tables[a],p=s?.hard===!0,T=!p&&u?.softDeleteMode?u.softDeleteMode.field:void 0;if(!(T&&l[T]!==null&&l[T]!==void 0)){if(Z(a,"before","delete")&&await ee("before","delete",{id:e,op:"delete",previous:l,table:a}),await oo({deletedId:e,deletedReference:E=>l[E],findHolders:async(E,k,S)=>(await Ve(E).findMany(E,{includeDeleted:p,where:{[k]:S}})).page,onCascade:(E,k)=>Ve(E).delete(k,void 0,s),onRestrict:E=>{throw new Re(E,"restrict")},onSetNull:(E,k,S)=>Ve(E).patch(k,{[S]:null}),schema:i,tableName:a}),pe(a),ge(a),T){const E={...l,...g(a),[T]:L(),_id:e};Ge(d,a,Gt(a),[de(E),e,h]),Me(a,e,E,l),be(a,e,void 0),xe(a,l,E),ye(a,e,l,void 0),D?.invalidate(a,e,b(a,l,E)),we(a,e,"update",E),w({indexKeys:b(a,l,E),key:e,op:"update",row:E,table:a}),Z(a,"after","delete")&&await ee("after","delete",{id:e,op:"delete",previous:l,table:a}),await A({id:e,op:"delete",table:a});return}Ge(d,a,Do(a),[e,h]),Me(a,e,void 0),be(a,e,void 0),xe(a,l,void 0),ye(a,e,l,void 0),D?.invalidate(a,e,b(a,l)),we(a,e,"delete"),w({indexKeys:b(a,l),key:e,op:"delete",table:a}),Z(a,"after","delete")&&await ee("after","delete",{id:e,op:"delete",previous:l,table:a}),await A({id:e,op:"delete",table:a})}},async deleteAll(e,t){if(!i.tables[e])throw new $("INTERNAL",`unknown table: ${e}`);const s=Math.max(1,t?.chunkSize??dn),f=t?.hard===void 0?void 0:{hard:t.hard},h=ie(e)?void 0:e;let l=0;return await M(async()=>{for(;;){const u=(await G.findMany(e,{limit:s})).page.map(p=>String(p._id));if(u.length===0)break;for(const p of u)await G.delete(p,h,f),l+=1;if(u.length<s)break}}),{deleted:l}},async deleteMany(e,t,s){le(e.length,t?.limit,"deleteMany");for(const f of e)await G.delete(f,s);return{deleted:e.length}},async deleteWhere(e,t,s){const l=(await(Q(e,"deleteWhere")??G).findMany(e,{where:t})).page.map(a=>String(a._id));if(le(l.length,s?.limit,"deleteWhere"),G.deleteMany===void 0)throw new $("INTERNAL",`ctx.db.${e}.deleteMany is unavailable: this writer has no batch delete`);return G.deleteMany(l,s)},async findFirst(e,t={}){return(await G.findMany(e,{...t,limit:1,omitContinueCursor:!0})).page[0]??null},async findFirstOrThrow(e,t={}){const s=await G.findFirst(e,t);if(s===null)throw new On(`findFirstOrThrow: no "${e}" document matched`);return s},async findMany(e,t={}){const s=Q(e,"findMany");if(s)return C(e,O),s.findMany(e,t);const f=i.tables[e];if(!f)throw new $("INTERNAL",`unknown table: ${e}`);const h=!t.where&&!t.baseWhere;h?C(e,O):C(e);const l=ct(t.orderBy,f.shape,{pinned:Kn(t.where),uniqueBy:on(f.indexes,f.shape)}),a=t.cursor?rn(l,at(t.cursor)):void 0;let u=N(t.baseWhere,t.where);u=N(u,ue(f.softDeleteMode,t.includeDeleted)),u=await qt(u,{canPushExists:Et?gn:void 0,existsPushMode:$t==="always"?"always":"auto",fetcher:yt,maxRelationKeys:mt,relationBaseWhere:t.relationBaseWhere,schema:i,tableName:e}),a&&(u=u?{AND:[u,a]}:a);const p=Et?zo(C):wt,T=te(u,p,je),E=typeof t.limit=="number"?Math.max(0,Math.floor(t.limit)):void 0,k=sn(e,T,cn(l),E===void 0?void 0:E+1),S=Te(d,k.text,...k.params).toArray();h&&!R&&v?.recordRead(S.length);const W=[];for(const V of S){const H=Se(V);H&&(W.push(H),!h&&typeof H._id=="string"&&C(e,H._id))}if(E===void 0)return t.with&&await Bt({groupedCounter:St,fetcher:ze,parents:W,...Wt(t),schema:i,tableName:e,with:t.with}),{continueCursor:null,isDone:!0,page:Mt(W,t.select,t.with)};const U=W.length>E,I=U?W.slice(0,E):W,K=I.at(-1);return t.with&&await Bt({fetcher:ze,groupedCounter:St,parents:I,...Wt(t),schema:i,tableName:e,with:t.with}),{continueCursor:U&&K&&t.omitContinueCursor!==!0?Oe(K,l):null,isDone:!U,page:Mt(I,t.select,t.with)}},async get(e,t){const s=se(e,t);if(!s){const f=$e(t);return f?f.get(e,t):null}return C(s.tableName,e),s.row},async lookupById(e,t){const s=se(e,t);return s?(C(s.tableName,e),{row:s.row,tableName:s.tableName}):null},async groupBy(e,t){const s=Q(e,"groupBy");if(s)return C(e,O),s.groupBy(e,t);const f=i.tables[e];if(!f)throw new $("INTERNAL",`unknown table: ${e}`);C(e,O);const h=t.agg??{op:"count"};if(Be(h.op),h.op!=="count"&&!h.field)throw new $("INTERNAL",`groupBy(${e}, { agg: { op: "${h.op}" } }): "field" is required for non-count reducers`);const l=ue(f.softDeleteMode,void 0),a=N(N(t.baseWhere,t.where),l),u=await Ie(a,e,t.relationBaseWhere),p=u!==a,T=[...t.by,h.field];if(f.aggregateIndexes&&!t.baseWhere&&!p&&(!l||jt(f,T))){const I=vn(f.aggregateIndexes,h.op,h.field,t.by,t.where),K=I===void 0?0:Object.keys(I.partial).length,V=I?.index.by?.length??0;if(I&&(K===0||K===V)){Je(e,I.index);const H=Xe(e,I.index.name),De=Object.keys(I.partial),ke=[];if(De.length===(I.index.by??[]).length&&De.length>0){const Le=Ze(I.index.by??[],I.partial),Fe=j(d,c`SELECT ${We} AS value, ${nt} AS count FROM ${c.identifier(H)} WHERE ${Pe} = ${Le}`).toArray();return Fe.length>0&&ke.push({key:{...I.partial},value:et(h.op,Fe[0])}),ke}const En=j(d,c`SELECT ${Pe} AS key, ${We} AS value, ${nt} AS count FROM ${c.identifier(H)}`).toArray();for(const Le of En){const Fe=_n(JSON.parse(Le.key));ke.push({key:Fe,value:et(h.op,Le)})}return ke}}for(const I of T){if(I===void 0)continue;const K=I===h.field?`groupBy(${e}, { agg: { op: "${h.op}", field: "${I}" } })`:`groupBy(${e}, { by: [..."${I}"] })`;Kt(f,I,K)}const E=te(u,me),k=t.by.map(I=>c`${ce(I)} AS ${c.identifier(I)}`);if(h.op==="count")k.push(c`COUNT(*) AS value`);else{const{field:I}=h;if(I===void 0)throw new $("INTERNAL",`groupBy(${e}, { agg: { op: "${h.op}" } }): "field" is required for non-count reducers`);k.push(c`${c.raw(Be(h.op))}(${ce(I)}) AS value`)}let S=c`SELECT ${c.join(k,c`, `)} FROM ${c.identifier(e)}`;E&&(S=c`${S} WHERE ${E}`),S=c`${S} GROUP BY ${c.join(t.by.map(I=>ce(I)),c`, `)}`;const W=j(d,S).toArray(),U=[];for(const I of W){const K={};for(const H of t.by)K[H]=Fn(f.shape[H],I[H]??null);const{value:V}=I;U.push({key:K,value:V==null?null:Number(V)})}return U},async insert(e,t,s){const f=Q(e,"insert");if(f)return gt(f,e,t,s,!0);const h=i.tables[e];if(!h)throw new $("INTERNAL",`unknown table: ${e}`);const l=Vt(h,t,re);rt(h,l);let a;s?.clientId!==void 0?(Wo(s.clientId),a=s.clientId):s?.allowExplicitId&&typeof l._id=="string"?a=l._id:a=X();const u=s?.allowExplicitId&&typeof l._creationTime=="number"?l._creationTime:L(),p={...l,...g(e),_creationTime:u,_id:a};return Z(e,"before","insert")&&await ee("before","insert",{doc:{...p},id:a,op:"insert",table:e}),pe(e),ge(e),lt(d,e,bo(e),[a,u,de(p)]),Rt(e,a,p),Z(e,"after","insert")&&await ee("after","insert",{doc:p,id:a,op:"insert",table:e}),await A({doc:p,id:a,op:"insert",table:e}),a},async insertManyUnsafe(e,t,s){if(le(t.length,s?.limit,"insertManyUnsafe"),t.length===0)return[];const f=Q(e,"insert");if(f){const u=[];for(const p of t)y(p);for(const p of t){const T=await f.insert(e,p,{allowExplicitId:s?.allowExplicitId});w({key:T,op:"insert",row:{...p,_id:T},table:e}),u.push(T)}return u}const h=i.tables[e];if(!h)throw new $("INTERNAL",`unknown table: ${e}`);pe(e),ge(e);const l=[];for(let u=0;u<t.length;u+=Ue)l.push(g(e));const a=t.map((u,p)=>{const T=Vt(h,u,re),E=s?.allowExplicitId===!0&&typeof T._id=="string"?T._id:X(),k=s?.allowExplicitId===!0&&typeof T._creationTime=="number"?T._creationTime:L(),S={...T,...l[Math.floor(p/Ue)],_creationTime:k,_id:E};return{creationTime:k,document:S,id:E}});for(const u of a)y(u.document);for(let u=0;u<a.length;u+=Ue){const p=c.join(a.slice(u,u+Ue).map(E=>c`(${E.id}, ${E.creationTime}, ${de(E.document)})`),c`, `),T=tn("sqlite",c`INSERT INTO ${c.identifier(e)} (id, _creationTime, ${c.identifier(oe)}) VALUES ${p}`);lt(d,e,T.sql,T.params)}for(const{document:u,id:p}of a)Rt(e,p,u),await Y({doc:u,id:p,op:"insert",table:e});return a.map(u=>u.id)},async insertMany(e,t,s){le(t.length,s?.limit,"insertMany");const f=s?.skipDuplicates===!0,h=[],l=Q(e,"insert");if(l)for(const u of t)y(u);const a=async u=>l?gt(l,e,u,void 0,!1):G.insert(e,u);for(const u of t)try{h.push(await a(u))}catch(p){if(f&&p instanceof Re&&p.kind==="unique")h.push(null);else throw p}return h},normalizeId(e,t){return Qt(i,e,t)},async patch(e,t,s){const f=se(e,s);if(!f){const T=$e(s);if(T){y(t),await T.patch(e,t,s);return}throw new $("NOT_FOUND",`document not found: ${e}`)}const{docJson:h,row:l,tableName:a}=f,u=i.tables[a];if(!u)throw new $("INTERNAL",`unknown table: ${a}`);if(C(a,e),Jt("patch",t),pn(a,e,t,l)){o?.({fields:Object.keys(st(t)),id:e,table:a});return}const p={...l,...st(t),...g(a),_id:e};zt(u,t,p,re),rt(u,p,!0),Z(a,"before","update")&&await ee("before","update",{doc:{...p},id:e,op:"update",previous:l,table:a}),pe(a),ge(a),Ge(d,a,Gt(a),[de(p),e,h]),Me(a,e,p,l),be(a,e,p),xe(a,l,p),ye(a,e,l,p),D?.invalidate(a,e,b(a,l,p)),we(a,e,"update",p),w({indexKeys:b(a,l,p),key:e,op:"update",row:p,table:a}),Z(a,"after","update")&&await ee("after","update",{doc:p,id:e,op:"update",previous:l,table:a}),await A({doc:p,id:e,op:"update",table:a})},async patchMany(e,t,s){le(e.length,t?.limit,"patchMany");for(const f of e)await G.patch(f.id,f.patch,s);return{patched:e.length}},async patchWhere(e,t,s){const l=(await(Q(e,"patchWhere")??G).findMany(e,{where:t.where})).page.map(a=>({id:String(a._id),patch:t.patch}));if(le(l.length,s?.limit,"patchWhere"),G.patchMany===void 0)throw new $("INTERNAL",`ctx.db.${e}.patchMany is unavailable: this writer has no batch patch`);return await G.patchMany(l,s),{patched:l.length}},async related(e,t){return no(G,_,e,t)},relationEdges:_,query(e){const t=Q(e,"query");return t?(C(e,O),t.query(e)):hn(d,i,e,ne,s=>{s?P(s):C(e,O)},s=>{R||v?.recordRead(s)})},async rank(e,t,s){const f=Q(e,"rank");if(f)return C(e,O),f.rank(e,t,s);ne(e,t,"rank");const h=i.tables[e];if(!h)throw new $("INTERNAL",`unknown table: ${e}`);const l=h.rankIndexes?.find(H=>H.name===t);if(!l)throw new $("INTERNAL",`unknown rankIndex "${t}" on table "${e}"`);if(Tt(e,h,l),s.restrictsCounts)throw new tt(e);C(e,O),Ye(e,l);const a=typeof s.row=="string"?s.row:s.row._id;if(!a)return null;const u=Dt(e,l.name),p=l.sortBy.map((H,De)=>kt(De)),T=p.map(H=>ve(H)).join(", "),E=j(d,c`SELECT ${c.identifier("__partition__")}, ${c.raw(T)} FROM ${c.identifier(u)} WHERE ${c.identifier("__id__")} = ${a}`).toArray(),[k]=E;if(k===void 0)return null;let S=k.__partition__;const W=N(s.baseWhere,s.where);ot(W,i,e,"rank");const U=Qn(l,W);if(U){const H=Vn(l.partitionBy??[],U);if(H!==S)return null;S=H}const I=p.map(H=>k[H]),{before:K,total:V}=Xt(d,u,p,l.sortBy,S,I,a);return{position:K+1,total:V}},async rankBefore(e,t,s){if(ie(e))throw new $("INTERNAL",`rankBefore is not supported on the global (.global()) table '${e}' — cross-shard rank cursors apply only to sharded tables`);const f=i.tables[e];if(!f)throw new $("INTERNAL",`unknown table: ${e}`);const h=f.rankIndexes?.find(p=>p.name===t);if(!h)throw new $("INTERNAL",`unknown rankIndex "${t}" on table "${e}"`);if(s.restrictsCounts)throw new tt(e);C(e,O),Ye(e,h);const l=Dt(e,h.name),a=h.sortBy.map((p,T)=>kt(T)),u=h.sortBy.map((p,T)=>ae(s.sortValues[T]??null));return Xt(d,l,a,h.sortBy,s.partitionKey,u,s.rowId)},async rankPage(e,t,s={}){ot(N(s.baseWhere,s.where),i,e,"rankPage");const f=Q(e,"rankPage");if(f)return C(e,O),f.rankPage(e,t,s);ne(e,t,"rank");const{continueCursor:h,hasMore:l,rows:a}=xt(At,e,t,s);return{continueCursor:h,isDone:!l,page:a.map(u=>u.doc)}},async rankPageRows(e,t,s={}){ot(N(s.baseWhere,s.where),i,e,"rankPage"),ne(e,t,"rank");const{directions:f,hasMore:h,rows:l}=xt(At,e,t,s);return{directions:f,hasMore:h,rows:l}},async restore(e,t){const s=se(e,t);if(!s){const l=$e(t);if(l?.restore){await l.restore(e,t);return}throw new $("NOT_FOUND",`document not found: ${e}`)}const f=i.tables[s.tableName]?.softDeleteMode?.field;if(!f)throw new $("INTERNAL",`ctx.db.restore: table "${s.tableName}" is not a .softDelete() table`);const h=s.row[f]!==null&&s.row[f]!==void 0;await G.patch(e,{[f]:null},t),h&&ye(s.tableName,e,void 0,s.row)},async replace(e,t,s,f){const h=se(e,s);if(!h){const W=$e(s);if(W){y(t),await W.replace(e,t,s,f);return}throw new $("NOT_FOUND",`document not found: ${e}`)}const{docJson:l,row:a,tableName:u}=h,p=i.tables[u];if(!p)throw new $("INTERNAL",`unknown table: ${u}`);Jt("replace",t);const T=f?.allowExplicitId&&typeof t._creationTime=="number"?t._creationTime:void 0,E=typeof a._creationTime=="number"?a._creationTime:void 0,k=T??E??L(),S={...t,...g(u),_creationTime:k,_id:e};zt(p,t,S,re),rt(p,S),Z(u,"before","update")&&await ee("before","update",{doc:{...S},id:e,op:"update",previous:a,table:u}),pe(u),ge(u),Ge(d,u,Mo(u),[k,de(S),e,l]),Me(u,e,S,a),be(u,e,S),xe(u,a,S),ye(u,e,a,S),D?.invalidate(u,e,b(u,a,S)),we(u,e,"update",S),w({indexKeys:b(u,a,S),key:e,op:"update",row:S,table:u}),Z(u,"after","update")&&await ee("after","update",{doc:S,id:e,op:"update",previous:a,table:u}),await A({doc:S,id:e,op:"update",table:u})},async wipeShard(e){const t=new Set(e?.exclude),s=e?.tables,f=Object.entries(i.tables).filter(([u,p])=>t.has(u)||s!==void 0&&!s.includes(u)?!1:p.shardMode?.kind!=="global").map(([u])=>u);if(s!==void 0){for(const u of s)if(!i.tables[u])throw new $("INTERNAL",`wipeShard: unknown table: ${u}`)}const h={};let l=0;const{deleteAll:a}=G;if(a===void 0)throw new $("INTERNAL","wipeShard: this writer has no deleteAll");for(const u of f){const p=await a(u,{...e?.chunkSize===void 0?{}:{chunkSize:e.chunkSize},hard:!0});h[u]=p.deleted,l+=p.deleted}return{deleted:l,tables:h}}},$n={db:G,scheduler:he};return n.enforceRls===!0?io(G,i,(e,t)=>se(e,t)?.tableName,(e,t)=>yn(e,t),_):G};export{Qr as CDC_LOG_TABLE,ui as CLIENT_WATERMARK_TABLE,gi as GLOBAL_SHAPE_SNAPSHOT_TABLE,Ri as IDEMPOTENCY_TABLE,Jo as NotUniqueError,bi as SEARCH_STATE_TABLE,fi as advanceClientWatermark,Vr as applyCdcChanges,Jt as assertNoExplicitUndefined,Wo as assertValidClientId,Or as backfillAggregateIndexes,Nr as backfillRankIndexes,jr as backfillSearchIndexes,zr as bumpCdcEpoch,Jr as cdcCanVouchFor,Yr as cdcForkedError,Xr as cdcSeqLeavingRows,Zr as cdcTouchesTables,ei as cdcTrimmedError,ti as compactCdcDocs,Ur as createShardCtxDb,ni as cursorBelowRetainedFloor,yi as deleteGlobalShapeSnapshot,$i as deleteGlobalShapeSnapshotsForConnection,hi as migrateClientWatermark,Ei as migrateGlobalShapeSnapshot,oi as minCdcReplayableSeq,ri as minCdcSeq,Qt as normalizeIdStructurally,ii as readCdcChangeKeys,si as readCdcChanges,ci as readCdcCursor,ai as readCdcEpoch,wi as readClientWatermark,mi as readGlobalShapeSnapshot,Ti as readIdempotent,Ci as runShardMigrations,Di as selectShapeMembers,ki as selectShapeRows,st as stripReservedPatchFields,di as trimCdcChanges,vi as trimIdempotent,Si as writeGlobalShapeSnapshot,Ai as writeIdempotent};
|