@lunora/shard-engine 1.0.0-alpha.26 → 1.0.0-alpha.28
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/conformance/index.mjs +1 -1
- package/dist/index.d.mts +7 -1
- package/dist/index.d.ts +7 -1
- package/dist/index.mjs +1 -1
- package/dist/packem_shared/ADMIN_FUNCTIONS-Ddr79XHG.mjs +1 -0
- package/dist/packem_shared/AGGREGATE_SQL_FUNCTION-m1iUU1rv.mjs +1 -0
- package/dist/packem_shared/AGG_COUNT-DOlqqroz.mjs +1 -0
- package/dist/packem_shared/AUDIT_LOG_TABLE-uNVU9O1W.mjs +8 -0
- package/dist/packem_shared/CDC_LOG_TABLE-B58N8NQO.mjs +8 -0
- package/dist/packem_shared/CLIENT_WATERMARK_TABLE-BoS1HEqz.mjs +7 -0
- package/dist/packem_shared/CountRlsUnsupportedError-Bdfupt3g.mjs +1 -0
- package/dist/packem_shared/DATA_MIGRATION_STATE_TABLE-4l6aU1Vc.mjs +31 -0
- package/dist/packem_shared/DEFAULT_MAX_RELATION_KEYS-BAWGIEvC.mjs +1 -0
- package/dist/packem_shared/DEFAULT_MAX_RELAYS-DeVcEXBh.mjs +1 -0
- package/dist/packem_shared/DEFAULT_PROMOTION_THRESHOLDS-DVTD9iu0.mjs +1 -0
- package/dist/packem_shared/DEFAULT_TRANSACTION_LIMITS-Bcoi7Bvf.mjs +1 -0
- package/dist/packem_shared/DurableStreamRunner-Bm6KDMBU.mjs +1 -0
- package/dist/packem_shared/GEO_DEFAULT_PRECISION-CqpQZ-J_.mjs +1 -0
- package/dist/packem_shared/GLOBAL_SHAPE_SNAPSHOT_TABLE-NWaL77m5.mjs +7 -0
- package/dist/packem_shared/IDEMPOTENCY_TABLE-DKVe2Ohf.mjs +7 -0
- package/dist/packem_shared/MAIL_RETENTION-Cig9Dmc8.mjs +18 -0
- package/dist/packem_shared/MAX_SQL_ROWS-DnDyeZph.mjs +2 -0
- package/dist/packem_shared/NotUniqueError-BixDiv4O.mjs +1 -0
- package/dist/packem_shared/QUEUE_TABLE-zj9Tt6tk.mjs +17 -0
- package/dist/packem_shared/RANK_TIEBREAK-ci3MaM65.mjs +1 -0
- package/dist/packem_shared/RELATION_EXISTS_KEY-CFUhnZSZ.mjs +1 -0
- package/dist/packem_shared/REPROJECTION_MIGRATION_PREFIX-Czcb6_mO.mjs +1 -0
- package/dist/packem_shared/RLS_UNWRAP_SYMBOL-BWloGsd3.mjs +1 -0
- package/dist/packem_shared/ReactiveCache-DfyeaJOA.mjs +1 -0
- package/dist/packem_shared/SCAN_DEP-D7qE3iUe.mjs +1 -0
- package/dist/packem_shared/SCHEMA_HISTORY_MAX_VERSIONS-DsycDXWm.mjs +6 -0
- package/dist/packem_shared/SEARCH_STATE_TABLE-Dju8ebbU.mjs +1 -0
- package/dist/packem_shared/SHAPE_POKE_CURSOR_TABLE-Dh4HfSdC.mjs +7 -0
- package/dist/packem_shared/ShardRunner-C9p5DVOx.mjs +1 -0
- package/dist/packem_shared/aggregateTableName-Cy5e03oz.mjs +1 -0
- package/dist/packem_shared/appendStreamChunk-CH4e4nJn.mjs +19 -0
- package/dist/packem_shared/applyOnDelete-BlcwKjuO.mjs +1 -0
- package/dist/packem_shared/applySelect-BQbHyo-W.mjs +1 -0
- package/dist/packem_shared/{armRestore-BNzdvQ_o.mjs → armRestore-Bu1_8SUa.mjs} +1 -1
- package/dist/packem_shared/awaitWsDrain-kSGvAfw1.mjs +1 -0
- package/dist/packem_shared/backfillAggregateIndexes-DVQ2sVuV.mjs +1 -0
- package/dist/packem_shared/base64-DfpzS4o_.mjs +1 -0
- package/dist/packem_shared/buildIndexRange-CBKQmHSS.mjs +1 -0
- package/dist/packem_shared/buildPokeFrames-BXejpiII.mjs +1 -0
- package/dist/packem_shared/buildReprojectionMigration-8nVn8Qwb.mjs +1 -0
- package/dist/packem_shared/buildSettings-B4igo4rJ.mjs +1 -0
- package/dist/packem_shared/compileWhereSql-JBpSfQm9.mjs +1 -0
- package/dist/packem_shared/computeRankPage-Bby1Npkd.mjs +1 -0
- package/dist/packem_shared/createCompanionSync-zCwaB6wj.mjs +1 -0
- package/dist/packem_shared/createReadFootprint-MRH1If3F.mjs +1 -0
- package/dist/packem_shared/createReplicaLink-C1JuP_DN.mjs +7 -0
- package/dist/packem_shared/createSystemReader-BtYeSMDb.mjs +1 -0
- package/dist/packem_shared/ctx-db-companions-lTt-rvKG.mjs +1 -0
- package/dist/packem_shared/defineEngineContractSuite-0XtjRA7F.mjs +1 -0
- package/dist/packem_shared/diffExternalSource-pozJ4UdZ.mjs +1 -0
- package/dist/packem_shared/do-sql-Dk_DJxn4.mjs +1 -0
- package/dist/packem_shared/estimate-bytes-CzG5x1f8.mjs +1 -0
- package/dist/packem_shared/exportShardRows-Cgt3ITwH.mjs +1 -0
- package/dist/packem_shared/hasTrigger-CjlwI4le.mjs +1 -0
- package/dist/packem_shared/isSoftDeleted-DcGB0pov.mjs +9 -0
- package/dist/packem_shared/liftSourceId-CA3ENhXj.mjs +1 -0
- package/dist/packem_shared/materializeExternalRows-Drn0FGdb.mjs +1 -0
- package/dist/packem_shared/mergeChangedKeys-D1T-TPUb.mjs +1 -0
- package/dist/packem_shared/param-Ib8WHnrF.mjs +1 -0
- package/dist/packem_shared/runDrizzle-it6rL9bR.mjs +1 -0
- package/dist/packem_shared/runShardMigrations-Crppyq1f.mjs +5 -0
- package/dist/packem_shared/runSocketPool-CZJ2X9cF.mjs +1 -0
- package/dist/packem_shared/selectExpiredIds-_5514W_v.mjs +1 -0
- package/dist/packem_shared/selectShapeMemberIds-B-pQJHAu.mjs +1 -0
- package/dist/packem_shared/serializeSqlValue-DbI1VQYM.mjs +1 -0
- package/dist/packem_shared/sibling-channel-BRZpLiDA.mjs +1 -0
- package/dist/packem_shared/sql-projection-BqmxFxQU.mjs +1 -0
- package/dist/packem_shared/stableStringify-CujpENIO.mjs +1 -0
- package/dist/packem_shared/stableWireKey-BYB5GQJa.mjs +1 -0
- package/dist/packem_shared/wire-codec-BU9T2xJ7.mjs +1 -0
- package/package.json +3 -3
- package/dist/packem_shared/ADMIN_FUNCTIONS-Cj1pJjVg.mjs +0 -1
- package/dist/packem_shared/AGGREGATE_SQL_FUNCTION-CTo0-9iZ.mjs +0 -1
- package/dist/packem_shared/AGG_COUNT-CKtq03Go.mjs +0 -1
- package/dist/packem_shared/AUDIT_LOG_TABLE-Bl2mYtAQ.mjs +0 -8
- package/dist/packem_shared/CDC_LOG_TABLE-DNFFQwF_.mjs +0 -8
- package/dist/packem_shared/CLIENT_WATERMARK_TABLE-LrKfdxyt.mjs +0 -7
- package/dist/packem_shared/CountRlsUnsupportedError-8BqPYQoP.mjs +0 -1
- package/dist/packem_shared/DATA_MIGRATION_STATE_TABLE-DIQTu___.mjs +0 -31
- package/dist/packem_shared/DEFAULT_MAX_RELATION_KEYS-BV1RCoat.mjs +0 -1
- package/dist/packem_shared/DEFAULT_MAX_RELAYS-Cinp9pPC.mjs +0 -1
- package/dist/packem_shared/DEFAULT_PROMOTION_THRESHOLDS-DYGNAo1I.mjs +0 -1
- package/dist/packem_shared/DEFAULT_TRANSACTION_LIMITS-DLUzZbta.mjs +0 -1
- package/dist/packem_shared/DurableStreamRunner-B54Jt9Iu.mjs +0 -1
- package/dist/packem_shared/GEO_DEFAULT_PRECISION-DyI5zggj.mjs +0 -1
- package/dist/packem_shared/GLOBAL_SHAPE_SNAPSHOT_TABLE-B2LKe4KU.mjs +0 -7
- package/dist/packem_shared/IDEMPOTENCY_TABLE-tQ5mnqvw.mjs +0 -7
- package/dist/packem_shared/MAIL_RETENTION-CzZuX9bd.mjs +0 -18
- package/dist/packem_shared/MAX_SQL_ROWS-nMwkxv5f.mjs +0 -2
- package/dist/packem_shared/NotUniqueError-DYo7r67J.mjs +0 -1
- package/dist/packem_shared/QUEUE_TABLE-BX0nopuT.mjs +0 -17
- package/dist/packem_shared/RANK_TIEBREAK-BGk411OR.mjs +0 -1
- package/dist/packem_shared/RELATION_EXISTS_KEY-BaqSIFU1.mjs +0 -1
- package/dist/packem_shared/REPROJECTION_MIGRATION_PREFIX-D2dltRFC.mjs +0 -1
- package/dist/packem_shared/RLS_UNWRAP_SYMBOL-DcqORh2s.mjs +0 -1
- package/dist/packem_shared/ReactiveCache-D_T10KLy.mjs +0 -1
- package/dist/packem_shared/SCAN_DEP-D_yR9EeV.mjs +0 -1
- package/dist/packem_shared/SCHEMA_HISTORY_MAX_VERSIONS-CEK7b_7v.mjs +0 -6
- package/dist/packem_shared/SEARCH_STATE_TABLE-DRk_SB72.mjs +0 -1
- package/dist/packem_shared/ShardRunner-DIqVdWtk.mjs +0 -1
- package/dist/packem_shared/aggregateTableName-DN7gk6uh.mjs +0 -1
- package/dist/packem_shared/appendStreamChunk-ksZYy1hZ.mjs +0 -19
- package/dist/packem_shared/applyOnDelete-crbAzVfE.mjs +0 -1
- package/dist/packem_shared/applySelect-5w13bMAR.mjs +0 -1
- package/dist/packem_shared/awaitWsDrain-PT9o0d6J.mjs +0 -1
- package/dist/packem_shared/backfillAggregateIndexes-DTOIsYbi.mjs +0 -1
- package/dist/packem_shared/base64-fKomMf5D.mjs +0 -1
- package/dist/packem_shared/buildIndexRange-DFsdtPjD.mjs +0 -1
- package/dist/packem_shared/buildPokeFrames-DmB-FBeQ.mjs +0 -1
- package/dist/packem_shared/buildReprojectionMigration-JUwsTNTB.mjs +0 -1
- package/dist/packem_shared/buildSettings-COIJsw7a.mjs +0 -1
- package/dist/packem_shared/compileWhereSql-B3hq_v98.mjs +0 -1
- package/dist/packem_shared/computeRankPage-BU8LXvQs.mjs +0 -1
- package/dist/packem_shared/createCompanionSync-D-ckGBdA.mjs +0 -1
- package/dist/packem_shared/createReadFootprint-DIrrxRTE.mjs +0 -1
- package/dist/packem_shared/createReplicaLink-BMNW0SX6.mjs +0 -7
- package/dist/packem_shared/createSystemReader-DcDcrtM3.mjs +0 -1
- package/dist/packem_shared/ctx-db-companions-BJlCofon.mjs +0 -1
- package/dist/packem_shared/defineEngineContractSuite-CvdzORsy.mjs +0 -1
- package/dist/packem_shared/diffExternalSource-DMpkJta1.mjs +0 -1
- package/dist/packem_shared/do-sql-DKSFK627.mjs +0 -1
- package/dist/packem_shared/estimate-bytes-Drp8rhPs.mjs +0 -1
- package/dist/packem_shared/exportShardRows-Bbi_JGfn.mjs +0 -1
- package/dist/packem_shared/hasTrigger-CbkOHExZ.mjs +0 -1
- package/dist/packem_shared/isSoftDeleted-DyEJueIu.mjs +0 -9
- package/dist/packem_shared/liftSourceId-DApAbu7Q.mjs +0 -1
- package/dist/packem_shared/materializeExternalRows-C-5TKdc1.mjs +0 -1
- package/dist/packem_shared/mergeChangedKeys-BXtUgIPW.mjs +0 -1
- package/dist/packem_shared/param-CYxL68V-.mjs +0 -1
- package/dist/packem_shared/runDrizzle-C3n5gJsk.mjs +0 -1
- package/dist/packem_shared/runShardMigrations-BCuK60KT.mjs +0 -5
- package/dist/packem_shared/runSocketPool-DPQLVyWF.mjs +0 -1
- package/dist/packem_shared/selectExpiredIds-C4Ry_NxG.mjs +0 -1
- package/dist/packem_shared/selectShapeMemberIds-Bkkug6vU.mjs +0 -1
- package/dist/packem_shared/serializeSqlValue-BR4UOWoP.mjs +0 -1
- package/dist/packem_shared/sibling-channel-bg9FBL5s.mjs +0 -1
- package/dist/packem_shared/sql-projection-jfoe331H.mjs +0 -1
- package/dist/packem_shared/stableStringify-BjLh4gvA.mjs +0 -1
- package/dist/packem_shared/stableWireKey-Diuu1gGc.mjs +0 -1
- package/dist/packem_shared/wire-codec-Dh0j-GnY.mjs +0 -1
|
@@ -1 +1 @@
|
|
|
1
|
-
import{defineEngineContractSuite as t}from"../packem_shared/defineEngineContractSuite-
|
|
1
|
+
import{defineEngineContractSuite as t}from"../packem_shared/defineEngineContractSuite-0XtjRA7F.mjs";export{t as defineEngineContractSuite};
|
package/dist/index.d.mts
CHANGED
|
@@ -932,6 +932,12 @@ interface RankPageComputation {
|
|
|
932
932
|
}
|
|
933
933
|
declare const hydrateDocsById: (deps: RankPageDeps, tableName: string, ids: ReadonlyArray<string>) => Map<string, Record<string, unknown>>;
|
|
934
934
|
declare const computeRankPage: (deps: RankPageDeps, tableName: string, indexName: string, rankPageOptions: RankPageOptions) => RankPageComputation;
|
|
935
|
+
declare const SHAPE_POKE_CURSOR_TABLE = "__shape_poke_cursor";
|
|
936
|
+
declare const migrateShapePokeCursor: (sql: SqlExec) => void;
|
|
937
|
+
declare const readShapePokeCursor: (sql: SqlExec, connectionId: string, subId: string) => number | undefined;
|
|
938
|
+
declare const writeShapePokeCursor: (sql: SqlExec, connectionId: string, subId: string, cursor: number) => void;
|
|
939
|
+
declare const deleteShapePokeCursor: (sql: SqlExec, connectionId: string, subId: string) => void;
|
|
940
|
+
declare const deleteShapePokeCursorsForConnection: (sql: SqlExec, connectionId: string) => void;
|
|
935
941
|
declare const DATA_MIGRATION_STATE_TABLE = "__lunora_migrations";
|
|
936
942
|
type MigrationDirection = "down" | "up";
|
|
937
943
|
type MigrationStatus = "completed" | "failed" | "in_progress";
|
|
@@ -2138,4 +2144,4 @@ interface WhereSqlStrategy {
|
|
|
2138
2144
|
}
|
|
2139
2145
|
declare const literalInList: (reference: SQL, items: ReadonlyArray<unknown>, negated: boolean) => SQL;
|
|
2140
2146
|
declare const compileWhereSql: (where: WhereInput | undefined, strategy: WhereSqlStrategy) => SQL | undefined;
|
|
2141
|
-
export { ADMIN_FUNCTIONS, ADMIN_FUNCTION_PREFIX, AGGREGATE_SQL_FUNCTION, AGG_COUNT, AGG_KEY, AGG_VALUE, AUDIT_LOG_TABLE, type AdvisorProcedure, type AdvisorProceduresResult, type AdvisoriesResult, type AdvisoryFinding, type AggregateIndexDefinitionLike, type AggregateOp, type AggregateOptions, type AggregateResult, type AggregateTally, type AppendAuditEntry, type ApplyOnDeleteOptions$1 as ApplyOnDeleteOptions, type AuditEntry, type AuditLogResult, type BroadcastDelta, CDC_LOG_TABLE, CDC_META_TABLE, CLIENT_WATERMARK_TABLE, type CacheEntry, type CapturedMailRow, type CdcChange, type ChangedKeys, type Clock, type ColumnMeta, type ColumnMetaLike, type CompanionSync, type CompanionSyncDeps, ConflictError, type ConflictKind, type CountArgs, CountRlsUnsupportedError, type CreateWorkflowInstanceResult, type CrossShardReadArgs, type CtxDbOptions, DATA_MIGRATION_STATE_TABLE, DEFAULT_FANOUT_TOPIC_LIMIT, DEFAULT_MAX_RELATION_KEYS, DEFAULT_MAX_RELAYS, DEFAULT_PROMOTION_THRESHOLDS, DEFAULT_TRANSACTION_LIMITS, DOC_COLUMN, type DataMigrationDocument, type DataMigrationLike, type DataMigrationTransform, type DatabaseWriterLike, type DependencyTracker, type DeployInfo, type DurableAttachDecision, type DurableStreamAttach, type DurableStreamRun, DurableStreamRunner, type DurableStreamSink, type ExportRow, type ExportShardAdminArgs, type ExportShardArgs, type ExternalSourceDiffResult, type ExternalSourceLike, FLAGS_FUNCTION_PREFIX, type FacetColumnOptions, type FacetColumnResult, type FacetValue, type FanoutMetricsResult, type FanoutPathCounters, type FanoutTopicStat, type FieldOperators, type FilterClause, type FilterOperator, type FlagEvaluation, type FlagsResult, type FunctionCallStat, type FunctionScanAttribution, type FunctionStatsResult, GEO_DEFAULT_PRECISION, GLOBAL_SHAPE_SNAPSHOT_TABLE, type GeoBoundingBox, type GeoFilterBuilderLike, type GeoIndexDefinitionLike, type GeoPoint, type GeoScoredDocument, type GroupByEntry, type GroupByOptions, type GuardableSchema$1 as GuardableSchema, IDEMPOTENCY_TABLE, type IdGenerator, type IdempotentRecord, type ImportError, type ImportShardAdminArgs, type ImportShardArgs, type ImportShardResult, type IncrementalMaterializeResult, type IndexDefinitionLike, type IndexKeyEntry, type IndexRangeBuilderLike, type KeyRange, type LifecycleDispatchInfo, type LifecycleEvent, MAIL_RETENTION, MAIL_TABLE, MAX_DURABLE_STREAM_BYTES, MAX_DURABLE_STREAM_CHUNKS, MAX_PAGE_SIZE, MAX_SQL_ROWS, type MaskColumnMetadata, type MaskPoliciesResult, type MaterializeResult, type MigrationDirection, type MigrationRunResult, type MigrationStatus, type MigrationStatusRow, type MutationDelta, type NestedWith, NotFoundError, NotUniqueError, type OnDeleteActionLike, type OrderByClause, type OrderByInput, type OrderKey, OwnerRelay, type OwnerRelayFrame, type PaginationOptions, type PitrBookmarkResult, type PitrRestoreArgs, type PitrRestoreResult, type PitrStorage, type PokeFrameMeta, type PromotionState, type PromotionThresholds, QUEUE_TABLE, type QueryArgs, type QueryPage, type QueueMessageOutcome, type QueueMessageRow, type QueueMetadata, type QueuesResult, RANK_TIEBREAK, RELATION_EXISTS_KEY, RELATION_FUNCTION_PREFIX, REPROJECTION_MIGRATION_PREFIX, RLS_UNWRAP_SYMBOL, type RankBeforeOptions, type RankBeforeResult, type RankDirection, type RankIndexDefinitionLike, type RankOptions, type RankPage, type RankPageComputation, type RankPageDeps, type RankPageOptions, type RankPageRow, type RankPageRowKey, type RankResult, type RankSortKeyLike, ReactiveCache, type ReactiveCacheOptions, type ReadFootprint, type ReadHook, type ReadTablePageOptions, type RecordMailInput, type RecordQueueMessageInput, type RelationDefinitionLike, type RelationExistsMarker, type RelayAttach, type RelayDetach, type RelayFrame, type RelayHost, RelayMember, type RelayShapePoke, type RelayShapeSeed, type RelayShapeSubscribe, type RenderedSql, type ReplicaFollowerHost, type ReplicaOwnerHost, type ReplicaReadiness, type ResolveRelationPredicatesOptions, type ResolveWithOptions, type ResolveWithResult, type ResolvedShape, type RestrictableQueryOptions, type RlsPoliciesResult, type RlsPolicyMetadata, RlsRequiredError, type RlsRoleMetadata, type RpcRequest, type RunDataMigrationOptions, type RunTriggersOptions, SCAN_DEP, SCHEMA_HISTORY_MAX_VERSIONS, SEARCH_STATE_TABLE, type SchedulableWorkflowReferenceLike, type ScheduledFunctionDoc, type SchedulerLike, type SchemaLike, type ScoredDocument, type SearchFilterBuilderLike, type SearchIndexDefinitionLike, type SearchScoredDocument, type SelectMatchingIdsOptions, type ServerDefaultContextLike, type SettingEntry, type SettingKind, type SettingsResult, type ShapePokePart, type ShapeRow, type ShapeRowOp, type ShapeSubscriptionQuery, type ShardRankPageResult, ShardRunner, type ShardRunnerOptions, type ShardSiblingHost, type ShardSocketLike, type SocketAttachment, type SortDirection, type SourceClientLike, type SourceCursorLike, type SourceRefresh, type SqlConsoleResult, type SqlCursor, type SqlEngine, type SqlExec, type SqlLintResult, type StorageMetadata, type StorageReference, type StorageReferenceResult, type StorageRuleMetadata, type StorageRulesResult, type StudioFeaturesResult, type SubscriptionConnection, type SubscriptionEnvelope, type SubscriptionIdentity, type SubscriptionInfo, type SubscriptionQuery, type SubscriptionReadFootprint, type SubscriptionsResult, type SystemDatabaseReader, type SystemDoc, type SystemQuery, type SystemReaderOptions, type SystemReaderSchedulerLike, type SystemReaderStorageLike, type SystemTableName, type TableColumnsResult, type TableDefinitionLike, type TableIndexInfo, type TableIndexesResult, type TableInfo, type TablePage, type TableReaderLike, type TablesColumnsResult, type TablesIndexesResult, type TransactionHeadroom, TransactionHeadroomTracker, type TransactionLimits, type TransactionSqlLike, type TriggerContextLike, type TriggerDefinitionLike, type TriggerEventLike, type TriggerOpLike, type TriggerTimingLike, type TtlSweepSpec, type ValidatorLike, type WhereInput, type WhereSqlStrategy, type WithInput, type WorkflowInstanceState, type WorkflowInstanceStatusResult, type WorkflowMetadata, type WorkflowsResult, type WriteEvent, type WriteHook, advanceClientWatermark, aggUpsertSql, aggregateSqlFunction, aggregateTableName, appendAuditEntry, appendCdcChange, appendStreamChunk, applyCdcChanges, applyOnDelete, applySelect, armRestore, assertFlatPredicate, assertReadonly, assertShapeShardable, assertValidClientId, awaitWsDrain, backfillAggregateIndexes, backfillRankIndexes, backfillSearchIndexes, backfillSearchIndexesForTable, boundingBoxCenter, boundingBoxGeohashes, buildIndexRange, buildPokeFrames, buildReprojectionMigration, buildSeekBeforeWhere, buildSeekWhere, buildSettings, bumpCdcEpoch, claimStreamRun, clampPromotionThresholds, clearCapturedMail, clearQueueMessages, coerceAggregateNumber, compileWhereSql, computeRankPage, containsRelationPredicate, countLegacyRows, coveringGeohashes, createCompanionSync, createDependencyTracker, createFanoutCounters, createIndexSql, createReadFootprint, createRelayLink, createReplicaLink, createShardCtxDb, createSystemReader, decideDurableAttach, decodeCursor, deleteGlobalShapeSnapshot, deleteGlobalShapeSnapshotsForConnection, deleteStreamRun, depKey, diffExternalSource, diffGlobalMembership, distinctValues, encodeAggregateKey, encodeCursor, encodeGeohash, encodePartitionKey, encodeRowsPatch, ensureAuditTable, ensureMailTable, exportShardRows, exportShardTable, facetColumn, fanOutScalarCounts, findStorageReferences, finishStreamRun, foldAggregateTally, gateReplicaDispatch, geoTableName, guardWriter, handleReplicaControl, hasTrigger, haversineMeters, hydrateDocsById, importShardRows, indexKeysForRow, isDevEnvironment, isFtsAvailable, isLossyBody, isRelationPredicate, isSoftDeleted, isSourceDue, jsonPath, jsonPathSql, keysTouchRanges, liftSourceId, lintReadonlySql, listTables, literalInList, matchesRankStaticWhere, matchesStaticWhere, materializeExternalRows, materializeExternalRowsIncremental, mergeChangedKeys, mergeWhere, migrateCdcLog, migrateCdcMeta, migrateClientWatermark, migrateDurableStreams, migrateGlobalShapeSnapshot, migrateIdempotency, migrateSearchState, minCdcSeq, nextPromotionState, normalizeCountArgument, normalizeIdStructurally, normalizeOrderKeys, normalizeSourceDocument, normalizeSourceValue, param, parseExportShardArgs, parseImportShardArgs, planAggregateLookup, pointInBoundingBox, projectColumns, pullExternalSourceIncrementalTick, pullExternalSourceTick, qualifiedJsonPath, qualifiedJsonPathSql, quoteIdentifier, rankKeyFromDocument as rankKeyFromDoc, rankTableName, reactiveCacheKey, readAggregateValue, readAuditLog, readBookmark, readCapturedMail, readCdcChanges, readCdcCursor, readCdcEpoch, readClientWatermark, readExternalSourceBaseline, readGlobalShapeSnapshot, readIdempotent, readMigrationStatus, readQueueMessageById, readQueueMessages, readSchemaHistory, readSchemaVersion, readSearchBackfillState, readStreamChunks, readStreamRun, readTablePage, recordCapturedMail, recordChangedKeys, recordFanoutPass, recordQueueMessages, recordSchemaVersion, relationHooks, relayCountFor, renderSql, reprojectableFields, reprojectionMigrationId, reprojectionTables, resolveRankPartition, resolveRelationPredicates, resolveWith, rowToDocument, runDataMigration, runDrizzle, runExternalSourceTick, runReadonlySql, runRowValidators, runShardMigrations, runSocketPool, runSql, runTriggers, selectExpiredIds, selectExportTables, selectIndexForAggregate, selectIndexForCount, selectIndexForGroupBy, selectMatchingIds, selectShapeMemberIds, selectShapeRows, serializeSqlValue, shapeRoutingKey, softDeleteScope, sortColumnName, sqliteInList, stableStringify, stableWireKey, subscriptionFrames, subscriptionListDeltas, summarizeFanoutTopics, summarizeSubscriptions, tableColumns, tableFromDepKey, throwingScheduler, trimCdcChanges, trimIdempotent, trimStreamRuns, tryRowToDocument, trySendFrame, unionAll, validateImportRow, writeGlobalShapeSnapshot, writeIdempotent, writeSearchBackfillState, writeTouchesMemo };
|
|
2147
|
+
export { ADMIN_FUNCTIONS, ADMIN_FUNCTION_PREFIX, AGGREGATE_SQL_FUNCTION, AGG_COUNT, AGG_KEY, AGG_VALUE, AUDIT_LOG_TABLE, type AdvisorProcedure, type AdvisorProceduresResult, type AdvisoriesResult, type AdvisoryFinding, type AggregateIndexDefinitionLike, type AggregateOp, type AggregateOptions, type AggregateResult, type AggregateTally, type AppendAuditEntry, type ApplyOnDeleteOptions$1 as ApplyOnDeleteOptions, type AuditEntry, type AuditLogResult, type BroadcastDelta, CDC_LOG_TABLE, CDC_META_TABLE, CLIENT_WATERMARK_TABLE, type CacheEntry, type CapturedMailRow, type CdcChange, type ChangedKeys, type Clock, type ColumnMeta, type ColumnMetaLike, type CompanionSync, type CompanionSyncDeps, ConflictError, type ConflictKind, type CountArgs, CountRlsUnsupportedError, type CreateWorkflowInstanceResult, type CrossShardReadArgs, type CtxDbOptions, DATA_MIGRATION_STATE_TABLE, DEFAULT_FANOUT_TOPIC_LIMIT, DEFAULT_MAX_RELATION_KEYS, DEFAULT_MAX_RELAYS, DEFAULT_PROMOTION_THRESHOLDS, DEFAULT_TRANSACTION_LIMITS, DOC_COLUMN, type DataMigrationDocument, type DataMigrationLike, type DataMigrationTransform, type DatabaseWriterLike, type DependencyTracker, type DeployInfo, type DurableAttachDecision, type DurableStreamAttach, type DurableStreamRun, DurableStreamRunner, type DurableStreamSink, type ExportRow, type ExportShardAdminArgs, type ExportShardArgs, type ExternalSourceDiffResult, type ExternalSourceLike, FLAGS_FUNCTION_PREFIX, type FacetColumnOptions, type FacetColumnResult, type FacetValue, type FanoutMetricsResult, type FanoutPathCounters, type FanoutTopicStat, type FieldOperators, type FilterClause, type FilterOperator, type FlagEvaluation, type FlagsResult, type FunctionCallStat, type FunctionScanAttribution, type FunctionStatsResult, GEO_DEFAULT_PRECISION, GLOBAL_SHAPE_SNAPSHOT_TABLE, type GeoBoundingBox, type GeoFilterBuilderLike, type GeoIndexDefinitionLike, type GeoPoint, type GeoScoredDocument, type GroupByEntry, type GroupByOptions, type GuardableSchema$1 as GuardableSchema, IDEMPOTENCY_TABLE, type IdGenerator, type IdempotentRecord, type ImportError, type ImportShardAdminArgs, type ImportShardArgs, type ImportShardResult, type IncrementalMaterializeResult, type IndexDefinitionLike, type IndexKeyEntry, type IndexRangeBuilderLike, type KeyRange, type LifecycleDispatchInfo, type LifecycleEvent, MAIL_RETENTION, MAIL_TABLE, MAX_DURABLE_STREAM_BYTES, MAX_DURABLE_STREAM_CHUNKS, MAX_PAGE_SIZE, MAX_SQL_ROWS, type MaskColumnMetadata, type MaskPoliciesResult, type MaterializeResult, type MigrationDirection, type MigrationRunResult, type MigrationStatus, type MigrationStatusRow, type MutationDelta, type NestedWith, NotFoundError, NotUniqueError, type OnDeleteActionLike, type OrderByClause, type OrderByInput, type OrderKey, OwnerRelay, type OwnerRelayFrame, type PaginationOptions, type PitrBookmarkResult, type PitrRestoreArgs, type PitrRestoreResult, type PitrStorage, type PokeFrameMeta, type PromotionState, type PromotionThresholds, QUEUE_TABLE, type QueryArgs, type QueryPage, type QueueMessageOutcome, type QueueMessageRow, type QueueMetadata, type QueuesResult, RANK_TIEBREAK, RELATION_EXISTS_KEY, RELATION_FUNCTION_PREFIX, REPROJECTION_MIGRATION_PREFIX, RLS_UNWRAP_SYMBOL, type RankBeforeOptions, type RankBeforeResult, type RankDirection, type RankIndexDefinitionLike, type RankOptions, type RankPage, type RankPageComputation, type RankPageDeps, type RankPageOptions, type RankPageRow, type RankPageRowKey, type RankResult, type RankSortKeyLike, ReactiveCache, type ReactiveCacheOptions, type ReadFootprint, type ReadHook, type ReadTablePageOptions, type RecordMailInput, type RecordQueueMessageInput, type RelationDefinitionLike, type RelationExistsMarker, type RelayAttach, type RelayDetach, type RelayFrame, type RelayHost, RelayMember, type RelayShapePoke, type RelayShapeSeed, type RelayShapeSubscribe, type RenderedSql, type ReplicaFollowerHost, type ReplicaOwnerHost, type ReplicaReadiness, type ResolveRelationPredicatesOptions, type ResolveWithOptions, type ResolveWithResult, type ResolvedShape, type RestrictableQueryOptions, type RlsPoliciesResult, type RlsPolicyMetadata, RlsRequiredError, type RlsRoleMetadata, type RpcRequest, type RunDataMigrationOptions, type RunTriggersOptions, SCAN_DEP, SCHEMA_HISTORY_MAX_VERSIONS, SEARCH_STATE_TABLE, SHAPE_POKE_CURSOR_TABLE, type SchedulableWorkflowReferenceLike, type ScheduledFunctionDoc, type SchedulerLike, type SchemaLike, type ScoredDocument, type SearchFilterBuilderLike, type SearchIndexDefinitionLike, type SearchScoredDocument, type SelectMatchingIdsOptions, type ServerDefaultContextLike, type SettingEntry, type SettingKind, type SettingsResult, type ShapePokePart, type ShapeRow, type ShapeRowOp, type ShapeSubscriptionQuery, type ShardRankPageResult, ShardRunner, type ShardRunnerOptions, type ShardSiblingHost, type ShardSocketLike, type SocketAttachment, type SortDirection, type SourceClientLike, type SourceCursorLike, type SourceRefresh, type SqlConsoleResult, type SqlCursor, type SqlEngine, type SqlExec, type SqlLintResult, type StorageMetadata, type StorageReference, type StorageReferenceResult, type StorageRuleMetadata, type StorageRulesResult, type StudioFeaturesResult, type SubscriptionConnection, type SubscriptionEnvelope, type SubscriptionIdentity, type SubscriptionInfo, type SubscriptionQuery, type SubscriptionReadFootprint, type SubscriptionsResult, type SystemDatabaseReader, type SystemDoc, type SystemQuery, type SystemReaderOptions, type SystemReaderSchedulerLike, type SystemReaderStorageLike, type SystemTableName, type TableColumnsResult, type TableDefinitionLike, type TableIndexInfo, type TableIndexesResult, type TableInfo, type TablePage, type TableReaderLike, type TablesColumnsResult, type TablesIndexesResult, type TransactionHeadroom, TransactionHeadroomTracker, type TransactionLimits, type TransactionSqlLike, type TriggerContextLike, type TriggerDefinitionLike, type TriggerEventLike, type TriggerOpLike, type TriggerTimingLike, type TtlSweepSpec, type ValidatorLike, type WhereInput, type WhereSqlStrategy, type WithInput, type WorkflowInstanceState, type WorkflowInstanceStatusResult, type WorkflowMetadata, type WorkflowsResult, type WriteEvent, type WriteHook, advanceClientWatermark, aggUpsertSql, aggregateSqlFunction, aggregateTableName, appendAuditEntry, appendCdcChange, appendStreamChunk, applyCdcChanges, applyOnDelete, applySelect, armRestore, assertFlatPredicate, assertReadonly, assertShapeShardable, assertValidClientId, awaitWsDrain, backfillAggregateIndexes, backfillRankIndexes, backfillSearchIndexes, backfillSearchIndexesForTable, boundingBoxCenter, boundingBoxGeohashes, buildIndexRange, buildPokeFrames, buildReprojectionMigration, buildSeekBeforeWhere, buildSeekWhere, buildSettings, bumpCdcEpoch, claimStreamRun, clampPromotionThresholds, clearCapturedMail, clearQueueMessages, coerceAggregateNumber, compileWhereSql, computeRankPage, containsRelationPredicate, countLegacyRows, coveringGeohashes, createCompanionSync, createDependencyTracker, createFanoutCounters, createIndexSql, createReadFootprint, createRelayLink, createReplicaLink, createShardCtxDb, createSystemReader, decideDurableAttach, decodeCursor, deleteGlobalShapeSnapshot, deleteGlobalShapeSnapshotsForConnection, deleteShapePokeCursor, deleteShapePokeCursorsForConnection, deleteStreamRun, depKey, diffExternalSource, diffGlobalMembership, distinctValues, encodeAggregateKey, encodeCursor, encodeGeohash, encodePartitionKey, encodeRowsPatch, ensureAuditTable, ensureMailTable, exportShardRows, exportShardTable, facetColumn, fanOutScalarCounts, findStorageReferences, finishStreamRun, foldAggregateTally, gateReplicaDispatch, geoTableName, guardWriter, handleReplicaControl, hasTrigger, haversineMeters, hydrateDocsById, importShardRows, indexKeysForRow, isDevEnvironment, isFtsAvailable, isLossyBody, isRelationPredicate, isSoftDeleted, isSourceDue, jsonPath, jsonPathSql, keysTouchRanges, liftSourceId, lintReadonlySql, listTables, literalInList, matchesRankStaticWhere, matchesStaticWhere, materializeExternalRows, materializeExternalRowsIncremental, mergeChangedKeys, mergeWhere, migrateCdcLog, migrateCdcMeta, migrateClientWatermark, migrateDurableStreams, migrateGlobalShapeSnapshot, migrateIdempotency, migrateSearchState, migrateShapePokeCursor, minCdcSeq, nextPromotionState, normalizeCountArgument, normalizeIdStructurally, normalizeOrderKeys, normalizeSourceDocument, normalizeSourceValue, param, parseExportShardArgs, parseImportShardArgs, planAggregateLookup, pointInBoundingBox, projectColumns, pullExternalSourceIncrementalTick, pullExternalSourceTick, qualifiedJsonPath, qualifiedJsonPathSql, quoteIdentifier, rankKeyFromDocument as rankKeyFromDoc, rankTableName, reactiveCacheKey, readAggregateValue, readAuditLog, readBookmark, readCapturedMail, readCdcChanges, readCdcCursor, readCdcEpoch, readClientWatermark, readExternalSourceBaseline, readGlobalShapeSnapshot, readIdempotent, readMigrationStatus, readQueueMessageById, readQueueMessages, readSchemaHistory, readSchemaVersion, readSearchBackfillState, readShapePokeCursor, readStreamChunks, readStreamRun, readTablePage, recordCapturedMail, recordChangedKeys, recordFanoutPass, recordQueueMessages, recordSchemaVersion, relationHooks, relayCountFor, renderSql, reprojectableFields, reprojectionMigrationId, reprojectionTables, resolveRankPartition, resolveRelationPredicates, resolveWith, rowToDocument, runDataMigration, runDrizzle, runExternalSourceTick, runReadonlySql, runRowValidators, runShardMigrations, runSocketPool, runSql, runTriggers, selectExpiredIds, selectExportTables, selectIndexForAggregate, selectIndexForCount, selectIndexForGroupBy, selectMatchingIds, selectShapeMemberIds, selectShapeRows, serializeSqlValue, shapeRoutingKey, softDeleteScope, sortColumnName, sqliteInList, stableStringify, stableWireKey, subscriptionFrames, subscriptionListDeltas, summarizeFanoutTopics, summarizeSubscriptions, tableColumns, tableFromDepKey, throwingScheduler, trimCdcChanges, trimIdempotent, trimStreamRuns, tryRowToDocument, trySendFrame, unionAll, validateImportRow, writeGlobalShapeSnapshot, writeIdempotent, writeSearchBackfillState, writeShapePokeCursor, writeTouchesMemo };
|
package/dist/index.d.ts
CHANGED
|
@@ -932,6 +932,12 @@ interface RankPageComputation {
|
|
|
932
932
|
}
|
|
933
933
|
declare const hydrateDocsById: (deps: RankPageDeps, tableName: string, ids: ReadonlyArray<string>) => Map<string, Record<string, unknown>>;
|
|
934
934
|
declare const computeRankPage: (deps: RankPageDeps, tableName: string, indexName: string, rankPageOptions: RankPageOptions) => RankPageComputation;
|
|
935
|
+
declare const SHAPE_POKE_CURSOR_TABLE = "__shape_poke_cursor";
|
|
936
|
+
declare const migrateShapePokeCursor: (sql: SqlExec) => void;
|
|
937
|
+
declare const readShapePokeCursor: (sql: SqlExec, connectionId: string, subId: string) => number | undefined;
|
|
938
|
+
declare const writeShapePokeCursor: (sql: SqlExec, connectionId: string, subId: string, cursor: number) => void;
|
|
939
|
+
declare const deleteShapePokeCursor: (sql: SqlExec, connectionId: string, subId: string) => void;
|
|
940
|
+
declare const deleteShapePokeCursorsForConnection: (sql: SqlExec, connectionId: string) => void;
|
|
935
941
|
declare const DATA_MIGRATION_STATE_TABLE = "__lunora_migrations";
|
|
936
942
|
type MigrationDirection = "down" | "up";
|
|
937
943
|
type MigrationStatus = "completed" | "failed" | "in_progress";
|
|
@@ -2138,4 +2144,4 @@ interface WhereSqlStrategy {
|
|
|
2138
2144
|
}
|
|
2139
2145
|
declare const literalInList: (reference: SQL, items: ReadonlyArray<unknown>, negated: boolean) => SQL;
|
|
2140
2146
|
declare const compileWhereSql: (where: WhereInput | undefined, strategy: WhereSqlStrategy) => SQL | undefined;
|
|
2141
|
-
export { ADMIN_FUNCTIONS, ADMIN_FUNCTION_PREFIX, AGGREGATE_SQL_FUNCTION, AGG_COUNT, AGG_KEY, AGG_VALUE, AUDIT_LOG_TABLE, type AdvisorProcedure, type AdvisorProceduresResult, type AdvisoriesResult, type AdvisoryFinding, type AggregateIndexDefinitionLike, type AggregateOp, type AggregateOptions, type AggregateResult, type AggregateTally, type AppendAuditEntry, type ApplyOnDeleteOptions$1 as ApplyOnDeleteOptions, type AuditEntry, type AuditLogResult, type BroadcastDelta, CDC_LOG_TABLE, CDC_META_TABLE, CLIENT_WATERMARK_TABLE, type CacheEntry, type CapturedMailRow, type CdcChange, type ChangedKeys, type Clock, type ColumnMeta, type ColumnMetaLike, type CompanionSync, type CompanionSyncDeps, ConflictError, type ConflictKind, type CountArgs, CountRlsUnsupportedError, type CreateWorkflowInstanceResult, type CrossShardReadArgs, type CtxDbOptions, DATA_MIGRATION_STATE_TABLE, DEFAULT_FANOUT_TOPIC_LIMIT, DEFAULT_MAX_RELATION_KEYS, DEFAULT_MAX_RELAYS, DEFAULT_PROMOTION_THRESHOLDS, DEFAULT_TRANSACTION_LIMITS, DOC_COLUMN, type DataMigrationDocument, type DataMigrationLike, type DataMigrationTransform, type DatabaseWriterLike, type DependencyTracker, type DeployInfo, type DurableAttachDecision, type DurableStreamAttach, type DurableStreamRun, DurableStreamRunner, type DurableStreamSink, type ExportRow, type ExportShardAdminArgs, type ExportShardArgs, type ExternalSourceDiffResult, type ExternalSourceLike, FLAGS_FUNCTION_PREFIX, type FacetColumnOptions, type FacetColumnResult, type FacetValue, type FanoutMetricsResult, type FanoutPathCounters, type FanoutTopicStat, type FieldOperators, type FilterClause, type FilterOperator, type FlagEvaluation, type FlagsResult, type FunctionCallStat, type FunctionScanAttribution, type FunctionStatsResult, GEO_DEFAULT_PRECISION, GLOBAL_SHAPE_SNAPSHOT_TABLE, type GeoBoundingBox, type GeoFilterBuilderLike, type GeoIndexDefinitionLike, type GeoPoint, type GeoScoredDocument, type GroupByEntry, type GroupByOptions, type GuardableSchema$1 as GuardableSchema, IDEMPOTENCY_TABLE, type IdGenerator, type IdempotentRecord, type ImportError, type ImportShardAdminArgs, type ImportShardArgs, type ImportShardResult, type IncrementalMaterializeResult, type IndexDefinitionLike, type IndexKeyEntry, type IndexRangeBuilderLike, type KeyRange, type LifecycleDispatchInfo, type LifecycleEvent, MAIL_RETENTION, MAIL_TABLE, MAX_DURABLE_STREAM_BYTES, MAX_DURABLE_STREAM_CHUNKS, MAX_PAGE_SIZE, MAX_SQL_ROWS, type MaskColumnMetadata, type MaskPoliciesResult, type MaterializeResult, type MigrationDirection, type MigrationRunResult, type MigrationStatus, type MigrationStatusRow, type MutationDelta, type NestedWith, NotFoundError, NotUniqueError, type OnDeleteActionLike, type OrderByClause, type OrderByInput, type OrderKey, OwnerRelay, type OwnerRelayFrame, type PaginationOptions, type PitrBookmarkResult, type PitrRestoreArgs, type PitrRestoreResult, type PitrStorage, type PokeFrameMeta, type PromotionState, type PromotionThresholds, QUEUE_TABLE, type QueryArgs, type QueryPage, type QueueMessageOutcome, type QueueMessageRow, type QueueMetadata, type QueuesResult, RANK_TIEBREAK, RELATION_EXISTS_KEY, RELATION_FUNCTION_PREFIX, REPROJECTION_MIGRATION_PREFIX, RLS_UNWRAP_SYMBOL, type RankBeforeOptions, type RankBeforeResult, type RankDirection, type RankIndexDefinitionLike, type RankOptions, type RankPage, type RankPageComputation, type RankPageDeps, type RankPageOptions, type RankPageRow, type RankPageRowKey, type RankResult, type RankSortKeyLike, ReactiveCache, type ReactiveCacheOptions, type ReadFootprint, type ReadHook, type ReadTablePageOptions, type RecordMailInput, type RecordQueueMessageInput, type RelationDefinitionLike, type RelationExistsMarker, type RelayAttach, type RelayDetach, type RelayFrame, type RelayHost, RelayMember, type RelayShapePoke, type RelayShapeSeed, type RelayShapeSubscribe, type RenderedSql, type ReplicaFollowerHost, type ReplicaOwnerHost, type ReplicaReadiness, type ResolveRelationPredicatesOptions, type ResolveWithOptions, type ResolveWithResult, type ResolvedShape, type RestrictableQueryOptions, type RlsPoliciesResult, type RlsPolicyMetadata, RlsRequiredError, type RlsRoleMetadata, type RpcRequest, type RunDataMigrationOptions, type RunTriggersOptions, SCAN_DEP, SCHEMA_HISTORY_MAX_VERSIONS, SEARCH_STATE_TABLE, type SchedulableWorkflowReferenceLike, type ScheduledFunctionDoc, type SchedulerLike, type SchemaLike, type ScoredDocument, type SearchFilterBuilderLike, type SearchIndexDefinitionLike, type SearchScoredDocument, type SelectMatchingIdsOptions, type ServerDefaultContextLike, type SettingEntry, type SettingKind, type SettingsResult, type ShapePokePart, type ShapeRow, type ShapeRowOp, type ShapeSubscriptionQuery, type ShardRankPageResult, ShardRunner, type ShardRunnerOptions, type ShardSiblingHost, type ShardSocketLike, type SocketAttachment, type SortDirection, type SourceClientLike, type SourceCursorLike, type SourceRefresh, type SqlConsoleResult, type SqlCursor, type SqlEngine, type SqlExec, type SqlLintResult, type StorageMetadata, type StorageReference, type StorageReferenceResult, type StorageRuleMetadata, type StorageRulesResult, type StudioFeaturesResult, type SubscriptionConnection, type SubscriptionEnvelope, type SubscriptionIdentity, type SubscriptionInfo, type SubscriptionQuery, type SubscriptionReadFootprint, type SubscriptionsResult, type SystemDatabaseReader, type SystemDoc, type SystemQuery, type SystemReaderOptions, type SystemReaderSchedulerLike, type SystemReaderStorageLike, type SystemTableName, type TableColumnsResult, type TableDefinitionLike, type TableIndexInfo, type TableIndexesResult, type TableInfo, type TablePage, type TableReaderLike, type TablesColumnsResult, type TablesIndexesResult, type TransactionHeadroom, TransactionHeadroomTracker, type TransactionLimits, type TransactionSqlLike, type TriggerContextLike, type TriggerDefinitionLike, type TriggerEventLike, type TriggerOpLike, type TriggerTimingLike, type TtlSweepSpec, type ValidatorLike, type WhereInput, type WhereSqlStrategy, type WithInput, type WorkflowInstanceState, type WorkflowInstanceStatusResult, type WorkflowMetadata, type WorkflowsResult, type WriteEvent, type WriteHook, advanceClientWatermark, aggUpsertSql, aggregateSqlFunction, aggregateTableName, appendAuditEntry, appendCdcChange, appendStreamChunk, applyCdcChanges, applyOnDelete, applySelect, armRestore, assertFlatPredicate, assertReadonly, assertShapeShardable, assertValidClientId, awaitWsDrain, backfillAggregateIndexes, backfillRankIndexes, backfillSearchIndexes, backfillSearchIndexesForTable, boundingBoxCenter, boundingBoxGeohashes, buildIndexRange, buildPokeFrames, buildReprojectionMigration, buildSeekBeforeWhere, buildSeekWhere, buildSettings, bumpCdcEpoch, claimStreamRun, clampPromotionThresholds, clearCapturedMail, clearQueueMessages, coerceAggregateNumber, compileWhereSql, computeRankPage, containsRelationPredicate, countLegacyRows, coveringGeohashes, createCompanionSync, createDependencyTracker, createFanoutCounters, createIndexSql, createReadFootprint, createRelayLink, createReplicaLink, createShardCtxDb, createSystemReader, decideDurableAttach, decodeCursor, deleteGlobalShapeSnapshot, deleteGlobalShapeSnapshotsForConnection, deleteStreamRun, depKey, diffExternalSource, diffGlobalMembership, distinctValues, encodeAggregateKey, encodeCursor, encodeGeohash, encodePartitionKey, encodeRowsPatch, ensureAuditTable, ensureMailTable, exportShardRows, exportShardTable, facetColumn, fanOutScalarCounts, findStorageReferences, finishStreamRun, foldAggregateTally, gateReplicaDispatch, geoTableName, guardWriter, handleReplicaControl, hasTrigger, haversineMeters, hydrateDocsById, importShardRows, indexKeysForRow, isDevEnvironment, isFtsAvailable, isLossyBody, isRelationPredicate, isSoftDeleted, isSourceDue, jsonPath, jsonPathSql, keysTouchRanges, liftSourceId, lintReadonlySql, listTables, literalInList, matchesRankStaticWhere, matchesStaticWhere, materializeExternalRows, materializeExternalRowsIncremental, mergeChangedKeys, mergeWhere, migrateCdcLog, migrateCdcMeta, migrateClientWatermark, migrateDurableStreams, migrateGlobalShapeSnapshot, migrateIdempotency, migrateSearchState, minCdcSeq, nextPromotionState, normalizeCountArgument, normalizeIdStructurally, normalizeOrderKeys, normalizeSourceDocument, normalizeSourceValue, param, parseExportShardArgs, parseImportShardArgs, planAggregateLookup, pointInBoundingBox, projectColumns, pullExternalSourceIncrementalTick, pullExternalSourceTick, qualifiedJsonPath, qualifiedJsonPathSql, quoteIdentifier, rankKeyFromDocument as rankKeyFromDoc, rankTableName, reactiveCacheKey, readAggregateValue, readAuditLog, readBookmark, readCapturedMail, readCdcChanges, readCdcCursor, readCdcEpoch, readClientWatermark, readExternalSourceBaseline, readGlobalShapeSnapshot, readIdempotent, readMigrationStatus, readQueueMessageById, readQueueMessages, readSchemaHistory, readSchemaVersion, readSearchBackfillState, readStreamChunks, readStreamRun, readTablePage, recordCapturedMail, recordChangedKeys, recordFanoutPass, recordQueueMessages, recordSchemaVersion, relationHooks, relayCountFor, renderSql, reprojectableFields, reprojectionMigrationId, reprojectionTables, resolveRankPartition, resolveRelationPredicates, resolveWith, rowToDocument, runDataMigration, runDrizzle, runExternalSourceTick, runReadonlySql, runRowValidators, runShardMigrations, runSocketPool, runSql, runTriggers, selectExpiredIds, selectExportTables, selectIndexForAggregate, selectIndexForCount, selectIndexForGroupBy, selectMatchingIds, selectShapeMemberIds, selectShapeRows, serializeSqlValue, shapeRoutingKey, softDeleteScope, sortColumnName, sqliteInList, stableStringify, stableWireKey, subscriptionFrames, subscriptionListDeltas, summarizeFanoutTopics, summarizeSubscriptions, tableColumns, tableFromDepKey, throwingScheduler, trimCdcChanges, trimIdempotent, trimStreamRuns, tryRowToDocument, trySendFrame, unionAll, validateImportRow, writeGlobalShapeSnapshot, writeIdempotent, writeSearchBackfillState, writeTouchesMemo };
|
|
2147
|
+
export { ADMIN_FUNCTIONS, ADMIN_FUNCTION_PREFIX, AGGREGATE_SQL_FUNCTION, AGG_COUNT, AGG_KEY, AGG_VALUE, AUDIT_LOG_TABLE, type AdvisorProcedure, type AdvisorProceduresResult, type AdvisoriesResult, type AdvisoryFinding, type AggregateIndexDefinitionLike, type AggregateOp, type AggregateOptions, type AggregateResult, type AggregateTally, type AppendAuditEntry, type ApplyOnDeleteOptions$1 as ApplyOnDeleteOptions, type AuditEntry, type AuditLogResult, type BroadcastDelta, CDC_LOG_TABLE, CDC_META_TABLE, CLIENT_WATERMARK_TABLE, type CacheEntry, type CapturedMailRow, type CdcChange, type ChangedKeys, type Clock, type ColumnMeta, type ColumnMetaLike, type CompanionSync, type CompanionSyncDeps, ConflictError, type ConflictKind, type CountArgs, CountRlsUnsupportedError, type CreateWorkflowInstanceResult, type CrossShardReadArgs, type CtxDbOptions, DATA_MIGRATION_STATE_TABLE, DEFAULT_FANOUT_TOPIC_LIMIT, DEFAULT_MAX_RELATION_KEYS, DEFAULT_MAX_RELAYS, DEFAULT_PROMOTION_THRESHOLDS, DEFAULT_TRANSACTION_LIMITS, DOC_COLUMN, type DataMigrationDocument, type DataMigrationLike, type DataMigrationTransform, type DatabaseWriterLike, type DependencyTracker, type DeployInfo, type DurableAttachDecision, type DurableStreamAttach, type DurableStreamRun, DurableStreamRunner, type DurableStreamSink, type ExportRow, type ExportShardAdminArgs, type ExportShardArgs, type ExternalSourceDiffResult, type ExternalSourceLike, FLAGS_FUNCTION_PREFIX, type FacetColumnOptions, type FacetColumnResult, type FacetValue, type FanoutMetricsResult, type FanoutPathCounters, type FanoutTopicStat, type FieldOperators, type FilterClause, type FilterOperator, type FlagEvaluation, type FlagsResult, type FunctionCallStat, type FunctionScanAttribution, type FunctionStatsResult, GEO_DEFAULT_PRECISION, GLOBAL_SHAPE_SNAPSHOT_TABLE, type GeoBoundingBox, type GeoFilterBuilderLike, type GeoIndexDefinitionLike, type GeoPoint, type GeoScoredDocument, type GroupByEntry, type GroupByOptions, type GuardableSchema$1 as GuardableSchema, IDEMPOTENCY_TABLE, type IdGenerator, type IdempotentRecord, type ImportError, type ImportShardAdminArgs, type ImportShardArgs, type ImportShardResult, type IncrementalMaterializeResult, type IndexDefinitionLike, type IndexKeyEntry, type IndexRangeBuilderLike, type KeyRange, type LifecycleDispatchInfo, type LifecycleEvent, MAIL_RETENTION, MAIL_TABLE, MAX_DURABLE_STREAM_BYTES, MAX_DURABLE_STREAM_CHUNKS, MAX_PAGE_SIZE, MAX_SQL_ROWS, type MaskColumnMetadata, type MaskPoliciesResult, type MaterializeResult, type MigrationDirection, type MigrationRunResult, type MigrationStatus, type MigrationStatusRow, type MutationDelta, type NestedWith, NotFoundError, NotUniqueError, type OnDeleteActionLike, type OrderByClause, type OrderByInput, type OrderKey, OwnerRelay, type OwnerRelayFrame, type PaginationOptions, type PitrBookmarkResult, type PitrRestoreArgs, type PitrRestoreResult, type PitrStorage, type PokeFrameMeta, type PromotionState, type PromotionThresholds, QUEUE_TABLE, type QueryArgs, type QueryPage, type QueueMessageOutcome, type QueueMessageRow, type QueueMetadata, type QueuesResult, RANK_TIEBREAK, RELATION_EXISTS_KEY, RELATION_FUNCTION_PREFIX, REPROJECTION_MIGRATION_PREFIX, RLS_UNWRAP_SYMBOL, type RankBeforeOptions, type RankBeforeResult, type RankDirection, type RankIndexDefinitionLike, type RankOptions, type RankPage, type RankPageComputation, type RankPageDeps, type RankPageOptions, type RankPageRow, type RankPageRowKey, type RankResult, type RankSortKeyLike, ReactiveCache, type ReactiveCacheOptions, type ReadFootprint, type ReadHook, type ReadTablePageOptions, type RecordMailInput, type RecordQueueMessageInput, type RelationDefinitionLike, type RelationExistsMarker, type RelayAttach, type RelayDetach, type RelayFrame, type RelayHost, RelayMember, type RelayShapePoke, type RelayShapeSeed, type RelayShapeSubscribe, type RenderedSql, type ReplicaFollowerHost, type ReplicaOwnerHost, type ReplicaReadiness, type ResolveRelationPredicatesOptions, type ResolveWithOptions, type ResolveWithResult, type ResolvedShape, type RestrictableQueryOptions, type RlsPoliciesResult, type RlsPolicyMetadata, RlsRequiredError, type RlsRoleMetadata, type RpcRequest, type RunDataMigrationOptions, type RunTriggersOptions, SCAN_DEP, SCHEMA_HISTORY_MAX_VERSIONS, SEARCH_STATE_TABLE, SHAPE_POKE_CURSOR_TABLE, type SchedulableWorkflowReferenceLike, type ScheduledFunctionDoc, type SchedulerLike, type SchemaLike, type ScoredDocument, type SearchFilterBuilderLike, type SearchIndexDefinitionLike, type SearchScoredDocument, type SelectMatchingIdsOptions, type ServerDefaultContextLike, type SettingEntry, type SettingKind, type SettingsResult, type ShapePokePart, type ShapeRow, type ShapeRowOp, type ShapeSubscriptionQuery, type ShardRankPageResult, ShardRunner, type ShardRunnerOptions, type ShardSiblingHost, type ShardSocketLike, type SocketAttachment, type SortDirection, type SourceClientLike, type SourceCursorLike, type SourceRefresh, type SqlConsoleResult, type SqlCursor, type SqlEngine, type SqlExec, type SqlLintResult, type StorageMetadata, type StorageReference, type StorageReferenceResult, type StorageRuleMetadata, type StorageRulesResult, type StudioFeaturesResult, type SubscriptionConnection, type SubscriptionEnvelope, type SubscriptionIdentity, type SubscriptionInfo, type SubscriptionQuery, type SubscriptionReadFootprint, type SubscriptionsResult, type SystemDatabaseReader, type SystemDoc, type SystemQuery, type SystemReaderOptions, type SystemReaderSchedulerLike, type SystemReaderStorageLike, type SystemTableName, type TableColumnsResult, type TableDefinitionLike, type TableIndexInfo, type TableIndexesResult, type TableInfo, type TablePage, type TableReaderLike, type TablesColumnsResult, type TablesIndexesResult, type TransactionHeadroom, TransactionHeadroomTracker, type TransactionLimits, type TransactionSqlLike, type TriggerContextLike, type TriggerDefinitionLike, type TriggerEventLike, type TriggerOpLike, type TriggerTimingLike, type TtlSweepSpec, type ValidatorLike, type WhereInput, type WhereSqlStrategy, type WithInput, type WorkflowInstanceState, type WorkflowInstanceStatusResult, type WorkflowMetadata, type WorkflowsResult, type WriteEvent, type WriteHook, advanceClientWatermark, aggUpsertSql, aggregateSqlFunction, aggregateTableName, appendAuditEntry, appendCdcChange, appendStreamChunk, applyCdcChanges, applyOnDelete, applySelect, armRestore, assertFlatPredicate, assertReadonly, assertShapeShardable, assertValidClientId, awaitWsDrain, backfillAggregateIndexes, backfillRankIndexes, backfillSearchIndexes, backfillSearchIndexesForTable, boundingBoxCenter, boundingBoxGeohashes, buildIndexRange, buildPokeFrames, buildReprojectionMigration, buildSeekBeforeWhere, buildSeekWhere, buildSettings, bumpCdcEpoch, claimStreamRun, clampPromotionThresholds, clearCapturedMail, clearQueueMessages, coerceAggregateNumber, compileWhereSql, computeRankPage, containsRelationPredicate, countLegacyRows, coveringGeohashes, createCompanionSync, createDependencyTracker, createFanoutCounters, createIndexSql, createReadFootprint, createRelayLink, createReplicaLink, createShardCtxDb, createSystemReader, decideDurableAttach, decodeCursor, deleteGlobalShapeSnapshot, deleteGlobalShapeSnapshotsForConnection, deleteShapePokeCursor, deleteShapePokeCursorsForConnection, deleteStreamRun, depKey, diffExternalSource, diffGlobalMembership, distinctValues, encodeAggregateKey, encodeCursor, encodeGeohash, encodePartitionKey, encodeRowsPatch, ensureAuditTable, ensureMailTable, exportShardRows, exportShardTable, facetColumn, fanOutScalarCounts, findStorageReferences, finishStreamRun, foldAggregateTally, gateReplicaDispatch, geoTableName, guardWriter, handleReplicaControl, hasTrigger, haversineMeters, hydrateDocsById, importShardRows, indexKeysForRow, isDevEnvironment, isFtsAvailable, isLossyBody, isRelationPredicate, isSoftDeleted, isSourceDue, jsonPath, jsonPathSql, keysTouchRanges, liftSourceId, lintReadonlySql, listTables, literalInList, matchesRankStaticWhere, matchesStaticWhere, materializeExternalRows, materializeExternalRowsIncremental, mergeChangedKeys, mergeWhere, migrateCdcLog, migrateCdcMeta, migrateClientWatermark, migrateDurableStreams, migrateGlobalShapeSnapshot, migrateIdempotency, migrateSearchState, migrateShapePokeCursor, minCdcSeq, nextPromotionState, normalizeCountArgument, normalizeIdStructurally, normalizeOrderKeys, normalizeSourceDocument, normalizeSourceValue, param, parseExportShardArgs, parseImportShardArgs, planAggregateLookup, pointInBoundingBox, projectColumns, pullExternalSourceIncrementalTick, pullExternalSourceTick, qualifiedJsonPath, qualifiedJsonPathSql, quoteIdentifier, rankKeyFromDocument as rankKeyFromDoc, rankTableName, reactiveCacheKey, readAggregateValue, readAuditLog, readBookmark, readCapturedMail, readCdcChanges, readCdcCursor, readCdcEpoch, readClientWatermark, readExternalSourceBaseline, readGlobalShapeSnapshot, readIdempotent, readMigrationStatus, readQueueMessageById, readQueueMessages, readSchemaHistory, readSchemaVersion, readSearchBackfillState, readShapePokeCursor, readStreamChunks, readStreamRun, readTablePage, recordCapturedMail, recordChangedKeys, recordFanoutPass, recordQueueMessages, recordSchemaVersion, relationHooks, relayCountFor, renderSql, reprojectableFields, reprojectionMigrationId, reprojectionTables, resolveRankPartition, resolveRelationPredicates, resolveWith, rowToDocument, runDataMigration, runDrizzle, runExternalSourceTick, runReadonlySql, runRowValidators, runShardMigrations, runSocketPool, runSql, runTriggers, selectExpiredIds, selectExportTables, selectIndexForAggregate, selectIndexForCount, selectIndexForGroupBy, selectMatchingIds, selectShapeMemberIds, selectShapeRows, serializeSqlValue, shapeRoutingKey, softDeleteScope, sortColumnName, sqliteInList, stableStringify, stableWireKey, subscriptionFrames, subscriptionListDeltas, summarizeFanoutTopics, summarizeSubscriptions, tableColumns, tableFromDepKey, throwingScheduler, trimCdcChanges, trimIdempotent, trimStreamRuns, tryRowToDocument, trySendFrame, unionAll, validateImportRow, writeGlobalShapeSnapshot, writeIdempotent, writeSearchBackfillState, writeShapePokeCursor, writeTouchesMemo };
|
package/dist/index.mjs
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{exportShardRows as o,exportShardTable as a,importShardRows as t,parseExportShardArgs as n,parseImportShardArgs as l,selectExportTables as s,validateImportRow as i}from"./packem_shared/exportShardRows-Bbi_JGfn.mjs";import{AGGREGATE_SQL_FUNCTION as p,aggregateSqlFunction as d,matchesStaticWhere as c,normalizeCountArgument as S,throwingScheduler as u}from"./packem_shared/AGGREGATE_SQL_FUNCTION-CTo0-9iZ.mjs";import{aggregateTableName as f,coerceAggregateNumber as T,encodeAggregateKey as A,foldAggregateTally as E,readAggregateValue as g}from"./packem_shared/aggregateTableName-DN7gk6uh.mjs";import{CountRlsUnsupportedError as R,mergeWhere as I,planAggregateLookup as C,selectIndexForAggregate as _,selectIndexForCount as L,selectIndexForGroupBy as b}from"./packem_shared/CountRlsUnsupportedError-8BqPYQoP.mjs";import{AUDIT_LOG_TABLE as N,appendAuditEntry as y,ensureAuditTable as D,readAuditLog as O}from"./packem_shared/AUDIT_LOG_TABLE-Bl2mYtAQ.mjs";import{NotUniqueError as k,assertValidClientId as P,createShardCtxDb as B,normalizeIdStructurally as G}from"./packem_shared/NotUniqueError-DYo7r67J.mjs";import{backfillAggregateIndexes as w,backfillRankIndexes as K,backfillSearchIndexes as q,backfillSearchIndexesForTable as W}from"./packem_shared/backfillAggregateIndexes-DTOIsYbi.mjs";import{CDC_LOG_TABLE as z,CDC_META_TABLE as X,appendCdcChange as H,applyCdcChanges as V,bumpCdcEpoch as Y,migrateCdcLog as j,migrateCdcMeta as Q,minCdcSeq as J,readCdcChanges as Z,readCdcCursor as $,readCdcEpoch as ee,trimCdcChanges as re}from"./packem_shared/CDC_LOG_TABLE-DNFFQwF_.mjs";import{CLIENT_WATERMARK_TABLE as ae,advanceClientWatermark as te,migrateClientWatermark as ne,readClientWatermark as le}from"./packem_shared/CLIENT_WATERMARK_TABLE-LrKfdxyt.mjs";import{S as ie}from"./packem_shared/ctx-db-companions-BJlCofon.mjs";import{GLOBAL_SHAPE_SNAPSHOT_TABLE as pe,deleteGlobalShapeSnapshot as de,deleteGlobalShapeSnapshotsForConnection as ce,migrateGlobalShapeSnapshot as Se,readGlobalShapeSnapshot as ue,writeGlobalShapeSnapshot as xe}from"./packem_shared/GLOBAL_SHAPE_SNAPSHOT_TABLE-B2LKe4KU.mjs";import{IDEMPOTENCY_TABLE as Te,migrateIdempotency as Ae,readIdempotent as Ee,trimIdempotent as ge,writeIdempotent as he}from"./packem_shared/IDEMPOTENCY_TABLE-tQ5mnqvw.mjs";import{computeRankPage as Ie,hydrateDocsById as Ce}from"./packem_shared/computeRankPage-BU8LXvQs.mjs";import{SEARCH_STATE_TABLE as Le,migrateSearchState as be,readSearchBackfillState as Me,writeSearchBackfillState as Ne}from"./packem_shared/SEARCH_STATE_TABLE-DRk_SB72.mjs";import{selectShapeMemberIds as De,selectShapeRows as Oe}from"./packem_shared/selectShapeMemberIds-Bkkug6vU.mjs";import{DATA_MIGRATION_STATE_TABLE as ke,readMigrationStatus as Pe,runDataMigration as Be}from"./packem_shared/DATA_MIGRATION_STATE_TABLE-DIQTu___.mjs";import{SCAN_DEP as Ue,createDependencyTracker as we,depKey as Ke,tableFromDepKey as qe}from"./packem_shared/SCAN_DEP-D_yR9EeV.mjs";import{runDrizzle as ve,runSql as ze}from"./packem_shared/runDrizzle-C3n5gJsk.mjs";import{T as He,c as Ve,p as Ye,a as je,A as Qe,y as Je,h as Ze,C as $e,_ as er,N as rr,S as or,O as ar,E as tr,I as nr,D as lr}from"./packem_shared/do-sql-DKSFK627.mjs";import{param as ir,renderSql as mr,sqliteInList as pr,unionAll as dr}from"./packem_shared/param-CYxL68V-.mjs";import{appendStreamChunk as Sr,claimStreamRun as ur,deleteStreamRun as xr,finishStreamRun as fr,migrateDurableStreams as Tr,readStreamChunks as Ar,readStreamRun as Er,trimStreamRuns as gr}from"./packem_shared/appendStreamChunk-ksZYy1hZ.mjs";import{DurableStreamRunner as Rr,MAX_DURABLE_STREAM_BYTES as Ir,MAX_DURABLE_STREAM_CHUNKS as Cr,decideDurableAttach as _r}from"./packem_shared/DurableStreamRunner-B54Jt9Iu.mjs";import{diffExternalSource as br}from"./packem_shared/diffExternalSource-DMpkJta1.mjs";import{liftSourceId as Nr,normalizeSourceDocument as yr,normalizeSourceValue as Dr}from"./packem_shared/liftSourceId-DApAbu7Q.mjs";import{materializeExternalRows as Fr,materializeExternalRowsIncremental as kr,readExternalSourceBaseline as Pr,runExternalSourceTick as Br}from"./packem_shared/materializeExternalRows-C-5TKdc1.mjs";import{isSoftDeleted as Ur,isSourceDue as wr,pullExternalSourceIncrementalTick as Kr,pullExternalSourceTick as qr}from"./packem_shared/isSoftDeleted-DyEJueIu.mjs";import{GEO_DEFAULT_PRECISION as vr,boundingBoxCenter as zr,boundingBoxGeohashes as Xr,coveringGeohashes as Hr,encodeGeohash as Vr,haversineMeters as Yr,pointInBoundingBox as jr}from"./packem_shared/GEO_DEFAULT_PRECISION-DyI5zggj.mjs";import{ADMIN_FUNCTIONS as Jr,ADMIN_FUNCTION_PREFIX as Zr,DEFAULT_FANOUT_TOPIC_LIMIT as $r,FLAGS_FUNCTION_PREFIX as eo,MAX_PAGE_SIZE as ro,RELATION_FUNCTION_PREFIX as oo,createFanoutCounters as ao,facetColumn as to,findStorageReferences as no,listTables as lo,readTablePage as so,recordFanoutPass as io,selectMatchingIds as mo,summarizeFanoutTopics as po,summarizeSubscriptions as co}from"./packem_shared/ADMIN_FUNCTIONS-Cj1pJjVg.mjs";import{MAIL_RETENTION as uo,MAIL_TABLE as xo,clearCapturedMail as fo,ensureMailTable as To,readCapturedMail as Ao,recordCapturedMail as Eo}from"./packem_shared/MAIL_RETENTION-CzZuX9bd.mjs";import{NotFoundError as ho}from"./packem_shared/NotFoundError-BhF7FeFr.mjs";import{armRestore as Io,readBookmark as Co}from"./packem_shared/armRestore-BNzdvQ_o.mjs";import{applySelect as Lo,buildSeekBeforeWhere as bo,buildSeekWhere as Mo,decodeCursor as No,encodeCursor as yo,normalizeOrderKeys as Do,softDeleteScope as Oo}from"./packem_shared/applySelect-5w13bMAR.mjs";import{QUEUE_TABLE as ko,clearQueueMessages as Po,isLossyBody as Bo,readQueueMessageById as Go,readQueueMessages as Uo,recordQueueMessages as wo}from"./packem_shared/QUEUE_TABLE-BX0nopuT.mjs";import{RANK_TIEBREAK as qo,encodePartitionKey as Wo,matchesRankStaticWhere as vo,rankKeyFromDoc as zo,rankTableName as Xo,resolveRankPartition as Ho,sortColumnName as Vo}from"./packem_shared/RANK_TIEBREAK-BGk411OR.mjs";import{ReactiveCache as jo,reactiveCacheKey as Qo}from"./packem_shared/ReactiveCache-D_T10KLy.mjs";import{createReadFootprint as Zo}from"./packem_shared/createReadFootprint-DIrrxRTE.mjs";import{buildIndexRange as ea,indexKeysForRow as ra,keysTouchRanges as oa}from"./packem_shared/buildIndexRange-DFsdtPjD.mjs";import{DEFAULT_MAX_RELATION_KEYS as ta,assertFlatPredicate as na,assertShapeShardable as la,containsRelationPredicate as sa,isRelationPredicate as ia,resolveRelationPredicates as ma}from"./packem_shared/DEFAULT_MAX_RELATION_KEYS-BV1RCoat.mjs";import{applyOnDelete as da,distinctValues as ca,fanOutScalarCounts as Sa,relationHooks as ua,resolveWith as xa,runRowValidators as fa}from"./packem_shared/applyOnDelete-crbAzVfE.mjs";import{DEFAULT_PROMOTION_THRESHOLDS as Aa,clampPromotionThresholds as Ea,nextPromotionState as ga,relayCountFor as ha,shapeRoutingKey as Ra}from"./packem_shared/DEFAULT_PROMOTION_THRESHOLDS-DYGNAo1I.mjs";import{DEFAULT_MAX_RELAYS as Ca,OwnerRelay as _a,RelayMember as La,createRelayLink as ba}from"./packem_shared/DEFAULT_MAX_RELAYS-Cinp9pPC.mjs";import{createReplicaLink as Na,gateReplicaDispatch as ya,handleReplicaControl as Da}from"./packem_shared/createReplicaLink-BMNW0SX6.mjs";import{buildReprojectionMigration as Fa,countLegacyRows as ka,reprojectableFields as Pa,reprojectionTables as Ba}from"./packem_shared/buildReprojectionMigration-JUwsTNTB.mjs";import{RLS_UNWRAP_SYMBOL as Ua,RlsRequiredError as wa,guardWriter as Ka}from"./packem_shared/RLS_UNWRAP_SYMBOL-DcqORh2s.mjs";import{SCHEMA_HISTORY_MAX_VERSIONS as Wa,readSchemaHistory as va,readSchemaVersion as za,recordSchemaVersion as Xa}from"./packem_shared/SCHEMA_HISTORY_MAX_VERSIONS-CEK7b_7v.mjs";import{serializeSqlValue as Va}from"./packem_shared/serializeSqlValue-BR4UOWoP.mjs";import{buildSettings as ja,isDevEnvironment as Qa}from"./packem_shared/buildSettings-COIJsw7a.mjs";import{buildPokeFrames as Za,diffGlobalMembership as $a,encodeRowsPatch as et,projectColumns as rt}from"./packem_shared/buildPokeFrames-DmB-FBeQ.mjs";import{ShardRunner as at}from"./packem_shared/ShardRunner-DIqVdWtk.mjs";import{runSocketPool as nt}from"./packem_shared/runSocketPool-DPQLVyWF.mjs";import{MAX_SQL_ROWS as st,assertReadonly as it,lintReadonlySql as mt,runReadonlySql as pt}from"./packem_shared/MAX_SQL_ROWS-nMwkxv5f.mjs";import{awaitWsDrain as ct,subscriptionFrames as St,subscriptionListDeltas as ut,trySendFrame as xt}from"./packem_shared/awaitWsDrain-PT9o0d6J.mjs";import{mergeChangedKeys as Tt,recordChangedKeys as At,writeTouchesMemo as Et}from"./packem_shared/mergeChangedKeys-BXtUgIPW.mjs";import{createSystemReader as ht}from"./packem_shared/createSystemReader-DcDcrtM3.mjs";import{ConflictError as It}from"./packem_shared/ConflictError-C8GtJmjS.mjs";import{DEFAULT_TRANSACTION_LIMITS as _t,TransactionHeadroomTracker as Lt}from"./packem_shared/DEFAULT_TRANSACTION_LIMITS-DLUzZbta.mjs";import{hasTrigger as Mt,runTriggers as Nt}from"./packem_shared/hasTrigger-CbkOHExZ.mjs";import{selectExpiredIds as Dt}from"./packem_shared/selectExpiredIds-C4Ry_NxG.mjs";import{compileWhereSql as Ft,literalInList as kt}from"./packem_shared/compileWhereSql-B3hq_v98.mjs";import{RELATION_EXISTS_KEY as Bt}from"./packem_shared/RELATION_EXISTS_KEY-BaqSIFU1.mjs";import{REPROJECTION_MIGRATION_PREFIX as Ut,reprojectionMigrationId as wt}from"./packem_shared/REPROJECTION_MIGRATION_PREFIX-D2dltRFC.mjs";import{quoteIdentifier as qt}from"./packem_shared/quoteIdentifier-CObIFRhb.mjs";import{runShardMigrations as vt}from"./packem_shared/runShardMigrations-BCuK60KT.mjs";import{stableStringify as Xt}from"./packem_shared/stableStringify-BjLh4gvA.mjs";import{stableWireKey as Vt}from"./packem_shared/stableWireKey-Diuu1gGc.mjs";export{Jr as ADMIN_FUNCTIONS,Zr as ADMIN_FUNCTION_PREFIX,p as AGGREGATE_SQL_FUNCTION,He as AGG_COUNT,Ve as AGG_KEY,Ye as AGG_VALUE,N as AUDIT_LOG_TABLE,z as CDC_LOG_TABLE,X as CDC_META_TABLE,ae as CLIENT_WATERMARK_TABLE,It as ConflictError,R as CountRlsUnsupportedError,ke as DATA_MIGRATION_STATE_TABLE,$r as DEFAULT_FANOUT_TOPIC_LIMIT,ta as DEFAULT_MAX_RELATION_KEYS,Ca as DEFAULT_MAX_RELAYS,Aa as DEFAULT_PROMOTION_THRESHOLDS,_t as DEFAULT_TRANSACTION_LIMITS,je as DOC_COLUMN,Rr as DurableStreamRunner,eo as FLAGS_FUNCTION_PREFIX,vr as GEO_DEFAULT_PRECISION,pe as GLOBAL_SHAPE_SNAPSHOT_TABLE,Te as IDEMPOTENCY_TABLE,uo as MAIL_RETENTION,xo as MAIL_TABLE,Ir as MAX_DURABLE_STREAM_BYTES,Cr as MAX_DURABLE_STREAM_CHUNKS,ro as MAX_PAGE_SIZE,st as MAX_SQL_ROWS,ho as NotFoundError,k as NotUniqueError,_a as OwnerRelay,ko as QUEUE_TABLE,qo as RANK_TIEBREAK,Bt as RELATION_EXISTS_KEY,oo as RELATION_FUNCTION_PREFIX,Ut as REPROJECTION_MIGRATION_PREFIX,Ua as RLS_UNWRAP_SYMBOL,jo as ReactiveCache,La as RelayMember,wa as RlsRequiredError,Ue as SCAN_DEP,Wa as SCHEMA_HISTORY_MAX_VERSIONS,Le as SEARCH_STATE_TABLE,at as ShardRunner,Lt as TransactionHeadroomTracker,te as advanceClientWatermark,Qe as aggUpsertSql,d as aggregateSqlFunction,f as aggregateTableName,y as appendAuditEntry,H as appendCdcChange,Sr as appendStreamChunk,V as applyCdcChanges,da as applyOnDelete,Lo as applySelect,Io as armRestore,na as assertFlatPredicate,it as assertReadonly,la as assertShapeShardable,P as assertValidClientId,ct as awaitWsDrain,w as backfillAggregateIndexes,K as backfillRankIndexes,q as backfillSearchIndexes,W as backfillSearchIndexesForTable,zr as boundingBoxCenter,Xr as boundingBoxGeohashes,ea as buildIndexRange,Za as buildPokeFrames,Fa as buildReprojectionMigration,bo as buildSeekBeforeWhere,Mo as buildSeekWhere,ja as buildSettings,Y as bumpCdcEpoch,ur as claimStreamRun,Ea as clampPromotionThresholds,fo as clearCapturedMail,Po as clearQueueMessages,T as coerceAggregateNumber,Ft as compileWhereSql,Ie as computeRankPage,sa as containsRelationPredicate,ka as countLegacyRows,Hr as coveringGeohashes,ie as createCompanionSync,we as createDependencyTracker,ao as createFanoutCounters,Je as createIndexSql,Zo as createReadFootprint,ba as createRelayLink,Na as createReplicaLink,B as createShardCtxDb,ht as createSystemReader,_r as decideDurableAttach,No as decodeCursor,de as deleteGlobalShapeSnapshot,ce as deleteGlobalShapeSnapshotsForConnection,xr as deleteStreamRun,Ke as depKey,br as diffExternalSource,$a as diffGlobalMembership,ca as distinctValues,A as encodeAggregateKey,yo as encodeCursor,Vr as encodeGeohash,Wo as encodePartitionKey,et as encodeRowsPatch,D as ensureAuditTable,To as ensureMailTable,o as exportShardRows,a as exportShardTable,to as facetColumn,Sa as fanOutScalarCounts,no as findStorageReferences,fr as finishStreamRun,E as foldAggregateTally,ya as gateReplicaDispatch,Ze as geoTableName,Ka as guardWriter,Da as handleReplicaControl,Mt as hasTrigger,Yr as haversineMeters,Ce as hydrateDocsById,t as importShardRows,ra as indexKeysForRow,Qa as isDevEnvironment,$e as isFtsAvailable,Bo as isLossyBody,ia as isRelationPredicate,Ur as isSoftDeleted,wr as isSourceDue,er as jsonPath,rr as jsonPathSql,oa as keysTouchRanges,Nr as liftSourceId,mt as lintReadonlySql,lo as listTables,kt as literalInList,vo as matchesRankStaticWhere,c as matchesStaticWhere,Fr as materializeExternalRows,kr as materializeExternalRowsIncremental,Tt as mergeChangedKeys,I as mergeWhere,j as migrateCdcLog,Q as migrateCdcMeta,ne as migrateClientWatermark,Tr as migrateDurableStreams,Se as migrateGlobalShapeSnapshot,Ae as migrateIdempotency,be as migrateSearchState,J as minCdcSeq,ga as nextPromotionState,S as normalizeCountArgument,G as normalizeIdStructurally,Do as normalizeOrderKeys,yr as normalizeSourceDocument,Dr as normalizeSourceValue,ir as param,n as parseExportShardArgs,l as parseImportShardArgs,C as planAggregateLookup,jr as pointInBoundingBox,rt as projectColumns,Kr as pullExternalSourceIncrementalTick,qr as pullExternalSourceTick,or as qualifiedJsonPath,ar as qualifiedJsonPathSql,qt as quoteIdentifier,zo as rankKeyFromDoc,Xo as rankTableName,Qo as reactiveCacheKey,g as readAggregateValue,O as readAuditLog,Co as readBookmark,Ao as readCapturedMail,Z as readCdcChanges,$ as readCdcCursor,ee as readCdcEpoch,le as readClientWatermark,Pr as readExternalSourceBaseline,ue as readGlobalShapeSnapshot,Ee as readIdempotent,Pe as readMigrationStatus,Go as readQueueMessageById,Uo as readQueueMessages,va as readSchemaHistory,za as readSchemaVersion,Me as readSearchBackfillState,Ar as readStreamChunks,Er as readStreamRun,so as readTablePage,Eo as recordCapturedMail,At as recordChangedKeys,io as recordFanoutPass,wo as recordQueueMessages,Xa as recordSchemaVersion,ua as relationHooks,ha as relayCountFor,mr as renderSql,Pa as reprojectableFields,wt as reprojectionMigrationId,Ba as reprojectionTables,Ho as resolveRankPartition,ma as resolveRelationPredicates,xa as resolveWith,tr as rowToDocument,Be as runDataMigration,ve as runDrizzle,Br as runExternalSourceTick,pt as runReadonlySql,fa as runRowValidators,vt as runShardMigrations,nt as runSocketPool,ze as runSql,Nt as runTriggers,Dt as selectExpiredIds,s as selectExportTables,_ as selectIndexForAggregate,L as selectIndexForCount,b as selectIndexForGroupBy,mo as selectMatchingIds,De as selectShapeMemberIds,Oe as selectShapeRows,Va as serializeSqlValue,Ra as shapeRoutingKey,Oo as softDeleteScope,Vo as sortColumnName,pr as sqliteInList,Xt as stableStringify,Vt as stableWireKey,St as subscriptionFrames,ut as subscriptionListDeltas,po as summarizeFanoutTopics,co as summarizeSubscriptions,nr as tableColumns,qe as tableFromDepKey,u as throwingScheduler,re as trimCdcChanges,ge as trimIdempotent,gr as trimStreamRuns,lr as tryRowToDocument,xt as trySendFrame,dr as unionAll,i as validateImportRow,xe as writeGlobalShapeSnapshot,he as writeIdempotent,Ne as writeSearchBackfillState,Et as writeTouchesMemo};
|
|
1
|
+
import{exportShardRows as o,exportShardTable as a,importShardRows as t,parseExportShardArgs as n,parseImportShardArgs as s,selectExportTables as i,validateImportRow as l}from"./packem_shared/exportShardRows-Cgt3ITwH.mjs";import{AGGREGATE_SQL_FUNCTION as p,aggregateSqlFunction as d,matchesStaticWhere as c,normalizeCountArgument as S,throwingScheduler as u}from"./packem_shared/AGGREGATE_SQL_FUNCTION-m1iUU1rv.mjs";import{aggregateTableName as f,coerceAggregateNumber as h,encodeAggregateKey as A,foldAggregateTally as E,readAggregateValue as T}from"./packem_shared/aggregateTableName-Cy5e03oz.mjs";import{CountRlsUnsupportedError as R,mergeWhere as C,planAggregateLookup as _,selectIndexForAggregate as I,selectIndexForCount as L,selectIndexForGroupBy as b}from"./packem_shared/CountRlsUnsupportedError-Bdfupt3g.mjs";import{AUDIT_LOG_TABLE as N,appendAuditEntry as y,ensureAuditTable as D,readAuditLog as O}from"./packem_shared/AUDIT_LOG_TABLE-uNVU9O1W.mjs";import{NotUniqueError as P,assertValidClientId as k,createShardCtxDb as B,normalizeIdStructurally as G}from"./packem_shared/NotUniqueError-BixDiv4O.mjs";import{backfillAggregateIndexes as w,backfillRankIndexes as K,backfillSearchIndexes as q,backfillSearchIndexesForTable as W}from"./packem_shared/backfillAggregateIndexes-DVQ2sVuV.mjs";import{CDC_LOG_TABLE as z,CDC_META_TABLE as H,appendCdcChange as X,applyCdcChanges as V,bumpCdcEpoch as j,migrateCdcLog as Y,migrateCdcMeta as Q,minCdcSeq as J,readCdcChanges as Z,readCdcCursor as $,readCdcEpoch as ee,trimCdcChanges as re}from"./packem_shared/CDC_LOG_TABLE-B58N8NQO.mjs";import{CLIENT_WATERMARK_TABLE as ae,advanceClientWatermark as te,migrateClientWatermark as ne,readClientWatermark as se}from"./packem_shared/CLIENT_WATERMARK_TABLE-BoS1HEqz.mjs";import{c as le}from"./packem_shared/ctx-db-companions-lTt-rvKG.mjs";import{GLOBAL_SHAPE_SNAPSHOT_TABLE as pe,deleteGlobalShapeSnapshot as de,deleteGlobalShapeSnapshotsForConnection as ce,migrateGlobalShapeSnapshot as Se,readGlobalShapeSnapshot as ue,writeGlobalShapeSnapshot as xe}from"./packem_shared/GLOBAL_SHAPE_SNAPSHOT_TABLE-NWaL77m5.mjs";import{IDEMPOTENCY_TABLE as he,migrateIdempotency as Ae,readIdempotent as Ee,trimIdempotent as Te,writeIdempotent as ge}from"./packem_shared/IDEMPOTENCY_TABLE-DKVe2Ohf.mjs";import{computeRankPage as Ce,hydrateDocsById as _e}from"./packem_shared/computeRankPage-Bby1Npkd.mjs";import{SEARCH_STATE_TABLE as Le,migrateSearchState as be,readSearchBackfillState as Me,writeSearchBackfillState as Ne}from"./packem_shared/SEARCH_STATE_TABLE-Dju8ebbU.mjs";import{SHAPE_POKE_CURSOR_TABLE as De,deleteShapePokeCursor as Oe,deleteShapePokeCursorsForConnection as Fe,migrateShapePokeCursor as Pe,readShapePokeCursor as ke,writeShapePokeCursor as Be}from"./packem_shared/SHAPE_POKE_CURSOR_TABLE-Dh4HfSdC.mjs";import{selectShapeMemberIds as Ue,selectShapeRows as we}from"./packem_shared/selectShapeMemberIds-B-pQJHAu.mjs";import{DATA_MIGRATION_STATE_TABLE as qe,readMigrationStatus as We,runDataMigration as ve}from"./packem_shared/DATA_MIGRATION_STATE_TABLE-4l6aU1Vc.mjs";import{SCAN_DEP as He,createDependencyTracker as Xe,depKey as Ve,tableFromDepKey as je}from"./packem_shared/SCAN_DEP-D7qE3iUe.mjs";import{runDrizzle as Qe,runSql as Je}from"./packem_shared/runDrizzle-it6rL9bR.mjs";import{A as $e,a as er,b as rr,D as or,c as ar,d as tr,g as nr,i as sr,j as ir,e as lr,q as mr,f as pr,r as dr,t as cr,h as Sr}from"./packem_shared/do-sql-Dk_DJxn4.mjs";import{param as xr,renderSql as fr,sqliteInList as hr,unionAll as Ar}from"./packem_shared/param-Ib8WHnrF.mjs";import{appendStreamChunk as Tr,claimStreamRun as gr,deleteStreamRun as Rr,finishStreamRun as Cr,migrateDurableStreams as _r,readStreamChunks as Ir,readStreamRun as Lr,trimStreamRuns as br}from"./packem_shared/appendStreamChunk-CH4e4nJn.mjs";import{DurableStreamRunner as Nr,MAX_DURABLE_STREAM_BYTES as yr,MAX_DURABLE_STREAM_CHUNKS as Dr,decideDurableAttach as Or}from"./packem_shared/DurableStreamRunner-Bm6KDMBU.mjs";import{diffExternalSource as Pr}from"./packem_shared/diffExternalSource-pozJ4UdZ.mjs";import{liftSourceId as Br,normalizeSourceDocument as Gr,normalizeSourceValue as Ur}from"./packem_shared/liftSourceId-CA3ENhXj.mjs";import{materializeExternalRows as Kr,materializeExternalRowsIncremental as qr,readExternalSourceBaseline as Wr,runExternalSourceTick as vr}from"./packem_shared/materializeExternalRows-Drn0FGdb.mjs";import{isSoftDeleted as Hr,isSourceDue as Xr,pullExternalSourceIncrementalTick as Vr,pullExternalSourceTick as jr}from"./packem_shared/isSoftDeleted-DcGB0pov.mjs";import{GEO_DEFAULT_PRECISION as Qr,boundingBoxCenter as Jr,boundingBoxGeohashes as Zr,coveringGeohashes as $r,encodeGeohash as eo,haversineMeters as ro,pointInBoundingBox as oo}from"./packem_shared/GEO_DEFAULT_PRECISION-CqpQZ-J_.mjs";import{ADMIN_FUNCTIONS as to,ADMIN_FUNCTION_PREFIX as no,DEFAULT_FANOUT_TOPIC_LIMIT as so,FLAGS_FUNCTION_PREFIX as io,MAX_PAGE_SIZE as lo,RELATION_FUNCTION_PREFIX as mo,createFanoutCounters as po,facetColumn as co,findStorageReferences as So,listTables as uo,readTablePage as xo,recordFanoutPass as fo,selectMatchingIds as ho,summarizeFanoutTopics as Ao,summarizeSubscriptions as Eo}from"./packem_shared/ADMIN_FUNCTIONS-Ddr79XHG.mjs";import{MAIL_RETENTION as go,MAIL_TABLE as Ro,clearCapturedMail as Co,ensureMailTable as _o,readCapturedMail as Io,recordCapturedMail as Lo}from"./packem_shared/MAIL_RETENTION-Cig9Dmc8.mjs";import{NotFoundError as Mo}from"./packem_shared/NotFoundError-BhF7FeFr.mjs";import{armRestore as yo,readBookmark as Do}from"./packem_shared/armRestore-Bu1_8SUa.mjs";import{applySelect as Fo,buildSeekBeforeWhere as Po,buildSeekWhere as ko,decodeCursor as Bo,encodeCursor as Go,normalizeOrderKeys as Uo,softDeleteScope as wo}from"./packem_shared/applySelect-BQbHyo-W.mjs";import{QUEUE_TABLE as qo,clearQueueMessages as Wo,isLossyBody as vo,readQueueMessageById as zo,readQueueMessages as Ho,recordQueueMessages as Xo}from"./packem_shared/QUEUE_TABLE-zj9Tt6tk.mjs";import{RANK_TIEBREAK as jo,encodePartitionKey as Yo,matchesRankStaticWhere as Qo,rankKeyFromDoc as Jo,rankTableName as Zo,resolveRankPartition as $o,sortColumnName as ea}from"./packem_shared/RANK_TIEBREAK-ci3MaM65.mjs";import{ReactiveCache as oa,reactiveCacheKey as aa}from"./packem_shared/ReactiveCache-DfyeaJOA.mjs";import{createReadFootprint as na}from"./packem_shared/createReadFootprint-MRH1If3F.mjs";import{buildIndexRange as ia,indexKeysForRow as la,keysTouchRanges as ma}from"./packem_shared/buildIndexRange-CBKQmHSS.mjs";import{DEFAULT_MAX_RELATION_KEYS as da,assertFlatPredicate as ca,assertShapeShardable as Sa,containsRelationPredicate as ua,isRelationPredicate as xa,resolveRelationPredicates as fa}from"./packem_shared/DEFAULT_MAX_RELATION_KEYS-BAWGIEvC.mjs";import{applyOnDelete as Aa,distinctValues as Ea,fanOutScalarCounts as Ta,relationHooks as ga,resolveWith as Ra,runRowValidators as Ca}from"./packem_shared/applyOnDelete-BlcwKjuO.mjs";import{DEFAULT_PROMOTION_THRESHOLDS as Ia,clampPromotionThresholds as La,nextPromotionState as ba,relayCountFor as Ma,shapeRoutingKey as Na}from"./packem_shared/DEFAULT_PROMOTION_THRESHOLDS-DVTD9iu0.mjs";import{DEFAULT_MAX_RELAYS as Da,OwnerRelay as Oa,RelayMember as Fa,createRelayLink as Pa}from"./packem_shared/DEFAULT_MAX_RELAYS-DeVcEXBh.mjs";import{createReplicaLink as Ba,gateReplicaDispatch as Ga,handleReplicaControl as Ua}from"./packem_shared/createReplicaLink-C1JuP_DN.mjs";import{buildReprojectionMigration as Ka,countLegacyRows as qa,reprojectableFields as Wa,reprojectionTables as va}from"./packem_shared/buildReprojectionMigration-8nVn8Qwb.mjs";import{RLS_UNWRAP_SYMBOL as Ha,RlsRequiredError as Xa,guardWriter as Va}from"./packem_shared/RLS_UNWRAP_SYMBOL-BWloGsd3.mjs";import{SCHEMA_HISTORY_MAX_VERSIONS as Ya,readSchemaHistory as Qa,readSchemaVersion as Ja,recordSchemaVersion as Za}from"./packem_shared/SCHEMA_HISTORY_MAX_VERSIONS-DsycDXWm.mjs";import{serializeSqlValue as et}from"./packem_shared/serializeSqlValue-DbI1VQYM.mjs";import{buildSettings as ot,isDevEnvironment as at}from"./packem_shared/buildSettings-B4igo4rJ.mjs";import{buildPokeFrames as nt,diffGlobalMembership as st,encodeRowsPatch as it,projectColumns as lt}from"./packem_shared/buildPokeFrames-BXejpiII.mjs";import{ShardRunner as pt}from"./packem_shared/ShardRunner-C9p5DVOx.mjs";import{runSocketPool as ct}from"./packem_shared/runSocketPool-CZJ2X9cF.mjs";import{MAX_SQL_ROWS as ut,assertReadonly as xt,lintReadonlySql as ft,runReadonlySql as ht}from"./packem_shared/MAX_SQL_ROWS-DnDyeZph.mjs";import{awaitWsDrain as Et,subscriptionFrames as Tt,subscriptionListDeltas as gt,trySendFrame as Rt}from"./packem_shared/awaitWsDrain-kSGvAfw1.mjs";import{mergeChangedKeys as _t,recordChangedKeys as It,writeTouchesMemo as Lt}from"./packem_shared/mergeChangedKeys-D1T-TPUb.mjs";import{createSystemReader as Mt}from"./packem_shared/createSystemReader-BtYeSMDb.mjs";import{ConflictError as yt}from"./packem_shared/ConflictError-C8GtJmjS.mjs";import{DEFAULT_TRANSACTION_LIMITS as Ot,TransactionHeadroomTracker as Ft}from"./packem_shared/DEFAULT_TRANSACTION_LIMITS-Bcoi7Bvf.mjs";import{hasTrigger as kt,runTriggers as Bt}from"./packem_shared/hasTrigger-CjlwI4le.mjs";import{selectExpiredIds as Ut}from"./packem_shared/selectExpiredIds-_5514W_v.mjs";import{compileWhereSql as Kt,literalInList as qt}from"./packem_shared/compileWhereSql-JBpSfQm9.mjs";import{RELATION_EXISTS_KEY as vt}from"./packem_shared/RELATION_EXISTS_KEY-CFUhnZSZ.mjs";import{REPROJECTION_MIGRATION_PREFIX as Ht,reprojectionMigrationId as Xt}from"./packem_shared/REPROJECTION_MIGRATION_PREFIX-Czcb6_mO.mjs";import{quoteIdentifier as jt}from"./packem_shared/quoteIdentifier-CObIFRhb.mjs";import{runShardMigrations as Qt}from"./packem_shared/runShardMigrations-Crppyq1f.mjs";import{stableStringify as Zt}from"./packem_shared/stableStringify-CujpENIO.mjs";import{stableWireKey as en}from"./packem_shared/stableWireKey-BYB5GQJa.mjs";export{to as ADMIN_FUNCTIONS,no as ADMIN_FUNCTION_PREFIX,p as AGGREGATE_SQL_FUNCTION,$e as AGG_COUNT,er as AGG_KEY,rr as AGG_VALUE,N as AUDIT_LOG_TABLE,z as CDC_LOG_TABLE,H as CDC_META_TABLE,ae as CLIENT_WATERMARK_TABLE,yt as ConflictError,R as CountRlsUnsupportedError,qe as DATA_MIGRATION_STATE_TABLE,so as DEFAULT_FANOUT_TOPIC_LIMIT,da as DEFAULT_MAX_RELATION_KEYS,Da as DEFAULT_MAX_RELAYS,Ia as DEFAULT_PROMOTION_THRESHOLDS,Ot as DEFAULT_TRANSACTION_LIMITS,or as DOC_COLUMN,Nr as DurableStreamRunner,io as FLAGS_FUNCTION_PREFIX,Qr as GEO_DEFAULT_PRECISION,pe as GLOBAL_SHAPE_SNAPSHOT_TABLE,he as IDEMPOTENCY_TABLE,go as MAIL_RETENTION,Ro as MAIL_TABLE,yr as MAX_DURABLE_STREAM_BYTES,Dr as MAX_DURABLE_STREAM_CHUNKS,lo as MAX_PAGE_SIZE,ut as MAX_SQL_ROWS,Mo as NotFoundError,P as NotUniqueError,Oa as OwnerRelay,qo as QUEUE_TABLE,jo as RANK_TIEBREAK,vt as RELATION_EXISTS_KEY,mo as RELATION_FUNCTION_PREFIX,Ht as REPROJECTION_MIGRATION_PREFIX,Ha as RLS_UNWRAP_SYMBOL,oa as ReactiveCache,Fa as RelayMember,Xa as RlsRequiredError,He as SCAN_DEP,Ya as SCHEMA_HISTORY_MAX_VERSIONS,Le as SEARCH_STATE_TABLE,De as SHAPE_POKE_CURSOR_TABLE,pt as ShardRunner,Ft as TransactionHeadroomTracker,te as advanceClientWatermark,ar as aggUpsertSql,d as aggregateSqlFunction,f as aggregateTableName,y as appendAuditEntry,X as appendCdcChange,Tr as appendStreamChunk,V as applyCdcChanges,Aa as applyOnDelete,Fo as applySelect,yo as armRestore,ca as assertFlatPredicate,xt as assertReadonly,Sa as assertShapeShardable,k as assertValidClientId,Et as awaitWsDrain,w as backfillAggregateIndexes,K as backfillRankIndexes,q as backfillSearchIndexes,W as backfillSearchIndexesForTable,Jr as boundingBoxCenter,Zr as boundingBoxGeohashes,ia as buildIndexRange,nt as buildPokeFrames,Ka as buildReprojectionMigration,Po as buildSeekBeforeWhere,ko as buildSeekWhere,ot as buildSettings,j as bumpCdcEpoch,gr as claimStreamRun,La as clampPromotionThresholds,Co as clearCapturedMail,Wo as clearQueueMessages,h as coerceAggregateNumber,Kt as compileWhereSql,Ce as computeRankPage,ua as containsRelationPredicate,qa as countLegacyRows,$r as coveringGeohashes,le as createCompanionSync,Xe as createDependencyTracker,po as createFanoutCounters,tr as createIndexSql,na as createReadFootprint,Pa as createRelayLink,Ba as createReplicaLink,B as createShardCtxDb,Mt as createSystemReader,Or as decideDurableAttach,Bo as decodeCursor,de as deleteGlobalShapeSnapshot,ce as deleteGlobalShapeSnapshotsForConnection,Oe as deleteShapePokeCursor,Fe as deleteShapePokeCursorsForConnection,Rr as deleteStreamRun,Ve as depKey,Pr as diffExternalSource,st as diffGlobalMembership,Ea as distinctValues,A as encodeAggregateKey,Go as encodeCursor,eo as encodeGeohash,Yo as encodePartitionKey,it as encodeRowsPatch,D as ensureAuditTable,_o as ensureMailTable,o as exportShardRows,a as exportShardTable,co as facetColumn,Ta as fanOutScalarCounts,So as findStorageReferences,Cr as finishStreamRun,E as foldAggregateTally,Ga as gateReplicaDispatch,nr as geoTableName,Va as guardWriter,Ua as handleReplicaControl,kt as hasTrigger,ro as haversineMeters,_e as hydrateDocsById,t as importShardRows,la as indexKeysForRow,at as isDevEnvironment,sr as isFtsAvailable,vo as isLossyBody,xa as isRelationPredicate,Hr as isSoftDeleted,Xr as isSourceDue,ir as jsonPath,lr as jsonPathSql,ma as keysTouchRanges,Br as liftSourceId,ft as lintReadonlySql,uo as listTables,qt as literalInList,Qo as matchesRankStaticWhere,c as matchesStaticWhere,Kr as materializeExternalRows,qr as materializeExternalRowsIncremental,_t as mergeChangedKeys,C as mergeWhere,Y as migrateCdcLog,Q as migrateCdcMeta,ne as migrateClientWatermark,_r as migrateDurableStreams,Se as migrateGlobalShapeSnapshot,Ae as migrateIdempotency,be as migrateSearchState,Pe as migrateShapePokeCursor,J as minCdcSeq,ba as nextPromotionState,S as normalizeCountArgument,G as normalizeIdStructurally,Uo as normalizeOrderKeys,Gr as normalizeSourceDocument,Ur as normalizeSourceValue,xr as param,n as parseExportShardArgs,s as parseImportShardArgs,_ as planAggregateLookup,oo as pointInBoundingBox,lt as projectColumns,Vr as pullExternalSourceIncrementalTick,jr as pullExternalSourceTick,mr as qualifiedJsonPath,pr as qualifiedJsonPathSql,jt as quoteIdentifier,Jo as rankKeyFromDoc,Zo as rankTableName,aa as reactiveCacheKey,T as readAggregateValue,O as readAuditLog,Do as readBookmark,Io as readCapturedMail,Z as readCdcChanges,$ as readCdcCursor,ee as readCdcEpoch,se as readClientWatermark,Wr as readExternalSourceBaseline,ue as readGlobalShapeSnapshot,Ee as readIdempotent,We as readMigrationStatus,zo as readQueueMessageById,Ho as readQueueMessages,Qa as readSchemaHistory,Ja as readSchemaVersion,Me as readSearchBackfillState,ke as readShapePokeCursor,Ir as readStreamChunks,Lr as readStreamRun,xo as readTablePage,Lo as recordCapturedMail,It as recordChangedKeys,fo as recordFanoutPass,Xo as recordQueueMessages,Za as recordSchemaVersion,ga as relationHooks,Ma as relayCountFor,fr as renderSql,Wa as reprojectableFields,Xt as reprojectionMigrationId,va as reprojectionTables,$o as resolveRankPartition,fa as resolveRelationPredicates,Ra as resolveWith,dr as rowToDocument,ve as runDataMigration,Qe as runDrizzle,vr as runExternalSourceTick,ht as runReadonlySql,Ca as runRowValidators,Qt as runShardMigrations,ct as runSocketPool,Je as runSql,Bt as runTriggers,Ut as selectExpiredIds,i as selectExportTables,I as selectIndexForAggregate,L as selectIndexForCount,b as selectIndexForGroupBy,ho as selectMatchingIds,Ue as selectShapeMemberIds,we as selectShapeRows,et as serializeSqlValue,Na as shapeRoutingKey,wo as softDeleteScope,ea as sortColumnName,hr as sqliteInList,Zt as stableStringify,en as stableWireKey,Tt as subscriptionFrames,gt as subscriptionListDeltas,Ao as summarizeFanoutTopics,Eo as summarizeSubscriptions,cr as tableColumns,je as tableFromDepKey,u as throwingScheduler,re as trimCdcChanges,Te as trimIdempotent,br as trimStreamRuns,Sr as tryRowToDocument,Rt as trySendFrame,Ar as unionAll,l as validateImportRow,xe as writeGlobalShapeSnapshot,ge as writeIdempotent,Ne as writeSearchBackfillState,Be as writeShapePokeCursor,Lt as writeTouchesMemo};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{LunoraError as v}from"@lunora/errors";import{m as L,n as O}from"./do-sql-Dk_DJxn4.mjs";import{quoteIdentifier as d}from"./quoteIdentifier-CObIFRhb.mjs";import{d as P}from"./wire-codec-BU9T2xJ7.mjs";const te="__lunora_admin__:",ne="__lunora_relation__:",re="__lunora_flags__:",se={applyCdc:"__lunora_admin__:applyCdc",aiAvailable:"__lunora_admin__:aiAvailable",aiChartConfig:"__lunora_admin__:aiChartConfig",aiGenerateSql:"__lunora_admin__:aiGenerateSql",aiTableFilter:"__lunora_admin__:aiTableFilter",assignIssue:"__lunora_admin__:assignIssue",backRelationCounts:"__lunora_admin__:backRelationCounts",cdcSync:"__lunora_admin__:cdcSync",clearCapturedMail:"__lunora_admin__:clearCapturedMail",clearQueueMessages:"__lunora_admin__:clearQueueMessages",clearTable:"__lunora_admin__:clearTable",createWorkflowInstance:"__lunora_admin__:createWorkflowInstance",deleteRows:"__lunora_admin__:deleteRows",describeTable:"__lunora_admin__:describeTable",describeTables:"__lunora_admin__:describeTables",explainIssue:"__lunora_admin__:explainIssue",exportShard:"__lunora_admin__:exportShard",facetColumn:"__lunora_admin__:facetColumn",getAdvisories:"__lunora_admin__:getAdvisories",getAdvisorProcedures:"__lunora_admin__:getAdvisorProcedures",getAuditLog:"__lunora_admin__:getAuditLog",getAuthMetrics:"__lunora_admin__:getAuthMetrics",getCapturedMail:"__lunora_admin__:getCapturedMail",getFanoutMetrics:"__lunora_admin__:getFanoutMetrics",getFunctionStats:"__lunora_admin__:getFunctionStats",getIssues:"__lunora_admin__:getIssues",getMetricHistory:"__lunora_admin__:getMetricHistory",getMetricSeries:"__lunora_admin__:getMetricSeries",listSubscriptions:"__lunora_admin__:listSubscriptions",listTableIndexes:"__lunora_admin__:listTableIndexes",listTablesIndexes:"__lunora_admin__:listTablesIndexes",getLogs:"__lunora_admin__:getLogs",getMetrics:"__lunora_admin__:getMetrics",getPitrBookmark:"__lunora_admin__:getPitrBookmark",getQueryInsights:"__lunora_admin__:getQueryInsights",getQueueMessages:"__lunora_admin__:getQueueMessages",getRequestLog:"__lunora_admin__:getRequestLog",getSecurityAudit:"__lunora_admin__:getSecurityAudit",getSettings:"__lunora_admin__:getSettings",getTraces:"__lunora_admin__:getTraces",getWorkflowInstanceStatus:"__lunora_admin__:getWorkflowInstanceStatus",ignoreIssue:"__lunora_admin__:ignoreIssue",importShard:"__lunora_admin__:importShard",listFlags:"__lunora_admin__:listFlags",listQueues:"__lunora_admin__:listQueues",lintSql:"__lunora_admin__:lintSql",listTables:"__lunora_admin__:listTables",listWorkflows:"__lunora_admin__:listWorkflows",maskPolicies:"__lunora_admin__:maskPolicies",migrationStatus:"__lunora_admin__:migrationStatus",pitrRestore:"__lunora_admin__:pitrRestore",rankBefore:"__lunora_admin__:rankBefore",rankPage:"__lunora_admin__:rankPage",readTablePage:"__lunora_admin__:readTablePage",recordAuthEvent:"__lunora_admin__:recordAuthEvent",recordContainerEvent:"__lunora_admin__:recordContainerEvent",recordMail:"__lunora_admin__:recordMail",recordQueueMessage:"__lunora_admin__:recordQueueMessage",replayQueueMessage:"__lunora_admin__:replayQueueMessage",resolveIssue:"__lunora_admin__:resolveIssue",rlsPolicies:"__lunora_admin__:rlsPolicies",schemaHistory:"__lunora_admin__:schemaHistory",schemaVersion:"__lunora_admin__:schemaVersion",runAs:"__lunora_admin__:runAs",runMigration:"__lunora_admin__:runMigration",runSql:"__lunora_admin__:runSql",sendQueueMessage:"__lunora_admin__:sendQueueMessage",sendTestMail:"__lunora_admin__:sendTestMail",setIssueSeverity:"__lunora_admin__:setIssueSeverity",storageOrphans:"__lunora_admin__:storageOrphans",storageReferences:"__lunora_admin__:storageReferences",storageRules:"__lunora_admin__:storageRules",studioFeatures:"__lunora_admin__:studioFeatures",writeRow:"__lunora_admin__:writeRow"},D=50,g=500,U=30,W=200,m="__doc__",k=e=>{try{const t=JSON.parse(e);return t!==null&&typeof t=="object"&&!Array.isArray(t)?t:void 0}catch{return}},j=e=>{const{[O]:t,...n}=e;return t===void 0?n:t===null||typeof t!="object"||Array.isArray(t)?{[O]:t,...n}:{...n,...P(t)}},Q=(e,t)=>{if(!e.includes(m))return{columns:e,rows:t};const n=[];for(const s of t){const a=s[m],i=typeof a=="string"?k(a):void 0;if(i===void 0)return{columns:e,rows:t};const c=Object.fromEntries(Object.entries(s).filter(([u])=>u!==m));n.push({...c,...j(i)})}const r=e.filter(s=>s!==m),o=[],_=new Set(r);for(const s of n)for(const a of Object.keys(s))_.has(a)||(_.add(a),o.push(a));return{columns:[...r,...o],rows:n}},F=e=>`instr(lower(CAST(${e} AS TEXT)), lower(?)) > 0`,I=e=>e.startsWith("sqlite_")||e.startsWith("_cf_")||e.startsWith("__miniflare")||e.startsWith("__lunora")||e.includes("__fts_"),E=(e,t,n)=>Math.min(Math.max(e,t),n),x=(e,t)=>{const n=e.exec(`SELECT COUNT(*) AS c FROM ${t}`).one();return Number(n.c)},oe=e=>{const t=e.exec("SELECT name FROM sqlite_master WHERE type = 'table' ORDER BY name").toArray(),n=[];for(const{name:r}of t)I(r)||n.push({name:r,rowCount:x(e,d(r))});return n},N=(e,t)=>e.exec("SELECT name FROM sqlite_master WHERE type = 'table' AND name = ? LIMIT 1",t).toArray().length>0,C=(e,t)=>{if(I(t)||!N(e,t))throw new v("UNKNOWN_TABLE",`unknown table: ${t}`,{status:404})},M=(e,t)=>e.exec(`PRAGMA table_info(${t})`).toArray().map(n=>n.name),q={eq:"=",gt:">",gte:">=",lt:"<",lte:"<=",ne:"<>"},H=e=>typeof e=="string"?e:typeof e=="number"||typeof e=="boolean"?String(e):"",S=(e,t)=>{const n=t.includes(e),r=t.includes(m);if(!(!n&&!r))return n?{expression:d(e),params:[]}:{expression:`json_extract(${d(m)}, ?)`,params:[`$.${L(e)}`]}},B=(e,t)=>{const n=S(e.column,t);if(n===void 0)return;const{expression:r,params:o}=n;return e.operator==="contains"?{params:[...o,H(e.value)],sql:F(r)}:{params:[...o,e.value],sql:`${r} ${q[e.operator]} ?`}},G=/^(\d{4})(?:-(\d{2}))?(?:-(\d{2}))?$/u,X=e=>{const t=G.exec(e.trim());if(t===null)return;const n=Number(t[1]),r=t[2]===void 0?void 0:Number(t[2]),o=t[3]===void 0?void 0:Number(t[3]);if(r!==void 0&&(r<1||r>12)||o!==void 0&&(o<1||o>31)||n<100)return;const _=Date.UTC(n,(r??1)-1,o??1);if(o!==void 0&&new Date(_).getUTCDate()!==o)return;let s;return o!==void 0?s=Date.UTC(n,(r??1)-1,o+1):r===void 0?s=Date.UTC(n+1,0,1):s=Date.UTC(n,r,1),{from:_,to:s}},A=(e,t,n)=>{const r=[],o=[];if(t!==""&&e.length>0){const _=e.map(a=>F(d(a)));o.push(...e.map(()=>t));const s=X(t);if(s!==void 0)for(const a of e)_.push(`(${d(a)} >= ? AND ${d(a)} < ?)`),o.push(s.from,s.to);r.push(`(${_.join(" OR ")})`)}for(const _ of n??[]){const s=B(_,e);s!==void 0&&(r.push(`(${s.sql})`),o.push(...s.params))}return r.length===0?void 0:{parameters:o,where:r.join(" AND ")}},K=(e,t)=>{if(e===void 0)return;const n=S(e.column,t);if(n===void 0)return;const r=e.direction==="desc"?"DESC":"ASC";return{params:n.params,sql:`${n.expression} ${r}`}},ae=(e,t)=>{const{table:n}=t;C(e,n);const r=E(Math.trunc(t.limit??D),1,g),o=Math.max(0,Math.trunc(t.offset??0)),_=d(n),s=M(e,_),a=t.search?.trim()??"",i=b=>{if(t.refs===void 0)return b;const T={};for(const w of b.columns){const y=t.refs[w];y!==void 0&&(T[w]=y)}return Object.keys(T).length>0?{...b,refs:T}:b},c=A(s,a,t.filters),u=K(t.orderBy,s),l=c===void 0?"":` WHERE ${c.where}`,f=u===void 0?"":` ORDER BY ${u.sql}`,p=c?.parameters??[],h=u?.params??[];let R;t.skipCount||(R=c===void 0?x(e,_):Number(e.exec(`SELECT COUNT(*) AS c FROM ${_}${l}`,...p).one().c));const $=e.exec(`SELECT * FROM ${_}${l}${f} LIMIT ? OFFSET ?`,...p,...h,r,o).toArray();return i({...Q(s,$),total:R})},_e=(e,t)=>{const{table:n}=t;C(e,n);const r=E(Math.trunc(t.limit??g),1,g),o=d(n),_=M(e,o),s=t.search?.trim()??"",a=A(_,s,t.filters),i=a===void 0?e.exec(`SELECT id FROM ${o} LIMIT ?`,r+1).toArray():e.exec(`SELECT id FROM ${o} WHERE ${a.where} LIMIT ?`,...a.parameters,r+1).toArray(),c=i.length>r,u=i.slice(0,r).map(l=>l.id);return{hasMore:c,ids:u}},Y=(e,t,n)=>{const r=new Set(n.filter(_=>_!==m));if(!n.includes(m))return r;const o=e.exec(`SELECT ${d(m)} AS doc FROM ${t} LIMIT ?`,g).toArray();for(const{doc:_}of o){const s=typeof _=="string"?k(_):void 0;if(s!==void 0)for(const a of Object.keys(s))r.add(a)}return r},ie=(e,t)=>{const{column:n,table:r}=t;C(e,r);const o=d(r),_=M(e,o);if(!Y(e,o,_).has(n))throw new v("UNKNOWN_COLUMN",`unknown column: ${n}`,{status:404});const s=S(n,_);if(s===void 0)throw new v("UNKNOWN_COLUMN",`unknown column: ${n}`,{status:404});const a=E(Math.trunc(t.limit??U),1,W),i=t.search?.trim()??"",c=A(_,i,t.filters),u=c===void 0?"":` WHERE ${c.where}`,l=c?.parameters??[],f=e.exec(`SELECT ${s.expression} AS value, COUNT(*) AS count FROM ${o}${u} GROUP BY ${s.expression} ORDER BY count DESC LIMIT ?`,...s.params,...l,...s.params,a+1).toArray();return{truncated:f.length>a,values:f.slice(0,a).map(h=>({count:Number(h.count),value:h.value}))}},ce=(e,t,n)=>{const r={},o=n.slice(0,g);for(const s of o)r[s]=[];if(o.length===0)return{references:r,storageColumns:t};const _=o.map(()=>"?").join(", ");for(const[s,a]of Object.entries(t)){if(I(s)||!N(e,s))continue;const i=d(s),c=M(e,i);for(const u of a){const l=S(u,c);if(l===void 0)continue;const f=e.exec(`SELECT id, ${l.expression} AS ref FROM ${i} WHERE ${l.expression} IN (${_})`,...l.params,...l.params,...o).toArray();for(const p of f)r[p.ref]?.push({column:u,id:p.id,table:s})}}return{references:r,storageColumns:t}},ue=e=>{const t=e.map((r,o)=>{const _=Object.values(r.subs??{}).map(s=>({args:s.args,functionPath:s.functionPath,table:s.table}));return{admin:r.admin===!0,id:o,subscriptions:_}}),n=t.reduce((r,o)=>r+o.subscriptions.length,0);return{connections:t,totalConnections:t.length,totalSubscriptions:n}},V=20,le=()=>({maxMs:0,passes:0,peakSocketsIterated:0,socketsDelivered:0,socketsIterated:0,totalMs:0}),de=(e,t,n,r)=>({maxMs:Math.max(e.maxMs,r),passes:e.passes+1,peakSocketsIterated:Math.max(e.peakSocketsIterated,t),socketsDelivered:e.socketsDelivered+n,socketsIterated:e.socketsIterated+t,totalMs:e.totalMs+r}),me=(e,t=V)=>{const n=new Map,r=new Map;for(const s of e){for(const a of Object.values(s.shapes??{})){const i=a.name??"(unknown shape)";n.set(i,(n.get(i)??0)+1)}for(const a of s.whispers??[])r.set(a,(r.get(a)??0)+1)}const o=[...[...n].map(([s,a])=>({kind:"shape",subscribers:a,topic:s})),...[...r].map(([s,a])=>({kind:"whisper",subscribers:a,topic:s}))];return o.sort((s,a)=>a.subscribers-s.subscribers||s.topic.localeCompare(a.topic)),{peakSubscribers:o[0]?.subscribers??0,topics:o.slice(0,t),totalConnections:e.length}};export{se as ADMIN_FUNCTIONS,te as ADMIN_FUNCTION_PREFIX,V as DEFAULT_FANOUT_TOPIC_LIMIT,re as FLAGS_FUNCTION_PREFIX,g as MAX_PAGE_SIZE,ne as RELATION_FUNCTION_PREFIX,le as createFanoutCounters,X as datePrefixRange,ie as facetColumn,ce as findStorageReferences,oe as listTables,ae as readTablePage,de as recordFanoutPass,_e as selectMatchingIds,me as summarizeFanoutTopics,ue as summarizeSubscriptions};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{LunoraError as u}from"@lunora/errors";const f=new Set(["baseWhere","relationBaseWhere","restrictsCounts","where"]),c=()=>{throw new u("INTERNAL","ctx.scheduler: no scheduler configured for triggers. Pass `scheduler` to the ctx-db factory.")},h=(e,r)=>{for(const[n,t]of Object.entries(r)){const o=e[n];if(t!==null&&typeof t=="object"&&!Array.isArray(t)){const s=Object.keys(t);if(s.length===1&&s[0]==="eq"){if(o!==t.eq)return!1;continue}return!1}if(o!==t)return!1}return!0},l=e=>{if(e===void 0)return{};if(typeof e!="object"||Array.isArray(e))return{where:e};const r=Object.keys(e);return r.length===0?{}:r.every(n=>f.has(n))?e:{where:e}},i={avg:"AVG",count:"COUNT",max:"MAX",min:"MIN",sum:"SUM"},y=e=>{const r=i[e];if(r===void 0)throw new u("INTERNAL",`unknown aggregate op "${e}": expected one of ${Object.keys(i).join(", ")}`);return r},A={runAfter:c,runAt:c};export{i as AGGREGATE_SQL_FUNCTION,y as aggregateSqlFunction,h as matchesStaticWhere,l as normalizeCountArgument,A as throwingScheduler};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{A as r,a as l,b as i,D as n,n as m,c as q,d as c,l as d,k as f,g as p,i as u,j as A,e as D,q as G,f as S,r as _,t as h,h as C}from"./do-sql-Dk_DJxn4.mjs";import{quoteIdentifier as b}from"./quoteIdentifier-CObIFRhb.mjs";import"./wire-codec-BU9T2xJ7.mjs";import"./runDrizzle-it6rL9bR.mjs";import"./sql-projection-BqmxFxQU.mjs";import{serializeSqlValue as x}from"./serializeSqlValue-DbI1VQYM.mjs";export{r as AGG_COUNT,l as AGG_KEY,i as AGG_VALUE,n as DOC_COLUMN,m as DOC_ORIGINALS_KEY,q as aggUpsertSql,c as createIndexSql,d as decodeDocJson,f as encodeDocJson,p as geoTableName,u as isFtsAvailable,A as jsonPath,D as jsonPathSql,G as qualifiedJsonPath,S as qualifiedJsonPathSql,b as quoteIdentifier,_ as rowToDocument,x as serializeSqlValue,h as tableColumns,C as tryRowToDocument};
|
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
import{runSql as T}from"./runDrizzle-it6rL9bR.mjs";const i="__lunora_audit__",a=1e3,s=E=>{T(E,`CREATE TABLE IF NOT EXISTS "${i}" (
|
|
2
|
+
seq INTEGER PRIMARY KEY AUTOINCREMENT,
|
|
3
|
+
ts REAL NOT NULL,
|
|
4
|
+
op TEXT NOT NULL,
|
|
5
|
+
"table" TEXT,
|
|
6
|
+
id TEXT,
|
|
7
|
+
detail TEXT
|
|
8
|
+
)`)},R=(E,t)=>{s(E),T(E,`INSERT INTO "${i}" (ts, op, "table", id, detail) VALUES (?, ?, ?, ?, ?)`,t.ts,t.op,t.table??null,t.id??null,t.detail===void 0?null:JSON.stringify(t.detail)),T(E,`DELETE FROM "${i}" WHERE seq <= (SELECT MAX(seq) - ? FROM "${i}")`,a)},o=(E,t={})=>{s(E);const d=t.sinceSeq??0,n=Math.max(1,Math.min(t.limit??a,1e4));return T(E,`SELECT seq, ts, op, "table", id, detail FROM "${i}" WHERE seq > ? ORDER BY seq DESC LIMIT ?`,d,n).toArray().map(e=>{const l={op:e.op,seq:e.seq,ts:e.ts};return e.table!==null&&(l.table=e.table),e.id!==null&&(l.id=e.id),e.detail!==null&&(l.detail=JSON.parse(e.detail)),l})};export{i as AUDIT_LOG_TABLE,R as appendAuditEntry,s as ensureAuditTable,o as readAuditLog};
|
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
import{sql as e}from"drizzle-orm";import{runDrizzle as n}from"./runDrizzle-it6rL9bR.mjs";import{k as p,l as f}from"./do-sql-Dk_DJxn4.mjs";import{ConflictError as L}from"./ConflictError-C8GtJmjS.mjs";const s="__cdc_log",$=t=>{n(t,e`CREATE TABLE IF NOT EXISTS ${e.identifier(s)} (
|
|
2
|
+
seq INTEGER PRIMARY KEY AUTOINCREMENT,
|
|
3
|
+
ts REAL NOT NULL,
|
|
4
|
+
${e.identifier("table")} TEXT NOT NULL,
|
|
5
|
+
id TEXT NOT NULL,
|
|
6
|
+
op TEXT NOT NULL,
|
|
7
|
+
doc TEXT
|
|
8
|
+
)`)},u=(t,o,i,r,d,T)=>{const E=T===void 0?null:p(T);n(t,e`INSERT INTO ${e.identifier(s)} (ts, ${e.identifier("table")}, id, op, doc) VALUES (${o}, ${i}, ${r}, ${d}, ${E})`)},S=(t,o={})=>{const i=o.sinceSeq??0,r=Math.max(1,Math.min(o.limit??1e3,1e4)),d=o.tables&&o.tables.size>0?e` AND ${e.identifier("table")} IN (${e.join([...o.tables].map(c=>e`${c}`),e`, `)})`:e``,E=n(t,e`SELECT seq, ts, ${e.identifier("table")}, id, op, doc FROM ${e.identifier(s)} WHERE seq > ${i}${d} ORDER BY seq ASC LIMIT ${r}`).toArray().map(c=>{const l={id:c.id,op:c.op,seq:c.seq,table:c.table,ts:c.ts};return c.doc===null?l:{...l,doc:f(c.doc)}});return{changes:E,cursor:E.at(-1)?.seq??i}},O=(t,o)=>{n(t,e`DELETE FROM ${e.identifier(s)} WHERE seq <= ${o}`)},q=t=>{const i=n(t,e`SELECT seq FROM sqlite_sequence WHERE name = ${s}`).toArray()[0]?.seq;return typeof i=="number"?i:n(t,e`SELECT MAX(seq) AS seq FROM ${e.identifier(s)}`).toArray()[0]?.seq??0},h=t=>n(t,e`SELECT MIN(seq) AS seq FROM ${e.identifier(s)}`).toArray()[0]?.seq??void 0,a="__cdc_meta",C=t=>{n(t,e`CREATE TABLE IF NOT EXISTS ${e.identifier(a)} (id INTEGER PRIMARY KEY CHECK (id = 1), epoch TEXT NOT NULL)`)},M=t=>{C(t);const i=n(t,e`SELECT epoch FROM ${e.identifier(a)} WHERE id = 1`).toArray()[0]?.epoch;if(typeof i=="string"&&i.length>0)return i;const r=crypto.randomUUID();return n(t,e`INSERT INTO ${e.identifier(a)} (id, epoch) VALUES (1, ${r})`),r},b=t=>{C(t);const o=crypto.randomUUID();return n(t,e`INSERT INTO ${e.identifier(a)} (id, epoch) VALUES (1, ${o}) ON CONFLICT(id) DO UPDATE SET epoch = excluded.epoch`),o},m=async(t,o)=>{if(o.op==="delete"){await t.delete(o.id,o.table);return}const i=o.doc??{};try{await t.insert(o.table,i,{allowExplicitId:!0})}catch(r){if(!(r instanceof L))throw r;const d={...i};delete d._id,await t.replace(o.id,d,void 0,{allowExplicitId:!0})}},y=async(t,o)=>{for(const i of o)await m(t,i)};export{s as CDC_LOG_TABLE,a as CDC_META_TABLE,u as appendCdcChange,y as applyCdcChanges,b as bumpCdcEpoch,$ as migrateCdcLog,C as migrateCdcMeta,h as minCdcSeq,S as readCdcChanges,q as readCdcCursor,M as readCdcEpoch,O as trimCdcChanges};
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
import{sql as t}from"drizzle-orm";import{runDrizzle as a}from"./runDrizzle-it6rL9bR.mjs";const r="__client_watermark",o=i=>{a(i,t`CREATE TABLE IF NOT EXISTS ${t.identifier(r)} (
|
|
2
|
+
identity TEXT NOT NULL,
|
|
3
|
+
client_id TEXT NOT NULL,
|
|
4
|
+
last_mutation_id INTEGER NOT NULL,
|
|
5
|
+
PRIMARY KEY (identity, client_id)
|
|
6
|
+
)`)},E=(i,e,n)=>a(i,t`SELECT last_mutation_id FROM ${t.identifier(r)} WHERE identity = ${e} AND client_id = ${n} LIMIT 1`).toArray()[0]?.last_mutation_id??0,l=(i,e,n,d)=>{a(i,t`INSERT INTO ${t.identifier(r)} (identity, client_id, last_mutation_id) VALUES (${e}, ${n}, ${d})
|
|
7
|
+
ON CONFLICT(identity, client_id) DO UPDATE SET last_mutation_id = MAX(last_mutation_id, excluded.last_mutation_id)`)};export{r as CLIENT_WATERMARK_TABLE,l as advanceClientWatermark,o as migrateClientWatermark,E as readClientWatermark};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{LunoraError as p}from"@lunora/errors";class R extends p{constructor(n){super("COUNT_RLS_UNSUPPORTED",n===void 0?"count() is not supported in an RLS-restricted context":`count() is not supported on table "${n}" inside an RLS-restricted context`)}}const S=(e,n)=>e?n?{AND:[e,n]}:e:n,v=new Set(["AND","NOT","OR"]),d=Symbol("not-eq"),O=e=>{if(e!==null&&typeof e=="object"&&!Array.isArray(e)){const n=Object.keys(e);return n.length===1&&n[0]==="eq"?e.eq:d}return e},f=(e,n)=>{const i={};for(const[t,o]of Object.entries(e)){if(v.has(t)||!n(t))return;const r=O(o);if(r===d)return;i[t]=r}return i},l=(e,n,i)=>{const t={...n};if(!e)return t;for(const[o,r]of Object.entries(e))if(o in t){if(t[o]!==r)return}else if(o in i){if(i[o]!==r)return}else t[o]=r;return t},b=(e,n)=>{const i=e.by??[],t=n??{},o=f(t,r=>i.includes(r));if(o!==void 0){for(const r of i)if(!(r in o))return;return l(e.where,o,t)}},x=(e,n,i)=>{const t=f(n??{},o=>i.has(o));if(t!==void 0)return l(e.where,t,{})},y=(e,n,i,t)=>{let o;for(const r of e){if(r.op!==n||n!=="count"&&r.field!==i)continue;const s=b(r,t);s&&(!o||(r.by?.length??0)>(o.index.by?.length??0))&&(o={index:r,key:s})}return o},h=(e,n)=>y(e,"count",void 0,n),A=(e,n,i,t)=>y(e,n,i,t),N=(e,n,i,t,o)=>{const r=new Set(t);for(const s of e){if(s.op!==n||n!=="count"&&s.field!==i)continue;const c=s.by??[];if(c.length!==r.size||!c.every(a=>r.has(a)))continue;const u=x(s,o,r);if(u!==void 0)return{index:s,partial:u}}};export{R as CountRlsUnsupportedError,S as mergeWhere,b as planAggregateLookup,A as selectIndexForAggregate,h as selectIndexForCount,N as selectIndexForGroupBy};
|
|
@@ -0,0 +1,31 @@
|
|
|
1
|
+
import{LunoraError as b}from"@lunora/errors";import{runSql as c}from"./runDrizzle-it6rL9bR.mjs";const n="__lunora_migrations",x=100,D=3e4,y=1e4,M=e=>{c(e,`CREATE TABLE IF NOT EXISTS "${n}" (
|
|
2
|
+
id TEXT PRIMARY KEY,
|
|
3
|
+
direction TEXT NOT NULL,
|
|
4
|
+
status TEXT NOT NULL,
|
|
5
|
+
cursor TEXT,
|
|
6
|
+
processed INTEGER NOT NULL DEFAULT 0,
|
|
7
|
+
changed INTEGER NOT NULL DEFAULT 0,
|
|
8
|
+
started_at REAL,
|
|
9
|
+
updated_at REAL,
|
|
10
|
+
error TEXT
|
|
11
|
+
)`)},N=e=>({changed:e.changed,cursor:typeof e.cursor=="string"?e.cursor:null,direction:e.direction==="down"?"down":"up",processed:e.processed,status:e.status==="completed"||e.status==="failed"?e.status:"in_progress"}),h=(e,t)=>{const r=c(e,`SELECT * FROM "${n}" WHERE id = ?`,t).toArray()[0];if(r)return{...N(r),startedAt:typeof r.started_at=="number"?r.started_at:void 0}},C=(e,t)=>{c(e,`DELETE FROM "${n}" WHERE id = ?`,t)},S=(e,t)=>{c(e,`INSERT INTO "${n}"
|
|
12
|
+
(id, direction, status, cursor, processed, changed, started_at, updated_at, error)
|
|
13
|
+
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)
|
|
14
|
+
ON CONFLICT(id) DO UPDATE SET
|
|
15
|
+
direction = excluded.direction,
|
|
16
|
+
status = excluded.status,
|
|
17
|
+
cursor = excluded.cursor,
|
|
18
|
+
processed = excluded.processed,
|
|
19
|
+
changed = excluded.changed,
|
|
20
|
+
updated_at = excluded.updated_at,
|
|
21
|
+
error = excluded.error`,t.id,t.direction,t.status,t.cursor,t.processed,t.changed,t.startedAt,t.updatedAt,t.error)},U=(e,t,s,r)=>(c(e,`INSERT INTO "${n}"
|
|
22
|
+
(id, direction, status, cursor, processed, changed, started_at, updated_at, error)
|
|
23
|
+
VALUES (?, ?, 'in_progress', NULL, 0, 0, ?, ?, NULL)
|
|
24
|
+
ON CONFLICT(id) DO UPDATE SET
|
|
25
|
+
status = 'in_progress',
|
|
26
|
+
updated_at = excluded.updated_at
|
|
27
|
+
WHERE
|
|
28
|
+
"${n}".direction <> excluded.direction
|
|
29
|
+
OR "${n}".status <> 'in_progress'
|
|
30
|
+
OR "${n}".updated_at IS NULL
|
|
31
|
+
OR "${n}".updated_at <= excluded.updated_at - ${String(D)}`,t,s,r,r),c(e,"SELECT changes() AS changed").one().changed>0),$=(e,t,s)=>{c(e,`UPDATE "${n}" SET updated_at = ? WHERE id = ? AND status = 'in_progress'`,s,t)},F=(e,t)=>{c(e,`UPDATE "${n}" SET updated_at = 0 WHERE id = ? AND status = 'in_progress'`,t)},B=(e,t)=>{if(c(e,"SELECT name FROM sqlite_master WHERE type = 'table' AND name = ? LIMIT 1",n).toArray().length===0)return[];const r=t===void 0?" ORDER BY id":" WHERE id = ?",i=t===void 0?[]:[t];return c(e,`SELECT * FROM "${n}"${r}`,...i).toArray().map(a=>({...N(a),error:typeof a.error=="string"?a.error:null,id:a.id,startedAt:typeof a.started_at=="number"?a.started_at:null,updatedAt:typeof a.updated_at=="number"?a.updated_at:null}))},w=async e=>{const{migration:t,sql:s,writer:r}=e,i=e.direction??"up",o=e.dryRun??!1,a=e.clock??(()=>Date.now()),R=e.maxBatches??Number.POSITIVE_INFINITY,I=e.batchSize??t.batchSize??x,L=i==="up"?t.up:t.down;if(!L)throw new b("INTERNAL",`data migration "${t.id}" has no \`${i}\` transform`);const O={db:{count:r.count.bind(r),findFirst:r.findFirst.bind(r),findMany:r.findMany.bind(r),get:r.get.bind(r)}};let T=null,_=0,g=0,A=a();if(!o){M(s);const d=h(s,t.id);if(d?.direction===i&&d.status==="completed")return{changed:d.changed,cursor:null,direction:i,dryRun:o,id:t.id,processed:d.processed,status:"completed"};if(d&&d.direction!==i&&C(s,t.id),!U(s,t.id,i,a())){const E=h(s,t.id);return{changed:E?.changed??0,cursor:E?.cursor??T,direction:i,dryRun:o,id:t.id,processed:E?.processed??0,status:E?.status??"in_progress"}}const l=d?.direction===i?d:void 0;l&&(T=l.cursor,_=l.processed,g=l.changed,A=l.startedAt??A)}let p=!1,m=0,f=A;try{for(;!p&&m<R;){const d=await r.findMany(t.table,{cursor:T,limit:I});for(const u of d.page){_+=1;const l=await L(u,O);if(l!==void 0&&(g+=1,o||await r.replace(String(u._id),{...l,_creationTime:u._creationTime,_id:u._id},void 0,{allowExplicitId:!0})),!o){const E=a();E-f>=y&&($(s,t.id,E),f=E)}}if(T=d.continueCursor,p=d.isDone,m+=1,!o){const u=a();S(s,{changed:g,cursor:p?null:T,direction:i,error:null,id:t.id,processed:_,startedAt:A,status:p?"completed":"in_progress",updatedAt:u}),f=u;try{await e.onBatch?.({batches:m,changed:g,processed:_})}catch{}}}}catch(d){throw o||S(s,{changed:g,cursor:T,direction:i,error:d instanceof Error?d.message:String(d),id:t.id,processed:_,startedAt:A,status:"failed",updatedAt:a()}),d}if(!o&&!p)try{F(s,t.id)}catch(d){console.warn(`data migration "${t.id}": releaseClaim failed`,d)}return{changed:g,cursor:p?null:T,direction:i,dryRun:o,id:t.id,processed:_,status:p?"completed":"in_progress"}};export{n as DATA_MIGRATION_STATE_TABLE,B as readMigrationStatus,w as runDataMigration};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{LunoraError as h}from"@lunora/errors";import{distinctValues as w}from"./applyOnDelete-BlcwKjuO.mjs";import{RELATION_EXISTS_KEY as N}from"./RELATION_EXISTS_KEY-CFUhnZSZ.mjs";const g={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}},T=new Set(Object.keys(g)),p=e=>{const t=g[e];if(!t)throw new h("INTERNAL",`unknown relation operator "${e}"`);return t},j=e=>e.kind==="one"?{clause:e.field,project:e.references}:{clause:e.references,project:e.field},S=5e3,l=Symbol("relation-key-overflow"),b=e=>Array.isArray(e)?e.map(t=>t??{}):[],R=e=>{if(e.length===1){const[t]=e;return t??{}}return e.length===0?{}:{AND:e}},y=e=>{if(e===null||typeof e!="object"||Array.isArray(e))return!1;const t=Object.keys(e);return t.length>0&&t.every(n=>T.has(n))},u=(e,t,n)=>{const r=t.tables[n]?.relationMap??{};return Object.keys(e).some(s=>{const a=e[s];return s==="AND"||s==="OR"?b(a).some(o=>u(o,t,n)):s==="NOT"?u(a??{},t,n):!!r[s]&&y(a)})},K=(e,t,n,r)=>{if(e&&u(e,t,n))throw new h("INTERNAL",`relation-crossing predicates are not supported in ${r}() — use them in findMany/findFirst or an RLS read policy`)},P=async(e,t,n,r,s)=>{const a=await d(t,e.table,r),{page:o}=await r.fetcher(e.table,{baseWhere:r.relationBaseWhere?.(e.table),relationBaseWhere:r.relationBaseWhere,where:a}),i=w(o,n);if(i.length>r.maxRelationKeys){if(s)return l;throw new h("INTERNAL",`relation predicate on "${e.table}" matched ${String(i.length)} rows, exceeding the ${String(r.maxRelationKeys)}-key limit; narrow the predicate (a same-shard EXISTS push-down lifts this cap)`)}return i},$=async(e,t,n,r,s)=>{const a=p(e),{clause:o,project:i}=j(t),c=await P(t,a.negateChild?{NOT:n}:n,i,r,s);return c===l?l:a.negated?a.nullDisjunct?{OR:[{[o]:{notIn:c}},{[o]:{isNull:!0}}]}:{[o]:{notIn:c}}:{[o]:{in:c}}},m=async(e,t,n,r,s)=>{const a=p(e),o=s.relationBaseWhere?.(t.table),i=a.negateChild?{NOT:n}:n,A={childWhere:await d(o?{AND:[o,i]}:i,t.table,s),negated:a.negated,parentTable:r,relation:t};return{[N]:A}},k=(e,t,n)=>{const r=g[e];if(r&&r.kind!==n.kind)throw new h("INTERNAL",`relation operator "${e}" requires a to-${r.kind} relation, but "${t}" is to-${n.kind}`)},I=async(e,t,n,r,s)=>{const a=[];for(const o of Object.keys(n)){k(o,e,t);const i=n[o]??{},c=s.canPushExists?.(t)??!1;if(c&&s.existsPushMode==="always"){a.push(await m(o,t,i,r,s));continue}const f=await $(o,t,i,s,c);f===l?a.push(await m(o,t,i,r,s)):a.push(f)}return R(a)},L=async(e,t,n,r)=>{if(e==="AND"||e==="OR"){const a=[];for(const o of b(t))a.push(await d(o,n,r));return{[e]:a}}if(e==="NOT")return{NOT:await d(t??{},n,r)};const s=r.schema.tables[n]?.relationMap?.[e];return s&&y(t)?I(e,s,t,n,r):{[e]:t}},d=async(e,t,n)=>{const r=[];for(const s of Object.keys(e))r.push(await L(s,e[s],t,n));return R(r)},v=async(e,t)=>!e||!u(e,t.schema,t.tableName)?e:d(e,t.tableName,{canPushExists:t.canPushExists,existsPushMode:t.existsPushMode??"auto",fetcher:t.fetcher,maxRelationKeys:t.maxRelationKeys??S,relationBaseWhere:t.relationBaseWhere,schema:t.schema}),O=(e,t,n)=>{for(const r of e){const s=E(r,t,n);if(s)return s}},M=(e,t,n,r)=>{if(e==="AND"||e==="OR")return O(b(t),n,r);if(e==="NOT")return O([t??{}],n,r);const s=n.tables[r]?.relationMap?.[e];if(!(!s||!y(t)))return n.tables[s.table]?.shardMode?.kind==="shardBy"?{relation:e,target:s.table}:O(Object.values(t),n,s.table)},E=(e,t,n)=>{for(const r of Object.keys(e)){const s=M(r,e[r],t,n);if(s)return s}},B=(e,t,n)=>{if(!e)return;const r=E(e,t,n);if(r)throw Object.assign(new Error(`shape on "${n}" joins the sharded table "${r.target}" via relation "${r.relation}" — a live shape cannot replicate rows that live in another shard's Durable Object. Fix it by (a) denormalizing the joined columns into "${n}", or (b) moving "${r.target}" to .global() so it is served through the latency-tiered D1 shape tier.`),{code:"SHAPE_CROSS_SHARD_JOIN",name:"LunoraError",status:400})};export{S as DEFAULT_MAX_RELATION_KEYS,K as assertFlatPredicate,B as assertShapeShardable,u as containsRelationPredicate,y as isRelationPredicate,v as resolveRelationPredicates};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{toErrorBody as P,LunoraError as x}from"@lunora/errors";import{e as v,d as b}from"./wire-codec-BU9T2xJ7.mjs";import{e as S,v as L,R as I,s as M,a as T,b as D}from"./sibling-channel-BRZpLiDA.mjs";import{relayName as u,DEFAULT_PROMOTION_THRESHOLDS as w,nextPromotionState as O,shapeRoutingKey as R,parseRelayName as k,clampPromotionThresholds as N}from"./DEFAULT_PROMOTION_THRESHOLDS-DVTD9iu0.mjs";import{encodeRowsPatch as C,buildPokeFrames as E}from"./buildPokeFrames-BXejpiII.mjs";import{awaitWsDrain as F,trySendFrame as _}from"./awaitWsDrain-kSGvAfw1.mjs";import{stableWireKey as m}from"./stableWireKey-BYB5GQJa.mjs";const U=2,W=8,g={},K=l=>{throw new x("INTERNAL",`unhandled relay frame: ${JSON.stringify(l)}`)},Y=l=>Response.json(l,{headers:{"content-type":"application/json"}}),f=()=>new Response(null,{status:204});class A{constructor(e,t){this.host=e,this.roleId=t}host;roleId;async handleControl(e){let t;try{t=await e.text()}catch{return new Response("bad request",{status:400})}if(!await L(this.host.env(),e.headers.get(I),t))return new Response("forbidden",{status:403});let s;try{s=JSON.parse(t)}catch{return new Response("bad request",{status:400})}switch(s.type){case"relay_attach":return this.onAttach(s.relayIndex),f();case"relay_detach":return this.onDetach(s.relayIndex),f();case"relay_frame":return this.host.deliverWhisperLocal(s.topic,s.frame,void 0),await this.onWhisperFrame(s),f();case"relay_shape_poke":{const r=this.host.getWebSockets().length,o=Date.now(),a=this.onShapePoke({...s,args:b(s.args)});return this.host.recordShapePokeFanout(r,a,Date.now()-o),f()}case"relay_shape_subscribe":return Y(this.onShapeSubscribe({...s,args:b(s.args)}));default:return K(s)}}maxRelays(){return S(this.host.env(),"LUNORA_MAX_RELAYS",W)}canAddressSiblings(){return this.siblingStub(this.roleId.ownerKey)!==void 0}siblingStub(e){return M(this.host.env(),this.host.shardBinding(),e)}async postRelayMessage(e,t){await this.requestRelayMessage(e,t)}async requestRelayMessage(e,t){const s=this.siblingStub(e);if(s===void 0)return;const r=JSON.stringify(t),o={"content-type":"application/json","x-lunora-shard-binding":this.host.shardBinding()??""},a=T(this.host.env());a!==void 0&&(o[I]=await D(a,r));try{return await s.fetch("https://relay.internal/_lunora/relay",{body:r,headers:o,method:"POST"})}catch{return}}}class H extends A{shapeUniformCache=new Map;relaySetCache;relayShapeRegistry=new Map;relayShapeProxies=new Map;promotionState="owned";constructor(e,t){super(e,{ownerKey:t})}async forwardWhisper(e,t){if(!this.canAddressSiblings())return;const s=this.ownerRelaySet();s.size!==0&&await Promise.all([...s].map(r=>this.postRelayMessage(u(this.roleId.ownerKey,r),{frame:t,topic:e,type:"relay_frame"})))}async onFlush(e,t){await Promise.all([this.multicastShapePokes(e,t),this.proxyShapePokes(e,t)])}seedRelayShape(){return Promise.resolve(void 0)}announce(){return Promise.resolve()}announceDrain(){return Promise.resolve()}relayCount(){const e=this.host.getWebSockets().length,t=S(this.host.env(),"LUNORA_RELAY_THRESHOLD",w.tUp),s=S(this.host.env(),"LUNORA_RELAY_COLLAPSE_THRESHOLD",w.tDown);if(this.promotionState=O(this.promotionState,e,N(t,s)),this.promotionState==="owned")return 0;const r=S(this.host.env(),"LUNORA_RELAY_FAN",U);return Math.min(this.maxRelays(),Math.max(1,r))}isShapeRelayUniform(e,t){const s=R(e,t),r=this.shapeUniformCache.get(s);if(r!==void 0)return r;const o=this.probeShapeRelayUniform(e,t);return this.shapeUniformCache.set(s,o),o}onAttach(e){this.addRelayToSet(e)}onDetach(e){this.removeRelayFromSet(e)}async onWhisperFrame(e){await Promise.all([...this.ownerRelaySet()].filter(t=>t!==e.originRelay).map(t=>this.postRelayMessage(u(this.roleId.ownerKey,t),{frame:e.frame,topic:e.topic,type:"relay_frame"})))}onShapeSubscribe(e){return this.buildShapeSeedFrames(e)}onShapePoke(){return 0}buildShapePoke(e,t,s,r,o){let a;try{a=this.host.resolveShape(e.name,e.args,t)}catch{return}if(a===void 0||a.global===!0||!s.has(a.table))return;const n=e,c=n.cursor,i=this.host.buildShapeDiff(a,c,r);if(i.length!==0)return n.cursor=r,{args:v(e.args),checkpoint:r,epoch:o,fromCursor:c,name:e.name,rowsPatch:C(i),type:"relay_shape_poke"}}async multicastShapePokes(e,t){if(this.relayShapeRegistry.size===0)return;const s=this.ownerRelaySet();if(s.size===0)return;const r=this.host.currentCdcEpoch(),o=[];for(const a of this.relayShapeRegistry.values()){const n=this.buildShapePoke(a,g,e,t,r);if(n)for(const c of s)o.push(this.postRelayMessage(u(this.roleId.ownerKey,c),n))}await Promise.all(o)}async proxyShapePokes(e,t){if(this.relayShapeProxies.size===0)return;const s=this.host.currentCdcEpoch(),r=[];for(const o of this.relayShapeProxies.values()){const a=this.buildShapePoke(o,o.identity,e,t,s);a&&r.push(this.postRelayMessage(u(this.roleId.ownerKey,o.relayIndex),{...a,targetConnectionId:o.connectionId}))}await Promise.all(r)}buildShapeSeedFrames(e){const t={identity:e.identity,userId:e.userId};let s;try{s=this.host.resolveShape(e.name,e.args,t)}catch(h){const{body:d}=P(h,{fallbackCode:"SHAPE_RESOLVE_FAILED",redactedMessage:"shape resolution failed"});return{error:{code:d.code,message:d.message}}}if(s===void 0||s.global===!0)return{error:{code:"SHAPE_NOT_FOUND",message:`shape not relayable: ${e.name}`}};e.relayIndex!==void 0&&this.addRelayToSet(e.relayIndex);const{baseCheckpoint:r,cursor:o,epoch:a,rowsPatch:n}=this.host.computeOpLogShapeSeed({args:e.args,name:e.name,sinceEpoch:e.sinceEpoch,sinceSeq:e.sinceSeq},s);let c=o;if(this.isShapeRelayUniform(e.name,e.args)){const h=R(e.name,e.args);let d=this.relayShapeRegistry.get(h);d===void 0&&(d={args:e.args,cursor:o,name:e.name},this.relayShapeRegistry.set(h,d)),c=d.cursor}else e.relayIndex!==void 0&&e.connectionId!==void 0&&this.relayShapeProxies.set(`${String(e.relayIndex)}:${e.connectionId}:${e.subId}`,{args:e.args,connectionId:e.connectionId,cursor:o,epoch:a,identity:t,name:e.name,relayIndex:e.relayIndex,subId:e.subId});const i=E([{rowsPatch:n,shapeId:e.subId}],{baseCheckpoint:r,checkpoint:o,epoch:a,lastMutationId:void 0,pokeId:this.host.nextPokeId()});return{cursor:c,epoch:a,frames:i}}ensureRelayTable(){this.host.sql().exec("CREATE TABLE IF NOT EXISTS __lunora_relays (idx INTEGER PRIMARY KEY)")}ownerRelaySet(){if(this.relaySetCache===void 0){this.ensureRelayTable();const e=this.host.sql().exec("SELECT idx FROM __lunora_relays").toArray();this.relaySetCache=new Set(e.map(t=>Number(t.idx)))}return this.relaySetCache}addRelayToSet(e){this.ensureRelayTable(),this.host.sql().exec("INSERT OR IGNORE INTO __lunora_relays (idx) VALUES (?)",e),this.ownerRelaySet().add(e)}removeRelayFromSet(e){this.ensureRelayTable(),this.host.sql().exec("DELETE FROM __lunora_relays WHERE idx = ?",e);const t=this.ownerRelaySet();t.delete(e);for(const[s,r]of this.relayShapeProxies)r.relayIndex===e&&this.relayShapeProxies.delete(s);t.size===0&&(this.relayShapeRegistry.clear(),this.shapeUniformCache.clear())}probeShapeRelayUniform(e,t){let s;try{s=this.host.resolveShape(e,t,g)}catch{return!1}if(s===void 0||s.global===!0||this.host.rlsMetadata().policies.some(i=>i.on==="read"&&i.table===s.table)||this.tableHasAnyMask(s.table))return!1;const r=m(s.effectiveWhere),o=m(s.columns);let a=!1;const n=i=>{const h={groups:[`grp_${i}`],roles:[i],sub:`__lunora_probe_${i}__`};return{identity:new Proxy(h,{get:(y,p)=>typeof p=="symbol"||p in y?Reflect.get(y,p):`${i}:${p}`,getOwnPropertyDescriptor:(y,p)=>(a=!0,Reflect.getOwnPropertyDescriptor(y,p)),has:(y,p)=>typeof p=="symbol"?Reflect.has(y,p):!0,ownKeys:y=>(a=!0,Reflect.ownKeys(y))}),userId:`__lunora_probe_${i}__`}};return[g,n("a"),n("b")].every(i=>{let h;try{h=this.host.resolveShape(e,t,i)}catch{return!1}return h!==void 0&&h.global!==!0&&h.table===s.table&&m(h.effectiveWhere)===r&&m(h.columns)===o})&&!a}tableHasAnyMask(e){return this.host.maskMetadata().columns.some(t=>t.table===e)}}class $ extends A{relayAnnounced=!1;shapeRelayMemos=new WeakMap;constructor(e,t,s){super(e,{ownerKey:t,relayIndex:s})}async forwardWhisper(e,t){this.canAddressSiblings()&&await this.postRelayMessage(this.roleId.ownerKey,{frame:t,originRelay:this.roleId.relayIndex,topic:e,type:"relay_frame"})}onFlush(){return Promise.resolve()}async seedRelayShape(e,t,s,r){if(!this.canAddressSiblings())return{code:"RELAY_MISCONFIGURED",message:"relay cannot address its owner"};await this.announce();const o={args:v(s.args??{}),connectionId:this.host.readAttachment(e).connectionId,identity:r.identity,name:s.name,relayIndex:this.roleId.relayIndex,sinceEpoch:s.sinceEpoch,sinceSeq:s.sinceSeq,subId:t,type:"relay_shape_subscribe",userId:r.userId},a=await this.requestRelayMessage(this.roleId.ownerKey,o);if(a===void 0)return{code:"RELAY_SEED_FAILED",message:"owner did not answer the shape seed"};let n;try{n=await a.json()}catch{return{code:"RELAY_SEED_FAILED",message:"malformed shape seed from owner"}}if(n.error!==void 0)return n.error;if(n.frames===void 0)return{code:"RELAY_SEED_FAILED",message:"owner returned no shape frames"};await F(e);for(const c of n.frames)_(e,c);return this.recordRelayShapeMemo(e,t,n.cursor??0,n.epoch),"ok"}async announce(){if(this.relayAnnounced||!this.canAddressSiblings())return;this.relayAnnounced=!0,(await this.requestRelayMessage(this.roleId.ownerKey,{relayIndex:this.roleId.relayIndex,type:"relay_attach"}))?.ok||(this.relayAnnounced=!1)}async announceDrain(e){this.canAddressSiblings()&&(this.host.getWebSockets().some(t=>t!==e)||(this.relayAnnounced=!1,await this.postRelayMessage(this.roleId.ownerKey,{relayIndex:this.roleId.relayIndex,type:"relay_detach"})))}relayCount(){return 0}isShapeRelayUniform(){return!1}onAttach(){}onDetach(){}onWhisperFrame(){return Promise.resolve()}onShapeSubscribe(){return{error:{code:"RELAY_CANNOT_SEED",message:"a relay has no op-log to seed from"}}}onShapePoke(e){return this.deliverShapePoke(e)}recordRelayShapeMemo(e,t,s,r){let o=this.shapeRelayMemos.get(e);o===void 0&&(o=new Map,this.shapeRelayMemos.set(e,o)),o.set(t,{cursor:s,epoch:r})}deliverShapePoke(e){const t=R(e.name,e.args);let s=0;for(const r of this.host.getWebSockets()){const o=this.host.readAttachment(r),{shapes:a}=o,n=this.shapeRelayMemos.get(r);if(!(a===void 0||n===void 0)&&!(e.targetConnectionId!==void 0&&o.connectionId!==e.targetConnectionId))for(const[c,i]of Object.entries(a)){const h=n.get(c);if(h?.cursor!==e.fromCursor||h.epoch!==e.epoch||R(i.name,i.args)!==t)continue;const d=E([{rowsPatch:e.rowsPatch,shapeId:c}],{baseCheckpoint:void 0,checkpoint:e.checkpoint,epoch:e.epoch,lastMutationId:void 0,pokeId:this.host.nextPokeId()},{preEncoded:!0});for(const y of d)_(r,y);n.set(c,{cursor:e.checkpoint,epoch:e.epoch}),s+=1}}return s}}const Q=l=>{const e=l.doName();if(e===void 0)return;const t=k(e);return t===void 0?new H(l,e):new $(l,t.ownerKey,t.relayIndex)};export{W as DEFAULT_MAX_RELAYS,H as OwnerRelay,$ as RelayMember,Q as createRelayLink};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{LunoraError as m}from"@lunora/errors";import{stableWireKey as a}from"./stableWireKey-BYB5GQJa.mjs";const i="::relay::",f=(t,n)=>`${t}${i}${String(n)}`,s=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}},d=(t,n)=>a({args:n??{},name:t}),c={tDown:4e3,tUp:8e3},l=(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"},g=(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,i as RELAY_NAME_INFIX,g as clampPromotionThresholds,l as nextPromotionState,s as parseRelayName,N as relayCountFor,f as relayName,d as shapeRoutingKey};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{LunoraError as i}from"@lunora/errors";import{e}from"./estimate-bytes-CzG5x1f8.mjs";const r={maxReadRows:1e5,maxWrittenBytes:32*1024*1024,maxWrittenRows:5e4};class w{readRows=0;writtenRows=0;writtenBytes=0;limits;constructor(t={}){this.limits={...r,...t}}recordRead(t){if(this.readRows+=t,this.readRows>this.limits.maxReadRows)throw new i("TRANSACTION_LIMIT_EXCEEDED",`this transaction read ${String(this.readRows)} documents, over the ${String(this.limits.maxReadRows)}-document limit`)}recordWrite(t){const s=e(t);if(s===void 0)throw new i("BAD_REQUEST","this document is not JSON-serializable (cyclic or non-JSON value); it cannot be written");if(this.writtenRows+=1,this.writtenBytes+=s,this.writtenRows>this.limits.maxWrittenRows)throw new i("TRANSACTION_LIMIT_EXCEEDED",`this transaction wrote ${String(this.writtenRows)} documents, over the ${String(this.limits.maxWrittenRows)}-document limit`);if(this.writtenBytes>this.limits.maxWrittenBytes)throw new i("TRANSACTION_LIMIT_EXCEEDED",`this transaction wrote ${String(this.writtenBytes)} bytes, over the ${String(this.limits.maxWrittenBytes)}-byte limit`)}headroom(){return{readRows:this.readRows,remainingReadRows:Math.max(0,this.limits.maxReadRows-this.readRows),remainingWrittenBytes:Math.max(0,this.limits.maxWrittenBytes-this.writtenBytes),remainingWrittenRows:Math.max(0,this.limits.maxWrittenRows-this.writtenRows),writtenBytes:this.writtenBytes,writtenRows:this.writtenRows}}}export{r as DEFAULT_TRANSACTION_LIMITS,w as TransactionHeadroomTracker};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{toErrorBody as f,LunoraError as S}from"@lunora/errors";import{e as k}from"./wire-codec-BU9T2xJ7.mjs";import{readStreamRun as p,deleteStreamRun as T,claimStreamRun as _,appendStreamChunk as w,finishStreamRun as R,trimStreamRuns as A,readStreamChunks as y}from"./appendStreamChunk-CH4e4nJn.mjs";const E=5e4,g=64*1024*1024,b=864e5,M=36e5,N=(d,e)=>d===void 0||e.live?"attach":d.status==="complete"||d.status==="error"?e.resuming?"replay-terminal":"reclaim":e.resuming?"interrupted":"reclaim";class U{lastTrimAt=0;runs=new Map;sql;waitUntil;constructor(e){this.sql=e.sql,this.waitUntil=e.waitUntil}async attach(e){try{await this.attachOrThrow(e)}catch(r){const{body:t,redacted:i}=f(r,{fallbackCode:"INTERNAL_SERVER_ERROR",redactedMessage:"internal error"});i&&console.error("[@lunora/shard-engine] durable stream attach failed:",r),e.sink.fail({code:t.code,message:t.message})}}detach(e,r){this.runs.get(e)?.sinks.delete(r)}isLive(e){return this.runs.has(e)}async attachOrThrow(e){const r=this.sql(),{runKey:t,sinceChunk:i,sink:o}=e,s=p(r,t),u=i>0,a=this.runs.get(t),n=N(s,{live:a!==void 0,resuming:u}),c=()=>{for(const h of y(r,t,i))if(!o.chunk({data:JSON.parse(h.dataJson),seq:h.seq}))return!1;return!0};if(n==="replay-terminal"){c()&&(s?.status==="error"?o.fail({code:s.errorCode??"INTERNAL_SERVER_ERROR",message:s.error??"stream failed"}):o.complete());return}if(n==="interrupted"){c()&&o.fail({code:"STREAM_INTERRUPTED",message:"the producer for this durable stream did not survive; start a new run"});return}if(a){c()&&a.sinks.add(o);return}n==="reclaim"&&T(r,t),this.trim(r),_(r,t,Date.now(),e.ttlMs??b);const l={sinks:new Set([o])};this.runs.set(t,l);const m=this.produce(t,e.iterator,l);this.waitUntil?.(m),await m}async produce(e,r,t){const i=this.sql(),o=new AbortController;let s=0,u=0;try{for await(const a of r(o.signal)){const n=k(a),c=JSON.stringify(n);if(s+=1,u+=c.length,s>E||u>g)throw new S("STREAM_TOO_LONG",`durable stream exceeded its ceiling (${String(E)} chunks / ${String(g)} bytes); yield less, or drop \`durable\``,{status:507});w(i,e,s,c);for(const l of t.sinks)l.chunk({data:n,seq:s})||t.sinks.delete(l)}R(i,e,"complete",s);for(const a of t.sinks)a.complete()}catch(a){const{body:n,redacted:c}=f(a,{fallbackCode:"INTERNAL_SERVER_ERROR",redactedMessage:"internal error"});c&&console.error("[@lunora/shard-engine] unhandled durable stream error:",a),R(i,e,"error",s,{code:n.code,message:n.message});for(const l of t.sinks)l.fail({code:n.code,message:n.message})}finally{this.runs.delete(e)}}trim(e){const r=Date.now();if(!(r-this.lastTrimAt<=M)){this.lastTrimAt=r;try{A(e,r)}catch{}}}}export{U as DurableStreamRunner,g as MAX_DURABLE_STREAM_BYTES,E as MAX_DURABLE_STREAM_CHUNKS,N as decideDurableAttach};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
const m="0123456789bcdefghjkmnpqrstuvwxyz",k=9,p=63710088e-1,d=Math.PI/180,f=[Number.POSITIVE_INFINITY,5009400,1252300,156500,39100,4900,1200,152.9,38.2,4.77,1.19,.149,.037],S=f.map((t,n)=>n%2===0?t/2:t),I=.01,C=Math.acos(I)/d,z=2,_=t=>t/p/d,R=t=>{const n=5*t;return{latBands:2**Math.floor(n/2),lngSectors:2**Math.ceil(n/2)}},T=t=>Math.min(Math.max(Math.trunc(t),1),12),b=(t,n)=>{const a=T(n);let s=-90,o=90,e=-180,c=180,r="",g=0,l=0,u=!0;for(;r.length<a;){if(u){const h=(e+c)/2;t.lng>=h?(l=l*2+1,e=h):(l*=2,c=h)}else{const h=(s+o)/2;t.lat>=h?(l=l*2+1,s=h):(l*=2,o=h)}u=!u,g<4?g+=1:(r+=m[l]??"0",g=0,l=0)}return r},v=(t,n)=>Math.min(90,Math.abs(t)+_(n)),j=(t,n)=>{const a=(n.lat-t.lat)*d,s=(n.lng-t.lng)*d,o=t.lat*d,e=n.lat*d,c=Math.sin(a/2)**2+Math.cos(o)*Math.cos(e)*Math.sin(s/2)**2;return 2*p*Math.asin(Math.min(1,Math.sqrt(c)))},y=(t,n)=>{const a=Math.max(Math.cos(v(n,t)*d),I);for(let s=f.length-1;s>=1;s-=1){const o=f[s],e=S[s];if(o!==void 0&&e!==void 0&&o*a>=t&&e>=t)return s}return 1},B={east:["bc01fg45238967deuvhjyznpkmstqrwx","p0r21436x8zb9dcf5h7kjnmqesgutwvy"],north:["p0r21436x8zb9dcf5h7kjnmqesgutwvy","bc01fg45238967deuvhjyznpkmstqrwx"],south:["14365h7k9dcfesgujnmqp0r2twvyx8zb","238967debc01fg45kmstqrwxuvhjyznp"],west:["238967debc01fg45kmstqrwxuvhjyznp","14365h7k9dcfesgujnmqp0r2twvyx8zb"]},P={east:["bcfguvyz","prxz"],north:["prxz","bcfguvyz"],south:["028b","0145hjnp"],west:["0145hjnp","028b"]},i=(t,n)=>{const a=t.toLowerCase(),s=a.at(-1)??"";let o=a.slice(0,-1);const e=a.length%2===0?0:1;return P[n][e].includes(s)&&o!==""&&(o=i(o,n)),o+(m[B[n][e].indexOf(s)]??"")},q=(t,n,a)=>{const s=Math.min(a,z),{latBands:o,lngSectors:e}=R(s),c=180/o,r=360/e,g=_(n),l=Math.max(-90,t.lat-g),u=Math.min(90,t.lat+g),h=new Set;for(let M=0;M<o;M+=1){const w=-90+M*c;if(w+c<l||w>u)continue;const x=w+c/2;for(let E=0;E<e;E+=1){const L=-180+(E+.5)*r;h.add(b({lat:x,lng:L},s))}}return[...h]},A=(t,n)=>{const a=Math.max(n,1),s=y(a,t.lat);if(v(t.lat,a)>=C)return q(t,a,s);const e=b(t,s),c=i(e,"north"),r=i(e,"south"),g=[e,c,r,i(e,"east"),i(e,"west"),i(c,"east"),i(c,"west"),i(r,"east"),i(r,"west")];return[...new Set(g)]},G=(t,n)=>t.lat>=n.sw.lat&&t.lat<=n.ne.lat&&t.lng>=n.sw.lng&&t.lng<=n.ne.lng,D=t=>({lat:(t.sw.lat+t.ne.lat)/2,lng:(t.sw.lng+t.ne.lng)/2}),H=t=>{const n=D(t);return A(n,Math.max(j(n,t.ne),1))};export{k as GEO_DEFAULT_PRECISION,D as boundingBoxCenter,H as boundingBoxGeohashes,A as coveringGeohashes,b as encodeGeohash,j as haversineMeters,G as pointInBoundingBox};
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
import{sql as e}from"drizzle-orm";import{runDrizzle as i}from"./runDrizzle-it6rL9bR.mjs";const r="__global_shape_snapshot",T=n=>{i(n,e`CREATE TABLE IF NOT EXISTS ${e.identifier(r)} (
|
|
2
|
+
connection_id TEXT NOT NULL,
|
|
3
|
+
sub_id TEXT NOT NULL,
|
|
4
|
+
members TEXT NOT NULL,
|
|
5
|
+
PRIMARY KEY (connection_id, sub_id)
|
|
6
|
+
)`)},b=(n,o,t)=>{const s=i(n,e`SELECT members FROM ${e.identifier(r)} WHERE connection_id = ${o} AND sub_id = ${t} LIMIT 1`).toArray()[0]?.members;if(s===void 0)return new Map;try{const c=JSON.parse(s);return c===null||typeof c!="object"?new Map:new Map(Object.entries(c))}catch{return new Map}},p=(n,o,t,a)=>{const s=JSON.stringify(Object.fromEntries(a));i(n,e`INSERT INTO ${e.identifier(r)} (connection_id, sub_id, members) VALUES (${o}, ${t}, ${s})
|
|
7
|
+
ON CONFLICT(connection_id, sub_id) DO UPDATE SET members = excluded.members`)},S=(n,o,t)=>{i(n,e`DELETE FROM ${e.identifier(r)} WHERE connection_id = ${o} AND sub_id = ${t}`)},m=(n,o)=>{i(n,e`DELETE FROM ${e.identifier(r)} WHERE connection_id = ${o}`)};export{r as GLOBAL_SHAPE_SNAPSHOT_TABLE,S as deleteGlobalShapeSnapshot,m as deleteGlobalShapeSnapshotsForConnection,T as migrateGlobalShapeSnapshot,b as readGlobalShapeSnapshot,p as writeGlobalShapeSnapshot};
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
import{sql as t}from"drizzle-orm";import{runDrizzle as n}from"./runDrizzle-it6rL9bR.mjs";const r="__idempotency",m=i=>{n(i,t`CREATE TABLE IF NOT EXISTS ${t.identifier(r)} (
|
|
2
|
+
identity TEXT NOT NULL,
|
|
3
|
+
mutation_id TEXT NOT NULL,
|
|
4
|
+
result_json TEXT NOT NULL,
|
|
5
|
+
ts REAL NOT NULL,
|
|
6
|
+
PRIMARY KEY (identity, mutation_id)
|
|
7
|
+
)`)},L=(i,e,s)=>{const o=n(i,t`SELECT result_json, ts FROM ${t.identifier(r)} WHERE identity = ${e} AND mutation_id = ${s} LIMIT 1`).toArray()[0];return o===void 0?void 0:{resultJson:o.result_json,ts:o.ts}},N=(i,e,s,E,o)=>{n(i,t`INSERT OR IGNORE INTO ${t.identifier(r)} (identity, mutation_id, result_json, ts) VALUES (${e}, ${s}, ${E}, ${o})`)},I=(i,e)=>{n(i,t`DELETE FROM ${t.identifier(r)} WHERE ts < ${e}`)};export{r as IDEMPOTENCY_TABLE,m as migrateIdempotency,L as readIdempotent,I as trimIdempotent,N as writeIdempotent};
|
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
import{runSql as c,decodeJsonColumn as a,orNull as o}from"./runDrizzle-it6rL9bR.mjs";const e="__lunora_mail",l=500,i=256*1024,n=t=>t!==void 0&&t.length>i?`${t.slice(0,i)}
|
|
2
|
+
… [truncated by the dev mail catcher]`:t,s=t=>t===void 0?null:JSON.stringify(t),_=t=>{c(t,`CREATE TABLE IF NOT EXISTS "${e}" (
|
|
3
|
+
id TEXT PRIMARY KEY,
|
|
4
|
+
captured_at INTEGER NOT NULL,
|
|
5
|
+
from_addr TEXT,
|
|
6
|
+
to_addrs TEXT NOT NULL,
|
|
7
|
+
cc_addrs TEXT,
|
|
8
|
+
bcc_addrs TEXT,
|
|
9
|
+
reply_to TEXT,
|
|
10
|
+
subject TEXT NOT NULL,
|
|
11
|
+
html TEXT,
|
|
12
|
+
body_text TEXT,
|
|
13
|
+
headers TEXT
|
|
14
|
+
)`)},N=(t,r,T)=>{_(t);const E=crypto.randomUUID();return c(t,`INSERT INTO "${e}" (id, captured_at, from_addr, to_addrs, cc_addrs, bcc_addrs, reply_to, subject, html, body_text, headers)
|
|
15
|
+
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,E,T,o(r.from),JSON.stringify(r.to),s(r.cc),s(r.bcc),o(r.replyTo),r.subject,o(n(r.html)),o(n(r.text)),s(r.headers)),c(t,`DELETE FROM "${e}"
|
|
16
|
+
WHERE id NOT IN (
|
|
17
|
+
SELECT id FROM "${e}" ORDER BY captured_at DESC, id DESC LIMIT ?
|
|
18
|
+
)`,l),{id:E}},u=(t,r={})=>{_(t);const T=Math.min(Math.max(r.limit??50,1),l);return{entries:c(t,`SELECT * FROM "${e}" ORDER BY captured_at DESC, id DESC LIMIT ?`,T).toArray().map(d=>({bcc:a(d.bcc_addrs),capturedAt:d.captured_at,cc:a(d.cc_addrs),from:d.from_addr??void 0,headers:a(d.headers),html:d.html??void 0,id:d.id,replyTo:d.reply_to??void 0,subject:d.subject,text:d.body_text??void 0,to:a(d.to_addrs)??d.to_addrs}))}},M=t=>(_(t),c(t,`DELETE FROM "${e}"`),{cleared:!0});export{l as MAIL_RETENTION,e as MAIL_TABLE,i as MAX_BODY_CHARS,M as clearCapturedMail,_ as ensureMailTable,u as readCapturedMail,N as recordCapturedMail};
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
import{LunoraError as u}from"@lunora/errors";const g=/^(?:explain\s+(?:query\s+plan\s+)?)?(?:select|with)\b/iu,f=/\b(?:alter|attach|create|delete|detach|drop|insert|pragma|reindex|replace|truncate|update|vacuum)\b/iu,h=/^\w+/u,m=/;\s*$/u,E=/\s/u,L=(n,e)=>{let t=e+2;for(;t<n.length&&n[t]!==`
|
|
2
|
+
`;)t+=1;return t},S=(n,e)=>{const t=n.indexOf("*/",e+2);return t===-1?-1:t+2},p=n=>{let e=0;for(;e<n.length;){const t=n[e];if(t!==void 0&&E.test(t))e+=1;else if(t==="-"&&n[e+1]==="-")e=L(n,e);else if(t==="/"&&n[e+1]==="*"){const s=S(n,e);if(s===-1)break;e=s}else break}return e},d=n=>{const e=p(n),t=n.slice(e).trimEnd();if(t==="")return{code:"SQL_EMPTY",message:"the query is empty"};const s=t.replace(m,""),c=s.indexOf(";");if(c!==-1)return{code:"SQL_MULTIPLE_STATEMENTS",length:1,message:"only a single statement may be run",offset:e+c};const i="the SQL editor is read-only — only SELECT / WITH / EXPLAIN queries are allowed";if(!g.test(s))return{code:"SQL_NOT_READONLY",length:h.exec(s)?.[0].length??1,message:i,offset:e};const o=f.exec(s);if(o!==null)return{code:"SQL_NOT_READONLY",length:o[0].length,message:`${i} (\`${o[0].toUpperCase()}\` is not allowed)`,offset:e+o.index}},l=1e3,A=n=>{const e=d(n);if(e!==void 0)throw new u(e.code,e.message,{status:400})},O=(n,e)=>{A(e);const t=n.exec(e).toArray(),s=t.length>l?t.slice(0,l):t;return{columns:s.length>0?Object.keys(s[0]):[],rowCount:t.length,rows:s,truncated:t.length>l}},y=/near "([^"]*)": syntax error/iu,N=/^SCAN (?:TABLE )?(?!CONSTANT\b|SUBQUERY\b)([^\s(]+)/u,x=(n,e)=>{if(e==="")return{};const t=n.indexOf(e);return t===-1?{}:{length:e.length,offset:t}},_=(n,e)=>{const t=d(e);if(t!==void 0)return{diagnostics:t.code==="SQL_EMPTY"?[]:[{length:t.length,message:t.message,offset:t.offset,severity:"error",source:"gate"}],plan:[]};let s;try{s=n.exec(`EXPLAIN QUERY PLAN ${e}`).toArray().map(o=>{const{detail:r}=o;return typeof r=="string"?r:""}).filter(o=>o!=="")}catch(o){const r=o instanceof Error?o.message:String(o),a=y.exec(r);return{diagnostics:[{...a?x(e,a[1]??""):{},message:r,severity:"error",source:"syntax"}],plan:[]}}const c=[],i=new Set;for(const o of s){const r=N.exec(o);if(r){const a=r[1]??"";i.has(a)||(i.add(a),c.push({message:`full table scan on \`${a}\` — this query reads every row`,severity:"warning",source:"plan"}))}}return{diagnostics:c,plan:s}};export{l as MAX_SQL_ROWS,A as assertReadonly,_ as lintReadonlySql,O as runReadonlySql};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{LunoraError as E}from"@lunora/errors";import{s as Ut,c as Pt,j as Oe,a as Gt,y as Ae,h as Ht}from"./ctx-db-companions-lTt-rvKG.mjs";import{sql as r}from"drizzle-orm";import{d as Nt}from"./wire-codec-BU9T2xJ7.mjs";import{throwingScheduler as jt,aggregateSqlFunction as ve,normalizeCountArgument as Kt}from"./AGGREGATE_SQL_FUNCTION-m1iUU1rv.mjs";import{aggregateTableName as Le,encodeAggregateKey as Fe,readAggregateValue as We}from"./aggregateTableName-Cy5e03oz.mjs";import{mergeWhere as z,CountRlsUnsupportedError as Be,selectIndexForGroupBy as Ot,selectIndexForCount as Qt,selectIndexForAggregate as zt}from"./CountRlsUnsupportedError-Bdfupt3g.mjs";import{backfillSearchIndexesForTable as Jt}from"./backfillAggregateIndexes-DVQ2sVuV.mjs";import{backfillAggregateIndexes as Br,backfillRankIndexes as qr,backfillSearchIndexes as Ur}from"./backfillAggregateIndexes-DVQ2sVuV.mjs";import{appendCdcChange as Vt}from"./CDC_LOG_TABLE-B58N8NQO.mjs";import{CDC_LOG_TABLE as Gr,applyCdcChanges as Hr,bumpCdcEpoch as Nr,minCdcSeq as jr,readCdcChanges as Kr,readCdcCursor as Or,readCdcEpoch as Qr,trimCdcChanges as zr}from"./CDC_LOG_TABLE-B58N8NQO.mjs";import{computeRankPage as st}from"./computeRankPage-Bby1Npkd.mjs";import{SCAN_DEP as H}from"./SCAN_DEP-D7qE3iUe.mjs";import{runDrizzle as q}from"./runDrizzle-it6rL9bR.mjs";import{D as N,k as ce,r as le,b as Ie,A as qe,a as Ce,e as V,t as At,f as ct,i as Yt,h as vt,g as Xt}from"./do-sql-Dk_DJxn4.mjs";import{WORKERD_SQLITE_LIMITS as It,unionAll as He,sqliteInList as Zt}from"./param-Ib8WHnrF.mjs";import{coveringGeohashes as en,boundingBoxGeohashes as tn,haversineMeters as nn,pointInBoundingBox as rn}from"./GEO_DEFAULT_PRECISION-CqpQZ-J_.mjs";import{NotFoundError as on}from"./NotFoundError-BhF7FeFr.mjs";import{softDeleteScope as de,normalizeOrderKeys as sn,buildSeekWhere as Ct,decodeCursor as Ne,applySelect as at,encodeCursor as je,buildSeekBeforeWhere as cn}from"./applySelect-BQbHyo-W.mjs";import{rankTableName as dt,sortColumnName as lt,resolveRankPartition as an,encodePartitionKey as dn,RANK_TIEBREAK as ln}from"./RANK_TIEBREAK-ci3MaM65.mjs";import{indexKeysForRow as un,buildIndexRange as fn}from"./buildIndexRange-CBKQmHSS.mjs";import{assertFlatPredicate as Ue,resolveRelationPredicates as ut}from"./DEFAULT_MAX_RELATION_KEYS-BAWGIEvC.mjs";import{runRowValidators as Pe,resolveWith as ft,relationHooks as ht,applyOnDelete as hn,fanOutScalarCounts as wn}from"./applyOnDelete-BlcwKjuO.mjs";import{guardWriter as pn}from"./RLS_UNWRAP_SYMBOL-BWloGsd3.mjs";import{i as gn}from"./sql-projection-BqmxFxQU.mjs";import{createSystemReader as $n}from"./createSystemReader-BtYeSMDb.mjs";import{ConflictError as pe}from"./ConflictError-C8GtJmjS.mjs";import{runTriggers as yn}from"./hasTrigger-CjlwI4le.mjs";import{compileWhereSql as te}from"./compileWhereSql-JBpSfQm9.mjs";import{CLIENT_WATERMARK_TABLE as Vr,advanceClientWatermark as Yr,migrateClientWatermark as Xr,readClientWatermark as Zr}from"./CLIENT_WATERMARK_TABLE-BoS1HEqz.mjs";import{GLOBAL_SHAPE_SNAPSHOT_TABLE as to,deleteGlobalShapeSnapshot as no,deleteGlobalShapeSnapshotsForConnection as ro,migrateGlobalShapeSnapshot as oo,readGlobalShapeSnapshot as io,writeGlobalShapeSnapshot as so}from"./GLOBAL_SHAPE_SNAPSHOT_TABLE-NWaL77m5.mjs";import{IDEMPOTENCY_TABLE as ao,readIdempotent as lo,trimIdempotent as uo,writeIdempotent as fo}from"./IDEMPOTENCY_TABLE-DKVe2Ohf.mjs";import{runShardMigrations as wo}from"./runShardMigrations-Crppyq1f.mjs";import{SEARCH_STATE_TABLE as go}from"./SEARCH_STATE_TABLE-Dju8ebbU.mjs";import{selectShapeMemberIds as yo,selectShapeRows as Eo}from"./selectShapeMemberIds-B-pQJHAu.mjs";import{serializeSqlValue as ie}from"./serializeSqlValue-DbI1VQYM.mjs";import{quoteIdentifier as En}from"./quoteIdentifier-CObIFRhb.mjs";const mn=o=>{const i=new TextEncoder().encode(o);let t="";for(const a of i)t+=String.fromCodePoint(a);return btoa(t)},Sn=o=>{const i=atob(o),t=Uint8Array.from(i,a=>a.codePointAt(0)??0);return new TextDecoder().decode(t)},_n=()=>new E("BAD_REQUEST","invalid cursor"),wt=16,pt=8,X=1024,Qe=(o,i)=>i.query(o),Rn=(o,i,t)=>{const a=Ut(o,t);if(a.length===0)return 0;let f=0;for(const[p,m]of i.entries()){const v=p===i.length-1;let S=0;for(const $ of a)(v?$.startsWith(m):$===m)&&(S+=1);if(S===0)return 0;f+=S}return f},Tn=(o,i)=>{if(!i)return{exact:!0,lower:o,upper:o};const t=[...o].at(-1)??"",a=(t.codePointAt(0)??0)+1;if(a>=55296&&a<=57343||a>1114111)return{exact:!0,lower:o,upper:o};const f=o.slice(0,o.length-t.length);return{exact:!1,lower:o,upper:f+String.fromCodePoint(a)}},An=(o,i,t)=>{const a={eq:(f,p)=>{if(!o.definition.filterFields?.includes(f))throw new E("INTERNAL",`field "${f}" is not a filter field of search index "${o.indexName}" on table "${i}"`);if(o.filters.length>=pt)throw new E("BAD_REQUEST",`search index "${o.indexName}" on table "${i}": at most ${String(pt)} .eq() filters are supported per search query`);return o.filters.push({field:f,value:p}),a},search:(f,p)=>{const m=o;if(f!==m.definition.field)throw new E("INTERNAL",`search index "${m.indexName}" on table "${i}" indexes "${m.definition.field}", not "${f}"`);const v=Qe(p,t).length;if(v>wt)throw new E("BAD_REQUEST",`search index "${m.indexName}" on table "${i}": at most ${String(wt)} search terms are supported (got ${String(v)})`);return m.field=f,m.query=p,m.hasQuery=!0,a}};return a},vn=o=>{if(o.length>X)throw new E("BAD_REQUEST",`more than ${String(X)} documents match this search — narrow it with filters or read it a page at a time with .paginate()`)},In=o=>Math.min(o.offset+o.numItems+1,X),Cn=o=>mn(`search:${String(o)}`),xn=o=>{let i;try{i=Sn(o)}catch{return}if(!i.startsWith("search:"))return;const t=Number(i.slice(7));return Number.isInteger(t)&&t>=0?t:void 0},Mn=o=>{if(typeof o.endCursor=="string")throw new E("BAD_REQUEST","bounded (endCursor) pagination is not supported on search queries — relevance order has no stable range boundary");const i=Math.max(0,Math.floor(o.numItems)),t=o.cursor?xn(o.cursor):0;if(t===void 0)throw _n();if(t+i>X)throw new E("BAD_REQUEST",`search pagination reaches past the ${String(X)}-document limit (offset ${String(t)} + ${String(i)} requested) — narrow the query or the filters instead`);return{numItems:i,offset:t}},bn=(o,i)=>{const t=i.offset+i.numItems,a=i.numItems>0&&o.length>t;return{continueCursor:a?Cn(t):null,isDone:!a,page:o.slice(i.offset,t)}},Dn=o=>{if(o===void 0)return X+1;if(!Number.isFinite(o))return X;const i=Math.max(0,Math.floor(o));if(i>X)throw new E("BAD_REQUEST",`search returns at most ${String(X)} documents (asked for ${String(i)}) — narrow the query or paginate instead`);return i},kn=/^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/iu,Ln=o=>{if(!kn.test(o))throw new E("INTERNAL",`invalid clientId ${JSON.stringify(o)}: a client-supplied row id must be a UUID`)},gt=50,xt=500,$t=Math.floor(It.boundParams/3),we=It.boundParams,Fn=128,ae=(o,i,t)=>{const a=i??xt;if(o>a)throw new E("BATCH_LIMIT_EXCEEDED",`${t}: batch of ${String(o)} exceeds the limit of ${String(a)} (raise options.limit or chunk the call)`,{status:400})},Wn=o=>{const i={eq:(t,a)=>(o.sqlConditions.push({comparator:"=",field:t,value:a}),i),gt:(t,a)=>(o.sqlConditions.push({comparator:">",field:t,value:a}),i),gte:(t,a)=>(o.sqlConditions.push({comparator:">=",field:t,value:a}),i),lt:(t,a)=>(o.sqlConditions.push({comparator:"<",field:t,value:a}),i),lte:(t,a)=>(o.sqlConditions.push({comparator:"<=",field:t,value:a}),i)};return i},Bn=o=>Math.max(o,X),Mt=(o,i)=>{const t=o.filters.map(a=>r`${V(a.field)} = ${ie(a.value)}`);return i&&t.push(i),t},qn=(o,i,t,a,f)=>{const p=Qe(t.query,Oe(t.definition.language));if(p.length===0)return[];const m=Gt(i,t.indexName),v=`${m}__vocab`,S=p.length-1,$=p.map((F,k)=>{const j=Tn(F,k===S),K=j.exact?r`${r.identifier("term")} = ${j.lower}`:r`${r.identifier("term")} >= ${j.lower} AND ${r.identifier("term")} < ${j.upper}`;return r`SELECT ${r.identifier("doc")}, ${r.raw(String(k))} AS ${r.identifier("__term__")}, COUNT(*) AS ${r.identifier("__n__")} FROM ${r.identifier(v)} WHERE ${K} GROUP BY ${r.identifier("doc")}`}),_=p.map((F,k)=>r`SUM(CASE WHEN u.${r.identifier("__term__")} = ${r.raw(String(k))} THEN u.${r.identifier("__n__")} ELSE 0 END)`),R=r`SELECT f.${r.identifier(Ae)} AS ${r.identifier(Ae)}, ${r.join(_,r` + `)} AS ${r.identifier("__score__")} FROM (${He($)}) u JOIN ${r.identifier(m)} f ON f.rowid = u.${r.identifier("doc")} GROUP BY f.${r.identifier(Ae)} HAVING ${r.join(_.map(F=>r`${F} > 0`),r` AND `)}`,T=Mt(t,f);let x=r`SELECT m.id, m._creationTime, m.${r.identifier(N)}, s.${r.identifier("__score__")} AS ${r.identifier("__score__")} FROM (${R}) s JOIN ${r.identifier(i)} m ON m.id = s.${r.identifier(Ae)}`;T.length>0&&(x=r`${x} WHERE ${r.join(T,r` AND `)}`),x=r`${x} ORDER BY s.${r.identifier("__score__")} DESC, m._creationTime DESC, m.id ASC LIMIT ${r.raw(String(a))}`;const W=[];for(const F of q(o,x)){const k=vt(F);if(k){const j=F.__score__;W.push({document:k,score:typeof j=="number"?j:Number(j??0)})}}return W},Un=(o,i,t,a,f)=>{const p=Oe(t.definition.language),m=Qe(t.query,p);if(m.length===0)return[];const v=Mt(t,f);let S=r`SELECT id, _creationTime, ${r.identifier(N)} FROM ${r.identifier(i)}`;v.length>0&&(S=r`${S} WHERE ${r.join(v,r` AND `)}`),S=r`${S} ORDER BY _creationTime DESC, id ASC LIMIT ${r.raw(String(Bn(a)))}`;const $=q(o,S).toArray(),_=[];for(const R of $){const T=vt(R);if(!T)continue;const x=Rn(Ht(T,t.definition),m,p);x>0&&_.push({creationTime:typeof T._creationTime=="number"?T._creationTime:0,doc:T,id:typeof T._id=="string"?T._id:"",score:x})}return _.sort((R,T)=>T.score-R.score||T.creationTime-R.creationTime||R.id.localeCompare(T.id)),_.slice(0,a).map(R=>({document:R.doc,score:R.score}))},Ge=(o,i,t,a)=>{if(!Number.isFinite(o.lat)||o.lat<-90||o.lat>90||!Number.isFinite(o.lng)||o.lng<-180||o.lng>180)throw new E("BAD_REQUEST",`geo index "${a}" on table "${t}": ${i} must have a finite lat in [-90, 90] and lng in [-180, 180]`)},Pn=(o,i)=>{const t=o,a={near:(f,p)=>{if(t.within)throw new E("INTERNAL",`geo index "${t.indexName}" on table "${i}": call .near() or .within(), not both`);if(Ge(f,".near() point",i,t.indexName),!Number.isFinite(p)||p<=0)throw new E("BAD_REQUEST",`geo index "${t.indexName}" on table "${i}": .near() radiusMeters must be a finite number > 0, got ${String(p)}`);return t.near={point:{lat:f.lat,lng:f.lng},radiusMeters:p},a},within:f=>{if(t.near)throw new E("INTERNAL",`geo index "${t.indexName}" on table "${i}": call .near() or .within(), not both`);if(Ge(f.sw,".within() sw corner",i,t.indexName),Ge(f.ne,".within() ne corner",i,t.indexName),f.sw.lat>f.ne.lat)throw new E("BAD_REQUEST",`geo index "${t.indexName}" on table "${i}": .within() corners are transposed (sw.lat > ne.lat)`);if(f.sw.lng>f.ne.lng)throw new E("BAD_REQUEST",`geo index "${t.indexName}" on table "${i}": .within() box crosses the antimeridian (sw.lng > ne.lng), which is not supported — split it into two boxes at ±180 and union the results`);return t.within={ne:{lat:f.ne.lat,lng:f.ne.lng},sw:{lat:f.sw.lat,lng:f.sw.lng}},a}};return a},Gn=(o,i)=>{const t=o[i];if(t===null||typeof t!="object")return;const{lat:a,lng:f}=t;return typeof a=="number"&&typeof f=="number"?{lat:a,lng:f}:void 0},Hn=(o,i)=>{const t=Gn(o,i.definition.field);if(!t)return;const a=typeof o._creationTime=="number"?o._creationTime:0;if(i.near){const f=nn(i.near.point,t);return f<=i.near.radiusMeters?{creationTime:a,distance:f}:void 0}return rn(t,i.within)?{creationTime:a,distance:0}:void 0},Nn=(o,i,t,a)=>{if(!t.near&&!t.within)throw new E("INTERNAL",`geo index "${t.indexName}" on table "${i}": call .near(point, radius) or .within(box)`);const f=t.near?en(t.near.point,t.near.radiusMeters):tn(t.within),p=Xt(i,t.indexName),m=f.map(R=>r`(g.${r.identifier("__geohash__")} >= ${R} AND g.${r.identifier("__geohash__")} < ${`${R}{`})`),v=[r`(${r.join(m,r` OR `)})`];a&&v.push(a);const S=r`SELECT m.id, m._creationTime, m.${r.identifier(N)} FROM ${r.identifier(p)} g JOIN ${r.identifier(i)} m ON m.id = g.${r.identifier("__id__")} WHERE ${r.join(v,r` AND `)}`,$=q(o,S).toArray(),_=[];for(const R of $){const T=le(R),x=T?Hn(T,t):void 0;T&&x&&_.push({creationTime:x.creationTime,distance:x.distance,doc:T})}return _.sort((R,T)=>R.distance-T.distance||T.creationTime-R.creationTime),_},bt=(o,i,t,a)=>{const f=[];for(const p of o)if(i.every(m=>m(a(p)))&&(f.push(p),typeof t=="number"&&f.length>=t))break;return f},jn=(o,i,t,a,f,p=()=>{})=>{const m=t.within!==void 0,v=Nn(o,i,t,f).map(S=>({distanceMeters:m?null:S.distance,document:S.doc}));return p(v.length),typeof a=="number"?v.slice(0,Math.max(0,Math.floor(a))):v},Dt=(o,i,t,a,f,p=()=>{})=>{const{geo:m}=t;if(!m)throw new E("INTERNAL","runGeoTerminalScored called without a staged geo query");const v=t.inMemoryFilters.length>0,S=jn(o,i,m,v?void 0:f,a,p);return v?bt(S,t.inMemoryFilters,f,$=>$.document):S},Kn=(o,i,t,a,f,p=()=>{})=>Dt(o,i,t,a,f,p).map(m=>m.document),On=(o,i,t,a,f,p,m=()=>{})=>{const v=[];for(const R of t.sqlConditions)v.push(r`${V(R.field)} ${r.raw(R.comparator)} ${ie(R.value)}`);a&&v.push(a);let S=r`SELECT id, _creationTime, ${r.identifier(N)} FROM ${r.identifier(i)}`;v.length>0&&(S=r`${S} WHERE ${r.join(v,r` AND `)}`),S=r`${S} ORDER BY ${f}`,typeof p=="number"&&t.inMemoryFilters.length===0&&(S=r`${S} LIMIT ${r.raw(String(Math.max(0,Math.floor(p))))}`);const $=q(o,S).toArray();m($.length);const _=[];for(const R of $){const T=le(R);if(T&&t.inMemoryFilters.every(x=>x(T))&&(_.push(T),typeof p=="number"&&_.length>=p))break}return _},oe={fieldRef:V,serialize:ie},kt=(o,i)=>{const t=i===void 0?void 0:o.shape[i];return t!==void 0&&gn(t)},yt=(o,i)=>i.some(t=>kt(o,t)),Et=(o,i,t)=>{if(kt(o,i))throw new E("BAD_REQUEST",`${t}: "${i}" is stored as an order-preserving key, which SQL cannot reduce or group — declare an aggregateIndex covering this (by, field, op) so the maintained companion answers it`)},Qn=o=>{let i=0;const t=[],a={fieldRef:V,relationExists:f=>{const{childWhere:p,negated:m,parentTable:v,relation:S}=f,$=`__rel_${String(i)}`,_=t.at(-1)??v;i+=1,o(S.table,H);const R=S.kind==="one"?S.field:S.references,T=S.kind==="one"?S.references:S.field,x=r`${ct($,T)} = ${ct(_,R)}`;t.push($);const W=te(p,a);t.pop();const F=W?r`${x} AND ${W}`:x,k=r`EXISTS (SELECT 1 FROM ${r.identifier(S.table)} AS ${r.identifier($)} WHERE ${F})`;return m?r`NOT ${k}`:k},serialize:ie};return a},Lt=o=>{const i=o.map(t=>r`${V(t.field)} ${r.raw(t.direction==="desc"?"DESC":"ASC")}`);return o.some(t=>t.field==="_id"||t.field==="id")||i.push(r`${V("id")} ASC`),r.join(i,r`, `)},zn={"<":"lt","<=":"lte","=":"eq",">":"gt",">=":"gte"},Jn=o=>{const i=o.order;return o.indexFields.length>0?o.indexFields.map(t=>({direction:i,field:t})):[{direction:i,field:"_creationTime"}]},Vn=(o,i,t,a)=>{const f=o.sqlConditions.map(p=>({[p.field]:{[zn[p.comparator]??"eq"]:p.value}}));if(t&&f.push(Ct(i,Ne(t))),a&&f.push(cn(i,Ne(a))),f.length!==0)return f.length===1?f[0]:{AND:f}},Yn=(o,i,t)=>{const a=[];for(const f of o){const p=le(f);if(p&&i.every(m=>m(p))&&(a.push(p),t!==void 0&&a.length>t))break}return a},Xn=(o,i,t,a,f,p=()=>{})=>{const m=Math.max(0,Math.floor(a.numItems)),v=Jn(t),S=typeof a.endCursor=="string",$=te(Vn(t,v,a.cursor,a.endCursor),oe),_=f&&$?r`${$} AND ${f}`:f??$;let R=r`SELECT id, _creationTime, ${r.identifier(N)} FROM ${r.identifier(i)}`;_&&(R=r`${R} WHERE ${_}`),R=r`${R} ORDER BY ${Lt(v)}`;const T=t.inMemoryFilters.length>0;!T&&!S&&(R=r`${R} LIMIT ${r.raw(String(m+1))}`);const x=q(o,R).toArray();p(x.length);const W=Yn(x,t.inMemoryFilters,T||S?void 0:m);if(S){const K=W.length>=2?W[Math.floor(W.length/2)-1]:void 0;return{continueCursor:a.endCursor??null,isDone:!0,page:W,splitCursor:K?je(K,v):null}}const F=W.length>m,k=F?W.slice(0,m):W,j=k.at(-1);return{continueCursor:F&&j?je(j,v):null,isDone:!F,page:k}};class Zn extends E{constructor(i="unique() found more than one matching document"){super("NOT_UNIQUE",i,{name:"NotUniqueError"})}}const er=/\s/u,tr=String.fromCodePoint(0),mt=(o,i,t)=>{if(!o.tables[i])throw new E("INTERNAL",`unknown table: ${i}`);return typeof t!="string"||t.length===0||er.test(t)||t.includes(tr)?null:t},nr=(o,i,t,a=()=>{},f=()=>{},p=()=>{})=>{const m=i.tables[t];if(!m)throw new E("INTERNAL",`unknown table: ${t}`);const v=de(m.softDeleteMode,void 0),S=v?te(v,oe):void 0,$={indexFields:[],indexName:void 0,inMemoryFilters:[],order:"asc",sqlConditions:[]};let _=0;const R=y=>{const{search:I}=$;if(!I)throw new E("INTERNAL","runSearchFetch called without a staged search");Jt(o,t,m);const b=$.inMemoryFilters.length>0,L=Dn(b?void 0:y),J=Yt(o)?qn(o,t,I,L,S):Un(o,t,I,L,S);return b?(_=J.length,bt(J,$.inMemoryFilters,y,ne=>ne.document)):(y===void 0&&vn(J),J)},T=y=>R(y).map(I=>I.document),x=y=>{const I=Mn(y);return bn(T(In(I)),I)},W=()=>{const y=$.indexFields.length>0?$.indexFields:["_creationTime"],I=$.order==="desc"?"DESC":"ASC";return r.join(y.map(b=>r`${V(b)} ${r.raw(I)}`),r`, `)},F=()=>{if($.search||$.geo||$.indexName===void 0){f(void 0);return}f(fn(t,$.indexName,$.indexFields,$.sqlConditions,ie))},k=y=>{F();let I=0;const b=(()=>{if($.search){const L=T(y);return I=_,L}return $.geo?Kn(o,t,$,S,y,L=>{I=L}):On(o,t,$,S,W(),y,L=>{I=L})})();return p(Math.max(I,b.length)),b},j=()=>{if(!$.search&&!$.geo)throw new E("INTERNAL",`ctx.db.query("${t}").collectWithScores() requires a staged .withSearchIndex(...) or .withGeoIndex(...)`);F();let y=0;const I=(()=>{if($.search){const b=R(void 0);return y=_,b}return Dt(o,t,$,S,void 0,b=>{y=b})})();return p(Math.max(y,I.length)),I},K={async*[Symbol.asyncIterator](){const y=[...$.inMemoryFilters];let I;$.inMemoryFilters=[];try{for(;;){const b=await K.paginate({cursor:I??null,numItems:Fn});for(const L of b.page)y.every(J=>J(L))&&(yield L);if(b.isDone||b.continueCursor===null)return;I=b.continueCursor}}finally{$.inMemoryFilters=y}},async collect(){return k(void 0)},async collectWithScores(){return j()},filter(y){return $.inMemoryFilters.push(y),K},async first(){return k($.inMemoryFilters.length>0?void 0:1)[0]??null},order(y){return $.order=y==="desc"?"desc":"asc",K},async paginate(y){let I=0;if(F(),$.search){const L=x(y);return p(L.page.length),L}if($.geo)throw new E("INTERNAL","pagination is not supported on geo queries; use .take(n) or .collect()");const b=Xn(o,t,$,y,S,L=>{I=L});return p(Math.max(I,b.page.length)),b},async take(y){return k(y)},async unique(){const y=k($.inMemoryFilters.length>0?void 0:2);if(y.length>1)throw new Zn(`unique() on table "${t}" matched ${String(y.length)} documents; expected at most one`);return y[0]??null},withGeoIndex(y,I){const b=(m.geoIndexes??[]).find(J=>J.name===y);if(!b)throw new E("INTERNAL",`unknown geo index "${y}" on table "${t}"`);a(t,y,"geo");const L={definition:b,indexName:y};if($.geo=L,I(Pn(L,t)),!L.near&&!L.within)throw new E("INTERNAL",`geo index "${y}" on table "${t}" requires a .near(point, radius) or .within(box) call`);return K},withIndex(y,I){const b=m.indexes.find(L=>L.name===y);if(!b)throw new E("INTERNAL",`unknown index "${y}" on table "${t}"`);return a(t,y,"index"),$.indexName=y,$.indexFields=b.fields,I&&I(Wn($)),K},withSearchIndex(y,I){const b=(m.searchIndexes??[]).find(J=>J.name===y);if(!b)throw new E("INTERNAL",`unknown search index "${y}" on table "${t}"`);a(t,y,"search");const L={definition:b,field:b.field,filters:[],hasQuery:!1,indexName:y,query:""};if($.search=L,I(An(L,t,Oe(b.language))),!L.hasQuery)throw new E("INTERNAL",`search index "${y}" on table "${t}" requires a .search(field, query) call`);return K}};return K},St=(o,i,t)=>{const a={...i};for(const[f,p]of At(o)){if(p.serverDefault){a[f]=p.serverDefault({auth:t});continue}a[f]===void 0&&(p.defaultFn?a[f]=p.defaultFn():"defaultValue"in p&&(a[f]=p.defaultValue))}return a},_t=(o,i,t,a)=>{const f=t;for(const[p,m]of At(o)){if(m.serverDefault){p in i&&(f[p]=m.serverDefault({auth:a}));continue}m.onUpdateFn&&!(p in i)&&(f[p]=m.onUpdateFn())}},Rt=(o,i)=>{for(const t of Object.keys(i))if(i[t]===void 0)throw new E("INTERNAL",`Cannot ${o} field '${t}' to undefined — use null to clear a nullable field, or omit the key to leave it unchanged.`)},rr=/unique constraint failed/i,or=o=>o instanceof Error&&rr.test(o.message),Ke=(o,i,t)=>{try{q(o,t)}catch(a){throw or(a)?new pe(`unique constraint violation on "${i}"`,"unique"):a}},xe=(o,i,t)=>{if(Ke(o,i,t),q(o,r`SELECT changes() AS changed`).one().changed===0)throw new pe(`optimistic concurrency conflict on "${i}" — the row changed during this mutation; refetch and retry`,"occ")},Tt=(o,i,t,a,f,p,m)=>{const v=[];for(let R=0;R<t.length+1;R+=1){const T=[];for(let k=0;k<R;k+=1)T.push(r`${r.identifier(t[k])} IS ${p[k]}`);const x=t[R],W=a[R];if(x!==void 0&&W!==void 0){const k=W.direction==="desc"?">":"<";T.push(r`${r.identifier(x)} ${r.raw(k)} ${p[R]}`)}else T.push(r`${r.identifier(ln)} < ${m}`);const[F]=T;v.push(T.length===1&&F!==void 0?F:r`(${r.join(T,r` AND `)})`)}const S=r.join(v,r` OR `),$=q(o,r`SELECT COUNT(*) AS c FROM ${r.identifier(i)} WHERE ${r.identifier("__partition__")} = ${f} AND (${S})`).one(),_=q(o,r`SELECT COUNT(*) AS c FROM ${r.identifier(i)} WHERE ${r.identifier("__partition__")} = ${f}`).one();return{before:$.c,total:_.c}},Lr=o=>{const{sql:i}=o,{schema:t}=o,a=o.broadcast??(()=>{}),f=(e,...n)=>{const s=t.tables[e]?.indexes;if(!s||s.length===0)return;const u=[];for(const h of n)h&&u.push(...un(s,h,ie));return u.length>0?u:void 0},{headroom:p}=o;let m=!1;const v=async e=>{const n=m;m=!0;try{return await e()}finally{m=n}},S=o.onRead??(()=>{}),$=o.onReadRange??(e=>{S(e.table,H)}),_=(e,n)=>{n!==void 0&&n!==H&&!m&&p?.recordRead(1),S(e,n)},R=o.onIndexUse??(()=>{}),T=o.onWrite??(()=>{}),x=e=>{m||p?.recordWrite(e)},W=async e=>{x(e.doc),await T(e)},{cache:F}=o,k=o.clock??(()=>Date.now()),j=o.idGenerator??(()=>crypto.randomUUID()),K=o.scheduler??jt,{globalDb:y}=o,I=o.auth??{identity:null,userId:null},b=o.cdc??!1,L=K,J=$n({scheduler:typeof L.list=="function"&&typeof L.get=="function"?L:void 0,storage:o.storage}),ne=(e,n,s,u)=>{b&&Vt(i,k(),e,n,s,u)},se=e=>t.tables[e]?.shardMode?.kind==="global",ze=(e,n)=>{if(se(e)){if(!y)throw new E("INTERNAL",`cross-backend ${n} for global table '${e}' requires a globalDb writer — pass one to createShardCtxDb({ globalDb })`);return y}return U},Me=e=>ze(e,"cascade"),Q=(e,n)=>{if(se(e)){if(!y)throw new E("INTERNAL",`${n} on global table '${e}' requires a globalDb writer — pass one to createShardCtxDb({ globalDb })`);return y}},Je=async(e,n,s,u,h)=>{h&&x(s);const d=await e.insert(n,s,u);return a({key:d,op:"insert",row:{...s,_id:d},table:n}),d},be=(e,n)=>ze(e,"relation load").findMany(e,n),Ve=(e,n)=>(se(e)&&_(e,H),be(e,n)),Ft=e=>!se(e.table),Ye=o.relationExistsPushDown??"auto",Xe=Ye!=="never",{maxRelationKeys:Ze}=o,ge=(e,n,s)=>ut(e,{fetcher:Ve,maxRelationKeys:Ze,relationBaseWhere:s,schema:t,tableName:n}),et=async(e,n,s,u)=>{const h=Q(e,"relation grouped count");if(h)return _(e,H),wn((B,A)=>h.count(B,A),e,n,s,u);const d=t.tables[e];if(!d)throw new E("INTERNAL",`unknown table: ${e}`);_(e,H);const c=de(d.softDeleteMode,void 0),l={[n]:{in:s}},w=z(z(l,u),c),C=await ge(w,e,void 0),g=te(C,oe),M=V(n);let D=r`SELECT ${M} AS __fk__, COUNT(*) AS count FROM ${r.identifier(e)}`;g&&(D=r`${D} WHERE ${g}`),D=r`${D} GROUP BY ${M}`;const P=q(i,D).toArray();return new Map(P.map(B=>[B.__fk__,B.count]))};let $e=0;const tt=new Set;for(const[e,n]of Object.entries(t.tables))for(const s of Object.values(n.triggerMap??{}))tt.add(`${e} ${s.timing} ${s.op}`);const Z=(e,n,s)=>tt.has(`${e} ${n} ${s}`),ee=async(e,n,s)=>{if($e+=1,$e>gt)throw $e-=1,new pe(`trigger recursion exceeded ${String(gt)} levels on "${s.table}" — check for a self-triggering write`,"trigger");try{await yn({ctx:Bt,event:s,op:n,schema:t,tableName:s.table,timing:e})}finally{$e-=1}},{ensureBackfilledForTable:ue,ensureBackfilledIndex:De,ensureRankBackfilled:ke,ensureRankBackfilledForTable:fe,syncAggregates:ye,syncCompanionsForInsert:nt,syncGeo:Ee,syncRanks:he,syncSearch:me}=Pt({broadcast:a,indexKeysFor:(e,n)=>f(e,n),invalidateCache:(e,n,s)=>F?.invalidate(e,n,f(e,s)),recordCdc:ne,schema:t,sql:i}),rt=(e,n,s)=>{const{shardMode:u}=n;if(u?.kind==="shardBy"&&!(u.field!==void 0&&(s.partitionBy??[]).includes(u.field)))throw Object.assign(new Error(`rank index "${s.name}" on "${e}" partitions across shards (shard key "${u.field??"?"}" is not in partitionBy) — a shard-local rank()/rankPage() would be wrong; roll it up through the Query Coordinator instead`),{code:"CROSS_SHARD_RANK_UNSUPPORTED",name:"LunoraError",status:400})},ot=e=>Object.entries(t.tables).filter(([,n])=>n.shardMode?.kind!=="global").map(([n])=>n).filter(n=>e===void 0||n===e),re=(e,n)=>{const s=ot(n);for(let u=0;u<s.length;u+=we){const h=s.slice(u,u+we).map(g=>r`SELECT ${r.raw(`'${g.replaceAll("'","''")}'`)} AS __t__, id, _creationTime, ${r.identifier(N)} FROM ${r.identifier(g)} WHERE id = ${e}`),[d]=q(i,r`${He(h)} LIMIT 1`).toArray();if(!d)continue;const c=d.__t__,l=le(d);if(typeof c!="string"||!l)return;const w=d[N];return{docJson:typeof w=="string"?w:ce(w??{}),row:l,tableName:c}}},Wt=(e,n)=>{const s=[...new Set(e)],u=new Map;if(s.length===0)return u;const h=ot(n);for(let d=0;d<h.length;d+=we){const c=h.slice(d,d+we),l=Math.floor(we/c.length),w=Zt(r`${r.identifier("id")}`,s,!1,l),C=c.map(g=>r`SELECT ${r.raw(`'${g.replaceAll("'","''")}'`)} AS __t__, id FROM ${r.identifier(g)} WHERE ${w}`);for(const g of q(i,He(C))){const{id:M,__t__:D}=g;typeof D=="string"&&typeof M=="string"&&u.set(M,D)}}return u},it={assertRankPartitionLocal:rt,ensureRankBackfilled:ke,onRead:_,rowToDocument:le,schema:t,sql:i},U={system:J,async aggregate(e,n){const s=Q(e,"aggregate");if(s)return _(e,H),s.aggregate(e,n);const u=t.tables[e];if(!u)throw new E("INTERNAL",`unknown table: ${e}`);if(ve(n.op),n.op==="count")return U.count(e,{baseWhere:n.baseWhere,relationBaseWhere:n.relationBaseWhere,restrictsCounts:n.restrictsCounts,where:n.where});if(!n.field)throw new E("INTERNAL",`aggregate(${e}, { op: "${n.op}" }): "field" is required for non-count reducers`);_(e,H);const h=de(u.softDeleteMode,void 0),d=z(z(n.baseWhere,n.where),h),c=await ge(d,e,n.relationBaseWhere),l=c!==d;if(u.aggregateIndexes&&!n.baseWhere&&!l&&(!h||yt(u,[n.field]))){const B=zt(u.aggregateIndexes,n.op,n.field,n.where);if(B){De(e,B.index);const A=Fe(B.index.by??[],B.key),O=Le(e,B.index.name),Y=q(i,r`SELECT ${Ie} AS value, ${qe} AS count FROM ${r.identifier(O)} WHERE ${Ce} = ${A}`).toArray()[0];return We(n.op,Y)}}Et(u,n.field,`aggregate(${e}, { op: "${n.op}", field: "${n.field}" })`);const w=te(c,oe),C=ve(n.op),g=V(n.field);let M=r`SELECT ${r.raw(C)}(${g}) AS value FROM ${r.identifier(e)}`;w&&(M=r`${M} WHERE ${w}`);const P=q(i,M).toArray()[0]?.value;return P??null},asId(e,n){const s=mt(t,e,n);if(s===null)throw new E("BAD_REQUEST",`asId("${e}", …): "${n}" is not a valid id for table "${e}"`,{status:400});return s},async count(e,n){const s=Q(e,"count");if(s)return _(e,H),s.count(e,n);const u=t.tables[e];if(!u)throw new E("INTERNAL",`unknown table: ${e}`);const h=Kt(n);if(h.restrictsCounts)throw new Be(e);_(e,H);const d=de(u.softDeleteMode,void 0),c=z(z(h.baseWhere,h.where),d),l=await ge(c,e,h.relationBaseWhere),w=l!==c;if(u.aggregateIndexes&&!h.baseWhere&&!w&&!d){const D=Qt(u.aggregateIndexes,h.where);if(D){De(e,D.index);const P=Fe(D.index.by??[],D.key),B=Le(e,D.index.name),A=q(i,r`SELECT ${Ie} AS value FROM ${r.identifier(B)} WHERE ${Ce} = ${P}`).toArray();return A[0]===void 0?0:A[0].value??0}}const C=te(l,oe);let g=r`SELECT COUNT(*) AS count FROM ${r.identifier(e)}`;return C&&(g=r`${g} WHERE ${C}`),q(i,g).one().count},async delete(e,n,s){const u=re(e,n);if(!u){const g=n===void 0?y:void 0;g&&(x(void 0),await g.delete(e,void 0,s));return}const{docJson:h,row:d,tableName:c}=u,l=t.tables[c],w=s?.hard===!0,C=!w&&l?.softDeleteMode?l.softDeleteMode.field:void 0;if(!(C&&d[C]!==null&&d[C]!==void 0)){if(Z(c,"before","delete")&&await ee("before","delete",{id:e,op:"delete",previous:d,table:c}),await hn({deletedId:e,deletedReference:g=>d[g],findHolders:async(g,M,D)=>(await Me(g).findMany(g,{includeDeleted:w,where:{[M]:D}})).page,onCascade:(g,M)=>Me(g).delete(M,void 0,s),onRestrict:g=>{throw new pe(g,"restrict")},onSetNull:(g,M,D)=>Me(g).patch(M,{[D]:null}),schema:t,tableName:c}),ue(c),fe(c),C){const g={...d,[C]:k(),_id:e};xe(i,c,r`UPDATE ${r.identifier(c)} SET ${r.identifier(N)} = ${ce(g)} WHERE id = ${e} AND ${r.identifier(N)} = ${h}`),me(c,e,g,d),Ee(c,e,void 0),ye(c,d,g),he(c,e,d,void 0),F?.invalidate(c,e,f(c,d,g)),ne(c,e,"update",g),a({indexKeys:f(c,d,g),key:e,op:"update",row:g,table:c}),Z(c,"after","delete")&&await ee("after","delete",{id:e,op:"delete",previous:d,table:c}),await W({id:e,op:"delete",table:c});return}xe(i,c,r`DELETE FROM ${r.identifier(c)} WHERE id = ${e} AND ${r.identifier(N)} = ${h}`),me(c,e,void 0),Ee(c,e,void 0),ye(c,d,void 0),he(c,e,d,void 0),F?.invalidate(c,e,f(c,d)),ne(c,e,"delete"),a({indexKeys:f(c,d),key:e,op:"delete",table:c}),Z(c,"after","delete")&&await ee("after","delete",{id:e,op:"delete",previous:d,table:c}),await W({id:e,op:"delete",table:c})}},async deleteAll(e,n){if(!t.tables[e])throw new E("INTERNAL",`unknown table: ${e}`);const s=Math.max(1,n?.chunkSize??xt),u=n?.hard===void 0?void 0:{hard:n.hard},h=se(e)?void 0:e;let d=0;return await v(async()=>{for(;;){const l=(await U.findMany(e,{limit:s})).page.map(w=>String(w._id));if(l.length===0)break;for(const w of l)await U.delete(w,h,u),d+=1;if(l.length<s)break}}),{deleted:d}},async deleteMany(e,n,s){ae(e.length,n?.limit,"deleteMany");for(const u of e)await U.delete(u,s);return{deleted:e.length}},async deleteWhere(e,n,s){const d=(await(Q(e,"deleteWhere")??U).findMany(e,{where:n})).page.map(c=>String(c._id));if(ae(d.length,s?.limit,"deleteWhere"),U.deleteMany===void 0)throw new E("INTERNAL",`ctx.db.${e}.deleteMany is unavailable: this writer has no batch delete`);return U.deleteMany(d,s)},async findFirst(e,n={}){return(await U.findMany(e,{...n,limit:1})).page[0]??null},async findFirstOrThrow(e,n={}){const s=await U.findFirst(e,n);if(s===null)throw new on(`findFirstOrThrow: no "${e}" document matched`);return s},async findMany(e,n={}){const s=Q(e,"findMany");if(s)return _(e,H),s.findMany(e,n);const u=t.tables[e];if(!u)throw new E("INTERNAL",`unknown table: ${e}`);const h=!n.where&&!n.baseWhere;h?_(e,H):_(e);const d=sn(n.orderBy),c=n.cursor?Ct(d,Ne(n.cursor)):void 0;let l=z(n.baseWhere,n.where);l=z(l,de(u.softDeleteMode,n.includeDeleted)),l=await ut(l,{canPushExists:Xe?Ft:void 0,existsPushMode:Ye==="always"?"always":"auto",fetcher:Ve,maxRelationKeys:Ze,relationBaseWhere:n.relationBaseWhere,schema:t,tableName:e}),c&&(l=l?{AND:[l,c]}:c);const w=Xe?Qn(_):oe,C=te(l,w);let g=r`SELECT id, _creationTime, ${r.identifier(N)} FROM ${r.identifier(e)}`;C&&(g=r`${g} WHERE ${C}`),g=r`${g} ORDER BY ${Lt(d)}`;const M=typeof n.limit=="number"?Math.max(0,Math.floor(n.limit)):void 0;M!==void 0&&(g=r`${g} LIMIT ${r.raw(String(M+1))}`);const D=q(i,g).toArray();h&&!m&&p?.recordRead(D.length);const P=[];for(const Y of D){const G=le(Y);G&&(P.push(G),!h&&typeof G._id=="string"&&_(e,G._id))}if(M===void 0)return n.with&&await ft({groupedCounter:et,fetcher:be,parents:P,...ht(n),schema:t,tableName:e,with:n.with}),{continueCursor:null,isDone:!0,page:at(P,n.select,n.with)};const B=P.length>M,A=B?P.slice(0,M):P,O=A.at(-1);return n.with&&await ft({fetcher:be,groupedCounter:et,parents:A,...ht(n),schema:t,tableName:e,with:n.with}),{continueCursor:B&&O?je(O,d):null,isDone:!B,page:at(A,n.select,n.with)}},async get(e,n){const s=re(e,n);if(!s){const u=n===void 0?y:void 0;return u?u.get(e):null}return _(s.tableName,e),s.row},async lookupById(e,n){const s=re(e,n);return s?(_(s.tableName,e),{row:s.row,tableName:s.tableName}):null},async groupBy(e,n){const s=Q(e,"groupBy");if(s)return _(e,H),s.groupBy(e,n);const u=t.tables[e];if(!u)throw new E("INTERNAL",`unknown table: ${e}`);_(e,H);const h=n.agg??{op:"count"};if(ve(h.op),h.op!=="count"&&!h.field)throw new E("INTERNAL",`groupBy(${e}, { agg: { op: "${h.op}" } }): "field" is required for non-count reducers`);const d=de(u.softDeleteMode,void 0),c=z(z(n.baseWhere,n.where),d),l=await ge(c,e,n.relationBaseWhere),w=l!==c,C=[...n.by,h.field];if(u.aggregateIndexes&&!n.baseWhere&&!w&&(!d||yt(u,C))){const A=Ot(u.aggregateIndexes,h.op,h.field,n.by,n.where),O=A===void 0?0:Object.keys(A.partial).length,Y=A?.index.by?.length??0;if(A&&(O===0||O===Y)){De(e,A.index);const G=Le(e,A.index.name),Se=Object.keys(A.partial),_e=[];if(Se.length===(A.index.by??[]).length&&Se.length>0){const Re=Fe(A.index.by??[],A.partial),Te=q(i,r`SELECT ${Ie} AS value, ${qe} AS count FROM ${r.identifier(G)} WHERE ${Ce} = ${Re}`).toArray();return Te.length>0&&_e.push({key:{...A.partial},value:We(h.op,Te[0])}),_e}const qt=q(i,r`SELECT ${Ce} AS key, ${Ie} AS value, ${qe} AS count FROM ${r.identifier(G)}`).toArray();for(const Re of qt){const Te=Nt(JSON.parse(Re.key));_e.push({key:Te,value:We(h.op,Re)})}return _e}}for(const A of C){if(A===void 0)continue;const O=A===h.field?`groupBy(${e}, { agg: { op: "${h.op}", field: "${A}" } })`:`groupBy(${e}, { by: [..."${A}"] })`;Et(u,A,O)}const g=te(l,oe),M=n.by.map(A=>r`${V(A)} AS ${r.identifier(A)}`);if(h.op==="count")M.push(r`COUNT(*) AS value`);else{const{field:A}=h;if(A===void 0)throw new E("INTERNAL",`groupBy(${e}, { agg: { op: "${h.op}" } }): "field" is required for non-count reducers`);M.push(r`${r.raw(ve(h.op))}(${V(A)}) AS value`)}let D=r`SELECT ${r.join(M,r`, `)} FROM ${r.identifier(e)}`;g&&(D=r`${D} WHERE ${g}`),D=r`${D} GROUP BY ${r.join(n.by.map(A=>V(A)),r`, `)}`;const P=q(i,D).toArray(),B=[];for(const A of P){const O={};for(const G of n.by)O[G]=A[G]??null;const{value:Y}=A;B.push({key:O,value:Y==null?null:Number(Y)})}return B},async insert(e,n,s){const u=Q(e,"insert");if(u)return Je(u,e,n,s,!0);const h=t.tables[e];if(!h)throw new E("INTERNAL",`unknown table: ${e}`);const d=St(h,n,I);Pe(h,d);let c;s?.clientId!==void 0?(Ln(s.clientId),c=s.clientId):s?.allowExplicitId&&typeof d._id=="string"?c=d._id:c=j();const l=s?.allowExplicitId&&typeof d._creationTime=="number"?d._creationTime:k(),w={...d,_creationTime:l,_id:c};return Z(e,"before","insert")&&await ee("before","insert",{doc:{...w},id:c,op:"insert",table:e}),ue(e),fe(e),Ke(i,e,r`INSERT INTO ${r.identifier(e)} (id, _creationTime, ${r.identifier(N)}) VALUES (${c}, ${l}, ${ce(w)})`),nt(e,c,w),Z(e,"after","insert")&&await ee("after","insert",{doc:w,id:c,op:"insert",table:e}),await W({doc:w,id:c,op:"insert",table:e}),c},async insertManyUnsafe(e,n,s){if(ae(n.length,s?.limit,"insertManyUnsafe"),n.length===0)return[];const u=Q(e,"insert");if(u){const c=[];for(const l of n)x(l);for(const l of n){const w=await u.insert(e,l,{allowExplicitId:s?.allowExplicitId});a({key:w,op:"insert",row:{...l,_id:w},table:e}),c.push(w)}return c}const h=t.tables[e];if(!h)throw new E("INTERNAL",`unknown table: ${e}`);ue(e),fe(e);const d=n.map(c=>{const l=St(h,c,I),w=s?.allowExplicitId===!0&&typeof l._id=="string"?l._id:j(),C=s?.allowExplicitId===!0&&typeof l._creationTime=="number"?l._creationTime:k();return{creationTime:C,document:{...l,_creationTime:C,_id:w},id:w}});for(const c of d)x(c.document);for(let c=0;c<d.length;c+=$t){const l=r.join(d.slice(c,c+$t).map(w=>r`(${w.id}, ${w.creationTime}, ${ce(w.document)})`),r`, `);Ke(i,e,r`INSERT INTO ${r.identifier(e)} (id, _creationTime, ${r.identifier(N)}) VALUES ${l}`)}for(const{document:c,id:l}of d)nt(e,l,c),await T({doc:c,id:l,op:"insert",table:e});return d.map(c=>c.id)},async insertMany(e,n,s){ae(n.length,s?.limit,"insertMany");const u=s?.skipDuplicates===!0,h=[],d=Q(e,"insert");if(d)for(const l of n)x(l);const c=async l=>d?Je(d,e,l,void 0,!1):U.insert(e,l);for(const l of n)try{h.push(await c(l))}catch(w){if(u&&w instanceof pe&&w.kind==="unique")h.push(null);else throw w}return h},normalizeId(e,n){return mt(t,e,n)},async patch(e,n,s){const u=re(e,s);if(!u){const C=s===void 0?y:void 0;if(C){x(n),await C.patch(e,n);return}throw new E("INTERNAL",`document not found: ${e}`)}const{docJson:h,row:d,tableName:c}=u,l=t.tables[c];if(!l)throw new E("INTERNAL",`unknown table: ${c}`);_(c,e),Rt("patch",n);const w={...d,...n,_id:e};_t(l,n,w,I),Pe(l,w,!0),Z(c,"before","update")&&await ee("before","update",{doc:{...w},id:e,op:"update",previous:d,table:c}),ue(c),fe(c),xe(i,c,r`UPDATE ${r.identifier(c)} SET ${r.identifier(N)} = ${ce(w)} WHERE id = ${e} AND ${r.identifier(N)} = ${h}`),me(c,e,w,d),Ee(c,e,w),ye(c,d,w),he(c,e,d,w),F?.invalidate(c,e,f(c,d,w)),ne(c,e,"update",w),a({indexKeys:f(c,d,w),key:e,op:"update",row:w,table:c}),Z(c,"after","update")&&await ee("after","update",{doc:w,id:e,op:"update",previous:d,table:c}),await W({doc:w,id:e,op:"update",table:c})},async patchMany(e,n,s){ae(e.length,n?.limit,"patchMany");for(const u of e)await U.patch(u.id,u.patch,s);return{patched:e.length}},async patchWhere(e,n,s){const d=(await(Q(e,"patchWhere")??U).findMany(e,{where:n.where})).page.map(c=>({id:String(c._id),patch:n.patch}));if(ae(d.length,s?.limit,"patchWhere"),U.patchMany===void 0)throw new E("INTERNAL",`ctx.db.${e}.patchMany is unavailable: this writer has no batch patch`);return await U.patchMany(d,s),{patched:d.length}},query(e){const n=Q(e,"query");return n?(_(e,H),n.query(e)):nr(i,t,e,R,s=>{s?$(s):_(e,H)},s=>{m||p?.recordRead(s)})},async rank(e,n,s){const u=Q(e,"rank");if(u)return _(e,H),u.rank(e,n,s);R(e,n,"rank");const h=t.tables[e];if(!h)throw new E("INTERNAL",`unknown table: ${e}`);const d=h.rankIndexes?.find(G=>G.name===n);if(!d)throw new E("INTERNAL",`unknown rankIndex "${n}" on table "${e}"`);if(rt(e,h,d),s.restrictsCounts)throw new Be(e);_(e,H),ke(e,d);const c=typeof s.row=="string"?s.row:s.row._id;if(!c)return null;const l=dt(e,d.name),w=d.sortBy.map((G,Se)=>lt(Se)),C=w.map(G=>En(G)).join(", "),g=q(i,r`SELECT ${r.identifier("__partition__")}, ${r.raw(C)} FROM ${r.identifier(l)} WHERE ${r.identifier("__id__")} = ${c}`).toArray(),[M]=g;if(M===void 0)return null;let D=M.__partition__;const P=z(s.baseWhere,s.where);Ue(P,t,e,"rank");const B=an(d,P);if(B){const G=dn(d.partitionBy??[],B);if(G!==D)return null;D=G}const A=w.map(G=>M[G]),{before:O,total:Y}=Tt(i,l,w,d.sortBy,D,A,c);return{position:O+1,total:Y}},async rankBefore(e,n,s){if(se(e))throw new E("INTERNAL",`rankBefore is not supported on the global (.global()) table '${e}' — cross-shard rank cursors apply only to sharded tables`);const u=t.tables[e];if(!u)throw new E("INTERNAL",`unknown table: ${e}`);const h=u.rankIndexes?.find(w=>w.name===n);if(!h)throw new E("INTERNAL",`unknown rankIndex "${n}" on table "${e}"`);if(s.restrictsCounts)throw new Be(e);_(e,H),ke(e,h);const d=dt(e,h.name),c=h.sortBy.map((w,C)=>lt(C)),l=h.sortBy.map((w,C)=>ie(s.sortValues[C]??null));return Tt(i,d,c,h.sortBy,s.partitionKey,l,s.rowId)},async rankPage(e,n,s={}){Ue(z(s.baseWhere,s.where),t,e,"rankPage");const u=Q(e,"rankPage");if(u)return _(e,H),u.rankPage(e,n,s);R(e,n,"rank");const{continueCursor:h,hasMore:d,rows:c}=st(it,e,n,s);return{continueCursor:h,isDone:!d,page:c.map(l=>l.doc)}},async rankPageRows(e,n,s={}){Ue(z(s.baseWhere,s.where),t,e,"rankPage"),R(e,n,"rank");const{directions:u,hasMore:h,rows:d}=st(it,e,n,s);return{directions:u,hasMore:h,rows:d}},async restore(e,n){const s=re(e,n);if(!s){const d=n===void 0?y:void 0;if(d?.restore){await d.restore(e);return}throw new E("INTERNAL",`document not found: ${e}`)}const u=t.tables[s.tableName]?.softDeleteMode?.field;if(!u)throw new E("INTERNAL",`ctx.db.restore: table "${s.tableName}" is not a .softDelete() table`);const h=s.row[u]!==null&&s.row[u]!==void 0;await U.patch(e,{[u]:null},n),h&&he(s.tableName,e,void 0,s.row)},async replace(e,n,s,u){const h=re(e,s);if(!h){const M=s===void 0?y:void 0;if(M){x(n),await M.replace(e,n,void 0,u);return}throw new E("INTERNAL",`document not found: ${e}`)}const{docJson:d,row:c,tableName:l}=h,w=t.tables[l];if(!w)throw new E("INTERNAL",`unknown table: ${l}`);Rt("replace",n);const C=u?.allowExplicitId&&typeof n._creationTime=="number"?n._creationTime:k(),g={...n,_creationTime:C,_id:e};_t(w,n,g,I),Pe(w,g),Z(l,"before","update")&&await ee("before","update",{doc:{...g},id:e,op:"update",previous:c,table:l}),ue(l),fe(l),xe(i,l,r`UPDATE ${r.identifier(l)} SET _creationTime = ${C}, ${r.identifier(N)} = ${ce(g)} WHERE id = ${e} AND ${r.identifier(N)} = ${d}`),me(l,e,g,c),Ee(l,e,g),ye(l,c,g),he(l,e,c,g),F?.invalidate(l,e,f(l,c,g)),ne(l,e,"update",g),a({indexKeys:f(l,c,g),key:e,op:"update",row:g,table:l}),Z(l,"after","update")&&await ee("after","update",{doc:g,id:e,op:"update",previous:c,table:l}),await W({doc:g,id:e,op:"update",table:l})},async wipeShard(e){const n=new Set(e?.exclude),s=e?.tables,u=Object.entries(t.tables).filter(([l,w])=>n.has(l)||s!==void 0&&!s.includes(l)?!1:w.shardMode?.kind!=="global").map(([l])=>l);if(s!==void 0){for(const l of s)if(!t.tables[l])throw new E("INTERNAL",`wipeShard: unknown table: ${l}`)}const h={};let d=0;const{deleteAll:c}=U;if(c===void 0)throw new E("INTERNAL","wipeShard: this writer has no deleteAll");for(const l of u){const w=await c(l,{...e?.chunkSize===void 0?{}:{chunkSize:e.chunkSize},hard:!0});h[l]=w.deleted,d+=w.deleted}return{deleted:d,tables:h}}},Bt={db:U,scheduler:K};return o.enforceRls===!0?pn(U,t,(e,n)=>re(e,n)?.tableName,(e,n)=>Wt(e,n)):U};export{Gr as CDC_LOG_TABLE,Vr as CLIENT_WATERMARK_TABLE,to as GLOBAL_SHAPE_SNAPSHOT_TABLE,ao as IDEMPOTENCY_TABLE,Zn as NotUniqueError,go as SEARCH_STATE_TABLE,Yr as advanceClientWatermark,Hr as applyCdcChanges,Ln as assertValidClientId,Br as backfillAggregateIndexes,qr as backfillRankIndexes,Ur as backfillSearchIndexes,Nr as bumpCdcEpoch,Lr as createShardCtxDb,no as deleteGlobalShapeSnapshot,ro as deleteGlobalShapeSnapshotsForConnection,Xr as migrateClientWatermark,oo as migrateGlobalShapeSnapshot,jr as minCdcSeq,mt as normalizeIdStructurally,Kr as readCdcChanges,Or as readCdcCursor,Qr as readCdcEpoch,Zr as readClientWatermark,io as readGlobalShapeSnapshot,lo as readIdempotent,wo as runShardMigrations,yo as selectShapeMemberIds,Eo as selectShapeRows,zr as trimCdcChanges,uo as trimIdempotent,so as writeGlobalShapeSnapshot,fo as writeIdempotent};
|