@lunora/shard-engine 1.0.0-alpha.182 → 1.0.0-alpha.184
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/conformance/index.mjs +1 -1
- package/dist/index.d.mts +59 -35
- package/dist/index.d.ts +59 -35
- package/dist/index.mjs +1 -1
- package/dist/packem_shared/ADMIN_FUNCTIONS-B_4sLV4q.mjs +1 -0
- package/dist/packem_shared/ADMIN_TOKEN_TABLE-DfQ5osdI.mjs +1 -0
- package/dist/packem_shared/{DEFAULT_MAX_RELAYS-B66neS_B.mjs → DEFAULT_MAX_RELAYS-Bc6PI-xy.mjs} +1 -1
- package/dist/packem_shared/MAX_SQL_ROWS-B4WlVI-e.mjs +5 -0
- package/dist/packem_shared/NotUniqueError-BjwNIte8.mjs +1 -0
- package/dist/packem_shared/RELAY_SIGNATURE_HEADER-CAfC4tqg.mjs +1 -0
- package/dist/packem_shared/adminTokenExists-CjKKZzfY.mjs +7 -0
- package/dist/packem_shared/constant-time-equal-BRh9yUCr.mjs +1 -0
- package/dist/packem_shared/{createReplicaLink-DVXW9rR6.mjs → createReplicaLink-DtqXBi-0.mjs} +1 -1
- package/dist/packem_shared/{defineEngineContractSuite-C4w7jbyk.mjs → defineEngineContractSuite-BiFprp2V.mjs} +1 -1
- package/dist/packem_shared/{stubByName-B8cFYipA.mjs → stubByName-DQSivmvb.mjs} +1 -1
- package/package.json +2 -2
- package/dist/packem_shared/ADMIN_FUNCTIONS-BMBnudzO.mjs +0 -1
- package/dist/packem_shared/MAX_SQL_ROWS-eRignWyO.mjs +0 -4
- package/dist/packem_shared/NotUniqueError-CO-HgL4c.mjs +0 -1
- package/dist/packem_shared/RELAY_SIGNATURE_HEADER-DP0glzE_.mjs +0 -1
|
@@ -1 +1 @@
|
|
|
1
|
-
import{defineEngineContractSuite as t}from"../packem_shared/defineEngineContractSuite-
|
|
1
|
+
import{defineEngineContractSuite as t}from"../packem_shared/defineEngineContractSuite-BiFprp2V.mjs";export{t as defineEngineContractSuite};
|
package/dist/index.d.mts
CHANGED
|
@@ -758,40 +758,6 @@ interface ImportShardAdminArgs {
|
|
|
758
758
|
}
|
|
759
759
|
declare const parseExportShardArgs: (args: Record<string, unknown>) => ExportShardAdminArgs;
|
|
760
760
|
declare const parseImportShardArgs: (args: Record<string, unknown>) => ImportShardAdminArgs;
|
|
761
|
-
declare const matchesStaticWhere: (document: Record<string, unknown>, predicate: Record<string, unknown>) => boolean;
|
|
762
|
-
declare const normalizeCountArgument: (argument: RestrictableQueryOptions | undefined | WhereInput) => RestrictableQueryOptions;
|
|
763
|
-
declare const AGGREGATE_SQL_FUNCTION: Record<string, string>;
|
|
764
|
-
declare const aggregateSqlFunction: (op: string) => string;
|
|
765
|
-
declare const throwingScheduler: SchedulerLike;
|
|
766
|
-
declare const aggregateTableName: (table: string, indexName: string) => string;
|
|
767
|
-
declare const coerceAggregateNumber: (value: unknown) => number | undefined;
|
|
768
|
-
interface AggregateTally {
|
|
769
|
-
count: number;
|
|
770
|
-
value: null | number;
|
|
771
|
-
}
|
|
772
|
-
declare const foldAggregateTally: (tallies: Map<string, AggregateTally>, encoded: string, index: AggregateIndexDefinitionLike, record: Record<string, unknown>) => void;
|
|
773
|
-
declare const readAggregateValue: (op: string, row: {
|
|
774
|
-
count: number;
|
|
775
|
-
value: null | number;
|
|
776
|
-
} | undefined) => null | number;
|
|
777
|
-
declare const encodeAggregateKey: (by: ReadonlyArray<string>, source: Record<string, unknown>) => string;
|
|
778
|
-
declare class CountRlsUnsupportedError extends LunoraError {
|
|
779
|
-
constructor(table?: string);
|
|
780
|
-
}
|
|
781
|
-
declare const mergeWhere: (left: undefined | WhereInput, right: undefined | WhereInput) => undefined | WhereInput;
|
|
782
|
-
declare const planAggregateLookup: (index: AggregateIndexDefinitionLike, requestedWhere: Record<string, unknown> | undefined) => Record<string, unknown> | undefined;
|
|
783
|
-
declare const selectIndexForCount: (indexes: ReadonlyArray<AggregateIndexDefinitionLike>, requestedWhere: Record<string, unknown> | undefined) => undefined | {
|
|
784
|
-
index: AggregateIndexDefinitionLike;
|
|
785
|
-
key: Record<string, unknown>;
|
|
786
|
-
};
|
|
787
|
-
declare const selectIndexForAggregate: (indexes: ReadonlyArray<AggregateIndexDefinitionLike>, op: AggregateOp, field: string, requestedWhere: Record<string, unknown> | undefined) => undefined | {
|
|
788
|
-
index: AggregateIndexDefinitionLike;
|
|
789
|
-
key: Record<string, unknown>;
|
|
790
|
-
};
|
|
791
|
-
declare const selectIndexForGroupBy: (indexes: ReadonlyArray<AggregateIndexDefinitionLike>, op: AggregateOp, field: string | undefined, by: ReadonlyArray<string>, requestedWhere: Record<string, unknown> | undefined) => undefined | {
|
|
792
|
-
index: AggregateIndexDefinitionLike;
|
|
793
|
-
partial: Record<string, unknown>;
|
|
794
|
-
};
|
|
795
761
|
declare const clearCompanionSignatures: (sql: SqlExec) => void;
|
|
796
762
|
declare class CompanionMemo {
|
|
797
763
|
readonly verified: Set<string>;
|
|
@@ -1040,6 +1006,60 @@ declare const normalizeIdStructurally: (schema: SchemaLike, tableName: string, i
|
|
|
1040
1006
|
declare const assertNoExplicitUndefined: (op: "patch" | "patchIf" | "replace", document: Record<string, unknown>) => void;
|
|
1041
1007
|
declare const stripReservedPatchFields: (patch: Record<string, unknown>) => Record<string, unknown>;
|
|
1042
1008
|
declare const createShardCtxDb: (options: CtxDbOptions) => DatabaseWriterLike;
|
|
1009
|
+
declare const ADMIN_TOKEN_TABLE = "__lunora_admin_tokens__";
|
|
1010
|
+
interface AdminTokenSummary {
|
|
1011
|
+
createdAt: number;
|
|
1012
|
+
expiresAt?: number;
|
|
1013
|
+
lastUsedAt?: number;
|
|
1014
|
+
name: string;
|
|
1015
|
+
}
|
|
1016
|
+
declare const createAdminTokenRecord: (sql: SqlExec, record: {
|
|
1017
|
+
createdAt: number;
|
|
1018
|
+
digest: string;
|
|
1019
|
+
expiresAt?: number;
|
|
1020
|
+
name: string;
|
|
1021
|
+
}) => boolean;
|
|
1022
|
+
declare const listAdminTokens: (sql: SqlExec) => AdminTokenSummary[];
|
|
1023
|
+
declare const revokeAdminTokenRecord: (sql: SqlExec, name: string, createdAt: number) => boolean;
|
|
1024
|
+
declare const verifyAdminTokenDigest: (sql: SqlExec, name: string, digest: string, now: number) => undefined | {
|
|
1025
|
+
createdAt: number;
|
|
1026
|
+
expiresAt?: number;
|
|
1027
|
+
};
|
|
1028
|
+
declare const adminTokenExists: (sql: SqlExec, name: string) => boolean;
|
|
1029
|
+
declare const matchesStaticWhere: (document: Record<string, unknown>, predicate: Record<string, unknown>) => boolean;
|
|
1030
|
+
declare const normalizeCountArgument: (argument: RestrictableQueryOptions | undefined | WhereInput) => RestrictableQueryOptions;
|
|
1031
|
+
declare const AGGREGATE_SQL_FUNCTION: Record<string, string>;
|
|
1032
|
+
declare const aggregateSqlFunction: (op: string) => string;
|
|
1033
|
+
declare const throwingScheduler: SchedulerLike;
|
|
1034
|
+
declare const aggregateTableName: (table: string, indexName: string) => string;
|
|
1035
|
+
declare const coerceAggregateNumber: (value: unknown) => number | undefined;
|
|
1036
|
+
interface AggregateTally {
|
|
1037
|
+
count: number;
|
|
1038
|
+
value: null | number;
|
|
1039
|
+
}
|
|
1040
|
+
declare const foldAggregateTally: (tallies: Map<string, AggregateTally>, encoded: string, index: AggregateIndexDefinitionLike, record: Record<string, unknown>) => void;
|
|
1041
|
+
declare const readAggregateValue: (op: string, row: {
|
|
1042
|
+
count: number;
|
|
1043
|
+
value: null | number;
|
|
1044
|
+
} | undefined) => null | number;
|
|
1045
|
+
declare const encodeAggregateKey: (by: ReadonlyArray<string>, source: Record<string, unknown>) => string;
|
|
1046
|
+
declare class CountRlsUnsupportedError extends LunoraError {
|
|
1047
|
+
constructor(table?: string);
|
|
1048
|
+
}
|
|
1049
|
+
declare const mergeWhere: (left: undefined | WhereInput, right: undefined | WhereInput) => undefined | WhereInput;
|
|
1050
|
+
declare const planAggregateLookup: (index: AggregateIndexDefinitionLike, requestedWhere: Record<string, unknown> | undefined) => Record<string, unknown> | undefined;
|
|
1051
|
+
declare const selectIndexForCount: (indexes: ReadonlyArray<AggregateIndexDefinitionLike>, requestedWhere: Record<string, unknown> | undefined) => undefined | {
|
|
1052
|
+
index: AggregateIndexDefinitionLike;
|
|
1053
|
+
key: Record<string, unknown>;
|
|
1054
|
+
};
|
|
1055
|
+
declare const selectIndexForAggregate: (indexes: ReadonlyArray<AggregateIndexDefinitionLike>, op: AggregateOp, field: string, requestedWhere: Record<string, unknown> | undefined) => undefined | {
|
|
1056
|
+
index: AggregateIndexDefinitionLike;
|
|
1057
|
+
key: Record<string, unknown>;
|
|
1058
|
+
};
|
|
1059
|
+
declare const selectIndexForGroupBy: (indexes: ReadonlyArray<AggregateIndexDefinitionLike>, op: AggregateOp, field: string | undefined, by: ReadonlyArray<string>, requestedWhere: Record<string, unknown> | undefined) => undefined | {
|
|
1060
|
+
index: AggregateIndexDefinitionLike;
|
|
1061
|
+
partial: Record<string, unknown>;
|
|
1062
|
+
};
|
|
1043
1063
|
declare const AUDIT_LOG_TABLE = "__lunora_audit__";
|
|
1044
1064
|
interface AuditEntry {
|
|
1045
1065
|
detail?: Record<string, unknown>;
|
|
@@ -1530,6 +1550,7 @@ declare const ADMIN_FUNCTIONS: {
|
|
|
1530
1550
|
readonly clearCapturedMail: "__lunora_admin__:clearCapturedMail";
|
|
1531
1551
|
readonly clearQueueMessages: "__lunora_admin__:clearQueueMessages";
|
|
1532
1552
|
readonly clearTable: "__lunora_admin__:clearTable";
|
|
1553
|
+
readonly createAdminToken: "__lunora_admin__:createAdminToken";
|
|
1533
1554
|
readonly createWorkflowInstance: "__lunora_admin__:createWorkflowInstance";
|
|
1534
1555
|
readonly deleteRows: "__lunora_admin__:deleteRows";
|
|
1535
1556
|
readonly describeTable: "__lunora_admin__:describeTable";
|
|
@@ -1565,6 +1586,7 @@ declare const ADMIN_FUNCTIONS: {
|
|
|
1565
1586
|
readonly getWorkflowInstanceStatus: "__lunora_admin__:getWorkflowInstanceStatus";
|
|
1566
1587
|
readonly ignoreIssue: "__lunora_admin__:ignoreIssue";
|
|
1567
1588
|
readonly importShard: "__lunora_admin__:importShard";
|
|
1589
|
+
readonly listAdminTokens: "__lunora_admin__:listAdminTokens";
|
|
1568
1590
|
readonly listFlags: "__lunora_admin__:listFlags";
|
|
1569
1591
|
readonly listReactors: "__lunora_admin__:listReactors";
|
|
1570
1592
|
readonly listQueues: "__lunora_admin__:listQueues";
|
|
@@ -1587,6 +1609,7 @@ declare const ADMIN_FUNCTIONS: {
|
|
|
1587
1609
|
readonly replayQueueMessage: "__lunora_admin__:replayQueueMessage";
|
|
1588
1610
|
readonly retryOutboxEntry: "__lunora_admin__:retryOutboxEntry";
|
|
1589
1611
|
readonly resolveIssue: "__lunora_admin__:resolveIssue";
|
|
1612
|
+
readonly revokeAdminToken: "__lunora_admin__:revokeAdminToken";
|
|
1590
1613
|
readonly rlsPolicies: "__lunora_admin__:rlsPolicies";
|
|
1591
1614
|
readonly schemaHistory: "__lunora_admin__:schemaHistory";
|
|
1592
1615
|
readonly schemaVersion: "__lunora_admin__:schemaVersion";
|
|
@@ -1601,6 +1624,7 @@ declare const ADMIN_FUNCTIONS: {
|
|
|
1601
1624
|
readonly storageReferences: "__lunora_admin__:storageReferences";
|
|
1602
1625
|
readonly storageRules: "__lunora_admin__:storageRules";
|
|
1603
1626
|
readonly studioFeatures: "__lunora_admin__:studioFeatures";
|
|
1627
|
+
readonly verifyAdminToken: "__lunora_admin__:verifyAdminToken";
|
|
1604
1628
|
readonly writeRow: "__lunora_admin__:writeRow";
|
|
1605
1629
|
};
|
|
1606
1630
|
interface TableInfo {
|
|
@@ -2785,4 +2809,4 @@ declare const backfillVectorIndexes: (sql: SqlExec, targets: ReadonlyArray<Vecto
|
|
|
2785
2809
|
ordered: OrderedAfterWrites;
|
|
2786
2810
|
restart?: boolean;
|
|
2787
2811
|
}) => Promise<VectorBackfillProgress>;
|
|
2788
|
-
export { ADMIN_FUNCTIONS, ADMIN_FUNCTION_PREFIX, AGGREGATE_SQL_FUNCTION, AGG_COUNT, AGG_KEY, AGG_VALUE, AUDIT_LOG_TABLE, type AdvisorProcedure, type AdvisorProceduresResult, type AdvisoriesResult, type AdvisoryFinding, type AggregateIndexDefinitionLike, type AggregateOp, type AggregateOptions, type AggregateResult, type AggregateTally, type AppendAuditEntry, type ApplyOnDeleteOptions, type AuditEntry, type AuditLogResult, BIGINT_KEY_DIGITS, type BroadcastDelta, CDC_LOG_TABLE, CDC_LOG_TABLE_SEQ_INDEX, CDC_META_TABLE, CLIENT_WATERMARK_TABLE, COMMIT_SEQ_FIELD, COMMIT_SEQ_TABLE, CURSOR_PREFIX, type CacheEntry, type CapturedMailRow, type CdcArchiveScope, type CdcChange, type CdcChangeKey, type ChangedKeys, type Clock, type ColumnMeta, type ColumnMetaLike, CompanionMemo, type CompanionSync, type CompanionSyncDeps, ConflictError, type ConflictKind, type CountArgs, CountRlsUnsupportedError, type CreateWorkflowInstanceResult, type CrossShardReadArgs, type CtxDbOptions, DATA_MIGRATION_STATE_TABLE, DEFAULT_FANOUT_TOPIC_LIMIT, DEFAULT_MAX_RELATION_KEYS, DEFAULT_MAX_RELAYS, DEFAULT_PROMOTION_THRESHOLDS, DEFAULT_TRANSACTION_LIMITS, DOC_COLUMN, type DataMigrationDocument, type DataMigrationLike, type DataMigrationTransform, type DatabaseWriterLike, type DependencyTracker, type DeployInfo, type DurableAttachDecision, type DurableStreamAttach, type DurableStreamRun, DurableStreamRunner, type DurableStreamSink, type ExportRow, type ExportShardAdminArgs, type ExportShardArgs, type ExternalSourceDiffResult, type ExternalSourceLike, FLAGS_FUNCTION_PREFIX, type FacetColumnOptions, type FacetColumnResult, type FacetValue, type FanOutBudget, type FanoutMetricsResult, type FanoutPathCounters, type FanoutTopicStat, type FieldOperators, type FilterClause, type FilterOperator, type FlagEvaluation, type FlagsResult, type FtsWriteOptions, type FunctionCallStat, type FunctionScanAttribution, type FunctionStatsResult, GEO_DEFAULT_PRECISION, GLOBAL_SHAPE_SNAPSHOT_TABLE, type GeoBoundingBox, type GeoFilterBuilderLike, type GeoIndexDefinitionLike, type GeoPoint, type GeoScoredDocument, type GlobalPollCounters, GlobalPollTick, type GroupByEntry, type GroupByOptions, type GuardableSchema$1 as GuardableSchema, IDEMPOTENCY_TABLE, type IdGenerator, type IdempotentRecord, type ImportConflictMode, type ImportError, type ImportRow, type ImportShardAdminArgs, type ImportShardArgs, type ImportShardResult, type IncrementalMaterializeResult, type IndexDefinitionLike, type IndexKeyEntry, type IndexRangeBuilderLike, type KeyRange, type KeyedRelationWriteInfo, type LifecycleDispatchInfo, type LifecycleEvent, type LiveSocketControlCall, MAIL_RETENTION, MAIL_TABLE, MAX_DURABLE_STREAM_BYTES, MAX_DURABLE_STREAM_CHUNKS, MAX_PAGE_SIZE, MAX_SQL_ROWS, type MaskColumnMetadata, type MaskPoliciesResult, type MaterializeResult, type MigrationDirection, type MigrationRunResult, type MigrationStatus, type MigrationStatusRow, type MutationDelta, type NestedWith, NotFoundError, NotUniqueError, type NullPlacement, type OnDeleteActionLike, type OrderByClause, type OrderByInput, type OrderKey, type OrderKeyConstraints, OwnerRelay, type OwnerRelayFrame, type PaginationOptions, type PatchVerifier, type PatchWriteOptions, type PitrBookmarkResult, type PitrRestoreArgs, type PitrRestoreResult, type PitrStorage, type PokeFrameMeta, type PromotionState, type PromotionThresholds, QUEUE_TABLE, type QueryArgs, type QueryPage, type QueryPlan, type QueueMessageOutcome, type QueueMessageRow, type QueueMetadata, type QueuesResult, RANK_TIEBREAK, REACTOR_STATE_TABLE, RELATED_DEFAULT_LIMIT, RELATED_DEPTH_DECAY, RELATED_MAX_DEPTH, RELATED_MAX_LIMIT, RELATION_EXISTS_KEY, RELATION_FUNCTION_PREFIX, RELAY_SIGNATURE_HEADER, REPROJECTION_MIGRATION_PREFIX, RLS_UNWRAP_SYMBOL, type RangeOperandType, type RankBeforeOptions, type RankBeforeResult, type RankDirection, type RankIndexDefinitionLike, type RankOptions, type RankPage, type RankPageComputation, type RankPageDeps, type RankPageOptions, type RankPageRow, type RankPageRowKey, type RankResult, type RankSortKeyLike, ReactiveCache, type ReactiveCacheOptions, type ReactorDispatchResult, type ReactorMetadata, type ReactorState, type ReactorStats, type ReactorsResult, type ReadFootprint, type ReadHook, type ReadTablePageOptions, type RecordMailInput, type RecordQueueMessageInput, type RelatedDirection, type RelatedNode, type RelatedOptions, type RelatedPage, type RelatedStart, type RelatedStartReference, type RelationDefinitionLike, type RelationEdge, type RelationExistsMarker, type RelationGraphReader, type RelationWriteInfo, type RelationWriteMap, type RelayAttach, type RelayDetach, type RelayFrame, type RelayHost, RelayMember, type RelayPokeDelivery, type RelayRoomEvent, type RelayRoomVerdict, type RelayShapePoke, type RelayShapeSeed, type RelayShapeSubscribe, type RelayShapeUnsubscribe, type RenderedSql, type ReplicaFollowerHost, type ReplicaOwnerHost, type ReplicaReadiness, type ResolveRelationPredicatesOptions, type ResolveWithOptions, type ResolveWithResult, type ResolvedShape, type RestrictableQueryOptions, type RlsPoliciesResult, type RlsPolicyMetadata, RlsRequiredError, type RlsRoleMetadata, type RpcRequest, type RunDataMigrationOptions, type RunTriggersOptions, SCAN_DEP, SCHEDULE_OUTBOX_TABLE, SCHEMA_HISTORY_MAX_VERSIONS, SEARCH_STATE_TABLE, SHAPE_POKE_CURSOR_TABLE, type SchedulableWorkflowReferenceLike, type ScheduleOutbox, type ScheduleOutboxEntry, type ScheduleOutboxEnvelope, type ScheduleOutboxRow, type ScheduledFunctionDoc, type SchedulerLike, type SchemaLike, type ScoredDocument, type SearchBackfillProgress, type SearchFilterBuilderLike, type SearchIndexDefinitionLike, type SearchScoredDocument, type SelectMatchingIdsOptions, type ServerDefaultContextLike, type SettingEntry, type SettingKind, type SettingsResult, ShapeDiffCache, type ShapePokeCursorRow, type ShapePokePart, type ShapeProbeCounters, type ShapeRow, type ShapeRowOp, type ShapeSubscriptionQuery, type ShardRankPageResult, ShardRunner, type ShardRunnerOptions, type ShardSiblingHost, type ShardSocketLike, type SocketAttachment, type SortDirection, type SourceClientLike, type SourceCursorLike, type SourceRefresh, type SqlConsoleResult, type SqlCursor, type SqlEngine, type SqlExec, type SqlLintResult, type StorageMetadata, type StorageReference, type StorageReferenceResult, type StorageRuleMetadata, type StorageRulesResult, type StudioFeaturesResult, type SubscriptionConnection, type SubscriptionEnvelope, type SubscriptionIdentity, type SubscriptionInfo, type SubscriptionQuery, type SubscriptionReadFootprint, type SubscriptionsResult, type SystemDatabaseReader, type SystemDoc, type SystemQuery, type SystemReaderOptions, type SystemReaderSchedulerLike, type SystemReaderStorageLike, type SystemTableName, type TableColumnsResult, type TableDefinitionLike, type TableIndexInfo, type TableIndexesResult, type TableInfo, type TablePage, type TableReaderLike, type TablesColumnsResult, type TablesIndexesResult, type ThroughRelationWriteInfo, type TransactionHeadroom, TransactionHeadroomTracker, type TransactionLimitKind, type TransactionLimitWarning, type TransactionLimits, type TransactionSqlLike, type TriggerContextLike, type TriggerDefinitionLike, type TriggerEventLike, type TriggerOpLike, type TriggerTimingLike, type TtlSweepSpec, UNVOUCHABLE_DEP, VECTOR_BACKFILL_MAX_PAGES, type ValidatorLike, type VectorBackfillProgress, WORKERD_SQLITE_LIMITS, type WhereFilter, type WhereInput, type WhereSqlStrategy, type WithInput, type WorkflowInstanceState, type WorkflowInstanceStatusResult, type WorkflowMetadata, type WorkflowsResult, type WriteEvent, type WriteHook, advanceClientWatermark, aggUpsertSql, aggregateSqlFunction, aggregateTableName, allocateCommitSeq, appendAuditEntry, appendCdcChange, appendStreamChunk, applyCdcChanges, applyInsertDefaults, applyOnDelete, applySelect, archiveCdcSegment, armRestore, assertFlatPredicate, assertNoExplicitUndefined, assertPatchAllowed, assertReadonly, assertShapeShardable, assertStorableRowId, assertValidClientId, awaitWsDrain, backfillAggregateIndexes, backfillRankIndexes, backfillSearchIndexes, backfillSearchIndexesForTable, backfillVectorIndexes, bigintSqlKey, boundingBoxCenter, boundingBoxGeohashes, buildIndexRange, buildPokeFrames, buildReprojectionMigration, buildSeekBeforeWhere, buildSeekWhere, buildSettings, buildShapeDiff, bumpCdcEpoch, cdcArchiveRewound, cdcCanVouchFor, cdcForkedError, cdcSeqLeavingRows, cdcTouchesTables, cdcTrimmedError, claimStreamRun, clampPromotionThresholds, clearCapturedMail, clearCompanionSignatures, clearMemoryTables, clearQueueMessages, coerceAggregateNumber, compactCdcDocs, compileWhereSql, composeReadPredicate, computeRankPage, containsRelationPredicate, countLegacyRows, coveringGeohashes, createCompanionSync, createDependencyTracker, createFanoutCounters, createGlobalPollCounters, createIndexSql, createReadFootprint, createRelayLink, createReplicaLink, createShapeDiffCache, createShapeProbeCounters, createShardCtxDb, createSystemReader, cursorBelowRetainedFloor, decideDurableAttach, decodeBigintSqlKey, decodeCursor, decodeFloat64SqlKey, deferScheduleOutbox, deleteGlobalShapeSnapshot, deleteGlobalShapeSnapshotsForConnection, deleteShapePokeCursor, deleteShapePokeCursorsForConnection, deleteStreamRun, depKey, deriveRelationEdges, describeRelationWrites, diffExternalSource, diffGlobalMembership, distinctValues, dropScheduleOutbox, encodeAggregateKey, encodeCursor, encodeGeohash, encodePartitionKey, encodeRowsPatch, ensureAuditTable, ensureMailTable, envOptionalPositiveInt, envPositiveInt, equalityPinnedFields, exportShardRows, facetColumn, fanOutScalarCounts, findRelated, findStorageReferences, finishStreamRun, float64SqlKey, foldAggregateTally, forgetScheduleOutbox, ftsCompanionDdl, ftsPurgeDocument, ftsRowidMapName, ftsUnmappedPage, ftsWriteDocument, gateReplicaDispatch, geoTableName, globalShapeReadKey, groupUnmappedRows, guardWriter, handleReplicaControl, hasScheduleOutboxEntry, hasTrigger, haversineMeters, importShardRows, indexKeysForRow, isDevEnvironment, isFtsAvailable, isInternalTableName, isLossyBody, isMemoryTable, isPushableWhere, isRelationPredicate, isSoftDeleted, isSourceDue, isTtlExpired, isVacuousFilterClause, jsonPath, jsonPathSql, keysTouchRanges, liftSourceId, lintReadonlySql, listReactorStates, listTables, markUnvouchableReads, matchesRankStaticWhere, matchesStaticWhere, materializeExternalRows, materializeExternalRowsIncremental, memoryTableNames, mergeChangedKeys, mergeWhere, migrateCdcLog, migrateCdcMeta, migrateClientWatermark, migrateCommitSeq, migrateDurableStreams, migrateGlobalShapeSnapshot, migrateIdempotency, migrateReactorState, migrateScheduleOutbox, migrateSearchState, migrateShapePokeCursor, minCdcReplayableSeq, minCdcSeq, minShapePokeCursor, nextPromotionState, nextTtlExpiry, normalizeCountArgument, normalizeIdStructurally, normalizeOrderKeys, normalizeSourceDocument, normalizeSourceValue, nullsFirstOf, nullsOrderSuffix, operatorFields, param, parkScheduleOutbox, parseExportShardArgs, parseImportShardArgs, patchDependsOnRow, planAggregateLookup, pointInBoundingBox, probeScheduleOutbox, projectColumns, pullExternalSourceIncrementalTick, pullExternalSourceTick, qualifiedJsonPath, qualifiedJsonPathSql, quoteIdentifier, rankKeyFromDocument as rankKeyFromDoc, rankPivotConditionSql, rankTableName, reactiveCacheKey, reactorNeedsRun, readAggregateValue, readArchivedCdcChanges, readAuditLog, readBookmark, readCapturedMail, readCdcArchivedThrough, readCdcChangeKeys, readCdcChanges, readCdcCursor, readCdcEpoch, readClientWatermark, readCommitSeq, readDeployInfo, readDueScheduleOutbox, readDueScheduleOutboxEntry, readExternalSourceBaseline, readGlobalShapeSnapshot, readIdempotent, readMigrationStatus, readPatchField, readQueueMessageById, readQueueMessages, readReactorState, readScheduleOutbox, readScheduleOutboxState, readSchemaHistory, readSchemaVersion, readSearchBackfillState, readShapePokeCursor, readStreamChunks, readStreamRun, readTablePage, recordCapturedMail, recordChangedKeys, recordFanoutPass, recordGlobalPollPass, recordQueueMessages, recordScheduleOutbox, recordSchemaVersion, recordShapeProbePass, relationHooks, relayCountFor, renderSql, reprojectableFields, reprojectionMigrationId, reprojectionTables, requeueScheduleOutbox, resolvePatch, resolveRankPartition, resolveRankSeekTuple, resolveRelationPredicates, resolveWith, rowToDocument, runDataMigration, runDrizzle, runExternalSourceTick, runReadonlySql, runRowValidators, runShardMigrations, runSocketPool, runSql, runTriggers, selectExpiredIds, selectExportTables, selectIndexForAggregate, selectIndexForCount, selectIndexForGroupBy, selectMatchingIds, selectShapeMembers, selectShapeRows, serializeSqlValue, serverInList, shapeRoutingKey, siblingSecretOf, signSiblingBody, softDeleteScope, sortColumnName, sqliteInList, stripReservedPatchFields, stubByName, subscriptionFrames, subscriptionListDeltas, summarizeFanoutTopics, summarizeSubscriptions, tableColumns, tableFromDepKey, throwingScheduler, tiebreakDirectionFor, trimCdcChanges, trimIdempotent, trimScheduleOutbox, trimStreamRuns, tryRowToDocument, trySendFrame, unionAll, uniqueIndexFields, validateImportRow, verifySiblingBody, whereFilter, whereOfFilter, writeCdcArchivedThrough, writeGlobalShapeSnapshot, writeIdempotent, writeReactorState, writeSearchBackfillState, writeShapePokeCursor, writeShapePokeCursors, writeTouchesMemo };
|
|
2812
|
+
export { ADMIN_FUNCTIONS, ADMIN_FUNCTION_PREFIX, ADMIN_TOKEN_TABLE, AGGREGATE_SQL_FUNCTION, AGG_COUNT, AGG_KEY, AGG_VALUE, AUDIT_LOG_TABLE, type AdminTokenSummary, type AdvisorProcedure, type AdvisorProceduresResult, type AdvisoriesResult, type AdvisoryFinding, type AggregateIndexDefinitionLike, type AggregateOp, type AggregateOptions, type AggregateResult, type AggregateTally, type AppendAuditEntry, type ApplyOnDeleteOptions, type AuditEntry, type AuditLogResult, BIGINT_KEY_DIGITS, type BroadcastDelta, CDC_LOG_TABLE, CDC_LOG_TABLE_SEQ_INDEX, CDC_META_TABLE, CLIENT_WATERMARK_TABLE, COMMIT_SEQ_FIELD, COMMIT_SEQ_TABLE, CURSOR_PREFIX, type CacheEntry, type CapturedMailRow, type CdcArchiveScope, type CdcChange, type CdcChangeKey, type ChangedKeys, type Clock, type ColumnMeta, type ColumnMetaLike, CompanionMemo, type CompanionSync, type CompanionSyncDeps, ConflictError, type ConflictKind, type CountArgs, CountRlsUnsupportedError, type CreateWorkflowInstanceResult, type CrossShardReadArgs, type CtxDbOptions, DATA_MIGRATION_STATE_TABLE, DEFAULT_FANOUT_TOPIC_LIMIT, DEFAULT_MAX_RELATION_KEYS, DEFAULT_MAX_RELAYS, DEFAULT_PROMOTION_THRESHOLDS, DEFAULT_TRANSACTION_LIMITS, DOC_COLUMN, type DataMigrationDocument, type DataMigrationLike, type DataMigrationTransform, type DatabaseWriterLike, type DependencyTracker, type DeployInfo, type DurableAttachDecision, type DurableStreamAttach, type DurableStreamRun, DurableStreamRunner, type DurableStreamSink, type ExportRow, type ExportShardAdminArgs, type ExportShardArgs, type ExternalSourceDiffResult, type ExternalSourceLike, FLAGS_FUNCTION_PREFIX, type FacetColumnOptions, type FacetColumnResult, type FacetValue, type FanOutBudget, type FanoutMetricsResult, type FanoutPathCounters, type FanoutTopicStat, type FieldOperators, type FilterClause, type FilterOperator, type FlagEvaluation, type FlagsResult, type FtsWriteOptions, type FunctionCallStat, type FunctionScanAttribution, type FunctionStatsResult, GEO_DEFAULT_PRECISION, GLOBAL_SHAPE_SNAPSHOT_TABLE, type GeoBoundingBox, type GeoFilterBuilderLike, type GeoIndexDefinitionLike, type GeoPoint, type GeoScoredDocument, type GlobalPollCounters, GlobalPollTick, type GroupByEntry, type GroupByOptions, type GuardableSchema$1 as GuardableSchema, IDEMPOTENCY_TABLE, type IdGenerator, type IdempotentRecord, type ImportConflictMode, type ImportError, type ImportRow, type ImportShardAdminArgs, type ImportShardArgs, type ImportShardResult, type IncrementalMaterializeResult, type IndexDefinitionLike, type IndexKeyEntry, type IndexRangeBuilderLike, type KeyRange, type KeyedRelationWriteInfo, type LifecycleDispatchInfo, type LifecycleEvent, type LiveSocketControlCall, MAIL_RETENTION, MAIL_TABLE, MAX_DURABLE_STREAM_BYTES, MAX_DURABLE_STREAM_CHUNKS, MAX_PAGE_SIZE, MAX_SQL_ROWS, type MaskColumnMetadata, type MaskPoliciesResult, type MaterializeResult, type MigrationDirection, type MigrationRunResult, type MigrationStatus, type MigrationStatusRow, type MutationDelta, type NestedWith, NotFoundError, NotUniqueError, type NullPlacement, type OnDeleteActionLike, type OrderByClause, type OrderByInput, type OrderKey, type OrderKeyConstraints, OwnerRelay, type OwnerRelayFrame, type PaginationOptions, type PatchVerifier, type PatchWriteOptions, type PitrBookmarkResult, type PitrRestoreArgs, type PitrRestoreResult, type PitrStorage, type PokeFrameMeta, type PromotionState, type PromotionThresholds, QUEUE_TABLE, type QueryArgs, type QueryPage, type QueryPlan, type QueueMessageOutcome, type QueueMessageRow, type QueueMetadata, type QueuesResult, RANK_TIEBREAK, REACTOR_STATE_TABLE, RELATED_DEFAULT_LIMIT, RELATED_DEPTH_DECAY, RELATED_MAX_DEPTH, RELATED_MAX_LIMIT, RELATION_EXISTS_KEY, RELATION_FUNCTION_PREFIX, RELAY_SIGNATURE_HEADER, REPROJECTION_MIGRATION_PREFIX, RLS_UNWRAP_SYMBOL, type RangeOperandType, type RankBeforeOptions, type RankBeforeResult, type RankDirection, type RankIndexDefinitionLike, type RankOptions, type RankPage, type RankPageComputation, type RankPageDeps, type RankPageOptions, type RankPageRow, type RankPageRowKey, type RankResult, type RankSortKeyLike, ReactiveCache, type ReactiveCacheOptions, type ReactorDispatchResult, type ReactorMetadata, type ReactorState, type ReactorStats, type ReactorsResult, type ReadFootprint, type ReadHook, type ReadTablePageOptions, type RecordMailInput, type RecordQueueMessageInput, type RelatedDirection, type RelatedNode, type RelatedOptions, type RelatedPage, type RelatedStart, type RelatedStartReference, type RelationDefinitionLike, type RelationEdge, type RelationExistsMarker, type RelationGraphReader, type RelationWriteInfo, type RelationWriteMap, type RelayAttach, type RelayDetach, type RelayFrame, type RelayHost, RelayMember, type RelayPokeDelivery, type RelayRoomEvent, type RelayRoomVerdict, type RelayShapePoke, type RelayShapeSeed, type RelayShapeSubscribe, type RelayShapeUnsubscribe, type RenderedSql, type ReplicaFollowerHost, type ReplicaOwnerHost, type ReplicaReadiness, type ResolveRelationPredicatesOptions, type ResolveWithOptions, type ResolveWithResult, type ResolvedShape, type RestrictableQueryOptions, type RlsPoliciesResult, type RlsPolicyMetadata, RlsRequiredError, type RlsRoleMetadata, type RpcRequest, type RunDataMigrationOptions, type RunTriggersOptions, SCAN_DEP, SCHEDULE_OUTBOX_TABLE, SCHEMA_HISTORY_MAX_VERSIONS, SEARCH_STATE_TABLE, SHAPE_POKE_CURSOR_TABLE, type SchedulableWorkflowReferenceLike, type ScheduleOutbox, type ScheduleOutboxEntry, type ScheduleOutboxEnvelope, type ScheduleOutboxRow, type ScheduledFunctionDoc, type SchedulerLike, type SchemaLike, type ScoredDocument, type SearchBackfillProgress, type SearchFilterBuilderLike, type SearchIndexDefinitionLike, type SearchScoredDocument, type SelectMatchingIdsOptions, type ServerDefaultContextLike, type SettingEntry, type SettingKind, type SettingsResult, ShapeDiffCache, type ShapePokeCursorRow, type ShapePokePart, type ShapeProbeCounters, type ShapeRow, type ShapeRowOp, type ShapeSubscriptionQuery, type ShardRankPageResult, ShardRunner, type ShardRunnerOptions, type ShardSiblingHost, type ShardSocketLike, type SocketAttachment, type SortDirection, type SourceClientLike, type SourceCursorLike, type SourceRefresh, type SqlConsoleResult, type SqlCursor, type SqlEngine, type SqlExec, type SqlLintResult, type StorageMetadata, type StorageReference, type StorageReferenceResult, type StorageRuleMetadata, type StorageRulesResult, type StudioFeaturesResult, type SubscriptionConnection, type SubscriptionEnvelope, type SubscriptionIdentity, type SubscriptionInfo, type SubscriptionQuery, type SubscriptionReadFootprint, type SubscriptionsResult, type SystemDatabaseReader, type SystemDoc, type SystemQuery, type SystemReaderOptions, type SystemReaderSchedulerLike, type SystemReaderStorageLike, type SystemTableName, type TableColumnsResult, type TableDefinitionLike, type TableIndexInfo, type TableIndexesResult, type TableInfo, type TablePage, type TableReaderLike, type TablesColumnsResult, type TablesIndexesResult, type ThroughRelationWriteInfo, type TransactionHeadroom, TransactionHeadroomTracker, type TransactionLimitKind, type TransactionLimitWarning, type TransactionLimits, type TransactionSqlLike, type TriggerContextLike, type TriggerDefinitionLike, type TriggerEventLike, type TriggerOpLike, type TriggerTimingLike, type TtlSweepSpec, UNVOUCHABLE_DEP, VECTOR_BACKFILL_MAX_PAGES, type ValidatorLike, type VectorBackfillProgress, WORKERD_SQLITE_LIMITS, type WhereFilter, type WhereInput, type WhereSqlStrategy, type WithInput, type WorkflowInstanceState, type WorkflowInstanceStatusResult, type WorkflowMetadata, type WorkflowsResult, type WriteEvent, type WriteHook, adminTokenExists, advanceClientWatermark, aggUpsertSql, aggregateSqlFunction, aggregateTableName, allocateCommitSeq, appendAuditEntry, appendCdcChange, appendStreamChunk, applyCdcChanges, applyInsertDefaults, applyOnDelete, applySelect, archiveCdcSegment, armRestore, assertFlatPredicate, assertNoExplicitUndefined, assertPatchAllowed, assertReadonly, assertShapeShardable, assertStorableRowId, assertValidClientId, awaitWsDrain, backfillAggregateIndexes, backfillRankIndexes, backfillSearchIndexes, backfillSearchIndexesForTable, backfillVectorIndexes, bigintSqlKey, boundingBoxCenter, boundingBoxGeohashes, buildIndexRange, buildPokeFrames, buildReprojectionMigration, buildSeekBeforeWhere, buildSeekWhere, buildSettings, buildShapeDiff, bumpCdcEpoch, cdcArchiveRewound, cdcCanVouchFor, cdcForkedError, cdcSeqLeavingRows, cdcTouchesTables, cdcTrimmedError, claimStreamRun, clampPromotionThresholds, clearCapturedMail, clearCompanionSignatures, clearMemoryTables, clearQueueMessages, coerceAggregateNumber, compactCdcDocs, compileWhereSql, composeReadPredicate, computeRankPage, containsRelationPredicate, countLegacyRows, coveringGeohashes, createAdminTokenRecord, createCompanionSync, createDependencyTracker, createFanoutCounters, createGlobalPollCounters, createIndexSql, createReadFootprint, createRelayLink, createReplicaLink, createShapeDiffCache, createShapeProbeCounters, createShardCtxDb, createSystemReader, cursorBelowRetainedFloor, decideDurableAttach, decodeBigintSqlKey, decodeCursor, decodeFloat64SqlKey, deferScheduleOutbox, deleteGlobalShapeSnapshot, deleteGlobalShapeSnapshotsForConnection, deleteShapePokeCursor, deleteShapePokeCursorsForConnection, deleteStreamRun, depKey, deriveRelationEdges, describeRelationWrites, diffExternalSource, diffGlobalMembership, distinctValues, dropScheduleOutbox, encodeAggregateKey, encodeCursor, encodeGeohash, encodePartitionKey, encodeRowsPatch, ensureAuditTable, ensureMailTable, envOptionalPositiveInt, envPositiveInt, equalityPinnedFields, exportShardRows, facetColumn, fanOutScalarCounts, findRelated, findStorageReferences, finishStreamRun, float64SqlKey, foldAggregateTally, forgetScheduleOutbox, ftsCompanionDdl, ftsPurgeDocument, ftsRowidMapName, ftsUnmappedPage, ftsWriteDocument, gateReplicaDispatch, geoTableName, globalShapeReadKey, groupUnmappedRows, guardWriter, handleReplicaControl, hasScheduleOutboxEntry, hasTrigger, haversineMeters, importShardRows, indexKeysForRow, isDevEnvironment, isFtsAvailable, isInternalTableName, isLossyBody, isMemoryTable, isPushableWhere, isRelationPredicate, isSoftDeleted, isSourceDue, isTtlExpired, isVacuousFilterClause, jsonPath, jsonPathSql, keysTouchRanges, liftSourceId, lintReadonlySql, listAdminTokens, listReactorStates, listTables, markUnvouchableReads, matchesRankStaticWhere, matchesStaticWhere, materializeExternalRows, materializeExternalRowsIncremental, memoryTableNames, mergeChangedKeys, mergeWhere, migrateCdcLog, migrateCdcMeta, migrateClientWatermark, migrateCommitSeq, migrateDurableStreams, migrateGlobalShapeSnapshot, migrateIdempotency, migrateReactorState, migrateScheduleOutbox, migrateSearchState, migrateShapePokeCursor, minCdcReplayableSeq, minCdcSeq, minShapePokeCursor, nextPromotionState, nextTtlExpiry, normalizeCountArgument, normalizeIdStructurally, normalizeOrderKeys, normalizeSourceDocument, normalizeSourceValue, nullsFirstOf, nullsOrderSuffix, operatorFields, param, parkScheduleOutbox, parseExportShardArgs, parseImportShardArgs, patchDependsOnRow, planAggregateLookup, pointInBoundingBox, probeScheduleOutbox, projectColumns, pullExternalSourceIncrementalTick, pullExternalSourceTick, qualifiedJsonPath, qualifiedJsonPathSql, quoteIdentifier, rankKeyFromDocument as rankKeyFromDoc, rankPivotConditionSql, rankTableName, reactiveCacheKey, reactorNeedsRun, readAggregateValue, readArchivedCdcChanges, readAuditLog, readBookmark, readCapturedMail, readCdcArchivedThrough, readCdcChangeKeys, readCdcChanges, readCdcCursor, readCdcEpoch, readClientWatermark, readCommitSeq, readDeployInfo, readDueScheduleOutbox, readDueScheduleOutboxEntry, readExternalSourceBaseline, readGlobalShapeSnapshot, readIdempotent, readMigrationStatus, readPatchField, readQueueMessageById, readQueueMessages, readReactorState, readScheduleOutbox, readScheduleOutboxState, readSchemaHistory, readSchemaVersion, readSearchBackfillState, readShapePokeCursor, readStreamChunks, readStreamRun, readTablePage, recordCapturedMail, recordChangedKeys, recordFanoutPass, recordGlobalPollPass, recordQueueMessages, recordScheduleOutbox, recordSchemaVersion, recordShapeProbePass, relationHooks, relayCountFor, renderSql, reprojectableFields, reprojectionMigrationId, reprojectionTables, requeueScheduleOutbox, resolvePatch, resolveRankPartition, resolveRankSeekTuple, resolveRelationPredicates, resolveWith, revokeAdminTokenRecord, rowToDocument, runDataMigration, runDrizzle, runExternalSourceTick, runReadonlySql, runRowValidators, runShardMigrations, runSocketPool, runSql, runTriggers, selectExpiredIds, selectExportTables, selectIndexForAggregate, selectIndexForCount, selectIndexForGroupBy, selectMatchingIds, selectShapeMembers, selectShapeRows, serializeSqlValue, serverInList, shapeRoutingKey, siblingSecretOf, signSiblingBody, softDeleteScope, sortColumnName, sqliteInList, stripReservedPatchFields, stubByName, subscriptionFrames, subscriptionListDeltas, summarizeFanoutTopics, summarizeSubscriptions, tableColumns, tableFromDepKey, throwingScheduler, tiebreakDirectionFor, trimCdcChanges, trimIdempotent, trimScheduleOutbox, trimStreamRuns, tryRowToDocument, trySendFrame, unionAll, uniqueIndexFields, validateImportRow, verifyAdminTokenDigest, verifySiblingBody, whereFilter, whereOfFilter, writeCdcArchivedThrough, writeGlobalShapeSnapshot, writeIdempotent, writeReactorState, writeSearchBackfillState, writeShapePokeCursor, writeShapePokeCursors, writeTouchesMemo };
|
package/dist/index.d.ts
CHANGED
|
@@ -758,40 +758,6 @@ interface ImportShardAdminArgs {
|
|
|
758
758
|
}
|
|
759
759
|
declare const parseExportShardArgs: (args: Record<string, unknown>) => ExportShardAdminArgs;
|
|
760
760
|
declare const parseImportShardArgs: (args: Record<string, unknown>) => ImportShardAdminArgs;
|
|
761
|
-
declare const matchesStaticWhere: (document: Record<string, unknown>, predicate: Record<string, unknown>) => boolean;
|
|
762
|
-
declare const normalizeCountArgument: (argument: RestrictableQueryOptions | undefined | WhereInput) => RestrictableQueryOptions;
|
|
763
|
-
declare const AGGREGATE_SQL_FUNCTION: Record<string, string>;
|
|
764
|
-
declare const aggregateSqlFunction: (op: string) => string;
|
|
765
|
-
declare const throwingScheduler: SchedulerLike;
|
|
766
|
-
declare const aggregateTableName: (table: string, indexName: string) => string;
|
|
767
|
-
declare const coerceAggregateNumber: (value: unknown) => number | undefined;
|
|
768
|
-
interface AggregateTally {
|
|
769
|
-
count: number;
|
|
770
|
-
value: null | number;
|
|
771
|
-
}
|
|
772
|
-
declare const foldAggregateTally: (tallies: Map<string, AggregateTally>, encoded: string, index: AggregateIndexDefinitionLike, record: Record<string, unknown>) => void;
|
|
773
|
-
declare const readAggregateValue: (op: string, row: {
|
|
774
|
-
count: number;
|
|
775
|
-
value: null | number;
|
|
776
|
-
} | undefined) => null | number;
|
|
777
|
-
declare const encodeAggregateKey: (by: ReadonlyArray<string>, source: Record<string, unknown>) => string;
|
|
778
|
-
declare class CountRlsUnsupportedError extends LunoraError {
|
|
779
|
-
constructor(table?: string);
|
|
780
|
-
}
|
|
781
|
-
declare const mergeWhere: (left: undefined | WhereInput, right: undefined | WhereInput) => undefined | WhereInput;
|
|
782
|
-
declare const planAggregateLookup: (index: AggregateIndexDefinitionLike, requestedWhere: Record<string, unknown> | undefined) => Record<string, unknown> | undefined;
|
|
783
|
-
declare const selectIndexForCount: (indexes: ReadonlyArray<AggregateIndexDefinitionLike>, requestedWhere: Record<string, unknown> | undefined) => undefined | {
|
|
784
|
-
index: AggregateIndexDefinitionLike;
|
|
785
|
-
key: Record<string, unknown>;
|
|
786
|
-
};
|
|
787
|
-
declare const selectIndexForAggregate: (indexes: ReadonlyArray<AggregateIndexDefinitionLike>, op: AggregateOp, field: string, requestedWhere: Record<string, unknown> | undefined) => undefined | {
|
|
788
|
-
index: AggregateIndexDefinitionLike;
|
|
789
|
-
key: Record<string, unknown>;
|
|
790
|
-
};
|
|
791
|
-
declare const selectIndexForGroupBy: (indexes: ReadonlyArray<AggregateIndexDefinitionLike>, op: AggregateOp, field: string | undefined, by: ReadonlyArray<string>, requestedWhere: Record<string, unknown> | undefined) => undefined | {
|
|
792
|
-
index: AggregateIndexDefinitionLike;
|
|
793
|
-
partial: Record<string, unknown>;
|
|
794
|
-
};
|
|
795
761
|
declare const clearCompanionSignatures: (sql: SqlExec) => void;
|
|
796
762
|
declare class CompanionMemo {
|
|
797
763
|
readonly verified: Set<string>;
|
|
@@ -1040,6 +1006,60 @@ declare const normalizeIdStructurally: (schema: SchemaLike, tableName: string, i
|
|
|
1040
1006
|
declare const assertNoExplicitUndefined: (op: "patch" | "patchIf" | "replace", document: Record<string, unknown>) => void;
|
|
1041
1007
|
declare const stripReservedPatchFields: (patch: Record<string, unknown>) => Record<string, unknown>;
|
|
1042
1008
|
declare const createShardCtxDb: (options: CtxDbOptions) => DatabaseWriterLike;
|
|
1009
|
+
declare const ADMIN_TOKEN_TABLE = "__lunora_admin_tokens__";
|
|
1010
|
+
interface AdminTokenSummary {
|
|
1011
|
+
createdAt: number;
|
|
1012
|
+
expiresAt?: number;
|
|
1013
|
+
lastUsedAt?: number;
|
|
1014
|
+
name: string;
|
|
1015
|
+
}
|
|
1016
|
+
declare const createAdminTokenRecord: (sql: SqlExec, record: {
|
|
1017
|
+
createdAt: number;
|
|
1018
|
+
digest: string;
|
|
1019
|
+
expiresAt?: number;
|
|
1020
|
+
name: string;
|
|
1021
|
+
}) => boolean;
|
|
1022
|
+
declare const listAdminTokens: (sql: SqlExec) => AdminTokenSummary[];
|
|
1023
|
+
declare const revokeAdminTokenRecord: (sql: SqlExec, name: string, createdAt: number) => boolean;
|
|
1024
|
+
declare const verifyAdminTokenDigest: (sql: SqlExec, name: string, digest: string, now: number) => undefined | {
|
|
1025
|
+
createdAt: number;
|
|
1026
|
+
expiresAt?: number;
|
|
1027
|
+
};
|
|
1028
|
+
declare const adminTokenExists: (sql: SqlExec, name: string) => boolean;
|
|
1029
|
+
declare const matchesStaticWhere: (document: Record<string, unknown>, predicate: Record<string, unknown>) => boolean;
|
|
1030
|
+
declare const normalizeCountArgument: (argument: RestrictableQueryOptions | undefined | WhereInput) => RestrictableQueryOptions;
|
|
1031
|
+
declare const AGGREGATE_SQL_FUNCTION: Record<string, string>;
|
|
1032
|
+
declare const aggregateSqlFunction: (op: string) => string;
|
|
1033
|
+
declare const throwingScheduler: SchedulerLike;
|
|
1034
|
+
declare const aggregateTableName: (table: string, indexName: string) => string;
|
|
1035
|
+
declare const coerceAggregateNumber: (value: unknown) => number | undefined;
|
|
1036
|
+
interface AggregateTally {
|
|
1037
|
+
count: number;
|
|
1038
|
+
value: null | number;
|
|
1039
|
+
}
|
|
1040
|
+
declare const foldAggregateTally: (tallies: Map<string, AggregateTally>, encoded: string, index: AggregateIndexDefinitionLike, record: Record<string, unknown>) => void;
|
|
1041
|
+
declare const readAggregateValue: (op: string, row: {
|
|
1042
|
+
count: number;
|
|
1043
|
+
value: null | number;
|
|
1044
|
+
} | undefined) => null | number;
|
|
1045
|
+
declare const encodeAggregateKey: (by: ReadonlyArray<string>, source: Record<string, unknown>) => string;
|
|
1046
|
+
declare class CountRlsUnsupportedError extends LunoraError {
|
|
1047
|
+
constructor(table?: string);
|
|
1048
|
+
}
|
|
1049
|
+
declare const mergeWhere: (left: undefined | WhereInput, right: undefined | WhereInput) => undefined | WhereInput;
|
|
1050
|
+
declare const planAggregateLookup: (index: AggregateIndexDefinitionLike, requestedWhere: Record<string, unknown> | undefined) => Record<string, unknown> | undefined;
|
|
1051
|
+
declare const selectIndexForCount: (indexes: ReadonlyArray<AggregateIndexDefinitionLike>, requestedWhere: Record<string, unknown> | undefined) => undefined | {
|
|
1052
|
+
index: AggregateIndexDefinitionLike;
|
|
1053
|
+
key: Record<string, unknown>;
|
|
1054
|
+
};
|
|
1055
|
+
declare const selectIndexForAggregate: (indexes: ReadonlyArray<AggregateIndexDefinitionLike>, op: AggregateOp, field: string, requestedWhere: Record<string, unknown> | undefined) => undefined | {
|
|
1056
|
+
index: AggregateIndexDefinitionLike;
|
|
1057
|
+
key: Record<string, unknown>;
|
|
1058
|
+
};
|
|
1059
|
+
declare const selectIndexForGroupBy: (indexes: ReadonlyArray<AggregateIndexDefinitionLike>, op: AggregateOp, field: string | undefined, by: ReadonlyArray<string>, requestedWhere: Record<string, unknown> | undefined) => undefined | {
|
|
1060
|
+
index: AggregateIndexDefinitionLike;
|
|
1061
|
+
partial: Record<string, unknown>;
|
|
1062
|
+
};
|
|
1043
1063
|
declare const AUDIT_LOG_TABLE = "__lunora_audit__";
|
|
1044
1064
|
interface AuditEntry {
|
|
1045
1065
|
detail?: Record<string, unknown>;
|
|
@@ -1530,6 +1550,7 @@ declare const ADMIN_FUNCTIONS: {
|
|
|
1530
1550
|
readonly clearCapturedMail: "__lunora_admin__:clearCapturedMail";
|
|
1531
1551
|
readonly clearQueueMessages: "__lunora_admin__:clearQueueMessages";
|
|
1532
1552
|
readonly clearTable: "__lunora_admin__:clearTable";
|
|
1553
|
+
readonly createAdminToken: "__lunora_admin__:createAdminToken";
|
|
1533
1554
|
readonly createWorkflowInstance: "__lunora_admin__:createWorkflowInstance";
|
|
1534
1555
|
readonly deleteRows: "__lunora_admin__:deleteRows";
|
|
1535
1556
|
readonly describeTable: "__lunora_admin__:describeTable";
|
|
@@ -1565,6 +1586,7 @@ declare const ADMIN_FUNCTIONS: {
|
|
|
1565
1586
|
readonly getWorkflowInstanceStatus: "__lunora_admin__:getWorkflowInstanceStatus";
|
|
1566
1587
|
readonly ignoreIssue: "__lunora_admin__:ignoreIssue";
|
|
1567
1588
|
readonly importShard: "__lunora_admin__:importShard";
|
|
1589
|
+
readonly listAdminTokens: "__lunora_admin__:listAdminTokens";
|
|
1568
1590
|
readonly listFlags: "__lunora_admin__:listFlags";
|
|
1569
1591
|
readonly listReactors: "__lunora_admin__:listReactors";
|
|
1570
1592
|
readonly listQueues: "__lunora_admin__:listQueues";
|
|
@@ -1587,6 +1609,7 @@ declare const ADMIN_FUNCTIONS: {
|
|
|
1587
1609
|
readonly replayQueueMessage: "__lunora_admin__:replayQueueMessage";
|
|
1588
1610
|
readonly retryOutboxEntry: "__lunora_admin__:retryOutboxEntry";
|
|
1589
1611
|
readonly resolveIssue: "__lunora_admin__:resolveIssue";
|
|
1612
|
+
readonly revokeAdminToken: "__lunora_admin__:revokeAdminToken";
|
|
1590
1613
|
readonly rlsPolicies: "__lunora_admin__:rlsPolicies";
|
|
1591
1614
|
readonly schemaHistory: "__lunora_admin__:schemaHistory";
|
|
1592
1615
|
readonly schemaVersion: "__lunora_admin__:schemaVersion";
|
|
@@ -1601,6 +1624,7 @@ declare const ADMIN_FUNCTIONS: {
|
|
|
1601
1624
|
readonly storageReferences: "__lunora_admin__:storageReferences";
|
|
1602
1625
|
readonly storageRules: "__lunora_admin__:storageRules";
|
|
1603
1626
|
readonly studioFeatures: "__lunora_admin__:studioFeatures";
|
|
1627
|
+
readonly verifyAdminToken: "__lunora_admin__:verifyAdminToken";
|
|
1604
1628
|
readonly writeRow: "__lunora_admin__:writeRow";
|
|
1605
1629
|
};
|
|
1606
1630
|
interface TableInfo {
|
|
@@ -2785,4 +2809,4 @@ declare const backfillVectorIndexes: (sql: SqlExec, targets: ReadonlyArray<Vecto
|
|
|
2785
2809
|
ordered: OrderedAfterWrites;
|
|
2786
2810
|
restart?: boolean;
|
|
2787
2811
|
}) => Promise<VectorBackfillProgress>;
|
|
2788
|
-
export { ADMIN_FUNCTIONS, ADMIN_FUNCTION_PREFIX, AGGREGATE_SQL_FUNCTION, AGG_COUNT, AGG_KEY, AGG_VALUE, AUDIT_LOG_TABLE, type AdvisorProcedure, type AdvisorProceduresResult, type AdvisoriesResult, type AdvisoryFinding, type AggregateIndexDefinitionLike, type AggregateOp, type AggregateOptions, type AggregateResult, type AggregateTally, type AppendAuditEntry, type ApplyOnDeleteOptions, type AuditEntry, type AuditLogResult, BIGINT_KEY_DIGITS, type BroadcastDelta, CDC_LOG_TABLE, CDC_LOG_TABLE_SEQ_INDEX, CDC_META_TABLE, CLIENT_WATERMARK_TABLE, COMMIT_SEQ_FIELD, COMMIT_SEQ_TABLE, CURSOR_PREFIX, type CacheEntry, type CapturedMailRow, type CdcArchiveScope, type CdcChange, type CdcChangeKey, type ChangedKeys, type Clock, type ColumnMeta, type ColumnMetaLike, CompanionMemo, type CompanionSync, type CompanionSyncDeps, ConflictError, type ConflictKind, type CountArgs, CountRlsUnsupportedError, type CreateWorkflowInstanceResult, type CrossShardReadArgs, type CtxDbOptions, DATA_MIGRATION_STATE_TABLE, DEFAULT_FANOUT_TOPIC_LIMIT, DEFAULT_MAX_RELATION_KEYS, DEFAULT_MAX_RELAYS, DEFAULT_PROMOTION_THRESHOLDS, DEFAULT_TRANSACTION_LIMITS, DOC_COLUMN, type DataMigrationDocument, type DataMigrationLike, type DataMigrationTransform, type DatabaseWriterLike, type DependencyTracker, type DeployInfo, type DurableAttachDecision, type DurableStreamAttach, type DurableStreamRun, DurableStreamRunner, type DurableStreamSink, type ExportRow, type ExportShardAdminArgs, type ExportShardArgs, type ExternalSourceDiffResult, type ExternalSourceLike, FLAGS_FUNCTION_PREFIX, type FacetColumnOptions, type FacetColumnResult, type FacetValue, type FanOutBudget, type FanoutMetricsResult, type FanoutPathCounters, type FanoutTopicStat, type FieldOperators, type FilterClause, type FilterOperator, type FlagEvaluation, type FlagsResult, type FtsWriteOptions, type FunctionCallStat, type FunctionScanAttribution, type FunctionStatsResult, GEO_DEFAULT_PRECISION, GLOBAL_SHAPE_SNAPSHOT_TABLE, type GeoBoundingBox, type GeoFilterBuilderLike, type GeoIndexDefinitionLike, type GeoPoint, type GeoScoredDocument, type GlobalPollCounters, GlobalPollTick, type GroupByEntry, type GroupByOptions, type GuardableSchema$1 as GuardableSchema, IDEMPOTENCY_TABLE, type IdGenerator, type IdempotentRecord, type ImportConflictMode, type ImportError, type ImportRow, type ImportShardAdminArgs, type ImportShardArgs, type ImportShardResult, type IncrementalMaterializeResult, type IndexDefinitionLike, type IndexKeyEntry, type IndexRangeBuilderLike, type KeyRange, type KeyedRelationWriteInfo, type LifecycleDispatchInfo, type LifecycleEvent, type LiveSocketControlCall, MAIL_RETENTION, MAIL_TABLE, MAX_DURABLE_STREAM_BYTES, MAX_DURABLE_STREAM_CHUNKS, MAX_PAGE_SIZE, MAX_SQL_ROWS, type MaskColumnMetadata, type MaskPoliciesResult, type MaterializeResult, type MigrationDirection, type MigrationRunResult, type MigrationStatus, type MigrationStatusRow, type MutationDelta, type NestedWith, NotFoundError, NotUniqueError, type NullPlacement, type OnDeleteActionLike, type OrderByClause, type OrderByInput, type OrderKey, type OrderKeyConstraints, OwnerRelay, type OwnerRelayFrame, type PaginationOptions, type PatchVerifier, type PatchWriteOptions, type PitrBookmarkResult, type PitrRestoreArgs, type PitrRestoreResult, type PitrStorage, type PokeFrameMeta, type PromotionState, type PromotionThresholds, QUEUE_TABLE, type QueryArgs, type QueryPage, type QueryPlan, type QueueMessageOutcome, type QueueMessageRow, type QueueMetadata, type QueuesResult, RANK_TIEBREAK, REACTOR_STATE_TABLE, RELATED_DEFAULT_LIMIT, RELATED_DEPTH_DECAY, RELATED_MAX_DEPTH, RELATED_MAX_LIMIT, RELATION_EXISTS_KEY, RELATION_FUNCTION_PREFIX, RELAY_SIGNATURE_HEADER, REPROJECTION_MIGRATION_PREFIX, RLS_UNWRAP_SYMBOL, type RangeOperandType, type RankBeforeOptions, type RankBeforeResult, type RankDirection, type RankIndexDefinitionLike, type RankOptions, type RankPage, type RankPageComputation, type RankPageDeps, type RankPageOptions, type RankPageRow, type RankPageRowKey, type RankResult, type RankSortKeyLike, ReactiveCache, type ReactiveCacheOptions, type ReactorDispatchResult, type ReactorMetadata, type ReactorState, type ReactorStats, type ReactorsResult, type ReadFootprint, type ReadHook, type ReadTablePageOptions, type RecordMailInput, type RecordQueueMessageInput, type RelatedDirection, type RelatedNode, type RelatedOptions, type RelatedPage, type RelatedStart, type RelatedStartReference, type RelationDefinitionLike, type RelationEdge, type RelationExistsMarker, type RelationGraphReader, type RelationWriteInfo, type RelationWriteMap, type RelayAttach, type RelayDetach, type RelayFrame, type RelayHost, RelayMember, type RelayPokeDelivery, type RelayRoomEvent, type RelayRoomVerdict, type RelayShapePoke, type RelayShapeSeed, type RelayShapeSubscribe, type RelayShapeUnsubscribe, type RenderedSql, type ReplicaFollowerHost, type ReplicaOwnerHost, type ReplicaReadiness, type ResolveRelationPredicatesOptions, type ResolveWithOptions, type ResolveWithResult, type ResolvedShape, type RestrictableQueryOptions, type RlsPoliciesResult, type RlsPolicyMetadata, RlsRequiredError, type RlsRoleMetadata, type RpcRequest, type RunDataMigrationOptions, type RunTriggersOptions, SCAN_DEP, SCHEDULE_OUTBOX_TABLE, SCHEMA_HISTORY_MAX_VERSIONS, SEARCH_STATE_TABLE, SHAPE_POKE_CURSOR_TABLE, type SchedulableWorkflowReferenceLike, type ScheduleOutbox, type ScheduleOutboxEntry, type ScheduleOutboxEnvelope, type ScheduleOutboxRow, type ScheduledFunctionDoc, type SchedulerLike, type SchemaLike, type ScoredDocument, type SearchBackfillProgress, type SearchFilterBuilderLike, type SearchIndexDefinitionLike, type SearchScoredDocument, type SelectMatchingIdsOptions, type ServerDefaultContextLike, type SettingEntry, type SettingKind, type SettingsResult, ShapeDiffCache, type ShapePokeCursorRow, type ShapePokePart, type ShapeProbeCounters, type ShapeRow, type ShapeRowOp, type ShapeSubscriptionQuery, type ShardRankPageResult, ShardRunner, type ShardRunnerOptions, type ShardSiblingHost, type ShardSocketLike, type SocketAttachment, type SortDirection, type SourceClientLike, type SourceCursorLike, type SourceRefresh, type SqlConsoleResult, type SqlCursor, type SqlEngine, type SqlExec, type SqlLintResult, type StorageMetadata, type StorageReference, type StorageReferenceResult, type StorageRuleMetadata, type StorageRulesResult, type StudioFeaturesResult, type SubscriptionConnection, type SubscriptionEnvelope, type SubscriptionIdentity, type SubscriptionInfo, type SubscriptionQuery, type SubscriptionReadFootprint, type SubscriptionsResult, type SystemDatabaseReader, type SystemDoc, type SystemQuery, type SystemReaderOptions, type SystemReaderSchedulerLike, type SystemReaderStorageLike, type SystemTableName, type TableColumnsResult, type TableDefinitionLike, type TableIndexInfo, type TableIndexesResult, type TableInfo, type TablePage, type TableReaderLike, type TablesColumnsResult, type TablesIndexesResult, type ThroughRelationWriteInfo, type TransactionHeadroom, TransactionHeadroomTracker, type TransactionLimitKind, type TransactionLimitWarning, type TransactionLimits, type TransactionSqlLike, type TriggerContextLike, type TriggerDefinitionLike, type TriggerEventLike, type TriggerOpLike, type TriggerTimingLike, type TtlSweepSpec, UNVOUCHABLE_DEP, VECTOR_BACKFILL_MAX_PAGES, type ValidatorLike, type VectorBackfillProgress, WORKERD_SQLITE_LIMITS, type WhereFilter, type WhereInput, type WhereSqlStrategy, type WithInput, type WorkflowInstanceState, type WorkflowInstanceStatusResult, type WorkflowMetadata, type WorkflowsResult, type WriteEvent, type WriteHook, advanceClientWatermark, aggUpsertSql, aggregateSqlFunction, aggregateTableName, allocateCommitSeq, appendAuditEntry, appendCdcChange, appendStreamChunk, applyCdcChanges, applyInsertDefaults, applyOnDelete, applySelect, archiveCdcSegment, armRestore, assertFlatPredicate, assertNoExplicitUndefined, assertPatchAllowed, assertReadonly, assertShapeShardable, assertStorableRowId, assertValidClientId, awaitWsDrain, backfillAggregateIndexes, backfillRankIndexes, backfillSearchIndexes, backfillSearchIndexesForTable, backfillVectorIndexes, bigintSqlKey, boundingBoxCenter, boundingBoxGeohashes, buildIndexRange, buildPokeFrames, buildReprojectionMigration, buildSeekBeforeWhere, buildSeekWhere, buildSettings, buildShapeDiff, bumpCdcEpoch, cdcArchiveRewound, cdcCanVouchFor, cdcForkedError, cdcSeqLeavingRows, cdcTouchesTables, cdcTrimmedError, claimStreamRun, clampPromotionThresholds, clearCapturedMail, clearCompanionSignatures, clearMemoryTables, clearQueueMessages, coerceAggregateNumber, compactCdcDocs, compileWhereSql, composeReadPredicate, computeRankPage, containsRelationPredicate, countLegacyRows, coveringGeohashes, createCompanionSync, createDependencyTracker, createFanoutCounters, createGlobalPollCounters, createIndexSql, createReadFootprint, createRelayLink, createReplicaLink, createShapeDiffCache, createShapeProbeCounters, createShardCtxDb, createSystemReader, cursorBelowRetainedFloor, decideDurableAttach, decodeBigintSqlKey, decodeCursor, decodeFloat64SqlKey, deferScheduleOutbox, deleteGlobalShapeSnapshot, deleteGlobalShapeSnapshotsForConnection, deleteShapePokeCursor, deleteShapePokeCursorsForConnection, deleteStreamRun, depKey, deriveRelationEdges, describeRelationWrites, diffExternalSource, diffGlobalMembership, distinctValues, dropScheduleOutbox, encodeAggregateKey, encodeCursor, encodeGeohash, encodePartitionKey, encodeRowsPatch, ensureAuditTable, ensureMailTable, envOptionalPositiveInt, envPositiveInt, equalityPinnedFields, exportShardRows, facetColumn, fanOutScalarCounts, findRelated, findStorageReferences, finishStreamRun, float64SqlKey, foldAggregateTally, forgetScheduleOutbox, ftsCompanionDdl, ftsPurgeDocument, ftsRowidMapName, ftsUnmappedPage, ftsWriteDocument, gateReplicaDispatch, geoTableName, globalShapeReadKey, groupUnmappedRows, guardWriter, handleReplicaControl, hasScheduleOutboxEntry, hasTrigger, haversineMeters, importShardRows, indexKeysForRow, isDevEnvironment, isFtsAvailable, isInternalTableName, isLossyBody, isMemoryTable, isPushableWhere, isRelationPredicate, isSoftDeleted, isSourceDue, isTtlExpired, isVacuousFilterClause, jsonPath, jsonPathSql, keysTouchRanges, liftSourceId, lintReadonlySql, listReactorStates, listTables, markUnvouchableReads, matchesRankStaticWhere, matchesStaticWhere, materializeExternalRows, materializeExternalRowsIncremental, memoryTableNames, mergeChangedKeys, mergeWhere, migrateCdcLog, migrateCdcMeta, migrateClientWatermark, migrateCommitSeq, migrateDurableStreams, migrateGlobalShapeSnapshot, migrateIdempotency, migrateReactorState, migrateScheduleOutbox, migrateSearchState, migrateShapePokeCursor, minCdcReplayableSeq, minCdcSeq, minShapePokeCursor, nextPromotionState, nextTtlExpiry, normalizeCountArgument, normalizeIdStructurally, normalizeOrderKeys, normalizeSourceDocument, normalizeSourceValue, nullsFirstOf, nullsOrderSuffix, operatorFields, param, parkScheduleOutbox, parseExportShardArgs, parseImportShardArgs, patchDependsOnRow, planAggregateLookup, pointInBoundingBox, probeScheduleOutbox, projectColumns, pullExternalSourceIncrementalTick, pullExternalSourceTick, qualifiedJsonPath, qualifiedJsonPathSql, quoteIdentifier, rankKeyFromDocument as rankKeyFromDoc, rankPivotConditionSql, rankTableName, reactiveCacheKey, reactorNeedsRun, readAggregateValue, readArchivedCdcChanges, readAuditLog, readBookmark, readCapturedMail, readCdcArchivedThrough, readCdcChangeKeys, readCdcChanges, readCdcCursor, readCdcEpoch, readClientWatermark, readCommitSeq, readDeployInfo, readDueScheduleOutbox, readDueScheduleOutboxEntry, readExternalSourceBaseline, readGlobalShapeSnapshot, readIdempotent, readMigrationStatus, readPatchField, readQueueMessageById, readQueueMessages, readReactorState, readScheduleOutbox, readScheduleOutboxState, readSchemaHistory, readSchemaVersion, readSearchBackfillState, readShapePokeCursor, readStreamChunks, readStreamRun, readTablePage, recordCapturedMail, recordChangedKeys, recordFanoutPass, recordGlobalPollPass, recordQueueMessages, recordScheduleOutbox, recordSchemaVersion, recordShapeProbePass, relationHooks, relayCountFor, renderSql, reprojectableFields, reprojectionMigrationId, reprojectionTables, requeueScheduleOutbox, resolvePatch, resolveRankPartition, resolveRankSeekTuple, resolveRelationPredicates, resolveWith, rowToDocument, runDataMigration, runDrizzle, runExternalSourceTick, runReadonlySql, runRowValidators, runShardMigrations, runSocketPool, runSql, runTriggers, selectExpiredIds, selectExportTables, selectIndexForAggregate, selectIndexForCount, selectIndexForGroupBy, selectMatchingIds, selectShapeMembers, selectShapeRows, serializeSqlValue, serverInList, shapeRoutingKey, siblingSecretOf, signSiblingBody, softDeleteScope, sortColumnName, sqliteInList, stripReservedPatchFields, stubByName, subscriptionFrames, subscriptionListDeltas, summarizeFanoutTopics, summarizeSubscriptions, tableColumns, tableFromDepKey, throwingScheduler, tiebreakDirectionFor, trimCdcChanges, trimIdempotent, trimScheduleOutbox, trimStreamRuns, tryRowToDocument, trySendFrame, unionAll, uniqueIndexFields, validateImportRow, verifySiblingBody, whereFilter, whereOfFilter, writeCdcArchivedThrough, writeGlobalShapeSnapshot, writeIdempotent, writeReactorState, writeSearchBackfillState, writeShapePokeCursor, writeShapePokeCursors, writeTouchesMemo };
|
|
2812
|
+
export { ADMIN_FUNCTIONS, ADMIN_FUNCTION_PREFIX, ADMIN_TOKEN_TABLE, AGGREGATE_SQL_FUNCTION, AGG_COUNT, AGG_KEY, AGG_VALUE, AUDIT_LOG_TABLE, type AdminTokenSummary, type AdvisorProcedure, type AdvisorProceduresResult, type AdvisoriesResult, type AdvisoryFinding, type AggregateIndexDefinitionLike, type AggregateOp, type AggregateOptions, type AggregateResult, type AggregateTally, type AppendAuditEntry, type ApplyOnDeleteOptions, type AuditEntry, type AuditLogResult, BIGINT_KEY_DIGITS, type BroadcastDelta, CDC_LOG_TABLE, CDC_LOG_TABLE_SEQ_INDEX, CDC_META_TABLE, CLIENT_WATERMARK_TABLE, COMMIT_SEQ_FIELD, COMMIT_SEQ_TABLE, CURSOR_PREFIX, type CacheEntry, type CapturedMailRow, type CdcArchiveScope, type CdcChange, type CdcChangeKey, type ChangedKeys, type Clock, type ColumnMeta, type ColumnMetaLike, CompanionMemo, type CompanionSync, type CompanionSyncDeps, ConflictError, type ConflictKind, type CountArgs, CountRlsUnsupportedError, type CreateWorkflowInstanceResult, type CrossShardReadArgs, type CtxDbOptions, DATA_MIGRATION_STATE_TABLE, DEFAULT_FANOUT_TOPIC_LIMIT, DEFAULT_MAX_RELATION_KEYS, DEFAULT_MAX_RELAYS, DEFAULT_PROMOTION_THRESHOLDS, DEFAULT_TRANSACTION_LIMITS, DOC_COLUMN, type DataMigrationDocument, type DataMigrationLike, type DataMigrationTransform, type DatabaseWriterLike, type DependencyTracker, type DeployInfo, type DurableAttachDecision, type DurableStreamAttach, type DurableStreamRun, DurableStreamRunner, type DurableStreamSink, type ExportRow, type ExportShardAdminArgs, type ExportShardArgs, type ExternalSourceDiffResult, type ExternalSourceLike, FLAGS_FUNCTION_PREFIX, type FacetColumnOptions, type FacetColumnResult, type FacetValue, type FanOutBudget, type FanoutMetricsResult, type FanoutPathCounters, type FanoutTopicStat, type FieldOperators, type FilterClause, type FilterOperator, type FlagEvaluation, type FlagsResult, type FtsWriteOptions, type FunctionCallStat, type FunctionScanAttribution, type FunctionStatsResult, GEO_DEFAULT_PRECISION, GLOBAL_SHAPE_SNAPSHOT_TABLE, type GeoBoundingBox, type GeoFilterBuilderLike, type GeoIndexDefinitionLike, type GeoPoint, type GeoScoredDocument, type GlobalPollCounters, GlobalPollTick, type GroupByEntry, type GroupByOptions, type GuardableSchema$1 as GuardableSchema, IDEMPOTENCY_TABLE, type IdGenerator, type IdempotentRecord, type ImportConflictMode, type ImportError, type ImportRow, type ImportShardAdminArgs, type ImportShardArgs, type ImportShardResult, type IncrementalMaterializeResult, type IndexDefinitionLike, type IndexKeyEntry, type IndexRangeBuilderLike, type KeyRange, type KeyedRelationWriteInfo, type LifecycleDispatchInfo, type LifecycleEvent, type LiveSocketControlCall, MAIL_RETENTION, MAIL_TABLE, MAX_DURABLE_STREAM_BYTES, MAX_DURABLE_STREAM_CHUNKS, MAX_PAGE_SIZE, MAX_SQL_ROWS, type MaskColumnMetadata, type MaskPoliciesResult, type MaterializeResult, type MigrationDirection, type MigrationRunResult, type MigrationStatus, type MigrationStatusRow, type MutationDelta, type NestedWith, NotFoundError, NotUniqueError, type NullPlacement, type OnDeleteActionLike, type OrderByClause, type OrderByInput, type OrderKey, type OrderKeyConstraints, OwnerRelay, type OwnerRelayFrame, type PaginationOptions, type PatchVerifier, type PatchWriteOptions, type PitrBookmarkResult, type PitrRestoreArgs, type PitrRestoreResult, type PitrStorage, type PokeFrameMeta, type PromotionState, type PromotionThresholds, QUEUE_TABLE, type QueryArgs, type QueryPage, type QueryPlan, type QueueMessageOutcome, type QueueMessageRow, type QueueMetadata, type QueuesResult, RANK_TIEBREAK, REACTOR_STATE_TABLE, RELATED_DEFAULT_LIMIT, RELATED_DEPTH_DECAY, RELATED_MAX_DEPTH, RELATED_MAX_LIMIT, RELATION_EXISTS_KEY, RELATION_FUNCTION_PREFIX, RELAY_SIGNATURE_HEADER, REPROJECTION_MIGRATION_PREFIX, RLS_UNWRAP_SYMBOL, type RangeOperandType, type RankBeforeOptions, type RankBeforeResult, type RankDirection, type RankIndexDefinitionLike, type RankOptions, type RankPage, type RankPageComputation, type RankPageDeps, type RankPageOptions, type RankPageRow, type RankPageRowKey, type RankResult, type RankSortKeyLike, ReactiveCache, type ReactiveCacheOptions, type ReactorDispatchResult, type ReactorMetadata, type ReactorState, type ReactorStats, type ReactorsResult, type ReadFootprint, type ReadHook, type ReadTablePageOptions, type RecordMailInput, type RecordQueueMessageInput, type RelatedDirection, type RelatedNode, type RelatedOptions, type RelatedPage, type RelatedStart, type RelatedStartReference, type RelationDefinitionLike, type RelationEdge, type RelationExistsMarker, type RelationGraphReader, type RelationWriteInfo, type RelationWriteMap, type RelayAttach, type RelayDetach, type RelayFrame, type RelayHost, RelayMember, type RelayPokeDelivery, type RelayRoomEvent, type RelayRoomVerdict, type RelayShapePoke, type RelayShapeSeed, type RelayShapeSubscribe, type RelayShapeUnsubscribe, type RenderedSql, type ReplicaFollowerHost, type ReplicaOwnerHost, type ReplicaReadiness, type ResolveRelationPredicatesOptions, type ResolveWithOptions, type ResolveWithResult, type ResolvedShape, type RestrictableQueryOptions, type RlsPoliciesResult, type RlsPolicyMetadata, RlsRequiredError, type RlsRoleMetadata, type RpcRequest, type RunDataMigrationOptions, type RunTriggersOptions, SCAN_DEP, SCHEDULE_OUTBOX_TABLE, SCHEMA_HISTORY_MAX_VERSIONS, SEARCH_STATE_TABLE, SHAPE_POKE_CURSOR_TABLE, type SchedulableWorkflowReferenceLike, type ScheduleOutbox, type ScheduleOutboxEntry, type ScheduleOutboxEnvelope, type ScheduleOutboxRow, type ScheduledFunctionDoc, type SchedulerLike, type SchemaLike, type ScoredDocument, type SearchBackfillProgress, type SearchFilterBuilderLike, type SearchIndexDefinitionLike, type SearchScoredDocument, type SelectMatchingIdsOptions, type ServerDefaultContextLike, type SettingEntry, type SettingKind, type SettingsResult, ShapeDiffCache, type ShapePokeCursorRow, type ShapePokePart, type ShapeProbeCounters, type ShapeRow, type ShapeRowOp, type ShapeSubscriptionQuery, type ShardRankPageResult, ShardRunner, type ShardRunnerOptions, type ShardSiblingHost, type ShardSocketLike, type SocketAttachment, type SortDirection, type SourceClientLike, type SourceCursorLike, type SourceRefresh, type SqlConsoleResult, type SqlCursor, type SqlEngine, type SqlExec, type SqlLintResult, type StorageMetadata, type StorageReference, type StorageReferenceResult, type StorageRuleMetadata, type StorageRulesResult, type StudioFeaturesResult, type SubscriptionConnection, type SubscriptionEnvelope, type SubscriptionIdentity, type SubscriptionInfo, type SubscriptionQuery, type SubscriptionReadFootprint, type SubscriptionsResult, type SystemDatabaseReader, type SystemDoc, type SystemQuery, type SystemReaderOptions, type SystemReaderSchedulerLike, type SystemReaderStorageLike, type SystemTableName, type TableColumnsResult, type TableDefinitionLike, type TableIndexInfo, type TableIndexesResult, type TableInfo, type TablePage, type TableReaderLike, type TablesColumnsResult, type TablesIndexesResult, type ThroughRelationWriteInfo, type TransactionHeadroom, TransactionHeadroomTracker, type TransactionLimitKind, type TransactionLimitWarning, type TransactionLimits, type TransactionSqlLike, type TriggerContextLike, type TriggerDefinitionLike, type TriggerEventLike, type TriggerOpLike, type TriggerTimingLike, type TtlSweepSpec, UNVOUCHABLE_DEP, VECTOR_BACKFILL_MAX_PAGES, type ValidatorLike, type VectorBackfillProgress, WORKERD_SQLITE_LIMITS, type WhereFilter, type WhereInput, type WhereSqlStrategy, type WithInput, type WorkflowInstanceState, type WorkflowInstanceStatusResult, type WorkflowMetadata, type WorkflowsResult, type WriteEvent, type WriteHook, adminTokenExists, advanceClientWatermark, aggUpsertSql, aggregateSqlFunction, aggregateTableName, allocateCommitSeq, appendAuditEntry, appendCdcChange, appendStreamChunk, applyCdcChanges, applyInsertDefaults, applyOnDelete, applySelect, archiveCdcSegment, armRestore, assertFlatPredicate, assertNoExplicitUndefined, assertPatchAllowed, assertReadonly, assertShapeShardable, assertStorableRowId, assertValidClientId, awaitWsDrain, backfillAggregateIndexes, backfillRankIndexes, backfillSearchIndexes, backfillSearchIndexesForTable, backfillVectorIndexes, bigintSqlKey, boundingBoxCenter, boundingBoxGeohashes, buildIndexRange, buildPokeFrames, buildReprojectionMigration, buildSeekBeforeWhere, buildSeekWhere, buildSettings, buildShapeDiff, bumpCdcEpoch, cdcArchiveRewound, cdcCanVouchFor, cdcForkedError, cdcSeqLeavingRows, cdcTouchesTables, cdcTrimmedError, claimStreamRun, clampPromotionThresholds, clearCapturedMail, clearCompanionSignatures, clearMemoryTables, clearQueueMessages, coerceAggregateNumber, compactCdcDocs, compileWhereSql, composeReadPredicate, computeRankPage, containsRelationPredicate, countLegacyRows, coveringGeohashes, createAdminTokenRecord, createCompanionSync, createDependencyTracker, createFanoutCounters, createGlobalPollCounters, createIndexSql, createReadFootprint, createRelayLink, createReplicaLink, createShapeDiffCache, createShapeProbeCounters, createShardCtxDb, createSystemReader, cursorBelowRetainedFloor, decideDurableAttach, decodeBigintSqlKey, decodeCursor, decodeFloat64SqlKey, deferScheduleOutbox, deleteGlobalShapeSnapshot, deleteGlobalShapeSnapshotsForConnection, deleteShapePokeCursor, deleteShapePokeCursorsForConnection, deleteStreamRun, depKey, deriveRelationEdges, describeRelationWrites, diffExternalSource, diffGlobalMembership, distinctValues, dropScheduleOutbox, encodeAggregateKey, encodeCursor, encodeGeohash, encodePartitionKey, encodeRowsPatch, ensureAuditTable, ensureMailTable, envOptionalPositiveInt, envPositiveInt, equalityPinnedFields, exportShardRows, facetColumn, fanOutScalarCounts, findRelated, findStorageReferences, finishStreamRun, float64SqlKey, foldAggregateTally, forgetScheduleOutbox, ftsCompanionDdl, ftsPurgeDocument, ftsRowidMapName, ftsUnmappedPage, ftsWriteDocument, gateReplicaDispatch, geoTableName, globalShapeReadKey, groupUnmappedRows, guardWriter, handleReplicaControl, hasScheduleOutboxEntry, hasTrigger, haversineMeters, importShardRows, indexKeysForRow, isDevEnvironment, isFtsAvailable, isInternalTableName, isLossyBody, isMemoryTable, isPushableWhere, isRelationPredicate, isSoftDeleted, isSourceDue, isTtlExpired, isVacuousFilterClause, jsonPath, jsonPathSql, keysTouchRanges, liftSourceId, lintReadonlySql, listAdminTokens, listReactorStates, listTables, markUnvouchableReads, matchesRankStaticWhere, matchesStaticWhere, materializeExternalRows, materializeExternalRowsIncremental, memoryTableNames, mergeChangedKeys, mergeWhere, migrateCdcLog, migrateCdcMeta, migrateClientWatermark, migrateCommitSeq, migrateDurableStreams, migrateGlobalShapeSnapshot, migrateIdempotency, migrateReactorState, migrateScheduleOutbox, migrateSearchState, migrateShapePokeCursor, minCdcReplayableSeq, minCdcSeq, minShapePokeCursor, nextPromotionState, nextTtlExpiry, normalizeCountArgument, normalizeIdStructurally, normalizeOrderKeys, normalizeSourceDocument, normalizeSourceValue, nullsFirstOf, nullsOrderSuffix, operatorFields, param, parkScheduleOutbox, parseExportShardArgs, parseImportShardArgs, patchDependsOnRow, planAggregateLookup, pointInBoundingBox, probeScheduleOutbox, projectColumns, pullExternalSourceIncrementalTick, pullExternalSourceTick, qualifiedJsonPath, qualifiedJsonPathSql, quoteIdentifier, rankKeyFromDocument as rankKeyFromDoc, rankPivotConditionSql, rankTableName, reactiveCacheKey, reactorNeedsRun, readAggregateValue, readArchivedCdcChanges, readAuditLog, readBookmark, readCapturedMail, readCdcArchivedThrough, readCdcChangeKeys, readCdcChanges, readCdcCursor, readCdcEpoch, readClientWatermark, readCommitSeq, readDeployInfo, readDueScheduleOutbox, readDueScheduleOutboxEntry, readExternalSourceBaseline, readGlobalShapeSnapshot, readIdempotent, readMigrationStatus, readPatchField, readQueueMessageById, readQueueMessages, readReactorState, readScheduleOutbox, readScheduleOutboxState, readSchemaHistory, readSchemaVersion, readSearchBackfillState, readShapePokeCursor, readStreamChunks, readStreamRun, readTablePage, recordCapturedMail, recordChangedKeys, recordFanoutPass, recordGlobalPollPass, recordQueueMessages, recordScheduleOutbox, recordSchemaVersion, recordShapeProbePass, relationHooks, relayCountFor, renderSql, reprojectableFields, reprojectionMigrationId, reprojectionTables, requeueScheduleOutbox, resolvePatch, resolveRankPartition, resolveRankSeekTuple, resolveRelationPredicates, resolveWith, revokeAdminTokenRecord, rowToDocument, runDataMigration, runDrizzle, runExternalSourceTick, runReadonlySql, runRowValidators, runShardMigrations, runSocketPool, runSql, runTriggers, selectExpiredIds, selectExportTables, selectIndexForAggregate, selectIndexForCount, selectIndexForGroupBy, selectMatchingIds, selectShapeMembers, selectShapeRows, serializeSqlValue, serverInList, shapeRoutingKey, siblingSecretOf, signSiblingBody, softDeleteScope, sortColumnName, sqliteInList, stripReservedPatchFields, stubByName, subscriptionFrames, subscriptionListDeltas, summarizeFanoutTopics, summarizeSubscriptions, tableColumns, tableFromDepKey, throwingScheduler, tiebreakDirectionFor, trimCdcChanges, trimIdempotent, trimScheduleOutbox, trimStreamRuns, tryRowToDocument, trySendFrame, unionAll, uniqueIndexFields, validateImportRow, verifyAdminTokenDigest, verifySiblingBody, whereFilter, whereOfFilter, writeCdcArchivedThrough, writeGlobalShapeSnapshot, writeIdempotent, writeReactorState, writeSearchBackfillState, writeShapePokeCursor, writeShapePokeCursors, writeTouchesMemo };
|
package/dist/index.mjs
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{exportShardRows as o,importShardRows as a,parseExportShardArgs as t,parseImportShardArgs as s,selectExportTables as i,validateImportRow as l}from"./packem_shared/exportShardRows-CZh4wrvI.mjs";import{AGGREGATE_SQL_FUNCTION as d,aggregateSqlFunction as c,matchesStaticWhere as m,normalizeCountArgument as p,throwingScheduler as u}from"./packem_shared/AGGREGATE_SQL_FUNCTION-C_ZipS9R.mjs";import{aggregateTableName as f,coerceAggregateNumber as x,encodeAggregateKey as h,foldAggregateTally as E,readAggregateValue as T}from"./packem_shared/aggregateTableName-B_CtIQCS.mjs";import{CountRlsUnsupportedError as A,mergeWhere as C,planAggregateLookup as g,selectIndexForAggregate as _,selectIndexForCount as I,selectIndexForGroupBy as b}from"./packem_shared/CountRlsUnsupportedError-BvsDqfO2.mjs";import{AUDIT_LOG_TABLE as O,appendAuditEntry as D,ensureAuditTable as P,readAuditLog as y}from"./packem_shared/AUDIT_LOG_TABLE-BFJ65SRS.mjs";import{NotUniqueError as F,assertNoExplicitUndefined as N,assertStorableRowId as k,assertValidClientId as B,createShardCtxDb as U,normalizeIdStructurally as G,stripReservedPatchFields as w}from"./packem_shared/NotUniqueError-CO-HgL4c.mjs";import{backfillAggregateIndexes as v,backfillRankIndexes as K,backfillSearchIndexes as W,backfillSearchIndexesForTable as X}from"./packem_shared/backfillAggregateIndexes-Pk0KLrfk.mjs";import{CDC_LOG_TABLE as V,CDC_LOG_TABLE_SEQ_INDEX as z,CDC_META_TABLE as Q,appendCdcChange as Y,applyCdcChanges as j,bumpCdcEpoch as J,cdcCanVouchFor as Z,cdcForkedError as $,cdcSeqLeavingRows as ee,cdcTouchesTables as re,cdcTrimmedError as oe,compactCdcDocs as ae,cursorBelowRetainedFloor as te,migrateCdcLog as se,migrateCdcMeta as ie,minCdcReplayableSeq as le,minCdcSeq as ne,readCdcChangeKeys as de,readCdcChanges as ce,readCdcCursor as me,readCdcEpoch as pe,trimCdcChanges as ue}from"./packem_shared/CDC_LOG_TABLE-BFGgqai8.mjs";import{archiveCdcSegment as fe,cdcArchiveRewound as xe,readArchivedCdcChanges as he,readCdcArchivedThrough as Ee,writeCdcArchivedThrough as Te}from"./packem_shared/archiveCdcSegment-Cr8oGLfB.mjs";import{CLIENT_WATERMARK_TABLE as Ae,advanceClientWatermark as Ce,migrateClientWatermark as ge,readClientWatermark as _e}from"./packem_shared/CLIENT_WATERMARK_TABLE-De7z_OHV.mjs";import{COMMIT_SEQ_FIELD as be,COMMIT_SEQ_TABLE as Le,allocateCommitSeq as Oe,migrateCommitSeq as De,readCommitSeq as Pe}from"./packem_shared/COMMIT_SEQ_FIELD-Da1DjGqo.mjs";import{CompanionMemo as Me,clearCompanionSignatures as Fe}from"./packem_shared/CompanionMemo-BXU5vfak.mjs";import{createCompanionSync as ke}from"./packem_shared/createCompanionSync-CEht4hXX.mjs";import{GLOBAL_SHAPE_SNAPSHOT_TABLE as Ue,deleteGlobalShapeSnapshot as Ge,deleteGlobalShapeSnapshotsForConnection as we,migrateGlobalShapeSnapshot as qe,readGlobalShapeSnapshot as ve,writeGlobalShapeSnapshot as Ke}from"./packem_shared/GLOBAL_SHAPE_SNAPSHOT_TABLE-Bb6-aZuH.mjs";import{IDEMPOTENCY_TABLE as Xe,migrateIdempotency as He,readIdempotent as Ve,trimIdempotent as ze,writeIdempotent as Qe}from"./packem_shared/IDEMPOTENCY_TABLE-COrgeP3O.mjs";import{clearMemoryTables as je,isMemoryTable as Je,memoryTableNames as Ze}from"./packem_shared/clearMemoryTables-aMRERF0w.mjs";import{computeRankPage as er,resolveRankSeekTuple as rr}from"./packem_shared/computeRankPage-BZIpATcs.mjs";import{SCHEDULE_OUTBOX_TABLE as ar,deferScheduleOutbox as tr,dropScheduleOutbox as sr,forgetScheduleOutbox as ir,hasScheduleOutboxEntry as lr,migrateScheduleOutbox as nr,parkScheduleOutbox as dr,probeScheduleOutbox as cr,readDueScheduleOutbox as mr,readDueScheduleOutboxEntry as pr,readScheduleOutbox as ur,readScheduleOutboxState as Sr,recordScheduleOutbox as fr,requeueScheduleOutbox as xr,trimScheduleOutbox as hr}from"./packem_shared/SCHEDULE_OUTBOX_TABLE-iyyiSjsO.mjs";import{S as Tr,m as Rr,r as Ar,w as Cr}from"./packem_shared/ctx-db-search-state-CPKPy8N6.mjs";import{SHAPE_POKE_CURSOR_TABLE as _r,deleteShapePokeCursor as Ir,deleteShapePokeCursorsForConnection as br,migrateShapePokeCursor as Lr,minShapePokeCursor as Or,readShapePokeCursor as Dr,writeShapePokeCursor as Pr,writeShapePokeCursors as yr}from"./packem_shared/SHAPE_POKE_CURSOR_TABLE-BGvY3sFI.mjs";import{selectShapeMembers as Fr,selectShapeRows as Nr}from"./packem_shared/selectShapeMembers-Dqx_m7BF.mjs";import{DATA_MIGRATION_STATE_TABLE as Br,readMigrationStatus as Ur,runDataMigration as Gr}from"./packem_shared/DATA_MIGRATION_STATE_TABLE-CFvBS9-M.mjs";import{SCAN_DEP as qr,createDependencyTracker as vr,depKey as Kr,tableFromDepKey as Wr}from"./packem_shared/SCAN_DEP-D7qE3iUe.mjs";import{runDrizzle as Hr,runSql as Vr}from"./packem_shared/runDrizzle-RC09zZrh.mjs";import{A as Qr,a as Yr,b as jr,D as Jr,c as Zr,d as $r,g as eo,i as ro,j as oo,e as ao,q as to,f as so,r as io,t as lo,h as no}from"./packem_shared/do-sql-105TONaE.mjs";import{WORKERD_SQLITE_LIMITS as mo,param as po,renderSql as uo,sqliteInList as So,unionAll as fo}from"./packem_shared/WORKERD_SQLITE_LIMITS-B_4w7tzY.mjs";import{appendStreamChunk as ho,claimStreamRun as Eo,deleteStreamRun as To,finishStreamRun as Ro,migrateDurableStreams as Ao,readStreamChunks as Co,readStreamRun as go,trimStreamRuns as _o}from"./packem_shared/appendStreamChunk-BZYgGE9Y.mjs";import{DurableStreamRunner as bo,MAX_DURABLE_STREAM_BYTES as Lo,MAX_DURABLE_STREAM_CHUNKS as Oo,decideDurableAttach as Do}from"./packem_shared/DurableStreamRunner-MMlV5qKQ.mjs";import{envOptionalPositiveInt as yo,envPositiveInt as Mo}from"./packem_shared/envOptionalPositiveInt-D2pY-c64.mjs";import{diffExternalSource as No}from"./packem_shared/diffExternalSource-B0FZlDoL.mjs";import{liftSourceId as Bo,normalizeSourceDocument as Uo,normalizeSourceValue as Go}from"./packem_shared/liftSourceId-CA3ENhXj.mjs";import{materializeExternalRows as qo,materializeExternalRowsIncremental as vo,readExternalSourceBaseline as Ko,runExternalSourceTick as Wo}from"./packem_shared/materializeExternalRows-CHPRx8fu.mjs";import{isSoftDeleted as Ho,isSourceDue as Vo,pullExternalSourceIncrementalTick as zo,pullExternalSourceTick as Qo}from"./packem_shared/isSoftDeleted-BBWKE0Sm.mjs";import{f as jo,a as Jo,b as Zo,c as $o,d as ea,g as ra}from"./packem_shared/fts-companion-CE3EmIjk.mjs";import{GEO_DEFAULT_PRECISION as aa,boundingBoxCenter as ta,boundingBoxGeohashes as sa,coveringGeohashes as ia,encodeGeohash as la,haversineMeters as na,pointInBoundingBox as da}from"./packem_shared/GEO_DEFAULT_PRECISION-CqpQZ-J_.mjs";import{default as ma}from"./packem_shared/GlobalPollTick-BNK4o-XT.mjs";import{ADMIN_FUNCTIONS as ua,ADMIN_FUNCTION_PREFIX as Sa,DEFAULT_FANOUT_TOPIC_LIMIT as fa,FLAGS_FUNCTION_PREFIX as xa,MAX_PAGE_SIZE as ha,RELATION_FUNCTION_PREFIX as Ea,createFanoutCounters as Ta,createGlobalPollCounters as Ra,createShapeProbeCounters as Aa,facetColumn as Ca,findStorageReferences as ga,isVacuousFilterClause as _a,listTables as Ia,readTablePage as ba,recordFanoutPass as La,recordGlobalPollPass as Oa,recordShapeProbePass as Da,selectMatchingIds as Pa,summarizeFanoutTopics as ya,summarizeSubscriptions as Ma}from"./packem_shared/ADMIN_FUNCTIONS-BMBnudzO.mjs";import{MAIL_RETENTION as Na,MAIL_TABLE as ka,clearCapturedMail as Ba,ensureMailTable as Ua,readCapturedMail as Ga,recordCapturedMail as wa}from"./packem_shared/MAIL_RETENTION-DMolrLYt.mjs";import{NotFoundError as va}from"./packem_shared/NotFoundError-BhF7FeFr.mjs";import{assertPatchAllowed as Wa,operatorFields as Xa,patchDependsOnRow as Ha,readPatchField as Va,resolvePatch as za}from"./packem_shared/assertPatchAllowed-CA_H466g.mjs";import{armRestore as Ya,readBookmark as ja}from"./packem_shared/armRestore-Bu1_8SUa.mjs";import{CURSOR_PREFIX as Za,applySelect as $a,buildSeekBeforeWhere as et,buildSeekWhere as rt,decodeCursor as ot,encodeCursor as at,equalityPinnedFields as tt,normalizeOrderKeys as st,nullsFirstOf as it,nullsOrderSuffix as lt,softDeleteScope as nt,tiebreakDirectionFor as dt,uniqueIndexFields as ct}from"./packem_shared/CURSOR_PREFIX-6offuG6M.mjs";import{QUEUE_TABLE as pt,clearQueueMessages as ut,isLossyBody as St,readQueueMessageById as ft,readQueueMessages as xt,recordQueueMessages as ht}from"./packem_shared/QUEUE_TABLE-C-goXtGd.mjs";import{RANK_TIEBREAK as Tt,encodePartitionKey as Rt,matchesRankStaticWhere as At,rankKeyFromDoc as Ct,rankPivotConditionSql as gt,rankTableName as _t,resolveRankPartition as It,sortColumnName as bt}from"./packem_shared/RANK_TIEBREAK-D3ye2GsL.mjs";import{ReactiveCache as Ot,reactiveCacheKey as Dt}from"./packem_shared/ReactiveCache-5XPk8qfW.mjs";import{REACTOR_STATE_TABLE as yt,listReactorStates as Mt,migrateReactorState as Ft,reactorNeedsRun as Nt,readReactorState as kt,writeReactorState as Bt}from"./packem_shared/REACTOR_STATE_TABLE-D2Mn204f.mjs";import{UNVOUCHABLE_DEP as Gt,createReadFootprint as wt,markUnvouchableReads as qt}from"./packem_shared/UNVOUCHABLE_DEP-Ds9gxVqs.mjs";import{buildIndexRange as Kt,indexKeysForRow as Wt,keysTouchRanges as Xt}from"./packem_shared/buildIndexRange-BTChxh3k.mjs";import{isPushableWhere as Vt,whereFilter as zt,whereOfFilter as Qt}from"./packem_shared/isPushableWhere-BeYAOjUb.mjs";import{RELATED_DEFAULT_LIMIT as jt,RELATED_DEPTH_DECAY as Jt,RELATED_MAX_DEPTH as Zt,RELATED_MAX_LIMIT as $t,deriveRelationEdges as es,findRelated as rs}from"./packem_shared/RELATED_DEFAULT_LIMIT-CVqN4JEu.mjs";import{DEFAULT_MAX_RELATION_KEYS as as,assertFlatPredicate as ts,assertShapeShardable as ss,composeReadPredicate as is,containsRelationPredicate as ls,isRelationPredicate as ns,resolveRelationPredicates as ds}from"./packem_shared/DEFAULT_MAX_RELATION_KEYS-DfrMi_eE.mjs";import{describeRelationWrites as ms}from"./packem_shared/describeRelationWrites-omar6-u9.mjs";import{applyInsertDefaults as us,applyOnDelete as Ss,distinctValues as fs,fanOutScalarCounts as xs,relationHooks as hs,resolveWith as Es,runRowValidators as Ts}from"./packem_shared/applyInsertDefaults-CVukTkQ5.mjs";import{D as As,c as Cs,n as gs,r as _s,s as Is}from"./packem_shared/relay-CKEdfUjH.mjs";import{DEFAULT_MAX_RELAYS as Ls,OwnerRelay as Os,RelayMember as Ds,createRelayLink as Ps}from"./packem_shared/DEFAULT_MAX_RELAYS-B66neS_B.mjs";import{createReplicaLink as Ms,gateReplicaDispatch as Fs,handleReplicaControl as Ns}from"./packem_shared/createReplicaLink-DVXW9rR6.mjs";import{buildReprojectionMigration as Bs,countLegacyRows as Us,reprojectableFields as Gs,reprojectionTables as ws}from"./packem_shared/buildReprojectionMigration-B8aEpETD.mjs";import{RLS_UNWRAP_SYMBOL as vs,RlsRequiredError as Ks,guardWriter as Ws}from"./packem_shared/RLS_UNWRAP_SYMBOL-H6J96vgK.mjs";import{SCHEMA_HISTORY_MAX_VERSIONS as Hs,readSchemaHistory as Vs,readSchemaVersion as zs,recordSchemaVersion as Qs}from"./packem_shared/SCHEMA_HISTORY_MAX_VERSIONS-CEwFjj-O.mjs";import{serializeSqlValue as js}from"./packem_shared/serializeSqlValue-DeoBMpZ2.mjs";import{buildSettings as Zs,isDevEnvironment as $s,readDeployInfo as ei}from"./packem_shared/buildSettings-BRkZd6_E.mjs";import{buildShapeDiff as oi}from"./packem_shared/buildShapeDiff-CdLJTijm.mjs";import{ShapeDiffCache as ti,createShapeDiffCache as si,globalShapeReadKey as ii}from"./packem_shared/ShapeDiffCache-iNO-hUiy.mjs";import{buildPokeFrames as ni,diffGlobalMembership as di,encodeRowsPatch as ci,projectColumns as mi}from"./packem_shared/buildPokeFrames-WR-hp0mX.mjs";import{ShardRunner as ui}from"./packem_shared/ShardRunner-CrveaPId.mjs";import{stubByName as fi}from"./packem_shared/stubByName-B8cFYipA.mjs";import{runSocketPool as hi}from"./packem_shared/runSocketPool-CZJ2X9cF.mjs";import{MAX_SQL_ROWS as Ti,assertReadonly as Ri,lintReadonlySql as Ai,runReadonlySql as Ci}from"./packem_shared/MAX_SQL_ROWS-eRignWyO.mjs";import{BIGINT_KEY_DIGITS as _i,bigintSqlKey as Ii,decodeBigintSqlKey as bi,decodeFloat64SqlKey as Li,float64SqlKey as Oi}from"./packem_shared/BIGINT_KEY_DIGITS-DE6yshOt.mjs";import{awaitWsDrain as Pi,subscriptionFrames as yi,subscriptionListDeltas as Mi,trySendFrame as Fi}from"./packem_shared/awaitWsDrain-DMcWBQ7I.mjs";import{mergeChangedKeys as ki,recordChangedKeys as Bi,writeTouchesMemo as Ui}from"./packem_shared/mergeChangedKeys-DPKhen6e.mjs";import{createSystemReader as wi}from"./packem_shared/createSystemReader-BSCxr8Qs.mjs";import{ConflictError as vi}from"./packem_shared/ConflictError-C8GtJmjS.mjs";import{DEFAULT_TRANSACTION_LIMITS as Wi,TransactionHeadroomTracker as Xi}from"./packem_shared/DEFAULT_TRANSACTION_LIMITS-D7p7Ys0M.mjs";import{hasTrigger as Vi,runTriggers as zi}from"./packem_shared/hasTrigger-CjlwI4le.mjs";import{isTtlExpired as Yi,nextTtlExpiry as ji,selectExpiredIds as Ji}from"./packem_shared/isTtlExpired-DNxmZA6e.mjs";import{VECTOR_BACKFILL_MAX_PAGES as $i,backfillVectorIndexes as el}from"./packem_shared/VECTOR_BACKFILL_MAX_PAGES-DcQpf83n.mjs";import{c as ol,s as al}from"./packem_shared/where-sql-BjY4rnqb.mjs";import{RELATION_EXISTS_KEY as sl}from"./packem_shared/RELATION_EXISTS_KEY-wxgj6rSL.mjs";import{RELAY_SIGNATURE_HEADER as ll,siblingSecretOf as nl,signSiblingBody as dl,verifySiblingBody as cl}from"./packem_shared/RELAY_SIGNATURE_HEADER-DP0glzE_.mjs";import{REPROJECTION_MIGRATION_PREFIX as pl,reprojectionMigrationId as ul}from"./packem_shared/REPROJECTION_MIGRATION_PREFIX-Czcb6_mO.mjs";import{isInternalTableName as fl}from"./packem_shared/isInternalTableName-BoljO2tP.mjs";import{quoteIdentifier as hl}from"./packem_shared/quoteIdentifier-CObIFRhb.mjs";import{runShardMigrations as Tl}from"./packem_shared/runShardMigrations-xu993yo2.mjs";import{stableStringify as Al,stableWireKey as Cl}from"@lunora/wire";export{ua as ADMIN_FUNCTIONS,Sa as ADMIN_FUNCTION_PREFIX,d as AGGREGATE_SQL_FUNCTION,Qr as AGG_COUNT,Yr as AGG_KEY,jr as AGG_VALUE,O as AUDIT_LOG_TABLE,_i as BIGINT_KEY_DIGITS,V as CDC_LOG_TABLE,z as CDC_LOG_TABLE_SEQ_INDEX,Q as CDC_META_TABLE,Ae as CLIENT_WATERMARK_TABLE,be as COMMIT_SEQ_FIELD,Le as COMMIT_SEQ_TABLE,Za as CURSOR_PREFIX,Me as CompanionMemo,vi as ConflictError,A as CountRlsUnsupportedError,Br as DATA_MIGRATION_STATE_TABLE,fa as DEFAULT_FANOUT_TOPIC_LIMIT,as as DEFAULT_MAX_RELATION_KEYS,Ls as DEFAULT_MAX_RELAYS,As as DEFAULT_PROMOTION_THRESHOLDS,Wi as DEFAULT_TRANSACTION_LIMITS,Jr as DOC_COLUMN,bo as DurableStreamRunner,xa as FLAGS_FUNCTION_PREFIX,aa as GEO_DEFAULT_PRECISION,Ue as GLOBAL_SHAPE_SNAPSHOT_TABLE,ma as GlobalPollTick,Xe as IDEMPOTENCY_TABLE,Na as MAIL_RETENTION,ka as MAIL_TABLE,Lo as MAX_DURABLE_STREAM_BYTES,Oo as MAX_DURABLE_STREAM_CHUNKS,ha as MAX_PAGE_SIZE,Ti as MAX_SQL_ROWS,va as NotFoundError,F as NotUniqueError,Os as OwnerRelay,pt as QUEUE_TABLE,Tt as RANK_TIEBREAK,yt as REACTOR_STATE_TABLE,jt as RELATED_DEFAULT_LIMIT,Jt as RELATED_DEPTH_DECAY,Zt as RELATED_MAX_DEPTH,$t as RELATED_MAX_LIMIT,sl as RELATION_EXISTS_KEY,Ea as RELATION_FUNCTION_PREFIX,ll as RELAY_SIGNATURE_HEADER,pl as REPROJECTION_MIGRATION_PREFIX,vs as RLS_UNWRAP_SYMBOL,Ot as ReactiveCache,Ds as RelayMember,Ks as RlsRequiredError,qr as SCAN_DEP,ar as SCHEDULE_OUTBOX_TABLE,Hs as SCHEMA_HISTORY_MAX_VERSIONS,Tr as SEARCH_STATE_TABLE,_r as SHAPE_POKE_CURSOR_TABLE,ti as ShapeDiffCache,ui as ShardRunner,Xi as TransactionHeadroomTracker,Gt as UNVOUCHABLE_DEP,$i as VECTOR_BACKFILL_MAX_PAGES,mo as WORKERD_SQLITE_LIMITS,Ce as advanceClientWatermark,Zr as aggUpsertSql,c as aggregateSqlFunction,f as aggregateTableName,Oe as allocateCommitSeq,D as appendAuditEntry,Y as appendCdcChange,ho as appendStreamChunk,j as applyCdcChanges,us as applyInsertDefaults,Ss as applyOnDelete,$a as applySelect,fe as archiveCdcSegment,Ya as armRestore,ts as assertFlatPredicate,N as assertNoExplicitUndefined,Wa as assertPatchAllowed,Ri as assertReadonly,ss as assertShapeShardable,k as assertStorableRowId,B as assertValidClientId,Pi as awaitWsDrain,v as backfillAggregateIndexes,K as backfillRankIndexes,W as backfillSearchIndexes,X as backfillSearchIndexesForTable,el as backfillVectorIndexes,Ii as bigintSqlKey,ta as boundingBoxCenter,sa as boundingBoxGeohashes,Kt as buildIndexRange,ni as buildPokeFrames,Bs as buildReprojectionMigration,et as buildSeekBeforeWhere,rt as buildSeekWhere,Zs as buildSettings,oi as buildShapeDiff,J as bumpCdcEpoch,xe as cdcArchiveRewound,Z as cdcCanVouchFor,$ as cdcForkedError,ee as cdcSeqLeavingRows,re as cdcTouchesTables,oe as cdcTrimmedError,Eo as claimStreamRun,Cs as clampPromotionThresholds,Ba as clearCapturedMail,Fe as clearCompanionSignatures,je as clearMemoryTables,ut as clearQueueMessages,x as coerceAggregateNumber,ae as compactCdcDocs,ol as compileWhereSql,is as composeReadPredicate,er as computeRankPage,ls as containsRelationPredicate,Us as countLegacyRows,ia as coveringGeohashes,ke as createCompanionSync,vr as createDependencyTracker,Ta as createFanoutCounters,Ra as createGlobalPollCounters,$r as createIndexSql,wt as createReadFootprint,Ps as createRelayLink,Ms as createReplicaLink,si as createShapeDiffCache,Aa as createShapeProbeCounters,U as createShardCtxDb,wi as createSystemReader,te as cursorBelowRetainedFloor,Do as decideDurableAttach,bi as decodeBigintSqlKey,ot as decodeCursor,Li as decodeFloat64SqlKey,tr as deferScheduleOutbox,Ge as deleteGlobalShapeSnapshot,we as deleteGlobalShapeSnapshotsForConnection,Ir as deleteShapePokeCursor,br as deleteShapePokeCursorsForConnection,To as deleteStreamRun,Kr as depKey,es as deriveRelationEdges,ms as describeRelationWrites,No as diffExternalSource,di as diffGlobalMembership,fs as distinctValues,sr as dropScheduleOutbox,h as encodeAggregateKey,at as encodeCursor,la as encodeGeohash,Rt as encodePartitionKey,ci as encodeRowsPatch,P as ensureAuditTable,Ua as ensureMailTable,yo as envOptionalPositiveInt,Mo as envPositiveInt,tt as equalityPinnedFields,o as exportShardRows,Ca as facetColumn,xs as fanOutScalarCounts,rs as findRelated,ga as findStorageReferences,Ro as finishStreamRun,Oi as float64SqlKey,E as foldAggregateTally,ir as forgetScheduleOutbox,jo as ftsCompanionDdl,Jo as ftsPurgeDocument,Zo as ftsRowidMapName,$o as ftsUnmappedPage,ea as ftsWriteDocument,Fs as gateReplicaDispatch,eo as geoTableName,ii as globalShapeReadKey,ra as groupUnmappedRows,Ws as guardWriter,Ns as handleReplicaControl,lr as hasScheduleOutboxEntry,Vi as hasTrigger,na as haversineMeters,a as importShardRows,Wt as indexKeysForRow,$s as isDevEnvironment,ro as isFtsAvailable,fl as isInternalTableName,St as isLossyBody,Je as isMemoryTable,Vt as isPushableWhere,ns as isRelationPredicate,Ho as isSoftDeleted,Vo as isSourceDue,Yi as isTtlExpired,_a as isVacuousFilterClause,oo as jsonPath,ao as jsonPathSql,Xt as keysTouchRanges,Bo as liftSourceId,Ai as lintReadonlySql,Mt as listReactorStates,Ia as listTables,qt as markUnvouchableReads,At as matchesRankStaticWhere,m as matchesStaticWhere,qo as materializeExternalRows,vo as materializeExternalRowsIncremental,Ze as memoryTableNames,ki as mergeChangedKeys,C as mergeWhere,se as migrateCdcLog,ie as migrateCdcMeta,ge as migrateClientWatermark,De as migrateCommitSeq,Ao as migrateDurableStreams,qe as migrateGlobalShapeSnapshot,He as migrateIdempotency,Ft as migrateReactorState,nr as migrateScheduleOutbox,Rr as migrateSearchState,Lr as migrateShapePokeCursor,le as minCdcReplayableSeq,ne as minCdcSeq,Or as minShapePokeCursor,gs as nextPromotionState,ji as nextTtlExpiry,p as normalizeCountArgument,G as normalizeIdStructurally,st as normalizeOrderKeys,Uo as normalizeSourceDocument,Go as normalizeSourceValue,it as nullsFirstOf,lt as nullsOrderSuffix,Xa as operatorFields,po as param,dr as parkScheduleOutbox,t as parseExportShardArgs,s as parseImportShardArgs,Ha as patchDependsOnRow,g as planAggregateLookup,da as pointInBoundingBox,cr as probeScheduleOutbox,mi as projectColumns,zo as pullExternalSourceIncrementalTick,Qo as pullExternalSourceTick,to as qualifiedJsonPath,so as qualifiedJsonPathSql,hl as quoteIdentifier,Ct as rankKeyFromDoc,gt as rankPivotConditionSql,_t as rankTableName,Dt as reactiveCacheKey,Nt as reactorNeedsRun,T as readAggregateValue,he as readArchivedCdcChanges,y as readAuditLog,ja as readBookmark,Ga as readCapturedMail,Ee as readCdcArchivedThrough,de as readCdcChangeKeys,ce as readCdcChanges,me as readCdcCursor,pe as readCdcEpoch,_e as readClientWatermark,Pe as readCommitSeq,ei as readDeployInfo,mr as readDueScheduleOutbox,pr as readDueScheduleOutboxEntry,Ko as readExternalSourceBaseline,ve as readGlobalShapeSnapshot,Ve as readIdempotent,Ur as readMigrationStatus,Va as readPatchField,ft as readQueueMessageById,xt as readQueueMessages,kt as readReactorState,ur as readScheduleOutbox,Sr as readScheduleOutboxState,Vs as readSchemaHistory,zs as readSchemaVersion,Ar as readSearchBackfillState,Dr as readShapePokeCursor,Co as readStreamChunks,go as readStreamRun,ba as readTablePage,wa as recordCapturedMail,Bi as recordChangedKeys,La as recordFanoutPass,Oa as recordGlobalPollPass,ht as recordQueueMessages,fr as recordScheduleOutbox,Qs as recordSchemaVersion,Da as recordShapeProbePass,hs as relationHooks,_s as relayCountFor,uo as renderSql,Gs as reprojectableFields,ul as reprojectionMigrationId,ws as reprojectionTables,xr as requeueScheduleOutbox,za as resolvePatch,It as resolveRankPartition,rr as resolveRankSeekTuple,ds as resolveRelationPredicates,Es as resolveWith,io as rowToDocument,Gr as runDataMigration,Hr as runDrizzle,Wo as runExternalSourceTick,Ci as runReadonlySql,Ts as runRowValidators,Tl as runShardMigrations,hi as runSocketPool,Vr as runSql,zi as runTriggers,Ji as selectExpiredIds,i as selectExportTables,_ as selectIndexForAggregate,I as selectIndexForCount,b as selectIndexForGroupBy,Pa as selectMatchingIds,Fr as selectShapeMembers,Nr as selectShapeRows,js as serializeSqlValue,al as serverInList,Is as shapeRoutingKey,nl as siblingSecretOf,dl as signSiblingBody,nt as softDeleteScope,bt as sortColumnName,So as sqliteInList,Al as stableStringify,Cl as stableWireKey,w as stripReservedPatchFields,fi as stubByName,yi as subscriptionFrames,Mi as subscriptionListDeltas,ya as summarizeFanoutTopics,Ma as summarizeSubscriptions,lo as tableColumns,Wr as tableFromDepKey,u as throwingScheduler,dt as tiebreakDirectionFor,ue as trimCdcChanges,ze as trimIdempotent,hr as trimScheduleOutbox,_o as trimStreamRuns,no as tryRowToDocument,Fi as trySendFrame,fo as unionAll,ct as uniqueIndexFields,l as validateImportRow,cl as verifySiblingBody,zt as whereFilter,Qt as whereOfFilter,Te as writeCdcArchivedThrough,Ke as writeGlobalShapeSnapshot,Qe as writeIdempotent,Bt as writeReactorState,Cr as writeSearchBackfillState,Pr as writeShapePokeCursor,yr as writeShapePokeCursors,Ui as writeTouchesMemo};
|
|
1
|
+
import{exportShardRows as o,importShardRows as a,parseExportShardArgs as t,parseImportShardArgs as i,selectExportTables as s,validateImportRow as n}from"./packem_shared/exportShardRows-CZh4wrvI.mjs";import{adminTokenExists as d,createAdminTokenRecord as c,listAdminTokens as m,revokeAdminTokenRecord as p,verifyAdminTokenDigest as u}from"./packem_shared/adminTokenExists-CjKKZzfY.mjs";import{AGGREGATE_SQL_FUNCTION as f,aggregateSqlFunction as x,matchesStaticWhere as E,normalizeCountArgument as h,throwingScheduler as T}from"./packem_shared/AGGREGATE_SQL_FUNCTION-C_ZipS9R.mjs";import{aggregateTableName as A,coerceAggregateNumber as C,encodeAggregateKey as g,foldAggregateTally as _,readAggregateValue as I}from"./packem_shared/aggregateTableName-B_CtIQCS.mjs";import{CountRlsUnsupportedError as L,mergeWhere as D,planAggregateLookup as O,selectIndexForAggregate as P,selectIndexForCount as y,selectIndexForGroupBy as M}from"./packem_shared/CountRlsUnsupportedError-BvsDqfO2.mjs";import{AUDIT_LOG_TABLE as k,appendAuditEntry as N,ensureAuditTable as B,readAuditLog as U}from"./packem_shared/AUDIT_LOG_TABLE-BFJ65SRS.mjs";import{NotUniqueError as w,assertNoExplicitUndefined as q,assertStorableRowId as v,assertValidClientId as K,createShardCtxDb as W,normalizeIdStructurally as X,stripReservedPatchFields as H}from"./packem_shared/NotUniqueError-BjwNIte8.mjs";import{backfillAggregateIndexes as z,backfillRankIndexes as Q,backfillSearchIndexes as Y,backfillSearchIndexesForTable as j}from"./packem_shared/backfillAggregateIndexes-Pk0KLrfk.mjs";import{CDC_LOG_TABLE as Z,CDC_LOG_TABLE_SEQ_INDEX as $,CDC_META_TABLE as ee,appendCdcChange as re,applyCdcChanges as oe,bumpCdcEpoch as ae,cdcCanVouchFor as te,cdcForkedError as ie,cdcSeqLeavingRows as se,cdcTouchesTables as ne,cdcTrimmedError as le,compactCdcDocs as de,cursorBelowRetainedFloor as ce,migrateCdcLog as me,migrateCdcMeta as pe,minCdcReplayableSeq as ue,minCdcSeq as Se,readCdcChangeKeys as fe,readCdcChanges as xe,readCdcCursor as Ee,readCdcEpoch as he,trimCdcChanges as Te}from"./packem_shared/CDC_LOG_TABLE-BFGgqai8.mjs";import{archiveCdcSegment as Ae,cdcArchiveRewound as Ce,readArchivedCdcChanges as ge,readCdcArchivedThrough as _e,writeCdcArchivedThrough as Ie}from"./packem_shared/archiveCdcSegment-Cr8oGLfB.mjs";import{CLIENT_WATERMARK_TABLE as Le,advanceClientWatermark as De,migrateClientWatermark as Oe,readClientWatermark as Pe}from"./packem_shared/CLIENT_WATERMARK_TABLE-De7z_OHV.mjs";import{COMMIT_SEQ_FIELD as Me,COMMIT_SEQ_TABLE as Fe,allocateCommitSeq as ke,migrateCommitSeq as Ne,readCommitSeq as Be}from"./packem_shared/COMMIT_SEQ_FIELD-Da1DjGqo.mjs";import{CompanionMemo as Ge,clearCompanionSignatures as we}from"./packem_shared/CompanionMemo-BXU5vfak.mjs";import{createCompanionSync as ve}from"./packem_shared/createCompanionSync-CEht4hXX.mjs";import{GLOBAL_SHAPE_SNAPSHOT_TABLE as We,deleteGlobalShapeSnapshot as Xe,deleteGlobalShapeSnapshotsForConnection as He,migrateGlobalShapeSnapshot as Ve,readGlobalShapeSnapshot as ze,writeGlobalShapeSnapshot as Qe}from"./packem_shared/GLOBAL_SHAPE_SNAPSHOT_TABLE-Bb6-aZuH.mjs";import{IDEMPOTENCY_TABLE as je,migrateIdempotency as Je,readIdempotent as Ze,trimIdempotent as $e,writeIdempotent as er}from"./packem_shared/IDEMPOTENCY_TABLE-COrgeP3O.mjs";import{clearMemoryTables as or,isMemoryTable as ar,memoryTableNames as tr}from"./packem_shared/clearMemoryTables-aMRERF0w.mjs";import{computeRankPage as sr,resolveRankSeekTuple as nr}from"./packem_shared/computeRankPage-BZIpATcs.mjs";import{SCHEDULE_OUTBOX_TABLE as dr,deferScheduleOutbox as cr,dropScheduleOutbox as mr,forgetScheduleOutbox as pr,hasScheduleOutboxEntry as ur,migrateScheduleOutbox as Sr,parkScheduleOutbox as fr,probeScheduleOutbox as xr,readDueScheduleOutbox as Er,readDueScheduleOutboxEntry as hr,readScheduleOutbox as Tr,readScheduleOutboxState as Rr,recordScheduleOutbox as Ar,requeueScheduleOutbox as Cr,trimScheduleOutbox as gr}from"./packem_shared/SCHEDULE_OUTBOX_TABLE-iyyiSjsO.mjs";import{S as Ir,m as br,r as Lr,w as Dr}from"./packem_shared/ctx-db-search-state-CPKPy8N6.mjs";import{SHAPE_POKE_CURSOR_TABLE as Pr,deleteShapePokeCursor as yr,deleteShapePokeCursorsForConnection as Mr,migrateShapePokeCursor as Fr,minShapePokeCursor as kr,readShapePokeCursor as Nr,writeShapePokeCursor as Br,writeShapePokeCursors as Ur}from"./packem_shared/SHAPE_POKE_CURSOR_TABLE-BGvY3sFI.mjs";import{selectShapeMembers as wr,selectShapeRows as qr}from"./packem_shared/selectShapeMembers-Dqx_m7BF.mjs";import{DATA_MIGRATION_STATE_TABLE as Kr,readMigrationStatus as Wr,runDataMigration as Xr}from"./packem_shared/DATA_MIGRATION_STATE_TABLE-CFvBS9-M.mjs";import{SCAN_DEP as Vr,createDependencyTracker as zr,depKey as Qr,tableFromDepKey as Yr}from"./packem_shared/SCAN_DEP-D7qE3iUe.mjs";import{runDrizzle as Jr,runSql as Zr}from"./packem_shared/runDrizzle-RC09zZrh.mjs";import{A as eo,a as ro,b as oo,D as ao,c as to,d as io,g as so,i as no,j as lo,e as co,q as mo,f as po,r as uo,t as So,h as fo}from"./packem_shared/do-sql-105TONaE.mjs";import{WORKERD_SQLITE_LIMITS as Eo,param as ho,renderSql as To,sqliteInList as Ro,unionAll as Ao}from"./packem_shared/WORKERD_SQLITE_LIMITS-B_4w7tzY.mjs";import{appendStreamChunk as go,claimStreamRun as _o,deleteStreamRun as Io,finishStreamRun as bo,migrateDurableStreams as Lo,readStreamChunks as Do,readStreamRun as Oo,trimStreamRuns as Po}from"./packem_shared/appendStreamChunk-BZYgGE9Y.mjs";import{DurableStreamRunner as Mo,MAX_DURABLE_STREAM_BYTES as Fo,MAX_DURABLE_STREAM_CHUNKS as ko,decideDurableAttach as No}from"./packem_shared/DurableStreamRunner-MMlV5qKQ.mjs";import{envOptionalPositiveInt as Uo,envPositiveInt as Go}from"./packem_shared/envOptionalPositiveInt-D2pY-c64.mjs";import{diffExternalSource as qo}from"./packem_shared/diffExternalSource-B0FZlDoL.mjs";import{liftSourceId as Ko,normalizeSourceDocument as Wo,normalizeSourceValue as Xo}from"./packem_shared/liftSourceId-CA3ENhXj.mjs";import{materializeExternalRows as Vo,materializeExternalRowsIncremental as zo,readExternalSourceBaseline as Qo,runExternalSourceTick as Yo}from"./packem_shared/materializeExternalRows-CHPRx8fu.mjs";import{isSoftDeleted as Jo,isSourceDue as Zo,pullExternalSourceIncrementalTick as $o,pullExternalSourceTick as ea}from"./packem_shared/isSoftDeleted-BBWKE0Sm.mjs";import{f as oa,a as aa,b as ta,c as ia,d as sa,g as na}from"./packem_shared/fts-companion-CE3EmIjk.mjs";import{GEO_DEFAULT_PRECISION as da,boundingBoxCenter as ca,boundingBoxGeohashes as ma,coveringGeohashes as pa,encodeGeohash as ua,haversineMeters as Sa,pointInBoundingBox as fa}from"./packem_shared/GEO_DEFAULT_PRECISION-CqpQZ-J_.mjs";import{default as Ea}from"./packem_shared/GlobalPollTick-BNK4o-XT.mjs";import{ADMIN_FUNCTIONS as Ta,ADMIN_FUNCTION_PREFIX as Ra,DEFAULT_FANOUT_TOPIC_LIMIT as Aa,FLAGS_FUNCTION_PREFIX as Ca,MAX_PAGE_SIZE as ga,RELATION_FUNCTION_PREFIX as _a,createFanoutCounters as Ia,createGlobalPollCounters as ba,createShapeProbeCounters as La,facetColumn as Da,findStorageReferences as Oa,isVacuousFilterClause as Pa,listTables as ya,readTablePage as Ma,recordFanoutPass as Fa,recordGlobalPollPass as ka,recordShapeProbePass as Na,selectMatchingIds as Ba,summarizeFanoutTopics as Ua,summarizeSubscriptions as Ga}from"./packem_shared/ADMIN_FUNCTIONS-B_4sLV4q.mjs";import{MAIL_RETENTION as qa,MAIL_TABLE as va,clearCapturedMail as Ka,ensureMailTable as Wa,readCapturedMail as Xa,recordCapturedMail as Ha}from"./packem_shared/MAIL_RETENTION-DMolrLYt.mjs";import{NotFoundError as za}from"./packem_shared/NotFoundError-BhF7FeFr.mjs";import{assertPatchAllowed as Ya,operatorFields as ja,patchDependsOnRow as Ja,readPatchField as Za,resolvePatch as $a}from"./packem_shared/assertPatchAllowed-CA_H466g.mjs";import{armRestore as rt,readBookmark as ot}from"./packem_shared/armRestore-Bu1_8SUa.mjs";import{CURSOR_PREFIX as tt,applySelect as it,buildSeekBeforeWhere as st,buildSeekWhere as nt,decodeCursor as lt,encodeCursor as dt,equalityPinnedFields as ct,normalizeOrderKeys as mt,nullsFirstOf as pt,nullsOrderSuffix as ut,softDeleteScope as St,tiebreakDirectionFor as ft,uniqueIndexFields as xt}from"./packem_shared/CURSOR_PREFIX-6offuG6M.mjs";import{QUEUE_TABLE as ht,clearQueueMessages as Tt,isLossyBody as Rt,readQueueMessageById as At,readQueueMessages as Ct,recordQueueMessages as gt}from"./packem_shared/QUEUE_TABLE-C-goXtGd.mjs";import{RANK_TIEBREAK as It,encodePartitionKey as bt,matchesRankStaticWhere as Lt,rankKeyFromDoc as Dt,rankPivotConditionSql as Ot,rankTableName as Pt,resolveRankPartition as yt,sortColumnName as Mt}from"./packem_shared/RANK_TIEBREAK-D3ye2GsL.mjs";import{ReactiveCache as kt,reactiveCacheKey as Nt}from"./packem_shared/ReactiveCache-5XPk8qfW.mjs";import{REACTOR_STATE_TABLE as Ut,listReactorStates as Gt,migrateReactorState as wt,reactorNeedsRun as qt,readReactorState as vt,writeReactorState as Kt}from"./packem_shared/REACTOR_STATE_TABLE-D2Mn204f.mjs";import{UNVOUCHABLE_DEP as Xt,createReadFootprint as Ht,markUnvouchableReads as Vt}from"./packem_shared/UNVOUCHABLE_DEP-Ds9gxVqs.mjs";import{buildIndexRange as Qt,indexKeysForRow as Yt,keysTouchRanges as jt}from"./packem_shared/buildIndexRange-BTChxh3k.mjs";import{isPushableWhere as Zt,whereFilter as $t,whereOfFilter as ei}from"./packem_shared/isPushableWhere-BeYAOjUb.mjs";import{RELATED_DEFAULT_LIMIT as oi,RELATED_DEPTH_DECAY as ai,RELATED_MAX_DEPTH as ti,RELATED_MAX_LIMIT as ii,deriveRelationEdges as si,findRelated as ni}from"./packem_shared/RELATED_DEFAULT_LIMIT-CVqN4JEu.mjs";import{DEFAULT_MAX_RELATION_KEYS as di,assertFlatPredicate as ci,assertShapeShardable as mi,composeReadPredicate as pi,containsRelationPredicate as ui,isRelationPredicate as Si,resolveRelationPredicates as fi}from"./packem_shared/DEFAULT_MAX_RELATION_KEYS-DfrMi_eE.mjs";import{describeRelationWrites as Ei}from"./packem_shared/describeRelationWrites-omar6-u9.mjs";import{applyInsertDefaults as Ti,applyOnDelete as Ri,distinctValues as Ai,fanOutScalarCounts as Ci,relationHooks as gi,resolveWith as _i,runRowValidators as Ii}from"./packem_shared/applyInsertDefaults-CVukTkQ5.mjs";import{D as Li,c as Di,n as Oi,r as Pi,s as yi}from"./packem_shared/relay-CKEdfUjH.mjs";import{DEFAULT_MAX_RELAYS as Fi,OwnerRelay as ki,RelayMember as Ni,createRelayLink as Bi}from"./packem_shared/DEFAULT_MAX_RELAYS-Bc6PI-xy.mjs";import{createReplicaLink as Gi,gateReplicaDispatch as wi,handleReplicaControl as qi}from"./packem_shared/createReplicaLink-DtqXBi-0.mjs";import{buildReprojectionMigration as Ki,countLegacyRows as Wi,reprojectableFields as Xi,reprojectionTables as Hi}from"./packem_shared/buildReprojectionMigration-B8aEpETD.mjs";import{RLS_UNWRAP_SYMBOL as zi,RlsRequiredError as Qi,guardWriter as Yi}from"./packem_shared/RLS_UNWRAP_SYMBOL-H6J96vgK.mjs";import{SCHEMA_HISTORY_MAX_VERSIONS as Ji,readSchemaHistory as Zi,readSchemaVersion as $i,recordSchemaVersion as es}from"./packem_shared/SCHEMA_HISTORY_MAX_VERSIONS-CEwFjj-O.mjs";import{serializeSqlValue as os}from"./packem_shared/serializeSqlValue-DeoBMpZ2.mjs";import{buildSettings as ts,isDevEnvironment as is,readDeployInfo as ss}from"./packem_shared/buildSettings-BRkZd6_E.mjs";import{buildShapeDiff as ls}from"./packem_shared/buildShapeDiff-CdLJTijm.mjs";import{ShapeDiffCache as cs,createShapeDiffCache as ms,globalShapeReadKey as ps}from"./packem_shared/ShapeDiffCache-iNO-hUiy.mjs";import{buildPokeFrames as Ss,diffGlobalMembership as fs,encodeRowsPatch as xs,projectColumns as Es}from"./packem_shared/buildPokeFrames-WR-hp0mX.mjs";import{ShardRunner as Ts}from"./packem_shared/ShardRunner-CrveaPId.mjs";import{stubByName as As}from"./packem_shared/stubByName-DQSivmvb.mjs";import{runSocketPool as gs}from"./packem_shared/runSocketPool-CZJ2X9cF.mjs";import{MAX_SQL_ROWS as Is,assertReadonly as bs,lintReadonlySql as Ls,runReadonlySql as Ds}from"./packem_shared/MAX_SQL_ROWS-B4WlVI-e.mjs";import{BIGINT_KEY_DIGITS as Ps,bigintSqlKey as ys,decodeBigintSqlKey as Ms,decodeFloat64SqlKey as Fs,float64SqlKey as ks}from"./packem_shared/BIGINT_KEY_DIGITS-DE6yshOt.mjs";import{awaitWsDrain as Bs,subscriptionFrames as Us,subscriptionListDeltas as Gs,trySendFrame as ws}from"./packem_shared/awaitWsDrain-DMcWBQ7I.mjs";import{mergeChangedKeys as vs,recordChangedKeys as Ks,writeTouchesMemo as Ws}from"./packem_shared/mergeChangedKeys-DPKhen6e.mjs";import{createSystemReader as Hs}from"./packem_shared/createSystemReader-BSCxr8Qs.mjs";import{ConflictError as zs}from"./packem_shared/ConflictError-C8GtJmjS.mjs";import{DEFAULT_TRANSACTION_LIMITS as Ys,TransactionHeadroomTracker as js}from"./packem_shared/DEFAULT_TRANSACTION_LIMITS-D7p7Ys0M.mjs";import{hasTrigger as Zs,runTriggers as $s}from"./packem_shared/hasTrigger-CjlwI4le.mjs";import{isTtlExpired as rn,nextTtlExpiry as on,selectExpiredIds as an}from"./packem_shared/isTtlExpired-DNxmZA6e.mjs";import{VECTOR_BACKFILL_MAX_PAGES as sn,backfillVectorIndexes as nn}from"./packem_shared/VECTOR_BACKFILL_MAX_PAGES-DcQpf83n.mjs";import{c as dn,s as cn}from"./packem_shared/where-sql-BjY4rnqb.mjs";import{RELATION_EXISTS_KEY as pn}from"./packem_shared/RELATION_EXISTS_KEY-wxgj6rSL.mjs";import{ADMIN_TOKEN_TABLE as Sn}from"./packem_shared/ADMIN_TOKEN_TABLE-DfQ5osdI.mjs";import{RELAY_SIGNATURE_HEADER as xn,siblingSecretOf as En,signSiblingBody as hn,verifySiblingBody as Tn}from"./packem_shared/RELAY_SIGNATURE_HEADER-CAfC4tqg.mjs";import{REPROJECTION_MIGRATION_PREFIX as An,reprojectionMigrationId as Cn}from"./packem_shared/REPROJECTION_MIGRATION_PREFIX-Czcb6_mO.mjs";import{isInternalTableName as _n}from"./packem_shared/isInternalTableName-BoljO2tP.mjs";import{quoteIdentifier as bn}from"./packem_shared/quoteIdentifier-CObIFRhb.mjs";import{runShardMigrations as Dn}from"./packem_shared/runShardMigrations-xu993yo2.mjs";import{stableStringify as Pn,stableWireKey as yn}from"@lunora/wire";export{Ta as ADMIN_FUNCTIONS,Ra as ADMIN_FUNCTION_PREFIX,Sn as ADMIN_TOKEN_TABLE,f as AGGREGATE_SQL_FUNCTION,eo as AGG_COUNT,ro as AGG_KEY,oo as AGG_VALUE,k as AUDIT_LOG_TABLE,Ps as BIGINT_KEY_DIGITS,Z as CDC_LOG_TABLE,$ as CDC_LOG_TABLE_SEQ_INDEX,ee as CDC_META_TABLE,Le as CLIENT_WATERMARK_TABLE,Me as COMMIT_SEQ_FIELD,Fe as COMMIT_SEQ_TABLE,tt as CURSOR_PREFIX,Ge as CompanionMemo,zs as ConflictError,L as CountRlsUnsupportedError,Kr as DATA_MIGRATION_STATE_TABLE,Aa as DEFAULT_FANOUT_TOPIC_LIMIT,di as DEFAULT_MAX_RELATION_KEYS,Fi as DEFAULT_MAX_RELAYS,Li as DEFAULT_PROMOTION_THRESHOLDS,Ys as DEFAULT_TRANSACTION_LIMITS,ao as DOC_COLUMN,Mo as DurableStreamRunner,Ca as FLAGS_FUNCTION_PREFIX,da as GEO_DEFAULT_PRECISION,We as GLOBAL_SHAPE_SNAPSHOT_TABLE,Ea as GlobalPollTick,je as IDEMPOTENCY_TABLE,qa as MAIL_RETENTION,va as MAIL_TABLE,Fo as MAX_DURABLE_STREAM_BYTES,ko as MAX_DURABLE_STREAM_CHUNKS,ga as MAX_PAGE_SIZE,Is as MAX_SQL_ROWS,za as NotFoundError,w as NotUniqueError,ki as OwnerRelay,ht as QUEUE_TABLE,It as RANK_TIEBREAK,Ut as REACTOR_STATE_TABLE,oi as RELATED_DEFAULT_LIMIT,ai as RELATED_DEPTH_DECAY,ti as RELATED_MAX_DEPTH,ii as RELATED_MAX_LIMIT,pn as RELATION_EXISTS_KEY,_a as RELATION_FUNCTION_PREFIX,xn as RELAY_SIGNATURE_HEADER,An as REPROJECTION_MIGRATION_PREFIX,zi as RLS_UNWRAP_SYMBOL,kt as ReactiveCache,Ni as RelayMember,Qi as RlsRequiredError,Vr as SCAN_DEP,dr as SCHEDULE_OUTBOX_TABLE,Ji as SCHEMA_HISTORY_MAX_VERSIONS,Ir as SEARCH_STATE_TABLE,Pr as SHAPE_POKE_CURSOR_TABLE,cs as ShapeDiffCache,Ts as ShardRunner,js as TransactionHeadroomTracker,Xt as UNVOUCHABLE_DEP,sn as VECTOR_BACKFILL_MAX_PAGES,Eo as WORKERD_SQLITE_LIMITS,d as adminTokenExists,De as advanceClientWatermark,to as aggUpsertSql,x as aggregateSqlFunction,A as aggregateTableName,ke as allocateCommitSeq,N as appendAuditEntry,re as appendCdcChange,go as appendStreamChunk,oe as applyCdcChanges,Ti as applyInsertDefaults,Ri as applyOnDelete,it as applySelect,Ae as archiveCdcSegment,rt as armRestore,ci as assertFlatPredicate,q as assertNoExplicitUndefined,Ya as assertPatchAllowed,bs as assertReadonly,mi as assertShapeShardable,v as assertStorableRowId,K as assertValidClientId,Bs as awaitWsDrain,z as backfillAggregateIndexes,Q as backfillRankIndexes,Y as backfillSearchIndexes,j as backfillSearchIndexesForTable,nn as backfillVectorIndexes,ys as bigintSqlKey,ca as boundingBoxCenter,ma as boundingBoxGeohashes,Qt as buildIndexRange,Ss as buildPokeFrames,Ki as buildReprojectionMigration,st as buildSeekBeforeWhere,nt as buildSeekWhere,ts as buildSettings,ls as buildShapeDiff,ae as bumpCdcEpoch,Ce as cdcArchiveRewound,te as cdcCanVouchFor,ie as cdcForkedError,se as cdcSeqLeavingRows,ne as cdcTouchesTables,le as cdcTrimmedError,_o as claimStreamRun,Di as clampPromotionThresholds,Ka as clearCapturedMail,we as clearCompanionSignatures,or as clearMemoryTables,Tt as clearQueueMessages,C as coerceAggregateNumber,de as compactCdcDocs,dn as compileWhereSql,pi as composeReadPredicate,sr as computeRankPage,ui as containsRelationPredicate,Wi as countLegacyRows,pa as coveringGeohashes,c as createAdminTokenRecord,ve as createCompanionSync,zr as createDependencyTracker,Ia as createFanoutCounters,ba as createGlobalPollCounters,io as createIndexSql,Ht as createReadFootprint,Bi as createRelayLink,Gi as createReplicaLink,ms as createShapeDiffCache,La as createShapeProbeCounters,W as createShardCtxDb,Hs as createSystemReader,ce as cursorBelowRetainedFloor,No as decideDurableAttach,Ms as decodeBigintSqlKey,lt as decodeCursor,Fs as decodeFloat64SqlKey,cr as deferScheduleOutbox,Xe as deleteGlobalShapeSnapshot,He as deleteGlobalShapeSnapshotsForConnection,yr as deleteShapePokeCursor,Mr as deleteShapePokeCursorsForConnection,Io as deleteStreamRun,Qr as depKey,si as deriveRelationEdges,Ei as describeRelationWrites,qo as diffExternalSource,fs as diffGlobalMembership,Ai as distinctValues,mr as dropScheduleOutbox,g as encodeAggregateKey,dt as encodeCursor,ua as encodeGeohash,bt as encodePartitionKey,xs as encodeRowsPatch,B as ensureAuditTable,Wa as ensureMailTable,Uo as envOptionalPositiveInt,Go as envPositiveInt,ct as equalityPinnedFields,o as exportShardRows,Da as facetColumn,Ci as fanOutScalarCounts,ni as findRelated,Oa as findStorageReferences,bo as finishStreamRun,ks as float64SqlKey,_ as foldAggregateTally,pr as forgetScheduleOutbox,oa as ftsCompanionDdl,aa as ftsPurgeDocument,ta as ftsRowidMapName,ia as ftsUnmappedPage,sa as ftsWriteDocument,wi as gateReplicaDispatch,so as geoTableName,ps as globalShapeReadKey,na as groupUnmappedRows,Yi as guardWriter,qi as handleReplicaControl,ur as hasScheduleOutboxEntry,Zs as hasTrigger,Sa as haversineMeters,a as importShardRows,Yt as indexKeysForRow,is as isDevEnvironment,no as isFtsAvailable,_n as isInternalTableName,Rt as isLossyBody,ar as isMemoryTable,Zt as isPushableWhere,Si as isRelationPredicate,Jo as isSoftDeleted,Zo as isSourceDue,rn as isTtlExpired,Pa as isVacuousFilterClause,lo as jsonPath,co as jsonPathSql,jt as keysTouchRanges,Ko as liftSourceId,Ls as lintReadonlySql,m as listAdminTokens,Gt as listReactorStates,ya as listTables,Vt as markUnvouchableReads,Lt as matchesRankStaticWhere,E as matchesStaticWhere,Vo as materializeExternalRows,zo as materializeExternalRowsIncremental,tr as memoryTableNames,vs as mergeChangedKeys,D as mergeWhere,me as migrateCdcLog,pe as migrateCdcMeta,Oe as migrateClientWatermark,Ne as migrateCommitSeq,Lo as migrateDurableStreams,Ve as migrateGlobalShapeSnapshot,Je as migrateIdempotency,wt as migrateReactorState,Sr as migrateScheduleOutbox,br as migrateSearchState,Fr as migrateShapePokeCursor,ue as minCdcReplayableSeq,Se as minCdcSeq,kr as minShapePokeCursor,Oi as nextPromotionState,on as nextTtlExpiry,h as normalizeCountArgument,X as normalizeIdStructurally,mt as normalizeOrderKeys,Wo as normalizeSourceDocument,Xo as normalizeSourceValue,pt as nullsFirstOf,ut as nullsOrderSuffix,ja as operatorFields,ho as param,fr as parkScheduleOutbox,t as parseExportShardArgs,i as parseImportShardArgs,Ja as patchDependsOnRow,O as planAggregateLookup,fa as pointInBoundingBox,xr as probeScheduleOutbox,Es as projectColumns,$o as pullExternalSourceIncrementalTick,ea as pullExternalSourceTick,mo as qualifiedJsonPath,po as qualifiedJsonPathSql,bn as quoteIdentifier,Dt as rankKeyFromDoc,Ot as rankPivotConditionSql,Pt as rankTableName,Nt as reactiveCacheKey,qt as reactorNeedsRun,I as readAggregateValue,ge as readArchivedCdcChanges,U as readAuditLog,ot as readBookmark,Xa as readCapturedMail,_e as readCdcArchivedThrough,fe as readCdcChangeKeys,xe as readCdcChanges,Ee as readCdcCursor,he as readCdcEpoch,Pe as readClientWatermark,Be as readCommitSeq,ss as readDeployInfo,Er as readDueScheduleOutbox,hr as readDueScheduleOutboxEntry,Qo as readExternalSourceBaseline,ze as readGlobalShapeSnapshot,Ze as readIdempotent,Wr as readMigrationStatus,Za as readPatchField,At as readQueueMessageById,Ct as readQueueMessages,vt as readReactorState,Tr as readScheduleOutbox,Rr as readScheduleOutboxState,Zi as readSchemaHistory,$i as readSchemaVersion,Lr as readSearchBackfillState,Nr as readShapePokeCursor,Do as readStreamChunks,Oo as readStreamRun,Ma as readTablePage,Ha as recordCapturedMail,Ks as recordChangedKeys,Fa as recordFanoutPass,ka as recordGlobalPollPass,gt as recordQueueMessages,Ar as recordScheduleOutbox,es as recordSchemaVersion,Na as recordShapeProbePass,gi as relationHooks,Pi as relayCountFor,To as renderSql,Xi as reprojectableFields,Cn as reprojectionMigrationId,Hi as reprojectionTables,Cr as requeueScheduleOutbox,$a as resolvePatch,yt as resolveRankPartition,nr as resolveRankSeekTuple,fi as resolveRelationPredicates,_i as resolveWith,p as revokeAdminTokenRecord,uo as rowToDocument,Xr as runDataMigration,Jr as runDrizzle,Yo as runExternalSourceTick,Ds as runReadonlySql,Ii as runRowValidators,Dn as runShardMigrations,gs as runSocketPool,Zr as runSql,$s as runTriggers,an as selectExpiredIds,s as selectExportTables,P as selectIndexForAggregate,y as selectIndexForCount,M as selectIndexForGroupBy,Ba as selectMatchingIds,wr as selectShapeMembers,qr as selectShapeRows,os as serializeSqlValue,cn as serverInList,yi as shapeRoutingKey,En as siblingSecretOf,hn as signSiblingBody,St as softDeleteScope,Mt as sortColumnName,Ro as sqliteInList,Pn as stableStringify,yn as stableWireKey,H as stripReservedPatchFields,As as stubByName,Us as subscriptionFrames,Gs as subscriptionListDeltas,Ua as summarizeFanoutTopics,Ga as summarizeSubscriptions,So as tableColumns,Yr as tableFromDepKey,T as throwingScheduler,ft as tiebreakDirectionFor,Te as trimCdcChanges,$e as trimIdempotent,gr as trimScheduleOutbox,Po as trimStreamRuns,fo as tryRowToDocument,ws as trySendFrame,Ao as unionAll,xt as uniqueIndexFields,n as validateImportRow,u as verifyAdminTokenDigest,Tn as verifySiblingBody,$t as whereFilter,ei as whereOfFilter,Ie as writeCdcArchivedThrough,Qe as writeGlobalShapeSnapshot,er as writeIdempotent,Kt as writeReactorState,Dr as writeSearchBackfillState,Br as writeShapePokeCursor,Ur as writeShapePokeCursors,Ws as writeTouchesMemo};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{LunoraError as d}from"@lunora/errors";import{decodeWire as Q,WIRE_TAG as R,needsWireEncoding as X,encodeWire as G}from"@lunora/wire";import{sql as K}from"drizzle-orm";import{isInternalTableName as w}from"./isInternalTableName-BoljO2tP.mjs";import{n as A,o as V}from"./do-sql-105TONaE.mjs";import{quoteIdentifier as u}from"./quoteIdentifier-CObIFRhb.mjs";import{renderSql as J,sqliteInList as Y}from"./WORKERD_SQLITE_LIMITS-B_4w7tzY.mjs";import{serializeSqlValue as L}from"./serializeSqlValue-DeoBMpZ2.mjs";import{decodeBigintSqlKey as z}from"./BIGINT_KEY_DIGITS-DE6yshOt.mjs";const je="__lunora_admin__:",Le="__lunora_relation__:",Fe="__lunora_flags__:",xe={applyCdc:"__lunora_admin__:applyCdc",aiAvailable:"__lunora_admin__:aiAvailable",aiChartConfig:"__lunora_admin__:aiChartConfig",aiCronExpression:"__lunora_admin__:aiCronExpression",aiGenerateSql:"__lunora_admin__:aiGenerateSql",aiNameQuery:"__lunora_admin__:aiNameQuery",aiTableFilter:"__lunora_admin__:aiTableFilter",assignIssue:"__lunora_admin__:assignIssue",backfillSearch:"__lunora_admin__:backfillSearch",backfillVectors:"__lunora_admin__:backfillVectors",backRelationCounts:"__lunora_admin__:backRelationCounts",cdcSync:"__lunora_admin__:cdcSync",clearCapturedMail:"__lunora_admin__:clearCapturedMail",clearQueueMessages:"__lunora_admin__:clearQueueMessages",clearTable:"__lunora_admin__:clearTable",createAdminToken:"__lunora_admin__:createAdminToken",createWorkflowInstance:"__lunora_admin__:createWorkflowInstance",deleteRows:"__lunora_admin__:deleteRows",describeTable:"__lunora_admin__:describeTable",describeTables:"__lunora_admin__:describeTables",dropOutboxEntry:"__lunora_admin__:dropOutboxEntry",explainIssue:"__lunora_admin__:explainIssue",exportShard:"__lunora_admin__:exportShard",facetColumn:"__lunora_admin__:facetColumn",findRelated:"__lunora_admin__:findRelated",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",getScheduleOutbox:"__lunora_admin__:getScheduleOutbox",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",listAdminTokens:"__lunora_admin__:listAdminTokens",listFlags:"__lunora_admin__:listFlags",listReactors:"__lunora_admin__:listReactors",listQueues:"__lunora_admin__:listQueues",lintSql:"__lunora_admin__:lintSql",listTables:"__lunora_admin__:listTables",listWorkflows:"__lunora_admin__:listWorkflows",maskPolicies:"__lunora_admin__:maskPolicies",migrationStatus:"__lunora_admin__:migrationStatus",patchRows:"__lunora_admin__:patchRows",pitrRestore:"__lunora_admin__:pitrRestore",rankBefore:"__lunora_admin__:rankBefore",rankPage:"__lunora_admin__:rankPage",readTablePage:"__lunora_admin__:readTablePage",rebuildCompanions:"__lunora_admin__:rebuildCompanions",recordAuthEvent:"__lunora_admin__:recordAuthEvent",recordContainerEvent:"__lunora_admin__:recordContainerEvent",recordMail:"__lunora_admin__:recordMail",recordQueueMessage:"__lunora_admin__:recordQueueMessage",releaseShardRegistration:"__lunora_admin__:releaseShardRegistration",replayQueueMessage:"__lunora_admin__:replayQueueMessage",retryOutboxEntry:"__lunora_admin__:retryOutboxEntry",resolveIssue:"__lunora_admin__:resolveIssue",revokeAdminToken:"__lunora_admin__:revokeAdminToken",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",sendWorkflowEvent:"__lunora_admin__:sendWorkflowEvent",setIssueSeverity:"__lunora_admin__:setIssueSeverity",storageOrphans:"__lunora_admin__:storageOrphans",storageReferences:"__lunora_admin__:storageReferences",storageRules:"__lunora_admin__:storageRules",studioFeatures:"__lunora_admin__:studioFeatures",verifyAdminToken:"__lunora_admin__:verifyAdminToken",writeRow:"__lunora_admin__:writeRow"},Z=50,y=500,ee=30,te=200,c="__doc__",x=e=>{try{const t=JSON.parse(e);return t!==null&&typeof t=="object"&&!Array.isArray(t)?t:void 0}catch{return}},ne=e=>{const{[A]:t,...n}=e;return t===void 0?n:t===null||typeof t!="object"||Array.isArray(t)?{[A]:t,...n}:{...n,...Q(t)}},re=(e,t)=>{if(!e.includes(c))return{columns:e,rows:t};const n=[];for(const a of t){const i=a[c],_=typeof i=="string"?x(i):void 0;if(_===void 0)return{columns:e,rows:t};const l=Object.fromEntries(Object.entries(a).filter(([m])=>m!==c));n.push({...l,...ne(_)})}const r=e.filter(a=>a!==c),o=[],s=new Set(r);for(const a of n)for(const i of Object.keys(a))s.has(i)||(s.add(i),o.push(i));return{columns:[...r,...o],rows:n}},S=e=>`instr(lower(CAST(${e} AS TEXT)), lower(?)) > 0`,k=(e,t,n)=>Math.min(Math.max(e,t),n),U=(e,t)=>{const n=e.exec(`SELECT COUNT(*) AS c FROM ${t}`).one();return Number(n.c)},Ue=e=>{const t=e.exec("SELECT name FROM sqlite_master WHERE type = 'table' ORDER BY name").toArray(),n=[];for(const{name:r}of t)w(r)||n.push({name:r,rowCount:U(e,u(r))});return n},q=(e,t)=>e.exec("SELECT name FROM sqlite_master WHERE type = 'table' AND name = ? LIMIT 1",t).toArray().length>0,C=(e,t)=>{if(w(t)||!q(e,t))throw new d("UNKNOWN_TABLE",`unknown table: ${t}`,{status:404})},N=(e,t)=>e.exec(`PRAGMA table_info(${t})`).toArray().map(n=>n.name),I={eq:"=",gt:">",gte:">=",lt:"<",lte:"<=",ne:"<>"},F=100,O=(e,t)=>{if(t>F)throw new d("BAD_REQUEST",`the query over ${e} binds ${String(t)} parameters, and a statement takes at most ${String(F)} — remove some filters or narrow the search`)},P=e=>typeof e=="string"?e:typeof e=="number"||typeof e=="boolean"?String(e):"",oe=new Set(["gt","gte","lt","lte"]),se=e=>e.operator==="contains"?P(e.value)==="":oe.has(e.operator)&&e.value==="",W=(e,t)=>{if(!t.every(n=>typeof n=="string"&&n!==""))throw new d("BAD_REQUEST",`nested path under ${e} must name each field with a non-empty string, got ${JSON.stringify(t)}`);return`$.${[e,...t].map(n=>V(n)).join(".")}`},T=(e,t,n=[])=>{const r=t.includes(e),o=t.includes(c);if(!(!r&&!o)){if(r){if(n.length>0)throw new d("BAD_REQUEST",`${e} is a physical column, so it has no nested path`);return{expression:u(e),params:[]}}return{expression:`json_extract(${u(c)}, ?)`,params:[W(e,n)]}}},ae=/^-?\d+$/u,v=(e,t)=>{const{value:n}=e;if(t==="bigint"&&(typeof n=="number"||typeof n=="string")){const r=typeof n=="number"&&Number.isInteger(n)?BigInt(n).toString():String(n).trim();if(!ae.test(r))throw new d("BAD_REQUEST",`bigint column ${e.column} can only be filtered by an integer, got ${JSON.stringify(n)}`);return L(BigInt(r))}if(t==="bigint"&&typeof n!="bigint")throw new d("BAD_REQUEST",`bigint column ${e.column} can only be filtered by an integer, got ${JSON.stringify(n)}`);return L(n)},ie=(e,t)=>t==="bigint"&&typeof e=="string"?z(e)??e:e,_e=e=>{if(typeof e=="boolean")return{params:[],sql:`j.type = '${e?"true":"false"}'`};if(typeof e=="string")return{params:[e],sql:"j.type = 'text' AND j.value = ?"};if(typeof e=="number"&&Number.isFinite(e))return{params:[e],sql:"j.type IN ('integer', 'real') AND j.value = ?"};throw new d("BAD_REQUEST",'"has" needs a string, number or boolean value to look for in the array')},le=(e,t,n)=>{if(t.includes(e.column))throw new d("BAD_REQUEST",`"has" needs an array-valued document field, but ${e.column} is a physical column`);if(!t.includes(c))return;const r=e.path??[];if(r.length===0&&n?.[e.column]==="bigint")throw new d("BAD_REQUEST",`"has" is not supported on bigint column ${e.column} — it stores a sort key, not an array`);const o=_e(e.value),s=W(e.column,r),a=u(c),i=`SELECT 1 FROM json_each(${a}, ?) AS j WHERE typeof(j.key) = 'integer' AND ${o.sql}`;return{params:[`${s}[0]`,s,...o.params,`${s}[1]`,`${s}[2]`,...o.params],sql:`CASE WHEN json_extract(${a}, ?) IS NOT '${R}' THEN EXISTS (${i}) WHEN json_extract(${a}, ?) IS 'arr' THEN EXISTS (${i}) ELSE 0 END`}},ce=e=>{if(!(e==null||typeof e=="string"||typeof e=="boolean"))try{return X(e)?JSON.stringify(G(e)):void 0}catch(t){throw new d("BAD_REQUEST",`this filter value cannot be compared: ${t instanceof Error?t.message:String(t)}`)}},ue=e=>typeof e=="number"?"'integer', 'real'":e?"'true'":"'false'",de=(e,t,n)=>{const r=ce(e.value);if(r!==void 0){if(e.operator!=="eq"&&e.operator!=="ne")throw new d("BAD_REQUEST",`a value nested under ${e.column} that holds a bigint, bytes, date, map or set can only be compared with = or <>, got ${e.operator}`);return{params:[...n,r],sql:`${t} ${I[e.operator]} ?`}}const{operator:o}=e;if(o==="gt"||o==="gte"||o==="lt"||o==="lte"){let s="'integer', 'real'";return typeof e.value=="string"?s="'text'":typeof e.value=="boolean"&&(s="'true', 'false'"),{params:[...n,...n,v(e,void 0)],sql:`(json_type(${u(c)}, ?) IN (${s}) AND ${t} ${I[o]} ?)`}}if((o==="eq"||o==="ne")&&(typeof e.value=="boolean"||typeof e.value=="number")){const s=`json_type(${u(c)}, ?) IN (${ue(e.value)}) AND ${t} = ?`,a=v(e,void 0);return o==="eq"?{params:[...n,...n,a],sql:`(${s})`}:{params:[...n,...n,...n,a],sql:`(${t} IS NOT NULL AND NOT (${s}))`}}},H=e=>{const t=`json_tree(${e})`;return`NOT (typeof(j.key) = 'integer' AND j.key IN (0, 1) AND EXISTS (SELECT 1 FROM ${t} AS f WHERE f.parent = j.parent AND f.key = 0 AND f.type = 'text' AND f.atom = '${R}') AND (WITH RECURSIVE links(node, k) AS (SELECT j.parent, 0 UNION ALL SELECT c.parent, links.k + 1 FROM links JOIN ${t} AS c ON c.id = links.node WHERE typeof(c.key) = 'integer' AND c.key = 2 AND ${((r,o)=>`(SELECT count(*) FROM ${t} AS ${r} WHERE ${r}.parent = ${o} AND typeof(${r}.key) = 'integer' AND ((${r}.key = 0 AND ${r}.atom = '${R}') OR (${r}.key = 1 AND ${r}.atom = 'arr'))) = 2`)("h","c.parent")}) SELECT max(k) FROM links) % 2 = 0)`},me=(e,t,n)=>({params:[t,t,n,t,t,n,t,t,n,t,t,t],sql:`CASE WHEN json_type(${e}, ?) IN ('text', 'integer', 'real') THEN ${S(`json_extract(${e}, ?)`)} WHEN json_type(${e}, ?) IN ('true', 'false') THEN ${S(`json_type(${e}, ?)`)} WHEN json_type(${e}, ?) IN ('array', 'object') THEN EXISTS (SELECT 1 FROM json_tree(${e}, ?) AS j WHERE j.type IN ('text', 'integer', 'real', 'true', 'false') AND ${S("CASE WHEN j.type IN ('true', 'false') THEN j.type ELSE j.value END")} AND ${H(`${e}, ?`)}) ELSE 0 END`}),fe=(e,{expression:t,kind:n,pathParameters:r,physical:o})=>{const s=e.path??[];if(n==="bigint")throw new d("BAD_REQUEST",`"contains" is not supported on bigint column ${e.column} — use =, <, > instead`);const a=P(e.value);return s.length===0&&o?{params:[a],sql:S(t)}:s.length===0?me(u(c),r[0],a):{params:[...r,...r,a],sql:`(json_type(${u(c)}, ?) IN ('text', 'integer', 'real') AND ${S(t)})`}},pe=(e,t,n)=>{if(e.operator==="has")return le(e,t,n);const r=e.path??[],o=T(e.column,t,r);if(o===void 0||se(e))return;const{expression:s,params:a}=o,i=t.includes(e.column)||r.length>0?void 0:n?.[e.column];if(e.operator==="contains")return fe(e,{expression:s,kind:i,pathParameters:a,physical:t.includes(e.column)});if(e.value===null&&(e.operator==="eq"||e.operator==="ne"))return{params:a,sql:`${s} IS ${e.operator==="ne"?"NOT ":""}NULL`};if(r.length>0){const _=de(e,s,a);if(_!==void 0)return _}return{params:[...a,v(e,i)],sql:`${s} ${I[e.operator]} ?`}},Ee=new Set(["date","timestamp"]),ge=[`$.${A}`,`$."${A}"`].map(e=>`substr(j.fullkey, 1, ${String(e.length+1)}) NOT IN ('${e}.', '${e}[')`).join(" AND "),Se=e=>`(${S(e)} AND EXISTS (SELECT 1 FROM json_tree(${e}) AS j WHERE j.type IN ('text', 'integer', 'real', 'true', 'false') AND ${S("CASE WHEN j.type IN ('true', 'false') THEN j.type ELSE j.value END")} AND ${ge} AND ${H(e)}))`,he=/["\\\u0000-\u001F]/u,ye=e=>he.test(e)?"":e,Te=/^(\d{4})(?:-(\d{2}))?(?:-(\d{2}))?$/u,be=e=>{const t=Te.exec(e.trim());if(t===null)return;const n=Number(t[1]),r=t[2]===void 0?void 0:Number(t[2]),o=t[3]===void 0?void 0:Number(t[3]);if(r!==void 0&&(r<1||r>12)||o!==void 0&&(o<1||o>31)||n<100)return;const s=Date.UTC(n,(r??1)-1,o??1);if(o!==void 0&&new Date(s).getUTCDate()!==o)return;let a;return o!==void 0?a=Date.UTC(n,(r??1)-1,o+1):r===void 0?a=Date.UTC(n+1,0,1):a=Date.UTC(n,r,1),{from:s,to:a}},M=(e,t,n,r)=>{const o=[],s=[];if(t!==""&&e.length>0){const a=e.map(_=>_===c?Se(u(_)):S(u(_)));s.push(...e.flatMap(_=>_===c?[ye(t),t]:[t]));const i=be(t);if(i!==void 0){for(const l of e)a.push(`(${u(l)} >= ? AND ${u(l)} < ?)`),s.push(i.from,i.to);const _=Object.keys(r??{}).filter(l=>!e.includes(l)&&Ee.has(r?.[l]??""));_.length>0&&e.includes(c)&&(a.push(`EXISTS (SELECT 1 FROM json_each(${u(c)}) AS j WHERE j.key IN (SELECT value FROM json_each(?)) AND j.type IN ('integer', 'real') AND j.value >= ? AND j.value < ?)`),s.push(JSON.stringify(_),i.from,i.to))}o.push(`(${a.join(" OR ")})`)}for(const a of n??[]){const i=pe(a,e,r);i!==void 0&&(o.push(`(${i.sql})`),s.push(...i.params))}return o.length===0?void 0:{parameters:s,where:o.join(" AND ")}},Ae=(e,t)=>{if(e===void 0)return;const n=T(e.column,t);if(n===void 0)return;const r=e.direction==="desc"?"DESC":"ASC";return{params:n.params,sql:`${n.expression} ${r}`}},qe=(e,t)=>{const{table:n}=t;C(e,n);const r=k(Math.trunc(t.limit??Z),1,y),o=Math.max(0,Math.trunc(t.offset??0)),s=u(n),a=N(e,s),i=t.search?.trim()??"",_=b=>{if(t.refs===void 0)return b;const $={};for(const D of b.columns){const j=t.refs[D];j!==void 0&&($[D]=j)}return Object.keys($).length>0?{...b,refs:$}:b},l=M(a,i,t.filters,t.columnKinds),m=Ae(t.orderBy,a),p=l===void 0?"":` WHERE ${l.where}`,g=m===void 0?"":` ORDER BY ${m.sql}`,E=l?.parameters??[],h=m?.params??[];O(n,E.length+h.length+2);let f;t.skipCount||(f=l===void 0?U(e,s):Number(e.exec(`SELECT COUNT(*) AS c FROM ${s}${p}`,...E).one().c));const B=e.exec(`SELECT * FROM ${s}${p}${g} LIMIT ? OFFSET ?`,...E,...h,r,o).toArray();return _({...re(a,B),sqlColumns:a,total:f})},Pe=(e,t)=>{const{table:n}=t;C(e,n);const r=k(Math.trunc(t.limit??y),1,y),o=u(n),s=N(e,o),a=t.search?.trim()??"";for(const f of t.filters??[])if(T(f.column,s,f.path??[])===void 0)throw new d("BAD_REQUEST",`unknown column: ${f.column}`);const i=M(s,a,t.filters,t.columnKinds);if(i===void 0&&(t.filters?.length??0)>0)throw new d("BAD_REQUEST",`the filters on ${n} are all empty, so the predicate constrains no rows — refusing to select the whole table`);const _=[],l=[];i!==void 0&&(_.push(i.where),l.push(...i.parameters)),t.after!==void 0&&(_.push("id > ?"),l.push(t.after));const m=_.length===0?"":` WHERE ${_.join(" AND ")}`,p=t.after===void 0?"":" ORDER BY id";O(n,l.length+1);const g=e.exec(`SELECT id FROM ${o}${m}${p} LIMIT ?`,...l,r+1).toArray(),E=g.length>r,h=g.slice(0,r).map(f=>f.id);return{hasMore:E,ids:h}},Ne=(e,t,n,r)=>{const o=new Set(n.filter(a=>a!==c));if(!n.includes(c))return o;for(const a of Object.keys(r??{}))o.add(a);const s=e.exec(`SELECT ${u(c)} AS doc FROM ${t} LIMIT ?`,y).toArray();for(const{doc:a}of s){const i=typeof a=="string"?x(a):void 0;if(i!==void 0)for(const _ of Object.keys(i))o.add(_)}return o},We=(e,t)=>{const{column:n,table:r}=t;C(e,r);const o=u(r),s=N(e,o);if(!Ne(e,o,s,t.columnKinds).has(n))throw new d("UNKNOWN_COLUMN",`unknown column: ${n}`,{status:404});const a=T(n,s);if(a===void 0)throw new d("UNKNOWN_COLUMN",`unknown column: ${n}`,{status:404});const i=k(Math.trunc(t.limit??ee),1,te),_=t.search?.trim()??"",l=M(s,_,t.filters,t.columnKinds),m=l===void 0?"":` WHERE ${l.where}`,p=l?.parameters??[];O(r,a.params.length*2+p.length+1);const g=e.exec(`SELECT ${a.expression} AS value, COUNT(*) AS count FROM ${o}${m} GROUP BY ${a.expression} ORDER BY count DESC LIMIT ?`,...a.params,...p,...a.params,i+1).toArray(),E=g.length>i,h=s.includes(n)?void 0:t.columnKinds?.[n];return{truncated:E,values:g.slice(0,i).map(f=>({count:Number(f.count),value:ie(f.value,h)}))}},He=(e,t,n)=>{const r={},o=n.slice(0,y);for(const s of o)r[s]=[];if(o.length===0)return{references:r,storageColumns:t};for(const[s,a]of Object.entries(t)){if(w(s)||!q(e,s))continue;const i=u(s),_=N(e,i);for(const l of a){const m=T(l,_);if(m===void 0)continue;const p=J("sqlite",Y(K.raw(m.expression),o,!1)),g=e.exec(`SELECT id, ${m.expression} AS ref FROM ${i} WHERE ${p.sql}`,...m.params,...m.params,...p.params).toArray();for(const E of g)r[E.ref]?.push({column:l,id:E.id,table:s})}}return{references:r,storageColumns:t}},Be=e=>{const n=e.filter(o=>o.authenticated!==!1).map((o,s)=>{const a=Object.values(o.subs??{}).map(i=>({args:i.args,functionPath:i.functionPath,table:i.table}));return{admin:o.admin===!0,id:s,subscriptions:a}}),r=n.reduce((o,s)=>o+s.subscriptions.length,0);return{connections:n,totalConnections:n.length,totalSubscriptions:r}},$e=20,Qe=()=>({maxMs:0,passes:0,peakSocketsIterated:0,socketsDelivered:0,socketsIterated:0,totalMs:0}),Xe=()=>({run:0,served:0}),Ge=()=>({drains:0,pairsSkipped:0}),Ke=(e,t,n)=>({drains:e.drains+t,pairsSkipped:e.pairsSkipped+n}),Ve=(e,t,n)=>({run:e.run+t,served:e.served+n}),Je=(e,t,n,r)=>({maxMs:Math.max(e.maxMs,r),passes:e.passes+1,peakSocketsIterated:Math.max(e.peakSocketsIterated,t),socketsDelivered:e.socketsDelivered+n,socketsIterated:e.socketsIterated+t,totalMs:e.totalMs+r}),Ye=(e,t=$e)=>{const n=new Map,r=new Map,o=e.filter(i=>i.authenticated!==!1);for(const i of o){for(const _ of Object.values(i.shapes??{})){const l=_.name??"(unknown shape)";n.set(l,(n.get(l)??0)+1)}for(const _ of i.whispers??[])r.set(_,(r.get(_)??0)+1)}const s=[...[...n].map(([i,_])=>({kind:"shape",subscribers:_,topic:i})),...[...r].map(([i,_])=>({kind:"whisper",subscribers:_,topic:i}))];return s.sort((i,_)=>_.subscribers-i.subscribers||i.topic.localeCompare(_.topic)),{peakSubscribers:s[0]?.subscribers??0,topics:s.slice(0,t),totalConnections:o.length}};export{xe as ADMIN_FUNCTIONS,je as ADMIN_FUNCTION_PREFIX,$e as DEFAULT_FANOUT_TOPIC_LIMIT,Fe as FLAGS_FUNCTION_PREFIX,y as MAX_PAGE_SIZE,Le as RELATION_FUNCTION_PREFIX,Qe as createFanoutCounters,Ge as createGlobalPollCounters,Xe as createShapeProbeCounters,be as datePrefixRange,We as facetColumn,He as findStorageReferences,w as isInternalTableName,se as isVacuousFilterClause,Ue as listTables,qe as readTablePage,Je as recordFanoutPass,Ke as recordGlobalPollPass,Ve as recordShapeProbePass,Pe as selectMatchingIds,Ye as summarizeFanoutTopics,Be as summarizeSubscriptions};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
const _="__lunora_admin_tokens__";export{_ as ADMIN_TOKEN_TABLE};
|
package/dist/packem_shared/{DEFAULT_MAX_RELAYS-B66neS_B.mjs → DEFAULT_MAX_RELAYS-Bc6PI-xy.mjs}
RENAMED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{toErrorBody as Y,LunoraError as G}from"@lunora/errors";import{encodeWire as q,stableWireKey as _,decodeWire as g}from"@lunora/wire";import{b as W,D as I,n as $,s as b,a as A,d as T,p as K,c as H}from"./relay-CKEdfUjH.mjs";import{sql as u}from"drizzle-orm";import{runDrizzle as m}from"./runDrizzle-RC09zZrh.mjs";import{WORKERD_SQLITE_LIMITS as B}from"./WORKERD_SQLITE_LIMITS-B_4w7tzY.mjs";import{d as j,w,a as L,m as X,r as z,b as V,c as J}from"./ctx-db-relay-shapes-DBobAek2.mjs";import{envPositiveInt as v}from"./envOptionalPositiveInt-D2pY-c64.mjs";import{encodeRowsPatch as Q,buildPokeFrames as D}from"./buildPokeFrames-WR-hp0mX.mjs";import{siblingStub as Z}from"./stubByName-
|
|
1
|
+
import{toErrorBody as Y,LunoraError as G}from"@lunora/errors";import{encodeWire as q,stableWireKey as _,decodeWire as g}from"@lunora/wire";import{b as W,D as I,n as $,s as b,a as A,d as T,p as K,c as H}from"./relay-CKEdfUjH.mjs";import{sql as u}from"drizzle-orm";import{runDrizzle as m}from"./runDrizzle-RC09zZrh.mjs";import{WORKERD_SQLITE_LIMITS as B}from"./WORKERD_SQLITE_LIMITS-B_4w7tzY.mjs";import{d as j,w,a as L,m as X,r as z,b as V,c as J}from"./ctx-db-relay-shapes-DBobAek2.mjs";import{envPositiveInt as v}from"./envOptionalPositiveInt-D2pY-c64.mjs";import{encodeRowsPatch as Q,buildPokeFrames as D}from"./buildPokeFrames-WR-hp0mX.mjs";import{siblingStub as Z}from"./stubByName-DQSivmvb.mjs";import{awaitWsDrain as ee,trySendFrame as M}from"./awaitWsDrain-DMcWBQ7I.mjs";import{verifySiblingBody as te,RELAY_SIGNATURE_HEADER as C,siblingSecretOf as se,signSiblingBody as re}from"./RELAY_SIGNATURE_HEADER-CAfC4tqg.mjs";const S="__lunora_relay_memos",oe=i=>{m(i,u`CREATE TABLE IF NOT EXISTS ${u.identifier(S)} (
|
|
2
2
|
connection_id TEXT NOT NULL,
|
|
3
3
|
sub_id TEXT NOT NULL,
|
|
4
4
|
cursor INTEGER NOT NULL,
|
|
@@ -0,0 +1,5 @@
|
|
|
1
|
+
import{LunoraError as w}from"@lunora/errors";import{ADMIN_TOKEN_TABLE as v}from"./ADMIN_TOKEN_TABLE-DfQ5osdI.mjs";const O="x",g=" ",x={'"':'"',"'":"'","[":"]","`":"`"},S=(e,t)=>{let n=t+2;for(;n<e.length&&e[n]!==`
|
|
2
|
+
`;)n+=1;return n},L=(e,t)=>{const n=e.indexOf("*/",t+2);return n===-1?-1:n+2},R=e=>{const t=e.split("");let n=0;for(;n<e.length;){const o=e[n]??"",r=x[o];if(o==="-"&&e[n+1]==="-"){const s=S(e,n);t.fill(g,n,s),n=s}else if(o==="/"&&e[n+1]==="*"){const s=L(e,n);if(s===-1)return;t.fill(g,n,s),n=s}else if(r!==void 0){let s=n+1;for(;s<e.length;)if(e[s]!==r)s+=1;else if(r!=="]"&&e[s+1]===r)s+=2;else break;if(s>=e.length)return;t.fill(O,n,s+1),n=s+1}else n+=1}for(let o=0;o<e.length;o+=1)e[o]===`
|
|
3
|
+
`&&(t[o]=`
|
|
4
|
+
`);return t.join("")},f=new Set([v,"dbstat","sqlite_dbpage"]),_="pragma_",C=e=>/[\p{L}_]/u.test(e)||(e.codePointAt(0)??0)>127,T=e=>/[\p{L}\p{N}_$]/u.test(e)||(e.codePointAt(0)??0)>127,b=/^pragma_\w+$/u,y=e=>f.has(e)||b.test(e)?e:void 0,h=e=>{if(f.has(e)||e.startsWith(_))return e},m=(e,t,n)=>{let o="",r=t+1;for(;r<e.length;){const s=e[r];if(s===n){if(n!=="]"&&e[r+1]===n){o+=n,r+=2;continue}return{end:r+1,text:o}}o+=s,r+=1}},E={'"':'"',"`":"`","[":"]"},u=e=>{const t=e.toLowerCase().replaceAll(/["'`[\]]/gu,"");for(const n of f)if(t.includes(n))return n;return/\bpragma_/u.test(t)?_:void 0},I=e=>{let t=0;for(;t<e.length;){const n=e[t];if(/\s/u.test(n))t+=1;else if(n==="-"&&e[t+1]==="-"){const o=e.indexOf(`
|
|
5
|
+
`,t);t=o===-1?e.length:o+1}else if(n==="/"&&e[t+1]==="*"){const o=e.indexOf("*/",t+2);if(o===-1)return u(e.slice(t+2));t=o+2}else if(n==="'"){const o=m(e,t,"'");if(o===void 0)return u(e.slice(t+1));const r=y(o.text.trim().toLowerCase());if(r!==void 0)return r;t=o.end}else if(n in E){const o=m(e,t,E[n]);if(o===void 0)return u(e.slice(t+1));const r=h(o.text.toLowerCase());if(r!==void 0)return r;t=o.end}else if(C(n)){let o=t+1;for(;o<e.length&&T(e[o]);)o+=1;const r=e.slice(t,o).toLowerCase(),s=h(r);if(s!==void 0)return s;t=o}else t+=1}},M=/^(?:explain\s+(?:query\s+plan\s+)?)?(?:select|with)\b/iu,Q=/\b(?:alter|attach|create|delete|detach|drop|insert|pragma|reindex|truncate|update|vacuum)\b|\breplace\b(?!\s*\()/iu,D=/^\w+/u,k=/;\s*$/u,P=/\s/u,$=e=>{let t=0;for(;t<e.length;){const n=e[t];if(n!==void 0&&P.test(n))t+=1;else if(n==="-"&&e[t+1]==="-")t=S(e,t);else if(n==="/"&&e[t+1]==="*"){const o=L(e,t);if(o===-1)break;t=o}else break}return t},A=e=>{const t=$(e),n=e.slice(t).trimEnd();if(n==="")return{code:"SQL_EMPTY",message:"the query is empty"};const r=(R(n)??n).replace(k,""),s=n.slice(0,r.length),i=r.indexOf(";");if(i!==-1)return{code:"SQL_MULTIPLE_STATEMENTS",length:1,message:"only a single statement may be run",offset:t+i};const a="the SQL editor is read-only — only SELECT / WITH / EXPLAIN queries are allowed";if(!M.test(s))return{code:"SQL_NOT_READONLY",length:D.exec(s)?.[0].length??1,message:a,offset:t};const c=Q.exec(s);if(c!==null)return{code:"SQL_NOT_READONLY",length:c[0].length,message:`${a} (\`${c[0].toUpperCase()}\` is not allowed)`,offset:t+c.index};const d=I(s);if(d!==void 0)return{code:"SQL_NOT_READONLY",message:`\`${d}\` is reserved framework storage and cannot be queried`}},U=1e3,p=e=>{const t=[];for(const n of e){if(t.length===U)return{items:t,truncated:!0};t.push(n)}return{items:t,truncated:!1}},Y=e=>{const t=new Map;return e.map(n=>{const o=(t.get(n)??0)+1;return t.set(n,o),o===1?n:`${n}:${String(o)}`})},W=e=>{const t=A(e);if(t!==void 0)throw new w(t.code,t.message,{status:400})},X=(e,t)=>{W(t);const n=e.exec(t),{columnNames:o,raw:r}=n;if(o===void 0||r===void 0){const{items:d,truncated:l}=p(n);return{columns:d.length>0?Object.keys(d[0]):[],rowCount:d.length,rows:d,truncated:l}}const s=Y(o),{items:i,truncated:a}=p(r.call(n)),c=i.map(d=>Object.fromEntries(s.map((l,N)=>[l,d[N]])));return{columns:s,rowCount:c.length,rows:c,truncated:a}},j=/near "([^"]*)": syntax error/iu,B=/^SCAN (?:TABLE )?(?!CONSTANT\b|SUBQUERY\b)([^\s(]+)/u,F=(e,t)=>{if(t==="")return{};const n=e.indexOf(t);return n===-1?{}:{length:t.length,offset:n}},G=(e,t)=>{const n=A(t);if(n!==void 0)return{diagnostics:n.code==="SQL_EMPTY"?[]:[{length:n.length,message:n.message,offset:n.offset,severity:"error",source:"gate"}],plan:[]};let o;try{o=e.exec(`EXPLAIN QUERY PLAN ${t}`).toArray().map(i=>{const{detail:a}=i;return typeof a=="string"?a:""}).filter(i=>i!=="")}catch(i){const a=i instanceof Error?i.message:String(i),c=j.exec(a);return{diagnostics:[{...c?F(t,c[1]??""):{},message:a,severity:"error",source:"syntax"}],plan:[]}}const r=[],s=new Set;for(const i of o){const a=B.exec(i);if(a){const c=a[1]??"";s.has(c)||(s.add(c),r.push({message:`full table scan on \`${c}\` — this query reads every row`,severity:"warning",source:"plan"}))}}return{diagnostics:r,plan:o}};export{U as MAX_SQL_ROWS,W as assertReadonly,G as lintReadonlySql,X as runReadonlySql};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{LunoraError as S}from"@lunora/errors";import{q as St}from"./MAX_TOKEN_LENGTH-iFEGEcDL-DBPC6ZWl.mjs";import{S as Un,l as qe,s as On}from"./fts-companion-CE3EmIjk.mjs";import{decodeWire as Gn,stableWireKey as Ut}from"@lunora/wire";import{sql as d}from"drizzle-orm";import{throwingScheduler as jn,aggregateSqlFunction as Pe,normalizeCountArgument as Hn}from"./AGGREGATE_SQL_FUNCTION-C_ZipS9R.mjs";import{aggregateTableName as st,encodeAggregateKey as ct,readAggregateValue as at}from"./aggregateTableName-B_CtIQCS.mjs";import{mergeWhere as Q,CountRlsUnsupportedError as dt,selectIndexForGroupBy as Kn,selectIndexForCount as Nn,selectIndexForAggregate as Qn}from"./CountRlsUnsupportedError-BvsDqfO2.mjs";import{backfillSearchIndexesForTable as Vn,searchIndexCoversTable as Jn}from"./backfillAggregateIndexes-Pk0KLrfk.mjs";import{backfillAggregateIndexes as Oi,backfillRankIndexes as Gi,backfillSearchIndexes as ji}from"./backfillAggregateIndexes-Pk0KLrfk.mjs";import{appendCdcChange as zn,readCdcDocAtOrBefore as Yn}from"./CDC_LOG_TABLE-BFGgqai8.mjs";import{CDC_LOG_TABLE as Ki,applyCdcChanges as Ni,bumpCdcEpoch as Qi,cdcCanVouchFor as Vi,cdcForkedError as Ji,cdcSeqLeavingRows as zi,cdcTouchesTables as Yi,cdcTrimmedError as Xi,compactCdcDocs as Zi,cursorBelowRetainedFloor as es,minCdcReplayableSeq as ts,minCdcSeq as ns,readCdcChangeKeys as os,readCdcChanges as rs,readCdcCursor as is,readCdcEpoch as ss,trimCdcChanges as cs}from"./CDC_LOG_TABLE-BFGgqai8.mjs";import{allocateCommitSeq as Xn,COMMIT_SEQ_FIELD as Zn}from"./COMMIT_SEQ_FIELD-Da1DjGqo.mjs";import{createCompanionSync as eo}from"./createCompanionSync-CEht4hXX.mjs";import{isMemoryTable as Ot}from"./clearMemoryTables-aMRERF0w.mjs";import{computeRankPage as Gt}from"./computeRankPage-BZIpATcs.mjs";import{SCAN_DEP as G}from"./SCAN_DEP-D7qE3iUe.mjs";import{runSql as he,runDrizzle as K}from"./runDrizzle-RC09zZrh.mjs";import{p as to,j as pt,D as ie,r as xe,W as no,k as le,b as Ue,A as lt,a as Oe,m as ue,e as fe,s as oo,t as ro,u as io,i as so,q as jt,h as $n,g as co}from"./do-sql-105TONaE.mjs";import{renderSql as mn,unionAll as Sn,WORKERD_SQLITE_LIMITS as Rn}from"./WORKERD_SQLITE_LIMITS-B_4w7tzY.mjs";import{a as ao,u as lo}from"./estimate-bytes-C-C35VXL.mjs";import{coveringGeohashes as uo,boundingBoxGeohashes as fo,haversineMeters as ho,pointInBoundingBox as wo}from"./GEO_DEFAULT_PRECISION-CqpQZ-J_.mjs";import{NotFoundError as po}from"./NotFoundError-BhF7FeFr.mjs";import{resolvePatch as go,assertPatchAllowed as yo,operatorFields as Eo,readPatchField as Ht}from"./assertPatchAllowed-CA_H466g.mjs";import{tiebreakDirectionFor as $o,encodeCursor as Qe,nullsOrderSuffix as mo,normalizeOrderKeys as Kt,uniqueIndexFields as So,buildSeekWhere as Ro,decodeCursor as Nt,buildSeekBeforeWhere as vo,softDeleteScope as Ae,applySelect as gt}from"./CURSOR_PREFIX-6offuG6M.mjs";import{rankTableName as Qt,sortColumnName as Vt,resolveRankPartition as _o,encodePartitionKey as To,RANK_TIEBREAK as Ao,rankPivotConditionSql as Io}from"./RANK_TIEBREAK-D3ye2GsL.mjs";import{UNVOUCHABLE_DEP as Jt}from"./UNVOUCHABLE_DEP-Ds9gxVqs.mjs";import{idIndexKey as xo,withUnknownIndexKeys as bo,indexKeysForRow as Co,buildIndexRange as Mo}from"./buildIndexRange-BTChxh3k.mjs";import{r as Ve,j as be,c as Z,t as Ye,i as zt}from"./where-sql-BjY4rnqb.mjs";import{serializeSqlValue as Ce}from"./serializeSqlValue-DeoBMpZ2.mjs";import{quoteIdentifier as Me}from"./quoteIdentifier-CObIFRhb.mjs";import{whereOfFilter as Do,isPushableWhere as ko}from"./isPushableWhere-BeYAOjUb.mjs";import{deriveRelationEdges as Lo,findRelated as Fo}from"./RELATED_DEFAULT_LIMIT-CVqN4JEu.mjs";import{assertFlatPredicate as ut,resolveRelationPredicates as Bo,composeReadPredicate as Wo}from"./DEFAULT_MAX_RELATION_KEYS-DfrMi_eE.mjs";import{describeRelationWrites as qo}from"./describeRelationWrites-omar6-u9.mjs";import{runRowValidators as Ge,transformOnlyDefinition as Po,applyInsertDefaults as yt,resolveWith as Yt,relationHooks as Xt,applyOnDelete as Uo,fanOutScalarCounts as Oo}from"./applyInsertDefaults-CVukTkQ5.mjs";import{guardWriter as Go}from"./RLS_UNWRAP_SYMBOL-H6J96vgK.mjs";import{mayHoldProjectedValue as jo}from"./BIGINT_KEY_DIGITS-DE6yshOt.mjs";import{createSystemReader as Ho}from"./createSystemReader-BSCxr8Qs.mjs";import{ConflictError as se}from"./ConflictError-C8GtJmjS.mjs";import{hasTrigger as Zt,runTriggers as Ko}from"./hasTrigger-CjlwI4le.mjs";import{advanceClientWatermark as ds,migrateClientWatermark as ls,readClientWatermark as us}from"./CLIENT_WATERMARK_TABLE-De7z_OHV.mjs";import{IDEMPOTENCY_TABLE as hs,readIdempotent as ws,trimIdempotent as ps,writeIdempotent as gs}from"./IDEMPOTENCY_TABLE-COrgeP3O.mjs";import{runShardMigrations as Es}from"./runShardMigrations-xu993yo2.mjs";import{selectShapeMembers as ms,selectShapeRows as Ss}from"./selectShapeMembers-Dqx_m7BF.mjs";const No=n=>{const r=atob(n),o=Uint8Array.from(r,s=>s.codePointAt(0)??0);return new TextDecoder().decode(o)},Qo=()=>new S("BAD_REQUEST","invalid cursor"),en=16,tn=8,z=1024,Rt=(n,r)=>r.query(n),Vo=(n,r)=>{if(n.length===0)return 0;let o=0;for(const[s,c]of r.entries()){const u=s===r.length-1;let g=0;for(const $ of n)(u?$.startsWith(c):$===c)&&(g+=1);if(g===0)return 0;o+=g}return o},Jo=(n,r)=>{if(!r)return{exact:!0,lower:n,upper:n};const o=[...n].at(-1)??"",s=(o.codePointAt(0)??0)+1;if(s>=55296&&s<=57343||s>1114111)return{exact:!0,lower:n,upper:n};const c=n.slice(0,n.length-o.length);return{exact:!1,lower:n,upper:c+String.fromCodePoint(s)}},zo=(n,r,o)=>{const s={eq:(c,u)=>{if(!n.definition.filterFields?.includes(c))throw new S("INTERNAL",`field "${c}" is not a filter field of search index "${n.indexName}" on table "${r}"`);if(n.filters.length>=tn)throw new S("BAD_REQUEST",`search index "${n.indexName}" on table "${r}": at most ${String(tn)} .eq() filters are supported per search query`);return n.filters.push({field:c,value:u}),s},search:(c,u)=>{const g=n;if(c!==g.definition.field)throw new S("INTERNAL",`search index "${g.indexName}" on table "${r}" indexes "${g.definition.field}", not "${c}"`);const $=Rt(u,o).length;if($>en)throw new S("BAD_REQUEST",`search index "${g.indexName}" on table "${r}": at most ${String(en)} search terms are supported (got ${String($)})`);return g.field=c,g.query=u,g.hasQuery=!0,s}};return s},Yo=n=>{if(n.length>z)throw new S("BAD_REQUEST",`more than ${String(z)} documents match this search — narrow it with filters or read it a page at a time with .paginate()`)},Xo=n=>Math.min(n.offset+n.numItems+1,z),Zo=n=>btoa(`search:${String(n)}`),er=n=>{let r;try{r=No(n)}catch{return}if(!r.startsWith("search:"))return;const o=Number(r.slice(7));return Number.isInteger(o)&&o>=0?o:void 0},tr=n=>{if(typeof n.endCursor=="string")throw new S("BAD_REQUEST","bounded (endCursor) pagination is not supported on search queries — relevance order has no stable range boundary");if(!Number.isFinite(n.numItems))throw new S("BAD_REQUEST",`search pagination needs a finite numItems, got ${String(n.numItems)}`);const r=Math.max(0,Math.floor(n.numItems)),o=n.cursor?er(n.cursor):0;if(o===void 0)throw Qo();if(o+r>=z)throw new S("BAD_REQUEST",`search pagination reaches the ${String(z)}-document limit (offset ${String(o)} + ${String(r)} requested) — a page must end below the cap so the probe row that answers \`hasMore\` still fits: retry with numItems ${String(Math.max(1,z-o-1))} or fewer, or narrow the query or the filters instead`);return{numItems:r,offset:o}},nr=(n,r)=>{const o=r.offset+r.numItems,s=r.numItems>0&&n.length>o;return{continueCursor:s?Zo(o):null,isDone:!s,page:n.slice(r.offset,o)}},or=n=>{if(n===void 0)return z+1;if(!Number.isFinite(n))return z;const r=Math.max(0,Math.floor(n));if(r>z)throw new S("BAD_REQUEST",`search returns at most ${String(z)} documents (asked for ${String(r)}) — narrow the query or paginate instead`);return r},vn=500,_n=(n,r,o)=>{if(n!==void 0&&n!==Number.POSITIVE_INFINITY&&(!Number.isInteger(n)||n<0))throw o(`${r}: batch limit must be a non-negative integer`);return n??vn},Tn=(n,r,o,s)=>{if(n>r)throw s(`${o}: batch of ${String(n)} exceeds the limit of ${String(r)} (raise options.limit or chunk the call)`)},rr=32,ir=1024,An=(n,r,o,s)=>{const c=`SELECT id, _creationTime, ${Me(ie)} FROM ${Me(n)}`,u=`ORDER BY ${o}${s===void 0?"":` LIMIT ${String(s)}`}`;return r===void 0?Ve(`${c} ${u}`):be(`${c} WHERE `,r,` ${u}`)},Xe={fieldRef:n=>Ve(pt(n)),rangeTypeGuard:(n,r)=>Ve(to(n,r)),serialize:Ce},sr=n=>n===void 0?"":mo(n==="first"),In=n=>{const r=n.map(o=>`${pt(o.field)} ${o.direction==="desc"?"DESC":"ASC"}${sr(o.nulls)}`);return n.some(o=>o.field==="_id"||o.field==="id")||r.push(`${pt("id")} ${$o(n)==="desc"?"DESC":"ASC"}`),r.join(", ")},cr={"<":"lt","<=":"lte","=":"eq",">":"gt",">=":"gte"},xn=n=>new Set(n.sqlConditions.filter(r=>r.comparator==="=").map(r=>r.field)),ar=n=>{const r=xn(n);let o=0;for(;o<n.indexFields.length&&r.has(n.indexFields[o]??"");)o+=1;return n.indexFields.slice(o)},dr=(n,r)=>{const o=n.order,s=ar(n),{shape:c}=r;return s.length>0?Kt(s.map(u=>({[u]:o})),c,{pinned:xn(n),uniqueBy:So(r.indexes,c)}):Kt([{_creationTime:o}],c)},lr=(n,r,o,s)=>{const c=n.sqlConditions.map(u=>({[u.field]:{[cr[u.comparator]??"eq"]:u.value}}));if(o&&c.push(Ro(r,Nt(o))),s&&c.push(vo(r,Nt(s))),c.length!==0)return c.length===1?c[0]:{AND:c}},ur=n=>{if(n.want!==void 0)return n.selective?Math.max(n.want,rr):n.want},Et=(n,r,o,s,c,u,g)=>{const $=dr(s,o),y=In($),a=[],{filters:M,want:T}=u;let v=u.cursor??void 0,x=ur(u);if(T===0)return{documents:a,orderKeys:$};for(;;){const W=Z(lr(s,$,v,u.endCursor),Xe,Ye),P=An(r,c&&W?be(W," AND ",c):c??W,y,x),B=he(n,P.text,...P.params).toArray();let U={};g(B.length);for(const j of B)if(U=xe(j),M.every(ee=>ee(U))&&a.push(U)===T)return{documents:a,orderKeys:$};if(x===void 0||B.length<x)return{documents:a,orderKeys:$};v=Qe(U,$),x=Math.max(x,Math.min(x*2,ir))}},fr=(n,r,o,s,c,u,g,$)=>{const y=Math.max(0,Math.floor(c.numItems));if(typeof c.endCursor=="string"){const{documents:W,orderKeys:P}=Et(n,r,o,s,u,{cursor:c.cursor,endCursor:c.endCursor,filters:g.all,selective:g.selective,want:void 0},$),B=W.length>=2?W[Math.floor(W.length/2)-1]:void 0;return{continueCursor:c.endCursor,isDone:!0,page:W,splitCursor:B?Qe(B,P):null}}const{documents:a,orderKeys:M}=Et(n,r,o,s,u,{cursor:c.cursor,filters:g.all,selective:g.selective,want:y+1},$),T=a.length>y,v=T?a.slice(0,y):a,x=v.at(-1);return{continueCursor:T&&x?Qe(x,M):null,isDone:!T,page:v}},Ze=n=>{const r=new Map;return o=>{const s=r.get(o);if(s!==void 0)return s;const c=n(Me(o));return r.set(o,c),c}},we=Me(ie),hr=Ze(n=>`INSERT INTO ${n} (id, _creationTime, ${we}) VALUES (?, ?, ?)`),nn=Ze(n=>`UPDATE ${n} SET ${we} = ? WHERE id = ? AND ${we} = ?`),wr=Ze(n=>`UPDATE ${n} SET _creationTime = ?, ${we} = ? WHERE id = ? AND ${we} = ?`),pr=Ze(n=>`DELETE FROM ${n} WHERE id = ? AND ${we} = ?`),gr="SELECT changes() AS changed",on=new Map,yr="",Er=n=>{const r=JSON.stringify(n),o=on.get(r);if(o!==void 0)return o;const s=n.map(u=>d`SELECT ${d.raw(`'${u.replaceAll("'","''")}'`)} AS __t__, id, _creationTime, ${d.identifier(ie)} FROM ${d.identifier(u)} WHERE id = ${yr}`),{sql:c}=mn("sqlite",d`${Sn(s)} LIMIT 1`);return on.set(r,c),c},$r=(n,r)=>r.map(()=>n),mr=/^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/iu,Sr=n=>{if(!mr.test(n))throw new S("INTERNAL",`invalid clientId ${JSON.stringify(n)}: a client-supplied row id must be a UUID`)},$t=n=>{if(n.includes("\0"))throw new S("BAD_REQUEST",`invalid row id ${JSON.stringify(n)}: a row id cannot hold a NUL character (U+0000)`)},Rr=(n,r,o,s)=>{if(o!==!0)return;const c=n!==void 0&&"serverDefault"in(n.shape._id?._meta?.column??{});for(const u of r){const g=c?yt(n,u,s)._id:u._id;typeof g=="string"&&$t(g)}},rn=50,je=Math.floor(Rn.boundParams/3),sn=Rn.boundParams,vr=128,Je=n=>new S("BATCH_LIMIT_EXCEEDED",n,{status:400}),He=(n,r,o)=>{Tn(n,_n(r,o,Je),o,Je)},cn=async(n,r,o,s,c)=>{const u=_n(s,c,Je),{page:g}=await n.findMany(r,Number.isFinite(u)?{limit:u+1,omitContinueCursor:!0,where:o}:{where:o});return g.length>u&&Tn(Math.max(await n.count(r,{where:o}),g.length),u,c,Je),g},_r=n=>{const r={eq:(o,s)=>(n.sqlConditions.push({comparator:"=",field:o,value:s}),r),gt:(o,s)=>(n.sqlConditions.push({comparator:">",field:o,value:s}),r),gte:(o,s)=>(n.sqlConditions.push({comparator:">=",field:o,value:s}),r),lt:(o,s)=>(n.sqlConditions.push({comparator:"<",field:o,value:s}),r),lte:(o,s)=>(n.sqlConditions.push({comparator:"<=",field:o,value:s}),r)};return r},Tr=n=>Math.max(n,z),bn=(n,r)=>{const o=n.filters.map(s=>d`${fe(s.field)} = ${Ce(s.value)}`);return r&&o.push(r),o},Ar=(n,r,o,s,c)=>{const u=Rt(o.query,St(o.definition.language));if(u.length===0)return[];const g=Un(r,o.indexName),$=`${g}__vocab`,y=u.length-1,a=u.map((P,B)=>{const U=Jo(P,B===y),j=U.exact?d`${d.identifier("term")} = ${U.lower}`:d`${d.identifier("term")} >= ${U.lower} AND ${d.identifier("term")} < ${U.upper}`;return d`SELECT ${d.identifier("doc")}, ${d.raw(String(B))} AS ${d.identifier("__term__")}, COUNT(*) AS ${d.identifier("__n__")} FROM ${d.identifier($)} WHERE ${j} GROUP BY ${d.identifier("doc")}`}),M=u.map((P,B)=>d`SUM(CASE WHEN u.${d.identifier("__term__")} = ${d.raw(String(B))} THEN u.${d.identifier("__n__")} ELSE 0 END)`),T=d`SELECT f.${d.identifier(qe)} AS ${d.identifier(qe)}, ${d.join(M,d` + `)} AS ${d.identifier("__score__")} FROM (${Sn(a)}) u JOIN ${d.identifier(g)} f ON f.rowid = u.${d.identifier("doc")} GROUP BY f.${d.identifier(qe)} HAVING ${d.join(M.map(P=>d`${P} > 0`),d` AND `)}`,v=bn(o,c);let x=d`SELECT m.id, m._creationTime, m.${d.identifier(ie)}, s.${d.identifier("__score__")} AS ${d.identifier("__score__")} FROM (${T}) s JOIN ${d.identifier(r)} m ON m.id = s.${d.identifier(qe)}`;v.length>0&&(x=d`${x} WHERE ${d.join(v,d` AND `)}`),x=d`${x} ORDER BY s.${d.identifier("__score__")} DESC, m._creationTime DESC, m.id ASC LIMIT ${d.raw(String(s))}`;const W=[];for(const P of K(n,x)){const B=$n(P);if(B){const U=P.__score__;W.push({document:B,score:typeof U=="number"?U:Number(U??0)})}}return W},Ir=(n,r,o,s,c)=>{const u=St(o.definition.language),g=Rt(o.query,u);if(g.length===0)return[];const $=bn(o,c);let y=d`SELECT id, _creationTime, ${d.identifier(ie)} FROM ${d.identifier(r)}`;$.length>0&&(y=d`${y} WHERE ${d.join($,d` AND `)}`),y=d`${y} ORDER BY _creationTime DESC, id ASC LIMIT ${d.raw(String(Tr(s)))}`;const a=K(n,y).toArray(),M=[];for(const T of a){const v=$n(T);if(!v)continue;const x=Vo(On(v,o.definition),g);x>0&&M.push({creationTime:typeof v._creationTime=="number"?v._creationTime:0,doc:v,id:typeof v._id=="string"?v._id:"",score:x})}return M.sort((T,v)=>v.score-T.score||v.creationTime-T.creationTime||T.id.localeCompare(v.id)),M.slice(0,s).map(T=>({document:T.doc,score:T.score}))},ft=(n,r,o,s)=>{if(!Number.isFinite(n.lat)||n.lat<-90||n.lat>90||!Number.isFinite(n.lng)||n.lng<-180||n.lng>180)throw new S("BAD_REQUEST",`geo index "${s}" on table "${o}": ${r} must have a finite lat in [-90, 90] and lng in [-180, 180]`)},xr=(n,r)=>{const o=n,s={near:(c,u)=>{if(o.within)throw new S("INTERNAL",`geo index "${o.indexName}" on table "${r}": call .near() or .within(), not both`);if(ft(c,".near() point",r,o.indexName),!Number.isFinite(u)||u<=0)throw new S("BAD_REQUEST",`geo index "${o.indexName}" on table "${r}": .near() radiusMeters must be a finite number > 0, got ${String(u)}`);return o.near={point:{lat:c.lat,lng:c.lng},radiusMeters:u},s},within:c=>{if(o.near)throw new S("INTERNAL",`geo index "${o.indexName}" on table "${r}": call .near() or .within(), not both`);if(ft(c.sw,".within() sw corner",r,o.indexName),ft(c.ne,".within() ne corner",r,o.indexName),c.sw.lat>c.ne.lat)throw new S("BAD_REQUEST",`geo index "${o.indexName}" on table "${r}": .within() corners are transposed (sw.lat > ne.lat)`);if(c.sw.lng>c.ne.lng)throw new S("BAD_REQUEST",`geo index "${o.indexName}" on table "${r}": .within() box crosses the antimeridian (sw.lng > ne.lng), which is not supported — split it into two boxes at ±180 and union the results`);return o.within={ne:{lat:c.ne.lat,lng:c.ne.lng},sw:{lat:c.sw.lat,lng:c.sw.lng}},s}};return s},br=(n,r)=>{const o=n[r];if(o===null||typeof o!="object")return;const{lat:s,lng:c}=o;return typeof s=="number"&&typeof c=="number"?{lat:s,lng:c}:void 0},Cr=(n,r)=>{const o=br(n,r.definition.field);if(!o)return;const s=typeof n._creationTime=="number"?n._creationTime:0;if(r.near){const c=ho(r.near.point,o);return c<=r.near.radiusMeters?{creationTime:s,distance:c}:void 0}return wo(o,r.within)?{creationTime:s,distance:0}:void 0},Mr=(n,r,o,s)=>{if(!o.near&&!o.within)throw new S("INTERNAL",`geo index "${o.indexName}" on table "${r}": call .near(point, radius) or .within(box)`);const c=o.near?uo(o.near.point,o.near.radiusMeters):fo(o.within),u=co(r,o.indexName),g=c.map(T=>d`(g.${d.identifier("__geohash__")} >= ${T} AND g.${d.identifier("__geohash__")} < ${`${T}{`})`),$=[d`(${d.join(g,d` OR `)})`];s&&$.push(s);const y=d`SELECT m.id, m._creationTime, m.${d.identifier(ie)} FROM ${d.identifier(u)} g JOIN ${d.identifier(r)} m ON m.id = g.${d.identifier("__id__")} WHERE ${d.join($,d` AND `)}`,a=K(n,y).toArray(),M=[];for(const T of a){const v=xe(T),x=v?Cr(v,o):void 0;v&&x&&M.push({creationTime:x.creationTime,distance:x.distance,doc:v})}return M.sort((T,v)=>T.distance-v.distance||v.creationTime-T.creationTime),M},Cn=(n,r,o,s)=>{const c=[];for(const u of n)if(r.every(g=>g(s(u)))&&(c.push(u),typeof o=="number"&&c.length>=o))break;return c},Dr=(n,r,o,s,c,u=()=>{})=>{const g=o.within!==void 0,$=Mr(n,r,o,c).map(y=>({distanceMeters:g?null:y.distance,document:y.doc}));return u($.length),typeof s=="number"?$.slice(0,Math.max(0,Math.floor(s))):$},an=(n,r,o,s,c,u,g=()=>{})=>{const{geo:$}=o;if(!$)throw new S("INTERNAL","runGeoTerminalScored called without a staged geo query");const y=c.length>0,a=Dr(n,r,$,y?void 0:u,s,g);return y?Cn(a,c,u,M=>M.document):a},dn=(n,r,o)=>{const s=n.shape[r];if(s!==void 0&&jo(s))throw new S("BAD_REQUEST",`${o}: "${r}" may hold an order-preserving key rather than a value SQL can reduce or group — declare an aggregateIndex covering this (by, field, op) so the maintained companion answers it instead (its running total is a REAL, so it stays exact only while the total is inside 2^53)`)},kr=n=>{let r=0;const o=[],s={...Xe,relationExists:c=>{const{childWhere:u,negated:g,parentTable:$,relation:y}=c,a=`__rel_${String(r)}`,M=o.at(-1)??$;r+=1,n(y.table,G);const T=y.kind==="one"?y.field:y.references,v=y.kind==="one"?y.references:y.field,x=Ve(`${jt(a,v)} = ${jt(M,T)}`);o.push(a);const W=Z(u,s,Ye);o.pop();const P=W===void 0?x:be(x," AND ",W),B=be("EXISTS (SELECT 1 FROM ",zt(y.table)," AS ",zt(a)," WHERE ",P,")");return g?be("NOT ",B):B}};return s};class Lr extends S{constructor(r="unique() found more than one matching document"){super("NOT_UNIQUE",r,{name:"NotUniqueError"})}}const Fr=/\s/u,Br=String.fromCodePoint(0),ln=(n,r,o)=>{if(!n.tables[r])throw new S("INTERNAL",`unknown table: ${r}`);return typeof o!="string"||o.length===0||Fr.test(o)||o.includes(Br)?null:o},Mn=(n,r,o,s=()=>{},c=()=>{},u=()=>{},g)=>{const $=r.tables[o];if(!$)throw new S("INTERNAL",`unknown table: ${o}`);const y=Ae($.softDeleteMode,void 0),a=g??{indexFields:[],indexName:void 0,inMemoryFilters:[],order:"asc",sqlConditions:[],verifyFilters:[]},M=()=>{const R=Q(y,a.pushedWhere);return R?Z(R,ue):void 0},T=()=>{const R=Q(y,a.pushedWhere);return R?Z(R,Xe,Ye):void 0},v=()=>[...a.inMemoryFilters,...a.verifyFilters];let x=0;const W=R=>{const{search:C}=a;if(!C)throw new S("INTERNAL","runSearchFetch called without a staged search");Vn(io(n),o,$);const L=a.inMemoryFilters.length>0,F=or(L?void 0:R),k=so(n);if(k&&!Jn(n,o,C.definition))throw new S("SEARCH_INDEX_BUILDING",`search index "${C.indexName}" on table "${o}" is still backfilling and currently covers only part of the table — retry once it finishes, or run the backfillSearch admin operation to complete it now`);const pe=M(),te=k?Ar(n,o,C,F,pe):Ir(n,o,C,F,pe);!L&&R===void 0&&Yo(te);const ge=v();return x=te.length,ge.length>0?Cn(te,ge,R,J=>J.document):te},P=R=>W(R).map(C=>C.document),B=R=>{const C=tr(R);return nr(P(Xo(C)),C)},U=()=>{if(a.search||a.geo||a.indexName===void 0){c(void 0);return}c(Mo(o,a.indexName,a.indexFields,a.sqlConditions,Ce))},j=R=>{U();let C=0;const L=(()=>{if(a.search){const F=P(R);return C=x,F}return a.geo?an(n,o,a,M(),v(),R,F=>{C=F}).map(F=>F.document):Et(n,o,$,a,T(),{filters:v(),selective:a.inMemoryFilters.length>0,want:R===void 0?void 0:Math.max(0,Math.floor(R))},F=>{C+=F}).documents})();return u(Math.max(C,L.length)),L},ee=()=>{if(!a.search&&!a.geo)throw new S("INTERNAL",`ctx.db.query("${o}").collectWithScores() requires a staged .withSearchIndex(...) or .withGeoIndex(...)`);U();let R=0;const C=(()=>{if(a.search){const L=W(void 0);return R=x,L}return an(n,o,a,M(),v(),void 0,L=>{R=L})})();return u(Math.max(R,C.length)),C},N={async*[Symbol.asyncIterator](){const R=Mn(n,r,o,s,c,u,{...a,indexFields:[...a.indexFields],inMemoryFilters:[...a.inMemoryFilters],sqlConditions:[...a.sqlConditions],verifyFilters:[...a.verifyFilters]});if(a.search){yield*await R.collect();return}let C;for(;;){const L=await R.paginate({cursor:C??null,numItems:vr});if(yield*L.page,L.isDone||L.continueCursor===null)return;C=L.continueCursor}},async collect(){return j(void 0)},async collectWithScores(){return ee()},filter(R){const C=Do(R);return C!==void 0&&ko(C,$.shape)?(a.pushedWhere=Q(a.pushedWhere,C),a.verifyFilters.push(R)):a.inMemoryFilters.push(R),N},async first(){return j(1)[0]??null},order(R){return a.order=R==="desc"?"desc":"asc",N},async paginate(R){let C=0;if(U(),a.search){const F=B(R);return u(F.page.length),F}if(a.geo)throw new S("INTERNAL","pagination is not supported on geo queries; use .take(n) or .collect()");const L=fr(n,o,$,a,R,T(),{all:v(),selective:a.inMemoryFilters.length>0},F=>{C+=F});return u(Math.max(C,L.page.length)),L},async take(R){return j(R)},async unique(){const R=j(2);if(R.length>1)throw new Lr(`unique() on table "${o}" matched ${String(R.length)} documents; expected at most one`);return R[0]??null},withGeoIndex(R,C){const L=($.geoIndexes??[]).find(k=>k.name===R);if(!L)throw new S("INTERNAL",`unknown geo index "${R}" on table "${o}"`);s(o,R,"geo");const F={definition:L,indexName:R};if(a.geo=F,C(xr(F,o)),!F.near&&!F.within)throw new S("INTERNAL",`geo index "${R}" on table "${o}" requires a .near(point, radius) or .within(box) call`);return N},withIndex(R,C){const L=$.indexes.find(F=>F.name===R);if(!L)throw new S("INTERNAL",`unknown index "${R}" on table "${o}"`);return s(o,R,"index"),a.indexName=R,a.indexFields=L.fields,C&&C(_r(a)),N},withSearchIndex(R,C){const L=($.searchIndexes??[]).find(k=>k.name===R);if(!L)throw new S("INTERNAL",`unknown search index "${R}" on table "${o}"`);s(o,R,"search");const F={definition:L,field:L.field,filters:[],hasQuery:!1,indexName:R,query:""};if(a.search=F,C(zo(F,o,St(L.language))),!F.hasQuery)throw new S("INTERNAL",`search index "${R}" on table "${o}" requires a .search(field, query) call`);return N}};return N},ht=(n,r,o,s)=>{const c=o;for(const[u,g]of ro(n)){if(g.serverDefault){u in r&&(c[u]=g.serverDefault({auth:s}));continue}g.onUpdateFn&&!(u in r)&&(c[u]=g.onUpdateFn())}},un=5,fn=(n,r)=>{for(const o of Object.keys(r))if(r[o]===void 0)throw new S("INTERNAL",`Cannot ${n} field '${o}' to undefined — use null to clear a nullable field, or omit the key to leave it unchanged.`)},hn=["_commitSeq","_creationTime","_id"],Ke=n=>hn.some(r=>r in n)?Object.fromEntries(Object.entries(n).filter(([r])=>!hn.includes(r))):n,Wr=/unique constraint failed/i,qr=n=>n instanceof Error&&Wr.test(n.message),Pr=/string or blob too big/iu,Ur=(n,r)=>{if(!(!(n instanceof Error)||!Pr.test(n.message)))throw new S("PAYLOAD_TOO_LARGE",`document is too large to store in "${r}": a single row cannot exceed the storage engine's per-row ceiling (2 MB on a Durable Object's SQLite). The limit is on the STORED bytes, which are UTF-8, and v.bytes()/v.bigint() columns are stored twice on a shard-local table. Keep the payload in R2 (ctx.storage) and store a reference on the row.`)},mt=(n,r,o,s)=>{try{he(n,o,...s)}catch(c){throw qr(c)?new se(`unique constraint violation on "${r}"`,"unique"):(Ur(c,r),c)}},Ne=(n,r,o,s)=>{if(mt(n,r,o,s),he(n,gr).one().changed===0)throw new se(`optimistic concurrency conflict on "${r}" — the row changed during this mutation; refetch and retry`,"occ")},wn=(n,r,o,s,c,u,g)=>{const $=[];for(let T=0;T<o.length+1;T+=1){const v=o[T],x=s[T],W=x?.direction==="desc"?"desc":"asc",P=v===void 0||x===void 0?d`${d.identifier(Ao)} < ${g}`:Io(v,u[T],W,!1);if(P===void 0)continue;const B=[];for(let j=0;j<T;j+=1)B.push(d`${d.identifier(o[j])} IS ${u[j]}`);B.push(P);const[U]=B;$.push(B.length===1&&U!==void 0?U:d`(${d.join(B,d` AND `)})`)}const y=$.length>0?d.join($,d` OR `):d`1 = 0`,a=K(n,d`SELECT COUNT(*) AS c FROM ${d.identifier(r)} WHERE ${d.identifier("__partition__")} = ${c} AND (${y})`).one(),M=K(n,d`SELECT COUNT(*) AS c FROM ${d.identifier(r)} WHERE ${d.identifier("__partition__")} = ${c}`).one();return{before:a.c,total:M.c}},Or=n=>{const r=new Map;for(const[s,c]of Object.entries(n.tables))for(const u of Object.values(c.relationMap??{}))u.kind==="one"&&(u.onDelete==="cascade"||u.onDelete==="set null")&&r.set(u.table,[...r.get(u.table)??[],{holder:s,op:u.onDelete==="cascade"?"delete":"update"}]);const o=s=>{const c=new Set,u=[s];for(let g=u.pop();g!==void 0;g=u.pop())for(const{holder:$,op:y}of r.get(g)??[]){if($===s||Zt(n,$,y))return!0;c.has($)||(c.add($),u.push($))}return!1};return new Set(Object.entries(n.tables).filter(([s,c])=>c.shardMode?.kind==="global"||Zt(n,s,"delete")||o(s)).map(([s])=>s))},Gr=n=>{const r=new Map;for(const[o,s]of Object.entries(n.tables))s.softDeleteMode&&r.set(o,s.softDeleteMode.field);return r},wt=new WeakMap,jr=(n,r)=>{let o=wt.get(r.tables);if(!wt.has(r.tables)){const c=Object.keys(r.tables).map(u=>u.replaceAll(/[$()*+.?[\\\]^{|}]/gu,String.raw`\$&`));o=c.length===0?void 0:new RegExp(`"(${c.join("|")})"`,"gu"),wt.set(r.tables,o)}if(o===void 0)return;const s=new Set;for(const c of n.matchAll(o))s.add(c[1]);return s.size===1?[...s][0]:void 0},Hr=(n,r,o)=>{for(const s of n){const c=s,u=c?.[ie];if(typeof u=="string"){const g=c?.id,$=lo(u);typeof g!="string"?r.recordReadBytes($):o===void 0?r.recordDocumentRead(`${g}\0${String($)}`,$):r.recordDocumentRead(`${o}\0${g}`,$)}}},Kr=(n,r,o)=>{if(r===void 0)return n;const s=(c,...u)=>{const g=n.exec(c,...u),$=g.one.bind(g),y=g[Symbol.iterator].bind(g),a=o===void 0?void 0:jr(c,o);let M=!1;const T=v=>{Hr(v,r,a)};return g.toArray=()=>{const v=[];for(const x of{[Symbol.iterator]:y})T([x]),v.push(x);return v},g.one=()=>{M=!0;try{const v=$();return T([v]),v}finally{M=!1}},g[Symbol.iterator]=function*(){for(const x of{[Symbol.iterator]:y})M||T([x]),yield x},g};return new Proxy(n,{get:(c,u)=>u==="exec"?s:u===no?c:Reflect.get(c,u,c)})},Nr=new Map([["findFirst","rows"],["findFirstOrThrow","rows"],["findMany","page"],["get","rows"],["lookupById","lookup"],["rankPage","page"]]),Qr=new Map([["collect","rows"],["collectWithScores","scored"],["first","rows"],["paginate","page"],["take","rows"],["unique","rows"]]),Ie=(n,r,o)=>{if(typeof n!="object"||n===null)return;const s=ao(n);if(s===void 0)return;const c=n._id;typeof c=="string"?o.recordDocumentRead(`global\0${r}\0${c}`,s):o.recordReadBytes(s)},ze=(n,r,o,s)=>{if(typeof n!="object"||n===null)return;const c=n;switch(r){case"lookup":{Ie(c.row,typeof c.tableName=="string"?c.tableName:o,s);return}case"page":{for(const u of c.page??[])Ie(u,o,s);return}case"rows":{for(const u of Array.isArray(n)?n:[n])Ie(u,o,s);return}default:for(const u of Array.isArray(n)?n:[])Ie(u.document,o,s)}},Dn=(n,r,o)=>new Proxy(n,{get:(s,c)=>{const u=Reflect.get(s,c,s);if(typeof u!="function")return u;if(c===Symbol.asyncIterator)return async function*(){for await(const y of Reflect.apply(u,s,[]))Ie(y,r,o),yield y};const g=Qr.get(c);return(...$)=>{const y=Reflect.apply(u,s,$);return g!==void 0?Promise.resolve(y).then(a=>(ze(a,g,r,o),a)):typeof y=="object"&&y!==null&&!(y instanceof Promise)?Dn(y,r,o):y}}}),Vr=new Set(["findFirst","findFirstOrThrow","findMany"]),Jr=n=>{const r=n[1],o=r?.select;if(!Array.isArray(o))return;const s=Object.fromEntries(Object.entries(r).filter(([g])=>g!=="select")),c=s.with,u=g=>gt(g,o,c);return{args:[n[0],s,...n.slice(2)],project:(g,$)=>typeof g!="object"||g===null?g:$==="page"?{...g,page:u(g.page)}:u([g])[0]}},pn=256,gn=4096,zr=1024*1024,Yr=async(n,r,o,s)=>{const c=r[1]??{},u=[];let{cursor:g}=c,$=pn,y=0;for(;;){const a=await n([r[0],{...c,cursor:g,limit:$},...r.slice(2)]);if(Array.isArray(a))return ze(a,"rows",o,s),[...u,...a];const M=s.headroom().readBytes;if(ze(a,"page",o,s),u.push(...a.page),a.isDone||typeof a.continueCursor!="string")return{continueCursor:null,isDone:!0,page:u};g=a.continueCursor,y+=s.headroom().readBytes-M,$=y>0?Math.min(gn,Math.max(pn,Math.floor(zr*u.length/y))):gn}},Xr=(n,r)=>n===void 0||r===void 0?n:new Proxy(n,{get:(o,s)=>{const c=Reflect.get(o,s,o);if(typeof c!="function")return c;if(s==="query")return(...g)=>Dn(Reflect.apply(c,o,g),String(g[0]),r);const u=Nr.get(s);return u===void 0?c:async(...g)=>{const $=Vr.has(s)?Jr(g):void 0,y=$?.args??g,a=String(g[0]);if(s==="findMany"&&typeof y[1]?.limit!="number"){const v=await Yr(x=>Reflect.apply(c,o,x),y,a,r);return $===void 0?v:$.project(v,u)}const T=await Reflect.apply(c,o,y);return ze(T,u,a,r),$===void 0?T:$.project(T,u)}}}),yn=new WeakMap,En=new WeakMap,Zr=n=>{const{baselineSeq:r,onStalePatchDropped:o}=n,{headroom:s}=n,c=yn.get(n)??{value:void 0},u=En.get(n)??{value:0};let g;const $=()=>{if(g===void 0){const e={...n,enforceRls:!1,headroom:void 0};yn.set(e,c),En.set(e,u),g=Zr(e)}return g},y=Kr(n.sql,s,n.schema),{schema:a}=n,M=n.broadcast??(()=>{}),T=(e,t)=>{if(!Object.hasOwn(a.tables,e))throw new S("BAD_REQUEST",`${t}: "${e}" is not a table in this schema`)},v=Lo(a),x=new Map;for(const e of v){const t=i=>(a.tables[i]?.shardMode?.kind??"root")==="root";!e.array&&t(e.sourceTable)&&t(e.targetTable)&&x.set(e.sourceTable,[...x.get(e.sourceTable)??[],e])}const W=(e,t,i)=>{for(const l of x.get(e)??[]){const w=t[l.column];if(typeof w!="string"||i?.[l.column]===w||l.targetTable===e&&t._id===w)continue;if(K(y,d`SELECT 1 FROM ${d.identifier(l.targetTable)} WHERE id = ${w} LIMIT 1`).toArray().length===0)throw new S("VALIDATION_ERROR",`${l.name} references ${l.targetTable} row "${w}", which does not exist`)}},P=qo(a,n.inTransaction),B=Or(a),U=Gr(a),j=()=>n.inTransaction?.()===!0,ee=e=>a.tables[e]?.commitOrderedMode!==!0?{}:((c.value===void 0||!j())&&(c.value=Xn(y)),{[Zn]:c.value}),N=(e,...t)=>{const i=a.tables[e]?.indexes??[],l=[];let w;for(const p of t)p&&(typeof p._id=="string"&&p._id!==w&&(w=p._id,l.push(xo(w))),l.push(...bo(i,Co(i,p,Ce))));return l.length>0?l:void 0},R=n.onRead??(()=>{}),C=e=>{Ot(a.tables[e])&&R(Jt,Jt)},L=n.onReadRange??(e=>{R(e.table,G)}),F=e=>{C(e.table),L(e)},k=(e,t,i)=>{t!==void 0&&t!==G&&s?.recordRead(1),C(e),R(e,t,i)},pe=(e,t)=>{const i=e.row._id;k(e.tableName,typeof i=="string"?i:t,typeof i=="string")},te=n.onIndexUse??(()=>{}),ge=n.onWrite??(()=>{}),J=e=>{s?.recordWrite(e)},ye=async e=>{J(e.doc),await ge(e)},{cache:Ee}=n,$e=n.clock??(()=>Date.now()),vt=n.idGenerator??(()=>crypto.randomUUID()),_t=n.scheduler??jn,me=Xr(n.globalDb,s),ce=n.auth??{identity:null,userId:null},Tt=n.cdc??!1,et=_t,kn=Ho({scheduler:typeof et.list=="function"&&typeof et.get=="function"?et:void 0,storage:n.storage}),Se=(e,t,i,l)=>{Tt&&!Ot(a.tables[e])&&zn(y,$e(),e,t,i,l)},At=(e,t,i,l)=>{const w=a.tables[e];if(w?.dropStalePatchesMode!==!0||!Tt)return!1;const p=r?.();if(p===void 0)return!1;const f=Yn(y,e,t,p);if(f===void 0)return!1;const h=Eo(w,i);return Object.keys(Ke(i)).some(E=>!h.has(E)&&Ut(Ht(f,E))!==Ut(Ht(l,E)))},ae=e=>a.tables[e]?.shardMode?.kind==="global",It=(e,t)=>{if(ae(e)){if(!me)throw new S("INTERNAL",`cross-backend ${t} for global table '${e}' requires a globalDb writer — pass one to createShardCtxDb({ globalDb })`);return me}return O},tt=e=>It(e,"cascade"),H=(e,t)=>{if(ae(e)){if(!me)throw new S("INTERNAL",`${t} on global table '${e}' requires a globalDb writer — pass one to createShardCtxDb({ globalDb })`);return me}},xt=async(e,t,i,l,w)=>{w&&J(i);const p=await e.insert(t,i,l);return M({key:p,op:"insert",row:{...i,_id:p},table:t}),p},nt=(e,t)=>It(e,"relation load").findMany(e,t),bt=(e,t)=>(ae(e)&&k(e,G),nt(e,t)),Ln=e=>!ae(e.table),Ct=n.relationExistsPushDown??"auto",Mt=Ct!=="never",{maxRelationKeys:Dt}=n,De=(e,t,i)=>Bo(e,{fetcher:bt,maxRelationKeys:Dt,relationBaseWhere:i,schema:a,tableName:t}),kt=async(e,t,i,l)=>{const w=H(e,"relation grouped count");if(w)return k(e,G),Oo((m,q)=>w.count(m,q),e,t,i,l);const p=a.tables[e];if(!p)throw new S("INTERNAL",`unknown table: ${e}`);k(e,G);const f=Ae(p.softDeleteMode,void 0),h={[t]:{in:i}},E=Q(Q(h,l),f),_=await De(E,e,void 0),b=Z(_,ue),A=fe(t);let I=d`SELECT ${A} AS __fk__, COUNT(*) AS count FROM ${d.identifier(e)}`;b&&(I=d`${I} WHERE ${b}`),I=d`${I} GROUP BY ${A}`;const D=K(y,I).toArray();return new Map(D.map(m=>[m.__fk__,m.count]))},Lt=new Set;for(const[e,t]of Object.entries(a.tables))for(const i of Object.values(t.triggerMap??{}))Lt.add(`${e} ${i.timing} ${i.op}`);const ne=(e,t,i)=>Lt.has(`${e} ${t} ${i}`),oe=async(e,t,i)=>{if(u.value+=1,u.value>rn)throw u.value-=1,new se(`trigger recursion exceeded ${String(rn)} levels on "${i.table}" — check for a self-triggering write`,"trigger");try{await Ko({ctx:qn,event:i,op:t,schema:a,tableName:i.table,timing:e})}finally{u.value-=1}},{ensureBackfilledForTable:Re,ensureBackfilledIndex:ot,ensureRankBackfilled:rt,ensureRankBackfilledForTable:ve,syncAggregates:ke,syncCompanionsForInsert:Ft,syncGeo:Le,syncRanks:_e,syncSearch:Fe}=eo({broadcast:M,indexKeysFor:(e,t)=>N(e,t),invalidateCache:(e,t,i)=>Ee?.invalidate(e,t,N(e,i)),recordCdc:Se,schema:a,sql:y,verified:n.companionMemo?.verified}),Bt=(e,t,i)=>{const{shardMode:l}=t;if(l?.kind==="shardBy"&&!(l.field!==void 0&&(i.partitionBy??[]).includes(l.field)))throw Object.assign(new Error(`rank index "${i.name}" on "${e}" partitions across shards (shard key "${l.field??"?"}" is not in partitionBy) — a shard-local rank()/rankPage() would be wrong; roll it up through the Query Coordinator instead`),{code:"CROSS_SHARD_RANK_UNSUPPORTED",name:"LunoraError",status:400})},Wt=e=>Object.entries(a.tables).filter(([,t])=>t.shardMode?.kind!=="global").map(([t])=>t).filter(t=>e===void 0||t===e),Te=e=>e===void 0||ae(e)?me:void 0,it=async(e,t,i,l,w)=>{for(let p=0;p<i.length;p+=1)J(void 0);if(w!==void 0&&e.deleteMany!==void 0)return e.deleteMany(t,i,w.options);for(const p of i)await e.delete(t,p,l);return{deleted:i.length}},re=(e,t)=>{const i=Wt(t);for(let l=0;l<i.length;l+=sn){const w=i.slice(l,l+sn),[p]=he(y,Er(w),...$r(e,w)).toArray();if(!p)continue;const f=p.__t__,h=xe(p);if(typeof f!="string"||!h)return;const E=p[ie];return{docJson:typeof E=="string"?E:le(E??{}),row:h,tableName:f}}},qt={assertRankPartitionLocal:Bt,ensureRankBackfilled:rt,onRead:k,rowToDocument:xe,schema:a,sql:y},Fn=(e,t,i)=>{const l=Z(i,ue);return l===void 0||K(y,d`SELECT 1 FROM ${d.identifier(e)} WHERE ${d.identifier("id")} = ${t} AND ${l}`).toArray().length>0},Bn=(e,t,i,l)=>At(e,t,i,l)?(o?.({fields:Object.keys(Ke(i)),id:t,table:e}),!0):!1,Wn=async(e,t,i,l,w)=>{const p=re(t,e);if(!p)return{applied:!1,doc:null};if(k(e,t),!Fn(e,t,i.where)||Bn(e,t,i.patch,p.row))return{applied:!1,doc:p.row};try{await w(i.patch)}catch(f){if(f instanceof se&&f.kind==="occ"&&l)return;throw f}return{applied:!0,doc:re(t,e)?.row??null}},Pt=async(e,t,i,l)=>{const{fetchLimit:w,limit:p,orderKeys:f,predicate:h}=await Wo(t,i,{canPushExists:Mt?Ln:void 0,existsPushMode:Ct==="always"?"always":"auto",fetcher:bt,maxRelationKeys:Dt,schema:a,tableName:e}),E=Mt?kr(l):Xe,_=Z(h,E,Ye),b=An(e,_,In(f),w);return{limit:p,orderKeys:f,statement:b}},O={system:kn,async aggregate(e,t){const i=H(e,"aggregate");if(i)return k(e,G),i.aggregate(e,t);const l=a.tables[e];if(!l)throw new S("INTERNAL",`unknown table: ${e}`);if(Pe(t.op),t.op==="count")return O.count(e,{baseWhere:t.baseWhere,relationBaseWhere:t.relationBaseWhere,restrictsCounts:t.restrictsCounts,where:t.where});if(!t.field)throw new S("INTERNAL",`aggregate(${e}, { op: "${t.op}" }): "field" is required for non-count reducers`);k(e,G);const w=Ae(l.softDeleteMode,void 0),p=Q(Q(t.baseWhere,t.where),w),f=await De(p,e,t.relationBaseWhere),h=f!==p;if(l.aggregateIndexes&&!t.baseWhere&&!h){const m=Qn(l.aggregateIndexes,t.op,t.field,t.where);if(m){ot(e,m.index);const q=ct(m.index.by??[],m.key),Y=st(e,m.index.name),X=K(y,d`SELECT ${Ue} AS value, ${lt} AS count FROM ${d.identifier(Y)} WHERE ${Oe} = ${q}`).toArray()[0];return at(t.op,X)}}dn(l,t.field,`aggregate(${e}, { op: "${t.op}", field: "${t.field}" })`);const E=Z(f,ue),_=Pe(t.op),b=fe(t.field);let A=d`SELECT ${d.raw(_)}(${b}) AS value FROM ${d.identifier(e)}`;E&&(A=d`${A} WHERE ${E}`);const D=K(y,A).toArray()[0]?.value;return D??null},asId(e,t){const i=ln(a,e,t);if(i===null)throw new S("BAD_REQUEST",`asId("${e}", …): "${t}" is not a valid id for table "${e}"`,{status:400});return i},async count(e,t){const i=H(e,"count");if(i)return k(e,G),i.count(e,t);const l=a.tables[e];if(!l)throw new S("INTERNAL",`unknown table: ${e}`);const w=Hn(t);if(w.restrictsCounts)throw new dt(e);k(e,G);const p=Ae(l.softDeleteMode,void 0),f=Q(Q(w.baseWhere,w.where),p),h=await De(f,e,w.relationBaseWhere),E=h!==f;if(l.aggregateIndexes&&!w.baseWhere&&!E){const I=Nn(l.aggregateIndexes,w.where);if(I){ot(e,I.index);const D=ct(I.index.by??[],I.key),m=st(e,I.index.name),q=K(y,d`SELECT ${Ue} AS value FROM ${d.identifier(m)} WHERE ${Oe} = ${D}`).toArray();return q[0]===void 0?0:q[0].value??0}}const _=Z(h,ue);let b=d`SELECT COUNT(*) AS count FROM ${d.identifier(e)}`;return _&&(b=d`${b} WHERE ${_}`),K(y,b).one().count},async delete(e,t,i){T(e,"ctx.db.delete(table, id)");const l=re(t,e);if(!l){const I=Te(e);I&&await it(I,e,[t],i);return}const{docJson:w,row:p,tableName:f}=l,h=a.tables[f],E=i?.hard===!0,_=!E&&h?.softDeleteMode?h:void 0,b=_?.softDeleteMode?.field;if(b&&p[b]!==null&&p[b]!==void 0)return;if(ne(f,"before","delete")&&await oe("before","delete",{id:t,op:"delete",previous:p,table:f}),i?.skipOnDelete!==!0&&await Uo({deletedId:t,deletedReference:I=>p[I],findHolders:async(I,D,m,q)=>(await tt(I).findMany(I,{...q,includeDeleted:E,where:{[D]:m}})).page,onCascade:(I,D)=>tt(I).delete(I,D,i),onRestrict:I=>{throw new se(I,"restrict")},onSetNull:(I,D,m)=>tt(I).patch(I,D,{[m]:null}),schema:a,tableName:f}),Re(f),ve(f),_&&b){const I={[b]:$e()},D={...p,...ee(f),...I,_id:t};ht(_,I,D,ce),Ne(y,f,nn(f),[le(D),t,w]),Fe(f,t,D,p),Le(f,t,void 0),ke(f,p,D),_e(f,t,p,void 0);const m=N(f,p,D);Ee?.invalidate(f,t,m),Se(f,t,"update",D),M({indexKeys:m,key:t,op:"update",row:D,table:f}),ne(f,"after","delete")&&await oe("after","delete",{id:t,op:"delete",previous:p,table:f}),await ye({id:t,op:"delete",table:f});return}Ne(y,f,pr(f),[t,w]),Fe(f,t,void 0),Le(f,t,void 0),ke(f,p,void 0),_e(f,t,p,void 0);const A=N(f,p);Ee?.invalidate(f,t,A),Se(f,t,"delete"),M({indexKeys:A,key:t,op:"delete",table:f}),ne(f,"after","delete")&&await oe("after","delete",{id:t,op:"delete",previous:p,table:f}),await ye({id:t,op:"delete",table:f})},async deleteAll(e,t){if(!a.tables[e])throw new S("INTERNAL",`unknown table: ${e}`);if(s!==void 0)return $().deleteAll(e,t);const i=Math.max(1,t?.chunkSize??vn),l=t?.hard===void 0?void 0:{hard:t.hard},w=H(e,"deleteAll");let p=0;for(;;){const h=(await O.findMany(e,{limit:i})).page.map(E=>String(E._id));if(h.length===0)break;for(const E of h)await(w===void 0?O.delete(e,E,l):it(w,e,[E],l)),p+=1;if(h.length<i)break}return{deleted:p}},async deleteMany(e,t,i){T(e,"ctx.db.deleteMany(table, ids)"),He(t.length,i?.limit,"deleteMany");for(const l of t)await O.delete(e,l);return{deleted:t.length}},async deleteWhere(e,t,i){const l=H(e,"deleteWhere"),p=(await cn(l??O,e,t,i?.limit,"deleteWhere")).map(f=>String(f._id));if(l)return it(l,e,p,void 0,{options:i});if(O.deleteMany===void 0)throw new S("INTERNAL",`ctx.db.${e}.deleteMany is unavailable: this writer has no batch delete`);return O.deleteMany(e,p,i)},async findFirst(e,t={}){return(await O.findMany(e,{...t,limit:1,omitContinueCursor:!0})).page[0]??null},async findFirstOrThrow(e,t={}){const i=await O.findFirst(e,t);if(i===null)throw new po(`findFirstOrThrow: no "${e}" document matched`);return i},async findMany(e,t={}){const i=H(e,"findMany");if(i)return k(e,G),i.findMany(e,t);const l=a.tables[e];if(!l)throw new S("INTERNAL",`unknown table: ${e}`);const w=!t.where&&!t.baseWhere;w?k(e,G):k(e);const{limit:p,orderKeys:f,statement:h}=await Pt(e,l,t,k),E=he(y,h.text,...h.params).toArray();w&&s?.recordRead(E.length);const _=[];for(const D of E){const m=xe(D);m&&(_.push(m),!w&&typeof m._id=="string"&&k(e,m._id))}if(p===void 0)return t.with&&await Yt({groupedCounter:kt,fetcher:nt,parents:_,...Xt(t),schema:a,tableName:e,with:t.with}),{continueCursor:null,isDone:!0,page:gt(_,t.select,t.with)};const b=_.length>p,A=b?_.slice(0,p):_,I=A.at(-1);return t.with&&await Yt({fetcher:nt,groupedCounter:kt,parents:A,...Xt(t),schema:a,tableName:e,with:t.with}),{continueCursor:b&&I&&t.omitContinueCursor!==!0?Qe(I,f):null,isDone:!b,page:gt(A,t.select,t.with)}},async explain(e,t={}){const i=H(e,"explain");if(i)return i.explain(e,t);const l=a.tables[e];if(!l)throw new S("INTERNAL",`unknown table: ${e}`);const{statement:w}=await Pt(e,l,t,()=>{}),p=he(y,`EXPLAIN QUERY PLAN ${w.text}`,...w.params).toArray();return{params:w.params,plan:p.map(f=>String(f.detail)),sql:w.text}},async get(e,t){T(e,"ctx.db.get(table, id)");const i=re(t,e);if(!i){const l=Te(e);return l?l.get(e,t):(C(e),R(e,t,!0),null)}return pe(i,t),i.row},async lookupById(e,t){const i=re(e,t);if(!i){for(const l of Wt(t))C(l),R(l,e,!0);return null}return pe(i,e),{row:i.row,tableName:i.tableName}},async groupBy(e,t){const i=H(e,"groupBy");if(i)return k(e,G),i.groupBy(e,t);const l=a.tables[e];if(!l)throw new S("INTERNAL",`unknown table: ${e}`);k(e,G);const w=t.agg??{op:"count"};if(Pe(w.op),w.op!=="count"&&!w.field)throw new S("INTERNAL",`groupBy(${e}, { agg: { op: "${w.op}" } }): "field" is required for non-count reducers`);const p=Ae(l.softDeleteMode,void 0),f=Q(Q(t.baseWhere,t.where),p),h=await De(f,e,t.relationBaseWhere),E=h!==f;if(l.aggregateIndexes&&!t.baseWhere&&!E){const m=Kn(l.aggregateIndexes,w.op,w.field,t.by,t.where),q=m===void 0?0:Object.keys(m.partial).length,Y=m?.index.by?.length??0;if(m&&(q===0||q===Y)){ot(e,m.index);const X=st(e,m.index.name),V=Object.keys(m.partial),de=[];if(V.length===(m.index.by??[]).length&&V.length>0){const Be=ct(m.index.by??[],m.partial),We=K(y,d`SELECT ${Ue} AS value, ${lt} AS count FROM ${d.identifier(X)} WHERE ${Oe} = ${Be}`).toArray();return We.length>0&&de.push({key:{...m.partial},value:at(w.op,We[0])}),de}const Pn=K(y,d`SELECT ${Oe} AS key, ${Ue} AS value, ${lt} AS count FROM ${d.identifier(X)}`).toArray();for(const Be of Pn){const We=Gn(JSON.parse(Be.key));de.push({key:We,value:at(w.op,Be)})}return de}}for(const m of[...t.by,w.field]){if(m===void 0)continue;const q=m===w.field?`groupBy(${e}, { agg: { op: "${w.op}", field: "${m}" } })`:`groupBy(${e}, { by: [..."${m}"] })`;dn(l,m,q)}const _=Z(h,ue),b=t.by.map(m=>d`${fe(m)} AS ${d.identifier(m)}`);if(w.op==="count")b.push(d`COUNT(*) AS value`);else{const{field:m}=w;if(m===void 0)throw new S("INTERNAL",`groupBy(${e}, { agg: { op: "${w.op}" } }): "field" is required for non-count reducers`);b.push(d`${d.raw(Pe(w.op))}(${fe(m)}) AS value`)}let A=d`SELECT ${d.join(b,d`, `)} FROM ${d.identifier(e)}`;_&&(A=d`${A} WHERE ${_}`),A=d`${A} GROUP BY ${d.join(t.by.map(m=>fe(m)),d`, `)}`;const I=K(y,A).toArray(),D=[];for(const m of I){const q={};for(const X of t.by)q[X]=oo(l.shape[X],m[X]??null);const{value:Y}=m;D.push({key:q,value:Y==null?null:Number(Y)})}return D},async insert(e,t,i){const l=H(e,"insert");if(l)return xt(l,e,t,i,!0);const w=a.tables[e];if(!w)throw new S("INTERNAL",`unknown table: ${e}`);const p=i?.allowExplicitId===!0,f=Ge(w,yt(w,t,ce),{supplied:t,trusted:p});let h;i?.clientId!==void 0?(Sr(i.clientId),h=i.clientId):i?.allowExplicitId&&typeof f._id=="string"?($t(f._id),h=f._id):h=vt();const E=i?.allowExplicitId&&typeof f._creationTime=="number"?f._creationTime:$e(),_={...f,...ee(e),_creationTime:E,_id:h};return ne(e,"before","insert")&&await oe("before","insert",{doc:{..._},id:h,op:"insert",table:e}),p||W(e,_),Re(e),ve(e),mt(y,e,hr(e),[h,E,le(_)]),Ft(e,h,_),ne(e,"after","insert")&&await oe("after","insert",{doc:_,id:h,op:"insert",table:e}),await ye({doc:_,id:h,op:"insert",table:e}),h},async insertManyUnsafe(e,t,i){if(He(t.length,i?.limit,"insertManyUnsafe"),t.length===0)return[];const l=H(e,"insert");if(l){const E=[];Rr(a.tables[e],t,i?.allowExplicitId,ce);for(const _ of t)J(_);for(const _ of t){const b=await l.insert(e,_,{allowExplicitId:i?.allowExplicitId});M({key:b,op:"insert",row:{..._,_id:b},table:e}),E.push(b)}return E}const w=a.tables[e];if(!w)throw new S("INTERNAL",`unknown table: ${e}`);Re(e),ve(e);const p=[];for(let E=0;E<t.length;E+=je)p.push(ee(e));const f=i?.allowExplicitId===!0?void 0:Po(w),h=t.map((E,_)=>{const b=yt(w,E,ce),A=f===void 0?b:Ge(f,b,{supplied:E}),I=i?.allowExplicitId===!0&&typeof A._id=="string"?A._id:void 0;I!==void 0&&$t(I);const D=I??vt(),m=i?.allowExplicitId===!0&&typeof A._creationTime=="number"?A._creationTime:$e(),q={...A,...p[Math.floor(_/je)],_creationTime:m,_id:D};return{creationTime:m,document:q,id:D}});for(const E of h)J(E.document);for(let E=0;E<h.length;E+=je){const _=d.join(h.slice(E,E+je).map(A=>d`(${A.id}, ${A.creationTime}, ${le(A.document)})`),d`, `),b=mn("sqlite",d`INSERT INTO ${d.identifier(e)} (id, _creationTime, ${d.identifier(ie)}) VALUES ${_}`);mt(y,e,b.sql,b.params)}for(const{document:E,id:_}of h)Ft(e,_,E),await ge({doc:E,id:_,op:"insert",table:e});return h.map(E=>E.id)},async insertMany(e,t,i){He(t.length,i?.limit,"insertMany");const l=i?.skipDuplicates===!0,w=[],p=H(e,"insert");if(p)for(const h of t)J(h);const f=async h=>p?xt(p,e,h,void 0,!1):O.insert(e,h);for(const h of t)try{w.push(await f(h))}catch(E){if(l&&E instanceof se&&E.kind==="unique")w.push(null);else throw E}return w},normalizeId(e,t){return ln(a,e,t)},async patch(e,t,i,l){T(e,"ctx.db.patch(table, id, values)");const w=re(t,e);if(!w){const D=Te(e);if(D){J(i),await D.patch(e,t,i,l);return}throw new S("NOT_FOUND",`document not found: ${t}`)}const{docJson:p,row:f,tableName:h}=w,E=a.tables[h];if(!E)throw new S("INTERNAL",`unknown table: ${h}`);if(k(h,t),fn("patch",i),At(h,t,i,f)){o?.({fields:Object.keys(Ke(i)),id:t,table:h});return}const _=go(E,i,f),b={...f,...Ke(_),...ee(h),_id:t};ht(E,_,b,ce);const A=Ge(E,b,{only:new Set(Object.keys(_)),previous:()=>f,tolerateStoredNull:!0});yo(l,f,A),ne(h,"before","update")&&await oe("before","update",{doc:{...A},id:t,op:"update",previous:f,table:h}),W(h,A,f),Re(h),ve(h),Ne(y,h,nn(h),[le(A),t,p]),Fe(h,t,A,f),Le(h,t,A),ke(h,f,A),_e(h,t,f,A);const I=N(h,f,A);Ee?.invalidate(h,t,I),Se(h,t,"update",A),M({indexKeys:I,key:t,op:"update",row:A,table:h}),ne(h,"after","update")&&await oe("after","update",{doc:A,id:t,op:"update",previous:f,table:h}),await ye({doc:A,id:t,op:"update",table:h})},async patchIf(e,t,i){const l=H(e,"patchIf");if(l){if(l.patchIf===void 0)throw new S("INTERNAL",`ctx.db.patchIf on global table '${e}' is unsupported: its backend has no conditional write`);return J(i.patch),l.patchIf(e,t,i)}if(!a.tables[e])throw new S("INTERNAL",`unknown table: ${e}`);for(let w=1;w<=un;w+=1){const p=await Wn(e,t,i,w<un,f=>O.patch(e,t,f,{verify:i.verify}));if(p!==void 0)return p}throw new se(`patchIf on "${e}" kept conflicting; the row changed on every attempt`,"occ")},async patchMany(e,t,i){T(e,"ctx.db.patchMany(table, patches)"),He(t.length,i?.limit,"patchMany");for(const l of t)await O.patch(e,l.id,l.patch);return{patched:t.length}},async patchWhere(e,t,i){const l=H(e,"patchWhere")??O,p=(await cn(l,e,t.where,i?.limit,"patchWhere")).map(f=>({id:String(f._id),patch:t.patch}));if(O.patchMany===void 0)throw new S("INTERNAL",`ctx.db.${e}.patchMany is unavailable: this writer has no batch patch`);return await O.patchMany(e,p,i),{patched:p.length}},async related(e,t){return Fo(O,v,e,t)},relationEdges:v,deleteRereadTables:B,inTransaction:j,softDeleteFields:U,relationWrites:P,query(e){const t=H(e,"query");return t?(k(e,G),t.query(e)):Mn(y,a,e,te,i=>{i?F(i):k(e,G)},i=>{s?.recordRead(i)})},async rank(e,t,i){const l=H(e,"rank");if(l)return k(e,G),l.rank(e,t,i);te(e,t,"rank");const w=a.tables[e];if(!w)throw new S("INTERNAL",`unknown table: ${e}`);const p=w.rankIndexes?.find(V=>V.name===t);if(!p)throw new S("INTERNAL",`unknown rankIndex "${t}" on table "${e}"`);if(Bt(e,w,p),i.restrictsCounts)throw new dt(e);k(e,G),rt(e,p);const f=typeof i.row=="string"?i.row:i.row._id;if(!f)return null;const h=Qt(e,p.name),E=p.sortBy.map((V,de)=>Vt(de)),_=E.map(V=>Me(V)).join(", "),b=K(y,d`SELECT ${d.identifier("__partition__")}, ${d.raw(_)} FROM ${d.identifier(h)} WHERE ${d.identifier("__id__")} = ${f}`).toArray(),[A]=b;if(A===void 0)return null;let I=A.__partition__;const D=Q(i.baseWhere,i.where);ut(D,a,e,"rank");const m=_o(p,D);if(m){const V=To(p.partitionBy??[],m);if(V!==I)return null;I=V}const q=E.map(V=>A[V]),{before:Y,total:X}=wn(y,h,E,p.sortBy,I,q,f);return{position:Y+1,total:X}},async rankBefore(e,t,i){if(ae(e))throw new S("INTERNAL",`rankBefore is not supported on the global (.global()) table '${e}' — cross-shard rank cursors apply only to sharded tables`);const l=a.tables[e];if(!l)throw new S("INTERNAL",`unknown table: ${e}`);const w=l.rankIndexes?.find(E=>E.name===t);if(!w)throw new S("INTERNAL",`unknown rankIndex "${t}" on table "${e}"`);if(i.restrictsCounts)throw new dt(e);k(e,G),rt(e,w);const p=Qt(e,w.name),f=w.sortBy.map((E,_)=>Vt(_)),h=w.sortBy.map((E,_)=>Ce(i.sortValues[_]??null));return wn(y,p,f,w.sortBy,i.partitionKey,h,i.rowId)},async rankPage(e,t,i={}){ut(Q(i.baseWhere,i.where),a,e,"rankPage");const l=H(e,"rankPage");if(l)return k(e,G),l.rankPage(e,t,i);te(e,t,"rank");const{continueCursor:w,hasMore:p,rows:f}=Gt(qt,e,t,i);return{continueCursor:w,isDone:!p,page:f.map(h=>h.doc)}},async rankPageRows(e,t,i={}){ut(Q(i.baseWhere,i.where),a,e,"rankPage"),te(e,t,"rank");const{directions:l,hasMore:w,rows:p}=Gt(qt,e,t,i);return{directions:l,hasMore:w,rows:p}},async restore(e,t){T(e,"ctx.db.restore(table, id)");const i=re(t,e);if(!i){const p=Te(e);if(p?.restore){await p.restore(e,t);return}throw new S("NOT_FOUND",`document not found: ${t}`)}const l=a.tables[i.tableName]?.softDeleteMode?.field;if(!l)throw new S("INTERNAL",`ctx.db.restore: table "${i.tableName}" is not a .softDelete() table`);const w=i.row[l]!==null&&i.row[l]!==void 0;await O.patch(e,t,{[l]:null}),w&&_e(i.tableName,t,void 0,i.row)},async replace(e,t,i,l){T(e,"ctx.db.replace(table, id, document)");const w=re(t,e);if(!w){const q=Te(e);if(q){J(i),await q.replace(e,t,i,l);return}throw new S("NOT_FOUND",`document not found: ${t}`)}const{docJson:p,row:f,tableName:h}=w,E=a.tables[h];if(!E)throw new S("INTERNAL",`unknown table: ${h}`);fn("replace",i);const _=l?.allowExplicitId&&typeof i._creationTime=="number"?i._creationTime:void 0,b=typeof f._creationTime=="number"?f._creationTime:void 0,A=_??b??$e(),I={...i,...ee(h),_creationTime:A,_id:t};ht(E,i,I,ce);const D=l?.allowExplicitId===!0,m=Ge(E,I,{previous:()=>f,supplied:i,trusted:D});ne(h,"before","update")&&await oe("before","update",{doc:{...m},id:t,op:"update",previous:f,table:h}),D||W(h,m,f),Re(h),ve(h),Ne(y,h,wr(h),[A,le(m),t,p]),Fe(h,t,m,f),Le(h,t,m),ke(h,f,m),_e(h,t,f,m),Ee?.invalidate(h,t,N(h,f,m)),Se(h,t,"update",m),M({indexKeys:N(h,f,m),key:t,op:"update",row:m,table:h}),ne(h,"after","update")&&await oe("after","update",{doc:m,id:t,op:"update",previous:f,table:h}),await ye({doc:m,id:t,op:"update",table:h})},async wipeShard(e){const t=new Set(e?.exclude),i=e?.tables,l=Object.entries(a.tables).filter(([h,E])=>t.has(h)||i!==void 0&&!i.includes(h)?!1:E.shardMode?.kind!=="global").map(([h])=>h);if(i!==void 0){for(const h of i)if(!a.tables[h])throw new S("INTERNAL",`wipeShard: unknown table: ${h}`)}const w={};let p=0;const{deleteAll:f}=O;if(f===void 0)throw new S("INTERNAL","wipeShard: this writer has no deleteAll");for(const h of l){const E=await f(h,{...e?.chunkSize===void 0?{}:{chunkSize:e.chunkSize},hard:!0});w[h]=E.deleted,p+=E.deleted}return{deleted:p,tables:w}}},qn={db:O,scheduler:_t};return n.enforceRls===!0?Go(O,a,(e,t)=>re(e,t)?.tableName,v):O};export{Ki as CDC_LOG_TABLE,hs as IDEMPOTENCY_TABLE,Lr as NotUniqueError,ds as advanceClientWatermark,Ni as applyCdcChanges,fn as assertNoExplicitUndefined,$t as assertStorableRowId,Sr as assertValidClientId,Oi as backfillAggregateIndexes,Gi as backfillRankIndexes,ji as backfillSearchIndexes,Qi as bumpCdcEpoch,Vi as cdcCanVouchFor,Ji as cdcForkedError,zi as cdcSeqLeavingRows,Yi as cdcTouchesTables,Xi as cdcTrimmedError,Zi as compactCdcDocs,Zr as createShardCtxDb,es as cursorBelowRetainedFloor,Kr as meterReadBytes,ls as migrateClientWatermark,ts as minCdcReplayableSeq,ns as minCdcSeq,ln as normalizeIdStructurally,os as readCdcChangeKeys,rs as readCdcChanges,is as readCdcCursor,ss as readCdcEpoch,us as readClientWatermark,ws as readIdempotent,Es as runShardMigrations,ms as selectShapeMembers,Ss as selectShapeRows,Ke as stripReservedPatchFields,cs as trimCdcChanges,ps as trimIdempotent,gs as writeIdempotent};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{c as i}from"./constant-time-equal-BRh9yUCr.mjs";const a=(t,e)=>{if(t.size<e)return;const n=t.keys().next().value;n!==void 0&&t.delete(n)},l=(t,e,n,o)=>{const s=t.get(e);if(s!==void 0)return s;a(t,o);const r=n().catch(c=>{throw t.get(e)===r&&t.delete(e),c});return t.set(e,r),r},E=new TextEncoder,d=64,u=new Map,y=async t=>l(u,t,async()=>crypto.subtle.importKey("raw",E.encode(t),{hash:"SHA-256",name:"HMAC"},!1,["sign","verify"]),d),g="LUNORA_RELAY_SECRET",w="x-lunora-relay-sig",f=t=>{const e=t?.[g];return typeof e=="string"&&e.length>0?e:void 0},A=async(t,e)=>{const n=await crypto.subtle.sign("HMAC",await y(t),new TextEncoder().encode(e));return[...new Uint8Array(n)].map(o=>o.toString(16).padStart(2,"0")).join("")},S=async(t,e,n)=>{const o=f(t);return o===void 0?!0:e===null?!1:i(e,await A(o,n))};export{w as RELAY_SIGNATURE_HEADER,f as siblingSecretOf,A as signSiblingBody,S as verifySiblingBody};
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
import{ADMIN_TOKEN_TABLE as n}from"./ADMIN_TOKEN_TABLE-DfQ5osdI.mjs";import{c as E}from"./constant-time-equal-BRh9yUCr.mjs";import{runSql as s}from"./runDrizzle-RC09zZrh.mjs";const T=6e4,i=t=>{s(t,`CREATE TABLE IF NOT EXISTS "${n}" (
|
|
2
|
+
name TEXT PRIMARY KEY,
|
|
3
|
+
digest TEXT NOT NULL,
|
|
4
|
+
created_at REAL NOT NULL,
|
|
5
|
+
last_used_at REAL,
|
|
6
|
+
expires_at REAL
|
|
7
|
+
)`)},d=(t,e)=>s(t,`SELECT name, digest, created_at, last_used_at, expires_at FROM "${n}" WHERE name = ?`,e).toArray()[0],m=(t,e)=>(i(t),d(t,e.name)!==void 0?!1:(s(t,`INSERT INTO "${n}" (name, digest, created_at, expires_at) VALUES (?, ?, ?, ?)`,e.name,e.digest,e.createdAt,e.expiresAt??null),!0)),c=t=>(i(t),s(t,`SELECT name, created_at, last_used_at, expires_at FROM "${n}" ORDER BY name`).toArray().map(e=>{const r={createdAt:e.created_at,name:e.name};return e.last_used_at!==null&&(r.lastUsedAt=e.last_used_at),e.expires_at!==null&&(r.expiresAt=e.expires_at),r})),R=(t,e,r)=>(i(t),d(t,e)?.created_at!==r?!1:(s(t,`DELETE FROM "${n}" WHERE name = ? AND created_at = ?`,e,r),!0)),l=(t,e,r,_)=>{i(t);const a=d(t,e);if(!(a===void 0||!E(a.digest,r)||a.expires_at!==null&&a.expires_at<=_))return(a.last_used_at===null||_-a.last_used_at>=T)&&s(t,`UPDATE "${n}" SET last_used_at = ? WHERE name = ?`,_,e),a.expires_at===null?{createdAt:a.created_at}:{createdAt:a.created_at,expiresAt:a.expires_at}},p=(t,e)=>(i(t),d(t,e)!==void 0);export{n as ADMIN_TOKEN_TABLE,p as adminTokenExists,m as createAdminTokenRecord,c as listAdminTokens,R as revokeAdminTokenRecord,l as verifyAdminTokenDigest};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
const r=(e,n)=>{const c=Math.max(e.length,n.length);let h=e.length^n.length;for(let t=0;t<c;t+=1){const l=t<e.length?e.charCodeAt(t):0,o=t<n.length?n.charCodeAt(t):0;h|=l^o}return h===0};export{r as c};
|
package/dist/packem_shared/{createReplicaLink-DVXW9rR6.mjs → createReplicaLink-DtqXBi-0.mjs}
RENAMED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{LunoraError as T}from"@lunora/errors";import{decodeWire as v,encodeWire as N}from"@lunora/wire";import{cursorBelowRetainedFloor as b}from"./CDC_LOG_TABLE-BFGgqai8.mjs";import{envPositiveInt as E}from"./envOptionalPositiveInt-D2pY-c64.mjs";import{e as I}from"./estimate-bytes-C-C35VXL.mjs";import{siblingStub as L}from"./stubByName-
|
|
1
|
+
import{LunoraError as T}from"@lunora/errors";import{decodeWire as v,encodeWire as N}from"@lunora/wire";import{cursorBelowRetainedFloor as b}from"./CDC_LOG_TABLE-BFGgqai8.mjs";import{envPositiveInt as E}from"./envOptionalPositiveInt-D2pY-c64.mjs";import{e as I}from"./estimate-bytes-C-C35VXL.mjs";import{siblingStub as L}from"./stubByName-DQSivmvb.mjs";import{DEFAULT_TRANSACTION_LIMITS as O}from"./DEFAULT_TRANSACTION_LIMITS-D7p7Ys0M.mjs";import{verifySiblingBody as C,RELAY_SIGNATURE_HEADER as S,siblingSecretOf as R,signSiblingBody as U}from"./RELAY_SIGNATURE_HEADER-CAfC4tqg.mjs";const q=["wnam","enam","sam","weur","eeur","apac","apac-ne","apac-se","oc","afr","me"],x=new Set(q),F=r=>typeof r=="string"&&x.has(r),w="::replica::",_=r=>{const e=r.lastIndexOf(w);if(e===-1)return;const t=r.slice(0,e),s=r.slice(e+w.length);if(!(t.length===0||!F(s)))return{ownerKey:t,region:s}},M=r=>{if(r==null||!/^\d+$/.test(r))return;const e=Number.parseInt(r,10);return Number.isSafeInteger(e)&&e>0?e:void 0},P=1e3,A=1e3,B=10,D=5e4,W=r=>E(r,"LUNORA_REPLICA_MAX_BOOTSTRAP_ROWS",D),f="__replica_state",g=new WeakSet,m=r=>{g.has(r)||(r.exec(`CREATE TABLE IF NOT EXISTS ${f} (
|
|
2
2
|
id INTEGER PRIMARY KEY CHECK (id = 1),
|
|
3
3
|
epoch TEXT NOT NULL,
|
|
4
4
|
applied_seq INTEGER NOT NULL,
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{createShardCtxDb as C}from"./NotUniqueError-
|
|
1
|
+
import{createShardCtxDb as C}from"./NotUniqueError-BjwNIte8.mjs";import{createRelayLink as N}from"./DEFAULT_MAX_RELAYS-Bc6PI-xy.mjs";import{ConflictError as q}from"./ConflictError-C8GtJmjS.mjs";import{runShardMigrations as B}from"./runShardMigrations-xu993yo2.mjs";import{d as x}from"./relay-CKEdfUjH.mjs";const v=(O,y={})=>({_meta:{column:{notNull:!0,...y}},kind:O}),W=(O,y,F)=>{const{describe:_,expect:l,it:b}=F;_(`engine contract: ${O}`,()=>{_("optimistic concurrency",()=>{const g=u=>({tables:{items:{indexes:[],shape:{title:v("string"),version:v("number",{notNull:!1})},triggerMap:{clobber:{handler:()=>{u.exec(`UPDATE "items" SET "__doc__" = json_set("__doc__", '$.version', 99) WHERE "id" = 'i1'`)},op:"update",timing:"before"}}}}});b("raises a CONFLICT of kind `occ` when a write's snapshot is clobbered",async()=>{const{close:u,host:h}=y();try{const d=h.sql,p=g(d);B(d,p);const s=C({schema:p,sql:d});await s.insert("items",{_id:"i1",title:"first",version:1},{allowExplicitId:!0}),await l(s.patch("items","i1",{title:"second"})).rejects.toBeInstanceOf(q)}finally{u?.()}}),b("reports the conflict as CONFLICT/409 rather than retrying it away",async()=>{const{close:u,host:h}=y();try{const d=h.sql,p=g(d);B(d,p);const s=C({schema:p,sql:d});await s.insert("items",{_id:"i1",title:"first",version:1},{allowExplicitId:!0});let r;try{await s.patch("items","i1",{title:"second"})}catch(t){r=t}const e=r;l(e.code).toBe("CONFLICT"),l(e.kind).toBe("occ")}finally{u?.()}}),b("leaves the row readable and unchanged after a conflict",async()=>{const{close:u,host:h}=y();try{const d=h.sql,p=g(d);B(d,p);const s=C({schema:p,sql:d});await s.insert("items",{_id:"i1",title:"first",version:1},{allowExplicitId:!0});try{await s.patch("items","i1",{title:"second"})}catch{}const r=await s.get("items","i1");l(r?.title).toBe("first"),l(r?.version).toBe(99)}finally{u?.()}}),b("raises a CONFLICT of kind `trigger` when a trigger writes its own row through the db",async()=>{const{close:u,host:h}=y();try{const d=h.sql,p={tables:{items:{indexes:[],shape:{title:v("string"),version:v("number",{notNull:!1})},triggerMap:{recurse:{handler:async(t,a)=>{await t.db.patch("items",a.doc._id,{version:99})},op:"update",timing:"before"}}}}};B(d,p);const s=C({schema:p,sql:d});await s.insert("items",{_id:"i1",title:"first",version:1},{allowExplicitId:!0});let r;try{await s.patch("items","i1",{title:"second"})}catch(t){r=t}const e=r;l(e).toBeInstanceOf(q),l(e.code).toBe("CONFLICT"),l(e.kind).toBe("trigger")}finally{u?.()}})}),_("shape-poke ordering",()=>{const g="shard-a",u={args:{},name:"messages"},h=(e,t,a,n)=>e.accept(t?.()??{},{connectionId:a,shapes:{[n]:u}}),d=(e,t,a,n=new Set)=>{let c=0,i=0;const o=k=>()=>{throw new Error(`the relay poke path must not reach RelayHost.${k}`)},m={fetch:(k,E)=>{if(JSON.parse(E?.body??"{}").type!=="relay_shape_subscribe")return Promise.resolve(new Response(void 0,{status:204}));const I=a[i];if(i+=1,I===void 0)throw new Error("the relay asked for more seeds than this fixture supplies");return Promise.resolve(Response.json(I))}},f={get:()=>m,getByName:()=>m,idFromName:k=>k},w={buildShapeDiff:o("buildShapeDiff"),computeOpLogShapeSeed:o("computeOpLogShapeSeed"),currentCdcEpoch:o("currentCdcEpoch"),deliverWhisperLocal:o("deliverWhisperLocal"),dropIfLapsed:k=>n.has((k.deserializeAttachment?.()).connectionId??""),doName:()=>x(g,0),env:()=>({SHARD:f}),getWebSockets:()=>e.getSockets(),maskMetadata:o("maskMetadata"),nextPokeId:()=>(c+=1,`poke-${String(c)}`),readAttachment:k=>k.deserializeAttachment?.(),recordShapePokeFanout:()=>{},resolveShape:o("resolveShape"),rlsMetadata:o("rlsMetadata"),shardBinding:()=>"SHARD",shardJurisdiction:()=>{},sql:()=>t},S=N(w);if(S===void 0)throw new Error("expected a relay link for a `…::relay::N` name");return S},p=e=>new Request("https://relay.internal/_lunora/relay",{body:JSON.stringify(e),headers:{"content-type":"application/json"},method:"POST"}),s=async(e,t,a)=>{const n=await e.seedRelayShape(t,a,u,{identity:void 0,userId:void 0});if(n!=="ok")throw new Error(`seed failed: ${JSON.stringify(n)}`)},r=(e={})=>p({...u,checkpoint:20,epoch:"e1",fromCursor:10,rowsPatch:[{id:"r1",op:"upsert",value:{title:"hello"}}],type:"relay_shape_poke",...e});b("frames a poke as pokeStart → pokePart per shape → pokeEnd, under one poke id",async()=>{const{close:e,createSocket:t,host:a,readFrames:n,sockets:c}=y();try{const i=d(c,a.sql,[{cursor:10,epoch:"e1",frames:[]}]),o=h(c,t,"c-alice","s1");await s(i,o,"s1"),await i.handleControl(r());const f=(await n(o)).map(w=>JSON.parse(w));l(f.map(w=>w.type)).toStrictEqual(["pokeStart","pokePart","pokeEnd"]),l(new Set(f.map(w=>w.pokeId)).size).toBe(1),l(f[1]?.shapeId).toBe("s1"),l(f[2]?.checkpoint).toBe(20)}finally{e?.()}}),b("delivers a poke only to sockets whose cursor matches, and advances them past it",async()=>{const{close:e,createSocket:t,host:a,readFrames:n,sockets:c}=y();try{const i=d(c,a.sql,[{cursor:10,epoch:"e1",frames:[]},{cursor:7,epoch:"e1",frames:[]}]),o=h(c,t,"c-alice","s1"),m=h(c,t,"c-bob","s2");await s(i,o,"s1"),await s(i,m,"s2"),await i.handleControl(r());const f=await n(o);l(f.length).toBe(3);const w=await n(m);l(w.length).toBe(0),await i.handleControl(r());const S=await n(o);l(S.length).toBe(3)}finally{e?.()}}),b("pokes no subscriber the host reports lapsed, and still pokes the others",async()=>{const{close:e,createSocket:t,host:a,readFrames:n,sockets:c}=y();try{const i=new Set,o=d(c,a.sql,[{cursor:10,epoch:"e1",frames:[]},{cursor:10,epoch:"e1",frames:[]}],i),m=h(c,t,"c-alice","s1"),f=h(c,t,"c-bob","s2");await s(o,m,"s1"),await s(o,f,"s2"),i.add("c-bob"),await o.handleControl(r());const w=await n(m),S=await n(f);l(w.length).toBe(3),l(S.length).toBe(0)}finally{e?.()}}),b("skips a socket whose cursor matches under a different CDC epoch",async()=>{const{close:e,createSocket:t,host:a,readFrames:n,sockets:c}=y();try{const i=d(c,a.sql,[{cursor:10,epoch:"e1",frames:[]}]),o=h(c,t,"c-alice","s1");await s(i,o,"s1"),await i.handleControl(r({epoch:"e2"}));const m=await n(o);l(m.length).toBe(0),await i.handleControl(r());const f=await n(o);l(f.length).toBe(3)}finally{e?.()}})}),_("orderBy null placement",()=>{const g=[["a",void 0],["b",3],["c",void 0],["d",1],["e",void 0],["f",3],["g",2],["h",void 0]],u=[{nulls:"first",sort:"asc"},{nulls:"last",sort:"asc"},{nulls:"first",sort:"desc"},{nulls:"last",sort:"desc"}],h=({nulls:p,sort:s})=>{const r=new Map(g.map(([t],a)=>[t,a])),e=s==="asc"?1:-1;return g.toSorted(([t,a],[n,c])=>a!==c?a===void 0?p==="first"?-1:1:c===void 0?p==="first"?1:-1:(a-c)*e:((r.get(t)??0)-(r.get(n)??0))*e).map(([t])=>t)},d=p=>p.map(s=>String(s.label));b("pages every placement in threes with no row skipped or repeated",async()=>{const{close:p,host:s}=y();try{const r=s.sql,e=u.map((i,o)=>`items_${String(o)}`),t={label:v("string"),score:v("number",{notNull:!1})},a={tables:Object.fromEntries(e.map(i=>[i,{indexes:[{fields:["score"],name:"by_score"}],shape:t}]))};B(r,a);let n=17e11;const c=C({clock:()=>(n+=1e3,n),schema:a,sql:r});for(const i of e)for(const[o,m]of g)await c.insert(i,m===void 0?{label:o}:{label:o,score:m});for(const[i,o]of u.entries()){const m=e[i]??"",f=await c.findMany(m,{orderBy:[{score:o}]});l(d(f.page)).toStrictEqual(h(o));const w=[];let S;for(let k=0;k<g.length+2;k+=1){const E=await c.findMany(m,{cursor:S,limit:3,orderBy:[{score:o}]});if(w.push(...d(E.page)),E.isDone)break;S=E.continueCursor}l(w).toStrictEqual(h(o))}}finally{p?.()}})}),_("RLS identity under live subscription",()=>{const g="shard-a",u={args:{},name:"lobby-messages"},h={args:{},name:"my-orders"},d=s=>{const r=[],e=[],t={fetch:(c,i)=>(r.push(JSON.parse(i?.body??"{}")),Promise.resolve(new Response(void 0,{status:204})))},n=N({buildShapeDiff:()=>[{id:"r1",op:"upsert",value:{}}],computeOpLogShapeSeed:()=>({baseCheckpoint:void 0,cursor:10,epoch:"e1",reset:!0,rowsPatch:[]}),currentCdcEpoch:()=>"e1",deliverWhisperLocal:()=>0,dropIfLapsed:()=>!1,doName:()=>g,env:()=>({SHARD:{get:()=>t,getByName:()=>t,idFromName:c=>c}}),getWebSockets:()=>[],maskMetadata:()=>({columns:[]}),nextPokeId:()=>"poke-1",readAttachment:()=>({}),recordShapePokeFanout:()=>{},resolveShape:(c,i,o)=>(e.push(o),c===h.name?{columns:["id"],effectiveWhere:{org:o?.identity?.org??"anonymous"},global:!1,table:"orders"}:{columns:["id"],effectiveWhere:{room:"lobby"},global:!1,table:"messages"}),rlsMetadata:()=>({policies:[]}),shardBinding:()=>"SHARD",shardJurisdiction:()=>{},sql:()=>s});if(n===void 0)throw new Error("expected an owner link for an un-suffixed DO name");return{owner:n,posts:r,resolvedUnder:e}},p=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"}))};b("seeds a subscriber under its own forwarded identity, never the anonymous one",async()=>{const{close:s,host:r}=y();try{const{owner:e,resolvedUnder:t}=d(r.sql);await p(e,h),l(t.some(a=>a?.userId==="u1"&&a.identity?.org==="acme")).toBe(!0)}finally{s?.()}}),b("routes an identity-scoped shape to a per-socket poke, not the cohort multicast",async()=>{const{close:s,host:r}=y();try{const{owner:e,posts:t}=d(r.sql);await p(e,h),t.length=0,await e.onFlush(new Set(["orders"]),20);const a=t.filter(n=>n.type==="relay_shape_poke");l(a.length).toBe(1),l(a[0]?.targetConnectionId).toBe("c-alice")}finally{s?.()}}),b("still multicasts an identity-blind shape to the whole cohort",async()=>{const{close:s,host:r}=y();try{const{owner:e,posts:t}=d(r.sql);await p(e,u),t.length=0,await e.onFlush(new Set(["messages"]),20);const a=t.filter(n=>n.type==="relay_shape_poke");l(a.length).toBe(1),l(a[0]?.targetConnectionId).toBeUndefined()}finally{s?.()}})})})};export{W as defineEngineContractSuite};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{RELAY_SIGNATURE_HEADER as u,siblingSecretOf as y,signSiblingBody as a,verifySiblingBody as g}from"./RELAY_SIGNATURE_HEADER-
|
|
1
|
+
import{RELAY_SIGNATURE_HEADER as u,siblingSecretOf as y,signSiblingBody as a,verifySiblingBody as g}from"./RELAY_SIGNATURE_HEADER-CAfC4tqg.mjs";const r=t=>{if(t===null||typeof t!="object")return;const o=t;return typeof o.idFromName=="function"&&typeof o.get=="function"?o:void 0},d=(t,o,n)=>{const i=r(t);if(i===void 0)return;const e=n===void 0?i:r(i.jurisdiction?.(n));if(e!==void 0)return typeof e.getByName=="function"?e.getByName(o):e.get(e.idFromName(o))},c=(t,o,n,i)=>o===void 0?void 0:d(t?.[o],n,i);export{u as RELAY_SIGNATURE_HEADER,y as siblingSecretOf,c as siblingStub,a as signSiblingBody,d as stubByName,g as verifySiblingBody};
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@lunora/shard-engine",
|
|
3
|
-
"version": "1.0.0-alpha.
|
|
3
|
+
"version": "1.0.0-alpha.184",
|
|
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",
|
|
@@ -49,7 +49,7 @@
|
|
|
49
49
|
},
|
|
50
50
|
"dependencies": {
|
|
51
51
|
"@lunora/errors": ">=1.0.0-alpha.77 <2.0.0-0",
|
|
52
|
-
"@lunora/platform": "1.0.0-alpha.
|
|
52
|
+
"@lunora/platform": "1.0.0-alpha.79",
|
|
53
53
|
"@lunora/wire": "1.0.0-alpha.6",
|
|
54
54
|
"drizzle-orm": "1.0.0-rc.5"
|
|
55
55
|
},
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{LunoraError as d}from"@lunora/errors";import{decodeWire as Q,WIRE_TAG as R,needsWireEncoding as X,encodeWire as G}from"@lunora/wire";import{sql as K}from"drizzle-orm";import{isInternalTableName as w}from"./isInternalTableName-BoljO2tP.mjs";import{n as T,o as V}from"./do-sql-105TONaE.mjs";import{quoteIdentifier as u}from"./quoteIdentifier-CObIFRhb.mjs";import{renderSql as J,sqliteInList as Y}from"./WORKERD_SQLITE_LIMITS-B_4w7tzY.mjs";import{serializeSqlValue as L}from"./serializeSqlValue-DeoBMpZ2.mjs";import{decodeBigintSqlKey as z}from"./BIGINT_KEY_DIGITS-DE6yshOt.mjs";const je="__lunora_admin__:",Le="__lunora_relation__:",Fe="__lunora_flags__:",xe={applyCdc:"__lunora_admin__:applyCdc",aiAvailable:"__lunora_admin__:aiAvailable",aiChartConfig:"__lunora_admin__:aiChartConfig",aiCronExpression:"__lunora_admin__:aiCronExpression",aiGenerateSql:"__lunora_admin__:aiGenerateSql",aiNameQuery:"__lunora_admin__:aiNameQuery",aiTableFilter:"__lunora_admin__:aiTableFilter",assignIssue:"__lunora_admin__:assignIssue",backfillSearch:"__lunora_admin__:backfillSearch",backfillVectors:"__lunora_admin__:backfillVectors",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",dropOutboxEntry:"__lunora_admin__:dropOutboxEntry",explainIssue:"__lunora_admin__:explainIssue",exportShard:"__lunora_admin__:exportShard",facetColumn:"__lunora_admin__:facetColumn",findRelated:"__lunora_admin__:findRelated",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",getScheduleOutbox:"__lunora_admin__:getScheduleOutbox",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",listReactors:"__lunora_admin__:listReactors",listQueues:"__lunora_admin__:listQueues",lintSql:"__lunora_admin__:lintSql",listTables:"__lunora_admin__:listTables",listWorkflows:"__lunora_admin__:listWorkflows",maskPolicies:"__lunora_admin__:maskPolicies",migrationStatus:"__lunora_admin__:migrationStatus",patchRows:"__lunora_admin__:patchRows",pitrRestore:"__lunora_admin__:pitrRestore",rankBefore:"__lunora_admin__:rankBefore",rankPage:"__lunora_admin__:rankPage",readTablePage:"__lunora_admin__:readTablePage",rebuildCompanions:"__lunora_admin__:rebuildCompanions",recordAuthEvent:"__lunora_admin__:recordAuthEvent",recordContainerEvent:"__lunora_admin__:recordContainerEvent",recordMail:"__lunora_admin__:recordMail",recordQueueMessage:"__lunora_admin__:recordQueueMessage",releaseShardRegistration:"__lunora_admin__:releaseShardRegistration",replayQueueMessage:"__lunora_admin__:replayQueueMessage",retryOutboxEntry:"__lunora_admin__:retryOutboxEntry",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",sendWorkflowEvent:"__lunora_admin__:sendWorkflowEvent",setIssueSeverity:"__lunora_admin__:setIssueSeverity",storageOrphans:"__lunora_admin__:storageOrphans",storageReferences:"__lunora_admin__:storageReferences",storageRules:"__lunora_admin__:storageRules",studioFeatures:"__lunora_admin__:studioFeatures",writeRow:"__lunora_admin__:writeRow"},Z=50,y=500,ee=30,te=200,c="__doc__",x=e=>{try{const t=JSON.parse(e);return t!==null&&typeof t=="object"&&!Array.isArray(t)?t:void 0}catch{return}},ne=e=>{const{[T]:t,...n}=e;return t===void 0?n:t===null||typeof t!="object"||Array.isArray(t)?{[T]:t,...n}:{...n,...Q(t)}},re=(e,t)=>{if(!e.includes(c))return{columns:e,rows:t};const n=[];for(const a of t){const i=a[c],_=typeof i=="string"?x(i):void 0;if(_===void 0)return{columns:e,rows:t};const l=Object.fromEntries(Object.entries(a).filter(([m])=>m!==c));n.push({...l,...ne(_)})}const r=e.filter(a=>a!==c),o=[],s=new Set(r);for(const a of n)for(const i of Object.keys(a))s.has(i)||(s.add(i),o.push(i));return{columns:[...r,...o],rows:n}},S=e=>`instr(lower(CAST(${e} AS TEXT)), lower(?)) > 0`,C=(e,t,n)=>Math.min(Math.max(e,t),n),U=(e,t)=>{const n=e.exec(`SELECT COUNT(*) AS c FROM ${t}`).one();return Number(n.c)},Ue=e=>{const t=e.exec("SELECT name FROM sqlite_master WHERE type = 'table' ORDER BY name").toArray(),n=[];for(const{name:r}of t)w(r)||n.push({name:r,rowCount:U(e,u(r))});return n},q=(e,t)=>e.exec("SELECT name FROM sqlite_master WHERE type = 'table' AND name = ? LIMIT 1",t).toArray().length>0,O=(e,t)=>{if(w(t)||!q(e,t))throw new d("UNKNOWN_TABLE",`unknown table: ${t}`,{status:404})},A=(e,t)=>e.exec(`PRAGMA table_info(${t})`).toArray().map(n=>n.name),I={eq:"=",gt:">",gte:">=",lt:"<",lte:"<=",ne:"<>"},F=100,M=(e,t)=>{if(t>F)throw new d("BAD_REQUEST",`the query over ${e} binds ${String(t)} parameters, and a statement takes at most ${String(F)} — remove some filters or narrow the search`)},P=e=>typeof e=="string"?e:typeof e=="number"||typeof e=="boolean"?String(e):"",oe=new Set(["gt","gte","lt","lte"]),se=e=>e.operator==="contains"?P(e.value)==="":oe.has(e.operator)&&e.value==="",W=(e,t)=>{if(!t.every(n=>typeof n=="string"&&n!==""))throw new d("BAD_REQUEST",`nested path under ${e} must name each field with a non-empty string, got ${JSON.stringify(t)}`);return`$.${[e,...t].map(n=>V(n)).join(".")}`},b=(e,t,n=[])=>{const r=t.includes(e),o=t.includes(c);if(!(!r&&!o)){if(r){if(n.length>0)throw new d("BAD_REQUEST",`${e} is a physical column, so it has no nested path`);return{expression:u(e),params:[]}}return{expression:`json_extract(${u(c)}, ?)`,params:[W(e,n)]}}},ae=/^-?\d+$/u,v=(e,t)=>{const{value:n}=e;if(t==="bigint"&&(typeof n=="number"||typeof n=="string")){const r=typeof n=="number"&&Number.isInteger(n)?BigInt(n).toString():String(n).trim();if(!ae.test(r))throw new d("BAD_REQUEST",`bigint column ${e.column} can only be filtered by an integer, got ${JSON.stringify(n)}`);return L(BigInt(r))}if(t==="bigint"&&typeof n!="bigint")throw new d("BAD_REQUEST",`bigint column ${e.column} can only be filtered by an integer, got ${JSON.stringify(n)}`);return L(n)},ie=(e,t)=>t==="bigint"&&typeof e=="string"?z(e)??e:e,_e=e=>{if(typeof e=="boolean")return{params:[],sql:`j.type = '${e?"true":"false"}'`};if(typeof e=="string")return{params:[e],sql:"j.type = 'text' AND j.value = ?"};if(typeof e=="number"&&Number.isFinite(e))return{params:[e],sql:"j.type IN ('integer', 'real') AND j.value = ?"};throw new d("BAD_REQUEST",'"has" needs a string, number or boolean value to look for in the array')},le=(e,t,n)=>{if(t.includes(e.column))throw new d("BAD_REQUEST",`"has" needs an array-valued document field, but ${e.column} is a physical column`);if(!t.includes(c))return;const r=e.path??[];if(r.length===0&&n?.[e.column]==="bigint")throw new d("BAD_REQUEST",`"has" is not supported on bigint column ${e.column} — it stores a sort key, not an array`);const o=_e(e.value),s=W(e.column,r),a=u(c),i=`SELECT 1 FROM json_each(${a}, ?) AS j WHERE typeof(j.key) = 'integer' AND ${o.sql}`;return{params:[`${s}[0]`,s,...o.params,`${s}[1]`,`${s}[2]`,...o.params],sql:`CASE WHEN json_extract(${a}, ?) IS NOT '${R}' THEN EXISTS (${i}) WHEN json_extract(${a}, ?) IS 'arr' THEN EXISTS (${i}) ELSE 0 END`}},ce=e=>{if(!(e==null||typeof e=="string"||typeof e=="boolean"))try{return X(e)?JSON.stringify(G(e)):void 0}catch(t){throw new d("BAD_REQUEST",`this filter value cannot be compared: ${t instanceof Error?t.message:String(t)}`)}},ue=e=>typeof e=="number"?"'integer', 'real'":e?"'true'":"'false'",de=(e,t,n)=>{const r=ce(e.value);if(r!==void 0){if(e.operator!=="eq"&&e.operator!=="ne")throw new d("BAD_REQUEST",`a value nested under ${e.column} that holds a bigint, bytes, date, map or set can only be compared with = or <>, got ${e.operator}`);return{params:[...n,r],sql:`${t} ${I[e.operator]} ?`}}const{operator:o}=e;if(o==="gt"||o==="gte"||o==="lt"||o==="lte"){let s="'integer', 'real'";return typeof e.value=="string"?s="'text'":typeof e.value=="boolean"&&(s="'true', 'false'"),{params:[...n,...n,v(e,void 0)],sql:`(json_type(${u(c)}, ?) IN (${s}) AND ${t} ${I[o]} ?)`}}if((o==="eq"||o==="ne")&&(typeof e.value=="boolean"||typeof e.value=="number")){const s=`json_type(${u(c)}, ?) IN (${ue(e.value)}) AND ${t} = ?`,a=v(e,void 0);return o==="eq"?{params:[...n,...n,a],sql:`(${s})`}:{params:[...n,...n,...n,a],sql:`(${t} IS NOT NULL AND NOT (${s}))`}}},H=e=>{const t=`json_tree(${e})`;return`NOT (typeof(j.key) = 'integer' AND j.key IN (0, 1) AND EXISTS (SELECT 1 FROM ${t} AS f WHERE f.parent = j.parent AND f.key = 0 AND f.type = 'text' AND f.atom = '${R}') AND (WITH RECURSIVE links(node, k) AS (SELECT j.parent, 0 UNION ALL SELECT c.parent, links.k + 1 FROM links JOIN ${t} AS c ON c.id = links.node WHERE typeof(c.key) = 'integer' AND c.key = 2 AND ${((r,o)=>`(SELECT count(*) FROM ${t} AS ${r} WHERE ${r}.parent = ${o} AND typeof(${r}.key) = 'integer' AND ((${r}.key = 0 AND ${r}.atom = '${R}') OR (${r}.key = 1 AND ${r}.atom = 'arr'))) = 2`)("h","c.parent")}) SELECT max(k) FROM links) % 2 = 0)`},me=(e,t,n)=>({params:[t,t,n,t,t,n,t,t,n,t,t,t],sql:`CASE WHEN json_type(${e}, ?) IN ('text', 'integer', 'real') THEN ${S(`json_extract(${e}, ?)`)} WHEN json_type(${e}, ?) IN ('true', 'false') THEN ${S(`json_type(${e}, ?)`)} WHEN json_type(${e}, ?) IN ('array', 'object') THEN EXISTS (SELECT 1 FROM json_tree(${e}, ?) AS j WHERE j.type IN ('text', 'integer', 'real', 'true', 'false') AND ${S("CASE WHEN j.type IN ('true', 'false') THEN j.type ELSE j.value END")} AND ${H(`${e}, ?`)}) ELSE 0 END`}),fe=(e,{expression:t,kind:n,pathParameters:r,physical:o})=>{const s=e.path??[];if(n==="bigint")throw new d("BAD_REQUEST",`"contains" is not supported on bigint column ${e.column} — use =, <, > instead`);const a=P(e.value);return s.length===0&&o?{params:[a],sql:S(t)}:s.length===0?me(u(c),r[0],a):{params:[...r,...r,a],sql:`(json_type(${u(c)}, ?) IN ('text', 'integer', 'real') AND ${S(t)})`}},pe=(e,t,n)=>{if(e.operator==="has")return le(e,t,n);const r=e.path??[],o=b(e.column,t,r);if(o===void 0||se(e))return;const{expression:s,params:a}=o,i=t.includes(e.column)||r.length>0?void 0:n?.[e.column];if(e.operator==="contains")return fe(e,{expression:s,kind:i,pathParameters:a,physical:t.includes(e.column)});if(e.value===null&&(e.operator==="eq"||e.operator==="ne"))return{params:a,sql:`${s} IS ${e.operator==="ne"?"NOT ":""}NULL`};if(r.length>0){const _=de(e,s,a);if(_!==void 0)return _}return{params:[...a,v(e,i)],sql:`${s} ${I[e.operator]} ?`}},Ee=new Set(["date","timestamp"]),ge=[`$.${T}`,`$."${T}"`].map(e=>`substr(j.fullkey, 1, ${String(e.length+1)}) NOT IN ('${e}.', '${e}[')`).join(" AND "),Se=e=>`(${S(e)} AND EXISTS (SELECT 1 FROM json_tree(${e}) AS j WHERE j.type IN ('text', 'integer', 'real', 'true', 'false') AND ${S("CASE WHEN j.type IN ('true', 'false') THEN j.type ELSE j.value END")} AND ${ge} AND ${H(e)}))`,he=/["\\\u0000-\u001F]/u,ye=e=>he.test(e)?"":e,be=/^(\d{4})(?:-(\d{2}))?(?:-(\d{2}))?$/u,Ne=e=>{const t=be.exec(e.trim());if(t===null)return;const n=Number(t[1]),r=t[2]===void 0?void 0:Number(t[2]),o=t[3]===void 0?void 0:Number(t[3]);if(r!==void 0&&(r<1||r>12)||o!==void 0&&(o<1||o>31)||n<100)return;const s=Date.UTC(n,(r??1)-1,o??1);if(o!==void 0&&new Date(s).getUTCDate()!==o)return;let a;return o!==void 0?a=Date.UTC(n,(r??1)-1,o+1):r===void 0?a=Date.UTC(n+1,0,1):a=Date.UTC(n,r,1),{from:s,to:a}},D=(e,t,n,r)=>{const o=[],s=[];if(t!==""&&e.length>0){const a=e.map(_=>_===c?Se(u(_)):S(u(_)));s.push(...e.flatMap(_=>_===c?[ye(t),t]:[t]));const i=Ne(t);if(i!==void 0){for(const l of e)a.push(`(${u(l)} >= ? AND ${u(l)} < ?)`),s.push(i.from,i.to);const _=Object.keys(r??{}).filter(l=>!e.includes(l)&&Ee.has(r?.[l]??""));_.length>0&&e.includes(c)&&(a.push(`EXISTS (SELECT 1 FROM json_each(${u(c)}) AS j WHERE j.key IN (SELECT value FROM json_each(?)) AND j.type IN ('integer', 'real') AND j.value >= ? AND j.value < ?)`),s.push(JSON.stringify(_),i.from,i.to))}o.push(`(${a.join(" OR ")})`)}for(const a of n??[]){const i=pe(a,e,r);i!==void 0&&(o.push(`(${i.sql})`),s.push(...i.params))}return o.length===0?void 0:{parameters:s,where:o.join(" AND ")}},Te=(e,t)=>{if(e===void 0)return;const n=b(e.column,t);if(n===void 0)return;const r=e.direction==="desc"?"DESC":"ASC";return{params:n.params,sql:`${n.expression} ${r}`}},qe=(e,t)=>{const{table:n}=t;O(e,n);const r=C(Math.trunc(t.limit??Z),1,y),o=Math.max(0,Math.trunc(t.offset??0)),s=u(n),a=A(e,s),i=t.search?.trim()??"",_=N=>{if(t.refs===void 0)return N;const $={};for(const k of N.columns){const j=t.refs[k];j!==void 0&&($[k]=j)}return Object.keys($).length>0?{...N,refs:$}:N},l=D(a,i,t.filters,t.columnKinds),m=Te(t.orderBy,a),p=l===void 0?"":` WHERE ${l.where}`,g=m===void 0?"":` ORDER BY ${m.sql}`,E=l?.parameters??[],h=m?.params??[];M(n,E.length+h.length+2);let f;t.skipCount||(f=l===void 0?U(e,s):Number(e.exec(`SELECT COUNT(*) AS c FROM ${s}${p}`,...E).one().c));const B=e.exec(`SELECT * FROM ${s}${p}${g} LIMIT ? OFFSET ?`,...E,...h,r,o).toArray();return _({...re(a,B),sqlColumns:a,total:f})},Pe=(e,t)=>{const{table:n}=t;O(e,n);const r=C(Math.trunc(t.limit??y),1,y),o=u(n),s=A(e,o),a=t.search?.trim()??"";for(const f of t.filters??[])if(b(f.column,s,f.path??[])===void 0)throw new d("BAD_REQUEST",`unknown column: ${f.column}`);const i=D(s,a,t.filters,t.columnKinds);if(i===void 0&&(t.filters?.length??0)>0)throw new d("BAD_REQUEST",`the filters on ${n} are all empty, so the predicate constrains no rows — refusing to select the whole table`);const _=[],l=[];i!==void 0&&(_.push(i.where),l.push(...i.parameters)),t.after!==void 0&&(_.push("id > ?"),l.push(t.after));const m=_.length===0?"":` WHERE ${_.join(" AND ")}`,p=t.after===void 0?"":" ORDER BY id";M(n,l.length+1);const g=e.exec(`SELECT id FROM ${o}${m}${p} LIMIT ?`,...l,r+1).toArray(),E=g.length>r,h=g.slice(0,r).map(f=>f.id);return{hasMore:E,ids:h}},Ae=(e,t,n,r)=>{const o=new Set(n.filter(a=>a!==c));if(!n.includes(c))return o;for(const a of Object.keys(r??{}))o.add(a);const s=e.exec(`SELECT ${u(c)} AS doc FROM ${t} LIMIT ?`,y).toArray();for(const{doc:a}of s){const i=typeof a=="string"?x(a):void 0;if(i!==void 0)for(const _ of Object.keys(i))o.add(_)}return o},We=(e,t)=>{const{column:n,table:r}=t;O(e,r);const o=u(r),s=A(e,o);if(!Ae(e,o,s,t.columnKinds).has(n))throw new d("UNKNOWN_COLUMN",`unknown column: ${n}`,{status:404});const a=b(n,s);if(a===void 0)throw new d("UNKNOWN_COLUMN",`unknown column: ${n}`,{status:404});const i=C(Math.trunc(t.limit??ee),1,te),_=t.search?.trim()??"",l=D(s,_,t.filters,t.columnKinds),m=l===void 0?"":` WHERE ${l.where}`,p=l?.parameters??[];M(r,a.params.length*2+p.length+1);const g=e.exec(`SELECT ${a.expression} AS value, COUNT(*) AS count FROM ${o}${m} GROUP BY ${a.expression} ORDER BY count DESC LIMIT ?`,...a.params,...p,...a.params,i+1).toArray(),E=g.length>i,h=s.includes(n)?void 0:t.columnKinds?.[n];return{truncated:E,values:g.slice(0,i).map(f=>({count:Number(f.count),value:ie(f.value,h)}))}},He=(e,t,n)=>{const r={},o=n.slice(0,y);for(const s of o)r[s]=[];if(o.length===0)return{references:r,storageColumns:t};for(const[s,a]of Object.entries(t)){if(w(s)||!q(e,s))continue;const i=u(s),_=A(e,i);for(const l of a){const m=b(l,_);if(m===void 0)continue;const p=J("sqlite",Y(K.raw(m.expression),o,!1)),g=e.exec(`SELECT id, ${m.expression} AS ref FROM ${i} WHERE ${p.sql}`,...m.params,...m.params,...p.params).toArray();for(const E of g)r[E.ref]?.push({column:l,id:E.id,table:s})}}return{references:r,storageColumns:t}},Be=e=>{const n=e.filter(o=>o.authenticated!==!1).map((o,s)=>{const a=Object.values(o.subs??{}).map(i=>({args:i.args,functionPath:i.functionPath,table:i.table}));return{admin:o.admin===!0,id:s,subscriptions:a}}),r=n.reduce((o,s)=>o+s.subscriptions.length,0);return{connections:n,totalConnections:n.length,totalSubscriptions:r}},$e=20,Qe=()=>({maxMs:0,passes:0,peakSocketsIterated:0,socketsDelivered:0,socketsIterated:0,totalMs:0}),Xe=()=>({run:0,served:0}),Ge=()=>({drains:0,pairsSkipped:0}),Ke=(e,t,n)=>({drains:e.drains+t,pairsSkipped:e.pairsSkipped+n}),Ve=(e,t,n)=>({run:e.run+t,served:e.served+n}),Je=(e,t,n,r)=>({maxMs:Math.max(e.maxMs,r),passes:e.passes+1,peakSocketsIterated:Math.max(e.peakSocketsIterated,t),socketsDelivered:e.socketsDelivered+n,socketsIterated:e.socketsIterated+t,totalMs:e.totalMs+r}),Ye=(e,t=$e)=>{const n=new Map,r=new Map,o=e.filter(i=>i.authenticated!==!1);for(const i of o){for(const _ of Object.values(i.shapes??{})){const l=_.name??"(unknown shape)";n.set(l,(n.get(l)??0)+1)}for(const _ of i.whispers??[])r.set(_,(r.get(_)??0)+1)}const s=[...[...n].map(([i,_])=>({kind:"shape",subscribers:_,topic:i})),...[...r].map(([i,_])=>({kind:"whisper",subscribers:_,topic:i}))];return s.sort((i,_)=>_.subscribers-i.subscribers||i.topic.localeCompare(_.topic)),{peakSubscribers:s[0]?.subscribers??0,topics:s.slice(0,t),totalConnections:o.length}};export{xe as ADMIN_FUNCTIONS,je as ADMIN_FUNCTION_PREFIX,$e as DEFAULT_FANOUT_TOPIC_LIMIT,Fe as FLAGS_FUNCTION_PREFIX,y as MAX_PAGE_SIZE,Le as RELATION_FUNCTION_PREFIX,Qe as createFanoutCounters,Ge as createGlobalPollCounters,Xe as createShapeProbeCounters,Ne as datePrefixRange,We as facetColumn,He as findStorageReferences,w as isInternalTableName,se as isVacuousFilterClause,Ue as listTables,qe as readTablePage,Je as recordFanoutPass,Ke as recordGlobalPollPass,Ve as recordShapeProbePass,Pe as selectMatchingIds,Ye as summarizeFanoutTopics,Be as summarizeSubscriptions};
|
|
@@ -1,4 +0,0 @@
|
|
|
1
|
-
import{LunoraError as p}from"@lunora/errors";const S="x",u=" ",L={'"':'"',"'":"'","[":"]","`":"`"},g=(n,t)=>{let e=t+2;for(;e<n.length&&n[e]!==`
|
|
2
|
-
`;)e+=1;return e},m=(n,t)=>{const e=n.indexOf("*/",t+2);return e===-1?-1:e+2},A=n=>{const t=n.split("");let e=0;for(;e<n.length;){const o=n[e]??"",i=L[o];if(o==="-"&&n[e+1]==="-"){const s=g(n,e);t.fill(u,e,s),e=s}else if(o==="/"&&n[e+1]==="*"){const s=m(n,e);if(s===-1)return;t.fill(u,e,s),e=s}else if(i!==void 0){let s=e+1;for(;s<n.length;)if(n[s]!==i)s+=1;else if(i!=="]"&&n[s+1]===i)s+=2;else break;if(s>=n.length)return;t.fill(S,e,s+1),e=s+1}else e+=1}for(let o=0;o<n.length;o+=1)n[o]===`
|
|
3
|
-
`&&(t[o]=`
|
|
4
|
-
`);return t.join("")},N=/^(?:explain\s+(?:query\s+plan\s+)?)?(?:select|with)\b/iu,w=/\b(?:alter|attach|create|delete|detach|drop|insert|pragma|reindex|truncate|update|vacuum)\b|\breplace\b(?!\s*\()/iu,x=/^\w+/u,O=/;\s*$/u,_=/\s/u,y=n=>{let t=0;for(;t<n.length;){const e=n[t];if(e!==void 0&&_.test(e))t+=1;else if(e==="-"&&n[t+1]==="-")t=g(n,t);else if(e==="/"&&n[t+1]==="*"){const o=m(n,t);if(o===-1)break;t=o}else break}return t},h=n=>{const t=y(n),e=n.slice(t).trimEnd();if(e==="")return{code:"SQL_EMPTY",message:"the query is empty"};const i=(A(e)??e).replace(O,""),s=e.slice(0,i.length),r=i.indexOf(";");if(r!==-1)return{code:"SQL_MULTIPLE_STATEMENTS",length:1,message:"only a single statement may be run",offset:t+r};const a="the SQL editor is read-only — only SELECT / WITH / EXPLAIN queries are allowed";if(!N.test(s))return{code:"SQL_NOT_READONLY",length:x.exec(s)?.[0].length??1,message:a,offset:t};const c=w.exec(s);if(c!==null)return{code:"SQL_NOT_READONLY",length:c[0].length,message:`${a} (\`${c[0].toUpperCase()}\` is not allowed)`,offset:t+c.index}},T=1e3,f=n=>{const t=[];for(const e of n){if(t.length===T)return{items:t,truncated:!0};t.push(e)}return{items:t,truncated:!1}},C=n=>{const t=new Map;return n.map(e=>{const o=(t.get(e)??0)+1;return t.set(e,o),o===1?e:`${e}:${String(o)}`})},R=n=>{const t=h(n);if(t!==void 0)throw new p(t.code,t.message,{status:400})},M=(n,t)=>{R(t);const e=n.exec(t),{columnNames:o,raw:i}=e;if(o===void 0||i===void 0){const{items:l,truncated:d}=f(e);return{columns:l.length>0?Object.keys(l[0]):[],rowCount:l.length,rows:l,truncated:d}}const s=C(o),{items:r,truncated:a}=f(i.call(e)),c=r.map(l=>Object.fromEntries(s.map((d,E)=>[d,l[E]])));return{columns:s,rowCount:c.length,rows:c,truncated:a}},b=/near "([^"]*)": syntax error/iu,v=/^SCAN (?:TABLE )?(?!CONSTANT\b|SUBQUERY\b)([^\s(]+)/u,k=(n,t)=>{if(t==="")return{};const e=n.indexOf(t);return e===-1?{}:{length:t.length,offset:e}},Q=(n,t)=>{const e=h(t);if(e!==void 0)return{diagnostics:e.code==="SQL_EMPTY"?[]:[{length:e.length,message:e.message,offset:e.offset,severity:"error",source:"gate"}],plan:[]};let o;try{o=n.exec(`EXPLAIN QUERY PLAN ${t}`).toArray().map(r=>{const{detail:a}=r;return typeof a=="string"?a:""}).filter(r=>r!=="")}catch(r){const a=r instanceof Error?r.message:String(r),c=b.exec(a);return{diagnostics:[{...c?k(t,c[1]??""):{},message:a,severity:"error",source:"syntax"}],plan:[]}}const i=[],s=new Set;for(const r of o){const a=v.exec(r);if(a){const c=a[1]??"";s.has(c)||(s.add(c),i.push({message:`full table scan on \`${c}\` — this query reads every row`,severity:"warning",source:"plan"}))}}return{diagnostics:i,plan:o}};export{T as MAX_SQL_ROWS,R as assertReadonly,Q as lintReadonlySql,M as runReadonlySql};
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{LunoraError as S}from"@lunora/errors";import{q as mt}from"./MAX_TOKEN_LENGTH-iFEGEcDL-DBPC6ZWl.mjs";import{S as qn,l as qe,s as Pn}from"./fts-companion-CE3EmIjk.mjs";import{decodeWire as Un,stableWireKey as Pt}from"@lunora/wire";import{sql as a}from"drizzle-orm";import{throwingScheduler as On,aggregateSqlFunction as Pe,normalizeCountArgument as jn}from"./AGGREGATE_SQL_FUNCTION-C_ZipS9R.mjs";import{aggregateTableName as it,encodeAggregateKey as st,readAggregateValue as ct}from"./aggregateTableName-B_CtIQCS.mjs";import{mergeWhere as Q,CountRlsUnsupportedError as at,selectIndexForGroupBy as Gn,selectIndexForCount as Hn,selectIndexForAggregate as Kn}from"./CountRlsUnsupportedError-BvsDqfO2.mjs";import{backfillSearchIndexesForTable as Nn,searchIndexCoversTable as Qn}from"./backfillAggregateIndexes-Pk0KLrfk.mjs";import{backfillAggregateIndexes as Bi,backfillRankIndexes as qi,backfillSearchIndexes as Pi}from"./backfillAggregateIndexes-Pk0KLrfk.mjs";import{appendCdcChange as Vn,readCdcDocAtOrBefore as Jn}from"./CDC_LOG_TABLE-BFGgqai8.mjs";import{CDC_LOG_TABLE as Oi,applyCdcChanges as ji,bumpCdcEpoch as Gi,cdcCanVouchFor as Hi,cdcForkedError as Ki,cdcSeqLeavingRows as Ni,cdcTouchesTables as Qi,cdcTrimmedError as Vi,compactCdcDocs as Ji,cursorBelowRetainedFloor as zi,minCdcReplayableSeq as Yi,minCdcSeq as Xi,readCdcChangeKeys as Zi,readCdcChanges as es,readCdcCursor as ts,readCdcEpoch as ns,trimCdcChanges as os}from"./CDC_LOG_TABLE-BFGgqai8.mjs";import{allocateCommitSeq as zn,COMMIT_SEQ_FIELD as Yn}from"./COMMIT_SEQ_FIELD-Da1DjGqo.mjs";import{createCompanionSync as Xn}from"./createCompanionSync-CEht4hXX.mjs";import{isMemoryTable as Ut}from"./clearMemoryTables-aMRERF0w.mjs";import{computeRankPage as Ot}from"./computeRankPage-BZIpATcs.mjs";import{SCAN_DEP as j}from"./SCAN_DEP-D7qE3iUe.mjs";import{runSql as he,runDrizzle as K}from"./runDrizzle-RC09zZrh.mjs";import{p as Zn,j as wt,D as ie,r as xe,W as eo,k as le,b as Ue,A as dt,a as Oe,m as ue,e as fe,s as to,t as no,u as oo,i as ro,q as jt,h as gn,g as io}from"./do-sql-105TONaE.mjs";import{renderSql as yn,unionAll as $n,WORKERD_SQLITE_LIMITS as En}from"./WORKERD_SQLITE_LIMITS-B_4w7tzY.mjs";import{a as so,u as co}from"./estimate-bytes-C-C35VXL.mjs";import{coveringGeohashes as ao,boundingBoxGeohashes as lo,haversineMeters as uo,pointInBoundingBox as fo}from"./GEO_DEFAULT_PRECISION-CqpQZ-J_.mjs";import{NotFoundError as ho}from"./NotFoundError-BhF7FeFr.mjs";import{resolvePatch as wo,assertPatchAllowed as po,operatorFields as go,readPatchField as Gt}from"./assertPatchAllowed-CA_H466g.mjs";import{tiebreakDirectionFor as yo,encodeCursor as Qe,nullsOrderSuffix as $o,normalizeOrderKeys as Ht,uniqueIndexFields as Eo,buildSeekWhere as mo,decodeCursor as Kt,buildSeekBeforeWhere as So,softDeleteScope as Ae,applySelect as pt}from"./CURSOR_PREFIX-6offuG6M.mjs";import{rankTableName as Nt,sortColumnName as Qt,resolveRankPartition as Ro,encodePartitionKey as vo,RANK_TIEBREAK as To,rankPivotConditionSql as _o}from"./RANK_TIEBREAK-D3ye2GsL.mjs";import{UNVOUCHABLE_DEP as Vt}from"./UNVOUCHABLE_DEP-Ds9gxVqs.mjs";import{idIndexKey as Ao,withUnknownIndexKeys as Io,indexKeysForRow as xo,buildIndexRange as bo}from"./buildIndexRange-BTChxh3k.mjs";import{r as Ve,j as be,c as Z,t as ze,i as Jt}from"./where-sql-BjY4rnqb.mjs";import{serializeSqlValue as Ce}from"./serializeSqlValue-DeoBMpZ2.mjs";import{quoteIdentifier as Me}from"./quoteIdentifier-CObIFRhb.mjs";import{whereOfFilter as Co,isPushableWhere as Mo}from"./isPushableWhere-BeYAOjUb.mjs";import{deriveRelationEdges as Do,findRelated as ko}from"./RELATED_DEFAULT_LIMIT-CVqN4JEu.mjs";import{assertFlatPredicate as lt,resolveRelationPredicates as Lo,composeReadPredicate as Fo}from"./DEFAULT_MAX_RELATION_KEYS-DfrMi_eE.mjs";import{describeRelationWrites as Wo}from"./describeRelationWrites-omar6-u9.mjs";import{runRowValidators as je,transformOnlyDefinition as Bo,applyInsertDefaults as gt,resolveWith as zt,relationHooks as Yt,applyOnDelete as qo,fanOutScalarCounts as Po}from"./applyInsertDefaults-CVukTkQ5.mjs";import{guardWriter as Uo}from"./RLS_UNWRAP_SYMBOL-H6J96vgK.mjs";import{mayHoldProjectedValue as Oo}from"./BIGINT_KEY_DIGITS-DE6yshOt.mjs";import{createSystemReader as jo}from"./createSystemReader-BSCxr8Qs.mjs";import{ConflictError as se}from"./ConflictError-C8GtJmjS.mjs";import{hasTrigger as Xt,runTriggers as Go}from"./hasTrigger-CjlwI4le.mjs";import{advanceClientWatermark as is,migrateClientWatermark as ss,readClientWatermark as cs}from"./CLIENT_WATERMARK_TABLE-De7z_OHV.mjs";import{IDEMPOTENCY_TABLE as ds,readIdempotent as ls,trimIdempotent as us,writeIdempotent as fs}from"./IDEMPOTENCY_TABLE-COrgeP3O.mjs";import{runShardMigrations as ws}from"./runShardMigrations-xu993yo2.mjs";import{selectShapeMembers as gs,selectShapeRows as ys}from"./selectShapeMembers-Dqx_m7BF.mjs";const Ho=n=>{const r=atob(n),o=Uint8Array.from(r,s=>s.codePointAt(0)??0);return new TextDecoder().decode(o)},Ko=()=>new S("BAD_REQUEST","invalid cursor"),Zt=16,en=8,z=1024,St=(n,r)=>r.query(n),No=(n,r)=>{if(n.length===0)return 0;let o=0;for(const[s,c]of r.entries()){const u=s===r.length-1;let g=0;for(const m of n)(u?m.startsWith(c):m===c)&&(g+=1);if(g===0)return 0;o+=g}return o},Qo=(n,r)=>{if(!r)return{exact:!0,lower:n,upper:n};const o=[...n].at(-1)??"",s=(o.codePointAt(0)??0)+1;if(s>=55296&&s<=57343||s>1114111)return{exact:!0,lower:n,upper:n};const c=n.slice(0,n.length-o.length);return{exact:!1,lower:n,upper:c+String.fromCodePoint(s)}},Vo=(n,r,o)=>{const s={eq:(c,u)=>{if(!n.definition.filterFields?.includes(c))throw new S("INTERNAL",`field "${c}" is not a filter field of search index "${n.indexName}" on table "${r}"`);if(n.filters.length>=en)throw new S("BAD_REQUEST",`search index "${n.indexName}" on table "${r}": at most ${String(en)} .eq() filters are supported per search query`);return n.filters.push({field:c,value:u}),s},search:(c,u)=>{const g=n;if(c!==g.definition.field)throw new S("INTERNAL",`search index "${g.indexName}" on table "${r}" indexes "${g.definition.field}", not "${c}"`);const m=St(u,o).length;if(m>Zt)throw new S("BAD_REQUEST",`search index "${g.indexName}" on table "${r}": at most ${String(Zt)} search terms are supported (got ${String(m)})`);return g.field=c,g.query=u,g.hasQuery=!0,s}};return s},Jo=n=>{if(n.length>z)throw new S("BAD_REQUEST",`more than ${String(z)} documents match this search — narrow it with filters or read it a page at a time with .paginate()`)},zo=n=>Math.min(n.offset+n.numItems+1,z),Yo=n=>btoa(`search:${String(n)}`),Xo=n=>{let r;try{r=Ho(n)}catch{return}if(!r.startsWith("search:"))return;const o=Number(r.slice(7));return Number.isInteger(o)&&o>=0?o:void 0},Zo=n=>{if(typeof n.endCursor=="string")throw new S("BAD_REQUEST","bounded (endCursor) pagination is not supported on search queries — relevance order has no stable range boundary");if(!Number.isFinite(n.numItems))throw new S("BAD_REQUEST",`search pagination needs a finite numItems, got ${String(n.numItems)}`);const r=Math.max(0,Math.floor(n.numItems)),o=n.cursor?Xo(n.cursor):0;if(o===void 0)throw Ko();if(o+r>=z)throw new S("BAD_REQUEST",`search pagination reaches the ${String(z)}-document limit (offset ${String(o)} + ${String(r)} requested) — a page must end below the cap so the probe row that answers \`hasMore\` still fits: retry with numItems ${String(Math.max(1,z-o-1))} or fewer, or narrow the query or the filters instead`);return{numItems:r,offset:o}},er=(n,r)=>{const o=r.offset+r.numItems,s=r.numItems>0&&n.length>o;return{continueCursor:s?Yo(o):null,isDone:!s,page:n.slice(r.offset,o)}},tr=n=>{if(n===void 0)return z+1;if(!Number.isFinite(n))return z;const r=Math.max(0,Math.floor(n));if(r>z)throw new S("BAD_REQUEST",`search returns at most ${String(z)} documents (asked for ${String(r)}) — narrow the query or paginate instead`);return r},mn=500,Sn=(n,r,o)=>{if(n!==void 0&&n!==Number.POSITIVE_INFINITY&&(!Number.isInteger(n)||n<0))throw o(`${r}: batch limit must be a non-negative integer`);return n??mn},Rn=(n,r,o,s)=>{if(n>r)throw s(`${o}: batch of ${String(n)} exceeds the limit of ${String(r)} (raise options.limit or chunk the call)`)},nr=32,or=1024,vn=(n,r,o,s)=>{const c=`SELECT id, _creationTime, ${Me(ie)} FROM ${Me(n)}`,u=`ORDER BY ${o}${s===void 0?"":` LIMIT ${String(s)}`}`;return r===void 0?Ve(`${c} ${u}`):be(`${c} WHERE `,r,` ${u}`)},Ye={fieldRef:n=>Ve(wt(n)),rangeTypeGuard:(n,r)=>Ve(Zn(n,r)),serialize:Ce},rr=n=>n===void 0?"":$o(n==="first"),Tn=n=>{const r=n.map(o=>`${wt(o.field)} ${o.direction==="desc"?"DESC":"ASC"}${rr(o.nulls)}`);return n.some(o=>o.field==="_id"||o.field==="id")||r.push(`${wt("id")} ${yo(n)==="desc"?"DESC":"ASC"}`),r.join(", ")},ir={"<":"lt","<=":"lte","=":"eq",">":"gt",">=":"gte"},_n=n=>new Set(n.sqlConditions.filter(r=>r.comparator==="=").map(r=>r.field)),sr=n=>{const r=_n(n);let o=0;for(;o<n.indexFields.length&&r.has(n.indexFields[o]??"");)o+=1;return n.indexFields.slice(o)},cr=(n,r)=>{const o=n.order,s=sr(n),{shape:c}=r;return s.length>0?Ht(s.map(u=>({[u]:o})),c,{pinned:_n(n),uniqueBy:Eo(r.indexes,c)}):Ht([{_creationTime:o}],c)},ar=(n,r,o,s)=>{const c=n.sqlConditions.map(u=>({[u.field]:{[ir[u.comparator]??"eq"]:u.value}}));if(o&&c.push(mo(r,Kt(o))),s&&c.push(So(r,Kt(s))),c.length!==0)return c.length===1?c[0]:{AND:c}},dr=n=>{if(n.want!==void 0)return n.selective?Math.max(n.want,nr):n.want},yt=(n,r,o,s,c,u,g)=>{const m=cr(s,o),y=Tn(m),l=[],{filters:D,want:I}=u;let T=u.cursor??void 0,x=dr(u);if(I===0)return{documents:l,orderKeys:m};for(;;){const B=Z(ar(s,m,T,u.endCursor),Ye,ze),P=vn(r,c&&B?be(B," AND ",c):c??B,y,x),W=he(n,P.text,...P.params).toArray();let U={};g(W.length);for(const G of W)if(U=xe(G),D.every(ee=>ee(U))&&l.push(U)===I)return{documents:l,orderKeys:m};if(x===void 0||W.length<x)return{documents:l,orderKeys:m};T=Qe(U,m),x=Math.max(x,Math.min(x*2,or))}},lr=(n,r,o,s,c,u,g,m)=>{const y=Math.max(0,Math.floor(c.numItems));if(typeof c.endCursor=="string"){const{documents:B,orderKeys:P}=yt(n,r,o,s,u,{cursor:c.cursor,endCursor:c.endCursor,filters:g.all,selective:g.selective,want:void 0},m),W=B.length>=2?B[Math.floor(B.length/2)-1]:void 0;return{continueCursor:c.endCursor,isDone:!0,page:B,splitCursor:W?Qe(W,P):null}}const{documents:l,orderKeys:D}=yt(n,r,o,s,u,{cursor:c.cursor,filters:g.all,selective:g.selective,want:y+1},m),I=l.length>y,T=I?l.slice(0,y):l,x=T.at(-1);return{continueCursor:I&&x?Qe(x,D):null,isDone:!I,page:T}},Xe=n=>{const r=new Map;return o=>{const s=r.get(o);if(s!==void 0)return s;const c=n(Me(o));return r.set(o,c),c}},we=Me(ie),ur=Xe(n=>`INSERT INTO ${n} (id, _creationTime, ${we}) VALUES (?, ?, ?)`),tn=Xe(n=>`UPDATE ${n} SET ${we} = ? WHERE id = ? AND ${we} = ?`),fr=Xe(n=>`UPDATE ${n} SET _creationTime = ?, ${we} = ? WHERE id = ? AND ${we} = ?`),hr=Xe(n=>`DELETE FROM ${n} WHERE id = ? AND ${we} = ?`),wr="SELECT changes() AS changed",nn=new Map,pr="",gr=n=>{const r=JSON.stringify(n),o=nn.get(r);if(o!==void 0)return o;const s=n.map(u=>a`SELECT ${a.raw(`'${u.replaceAll("'","''")}'`)} AS __t__, id, _creationTime, ${a.identifier(ie)} FROM ${a.identifier(u)} WHERE id = ${pr}`),{sql:c}=yn("sqlite",a`${$n(s)} LIMIT 1`);return nn.set(r,c),c},yr=(n,r)=>r.map(()=>n),$r=/^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/iu,Er=n=>{if(!$r.test(n))throw new S("INTERNAL",`invalid clientId ${JSON.stringify(n)}: a client-supplied row id must be a UUID`)},$t=n=>{if(n.includes("\0"))throw new S("BAD_REQUEST",`invalid row id ${JSON.stringify(n)}: a row id cannot hold a NUL character (U+0000)`)},mr=(n,r,o,s)=>{if(o!==!0)return;const c=n!==void 0&&"serverDefault"in(n.shape._id?._meta?.column??{});for(const u of r){const g=c?gt(n,u,s)._id:u._id;typeof g=="string"&&$t(g)}},on=50,Ge=Math.floor(En.boundParams/3),rn=En.boundParams,Sr=128,Je=n=>new S("BATCH_LIMIT_EXCEEDED",n,{status:400}),He=(n,r,o)=>{Rn(n,Sn(r,o,Je),o,Je)},sn=async(n,r,o,s,c)=>{const u=Sn(s,c,Je),{page:g}=await n.findMany(r,Number.isFinite(u)?{limit:u+1,omitContinueCursor:!0,where:o}:{where:o});return g.length>u&&Rn(Math.max(await n.count(r,{where:o}),g.length),u,c,Je),g},Rr=n=>{const r={eq:(o,s)=>(n.sqlConditions.push({comparator:"=",field:o,value:s}),r),gt:(o,s)=>(n.sqlConditions.push({comparator:">",field:o,value:s}),r),gte:(o,s)=>(n.sqlConditions.push({comparator:">=",field:o,value:s}),r),lt:(o,s)=>(n.sqlConditions.push({comparator:"<",field:o,value:s}),r),lte:(o,s)=>(n.sqlConditions.push({comparator:"<=",field:o,value:s}),r)};return r},vr=n=>Math.max(n,z),An=(n,r)=>{const o=n.filters.map(s=>a`${fe(s.field)} = ${Ce(s.value)}`);return r&&o.push(r),o},Tr=(n,r,o,s,c)=>{const u=St(o.query,mt(o.definition.language));if(u.length===0)return[];const g=qn(r,o.indexName),m=`${g}__vocab`,y=u.length-1,l=u.map((P,W)=>{const U=Qo(P,W===y),G=U.exact?a`${a.identifier("term")} = ${U.lower}`:a`${a.identifier("term")} >= ${U.lower} AND ${a.identifier("term")} < ${U.upper}`;return a`SELECT ${a.identifier("doc")}, ${a.raw(String(W))} AS ${a.identifier("__term__")}, COUNT(*) AS ${a.identifier("__n__")} FROM ${a.identifier(m)} WHERE ${G} GROUP BY ${a.identifier("doc")}`}),D=u.map((P,W)=>a`SUM(CASE WHEN u.${a.identifier("__term__")} = ${a.raw(String(W))} THEN u.${a.identifier("__n__")} ELSE 0 END)`),I=a`SELECT f.${a.identifier(qe)} AS ${a.identifier(qe)}, ${a.join(D,a` + `)} AS ${a.identifier("__score__")} FROM (${$n(l)}) u JOIN ${a.identifier(g)} f ON f.rowid = u.${a.identifier("doc")} GROUP BY f.${a.identifier(qe)} HAVING ${a.join(D.map(P=>a`${P} > 0`),a` AND `)}`,T=An(o,c);let x=a`SELECT m.id, m._creationTime, m.${a.identifier(ie)}, s.${a.identifier("__score__")} AS ${a.identifier("__score__")} FROM (${I}) s JOIN ${a.identifier(r)} m ON m.id = s.${a.identifier(qe)}`;T.length>0&&(x=a`${x} WHERE ${a.join(T,a` AND `)}`),x=a`${x} ORDER BY s.${a.identifier("__score__")} DESC, m._creationTime DESC, m.id ASC LIMIT ${a.raw(String(s))}`;const B=[];for(const P of K(n,x)){const W=gn(P);if(W){const U=P.__score__;B.push({document:W,score:typeof U=="number"?U:Number(U??0)})}}return B},_r=(n,r,o,s,c)=>{const u=mt(o.definition.language),g=St(o.query,u);if(g.length===0)return[];const m=An(o,c);let y=a`SELECT id, _creationTime, ${a.identifier(ie)} FROM ${a.identifier(r)}`;m.length>0&&(y=a`${y} WHERE ${a.join(m,a` AND `)}`),y=a`${y} ORDER BY _creationTime DESC, id ASC LIMIT ${a.raw(String(vr(s)))}`;const l=K(n,y).toArray(),D=[];for(const I of l){const T=gn(I);if(!T)continue;const x=No(Pn(T,o.definition),g);x>0&&D.push({creationTime:typeof T._creationTime=="number"?T._creationTime:0,doc:T,id:typeof T._id=="string"?T._id:"",score:x})}return D.sort((I,T)=>T.score-I.score||T.creationTime-I.creationTime||I.id.localeCompare(T.id)),D.slice(0,s).map(I=>({document:I.doc,score:I.score}))},ut=(n,r,o,s)=>{if(!Number.isFinite(n.lat)||n.lat<-90||n.lat>90||!Number.isFinite(n.lng)||n.lng<-180||n.lng>180)throw new S("BAD_REQUEST",`geo index "${s}" on table "${o}": ${r} must have a finite lat in [-90, 90] and lng in [-180, 180]`)},Ar=(n,r)=>{const o=n,s={near:(c,u)=>{if(o.within)throw new S("INTERNAL",`geo index "${o.indexName}" on table "${r}": call .near() or .within(), not both`);if(ut(c,".near() point",r,o.indexName),!Number.isFinite(u)||u<=0)throw new S("BAD_REQUEST",`geo index "${o.indexName}" on table "${r}": .near() radiusMeters must be a finite number > 0, got ${String(u)}`);return o.near={point:{lat:c.lat,lng:c.lng},radiusMeters:u},s},within:c=>{if(o.near)throw new S("INTERNAL",`geo index "${o.indexName}" on table "${r}": call .near() or .within(), not both`);if(ut(c.sw,".within() sw corner",r,o.indexName),ut(c.ne,".within() ne corner",r,o.indexName),c.sw.lat>c.ne.lat)throw new S("BAD_REQUEST",`geo index "${o.indexName}" on table "${r}": .within() corners are transposed (sw.lat > ne.lat)`);if(c.sw.lng>c.ne.lng)throw new S("BAD_REQUEST",`geo index "${o.indexName}" on table "${r}": .within() box crosses the antimeridian (sw.lng > ne.lng), which is not supported — split it into two boxes at ±180 and union the results`);return o.within={ne:{lat:c.ne.lat,lng:c.ne.lng},sw:{lat:c.sw.lat,lng:c.sw.lng}},s}};return s},Ir=(n,r)=>{const o=n[r];if(o===null||typeof o!="object")return;const{lat:s,lng:c}=o;return typeof s=="number"&&typeof c=="number"?{lat:s,lng:c}:void 0},xr=(n,r)=>{const o=Ir(n,r.definition.field);if(!o)return;const s=typeof n._creationTime=="number"?n._creationTime:0;if(r.near){const c=uo(r.near.point,o);return c<=r.near.radiusMeters?{creationTime:s,distance:c}:void 0}return fo(o,r.within)?{creationTime:s,distance:0}:void 0},br=(n,r,o,s)=>{if(!o.near&&!o.within)throw new S("INTERNAL",`geo index "${o.indexName}" on table "${r}": call .near(point, radius) or .within(box)`);const c=o.near?ao(o.near.point,o.near.radiusMeters):lo(o.within),u=io(r,o.indexName),g=c.map(I=>a`(g.${a.identifier("__geohash__")} >= ${I} AND g.${a.identifier("__geohash__")} < ${`${I}{`})`),m=[a`(${a.join(g,a` OR `)})`];s&&m.push(s);const y=a`SELECT m.id, m._creationTime, m.${a.identifier(ie)} FROM ${a.identifier(u)} g JOIN ${a.identifier(r)} m ON m.id = g.${a.identifier("__id__")} WHERE ${a.join(m,a` AND `)}`,l=K(n,y).toArray(),D=[];for(const I of l){const T=xe(I),x=T?xr(T,o):void 0;T&&x&&D.push({creationTime:x.creationTime,distance:x.distance,doc:T})}return D.sort((I,T)=>I.distance-T.distance||T.creationTime-I.creationTime),D},In=(n,r,o,s)=>{const c=[];for(const u of n)if(r.every(g=>g(s(u)))&&(c.push(u),typeof o=="number"&&c.length>=o))break;return c},Cr=(n,r,o,s,c,u=()=>{})=>{const g=o.within!==void 0,m=br(n,r,o,c).map(y=>({distanceMeters:g?null:y.distance,document:y.doc}));return u(m.length),typeof s=="number"?m.slice(0,Math.max(0,Math.floor(s))):m},cn=(n,r,o,s,c,u,g=()=>{})=>{const{geo:m}=o;if(!m)throw new S("INTERNAL","runGeoTerminalScored called without a staged geo query");const y=c.length>0,l=Cr(n,r,m,y?void 0:u,s,g);return y?In(l,c,u,D=>D.document):l},an=(n,r,o)=>{const s=n.shape[r];if(s!==void 0&&Oo(s))throw new S("BAD_REQUEST",`${o}: "${r}" may hold an order-preserving key rather than a value SQL can reduce or group — declare an aggregateIndex covering this (by, field, op) so the maintained companion answers it instead (its running total is a REAL, so it stays exact only while the total is inside 2^53)`)},Mr=n=>{let r=0;const o=[],s={...Ye,relationExists:c=>{const{childWhere:u,negated:g,parentTable:m,relation:y}=c,l=`__rel_${String(r)}`,D=o.at(-1)??m;r+=1,n(y.table,j);const I=y.kind==="one"?y.field:y.references,T=y.kind==="one"?y.references:y.field,x=Ve(`${jt(l,T)} = ${jt(D,I)}`);o.push(l);const B=Z(u,s,ze);o.pop();const P=B===void 0?x:be(x," AND ",B),W=be("EXISTS (SELECT 1 FROM ",Jt(y.table)," AS ",Jt(l)," WHERE ",P,")");return g?be("NOT ",W):W}};return s};class Dr extends S{constructor(r="unique() found more than one matching document"){super("NOT_UNIQUE",r,{name:"NotUniqueError"})}}const kr=/\s/u,Lr=String.fromCodePoint(0),dn=(n,r,o)=>{if(!n.tables[r])throw new S("INTERNAL",`unknown table: ${r}`);return typeof o!="string"||o.length===0||kr.test(o)||o.includes(Lr)?null:o},xn=(n,r,o,s=()=>{},c=()=>{},u=()=>{},g)=>{const m=r.tables[o];if(!m)throw new S("INTERNAL",`unknown table: ${o}`);const y=Ae(m.softDeleteMode,void 0),l=g??{indexFields:[],indexName:void 0,inMemoryFilters:[],order:"asc",sqlConditions:[],verifyFilters:[]},D=()=>{const R=Q(y,l.pushedWhere);return R?Z(R,ue):void 0},I=()=>{const R=Q(y,l.pushedWhere);return R?Z(R,Ye,ze):void 0},T=()=>[...l.inMemoryFilters,...l.verifyFilters];let x=0;const B=R=>{const{search:C}=l;if(!C)throw new S("INTERNAL","runSearchFetch called without a staged search");Nn(oo(n),o,m);const L=l.inMemoryFilters.length>0,F=tr(L?void 0:R),k=ro(n);if(k&&!Qn(n,o,C.definition))throw new S("SEARCH_INDEX_BUILDING",`search index "${C.indexName}" on table "${o}" is still backfilling and currently covers only part of the table — retry once it finishes, or run the backfillSearch admin operation to complete it now`);const pe=D(),te=k?Tr(n,o,C,F,pe):_r(n,o,C,F,pe);!L&&R===void 0&&Jo(te);const ge=T();return x=te.length,ge.length>0?In(te,ge,R,J=>J.document):te},P=R=>B(R).map(C=>C.document),W=R=>{const C=Zo(R);return er(P(zo(C)),C)},U=()=>{if(l.search||l.geo||l.indexName===void 0){c(void 0);return}c(bo(o,l.indexName,l.indexFields,l.sqlConditions,Ce))},G=R=>{U();let C=0;const L=(()=>{if(l.search){const F=P(R);return C=x,F}return l.geo?cn(n,o,l,D(),T(),R,F=>{C=F}).map(F=>F.document):yt(n,o,m,l,I(),{filters:T(),selective:l.inMemoryFilters.length>0,want:R===void 0?void 0:Math.max(0,Math.floor(R))},F=>{C+=F}).documents})();return u(Math.max(C,L.length)),L},ee=()=>{if(!l.search&&!l.geo)throw new S("INTERNAL",`ctx.db.query("${o}").collectWithScores() requires a staged .withSearchIndex(...) or .withGeoIndex(...)`);U();let R=0;const C=(()=>{if(l.search){const L=B(void 0);return R=x,L}return cn(n,o,l,D(),T(),void 0,L=>{R=L})})();return u(Math.max(R,C.length)),C},N={async*[Symbol.asyncIterator](){const R=xn(n,r,o,s,c,u,{...l,indexFields:[...l.indexFields],inMemoryFilters:[...l.inMemoryFilters],sqlConditions:[...l.sqlConditions],verifyFilters:[...l.verifyFilters]});if(l.search){yield*await R.collect();return}let C;for(;;){const L=await R.paginate({cursor:C??null,numItems:Sr});if(yield*L.page,L.isDone||L.continueCursor===null)return;C=L.continueCursor}},async collect(){return G(void 0)},async collectWithScores(){return ee()},filter(R){const C=Co(R);return C!==void 0&&Mo(C,m.shape)?(l.pushedWhere=Q(l.pushedWhere,C),l.verifyFilters.push(R)):l.inMemoryFilters.push(R),N},async first(){return G(1)[0]??null},order(R){return l.order=R==="desc"?"desc":"asc",N},async paginate(R){let C=0;if(U(),l.search){const F=W(R);return u(F.page.length),F}if(l.geo)throw new S("INTERNAL","pagination is not supported on geo queries; use .take(n) or .collect()");const L=lr(n,o,m,l,R,I(),{all:T(),selective:l.inMemoryFilters.length>0},F=>{C+=F});return u(Math.max(C,L.page.length)),L},async take(R){return G(R)},async unique(){const R=G(2);if(R.length>1)throw new Dr(`unique() on table "${o}" matched ${String(R.length)} documents; expected at most one`);return R[0]??null},withGeoIndex(R,C){const L=(m.geoIndexes??[]).find(k=>k.name===R);if(!L)throw new S("INTERNAL",`unknown geo index "${R}" on table "${o}"`);s(o,R,"geo");const F={definition:L,indexName:R};if(l.geo=F,C(Ar(F,o)),!F.near&&!F.within)throw new S("INTERNAL",`geo index "${R}" on table "${o}" requires a .near(point, radius) or .within(box) call`);return N},withIndex(R,C){const L=m.indexes.find(F=>F.name===R);if(!L)throw new S("INTERNAL",`unknown index "${R}" on table "${o}"`);return s(o,R,"index"),l.indexName=R,l.indexFields=L.fields,C&&C(Rr(l)),N},withSearchIndex(R,C){const L=(m.searchIndexes??[]).find(k=>k.name===R);if(!L)throw new S("INTERNAL",`unknown search index "${R}" on table "${o}"`);s(o,R,"search");const F={definition:L,field:L.field,filters:[],hasQuery:!1,indexName:R,query:""};if(l.search=F,C(Vo(F,o,mt(L.language))),!F.hasQuery)throw new S("INTERNAL",`search index "${R}" on table "${o}" requires a .search(field, query) call`);return N}};return N},ft=(n,r,o,s)=>{const c=o;for(const[u,g]of no(n)){if(g.serverDefault){u in r&&(c[u]=g.serverDefault({auth:s}));continue}g.onUpdateFn&&!(u in r)&&(c[u]=g.onUpdateFn())}},ln=5,un=(n,r)=>{for(const o of Object.keys(r))if(r[o]===void 0)throw new S("INTERNAL",`Cannot ${n} field '${o}' to undefined — use null to clear a nullable field, or omit the key to leave it unchanged.`)},fn=["_commitSeq","_creationTime","_id"],Ke=n=>fn.some(r=>r in n)?Object.fromEntries(Object.entries(n).filter(([r])=>!fn.includes(r))):n,Fr=/unique constraint failed/i,Wr=n=>n instanceof Error&&Fr.test(n.message),Br=/string or blob too big/iu,qr=(n,r)=>{if(!(!(n instanceof Error)||!Br.test(n.message)))throw new S("PAYLOAD_TOO_LARGE",`document is too large to store in "${r}": a single row cannot exceed the storage engine's per-row ceiling (2 MB on a Durable Object's SQLite). The limit is on the STORED bytes, which are UTF-8, and v.bytes()/v.bigint() columns are stored twice on a shard-local table. Keep the payload in R2 (ctx.storage) and store a reference on the row.`)},Et=(n,r,o,s)=>{try{he(n,o,...s)}catch(c){throw Wr(c)?new se(`unique constraint violation on "${r}"`,"unique"):(qr(c,r),c)}},Ne=(n,r,o,s)=>{if(Et(n,r,o,s),he(n,wr).one().changed===0)throw new se(`optimistic concurrency conflict on "${r}" — the row changed during this mutation; refetch and retry`,"occ")},hn=(n,r,o,s,c,u,g)=>{const m=[];for(let I=0;I<o.length+1;I+=1){const T=o[I],x=s[I],B=x?.direction==="desc"?"desc":"asc",P=T===void 0||x===void 0?a`${a.identifier(To)} < ${g}`:_o(T,u[I],B,!1);if(P===void 0)continue;const W=[];for(let G=0;G<I;G+=1)W.push(a`${a.identifier(o[G])} IS ${u[G]}`);W.push(P);const[U]=W;m.push(W.length===1&&U!==void 0?U:a`(${a.join(W,a` AND `)})`)}const y=m.length>0?a.join(m,a` OR `):a`1 = 0`,l=K(n,a`SELECT COUNT(*) AS c FROM ${a.identifier(r)} WHERE ${a.identifier("__partition__")} = ${c} AND (${y})`).one(),D=K(n,a`SELECT COUNT(*) AS c FROM ${a.identifier(r)} WHERE ${a.identifier("__partition__")} = ${c}`).one();return{before:l.c,total:D.c}},Pr=n=>{const r=new Map;for(const[s,c]of Object.entries(n.tables))for(const u of Object.values(c.relationMap??{}))u.kind==="one"&&(u.onDelete==="cascade"||u.onDelete==="set null")&&r.set(u.table,[...r.get(u.table)??[],{holder:s,op:u.onDelete==="cascade"?"delete":"update"}]);const o=s=>{const c=new Set,u=[s];for(let g=u.pop();g!==void 0;g=u.pop())for(const{holder:m,op:y}of r.get(g)??[]){if(m===s||Xt(n,m,y))return!0;c.has(m)||(c.add(m),u.push(m))}return!1};return new Set(Object.entries(n.tables).filter(([s,c])=>c.shardMode?.kind==="global"||Xt(n,s,"delete")||o(s)).map(([s])=>s))},Ur=n=>{const r=new Map;for(const[o,s]of Object.entries(n.tables))s.softDeleteMode&&r.set(o,s.softDeleteMode.field);return r},ht=new WeakMap,Or=(n,r)=>{let o=ht.get(r.tables);if(!ht.has(r.tables)){const c=Object.keys(r.tables).map(u=>u.replaceAll(/[$()*+.?[\\\]^{|}]/gu,String.raw`\$&`));o=c.length===0?void 0:new RegExp(`"(${c.join("|")})"`,"gu"),ht.set(r.tables,o)}if(o===void 0)return;const s=new Set;for(const c of n.matchAll(o))s.add(c[1]);return s.size===1?[...s][0]:void 0},jr=(n,r,o)=>{for(const s of n){const c=s,u=c?.[ie];if(typeof u=="string"){const g=c?.id,m=co(u);typeof g!="string"?r.recordReadBytes(m):o===void 0?r.recordDocumentRead(`${g}\0${String(m)}`,m):r.recordDocumentRead(`${o}\0${g}`,m)}}},Gr=(n,r,o)=>{if(r===void 0)return n;const s=(c,...u)=>{const g=n.exec(c,...u),m=g.one.bind(g),y=g[Symbol.iterator].bind(g),l=o===void 0?void 0:Or(c,o);let D=!1;const I=T=>{jr(T,r,l)};return g.toArray=()=>{const T=[];for(const x of{[Symbol.iterator]:y})I([x]),T.push(x);return T},g.one=()=>{D=!0;try{const T=m();return I([T]),T}finally{D=!1}},g[Symbol.iterator]=function*(){for(const x of{[Symbol.iterator]:y})D||I([x]),yield x},g};return new Proxy(n,{get:(c,u)=>u==="exec"?s:u===eo?c:Reflect.get(c,u,c)})},Hr=new Map([["findFirst","rows"],["findFirstOrThrow","rows"],["findMany","page"],["get","rows"],["lookupById","lookup"],["rankPage","page"]]),Kr=new Map([["collect","rows"],["collectWithScores","scored"],["first","rows"],["paginate","page"],["take","rows"],["unique","rows"]]),Ie=(n,r,o)=>{if(typeof n!="object"||n===null)return;const s=so(n);if(s===void 0)return;const c=n._id;typeof c=="string"?o.recordDocumentRead(`global\0${r}\0${c}`,s):o.recordReadBytes(s)},bn=(n,r,o,s)=>{if(typeof n!="object"||n===null)return;const c=n;switch(r){case"lookup":{Ie(c.row,typeof c.tableName=="string"?c.tableName:o,s);return}case"page":{for(const u of c.page??[])Ie(u,o,s);return}case"rows":{for(const u of Array.isArray(n)?n:[n])Ie(u,o,s);return}default:for(const u of Array.isArray(n)?n:[])Ie(u.document,o,s)}},Cn=(n,r,o)=>new Proxy(n,{get:(s,c)=>{const u=Reflect.get(s,c,s);if(typeof u!="function")return u;if(c===Symbol.asyncIterator)return async function*(){for await(const y of Reflect.apply(u,s,[]))Ie(y,r,o),yield y};const g=Kr.get(c);return(...m)=>{const y=Reflect.apply(u,s,m);return g!==void 0?Promise.resolve(y).then(l=>(bn(l,g,r,o),l)):typeof y=="object"&&y!==null&&!(y instanceof Promise)?Cn(y,r,o):y}}}),Nr=new Set(["findFirst","findFirstOrThrow","findMany"]),Qr=n=>{const r=n[1],o=r?.select;if(!Array.isArray(o))return;const s=Object.fromEntries(Object.entries(r).filter(([g])=>g!=="select")),c=s.with,u=g=>pt(g,o,c);return{args:[n[0],s,...n.slice(2)],project:(g,m)=>typeof g!="object"||g===null?g:m==="page"?{...g,page:u(g.page)}:u([g])[0]}},Vr=(n,r)=>n===void 0||r===void 0?n:new Proxy(n,{get:(o,s)=>{const c=Reflect.get(o,s,o);if(typeof c!="function")return c;if(s==="query")return(...g)=>Cn(Reflect.apply(c,o,g),String(g[0]),r);const u=Hr.get(s);return u===void 0?c:async(...g)=>{const m=Nr.has(s)?Qr(g):void 0,y=await Reflect.apply(c,o,m?.args??g);return bn(y,u,String(g[0]),r),m===void 0?y:m.project(y,u)}}}),wn=new WeakMap,pn=new WeakMap,Jr=n=>{const{baselineSeq:r,onStalePatchDropped:o}=n,{headroom:s}=n,c=wn.get(n)??{value:void 0},u=pn.get(n)??{value:0};let g;const m=()=>{if(g===void 0){const e={...n,enforceRls:!1,headroom:void 0};wn.set(e,c),pn.set(e,u),g=Jr(e)}return g},y=Gr(n.sql,s,n.schema),{schema:l}=n,D=n.broadcast??(()=>{}),I=(e,t)=>{if(!Object.hasOwn(l.tables,e))throw new S("BAD_REQUEST",`${t}: "${e}" is not a table in this schema`)},T=Do(l),x=new Map;for(const e of T){const t=i=>(l.tables[i]?.shardMode?.kind??"root")==="root";!e.array&&t(e.sourceTable)&&t(e.targetTable)&&x.set(e.sourceTable,[...x.get(e.sourceTable)??[],e])}const B=(e,t,i)=>{for(const d of x.get(e)??[]){const w=t[d.column];if(typeof w!="string"||i?.[d.column]===w||d.targetTable===e&&t._id===w)continue;if(K(y,a`SELECT 1 FROM ${a.identifier(d.targetTable)} WHERE id = ${w} LIMIT 1`).toArray().length===0)throw new S("VALIDATION_ERROR",`${d.name} references ${d.targetTable} row "${w}", which does not exist`)}},P=Wo(l,n.inTransaction),W=Pr(l),U=Ur(l),G=()=>n.inTransaction?.()===!0,ee=e=>l.tables[e]?.commitOrderedMode!==!0?{}:((c.value===void 0||!G())&&(c.value=zn(y)),{[Yn]:c.value}),N=(e,...t)=>{const i=l.tables[e]?.indexes??[],d=[];let w;for(const p of t)p&&(typeof p._id=="string"&&p._id!==w&&(w=p._id,d.push(Ao(w))),d.push(...Io(i,xo(i,p,Ce))));return d.length>0?d:void 0},R=n.onRead??(()=>{}),C=e=>{Ut(l.tables[e])&&R(Vt,Vt)},L=n.onReadRange??(e=>{R(e.table,j)}),F=e=>{C(e.table),L(e)},k=(e,t,i)=>{t!==void 0&&t!==j&&s?.recordRead(1),C(e),R(e,t,i)},pe=(e,t)=>{const i=e.row._id;k(e.tableName,typeof i=="string"?i:t,typeof i=="string")},te=n.onIndexUse??(()=>{}),ge=n.onWrite??(()=>{}),J=e=>{s?.recordWrite(e)},ye=async e=>{J(e.doc),await ge(e)},{cache:$e}=n,Ee=n.clock??(()=>Date.now()),Rt=n.idGenerator??(()=>crypto.randomUUID()),vt=n.scheduler??On,me=Vr(n.globalDb,s),ce=n.auth??{identity:null,userId:null},Tt=n.cdc??!1,Ze=vt,Mn=jo({scheduler:typeof Ze.list=="function"&&typeof Ze.get=="function"?Ze:void 0,storage:n.storage}),Se=(e,t,i,d)=>{Tt&&!Ut(l.tables[e])&&Vn(y,Ee(),e,t,i,d)},_t=(e,t,i,d)=>{const w=l.tables[e];if(w?.dropStalePatchesMode!==!0||!Tt)return!1;const p=r?.();if(p===void 0)return!1;const f=Jn(y,e,t,p);if(f===void 0)return!1;const h=go(w,i);return Object.keys(Ke(i)).some($=>!h.has($)&&Pt(Gt(f,$))!==Pt(Gt(d,$)))},ae=e=>l.tables[e]?.shardMode?.kind==="global",At=(e,t)=>{if(ae(e)){if(!me)throw new S("INTERNAL",`cross-backend ${t} for global table '${e}' requires a globalDb writer — pass one to createShardCtxDb({ globalDb })`);return me}return O},et=e=>At(e,"cascade"),H=(e,t)=>{if(ae(e)){if(!me)throw new S("INTERNAL",`${t} on global table '${e}' requires a globalDb writer — pass one to createShardCtxDb({ globalDb })`);return me}},It=async(e,t,i,d,w)=>{w&&J(i);const p=await e.insert(t,i,d);return D({key:p,op:"insert",row:{...i,_id:p},table:t}),p},tt=(e,t)=>At(e,"relation load").findMany(e,t),xt=(e,t)=>(ae(e)&&k(e,j),tt(e,t)),Dn=e=>!ae(e.table),bt=n.relationExistsPushDown??"auto",Ct=bt!=="never",{maxRelationKeys:Mt}=n,De=(e,t,i)=>Lo(e,{fetcher:xt,maxRelationKeys:Mt,relationBaseWhere:i,schema:l,tableName:t}),Dt=async(e,t,i,d)=>{const w=H(e,"relation grouped count");if(w)return k(e,j),Po((E,q)=>w.count(E,q),e,t,i,d);const p=l.tables[e];if(!p)throw new S("INTERNAL",`unknown table: ${e}`);k(e,j);const f=Ae(p.softDeleteMode,void 0),h={[t]:{in:i}},$=Q(Q(h,d),f),v=await De($,e,void 0),b=Z(v,ue),_=fe(t);let A=a`SELECT ${_} AS __fk__, COUNT(*) AS count FROM ${a.identifier(e)}`;b&&(A=a`${A} WHERE ${b}`),A=a`${A} GROUP BY ${_}`;const M=K(y,A).toArray();return new Map(M.map(E=>[E.__fk__,E.count]))},kt=new Set;for(const[e,t]of Object.entries(l.tables))for(const i of Object.values(t.triggerMap??{}))kt.add(`${e} ${i.timing} ${i.op}`);const ne=(e,t,i)=>kt.has(`${e} ${t} ${i}`),oe=async(e,t,i)=>{if(u.value+=1,u.value>on)throw u.value-=1,new se(`trigger recursion exceeded ${String(on)} levels on "${i.table}" — check for a self-triggering write`,"trigger");try{await Go({ctx:Wn,event:i,op:t,schema:l,tableName:i.table,timing:e})}finally{u.value-=1}},{ensureBackfilledForTable:Re,ensureBackfilledIndex:nt,ensureRankBackfilled:ot,ensureRankBackfilledForTable:ve,syncAggregates:ke,syncCompanionsForInsert:Lt,syncGeo:Le,syncRanks:Te,syncSearch:Fe}=Xn({broadcast:D,indexKeysFor:(e,t)=>N(e,t),invalidateCache:(e,t,i)=>$e?.invalidate(e,t,N(e,i)),recordCdc:Se,schema:l,sql:y,verified:n.companionMemo?.verified}),Ft=(e,t,i)=>{const{shardMode:d}=t;if(d?.kind==="shardBy"&&!(d.field!==void 0&&(i.partitionBy??[]).includes(d.field)))throw Object.assign(new Error(`rank index "${i.name}" on "${e}" partitions across shards (shard key "${d.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})},Wt=e=>Object.entries(l.tables).filter(([,t])=>t.shardMode?.kind!=="global").map(([t])=>t).filter(t=>e===void 0||t===e),_e=e=>e===void 0||ae(e)?me:void 0,rt=async(e,t,i,d,w)=>{for(let p=0;p<i.length;p+=1)J(void 0);if(w!==void 0&&e.deleteMany!==void 0)return e.deleteMany(t,i,w.options);for(const p of i)await e.delete(t,p,d);return{deleted:i.length}},re=(e,t)=>{const i=Wt(t);for(let d=0;d<i.length;d+=rn){const w=i.slice(d,d+rn),[p]=he(y,gr(w),...yr(e,w)).toArray();if(!p)continue;const f=p.__t__,h=xe(p);if(typeof f!="string"||!h)return;const $=p[ie];return{docJson:typeof $=="string"?$:le($??{}),row:h,tableName:f}}},Bt={assertRankPartitionLocal:Ft,ensureRankBackfilled:ot,onRead:k,rowToDocument:xe,schema:l,sql:y},kn=(e,t,i)=>{const d=Z(i,ue);return d===void 0||K(y,a`SELECT 1 FROM ${a.identifier(e)} WHERE ${a.identifier("id")} = ${t} AND ${d}`).toArray().length>0},Ln=(e,t,i,d)=>_t(e,t,i,d)?(o?.({fields:Object.keys(Ke(i)),id:t,table:e}),!0):!1,Fn=async(e,t,i,d,w)=>{const p=re(t,e);if(!p)return{applied:!1,doc:null};if(k(e,t),!kn(e,t,i.where)||Ln(e,t,i.patch,p.row))return{applied:!1,doc:p.row};try{await w(i.patch)}catch(f){if(f instanceof se&&f.kind==="occ"&&d)return;throw f}return{applied:!0,doc:re(t,e)?.row??null}},qt=async(e,t,i,d)=>{const{fetchLimit:w,limit:p,orderKeys:f,predicate:h}=await Fo(t,i,{canPushExists:Ct?Dn:void 0,existsPushMode:bt==="always"?"always":"auto",fetcher:xt,maxRelationKeys:Mt,schema:l,tableName:e}),$=Ct?Mr(d):Ye,v=Z(h,$,ze),b=vn(e,v,Tn(f),w);return{limit:p,orderKeys:f,statement:b}},O={system:Mn,async aggregate(e,t){const i=H(e,"aggregate");if(i)return k(e,j),i.aggregate(e,t);const d=l.tables[e];if(!d)throw new S("INTERNAL",`unknown table: ${e}`);if(Pe(t.op),t.op==="count")return O.count(e,{baseWhere:t.baseWhere,relationBaseWhere:t.relationBaseWhere,restrictsCounts:t.restrictsCounts,where:t.where});if(!t.field)throw new S("INTERNAL",`aggregate(${e}, { op: "${t.op}" }): "field" is required for non-count reducers`);k(e,j);const w=Ae(d.softDeleteMode,void 0),p=Q(Q(t.baseWhere,t.where),w),f=await De(p,e,t.relationBaseWhere),h=f!==p;if(d.aggregateIndexes&&!t.baseWhere&&!h){const E=Kn(d.aggregateIndexes,t.op,t.field,t.where);if(E){nt(e,E.index);const q=st(E.index.by??[],E.key),Y=it(e,E.index.name),X=K(y,a`SELECT ${Ue} AS value, ${dt} AS count FROM ${a.identifier(Y)} WHERE ${Oe} = ${q}`).toArray()[0];return ct(t.op,X)}}an(d,t.field,`aggregate(${e}, { op: "${t.op}", field: "${t.field}" })`);const $=Z(f,ue),v=Pe(t.op),b=fe(t.field);let _=a`SELECT ${a.raw(v)}(${b}) AS value FROM ${a.identifier(e)}`;$&&(_=a`${_} WHERE ${$}`);const M=K(y,_).toArray()[0]?.value;return M??null},asId(e,t){const i=dn(l,e,t);if(i===null)throw new S("BAD_REQUEST",`asId("${e}", …): "${t}" is not a valid id for table "${e}"`,{status:400});return i},async count(e,t){const i=H(e,"count");if(i)return k(e,j),i.count(e,t);const d=l.tables[e];if(!d)throw new S("INTERNAL",`unknown table: ${e}`);const w=jn(t);if(w.restrictsCounts)throw new at(e);k(e,j);const p=Ae(d.softDeleteMode,void 0),f=Q(Q(w.baseWhere,w.where),p),h=await De(f,e,w.relationBaseWhere),$=h!==f;if(d.aggregateIndexes&&!w.baseWhere&&!$){const A=Hn(d.aggregateIndexes,w.where);if(A){nt(e,A.index);const M=st(A.index.by??[],A.key),E=it(e,A.index.name),q=K(y,a`SELECT ${Ue} AS value FROM ${a.identifier(E)} WHERE ${Oe} = ${M}`).toArray();return q[0]===void 0?0:q[0].value??0}}const v=Z(h,ue);let b=a`SELECT COUNT(*) AS count FROM ${a.identifier(e)}`;return v&&(b=a`${b} WHERE ${v}`),K(y,b).one().count},async delete(e,t,i){I(e,"ctx.db.delete(table, id)");const d=re(t,e);if(!d){const A=_e(e);A&&await rt(A,e,[t],i);return}const{docJson:w,row:p,tableName:f}=d,h=l.tables[f],$=i?.hard===!0,v=!$&&h?.softDeleteMode?h:void 0,b=v?.softDeleteMode?.field;if(b&&p[b]!==null&&p[b]!==void 0)return;if(ne(f,"before","delete")&&await oe("before","delete",{id:t,op:"delete",previous:p,table:f}),i?.skipOnDelete!==!0&&await qo({deletedId:t,deletedReference:A=>p[A],findHolders:async(A,M,E,q)=>(await et(A).findMany(A,{...q,includeDeleted:$,where:{[M]:E}})).page,onCascade:(A,M)=>et(A).delete(A,M,i),onRestrict:A=>{throw new se(A,"restrict")},onSetNull:(A,M,E)=>et(A).patch(A,M,{[E]:null}),schema:l,tableName:f}),Re(f),ve(f),v&&b){const A={[b]:Ee()},M={...p,...ee(f),...A,_id:t};ft(v,A,M,ce),Ne(y,f,tn(f),[le(M),t,w]),Fe(f,t,M,p),Le(f,t,void 0),ke(f,p,M),Te(f,t,p,void 0);const E=N(f,p,M);$e?.invalidate(f,t,E),Se(f,t,"update",M),D({indexKeys:E,key:t,op:"update",row:M,table:f}),ne(f,"after","delete")&&await oe("after","delete",{id:t,op:"delete",previous:p,table:f}),await ye({id:t,op:"delete",table:f});return}Ne(y,f,hr(f),[t,w]),Fe(f,t,void 0),Le(f,t,void 0),ke(f,p,void 0),Te(f,t,p,void 0);const _=N(f,p);$e?.invalidate(f,t,_),Se(f,t,"delete"),D({indexKeys:_,key:t,op:"delete",table:f}),ne(f,"after","delete")&&await oe("after","delete",{id:t,op:"delete",previous:p,table:f}),await ye({id:t,op:"delete",table:f})},async deleteAll(e,t){if(!l.tables[e])throw new S("INTERNAL",`unknown table: ${e}`);if(s!==void 0)return m().deleteAll(e,t);const i=Math.max(1,t?.chunkSize??mn),d=t?.hard===void 0?void 0:{hard:t.hard},w=H(e,"deleteAll");let p=0;for(;;){const h=(await O.findMany(e,{limit:i})).page.map($=>String($._id));if(h.length===0)break;for(const $ of h)await(w===void 0?O.delete(e,$,d):rt(w,e,[$],d)),p+=1;if(h.length<i)break}return{deleted:p}},async deleteMany(e,t,i){I(e,"ctx.db.deleteMany(table, ids)"),He(t.length,i?.limit,"deleteMany");for(const d of t)await O.delete(e,d);return{deleted:t.length}},async deleteWhere(e,t,i){const d=H(e,"deleteWhere"),p=(await sn(d??O,e,t,i?.limit,"deleteWhere")).map(f=>String(f._id));if(d)return rt(d,e,p,void 0,{options:i});if(O.deleteMany===void 0)throw new S("INTERNAL",`ctx.db.${e}.deleteMany is unavailable: this writer has no batch delete`);return O.deleteMany(e,p,i)},async findFirst(e,t={}){return(await O.findMany(e,{...t,limit:1,omitContinueCursor:!0})).page[0]??null},async findFirstOrThrow(e,t={}){const i=await O.findFirst(e,t);if(i===null)throw new ho(`findFirstOrThrow: no "${e}" document matched`);return i},async findMany(e,t={}){const i=H(e,"findMany");if(i)return k(e,j),i.findMany(e,t);const d=l.tables[e];if(!d)throw new S("INTERNAL",`unknown table: ${e}`);const w=!t.where&&!t.baseWhere;w?k(e,j):k(e);const{limit:p,orderKeys:f,statement:h}=await qt(e,d,t,k),$=he(y,h.text,...h.params).toArray();w&&s?.recordRead($.length);const v=[];for(const M of $){const E=xe(M);E&&(v.push(E),!w&&typeof E._id=="string"&&k(e,E._id))}if(p===void 0)return t.with&&await zt({groupedCounter:Dt,fetcher:tt,parents:v,...Yt(t),schema:l,tableName:e,with:t.with}),{continueCursor:null,isDone:!0,page:pt(v,t.select,t.with)};const b=v.length>p,_=b?v.slice(0,p):v,A=_.at(-1);return t.with&&await zt({fetcher:tt,groupedCounter:Dt,parents:_,...Yt(t),schema:l,tableName:e,with:t.with}),{continueCursor:b&&A&&t.omitContinueCursor!==!0?Qe(A,f):null,isDone:!b,page:pt(_,t.select,t.with)}},async explain(e,t={}){const i=H(e,"explain");if(i)return i.explain(e,t);const d=l.tables[e];if(!d)throw new S("INTERNAL",`unknown table: ${e}`);const{statement:w}=await qt(e,d,t,()=>{}),p=he(y,`EXPLAIN QUERY PLAN ${w.text}`,...w.params).toArray();return{params:w.params,plan:p.map(f=>String(f.detail)),sql:w.text}},async get(e,t){I(e,"ctx.db.get(table, id)");const i=re(t,e);if(!i){const d=_e(e);return d?d.get(e,t):(C(e),R(e,t,!0),null)}return pe(i,t),i.row},async lookupById(e,t){const i=re(e,t);if(!i){for(const d of Wt(t))C(d),R(d,e,!0);return null}return pe(i,e),{row:i.row,tableName:i.tableName}},async groupBy(e,t){const i=H(e,"groupBy");if(i)return k(e,j),i.groupBy(e,t);const d=l.tables[e];if(!d)throw new S("INTERNAL",`unknown table: ${e}`);k(e,j);const w=t.agg??{op:"count"};if(Pe(w.op),w.op!=="count"&&!w.field)throw new S("INTERNAL",`groupBy(${e}, { agg: { op: "${w.op}" } }): "field" is required for non-count reducers`);const p=Ae(d.softDeleteMode,void 0),f=Q(Q(t.baseWhere,t.where),p),h=await De(f,e,t.relationBaseWhere),$=h!==f;if(d.aggregateIndexes&&!t.baseWhere&&!$){const E=Gn(d.aggregateIndexes,w.op,w.field,t.by,t.where),q=E===void 0?0:Object.keys(E.partial).length,Y=E?.index.by?.length??0;if(E&&(q===0||q===Y)){nt(e,E.index);const X=it(e,E.index.name),V=Object.keys(E.partial),de=[];if(V.length===(E.index.by??[]).length&&V.length>0){const We=st(E.index.by??[],E.partial),Be=K(y,a`SELECT ${Ue} AS value, ${dt} AS count FROM ${a.identifier(X)} WHERE ${Oe} = ${We}`).toArray();return Be.length>0&&de.push({key:{...E.partial},value:ct(w.op,Be[0])}),de}const Bn=K(y,a`SELECT ${Oe} AS key, ${Ue} AS value, ${dt} AS count FROM ${a.identifier(X)}`).toArray();for(const We of Bn){const Be=Un(JSON.parse(We.key));de.push({key:Be,value:ct(w.op,We)})}return de}}for(const E of[...t.by,w.field]){if(E===void 0)continue;const q=E===w.field?`groupBy(${e}, { agg: { op: "${w.op}", field: "${E}" } })`:`groupBy(${e}, { by: [..."${E}"] })`;an(d,E,q)}const v=Z(h,ue),b=t.by.map(E=>a`${fe(E)} AS ${a.identifier(E)}`);if(w.op==="count")b.push(a`COUNT(*) AS value`);else{const{field:E}=w;if(E===void 0)throw new S("INTERNAL",`groupBy(${e}, { agg: { op: "${w.op}" } }): "field" is required for non-count reducers`);b.push(a`${a.raw(Pe(w.op))}(${fe(E)}) AS value`)}let _=a`SELECT ${a.join(b,a`, `)} FROM ${a.identifier(e)}`;v&&(_=a`${_} WHERE ${v}`),_=a`${_} GROUP BY ${a.join(t.by.map(E=>fe(E)),a`, `)}`;const A=K(y,_).toArray(),M=[];for(const E of A){const q={};for(const X of t.by)q[X]=to(d.shape[X],E[X]??null);const{value:Y}=E;M.push({key:q,value:Y==null?null:Number(Y)})}return M},async insert(e,t,i){const d=H(e,"insert");if(d)return It(d,e,t,i,!0);const w=l.tables[e];if(!w)throw new S("INTERNAL",`unknown table: ${e}`);const p=i?.allowExplicitId===!0,f=je(w,gt(w,t,ce),{supplied:t,trusted:p});let h;i?.clientId!==void 0?(Er(i.clientId),h=i.clientId):i?.allowExplicitId&&typeof f._id=="string"?($t(f._id),h=f._id):h=Rt();const $=i?.allowExplicitId&&typeof f._creationTime=="number"?f._creationTime:Ee(),v={...f,...ee(e),_creationTime:$,_id:h};return ne(e,"before","insert")&&await oe("before","insert",{doc:{...v},id:h,op:"insert",table:e}),p||B(e,v),Re(e),ve(e),Et(y,e,ur(e),[h,$,le(v)]),Lt(e,h,v),ne(e,"after","insert")&&await oe("after","insert",{doc:v,id:h,op:"insert",table:e}),await ye({doc:v,id:h,op:"insert",table:e}),h},async insertManyUnsafe(e,t,i){if(He(t.length,i?.limit,"insertManyUnsafe"),t.length===0)return[];const d=H(e,"insert");if(d){const $=[];mr(l.tables[e],t,i?.allowExplicitId,ce);for(const v of t)J(v);for(const v of t){const b=await d.insert(e,v,{allowExplicitId:i?.allowExplicitId});D({key:b,op:"insert",row:{...v,_id:b},table:e}),$.push(b)}return $}const w=l.tables[e];if(!w)throw new S("INTERNAL",`unknown table: ${e}`);Re(e),ve(e);const p=[];for(let $=0;$<t.length;$+=Ge)p.push(ee(e));const f=i?.allowExplicitId===!0?void 0:Bo(w),h=t.map(($,v)=>{const b=gt(w,$,ce),_=f===void 0?b:je(f,b,{supplied:$}),A=i?.allowExplicitId===!0&&typeof _._id=="string"?_._id:void 0;A!==void 0&&$t(A);const M=A??Rt(),E=i?.allowExplicitId===!0&&typeof _._creationTime=="number"?_._creationTime:Ee(),q={..._,...p[Math.floor(v/Ge)],_creationTime:E,_id:M};return{creationTime:E,document:q,id:M}});for(const $ of h)J($.document);for(let $=0;$<h.length;$+=Ge){const v=a.join(h.slice($,$+Ge).map(_=>a`(${_.id}, ${_.creationTime}, ${le(_.document)})`),a`, `),b=yn("sqlite",a`INSERT INTO ${a.identifier(e)} (id, _creationTime, ${a.identifier(ie)}) VALUES ${v}`);Et(y,e,b.sql,b.params)}for(const{document:$,id:v}of h)Lt(e,v,$),await ge({doc:$,id:v,op:"insert",table:e});return h.map($=>$.id)},async insertMany(e,t,i){He(t.length,i?.limit,"insertMany");const d=i?.skipDuplicates===!0,w=[],p=H(e,"insert");if(p)for(const h of t)J(h);const f=async h=>p?It(p,e,h,void 0,!1):O.insert(e,h);for(const h of t)try{w.push(await f(h))}catch($){if(d&&$ instanceof se&&$.kind==="unique")w.push(null);else throw $}return w},normalizeId(e,t){return dn(l,e,t)},async patch(e,t,i,d){I(e,"ctx.db.patch(table, id, values)");const w=re(t,e);if(!w){const M=_e(e);if(M){J(i),await M.patch(e,t,i,d);return}throw new S("NOT_FOUND",`document not found: ${t}`)}const{docJson:p,row:f,tableName:h}=w,$=l.tables[h];if(!$)throw new S("INTERNAL",`unknown table: ${h}`);if(k(h,t),un("patch",i),_t(h,t,i,f)){o?.({fields:Object.keys(Ke(i)),id:t,table:h});return}const v=wo($,i,f),b={...f,...Ke(v),...ee(h),_id:t};ft($,v,b,ce);const _=je($,b,{only:new Set(Object.keys(v)),previous:()=>f,tolerateStoredNull:!0});po(d,f,_),ne(h,"before","update")&&await oe("before","update",{doc:{..._},id:t,op:"update",previous:f,table:h}),B(h,_,f),Re(h),ve(h),Ne(y,h,tn(h),[le(_),t,p]),Fe(h,t,_,f),Le(h,t,_),ke(h,f,_),Te(h,t,f,_);const A=N(h,f,_);$e?.invalidate(h,t,A),Se(h,t,"update",_),D({indexKeys:A,key:t,op:"update",row:_,table:h}),ne(h,"after","update")&&await oe("after","update",{doc:_,id:t,op:"update",previous:f,table:h}),await ye({doc:_,id:t,op:"update",table:h})},async patchIf(e,t,i){const d=H(e,"patchIf");if(d){if(d.patchIf===void 0)throw new S("INTERNAL",`ctx.db.patchIf on global table '${e}' is unsupported: its backend has no conditional write`);return J(i.patch),d.patchIf(e,t,i)}if(!l.tables[e])throw new S("INTERNAL",`unknown table: ${e}`);for(let w=1;w<=ln;w+=1){const p=await Fn(e,t,i,w<ln,f=>O.patch(e,t,f,{verify:i.verify}));if(p!==void 0)return p}throw new se(`patchIf on "${e}" kept conflicting; the row changed on every attempt`,"occ")},async patchMany(e,t,i){I(e,"ctx.db.patchMany(table, patches)"),He(t.length,i?.limit,"patchMany");for(const d of t)await O.patch(e,d.id,d.patch);return{patched:t.length}},async patchWhere(e,t,i){const d=H(e,"patchWhere")??O,p=(await sn(d,e,t.where,i?.limit,"patchWhere")).map(f=>({id:String(f._id),patch:t.patch}));if(O.patchMany===void 0)throw new S("INTERNAL",`ctx.db.${e}.patchMany is unavailable: this writer has no batch patch`);return await O.patchMany(e,p,i),{patched:p.length}},async related(e,t){return ko(O,T,e,t)},relationEdges:T,deleteRereadTables:W,inTransaction:G,softDeleteFields:U,relationWrites:P,query(e){const t=H(e,"query");return t?(k(e,j),t.query(e)):xn(y,l,e,te,i=>{i?F(i):k(e,j)},i=>{s?.recordRead(i)})},async rank(e,t,i){const d=H(e,"rank");if(d)return k(e,j),d.rank(e,t,i);te(e,t,"rank");const w=l.tables[e];if(!w)throw new S("INTERNAL",`unknown table: ${e}`);const p=w.rankIndexes?.find(V=>V.name===t);if(!p)throw new S("INTERNAL",`unknown rankIndex "${t}" on table "${e}"`);if(Ft(e,w,p),i.restrictsCounts)throw new at(e);k(e,j),ot(e,p);const f=typeof i.row=="string"?i.row:i.row._id;if(!f)return null;const h=Nt(e,p.name),$=p.sortBy.map((V,de)=>Qt(de)),v=$.map(V=>Me(V)).join(", "),b=K(y,a`SELECT ${a.identifier("__partition__")}, ${a.raw(v)} FROM ${a.identifier(h)} WHERE ${a.identifier("__id__")} = ${f}`).toArray(),[_]=b;if(_===void 0)return null;let A=_.__partition__;const M=Q(i.baseWhere,i.where);lt(M,l,e,"rank");const E=Ro(p,M);if(E){const V=vo(p.partitionBy??[],E);if(V!==A)return null;A=V}const q=$.map(V=>_[V]),{before:Y,total:X}=hn(y,h,$,p.sortBy,A,q,f);return{position:Y+1,total:X}},async rankBefore(e,t,i){if(ae(e))throw new S("INTERNAL",`rankBefore is not supported on the global (.global()) table '${e}' — cross-shard rank cursors apply only to sharded tables`);const d=l.tables[e];if(!d)throw new S("INTERNAL",`unknown table: ${e}`);const w=d.rankIndexes?.find($=>$.name===t);if(!w)throw new S("INTERNAL",`unknown rankIndex "${t}" on table "${e}"`);if(i.restrictsCounts)throw new at(e);k(e,j),ot(e,w);const p=Nt(e,w.name),f=w.sortBy.map(($,v)=>Qt(v)),h=w.sortBy.map(($,v)=>Ce(i.sortValues[v]??null));return hn(y,p,f,w.sortBy,i.partitionKey,h,i.rowId)},async rankPage(e,t,i={}){lt(Q(i.baseWhere,i.where),l,e,"rankPage");const d=H(e,"rankPage");if(d)return k(e,j),d.rankPage(e,t,i);te(e,t,"rank");const{continueCursor:w,hasMore:p,rows:f}=Ot(Bt,e,t,i);return{continueCursor:w,isDone:!p,page:f.map(h=>h.doc)}},async rankPageRows(e,t,i={}){lt(Q(i.baseWhere,i.where),l,e,"rankPage"),te(e,t,"rank");const{directions:d,hasMore:w,rows:p}=Ot(Bt,e,t,i);return{directions:d,hasMore:w,rows:p}},async restore(e,t){I(e,"ctx.db.restore(table, id)");const i=re(t,e);if(!i){const p=_e(e);if(p?.restore){await p.restore(e,t);return}throw new S("NOT_FOUND",`document not found: ${t}`)}const d=l.tables[i.tableName]?.softDeleteMode?.field;if(!d)throw new S("INTERNAL",`ctx.db.restore: table "${i.tableName}" is not a .softDelete() table`);const w=i.row[d]!==null&&i.row[d]!==void 0;await O.patch(e,t,{[d]:null}),w&&Te(i.tableName,t,void 0,i.row)},async replace(e,t,i,d){I(e,"ctx.db.replace(table, id, document)");const w=re(t,e);if(!w){const q=_e(e);if(q){J(i),await q.replace(e,t,i,d);return}throw new S("NOT_FOUND",`document not found: ${t}`)}const{docJson:p,row:f,tableName:h}=w,$=l.tables[h];if(!$)throw new S("INTERNAL",`unknown table: ${h}`);un("replace",i);const v=d?.allowExplicitId&&typeof i._creationTime=="number"?i._creationTime:void 0,b=typeof f._creationTime=="number"?f._creationTime:void 0,_=v??b??Ee(),A={...i,...ee(h),_creationTime:_,_id:t};ft($,i,A,ce);const M=d?.allowExplicitId===!0,E=je($,A,{previous:()=>f,supplied:i,trusted:M});ne(h,"before","update")&&await oe("before","update",{doc:{...E},id:t,op:"update",previous:f,table:h}),M||B(h,E,f),Re(h),ve(h),Ne(y,h,fr(h),[_,le(E),t,p]),Fe(h,t,E,f),Le(h,t,E),ke(h,f,E),Te(h,t,f,E),$e?.invalidate(h,t,N(h,f,E)),Se(h,t,"update",E),D({indexKeys:N(h,f,E),key:t,op:"update",row:E,table:h}),ne(h,"after","update")&&await oe("after","update",{doc:E,id:t,op:"update",previous:f,table:h}),await ye({doc:E,id:t,op:"update",table:h})},async wipeShard(e){const t=new Set(e?.exclude),i=e?.tables,d=Object.entries(l.tables).filter(([h,$])=>t.has(h)||i!==void 0&&!i.includes(h)?!1:$.shardMode?.kind!=="global").map(([h])=>h);if(i!==void 0){for(const h of i)if(!l.tables[h])throw new S("INTERNAL",`wipeShard: unknown table: ${h}`)}const w={};let p=0;const{deleteAll:f}=O;if(f===void 0)throw new S("INTERNAL","wipeShard: this writer has no deleteAll");for(const h of d){const $=await f(h,{...e?.chunkSize===void 0?{}:{chunkSize:e.chunkSize},hard:!0});w[h]=$.deleted,p+=$.deleted}return{deleted:p,tables:w}}},Wn={db:O,scheduler:vt};return n.enforceRls===!0?Uo(O,l,(e,t)=>re(e,t)?.tableName,T):O};export{Oi as CDC_LOG_TABLE,ds as IDEMPOTENCY_TABLE,Dr as NotUniqueError,is as advanceClientWatermark,ji as applyCdcChanges,un as assertNoExplicitUndefined,$t as assertStorableRowId,Er as assertValidClientId,Bi as backfillAggregateIndexes,qi as backfillRankIndexes,Pi as backfillSearchIndexes,Gi as bumpCdcEpoch,Hi as cdcCanVouchFor,Ki as cdcForkedError,Ni as cdcSeqLeavingRows,Qi as cdcTouchesTables,Vi as cdcTrimmedError,Ji as compactCdcDocs,Jr as createShardCtxDb,zi as cursorBelowRetainedFloor,Gr as meterReadBytes,ss as migrateClientWatermark,Yi as minCdcReplayableSeq,Xi as minCdcSeq,dn as normalizeIdStructurally,Zi as readCdcChangeKeys,es as readCdcChanges,ts as readCdcCursor,ns as readCdcEpoch,cs as readClientWatermark,ls as readIdempotent,ws as runShardMigrations,gs as selectShapeMembers,ys as selectShapeRows,Ke as stripReservedPatchFields,os as trimCdcChanges,us as trimIdempotent,fs as writeIdempotent};
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
const i=(t,e)=>{const n=Math.max(t.length,e.length);let o=t.length^e.length;for(let r=0;r<n;r+=1){const c=r<t.length?t.charCodeAt(r):0,s=r<e.length?e.charCodeAt(r):0;o|=c^s}return o===0},a=(t,e)=>{if(t.size<e)return;const n=t.keys().next().value;n!==void 0&&t.delete(n)},l=(t,e,n,o)=>{const r=t.get(e);if(r!==void 0)return r;a(t,o);const c=n().catch(s=>{throw t.get(e)===c&&t.delete(e),s});return t.set(e,c),c},d=new TextEncoder,g=64,h=new Map,E=async t=>l(h,t,async()=>crypto.subtle.importKey("raw",d.encode(t),{hash:"SHA-256",name:"HMAC"},!1,["sign","verify"]),g),u="LUNORA_RELAY_SECRET",A="x-lunora-relay-sig",f=t=>{const e=t?.[u];return typeof e=="string"&&e.length>0?e:void 0},y=async(t,e)=>{const n=await crypto.subtle.sign("HMAC",await E(t),new TextEncoder().encode(e));return[...new Uint8Array(n)].map(o=>o.toString(16).padStart(2,"0")).join("")},v=async(t,e,n)=>{const o=f(t);return o===void 0?!0:e===null?!1:i(e,await y(o,n))};export{A as RELAY_SIGNATURE_HEADER,f as siblingSecretOf,y as signSiblingBody,v as verifySiblingBody};
|