@lunora/shard-engine 1.0.0-alpha.4 → 1.0.0-alpha.6

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 (24) hide show
  1. package/dist/conformance/index.mjs +1 -1
  2. package/dist/index.d.mts +26 -8
  3. package/dist/index.d.ts +26 -8
  4. package/dist/index.mjs +1 -1
  5. package/dist/packem_shared/ADMIN_FUNCTIONS-vj2G8OR6.mjs +1 -0
  6. package/dist/packem_shared/{DEFAULT_MAX_RELAYS-CnCyh6oX.mjs → DEFAULT_MAX_RELAYS-D0oc40p6.mjs} +1 -1
  7. package/dist/packem_shared/DEFAULT_TRANSACTION_LIMITS-BH5q0Ror.mjs +1 -0
  8. package/dist/packem_shared/NotUniqueError-Qrtwm7S6.mjs +1 -0
  9. package/dist/packem_shared/RLS_UNWRAP_SYMBOL-CBYPlYBb.mjs +1 -0
  10. package/dist/packem_shared/ReactiveCache-C6QAa7MG.mjs +1 -0
  11. package/dist/packem_shared/awaitWsDrain-CCZ-8wjm.mjs +1 -0
  12. package/dist/packem_shared/buildIndexRange-DFsdtPjD.mjs +1 -0
  13. package/dist/packem_shared/{defineEngineContractSuite-BefTibvY.mjs → defineEngineContractSuite-1f7OcQND.mjs} +1 -1
  14. package/dist/packem_shared/estimate-bytes-DwQON1Ky.mjs +1 -0
  15. package/dist/packem_shared/{mergeChangedKeys-CvSHlkv-.mjs → mergeChangedKeys-BXtUgIPW.mjs} +1 -1
  16. package/package.json +3 -3
  17. package/dist/packem_shared/ADMIN_FUNCTIONS-B0xlQJ4w.mjs +0 -1
  18. package/dist/packem_shared/DEFAULT_TRANSACTION_LIMITS--TtB8Gpo.mjs +0 -1
  19. package/dist/packem_shared/NotUniqueError-iGKd9wRR.mjs +0 -1
  20. package/dist/packem_shared/RLS_UNWRAP_SYMBOL-C6_WX3dG.mjs +0 -1
  21. package/dist/packem_shared/ReactiveCache-CF21t8IB.mjs +0 -1
  22. package/dist/packem_shared/awaitWsDrain-Dk50ISgE.mjs +0 -1
  23. package/dist/packem_shared/buildIndexRange-DIjFVgeO.mjs +0 -1
  24. package/dist/packem_shared/estimate-bytes-DzD3PdCc.mjs +0 -1
@@ -1 +1 @@
1
- import{defineEngineContractSuite as t}from"../packem_shared/defineEngineContractSuite-BefTibvY.mjs";export{t as defineEngineContractSuite};
1
+ import{defineEngineContractSuite as t}from"../packem_shared/defineEngineContractSuite-1f7OcQND.mjs";export{t as defineEngineContractSuite};
package/dist/index.d.mts CHANGED
@@ -359,9 +359,21 @@ interface GeoFilterBuilderLike {
359
359
  };
360
360
  }) => GeoFilterBuilderLike;
361
361
  }
362
+ type ScoredDocument = GeoScoredDocument | SearchScoredDocument;
363
+ interface GeoScoredDocument {
364
+ distanceMeters: null | number;
365
+ document: Record<string, unknown>;
366
+ score?: never;
367
+ }
368
+ interface SearchScoredDocument {
369
+ distanceMeters?: never;
370
+ document: Record<string, unknown>;
371
+ score: number;
372
+ }
362
373
  interface TableReaderLike {
363
374
  [Symbol.asyncIterator]: () => AsyncIterator<Record<string, unknown>>;
364
375
  collect: () => Promise<Record<string, unknown>[]>;
376
+ collectWithScores: () => Promise<ScoredDocument[]>;
365
377
  filter: (predicate: (document: Record<string, unknown>) => boolean) => TableReaderLike;
366
378
  first: () => Promise<Record<string, unknown> | null>;
367
379
  order: (direction: "asc" | "desc") => TableReaderLike;
@@ -1107,6 +1119,7 @@ declare const ADMIN_FUNCTIONS: {
1107
1119
  readonly getMetricSeries: "__lunora_admin__:getMetricSeries";
1108
1120
  readonly listSubscriptions: "__lunora_admin__:listSubscriptions";
1109
1121
  readonly listTableIndexes: "__lunora_admin__:listTableIndexes";
1122
+ readonly listTablesIndexes: "__lunora_admin__:listTablesIndexes";
1110
1123
  readonly getLogs: "__lunora_admin__:getLogs";
1111
1124
  readonly getMetrics: "__lunora_admin__:getMetrics";
1112
1125
  readonly getPitrBookmark: "__lunora_admin__:getPitrBookmark";
@@ -1199,6 +1212,9 @@ interface TableIndexInfo {
1199
1212
  interface TableIndexesResult {
1200
1213
  indexes: TableIndexInfo[];
1201
1214
  }
1215
+ interface TablesIndexesResult {
1216
+ indexesByTable: Record<string, TableIndexInfo[]>;
1217
+ }
1202
1218
  interface ColumnMeta {
1203
1219
  isStorage?: boolean;
1204
1220
  name: string;
@@ -1229,12 +1245,13 @@ interface AdvisoriesResult {
1229
1245
  advisories: AdvisoryFinding[];
1230
1246
  }
1231
1247
  interface AdvisorProcedure {
1232
- callsMail: boolean;
1248
+ analyzableBody?: boolean;
1249
+ callsMail?: boolean;
1233
1250
  emitsEvent?: boolean;
1234
1251
  exempt?: boolean;
1235
1252
  exemptReason?: string;
1236
1253
  exportName: string;
1237
- fanOut: boolean;
1254
+ fanOut?: boolean;
1238
1255
  file: string;
1239
1256
  handlesErrors?: boolean;
1240
1257
  hasEmailArg?: boolean;
@@ -1242,15 +1259,15 @@ interface AdvisorProcedure {
1242
1259
  reachesOutbound?: boolean;
1243
1260
  runsAiGeneration?: boolean;
1244
1261
  throwsBareError?: boolean;
1245
- unboundedAiGeneration: boolean;
1262
+ unboundedAiGeneration?: boolean;
1246
1263
  usesCaptcha: boolean;
1247
1264
  usesEmailGate: boolean;
1248
- usesInsertManyUnsafe: boolean;
1265
+ usesInsertManyUnsafe?: boolean;
1249
1266
  usesMask: boolean;
1250
1267
  usesRateLimit: boolean;
1251
1268
  usesRls: boolean;
1252
1269
  visibility: "internal" | "public";
1253
- writesUserTable: boolean;
1270
+ writesUserTable?: boolean;
1254
1271
  }
1255
1272
  interface AdvisorProceduresResult {
1256
1273
  procedures: AdvisorProcedure[];
@@ -1878,7 +1895,8 @@ interface GuardableSchema {
1878
1895
  }>;
1879
1896
  }
1880
1897
  type TableOfId = (id: string, expectedTable?: string) => Promise<string | undefined> | string | undefined;
1881
- declare const guardWriter: <W>(raw: W, schema: GuardableSchema, tableOfId: TableOfId) => W;
1898
+ type TablesOfIds = (ids: ReadonlyArray<string>, expectedTable?: string) => Promise<ReadonlyMap<string, string>> | ReadonlyMap<string, string>;
1899
+ declare const guardWriter: <W>(raw: W, schema: GuardableSchema, tableOfId: TableOfId, tablesOfIds?: TablesOfIds) => W;
1882
1900
  declare const SCHEMA_HISTORY_MAX_VERSIONS = 50;
1883
1901
  interface SchemaVersionRow {
1884
1902
  appliedAt: number;
@@ -1940,7 +1958,7 @@ interface DrainableSink {
1940
1958
  readonly bufferedAmount?: unknown;
1941
1959
  }
1942
1960
  declare const trySendFrame: (ws: FrameSink, frame: string) => boolean;
1943
- declare const sendDeltaFrames: (ws: FrameSink, subId: string, deltaFrames: ReadonlyArray<string>, cursorSuffix: string) => boolean;
1961
+ declare const sendDeltaFrames: (ws: FrameSink, subId: string, deltaFrames: ReadonlyArray<string>, cursorSuffix: string, lastMutationId?: number) => boolean;
1944
1962
  declare const awaitWsDrain: (ws: DrainableSink) => Promise<void>;
1945
1963
  interface SubscriptionReadFootprint {
1946
1964
  ranges?: Map<string, KeyRange[]>;
@@ -1977,4 +1995,4 @@ interface WhereSqlStrategy {
1977
1995
  serialize: SerializeValue;
1978
1996
  }
1979
1997
  declare const compileWhereSql: (where: WhereInput | undefined, strategy: WhereSqlStrategy) => SQL | undefined;
1980
- 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 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 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, 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 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 SearchFilterBuilderLike, type SearchIndexDefinitionLike, type SelectMatchingIdsOptions, type ServerDefaultContextLike, type SettingEntry, type SettingKind, type SettingsResult, type ShapePokePart, type ShapeRow, type ShapeRowOp, type ShapeSubscriptionQuery, type ShardRankPageResult, ShardRunner, type ShardRunnerOptions, 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 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, buildSeekBeforeWhere, buildSeekWhere, buildSettings, bumpCdcEpoch, clampPromotionThresholds, clearCapturedMail, clearQueueMessages, coerceAggregateNumber, compileWhereSql, computeRankPage, containsRelationPredicate, coveringGeohashes, createCompanionSync, createDependencyTracker, createFanoutCounters, createIndexSql, createReadFootprint, createRelayLink, createShardCtxDb, createSystemReader, decodeCursor, deleteGlobalShapeSnapshot, deleteGlobalShapeSnapshotsForConnection, depKey, diffExternalSource, diffGlobalMembership, distinctValues, encodeAggregateKey, encodeCursor, encodeGeohash, encodePartitionKey, encodeRowsPatch, ensureAuditTable, ensureMailTable, exportShardRows, exportShardTable, facetColumn, fanOutScalarCounts, findStorageReferences, foldAggregateTally, geoTableName, guardWriter, 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, relayCountFor, renderSql, 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 };
1998
+ 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 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, 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 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 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, buildSeekBeforeWhere, buildSeekWhere, buildSettings, bumpCdcEpoch, clampPromotionThresholds, clearCapturedMail, clearQueueMessages, coerceAggregateNumber, compileWhereSql, computeRankPage, containsRelationPredicate, coveringGeohashes, createCompanionSync, createDependencyTracker, createFanoutCounters, createIndexSql, createReadFootprint, createRelayLink, createShardCtxDb, createSystemReader, decodeCursor, deleteGlobalShapeSnapshot, deleteGlobalShapeSnapshotsForConnection, depKey, diffExternalSource, diffGlobalMembership, distinctValues, encodeAggregateKey, encodeCursor, encodeGeohash, encodePartitionKey, encodeRowsPatch, ensureAuditTable, ensureMailTable, exportShardRows, exportShardTable, facetColumn, fanOutScalarCounts, findStorageReferences, foldAggregateTally, geoTableName, guardWriter, 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, relayCountFor, renderSql, 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 };
package/dist/index.d.ts CHANGED
@@ -359,9 +359,21 @@ interface GeoFilterBuilderLike {
359
359
  };
360
360
  }) => GeoFilterBuilderLike;
361
361
  }
362
+ type ScoredDocument = GeoScoredDocument | SearchScoredDocument;
363
+ interface GeoScoredDocument {
364
+ distanceMeters: null | number;
365
+ document: Record<string, unknown>;
366
+ score?: never;
367
+ }
368
+ interface SearchScoredDocument {
369
+ distanceMeters?: never;
370
+ document: Record<string, unknown>;
371
+ score: number;
372
+ }
362
373
  interface TableReaderLike {
363
374
  [Symbol.asyncIterator]: () => AsyncIterator<Record<string, unknown>>;
364
375
  collect: () => Promise<Record<string, unknown>[]>;
376
+ collectWithScores: () => Promise<ScoredDocument[]>;
365
377
  filter: (predicate: (document: Record<string, unknown>) => boolean) => TableReaderLike;
366
378
  first: () => Promise<Record<string, unknown> | null>;
367
379
  order: (direction: "asc" | "desc") => TableReaderLike;
@@ -1107,6 +1119,7 @@ declare const ADMIN_FUNCTIONS: {
1107
1119
  readonly getMetricSeries: "__lunora_admin__:getMetricSeries";
1108
1120
  readonly listSubscriptions: "__lunora_admin__:listSubscriptions";
1109
1121
  readonly listTableIndexes: "__lunora_admin__:listTableIndexes";
1122
+ readonly listTablesIndexes: "__lunora_admin__:listTablesIndexes";
1110
1123
  readonly getLogs: "__lunora_admin__:getLogs";
1111
1124
  readonly getMetrics: "__lunora_admin__:getMetrics";
1112
1125
  readonly getPitrBookmark: "__lunora_admin__:getPitrBookmark";
@@ -1199,6 +1212,9 @@ interface TableIndexInfo {
1199
1212
  interface TableIndexesResult {
1200
1213
  indexes: TableIndexInfo[];
1201
1214
  }
1215
+ interface TablesIndexesResult {
1216
+ indexesByTable: Record<string, TableIndexInfo[]>;
1217
+ }
1202
1218
  interface ColumnMeta {
1203
1219
  isStorage?: boolean;
1204
1220
  name: string;
@@ -1229,12 +1245,13 @@ interface AdvisoriesResult {
1229
1245
  advisories: AdvisoryFinding[];
1230
1246
  }
1231
1247
  interface AdvisorProcedure {
1232
- callsMail: boolean;
1248
+ analyzableBody?: boolean;
1249
+ callsMail?: boolean;
1233
1250
  emitsEvent?: boolean;
1234
1251
  exempt?: boolean;
1235
1252
  exemptReason?: string;
1236
1253
  exportName: string;
1237
- fanOut: boolean;
1254
+ fanOut?: boolean;
1238
1255
  file: string;
1239
1256
  handlesErrors?: boolean;
1240
1257
  hasEmailArg?: boolean;
@@ -1242,15 +1259,15 @@ interface AdvisorProcedure {
1242
1259
  reachesOutbound?: boolean;
1243
1260
  runsAiGeneration?: boolean;
1244
1261
  throwsBareError?: boolean;
1245
- unboundedAiGeneration: boolean;
1262
+ unboundedAiGeneration?: boolean;
1246
1263
  usesCaptcha: boolean;
1247
1264
  usesEmailGate: boolean;
1248
- usesInsertManyUnsafe: boolean;
1265
+ usesInsertManyUnsafe?: boolean;
1249
1266
  usesMask: boolean;
1250
1267
  usesRateLimit: boolean;
1251
1268
  usesRls: boolean;
1252
1269
  visibility: "internal" | "public";
1253
- writesUserTable: boolean;
1270
+ writesUserTable?: boolean;
1254
1271
  }
1255
1272
  interface AdvisorProceduresResult {
1256
1273
  procedures: AdvisorProcedure[];
@@ -1878,7 +1895,8 @@ interface GuardableSchema {
1878
1895
  }>;
1879
1896
  }
1880
1897
  type TableOfId = (id: string, expectedTable?: string) => Promise<string | undefined> | string | undefined;
1881
- declare const guardWriter: <W>(raw: W, schema: GuardableSchema, tableOfId: TableOfId) => W;
1898
+ type TablesOfIds = (ids: ReadonlyArray<string>, expectedTable?: string) => Promise<ReadonlyMap<string, string>> | ReadonlyMap<string, string>;
1899
+ declare const guardWriter: <W>(raw: W, schema: GuardableSchema, tableOfId: TableOfId, tablesOfIds?: TablesOfIds) => W;
1882
1900
  declare const SCHEMA_HISTORY_MAX_VERSIONS = 50;
1883
1901
  interface SchemaVersionRow {
1884
1902
  appliedAt: number;
@@ -1940,7 +1958,7 @@ interface DrainableSink {
1940
1958
  readonly bufferedAmount?: unknown;
1941
1959
  }
1942
1960
  declare const trySendFrame: (ws: FrameSink, frame: string) => boolean;
1943
- declare const sendDeltaFrames: (ws: FrameSink, subId: string, deltaFrames: ReadonlyArray<string>, cursorSuffix: string) => boolean;
1961
+ declare const sendDeltaFrames: (ws: FrameSink, subId: string, deltaFrames: ReadonlyArray<string>, cursorSuffix: string, lastMutationId?: number) => boolean;
1944
1962
  declare const awaitWsDrain: (ws: DrainableSink) => Promise<void>;
1945
1963
  interface SubscriptionReadFootprint {
1946
1964
  ranges?: Map<string, KeyRange[]>;
@@ -1977,4 +1995,4 @@ interface WhereSqlStrategy {
1977
1995
  serialize: SerializeValue;
1978
1996
  }
1979
1997
  declare const compileWhereSql: (where: WhereInput | undefined, strategy: WhereSqlStrategy) => SQL | undefined;
1980
- 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 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 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, 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 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 SearchFilterBuilderLike, type SearchIndexDefinitionLike, type SelectMatchingIdsOptions, type ServerDefaultContextLike, type SettingEntry, type SettingKind, type SettingsResult, type ShapePokePart, type ShapeRow, type ShapeRowOp, type ShapeSubscriptionQuery, type ShardRankPageResult, ShardRunner, type ShardRunnerOptions, 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 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, buildSeekBeforeWhere, buildSeekWhere, buildSettings, bumpCdcEpoch, clampPromotionThresholds, clearCapturedMail, clearQueueMessages, coerceAggregateNumber, compileWhereSql, computeRankPage, containsRelationPredicate, coveringGeohashes, createCompanionSync, createDependencyTracker, createFanoutCounters, createIndexSql, createReadFootprint, createRelayLink, createShardCtxDb, createSystemReader, decodeCursor, deleteGlobalShapeSnapshot, deleteGlobalShapeSnapshotsForConnection, depKey, diffExternalSource, diffGlobalMembership, distinctValues, encodeAggregateKey, encodeCursor, encodeGeohash, encodePartitionKey, encodeRowsPatch, ensureAuditTable, ensureMailTable, exportShardRows, exportShardTable, facetColumn, fanOutScalarCounts, findStorageReferences, foldAggregateTally, geoTableName, guardWriter, 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, relayCountFor, renderSql, 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 };
1998
+ 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 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, 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 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 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, buildSeekBeforeWhere, buildSeekWhere, buildSettings, bumpCdcEpoch, clampPromotionThresholds, clearCapturedMail, clearQueueMessages, coerceAggregateNumber, compileWhereSql, computeRankPage, containsRelationPredicate, coveringGeohashes, createCompanionSync, createDependencyTracker, createFanoutCounters, createIndexSql, createReadFootprint, createRelayLink, createShardCtxDb, createSystemReader, decodeCursor, deleteGlobalShapeSnapshot, deleteGlobalShapeSnapshotsForConnection, depKey, diffExternalSource, diffGlobalMembership, distinctValues, encodeAggregateKey, encodeCursor, encodeGeohash, encodePartitionKey, encodeRowsPatch, ensureAuditTable, ensureMailTable, exportShardRows, exportShardTable, facetColumn, fanOutScalarCounts, findStorageReferences, foldAggregateTally, geoTableName, guardWriter, 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, relayCountFor, renderSql, 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 };
package/dist/index.mjs CHANGED
@@ -1 +1 @@
1
- import{exportShardRows as o,exportShardTable as a,importShardRows as t,parseExportShardArgs as n,parseImportShardArgs as l,selectExportTables as i,validateImportRow as s}from"./packem_shared/exportShardRows-kt42wijd.mjs";import{AGGREGATE_SQL_FUNCTION as d,aggregateSqlFunction as p,matchesStaticWhere as c,normalizeCountArgument as S,throwingScheduler as u}from"./packem_shared/AGGREGATE_SQL_FUNCTION-QYaiuty4.mjs";import{aggregateTableName as f,coerceAggregateNumber as T,encodeAggregateKey as g,foldAggregateTally as h,readAggregateValue as A}from"./packem_shared/aggregateTableName-G-eXyjcz.mjs";import{CountRlsUnsupportedError as C,mergeWhere as I,planAggregateLookup as _,selectIndexForAggregate as R,selectIndexForCount as L,selectIndexForGroupBy as b}from"./packem_shared/CountRlsUnsupportedError-B2WKJD9v.mjs";import{AUDIT_LOG_TABLE as N,appendAuditEntry as M,ensureAuditTable as F,readAuditLog as O}from"./packem_shared/AUDIT_LOG_TABLE-CaA0jL0L.mjs";import{NotUniqueError as P,assertValidClientId as k,createShardCtxDb as B,normalizeIdStructurally as G}from"./packem_shared/NotUniqueError-iGKd9wRR.mjs";import{backfillAggregateIndexes as w,backfillRankIndexes as K,backfillSearchIndexes as q,backfillSearchIndexesForTable as W}from"./packem_shared/backfillAggregateIndexes-BHiewuB-.mjs";import{CDC_LOG_TABLE as z,CDC_META_TABLE as V,appendCdcChange as H,applyCdcChanges as X,bumpCdcEpoch as Q,migrateCdcLog as Y,migrateCdcMeta as j,minCdcSeq as J,readCdcChanges as Z,readCdcCursor as $,readCdcEpoch as ee,trimCdcChanges as re}from"./packem_shared/CDC_LOG_TABLE-BnqlH2eZ.mjs";import{CLIENT_WATERMARK_TABLE as ae,advanceClientWatermark as te,migrateClientWatermark as ne,readClientWatermark as le}from"./packem_shared/CLIENT_WATERMARK_TABLE-CXsSLU8D.mjs";import{createCompanionSync as se}from"./packem_shared/createCompanionSync-DWK0Vlg1.mjs";import{GLOBAL_SHAPE_SNAPSHOT_TABLE as de,deleteGlobalShapeSnapshot as pe,deleteGlobalShapeSnapshotsForConnection as ce,migrateGlobalShapeSnapshot as Se,readGlobalShapeSnapshot as ue,writeGlobalShapeSnapshot as xe}from"./packem_shared/GLOBAL_SHAPE_SNAPSHOT_TABLE-DX-6-gBP.mjs";import{IDEMPOTENCY_TABLE as Te,migrateIdempotency as ge,readIdempotent as he,trimIdempotent as Ae,writeIdempotent as Ee}from"./packem_shared/IDEMPOTENCY_TABLE-DjkEMp6w.mjs";import{computeRankPage as Ie,hydrateDocsById as _e}from"./packem_shared/computeRankPage-IUSS-zIB.mjs";import{SEARCH_STATE_TABLE as Le,migrateSearchState as be,readSearchBackfillState as ye,writeSearchBackfillState as Ne}from"./packem_shared/SEARCH_STATE_TABLE-eLN8U5tz.mjs";import{selectShapeMemberIds as Fe,selectShapeRows as Oe}from"./packem_shared/selectShapeMemberIds-DvE7K6zG.mjs";import{DATA_MIGRATION_STATE_TABLE as Pe,readMigrationStatus as ke,runDataMigration as Be}from"./packem_shared/DATA_MIGRATION_STATE_TABLE-BZMVrLcy.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-GKR3y97k.mjs";import{AGG_COUNT as He,AGG_KEY as Xe,AGG_VALUE as Qe,DOC_COLUMN as Ye,aggUpsertSql as je,createIndexSql as Je,geoTableName as Ze,isFtsAvailable as $e,jsonPath as er,jsonPathSql as rr,qualifiedJsonPath as or,qualifiedJsonPathSql as ar,quoteIdentifier as tr,rowToDocument as nr,tableColumns as lr,tryRowToDocument as ir}from"./packem_shared/AGG_COUNT-BWXe3gtQ.mjs";import{param as mr,renderSql as dr}from"./packem_shared/param-B5lF5Jd9.mjs";import{diffExternalSource as cr}from"./packem_shared/diffExternalSource-DMpkJta1.mjs";import{liftSourceId as ur,normalizeSourceDocument as xr,normalizeSourceValue as fr}from"./packem_shared/liftSourceId-DApAbu7Q.mjs";import{materializeExternalRows as gr,materializeExternalRowsIncremental as hr,readExternalSourceBaseline as Ar,runExternalSourceTick as Er}from"./packem_shared/materializeExternalRows-DOQJV9p2.mjs";import{isSoftDeleted as Ir,isSourceDue as _r,pullExternalSourceIncrementalTick as Rr,pullExternalSourceTick as Lr}from"./packem_shared/isSoftDeleted-B-SXkGUo.mjs";import{GEO_DEFAULT_PRECISION as yr,boundingBoxCenter as Nr,boundingBoxGeohashes as Mr,coveringGeohashes as Fr,encodeGeohash as Or,haversineMeters as Dr,pointInBoundingBox as Pr}from"./packem_shared/GEO_DEFAULT_PRECISION-okRCkZ6r.mjs";import{ADMIN_FUNCTIONS as Br,ADMIN_FUNCTION_PREFIX as Gr,DEFAULT_FANOUT_TOPIC_LIMIT as Ur,FLAGS_FUNCTION_PREFIX as wr,MAX_PAGE_SIZE as Kr,RELATION_FUNCTION_PREFIX as qr,createFanoutCounters as Wr,facetColumn as vr,findStorageReferences as zr,listTables as Vr,readTablePage as Hr,recordFanoutPass as Xr,selectMatchingIds as Qr,summarizeFanoutTopics as Yr,summarizeSubscriptions as jr}from"./packem_shared/ADMIN_FUNCTIONS-B0xlQJ4w.mjs";import{MAIL_RETENTION as Zr,MAIL_TABLE as $r,clearCapturedMail as eo,ensureMailTable as ro,readCapturedMail as oo,recordCapturedMail as ao}from"./packem_shared/MAIL_RETENTION-KmozO2NQ.mjs";import{NotFoundError as no}from"./packem_shared/NotFoundError-BhF7FeFr.mjs";import{armRestore as io,readBookmark as so}from"./packem_shared/armRestore-BNzdvQ_o.mjs";import{applySelect as po,buildSeekBeforeWhere as co,buildSeekWhere as So,decodeCursor as uo,encodeCursor as xo,normalizeOrderKeys as fo,softDeleteScope as To}from"./packem_shared/applySelect-B0CF8T7y.mjs";import{QUEUE_TABLE as ho,clearQueueMessages as Ao,isLossyBody as Eo,readQueueMessageById as Co,readQueueMessages as Io,recordQueueMessages as _o}from"./packem_shared/QUEUE_TABLE-DYCDvzTG.mjs";import{RANK_TIEBREAK as Lo,encodePartitionKey as bo,matchesRankStaticWhere as yo,rankKeyFromDoc as No,rankTableName as Mo,resolveRankPartition as Fo,sortColumnName as Oo}from"./packem_shared/RANK_TIEBREAK-9NU5s_mi.mjs";import{ReactiveCache as Po,reactiveCacheKey as ko}from"./packem_shared/ReactiveCache-CF21t8IB.mjs";import{createReadFootprint as Go}from"./packem_shared/createReadFootprint-DIrrxRTE.mjs";import{buildIndexRange as wo,indexKeysForRow as Ko,keysTouchRanges as qo}from"./packem_shared/buildIndexRange-DIjFVgeO.mjs";import{DEFAULT_MAX_RELATION_KEYS as vo,assertFlatPredicate as zo,assertShapeShardable as Vo,containsRelationPredicate as Ho,isRelationPredicate as Xo,resolveRelationPredicates as Qo}from"./packem_shared/DEFAULT_MAX_RELATION_KEYS-bq00btqV.mjs";import{applyOnDelete as jo,distinctValues as Jo,fanOutScalarCounts as Zo,resolveWith as $o,runRowValidators as ea}from"./packem_shared/applyOnDelete-uFRC5p1d.mjs";import{DEFAULT_PROMOTION_THRESHOLDS as oa,clampPromotionThresholds as aa,nextPromotionState as ta,relayCountFor as na,shapeRoutingKey as la}from"./packem_shared/DEFAULT_PROMOTION_THRESHOLDS-Dteg0sZF.mjs";import{DEFAULT_MAX_RELAYS as sa,OwnerRelay as ma,RelayMember as da,createRelayLink as pa}from"./packem_shared/DEFAULT_MAX_RELAYS-CnCyh6oX.mjs";import{RLS_UNWRAP_SYMBOL as Sa,RlsRequiredError as ua,guardWriter as xa}from"./packem_shared/RLS_UNWRAP_SYMBOL-C6_WX3dG.mjs";import{SCHEMA_HISTORY_MAX_VERSIONS as Ta,readSchemaHistory as ga,readSchemaVersion as ha,recordSchemaVersion as Aa}from"./packem_shared/SCHEMA_HISTORY_MAX_VERSIONS-CHXz6p_z.mjs";import{serializeSqlValue as Ca}from"./packem_shared/serializeSqlValue-DnpyaLcw.mjs";import{buildSettings as _a,isDevEnvironment as Ra}from"./packem_shared/buildSettings-DT18_DkX.mjs";import{buildPokeFrames as ba,diffGlobalMembership as ya,encodeRowsPatch as Na,projectColumns as Ma}from"./packem_shared/buildPokeFrames-DaPpm5Ss.mjs";import{ShardRunner as Oa}from"./packem_shared/ShardRunner-DIqVdWtk.mjs";import{runSocketPool as Pa}from"./packem_shared/runSocketPool-DPQLVyWF.mjs";import{MAX_SQL_ROWS as Ba,assertReadonly as Ga,lintReadonlySql as Ua,runReadonlySql as wa}from"./packem_shared/MAX_SQL_ROWS-nMwkxv5f.mjs";import{awaitWsDrain as qa,sendDeltaFrames as Wa,subscriptionListDeltas as va,trySendFrame as za}from"./packem_shared/awaitWsDrain-Dk50ISgE.mjs";import{mergeChangedKeys as Ha,recordChangedKeys as Xa,writeTouchesMemo as Qa}from"./packem_shared/mergeChangedKeys-CvSHlkv-.mjs";import{createSystemReader as ja}from"./packem_shared/createSystemReader-DcDcrtM3.mjs";import{ConflictError as Za}from"./packem_shared/ConflictError-C8GtJmjS.mjs";import{DEFAULT_TRANSACTION_LIMITS as et,TransactionHeadroomTracker as rt}from"./packem_shared/DEFAULT_TRANSACTION_LIMITS--TtB8Gpo.mjs";import{hasTrigger as at,runTriggers as tt}from"./packem_shared/hasTrigger-CbkOHExZ.mjs";import{selectExpiredIds as lt}from"./packem_shared/selectExpiredIds-FzhIEeG1.mjs";import{compileWhereSql as st}from"./packem_shared/compileWhereSql-BLcfs4QW.mjs";import{RELATION_EXISTS_KEY as dt}from"./packem_shared/RELATION_EXISTS_KEY-BaqSIFU1.mjs";import{runShardMigrations as ct}from"./packem_shared/runShardMigrations-CPxqCh3O.mjs";import{stableStringify as ut}from"./packem_shared/stableStringify-BjLh4gvA.mjs";import{stableWireKey as ft}from"./packem_shared/stableWireKey-YEHLaX6X.mjs";export{Br as ADMIN_FUNCTIONS,Gr as ADMIN_FUNCTION_PREFIX,d as AGGREGATE_SQL_FUNCTION,He as AGG_COUNT,Xe as AGG_KEY,Qe as AGG_VALUE,N as AUDIT_LOG_TABLE,z as CDC_LOG_TABLE,V as CDC_META_TABLE,ae as CLIENT_WATERMARK_TABLE,Za as ConflictError,C as CountRlsUnsupportedError,Pe as DATA_MIGRATION_STATE_TABLE,Ur as DEFAULT_FANOUT_TOPIC_LIMIT,vo as DEFAULT_MAX_RELATION_KEYS,sa as DEFAULT_MAX_RELAYS,oa as DEFAULT_PROMOTION_THRESHOLDS,et as DEFAULT_TRANSACTION_LIMITS,Ye as DOC_COLUMN,wr as FLAGS_FUNCTION_PREFIX,yr as GEO_DEFAULT_PRECISION,de as GLOBAL_SHAPE_SNAPSHOT_TABLE,Te as IDEMPOTENCY_TABLE,Zr as MAIL_RETENTION,$r as MAIL_TABLE,Kr as MAX_PAGE_SIZE,Ba as MAX_SQL_ROWS,no as NotFoundError,P as NotUniqueError,ma as OwnerRelay,ho as QUEUE_TABLE,Lo as RANK_TIEBREAK,dt as RELATION_EXISTS_KEY,qr as RELATION_FUNCTION_PREFIX,Sa as RLS_UNWRAP_SYMBOL,Po as ReactiveCache,da as RelayMember,ua as RlsRequiredError,Ue as SCAN_DEP,Ta as SCHEMA_HISTORY_MAX_VERSIONS,Le as SEARCH_STATE_TABLE,Oa as ShardRunner,rt as TransactionHeadroomTracker,te as advanceClientWatermark,je as aggUpsertSql,p as aggregateSqlFunction,f as aggregateTableName,M as appendAuditEntry,H as appendCdcChange,X as applyCdcChanges,jo as applyOnDelete,po as applySelect,io as armRestore,zo as assertFlatPredicate,Ga as assertReadonly,Vo as assertShapeShardable,k as assertValidClientId,qa as awaitWsDrain,w as backfillAggregateIndexes,K as backfillRankIndexes,q as backfillSearchIndexes,W as backfillSearchIndexesForTable,Nr as boundingBoxCenter,Mr as boundingBoxGeohashes,wo as buildIndexRange,ba as buildPokeFrames,co as buildSeekBeforeWhere,So as buildSeekWhere,_a as buildSettings,Q as bumpCdcEpoch,aa as clampPromotionThresholds,eo as clearCapturedMail,Ao as clearQueueMessages,T as coerceAggregateNumber,st as compileWhereSql,Ie as computeRankPage,Ho as containsRelationPredicate,Fr as coveringGeohashes,se as createCompanionSync,we as createDependencyTracker,Wr as createFanoutCounters,Je as createIndexSql,Go as createReadFootprint,pa as createRelayLink,B as createShardCtxDb,ja as createSystemReader,uo as decodeCursor,pe as deleteGlobalShapeSnapshot,ce as deleteGlobalShapeSnapshotsForConnection,Ke as depKey,cr as diffExternalSource,ya as diffGlobalMembership,Jo as distinctValues,g as encodeAggregateKey,xo as encodeCursor,Or as encodeGeohash,bo as encodePartitionKey,Na as encodeRowsPatch,F as ensureAuditTable,ro as ensureMailTable,o as exportShardRows,a as exportShardTable,vr as facetColumn,Zo as fanOutScalarCounts,zr as findStorageReferences,h as foldAggregateTally,Ze as geoTableName,xa as guardWriter,at as hasTrigger,Dr as haversineMeters,_e as hydrateDocsById,t as importShardRows,Ko as indexKeysForRow,Ra as isDevEnvironment,$e as isFtsAvailable,Eo as isLossyBody,Xo as isRelationPredicate,Ir as isSoftDeleted,_r as isSourceDue,er as jsonPath,rr as jsonPathSql,qo as keysTouchRanges,ur as liftSourceId,Ua as lintReadonlySql,Vr as listTables,yo as matchesRankStaticWhere,c as matchesStaticWhere,gr as materializeExternalRows,hr as materializeExternalRowsIncremental,Ha as mergeChangedKeys,I as mergeWhere,Y as migrateCdcLog,j as migrateCdcMeta,ne as migrateClientWatermark,Se as migrateGlobalShapeSnapshot,ge as migrateIdempotency,be as migrateSearchState,J as minCdcSeq,ta as nextPromotionState,S as normalizeCountArgument,G as normalizeIdStructurally,fo as normalizeOrderKeys,xr as normalizeSourceDocument,fr as normalizeSourceValue,mr as param,n as parseExportShardArgs,l as parseImportShardArgs,_ as planAggregateLookup,Pr as pointInBoundingBox,Ma as projectColumns,Rr as pullExternalSourceIncrementalTick,Lr as pullExternalSourceTick,or as qualifiedJsonPath,ar as qualifiedJsonPathSql,tr as quoteIdentifier,No as rankKeyFromDoc,Mo as rankTableName,ko as reactiveCacheKey,A as readAggregateValue,O as readAuditLog,so as readBookmark,oo as readCapturedMail,Z as readCdcChanges,$ as readCdcCursor,ee as readCdcEpoch,le as readClientWatermark,Ar as readExternalSourceBaseline,ue as readGlobalShapeSnapshot,he as readIdempotent,ke as readMigrationStatus,Co as readQueueMessageById,Io as readQueueMessages,ga as readSchemaHistory,ha as readSchemaVersion,ye as readSearchBackfillState,Hr as readTablePage,ao as recordCapturedMail,Xa as recordChangedKeys,Xr as recordFanoutPass,_o as recordQueueMessages,Aa as recordSchemaVersion,na as relayCountFor,dr as renderSql,Fo as resolveRankPartition,Qo as resolveRelationPredicates,$o as resolveWith,nr as rowToDocument,Be as runDataMigration,ve as runDrizzle,Er as runExternalSourceTick,wa as runReadonlySql,ea as runRowValidators,ct as runShardMigrations,Pa as runSocketPool,ze as runSql,tt as runTriggers,lt as selectExpiredIds,i as selectExportTables,R as selectIndexForAggregate,L as selectIndexForCount,b as selectIndexForGroupBy,Qr as selectMatchingIds,Fe as selectShapeMemberIds,Oe as selectShapeRows,Wa as sendDeltaFrames,Ca as serializeSqlValue,la as shapeRoutingKey,To as softDeleteScope,Oo as sortColumnName,ut as stableStringify,ft as stableWireKey,va as subscriptionListDeltas,Yr as summarizeFanoutTopics,jr as summarizeSubscriptions,lr as tableColumns,qe as tableFromDepKey,u as throwingScheduler,re as trimCdcChanges,Ae as trimIdempotent,ir as tryRowToDocument,za as trySendFrame,s as validateImportRow,xe as writeGlobalShapeSnapshot,Ee as writeIdempotent,Ne as writeSearchBackfillState,Qa as writeTouchesMemo};
1
+ import{exportShardRows as o,exportShardTable as a,importShardRows as t,parseExportShardArgs as n,parseImportShardArgs as l,selectExportTables as i,validateImportRow as s}from"./packem_shared/exportShardRows-kt42wijd.mjs";import{AGGREGATE_SQL_FUNCTION as d,aggregateSqlFunction as p,matchesStaticWhere as c,normalizeCountArgument as S,throwingScheduler as u}from"./packem_shared/AGGREGATE_SQL_FUNCTION-QYaiuty4.mjs";import{aggregateTableName as f,coerceAggregateNumber as T,encodeAggregateKey as g,foldAggregateTally as h,readAggregateValue as A}from"./packem_shared/aggregateTableName-G-eXyjcz.mjs";import{CountRlsUnsupportedError as C,mergeWhere as I,planAggregateLookup as _,selectIndexForAggregate as R,selectIndexForCount as L,selectIndexForGroupBy as b}from"./packem_shared/CountRlsUnsupportedError-B2WKJD9v.mjs";import{AUDIT_LOG_TABLE as N,appendAuditEntry as M,ensureAuditTable as F,readAuditLog as O}from"./packem_shared/AUDIT_LOG_TABLE-CaA0jL0L.mjs";import{NotUniqueError as P,assertValidClientId as k,createShardCtxDb as B,normalizeIdStructurally as G}from"./packem_shared/NotUniqueError-Qrtwm7S6.mjs";import{backfillAggregateIndexes as w,backfillRankIndexes as K,backfillSearchIndexes as q,backfillSearchIndexesForTable as W}from"./packem_shared/backfillAggregateIndexes-BHiewuB-.mjs";import{CDC_LOG_TABLE as z,CDC_META_TABLE as V,appendCdcChange as H,applyCdcChanges as X,bumpCdcEpoch as Q,migrateCdcLog as Y,migrateCdcMeta as j,minCdcSeq as J,readCdcChanges as Z,readCdcCursor as $,readCdcEpoch as ee,trimCdcChanges as re}from"./packem_shared/CDC_LOG_TABLE-BnqlH2eZ.mjs";import{CLIENT_WATERMARK_TABLE as ae,advanceClientWatermark as te,migrateClientWatermark as ne,readClientWatermark as le}from"./packem_shared/CLIENT_WATERMARK_TABLE-CXsSLU8D.mjs";import{createCompanionSync as se}from"./packem_shared/createCompanionSync-DWK0Vlg1.mjs";import{GLOBAL_SHAPE_SNAPSHOT_TABLE as de,deleteGlobalShapeSnapshot as pe,deleteGlobalShapeSnapshotsForConnection as ce,migrateGlobalShapeSnapshot as Se,readGlobalShapeSnapshot as ue,writeGlobalShapeSnapshot as xe}from"./packem_shared/GLOBAL_SHAPE_SNAPSHOT_TABLE-DX-6-gBP.mjs";import{IDEMPOTENCY_TABLE as Te,migrateIdempotency as ge,readIdempotent as he,trimIdempotent as Ae,writeIdempotent as Ee}from"./packem_shared/IDEMPOTENCY_TABLE-DjkEMp6w.mjs";import{computeRankPage as Ie,hydrateDocsById as _e}from"./packem_shared/computeRankPage-IUSS-zIB.mjs";import{SEARCH_STATE_TABLE as Le,migrateSearchState as be,readSearchBackfillState as ye,writeSearchBackfillState as Ne}from"./packem_shared/SEARCH_STATE_TABLE-eLN8U5tz.mjs";import{selectShapeMemberIds as Fe,selectShapeRows as Oe}from"./packem_shared/selectShapeMemberIds-DvE7K6zG.mjs";import{DATA_MIGRATION_STATE_TABLE as Pe,readMigrationStatus as ke,runDataMigration as Be}from"./packem_shared/DATA_MIGRATION_STATE_TABLE-BZMVrLcy.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-GKR3y97k.mjs";import{AGG_COUNT as He,AGG_KEY as Xe,AGG_VALUE as Qe,DOC_COLUMN as Ye,aggUpsertSql as je,createIndexSql as Je,geoTableName as Ze,isFtsAvailable as $e,jsonPath as er,jsonPathSql as rr,qualifiedJsonPath as or,qualifiedJsonPathSql as ar,quoteIdentifier as tr,rowToDocument as nr,tableColumns as lr,tryRowToDocument as ir}from"./packem_shared/AGG_COUNT-BWXe3gtQ.mjs";import{param as mr,renderSql as dr}from"./packem_shared/param-B5lF5Jd9.mjs";import{diffExternalSource as cr}from"./packem_shared/diffExternalSource-DMpkJta1.mjs";import{liftSourceId as ur,normalizeSourceDocument as xr,normalizeSourceValue as fr}from"./packem_shared/liftSourceId-DApAbu7Q.mjs";import{materializeExternalRows as gr,materializeExternalRowsIncremental as hr,readExternalSourceBaseline as Ar,runExternalSourceTick as Er}from"./packem_shared/materializeExternalRows-DOQJV9p2.mjs";import{isSoftDeleted as Ir,isSourceDue as _r,pullExternalSourceIncrementalTick as Rr,pullExternalSourceTick as Lr}from"./packem_shared/isSoftDeleted-B-SXkGUo.mjs";import{GEO_DEFAULT_PRECISION as yr,boundingBoxCenter as Nr,boundingBoxGeohashes as Mr,coveringGeohashes as Fr,encodeGeohash as Or,haversineMeters as Dr,pointInBoundingBox as Pr}from"./packem_shared/GEO_DEFAULT_PRECISION-okRCkZ6r.mjs";import{ADMIN_FUNCTIONS as Br,ADMIN_FUNCTION_PREFIX as Gr,DEFAULT_FANOUT_TOPIC_LIMIT as Ur,FLAGS_FUNCTION_PREFIX as wr,MAX_PAGE_SIZE as Kr,RELATION_FUNCTION_PREFIX as qr,createFanoutCounters as Wr,facetColumn as vr,findStorageReferences as zr,listTables as Vr,readTablePage as Hr,recordFanoutPass as Xr,selectMatchingIds as Qr,summarizeFanoutTopics as Yr,summarizeSubscriptions as jr}from"./packem_shared/ADMIN_FUNCTIONS-vj2G8OR6.mjs";import{MAIL_RETENTION as Zr,MAIL_TABLE as $r,clearCapturedMail as eo,ensureMailTable as ro,readCapturedMail as oo,recordCapturedMail as ao}from"./packem_shared/MAIL_RETENTION-KmozO2NQ.mjs";import{NotFoundError as no}from"./packem_shared/NotFoundError-BhF7FeFr.mjs";import{armRestore as io,readBookmark as so}from"./packem_shared/armRestore-BNzdvQ_o.mjs";import{applySelect as po,buildSeekBeforeWhere as co,buildSeekWhere as So,decodeCursor as uo,encodeCursor as xo,normalizeOrderKeys as fo,softDeleteScope as To}from"./packem_shared/applySelect-B0CF8T7y.mjs";import{QUEUE_TABLE as ho,clearQueueMessages as Ao,isLossyBody as Eo,readQueueMessageById as Co,readQueueMessages as Io,recordQueueMessages as _o}from"./packem_shared/QUEUE_TABLE-DYCDvzTG.mjs";import{RANK_TIEBREAK as Lo,encodePartitionKey as bo,matchesRankStaticWhere as yo,rankKeyFromDoc as No,rankTableName as Mo,resolveRankPartition as Fo,sortColumnName as Oo}from"./packem_shared/RANK_TIEBREAK-9NU5s_mi.mjs";import{ReactiveCache as Po,reactiveCacheKey as ko}from"./packem_shared/ReactiveCache-C6QAa7MG.mjs";import{createReadFootprint as Go}from"./packem_shared/createReadFootprint-DIrrxRTE.mjs";import{buildIndexRange as wo,indexKeysForRow as Ko,keysTouchRanges as qo}from"./packem_shared/buildIndexRange-DFsdtPjD.mjs";import{DEFAULT_MAX_RELATION_KEYS as vo,assertFlatPredicate as zo,assertShapeShardable as Vo,containsRelationPredicate as Ho,isRelationPredicate as Xo,resolveRelationPredicates as Qo}from"./packem_shared/DEFAULT_MAX_RELATION_KEYS-bq00btqV.mjs";import{applyOnDelete as jo,distinctValues as Jo,fanOutScalarCounts as Zo,resolveWith as $o,runRowValidators as ea}from"./packem_shared/applyOnDelete-uFRC5p1d.mjs";import{DEFAULT_PROMOTION_THRESHOLDS as oa,clampPromotionThresholds as aa,nextPromotionState as ta,relayCountFor as na,shapeRoutingKey as la}from"./packem_shared/DEFAULT_PROMOTION_THRESHOLDS-Dteg0sZF.mjs";import{DEFAULT_MAX_RELAYS as sa,OwnerRelay as ma,RelayMember as da,createRelayLink as pa}from"./packem_shared/DEFAULT_MAX_RELAYS-D0oc40p6.mjs";import{RLS_UNWRAP_SYMBOL as Sa,RlsRequiredError as ua,guardWriter as xa}from"./packem_shared/RLS_UNWRAP_SYMBOL-CBYPlYBb.mjs";import{SCHEMA_HISTORY_MAX_VERSIONS as Ta,readSchemaHistory as ga,readSchemaVersion as ha,recordSchemaVersion as Aa}from"./packem_shared/SCHEMA_HISTORY_MAX_VERSIONS-CHXz6p_z.mjs";import{serializeSqlValue as Ca}from"./packem_shared/serializeSqlValue-DnpyaLcw.mjs";import{buildSettings as _a,isDevEnvironment as Ra}from"./packem_shared/buildSettings-DT18_DkX.mjs";import{buildPokeFrames as ba,diffGlobalMembership as ya,encodeRowsPatch as Na,projectColumns as Ma}from"./packem_shared/buildPokeFrames-DaPpm5Ss.mjs";import{ShardRunner as Oa}from"./packem_shared/ShardRunner-DIqVdWtk.mjs";import{runSocketPool as Pa}from"./packem_shared/runSocketPool-DPQLVyWF.mjs";import{MAX_SQL_ROWS as Ba,assertReadonly as Ga,lintReadonlySql as Ua,runReadonlySql as wa}from"./packem_shared/MAX_SQL_ROWS-nMwkxv5f.mjs";import{awaitWsDrain as qa,sendDeltaFrames as Wa,subscriptionListDeltas as va,trySendFrame as za}from"./packem_shared/awaitWsDrain-CCZ-8wjm.mjs";import{mergeChangedKeys as Ha,recordChangedKeys as Xa,writeTouchesMemo as Qa}from"./packem_shared/mergeChangedKeys-BXtUgIPW.mjs";import{createSystemReader as ja}from"./packem_shared/createSystemReader-DcDcrtM3.mjs";import{ConflictError as Za}from"./packem_shared/ConflictError-C8GtJmjS.mjs";import{DEFAULT_TRANSACTION_LIMITS as et,TransactionHeadroomTracker as rt}from"./packem_shared/DEFAULT_TRANSACTION_LIMITS-BH5q0Ror.mjs";import{hasTrigger as at,runTriggers as tt}from"./packem_shared/hasTrigger-CbkOHExZ.mjs";import{selectExpiredIds as lt}from"./packem_shared/selectExpiredIds-FzhIEeG1.mjs";import{compileWhereSql as st}from"./packem_shared/compileWhereSql-BLcfs4QW.mjs";import{RELATION_EXISTS_KEY as dt}from"./packem_shared/RELATION_EXISTS_KEY-BaqSIFU1.mjs";import{runShardMigrations as ct}from"./packem_shared/runShardMigrations-CPxqCh3O.mjs";import{stableStringify as ut}from"./packem_shared/stableStringify-BjLh4gvA.mjs";import{stableWireKey as ft}from"./packem_shared/stableWireKey-YEHLaX6X.mjs";export{Br as ADMIN_FUNCTIONS,Gr as ADMIN_FUNCTION_PREFIX,d as AGGREGATE_SQL_FUNCTION,He as AGG_COUNT,Xe as AGG_KEY,Qe as AGG_VALUE,N as AUDIT_LOG_TABLE,z as CDC_LOG_TABLE,V as CDC_META_TABLE,ae as CLIENT_WATERMARK_TABLE,Za as ConflictError,C as CountRlsUnsupportedError,Pe as DATA_MIGRATION_STATE_TABLE,Ur as DEFAULT_FANOUT_TOPIC_LIMIT,vo as DEFAULT_MAX_RELATION_KEYS,sa as DEFAULT_MAX_RELAYS,oa as DEFAULT_PROMOTION_THRESHOLDS,et as DEFAULT_TRANSACTION_LIMITS,Ye as DOC_COLUMN,wr as FLAGS_FUNCTION_PREFIX,yr as GEO_DEFAULT_PRECISION,de as GLOBAL_SHAPE_SNAPSHOT_TABLE,Te as IDEMPOTENCY_TABLE,Zr as MAIL_RETENTION,$r as MAIL_TABLE,Kr as MAX_PAGE_SIZE,Ba as MAX_SQL_ROWS,no as NotFoundError,P as NotUniqueError,ma as OwnerRelay,ho as QUEUE_TABLE,Lo as RANK_TIEBREAK,dt as RELATION_EXISTS_KEY,qr as RELATION_FUNCTION_PREFIX,Sa as RLS_UNWRAP_SYMBOL,Po as ReactiveCache,da as RelayMember,ua as RlsRequiredError,Ue as SCAN_DEP,Ta as SCHEMA_HISTORY_MAX_VERSIONS,Le as SEARCH_STATE_TABLE,Oa as ShardRunner,rt as TransactionHeadroomTracker,te as advanceClientWatermark,je as aggUpsertSql,p as aggregateSqlFunction,f as aggregateTableName,M as appendAuditEntry,H as appendCdcChange,X as applyCdcChanges,jo as applyOnDelete,po as applySelect,io as armRestore,zo as assertFlatPredicate,Ga as assertReadonly,Vo as assertShapeShardable,k as assertValidClientId,qa as awaitWsDrain,w as backfillAggregateIndexes,K as backfillRankIndexes,q as backfillSearchIndexes,W as backfillSearchIndexesForTable,Nr as boundingBoxCenter,Mr as boundingBoxGeohashes,wo as buildIndexRange,ba as buildPokeFrames,co as buildSeekBeforeWhere,So as buildSeekWhere,_a as buildSettings,Q as bumpCdcEpoch,aa as clampPromotionThresholds,eo as clearCapturedMail,Ao as clearQueueMessages,T as coerceAggregateNumber,st as compileWhereSql,Ie as computeRankPage,Ho as containsRelationPredicate,Fr as coveringGeohashes,se as createCompanionSync,we as createDependencyTracker,Wr as createFanoutCounters,Je as createIndexSql,Go as createReadFootprint,pa as createRelayLink,B as createShardCtxDb,ja as createSystemReader,uo as decodeCursor,pe as deleteGlobalShapeSnapshot,ce as deleteGlobalShapeSnapshotsForConnection,Ke as depKey,cr as diffExternalSource,ya as diffGlobalMembership,Jo as distinctValues,g as encodeAggregateKey,xo as encodeCursor,Or as encodeGeohash,bo as encodePartitionKey,Na as encodeRowsPatch,F as ensureAuditTable,ro as ensureMailTable,o as exportShardRows,a as exportShardTable,vr as facetColumn,Zo as fanOutScalarCounts,zr as findStorageReferences,h as foldAggregateTally,Ze as geoTableName,xa as guardWriter,at as hasTrigger,Dr as haversineMeters,_e as hydrateDocsById,t as importShardRows,Ko as indexKeysForRow,Ra as isDevEnvironment,$e as isFtsAvailable,Eo as isLossyBody,Xo as isRelationPredicate,Ir as isSoftDeleted,_r as isSourceDue,er as jsonPath,rr as jsonPathSql,qo as keysTouchRanges,ur as liftSourceId,Ua as lintReadonlySql,Vr as listTables,yo as matchesRankStaticWhere,c as matchesStaticWhere,gr as materializeExternalRows,hr as materializeExternalRowsIncremental,Ha as mergeChangedKeys,I as mergeWhere,Y as migrateCdcLog,j as migrateCdcMeta,ne as migrateClientWatermark,Se as migrateGlobalShapeSnapshot,ge as migrateIdempotency,be as migrateSearchState,J as minCdcSeq,ta as nextPromotionState,S as normalizeCountArgument,G as normalizeIdStructurally,fo as normalizeOrderKeys,xr as normalizeSourceDocument,fr as normalizeSourceValue,mr as param,n as parseExportShardArgs,l as parseImportShardArgs,_ as planAggregateLookup,Pr as pointInBoundingBox,Ma as projectColumns,Rr as pullExternalSourceIncrementalTick,Lr as pullExternalSourceTick,or as qualifiedJsonPath,ar as qualifiedJsonPathSql,tr as quoteIdentifier,No as rankKeyFromDoc,Mo as rankTableName,ko as reactiveCacheKey,A as readAggregateValue,O as readAuditLog,so as readBookmark,oo as readCapturedMail,Z as readCdcChanges,$ as readCdcCursor,ee as readCdcEpoch,le as readClientWatermark,Ar as readExternalSourceBaseline,ue as readGlobalShapeSnapshot,he as readIdempotent,ke as readMigrationStatus,Co as readQueueMessageById,Io as readQueueMessages,ga as readSchemaHistory,ha as readSchemaVersion,ye as readSearchBackfillState,Hr as readTablePage,ao as recordCapturedMail,Xa as recordChangedKeys,Xr as recordFanoutPass,_o as recordQueueMessages,Aa as recordSchemaVersion,na as relayCountFor,dr as renderSql,Fo as resolveRankPartition,Qo as resolveRelationPredicates,$o as resolveWith,nr as rowToDocument,Be as runDataMigration,ve as runDrizzle,Er as runExternalSourceTick,wa as runReadonlySql,ea as runRowValidators,ct as runShardMigrations,Pa as runSocketPool,ze as runSql,tt as runTriggers,lt as selectExpiredIds,i as selectExportTables,R as selectIndexForAggregate,L as selectIndexForCount,b as selectIndexForGroupBy,Qr as selectMatchingIds,Fe as selectShapeMemberIds,Oe as selectShapeRows,Wa as sendDeltaFrames,Ca as serializeSqlValue,la as shapeRoutingKey,To as softDeleteScope,Oo as sortColumnName,ut as stableStringify,ft as stableWireKey,va as subscriptionListDeltas,Yr as summarizeFanoutTopics,jr as summarizeSubscriptions,lr as tableColumns,qe as tableFromDepKey,u as throwingScheduler,re as trimCdcChanges,Ae as trimIdempotent,ir as tryRowToDocument,za as trySendFrame,s as validateImportRow,xe as writeGlobalShapeSnapshot,Ee as writeIdempotent,Ne as writeSearchBackfillState,Qa as writeTouchesMemo};
@@ -0,0 +1 @@
1
+ import{LunoraError as h}from"@lunora/errors";import{q as d}from"./quote-identifier-CGiYFBvY.mjs";const K="__lunora_admin__:",X="__lunora_relation__:",Y="__lunora_flags__:",z={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"},N=50,M=500,x=30,F=200,m="__doc__",w=e=>{try{const a=JSON.parse(e);return a!==null&&typeof a=="object"&&!Array.isArray(a)?a:void 0}catch{return}},L=(e,a)=>{if(!e.includes(m))return{columns:e,rows:a};const r=[];for(const s of a){const _=s[m],i=typeof _=="string"?w(_):void 0;if(i===void 0)return{columns:e,rows:a};const u=Object.fromEntries(Object.entries(s).filter(([l])=>l!==m));r.push({...u,...i})}const t=e.filter(s=>s!==m),n=[],o=new Set(t);for(const s of r)for(const _ of Object.keys(s))o.has(_)||(o.add(_),n.push(_));return{columns:[...t,...n],rows:r}},O=e=>e.replaceAll(/[\\%_]/g,a=>`\\${a}`),S=e=>e.startsWith("sqlite_")||e.startsWith("_cf_")||e.startsWith("__miniflare")||e.startsWith("__lunora")||e.includes("__fts_"),C=(e,a,r)=>Math.min(Math.max(e,a),r),k=(e,a)=>{const r=e.exec(`SELECT COUNT(*) AS c FROM ${a}`).one();return Number(r.c)},V=e=>{const a=e.exec("SELECT name FROM sqlite_master WHERE type = 'table' ORDER BY name").toArray(),r=[];for(const{name:t}of a)S(t)||r.push({name:t,rowCount:k(e,d(t))});return r},A=(e,a)=>e.exec("SELECT name FROM sqlite_master WHERE type = 'table' AND name = ? LIMIT 1",a).toArray().length>0,P={eq:"=",gt:">",gte:">=",lt:"<",lte:"<=",ne:"<>"},U=e=>typeof e=="string"?e:typeof e=="number"||typeof e=="boolean"?String(e):"",T=(e,a)=>{const r=a.includes(e),t=a.includes(m);if(!(!r&&!t))return r?{expression:d(e),params:[]}:{expression:`json_extract(${d(m)}, ?)`,params:[`$."${e.replaceAll('"','""')}"`]}},W=(e,a)=>{const r=T(e.column,a);if(r===void 0)return;const{expression:t,params:n}=r;return e.operator==="contains"?{params:[...n,`%${O(U(e.value))}%`],sql:String.raw`CAST(${t} AS TEXT) LIKE ? ESCAPE '\'`}:{params:[...n,e.value],sql:`${t} ${P[e.operator]} ?`}},D=/^(\d{4})(?:-(\d{2}))?(?:-(\d{2}))?$/u,q=e=>{const a=D.exec(e.trim());if(a===null)return;const r=Number(a[1]),t=a[2]===void 0?void 0:Number(a[2]),n=a[3]===void 0?void 0:Number(a[3]);if(t!==void 0&&(t<1||t>12)||n!==void 0&&(n<1||n>31)||r<100)return;const o=Date.UTC(r,(t??1)-1,n??1);if(n!==void 0&&new Date(o).getUTCDate()!==n)return;let s;return n!==void 0?s=Date.UTC(r,t===void 0?0:t-1,n+1):t===void 0?s=Date.UTC(r+1,0,1):s=Date.UTC(r,t,1),{from:o,to:s}},v=(e,a,r)=>{const t=[],n=[];if(a!==""&&e.length>0){const o=`%${O(a)}%`,s=e.map(i=>String.raw`CAST(${d(i)} AS TEXT) LIKE ? ESCAPE '\'`);n.push(...e.map(()=>o));const _=q(a);if(_!==void 0)for(const i of e)s.push(`(${d(i)} >= ? AND ${d(i)} < ?)`),n.push(_.from,_.to);t.push(`(${s.join(" OR ")})`)}for(const o of r??[]){const s=W(o,e);s!==void 0&&(t.push(`(${s.sql})`),n.push(...s.params))}return t.length===0?void 0:{parameters:n,where:t.join(" AND ")}},Q=(e,a)=>{if(e===void 0)return;const r=T(e.column,a);if(r===void 0)return;const t=e.direction==="desc"?"DESC":"ASC";return{params:r.params,sql:`${r.expression} ${t}`}},J=(e,a)=>{const{table:r}=a;if(S(r)||!A(e,r))throw new h("UNKNOWN_TABLE",`unknown table: ${r}`,{status:404});const t=C(Math.trunc(a.limit??N),1,M),n=Math.max(0,Math.trunc(a.offset??0)),o=d(r),s=e.exec(`PRAGMA table_info(${o})`).toArray().map(b=>b.name),_=a.search?.trim()??"",i=b=>{if(a.refs===void 0)return b;const I={};for(const R of b.columns){const $=a.refs[R];$!==void 0&&(I[R]=$)}return Object.keys(I).length>0?{...b,refs:I}:b},u=v(s,_,a.filters),l=Q(a.orderBy,s),c=u===void 0?"":` WHERE ${u.where}`,f=l===void 0?"":` ORDER BY ${l.sql}`,g=u?.parameters??[],E=l?.params??[];let p;a.skipCount||(p=u===void 0?k(e,o):Number(e.exec(`SELECT COUNT(*) AS c FROM ${o}${c}`,...g).one().c));const y=e.exec(`SELECT * FROM ${o}${c}${f} LIMIT ? OFFSET ?`,...g,...E,t,n).toArray();return i({...L(s,y),total:p})},Z=(e,a)=>{const{table:r}=a;if(S(r)||!A(e,r))throw new h("UNKNOWN_TABLE",`unknown table: ${r}`,{status:404});const t=C(Math.trunc(a.limit??M),1,M),n=d(r),o=e.exec(`PRAGMA table_info(${n})`).toArray().map(c=>c.name),s=a.search?.trim()??"",_=v(o,s,a.filters),i=_===void 0?e.exec(`SELECT id FROM ${n} LIMIT ?`,t+1).toArray():e.exec(`SELECT id FROM ${n} WHERE ${_.where} LIMIT ?`,..._.parameters,t+1).toArray(),u=i.length>t,l=(u?i.slice(0,t):i).map(c=>c.id);return{hasMore:u,ids:l}},j=(e,a,r)=>{const t=new Set(r.filter(o=>o!==m));if(!r.includes(m))return t;const n=e.exec(`SELECT ${d(m)} AS doc FROM ${a} LIMIT ?`,M).toArray();for(const{doc:o}of n){const s=typeof o=="string"?w(o):void 0;if(s!==void 0)for(const _ of Object.keys(s))t.add(_)}return t},ee=(e,a)=>{const{column:r,table:t}=a;if(S(t)||!A(e,t))throw new h("UNKNOWN_TABLE",`unknown table: ${t}`,{status:404});const n=d(t),o=e.exec(`PRAGMA table_info(${n})`).toArray().map(p=>p.name);if(!j(e,n,o).has(r))throw new h("UNKNOWN_COLUMN",`unknown column: ${r}`,{status:404});const s=T(r,o);if(s===void 0)throw new h("UNKNOWN_COLUMN",`unknown column: ${r}`,{status:404});const _=C(Math.trunc(a.limit??x),1,F),i=a.search?.trim()??"",u=v(o,i,a.filters),l=u===void 0?"":` WHERE ${u.where}`,c=u?.parameters??[],f=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(),g=f.length>_,E=g?f.slice(0,_):f;return{truncated:g,values:E.map(p=>({count:Number(p.count),value:p.value}))}},ae=(e,a,r)=>{const t={},n=r.slice(0,M);for(const s of n)t[s]=[];if(n.length===0)return{references:t,storageColumns:a};const o=n.map(()=>"?").join(", ");for(const[s,_]of Object.entries(a)){if(S(s)||!A(e,s))continue;const i=d(s),u=e.exec(`PRAGMA table_info(${i})`).toArray().map(l=>l.name);for(const l of _){const c=T(l,u);if(c===void 0)continue;const f=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 f)t[g.ref]?.push({column:l,id:g.id,table:s})}}return{references:t,storageColumns:a}},te=e=>{const a=e.map((t,n)=>{const o=Object.values(t.subs??{}).map(s=>({args:s.args,functionPath:s.functionPath,table:s.table}));return{admin:t.admin===!0,id:n,subscriptions:o}}),r=a.reduce((t,n)=>t+n.subscriptions.length,0);return{connections:a,totalConnections:a.length,totalSubscriptions:r}},B=20,re=()=>({maxMs:0,passes:0,peakSocketsIterated:0,socketsDelivered:0,socketsIterated:0,totalMs:0}),se=(e,a,r,t)=>({maxMs:Math.max(e.maxMs,t),passes:e.passes+1,peakSocketsIterated:Math.max(e.peakSocketsIterated,a),socketsDelivered:e.socketsDelivered+r,socketsIterated:e.socketsIterated+a,totalMs:e.totalMs+t}),ne=(e,a=B)=>{const r=new Map,t=new Map;for(const o of e){for(const s of Object.values(o.shapes??{})){const _=s.name??"(unknown shape)";r.set(_,(r.get(_)??0)+1)}for(const s of o.whispers??[])t.set(s,(t.get(s)??0)+1)}const n=[...[...r].map(([o,s])=>({kind:"shape",subscribers:s,topic:o})),...[...t].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,a),totalConnections:e.length}};export{z as ADMIN_FUNCTIONS,K as ADMIN_FUNCTION_PREFIX,B as DEFAULT_FANOUT_TOPIC_LIMIT,Y as FLAGS_FUNCTION_PREFIX,M as MAX_PAGE_SIZE,X as RELATION_FUNCTION_PREFIX,re as createFanoutCounters,q as datePrefixRange,ee as facetColumn,ae as findStorageReferences,V as listTables,J as readTablePage,se as recordFanoutPass,Z as selectMatchingIds,ne as summarizeFanoutTopics,te as summarizeSubscriptions};
@@ -1 +1 @@
1
- import{toErrorBody as k,LunoraError as N}from"@lunora/errors";import{f as g,c as R}from"./wire-codec-Ctnni0h6.mjs";import{relayName as p,nextPromotionState as L,shapeRoutingKey as f,parseRelayName as C,clampPromotionThresholds as O,DEFAULT_PROMOTION_THRESHOLDS as w}from"./DEFAULT_PROMOTION_THRESHOLDS-Dteg0sZF.mjs";import{encodeRowsPatch as b,buildPokeFrames as v}from"./buildPokeFrames-DaPpm5Ss.mjs";import{awaitWsDrain as T,trySendFrame as I}from"./awaitWsDrain-Dk50ISgE.mjs";import{stableWireKey as u}from"./stableWireKey-YEHLaX6X.mjs";const D=(i,e)=>{const t=Math.max(i.length,e.length);let s=i.length^e.length;for(let r=0;r<t;r+=1){const a=r<i.length?i.charCodeAt(r):0,o=r<e.length?e.charCodeAt(r):0;s|=a^o}return s===0},F=2,x=8,$="LUNORA_RELAY_SECRET",_="x-lunora-relay-sig",E=i=>{const e=i?.[$];return typeof e=="string"&&e.length>0?e:void 0},A=async(i,e)=>{const t=new TextEncoder,s=await crypto.subtle.importKey("raw",t.encode(i),{hash:"SHA-256",name:"HMAC"},!1,["sign"]),r=await crypto.subtle.sign("HMAC",s,t.encode(e));return[...new Uint8Array(r)].map(a=>a.toString(16).padStart(2,"0")).join("")},y=(i,e,t)=>{const s=i?.[e];let r=Number.NaN;return typeof s=="string"?r=Number.parseInt(s,10):typeof s=="number"&&(r=s),Number.isInteger(r)&&r>0?r:t},S={},U=i=>{throw new N("INTERNAL",`unhandled relay frame: ${JSON.stringify(i)}`)},K=i=>{if(i===null||typeof i!="object")return;const e=i;return typeof e.idFromName=="function"&&typeof e.get=="function"?e:void 0},W=i=>Response.json(i,{headers:{"content-type":"application/json"}}),m=()=>new Response(null,{status:204});class P{constructor(e,t){this.host=e,this.roleId=t}host;roleId;async handleControl(e){let t;try{t=await e.text()}catch{return new Response("bad request",{status:400})}const s=E(this.host.env());if(s!==void 0){const a=e.headers.get(_),o=await A(s,t);if(a===null||!D(a,o))return new Response("forbidden",{status:403})}let r;try{r=JSON.parse(t)}catch{return new Response("bad request",{status:400})}switch(r.type){case"relay_attach":return this.onAttach(r.relayIndex),m();case"relay_detach":return this.onDetach(r.relayIndex),m();case"relay_frame":return this.host.deliverWhisperLocal(r.topic,r.frame,void 0),await this.onWhisperFrame(r),m();case"relay_shape_poke":{const a=this.host.getWebSockets().length,o=Date.now(),n=this.onShapePoke({...r,args:R(r.args)});return this.host.recordShapePokeFanout(a,n,Date.now()-o),m()}case"relay_shape_subscribe":return W(this.onShapeSubscribe({...r,args:R(r.args)}));default:return U(r)}}maxRelays(){return y(this.host.env(),"LUNORA_MAX_RELAYS",x)}canAddressSiblings(){return this.relayNamespace()!==void 0}relayNamespace(){const e=this.host.shardBinding();if(e!==void 0)return K(this.host.env()?.[e])}async postRelayMessage(e,t){await this.requestRelayMessage(e,t)}async requestRelayMessage(e,t){const s=this.relayNamespace();if(s===void 0)return;const r=typeof s.getByName=="function"?s.getByName(e):s.get(s.idFromName(e)),a=JSON.stringify(t),o={"content-type":"application/json","x-lunora-shard-binding":this.host.shardBinding()??""},n=E(this.host.env());n!==void 0&&(o[_]=await A(n,a));try{return await r.fetch("https://relay.internal/_lunora/relay",{body:a,headers:o,method:"POST"})}catch{return}}}class q extends P{shapeUniformCache=new Map;relaySetCache;relayShapeRegistry=new Map;relayShapeProxies=new Map;promotionState="owned";constructor(e,t){super(e,{ownerKey:t})}async forwardWhisper(e,t){if(!this.canAddressSiblings())return;const s=this.ownerRelaySet();s.size!==0&&await Promise.all([...s].map(r=>this.postRelayMessage(p(this.roleId.ownerKey,r),{frame:t,topic:e,type:"relay_frame"})))}async onFlush(e,t){await Promise.all([this.multicastShapePokes(e,t),this.proxyShapePokes(e,t)])}seedRelayShape(){return Promise.resolve(void 0)}announce(){return Promise.resolve()}announceDrain(){return Promise.resolve()}relayCount(){const e=this.host.getWebSockets().length,t=y(this.host.env(),"LUNORA_RELAY_THRESHOLD",w.tUp),s=y(this.host.env(),"LUNORA_RELAY_COLLAPSE_THRESHOLD",w.tDown);if(this.promotionState=L(this.promotionState,e,O(t,s)),this.promotionState==="owned")return 0;const r=y(this.host.env(),"LUNORA_MAX_RELAYS",x),a=y(this.host.env(),"LUNORA_RELAY_FAN",F);return Math.min(r,Math.max(1,a))}isShapeRelayUniform(e,t){const s=f(e,t),r=this.shapeUniformCache.get(s);if(r!==void 0)return r;const a=this.probeShapeRelayUniform(e,t);return this.shapeUniformCache.set(s,a),a}onAttach(e){this.addRelayToSet(e)}onDetach(e){this.removeRelayFromSet(e)}async onWhisperFrame(e){await Promise.all([...this.ownerRelaySet()].filter(t=>t!==e.originRelay).map(t=>this.postRelayMessage(p(this.roleId.ownerKey,t),{frame:e.frame,topic:e.topic,type:"relay_frame"})))}onShapeSubscribe(e){return this.buildShapeSeedFrames(e)}onShapePoke(){return 0}async multicastShapePokes(e,t){if(this.relayShapeRegistry.size===0)return;const s=this.ownerRelaySet();if(s.size===0)return;const r=this.host.currentCdcEpoch(),a=[];for(const o of this.relayShapeRegistry.values()){let n;try{n=this.host.resolveShape(o.name,o.args,S)}catch{continue}if(n===void 0||n.global===!0||!e.has(n.table))continue;const h=o.cursor,l=this.host.buildShapeDiff(n,h,t);if(l.length===0)continue;o.cursor=t;const d={args:g(o.args),checkpoint:t,epoch:r,fromCursor:h,name:o.name,rowsPatch:b(l),type:"relay_shape_poke"};for(const c of s)a.push(this.postRelayMessage(p(this.roleId.ownerKey,c),d))}await Promise.all(a)}async proxyShapePokes(e,t){if(this.relayShapeProxies.size===0)return;const s=this.host.currentCdcEpoch(),r=[];for(const a of this.relayShapeProxies.values()){let o;try{o=this.host.resolveShape(a.name,a.args,a.identity)}catch{continue}if(o===void 0||o.global===!0||!e.has(o.table))continue;const n=a.cursor,h=this.host.buildShapeDiff(o,n,t);if(h.length===0)continue;a.cursor=t;const l={args:g(a.args),checkpoint:t,epoch:s,fromCursor:n,name:a.name,rowsPatch:b(h),targetConnectionId:a.connectionId,type:"relay_shape_poke"};r.push(this.postRelayMessage(p(this.roleId.ownerKey,a.relayIndex),l))}await Promise.all(r)}buildShapeSeedFrames(e){const t={identity:e.identity,userId:e.userId};let s;try{s=this.host.resolveShape(e.name,e.args,t)}catch(d){const{body:c}=k(d,{fallbackCode:"SHAPE_RESOLVE_FAILED",redactedMessage:"shape resolution failed"});return{error:{code:c.code,message:c.message}}}if(s===void 0||s.global===!0)return{error:{code:"SHAPE_NOT_FOUND",message:`shape not relayable: ${e.name}`}};e.relayIndex!==void 0&&this.addRelayToSet(e.relayIndex);const{baseCheckpoint:r,cursor:a,epoch:o,rowsPatch:n}=this.host.computeOpLogShapeSeed({args:e.args,name:e.name,sinceEpoch:e.sinceEpoch,sinceSeq:e.sinceSeq},s);let h=a;if(this.isShapeRelayUniform(e.name,e.args)){const d=f(e.name,e.args);let c=this.relayShapeRegistry.get(d);c===void 0&&(c={args:e.args,cursor:a,name:e.name},this.relayShapeRegistry.set(d,c)),h=c.cursor}else e.relayIndex!==void 0&&e.connectionId!==void 0&&this.relayShapeProxies.set(`${String(e.relayIndex)}:${e.connectionId}:${e.subId}`,{args:e.args,connectionId:e.connectionId,cursor:a,epoch:o,identity:t,name:e.name,relayIndex:e.relayIndex,subId:e.subId});const l=v([{rowsPatch:n,shapeId:e.subId}],{baseCheckpoint:r,checkpoint:a,epoch:o,lastMutationId:void 0,pokeId:this.host.nextPokeId()});return{cursor:h,epoch:o,frames:l}}ensureRelayTable(){this.host.sql().exec("CREATE TABLE IF NOT EXISTS __lunora_relays (idx INTEGER PRIMARY KEY)")}ownerRelaySet(){if(this.relaySetCache===void 0){this.ensureRelayTable();const e=this.host.sql().exec("SELECT idx FROM __lunora_relays").toArray();this.relaySetCache=new Set(e.map(t=>Number(t.idx)))}return this.relaySetCache}addRelayToSet(e){this.ensureRelayTable(),this.host.sql().exec("INSERT OR IGNORE INTO __lunora_relays (idx) VALUES (?)",e),this.ownerRelaySet().add(e)}removeRelayFromSet(e){this.ensureRelayTable(),this.host.sql().exec("DELETE FROM __lunora_relays WHERE idx = ?",e);const t=this.ownerRelaySet();t.delete(e);for(const[s,r]of this.relayShapeProxies)r.relayIndex===e&&this.relayShapeProxies.delete(s);t.size===0&&(this.relayShapeRegistry.clear(),this.shapeUniformCache.clear())}probeShapeRelayUniform(e,t){let s;try{s=this.host.resolveShape(e,t,S)}catch{return!1}if(s===void 0||s.global===!0||this.host.rlsMetadata().policies.some(h=>h.on==="read"&&h.table===s.table)||this.tableHasAnyMask(s.table))return!1;const r=u(s.effectiveWhere),a=u(s.columns);let o=!1;const n=h=>{const l={groups:[`grp_${h}`],roles:[h],sub:`__lunora_probe_${h}__`};return{identity:new Proxy(l,{get:(d,c)=>typeof c=="symbol"||c in d?Reflect.get(d,c):`${h}:${c}`,getOwnPropertyDescriptor:(d,c)=>(o=!0,Reflect.getOwnPropertyDescriptor(d,c)),has:(d,c)=>typeof c=="symbol"?Reflect.has(d,c):!0,ownKeys:d=>(o=!0,Reflect.ownKeys(d))}),userId:`__lunora_probe_${h}__`}};return[S,n("a"),n("b")].every(h=>{let l;try{l=this.host.resolveShape(e,t,h)}catch{return!1}return l!==void 0&&l.global!==!0&&l.table===s.table&&u(l.effectiveWhere)===r&&u(l.columns)===a})&&!o}tableHasAnyMask(e){return this.host.maskMetadata().columns.some(t=>t.table===e)}}class H extends P{relayAnnounced=!1;shapeRelayMemos=new WeakMap;constructor(e,t,s){super(e,{ownerKey:t,relayIndex:s})}async forwardWhisper(e,t){this.canAddressSiblings()&&await this.postRelayMessage(this.roleId.ownerKey,{frame:t,originRelay:this.roleId.relayIndex,topic:e,type:"relay_frame"})}onFlush(){return Promise.resolve()}async seedRelayShape(e,t,s,r){if(!this.canAddressSiblings())return{code:"RELAY_MISCONFIGURED",message:"relay cannot address its owner"};await this.announce();const a={args:g(s.args??{}),connectionId:this.host.readAttachment(e).connectionId,identity:r.identity,name:s.name,relayIndex:this.roleId.relayIndex,sinceEpoch:s.sinceEpoch,sinceSeq:s.sinceSeq,subId:t,type:"relay_shape_subscribe",userId:r.userId},o=await this.requestRelayMessage(this.roleId.ownerKey,a);if(o===void 0)return{code:"RELAY_SEED_FAILED",message:"owner did not answer the shape seed"};let n;try{n=await o.json()}catch{return{code:"RELAY_SEED_FAILED",message:"malformed shape seed from owner"}}if(n.error!==void 0)return n.error;if(n.frames===void 0)return{code:"RELAY_SEED_FAILED",message:"owner returned no shape frames"};await T(e);for(const h of n.frames)I(e,h);return this.recordRelayShapeMemo(e,t,n.cursor??0,n.epoch),"ok"}async announce(){this.relayAnnounced||!this.canAddressSiblings()||(this.relayAnnounced=!0,(await this.requestRelayMessage(this.roleId.ownerKey,{relayIndex:this.roleId.relayIndex,type:"relay_attach"}))?.ok||(this.relayAnnounced=!1))}async announceDrain(e){this.canAddressSiblings()&&(this.host.getWebSockets().some(t=>t!==e)||(this.relayAnnounced=!1,await this.postRelayMessage(this.roleId.ownerKey,{relayIndex:this.roleId.relayIndex,type:"relay_detach"})))}relayCount(){return 0}isShapeRelayUniform(){return!1}onAttach(){}onDetach(){}onWhisperFrame(){return Promise.resolve()}onShapeSubscribe(){return{error:{code:"RELAY_CANNOT_SEED",message:"a relay has no op-log to seed from"}}}onShapePoke(e){return this.deliverShapePoke(e)}recordRelayShapeMemo(e,t,s,r){let a=this.shapeRelayMemos.get(e);a===void 0&&(a=new Map,this.shapeRelayMemos.set(e,a)),a.set(t,{cursor:s,epoch:r})}deliverShapePoke(e){const t=f(e.name,e.args);let s=0;for(const r of this.host.getWebSockets()){const a=this.host.readAttachment(r),{shapes:o}=a,n=this.shapeRelayMemos.get(r);if(!(o===void 0||n===void 0)&&!(e.targetConnectionId!==void 0&&a.connectionId!==e.targetConnectionId))for(const[h,l]of Object.entries(o)){const d=n.get(h);if(d?.cursor!==e.fromCursor||d.epoch!==e.epoch||f(l.name,l.args)!==t)continue;const c=v([{rowsPatch:e.rowsPatch,shapeId:h}],{baseCheckpoint:void 0,checkpoint:e.checkpoint,epoch:e.epoch,lastMutationId:void 0,pokeId:this.host.nextPokeId()},{preEncoded:!0});for(const M of c)I(r,M);n.set(h,{cursor:e.checkpoint,epoch:e.epoch}),s+=1}}return s}}const J=i=>{const e=i.doName();if(e===void 0)return;const t=C(e);return t===void 0?new q(i,e):new H(i,t.ownerKey,t.relayIndex)};export{x as DEFAULT_MAX_RELAYS,q as OwnerRelay,H as RelayMember,J as createRelayLink};
1
+ import{toErrorBody as k,LunoraError as N}from"@lunora/errors";import{f as g,c as R}from"./wire-codec-Ctnni0h6.mjs";import{relayName as p,nextPromotionState as L,shapeRoutingKey as f,parseRelayName as C,clampPromotionThresholds as O,DEFAULT_PROMOTION_THRESHOLDS as w}from"./DEFAULT_PROMOTION_THRESHOLDS-Dteg0sZF.mjs";import{encodeRowsPatch as b,buildPokeFrames as v}from"./buildPokeFrames-DaPpm5Ss.mjs";import{awaitWsDrain as T,trySendFrame as I}from"./awaitWsDrain-CCZ-8wjm.mjs";import{stableWireKey as u}from"./stableWireKey-YEHLaX6X.mjs";const D=(i,e)=>{const t=Math.max(i.length,e.length);let s=i.length^e.length;for(let r=0;r<t;r+=1){const a=r<i.length?i.charCodeAt(r):0,o=r<e.length?e.charCodeAt(r):0;s|=a^o}return s===0},F=2,x=8,$="LUNORA_RELAY_SECRET",_="x-lunora-relay-sig",E=i=>{const e=i?.[$];return typeof e=="string"&&e.length>0?e:void 0},A=async(i,e)=>{const t=new TextEncoder,s=await crypto.subtle.importKey("raw",t.encode(i),{hash:"SHA-256",name:"HMAC"},!1,["sign"]),r=await crypto.subtle.sign("HMAC",s,t.encode(e));return[...new Uint8Array(r)].map(a=>a.toString(16).padStart(2,"0")).join("")},y=(i,e,t)=>{const s=i?.[e];let r=Number.NaN;return typeof s=="string"?r=Number.parseInt(s,10):typeof s=="number"&&(r=s),Number.isInteger(r)&&r>0?r:t},S={},U=i=>{throw new N("INTERNAL",`unhandled relay frame: ${JSON.stringify(i)}`)},K=i=>{if(i===null||typeof i!="object")return;const e=i;return typeof e.idFromName=="function"&&typeof e.get=="function"?e:void 0},W=i=>Response.json(i,{headers:{"content-type":"application/json"}}),m=()=>new Response(null,{status:204});class P{constructor(e,t){this.host=e,this.roleId=t}host;roleId;async handleControl(e){let t;try{t=await e.text()}catch{return new Response("bad request",{status:400})}const s=E(this.host.env());if(s!==void 0){const a=e.headers.get(_),o=await A(s,t);if(a===null||!D(a,o))return new Response("forbidden",{status:403})}let r;try{r=JSON.parse(t)}catch{return new Response("bad request",{status:400})}switch(r.type){case"relay_attach":return this.onAttach(r.relayIndex),m();case"relay_detach":return this.onDetach(r.relayIndex),m();case"relay_frame":return this.host.deliverWhisperLocal(r.topic,r.frame,void 0),await this.onWhisperFrame(r),m();case"relay_shape_poke":{const a=this.host.getWebSockets().length,o=Date.now(),n=this.onShapePoke({...r,args:R(r.args)});return this.host.recordShapePokeFanout(a,n,Date.now()-o),m()}case"relay_shape_subscribe":return W(this.onShapeSubscribe({...r,args:R(r.args)}));default:return U(r)}}maxRelays(){return y(this.host.env(),"LUNORA_MAX_RELAYS",x)}canAddressSiblings(){return this.relayNamespace()!==void 0}relayNamespace(){const e=this.host.shardBinding();if(e!==void 0)return K(this.host.env()?.[e])}async postRelayMessage(e,t){await this.requestRelayMessage(e,t)}async requestRelayMessage(e,t){const s=this.relayNamespace();if(s===void 0)return;const r=typeof s.getByName=="function"?s.getByName(e):s.get(s.idFromName(e)),a=JSON.stringify(t),o={"content-type":"application/json","x-lunora-shard-binding":this.host.shardBinding()??""},n=E(this.host.env());n!==void 0&&(o[_]=await A(n,a));try{return await r.fetch("https://relay.internal/_lunora/relay",{body:a,headers:o,method:"POST"})}catch{return}}}class q extends P{shapeUniformCache=new Map;relaySetCache;relayShapeRegistry=new Map;relayShapeProxies=new Map;promotionState="owned";constructor(e,t){super(e,{ownerKey:t})}async forwardWhisper(e,t){if(!this.canAddressSiblings())return;const s=this.ownerRelaySet();s.size!==0&&await Promise.all([...s].map(r=>this.postRelayMessage(p(this.roleId.ownerKey,r),{frame:t,topic:e,type:"relay_frame"})))}async onFlush(e,t){await Promise.all([this.multicastShapePokes(e,t),this.proxyShapePokes(e,t)])}seedRelayShape(){return Promise.resolve(void 0)}announce(){return Promise.resolve()}announceDrain(){return Promise.resolve()}relayCount(){const e=this.host.getWebSockets().length,t=y(this.host.env(),"LUNORA_RELAY_THRESHOLD",w.tUp),s=y(this.host.env(),"LUNORA_RELAY_COLLAPSE_THRESHOLD",w.tDown);if(this.promotionState=L(this.promotionState,e,O(t,s)),this.promotionState==="owned")return 0;const r=y(this.host.env(),"LUNORA_MAX_RELAYS",x),a=y(this.host.env(),"LUNORA_RELAY_FAN",F);return Math.min(r,Math.max(1,a))}isShapeRelayUniform(e,t){const s=f(e,t),r=this.shapeUniformCache.get(s);if(r!==void 0)return r;const a=this.probeShapeRelayUniform(e,t);return this.shapeUniformCache.set(s,a),a}onAttach(e){this.addRelayToSet(e)}onDetach(e){this.removeRelayFromSet(e)}async onWhisperFrame(e){await Promise.all([...this.ownerRelaySet()].filter(t=>t!==e.originRelay).map(t=>this.postRelayMessage(p(this.roleId.ownerKey,t),{frame:e.frame,topic:e.topic,type:"relay_frame"})))}onShapeSubscribe(e){return this.buildShapeSeedFrames(e)}onShapePoke(){return 0}async multicastShapePokes(e,t){if(this.relayShapeRegistry.size===0)return;const s=this.ownerRelaySet();if(s.size===0)return;const r=this.host.currentCdcEpoch(),a=[];for(const o of this.relayShapeRegistry.values()){let n;try{n=this.host.resolveShape(o.name,o.args,S)}catch{continue}if(n===void 0||n.global===!0||!e.has(n.table))continue;const h=o.cursor,l=this.host.buildShapeDiff(n,h,t);if(l.length===0)continue;o.cursor=t;const d={args:g(o.args),checkpoint:t,epoch:r,fromCursor:h,name:o.name,rowsPatch:b(l),type:"relay_shape_poke"};for(const c of s)a.push(this.postRelayMessage(p(this.roleId.ownerKey,c),d))}await Promise.all(a)}async proxyShapePokes(e,t){if(this.relayShapeProxies.size===0)return;const s=this.host.currentCdcEpoch(),r=[];for(const a of this.relayShapeProxies.values()){let o;try{o=this.host.resolveShape(a.name,a.args,a.identity)}catch{continue}if(o===void 0||o.global===!0||!e.has(o.table))continue;const n=a.cursor,h=this.host.buildShapeDiff(o,n,t);if(h.length===0)continue;a.cursor=t;const l={args:g(a.args),checkpoint:t,epoch:s,fromCursor:n,name:a.name,rowsPatch:b(h),targetConnectionId:a.connectionId,type:"relay_shape_poke"};r.push(this.postRelayMessage(p(this.roleId.ownerKey,a.relayIndex),l))}await Promise.all(r)}buildShapeSeedFrames(e){const t={identity:e.identity,userId:e.userId};let s;try{s=this.host.resolveShape(e.name,e.args,t)}catch(d){const{body:c}=k(d,{fallbackCode:"SHAPE_RESOLVE_FAILED",redactedMessage:"shape resolution failed"});return{error:{code:c.code,message:c.message}}}if(s===void 0||s.global===!0)return{error:{code:"SHAPE_NOT_FOUND",message:`shape not relayable: ${e.name}`}};e.relayIndex!==void 0&&this.addRelayToSet(e.relayIndex);const{baseCheckpoint:r,cursor:a,epoch:o,rowsPatch:n}=this.host.computeOpLogShapeSeed({args:e.args,name:e.name,sinceEpoch:e.sinceEpoch,sinceSeq:e.sinceSeq},s);let h=a;if(this.isShapeRelayUniform(e.name,e.args)){const d=f(e.name,e.args);let c=this.relayShapeRegistry.get(d);c===void 0&&(c={args:e.args,cursor:a,name:e.name},this.relayShapeRegistry.set(d,c)),h=c.cursor}else e.relayIndex!==void 0&&e.connectionId!==void 0&&this.relayShapeProxies.set(`${String(e.relayIndex)}:${e.connectionId}:${e.subId}`,{args:e.args,connectionId:e.connectionId,cursor:a,epoch:o,identity:t,name:e.name,relayIndex:e.relayIndex,subId:e.subId});const l=v([{rowsPatch:n,shapeId:e.subId}],{baseCheckpoint:r,checkpoint:a,epoch:o,lastMutationId:void 0,pokeId:this.host.nextPokeId()});return{cursor:h,epoch:o,frames:l}}ensureRelayTable(){this.host.sql().exec("CREATE TABLE IF NOT EXISTS __lunora_relays (idx INTEGER PRIMARY KEY)")}ownerRelaySet(){if(this.relaySetCache===void 0){this.ensureRelayTable();const e=this.host.sql().exec("SELECT idx FROM __lunora_relays").toArray();this.relaySetCache=new Set(e.map(t=>Number(t.idx)))}return this.relaySetCache}addRelayToSet(e){this.ensureRelayTable(),this.host.sql().exec("INSERT OR IGNORE INTO __lunora_relays (idx) VALUES (?)",e),this.ownerRelaySet().add(e)}removeRelayFromSet(e){this.ensureRelayTable(),this.host.sql().exec("DELETE FROM __lunora_relays WHERE idx = ?",e);const t=this.ownerRelaySet();t.delete(e);for(const[s,r]of this.relayShapeProxies)r.relayIndex===e&&this.relayShapeProxies.delete(s);t.size===0&&(this.relayShapeRegistry.clear(),this.shapeUniformCache.clear())}probeShapeRelayUniform(e,t){let s;try{s=this.host.resolveShape(e,t,S)}catch{return!1}if(s===void 0||s.global===!0||this.host.rlsMetadata().policies.some(h=>h.on==="read"&&h.table===s.table)||this.tableHasAnyMask(s.table))return!1;const r=u(s.effectiveWhere),a=u(s.columns);let o=!1;const n=h=>{const l={groups:[`grp_${h}`],roles:[h],sub:`__lunora_probe_${h}__`};return{identity:new Proxy(l,{get:(d,c)=>typeof c=="symbol"||c in d?Reflect.get(d,c):`${h}:${c}`,getOwnPropertyDescriptor:(d,c)=>(o=!0,Reflect.getOwnPropertyDescriptor(d,c)),has:(d,c)=>typeof c=="symbol"?Reflect.has(d,c):!0,ownKeys:d=>(o=!0,Reflect.ownKeys(d))}),userId:`__lunora_probe_${h}__`}};return[S,n("a"),n("b")].every(h=>{let l;try{l=this.host.resolveShape(e,t,h)}catch{return!1}return l!==void 0&&l.global!==!0&&l.table===s.table&&u(l.effectiveWhere)===r&&u(l.columns)===a})&&!o}tableHasAnyMask(e){return this.host.maskMetadata().columns.some(t=>t.table===e)}}class H extends P{relayAnnounced=!1;shapeRelayMemos=new WeakMap;constructor(e,t,s){super(e,{ownerKey:t,relayIndex:s})}async forwardWhisper(e,t){this.canAddressSiblings()&&await this.postRelayMessage(this.roleId.ownerKey,{frame:t,originRelay:this.roleId.relayIndex,topic:e,type:"relay_frame"})}onFlush(){return Promise.resolve()}async seedRelayShape(e,t,s,r){if(!this.canAddressSiblings())return{code:"RELAY_MISCONFIGURED",message:"relay cannot address its owner"};await this.announce();const a={args:g(s.args??{}),connectionId:this.host.readAttachment(e).connectionId,identity:r.identity,name:s.name,relayIndex:this.roleId.relayIndex,sinceEpoch:s.sinceEpoch,sinceSeq:s.sinceSeq,subId:t,type:"relay_shape_subscribe",userId:r.userId},o=await this.requestRelayMessage(this.roleId.ownerKey,a);if(o===void 0)return{code:"RELAY_SEED_FAILED",message:"owner did not answer the shape seed"};let n;try{n=await o.json()}catch{return{code:"RELAY_SEED_FAILED",message:"malformed shape seed from owner"}}if(n.error!==void 0)return n.error;if(n.frames===void 0)return{code:"RELAY_SEED_FAILED",message:"owner returned no shape frames"};await T(e);for(const h of n.frames)I(e,h);return this.recordRelayShapeMemo(e,t,n.cursor??0,n.epoch),"ok"}async announce(){this.relayAnnounced||!this.canAddressSiblings()||(this.relayAnnounced=!0,(await this.requestRelayMessage(this.roleId.ownerKey,{relayIndex:this.roleId.relayIndex,type:"relay_attach"}))?.ok||(this.relayAnnounced=!1))}async announceDrain(e){this.canAddressSiblings()&&(this.host.getWebSockets().some(t=>t!==e)||(this.relayAnnounced=!1,await this.postRelayMessage(this.roleId.ownerKey,{relayIndex:this.roleId.relayIndex,type:"relay_detach"})))}relayCount(){return 0}isShapeRelayUniform(){return!1}onAttach(){}onDetach(){}onWhisperFrame(){return Promise.resolve()}onShapeSubscribe(){return{error:{code:"RELAY_CANNOT_SEED",message:"a relay has no op-log to seed from"}}}onShapePoke(e){return this.deliverShapePoke(e)}recordRelayShapeMemo(e,t,s,r){let a=this.shapeRelayMemos.get(e);a===void 0&&(a=new Map,this.shapeRelayMemos.set(e,a)),a.set(t,{cursor:s,epoch:r})}deliverShapePoke(e){const t=f(e.name,e.args);let s=0;for(const r of this.host.getWebSockets()){const a=this.host.readAttachment(r),{shapes:o}=a,n=this.shapeRelayMemos.get(r);if(!(o===void 0||n===void 0)&&!(e.targetConnectionId!==void 0&&a.connectionId!==e.targetConnectionId))for(const[h,l]of Object.entries(o)){const d=n.get(h);if(d?.cursor!==e.fromCursor||d.epoch!==e.epoch||f(l.name,l.args)!==t)continue;const c=v([{rowsPatch:e.rowsPatch,shapeId:h}],{baseCheckpoint:void 0,checkpoint:e.checkpoint,epoch:e.epoch,lastMutationId:void 0,pokeId:this.host.nextPokeId()},{preEncoded:!0});for(const M of c)I(r,M);n.set(h,{cursor:e.checkpoint,epoch:e.epoch}),s+=1}}return s}}const J=i=>{const e=i.doName();if(e===void 0)return;const t=C(e);return t===void 0?new q(i,e):new H(i,t.ownerKey,t.relayIndex)};export{x as DEFAULT_MAX_RELAYS,q as OwnerRelay,H as RelayMember,J as createRelayLink};
@@ -0,0 +1 @@
1
+ import{LunoraError as i}from"@lunora/errors";import{t as e}from"./estimate-bytes-DwQON1Ky.mjs";const r={maxReadRows:1e5,maxWrittenBytes:32*1024*1024,maxWrittenRows:5e4};class w{readRows=0;writtenRows=0;writtenBytes=0;limits;constructor(t={}){this.limits={...r,...t}}recordRead(t){if(this.readRows+=t,this.readRows>this.limits.maxReadRows)throw new i("TRANSACTION_LIMIT_EXCEEDED",`this transaction read ${String(this.readRows)} documents, over the ${String(this.limits.maxReadRows)}-document limit`)}recordWrite(t){this.writtenRows+=1;const s=e(t);if(s===void 0)throw new i("BAD_REQUEST","this document is not JSON-serializable (cyclic or non-JSON value); it cannot be written");if(this.writtenBytes+=s,this.writtenRows>this.limits.maxWrittenRows)throw new i("TRANSACTION_LIMIT_EXCEEDED",`this transaction wrote ${String(this.writtenRows)} documents, over the ${String(this.limits.maxWrittenRows)}-document limit`);if(this.writtenBytes>this.limits.maxWrittenBytes)throw new i("TRANSACTION_LIMIT_EXCEEDED",`this transaction wrote ${String(this.writtenBytes)} bytes, over the ${String(this.limits.maxWrittenBytes)}-byte limit`)}headroom(){return{readRows:this.readRows,remainingReadRows:Math.max(0,this.limits.maxReadRows-this.readRows),remainingWrittenBytes:Math.max(0,this.limits.maxWrittenBytes-this.writtenBytes),remainingWrittenRows:Math.max(0,this.limits.maxWrittenRows-this.writtenRows),writtenBytes:this.writtenBytes,writtenRows:this.writtenRows}}}export{r as DEFAULT_TRANSACTION_LIMITS,w as TransactionHeadroomTracker};
@@ -0,0 +1 @@
1
+ import{LunoraError as b}from"@lunora/errors";import{n as St,A as Pe,T as Se,y as Tt,c as _t}from"./FTS_COUNT_COLUMN-D1gY3wwZ-CZHdaRrd.mjs";import{sql as n}from"drizzle-orm";import{aggregateSqlFunction as Te,normalizeCountArgument as Rt,throwingScheduler as At}from"./AGGREGATE_SQL_FUNCTION-QYaiuty4.mjs";import{encodeAggregateKey as Me,readAggregateValue as Ce,aggregateTableName as ke}from"./aggregateTableName-G-eXyjcz.mjs";import{mergeWhere as Q,CountRlsUnsupportedError as Le,selectIndexForGroupBy as xt,selectIndexForCount as vt,selectIndexForAggregate as It}from"./CountRlsUnsupportedError-B2WKJD9v.mjs";import{backfillSearchIndexesForTable as Mt}from"./backfillAggregateIndexes-BHiewuB-.mjs";import{backfillAggregateIndexes as mr,backfillRankIndexes as $r,backfillSearchIndexes as gr}from"./backfillAggregateIndexes-BHiewuB-.mjs";import{appendCdcChange as Ct}from"./CDC_LOG_TABLE-BnqlH2eZ.mjs";import{CDC_LOG_TABLE as yr,applyCdcChanges as Er,bumpCdcEpoch as Nr,minCdcSeq as Sr,readCdcChanges as Tr,readCdcCursor as _r,readCdcEpoch as Rr,trimCdcChanges as Ar}from"./CDC_LOG_TABLE-BnqlH2eZ.mjs";import{createCompanionSync as kt}from"./createCompanionSync-DWK0Vlg1.mjs";import{computeRankPage as Ze}from"./computeRankPage-IUSS-zIB.mjs";import{SCAN_DEP as B}from"./SCAN_DEP-D_yR9EeV.mjs";import{runDrizzle as F}from"./runDrizzle-GKR3y97k.mjs";import{DOC_COLUMN as P,quoteIdentifier as Lt,AGG_VALUE as _e,AGG_COUNT as De,AGG_KEY as Re,jsonPathSql as z,rowToDocument as de,tableColumns as pt,isFtsAvailable as Dt,tryRowToDocument as wt,geoTableName as Ot,qualifiedJsonPathSql as et}from"./AGG_COUNT-BWXe3gtQ.mjs";import{coveringGeohashes as Wt,boundingBoxGeohashes as Ft,pointInBoundingBox as qt,haversineMeters as Bt}from"./GEO_DEFAULT_PRECISION-okRCkZ6r.mjs";import{NotFoundError as Ut}from"./NotFoundError-BhF7FeFr.mjs";import{normalizeOrderKeys as Pt,buildSeekWhere as mt,decodeCursor as qe,applySelect as tt,encodeCursor as Be,softDeleteScope as le,buildSeekBeforeWhere as jt}from"./applySelect-B0CF8T7y.mjs";import{sortColumnName as nt,resolveRankPartition as Ht,encodePartitionKey as Gt,RANK_TIEBREAK as Kt,rankTableName as rt}from"./RANK_TIEBREAK-9NU5s_mi.mjs";import{indexKeysForRow as Qt,buildIndexRange as zt}from"./buildIndexRange-DFsdtPjD.mjs";import{assertFlatPredicate as Oe,resolveRelationPredicates as it}from"./DEFAULT_MAX_RELATION_KEYS-bq00btqV.mjs";import{runRowValidators as We,resolveWith as ot,applyOnDelete as Jt,fanOutScalarCounts as Yt}from"./applyOnDelete-uFRC5p1d.mjs";import{guardWriter as Vt}from"./RLS_UNWRAP_SYMBOL-CBYPlYBb.mjs";import{createSystemReader as Xt}from"./createSystemReader-DcDcrtM3.mjs";import{ConflictError as me}from"./ConflictError-C8GtJmjS.mjs";import{runTriggers as Zt}from"./hasTrigger-CbkOHExZ.mjs";import{compileWhereSql as ne}from"./compileWhereSql-BLcfs4QW.mjs";import{CLIENT_WATERMARK_TABLE as vr,advanceClientWatermark as Ir,migrateClientWatermark as Mr,readClientWatermark as Cr}from"./CLIENT_WATERMARK_TABLE-CXsSLU8D.mjs";import{GLOBAL_SHAPE_SNAPSHOT_TABLE as Lr,deleteGlobalShapeSnapshot as Dr,deleteGlobalShapeSnapshotsForConnection as Or,migrateGlobalShapeSnapshot as Wr,readGlobalShapeSnapshot as Fr,writeGlobalShapeSnapshot as qr}from"./GLOBAL_SHAPE_SNAPSHOT_TABLE-DX-6-gBP.mjs";import{IDEMPOTENCY_TABLE as Ur,readIdempotent as Pr,trimIdempotent as jr,writeIdempotent as Hr}from"./IDEMPOTENCY_TABLE-DjkEMp6w.mjs";import{runShardMigrations as Kr}from"./runShardMigrations-CPxqCh3O.mjs";import{SEARCH_STATE_TABLE as zr}from"./SEARCH_STATE_TABLE-eLN8U5tz.mjs";import{selectShapeMemberIds as Yr,selectShapeRows as Vr}from"./selectShapeMemberIds-DvE7K6zG.mjs";import{serializeSqlValue as re}from"./serializeSqlValue-DnpyaLcw.mjs";const en=i=>{const o=new TextEncoder().encode(i);let t="";for(const l of o)t+=String.fromCodePoint(l);return btoa(t)},tn=i=>{const o=atob(i),t=Uint8Array.from(o,l=>l.codePointAt(0)??0);return new TextDecoder().decode(t)},nn=()=>new b("BAD_REQUEST","invalid cursor"),at=16,st=8,Z=1024,je=(i,o)=>o.query(i),rn=(i,o,t)=>{const l=St(i,t);if(l.length===0)return 0;let c=0;for(const[p,m]of o.entries()){const R=p===o.length-1;let S=0;for(const $ of l)(R?$.startsWith(m):$===m)&&(S+=1);if(S===0)return 0;c+=S}return c},on=(i,o)=>{if(!o)return{exact:!0,lower:i,upper:i};const t=[...i].at(-1)??"",l=(t.codePointAt(0)??0)+1;if(l>=55296&&l<=57343||l>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(l)}},an=(i,o,t)=>{const l={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>=st)throw new b("BAD_REQUEST",`search index "${i.indexName}" on table "${o}": at most ${String(st)} .eq() filters are supported per search query`);return i.filters.push({field:c,value:p}),l},search:(c,p)=>{const m=i;if(c!==m.definition.field)throw new b("INTERNAL",`search index "${m.indexName}" on table "${o}" indexes "${m.definition.field}", not "${c}"`);const R=je(p,t).length;if(R>at)throw new b("BAD_REQUEST",`search index "${m.indexName}" on table "${o}": at most ${String(at)} search terms are supported (got ${String(R)})`);return m.field=c,m.query=p,m.hasQuery=!0,l}};return l},sn=i=>{if(i.length>Z)throw new b("BAD_REQUEST",`more than ${String(Z)} documents match this search — narrow it with filters or read it a page at a time with .paginate()`)},ln=i=>Math.min(i.offset+i.numItems+1,Z),dn=i=>en(`search:${String(i)}`),cn=i=>{let o;try{o=tn(i)}catch{return}if(!o.startsWith("search:"))return;const t=Number(o.slice(7));return Number.isInteger(t)&&t>=0?t:void 0},un=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?cn(i.cursor):0;if(t===void 0)throw nn();if(t+o>Z)throw new b("BAD_REQUEST",`search pagination reaches past the ${String(Z)}-document limit (offset ${String(t)} + ${String(o)} requested) — narrow the query or the filters instead`);return{numItems:o,offset:t}},fn=(i,o)=>{const t=o.offset+o.numItems,l=o.numItems>0&&i.length>t;return{continueCursor:l?dn(t):null,isDone:!l,page:i.slice(o.offset,t)}},hn=i=>{if(i===void 0)return Z+1;if(!Number.isFinite(i))return Z;const o=Math.max(0,Math.floor(i));if(o>Z)throw new b("BAD_REQUEST",`search returns at most ${String(Z)} documents (asked for ${String(o)}) — narrow the query or paginate instead`);return o},pn=/^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/iu,wn=i=>{if(!pn.test(i))throw new b("INTERNAL",`invalid clientId ${JSON.stringify(i)}: a client-supplied row id must be a UUID`)},lt=50,$t=500,mn=128,se=(i,o,t)=>{const l=o??$t;if(i>l)throw new b("BATCH_LIMIT_EXCEEDED",`${t}: batch of ${String(i)} exceeds the limit of ${String(l)} (raise options.limit or chunk the call)`,{status:400})},$n=i=>{const o={eq:(t,l)=>(i.sqlConditions.push({comparator:"=",field:t,value:l}),o),gt:(t,l)=>(i.sqlConditions.push({comparator:">",field:t,value:l}),o),gte:(t,l)=>(i.sqlConditions.push({comparator:">=",field:t,value:l}),o),lt:(t,l)=>(i.sqlConditions.push({comparator:"<",field:t,value:l}),o),lte:(t,l)=>(i.sqlConditions.push({comparator:"<=",field:t,value:l}),o)};return o},gn=i=>Math.max(i,Z),bn=(i,o,t,l,c)=>{const p=je(t.query,Pe(t.definition.language));if(p.length===0)return[];const m=_t(o,t.indexName),R=`${m}__vocab`,S=p.length-1,$=p.map((C,L)=>{const j=on(C,L===S),U=j.exact?n`${n.identifier("term")} = ${j.lower}`:n`${n.identifier("term")} >= ${j.lower} AND ${n.identifier("term")} < ${j.upper}`;return n`SELECT ${n.identifier("doc")}, ${n.raw(String(L))} AS ${n.identifier("__term__")}, COUNT(*) AS ${n.identifier("__n__")} FROM ${n.identifier(R)} WHERE ${U} GROUP BY ${n.identifier("doc")}`}),y=p.map((C,L)=>n`SUM(CASE WHEN u.${n.identifier("__term__")} = ${n.raw(String(L))} THEN u.${n.identifier("__n__")} ELSE 0 END)`),E=n`SELECT f.${n.identifier(Se)} AS ${n.identifier(Se)}, ${n.join(y,n` + `)} AS ${n.identifier("__score__")} FROM (${n.join($,n` UNION ALL `)}) u JOIN ${n.identifier(m)} f ON f.rowid = u.${n.identifier("doc")} GROUP BY f.${n.identifier(Se)} HAVING ${n.join(y.map(C=>n`${C} > 0`),n` AND `)}`,_=[];for(const C of t.filters)_.push(n`${z(C.field)} = ${re(C.value)}`);c&&_.push(c);let M=n`SELECT m.id, m._creationTime, m.${n.identifier(P)}, s.${n.identifier("__score__")} AS ${n.identifier("__score__")} FROM (${E}) s JOIN ${n.identifier(o)} m ON m.id = s.${n.identifier(Se)}`;_.length>0&&(M=n`${M} WHERE ${n.join(_,n` AND `)}`),M=n`${M} ORDER BY s.${n.identifier("__score__")} DESC, m._creationTime DESC, m.id ASC LIMIT ${n.raw(String(l))}`;const O=[];for(const C of F(i,M)){const L=wt(C);if(L){const j=C.__score__;O.push({document:L,score:typeof j=="number"?j:Number(j??0)})}}return O},yn=(i,o,t,l,c)=>{const p=Pe(t.definition.language),m=je(t.query,p);if(m.length===0)return[];const R=[];for(const E of t.filters)R.push(n`${z(E.field)} = ${re(E.value)}`);c&&R.push(c);let S=n`SELECT id, _creationTime, ${n.identifier(P)} FROM ${n.identifier(o)}`;R.length>0&&(S=n`${S} WHERE ${n.join(R,n` AND `)}`),S=n`${S} ORDER BY _creationTime DESC, id ASC LIMIT ${n.raw(String(gn(l)))}`;const $=F(i,S).toArray(),y=[];for(const E of $){const _=wt(E);if(!_)continue;const M=rn(Tt(_,t.definition),m,p);M>0&&y.push({creationTime:typeof _._creationTime=="number"?_._creationTime:0,doc:_,id:typeof _._id=="string"?_._id:"",score:M})}return y.sort((E,_)=>_.score-E.score||_.creationTime-E.creationTime||E.id.localeCompare(_.id)),y.slice(0,l).map(E=>({document:E.doc,score:E.score}))},Fe=(i,o,t,l)=>{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 "${l}" on table "${t}": ${o} must have a finite lat in [-90, 90] and lng in [-180, 180]`)},En=(i,o)=>{const t=i,l={near:(c,p)=>{if(t.within)throw new b("INTERNAL",`geo index "${t.indexName}" on table "${o}": call .near() or .within(), not both`);if(Fe(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},l},within:c=>{if(t.near)throw new b("INTERNAL",`geo index "${t.indexName}" on table "${o}": call .near() or .within(), not both`);if(Fe(c.sw,".within() sw corner",o,t.indexName),Fe(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}},l}};return l},Nn=(i,o)=>{const t=i[o];if(t===null||typeof t!="object")return;const{lat:l,lng:c}=t;return typeof l=="number"&&typeof c=="number"?{lat:l,lng:c}:void 0},Sn=(i,o)=>{const t=Nn(i,o.definition.field);if(!t)return;const l=typeof i._creationTime=="number"?i._creationTime:0;if(o.near){const c=Bt(o.near.point,t);return c<=o.near.radiusMeters?{creationTime:l,distance:c}:void 0}return qt(t,o.within)?{creationTime:l,distance:0}:void 0},gt=(i,o,t,l)=>{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?Wt(t.near.point,t.near.radiusMeters):Ft(t.within),p=Ot(o,t.indexName),m=c.map(E=>n`(g.${n.identifier("__geohash__")} >= ${E} AND g.${n.identifier("__geohash__")} < ${`${E}{`})`),R=[n`(${n.join(m,n` OR `)})`];l&&R.push(l);const S=n`SELECT m.id, m._creationTime, m.${n.identifier(P)} FROM ${n.identifier(p)} g JOIN ${n.identifier(o)} m ON m.id = g.${n.identifier("__id__")} WHERE ${n.join(R,n` AND `)}`,$=F(i,S).toArray(),y=[];for(const E of $){const _=de(E),M=_?Sn(_,t):void 0;_&&M&&y.push({creationTime:M.creationTime,distance:M.distance,doc:_})}return y.sort((E,_)=>E.distance-_.distance||_.creationTime-E.creationTime),y},Tn=(i,o,t,l,c,p=()=>{})=>{const m=gt(i,o,t,c).map(R=>R.doc);return p(m.length),typeof l=="number"?m.slice(0,Math.max(0,Math.floor(l))):m},_n=(i,o,t,l,c,p=()=>{})=>{const m=t.within!==void 0,R=gt(i,o,t,c).map(S=>({distanceMeters:m?null:S.distance,document:S.doc}));return p(R.length),R},Rn=(i,o,t,l,c,p=()=>{})=>{const{geo:m}=t;if(!m)throw new b("INTERNAL","runGeoTerminal called without a staged geo query");const R=t.inMemoryFilters.length>0,S=Tn(i,o,m,R?void 0:c,l,p);if(!R)return S;const $=[];for(const y of S)if(t.inMemoryFilters.every(E=>E(y))&&($.push(y),typeof c=="number"&&$.length>=c))break;return $},An=(i,o,t,l,c,p=()=>{})=>{const{geo:m}=t;if(!m)throw new b("INTERNAL","runGeoTerminalScored called without a staged geo query");const R=t.inMemoryFilters.length>0,S=_n(i,o,m,R?void 0:c,l,p);if(!R)return S;const $=[];for(const y of S)t.inMemoryFilters.every(E=>E(y.document))&&$.push(y);return $},xn=(i,o,t,l,c,p,m=()=>{})=>{const R=[];for(const E of t.sqlConditions)R.push(n`${z(E.field)} ${n.raw(E.comparator)} ${re(E.value)}`);l&&R.push(l);let S=n`SELECT id, _creationTime, ${n.identifier(P)} FROM ${n.identifier(o)}`;R.length>0&&(S=n`${S} WHERE ${n.join(R,n` AND `)}`),S=n`${S} ORDER BY ${c}`,typeof p=="number"&&t.inMemoryFilters.length===0&&(S=n`${S} LIMIT ${n.raw(String(Math.max(0,Math.floor(p))))}`);const $=F(i,S).toArray();m($.length);const y=[];for(const E of $){const _=de(E);if(_&&t.inMemoryFilters.every(M=>M(_))&&(y.push(_),typeof p=="number"&&y.length>=p))break}return y},oe={fieldRef:z,serialize:re},vn=i=>{let o=0;const t=[],l={fieldRef:z,relationExists:c=>{const{childWhere:p,negated:m,parentTable:R,relation:S}=c,$=`__rel_${String(o)}`,y=t.at(-1)??R;o+=1,i(S.table,B);const E=S.kind==="one"?S.field:S.references,_=S.kind==="one"?S.references:S.field,M=n`${et($,_)} = ${et(y,E)}`;t.push($);const O=ne(p,l);t.pop();const C=O?n`${M} AND ${O}`:M,L=n`EXISTS (SELECT 1 FROM ${n.identifier(S.table)} AS ${n.identifier($)} WHERE ${C})`;return m?n`NOT ${L}`:L},serialize:re};return l},bt=i=>{const o=i.map(t=>n`${z(t.field)} ${n.raw(t.direction==="desc"?"DESC":"ASC")}`);return i.some(t=>t.field==="_id"||t.field==="id")||o.push(n`${z("id")} ASC`),n.join(o,n`, `)},In={"<":"lt","<=":"lte","=":"eq",">":"gt",">=":"gte"},Mn=i=>{const o=i.order;return i.indexFields.length>0?i.indexFields.map(t=>({direction:o,field:t})):[{direction:o,field:"_creationTime"}]},Cn=(i,o,t,l)=>{const c=i.sqlConditions.map(p=>({[p.field]:{[In[p.comparator]??"eq"]:p.value}}));if(t&&c.push(mt(o,qe(t))),l&&c.push(jt(o,qe(l))),c.length!==0)return c.length===1?c[0]:{AND:c}},kn=(i,o,t)=>{const l=[];for(const c of i){const p=de(c);if(p&&o.every(m=>m(p))&&(l.push(p),t!==void 0&&l.length>t))break}return l},Ln=(i,o,t,l,c,p=()=>{})=>{const m=Math.max(0,Math.floor(l.numItems)),R=Mn(t),S=typeof l.endCursor=="string",$=ne(Cn(t,R,l.cursor,l.endCursor),oe),y=c&&$?n`${$} AND ${c}`:c??$;let E=n`SELECT id, _creationTime, ${n.identifier(P)} FROM ${n.identifier(o)}`;y&&(E=n`${E} WHERE ${y}`),E=n`${E} ORDER BY ${bt(R)}`;const _=t.inMemoryFilters.length>0;!_&&!S&&(E=n`${E} LIMIT ${n.raw(String(m+1))}`);const M=F(i,E).toArray();p(M.length);const O=kn(M,t.inMemoryFilters,_||S?void 0:m);if(S){const U=O.length>=2?O[Math.floor(O.length/2)-1]:void 0;return{continueCursor:l.endCursor??null,isDone:!0,page:O,splitCursor:U?Be(U,R):null}}const C=O.length>m,L=C?O.slice(0,m):O,j=L.at(-1);return{continueCursor:C&&j?Be(j,R):null,isDone:!C,page:L}};class Dn extends b{constructor(o="unique() found more than one matching document"){super("NOT_UNIQUE",o,{name:"NotUniqueError"})}}const On=/\s/u,Wn=String.fromCodePoint(0),dt=(i,o,t)=>{if(!i.tables[o])throw new b("INTERNAL",`unknown table: ${o}`);return typeof t!="string"||t.length===0||On.test(t)||t.includes(Wn)?null:t},Fn=(i,o,t,l=()=>{},c=()=>{},p=()=>{})=>{const m=o.tables[t];if(!m)throw new b("INTERNAL",`unknown table: ${t}`);const R=le(m.softDeleteMode,void 0),S=R?ne(R,oe):void 0,$={indexFields:[],indexName:void 0,inMemoryFilters:[],order:"asc",sqlConditions:[]};let y=0;const E=N=>{const{search:I}=$;if(!I)throw new b("INTERNAL","runSearchFetch called without a staged search");Mt(i,t,m);const v=$.inMemoryFilters.length>0,k=hn(v?void 0:N),H=Dt(i)?bn(i,t,I,k,S):yn(i,t,I,k,S);if(!v)return N===void 0&&sn(H),H;const X=[];y=H.length;for(const ce of H)if($.inMemoryFilters.every(ue=>ue(ce.document))&&(X.push(ce),typeof N=="number"&&X.length>=N))break;return X},_=N=>E(N).map(I=>I.document),M=N=>{const I=un(N);return fn(_(ln(I)),I)},O=()=>{const N=$.indexFields.length>0?$.indexFields:["_creationTime"],I=$.order==="desc"?"DESC":"ASC";return n.join(N.map(v=>n`${z(v)} ${n.raw(I)}`),n`, `)},C=()=>{if($.search||$.geo||$.indexName===void 0){c(void 0);return}c(zt(t,$.indexName,$.indexFields,$.sqlConditions,re))},L=N=>{C();let I=0;const v=(()=>{if($.search){const k=_(N);return I=y,k}return $.geo?Rn(i,t,$,S,N,k=>{I=k}):xn(i,t,$,S,O(),N,k=>{I=k})})();return p(Math.max(I,v.length)),v},j=()=>{if(!$.search&&!$.geo)throw new b("INTERNAL",`ctx.db.query("${t}").collectWithScores() requires a staged .withSearchIndex(...) or .withGeoIndex(...)`);C();let N=0;const I=(()=>{if($.search){const v=E(void 0);return N=y,v}return An(i,t,$,S,void 0,v=>{N=v})})();return p(Math.max(N,I.length)),I},U={async*[Symbol.asyncIterator](){const N=[...$.inMemoryFilters];let I;$.inMemoryFilters=[];try{for(;;){const v=await U.paginate({cursor:I??null,numItems:mn});for(const k of v.page)N.every(H=>H(k))&&(yield k);if(v.isDone||v.continueCursor===null)return;I=v.continueCursor}}finally{$.inMemoryFilters=N}},async collect(){return L(void 0)},async collectWithScores(){return j()},filter(N){return $.inMemoryFilters.push(N),U},async first(){return L($.inMemoryFilters.length>0?void 0:1)[0]??null},order(N){return $.order=N==="desc"?"desc":"asc",U},async paginate(N){let I=0;if(C(),$.search){const k=M(N);return p(k.page.length),k}if($.geo)throw new b("INTERNAL","pagination is not supported on geo queries; use .take(n) or .collect()");const v=Ln(i,t,$,N,S,k=>{I=k});return p(Math.max(I,v.page.length)),v},async take(N){return L(N)},async unique(){const N=L($.inMemoryFilters.length>0?void 0:2);if(N.length>1)throw new Dn(`unique() on table "${t}" matched ${String(N.length)} documents; expected at most one`);return N[0]??null},withGeoIndex(N,I){const v=(m.geoIndexes??[]).find(H=>H.name===N);if(!v)throw new b("INTERNAL",`unknown geo index "${N}" on table "${t}"`);l(t,N,"geo");const k={definition:v,indexName:N};if($.geo=k,I(En(k,t)),!k.near&&!k.within)throw new b("INTERNAL",`geo index "${N}" on table "${t}" requires a .near(point, radius) or .within(box) call`);return U},withIndex(N,I){const v=m.indexes.find(k=>k.name===N);if(!v)throw new b("INTERNAL",`unknown index "${N}" on table "${t}"`);return l(t,N,"index"),$.indexName=N,$.indexFields=v.fields,I&&I($n($)),U},withSearchIndex(N,I){const v=(m.searchIndexes??[]).find(H=>H.name===N);if(!v)throw new b("INTERNAL",`unknown search index "${N}" on table "${t}"`);l(t,N,"search");const k={definition:v,field:v.field,filters:[],hasQuery:!1,indexName:N,query:""};if($.search=k,I(an(k,t,Pe(v.language))),!k.hasQuery)throw new b("INTERNAL",`search index "${N}" on table "${t}" requires a .search(field, query) call`);return U}};return U},ct=(i,o,t)=>{const l={...o};for(const[c,p]of pt(i)){if(p.serverDefault){l[c]=p.serverDefault({auth:t});continue}l[c]===void 0&&(p.defaultFn?l[c]=p.defaultFn():"defaultValue"in p&&(l[c]=p.defaultValue))}return l},ut=(i,o,t,l)=>{const c=t;for(const[p,m]of pt(i)){if(m.serverDefault){p in o&&(c[p]=m.serverDefault({auth:l}));continue}m.onUpdateFn&&!(p in o)&&(c[p]=m.onUpdateFn())}},ft=(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.`)},qn=/unique constraint failed/i,Bn=i=>i instanceof Error&&qn.test(i.message),Ue=(i,o,t)=>{try{F(i,t)}catch(l){throw Bn(l)?new me(`unique constraint violation on "${o}"`,"unique"):l}},Ae=(i,o,t)=>{if(Ue(i,o,t),F(i,n`SELECT changes() AS changed`).one().changed===0)throw new me(`optimistic concurrency conflict on "${o}" — the row changed during this mutation; refetch and retry`,"occ")},ht=(i,o,t,l,c,p,m)=>{const R=[];for(let E=0;E<t.length+1;E+=1){const _=[];for(let L=0;L<E;L+=1)_.push(n`${n.identifier(t[L])} IS ${p[L]}`);const M=t[E],O=l[E];if(M!==void 0&&O!==void 0){const L=O.direction==="desc"?">":"<";_.push(n`${n.identifier(M)} ${n.raw(L)} ${p[E]}`)}else _.push(n`${n.identifier(Kt)} < ${m}`);const[C]=_;R.push(_.length===1&&C!==void 0?C:n`(${n.join(_,n` AND `)})`)}const S=n.join(R,n` OR `),$=F(i,n`SELECT COUNT(*) AS c FROM ${n.identifier(o)} WHERE ${n.identifier("__partition__")} = ${c} AND (${S})`).one(),y=F(i,n`SELECT COUNT(*) AS c FROM ${n.identifier(o)} WHERE ${n.identifier("__partition__")} = ${c}`).one();return{before:$.c,total:y.c}},hr=i=>{const{sql:o}=i,{schema:t}=i,l=i.broadcast??(()=>{}),c=(e,...r)=>{const a=t.tables[e]?.indexes;if(!a||a.length===0)return;const h=[];for(const f of r)f&&h.push(...Qt(a,f,re));return h.length>0?h:void 0},{headroom:p}=i;let m=!1;const R=async e=>{const r=m;m=!0;try{return await e()}finally{m=r}},S=i.onRead??(()=>{}),$=i.onReadRange??(e=>{S(e.table,B)}),y=(e,r)=>{r!==void 0&&r!==B&&!m&&p?.recordRead(1),S(e,r)},E=i.onIndexUse??(()=>{}),_=i.onWrite??(()=>{}),M=async e=>{m||p?.recordWrite(e.doc),await _(e)},{cache:O}=i,C=i.clock??(()=>Date.now()),L=i.idGenerator??(()=>crypto.randomUUID()),j=i.scheduler??At,{globalDb:U}=i,N=i.auth??{identity:null,userId:null},I=i.cdc??!1,v=j,k=Xt({scheduler:typeof v.list=="function"&&typeof v.get=="function"?v:void 0,storage:i.storage}),H=(e,r,a,h)=>{I&&Ct(o,C(),e,r,a,h)},X=e=>t.tables[e]?.shardMode?.kind==="global",ce=(e,r)=>{if(X(e)){if(!U)throw new b("INTERNAL",`cross-backend ${r} for global table '${e}' requires a globalDb writer — pass one to createShardCtxDb({ globalDb })`);return U}return q},ue=e=>ce(e,"cascade"),J=(e,r)=>{if(X(e)){if(!U)throw new b("INTERNAL",`${r} on global table '${e}' requires a globalDb writer — pass one to createShardCtxDb({ globalDb })`);return U}},fe=()=>U,xe=(e,r)=>ce(e,"relation load").findMany(e,r),He=(e,r)=>(X(e)&&y(e,B),xe(e,r)),yt=e=>!X(e.table),Ge=i.relationExistsPushDown??"auto",Ke=Ge!=="never",{maxRelationKeys:Qe}=i,$e=(e,r,a)=>it(e,{fetcher:He,maxRelationKeys:Qe,relationBaseWhere:a,schema:t,tableName:r}),ze=async(e,r,a,h)=>{const f=J(e,"relation grouped count");if(f)return y(e,B),Yt((x,K)=>f.count(x,K),e,r,a,h);const d=t.tables[e];if(!d)throw new b("INTERNAL",`unknown table: ${e}`);y(e,B);const s=le(d.softDeleteMode,void 0),u={[r]:{in:a}},w=Q(Q(u,h),s),T=await $e(w,e,void 0),g=ne(T,oe),A=z(r);let W=n`SELECT ${A} AS __fk__, COUNT(*) AS count FROM ${n.identifier(e)}`;g&&(W=n`${W} WHERE ${g}`),W=n`${W} GROUP BY ${A}`;const D=F(o,W).toArray();return new Map(D.map(x=>[x.__fk__,x.count]))};let ge=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 ee=(e,r,a)=>Je.has(`${e} ${r} ${a}`),te=async(e,r,a)=>{if(ge+=1,ge>lt)throw ge-=1,new me(`trigger recursion exceeded ${String(lt)} levels on "${a.table}" — check for a self-triggering write`,"trigger");try{await Zt({ctx:Nt,event:a,op:r,schema:t,tableName:a.table,timing:e})}finally{ge-=1}},{ensureBackfilledForTable:he,ensureBackfilledIndex:ve,ensureRankBackfilled:Ie,ensureRankBackfilledForTable:pe,syncAggregates:be,syncCompanionsForInsert:Ye,syncGeo:ye,syncRanks:we,syncSearch:Ee}=kt({broadcast:l,indexKeysFor:(e,r)=>c(e,r),invalidateCache:(e,r,a)=>O?.invalidate(e,r,c(e,a)),recordCdc:H,schema:t,sql:o}),Ve=(e,r,a)=>{const{shardMode:h}=r;if(h?.kind==="shardBy"&&!(h.field!==void 0&&(a.partitionBy??[]).includes(h.field)))throw Object.assign(new Error(`rank index "${a.name}" on "${e}" partitions across shards (shard key "${h.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})},ie=(e,r)=>{const a=Object.entries(t.tables).filter(([,T])=>T.shardMode?.kind!=="global").map(([T])=>T).filter(T=>r===void 0||T===r);if(a.length===0)return;const h=a.map(T=>n`SELECT ${n.raw(`'${T.replaceAll("'","''")}'`)} AS __t__, id, _creationTime, ${n.identifier(P)} FROM ${n.identifier(T)} WHERE id = ${e}`),f=n`${n.join(h,n` UNION ALL `)} LIMIT 1`,[d]=F(o,f).toArray();if(!d)return;const s=d.__t__,u=de(d);if(typeof s!="string"||!u)return;const w=d[P];return{docJson:typeof w=="string"?w:JSON.stringify(w??{}),row:u,tableName:s}},Et=(e,r)=>{const a=[...new Set(e)],h=new Map;if(a.length===0)return h;const f=Object.entries(t.tables).filter(([,s])=>s.shardMode?.kind!=="global").map(([s])=>s).filter(s=>r===void 0||s===r);if(f.length===0)return h;const d=Math.max(1,Math.floor(900/f.length));for(let s=0;s<a.length;s+=d){const u=a.slice(s,s+d),w=n.join(u.map(A=>n`${A}`),n`, `),T=f.map(A=>n`SELECT ${n.raw(`'${A.replaceAll("'","''")}'`)} AS __t__, id FROM ${n.identifier(A)} WHERE id IN (${w})`),g=n.join(T,n` UNION ALL `);for(const A of F(o,g)){const{id:W,__t__:D}=A;typeof D=="string"&&typeof W=="string"&&h.set(W,D)}}return h},Xe={assertRankPartitionLocal:Ve,ensureRankBackfilled:Ie,onRead:y,rowToDocument:de,schema:t,sql:o},q={system:k,async aggregate(e,r){const a=J(e,"aggregate");if(a)return y(e,B),a.aggregate(e,r);const h=t.tables[e];if(!h)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`);y(e,B);const f=le(h.softDeleteMode,void 0),d=Q(Q(r.baseWhere,r.where),f),s=await $e(d,e,r.relationBaseWhere),u=s!==d;if(h.aggregateIndexes&&!r.baseWhere&&!u&&!f){const D=It(h.aggregateIndexes,r.op,r.field,r.where);if(D){ve(e,D.index);const x=Me(D.index.by??[],D.key),K=ke(e,D.index.name),Y=F(o,n`SELECT ${_e} AS value, ${De} AS count FROM ${n.identifier(K)} WHERE ${Re} = ${x}`).toArray()[0];return Ce(r.op,Y)}}const w=ne(s,oe),T=Te(r.op),g=z(r.field);let A=n`SELECT ${n.raw(T)}(${g}) AS value FROM ${n.identifier(e)}`;return w&&(A=n`${A} WHERE ${w}`),F(o,A).toArray()[0]?.value??null},asId(e,r){const a=dt(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=J(e,"count");if(a)return y(e,B),a.count(e,r);const h=t.tables[e];if(!h)throw new b("INTERNAL",`unknown table: ${e}`);const f=Rt(r);if(f.restrictsCounts)throw new Le(e);y(e,B);const d=le(h.softDeleteMode,void 0),s=Q(Q(f.baseWhere,f.where),d),u=await $e(s,e,f.relationBaseWhere),w=u!==s;if(h.aggregateIndexes&&!f.baseWhere&&!w&&!d){const A=vt(h.aggregateIndexes,f.where);if(A){ve(e,A.index);const W=Me(A.index.by??[],A.key),D=ke(e,A.index.name),x=F(o,n`SELECT ${_e} AS value FROM ${n.identifier(D)} WHERE ${Re} = ${W}`).toArray();return x[0]===void 0?0:x[0].value??0}}const T=ne(u,oe);let g=n`SELECT COUNT(*) AS count FROM ${n.identifier(e)}`;return T&&(g=n`${g} WHERE ${T}`),F(o,g).one().count},async delete(e,r,a){const h=ie(e,r);if(!h){const g=r===void 0?fe():void 0;g&&await g.delete(e,void 0,a);return}const{docJson:f,row:d,tableName:s}=h,u=t.tables[s],w=a?.hard===!0,T=!w&&u?.softDeleteMode?u.softDeleteMode.field:void 0;if(!(T&&d[T]!==null&&d[T]!==void 0)){if(ee(s,"before","delete")&&await te("before","delete",{id:e,op:"delete",previous:d,table:s}),await Jt({deletedId:e,deletedReference:g=>d[g],findHolders:async(g,A,W)=>(await ue(g).findMany(g,{includeDeleted:w,where:{[A]:W}})).page,onCascade:(g,A)=>ue(g).delete(A,void 0,a),onRestrict:g=>{throw new me(g,"restrict")},onSetNull:(g,A,W)=>ue(g).patch(A,{[W]:null}),schema:t,tableName:s}),he(s),pe(s),T){const g={...d,[T]:C(),_id:e};Ae(o,s,n`UPDATE ${n.identifier(s)} SET ${n.identifier(P)} = ${JSON.stringify(g)} WHERE id = ${e} AND ${n.identifier(P)} = ${f}`),Ee(s,e,g,d),ye(s,e,void 0),be(s,d,g),we(s,e,d,void 0),O?.invalidate(s,e,c(s,d,g)),H(s,e,"update",g),l({indexKeys:c(s,d,g),key:e,op:"update",row:g,table:s}),ee(s,"after","delete")&&await te("after","delete",{id:e,op:"delete",previous:d,table:s}),await M({id:e,op:"delete",table:s});return}Ae(o,s,n`DELETE FROM ${n.identifier(s)} WHERE id = ${e} AND ${n.identifier(P)} = ${f}`),Ee(s,e,void 0),ye(s,e,void 0),be(s,d,void 0),we(s,e,d,void 0),O?.invalidate(s,e,c(s,d)),H(s,e,"delete"),l({indexKeys:c(s,d),key:e,op:"delete",table:s}),ee(s,"after","delete")&&await te("after","delete",{id:e,op:"delete",previous:d,table:s}),await M({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??$t),h=r?.hard===void 0?void 0:{hard:r.hard},f=X(e)?void 0:e;let d=0;return await R(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,f,h),d+=1;if(s.length<a)break}}),{deleted:d}},async deleteMany(e,r,a){se(e.length,r?.limit,"deleteMany");for(const h of e)await q.delete(h,a);return{deleted:e.length}},async deleteWhere(e,r,a){const h=J(e,"deleteWhere");let f;if(h)f=(await h.findMany(e,{where:r})).page.map(d=>String(d._id));else{if(!t.tables[e])throw new b("INTERNAL",`unknown table: ${e}`);f=(await q.findMany(e,{where:r})).page.map(d=>String(d._id))}if(se(f.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(f,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 Ut(`findFirstOrThrow: no "${e}" document matched`);return a},async findMany(e,r={}){const a=J(e,"findMany");if(a)return y(e,B),a.findMany(e,r);const h=t.tables[e];if(!h)throw new b("INTERNAL",`unknown table: ${e}`);const f=!r.where&&!r.baseWhere;f?y(e,B):y(e);const d=Pt(r.orderBy),s=r.cursor?mt(d,qe(r.cursor)):void 0;let u=Q(r.baseWhere,r.where);u=Q(u,le(h.softDeleteMode,r.includeDeleted)),u=await it(u,{canPushExists:Ke?yt:void 0,existsPushMode:Ge==="always"?"always":"auto",fetcher:He,maxRelationKeys:Qe,relationBaseWhere:r.relationBaseWhere,schema:t,tableName:e}),s&&(u=u?{AND:[u,s]}:s);const w=Ke?vn(y):oe,T=ne(u,w);let g=n`SELECT id, _creationTime, ${n.identifier(P)} FROM ${n.identifier(e)}`;T&&(g=n`${g} WHERE ${T}`),g=n`${g} ORDER BY ${bt(d)}`;const A=typeof r.limit=="number"?Math.max(0,Math.floor(r.limit)):void 0;A!==void 0&&(g=n`${g} LIMIT ${n.raw(String(A+1))}`);const W=F(o,g).toArray();f&&!m&&p?.recordRead(W.length);const D=[];for(const V of W){const G=de(V);G&&(D.push(G),!f&&typeof G._id=="string"&&y(e,G._id))}if(A===void 0)return r.with&&await ot({groupedCounter:ze,fetcher:xe,parents:D,relationBaseWhere:r.relationBaseWhere,schema:t,tableName:e,with:r.with}),{continueCursor:null,isDone:!0,page:tt(D,r.select,r.with)};const x=D.length>A,K=x?D.slice(0,A):D,Y=K.at(-1);return r.with&&await ot({fetcher:xe,groupedCounter:ze,parents:K,relationBaseWhere:r.relationBaseWhere,schema:t,tableName:e,with:r.with}),{continueCursor:x&&Y?Be(Y,d):null,isDone:!x,page:tt(K,r.select,r.with)}},async get(e,r){const a=ie(e,r);if(!a){const h=r===void 0?fe():void 0;return h?h.get(e):null}return y(a.tableName,e),a.row},async lookupById(e,r){const a=ie(e,r);return a?(y(a.tableName,e),{row:a.row,tableName:a.tableName}):null},async groupBy(e,r){const a=J(e,"groupBy");if(a)return y(e,B),a.groupBy(e,r);const h=t.tables[e];if(!h)throw new b("INTERNAL",`unknown table: ${e}`);y(e,B);const f=r.agg??{op:"count"};if(Te(f.op),f.op!=="count"&&!f.field)throw new b("INTERNAL",`groupBy(${e}, { agg: { op: "${f.op}" } }): "field" is required for non-count reducers`);const d=le(h.softDeleteMode,void 0),s=Q(Q(r.baseWhere,r.where),d),u=await $e(s,e,r.relationBaseWhere),w=u!==s;if(h.aggregateIndexes&&!r.baseWhere&&!w&&!d){const x=xt(h.aggregateIndexes,f.op,f.field,r.by,r.where);if(x){ve(e,x.index);const K=ke(e,x.index.name),Y=Object.keys(x.partial),V=[];if(Y.length===(x.index.by??[]).length&&Y.length>0){const ae=Me(x.index.by??[],x.partial),Ne=F(o,n`SELECT ${_e} AS value, ${De} AS count FROM ${n.identifier(K)} WHERE ${Re} = ${ae}`).toArray();return Ne.length>0&&V.push({key:{...x.partial},value:Ce(f.op,Ne[0])}),V}const G=F(o,n`SELECT ${Re} AS key, ${_e} AS value, ${De} AS count FROM ${n.identifier(K)}`).toArray();for(const ae of G){const Ne=JSON.parse(ae.key);V.push({key:Ne,value:Ce(f.op,ae)})}return V}}const T=ne(u,oe),g=r.by.map(x=>n`${z(x)} AS ${n.identifier(x)}`);if(f.op==="count")g.push(n`COUNT(*) AS value`);else{const{field:x}=f;if(x===void 0)throw new b("INTERNAL",`groupBy(${e}, { agg: { op: "${f.op}" } }): "field" is required for non-count reducers`);g.push(n`${n.raw(Te(f.op))}(${z(x)}) AS value`)}let A=n`SELECT ${n.join(g,n`, `)} FROM ${n.identifier(e)}`;T&&(A=n`${A} WHERE ${T}`),A=n`${A} GROUP BY ${n.join(r.by.map(x=>z(x)),n`, `)}`;const W=F(o,A).toArray(),D=[];for(const x of W){const K={};for(const V of r.by)K[V]=x[V]??null;const{value:Y}=x;D.push({key:K,value:Y==null?null:Number(Y)})}return D},async insert(e,r,a){const h=J(e,"insert");if(h){const T=await h.insert(e,r,a);return m||p?.recordWrite(r),l({key:T,op:"insert",row:{...r,_id:T},table:e}),T}const f=t.tables[e];if(!f)throw new b("INTERNAL",`unknown table: ${e}`);const d=ct(f,r,N);We(f,d);let s;a?.clientId!==void 0?(wn(a.clientId),s=a.clientId):a?.allowExplicitId&&typeof d._id=="string"?s=d._id:s=L();const u=a?.allowExplicitId&&typeof d._creationTime=="number"?d._creationTime:C(),w={...d,_creationTime:u,_id:s};return ee(e,"before","insert")&&await te("before","insert",{doc:{...w},id:s,op:"insert",table:e}),he(e),pe(e),Ue(o,e,n`INSERT INTO ${n.identifier(e)} (id, _creationTime, ${n.identifier(P)}) VALUES (${s}, ${u}, ${JSON.stringify(w)})`),Ye(e,s,w),ee(e,"after","insert")&&await te("after","insert",{doc:w,id:s,op:"insert",table:e}),await M({doc:w,id:s,op:"insert",table:e}),s},async insertManyUnsafe(e,r,a){if(se(r.length,a?.limit,"insertManyUnsafe"),r.length===0)return[];const h=J(e,"insert");if(h){const u=[];for(const w of r){const T=await h.insert(e,w,{allowExplicitId:a?.allowExplicitId});m||p?.recordWrite(w),l({key:T,op:"insert",row:{...w,_id:T},table:e}),u.push(T)}return u}const f=t.tables[e];if(!f)throw new b("INTERNAL",`unknown table: ${e}`);he(e),pe(e);const d=r.map(u=>{const w=ct(f,u,N),T=a?.allowExplicitId===!0&&typeof w._id=="string"?w._id:L(),g=a?.allowExplicitId===!0&&typeof w._creationTime=="number"?w._creationTime:C();return{creationTime:g,document:{...w,_creationTime:g,_id:T},id:T}});if(!m)for(const u of d)p?.recordWrite(u.document);const s=n.join(d.map(u=>n`(${u.id}, ${u.creationTime}, ${JSON.stringify(u.document)})`),n`, `);Ue(o,e,n`INSERT INTO ${n.identifier(e)} (id, _creationTime, ${n.identifier(P)}) VALUES ${s}`);for(const{document:u,id:w}of d)Ye(e,w,u),await _({doc:u,id:w,op:"insert",table:e});return d.map(u=>u.id)},async insertMany(e,r,a){se(r.length,a?.limit,"insertMany");const h=a?.skipDuplicates===!0,f=[];for(const d of r)try{f.push(await q.insert(e,d))}catch(s){if(h&&s instanceof me&&s.kind==="unique")f.push(null);else throw s}return f},normalizeId(e,r){return dt(t,e,r)},async patch(e,r,a){const h=ie(e,a);if(!h){const T=a===void 0?fe():void 0;if(T){await T.patch(e,r);return}throw new b("INTERNAL",`document not found: ${e}`)}const{docJson:f,row:d,tableName:s}=h,u=t.tables[s];if(!u)throw new b("INTERNAL",`unknown table: ${s}`);y(s,e),ft("patch",r);const w={...d,...r,_id:e};ut(u,r,w,N),We(u,w,!0),ee(s,"before","update")&&await te("before","update",{doc:{...w},id:e,op:"update",previous:d,table:s}),he(s),pe(s),Ae(o,s,n`UPDATE ${n.identifier(s)} SET ${n.identifier(P)} = ${JSON.stringify(w)} WHERE id = ${e} AND ${n.identifier(P)} = ${f}`),Ee(s,e,w,d),ye(s,e,w),be(s,d,w),we(s,e,d,w),O?.invalidate(s,e,c(s,d,w)),H(s,e,"update",w),l({indexKeys:c(s,d,w),key:e,op:"update",row:w,table:s}),ee(s,"after","update")&&await te("after","update",{doc:w,id:e,op:"update",previous:d,table:s}),await M({doc:w,id:e,op:"update",table:s})},async patchMany(e,r,a){se(e.length,r?.limit,"patchMany");for(const h of e)await q.patch(h.id,h.patch,a);return{patched:e.length}},async patchWhere(e,r,a){const h=J(e,"patchWhere");let f;if(h)f=(await h.findMany(e,{where:r.where})).page.map(d=>({id:String(d._id),patch:r.patch}));else{if(!t.tables[e])throw new b("INTERNAL",`unknown table: ${e}`);f=(await q.findMany(e,{where:r.where})).page.map(d=>({id:String(d._id),patch:r.patch}))}if(se(f.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(f,a),{patched:f.length}},query(e){const r=J(e,"query");return r?(y(e,B),r.query(e)):Fn(o,t,e,E,a=>{a?$(a):y(e,B)},a=>{m||p?.recordRead(a)})},async rank(e,r,a){const h=J(e,"rank");if(h)return y(e,B),h.rank(e,r,a);E(e,r,"rank");const f=t.tables[e];if(!f)throw new b("INTERNAL",`unknown table: ${e}`);const d=f.rankIndexes?.find(G=>G.name===r);if(!d)throw new b("INTERNAL",`unknown rankIndex "${r}" on table "${e}"`);if(Ve(e,f,d),a.restrictsCounts)throw new Le(e);y(e,B),Ie(e,d);const s=typeof a.row=="string"?a.row:a.row._id;if(!s)return null;const u=rt(e,d.name),w=d.sortBy.map((G,ae)=>nt(ae)),T=w.map(G=>Lt(G)).join(", "),g=F(o,n`SELECT ${n.identifier("__partition__")}, ${n.raw(T)} FROM ${n.identifier(u)} WHERE ${n.identifier("__id__")} = ${s}`).toArray(),[A]=g;if(A===void 0)return null;let W=A.__partition__;const D=Q(a.baseWhere,a.where);Oe(D,t,e,"rank");const x=Ht(d,D);if(x){const G=Gt(d.partitionBy??[],x);if(G!==W)return null;W=G}const K=w.map(G=>A[G]),{before:Y,total:V}=ht(o,u,w,d.sortBy,W,K,s);return{position:Y+1,total:V}},async rankBefore(e,r,a){if(X(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 h=t.tables[e];if(!h)throw new b("INTERNAL",`unknown table: ${e}`);const f=h.rankIndexes?.find(w=>w.name===r);if(!f)throw new b("INTERNAL",`unknown rankIndex "${r}" on table "${e}"`);if(a.restrictsCounts)throw new Le(e);y(e,B),Ie(e,f);const d=rt(e,f.name),s=f.sortBy.map((w,T)=>nt(T)),u=f.sortBy.map((w,T)=>re(a.sortValues[T]??null));return ht(o,d,s,f.sortBy,a.partitionKey,u,a.rowId)},async rankPage(e,r,a={}){Oe(Q(a.baseWhere,a.where),t,e,"rankPage");const h=J(e,"rankPage");if(h)return y(e,B),h.rankPage(e,r,a);E(e,r,"rank");const{continueCursor:f,hasMore:d,rows:s}=Ze(Xe,e,r,a);return{continueCursor:f,isDone:!d,page:s.map(u=>u.doc)}},async rankPageRows(e,r,a={}){Oe(Q(a.baseWhere,a.where),t,e,"rankPage"),E(e,r,"rank");const{directions:h,hasMore:f,rows:d}=Ze(Xe,e,r,a);return{directions:h,hasMore:f,rows:d}},async restore(e,r){const a=ie(e,r);if(!a){const d=r===void 0?fe():void 0;if(d?.restore){await d.restore(e);return}throw new b("INTERNAL",`document not found: ${e}`)}const h=t.tables[a.tableName]?.softDeleteMode?.field;if(!h)throw new b("INTERNAL",`ctx.db.restore: table "${a.tableName}" is not a .softDelete() table`);const f=a.row[h]!==null&&a.row[h]!==void 0;await q.patch(e,{[h]:null},r),f&&we(a.tableName,e,void 0,a.row)},async replace(e,r,a,h){const f=ie(e,a);if(!f){const A=a===void 0?fe():void 0;if(A){await A.replace(e,r,void 0,h);return}throw new b("INTERNAL",`document not found: ${e}`)}const{docJson:d,row:s,tableName:u}=f,w=t.tables[u];if(!w)throw new b("INTERNAL",`unknown table: ${u}`);ft("replace",r);const T=h?.allowExplicitId&&typeof r._creationTime=="number"?r._creationTime:C(),g={...r,_creationTime:T,_id:e};ut(w,r,g,N),We(w,g),ee(u,"before","update")&&await te("before","update",{doc:{...g},id:e,op:"update",previous:s,table:u}),he(u),pe(u),Ae(o,u,n`UPDATE ${n.identifier(u)} SET _creationTime = ${T}, ${n.identifier(P)} = ${JSON.stringify(g)} WHERE id = ${e} AND ${n.identifier(P)} = ${d}`),Ee(u,e,g,s),ye(u,e,g),be(u,s,g),we(u,e,s,g),O?.invalidate(u,e,c(u,s,g)),H(u,e,"update",g),l({indexKeys:c(u,s,g),key:e,op:"update",row:g,table:u}),ee(u,"after","update")&&await te("after","update",{doc:g,id:e,op:"update",previous:s,table:u}),await M({doc:g,id:e,op:"update",table:u})},async wipeShard(e){const r=new Set(e?.exclude),a=e?.tables,h=Object.entries(t.tables).filter(([u,w])=>r.has(u)||a!==void 0&&!a.includes(u)?!1:w.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 f={};let d=0;const{deleteAll:s}=q;if(s===void 0)throw new b("INTERNAL","wipeShard: this writer has no deleteAll");for(const u of h){const w=await s(u,{...e?.chunkSize===void 0?{}:{chunkSize:e.chunkSize},hard:!0});f[u]=w.deleted,d+=w.deleted}return{deleted:d,tables:f}}},Nt={db:q,scheduler:j};return i.enforceRls===!0?Vt(q,t,(e,r)=>ie(e,r)?.tableName,(e,r)=>Et(e,r)):q};export{yr as CDC_LOG_TABLE,vr as CLIENT_WATERMARK_TABLE,Lr as GLOBAL_SHAPE_SNAPSHOT_TABLE,Ur as IDEMPOTENCY_TABLE,Dn as NotUniqueError,zr as SEARCH_STATE_TABLE,Ir as advanceClientWatermark,Er as applyCdcChanges,wn as assertValidClientId,mr as backfillAggregateIndexes,$r as backfillRankIndexes,gr as backfillSearchIndexes,Nr as bumpCdcEpoch,hr as createShardCtxDb,Dr as deleteGlobalShapeSnapshot,Or as deleteGlobalShapeSnapshotsForConnection,Mr as migrateClientWatermark,Wr as migrateGlobalShapeSnapshot,Sr as minCdcSeq,dt as normalizeIdStructurally,Tr as readCdcChanges,_r as readCdcCursor,Rr as readCdcEpoch,Cr as readClientWatermark,Fr as readGlobalShapeSnapshot,Pr as readIdempotent,Kr as runShardMigrations,Yr as selectShapeMemberIds,Vr as selectShapeRows,Ar as trimCdcChanges,jr as trimIdempotent,qr as writeGlobalShapeSnapshot,Hr as writeIdempotent};
@@ -0,0 +1 @@
1
+ import{LunoraError as g}from"@lunora/errors";const b=Symbol.for("lunora.ctxdb.rls-unwrap");class k extends g{table;constructor(i){super("RLS_REQUIRED",`ctx.db access to "${i}" is denied: the schema is marked .rls("required"), so this table is protected. Apply RLS with .use(rls(policies)) in the procedure, or mark the table .public() to opt it out.`,{name:"RlsRequiredError"}),this.table=i}}const M=o=>Object.entries(o.tables).filter(([,i])=>i.shardMode?.kind!=="global").map(([i])=>i),R=(o,i,u)=>{const n=i?.tables,r=new Set(i?.exclude);for(const d of o)(n===void 0||n.includes(d))&&!r.has(d)&&u(d)},m=(o,i,u)=>{const n={},{deleteAll:r,wipeShard:d}=o;return r&&(n.deleteAll=(s,c)=>(u(s),r(s,c))),d&&(n.wipeShard=s=>(R(M(i),s,u),d(s))),n},v=(o,i,u,n)=>{if(i.rlsMode!=="required")return o;const r=o,d=e=>{const t=i.tables[e];return t!==void 0&&t.isPublic!==!0},s=e=>{if(d(e))throw new k(e)},c=async(e,t)=>{if(t!==void 0){s(t);return}const a=await u(e);a!==void 0&&s(a)},p=async(e,t)=>{if(t!==void 0){s(t);return}if(!n){for(const l of e)await c(l,t);return}const a=await n([...new Set(e)],t);for(const l of e){const f=a.get(l);f!==void 0&&s(f)}},h=r.rankBefore,w=r.rankPageRows,y={...o,...m(r,i,s),[b]:o,aggregate:(e,t)=>(s(e),r.aggregate(e,t)),count:(e,t)=>(s(e),r.count(e,t)),delete:async(e,t,a)=>(await c(e,t),r.delete(e,t,a)),deleteMany:async(e,t,a)=>(await p(e,a),r.deleteMany(e,t,a)),deleteWhere:r.deleteWhere?async(e,t,a)=>(s(e),await r.deleteWhere?.(e,t,a)):void 0,findFirst:(e,t)=>(s(e),r.findFirst(e,t)),findFirstOrThrow:(e,t)=>(s(e),r.findFirstOrThrow(e,t)),findMany:(e,t)=>(s(e),r.findMany(e,t)),get:async(e,t)=>(await c(e,t),r.get(e,t)),groupBy:(e,t)=>(s(e),r.groupBy(e,t)),insert:(e,t,a)=>(s(e),r.insert(e,t,a)),insertMany:(e,t,a)=>(s(e),r.insertMany(e,t,a)),insertManyUnsafe:(e,t,a)=>(s(e),r.insertManyUnsafe(e,t,a)),lookupById:async(e,t)=>(await c(e,t),r.lookupById?.(e,t)??null),patch:async(e,t,a)=>(await c(e,a),r.patch(e,t,a)),patchMany:async(e,t,a)=>(await p(e.map(l=>l.id),a),r.patchMany(e,t,a)),patchWhere:r.patchWhere?async(e,t,a)=>(s(e),await r.patchWhere?.(e,t,a)):void 0,query:e=>(s(e),r.query(e)),rank:(e,t,a)=>(s(e),r.rank(e,t,a)),rankPage:(e,t,a)=>(s(e),r.rankPage(e,t,a)),replace:async(e,t,a,l)=>(await c(e,a),r.replace(e,t,a,l)),restore:async(e,t)=>(await c(e,t),r.restore?.(e,t))};return h&&(y.rankBefore=(e,t,a)=>(s(e),h(e,t,a))),w&&(y.rankPageRows=(e,t,a)=>(s(e),w(e,t,a))),y};export{b as RLS_UNWRAP_SYMBOL,k as RlsRequiredError,v as guardWriter};
@@ -0,0 +1 @@
1
+ import{stableWireKey as g}from"./stableWireKey-YEHLaX6X.mjs";import{depKey as b,SCAN_DEP as p}from"./SCAN_DEP-D_yR9EeV.mjs";import{t as y}from"./estimate-bytes-DwQON1Ky.mjs";import{keysTouchRanges as x}from"./buildIndexRange-DFsdtPjD.mjs";import{stableStringify as R}from"./stableStringify-BjLh4gvA.mjs";const m=1e3,u=4*1024*1024;class z{entries=new Map;tableIndex=new Map;rangeIndex=new Map;totalBytes=0;hits=0;misses=0;evictions=0;maxEntries;maxBytes;now;monotonic=0;constructor(t={}){this.maxEntries=t.maxEntries??m,this.maxBytes=t.maxBytes??u,this.now=t.now??(()=>(this.monotonic+=1,this.monotonic))}async run(t,s,i,e=()=>[]){const n=this.entries.get(t);if(n)return this.hits+=1,n.lastUsed=this.now(),this.entries.delete(t),this.entries.set(t,n),n.result;this.misses+=1;const h=await i(),o=y(h);if(o===void 0)return h;const c=e(),f={bytes:o,deps:s,ranges:c,lastUsed:this.now(),result:h,subscribers:new Set};this.entries.set(t,f),this.totalBytes+=o;for(const a of s){let r=this.tableIndex.get(a);r||(r=new Set,this.tableIndex.set(a,r)),r.add(t)}for(const a of c){let r=this.rangeIndex.get(a.table);r||(r=new Map,this.rangeIndex.set(a.table,r));let l=r.get(a);l||(l=new Set,r.set(a,l)),l.add(t)}return this.evict(),h}invalidate(t,s,i){const e=[];return this.collectAndDrop(b(t,s),e),this.collectAndDrop(b(t,p),e),this.dropRangeDeps(t,i,e),e}invalidateTable(t){const s=[],i=`${t}:`;for(const e of this.tableIndex.keys())e.startsWith(i)&&this.collectAndDrop(e,s);return this.dropRangeDeps(t,void 0,s),s}subscribe(t,s){const i=this.entries.get(t);i&&i.subscribers.add(s)}unsubscribe(t,s){const i=this.entries.get(t);i&&i.subscribers.delete(s)}size(){return{bytes:this.totalBytes,entries:this.entries.size}}clear(){this.entries.clear(),this.tableIndex.clear(),this.rangeIndex.clear(),this.totalBytes=0}subscribers(t){const s=this.entries.get(t);return s?[...s.subscribers]:[]}stats(){return{bytes:this.totalBytes,entries:this.entries.size,evictions:this.evictions,hits:this.hits,misses:this.misses}}dropRangeDeps(t,s,i){const e=this.rangeIndex.get(t);if(!(!e||e.size===0)){for(const[n,h]of e)if(x([n],s))for(const o of h){const c=this.entries.get(o);c&&(this.dropEntry(o,c),i.push(o))}}}collectAndDrop(t,s){const i=this.tableIndex.get(t);if(i)for(const e of i){const n=this.entries.get(e);n&&(this.dropEntry(e,n),s.push(e))}}dropEntry(t,s){this.entries.delete(t),this.totalBytes-=s.bytes;for(const i of s.deps){const e=this.tableIndex.get(i);e&&(e.delete(t),e.size===0&&this.tableIndex.delete(i))}for(const i of s.ranges){const e=this.rangeIndex.get(i.table),n=e?.get(i);n?.delete(t),e&&n?.size===0&&(e.delete(i),e.size===0&&this.rangeIndex.delete(i.table))}}evict(){if(!(this.entries.size<=this.maxEntries&&this.totalBytes<=this.maxBytes))for(const[t,s]of this.entries){if(this.entries.size<=this.maxEntries&&this.totalBytes<=this.maxBytes)return;s.subscribers.size>0||(this.dropEntry(t,s),this.evictions+=1)}}}const E=(d,t,s)=>`${s??"\0anon"}\0${d}:${g(t)}`;export{z as ReactiveCache,E as reactiveCacheKey,R as stableStringify,g as stableWireKey};
@@ -0,0 +1 @@
1
+ import{f as l}from"./wire-codec-Ctnni0h6.mjs";const c="_id",p="__lunora__",b=r=>{if(typeof r!="object"||r===null||Array.isArray(r))return;const t=r[c];return typeof t=="string"?t:void 0},y=r=>{const t=new Map,o=[];for(const s of r){const e=b(s);if(e===void 0||t.has(e))return;t.set(e,s),o.push(e)}return{byId:t,order:o}},g=(r,t)=>{const o=r.order.filter(e=>t.byId.has(e)),s=t.order.filter(e=>r.byId.has(e));return o.length!==s.length?!1:o.every((e,n)=>s[n]===e)},h=(r,t,o,s)=>{const e=[];for(const n of r.order)t.byId.has(n)||e.push({delta:{key:n,op:"delete",table:o},frame:`{"key":${JSON.stringify(n)},"op":"delete","table":${s}}`});return e},m=(r,t,o,s)=>{const e=[];for(const n of t.order){const i=t.byId.get(n),a=r.byId.get(n),f=JSON.stringify(l(i)),d=a===void 0?void 0:JSON.stringify(a);if(d===f)continue;const u=d===void 0?"insert":"update";e.push({delta:{key:n,op:u,row:i,table:o},frame:`{"key":${JSON.stringify(n)},"op":"${u}","row":${f},"table":${s}}`})}return e},S=(r,t,o,s)=>{let e;try{e=JSON.parse(r)}catch{return}if(!Array.isArray(e)||!Array.isArray(t))return;const n=y(e),i=y(t);if(n===void 0||i===void 0||!g(n,i))return;const a=o===""?p:o,f=JSON.stringify(a),d=[...h(n,i,a,f),...m(n,i,a,f)];if(!(d.length>i.order.length)){if(s!==void 0)for(const{frame:u}of d)s.push(u);return d.map(({delta:u})=>u)}},$=(r,t)=>{try{return r.send(t),!0}catch{return!1}},I=(r,t,o,s,e)=>{const n=JSON.stringify(t),i=e===void 0?"":`,"lastMutationId":${String(e)}`;let a=!0;for(const f of o)$(r,`{"type":"delta","id":${n},"delta":${f}${i}${s}}`)||(a=!1);return a},w=async r=>{let t=0;for(;t<100;){t+=1;const{bufferedAmount:o}=r;if(typeof o!="number"||o<1048576)return;await new Promise(s=>{setTimeout(s,20)})}};export{w as awaitWsDrain,I as sendDeltaFrames,S as subscriptionListDeltas,$ as trySendFrame};
@@ -0,0 +1 @@
1
+ const v=t=>{const o=new DataView(new ArrayBuffer(8));o.setFloat64(0,t,!1);let r=o.getUint32(0,!1),e=o.getUint32(4,!1);return(r&2147483648)===0?r=(r^2147483648)>>>0:(r=~r>>>0,e=~e>>>0),r.toString(16).padStart(8,"0")+e.toString(16).padStart(8,"0")},g=t=>{const o=new TextEncoder().encode(t);let r="";for(const e of o)r+=e.toString(16).padStart(2,"0");return r},c=t=>{if(t===null)return"0";if(typeof t=="number")return Number.isFinite(t)?`1${v(t===0?0:t)}`:void 0;if(typeof t=="string")return`2${g(t)}`},d=t=>{const o=[];for(const r of t){const e=c(r);if(e===void 0)return;o.push(e)}return o.join("!")};const p=new Set([">",">="]),x=new Set(["<","<="]),h=(t,o,r,e)=>{const i=o.comparator==="=",n=p.has(o.comparator)||x.has(o.comparator);return!i&&!n||t.indexOf(o.field)!==r?!1:e===void 0?!0:!i&&e===o.field},w=(t,o,r)=>{const e={equalities:[],lowerExclusive:!1,upperExclusive:!1};let i;for(const n of o){const s=n.comparator==="=",a=p.has(n.comparator);if(!h(t,n,e.equalities.length,i))return;if(s){e.equalities.push(r(n.value));continue}if(i=n.field,a){if(e.lower!==void 0)return;e.lower=r(n.value),e.lowerExclusive=n.comparator===">"}else{if(e.upper!==void 0)return;e.upper=r(n.value),e.upperExclusive=n.comparator==="<"}}return e},f=(t,o)=>{const r=c(o);if(r!==void 0)return t===""?r:t+"!"+r},y=(t,o,r,e,i)=>{if(r.length===0)return;const n=w(r,e,i);if(!n)return;const s=d(n.equalities);if(s===void 0)return;let a=s,l=s+"￿";if(n.lower!==void 0){const u=f(s,n.lower);if(u===void 0)return;a=n.lowerExclusive?u+"!￿":u}if(n.upper!==void 0){const u=f(s,n.upper);if(u===void 0)return;l=n.upperExclusive?u:u+"￿"}if(!(a>=l))return{hi:l,index:o,lo:a,table:t}},E=(t,o,r)=>{const e=[];for(const i of t){const n=d(i.fields.map(s=>r(o[s])));n!==void 0&&e.push({index:i.name,key:n})}return e},m=(t,o)=>t.index===o.index&&o.key>=t.lo&&o.key<t.hi,S=(t,o)=>{if(!t||t.length===0||!o||o.length===0)return!0;const r=new Map;for(const e of o){const i=r.get(e.index);i?i.push(e):r.set(e.index,[e])}return t.some(e=>{const i=r.get(e.index);return!i||i.length===0?!0:i.some(n=>m(e,n))})};export{y as buildIndexRange,E as indexKeysForRow,S as keysTouchRanges,m as rangeContains};
@@ -1 +1 @@
1
- import{createShardCtxDb as b}from"./NotUniqueError-iGKd9wRR.mjs";import{createRelayLink as I}from"./DEFAULT_MAX_RELAYS-CnCyh6oX.mjs";import{ConflictError as N}from"./ConflictError-C8GtJmjS.mjs";import{runShardMigrations as v}from"./runShardMigrations-CPxqCh3O.mjs";import{relayName as q}from"./DEFAULT_PROMOTION_THRESHOLDS-Dteg0sZF.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-Qrtwm7S6.mjs";import{createRelayLink as I}from"./DEFAULT_MAX_RELAYS-D0oc40p6.mjs";import{ConflictError as N}from"./ConflictError-C8GtJmjS.mjs";import{runShardMigrations as v}from"./runShardMigrations-CPxqCh3O.mjs";import{relayName as q}from"./DEFAULT_PROMOTION_THRESHOLDS-Dteg0sZF.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};
@@ -0,0 +1 @@
1
+ const r=n=>{try{const t=JSON.stringify(n);return t===void 0?0:t.length}catch{return}};export{r as t};
@@ -1 +1 @@
1
- import{keysTouchRanges as g}from"./buildIndexRange-DIjFVgeO.mjs";const c=(s,t,o)=>{const e=s??new Map;for(const n of o){const r=t?.get(n),a=e.get(n),i=e.has(n)&&a===void 0;if(!t?.has(n)||r===void 0||i){e.set(n,void 0);continue}e.set(n,a?[...a,...r]:r)}return e},f=(s,t,o)=>{const e=s??new Map;if(e.has(t)&&e.get(t)===void 0)return e;if(!o||o.length===0)return e.set(t,void 0),e;const n=e.get(t);return e.set(t,n?[...n,...o]:[...o]),e},h=(s,t,o)=>{if(!o)return!0;for(const e of t){if(!s.tables.has(e))continue;const n=s.ranges?.get(e);if(!n||n.length===0||g(n,o.get(e)))return!0}return!1};export{c as mergeChangedKeys,f as recordChangedKeys,h as writeTouchesMemo};
1
+ import{keysTouchRanges as g}from"./buildIndexRange-DFsdtPjD.mjs";const c=(s,t,o)=>{const e=s??new Map;for(const n of o){const r=t?.get(n),a=e.get(n),i=e.has(n)&&a===void 0;if(!t?.has(n)||r===void 0||i){e.set(n,void 0);continue}e.set(n,a?[...a,...r]:r)}return e},f=(s,t,o)=>{const e=s??new Map;if(e.has(t)&&e.get(t)===void 0)return e;if(!o||o.length===0)return e.set(t,void 0),e;const n=e.get(t);return e.set(t,n?[...n,...o]:[...o]),e},h=(s,t,o)=>{if(!o)return!0;for(const e of t){if(!s.tables.has(e))continue;const n=s.ranges?.get(e);if(!n||n.length===0||g(n,o.get(e)))return!0}return!1};export{c as mergeChangedKeys,f as recordChangedKeys,h as writeTouchesMemo};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@lunora/shard-engine",
3
- "version": "1.0.0-alpha.4",
3
+ "version": "1.0.0-alpha.6",
4
4
  "description": "Host-neutral reactive engine for Lunora: per-shard state, OCC, CDC, reactive subscriptions, and the poke protocol. Consumes @lunora/platform host contracts and can be mounted on any platform host.",
5
5
  "keywords": [
6
6
  "cloudflare",
@@ -48,8 +48,8 @@
48
48
  "access": "public"
49
49
  },
50
50
  "dependencies": {
51
- "@lunora/errors": "1.0.0-alpha.10",
52
- "@lunora/platform": "1.0.0-alpha.1",
51
+ "@lunora/errors": "1.0.0-alpha.12",
52
+ "@lunora/platform": "1.0.0-alpha.3",
53
53
  "drizzle-orm": "^0.45.2"
54
54
  },
55
55
  "engines": {
@@ -1 +0,0 @@
1
- import{LunoraError as M}from"@lunora/errors";import{q as d}from"./quote-identifier-CGiYFBvY.mjs";const K="__lunora_admin__:",X="__lunora_relation__:",Y="__lunora_flags__:",z={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",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"},N=50,b=500,x=30,F=200,m="__doc__",w=e=>{try{const a=JSON.parse(e);return a!==null&&typeof a=="object"&&!Array.isArray(a)?a:void 0}catch{return}},L=(e,a)=>{if(!e.includes(m))return{columns:e,rows:a};const r=[];for(const s of a){const _=s[m],i=typeof _=="string"?w(_):void 0;if(i===void 0)return{columns:e,rows:a};const u=Object.fromEntries(Object.entries(s).filter(([l])=>l!==m));r.push({...u,...i})}const t=e.filter(s=>s!==m),n=[],o=new Set(t);for(const s of r)for(const _ of Object.keys(s))o.has(_)||(o.add(_),n.push(_));return{columns:[...t,...n],rows:r}},O=e=>e.replaceAll(/[\\%_]/g,a=>`\\${a}`),S=e=>e.startsWith("sqlite_")||e.startsWith("_cf_")||e.startsWith("__miniflare")||e.startsWith("__lunora")||e.includes("__fts_"),I=(e,a,r)=>Math.min(Math.max(e,a),r),k=(e,a)=>{const r=e.exec(`SELECT COUNT(*) AS c FROM ${a}`).one();return Number(r.c)},V=e=>{const a=e.exec("SELECT name FROM sqlite_master WHERE type = 'table' ORDER BY name").toArray(),r=[];for(const{name:t}of a)S(t)||r.push({name:t,rowCount:k(e,d(t))});return r},A=(e,a)=>e.exec("SELECT name FROM sqlite_master WHERE type = 'table' AND name = ? LIMIT 1",a).toArray().length>0,P={eq:"=",gt:">",gte:">=",lt:"<",lte:"<=",ne:"<>"},U=e=>typeof e=="string"?e:typeof e=="number"||typeof e=="boolean"?String(e):"",T=(e,a)=>{const r=a.includes(e),t=a.includes(m);if(!(!r&&!t))return r?{expression:d(e),params:[]}:{expression:`json_extract(${d(m)}, ?)`,params:[`$."${e.replaceAll('"','""')}"`]}},W=(e,a)=>{const r=T(e.column,a);if(r===void 0)return;const{expression:t,params:n}=r;return e.operator==="contains"?{params:[...n,`%${O(U(e.value))}%`],sql:String.raw`CAST(${t} AS TEXT) LIKE ? ESCAPE '\'`}:{params:[...n,e.value],sql:`${t} ${P[e.operator]} ?`}},D=/^(\d{4})(?:-(\d{2}))?(?:-(\d{2}))?$/u,q=e=>{const a=D.exec(e.trim());if(a===null)return;const r=Number(a[1]),t=a[2]===void 0?void 0:Number(a[2]),n=a[3]===void 0?void 0:Number(a[3]);if(t!==void 0&&(t<1||t>12)||n!==void 0&&(n<1||n>31)||r<100)return;const o=Date.UTC(r,(t??1)-1,n??1);if(n!==void 0&&new Date(o).getUTCDate()!==n)return;let s;return n!==void 0?s=Date.UTC(r,t===void 0?0:t-1,n+1):t===void 0?s=Date.UTC(r+1,0,1):s=Date.UTC(r,t,1),{from:o,to:s}},v=(e,a,r)=>{const t=[],n=[];if(a!==""&&e.length>0){const o=`%${O(a)}%`,s=e.map(i=>String.raw`CAST(${d(i)} AS TEXT) LIKE ? ESCAPE '\'`);n.push(...e.map(()=>o));const _=q(a);if(_!==void 0)for(const i of e)s.push(`(${d(i)} >= ? AND ${d(i)} < ?)`),n.push(_.from,_.to);t.push(`(${s.join(" OR ")})`)}for(const o of r??[]){const s=W(o,e);s!==void 0&&(t.push(`(${s.sql})`),n.push(...s.params))}return t.length===0?void 0:{parameters:n,where:t.join(" AND ")}},Q=(e,a)=>{if(e===void 0)return;const r=T(e.column,a);if(r===void 0)return;const t=e.direction==="desc"?"DESC":"ASC";return{params:r.params,sql:`${r.expression} ${t}`}},J=(e,a)=>{const{table:r}=a;if(S(r)||!A(e,r))throw new M("UNKNOWN_TABLE",`unknown table: ${r}`,{status:404});const t=I(Math.trunc(a.limit??N),1,b),n=Math.max(0,Math.trunc(a.offset??0)),o=d(r),s=e.exec(`PRAGMA table_info(${o})`).toArray().map(h=>h.name),_=a.search?.trim()??"",i=h=>{if(a.refs===void 0)return h;const C={};for(const R of h.columns){const $=a.refs[R];$!==void 0&&(C[R]=$)}return Object.keys(C).length>0?{...h,refs:C}:h},u=v(s,_,a.filters),l=Q(a.orderBy,s),c=u===void 0?"":` WHERE ${u.where}`,f=l===void 0?"":` ORDER BY ${l.sql}`,g=u?.parameters??[],E=l?.params??[];let p;a.skipCount||(p=u===void 0?k(e,o):Number(e.exec(`SELECT COUNT(*) AS c FROM ${o}${c}`,...g).one().c));const y=e.exec(`SELECT * FROM ${o}${c}${f} LIMIT ? OFFSET ?`,...g,...E,t,n).toArray();return i({...L(s,y),total:p})},Z=(e,a)=>{const{table:r}=a;if(S(r)||!A(e,r))throw new M("UNKNOWN_TABLE",`unknown table: ${r}`,{status:404});const t=I(Math.trunc(a.limit??b),1,b),n=d(r),o=e.exec(`PRAGMA table_info(${n})`).toArray().map(c=>c.name),s=a.search?.trim()??"",_=v(o,s,a.filters),i=_===void 0?e.exec(`SELECT id FROM ${n} LIMIT ?`,t+1).toArray():e.exec(`SELECT id FROM ${n} WHERE ${_.where} LIMIT ?`,..._.parameters,t+1).toArray(),u=i.length>t,l=(u?i.slice(0,t):i).map(c=>c.id);return{hasMore:u,ids:l}},j=(e,a,r)=>{const t=new Set(r.filter(o=>o!==m));if(!r.includes(m))return t;const n=e.exec(`SELECT ${d(m)} AS doc FROM ${a} LIMIT ?`,b).toArray();for(const{doc:o}of n){const s=typeof o=="string"?w(o):void 0;if(s!==void 0)for(const _ of Object.keys(s))t.add(_)}return t},ee=(e,a)=>{const{column:r,table:t}=a;if(S(t)||!A(e,t))throw new M("UNKNOWN_TABLE",`unknown table: ${t}`,{status:404});const n=d(t),o=e.exec(`PRAGMA table_info(${n})`).toArray().map(p=>p.name);if(!j(e,n,o).has(r))throw new M("UNKNOWN_COLUMN",`unknown column: ${r}`,{status:404});const s=T(r,o);if(s===void 0)throw new M("UNKNOWN_COLUMN",`unknown column: ${r}`,{status:404});const _=I(Math.trunc(a.limit??x),1,F),i=a.search?.trim()??"",u=v(o,i,a.filters),l=u===void 0?"":` WHERE ${u.where}`,c=u?.parameters??[],f=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(),g=f.length>_,E=g?f.slice(0,_):f;return{truncated:g,values:E.map(p=>({count:Number(p.count),value:p.value}))}},ae=(e,a,r)=>{const t={},n=r.slice(0,b);for(const s of n)t[s]=[];if(n.length===0)return{references:t,storageColumns:a};const o=n.map(()=>"?").join(", ");for(const[s,_]of Object.entries(a)){if(S(s)||!A(e,s))continue;const i=d(s),u=e.exec(`PRAGMA table_info(${i})`).toArray().map(l=>l.name);for(const l of _){const c=T(l,u);if(c===void 0)continue;const f=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 f)t[g.ref]?.push({column:l,id:g.id,table:s})}}return{references:t,storageColumns:a}},te=e=>{const a=e.map((t,n)=>{const o=Object.values(t.subs??{}).map(s=>({args:s.args,functionPath:s.functionPath,table:s.table}));return{admin:t.admin===!0,id:n,subscriptions:o}}),r=a.reduce((t,n)=>t+n.subscriptions.length,0);return{connections:a,totalConnections:a.length,totalSubscriptions:r}},B=20,re=()=>({maxMs:0,passes:0,peakSocketsIterated:0,socketsDelivered:0,socketsIterated:0,totalMs:0}),se=(e,a,r,t)=>({maxMs:Math.max(e.maxMs,t),passes:e.passes+1,peakSocketsIterated:Math.max(e.peakSocketsIterated,a),socketsDelivered:e.socketsDelivered+r,socketsIterated:e.socketsIterated+a,totalMs:e.totalMs+t}),ne=(e,a=B)=>{const r=new Map,t=new Map;for(const o of e){for(const s of Object.values(o.shapes??{})){const _=s.name??"(unknown shape)";r.set(_,(r.get(_)??0)+1)}for(const s of o.whispers??[])t.set(s,(t.get(s)??0)+1)}const n=[...[...r].map(([o,s])=>({kind:"shape",subscribers:s,topic:o})),...[...t].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,a),totalConnections:e.length}};export{z as ADMIN_FUNCTIONS,K as ADMIN_FUNCTION_PREFIX,B as DEFAULT_FANOUT_TOPIC_LIMIT,Y as FLAGS_FUNCTION_PREFIX,b as MAX_PAGE_SIZE,X as RELATION_FUNCTION_PREFIX,re as createFanoutCounters,q as datePrefixRange,ee as facetColumn,ae as findStorageReferences,V as listTables,J as readTablePage,se as recordFanoutPass,Z as selectMatchingIds,ne as summarizeFanoutTopics,te as summarizeSubscriptions};
@@ -1 +0,0 @@
1
- import{LunoraError as i}from"@lunora/errors";import{r as s}from"./estimate-bytes-DzD3PdCc.mjs";const e={maxReadRows:1e5,maxWrittenBytes:32*1024*1024,maxWrittenRows:5e4};class a{readRows=0;writtenRows=0;writtenBytes=0;limits;constructor(t={}){this.limits={...e,...t}}recordRead(t){if(this.readRows+=t,this.readRows>this.limits.maxReadRows)throw new i("TRANSACTION_LIMIT_EXCEEDED",`this transaction read ${String(this.readRows)} documents, over the ${String(this.limits.maxReadRows)}-document limit`)}recordWrite(t){if(this.writtenRows+=1,this.writtenBytes+=s(t,this.limits.maxWrittenBytes),this.writtenRows>this.limits.maxWrittenRows)throw new i("TRANSACTION_LIMIT_EXCEEDED",`this transaction wrote ${String(this.writtenRows)} documents, over the ${String(this.limits.maxWrittenRows)}-document limit`);if(this.writtenBytes>this.limits.maxWrittenBytes)throw new i("TRANSACTION_LIMIT_EXCEEDED",`this transaction wrote ${String(this.writtenBytes)} bytes, over the ${String(this.limits.maxWrittenBytes)}-byte limit`)}headroom(){return{readRows:this.readRows,remainingReadRows:Math.max(0,this.limits.maxReadRows-this.readRows),remainingWrittenBytes:Math.max(0,this.limits.maxWrittenBytes-this.writtenBytes),remainingWrittenRows:Math.max(0,this.limits.maxWrittenRows-this.writtenRows),writtenBytes:this.writtenBytes,writtenRows:this.writtenRows}}}export{e as DEFAULT_TRANSACTION_LIMITS,a as TransactionHeadroomTracker};
@@ -1 +0,0 @@
1
- import{LunoraError as y}from"@lunora/errors";import{n as gt,A as Be,T as Ee,y as bt,c as yt}from"./FTS_COUNT_COLUMN-D1gY3wwZ-CZHdaRrd.mjs";import{sql as t}from"drizzle-orm";import{aggregateSqlFunction as Ne,normalizeCountArgument as Et,throwingScheduler as Nt}from"./AGGREGATE_SQL_FUNCTION-QYaiuty4.mjs";import{encodeAggregateKey as Ie,readAggregateValue as xe,aggregateTableName as Ce}from"./aggregateTableName-G-eXyjcz.mjs";import{mergeWhere as G,CountRlsUnsupportedError as ke,selectIndexForGroupBy as Tt,selectIndexForCount as At,selectIndexForAggregate as St}from"./CountRlsUnsupportedError-B2WKJD9v.mjs";import{backfillSearchIndexesForTable as _t}from"./backfillAggregateIndexes-BHiewuB-.mjs";import{backfillAggregateIndexes as dr,backfillRankIndexes as cr,backfillSearchIndexes as ur}from"./backfillAggregateIndexes-BHiewuB-.mjs";import{appendCdcChange as Rt}from"./CDC_LOG_TABLE-BnqlH2eZ.mjs";import{CDC_LOG_TABLE as hr,applyCdcChanges as pr,bumpCdcEpoch as mr,minCdcSeq as $r,readCdcChanges as wr,readCdcCursor as gr,readCdcEpoch as br,trimCdcChanges as yr}from"./CDC_LOG_TABLE-BnqlH2eZ.mjs";import{createCompanionSync as vt}from"./createCompanionSync-DWK0Vlg1.mjs";import{computeRankPage as Ve}from"./computeRankPage-IUSS-zIB.mjs";import{SCAN_DEP as B}from"./SCAN_DEP-D_yR9EeV.mjs";import{runDrizzle as q}from"./runDrizzle-GKR3y97k.mjs";import{DOC_COLUMN as U,quoteIdentifier as It,AGG_VALUE as Te,AGG_COUNT as Me,AGG_KEY as Ae,jsonPathSql as K,rowToDocument as se,tableColumns as ut,isFtsAvailable as xt,tryRowToDocument as ft,geoTableName as Ct,qualifiedJsonPathSql as Ye}from"./AGG_COUNT-BWXe3gtQ.mjs";import{coveringGeohashes as kt,boundingBoxGeohashes as Mt,pointInBoundingBox as Lt,haversineMeters as Dt}from"./GEO_DEFAULT_PRECISION-okRCkZ6r.mjs";import{NotFoundError as Ot}from"./NotFoundError-BhF7FeFr.mjs";import{normalizeOrderKeys as Wt,buildSeekWhere as ht,decodeCursor as Oe,applySelect as Xe,encodeCursor as We,softDeleteScope as ae,buildSeekBeforeWhere as Ft}from"./applySelect-B0CF8T7y.mjs";import{sortColumnName as Ze,resolveRankPartition as Bt,encodePartitionKey as qt,RANK_TIEBREAK as Ut,rankTableName as et}from"./RANK_TIEBREAK-9NU5s_mi.mjs";import{indexKeysForRow as Ht,buildIndexRange as Pt}from"./buildIndexRange-DIjFVgeO.mjs";import{assertFlatPredicate as Le,resolveRelationPredicates as tt}from"./DEFAULT_MAX_RELATION_KEYS-bq00btqV.mjs";import{runRowValidators as De,resolveWith as nt,applyOnDelete as jt,fanOutScalarCounts as Gt}from"./applyOnDelete-uFRC5p1d.mjs";import{guardWriter as Kt}from"./RLS_UNWRAP_SYMBOL-C6_WX3dG.mjs";import{createSystemReader as Jt}from"./createSystemReader-DcDcrtM3.mjs";import{ConflictError as pe}from"./ConflictError-C8GtJmjS.mjs";import{runTriggers as Qt}from"./hasTrigger-CbkOHExZ.mjs";import{compileWhereSql as ee}from"./compileWhereSql-BLcfs4QW.mjs";import{CLIENT_WATERMARK_TABLE as Nr,advanceClientWatermark as Tr,migrateClientWatermark as Ar,readClientWatermark as Sr}from"./CLIENT_WATERMARK_TABLE-CXsSLU8D.mjs";import{GLOBAL_SHAPE_SNAPSHOT_TABLE as Rr,deleteGlobalShapeSnapshot as vr,deleteGlobalShapeSnapshotsForConnection as Ir,migrateGlobalShapeSnapshot as xr,readGlobalShapeSnapshot as Cr,writeGlobalShapeSnapshot as kr}from"./GLOBAL_SHAPE_SNAPSHOT_TABLE-DX-6-gBP.mjs";import{IDEMPOTENCY_TABLE as Lr,readIdempotent as Dr,trimIdempotent as Or,writeIdempotent as Wr}from"./IDEMPOTENCY_TABLE-DjkEMp6w.mjs";import{runShardMigrations as Br}from"./runShardMigrations-CPxqCh3O.mjs";import{SEARCH_STATE_TABLE as Ur}from"./SEARCH_STATE_TABLE-eLN8U5tz.mjs";import{selectShapeMemberIds as Pr,selectShapeRows as jr}from"./selectShapeMemberIds-DvE7K6zG.mjs";import{serializeSqlValue as te}from"./serializeSqlValue-DnpyaLcw.mjs";const zt=o=>{const a=new TextEncoder().encode(o);let n="";for(const d of a)n+=String.fromCodePoint(d);return btoa(n)},Vt=o=>{const a=atob(o),n=Uint8Array.from(a,d=>d.codePointAt(0)??0);return new TextDecoder().decode(n)},Yt=()=>new y("BAD_REQUEST","invalid cursor"),rt=16,ot=8,Y=1024,qe=(o,a)=>a.query(o),Xt=(o,a,n)=>{const d=gt(o,n);if(d.length===0)return 0;let h=0;for(const[$,N]of a.entries()){const R=$===a.length-1;let p=0;for(const w of d)(R?w.startsWith(N):w===N)&&(p+=1);if(p===0)return 0;h+=p}return h},Zt=(o,a)=>{if(!a)return{exact:!0,lower:o,upper:o};const n=o.codePointAt(o.length-1)??0,d=o.slice(0,Math.max(0,o.length-String.fromCodePoint(n).length));return{exact:!1,lower:o,upper:d+String.fromCodePoint(n+1)}},en=(o,a,n)=>{const d={eq:(h,$)=>{if(!o.definition.filterFields?.includes(h))throw new y("INTERNAL",`field "${h}" is not a filter field of search index "${o.indexName}" on table "${a}"`);if(o.filters.length>=ot)throw new y("BAD_REQUEST",`search index "${o.indexName}" on table "${a}": at most ${String(ot)} .eq() filters are supported per search query`);return o.filters.push({field:h,value:$}),d},search:(h,$)=>{const N=o;if(h!==N.definition.field)throw new y("INTERNAL",`search index "${N.indexName}" on table "${a}" indexes "${N.definition.field}", not "${h}"`);const R=qe($,n).length;if(R>rt)throw new y("BAD_REQUEST",`search index "${N.indexName}" on table "${a}": at most ${String(rt)} search terms are supported (got ${String(R)})`);return N.field=h,N.query=$,N.hasQuery=!0,d}};return d},tn=o=>{if(o.length>Y)throw new y("BAD_REQUEST",`more than ${String(Y)} documents match this search — narrow it with filters or read it a page at a time with .paginate()`)},nn=o=>Math.min(o.offset+o.numItems+1,Y),rn=o=>zt(`search:${String(o)}`),on=o=>{let a;try{a=Vt(o)}catch{return}if(!a.startsWith("search:"))return;const n=Number(a.slice(7));return Number.isInteger(n)&&n>=0?n:void 0},an=o=>{if(typeof o.endCursor=="string")throw new y("BAD_REQUEST","bounded (endCursor) pagination is not supported on search queries — relevance order has no stable range boundary");const a=Math.max(0,Math.floor(o.numItems)),n=o.cursor?on(o.cursor):0;if(n===void 0)throw Yt();if(n+a>Y)throw new y("BAD_REQUEST",`search pagination reaches past the ${String(Y)}-document limit (offset ${String(n)} + ${String(a)} requested) — narrow the query or the filters instead`);return{numItems:a,offset:n}},sn=(o,a)=>{const n=a.offset+a.numItems,d=a.numItems>0&&o.length>n;return{continueCursor:d?rn(n):null,isDone:!d,page:o.slice(a.offset,n)}},ln=o=>{if(o===void 0)return Y+1;if(!Number.isFinite(o))return Y;const a=Math.max(0,Math.floor(o));if(a>Y)throw new y("BAD_REQUEST",`search returns at most ${String(Y)} documents (asked for ${String(a)}) — narrow the query or paginate instead`);return a},dn=/^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/iu,cn=o=>{if(!dn.test(o))throw new y("INTERNAL",`invalid clientId ${JSON.stringify(o)}: a client-supplied row id must be a UUID`)},it=50,pt=500,un=128,ie=(o,a,n)=>{const d=a??pt;if(o>d)throw new y("BATCH_LIMIT_EXCEEDED",`${n}: batch of ${String(o)} exceeds the limit of ${String(d)} (raise options.limit or chunk the call)`,{status:400})},fn=o=>{const a={eq:(n,d)=>(o.sqlConditions.push({comparator:"=",field:n,value:d}),a),gt:(n,d)=>(o.sqlConditions.push({comparator:">",field:n,value:d}),a),gte:(n,d)=>(o.sqlConditions.push({comparator:">=",field:n,value:d}),a),lt:(n,d)=>(o.sqlConditions.push({comparator:"<",field:n,value:d}),a),lte:(n,d)=>(o.sqlConditions.push({comparator:"<=",field:n,value:d}),a)};return a},hn=o=>Math.max(o,Y),pn=(o,a,n,d,h)=>{const $=qe(n.query,Be(n.definition.language));if($.length===0)return[];const N=yt(a,n.indexName),R=`${N}__vocab`,p=$.length-1,w=$.map((I,S)=>{const b=Zt(I,S===p),x=b.exact?t`${t.identifier("term")} = ${b.lower}`:t`${t.identifier("term")} >= ${b.lower} AND ${t.identifier("term")} < ${b.upper}`;return t`SELECT ${t.identifier("doc")}, ${t.raw(String(S))} AS ${t.identifier("__term__")}, COUNT(*) AS ${t.identifier("__n__")} FROM ${t.identifier(R)} WHERE ${x} GROUP BY ${t.identifier("doc")}`}),D=$.map((I,S)=>t`SUM(CASE WHEN u.${t.identifier("__term__")} = ${t.raw(String(S))} THEN u.${t.identifier("__n__")} ELSE 0 END)`),T=t`SELECT f.${t.identifier(Ee)} AS ${t.identifier(Ee)}, ${t.join(D,t` + `)} AS ${t.identifier("__score__")} FROM (${t.join(w,t` UNION ALL `)}) u JOIN ${t.identifier(N)} f ON f.rowid = u.${t.identifier("doc")} GROUP BY f.${t.identifier(Ee)} HAVING ${t.join(D.map(I=>t`${I} > 0`),t` AND `)}`,A=[];for(const I of n.filters)A.push(t`${K(I.field)} = ${te(I.value)}`);h&&A.push(h);let k=t`SELECT m.id, m._creationTime, m.${t.identifier(U)} FROM (${T}) s JOIN ${t.identifier(a)} m ON m.id = s.${t.identifier(Ee)}`;A.length>0&&(k=t`${k} WHERE ${t.join(A,t` AND `)}`),k=t`${k} ORDER BY s.${t.identifier("__score__")} DESC, m._creationTime DESC, m.id ASC LIMIT ${t.raw(String(d))}`;const C=[];for(const I of q(o,k)){const S=ft(I);S&&C.push(S)}return C},mn=(o,a,n,d,h)=>{const $=Be(n.definition.language),N=qe(n.query,$);if(N.length===0)return[];const R=[];for(const T of n.filters)R.push(t`${K(T.field)} = ${te(T.value)}`);h&&R.push(h);let p=t`SELECT id, _creationTime, ${t.identifier(U)} FROM ${t.identifier(a)}`;R.length>0&&(p=t`${p} WHERE ${t.join(R,t` AND `)}`),p=t`${p} ORDER BY _creationTime DESC, id ASC LIMIT ${t.raw(String(hn(d)))}`;const w=q(o,p).toArray(),D=[];for(const T of w){const A=ft(T);if(!A)continue;const k=Xt(bt(A,n.definition),N,$);k>0&&D.push({creationTime:typeof A._creationTime=="number"?A._creationTime:0,doc:A,id:typeof A._id=="string"?A._id:"",score:k})}return D.sort((T,A)=>A.score-T.score||A.creationTime-T.creationTime||T.id.localeCompare(A.id)),D.slice(0,d).map(T=>T.doc)},$n=(o,a)=>{const n=o,d={near:(h,$)=>{if(n.within)throw new y("INTERNAL",`geo index "${n.indexName}" on table "${a}": call .near() or .within(), not both`);return n.near={point:{lat:h.lat,lng:h.lng},radiusMeters:$},d},within:h=>{if(n.near)throw new y("INTERNAL",`geo index "${n.indexName}" on table "${a}": call .near() or .within(), not both`);return n.within={ne:{lat:h.ne.lat,lng:h.ne.lng},sw:{lat:h.sw.lat,lng:h.sw.lng}},d}};return d},wn=(o,a)=>{const n=o[a];if(n===null||typeof n!="object")return;const{lat:d,lng:h}=n;return typeof d=="number"&&typeof h=="number"?{lat:d,lng:h}:void 0},gn=(o,a)=>{const n=wn(o,a.definition.field);if(!n)return;const d=typeof o._creationTime=="number"?o._creationTime:0;if(a.near){const h=Dt(a.near.point,n);return h<=a.near.radiusMeters?{creationTime:d,distance:h}:void 0}return Lt(n,a.within)?{creationTime:d,distance:0}:void 0},bn=(o,a,n,d,h,$=()=>{})=>{if(!n.near&&!n.within)throw new y("INTERNAL",`geo index "${n.indexName}" on table "${a}": call .near(point, radius) or .within(box)`);const N=n.near?kt(n.near.point,n.near.radiusMeters):Mt(n.within),R=Ct(a,n.indexName),p=N.map(C=>t`(g.${t.identifier("__geohash__")} >= ${C} AND g.${t.identifier("__geohash__")} < ${`${C}{`})`),w=[t`(${t.join(p,t` OR `)})`];h&&w.push(h);const D=t`SELECT m.id, m._creationTime, m.${t.identifier(U)} FROM ${t.identifier(R)} g JOIN ${t.identifier(a)} m ON m.id = g.${t.identifier("__id__")} WHERE ${t.join(w,t` AND `)}`,T=q(o,D).toArray(),A=[];for(const C of T){const I=se(C),S=I?gn(I,n):void 0;I&&S&&A.push({creationTime:S.creationTime,distance:S.distance,doc:I})}A.sort((C,I)=>C.distance-I.distance||I.creationTime-C.creationTime);const k=A.map(C=>C.doc);return $(k.length),typeof d=="number"?k.slice(0,Math.max(0,Math.floor(d))):k},yn=(o,a,n,d,h,$=()=>{})=>{const{geo:N}=n;if(!N)throw new y("INTERNAL","runGeoTerminal called without a staged geo query");const R=n.inMemoryFilters.length>0,p=bn(o,a,N,R?void 0:h,d,$);if(!R)return p;const w=[];for(const D of p)if(n.inMemoryFilters.every(T=>T(D))&&(w.push(D),typeof h=="number"&&w.length>=h))break;return w},En=(o,a,n,d,h,$,N=()=>{})=>{const R=[];for(const T of n.sqlConditions)R.push(t`${K(T.field)} ${t.raw(T.comparator)} ${te(T.value)}`);d&&R.push(d);let p=t`SELECT id, _creationTime, ${t.identifier(U)} FROM ${t.identifier(a)}`;R.length>0&&(p=t`${p} WHERE ${t.join(R,t` AND `)}`),p=t`${p} ORDER BY ${h}`,typeof $=="number"&&n.inMemoryFilters.length===0&&(p=t`${p} LIMIT ${t.raw(String(Math.max(0,Math.floor($))))}`);const w=q(o,p).toArray();N(w.length);const D=[];for(const T of w){const A=se(T);if(A&&n.inMemoryFilters.every(k=>k(A))&&(D.push(A),typeof $=="number"&&D.length>=$))break}return D},re={fieldRef:K,serialize:te},Nn=o=>{let a=0;const n=[],d={fieldRef:K,relationExists:h=>{const{childWhere:$,negated:N,parentTable:R,relation:p}=h,w=`__rel_${String(a)}`,D=n.at(-1)??R;a+=1,o(p.table,B);const T=p.kind==="one"?p.field:p.references,A=p.kind==="one"?p.references:p.field,k=t`${Ye(w,A)} = ${Ye(D,T)}`;n.push(w);const C=ee($,d);n.pop();const I=C?t`${k} AND ${C}`:k,S=t`EXISTS (SELECT 1 FROM ${t.identifier(p.table)} AS ${t.identifier(w)} WHERE ${I})`;return N?t`NOT ${S}`:S},serialize:te};return d},mt=o=>{const a=o.map(n=>t`${K(n.field)} ${t.raw(n.direction==="desc"?"DESC":"ASC")}`);return o.some(n=>n.field==="_id"||n.field==="id")||a.push(t`${K("id")} ASC`),t.join(a,t`, `)},Tn={"<":"lt","<=":"lte","=":"eq",">":"gt",">=":"gte"},An=o=>{const a=o.order;return o.indexFields.length>0?o.indexFields.map(n=>({direction:a,field:n})):[{direction:a,field:"_creationTime"}]},Sn=(o,a,n,d)=>{const h=o.sqlConditions.map($=>({[$.field]:{[Tn[$.comparator]??"eq"]:$.value}}));if(n&&h.push(ht(a,Oe(n))),d&&h.push(Ft(a,Oe(d))),h.length!==0)return h.length===1?h[0]:{AND:h}},_n=(o,a,n)=>{const d=[];for(const h of o){const $=se(h);if($&&a.every(N=>N($))&&(d.push($),n!==void 0&&d.length>n))break}return d},Rn=(o,a,n,d,h,$=()=>{})=>{const N=Math.max(0,Math.floor(d.numItems)),R=An(n),p=typeof d.endCursor=="string",w=ee(Sn(n,R,d.cursor,d.endCursor),re),D=h&&w?t`${w} AND ${h}`:h??w;let T=t`SELECT id, _creationTime, ${t.identifier(U)} FROM ${t.identifier(a)}`;D&&(T=t`${T} WHERE ${D}`),T=t`${T} ORDER BY ${mt(R)}`;const A=n.inMemoryFilters.length>0;!A&&!p&&(T=t`${T} LIMIT ${t.raw(String(N+1))}`);const k=q(o,T).toArray();$(k.length);const C=_n(k,n.inMemoryFilters,A||p?void 0:N);if(p){const x=C.length>=2?C[Math.floor(C.length/2)-1]:void 0;return{continueCursor:d.endCursor??null,isDone:!0,page:C,splitCursor:x?We(x,R):null}}const I=C.length>N,S=I?C.slice(0,N):C,b=S.at(-1);return{continueCursor:I&&b?We(b,R):null,isDone:!I,page:S}};class vn extends y{constructor(a="unique() found more than one matching document"){super("NOT_UNIQUE",a,{name:"NotUniqueError"})}}const In=/\s/u,xn=String.fromCodePoint(0),at=(o,a,n)=>{if(!o.tables[a])throw new y("INTERNAL",`unknown table: ${a}`);return typeof n!="string"||n.length===0||In.test(n)||n.includes(xn)?null:n},Cn=(o,a,n,d=()=>{},h=()=>{},$=()=>{})=>{const N=a.tables[n];if(!N)throw new y("INTERNAL",`unknown table: ${n}`);const R=ae(N.softDeleteMode,void 0),p=R?ee(R,re):void 0,w={indexFields:[],indexName:void 0,inMemoryFilters:[],order:"asc",sqlConditions:[]};let D=0;const T=b=>{const{search:x}=w;if(!x)throw new y("INTERNAL","runSearchFetch called without a staged search");_t(o,n,N);const M=w.inMemoryFilters.length>0,L=ln(M?void 0:b),H=xt(o)?pn(o,n,x,L,p):mn(o,n,x,L,p);if(!M)return b===void 0&&tn(H),H;const V=[];D=H.length;for(const le of H)if(w.inMemoryFilters.every(de=>de(le))&&(V.push(le),typeof b=="number"&&V.length>=b))break;return V},A=b=>{const x=an(b);return sn(T(nn(x)),x)},k=()=>{const b=w.indexFields.length>0?w.indexFields:["_creationTime"],x=w.order==="desc"?"DESC":"ASC";return t.join(b.map(M=>t`${K(M)} ${t.raw(x)}`),t`, `)},C=()=>{if(w.search||w.geo||w.indexName===void 0){h(void 0);return}h(Pt(n,w.indexName,w.indexFields,w.sqlConditions,te))},I=b=>{C();let x=0;const M=(()=>{if(w.search){const L=T(b);return x=D,L}return w.geo?yn(o,n,w,p,b,L=>{x=L}):En(o,n,w,p,k(),b,L=>{x=L})})();return $(Math.max(x,M.length)),M},S={async*[Symbol.asyncIterator](){const b=[...w.inMemoryFilters];let x;w.inMemoryFilters=[];try{for(;;){const M=await S.paginate({cursor:x??null,numItems:un});for(const L of M.page)b.every(H=>H(L))&&(yield L);if(M.isDone||M.continueCursor===null)return;x=M.continueCursor}}finally{w.inMemoryFilters=b}},async collect(){return I(void 0)},filter(b){return w.inMemoryFilters.push(b),S},async first(){return I(w.inMemoryFilters.length>0?void 0:1)[0]??null},order(b){return w.order=b==="desc"?"desc":"asc",S},async paginate(b){let x=0;if(C(),w.search){const L=A(b);return $(L.page.length),L}if(w.geo)throw new y("INTERNAL","pagination is not supported on geo queries; use .take(n) or .collect()");const M=Rn(o,n,w,b,p,L=>{x=L});return $(Math.max(x,M.page.length)),M},async take(b){return I(b)},async unique(){const b=I(w.inMemoryFilters.length>0?void 0:2);if(b.length>1)throw new vn(`unique() on table "${n}" matched ${String(b.length)} documents; expected at most one`);return b[0]??null},withGeoIndex(b,x){const M=(N.geoIndexes??[]).find(H=>H.name===b);if(!M)throw new y("INTERNAL",`unknown geo index "${b}" on table "${n}"`);d(n,b,"geo");const L={definition:M,indexName:b};if(w.geo=L,x($n(L,n)),!L.near&&!L.within)throw new y("INTERNAL",`geo index "${b}" on table "${n}" requires a .near(point, radius) or .within(box) call`);return S},withIndex(b,x){const M=N.indexes.find(L=>L.name===b);if(!M)throw new y("INTERNAL",`unknown index "${b}" on table "${n}"`);return d(n,b,"index"),w.indexName=b,w.indexFields=M.fields,x&&x(fn(w)),S},withSearchIndex(b,x){const M=(N.searchIndexes??[]).find(H=>H.name===b);if(!M)throw new y("INTERNAL",`unknown search index "${b}" on table "${n}"`);d(n,b,"search");const L={definition:M,field:M.field,filters:[],hasQuery:!1,indexName:b,query:""};if(w.search=L,x(en(L,n,Be(M.language))),!L.hasQuery)throw new y("INTERNAL",`search index "${b}" on table "${n}" requires a .search(field, query) call`);return S}};return S},st=(o,a,n)=>{const d={...a};for(const[h,$]of ut(o)){if($.serverDefault){d[h]=$.serverDefault({auth:n});continue}d[h]===void 0&&($.defaultFn?d[h]=$.defaultFn():"defaultValue"in $&&(d[h]=$.defaultValue))}return d},lt=(o,a,n,d)=>{const h=n;for(const[$,N]of ut(o)){if(N.serverDefault){$ in a&&(h[$]=N.serverDefault({auth:d}));continue}N.onUpdateFn&&!($ in a)&&(h[$]=N.onUpdateFn())}},dt=(o,a)=>{for(const n of Object.keys(a))if(a[n]===void 0)throw new y("INTERNAL",`Cannot ${o} field '${n}' to undefined — use null to clear a nullable field, or omit the key to leave it unchanged.`)},kn=/unique constraint failed/i,Mn=o=>o instanceof Error&&kn.test(o.message),Fe=(o,a,n)=>{try{q(o,n)}catch(d){throw Mn(d)?new pe(`unique constraint violation on "${a}"`,"unique"):d}},Se=(o,a,n)=>{if(Fe(o,a,n),q(o,t`SELECT changes() AS changed`).one().changed===0)throw new pe(`optimistic concurrency conflict on "${a}" — the row changed during this mutation; refetch and retry`,"occ")},ct=(o,a,n,d,h,$,N)=>{const R=[];for(let T=0;T<n.length+1;T+=1){const A=[];for(let S=0;S<T;S+=1)A.push(t`${t.identifier(n[S])} IS ${$[S]}`);const k=n[T],C=d[T];if(k!==void 0&&C!==void 0){const S=C.direction==="desc"?">":"<";A.push(t`${t.identifier(k)} ${t.raw(S)} ${$[T]}`)}else A.push(t`${t.identifier(Ut)} < ${N}`);const[I]=A;R.push(A.length===1&&I!==void 0?I:t`(${t.join(A,t` AND `)})`)}const p=t.join(R,t` OR `),w=q(o,t`SELECT COUNT(*) AS c FROM ${t.identifier(a)} WHERE ${t.identifier("__partition__")} = ${h} AND (${p})`).one(),D=q(o,t`SELECT COUNT(*) AS c FROM ${t.identifier(a)} WHERE ${t.identifier("__partition__")} = ${h}`).one();return{before:w.c,total:D.c}},ar=o=>{const{sql:a}=o,{schema:n}=o,d=o.broadcast??(()=>{}),h=(e,...r)=>{const i=n.tables[e]?.indexes;if(!i||i.length===0)return;const f=[];for(const u of r)u&&f.push(...Ht(i,u,te));return f.length>0?f:void 0},{headroom:$}=o,N=o.onRead??(()=>{}),R=o.onReadRange??(e=>{N(e.table,B)}),p=(e,r)=>{r!==void 0&&r!==B&&$?.recordRead(1),N(e,r)},w=o.onIndexUse??(()=>{}),D=o.onWrite??(()=>{}),T=async e=>{$?.recordWrite(e.doc),await D(e)},{cache:A}=o,k=o.clock??(()=>Date.now()),C=o.idGenerator??(()=>crypto.randomUUID()),I=o.scheduler??Nt,{globalDb:S}=o,b=o.auth??{identity:null,userId:null},x=o.cdc??!1,M=I,L=Jt({scheduler:typeof M.list=="function"&&typeof M.get=="function"?M:void 0,storage:o.storage}),H=(e,r,i,f)=>{x&&Rt(a,k(),e,r,i,f)},V=e=>n.tables[e]?.shardMode?.kind==="global",le=(e,r)=>{if(V(e)){if(!S)throw new y("INTERNAL",`cross-backend ${r} for global table '${e}' requires a globalDb writer — pass one to createShardCtxDb({ globalDb })`);return S}return F},de=e=>le(e,"cascade"),J=(e,r)=>{if(V(e)){if(!S)throw new y("INTERNAL",`${r} on global table '${e}' requires a globalDb writer — pass one to createShardCtxDb({ globalDb })`);return S}},ce=()=>S,_e=(e,r)=>le(e,"relation load").findMany(e,r),Ue=(e,r)=>(V(e)&&p(e,B),_e(e,r)),$t=e=>!V(e.table),He=o.relationExistsPushDown??"auto",Pe=He!=="never",{maxRelationKeys:je}=o,me=(e,r,i)=>tt(e,{fetcher:Ue,maxRelationKeys:je,relationBaseWhere:i,schema:n,tableName:r}),Ge=async(e,r,i,f)=>{const u=J(e,"relation grouped count");if(u)return p(e,B),Gt((v,j)=>u.count(v,j),e,r,i,f);const l=n.tables[e];if(!l)throw new y("INTERNAL",`unknown table: ${e}`);p(e,B);const s=ae(l.softDeleteMode,void 0),c={[r]:{in:i}},m=G(G(c,f),s),E=await me(m,e,void 0),g=ee(E,re),_=K(r);let W=t`SELECT ${_} AS __fk__, COUNT(*) AS count FROM ${t.identifier(e)}`;g&&(W=t`${W} WHERE ${g}`),W=t`${W} GROUP BY ${_}`;const O=q(a,W).toArray();return new Map(O.map(v=>[v.__fk__,v.count]))};let $e=0;const Ke=new Set;for(const[e,r]of Object.entries(n.tables))for(const i of Object.values(r.triggerMap??{}))Ke.add(`${e} ${i.timing} ${i.op}`);const X=(e,r,i)=>Ke.has(`${e} ${r} ${i}`),Z=async(e,r,i)=>{if($e+=1,$e>it)throw $e-=1,new pe(`trigger recursion exceeded ${String(it)} levels on "${i.table}" — check for a self-triggering write`,"trigger");try{await Qt({ctx:wt,event:i,op:r,schema:n,tableName:i.table,timing:e})}finally{$e-=1}},{ensureBackfilledForTable:ue,ensureBackfilledIndex:Re,ensureRankBackfilled:ve,ensureRankBackfilledForTable:fe,syncAggregates:we,syncCompanionsForInsert:Je,syncGeo:ge,syncRanks:he,syncSearch:be}=vt({broadcast:d,indexKeysFor:(e,r)=>h(e,r),invalidateCache:(e,r,i)=>A?.invalidate(e,r,h(e,i)),recordCdc:H,schema:n,sql:a}),Qe=(e,r,i)=>{const{shardMode:f}=r;if(f?.kind==="shardBy"&&!(f.field!==void 0&&(i.partitionBy??[]).includes(f.field)))throw Object.assign(new Error(`rank index "${i.name}" on "${e}" partitions across shards (shard key "${f.field??"?"}" is not in partitionBy) — a shard-local rank()/rankPage() would be wrong; roll it up through the Query Coordinator instead`),{code:"CROSS_SHARD_RANK_UNSUPPORTED",name:"LunoraError",status:400})},ne=(e,r)=>{const i=Object.entries(n.tables).filter(([,E])=>E.shardMode?.kind!=="global").map(([E])=>E).filter(E=>r===void 0||E===r);if(i.length===0)return;const f=i.map(E=>t`SELECT ${t.raw(`'${E.replaceAll("'","''")}'`)} AS __t__, id, _creationTime, ${t.identifier(U)} FROM ${t.identifier(E)} WHERE id = ${e}`),u=t`${t.join(f,t` UNION ALL `)} LIMIT 1`,[l]=q(a,u).toArray();if(!l)return;const s=l.__t__,c=se(l);if(typeof s!="string"||!c)return;const m=l[U];return{docJson:typeof m=="string"?m:JSON.stringify(m??{}),row:c,tableName:s}},ze={assertRankPartitionLocal:Qe,ensureRankBackfilled:ve,onRead:p,rowToDocument:se,schema:n,sql:a},F={system:L,async aggregate(e,r){const i=J(e,"aggregate");if(i)return p(e,B),i.aggregate(e,r);const f=n.tables[e];if(!f)throw new y("INTERNAL",`unknown table: ${e}`);if(Ne(r.op),r.op==="count")return F.count(e,{baseWhere:r.baseWhere,relationBaseWhere:r.relationBaseWhere,restrictsCounts:r.restrictsCounts,where:r.where});if(!r.field)throw new y("INTERNAL",`aggregate(${e}, { op: "${r.op}" }): "field" is required for non-count reducers`);p(e,B);const u=ae(f.softDeleteMode,void 0),l=G(G(r.baseWhere,r.where),u),s=await me(l,e,r.relationBaseWhere),c=s!==l;if(f.aggregateIndexes&&!r.baseWhere&&!c&&!u){const O=St(f.aggregateIndexes,r.op,r.field,r.where);if(O){Re(e,O.index);const v=Ie(O.index.by??[],O.key),j=Ce(e,O.index.name),Q=q(a,t`SELECT ${Te} AS value, ${Me} AS count FROM ${t.identifier(j)} WHERE ${Ae} = ${v}`).toArray()[0];return xe(r.op,Q)}}const m=ee(s,re),E=Ne(r.op),g=K(r.field);let _=t`SELECT ${t.raw(E)}(${g}) AS value FROM ${t.identifier(e)}`;return m&&(_=t`${_} WHERE ${m}`),q(a,_).toArray()[0]?.value??null},asId(e,r){const i=at(n,e,r);if(i===null)throw new y("BAD_REQUEST",`asId("${e}", …): "${r}" is not a valid id for table "${e}"`,{status:400});return i},async count(e,r){const i=J(e,"count");if(i)return p(e,B),i.count(e,r);const f=n.tables[e];if(!f)throw new y("INTERNAL",`unknown table: ${e}`);const u=Et(r);if(u.restrictsCounts)throw new ke(e);p(e,B);const l=ae(f.softDeleteMode,void 0),s=G(G(u.baseWhere,u.where),l),c=await me(s,e,u.relationBaseWhere),m=c!==s;if(f.aggregateIndexes&&!u.baseWhere&&!m&&!l){const _=At(f.aggregateIndexes,u.where);if(_){Re(e,_.index);const W=Ie(_.index.by??[],_.key),O=Ce(e,_.index.name),v=q(a,t`SELECT ${Te} AS value FROM ${t.identifier(O)} WHERE ${Ae} = ${W}`).toArray();return v[0]===void 0?0:v[0].value??0}}const E=ee(c,re);let g=t`SELECT COUNT(*) AS count FROM ${t.identifier(e)}`;return E&&(g=t`${g} WHERE ${E}`),q(a,g).one().count},async delete(e,r,i){const f=ne(e,r);if(!f){const g=r===void 0?ce():void 0;g&&await g.delete(e,void 0,i);return}const{docJson:u,row:l,tableName:s}=f,c=n.tables[s],m=i?.hard===!0,E=!m&&c?.softDeleteMode?c.softDeleteMode.field:void 0;if(!(E&&l[E]!==null&&l[E]!==void 0)){if(X(s,"before","delete")&&await Z("before","delete",{id:e,op:"delete",previous:l,table:s}),await jt({deletedId:e,deletedReference:g=>l[g],findHolders:async(g,_,W)=>(await de(g).findMany(g,{includeDeleted:m,where:{[_]:W}})).page,onCascade:(g,_)=>de(g).delete(_,void 0,i),onRestrict:g=>{throw new pe(g,"restrict")},onSetNull:(g,_,W)=>de(g).patch(_,{[W]:null}),schema:n,tableName:s}),ue(s),fe(s),E){const g={...l,[E]:k(),_id:e};Se(a,s,t`UPDATE ${t.identifier(s)} SET ${t.identifier(U)} = ${JSON.stringify(g)} WHERE id = ${e} AND ${t.identifier(U)} = ${u}`),be(s,e,g,l),ge(s,e,void 0),we(s,l,g),he(s,e,l,void 0),A?.invalidate(s,e,h(s,l,g)),H(s,e,"update",g),d({indexKeys:h(s,l,g),key:e,op:"update",row:g,table:s}),X(s,"after","delete")&&await Z("after","delete",{id:e,op:"delete",previous:l,table:s}),await T({id:e,op:"delete",table:s});return}Se(a,s,t`DELETE FROM ${t.identifier(s)} WHERE id = ${e} AND ${t.identifier(U)} = ${u}`),be(s,e,void 0),ge(s,e,void 0),we(s,l,void 0),he(s,e,l,void 0),A?.invalidate(s,e,h(s,l)),H(s,e,"delete"),d({indexKeys:h(s,l),key:e,op:"delete",table:s}),X(s,"after","delete")&&await Z("after","delete",{id:e,op:"delete",previous:l,table:s}),await T({id:e,op:"delete",table:s})}},async deleteAll(e,r){if(!n.tables[e])throw new y("INTERNAL",`unknown table: ${e}`);const i=Math.max(1,r?.chunkSize??pt),f=r?.hard===void 0?void 0:{hard:r.hard},u=V(e)?void 0:e;let l=0;for(;;){const s=(await F.findMany(e,{limit:i})).page.map(c=>String(c._id));if(s.length===0)break;for(const c of s)await F.delete(c,u,f),l+=1;if(s.length<i)break}return{deleted:l}},async deleteMany(e,r,i){ie(e.length,r?.limit,"deleteMany");for(const f of e)await F.delete(f,i);return{deleted:e.length}},async deleteWhere(e,r,i){const f=J(e,"deleteWhere");let u;if(f)u=(await f.findMany(e,{where:r})).page.map(l=>String(l._id));else{if(!n.tables[e])throw new y("INTERNAL",`unknown table: ${e}`);u=(await F.findMany(e,{where:r})).page.map(l=>String(l._id))}if(ie(u.length,i?.limit,"deleteWhere"),F.deleteMany===void 0)throw new y("INTERNAL",`ctx.db.${e}.deleteMany is unavailable: this writer has no batch delete`);return F.deleteMany(u,i)},async findFirst(e,r={}){return(await F.findMany(e,{...r,limit:1})).page[0]??null},async findFirstOrThrow(e,r={}){const i=await F.findFirst(e,r);if(i===null)throw new Ot(`findFirstOrThrow: no "${e}" document matched`);return i},async findMany(e,r={}){const i=J(e,"findMany");if(i)return p(e,B),i.findMany(e,r);const f=n.tables[e];if(!f)throw new y("INTERNAL",`unknown table: ${e}`);const u=!r.where&&!r.baseWhere;u?p(e,B):p(e);const l=Wt(r.orderBy),s=r.cursor?ht(l,Oe(r.cursor)):void 0;let c=G(r.baseWhere,r.where);c=G(c,ae(f.softDeleteMode,r.includeDeleted)),c=await tt(c,{canPushExists:Pe?$t:void 0,existsPushMode:He==="always"?"always":"auto",fetcher:Ue,maxRelationKeys:je,relationBaseWhere:r.relationBaseWhere,schema:n,tableName:e}),s&&(c=c?{AND:[c,s]}:s);const m=Pe?Nn(p):re,E=ee(c,m);let g=t`SELECT id, _creationTime, ${t.identifier(U)} FROM ${t.identifier(e)}`;E&&(g=t`${g} WHERE ${E}`),g=t`${g} ORDER BY ${mt(l)}`;const _=typeof r.limit=="number"?Math.max(0,Math.floor(r.limit)):void 0;_!==void 0&&(g=t`${g} LIMIT ${t.raw(String(_+1))}`);const W=q(a,g).toArray();u&&$?.recordRead(W.length);const O=[];for(const z of W){const P=se(z);P&&(O.push(P),!u&&typeof P._id=="string"&&p(e,P._id))}if(_===void 0)return r.with&&await nt({groupedCounter:Ge,fetcher:_e,parents:O,relationBaseWhere:r.relationBaseWhere,schema:n,tableName:e,with:r.with}),{continueCursor:null,isDone:!0,page:Xe(O,r.select,r.with)};const v=O.length>_,j=v?O.slice(0,_):O,Q=j.at(-1);return r.with&&await nt({fetcher:_e,groupedCounter:Ge,parents:j,relationBaseWhere:r.relationBaseWhere,schema:n,tableName:e,with:r.with}),{continueCursor:v&&Q?We(Q,l):null,isDone:!v,page:Xe(j,r.select,r.with)}},async get(e,r){const i=ne(e,r);if(!i){const f=r===void 0?ce():void 0;return f?f.get(e):null}return p(i.tableName,e),i.row},async lookupById(e,r){const i=ne(e,r);return i?(p(i.tableName,e),{row:i.row,tableName:i.tableName}):null},async groupBy(e,r){const i=J(e,"groupBy");if(i)return p(e,B),i.groupBy(e,r);const f=n.tables[e];if(!f)throw new y("INTERNAL",`unknown table: ${e}`);p(e,B);const u=r.agg??{op:"count"};if(Ne(u.op),u.op!=="count"&&!u.field)throw new y("INTERNAL",`groupBy(${e}, { agg: { op: "${u.op}" } }): "field" is required for non-count reducers`);const l=ae(f.softDeleteMode,void 0),s=G(G(r.baseWhere,r.where),l),c=await me(s,e,r.relationBaseWhere),m=c!==s;if(f.aggregateIndexes&&!r.baseWhere&&!m&&!l){const v=Tt(f.aggregateIndexes,u.op,u.field,r.by,r.where);if(v){Re(e,v.index);const j=Ce(e,v.index.name),Q=Object.keys(v.partial),z=[];if(Q.length===(v.index.by??[]).length&&Q.length>0){const oe=Ie(v.index.by??[],v.partial),ye=q(a,t`SELECT ${Te} AS value, ${Me} AS count FROM ${t.identifier(j)} WHERE ${Ae} = ${oe}`).toArray();return ye.length>0&&z.push({key:{...v.partial},value:xe(u.op,ye[0])}),z}const P=q(a,t`SELECT ${Ae} AS key, ${Te} AS value, ${Me} AS count FROM ${t.identifier(j)}`).toArray();for(const oe of P){const ye=JSON.parse(oe.key);z.push({key:ye,value:xe(u.op,oe)})}return z}}const E=ee(c,re),g=r.by.map(v=>t`${K(v)} AS ${t.identifier(v)}`);if(u.op==="count")g.push(t`COUNT(*) AS value`);else{const{field:v}=u;if(v===void 0)throw new y("INTERNAL",`groupBy(${e}, { agg: { op: "${u.op}" } }): "field" is required for non-count reducers`);g.push(t`${t.raw(Ne(u.op))}(${K(v)}) AS value`)}let _=t`SELECT ${t.join(g,t`, `)} FROM ${t.identifier(e)}`;E&&(_=t`${_} WHERE ${E}`),_=t`${_} GROUP BY ${t.join(r.by.map(v=>K(v)),t`, `)}`;const W=q(a,_).toArray(),O=[];for(const v of W){const j={};for(const z of r.by)j[z]=v[z]??null;const{value:Q}=v;O.push({key:j,value:Q==null?null:Number(Q)})}return O},async insert(e,r,i){const f=J(e,"insert");if(f){const E=await f.insert(e,r,i);return $?.recordWrite(r),d({key:E,op:"insert",row:{...r,_id:E},table:e}),E}const u=n.tables[e];if(!u)throw new y("INTERNAL",`unknown table: ${e}`);const l=st(u,r,b);De(u,l);let s;i?.clientId!==void 0?(cn(i.clientId),s=i.clientId):i?.allowExplicitId&&typeof l._id=="string"?s=l._id:s=C();const c=i?.allowExplicitId&&typeof l._creationTime=="number"?l._creationTime:k(),m={...l,_creationTime:c,_id:s};return X(e,"before","insert")&&await Z("before","insert",{doc:{...m},id:s,op:"insert",table:e}),ue(e),fe(e),Fe(a,e,t`INSERT INTO ${t.identifier(e)} (id, _creationTime, ${t.identifier(U)}) VALUES (${s}, ${c}, ${JSON.stringify(m)})`),Je(e,s,m),X(e,"after","insert")&&await Z("after","insert",{doc:m,id:s,op:"insert",table:e}),await T({doc:m,id:s,op:"insert",table:e}),s},async insertManyUnsafe(e,r,i){if(ie(r.length,i?.limit,"insertManyUnsafe"),r.length===0)return[];const f=J(e,"insert");if(f){const c=[];for(const m of r){const E=await f.insert(e,m,{allowExplicitId:i?.allowExplicitId});$?.recordWrite(m),d({key:E,op:"insert",row:{...m,_id:E},table:e}),c.push(E)}return c}const u=n.tables[e];if(!u)throw new y("INTERNAL",`unknown table: ${e}`);ue(e),fe(e);const l=r.map(c=>{const m=st(u,c,b),E=i?.allowExplicitId===!0&&typeof m._id=="string"?m._id:C(),g=i?.allowExplicitId===!0&&typeof m._creationTime=="number"?m._creationTime:k();return{creationTime:g,document:{...m,_creationTime:g,_id:E},id:E}});for(const c of l)$?.recordWrite(c.document);const s=t.join(l.map(c=>t`(${c.id}, ${c.creationTime}, ${JSON.stringify(c.document)})`),t`, `);Fe(a,e,t`INSERT INTO ${t.identifier(e)} (id, _creationTime, ${t.identifier(U)}) VALUES ${s}`);for(const{document:c,id:m}of l)Je(e,m,c),await D({doc:c,id:m,op:"insert",table:e});return l.map(c=>c.id)},async insertMany(e,r,i){ie(r.length,i?.limit,"insertMany");const f=i?.skipDuplicates===!0,u=[];for(const l of r)try{u.push(await F.insert(e,l))}catch(s){if(f&&s instanceof pe&&s.kind==="unique")u.push(null);else throw s}return u},normalizeId(e,r){return at(n,e,r)},async patch(e,r,i){const f=ne(e,i);if(!f){const E=i===void 0?ce():void 0;if(E){await E.patch(e,r);return}throw new y("INTERNAL",`document not found: ${e}`)}const{docJson:u,row:l,tableName:s}=f,c=n.tables[s];if(!c)throw new y("INTERNAL",`unknown table: ${s}`);p(s,e),dt("patch",r);const m={...l,...r,_id:e};lt(c,r,m,b),De(c,m,!0),X(s,"before","update")&&await Z("before","update",{doc:{...m},id:e,op:"update",previous:l,table:s}),ue(s),fe(s),Se(a,s,t`UPDATE ${t.identifier(s)} SET ${t.identifier(U)} = ${JSON.stringify(m)} WHERE id = ${e} AND ${t.identifier(U)} = ${u}`),be(s,e,m,l),ge(s,e,m),we(s,l,m),he(s,e,l,m),A?.invalidate(s,e,h(s,l,m)),H(s,e,"update",m),d({indexKeys:h(s,l,m),key:e,op:"update",row:m,table:s}),X(s,"after","update")&&await Z("after","update",{doc:m,id:e,op:"update",previous:l,table:s}),await T({doc:m,id:e,op:"update",table:s})},async patchMany(e,r,i){ie(e.length,r?.limit,"patchMany");for(const f of e)await F.patch(f.id,f.patch,i);return{patched:e.length}},async patchWhere(e,r,i){const f=J(e,"patchWhere");let u;if(f)u=(await f.findMany(e,{where:r.where})).page.map(l=>({id:String(l._id),patch:r.patch}));else{if(!n.tables[e])throw new y("INTERNAL",`unknown table: ${e}`);u=(await F.findMany(e,{where:r.where})).page.map(l=>({id:String(l._id),patch:r.patch}))}if(ie(u.length,i?.limit,"patchWhere"),F.patchMany===void 0)throw new y("INTERNAL",`ctx.db.${e}.patchMany is unavailable: this writer has no batch patch`);return await F.patchMany(u,i),{patched:u.length}},query(e){const r=J(e,"query");return r?(p(e,B),r.query(e)):Cn(a,n,e,w,i=>{i?R(i):p(e,B)},i=>$?.recordRead(i))},async rank(e,r,i){const f=J(e,"rank");if(f)return p(e,B),f.rank(e,r,i);w(e,r,"rank");const u=n.tables[e];if(!u)throw new y("INTERNAL",`unknown table: ${e}`);const l=u.rankIndexes?.find(P=>P.name===r);if(!l)throw new y("INTERNAL",`unknown rankIndex "${r}" on table "${e}"`);if(Qe(e,u,l),i.restrictsCounts)throw new ke(e);p(e,B),ve(e,l);const s=typeof i.row=="string"?i.row:i.row._id;if(!s)return null;const c=et(e,l.name),m=l.sortBy.map((P,oe)=>Ze(oe)),E=m.map(P=>It(P)).join(", "),g=q(a,t`SELECT ${t.identifier("__partition__")}, ${t.raw(E)} FROM ${t.identifier(c)} WHERE ${t.identifier("__id__")} = ${s}`).toArray(),[_]=g;if(_===void 0)return null;let W=_.__partition__;const O=G(i.baseWhere,i.where);Le(O,n,e,"rank");const v=Bt(l,O);if(v){const P=qt(l.partitionBy??[],v);if(P!==W)return null;W=P}const j=m.map(P=>_[P]),{before:Q,total:z}=ct(a,c,m,l.sortBy,W,j,s);return{position:Q+1,total:z}},async rankBefore(e,r,i){if(V(e))throw new y("INTERNAL",`rankBefore is not supported on the global (.global()) table '${e}' — cross-shard rank cursors apply only to sharded tables`);const f=n.tables[e];if(!f)throw new y("INTERNAL",`unknown table: ${e}`);const u=f.rankIndexes?.find(m=>m.name===r);if(!u)throw new y("INTERNAL",`unknown rankIndex "${r}" on table "${e}"`);if(i.restrictsCounts)throw new ke(e);p(e,B),ve(e,u);const l=et(e,u.name),s=u.sortBy.map((m,E)=>Ze(E)),c=u.sortBy.map((m,E)=>te(i.sortValues[E]??null));return ct(a,l,s,u.sortBy,i.partitionKey,c,i.rowId)},async rankPage(e,r,i={}){Le(G(i.baseWhere,i.where),n,e,"rankPage");const f=J(e,"rankPage");if(f)return p(e,B),f.rankPage(e,r,i);w(e,r,"rank");const{continueCursor:u,hasMore:l,rows:s}=Ve(ze,e,r,i);return{continueCursor:u,isDone:!l,page:s.map(c=>c.doc)}},async rankPageRows(e,r,i={}){Le(G(i.baseWhere,i.where),n,e,"rankPage"),w(e,r,"rank");const{directions:f,hasMore:u,rows:l}=Ve(ze,e,r,i);return{directions:f,hasMore:u,rows:l}},async restore(e,r){const i=ne(e,r);if(!i){const l=r===void 0?ce():void 0;if(l?.restore){await l.restore(e);return}throw new y("INTERNAL",`document not found: ${e}`)}const f=n.tables[i.tableName]?.softDeleteMode?.field;if(!f)throw new y("INTERNAL",`ctx.db.restore: table "${i.tableName}" is not a .softDelete() table`);const u=i.row[f]!==null&&i.row[f]!==void 0;await F.patch(e,{[f]:null},r),u&&he(i.tableName,e,void 0,i.row)},async replace(e,r,i,f){const u=ne(e,i);if(!u){const _=i===void 0?ce():void 0;if(_){await _.replace(e,r,void 0,f);return}throw new y("INTERNAL",`document not found: ${e}`)}const{docJson:l,row:s,tableName:c}=u,m=n.tables[c];if(!m)throw new y("INTERNAL",`unknown table: ${c}`);dt("replace",r);const E=f?.allowExplicitId&&typeof r._creationTime=="number"?r._creationTime:k(),g={...r,_creationTime:E,_id:e};lt(m,r,g,b),De(m,g),X(c,"before","update")&&await Z("before","update",{doc:{...g},id:e,op:"update",previous:s,table:c}),ue(c),fe(c),Se(a,c,t`UPDATE ${t.identifier(c)} SET _creationTime = ${E}, ${t.identifier(U)} = ${JSON.stringify(g)} WHERE id = ${e} AND ${t.identifier(U)} = ${l}`),be(c,e,g,s),ge(c,e,g),we(c,s,g),he(c,e,s,g),A?.invalidate(c,e,h(c,s,g)),H(c,e,"update",g),d({indexKeys:h(c,s,g),key:e,op:"update",row:g,table:c}),X(c,"after","update")&&await Z("after","update",{doc:g,id:e,op:"update",previous:s,table:c}),await T({doc:g,id:e,op:"update",table:c})},async wipeShard(e){const r=new Set(e?.exclude),i=e?.tables,f=Object.entries(n.tables).filter(([c,m])=>r.has(c)||i!==void 0&&!i.includes(c)?!1:m.shardMode?.kind!=="global").map(([c])=>c);if(i!==void 0){for(const c of i)if(!n.tables[c])throw new y("INTERNAL",`wipeShard: unknown table: ${c}`)}const u={};let l=0;const{deleteAll:s}=F;if(s===void 0)throw new y("INTERNAL","wipeShard: this writer has no deleteAll");for(const c of f){const m=await s(c,{...e?.chunkSize===void 0?{}:{chunkSize:e.chunkSize},hard:!0});u[c]=m.deleted,l+=m.deleted}return{deleted:l,tables:u}}},wt={db:F,scheduler:I};return o.enforceRls===!0?Kt(F,n,(e,r)=>ne(e,r)?.tableName):F};export{hr as CDC_LOG_TABLE,Nr as CLIENT_WATERMARK_TABLE,Rr as GLOBAL_SHAPE_SNAPSHOT_TABLE,Lr as IDEMPOTENCY_TABLE,vn as NotUniqueError,Ur as SEARCH_STATE_TABLE,Tr as advanceClientWatermark,pr as applyCdcChanges,cn as assertValidClientId,dr as backfillAggregateIndexes,cr as backfillRankIndexes,ur as backfillSearchIndexes,mr as bumpCdcEpoch,ar as createShardCtxDb,vr as deleteGlobalShapeSnapshot,Ir as deleteGlobalShapeSnapshotsForConnection,Ar as migrateClientWatermark,xr as migrateGlobalShapeSnapshot,$r as minCdcSeq,at as normalizeIdStructurally,wr as readCdcChanges,gr as readCdcCursor,br as readCdcEpoch,Sr as readClientWatermark,Cr as readGlobalShapeSnapshot,Dr as readIdempotent,Br as runShardMigrations,Pr as selectShapeMemberIds,jr as selectShapeRows,yr as trimCdcChanges,Or as trimIdempotent,kr as writeGlobalShapeSnapshot,Wr as writeIdempotent};
@@ -1 +0,0 @@
1
- import{LunoraError as p}from"@lunora/errors";const y=Symbol.for("lunora.ctxdb.rls-unwrap");class f extends p{table;constructor(i){super("RLS_REQUIRED",`ctx.db access to "${i}" is denied: the schema is marked .rls("required"), so this table is protected. Apply RLS with .use(rls(policies)) in the procedure, or mark the table .public() to opt it out.`,{name:"RlsRequiredError"}),this.table=i}}const w=n=>Object.entries(n.tables).filter(([,i])=>i.shardMode?.kind!=="global").map(([i])=>i),g=(n,i,c)=>{const t=i?.tables,d=new Set(i?.exclude);for(const s of n)(t===void 0||t.includes(s))&&!d.has(s)&&c(s)},b=(n,i,c)=>{const t={},{deleteAll:d,wipeShard:s}=n;return d&&(t.deleteAll=(o,u)=>(c(o),d(o,u))),s&&(t.wipeShard=o=>(g(w(i),o,c),s(o))),t},k=(n,i,c)=>{if(i.rlsMode!=="required")return n;const t=n,d=e=>{const r=i.tables[e];return r!==void 0&&r.isPublic!==!0},s=e=>{if(d(e))throw new f(e)},o=async(e,r)=>{if(r!==void 0){s(r);return}const a=await c(e);a!==void 0&&s(a)},u=t.rankBefore,h={...n,...b(t,i,s),[y]:n,aggregate:(e,r)=>(s(e),t.aggregate(e,r)),count:(e,r)=>(s(e),t.count(e,r)),delete:async(e,r,a)=>(await o(e,r),t.delete(e,r,a)),deleteMany:async(e,r,a)=>{for(const l of e)await o(l,a);return t.deleteMany(e,r,a)},deleteWhere:t.deleteWhere?async(e,r,a)=>(s(e),await t.deleteWhere?.(e,r,a)):void 0,findFirst:(e,r)=>(s(e),t.findFirst(e,r)),findFirstOrThrow:(e,r)=>(s(e),t.findFirstOrThrow(e,r)),findMany:(e,r)=>(s(e),t.findMany(e,r)),get:async(e,r)=>(await o(e,r),t.get(e,r)),groupBy:(e,r)=>(s(e),t.groupBy(e,r)),insert:(e,r,a)=>(s(e),t.insert(e,r,a)),insertMany:(e,r,a)=>(s(e),t.insertMany(e,r,a)),insertManyUnsafe:(e,r,a)=>(s(e),t.insertManyUnsafe(e,r,a)),patch:async(e,r,a)=>(await o(e,a),t.patch(e,r,a)),patchMany:async(e,r,a)=>{for(const l of e)await o(l.id,a);return t.patchMany(e,r,a)},patchWhere:t.patchWhere?async(e,r,a)=>(s(e),await t.patchWhere?.(e,r,a)):void 0,query:e=>(s(e),t.query(e)),rank:(e,r,a)=>(s(e),t.rank(e,r,a)),rankPage:(e,r,a)=>(s(e),t.rankPage(e,r,a)),replace:async(e,r,a,l)=>(await o(e,a),t.replace(e,r,a,l)),restore:async(e,r)=>(await o(e,r),t.restore?.(e,r))};return u&&(h.rankBefore=(e,r,a)=>(s(e),u(e,r,a))),h};export{y as RLS_UNWRAP_SYMBOL,f as RlsRequiredError,k as guardWriter};
@@ -1 +0,0 @@
1
- import{stableWireKey as g}from"./stableWireKey-YEHLaX6X.mjs";import{depKey as b,SCAN_DEP as y}from"./SCAN_DEP-D_yR9EeV.mjs";import{r as p}from"./estimate-bytes-DzD3PdCc.mjs";import{keysTouchRanges as x}from"./buildIndexRange-DIjFVgeO.mjs";import{stableStringify as A}from"./stableStringify-BjLh4gvA.mjs";const m=1e3,u=4*1024*1024;class z{entries=new Map;tableIndex=new Map;rangeIndex=new Map;totalBytes=0;hits=0;misses=0;evictions=0;maxEntries;maxBytes;now;monotonic=0;constructor(t={}){this.maxEntries=t.maxEntries??m,this.maxBytes=t.maxBytes??u,this.now=t.now??(()=>(this.monotonic+=1,this.monotonic))}async run(t,s,i,e=()=>[]){const n=this.entries.get(t);if(n)return this.hits+=1,n.lastUsed=this.now(),this.entries.delete(t),this.entries.set(t,n),n.result;this.misses+=1;const h=await i(),a=e(),c=p(h,this.maxBytes),f={bytes:c,deps:s,ranges:a,lastUsed:this.now(),result:h,subscribers:new Set};this.entries.set(t,f),this.totalBytes+=c;for(const o of s){let r=this.tableIndex.get(o);r||(r=new Set,this.tableIndex.set(o,r)),r.add(t)}for(const o of a){let r=this.rangeIndex.get(o.table);r||(r=new Map,this.rangeIndex.set(o.table,r));let l=r.get(o);l||(l=new Set,r.set(o,l)),l.add(t)}return this.evict(),h}invalidate(t,s,i){const e=[];return this.collectAndDrop(b(t,s),e),this.collectAndDrop(b(t,y),e),this.dropRangeDeps(t,i,e),e}invalidateTable(t){const s=[],i=`${t}:`;for(const e of this.tableIndex.keys())e.startsWith(i)&&this.collectAndDrop(e,s);return this.dropRangeDeps(t,void 0,s),s}subscribe(t,s){const i=this.entries.get(t);i&&i.subscribers.add(s)}unsubscribe(t,s){const i=this.entries.get(t);i&&i.subscribers.delete(s)}size(){return{bytes:this.totalBytes,entries:this.entries.size}}clear(){this.entries.clear(),this.tableIndex.clear(),this.rangeIndex.clear(),this.totalBytes=0}subscribers(t){const s=this.entries.get(t);return s?[...s.subscribers]:[]}stats(){return{bytes:this.totalBytes,entries:this.entries.size,evictions:this.evictions,hits:this.hits,misses:this.misses}}dropRangeDeps(t,s,i){const e=this.rangeIndex.get(t);if(!(!e||e.size===0)){for(const[n,h]of e)if(x([n],s))for(const a of h){const c=this.entries.get(a);c&&(this.dropEntry(a,c),i.push(a))}}}collectAndDrop(t,s){const i=this.tableIndex.get(t);if(i)for(const e of i){const n=this.entries.get(e);n&&(this.dropEntry(e,n),s.push(e))}}dropEntry(t,s){this.entries.delete(t),this.totalBytes-=s.bytes;for(const i of s.deps){const e=this.tableIndex.get(i);e&&(e.delete(t),e.size===0&&this.tableIndex.delete(i))}for(const i of s.ranges){const e=this.rangeIndex.get(i.table),n=e?.get(i);n?.delete(t),e&&n?.size===0&&(e.delete(i),e.size===0&&this.rangeIndex.delete(i.table))}}evict(){if(!(this.entries.size<=this.maxEntries&&this.totalBytes<=this.maxBytes))for(const[t,s]of this.entries){if(this.entries.size<=this.maxEntries&&this.totalBytes<=this.maxBytes)return;s.subscribers.size>0||(this.dropEntry(t,s),this.evictions+=1)}}}const E=(d,t,s)=>`${s??"\0anon"}\0${d}:${g(t)}`;export{z as ReactiveCache,E as reactiveCacheKey,A as stableStringify,g as stableWireKey};
@@ -1 +0,0 @@
1
- import{f as l}from"./wire-codec-Ctnni0h6.mjs";const c="_id",p="__lunora__",b=r=>{if(typeof r!="object"||r===null||Array.isArray(r))return;const t=r[c];return typeof t=="string"?t:void 0},y=r=>{const t=new Map,s=[];for(const n of r){const e=b(n);if(e===void 0||t.has(e))return;t.set(e,n),s.push(e)}return{byId:t,order:s}},h=(r,t)=>{const s=r.order.filter(e=>t.byId.has(e)),n=t.order.filter(e=>r.byId.has(e));return s.length!==n.length?!1:s.every((e,o)=>n[o]===e)},g=(r,t,s,n)=>{const e=[];for(const o of r.order)t.byId.has(o)||e.push({delta:{key:o,op:"delete",table:s},frame:`{"key":${JSON.stringify(o)},"op":"delete","table":${n}}`});return e},m=(r,t,s,n)=>{const e=[];for(const o of t.order){const i=t.byId.get(o),a=r.byId.get(o),u=JSON.stringify(l(i)),f=a===void 0?void 0:JSON.stringify(a);if(f===u)continue;const d=f===void 0?"insert":"update";e.push({delta:{key:o,op:d,row:i,table:s},frame:`{"key":${JSON.stringify(o)},"op":"${d}","row":${u},"table":${n}}`})}return e},S=(r,t,s,n)=>{let e;try{e=JSON.parse(r)}catch{return}if(!Array.isArray(e)||!Array.isArray(t))return;const o=y(e),i=y(t);if(o===void 0||i===void 0||!h(o,i))return;const a=s===""?p:s,u=JSON.stringify(a),f=[...g(o,i,a,u),...m(o,i,a,u)];if(!(f.length>i.order.length)){if(n!==void 0)for(const{frame:d}of f)n.push(d);return f.map(({delta:d})=>d)}},$=(r,t)=>{try{return r.send(t),!0}catch{return!1}},w=(r,t,s,n)=>{const e=JSON.stringify(t);let o=!0;for(const i of s)$(r,`{"type":"delta","id":${e},"delta":${i}${n}}`)||(o=!1);return o},A=async r=>{let t=0;for(;t<100;){t+=1;const{bufferedAmount:s}=r;if(typeof s!="number"||s<1048576)return;await new Promise(n=>{setTimeout(n,20)})}};export{A as awaitWsDrain,w as sendDeltaFrames,S as subscriptionListDeltas,$ as trySendFrame};
@@ -1 +0,0 @@
1
- const v=e=>{const r=new DataView(new ArrayBuffer(8));r.setFloat64(0,e,!1);let t=r.getUint32(0,!1),o=r.getUint32(4,!1);return(t&2147483648)===0?t=(t^2147483648)>>>0:(t=~t>>>0,o=~o>>>0),t.toString(16).padStart(8,"0")+o.toString(16).padStart(8,"0")},x=e=>{const r=new TextEncoder().encode(e);let t="";for(const o of r)t+=o.toString(16).padStart(2,"0");return t},c=e=>{if(e===null)return"0";if(typeof e=="number")return Number.isFinite(e)?`1${v(e===0?0:e)}`:void 0;if(typeof e=="string")return`2${x(e)}`},d=e=>{const r=[];for(const t of e){const o=c(t);if(o===void 0)return;r.push(o)}return r.join("!")};const p=new Set([">",">="]),g=new Set(["<","<="]),h=(e,r,t,o)=>{const i=r.comparator==="=",n=p.has(r.comparator)||g.has(r.comparator);return!i&&!n||e.indexOf(r.field)!==t?!1:o===void 0?!0:!i&&o===r.field},m=(e,r,t)=>{const o={equalities:[],lowerExclusive:!1,upperExclusive:!1};let i;for(const n of r){const s=n.comparator==="=",a=p.has(n.comparator);if(!h(e,n,o.equalities.length,i))return;if(s){o.equalities.push(t(n.value));continue}if(i=n.field,a){if(o.lower!==void 0)return;o.lower=t(n.value),o.lowerExclusive=n.comparator===">"}else{if(o.upper!==void 0)return;o.upper=t(n.value),o.upperExclusive=n.comparator==="<"}}return o},f=(e,r)=>{const t=c(r);if(t!==void 0)return e===""?t:e+"!"+t},y=(e,r,t,o,i)=>{if(t.length===0)return;const n=m(t,o,i);if(!n)return;const s=d(n.equalities);if(s===void 0)return;let a=s,l=s+"￿";if(n.lower!==void 0){const u=f(s,n.lower);if(u===void 0)return;a=n.lowerExclusive?u+"￿":u}if(n.upper!==void 0){const u=f(s,n.upper);if(u===void 0)return;l=n.upperExclusive?u:u+"￿"}if(!(a>=l))return{hi:l,index:r,lo:a,table:e}},E=(e,r,t)=>{const o=[];for(const i of e){const n=d(i.fields.map(s=>t(r[s])));n!==void 0&&o.push({index:i.name,key:n})}return o},w=(e,r)=>e.index===r.index&&r.key>=e.lo&&r.key<e.hi,S=(e,r)=>!e||e.length===0||!r||r.length===0?!0:e.some(t=>{const o=r.filter(i=>i.index===t.index);return o.length===0?!0:o.some(i=>w(t,i))});export{y as buildIndexRange,E as indexKeysForRow,S as keysTouchRanges,w as rangeContains};
@@ -1 +0,0 @@
1
- const c=(r,n)=>{try{const t=JSON.stringify(r);return t===void 0?0:t.length}catch{return n}};export{c as r};