@lunora/shard-engine 1.0.0-alpha.25 → 1.0.0-alpha.26
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 +14 -2
- package/dist/index.d.ts +14 -2
- package/dist/index.mjs +1 -1
- package/dist/packem_shared/{ADMIN_FUNCTIONS-B5HZoizX.mjs → ADMIN_FUNCTIONS-Cj1pJjVg.mjs} +1 -1
- package/dist/packem_shared/{AGG_COUNT-DmQFpsDX.mjs → AGG_COUNT-CKtq03Go.mjs} +1 -1
- package/dist/packem_shared/{CDC_LOG_TABLE-DH-KHUfU.mjs → CDC_LOG_TABLE-DNFFQwF_.mjs} +1 -1
- package/dist/packem_shared/{DEFAULT_MAX_RELATION_KEYS-DjKka36Z.mjs → DEFAULT_MAX_RELATION_KEYS-BV1RCoat.mjs} +1 -1
- package/dist/packem_shared/{DEFAULT_MAX_RELAYS-B19vrJxP.mjs → DEFAULT_MAX_RELAYS-Cinp9pPC.mjs} +1 -1
- package/dist/packem_shared/{DEFAULT_PROMOTION_THRESHOLDS-B2rUe1bg.mjs → DEFAULT_PROMOTION_THRESHOLDS-DYGNAo1I.mjs} +1 -1
- package/dist/packem_shared/{DurableStreamRunner-C-OSu02s.mjs → DurableStreamRunner-B54Jt9Iu.mjs} +1 -1
- package/dist/packem_shared/{NotUniqueError-BeTJrgRe.mjs → NotUniqueError-DYo7r67J.mjs} +1 -1
- package/dist/packem_shared/{RANK_TIEBREAK-DDtST3gN.mjs → RANK_TIEBREAK-BGk411OR.mjs} +1 -1
- package/dist/packem_shared/{ReactiveCache-Cu8IfE1M.mjs → ReactiveCache-D_T10KLy.mjs} +1 -1
- package/dist/packem_shared/{aggregateTableName-DgYMC5tr.mjs → aggregateTableName-DN7gk6uh.mjs} +1 -1
- package/dist/packem_shared/{applyOnDelete-By23GK-k.mjs → applyOnDelete-crbAzVfE.mjs} +1 -1
- package/dist/packem_shared/{applySelect-UY-o13Ia.mjs → applySelect-5w13bMAR.mjs} +1 -1
- package/dist/packem_shared/awaitWsDrain-PT9o0d6J.mjs +1 -0
- package/dist/packem_shared/{backfillAggregateIndexes-BEMWTEq1.mjs → backfillAggregateIndexes-DTOIsYbi.mjs} +1 -1
- package/dist/packem_shared/{buildPokeFrames-CqxaN8_H.mjs → buildPokeFrames-DmB-FBeQ.mjs} +1 -1
- package/dist/packem_shared/{buildReprojectionMigration-YQSJX2cC.mjs → buildReprojectionMigration-JUwsTNTB.mjs} +1 -1
- package/dist/packem_shared/{computeRankPage-D1ygctSC.mjs → computeRankPage-BU8LXvQs.mjs} +1 -1
- package/dist/packem_shared/createCompanionSync-D-ckGBdA.mjs +1 -0
- package/dist/packem_shared/{ctx-db-companions-c12P7dbv.mjs → ctx-db-companions-BJlCofon.mjs} +1 -1
- package/dist/packem_shared/{defineEngineContractSuite-CYR4BaIk.mjs → defineEngineContractSuite-CvdzORsy.mjs} +1 -1
- package/dist/packem_shared/{do-sql-C7qrlm6-.mjs → do-sql-DKSFK627.mjs} +1 -1
- package/dist/packem_shared/{isSoftDeleted-Tr2to2aw.mjs → isSoftDeleted-DyEJueIu.mjs} +1 -1
- package/dist/packem_shared/{materializeExternalRows-D53xwGfY.mjs → materializeExternalRows-C-5TKdc1.mjs} +1 -1
- package/dist/packem_shared/{runShardMigrations-BAtfEXbB.mjs → runShardMigrations-BCuK60KT.mjs} +1 -1
- package/dist/packem_shared/{selectExpiredIds-C3Vv1gPm.mjs → selectExpiredIds-C4Ry_NxG.mjs} +1 -1
- package/dist/packem_shared/{selectShapeMemberIds-WzxOG62k.mjs → selectShapeMemberIds-Bkkug6vU.mjs} +1 -1
- package/dist/packem_shared/{stableWireKey-l3cjIt-9.mjs → stableWireKey-Diuu1gGc.mjs} +1 -1
- package/dist/packem_shared/{wire-codec-Dsy70M3Q.mjs → wire-codec-Dh0j-GnY.mjs} +1 -1
- package/package.json +1 -1
- package/dist/packem_shared/awaitWsDrain-Bp2jKzIb.mjs +0 -1
- package/dist/packem_shared/createCompanionSync-D7DEvUvt.mjs +0 -1
|
@@ -1 +1 @@
|
|
|
1
|
-
import{defineEngineContractSuite as t}from"../packem_shared/defineEngineContractSuite-
|
|
1
|
+
import{defineEngineContractSuite as t}from"../packem_shared/defineEngineContractSuite-CvdzORsy.mjs";export{t as defineEngineContractSuite};
|
package/dist/index.d.mts
CHANGED
|
@@ -839,6 +839,7 @@ interface ShapeSubscriptionQuery {
|
|
|
839
839
|
sinceSeq?: number;
|
|
840
840
|
}
|
|
841
841
|
interface SubscriptionEnvelope {
|
|
842
|
+
caps?: string[];
|
|
842
843
|
clientId?: string;
|
|
843
844
|
context?: Record<string, unknown>;
|
|
844
845
|
data?: unknown;
|
|
@@ -866,6 +867,7 @@ interface SocketAttachment {
|
|
|
866
867
|
context?: Record<string, unknown>;
|
|
867
868
|
expiresAt?: number;
|
|
868
869
|
identity?: Record<string, unknown>;
|
|
870
|
+
pageDeltas?: boolean;
|
|
869
871
|
shapes?: Record<string, ShapeSubscriptionQuery>;
|
|
870
872
|
subs: Record<string, SubscriptionQuery>;
|
|
871
873
|
userId?: string;
|
|
@@ -2087,7 +2089,17 @@ interface DrainableSink {
|
|
|
2087
2089
|
readonly bufferedAmount?: unknown;
|
|
2088
2090
|
}
|
|
2089
2091
|
declare const trySendFrame: (ws: FrameSink, frame: string) => boolean;
|
|
2090
|
-
|
|
2092
|
+
interface SubscriptionFrameInput {
|
|
2093
|
+
cursorSuffix: string;
|
|
2094
|
+
lastMutationId?: number;
|
|
2095
|
+
nextResult: unknown;
|
|
2096
|
+
pageDeltas?: boolean;
|
|
2097
|
+
previousJson?: string;
|
|
2098
|
+
snapshotJson: string;
|
|
2099
|
+
subId: string;
|
|
2100
|
+
table: string;
|
|
2101
|
+
}
|
|
2102
|
+
declare const subscriptionFrames: (input: SubscriptionFrameInput) => string[];
|
|
2091
2103
|
declare const awaitWsDrain: (ws: DrainableSink) => Promise<void>;
|
|
2092
2104
|
interface SubscriptionReadFootprint {
|
|
2093
2105
|
ranges?: Map<string, KeyRange[]>;
|
|
@@ -2126,4 +2138,4 @@ interface WhereSqlStrategy {
|
|
|
2126
2138
|
}
|
|
2127
2139
|
declare const literalInList: (reference: SQL, items: ReadonlyArray<unknown>, negated: boolean) => SQL;
|
|
2128
2140
|
declare const compileWhereSql: (where: WhereInput | undefined, strategy: WhereSqlStrategy) => SQL | undefined;
|
|
2129
|
-
export { ADMIN_FUNCTIONS, ADMIN_FUNCTION_PREFIX, AGGREGATE_SQL_FUNCTION, AGG_COUNT, AGG_KEY, AGG_VALUE, AUDIT_LOG_TABLE, type AdvisorProcedure, type AdvisorProceduresResult, type AdvisoriesResult, type AdvisoryFinding, type AggregateIndexDefinitionLike, type AggregateOp, type AggregateOptions, type AggregateResult, type AggregateTally, type AppendAuditEntry, type ApplyOnDeleteOptions$1 as ApplyOnDeleteOptions, type AuditEntry, type AuditLogResult, type BroadcastDelta, CDC_LOG_TABLE, CDC_META_TABLE, CLIENT_WATERMARK_TABLE, type CacheEntry, type CapturedMailRow, type CdcChange, type ChangedKeys, type Clock, type ColumnMeta, type ColumnMetaLike, type CompanionSync, type CompanionSyncDeps, ConflictError, type ConflictKind, type CountArgs, CountRlsUnsupportedError, type CreateWorkflowInstanceResult, type CrossShardReadArgs, type CtxDbOptions, DATA_MIGRATION_STATE_TABLE, DEFAULT_FANOUT_TOPIC_LIMIT, DEFAULT_MAX_RELATION_KEYS, DEFAULT_MAX_RELAYS, DEFAULT_PROMOTION_THRESHOLDS, DEFAULT_TRANSACTION_LIMITS, DOC_COLUMN, type DataMigrationDocument, type DataMigrationLike, type DataMigrationTransform, type DatabaseWriterLike, type DependencyTracker, type DeployInfo, type DurableAttachDecision, type DurableStreamAttach, type DurableStreamRun, DurableStreamRunner, type DurableStreamSink, type ExportRow, type ExportShardAdminArgs, type ExportShardArgs, type ExternalSourceDiffResult, type ExternalSourceLike, FLAGS_FUNCTION_PREFIX, type FacetColumnOptions, type FacetColumnResult, type FacetValue, type FanoutMetricsResult, type FanoutPathCounters, type FanoutTopicStat, type FieldOperators, type FilterClause, type FilterOperator, type FlagEvaluation, type FlagsResult, type FunctionCallStat, type FunctionScanAttribution, type FunctionStatsResult, GEO_DEFAULT_PRECISION, GLOBAL_SHAPE_SNAPSHOT_TABLE, type GeoBoundingBox, type GeoFilterBuilderLike, type GeoIndexDefinitionLike, type GeoPoint, type GeoScoredDocument, type GroupByEntry, type GroupByOptions, type GuardableSchema$1 as GuardableSchema, IDEMPOTENCY_TABLE, type IdGenerator, type IdempotentRecord, type ImportError, type ImportShardAdminArgs, type ImportShardArgs, type ImportShardResult, type IncrementalMaterializeResult, type IndexDefinitionLike, type IndexKeyEntry, type IndexRangeBuilderLike, type KeyRange, type LifecycleDispatchInfo, type LifecycleEvent, MAIL_RETENTION, MAIL_TABLE, MAX_DURABLE_STREAM_BYTES, MAX_DURABLE_STREAM_CHUNKS, MAX_PAGE_SIZE, MAX_SQL_ROWS, type MaskColumnMetadata, type MaskPoliciesResult, type MaterializeResult, type MigrationDirection, type MigrationRunResult, type MigrationStatus, type MigrationStatusRow, type MutationDelta, type NestedWith, NotFoundError, NotUniqueError, type OnDeleteActionLike, type OrderByClause, type OrderByInput, type OrderKey, OwnerRelay, type OwnerRelayFrame, type PaginationOptions, type PitrBookmarkResult, type PitrRestoreArgs, type PitrRestoreResult, type PitrStorage, type PokeFrameMeta, type PromotionState, type PromotionThresholds, QUEUE_TABLE, type QueryArgs, type QueryPage, type QueueMessageOutcome, type QueueMessageRow, type QueueMetadata, type QueuesResult, RANK_TIEBREAK, RELATION_EXISTS_KEY, RELATION_FUNCTION_PREFIX, REPROJECTION_MIGRATION_PREFIX, RLS_UNWRAP_SYMBOL, type RankBeforeOptions, type RankBeforeResult, type RankDirection, type RankIndexDefinitionLike, type RankOptions, type RankPage, type RankPageComputation, type RankPageDeps, type RankPageOptions, type RankPageRow, type RankPageRowKey, type RankResult, type RankSortKeyLike, ReactiveCache, type ReactiveCacheOptions, type ReadFootprint, type ReadHook, type ReadTablePageOptions, type RecordMailInput, type RecordQueueMessageInput, type RelationDefinitionLike, type RelationExistsMarker, type RelayAttach, type RelayDetach, type RelayFrame, type RelayHost, RelayMember, type RelayShapePoke, type RelayShapeSeed, type RelayShapeSubscribe, type RenderedSql, type ReplicaFollowerHost, type ReplicaOwnerHost, type ReplicaReadiness, type ResolveRelationPredicatesOptions, type ResolveWithOptions, type ResolveWithResult, type ResolvedShape, type RestrictableQueryOptions, type RlsPoliciesResult, type RlsPolicyMetadata, RlsRequiredError, type RlsRoleMetadata, type RpcRequest, type RunDataMigrationOptions, type RunTriggersOptions, SCAN_DEP, SCHEMA_HISTORY_MAX_VERSIONS, SEARCH_STATE_TABLE, type SchedulableWorkflowReferenceLike, type ScheduledFunctionDoc, type SchedulerLike, type SchemaLike, type ScoredDocument, type SearchFilterBuilderLike, type SearchIndexDefinitionLike, type SearchScoredDocument, type SelectMatchingIdsOptions, type ServerDefaultContextLike, type SettingEntry, type SettingKind, type SettingsResult, type ShapePokePart, type ShapeRow, type ShapeRowOp, type ShapeSubscriptionQuery, type ShardRankPageResult, ShardRunner, type ShardRunnerOptions, type ShardSiblingHost, type ShardSocketLike, type SocketAttachment, type SortDirection, type SourceClientLike, type SourceCursorLike, type SourceRefresh, type SqlConsoleResult, type SqlCursor, type SqlEngine, type SqlExec, type SqlLintResult, type StorageMetadata, type StorageReference, type StorageReferenceResult, type StorageRuleMetadata, type StorageRulesResult, type StudioFeaturesResult, type SubscriptionConnection, type SubscriptionEnvelope, type SubscriptionIdentity, type SubscriptionInfo, type SubscriptionQuery, type SubscriptionReadFootprint, type SubscriptionsResult, type SystemDatabaseReader, type SystemDoc, type SystemQuery, type SystemReaderOptions, type SystemReaderSchedulerLike, type SystemReaderStorageLike, type SystemTableName, type TableColumnsResult, type TableDefinitionLike, type TableIndexInfo, type TableIndexesResult, type TableInfo, type TablePage, type TableReaderLike, type TablesColumnsResult, type TablesIndexesResult, type TransactionHeadroom, TransactionHeadroomTracker, type TransactionLimits, type TransactionSqlLike, type TriggerContextLike, type TriggerDefinitionLike, type TriggerEventLike, type TriggerOpLike, type TriggerTimingLike, type TtlSweepSpec, type ValidatorLike, type WhereInput, type WhereSqlStrategy, type WithInput, type WorkflowInstanceState, type WorkflowInstanceStatusResult, type WorkflowMetadata, type WorkflowsResult, type WriteEvent, type WriteHook, advanceClientWatermark, aggUpsertSql, aggregateSqlFunction, aggregateTableName, appendAuditEntry, appendCdcChange, appendStreamChunk, applyCdcChanges, applyOnDelete, applySelect, armRestore, assertFlatPredicate, assertReadonly, assertShapeShardable, assertValidClientId, awaitWsDrain, backfillAggregateIndexes, backfillRankIndexes, backfillSearchIndexes, backfillSearchIndexesForTable, boundingBoxCenter, boundingBoxGeohashes, buildIndexRange, buildPokeFrames, buildReprojectionMigration, buildSeekBeforeWhere, buildSeekWhere, buildSettings, bumpCdcEpoch, claimStreamRun, clampPromotionThresholds, clearCapturedMail, clearQueueMessages, coerceAggregateNumber, compileWhereSql, computeRankPage, containsRelationPredicate, countLegacyRows, coveringGeohashes, createCompanionSync, createDependencyTracker, createFanoutCounters, createIndexSql, createReadFootprint, createRelayLink, createReplicaLink, createShardCtxDb, createSystemReader, decideDurableAttach, decodeCursor, deleteGlobalShapeSnapshot, deleteGlobalShapeSnapshotsForConnection, deleteStreamRun, depKey, diffExternalSource, diffGlobalMembership, distinctValues, encodeAggregateKey, encodeCursor, encodeGeohash, encodePartitionKey, encodeRowsPatch, ensureAuditTable, ensureMailTable, exportShardRows, exportShardTable, facetColumn, fanOutScalarCounts, findStorageReferences, finishStreamRun, foldAggregateTally, gateReplicaDispatch, geoTableName, guardWriter, handleReplicaControl, hasTrigger, haversineMeters, hydrateDocsById, importShardRows, indexKeysForRow, isDevEnvironment, isFtsAvailable, isLossyBody, isRelationPredicate, isSoftDeleted, isSourceDue, jsonPath, jsonPathSql, keysTouchRanges, liftSourceId, lintReadonlySql, listTables, literalInList, matchesRankStaticWhere, matchesStaticWhere, materializeExternalRows, materializeExternalRowsIncremental, mergeChangedKeys, mergeWhere, migrateCdcLog, migrateCdcMeta, migrateClientWatermark, migrateDurableStreams, migrateGlobalShapeSnapshot, migrateIdempotency, migrateSearchState, minCdcSeq, nextPromotionState, normalizeCountArgument, normalizeIdStructurally, normalizeOrderKeys, normalizeSourceDocument, normalizeSourceValue, param, parseExportShardArgs, parseImportShardArgs, planAggregateLookup, pointInBoundingBox, projectColumns, pullExternalSourceIncrementalTick, pullExternalSourceTick, qualifiedJsonPath, qualifiedJsonPathSql, quoteIdentifier, rankKeyFromDocument as rankKeyFromDoc, rankTableName, reactiveCacheKey, readAggregateValue, readAuditLog, readBookmark, readCapturedMail, readCdcChanges, readCdcCursor, readCdcEpoch, readClientWatermark, readExternalSourceBaseline, readGlobalShapeSnapshot, readIdempotent, readMigrationStatus, readQueueMessageById, readQueueMessages, readSchemaHistory, readSchemaVersion, readSearchBackfillState, readStreamChunks, readStreamRun, readTablePage, recordCapturedMail, recordChangedKeys, recordFanoutPass, recordQueueMessages, recordSchemaVersion, relationHooks, relayCountFor, renderSql, reprojectableFields, reprojectionMigrationId, reprojectionTables, resolveRankPartition, resolveRelationPredicates, resolveWith, rowToDocument, runDataMigration, runDrizzle, runExternalSourceTick, runReadonlySql, runRowValidators, runShardMigrations, runSocketPool, runSql, runTriggers, selectExpiredIds, selectExportTables, selectIndexForAggregate, selectIndexForCount, selectIndexForGroupBy, selectMatchingIds, selectShapeMemberIds, selectShapeRows, sendDeltaFrames, serializeSqlValue, shapeRoutingKey, softDeleteScope, sortColumnName, sqliteInList, stableStringify, stableWireKey, subscriptionListDeltas, summarizeFanoutTopics, summarizeSubscriptions, tableColumns, tableFromDepKey, throwingScheduler, trimCdcChanges, trimIdempotent, trimStreamRuns, tryRowToDocument, trySendFrame, unionAll, validateImportRow, writeGlobalShapeSnapshot, writeIdempotent, writeSearchBackfillState, writeTouchesMemo };
|
|
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 };
|
package/dist/index.d.ts
CHANGED
|
@@ -839,6 +839,7 @@ interface ShapeSubscriptionQuery {
|
|
|
839
839
|
sinceSeq?: number;
|
|
840
840
|
}
|
|
841
841
|
interface SubscriptionEnvelope {
|
|
842
|
+
caps?: string[];
|
|
842
843
|
clientId?: string;
|
|
843
844
|
context?: Record<string, unknown>;
|
|
844
845
|
data?: unknown;
|
|
@@ -866,6 +867,7 @@ interface SocketAttachment {
|
|
|
866
867
|
context?: Record<string, unknown>;
|
|
867
868
|
expiresAt?: number;
|
|
868
869
|
identity?: Record<string, unknown>;
|
|
870
|
+
pageDeltas?: boolean;
|
|
869
871
|
shapes?: Record<string, ShapeSubscriptionQuery>;
|
|
870
872
|
subs: Record<string, SubscriptionQuery>;
|
|
871
873
|
userId?: string;
|
|
@@ -2087,7 +2089,17 @@ interface DrainableSink {
|
|
|
2087
2089
|
readonly bufferedAmount?: unknown;
|
|
2088
2090
|
}
|
|
2089
2091
|
declare const trySendFrame: (ws: FrameSink, frame: string) => boolean;
|
|
2090
|
-
|
|
2092
|
+
interface SubscriptionFrameInput {
|
|
2093
|
+
cursorSuffix: string;
|
|
2094
|
+
lastMutationId?: number;
|
|
2095
|
+
nextResult: unknown;
|
|
2096
|
+
pageDeltas?: boolean;
|
|
2097
|
+
previousJson?: string;
|
|
2098
|
+
snapshotJson: string;
|
|
2099
|
+
subId: string;
|
|
2100
|
+
table: string;
|
|
2101
|
+
}
|
|
2102
|
+
declare const subscriptionFrames: (input: SubscriptionFrameInput) => string[];
|
|
2091
2103
|
declare const awaitWsDrain: (ws: DrainableSink) => Promise<void>;
|
|
2092
2104
|
interface SubscriptionReadFootprint {
|
|
2093
2105
|
ranges?: Map<string, KeyRange[]>;
|
|
@@ -2126,4 +2138,4 @@ interface WhereSqlStrategy {
|
|
|
2126
2138
|
}
|
|
2127
2139
|
declare const literalInList: (reference: SQL, items: ReadonlyArray<unknown>, negated: boolean) => SQL;
|
|
2128
2140
|
declare const compileWhereSql: (where: WhereInput | undefined, strategy: WhereSqlStrategy) => SQL | undefined;
|
|
2129
|
-
export { ADMIN_FUNCTIONS, ADMIN_FUNCTION_PREFIX, AGGREGATE_SQL_FUNCTION, AGG_COUNT, AGG_KEY, AGG_VALUE, AUDIT_LOG_TABLE, type AdvisorProcedure, type AdvisorProceduresResult, type AdvisoriesResult, type AdvisoryFinding, type AggregateIndexDefinitionLike, type AggregateOp, type AggregateOptions, type AggregateResult, type AggregateTally, type AppendAuditEntry, type ApplyOnDeleteOptions$1 as ApplyOnDeleteOptions, type AuditEntry, type AuditLogResult, type BroadcastDelta, CDC_LOG_TABLE, CDC_META_TABLE, CLIENT_WATERMARK_TABLE, type CacheEntry, type CapturedMailRow, type CdcChange, type ChangedKeys, type Clock, type ColumnMeta, type ColumnMetaLike, type CompanionSync, type CompanionSyncDeps, ConflictError, type ConflictKind, type CountArgs, CountRlsUnsupportedError, type CreateWorkflowInstanceResult, type CrossShardReadArgs, type CtxDbOptions, DATA_MIGRATION_STATE_TABLE, DEFAULT_FANOUT_TOPIC_LIMIT, DEFAULT_MAX_RELATION_KEYS, DEFAULT_MAX_RELAYS, DEFAULT_PROMOTION_THRESHOLDS, DEFAULT_TRANSACTION_LIMITS, DOC_COLUMN, type DataMigrationDocument, type DataMigrationLike, type DataMigrationTransform, type DatabaseWriterLike, type DependencyTracker, type DeployInfo, type DurableAttachDecision, type DurableStreamAttach, type DurableStreamRun, DurableStreamRunner, type DurableStreamSink, type ExportRow, type ExportShardAdminArgs, type ExportShardArgs, type ExternalSourceDiffResult, type ExternalSourceLike, FLAGS_FUNCTION_PREFIX, type FacetColumnOptions, type FacetColumnResult, type FacetValue, type FanoutMetricsResult, type FanoutPathCounters, type FanoutTopicStat, type FieldOperators, type FilterClause, type FilterOperator, type FlagEvaluation, type FlagsResult, type FunctionCallStat, type FunctionScanAttribution, type FunctionStatsResult, GEO_DEFAULT_PRECISION, GLOBAL_SHAPE_SNAPSHOT_TABLE, type GeoBoundingBox, type GeoFilterBuilderLike, type GeoIndexDefinitionLike, type GeoPoint, type GeoScoredDocument, type GroupByEntry, type GroupByOptions, type GuardableSchema$1 as GuardableSchema, IDEMPOTENCY_TABLE, type IdGenerator, type IdempotentRecord, type ImportError, type ImportShardAdminArgs, type ImportShardArgs, type ImportShardResult, type IncrementalMaterializeResult, type IndexDefinitionLike, type IndexKeyEntry, type IndexRangeBuilderLike, type KeyRange, type LifecycleDispatchInfo, type LifecycleEvent, MAIL_RETENTION, MAIL_TABLE, MAX_DURABLE_STREAM_BYTES, MAX_DURABLE_STREAM_CHUNKS, MAX_PAGE_SIZE, MAX_SQL_ROWS, type MaskColumnMetadata, type MaskPoliciesResult, type MaterializeResult, type MigrationDirection, type MigrationRunResult, type MigrationStatus, type MigrationStatusRow, type MutationDelta, type NestedWith, NotFoundError, NotUniqueError, type OnDeleteActionLike, type OrderByClause, type OrderByInput, type OrderKey, OwnerRelay, type OwnerRelayFrame, type PaginationOptions, type PitrBookmarkResult, type PitrRestoreArgs, type PitrRestoreResult, type PitrStorage, type PokeFrameMeta, type PromotionState, type PromotionThresholds, QUEUE_TABLE, type QueryArgs, type QueryPage, type QueueMessageOutcome, type QueueMessageRow, type QueueMetadata, type QueuesResult, RANK_TIEBREAK, RELATION_EXISTS_KEY, RELATION_FUNCTION_PREFIX, REPROJECTION_MIGRATION_PREFIX, RLS_UNWRAP_SYMBOL, type RankBeforeOptions, type RankBeforeResult, type RankDirection, type RankIndexDefinitionLike, type RankOptions, type RankPage, type RankPageComputation, type RankPageDeps, type RankPageOptions, type RankPageRow, type RankPageRowKey, type RankResult, type RankSortKeyLike, ReactiveCache, type ReactiveCacheOptions, type ReadFootprint, type ReadHook, type ReadTablePageOptions, type RecordMailInput, type RecordQueueMessageInput, type RelationDefinitionLike, type RelationExistsMarker, type RelayAttach, type RelayDetach, type RelayFrame, type RelayHost, RelayMember, type RelayShapePoke, type RelayShapeSeed, type RelayShapeSubscribe, type RenderedSql, type ReplicaFollowerHost, type ReplicaOwnerHost, type ReplicaReadiness, type ResolveRelationPredicatesOptions, type ResolveWithOptions, type ResolveWithResult, type ResolvedShape, type RestrictableQueryOptions, type RlsPoliciesResult, type RlsPolicyMetadata, RlsRequiredError, type RlsRoleMetadata, type RpcRequest, type RunDataMigrationOptions, type RunTriggersOptions, SCAN_DEP, SCHEMA_HISTORY_MAX_VERSIONS, SEARCH_STATE_TABLE, type SchedulableWorkflowReferenceLike, type ScheduledFunctionDoc, type SchedulerLike, type SchemaLike, type ScoredDocument, type SearchFilterBuilderLike, type SearchIndexDefinitionLike, type SearchScoredDocument, type SelectMatchingIdsOptions, type ServerDefaultContextLike, type SettingEntry, type SettingKind, type SettingsResult, type ShapePokePart, type ShapeRow, type ShapeRowOp, type ShapeSubscriptionQuery, type ShardRankPageResult, ShardRunner, type ShardRunnerOptions, type ShardSiblingHost, type ShardSocketLike, type SocketAttachment, type SortDirection, type SourceClientLike, type SourceCursorLike, type SourceRefresh, type SqlConsoleResult, type SqlCursor, type SqlEngine, type SqlExec, type SqlLintResult, type StorageMetadata, type StorageReference, type StorageReferenceResult, type StorageRuleMetadata, type StorageRulesResult, type StudioFeaturesResult, type SubscriptionConnection, type SubscriptionEnvelope, type SubscriptionIdentity, type SubscriptionInfo, type SubscriptionQuery, type SubscriptionReadFootprint, type SubscriptionsResult, type SystemDatabaseReader, type SystemDoc, type SystemQuery, type SystemReaderOptions, type SystemReaderSchedulerLike, type SystemReaderStorageLike, type SystemTableName, type TableColumnsResult, type TableDefinitionLike, type TableIndexInfo, type TableIndexesResult, type TableInfo, type TablePage, type TableReaderLike, type TablesColumnsResult, type TablesIndexesResult, type TransactionHeadroom, TransactionHeadroomTracker, type TransactionLimits, type TransactionSqlLike, type TriggerContextLike, type TriggerDefinitionLike, type TriggerEventLike, type TriggerOpLike, type TriggerTimingLike, type TtlSweepSpec, type ValidatorLike, type WhereInput, type WhereSqlStrategy, type WithInput, type WorkflowInstanceState, type WorkflowInstanceStatusResult, type WorkflowMetadata, type WorkflowsResult, type WriteEvent, type WriteHook, advanceClientWatermark, aggUpsertSql, aggregateSqlFunction, aggregateTableName, appendAuditEntry, appendCdcChange, appendStreamChunk, applyCdcChanges, applyOnDelete, applySelect, armRestore, assertFlatPredicate, assertReadonly, assertShapeShardable, assertValidClientId, awaitWsDrain, backfillAggregateIndexes, backfillRankIndexes, backfillSearchIndexes, backfillSearchIndexesForTable, boundingBoxCenter, boundingBoxGeohashes, buildIndexRange, buildPokeFrames, buildReprojectionMigration, buildSeekBeforeWhere, buildSeekWhere, buildSettings, bumpCdcEpoch, claimStreamRun, clampPromotionThresholds, clearCapturedMail, clearQueueMessages, coerceAggregateNumber, compileWhereSql, computeRankPage, containsRelationPredicate, countLegacyRows, coveringGeohashes, createCompanionSync, createDependencyTracker, createFanoutCounters, createIndexSql, createReadFootprint, createRelayLink, createReplicaLink, createShardCtxDb, createSystemReader, decideDurableAttach, decodeCursor, deleteGlobalShapeSnapshot, deleteGlobalShapeSnapshotsForConnection, deleteStreamRun, depKey, diffExternalSource, diffGlobalMembership, distinctValues, encodeAggregateKey, encodeCursor, encodeGeohash, encodePartitionKey, encodeRowsPatch, ensureAuditTable, ensureMailTable, exportShardRows, exportShardTable, facetColumn, fanOutScalarCounts, findStorageReferences, finishStreamRun, foldAggregateTally, gateReplicaDispatch, geoTableName, guardWriter, handleReplicaControl, hasTrigger, haversineMeters, hydrateDocsById, importShardRows, indexKeysForRow, isDevEnvironment, isFtsAvailable, isLossyBody, isRelationPredicate, isSoftDeleted, isSourceDue, jsonPath, jsonPathSql, keysTouchRanges, liftSourceId, lintReadonlySql, listTables, literalInList, matchesRankStaticWhere, matchesStaticWhere, materializeExternalRows, materializeExternalRowsIncremental, mergeChangedKeys, mergeWhere, migrateCdcLog, migrateCdcMeta, migrateClientWatermark, migrateDurableStreams, migrateGlobalShapeSnapshot, migrateIdempotency, migrateSearchState, minCdcSeq, nextPromotionState, normalizeCountArgument, normalizeIdStructurally, normalizeOrderKeys, normalizeSourceDocument, normalizeSourceValue, param, parseExportShardArgs, parseImportShardArgs, planAggregateLookup, pointInBoundingBox, projectColumns, pullExternalSourceIncrementalTick, pullExternalSourceTick, qualifiedJsonPath, qualifiedJsonPathSql, quoteIdentifier, rankKeyFromDocument as rankKeyFromDoc, rankTableName, reactiveCacheKey, readAggregateValue, readAuditLog, readBookmark, readCapturedMail, readCdcChanges, readCdcCursor, readCdcEpoch, readClientWatermark, readExternalSourceBaseline, readGlobalShapeSnapshot, readIdempotent, readMigrationStatus, readQueueMessageById, readQueueMessages, readSchemaHistory, readSchemaVersion, readSearchBackfillState, readStreamChunks, readStreamRun, readTablePage, recordCapturedMail, recordChangedKeys, recordFanoutPass, recordQueueMessages, recordSchemaVersion, relationHooks, relayCountFor, renderSql, reprojectableFields, reprojectionMigrationId, reprojectionTables, resolveRankPartition, resolveRelationPredicates, resolveWith, rowToDocument, runDataMigration, runDrizzle, runExternalSourceTick, runReadonlySql, runRowValidators, runShardMigrations, runSocketPool, runSql, runTriggers, selectExpiredIds, selectExportTables, selectIndexForAggregate, selectIndexForCount, selectIndexForGroupBy, selectMatchingIds, selectShapeMemberIds, selectShapeRows, sendDeltaFrames, serializeSqlValue, shapeRoutingKey, softDeleteScope, sortColumnName, sqliteInList, stableStringify, stableWireKey, subscriptionListDeltas, summarizeFanoutTopics, summarizeSubscriptions, tableColumns, tableFromDepKey, throwingScheduler, trimCdcChanges, trimIdempotent, trimStreamRuns, tryRowToDocument, trySendFrame, unionAll, validateImportRow, writeGlobalShapeSnapshot, writeIdempotent, writeSearchBackfillState, writeTouchesMemo };
|
|
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 };
|
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-DgYMC5tr.mjs";import{CountRlsUnsupportedError as R,mergeWhere as I,planAggregateLookup as C,selectIndexForAggregate as _,selectIndexForCount as L,selectIndexForGroupBy as b}from"./packem_shared/CountRlsUnsupportedError-8BqPYQoP.mjs";import{AUDIT_LOG_TABLE as N,appendAuditEntry as y,ensureAuditTable as D,readAuditLog as O}from"./packem_shared/AUDIT_LOG_TABLE-Bl2mYtAQ.mjs";import{NotUniqueError as k,assertValidClientId as P,createShardCtxDb as B,normalizeIdStructurally as G}from"./packem_shared/NotUniqueError-BeTJrgRe.mjs";import{backfillAggregateIndexes as w,backfillRankIndexes as K,backfillSearchIndexes as q,backfillSearchIndexesForTable as W}from"./packem_shared/backfillAggregateIndexes-BEMWTEq1.mjs";import{CDC_LOG_TABLE as z,CDC_META_TABLE as X,appendCdcChange as H,applyCdcChanges as V,bumpCdcEpoch as Y,migrateCdcLog as j,migrateCdcMeta as Q,minCdcSeq as J,readCdcChanges as Z,readCdcCursor as $,readCdcEpoch as ee,trimCdcChanges as re}from"./packem_shared/CDC_LOG_TABLE-DH-KHUfU.mjs";import{CLIENT_WATERMARK_TABLE as ae,advanceClientWatermark as te,migrateClientWatermark as ne,readClientWatermark as le}from"./packem_shared/CLIENT_WATERMARK_TABLE-LrKfdxyt.mjs";import{S as ie}from"./packem_shared/ctx-db-companions-c12P7dbv.mjs";import{GLOBAL_SHAPE_SNAPSHOT_TABLE as pe,deleteGlobalShapeSnapshot as de,deleteGlobalShapeSnapshotsForConnection as ce,migrateGlobalShapeSnapshot as Se,readGlobalShapeSnapshot as ue,writeGlobalShapeSnapshot as xe}from"./packem_shared/GLOBAL_SHAPE_SNAPSHOT_TABLE-B2LKe4KU.mjs";import{IDEMPOTENCY_TABLE as Te,migrateIdempotency as Ae,readIdempotent as Ee,trimIdempotent as ge,writeIdempotent as he}from"./packem_shared/IDEMPOTENCY_TABLE-tQ5mnqvw.mjs";import{computeRankPage as Ie,hydrateDocsById as Ce}from"./packem_shared/computeRankPage-D1ygctSC.mjs";import{SEARCH_STATE_TABLE as Le,migrateSearchState as be,readSearchBackfillState as Me,writeSearchBackfillState as Ne}from"./packem_shared/SEARCH_STATE_TABLE-DRk_SB72.mjs";import{selectShapeMemberIds as De,selectShapeRows as Oe}from"./packem_shared/selectShapeMemberIds-WzxOG62k.mjs";import{DATA_MIGRATION_STATE_TABLE as ke,readMigrationStatus as Pe,runDataMigration as Be}from"./packem_shared/DATA_MIGRATION_STATE_TABLE-DIQTu___.mjs";import{SCAN_DEP as Ue,createDependencyTracker as we,depKey as Ke,tableFromDepKey as qe}from"./packem_shared/SCAN_DEP-D_yR9EeV.mjs";import{runDrizzle as ve,runSql as ze}from"./packem_shared/runDrizzle-C3n5gJsk.mjs";import{T as He,c as Ve,p as Ye,a as je,A as Qe,y as Je,h as Ze,C as $e,_ as er,N as rr,S as or,O as ar,E as tr,I as nr,D as lr}from"./packem_shared/do-sql-C7qrlm6-.mjs";import{param as ir,renderSql as mr,sqliteInList as pr,unionAll as dr}from"./packem_shared/param-CYxL68V-.mjs";import{appendStreamChunk as Sr,claimStreamRun as ur,deleteStreamRun as xr,finishStreamRun as fr,migrateDurableStreams as Tr,readStreamChunks as Ar,readStreamRun as Er,trimStreamRuns as gr}from"./packem_shared/appendStreamChunk-ksZYy1hZ.mjs";import{DurableStreamRunner as Rr,MAX_DURABLE_STREAM_BYTES as Ir,MAX_DURABLE_STREAM_CHUNKS as Cr,decideDurableAttach as _r}from"./packem_shared/DurableStreamRunner-C-OSu02s.mjs";import{diffExternalSource as br}from"./packem_shared/diffExternalSource-DMpkJta1.mjs";import{liftSourceId as Nr,normalizeSourceDocument as yr,normalizeSourceValue as Dr}from"./packem_shared/liftSourceId-DApAbu7Q.mjs";import{materializeExternalRows as Fr,materializeExternalRowsIncremental as kr,readExternalSourceBaseline as Pr,runExternalSourceTick as Br}from"./packem_shared/materializeExternalRows-D53xwGfY.mjs";import{isSoftDeleted as Ur,isSourceDue as wr,pullExternalSourceIncrementalTick as Kr,pullExternalSourceTick as qr}from"./packem_shared/isSoftDeleted-Tr2to2aw.mjs";import{GEO_DEFAULT_PRECISION as vr,boundingBoxCenter as zr,boundingBoxGeohashes as Xr,coveringGeohashes as Hr,encodeGeohash as Vr,haversineMeters as Yr,pointInBoundingBox as jr}from"./packem_shared/GEO_DEFAULT_PRECISION-DyI5zggj.mjs";import{ADMIN_FUNCTIONS as Jr,ADMIN_FUNCTION_PREFIX as Zr,DEFAULT_FANOUT_TOPIC_LIMIT as $r,FLAGS_FUNCTION_PREFIX as eo,MAX_PAGE_SIZE as ro,RELATION_FUNCTION_PREFIX as oo,createFanoutCounters as ao,facetColumn as to,findStorageReferences as no,listTables as lo,readTablePage as so,recordFanoutPass as io,selectMatchingIds as mo,summarizeFanoutTopics as po,summarizeSubscriptions as co}from"./packem_shared/ADMIN_FUNCTIONS-B5HZoizX.mjs";import{MAIL_RETENTION as uo,MAIL_TABLE as xo,clearCapturedMail as fo,ensureMailTable as To,readCapturedMail as Ao,recordCapturedMail as Eo}from"./packem_shared/MAIL_RETENTION-CzZuX9bd.mjs";import{NotFoundError as ho}from"./packem_shared/NotFoundError-BhF7FeFr.mjs";import{armRestore as Io,readBookmark as Co}from"./packem_shared/armRestore-BNzdvQ_o.mjs";import{applySelect as Lo,buildSeekBeforeWhere as bo,buildSeekWhere as Mo,decodeCursor as No,encodeCursor as yo,normalizeOrderKeys as Do,softDeleteScope as Oo}from"./packem_shared/applySelect-UY-o13Ia.mjs";import{QUEUE_TABLE as ko,clearQueueMessages as Po,isLossyBody as Bo,readQueueMessageById as Go,readQueueMessages as Uo,recordQueueMessages as wo}from"./packem_shared/QUEUE_TABLE-BX0nopuT.mjs";import{RANK_TIEBREAK as qo,encodePartitionKey as Wo,matchesRankStaticWhere as vo,rankKeyFromDoc as zo,rankTableName as Xo,resolveRankPartition as Ho,sortColumnName as Vo}from"./packem_shared/RANK_TIEBREAK-DDtST3gN.mjs";import{ReactiveCache as jo,reactiveCacheKey as Qo}from"./packem_shared/ReactiveCache-Cu8IfE1M.mjs";import{createReadFootprint as Zo}from"./packem_shared/createReadFootprint-DIrrxRTE.mjs";import{buildIndexRange as ea,indexKeysForRow as ra,keysTouchRanges as oa}from"./packem_shared/buildIndexRange-DFsdtPjD.mjs";import{DEFAULT_MAX_RELATION_KEYS as ta,assertFlatPredicate as na,assertShapeShardable as la,containsRelationPredicate as sa,isRelationPredicate as ia,resolveRelationPredicates as ma}from"./packem_shared/DEFAULT_MAX_RELATION_KEYS-DjKka36Z.mjs";import{applyOnDelete as da,distinctValues as ca,fanOutScalarCounts as Sa,relationHooks as ua,resolveWith as xa,runRowValidators as fa}from"./packem_shared/applyOnDelete-By23GK-k.mjs";import{DEFAULT_PROMOTION_THRESHOLDS as Aa,clampPromotionThresholds as Ea,nextPromotionState as ga,relayCountFor as ha,shapeRoutingKey as Ra}from"./packem_shared/DEFAULT_PROMOTION_THRESHOLDS-B2rUe1bg.mjs";import{DEFAULT_MAX_RELAYS as Ca,OwnerRelay as _a,RelayMember as La,createRelayLink as ba}from"./packem_shared/DEFAULT_MAX_RELAYS-B19vrJxP.mjs";import{createReplicaLink as Na,gateReplicaDispatch as ya,handleReplicaControl as Da}from"./packem_shared/createReplicaLink-BMNW0SX6.mjs";import{buildReprojectionMigration as Fa,countLegacyRows as ka,reprojectableFields as Pa,reprojectionTables as Ba}from"./packem_shared/buildReprojectionMigration-YQSJX2cC.mjs";import{RLS_UNWRAP_SYMBOL as Ua,RlsRequiredError as wa,guardWriter as Ka}from"./packem_shared/RLS_UNWRAP_SYMBOL-DcqORh2s.mjs";import{SCHEMA_HISTORY_MAX_VERSIONS as Wa,readSchemaHistory as va,readSchemaVersion as za,recordSchemaVersion as Xa}from"./packem_shared/SCHEMA_HISTORY_MAX_VERSIONS-CEK7b_7v.mjs";import{serializeSqlValue as Va}from"./packem_shared/serializeSqlValue-BR4UOWoP.mjs";import{buildSettings as ja,isDevEnvironment as Qa}from"./packem_shared/buildSettings-COIJsw7a.mjs";import{buildPokeFrames as Za,diffGlobalMembership as $a,encodeRowsPatch as et,projectColumns as rt}from"./packem_shared/buildPokeFrames-CqxaN8_H.mjs";import{ShardRunner as at}from"./packem_shared/ShardRunner-DIqVdWtk.mjs";import{runSocketPool as nt}from"./packem_shared/runSocketPool-DPQLVyWF.mjs";import{MAX_SQL_ROWS as st,assertReadonly as it,lintReadonlySql as mt,runReadonlySql as pt}from"./packem_shared/MAX_SQL_ROWS-nMwkxv5f.mjs";import{awaitWsDrain as ct,sendDeltaFrames as St,subscriptionListDeltas as ut,trySendFrame as xt}from"./packem_shared/awaitWsDrain-Bp2jKzIb.mjs";import{mergeChangedKeys as Tt,recordChangedKeys as At,writeTouchesMemo as Et}from"./packem_shared/mergeChangedKeys-BXtUgIPW.mjs";import{createSystemReader as ht}from"./packem_shared/createSystemReader-DcDcrtM3.mjs";import{ConflictError as It}from"./packem_shared/ConflictError-C8GtJmjS.mjs";import{DEFAULT_TRANSACTION_LIMITS as _t,TransactionHeadroomTracker as Lt}from"./packem_shared/DEFAULT_TRANSACTION_LIMITS-DLUzZbta.mjs";import{hasTrigger as Mt,runTriggers as Nt}from"./packem_shared/hasTrigger-CbkOHExZ.mjs";import{selectExpiredIds as Dt}from"./packem_shared/selectExpiredIds-C3Vv1gPm.mjs";import{compileWhereSql as Ft,literalInList as kt}from"./packem_shared/compileWhereSql-B3hq_v98.mjs";import{RELATION_EXISTS_KEY as Bt}from"./packem_shared/RELATION_EXISTS_KEY-BaqSIFU1.mjs";import{REPROJECTION_MIGRATION_PREFIX as Ut,reprojectionMigrationId as wt}from"./packem_shared/REPROJECTION_MIGRATION_PREFIX-D2dltRFC.mjs";import{quoteIdentifier as qt}from"./packem_shared/quoteIdentifier-CObIFRhb.mjs";import{runShardMigrations as vt}from"./packem_shared/runShardMigrations-BAtfEXbB.mjs";import{stableStringify as Xt}from"./packem_shared/stableStringify-BjLh4gvA.mjs";import{stableWireKey as Vt}from"./packem_shared/stableWireKey-l3cjIt-9.mjs";export{Jr as ADMIN_FUNCTIONS,Zr as ADMIN_FUNCTION_PREFIX,p as AGGREGATE_SQL_FUNCTION,He as AGG_COUNT,Ve as AGG_KEY,Ye as AGG_VALUE,N as AUDIT_LOG_TABLE,z as CDC_LOG_TABLE,X as CDC_META_TABLE,ae as CLIENT_WATERMARK_TABLE,It as ConflictError,R as CountRlsUnsupportedError,ke as DATA_MIGRATION_STATE_TABLE,$r as DEFAULT_FANOUT_TOPIC_LIMIT,ta as DEFAULT_MAX_RELATION_KEYS,Ca as DEFAULT_MAX_RELAYS,Aa as DEFAULT_PROMOTION_THRESHOLDS,_t as DEFAULT_TRANSACTION_LIMITS,je as DOC_COLUMN,Rr as DurableStreamRunner,eo as FLAGS_FUNCTION_PREFIX,vr as GEO_DEFAULT_PRECISION,pe as GLOBAL_SHAPE_SNAPSHOT_TABLE,Te as IDEMPOTENCY_TABLE,uo as MAIL_RETENTION,xo as MAIL_TABLE,Ir as MAX_DURABLE_STREAM_BYTES,Cr as MAX_DURABLE_STREAM_CHUNKS,ro as MAX_PAGE_SIZE,st as MAX_SQL_ROWS,ho as NotFoundError,k as NotUniqueError,_a as OwnerRelay,ko as QUEUE_TABLE,qo as RANK_TIEBREAK,Bt as RELATION_EXISTS_KEY,oo as RELATION_FUNCTION_PREFIX,Ut as REPROJECTION_MIGRATION_PREFIX,Ua as RLS_UNWRAP_SYMBOL,jo as ReactiveCache,La as RelayMember,wa as RlsRequiredError,Ue as SCAN_DEP,Wa as SCHEMA_HISTORY_MAX_VERSIONS,Le as SEARCH_STATE_TABLE,at as ShardRunner,Lt as TransactionHeadroomTracker,te as advanceClientWatermark,Qe as aggUpsertSql,d as aggregateSqlFunction,f as aggregateTableName,y as appendAuditEntry,H as appendCdcChange,Sr as appendStreamChunk,V as applyCdcChanges,da as applyOnDelete,Lo as applySelect,Io as armRestore,na as assertFlatPredicate,it as assertReadonly,la as assertShapeShardable,P as assertValidClientId,ct as awaitWsDrain,w as backfillAggregateIndexes,K as backfillRankIndexes,q as backfillSearchIndexes,W as backfillSearchIndexesForTable,zr as boundingBoxCenter,Xr as boundingBoxGeohashes,ea as buildIndexRange,Za as buildPokeFrames,Fa as buildReprojectionMigration,bo as buildSeekBeforeWhere,Mo as buildSeekWhere,ja as buildSettings,Y as bumpCdcEpoch,ur as claimStreamRun,Ea as clampPromotionThresholds,fo as clearCapturedMail,Po as clearQueueMessages,T as coerceAggregateNumber,Ft as compileWhereSql,Ie as computeRankPage,sa as containsRelationPredicate,ka as countLegacyRows,Hr as coveringGeohashes,ie as createCompanionSync,we as createDependencyTracker,ao as createFanoutCounters,Je as createIndexSql,Zo as createReadFootprint,ba as createRelayLink,Na as createReplicaLink,B as createShardCtxDb,ht as createSystemReader,_r as decideDurableAttach,No as decodeCursor,de as deleteGlobalShapeSnapshot,ce as deleteGlobalShapeSnapshotsForConnection,xr as deleteStreamRun,Ke as depKey,br as diffExternalSource,$a as diffGlobalMembership,ca as distinctValues,A as encodeAggregateKey,yo as encodeCursor,Vr as encodeGeohash,Wo as encodePartitionKey,et as encodeRowsPatch,D as ensureAuditTable,To as ensureMailTable,o as exportShardRows,a as exportShardTable,to as facetColumn,Sa as fanOutScalarCounts,no as findStorageReferences,fr as finishStreamRun,E as foldAggregateTally,ya as gateReplicaDispatch,Ze as geoTableName,Ka as guardWriter,Da as handleReplicaControl,Mt as hasTrigger,Yr as haversineMeters,Ce as hydrateDocsById,t as importShardRows,ra as indexKeysForRow,Qa as isDevEnvironment,$e as isFtsAvailable,Bo as isLossyBody,ia as isRelationPredicate,Ur as isSoftDeleted,wr as isSourceDue,er as jsonPath,rr as jsonPathSql,oa as keysTouchRanges,Nr as liftSourceId,mt as lintReadonlySql,lo as listTables,kt as literalInList,vo as matchesRankStaticWhere,c as matchesStaticWhere,Fr as materializeExternalRows,kr as materializeExternalRowsIncremental,Tt as mergeChangedKeys,I as mergeWhere,j as migrateCdcLog,Q as migrateCdcMeta,ne as migrateClientWatermark,Tr as migrateDurableStreams,Se as migrateGlobalShapeSnapshot,Ae as migrateIdempotency,be as migrateSearchState,J as minCdcSeq,ga as nextPromotionState,S as normalizeCountArgument,G as normalizeIdStructurally,Do as normalizeOrderKeys,yr as normalizeSourceDocument,Dr as normalizeSourceValue,ir as param,n as parseExportShardArgs,l as parseImportShardArgs,C as planAggregateLookup,jr as pointInBoundingBox,rt as projectColumns,Kr as pullExternalSourceIncrementalTick,qr as pullExternalSourceTick,or as qualifiedJsonPath,ar as qualifiedJsonPathSql,qt as quoteIdentifier,zo as rankKeyFromDoc,Xo as rankTableName,Qo as reactiveCacheKey,g as readAggregateValue,O as readAuditLog,Co as readBookmark,Ao as readCapturedMail,Z as readCdcChanges,$ as readCdcCursor,ee as readCdcEpoch,le as readClientWatermark,Pr as readExternalSourceBaseline,ue as readGlobalShapeSnapshot,Ee as readIdempotent,Pe as readMigrationStatus,Go as readQueueMessageById,Uo as readQueueMessages,va as readSchemaHistory,za as readSchemaVersion,Me as readSearchBackfillState,Ar as readStreamChunks,Er as readStreamRun,so as readTablePage,Eo as recordCapturedMail,At as recordChangedKeys,io as recordFanoutPass,wo as recordQueueMessages,Xa as recordSchemaVersion,ua as relationHooks,ha as relayCountFor,mr as renderSql,Pa as reprojectableFields,wt as reprojectionMigrationId,Ba as reprojectionTables,Ho as resolveRankPartition,ma as resolveRelationPredicates,xa as resolveWith,tr as rowToDocument,Be as runDataMigration,ve as runDrizzle,Br as runExternalSourceTick,pt as runReadonlySql,fa as runRowValidators,vt as runShardMigrations,nt as runSocketPool,ze as runSql,Nt as runTriggers,Dt as selectExpiredIds,s as selectExportTables,_ as selectIndexForAggregate,L as selectIndexForCount,b as selectIndexForGroupBy,mo as selectMatchingIds,De as selectShapeMemberIds,Oe as selectShapeRows,St as sendDeltaFrames,Va as serializeSqlValue,Ra as shapeRoutingKey,Oo as softDeleteScope,Vo as sortColumnName,pr as sqliteInList,Xt as stableStringify,Vt as stableWireKey,ut as subscriptionListDeltas,po as summarizeFanoutTopics,co as summarizeSubscriptions,nr as tableColumns,qe as tableFromDepKey,u as throwingScheduler,re as trimCdcChanges,ge as trimIdempotent,gr as trimStreamRuns,lr as tryRowToDocument,xt as trySendFrame,dr as unionAll,i as validateImportRow,xe as writeGlobalShapeSnapshot,he as writeIdempotent,Ne as writeSearchBackfillState,Et as writeTouchesMemo};
|
|
1
|
+
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 +1 @@
|
|
|
1
|
-
import{LunoraError as T}from"@lunora/errors";import{j as L,s as k}from"./do-sql-C7qrlm6-.mjs";import{quoteIdentifier as d}from"./quoteIdentifier-CObIFRhb.mjs";import{s as P}from"./wire-codec-Dsy70M3Q.mjs";const te="__lunora_admin__:",ae="__lunora_relation__:",re="__lunora_flags__:",se={applyCdc:"__lunora_admin__:applyCdc",aiAvailable:"__lunora_admin__:aiAvailable",aiChartConfig:"__lunora_admin__:aiChartConfig",aiGenerateSql:"__lunora_admin__:aiGenerateSql",aiTableFilter:"__lunora_admin__:aiTableFilter",assignIssue:"__lunora_admin__:assignIssue",backRelationCounts:"__lunora_admin__:backRelationCounts",cdcSync:"__lunora_admin__:cdcSync",clearCapturedMail:"__lunora_admin__:clearCapturedMail",clearQueueMessages:"__lunora_admin__:clearQueueMessages",clearTable:"__lunora_admin__:clearTable",createWorkflowInstance:"__lunora_admin__:createWorkflowInstance",deleteRows:"__lunora_admin__:deleteRows",describeTable:"__lunora_admin__:describeTable",describeTables:"__lunora_admin__:describeTables",explainIssue:"__lunora_admin__:explainIssue",exportShard:"__lunora_admin__:exportShard",facetColumn:"__lunora_admin__:facetColumn",getAdvisories:"__lunora_admin__:getAdvisories",getAdvisorProcedures:"__lunora_admin__:getAdvisorProcedures",getAuditLog:"__lunora_admin__:getAuditLog",getAuthMetrics:"__lunora_admin__:getAuthMetrics",getCapturedMail:"__lunora_admin__:getCapturedMail",getFanoutMetrics:"__lunora_admin__:getFanoutMetrics",getFunctionStats:"__lunora_admin__:getFunctionStats",getIssues:"__lunora_admin__:getIssues",getMetricHistory:"__lunora_admin__:getMetricHistory",getMetricSeries:"__lunora_admin__:getMetricSeries",listSubscriptions:"__lunora_admin__:listSubscriptions",listTableIndexes:"__lunora_admin__:listTableIndexes",listTablesIndexes:"__lunora_admin__:listTablesIndexes",getLogs:"__lunora_admin__:getLogs",getMetrics:"__lunora_admin__:getMetrics",getPitrBookmark:"__lunora_admin__:getPitrBookmark",getQueryInsights:"__lunora_admin__:getQueryInsights",getQueueMessages:"__lunora_admin__:getQueueMessages",getRequestLog:"__lunora_admin__:getRequestLog",getSecurityAudit:"__lunora_admin__:getSecurityAudit",getSettings:"__lunora_admin__:getSettings",getTraces:"__lunora_admin__:getTraces",getWorkflowInstanceStatus:"__lunora_admin__:getWorkflowInstanceStatus",ignoreIssue:"__lunora_admin__:ignoreIssue",importShard:"__lunora_admin__:importShard",listFlags:"__lunora_admin__:listFlags",listQueues:"__lunora_admin__:listQueues",lintSql:"__lunora_admin__:lintSql",listTables:"__lunora_admin__:listTables",listWorkflows:"__lunora_admin__:listWorkflows",maskPolicies:"__lunora_admin__:maskPolicies",migrationStatus:"__lunora_admin__:migrationStatus",pitrRestore:"__lunora_admin__:pitrRestore",rankBefore:"__lunora_admin__:rankBefore",rankPage:"__lunora_admin__:rankPage",readTablePage:"__lunora_admin__:readTablePage",recordAuthEvent:"__lunora_admin__:recordAuthEvent",recordContainerEvent:"__lunora_admin__:recordContainerEvent",recordMail:"__lunora_admin__:recordMail",recordQueueMessage:"__lunora_admin__:recordQueueMessage",replayQueueMessage:"__lunora_admin__:replayQueueMessage",resolveIssue:"__lunora_admin__:resolveIssue",rlsPolicies:"__lunora_admin__:rlsPolicies",schemaHistory:"__lunora_admin__:schemaHistory",schemaVersion:"__lunora_admin__:schemaVersion",runAs:"__lunora_admin__:runAs",runMigration:"__lunora_admin__:runMigration",runSql:"__lunora_admin__:runSql",sendQueueMessage:"__lunora_admin__:sendQueueMessage",sendTestMail:"__lunora_admin__:sendTestMail",setIssueSeverity:"__lunora_admin__:setIssueSeverity",storageOrphans:"__lunora_admin__:storageOrphans",storageReferences:"__lunora_admin__:storageReferences",storageRules:"__lunora_admin__:storageRules",studioFeatures:"__lunora_admin__:studioFeatures",writeRow:"__lunora_admin__:writeRow"},D=50,f=500,U=30,q=200,m="__doc__",R=e=>{try{const t=JSON.parse(e);return t!==null&&typeof t=="object"&&!Array.isArray(t)?t:void 0}catch{return}},W=e=>{const{[k]:t,...a}=e;return t===void 0?a:t===null||typeof t!="object"||Array.isArray(t)?{[k]:t,...a}:{...a,...P(t)}},j=(e,t)=>{if(!e.includes(m))return{columns:e,rows:t};const a=[];for(const s of t){const _=s[m],u=typeof _=="string"?R(_):void 0;if(u===void 0)return{columns:e,rows:t};const i=Object.fromEntries(Object.entries(s).filter(([l])=>l!==m));a.push({...i,...W(u)})}const r=e.filter(s=>s!==m),o=[],n=new Set(r);for(const s of a)for(const _ of Object.keys(s))n.has(_)||(n.add(_),o.push(_));return{columns:[...r,...o],rows:a}},w=e=>`instr(lower(CAST(${e} AS TEXT)), lower(?)) > 0`,I=e=>e.startsWith("sqlite_")||e.startsWith("_cf_")||e.startsWith("__miniflare")||e.startsWith("__lunora")||e.includes("__fts_"),v=(e,t,a)=>Math.min(Math.max(e,t),a),$=(e,t)=>{const a=e.exec(`SELECT COUNT(*) AS c FROM ${t}`).one();return Number(a.c)},oe=e=>{const t=e.exec("SELECT name FROM sqlite_master WHERE type = 'table' ORDER BY name").toArray(),a=[];for(const{name:r}of t)I(r)||a.push({name:r,rowCount:$(e,d(r))});return a},x=(e,t)=>e.exec("SELECT name FROM sqlite_master WHERE type = 'table' AND name = ? LIMIT 1",t).toArray().length>0,C=(e,t)=>{if(I(t)||!x(e,t))throw new T("UNKNOWN_TABLE",`unknown table: ${t}`,{status:404})},b=(e,t)=>e.exec(`PRAGMA table_info(${t})`).toArray().map(a=>a.name),Q={eq:"=",gt:">",gte:">=",lt:"<",lte:"<=",ne:"<>"},B=e=>typeof e=="string"?e:typeof e=="number"||typeof e=="boolean"?String(e):"",M=(e,t)=>{const a=t.includes(e),r=t.includes(m);if(!(!a&&!r))return a?{expression:d(e),params:[]}:{expression:`json_extract(${d(m)}, ?)`,params:[`$.${L(e)}`]}},H=(e,t)=>{const a=M(e.column,t);if(a===void 0)return;const{expression:r,params:o}=a;return e.operator==="contains"?{params:[...o,B(e.value)],sql:w(r)}:{params:[...o,e.value],sql:`${r} ${Q[e.operator]} ?`}},G=/^(\d{4})(?:-(\d{2}))?(?:-(\d{2}))?$/u,X=e=>{const t=G.exec(e.trim());if(t===null)return;const a=Number(t[1]),r=t[2]===void 0?void 0:Number(t[2]),o=t[3]===void 0?void 0:Number(t[3]);if(r!==void 0&&(r<1||r>12)||o!==void 0&&(o<1||o>31)||a<100)return;const n=Date.UTC(a,(r??1)-1,o??1);if(o!==void 0&&new Date(n).getUTCDate()!==o)return;let s;return o!==void 0?s=Date.UTC(a,(r??1)-1,o+1):r===void 0?s=Date.UTC(a+1,0,1):s=Date.UTC(a,r,1),{from:n,to:s}},E=(e,t,a)=>{const r=[],o=[];if(t!==""&&e.length>0){const n=e.map(_=>w(d(_)));o.push(...e.map(()=>t));const s=X(t);if(s!==void 0)for(const _ of e)n.push(`(${d(_)} >= ? AND ${d(_)} < ?)`),o.push(s.from,s.to);r.push(`(${n.join(" OR ")})`)}for(const n of a??[]){const s=H(n,e);s!==void 0&&(r.push(`(${s.sql})`),o.push(...s.params))}return r.length===0?void 0:{parameters:o,where:r.join(" AND ")}},Y=(e,t)=>{if(e===void 0)return;const a=M(e.column,t);if(a===void 0)return;const r=e.direction==="desc"?"DESC":"ASC";return{params:a.params,sql:`${a.expression} ${r}`}},ne=(e,t)=>{const{table:a}=t;C(e,a);const r=v(Math.trunc(t.limit??D),1,f),o=Math.max(0,Math.trunc(t.offset??0)),n=d(a),s=b(e,n),_=t.search?.trim()??"",u=h=>{if(t.refs===void 0)return h;const S={};for(const y of h.columns){const O=t.refs[y];O!==void 0&&(S[y]=O)}return Object.keys(S).length>0?{...h,refs:S}:h},i=E(s,_,t.filters),l=Y(t.orderBy,s),c=i===void 0?"":` WHERE ${i.where}`,p=l===void 0?"":` ORDER BY ${l.sql}`,g=i?.parameters??[],N=l?.params??[];let A;t.skipCount||(A=i===void 0?$(e,n):Number(e.exec(`SELECT COUNT(*) AS c FROM ${n}${c}`,...g).one().c));const F=e.exec(`SELECT * FROM ${n}${c}${p} LIMIT ? OFFSET ?`,...g,...N,r,o).toArray();return u({...j(s,F),total:A})},_e=(e,t)=>{const{table:a}=t;C(e,a);const r=v(Math.trunc(t.limit??f),1,f),o=d(a),n=b(e,o),s=t.search?.trim()??"",_=E(n,s,t.filters),u=_===void 0?e.exec(`SELECT id FROM ${o} LIMIT ?`,r+1).toArray():e.exec(`SELECT id FROM ${o} WHERE ${_.where} LIMIT ?`,..._.parameters,r+1).toArray(),i=u.length>r,l=u.slice(0,r).map(c=>c.id);return{hasMore:i,ids:l}},K=(e,t,a)=>{const r=new Set(a.filter(n=>n!==m));if(!a.includes(m))return r;const o=e.exec(`SELECT ${d(m)} AS doc FROM ${t} LIMIT ?`,f).toArray();for(const{doc:n}of o){const s=typeof n=="string"?R(n):void 0;if(s!==void 0)for(const _ of Object.keys(s))r.add(_)}return r},ie=(e,t)=>{const{column:a,table:r}=t;C(e,r);const o=d(r),n=b(e,o);if(!K(e,o,n).has(a))throw new T("UNKNOWN_COLUMN",`unknown column: ${a}`,{status:404});const s=M(a,n);if(s===void 0)throw new T("UNKNOWN_COLUMN",`unknown column: ${a}`,{status:404});const _=v(Math.trunc(t.limit??U),1,q),u=t.search?.trim()??"",i=E(n,u,t.filters),l=i===void 0?"":` WHERE ${i.where}`,c=i?.parameters??[],p=e.exec(`SELECT ${s.expression} AS value, COUNT(*) AS count FROM ${o}${l} GROUP BY ${s.expression} ORDER BY count DESC LIMIT ?`,...s.params,...c,...s.params,_+1).toArray();return{truncated:p.length>_,values:p.slice(0,_).map(g=>({count:Number(g.count),value:g.value}))}},ue=(e,t,a)=>{const r={},o=a.slice(0,f);for(const s of o)r[s]=[];if(o.length===0)return{references:r,storageColumns:t};const n=o.map(()=>"?").join(", ");for(const[s,_]of Object.entries(t)){if(I(s)||!x(e,s))continue;const u=d(s),i=b(e,u);for(const l of _){const c=M(l,i);if(c===void 0)continue;const p=e.exec(`SELECT id, ${c.expression} AS ref FROM ${u} WHERE ${c.expression} IN (${n})`,...c.params,...c.params,...o).toArray();for(const g of p)r[g.ref]?.push({column:l,id:g.id,table:s})}}return{references:r,storageColumns:t}},le=e=>{const t=e.map((r,o)=>{const n=Object.values(r.subs??{}).map(s=>({args:s.args,functionPath:s.functionPath,table:s.table}));return{admin:r.admin===!0,id:o,subscriptions:n}}),a=t.reduce((r,o)=>r+o.subscriptions.length,0);return{connections:t,totalConnections:t.length,totalSubscriptions:a}},z=20,ce=()=>({maxMs:0,passes:0,peakSocketsIterated:0,socketsDelivered:0,socketsIterated:0,totalMs:0}),de=(e,t,a,r)=>({maxMs:Math.max(e.maxMs,r),passes:e.passes+1,peakSocketsIterated:Math.max(e.peakSocketsIterated,t),socketsDelivered:e.socketsDelivered+a,socketsIterated:e.socketsIterated+t,totalMs:e.totalMs+r}),me=(e,t=z)=>{const a=new Map,r=new Map;for(const n of e){for(const s of Object.values(n.shapes??{})){const _=s.name??"(unknown shape)";a.set(_,(a.get(_)??0)+1)}for(const s of n.whispers??[])r.set(s,(r.get(s)??0)+1)}const o=[...[...a].map(([n,s])=>({kind:"shape",subscribers:s,topic:n})),...[...r].map(([n,s])=>({kind:"whisper",subscribers:s,topic:n}))];return o.sort((n,s)=>s.subscribers-n.subscribers||n.topic.localeCompare(s.topic)),{peakSubscribers:o[0]?.subscribers??0,topics:o.slice(0,t),totalConnections:e.length}};export{se as ADMIN_FUNCTIONS,te as ADMIN_FUNCTION_PREFIX,z as DEFAULT_FANOUT_TOPIC_LIMIT,re as FLAGS_FUNCTION_PREFIX,f as MAX_PAGE_SIZE,ae as RELATION_FUNCTION_PREFIX,ce as createFanoutCounters,X as datePrefixRange,ie as facetColumn,ue as findStorageReferences,oe as listTables,ne as readTablePage,de as recordFanoutPass,_e as selectMatchingIds,me as summarizeFanoutTopics,le as summarizeSubscriptions};
|
|
1
|
+
import{LunoraError as T}from"@lunora/errors";import{j as L,s as k}from"./do-sql-DKSFK627.mjs";import{quoteIdentifier as d}from"./quoteIdentifier-CObIFRhb.mjs";import{s as P}from"./wire-codec-Dh0j-GnY.mjs";const te="__lunora_admin__:",ae="__lunora_relation__:",re="__lunora_flags__:",se={applyCdc:"__lunora_admin__:applyCdc",aiAvailable:"__lunora_admin__:aiAvailable",aiChartConfig:"__lunora_admin__:aiChartConfig",aiGenerateSql:"__lunora_admin__:aiGenerateSql",aiTableFilter:"__lunora_admin__:aiTableFilter",assignIssue:"__lunora_admin__:assignIssue",backRelationCounts:"__lunora_admin__:backRelationCounts",cdcSync:"__lunora_admin__:cdcSync",clearCapturedMail:"__lunora_admin__:clearCapturedMail",clearQueueMessages:"__lunora_admin__:clearQueueMessages",clearTable:"__lunora_admin__:clearTable",createWorkflowInstance:"__lunora_admin__:createWorkflowInstance",deleteRows:"__lunora_admin__:deleteRows",describeTable:"__lunora_admin__:describeTable",describeTables:"__lunora_admin__:describeTables",explainIssue:"__lunora_admin__:explainIssue",exportShard:"__lunora_admin__:exportShard",facetColumn:"__lunora_admin__:facetColumn",getAdvisories:"__lunora_admin__:getAdvisories",getAdvisorProcedures:"__lunora_admin__:getAdvisorProcedures",getAuditLog:"__lunora_admin__:getAuditLog",getAuthMetrics:"__lunora_admin__:getAuthMetrics",getCapturedMail:"__lunora_admin__:getCapturedMail",getFanoutMetrics:"__lunora_admin__:getFanoutMetrics",getFunctionStats:"__lunora_admin__:getFunctionStats",getIssues:"__lunora_admin__:getIssues",getMetricHistory:"__lunora_admin__:getMetricHistory",getMetricSeries:"__lunora_admin__:getMetricSeries",listSubscriptions:"__lunora_admin__:listSubscriptions",listTableIndexes:"__lunora_admin__:listTableIndexes",listTablesIndexes:"__lunora_admin__:listTablesIndexes",getLogs:"__lunora_admin__:getLogs",getMetrics:"__lunora_admin__:getMetrics",getPitrBookmark:"__lunora_admin__:getPitrBookmark",getQueryInsights:"__lunora_admin__:getQueryInsights",getQueueMessages:"__lunora_admin__:getQueueMessages",getRequestLog:"__lunora_admin__:getRequestLog",getSecurityAudit:"__lunora_admin__:getSecurityAudit",getSettings:"__lunora_admin__:getSettings",getTraces:"__lunora_admin__:getTraces",getWorkflowInstanceStatus:"__lunora_admin__:getWorkflowInstanceStatus",ignoreIssue:"__lunora_admin__:ignoreIssue",importShard:"__lunora_admin__:importShard",listFlags:"__lunora_admin__:listFlags",listQueues:"__lunora_admin__:listQueues",lintSql:"__lunora_admin__:lintSql",listTables:"__lunora_admin__:listTables",listWorkflows:"__lunora_admin__:listWorkflows",maskPolicies:"__lunora_admin__:maskPolicies",migrationStatus:"__lunora_admin__:migrationStatus",pitrRestore:"__lunora_admin__:pitrRestore",rankBefore:"__lunora_admin__:rankBefore",rankPage:"__lunora_admin__:rankPage",readTablePage:"__lunora_admin__:readTablePage",recordAuthEvent:"__lunora_admin__:recordAuthEvent",recordContainerEvent:"__lunora_admin__:recordContainerEvent",recordMail:"__lunora_admin__:recordMail",recordQueueMessage:"__lunora_admin__:recordQueueMessage",replayQueueMessage:"__lunora_admin__:replayQueueMessage",resolveIssue:"__lunora_admin__:resolveIssue",rlsPolicies:"__lunora_admin__:rlsPolicies",schemaHistory:"__lunora_admin__:schemaHistory",schemaVersion:"__lunora_admin__:schemaVersion",runAs:"__lunora_admin__:runAs",runMigration:"__lunora_admin__:runMigration",runSql:"__lunora_admin__:runSql",sendQueueMessage:"__lunora_admin__:sendQueueMessage",sendTestMail:"__lunora_admin__:sendTestMail",setIssueSeverity:"__lunora_admin__:setIssueSeverity",storageOrphans:"__lunora_admin__:storageOrphans",storageReferences:"__lunora_admin__:storageReferences",storageRules:"__lunora_admin__:storageRules",studioFeatures:"__lunora_admin__:studioFeatures",writeRow:"__lunora_admin__:writeRow"},D=50,f=500,U=30,q=200,m="__doc__",R=e=>{try{const t=JSON.parse(e);return t!==null&&typeof t=="object"&&!Array.isArray(t)?t:void 0}catch{return}},W=e=>{const{[k]:t,...a}=e;return t===void 0?a:t===null||typeof t!="object"||Array.isArray(t)?{[k]:t,...a}:{...a,...P(t)}},j=(e,t)=>{if(!e.includes(m))return{columns:e,rows:t};const a=[];for(const s of t){const _=s[m],u=typeof _=="string"?R(_):void 0;if(u===void 0)return{columns:e,rows:t};const i=Object.fromEntries(Object.entries(s).filter(([l])=>l!==m));a.push({...i,...W(u)})}const r=e.filter(s=>s!==m),o=[],n=new Set(r);for(const s of a)for(const _ of Object.keys(s))n.has(_)||(n.add(_),o.push(_));return{columns:[...r,...o],rows:a}},w=e=>`instr(lower(CAST(${e} AS TEXT)), lower(?)) > 0`,I=e=>e.startsWith("sqlite_")||e.startsWith("_cf_")||e.startsWith("__miniflare")||e.startsWith("__lunora")||e.includes("__fts_"),v=(e,t,a)=>Math.min(Math.max(e,t),a),$=(e,t)=>{const a=e.exec(`SELECT COUNT(*) AS c FROM ${t}`).one();return Number(a.c)},oe=e=>{const t=e.exec("SELECT name FROM sqlite_master WHERE type = 'table' ORDER BY name").toArray(),a=[];for(const{name:r}of t)I(r)||a.push({name:r,rowCount:$(e,d(r))});return a},x=(e,t)=>e.exec("SELECT name FROM sqlite_master WHERE type = 'table' AND name = ? LIMIT 1",t).toArray().length>0,C=(e,t)=>{if(I(t)||!x(e,t))throw new T("UNKNOWN_TABLE",`unknown table: ${t}`,{status:404})},b=(e,t)=>e.exec(`PRAGMA table_info(${t})`).toArray().map(a=>a.name),Q={eq:"=",gt:">",gte:">=",lt:"<",lte:"<=",ne:"<>"},B=e=>typeof e=="string"?e:typeof e=="number"||typeof e=="boolean"?String(e):"",M=(e,t)=>{const a=t.includes(e),r=t.includes(m);if(!(!a&&!r))return a?{expression:d(e),params:[]}:{expression:`json_extract(${d(m)}, ?)`,params:[`$.${L(e)}`]}},H=(e,t)=>{const a=M(e.column,t);if(a===void 0)return;const{expression:r,params:o}=a;return e.operator==="contains"?{params:[...o,B(e.value)],sql:w(r)}:{params:[...o,e.value],sql:`${r} ${Q[e.operator]} ?`}},G=/^(\d{4})(?:-(\d{2}))?(?:-(\d{2}))?$/u,X=e=>{const t=G.exec(e.trim());if(t===null)return;const a=Number(t[1]),r=t[2]===void 0?void 0:Number(t[2]),o=t[3]===void 0?void 0:Number(t[3]);if(r!==void 0&&(r<1||r>12)||o!==void 0&&(o<1||o>31)||a<100)return;const n=Date.UTC(a,(r??1)-1,o??1);if(o!==void 0&&new Date(n).getUTCDate()!==o)return;let s;return o!==void 0?s=Date.UTC(a,(r??1)-1,o+1):r===void 0?s=Date.UTC(a+1,0,1):s=Date.UTC(a,r,1),{from:n,to:s}},E=(e,t,a)=>{const r=[],o=[];if(t!==""&&e.length>0){const n=e.map(_=>w(d(_)));o.push(...e.map(()=>t));const s=X(t);if(s!==void 0)for(const _ of e)n.push(`(${d(_)} >= ? AND ${d(_)} < ?)`),o.push(s.from,s.to);r.push(`(${n.join(" OR ")})`)}for(const n of a??[]){const s=H(n,e);s!==void 0&&(r.push(`(${s.sql})`),o.push(...s.params))}return r.length===0?void 0:{parameters:o,where:r.join(" AND ")}},Y=(e,t)=>{if(e===void 0)return;const a=M(e.column,t);if(a===void 0)return;const r=e.direction==="desc"?"DESC":"ASC";return{params:a.params,sql:`${a.expression} ${r}`}},ne=(e,t)=>{const{table:a}=t;C(e,a);const r=v(Math.trunc(t.limit??D),1,f),o=Math.max(0,Math.trunc(t.offset??0)),n=d(a),s=b(e,n),_=t.search?.trim()??"",u=h=>{if(t.refs===void 0)return h;const S={};for(const y of h.columns){const O=t.refs[y];O!==void 0&&(S[y]=O)}return Object.keys(S).length>0?{...h,refs:S}:h},i=E(s,_,t.filters),l=Y(t.orderBy,s),c=i===void 0?"":` WHERE ${i.where}`,p=l===void 0?"":` ORDER BY ${l.sql}`,g=i?.parameters??[],N=l?.params??[];let A;t.skipCount||(A=i===void 0?$(e,n):Number(e.exec(`SELECT COUNT(*) AS c FROM ${n}${c}`,...g).one().c));const F=e.exec(`SELECT * FROM ${n}${c}${p} LIMIT ? OFFSET ?`,...g,...N,r,o).toArray();return u({...j(s,F),total:A})},_e=(e,t)=>{const{table:a}=t;C(e,a);const r=v(Math.trunc(t.limit??f),1,f),o=d(a),n=b(e,o),s=t.search?.trim()??"",_=E(n,s,t.filters),u=_===void 0?e.exec(`SELECT id FROM ${o} LIMIT ?`,r+1).toArray():e.exec(`SELECT id FROM ${o} WHERE ${_.where} LIMIT ?`,..._.parameters,r+1).toArray(),i=u.length>r,l=u.slice(0,r).map(c=>c.id);return{hasMore:i,ids:l}},K=(e,t,a)=>{const r=new Set(a.filter(n=>n!==m));if(!a.includes(m))return r;const o=e.exec(`SELECT ${d(m)} AS doc FROM ${t} LIMIT ?`,f).toArray();for(const{doc:n}of o){const s=typeof n=="string"?R(n):void 0;if(s!==void 0)for(const _ of Object.keys(s))r.add(_)}return r},ie=(e,t)=>{const{column:a,table:r}=t;C(e,r);const o=d(r),n=b(e,o);if(!K(e,o,n).has(a))throw new T("UNKNOWN_COLUMN",`unknown column: ${a}`,{status:404});const s=M(a,n);if(s===void 0)throw new T("UNKNOWN_COLUMN",`unknown column: ${a}`,{status:404});const _=v(Math.trunc(t.limit??U),1,q),u=t.search?.trim()??"",i=E(n,u,t.filters),l=i===void 0?"":` WHERE ${i.where}`,c=i?.parameters??[],p=e.exec(`SELECT ${s.expression} AS value, COUNT(*) AS count FROM ${o}${l} GROUP BY ${s.expression} ORDER BY count DESC LIMIT ?`,...s.params,...c,...s.params,_+1).toArray();return{truncated:p.length>_,values:p.slice(0,_).map(g=>({count:Number(g.count),value:g.value}))}},ue=(e,t,a)=>{const r={},o=a.slice(0,f);for(const s of o)r[s]=[];if(o.length===0)return{references:r,storageColumns:t};const n=o.map(()=>"?").join(", ");for(const[s,_]of Object.entries(t)){if(I(s)||!x(e,s))continue;const u=d(s),i=b(e,u);for(const l of _){const c=M(l,i);if(c===void 0)continue;const p=e.exec(`SELECT id, ${c.expression} AS ref FROM ${u} WHERE ${c.expression} IN (${n})`,...c.params,...c.params,...o).toArray();for(const g of p)r[g.ref]?.push({column:l,id:g.id,table:s})}}return{references:r,storageColumns:t}},le=e=>{const t=e.map((r,o)=>{const n=Object.values(r.subs??{}).map(s=>({args:s.args,functionPath:s.functionPath,table:s.table}));return{admin:r.admin===!0,id:o,subscriptions:n}}),a=t.reduce((r,o)=>r+o.subscriptions.length,0);return{connections:t,totalConnections:t.length,totalSubscriptions:a}},z=20,ce=()=>({maxMs:0,passes:0,peakSocketsIterated:0,socketsDelivered:0,socketsIterated:0,totalMs:0}),de=(e,t,a,r)=>({maxMs:Math.max(e.maxMs,r),passes:e.passes+1,peakSocketsIterated:Math.max(e.peakSocketsIterated,t),socketsDelivered:e.socketsDelivered+a,socketsIterated:e.socketsIterated+t,totalMs:e.totalMs+r}),me=(e,t=z)=>{const a=new Map,r=new Map;for(const n of e){for(const s of Object.values(n.shapes??{})){const _=s.name??"(unknown shape)";a.set(_,(a.get(_)??0)+1)}for(const s of n.whispers??[])r.set(s,(r.get(s)??0)+1)}const o=[...[...a].map(([n,s])=>({kind:"shape",subscribers:s,topic:n})),...[...r].map(([n,s])=>({kind:"whisper",subscribers:s,topic:n}))];return o.sort((n,s)=>s.subscribers-n.subscribers||n.topic.localeCompare(s.topic)),{peakSubscribers:o[0]?.subscribers??0,topics:o.slice(0,t),totalConnections:e.length}};export{se as ADMIN_FUNCTIONS,te as ADMIN_FUNCTION_PREFIX,z as DEFAULT_FANOUT_TOPIC_LIMIT,re as FLAGS_FUNCTION_PREFIX,f as MAX_PAGE_SIZE,ae as RELATION_FUNCTION_PREFIX,ce as createFanoutCounters,X as datePrefixRange,ie as facetColumn,ue as findStorageReferences,oe as listTables,ne as readTablePage,de as recordFanoutPass,_e as selectMatchingIds,me as summarizeFanoutTopics,le as summarizeSubscriptions};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import"@lunora/errors";import"drizzle-orm";import{T as l,c as m,p as n,a as p,s as c,A as q,y as d,g as u,L as A,h as D,C as G,_ as S,N as _,S as f,O as C,E as O,I as h,D as I}from"./do-sql-
|
|
1
|
+
import"@lunora/errors";import"drizzle-orm";import{T as l,c as m,p as n,a as p,s as c,A as q,y as d,g as u,L as A,h as D,C as G,_ as S,N as _,S as f,O as C,E as O,I as h,D as I}from"./do-sql-DKSFK627.mjs";import{quoteIdentifier as T}from"./quoteIdentifier-CObIFRhb.mjs";import"./wire-codec-Dh0j-GnY.mjs";import"./runDrizzle-C3n5gJsk.mjs";import"./sql-projection-jfoe331H.mjs";import{serializeSqlValue as x}from"./serializeSqlValue-BR4UOWoP.mjs";export{l as AGG_COUNT,m as AGG_KEY,n as AGG_VALUE,p as DOC_COLUMN,c as DOC_ORIGINALS_KEY,q as aggUpsertSql,d as createIndexSql,u as decodeDocJson,A as encodeDocJson,D as geoTableName,G as isFtsAvailable,S as jsonPath,_ as jsonPathSql,f as qualifiedJsonPath,C as qualifiedJsonPathSql,T as quoteIdentifier,O as rowToDocument,x as serializeSqlValue,h as tableColumns,I as tryRowToDocument};
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{sql as e}from"drizzle-orm";import{runDrizzle as a}from"./runDrizzle-C3n5gJsk.mjs";import{L as C,g as l}from"./do-sql-
|
|
1
|
+
import{sql as e}from"drizzle-orm";import{runDrizzle as a}from"./runDrizzle-C3n5gJsk.mjs";import{L as C,g as l}from"./do-sql-DKSFK627.mjs";import{ConflictError as L}from"./ConflictError-C8GtJmjS.mjs";const d="__cdc_log",I=t=>{a(t,e`CREATE TABLE IF NOT EXISTS ${e.identifier(d)} (
|
|
2
2
|
seq INTEGER PRIMARY KEY AUTOINCREMENT,
|
|
3
3
|
ts REAL NOT NULL,
|
|
4
4
|
${e.identifier("table")} TEXT NOT NULL,
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{LunoraError as d}from"@lunora/errors";import{distinctValues as R}from"./applyOnDelete-
|
|
1
|
+
import{LunoraError as d}from"@lunora/errors";import{distinctValues as R}from"./applyOnDelete-crbAzVfE.mjs";import{RELATION_EXISTS_KEY as k}from"./RELATION_EXISTS_KEY-BaqSIFU1.mjs";const y={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}},A=new Set(Object.keys(y)),w=e=>{const t=y[e];if(!t)throw new d("INTERNAL",`unknown relation operator "${e}"`);return t},E=e=>e.kind==="one"?{clause:e.field,project:e.references}:{clause:e.references,project:e.field},j=5e3,h=Symbol("relation-key-overflow"),b=e=>Array.isArray(e)?e.map(t=>t??{}):[],N=e=>{if(e.length===1){const[t]=e;return t??{}}return e.length===0?{}:{AND:e}},p=e=>{if(e===null||typeof e!="object"||Array.isArray(e))return!1;const t=Object.keys(e);return t.length>0&&t.every(n=>A.has(n))},u=(e,t,n)=>{const a=t.tables[n]?.relationMap??{};return Object.keys(e).some(r=>{const s=e[r];return r==="AND"||r==="OR"?b(s).some(o=>u(o,t,n)):r==="NOT"?u(s??{},t,n):!!a[r]&&p(s)})},M=(e,t,n,a)=>{if(e&&u(e,t,n))throw new d("INTERNAL",`relation-crossing predicates are not supported in ${a}() — use them in findMany/findFirst or an RLS read policy`)},S=async(e,t,n,a,r)=>{const s=await c(t,e.table,a),{page:o}=await a.fetcher(e.table,{baseWhere:a.relationBaseWhere?.(e.table),relationBaseWhere:a.relationBaseWhere,where:s}),i=R(o,n);if(i.length>a.maxRelationKeys){if(r)return h;throw new d("INTERNAL",`relation predicate on "${e.table}" matched ${String(i.length)} rows, exceeding the ${String(a.maxRelationKeys)}-key limit; narrow the predicate (a same-shard EXISTS push-down lifts this cap)`)}return i},T=async(e,t,n,a,r)=>{const s=w(e),{clause:o,project:i}=E(t),l=await S(t,s.negateChild?{NOT:n}:n,i,a,r);return l===h?h:s.negated?s.nullDisjunct?{OR:[{[o]:{notIn:l}},{[o]:{isNull:!0}}]}:{[o]:{notIn:l}}:{[o]:{in:l}}},g=async(e,t,n,a,r)=>{const s=w(e),o=r.relationBaseWhere?.(t.table),i=s.negateChild?{NOT:n}:n,l={childWhere:await c(o?{AND:[o,i]}:i,t.table,r),negated:s.negated,parentTable:a,relation:t};return{[k]:l}},$=(e,t,n)=>{const a=y[e];if(a&&a.kind!==n.kind)throw new d("INTERNAL",`relation operator "${e}" requires a to-${a.kind} relation, but "${t}" is to-${n.kind}`)},x=async(e,t,n,a,r)=>{const s=[];for(const o of Object.keys(n)){$(o,e,t);const i=n[o]??{},l=r.canPushExists?.(t)??!1;if(l&&r.existsPushMode==="always"){s.push(await g(o,t,i,a,r));continue}const m=await T(o,t,i,r,l);m===h?s.push(await g(o,t,i,a,r)):s.push(m)}return N(s)},D=async(e,t,n,a)=>{if(e==="AND"||e==="OR"){const s=[];for(const o of b(t))s.push(await c(o,n,a));return{[e]:s}}if(e==="NOT")return{NOT:await c(t??{},n,a)};const r=a.schema.tables[n]?.relationMap?.[e];return r&&p(t)?x(e,r,t,n,a):{[e]:t}},c=async(e,t,n)=>{const a=[];for(const r of Object.keys(e))a.push(await D(r,e[r],t,n));return N(a)},W=async(e,t)=>!e||!u(e,t.schema,t.tableName)?e:c(e,t.tableName,{canPushExists:t.canPushExists,existsPushMode:t.existsPushMode??"auto",fetcher:t.fetcher,maxRelationKeys:t.maxRelationKeys??j,relationBaseWhere:t.relationBaseWhere,schema:t.schema}),f=(e,t,n)=>{for(const a of e){const r=O(a,t,n);if(r)return r}},I=(e,t,n,a)=>{if(e==="AND"||e==="OR")return f(b(t),n,a);if(e==="NOT")return f([t??{}],n,a);const r=n.tables[a]?.relationMap?.[e];if(!(!r||!p(t)))return n.tables[r.table]?.shardMode?.kind==="shardBy"?{relation:e,target:r.table}:f(Object.values(t),n,r.table)},O=(e,t,n)=>{for(const a of Object.keys(e)){const r=I(a,e[a],t,n);if(r)return r}},_=(e,t,n)=>{if(!e)return;const a=O(e,t,n);if(a)throw Object.assign(new Error(`shape on "${n}" joins the sharded table "${a.target}" via relation "${a.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 "${a.target}" to .global() so it is served through the latency-tiered D1 shape tier.`),{code:"SHAPE_CROSS_SHARD_JOIN",name:"LunoraError",status:400})};export{j as DEFAULT_MAX_RELATION_KEYS,M as assertFlatPredicate,_ as assertShapeShardable,u as containsRelationPredicate,p as isRelationPredicate,W as resolveRelationPredicates};
|
package/dist/packem_shared/{DEFAULT_MAX_RELAYS-B19vrJxP.mjs → DEFAULT_MAX_RELAYS-Cinp9pPC.mjs}
RENAMED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{toErrorBody as A,LunoraError as x}from"@lunora/errors";import{a as w,s as g}from"./wire-codec-Dsy70M3Q.mjs";import{u as m,f as P,g as R,l as k,s as M,o as L}from"./sibling-channel-bg9FBL5s.mjs";import{relayName as y,nextPromotionState as O,shapeRoutingKey as S,parseRelayName as D,clampPromotionThresholds as C,DEFAULT_PROMOTION_THRESHOLDS as b}from"./DEFAULT_PROMOTION_THRESHOLDS-B2rUe1bg.mjs";import{encodeRowsPatch as T,buildPokeFrames as _}from"./buildPokeFrames-CqxaN8_H.mjs";import{awaitWsDrain as N,trySendFrame as I}from"./awaitWsDrain-Bp2jKzIb.mjs";import{stableWireKey as p}from"./stableWireKey-l3cjIt-9.mjs";const $=2,F=8,f={},U=d=>{throw new x("INTERNAL",`unhandled relay frame: ${JSON.stringify(d)}`)},K=d=>Response.json(d,{headers:{"content-type":"application/json"}}),u=()=>new Response(null,{status:204});class E{constructor(e,s){this.host=e,this.roleId=s}host;roleId;async handleControl(e){let s;try{s=await e.text()}catch{return new Response("bad request",{status:400})}if(!await P(this.host.env(),e.headers.get(R),s))return new Response("forbidden",{status:403});let t;try{t=JSON.parse(s)}catch{return new Response("bad request",{status:400})}switch(t.type){case"relay_attach":return this.onAttach(t.relayIndex),u();case"relay_detach":return this.onDetach(t.relayIndex),u();case"relay_frame":return this.host.deliverWhisperLocal(t.topic,t.frame,void 0),await this.onWhisperFrame(t),u();case"relay_shape_poke":{const r=this.host.getWebSockets().length,a=Date.now(),o=this.onShapePoke({...t,args:g(t.args)});return this.host.recordShapePokeFanout(r,o,Date.now()-a),u()}case"relay_shape_subscribe":return K(this.onShapeSubscribe({...t,args:g(t.args)}));default:return U(t)}}maxRelays(){return m(this.host.env(),"LUNORA_MAX_RELAYS",F)}canAddressSiblings(){return this.siblingStub(this.roleId.ownerKey)!==void 0}siblingStub(e){return k(this.host.env(),this.host.shardBinding(),e)}async postRelayMessage(e,s){await this.requestRelayMessage(e,s)}async requestRelayMessage(e,s){const t=this.siblingStub(e);if(t===void 0)return;const r=JSON.stringify(s),a={"content-type":"application/json","x-lunora-shard-binding":this.host.shardBinding()??""},o=M(this.host.env());o!==void 0&&(a[R]=await L(o,r));try{return await t.fetch("https://relay.internal/_lunora/relay",{body:r,headers:a,method:"POST"})}catch{return}}}class W extends E{shapeUniformCache=new Map;relaySetCache;relayShapeRegistry=new Map;relayShapeProxies=new Map;promotionState="owned";constructor(e,s){super(e,{ownerKey:s})}async forwardWhisper(e,s){if(!this.canAddressSiblings())return;const t=this.ownerRelaySet();t.size!==0&&await Promise.all([...t].map(r=>this.postRelayMessage(y(this.roleId.ownerKey,r),{frame:s,topic:e,type:"relay_frame"})))}async onFlush(e,s){await Promise.all([this.multicastShapePokes(e,s),this.proxyShapePokes(e,s)])}seedRelayShape(){return Promise.resolve(void 0)}announce(){return Promise.resolve()}announceDrain(){return Promise.resolve()}relayCount(){const e=this.host.getWebSockets().length,s=m(this.host.env(),"LUNORA_RELAY_THRESHOLD",b.tUp),t=m(this.host.env(),"LUNORA_RELAY_COLLAPSE_THRESHOLD",b.tDown);if(this.promotionState=O(this.promotionState,e,C(s,t)),this.promotionState==="owned")return 0;const r=m(this.host.env(),"LUNORA_RELAY_FAN",$);return Math.min(this.maxRelays(),Math.max(1,r))}isShapeRelayUniform(e,s){const t=S(e,s),r=this.shapeUniformCache.get(t);if(r!==void 0)return r;const a=this.probeShapeRelayUniform(e,s);return this.shapeUniformCache.set(t,a),a}onAttach(e){this.addRelayToSet(e)}onDetach(e){this.removeRelayFromSet(e)}async onWhisperFrame(e){await Promise.all([...this.ownerRelaySet()].filter(s=>s!==e.originRelay).map(s=>this.postRelayMessage(y(this.roleId.ownerKey,s),{frame:e.frame,topic:e.topic,type:"relay_frame"})))}onShapeSubscribe(e){return this.buildShapeSeedFrames(e)}onShapePoke(){return 0}buildShapePoke(e,s,t,r,a){let o;try{o=this.host.resolveShape(e.name,e.args,s)}catch{return}if(o===void 0||o.global===!0||!t.has(o.table))return;const i=e,n=i.cursor,l=this.host.buildShapeDiff(o,n,r);if(l.length!==0)return i.cursor=r,{args:w(e.args),checkpoint:r,epoch:a,fromCursor:n,name:e.name,rowsPatch:T(l),type:"relay_shape_poke"}}async multicastShapePokes(e,s){if(this.relayShapeRegistry.size===0)return;const t=this.ownerRelaySet();if(t.size===0)return;const r=this.host.currentCdcEpoch(),a=[];for(const o of this.relayShapeRegistry.values()){const i=this.buildShapePoke(o,f,e,s,r);if(i)for(const n of t)a.push(this.postRelayMessage(y(this.roleId.ownerKey,n),i))}await Promise.all(a)}async proxyShapePokes(e,s){if(this.relayShapeProxies.size===0)return;const t=this.host.currentCdcEpoch(),r=[];for(const a of this.relayShapeProxies.values()){const o=this.buildShapePoke(a,a.identity,e,s,t);o&&r.push(this.postRelayMessage(y(this.roleId.ownerKey,a.relayIndex),{...o,targetConnectionId:a.connectionId}))}await Promise.all(r)}buildShapeSeedFrames(e){const s={identity:e.identity,userId:e.userId};let t;try{t=this.host.resolveShape(e.name,e.args,s)}catch(c){const{body:h}=A(c,{fallbackCode:"SHAPE_RESOLVE_FAILED",redactedMessage:"shape resolution failed"});return{error:{code:h.code,message:h.message}}}if(t===void 0||t.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:a,epoch:o,rowsPatch:i}=this.host.computeOpLogShapeSeed({args:e.args,name:e.name,sinceEpoch:e.sinceEpoch,sinceSeq:e.sinceSeq},t);let n=a;if(this.isShapeRelayUniform(e.name,e.args)){const c=S(e.name,e.args);let h=this.relayShapeRegistry.get(c);h===void 0&&(h={args:e.args,cursor:a,name:e.name},this.relayShapeRegistry.set(c,h)),n=h.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:a,epoch:o,identity:s,name:e.name,relayIndex:e.relayIndex,subId:e.subId});const l=_([{rowsPatch:i,shapeId:e.subId}],{baseCheckpoint:r,checkpoint:a,epoch:o,lastMutationId:void 0,pokeId:this.host.nextPokeId()});return{cursor:n,epoch:o,frames:l}}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(s=>Number(s.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 s=this.ownerRelaySet();s.delete(e);for(const[t,r]of this.relayShapeProxies)r.relayIndex===e&&this.relayShapeProxies.delete(t);s.size===0&&(this.relayShapeRegistry.clear(),this.shapeUniformCache.clear())}probeShapeRelayUniform(e,s){let t;try{t=this.host.resolveShape(e,s,f)}catch{return!1}if(t===void 0||t.global===!0||this.host.rlsMetadata().policies.some(n=>n.on==="read"&&n.table===t.table)||this.tableHasAnyMask(t.table))return!1;const r=p(t.effectiveWhere),a=p(t.columns);let o=!1;const i=n=>{const l={groups:[`grp_${n}`],roles:[n],sub:`__lunora_probe_${n}__`};return{identity:new Proxy(l,{get:(c,h)=>typeof h=="symbol"||h in c?Reflect.get(c,h):`${n}:${h}`,getOwnPropertyDescriptor:(c,h)=>(o=!0,Reflect.getOwnPropertyDescriptor(c,h)),has:(c,h)=>typeof h=="symbol"?Reflect.has(c,h):!0,ownKeys:c=>(o=!0,Reflect.ownKeys(c))}),userId:`__lunora_probe_${n}__`}};return[f,i("a"),i("b")].every(n=>{let l;try{l=this.host.resolveShape(e,s,n)}catch{return!1}return l!==void 0&&l.global!==!0&&l.table===t.table&&p(l.effectiveWhere)===r&&p(l.columns)===a})&&!o}tableHasAnyMask(e){return this.host.maskMetadata().columns.some(s=>s.table===e)}}class q extends E{relayAnnounced=!1;shapeRelayMemos=new WeakMap;constructor(e,s,t){super(e,{ownerKey:s,relayIndex:t})}async forwardWhisper(e,s){this.canAddressSiblings()&&await this.postRelayMessage(this.roleId.ownerKey,{frame:s,originRelay:this.roleId.relayIndex,topic:e,type:"relay_frame"})}onFlush(){return Promise.resolve()}async seedRelayShape(e,s,t,r){if(!this.canAddressSiblings())return{code:"RELAY_MISCONFIGURED",message:"relay cannot address its owner"};await this.announce();const a={args:w(t.args??{}),connectionId:this.host.readAttachment(e).connectionId,identity:r.identity,name:t.name,relayIndex:this.roleId.relayIndex,sinceEpoch:t.sinceEpoch,sinceSeq:t.sinceSeq,subId:s,type:"relay_shape_subscribe",userId:r.userId},o=await this.requestRelayMessage(this.roleId.ownerKey,a);if(o===void 0)return{code:"RELAY_SEED_FAILED",message:"owner did not answer the shape seed"};let i;try{i=await o.json()}catch{return{code:"RELAY_SEED_FAILED",message:"malformed shape seed from owner"}}if(i.error!==void 0)return i.error;if(i.frames===void 0)return{code:"RELAY_SEED_FAILED",message:"owner returned no shape frames"};await N(e);for(const n of i.frames)I(e,n);return this.recordRelayShapeMemo(e,s,i.cursor??0,i.epoch),"ok"}async announce(){this.relayAnnounced||!this.canAddressSiblings()||(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(s=>s!==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,s,t,r){let a=this.shapeRelayMemos.get(e);a===void 0&&(a=new Map,this.shapeRelayMemos.set(e,a)),a.set(s,{cursor:t,epoch:r})}deliverShapePoke(e){const s=S(e.name,e.args);let t=0;for(const r of this.host.getWebSockets()){const a=this.host.readAttachment(r),{shapes:o}=a,i=this.shapeRelayMemos.get(r);if(!(o===void 0||i===void 0)&&!(e.targetConnectionId!==void 0&&a.connectionId!==e.targetConnectionId))for(const[n,l]of Object.entries(o)){const c=i.get(n);if(c?.cursor!==e.fromCursor||c.epoch!==e.epoch||S(l.name,l.args)!==s)continue;const h=_([{rowsPatch:e.rowsPatch,shapeId:n}],{baseCheckpoint:void 0,checkpoint:e.checkpoint,epoch:e.epoch,lastMutationId:void 0,pokeId:this.host.nextPokeId()},{preEncoded:!0});for(const v of h)I(r,v);i.set(n,{cursor:e.checkpoint,epoch:e.epoch}),t+=1}}return t}}const X=d=>{const e=d.doName();if(e===void 0)return;const s=D(e);return s===void 0?new W(d,e):new q(d,s.ownerKey,s.relayIndex)};export{F as DEFAULT_MAX_RELAYS,W as OwnerRelay,q as RelayMember,X as createRelayLink};
|
|
1
|
+
import{toErrorBody as A,LunoraError as x}from"@lunora/errors";import{a as w,s as g}from"./wire-codec-Dh0j-GnY.mjs";import{u as m,f as P,g as R,l as k,s as M,o as L}from"./sibling-channel-bg9FBL5s.mjs";import{relayName as y,nextPromotionState as O,shapeRoutingKey as S,parseRelayName as D,clampPromotionThresholds as C,DEFAULT_PROMOTION_THRESHOLDS as b}from"./DEFAULT_PROMOTION_THRESHOLDS-DYGNAo1I.mjs";import{encodeRowsPatch as T,buildPokeFrames as _}from"./buildPokeFrames-DmB-FBeQ.mjs";import{awaitWsDrain as N,trySendFrame as I}from"./awaitWsDrain-PT9o0d6J.mjs";import{stableWireKey as p}from"./stableWireKey-Diuu1gGc.mjs";const F=2,$=8,f={},U=d=>{throw new x("INTERNAL",`unhandled relay frame: ${JSON.stringify(d)}`)},K=d=>Response.json(d,{headers:{"content-type":"application/json"}}),u=()=>new Response(null,{status:204});class E{constructor(e,s){this.host=e,this.roleId=s}host;roleId;async handleControl(e){let s;try{s=await e.text()}catch{return new Response("bad request",{status:400})}if(!await P(this.host.env(),e.headers.get(R),s))return new Response("forbidden",{status:403});let t;try{t=JSON.parse(s)}catch{return new Response("bad request",{status:400})}switch(t.type){case"relay_attach":return this.onAttach(t.relayIndex),u();case"relay_detach":return this.onDetach(t.relayIndex),u();case"relay_frame":return this.host.deliverWhisperLocal(t.topic,t.frame,void 0),await this.onWhisperFrame(t),u();case"relay_shape_poke":{const r=this.host.getWebSockets().length,a=Date.now(),o=this.onShapePoke({...t,args:g(t.args)});return this.host.recordShapePokeFanout(r,o,Date.now()-a),u()}case"relay_shape_subscribe":return K(this.onShapeSubscribe({...t,args:g(t.args)}));default:return U(t)}}maxRelays(){return m(this.host.env(),"LUNORA_MAX_RELAYS",$)}canAddressSiblings(){return this.siblingStub(this.roleId.ownerKey)!==void 0}siblingStub(e){return k(this.host.env(),this.host.shardBinding(),e)}async postRelayMessage(e,s){await this.requestRelayMessage(e,s)}async requestRelayMessage(e,s){const t=this.siblingStub(e);if(t===void 0)return;const r=JSON.stringify(s),a={"content-type":"application/json","x-lunora-shard-binding":this.host.shardBinding()??""},o=M(this.host.env());o!==void 0&&(a[R]=await L(o,r));try{return await t.fetch("https://relay.internal/_lunora/relay",{body:r,headers:a,method:"POST"})}catch{return}}}class W extends E{shapeUniformCache=new Map;relaySetCache;relayShapeRegistry=new Map;relayShapeProxies=new Map;promotionState="owned";constructor(e,s){super(e,{ownerKey:s})}async forwardWhisper(e,s){if(!this.canAddressSiblings())return;const t=this.ownerRelaySet();t.size!==0&&await Promise.all([...t].map(r=>this.postRelayMessage(y(this.roleId.ownerKey,r),{frame:s,topic:e,type:"relay_frame"})))}async onFlush(e,s){await Promise.all([this.multicastShapePokes(e,s),this.proxyShapePokes(e,s)])}seedRelayShape(){return Promise.resolve(void 0)}announce(){return Promise.resolve()}announceDrain(){return Promise.resolve()}relayCount(){const e=this.host.getWebSockets().length,s=m(this.host.env(),"LUNORA_RELAY_THRESHOLD",b.tUp),t=m(this.host.env(),"LUNORA_RELAY_COLLAPSE_THRESHOLD",b.tDown);if(this.promotionState=O(this.promotionState,e,C(s,t)),this.promotionState==="owned")return 0;const r=m(this.host.env(),"LUNORA_RELAY_FAN",F);return Math.min(this.maxRelays(),Math.max(1,r))}isShapeRelayUniform(e,s){const t=S(e,s),r=this.shapeUniformCache.get(t);if(r!==void 0)return r;const a=this.probeShapeRelayUniform(e,s);return this.shapeUniformCache.set(t,a),a}onAttach(e){this.addRelayToSet(e)}onDetach(e){this.removeRelayFromSet(e)}async onWhisperFrame(e){await Promise.all([...this.ownerRelaySet()].filter(s=>s!==e.originRelay).map(s=>this.postRelayMessage(y(this.roleId.ownerKey,s),{frame:e.frame,topic:e.topic,type:"relay_frame"})))}onShapeSubscribe(e){return this.buildShapeSeedFrames(e)}onShapePoke(){return 0}buildShapePoke(e,s,t,r,a){let o;try{o=this.host.resolveShape(e.name,e.args,s)}catch{return}if(o===void 0||o.global===!0||!t.has(o.table))return;const i=e,n=i.cursor,l=this.host.buildShapeDiff(o,n,r);if(l.length!==0)return i.cursor=r,{args:w(e.args),checkpoint:r,epoch:a,fromCursor:n,name:e.name,rowsPatch:T(l),type:"relay_shape_poke"}}async multicastShapePokes(e,s){if(this.relayShapeRegistry.size===0)return;const t=this.ownerRelaySet();if(t.size===0)return;const r=this.host.currentCdcEpoch(),a=[];for(const o of this.relayShapeRegistry.values()){const i=this.buildShapePoke(o,f,e,s,r);if(i)for(const n of t)a.push(this.postRelayMessage(y(this.roleId.ownerKey,n),i))}await Promise.all(a)}async proxyShapePokes(e,s){if(this.relayShapeProxies.size===0)return;const t=this.host.currentCdcEpoch(),r=[];for(const a of this.relayShapeProxies.values()){const o=this.buildShapePoke(a,a.identity,e,s,t);o&&r.push(this.postRelayMessage(y(this.roleId.ownerKey,a.relayIndex),{...o,targetConnectionId:a.connectionId}))}await Promise.all(r)}buildShapeSeedFrames(e){const s={identity:e.identity,userId:e.userId};let t;try{t=this.host.resolveShape(e.name,e.args,s)}catch(c){const{body:h}=A(c,{fallbackCode:"SHAPE_RESOLVE_FAILED",redactedMessage:"shape resolution failed"});return{error:{code:h.code,message:h.message}}}if(t===void 0||t.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:a,epoch:o,rowsPatch:i}=this.host.computeOpLogShapeSeed({args:e.args,name:e.name,sinceEpoch:e.sinceEpoch,sinceSeq:e.sinceSeq},t);let n=a;if(this.isShapeRelayUniform(e.name,e.args)){const c=S(e.name,e.args);let h=this.relayShapeRegistry.get(c);h===void 0&&(h={args:e.args,cursor:a,name:e.name},this.relayShapeRegistry.set(c,h)),n=h.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:a,epoch:o,identity:s,name:e.name,relayIndex:e.relayIndex,subId:e.subId});const l=_([{rowsPatch:i,shapeId:e.subId}],{baseCheckpoint:r,checkpoint:a,epoch:o,lastMutationId:void 0,pokeId:this.host.nextPokeId()});return{cursor:n,epoch:o,frames:l}}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(s=>Number(s.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 s=this.ownerRelaySet();s.delete(e);for(const[t,r]of this.relayShapeProxies)r.relayIndex===e&&this.relayShapeProxies.delete(t);s.size===0&&(this.relayShapeRegistry.clear(),this.shapeUniformCache.clear())}probeShapeRelayUniform(e,s){let t;try{t=this.host.resolveShape(e,s,f)}catch{return!1}if(t===void 0||t.global===!0||this.host.rlsMetadata().policies.some(n=>n.on==="read"&&n.table===t.table)||this.tableHasAnyMask(t.table))return!1;const r=p(t.effectiveWhere),a=p(t.columns);let o=!1;const i=n=>{const l={groups:[`grp_${n}`],roles:[n],sub:`__lunora_probe_${n}__`};return{identity:new Proxy(l,{get:(c,h)=>typeof h=="symbol"||h in c?Reflect.get(c,h):`${n}:${h}`,getOwnPropertyDescriptor:(c,h)=>(o=!0,Reflect.getOwnPropertyDescriptor(c,h)),has:(c,h)=>typeof h=="symbol"?Reflect.has(c,h):!0,ownKeys:c=>(o=!0,Reflect.ownKeys(c))}),userId:`__lunora_probe_${n}__`}};return[f,i("a"),i("b")].every(n=>{let l;try{l=this.host.resolveShape(e,s,n)}catch{return!1}return l!==void 0&&l.global!==!0&&l.table===t.table&&p(l.effectiveWhere)===r&&p(l.columns)===a})&&!o}tableHasAnyMask(e){return this.host.maskMetadata().columns.some(s=>s.table===e)}}class q extends E{relayAnnounced=!1;shapeRelayMemos=new WeakMap;constructor(e,s,t){super(e,{ownerKey:s,relayIndex:t})}async forwardWhisper(e,s){this.canAddressSiblings()&&await this.postRelayMessage(this.roleId.ownerKey,{frame:s,originRelay:this.roleId.relayIndex,topic:e,type:"relay_frame"})}onFlush(){return Promise.resolve()}async seedRelayShape(e,s,t,r){if(!this.canAddressSiblings())return{code:"RELAY_MISCONFIGURED",message:"relay cannot address its owner"};await this.announce();const a={args:w(t.args??{}),connectionId:this.host.readAttachment(e).connectionId,identity:r.identity,name:t.name,relayIndex:this.roleId.relayIndex,sinceEpoch:t.sinceEpoch,sinceSeq:t.sinceSeq,subId:s,type:"relay_shape_subscribe",userId:r.userId},o=await this.requestRelayMessage(this.roleId.ownerKey,a);if(o===void 0)return{code:"RELAY_SEED_FAILED",message:"owner did not answer the shape seed"};let i;try{i=await o.json()}catch{return{code:"RELAY_SEED_FAILED",message:"malformed shape seed from owner"}}if(i.error!==void 0)return i.error;if(i.frames===void 0)return{code:"RELAY_SEED_FAILED",message:"owner returned no shape frames"};await N(e);for(const n of i.frames)I(e,n);return this.recordRelayShapeMemo(e,s,i.cursor??0,i.epoch),"ok"}async announce(){this.relayAnnounced||!this.canAddressSiblings()||(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(s=>s!==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,s,t,r){let a=this.shapeRelayMemos.get(e);a===void 0&&(a=new Map,this.shapeRelayMemos.set(e,a)),a.set(s,{cursor:t,epoch:r})}deliverShapePoke(e){const s=S(e.name,e.args);let t=0;for(const r of this.host.getWebSockets()){const a=this.host.readAttachment(r),{shapes:o}=a,i=this.shapeRelayMemos.get(r);if(!(o===void 0||i===void 0)&&!(e.targetConnectionId!==void 0&&a.connectionId!==e.targetConnectionId))for(const[n,l]of Object.entries(o)){const c=i.get(n);if(c?.cursor!==e.fromCursor||c.epoch!==e.epoch||S(l.name,l.args)!==s)continue;const h=_([{rowsPatch:e.rowsPatch,shapeId:n}],{baseCheckpoint:void 0,checkpoint:e.checkpoint,epoch:e.epoch,lastMutationId:void 0,pokeId:this.host.nextPokeId()},{preEncoded:!0});for(const v of h)I(r,v);i.set(n,{cursor:e.checkpoint,epoch:e.epoch}),t+=1}}return t}}const X=d=>{const e=d.doName();if(e===void 0)return;const s=D(e);return s===void 0?new W(d,e):new q(d,s.ownerKey,s.relayIndex)};export{$ as DEFAULT_MAX_RELAYS,W as OwnerRelay,q as RelayMember,X as createRelayLink};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{LunoraError as s}from"@lunora/errors";import{stableWireKey as i}from"./stableWireKey-
|
|
1
|
+
import{LunoraError as s}from"@lunora/errors";import{stableWireKey as i}from"./stableWireKey-Diuu1gGc.mjs";const a="::relay::",h=(t,o)=>`${t}${a}${String(o)}`,w=t=>{const o=t.lastIndexOf(a);if(o===-1)return;const r=t.slice(0,o),n=t.slice(o+a.length),e=Number(n);if(!(r.length===0||!Number.isInteger(e)||e<0||String(e)!==n))return{ownerKey:r,relayIndex:e}},d=(t,o)=>i({args:o??{},name:t}),m={tDown:4e3,tUp:8e3},u=(t,o,r=m)=>{if(r.tDown>=r.tUp)throw new s("INTERNAL",`invalid promotion thresholds: tDown (${String(r.tDown)}) must be < tUp (${String(r.tUp)})`);return t==="owned"?o>=r.tUp?"promoted":"owned":o<r.tDown?"owned":"promoted"},c=(t,o)=>o<t?{tDown:o,tUp:t}:{tDown:Math.min(Math.max(1,Math.floor(t/2)),t-1),tUp:t},g=(t,o,r)=>{if(t<=o||o<=0)return 0;const n=t-o,e=Math.ceil(n/o);return Math.min(e,Math.max(0,r))};export{m as DEFAULT_PROMOTION_THRESHOLDS,a as RELAY_NAME_INFIX,c as clampPromotionThresholds,u as nextPromotionState,w as parseRelayName,g as relayCountFor,h as relayName,d as shapeRoutingKey};
|
package/dist/packem_shared/{DurableStreamRunner-C-OSu02s.mjs → DurableStreamRunner-B54Jt9Iu.mjs}
RENAMED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{toErrorBody as f,LunoraError as S}from"@lunora/errors";import{a as p}from"./wire-codec-
|
|
1
|
+
import{toErrorBody as f,LunoraError as S}from"@lunora/errors";import{a as p}from"./wire-codec-Dh0j-GnY.mjs";import{readStreamRun as k,deleteStreamRun as T,claimStreamRun as w,appendStreamChunk as y,finishStreamRun as R,trimStreamRuns as A,readStreamChunks as _}from"./appendStreamChunk-ksZYy1hZ.mjs";const g=5e4,E=64*1024*1024,b=864e5,N=36e5,M=(d,e)=>d===void 0||e.live?"attach":d.status==="complete"||d.status==="error"?e.resuming?"replay-terminal":"reclaim":e.resuming?"interrupted":"reclaim";class v{lastTrimAt=0;runs=new Map;sql;waitUntil;constructor(e){this.sql=e.sql,this.waitUntil=e.waitUntil}async attach(e){try{await this.attachOrThrow(e)}catch(r){const{body:t,redacted:i}=f(r,{fallbackCode:"INTERNAL_SERVER_ERROR",redactedMessage:"internal error"});i&&console.error("[@lunora/shard-engine] durable stream attach failed:",r),e.sink.fail({code:t.code,message:t.message})}}detach(e,r){this.runs.get(e)?.sinks.delete(r)}isLive(e){return this.runs.has(e)}async attachOrThrow(e){const r=this.sql(),{runKey:t,sinceChunk:i,sink:o}=e,s=k(r,t),u=i>0,n=this.runs.get(t),a=M(s,{live:n!==void 0,resuming:u}),c=()=>{for(const h of _(r,t,i))if(!o.chunk({data:JSON.parse(h.dataJson),seq:h.seq}))return!1;return!0};if(a==="replay-terminal"){c()&&(s?.status==="error"?o.fail({code:s.errorCode??"INTERNAL_SERVER_ERROR",message:s.error??"stream failed"}):o.complete());return}if(a==="interrupted"){c()&&o.fail({code:"STREAM_INTERRUPTED",message:"the producer for this durable stream did not survive; start a new run"});return}if(n){c()&&n.sinks.add(o);return}a==="reclaim"&&T(r,t),this.trim(r),w(r,t,Date.now(),e.ttlMs??b);const l={sinks:new Set([o])};this.runs.set(t,l);const m=this.produce(t,e.iterator,l);this.waitUntil?.(m),await m}async produce(e,r,t){const i=this.sql(),o=new AbortController;let s=0,u=0;try{for await(const n of r(o.signal)){const a=p(n),c=JSON.stringify(a);if(s+=1,u+=c.length,s>g||u>E)throw new S("STREAM_TOO_LONG",`durable stream exceeded its ceiling (${String(g)} chunks / ${String(E)} bytes); yield less, or drop \`durable\``,{status:507});y(i,e,s,c);for(const l of t.sinks)l.chunk({data:a,seq:s})||t.sinks.delete(l)}R(i,e,"complete",s);for(const n of t.sinks)n.complete()}catch(n){const{body:a,redacted:c}=f(n,{fallbackCode:"INTERNAL_SERVER_ERROR",redactedMessage:"internal error"});c&&console.error("[@lunora/shard-engine] unhandled durable stream error:",n),R(i,e,"error",s,{code:a.code,message:a.message});for(const l of t.sinks)l.fail({code:a.code,message:a.message})}finally{this.runs.delete(e)}}trim(e){const r=Date.now();if(!(r-this.lastTrimAt<=N)){this.lastTrimAt=r;try{A(e,r)}catch{}}}}export{v as DurableStreamRunner,E as MAX_DURABLE_STREAM_BYTES,g as MAX_DURABLE_STREAM_CHUNKS,M as decideDurableAttach};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{LunoraError as g}from"@lunora/errors";import{n as Bt,S as qt,x as Qe,T as Se,y as Ut,c as Pt}from"./ctx-db-companions-c12P7dbv.mjs";import{sql as r}from"drizzle-orm";import{s as Ht}from"./wire-codec-Dsy70M3Q.mjs";import{aggregateSqlFunction as Re,normalizeCountArgument as Gt,throwingScheduler as jt}from"./AGGREGATE_SQL_FUNCTION-CTo0-9iZ.mjs";import{encodeAggregateKey as De,readAggregateValue as Le,aggregateTableName as Oe}from"./aggregateTableName-DgYMC5tr.mjs";import{mergeWhere as Y,CountRlsUnsupportedError as Fe,selectIndexForGroupBy as Qt,selectIndexForCount as Kt,selectIndexForAggregate as Yt}from"./CountRlsUnsupportedError-8BqPYQoP.mjs";import{backfillSearchIndexesForTable as zt}from"./backfillAggregateIndexes-BEMWTEq1.mjs";import{backfillAggregateIndexes as Fr,backfillRankIndexes as Wr,backfillSearchIndexes as Br}from"./backfillAggregateIndexes-BEMWTEq1.mjs";import{appendCdcChange as Jt}from"./CDC_LOG_TABLE-DH-KHUfU.mjs";import{CDC_LOG_TABLE as Ur,applyCdcChanges as Pr,bumpCdcEpoch as Hr,minCdcSeq as Gr,readCdcChanges as jr,readCdcCursor as Qr,readCdcEpoch as Kr,trimCdcChanges as Yr}from"./CDC_LOG_TABLE-DH-KHUfU.mjs";import{computeRankPage as at}from"./computeRankPage-D1ygctSC.mjs";import{SCAN_DEP as U}from"./SCAN_DEP-D_yR9EeV.mjs";import{runDrizzle as W}from"./runDrizzle-C3n5gJsk.mjs";import{a as H,L as se,p as Ae,T as We,c as xe,N as J,E as ce,I as St,C as Vt,D as Rt,h as Xt,O as st}from"./do-sql-C7qrlm6-.mjs";import{WORKERD_SQLITE_LIMITS as At,unionAll as Pe,sqliteInList as Zt}from"./param-CYxL68V-.mjs";import{coveringGeohashes as en,boundingBoxGeohashes as tn,pointInBoundingBox as nn,haversineMeters as rn}from"./GEO_DEFAULT_PRECISION-DyI5zggj.mjs";import{NotFoundError as on}from"./NotFoundError-BhF7FeFr.mjs";import{normalizeOrderKeys as an,buildSeekWhere as xt,decodeCursor as He,applySelect as dt,encodeCursor as Ge,softDeleteScope as le,buildSeekBeforeWhere as sn}from"./applySelect-UY-o13Ia.mjs";import{sortColumnName as lt,resolveRankPartition as dn,encodePartitionKey as ln,RANK_TIEBREAK as cn,rankTableName as ct}from"./RANK_TIEBREAK-DDtST3gN.mjs";import{indexKeysForRow as un,buildIndexRange as fn}from"./buildIndexRange-DFsdtPjD.mjs";import{assertFlatPredicate as Be,resolveRelationPredicates as ut}from"./DEFAULT_MAX_RELATION_KEYS-DjKka36Z.mjs";import{runRowValidators as qe,resolveWith as ft,relationHooks as ht,applyOnDelete as hn,fanOutScalarCounts as mn}from"./applyOnDelete-By23GK-k.mjs";import{guardWriter as pn}from"./RLS_UNWRAP_SYMBOL-DcqORh2s.mjs";import{f as $n}from"./sql-projection-jfoe331H.mjs";import{createSystemReader as wn}from"./createSystemReader-DcDcrtM3.mjs";import{ConflictError as pe}from"./ConflictError-C8GtJmjS.mjs";import{runTriggers as gn}from"./hasTrigger-CbkOHExZ.mjs";import{compileWhereSql as te}from"./compileWhereSql-B3hq_v98.mjs";import{CLIENT_WATERMARK_TABLE as Jr,advanceClientWatermark as Vr,migrateClientWatermark as Xr,readClientWatermark as Zr}from"./CLIENT_WATERMARK_TABLE-LrKfdxyt.mjs";import{GLOBAL_SHAPE_SNAPSHOT_TABLE as to,deleteGlobalShapeSnapshot as no,deleteGlobalShapeSnapshotsForConnection as ro,migrateGlobalShapeSnapshot as oo,readGlobalShapeSnapshot as io,writeGlobalShapeSnapshot as ao}from"./GLOBAL_SHAPE_SNAPSHOT_TABLE-B2LKe4KU.mjs";import{IDEMPOTENCY_TABLE as lo,readIdempotent as co,trimIdempotent as uo,writeIdempotent as fo}from"./IDEMPOTENCY_TABLE-tQ5mnqvw.mjs";import{runShardMigrations as mo}from"./runShardMigrations-BAtfEXbB.mjs";import{SEARCH_STATE_TABLE as $o}from"./SEARCH_STATE_TABLE-DRk_SB72.mjs";import{selectShapeMemberIds as go,selectShapeRows as bo}from"./selectShapeMemberIds-WzxOG62k.mjs";import{serializeSqlValue as ie}from"./serializeSqlValue-BR4UOWoP.mjs";import{quoteIdentifier as bn}from"./quoteIdentifier-CObIFRhb.mjs";const En=o=>{const i=new TextEncoder().encode(o);let t="";for(const d of i)t+=String.fromCodePoint(d);return btoa(t)},yn=o=>{const i=atob(o),t=Uint8Array.from(i,d=>d.codePointAt(0)??0);return new TextDecoder().decode(t)},Nn=()=>new g("BAD_REQUEST","invalid cursor"),mt=16,pt=8,V=1024,Ke=(o,i)=>i.query(o),_n=(o,i,t)=>{const d=Bt(o,t);if(d.length===0)return 0;let f=0;for(const[m,b]of i.entries()){const S=m===i.length-1;let y=0;for(const w of d)(S?w.startsWith(b):w===b)&&(y+=1);if(y===0)return 0;f+=y}return f},Tn=(o,i)=>{if(!i)return{exact:!0,lower:o,upper:o};const t=[...o].at(-1)??"",d=(t.codePointAt(0)??0)+1;if(d>=55296&&d<=57343||d>1114111)return{exact:!0,lower:o,upper:o};const f=o.slice(0,o.length-t.length);return{exact:!1,lower:o,upper:f+String.fromCodePoint(d)}},Sn=(o,i,t)=>{const d={eq:(f,m)=>{if(!o.definition.filterFields?.includes(f))throw new g("INTERNAL",`field "${f}" is not a filter field of search index "${o.indexName}" on table "${i}"`);if(o.filters.length>=pt)throw new g("BAD_REQUEST",`search index "${o.indexName}" on table "${i}": at most ${String(pt)} .eq() filters are supported per search query`);return o.filters.push({field:f,value:m}),d},search:(f,m)=>{const b=o;if(f!==b.definition.field)throw new g("INTERNAL",`search index "${b.indexName}" on table "${i}" indexes "${b.definition.field}", not "${f}"`);const S=Ke(m,t).length;if(S>mt)throw new g("BAD_REQUEST",`search index "${b.indexName}" on table "${i}": at most ${String(mt)} search terms are supported (got ${String(S)})`);return b.field=f,b.query=m,b.hasQuery=!0,d}};return d},Rn=o=>{if(o.length>V)throw new g("BAD_REQUEST",`more than ${String(V)} documents match this search — narrow it with filters or read it a page at a time with .paginate()`)},An=o=>Math.min(o.offset+o.numItems+1,V),xn=o=>En(`search:${String(o)}`),In=o=>{let i;try{i=yn(o)}catch{return}if(!i.startsWith("search:"))return;const t=Number(i.slice(7));return Number.isInteger(t)&&t>=0?t:void 0},vn=o=>{if(typeof o.endCursor=="string")throw new g("BAD_REQUEST","bounded (endCursor) pagination is not supported on search queries — relevance order has no stable range boundary");const i=Math.max(0,Math.floor(o.numItems)),t=o.cursor?In(o.cursor):0;if(t===void 0)throw Nn();if(t+i>V)throw new g("BAD_REQUEST",`search pagination reaches past the ${String(V)}-document limit (offset ${String(t)} + ${String(i)} requested) — narrow the query or the filters instead`);return{numItems:i,offset:t}},Cn=(o,i)=>{const t=i.offset+i.numItems,d=i.numItems>0&&o.length>t;return{continueCursor:d?xn(t):null,isDone:!d,page:o.slice(i.offset,t)}},Mn=o=>{if(o===void 0)return V+1;if(!Number.isFinite(o))return V;const i=Math.max(0,Math.floor(o));if(i>V)throw new g("BAD_REQUEST",`search returns at most ${String(V)} documents (asked for ${String(i)}) — narrow the query or paginate instead`);return i},kn=/^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/iu,Dn=o=>{if(!kn.test(o))throw new g("INTERNAL",`invalid clientId ${JSON.stringify(o)}: a client-supplied row id must be a UUID`)},$t=50,It=500,wt=Math.floor(At.boundParams/3),me=At.boundParams,Ln=128,de=(o,i,t)=>{const d=i??It;if(o>d)throw new g("BATCH_LIMIT_EXCEEDED",`${t}: batch of ${String(o)} exceeds the limit of ${String(d)} (raise options.limit or chunk the call)`,{status:400})},On=o=>{const i={eq:(t,d)=>(o.sqlConditions.push({comparator:"=",field:t,value:d}),i),gt:(t,d)=>(o.sqlConditions.push({comparator:">",field:t,value:d}),i),gte:(t,d)=>(o.sqlConditions.push({comparator:">=",field:t,value:d}),i),lt:(t,d)=>(o.sqlConditions.push({comparator:"<",field:t,value:d}),i),lte:(t,d)=>(o.sqlConditions.push({comparator:"<=",field:t,value:d}),i)};return i},Fn=o=>Math.max(o,V),vt=(o,i)=>{const t=o.filters.map(d=>r`${J(d.field)} = ${ie(d.value)}`);return i&&t.push(i),t},Wn=(o,i,t,d,f)=>{const m=Ke(t.query,Qe(t.definition.language));if(m.length===0)return[];const b=Pt(i,t.indexName),S=`${b}__vocab`,y=m.length-1,w=m.map((L,M)=>{const G=Tn(L,M===y),j=G.exact?r`${r.identifier("term")} = ${G.lower}`:r`${r.identifier("term")} >= ${G.lower} AND ${r.identifier("term")} < ${G.upper}`;return r`SELECT ${r.identifier("doc")}, ${r.raw(String(M))} AS ${r.identifier("__term__")}, COUNT(*) AS ${r.identifier("__n__")} FROM ${r.identifier(S)} WHERE ${j} GROUP BY ${r.identifier("doc")}`}),N=m.map((L,M)=>r`SUM(CASE WHEN u.${r.identifier("__term__")} = ${r.raw(String(M))} THEN u.${r.identifier("__n__")} ELSE 0 END)`),_=r`SELECT f.${r.identifier(Se)} AS ${r.identifier(Se)}, ${r.join(N,r` + `)} AS ${r.identifier("__score__")} FROM (${Pe(w)}) u JOIN ${r.identifier(b)} f ON f.rowid = u.${r.identifier("doc")} GROUP BY f.${r.identifier(Se)} HAVING ${r.join(N.map(L=>r`${L} > 0`),r` AND `)}`,T=vt(t,f);let v=r`SELECT m.id, m._creationTime, m.${r.identifier(H)}, s.${r.identifier("__score__")} AS ${r.identifier("__score__")} FROM (${_}) s JOIN ${r.identifier(i)} m ON m.id = s.${r.identifier(Se)}`;T.length>0&&(v=r`${v} WHERE ${r.join(T,r` AND `)}`),v=r`${v} ORDER BY s.${r.identifier("__score__")} DESC, m._creationTime DESC, m.id ASC LIMIT ${r.raw(String(d))}`;const O=[];for(const L of W(o,v)){const M=Rt(L);if(M){const G=L.__score__;O.push({document:M,score:typeof G=="number"?G:Number(G??0)})}}return O},Bn=(o,i,t,d,f)=>{const m=Qe(t.definition.language),b=Ke(t.query,m);if(b.length===0)return[];const S=vt(t,f);let y=r`SELECT id, _creationTime, ${r.identifier(H)} FROM ${r.identifier(i)}`;S.length>0&&(y=r`${y} WHERE ${r.join(S,r` AND `)}`),y=r`${y} ORDER BY _creationTime DESC, id ASC LIMIT ${r.raw(String(Fn(d)))}`;const w=W(o,y).toArray(),N=[];for(const _ of w){const T=Rt(_);if(!T)continue;const v=_n(Ut(T,t.definition),b,m);v>0&&N.push({creationTime:typeof T._creationTime=="number"?T._creationTime:0,doc:T,id:typeof T._id=="string"?T._id:"",score:v})}return N.sort((_,T)=>T.score-_.score||T.creationTime-_.creationTime||_.id.localeCompare(T.id)),N.slice(0,d).map(_=>({document:_.doc,score:_.score}))},Ue=(o,i,t,d)=>{if(!Number.isFinite(o.lat)||o.lat<-90||o.lat>90||!Number.isFinite(o.lng)||o.lng<-180||o.lng>180)throw new g("BAD_REQUEST",`geo index "${d}" on table "${t}": ${i} must have a finite lat in [-90, 90] and lng in [-180, 180]`)},qn=(o,i)=>{const t=o,d={near:(f,m)=>{if(t.within)throw new g("INTERNAL",`geo index "${t.indexName}" on table "${i}": call .near() or .within(), not both`);if(Ue(f,".near() point",i,t.indexName),!Number.isFinite(m)||m<=0)throw new g("BAD_REQUEST",`geo index "${t.indexName}" on table "${i}": .near() radiusMeters must be a finite number > 0, got ${String(m)}`);return t.near={point:{lat:f.lat,lng:f.lng},radiusMeters:m},d},within:f=>{if(t.near)throw new g("INTERNAL",`geo index "${t.indexName}" on table "${i}": call .near() or .within(), not both`);if(Ue(f.sw,".within() sw corner",i,t.indexName),Ue(f.ne,".within() ne corner",i,t.indexName),f.sw.lat>f.ne.lat)throw new g("BAD_REQUEST",`geo index "${t.indexName}" on table "${i}": .within() corners are transposed (sw.lat > ne.lat)`);if(f.sw.lng>f.ne.lng)throw new g("BAD_REQUEST",`geo index "${t.indexName}" on table "${i}": .within() box crosses the antimeridian (sw.lng > ne.lng), which is not supported — split it into two boxes at ±180 and union the results`);return t.within={ne:{lat:f.ne.lat,lng:f.ne.lng},sw:{lat:f.sw.lat,lng:f.sw.lng}},d}};return d},Un=(o,i)=>{const t=o[i];if(t===null||typeof t!="object")return;const{lat:d,lng:f}=t;return typeof d=="number"&&typeof f=="number"?{lat:d,lng:f}:void 0},Pn=(o,i)=>{const t=Un(o,i.definition.field);if(!t)return;const d=typeof o._creationTime=="number"?o._creationTime:0;if(i.near){const f=rn(i.near.point,t);return f<=i.near.radiusMeters?{creationTime:d,distance:f}:void 0}return nn(t,i.within)?{creationTime:d,distance:0}:void 0},Hn=(o,i,t,d)=>{if(!t.near&&!t.within)throw new g("INTERNAL",`geo index "${t.indexName}" on table "${i}": call .near(point, radius) or .within(box)`);const f=t.near?en(t.near.point,t.near.radiusMeters):tn(t.within),m=Xt(i,t.indexName),b=f.map(_=>r`(g.${r.identifier("__geohash__")} >= ${_} AND g.${r.identifier("__geohash__")} < ${`${_}{`})`),S=[r`(${r.join(b,r` OR `)})`];d&&S.push(d);const y=r`SELECT m.id, m._creationTime, m.${r.identifier(H)} FROM ${r.identifier(m)} g JOIN ${r.identifier(i)} m ON m.id = g.${r.identifier("__id__")} WHERE ${r.join(S,r` AND `)}`,w=W(o,y).toArray(),N=[];for(const _ of w){const T=ce(_),v=T?Pn(T,t):void 0;T&&v&&N.push({creationTime:v.creationTime,distance:v.distance,doc:T})}return N.sort((_,T)=>_.distance-T.distance||T.creationTime-_.creationTime),N},Ct=(o,i,t,d)=>{const f=[];for(const m of o)if(i.every(b=>b(d(m)))&&(f.push(m),typeof t=="number"&&f.length>=t))break;return f},Gn=(o,i,t,d,f,m=()=>{})=>{const b=t.within!==void 0,S=Hn(o,i,t,f).map(y=>({distanceMeters:b?null:y.distance,document:y.doc}));return m(S.length),typeof d=="number"?S.slice(0,Math.max(0,Math.floor(d))):S},Mt=(o,i,t,d,f,m=()=>{})=>{const{geo:b}=t;if(!b)throw new g("INTERNAL","runGeoTerminalScored called without a staged geo query");const S=t.inMemoryFilters.length>0,y=Gn(o,i,b,S?void 0:f,d,m);return S?Ct(y,t.inMemoryFilters,f,w=>w.document):y},jn=(o,i,t,d,f,m=()=>{})=>Mt(o,i,t,d,f,m).map(b=>b.document),Qn=(o,i,t,d,f,m,b=()=>{})=>{const S=[];for(const _ of t.sqlConditions)S.push(r`${J(_.field)} ${r.raw(_.comparator)} ${ie(_.value)}`);d&&S.push(d);let y=r`SELECT id, _creationTime, ${r.identifier(H)} FROM ${r.identifier(i)}`;S.length>0&&(y=r`${y} WHERE ${r.join(S,r` AND `)}`),y=r`${y} ORDER BY ${f}`,typeof m=="number"&&t.inMemoryFilters.length===0&&(y=r`${y} LIMIT ${r.raw(String(Math.max(0,Math.floor(m))))}`);const w=W(o,y).toArray();b(w.length);const N=[];for(const _ of w){const T=ce(_);if(T&&t.inMemoryFilters.every(v=>v(T))&&(N.push(T),typeof m=="number"&&N.length>=m))break}return N},oe={fieldRef:J,serialize:ie},kt=(o,i)=>{const t=i===void 0?void 0:o.shape[i];return t!==void 0&&$n(t)},gt=(o,i)=>i.some(t=>kt(o,t)),bt=(o,i,t)=>{if(kt(o,i))throw new g("BAD_REQUEST",`${t}: "${i}" is stored as an order-preserving key, which SQL cannot reduce or group — declare an aggregateIndex covering this (by, field, op) so the maintained companion answers it`)},Kn=o=>{let i=0;const t=[],d={fieldRef:J,relationExists:f=>{const{childWhere:m,negated:b,parentTable:S,relation:y}=f,w=`__rel_${String(i)}`,N=t.at(-1)??S;i+=1,o(y.table,U);const _=y.kind==="one"?y.field:y.references,T=y.kind==="one"?y.references:y.field,v=r`${st(w,T)} = ${st(N,_)}`;t.push(w);const O=te(m,d);t.pop();const L=O?r`${v} AND ${O}`:v,M=r`EXISTS (SELECT 1 FROM ${r.identifier(y.table)} AS ${r.identifier(w)} WHERE ${L})`;return b?r`NOT ${M}`:M},serialize:ie};return d},Dt=o=>{const i=o.map(t=>r`${J(t.field)} ${r.raw(t.direction==="desc"?"DESC":"ASC")}`);return o.some(t=>t.field==="_id"||t.field==="id")||i.push(r`${J("id")} ASC`),r.join(i,r`, `)},Yn={"<":"lt","<=":"lte","=":"eq",">":"gt",">=":"gte"},zn=o=>{const i=o.order;return o.indexFields.length>0?o.indexFields.map(t=>({direction:i,field:t})):[{direction:i,field:"_creationTime"}]},Jn=(o,i,t,d)=>{const f=o.sqlConditions.map(m=>({[m.field]:{[Yn[m.comparator]??"eq"]:m.value}}));if(t&&f.push(xt(i,He(t))),d&&f.push(sn(i,He(d))),f.length!==0)return f.length===1?f[0]:{AND:f}},Vn=(o,i,t)=>{const d=[];for(const f of o){const m=ce(f);if(m&&i.every(b=>b(m))&&(d.push(m),t!==void 0&&d.length>t))break}return d},Xn=(o,i,t,d,f,m=()=>{})=>{const b=Math.max(0,Math.floor(d.numItems)),S=zn(t),y=typeof d.endCursor=="string",w=te(Jn(t,S,d.cursor,d.endCursor),oe),N=f&&w?r`${w} AND ${f}`:f??w;let _=r`SELECT id, _creationTime, ${r.identifier(H)} FROM ${r.identifier(i)}`;N&&(_=r`${_} WHERE ${N}`),_=r`${_} ORDER BY ${Dt(S)}`;const T=t.inMemoryFilters.length>0;!T&&!y&&(_=r`${_} LIMIT ${r.raw(String(b+1))}`);const v=W(o,_).toArray();m(v.length);const O=Vn(v,t.inMemoryFilters,T||y?void 0:b);if(y){const j=O.length>=2?O[Math.floor(O.length/2)-1]:void 0;return{continueCursor:d.endCursor??null,isDone:!0,page:O,splitCursor:j?Ge(j,S):null}}const L=O.length>b,M=L?O.slice(0,b):O,G=M.at(-1);return{continueCursor:L&&G?Ge(G,S):null,isDone:!L,page:M}};class Zn extends g{constructor(i="unique() found more than one matching document"){super("NOT_UNIQUE",i,{name:"NotUniqueError"})}}const er=/\s/u,tr=String.fromCodePoint(0),Et=(o,i,t)=>{if(!o.tables[i])throw new g("INTERNAL",`unknown table: ${i}`);return typeof t!="string"||t.length===0||er.test(t)||t.includes(tr)?null:t},nr=(o,i,t,d=()=>{},f=()=>{},m=()=>{})=>{const b=i.tables[t];if(!b)throw new g("INTERNAL",`unknown table: ${t}`);const S=le(b.softDeleteMode,void 0),y=S?te(S,oe):void 0,w={indexFields:[],indexName:void 0,inMemoryFilters:[],order:"asc",sqlConditions:[]};let N=0;const _=E=>{const{search:I}=w;if(!I)throw new g("INTERNAL","runSearchFetch called without a staged search");zt(o,t,b);const C=w.inMemoryFilters.length>0,k=Mn(C?void 0:E),z=Vt(o)?Wn(o,t,I,k,y):Bn(o,t,I,k,y);return C?(N=z.length,Ct(z,w.inMemoryFilters,E,ne=>ne.document)):(E===void 0&&Rn(z),z)},T=E=>_(E).map(I=>I.document),v=E=>{const I=vn(E);return Cn(T(An(I)),I)},O=()=>{const E=w.indexFields.length>0?w.indexFields:["_creationTime"],I=w.order==="desc"?"DESC":"ASC";return r.join(E.map(C=>r`${J(C)} ${r.raw(I)}`),r`, `)},L=()=>{if(w.search||w.geo||w.indexName===void 0){f(void 0);return}f(fn(t,w.indexName,w.indexFields,w.sqlConditions,ie))},M=E=>{L();let I=0;const C=(()=>{if(w.search){const k=T(E);return I=N,k}return w.geo?jn(o,t,w,y,E,k=>{I=k}):Qn(o,t,w,y,O(),E,k=>{I=k})})();return m(Math.max(I,C.length)),C},G=()=>{if(!w.search&&!w.geo)throw new g("INTERNAL",`ctx.db.query("${t}").collectWithScores() requires a staged .withSearchIndex(...) or .withGeoIndex(...)`);L();let E=0;const I=(()=>{if(w.search){const C=_(void 0);return E=N,C}return Mt(o,t,w,y,void 0,C=>{E=C})})();return m(Math.max(E,I.length)),I},j={async*[Symbol.asyncIterator](){const E=[...w.inMemoryFilters];let I;w.inMemoryFilters=[];try{for(;;){const C=await j.paginate({cursor:I??null,numItems:Ln});for(const k of C.page)E.every(z=>z(k))&&(yield k);if(C.isDone||C.continueCursor===null)return;I=C.continueCursor}}finally{w.inMemoryFilters=E}},async collect(){return M(void 0)},async collectWithScores(){return G()},filter(E){return w.inMemoryFilters.push(E),j},async first(){return M(w.inMemoryFilters.length>0?void 0:1)[0]??null},order(E){return w.order=E==="desc"?"desc":"asc",j},async paginate(E){let I=0;if(L(),w.search){const k=v(E);return m(k.page.length),k}if(w.geo)throw new g("INTERNAL","pagination is not supported on geo queries; use .take(n) or .collect()");const C=Xn(o,t,w,E,y,k=>{I=k});return m(Math.max(I,C.page.length)),C},async take(E){return M(E)},async unique(){const E=M(w.inMemoryFilters.length>0?void 0:2);if(E.length>1)throw new Zn(`unique() on table "${t}" matched ${String(E.length)} documents; expected at most one`);return E[0]??null},withGeoIndex(E,I){const C=(b.geoIndexes??[]).find(z=>z.name===E);if(!C)throw new g("INTERNAL",`unknown geo index "${E}" on table "${t}"`);d(t,E,"geo");const k={definition:C,indexName:E};if(w.geo=k,I(qn(k,t)),!k.near&&!k.within)throw new g("INTERNAL",`geo index "${E}" on table "${t}" requires a .near(point, radius) or .within(box) call`);return j},withIndex(E,I){const C=b.indexes.find(k=>k.name===E);if(!C)throw new g("INTERNAL",`unknown index "${E}" on table "${t}"`);return d(t,E,"index"),w.indexName=E,w.indexFields=C.fields,I&&I(On(w)),j},withSearchIndex(E,I){const C=(b.searchIndexes??[]).find(z=>z.name===E);if(!C)throw new g("INTERNAL",`unknown search index "${E}" on table "${t}"`);d(t,E,"search");const k={definition:C,field:C.field,filters:[],hasQuery:!1,indexName:E,query:""};if(w.search=k,I(Sn(k,t,Qe(C.language))),!k.hasQuery)throw new g("INTERNAL",`search index "${E}" on table "${t}" requires a .search(field, query) call`);return j}};return j},yt=(o,i,t)=>{const d={...i};for(const[f,m]of St(o)){if(m.serverDefault){d[f]=m.serverDefault({auth:t});continue}d[f]===void 0&&(m.defaultFn?d[f]=m.defaultFn():"defaultValue"in m&&(d[f]=m.defaultValue))}return d},Nt=(o,i,t,d)=>{const f=t;for(const[m,b]of St(o)){if(b.serverDefault){m in i&&(f[m]=b.serverDefault({auth:d}));continue}b.onUpdateFn&&!(m in i)&&(f[m]=b.onUpdateFn())}},_t=(o,i)=>{for(const t of Object.keys(i))if(i[t]===void 0)throw new g("INTERNAL",`Cannot ${o} field '${t}' to undefined — use null to clear a nullable field, or omit the key to leave it unchanged.`)},rr=/unique constraint failed/i,or=o=>o instanceof Error&&rr.test(o.message),je=(o,i,t)=>{try{W(o,t)}catch(d){throw or(d)?new pe(`unique constraint violation on "${i}"`,"unique"):d}},Ie=(o,i,t)=>{if(je(o,i,t),W(o,r`SELECT changes() AS changed`).one().changed===0)throw new pe(`optimistic concurrency conflict on "${i}" — the row changed during this mutation; refetch and retry`,"occ")},Tt=(o,i,t,d,f,m,b)=>{const S=[];for(let _=0;_<t.length+1;_+=1){const T=[];for(let M=0;M<_;M+=1)T.push(r`${r.identifier(t[M])} IS ${m[M]}`);const v=t[_],O=d[_];if(v!==void 0&&O!==void 0){const M=O.direction==="desc"?">":"<";T.push(r`${r.identifier(v)} ${r.raw(M)} ${m[_]}`)}else T.push(r`${r.identifier(cn)} < ${b}`);const[L]=T;S.push(T.length===1&&L!==void 0?L:r`(${r.join(T,r` AND `)})`)}const y=r.join(S,r` OR `),w=W(o,r`SELECT COUNT(*) AS c FROM ${r.identifier(i)} WHERE ${r.identifier("__partition__")} = ${f} AND (${y})`).one(),N=W(o,r`SELECT COUNT(*) AS c FROM ${r.identifier(i)} WHERE ${r.identifier("__partition__")} = ${f}`).one();return{before:w.c,total:N.c}},Dr=o=>{const{sql:i}=o,{schema:t}=o,d=o.broadcast??(()=>{}),f=(e,...n)=>{const a=t.tables[e]?.indexes;if(!a||a.length===0)return;const c=[];for(const h of n)h&&c.push(...un(a,h,ie));return c.length>0?c:void 0},{headroom:m}=o;let b=!1;const S=async e=>{const n=b;b=!0;try{return await e()}finally{b=n}},y=o.onRead??(()=>{}),w=o.onReadRange??(e=>{y(e.table,U)}),N=(e,n)=>{n!==void 0&&n!==U&&!b&&m?.recordRead(1),y(e,n)},_=o.onIndexUse??(()=>{}),T=o.onWrite??(()=>{}),v=e=>{b||m?.recordWrite(e)},O=async e=>{v(e.doc),await T(e)},{cache:L}=o,M=o.clock??(()=>Date.now()),G=o.idGenerator??(()=>crypto.randomUUID()),j=o.scheduler??jt,{globalDb:E}=o,I=o.auth??{identity:null,userId:null},C=o.cdc??!1,k=j,z=wn({scheduler:typeof k.list=="function"&&typeof k.get=="function"?k:void 0,storage:o.storage}),ne=(e,n,a,c)=>{C&&Jt(i,M(),e,n,a,c)},ae=e=>t.tables[e]?.shardMode?.kind==="global",Ye=(e,n)=>{if(ae(e)){if(!E)throw new g("INTERNAL",`cross-backend ${n} for global table '${e}' requires a globalDb writer — pass one to createShardCtxDb({ globalDb })`);return E}return B},ve=e=>Ye(e,"cascade"),K=(e,n)=>{if(ae(e)){if(!E)throw new g("INTERNAL",`${n} on global table '${e}' requires a globalDb writer — pass one to createShardCtxDb({ globalDb })`);return E}},ze=async(e,n,a,c,h)=>{h&&v(a);const u=await e.insert(n,a,c);return d({key:u,op:"insert",row:{...a,_id:u},table:n}),u},Ce=(e,n)=>Ye(e,"relation load").findMany(e,n),Je=(e,n)=>(ae(e)&&N(e,U),Ce(e,n)),Lt=e=>!ae(e.table),Ve=o.relationExistsPushDown??"auto",Xe=Ve!=="never",{maxRelationKeys:Ze}=o,$e=(e,n,a)=>ut(e,{fetcher:Je,maxRelationKeys:Ze,relationBaseWhere:a,schema:t,tableName:n}),et=async(e,n,a,c)=>{const h=K(e,"relation grouped count");if(h)return N(e,U),mn((P,x)=>h.count(P,x),e,n,a,c);const u=t.tables[e];if(!u)throw new g("INTERNAL",`unknown table: ${e}`);N(e,U);const s=le(u.softDeleteMode,void 0),l={[n]:{in:a}},p=Y(Y(l,c),s),R=await $e(p,e,void 0),$=te(R,oe),A=J(n);let D=r`SELECT ${A} AS __fk__, COUNT(*) AS count FROM ${r.identifier(e)}`;$&&(D=r`${D} WHERE ${$}`),D=r`${D} GROUP BY ${A}`;const F=W(i,D).toArray();return new Map(F.map(P=>[P.__fk__,P.count]))};let we=0;const tt=new Set;for(const[e,n]of Object.entries(t.tables))for(const a of Object.values(n.triggerMap??{}))tt.add(`${e} ${a.timing} ${a.op}`);const X=(e,n,a)=>tt.has(`${e} ${n} ${a}`),Z=async(e,n,a)=>{if(we+=1,we>$t)throw we-=1,new pe(`trigger recursion exceeded ${String($t)} levels on "${a.table}" — check for a self-triggering write`,"trigger");try{await gn({ctx:Ft,event:a,op:n,schema:t,tableName:a.table,timing:e})}finally{we-=1}},{ensureBackfilledForTable:ue,ensureBackfilledIndex:Me,ensureRankBackfilled:ke,ensureRankBackfilledForTable:fe,syncAggregates:ge,syncCompanionsForInsert:nt,syncGeo:be,syncRanks:he,syncSearch:Ee}=qt({broadcast:d,indexKeysFor:(e,n)=>f(e,n),invalidateCache:(e,n,a)=>L?.invalidate(e,n,f(e,a)),recordCdc:ne,schema:t,sql:i}),rt=(e,n,a)=>{const{shardMode:c}=n;if(c?.kind==="shardBy"&&!(c.field!==void 0&&(a.partitionBy??[]).includes(c.field)))throw Object.assign(new Error(`rank index "${a.name}" on "${e}" partitions across shards (shard key "${c.field??"?"}" is not in partitionBy) — a shard-local rank()/rankPage() would be wrong; roll it up through the Query Coordinator instead`),{code:"CROSS_SHARD_RANK_UNSUPPORTED",name:"LunoraError",status:400})},ot=e=>Object.entries(t.tables).filter(([,n])=>n.shardMode?.kind!=="global").map(([n])=>n).filter(n=>e===void 0||n===e),re=(e,n)=>{const a=ot(n);for(let c=0;c<a.length;c+=me){const h=a.slice(c,c+me).map(R=>r`SELECT ${r.raw(`'${R.replaceAll("'","''")}'`)} AS __t__, id, _creationTime, ${r.identifier(H)} FROM ${r.identifier(R)} WHERE id = ${e}`),[u]=W(i,r`${Pe(h)} LIMIT 1`).toArray();if(!u)continue;const s=u.__t__,l=ce(u);if(typeof s!="string"||!l)return;const p=u[H];return{docJson:typeof p=="string"?p:se(p??{}),row:l,tableName:s}}},Ot=(e,n)=>{const a=[...new Set(e)],c=new Map;if(a.length===0)return c;const h=ot(n);for(let u=0;u<h.length;u+=me){const s=h.slice(u,u+me),l=Math.floor(me/s.length),p=Zt(r`${r.identifier("id")}`,a,!1,l),R=s.map($=>r`SELECT ${r.raw(`'${$.replaceAll("'","''")}'`)} AS __t__, id FROM ${r.identifier($)} WHERE ${p}`);for(const $ of W(i,Pe(R))){const{id:A,__t__:D}=$;typeof D=="string"&&typeof A=="string"&&c.set(A,D)}}return c},it={assertRankPartitionLocal:rt,ensureRankBackfilled:ke,onRead:N,rowToDocument:ce,schema:t,sql:i},B={system:z,async aggregate(e,n){const a=K(e,"aggregate");if(a)return N(e,U),a.aggregate(e,n);const c=t.tables[e];if(!c)throw new g("INTERNAL",`unknown table: ${e}`);if(Re(n.op),n.op==="count")return B.count(e,{baseWhere:n.baseWhere,relationBaseWhere:n.relationBaseWhere,restrictsCounts:n.restrictsCounts,where:n.where});if(!n.field)throw new g("INTERNAL",`aggregate(${e}, { op: "${n.op}" }): "field" is required for non-count reducers`);N(e,U);const h=le(c.softDeleteMode,void 0),u=Y(Y(n.baseWhere,n.where),h),s=await $e(u,e,n.relationBaseWhere),l=s!==u;if(c.aggregateIndexes&&!n.baseWhere&&!l&&(!h||gt(c,[n.field]))){const F=Yt(c.aggregateIndexes,n.op,n.field,n.where);if(F){Me(e,F.index);const P=De(F.index.by??[],F.key),x=Oe(e,F.index.name),Q=W(i,r`SELECT ${Ae} AS value, ${We} AS count FROM ${r.identifier(x)} WHERE ${xe} = ${P}`).toArray()[0];return Le(n.op,Q)}}bt(c,n.field,`aggregate(${e}, { op: "${n.op}", field: "${n.field}" })`);const p=te(s,oe),R=Re(n.op),$=J(n.field);let A=r`SELECT ${r.raw(R)}(${$}) AS value FROM ${r.identifier(e)}`;return p&&(A=r`${A} WHERE ${p}`),W(i,A).toArray()[0]?.value??null},asId(e,n){const a=Et(t,e,n);if(a===null)throw new g("BAD_REQUEST",`asId("${e}", …): "${n}" is not a valid id for table "${e}"`,{status:400});return a},async count(e,n){const a=K(e,"count");if(a)return N(e,U),a.count(e,n);const c=t.tables[e];if(!c)throw new g("INTERNAL",`unknown table: ${e}`);const h=Gt(n);if(h.restrictsCounts)throw new Fe(e);N(e,U);const u=le(c.softDeleteMode,void 0),s=Y(Y(h.baseWhere,h.where),u),l=await $e(s,e,h.relationBaseWhere),p=l!==s;if(c.aggregateIndexes&&!h.baseWhere&&!p&&!u){const A=Kt(c.aggregateIndexes,h.where);if(A){Me(e,A.index);const D=De(A.index.by??[],A.key),F=Oe(e,A.index.name),P=W(i,r`SELECT ${Ae} AS value FROM ${r.identifier(F)} WHERE ${xe} = ${D}`).toArray();return P[0]===void 0?0:P[0].value??0}}const R=te(l,oe);let $=r`SELECT COUNT(*) AS count FROM ${r.identifier(e)}`;return R&&($=r`${$} WHERE ${R}`),W(i,$).one().count},async delete(e,n,a){const c=re(e,n);if(!c){const $=n===void 0?E:void 0;$&&(v(void 0),await $.delete(e,void 0,a));return}const{docJson:h,row:u,tableName:s}=c,l=t.tables[s],p=a?.hard===!0,R=!p&&l?.softDeleteMode?l.softDeleteMode.field:void 0;if(!(R&&u[R]!==null&&u[R]!==void 0)){if(X(s,"before","delete")&&await Z("before","delete",{id:e,op:"delete",previous:u,table:s}),await hn({deletedId:e,deletedReference:$=>u[$],findHolders:async($,A,D)=>(await ve($).findMany($,{includeDeleted:p,where:{[A]:D}})).page,onCascade:($,A)=>ve($).delete(A,void 0,a),onRestrict:$=>{throw new pe($,"restrict")},onSetNull:($,A,D)=>ve($).patch(A,{[D]:null}),schema:t,tableName:s}),ue(s),fe(s),R){const $={...u,[R]:M(),_id:e};Ie(i,s,r`UPDATE ${r.identifier(s)} SET ${r.identifier(H)} = ${se($)} WHERE id = ${e} AND ${r.identifier(H)} = ${h}`),Ee(s,e,$,u),be(s,e,void 0),ge(s,u,$),he(s,e,u,void 0),L?.invalidate(s,e,f(s,u,$)),ne(s,e,"update",$),d({indexKeys:f(s,u,$),key:e,op:"update",row:$,table:s}),X(s,"after","delete")&&await Z("after","delete",{id:e,op:"delete",previous:u,table:s}),await O({id:e,op:"delete",table:s});return}Ie(i,s,r`DELETE FROM ${r.identifier(s)} WHERE id = ${e} AND ${r.identifier(H)} = ${h}`),Ee(s,e,void 0),be(s,e,void 0),ge(s,u,void 0),he(s,e,u,void 0),L?.invalidate(s,e,f(s,u)),ne(s,e,"delete"),d({indexKeys:f(s,u),key:e,op:"delete",table:s}),X(s,"after","delete")&&await Z("after","delete",{id:e,op:"delete",previous:u,table:s}),await O({id:e,op:"delete",table:s})}},async deleteAll(e,n){if(!t.tables[e])throw new g("INTERNAL",`unknown table: ${e}`);const a=Math.max(1,n?.chunkSize??It),c=n?.hard===void 0?void 0:{hard:n.hard},h=ae(e)?void 0:e;let u=0;return await S(async()=>{for(;;){const s=(await B.findMany(e,{limit:a})).page.map(l=>String(l._id));if(s.length===0)break;for(const l of s)await B.delete(l,h,c),u+=1;if(s.length<a)break}}),{deleted:u}},async deleteMany(e,n,a){de(e.length,n?.limit,"deleteMany");for(const c of e)await B.delete(c,a);return{deleted:e.length}},async deleteWhere(e,n,a){const c=(await(K(e,"deleteWhere")??B).findMany(e,{where:n})).page.map(h=>String(h._id));if(de(c.length,a?.limit,"deleteWhere"),B.deleteMany===void 0)throw new g("INTERNAL",`ctx.db.${e}.deleteMany is unavailable: this writer has no batch delete`);return B.deleteMany(c,a)},async findFirst(e,n={}){return(await B.findMany(e,{...n,limit:1})).page[0]??null},async findFirstOrThrow(e,n={}){const a=await B.findFirst(e,n);if(a===null)throw new on(`findFirstOrThrow: no "${e}" document matched`);return a},async findMany(e,n={}){const a=K(e,"findMany");if(a)return N(e,U),a.findMany(e,n);const c=t.tables[e];if(!c)throw new g("INTERNAL",`unknown table: ${e}`);const h=!n.where&&!n.baseWhere;h?N(e,U):N(e);const u=an(n.orderBy),s=n.cursor?xt(u,He(n.cursor)):void 0;let l=Y(n.baseWhere,n.where);l=Y(l,le(c.softDeleteMode,n.includeDeleted)),l=await ut(l,{canPushExists:Xe?Lt:void 0,existsPushMode:Ve==="always"?"always":"auto",fetcher:Je,maxRelationKeys:Ze,relationBaseWhere:n.relationBaseWhere,schema:t,tableName:e}),s&&(l=l?{AND:[l,s]}:s);const p=Xe?Kn(N):oe,R=te(l,p);let $=r`SELECT id, _creationTime, ${r.identifier(H)} FROM ${r.identifier(e)}`;R&&($=r`${$} WHERE ${R}`),$=r`${$} ORDER BY ${Dt(u)}`;const A=typeof n.limit=="number"?Math.max(0,Math.floor(n.limit)):void 0;A!==void 0&&($=r`${$} LIMIT ${r.raw(String(A+1))}`);const D=W(i,$).toArray();h&&!b&&m?.recordRead(D.length);const F=[];for(const ee of D){const q=ce(ee);q&&(F.push(q),!h&&typeof q._id=="string"&&N(e,q._id))}if(A===void 0)return n.with&&await ft({groupedCounter:et,fetcher:Ce,parents:F,...ht(n),schema:t,tableName:e,with:n.with}),{continueCursor:null,isDone:!0,page:dt(F,n.select,n.with)};const P=F.length>A,x=P?F.slice(0,A):F,Q=x.at(-1);return n.with&&await ft({fetcher:Ce,groupedCounter:et,parents:x,...ht(n),schema:t,tableName:e,with:n.with}),{continueCursor:P&&Q?Ge(Q,u):null,isDone:!P,page:dt(x,n.select,n.with)}},async get(e,n){const a=re(e,n);if(!a){const c=n===void 0?E:void 0;return c?c.get(e):null}return N(a.tableName,e),a.row},async lookupById(e,n){const a=re(e,n);return a?(N(a.tableName,e),{row:a.row,tableName:a.tableName}):null},async groupBy(e,n){const a=K(e,"groupBy");if(a)return N(e,U),a.groupBy(e,n);const c=t.tables[e];if(!c)throw new g("INTERNAL",`unknown table: ${e}`);N(e,U);const h=n.agg??{op:"count"};if(Re(h.op),h.op!=="count"&&!h.field)throw new g("INTERNAL",`groupBy(${e}, { agg: { op: "${h.op}" } }): "field" is required for non-count reducers`);const u=le(c.softDeleteMode,void 0),s=Y(Y(n.baseWhere,n.where),u),l=await $e(s,e,n.relationBaseWhere),p=l!==s,R=[...n.by,h.field];if(c.aggregateIndexes&&!n.baseWhere&&!p&&(!u||gt(c,R))){const x=Qt(c.aggregateIndexes,h.op,h.field,n.by,n.where),Q=x===void 0?0:Object.keys(x.partial).length,ee=x?.index.by?.length??0;if(x&&(Q===0||Q===ee)){Me(e,x.index);const q=Oe(e,x.index.name),ye=Object.keys(x.partial),Ne=[];if(ye.length===(x.index.by??[]).length&&ye.length>0){const _e=De(x.index.by??[],x.partial),Te=W(i,r`SELECT ${Ae} AS value, ${We} AS count FROM ${r.identifier(q)} WHERE ${xe} = ${_e}`).toArray();return Te.length>0&&Ne.push({key:{...x.partial},value:Le(h.op,Te[0])}),Ne}const Wt=W(i,r`SELECT ${xe} AS key, ${Ae} AS value, ${We} AS count FROM ${r.identifier(q)}`).toArray();for(const _e of Wt){const Te=Ht(JSON.parse(_e.key));Ne.push({key:Te,value:Le(h.op,_e)})}return Ne}}for(const x of R){if(x===void 0)continue;const Q=x===h.field?`groupBy(${e}, { agg: { op: "${h.op}", field: "${x}" } })`:`groupBy(${e}, { by: [..."${x}"] })`;bt(c,x,Q)}const $=te(l,oe),A=n.by.map(x=>r`${J(x)} AS ${r.identifier(x)}`);if(h.op==="count")A.push(r`COUNT(*) AS value`);else{const{field:x}=h;if(x===void 0)throw new g("INTERNAL",`groupBy(${e}, { agg: { op: "${h.op}" } }): "field" is required for non-count reducers`);A.push(r`${r.raw(Re(h.op))}(${J(x)}) AS value`)}let D=r`SELECT ${r.join(A,r`, `)} FROM ${r.identifier(e)}`;$&&(D=r`${D} WHERE ${$}`),D=r`${D} GROUP BY ${r.join(n.by.map(x=>J(x)),r`, `)}`;const F=W(i,D).toArray(),P=[];for(const x of F){const Q={};for(const q of n.by)Q[q]=x[q]??null;const{value:ee}=x;P.push({key:Q,value:ee==null?null:Number(ee)})}return P},async insert(e,n,a){const c=K(e,"insert");if(c)return ze(c,e,n,a,!0);const h=t.tables[e];if(!h)throw new g("INTERNAL",`unknown table: ${e}`);const u=yt(h,n,I);qe(h,u);let s;a?.clientId!==void 0?(Dn(a.clientId),s=a.clientId):a?.allowExplicitId&&typeof u._id=="string"?s=u._id:s=G();const l=a?.allowExplicitId&&typeof u._creationTime=="number"?u._creationTime:M(),p={...u,_creationTime:l,_id:s};return X(e,"before","insert")&&await Z("before","insert",{doc:{...p},id:s,op:"insert",table:e}),ue(e),fe(e),je(i,e,r`INSERT INTO ${r.identifier(e)} (id, _creationTime, ${r.identifier(H)}) VALUES (${s}, ${l}, ${se(p)})`),nt(e,s,p),X(e,"after","insert")&&await Z("after","insert",{doc:p,id:s,op:"insert",table:e}),await O({doc:p,id:s,op:"insert",table:e}),s},async insertManyUnsafe(e,n,a){if(de(n.length,a?.limit,"insertManyUnsafe"),n.length===0)return[];const c=K(e,"insert");if(c){const s=[];for(const l of n)v(l);for(const l of n){const p=await c.insert(e,l,{allowExplicitId:a?.allowExplicitId});d({key:p,op:"insert",row:{...l,_id:p},table:e}),s.push(p)}return s}const h=t.tables[e];if(!h)throw new g("INTERNAL",`unknown table: ${e}`);ue(e),fe(e);const u=n.map(s=>{const l=yt(h,s,I),p=a?.allowExplicitId===!0&&typeof l._id=="string"?l._id:G(),R=a?.allowExplicitId===!0&&typeof l._creationTime=="number"?l._creationTime:M();return{creationTime:R,document:{...l,_creationTime:R,_id:p},id:p}});for(const s of u)v(s.document);for(let s=0;s<u.length;s+=wt){const l=r.join(u.slice(s,s+wt).map(p=>r`(${p.id}, ${p.creationTime}, ${se(p.document)})`),r`, `);je(i,e,r`INSERT INTO ${r.identifier(e)} (id, _creationTime, ${r.identifier(H)}) VALUES ${l}`)}for(const{document:s,id:l}of u)nt(e,l,s),await T({doc:s,id:l,op:"insert",table:e});return u.map(s=>s.id)},async insertMany(e,n,a){de(n.length,a?.limit,"insertMany");const c=a?.skipDuplicates===!0,h=[],u=K(e,"insert");if(u)for(const l of n)v(l);const s=async l=>u?ze(u,e,l,void 0,!1):B.insert(e,l);for(const l of n)try{h.push(await s(l))}catch(p){if(c&&p instanceof pe&&p.kind==="unique")h.push(null);else throw p}return h},normalizeId(e,n){return Et(t,e,n)},async patch(e,n,a){const c=re(e,a);if(!c){const R=a===void 0?E:void 0;if(R){v(n),await R.patch(e,n);return}throw new g("INTERNAL",`document not found: ${e}`)}const{docJson:h,row:u,tableName:s}=c,l=t.tables[s];if(!l)throw new g("INTERNAL",`unknown table: ${s}`);N(s,e),_t("patch",n);const p={...u,...n,_id:e};Nt(l,n,p,I),qe(l,p,!0),X(s,"before","update")&&await Z("before","update",{doc:{...p},id:e,op:"update",previous:u,table:s}),ue(s),fe(s),Ie(i,s,r`UPDATE ${r.identifier(s)} SET ${r.identifier(H)} = ${se(p)} WHERE id = ${e} AND ${r.identifier(H)} = ${h}`),Ee(s,e,p,u),be(s,e,p),ge(s,u,p),he(s,e,u,p),L?.invalidate(s,e,f(s,u,p)),ne(s,e,"update",p),d({indexKeys:f(s,u,p),key:e,op:"update",row:p,table:s}),X(s,"after","update")&&await Z("after","update",{doc:p,id:e,op:"update",previous:u,table:s}),await O({doc:p,id:e,op:"update",table:s})},async patchMany(e,n,a){de(e.length,n?.limit,"patchMany");for(const c of e)await B.patch(c.id,c.patch,a);return{patched:e.length}},async patchWhere(e,n,a){const c=(await(K(e,"patchWhere")??B).findMany(e,{where:n.where})).page.map(h=>({id:String(h._id),patch:n.patch}));if(de(c.length,a?.limit,"patchWhere"),B.patchMany===void 0)throw new g("INTERNAL",`ctx.db.${e}.patchMany is unavailable: this writer has no batch patch`);return await B.patchMany(c,a),{patched:c.length}},query(e){const n=K(e,"query");return n?(N(e,U),n.query(e)):nr(i,t,e,_,a=>{a?w(a):N(e,U)},a=>{b||m?.recordRead(a)})},async rank(e,n,a){const c=K(e,"rank");if(c)return N(e,U),c.rank(e,n,a);_(e,n,"rank");const h=t.tables[e];if(!h)throw new g("INTERNAL",`unknown table: ${e}`);const u=h.rankIndexes?.find(q=>q.name===n);if(!u)throw new g("INTERNAL",`unknown rankIndex "${n}" on table "${e}"`);if(rt(e,h,u),a.restrictsCounts)throw new Fe(e);N(e,U),ke(e,u);const s=typeof a.row=="string"?a.row:a.row._id;if(!s)return null;const l=ct(e,u.name),p=u.sortBy.map((q,ye)=>lt(ye)),R=p.map(q=>bn(q)).join(", "),$=W(i,r`SELECT ${r.identifier("__partition__")}, ${r.raw(R)} FROM ${r.identifier(l)} WHERE ${r.identifier("__id__")} = ${s}`).toArray(),[A]=$;if(A===void 0)return null;let D=A.__partition__;const F=Y(a.baseWhere,a.where);Be(F,t,e,"rank");const P=dn(u,F);if(P){const q=ln(u.partitionBy??[],P);if(q!==D)return null;D=q}const x=p.map(q=>A[q]),{before:Q,total:ee}=Tt(i,l,p,u.sortBy,D,x,s);return{position:Q+1,total:ee}},async rankBefore(e,n,a){if(ae(e))throw new g("INTERNAL",`rankBefore is not supported on the global (.global()) table '${e}' — cross-shard rank cursors apply only to sharded tables`);const c=t.tables[e];if(!c)throw new g("INTERNAL",`unknown table: ${e}`);const h=c.rankIndexes?.find(p=>p.name===n);if(!h)throw new g("INTERNAL",`unknown rankIndex "${n}" on table "${e}"`);if(a.restrictsCounts)throw new Fe(e);N(e,U),ke(e,h);const u=ct(e,h.name),s=h.sortBy.map((p,R)=>lt(R)),l=h.sortBy.map((p,R)=>ie(a.sortValues[R]??null));return Tt(i,u,s,h.sortBy,a.partitionKey,l,a.rowId)},async rankPage(e,n,a={}){Be(Y(a.baseWhere,a.where),t,e,"rankPage");const c=K(e,"rankPage");if(c)return N(e,U),c.rankPage(e,n,a);_(e,n,"rank");const{continueCursor:h,hasMore:u,rows:s}=at(it,e,n,a);return{continueCursor:h,isDone:!u,page:s.map(l=>l.doc)}},async rankPageRows(e,n,a={}){Be(Y(a.baseWhere,a.where),t,e,"rankPage"),_(e,n,"rank");const{directions:c,hasMore:h,rows:u}=at(it,e,n,a);return{directions:c,hasMore:h,rows:u}},async restore(e,n){const a=re(e,n);if(!a){const u=n===void 0?E:void 0;if(u?.restore){await u.restore(e);return}throw new g("INTERNAL",`document not found: ${e}`)}const c=t.tables[a.tableName]?.softDeleteMode?.field;if(!c)throw new g("INTERNAL",`ctx.db.restore: table "${a.tableName}" is not a .softDelete() table`);const h=a.row[c]!==null&&a.row[c]!==void 0;await B.patch(e,{[c]:null},n),h&&he(a.tableName,e,void 0,a.row)},async replace(e,n,a,c){const h=re(e,a);if(!h){const A=a===void 0?E:void 0;if(A){v(n),await A.replace(e,n,void 0,c);return}throw new g("INTERNAL",`document not found: ${e}`)}const{docJson:u,row:s,tableName:l}=h,p=t.tables[l];if(!p)throw new g("INTERNAL",`unknown table: ${l}`);_t("replace",n);const R=c?.allowExplicitId&&typeof n._creationTime=="number"?n._creationTime:M(),$={...n,_creationTime:R,_id:e};Nt(p,n,$,I),qe(p,$),X(l,"before","update")&&await Z("before","update",{doc:{...$},id:e,op:"update",previous:s,table:l}),ue(l),fe(l),Ie(i,l,r`UPDATE ${r.identifier(l)} SET _creationTime = ${R}, ${r.identifier(H)} = ${se($)} WHERE id = ${e} AND ${r.identifier(H)} = ${u}`),Ee(l,e,$,s),be(l,e,$),ge(l,s,$),he(l,e,s,$),L?.invalidate(l,e,f(l,s,$)),ne(l,e,"update",$),d({indexKeys:f(l,s,$),key:e,op:"update",row:$,table:l}),X(l,"after","update")&&await Z("after","update",{doc:$,id:e,op:"update",previous:s,table:l}),await O({doc:$,id:e,op:"update",table:l})},async wipeShard(e){const n=new Set(e?.exclude),a=e?.tables,c=Object.entries(t.tables).filter(([l,p])=>n.has(l)||a!==void 0&&!a.includes(l)?!1:p.shardMode?.kind!=="global").map(([l])=>l);if(a!==void 0){for(const l of a)if(!t.tables[l])throw new g("INTERNAL",`wipeShard: unknown table: ${l}`)}const h={};let u=0;const{deleteAll:s}=B;if(s===void 0)throw new g("INTERNAL","wipeShard: this writer has no deleteAll");for(const l of c){const p=await s(l,{...e?.chunkSize===void 0?{}:{chunkSize:e.chunkSize},hard:!0});h[l]=p.deleted,u+=p.deleted}return{deleted:u,tables:h}}},Ft={db:B,scheduler:j};return o.enforceRls===!0?pn(B,t,(e,n)=>re(e,n)?.tableName,(e,n)=>Ot(e,n)):B};export{Ur as CDC_LOG_TABLE,Jr as CLIENT_WATERMARK_TABLE,to as GLOBAL_SHAPE_SNAPSHOT_TABLE,lo as IDEMPOTENCY_TABLE,Zn as NotUniqueError,$o as SEARCH_STATE_TABLE,Vr as advanceClientWatermark,Pr as applyCdcChanges,Dn as assertValidClientId,Fr as backfillAggregateIndexes,Wr as backfillRankIndexes,Br as backfillSearchIndexes,Hr as bumpCdcEpoch,Dr as createShardCtxDb,no as deleteGlobalShapeSnapshot,ro as deleteGlobalShapeSnapshotsForConnection,Xr as migrateClientWatermark,oo as migrateGlobalShapeSnapshot,Gr as minCdcSeq,Et as normalizeIdStructurally,jr as readCdcChanges,Qr as readCdcCursor,Kr as readCdcEpoch,Zr as readClientWatermark,io as readGlobalShapeSnapshot,co as readIdempotent,mo as runShardMigrations,go as selectShapeMemberIds,bo as selectShapeRows,Yr as trimCdcChanges,uo as trimIdempotent,ao as writeGlobalShapeSnapshot,fo as writeIdempotent};
|
|
1
|
+
import{LunoraError as g}from"@lunora/errors";import{n as Bt,S as qt,x as Qe,T as Se,y as Ut,c as Pt}from"./ctx-db-companions-BJlCofon.mjs";import{sql as r}from"drizzle-orm";import{s as Ht}from"./wire-codec-Dh0j-GnY.mjs";import{aggregateSqlFunction as Re,normalizeCountArgument as Gt,throwingScheduler as jt}from"./AGGREGATE_SQL_FUNCTION-CTo0-9iZ.mjs";import{encodeAggregateKey as De,readAggregateValue as Le,aggregateTableName as Oe}from"./aggregateTableName-DN7gk6uh.mjs";import{mergeWhere as Y,CountRlsUnsupportedError as Fe,selectIndexForGroupBy as Qt,selectIndexForCount as Kt,selectIndexForAggregate as Yt}from"./CountRlsUnsupportedError-8BqPYQoP.mjs";import{backfillSearchIndexesForTable as zt}from"./backfillAggregateIndexes-DTOIsYbi.mjs";import{backfillAggregateIndexes as Fr,backfillRankIndexes as Wr,backfillSearchIndexes as Br}from"./backfillAggregateIndexes-DTOIsYbi.mjs";import{appendCdcChange as Jt}from"./CDC_LOG_TABLE-DNFFQwF_.mjs";import{CDC_LOG_TABLE as Ur,applyCdcChanges as Pr,bumpCdcEpoch as Hr,minCdcSeq as Gr,readCdcChanges as jr,readCdcCursor as Qr,readCdcEpoch as Kr,trimCdcChanges as Yr}from"./CDC_LOG_TABLE-DNFFQwF_.mjs";import{computeRankPage as at}from"./computeRankPage-BU8LXvQs.mjs";import{SCAN_DEP as U}from"./SCAN_DEP-D_yR9EeV.mjs";import{runDrizzle as W}from"./runDrizzle-C3n5gJsk.mjs";import{a as H,L as se,p as Ae,T as We,c as xe,N as J,E as ce,I as St,C as Vt,D as Rt,h as Xt,O as st}from"./do-sql-DKSFK627.mjs";import{WORKERD_SQLITE_LIMITS as At,unionAll as Pe,sqliteInList as Zt}from"./param-CYxL68V-.mjs";import{coveringGeohashes as en,boundingBoxGeohashes as tn,pointInBoundingBox as nn,haversineMeters as rn}from"./GEO_DEFAULT_PRECISION-DyI5zggj.mjs";import{NotFoundError as on}from"./NotFoundError-BhF7FeFr.mjs";import{normalizeOrderKeys as an,buildSeekWhere as xt,decodeCursor as He,applySelect as dt,encodeCursor as Ge,softDeleteScope as le,buildSeekBeforeWhere as sn}from"./applySelect-5w13bMAR.mjs";import{sortColumnName as lt,resolveRankPartition as dn,encodePartitionKey as ln,RANK_TIEBREAK as cn,rankTableName as ct}from"./RANK_TIEBREAK-BGk411OR.mjs";import{indexKeysForRow as un,buildIndexRange as fn}from"./buildIndexRange-DFsdtPjD.mjs";import{assertFlatPredicate as Be,resolveRelationPredicates as ut}from"./DEFAULT_MAX_RELATION_KEYS-BV1RCoat.mjs";import{runRowValidators as qe,resolveWith as ft,relationHooks as ht,applyOnDelete as hn,fanOutScalarCounts as mn}from"./applyOnDelete-crbAzVfE.mjs";import{guardWriter as pn}from"./RLS_UNWRAP_SYMBOL-DcqORh2s.mjs";import{f as $n}from"./sql-projection-jfoe331H.mjs";import{createSystemReader as wn}from"./createSystemReader-DcDcrtM3.mjs";import{ConflictError as pe}from"./ConflictError-C8GtJmjS.mjs";import{runTriggers as gn}from"./hasTrigger-CbkOHExZ.mjs";import{compileWhereSql as te}from"./compileWhereSql-B3hq_v98.mjs";import{CLIENT_WATERMARK_TABLE as Jr,advanceClientWatermark as Vr,migrateClientWatermark as Xr,readClientWatermark as Zr}from"./CLIENT_WATERMARK_TABLE-LrKfdxyt.mjs";import{GLOBAL_SHAPE_SNAPSHOT_TABLE as to,deleteGlobalShapeSnapshot as no,deleteGlobalShapeSnapshotsForConnection as ro,migrateGlobalShapeSnapshot as oo,readGlobalShapeSnapshot as io,writeGlobalShapeSnapshot as ao}from"./GLOBAL_SHAPE_SNAPSHOT_TABLE-B2LKe4KU.mjs";import{IDEMPOTENCY_TABLE as lo,readIdempotent as co,trimIdempotent as uo,writeIdempotent as fo}from"./IDEMPOTENCY_TABLE-tQ5mnqvw.mjs";import{runShardMigrations as mo}from"./runShardMigrations-BCuK60KT.mjs";import{SEARCH_STATE_TABLE as $o}from"./SEARCH_STATE_TABLE-DRk_SB72.mjs";import{selectShapeMemberIds as go,selectShapeRows as bo}from"./selectShapeMemberIds-Bkkug6vU.mjs";import{serializeSqlValue as ie}from"./serializeSqlValue-BR4UOWoP.mjs";import{quoteIdentifier as bn}from"./quoteIdentifier-CObIFRhb.mjs";const En=o=>{const i=new TextEncoder().encode(o);let t="";for(const d of i)t+=String.fromCodePoint(d);return btoa(t)},yn=o=>{const i=atob(o),t=Uint8Array.from(i,d=>d.codePointAt(0)??0);return new TextDecoder().decode(t)},Nn=()=>new g("BAD_REQUEST","invalid cursor"),mt=16,pt=8,V=1024,Ke=(o,i)=>i.query(o),_n=(o,i,t)=>{const d=Bt(o,t);if(d.length===0)return 0;let f=0;for(const[m,b]of i.entries()){const S=m===i.length-1;let y=0;for(const w of d)(S?w.startsWith(b):w===b)&&(y+=1);if(y===0)return 0;f+=y}return f},Tn=(o,i)=>{if(!i)return{exact:!0,lower:o,upper:o};const t=[...o].at(-1)??"",d=(t.codePointAt(0)??0)+1;if(d>=55296&&d<=57343||d>1114111)return{exact:!0,lower:o,upper:o};const f=o.slice(0,o.length-t.length);return{exact:!1,lower:o,upper:f+String.fromCodePoint(d)}},Sn=(o,i,t)=>{const d={eq:(f,m)=>{if(!o.definition.filterFields?.includes(f))throw new g("INTERNAL",`field "${f}" is not a filter field of search index "${o.indexName}" on table "${i}"`);if(o.filters.length>=pt)throw new g("BAD_REQUEST",`search index "${o.indexName}" on table "${i}": at most ${String(pt)} .eq() filters are supported per search query`);return o.filters.push({field:f,value:m}),d},search:(f,m)=>{const b=o;if(f!==b.definition.field)throw new g("INTERNAL",`search index "${b.indexName}" on table "${i}" indexes "${b.definition.field}", not "${f}"`);const S=Ke(m,t).length;if(S>mt)throw new g("BAD_REQUEST",`search index "${b.indexName}" on table "${i}": at most ${String(mt)} search terms are supported (got ${String(S)})`);return b.field=f,b.query=m,b.hasQuery=!0,d}};return d},Rn=o=>{if(o.length>V)throw new g("BAD_REQUEST",`more than ${String(V)} documents match this search — narrow it with filters or read it a page at a time with .paginate()`)},An=o=>Math.min(o.offset+o.numItems+1,V),xn=o=>En(`search:${String(o)}`),In=o=>{let i;try{i=yn(o)}catch{return}if(!i.startsWith("search:"))return;const t=Number(i.slice(7));return Number.isInteger(t)&&t>=0?t:void 0},vn=o=>{if(typeof o.endCursor=="string")throw new g("BAD_REQUEST","bounded (endCursor) pagination is not supported on search queries — relevance order has no stable range boundary");const i=Math.max(0,Math.floor(o.numItems)),t=o.cursor?In(o.cursor):0;if(t===void 0)throw Nn();if(t+i>V)throw new g("BAD_REQUEST",`search pagination reaches past the ${String(V)}-document limit (offset ${String(t)} + ${String(i)} requested) — narrow the query or the filters instead`);return{numItems:i,offset:t}},Cn=(o,i)=>{const t=i.offset+i.numItems,d=i.numItems>0&&o.length>t;return{continueCursor:d?xn(t):null,isDone:!d,page:o.slice(i.offset,t)}},Mn=o=>{if(o===void 0)return V+1;if(!Number.isFinite(o))return V;const i=Math.max(0,Math.floor(o));if(i>V)throw new g("BAD_REQUEST",`search returns at most ${String(V)} documents (asked for ${String(i)}) — narrow the query or paginate instead`);return i},kn=/^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/iu,Dn=o=>{if(!kn.test(o))throw new g("INTERNAL",`invalid clientId ${JSON.stringify(o)}: a client-supplied row id must be a UUID`)},$t=50,It=500,wt=Math.floor(At.boundParams/3),me=At.boundParams,Ln=128,de=(o,i,t)=>{const d=i??It;if(o>d)throw new g("BATCH_LIMIT_EXCEEDED",`${t}: batch of ${String(o)} exceeds the limit of ${String(d)} (raise options.limit or chunk the call)`,{status:400})},On=o=>{const i={eq:(t,d)=>(o.sqlConditions.push({comparator:"=",field:t,value:d}),i),gt:(t,d)=>(o.sqlConditions.push({comparator:">",field:t,value:d}),i),gte:(t,d)=>(o.sqlConditions.push({comparator:">=",field:t,value:d}),i),lt:(t,d)=>(o.sqlConditions.push({comparator:"<",field:t,value:d}),i),lte:(t,d)=>(o.sqlConditions.push({comparator:"<=",field:t,value:d}),i)};return i},Fn=o=>Math.max(o,V),vt=(o,i)=>{const t=o.filters.map(d=>r`${J(d.field)} = ${ie(d.value)}`);return i&&t.push(i),t},Wn=(o,i,t,d,f)=>{const m=Ke(t.query,Qe(t.definition.language));if(m.length===0)return[];const b=Pt(i,t.indexName),S=`${b}__vocab`,y=m.length-1,w=m.map((L,M)=>{const G=Tn(L,M===y),j=G.exact?r`${r.identifier("term")} = ${G.lower}`:r`${r.identifier("term")} >= ${G.lower} AND ${r.identifier("term")} < ${G.upper}`;return r`SELECT ${r.identifier("doc")}, ${r.raw(String(M))} AS ${r.identifier("__term__")}, COUNT(*) AS ${r.identifier("__n__")} FROM ${r.identifier(S)} WHERE ${j} GROUP BY ${r.identifier("doc")}`}),N=m.map((L,M)=>r`SUM(CASE WHEN u.${r.identifier("__term__")} = ${r.raw(String(M))} THEN u.${r.identifier("__n__")} ELSE 0 END)`),_=r`SELECT f.${r.identifier(Se)} AS ${r.identifier(Se)}, ${r.join(N,r` + `)} AS ${r.identifier("__score__")} FROM (${Pe(w)}) u JOIN ${r.identifier(b)} f ON f.rowid = u.${r.identifier("doc")} GROUP BY f.${r.identifier(Se)} HAVING ${r.join(N.map(L=>r`${L} > 0`),r` AND `)}`,T=vt(t,f);let v=r`SELECT m.id, m._creationTime, m.${r.identifier(H)}, s.${r.identifier("__score__")} AS ${r.identifier("__score__")} FROM (${_}) s JOIN ${r.identifier(i)} m ON m.id = s.${r.identifier(Se)}`;T.length>0&&(v=r`${v} WHERE ${r.join(T,r` AND `)}`),v=r`${v} ORDER BY s.${r.identifier("__score__")} DESC, m._creationTime DESC, m.id ASC LIMIT ${r.raw(String(d))}`;const O=[];for(const L of W(o,v)){const M=Rt(L);if(M){const G=L.__score__;O.push({document:M,score:typeof G=="number"?G:Number(G??0)})}}return O},Bn=(o,i,t,d,f)=>{const m=Qe(t.definition.language),b=Ke(t.query,m);if(b.length===0)return[];const S=vt(t,f);let y=r`SELECT id, _creationTime, ${r.identifier(H)} FROM ${r.identifier(i)}`;S.length>0&&(y=r`${y} WHERE ${r.join(S,r` AND `)}`),y=r`${y} ORDER BY _creationTime DESC, id ASC LIMIT ${r.raw(String(Fn(d)))}`;const w=W(o,y).toArray(),N=[];for(const _ of w){const T=Rt(_);if(!T)continue;const v=_n(Ut(T,t.definition),b,m);v>0&&N.push({creationTime:typeof T._creationTime=="number"?T._creationTime:0,doc:T,id:typeof T._id=="string"?T._id:"",score:v})}return N.sort((_,T)=>T.score-_.score||T.creationTime-_.creationTime||_.id.localeCompare(T.id)),N.slice(0,d).map(_=>({document:_.doc,score:_.score}))},Ue=(o,i,t,d)=>{if(!Number.isFinite(o.lat)||o.lat<-90||o.lat>90||!Number.isFinite(o.lng)||o.lng<-180||o.lng>180)throw new g("BAD_REQUEST",`geo index "${d}" on table "${t}": ${i} must have a finite lat in [-90, 90] and lng in [-180, 180]`)},qn=(o,i)=>{const t=o,d={near:(f,m)=>{if(t.within)throw new g("INTERNAL",`geo index "${t.indexName}" on table "${i}": call .near() or .within(), not both`);if(Ue(f,".near() point",i,t.indexName),!Number.isFinite(m)||m<=0)throw new g("BAD_REQUEST",`geo index "${t.indexName}" on table "${i}": .near() radiusMeters must be a finite number > 0, got ${String(m)}`);return t.near={point:{lat:f.lat,lng:f.lng},radiusMeters:m},d},within:f=>{if(t.near)throw new g("INTERNAL",`geo index "${t.indexName}" on table "${i}": call .near() or .within(), not both`);if(Ue(f.sw,".within() sw corner",i,t.indexName),Ue(f.ne,".within() ne corner",i,t.indexName),f.sw.lat>f.ne.lat)throw new g("BAD_REQUEST",`geo index "${t.indexName}" on table "${i}": .within() corners are transposed (sw.lat > ne.lat)`);if(f.sw.lng>f.ne.lng)throw new g("BAD_REQUEST",`geo index "${t.indexName}" on table "${i}": .within() box crosses the antimeridian (sw.lng > ne.lng), which is not supported — split it into two boxes at ±180 and union the results`);return t.within={ne:{lat:f.ne.lat,lng:f.ne.lng},sw:{lat:f.sw.lat,lng:f.sw.lng}},d}};return d},Un=(o,i)=>{const t=o[i];if(t===null||typeof t!="object")return;const{lat:d,lng:f}=t;return typeof d=="number"&&typeof f=="number"?{lat:d,lng:f}:void 0},Pn=(o,i)=>{const t=Un(o,i.definition.field);if(!t)return;const d=typeof o._creationTime=="number"?o._creationTime:0;if(i.near){const f=rn(i.near.point,t);return f<=i.near.radiusMeters?{creationTime:d,distance:f}:void 0}return nn(t,i.within)?{creationTime:d,distance:0}:void 0},Hn=(o,i,t,d)=>{if(!t.near&&!t.within)throw new g("INTERNAL",`geo index "${t.indexName}" on table "${i}": call .near(point, radius) or .within(box)`);const f=t.near?en(t.near.point,t.near.radiusMeters):tn(t.within),m=Xt(i,t.indexName),b=f.map(_=>r`(g.${r.identifier("__geohash__")} >= ${_} AND g.${r.identifier("__geohash__")} < ${`${_}{`})`),S=[r`(${r.join(b,r` OR `)})`];d&&S.push(d);const y=r`SELECT m.id, m._creationTime, m.${r.identifier(H)} FROM ${r.identifier(m)} g JOIN ${r.identifier(i)} m ON m.id = g.${r.identifier("__id__")} WHERE ${r.join(S,r` AND `)}`,w=W(o,y).toArray(),N=[];for(const _ of w){const T=ce(_),v=T?Pn(T,t):void 0;T&&v&&N.push({creationTime:v.creationTime,distance:v.distance,doc:T})}return N.sort((_,T)=>_.distance-T.distance||T.creationTime-_.creationTime),N},Ct=(o,i,t,d)=>{const f=[];for(const m of o)if(i.every(b=>b(d(m)))&&(f.push(m),typeof t=="number"&&f.length>=t))break;return f},Gn=(o,i,t,d,f,m=()=>{})=>{const b=t.within!==void 0,S=Hn(o,i,t,f).map(y=>({distanceMeters:b?null:y.distance,document:y.doc}));return m(S.length),typeof d=="number"?S.slice(0,Math.max(0,Math.floor(d))):S},Mt=(o,i,t,d,f,m=()=>{})=>{const{geo:b}=t;if(!b)throw new g("INTERNAL","runGeoTerminalScored called without a staged geo query");const S=t.inMemoryFilters.length>0,y=Gn(o,i,b,S?void 0:f,d,m);return S?Ct(y,t.inMemoryFilters,f,w=>w.document):y},jn=(o,i,t,d,f,m=()=>{})=>Mt(o,i,t,d,f,m).map(b=>b.document),Qn=(o,i,t,d,f,m,b=()=>{})=>{const S=[];for(const _ of t.sqlConditions)S.push(r`${J(_.field)} ${r.raw(_.comparator)} ${ie(_.value)}`);d&&S.push(d);let y=r`SELECT id, _creationTime, ${r.identifier(H)} FROM ${r.identifier(i)}`;S.length>0&&(y=r`${y} WHERE ${r.join(S,r` AND `)}`),y=r`${y} ORDER BY ${f}`,typeof m=="number"&&t.inMemoryFilters.length===0&&(y=r`${y} LIMIT ${r.raw(String(Math.max(0,Math.floor(m))))}`);const w=W(o,y).toArray();b(w.length);const N=[];for(const _ of w){const T=ce(_);if(T&&t.inMemoryFilters.every(v=>v(T))&&(N.push(T),typeof m=="number"&&N.length>=m))break}return N},oe={fieldRef:J,serialize:ie},kt=(o,i)=>{const t=i===void 0?void 0:o.shape[i];return t!==void 0&&$n(t)},gt=(o,i)=>i.some(t=>kt(o,t)),bt=(o,i,t)=>{if(kt(o,i))throw new g("BAD_REQUEST",`${t}: "${i}" is stored as an order-preserving key, which SQL cannot reduce or group — declare an aggregateIndex covering this (by, field, op) so the maintained companion answers it`)},Kn=o=>{let i=0;const t=[],d={fieldRef:J,relationExists:f=>{const{childWhere:m,negated:b,parentTable:S,relation:y}=f,w=`__rel_${String(i)}`,N=t.at(-1)??S;i+=1,o(y.table,U);const _=y.kind==="one"?y.field:y.references,T=y.kind==="one"?y.references:y.field,v=r`${st(w,T)} = ${st(N,_)}`;t.push(w);const O=te(m,d);t.pop();const L=O?r`${v} AND ${O}`:v,M=r`EXISTS (SELECT 1 FROM ${r.identifier(y.table)} AS ${r.identifier(w)} WHERE ${L})`;return b?r`NOT ${M}`:M},serialize:ie};return d},Dt=o=>{const i=o.map(t=>r`${J(t.field)} ${r.raw(t.direction==="desc"?"DESC":"ASC")}`);return o.some(t=>t.field==="_id"||t.field==="id")||i.push(r`${J("id")} ASC`),r.join(i,r`, `)},Yn={"<":"lt","<=":"lte","=":"eq",">":"gt",">=":"gte"},zn=o=>{const i=o.order;return o.indexFields.length>0?o.indexFields.map(t=>({direction:i,field:t})):[{direction:i,field:"_creationTime"}]},Jn=(o,i,t,d)=>{const f=o.sqlConditions.map(m=>({[m.field]:{[Yn[m.comparator]??"eq"]:m.value}}));if(t&&f.push(xt(i,He(t))),d&&f.push(sn(i,He(d))),f.length!==0)return f.length===1?f[0]:{AND:f}},Vn=(o,i,t)=>{const d=[];for(const f of o){const m=ce(f);if(m&&i.every(b=>b(m))&&(d.push(m),t!==void 0&&d.length>t))break}return d},Xn=(o,i,t,d,f,m=()=>{})=>{const b=Math.max(0,Math.floor(d.numItems)),S=zn(t),y=typeof d.endCursor=="string",w=te(Jn(t,S,d.cursor,d.endCursor),oe),N=f&&w?r`${w} AND ${f}`:f??w;let _=r`SELECT id, _creationTime, ${r.identifier(H)} FROM ${r.identifier(i)}`;N&&(_=r`${_} WHERE ${N}`),_=r`${_} ORDER BY ${Dt(S)}`;const T=t.inMemoryFilters.length>0;!T&&!y&&(_=r`${_} LIMIT ${r.raw(String(b+1))}`);const v=W(o,_).toArray();m(v.length);const O=Vn(v,t.inMemoryFilters,T||y?void 0:b);if(y){const j=O.length>=2?O[Math.floor(O.length/2)-1]:void 0;return{continueCursor:d.endCursor??null,isDone:!0,page:O,splitCursor:j?Ge(j,S):null}}const L=O.length>b,M=L?O.slice(0,b):O,G=M.at(-1);return{continueCursor:L&&G?Ge(G,S):null,isDone:!L,page:M}};class Zn extends g{constructor(i="unique() found more than one matching document"){super("NOT_UNIQUE",i,{name:"NotUniqueError"})}}const er=/\s/u,tr=String.fromCodePoint(0),Et=(o,i,t)=>{if(!o.tables[i])throw new g("INTERNAL",`unknown table: ${i}`);return typeof t!="string"||t.length===0||er.test(t)||t.includes(tr)?null:t},nr=(o,i,t,d=()=>{},f=()=>{},m=()=>{})=>{const b=i.tables[t];if(!b)throw new g("INTERNAL",`unknown table: ${t}`);const S=le(b.softDeleteMode,void 0),y=S?te(S,oe):void 0,w={indexFields:[],indexName:void 0,inMemoryFilters:[],order:"asc",sqlConditions:[]};let N=0;const _=E=>{const{search:I}=w;if(!I)throw new g("INTERNAL","runSearchFetch called without a staged search");zt(o,t,b);const C=w.inMemoryFilters.length>0,k=Mn(C?void 0:E),z=Vt(o)?Wn(o,t,I,k,y):Bn(o,t,I,k,y);return C?(N=z.length,Ct(z,w.inMemoryFilters,E,ne=>ne.document)):(E===void 0&&Rn(z),z)},T=E=>_(E).map(I=>I.document),v=E=>{const I=vn(E);return Cn(T(An(I)),I)},O=()=>{const E=w.indexFields.length>0?w.indexFields:["_creationTime"],I=w.order==="desc"?"DESC":"ASC";return r.join(E.map(C=>r`${J(C)} ${r.raw(I)}`),r`, `)},L=()=>{if(w.search||w.geo||w.indexName===void 0){f(void 0);return}f(fn(t,w.indexName,w.indexFields,w.sqlConditions,ie))},M=E=>{L();let I=0;const C=(()=>{if(w.search){const k=T(E);return I=N,k}return w.geo?jn(o,t,w,y,E,k=>{I=k}):Qn(o,t,w,y,O(),E,k=>{I=k})})();return m(Math.max(I,C.length)),C},G=()=>{if(!w.search&&!w.geo)throw new g("INTERNAL",`ctx.db.query("${t}").collectWithScores() requires a staged .withSearchIndex(...) or .withGeoIndex(...)`);L();let E=0;const I=(()=>{if(w.search){const C=_(void 0);return E=N,C}return Mt(o,t,w,y,void 0,C=>{E=C})})();return m(Math.max(E,I.length)),I},j={async*[Symbol.asyncIterator](){const E=[...w.inMemoryFilters];let I;w.inMemoryFilters=[];try{for(;;){const C=await j.paginate({cursor:I??null,numItems:Ln});for(const k of C.page)E.every(z=>z(k))&&(yield k);if(C.isDone||C.continueCursor===null)return;I=C.continueCursor}}finally{w.inMemoryFilters=E}},async collect(){return M(void 0)},async collectWithScores(){return G()},filter(E){return w.inMemoryFilters.push(E),j},async first(){return M(w.inMemoryFilters.length>0?void 0:1)[0]??null},order(E){return w.order=E==="desc"?"desc":"asc",j},async paginate(E){let I=0;if(L(),w.search){const k=v(E);return m(k.page.length),k}if(w.geo)throw new g("INTERNAL","pagination is not supported on geo queries; use .take(n) or .collect()");const C=Xn(o,t,w,E,y,k=>{I=k});return m(Math.max(I,C.page.length)),C},async take(E){return M(E)},async unique(){const E=M(w.inMemoryFilters.length>0?void 0:2);if(E.length>1)throw new Zn(`unique() on table "${t}" matched ${String(E.length)} documents; expected at most one`);return E[0]??null},withGeoIndex(E,I){const C=(b.geoIndexes??[]).find(z=>z.name===E);if(!C)throw new g("INTERNAL",`unknown geo index "${E}" on table "${t}"`);d(t,E,"geo");const k={definition:C,indexName:E};if(w.geo=k,I(qn(k,t)),!k.near&&!k.within)throw new g("INTERNAL",`geo index "${E}" on table "${t}" requires a .near(point, radius) or .within(box) call`);return j},withIndex(E,I){const C=b.indexes.find(k=>k.name===E);if(!C)throw new g("INTERNAL",`unknown index "${E}" on table "${t}"`);return d(t,E,"index"),w.indexName=E,w.indexFields=C.fields,I&&I(On(w)),j},withSearchIndex(E,I){const C=(b.searchIndexes??[]).find(z=>z.name===E);if(!C)throw new g("INTERNAL",`unknown search index "${E}" on table "${t}"`);d(t,E,"search");const k={definition:C,field:C.field,filters:[],hasQuery:!1,indexName:E,query:""};if(w.search=k,I(Sn(k,t,Qe(C.language))),!k.hasQuery)throw new g("INTERNAL",`search index "${E}" on table "${t}" requires a .search(field, query) call`);return j}};return j},yt=(o,i,t)=>{const d={...i};for(const[f,m]of St(o)){if(m.serverDefault){d[f]=m.serverDefault({auth:t});continue}d[f]===void 0&&(m.defaultFn?d[f]=m.defaultFn():"defaultValue"in m&&(d[f]=m.defaultValue))}return d},Nt=(o,i,t,d)=>{const f=t;for(const[m,b]of St(o)){if(b.serverDefault){m in i&&(f[m]=b.serverDefault({auth:d}));continue}b.onUpdateFn&&!(m in i)&&(f[m]=b.onUpdateFn())}},_t=(o,i)=>{for(const t of Object.keys(i))if(i[t]===void 0)throw new g("INTERNAL",`Cannot ${o} field '${t}' to undefined — use null to clear a nullable field, or omit the key to leave it unchanged.`)},rr=/unique constraint failed/i,or=o=>o instanceof Error&&rr.test(o.message),je=(o,i,t)=>{try{W(o,t)}catch(d){throw or(d)?new pe(`unique constraint violation on "${i}"`,"unique"):d}},Ie=(o,i,t)=>{if(je(o,i,t),W(o,r`SELECT changes() AS changed`).one().changed===0)throw new pe(`optimistic concurrency conflict on "${i}" — the row changed during this mutation; refetch and retry`,"occ")},Tt=(o,i,t,d,f,m,b)=>{const S=[];for(let _=0;_<t.length+1;_+=1){const T=[];for(let M=0;M<_;M+=1)T.push(r`${r.identifier(t[M])} IS ${m[M]}`);const v=t[_],O=d[_];if(v!==void 0&&O!==void 0){const M=O.direction==="desc"?">":"<";T.push(r`${r.identifier(v)} ${r.raw(M)} ${m[_]}`)}else T.push(r`${r.identifier(cn)} < ${b}`);const[L]=T;S.push(T.length===1&&L!==void 0?L:r`(${r.join(T,r` AND `)})`)}const y=r.join(S,r` OR `),w=W(o,r`SELECT COUNT(*) AS c FROM ${r.identifier(i)} WHERE ${r.identifier("__partition__")} = ${f} AND (${y})`).one(),N=W(o,r`SELECT COUNT(*) AS c FROM ${r.identifier(i)} WHERE ${r.identifier("__partition__")} = ${f}`).one();return{before:w.c,total:N.c}},Dr=o=>{const{sql:i}=o,{schema:t}=o,d=o.broadcast??(()=>{}),f=(e,...n)=>{const a=t.tables[e]?.indexes;if(!a||a.length===0)return;const c=[];for(const h of n)h&&c.push(...un(a,h,ie));return c.length>0?c:void 0},{headroom:m}=o;let b=!1;const S=async e=>{const n=b;b=!0;try{return await e()}finally{b=n}},y=o.onRead??(()=>{}),w=o.onReadRange??(e=>{y(e.table,U)}),N=(e,n)=>{n!==void 0&&n!==U&&!b&&m?.recordRead(1),y(e,n)},_=o.onIndexUse??(()=>{}),T=o.onWrite??(()=>{}),v=e=>{b||m?.recordWrite(e)},O=async e=>{v(e.doc),await T(e)},{cache:L}=o,M=o.clock??(()=>Date.now()),G=o.idGenerator??(()=>crypto.randomUUID()),j=o.scheduler??jt,{globalDb:E}=o,I=o.auth??{identity:null,userId:null},C=o.cdc??!1,k=j,z=wn({scheduler:typeof k.list=="function"&&typeof k.get=="function"?k:void 0,storage:o.storage}),ne=(e,n,a,c)=>{C&&Jt(i,M(),e,n,a,c)},ae=e=>t.tables[e]?.shardMode?.kind==="global",Ye=(e,n)=>{if(ae(e)){if(!E)throw new g("INTERNAL",`cross-backend ${n} for global table '${e}' requires a globalDb writer — pass one to createShardCtxDb({ globalDb })`);return E}return B},ve=e=>Ye(e,"cascade"),K=(e,n)=>{if(ae(e)){if(!E)throw new g("INTERNAL",`${n} on global table '${e}' requires a globalDb writer — pass one to createShardCtxDb({ globalDb })`);return E}},ze=async(e,n,a,c,h)=>{h&&v(a);const u=await e.insert(n,a,c);return d({key:u,op:"insert",row:{...a,_id:u},table:n}),u},Ce=(e,n)=>Ye(e,"relation load").findMany(e,n),Je=(e,n)=>(ae(e)&&N(e,U),Ce(e,n)),Lt=e=>!ae(e.table),Ve=o.relationExistsPushDown??"auto",Xe=Ve!=="never",{maxRelationKeys:Ze}=o,$e=(e,n,a)=>ut(e,{fetcher:Je,maxRelationKeys:Ze,relationBaseWhere:a,schema:t,tableName:n}),et=async(e,n,a,c)=>{const h=K(e,"relation grouped count");if(h)return N(e,U),mn((P,x)=>h.count(P,x),e,n,a,c);const u=t.tables[e];if(!u)throw new g("INTERNAL",`unknown table: ${e}`);N(e,U);const s=le(u.softDeleteMode,void 0),l={[n]:{in:a}},p=Y(Y(l,c),s),R=await $e(p,e,void 0),$=te(R,oe),A=J(n);let D=r`SELECT ${A} AS __fk__, COUNT(*) AS count FROM ${r.identifier(e)}`;$&&(D=r`${D} WHERE ${$}`),D=r`${D} GROUP BY ${A}`;const F=W(i,D).toArray();return new Map(F.map(P=>[P.__fk__,P.count]))};let we=0;const tt=new Set;for(const[e,n]of Object.entries(t.tables))for(const a of Object.values(n.triggerMap??{}))tt.add(`${e} ${a.timing} ${a.op}`);const X=(e,n,a)=>tt.has(`${e} ${n} ${a}`),Z=async(e,n,a)=>{if(we+=1,we>$t)throw we-=1,new pe(`trigger recursion exceeded ${String($t)} levels on "${a.table}" — check for a self-triggering write`,"trigger");try{await gn({ctx:Ft,event:a,op:n,schema:t,tableName:a.table,timing:e})}finally{we-=1}},{ensureBackfilledForTable:ue,ensureBackfilledIndex:Me,ensureRankBackfilled:ke,ensureRankBackfilledForTable:fe,syncAggregates:ge,syncCompanionsForInsert:nt,syncGeo:be,syncRanks:he,syncSearch:Ee}=qt({broadcast:d,indexKeysFor:(e,n)=>f(e,n),invalidateCache:(e,n,a)=>L?.invalidate(e,n,f(e,a)),recordCdc:ne,schema:t,sql:i}),rt=(e,n,a)=>{const{shardMode:c}=n;if(c?.kind==="shardBy"&&!(c.field!==void 0&&(a.partitionBy??[]).includes(c.field)))throw Object.assign(new Error(`rank index "${a.name}" on "${e}" partitions across shards (shard key "${c.field??"?"}" is not in partitionBy) — a shard-local rank()/rankPage() would be wrong; roll it up through the Query Coordinator instead`),{code:"CROSS_SHARD_RANK_UNSUPPORTED",name:"LunoraError",status:400})},ot=e=>Object.entries(t.tables).filter(([,n])=>n.shardMode?.kind!=="global").map(([n])=>n).filter(n=>e===void 0||n===e),re=(e,n)=>{const a=ot(n);for(let c=0;c<a.length;c+=me){const h=a.slice(c,c+me).map(R=>r`SELECT ${r.raw(`'${R.replaceAll("'","''")}'`)} AS __t__, id, _creationTime, ${r.identifier(H)} FROM ${r.identifier(R)} WHERE id = ${e}`),[u]=W(i,r`${Pe(h)} LIMIT 1`).toArray();if(!u)continue;const s=u.__t__,l=ce(u);if(typeof s!="string"||!l)return;const p=u[H];return{docJson:typeof p=="string"?p:se(p??{}),row:l,tableName:s}}},Ot=(e,n)=>{const a=[...new Set(e)],c=new Map;if(a.length===0)return c;const h=ot(n);for(let u=0;u<h.length;u+=me){const s=h.slice(u,u+me),l=Math.floor(me/s.length),p=Zt(r`${r.identifier("id")}`,a,!1,l),R=s.map($=>r`SELECT ${r.raw(`'${$.replaceAll("'","''")}'`)} AS __t__, id FROM ${r.identifier($)} WHERE ${p}`);for(const $ of W(i,Pe(R))){const{id:A,__t__:D}=$;typeof D=="string"&&typeof A=="string"&&c.set(A,D)}}return c},it={assertRankPartitionLocal:rt,ensureRankBackfilled:ke,onRead:N,rowToDocument:ce,schema:t,sql:i},B={system:z,async aggregate(e,n){const a=K(e,"aggregate");if(a)return N(e,U),a.aggregate(e,n);const c=t.tables[e];if(!c)throw new g("INTERNAL",`unknown table: ${e}`);if(Re(n.op),n.op==="count")return B.count(e,{baseWhere:n.baseWhere,relationBaseWhere:n.relationBaseWhere,restrictsCounts:n.restrictsCounts,where:n.where});if(!n.field)throw new g("INTERNAL",`aggregate(${e}, { op: "${n.op}" }): "field" is required for non-count reducers`);N(e,U);const h=le(c.softDeleteMode,void 0),u=Y(Y(n.baseWhere,n.where),h),s=await $e(u,e,n.relationBaseWhere),l=s!==u;if(c.aggregateIndexes&&!n.baseWhere&&!l&&(!h||gt(c,[n.field]))){const F=Yt(c.aggregateIndexes,n.op,n.field,n.where);if(F){Me(e,F.index);const P=De(F.index.by??[],F.key),x=Oe(e,F.index.name),Q=W(i,r`SELECT ${Ae} AS value, ${We} AS count FROM ${r.identifier(x)} WHERE ${xe} = ${P}`).toArray()[0];return Le(n.op,Q)}}bt(c,n.field,`aggregate(${e}, { op: "${n.op}", field: "${n.field}" })`);const p=te(s,oe),R=Re(n.op),$=J(n.field);let A=r`SELECT ${r.raw(R)}(${$}) AS value FROM ${r.identifier(e)}`;return p&&(A=r`${A} WHERE ${p}`),W(i,A).toArray()[0]?.value??null},asId(e,n){const a=Et(t,e,n);if(a===null)throw new g("BAD_REQUEST",`asId("${e}", …): "${n}" is not a valid id for table "${e}"`,{status:400});return a},async count(e,n){const a=K(e,"count");if(a)return N(e,U),a.count(e,n);const c=t.tables[e];if(!c)throw new g("INTERNAL",`unknown table: ${e}`);const h=Gt(n);if(h.restrictsCounts)throw new Fe(e);N(e,U);const u=le(c.softDeleteMode,void 0),s=Y(Y(h.baseWhere,h.where),u),l=await $e(s,e,h.relationBaseWhere),p=l!==s;if(c.aggregateIndexes&&!h.baseWhere&&!p&&!u){const A=Kt(c.aggregateIndexes,h.where);if(A){Me(e,A.index);const D=De(A.index.by??[],A.key),F=Oe(e,A.index.name),P=W(i,r`SELECT ${Ae} AS value FROM ${r.identifier(F)} WHERE ${xe} = ${D}`).toArray();return P[0]===void 0?0:P[0].value??0}}const R=te(l,oe);let $=r`SELECT COUNT(*) AS count FROM ${r.identifier(e)}`;return R&&($=r`${$} WHERE ${R}`),W(i,$).one().count},async delete(e,n,a){const c=re(e,n);if(!c){const $=n===void 0?E:void 0;$&&(v(void 0),await $.delete(e,void 0,a));return}const{docJson:h,row:u,tableName:s}=c,l=t.tables[s],p=a?.hard===!0,R=!p&&l?.softDeleteMode?l.softDeleteMode.field:void 0;if(!(R&&u[R]!==null&&u[R]!==void 0)){if(X(s,"before","delete")&&await Z("before","delete",{id:e,op:"delete",previous:u,table:s}),await hn({deletedId:e,deletedReference:$=>u[$],findHolders:async($,A,D)=>(await ve($).findMany($,{includeDeleted:p,where:{[A]:D}})).page,onCascade:($,A)=>ve($).delete(A,void 0,a),onRestrict:$=>{throw new pe($,"restrict")},onSetNull:($,A,D)=>ve($).patch(A,{[D]:null}),schema:t,tableName:s}),ue(s),fe(s),R){const $={...u,[R]:M(),_id:e};Ie(i,s,r`UPDATE ${r.identifier(s)} SET ${r.identifier(H)} = ${se($)} WHERE id = ${e} AND ${r.identifier(H)} = ${h}`),Ee(s,e,$,u),be(s,e,void 0),ge(s,u,$),he(s,e,u,void 0),L?.invalidate(s,e,f(s,u,$)),ne(s,e,"update",$),d({indexKeys:f(s,u,$),key:e,op:"update",row:$,table:s}),X(s,"after","delete")&&await Z("after","delete",{id:e,op:"delete",previous:u,table:s}),await O({id:e,op:"delete",table:s});return}Ie(i,s,r`DELETE FROM ${r.identifier(s)} WHERE id = ${e} AND ${r.identifier(H)} = ${h}`),Ee(s,e,void 0),be(s,e,void 0),ge(s,u,void 0),he(s,e,u,void 0),L?.invalidate(s,e,f(s,u)),ne(s,e,"delete"),d({indexKeys:f(s,u),key:e,op:"delete",table:s}),X(s,"after","delete")&&await Z("after","delete",{id:e,op:"delete",previous:u,table:s}),await O({id:e,op:"delete",table:s})}},async deleteAll(e,n){if(!t.tables[e])throw new g("INTERNAL",`unknown table: ${e}`);const a=Math.max(1,n?.chunkSize??It),c=n?.hard===void 0?void 0:{hard:n.hard},h=ae(e)?void 0:e;let u=0;return await S(async()=>{for(;;){const s=(await B.findMany(e,{limit:a})).page.map(l=>String(l._id));if(s.length===0)break;for(const l of s)await B.delete(l,h,c),u+=1;if(s.length<a)break}}),{deleted:u}},async deleteMany(e,n,a){de(e.length,n?.limit,"deleteMany");for(const c of e)await B.delete(c,a);return{deleted:e.length}},async deleteWhere(e,n,a){const c=(await(K(e,"deleteWhere")??B).findMany(e,{where:n})).page.map(h=>String(h._id));if(de(c.length,a?.limit,"deleteWhere"),B.deleteMany===void 0)throw new g("INTERNAL",`ctx.db.${e}.deleteMany is unavailable: this writer has no batch delete`);return B.deleteMany(c,a)},async findFirst(e,n={}){return(await B.findMany(e,{...n,limit:1})).page[0]??null},async findFirstOrThrow(e,n={}){const a=await B.findFirst(e,n);if(a===null)throw new on(`findFirstOrThrow: no "${e}" document matched`);return a},async findMany(e,n={}){const a=K(e,"findMany");if(a)return N(e,U),a.findMany(e,n);const c=t.tables[e];if(!c)throw new g("INTERNAL",`unknown table: ${e}`);const h=!n.where&&!n.baseWhere;h?N(e,U):N(e);const u=an(n.orderBy),s=n.cursor?xt(u,He(n.cursor)):void 0;let l=Y(n.baseWhere,n.where);l=Y(l,le(c.softDeleteMode,n.includeDeleted)),l=await ut(l,{canPushExists:Xe?Lt:void 0,existsPushMode:Ve==="always"?"always":"auto",fetcher:Je,maxRelationKeys:Ze,relationBaseWhere:n.relationBaseWhere,schema:t,tableName:e}),s&&(l=l?{AND:[l,s]}:s);const p=Xe?Kn(N):oe,R=te(l,p);let $=r`SELECT id, _creationTime, ${r.identifier(H)} FROM ${r.identifier(e)}`;R&&($=r`${$} WHERE ${R}`),$=r`${$} ORDER BY ${Dt(u)}`;const A=typeof n.limit=="number"?Math.max(0,Math.floor(n.limit)):void 0;A!==void 0&&($=r`${$} LIMIT ${r.raw(String(A+1))}`);const D=W(i,$).toArray();h&&!b&&m?.recordRead(D.length);const F=[];for(const ee of D){const q=ce(ee);q&&(F.push(q),!h&&typeof q._id=="string"&&N(e,q._id))}if(A===void 0)return n.with&&await ft({groupedCounter:et,fetcher:Ce,parents:F,...ht(n),schema:t,tableName:e,with:n.with}),{continueCursor:null,isDone:!0,page:dt(F,n.select,n.with)};const P=F.length>A,x=P?F.slice(0,A):F,Q=x.at(-1);return n.with&&await ft({fetcher:Ce,groupedCounter:et,parents:x,...ht(n),schema:t,tableName:e,with:n.with}),{continueCursor:P&&Q?Ge(Q,u):null,isDone:!P,page:dt(x,n.select,n.with)}},async get(e,n){const a=re(e,n);if(!a){const c=n===void 0?E:void 0;return c?c.get(e):null}return N(a.tableName,e),a.row},async lookupById(e,n){const a=re(e,n);return a?(N(a.tableName,e),{row:a.row,tableName:a.tableName}):null},async groupBy(e,n){const a=K(e,"groupBy");if(a)return N(e,U),a.groupBy(e,n);const c=t.tables[e];if(!c)throw new g("INTERNAL",`unknown table: ${e}`);N(e,U);const h=n.agg??{op:"count"};if(Re(h.op),h.op!=="count"&&!h.field)throw new g("INTERNAL",`groupBy(${e}, { agg: { op: "${h.op}" } }): "field" is required for non-count reducers`);const u=le(c.softDeleteMode,void 0),s=Y(Y(n.baseWhere,n.where),u),l=await $e(s,e,n.relationBaseWhere),p=l!==s,R=[...n.by,h.field];if(c.aggregateIndexes&&!n.baseWhere&&!p&&(!u||gt(c,R))){const x=Qt(c.aggregateIndexes,h.op,h.field,n.by,n.where),Q=x===void 0?0:Object.keys(x.partial).length,ee=x?.index.by?.length??0;if(x&&(Q===0||Q===ee)){Me(e,x.index);const q=Oe(e,x.index.name),ye=Object.keys(x.partial),Ne=[];if(ye.length===(x.index.by??[]).length&&ye.length>0){const _e=De(x.index.by??[],x.partial),Te=W(i,r`SELECT ${Ae} AS value, ${We} AS count FROM ${r.identifier(q)} WHERE ${xe} = ${_e}`).toArray();return Te.length>0&&Ne.push({key:{...x.partial},value:Le(h.op,Te[0])}),Ne}const Wt=W(i,r`SELECT ${xe} AS key, ${Ae} AS value, ${We} AS count FROM ${r.identifier(q)}`).toArray();for(const _e of Wt){const Te=Ht(JSON.parse(_e.key));Ne.push({key:Te,value:Le(h.op,_e)})}return Ne}}for(const x of R){if(x===void 0)continue;const Q=x===h.field?`groupBy(${e}, { agg: { op: "${h.op}", field: "${x}" } })`:`groupBy(${e}, { by: [..."${x}"] })`;bt(c,x,Q)}const $=te(l,oe),A=n.by.map(x=>r`${J(x)} AS ${r.identifier(x)}`);if(h.op==="count")A.push(r`COUNT(*) AS value`);else{const{field:x}=h;if(x===void 0)throw new g("INTERNAL",`groupBy(${e}, { agg: { op: "${h.op}" } }): "field" is required for non-count reducers`);A.push(r`${r.raw(Re(h.op))}(${J(x)}) AS value`)}let D=r`SELECT ${r.join(A,r`, `)} FROM ${r.identifier(e)}`;$&&(D=r`${D} WHERE ${$}`),D=r`${D} GROUP BY ${r.join(n.by.map(x=>J(x)),r`, `)}`;const F=W(i,D).toArray(),P=[];for(const x of F){const Q={};for(const q of n.by)Q[q]=x[q]??null;const{value:ee}=x;P.push({key:Q,value:ee==null?null:Number(ee)})}return P},async insert(e,n,a){const c=K(e,"insert");if(c)return ze(c,e,n,a,!0);const h=t.tables[e];if(!h)throw new g("INTERNAL",`unknown table: ${e}`);const u=yt(h,n,I);qe(h,u);let s;a?.clientId!==void 0?(Dn(a.clientId),s=a.clientId):a?.allowExplicitId&&typeof u._id=="string"?s=u._id:s=G();const l=a?.allowExplicitId&&typeof u._creationTime=="number"?u._creationTime:M(),p={...u,_creationTime:l,_id:s};return X(e,"before","insert")&&await Z("before","insert",{doc:{...p},id:s,op:"insert",table:e}),ue(e),fe(e),je(i,e,r`INSERT INTO ${r.identifier(e)} (id, _creationTime, ${r.identifier(H)}) VALUES (${s}, ${l}, ${se(p)})`),nt(e,s,p),X(e,"after","insert")&&await Z("after","insert",{doc:p,id:s,op:"insert",table:e}),await O({doc:p,id:s,op:"insert",table:e}),s},async insertManyUnsafe(e,n,a){if(de(n.length,a?.limit,"insertManyUnsafe"),n.length===0)return[];const c=K(e,"insert");if(c){const s=[];for(const l of n)v(l);for(const l of n){const p=await c.insert(e,l,{allowExplicitId:a?.allowExplicitId});d({key:p,op:"insert",row:{...l,_id:p},table:e}),s.push(p)}return s}const h=t.tables[e];if(!h)throw new g("INTERNAL",`unknown table: ${e}`);ue(e),fe(e);const u=n.map(s=>{const l=yt(h,s,I),p=a?.allowExplicitId===!0&&typeof l._id=="string"?l._id:G(),R=a?.allowExplicitId===!0&&typeof l._creationTime=="number"?l._creationTime:M();return{creationTime:R,document:{...l,_creationTime:R,_id:p},id:p}});for(const s of u)v(s.document);for(let s=0;s<u.length;s+=wt){const l=r.join(u.slice(s,s+wt).map(p=>r`(${p.id}, ${p.creationTime}, ${se(p.document)})`),r`, `);je(i,e,r`INSERT INTO ${r.identifier(e)} (id, _creationTime, ${r.identifier(H)}) VALUES ${l}`)}for(const{document:s,id:l}of u)nt(e,l,s),await T({doc:s,id:l,op:"insert",table:e});return u.map(s=>s.id)},async insertMany(e,n,a){de(n.length,a?.limit,"insertMany");const c=a?.skipDuplicates===!0,h=[],u=K(e,"insert");if(u)for(const l of n)v(l);const s=async l=>u?ze(u,e,l,void 0,!1):B.insert(e,l);for(const l of n)try{h.push(await s(l))}catch(p){if(c&&p instanceof pe&&p.kind==="unique")h.push(null);else throw p}return h},normalizeId(e,n){return Et(t,e,n)},async patch(e,n,a){const c=re(e,a);if(!c){const R=a===void 0?E:void 0;if(R){v(n),await R.patch(e,n);return}throw new g("INTERNAL",`document not found: ${e}`)}const{docJson:h,row:u,tableName:s}=c,l=t.tables[s];if(!l)throw new g("INTERNAL",`unknown table: ${s}`);N(s,e),_t("patch",n);const p={...u,...n,_id:e};Nt(l,n,p,I),qe(l,p,!0),X(s,"before","update")&&await Z("before","update",{doc:{...p},id:e,op:"update",previous:u,table:s}),ue(s),fe(s),Ie(i,s,r`UPDATE ${r.identifier(s)} SET ${r.identifier(H)} = ${se(p)} WHERE id = ${e} AND ${r.identifier(H)} = ${h}`),Ee(s,e,p,u),be(s,e,p),ge(s,u,p),he(s,e,u,p),L?.invalidate(s,e,f(s,u,p)),ne(s,e,"update",p),d({indexKeys:f(s,u,p),key:e,op:"update",row:p,table:s}),X(s,"after","update")&&await Z("after","update",{doc:p,id:e,op:"update",previous:u,table:s}),await O({doc:p,id:e,op:"update",table:s})},async patchMany(e,n,a){de(e.length,n?.limit,"patchMany");for(const c of e)await B.patch(c.id,c.patch,a);return{patched:e.length}},async patchWhere(e,n,a){const c=(await(K(e,"patchWhere")??B).findMany(e,{where:n.where})).page.map(h=>({id:String(h._id),patch:n.patch}));if(de(c.length,a?.limit,"patchWhere"),B.patchMany===void 0)throw new g("INTERNAL",`ctx.db.${e}.patchMany is unavailable: this writer has no batch patch`);return await B.patchMany(c,a),{patched:c.length}},query(e){const n=K(e,"query");return n?(N(e,U),n.query(e)):nr(i,t,e,_,a=>{a?w(a):N(e,U)},a=>{b||m?.recordRead(a)})},async rank(e,n,a){const c=K(e,"rank");if(c)return N(e,U),c.rank(e,n,a);_(e,n,"rank");const h=t.tables[e];if(!h)throw new g("INTERNAL",`unknown table: ${e}`);const u=h.rankIndexes?.find(q=>q.name===n);if(!u)throw new g("INTERNAL",`unknown rankIndex "${n}" on table "${e}"`);if(rt(e,h,u),a.restrictsCounts)throw new Fe(e);N(e,U),ke(e,u);const s=typeof a.row=="string"?a.row:a.row._id;if(!s)return null;const l=ct(e,u.name),p=u.sortBy.map((q,ye)=>lt(ye)),R=p.map(q=>bn(q)).join(", "),$=W(i,r`SELECT ${r.identifier("__partition__")}, ${r.raw(R)} FROM ${r.identifier(l)} WHERE ${r.identifier("__id__")} = ${s}`).toArray(),[A]=$;if(A===void 0)return null;let D=A.__partition__;const F=Y(a.baseWhere,a.where);Be(F,t,e,"rank");const P=dn(u,F);if(P){const q=ln(u.partitionBy??[],P);if(q!==D)return null;D=q}const x=p.map(q=>A[q]),{before:Q,total:ee}=Tt(i,l,p,u.sortBy,D,x,s);return{position:Q+1,total:ee}},async rankBefore(e,n,a){if(ae(e))throw new g("INTERNAL",`rankBefore is not supported on the global (.global()) table '${e}' — cross-shard rank cursors apply only to sharded tables`);const c=t.tables[e];if(!c)throw new g("INTERNAL",`unknown table: ${e}`);const h=c.rankIndexes?.find(p=>p.name===n);if(!h)throw new g("INTERNAL",`unknown rankIndex "${n}" on table "${e}"`);if(a.restrictsCounts)throw new Fe(e);N(e,U),ke(e,h);const u=ct(e,h.name),s=h.sortBy.map((p,R)=>lt(R)),l=h.sortBy.map((p,R)=>ie(a.sortValues[R]??null));return Tt(i,u,s,h.sortBy,a.partitionKey,l,a.rowId)},async rankPage(e,n,a={}){Be(Y(a.baseWhere,a.where),t,e,"rankPage");const c=K(e,"rankPage");if(c)return N(e,U),c.rankPage(e,n,a);_(e,n,"rank");const{continueCursor:h,hasMore:u,rows:s}=at(it,e,n,a);return{continueCursor:h,isDone:!u,page:s.map(l=>l.doc)}},async rankPageRows(e,n,a={}){Be(Y(a.baseWhere,a.where),t,e,"rankPage"),_(e,n,"rank");const{directions:c,hasMore:h,rows:u}=at(it,e,n,a);return{directions:c,hasMore:h,rows:u}},async restore(e,n){const a=re(e,n);if(!a){const u=n===void 0?E:void 0;if(u?.restore){await u.restore(e);return}throw new g("INTERNAL",`document not found: ${e}`)}const c=t.tables[a.tableName]?.softDeleteMode?.field;if(!c)throw new g("INTERNAL",`ctx.db.restore: table "${a.tableName}" is not a .softDelete() table`);const h=a.row[c]!==null&&a.row[c]!==void 0;await B.patch(e,{[c]:null},n),h&&he(a.tableName,e,void 0,a.row)},async replace(e,n,a,c){const h=re(e,a);if(!h){const A=a===void 0?E:void 0;if(A){v(n),await A.replace(e,n,void 0,c);return}throw new g("INTERNAL",`document not found: ${e}`)}const{docJson:u,row:s,tableName:l}=h,p=t.tables[l];if(!p)throw new g("INTERNAL",`unknown table: ${l}`);_t("replace",n);const R=c?.allowExplicitId&&typeof n._creationTime=="number"?n._creationTime:M(),$={...n,_creationTime:R,_id:e};Nt(p,n,$,I),qe(p,$),X(l,"before","update")&&await Z("before","update",{doc:{...$},id:e,op:"update",previous:s,table:l}),ue(l),fe(l),Ie(i,l,r`UPDATE ${r.identifier(l)} SET _creationTime = ${R}, ${r.identifier(H)} = ${se($)} WHERE id = ${e} AND ${r.identifier(H)} = ${u}`),Ee(l,e,$,s),be(l,e,$),ge(l,s,$),he(l,e,s,$),L?.invalidate(l,e,f(l,s,$)),ne(l,e,"update",$),d({indexKeys:f(l,s,$),key:e,op:"update",row:$,table:l}),X(l,"after","update")&&await Z("after","update",{doc:$,id:e,op:"update",previous:s,table:l}),await O({doc:$,id:e,op:"update",table:l})},async wipeShard(e){const n=new Set(e?.exclude),a=e?.tables,c=Object.entries(t.tables).filter(([l,p])=>n.has(l)||a!==void 0&&!a.includes(l)?!1:p.shardMode?.kind!=="global").map(([l])=>l);if(a!==void 0){for(const l of a)if(!t.tables[l])throw new g("INTERNAL",`wipeShard: unknown table: ${l}`)}const h={};let u=0;const{deleteAll:s}=B;if(s===void 0)throw new g("INTERNAL","wipeShard: this writer has no deleteAll");for(const l of c){const p=await s(l,{...e?.chunkSize===void 0?{}:{chunkSize:e.chunkSize},hard:!0});h[l]=p.deleted,u+=p.deleted}return{deleted:u,tables:h}}},Ft={db:B,scheduler:j};return o.enforceRls===!0?pn(B,t,(e,n)=>re(e,n)?.tableName,(e,n)=>Ot(e,n)):B};export{Ur as CDC_LOG_TABLE,Jr as CLIENT_WATERMARK_TABLE,to as GLOBAL_SHAPE_SNAPSHOT_TABLE,lo as IDEMPOTENCY_TABLE,Zn as NotUniqueError,$o as SEARCH_STATE_TABLE,Vr as advanceClientWatermark,Pr as applyCdcChanges,Dn as assertValidClientId,Fr as backfillAggregateIndexes,Wr as backfillRankIndexes,Br as backfillSearchIndexes,Hr as bumpCdcEpoch,Dr as createShardCtxDb,no as deleteGlobalShapeSnapshot,ro as deleteGlobalShapeSnapshotsForConnection,Xr as migrateClientWatermark,oo as migrateGlobalShapeSnapshot,Gr as minCdcSeq,Et as normalizeIdStructurally,jr as readCdcChanges,Qr as readCdcCursor,Kr as readCdcEpoch,Zr as readClientWatermark,io as readGlobalShapeSnapshot,co as readIdempotent,mo as runShardMigrations,go as selectShapeMemberIds,bo as selectShapeRows,Yr as trimCdcChanges,uo as trimIdempotent,ao as writeGlobalShapeSnapshot,fo as writeIdempotent};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{matchesStaticWhere as l}from"./AGGREGATE_SQL_FUNCTION-CTo0-9iZ.mjs";import{compareStrings as c}from"./aggregateTableName-
|
|
1
|
+
import{matchesStaticWhere as l}from"./AGGREGATE_SQL_FUNCTION-CTo0-9iZ.mjs";import{compareStrings as c}from"./aggregateTableName-DN7gk6uh.mjs";import{serializeSqlValue as f}from"./serializeSqlValue-BR4UOWoP.mjs";const n=Symbol("not-resolvable"),m=r=>{if(r!==null&&typeof r=="object"&&!Array.isArray(r)){const t=Object.keys(r);return t.length===1&&t[0]==="eq"?r.eq:n}return r},u=(r,t)=>{if(r.length===0)return"";const o={};for(const s of r.toSorted(c))o[s]=t[s]??null;return JSON.stringify(o)},h="__id__",k=r=>`__sort_k${String(r)}__`,S=(r,t)=>{const o=r.partitionBy??[],s=t??{};for(const e of Object.keys(s))if(e==="AND"||e==="OR"||e==="NOT")return;const i={};for(const e of o)if(e in s){const a=m(s[e]);if(a===n)return;i[e]=a}else if(r.where&&e in r.where)i[e]=r.where[e];else return;return i},d=(r,t)=>`${r}__rank_${t}`,b=(r,t)=>({partitionKey:u(r.partitionBy??[],t),rowId:t._id,sortValues:r.sortBy.map(o=>f(t[o.field]??null))}),g=l;export{h as RANK_TIEBREAK,u as encodePartitionKey,g as matchesRankStaticWhere,b as rankKeyFromDoc,d as rankTableName,S as resolveRankPartition,k as sortColumnName};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{stableWireKey as p}from"./stableWireKey-
|
|
1
|
+
import{stableWireKey as p}from"./stableWireKey-Diuu1gGc.mjs";import{depKey as l,SCAN_DEP as f}from"./SCAN_DEP-D_yR9EeV.mjs";import{o as m}from"./estimate-bytes-Drp8rhPs.mjs";import{keysTouchRanges as u}from"./buildIndexRange-DFsdtPjD.mjs";import{stableStringify as A}from"./stableStringify-BjLh4gvA.mjs";const c=(o,t,e)=>{let s=o.get(t);return s===void 0&&(s=e(),o.set(t,s)),s},x=1e3,g=4*1024*1024;class z{entries=new Map;tableIndex=new Map;rangeIndex=new Map;totalBytes=0;hits=0;misses=0;evictions=0;maxEntries;maxBytes;now;monotonic=0;constructor(t={}){this.maxEntries=t.maxEntries??x,this.maxBytes=t.maxBytes??g,this.now=t.now??(()=>(this.monotonic+=1,this.monotonic))}async run(t,e,s,i=()=>[]){const n=this.entries.get(t);if(n)return this.hits+=1,n.lastUsed=this.now(),this.entries.delete(t),this.entries.set(t,n),n.result;this.misses+=1;const r=await s(),h=m(r);if(h===void 0)return r;const d=i(),b={bytes:h,deps:e,ranges:d,lastUsed:this.now(),result:r,subscribers:new Set};this.entries.set(t,b),this.totalBytes+=h;for(const a of e)c(this.tableIndex,a,()=>new Set).add(t);for(const a of d){const y=c(this.rangeIndex,a.table,()=>new Map);c(y,a,()=>new Set).add(t)}return this.evict(),r}invalidate(t,e,s){const i=[];return this.collectAndDrop(l(t,e),i),this.collectAndDrop(l(t,f),i),this.dropRangeDeps(t,s,i),i}invalidateTable(t){const e=[],s=`${t}:`;for(const i of this.tableIndex.keys())i.startsWith(s)&&this.collectAndDrop(i,e);return this.dropRangeDeps(t,void 0,e),e}subscribe(t,e){const s=this.entries.get(t);s&&s.subscribers.add(e)}unsubscribe(t,e){const s=this.entries.get(t);s&&s.subscribers.delete(e)}size(){return{bytes:this.totalBytes,entries:this.entries.size}}clear(){this.entries.clear(),this.tableIndex.clear(),this.rangeIndex.clear(),this.totalBytes=0}subscribers(t){const e=this.entries.get(t);return e?[...e.subscribers]:[]}stats(){return{bytes:this.totalBytes,entries:this.entries.size,evictions:this.evictions,hits:this.hits,misses:this.misses}}dropRangeDeps(t,e,s){const i=this.rangeIndex.get(t);if(!(!i||i.size===0))for(const[n,r]of i)u([n],e)&&this.dropKeys(r,s)}collectAndDrop(t,e){const s=this.tableIndex.get(t);s&&this.dropKeys(s,e)}dropKeys(t,e){for(const s of t){const i=this.entries.get(s);i&&(this.dropEntry(s,i),e.push(s))}}dropEntry(t,e){this.entries.delete(t),this.totalBytes-=e.bytes;for(const s of e.deps){const i=this.tableIndex.get(s);i&&(i.delete(t),i.size===0&&this.tableIndex.delete(s))}for(const s of e.ranges){const i=this.rangeIndex.get(s.table),n=i?.get(s);n?.delete(t),i&&n?.size===0&&(i.delete(s),i.size===0&&this.rangeIndex.delete(s.table))}}evict(){if(!(this.entries.size<=this.maxEntries&&this.totalBytes<=this.maxBytes))for(const[t,e]of this.entries){if(this.entries.size<=this.maxEntries&&this.totalBytes<=this.maxBytes)return;e.subscribers.size>0||(this.dropEntry(t,e),this.evictions+=1)}}}const E=(o,t,e)=>`${e??"\0anon"}\0${o}:${p(t)}`;export{z as ReactiveCache,E as reactiveCacheKey,A as stableStringify,p as stableWireKey};
|
package/dist/packem_shared/{aggregateTableName-DgYMC5tr.mjs → aggregateTableName-DN7gk6uh.mjs}
RENAMED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{LunoraError as l}from"@lunora/errors";import{a as g}from"./wire-codec-
|
|
1
|
+
import{LunoraError as l}from"@lunora/errors";import{a as g}from"./wire-codec-Dh0j-GnY.mjs";const n=BigInt(Number.MAX_SAFE_INTEGER),i=(e,t)=>e<t?-1:e>t?1:0,s=(e,t)=>`${e}__agg_${t}`,c=e=>{if(typeof e=="bigint"){if(e>n||e<-n)throw new l("BAD_REQUEST",`bigint ${e.toString()} exceeds Number.MAX_SAFE_INTEGER, so an aggregateIndex declared over this column cannot tally it exactly (the companion's value column is a REAL) — drop the aggregateIndex, aggregate a narrower column, or read the rows and reduce them in the handler`);return Number(e)}if(typeof e=="number")return Number.isFinite(e)?e:void 0},d=(e,t,o,u)=>{const r=e.get(t)??{count:0,value:null};if(o.op==="count"){r.count+=1,r.value=r.count,e.set(t,r);return}const a=c(u[o.field??""]);if(o.op==="sum"||o.op==="avg"){a!==void 0&&(r.value=(r.value??0)+a,r.count+=1),e.set(t,r);return}r.count+=1,a!==void 0&&(r.value===null?r.value=a:r.value=o.op==="min"?Math.min(r.value,a):Math.max(r.value,a)),e.set(t,r)},f=(e,t)=>e==="count"?t?.value??0:!t||t.count===0?null:e==="avg"?t.value===null?null:t.value/t.count:t.value,p=(e,t)=>{if(e.length===0)return"";const o={};for(const u of e.toSorted(i))o[u]=t[u]??null;return JSON.stringify(g(o))};export{s as aggregateTableName,c as coerceAggregateNumber,i as compareStrings,p as encodeAggregateKey,d as foldAggregateTally,f as readAggregateValue};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{LunoraError as B}from"@lunora/errors";import{applySelect as A}from"./applySelect-
|
|
1
|
+
import{LunoraError as B}from"@lunora/errors";import{applySelect as A}from"./applySelect-5w13bMAR.mjs";const C=s=>({relationBaseWhere:s.relationBaseWhere,relationMask:s.relationMask}),$=(s,o)=>o.select?A(s,o.select,o.with):s,E=async(s,o,t,a,r)=>{const u=await Promise.all(a.map(async i=>{const p=r?{AND:[{[t]:i},r]}:{[t]:i};return[i,await s(o,p)]}));return new Map(u)},R=(s,o)=>{const t=new Set;for(const a of s){const r=a[o];r!=null&&t.add(r)}return[...t]},S=async s=>{const{groupedCounter:o,fetcher:t,parents:a,relationBaseWhere:r,relationMask:u,schema:i,tableName:p,with:O}=s,M=(l,e)=>u?.(l,e)??e;if(a.length===0)return;const g=i.tables[p];if(!g)throw new B("INTERNAL",`unknown table: ${p}`);const N=g.relationMap??{},W=l=>{const e=N[l];if(!e)throw new B("INTERNAL",`unknown relation "${l}" on table "${p}"`);return e},k=async(l,e,n)=>{const d=R(a,e.field);if(d.length===0){for(const c of a)c[l]=null;return}const{page:b}=await t(e.table,{baseWhere:r?.(e.table),relationBaseWhere:r,relationMask:u,where:{[e.references]:{in:d}},with:n.with}),y=new Map;for(const c of M(e.table,b))y.set(c[e.references],c);for(const c of a){const w=y.get(c[e.field]);c[l]=w?$([w],n)[0]??null:null}},j=async(l,e,n)=>{const d=R(a,e.references);if(d.length===0){for(const f of a)f[l]=[];return}const b={[e.field]:{in:d}},y=n.where?{AND:[n.where,b]}:b,{page:c}=await t(e.table,{baseWhere:r?.(e.table),orderBy:n.orderBy,relationBaseWhere:r,relationMask:u,where:y,with:n.with}),w=new Map;for(const f of M(e.table,c)){const h=f[e.field],D=w.get(h);D?D.push(f):w.set(h,[f])}const m=typeof n.limit=="number"?Math.max(0,Math.floor(n.limit)):void 0;for(const f of a){const h=w.get(f[e.references])??[];f[l]=$(m===void 0?h:h.slice(0,m),n)}},v=async l=>{for(const e of Object.keys(l)){const n=W(e),[d,b]=n.kind==="many"?[n.field,n.references]:[n.references,n.field],y=r?.(n.table),c=R(a,b),w=c.length===0?new Map:await o(n.table,d,c,y);for(const m of a){const f=m._count??{},h=m[b];f[e]=h==null?0:w.get(h)??0,m._count=f}}};for(const[l,e]of Object.entries(O)){if(e===void 0||e===!1)continue;if(l==="_count"){await v(e);continue}const n=W(l),d=e===!0?{}:e;await(n.kind==="one"?k(l,n,d):j(l,n,d))}},I=async(s,o,t)=>{const{deletedId:a,deletedReference:r,findHolders:u,onCascade:i,onRestrict:p,onSetNull:O,tableName:M}=s,g=t.references==="_id"?a:r(t.references);if(g==null)return;const N=await u(o,t.field,g);if(N.length!==0){t.onDelete==="restrict"&&p(`cannot delete "${M}" row: "${o}.${t.field}" still references it`);for(const W of N){const k=W._id;typeof k=="string"&&await(t.onDelete==="cascade"?i(o,k):O(o,k,t.field))}}},T=async s=>{const{schema:o,tableName:t}=s;if(!o.tables[t])throw new B("INTERNAL",`unknown table: ${t}`);for(const[a,r]of Object.entries(o.tables)){const u=r.relationMap;if(u)for(const i of Object.values(u))i.kind!=="one"||i.table!==t||!i.onDelete||await I(s,a,i)}},V=(s,o,t=!1)=>{for(const[a,r]of Object.entries(s.shape))a in o&&typeof r.parse=="function"&&(t&&o[a]===null&&r.kind==="optional"||r.parse(o[a]))};export{T as applyOnDelete,R as distinctValues,E as fanOutScalarCounts,C as relationHooks,S as resolveWith,V as runRowValidators};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{LunoraError as h}from"@lunora/errors";import{s as m,a as S}from"./wire-codec-
|
|
1
|
+
import{LunoraError as h}from"@lunora/errors";import{s as m,a as S}from"./wire-codec-Dh0j-GnY.mjs";const g="id",y=new Set(["_id","id"]),C=r=>{const e=[];for(const o of r??[])for(const[t,i]of Object.entries(o))e.push({direction:i,field:t});return e.length===0?[{direction:"asc",field:"_creationTime"}]:e},w=r=>{const e=new TextEncoder().encode(r);let o="";for(const t of e)o+=String.fromCodePoint(t);return btoa(o)},b=r=>{const e=atob(r),o=Uint8Array.from(e,t=>t.codePointAt(0)??0);return new TextDecoder().decode(o)},D=(r,e)=>{const o=e.map(t=>r[t.field]);return o.push(r._id),w(JSON.stringify(S(o)))},a=()=>new h("BAD_REQUEST","invalid cursor"),E=r=>{let e;try{e=m(JSON.parse(b(r)))}catch{throw a()}if(!Array.isArray(e))throw a();return e},f=(r,e,o)=>{const t=r.some(s=>y.has(s.field))?r:[...r,{direction:"asc",field:g}],i=[];for(const[s,n]of t.entries()){const c=[];for(const[u,p]of t.slice(0,s).entries())c.push({[p.field]:{eq:e[u]}});const l=o(n.direction,s===t.length-1);c.push({[n.field]:{[l]:e[s]}});const[d]=c;i.push(c.length===1&&d!==void 0?d:{AND:c})}return{OR:i}},T=(r,e)=>f(r,e,o=>o==="desc"?"lt":"gt"),v=(r,e)=>r==="desc"?e?"gte":"gt":e?"lte":"lt",k=(r,e)=>f(r,e,v),A=["_id","_creationTime"],B=(r,e,o)=>{if(!e)return r;const t=new Set([...e,...A,...o?Object.keys(o):[]]);return r.map(i=>{const s={};for(const n of t)n in i&&(s[n]=i[n]);return s})},N=(r,e)=>r&&e!==!0?{[r.field]:{isNull:!0}}:void 0,x=(r,e)=>e===void 0||r[e]===null||r[e]===void 0;export{B as applySelect,k as buildSeekBeforeWhere,T as buildSeekWhere,E as decodeCursor,D as encodeCursor,b as fromBase64,a as invalidCursor,x as isLiveForCompanion,C as normalizeOrderKeys,N as softDeleteScope,w as toBase64};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{stableStringify as v}from"./stableStringify-BjLh4gvA.mjs";import{A as m,a as A}from"./wire-codec-Dh0j-GnY.mjs";const S="_id",p="_creationTime",y="page",O=r=>{let t;for(const s of r){const n=s[p];if(typeof n=="number"){if(t!==void 0){if(n<t)return!0;if(n>t)return!1}t=n}}return!1},w=(r,t)=>{const s=t[p];if(typeof s!="number")return r.length;const n=O(r);for(const[o,e]of r.entries()){const i=e[p];if(typeof i=="number"&&(n?i<s:i>s))return o}return r.length},x="__lunora__",N=r=>{if(typeof r!="object"||r===null||Array.isArray(r))return;const t=r[S];return typeof t=="string"?t:void 0},$=r=>{const t=new Map,s=[];for(const n of r){const o=N(n);if(o===void 0||t.has(o))return;t.set(o,n),s.push(o)}return{byId:t,order:s}},_=(r,t)=>{const s=r.order.filter(o=>t.byId.has(o)),n=t.order.filter(o=>r.byId.has(o));return s.length!==n.length?!1:s.every((o,e)=>n[e]===o)},k=(r,t,s,n)=>{const o=[];for(const e of r.order)t.byId.has(e)||o.push({delta:{key:e,op:"delete",table:s},frame:`{"key":${JSON.stringify(e)},"op":"delete","table":${n}}`});return o},D=(r,t,s,n)=>{const o=[];for(const e of t.order){const i=t.byId.get(e),a=r.byId.get(e),u=JSON.stringify(A(i)),f=a===void 0?void 0:JSON.stringify(a);if(f===u)continue;const d=f===void 0?"insert":"update";o.push({delta:{key:e,op:d,row:i,table:s},frame:`{"key":${JSON.stringify(e)},"op":"${d}","row":${u},"table":${n}}`})}return o},M=(r,t)=>{if(Array.isArray(r)&&Array.isArray(t))return{next:t,previous:r};if(!m(r)||!m(t))return;const s=r[y],n=t[y];if(!Array.isArray(s)||!Array.isArray(n))return;const o=e=>Object.fromEntries(Object.entries(e).filter(([i])=>i!==y));if(v(o(r))===v(A(o(t))))return{next:n,previous:s}},j=(r,t,s)=>{const n=s.filter(({delta:e})=>e.op==="insert");if(n.length===0)return!0;const o=r.order.filter(e=>t.byId.has(e)).map(e=>r.byId.get(e));for(const{delta:e}of n){const i=e.row;o.splice(w(o,i),0,i)}return o.length===t.order.length&&o.every((e,i)=>e[S]===t.order[i])},I=(r,t,s)=>{let n;try{n=JSON.parse(r)}catch{return}const o=M(n,t);if(o===void 0)return;const e=$(o.previous),i=$(o.next);if(e===void 0||i===void 0||!_(e,i))return;const a=s===""?x:s,u=JSON.stringify(a),f=[...k(e,i,a,u),...D(e,i,a,u)];return j(e,i,f)?f:void 0},P=(r,t,s,n)=>{const o=I(r,t,s);if(o!==void 0){if(n!==void 0)for(const{frame:e}of o)n.push(e);return o.map(({delta:e})=>e)}},T=(r,t)=>{try{return r.send(t),!0}catch{return!1}},E=r=>{const{cursorSuffix:t,lastMutationId:s,nextResult:n,pageDeltas:o,previousJson:e,snapshotJson:i,subId:a,table:u}=r,f=JSON.stringify(a),d=(s===void 0?"":`,"lastMutationId":${String(s)}`)+t,c=`{"type":"data","id":${f},"data":${i}${d}}`,l=e!==void 0&&(o===!0||Array.isArray(n))?I(e,n,u):void 0;if(l===void 0||l.length===0)return[c];const b=[];let g=0;for(const{frame:J}of l){const h=`{"type":"delta","id":${f},"delta":${J}${d}}`;if(g+=h.length,g>=c.length)return[c];b.push(h)}return b},R=async r=>{let t=0;for(;t<100;){t+=1;const{bufferedAmount:s}=r;if(typeof s!="number"||s<1048576)return;await new Promise(n=>{setTimeout(n,20)})}};export{R as awaitWsDrain,E as subscriptionFrames,P as subscriptionListDeltas,T as trySendFrame};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{B as R,W as x,x as k,T as S,l as O,y as M,c as w}from"./ctx-db-companions-
|
|
1
|
+
import{B as R,W as x,x as k,T as S,l as O,y as M,c as w}from"./ctx-db-companions-BJlCofon.mjs";import"@lunora/errors";import{sql as r}from"drizzle-orm";import{matchesStaticWhere as A}from"./AGGREGATE_SQL_FUNCTION-CTo0-9iZ.mjs";import{encodeAggregateKey as L,foldAggregateTally as C,aggregateTableName as F}from"./aggregateTableName-DN7gk6uh.mjs";import{migrateSearchState as y,readSearchBackfillState as D,writeSearchBackfillState as N}from"./SEARCH_STATE_TABLE-DRk_SB72.mjs";import{runDrizzle as d}from"./runDrizzle-C3n5gJsk.mjs";import{C as T,E as p,c as v,p as B,T as W,a as E,D as j}from"./do-sql-DKSFK627.mjs";import{isLiveForCompanion as _}from"./applySelect-5w13bMAR.mjs";import{matchesRankStaticWhere as U,rankTableName as V}from"./RANK_TIEBREAK-BGk411OR.mjs";const Y=(e,o)=>e.profile!==o?{cursor:void 0,finished:!1,wipe:e.cursor!==void 0||e.done}:{cursor:e.cursor,finished:e.done,wipe:!1},u=(e,o)=>d(e,r`SELECT COUNT(*) AS count FROM ${r.identifier(o)}`).one().count>0,I=(e,o)=>d(e,r`SELECT id, _creationTime, ${r.identifier(E)} FROM ${r.identifier(o)}`).toArray(),q=(e,o,n,i)=>{const t=F(o,n.name);if(u(e,t))return;const s=n.by??[],c=new Map,f=I(e,o);for(const l of f){const a=p(l);if(!a||!_(a,i)||n.where&&!A(a,n.where))continue;const $=L(s,a);C(c,$,n,a)}for(const[l,a]of c)d(e,r`INSERT INTO ${r.identifier(t)} (${v}, ${B}, ${W}) VALUES (${l}, ${a.value}, ${a.count})`)},re=(e,o)=>{for(const[n,i]of Object.entries(o.tables))if(!(i.shardMode?.kind==="global"||!i.aggregateIndexes))for(const t of i.aggregateIndexes)q(e,n,t,i.softDeleteMode?.field)},z=(e,o,n)=>{const i=V(o,n.name);if(u(e,i))return;const t=R(n),s=I(e,o);for(const c of s){const f=p(c);!f||n.where&&!U(f,n.where)||x(e,i,n,t,f._id,f)}},oe=(e,o)=>{for(const[n,i]of Object.entries(o.tables))if(!(i.shardMode?.kind==="global"||!i.rankIndexes))for(const t of i.rankIndexes)z(e,n,t)},g=500,b=(e,o,n)=>{const i=w(o,n.name),{profile:t}=k(n.language),s=Y(D(e,i),t);if(s.finished)return!0;s.wipe&&d(e,r`DELETE FROM ${r.identifier(i)}`);const{cursor:c}=s,f=d(e,c===void 0?r`SELECT id, _creationTime, ${r.identifier(E)} FROM ${r.identifier(o)} ORDER BY id ASC LIMIT ${r.raw(String(g))}`:r`SELECT id, _creationTime, ${r.identifier(E)} FROM ${r.identifier(o)} WHERE id > ${c} ORDER BY id ASC LIMIT ${r.raw(String(g))}`).toArray();let l=c;for(const $ of f){const{id:m}=$;if(typeof m!="string")continue;l=m,d(e,r`DELETE FROM ${r.identifier(i)} WHERE ${r.identifier(S)} = ${m}`);const h=j($);h&&d(e,r`INSERT INTO ${r.identifier(i)} (${r.identifier(O)}, ${r.identifier(S)}) VALUES (${M(h,n)}, ${m})`)}const a=f.length<g;return N(e,i,l,a,t),a},ne=(e,o,n)=>{if(T(e))for(const i of n.searchIndexes??[])i.staged||b(e,o,i)},te=(e,o)=>{if(T(e)){y(e);for(const[n,i]of Object.entries(o.tables))if(!(i.shardMode?.kind==="global"||!i.searchIndexes))for(const t of i.searchIndexes){let s=!1;for(;!s;)s=b(e,n,t)}}};export{re as backfillAggregateIndexes,oe as backfillRankIndexes,te as backfillSearchIndexes,ne as backfillSearchIndexesForTable};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{a as u}from"./wire-codec-
|
|
1
|
+
import{a as u}from"./wire-codec-Dh0j-GnY.mjs";const l=(t,o)=>{if(!o)return t;const r=Object.create(null);for(const a of["_id","_creationTime",...o])Object.hasOwn(t,a)&&(r[a]=t[a]);return r},b=(t,o,r)=>{const{columns:a,table:i}=r,n=new Map,p=[];for(const{doc:e,id:s}of t){const c=l(e,a),d=JSON.stringify(u(c));n.set(s,d);const h=o.get(s);h===void 0?p.push({key:s,op:"insert",table:i,value:c}):h!==d&&p.push({key:s,op:"update",table:i,value:c})}for(const e of o.keys())n.has(e)||p.push({key:e,op:"delete",table:i});return{next:n,rowsPatch:p}},f=t=>t.map(o=>o.value===void 0?o:{...o,value:u(o.value)}),y=(t,o,r={})=>{const{baseCheckpoint:a,checkpoint:i,epoch:n,lastMutationId:p,pokeId:e}=o,s=[JSON.stringify({baseCheckpoint:a,epoch:n,pokeId:e,type:"pokeStart"})];for(const c of t){const d=r.preEncoded?c.rowsPatch:f(c.rowsPatch);s.push(JSON.stringify({pokeId:e,rowsPatch:d,shapeId:c.shapeId,type:"pokePart",...p===void 0?{}:{lastMutationId:p}}))}return s.push(JSON.stringify({checkpoint:i,epoch:n,pokeId:e,type:"pokeEnd"})),s};export{y as buildPokeFrames,b as diffGlobalMembership,f as encodeRowsPatch,l as projectColumns};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{quoteIdentifier as _}from"./quoteIdentifier-CObIFRhb.mjs";import{reprojectionMigrationTable as u}from"./REPROJECTION_MIGRATION_PREFIX-D2dltRFC.mjs";import{REPROJECTION_MIGRATION_PREFIX as L,reprojectionMigrationId as C}from"./REPROJECTION_MIGRATION_PREFIX-D2dltRFC.mjs";import{a as m}from"./wire-codec-
|
|
1
|
+
import{quoteIdentifier as _}from"./quoteIdentifier-CObIFRhb.mjs";import{reprojectionMigrationTable as u}from"./REPROJECTION_MIGRATION_PREFIX-D2dltRFC.mjs";import{REPROJECTION_MIGRATION_PREFIX as L,reprojectionMigrationId as C}from"./REPROJECTION_MIGRATION_PREFIX-D2dltRFC.mjs";import{a as m}from"./wire-codec-Dh0j-GnY.mjs";import{runSql as p}from"./runDrizzle-C3n5gJsk.mjs";import{L as E,a as g}from"./do-sql-DKSFK627.mjs";import{y as b}from"./sql-projection-jfoe331H.mjs";const R=m(0n)[0],l=t=>t.shardMode?.kind==="global"?[]:Object.entries(t.shape).filter(([,r])=>b(r)).map(([r])=>r),T=t=>Object.entries(t.tables).filter(([,r])=>l(r).length>0).map(([r])=>r),f=t=>{const r=`json_each(${_(g)}) AS __f__`;return{params:[JSON.stringify(t),R,"bigint","bytes"],sql:`EXISTS (SELECT 1 FROM ${r} WHERE __f__.type = 'array' AND __f__.key IN (SELECT value FROM json_each(?)) AND json_extract(__f__.value, '$[0]') = ? AND json_extract(__f__.value, '$[1]') IN (?, ?))`}},M=(t,r,o)=>{if(o.length===0)return 0;const{params:e,sql:n}=f(o);return p(t,`SELECT COUNT(*) AS count FROM ${_(r)} WHERE ${n}`,...e).toArray()[0]?.count??0},$=(t,r,o,e)=>{const{params:n,sql:i}=f(o);return p(t,`SELECT 1 FROM ${_(r)} WHERE id = ? AND (${i}) LIMIT 1`,e,...n).toArray().length>0},N=(t,r,o)=>{const e=u(t);if(e===void 0)return;const n=r.tables[e];if(!n)return;const i=l(n);if(i.length!==0)return{id:t,table:e,up:a=>{const s=a._id;if(!(typeof s!="string"||!$(o,e,i,s))){try{E(a)}catch(c){console.warn(`${t}: skipping row ${s} — it cannot be re-projected: ${c instanceof Error?c.message:String(c)}`);return}return a}}}};export{L as REPROJECTION_MIGRATION_PREFIX,N as buildReprojectionMigration,M as countLegacyRows,l as reprojectableFields,C as reprojectionMigrationId,T as reprojectionTables};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{LunoraError as N}from"@lunora/errors";import{sql as t}from"drizzle-orm";import{mergeWhere as v}from"./CountRlsUnsupportedError-8BqPYQoP.mjs";import{SCAN_DEP as x}from"./SCAN_DEP-D_yR9EeV.mjs";import{runDrizzle as B}from"./runDrizzle-C3n5gJsk.mjs";import{sqliteInList as O}from"./param-CYxL68V-.mjs";import{decodeCursor as W,toBase64 as z}from"./applySelect-
|
|
1
|
+
import{LunoraError as N}from"@lunora/errors";import{sql as t}from"drizzle-orm";import{mergeWhere as v}from"./CountRlsUnsupportedError-8BqPYQoP.mjs";import{SCAN_DEP as x}from"./SCAN_DEP-D_yR9EeV.mjs";import{runDrizzle as B}from"./runDrizzle-C3n5gJsk.mjs";import{sqliteInList as O}from"./param-CYxL68V-.mjs";import{decodeCursor as W,toBase64 as z}from"./applySelect-5w13bMAR.mjs";import{sortColumnName as F,resolveRankPartition as H,RANK_TIEBREAK as m,encodePartitionKey as J,rankTableName as V}from"./RANK_TIEBREAK-BGk411OR.mjs";const Y="__doc__",G=n=>z(JSON.stringify(n)),X=n=>n.after?[n.after.partitionKey,...n.after.sortValues,n.after.rowId]:n.cursor?W(n.cursor):void 0,Z=(n,o,f)=>{if(n?.length!==1+o.length+1)return;const r=[{column:"__partition__",direction:"asc"}];for(const[s,a]of o.entries())r.push({column:a,direction:f[s]?.direction??"asc"});r.push({column:m,direction:"asc"});const e=[];for(const[s,a]of r.entries()){const c=[];for(const[i,l]of r.slice(0,s).entries())c.push(t`${t.identifier(l.column)} IS ${n[i]}`);c.push(t`${t.identifier(a.column)} ${t.raw(a.direction==="desc"?"<":">")} ${n[s]}`);const[p]=c;e.push(c.length===1&&p!==void 0?p:t`(${t.join(c,t` AND `)})`)}return t`(${t.join(e,t` OR `)})`},C=null,Q=(n,o)=>{if(n===void 0)return C;const f=[n.__partition__,...o.map(r=>n[r]),n[m]];return G(f)},U=(n,o,f)=>{const r=[];for(const e of n){const s=e[m];if(typeof s!="string")continue;const a=o.get(s);if(!a)continue;const c=typeof e.__partition__=="string"?e.__partition__:"",p=f.map(i=>e[i]??null);r.push({doc:a,key:{partitionKey:c,rowId:s,sortValues:p}})}return r},tt=t`${t.identifier("id")}`,nt=(n,o,f)=>{const{rowToDocument:r}=n,e=new Map;if(f.length===0)return e;const s=B(n.sql,t`SELECT id, _creationTime, ${t.identifier(Y)} FROM ${t.identifier(o)} WHERE ${O(tt,f,!1)}`).toArray();for(const a of s){const c=r(a),p=a.id;c&&typeof p=="string"&&e.set(p,c)}return e},pt=(n,o,f,r)=>{const{assertRankPartitionLocal:e,ensureRankBackfilled:s,onRead:a,schema:c}=n,p=c.tables[o];if(!p)throw new N("INTERNAL",`unknown table: ${o}`);const i=p.rankIndexes?.find(u=>u.name===f);if(!i)throw new N("INTERNAL",`unknown rankIndex "${f}" on table "${o}"`);e(o,p,i),a(o,x),s(o,i);const l=V(o,i.name),d=i.sortBy.map((u,w)=>F(w)),$=Math.max(1,Math.min(1e3,Math.floor(r.take??100))),S=v(r.baseWhere,r.where),R=H(i,S),h=[t`${t.identifier("__partition__")} ASC`];for(const[u,w]of d.entries()){const q=i.sortBy[u]?.direction;h.push(t`${t.identifier(w)} ${t.raw(q==="desc"?"DESC":"ASC")}`)}h.push(t`${t.identifier(m)} ASC`);const _=[];typeof r.partitionKey=="string"?_.push(t`${t.identifier("__partition__")} = ${r.partitionKey}`):R&&_.push(t`${t.identifier("__partition__")} = ${J(i.partitionBy??[],R)}`);const T=X(r),k=Z(T,d,i.sortBy);k&&_.push(k);const I=t.identifier(m),A=t.identifier("__partition__"),L=_.length>0?t` WHERE ${t.join(_,t` AND `)}`:t``,M=d.length>0?t`${I}, ${A}, ${t.join(d.map(u=>t.identifier(u)),t`, `)}`:t`${I}, ${A}`,D=t`SELECT ${M} FROM ${t.identifier(l)}${L} ORDER BY ${t.join(h,t`, `)} LIMIT ${t.raw(String($+1))}`,y=B(n.sql,D).toArray(),g=y.length>$,E=g?y.slice(0,$):y,K=E.map(u=>u[m]),b=U(E,nt(n,o,K),d),P=g?Q(E.at(-1),d):C,j=i.sortBy.map(u=>u.direction==="desc"?"desc":"asc");return{continueCursor:P,directions:j,hasMore:g,rows:b}};export{pt as computeRankPage,nt as hydrateDocsById};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{S as C,W as R,B as f}from"./ctx-db-companions-BJlCofon.mjs";import"@lunora/errors";import"drizzle-orm";import"./AGGREGATE_SQL_FUNCTION-CTo0-9iZ.mjs";import"./aggregateTableName-DN7gk6uh.mjs";import"./runDrizzle-C3n5gJsk.mjs";import"./do-sql-DKSFK627.mjs";import"./param-CYxL68V-.mjs";import"./GEO_DEFAULT_PRECISION-DyI5zggj.mjs";import"./applySelect-5w13bMAR.mjs";import"./RANK_TIEBREAK-BGk411OR.mjs";import"./sql-projection-jfoe331H.mjs";import"./serializeSqlValue-BR4UOWoP.mjs";export{C as createCompanionSync,R as insertRankRow,f as rankColumnsSql};
|
package/dist/packem_shared/{ctx-db-companions-c12P7dbv.mjs → ctx-db-companions-BJlCofon.mjs}
RENAMED
|
@@ -1 +1 @@
|
|
|
1
|
-
import"@lunora/errors";import{sql as e}from"drizzle-orm";import{matchesStaticWhere as P,aggregateSqlFunction as de}from"./AGGREGATE_SQL_FUNCTION-CTo0-9iZ.mjs";import{encodeAggregateKey as N,foldAggregateTally as V,coerceAggregateNumber as F,aggregateTableName as G}from"./aggregateTableName-
|
|
1
|
+
import"@lunora/errors";import{sql as e}from"drizzle-orm";import{matchesStaticWhere as P,aggregateSqlFunction as de}from"./AGGREGATE_SQL_FUNCTION-CTo0-9iZ.mjs";import{encodeAggregateKey as N,foldAggregateTally as V,coerceAggregateNumber as F,aggregateTableName as G}from"./aggregateTableName-DN7gk6uh.mjs";import{runDrizzle as u}from"./runDrizzle-C3n5gJsk.mjs";import{C as ce,a as M,E as D,c as j,p as S,T as _,h as fe,A as C,N as k}from"./do-sql-DKSFK627.mjs";import{param as ue,WORKERD_SQLITE_LIMITS as $e}from"./param-CYxL68V-.mjs";import{encodeGeohash as me,GEO_DEFAULT_PRECISION as Ee}from"./GEO_DEFAULT_PRECISION-DyI5zggj.mjs";import{isLiveForCompanion as J}from"./applySelect-5w13bMAR.mjs";import{encodePartitionKey as he,sortColumnName as pe,matchesRankStaticWhere as Y,rankTableName as Z}from"./RANK_TIEBREAK-BGk411OR.mjs";import{y as ge}from"./sql-projection-jfoe331H.mjs";import{serializeSqlValue as ee}from"./serializeSqlValue-BR4UOWoP.mjs";const _e=["de","en","es","fr","it","nl","none","pt"],ye=o=>_e.includes(o),be="a an and are as at be but by for if in into is it no not of on or such that the their then there these they this to was will with",Se="aber als am an auch auf aus bei bin bis bist da dass der den des dem die das denn dir du ein eine für hat ich im in ist mit nicht noch nur oder sich sie sind über und von vor war wie wir zu zum zur",Te="a al como con de del el en es la las lo los mas no o para pero por que se su sus un una uno y ya",ve="au aux avec ce ces dans de des du elle en et eux il je la le les leur lui ma mais me même mes moi mon ne nos notre nous on ou par pas pour qu que qui sa se ses son sur ta te tes toi ton tu un une vos votre vous y",we="a ai al alla anche che chi ci coi col come con da dal degli dei del della di do e ed gli ha hai hanno i il in la le lo ma mi ne nei nel non o per più quale quanto se si sono su sul tra un una uno vi",Ae="aan al als bij dan dat de der deze die dit door een en er het hij ij in is je kan me men met mij na naar niet nog nu of om ons ook op over te tot uit van voor was wat we wij zij zijn zo",Re="a ao aos as até com como da das de do dos e em entre era essa esse esta este eu foi há isso já mais mas me mesmo meu na nas no nos num numa o os ou para pela pelo por qual que quem se sem seu só sua também te tem um uma você",Le=/[\u0300-\u036F]/gu,ne=o=>o.normalize("NFD").replaceAll(Le,"").normalize("NFC").toLowerCase(),O=o=>new Set(ne(o).split(" ")),Ie={de:O(Se),en:O(be),es:O(Te),fr:O(ve),it:O(we),nl:O(Ae),none:new Set,pt:O(Re)},Ne=2,Oe=256,Q=new Map,je=o=>{const a=o!==void 0&&ye(o)?o:"none",l=Q.get(a);if(l)return l;const g=Ie[a],w=r=>{const A=(ne(r).match(/[\p{L}\p{N}]+/gu)??[]).filter(T=>T.length<=Oe);return g.size===0?A:A.filter(T=>!g.has(T))},m={document:w,profile:`${a}-v${String(Ne)}`,query:r=>{const A=w(r);return A.filter((T,L)=>A.lastIndexOf(T)===L)}};return Q.set(a,m),m},xe=(o,a)=>{if(!a.includes("."))return o[a];let l=o;for(const g of a.split(".")){if(l===null||typeof l!="object"||Array.isArray(l))return;l=l[g]}return l},Fe=(o,a)=>`${o}__fts_${a}`,Ce="__text__",X="__id__",Me=1e3,De=(o,a)=>a.document(o),q=(o,a)=>xe(o,a),ke=o=>typeof o=="string"?o:o==null?"":typeof o=="number"||typeof o=="bigint"||typeof o=="boolean"?String(o):JSON.stringify(o)??"",qe=(o,a,l)=>o!==void 0&&a!==void 0&&q(o,l.field)===q(a,l.field),ze=(o,a)=>De(ke(q(o,a.field)),je(a.language)).slice(0,Me).join(" "),We=(o,a,l)=>[...o.partitionBy??[],...o.sortBy.map(g=>g.field),...o.where?Object.keys(o.where):[]].every(g=>a[g]===l[g]),oe=o=>e.join(["__id__","__partition__",...o.sortBy.map((a,l)=>pe(l))].map(a=>e.identifier(a)),e`, `),te=(o,a,l,g,w,m)=>{const r=he(l.partitionBy??[],m),A=l.sortBy.map(L=>ee(m[L.field]??null)),T=e.join([w,r,...A].map(L=>ue(L)),e`, `);u(o,e`INSERT INTO ${e.identifier(a)} (${g}) VALUES (${T})`)},Be=(o,a,l,g,w,m)=>{if(w&&m&&We(l,w,m))return;const r=Z(a,l.name);w&&u(o,e`DELETE FROM ${e.identifier(r)} WHERE ${e.identifier("__id__")} = ${g}`),!(!m||l.where&&!Y(m,l.where))&&te(o,r,l,oe(l),g,m)},nn=o=>{const{broadcast:a,indexKeysFor:l,invalidateCache:g,recordCdc:w,schema:m,sql:r}=o,A=new Set,T=t=>m.tables[t]?.softDeleteMode?.field,L=new Set,z=(t,n)=>{const s=`${t}::${n.name}`;if(A.has(s))return;const d=G(t,n.name),c=n.by??[],f=T(t),h=new Map,y=u(r,e`SELECT id, _creationTime, ${e.identifier(M)} FROM ${e.identifier(t)}`).toArray();for(const v of y){const $=D(v);if(!$||!J($,f)||n.where&&!P($,n.where))continue;const E=N(c,$);V(h,E,n,$)}u(r,e`DELETE FROM ${e.identifier(d)}`);const R=Math.floor($e.boundParams/3),I=[...h];for(let v=0;v<I.length;v+=R){const $=I.slice(v,v+R),E=e.join($.map(([i,p])=>e`(${i}, ${p.value}, ${p.count})`),e`, `);u(r,e`INSERT INTO ${e.identifier(d)} (${j}, ${S}, ${_}) VALUES ${E}`)}A.add(s)},ie=(t,n,s)=>{const d=n.by??[],c=n.field??"",f=[],h=(E,i)=>{const p=ee(i);p===null?f.push(e`${k(E)} IS NULL`):f.push(e`${k(E)} = ${p}`)};for(const E of d)h(E,s[E]??null);const y=T(t);y!==void 0&&h(y,null);for(const[E,i]of Object.entries(n.where??{}))h(E,i!==null&&typeof i=="object"&&!Array.isArray(i)?i.eq:i);const R=f.length>0?e` WHERE ${e.join(f,e` AND `)}`:e``,I=m.tables[t]?.shape[c];if(I&&ge(I)){const E=u(r,e`SELECT id, _creationTime, ${e.identifier(M)} FROM ${e.identifier(t)}${R}`).toArray(),i=new Map;for(const p of E){const b=D(p);b&&V(i,"",n,b)}return{value:i.get("")?.value??null}}const v=de(n.op),$=k(c);return{value:u(r,e`SELECT ${e.raw(v)}(${$}) AS value FROM ${e.identifier(t)}${R}`).one().value??null}},re=(t,n,s,d)=>{const c=G(t,n.name),{op:f}=n,h=n.field??"",y=i=>{u(r,e`DELETE FROM ${e.identifier(c)} WHERE ${j} = ${i} AND ${_} <= 0`)},R=T(t),I=i=>!n.where||P(i,n.where),v=i=>J(i,R)&&I(i);d!==void 0&&f!=="count"&&I(d)&&F(d[h]);const $=s&&v(s)?s:void 0,E=d&&v(d)?d:void 0;if(!(!$&&!E)){if(f==="count"){for(const[i,p]of[[$,-1],[E,1]]){if(!i)continue;const b=N(n.by??[],i);u(r,C(c,b,p,p,e`${S} = ${S} + excluded.${S}, ${_} = ${_} + excluded.${_}`))}$&&y(N(n.by??[],$));return}if(f==="sum"||f==="avg"){for(const[i,p]of[[$,-1],[E,1]]){if(!i)continue;const b=F(i[h]);if(b===void 0)continue;const x=N(n.by??[],i);u(r,C(c,x,p*b,p,e`${S} = COALESCE(${S}, 0) + excluded.${S}, ${_} = ${_} + excluded.${_}`))}$&&y(N(n.by??[],$));return}if($){const i=N(n.by??[],$),p=F($[h]),b=u(r,e`SELECT ${S} AS value, ${_} AS count FROM ${e.identifier(c)} WHERE ${j} = ${i}`).toArray()[0],x=(b?.count??0)-1;if(x<=0)u(r,e`DELETE FROM ${e.identifier(c)} WHERE ${j} = ${i}`);else if(b&&p!==void 0&&b.value!==null&&p===b.value){const le=ie(t,n,$);u(r,e`UPDATE ${e.identifier(c)} SET ${S} = ${le.value}, ${_} = ${x} WHERE ${j} = ${i}`)}else u(r,e`UPDATE ${e.identifier(c)} SET ${_} = ${_} - 1 WHERE ${j} = ${i}`)}if(E){const i=N(n.by??[],E),p=F(E[h]);if(p===void 0)u(r,C(c,i,null,1,e`${_} = ${_} + 1`));else{const b=f==="min"?"MIN":"MAX";u(r,C(c,i,p,1,e`${S} = ${e.raw(b)}(COALESCE(${S}, excluded.${S}), excluded.${S}), ${_} = ${_} + 1`))}}}},ae=t=>{for(const n of m.tables[t]?.aggregateIndexes??[])z(t,n)},W=(t,n,s)=>{for(const d of m.tables[t]?.aggregateIndexes??[])re(t,d,n,s)},B=(t,n)=>{const s=`${t}::rank::${n.name}`;if(L.has(s))return;const d=Z(t,n.name),c=u(r,e`SELECT id, _creationTime, ${e.identifier(M)} FROM ${e.identifier(t)}`).toArray();u(r,e`DELETE FROM ${e.identifier(d)}`);const f=oe(n);for(const h of c){const y=D(h);!y||n.where&&!Y(y,n.where)||te(r,d,n,f,y._id,y)}L.add(s)},se=t=>{for(const n of m.tables[t]?.rankIndexes??[])B(t,n)},H=(t,n,s,d)=>{for(const c of m.tables[t]?.rankIndexes??[])Be(r,t,c,n,s,d)},U=(t,n,s,d)=>{const c=m.tables[t]?.searchIndexes??[];if(!(c.length===0||!ce(r)))for(const f of c){if(qe(d,s,f))continue;const h=Fe(t,f.name);u(r,e`DELETE FROM ${e.identifier(h)} WHERE ${e.identifier(X)} = ${n}`),s&&u(r,e`INSERT INTO ${e.identifier(h)} (${e.identifier(Ce)}, ${e.identifier(X)}) VALUES (${ze(s,f)}, ${n})`)}},K=(t,n,s)=>{for(const d of m.tables[t]?.geoIndexes??[]){const c=fe(t,d.name);u(r,e`DELETE FROM ${e.identifier(c)} WHERE ${e.identifier("__id__")} = ${n}`);const f=s?.[d.field];if(f!==null&&typeof f=="object"&&typeof f.lat=="number"&&typeof f.lng=="number"){const{lat:h,lng:y}=f,R=me({lat:h,lng:y},d.precision??Ee);u(r,e`INSERT INTO ${e.identifier(c)} (${e.identifier("__id__")}, ${e.identifier("__geohash__")}, ${e.identifier("__lat__")}, ${e.identifier("__lng__")}) VALUES (${n}, ${R}, ${h}, ${y})`)}}};return{ensureBackfilledForTable:ae,ensureBackfilledIndex:z,ensureRankBackfilled:B,ensureRankBackfilledForTable:se,syncAggregates:W,syncCompanionsForInsert:(t,n,s)=>{U(t,n,s),K(t,n,s),W(t,void 0,s),H(t,n,void 0,s),g(t,n,s),w(t,n,"insert",s),a({indexKeys:l(t,s),key:n,op:"insert",row:s,table:t})},syncGeo:K,syncRanks:H,syncSearch:U}};export{oe as B,nn as S,X as T,te as W,Fe as c,Ce as l,De as n,je as x,ze as y};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{createShardCtxDb as b}from"./NotUniqueError-
|
|
1
|
+
import{createShardCtxDb as b}from"./NotUniqueError-DYo7r67J.mjs";import{createRelayLink as I}from"./DEFAULT_MAX_RELAYS-Cinp9pPC.mjs";import{ConflictError as N}from"./ConflictError-C8GtJmjS.mjs";import{runShardMigrations as v}from"./runShardMigrations-BCuK60KT.mjs";import{relayName as q}from"./DEFAULT_PROMOTION_THRESHOLDS-DYGNAo1I.mjs";const C=(_,m={})=>({_meta:{column:{notNull:!0,...m}},kind:_}),D=(_,m,E)=>{const{describe:k,expect:i,it:f}=E;k(`engine contract: ${_}`,()=>{k("optimistic concurrency",()=>{const g=p=>({tables:{items:{indexes:[],shape:{title:C("string"),version:C("number",{notNull:!1})},triggerMap:{clobber:{handler:()=>{p.exec(`UPDATE "items" SET "__doc__" = json_set("__doc__", '$.version', 99) WHERE "id" = 'i1'`)},op:"update",timing:"before"}}}}});f("raises a CONFLICT of kind `occ` when a write's snapshot is clobbered",async()=>{const{close:p,host:d}=m();try{const c=d.sql,l=g(c);v(c,l);const s=b({schema:l,sql:c});await s.insert("items",{_id:"i1",title:"first",version:1},{allowExplicitId:!0}),await i(s.patch("i1",{title:"second"})).rejects.toBeInstanceOf(N)}finally{p?.()}}),f("reports the conflict as CONFLICT/409 rather than retrying it away",async()=>{const{close:p,host:d}=m();try{const c=d.sql,l=g(c);v(c,l);const s=b({schema:l,sql:c});await s.insert("items",{_id:"i1",title:"first",version:1},{allowExplicitId:!0});let r;try{await s.patch("i1",{title:"second"})}catch(t){r=t}const e=r;i(e.code).toBe("CONFLICT"),i(e.kind).toBe("occ")}finally{p?.()}}),f("leaves the row readable and unchanged after a conflict",async()=>{const{close:p,host:d}=m();try{const c=d.sql,l=g(c);v(c,l);const s=b({schema:l,sql:c});await s.insert("items",{_id:"i1",title:"first",version:1},{allowExplicitId:!0});try{await s.patch("i1",{title:"second"})}catch{}const r=await s.get("i1");i(r?.title).toBe("first"),i(r?.version).toBe(99)}finally{p?.()}}),f("raises a CONFLICT of kind `trigger` when a trigger writes its own row through the db",async()=>{const{close:p,host:d}=m();try{const c=d.sql,l={tables:{items:{indexes:[],shape:{title:C("string"),version:C("number",{notNull:!1})},triggerMap:{recurse:{handler:async(t,o)=>{await t.db.patch(o.doc._id,{version:99})},op:"update",timing:"before"}}}}};v(c,l);const s=b({schema:l,sql:c});await s.insert("items",{_id:"i1",title:"first",version:1},{allowExplicitId:!0});let r;try{await s.patch("i1",{title:"second"})}catch(t){r=t}const e=r;i(e).toBeInstanceOf(N),i(e.code).toBe("CONFLICT"),i(e.kind).toBe("trigger")}finally{p?.()}})}),k("shape-poke ordering",()=>{const g="shard-a",p={args:{},name:"messages"},d=(e,t,o,a)=>e.accept(t?.()??{},{connectionId:o,shapes:{[a]:p}}),c=(e,t)=>{let o=0,a=0;const n=u=>()=>{throw new Error(`the relay poke path must not reach RelayHost.${u}`)},h={fetch:(u,O)=>{if(JSON.parse(O?.body??"{}").type!=="relay_shape_subscribe")return Promise.resolve(new Response(void 0,{status:204}));const B=t[a];if(a+=1,B===void 0)throw new Error("the relay asked for more seeds than this fixture supplies");return Promise.resolve(Response.json(B))}},y={get:()=>h,getByName:()=>h,idFromName:u=>u},w={buildShapeDiff:n("buildShapeDiff"),computeOpLogShapeSeed:n("computeOpLogShapeSeed"),currentCdcEpoch:n("currentCdcEpoch"),deliverWhisperLocal:n("deliverWhisperLocal"),doName:()=>q(g,0),env:()=>({SHARD:y}),getWebSockets:()=>e.getSockets(),maskMetadata:n("maskMetadata"),nextPokeId:()=>(o+=1,`poke-${String(o)}`),readAttachment:u=>u.deserializeAttachment?.(),recordShapePokeFanout:()=>{},resolveShape:n("resolveShape"),rlsMetadata:n("rlsMetadata"),shardBinding:()=>"SHARD",sql:n("sql")},S=I(w);if(S===void 0)throw new Error("expected a relay link for a `…::relay::N` name");return S},l=e=>new Request("https://relay.internal/_lunora/relay",{body:JSON.stringify(e),headers:{"content-type":"application/json"},method:"POST"}),s=async(e,t,o)=>{const a=await e.seedRelayShape(t,o,p,{identity:void 0,userId:void 0});if(a!=="ok")throw new Error(`seed failed: ${JSON.stringify(a)}`)},r=(e={})=>l({...p,checkpoint:20,epoch:"e1",fromCursor:10,rowsPatch:[{id:"r1",op:"upsert",value:{title:"hello"}}],type:"relay_shape_poke",...e});f("frames a poke as pokeStart → pokePart per shape → pokeEnd, under one poke id",async()=>{const{close:e,createSocket:t,readFrames:o,sockets:a}=m();try{const n=c(a,[{cursor:10,epoch:"e1",frames:[]}]),h=d(a,t,"c-alice","s1");await s(n,h,"s1"),await n.handleControl(r());const y=(await o(h)).map(w=>JSON.parse(w));i(y.map(w=>w.type)).toStrictEqual(["pokeStart","pokePart","pokeEnd"]),i(new Set(y.map(w=>w.pokeId)).size).toBe(1),i(y[1]?.shapeId).toBe("s1"),i(y[2]?.checkpoint).toBe(20)}finally{e?.()}}),f("delivers a poke only to sockets whose cursor matches, and advances them past it",async()=>{const{close:e,createSocket:t,readFrames:o,sockets:a}=m();try{const n=c(a,[{cursor:10,epoch:"e1",frames:[]},{cursor:7,epoch:"e1",frames:[]}]),h=d(a,t,"c-alice","s1"),y=d(a,t,"c-bob","s2");await s(n,h,"s1"),await s(n,y,"s2"),await n.handleControl(r());const w=await o(h);i(w.length).toBe(3);const S=await o(y);i(S.length).toBe(0),await n.handleControl(r());const u=await o(h);i(u.length).toBe(3)}finally{e?.()}}),f("skips a socket whose cursor matches under a different CDC epoch",async()=>{const{close:e,createSocket:t,readFrames:o,sockets:a}=m();try{const n=c(a,[{cursor:10,epoch:"e1",frames:[]}]),h=d(a,t,"c-alice","s1");await s(n,h,"s1"),await n.handleControl(r({epoch:"e2"}));const y=await o(h);i(y.length).toBe(0),await n.handleControl(r());const w=await o(h);i(w.length).toBe(3)}finally{e?.()}})}),k("RLS identity under live subscription",()=>{const g="shard-a",p={args:{},name:"lobby-messages"},d={args:{},name:"my-orders"},c=s=>{const r=[],e=[],t={fetch:(a,n)=>(r.push(JSON.parse(n?.body??"{}")),Promise.resolve(new Response(void 0,{status:204})))},o=I({buildShapeDiff:()=>[{id:"r1",op:"upsert",value:{}}],computeOpLogShapeSeed:()=>({baseCheckpoint:void 0,cursor:10,epoch:"e1",rowsPatch:[]}),currentCdcEpoch:()=>"e1",deliverWhisperLocal:()=>0,doName:()=>g,env:()=>({SHARD:{get:()=>t,getByName:()=>t,idFromName:a=>a}}),getWebSockets:()=>[],maskMetadata:()=>({columns:[]}),nextPokeId:()=>"poke-1",readAttachment:()=>({}),recordShapePokeFanout:()=>{},resolveShape:(a,n,h)=>(e.push(h),a===d.name?{columns:["id"],effectiveWhere:{org:h?.identity?.org??"anonymous"},global:!1,table:"orders"}:{columns:["id"],effectiveWhere:{room:"lobby"},global:!1,table:"messages"}),rlsMetadata:()=>({policies:[]}),shardBinding:()=>"SHARD",sql:()=>s});if(o===void 0)throw new Error("expected an owner link for an un-suffixed DO name");return{owner:o,posts:r,resolvedUnder:e}},l=async(s,r)=>{await s.handleControl(new Request("https://owner.internal/_lunora/relay",{body:JSON.stringify({...r,connectionId:"c-alice",identity:{org:"acme"},relayIndex:0,subId:"s1",type:"relay_shape_subscribe",userId:"u1"}),headers:{"content-type":"application/json"},method:"POST"}))};f("seeds a subscriber under its own forwarded identity, never the anonymous one",async()=>{const{close:s,host:r}=m();try{const{owner:e,resolvedUnder:t}=c(r.sql);await l(e,d),i(t.some(o=>o?.userId==="u1"&&o.identity?.org==="acme")).toBe(!0)}finally{s?.()}}),f("routes an identity-scoped shape to a per-socket poke, not the cohort multicast",async()=>{const{close:s,host:r}=m();try{const{owner:e,posts:t}=c(r.sql);await l(e,d),t.length=0,await e.onFlush(new Set(["orders"]),20);const o=t.filter(a=>a.type==="relay_shape_poke");i(o.length).toBe(1),i(o[0]?.targetConnectionId).toBe("c-alice")}finally{s?.()}}),f("still multicasts an identity-blind shape to the whole cohort",async()=>{const{close:s,host:r}=m();try{const{owner:e,posts:t}=c(r.sql);await l(e,p),t.length=0,await e.onFlush(new Set(["messages"]),20);const o=t.filter(a=>a.type==="relay_shape_poke");i(o.length).toBe(1),i(o[0]?.targetConnectionId).toBeUndefined()}finally{s?.()}})})})};export{D as defineEngineContractSuite};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{LunoraError as c}from"@lunora/errors";import{sql as o}from"drizzle-orm";import{quoteIdentifier as m}from"./quoteIdentifier-CObIFRhb.mjs";import{s as u,a as p}from"./wire-codec-
|
|
1
|
+
import{LunoraError as c}from"@lunora/errors";import{sql as o}from"drizzle-orm";import{quoteIdentifier as m}from"./quoteIdentifier-CObIFRhb.mjs";import{s as u,a as p}from"./wire-codec-Dh0j-GnY.mjs";import{runDrizzle as _}from"./runDrizzle-C3n5gJsk.mjs";import{b as E}from"./sql-projection-jfoe331H.mjs";import"./serializeSqlValue-BR4UOWoP.mjs";const T=/^[A-Za-z_$][\w$]*$/u,S=e=>T.test(e)?e:`"${e.replaceAll("\\",String.raw`\\`).replaceAll('"',String.raw`\"`)}"`,l="__doc__",s="__originals__",R=e=>{if(Object.hasOwn(e,s))throw new c("BAD_REQUEST",`"${s}" is reserved by the row store's document encoding and cannot be used as a field name — rename the field`);let t,r;for(const[i,n]of Object.entries(e)){const a=E(n);a!==void 0&&(t??={...e},r??=Object.create(null),t[i]=a,r[i]=n)}t&&r&&(t[s]=r);try{return JSON.stringify(p(t??e))}catch(i){throw new c("BAD_REQUEST",`this document cannot be stored: ${i instanceof Error?i.message:String(i)}`)}},y=e=>{const t=u(JSON.parse(e)),{[s]:r,...i}=t;return r===null||typeof r!="object"||Array.isArray(r)?t:{...i,...r}},C=(e,t)=>`${e}__geo_${t}`,d=(e,t)=>t==="_id"||t==="id"?`${e}id`:t==="_creationTime"?`${e}_creationTime`:`json_extract(${e}${l}, '$.${S(t).replaceAll("'","''")}')`,A=e=>d("",e),v=e=>o.raw(A(e)),O=(e,t)=>d(`${m(e)}.`,t),B=(e,t)=>o.raw(O(e,t)),F=(e,t,r,i)=>o`CREATE ${i?o`UNIQUE `:o``}INDEX IF NOT EXISTS ${o.identifier(e)} ON ${o.identifier(t)} (${r})`,f=o.identifier("__key__"),I=o.identifier("__value__"),h=o.identifier("__count__"),X=(e,t,r,i,n)=>o`INSERT INTO ${o.identifier(e)} (${f}, ${I}, ${h}) VALUES (${t}, ${r}, ${i}) ON CONFLICT(${f}) DO UPDATE SET ${n}`,x=e=>{const t=[];for(const[r,i]of Object.entries(e.shape)){const n=i._meta?.column;n&&t.push([r,n])}return t},b=e=>{if(!e)return;const t=e[l];let r;typeof t=="string"?r=y(t):t&&typeof t=="object"?r=t:r={};const{id:i}=e;typeof i=="string"&&(r._id=i);const n=e._creationTime;return typeof n=="number"&&(r._creationTime=n),r},z=e=>{try{return b(e)}catch{return}},$=new WeakMap,P=e=>{const t=$.get(e);if(t!==void 0)return t;let r;try{_(e,o`CREATE VIRTUAL TABLE IF NOT EXISTS ${o.identifier("__lunora_fts_probe")} USING fts5(x)`),r=!0}catch{r=!1}finally{try{_(e,o`DROP TABLE IF EXISTS ${o.identifier("__lunora_fts_probe")}`)}catch{}}return $.set(e,r),r};export{X as A,P as C,z as D,b as E,x as I,R as L,v as N,B as O,O as S,h as T,A as _,l as a,f as c,y as g,C as h,S as j,I as p,s,F as y};
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{LunoraError as E}from"@lunora/errors";import{sql as m}from"drizzle-orm";import{runDrizzle as h}from"./runDrizzle-C3n5gJsk.mjs";import{liftSourceId as x}from"./liftSourceId-DApAbu7Q.mjs";import{normalizeSourceValue as K}from"./liftSourceId-DApAbu7Q.mjs";import{runExternalSourceTick as v,materializeExternalRowsIncremental as M}from"./materializeExternalRows-
|
|
1
|
+
import{LunoraError as E}from"@lunora/errors";import{sql as m}from"drizzle-orm";import{runDrizzle as h}from"./runDrizzle-C3n5gJsk.mjs";import{liftSourceId as x}from"./liftSourceId-DApAbu7Q.mjs";import{normalizeSourceValue as K}from"./liftSourceId-DApAbu7Q.mjs";import{runExternalSourceTick as v,materializeExternalRowsIncremental as M}from"./materializeExternalRows-C-5TKdc1.mjs";const _="__lunora_source_cursor",D=e=>e instanceof Date?`d:${e.toISOString()}`:typeof e=="bigint"?`b:${e.toString()}`:typeof e=="number"?`n:${e.toString()}`:`s:${e}`,R=e=>{const t=e.slice(2);switch(e[0]){case"b":return BigInt(t);case"d":return new Date(t);case"n":return Number(t);default:return t}},k=/^-?\d+$/,I=/^-?\d+(?:\.\d+)?$/,A=(e,t)=>e instanceof Date&&t instanceof Date?e.getTime()>t.getTime():typeof e=="bigint"&&typeof t=="bigint"||typeof e=="number"&&typeof t=="number"?e>t:typeof e=="string"&&typeof t=="string"&&I.test(e)&&I.test(t)?k.test(e)&&k.test(t)?BigInt(e)>BigInt(t):Number(e)>Number(t):String(e)>String(t),q=(e,t,a)=>{let n=a===null?void 0:R(a);for(const r of e){const s=r[t];if(s==null)continue;const i=s;(n===void 0||A(i,n))&&(n=i)}return n===void 0?null:D(n)},O=e=>{h(e,m`CREATE TABLE IF NOT EXISTS ${m.identifier(_)} (
|
|
2
2
|
table_name TEXT NOT NULL,
|
|
3
3
|
shard_key TEXT NOT NULL,
|
|
4
4
|
watermark TEXT,
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{applyCdcChanges as m}from"./CDC_LOG_TABLE-
|
|
1
|
+
import{applyCdcChanges as m}from"./CDC_LOG_TABLE-DNFFQwF_.mjs";import{selectShapeRows as f}from"./selectShapeMemberIds-Bkkug6vU.mjs";import{diffExternalSource as g,projectExternalSourceRow as c}from"./diffExternalSource-DMpkJta1.mjs";import{stableStringify as p}from"./stableStringify-BjLh4gvA.mjs";const x=async(t,s,r,e)=>{const{changes:n,nextBaseline:a}=g(s,r,e);return await m(t,n),{applied:n.length,nextBaseline:a}},E=async(t,s,r)=>{const{columns:e,deletedIds:n,table:a}=r,i=[];for(const u of s){const l=c(u,e),o=String(l._id);if(n?.has(o)){await t.get(o,a)&&i.push({id:o,op:"delete",seq:0,table:a,ts:0});continue}const d=await t.get(o,a);d&&p(c({...d,_id:o},e))===p(l)||i.push({doc:l,id:o,op:"insert",seq:0,table:a,ts:0})}return await m(t,i),{applied:i.length}},h=(t,s,r)=>{const e=new Map;for(const{doc:n,id:a}of f(t,s,void 0))e.set(a,p(c({...n,_id:a},r)));return e},R=async(t,s,r,e)=>{const n=h(t,e.table,e.columns);return x(s,r,n,e)};export{x as materializeExternalRows,E as materializeExternalRowsIncremental,h as readExternalSourceBaseline,R as runExternalSourceTick};
|
package/dist/packem_shared/{runShardMigrations-BAtfEXbB.mjs → runShardMigrations-BCuK60KT.mjs}
RENAMED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{l as I,T as N,c as S}from"./ctx-db-companions-
|
|
1
|
+
import{l as I,T as N,c as S}from"./ctx-db-companions-BJlCofon.mjs";import"@lunora/errors";import{sql as e}from"drizzle-orm";import{aggregateTableName as p}from"./aggregateTableName-DN7gk6uh.mjs";import{backfillSearchIndexesForTable as g}from"./backfillAggregateIndexes-DTOIsYbi.mjs";import{migrateCdcLog as l,migrateCdcMeta as h}from"./CDC_LOG_TABLE-DNFFQwF_.mjs";import{migrateClientWatermark as R}from"./CLIENT_WATERMARK_TABLE-LrKfdxyt.mjs";import{migrateGlobalShapeSnapshot as C}from"./GLOBAL_SHAPE_SNAPSHOT_TABLE-B2LKe4KU.mjs";import{migrateIdempotency as O}from"./IDEMPOTENCY_TABLE-tQ5mnqvw.mjs";import{migrateSearchState as u}from"./SEARCH_STATE_TABLE-DRk_SB72.mjs";import{runDrizzle as a}from"./runDrizzle-C3n5gJsk.mjs";import{a as U,N as E,y as _,I as b,C as X,c as x,p as B,T as c,h as D}from"./do-sql-DKSFK627.mjs";import{migrateDurableStreams as F}from"./appendStreamChunk-ksZYy1hZ.mjs";import{sortColumnName as M,rankTableName as Y}from"./RANK_TIEBREAK-BGk411OR.mjs";import{recordSchemaVersion as k}from"./SCHEMA_HISTORY_MAX_VERSIONS-CEK7b_7v.mjs";const y=(r,t,o)=>{for(const i of o.indexes){const n=`${t}_${i.name}`,s=e.join(i.fields.map(f=>E(f)),e`, `);a(r,_(n,t,s,i.unique??!1))}for(const[i,n]of b(o)){if(!n.unique)continue;const s=`${t}_unique_${i}`;a(r,_(s,t,E(i),!0))}},j=(r,t,o)=>{if(!(!o.searchIndexes||o.searchIndexes.length===0||!X(r))){for(const i of o.searchIndexes){const n=S(t,i.name);a(r,e`CREATE VIRTUAL TABLE IF NOT EXISTS ${e.identifier(n)} USING fts5(${e.identifier(I)}, ${e.identifier(N)} UNINDEXED)`),a(r,e`CREATE VIRTUAL TABLE IF NOT EXISTS ${e.identifier(`${n}__vocab`)} USING fts5vocab(${e.identifier(n)}, ${e.raw("instance")})`)}g(r,t,o)}},q=(r,t,o)=>{if(o.geoIndexes)for(const i of o.geoIndexes){const n=D(t,i.name);a(r,e`CREATE TABLE IF NOT EXISTS ${e.identifier(n)} (${e.identifier("__id__")} TEXT PRIMARY KEY, ${e.identifier("__geohash__")} TEXT NOT NULL, ${e.identifier("__lat__")} REAL NOT NULL, ${e.identifier("__lng__")} REAL NOT NULL)`);const s=`${t}__geo_${i.name}__btree`;a(r,_(s,n,e`${e.identifier("__geohash__")} ASC, ${e.identifier("__id__")} ASC`,!1))}},G=(r,t,o)=>{if(o.aggregateIndexes)for(const i of o.aggregateIndexes){const n=p(t,i.name);a(r,e`CREATE TABLE IF NOT EXISTS ${e.identifier(n)} (${x} TEXT PRIMARY KEY, ${B} REAL, ${c} INTEGER NOT NULL DEFAULT 0)`),a(r,e`PRAGMA table_info(${e.identifier(n)})`).toArray().some(s=>s.name==="__count__")||a(r,e`ALTER TABLE ${e.identifier(n)} ADD COLUMN ${c} INTEGER NOT NULL DEFAULT 0`)}},P=(r,t,o)=>{if(o.rankIndexes)for(const i of o.rankIndexes){const n=Y(t,i.name),s=i.sortBy.map((T,d)=>M(d)),f=s.map(T=>e`${e.identifier(T)} BLOB`),$=f.length>0?e`, ${e.join(f,e`, `)}`:e``;a(r,e`CREATE TABLE IF NOT EXISTS ${e.identifier(n)} (${e.identifier("__id__")} TEXT PRIMARY KEY, ${e.identifier("__partition__")} TEXT NOT NULL${$})`);const m=[e`${e.identifier("__partition__")} ASC`];for(const[T,d]of s.entries()){const A=i.sortBy[T]?.direction;m.push(e`${e.identifier(d)} ${e.raw(A==="desc"?"DESC":"ASC")}`)}m.push(e`${e.identifier("__id__")} ASC`);const L=`${t}__rank_${i.name}__btree`;a(r,_(L,n,e.join(m,e`, `),!1))}},te=(r,t,o={})=>{o.schemaSnapshot!==void 0&&k(r,o.schemaSnapshot.hash,o.schemaSnapshot.json),u(r);for(const[i,n]of Object.entries(t.tables))n.shardMode?.kind!=="global"&&(a(r,e`CREATE TABLE IF NOT EXISTS ${e.identifier(i)} (
|
|
2
2
|
id TEXT PRIMARY KEY,
|
|
3
3
|
_creationTime REAL NOT NULL,
|
|
4
4
|
${e.identifier(U)} TEXT NOT NULL
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{sql as e}from"drizzle-orm";import{runDrizzle as $}from"./runDrizzle-C3n5gJsk.mjs";import{N as r}from"./do-sql-
|
|
1
|
+
import{sql as e}from"drizzle-orm";import{runDrizzle as $}from"./runDrizzle-C3n5gJsk.mjs";import{N as r}from"./do-sql-DKSFK627.mjs";const E=(d,i,s,o)=>{const f=s-(i.after??0),t=[e`${r(i.field)} IS NOT NULL`,e`${r(i.field)} < ${f}`];i.softDeleteField!==void 0&&t.push(e`${r(i.softDeleteField)} IS NULL`);const a=e`SELECT id FROM ${e.identifier(i.table)} WHERE ${e.join(t,e` AND `)} LIMIT ${e.raw(String(Math.max(0,Math.floor(o))+1))}`,l=$(d,a).toArray(),n=l.length>o,m=l.slice(0,o).map(p=>p.id);return{hasMore:n,ids:m}};export{E as selectExpiredIds};
|
package/dist/packem_shared/{selectShapeMemberIds-WzxOG62k.mjs → selectShapeMemberIds-Bkkug6vU.mjs}
RENAMED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{sql as e}from"drizzle-orm";import{runDrizzle as m}from"./runDrizzle-C3n5gJsk.mjs";import{a as c,E as a,N as u}from"./do-sql-
|
|
1
|
+
import{sql as e}from"drizzle-orm";import{runDrizzle as m}from"./runDrizzle-C3n5gJsk.mjs";import{a as c,E as a,N as u}from"./do-sql-DKSFK627.mjs";import{sqliteInList as h}from"./param-CYxL68V-.mjs";import{compileWhereSql as S}from"./compileWhereSql-B3hq_v98.mjs";import{serializeSqlValue as E}from"./serializeSqlValue-BR4UOWoP.mjs";const $={fieldRef:u,serialize:E},R=i=>{if(i.length!==0)return h(e`${e.identifier("id")}`,i,!1)},p=(i,o)=>{const r=[];o&&r.push(o);const t=S(i,$);return t&&r.push(t),r.length===0?e``:e` WHERE ${e.join(r,e` AND `)}`},L=(i,o,r)=>{const t=p(r,void 0),f=m(i,e`SELECT id, _creationTime, ${e.identifier(c)} FROM ${e.identifier(o)}${t}`).toArray(),n=[];for(const s of f){const d=a(s),{id:l}=s;d!==void 0&&typeof l=="string"&&n.push({doc:d,id:l})}return n},M=(i,o,r,t)=>{if(t.length===0)return new Set;const f=p(r,R(t)),n=m(i,e`SELECT id FROM ${e.identifier(o)}${f}`).toArray();return new Set(n.map(s=>s.id))};export{M as selectShapeMemberIds,L as selectShapeRows};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{stableStringify as r}from"./stableStringify-BjLh4gvA.mjs";import{a as e}from"./wire-codec-
|
|
1
|
+
import{stableStringify as r}from"./stableStringify-BjLh4gvA.mjs";import{a as e}from"./wire-codec-Dh0j-GnY.mjs";const i=t=>r(e(t));export{i as stableWireKey};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{a as p,o as A}from"./base64-fKomMf5D.mjs";const i="$lunora.wire$",b=64,g=1024,d="__proto__",w={BigInt64Array,BigUint64Array,Float32Array,Float64Array,Int8Array,Int16Array,Int32Array,Uint8Array,Uint8ClampedArray,Uint16Array,Uint32Array},m={Error,EvalError,RangeError,ReferenceError,SyntaxError,TypeError,URIError},v=r=>{if(r===null||typeof r!="object")return!1;const a=Object.getPrototypeOf(r);return a===null||a===Object.prototype},c=(r,a=0)=>{if(a>b)throw new RangeError(`wire-codec: value nesting exceeds the ${b}-level limit`);if(r===void 0)return[i,"undefined"];if(r===null)return null;const s=typeof r;if(s==="bigint")return[i,"bigint",r.toString()];if(s==="number"){const e=r;return Number.isNaN(e)?[i,"nan"]:e===1/0?[i,"inf"]:e===-1/0?[i,"-inf"]:e}if(s!=="object")return r;if(r instanceof Date)return[i,"date",c(r.getTime(),a+1)];if(r instanceof Error){const e=r,n={};for(const f of Object.keys(e))e[f]!==void 0&&(n[f]=c(e[f],a+1));const o=[i,"error",e.name,e.message,n];return e.cause!==void 0&&o.push(c(e.cause,a+1)),o}if(r instanceof URL)return[i,"url",r.href];if(r instanceof Map)return[i,"map",[...r.entries()].map(([e,n])=>[c(e,a+1),c(n,a+1)])];if(r instanceof Set)return[i,"set",[...r].map(e=>c(e,a+1))];if(r instanceof ArrayBuffer)return[i,"bytes",p(new Uint8Array(r)),"ArrayBuffer"];if(ArrayBuffer.isView(r)){const e=r,n=e.constructor.name,o=new Uint8Array(e.buffer,e.byteOffset,e.byteLength);return n==="Uint8Array"?[i,"bytes",p(o)]:[i,"bytes",p(o),n]}if(Array.isArray(r)){const e=r.map(n=>c(n,a+1));return e.length>0&&e[0]===i?[i,"arr",e]:e}if(!v(r)){const e=r.constructor?.name??"value";throw new TypeError(`wire-codec: cannot encode a ${e} over the Lunora wire — only plain objects, arrays, and the supported built-ins (Date, Error, URL, Map, Set, ArrayBuffer/typed arrays, bigint) round-trip`)}const l=r,t={};for(const e of Object.keys(l)){const n=l[e];if(n===void 0)continue;const o=c(n,a+1);e===d?Object.defineProperty(t,e,{configurable:!0,enumerable:!0,value:o,writable:!0}):t[e]=o}return t},u=(r,a=0)=>{if(a>b)throw new RangeError(`wire-codec: value nesting exceeds the ${b}-level limit`);if(r===null||typeof r!="object")return r;if(Array.isArray(r)){if(r[0]===i)switch(r[1]){case"-inf":return-1/0;case"arr":return r[2].map(t=>u(t,a+1));case"bigint":{const t=r[2];if(typeof t!="string"||t.length>g||!/^-?\d+$/.test(t))throw new RangeError(`wire-codec: invalid or over-long bigint (max ${g} digits)`);return BigInt(t)}case"date":return new Date(u(r[2],a+1));case"map":return new Map(r[2].map(([t,e])=>[u(t,a+1),u(e,a+1)]));case"set":return new Set(r[2].map(t=>u(t,a+1)));case"url":return new URL(r[2]);case"error":{const t=r[2],e=r[3],n=(Object.hasOwn(m,t)?m[t]:void 0)??Error,o=new n(e);o.name!==t&&Object.defineProperty(o,"name",{configurable:!0,value:t,writable:!0});const f=u(r[4],a+1);for(const y of Object.keys(f))y===d?Object.defineProperty(o,y,{configurable:!0,enumerable:!0,value:f[y],writable:!0}):o[y]=f[y];return r.length>5&&Object.defineProperty(o,"cause",{configurable:!0,value:u(r[5],a+1),writable:!0}),o}case"bytes":{const t=A(r[2]),e=r[3]??"Uint8Array";if(e==="ArrayBuffer")return t.buffer.byteLength===t.byteLength?t.buffer:t.slice().buffer;const n=Object.hasOwn(w,e)?w[e]:void 0;return n?new n(t.slice().buffer):t}case"inf":return 1/0;case"nan":return Number.NaN;case"undefined":return;default:return r.map(t=>u(t,a+1))}return r.map(t=>u(t,a+1))}const s=r,l={};for(const t of Object.keys(s)){const e=u(s[t],a+1);t===d?Object.defineProperty(l,t,{configurable:!0,enumerable:!0,value:e,writable:!0}):l[t]=e}return l};export{c as a,u as s};
|
|
1
|
+
import{a as p,o as A}from"./base64-fKomMf5D.mjs";const i="$lunora.wire$",b=64,g=1024,d="__proto__",w={BigInt64Array,BigUint64Array,Float32Array,Float64Array,Int8Array,Int16Array,Int32Array,Uint8Array,Uint8ClampedArray,Uint16Array,Uint32Array},m={Error,EvalError,RangeError,ReferenceError,SyntaxError,TypeError,URIError},v=r=>{if(r===null||typeof r!="object")return!1;const a=Object.getPrototypeOf(r);return a===null||a===Object.prototype},c=(r,a=0)=>{if(a>b)throw new RangeError(`wire-codec: value nesting exceeds the ${b}-level limit`);if(r===void 0)return[i,"undefined"];if(r===null)return null;const s=typeof r;if(s==="bigint")return[i,"bigint",r.toString()];if(s==="number"){const e=r;return Number.isNaN(e)?[i,"nan"]:e===1/0?[i,"inf"]:e===-1/0?[i,"-inf"]:e}if(s!=="object")return r;if(r instanceof Date)return[i,"date",c(r.getTime(),a+1)];if(r instanceof Error){const e=r,n={};for(const f of Object.keys(e))e[f]!==void 0&&(n[f]=c(e[f],a+1));const o=[i,"error",e.name,e.message,n];return e.cause!==void 0&&o.push(c(e.cause,a+1)),o}if(r instanceof URL)return[i,"url",r.href];if(r instanceof Map)return[i,"map",[...r.entries()].map(([e,n])=>[c(e,a+1),c(n,a+1)])];if(r instanceof Set)return[i,"set",[...r].map(e=>c(e,a+1))];if(r instanceof ArrayBuffer)return[i,"bytes",p(new Uint8Array(r)),"ArrayBuffer"];if(ArrayBuffer.isView(r)){const e=r,n=e.constructor.name,o=new Uint8Array(e.buffer,e.byteOffset,e.byteLength);return n==="Uint8Array"?[i,"bytes",p(o)]:[i,"bytes",p(o),n]}if(Array.isArray(r)){const e=r.map(n=>c(n,a+1));return e.length>0&&e[0]===i?[i,"arr",e]:e}if(!v(r)){const e=r.constructor?.name??"value";throw new TypeError(`wire-codec: cannot encode a ${e} over the Lunora wire — only plain objects, arrays, and the supported built-ins (Date, Error, URL, Map, Set, ArrayBuffer/typed arrays, bigint) round-trip`)}const l=r,t={};for(const e of Object.keys(l)){const n=l[e];if(n===void 0)continue;const o=c(n,a+1);e===d?Object.defineProperty(t,e,{configurable:!0,enumerable:!0,value:o,writable:!0}):t[e]=o}return t},u=(r,a=0)=>{if(a>b)throw new RangeError(`wire-codec: value nesting exceeds the ${b}-level limit`);if(r===null||typeof r!="object")return r;if(Array.isArray(r)){if(r[0]===i)switch(r[1]){case"-inf":return-1/0;case"arr":return r[2].map(t=>u(t,a+1));case"bigint":{const t=r[2];if(typeof t!="string"||t.length>g||!/^-?\d+$/.test(t))throw new RangeError(`wire-codec: invalid or over-long bigint (max ${g} digits)`);return BigInt(t)}case"date":return new Date(u(r[2],a+1));case"map":return new Map(r[2].map(([t,e])=>[u(t,a+1),u(e,a+1)]));case"set":return new Set(r[2].map(t=>u(t,a+1)));case"url":return new URL(r[2]);case"error":{const t=r[2],e=r[3],n=(Object.hasOwn(m,t)?m[t]:void 0)??Error,o=new n(e);o.name!==t&&Object.defineProperty(o,"name",{configurable:!0,value:t,writable:!0});const f=u(r[4],a+1);for(const y of Object.keys(f))y===d?Object.defineProperty(o,y,{configurable:!0,enumerable:!0,value:f[y],writable:!0}):o[y]=f[y];return r.length>5&&Object.defineProperty(o,"cause",{configurable:!0,value:u(r[5],a+1),writable:!0}),o}case"bytes":{const t=A(r[2]),e=r[3]??"Uint8Array";if(e==="ArrayBuffer")return t.buffer.byteLength===t.byteLength?t.buffer:t.slice().buffer;const n=Object.hasOwn(w,e)?w[e]:void 0;return n?new n(t.slice().buffer):t}case"inf":return 1/0;case"nan":return Number.NaN;case"undefined":return;default:return r.map(t=>u(t,a+1))}return r.map(t=>u(t,a+1))}const s=r,l={};for(const t of Object.keys(s)){const e=u(s[t],a+1);t===d?Object.defineProperty(l,t,{configurable:!0,enumerable:!0,value:e,writable:!0}):l[t]=e}return l};export{v as A,c as a,u as s};
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@lunora/shard-engine",
|
|
3
|
-
"version": "1.0.0-alpha.
|
|
3
|
+
"version": "1.0.0-alpha.26",
|
|
4
4
|
"description": "Host-neutral reactive engine for Lunora: per-shard state, OCC, CDC, reactive subscriptions, and the poke protocol. Consumes @lunora/platform host contracts and can be mounted on any platform host.",
|
|
5
5
|
"keywords": [
|
|
6
6
|
"cloudflare",
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{a as l}from"./wire-codec-Dsy70M3Q.mjs";const c="_id",p="__lunora__",b=e=>{if(typeof e!="object"||e===null||Array.isArray(e))return;const r=e[c];return typeof r=="string"?r:void 0},y=e=>{const r=new Map,o=[];for(const s of e){const t=b(s);if(t===void 0||r.has(t))return;r.set(t,s),o.push(t)}return{byId:r,order:o}},g=(e,r)=>{const o=e.order.filter(t=>r.byId.has(t)),s=r.order.filter(t=>e.byId.has(t));return o.length!==s.length?!1:o.every((t,n)=>s[n]===t)},h=(e,r,o,s)=>{const t=[];for(const n of e.order)r.byId.has(n)||t.push({delta:{key:n,op:"delete",table:o},frame:`{"key":${JSON.stringify(n)},"op":"delete","table":${s}}`});return t},m=(e,r,o,s)=>{const t=[];for(const n of r.order){const a=r.byId.get(n),i=e.byId.get(n),f=JSON.stringify(l(a)),d=i===void 0?void 0:JSON.stringify(i);if(d===f)continue;const u=d===void 0?"insert":"update";t.push({delta:{key:n,op:u,row:a,table:o},frame:`{"key":${JSON.stringify(n)},"op":"${u}","row":${f},"table":${s}}`})}return t},S=(e,r,o,s)=>{let t;try{t=JSON.parse(e)}catch{return}if(!Array.isArray(t)||!Array.isArray(r))return;const n=y(t),a=y(r);if(n===void 0||a===void 0||!g(n,a))return;const i=o===""?p:o,f=JSON.stringify(i),d=[...h(n,a,i,f),...m(n,a,i,f)];if(!(d.length>a.order.length)){if(s!==void 0)for(const{frame:u}of d)s.push(u);return d.map(({delta:u})=>u)}},$=(e,r)=>{try{return e.send(r),!0}catch{return!1}},I=(e,r,o,s,t)=>{const n=JSON.stringify(r),a=t===void 0?"":`,"lastMutationId":${String(t)}`;let i=!0;for(const f of o)$(e,`{"type":"delta","id":${n},"delta":${f}${a}${s}}`)||(i=!1);return i},w=async e=>{let r=0;for(;r<100;){r+=1;const{bufferedAmount:o}=e;if(typeof o!="number"||o<1048576)return;await new Promise(s=>{setTimeout(s,20)})}};export{w as awaitWsDrain,I as sendDeltaFrames,S as subscriptionListDeltas,$ as trySendFrame};
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{S as C,W as R,B as f}from"./ctx-db-companions-c12P7dbv.mjs";import"@lunora/errors";import"drizzle-orm";import"./AGGREGATE_SQL_FUNCTION-CTo0-9iZ.mjs";import"./aggregateTableName-DgYMC5tr.mjs";import"./runDrizzle-C3n5gJsk.mjs";import"./do-sql-C7qrlm6-.mjs";import"./param-CYxL68V-.mjs";import"./GEO_DEFAULT_PRECISION-DyI5zggj.mjs";import"./applySelect-UY-o13Ia.mjs";import"./RANK_TIEBREAK-DDtST3gN.mjs";import"./sql-projection-jfoe331H.mjs";import"./serializeSqlValue-BR4UOWoP.mjs";export{C as createCompanionSync,R as insertRankRow,f as rankColumnsSql};
|