@lunora/shard-engine 1.0.0-alpha.22 → 1.0.0-alpha.23

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.
Files changed (40) hide show
  1. package/dist/conformance/index.mjs +1 -1
  2. package/dist/index.d.mts +6 -2
  3. package/dist/index.d.ts +6 -2
  4. package/dist/index.mjs +1 -1
  5. package/dist/packem_shared/ADMIN_FUNCTIONS-BFYAiahG.mjs +1 -0
  6. package/dist/packem_shared/{AGG_COUNT-CqQLWpb4.mjs → AGG_COUNT-DjIzJ7nc.mjs} +1 -1
  7. package/dist/packem_shared/{AUDIT_LOG_TABLE-C6nwXFPd.mjs → AUDIT_LOG_TABLE-0FKs74RO.mjs} +1 -1
  8. package/dist/packem_shared/{CDC_LOG_TABLE-ZqcflEen.mjs → CDC_LOG_TABLE-CIfexI1y.mjs} +1 -1
  9. package/dist/packem_shared/{CLIENT_WATERMARK_TABLE-CzApRlyv.mjs → CLIENT_WATERMARK_TABLE-BogWgD2Q.mjs} +1 -1
  10. package/dist/packem_shared/{DATA_MIGRATION_STATE_TABLE-BrpAGtXf.mjs → DATA_MIGRATION_STATE_TABLE-BcmXmY5q.mjs} +1 -1
  11. package/dist/packem_shared/{GLOBAL_SHAPE_SNAPSHOT_TABLE-soMJDSBs.mjs → GLOBAL_SHAPE_SNAPSHOT_TABLE-T5smo6RP.mjs} +1 -1
  12. package/dist/packem_shared/{IDEMPOTENCY_TABLE-Bvu9JkiL.mjs → IDEMPOTENCY_TABLE-DPFwgQbE.mjs} +1 -1
  13. package/dist/packem_shared/{MAIL_RETENTION-BefR9Sei.mjs → MAIL_RETENTION-Cp9LWzM4.mjs} +1 -1
  14. package/dist/packem_shared/NotUniqueError-DJf3W9gG.mjs +1 -0
  15. package/dist/packem_shared/{QUEUE_TABLE-DgBqWrXX.mjs → QUEUE_TABLE-C1mp0Du0.mjs} +1 -1
  16. package/dist/packem_shared/{SCHEMA_HISTORY_MAX_VERSIONS-BEU0CuW5.mjs → SCHEMA_HISTORY_MAX_VERSIONS-CGlXjXRT.mjs} +1 -1
  17. package/dist/packem_shared/{SEARCH_STATE_TABLE-BZ_fxI5l.mjs → SEARCH_STATE_TABLE-MDlr30EJ.mjs} +1 -1
  18. package/dist/packem_shared/{backfillAggregateIndexes-DmqOHg0U.mjs → backfillAggregateIndexes-Czk8MQ3M.mjs} +1 -1
  19. package/dist/packem_shared/{buildReprojectionMigration-Ctl4r84d.mjs → buildReprojectionMigration-DMMWPqvy.mjs} +1 -1
  20. package/dist/packem_shared/compileWhereSql-DxD5mzDy.mjs +1 -0
  21. package/dist/packem_shared/computeRankPage-CPVNOrM5.mjs +1 -0
  22. package/dist/packem_shared/{createCompanionSync-COw1Uy6a.mjs → createCompanionSync-BPQ1EJ06.mjs} +1 -1
  23. package/dist/packem_shared/ctx-db-companions-D2ZMFBrP.mjs +1 -0
  24. package/dist/packem_shared/{defineEngineContractSuite-B6nrsKSE.mjs → defineEngineContractSuite-eFffNiTW.mjs} +1 -1
  25. package/dist/packem_shared/{do-sql-1Yi1_Yq0.mjs → do-sql-Cg_QiQYA.mjs} +1 -1
  26. package/dist/packem_shared/{isSoftDeleted-Bo-y3DOe.mjs → isSoftDeleted-ZosHVk5V.mjs} +1 -1
  27. package/dist/packem_shared/{materializeExternalRows-DcCENzpV.mjs → materializeExternalRows-CUrDeD82.mjs} +1 -1
  28. package/dist/packem_shared/param-C68MV3DD.mjs +1 -0
  29. package/dist/packem_shared/{runDrizzle-B6rnz3so.mjs → runDrizzle-CgYGDEeB.mjs} +1 -1
  30. package/dist/packem_shared/{runShardMigrations-BqO6HPtX.mjs → runShardMigrations-CtlcSZ3r.mjs} +1 -1
  31. package/dist/packem_shared/{selectExpiredIds-C6nQK7E2.mjs → selectExpiredIds-DLKts8V0.mjs} +1 -1
  32. package/dist/packem_shared/selectShapeMemberIds-EPo0xxs_.mjs +1 -0
  33. package/package.json +1 -1
  34. package/dist/packem_shared/ADMIN_FUNCTIONS-OnYxyTXW.mjs +0 -1
  35. package/dist/packem_shared/NotUniqueError-CVHdtVw6.mjs +0 -1
  36. package/dist/packem_shared/compileWhereSql-B4rPariq.mjs +0 -1
  37. package/dist/packem_shared/computeRankPage-QK8SeTZ-.mjs +0 -1
  38. package/dist/packem_shared/ctx-db-companions-BTi8DLUl.mjs +0 -1
  39. package/dist/packem_shared/param-B5lF5Jd9.mjs +0 -1
  40. package/dist/packem_shared/selectShapeMemberIds-BdBcbrUP.mjs +0 -1
@@ -1 +1 @@
1
- import{defineEngineContractSuite as t}from"../packem_shared/defineEngineContractSuite-B6nrsKSE.mjs";export{t as defineEngineContractSuite};
1
+ import{defineEngineContractSuite as t}from"../packem_shared/defineEngineContractSuite-eFffNiTW.mjs";export{t as defineEngineContractSuite};
package/dist/index.d.mts CHANGED
@@ -1016,6 +1016,8 @@ interface RenderedSql {
1016
1016
  }
1017
1017
  declare const renderSql: (engine: SqlEngine, query: SQL) => RenderedSql;
1018
1018
  declare const param: (value: unknown) => SQL;
1019
+ declare const unionAll: (branches: ReadonlyArray<SQL>) => SQL;
1020
+ declare const sqliteInList: (reference: SQL, items: ReadonlyArray<unknown>, negated: boolean, budget?: number) => SQL;
1019
1021
  interface ExternalSourceDiffResult {
1020
1022
  changes: CdcChange[];
1021
1023
  nextBaseline: Map<string, string>;
@@ -2051,10 +2053,12 @@ declare const selectExpiredIds: (sql: SqlExec, spec: TtlSweepSpec, now: number,
2051
2053
  type FieldRefSql = (field: string) => SQL;
2052
2054
  type SerializeValue = (value: unknown) => unknown;
2053
2055
  interface WhereSqlStrategy {
2056
+ containsExpr?: (reference: SQL, term: SQL) => SQL;
2054
2057
  fieldRef: FieldRefSql;
2055
- likeContains?: (reference: SQL, term: SQL) => SQL;
2058
+ inList?: (reference: SQL, items: ReadonlyArray<unknown>, negated: boolean, budget?: number) => SQL;
2056
2059
  relationExists?: (request: unknown) => SQL;
2057
2060
  serialize: SerializeValue;
2058
2061
  }
2062
+ declare const literalInList: (reference: SQL, items: ReadonlyArray<unknown>, negated: boolean) => SQL;
2059
2063
  declare const compileWhereSql: (where: WhereInput | undefined, strategy: WhereSqlStrategy) => SQL | undefined;
2060
- export { ADMIN_FUNCTIONS, ADMIN_FUNCTION_PREFIX, AGGREGATE_SQL_FUNCTION, AGG_COUNT, AGG_KEY, AGG_VALUE, AUDIT_LOG_TABLE, type AdvisorProcedure, type AdvisorProceduresResult, type AdvisoriesResult, type AdvisoryFinding, type AggregateIndexDefinitionLike, type AggregateOp, type AggregateOptions, type AggregateResult, type AggregateTally, type AppendAuditEntry, type ApplyOnDeleteOptions$1 as ApplyOnDeleteOptions, type AuditEntry, type AuditLogResult, type BroadcastDelta, CDC_LOG_TABLE, CDC_META_TABLE, CLIENT_WATERMARK_TABLE, type CacheEntry, type CapturedMailRow, type CdcChange, type ChangedKeys, type Clock, type ColumnMeta, type ColumnMetaLike, type CompanionSync, type CompanionSyncDeps, ConflictError, type ConflictKind, type CountArgs, CountRlsUnsupportedError, type CreateWorkflowInstanceResult, type CrossShardReadArgs, type CtxDbOptions, DATA_MIGRATION_STATE_TABLE, DEFAULT_FANOUT_TOPIC_LIMIT, DEFAULT_MAX_RELATION_KEYS, DEFAULT_MAX_RELAYS, DEFAULT_PROMOTION_THRESHOLDS, DEFAULT_TRANSACTION_LIMITS, DOC_COLUMN, type DataMigrationDocument, type DataMigrationLike, type DataMigrationTransform, type DatabaseWriterLike, type DependencyTracker, type DeployInfo, type ExportRow, type ExportShardAdminArgs, type ExportShardArgs, type ExternalSourceDiffResult, type ExternalSourceLike, FLAGS_FUNCTION_PREFIX, type FacetColumnOptions, type FacetColumnResult, type FacetValue, type FanoutMetricsResult, type FanoutPathCounters, type FanoutTopicStat, type FieldOperators, type FilterClause, type FilterOperator, type FlagEvaluation, type FlagsResult, type FunctionCallStat, type FunctionScanAttribution, type FunctionStatsResult, GEO_DEFAULT_PRECISION, GLOBAL_SHAPE_SNAPSHOT_TABLE, type GeoBoundingBox, type GeoFilterBuilderLike, type GeoIndexDefinitionLike, type GeoPoint, type GeoScoredDocument, type GroupByEntry, type GroupByOptions, type GuardableSchema$1 as GuardableSchema, IDEMPOTENCY_TABLE, type IdGenerator, type IdempotentRecord, type ImportError, type ImportShardAdminArgs, type ImportShardArgs, type ImportShardResult, type IncrementalMaterializeResult, type IndexDefinitionLike, type IndexKeyEntry, type IndexRangeBuilderLike, type KeyRange, type LifecycleDispatchInfo, type LifecycleEvent, MAIL_RETENTION, MAIL_TABLE, MAX_PAGE_SIZE, MAX_SQL_ROWS, type MaskColumnMetadata, type MaskPoliciesResult, type MaterializeResult, type MigrationDirection, type MigrationRunResult, type MigrationStatus, type MigrationStatusRow, type MutationDelta, type NestedWith, NotFoundError, NotUniqueError, type OnDeleteActionLike, type OrderByClause, type OrderByInput, type OrderKey, OwnerRelay, type OwnerRelayFrame, type PaginationOptions, type PitrBookmarkResult, type PitrRestoreArgs, type PitrRestoreResult, type PitrStorage, type PokeFrameMeta, type PromotionState, type PromotionThresholds, QUEUE_TABLE, type QueryArgs, type QueryPage, type QueueMessageOutcome, type QueueMessageRow, type QueueMetadata, type QueuesResult, RANK_TIEBREAK, RELATION_EXISTS_KEY, RELATION_FUNCTION_PREFIX, REPROJECTION_MIGRATION_PREFIX, RLS_UNWRAP_SYMBOL, type RankBeforeOptions, type RankBeforeResult, type RankDirection, type RankIndexDefinitionLike, type RankOptions, type RankPage, type RankPageComputation, type RankPageDeps, type RankPageOptions, type RankPageRow, type RankPageRowKey, type RankResult, type RankSortKeyLike, ReactiveCache, type ReactiveCacheOptions, type ReadFootprint, type ReadHook, type ReadTablePageOptions, type RecordMailInput, type RecordQueueMessageInput, type RelationDefinitionLike, type RelationExistsMarker, type RelayAttach, type RelayDetach, type RelayFrame, type RelayHost, RelayMember, type RelayShapePoke, type RelayShapeSeed, type RelayShapeSubscribe, type RenderedSql, type ReplicaFollowerHost, type ReplicaOwnerHost, type ReplicaReadiness, type ResolveRelationPredicatesOptions, type ResolveWithOptions, type ResolveWithResult, type ResolvedShape, type RestrictableQueryOptions, type RlsPoliciesResult, type RlsPolicyMetadata, RlsRequiredError, type RlsRoleMetadata, type RpcRequest, type RunDataMigrationOptions, type RunTriggersOptions, SCAN_DEP, SCHEMA_HISTORY_MAX_VERSIONS, SEARCH_STATE_TABLE, type SchedulableWorkflowReferenceLike, type ScheduledFunctionDoc, type SchedulerLike, type SchemaLike, type ScoredDocument, type SearchFilterBuilderLike, type SearchIndexDefinitionLike, type SearchScoredDocument, type SelectMatchingIdsOptions, type ServerDefaultContextLike, type SettingEntry, type SettingKind, type SettingsResult, type ShapePokePart, type ShapeRow, type ShapeRowOp, type ShapeSubscriptionQuery, type ShardRankPageResult, ShardRunner, type ShardRunnerOptions, type ShardSiblingHost, type ShardSocketLike, type SocketAttachment, type SortDirection, type SourceClientLike, type SourceCursorLike, type SourceRefresh, type SqlConsoleResult, type SqlCursor, type SqlEngine, type SqlExec, type SqlLintResult, type StorageMetadata, type StorageReference, type StorageReferenceResult, type StorageRuleMetadata, type StorageRulesResult, type StudioFeaturesResult, type SubscriptionConnection, type SubscriptionEnvelope, type SubscriptionIdentity, type SubscriptionInfo, type SubscriptionQuery, type SubscriptionReadFootprint, type SubscriptionsResult, type SystemDatabaseReader, type SystemDoc, type SystemQuery, type SystemReaderOptions, type SystemReaderSchedulerLike, type SystemReaderStorageLike, type SystemTableName, type TableColumnsResult, type TableDefinitionLike, type TableIndexInfo, type TableIndexesResult, type TableInfo, type TablePage, type TableReaderLike, type TablesColumnsResult, type TablesIndexesResult, type TransactionHeadroom, TransactionHeadroomTracker, type TransactionLimits, type TransactionSqlLike, type TriggerContextLike, type TriggerDefinitionLike, type TriggerEventLike, type TriggerOpLike, type TriggerTimingLike, type TtlSweepSpec, type ValidatorLike, type WhereInput, type WhereSqlStrategy, type WithInput, type WorkflowInstanceState, type WorkflowInstanceStatusResult, type WorkflowMetadata, type WorkflowsResult, type WriteEvent, type WriteHook, advanceClientWatermark, aggUpsertSql, aggregateSqlFunction, aggregateTableName, appendAuditEntry, appendCdcChange, applyCdcChanges, applyOnDelete, applySelect, armRestore, assertFlatPredicate, assertReadonly, assertShapeShardable, assertValidClientId, awaitWsDrain, backfillAggregateIndexes, backfillRankIndexes, backfillSearchIndexes, backfillSearchIndexesForTable, boundingBoxCenter, boundingBoxGeohashes, buildIndexRange, buildPokeFrames, buildReprojectionMigration, buildSeekBeforeWhere, buildSeekWhere, buildSettings, bumpCdcEpoch, clampPromotionThresholds, clearCapturedMail, clearQueueMessages, coerceAggregateNumber, compileWhereSql, computeRankPage, containsRelationPredicate, countLegacyRows, coveringGeohashes, createCompanionSync, createDependencyTracker, createFanoutCounters, createIndexSql, createReadFootprint, createRelayLink, createReplicaLink, createShardCtxDb, createSystemReader, decodeCursor, deleteGlobalShapeSnapshot, deleteGlobalShapeSnapshotsForConnection, depKey, diffExternalSource, diffGlobalMembership, distinctValues, encodeAggregateKey, encodeCursor, encodeGeohash, encodePartitionKey, encodeRowsPatch, ensureAuditTable, ensureMailTable, exportShardRows, exportShardTable, facetColumn, fanOutScalarCounts, findStorageReferences, foldAggregateTally, gateReplicaDispatch, geoTableName, guardWriter, handleReplicaControl, hasTrigger, haversineMeters, hydrateDocsById, importShardRows, indexKeysForRow, isDevEnvironment, isFtsAvailable, isLossyBody, isRelationPredicate, isSoftDeleted, isSourceDue, jsonPath, jsonPathSql, keysTouchRanges, liftSourceId, lintReadonlySql, listTables, matchesRankStaticWhere, matchesStaticWhere, materializeExternalRows, materializeExternalRowsIncremental, mergeChangedKeys, mergeWhere, migrateCdcLog, migrateCdcMeta, migrateClientWatermark, migrateGlobalShapeSnapshot, migrateIdempotency, migrateSearchState, minCdcSeq, nextPromotionState, normalizeCountArgument, normalizeIdStructurally, normalizeOrderKeys, normalizeSourceDocument, normalizeSourceValue, param, parseExportShardArgs, parseImportShardArgs, planAggregateLookup, pointInBoundingBox, projectColumns, pullExternalSourceIncrementalTick, pullExternalSourceTick, qualifiedJsonPath, qualifiedJsonPathSql, quoteIdentifier, rankKeyFromDocument as rankKeyFromDoc, rankTableName, reactiveCacheKey, readAggregateValue, readAuditLog, readBookmark, readCapturedMail, readCdcChanges, readCdcCursor, readCdcEpoch, readClientWatermark, readExternalSourceBaseline, readGlobalShapeSnapshot, readIdempotent, readMigrationStatus, readQueueMessageById, readQueueMessages, readSchemaHistory, readSchemaVersion, readSearchBackfillState, readTablePage, recordCapturedMail, recordChangedKeys, recordFanoutPass, recordQueueMessages, recordSchemaVersion, relationHooks, relayCountFor, renderSql, reprojectableFields, reprojectionMigrationId, reprojectionTables, resolveRankPartition, resolveRelationPredicates, resolveWith, rowToDocument, runDataMigration, runDrizzle, runExternalSourceTick, runReadonlySql, runRowValidators, runShardMigrations, runSocketPool, runSql, runTriggers, selectExpiredIds, selectExportTables, selectIndexForAggregate, selectIndexForCount, selectIndexForGroupBy, selectMatchingIds, selectShapeMemberIds, selectShapeRows, sendDeltaFrames, serializeSqlValue, shapeRoutingKey, softDeleteScope, sortColumnName, stableStringify, stableWireKey, subscriptionListDeltas, summarizeFanoutTopics, summarizeSubscriptions, tableColumns, tableFromDepKey, throwingScheduler, trimCdcChanges, trimIdempotent, tryRowToDocument, trySendFrame, validateImportRow, writeGlobalShapeSnapshot, writeIdempotent, writeSearchBackfillState, writeTouchesMemo };
2064
+ export { ADMIN_FUNCTIONS, ADMIN_FUNCTION_PREFIX, AGGREGATE_SQL_FUNCTION, AGG_COUNT, AGG_KEY, AGG_VALUE, AUDIT_LOG_TABLE, type AdvisorProcedure, type AdvisorProceduresResult, type AdvisoriesResult, type AdvisoryFinding, type AggregateIndexDefinitionLike, type AggregateOp, type AggregateOptions, type AggregateResult, type AggregateTally, type AppendAuditEntry, type ApplyOnDeleteOptions$1 as ApplyOnDeleteOptions, type AuditEntry, type AuditLogResult, type BroadcastDelta, CDC_LOG_TABLE, CDC_META_TABLE, CLIENT_WATERMARK_TABLE, type CacheEntry, type CapturedMailRow, type CdcChange, type ChangedKeys, type Clock, type ColumnMeta, type ColumnMetaLike, type CompanionSync, type CompanionSyncDeps, ConflictError, type ConflictKind, type CountArgs, CountRlsUnsupportedError, type CreateWorkflowInstanceResult, type CrossShardReadArgs, type CtxDbOptions, DATA_MIGRATION_STATE_TABLE, DEFAULT_FANOUT_TOPIC_LIMIT, DEFAULT_MAX_RELATION_KEYS, DEFAULT_MAX_RELAYS, DEFAULT_PROMOTION_THRESHOLDS, DEFAULT_TRANSACTION_LIMITS, DOC_COLUMN, type DataMigrationDocument, type DataMigrationLike, type DataMigrationTransform, type DatabaseWriterLike, type DependencyTracker, type DeployInfo, type ExportRow, type ExportShardAdminArgs, type ExportShardArgs, type ExternalSourceDiffResult, type ExternalSourceLike, FLAGS_FUNCTION_PREFIX, type FacetColumnOptions, type FacetColumnResult, type FacetValue, type FanoutMetricsResult, type FanoutPathCounters, type FanoutTopicStat, type FieldOperators, type FilterClause, type FilterOperator, type FlagEvaluation, type FlagsResult, type FunctionCallStat, type FunctionScanAttribution, type FunctionStatsResult, GEO_DEFAULT_PRECISION, GLOBAL_SHAPE_SNAPSHOT_TABLE, type GeoBoundingBox, type GeoFilterBuilderLike, type GeoIndexDefinitionLike, type GeoPoint, type GeoScoredDocument, type GroupByEntry, type GroupByOptions, type GuardableSchema$1 as GuardableSchema, IDEMPOTENCY_TABLE, type IdGenerator, type IdempotentRecord, type ImportError, type ImportShardAdminArgs, type ImportShardArgs, type ImportShardResult, type IncrementalMaterializeResult, type IndexDefinitionLike, type IndexKeyEntry, type IndexRangeBuilderLike, type KeyRange, type LifecycleDispatchInfo, type LifecycleEvent, MAIL_RETENTION, MAIL_TABLE, MAX_PAGE_SIZE, MAX_SQL_ROWS, type MaskColumnMetadata, type MaskPoliciesResult, type MaterializeResult, type MigrationDirection, type MigrationRunResult, type MigrationStatus, type MigrationStatusRow, type MutationDelta, type NestedWith, NotFoundError, NotUniqueError, type OnDeleteActionLike, type OrderByClause, type OrderByInput, type OrderKey, OwnerRelay, type OwnerRelayFrame, type PaginationOptions, type PitrBookmarkResult, type PitrRestoreArgs, type PitrRestoreResult, type PitrStorage, type PokeFrameMeta, type PromotionState, type PromotionThresholds, QUEUE_TABLE, type QueryArgs, type QueryPage, type QueueMessageOutcome, type QueueMessageRow, type QueueMetadata, type QueuesResult, RANK_TIEBREAK, RELATION_EXISTS_KEY, RELATION_FUNCTION_PREFIX, REPROJECTION_MIGRATION_PREFIX, RLS_UNWRAP_SYMBOL, type RankBeforeOptions, type RankBeforeResult, type RankDirection, type RankIndexDefinitionLike, type RankOptions, type RankPage, type RankPageComputation, type RankPageDeps, type RankPageOptions, type RankPageRow, type RankPageRowKey, type RankResult, type RankSortKeyLike, ReactiveCache, type ReactiveCacheOptions, type ReadFootprint, type ReadHook, type ReadTablePageOptions, type RecordMailInput, type RecordQueueMessageInput, type RelationDefinitionLike, type RelationExistsMarker, type RelayAttach, type RelayDetach, type RelayFrame, type RelayHost, RelayMember, type RelayShapePoke, type RelayShapeSeed, type RelayShapeSubscribe, type RenderedSql, type ReplicaFollowerHost, type ReplicaOwnerHost, type ReplicaReadiness, type ResolveRelationPredicatesOptions, type ResolveWithOptions, type ResolveWithResult, type ResolvedShape, type RestrictableQueryOptions, type RlsPoliciesResult, type RlsPolicyMetadata, RlsRequiredError, type RlsRoleMetadata, type RpcRequest, type RunDataMigrationOptions, type RunTriggersOptions, SCAN_DEP, SCHEMA_HISTORY_MAX_VERSIONS, SEARCH_STATE_TABLE, type SchedulableWorkflowReferenceLike, type ScheduledFunctionDoc, type SchedulerLike, type SchemaLike, type ScoredDocument, type SearchFilterBuilderLike, type SearchIndexDefinitionLike, type SearchScoredDocument, type SelectMatchingIdsOptions, type ServerDefaultContextLike, type SettingEntry, type SettingKind, type SettingsResult, type ShapePokePart, type ShapeRow, type ShapeRowOp, type ShapeSubscriptionQuery, type ShardRankPageResult, ShardRunner, type ShardRunnerOptions, type ShardSiblingHost, type ShardSocketLike, type SocketAttachment, type SortDirection, type SourceClientLike, type SourceCursorLike, type SourceRefresh, type SqlConsoleResult, type SqlCursor, type SqlEngine, type SqlExec, type SqlLintResult, type StorageMetadata, type StorageReference, type StorageReferenceResult, type StorageRuleMetadata, type StorageRulesResult, type StudioFeaturesResult, type SubscriptionConnection, type SubscriptionEnvelope, type SubscriptionIdentity, type SubscriptionInfo, type SubscriptionQuery, type SubscriptionReadFootprint, type SubscriptionsResult, type SystemDatabaseReader, type SystemDoc, type SystemQuery, type SystemReaderOptions, type SystemReaderSchedulerLike, type SystemReaderStorageLike, type SystemTableName, type TableColumnsResult, type TableDefinitionLike, type TableIndexInfo, type TableIndexesResult, type TableInfo, type TablePage, type TableReaderLike, type TablesColumnsResult, type TablesIndexesResult, type TransactionHeadroom, TransactionHeadroomTracker, type TransactionLimits, type TransactionSqlLike, type TriggerContextLike, type TriggerDefinitionLike, type TriggerEventLike, type TriggerOpLike, type TriggerTimingLike, type TtlSweepSpec, type ValidatorLike, type WhereInput, type WhereSqlStrategy, type WithInput, type WorkflowInstanceState, type WorkflowInstanceStatusResult, type WorkflowMetadata, type WorkflowsResult, type WriteEvent, type WriteHook, advanceClientWatermark, aggUpsertSql, aggregateSqlFunction, aggregateTableName, appendAuditEntry, appendCdcChange, applyCdcChanges, applyOnDelete, applySelect, armRestore, assertFlatPredicate, assertReadonly, assertShapeShardable, assertValidClientId, awaitWsDrain, backfillAggregateIndexes, backfillRankIndexes, backfillSearchIndexes, backfillSearchIndexesForTable, boundingBoxCenter, boundingBoxGeohashes, buildIndexRange, buildPokeFrames, buildReprojectionMigration, buildSeekBeforeWhere, buildSeekWhere, buildSettings, bumpCdcEpoch, clampPromotionThresholds, clearCapturedMail, clearQueueMessages, coerceAggregateNumber, compileWhereSql, computeRankPage, containsRelationPredicate, countLegacyRows, coveringGeohashes, createCompanionSync, createDependencyTracker, createFanoutCounters, createIndexSql, createReadFootprint, createRelayLink, createReplicaLink, createShardCtxDb, createSystemReader, decodeCursor, deleteGlobalShapeSnapshot, deleteGlobalShapeSnapshotsForConnection, depKey, diffExternalSource, diffGlobalMembership, distinctValues, encodeAggregateKey, encodeCursor, encodeGeohash, encodePartitionKey, encodeRowsPatch, ensureAuditTable, ensureMailTable, exportShardRows, exportShardTable, facetColumn, fanOutScalarCounts, findStorageReferences, foldAggregateTally, gateReplicaDispatch, geoTableName, guardWriter, handleReplicaControl, hasTrigger, haversineMeters, hydrateDocsById, importShardRows, indexKeysForRow, isDevEnvironment, isFtsAvailable, isLossyBody, isRelationPredicate, isSoftDeleted, isSourceDue, jsonPath, jsonPathSql, keysTouchRanges, liftSourceId, lintReadonlySql, listTables, literalInList, matchesRankStaticWhere, matchesStaticWhere, materializeExternalRows, materializeExternalRowsIncremental, mergeChangedKeys, mergeWhere, migrateCdcLog, migrateCdcMeta, migrateClientWatermark, migrateGlobalShapeSnapshot, migrateIdempotency, migrateSearchState, minCdcSeq, nextPromotionState, normalizeCountArgument, normalizeIdStructurally, normalizeOrderKeys, normalizeSourceDocument, normalizeSourceValue, param, parseExportShardArgs, parseImportShardArgs, planAggregateLookup, pointInBoundingBox, projectColumns, pullExternalSourceIncrementalTick, pullExternalSourceTick, qualifiedJsonPath, qualifiedJsonPathSql, quoteIdentifier, rankKeyFromDocument as rankKeyFromDoc, rankTableName, reactiveCacheKey, readAggregateValue, readAuditLog, readBookmark, readCapturedMail, readCdcChanges, readCdcCursor, readCdcEpoch, readClientWatermark, readExternalSourceBaseline, readGlobalShapeSnapshot, readIdempotent, readMigrationStatus, readQueueMessageById, readQueueMessages, readSchemaHistory, readSchemaVersion, readSearchBackfillState, readTablePage, recordCapturedMail, recordChangedKeys, recordFanoutPass, recordQueueMessages, recordSchemaVersion, relationHooks, relayCountFor, renderSql, reprojectableFields, reprojectionMigrationId, reprojectionTables, resolveRankPartition, resolveRelationPredicates, resolveWith, rowToDocument, runDataMigration, runDrizzle, runExternalSourceTick, runReadonlySql, runRowValidators, runShardMigrations, runSocketPool, runSql, runTriggers, selectExpiredIds, selectExportTables, selectIndexForAggregate, selectIndexForCount, selectIndexForGroupBy, selectMatchingIds, selectShapeMemberIds, selectShapeRows, sendDeltaFrames, serializeSqlValue, shapeRoutingKey, softDeleteScope, sortColumnName, sqliteInList, stableStringify, stableWireKey, subscriptionListDeltas, summarizeFanoutTopics, summarizeSubscriptions, tableColumns, tableFromDepKey, throwingScheduler, trimCdcChanges, trimIdempotent, tryRowToDocument, trySendFrame, unionAll, validateImportRow, writeGlobalShapeSnapshot, writeIdempotent, writeSearchBackfillState, writeTouchesMemo };
package/dist/index.d.ts CHANGED
@@ -1016,6 +1016,8 @@ interface RenderedSql {
1016
1016
  }
1017
1017
  declare const renderSql: (engine: SqlEngine, query: SQL) => RenderedSql;
1018
1018
  declare const param: (value: unknown) => SQL;
1019
+ declare const unionAll: (branches: ReadonlyArray<SQL>) => SQL;
1020
+ declare const sqliteInList: (reference: SQL, items: ReadonlyArray<unknown>, negated: boolean, budget?: number) => SQL;
1019
1021
  interface ExternalSourceDiffResult {
1020
1022
  changes: CdcChange[];
1021
1023
  nextBaseline: Map<string, string>;
@@ -2051,10 +2053,12 @@ declare const selectExpiredIds: (sql: SqlExec, spec: TtlSweepSpec, now: number,
2051
2053
  type FieldRefSql = (field: string) => SQL;
2052
2054
  type SerializeValue = (value: unknown) => unknown;
2053
2055
  interface WhereSqlStrategy {
2056
+ containsExpr?: (reference: SQL, term: SQL) => SQL;
2054
2057
  fieldRef: FieldRefSql;
2055
- likeContains?: (reference: SQL, term: SQL) => SQL;
2058
+ inList?: (reference: SQL, items: ReadonlyArray<unknown>, negated: boolean, budget?: number) => SQL;
2056
2059
  relationExists?: (request: unknown) => SQL;
2057
2060
  serialize: SerializeValue;
2058
2061
  }
2062
+ declare const literalInList: (reference: SQL, items: ReadonlyArray<unknown>, negated: boolean) => SQL;
2059
2063
  declare const compileWhereSql: (where: WhereInput | undefined, strategy: WhereSqlStrategy) => SQL | undefined;
2060
- export { ADMIN_FUNCTIONS, ADMIN_FUNCTION_PREFIX, AGGREGATE_SQL_FUNCTION, AGG_COUNT, AGG_KEY, AGG_VALUE, AUDIT_LOG_TABLE, type AdvisorProcedure, type AdvisorProceduresResult, type AdvisoriesResult, type AdvisoryFinding, type AggregateIndexDefinitionLike, type AggregateOp, type AggregateOptions, type AggregateResult, type AggregateTally, type AppendAuditEntry, type ApplyOnDeleteOptions$1 as ApplyOnDeleteOptions, type AuditEntry, type AuditLogResult, type BroadcastDelta, CDC_LOG_TABLE, CDC_META_TABLE, CLIENT_WATERMARK_TABLE, type CacheEntry, type CapturedMailRow, type CdcChange, type ChangedKeys, type Clock, type ColumnMeta, type ColumnMetaLike, type CompanionSync, type CompanionSyncDeps, ConflictError, type ConflictKind, type CountArgs, CountRlsUnsupportedError, type CreateWorkflowInstanceResult, type CrossShardReadArgs, type CtxDbOptions, DATA_MIGRATION_STATE_TABLE, DEFAULT_FANOUT_TOPIC_LIMIT, DEFAULT_MAX_RELATION_KEYS, DEFAULT_MAX_RELAYS, DEFAULT_PROMOTION_THRESHOLDS, DEFAULT_TRANSACTION_LIMITS, DOC_COLUMN, type DataMigrationDocument, type DataMigrationLike, type DataMigrationTransform, type DatabaseWriterLike, type DependencyTracker, type DeployInfo, type ExportRow, type ExportShardAdminArgs, type ExportShardArgs, type ExternalSourceDiffResult, type ExternalSourceLike, FLAGS_FUNCTION_PREFIX, type FacetColumnOptions, type FacetColumnResult, type FacetValue, type FanoutMetricsResult, type FanoutPathCounters, type FanoutTopicStat, type FieldOperators, type FilterClause, type FilterOperator, type FlagEvaluation, type FlagsResult, type FunctionCallStat, type FunctionScanAttribution, type FunctionStatsResult, GEO_DEFAULT_PRECISION, GLOBAL_SHAPE_SNAPSHOT_TABLE, type GeoBoundingBox, type GeoFilterBuilderLike, type GeoIndexDefinitionLike, type GeoPoint, type GeoScoredDocument, type GroupByEntry, type GroupByOptions, type GuardableSchema$1 as GuardableSchema, IDEMPOTENCY_TABLE, type IdGenerator, type IdempotentRecord, type ImportError, type ImportShardAdminArgs, type ImportShardArgs, type ImportShardResult, type IncrementalMaterializeResult, type IndexDefinitionLike, type IndexKeyEntry, type IndexRangeBuilderLike, type KeyRange, type LifecycleDispatchInfo, type LifecycleEvent, MAIL_RETENTION, MAIL_TABLE, MAX_PAGE_SIZE, MAX_SQL_ROWS, type MaskColumnMetadata, type MaskPoliciesResult, type MaterializeResult, type MigrationDirection, type MigrationRunResult, type MigrationStatus, type MigrationStatusRow, type MutationDelta, type NestedWith, NotFoundError, NotUniqueError, type OnDeleteActionLike, type OrderByClause, type OrderByInput, type OrderKey, OwnerRelay, type OwnerRelayFrame, type PaginationOptions, type PitrBookmarkResult, type PitrRestoreArgs, type PitrRestoreResult, type PitrStorage, type PokeFrameMeta, type PromotionState, type PromotionThresholds, QUEUE_TABLE, type QueryArgs, type QueryPage, type QueueMessageOutcome, type QueueMessageRow, type QueueMetadata, type QueuesResult, RANK_TIEBREAK, RELATION_EXISTS_KEY, RELATION_FUNCTION_PREFIX, REPROJECTION_MIGRATION_PREFIX, RLS_UNWRAP_SYMBOL, type RankBeforeOptions, type RankBeforeResult, type RankDirection, type RankIndexDefinitionLike, type RankOptions, type RankPage, type RankPageComputation, type RankPageDeps, type RankPageOptions, type RankPageRow, type RankPageRowKey, type RankResult, type RankSortKeyLike, ReactiveCache, type ReactiveCacheOptions, type ReadFootprint, type ReadHook, type ReadTablePageOptions, type RecordMailInput, type RecordQueueMessageInput, type RelationDefinitionLike, type RelationExistsMarker, type RelayAttach, type RelayDetach, type RelayFrame, type RelayHost, RelayMember, type RelayShapePoke, type RelayShapeSeed, type RelayShapeSubscribe, type RenderedSql, type ReplicaFollowerHost, type ReplicaOwnerHost, type ReplicaReadiness, type ResolveRelationPredicatesOptions, type ResolveWithOptions, type ResolveWithResult, type ResolvedShape, type RestrictableQueryOptions, type RlsPoliciesResult, type RlsPolicyMetadata, RlsRequiredError, type RlsRoleMetadata, type RpcRequest, type RunDataMigrationOptions, type RunTriggersOptions, SCAN_DEP, SCHEMA_HISTORY_MAX_VERSIONS, SEARCH_STATE_TABLE, type SchedulableWorkflowReferenceLike, type ScheduledFunctionDoc, type SchedulerLike, type SchemaLike, type ScoredDocument, type SearchFilterBuilderLike, type SearchIndexDefinitionLike, type SearchScoredDocument, type SelectMatchingIdsOptions, type ServerDefaultContextLike, type SettingEntry, type SettingKind, type SettingsResult, type ShapePokePart, type ShapeRow, type ShapeRowOp, type ShapeSubscriptionQuery, type ShardRankPageResult, ShardRunner, type ShardRunnerOptions, type ShardSiblingHost, type ShardSocketLike, type SocketAttachment, type SortDirection, type SourceClientLike, type SourceCursorLike, type SourceRefresh, type SqlConsoleResult, type SqlCursor, type SqlEngine, type SqlExec, type SqlLintResult, type StorageMetadata, type StorageReference, type StorageReferenceResult, type StorageRuleMetadata, type StorageRulesResult, type StudioFeaturesResult, type SubscriptionConnection, type SubscriptionEnvelope, type SubscriptionIdentity, type SubscriptionInfo, type SubscriptionQuery, type SubscriptionReadFootprint, type SubscriptionsResult, type SystemDatabaseReader, type SystemDoc, type SystemQuery, type SystemReaderOptions, type SystemReaderSchedulerLike, type SystemReaderStorageLike, type SystemTableName, type TableColumnsResult, type TableDefinitionLike, type TableIndexInfo, type TableIndexesResult, type TableInfo, type TablePage, type TableReaderLike, type TablesColumnsResult, type TablesIndexesResult, type TransactionHeadroom, TransactionHeadroomTracker, type TransactionLimits, type TransactionSqlLike, type TriggerContextLike, type TriggerDefinitionLike, type TriggerEventLike, type TriggerOpLike, type TriggerTimingLike, type TtlSweepSpec, type ValidatorLike, type WhereInput, type WhereSqlStrategy, type WithInput, type WorkflowInstanceState, type WorkflowInstanceStatusResult, type WorkflowMetadata, type WorkflowsResult, type WriteEvent, type WriteHook, advanceClientWatermark, aggUpsertSql, aggregateSqlFunction, aggregateTableName, appendAuditEntry, appendCdcChange, applyCdcChanges, applyOnDelete, applySelect, armRestore, assertFlatPredicate, assertReadonly, assertShapeShardable, assertValidClientId, awaitWsDrain, backfillAggregateIndexes, backfillRankIndexes, backfillSearchIndexes, backfillSearchIndexesForTable, boundingBoxCenter, boundingBoxGeohashes, buildIndexRange, buildPokeFrames, buildReprojectionMigration, buildSeekBeforeWhere, buildSeekWhere, buildSettings, bumpCdcEpoch, clampPromotionThresholds, clearCapturedMail, clearQueueMessages, coerceAggregateNumber, compileWhereSql, computeRankPage, containsRelationPredicate, countLegacyRows, coveringGeohashes, createCompanionSync, createDependencyTracker, createFanoutCounters, createIndexSql, createReadFootprint, createRelayLink, createReplicaLink, createShardCtxDb, createSystemReader, decodeCursor, deleteGlobalShapeSnapshot, deleteGlobalShapeSnapshotsForConnection, depKey, diffExternalSource, diffGlobalMembership, distinctValues, encodeAggregateKey, encodeCursor, encodeGeohash, encodePartitionKey, encodeRowsPatch, ensureAuditTable, ensureMailTable, exportShardRows, exportShardTable, facetColumn, fanOutScalarCounts, findStorageReferences, foldAggregateTally, gateReplicaDispatch, geoTableName, guardWriter, handleReplicaControl, hasTrigger, haversineMeters, hydrateDocsById, importShardRows, indexKeysForRow, isDevEnvironment, isFtsAvailable, isLossyBody, isRelationPredicate, isSoftDeleted, isSourceDue, jsonPath, jsonPathSql, keysTouchRanges, liftSourceId, lintReadonlySql, listTables, matchesRankStaticWhere, matchesStaticWhere, materializeExternalRows, materializeExternalRowsIncremental, mergeChangedKeys, mergeWhere, migrateCdcLog, migrateCdcMeta, migrateClientWatermark, migrateGlobalShapeSnapshot, migrateIdempotency, migrateSearchState, minCdcSeq, nextPromotionState, normalizeCountArgument, normalizeIdStructurally, normalizeOrderKeys, normalizeSourceDocument, normalizeSourceValue, param, parseExportShardArgs, parseImportShardArgs, planAggregateLookup, pointInBoundingBox, projectColumns, pullExternalSourceIncrementalTick, pullExternalSourceTick, qualifiedJsonPath, qualifiedJsonPathSql, quoteIdentifier, rankKeyFromDocument as rankKeyFromDoc, rankTableName, reactiveCacheKey, readAggregateValue, readAuditLog, readBookmark, readCapturedMail, readCdcChanges, readCdcCursor, readCdcEpoch, readClientWatermark, readExternalSourceBaseline, readGlobalShapeSnapshot, readIdempotent, readMigrationStatus, readQueueMessageById, readQueueMessages, readSchemaHistory, readSchemaVersion, readSearchBackfillState, readTablePage, recordCapturedMail, recordChangedKeys, recordFanoutPass, recordQueueMessages, recordSchemaVersion, relationHooks, relayCountFor, renderSql, reprojectableFields, reprojectionMigrationId, reprojectionTables, resolveRankPartition, resolveRelationPredicates, resolveWith, rowToDocument, runDataMigration, runDrizzle, runExternalSourceTick, runReadonlySql, runRowValidators, runShardMigrations, runSocketPool, runSql, runTriggers, selectExpiredIds, selectExportTables, selectIndexForAggregate, selectIndexForCount, selectIndexForGroupBy, selectMatchingIds, selectShapeMemberIds, selectShapeRows, sendDeltaFrames, serializeSqlValue, shapeRoutingKey, softDeleteScope, sortColumnName, stableStringify, stableWireKey, subscriptionListDeltas, summarizeFanoutTopics, summarizeSubscriptions, tableColumns, tableFromDepKey, throwingScheduler, trimCdcChanges, trimIdempotent, tryRowToDocument, trySendFrame, validateImportRow, writeGlobalShapeSnapshot, writeIdempotent, writeSearchBackfillState, writeTouchesMemo };
2064
+ export { ADMIN_FUNCTIONS, ADMIN_FUNCTION_PREFIX, AGGREGATE_SQL_FUNCTION, AGG_COUNT, AGG_KEY, AGG_VALUE, AUDIT_LOG_TABLE, type AdvisorProcedure, type AdvisorProceduresResult, type AdvisoriesResult, type AdvisoryFinding, type AggregateIndexDefinitionLike, type AggregateOp, type AggregateOptions, type AggregateResult, type AggregateTally, type AppendAuditEntry, type ApplyOnDeleteOptions$1 as ApplyOnDeleteOptions, type AuditEntry, type AuditLogResult, type BroadcastDelta, CDC_LOG_TABLE, CDC_META_TABLE, CLIENT_WATERMARK_TABLE, type CacheEntry, type CapturedMailRow, type CdcChange, type ChangedKeys, type Clock, type ColumnMeta, type ColumnMetaLike, type CompanionSync, type CompanionSyncDeps, ConflictError, type ConflictKind, type CountArgs, CountRlsUnsupportedError, type CreateWorkflowInstanceResult, type CrossShardReadArgs, type CtxDbOptions, DATA_MIGRATION_STATE_TABLE, DEFAULT_FANOUT_TOPIC_LIMIT, DEFAULT_MAX_RELATION_KEYS, DEFAULT_MAX_RELAYS, DEFAULT_PROMOTION_THRESHOLDS, DEFAULT_TRANSACTION_LIMITS, DOC_COLUMN, type DataMigrationDocument, type DataMigrationLike, type DataMigrationTransform, type DatabaseWriterLike, type DependencyTracker, type DeployInfo, type ExportRow, type ExportShardAdminArgs, type ExportShardArgs, type ExternalSourceDiffResult, type ExternalSourceLike, FLAGS_FUNCTION_PREFIX, type FacetColumnOptions, type FacetColumnResult, type FacetValue, type FanoutMetricsResult, type FanoutPathCounters, type FanoutTopicStat, type FieldOperators, type FilterClause, type FilterOperator, type FlagEvaluation, type FlagsResult, type FunctionCallStat, type FunctionScanAttribution, type FunctionStatsResult, GEO_DEFAULT_PRECISION, GLOBAL_SHAPE_SNAPSHOT_TABLE, type GeoBoundingBox, type GeoFilterBuilderLike, type GeoIndexDefinitionLike, type GeoPoint, type GeoScoredDocument, type GroupByEntry, type GroupByOptions, type GuardableSchema$1 as GuardableSchema, IDEMPOTENCY_TABLE, type IdGenerator, type IdempotentRecord, type ImportError, type ImportShardAdminArgs, type ImportShardArgs, type ImportShardResult, type IncrementalMaterializeResult, type IndexDefinitionLike, type IndexKeyEntry, type IndexRangeBuilderLike, type KeyRange, type LifecycleDispatchInfo, type LifecycleEvent, MAIL_RETENTION, MAIL_TABLE, MAX_PAGE_SIZE, MAX_SQL_ROWS, type MaskColumnMetadata, type MaskPoliciesResult, type MaterializeResult, type MigrationDirection, type MigrationRunResult, type MigrationStatus, type MigrationStatusRow, type MutationDelta, type NestedWith, NotFoundError, NotUniqueError, type OnDeleteActionLike, type OrderByClause, type OrderByInput, type OrderKey, OwnerRelay, type OwnerRelayFrame, type PaginationOptions, type PitrBookmarkResult, type PitrRestoreArgs, type PitrRestoreResult, type PitrStorage, type PokeFrameMeta, type PromotionState, type PromotionThresholds, QUEUE_TABLE, type QueryArgs, type QueryPage, type QueueMessageOutcome, type QueueMessageRow, type QueueMetadata, type QueuesResult, RANK_TIEBREAK, RELATION_EXISTS_KEY, RELATION_FUNCTION_PREFIX, REPROJECTION_MIGRATION_PREFIX, RLS_UNWRAP_SYMBOL, type RankBeforeOptions, type RankBeforeResult, type RankDirection, type RankIndexDefinitionLike, type RankOptions, type RankPage, type RankPageComputation, type RankPageDeps, type RankPageOptions, type RankPageRow, type RankPageRowKey, type RankResult, type RankSortKeyLike, ReactiveCache, type ReactiveCacheOptions, type ReadFootprint, type ReadHook, type ReadTablePageOptions, type RecordMailInput, type RecordQueueMessageInput, type RelationDefinitionLike, type RelationExistsMarker, type RelayAttach, type RelayDetach, type RelayFrame, type RelayHost, RelayMember, type RelayShapePoke, type RelayShapeSeed, type RelayShapeSubscribe, type RenderedSql, type ReplicaFollowerHost, type ReplicaOwnerHost, type ReplicaReadiness, type ResolveRelationPredicatesOptions, type ResolveWithOptions, type ResolveWithResult, type ResolvedShape, type RestrictableQueryOptions, type RlsPoliciesResult, type RlsPolicyMetadata, RlsRequiredError, type RlsRoleMetadata, type RpcRequest, type RunDataMigrationOptions, type RunTriggersOptions, SCAN_DEP, SCHEMA_HISTORY_MAX_VERSIONS, SEARCH_STATE_TABLE, type SchedulableWorkflowReferenceLike, type ScheduledFunctionDoc, type SchedulerLike, type SchemaLike, type ScoredDocument, type SearchFilterBuilderLike, type SearchIndexDefinitionLike, type SearchScoredDocument, type SelectMatchingIdsOptions, type ServerDefaultContextLike, type SettingEntry, type SettingKind, type SettingsResult, type ShapePokePart, type ShapeRow, type ShapeRowOp, type ShapeSubscriptionQuery, type ShardRankPageResult, ShardRunner, type ShardRunnerOptions, type ShardSiblingHost, type ShardSocketLike, type SocketAttachment, type SortDirection, type SourceClientLike, type SourceCursorLike, type SourceRefresh, type SqlConsoleResult, type SqlCursor, type SqlEngine, type SqlExec, type SqlLintResult, type StorageMetadata, type StorageReference, type StorageReferenceResult, type StorageRuleMetadata, type StorageRulesResult, type StudioFeaturesResult, type SubscriptionConnection, type SubscriptionEnvelope, type SubscriptionIdentity, type SubscriptionInfo, type SubscriptionQuery, type SubscriptionReadFootprint, type SubscriptionsResult, type SystemDatabaseReader, type SystemDoc, type SystemQuery, type SystemReaderOptions, type SystemReaderSchedulerLike, type SystemReaderStorageLike, type SystemTableName, type TableColumnsResult, type TableDefinitionLike, type TableIndexInfo, type TableIndexesResult, type TableInfo, type TablePage, type TableReaderLike, type TablesColumnsResult, type TablesIndexesResult, type TransactionHeadroom, TransactionHeadroomTracker, type TransactionLimits, type TransactionSqlLike, type TriggerContextLike, type TriggerDefinitionLike, type TriggerEventLike, type TriggerOpLike, type TriggerTimingLike, type TtlSweepSpec, type ValidatorLike, type WhereInput, type WhereSqlStrategy, type WithInput, type WorkflowInstanceState, type WorkflowInstanceStatusResult, type WorkflowMetadata, type WorkflowsResult, type WriteEvent, type WriteHook, advanceClientWatermark, aggUpsertSql, aggregateSqlFunction, aggregateTableName, appendAuditEntry, appendCdcChange, applyCdcChanges, applyOnDelete, applySelect, armRestore, assertFlatPredicate, assertReadonly, assertShapeShardable, assertValidClientId, awaitWsDrain, backfillAggregateIndexes, backfillRankIndexes, backfillSearchIndexes, backfillSearchIndexesForTable, boundingBoxCenter, boundingBoxGeohashes, buildIndexRange, buildPokeFrames, buildReprojectionMigration, buildSeekBeforeWhere, buildSeekWhere, buildSettings, bumpCdcEpoch, clampPromotionThresholds, clearCapturedMail, clearQueueMessages, coerceAggregateNumber, compileWhereSql, computeRankPage, containsRelationPredicate, countLegacyRows, coveringGeohashes, createCompanionSync, createDependencyTracker, createFanoutCounters, createIndexSql, createReadFootprint, createRelayLink, createReplicaLink, createShardCtxDb, createSystemReader, decodeCursor, deleteGlobalShapeSnapshot, deleteGlobalShapeSnapshotsForConnection, depKey, diffExternalSource, diffGlobalMembership, distinctValues, encodeAggregateKey, encodeCursor, encodeGeohash, encodePartitionKey, encodeRowsPatch, ensureAuditTable, ensureMailTable, exportShardRows, exportShardTable, facetColumn, fanOutScalarCounts, findStorageReferences, foldAggregateTally, gateReplicaDispatch, geoTableName, guardWriter, handleReplicaControl, hasTrigger, haversineMeters, hydrateDocsById, importShardRows, indexKeysForRow, isDevEnvironment, isFtsAvailable, isLossyBody, isRelationPredicate, isSoftDeleted, isSourceDue, jsonPath, jsonPathSql, keysTouchRanges, liftSourceId, lintReadonlySql, listTables, literalInList, matchesRankStaticWhere, matchesStaticWhere, materializeExternalRows, materializeExternalRowsIncremental, mergeChangedKeys, mergeWhere, migrateCdcLog, migrateCdcMeta, migrateClientWatermark, migrateGlobalShapeSnapshot, migrateIdempotency, migrateSearchState, minCdcSeq, nextPromotionState, normalizeCountArgument, normalizeIdStructurally, normalizeOrderKeys, normalizeSourceDocument, normalizeSourceValue, param, parseExportShardArgs, parseImportShardArgs, planAggregateLookup, pointInBoundingBox, projectColumns, pullExternalSourceIncrementalTick, pullExternalSourceTick, qualifiedJsonPath, qualifiedJsonPathSql, quoteIdentifier, rankKeyFromDocument as rankKeyFromDoc, rankTableName, reactiveCacheKey, readAggregateValue, readAuditLog, readBookmark, readCapturedMail, readCdcChanges, readCdcCursor, readCdcEpoch, readClientWatermark, readExternalSourceBaseline, readGlobalShapeSnapshot, readIdempotent, readMigrationStatus, readQueueMessageById, readQueueMessages, readSchemaHistory, readSchemaVersion, readSearchBackfillState, readTablePage, recordCapturedMail, recordChangedKeys, recordFanoutPass, recordQueueMessages, recordSchemaVersion, relationHooks, relayCountFor, renderSql, reprojectableFields, reprojectionMigrationId, reprojectionTables, resolveRankPartition, resolveRelationPredicates, resolveWith, rowToDocument, runDataMigration, runDrizzle, runExternalSourceTick, runReadonlySql, runRowValidators, runShardMigrations, runSocketPool, runSql, runTriggers, selectExpiredIds, selectExportTables, selectIndexForAggregate, selectIndexForCount, selectIndexForGroupBy, selectMatchingIds, selectShapeMemberIds, selectShapeRows, sendDeltaFrames, serializeSqlValue, shapeRoutingKey, softDeleteScope, sortColumnName, sqliteInList, stableStringify, stableWireKey, subscriptionListDeltas, summarizeFanoutTopics, summarizeSubscriptions, tableColumns, tableFromDepKey, throwingScheduler, trimCdcChanges, trimIdempotent, tryRowToDocument, trySendFrame, unionAll, validateImportRow, writeGlobalShapeSnapshot, writeIdempotent, writeSearchBackfillState, writeTouchesMemo };
package/dist/index.mjs CHANGED
@@ -1 +1 @@
1
- import{exportShardRows as o,exportShardTable as a,importShardRows as t,parseExportShardArgs as n,parseImportShardArgs as s,selectExportTables as l,validateImportRow as i}from"./packem_shared/exportShardRows-Bbi_JGfn.mjs";import{AGGREGATE_SQL_FUNCTION as m,aggregateSqlFunction as d,matchesStaticWhere as c,normalizeCountArgument as S,throwingScheduler as u}from"./packem_shared/AGGREGATE_SQL_FUNCTION-CTo0-9iZ.mjs";import{aggregateTableName as f,coerceAggregateNumber as T,encodeAggregateKey as g,foldAggregateTally as E,readAggregateValue as h}from"./packem_shared/aggregateTableName-DgYMC5tr.mjs";import{CountRlsUnsupportedError as I,mergeWhere as R,planAggregateLookup as C,selectIndexForAggregate as _,selectIndexForCount as L,selectIndexForGroupBy as b}from"./packem_shared/CountRlsUnsupportedError-8BqPYQoP.mjs";import{AUDIT_LOG_TABLE as N,appendAuditEntry as M,ensureAuditTable as O,readAuditLog as F}from"./packem_shared/AUDIT_LOG_TABLE-C6nwXFPd.mjs";import{NotUniqueError as P,assertValidClientId as k,createShardCtxDb as G,normalizeIdStructurally as B}from"./packem_shared/NotUniqueError-CVHdtVw6.mjs";import{backfillAggregateIndexes as w,backfillRankIndexes as K,backfillSearchIndexes as q,backfillSearchIndexesForTable as W}from"./packem_shared/backfillAggregateIndexes-DmqOHg0U.mjs";import{CDC_LOG_TABLE as z,CDC_META_TABLE as H,appendCdcChange as V,applyCdcChanges as X,bumpCdcEpoch as j,migrateCdcLog as Q,migrateCdcMeta as Y,minCdcSeq as J,readCdcChanges as Z,readCdcCursor as $,readCdcEpoch as ee,trimCdcChanges as re}from"./packem_shared/CDC_LOG_TABLE-ZqcflEen.mjs";import{CLIENT_WATERMARK_TABLE as ae,advanceClientWatermark as te,migrateClientWatermark as ne,readClientWatermark as se}from"./packem_shared/CLIENT_WATERMARK_TABLE-CzApRlyv.mjs";import{w as ie}from"./packem_shared/ctx-db-companions-BTi8DLUl.mjs";import{GLOBAL_SHAPE_SNAPSHOT_TABLE as me,deleteGlobalShapeSnapshot as de,deleteGlobalShapeSnapshotsForConnection as ce,migrateGlobalShapeSnapshot as Se,readGlobalShapeSnapshot as ue,writeGlobalShapeSnapshot as xe}from"./packem_shared/GLOBAL_SHAPE_SNAPSHOT_TABLE-soMJDSBs.mjs";import{IDEMPOTENCY_TABLE as Te,migrateIdempotency as ge,readIdempotent as Ee,trimIdempotent as he,writeIdempotent as Ae}from"./packem_shared/IDEMPOTENCY_TABLE-Bvu9JkiL.mjs";import{computeRankPage as Re,hydrateDocsById as Ce}from"./packem_shared/computeRankPage-QK8SeTZ-.mjs";import{SEARCH_STATE_TABLE as Le,migrateSearchState as be,readSearchBackfillState as ye,writeSearchBackfillState as Ne}from"./packem_shared/SEARCH_STATE_TABLE-BZ_fxI5l.mjs";import{selectShapeMemberIds as Oe,selectShapeRows as Fe}from"./packem_shared/selectShapeMemberIds-BdBcbrUP.mjs";import{DATA_MIGRATION_STATE_TABLE as Pe,readMigrationStatus as ke,runDataMigration as Ge}from"./packem_shared/DATA_MIGRATION_STATE_TABLE-BrpAGtXf.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-B6rnz3so.mjs";import{T as Ve,c as Xe,p as je,a as Qe,A as Ye,y as Je,h as Ze,C as $e,_ as er,N as rr,S as or,O as ar,E as tr,I as nr,D as sr}from"./packem_shared/do-sql-1Yi1_Yq0.mjs";import{param as ir,renderSql as pr}from"./packem_shared/param-B5lF5Jd9.mjs";import{diffExternalSource as dr}from"./packem_shared/diffExternalSource-DMpkJta1.mjs";import{liftSourceId as Sr,normalizeSourceDocument as ur,normalizeSourceValue as xr}from"./packem_shared/liftSourceId-DApAbu7Q.mjs";import{materializeExternalRows as Tr,materializeExternalRowsIncremental as gr,readExternalSourceBaseline as Er,runExternalSourceTick as hr}from"./packem_shared/materializeExternalRows-DcCENzpV.mjs";import{isSoftDeleted as Ir,isSourceDue as Rr,pullExternalSourceIncrementalTick as Cr,pullExternalSourceTick as _r}from"./packem_shared/isSoftDeleted-Bo-y3DOe.mjs";import{GEO_DEFAULT_PRECISION as br,boundingBoxCenter as yr,boundingBoxGeohashes as Nr,coveringGeohashes as Mr,encodeGeohash as Or,haversineMeters as Fr,pointInBoundingBox as Dr}from"./packem_shared/GEO_DEFAULT_PRECISION-DyI5zggj.mjs";import{ADMIN_FUNCTIONS as kr,ADMIN_FUNCTION_PREFIX as Gr,DEFAULT_FANOUT_TOPIC_LIMIT as Br,FLAGS_FUNCTION_PREFIX as Ur,MAX_PAGE_SIZE as wr,RELATION_FUNCTION_PREFIX as Kr,createFanoutCounters as qr,facetColumn as Wr,findStorageReferences as vr,listTables as zr,readTablePage as Hr,recordFanoutPass as Vr,selectMatchingIds as Xr,summarizeFanoutTopics as jr,summarizeSubscriptions as Qr}from"./packem_shared/ADMIN_FUNCTIONS-OnYxyTXW.mjs";import{MAIL_RETENTION as Jr,MAIL_TABLE as Zr,clearCapturedMail as $r,ensureMailTable as eo,readCapturedMail as ro,recordCapturedMail as oo}from"./packem_shared/MAIL_RETENTION-BefR9Sei.mjs";import{NotFoundError as to}from"./packem_shared/NotFoundError-BhF7FeFr.mjs";import{armRestore as so,readBookmark as lo}from"./packem_shared/armRestore-BNzdvQ_o.mjs";import{applySelect as po,buildSeekBeforeWhere as mo,buildSeekWhere as co,decodeCursor as So,encodeCursor as uo,normalizeOrderKeys as xo,softDeleteScope as fo}from"./packem_shared/applySelect-UY-o13Ia.mjs";import{QUEUE_TABLE as go,clearQueueMessages as Eo,isLossyBody as ho,readQueueMessageById as Ao,readQueueMessages as Io,recordQueueMessages as Ro}from"./packem_shared/QUEUE_TABLE-DgBqWrXX.mjs";import{RANK_TIEBREAK as _o,encodePartitionKey as Lo,matchesRankStaticWhere as bo,rankKeyFromDoc as yo,rankTableName as No,resolveRankPartition as Mo,sortColumnName as Oo}from"./packem_shared/RANK_TIEBREAK-DDtST3gN.mjs";import{ReactiveCache as Do,reactiveCacheKey as Po}from"./packem_shared/ReactiveCache-Cu8IfE1M.mjs";import{createReadFootprint as Go}from"./packem_shared/createReadFootprint-DIrrxRTE.mjs";import{buildIndexRange as Uo,indexKeysForRow as wo,keysTouchRanges as Ko}from"./packem_shared/buildIndexRange-DFsdtPjD.mjs";import{DEFAULT_MAX_RELATION_KEYS as Wo,assertFlatPredicate as vo,assertShapeShardable as zo,containsRelationPredicate as Ho,isRelationPredicate as Vo,resolveRelationPredicates as Xo}from"./packem_shared/DEFAULT_MAX_RELATION_KEYS-DjKka36Z.mjs";import{applyOnDelete as Qo,distinctValues as Yo,fanOutScalarCounts as Jo,relationHooks as Zo,resolveWith as $o,runRowValidators as ea}from"./packem_shared/applyOnDelete-By23GK-k.mjs";import{DEFAULT_PROMOTION_THRESHOLDS as oa,clampPromotionThresholds as aa,nextPromotionState as ta,relayCountFor as na,shapeRoutingKey as sa}from"./packem_shared/DEFAULT_PROMOTION_THRESHOLDS-B2rUe1bg.mjs";import{DEFAULT_MAX_RELAYS as ia,OwnerRelay as pa,RelayMember as ma,createRelayLink as da}from"./packem_shared/DEFAULT_MAX_RELAYS-B19vrJxP.mjs";import{createReplicaLink as Sa,gateReplicaDispatch as ua,handleReplicaControl as xa}from"./packem_shared/createReplicaLink-BMNW0SX6.mjs";import{buildReprojectionMigration as Ta,countLegacyRows as ga,reprojectableFields as Ea,reprojectionTables as ha}from"./packem_shared/buildReprojectionMigration-Ctl4r84d.mjs";import{RLS_UNWRAP_SYMBOL as Ia,RlsRequiredError as Ra,guardWriter as Ca}from"./packem_shared/RLS_UNWRAP_SYMBOL-DcqORh2s.mjs";import{SCHEMA_HISTORY_MAX_VERSIONS as La,readSchemaHistory as ba,readSchemaVersion as ya,recordSchemaVersion as Na}from"./packem_shared/SCHEMA_HISTORY_MAX_VERSIONS-BEU0CuW5.mjs";import{serializeSqlValue as Oa}from"./packem_shared/serializeSqlValue-BR4UOWoP.mjs";import{buildSettings as Da,isDevEnvironment as Pa}from"./packem_shared/buildSettings-COIJsw7a.mjs";import{buildPokeFrames as Ga,diffGlobalMembership as Ba,encodeRowsPatch as Ua,projectColumns as wa}from"./packem_shared/buildPokeFrames-CqxaN8_H.mjs";import{ShardRunner as qa}from"./packem_shared/ShardRunner-DIqVdWtk.mjs";import{runSocketPool as va}from"./packem_shared/runSocketPool-DPQLVyWF.mjs";import{MAX_SQL_ROWS as Ha,assertReadonly as Va,lintReadonlySql as Xa,runReadonlySql as ja}from"./packem_shared/MAX_SQL_ROWS-nMwkxv5f.mjs";import{awaitWsDrain as Ya,sendDeltaFrames as Ja,subscriptionListDeltas as Za,trySendFrame as $a}from"./packem_shared/awaitWsDrain-Bp2jKzIb.mjs";import{mergeChangedKeys as rt,recordChangedKeys as ot,writeTouchesMemo as at}from"./packem_shared/mergeChangedKeys-BXtUgIPW.mjs";import{createSystemReader as nt}from"./packem_shared/createSystemReader-DcDcrtM3.mjs";import{ConflictError as lt}from"./packem_shared/ConflictError-C8GtJmjS.mjs";import{DEFAULT_TRANSACTION_LIMITS as pt,TransactionHeadroomTracker as mt}from"./packem_shared/DEFAULT_TRANSACTION_LIMITS-DLUzZbta.mjs";import{hasTrigger as ct,runTriggers as St}from"./packem_shared/hasTrigger-CbkOHExZ.mjs";import{selectExpiredIds as xt}from"./packem_shared/selectExpiredIds-C6nQK7E2.mjs";import{compileWhereSql as Tt}from"./packem_shared/compileWhereSql-B4rPariq.mjs";import{RELATION_EXISTS_KEY as Et}from"./packem_shared/RELATION_EXISTS_KEY-BaqSIFU1.mjs";import{REPROJECTION_MIGRATION_PREFIX as At,reprojectionMigrationId as It}from"./packem_shared/REPROJECTION_MIGRATION_PREFIX-D2dltRFC.mjs";import{quoteIdentifier as Ct}from"./packem_shared/quoteIdentifier-CObIFRhb.mjs";import{runShardMigrations as Lt}from"./packem_shared/runShardMigrations-BqO6HPtX.mjs";import{stableStringify as yt}from"./packem_shared/stableStringify-BjLh4gvA.mjs";import{stableWireKey as Mt}from"./packem_shared/stableWireKey-l3cjIt-9.mjs";export{kr as ADMIN_FUNCTIONS,Gr as ADMIN_FUNCTION_PREFIX,m as AGGREGATE_SQL_FUNCTION,Ve as AGG_COUNT,Xe as AGG_KEY,je as AGG_VALUE,N as AUDIT_LOG_TABLE,z as CDC_LOG_TABLE,H as CDC_META_TABLE,ae as CLIENT_WATERMARK_TABLE,lt as ConflictError,I as CountRlsUnsupportedError,Pe as DATA_MIGRATION_STATE_TABLE,Br as DEFAULT_FANOUT_TOPIC_LIMIT,Wo as DEFAULT_MAX_RELATION_KEYS,ia as DEFAULT_MAX_RELAYS,oa as DEFAULT_PROMOTION_THRESHOLDS,pt as DEFAULT_TRANSACTION_LIMITS,Qe as DOC_COLUMN,Ur as FLAGS_FUNCTION_PREFIX,br as GEO_DEFAULT_PRECISION,me as GLOBAL_SHAPE_SNAPSHOT_TABLE,Te as IDEMPOTENCY_TABLE,Jr as MAIL_RETENTION,Zr as MAIL_TABLE,wr as MAX_PAGE_SIZE,Ha as MAX_SQL_ROWS,to as NotFoundError,P as NotUniqueError,pa as OwnerRelay,go as QUEUE_TABLE,_o as RANK_TIEBREAK,Et as RELATION_EXISTS_KEY,Kr as RELATION_FUNCTION_PREFIX,At as REPROJECTION_MIGRATION_PREFIX,Ia as RLS_UNWRAP_SYMBOL,Do as ReactiveCache,ma as RelayMember,Ra as RlsRequiredError,Ue as SCAN_DEP,La as SCHEMA_HISTORY_MAX_VERSIONS,Le as SEARCH_STATE_TABLE,qa as ShardRunner,mt as TransactionHeadroomTracker,te as advanceClientWatermark,Ye as aggUpsertSql,d as aggregateSqlFunction,f as aggregateTableName,M as appendAuditEntry,V as appendCdcChange,X as applyCdcChanges,Qo as applyOnDelete,po as applySelect,so as armRestore,vo as assertFlatPredicate,Va as assertReadonly,zo as assertShapeShardable,k as assertValidClientId,Ya as awaitWsDrain,w as backfillAggregateIndexes,K as backfillRankIndexes,q as backfillSearchIndexes,W as backfillSearchIndexesForTable,yr as boundingBoxCenter,Nr as boundingBoxGeohashes,Uo as buildIndexRange,Ga as buildPokeFrames,Ta as buildReprojectionMigration,mo as buildSeekBeforeWhere,co as buildSeekWhere,Da as buildSettings,j as bumpCdcEpoch,aa as clampPromotionThresholds,$r as clearCapturedMail,Eo as clearQueueMessages,T as coerceAggregateNumber,Tt as compileWhereSql,Re as computeRankPage,Ho as containsRelationPredicate,ga as countLegacyRows,Mr as coveringGeohashes,ie as createCompanionSync,we as createDependencyTracker,qr as createFanoutCounters,Je as createIndexSql,Go as createReadFootprint,da as createRelayLink,Sa as createReplicaLink,G as createShardCtxDb,nt as createSystemReader,So as decodeCursor,de as deleteGlobalShapeSnapshot,ce as deleteGlobalShapeSnapshotsForConnection,Ke as depKey,dr as diffExternalSource,Ba as diffGlobalMembership,Yo as distinctValues,g as encodeAggregateKey,uo as encodeCursor,Or as encodeGeohash,Lo as encodePartitionKey,Ua as encodeRowsPatch,O as ensureAuditTable,eo as ensureMailTable,o as exportShardRows,a as exportShardTable,Wr as facetColumn,Jo as fanOutScalarCounts,vr as findStorageReferences,E as foldAggregateTally,ua as gateReplicaDispatch,Ze as geoTableName,Ca as guardWriter,xa as handleReplicaControl,ct as hasTrigger,Fr as haversineMeters,Ce as hydrateDocsById,t as importShardRows,wo as indexKeysForRow,Pa as isDevEnvironment,$e as isFtsAvailable,ho as isLossyBody,Vo as isRelationPredicate,Ir as isSoftDeleted,Rr as isSourceDue,er as jsonPath,rr as jsonPathSql,Ko as keysTouchRanges,Sr as liftSourceId,Xa as lintReadonlySql,zr as listTables,bo as matchesRankStaticWhere,c as matchesStaticWhere,Tr as materializeExternalRows,gr as materializeExternalRowsIncremental,rt as mergeChangedKeys,R as mergeWhere,Q as migrateCdcLog,Y as migrateCdcMeta,ne as migrateClientWatermark,Se as migrateGlobalShapeSnapshot,ge as migrateIdempotency,be as migrateSearchState,J as minCdcSeq,ta as nextPromotionState,S as normalizeCountArgument,B as normalizeIdStructurally,xo as normalizeOrderKeys,ur as normalizeSourceDocument,xr as normalizeSourceValue,ir as param,n as parseExportShardArgs,s as parseImportShardArgs,C as planAggregateLookup,Dr as pointInBoundingBox,wa as projectColumns,Cr as pullExternalSourceIncrementalTick,_r as pullExternalSourceTick,or as qualifiedJsonPath,ar as qualifiedJsonPathSql,Ct as quoteIdentifier,yo as rankKeyFromDoc,No as rankTableName,Po as reactiveCacheKey,h as readAggregateValue,F as readAuditLog,lo as readBookmark,ro as readCapturedMail,Z as readCdcChanges,$ as readCdcCursor,ee as readCdcEpoch,se as readClientWatermark,Er as readExternalSourceBaseline,ue as readGlobalShapeSnapshot,Ee as readIdempotent,ke as readMigrationStatus,Ao as readQueueMessageById,Io as readQueueMessages,ba as readSchemaHistory,ya as readSchemaVersion,ye as readSearchBackfillState,Hr as readTablePage,oo as recordCapturedMail,ot as recordChangedKeys,Vr as recordFanoutPass,Ro as recordQueueMessages,Na as recordSchemaVersion,Zo as relationHooks,na as relayCountFor,pr as renderSql,Ea as reprojectableFields,It as reprojectionMigrationId,ha as reprojectionTables,Mo as resolveRankPartition,Xo as resolveRelationPredicates,$o as resolveWith,tr as rowToDocument,Ge as runDataMigration,ve as runDrizzle,hr as runExternalSourceTick,ja as runReadonlySql,ea as runRowValidators,Lt as runShardMigrations,va as runSocketPool,ze as runSql,St as runTriggers,xt as selectExpiredIds,l as selectExportTables,_ as selectIndexForAggregate,L as selectIndexForCount,b as selectIndexForGroupBy,Xr as selectMatchingIds,Oe as selectShapeMemberIds,Fe as selectShapeRows,Ja as sendDeltaFrames,Oa as serializeSqlValue,sa as shapeRoutingKey,fo as softDeleteScope,Oo as sortColumnName,yt as stableStringify,Mt as stableWireKey,Za as subscriptionListDeltas,jr as summarizeFanoutTopics,Qr as summarizeSubscriptions,nr as tableColumns,qe as tableFromDepKey,u as throwingScheduler,re as trimCdcChanges,he as trimIdempotent,sr as tryRowToDocument,$a as trySendFrame,i as validateImportRow,xe as writeGlobalShapeSnapshot,Ae as writeIdempotent,Ne as writeSearchBackfillState,at 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 m,aggregateSqlFunction as d,matchesStaticWhere as c,normalizeCountArgument as S,throwingScheduler as u}from"./packem_shared/AGGREGATE_SQL_FUNCTION-CTo0-9iZ.mjs";import{aggregateTableName as f,coerceAggregateNumber as T,encodeAggregateKey as g,foldAggregateTally as E,readAggregateValue as h}from"./packem_shared/aggregateTableName-DgYMC5tr.mjs";import{CountRlsUnsupportedError as I,mergeWhere as R,planAggregateLookup as C,selectIndexForAggregate as _,selectIndexForCount as L,selectIndexForGroupBy as b}from"./packem_shared/CountRlsUnsupportedError-8BqPYQoP.mjs";import{AUDIT_LOG_TABLE as N,appendAuditEntry as M,ensureAuditTable as O,readAuditLog as F}from"./packem_shared/AUDIT_LOG_TABLE-0FKs74RO.mjs";import{NotUniqueError as P,assertValidClientId as k,createShardCtxDb as G,normalizeIdStructurally as B}from"./packem_shared/NotUniqueError-DJf3W9gG.mjs";import{backfillAggregateIndexes as w,backfillRankIndexes as q,backfillSearchIndexes as K,backfillSearchIndexesForTable as W}from"./packem_shared/backfillAggregateIndexes-Czk8MQ3M.mjs";import{CDC_LOG_TABLE as z,CDC_META_TABLE as H,appendCdcChange as V,applyCdcChanges as X,bumpCdcEpoch as j,migrateCdcLog as Q,migrateCdcMeta as Y,minCdcSeq as J,readCdcChanges as Z,readCdcCursor as $,readCdcEpoch as ee,trimCdcChanges as re}from"./packem_shared/CDC_LOG_TABLE-CIfexI1y.mjs";import{CLIENT_WATERMARK_TABLE as ae,advanceClientWatermark as te,migrateClientWatermark as ne,readClientWatermark as le}from"./packem_shared/CLIENT_WATERMARK_TABLE-BogWgD2Q.mjs";import{S as ie}from"./packem_shared/ctx-db-companions-D2ZMFBrP.mjs";import{GLOBAL_SHAPE_SNAPSHOT_TABLE as me,deleteGlobalShapeSnapshot as de,deleteGlobalShapeSnapshotsForConnection as ce,migrateGlobalShapeSnapshot as Se,readGlobalShapeSnapshot as ue,writeGlobalShapeSnapshot as xe}from"./packem_shared/GLOBAL_SHAPE_SNAPSHOT_TABLE-T5smo6RP.mjs";import{IDEMPOTENCY_TABLE as Te,migrateIdempotency as ge,readIdempotent as Ee,trimIdempotent as he,writeIdempotent as Ae}from"./packem_shared/IDEMPOTENCY_TABLE-DPFwgQbE.mjs";import{computeRankPage as Re,hydrateDocsById as Ce}from"./packem_shared/computeRankPage-CPVNOrM5.mjs";import{SEARCH_STATE_TABLE as Le,migrateSearchState as be,readSearchBackfillState as ye,writeSearchBackfillState as Ne}from"./packem_shared/SEARCH_STATE_TABLE-MDlr30EJ.mjs";import{selectShapeMemberIds as Oe,selectShapeRows as Fe}from"./packem_shared/selectShapeMemberIds-EPo0xxs_.mjs";import{DATA_MIGRATION_STATE_TABLE as Pe,readMigrationStatus as ke,runDataMigration as Ge}from"./packem_shared/DATA_MIGRATION_STATE_TABLE-BcmXmY5q.mjs";import{SCAN_DEP as Ue,createDependencyTracker as we,depKey as qe,tableFromDepKey as Ke}from"./packem_shared/SCAN_DEP-D_yR9EeV.mjs";import{runDrizzle as ve,runSql as ze}from"./packem_shared/runDrizzle-CgYGDEeB.mjs";import{T as Ve,c as Xe,p as je,a as Qe,A as Ye,y as Je,h as Ze,C as $e,_ as er,N as rr,S as or,O as ar,E as tr,I as nr,D as lr}from"./packem_shared/do-sql-Cg_QiQYA.mjs";import{param as ir,renderSql as pr,sqliteInList as mr,unionAll as dr}from"./packem_shared/param-C68MV3DD.mjs";import{diffExternalSource as Sr}from"./packem_shared/diffExternalSource-DMpkJta1.mjs";import{liftSourceId as xr,normalizeSourceDocument as fr,normalizeSourceValue as Tr}from"./packem_shared/liftSourceId-DApAbu7Q.mjs";import{materializeExternalRows as Er,materializeExternalRowsIncremental as hr,readExternalSourceBaseline as Ar,runExternalSourceTick as Ir}from"./packem_shared/materializeExternalRows-CUrDeD82.mjs";import{isSoftDeleted as Cr,isSourceDue as _r,pullExternalSourceIncrementalTick as Lr,pullExternalSourceTick as br}from"./packem_shared/isSoftDeleted-ZosHVk5V.mjs";import{GEO_DEFAULT_PRECISION as Nr,boundingBoxCenter as Mr,boundingBoxGeohashes as Or,coveringGeohashes as Fr,encodeGeohash as Dr,haversineMeters as Pr,pointInBoundingBox as kr}from"./packem_shared/GEO_DEFAULT_PRECISION-DyI5zggj.mjs";import{ADMIN_FUNCTIONS as Br,ADMIN_FUNCTION_PREFIX as Ur,DEFAULT_FANOUT_TOPIC_LIMIT as wr,FLAGS_FUNCTION_PREFIX as qr,MAX_PAGE_SIZE as Kr,RELATION_FUNCTION_PREFIX as Wr,createFanoutCounters as vr,facetColumn as zr,findStorageReferences as Hr,listTables as Vr,readTablePage as Xr,recordFanoutPass as jr,selectMatchingIds as Qr,summarizeFanoutTopics as Yr,summarizeSubscriptions as Jr}from"./packem_shared/ADMIN_FUNCTIONS-BFYAiahG.mjs";import{MAIL_RETENTION as $r,MAIL_TABLE as eo,clearCapturedMail as ro,ensureMailTable as oo,readCapturedMail as ao,recordCapturedMail as to}from"./packem_shared/MAIL_RETENTION-Cp9LWzM4.mjs";import{NotFoundError as lo}from"./packem_shared/NotFoundError-BhF7FeFr.mjs";import{armRestore as io,readBookmark as po}from"./packem_shared/armRestore-BNzdvQ_o.mjs";import{applySelect as co,buildSeekBeforeWhere as So,buildSeekWhere as uo,decodeCursor as xo,encodeCursor as fo,normalizeOrderKeys as To,softDeleteScope as go}from"./packem_shared/applySelect-UY-o13Ia.mjs";import{QUEUE_TABLE as ho,clearQueueMessages as Ao,isLossyBody as Io,readQueueMessageById as Ro,readQueueMessages as Co,recordQueueMessages as _o}from"./packem_shared/QUEUE_TABLE-C1mp0Du0.mjs";import{RANK_TIEBREAK as bo,encodePartitionKey as yo,matchesRankStaticWhere as No,rankKeyFromDoc as Mo,rankTableName as Oo,resolveRankPartition as Fo,sortColumnName as Do}from"./packem_shared/RANK_TIEBREAK-DDtST3gN.mjs";import{ReactiveCache as ko,reactiveCacheKey as Go}from"./packem_shared/ReactiveCache-Cu8IfE1M.mjs";import{createReadFootprint as Uo}from"./packem_shared/createReadFootprint-DIrrxRTE.mjs";import{buildIndexRange as qo,indexKeysForRow as Ko,keysTouchRanges as Wo}from"./packem_shared/buildIndexRange-DFsdtPjD.mjs";import{DEFAULT_MAX_RELATION_KEYS as zo,assertFlatPredicate as Ho,assertShapeShardable as Vo,containsRelationPredicate as Xo,isRelationPredicate as jo,resolveRelationPredicates as Qo}from"./packem_shared/DEFAULT_MAX_RELATION_KEYS-DjKka36Z.mjs";import{applyOnDelete as Jo,distinctValues as Zo,fanOutScalarCounts as $o,relationHooks as ea,resolveWith as ra,runRowValidators as oa}from"./packem_shared/applyOnDelete-By23GK-k.mjs";import{DEFAULT_PROMOTION_THRESHOLDS as ta,clampPromotionThresholds as na,nextPromotionState as la,relayCountFor as sa,shapeRoutingKey as ia}from"./packem_shared/DEFAULT_PROMOTION_THRESHOLDS-B2rUe1bg.mjs";import{DEFAULT_MAX_RELAYS as ma,OwnerRelay as da,RelayMember as ca,createRelayLink as Sa}from"./packem_shared/DEFAULT_MAX_RELAYS-B19vrJxP.mjs";import{createReplicaLink as xa,gateReplicaDispatch as fa,handleReplicaControl as Ta}from"./packem_shared/createReplicaLink-BMNW0SX6.mjs";import{buildReprojectionMigration as Ea,countLegacyRows as ha,reprojectableFields as Aa,reprojectionTables as Ia}from"./packem_shared/buildReprojectionMigration-DMMWPqvy.mjs";import{RLS_UNWRAP_SYMBOL as Ca,RlsRequiredError as _a,guardWriter as La}from"./packem_shared/RLS_UNWRAP_SYMBOL-DcqORh2s.mjs";import{SCHEMA_HISTORY_MAX_VERSIONS as ya,readSchemaHistory as Na,readSchemaVersion as Ma,recordSchemaVersion as Oa}from"./packem_shared/SCHEMA_HISTORY_MAX_VERSIONS-CGlXjXRT.mjs";import{serializeSqlValue as Da}from"./packem_shared/serializeSqlValue-BR4UOWoP.mjs";import{buildSettings as ka,isDevEnvironment as Ga}from"./packem_shared/buildSettings-COIJsw7a.mjs";import{buildPokeFrames as Ua,diffGlobalMembership as wa,encodeRowsPatch as qa,projectColumns as Ka}from"./packem_shared/buildPokeFrames-CqxaN8_H.mjs";import{ShardRunner as va}from"./packem_shared/ShardRunner-DIqVdWtk.mjs";import{runSocketPool as Ha}from"./packem_shared/runSocketPool-DPQLVyWF.mjs";import{MAX_SQL_ROWS as Xa,assertReadonly as ja,lintReadonlySql as Qa,runReadonlySql as Ya}from"./packem_shared/MAX_SQL_ROWS-nMwkxv5f.mjs";import{awaitWsDrain as Za,sendDeltaFrames as $a,subscriptionListDeltas as et,trySendFrame as rt}from"./packem_shared/awaitWsDrain-Bp2jKzIb.mjs";import{mergeChangedKeys as at,recordChangedKeys as tt,writeTouchesMemo as nt}from"./packem_shared/mergeChangedKeys-BXtUgIPW.mjs";import{createSystemReader as st}from"./packem_shared/createSystemReader-DcDcrtM3.mjs";import{ConflictError as pt}from"./packem_shared/ConflictError-C8GtJmjS.mjs";import{DEFAULT_TRANSACTION_LIMITS as dt,TransactionHeadroomTracker as ct}from"./packem_shared/DEFAULT_TRANSACTION_LIMITS-DLUzZbta.mjs";import{hasTrigger as ut,runTriggers as xt}from"./packem_shared/hasTrigger-CbkOHExZ.mjs";import{selectExpiredIds as Tt}from"./packem_shared/selectExpiredIds-DLKts8V0.mjs";import{compileWhereSql as Et,literalInList as ht}from"./packem_shared/compileWhereSql-DxD5mzDy.mjs";import{RELATION_EXISTS_KEY as It}from"./packem_shared/RELATION_EXISTS_KEY-BaqSIFU1.mjs";import{REPROJECTION_MIGRATION_PREFIX as Ct,reprojectionMigrationId as _t}from"./packem_shared/REPROJECTION_MIGRATION_PREFIX-D2dltRFC.mjs";import{quoteIdentifier as bt}from"./packem_shared/quoteIdentifier-CObIFRhb.mjs";import{runShardMigrations as Nt}from"./packem_shared/runShardMigrations-CtlcSZ3r.mjs";import{stableStringify as Ot}from"./packem_shared/stableStringify-BjLh4gvA.mjs";import{stableWireKey as Dt}from"./packem_shared/stableWireKey-l3cjIt-9.mjs";export{Br as ADMIN_FUNCTIONS,Ur as ADMIN_FUNCTION_PREFIX,m as AGGREGATE_SQL_FUNCTION,Ve as AGG_COUNT,Xe as AGG_KEY,je as AGG_VALUE,N as AUDIT_LOG_TABLE,z as CDC_LOG_TABLE,H as CDC_META_TABLE,ae as CLIENT_WATERMARK_TABLE,pt as ConflictError,I as CountRlsUnsupportedError,Pe as DATA_MIGRATION_STATE_TABLE,wr as DEFAULT_FANOUT_TOPIC_LIMIT,zo as DEFAULT_MAX_RELATION_KEYS,ma as DEFAULT_MAX_RELAYS,ta as DEFAULT_PROMOTION_THRESHOLDS,dt as DEFAULT_TRANSACTION_LIMITS,Qe as DOC_COLUMN,qr as FLAGS_FUNCTION_PREFIX,Nr as GEO_DEFAULT_PRECISION,me as GLOBAL_SHAPE_SNAPSHOT_TABLE,Te as IDEMPOTENCY_TABLE,$r as MAIL_RETENTION,eo as MAIL_TABLE,Kr as MAX_PAGE_SIZE,Xa as MAX_SQL_ROWS,lo as NotFoundError,P as NotUniqueError,da as OwnerRelay,ho as QUEUE_TABLE,bo as RANK_TIEBREAK,It as RELATION_EXISTS_KEY,Wr as RELATION_FUNCTION_PREFIX,Ct as REPROJECTION_MIGRATION_PREFIX,Ca as RLS_UNWRAP_SYMBOL,ko as ReactiveCache,ca as RelayMember,_a as RlsRequiredError,Ue as SCAN_DEP,ya as SCHEMA_HISTORY_MAX_VERSIONS,Le as SEARCH_STATE_TABLE,va as ShardRunner,ct as TransactionHeadroomTracker,te as advanceClientWatermark,Ye as aggUpsertSql,d as aggregateSqlFunction,f as aggregateTableName,M as appendAuditEntry,V as appendCdcChange,X as applyCdcChanges,Jo as applyOnDelete,co as applySelect,io as armRestore,Ho as assertFlatPredicate,ja as assertReadonly,Vo as assertShapeShardable,k as assertValidClientId,Za as awaitWsDrain,w as backfillAggregateIndexes,q as backfillRankIndexes,K as backfillSearchIndexes,W as backfillSearchIndexesForTable,Mr as boundingBoxCenter,Or as boundingBoxGeohashes,qo as buildIndexRange,Ua as buildPokeFrames,Ea as buildReprojectionMigration,So as buildSeekBeforeWhere,uo as buildSeekWhere,ka as buildSettings,j as bumpCdcEpoch,na as clampPromotionThresholds,ro as clearCapturedMail,Ao as clearQueueMessages,T as coerceAggregateNumber,Et as compileWhereSql,Re as computeRankPage,Xo as containsRelationPredicate,ha as countLegacyRows,Fr as coveringGeohashes,ie as createCompanionSync,we as createDependencyTracker,vr as createFanoutCounters,Je as createIndexSql,Uo as createReadFootprint,Sa as createRelayLink,xa as createReplicaLink,G as createShardCtxDb,st as createSystemReader,xo as decodeCursor,de as deleteGlobalShapeSnapshot,ce as deleteGlobalShapeSnapshotsForConnection,qe as depKey,Sr as diffExternalSource,wa as diffGlobalMembership,Zo as distinctValues,g as encodeAggregateKey,fo as encodeCursor,Dr as encodeGeohash,yo as encodePartitionKey,qa as encodeRowsPatch,O as ensureAuditTable,oo as ensureMailTable,o as exportShardRows,a as exportShardTable,zr as facetColumn,$o as fanOutScalarCounts,Hr as findStorageReferences,E as foldAggregateTally,fa as gateReplicaDispatch,Ze as geoTableName,La as guardWriter,Ta as handleReplicaControl,ut as hasTrigger,Pr as haversineMeters,Ce as hydrateDocsById,t as importShardRows,Ko as indexKeysForRow,Ga as isDevEnvironment,$e as isFtsAvailable,Io as isLossyBody,jo as isRelationPredicate,Cr as isSoftDeleted,_r as isSourceDue,er as jsonPath,rr as jsonPathSql,Wo as keysTouchRanges,xr as liftSourceId,Qa as lintReadonlySql,Vr as listTables,ht as literalInList,No as matchesRankStaticWhere,c as matchesStaticWhere,Er as materializeExternalRows,hr as materializeExternalRowsIncremental,at as mergeChangedKeys,R as mergeWhere,Q as migrateCdcLog,Y as migrateCdcMeta,ne as migrateClientWatermark,Se as migrateGlobalShapeSnapshot,ge as migrateIdempotency,be as migrateSearchState,J as minCdcSeq,la as nextPromotionState,S as normalizeCountArgument,B as normalizeIdStructurally,To as normalizeOrderKeys,fr as normalizeSourceDocument,Tr as normalizeSourceValue,ir as param,n as parseExportShardArgs,l as parseImportShardArgs,C as planAggregateLookup,kr as pointInBoundingBox,Ka as projectColumns,Lr as pullExternalSourceIncrementalTick,br as pullExternalSourceTick,or as qualifiedJsonPath,ar as qualifiedJsonPathSql,bt as quoteIdentifier,Mo as rankKeyFromDoc,Oo as rankTableName,Go as reactiveCacheKey,h as readAggregateValue,F as readAuditLog,po as readBookmark,ao as readCapturedMail,Z as readCdcChanges,$ as readCdcCursor,ee as readCdcEpoch,le as readClientWatermark,Ar as readExternalSourceBaseline,ue as readGlobalShapeSnapshot,Ee as readIdempotent,ke as readMigrationStatus,Ro as readQueueMessageById,Co as readQueueMessages,Na as readSchemaHistory,Ma as readSchemaVersion,ye as readSearchBackfillState,Xr as readTablePage,to as recordCapturedMail,tt as recordChangedKeys,jr as recordFanoutPass,_o as recordQueueMessages,Oa as recordSchemaVersion,ea as relationHooks,sa as relayCountFor,pr as renderSql,Aa as reprojectableFields,_t as reprojectionMigrationId,Ia as reprojectionTables,Fo as resolveRankPartition,Qo as resolveRelationPredicates,ra as resolveWith,tr as rowToDocument,Ge as runDataMigration,ve as runDrizzle,Ir as runExternalSourceTick,Ya as runReadonlySql,oa as runRowValidators,Nt as runShardMigrations,Ha as runSocketPool,ze as runSql,xt as runTriggers,Tt as selectExpiredIds,s as selectExportTables,_ as selectIndexForAggregate,L as selectIndexForCount,b as selectIndexForGroupBy,Qr as selectMatchingIds,Oe as selectShapeMemberIds,Fe as selectShapeRows,$a as sendDeltaFrames,Da as serializeSqlValue,ia as shapeRoutingKey,go as softDeleteScope,Do as sortColumnName,mr as sqliteInList,Ot as stableStringify,Dt as stableWireKey,et as subscriptionListDeltas,Yr as summarizeFanoutTopics,Jr as summarizeSubscriptions,nr as tableColumns,Ke as tableFromDepKey,u as throwingScheduler,re as trimCdcChanges,he as trimIdempotent,lr as tryRowToDocument,rt as trySendFrame,dr as unionAll,i as validateImportRow,xe as writeGlobalShapeSnapshot,Ae as writeIdempotent,Ne as writeSearchBackfillState,nt as writeTouchesMemo};
@@ -0,0 +1 @@
1
+ import{LunoraError as T}from"@lunora/errors";import{j as L,s as k}from"./do-sql-Cg_QiQYA.mjs";import{quoteIdentifier as d}from"./quoteIdentifier-CObIFRhb.mjs";import{s as P}from"./wire-codec-Dsy70M3Q.mjs";const te="__lunora_admin__:",ae="__lunora_relation__:",re="__lunora_flags__:",se={applyCdc:"__lunora_admin__:applyCdc",aiAvailable:"__lunora_admin__:aiAvailable",aiChartConfig:"__lunora_admin__:aiChartConfig",aiGenerateSql:"__lunora_admin__:aiGenerateSql",aiTableFilter:"__lunora_admin__:aiTableFilter",assignIssue:"__lunora_admin__:assignIssue",backRelationCounts:"__lunora_admin__:backRelationCounts",cdcSync:"__lunora_admin__:cdcSync",clearCapturedMail:"__lunora_admin__:clearCapturedMail",clearQueueMessages:"__lunora_admin__:clearQueueMessages",clearTable:"__lunora_admin__:clearTable",createWorkflowInstance:"__lunora_admin__:createWorkflowInstance",deleteRows:"__lunora_admin__:deleteRows",describeTable:"__lunora_admin__:describeTable",describeTables:"__lunora_admin__:describeTables",explainIssue:"__lunora_admin__:explainIssue",exportShard:"__lunora_admin__:exportShard",facetColumn:"__lunora_admin__:facetColumn",getAdvisories:"__lunora_admin__:getAdvisories",getAdvisorProcedures:"__lunora_admin__:getAdvisorProcedures",getAuditLog:"__lunora_admin__:getAuditLog",getAuthMetrics:"__lunora_admin__:getAuthMetrics",getCapturedMail:"__lunora_admin__:getCapturedMail",getFanoutMetrics:"__lunora_admin__:getFanoutMetrics",getFunctionStats:"__lunora_admin__:getFunctionStats",getIssues:"__lunora_admin__:getIssues",getMetricHistory:"__lunora_admin__:getMetricHistory",getMetricSeries:"__lunora_admin__:getMetricSeries",listSubscriptions:"__lunora_admin__:listSubscriptions",listTableIndexes:"__lunora_admin__:listTableIndexes",listTablesIndexes:"__lunora_admin__:listTablesIndexes",getLogs:"__lunora_admin__:getLogs",getMetrics:"__lunora_admin__:getMetrics",getPitrBookmark:"__lunora_admin__:getPitrBookmark",getQueryInsights:"__lunora_admin__:getQueryInsights",getQueueMessages:"__lunora_admin__:getQueueMessages",getRequestLog:"__lunora_admin__:getRequestLog",getSecurityAudit:"__lunora_admin__:getSecurityAudit",getSettings:"__lunora_admin__:getSettings",getTraces:"__lunora_admin__:getTraces",getWorkflowInstanceStatus:"__lunora_admin__:getWorkflowInstanceStatus",ignoreIssue:"__lunora_admin__:ignoreIssue",importShard:"__lunora_admin__:importShard",listFlags:"__lunora_admin__:listFlags",listQueues:"__lunora_admin__:listQueues",lintSql:"__lunora_admin__:lintSql",listTables:"__lunora_admin__:listTables",listWorkflows:"__lunora_admin__:listWorkflows",maskPolicies:"__lunora_admin__:maskPolicies",migrationStatus:"__lunora_admin__:migrationStatus",pitrRestore:"__lunora_admin__:pitrRestore",rankBefore:"__lunora_admin__:rankBefore",rankPage:"__lunora_admin__:rankPage",readTablePage:"__lunora_admin__:readTablePage",recordAuthEvent:"__lunora_admin__:recordAuthEvent",recordContainerEvent:"__lunora_admin__:recordContainerEvent",recordMail:"__lunora_admin__:recordMail",recordQueueMessage:"__lunora_admin__:recordQueueMessage",replayQueueMessage:"__lunora_admin__:replayQueueMessage",resolveIssue:"__lunora_admin__:resolveIssue",rlsPolicies:"__lunora_admin__:rlsPolicies",schemaHistory:"__lunora_admin__:schemaHistory",schemaVersion:"__lunora_admin__:schemaVersion",runAs:"__lunora_admin__:runAs",runMigration:"__lunora_admin__:runMigration",runSql:"__lunora_admin__:runSql",sendQueueMessage:"__lunora_admin__:sendQueueMessage",sendTestMail:"__lunora_admin__:sendTestMail",setIssueSeverity:"__lunora_admin__:setIssueSeverity",storageOrphans:"__lunora_admin__:storageOrphans",storageReferences:"__lunora_admin__:storageReferences",storageRules:"__lunora_admin__:storageRules",studioFeatures:"__lunora_admin__:studioFeatures",writeRow:"__lunora_admin__:writeRow"},D=50,f=500,U=30,q=200,m="__doc__",R=e=>{try{const t=JSON.parse(e);return t!==null&&typeof t=="object"&&!Array.isArray(t)?t:void 0}catch{return}},W=e=>{const{[k]:t,...a}=e;return t===void 0?a:t===null||typeof t!="object"||Array.isArray(t)?{[k]:t,...a}:{...a,...P(t)}},j=(e,t)=>{if(!e.includes(m))return{columns:e,rows:t};const a=[];for(const s of t){const _=s[m],u=typeof _=="string"?R(_):void 0;if(u===void 0)return{columns:e,rows:t};const i=Object.fromEntries(Object.entries(s).filter(([l])=>l!==m));a.push({...i,...W(u)})}const r=e.filter(s=>s!==m),o=[],n=new Set(r);for(const s of a)for(const _ of Object.keys(s))n.has(_)||(n.add(_),o.push(_));return{columns:[...r,...o],rows:a}},w=e=>`instr(lower(CAST(${e} AS TEXT)), lower(?)) > 0`,I=e=>e.startsWith("sqlite_")||e.startsWith("_cf_")||e.startsWith("__miniflare")||e.startsWith("__lunora")||e.includes("__fts_"),v=(e,t,a)=>Math.min(Math.max(e,t),a),$=(e,t)=>{const a=e.exec(`SELECT COUNT(*) AS c FROM ${t}`).one();return Number(a.c)},oe=e=>{const t=e.exec("SELECT name FROM sqlite_master WHERE type = 'table' ORDER BY name").toArray(),a=[];for(const{name:r}of t)I(r)||a.push({name:r,rowCount:$(e,d(r))});return a},x=(e,t)=>e.exec("SELECT name FROM sqlite_master WHERE type = 'table' AND name = ? LIMIT 1",t).toArray().length>0,C=(e,t)=>{if(I(t)||!x(e,t))throw new T("UNKNOWN_TABLE",`unknown table: ${t}`,{status:404})},b=(e,t)=>e.exec(`PRAGMA table_info(${t})`).toArray().map(a=>a.name),Q={eq:"=",gt:">",gte:">=",lt:"<",lte:"<=",ne:"<>"},B=e=>typeof e=="string"?e:typeof e=="number"||typeof e=="boolean"?String(e):"",M=(e,t)=>{const a=t.includes(e),r=t.includes(m);if(!(!a&&!r))return a?{expression:d(e),params:[]}:{expression:`json_extract(${d(m)}, ?)`,params:[`$.${L(e)}`]}},H=(e,t)=>{const a=M(e.column,t);if(a===void 0)return;const{expression:r,params:o}=a;return e.operator==="contains"?{params:[...o,B(e.value)],sql:w(r)}:{params:[...o,e.value],sql:`${r} ${Q[e.operator]} ?`}},G=/^(\d{4})(?:-(\d{2}))?(?:-(\d{2}))?$/u,X=e=>{const t=G.exec(e.trim());if(t===null)return;const a=Number(t[1]),r=t[2]===void 0?void 0:Number(t[2]),o=t[3]===void 0?void 0:Number(t[3]);if(r!==void 0&&(r<1||r>12)||o!==void 0&&(o<1||o>31)||a<100)return;const n=Date.UTC(a,(r??1)-1,o??1);if(o!==void 0&&new Date(n).getUTCDate()!==o)return;let s;return o!==void 0?s=Date.UTC(a,(r??1)-1,o+1):r===void 0?s=Date.UTC(a+1,0,1):s=Date.UTC(a,r,1),{from:n,to:s}},E=(e,t,a)=>{const r=[],o=[];if(t!==""&&e.length>0){const n=e.map(_=>w(d(_)));o.push(...e.map(()=>t));const s=X(t);if(s!==void 0)for(const _ of e)n.push(`(${d(_)} >= ? AND ${d(_)} < ?)`),o.push(s.from,s.to);r.push(`(${n.join(" OR ")})`)}for(const n of a??[]){const s=H(n,e);s!==void 0&&(r.push(`(${s.sql})`),o.push(...s.params))}return r.length===0?void 0:{parameters:o,where:r.join(" AND ")}},Y=(e,t)=>{if(e===void 0)return;const a=M(e.column,t);if(a===void 0)return;const r=e.direction==="desc"?"DESC":"ASC";return{params:a.params,sql:`${a.expression} ${r}`}},ne=(e,t)=>{const{table:a}=t;C(e,a);const r=v(Math.trunc(t.limit??D),1,f),o=Math.max(0,Math.trunc(t.offset??0)),n=d(a),s=b(e,n),_=t.search?.trim()??"",u=h=>{if(t.refs===void 0)return h;const S={};for(const y of h.columns){const O=t.refs[y];O!==void 0&&(S[y]=O)}return Object.keys(S).length>0?{...h,refs:S}:h},i=E(s,_,t.filters),l=Y(t.orderBy,s),c=i===void 0?"":` WHERE ${i.where}`,p=l===void 0?"":` ORDER BY ${l.sql}`,g=i?.parameters??[],N=l?.params??[];let A;t.skipCount||(A=i===void 0?$(e,n):Number(e.exec(`SELECT COUNT(*) AS c FROM ${n}${c}`,...g).one().c));const F=e.exec(`SELECT * FROM ${n}${c}${p} LIMIT ? OFFSET ?`,...g,...N,r,o).toArray();return u({...j(s,F),total:A})},_e=(e,t)=>{const{table:a}=t;C(e,a);const r=v(Math.trunc(t.limit??f),1,f),o=d(a),n=b(e,o),s=t.search?.trim()??"",_=E(n,s,t.filters),u=_===void 0?e.exec(`SELECT id FROM ${o} LIMIT ?`,r+1).toArray():e.exec(`SELECT id FROM ${o} WHERE ${_.where} LIMIT ?`,..._.parameters,r+1).toArray(),i=u.length>r,l=u.slice(0,r).map(c=>c.id);return{hasMore:i,ids:l}},K=(e,t,a)=>{const r=new Set(a.filter(n=>n!==m));if(!a.includes(m))return r;const o=e.exec(`SELECT ${d(m)} AS doc FROM ${t} LIMIT ?`,f).toArray();for(const{doc:n}of o){const s=typeof n=="string"?R(n):void 0;if(s!==void 0)for(const _ of Object.keys(s))r.add(_)}return r},ie=(e,t)=>{const{column:a,table:r}=t;C(e,r);const o=d(r),n=b(e,o);if(!K(e,o,n).has(a))throw new T("UNKNOWN_COLUMN",`unknown column: ${a}`,{status:404});const s=M(a,n);if(s===void 0)throw new T("UNKNOWN_COLUMN",`unknown column: ${a}`,{status:404});const _=v(Math.trunc(t.limit??U),1,q),u=t.search?.trim()??"",i=E(n,u,t.filters),l=i===void 0?"":` WHERE ${i.where}`,c=i?.parameters??[],p=e.exec(`SELECT ${s.expression} AS value, COUNT(*) AS count FROM ${o}${l} GROUP BY ${s.expression} ORDER BY count DESC LIMIT ?`,...s.params,...c,...s.params,_+1).toArray();return{truncated:p.length>_,values:p.slice(0,_).map(g=>({count:Number(g.count),value:g.value}))}},ue=(e,t,a)=>{const r={},o=a.slice(0,f);for(const s of o)r[s]=[];if(o.length===0)return{references:r,storageColumns:t};const n=o.map(()=>"?").join(", ");for(const[s,_]of Object.entries(t)){if(I(s)||!x(e,s))continue;const u=d(s),i=b(e,u);for(const l of _){const c=M(l,i);if(c===void 0)continue;const p=e.exec(`SELECT id, ${c.expression} AS ref FROM ${u} WHERE ${c.expression} IN (${n})`,...c.params,...c.params,...o).toArray();for(const g of p)r[g.ref]?.push({column:l,id:g.id,table:s})}}return{references:r,storageColumns:t}},le=e=>{const t=e.map((r,o)=>{const n=Object.values(r.subs??{}).map(s=>({args:s.args,functionPath:s.functionPath,table:s.table}));return{admin:r.admin===!0,id:o,subscriptions:n}}),a=t.reduce((r,o)=>r+o.subscriptions.length,0);return{connections:t,totalConnections:t.length,totalSubscriptions:a}},z=20,ce=()=>({maxMs:0,passes:0,peakSocketsIterated:0,socketsDelivered:0,socketsIterated:0,totalMs:0}),de=(e,t,a,r)=>({maxMs:Math.max(e.maxMs,r),passes:e.passes+1,peakSocketsIterated:Math.max(e.peakSocketsIterated,t),socketsDelivered:e.socketsDelivered+a,socketsIterated:e.socketsIterated+t,totalMs:e.totalMs+r}),me=(e,t=z)=>{const a=new Map,r=new Map;for(const n of e){for(const s of Object.values(n.shapes??{})){const _=s.name??"(unknown shape)";a.set(_,(a.get(_)??0)+1)}for(const s of n.whispers??[])r.set(s,(r.get(s)??0)+1)}const o=[...[...a].map(([n,s])=>({kind:"shape",subscribers:s,topic:n})),...[...r].map(([n,s])=>({kind:"whisper",subscribers:s,topic:n}))];return o.sort((n,s)=>s.subscribers-n.subscribers||n.topic.localeCompare(s.topic)),{peakSubscribers:o[0]?.subscribers??0,topics:o.slice(0,t),totalConnections:e.length}};export{se as ADMIN_FUNCTIONS,te as ADMIN_FUNCTION_PREFIX,z as DEFAULT_FANOUT_TOPIC_LIMIT,re as FLAGS_FUNCTION_PREFIX,f as MAX_PAGE_SIZE,ae as RELATION_FUNCTION_PREFIX,ce as createFanoutCounters,X as datePrefixRange,ie as facetColumn,ue as findStorageReferences,oe as listTables,ne as readTablePage,de as recordFanoutPass,_e as selectMatchingIds,me as summarizeFanoutTopics,le as summarizeSubscriptions};
@@ -1 +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-1Yi1_Yq0.mjs";import{quoteIdentifier as T}from"./quoteIdentifier-CObIFRhb.mjs";import"./wire-codec-Dsy70M3Q.mjs";import"./runDrizzle-B6rnz3so.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
+ 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-Cg_QiQYA.mjs";import{quoteIdentifier as T}from"./quoteIdentifier-CObIFRhb.mjs";import"./wire-codec-Dsy70M3Q.mjs";import"./runDrizzle-CgYGDEeB.mjs";import"./sql-projection-jfoe331H.mjs";import{serializeSqlValue as x}from"./serializeSqlValue-BR4UOWoP.mjs";export{l as AGG_COUNT,m as AGG_KEY,n as AGG_VALUE,p as DOC_COLUMN,c as DOC_ORIGINALS_KEY,q as aggUpsertSql,d as createIndexSql,u as decodeDocJson,A as encodeDocJson,D as geoTableName,G as isFtsAvailable,S as jsonPath,_ as jsonPathSql,f as qualifiedJsonPath,C as qualifiedJsonPathSql,T as quoteIdentifier,O as rowToDocument,x as serializeSqlValue,h as tableColumns,I as tryRowToDocument};
@@ -1,4 +1,4 @@
1
- import{runSql as i}from"./runDrizzle-B6rnz3so.mjs";const a="__lunora_audit__",T=1e3,s=E=>{i(E,`CREATE TABLE IF NOT EXISTS "${a}" (
1
+ import{runSql as i}from"./runDrizzle-CgYGDEeB.mjs";const a="__lunora_audit__",T=1e3,s=E=>{i(E,`CREATE TABLE IF NOT EXISTS "${a}" (
2
2
  seq INTEGER PRIMARY KEY AUTOINCREMENT,
3
3
  ts REAL NOT NULL,
4
4
  op TEXT NOT NULL,
@@ -1,4 +1,4 @@
1
- import{sql as e}from"drizzle-orm";import{runDrizzle as a}from"./runDrizzle-B6rnz3so.mjs";import{L as C,g as l}from"./do-sql-1Yi1_Yq0.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)} (
1
+ import{sql as e}from"drizzle-orm";import{runDrizzle as a}from"./runDrizzle-CgYGDEeB.mjs";import{L as C,g as l}from"./do-sql-Cg_QiQYA.mjs";import{ConflictError as L}from"./ConflictError-C8GtJmjS.mjs";const d="__cdc_log",I=t=>{a(t,e`CREATE TABLE IF NOT EXISTS ${e.identifier(d)} (
2
2
  seq INTEGER PRIMARY KEY AUTOINCREMENT,
3
3
  ts REAL NOT NULL,
4
4
  ${e.identifier("table")} TEXT NOT NULL,
@@ -1,4 +1,4 @@
1
- import{sql as t}from"drizzle-orm";import{runDrizzle as n}from"./runDrizzle-B6rnz3so.mjs";const _="__client_watermark",l=i=>{n(i,t`CREATE TABLE IF NOT EXISTS ${t.identifier(_)} (
1
+ import{sql as t}from"drizzle-orm";import{runDrizzle as n}from"./runDrizzle-CgYGDEeB.mjs";const _="__client_watermark",l=i=>{n(i,t`CREATE TABLE IF NOT EXISTS ${t.identifier(_)} (
2
2
  identity TEXT NOT NULL,
3
3
  client_id TEXT NOT NULL,
4
4
  last_mutation_id INTEGER NOT NULL,
@@ -1,4 +1,4 @@
1
- import{LunoraError as y}from"@lunora/errors";import{runSql as n}from"./runDrizzle-B6rnz3so.mjs";const o="__lunora_migrations",D=100,$=3e4,U=1e4,b=r=>{n(r,`CREATE TABLE IF NOT EXISTS "${o}" (
1
+ import{LunoraError as y}from"@lunora/errors";import{runSql as n}from"./runDrizzle-CgYGDEeB.mjs";const o="__lunora_migrations",D=100,$=3e4,U=1e4,b=r=>{n(r,`CREATE TABLE IF NOT EXISTS "${o}" (
2
2
  id TEXT PRIMARY KEY,
3
3
  direction TEXT NOT NULL,
4
4
  status TEXT NOT NULL,
@@ -1,4 +1,4 @@
1
- import{sql as e}from"drizzle-orm";import{runDrizzle as r}from"./runDrizzle-B6rnz3so.mjs";const s="__global_shape_snapshot",d=n=>{r(n,e`CREATE TABLE IF NOT EXISTS ${e.identifier(s)} (
1
+ import{sql as e}from"drizzle-orm";import{runDrizzle as r}from"./runDrizzle-CgYGDEeB.mjs";const s="__global_shape_snapshot",d=n=>{r(n,e`CREATE TABLE IF NOT EXISTS ${e.identifier(s)} (
2
2
  connection_id TEXT NOT NULL,
3
3
  sub_id TEXT NOT NULL,
4
4
  members TEXT NOT NULL,
@@ -1,4 +1,4 @@
1
- import{sql as t}from"drizzle-orm";import{runDrizzle as r}from"./runDrizzle-B6rnz3so.mjs";const E="__idempotency",m=i=>{r(i,t`CREATE TABLE IF NOT EXISTS ${t.identifier(E)} (
1
+ import{sql as t}from"drizzle-orm";import{runDrizzle as r}from"./runDrizzle-CgYGDEeB.mjs";const E="__idempotency",m=i=>{r(i,t`CREATE TABLE IF NOT EXISTS ${t.identifier(E)} (
2
2
  identity TEXT NOT NULL,
3
3
  mutation_id TEXT NOT NULL,
4
4
  result_json TEXT NOT NULL,
@@ -1,4 +1,4 @@
1
- import{runSql as e,decodeJsonColumn as c,orNull as T}from"./runDrizzle-B6rnz3so.mjs";const r="__lunora_mail",l=500,_=256*1024,i=d=>d!==void 0&&d.length>_?`${d.slice(0,_)}
1
+ import{runSql as e,decodeJsonColumn as c,orNull as T}from"./runDrizzle-CgYGDEeB.mjs";const r="__lunora_mail",l=500,_=256*1024,i=d=>d!==void 0&&d.length>_?`${d.slice(0,_)}
2
2
  … [truncated by the dev mail catcher]`:d,E=d=>d===void 0?null:JSON.stringify(d),s=d=>{e(d,`CREATE TABLE IF NOT EXISTS "${r}" (
3
3
  id TEXT PRIMARY KEY,
4
4
  captured_at INTEGER NOT NULL,
@@ -0,0 +1 @@
1
+ import{LunoraError as b}from"@lunora/errors";import{n as Ft,S as Ot,x as Qe,T as _e,y as Bt,c as qt}from"./ctx-db-companions-D2ZMFBrP.mjs";import{sql as n}from"drizzle-orm";import{s as Ut}from"./wire-codec-Dsy70M3Q.mjs";import{aggregateSqlFunction as Te,normalizeCountArgument as Ht,throwingScheduler as Pt}from"./AGGREGATE_SQL_FUNCTION-CTo0-9iZ.mjs";import{encodeAggregateKey as ke,readAggregateValue as Le,aggregateTableName as De}from"./aggregateTableName-DgYMC5tr.mjs";import{mergeWhere as Y,CountRlsUnsupportedError as We,selectIndexForGroupBy as jt,selectIndexForCount as Qt,selectIndexForAggregate as Kt}from"./CountRlsUnsupportedError-8BqPYQoP.mjs";import{backfillSearchIndexesForTable as Gt}from"./backfillAggregateIndexes-Czk8MQ3M.mjs";import{backfillAggregateIndexes as Dr,backfillRankIndexes as Wr,backfillSearchIndexes as Fr}from"./backfillAggregateIndexes-Czk8MQ3M.mjs";import{appendCdcChange as Yt}from"./CDC_LOG_TABLE-CIfexI1y.mjs";import{CDC_LOG_TABLE as Br,applyCdcChanges as qr,bumpCdcEpoch as Ur,minCdcSeq as Hr,readCdcChanges as Pr,readCdcCursor as jr,readCdcEpoch as Qr,trimCdcChanges as Kr}from"./CDC_LOG_TABLE-CIfexI1y.mjs";import{computeRankPage as ot}from"./computeRankPage-CPVNOrM5.mjs";import{SCAN_DEP as H}from"./SCAN_DEP-D_yR9EeV.mjs";import{runDrizzle as B}from"./runDrizzle-CgYGDEeB.mjs";import{a as j,L as ae,p as Re,T as Fe,c as Ae,N as J,E as le,I as St,C as zt,D as _t,h as Jt,O as it}from"./do-sql-Cg_QiQYA.mjs";import{WORKERD_SQLITE_LIMITS as Tt,unionAll as Ue,sqliteInList as Vt}from"./param-C68MV3DD.mjs";import{coveringGeohashes as Xt,boundingBoxGeohashes as Zt,pointInBoundingBox as en,haversineMeters as tn}from"./GEO_DEFAULT_PRECISION-DyI5zggj.mjs";import{NotFoundError as nn}from"./NotFoundError-BhF7FeFr.mjs";import{normalizeOrderKeys as rn,buildSeekWhere as Rt,decodeCursor as He,applySelect as at,encodeCursor as Pe,softDeleteScope as de,buildSeekBeforeWhere as on}from"./applySelect-UY-o13Ia.mjs";import{sortColumnName as st,resolveRankPartition as an,encodePartitionKey as sn,RANK_TIEBREAK as dn,rankTableName as dt}from"./RANK_TIEBREAK-DDtST3gN.mjs";import{indexKeysForRow as ln,buildIndexRange as cn}from"./buildIndexRange-DFsdtPjD.mjs";import{assertFlatPredicate as Oe,resolveRelationPredicates as lt}from"./DEFAULT_MAX_RELATION_KEYS-DjKka36Z.mjs";import{runRowValidators as Be,resolveWith as ct,relationHooks as ut,applyOnDelete as un,fanOutScalarCounts as fn}from"./applyOnDelete-By23GK-k.mjs";import{guardWriter as hn}from"./RLS_UNWRAP_SYMBOL-DcqORh2s.mjs";import{f as pn}from"./sql-projection-jfoe331H.mjs";import{createSystemReader as mn}from"./createSystemReader-DcDcrtM3.mjs";import{ConflictError as pe}from"./ConflictError-C8GtJmjS.mjs";import{runTriggers as $n}from"./hasTrigger-CbkOHExZ.mjs";import{compileWhereSql as ne}from"./compileWhereSql-DxD5mzDy.mjs";import{CLIENT_WATERMARK_TABLE as Yr,advanceClientWatermark as zr,migrateClientWatermark as Jr,readClientWatermark as Vr}from"./CLIENT_WATERMARK_TABLE-BogWgD2Q.mjs";import{GLOBAL_SHAPE_SNAPSHOT_TABLE as Zr,deleteGlobalShapeSnapshot as eo,deleteGlobalShapeSnapshotsForConnection as to,migrateGlobalShapeSnapshot as no,readGlobalShapeSnapshot as ro,writeGlobalShapeSnapshot as oo}from"./GLOBAL_SHAPE_SNAPSHOT_TABLE-T5smo6RP.mjs";import{IDEMPOTENCY_TABLE as ao,readIdempotent as so,trimIdempotent as lo,writeIdempotent as co}from"./IDEMPOTENCY_TABLE-DPFwgQbE.mjs";import{runShardMigrations as fo}from"./runShardMigrations-CtlcSZ3r.mjs";import{SEARCH_STATE_TABLE as po}from"./SEARCH_STATE_TABLE-MDlr30EJ.mjs";import{selectShapeMemberIds as $o,selectShapeRows as wo}from"./selectShapeMemberIds-EPo0xxs_.mjs";import{serializeSqlValue as ie}from"./serializeSqlValue-BR4UOWoP.mjs";import{quoteIdentifier as wn}from"./quoteIdentifier-CObIFRhb.mjs";const gn=o=>{const i=new TextEncoder().encode(o);let t="";for(const d of i)t+=String.fromCodePoint(d);return btoa(t)},bn=o=>{const i=atob(o),t=Uint8Array.from(i,d=>d.codePointAt(0)??0);return new TextDecoder().decode(t)},En=()=>new b("BAD_REQUEST","invalid cursor"),ft=16,ht=8,V=1024,Ke=(o,i)=>i.query(o),yn=(o,i,t)=>{const d=Ft(o,t);if(d.length===0)return 0;let c=0;for(const[p,$]of i.entries()){const R=p===i.length-1;let y=0;for(const g of d)(R?g.startsWith($):g===$)&&(y+=1);if(y===0)return 0;c+=y}return c},Nn=(o,i)=>{if(!i)return{exact:!0,lower:o,upper:o};const t=[...o].at(-1)??"",d=(t.codePointAt(0)??0)+1;if(d>=55296&&d<=57343||d>1114111)return{exact:!0,lower:o,upper:o};const c=o.slice(0,o.length-t.length);return{exact:!1,lower:o,upper:c+String.fromCodePoint(d)}},Sn=(o,i,t)=>{const d={eq:(c,p)=>{if(!o.definition.filterFields?.includes(c))throw new b("INTERNAL",`field "${c}" is not a filter field of search index "${o.indexName}" on table "${i}"`);if(o.filters.length>=ht)throw new b("BAD_REQUEST",`search index "${o.indexName}" on table "${i}": at most ${String(ht)} .eq() filters are supported per search query`);return o.filters.push({field:c,value:p}),d},search:(c,p)=>{const $=o;if(c!==$.definition.field)throw new b("INTERNAL",`search index "${$.indexName}" on table "${i}" indexes "${$.definition.field}", not "${c}"`);const R=Ke(p,t).length;if(R>ft)throw new b("BAD_REQUEST",`search index "${$.indexName}" on table "${i}": at most ${String(ft)} search terms are supported (got ${String(R)})`);return $.field=c,$.query=p,$.hasQuery=!0,d}};return d},_n=o=>{if(o.length>V)throw new b("BAD_REQUEST",`more than ${String(V)} documents match this search — narrow it with filters or read it a page at a time with .paginate()`)},Tn=o=>Math.min(o.offset+o.numItems+1,V),Rn=o=>gn(`search:${String(o)}`),An=o=>{let i;try{i=bn(o)}catch{return}if(!i.startsWith("search:"))return;const t=Number(i.slice(7));return Number.isInteger(t)&&t>=0?t:void 0},xn=o=>{if(typeof o.endCursor=="string")throw new b("BAD_REQUEST","bounded (endCursor) pagination is not supported on search queries — relevance order has no stable range boundary");const i=Math.max(0,Math.floor(o.numItems)),t=o.cursor?An(o.cursor):0;if(t===void 0)throw En();if(t+i>V)throw new b("BAD_REQUEST",`search pagination reaches past the ${String(V)}-document limit (offset ${String(t)} + ${String(i)} requested) — narrow the query or the filters instead`);return{numItems:i,offset:t}},In=(o,i)=>{const t=i.offset+i.numItems,d=i.numItems>0&&o.length>t;return{continueCursor:d?Rn(t):null,isDone:!d,page:o.slice(i.offset,t)}},vn=o=>{if(o===void 0)return V+1;if(!Number.isFinite(o))return V;const i=Math.max(0,Math.floor(o));if(i>V)throw new b("BAD_REQUEST",`search returns at most ${String(V)} documents (asked for ${String(i)}) — narrow the query or paginate instead`);return i},Cn=/^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/iu,Mn=o=>{if(!Cn.test(o))throw new b("INTERNAL",`invalid clientId ${JSON.stringify(o)}: a client-supplied row id must be a UUID`)},pt=50,At=500,mt=Math.floor(Tt.boundParams/3),he=Tt.boundParams,kn=128,se=(o,i,t)=>{const d=i??At;if(o>d)throw new b("BATCH_LIMIT_EXCEEDED",`${t}: batch of ${String(o)} exceeds the limit of ${String(d)} (raise options.limit or chunk the call)`,{status:400})},Ln=o=>{const i={eq:(t,d)=>(o.sqlConditions.push({comparator:"=",field:t,value:d}),i),gt:(t,d)=>(o.sqlConditions.push({comparator:">",field:t,value:d}),i),gte:(t,d)=>(o.sqlConditions.push({comparator:">=",field:t,value:d}),i),lt:(t,d)=>(o.sqlConditions.push({comparator:"<",field:t,value:d}),i),lte:(t,d)=>(o.sqlConditions.push({comparator:"<=",field:t,value:d}),i)};return i},Dn=o=>Math.max(o,V),xt=(o,i)=>{const t=o.filters.map(d=>n`${J(d.field)} = ${ie(d.value)}`);return i&&t.push(i),t},Wn=(o,i,t,d,c)=>{const p=Ke(t.query,Qe(t.definition.language));if(p.length===0)return[];const $=qt(i,t.indexName),R=`${$}__vocab`,y=p.length-1,g=p.map((D,k)=>{const Q=Nn(D,k===y),F=Q.exact?n`${n.identifier("term")} = ${Q.lower}`:n`${n.identifier("term")} >= ${Q.lower} AND ${n.identifier("term")} < ${Q.upper}`;return n`SELECT ${n.identifier("doc")}, ${n.raw(String(k))} AS ${n.identifier("__term__")}, COUNT(*) AS ${n.identifier("__n__")} FROM ${n.identifier(R)} WHERE ${F} GROUP BY ${n.identifier("doc")}`}),N=p.map((D,k)=>n`SUM(CASE WHEN u.${n.identifier("__term__")} = ${n.raw(String(k))} THEN u.${n.identifier("__n__")} ELSE 0 END)`),S=n`SELECT f.${n.identifier(_e)} AS ${n.identifier(_e)}, ${n.join(N,n` + `)} AS ${n.identifier("__score__")} FROM (${Ue(g)}) u JOIN ${n.identifier($)} f ON f.rowid = u.${n.identifier("doc")} GROUP BY f.${n.identifier(_e)} HAVING ${n.join(N.map(D=>n`${D} > 0`),n` AND `)}`,_=xt(t,c);let C=n`SELECT m.id, m._creationTime, m.${n.identifier(j)}, s.${n.identifier("__score__")} AS ${n.identifier("__score__")} FROM (${S}) s JOIN ${n.identifier(i)} m ON m.id = s.${n.identifier(_e)}`;_.length>0&&(C=n`${C} WHERE ${n.join(_,n` AND `)}`),C=n`${C} ORDER BY s.${n.identifier("__score__")} DESC, m._creationTime DESC, m.id ASC LIMIT ${n.raw(String(d))}`;const W=[];for(const D of B(o,C)){const k=_t(D);if(k){const Q=D.__score__;W.push({document:k,score:typeof Q=="number"?Q:Number(Q??0)})}}return W},Fn=(o,i,t,d,c)=>{const p=Qe(t.definition.language),$=Ke(t.query,p);if($.length===0)return[];const R=xt(t,c);let y=n`SELECT id, _creationTime, ${n.identifier(j)} FROM ${n.identifier(i)}`;R.length>0&&(y=n`${y} WHERE ${n.join(R,n` AND `)}`),y=n`${y} ORDER BY _creationTime DESC, id ASC LIMIT ${n.raw(String(Dn(d)))}`;const g=B(o,y).toArray(),N=[];for(const S of g){const _=_t(S);if(!_)continue;const C=yn(Bt(_,t.definition),$,p);C>0&&N.push({creationTime:typeof _._creationTime=="number"?_._creationTime:0,doc:_,id:typeof _._id=="string"?_._id:"",score:C})}return N.sort((S,_)=>_.score-S.score||_.creationTime-S.creationTime||S.id.localeCompare(_.id)),N.slice(0,d).map(S=>({document:S.doc,score:S.score}))},qe=(o,i,t,d)=>{if(!Number.isFinite(o.lat)||o.lat<-90||o.lat>90||!Number.isFinite(o.lng)||o.lng<-180||o.lng>180)throw new b("BAD_REQUEST",`geo index "${d}" on table "${t}": ${i} must have a finite lat in [-90, 90] and lng in [-180, 180]`)},On=(o,i)=>{const t=o,d={near:(c,p)=>{if(t.within)throw new b("INTERNAL",`geo index "${t.indexName}" on table "${i}": call .near() or .within(), not both`);if(qe(c,".near() point",i,t.indexName),!Number.isFinite(p)||p<=0)throw new b("BAD_REQUEST",`geo index "${t.indexName}" on table "${i}": .near() radiusMeters must be a finite number > 0, got ${String(p)}`);return t.near={point:{lat:c.lat,lng:c.lng},radiusMeters:p},d},within:c=>{if(t.near)throw new b("INTERNAL",`geo index "${t.indexName}" on table "${i}": call .near() or .within(), not both`);if(qe(c.sw,".within() sw corner",i,t.indexName),qe(c.ne,".within() ne corner",i,t.indexName),c.sw.lat>c.ne.lat)throw new b("BAD_REQUEST",`geo index "${t.indexName}" on table "${i}": .within() corners are transposed (sw.lat > ne.lat)`);if(c.sw.lng>c.ne.lng)throw new b("BAD_REQUEST",`geo index "${t.indexName}" on table "${i}": .within() box crosses the antimeridian (sw.lng > ne.lng), which is not supported — split it into two boxes at ±180 and union the results`);return t.within={ne:{lat:c.ne.lat,lng:c.ne.lng},sw:{lat:c.sw.lat,lng:c.sw.lng}},d}};return d},Bn=(o,i)=>{const t=o[i];if(t===null||typeof t!="object")return;const{lat:d,lng:c}=t;return typeof d=="number"&&typeof c=="number"?{lat:d,lng:c}:void 0},qn=(o,i)=>{const t=Bn(o,i.definition.field);if(!t)return;const d=typeof o._creationTime=="number"?o._creationTime:0;if(i.near){const c=tn(i.near.point,t);return c<=i.near.radiusMeters?{creationTime:d,distance:c}:void 0}return en(t,i.within)?{creationTime:d,distance:0}:void 0},Un=(o,i,t,d)=>{if(!t.near&&!t.within)throw new b("INTERNAL",`geo index "${t.indexName}" on table "${i}": call .near(point, radius) or .within(box)`);const c=t.near?Xt(t.near.point,t.near.radiusMeters):Zt(t.within),p=Jt(i,t.indexName),$=c.map(S=>n`(g.${n.identifier("__geohash__")} >= ${S} AND g.${n.identifier("__geohash__")} < ${`${S}{`})`),R=[n`(${n.join($,n` OR `)})`];d&&R.push(d);const y=n`SELECT m.id, m._creationTime, m.${n.identifier(j)} FROM ${n.identifier(p)} g JOIN ${n.identifier(i)} m ON m.id = g.${n.identifier("__id__")} WHERE ${n.join(R,n` AND `)}`,g=B(o,y).toArray(),N=[];for(const S of g){const _=le(S),C=_?qn(_,t):void 0;_&&C&&N.push({creationTime:C.creationTime,distance:C.distance,doc:_})}return N.sort((S,_)=>S.distance-_.distance||_.creationTime-S.creationTime),N},It=(o,i,t,d)=>{const c=[];for(const p of o)if(i.every($=>$(d(p)))&&(c.push(p),typeof t=="number"&&c.length>=t))break;return c},Hn=(o,i,t,d,c,p=()=>{})=>{const $=t.within!==void 0,R=Un(o,i,t,c).map(y=>({distanceMeters:$?null:y.distance,document:y.doc}));return p(R.length),typeof d=="number"?R.slice(0,Math.max(0,Math.floor(d))):R},vt=(o,i,t,d,c,p=()=>{})=>{const{geo:$}=t;if(!$)throw new b("INTERNAL","runGeoTerminalScored called without a staged geo query");const R=t.inMemoryFilters.length>0,y=Hn(o,i,$,R?void 0:c,d,p);return R?It(y,t.inMemoryFilters,c,g=>g.document):y},Pn=(o,i,t,d,c,p=()=>{})=>vt(o,i,t,d,c,p).map($=>$.document),jn=(o,i,t,d,c,p,$=()=>{})=>{const R=[];for(const S of t.sqlConditions)R.push(n`${J(S.field)} ${n.raw(S.comparator)} ${ie(S.value)}`);d&&R.push(d);let y=n`SELECT id, _creationTime, ${n.identifier(j)} FROM ${n.identifier(i)}`;R.length>0&&(y=n`${y} WHERE ${n.join(R,n` AND `)}`),y=n`${y} ORDER BY ${c}`,typeof p=="number"&&t.inMemoryFilters.length===0&&(y=n`${y} LIMIT ${n.raw(String(Math.max(0,Math.floor(p))))}`);const g=B(o,y).toArray();$(g.length);const N=[];for(const S of g){const _=le(S);if(_&&t.inMemoryFilters.every(C=>C(_))&&(N.push(_),typeof p=="number"&&N.length>=p))break}return N},oe={fieldRef:J,serialize:ie},Ct=(o,i)=>{const t=i===void 0?void 0:o.shape[i];return t!==void 0&&pn(t)},$t=(o,i)=>i.some(t=>Ct(o,t)),wt=(o,i,t)=>{if(Ct(o,i))throw new b("BAD_REQUEST",`${t}: "${i}" is stored as an order-preserving key, which SQL cannot reduce or group — declare an aggregateIndex covering this (by, field, op) so the maintained companion answers it`)},Qn=o=>{let i=0;const t=[],d={fieldRef:J,relationExists:c=>{const{childWhere:p,negated:$,parentTable:R,relation:y}=c,g=`__rel_${String(i)}`,N=t.at(-1)??R;i+=1,o(y.table,H);const S=y.kind==="one"?y.field:y.references,_=y.kind==="one"?y.references:y.field,C=n`${it(g,_)} = ${it(N,S)}`;t.push(g);const W=ne(p,d);t.pop();const D=W?n`${C} AND ${W}`:C,k=n`EXISTS (SELECT 1 FROM ${n.identifier(y.table)} AS ${n.identifier(g)} WHERE ${D})`;return $?n`NOT ${k}`:k},serialize:ie};return d},Mt=o=>{const i=o.map(t=>n`${J(t.field)} ${n.raw(t.direction==="desc"?"DESC":"ASC")}`);return o.some(t=>t.field==="_id"||t.field==="id")||i.push(n`${J("id")} ASC`),n.join(i,n`, `)},Kn={"<":"lt","<=":"lte","=":"eq",">":"gt",">=":"gte"},Gn=o=>{const i=o.order;return o.indexFields.length>0?o.indexFields.map(t=>({direction:i,field:t})):[{direction:i,field:"_creationTime"}]},Yn=(o,i,t,d)=>{const c=o.sqlConditions.map(p=>({[p.field]:{[Kn[p.comparator]??"eq"]:p.value}}));if(t&&c.push(Rt(i,He(t))),d&&c.push(on(i,He(d))),c.length!==0)return c.length===1?c[0]:{AND:c}},zn=(o,i,t)=>{const d=[];for(const c of o){const p=le(c);if(p&&i.every($=>$(p))&&(d.push(p),t!==void 0&&d.length>t))break}return d},Jn=(o,i,t,d,c,p=()=>{})=>{const $=Math.max(0,Math.floor(d.numItems)),R=Gn(t),y=typeof d.endCursor=="string",g=ne(Yn(t,R,d.cursor,d.endCursor),oe),N=c&&g?n`${g} AND ${c}`:c??g;let S=n`SELECT id, _creationTime, ${n.identifier(j)} FROM ${n.identifier(i)}`;N&&(S=n`${S} WHERE ${N}`),S=n`${S} ORDER BY ${Mt(R)}`;const _=t.inMemoryFilters.length>0;!_&&!y&&(S=n`${S} LIMIT ${n.raw(String($+1))}`);const C=B(o,S).toArray();p(C.length);const W=zn(C,t.inMemoryFilters,_||y?void 0:$);if(y){const F=W.length>=2?W[Math.floor(W.length/2)-1]:void 0;return{continueCursor:d.endCursor??null,isDone:!0,page:W,splitCursor:F?Pe(F,R):null}}const D=W.length>$,k=D?W.slice(0,$):W,Q=k.at(-1);return{continueCursor:D&&Q?Pe(Q,R):null,isDone:!D,page:k}};class Vn extends b{constructor(i="unique() found more than one matching document"){super("NOT_UNIQUE",i,{name:"NotUniqueError"})}}const Xn=/\s/u,Zn=String.fromCodePoint(0),gt=(o,i,t)=>{if(!o.tables[i])throw new b("INTERNAL",`unknown table: ${i}`);return typeof t!="string"||t.length===0||Xn.test(t)||t.includes(Zn)?null:t},er=(o,i,t,d=()=>{},c=()=>{},p=()=>{})=>{const $=i.tables[t];if(!$)throw new b("INTERNAL",`unknown table: ${t}`);const R=de($.softDeleteMode,void 0),y=R?ne(R,oe):void 0,g={indexFields:[],indexName:void 0,inMemoryFilters:[],order:"asc",sqlConditions:[]};let N=0;const S=E=>{const{search:v}=g;if(!v)throw new b("INTERNAL","runSearchFetch called without a staged search");Gt(o,t,$);const I=g.inMemoryFilters.length>0,M=vn(I?void 0:E),K=zt(o)?Wn(o,t,v,M,y):Fn(o,t,v,M,y);return I?(N=K.length,It(K,g.inMemoryFilters,E,ee=>ee.document)):(E===void 0&&_n(K),K)},_=E=>S(E).map(v=>v.document),C=E=>{const v=xn(E);return In(_(Tn(v)),v)},W=()=>{const E=g.indexFields.length>0?g.indexFields:["_creationTime"],v=g.order==="desc"?"DESC":"ASC";return n.join(E.map(I=>n`${J(I)} ${n.raw(v)}`),n`, `)},D=()=>{if(g.search||g.geo||g.indexName===void 0){c(void 0);return}c(cn(t,g.indexName,g.indexFields,g.sqlConditions,ie))},k=E=>{D();let v=0;const I=(()=>{if(g.search){const M=_(E);return v=N,M}return g.geo?Pn(o,t,g,y,E,M=>{v=M}):jn(o,t,g,y,W(),E,M=>{v=M})})();return p(Math.max(v,I.length)),I},Q=()=>{if(!g.search&&!g.geo)throw new b("INTERNAL",`ctx.db.query("${t}").collectWithScores() requires a staged .withSearchIndex(...) or .withGeoIndex(...)`);D();let E=0;const v=(()=>{if(g.search){const I=S(void 0);return E=N,I}return vt(o,t,g,y,void 0,I=>{E=I})})();return p(Math.max(E,v.length)),v},F={async*[Symbol.asyncIterator](){const E=[...g.inMemoryFilters];let v;g.inMemoryFilters=[];try{for(;;){const I=await F.paginate({cursor:v??null,numItems:kn});for(const M of I.page)E.every(K=>K(M))&&(yield M);if(I.isDone||I.continueCursor===null)return;v=I.continueCursor}}finally{g.inMemoryFilters=E}},async collect(){return k(void 0)},async collectWithScores(){return Q()},filter(E){return g.inMemoryFilters.push(E),F},async first(){return k(g.inMemoryFilters.length>0?void 0:1)[0]??null},order(E){return g.order=E==="desc"?"desc":"asc",F},async paginate(E){let v=0;if(D(),g.search){const M=C(E);return p(M.page.length),M}if(g.geo)throw new b("INTERNAL","pagination is not supported on geo queries; use .take(n) or .collect()");const I=Jn(o,t,g,E,y,M=>{v=M});return p(Math.max(v,I.page.length)),I},async take(E){return k(E)},async unique(){const E=k(g.inMemoryFilters.length>0?void 0:2);if(E.length>1)throw new Vn(`unique() on table "${t}" matched ${String(E.length)} documents; expected at most one`);return E[0]??null},withGeoIndex(E,v){const I=($.geoIndexes??[]).find(K=>K.name===E);if(!I)throw new b("INTERNAL",`unknown geo index "${E}" on table "${t}"`);d(t,E,"geo");const M={definition:I,indexName:E};if(g.geo=M,v(On(M,t)),!M.near&&!M.within)throw new b("INTERNAL",`geo index "${E}" on table "${t}" requires a .near(point, radius) or .within(box) call`);return F},withIndex(E,v){const I=$.indexes.find(M=>M.name===E);if(!I)throw new b("INTERNAL",`unknown index "${E}" on table "${t}"`);return d(t,E,"index"),g.indexName=E,g.indexFields=I.fields,v&&v(Ln(g)),F},withSearchIndex(E,v){const I=($.searchIndexes??[]).find(K=>K.name===E);if(!I)throw new b("INTERNAL",`unknown search index "${E}" on table "${t}"`);d(t,E,"search");const M={definition:I,field:I.field,filters:[],hasQuery:!1,indexName:E,query:""};if(g.search=M,v(Sn(M,t,Qe(I.language))),!M.hasQuery)throw new b("INTERNAL",`search index "${E}" on table "${t}" requires a .search(field, query) call`);return F}};return F},bt=(o,i,t)=>{const d={...i};for(const[c,p]of St(o)){if(p.serverDefault){d[c]=p.serverDefault({auth:t});continue}d[c]===void 0&&(p.defaultFn?d[c]=p.defaultFn():"defaultValue"in p&&(d[c]=p.defaultValue))}return d},Et=(o,i,t,d)=>{const c=t;for(const[p,$]of St(o)){if($.serverDefault){p in i&&(c[p]=$.serverDefault({auth:d}));continue}$.onUpdateFn&&!(p in i)&&(c[p]=$.onUpdateFn())}},yt=(o,i)=>{for(const t of Object.keys(i))if(i[t]===void 0)throw new b("INTERNAL",`Cannot ${o} field '${t}' to undefined — use null to clear a nullable field, or omit the key to leave it unchanged.`)},tr=/unique constraint failed/i,nr=o=>o instanceof Error&&tr.test(o.message),je=(o,i,t)=>{try{B(o,t)}catch(d){throw nr(d)?new pe(`unique constraint violation on "${i}"`,"unique"):d}},xe=(o,i,t)=>{if(je(o,i,t),B(o,n`SELECT changes() AS changed`).one().changed===0)throw new pe(`optimistic concurrency conflict on "${i}" — the row changed during this mutation; refetch and retry`,"occ")},Nt=(o,i,t,d,c,p,$)=>{const R=[];for(let S=0;S<t.length+1;S+=1){const _=[];for(let k=0;k<S;k+=1)_.push(n`${n.identifier(t[k])} IS ${p[k]}`);const C=t[S],W=d[S];if(C!==void 0&&W!==void 0){const k=W.direction==="desc"?">":"<";_.push(n`${n.identifier(C)} ${n.raw(k)} ${p[S]}`)}else _.push(n`${n.identifier(dn)} < ${$}`);const[D]=_;R.push(_.length===1&&D!==void 0?D:n`(${n.join(_,n` AND `)})`)}const y=n.join(R,n` OR `),g=B(o,n`SELECT COUNT(*) AS c FROM ${n.identifier(i)} WHERE ${n.identifier("__partition__")} = ${c} AND (${y})`).one(),N=B(o,n`SELECT COUNT(*) AS c FROM ${n.identifier(i)} WHERE ${n.identifier("__partition__")} = ${c}`).one();return{before:g.c,total:N.c}},Mr=o=>{const{sql:i}=o,{schema:t}=o,d=o.broadcast??(()=>{}),c=(e,...r)=>{const a=t.tables[e]?.indexes;if(!a||a.length===0)return;const l=[];for(const h of r)h&&l.push(...ln(a,h,ie));return l.length>0?l:void 0},{headroom:p}=o;let $=!1;const R=async e=>{const r=$;$=!0;try{return await e()}finally{$=r}},y=o.onRead??(()=>{}),g=o.onReadRange??(e=>{y(e.table,H)}),N=(e,r)=>{r!==void 0&&r!==H&&!$&&p?.recordRead(1),y(e,r)},S=o.onIndexUse??(()=>{}),_=o.onWrite??(()=>{}),C=async e=>{$||p?.recordWrite(e.doc),await _(e)},{cache:W}=o,D=o.clock??(()=>Date.now()),k=o.idGenerator??(()=>crypto.randomUUID()),Q=o.scheduler??Pt,{globalDb:F}=o,E=o.auth??{identity:null,userId:null},v=o.cdc??!1,I=Q,M=mn({scheduler:typeof I.list=="function"&&typeof I.get=="function"?I:void 0,storage:o.storage}),K=(e,r,a,l)=>{v&&Yt(i,D(),e,r,a,l)},ee=e=>t.tables[e]?.shardMode?.kind==="global",Ge=(e,r)=>{if(ee(e)){if(!F)throw new b("INTERNAL",`cross-backend ${r} for global table '${e}' requires a globalDb writer — pass one to createShardCtxDb({ globalDb })`);return F}return q},Ie=e=>Ge(e,"cascade"),z=(e,r)=>{if(ee(e)){if(!F)throw new b("INTERNAL",`${r} on global table '${e}' requires a globalDb writer — pass one to createShardCtxDb({ globalDb })`);return F}},ve=(e,r)=>Ge(e,"relation load").findMany(e,r),Ye=(e,r)=>(ee(e)&&N(e,H),ve(e,r)),kt=e=>!ee(e.table),ze=o.relationExistsPushDown??"auto",Je=ze!=="never",{maxRelationKeys:Ve}=o,me=(e,r,a)=>lt(e,{fetcher:Ye,maxRelationKeys:Ve,relationBaseWhere:a,schema:t,tableName:r}),Xe=async(e,r,a,l)=>{const h=z(e,"relation grouped count");if(h)return N(e,H),fn((P,x)=>h.count(P,x),e,r,a,l);const u=t.tables[e];if(!u)throw new b("INTERNAL",`unknown table: ${e}`);N(e,H);const s=de(u.softDeleteMode,void 0),f={[r]:{in:a}},m=Y(Y(f,l),s),T=await me(m,e,void 0),w=ne(T,oe),A=J(r);let L=n`SELECT ${A} AS __fk__, COUNT(*) AS count FROM ${n.identifier(e)}`;w&&(L=n`${L} WHERE ${w}`),L=n`${L} GROUP BY ${A}`;const O=B(i,L).toArray();return new Map(O.map(P=>[P.__fk__,P.count]))};let $e=0;const Ze=new Set;for(const[e,r]of Object.entries(t.tables))for(const a of Object.values(r.triggerMap??{}))Ze.add(`${e} ${a.timing} ${a.op}`);const X=(e,r,a)=>Ze.has(`${e} ${r} ${a}`),Z=async(e,r,a)=>{if($e+=1,$e>pt)throw $e-=1,new pe(`trigger recursion exceeded ${String(pt)} levels on "${a.table}" — check for a self-triggering write`,"trigger");try{await $n({ctx:Dt,event:a,op:r,schema:t,tableName:a.table,timing:e})}finally{$e-=1}},{ensureBackfilledForTable:ce,ensureBackfilledIndex:Ce,ensureRankBackfilled:Me,ensureRankBackfilledForTable:ue,syncAggregates:we,syncCompanionsForInsert:et,syncGeo:ge,syncRanks:fe,syncSearch:be}=Ot({broadcast:d,indexKeysFor:(e,r)=>c(e,r),invalidateCache:(e,r,a)=>W?.invalidate(e,r,c(e,a)),recordCdc:K,schema:t,sql:i}),tt=(e,r,a)=>{const{shardMode:l}=r;if(l?.kind==="shardBy"&&!(l.field!==void 0&&(a.partitionBy??[]).includes(l.field)))throw Object.assign(new Error(`rank index "${a.name}" on "${e}" partitions across shards (shard key "${l.field??"?"}" is not in partitionBy) — a shard-local rank()/rankPage() would be wrong; roll it up through the Query Coordinator instead`),{code:"CROSS_SHARD_RANK_UNSUPPORTED",name:"LunoraError",status:400})},nt=e=>Object.entries(t.tables).filter(([,r])=>r.shardMode?.kind!=="global").map(([r])=>r).filter(r=>e===void 0||r===e),re=(e,r)=>{const a=nt(r);for(let l=0;l<a.length;l+=he){const h=a.slice(l,l+he).map(T=>n`SELECT ${n.raw(`'${T.replaceAll("'","''")}'`)} AS __t__, id, _creationTime, ${n.identifier(j)} FROM ${n.identifier(T)} WHERE id = ${e}`),[u]=B(i,n`${Ue(h)} LIMIT 1`).toArray();if(!u)continue;const s=u.__t__,f=le(u);if(typeof s!="string"||!f)return;const m=u[j];return{docJson:typeof m=="string"?m:ae(m??{}),row:f,tableName:s}}},Lt=(e,r)=>{const a=[...new Set(e)],l=new Map;if(a.length===0)return l;const h=nt(r);for(let u=0;u<h.length;u+=he){const s=h.slice(u,u+he),f=Math.floor(he/s.length),m=Vt(n`${n.identifier("id")}`,a,!1,f),T=s.map(w=>n`SELECT ${n.raw(`'${w.replaceAll("'","''")}'`)} AS __t__, id FROM ${n.identifier(w)} WHERE ${m}`);for(const w of B(i,Ue(T))){const{id:A,__t__:L}=w;typeof L=="string"&&typeof A=="string"&&l.set(A,L)}}return l},rt={assertRankPartitionLocal:tt,ensureRankBackfilled:Me,onRead:N,rowToDocument:le,schema:t,sql:i},q={system:M,async aggregate(e,r){const a=z(e,"aggregate");if(a)return N(e,H),a.aggregate(e,r);const l=t.tables[e];if(!l)throw new b("INTERNAL",`unknown table: ${e}`);if(Te(r.op),r.op==="count")return q.count(e,{baseWhere:r.baseWhere,relationBaseWhere:r.relationBaseWhere,restrictsCounts:r.restrictsCounts,where:r.where});if(!r.field)throw new b("INTERNAL",`aggregate(${e}, { op: "${r.op}" }): "field" is required for non-count reducers`);N(e,H);const h=de(l.softDeleteMode,void 0),u=Y(Y(r.baseWhere,r.where),h),s=await me(u,e,r.relationBaseWhere),f=s!==u;if(l.aggregateIndexes&&!r.baseWhere&&!f&&(!h||$t(l,[r.field]))){const O=Kt(l.aggregateIndexes,r.op,r.field,r.where);if(O){Ce(e,O.index);const P=ke(O.index.by??[],O.key),x=De(e,O.index.name),G=B(i,n`SELECT ${Re} AS value, ${Fe} AS count FROM ${n.identifier(x)} WHERE ${Ae} = ${P}`).toArray()[0];return Le(r.op,G)}}wt(l,r.field,`aggregate(${e}, { op: "${r.op}", field: "${r.field}" })`);const m=ne(s,oe),T=Te(r.op),w=J(r.field);let A=n`SELECT ${n.raw(T)}(${w}) AS value FROM ${n.identifier(e)}`;return m&&(A=n`${A} WHERE ${m}`),B(i,A).toArray()[0]?.value??null},asId(e,r){const a=gt(t,e,r);if(a===null)throw new b("BAD_REQUEST",`asId("${e}", …): "${r}" is not a valid id for table "${e}"`,{status:400});return a},async count(e,r){const a=z(e,"count");if(a)return N(e,H),a.count(e,r);const l=t.tables[e];if(!l)throw new b("INTERNAL",`unknown table: ${e}`);const h=Ht(r);if(h.restrictsCounts)throw new We(e);N(e,H);const u=de(l.softDeleteMode,void 0),s=Y(Y(h.baseWhere,h.where),u),f=await me(s,e,h.relationBaseWhere),m=f!==s;if(l.aggregateIndexes&&!h.baseWhere&&!m&&!u){const A=Qt(l.aggregateIndexes,h.where);if(A){Ce(e,A.index);const L=ke(A.index.by??[],A.key),O=De(e,A.index.name),P=B(i,n`SELECT ${Re} AS value FROM ${n.identifier(O)} WHERE ${Ae} = ${L}`).toArray();return P[0]===void 0?0:P[0].value??0}}const T=ne(f,oe);let w=n`SELECT COUNT(*) AS count FROM ${n.identifier(e)}`;return T&&(w=n`${w} WHERE ${T}`),B(i,w).one().count},async delete(e,r,a){const l=re(e,r);if(!l){const w=r===void 0?F:void 0;w&&await w.delete(e,void 0,a);return}const{docJson:h,row:u,tableName:s}=l,f=t.tables[s],m=a?.hard===!0,T=!m&&f?.softDeleteMode?f.softDeleteMode.field:void 0;if(!(T&&u[T]!==null&&u[T]!==void 0)){if(X(s,"before","delete")&&await Z("before","delete",{id:e,op:"delete",previous:u,table:s}),await un({deletedId:e,deletedReference:w=>u[w],findHolders:async(w,A,L)=>(await Ie(w).findMany(w,{includeDeleted:m,where:{[A]:L}})).page,onCascade:(w,A)=>Ie(w).delete(A,void 0,a),onRestrict:w=>{throw new pe(w,"restrict")},onSetNull:(w,A,L)=>Ie(w).patch(A,{[L]:null}),schema:t,tableName:s}),ce(s),ue(s),T){const w={...u,[T]:D(),_id:e};xe(i,s,n`UPDATE ${n.identifier(s)} SET ${n.identifier(j)} = ${ae(w)} WHERE id = ${e} AND ${n.identifier(j)} = ${h}`),be(s,e,w,u),ge(s,e,void 0),we(s,u,w),fe(s,e,u,void 0),W?.invalidate(s,e,c(s,u,w)),K(s,e,"update",w),d({indexKeys:c(s,u,w),key:e,op:"update",row:w,table:s}),X(s,"after","delete")&&await Z("after","delete",{id:e,op:"delete",previous:u,table:s}),await C({id:e,op:"delete",table:s});return}xe(i,s,n`DELETE FROM ${n.identifier(s)} WHERE id = ${e} AND ${n.identifier(j)} = ${h}`),be(s,e,void 0),ge(s,e,void 0),we(s,u,void 0),fe(s,e,u,void 0),W?.invalidate(s,e,c(s,u)),K(s,e,"delete"),d({indexKeys:c(s,u),key:e,op:"delete",table:s}),X(s,"after","delete")&&await Z("after","delete",{id:e,op:"delete",previous:u,table:s}),await C({id:e,op:"delete",table:s})}},async deleteAll(e,r){if(!t.tables[e])throw new b("INTERNAL",`unknown table: ${e}`);const a=Math.max(1,r?.chunkSize??At),l=r?.hard===void 0?void 0:{hard:r.hard},h=ee(e)?void 0:e;let u=0;return await R(async()=>{for(;;){const s=(await q.findMany(e,{limit:a})).page.map(f=>String(f._id));if(s.length===0)break;for(const f of s)await q.delete(f,h,l),u+=1;if(s.length<a)break}}),{deleted:u}},async deleteMany(e,r,a){se(e.length,r?.limit,"deleteMany");for(const l of e)await q.delete(l,a);return{deleted:e.length}},async deleteWhere(e,r,a){const l=(await(z(e,"deleteWhere")??q).findMany(e,{where:r})).page.map(h=>String(h._id));if(se(l.length,a?.limit,"deleteWhere"),q.deleteMany===void 0)throw new b("INTERNAL",`ctx.db.${e}.deleteMany is unavailable: this writer has no batch delete`);return q.deleteMany(l,a)},async findFirst(e,r={}){return(await q.findMany(e,{...r,limit:1})).page[0]??null},async findFirstOrThrow(e,r={}){const a=await q.findFirst(e,r);if(a===null)throw new nn(`findFirstOrThrow: no "${e}" document matched`);return a},async findMany(e,r={}){const a=z(e,"findMany");if(a)return N(e,H),a.findMany(e,r);const l=t.tables[e];if(!l)throw new b("INTERNAL",`unknown table: ${e}`);const h=!r.where&&!r.baseWhere;h?N(e,H):N(e);const u=rn(r.orderBy),s=r.cursor?Rt(u,He(r.cursor)):void 0;let f=Y(r.baseWhere,r.where);f=Y(f,de(l.softDeleteMode,r.includeDeleted)),f=await lt(f,{canPushExists:Je?kt:void 0,existsPushMode:ze==="always"?"always":"auto",fetcher:Ye,maxRelationKeys:Ve,relationBaseWhere:r.relationBaseWhere,schema:t,tableName:e}),s&&(f=f?{AND:[f,s]}:s);const m=Je?Qn(N):oe,T=ne(f,m);let w=n`SELECT id, _creationTime, ${n.identifier(j)} FROM ${n.identifier(e)}`;T&&(w=n`${w} WHERE ${T}`),w=n`${w} ORDER BY ${Mt(u)}`;const A=typeof r.limit=="number"?Math.max(0,Math.floor(r.limit)):void 0;A!==void 0&&(w=n`${w} LIMIT ${n.raw(String(A+1))}`);const L=B(i,w).toArray();h&&!$&&p?.recordRead(L.length);const O=[];for(const te of L){const U=le(te);U&&(O.push(U),!h&&typeof U._id=="string"&&N(e,U._id))}if(A===void 0)return r.with&&await ct({groupedCounter:Xe,fetcher:ve,parents:O,...ut(r),schema:t,tableName:e,with:r.with}),{continueCursor:null,isDone:!0,page:at(O,r.select,r.with)};const P=O.length>A,x=P?O.slice(0,A):O,G=x.at(-1);return r.with&&await ct({fetcher:ve,groupedCounter:Xe,parents:x,...ut(r),schema:t,tableName:e,with:r.with}),{continueCursor:P&&G?Pe(G,u):null,isDone:!P,page:at(x,r.select,r.with)}},async get(e,r){const a=re(e,r);if(!a){const l=r===void 0?F:void 0;return l?l.get(e):null}return N(a.tableName,e),a.row},async lookupById(e,r){const a=re(e,r);return a?(N(a.tableName,e),{row:a.row,tableName:a.tableName}):null},async groupBy(e,r){const a=z(e,"groupBy");if(a)return N(e,H),a.groupBy(e,r);const l=t.tables[e];if(!l)throw new b("INTERNAL",`unknown table: ${e}`);N(e,H);const h=r.agg??{op:"count"};if(Te(h.op),h.op!=="count"&&!h.field)throw new b("INTERNAL",`groupBy(${e}, { agg: { op: "${h.op}" } }): "field" is required for non-count reducers`);const u=de(l.softDeleteMode,void 0),s=Y(Y(r.baseWhere,r.where),u),f=await me(s,e,r.relationBaseWhere),m=f!==s,T=[...r.by,h.field];if(l.aggregateIndexes&&!r.baseWhere&&!m&&(!u||$t(l,T))){const x=jt(l.aggregateIndexes,h.op,h.field,r.by,r.where),G=x===void 0?0:Object.keys(x.partial).length,te=x?.index.by?.length??0;if(x&&(G===0||G===te)){Ce(e,x.index);const U=De(e,x.index.name),Ee=Object.keys(x.partial),ye=[];if(Ee.length===(x.index.by??[]).length&&Ee.length>0){const Ne=ke(x.index.by??[],x.partial),Se=B(i,n`SELECT ${Re} AS value, ${Fe} AS count FROM ${n.identifier(U)} WHERE ${Ae} = ${Ne}`).toArray();return Se.length>0&&ye.push({key:{...x.partial},value:Le(h.op,Se[0])}),ye}const Wt=B(i,n`SELECT ${Ae} AS key, ${Re} AS value, ${Fe} AS count FROM ${n.identifier(U)}`).toArray();for(const Ne of Wt){const Se=Ut(JSON.parse(Ne.key));ye.push({key:Se,value:Le(h.op,Ne)})}return ye}}for(const x of T){if(x===void 0)continue;const G=x===h.field?`groupBy(${e}, { agg: { op: "${h.op}", field: "${x}" } })`:`groupBy(${e}, { by: [..."${x}"] })`;wt(l,x,G)}const w=ne(f,oe),A=r.by.map(x=>n`${J(x)} AS ${n.identifier(x)}`);if(h.op==="count")A.push(n`COUNT(*) AS value`);else{const{field:x}=h;if(x===void 0)throw new b("INTERNAL",`groupBy(${e}, { agg: { op: "${h.op}" } }): "field" is required for non-count reducers`);A.push(n`${n.raw(Te(h.op))}(${J(x)}) AS value`)}let L=n`SELECT ${n.join(A,n`, `)} FROM ${n.identifier(e)}`;w&&(L=n`${L} WHERE ${w}`),L=n`${L} GROUP BY ${n.join(r.by.map(x=>J(x)),n`, `)}`;const O=B(i,L).toArray(),P=[];for(const x of O){const G={};for(const U of r.by)G[U]=x[U]??null;const{value:te}=x;P.push({key:G,value:te==null?null:Number(te)})}return P},async insert(e,r,a){const l=z(e,"insert");if(l){const T=await l.insert(e,r,a);return $||p?.recordWrite(r),d({key:T,op:"insert",row:{...r,_id:T},table:e}),T}const h=t.tables[e];if(!h)throw new b("INTERNAL",`unknown table: ${e}`);const u=bt(h,r,E);Be(h,u);let s;a?.clientId!==void 0?(Mn(a.clientId),s=a.clientId):a?.allowExplicitId&&typeof u._id=="string"?s=u._id:s=k();const f=a?.allowExplicitId&&typeof u._creationTime=="number"?u._creationTime:D(),m={...u,_creationTime:f,_id:s};return X(e,"before","insert")&&await Z("before","insert",{doc:{...m},id:s,op:"insert",table:e}),ce(e),ue(e),je(i,e,n`INSERT INTO ${n.identifier(e)} (id, _creationTime, ${n.identifier(j)}) VALUES (${s}, ${f}, ${ae(m)})`),et(e,s,m),X(e,"after","insert")&&await Z("after","insert",{doc:m,id:s,op:"insert",table:e}),await C({doc:m,id:s,op:"insert",table:e}),s},async insertManyUnsafe(e,r,a){if(se(r.length,a?.limit,"insertManyUnsafe"),r.length===0)return[];const l=z(e,"insert");if(l){const s=[];for(const f of r){const m=await l.insert(e,f,{allowExplicitId:a?.allowExplicitId});$||p?.recordWrite(f),d({key:m,op:"insert",row:{...f,_id:m},table:e}),s.push(m)}return s}const h=t.tables[e];if(!h)throw new b("INTERNAL",`unknown table: ${e}`);ce(e),ue(e);const u=r.map(s=>{const f=bt(h,s,E),m=a?.allowExplicitId===!0&&typeof f._id=="string"?f._id:k(),T=a?.allowExplicitId===!0&&typeof f._creationTime=="number"?f._creationTime:D();return{creationTime:T,document:{...f,_creationTime:T,_id:m},id:m}});if(!$)for(const s of u)p?.recordWrite(s.document);for(let s=0;s<u.length;s+=mt){const f=n.join(u.slice(s,s+mt).map(m=>n`(${m.id}, ${m.creationTime}, ${ae(m.document)})`),n`, `);je(i,e,n`INSERT INTO ${n.identifier(e)} (id, _creationTime, ${n.identifier(j)}) VALUES ${f}`)}for(const{document:s,id:f}of u)et(e,f,s),await _({doc:s,id:f,op:"insert",table:e});return u.map(s=>s.id)},async insertMany(e,r,a){se(r.length,a?.limit,"insertMany");const l=a?.skipDuplicates===!0,h=[];for(const u of r)try{h.push(await q.insert(e,u))}catch(s){if(l&&s instanceof pe&&s.kind==="unique")h.push(null);else throw s}return h},normalizeId(e,r){return gt(t,e,r)},async patch(e,r,a){const l=re(e,a);if(!l){const T=a===void 0?F:void 0;if(T){await T.patch(e,r);return}throw new b("INTERNAL",`document not found: ${e}`)}const{docJson:h,row:u,tableName:s}=l,f=t.tables[s];if(!f)throw new b("INTERNAL",`unknown table: ${s}`);N(s,e),yt("patch",r);const m={...u,...r,_id:e};Et(f,r,m,E),Be(f,m,!0),X(s,"before","update")&&await Z("before","update",{doc:{...m},id:e,op:"update",previous:u,table:s}),ce(s),ue(s),xe(i,s,n`UPDATE ${n.identifier(s)} SET ${n.identifier(j)} = ${ae(m)} WHERE id = ${e} AND ${n.identifier(j)} = ${h}`),be(s,e,m,u),ge(s,e,m),we(s,u,m),fe(s,e,u,m),W?.invalidate(s,e,c(s,u,m)),K(s,e,"update",m),d({indexKeys:c(s,u,m),key:e,op:"update",row:m,table:s}),X(s,"after","update")&&await Z("after","update",{doc:m,id:e,op:"update",previous:u,table:s}),await C({doc:m,id:e,op:"update",table:s})},async patchMany(e,r,a){se(e.length,r?.limit,"patchMany");for(const l of e)await q.patch(l.id,l.patch,a);return{patched:e.length}},async patchWhere(e,r,a){const l=(await(z(e,"patchWhere")??q).findMany(e,{where:r.where})).page.map(h=>({id:String(h._id),patch:r.patch}));if(se(l.length,a?.limit,"patchWhere"),q.patchMany===void 0)throw new b("INTERNAL",`ctx.db.${e}.patchMany is unavailable: this writer has no batch patch`);return await q.patchMany(l,a),{patched:l.length}},query(e){const r=z(e,"query");return r?(N(e,H),r.query(e)):er(i,t,e,S,a=>{a?g(a):N(e,H)},a=>{$||p?.recordRead(a)})},async rank(e,r,a){const l=z(e,"rank");if(l)return N(e,H),l.rank(e,r,a);S(e,r,"rank");const h=t.tables[e];if(!h)throw new b("INTERNAL",`unknown table: ${e}`);const u=h.rankIndexes?.find(U=>U.name===r);if(!u)throw new b("INTERNAL",`unknown rankIndex "${r}" on table "${e}"`);if(tt(e,h,u),a.restrictsCounts)throw new We(e);N(e,H),Me(e,u);const s=typeof a.row=="string"?a.row:a.row._id;if(!s)return null;const f=dt(e,u.name),m=u.sortBy.map((U,Ee)=>st(Ee)),T=m.map(U=>wn(U)).join(", "),w=B(i,n`SELECT ${n.identifier("__partition__")}, ${n.raw(T)} FROM ${n.identifier(f)} WHERE ${n.identifier("__id__")} = ${s}`).toArray(),[A]=w;if(A===void 0)return null;let L=A.__partition__;const O=Y(a.baseWhere,a.where);Oe(O,t,e,"rank");const P=an(u,O);if(P){const U=sn(u.partitionBy??[],P);if(U!==L)return null;L=U}const x=m.map(U=>A[U]),{before:G,total:te}=Nt(i,f,m,u.sortBy,L,x,s);return{position:G+1,total:te}},async rankBefore(e,r,a){if(ee(e))throw new b("INTERNAL",`rankBefore is not supported on the global (.global()) table '${e}' — cross-shard rank cursors apply only to sharded tables`);const l=t.tables[e];if(!l)throw new b("INTERNAL",`unknown table: ${e}`);const h=l.rankIndexes?.find(m=>m.name===r);if(!h)throw new b("INTERNAL",`unknown rankIndex "${r}" on table "${e}"`);if(a.restrictsCounts)throw new We(e);N(e,H),Me(e,h);const u=dt(e,h.name),s=h.sortBy.map((m,T)=>st(T)),f=h.sortBy.map((m,T)=>ie(a.sortValues[T]??null));return Nt(i,u,s,h.sortBy,a.partitionKey,f,a.rowId)},async rankPage(e,r,a={}){Oe(Y(a.baseWhere,a.where),t,e,"rankPage");const l=z(e,"rankPage");if(l)return N(e,H),l.rankPage(e,r,a);S(e,r,"rank");const{continueCursor:h,hasMore:u,rows:s}=ot(rt,e,r,a);return{continueCursor:h,isDone:!u,page:s.map(f=>f.doc)}},async rankPageRows(e,r,a={}){Oe(Y(a.baseWhere,a.where),t,e,"rankPage"),S(e,r,"rank");const{directions:l,hasMore:h,rows:u}=ot(rt,e,r,a);return{directions:l,hasMore:h,rows:u}},async restore(e,r){const a=re(e,r);if(!a){const u=r===void 0?F:void 0;if(u?.restore){await u.restore(e);return}throw new b("INTERNAL",`document not found: ${e}`)}const l=t.tables[a.tableName]?.softDeleteMode?.field;if(!l)throw new b("INTERNAL",`ctx.db.restore: table "${a.tableName}" is not a .softDelete() table`);const h=a.row[l]!==null&&a.row[l]!==void 0;await q.patch(e,{[l]:null},r),h&&fe(a.tableName,e,void 0,a.row)},async replace(e,r,a,l){const h=re(e,a);if(!h){const A=a===void 0?F:void 0;if(A){await A.replace(e,r,void 0,l);return}throw new b("INTERNAL",`document not found: ${e}`)}const{docJson:u,row:s,tableName:f}=h,m=t.tables[f];if(!m)throw new b("INTERNAL",`unknown table: ${f}`);yt("replace",r);const T=l?.allowExplicitId&&typeof r._creationTime=="number"?r._creationTime:D(),w={...r,_creationTime:T,_id:e};Et(m,r,w,E),Be(m,w),X(f,"before","update")&&await Z("before","update",{doc:{...w},id:e,op:"update",previous:s,table:f}),ce(f),ue(f),xe(i,f,n`UPDATE ${n.identifier(f)} SET _creationTime = ${T}, ${n.identifier(j)} = ${ae(w)} WHERE id = ${e} AND ${n.identifier(j)} = ${u}`),be(f,e,w,s),ge(f,e,w),we(f,s,w),fe(f,e,s,w),W?.invalidate(f,e,c(f,s,w)),K(f,e,"update",w),d({indexKeys:c(f,s,w),key:e,op:"update",row:w,table:f}),X(f,"after","update")&&await Z("after","update",{doc:w,id:e,op:"update",previous:s,table:f}),await C({doc:w,id:e,op:"update",table:f})},async wipeShard(e){const r=new Set(e?.exclude),a=e?.tables,l=Object.entries(t.tables).filter(([f,m])=>r.has(f)||a!==void 0&&!a.includes(f)?!1:m.shardMode?.kind!=="global").map(([f])=>f);if(a!==void 0){for(const f of a)if(!t.tables[f])throw new b("INTERNAL",`wipeShard: unknown table: ${f}`)}const h={};let u=0;const{deleteAll:s}=q;if(s===void 0)throw new b("INTERNAL","wipeShard: this writer has no deleteAll");for(const f of l){const m=await s(f,{...e?.chunkSize===void 0?{}:{chunkSize:e.chunkSize},hard:!0});h[f]=m.deleted,u+=m.deleted}return{deleted:u,tables:h}}},Dt={db:q,scheduler:Q};return o.enforceRls===!0?hn(q,t,(e,r)=>re(e,r)?.tableName,(e,r)=>Lt(e,r)):q};export{Br as CDC_LOG_TABLE,Yr as CLIENT_WATERMARK_TABLE,Zr as GLOBAL_SHAPE_SNAPSHOT_TABLE,ao as IDEMPOTENCY_TABLE,Vn as NotUniqueError,po as SEARCH_STATE_TABLE,zr as advanceClientWatermark,qr as applyCdcChanges,Mn as assertValidClientId,Dr as backfillAggregateIndexes,Wr as backfillRankIndexes,Fr as backfillSearchIndexes,Ur as bumpCdcEpoch,Mr as createShardCtxDb,eo as deleteGlobalShapeSnapshot,to as deleteGlobalShapeSnapshotsForConnection,Jr as migrateClientWatermark,no as migrateGlobalShapeSnapshot,Hr as minCdcSeq,gt as normalizeIdStructurally,Pr as readCdcChanges,jr as readCdcCursor,Qr as readCdcEpoch,Vr as readClientWatermark,ro as readGlobalShapeSnapshot,so as readIdempotent,fo as runShardMigrations,$o as selectShapeMemberIds,wo as selectShapeRows,Kr as trimCdcChanges,lo as trimIdempotent,oo as writeGlobalShapeSnapshot,co as writeIdempotent};
@@ -1,4 +1,4 @@
1
- import{runSql as d,orNull as u,decodeJsonColumn as _}from"./runDrizzle-B6rnz3so.mjs";const s="__lunora_queue_messages",T=500,E=128*1024,i="… [truncated by the dev queue catcher]",m="[unserializable message body]",p=e=>{if(e===void 0)return"null";try{const t=JSON.stringify(e);return t.length>E?JSON.stringify(`${t.slice(0,E)}${i}`):t}catch{return JSON.stringify(m)}},g=e=>typeof e=="string"&&(e===m||e.endsWith(i)),o=e=>{d(e,`CREATE TABLE IF NOT EXISTS "${s}" (
1
+ import{runSql as d,orNull as u,decodeJsonColumn as _}from"./runDrizzle-CgYGDEeB.mjs";const s="__lunora_queue_messages",T=500,E=128*1024,i="… [truncated by the dev queue catcher]",m="[unserializable message body]",p=e=>{if(e===void 0)return"null";try{const t=JSON.stringify(e);return t.length>E?JSON.stringify(`${t.slice(0,E)}${i}`):t}catch{return JSON.stringify(m)}},g=e=>typeof e=="string"&&(e===m||e.endsWith(i)),o=e=>{d(e,`CREATE TABLE IF NOT EXISTS "${s}" (
2
2
  id TEXT PRIMARY KEY,
3
3
  captured_at INTEGER NOT NULL,
4
4
  message_id TEXT NOT NULL,
@@ -1,4 +1,4 @@
1
- import{quoteIdentifier as T}from"./quoteIdentifier-CObIFRhb.mjs";import{runSql as e}from"./runDrizzle-B6rnz3so.mjs";const i="__lunora_schema_history",R=50,a=T(i),n=s=>({appliedAt:typeof s.applied_at=="number"?s.applied_at:0,hash:typeof s.hash=="string"?s.hash:"",seq:typeof s.seq=="number"?s.seq:0}),h=s=>{e(s,`CREATE TABLE IF NOT EXISTS ${a} (
1
+ import{quoteIdentifier as T}from"./quoteIdentifier-CObIFRhb.mjs";import{runSql as e}from"./runDrizzle-CgYGDEeB.mjs";const i="__lunora_schema_history",R=50,a=T(i),n=s=>({appliedAt:typeof s.applied_at=="number"?s.applied_at:0,hash:typeof s.hash=="string"?s.hash:"",seq:typeof s.seq=="number"?s.seq:0}),h=s=>{e(s,`CREATE TABLE IF NOT EXISTS ${a} (
2
2
  hash TEXT PRIMARY KEY,
3
3
  seq INTEGER NOT NULL,
4
4
  snapshot_json TEXT NOT NULL,
@@ -1 +1 @@
1
- import{sql as i}from"drizzle-orm";import{runDrizzle as n}from"./runDrizzle-B6rnz3so.mjs";const o="__lunora_search_state",a=e=>{n(e,i`CREATE TABLE IF NOT EXISTS ${i.identifier(o)} (${i.identifier("companion")} TEXT PRIMARY KEY, ${i.identifier("cursor")} TEXT, ${i.identifier("done")} INTEGER NOT NULL DEFAULT 0, ${i.identifier("profile")} TEXT)`);try{n(e,i`ALTER TABLE ${i.identifier(o)} ADD COLUMN ${i.identifier("profile")} TEXT`)}catch{}},c=e=>e===1||e===!0||e==="1",l=(e,t)=>{const r=n(e,i`SELECT ${i.identifier("cursor")}, ${i.identifier("done")}, ${i.identifier("profile")} FROM ${i.identifier(o)} WHERE ${i.identifier("companion")} = ${t}`).toArray()[0];return r?{cursor:r.cursor??void 0,done:c(r.done),profile:r.profile??void 0}:{cursor:void 0,done:!1,profile:void 0}},s=(e,t,r,d,f)=>{const $=r??null;n(e,i`INSERT INTO ${i.identifier(o)} (${i.identifier("companion")}, ${i.identifier("cursor")}, ${i.identifier("done")}, ${i.identifier("profile")}) VALUES (${t}, ${$}, ${d?1:0}, ${f}) ON CONFLICT (${i.identifier("companion")}) DO UPDATE SET ${i.identifier("cursor")} = excluded.${i.identifier("cursor")}, ${i.identifier("done")} = excluded.${i.identifier("done")}, ${i.identifier("profile")} = excluded.${i.identifier("profile")}`)};export{o as SEARCH_STATE_TABLE,a as migrateSearchState,l as readSearchBackfillState,s as writeSearchBackfillState};
1
+ import{sql as i}from"drizzle-orm";import{runDrizzle as n}from"./runDrizzle-CgYGDEeB.mjs";const o="__lunora_search_state",a=e=>{n(e,i`CREATE TABLE IF NOT EXISTS ${i.identifier(o)} (${i.identifier("companion")} TEXT PRIMARY KEY, ${i.identifier("cursor")} TEXT, ${i.identifier("done")} INTEGER NOT NULL DEFAULT 0, ${i.identifier("profile")} TEXT)`);try{n(e,i`ALTER TABLE ${i.identifier(o)} ADD COLUMN ${i.identifier("profile")} TEXT`)}catch{}},c=e=>e===1||e===!0||e==="1",l=(e,t)=>{const r=n(e,i`SELECT ${i.identifier("cursor")}, ${i.identifier("done")}, ${i.identifier("profile")} FROM ${i.identifier(o)} WHERE ${i.identifier("companion")} = ${t}`).toArray()[0];return r?{cursor:r.cursor??void 0,done:c(r.done),profile:r.profile??void 0}:{cursor:void 0,done:!1,profile:void 0}},s=(e,t,r,d,f)=>{const $=r??null;n(e,i`INSERT INTO ${i.identifier(o)} (${i.identifier("companion")}, ${i.identifier("cursor")}, ${i.identifier("done")}, ${i.identifier("profile")}) VALUES (${t}, ${$}, ${d?1:0}, ${f}) ON CONFLICT (${i.identifier("companion")}) DO UPDATE SET ${i.identifier("cursor")} = excluded.${i.identifier("cursor")}, ${i.identifier("done")} = excluded.${i.identifier("done")}, ${i.identifier("profile")} = excluded.${i.identifier("profile")}`)};export{o as SEARCH_STATE_TABLE,a as migrateSearchState,l as readSearchBackfillState,s as writeSearchBackfillState};
@@ -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-BTi8DLUl.mjs";import"@lunora/errors";import{sql as r}from"drizzle-orm";import{matchesStaticWhere as A}from"./AGGREGATE_SQL_FUNCTION-CTo0-9iZ.mjs";import{encodeAggregateKey as L,foldAggregateTally as C,aggregateTableName as F}from"./aggregateTableName-DgYMC5tr.mjs";import{migrateSearchState as y,readSearchBackfillState as D,writeSearchBackfillState as N}from"./SEARCH_STATE_TABLE-BZ_fxI5l.mjs";import{runDrizzle as d}from"./runDrizzle-B6rnz3so.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-1Yi1_Yq0.mjs";import{isLiveForCompanion as _}from"./applySelect-UY-o13Ia.mjs";import{matchesRankStaticWhere as U,rankTableName as V}from"./RANK_TIEBREAK-DDtST3gN.mjs";const Y=(e,o)=>e.profile!==o?{cursor:void 0,finished:!1,wipe:e.cursor!==void 0||e.done}:{cursor:e.cursor,finished:e.done,wipe:!1},u=(e,o)=>d(e,r`SELECT COUNT(*) AS count FROM ${r.identifier(o)}`).one().count>0,I=(e,o)=>d(e,r`SELECT id, _creationTime, ${r.identifier(E)} FROM ${r.identifier(o)}`).toArray(),q=(e,o,n,i)=>{const t=F(o,n.name);if(u(e,t))return;const s=n.by??[],c=new Map,f=I(e,o);for(const l of f){const a=p(l);if(!a||!_(a,i)||n.where&&!A(a,n.where))continue;const $=L(s,a);C(c,$,n,a)}for(const[l,a]of c)d(e,r`INSERT INTO ${r.identifier(t)} (${v}, ${B}, ${W}) VALUES (${l}, ${a.value}, ${a.count})`)},re=(e,o)=>{for(const[n,i]of Object.entries(o.tables))if(!(i.shardMode?.kind==="global"||!i.aggregateIndexes))for(const t of i.aggregateIndexes)q(e,n,t,i.softDeleteMode?.field)},z=(e,o,n)=>{const i=V(o,n.name);if(u(e,i))return;const t=R(n),s=I(e,o);for(const c of s){const f=p(c);!f||n.where&&!U(f,n.where)||x(e,i,n,t,f._id,f)}},oe=(e,o)=>{for(const[n,i]of Object.entries(o.tables))if(!(i.shardMode?.kind==="global"||!i.rankIndexes))for(const t of i.rankIndexes)z(e,n,t)},g=500,b=(e,o,n)=>{const i=w(o,n.name),{profile:t}=k(n.language),s=Y(D(e,i),t);if(s.finished)return!0;s.wipe&&d(e,r`DELETE FROM ${r.identifier(i)}`);const{cursor:c}=s,f=d(e,c===void 0?r`SELECT id, _creationTime, ${r.identifier(E)} FROM ${r.identifier(o)} ORDER BY id ASC LIMIT ${r.raw(String(g))}`:r`SELECT id, _creationTime, ${r.identifier(E)} FROM ${r.identifier(o)} WHERE id > ${c} ORDER BY id ASC LIMIT ${r.raw(String(g))}`).toArray();let l=c;for(const $ of f){const{id:m}=$;if(typeof m!="string")continue;l=m,d(e,r`DELETE FROM ${r.identifier(i)} WHERE ${r.identifier(S)} = ${m}`);const h=j($);h&&d(e,r`INSERT INTO ${r.identifier(i)} (${r.identifier(O)}, ${r.identifier(S)}) VALUES (${M(h,n)}, ${m})`)}const a=f.length<g;return N(e,i,l,a,t),a},ne=(e,o,n)=>{if(T(e))for(const i of n.searchIndexes??[])i.staged||b(e,o,i)},te=(e,o)=>{if(T(e)){y(e);for(const[n,i]of Object.entries(o.tables))if(!(i.shardMode?.kind==="global"||!i.searchIndexes))for(const t of i.searchIndexes){let s=!1;for(;!s;)s=b(e,n,t)}}};export{re as backfillAggregateIndexes,oe as backfillRankIndexes,te as backfillSearchIndexes,ne as backfillSearchIndexesForTable};
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-D2ZMFBrP.mjs";import"@lunora/errors";import{sql as r}from"drizzle-orm";import{matchesStaticWhere as A}from"./AGGREGATE_SQL_FUNCTION-CTo0-9iZ.mjs";import{encodeAggregateKey as L,foldAggregateTally as C,aggregateTableName as F}from"./aggregateTableName-DgYMC5tr.mjs";import{migrateSearchState as y,readSearchBackfillState as D,writeSearchBackfillState as N}from"./SEARCH_STATE_TABLE-MDlr30EJ.mjs";import{runDrizzle as d}from"./runDrizzle-CgYGDEeB.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-Cg_QiQYA.mjs";import{isLiveForCompanion as _}from"./applySelect-UY-o13Ia.mjs";import{matchesRankStaticWhere as U,rankTableName as V}from"./RANK_TIEBREAK-DDtST3gN.mjs";const Y=(e,o)=>e.profile!==o?{cursor:void 0,finished:!1,wipe:e.cursor!==void 0||e.done}:{cursor:e.cursor,finished:e.done,wipe:!1},u=(e,o)=>d(e,r`SELECT COUNT(*) AS count FROM ${r.identifier(o)}`).one().count>0,I=(e,o)=>d(e,r`SELECT id, _creationTime, ${r.identifier(E)} FROM ${r.identifier(o)}`).toArray(),q=(e,o,n,i)=>{const t=F(o,n.name);if(u(e,t))return;const s=n.by??[],c=new Map,f=I(e,o);for(const l of f){const a=p(l);if(!a||!_(a,i)||n.where&&!A(a,n.where))continue;const $=L(s,a);C(c,$,n,a)}for(const[l,a]of c)d(e,r`INSERT INTO ${r.identifier(t)} (${v}, ${B}, ${W}) VALUES (${l}, ${a.value}, ${a.count})`)},re=(e,o)=>{for(const[n,i]of Object.entries(o.tables))if(!(i.shardMode?.kind==="global"||!i.aggregateIndexes))for(const t of i.aggregateIndexes)q(e,n,t,i.softDeleteMode?.field)},z=(e,o,n)=>{const i=V(o,n.name);if(u(e,i))return;const t=R(n),s=I(e,o);for(const c of s){const f=p(c);!f||n.where&&!U(f,n.where)||x(e,i,n,t,f._id,f)}},oe=(e,o)=>{for(const[n,i]of Object.entries(o.tables))if(!(i.shardMode?.kind==="global"||!i.rankIndexes))for(const t of i.rankIndexes)z(e,n,t)},g=500,b=(e,o,n)=>{const i=w(o,n.name),{profile:t}=k(n.language),s=Y(D(e,i),t);if(s.finished)return!0;s.wipe&&d(e,r`DELETE FROM ${r.identifier(i)}`);const{cursor:c}=s,f=d(e,c===void 0?r`SELECT id, _creationTime, ${r.identifier(E)} FROM ${r.identifier(o)} ORDER BY id ASC LIMIT ${r.raw(String(g))}`:r`SELECT id, _creationTime, ${r.identifier(E)} FROM ${r.identifier(o)} WHERE id > ${c} ORDER BY id ASC LIMIT ${r.raw(String(g))}`).toArray();let l=c;for(const $ of f){const{id:m}=$;if(typeof m!="string")continue;l=m,d(e,r`DELETE FROM ${r.identifier(i)} WHERE ${r.identifier(S)} = ${m}`);const h=j($);h&&d(e,r`INSERT INTO ${r.identifier(i)} (${r.identifier(O)}, ${r.identifier(S)}) VALUES (${M(h,n)}, ${m})`)}const a=f.length<g;return N(e,i,l,a,t),a},ne=(e,o,n)=>{if(T(e))for(const i of n.searchIndexes??[])i.staged||b(e,o,i)},te=(e,o)=>{if(T(e)){y(e);for(const[n,i]of Object.entries(o.tables))if(!(i.shardMode?.kind==="global"||!i.searchIndexes))for(const t of i.searchIndexes){let s=!1;for(;!s;)s=b(e,n,t)}}};export{re as backfillAggregateIndexes,oe as backfillRankIndexes,te as backfillSearchIndexes,ne as backfillSearchIndexesForTable};
@@ -1 +1 @@
1
- import{L as u,a as l,j as m}from"./do-sql-1Yi1_Yq0.mjs";import{quoteIdentifier as a}from"./quoteIdentifier-CObIFRhb.mjs";import{reprojectionMigrationTable as j}from"./REPROJECTION_MIGRATION_PREFIX-D2dltRFC.mjs";import{REPROJECTION_MIGRATION_PREFIX as _,reprojectionMigrationId as x}from"./REPROJECTION_MIGRATION_PREFIX-D2dltRFC.mjs";import{a as b}from"./wire-codec-Dsy70M3Q.mjs";import{runSql as f}from"./runDrizzle-B6rnz3so.mjs";import{y as d}from"./sql-projection-jfoe331H.mjs";const E=b(0n)[0],$=r=>r.shardMode?.kind==="global"?[]:Object.entries(r.shape).filter(([,t])=>d(t)).map(([t])=>t),L=r=>Object.entries(r.tables).filter(([,t])=>$(t).length>0).map(([t])=>t),g=r=>{const t=r.map(()=>`(json_extract(${a(l)}, ?) = ? AND json_extract(${a(l)}, ?) IN (?, ?))`);return{params:r.flatMap(o=>[`$.${m(o)}[0]`,E,`$.${m(o)}[1]`,"bigint","bytes"]),sql:t.join(" OR ")}},S=(r,t,o)=>{if(o.length===0)return 0;const{params:e,sql:n}=g(o);return f(r,`SELECT COUNT(*) AS count FROM ${a(t)} WHERE ${n}`,...e).toArray()[0]?.count??0},R=(r,t,o,e)=>{const{params:n,sql:i}=g(o);return f(r,`SELECT 1 FROM ${a(t)} WHERE id = ? AND (${i}) LIMIT 1`,e,...n).toArray().length>0},A=(r,t,o)=>{const e=j(r);if(e===void 0)return;const n=t.tables[e];if(!n)return;const i=$(n);if(i.length!==0)return{id:r,table:e,up:s=>{const c=s._id;if(!(typeof c!="string"||!R(o,e,i,c))){try{u(s)}catch(p){console.warn(`${r}: skipping row ${c} — it cannot be re-projected: ${p instanceof Error?p.message:String(p)}`);return}return s}}}};export{_ as REPROJECTION_MIGRATION_PREFIX,A as buildReprojectionMigration,S as countLegacyRows,$ as reprojectableFields,x as reprojectionMigrationId,L as reprojectionTables};
1
+ import{L as u,a as l,j as m}from"./do-sql-Cg_QiQYA.mjs";import{quoteIdentifier as a}from"./quoteIdentifier-CObIFRhb.mjs";import{reprojectionMigrationTable as j}from"./REPROJECTION_MIGRATION_PREFIX-D2dltRFC.mjs";import{REPROJECTION_MIGRATION_PREFIX as _,reprojectionMigrationId as x}from"./REPROJECTION_MIGRATION_PREFIX-D2dltRFC.mjs";import{a as b}from"./wire-codec-Dsy70M3Q.mjs";import{runSql as f}from"./runDrizzle-CgYGDEeB.mjs";import{y as d}from"./sql-projection-jfoe331H.mjs";const E=b(0n)[0],$=r=>r.shardMode?.kind==="global"?[]:Object.entries(r.shape).filter(([,t])=>d(t)).map(([t])=>t),L=r=>Object.entries(r.tables).filter(([,t])=>$(t).length>0).map(([t])=>t),g=r=>{const t=r.map(()=>`(json_extract(${a(l)}, ?) = ? AND json_extract(${a(l)}, ?) IN (?, ?))`);return{params:r.flatMap(o=>[`$.${m(o)}[0]`,E,`$.${m(o)}[1]`,"bigint","bytes"]),sql:t.join(" OR ")}},S=(r,t,o)=>{if(o.length===0)return 0;const{params:e,sql:n}=g(o);return f(r,`SELECT COUNT(*) AS count FROM ${a(t)} WHERE ${n}`,...e).toArray()[0]?.count??0},R=(r,t,o,e)=>{const{params:n,sql:i}=g(o);return f(r,`SELECT 1 FROM ${a(t)} WHERE id = ? AND (${i}) LIMIT 1`,e,...n).toArray().length>0},A=(r,t,o)=>{const e=j(r);if(e===void 0)return;const n=t.tables[e];if(!n)return;const i=$(n);if(i.length!==0)return{id:r,table:e,up:s=>{const c=s._id;if(!(typeof c!="string"||!R(o,e,i,c))){try{u(s)}catch(p){console.warn(`${r}: skipping row ${c} — it cannot be re-projected: ${p instanceof Error?p.message:String(p)}`);return}return s}}}};export{_ as REPROJECTION_MIGRATION_PREFIX,A as buildReprojectionMigration,S as countLegacyRows,$ as reprojectableFields,x as reprojectionMigrationId,L as reprojectionTables};
@@ -0,0 +1 @@
1
+ import{LunoraError as p}from"@lunora/errors";import{sql as s}from"drizzle-orm";import{sqliteInList as f,WORKERD_SQLITE_LIMITS as $}from"./param-C68MV3DD.mjs";import{RELATION_EXISTS_KEY as N}from"./RELATION_EXISTS_KEY-BaqSIFU1.mjs";const I=["eq","ne","lt","lte","gt","gte","in","notIn","isNull","contains"],O=new Set(I),T={eq:"=",gt:">",gte:">=",lt:"<",lte:"<=",ne:"<>"},h=r=>{if(r===null||typeof r!="object"||Array.isArray(r))return!1;const e=Object.keys(r);return e.length>0&&e.every(t=>O.has(t))},m=(r,e,t)=>{const o=s`${t.serialize(e)}`;return t.containsExpr?t.containsExpr(r,o):s`instr(lower(${r}), lower(${o})) > 0`},y=(r,e,t,o,n)=>o===null?e==="ne"?s`${r} IS NOT NULL`:s`${r} IS NULL`:s`${r} ${s.raw(t)} ${n.serialize(o)}`,S=(r,e,t,o)=>{const n=Array.isArray(t)?t:[];if(n.length===0)return e==="IN"?s`0 = 1`:s`1 = 1`;const i=n.map(a=>o.serialize(a)),l=e==="NOT IN";return(o.inList??f)(r,i,l)},U=(r,e,t)=>{const o=s.join(e.map(n=>s`${n}`),s`, `);return t?s`${r} NOT IN (${o})`:s`${r} IN (${o})`},A=(r,e,t)=>{const o=e,n=[];for(const i of I){if(!(i in o))continue;const l=o[i],a=T[i];a?n.push(y(r,i,a,l,t)):i==="isNull"?n.push(l?s`${r} IS NULL`:s`${r} IS NOT NULL`):i==="contains"?n.push(m(r,l,t)):n.push(S(r,i==="in"?"IN":"NOT IN",l,t))}return n},E=(r,e,t)=>{const o=t.fieldRef(r);return h(e)?A(o,e,t):e===null?[s`${o} IS NULL`]:[s`${o} = ${t.serialize(e)}`]},L=(r,e)=>{if(r.length!==0)return r.length===1?r[0]:s.join(r.map(t=>s`(${t})`),s` ${s.raw(e)} `)},g=(r,e,t)=>{const o=Array.isArray(r)?r:[],n=[];for(const i of o){const l=u(i??{},t);l&&n.push(l)}return n.length===0?e==="OR"?s`0 = 1`:void 0:L(n,e)},w=new Set(["AND","NOT","OR",N]),R=(r,e,t)=>{if(r===N){if(!t.relationExists)throw new p("INTERNAL","encountered a relation EXISTS marker without a relationExists strategy hook");return t.relationExists(e)}if(r==="NOT"){const o=u(e??{},t);return o?s`NOT (${o})`:void 0}return g(e,r,t)},u=(r,e)=>{const t=[];for(const[o,n]of Object.entries(r))if(w.has(o)){const i=R(o,n,e);i&&t.push(i)}else t.push(...E(o,n,e));return L(t,"AND")},j=$.boundParams/2,c=r=>{if(Array.isArray(r))return r.reduce((t,o)=>t+c(o),0);if(r===null||typeof r!="object")return 0;let e=0;for(const[t,o]of Object.entries(r))t==="in"||t==="notIn"?e+=1:(t==="AND"||t==="NOT"||t==="OR"||h(o))&&(e+=c(o));return e},k=(r,e)=>{if(!r||Object.keys(r).length===0)return;const t=e.inList??f,o=c(r);if(o===0)return u(r,e);const n=Math.max(1,Math.floor(j/o));return u(r,{...e,inList:(i,l,a)=>t(i,l,a,n)})};export{k as compileWhereSql,U as literalInList};
@@ -0,0 +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-CgYGDEeB.mjs";import{sqliteInList as O}from"./param-C68MV3DD.mjs";import{decodeCursor as W,toBase64 as z}from"./applySelect-UY-o13Ia.mjs";import{sortColumnName as F,resolveRankPartition as H,RANK_TIEBREAK as m,encodePartitionKey as J,rankTableName as V}from"./RANK_TIEBREAK-DDtST3gN.mjs";const Y="__doc__",G=n=>z(JSON.stringify(n)),X=n=>n.after?[n.after.partitionKey,...n.after.sortValues,n.after.rowId]:n.cursor?W(n.cursor):void 0,Z=(n,o,f)=>{if(n?.length!==1+o.length+1)return;const r=[{column:"__partition__",direction:"asc"}];for(const[s,a]of o.entries())r.push({column:a,direction:f[s]?.direction??"asc"});r.push({column:m,direction:"asc"});const e=[];for(const[s,a]of r.entries()){const c=[];for(const[i,l]of r.slice(0,s).entries())c.push(t`${t.identifier(l.column)} IS ${n[i]}`);c.push(t`${t.identifier(a.column)} ${t.raw(a.direction==="desc"?"<":">")} ${n[s]}`);const[p]=c;e.push(c.length===1&&p!==void 0?p:t`(${t.join(c,t` AND `)})`)}return t`(${t.join(e,t` OR `)})`},C=null,Q=(n,o)=>{if(n===void 0)return C;const f=[n.__partition__,...o.map(r=>n[r]),n[m]];return G(f)},U=(n,o,f)=>{const r=[];for(const e of n){const s=e[m];if(typeof s!="string")continue;const a=o.get(s);if(!a)continue;const c=typeof e.__partition__=="string"?e.__partition__:"",p=f.map(i=>e[i]??null);r.push({doc:a,key:{partitionKey:c,rowId:s,sortValues:p}})}return r},tt=t`${t.identifier("id")}`,nt=(n,o,f)=>{const{rowToDocument:r}=n,e=new Map;if(f.length===0)return e;const s=B(n.sql,t`SELECT id, _creationTime, ${t.identifier(Y)} FROM ${t.identifier(o)} WHERE ${O(tt,f,!1)}`).toArray();for(const a of s){const c=r(a),p=a.id;c&&typeof p=="string"&&e.set(p,c)}return e},pt=(n,o,f,r)=>{const{assertRankPartitionLocal:e,ensureRankBackfilled:s,onRead:a,schema:c}=n,p=c.tables[o];if(!p)throw new N("INTERNAL",`unknown table: ${o}`);const i=p.rankIndexes?.find(u=>u.name===f);if(!i)throw new N("INTERNAL",`unknown rankIndex "${f}" on table "${o}"`);e(o,p,i),a(o,x),s(o,i);const l=V(o,i.name),d=i.sortBy.map((u,w)=>F(w)),$=Math.max(1,Math.min(1e3,Math.floor(r.take??100))),S=v(r.baseWhere,r.where),R=H(i,S),h=[t`${t.identifier("__partition__")} ASC`];for(const[u,w]of d.entries()){const q=i.sortBy[u]?.direction;h.push(t`${t.identifier(w)} ${t.raw(q==="desc"?"DESC":"ASC")}`)}h.push(t`${t.identifier(m)} ASC`);const _=[];typeof r.partitionKey=="string"?_.push(t`${t.identifier("__partition__")} = ${r.partitionKey}`):R&&_.push(t`${t.identifier("__partition__")} = ${J(i.partitionBy??[],R)}`);const T=X(r),k=Z(T,d,i.sortBy);k&&_.push(k);const I=t.identifier(m),A=t.identifier("__partition__"),L=_.length>0?t` WHERE ${t.join(_,t` AND `)}`:t``,M=d.length>0?t`${I}, ${A}, ${t.join(d.map(u=>t.identifier(u)),t`, `)}`:t`${I}, ${A}`,D=t`SELECT ${M} FROM ${t.identifier(l)}${L} ORDER BY ${t.join(h,t`, `)} LIMIT ${t.raw(String($+1))}`,y=B(n.sql,D).toArray(),g=y.length>$,E=g?y.slice(0,$):y,K=E.map(u=>u[m]),b=U(E,nt(n,o,K),d),P=g?Q(E.at(-1),d):C,j=i.sortBy.map(u=>u.direction==="desc"?"desc":"asc");return{continueCursor:P,directions:j,hasMore:g,rows:b}};export{pt as computeRankPage,nt as hydrateDocsById};
@@ -1 +1 @@
1
- import{w as C,W as R,B as S}from"./ctx-db-companions-BTi8DLUl.mjs";import"@lunora/errors";import"drizzle-orm";import"./AGGREGATE_SQL_FUNCTION-CTo0-9iZ.mjs";import"./aggregateTableName-DgYMC5tr.mjs";import"./runDrizzle-B6rnz3so.mjs";import"./do-sql-1Yi1_Yq0.mjs";import"./param-B5lF5Jd9.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,S as rankColumnsSql};
1
+ import{S as C,W as R,B as f}from"./ctx-db-companions-D2ZMFBrP.mjs";import"@lunora/errors";import"drizzle-orm";import"./AGGREGATE_SQL_FUNCTION-CTo0-9iZ.mjs";import"./aggregateTableName-DgYMC5tr.mjs";import"./runDrizzle-CgYGDEeB.mjs";import"./do-sql-Cg_QiQYA.mjs";import"./param-C68MV3DD.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};
@@ -0,0 +1 @@
1
+ import"@lunora/errors";import{sql as e}from"drizzle-orm";import{matchesStaticWhere as P,aggregateSqlFunction as de}from"./AGGREGATE_SQL_FUNCTION-CTo0-9iZ.mjs";import{encodeAggregateKey as N,foldAggregateTally as V,coerceAggregateNumber as F,aggregateTableName as G}from"./aggregateTableName-DgYMC5tr.mjs";import{runDrizzle as u}from"./runDrizzle-CgYGDEeB.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-Cg_QiQYA.mjs";import{param as ue,WORKERD_SQLITE_LIMITS as $e}from"./param-C68MV3DD.mjs";import{encodeGeohash as me,GEO_DEFAULT_PRECISION as Ee}from"./GEO_DEFAULT_PRECISION-DyI5zggj.mjs";import{isLiveForCompanion as J}from"./applySelect-UY-o13Ia.mjs";import{encodePartitionKey as he,sortColumnName as pe,matchesRankStaticWhere as Y,rankTableName as Z}from"./RANK_TIEBREAK-DDtST3gN.mjs";import{y as ge}from"./sql-projection-jfoe331H.mjs";import{serializeSqlValue as ee}from"./serializeSqlValue-BR4UOWoP.mjs";const _e=["de","en","es","fr","it","nl","none","pt"],ye=o=>_e.includes(o),be="a an and are as at be but by for if in into is it no not of on or such that the their then there these they this to was will with",Se="aber als am an auch auf aus bei bin bis bist da dass der den des dem die das denn dir du ein eine für hat ich im in ist mit nicht noch nur oder sich sie sind über und von vor war wie wir zu zum zur",Te="a al como con de del el en es la las lo los mas no o para pero por que se su sus un una uno y ya",ve="au aux avec ce ces dans de des du elle en et eux il je la le les leur lui ma mais me même mes moi mon ne nos notre nous on ou par pas pour qu que qui sa se ses son sur ta te tes toi ton tu un une vos votre vous y",we="a ai al alla anche che chi ci coi col come con da dal degli dei del della di do e ed gli ha hai hanno i il in la le lo ma mi ne nei nel non o per più quale quanto se si sono su sul tra un una uno vi",Ae="aan al als bij dan dat de der deze die dit door een en er het hij ij in is je kan me men met mij na naar niet nog nu of om ons ook op over te tot uit van voor was wat we wij zij zijn zo",Re="a ao aos as até com como da das de do dos e em entre era essa esse esta este eu foi há isso já mais mas me mesmo meu na nas no nos num numa o os ou para pela pelo por qual que quem se sem seu só sua também te tem um uma você",Le=/[\u0300-\u036F]/gu,ne=o=>o.normalize("NFD").replaceAll(Le,"").normalize("NFC").toLowerCase(),O=o=>new Set(ne(o).split(" ")),Ie={de:O(Se),en:O(be),es:O(Te),fr:O(ve),it:O(we),nl:O(Ae),none:new Set,pt:O(Re)},Ne=2,Oe=256,Q=new Map,je=o=>{const a=o!==void 0&&ye(o)?o:"none",l=Q.get(a);if(l)return l;const g=Ie[a],w=r=>{const A=(ne(r).match(/[\p{L}\p{N}]+/gu)??[]).filter(T=>T.length<=Oe);return g.size===0?A:A.filter(T=>!g.has(T))},m={document:w,profile:`${a}-v${String(Ne)}`,query:r=>{const A=w(r);return A.filter((T,L)=>A.lastIndexOf(T)===L)}};return Q.set(a,m),m},xe=(o,a)=>{if(!a.includes("."))return o[a];let l=o;for(const g of a.split(".")){if(l===null||typeof l!="object"||Array.isArray(l))return;l=l[g]}return l},Fe=(o,a)=>`${o}__fts_${a}`,Ce="__text__",X="__id__",Me=1e3,De=(o,a)=>a.document(o),q=(o,a)=>xe(o,a),ke=o=>typeof o=="string"?o:o==null?"":typeof o=="number"||typeof o=="bigint"||typeof o=="boolean"?String(o):JSON.stringify(o)??"",qe=(o,a,l)=>o!==void 0&&a!==void 0&&q(o,l.field)===q(a,l.field),ze=(o,a)=>De(ke(q(o,a.field)),je(a.language)).slice(0,Me).join(" "),We=(o,a,l)=>[...o.partitionBy??[],...o.sortBy.map(g=>g.field),...o.where?Object.keys(o.where):[]].every(g=>a[g]===l[g]),oe=o=>e.join(["__id__","__partition__",...o.sortBy.map((a,l)=>pe(l))].map(a=>e.identifier(a)),e`, `),te=(o,a,l,g,w,m)=>{const r=he(l.partitionBy??[],m),A=l.sortBy.map(L=>ee(m[L.field]??null)),T=e.join([w,r,...A].map(L=>ue(L)),e`, `);u(o,e`INSERT INTO ${e.identifier(a)} (${g}) VALUES (${T})`)},Be=(o,a,l,g,w,m)=>{if(w&&m&&We(l,w,m))return;const r=Z(a,l.name);w&&u(o,e`DELETE FROM ${e.identifier(r)} WHERE ${e.identifier("__id__")} = ${g}`),!(!m||l.where&&!Y(m,l.where))&&te(o,r,l,oe(l),g,m)},nn=o=>{const{broadcast:a,indexKeysFor:l,invalidateCache:g,recordCdc:w,schema:m,sql:r}=o,A=new Set,T=t=>m.tables[t]?.softDeleteMode?.field,L=new Set,z=(t,n)=>{const s=`${t}::${n.name}`;if(A.has(s))return;const d=G(t,n.name),c=n.by??[],f=T(t),h=new Map,y=u(r,e`SELECT id, _creationTime, ${e.identifier(M)} FROM ${e.identifier(t)}`).toArray();for(const v of y){const $=D(v);if(!$||!J($,f)||n.where&&!P($,n.where))continue;const E=N(c,$);V(h,E,n,$)}u(r,e`DELETE FROM ${e.identifier(d)}`);const R=Math.floor($e.boundParams/3),I=[...h];for(let v=0;v<I.length;v+=R){const $=I.slice(v,v+R),E=e.join($.map(([i,p])=>e`(${i}, ${p.value}, ${p.count})`),e`, `);u(r,e`INSERT INTO ${e.identifier(d)} (${j}, ${S}, ${_}) VALUES ${E}`)}A.add(s)},ie=(t,n,s)=>{const d=n.by??[],c=n.field??"",f=[],h=(E,i)=>{const p=ee(i);p===null?f.push(e`${k(E)} IS NULL`):f.push(e`${k(E)} = ${p}`)};for(const E of d)h(E,s[E]??null);const y=T(t);y!==void 0&&h(y,null);for(const[E,i]of Object.entries(n.where??{}))h(E,i!==null&&typeof i=="object"&&!Array.isArray(i)?i.eq:i);const R=f.length>0?e` WHERE ${e.join(f,e` AND `)}`:e``,I=m.tables[t]?.shape[c];if(I&&ge(I)){const E=u(r,e`SELECT id, _creationTime, ${e.identifier(M)} FROM ${e.identifier(t)}${R}`).toArray(),i=new Map;for(const p of E){const b=D(p);b&&V(i,"",n,b)}return{value:i.get("")?.value??null}}const v=de(n.op),$=k(c);return{value:u(r,e`SELECT ${e.raw(v)}(${$}) AS value FROM ${e.identifier(t)}${R}`).one().value??null}},re=(t,n,s,d)=>{const c=G(t,n.name),{op:f}=n,h=n.field??"",y=i=>{u(r,e`DELETE FROM ${e.identifier(c)} WHERE ${j} = ${i} AND ${_} <= 0`)},R=T(t),I=i=>!n.where||P(i,n.where),v=i=>J(i,R)&&I(i);d!==void 0&&f!=="count"&&I(d)&&F(d[h]);const $=s&&v(s)?s:void 0,E=d&&v(d)?d:void 0;if(!(!$&&!E)){if(f==="count"){for(const[i,p]of[[$,-1],[E,1]]){if(!i)continue;const b=N(n.by??[],i);u(r,C(c,b,p,p,e`${S} = ${S} + excluded.${S}, ${_} = ${_} + excluded.${_}`))}$&&y(N(n.by??[],$));return}if(f==="sum"||f==="avg"){for(const[i,p]of[[$,-1],[E,1]]){if(!i)continue;const b=F(i[h]);if(b===void 0)continue;const x=N(n.by??[],i);u(r,C(c,x,p*b,p,e`${S} = COALESCE(${S}, 0) + excluded.${S}, ${_} = ${_} + excluded.${_}`))}$&&y(N(n.by??[],$));return}if($){const i=N(n.by??[],$),p=F($[h]),b=u(r,e`SELECT ${S} AS value, ${_} AS count FROM ${e.identifier(c)} WHERE ${j} = ${i}`).toArray()[0],x=(b?.count??0)-1;if(x<=0)u(r,e`DELETE FROM ${e.identifier(c)} WHERE ${j} = ${i}`);else if(b&&p!==void 0&&b.value!==null&&p===b.value){const le=ie(t,n,$);u(r,e`UPDATE ${e.identifier(c)} SET ${S} = ${le.value}, ${_} = ${x} WHERE ${j} = ${i}`)}else u(r,e`UPDATE ${e.identifier(c)} SET ${_} = ${_} - 1 WHERE ${j} = ${i}`)}if(E){const i=N(n.by??[],E),p=F(E[h]);if(p===void 0)u(r,C(c,i,null,1,e`${_} = ${_} + 1`));else{const b=f==="min"?"MIN":"MAX";u(r,C(c,i,p,1,e`${S} = ${e.raw(b)}(COALESCE(${S}, excluded.${S}), excluded.${S}), ${_} = ${_} + 1`))}}}},ae=t=>{for(const n of m.tables[t]?.aggregateIndexes??[])z(t,n)},W=(t,n,s)=>{for(const d of m.tables[t]?.aggregateIndexes??[])re(t,d,n,s)},B=(t,n)=>{const s=`${t}::rank::${n.name}`;if(L.has(s))return;const d=Z(t,n.name),c=u(r,e`SELECT id, _creationTime, ${e.identifier(M)} FROM ${e.identifier(t)}`).toArray();u(r,e`DELETE FROM ${e.identifier(d)}`);const f=oe(n);for(const h of c){const y=D(h);!y||n.where&&!Y(y,n.where)||te(r,d,n,f,y._id,y)}L.add(s)},se=t=>{for(const n of m.tables[t]?.rankIndexes??[])B(t,n)},H=(t,n,s,d)=>{for(const c of m.tables[t]?.rankIndexes??[])Be(r,t,c,n,s,d)},U=(t,n,s,d)=>{const c=m.tables[t]?.searchIndexes??[];if(!(c.length===0||!ce(r)))for(const f of c){if(qe(d,s,f))continue;const h=Fe(t,f.name);u(r,e`DELETE FROM ${e.identifier(h)} WHERE ${e.identifier(X)} = ${n}`),s&&u(r,e`INSERT INTO ${e.identifier(h)} (${e.identifier(Ce)}, ${e.identifier(X)}) VALUES (${ze(s,f)}, ${n})`)}},K=(t,n,s)=>{for(const d of m.tables[t]?.geoIndexes??[]){const c=fe(t,d.name);u(r,e`DELETE FROM ${e.identifier(c)} WHERE ${e.identifier("__id__")} = ${n}`);const f=s?.[d.field];if(f!==null&&typeof f=="object"&&typeof f.lat=="number"&&typeof f.lng=="number"){const{lat:h,lng:y}=f,R=me({lat:h,lng:y},d.precision??Ee);u(r,e`INSERT INTO ${e.identifier(c)} (${e.identifier("__id__")}, ${e.identifier("__geohash__")}, ${e.identifier("__lat__")}, ${e.identifier("__lng__")}) VALUES (${n}, ${R}, ${h}, ${y})`)}}};return{ensureBackfilledForTable:ae,ensureBackfilledIndex:z,ensureRankBackfilled:B,ensureRankBackfilledForTable:se,syncAggregates:W,syncCompanionsForInsert:(t,n,s)=>{U(t,n,s),K(t,n,s),W(t,void 0,s),H(t,n,void 0,s),g(t,n,s),w(t,n,"insert",s),a({indexKeys:l(t,s),key:n,op:"insert",row:s,table:t})},syncGeo:K,syncRanks:H,syncSearch:U}};export{oe as B,nn as S,X as T,te as W,Fe as c,Ce as l,De as n,je as x,ze as y};
@@ -1 +1 @@
1
- import{createShardCtxDb as b}from"./NotUniqueError-CVHdtVw6.mjs";import{createRelayLink as I}from"./DEFAULT_MAX_RELAYS-B19vrJxP.mjs";import{ConflictError as N}from"./ConflictError-C8GtJmjS.mjs";import{runShardMigrations as v}from"./runShardMigrations-BqO6HPtX.mjs";import{relayName as q}from"./DEFAULT_PROMOTION_THRESHOLDS-B2rUe1bg.mjs";const C=(_,m={})=>({_meta:{column:{notNull:!0,...m}},kind:_}),D=(_,m,E)=>{const{describe:k,expect:i,it:f}=E;k(`engine contract: ${_}`,()=>{k("optimistic concurrency",()=>{const g=p=>({tables:{items:{indexes:[],shape:{title:C("string"),version:C("number",{notNull:!1})},triggerMap:{clobber:{handler:()=>{p.exec(`UPDATE "items" SET "__doc__" = json_set("__doc__", '$.version', 99) WHERE "id" = 'i1'`)},op:"update",timing:"before"}}}}});f("raises a CONFLICT of kind `occ` when a write's snapshot is clobbered",async()=>{const{close:p,host:d}=m();try{const c=d.sql,l=g(c);v(c,l);const s=b({schema:l,sql:c});await s.insert("items",{_id:"i1",title:"first",version:1},{allowExplicitId:!0}),await i(s.patch("i1",{title:"second"})).rejects.toBeInstanceOf(N)}finally{p?.()}}),f("reports the conflict as CONFLICT/409 rather than retrying it away",async()=>{const{close:p,host:d}=m();try{const c=d.sql,l=g(c);v(c,l);const s=b({schema:l,sql:c});await s.insert("items",{_id:"i1",title:"first",version:1},{allowExplicitId:!0});let r;try{await s.patch("i1",{title:"second"})}catch(t){r=t}const e=r;i(e.code).toBe("CONFLICT"),i(e.kind).toBe("occ")}finally{p?.()}}),f("leaves the row readable and unchanged after a conflict",async()=>{const{close:p,host:d}=m();try{const c=d.sql,l=g(c);v(c,l);const s=b({schema:l,sql:c});await s.insert("items",{_id:"i1",title:"first",version:1},{allowExplicitId:!0});try{await s.patch("i1",{title:"second"})}catch{}const r=await s.get("i1");i(r?.title).toBe("first"),i(r?.version).toBe(99)}finally{p?.()}}),f("raises a CONFLICT of kind `trigger` when a trigger writes its own row through the db",async()=>{const{close:p,host:d}=m();try{const c=d.sql,l={tables:{items:{indexes:[],shape:{title:C("string"),version:C("number",{notNull:!1})},triggerMap:{recurse:{handler:async(t,o)=>{await t.db.patch(o.doc._id,{version:99})},op:"update",timing:"before"}}}}};v(c,l);const s=b({schema:l,sql:c});await s.insert("items",{_id:"i1",title:"first",version:1},{allowExplicitId:!0});let r;try{await s.patch("i1",{title:"second"})}catch(t){r=t}const e=r;i(e).toBeInstanceOf(N),i(e.code).toBe("CONFLICT"),i(e.kind).toBe("trigger")}finally{p?.()}})}),k("shape-poke ordering",()=>{const g="shard-a",p={args:{},name:"messages"},d=(e,t,o,a)=>e.accept(t?.()??{},{connectionId:o,shapes:{[a]:p}}),c=(e,t)=>{let o=0,a=0;const n=u=>()=>{throw new Error(`the relay poke path must not reach RelayHost.${u}`)},h={fetch:(u,O)=>{if(JSON.parse(O?.body??"{}").type!=="relay_shape_subscribe")return Promise.resolve(new Response(void 0,{status:204}));const B=t[a];if(a+=1,B===void 0)throw new Error("the relay asked for more seeds than this fixture supplies");return Promise.resolve(Response.json(B))}},y={get:()=>h,getByName:()=>h,idFromName:u=>u},w={buildShapeDiff:n("buildShapeDiff"),computeOpLogShapeSeed:n("computeOpLogShapeSeed"),currentCdcEpoch:n("currentCdcEpoch"),deliverWhisperLocal:n("deliverWhisperLocal"),doName:()=>q(g,0),env:()=>({SHARD:y}),getWebSockets:()=>e.getSockets(),maskMetadata:n("maskMetadata"),nextPokeId:()=>(o+=1,`poke-${String(o)}`),readAttachment:u=>u.deserializeAttachment?.(),recordShapePokeFanout:()=>{},resolveShape:n("resolveShape"),rlsMetadata:n("rlsMetadata"),shardBinding:()=>"SHARD",sql:n("sql")},S=I(w);if(S===void 0)throw new Error("expected a relay link for a `…::relay::N` name");return S},l=e=>new Request("https://relay.internal/_lunora/relay",{body:JSON.stringify(e),headers:{"content-type":"application/json"},method:"POST"}),s=async(e,t,o)=>{const a=await e.seedRelayShape(t,o,p,{identity:void 0,userId:void 0});if(a!=="ok")throw new Error(`seed failed: ${JSON.stringify(a)}`)},r=(e={})=>l({...p,checkpoint:20,epoch:"e1",fromCursor:10,rowsPatch:[{id:"r1",op:"upsert",value:{title:"hello"}}],type:"relay_shape_poke",...e});f("frames a poke as pokeStart → pokePart per shape → pokeEnd, under one poke id",async()=>{const{close:e,createSocket:t,readFrames:o,sockets:a}=m();try{const n=c(a,[{cursor:10,epoch:"e1",frames:[]}]),h=d(a,t,"c-alice","s1");await s(n,h,"s1"),await n.handleControl(r());const y=(await o(h)).map(w=>JSON.parse(w));i(y.map(w=>w.type)).toStrictEqual(["pokeStart","pokePart","pokeEnd"]),i(new Set(y.map(w=>w.pokeId)).size).toBe(1),i(y[1]?.shapeId).toBe("s1"),i(y[2]?.checkpoint).toBe(20)}finally{e?.()}}),f("delivers a poke only to sockets whose cursor matches, and advances them past it",async()=>{const{close:e,createSocket:t,readFrames:o,sockets:a}=m();try{const n=c(a,[{cursor:10,epoch:"e1",frames:[]},{cursor:7,epoch:"e1",frames:[]}]),h=d(a,t,"c-alice","s1"),y=d(a,t,"c-bob","s2");await s(n,h,"s1"),await s(n,y,"s2"),await n.handleControl(r());const w=await o(h);i(w.length).toBe(3);const S=await o(y);i(S.length).toBe(0),await n.handleControl(r());const u=await o(h);i(u.length).toBe(3)}finally{e?.()}}),f("skips a socket whose cursor matches under a different CDC epoch",async()=>{const{close:e,createSocket:t,readFrames:o,sockets:a}=m();try{const n=c(a,[{cursor:10,epoch:"e1",frames:[]}]),h=d(a,t,"c-alice","s1");await s(n,h,"s1"),await n.handleControl(r({epoch:"e2"}));const y=await o(h);i(y.length).toBe(0),await n.handleControl(r());const w=await o(h);i(w.length).toBe(3)}finally{e?.()}})}),k("RLS identity under live subscription",()=>{const g="shard-a",p={args:{},name:"lobby-messages"},d={args:{},name:"my-orders"},c=s=>{const r=[],e=[],t={fetch:(a,n)=>(r.push(JSON.parse(n?.body??"{}")),Promise.resolve(new Response(void 0,{status:204})))},o=I({buildShapeDiff:()=>[{id:"r1",op:"upsert",value:{}}],computeOpLogShapeSeed:()=>({baseCheckpoint:void 0,cursor:10,epoch:"e1",rowsPatch:[]}),currentCdcEpoch:()=>"e1",deliverWhisperLocal:()=>0,doName:()=>g,env:()=>({SHARD:{get:()=>t,getByName:()=>t,idFromName:a=>a}}),getWebSockets:()=>[],maskMetadata:()=>({columns:[]}),nextPokeId:()=>"poke-1",readAttachment:()=>({}),recordShapePokeFanout:()=>{},resolveShape:(a,n,h)=>(e.push(h),a===d.name?{columns:["id"],effectiveWhere:{org:h?.identity?.org??"anonymous"},global:!1,table:"orders"}:{columns:["id"],effectiveWhere:{room:"lobby"},global:!1,table:"messages"}),rlsMetadata:()=>({policies:[]}),shardBinding:()=>"SHARD",sql:()=>s});if(o===void 0)throw new Error("expected an owner link for an un-suffixed DO name");return{owner:o,posts:r,resolvedUnder:e}},l=async(s,r)=>{await s.handleControl(new Request("https://owner.internal/_lunora/relay",{body:JSON.stringify({...r,connectionId:"c-alice",identity:{org:"acme"},relayIndex:0,subId:"s1",type:"relay_shape_subscribe",userId:"u1"}),headers:{"content-type":"application/json"},method:"POST"}))};f("seeds a subscriber under its own forwarded identity, never the anonymous one",async()=>{const{close:s,host:r}=m();try{const{owner:e,resolvedUnder:t}=c(r.sql);await l(e,d),i(t.some(o=>o?.userId==="u1"&&o.identity?.org==="acme")).toBe(!0)}finally{s?.()}}),f("routes an identity-scoped shape to a per-socket poke, not the cohort multicast",async()=>{const{close:s,host:r}=m();try{const{owner:e,posts:t}=c(r.sql);await l(e,d),t.length=0,await e.onFlush(new Set(["orders"]),20);const o=t.filter(a=>a.type==="relay_shape_poke");i(o.length).toBe(1),i(o[0]?.targetConnectionId).toBe("c-alice")}finally{s?.()}}),f("still multicasts an identity-blind shape to the whole cohort",async()=>{const{close:s,host:r}=m();try{const{owner:e,posts:t}=c(r.sql);await l(e,p),t.length=0,await e.onFlush(new Set(["messages"]),20);const o=t.filter(a=>a.type==="relay_shape_poke");i(o.length).toBe(1),i(o[0]?.targetConnectionId).toBeUndefined()}finally{s?.()}})})})};export{D as defineEngineContractSuite};
1
+ import{createShardCtxDb as b}from"./NotUniqueError-DJf3W9gG.mjs";import{createRelayLink as I}from"./DEFAULT_MAX_RELAYS-B19vrJxP.mjs";import{ConflictError as N}from"./ConflictError-C8GtJmjS.mjs";import{runShardMigrations as v}from"./runShardMigrations-CtlcSZ3r.mjs";import{relayName as q}from"./DEFAULT_PROMOTION_THRESHOLDS-B2rUe1bg.mjs";const C=(_,m={})=>({_meta:{column:{notNull:!0,...m}},kind:_}),D=(_,m,E)=>{const{describe:k,expect:i,it:f}=E;k(`engine contract: ${_}`,()=>{k("optimistic concurrency",()=>{const g=p=>({tables:{items:{indexes:[],shape:{title:C("string"),version:C("number",{notNull:!1})},triggerMap:{clobber:{handler:()=>{p.exec(`UPDATE "items" SET "__doc__" = json_set("__doc__", '$.version', 99) WHERE "id" = 'i1'`)},op:"update",timing:"before"}}}}});f("raises a CONFLICT of kind `occ` when a write's snapshot is clobbered",async()=>{const{close:p,host:d}=m();try{const c=d.sql,l=g(c);v(c,l);const s=b({schema:l,sql:c});await s.insert("items",{_id:"i1",title:"first",version:1},{allowExplicitId:!0}),await i(s.patch("i1",{title:"second"})).rejects.toBeInstanceOf(N)}finally{p?.()}}),f("reports the conflict as CONFLICT/409 rather than retrying it away",async()=>{const{close:p,host:d}=m();try{const c=d.sql,l=g(c);v(c,l);const s=b({schema:l,sql:c});await s.insert("items",{_id:"i1",title:"first",version:1},{allowExplicitId:!0});let r;try{await s.patch("i1",{title:"second"})}catch(t){r=t}const e=r;i(e.code).toBe("CONFLICT"),i(e.kind).toBe("occ")}finally{p?.()}}),f("leaves the row readable and unchanged after a conflict",async()=>{const{close:p,host:d}=m();try{const c=d.sql,l=g(c);v(c,l);const s=b({schema:l,sql:c});await s.insert("items",{_id:"i1",title:"first",version:1},{allowExplicitId:!0});try{await s.patch("i1",{title:"second"})}catch{}const r=await s.get("i1");i(r?.title).toBe("first"),i(r?.version).toBe(99)}finally{p?.()}}),f("raises a CONFLICT of kind `trigger` when a trigger writes its own row through the db",async()=>{const{close:p,host:d}=m();try{const c=d.sql,l={tables:{items:{indexes:[],shape:{title:C("string"),version:C("number",{notNull:!1})},triggerMap:{recurse:{handler:async(t,o)=>{await t.db.patch(o.doc._id,{version:99})},op:"update",timing:"before"}}}}};v(c,l);const s=b({schema:l,sql:c});await s.insert("items",{_id:"i1",title:"first",version:1},{allowExplicitId:!0});let r;try{await s.patch("i1",{title:"second"})}catch(t){r=t}const e=r;i(e).toBeInstanceOf(N),i(e.code).toBe("CONFLICT"),i(e.kind).toBe("trigger")}finally{p?.()}})}),k("shape-poke ordering",()=>{const g="shard-a",p={args:{},name:"messages"},d=(e,t,o,a)=>e.accept(t?.()??{},{connectionId:o,shapes:{[a]:p}}),c=(e,t)=>{let o=0,a=0;const n=u=>()=>{throw new Error(`the relay poke path must not reach RelayHost.${u}`)},h={fetch:(u,O)=>{if(JSON.parse(O?.body??"{}").type!=="relay_shape_subscribe")return Promise.resolve(new Response(void 0,{status:204}));const B=t[a];if(a+=1,B===void 0)throw new Error("the relay asked for more seeds than this fixture supplies");return Promise.resolve(Response.json(B))}},y={get:()=>h,getByName:()=>h,idFromName:u=>u},w={buildShapeDiff:n("buildShapeDiff"),computeOpLogShapeSeed:n("computeOpLogShapeSeed"),currentCdcEpoch:n("currentCdcEpoch"),deliverWhisperLocal:n("deliverWhisperLocal"),doName:()=>q(g,0),env:()=>({SHARD:y}),getWebSockets:()=>e.getSockets(),maskMetadata:n("maskMetadata"),nextPokeId:()=>(o+=1,`poke-${String(o)}`),readAttachment:u=>u.deserializeAttachment?.(),recordShapePokeFanout:()=>{},resolveShape:n("resolveShape"),rlsMetadata:n("rlsMetadata"),shardBinding:()=>"SHARD",sql:n("sql")},S=I(w);if(S===void 0)throw new Error("expected a relay link for a `…::relay::N` name");return S},l=e=>new Request("https://relay.internal/_lunora/relay",{body:JSON.stringify(e),headers:{"content-type":"application/json"},method:"POST"}),s=async(e,t,o)=>{const a=await e.seedRelayShape(t,o,p,{identity:void 0,userId:void 0});if(a!=="ok")throw new Error(`seed failed: ${JSON.stringify(a)}`)},r=(e={})=>l({...p,checkpoint:20,epoch:"e1",fromCursor:10,rowsPatch:[{id:"r1",op:"upsert",value:{title:"hello"}}],type:"relay_shape_poke",...e});f("frames a poke as pokeStart → pokePart per shape → pokeEnd, under one poke id",async()=>{const{close:e,createSocket:t,readFrames:o,sockets:a}=m();try{const n=c(a,[{cursor:10,epoch:"e1",frames:[]}]),h=d(a,t,"c-alice","s1");await s(n,h,"s1"),await n.handleControl(r());const y=(await o(h)).map(w=>JSON.parse(w));i(y.map(w=>w.type)).toStrictEqual(["pokeStart","pokePart","pokeEnd"]),i(new Set(y.map(w=>w.pokeId)).size).toBe(1),i(y[1]?.shapeId).toBe("s1"),i(y[2]?.checkpoint).toBe(20)}finally{e?.()}}),f("delivers a poke only to sockets whose cursor matches, and advances them past it",async()=>{const{close:e,createSocket:t,readFrames:o,sockets:a}=m();try{const n=c(a,[{cursor:10,epoch:"e1",frames:[]},{cursor:7,epoch:"e1",frames:[]}]),h=d(a,t,"c-alice","s1"),y=d(a,t,"c-bob","s2");await s(n,h,"s1"),await s(n,y,"s2"),await n.handleControl(r());const w=await o(h);i(w.length).toBe(3);const S=await o(y);i(S.length).toBe(0),await n.handleControl(r());const u=await o(h);i(u.length).toBe(3)}finally{e?.()}}),f("skips a socket whose cursor matches under a different CDC epoch",async()=>{const{close:e,createSocket:t,readFrames:o,sockets:a}=m();try{const n=c(a,[{cursor:10,epoch:"e1",frames:[]}]),h=d(a,t,"c-alice","s1");await s(n,h,"s1"),await n.handleControl(r({epoch:"e2"}));const y=await o(h);i(y.length).toBe(0),await n.handleControl(r());const w=await o(h);i(w.length).toBe(3)}finally{e?.()}})}),k("RLS identity under live subscription",()=>{const g="shard-a",p={args:{},name:"lobby-messages"},d={args:{},name:"my-orders"},c=s=>{const r=[],e=[],t={fetch:(a,n)=>(r.push(JSON.parse(n?.body??"{}")),Promise.resolve(new Response(void 0,{status:204})))},o=I({buildShapeDiff:()=>[{id:"r1",op:"upsert",value:{}}],computeOpLogShapeSeed:()=>({baseCheckpoint:void 0,cursor:10,epoch:"e1",rowsPatch:[]}),currentCdcEpoch:()=>"e1",deliverWhisperLocal:()=>0,doName:()=>g,env:()=>({SHARD:{get:()=>t,getByName:()=>t,idFromName:a=>a}}),getWebSockets:()=>[],maskMetadata:()=>({columns:[]}),nextPokeId:()=>"poke-1",readAttachment:()=>({}),recordShapePokeFanout:()=>{},resolveShape:(a,n,h)=>(e.push(h),a===d.name?{columns:["id"],effectiveWhere:{org:h?.identity?.org??"anonymous"},global:!1,table:"orders"}:{columns:["id"],effectiveWhere:{room:"lobby"},global:!1,table:"messages"}),rlsMetadata:()=>({policies:[]}),shardBinding:()=>"SHARD",sql:()=>s});if(o===void 0)throw new Error("expected an owner link for an un-suffixed DO name");return{owner:o,posts:r,resolvedUnder:e}},l=async(s,r)=>{await s.handleControl(new Request("https://owner.internal/_lunora/relay",{body:JSON.stringify({...r,connectionId:"c-alice",identity:{org:"acme"},relayIndex:0,subId:"s1",type:"relay_shape_subscribe",userId:"u1"}),headers:{"content-type":"application/json"},method:"POST"}))};f("seeds a subscriber under its own forwarded identity, never the anonymous one",async()=>{const{close:s,host:r}=m();try{const{owner:e,resolvedUnder:t}=c(r.sql);await l(e,d),i(t.some(o=>o?.userId==="u1"&&o.identity?.org==="acme")).toBe(!0)}finally{s?.()}}),f("routes an identity-scoped shape to a per-socket poke, not the cohort multicast",async()=>{const{close:s,host:r}=m();try{const{owner:e,posts:t}=c(r.sql);await l(e,d),t.length=0,await e.onFlush(new Set(["orders"]),20);const o=t.filter(a=>a.type==="relay_shape_poke");i(o.length).toBe(1),i(o[0]?.targetConnectionId).toBe("c-alice")}finally{s?.()}}),f("still multicasts an identity-blind shape to the whole cohort",async()=>{const{close:s,host:r}=m();try{const{owner:e,posts:t}=c(r.sql);await l(e,p),t.length=0,await e.onFlush(new Set(["messages"]),20);const o=t.filter(a=>a.type==="relay_shape_poke");i(o.length).toBe(1),i(o[0]?.targetConnectionId).toBeUndefined()}finally{s?.()}})})})};export{D as defineEngineContractSuite};
@@ -1 +1 @@
1
- import{LunoraError as c}from"@lunora/errors";import{sql as o}from"drizzle-orm";import{quoteIdentifier as m}from"./quoteIdentifier-CObIFRhb.mjs";import{s as u,a as p}from"./wire-codec-Dsy70M3Q.mjs";import{runDrizzle as _}from"./runDrizzle-B6rnz3so.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
+ import{LunoraError as c}from"@lunora/errors";import{sql as o}from"drizzle-orm";import{quoteIdentifier as m}from"./quoteIdentifier-CObIFRhb.mjs";import{s as u,a as p}from"./wire-codec-Dsy70M3Q.mjs";import{runDrizzle as _}from"./runDrizzle-CgYGDEeB.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-B6rnz3so.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-DcCENzpV.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(_)} (
1
+ import{LunoraError as E}from"@lunora/errors";import{sql as m}from"drizzle-orm";import{runDrizzle as h}from"./runDrizzle-CgYGDEeB.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-CUrDeD82.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-ZqcflEen.mjs";import{selectShapeRows as f}from"./selectShapeMemberIds-BdBcbrUP.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};
1
+ import{applyCdcChanges as m}from"./CDC_LOG_TABLE-CIfexI1y.mjs";import{selectShapeRows as f}from"./selectShapeMemberIds-EPo0xxs_.mjs";import{diffExternalSource as g,projectExternalSourceRow as c}from"./diffExternalSource-DMpkJta1.mjs";import{stableStringify as p}from"./stableStringify-BjLh4gvA.mjs";const x=async(t,s,r,e)=>{const{changes:n,nextBaseline:a}=g(s,r,e);return await m(t,n),{applied:n.length,nextBaseline:a}},E=async(t,s,r)=>{const{columns:e,deletedIds:n,table:a}=r,i=[];for(const u of s){const l=c(u,e),o=String(l._id);if(n?.has(o)){await t.get(o,a)&&i.push({id:o,op:"delete",seq:0,table:a,ts:0});continue}const d=await t.get(o,a);d&&p(c({...d,_id:o},e))===p(l)||i.push({doc:l,id:o,op:"insert",seq:0,table:a,ts:0})}return await m(t,i),{applied:i.length}},h=(t,s,r)=>{const e=new Map;for(const{doc:n,id:a}of f(t,s,void 0))e.set(a,p(c({...n,_id:a},r)));return e},R=async(t,s,r,e)=>{const n=h(t,e.table,e.columns);return x(s,r,n,e)};export{x as materializeExternalRows,E as materializeExternalRowsIncremental,h as readExternalSourceBaseline,R as runExternalSourceTick};
@@ -0,0 +1 @@
1
+ import{LunoraError as m}from"@lunora/errors";import{sql as r}from"drizzle-orm";import{MySqlDialect as c}from"drizzle-orm/mysql-core";import{PgDialect as u}from"drizzle-orm/pg-core";import{SQLiteSyncDialect as p}from"drizzle-orm/sqlite-core";const f=new u,d=new c,S=new p,h={mysql:d,postgres:f,sqlite:S},a={boundParams:100,compoundSelect:5,likePattern:50},g=a.boundParams/2,L=e=>e===null||typeof e=="boolean"?!0:typeof e=="number"?Number.isFinite(e):typeof e=="string"&&e.isWellFormed(),w=(e,t)=>{const{params:n,sql:o}=h[e].sqlToQuery(t);return{params:n,sql:o}},$=e=>r`${e}`,O=e=>{if(e.length===0)throw new Error("unionAll: expected at least one branch");let t=[...e];for(;t.length>a.compoundSelect;){const n=[];for(let o=0;o<t.length;o+=a.compoundSelect){const l=r.join(t.slice(o,o+a.compoundSelect),r` UNION ALL `);n.push(r`SELECT * FROM (${l}) ${r.identifier("__u__")}`)}t=n}return r.join(t,r` UNION ALL `)},I=(e,t,n,o=g)=>{const l=n?r` NOT IN `:r` IN `,s=t.every(i=>L(i));if(t.length>o&&!s)throw new m("BAD_REQUEST",`an "in" list of ${String(t.length)} values holds a value JSON cannot carry (bytes, a non-finite number, or malformed text), so it cannot be bound as one parameter — and ${String(t.length)} placeholders exceed SQLite's per-statement cap of 100 on Durable Objects and D1. Narrow the list to ${String(o)} values or fewer.`);return t.length<=o?r`${e}${l}(${r.join(t.map(i=>$(i)),r`, `)})`:r`${e}${l}(SELECT ${r.identifier("value")} FROM json_each(${JSON.stringify(t)}))`};export{a as WORKERD_SQLITE_LIMITS,$ as param,w as renderSql,I as sqliteInList,O as unionAll};
@@ -1 +1 @@
1
- import{renderSql as t}from"./param-B5lF5Jd9.mjs";const n=(r,e,...l)=>r.exec.call(r,e,...l),c=(r,e)=>{const{params:l,sql:o}=t("sqlite",e);return n(r,o,...l)},s=r=>r??null,a=r=>{if(!(r==null||r===""))try{return JSON.parse(r)}catch{return}};export{a as decodeJsonColumn,s as orNull,c as runDrizzle,n as runSql};
1
+ import{renderSql as t}from"./param-C68MV3DD.mjs";const n=(r,e,...l)=>r.exec.call(r,e,...l),c=(r,e)=>{const{params:l,sql:o}=t("sqlite",e);return n(r,o,...l)},s=r=>r??null,a=r=>{if(!(r==null||r===""))try{return JSON.parse(r)}catch{return}};export{a as decodeJsonColumn,s as orNull,c as runDrizzle,n as runSql};
@@ -1,4 +1,4 @@
1
- import{l as I,T as N,c as S}from"./ctx-db-companions-BTi8DLUl.mjs";import"@lunora/errors";import{sql as e}from"drizzle-orm";import{aggregateTableName as p}from"./aggregateTableName-DgYMC5tr.mjs";import{backfillSearchIndexesForTable as g}from"./backfillAggregateIndexes-DmqOHg0U.mjs";import{migrateCdcLog as h,migrateCdcMeta as l}from"./CDC_LOG_TABLE-ZqcflEen.mjs";import{migrateClientWatermark as R}from"./CLIENT_WATERMARK_TABLE-CzApRlyv.mjs";import{migrateGlobalShapeSnapshot as C}from"./GLOBAL_SHAPE_SNAPSHOT_TABLE-soMJDSBs.mjs";import{migrateIdempotency as O}from"./IDEMPOTENCY_TABLE-Bvu9JkiL.mjs";import{migrateSearchState as U}from"./SEARCH_STATE_TABLE-BZ_fxI5l.mjs";import{runDrizzle as a}from"./runDrizzle-B6rnz3so.mjs";import{a as u,N as E,y as _,I as X,C as b,c as x,p as B,T as c,h as F}from"./do-sql-1Yi1_Yq0.mjs";import{sortColumnName as M,rankTableName as Y}from"./RANK_TIEBREAK-DDtST3gN.mjs";import{recordSchemaVersion as D}from"./SCHEMA_HISTORY_MAX_VERSIONS-BEU0CuW5.mjs";const k=(r,t,o)=>{for(const i of o.indexes){const n=`${t}_${i.name}`,s=e.join(i.fields.map(f=>E(f)),e`, `);a(r,_(n,t,s,i.unique??!1))}for(const[i,n]of X(o)){if(!n.unique)continue;const s=`${t}_unique_${i}`;a(r,_(s,t,E(i),!0))}},y=(r,t,o)=>{if(!(!o.searchIndexes||o.searchIndexes.length===0||!b(r))){for(const i of o.searchIndexes){const n=S(t,i.name);a(r,e`CREATE VIRTUAL TABLE IF NOT EXISTS ${e.identifier(n)} USING fts5(${e.identifier(I)}, ${e.identifier(N)} UNINDEXED)`),a(r,e`CREATE VIRTUAL TABLE IF NOT EXISTS ${e.identifier(`${n}__vocab`)} USING fts5vocab(${e.identifier(n)}, ${e.raw("instance")})`)}g(r,t,o)}},j=(r,t,o)=>{if(o.geoIndexes)for(const i of o.geoIndexes){const n=F(t,i.name);a(r,e`CREATE TABLE IF NOT EXISTS ${e.identifier(n)} (${e.identifier("__id__")} TEXT PRIMARY KEY, ${e.identifier("__geohash__")} TEXT NOT NULL, ${e.identifier("__lat__")} REAL NOT NULL, ${e.identifier("__lng__")} REAL NOT NULL)`);const s=`${t}__geo_${i.name}__btree`;a(r,_(s,n,e`${e.identifier("__geohash__")} ASC, ${e.identifier("__id__")} ASC`,!1))}},q=(r,t,o)=>{if(o.aggregateIndexes)for(const i of o.aggregateIndexes){const n=p(t,i.name);a(r,e`CREATE TABLE IF NOT EXISTS ${e.identifier(n)} (${x} TEXT PRIMARY KEY, ${B} REAL, ${c} INTEGER NOT NULL DEFAULT 0)`),a(r,e`PRAGMA table_info(${e.identifier(n)})`).toArray().some(s=>s.name==="__count__")||a(r,e`ALTER TABLE ${e.identifier(n)} ADD COLUMN ${c} INTEGER NOT NULL DEFAULT 0`)}},G=(r,t,o)=>{if(o.rankIndexes)for(const i of o.rankIndexes){const n=Y(t,i.name),s=i.sortBy.map((T,d)=>M(d)),f=s.map(T=>e`${e.identifier(T)} BLOB`),$=f.length>0?e`, ${e.join(f,e`, `)}`:e``;a(r,e`CREATE TABLE IF NOT EXISTS ${e.identifier(n)} (${e.identifier("__id__")} TEXT PRIMARY KEY, ${e.identifier("__partition__")} TEXT NOT NULL${$})`);const m=[e`${e.identifier("__partition__")} ASC`];for(const[T,d]of s.entries()){const A=i.sortBy[T]?.direction;m.push(e`${e.identifier(d)} ${e.raw(A==="desc"?"DESC":"ASC")}`)}m.push(e`${e.identifier("__id__")} ASC`);const L=`${t}__rank_${i.name}__btree`;a(r,_(L,n,e.join(m,e`, `),!1))}},ne=(r,t,o={})=>{o.schemaSnapshot!==void 0&&D(r,o.schemaSnapshot.hash,o.schemaSnapshot.json),U(r);for(const[i,n]of Object.entries(t.tables))n.shardMode?.kind!=="global"&&(a(r,e`CREATE TABLE IF NOT EXISTS ${e.identifier(i)} (
1
+ import{l as I,T as N,c as S}from"./ctx-db-companions-D2ZMFBrP.mjs";import"@lunora/errors";import{sql as e}from"drizzle-orm";import{aggregateTableName as p}from"./aggregateTableName-DgYMC5tr.mjs";import{backfillSearchIndexesForTable as g}from"./backfillAggregateIndexes-Czk8MQ3M.mjs";import{migrateCdcLog as h,migrateCdcMeta as l}from"./CDC_LOG_TABLE-CIfexI1y.mjs";import{migrateClientWatermark as R}from"./CLIENT_WATERMARK_TABLE-BogWgD2Q.mjs";import{migrateGlobalShapeSnapshot as C}from"./GLOBAL_SHAPE_SNAPSHOT_TABLE-T5smo6RP.mjs";import{migrateIdempotency as O}from"./IDEMPOTENCY_TABLE-DPFwgQbE.mjs";import{migrateSearchState as U}from"./SEARCH_STATE_TABLE-MDlr30EJ.mjs";import{runDrizzle as a}from"./runDrizzle-CgYGDEeB.mjs";import{a as u,N as E,y as _,I as X,C as b,c as x,p as B,T as c,h as F}from"./do-sql-Cg_QiQYA.mjs";import{sortColumnName as M,rankTableName as Y}from"./RANK_TIEBREAK-DDtST3gN.mjs";import{recordSchemaVersion as D}from"./SCHEMA_HISTORY_MAX_VERSIONS-CGlXjXRT.mjs";const k=(r,t,o)=>{for(const i of o.indexes){const n=`${t}_${i.name}`,s=e.join(i.fields.map(f=>E(f)),e`, `);a(r,_(n,t,s,i.unique??!1))}for(const[i,n]of X(o)){if(!n.unique)continue;const s=`${t}_unique_${i}`;a(r,_(s,t,E(i),!0))}},y=(r,t,o)=>{if(!(!o.searchIndexes||o.searchIndexes.length===0||!b(r))){for(const i of o.searchIndexes){const n=S(t,i.name);a(r,e`CREATE VIRTUAL TABLE IF NOT EXISTS ${e.identifier(n)} USING fts5(${e.identifier(I)}, ${e.identifier(N)} UNINDEXED)`),a(r,e`CREATE VIRTUAL TABLE IF NOT EXISTS ${e.identifier(`${n}__vocab`)} USING fts5vocab(${e.identifier(n)}, ${e.raw("instance")})`)}g(r,t,o)}},j=(r,t,o)=>{if(o.geoIndexes)for(const i of o.geoIndexes){const n=F(t,i.name);a(r,e`CREATE TABLE IF NOT EXISTS ${e.identifier(n)} (${e.identifier("__id__")} TEXT PRIMARY KEY, ${e.identifier("__geohash__")} TEXT NOT NULL, ${e.identifier("__lat__")} REAL NOT NULL, ${e.identifier("__lng__")} REAL NOT NULL)`);const s=`${t}__geo_${i.name}__btree`;a(r,_(s,n,e`${e.identifier("__geohash__")} ASC, ${e.identifier("__id__")} ASC`,!1))}},q=(r,t,o)=>{if(o.aggregateIndexes)for(const i of o.aggregateIndexes){const n=p(t,i.name);a(r,e`CREATE TABLE IF NOT EXISTS ${e.identifier(n)} (${x} TEXT PRIMARY KEY, ${B} REAL, ${c} INTEGER NOT NULL DEFAULT 0)`),a(r,e`PRAGMA table_info(${e.identifier(n)})`).toArray().some(s=>s.name==="__count__")||a(r,e`ALTER TABLE ${e.identifier(n)} ADD COLUMN ${c} INTEGER NOT NULL DEFAULT 0`)}},G=(r,t,o)=>{if(o.rankIndexes)for(const i of o.rankIndexes){const n=Y(t,i.name),s=i.sortBy.map((T,d)=>M(d)),f=s.map(T=>e`${e.identifier(T)} BLOB`),$=f.length>0?e`, ${e.join(f,e`, `)}`:e``;a(r,e`CREATE TABLE IF NOT EXISTS ${e.identifier(n)} (${e.identifier("__id__")} TEXT PRIMARY KEY, ${e.identifier("__partition__")} TEXT NOT NULL${$})`);const m=[e`${e.identifier("__partition__")} ASC`];for(const[T,d]of s.entries()){const A=i.sortBy[T]?.direction;m.push(e`${e.identifier(d)} ${e.raw(A==="desc"?"DESC":"ASC")}`)}m.push(e`${e.identifier("__id__")} ASC`);const L=`${t}__rank_${i.name}__btree`;a(r,_(L,n,e.join(m,e`, `),!1))}},ne=(r,t,o={})=>{o.schemaSnapshot!==void 0&&D(r,o.schemaSnapshot.hash,o.schemaSnapshot.json),U(r);for(const[i,n]of Object.entries(t.tables))n.shardMode?.kind!=="global"&&(a(r,e`CREATE TABLE IF NOT EXISTS ${e.identifier(i)} (
2
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-B6rnz3so.mjs";import{N as r}from"./do-sql-1Yi1_Yq0.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};
1
+ import{sql as e}from"drizzle-orm";import{runDrizzle as $}from"./runDrizzle-CgYGDEeB.mjs";import{N as r}from"./do-sql-Cg_QiQYA.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};
@@ -0,0 +1 @@
1
+ import{sql as e}from"drizzle-orm";import{runDrizzle as m}from"./runDrizzle-CgYGDEeB.mjs";import{a as c,E as a,N as u}from"./do-sql-Cg_QiQYA.mjs";import{sqliteInList as h}from"./param-C68MV3DD.mjs";import{compileWhereSql as S}from"./compileWhereSql-DxD5mzDy.mjs";import{serializeSqlValue as E}from"./serializeSqlValue-BR4UOWoP.mjs";const $={fieldRef:u,serialize:E},R=i=>{if(i.length!==0)return h(e`${e.identifier("id")}`,i,!1)},p=(i,o)=>{const r=[];o&&r.push(o);const t=S(i,$);return t&&r.push(t),r.length===0?e``:e` WHERE ${e.join(r,e` AND `)}`},L=(i,o,r)=>{const t=p(r,void 0),f=m(i,e`SELECT id, _creationTime, ${e.identifier(c)} FROM ${e.identifier(o)}${t}`).toArray(),n=[];for(const s of f){const d=a(s),{id:l}=s;d!==void 0&&typeof l=="string"&&n.push({doc:d,id:l})}return n},M=(i,o,r,t)=>{if(t.length===0)return new Set;const f=p(r,R(t)),n=m(i,e`SELECT id FROM ${e.identifier(o)}${f}`).toArray();return new Set(n.map(s=>s.id))};export{M as selectShapeMemberIds,L as selectShapeRows};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@lunora/shard-engine",
3
- "version": "1.0.0-alpha.22",
3
+ "version": "1.0.0-alpha.23",
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{LunoraError as T}from"@lunora/errors";import{j as L,s as O}from"./do-sql-1Yi1_Yq0.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"},U=50,f=500,D=30,q=200,m="__doc__",k=e=>{try{const t=JSON.parse(e);return t!==null&&typeof t=="object"&&!Array.isArray(t)?t:void 0}catch{return}},W=e=>{const{[O]:t,...a}=e;return t===void 0?a:t===null||typeof t!="object"||Array.isArray(t)?{[O]: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],i=typeof _=="string"?k(_):void 0;if(i===void 0)return{columns:e,rows:t};const u=Object.fromEntries(Object.entries(s).filter(([l])=>l!==m));a.push({...u,...W(i)})}const r=e.filter(s=>s!==m),n=[],o=new Set(r);for(const s of a)for(const _ of Object.keys(s))o.has(_)||(o.add(_),n.push(_));return{columns:[...r,...n],rows:a}},R=e=>e.replaceAll(/[\\%_]/g,t=>`\\${t}`),E=e=>e.startsWith("sqlite_")||e.startsWith("_cf_")||e.startsWith("__miniflare")||e.startsWith("__lunora")||e.includes("__fts_"),I=(e,t,a)=>Math.min(Math.max(e,t),a),w=(e,t)=>{const a=e.exec(`SELECT COUNT(*) AS c FROM ${t}`).one();return Number(a.c)},ne=e=>{const t=e.exec("SELECT name FROM sqlite_master WHERE type = 'table' ORDER BY name").toArray(),a=[];for(const{name:r}of t)E(r)||a.push({name:r,rowCount:w(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,A=(e,t)=>{if(E(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:n}=a;return e.operator==="contains"?{params:[...n,`%${R(B(e.value))}%`],sql:String.raw`CAST(${r} AS TEXT) LIKE ? ESCAPE '\'`}:{params:[...n,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]),n=t[3]===void 0?void 0:Number(t[3]);if(r!==void 0&&(r<1||r>12)||n!==void 0&&(n<1||n>31)||a<100)return;const o=Date.UTC(a,(r??1)-1,n??1);if(n!==void 0&&new Date(o).getUTCDate()!==n)return;let s;return n!==void 0?s=Date.UTC(a,(r??1)-1,n+1):r===void 0?s=Date.UTC(a+1,0,1):s=Date.UTC(a,r,1),{from:o,to:s}},C=(e,t,a)=>{const r=[],n=[];if(t!==""&&e.length>0){const o=`%${R(t)}%`,s=e.map(i=>String.raw`CAST(${d(i)} AS TEXT) LIKE ? ESCAPE '\'`);n.push(...e.map(()=>o));const _=X(t);if(_!==void 0)for(const i of e)s.push(`(${d(i)} >= ? AND ${d(i)} < ?)`),n.push(_.from,_.to);r.push(`(${s.join(" OR ")})`)}for(const o of a??[]){const s=H(o,e);s!==void 0&&(r.push(`(${s.sql})`),n.push(...s.params))}return r.length===0?void 0:{parameters:n,where:r.join(" AND ")}},K=(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}`}},oe=(e,t)=>{const{table:a}=t;A(e,a);const r=I(Math.trunc(t.limit??U),1,f),n=Math.max(0,Math.trunc(t.offset??0)),o=d(a),s=b(e,o),_=t.search?.trim()??"",i=h=>{if(t.refs===void 0)return h;const S={};for(const $ of h.columns){const y=t.refs[$];y!==void 0&&(S[$]=y)}return Object.keys(S).length>0?{...h,refs:S}:h},u=C(s,_,t.filters),l=K(t.orderBy,s),c=u===void 0?"":` WHERE ${u.where}`,p=l===void 0?"":` ORDER BY ${l.sql}`,g=u?.parameters??[],N=l?.params??[];let v;t.skipCount||(v=u===void 0?w(e,o):Number(e.exec(`SELECT COUNT(*) AS c FROM ${o}${c}`,...g).one().c));const F=e.exec(`SELECT * FROM ${o}${c}${p} LIMIT ? OFFSET ?`,...g,...N,r,n).toArray();return i({...j(s,F),total:v})},_e=(e,t)=>{const{table:a}=t;A(e,a);const r=I(Math.trunc(t.limit??f),1,f),n=d(a),o=b(e,n),s=t.search?.trim()??"",_=C(o,s,t.filters),i=_===void 0?e.exec(`SELECT id FROM ${n} LIMIT ?`,r+1).toArray():e.exec(`SELECT id FROM ${n} WHERE ${_.where} LIMIT ?`,..._.parameters,r+1).toArray(),u=i.length>r,l=i.slice(0,r).map(c=>c.id);return{hasMore:u,ids:l}},Y=(e,t,a)=>{const r=new Set(a.filter(o=>o!==m));if(!a.includes(m))return r;const n=e.exec(`SELECT ${d(m)} AS doc FROM ${t} LIMIT ?`,f).toArray();for(const{doc:o}of n){const s=typeof o=="string"?k(o):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;A(e,r);const n=d(r),o=b(e,n);if(!Y(e,n,o).has(a))throw new T("UNKNOWN_COLUMN",`unknown column: ${a}`,{status:404});const s=M(a,o);if(s===void 0)throw new T("UNKNOWN_COLUMN",`unknown column: ${a}`,{status:404});const _=I(Math.trunc(t.limit??D),1,q),i=t.search?.trim()??"",u=C(o,i,t.filters),l=u===void 0?"":` WHERE ${u.where}`,c=u?.parameters??[],p=e.exec(`SELECT ${s.expression} AS value, COUNT(*) AS count FROM ${n}${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={},n=a.slice(0,f);for(const s of n)r[s]=[];if(n.length===0)return{references:r,storageColumns:t};const o=n.map(()=>"?").join(", ");for(const[s,_]of Object.entries(t)){if(E(s)||!x(e,s))continue;const i=d(s),u=b(e,i);for(const l of _){const c=M(l,u);if(c===void 0)continue;const p=e.exec(`SELECT id, ${c.expression} AS ref FROM ${i} WHERE ${c.expression} IN (${o})`,...c.params,...c.params,...n).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,n)=>{const o=Object.values(r.subs??{}).map(s=>({args:s.args,functionPath:s.functionPath,table:s.table}));return{admin:r.admin===!0,id:n,subscriptions:o}}),a=t.reduce((r,n)=>r+n.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 o of e){for(const s of Object.values(o.shapes??{})){const _=s.name??"(unknown shape)";a.set(_,(a.get(_)??0)+1)}for(const s of o.whispers??[])r.set(s,(r.get(s)??0)+1)}const n=[...[...a].map(([o,s])=>({kind:"shape",subscribers:s,topic:o})),...[...r].map(([o,s])=>({kind:"whisper",subscribers:s,topic:o}))];return n.sort((o,s)=>s.subscribers-o.subscribers||o.topic.localeCompare(s.topic)),{peakSubscribers:n[0]?.subscribers??0,topics:n.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,ne as listTables,oe as readTablePage,de as recordFanoutPass,_e as selectMatchingIds,me as summarizeFanoutTopics,le as summarizeSubscriptions};
@@ -1 +0,0 @@
1
- import{LunoraError as b}from"@lunora/errors";import{n as kt,w as Lt,x as je,T as Te,y as Dt,c as Ot}from"./ctx-db-companions-BTi8DLUl.mjs";import{sql as n}from"drizzle-orm";import{s as Ft}from"./wire-codec-Dsy70M3Q.mjs";import{aggregateSqlFunction as Se,normalizeCountArgument as Wt,throwingScheduler as Bt}from"./AGGREGATE_SQL_FUNCTION-CTo0-9iZ.mjs";import{encodeAggregateKey as Me,readAggregateValue as ke,aggregateTableName as Le}from"./aggregateTableName-DgYMC5tr.mjs";import{mergeWhere as Y,CountRlsUnsupportedError as De,selectIndexForGroupBy as qt,selectIndexForCount as Ut,selectIndexForAggregate as Pt}from"./CountRlsUnsupportedError-8BqPYQoP.mjs";import{backfillSearchIndexesForTable as jt}from"./backfillAggregateIndexes-DmqOHg0U.mjs";import{backfillAggregateIndexes as Ir,backfillRankIndexes as vr,backfillSearchIndexes as Cr}from"./backfillAggregateIndexes-DmqOHg0U.mjs";import{appendCdcChange as Ht}from"./CDC_LOG_TABLE-ZqcflEen.mjs";import{CDC_LOG_TABLE as kr,applyCdcChanges as Lr,bumpCdcEpoch as Dr,minCdcSeq as Or,readCdcChanges as Fr,readCdcCursor as Wr,readCdcEpoch as Br,trimCdcChanges as qr}from"./CDC_LOG_TABLE-ZqcflEen.mjs";import{computeRankPage as nt}from"./computeRankPage-QK8SeTZ-.mjs";import{SCAN_DEP as P}from"./SCAN_DEP-D_yR9EeV.mjs";import{runDrizzle as B}from"./runDrizzle-B6rnz3so.mjs";import{a as H,L as ae,p as _e,T as Oe,c as Re,N as V,E as le,I as Et,C as Qt,D as yt,h as Gt,O as rt}from"./do-sql-1Yi1_Yq0.mjs";import{coveringGeohashes as Kt,boundingBoxGeohashes as Yt,pointInBoundingBox as zt,haversineMeters as Vt}from"./GEO_DEFAULT_PRECISION-DyI5zggj.mjs";import{NotFoundError as Jt}from"./NotFoundError-BhF7FeFr.mjs";import{normalizeOrderKeys as Xt,buildSeekWhere as Nt,decodeCursor as qe,applySelect as it,encodeCursor as Ue,softDeleteScope as de,buildSeekBeforeWhere as Zt}from"./applySelect-UY-o13Ia.mjs";import{sortColumnName as ot,resolveRankPartition as en,encodePartitionKey as tn,RANK_TIEBREAK as nn,rankTableName as at}from"./RANK_TIEBREAK-DDtST3gN.mjs";import{indexKeysForRow as rn,buildIndexRange as on}from"./buildIndexRange-DFsdtPjD.mjs";import{assertFlatPredicate as Fe,resolveRelationPredicates as st}from"./DEFAULT_MAX_RELATION_KEYS-DjKka36Z.mjs";import{runRowValidators as We,resolveWith as dt,relationHooks as lt,applyOnDelete as an,fanOutScalarCounts as sn}from"./applyOnDelete-By23GK-k.mjs";import{guardWriter as dn}from"./RLS_UNWRAP_SYMBOL-DcqORh2s.mjs";import{f as ln}from"./sql-projection-jfoe331H.mjs";import{createSystemReader as cn}from"./createSystemReader-DcDcrtM3.mjs";import{ConflictError as he}from"./ConflictError-C8GtJmjS.mjs";import{runTriggers as un}from"./hasTrigger-CbkOHExZ.mjs";import{compileWhereSql as ne}from"./compileWhereSql-B4rPariq.mjs";import{CLIENT_WATERMARK_TABLE as Pr,advanceClientWatermark as jr,migrateClientWatermark as Hr,readClientWatermark as Qr}from"./CLIENT_WATERMARK_TABLE-CzApRlyv.mjs";import{GLOBAL_SHAPE_SNAPSHOT_TABLE as Kr,deleteGlobalShapeSnapshot as Yr,deleteGlobalShapeSnapshotsForConnection as zr,migrateGlobalShapeSnapshot as Vr,readGlobalShapeSnapshot as Jr,writeGlobalShapeSnapshot as Xr}from"./GLOBAL_SHAPE_SNAPSHOT_TABLE-soMJDSBs.mjs";import{IDEMPOTENCY_TABLE as ei,readIdempotent as ti,trimIdempotent as ni,writeIdempotent as ri}from"./IDEMPOTENCY_TABLE-Bvu9JkiL.mjs";import{runShardMigrations as oi}from"./runShardMigrations-BqO6HPtX.mjs";import{SEARCH_STATE_TABLE as si}from"./SEARCH_STATE_TABLE-BZ_fxI5l.mjs";import{selectShapeMemberIds as li,selectShapeRows as ci}from"./selectShapeMemberIds-BdBcbrUP.mjs";import{serializeSqlValue as oe}from"./serializeSqlValue-BR4UOWoP.mjs";import{quoteIdentifier as fn}from"./quoteIdentifier-CObIFRhb.mjs";const hn=i=>{const o=new TextEncoder().encode(i);let t="";for(const d of o)t+=String.fromCodePoint(d);return btoa(t)},pn=i=>{const o=atob(i),t=Uint8Array.from(o,d=>d.codePointAt(0)??0);return new TextDecoder().decode(t)},mn=()=>new b("BAD_REQUEST","invalid cursor"),ct=16,ut=8,J=1024,He=(i,o)=>o.query(i),$n=(i,o,t)=>{const d=kt(i,t);if(d.length===0)return 0;let c=0;for(const[p,$]of o.entries()){const A=p===o.length-1;let y=0;for(const g of d)(A?g.startsWith($):g===$)&&(y+=1);if(y===0)return 0;c+=y}return c},wn=(i,o)=>{if(!o)return{exact:!0,lower:i,upper:i};const t=[...i].at(-1)??"",d=(t.codePointAt(0)??0)+1;if(d>=55296&&d<=57343||d>1114111)return{exact:!0,lower:i,upper:i};const c=i.slice(0,i.length-t.length);return{exact:!1,lower:i,upper:c+String.fromCodePoint(d)}},gn=(i,o,t)=>{const d={eq:(c,p)=>{if(!i.definition.filterFields?.includes(c))throw new b("INTERNAL",`field "${c}" is not a filter field of search index "${i.indexName}" on table "${o}"`);if(i.filters.length>=ut)throw new b("BAD_REQUEST",`search index "${i.indexName}" on table "${o}": at most ${String(ut)} .eq() filters are supported per search query`);return i.filters.push({field:c,value:p}),d},search:(c,p)=>{const $=i;if(c!==$.definition.field)throw new b("INTERNAL",`search index "${$.indexName}" on table "${o}" indexes "${$.definition.field}", not "${c}"`);const A=He(p,t).length;if(A>ct)throw new b("BAD_REQUEST",`search index "${$.indexName}" on table "${o}": at most ${String(ct)} search terms are supported (got ${String(A)})`);return $.field=c,$.query=p,$.hasQuery=!0,d}};return d},bn=i=>{if(i.length>J)throw new b("BAD_REQUEST",`more than ${String(J)} documents match this search — narrow it with filters or read it a page at a time with .paginate()`)},En=i=>Math.min(i.offset+i.numItems+1,J),yn=i=>hn(`search:${String(i)}`),Nn=i=>{let o;try{o=pn(i)}catch{return}if(!o.startsWith("search:"))return;const t=Number(o.slice(7));return Number.isInteger(t)&&t>=0?t:void 0},Tn=i=>{if(typeof i.endCursor=="string")throw new b("BAD_REQUEST","bounded (endCursor) pagination is not supported on search queries — relevance order has no stable range boundary");const o=Math.max(0,Math.floor(i.numItems)),t=i.cursor?Nn(i.cursor):0;if(t===void 0)throw mn();if(t+o>J)throw new b("BAD_REQUEST",`search pagination reaches past the ${String(J)}-document limit (offset ${String(t)} + ${String(o)} requested) — narrow the query or the filters instead`);return{numItems:o,offset:t}},Sn=(i,o)=>{const t=o.offset+o.numItems,d=o.numItems>0&&i.length>t;return{continueCursor:d?yn(t):null,isDone:!d,page:i.slice(o.offset,t)}},_n=i=>{if(i===void 0)return J+1;if(!Number.isFinite(i))return J;const o=Math.max(0,Math.floor(i));if(o>J)throw new b("BAD_REQUEST",`search returns at most ${String(J)} documents (asked for ${String(o)}) — narrow the query or paginate instead`);return o},Rn=/^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/iu,An=i=>{if(!Rn.test(i))throw new b("INTERNAL",`invalid clientId ${JSON.stringify(i)}: a client-supplied row id must be a UUID`)},ft=50,Tt=500,xn=128,se=(i,o,t)=>{const d=o??Tt;if(i>d)throw new b("BATCH_LIMIT_EXCEEDED",`${t}: batch of ${String(i)} exceeds the limit of ${String(d)} (raise options.limit or chunk the call)`,{status:400})},In=i=>{const o={eq:(t,d)=>(i.sqlConditions.push({comparator:"=",field:t,value:d}),o),gt:(t,d)=>(i.sqlConditions.push({comparator:">",field:t,value:d}),o),gte:(t,d)=>(i.sqlConditions.push({comparator:">=",field:t,value:d}),o),lt:(t,d)=>(i.sqlConditions.push({comparator:"<",field:t,value:d}),o),lte:(t,d)=>(i.sqlConditions.push({comparator:"<=",field:t,value:d}),o)};return o},vn=i=>Math.max(i,J),St=(i,o)=>{const t=i.filters.map(d=>n`${V(d.field)} = ${oe(d.value)}`);return o&&t.push(o),t},Cn=(i,o,t,d,c)=>{const p=He(t.query,je(t.definition.language));if(p.length===0)return[];const $=Ot(o,t.indexName),A=`${$}__vocab`,y=p.length-1,g=p.map((D,k)=>{const Q=wn(D,k===y),W=Q.exact?n`${n.identifier("term")} = ${Q.lower}`:n`${n.identifier("term")} >= ${Q.lower} AND ${n.identifier("term")} < ${Q.upper}`;return n`SELECT ${n.identifier("doc")}, ${n.raw(String(k))} AS ${n.identifier("__term__")}, COUNT(*) AS ${n.identifier("__n__")} FROM ${n.identifier(A)} WHERE ${W} GROUP BY ${n.identifier("doc")}`}),N=p.map((D,k)=>n`SUM(CASE WHEN u.${n.identifier("__term__")} = ${n.raw(String(k))} THEN u.${n.identifier("__n__")} ELSE 0 END)`),T=n`SELECT f.${n.identifier(Te)} AS ${n.identifier(Te)}, ${n.join(N,n` + `)} AS ${n.identifier("__score__")} FROM (${n.join(g,n` UNION ALL `)}) u JOIN ${n.identifier($)} f ON f.rowid = u.${n.identifier("doc")} GROUP BY f.${n.identifier(Te)} HAVING ${n.join(N.map(D=>n`${D} > 0`),n` AND `)}`,_=St(t,c);let C=n`SELECT m.id, m._creationTime, m.${n.identifier(H)}, s.${n.identifier("__score__")} AS ${n.identifier("__score__")} FROM (${T}) s JOIN ${n.identifier(o)} m ON m.id = s.${n.identifier(Te)}`;_.length>0&&(C=n`${C} WHERE ${n.join(_,n` AND `)}`),C=n`${C} ORDER BY s.${n.identifier("__score__")} DESC, m._creationTime DESC, m.id ASC LIMIT ${n.raw(String(d))}`;const O=[];for(const D of B(i,C)){const k=yt(D);if(k){const Q=D.__score__;O.push({document:k,score:typeof Q=="number"?Q:Number(Q??0)})}}return O},Mn=(i,o,t,d,c)=>{const p=je(t.definition.language),$=He(t.query,p);if($.length===0)return[];const A=St(t,c);let y=n`SELECT id, _creationTime, ${n.identifier(H)} FROM ${n.identifier(o)}`;A.length>0&&(y=n`${y} WHERE ${n.join(A,n` AND `)}`),y=n`${y} ORDER BY _creationTime DESC, id ASC LIMIT ${n.raw(String(vn(d)))}`;const g=B(i,y).toArray(),N=[];for(const T of g){const _=yt(T);if(!_)continue;const C=$n(Dt(_,t.definition),$,p);C>0&&N.push({creationTime:typeof _._creationTime=="number"?_._creationTime:0,doc:_,id:typeof _._id=="string"?_._id:"",score:C})}return N.sort((T,_)=>_.score-T.score||_.creationTime-T.creationTime||T.id.localeCompare(_.id)),N.slice(0,d).map(T=>({document:T.doc,score:T.score}))},Be=(i,o,t,d)=>{if(!Number.isFinite(i.lat)||i.lat<-90||i.lat>90||!Number.isFinite(i.lng)||i.lng<-180||i.lng>180)throw new b("BAD_REQUEST",`geo index "${d}" on table "${t}": ${o} must have a finite lat in [-90, 90] and lng in [-180, 180]`)},kn=(i,o)=>{const t=i,d={near:(c,p)=>{if(t.within)throw new b("INTERNAL",`geo index "${t.indexName}" on table "${o}": call .near() or .within(), not both`);if(Be(c,".near() point",o,t.indexName),!Number.isFinite(p)||p<=0)throw new b("BAD_REQUEST",`geo index "${t.indexName}" on table "${o}": .near() radiusMeters must be a finite number > 0, got ${String(p)}`);return t.near={point:{lat:c.lat,lng:c.lng},radiusMeters:p},d},within:c=>{if(t.near)throw new b("INTERNAL",`geo index "${t.indexName}" on table "${o}": call .near() or .within(), not both`);if(Be(c.sw,".within() sw corner",o,t.indexName),Be(c.ne,".within() ne corner",o,t.indexName),c.sw.lat>c.ne.lat)throw new b("BAD_REQUEST",`geo index "${t.indexName}" on table "${o}": .within() corners are transposed (sw.lat > ne.lat)`);if(c.sw.lng>c.ne.lng)throw new b("BAD_REQUEST",`geo index "${t.indexName}" on table "${o}": .within() box crosses the antimeridian (sw.lng > ne.lng), which is not supported — split it into two boxes at ±180 and union the results`);return t.within={ne:{lat:c.ne.lat,lng:c.ne.lng},sw:{lat:c.sw.lat,lng:c.sw.lng}},d}};return d},Ln=(i,o)=>{const t=i[o];if(t===null||typeof t!="object")return;const{lat:d,lng:c}=t;return typeof d=="number"&&typeof c=="number"?{lat:d,lng:c}:void 0},Dn=(i,o)=>{const t=Ln(i,o.definition.field);if(!t)return;const d=typeof i._creationTime=="number"?i._creationTime:0;if(o.near){const c=Vt(o.near.point,t);return c<=o.near.radiusMeters?{creationTime:d,distance:c}:void 0}return zt(t,o.within)?{creationTime:d,distance:0}:void 0},On=(i,o,t,d)=>{if(!t.near&&!t.within)throw new b("INTERNAL",`geo index "${t.indexName}" on table "${o}": call .near(point, radius) or .within(box)`);const c=t.near?Kt(t.near.point,t.near.radiusMeters):Yt(t.within),p=Gt(o,t.indexName),$=c.map(T=>n`(g.${n.identifier("__geohash__")} >= ${T} AND g.${n.identifier("__geohash__")} < ${`${T}{`})`),A=[n`(${n.join($,n` OR `)})`];d&&A.push(d);const y=n`SELECT m.id, m._creationTime, m.${n.identifier(H)} FROM ${n.identifier(p)} g JOIN ${n.identifier(o)} m ON m.id = g.${n.identifier("__id__")} WHERE ${n.join(A,n` AND `)}`,g=B(i,y).toArray(),N=[];for(const T of g){const _=le(T),C=_?Dn(_,t):void 0;_&&C&&N.push({creationTime:C.creationTime,distance:C.distance,doc:_})}return N.sort((T,_)=>T.distance-_.distance||_.creationTime-T.creationTime),N},_t=(i,o,t,d)=>{const c=[];for(const p of i)if(o.every($=>$(d(p)))&&(c.push(p),typeof t=="number"&&c.length>=t))break;return c},Fn=(i,o,t,d,c,p=()=>{})=>{const $=t.within!==void 0,A=On(i,o,t,c).map(y=>({distanceMeters:$?null:y.distance,document:y.doc}));return p(A.length),typeof d=="number"?A.slice(0,Math.max(0,Math.floor(d))):A},Rt=(i,o,t,d,c,p=()=>{})=>{const{geo:$}=t;if(!$)throw new b("INTERNAL","runGeoTerminalScored called without a staged geo query");const A=t.inMemoryFilters.length>0,y=Fn(i,o,$,A?void 0:c,d,p);return A?_t(y,t.inMemoryFilters,c,g=>g.document):y},Wn=(i,o,t,d,c,p=()=>{})=>Rt(i,o,t,d,c,p).map($=>$.document),Bn=(i,o,t,d,c,p,$=()=>{})=>{const A=[];for(const T of t.sqlConditions)A.push(n`${V(T.field)} ${n.raw(T.comparator)} ${oe(T.value)}`);d&&A.push(d);let y=n`SELECT id, _creationTime, ${n.identifier(H)} FROM ${n.identifier(o)}`;A.length>0&&(y=n`${y} WHERE ${n.join(A,n` AND `)}`),y=n`${y} ORDER BY ${c}`,typeof p=="number"&&t.inMemoryFilters.length===0&&(y=n`${y} LIMIT ${n.raw(String(Math.max(0,Math.floor(p))))}`);const g=B(i,y).toArray();$(g.length);const N=[];for(const T of g){const _=le(T);if(_&&t.inMemoryFilters.every(C=>C(_))&&(N.push(_),typeof p=="number"&&N.length>=p))break}return N},ie={fieldRef:V,serialize:oe},At=(i,o)=>{const t=o===void 0?void 0:i.shape[o];return t!==void 0&&ln(t)},ht=(i,o)=>o.some(t=>At(i,t)),pt=(i,o,t)=>{if(At(i,o))throw new b("BAD_REQUEST",`${t}: "${o}" is stored as an order-preserving key, which SQL cannot reduce or group — declare an aggregateIndex covering this (by, field, op) so the maintained companion answers it`)},qn=i=>{let o=0;const t=[],d={fieldRef:V,relationExists:c=>{const{childWhere:p,negated:$,parentTable:A,relation:y}=c,g=`__rel_${String(o)}`,N=t.at(-1)??A;o+=1,i(y.table,P);const T=y.kind==="one"?y.field:y.references,_=y.kind==="one"?y.references:y.field,C=n`${rt(g,_)} = ${rt(N,T)}`;t.push(g);const O=ne(p,d);t.pop();const D=O?n`${C} AND ${O}`:C,k=n`EXISTS (SELECT 1 FROM ${n.identifier(y.table)} AS ${n.identifier(g)} WHERE ${D})`;return $?n`NOT ${k}`:k},serialize:oe};return d},xt=i=>{const o=i.map(t=>n`${V(t.field)} ${n.raw(t.direction==="desc"?"DESC":"ASC")}`);return i.some(t=>t.field==="_id"||t.field==="id")||o.push(n`${V("id")} ASC`),n.join(o,n`, `)},Un={"<":"lt","<=":"lte","=":"eq",">":"gt",">=":"gte"},Pn=i=>{const o=i.order;return i.indexFields.length>0?i.indexFields.map(t=>({direction:o,field:t})):[{direction:o,field:"_creationTime"}]},jn=(i,o,t,d)=>{const c=i.sqlConditions.map(p=>({[p.field]:{[Un[p.comparator]??"eq"]:p.value}}));if(t&&c.push(Nt(o,qe(t))),d&&c.push(Zt(o,qe(d))),c.length!==0)return c.length===1?c[0]:{AND:c}},Hn=(i,o,t)=>{const d=[];for(const c of i){const p=le(c);if(p&&o.every($=>$(p))&&(d.push(p),t!==void 0&&d.length>t))break}return d},Qn=(i,o,t,d,c,p=()=>{})=>{const $=Math.max(0,Math.floor(d.numItems)),A=Pn(t),y=typeof d.endCursor=="string",g=ne(jn(t,A,d.cursor,d.endCursor),ie),N=c&&g?n`${g} AND ${c}`:c??g;let T=n`SELECT id, _creationTime, ${n.identifier(H)} FROM ${n.identifier(o)}`;N&&(T=n`${T} WHERE ${N}`),T=n`${T} ORDER BY ${xt(A)}`;const _=t.inMemoryFilters.length>0;!_&&!y&&(T=n`${T} LIMIT ${n.raw(String($+1))}`);const C=B(i,T).toArray();p(C.length);const O=Hn(C,t.inMemoryFilters,_||y?void 0:$);if(y){const W=O.length>=2?O[Math.floor(O.length/2)-1]:void 0;return{continueCursor:d.endCursor??null,isDone:!0,page:O,splitCursor:W?Ue(W,A):null}}const D=O.length>$,k=D?O.slice(0,$):O,Q=k.at(-1);return{continueCursor:D&&Q?Ue(Q,A):null,isDone:!D,page:k}};class Gn extends b{constructor(o="unique() found more than one matching document"){super("NOT_UNIQUE",o,{name:"NotUniqueError"})}}const Kn=/\s/u,Yn=String.fromCodePoint(0),mt=(i,o,t)=>{if(!i.tables[o])throw new b("INTERNAL",`unknown table: ${o}`);return typeof t!="string"||t.length===0||Kn.test(t)||t.includes(Yn)?null:t},zn=(i,o,t,d=()=>{},c=()=>{},p=()=>{})=>{const $=o.tables[t];if(!$)throw new b("INTERNAL",`unknown table: ${t}`);const A=de($.softDeleteMode,void 0),y=A?ne(A,ie):void 0,g={indexFields:[],indexName:void 0,inMemoryFilters:[],order:"asc",sqlConditions:[]};let N=0;const T=E=>{const{search:v}=g;if(!v)throw new b("INTERNAL","runSearchFetch called without a staged search");jt(i,t,$);const I=g.inMemoryFilters.length>0,M=_n(I?void 0:E),G=Qt(i)?Cn(i,t,v,M,y):Mn(i,t,v,M,y);return I?(N=G.length,_t(G,g.inMemoryFilters,E,ee=>ee.document)):(E===void 0&&bn(G),G)},_=E=>T(E).map(v=>v.document),C=E=>{const v=Tn(E);return Sn(_(En(v)),v)},O=()=>{const E=g.indexFields.length>0?g.indexFields:["_creationTime"],v=g.order==="desc"?"DESC":"ASC";return n.join(E.map(I=>n`${V(I)} ${n.raw(v)}`),n`, `)},D=()=>{if(g.search||g.geo||g.indexName===void 0){c(void 0);return}c(on(t,g.indexName,g.indexFields,g.sqlConditions,oe))},k=E=>{D();let v=0;const I=(()=>{if(g.search){const M=_(E);return v=N,M}return g.geo?Wn(i,t,g,y,E,M=>{v=M}):Bn(i,t,g,y,O(),E,M=>{v=M})})();return p(Math.max(v,I.length)),I},Q=()=>{if(!g.search&&!g.geo)throw new b("INTERNAL",`ctx.db.query("${t}").collectWithScores() requires a staged .withSearchIndex(...) or .withGeoIndex(...)`);D();let E=0;const v=(()=>{if(g.search){const I=T(void 0);return E=N,I}return Rt(i,t,g,y,void 0,I=>{E=I})})();return p(Math.max(E,v.length)),v},W={async*[Symbol.asyncIterator](){const E=[...g.inMemoryFilters];let v;g.inMemoryFilters=[];try{for(;;){const I=await W.paginate({cursor:v??null,numItems:xn});for(const M of I.page)E.every(G=>G(M))&&(yield M);if(I.isDone||I.continueCursor===null)return;v=I.continueCursor}}finally{g.inMemoryFilters=E}},async collect(){return k(void 0)},async collectWithScores(){return Q()},filter(E){return g.inMemoryFilters.push(E),W},async first(){return k(g.inMemoryFilters.length>0?void 0:1)[0]??null},order(E){return g.order=E==="desc"?"desc":"asc",W},async paginate(E){let v=0;if(D(),g.search){const M=C(E);return p(M.page.length),M}if(g.geo)throw new b("INTERNAL","pagination is not supported on geo queries; use .take(n) or .collect()");const I=Qn(i,t,g,E,y,M=>{v=M});return p(Math.max(v,I.page.length)),I},async take(E){return k(E)},async unique(){const E=k(g.inMemoryFilters.length>0?void 0:2);if(E.length>1)throw new Gn(`unique() on table "${t}" matched ${String(E.length)} documents; expected at most one`);return E[0]??null},withGeoIndex(E,v){const I=($.geoIndexes??[]).find(G=>G.name===E);if(!I)throw new b("INTERNAL",`unknown geo index "${E}" on table "${t}"`);d(t,E,"geo");const M={definition:I,indexName:E};if(g.geo=M,v(kn(M,t)),!M.near&&!M.within)throw new b("INTERNAL",`geo index "${E}" on table "${t}" requires a .near(point, radius) or .within(box) call`);return W},withIndex(E,v){const I=$.indexes.find(M=>M.name===E);if(!I)throw new b("INTERNAL",`unknown index "${E}" on table "${t}"`);return d(t,E,"index"),g.indexName=E,g.indexFields=I.fields,v&&v(In(g)),W},withSearchIndex(E,v){const I=($.searchIndexes??[]).find(G=>G.name===E);if(!I)throw new b("INTERNAL",`unknown search index "${E}" on table "${t}"`);d(t,E,"search");const M={definition:I,field:I.field,filters:[],hasQuery:!1,indexName:E,query:""};if(g.search=M,v(gn(M,t,je(I.language))),!M.hasQuery)throw new b("INTERNAL",`search index "${E}" on table "${t}" requires a .search(field, query) call`);return W}};return W},$t=(i,o,t)=>{const d={...o};for(const[c,p]of Et(i)){if(p.serverDefault){d[c]=p.serverDefault({auth:t});continue}d[c]===void 0&&(p.defaultFn?d[c]=p.defaultFn():"defaultValue"in p&&(d[c]=p.defaultValue))}return d},wt=(i,o,t,d)=>{const c=t;for(const[p,$]of Et(i)){if($.serverDefault){p in o&&(c[p]=$.serverDefault({auth:d}));continue}$.onUpdateFn&&!(p in o)&&(c[p]=$.onUpdateFn())}},gt=(i,o)=>{for(const t of Object.keys(o))if(o[t]===void 0)throw new b("INTERNAL",`Cannot ${i} field '${t}' to undefined — use null to clear a nullable field, or omit the key to leave it unchanged.`)},Vn=/unique constraint failed/i,Jn=i=>i instanceof Error&&Vn.test(i.message),Pe=(i,o,t)=>{try{B(i,t)}catch(d){throw Jn(d)?new he(`unique constraint violation on "${o}"`,"unique"):d}},Ae=(i,o,t)=>{if(Pe(i,o,t),B(i,n`SELECT changes() AS changed`).one().changed===0)throw new he(`optimistic concurrency conflict on "${o}" — the row changed during this mutation; refetch and retry`,"occ")},bt=(i,o,t,d,c,p,$)=>{const A=[];for(let T=0;T<t.length+1;T+=1){const _=[];for(let k=0;k<T;k+=1)_.push(n`${n.identifier(t[k])} IS ${p[k]}`);const C=t[T],O=d[T];if(C!==void 0&&O!==void 0){const k=O.direction==="desc"?">":"<";_.push(n`${n.identifier(C)} ${n.raw(k)} ${p[T]}`)}else _.push(n`${n.identifier(nn)} < ${$}`);const[D]=_;A.push(_.length===1&&D!==void 0?D:n`(${n.join(_,n` AND `)})`)}const y=n.join(A,n` OR `),g=B(i,n`SELECT COUNT(*) AS c FROM ${n.identifier(o)} WHERE ${n.identifier("__partition__")} = ${c} AND (${y})`).one(),N=B(i,n`SELECT COUNT(*) AS c FROM ${n.identifier(o)} WHERE ${n.identifier("__partition__")} = ${c}`).one();return{before:g.c,total:N.c}},Rr=i=>{const{sql:o}=i,{schema:t}=i,d=i.broadcast??(()=>{}),c=(e,...r)=>{const a=t.tables[e]?.indexes;if(!a||a.length===0)return;const l=[];for(const h of r)h&&l.push(...rn(a,h,oe));return l.length>0?l:void 0},{headroom:p}=i;let $=!1;const A=async e=>{const r=$;$=!0;try{return await e()}finally{$=r}},y=i.onRead??(()=>{}),g=i.onReadRange??(e=>{y(e.table,P)}),N=(e,r)=>{r!==void 0&&r!==P&&!$&&p?.recordRead(1),y(e,r)},T=i.onIndexUse??(()=>{}),_=i.onWrite??(()=>{}),C=async e=>{$||p?.recordWrite(e.doc),await _(e)},{cache:O}=i,D=i.clock??(()=>Date.now()),k=i.idGenerator??(()=>crypto.randomUUID()),Q=i.scheduler??Bt,{globalDb:W}=i,E=i.auth??{identity:null,userId:null},v=i.cdc??!1,I=Q,M=cn({scheduler:typeof I.list=="function"&&typeof I.get=="function"?I:void 0,storage:i.storage}),G=(e,r,a,l)=>{v&&Ht(o,D(),e,r,a,l)},ee=e=>t.tables[e]?.shardMode?.kind==="global",Qe=(e,r)=>{if(ee(e)){if(!W)throw new b("INTERNAL",`cross-backend ${r} for global table '${e}' requires a globalDb writer — pass one to createShardCtxDb({ globalDb })`);return W}return q},xe=e=>Qe(e,"cascade"),z=(e,r)=>{if(ee(e)){if(!W)throw new b("INTERNAL",`${r} on global table '${e}' requires a globalDb writer — pass one to createShardCtxDb({ globalDb })`);return W}},Ie=(e,r)=>Qe(e,"relation load").findMany(e,r),Ge=(e,r)=>(ee(e)&&N(e,P),Ie(e,r)),It=e=>!ee(e.table),Ke=i.relationExistsPushDown??"auto",Ye=Ke!=="never",{maxRelationKeys:ze}=i,pe=(e,r,a)=>st(e,{fetcher:Ge,maxRelationKeys:ze,relationBaseWhere:a,schema:t,tableName:r}),Ve=async(e,r,a,l)=>{const h=z(e,"relation grouped count");if(h)return N(e,P),sn((j,x)=>h.count(j,x),e,r,a,l);const f=t.tables[e];if(!f)throw new b("INTERNAL",`unknown table: ${e}`);N(e,P);const s=de(f.softDeleteMode,void 0),u={[r]:{in:a}},m=Y(Y(u,l),s),S=await pe(m,e,void 0),w=ne(S,ie),R=V(r);let L=n`SELECT ${R} AS __fk__, COUNT(*) AS count FROM ${n.identifier(e)}`;w&&(L=n`${L} WHERE ${w}`),L=n`${L} GROUP BY ${R}`;const F=B(o,L).toArray();return new Map(F.map(j=>[j.__fk__,j.count]))};let me=0;const Je=new Set;for(const[e,r]of Object.entries(t.tables))for(const a of Object.values(r.triggerMap??{}))Je.add(`${e} ${a.timing} ${a.op}`);const X=(e,r,a)=>Je.has(`${e} ${r} ${a}`),Z=async(e,r,a)=>{if(me+=1,me>ft)throw me-=1,new he(`trigger recursion exceeded ${String(ft)} levels on "${a.table}" — check for a self-triggering write`,"trigger");try{await un({ctx:Ct,event:a,op:r,schema:t,tableName:a.table,timing:e})}finally{me-=1}},{ensureBackfilledForTable:ce,ensureBackfilledIndex:ve,ensureRankBackfilled:Ce,ensureRankBackfilledForTable:ue,syncAggregates:$e,syncCompanionsForInsert:Xe,syncGeo:we,syncRanks:fe,syncSearch:ge}=Lt({broadcast:d,indexKeysFor:(e,r)=>c(e,r),invalidateCache:(e,r,a)=>O?.invalidate(e,r,c(e,a)),recordCdc:G,schema:t,sql:o}),Ze=(e,r,a)=>{const{shardMode:l}=r;if(l?.kind==="shardBy"&&!(l.field!==void 0&&(a.partitionBy??[]).includes(l.field)))throw Object.assign(new Error(`rank index "${a.name}" on "${e}" partitions across shards (shard key "${l.field??"?"}" is not in partitionBy) — a shard-local rank()/rankPage() would be wrong; roll it up through the Query Coordinator instead`),{code:"CROSS_SHARD_RANK_UNSUPPORTED",name:"LunoraError",status:400})},et=e=>Object.entries(t.tables).filter(([,r])=>r.shardMode?.kind!=="global").map(([r])=>r).filter(r=>e===void 0||r===e),re=(e,r)=>{const a=et(r);if(a.length===0)return;const l=a.map(S=>n`SELECT ${n.raw(`'${S.replaceAll("'","''")}'`)} AS __t__, id, _creationTime, ${n.identifier(H)} FROM ${n.identifier(S)} WHERE id = ${e}`),h=n`${n.join(l,n` UNION ALL `)} LIMIT 1`,[f]=B(o,h).toArray();if(!f)return;const s=f.__t__,u=le(f);if(typeof s!="string"||!u)return;const m=f[H];return{docJson:typeof m=="string"?m:ae(m??{}),row:u,tableName:s}},vt=(e,r)=>{const a=[...new Set(e)],l=new Map;if(a.length===0)return l;const h=et(r);if(h.length===0)return l;const f=Math.max(1,Math.floor(900/h.length));for(let s=0;s<a.length;s+=f){const u=a.slice(s,s+f),m=n.join(u.map(R=>n`${R}`),n`, `),S=h.map(R=>n`SELECT ${n.raw(`'${R.replaceAll("'","''")}'`)} AS __t__, id FROM ${n.identifier(R)} WHERE id IN (${m})`),w=n.join(S,n` UNION ALL `);for(const R of B(o,w)){const{id:L,__t__:F}=R;typeof F=="string"&&typeof L=="string"&&l.set(L,F)}}return l},tt={assertRankPartitionLocal:Ze,ensureRankBackfilled:Ce,onRead:N,rowToDocument:le,schema:t,sql:o},q={system:M,async aggregate(e,r){const a=z(e,"aggregate");if(a)return N(e,P),a.aggregate(e,r);const l=t.tables[e];if(!l)throw new b("INTERNAL",`unknown table: ${e}`);if(Se(r.op),r.op==="count")return q.count(e,{baseWhere:r.baseWhere,relationBaseWhere:r.relationBaseWhere,restrictsCounts:r.restrictsCounts,where:r.where});if(!r.field)throw new b("INTERNAL",`aggregate(${e}, { op: "${r.op}" }): "field" is required for non-count reducers`);N(e,P);const h=de(l.softDeleteMode,void 0),f=Y(Y(r.baseWhere,r.where),h),s=await pe(f,e,r.relationBaseWhere),u=s!==f;if(l.aggregateIndexes&&!r.baseWhere&&!u&&(!h||ht(l,[r.field]))){const F=Pt(l.aggregateIndexes,r.op,r.field,r.where);if(F){ve(e,F.index);const j=Me(F.index.by??[],F.key),x=Le(e,F.index.name),K=B(o,n`SELECT ${_e} AS value, ${Oe} AS count FROM ${n.identifier(x)} WHERE ${Re} = ${j}`).toArray()[0];return ke(r.op,K)}}pt(l,r.field,`aggregate(${e}, { op: "${r.op}", field: "${r.field}" })`);const m=ne(s,ie),S=Se(r.op),w=V(r.field);let R=n`SELECT ${n.raw(S)}(${w}) AS value FROM ${n.identifier(e)}`;return m&&(R=n`${R} WHERE ${m}`),B(o,R).toArray()[0]?.value??null},asId(e,r){const a=mt(t,e,r);if(a===null)throw new b("BAD_REQUEST",`asId("${e}", …): "${r}" is not a valid id for table "${e}"`,{status:400});return a},async count(e,r){const a=z(e,"count");if(a)return N(e,P),a.count(e,r);const l=t.tables[e];if(!l)throw new b("INTERNAL",`unknown table: ${e}`);const h=Wt(r);if(h.restrictsCounts)throw new De(e);N(e,P);const f=de(l.softDeleteMode,void 0),s=Y(Y(h.baseWhere,h.where),f),u=await pe(s,e,h.relationBaseWhere),m=u!==s;if(l.aggregateIndexes&&!h.baseWhere&&!m&&!f){const R=Ut(l.aggregateIndexes,h.where);if(R){ve(e,R.index);const L=Me(R.index.by??[],R.key),F=Le(e,R.index.name),j=B(o,n`SELECT ${_e} AS value FROM ${n.identifier(F)} WHERE ${Re} = ${L}`).toArray();return j[0]===void 0?0:j[0].value??0}}const S=ne(u,ie);let w=n`SELECT COUNT(*) AS count FROM ${n.identifier(e)}`;return S&&(w=n`${w} WHERE ${S}`),B(o,w).one().count},async delete(e,r,a){const l=re(e,r);if(!l){const w=r===void 0?W:void 0;w&&await w.delete(e,void 0,a);return}const{docJson:h,row:f,tableName:s}=l,u=t.tables[s],m=a?.hard===!0,S=!m&&u?.softDeleteMode?u.softDeleteMode.field:void 0;if(!(S&&f[S]!==null&&f[S]!==void 0)){if(X(s,"before","delete")&&await Z("before","delete",{id:e,op:"delete",previous:f,table:s}),await an({deletedId:e,deletedReference:w=>f[w],findHolders:async(w,R,L)=>(await xe(w).findMany(w,{includeDeleted:m,where:{[R]:L}})).page,onCascade:(w,R)=>xe(w).delete(R,void 0,a),onRestrict:w=>{throw new he(w,"restrict")},onSetNull:(w,R,L)=>xe(w).patch(R,{[L]:null}),schema:t,tableName:s}),ce(s),ue(s),S){const w={...f,[S]:D(),_id:e};Ae(o,s,n`UPDATE ${n.identifier(s)} SET ${n.identifier(H)} = ${ae(w)} WHERE id = ${e} AND ${n.identifier(H)} = ${h}`),ge(s,e,w,f),we(s,e,void 0),$e(s,f,w),fe(s,e,f,void 0),O?.invalidate(s,e,c(s,f,w)),G(s,e,"update",w),d({indexKeys:c(s,f,w),key:e,op:"update",row:w,table:s}),X(s,"after","delete")&&await Z("after","delete",{id:e,op:"delete",previous:f,table:s}),await C({id:e,op:"delete",table:s});return}Ae(o,s,n`DELETE FROM ${n.identifier(s)} WHERE id = ${e} AND ${n.identifier(H)} = ${h}`),ge(s,e,void 0),we(s,e,void 0),$e(s,f,void 0),fe(s,e,f,void 0),O?.invalidate(s,e,c(s,f)),G(s,e,"delete"),d({indexKeys:c(s,f),key:e,op:"delete",table:s}),X(s,"after","delete")&&await Z("after","delete",{id:e,op:"delete",previous:f,table:s}),await C({id:e,op:"delete",table:s})}},async deleteAll(e,r){if(!t.tables[e])throw new b("INTERNAL",`unknown table: ${e}`);const a=Math.max(1,r?.chunkSize??Tt),l=r?.hard===void 0?void 0:{hard:r.hard},h=ee(e)?void 0:e;let f=0;return await A(async()=>{for(;;){const s=(await q.findMany(e,{limit:a})).page.map(u=>String(u._id));if(s.length===0)break;for(const u of s)await q.delete(u,h,l),f+=1;if(s.length<a)break}}),{deleted:f}},async deleteMany(e,r,a){se(e.length,r?.limit,"deleteMany");for(const l of e)await q.delete(l,a);return{deleted:e.length}},async deleteWhere(e,r,a){const l=(await(z(e,"deleteWhere")??q).findMany(e,{where:r})).page.map(h=>String(h._id));if(se(l.length,a?.limit,"deleteWhere"),q.deleteMany===void 0)throw new b("INTERNAL",`ctx.db.${e}.deleteMany is unavailable: this writer has no batch delete`);return q.deleteMany(l,a)},async findFirst(e,r={}){return(await q.findMany(e,{...r,limit:1})).page[0]??null},async findFirstOrThrow(e,r={}){const a=await q.findFirst(e,r);if(a===null)throw new Jt(`findFirstOrThrow: no "${e}" document matched`);return a},async findMany(e,r={}){const a=z(e,"findMany");if(a)return N(e,P),a.findMany(e,r);const l=t.tables[e];if(!l)throw new b("INTERNAL",`unknown table: ${e}`);const h=!r.where&&!r.baseWhere;h?N(e,P):N(e);const f=Xt(r.orderBy),s=r.cursor?Nt(f,qe(r.cursor)):void 0;let u=Y(r.baseWhere,r.where);u=Y(u,de(l.softDeleteMode,r.includeDeleted)),u=await st(u,{canPushExists:Ye?It:void 0,existsPushMode:Ke==="always"?"always":"auto",fetcher:Ge,maxRelationKeys:ze,relationBaseWhere:r.relationBaseWhere,schema:t,tableName:e}),s&&(u=u?{AND:[u,s]}:s);const m=Ye?qn(N):ie,S=ne(u,m);let w=n`SELECT id, _creationTime, ${n.identifier(H)} FROM ${n.identifier(e)}`;S&&(w=n`${w} WHERE ${S}`),w=n`${w} ORDER BY ${xt(f)}`;const R=typeof r.limit=="number"?Math.max(0,Math.floor(r.limit)):void 0;R!==void 0&&(w=n`${w} LIMIT ${n.raw(String(R+1))}`);const L=B(o,w).toArray();h&&!$&&p?.recordRead(L.length);const F=[];for(const te of L){const U=le(te);U&&(F.push(U),!h&&typeof U._id=="string"&&N(e,U._id))}if(R===void 0)return r.with&&await dt({groupedCounter:Ve,fetcher:Ie,parents:F,...lt(r),schema:t,tableName:e,with:r.with}),{continueCursor:null,isDone:!0,page:it(F,r.select,r.with)};const j=F.length>R,x=j?F.slice(0,R):F,K=x.at(-1);return r.with&&await dt({fetcher:Ie,groupedCounter:Ve,parents:x,...lt(r),schema:t,tableName:e,with:r.with}),{continueCursor:j&&K?Ue(K,f):null,isDone:!j,page:it(x,r.select,r.with)}},async get(e,r){const a=re(e,r);if(!a){const l=r===void 0?W:void 0;return l?l.get(e):null}return N(a.tableName,e),a.row},async lookupById(e,r){const a=re(e,r);return a?(N(a.tableName,e),{row:a.row,tableName:a.tableName}):null},async groupBy(e,r){const a=z(e,"groupBy");if(a)return N(e,P),a.groupBy(e,r);const l=t.tables[e];if(!l)throw new b("INTERNAL",`unknown table: ${e}`);N(e,P);const h=r.agg??{op:"count"};if(Se(h.op),h.op!=="count"&&!h.field)throw new b("INTERNAL",`groupBy(${e}, { agg: { op: "${h.op}" } }): "field" is required for non-count reducers`);const f=de(l.softDeleteMode,void 0),s=Y(Y(r.baseWhere,r.where),f),u=await pe(s,e,r.relationBaseWhere),m=u!==s,S=[...r.by,h.field];if(l.aggregateIndexes&&!r.baseWhere&&!m&&(!f||ht(l,S))){const x=qt(l.aggregateIndexes,h.op,h.field,r.by,r.where),K=x===void 0?0:Object.keys(x.partial).length,te=x?.index.by?.length??0;if(x&&(K===0||K===te)){ve(e,x.index);const U=Le(e,x.index.name),be=Object.keys(x.partial),Ee=[];if(be.length===(x.index.by??[]).length&&be.length>0){const ye=Me(x.index.by??[],x.partial),Ne=B(o,n`SELECT ${_e} AS value, ${Oe} AS count FROM ${n.identifier(U)} WHERE ${Re} = ${ye}`).toArray();return Ne.length>0&&Ee.push({key:{...x.partial},value:ke(h.op,Ne[0])}),Ee}const Mt=B(o,n`SELECT ${Re} AS key, ${_e} AS value, ${Oe} AS count FROM ${n.identifier(U)}`).toArray();for(const ye of Mt){const Ne=Ft(JSON.parse(ye.key));Ee.push({key:Ne,value:ke(h.op,ye)})}return Ee}}for(const x of S){if(x===void 0)continue;const K=x===h.field?`groupBy(${e}, { agg: { op: "${h.op}", field: "${x}" } })`:`groupBy(${e}, { by: [..."${x}"] })`;pt(l,x,K)}const w=ne(u,ie),R=r.by.map(x=>n`${V(x)} AS ${n.identifier(x)}`);if(h.op==="count")R.push(n`COUNT(*) AS value`);else{const{field:x}=h;if(x===void 0)throw new b("INTERNAL",`groupBy(${e}, { agg: { op: "${h.op}" } }): "field" is required for non-count reducers`);R.push(n`${n.raw(Se(h.op))}(${V(x)}) AS value`)}let L=n`SELECT ${n.join(R,n`, `)} FROM ${n.identifier(e)}`;w&&(L=n`${L} WHERE ${w}`),L=n`${L} GROUP BY ${n.join(r.by.map(x=>V(x)),n`, `)}`;const F=B(o,L).toArray(),j=[];for(const x of F){const K={};for(const U of r.by)K[U]=x[U]??null;const{value:te}=x;j.push({key:K,value:te==null?null:Number(te)})}return j},async insert(e,r,a){const l=z(e,"insert");if(l){const S=await l.insert(e,r,a);return $||p?.recordWrite(r),d({key:S,op:"insert",row:{...r,_id:S},table:e}),S}const h=t.tables[e];if(!h)throw new b("INTERNAL",`unknown table: ${e}`);const f=$t(h,r,E);We(h,f);let s;a?.clientId!==void 0?(An(a.clientId),s=a.clientId):a?.allowExplicitId&&typeof f._id=="string"?s=f._id:s=k();const u=a?.allowExplicitId&&typeof f._creationTime=="number"?f._creationTime:D(),m={...f,_creationTime:u,_id:s};return X(e,"before","insert")&&await Z("before","insert",{doc:{...m},id:s,op:"insert",table:e}),ce(e),ue(e),Pe(o,e,n`INSERT INTO ${n.identifier(e)} (id, _creationTime, ${n.identifier(H)}) VALUES (${s}, ${u}, ${ae(m)})`),Xe(e,s,m),X(e,"after","insert")&&await Z("after","insert",{doc:m,id:s,op:"insert",table:e}),await C({doc:m,id:s,op:"insert",table:e}),s},async insertManyUnsafe(e,r,a){if(se(r.length,a?.limit,"insertManyUnsafe"),r.length===0)return[];const l=z(e,"insert");if(l){const u=[];for(const m of r){const S=await l.insert(e,m,{allowExplicitId:a?.allowExplicitId});$||p?.recordWrite(m),d({key:S,op:"insert",row:{...m,_id:S},table:e}),u.push(S)}return u}const h=t.tables[e];if(!h)throw new b("INTERNAL",`unknown table: ${e}`);ce(e),ue(e);const f=r.map(u=>{const m=$t(h,u,E),S=a?.allowExplicitId===!0&&typeof m._id=="string"?m._id:k(),w=a?.allowExplicitId===!0&&typeof m._creationTime=="number"?m._creationTime:D();return{creationTime:w,document:{...m,_creationTime:w,_id:S},id:S}});if(!$)for(const u of f)p?.recordWrite(u.document);const s=n.join(f.map(u=>n`(${u.id}, ${u.creationTime}, ${ae(u.document)})`),n`, `);Pe(o,e,n`INSERT INTO ${n.identifier(e)} (id, _creationTime, ${n.identifier(H)}) VALUES ${s}`);for(const{document:u,id:m}of f)Xe(e,m,u),await _({doc:u,id:m,op:"insert",table:e});return f.map(u=>u.id)},async insertMany(e,r,a){se(r.length,a?.limit,"insertMany");const l=a?.skipDuplicates===!0,h=[];for(const f of r)try{h.push(await q.insert(e,f))}catch(s){if(l&&s instanceof he&&s.kind==="unique")h.push(null);else throw s}return h},normalizeId(e,r){return mt(t,e,r)},async patch(e,r,a){const l=re(e,a);if(!l){const S=a===void 0?W:void 0;if(S){await S.patch(e,r);return}throw new b("INTERNAL",`document not found: ${e}`)}const{docJson:h,row:f,tableName:s}=l,u=t.tables[s];if(!u)throw new b("INTERNAL",`unknown table: ${s}`);N(s,e),gt("patch",r);const m={...f,...r,_id:e};wt(u,r,m,E),We(u,m,!0),X(s,"before","update")&&await Z("before","update",{doc:{...m},id:e,op:"update",previous:f,table:s}),ce(s),ue(s),Ae(o,s,n`UPDATE ${n.identifier(s)} SET ${n.identifier(H)} = ${ae(m)} WHERE id = ${e} AND ${n.identifier(H)} = ${h}`),ge(s,e,m,f),we(s,e,m),$e(s,f,m),fe(s,e,f,m),O?.invalidate(s,e,c(s,f,m)),G(s,e,"update",m),d({indexKeys:c(s,f,m),key:e,op:"update",row:m,table:s}),X(s,"after","update")&&await Z("after","update",{doc:m,id:e,op:"update",previous:f,table:s}),await C({doc:m,id:e,op:"update",table:s})},async patchMany(e,r,a){se(e.length,r?.limit,"patchMany");for(const l of e)await q.patch(l.id,l.patch,a);return{patched:e.length}},async patchWhere(e,r,a){const l=(await(z(e,"patchWhere")??q).findMany(e,{where:r.where})).page.map(h=>({id:String(h._id),patch:r.patch}));if(se(l.length,a?.limit,"patchWhere"),q.patchMany===void 0)throw new b("INTERNAL",`ctx.db.${e}.patchMany is unavailable: this writer has no batch patch`);return await q.patchMany(l,a),{patched:l.length}},query(e){const r=z(e,"query");return r?(N(e,P),r.query(e)):zn(o,t,e,T,a=>{a?g(a):N(e,P)},a=>{$||p?.recordRead(a)})},async rank(e,r,a){const l=z(e,"rank");if(l)return N(e,P),l.rank(e,r,a);T(e,r,"rank");const h=t.tables[e];if(!h)throw new b("INTERNAL",`unknown table: ${e}`);const f=h.rankIndexes?.find(U=>U.name===r);if(!f)throw new b("INTERNAL",`unknown rankIndex "${r}" on table "${e}"`);if(Ze(e,h,f),a.restrictsCounts)throw new De(e);N(e,P),Ce(e,f);const s=typeof a.row=="string"?a.row:a.row._id;if(!s)return null;const u=at(e,f.name),m=f.sortBy.map((U,be)=>ot(be)),S=m.map(U=>fn(U)).join(", "),w=B(o,n`SELECT ${n.identifier("__partition__")}, ${n.raw(S)} FROM ${n.identifier(u)} WHERE ${n.identifier("__id__")} = ${s}`).toArray(),[R]=w;if(R===void 0)return null;let L=R.__partition__;const F=Y(a.baseWhere,a.where);Fe(F,t,e,"rank");const j=en(f,F);if(j){const U=tn(f.partitionBy??[],j);if(U!==L)return null;L=U}const x=m.map(U=>R[U]),{before:K,total:te}=bt(o,u,m,f.sortBy,L,x,s);return{position:K+1,total:te}},async rankBefore(e,r,a){if(ee(e))throw new b("INTERNAL",`rankBefore is not supported on the global (.global()) table '${e}' — cross-shard rank cursors apply only to sharded tables`);const l=t.tables[e];if(!l)throw new b("INTERNAL",`unknown table: ${e}`);const h=l.rankIndexes?.find(m=>m.name===r);if(!h)throw new b("INTERNAL",`unknown rankIndex "${r}" on table "${e}"`);if(a.restrictsCounts)throw new De(e);N(e,P),Ce(e,h);const f=at(e,h.name),s=h.sortBy.map((m,S)=>ot(S)),u=h.sortBy.map((m,S)=>oe(a.sortValues[S]??null));return bt(o,f,s,h.sortBy,a.partitionKey,u,a.rowId)},async rankPage(e,r,a={}){Fe(Y(a.baseWhere,a.where),t,e,"rankPage");const l=z(e,"rankPage");if(l)return N(e,P),l.rankPage(e,r,a);T(e,r,"rank");const{continueCursor:h,hasMore:f,rows:s}=nt(tt,e,r,a);return{continueCursor:h,isDone:!f,page:s.map(u=>u.doc)}},async rankPageRows(e,r,a={}){Fe(Y(a.baseWhere,a.where),t,e,"rankPage"),T(e,r,"rank");const{directions:l,hasMore:h,rows:f}=nt(tt,e,r,a);return{directions:l,hasMore:h,rows:f}},async restore(e,r){const a=re(e,r);if(!a){const f=r===void 0?W:void 0;if(f?.restore){await f.restore(e);return}throw new b("INTERNAL",`document not found: ${e}`)}const l=t.tables[a.tableName]?.softDeleteMode?.field;if(!l)throw new b("INTERNAL",`ctx.db.restore: table "${a.tableName}" is not a .softDelete() table`);const h=a.row[l]!==null&&a.row[l]!==void 0;await q.patch(e,{[l]:null},r),h&&fe(a.tableName,e,void 0,a.row)},async replace(e,r,a,l){const h=re(e,a);if(!h){const R=a===void 0?W:void 0;if(R){await R.replace(e,r,void 0,l);return}throw new b("INTERNAL",`document not found: ${e}`)}const{docJson:f,row:s,tableName:u}=h,m=t.tables[u];if(!m)throw new b("INTERNAL",`unknown table: ${u}`);gt("replace",r);const S=l?.allowExplicitId&&typeof r._creationTime=="number"?r._creationTime:D(),w={...r,_creationTime:S,_id:e};wt(m,r,w,E),We(m,w),X(u,"before","update")&&await Z("before","update",{doc:{...w},id:e,op:"update",previous:s,table:u}),ce(u),ue(u),Ae(o,u,n`UPDATE ${n.identifier(u)} SET _creationTime = ${S}, ${n.identifier(H)} = ${ae(w)} WHERE id = ${e} AND ${n.identifier(H)} = ${f}`),ge(u,e,w,s),we(u,e,w),$e(u,s,w),fe(u,e,s,w),O?.invalidate(u,e,c(u,s,w)),G(u,e,"update",w),d({indexKeys:c(u,s,w),key:e,op:"update",row:w,table:u}),X(u,"after","update")&&await Z("after","update",{doc:w,id:e,op:"update",previous:s,table:u}),await C({doc:w,id:e,op:"update",table:u})},async wipeShard(e){const r=new Set(e?.exclude),a=e?.tables,l=Object.entries(t.tables).filter(([u,m])=>r.has(u)||a!==void 0&&!a.includes(u)?!1:m.shardMode?.kind!=="global").map(([u])=>u);if(a!==void 0){for(const u of a)if(!t.tables[u])throw new b("INTERNAL",`wipeShard: unknown table: ${u}`)}const h={};let f=0;const{deleteAll:s}=q;if(s===void 0)throw new b("INTERNAL","wipeShard: this writer has no deleteAll");for(const u of l){const m=await s(u,{...e?.chunkSize===void 0?{}:{chunkSize:e.chunkSize},hard:!0});h[u]=m.deleted,f+=m.deleted}return{deleted:f,tables:h}}},Ct={db:q,scheduler:Q};return i.enforceRls===!0?dn(q,t,(e,r)=>re(e,r)?.tableName,(e,r)=>vt(e,r)):q};export{kr as CDC_LOG_TABLE,Pr as CLIENT_WATERMARK_TABLE,Kr as GLOBAL_SHAPE_SNAPSHOT_TABLE,ei as IDEMPOTENCY_TABLE,Gn as NotUniqueError,si as SEARCH_STATE_TABLE,jr as advanceClientWatermark,Lr as applyCdcChanges,An as assertValidClientId,Ir as backfillAggregateIndexes,vr as backfillRankIndexes,Cr as backfillSearchIndexes,Dr as bumpCdcEpoch,Rr as createShardCtxDb,Yr as deleteGlobalShapeSnapshot,zr as deleteGlobalShapeSnapshotsForConnection,Hr as migrateClientWatermark,Vr as migrateGlobalShapeSnapshot,Or as minCdcSeq,mt as normalizeIdStructurally,Fr as readCdcChanges,Wr as readCdcCursor,Br as readCdcEpoch,Qr as readClientWatermark,Jr as readGlobalShapeSnapshot,ti as readIdempotent,oi as runShardMigrations,li as selectShapeMemberIds,ci as selectShapeRows,qr as trimCdcChanges,ni as trimIdempotent,Xr as writeGlobalShapeSnapshot,ri as writeIdempotent};
@@ -1 +0,0 @@
1
- import{LunoraError as $}from"@lunora/errors";import{sql as s}from"drizzle-orm";import{RELATION_EXISTS_KEY as c}from"./RELATION_EXISTS_KEY-BaqSIFU1.mjs";const N=["eq","ne","lt","lte","gt","gte","in","notIn","isNull","contains"],h=new Set(N),p={eq:"=",gt:">",gte:">=",lt:"<",lte:"<=",ne:"<>"},I=r=>{if(r===null||typeof r!="object"||Array.isArray(r))return!1;const e=Object.keys(r);return e.length>0&&e.every(t=>h.has(t))},L=r=>typeof r=="string"?r.replaceAll(/[\\%_]/g,e=>`\\${e}`):r,g=(r,e,t)=>{const o=s`${t.serialize(L(e))}`;return t.likeContains?t.likeContains(r,o):s`${r} LIKE '%' || ${o} || '%' ESCAPE '\\'`},O=(r,e,t,o,n)=>o===null?e==="ne"?s`${r} IS NOT NULL`:s`${r} IS NULL`:s`${r} ${s.raw(t)} ${n.serialize(o)}`,S=(r,e,t,o)=>{const n=Array.isArray(t)?t:[];if(n.length===0)return e==="IN"?s`0 = 1`:s`1 = 1`;const i=s.join(n.map(l=>s`${o.serialize(l)}`),s`, `);return e==="IN"?s`${r} IN (${i})`:s`${r} NOT IN (${i})`},A=(r,e,t)=>{const o=e,n=[];for(const i of N){if(!(i in o))continue;const l=o[i],u=p[i];u?n.push(O(r,i,u,l,t)):i==="isNull"?n.push(l?s`${r} IS NULL`:s`${r} IS NOT NULL`):i==="contains"?n.push(g(r,l,t)):n.push(S(r,i==="in"?"IN":"NOT IN",l,t))}return n},y=(r,e,t)=>{const o=t.fieldRef(r);return I(e)?A(o,e,t):e===null?[s`${o} IS NULL`]:[s`${o} = ${t.serialize(e)}`]},f=(r,e)=>{if(r.length!==0)return r.length===1?r[0]:s.join(r.map(t=>s`(${t})`),s` ${s.raw(e)} `)},E=(r,e,t)=>{const o=Array.isArray(r)?r:[],n=[];for(const i of o){const l=a(i??{},t);l&&n.push(l)}return n.length===0?e==="OR"?s`0 = 1`:void 0:f(n,e)},m=new Set(["AND","NOT","OR",c]),T=(r,e,t)=>{if(r===c){if(!t.relationExists)throw new $("INTERNAL","encountered a relation EXISTS marker without a relationExists strategy hook");return t.relationExists(e)}if(r==="NOT"){const o=a(e??{},t);return o?s`NOT (${o})`:void 0}return E(e,r,t)},a=(r,e)=>{const t=[];for(const[o,n]of Object.entries(r))if(m.has(o)){const i=T(o,n,e);i&&t.push(i)}else t.push(...y(o,n,e));return f(t,"AND")},R=(r,e)=>{if(!(!r||Object.keys(r).length===0))return a(r,e)};export{R as compileWhereSql};
@@ -1 +0,0 @@
1
- import{LunoraError as A}from"@lunora/errors";import{sql as t}from"drizzle-orm";import{mergeWhere as x}from"./CountRlsUnsupportedError-8BqPYQoP.mjs";import{SCAN_DEP as O}from"./SCAN_DEP-D_yR9EeV.mjs";import{runDrizzle as B}from"./runDrizzle-B6rnz3so.mjs";import{param as q}from"./param-B5lF5Jd9.mjs";import{decodeCursor as W,toBase64 as z}from"./applySelect-UY-o13Ia.mjs";import{sortColumnName as F,resolveRankPartition as H,RANK_TIEBREAK as m,encodePartitionKey as J,rankTableName as V}from"./RANK_TIEBREAK-DDtST3gN.mjs";const Y="__doc__",G=n=>z(JSON.stringify(n)),X=n=>n.after?[n.after.partitionKey,...n.after.sortValues,n.after.rowId]:n.cursor?W(n.cursor):void 0,Z=(n,o,c)=>{if(n?.length!==1+o.length+1)return;const i=[{column:"__partition__",direction:"asc"}];for(const[a,f]of o.entries())i.push({column:f,direction:c[a]?.direction??"asc"});i.push({column:m,direction:"asc"});const s=[];for(const[a,f]of i.entries()){const e=[];for(const[r,$]of i.slice(0,a).entries())e.push(t`${t.identifier($.column)} IS ${n[r]}`);e.push(t`${t.identifier(f.column)} ${t.raw(f.direction==="desc"?"<":">")} ${n[a]}`);const[d]=e;s.push(e.length===1&&d!==void 0?d:t`(${t.join(e,t` AND `)})`)}return t`(${t.join(s,t` OR `)})`},C=null,Q=(n,o)=>{if(n===void 0)return C;const c=[n.__partition__,...o.map(i=>n[i]),n[m]];return G(c)},U=(n,o,c)=>{const i=[];for(const s of n){const a=s[m];if(typeof a!="string")continue;const f=o.get(a);if(!f)continue;const e=typeof s.__partition__=="string"?s.__partition__:"",d=c.map(r=>s[r]??null);i.push({doc:f,key:{partitionKey:e,rowId:a,sortValues:d}})}return i},tt=(n,o,c)=>{const{rowToDocument:i}=n,s=new Map;if(c.length===0)return s;const a=t.join(c.map(e=>q(e)),t`, `),f=B(n.sql,t`SELECT id, _creationTime, ${t.identifier(Y)} FROM ${t.identifier(o)} WHERE id IN (${a})`).toArray();for(const e of f){const d=i(e),r=e.id;d&&typeof r=="string"&&s.set(r,d)}return s},ft=(n,o,c,i)=>{const{assertRankPartitionLocal:s,ensureRankBackfilled:a,onRead:f,schema:e}=n,d=e.tables[o];if(!d)throw new A("INTERNAL",`unknown table: ${o}`);const r=d.rankIndexes?.find(p=>p.name===c);if(!r)throw new A("INTERNAL",`unknown rankIndex "${c}" on table "${o}"`);s(o,d,r),f(o,O),a(o,r);const $=V(o,r.name),u=r.sortBy.map((p,w)=>F(w)),l=Math.max(1,Math.min(1e3,Math.floor(i.take??100))),S=x(i.baseWhere,i.where),R=H(r,S),h=[t`${t.identifier("__partition__")} ASC`];for(const[p,w]of u.entries()){const v=r.sortBy[p]?.direction;h.push(t`${t.identifier(w)} ${t.raw(v==="desc"?"DESC":"ASC")}`)}h.push(t`${t.identifier(m)} ASC`);const _=[];typeof i.partitionKey=="string"?_.push(t`${t.identifier("__partition__")} = ${i.partitionKey}`):R&&_.push(t`${t.identifier("__partition__")} = ${J(r.partitionBy??[],R)}`);const T=X(i),k=Z(T,u,r.sortBy);k&&_.push(k);const I=t.identifier(m),N=t.identifier("__partition__"),M=_.length>0?t` WHERE ${t.join(_,t` AND `)}`:t``,D=u.length>0?t`${I}, ${N}, ${t.join(u.map(p=>t.identifier(p)),t`, `)}`:t`${I}, ${N}`,K=t`SELECT ${D} FROM ${t.identifier($)}${M} ORDER BY ${t.join(h,t`, `)} LIMIT ${t.raw(String(l+1))}`,y=B(n.sql,K).toArray(),g=y.length>l,E=g?y.slice(0,l):y,L=E.map(p=>p[m]),b=U(E,tt(n,o,L),u),j=g?Q(E.at(-1),u):C,P=r.sortBy.map(p=>p.direction==="desc"?"desc":"asc");return{continueCursor:j,directions:P,hasMore:g,rows:b}};export{ft as computeRankPage,tt as hydrateDocsById};
@@ -1 +0,0 @@
1
- import"@lunora/errors";import{sql as e}from"drizzle-orm";import{matchesStaticWhere as V,aggregateSqlFunction as de}from"./AGGREGATE_SQL_FUNCTION-CTo0-9iZ.mjs";import{encodeAggregateKey as O,foldAggregateTally as G,coerceAggregateNumber as I,aggregateTableName as P}from"./aggregateTableName-DgYMC5tr.mjs";import{runDrizzle as $}from"./runDrizzle-B6rnz3so.mjs";import{C as ce,a as M,E as k,c as x,p as v,T as y,h as fe,A as C,N as D}from"./do-sql-1Yi1_Yq0.mjs";import{param as $e}from"./param-B5lF5Jd9.mjs";import{encodeGeohash as ue,GEO_DEFAULT_PRECISION as me}from"./GEO_DEFAULT_PRECISION-DyI5zggj.mjs";import{isLiveForCompanion as J}from"./applySelect-UY-o13Ia.mjs";import{encodePartitionKey as Ee,sortColumnName as he,matchesRankStaticWhere as Y,rankTableName as Z}from"./RANK_TIEBREAK-DDtST3gN.mjs";import{y as pe}from"./sql-projection-jfoe331H.mjs";import{serializeSqlValue as ee}from"./serializeSqlValue-BR4UOWoP.mjs";const ge=["de","en","es","fr","it","nl","none","pt"],ye=o=>ge.includes(o),_e="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",be="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",ve="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",we="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",Te="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",Se="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",Ae="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ê",Re=/[\u0300-\u036F]/gu,ne=o=>o.normalize("NFD").replaceAll(Re,"").normalize("NFC").toLowerCase(),j=o=>new Set(ne(o).split(" ")),Le={de:j(be),en:j(_e),es:j(ve),fr:j(we),it:j(Te),nl:j(Se),none:new Set,pt:j(Ae)},Ne=2,Oe=256,X=new Map,je=o=>{const a=o!==void 0&&ye(o)?o:"none",l=X.get(a);if(l)return l;const g=Le[a],S=r=>{const A=(ne(r).match(/[\p{L}\p{N}]+/gu)??[]).filter(w=>w.length<=Oe);return g.size===0?A:A.filter(w=>!g.has(w))},m={document:S,profile:`${a}-v${String(Ne)}`,query:r=>{const A=S(r);return A.filter((w,L)=>A.lastIndexOf(w)===L)}};return X.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}`,Ie="__text__",Q="__id__",Ce=1e3,Me=(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)??"",De=(o,a,l)=>o!==void 0&&a!==void 0&&q(o,l.field)===q(a,l.field),qe=(o,a)=>Me(ke(q(o,a.field)),je(a.language)).slice(0,Ce).join(" "),ze=(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)=>he(l))].map(a=>e.identifier(a)),e`, `),ie=(o,a,l,g,S,m)=>{const r=Ee(l.partitionBy??[],m),A=l.sortBy.map(L=>ee(m[L.field]??null)),w=e.join([S,r,...A].map(L=>$e(L)),e`, `);$(o,e`INSERT INTO ${e.identifier(a)} (${g}) VALUES (${w})`)},We=(o,a,l,g,S,m)=>{if(S&&m&&ze(l,S,m))return;const r=Z(a,l.name);S&&$(o,e`DELETE FROM ${e.identifier(r)} WHERE ${e.identifier("__id__")} = ${g}`),!(!m||l.where&&!Y(m,l.where))&&ie(o,r,l,oe(l),g,m)},en=o=>{const{broadcast:a,indexKeysFor:l,invalidateCache:g,recordCdc:S,schema:m,sql:r}=o,A=new Set,w=i=>m.tables[i]?.softDeleteMode?.field,L=new Set,z=(i,n)=>{const s=`${i}::${n.name}`;if(A.has(s))return;const d=P(i,n.name),c=n.by??[],f=w(i),h=new Map,_=$(r,e`SELECT id, _creationTime, ${e.identifier(M)} FROM ${e.identifier(i)}`).toArray();for(const T of _){const u=k(T);if(!u||!J(u,f)||n.where&&!V(u,n.where))continue;const E=O(c,u);G(h,E,n,u)}$(r,e`DELETE FROM ${e.identifier(d)}`);const R=32,N=[...h];for(let T=0;T<N.length;T+=R){const u=N.slice(T,T+R),E=e.join(u.map(([t,p])=>e`(${t}, ${p.value}, ${p.count})`),e`, `);$(r,e`INSERT INTO ${e.identifier(d)} (${x}, ${v}, ${y}) VALUES ${E}`)}A.add(s)},te=(i,n,s)=>{const d=n.by??[],c=n.field??"",f=[],h=(E,t)=>{const p=ee(t);p===null?f.push(e`${D(E)} IS NULL`):f.push(e`${D(E)} = ${p}`)};for(const E of d)h(E,s[E]??null);const _=w(i);_!==void 0&&h(_,null);for(const[E,t]of Object.entries(n.where??{}))h(E,t!==null&&typeof t=="object"&&!Array.isArray(t)?t.eq:t);const R=f.length>0?e` WHERE ${e.join(f,e` AND `)}`:e``,N=m.tables[i]?.shape[c];if(N&&pe(N)){const E=$(r,e`SELECT id, _creationTime, ${e.identifier(M)} FROM ${e.identifier(i)}${R}`).toArray(),t=new Map;for(const p of E){const b=k(p);b&&G(t,"",n,b)}return{value:t.get("")?.value??null}}const T=de(n.op),u=D(c);return{value:$(r,e`SELECT ${e.raw(T)}(${u}) AS value FROM ${e.identifier(i)}${R}`).one().value??null}},re=(i,n,s,d)=>{const c=P(i,n.name),{op:f}=n,h=n.field??"",_=t=>{$(r,e`DELETE FROM ${e.identifier(c)} WHERE ${x} = ${t} AND ${y} <= 0`)},R=w(i),N=t=>!n.where||V(t,n.where),T=t=>J(t,R)&&N(t);d!==void 0&&f!=="count"&&N(d)&&I(d[h]);const u=s&&T(s)?s:void 0,E=d&&T(d)?d:void 0;if(!(!u&&!E)){if(f==="count"){for(const[t,p]of[[u,-1],[E,1]]){if(!t)continue;const b=O(n.by??[],t);$(r,C(c,b,p,p,e`${v} = ${v} + excluded.${v}, ${y} = ${y} + excluded.${y}`))}u&&_(O(n.by??[],u));return}if(f==="sum"||f==="avg"){for(const[t,p]of[[u,-1],[E,1]]){if(!t)continue;const b=I(t[h]);if(b===void 0)continue;const F=O(n.by??[],t);$(r,C(c,F,p*b,p,e`${v} = COALESCE(${v}, 0) + excluded.${v}, ${y} = ${y} + excluded.${y}`))}u&&_(O(n.by??[],u));return}if(u){const t=O(n.by??[],u),p=I(u[h]),b=$(r,e`SELECT ${v} AS value, ${y} AS count FROM ${e.identifier(c)} WHERE ${x} = ${t}`).toArray()[0],F=(b?.count??0)-1;if(F<=0)$(r,e`DELETE FROM ${e.identifier(c)} WHERE ${x} = ${t}`);else if(b&&p!==void 0&&b.value!==null&&p===b.value){const le=te(i,n,u);$(r,e`UPDATE ${e.identifier(c)} SET ${v} = ${le.value}, ${y} = ${F} WHERE ${x} = ${t}`)}else $(r,e`UPDATE ${e.identifier(c)} SET ${y} = ${y} - 1 WHERE ${x} = ${t}`)}if(E){const t=O(n.by??[],E),p=I(E[h]);if(p===void 0)$(r,C(c,t,null,1,e`${y} = ${y} + 1`));else{const b=f==="min"?"MIN":"MAX";$(r,C(c,t,p,1,e`${v} = ${e.raw(b)}(COALESCE(${v}, excluded.${v}), excluded.${v}), ${y} = ${y} + 1`))}}}},ae=i=>{for(const n of m.tables[i]?.aggregateIndexes??[])z(i,n)},W=(i,n,s)=>{for(const d of m.tables[i]?.aggregateIndexes??[])re(i,d,n,s)},B=(i,n)=>{const s=`${i}::rank::${n.name}`;if(L.has(s))return;const d=Z(i,n.name),c=$(r,e`SELECT id, _creationTime, ${e.identifier(M)} FROM ${e.identifier(i)}`).toArray();$(r,e`DELETE FROM ${e.identifier(d)}`);const f=oe(n);for(const h of c){const _=k(h);!_||n.where&&!Y(_,n.where)||ie(r,d,n,f,_._id,_)}L.add(s)},se=i=>{for(const n of m.tables[i]?.rankIndexes??[])B(i,n)},H=(i,n,s,d)=>{for(const c of m.tables[i]?.rankIndexes??[])We(r,i,c,n,s,d)},U=(i,n,s,d)=>{const c=m.tables[i]?.searchIndexes??[];if(!(c.length===0||!ce(r)))for(const f of c){if(De(d,s,f))continue;const h=Fe(i,f.name);$(r,e`DELETE FROM ${e.identifier(h)} WHERE ${e.identifier(Q)} = ${n}`),s&&$(r,e`INSERT INTO ${e.identifier(h)} (${e.identifier(Ie)}, ${e.identifier(Q)}) VALUES (${qe(s,f)}, ${n})`)}},K=(i,n,s)=>{for(const d of m.tables[i]?.geoIndexes??[]){const c=fe(i,d.name);$(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:_}=f,R=ue({lat:h,lng:_},d.precision??me);$(r,e`INSERT INTO ${e.identifier(c)} (${e.identifier("__id__")}, ${e.identifier("__geohash__")}, ${e.identifier("__lat__")}, ${e.identifier("__lng__")}) VALUES (${n}, ${R}, ${h}, ${_})`)}}};return{ensureBackfilledForTable:ae,ensureBackfilledIndex:z,ensureRankBackfilled:B,ensureRankBackfilledForTable:se,syncAggregates:W,syncCompanionsForInsert:(i,n,s)=>{U(i,n,s),K(i,n,s),W(i,void 0,s),H(i,n,void 0,s),g(i,n,s),S(i,n,"insert",s),a({indexKeys:l(i,s),key:n,op:"insert",row:s,table:i})},syncGeo:K,syncRanks:H,syncSearch:U}};export{oe as B,Q as T,ie as W,Fe as c,Ie as l,Me as n,en as w,je as x,qe as y};
@@ -1 +0,0 @@
1
- import{sql as m}from"drizzle-orm";import{MySqlDialect as s}from"drizzle-orm/mysql-core";import{PgDialect as l}from"drizzle-orm/pg-core";import{SQLiteSyncDialect as n}from"drizzle-orm/sqlite-core";const p=new l,a=new s,i=new n,q={mysql:a,postgres:p,sqlite:i},w=(r,t)=>{const{params:e,sql:o}=q[r].sqlToQuery(t);return{params:e,sql:o}},D=r=>m`${r}`;export{D as param,w as renderSql};
@@ -1 +0,0 @@
1
- import{sql as e}from"drizzle-orm";import{runDrizzle as l}from"./runDrizzle-B6rnz3so.mjs";import{a as c,E as a,N as u}from"./do-sql-1Yi1_Yq0.mjs";import{compileWhereSql as h}from"./compileWhereSql-B4rPariq.mjs";import{serializeSqlValue as S}from"./serializeSqlValue-BR4UOWoP.mjs";const $={fieldRef:u,serialize:S},E=i=>{if(i.length!==0)return e`id IN (${e.join(i.map(r=>e`${r}`),e`, `)})`},m=(i,r)=>{const o=[];r&&o.push(r);const t=h(i,$);return t&&o.push(t),o.length===0?e``:e` WHERE ${e.join(o,e` AND `)}`},y=(i,r,o)=>{const t=m(o,void 0),d=l(i,e`SELECT id, _creationTime, ${e.identifier(c)} FROM ${e.identifier(r)}${t}`).toArray(),n=[];for(const s of d){const f=a(s),{id:p}=s;f!==void 0&&typeof p=="string"&&n.push({doc:f,id:p})}return n},A=(i,r,o,t)=>{if(t.length===0)return new Set;const d=m(o,E(t)),n=l(i,e`SELECT id FROM ${e.identifier(r)}${d}`).toArray();return new Set(n.map(s=>s.id))};export{A as selectShapeMemberIds,y as selectShapeRows};