@lunora/shard-engine 1.0.0-alpha.63 → 1.0.0-alpha.65
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 +122 -76
- package/dist/index.d.ts +122 -76
- package/dist/index.mjs +1 -1
- package/dist/packem_shared/ADMIN_FUNCTIONS-CRXp5IZu.mjs +1 -0
- package/dist/packem_shared/{DEFAULT_MAX_RELAYS-DDOVsK5A.mjs → DEFAULT_MAX_RELAYS-Ng4SyJ7k.mjs} +2 -2
- package/dist/packem_shared/NotUniqueError-BMom69SD.mjs +1 -0
- package/dist/packem_shared/RELATED_DEFAULT_LIMIT-B9PH28Pn.mjs +1 -0
- package/dist/packem_shared/RLS_UNWRAP_SYMBOL-BwwTbz3Q.mjs +1 -0
- package/dist/packem_shared/{defineEngineContractSuite-C5r9sGEo.mjs → defineEngineContractSuite-BFT_djtN.mjs} +1 -1
- package/package.json +3 -3
- package/dist/packem_shared/ADMIN_FUNCTIONS-B-nIrmAV.mjs +0 -1
- package/dist/packem_shared/NotUniqueError-DqlL1ViB.mjs +0 -1
- package/dist/packem_shared/RLS_UNWRAP_SYMBOL-BF5gi64E.mjs +0 -1
|
@@ -1 +1 @@
|
|
|
1
|
-
import{defineEngineContractSuite as t}from"../packem_shared/defineEngineContractSuite-
|
|
1
|
+
import{defineEngineContractSuite as t}from"../packem_shared/defineEngineContractSuite-BFT_djtN.mjs";export{t as defineEngineContractSuite};
|
package/dist/index.d.mts
CHANGED
|
@@ -88,6 +88,75 @@ interface WhereInput {
|
|
|
88
88
|
OR?: WhereInput[];
|
|
89
89
|
}
|
|
90
90
|
declare const RELATION_EXISTS_KEY = "__relationExists";
|
|
91
|
+
interface SubscriptionQuery {
|
|
92
|
+
args?: Record<string, unknown>;
|
|
93
|
+
functionPath?: string;
|
|
94
|
+
sinceEpoch?: string;
|
|
95
|
+
sinceSeq?: number;
|
|
96
|
+
table?: string;
|
|
97
|
+
}
|
|
98
|
+
interface ShapeSubscriptionQuery {
|
|
99
|
+
args?: Record<string, unknown>;
|
|
100
|
+
name: string;
|
|
101
|
+
sinceEpoch?: string;
|
|
102
|
+
sinceSeq?: number;
|
|
103
|
+
}
|
|
104
|
+
interface SubscriptionEnvelope {
|
|
105
|
+
caps?: string[];
|
|
106
|
+
clientId?: string;
|
|
107
|
+
context?: Record<string, unknown>;
|
|
108
|
+
data?: unknown;
|
|
109
|
+
generation?: number;
|
|
110
|
+
id: string;
|
|
111
|
+
query?: SubscriptionQuery;
|
|
112
|
+
shape?: {
|
|
113
|
+
args?: Record<string, unknown>;
|
|
114
|
+
name: string;
|
|
115
|
+
};
|
|
116
|
+
sinceCheckpoint?: number;
|
|
117
|
+
sinceChunk?: number;
|
|
118
|
+
sinceEpoch?: string;
|
|
119
|
+
topic?: string;
|
|
120
|
+
type: "ack" | "connect" | "shape_subscribe" | "shape_unsubscribe" | "stream" | "subscribe" | "unsubscribe" | "whisper" | "whisper_subscribe" | "whisper_unsubscribe";
|
|
121
|
+
}
|
|
122
|
+
interface RpcRequest {
|
|
123
|
+
args?: Record<string, unknown>;
|
|
124
|
+
functionPath: string;
|
|
125
|
+
}
|
|
126
|
+
interface SocketAttachment {
|
|
127
|
+
admin?: boolean;
|
|
128
|
+
adminBinding?: string;
|
|
129
|
+
clientId?: string;
|
|
130
|
+
connected?: boolean;
|
|
131
|
+
connectionId?: string;
|
|
132
|
+
context?: Record<string, unknown>;
|
|
133
|
+
expiresAt?: number;
|
|
134
|
+
identity?: Record<string, unknown>;
|
|
135
|
+
ip?: string;
|
|
136
|
+
pageDeltas?: boolean;
|
|
137
|
+
shapes?: Record<string, ShapeSubscriptionQuery>;
|
|
138
|
+
subs: Record<string, SubscriptionQuery>;
|
|
139
|
+
userId?: string;
|
|
140
|
+
whispers?: string[];
|
|
141
|
+
}
|
|
142
|
+
interface ResolvedShape {
|
|
143
|
+
columns?: ReadonlyArray<string>;
|
|
144
|
+
effectiveWhere?: WhereInput;
|
|
145
|
+
global?: boolean;
|
|
146
|
+
table: string;
|
|
147
|
+
}
|
|
148
|
+
interface SubscriptionIdentity {
|
|
149
|
+
identity?: Record<string, unknown>;
|
|
150
|
+
ip?: string;
|
|
151
|
+
userId?: string;
|
|
152
|
+
}
|
|
153
|
+
interface ShardSocketLike {
|
|
154
|
+
readonly bufferedAmount?: number;
|
|
155
|
+
close?: (code?: number, reason?: string) => void;
|
|
156
|
+
deserializeAttachment?: () => unknown;
|
|
157
|
+
send: (data: string) => void;
|
|
158
|
+
serializeAttachment?: (value: unknown) => void;
|
|
159
|
+
}
|
|
91
160
|
type AggregateOp = "avg" | "count" | "max" | "min" | "sum";
|
|
92
161
|
interface AggregateIndexDefinitionLike {
|
|
93
162
|
readonly by?: ReadonlyArray<string>;
|
|
@@ -139,6 +208,8 @@ interface ColumnMetaLike {
|
|
|
139
208
|
interface ValidatorLike {
|
|
140
209
|
readonly _meta?: {
|
|
141
210
|
readonly column?: ColumnMetaLike;
|
|
211
|
+
readonly inner?: ValidatorLike;
|
|
212
|
+
readonly tableName?: string;
|
|
142
213
|
};
|
|
143
214
|
readonly kind?: string;
|
|
144
215
|
readonly parse?: (value: unknown) => unknown;
|
|
@@ -279,6 +350,43 @@ interface QueryPage {
|
|
|
279
350
|
page: Record<string, unknown>[];
|
|
280
351
|
splitCursor?: null | string;
|
|
281
352
|
}
|
|
353
|
+
interface RelationEdge {
|
|
354
|
+
readonly array: boolean;
|
|
355
|
+
readonly column: string;
|
|
356
|
+
readonly name: string;
|
|
357
|
+
readonly sourceTable: string;
|
|
358
|
+
readonly targetTable: string;
|
|
359
|
+
}
|
|
360
|
+
interface RelatedStartReference {
|
|
361
|
+
id: string;
|
|
362
|
+
table: string;
|
|
363
|
+
}
|
|
364
|
+
type RelatedStart = (Record<string, unknown> & {
|
|
365
|
+
_id: string;
|
|
366
|
+
}) | RelatedStartReference;
|
|
367
|
+
type RelatedDirection = "both" | "in" | "out";
|
|
368
|
+
interface RelatedOptions {
|
|
369
|
+
cursor?: null | string;
|
|
370
|
+
depth?: number;
|
|
371
|
+
direction?: RelatedDirection;
|
|
372
|
+
edges?: ReadonlyArray<string>;
|
|
373
|
+
limit?: number;
|
|
374
|
+
relationBaseWhere?: (table: string) => undefined | WhereInput;
|
|
375
|
+
relationMask?: RelationMask;
|
|
376
|
+
}
|
|
377
|
+
interface RelatedNode {
|
|
378
|
+
depth: number;
|
|
379
|
+
document: Record<string, unknown>;
|
|
380
|
+
path: ReadonlyArray<string>;
|
|
381
|
+
pathIds: ReadonlyArray<string>;
|
|
382
|
+
score: number;
|
|
383
|
+
table: string;
|
|
384
|
+
}
|
|
385
|
+
interface RelatedPage {
|
|
386
|
+
continueCursor: null | string;
|
|
387
|
+
isDone: boolean;
|
|
388
|
+
nodes: RelatedNode[];
|
|
389
|
+
}
|
|
282
390
|
interface OrderKey {
|
|
283
391
|
direction: SortDirection;
|
|
284
392
|
field: string;
|
|
@@ -418,10 +526,8 @@ interface LifecycleEvent {
|
|
|
418
526
|
shardKey: string;
|
|
419
527
|
userId: string | null;
|
|
420
528
|
}
|
|
421
|
-
interface LifecycleDispatchInfo {
|
|
529
|
+
interface LifecycleDispatchInfo extends SubscriptionIdentity {
|
|
422
530
|
event: LifecycleEvent;
|
|
423
|
-
identity: Record<string, unknown> | undefined;
|
|
424
|
-
userId: string | undefined;
|
|
425
531
|
}
|
|
426
532
|
interface MutationDelta {
|
|
427
533
|
indexKeys?: ReadonlyArray<IndexKeyEntry>;
|
|
@@ -504,6 +610,8 @@ interface DatabaseWriterLike {
|
|
|
504
610
|
rankBefore?: (tableName: string, indexName: string, options: RankBeforeOptions) => Promise<RankBeforeResult>;
|
|
505
611
|
rankPage: (tableName: string, indexName: string, options?: RankPageOptions) => Promise<RankPage>;
|
|
506
612
|
rankPageRows?: (tableName: string, indexName: string, options?: RankPageOptions) => Promise<ShardRankPageResult>;
|
|
613
|
+
related?: (start: RelatedStart, options?: RelatedOptions) => Promise<RelatedPage>;
|
|
614
|
+
relationEdges?: ReadonlyArray<RelationEdge>;
|
|
507
615
|
replace: (id: string, document: Record<string, unknown>, expectedTable?: string, options?: {
|
|
508
616
|
allowExplicitId?: boolean;
|
|
509
617
|
}) => Promise<void>;
|
|
@@ -864,73 +972,6 @@ declare const COMMIT_SEQ_FIELD = "_commitSeq";
|
|
|
864
972
|
declare const migrateCommitSeq: (sql: SqlExec) => void;
|
|
865
973
|
declare const readCommitSeq: (sql: SqlExec) => number;
|
|
866
974
|
declare const allocateCommitSeq: (sql: SqlExec) => number;
|
|
867
|
-
interface SubscriptionQuery {
|
|
868
|
-
args?: Record<string, unknown>;
|
|
869
|
-
functionPath?: string;
|
|
870
|
-
sinceEpoch?: string;
|
|
871
|
-
sinceSeq?: number;
|
|
872
|
-
table?: string;
|
|
873
|
-
}
|
|
874
|
-
interface ShapeSubscriptionQuery {
|
|
875
|
-
args?: Record<string, unknown>;
|
|
876
|
-
name: string;
|
|
877
|
-
sinceEpoch?: string;
|
|
878
|
-
sinceSeq?: number;
|
|
879
|
-
}
|
|
880
|
-
interface SubscriptionEnvelope {
|
|
881
|
-
caps?: string[];
|
|
882
|
-
clientId?: string;
|
|
883
|
-
context?: Record<string, unknown>;
|
|
884
|
-
data?: unknown;
|
|
885
|
-
generation?: number;
|
|
886
|
-
id: string;
|
|
887
|
-
query?: SubscriptionQuery;
|
|
888
|
-
shape?: {
|
|
889
|
-
args?: Record<string, unknown>;
|
|
890
|
-
name: string;
|
|
891
|
-
};
|
|
892
|
-
sinceCheckpoint?: number;
|
|
893
|
-
sinceChunk?: number;
|
|
894
|
-
sinceEpoch?: string;
|
|
895
|
-
topic?: string;
|
|
896
|
-
type: "ack" | "connect" | "shape_subscribe" | "shape_unsubscribe" | "stream" | "subscribe" | "unsubscribe" | "whisper" | "whisper_subscribe" | "whisper_unsubscribe";
|
|
897
|
-
}
|
|
898
|
-
interface RpcRequest {
|
|
899
|
-
args?: Record<string, unknown>;
|
|
900
|
-
functionPath: string;
|
|
901
|
-
}
|
|
902
|
-
interface SocketAttachment {
|
|
903
|
-
admin?: boolean;
|
|
904
|
-
adminBinding?: string;
|
|
905
|
-
clientId?: string;
|
|
906
|
-
connected?: boolean;
|
|
907
|
-
connectionId?: string;
|
|
908
|
-
context?: Record<string, unknown>;
|
|
909
|
-
expiresAt?: number;
|
|
910
|
-
identity?: Record<string, unknown>;
|
|
911
|
-
pageDeltas?: boolean;
|
|
912
|
-
shapes?: Record<string, ShapeSubscriptionQuery>;
|
|
913
|
-
subs: Record<string, SubscriptionQuery>;
|
|
914
|
-
userId?: string;
|
|
915
|
-
whispers?: string[];
|
|
916
|
-
}
|
|
917
|
-
interface ResolvedShape {
|
|
918
|
-
columns?: ReadonlyArray<string>;
|
|
919
|
-
effectiveWhere?: WhereInput;
|
|
920
|
-
global?: boolean;
|
|
921
|
-
table: string;
|
|
922
|
-
}
|
|
923
|
-
interface SubscriptionIdentity {
|
|
924
|
-
identity?: Record<string, unknown>;
|
|
925
|
-
userId?: string;
|
|
926
|
-
}
|
|
927
|
-
interface ShardSocketLike {
|
|
928
|
-
readonly bufferedAmount?: number;
|
|
929
|
-
close?: (code?: number, reason?: string) => void;
|
|
930
|
-
deserializeAttachment?: () => unknown;
|
|
931
|
-
send: (data: string) => void;
|
|
932
|
-
serializeAttachment?: (value: unknown) => void;
|
|
933
|
-
}
|
|
934
975
|
interface CompanionSyncDeps {
|
|
935
976
|
broadcast: (delta: MutationDelta) => void;
|
|
936
977
|
indexKeysFor: (table: string, document?: Record<string, unknown>) => ReadonlyArray<{
|
|
@@ -1267,6 +1308,7 @@ declare const ADMIN_FUNCTIONS: {
|
|
|
1267
1308
|
readonly explainIssue: "__lunora_admin__:explainIssue";
|
|
1268
1309
|
readonly exportShard: "__lunora_admin__:exportShard";
|
|
1269
1310
|
readonly facetColumn: "__lunora_admin__:facetColumn";
|
|
1311
|
+
readonly findRelated: "__lunora_admin__:findRelated";
|
|
1270
1312
|
readonly getAdvisories: "__lunora_admin__:getAdvisories";
|
|
1271
1313
|
readonly getAdvisorProcedures: "__lunora_admin__:getAdvisorProcedures";
|
|
1272
1314
|
readonly getAuditLog: "__lunora_admin__:getAuditLog";
|
|
@@ -1861,6 +1903,13 @@ interface ReadFootprint {
|
|
|
1861
1903
|
declare const createReadFootprint: () => ReadFootprint;
|
|
1862
1904
|
declare const UNVOUCHABLE_DEP = "!unvouchable";
|
|
1863
1905
|
declare const markUnvouchableReads: <T extends object>(facade: T, onRead: ReadFootprint["onRead"] | undefined, methods: ReadonlyArray<string>) => T;
|
|
1906
|
+
declare const RELATED_MAX_DEPTH = 4;
|
|
1907
|
+
declare const RELATED_DEFAULT_LIMIT = 50;
|
|
1908
|
+
declare const RELATED_MAX_LIMIT = 200;
|
|
1909
|
+
declare const RELATED_DEPTH_DECAY = 0.5;
|
|
1910
|
+
declare const deriveRelationEdges: (schema: SchemaLike) => RelationEdge[];
|
|
1911
|
+
type RelationGraphReader = Pick<DatabaseWriterLike, "findMany"> & Pick<Partial<DatabaseWriterLike>, "lookupById">;
|
|
1912
|
+
declare const findRelated: (reader: RelationGraphReader, edges: ReadonlyArray<RelationEdge>, start: RelatedStart, options?: RelatedOptions) => Promise<RelatedPage>;
|
|
1864
1913
|
declare const DEFAULT_MAX_RELATION_KEYS = 5000;
|
|
1865
1914
|
interface RelationExistsMarker {
|
|
1866
1915
|
childWhere: WhereInput;
|
|
@@ -2221,7 +2270,7 @@ interface GuardableSchema {
|
|
|
2221
2270
|
}
|
|
2222
2271
|
type TableOfId = (id: string, expectedTable?: string) => Promise<string | undefined> | string | undefined;
|
|
2223
2272
|
type TablesOfIds = (ids: ReadonlyArray<string>, expectedTable?: string) => Promise<ReadonlyMap<string, string>> | ReadonlyMap<string, string>;
|
|
2224
|
-
declare const guardWriter: <W>(raw: W, schema: GuardableSchema, tableOfId: TableOfId, tablesOfIds?: TablesOfIds) => W;
|
|
2273
|
+
declare const guardWriter: <W>(raw: W, schema: GuardableSchema, tableOfId: TableOfId, tablesOfIds?: TablesOfIds, relationEdges?: ReadonlyArray<RelationEdge>) => W;
|
|
2225
2274
|
declare const SCHEMA_HISTORY_MAX_VERSIONS = 50;
|
|
2226
2275
|
interface SchemaVersionRow {
|
|
2227
2276
|
appliedAt: number;
|
|
@@ -2247,10 +2296,7 @@ declare class ShapeDiffCache {
|
|
|
2247
2296
|
private getOrLoad;
|
|
2248
2297
|
}
|
|
2249
2298
|
declare const createShapeDiffCache: () => ShapeDiffCache;
|
|
2250
|
-
declare const globalShapeReadKey: (resolved: ResolvedShape, identity:
|
|
2251
|
-
identity?: Record<string, unknown>;
|
|
2252
|
-
userId?: string;
|
|
2253
|
-
}) => string | undefined;
|
|
2299
|
+
declare const globalShapeReadKey: (resolved: ResolvedShape, identity: SubscriptionIdentity) => string | undefined;
|
|
2254
2300
|
type ReadShapeCdcKeys = (sql: SqlExec, table: string, sinceSeq: number, upTo: number) => CdcChangeKey[];
|
|
2255
2301
|
declare const buildShapeDiff: (sql: SqlExec, resolved: ResolvedShape, sinceSeq: number, upTo: number, cache: ShapeDiffCache, readKeys?: ReadShapeCdcKeys) => ShapeRowOp[];
|
|
2256
2302
|
interface ShardRunnerOptions {
|
|
@@ -2366,4 +2412,4 @@ interface WhereSqlStrategy<T = SQL> {
|
|
|
2366
2412
|
}
|
|
2367
2413
|
declare const literalInList: (reference: SQL, items: ReadonlyArray<unknown>, negated: boolean) => SQL;
|
|
2368
2414
|
declare const compileWhereSql: <T = SQL>(where: WhereInput | undefined, strategy: WhereSqlStrategy<T>, fragments?: WhereFragments<T>) => T | undefined;
|
|
2369
|
-
export { ADMIN_FUNCTIONS, ADMIN_FUNCTION_PREFIX, AGGREGATE_SQL_FUNCTION, AGG_COUNT, AGG_KEY, AGG_VALUE, AUDIT_LOG_TABLE, type AdvisorProcedure, type AdvisorProceduresResult, type AdvisoriesResult, type AdvisoryFinding, type AggregateIndexDefinitionLike, type AggregateOp, type AggregateOptions, type AggregateResult, type AggregateTally, type AppendAuditEntry, type ApplyOnDeleteOptions$1 as ApplyOnDeleteOptions, type AuditEntry, type AuditLogResult, 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, 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 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 ImportError, type ImportShardAdminArgs, type ImportShardArgs, type ImportShardResult, type IncrementalMaterializeResult, type IndexDefinitionLike, type IndexKeyEntry, type IndexRangeBuilderLike, type KeyRange, type LifecycleDispatchInfo, type LifecycleEvent, MAIL_RETENTION, MAIL_TABLE, MAX_DURABLE_STREAM_BYTES, MAX_DURABLE_STREAM_CHUNKS, MAX_PAGE_SIZE, MAX_SQL_ROWS, type MaskColumnMetadata, type MaskPoliciesResult, type MaterializeResult, type MigrationDirection, type MigrationRunResult, type MigrationStatus, type MigrationStatusRow, type MutationDelta, type NestedWith, NotFoundError, NotUniqueError, type OnDeleteActionLike, type OrderByClause, type OrderByInput, type OrderKey, type OrderKeyConstraints, OwnerRelay, type OwnerRelayFrame, type PaginationOptions, type PitrBookmarkResult, type PitrRestoreArgs, type PitrRestoreResult, type PitrStorage, type PokeFrameMeta, type PromotionState, type PromotionThresholds, QUEUE_TABLE, type QueryArgs, type QueryPage, type QueueMessageOutcome, type QueueMessageRow, type QueueMetadata, type QueuesResult, RANK_TIEBREAK, REACTOR_STATE_TABLE, RELATION_EXISTS_KEY, RELATION_FUNCTION_PREFIX, REPROJECTION_MIGRATION_PREFIX, RLS_UNWRAP_SYMBOL, type RankBeforeOptions, type RankBeforeResult, type RankDirection, type RankIndexDefinitionLike, type RankOptions, type RankPage, type RankPageComputation, type RankPageDeps, type RankPageOptions, type RankPageRow, type RankPageRowKey, type RankResult, type RankSortKeyLike, ReactiveCache, type ReactiveCacheOptions, type ReactorDispatchResult, type ReactorMetadata, type ReactorState, type ReactorStats, type ReactorsResult, type ReadFootprint, type ReadHook, type ReadTablePageOptions, type RecordMailInput, type RecordQueueMessageInput, type RelationDefinitionLike, type RelationExistsMarker, type RelayAttach, type RelayDetach, type RelayFrame, type RelayHost, RelayMember, type RelayPokeDelivery, 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, SCHEMA_HISTORY_MAX_VERSIONS, SEARCH_STATE_TABLE, SHAPE_POKE_CURSOR_TABLE, type SchedulableWorkflowReferenceLike, 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 TransactionHeadroom, TransactionHeadroomTracker, type TransactionLimits, type TransactionSqlLike, type TriggerContextLike, type TriggerDefinitionLike, type TriggerEventLike, type TriggerOpLike, type TriggerTimingLike, type TtlSweepSpec, UNVOUCHABLE_DEP, type ValidatorLike, 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, applyOnDelete, applySelect, archiveCdcSegment, armRestore, assertFlatPredicate, assertNoExplicitUndefined, assertReadonly, assertShapeShardable, assertValidClientId, awaitWsDrain, backfillAggregateIndexes, backfillRankIndexes, backfillSearchIndexes, backfillSearchIndexesForTable, bigintSqlKey, boundingBoxCenter, boundingBoxGeohashes, buildIndexRange, buildPokeFrames, buildReprojectionMigration, buildSeekBeforeWhere, buildSeekWhere, buildSettings, buildShapeDiff, bumpCdcEpoch, cdcCanVouchFor, cdcSeqLeavingRows, cdcTouchesTables, cdcTrimmedError, claimStreamRun, clampPromotionThresholds, clearCapturedMail, clearMemoryTables, clearQueueMessages, coerceAggregateNumber, compactCdcDocs, compileWhereSql, computeRankPage, containsRelationPredicate, countLegacyRows, coveringGeohashes, createCompanionSync, createDependencyTracker, createFanoutCounters, createGlobalPollCounters, createIndexSql, createReadFootprint, createRelayLink, createReplicaLink, createShapeDiffCache, createShapeProbeCounters, createShardCtxDb, createSystemReader, cursorBelowRetainedFloor, decideDurableAttach, decodeBigintSqlKey, decodeCursor, decodeFloat64SqlKey, deleteGlobalShapeSnapshot, deleteGlobalShapeSnapshotsForConnection, deleteShapePokeCursor, deleteShapePokeCursorsForConnection, deleteStreamRun, depKey, diffExternalSource, diffGlobalMembership, distinctValues, encodeAggregateKey, encodeCursor, encodeGeohash, encodePartitionKey, encodeRowsPatch, ensureAuditTable, ensureMailTable, envOptionalPositiveInt, envPositiveInt, equalityPinnedFields, exportShardRows, facetColumn, fanOutScalarCounts, findStorageReferences, finishStreamRun, float64SqlKey, foldAggregateTally, gateReplicaDispatch, geoTableName, globalShapeReadKey, guardWriter, handleReplicaControl, hasTrigger, haversineMeters, importShardRows, indexKeysForRow, isDevEnvironment, isFtsAvailable, isLossyBody, isMemoryTable, isRelationPredicate, isSoftDeleted, isSourceDue, jsonPath, jsonPathSql, keysTouchRanges, liftSourceId, lintReadonlySql, listReactorStates, listTables, literalInList, markUnvouchableReads, matchesRankStaticWhere, matchesStaticWhere, materializeExternalRows, materializeExternalRowsIncremental, memoryTableNames, mergeChangedKeys, mergeWhere, migrateCdcLog, migrateCdcMeta, migrateClientWatermark, migrateCommitSeq, migrateDurableStreams, migrateGlobalShapeSnapshot, migrateIdempotency, migrateReactorState, migrateSearchState, migrateShapePokeCursor, minCdcReplayableSeq, minCdcSeq, minShapePokeCursor, nextPromotionState, normalizeCountArgument, normalizeIdStructurally, normalizeOrderKeys, normalizeSourceDocument, normalizeSourceValue, param, parseExportShardArgs, parseImportShardArgs, planAggregateLookup, pointInBoundingBox, 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, readExternalSourceBaseline, readGlobalShapeSnapshot, readIdempotent, readMigrationStatus, readQueueMessageById, readQueueMessages, readReactorState, readSchemaHistory, readSchemaVersion, readSearchBackfillState, readShapePokeCursor, readStreamChunks, readStreamRun, readTablePage, recordCapturedMail, recordChangedKeys, recordFanoutPass, recordGlobalPollPass, recordQueueMessages, recordSchemaVersion, recordShapeProbePass, relationHooks, relayCountFor, renderSql, reprojectableFields, reprojectionMigrationId, reprojectionTables, resolveRankPartition, resolveRankSeekTuple, resolveRelationPredicates, resolveWith, rowToDocument, runDataMigration, runDrizzle, runExternalSourceTick, runReadonlySql, runRowValidators, runShardMigrations, runSocketPool, runSql, runTriggers, selectExpiredIds, selectExportTables, selectIndexForAggregate, selectIndexForCount, selectIndexForGroupBy, selectMatchingIds, selectShapeMembers, selectShapeRows, serializeSqlValue, shapeRoutingKey, softDeleteScope, sortColumnName, sqliteInList, stableStringify, stableWireKey, subscriptionFrames, subscriptionListDeltas, summarizeFanoutTopics, summarizeSubscriptions, tableColumns, tableFromDepKey, throwingScheduler, tiebreakDirectionFor, trimCdcChanges, trimIdempotent, trimStreamRuns, tryRowToDocument, trySendFrame, unionAll, uniqueIndexFields, validateImportRow, writeCdcArchivedThrough, writeGlobalShapeSnapshot, writeIdempotent, writeReactorState, writeSearchBackfillState, writeShapePokeCursor, writeShapePokeCursors, writeTouchesMemo };
|
|
2415
|
+
export { ADMIN_FUNCTIONS, ADMIN_FUNCTION_PREFIX, AGGREGATE_SQL_FUNCTION, AGG_COUNT, AGG_KEY, AGG_VALUE, AUDIT_LOG_TABLE, type AdvisorProcedure, type AdvisorProceduresResult, type AdvisoriesResult, type AdvisoryFinding, type AggregateIndexDefinitionLike, type AggregateOp, type AggregateOptions, type AggregateResult, type AggregateTally, type AppendAuditEntry, type ApplyOnDeleteOptions$1 as ApplyOnDeleteOptions, type AuditEntry, type AuditLogResult, 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, 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 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 ImportError, type ImportShardAdminArgs, type ImportShardArgs, type ImportShardResult, type IncrementalMaterializeResult, type IndexDefinitionLike, type IndexKeyEntry, type IndexRangeBuilderLike, type KeyRange, type LifecycleDispatchInfo, type LifecycleEvent, MAIL_RETENTION, MAIL_TABLE, MAX_DURABLE_STREAM_BYTES, MAX_DURABLE_STREAM_CHUNKS, MAX_PAGE_SIZE, MAX_SQL_ROWS, type MaskColumnMetadata, type MaskPoliciesResult, type MaterializeResult, type MigrationDirection, type MigrationRunResult, type MigrationStatus, type MigrationStatusRow, type MutationDelta, type NestedWith, NotFoundError, NotUniqueError, type OnDeleteActionLike, type OrderByClause, type OrderByInput, type OrderKey, type OrderKeyConstraints, OwnerRelay, type OwnerRelayFrame, type PaginationOptions, type PitrBookmarkResult, type PitrRestoreArgs, type PitrRestoreResult, type PitrStorage, type PokeFrameMeta, type PromotionState, type PromotionThresholds, QUEUE_TABLE, type QueryArgs, type QueryPage, type QueueMessageOutcome, type QueueMessageRow, type QueueMetadata, type QueuesResult, RANK_TIEBREAK, REACTOR_STATE_TABLE, RELATED_DEFAULT_LIMIT, RELATED_DEPTH_DECAY, RELATED_MAX_DEPTH, RELATED_MAX_LIMIT, RELATION_EXISTS_KEY, RELATION_FUNCTION_PREFIX, REPROJECTION_MIGRATION_PREFIX, RLS_UNWRAP_SYMBOL, type RankBeforeOptions, type RankBeforeResult, type RankDirection, type RankIndexDefinitionLike, type RankOptions, type RankPage, type RankPageComputation, type RankPageDeps, type RankPageOptions, type RankPageRow, type RankPageRowKey, type RankResult, type RankSortKeyLike, ReactiveCache, type ReactiveCacheOptions, type 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 RelayAttach, type RelayDetach, type RelayFrame, type RelayHost, RelayMember, type RelayPokeDelivery, 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, SCHEMA_HISTORY_MAX_VERSIONS, SEARCH_STATE_TABLE, SHAPE_POKE_CURSOR_TABLE, type SchedulableWorkflowReferenceLike, 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 TransactionHeadroom, TransactionHeadroomTracker, type TransactionLimits, type TransactionSqlLike, type TriggerContextLike, type TriggerDefinitionLike, type TriggerEventLike, type TriggerOpLike, type TriggerTimingLike, type TtlSweepSpec, UNVOUCHABLE_DEP, type ValidatorLike, 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, applyOnDelete, applySelect, archiveCdcSegment, armRestore, assertFlatPredicate, assertNoExplicitUndefined, assertReadonly, assertShapeShardable, assertValidClientId, awaitWsDrain, backfillAggregateIndexes, backfillRankIndexes, backfillSearchIndexes, backfillSearchIndexesForTable, bigintSqlKey, boundingBoxCenter, boundingBoxGeohashes, buildIndexRange, buildPokeFrames, buildReprojectionMigration, buildSeekBeforeWhere, buildSeekWhere, buildSettings, buildShapeDiff, bumpCdcEpoch, cdcCanVouchFor, cdcSeqLeavingRows, cdcTouchesTables, cdcTrimmedError, claimStreamRun, clampPromotionThresholds, clearCapturedMail, clearMemoryTables, clearQueueMessages, coerceAggregateNumber, compactCdcDocs, compileWhereSql, computeRankPage, containsRelationPredicate, countLegacyRows, coveringGeohashes, createCompanionSync, createDependencyTracker, createFanoutCounters, createGlobalPollCounters, createIndexSql, createReadFootprint, createRelayLink, createReplicaLink, createShapeDiffCache, createShapeProbeCounters, createShardCtxDb, createSystemReader, cursorBelowRetainedFloor, decideDurableAttach, decodeBigintSqlKey, decodeCursor, decodeFloat64SqlKey, deleteGlobalShapeSnapshot, deleteGlobalShapeSnapshotsForConnection, deleteShapePokeCursor, deleteShapePokeCursorsForConnection, deleteStreamRun, depKey, deriveRelationEdges, diffExternalSource, diffGlobalMembership, distinctValues, encodeAggregateKey, encodeCursor, encodeGeohash, encodePartitionKey, encodeRowsPatch, ensureAuditTable, ensureMailTable, envOptionalPositiveInt, envPositiveInt, equalityPinnedFields, exportShardRows, facetColumn, fanOutScalarCounts, findRelated, findStorageReferences, finishStreamRun, float64SqlKey, foldAggregateTally, gateReplicaDispatch, geoTableName, globalShapeReadKey, guardWriter, handleReplicaControl, hasTrigger, haversineMeters, importShardRows, indexKeysForRow, isDevEnvironment, isFtsAvailable, isLossyBody, isMemoryTable, isRelationPredicate, isSoftDeleted, isSourceDue, jsonPath, jsonPathSql, keysTouchRanges, liftSourceId, lintReadonlySql, listReactorStates, listTables, literalInList, markUnvouchableReads, matchesRankStaticWhere, matchesStaticWhere, materializeExternalRows, materializeExternalRowsIncremental, memoryTableNames, mergeChangedKeys, mergeWhere, migrateCdcLog, migrateCdcMeta, migrateClientWatermark, migrateCommitSeq, migrateDurableStreams, migrateGlobalShapeSnapshot, migrateIdempotency, migrateReactorState, migrateSearchState, migrateShapePokeCursor, minCdcReplayableSeq, minCdcSeq, minShapePokeCursor, nextPromotionState, normalizeCountArgument, normalizeIdStructurally, normalizeOrderKeys, normalizeSourceDocument, normalizeSourceValue, param, parseExportShardArgs, parseImportShardArgs, planAggregateLookup, pointInBoundingBox, 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, readExternalSourceBaseline, readGlobalShapeSnapshot, readIdempotent, readMigrationStatus, readQueueMessageById, readQueueMessages, readReactorState, readSchemaHistory, readSchemaVersion, readSearchBackfillState, readShapePokeCursor, readStreamChunks, readStreamRun, readTablePage, recordCapturedMail, recordChangedKeys, recordFanoutPass, recordGlobalPollPass, recordQueueMessages, recordSchemaVersion, recordShapeProbePass, relationHooks, relayCountFor, renderSql, reprojectableFields, reprojectionMigrationId, reprojectionTables, resolveRankPartition, resolveRankSeekTuple, resolveRelationPredicates, resolveWith, rowToDocument, runDataMigration, runDrizzle, runExternalSourceTick, runReadonlySql, runRowValidators, runShardMigrations, runSocketPool, runSql, runTriggers, selectExpiredIds, selectExportTables, selectIndexForAggregate, selectIndexForCount, selectIndexForGroupBy, selectMatchingIds, selectShapeMembers, selectShapeRows, serializeSqlValue, shapeRoutingKey, softDeleteScope, sortColumnName, sqliteInList, stableStringify, stableWireKey, subscriptionFrames, subscriptionListDeltas, summarizeFanoutTopics, summarizeSubscriptions, tableColumns, tableFromDepKey, throwingScheduler, tiebreakDirectionFor, trimCdcChanges, trimIdempotent, trimStreamRuns, tryRowToDocument, trySendFrame, unionAll, uniqueIndexFields, validateImportRow, writeCdcArchivedThrough, writeGlobalShapeSnapshot, writeIdempotent, writeReactorState, writeSearchBackfillState, writeShapePokeCursor, writeShapePokeCursors, writeTouchesMemo };
|
package/dist/index.d.ts
CHANGED
|
@@ -88,6 +88,75 @@ interface WhereInput {
|
|
|
88
88
|
OR?: WhereInput[];
|
|
89
89
|
}
|
|
90
90
|
declare const RELATION_EXISTS_KEY = "__relationExists";
|
|
91
|
+
interface SubscriptionQuery {
|
|
92
|
+
args?: Record<string, unknown>;
|
|
93
|
+
functionPath?: string;
|
|
94
|
+
sinceEpoch?: string;
|
|
95
|
+
sinceSeq?: number;
|
|
96
|
+
table?: string;
|
|
97
|
+
}
|
|
98
|
+
interface ShapeSubscriptionQuery {
|
|
99
|
+
args?: Record<string, unknown>;
|
|
100
|
+
name: string;
|
|
101
|
+
sinceEpoch?: string;
|
|
102
|
+
sinceSeq?: number;
|
|
103
|
+
}
|
|
104
|
+
interface SubscriptionEnvelope {
|
|
105
|
+
caps?: string[];
|
|
106
|
+
clientId?: string;
|
|
107
|
+
context?: Record<string, unknown>;
|
|
108
|
+
data?: unknown;
|
|
109
|
+
generation?: number;
|
|
110
|
+
id: string;
|
|
111
|
+
query?: SubscriptionQuery;
|
|
112
|
+
shape?: {
|
|
113
|
+
args?: Record<string, unknown>;
|
|
114
|
+
name: string;
|
|
115
|
+
};
|
|
116
|
+
sinceCheckpoint?: number;
|
|
117
|
+
sinceChunk?: number;
|
|
118
|
+
sinceEpoch?: string;
|
|
119
|
+
topic?: string;
|
|
120
|
+
type: "ack" | "connect" | "shape_subscribe" | "shape_unsubscribe" | "stream" | "subscribe" | "unsubscribe" | "whisper" | "whisper_subscribe" | "whisper_unsubscribe";
|
|
121
|
+
}
|
|
122
|
+
interface RpcRequest {
|
|
123
|
+
args?: Record<string, unknown>;
|
|
124
|
+
functionPath: string;
|
|
125
|
+
}
|
|
126
|
+
interface SocketAttachment {
|
|
127
|
+
admin?: boolean;
|
|
128
|
+
adminBinding?: string;
|
|
129
|
+
clientId?: string;
|
|
130
|
+
connected?: boolean;
|
|
131
|
+
connectionId?: string;
|
|
132
|
+
context?: Record<string, unknown>;
|
|
133
|
+
expiresAt?: number;
|
|
134
|
+
identity?: Record<string, unknown>;
|
|
135
|
+
ip?: string;
|
|
136
|
+
pageDeltas?: boolean;
|
|
137
|
+
shapes?: Record<string, ShapeSubscriptionQuery>;
|
|
138
|
+
subs: Record<string, SubscriptionQuery>;
|
|
139
|
+
userId?: string;
|
|
140
|
+
whispers?: string[];
|
|
141
|
+
}
|
|
142
|
+
interface ResolvedShape {
|
|
143
|
+
columns?: ReadonlyArray<string>;
|
|
144
|
+
effectiveWhere?: WhereInput;
|
|
145
|
+
global?: boolean;
|
|
146
|
+
table: string;
|
|
147
|
+
}
|
|
148
|
+
interface SubscriptionIdentity {
|
|
149
|
+
identity?: Record<string, unknown>;
|
|
150
|
+
ip?: string;
|
|
151
|
+
userId?: string;
|
|
152
|
+
}
|
|
153
|
+
interface ShardSocketLike {
|
|
154
|
+
readonly bufferedAmount?: number;
|
|
155
|
+
close?: (code?: number, reason?: string) => void;
|
|
156
|
+
deserializeAttachment?: () => unknown;
|
|
157
|
+
send: (data: string) => void;
|
|
158
|
+
serializeAttachment?: (value: unknown) => void;
|
|
159
|
+
}
|
|
91
160
|
type AggregateOp = "avg" | "count" | "max" | "min" | "sum";
|
|
92
161
|
interface AggregateIndexDefinitionLike {
|
|
93
162
|
readonly by?: ReadonlyArray<string>;
|
|
@@ -139,6 +208,8 @@ interface ColumnMetaLike {
|
|
|
139
208
|
interface ValidatorLike {
|
|
140
209
|
readonly _meta?: {
|
|
141
210
|
readonly column?: ColumnMetaLike;
|
|
211
|
+
readonly inner?: ValidatorLike;
|
|
212
|
+
readonly tableName?: string;
|
|
142
213
|
};
|
|
143
214
|
readonly kind?: string;
|
|
144
215
|
readonly parse?: (value: unknown) => unknown;
|
|
@@ -279,6 +350,43 @@ interface QueryPage {
|
|
|
279
350
|
page: Record<string, unknown>[];
|
|
280
351
|
splitCursor?: null | string;
|
|
281
352
|
}
|
|
353
|
+
interface RelationEdge {
|
|
354
|
+
readonly array: boolean;
|
|
355
|
+
readonly column: string;
|
|
356
|
+
readonly name: string;
|
|
357
|
+
readonly sourceTable: string;
|
|
358
|
+
readonly targetTable: string;
|
|
359
|
+
}
|
|
360
|
+
interface RelatedStartReference {
|
|
361
|
+
id: string;
|
|
362
|
+
table: string;
|
|
363
|
+
}
|
|
364
|
+
type RelatedStart = (Record<string, unknown> & {
|
|
365
|
+
_id: string;
|
|
366
|
+
}) | RelatedStartReference;
|
|
367
|
+
type RelatedDirection = "both" | "in" | "out";
|
|
368
|
+
interface RelatedOptions {
|
|
369
|
+
cursor?: null | string;
|
|
370
|
+
depth?: number;
|
|
371
|
+
direction?: RelatedDirection;
|
|
372
|
+
edges?: ReadonlyArray<string>;
|
|
373
|
+
limit?: number;
|
|
374
|
+
relationBaseWhere?: (table: string) => undefined | WhereInput;
|
|
375
|
+
relationMask?: RelationMask;
|
|
376
|
+
}
|
|
377
|
+
interface RelatedNode {
|
|
378
|
+
depth: number;
|
|
379
|
+
document: Record<string, unknown>;
|
|
380
|
+
path: ReadonlyArray<string>;
|
|
381
|
+
pathIds: ReadonlyArray<string>;
|
|
382
|
+
score: number;
|
|
383
|
+
table: string;
|
|
384
|
+
}
|
|
385
|
+
interface RelatedPage {
|
|
386
|
+
continueCursor: null | string;
|
|
387
|
+
isDone: boolean;
|
|
388
|
+
nodes: RelatedNode[];
|
|
389
|
+
}
|
|
282
390
|
interface OrderKey {
|
|
283
391
|
direction: SortDirection;
|
|
284
392
|
field: string;
|
|
@@ -418,10 +526,8 @@ interface LifecycleEvent {
|
|
|
418
526
|
shardKey: string;
|
|
419
527
|
userId: string | null;
|
|
420
528
|
}
|
|
421
|
-
interface LifecycleDispatchInfo {
|
|
529
|
+
interface LifecycleDispatchInfo extends SubscriptionIdentity {
|
|
422
530
|
event: LifecycleEvent;
|
|
423
|
-
identity: Record<string, unknown> | undefined;
|
|
424
|
-
userId: string | undefined;
|
|
425
531
|
}
|
|
426
532
|
interface MutationDelta {
|
|
427
533
|
indexKeys?: ReadonlyArray<IndexKeyEntry>;
|
|
@@ -504,6 +610,8 @@ interface DatabaseWriterLike {
|
|
|
504
610
|
rankBefore?: (tableName: string, indexName: string, options: RankBeforeOptions) => Promise<RankBeforeResult>;
|
|
505
611
|
rankPage: (tableName: string, indexName: string, options?: RankPageOptions) => Promise<RankPage>;
|
|
506
612
|
rankPageRows?: (tableName: string, indexName: string, options?: RankPageOptions) => Promise<ShardRankPageResult>;
|
|
613
|
+
related?: (start: RelatedStart, options?: RelatedOptions) => Promise<RelatedPage>;
|
|
614
|
+
relationEdges?: ReadonlyArray<RelationEdge>;
|
|
507
615
|
replace: (id: string, document: Record<string, unknown>, expectedTable?: string, options?: {
|
|
508
616
|
allowExplicitId?: boolean;
|
|
509
617
|
}) => Promise<void>;
|
|
@@ -864,73 +972,6 @@ declare const COMMIT_SEQ_FIELD = "_commitSeq";
|
|
|
864
972
|
declare const migrateCommitSeq: (sql: SqlExec) => void;
|
|
865
973
|
declare const readCommitSeq: (sql: SqlExec) => number;
|
|
866
974
|
declare const allocateCommitSeq: (sql: SqlExec) => number;
|
|
867
|
-
interface SubscriptionQuery {
|
|
868
|
-
args?: Record<string, unknown>;
|
|
869
|
-
functionPath?: string;
|
|
870
|
-
sinceEpoch?: string;
|
|
871
|
-
sinceSeq?: number;
|
|
872
|
-
table?: string;
|
|
873
|
-
}
|
|
874
|
-
interface ShapeSubscriptionQuery {
|
|
875
|
-
args?: Record<string, unknown>;
|
|
876
|
-
name: string;
|
|
877
|
-
sinceEpoch?: string;
|
|
878
|
-
sinceSeq?: number;
|
|
879
|
-
}
|
|
880
|
-
interface SubscriptionEnvelope {
|
|
881
|
-
caps?: string[];
|
|
882
|
-
clientId?: string;
|
|
883
|
-
context?: Record<string, unknown>;
|
|
884
|
-
data?: unknown;
|
|
885
|
-
generation?: number;
|
|
886
|
-
id: string;
|
|
887
|
-
query?: SubscriptionQuery;
|
|
888
|
-
shape?: {
|
|
889
|
-
args?: Record<string, unknown>;
|
|
890
|
-
name: string;
|
|
891
|
-
};
|
|
892
|
-
sinceCheckpoint?: number;
|
|
893
|
-
sinceChunk?: number;
|
|
894
|
-
sinceEpoch?: string;
|
|
895
|
-
topic?: string;
|
|
896
|
-
type: "ack" | "connect" | "shape_subscribe" | "shape_unsubscribe" | "stream" | "subscribe" | "unsubscribe" | "whisper" | "whisper_subscribe" | "whisper_unsubscribe";
|
|
897
|
-
}
|
|
898
|
-
interface RpcRequest {
|
|
899
|
-
args?: Record<string, unknown>;
|
|
900
|
-
functionPath: string;
|
|
901
|
-
}
|
|
902
|
-
interface SocketAttachment {
|
|
903
|
-
admin?: boolean;
|
|
904
|
-
adminBinding?: string;
|
|
905
|
-
clientId?: string;
|
|
906
|
-
connected?: boolean;
|
|
907
|
-
connectionId?: string;
|
|
908
|
-
context?: Record<string, unknown>;
|
|
909
|
-
expiresAt?: number;
|
|
910
|
-
identity?: Record<string, unknown>;
|
|
911
|
-
pageDeltas?: boolean;
|
|
912
|
-
shapes?: Record<string, ShapeSubscriptionQuery>;
|
|
913
|
-
subs: Record<string, SubscriptionQuery>;
|
|
914
|
-
userId?: string;
|
|
915
|
-
whispers?: string[];
|
|
916
|
-
}
|
|
917
|
-
interface ResolvedShape {
|
|
918
|
-
columns?: ReadonlyArray<string>;
|
|
919
|
-
effectiveWhere?: WhereInput;
|
|
920
|
-
global?: boolean;
|
|
921
|
-
table: string;
|
|
922
|
-
}
|
|
923
|
-
interface SubscriptionIdentity {
|
|
924
|
-
identity?: Record<string, unknown>;
|
|
925
|
-
userId?: string;
|
|
926
|
-
}
|
|
927
|
-
interface ShardSocketLike {
|
|
928
|
-
readonly bufferedAmount?: number;
|
|
929
|
-
close?: (code?: number, reason?: string) => void;
|
|
930
|
-
deserializeAttachment?: () => unknown;
|
|
931
|
-
send: (data: string) => void;
|
|
932
|
-
serializeAttachment?: (value: unknown) => void;
|
|
933
|
-
}
|
|
934
975
|
interface CompanionSyncDeps {
|
|
935
976
|
broadcast: (delta: MutationDelta) => void;
|
|
936
977
|
indexKeysFor: (table: string, document?: Record<string, unknown>) => ReadonlyArray<{
|
|
@@ -1267,6 +1308,7 @@ declare const ADMIN_FUNCTIONS: {
|
|
|
1267
1308
|
readonly explainIssue: "__lunora_admin__:explainIssue";
|
|
1268
1309
|
readonly exportShard: "__lunora_admin__:exportShard";
|
|
1269
1310
|
readonly facetColumn: "__lunora_admin__:facetColumn";
|
|
1311
|
+
readonly findRelated: "__lunora_admin__:findRelated";
|
|
1270
1312
|
readonly getAdvisories: "__lunora_admin__:getAdvisories";
|
|
1271
1313
|
readonly getAdvisorProcedures: "__lunora_admin__:getAdvisorProcedures";
|
|
1272
1314
|
readonly getAuditLog: "__lunora_admin__:getAuditLog";
|
|
@@ -1861,6 +1903,13 @@ interface ReadFootprint {
|
|
|
1861
1903
|
declare const createReadFootprint: () => ReadFootprint;
|
|
1862
1904
|
declare const UNVOUCHABLE_DEP = "!unvouchable";
|
|
1863
1905
|
declare const markUnvouchableReads: <T extends object>(facade: T, onRead: ReadFootprint["onRead"] | undefined, methods: ReadonlyArray<string>) => T;
|
|
1906
|
+
declare const RELATED_MAX_DEPTH = 4;
|
|
1907
|
+
declare const RELATED_DEFAULT_LIMIT = 50;
|
|
1908
|
+
declare const RELATED_MAX_LIMIT = 200;
|
|
1909
|
+
declare const RELATED_DEPTH_DECAY = 0.5;
|
|
1910
|
+
declare const deriveRelationEdges: (schema: SchemaLike) => RelationEdge[];
|
|
1911
|
+
type RelationGraphReader = Pick<DatabaseWriterLike, "findMany"> & Pick<Partial<DatabaseWriterLike>, "lookupById">;
|
|
1912
|
+
declare const findRelated: (reader: RelationGraphReader, edges: ReadonlyArray<RelationEdge>, start: RelatedStart, options?: RelatedOptions) => Promise<RelatedPage>;
|
|
1864
1913
|
declare const DEFAULT_MAX_RELATION_KEYS = 5000;
|
|
1865
1914
|
interface RelationExistsMarker {
|
|
1866
1915
|
childWhere: WhereInput;
|
|
@@ -2221,7 +2270,7 @@ interface GuardableSchema {
|
|
|
2221
2270
|
}
|
|
2222
2271
|
type TableOfId = (id: string, expectedTable?: string) => Promise<string | undefined> | string | undefined;
|
|
2223
2272
|
type TablesOfIds = (ids: ReadonlyArray<string>, expectedTable?: string) => Promise<ReadonlyMap<string, string>> | ReadonlyMap<string, string>;
|
|
2224
|
-
declare const guardWriter: <W>(raw: W, schema: GuardableSchema, tableOfId: TableOfId, tablesOfIds?: TablesOfIds) => W;
|
|
2273
|
+
declare const guardWriter: <W>(raw: W, schema: GuardableSchema, tableOfId: TableOfId, tablesOfIds?: TablesOfIds, relationEdges?: ReadonlyArray<RelationEdge>) => W;
|
|
2225
2274
|
declare const SCHEMA_HISTORY_MAX_VERSIONS = 50;
|
|
2226
2275
|
interface SchemaVersionRow {
|
|
2227
2276
|
appliedAt: number;
|
|
@@ -2247,10 +2296,7 @@ declare class ShapeDiffCache {
|
|
|
2247
2296
|
private getOrLoad;
|
|
2248
2297
|
}
|
|
2249
2298
|
declare const createShapeDiffCache: () => ShapeDiffCache;
|
|
2250
|
-
declare const globalShapeReadKey: (resolved: ResolvedShape, identity:
|
|
2251
|
-
identity?: Record<string, unknown>;
|
|
2252
|
-
userId?: string;
|
|
2253
|
-
}) => string | undefined;
|
|
2299
|
+
declare const globalShapeReadKey: (resolved: ResolvedShape, identity: SubscriptionIdentity) => string | undefined;
|
|
2254
2300
|
type ReadShapeCdcKeys = (sql: SqlExec, table: string, sinceSeq: number, upTo: number) => CdcChangeKey[];
|
|
2255
2301
|
declare const buildShapeDiff: (sql: SqlExec, resolved: ResolvedShape, sinceSeq: number, upTo: number, cache: ShapeDiffCache, readKeys?: ReadShapeCdcKeys) => ShapeRowOp[];
|
|
2256
2302
|
interface ShardRunnerOptions {
|
|
@@ -2366,4 +2412,4 @@ interface WhereSqlStrategy<T = SQL> {
|
|
|
2366
2412
|
}
|
|
2367
2413
|
declare const literalInList: (reference: SQL, items: ReadonlyArray<unknown>, negated: boolean) => SQL;
|
|
2368
2414
|
declare const compileWhereSql: <T = SQL>(where: WhereInput | undefined, strategy: WhereSqlStrategy<T>, fragments?: WhereFragments<T>) => T | undefined;
|
|
2369
|
-
export { ADMIN_FUNCTIONS, ADMIN_FUNCTION_PREFIX, AGGREGATE_SQL_FUNCTION, AGG_COUNT, AGG_KEY, AGG_VALUE, AUDIT_LOG_TABLE, type AdvisorProcedure, type AdvisorProceduresResult, type AdvisoriesResult, type AdvisoryFinding, type AggregateIndexDefinitionLike, type AggregateOp, type AggregateOptions, type AggregateResult, type AggregateTally, type AppendAuditEntry, type ApplyOnDeleteOptions$1 as ApplyOnDeleteOptions, type AuditEntry, type AuditLogResult, 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, 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 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 ImportError, type ImportShardAdminArgs, type ImportShardArgs, type ImportShardResult, type IncrementalMaterializeResult, type IndexDefinitionLike, type IndexKeyEntry, type IndexRangeBuilderLike, type KeyRange, type LifecycleDispatchInfo, type LifecycleEvent, MAIL_RETENTION, MAIL_TABLE, MAX_DURABLE_STREAM_BYTES, MAX_DURABLE_STREAM_CHUNKS, MAX_PAGE_SIZE, MAX_SQL_ROWS, type MaskColumnMetadata, type MaskPoliciesResult, type MaterializeResult, type MigrationDirection, type MigrationRunResult, type MigrationStatus, type MigrationStatusRow, type MutationDelta, type NestedWith, NotFoundError, NotUniqueError, type OnDeleteActionLike, type OrderByClause, type OrderByInput, type OrderKey, type OrderKeyConstraints, OwnerRelay, type OwnerRelayFrame, type PaginationOptions, type PitrBookmarkResult, type PitrRestoreArgs, type PitrRestoreResult, type PitrStorage, type PokeFrameMeta, type PromotionState, type PromotionThresholds, QUEUE_TABLE, type QueryArgs, type QueryPage, type QueueMessageOutcome, type QueueMessageRow, type QueueMetadata, type QueuesResult, RANK_TIEBREAK, REACTOR_STATE_TABLE, RELATION_EXISTS_KEY, RELATION_FUNCTION_PREFIX, REPROJECTION_MIGRATION_PREFIX, RLS_UNWRAP_SYMBOL, type RankBeforeOptions, type RankBeforeResult, type RankDirection, type RankIndexDefinitionLike, type RankOptions, type RankPage, type RankPageComputation, type RankPageDeps, type RankPageOptions, type RankPageRow, type RankPageRowKey, type RankResult, type RankSortKeyLike, ReactiveCache, type ReactiveCacheOptions, type ReactorDispatchResult, type ReactorMetadata, type ReactorState, type ReactorStats, type ReactorsResult, type ReadFootprint, type ReadHook, type ReadTablePageOptions, type RecordMailInput, type RecordQueueMessageInput, type RelationDefinitionLike, type RelationExistsMarker, type RelayAttach, type RelayDetach, type RelayFrame, type RelayHost, RelayMember, type RelayPokeDelivery, 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, SCHEMA_HISTORY_MAX_VERSIONS, SEARCH_STATE_TABLE, SHAPE_POKE_CURSOR_TABLE, type SchedulableWorkflowReferenceLike, 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 TransactionHeadroom, TransactionHeadroomTracker, type TransactionLimits, type TransactionSqlLike, type TriggerContextLike, type TriggerDefinitionLike, type TriggerEventLike, type TriggerOpLike, type TriggerTimingLike, type TtlSweepSpec, UNVOUCHABLE_DEP, type ValidatorLike, 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, applyOnDelete, applySelect, archiveCdcSegment, armRestore, assertFlatPredicate, assertNoExplicitUndefined, assertReadonly, assertShapeShardable, assertValidClientId, awaitWsDrain, backfillAggregateIndexes, backfillRankIndexes, backfillSearchIndexes, backfillSearchIndexesForTable, bigintSqlKey, boundingBoxCenter, boundingBoxGeohashes, buildIndexRange, buildPokeFrames, buildReprojectionMigration, buildSeekBeforeWhere, buildSeekWhere, buildSettings, buildShapeDiff, bumpCdcEpoch, cdcCanVouchFor, cdcSeqLeavingRows, cdcTouchesTables, cdcTrimmedError, claimStreamRun, clampPromotionThresholds, clearCapturedMail, clearMemoryTables, clearQueueMessages, coerceAggregateNumber, compactCdcDocs, compileWhereSql, computeRankPage, containsRelationPredicate, countLegacyRows, coveringGeohashes, createCompanionSync, createDependencyTracker, createFanoutCounters, createGlobalPollCounters, createIndexSql, createReadFootprint, createRelayLink, createReplicaLink, createShapeDiffCache, createShapeProbeCounters, createShardCtxDb, createSystemReader, cursorBelowRetainedFloor, decideDurableAttach, decodeBigintSqlKey, decodeCursor, decodeFloat64SqlKey, deleteGlobalShapeSnapshot, deleteGlobalShapeSnapshotsForConnection, deleteShapePokeCursor, deleteShapePokeCursorsForConnection, deleteStreamRun, depKey, diffExternalSource, diffGlobalMembership, distinctValues, encodeAggregateKey, encodeCursor, encodeGeohash, encodePartitionKey, encodeRowsPatch, ensureAuditTable, ensureMailTable, envOptionalPositiveInt, envPositiveInt, equalityPinnedFields, exportShardRows, facetColumn, fanOutScalarCounts, findStorageReferences, finishStreamRun, float64SqlKey, foldAggregateTally, gateReplicaDispatch, geoTableName, globalShapeReadKey, guardWriter, handleReplicaControl, hasTrigger, haversineMeters, importShardRows, indexKeysForRow, isDevEnvironment, isFtsAvailable, isLossyBody, isMemoryTable, isRelationPredicate, isSoftDeleted, isSourceDue, jsonPath, jsonPathSql, keysTouchRanges, liftSourceId, lintReadonlySql, listReactorStates, listTables, literalInList, markUnvouchableReads, matchesRankStaticWhere, matchesStaticWhere, materializeExternalRows, materializeExternalRowsIncremental, memoryTableNames, mergeChangedKeys, mergeWhere, migrateCdcLog, migrateCdcMeta, migrateClientWatermark, migrateCommitSeq, migrateDurableStreams, migrateGlobalShapeSnapshot, migrateIdempotency, migrateReactorState, migrateSearchState, migrateShapePokeCursor, minCdcReplayableSeq, minCdcSeq, minShapePokeCursor, nextPromotionState, normalizeCountArgument, normalizeIdStructurally, normalizeOrderKeys, normalizeSourceDocument, normalizeSourceValue, param, parseExportShardArgs, parseImportShardArgs, planAggregateLookup, pointInBoundingBox, 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, readExternalSourceBaseline, readGlobalShapeSnapshot, readIdempotent, readMigrationStatus, readQueueMessageById, readQueueMessages, readReactorState, readSchemaHistory, readSchemaVersion, readSearchBackfillState, readShapePokeCursor, readStreamChunks, readStreamRun, readTablePage, recordCapturedMail, recordChangedKeys, recordFanoutPass, recordGlobalPollPass, recordQueueMessages, recordSchemaVersion, recordShapeProbePass, relationHooks, relayCountFor, renderSql, reprojectableFields, reprojectionMigrationId, reprojectionTables, resolveRankPartition, resolveRankSeekTuple, resolveRelationPredicates, resolveWith, rowToDocument, runDataMigration, runDrizzle, runExternalSourceTick, runReadonlySql, runRowValidators, runShardMigrations, runSocketPool, runSql, runTriggers, selectExpiredIds, selectExportTables, selectIndexForAggregate, selectIndexForCount, selectIndexForGroupBy, selectMatchingIds, selectShapeMembers, selectShapeRows, serializeSqlValue, shapeRoutingKey, softDeleteScope, sortColumnName, sqliteInList, stableStringify, stableWireKey, subscriptionFrames, subscriptionListDeltas, summarizeFanoutTopics, summarizeSubscriptions, tableColumns, tableFromDepKey, throwingScheduler, tiebreakDirectionFor, trimCdcChanges, trimIdempotent, trimStreamRuns, tryRowToDocument, trySendFrame, unionAll, uniqueIndexFields, validateImportRow, writeCdcArchivedThrough, writeGlobalShapeSnapshot, writeIdempotent, writeReactorState, writeSearchBackfillState, writeShapePokeCursor, writeShapePokeCursors, writeTouchesMemo };
|
|
2415
|
+
export { ADMIN_FUNCTIONS, ADMIN_FUNCTION_PREFIX, AGGREGATE_SQL_FUNCTION, AGG_COUNT, AGG_KEY, AGG_VALUE, AUDIT_LOG_TABLE, type AdvisorProcedure, type AdvisorProceduresResult, type AdvisoriesResult, type AdvisoryFinding, type AggregateIndexDefinitionLike, type AggregateOp, type AggregateOptions, type AggregateResult, type AggregateTally, type AppendAuditEntry, type ApplyOnDeleteOptions$1 as ApplyOnDeleteOptions, type AuditEntry, type AuditLogResult, 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, 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 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 ImportError, type ImportShardAdminArgs, type ImportShardArgs, type ImportShardResult, type IncrementalMaterializeResult, type IndexDefinitionLike, type IndexKeyEntry, type IndexRangeBuilderLike, type KeyRange, type LifecycleDispatchInfo, type LifecycleEvent, MAIL_RETENTION, MAIL_TABLE, MAX_DURABLE_STREAM_BYTES, MAX_DURABLE_STREAM_CHUNKS, MAX_PAGE_SIZE, MAX_SQL_ROWS, type MaskColumnMetadata, type MaskPoliciesResult, type MaterializeResult, type MigrationDirection, type MigrationRunResult, type MigrationStatus, type MigrationStatusRow, type MutationDelta, type NestedWith, NotFoundError, NotUniqueError, type OnDeleteActionLike, type OrderByClause, type OrderByInput, type OrderKey, type OrderKeyConstraints, OwnerRelay, type OwnerRelayFrame, type PaginationOptions, type PitrBookmarkResult, type PitrRestoreArgs, type PitrRestoreResult, type PitrStorage, type PokeFrameMeta, type PromotionState, type PromotionThresholds, QUEUE_TABLE, type QueryArgs, type QueryPage, type QueueMessageOutcome, type QueueMessageRow, type QueueMetadata, type QueuesResult, RANK_TIEBREAK, REACTOR_STATE_TABLE, RELATED_DEFAULT_LIMIT, RELATED_DEPTH_DECAY, RELATED_MAX_DEPTH, RELATED_MAX_LIMIT, RELATION_EXISTS_KEY, RELATION_FUNCTION_PREFIX, REPROJECTION_MIGRATION_PREFIX, RLS_UNWRAP_SYMBOL, type RankBeforeOptions, type RankBeforeResult, type RankDirection, type RankIndexDefinitionLike, type RankOptions, type RankPage, type RankPageComputation, type RankPageDeps, type RankPageOptions, type RankPageRow, type RankPageRowKey, type RankResult, type RankSortKeyLike, ReactiveCache, type ReactiveCacheOptions, type 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 RelayAttach, type RelayDetach, type RelayFrame, type RelayHost, RelayMember, type RelayPokeDelivery, 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, SCHEMA_HISTORY_MAX_VERSIONS, SEARCH_STATE_TABLE, SHAPE_POKE_CURSOR_TABLE, type SchedulableWorkflowReferenceLike, 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 TransactionHeadroom, TransactionHeadroomTracker, type TransactionLimits, type TransactionSqlLike, type TriggerContextLike, type TriggerDefinitionLike, type TriggerEventLike, type TriggerOpLike, type TriggerTimingLike, type TtlSweepSpec, UNVOUCHABLE_DEP, type ValidatorLike, 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, applyOnDelete, applySelect, archiveCdcSegment, armRestore, assertFlatPredicate, assertNoExplicitUndefined, assertReadonly, assertShapeShardable, assertValidClientId, awaitWsDrain, backfillAggregateIndexes, backfillRankIndexes, backfillSearchIndexes, backfillSearchIndexesForTable, bigintSqlKey, boundingBoxCenter, boundingBoxGeohashes, buildIndexRange, buildPokeFrames, buildReprojectionMigration, buildSeekBeforeWhere, buildSeekWhere, buildSettings, buildShapeDiff, bumpCdcEpoch, cdcCanVouchFor, cdcSeqLeavingRows, cdcTouchesTables, cdcTrimmedError, claimStreamRun, clampPromotionThresholds, clearCapturedMail, clearMemoryTables, clearQueueMessages, coerceAggregateNumber, compactCdcDocs, compileWhereSql, computeRankPage, containsRelationPredicate, countLegacyRows, coveringGeohashes, createCompanionSync, createDependencyTracker, createFanoutCounters, createGlobalPollCounters, createIndexSql, createReadFootprint, createRelayLink, createReplicaLink, createShapeDiffCache, createShapeProbeCounters, createShardCtxDb, createSystemReader, cursorBelowRetainedFloor, decideDurableAttach, decodeBigintSqlKey, decodeCursor, decodeFloat64SqlKey, deleteGlobalShapeSnapshot, deleteGlobalShapeSnapshotsForConnection, deleteShapePokeCursor, deleteShapePokeCursorsForConnection, deleteStreamRun, depKey, deriveRelationEdges, diffExternalSource, diffGlobalMembership, distinctValues, encodeAggregateKey, encodeCursor, encodeGeohash, encodePartitionKey, encodeRowsPatch, ensureAuditTable, ensureMailTable, envOptionalPositiveInt, envPositiveInt, equalityPinnedFields, exportShardRows, facetColumn, fanOutScalarCounts, findRelated, findStorageReferences, finishStreamRun, float64SqlKey, foldAggregateTally, gateReplicaDispatch, geoTableName, globalShapeReadKey, guardWriter, handleReplicaControl, hasTrigger, haversineMeters, importShardRows, indexKeysForRow, isDevEnvironment, isFtsAvailable, isLossyBody, isMemoryTable, isRelationPredicate, isSoftDeleted, isSourceDue, jsonPath, jsonPathSql, keysTouchRanges, liftSourceId, lintReadonlySql, listReactorStates, listTables, literalInList, markUnvouchableReads, matchesRankStaticWhere, matchesStaticWhere, materializeExternalRows, materializeExternalRowsIncremental, memoryTableNames, mergeChangedKeys, mergeWhere, migrateCdcLog, migrateCdcMeta, migrateClientWatermark, migrateCommitSeq, migrateDurableStreams, migrateGlobalShapeSnapshot, migrateIdempotency, migrateReactorState, migrateSearchState, migrateShapePokeCursor, minCdcReplayableSeq, minCdcSeq, minShapePokeCursor, nextPromotionState, normalizeCountArgument, normalizeIdStructurally, normalizeOrderKeys, normalizeSourceDocument, normalizeSourceValue, param, parseExportShardArgs, parseImportShardArgs, planAggregateLookup, pointInBoundingBox, 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, readExternalSourceBaseline, readGlobalShapeSnapshot, readIdempotent, readMigrationStatus, readQueueMessageById, readQueueMessages, readReactorState, readSchemaHistory, readSchemaVersion, readSearchBackfillState, readShapePokeCursor, readStreamChunks, readStreamRun, readTablePage, recordCapturedMail, recordChangedKeys, recordFanoutPass, recordGlobalPollPass, recordQueueMessages, recordSchemaVersion, recordShapeProbePass, relationHooks, relayCountFor, renderSql, reprojectableFields, reprojectionMigrationId, reprojectionTables, resolveRankPartition, resolveRankSeekTuple, resolveRelationPredicates, resolveWith, rowToDocument, runDataMigration, runDrizzle, runExternalSourceTick, runReadonlySql, runRowValidators, runShardMigrations, runSocketPool, runSql, runTriggers, selectExpiredIds, selectExportTables, selectIndexForAggregate, selectIndexForCount, selectIndexForGroupBy, selectMatchingIds, selectShapeMembers, selectShapeRows, serializeSqlValue, shapeRoutingKey, softDeleteScope, sortColumnName, sqliteInList, stableStringify, stableWireKey, subscriptionFrames, subscriptionListDeltas, summarizeFanoutTopics, summarizeSubscriptions, tableColumns, tableFromDepKey, throwingScheduler, tiebreakDirectionFor, trimCdcChanges, trimIdempotent, trimStreamRuns, tryRowToDocument, trySendFrame, unionAll, uniqueIndexFields, validateImportRow, 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 n,selectExportTables as i,validateImportRow as s}from"./packem_shared/exportShardRows-D_upYHRQ.mjs";import{AGGREGATE_SQL_FUNCTION as c,aggregateSqlFunction as m,matchesStaticWhere as d,normalizeCountArgument as p,throwingScheduler as S}from"./packem_shared/AGGREGATE_SQL_FUNCTION-DDEoMnJR.mjs";import{aggregateTableName as f,coerceAggregateNumber as h,encodeAggregateKey as x,foldAggregateTally as C,readAggregateValue as T}from"./packem_shared/aggregateTableName-C7o-gpms.mjs";import{CountRlsUnsupportedError as R,mergeWhere as g,planAggregateLookup as A,selectIndexForAggregate as _,selectIndexForCount as I,selectIndexForGroupBy as b}from"./packem_shared/CountRlsUnsupportedError-BvsDqfO2.mjs";import{AUDIT_LOG_TABLE as P,appendAuditEntry as y,ensureAuditTable as D,readAuditLog as M}from"./packem_shared/AUDIT_LOG_TABLE-ONxmEAIz.mjs";import{NotUniqueError as F,assertNoExplicitUndefined as O,assertValidClientId as k,createShardCtxDb as B,normalizeIdStructurally as G}from"./packem_shared/NotUniqueError-DqlL1ViB.mjs";import{backfillAggregateIndexes as U,backfillRankIndexes as K,backfillSearchIndexes as w,backfillSearchIndexesForTable as v}from"./packem_shared/backfillAggregateIndexes-BG5-SC1q.mjs";import{CDC_LOG_TABLE as X,CDC_LOG_TABLE_SEQ_INDEX as H,CDC_META_TABLE as z,appendCdcChange as V,applyCdcChanges as Q,bumpCdcEpoch as Y,cdcCanVouchFor as j,cdcSeqLeavingRows as J,cdcTouchesTables as Z,cdcTrimmedError as $,compactCdcDocs as ee,cursorBelowRetainedFloor as re,migrateCdcLog as oe,migrateCdcMeta as ae,minCdcReplayableSeq as te,minCdcSeq as ne,readCdcChangeKeys as ie,readCdcChanges as se,readCdcCursor as le,readCdcEpoch as ce,trimCdcChanges as me}from"./packem_shared/CDC_LOG_TABLE-vVheEulD.mjs";import{archiveCdcSegment as pe,readArchivedCdcChanges as Se,readCdcArchivedThrough as ue,writeCdcArchivedThrough as fe}from"./packem_shared/archiveCdcSegment-DU4uzDFQ.mjs";import{CLIENT_WATERMARK_TABLE as xe,advanceClientWatermark as Ce,migrateClientWatermark as Te,readClientWatermark as Ee}from"./packem_shared/CLIENT_WATERMARK_TABLE-CRnrAnJ2.mjs";import{COMMIT_SEQ_FIELD as ge,COMMIT_SEQ_TABLE as Ae,allocateCommitSeq as _e,migrateCommitSeq as Ie,readCommitSeq as be}from"./packem_shared/COMMIT_SEQ_FIELD-BUdOMG5y.mjs";import{c as Pe}from"./packem_shared/ctx-db-companions-w-CfeOda.mjs";import{GLOBAL_SHAPE_SNAPSHOT_TABLE as De,deleteGlobalShapeSnapshot as Me,deleteGlobalShapeSnapshotsForConnection as Ne,migrateGlobalShapeSnapshot as Fe,readGlobalShapeSnapshot as Oe,writeGlobalShapeSnapshot as ke}from"./packem_shared/GLOBAL_SHAPE_SNAPSHOT_TABLE-DSA6mzyx.mjs";import{IDEMPOTENCY_TABLE as Ge,migrateIdempotency as qe,readIdempotent as Ue,trimIdempotent as Ke,writeIdempotent as we}from"./packem_shared/IDEMPOTENCY_TABLE-DOpm_oMF.mjs";import{clearMemoryTables as We,isMemoryTable as Xe,memoryTableNames as He}from"./packem_shared/clearMemoryTables-BGbmag2i.mjs";import{computeRankPage as Ve,resolveRankSeekTuple as Qe}from"./packem_shared/computeRankPage-DsQ16o1z.mjs";import{S as je,m as Je,r as Ze,w as $e}from"./packem_shared/ctx-db-search-state-ruTuCsxa.mjs";import{SHAPE_POKE_CURSOR_TABLE as rr,deleteShapePokeCursor as or,deleteShapePokeCursorsForConnection as ar,migrateShapePokeCursor as tr,minShapePokeCursor as nr,readShapePokeCursor as ir,writeShapePokeCursor as sr,writeShapePokeCursors as lr}from"./packem_shared/SHAPE_POKE_CURSOR_TABLE-ByJVDHds.mjs";import{selectShapeMembers as mr,selectShapeRows as dr}from"./packem_shared/selectShapeMembers-CCZyZggM.mjs";import{DATA_MIGRATION_STATE_TABLE as Sr,readMigrationStatus as ur,runDataMigration as fr}from"./packem_shared/DATA_MIGRATION_STATE_TABLE-BNMWxRzv.mjs";import{SCAN_DEP as xr,createDependencyTracker as Cr,depKey as Tr,tableFromDepKey as Er}from"./packem_shared/SCAN_DEP-D7qE3iUe.mjs";import{runDrizzle as gr,runSql as Ar}from"./packem_shared/runDrizzle-2ULFQR_k.mjs";import{A as Ir,a as br,b as Lr,D as Pr,c as yr,d as Dr,g as Mr,i as Nr,j as Fr,e as Or,q as kr,f as Br,r as Gr,t as qr,h as Ur}from"./packem_shared/do-sql-Dvj8Yl5N.mjs";import{param as wr,renderSql as vr,sqliteInList as Wr,unionAll as Xr}from"./packem_shared/param-DlozcSQu.mjs";import{appendStreamChunk as zr,claimStreamRun as Vr,deleteStreamRun as Qr,finishStreamRun as Yr,migrateDurableStreams as jr,readStreamChunks as Jr,readStreamRun as Zr,trimStreamRuns as $r}from"./packem_shared/appendStreamChunk-C1Ok4b6J.mjs";import{DurableStreamRunner as ro,MAX_DURABLE_STREAM_BYTES as oo,MAX_DURABLE_STREAM_CHUNKS as ao,decideDurableAttach as to}from"./packem_shared/DurableStreamRunner-rTYp4v03.mjs";import{envOptionalPositiveInt as io,envPositiveInt as so}from"./packem_shared/envOptionalPositiveInt-D2pY-c64.mjs";import{diffExternalSource as co}from"./packem_shared/diffExternalSource-DgDJhslq.mjs";import{liftSourceId as po,normalizeSourceDocument as So,normalizeSourceValue as uo}from"./packem_shared/liftSourceId-CA3ENhXj.mjs";import{materializeExternalRows as ho,materializeExternalRowsIncremental as xo,readExternalSourceBaseline as Co,runExternalSourceTick as To}from"./packem_shared/materializeExternalRows-iEVQKOKT.mjs";import{isSoftDeleted as Ro,isSourceDue as go,pullExternalSourceIncrementalTick as Ao,pullExternalSourceTick as _o}from"./packem_shared/isSoftDeleted-CYf6ijO3.mjs";import{GEO_DEFAULT_PRECISION as bo,boundingBoxCenter as Lo,boundingBoxGeohashes as Po,coveringGeohashes as yo,encodeGeohash as Do,haversineMeters as Mo,pointInBoundingBox as No}from"./packem_shared/GEO_DEFAULT_PRECISION-CqpQZ-J_.mjs";import{default as Oo}from"./packem_shared/GlobalPollTick-BNK4o-XT.mjs";import{ADMIN_FUNCTIONS as Bo,ADMIN_FUNCTION_PREFIX as Go,DEFAULT_FANOUT_TOPIC_LIMIT as qo,FLAGS_FUNCTION_PREFIX as Uo,MAX_PAGE_SIZE as Ko,RELATION_FUNCTION_PREFIX as wo,createFanoutCounters as vo,createGlobalPollCounters as Wo,createShapeProbeCounters as Xo,facetColumn as Ho,findStorageReferences as zo,listTables as Vo,readTablePage as Qo,recordFanoutPass as Yo,recordGlobalPollPass as jo,recordShapeProbePass as Jo,selectMatchingIds as Zo,summarizeFanoutTopics as $o,summarizeSubscriptions as ea}from"./packem_shared/ADMIN_FUNCTIONS-B-nIrmAV.mjs";import{MAIL_RETENTION as oa,MAIL_TABLE as aa,clearCapturedMail as ta,ensureMailTable as na,readCapturedMail as ia,recordCapturedMail as sa}from"./packem_shared/MAIL_RETENTION-DGAQTHHs.mjs";import{NotFoundError as ca}from"./packem_shared/NotFoundError-BhF7FeFr.mjs";import{armRestore as da,readBookmark as pa}from"./packem_shared/armRestore-Bu1_8SUa.mjs";import{CURSOR_PREFIX as ua,applySelect as fa,buildSeekBeforeWhere as ha,buildSeekWhere as xa,decodeCursor as Ca,encodeCursor as Ta,equalityPinnedFields as Ea,normalizeOrderKeys as Ra,softDeleteScope as ga,tiebreakDirectionFor as Aa,uniqueIndexFields as _a}from"./packem_shared/CURSOR_PREFIX-Bn8SFoGd.mjs";import{QUEUE_TABLE as ba,clearQueueMessages as La,isLossyBody as Pa,readQueueMessageById as ya,readQueueMessages as Da,recordQueueMessages as Ma}from"./packem_shared/QUEUE_TABLE-s7QJZvBz.mjs";import{RANK_TIEBREAK as Fa,encodePartitionKey as Oa,matchesRankStaticWhere as ka,rankKeyFromDoc as Ba,rankPivotConditionSql as Ga,rankTableName as qa,resolveRankPartition as Ua,sortColumnName as Ka}from"./packem_shared/RANK_TIEBREAK-BXDiMmkH.mjs";import{ReactiveCache as va,reactiveCacheKey as Wa}from"./packem_shared/ReactiveCache-CzeUmTTN.mjs";import{REACTOR_STATE_TABLE as Ha,listReactorStates as za,migrateReactorState as Va,reactorNeedsRun as Qa,readReactorState as Ya,writeReactorState as ja}from"./packem_shared/REACTOR_STATE_TABLE-QPRFyxMS.mjs";import{UNVOUCHABLE_DEP as Za,createReadFootprint as $a,markUnvouchableReads as et}from"./packem_shared/UNVOUCHABLE_DEP-C68htACn.mjs";import{buildIndexRange as ot,indexKeysForRow as at,keysTouchRanges as tt}from"./packem_shared/buildIndexRange-NtciKq3M.mjs";import{DEFAULT_MAX_RELATION_KEYS as it,assertFlatPredicate as st,assertShapeShardable as lt,containsRelationPredicate as ct,isRelationPredicate as mt,resolveRelationPredicates as dt}from"./packem_shared/DEFAULT_MAX_RELATION_KEYS-XESc7TiB.mjs";import{applyOnDelete as St,distinctValues as ut,fanOutScalarCounts as ft,relationHooks as ht,resolveWith as xt,runRowValidators as Ct}from"./packem_shared/applyOnDelete-7JZ4vR9r.mjs";import{DEFAULT_PROMOTION_THRESHOLDS as Et,clampPromotionThresholds as Rt,nextPromotionState as gt,relayCountFor as At,shapeRoutingKey as _t}from"./packem_shared/DEFAULT_PROMOTION_THRESHOLDS-Bfx7KakS.mjs";import{DEFAULT_MAX_RELAYS as bt,OwnerRelay as Lt,RelayMember as Pt,createRelayLink as yt}from"./packem_shared/DEFAULT_MAX_RELAYS-DDOVsK5A.mjs";import{createReplicaLink as Mt,gateReplicaDispatch as Nt,handleReplicaControl as Ft}from"./packem_shared/createReplicaLink-Bo4IWADY.mjs";import{buildReprojectionMigration as kt,countLegacyRows as Bt,reprojectableFields as Gt,reprojectionTables as qt}from"./packem_shared/buildReprojectionMigration-Coeg-J0M.mjs";import{RLS_UNWRAP_SYMBOL as Kt,RlsRequiredError as wt,guardWriter as vt}from"./packem_shared/RLS_UNWRAP_SYMBOL-BF5gi64E.mjs";import{SCHEMA_HISTORY_MAX_VERSIONS as Xt,readSchemaHistory as Ht,readSchemaVersion as zt,recordSchemaVersion as Vt}from"./packem_shared/SCHEMA_HISTORY_MAX_VERSIONS-BluIj2s-.mjs";import{serializeSqlValue as Yt}from"./packem_shared/serializeSqlValue-CjbhIHjJ.mjs";import{buildSettings as Jt,isDevEnvironment as Zt,readDeployInfo as $t}from"./packem_shared/buildSettings-DC3VeQ0H.mjs";import{buildShapeDiff as rn}from"./packem_shared/buildShapeDiff-WSoMs1_h.mjs";import{ShapeDiffCache as an,createShapeDiffCache as tn,globalShapeReadKey as nn}from"./packem_shared/ShapeDiffCache-gdaILV5E.mjs";import{buildPokeFrames as ln,diffGlobalMembership as cn,encodeRowsPatch as mn,projectColumns as dn}from"./packem_shared/buildPokeFrames-BBE6J91z.mjs";import{ShardRunner as Sn}from"./packem_shared/ShardRunner-C9p5DVOx.mjs";import{runSocketPool as fn}from"./packem_shared/runSocketPool-CZJ2X9cF.mjs";import{MAX_SQL_ROWS as xn,assertReadonly as Cn,lintReadonlySql as Tn,runReadonlySql as En}from"./packem_shared/MAX_SQL_ROWS-RvXZ7S7f.mjs";import{B as gn,b as An,d as _n,a as In,f as bn}from"./packem_shared/sql-projection-BB2lCbYV.mjs";import{awaitWsDrain as Pn,subscriptionFrames as yn,subscriptionListDeltas as Dn,trySendFrame as Mn}from"./packem_shared/awaitWsDrain-apizgmKY.mjs";import{mergeChangedKeys as Fn,recordChangedKeys as On,writeTouchesMemo as kn}from"./packem_shared/mergeChangedKeys-CPw4EamV.mjs";import{createSystemReader as Gn}from"./packem_shared/createSystemReader-DcDLFfC-.mjs";import{ConflictError as Un}from"./packem_shared/ConflictError-C8GtJmjS.mjs";import{DEFAULT_TRANSACTION_LIMITS as wn,TransactionHeadroomTracker as vn}from"./packem_shared/DEFAULT_TRANSACTION_LIMITS-DDGk9ebh.mjs";import{hasTrigger as Xn,runTriggers as Hn}from"./packem_shared/hasTrigger-CjlwI4le.mjs";import{selectExpiredIds as Vn}from"./packem_shared/selectExpiredIds-CKOUTIHn.mjs";import{c as Yn,l as jn}from"./packem_shared/where-sql-x1YKldcq.mjs";import{RELATION_EXISTS_KEY as Zn}from"./packem_shared/RELATION_EXISTS_KEY-CFUhnZSZ.mjs";import{REPROJECTION_MIGRATION_PREFIX as ei,reprojectionMigrationId as ri}from"./packem_shared/REPROJECTION_MIGRATION_PREFIX-Czcb6_mO.mjs";import{quoteIdentifier as ai}from"./packem_shared/quoteIdentifier-CObIFRhb.mjs";import{runShardMigrations as ni}from"./packem_shared/runShardMigrations-CeT_SVrI.mjs";import{stableStringify as si}from"./packem_shared/stableStringify-DibjylKD.mjs";import{stableWireKey as ci}from"./packem_shared/stableWireKey-D2US4k_J.mjs";export{Bo as ADMIN_FUNCTIONS,Go as ADMIN_FUNCTION_PREFIX,c as AGGREGATE_SQL_FUNCTION,Ir as AGG_COUNT,br as AGG_KEY,Lr as AGG_VALUE,P as AUDIT_LOG_TABLE,gn as BIGINT_KEY_DIGITS,X as CDC_LOG_TABLE,H as CDC_LOG_TABLE_SEQ_INDEX,z as CDC_META_TABLE,xe as CLIENT_WATERMARK_TABLE,ge as COMMIT_SEQ_FIELD,Ae as COMMIT_SEQ_TABLE,ua as CURSOR_PREFIX,Un as ConflictError,R as CountRlsUnsupportedError,Sr as DATA_MIGRATION_STATE_TABLE,qo as DEFAULT_FANOUT_TOPIC_LIMIT,it as DEFAULT_MAX_RELATION_KEYS,bt as DEFAULT_MAX_RELAYS,Et as DEFAULT_PROMOTION_THRESHOLDS,wn as DEFAULT_TRANSACTION_LIMITS,Pr as DOC_COLUMN,ro as DurableStreamRunner,Uo as FLAGS_FUNCTION_PREFIX,bo as GEO_DEFAULT_PRECISION,De as GLOBAL_SHAPE_SNAPSHOT_TABLE,Oo as GlobalPollTick,Ge as IDEMPOTENCY_TABLE,oa as MAIL_RETENTION,aa as MAIL_TABLE,oo as MAX_DURABLE_STREAM_BYTES,ao as MAX_DURABLE_STREAM_CHUNKS,Ko as MAX_PAGE_SIZE,xn as MAX_SQL_ROWS,ca as NotFoundError,F as NotUniqueError,Lt as OwnerRelay,ba as QUEUE_TABLE,Fa as RANK_TIEBREAK,Ha as REACTOR_STATE_TABLE,Zn as RELATION_EXISTS_KEY,wo as RELATION_FUNCTION_PREFIX,ei as REPROJECTION_MIGRATION_PREFIX,Kt as RLS_UNWRAP_SYMBOL,va as ReactiveCache,Pt as RelayMember,wt as RlsRequiredError,xr as SCAN_DEP,Xt as SCHEMA_HISTORY_MAX_VERSIONS,je as SEARCH_STATE_TABLE,rr as SHAPE_POKE_CURSOR_TABLE,an as ShapeDiffCache,Sn as ShardRunner,vn as TransactionHeadroomTracker,Za as UNVOUCHABLE_DEP,Ce as advanceClientWatermark,yr as aggUpsertSql,m as aggregateSqlFunction,f as aggregateTableName,_e as allocateCommitSeq,y as appendAuditEntry,V as appendCdcChange,zr as appendStreamChunk,Q as applyCdcChanges,St as applyOnDelete,fa as applySelect,pe as archiveCdcSegment,da as armRestore,st as assertFlatPredicate,O as assertNoExplicitUndefined,Cn as assertReadonly,lt as assertShapeShardable,k as assertValidClientId,Pn as awaitWsDrain,U as backfillAggregateIndexes,K as backfillRankIndexes,w as backfillSearchIndexes,v as backfillSearchIndexesForTable,An as bigintSqlKey,Lo as boundingBoxCenter,Po as boundingBoxGeohashes,ot as buildIndexRange,ln as buildPokeFrames,kt as buildReprojectionMigration,ha as buildSeekBeforeWhere,xa as buildSeekWhere,Jt as buildSettings,rn as buildShapeDiff,Y as bumpCdcEpoch,j as cdcCanVouchFor,J as cdcSeqLeavingRows,Z as cdcTouchesTables,$ as cdcTrimmedError,Vr as claimStreamRun,Rt as clampPromotionThresholds,ta as clearCapturedMail,We as clearMemoryTables,La as clearQueueMessages,h as coerceAggregateNumber,ee as compactCdcDocs,Yn as compileWhereSql,Ve as computeRankPage,ct as containsRelationPredicate,Bt as countLegacyRows,yo as coveringGeohashes,Pe as createCompanionSync,Cr as createDependencyTracker,vo as createFanoutCounters,Wo as createGlobalPollCounters,Dr as createIndexSql,$a as createReadFootprint,yt as createRelayLink,Mt as createReplicaLink,tn as createShapeDiffCache,Xo as createShapeProbeCounters,B as createShardCtxDb,Gn as createSystemReader,re as cursorBelowRetainedFloor,to as decideDurableAttach,_n as decodeBigintSqlKey,Ca as decodeCursor,In as decodeFloat64SqlKey,Me as deleteGlobalShapeSnapshot,Ne as deleteGlobalShapeSnapshotsForConnection,or as deleteShapePokeCursor,ar as deleteShapePokeCursorsForConnection,Qr as deleteStreamRun,Tr as depKey,co as diffExternalSource,cn as diffGlobalMembership,ut as distinctValues,x as encodeAggregateKey,Ta as encodeCursor,Do as encodeGeohash,Oa as encodePartitionKey,mn as encodeRowsPatch,D as ensureAuditTable,na as ensureMailTable,io as envOptionalPositiveInt,so as envPositiveInt,Ea as equalityPinnedFields,o as exportShardRows,Ho as facetColumn,ft as fanOutScalarCounts,zo as findStorageReferences,Yr as finishStreamRun,bn as float64SqlKey,C as foldAggregateTally,Nt as gateReplicaDispatch,Mr as geoTableName,nn as globalShapeReadKey,vt as guardWriter,Ft as handleReplicaControl,Xn as hasTrigger,Mo as haversineMeters,a as importShardRows,at as indexKeysForRow,Zt as isDevEnvironment,Nr as isFtsAvailable,Pa as isLossyBody,Xe as isMemoryTable,mt as isRelationPredicate,Ro as isSoftDeleted,go as isSourceDue,Fr as jsonPath,Or as jsonPathSql,tt as keysTouchRanges,po as liftSourceId,Tn as lintReadonlySql,za as listReactorStates,Vo as listTables,jn as literalInList,et as markUnvouchableReads,ka as matchesRankStaticWhere,d as matchesStaticWhere,ho as materializeExternalRows,xo as materializeExternalRowsIncremental,He as memoryTableNames,Fn as mergeChangedKeys,g as mergeWhere,oe as migrateCdcLog,ae as migrateCdcMeta,Te as migrateClientWatermark,Ie as migrateCommitSeq,jr as migrateDurableStreams,Fe as migrateGlobalShapeSnapshot,qe as migrateIdempotency,Va as migrateReactorState,Je as migrateSearchState,tr as migrateShapePokeCursor,te as minCdcReplayableSeq,ne as minCdcSeq,nr as minShapePokeCursor,gt as nextPromotionState,p as normalizeCountArgument,G as normalizeIdStructurally,Ra as normalizeOrderKeys,So as normalizeSourceDocument,uo as normalizeSourceValue,wr as param,t as parseExportShardArgs,n as parseImportShardArgs,A as planAggregateLookup,No as pointInBoundingBox,dn as projectColumns,Ao as pullExternalSourceIncrementalTick,_o as pullExternalSourceTick,kr as qualifiedJsonPath,Br as qualifiedJsonPathSql,ai as quoteIdentifier,Ba as rankKeyFromDoc,Ga as rankPivotConditionSql,qa as rankTableName,Wa as reactiveCacheKey,Qa as reactorNeedsRun,T as readAggregateValue,Se as readArchivedCdcChanges,M as readAuditLog,pa as readBookmark,ia as readCapturedMail,ue as readCdcArchivedThrough,ie as readCdcChangeKeys,se as readCdcChanges,le as readCdcCursor,ce as readCdcEpoch,Ee as readClientWatermark,be as readCommitSeq,$t as readDeployInfo,Co as readExternalSourceBaseline,Oe as readGlobalShapeSnapshot,Ue as readIdempotent,ur as readMigrationStatus,ya as readQueueMessageById,Da as readQueueMessages,Ya as readReactorState,Ht as readSchemaHistory,zt as readSchemaVersion,Ze as readSearchBackfillState,ir as readShapePokeCursor,Jr as readStreamChunks,Zr as readStreamRun,Qo as readTablePage,sa as recordCapturedMail,On as recordChangedKeys,Yo as recordFanoutPass,jo as recordGlobalPollPass,Ma as recordQueueMessages,Vt as recordSchemaVersion,Jo as recordShapeProbePass,ht as relationHooks,At as relayCountFor,vr as renderSql,Gt as reprojectableFields,ri as reprojectionMigrationId,qt as reprojectionTables,Ua as resolveRankPartition,Qe as resolveRankSeekTuple,dt as resolveRelationPredicates,xt as resolveWith,Gr as rowToDocument,fr as runDataMigration,gr as runDrizzle,To as runExternalSourceTick,En as runReadonlySql,Ct as runRowValidators,ni as runShardMigrations,fn as runSocketPool,Ar as runSql,Hn as runTriggers,Vn as selectExpiredIds,i as selectExportTables,_ as selectIndexForAggregate,I as selectIndexForCount,b as selectIndexForGroupBy,Zo as selectMatchingIds,mr as selectShapeMembers,dr as selectShapeRows,Yt as serializeSqlValue,_t as shapeRoutingKey,ga as softDeleteScope,Ka as sortColumnName,Wr as sqliteInList,si as stableStringify,ci as stableWireKey,yn as subscriptionFrames,Dn as subscriptionListDeltas,$o as summarizeFanoutTopics,ea as summarizeSubscriptions,qr as tableColumns,Er as tableFromDepKey,S as throwingScheduler,Aa as tiebreakDirectionFor,me as trimCdcChanges,Ke as trimIdempotent,$r as trimStreamRuns,Ur as tryRowToDocument,Mn as trySendFrame,Xr as unionAll,_a as uniqueIndexFields,s as validateImportRow,fe as writeCdcArchivedThrough,ke as writeGlobalShapeSnapshot,we as writeIdempotent,ja as writeReactorState,$e as writeSearchBackfillState,sr as writeShapePokeCursor,lr as writeShapePokeCursors,kn as writeTouchesMemo};
|
|
1
|
+
import{exportShardRows as o,importShardRows as a,parseExportShardArgs as t,parseImportShardArgs as n,selectExportTables as i,validateImportRow as l}from"./packem_shared/exportShardRows-D_upYHRQ.mjs";import{AGGREGATE_SQL_FUNCTION as m,aggregateSqlFunction as c,matchesStaticWhere as d,normalizeCountArgument as p,throwingScheduler as S}from"./packem_shared/AGGREGATE_SQL_FUNCTION-DDEoMnJR.mjs";import{aggregateTableName as f,coerceAggregateNumber as E,encodeAggregateKey as T,foldAggregateTally as h,readAggregateValue as x}from"./packem_shared/aggregateTableName-C7o-gpms.mjs";import{CountRlsUnsupportedError as R,mergeWhere as A,planAggregateLookup as g,selectIndexForAggregate as _,selectIndexForCount as I,selectIndexForGroupBy as b}from"./packem_shared/CountRlsUnsupportedError-BvsDqfO2.mjs";import{AUDIT_LOG_TABLE as D,appendAuditEntry as P,ensureAuditTable as M,readAuditLog as y}from"./packem_shared/AUDIT_LOG_TABLE-ONxmEAIz.mjs";import{NotUniqueError as N,assertNoExplicitUndefined as O,assertValidClientId as k,createShardCtxDb as B,normalizeIdStructurally as G}from"./packem_shared/NotUniqueError-BMom69SD.mjs";import{backfillAggregateIndexes as q,backfillRankIndexes as K,backfillSearchIndexes as w,backfillSearchIndexesForTable as v}from"./packem_shared/backfillAggregateIndexes-BG5-SC1q.mjs";import{CDC_LOG_TABLE as X,CDC_LOG_TABLE_SEQ_INDEX as H,CDC_META_TABLE as z,appendCdcChange as V,applyCdcChanges as Q,bumpCdcEpoch as Y,cdcCanVouchFor as j,cdcSeqLeavingRows as J,cdcTouchesTables as Z,cdcTrimmedError as $,compactCdcDocs as ee,cursorBelowRetainedFloor as re,migrateCdcLog as oe,migrateCdcMeta as ae,minCdcReplayableSeq as te,minCdcSeq as ne,readCdcChangeKeys as ie,readCdcChanges as le,readCdcCursor as se,readCdcEpoch as me,trimCdcChanges as ce}from"./packem_shared/CDC_LOG_TABLE-vVheEulD.mjs";import{archiveCdcSegment as pe,readArchivedCdcChanges as Se,readCdcArchivedThrough as ue,writeCdcArchivedThrough as fe}from"./packem_shared/archiveCdcSegment-DU4uzDFQ.mjs";import{CLIENT_WATERMARK_TABLE as Te,advanceClientWatermark as he,migrateClientWatermark as xe,readClientWatermark as Ce}from"./packem_shared/CLIENT_WATERMARK_TABLE-CRnrAnJ2.mjs";import{COMMIT_SEQ_FIELD as Ae,COMMIT_SEQ_TABLE as ge,allocateCommitSeq as _e,migrateCommitSeq as Ie,readCommitSeq as be}from"./packem_shared/COMMIT_SEQ_FIELD-BUdOMG5y.mjs";import{c as De}from"./packem_shared/ctx-db-companions-w-CfeOda.mjs";import{GLOBAL_SHAPE_SNAPSHOT_TABLE as Me,deleteGlobalShapeSnapshot as ye,deleteGlobalShapeSnapshotsForConnection as Fe,migrateGlobalShapeSnapshot as Ne,readGlobalShapeSnapshot as Oe,writeGlobalShapeSnapshot as ke}from"./packem_shared/GLOBAL_SHAPE_SNAPSHOT_TABLE-DSA6mzyx.mjs";import{IDEMPOTENCY_TABLE as Ge,migrateIdempotency as Ue,readIdempotent as qe,trimIdempotent as Ke,writeIdempotent as we}from"./packem_shared/IDEMPOTENCY_TABLE-DOpm_oMF.mjs";import{clearMemoryTables as We,isMemoryTable as Xe,memoryTableNames as He}from"./packem_shared/clearMemoryTables-BGbmag2i.mjs";import{computeRankPage as Ve,resolveRankSeekTuple as Qe}from"./packem_shared/computeRankPage-DsQ16o1z.mjs";import{S as je,m as Je,r as Ze,w as $e}from"./packem_shared/ctx-db-search-state-ruTuCsxa.mjs";import{SHAPE_POKE_CURSOR_TABLE as rr,deleteShapePokeCursor as or,deleteShapePokeCursorsForConnection as ar,migrateShapePokeCursor as tr,minShapePokeCursor as nr,readShapePokeCursor as ir,writeShapePokeCursor as lr,writeShapePokeCursors as sr}from"./packem_shared/SHAPE_POKE_CURSOR_TABLE-ByJVDHds.mjs";import{selectShapeMembers as cr,selectShapeRows as dr}from"./packem_shared/selectShapeMembers-CCZyZggM.mjs";import{DATA_MIGRATION_STATE_TABLE as Sr,readMigrationStatus as ur,runDataMigration as fr}from"./packem_shared/DATA_MIGRATION_STATE_TABLE-BNMWxRzv.mjs";import{SCAN_DEP as Tr,createDependencyTracker as hr,depKey as xr,tableFromDepKey as Cr}from"./packem_shared/SCAN_DEP-D7qE3iUe.mjs";import{runDrizzle as Ar,runSql as gr}from"./packem_shared/runDrizzle-2ULFQR_k.mjs";import{A as Ir,a as br,b as Lr,D as Dr,c as Pr,d as Mr,g as yr,i as Fr,j as Nr,e as Or,q as kr,f as Br,r as Gr,t as Ur,h as qr}from"./packem_shared/do-sql-Dvj8Yl5N.mjs";import{param as wr,renderSql as vr,sqliteInList as Wr,unionAll as Xr}from"./packem_shared/param-DlozcSQu.mjs";import{appendStreamChunk as zr,claimStreamRun as Vr,deleteStreamRun as Qr,finishStreamRun as Yr,migrateDurableStreams as jr,readStreamChunks as Jr,readStreamRun as Zr,trimStreamRuns as $r}from"./packem_shared/appendStreamChunk-C1Ok4b6J.mjs";import{DurableStreamRunner as ro,MAX_DURABLE_STREAM_BYTES as oo,MAX_DURABLE_STREAM_CHUNKS as ao,decideDurableAttach as to}from"./packem_shared/DurableStreamRunner-rTYp4v03.mjs";import{envOptionalPositiveInt as io,envPositiveInt as lo}from"./packem_shared/envOptionalPositiveInt-D2pY-c64.mjs";import{diffExternalSource as mo}from"./packem_shared/diffExternalSource-DgDJhslq.mjs";import{liftSourceId as po,normalizeSourceDocument as So,normalizeSourceValue as uo}from"./packem_shared/liftSourceId-CA3ENhXj.mjs";import{materializeExternalRows as Eo,materializeExternalRowsIncremental as To,readExternalSourceBaseline as ho,runExternalSourceTick as xo}from"./packem_shared/materializeExternalRows-iEVQKOKT.mjs";import{isSoftDeleted as Ro,isSourceDue as Ao,pullExternalSourceIncrementalTick as go,pullExternalSourceTick as _o}from"./packem_shared/isSoftDeleted-CYf6ijO3.mjs";import{GEO_DEFAULT_PRECISION as bo,boundingBoxCenter as Lo,boundingBoxGeohashes as Do,coveringGeohashes as Po,encodeGeohash as Mo,haversineMeters as yo,pointInBoundingBox as Fo}from"./packem_shared/GEO_DEFAULT_PRECISION-CqpQZ-J_.mjs";import{default as Oo}from"./packem_shared/GlobalPollTick-BNK4o-XT.mjs";import{ADMIN_FUNCTIONS as Bo,ADMIN_FUNCTION_PREFIX as Go,DEFAULT_FANOUT_TOPIC_LIMIT as Uo,FLAGS_FUNCTION_PREFIX as qo,MAX_PAGE_SIZE as Ko,RELATION_FUNCTION_PREFIX as wo,createFanoutCounters as vo,createGlobalPollCounters as Wo,createShapeProbeCounters as Xo,facetColumn as Ho,findStorageReferences as zo,listTables as Vo,readTablePage as Qo,recordFanoutPass as Yo,recordGlobalPollPass as jo,recordShapeProbePass as Jo,selectMatchingIds as Zo,summarizeFanoutTopics as $o,summarizeSubscriptions as ea}from"./packem_shared/ADMIN_FUNCTIONS-CRXp5IZu.mjs";import{MAIL_RETENTION as oa,MAIL_TABLE as aa,clearCapturedMail as ta,ensureMailTable as na,readCapturedMail as ia,recordCapturedMail as la}from"./packem_shared/MAIL_RETENTION-DGAQTHHs.mjs";import{NotFoundError as ma}from"./packem_shared/NotFoundError-BhF7FeFr.mjs";import{armRestore as da,readBookmark as pa}from"./packem_shared/armRestore-Bu1_8SUa.mjs";import{CURSOR_PREFIX as ua,applySelect as fa,buildSeekBeforeWhere as Ea,buildSeekWhere as Ta,decodeCursor as ha,encodeCursor as xa,equalityPinnedFields as Ca,normalizeOrderKeys as Ra,softDeleteScope as Aa,tiebreakDirectionFor as ga,uniqueIndexFields as _a}from"./packem_shared/CURSOR_PREFIX-Bn8SFoGd.mjs";import{QUEUE_TABLE as ba,clearQueueMessages as La,isLossyBody as Da,readQueueMessageById as Pa,readQueueMessages as Ma,recordQueueMessages as ya}from"./packem_shared/QUEUE_TABLE-s7QJZvBz.mjs";import{RANK_TIEBREAK as Na,encodePartitionKey as Oa,matchesRankStaticWhere as ka,rankKeyFromDoc as Ba,rankPivotConditionSql as Ga,rankTableName as Ua,resolveRankPartition as qa,sortColumnName as Ka}from"./packem_shared/RANK_TIEBREAK-BXDiMmkH.mjs";import{ReactiveCache as va,reactiveCacheKey as Wa}from"./packem_shared/ReactiveCache-CzeUmTTN.mjs";import{REACTOR_STATE_TABLE as Ha,listReactorStates as za,migrateReactorState as Va,reactorNeedsRun as Qa,readReactorState as Ya,writeReactorState as ja}from"./packem_shared/REACTOR_STATE_TABLE-QPRFyxMS.mjs";import{UNVOUCHABLE_DEP as Za,createReadFootprint as $a,markUnvouchableReads as et}from"./packem_shared/UNVOUCHABLE_DEP-C68htACn.mjs";import{buildIndexRange as ot,indexKeysForRow as at,keysTouchRanges as tt}from"./packem_shared/buildIndexRange-NtciKq3M.mjs";import{RELATED_DEFAULT_LIMIT as it,RELATED_DEPTH_DECAY as lt,RELATED_MAX_DEPTH as st,RELATED_MAX_LIMIT as mt,deriveRelationEdges as ct,findRelated as dt}from"./packem_shared/RELATED_DEFAULT_LIMIT-B9PH28Pn.mjs";import{DEFAULT_MAX_RELATION_KEYS as St,assertFlatPredicate as ut,assertShapeShardable as ft,containsRelationPredicate as Et,isRelationPredicate as Tt,resolveRelationPredicates as ht}from"./packem_shared/DEFAULT_MAX_RELATION_KEYS-XESc7TiB.mjs";import{applyOnDelete as Ct,distinctValues as Rt,fanOutScalarCounts as At,relationHooks as gt,resolveWith as _t,runRowValidators as It}from"./packem_shared/applyOnDelete-7JZ4vR9r.mjs";import{DEFAULT_PROMOTION_THRESHOLDS as Lt,clampPromotionThresholds as Dt,nextPromotionState as Pt,relayCountFor as Mt,shapeRoutingKey as yt}from"./packem_shared/DEFAULT_PROMOTION_THRESHOLDS-Bfx7KakS.mjs";import{DEFAULT_MAX_RELAYS as Nt,OwnerRelay as Ot,RelayMember as kt,createRelayLink as Bt}from"./packem_shared/DEFAULT_MAX_RELAYS-Ng4SyJ7k.mjs";import{createReplicaLink as Ut,gateReplicaDispatch as qt,handleReplicaControl as Kt}from"./packem_shared/createReplicaLink-Bo4IWADY.mjs";import{buildReprojectionMigration as vt,countLegacyRows as Wt,reprojectableFields as Xt,reprojectionTables as Ht}from"./packem_shared/buildReprojectionMigration-Coeg-J0M.mjs";import{RLS_UNWRAP_SYMBOL as Vt,RlsRequiredError as Qt,guardWriter as Yt}from"./packem_shared/RLS_UNWRAP_SYMBOL-BwwTbz3Q.mjs";import{SCHEMA_HISTORY_MAX_VERSIONS as Jt,readSchemaHistory as Zt,readSchemaVersion as $t,recordSchemaVersion as en}from"./packem_shared/SCHEMA_HISTORY_MAX_VERSIONS-BluIj2s-.mjs";import{serializeSqlValue as on}from"./packem_shared/serializeSqlValue-CjbhIHjJ.mjs";import{buildSettings as tn,isDevEnvironment as nn,readDeployInfo as ln}from"./packem_shared/buildSettings-DC3VeQ0H.mjs";import{buildShapeDiff as mn}from"./packem_shared/buildShapeDiff-WSoMs1_h.mjs";import{ShapeDiffCache as dn,createShapeDiffCache as pn,globalShapeReadKey as Sn}from"./packem_shared/ShapeDiffCache-gdaILV5E.mjs";import{buildPokeFrames as fn,diffGlobalMembership as En,encodeRowsPatch as Tn,projectColumns as hn}from"./packem_shared/buildPokeFrames-BBE6J91z.mjs";import{ShardRunner as Cn}from"./packem_shared/ShardRunner-C9p5DVOx.mjs";import{runSocketPool as An}from"./packem_shared/runSocketPool-CZJ2X9cF.mjs";import{MAX_SQL_ROWS as _n,assertReadonly as In,lintReadonlySql as bn,runReadonlySql as Ln}from"./packem_shared/MAX_SQL_ROWS-RvXZ7S7f.mjs";import{B as Pn,b as Mn,d as yn,a as Fn,f as Nn}from"./packem_shared/sql-projection-BB2lCbYV.mjs";import{awaitWsDrain as kn,subscriptionFrames as Bn,subscriptionListDeltas as Gn,trySendFrame as Un}from"./packem_shared/awaitWsDrain-apizgmKY.mjs";import{mergeChangedKeys as Kn,recordChangedKeys as wn,writeTouchesMemo as vn}from"./packem_shared/mergeChangedKeys-CPw4EamV.mjs";import{createSystemReader as Xn}from"./packem_shared/createSystemReader-DcDLFfC-.mjs";import{ConflictError as zn}from"./packem_shared/ConflictError-C8GtJmjS.mjs";import{DEFAULT_TRANSACTION_LIMITS as Qn,TransactionHeadroomTracker as Yn}from"./packem_shared/DEFAULT_TRANSACTION_LIMITS-DDGk9ebh.mjs";import{hasTrigger as Jn,runTriggers as Zn}from"./packem_shared/hasTrigger-CjlwI4le.mjs";import{selectExpiredIds as ei}from"./packem_shared/selectExpiredIds-CKOUTIHn.mjs";import{c as oi,l as ai}from"./packem_shared/where-sql-x1YKldcq.mjs";import{RELATION_EXISTS_KEY as ni}from"./packem_shared/RELATION_EXISTS_KEY-CFUhnZSZ.mjs";import{REPROJECTION_MIGRATION_PREFIX as li,reprojectionMigrationId as si}from"./packem_shared/REPROJECTION_MIGRATION_PREFIX-Czcb6_mO.mjs";import{quoteIdentifier as ci}from"./packem_shared/quoteIdentifier-CObIFRhb.mjs";import{runShardMigrations as pi}from"./packem_shared/runShardMigrations-CeT_SVrI.mjs";import{stableStringify as ui}from"./packem_shared/stableStringify-DibjylKD.mjs";import{stableWireKey as Ei}from"./packem_shared/stableWireKey-D2US4k_J.mjs";export{Bo as ADMIN_FUNCTIONS,Go as ADMIN_FUNCTION_PREFIX,m as AGGREGATE_SQL_FUNCTION,Ir as AGG_COUNT,br as AGG_KEY,Lr as AGG_VALUE,D as AUDIT_LOG_TABLE,Pn as BIGINT_KEY_DIGITS,X as CDC_LOG_TABLE,H as CDC_LOG_TABLE_SEQ_INDEX,z as CDC_META_TABLE,Te as CLIENT_WATERMARK_TABLE,Ae as COMMIT_SEQ_FIELD,ge as COMMIT_SEQ_TABLE,ua as CURSOR_PREFIX,zn as ConflictError,R as CountRlsUnsupportedError,Sr as DATA_MIGRATION_STATE_TABLE,Uo as DEFAULT_FANOUT_TOPIC_LIMIT,St as DEFAULT_MAX_RELATION_KEYS,Nt as DEFAULT_MAX_RELAYS,Lt as DEFAULT_PROMOTION_THRESHOLDS,Qn as DEFAULT_TRANSACTION_LIMITS,Dr as DOC_COLUMN,ro as DurableStreamRunner,qo as FLAGS_FUNCTION_PREFIX,bo as GEO_DEFAULT_PRECISION,Me as GLOBAL_SHAPE_SNAPSHOT_TABLE,Oo as GlobalPollTick,Ge as IDEMPOTENCY_TABLE,oa as MAIL_RETENTION,aa as MAIL_TABLE,oo as MAX_DURABLE_STREAM_BYTES,ao as MAX_DURABLE_STREAM_CHUNKS,Ko as MAX_PAGE_SIZE,_n as MAX_SQL_ROWS,ma as NotFoundError,N as NotUniqueError,Ot as OwnerRelay,ba as QUEUE_TABLE,Na as RANK_TIEBREAK,Ha as REACTOR_STATE_TABLE,it as RELATED_DEFAULT_LIMIT,lt as RELATED_DEPTH_DECAY,st as RELATED_MAX_DEPTH,mt as RELATED_MAX_LIMIT,ni as RELATION_EXISTS_KEY,wo as RELATION_FUNCTION_PREFIX,li as REPROJECTION_MIGRATION_PREFIX,Vt as RLS_UNWRAP_SYMBOL,va as ReactiveCache,kt as RelayMember,Qt as RlsRequiredError,Tr as SCAN_DEP,Jt as SCHEMA_HISTORY_MAX_VERSIONS,je as SEARCH_STATE_TABLE,rr as SHAPE_POKE_CURSOR_TABLE,dn as ShapeDiffCache,Cn as ShardRunner,Yn as TransactionHeadroomTracker,Za as UNVOUCHABLE_DEP,he as advanceClientWatermark,Pr as aggUpsertSql,c as aggregateSqlFunction,f as aggregateTableName,_e as allocateCommitSeq,P as appendAuditEntry,V as appendCdcChange,zr as appendStreamChunk,Q as applyCdcChanges,Ct as applyOnDelete,fa as applySelect,pe as archiveCdcSegment,da as armRestore,ut as assertFlatPredicate,O as assertNoExplicitUndefined,In as assertReadonly,ft as assertShapeShardable,k as assertValidClientId,kn as awaitWsDrain,q as backfillAggregateIndexes,K as backfillRankIndexes,w as backfillSearchIndexes,v as backfillSearchIndexesForTable,Mn as bigintSqlKey,Lo as boundingBoxCenter,Do as boundingBoxGeohashes,ot as buildIndexRange,fn as buildPokeFrames,vt as buildReprojectionMigration,Ea as buildSeekBeforeWhere,Ta as buildSeekWhere,tn as buildSettings,mn as buildShapeDiff,Y as bumpCdcEpoch,j as cdcCanVouchFor,J as cdcSeqLeavingRows,Z as cdcTouchesTables,$ as cdcTrimmedError,Vr as claimStreamRun,Dt as clampPromotionThresholds,ta as clearCapturedMail,We as clearMemoryTables,La as clearQueueMessages,E as coerceAggregateNumber,ee as compactCdcDocs,oi as compileWhereSql,Ve as computeRankPage,Et as containsRelationPredicate,Wt as countLegacyRows,Po as coveringGeohashes,De as createCompanionSync,hr as createDependencyTracker,vo as createFanoutCounters,Wo as createGlobalPollCounters,Mr as createIndexSql,$a as createReadFootprint,Bt as createRelayLink,Ut as createReplicaLink,pn as createShapeDiffCache,Xo as createShapeProbeCounters,B as createShardCtxDb,Xn as createSystemReader,re as cursorBelowRetainedFloor,to as decideDurableAttach,yn as decodeBigintSqlKey,ha as decodeCursor,Fn as decodeFloat64SqlKey,ye as deleteGlobalShapeSnapshot,Fe as deleteGlobalShapeSnapshotsForConnection,or as deleteShapePokeCursor,ar as deleteShapePokeCursorsForConnection,Qr as deleteStreamRun,xr as depKey,ct as deriveRelationEdges,mo as diffExternalSource,En as diffGlobalMembership,Rt as distinctValues,T as encodeAggregateKey,xa as encodeCursor,Mo as encodeGeohash,Oa as encodePartitionKey,Tn as encodeRowsPatch,M as ensureAuditTable,na as ensureMailTable,io as envOptionalPositiveInt,lo as envPositiveInt,Ca as equalityPinnedFields,o as exportShardRows,Ho as facetColumn,At as fanOutScalarCounts,dt as findRelated,zo as findStorageReferences,Yr as finishStreamRun,Nn as float64SqlKey,h as foldAggregateTally,qt as gateReplicaDispatch,yr as geoTableName,Sn as globalShapeReadKey,Yt as guardWriter,Kt as handleReplicaControl,Jn as hasTrigger,yo as haversineMeters,a as importShardRows,at as indexKeysForRow,nn as isDevEnvironment,Fr as isFtsAvailable,Da as isLossyBody,Xe as isMemoryTable,Tt as isRelationPredicate,Ro as isSoftDeleted,Ao as isSourceDue,Nr as jsonPath,Or as jsonPathSql,tt as keysTouchRanges,po as liftSourceId,bn as lintReadonlySql,za as listReactorStates,Vo as listTables,ai as literalInList,et as markUnvouchableReads,ka as matchesRankStaticWhere,d as matchesStaticWhere,Eo as materializeExternalRows,To as materializeExternalRowsIncremental,He as memoryTableNames,Kn as mergeChangedKeys,A as mergeWhere,oe as migrateCdcLog,ae as migrateCdcMeta,xe as migrateClientWatermark,Ie as migrateCommitSeq,jr as migrateDurableStreams,Ne as migrateGlobalShapeSnapshot,Ue as migrateIdempotency,Va as migrateReactorState,Je as migrateSearchState,tr as migrateShapePokeCursor,te as minCdcReplayableSeq,ne as minCdcSeq,nr as minShapePokeCursor,Pt as nextPromotionState,p as normalizeCountArgument,G as normalizeIdStructurally,Ra as normalizeOrderKeys,So as normalizeSourceDocument,uo as normalizeSourceValue,wr as param,t as parseExportShardArgs,n as parseImportShardArgs,g as planAggregateLookup,Fo as pointInBoundingBox,hn as projectColumns,go as pullExternalSourceIncrementalTick,_o as pullExternalSourceTick,kr as qualifiedJsonPath,Br as qualifiedJsonPathSql,ci as quoteIdentifier,Ba as rankKeyFromDoc,Ga as rankPivotConditionSql,Ua as rankTableName,Wa as reactiveCacheKey,Qa as reactorNeedsRun,x as readAggregateValue,Se as readArchivedCdcChanges,y as readAuditLog,pa as readBookmark,ia as readCapturedMail,ue as readCdcArchivedThrough,ie as readCdcChangeKeys,le as readCdcChanges,se as readCdcCursor,me as readCdcEpoch,Ce as readClientWatermark,be as readCommitSeq,ln as readDeployInfo,ho as readExternalSourceBaseline,Oe as readGlobalShapeSnapshot,qe as readIdempotent,ur as readMigrationStatus,Pa as readQueueMessageById,Ma as readQueueMessages,Ya as readReactorState,Zt as readSchemaHistory,$t as readSchemaVersion,Ze as readSearchBackfillState,ir as readShapePokeCursor,Jr as readStreamChunks,Zr as readStreamRun,Qo as readTablePage,la as recordCapturedMail,wn as recordChangedKeys,Yo as recordFanoutPass,jo as recordGlobalPollPass,ya as recordQueueMessages,en as recordSchemaVersion,Jo as recordShapeProbePass,gt as relationHooks,Mt as relayCountFor,vr as renderSql,Xt as reprojectableFields,si as reprojectionMigrationId,Ht as reprojectionTables,qa as resolveRankPartition,Qe as resolveRankSeekTuple,ht as resolveRelationPredicates,_t as resolveWith,Gr as rowToDocument,fr as runDataMigration,Ar as runDrizzle,xo as runExternalSourceTick,Ln as runReadonlySql,It as runRowValidators,pi as runShardMigrations,An as runSocketPool,gr as runSql,Zn as runTriggers,ei as selectExpiredIds,i as selectExportTables,_ as selectIndexForAggregate,I as selectIndexForCount,b as selectIndexForGroupBy,Zo as selectMatchingIds,cr as selectShapeMembers,dr as selectShapeRows,on as serializeSqlValue,yt as shapeRoutingKey,Aa as softDeleteScope,Ka as sortColumnName,Wr as sqliteInList,ui as stableStringify,Ei as stableWireKey,Bn as subscriptionFrames,Gn as subscriptionListDeltas,$o as summarizeFanoutTopics,ea as summarizeSubscriptions,Ur as tableColumns,Cr as tableFromDepKey,S as throwingScheduler,ga as tiebreakDirectionFor,ce as trimCdcChanges,Ke as trimIdempotent,$r as trimStreamRuns,qr as tryRowToDocument,Un as trySendFrame,Xr as unionAll,_a as uniqueIndexFields,l as validateImportRow,fe as writeCdcArchivedThrough,ke as writeGlobalShapeSnapshot,we as writeIdempotent,ja as writeReactorState,$e as writeSearchBackfillState,lr as writeShapePokeCursor,sr as writeShapePokeCursors,vn as writeTouchesMemo};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{LunoraError as E}from"@lunora/errors";import{m as $,n as y}from"./do-sql-Dvj8Yl5N.mjs";import{quoteIdentifier as d}from"./quoteIdentifier-CObIFRhb.mjs";import{d as L}from"./wire-codec-C-FpWm52.mjs";const te="__lunora_admin__:",re="__lunora_relation__:",ne="__lunora_flags__:",se={applyCdc:"__lunora_admin__:applyCdc",aiAvailable:"__lunora_admin__:aiAvailable",aiChartConfig:"__lunora_admin__:aiChartConfig",aiGenerateSql:"__lunora_admin__:aiGenerateSql",aiTableFilter:"__lunora_admin__:aiTableFilter",assignIssue:"__lunora_admin__:assignIssue",backfillSearch:"__lunora_admin__:backfillSearch",backRelationCounts:"__lunora_admin__:backRelationCounts",cdcSync:"__lunora_admin__:cdcSync",clearCapturedMail:"__lunora_admin__:clearCapturedMail",clearQueueMessages:"__lunora_admin__:clearQueueMessages",clearTable:"__lunora_admin__:clearTable",createWorkflowInstance:"__lunora_admin__:createWorkflowInstance",deleteRows:"__lunora_admin__:deleteRows",describeTable:"__lunora_admin__:describeTable",describeTables:"__lunora_admin__:describeTables",explainIssue:"__lunora_admin__:explainIssue",exportShard:"__lunora_admin__:exportShard",facetColumn:"__lunora_admin__:facetColumn",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",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",recordAuthEvent:"__lunora_admin__:recordAuthEvent",recordContainerEvent:"__lunora_admin__:recordContainerEvent",recordMail:"__lunora_admin__:recordMail",recordQueueMessage:"__lunora_admin__:recordQueueMessage",replayQueueMessage:"__lunora_admin__:replayQueueMessage",resolveIssue:"__lunora_admin__:resolveIssue",rlsPolicies:"__lunora_admin__:rlsPolicies",schemaHistory:"__lunora_admin__:schemaHistory",schemaVersion:"__lunora_admin__:schemaVersion",runAs:"__lunora_admin__:runAs",runMigration:"__lunora_admin__:runMigration",runSql:"__lunora_admin__:runSql",sendQueueMessage:"__lunora_admin__:sendQueueMessage",sendTestMail:"__lunora_admin__:sendTestMail",setIssueSeverity:"__lunora_admin__:setIssueSeverity",storageOrphans:"__lunora_admin__:storageOrphans",storageReferences:"__lunora_admin__:storageReferences",storageRules:"__lunora_admin__:storageRules",studioFeatures:"__lunora_admin__:studioFeatures",writeRow:"__lunora_admin__:writeRow"},D=50,h=500,U=30,j=200,f="__doc__",O=e=>{try{const t=JSON.parse(e);return t!==null&&typeof t=="object"&&!Array.isArray(t)?t:void 0}catch{return}},W=e=>{const{[y]:t,...r}=e;return t===void 0?r:t===null||typeof t!="object"||Array.isArray(t)?{[y]:t,...r}:{...r,...L(t)}},q=(e,t)=>{if(!e.includes(f))return{columns:e,rows:t};const r=[];for(const s of t){const o=s[f],i=typeof o=="string"?O(o):void 0;if(i===void 0)return{columns:e,rows:t};const c=Object.fromEntries(Object.entries(s).filter(([u])=>u!==f));r.push({...c,...W(i)})}const n=e.filter(s=>s!==f),a=[],_=new Set(n);for(const s of r)for(const o of Object.keys(s))_.has(o)||(_.add(o),a.push(o));return{columns:[...n,...a],rows:r}},F=e=>`instr(lower(CAST(${e} AS TEXT)), lower(?)) > 0`,I=e=>e.startsWith("sqlite_")||e.startsWith("_cf_")||e.startsWith("__miniflare")||e.startsWith("__lunora")||e.includes("__fts_"),C=(e,t,r)=>Math.min(Math.max(e,t),r),P=(e,t)=>{const r=e.exec(`SELECT COUNT(*) AS c FROM ${t}`).one();return Number(r.c)},ae=e=>{const t=e.exec("SELECT name FROM sqlite_master WHERE type = 'table' ORDER BY name").toArray(),r=[];for(const{name:n}of t)I(n)||r.push({name:n,rowCount:P(e,d(n))});return r},x=(e,t)=>e.exec("SELECT name FROM sqlite_master WHERE type = 'table' AND name = ? LIMIT 1",t).toArray().length>0,A=(e,t)=>{if(I(t)||!x(e,t))throw new E("UNKNOWN_TABLE",`unknown table: ${t}`,{status:404})},M=(e,t)=>e.exec(`PRAGMA table_info(${t})`).toArray().map(r=>r.name),Q={eq:"=",gt:">",gte:">=",lt:"<",lte:"<=",ne:"<>"},B=e=>typeof e=="string"?e:typeof e=="number"||typeof e=="boolean"?String(e):"",v=(e,t)=>{const r=t.includes(e),n=t.includes(f);if(!(!r&&!n))return r?{expression:d(e),params:[]}:{expression:`json_extract(${d(f)}, ?)`,params:[`$.${$(e)}`]}},G=(e,t)=>{const r=v(e.column,t);if(r===void 0)return;const{expression:n,params:a}=r;return e.operator==="contains"?{params:[...a,B(e.value)],sql:F(n)}:{params:[...a,e.value],sql:`${n} ${Q[e.operator]} ?`}},H=/^(\d{4})(?:-(\d{2}))?(?:-(\d{2}))?$/u,X=e=>{const t=H.exec(e.trim());if(t===null)return;const r=Number(t[1]),n=t[2]===void 0?void 0:Number(t[2]),a=t[3]===void 0?void 0:Number(t[3]);if(n!==void 0&&(n<1||n>12)||a!==void 0&&(a<1||a>31)||r<100)return;const _=Date.UTC(r,(n??1)-1,a??1);if(a!==void 0&&new Date(_).getUTCDate()!==a)return;let s;return a!==void 0?s=Date.UTC(r,(n??1)-1,a+1):n===void 0?s=Date.UTC(r+1,0,1):s=Date.UTC(r,n,1),{from:_,to:s}},R=(e,t,r)=>{const n=[],a=[];if(t!==""&&e.length>0){const _=e.map(o=>F(d(o)));a.push(...e.map(()=>t));const s=X(t);if(s!==void 0)for(const o of e)_.push(`(${d(o)} >= ? AND ${d(o)} < ?)`),a.push(s.from,s.to);n.push(`(${_.join(" OR ")})`)}for(const _ of r??[]){const s=G(_,e);s!==void 0&&(n.push(`(${s.sql})`),a.push(...s.params))}return n.length===0?void 0:{parameters:a,where:n.join(" AND ")}},Y=(e,t)=>{if(e===void 0)return;const r=v(e.column,t);if(r===void 0)return;const n=e.direction==="desc"?"DESC":"ASC";return{params:r.params,sql:`${r.expression} ${n}`}},oe=(e,t)=>{const{table:r}=t;A(e,r);const n=C(Math.trunc(t.limit??D),1,h),a=Math.max(0,Math.trunc(t.offset??0)),_=d(r),s=M(e,_),o=t.search?.trim()??"",i=S=>{if(t.refs===void 0)return S;const T={};for(const w of S.columns){const k=t.refs[w];k!==void 0&&(T[w]=k)}return Object.keys(T).length>0?{...S,refs:T}:S},c=R(s,o,t.filters),u=Y(t.orderBy,s),l=c===void 0?"":` WHERE ${c.where}`,m=u===void 0?"":` ORDER BY ${u.sql}`,p=c?.parameters??[],g=u?.params??[];let b;t.skipCount||(b=c===void 0?P(e,_):Number(e.exec(`SELECT COUNT(*) AS c FROM ${_}${l}`,...p).one().c));const N=e.exec(`SELECT * FROM ${_}${l}${m} LIMIT ? OFFSET ?`,...p,...g,n,a).toArray();return i({...q(s,N),total:b})},_e=(e,t)=>{const{table:r}=t;A(e,r);const n=C(Math.trunc(t.limit??h),1,h),a=d(r),_=M(e,a),s=t.search?.trim()??"",o=R(_,s,t.filters),i=[],c=[];o!==void 0&&(i.push(o.where),c.push(...o.parameters)),t.after!==void 0&&(i.push("id > ?"),c.push(t.after));const u=i.length===0?"":` WHERE ${i.join(" AND ")}`,l=t.after===void 0?"":" ORDER BY id",m=e.exec(`SELECT id FROM ${a}${u}${l} LIMIT ?`,...c,n+1).toArray(),p=m.length>n,g=m.slice(0,n).map(b=>b.id);return{hasMore:p,ids:g}},K=(e,t,r)=>{const n=new Set(r.filter(_=>_!==f));if(!r.includes(f))return n;const a=e.exec(`SELECT ${d(f)} AS doc FROM ${t} LIMIT ?`,h).toArray();for(const{doc:_}of a){const s=typeof _=="string"?O(_):void 0;if(s!==void 0)for(const o of Object.keys(s))n.add(o)}return n},ie=(e,t)=>{const{column:r,table:n}=t;A(e,n);const a=d(n),_=M(e,a);if(!K(e,a,_).has(r))throw new E("UNKNOWN_COLUMN",`unknown column: ${r}`,{status:404});const s=v(r,_);if(s===void 0)throw new E("UNKNOWN_COLUMN",`unknown column: ${r}`,{status:404});const o=C(Math.trunc(t.limit??U),1,j),i=t.search?.trim()??"",c=R(_,i,t.filters),u=c===void 0?"":` WHERE ${c.where}`,l=c?.parameters??[],m=e.exec(`SELECT ${s.expression} AS value, COUNT(*) AS count FROM ${a}${u} GROUP BY ${s.expression} ORDER BY count DESC LIMIT ?`,...s.params,...l,...s.params,o+1).toArray();return{truncated:m.length>o,values:m.slice(0,o).map(g=>({count:Number(g.count),value:g.value}))}},ce=(e,t,r)=>{const n={},a=r.slice(0,h);for(const s of a)n[s]=[];if(a.length===0)return{references:n,storageColumns:t};const _=a.map(()=>"?").join(", ");for(const[s,o]of Object.entries(t)){if(I(s)||!x(e,s))continue;const i=d(s),c=M(e,i);for(const u of o){const l=v(u,c);if(l===void 0)continue;const m=e.exec(`SELECT id, ${l.expression} AS ref FROM ${i} WHERE ${l.expression} IN (${_})`,...l.params,...l.params,...a).toArray();for(const p of m)n[p.ref]?.push({column:u,id:p.id,table:s})}}return{references:n,storageColumns:t}},ue=e=>{const t=e.map((n,a)=>{const _=Object.values(n.subs??{}).map(s=>({args:s.args,functionPath:s.functionPath,table:s.table}));return{admin:n.admin===!0,id:a,subscriptions:_}}),r=t.reduce((n,a)=>n+a.subscriptions.length,0);return{connections:t,totalConnections:t.length,totalSubscriptions:r}},V=20,le=()=>({maxMs:0,passes:0,peakSocketsIterated:0,socketsDelivered:0,socketsIterated:0,totalMs:0}),de=()=>({run:0,served:0}),me=()=>({drains:0,pairsSkipped:0}),fe=(e,t,r)=>({drains:e.drains+t,pairsSkipped:e.pairsSkipped+r}),pe=(e,t,r)=>({run:e.run+t,served:e.served+r}),ge=(e,t,r,n)=>({maxMs:Math.max(e.maxMs,n),passes:e.passes+1,peakSocketsIterated:Math.max(e.peakSocketsIterated,t),socketsDelivered:e.socketsDelivered+r,socketsIterated:e.socketsIterated+t,totalMs:e.totalMs+n}),he=(e,t=V)=>{const r=new Map,n=new Map;for(const s of e){for(const o of Object.values(s.shapes??{})){const i=o.name??"(unknown shape)";r.set(i,(r.get(i)??0)+1)}for(const o of s.whispers??[])n.set(o,(n.get(o)??0)+1)}const a=[...[...r].map(([s,o])=>({kind:"shape",subscribers:o,topic:s})),...[...n].map(([s,o])=>({kind:"whisper",subscribers:o,topic:s}))];return a.sort((s,o)=>o.subscribers-s.subscribers||s.topic.localeCompare(o.topic)),{peakSubscribers:a[0]?.subscribers??0,topics:a.slice(0,t),totalConnections:e.length}};export{se as ADMIN_FUNCTIONS,te as ADMIN_FUNCTION_PREFIX,V as DEFAULT_FANOUT_TOPIC_LIMIT,ne as FLAGS_FUNCTION_PREFIX,h as MAX_PAGE_SIZE,re as RELATION_FUNCTION_PREFIX,le as createFanoutCounters,me as createGlobalPollCounters,de as createShapeProbeCounters,X as datePrefixRange,ie as facetColumn,ce as findStorageReferences,ae as listTables,oe as readTablePage,ge as recordFanoutPass,fe as recordGlobalPollPass,pe as recordShapeProbePass,_e as selectMatchingIds,he as summarizeFanoutTopics,ue as summarizeSubscriptions};
|
package/dist/packem_shared/{DEFAULT_MAX_RELAYS-DDOVsK5A.mjs → DEFAULT_MAX_RELAYS-Ng4SyJ7k.mjs}
RENAMED
|
@@ -1,8 +1,8 @@
|
|
|
1
|
-
import{toErrorBody as k,LunoraError as D}from"@lunora/errors";import{e as N,d as v}from"./wire-codec-C-FpWm52.mjs";import{sql as y}from"drizzle-orm";import{runDrizzle as m}from"./runDrizzle-2ULFQR_k.mjs";import{WORKERD_SQLITE_LIMITS as F}from"./param-DlozcSQu.mjs";import{d as U,w,a as A,m as
|
|
1
|
+
import{toErrorBody as k,LunoraError as D}from"@lunora/errors";import{e as N,d as v}from"./wire-codec-C-FpWm52.mjs";import{sql as y}from"drizzle-orm";import{runDrizzle as m}from"./runDrizzle-2ULFQR_k.mjs";import{WORKERD_SQLITE_LIMITS as F}from"./param-DlozcSQu.mjs";import{d as U,w,a as A,m as $,r as K,b as Y,c as W}from"./ctx-db-relay-shapes-Bg5YYnmN.mjs";import{envPositiveInt as g}from"./envOptionalPositiveInt-D2pY-c64.mjs";import{relayName as R,DEFAULT_PROMOTION_THRESHOLDS as T,nextPromotionState as B,shapeRoutingKey as _,relayProxyKey as M,parseRelayName as H,clampPromotionThresholds as q}from"./DEFAULT_PROMOTION_THRESHOLDS-Bfx7KakS.mjs";import{encodeRowsPatch as X,buildPokeFrames as O}from"./buildPokeFrames-BBE6J91z.mjs";import{v as j,R as L,s as z,a as G,b as J}from"./sibling-channel-BkL5cTCc.mjs";import{awaitWsDrain as V,trySendFrame as x}from"./awaitWsDrain-apizgmKY.mjs";import{stableWireKey as b}from"./stableWireKey-D2US4k_J.mjs";const f="__lunora_relay_memos",Q=i=>{m(i,y`CREATE TABLE IF NOT EXISTS ${y.identifier(f)} (
|
|
2
2
|
connection_id TEXT NOT NULL,
|
|
3
3
|
sub_id TEXT NOT NULL,
|
|
4
4
|
cursor INTEGER NOT NULL,
|
|
5
5
|
epoch TEXT,
|
|
6
6
|
PRIMARY KEY (connection_id, sub_id)
|
|
7
7
|
)`)},Z=i=>{const e=m(i,y`SELECT connection_id, sub_id, cursor, epoch FROM ${y.identifier(f)}`).toArray(),s=new Map;for(const t of e){let o=s.get(t.connection_id);o===void 0&&(o=new Map,s.set(t.connection_id,o)),o.set(t.sub_id,{cursor:Number(t.cursor),epoch:t.epoch??void 0})}return s},ee=4,C=(i,e)=>{const s=Math.floor(F.boundParams/ee);for(let t=0;t<e.length;t+=s){const o=e.slice(t,t+s),n=y.join(o.map(r=>y`(${r.connectionId}, ${r.subId}, ${r.cursor}, ${r.epoch??null})`),y`, `);m(i,y`INSERT INTO ${y.identifier(f)} (connection_id, sub_id, cursor, epoch) VALUES ${n}
|
|
8
|
-
ON CONFLICT(connection_id, sub_id) DO UPDATE SET cursor = excluded.cursor, epoch = excluded.epoch`)}},te=(i,e,s)=>{m(i,y`DELETE FROM ${y.identifier(f)} WHERE connection_id = ${e} AND sub_id = ${s}`)},se=(i,e)=>{m(i,y`DELETE FROM ${y.identifier(f)} WHERE connection_id = ${e}`)},oe=i=>{m(i,y`DELETE FROM ${y.identifier(f)}`)},re=2,ne=8,I={},ae=i=>{throw new D("INTERNAL",`unhandled relay frame: ${JSON.stringify(i)}`)},ie=(i,e)=>i===void 0||i.epoch!==e.epoch?!1:i.cursor>=e.fromCursor&&i.cursor<e.checkpoint,ce=i=>Response.json(i,{headers:{"content-type":"application/json"}}),S=()=>new Response(null,{status:204});class P{constructor(e,s){this.host=e,this.roleId=s}host;roleId;async handleControl(e){let s;try{s=await e.text()}catch{return new Response("bad request",{status:400})}if(!await j(this.host.env(),e.headers.get(L),s))return new Response("forbidden",{status:403});let t;try{t=JSON.parse(s)}catch{return new Response("bad request",{status:400})}switch(t.type){case"relay_attach":return this.onAttach(t.relayIndex),S();case"relay_detach":return this.onDetach(t.relayIndex),S();case"relay_frame":return this.host.deliverWhisperLocal(t.topic,t.frame,void 0),await this.onWhisperFrame(t),S();case"relay_shape_poke":{const o=this.host.getWebSockets().length,n=Date.now(),{delivered:r,matched:a}=this.onShapePoke({...t,args:v(t.args)});return this.host.recordShapePokeFanout(o,r,Date.now()-n),r<a?Response.json({delivered:r,matched:a},{status:503}):S()}case"relay_shape_subscribe":return ce(this.onShapeSubscribe({...t,args:v(t.args)}));case"relay_shape_unsubscribe":return this.onShapeUnsubscribe(t),S();default:return ae(t)}}maxRelays(){return g(this.host.env(),"LUNORA_MAX_RELAYS",ne)}canAddressSiblings(){return this.siblingStub(this.roleId.ownerKey)!==void 0}siblingStub(e){return z(this.host.env(),this.bindingName(),e,this.host.shardJurisdiction())}bindingName(){return this.host.shardBinding()}async postRelayMessage(e,s){await this.requestRelayMessage(e,s)}async requestRelayMessage(e,s){const t=this.siblingStub(e);if(t===void 0)return;const o=JSON.stringify(s),n={"content-type":"application/json","x-lunora-shard-binding":this.host.shardBinding()??""},r=G(this.host.env());r!==void 0&&(n[L]=await J(r,o));try{return await t.fetch("https://relay.internal/_lunora/relay",{body:o,headers:n,method:"POST"})}catch{return}}}class he extends P{shapeUniformCache=new Map;relaySetCache;registryCache;recordedBinding;promotionState="owned";constructor(e,s){super(e,{ownerKey:s})}async forwardWhisper(e,s){if(!this.canAddressSiblings())return;const t=this.ownerRelaySet();t.size!==0&&await Promise.all([...t].map(o=>this.postRelayMessage(R(this.roleId.ownerKey,o),{frame:s,topic:e,type:"relay_frame"})))}async onFlush(e,s){this.canAddressSiblings()&&await Promise.all([this.multicastShapePokes(e,s),this.proxyShapePokes(e,s)])}seedRelayShape(){return Promise.resolve(void 0)}announce(){return Promise.resolve()}announceDrain(){return Promise.resolve()}releaseRelayShapes(){return Promise.resolve()}relayCount(){const e=this.host.getWebSockets().length,s=g(this.host.env(),"LUNORA_RELAY_THRESHOLD",T.tUp),t=g(this.host.env(),"LUNORA_RELAY_COLLAPSE_THRESHOLD",T.tDown);if(this.promotionState=B(this.promotionState,e,q(s,t)),this.promotionState==="owned")return 0;const o=g(this.host.env(),"LUNORA_RELAY_FAN",re);return Math.min(this.maxRelays(),Math.max(1,o))}minShapeCursor(){const{cohort:e,proxies:s}=this.relayShapes();let t;for(const o of[...e.values(),...s.values()])t=t===void 0?o.cursor:Math.min(t,o.cursor);return t}isShapeRelayUniform(e,s){const t=E(e,s),o=this.shapeUniformCache.get(t);if(o!==void 0)return o;const n=this.probeShapeRelayUniform(e,s);return this.shapeUniformCache.set(t,n),n}onShapeUnsubscribe(e){const{proxies:s}=this.relayShapes(),t=e.subId===void 0?void 0:M(e.relayIndex,e.connectionId,e.subId);for(const[o,n]of s)n.relayIndex!==e.relayIndex||n.connectionId!==e.connectionId||(t===void 0||o===t)&&s.delete(o);U(this.host.sql(),e.relayIndex,e.connectionId,e.subId)}onAttach(e){this.addRelayToSet(e)}onDetach(e){this.removeRelayFromSet(e)}async onWhisperFrame(e){await Promise.all([...this.ownerRelaySet()].filter(s=>s!==e.originRelay).map(s=>this.postRelayMessage(R(this.roleId.ownerKey,s),{frame:e.frame,topic:e.topic,type:"relay_frame"})))}onShapeSubscribe(e){return this.buildShapeSeedFrames(e)}onShapePoke(){return{delivered:0,matched:0}}buildShapePoke(e,s,t,o,n){let r;try{r=this.host.resolveShape(e.name,e.args,s)}catch{return}if(r===void 0||r.global===!0||!t.has(r.table))return;const a=e,h=a.cursor,c=this.host.buildShapeDiff(r,h,o);if(c.length!==0)return a.cursor=o,w(this.host.sql(),a.key,o),{args:N(e.args),checkpoint:o,epoch:n,fromCursor:h,name:e.name,rowsPatch:X(c),type:"relay_shape_poke"}}async multicastShapePokes(e,s){const t=this.ownerRelaySet();if(t.size===0)return;const{cohort:o}=this.relayShapes();if(o.size===0)return;const n=this.host.currentCdcEpoch(),r=[];for(const a of o.values()){const h=this.buildShapePoke(a,I,e,s,n);h&&r.push(this.multicastToRelays(t,h,a))}await Promise.all(r)}async multicastToRelays(e,s,t){(await Promise.all([...e].map(async n=>(await this.requestRelayMessage(R(this.roleId.ownerKey,n),s))?.ok===!0))).includes(!1)&&this.rewindShapeCursor(t,s.fromCursor)}async proxyShapePokes(e,s){if(this.ownerRelaySet().size===0)return;const{proxies:t}=this.relayShapes();if(t.size===0)return;const o=this.host.currentCdcEpoch(),n=[];for(const r of t.values()){const a=this.buildShapePoke(r,r.identity,e,s,o);a&&n.push(this.proxyToRelay(a,r))}await Promise.all(n)}async proxyToRelay(e,s){(await this.requestRelayMessage(R(this.roleId.ownerKey,s.relayIndex),{...e,targetConnectionId:s.connectionId}))?.ok!==!0&&this.rewindShapeCursor(s,e.fromCursor)}buildShapeSeedFrames(e){const s={identity:e.identity,userId:e.userId};let t;try{t=this.host.resolveShape(e.name,e.args,s)}catch(l){const{body:p}=k(l,{fallbackCode:"SHAPE_RESOLVE_FAILED",redactedMessage:"shape resolution failed"});return{error:{code:p.code,message:p.message}}}if(t===void 0||t.global===!0)return{error:{code:"SHAPE_NOT_FOUND",message:`shape not relayable: ${e.name}`}};e.relayIndex!==void 0&&this.addRelayToSet(e.relayIndex);const{baseCheckpoint:o,cursor:n,epoch:r,reset:a,rowsPatch:h}=this.host.computeOpLogShapeSeed({args:e.args,name:e.name,sinceEpoch:e.sinceEpoch,sinceSeq:e.sinceSeq},t);let c=n;const{cohort:d,proxies:_}=this.relayShapes();if(this.isShapeRelayUniform(e.name,e.args)){const l=E(e.name,e.args);let p=d.get(l);p===void 0&&(p={args:e.args,cursor:n,key:l,name:e.name},d.set(l,p),A(this.host.sql(),p)),c=p.cursor}else if(e.relayIndex!==void 0&&e.connectionId!==void 0){const l=M(e.relayIndex,e.connectionId,e.subId),p={args:e.args,connectionId:e.connectionId,cursor:n,identity:s,key:l,name:e.name,relayIndex:e.relayIndex};_.set(l,p),A(this.host.sql(),p)}else return{error:{code:"RELAY_SHAPE_UNROUTABLE",message:`shape ${e.name} is per-socket on a relay, but the subscribe carries no ${e.relayIndex===void 0?"relay index":"connection id"}`}};const u=O([{reset:a,rowsPatch:h,shapeId:e.subId}],{baseCheckpoint:o,checkpoint:c,epoch:r,lastMutationId:void 0,pokeId:this.host.nextPokeId()});return{cursor:c,epoch:r,frames:u}}ensureRelayTables(){this.host.sql().exec("CREATE TABLE IF NOT EXISTS __lunora_relays (idx INTEGER PRIMARY KEY)"),this.host.sql().exec("CREATE TABLE IF NOT EXISTS __lunora_relay_binding (id INTEGER PRIMARY KEY, binding TEXT NOT NULL)"),K(this.host.sql())}bindingName(){const e=this.host.shardBinding();if(e!==void 0&&e!=="")return e!==this.recordedBinding&&(this.recordedBinding=e,this.ensureRelayTables(),this.host.sql().exec("INSERT INTO __lunora_relay_binding (id, binding) VALUES (1, ?) ON CONFLICT(id) DO UPDATE SET binding = excluded.binding",e)),e;if(this.recordedBinding!==void 0)return this.recordedBinding;try{const s=this.host.sql().exec("SELECT binding FROM __lunora_relay_binding WHERE id = 1").toArray();this.recordedBinding=s[0]?.binding}catch{this.recordedBinding=void 0}return this.recordedBinding}relayShapes(){const e=this.registryCache;if(e!==void 0)return e;this.ensureRelayTables();const s={cohort:new Map,proxies:new Map};for(const t of Y(this.host.sql()))t.relayIndex===void 0||t.connectionId===void 0?s.cohort.set(t.key,{args:t.args,cursor:t.cursor,key:t.key,name:t.name}):s.proxies.set(t.key,{args:t.args,connectionId:t.connectionId,cursor:t.cursor,identity:t.identity??{},key:t.key,name:t.name,relayIndex:t.relayIndex});return this.registryCache=s,s}rewindShapeCursor(e,s){const t=e;t.cursor<=s||(t.cursor=s,w(this.host.sql(),t.key,s))}ownerRelaySet(){if(this.relaySetCache===void 0){this.ensureRelayTables();const e=this.host.sql().exec("SELECT idx FROM __lunora_relays").toArray();this.relaySetCache=new Set(e.map(s=>Number(s.idx)))}return this.relaySetCache}addRelayToSet(e){this.ensureRelayTables(),this.host.sql().exec("INSERT OR IGNORE INTO __lunora_relays (idx) VALUES (?)",e),this.ownerRelaySet().add(e)}removeRelayFromSet(e){this.ensureRelayTables(),this.host.sql().exec("DELETE FROM __lunora_relays WHERE idx = ?",e);const s=this.ownerRelaySet();s.delete(e);const{cohort:t,proxies:o}=this.relayShapes();for(const[n,r]of o)r.relayIndex===e&&o.delete(n);$(this.host.sql(),e),s.size===0&&(t.clear(),this.shapeUniformCache.clear(),W(this.host.sql()))}probeShapeRelayUniform(e,s){let t;try{t=this.host.resolveShape(e,s,I)}catch{return!1}if(t===void 0||t.global===!0||this.host.rlsMetadata().policies.some(c=>c.on==="read"&&c.table===t.table)||this.tableHasAnyMask(t.table))return!1;const o=b(t.effectiveWhere),n=b(t.columns);let r=!1;const a=c=>{const d={groups:[`grp_${c}`],roles:[c],sub:`__lunora_probe_${c}__`};return{identity:new Proxy(d,{get:(u,l)=>typeof l=="symbol"||l in u?Reflect.get(u,l):`${c}:${l}`,getOwnPropertyDescriptor:(u,l)=>(r=!0,Reflect.getOwnPropertyDescriptor(u,l)),has:(u,l)=>typeof l=="symbol"?Reflect.has(u,l):!0,ownKeys:u=>(r=!0,Reflect.ownKeys(u))}),userId:`__lunora_probe_${c}__`}};return[I,a("a"),a("b")].every(c=>{let d;try{d=this.host.resolveShape(e,s,c)}catch{return!1}return d!==void 0&&d.global!==!0&&d.table===t.table&&b(d.effectiveWhere)===o&&b(d.columns)===n})&&!r}tableHasAnyMask(e){return this.host.maskMetadata().columns.some(s=>s.table===e)}}class le extends P{relayAnnounced=!1;relayMemoCache;shapeControl=new Map;constructor(e,s,t){super(e,{ownerKey:s,relayIndex:t})}async forwardWhisper(e,s){this.canAddressSiblings()&&await this.postRelayMessage(this.roleId.ownerKey,{frame:s,originRelay:this.roleId.relayIndex,topic:e,type:"relay_frame"})}onFlush(){return Promise.resolve()}async seedRelayShape(e,s,t,o){if(!this.canAddressSiblings())return{code:"RELAY_MISCONFIGURED",message:"relay cannot address its owner"};const{connectionId:n}=this.host.readAttachment(e),r={args:N(t.args??{}),connectionId:n,identity:o.identity,name:t.name,relayIndex:this.roleId.relayIndex,sinceEpoch:t.sinceEpoch,sinceSeq:t.sinceSeq,subId:s,type:"relay_shape_subscribe",userId:o.userId},a=await this.queueShapeControl(n,async()=>(await this.announce(),this.requestRelayMessage(this.roleId.ownerKey,r)));if(a===void 0)return{code:"RELAY_SEED_FAILED",message:"owner did not answer the shape seed"};let h;try{h=await a.json()}catch{return{code:"RELAY_SEED_FAILED",message:"malformed shape seed from owner"}}if(h.error!==void 0)return h.error;if(h.frames===void 0)return{code:"RELAY_SEED_FAILED",message:"owner returned no shape frames"};await V(e);for(const c of h.frames)x(e,c);return this.recordRelayShapeMemo(e,s,h.cursor??0,h.epoch),"ok"}async announce(){if(this.relayAnnounced||!this.canAddressSiblings())return;this.relayAnnounced=!0,(await this.requestRelayMessage(this.roleId.ownerKey,{relayIndex:this.roleId.relayIndex,type:"relay_attach"}))?.ok||(this.relayAnnounced=!1)}async announceDrain(e){this.host.getWebSockets().some(s=>s!==e)||(this.relayMemos().clear(),oe(this.host.sql()),this.canAddressSiblings()&&(this.relayAnnounced=!1,await this.postRelayMessage(this.roleId.ownerKey,{relayIndex:this.roleId.relayIndex,type:"relay_detach"})))}async releaseRelayShapes(e,s){const{connectionId:t}=this.host.readAttachment(e);t!==void 0&&this.forgetRelayShapeMemos(t,s),!(t===void 0||!this.canAddressSiblings())&&await this.queueShapeControl(t,async()=>this.postRelayMessage(this.roleId.ownerKey,{connectionId:t,relayIndex:this.roleId.relayIndex,...s===void 0?{}:{subId:s},type:"relay_shape_unsubscribe"}))}relayCount(){return 0}isShapeRelayUniform(){return!1}minShapeCursor(){}onAttach(){}onDetach(){}onWhisperFrame(){return Promise.resolve()}onShapeSubscribe(){return{error:{code:"RELAY_CANNOT_SEED",message:"a relay has no op-log to seed from"}}}onShapeUnsubscribe(){}onShapePoke(e){return this.deliverShapePoke(e)}async queueShapeControl(e,s){if(e===void 0)return s();const t=(this.shapeControl.get(e)??Promise.resolve()).then(s,s),o={},n=()=>{this.shapeControl.get(e)===o.chain&&this.shapeControl.delete(e)},r=t.then(n,n);return o.chain=r,this.shapeControl.set(e,r),t}relayMemos(){return this.relayMemoCache===void 0&&(Q(this.host.sql()),this.relayMemoCache=Z(this.host.sql())),this.relayMemoCache}connectionMemos(e){const s=this.relayMemos();let t=s.get(e);return t===void 0&&(t=new Map,s.set(e,t)),t}recordRelayShapeMemo(e,s,t,o){const{connectionId:n}=this.host.readAttachment(e);n!==void 0&&(this.connectionMemos(n).set(s,{cursor:t,epoch:o}),C(this.host.sql(),[{connectionId:n,cursor:t,epoch:o,subId:s}]))}forgetRelayShapeMemos(e,s){if(s===void 0){this.relayMemos().delete(e),se(this.host.sql(),e);return}this.relayMemos().get(e)?.delete(s),te(this.host.sql(),e,s)}deliverShapePoke(e){const s=E(e.name,e.args),t=[];let o=0,n=0;for(const r of this.host.getWebSockets()){const{connectionId:a,shapes:h}=this.host.readAttachment(r);if(h===void 0||a===void 0||e.targetConnectionId!==void 0&&a!==e.targetConnectionId)continue;const c=this.pokeSocketShapes(r,h,this.connectionMemos(a),e,s);n+=c.matched.length,o+=c.sent;for(const d of c.matched)t.push({connectionId:a,cursor:e.checkpoint,epoch:e.epoch,subId:d})}return C(this.host.sql(),t),{delivered:o,matched:n}}pokeSocketShapes(e,s,t,o,n){const r=[];let a=0;for(const[h,c]of Object.entries(s)){const d=t.get(h);if(E(c.name,c.args)!==n||!ie(d,o))continue;const u=O([{baseCheckpoint:d?.cursor,rowsPatch:o.rowsPatch,shapeId:h}],{baseCheckpoint:void 0,checkpoint:o.checkpoint,epoch:o.epoch,lastMutationId:void 0,pokeId:this.host.nextPokeId()},{preEncoded:!0}).map(l=>x(e,l)).every(Boolean);t.set(h,{cursor:o.checkpoint,epoch:o.epoch}),r.push(h),u&&(a+=1)}return{matched:r,sent:a}}}const Ie=i=>{const e=i.doName();if(e===void 0)return;const s=H(e);return s===void 0?new he(i,e):new le(i,s.ownerKey,s.relayIndex)};export{ne as DEFAULT_MAX_RELAYS,he as OwnerRelay,le as RelayMember,Ie as createRelayLink};
|
|
8
|
+
ON CONFLICT(connection_id, sub_id) DO UPDATE SET cursor = excluded.cursor, epoch = excluded.epoch`)}},te=(i,e,s)=>{m(i,y`DELETE FROM ${y.identifier(f)} WHERE connection_id = ${e} AND sub_id = ${s}`)},se=(i,e)=>{m(i,y`DELETE FROM ${y.identifier(f)} WHERE connection_id = ${e}`)},oe=i=>{m(i,y`DELETE FROM ${y.identifier(f)}`)},re=2,ne=8,I={},ae=i=>{throw new D("INTERNAL",`unhandled relay frame: ${JSON.stringify(i)}`)},ie=(i,e)=>i===void 0||i.epoch!==e.epoch?!1:i.cursor>=e.fromCursor&&i.cursor<e.checkpoint,ce=i=>Response.json(i,{headers:{"content-type":"application/json"}}),S=()=>new Response(null,{status:204});class P{constructor(e,s){this.host=e,this.roleId=s}host;roleId;async handleControl(e){let s;try{s=await e.text()}catch{return new Response("bad request",{status:400})}if(!await j(this.host.env(),e.headers.get(L),s))return new Response("forbidden",{status:403});let t;try{t=JSON.parse(s)}catch{return new Response("bad request",{status:400})}switch(t.type){case"relay_attach":return this.onAttach(t.relayIndex),S();case"relay_detach":return this.onDetach(t.relayIndex),S();case"relay_frame":return this.host.deliverWhisperLocal(t.topic,t.frame,void 0),await this.onWhisperFrame(t),S();case"relay_shape_poke":{const o=this.host.getWebSockets().length,n=Date.now(),{delivered:r,matched:a}=this.onShapePoke({...t,args:v(t.args)});return this.host.recordShapePokeFanout(o,r,Date.now()-n),r<a?Response.json({delivered:r,matched:a},{status:503}):S()}case"relay_shape_subscribe":return ce(this.onShapeSubscribe({...t,args:v(t.args)}));case"relay_shape_unsubscribe":return this.onShapeUnsubscribe(t),S();default:return ae(t)}}maxRelays(){return g(this.host.env(),"LUNORA_MAX_RELAYS",ne)}canAddressSiblings(){return this.siblingStub(this.roleId.ownerKey)!==void 0}siblingStub(e){return z(this.host.env(),this.bindingName(),e,this.host.shardJurisdiction())}bindingName(){return this.host.shardBinding()}async postRelayMessage(e,s){await this.requestRelayMessage(e,s)}async requestRelayMessage(e,s){const t=this.siblingStub(e);if(t===void 0)return;const o=JSON.stringify(s),n={"content-type":"application/json","x-lunora-shard-binding":this.host.shardBinding()??""},r=G(this.host.env());r!==void 0&&(n[L]=await J(r,o));try{return await t.fetch("https://relay.internal/_lunora/relay",{body:o,headers:n,method:"POST"})}catch{return}}}class he extends P{shapeUniformCache=new Map;relaySetCache;registryCache;recordedBinding;promotionState="owned";constructor(e,s){super(e,{ownerKey:s})}async forwardWhisper(e,s){if(!this.canAddressSiblings())return;const t=this.ownerRelaySet();t.size!==0&&await Promise.all([...t].map(o=>this.postRelayMessage(R(this.roleId.ownerKey,o),{frame:s,topic:e,type:"relay_frame"})))}async onFlush(e,s){this.canAddressSiblings()&&await Promise.all([this.multicastShapePokes(e,s),this.proxyShapePokes(e,s)])}seedRelayShape(){return Promise.resolve(void 0)}announce(){return Promise.resolve()}announceDrain(){return Promise.resolve()}releaseRelayShapes(){return Promise.resolve()}relayCount(){const e=this.host.getWebSockets().length,s=g(this.host.env(),"LUNORA_RELAY_THRESHOLD",T.tUp),t=g(this.host.env(),"LUNORA_RELAY_COLLAPSE_THRESHOLD",T.tDown);if(this.promotionState=B(this.promotionState,e,q(s,t)),this.promotionState==="owned")return 0;const o=g(this.host.env(),"LUNORA_RELAY_FAN",re);return Math.min(this.maxRelays(),Math.max(1,o))}minShapeCursor(){const{cohort:e,proxies:s}=this.relayShapes();let t;for(const o of[...e.values(),...s.values()])t=t===void 0?o.cursor:Math.min(t,o.cursor);return t}isShapeRelayUniform(e,s){const t=_(e,s),o=this.shapeUniformCache.get(t);if(o!==void 0)return o;const n=this.probeShapeRelayUniform(e,s);return this.shapeUniformCache.set(t,n),n}onShapeUnsubscribe(e){const{proxies:s}=this.relayShapes(),t=e.subId===void 0?void 0:M(e.relayIndex,e.connectionId,e.subId);for(const[o,n]of s)n.relayIndex!==e.relayIndex||n.connectionId!==e.connectionId||(t===void 0||o===t)&&s.delete(o);U(this.host.sql(),e.relayIndex,e.connectionId,e.subId)}onAttach(e){this.addRelayToSet(e)}onDetach(e){this.removeRelayFromSet(e)}async onWhisperFrame(e){await Promise.all([...this.ownerRelaySet()].filter(s=>s!==e.originRelay).map(s=>this.postRelayMessage(R(this.roleId.ownerKey,s),{frame:e.frame,topic:e.topic,type:"relay_frame"})))}onShapeSubscribe(e){return this.buildShapeSeedFrames(e)}onShapePoke(){return{delivered:0,matched:0}}buildShapePoke(e,s,t,o,n){let r;try{r=this.host.resolveShape(e.name,e.args,s)}catch{return}if(r===void 0||r.global===!0||!t.has(r.table))return;const a=e,h=a.cursor,c=this.host.buildShapeDiff(r,h,o);if(c.length!==0)return a.cursor=o,w(this.host.sql(),a.key,o),{args:N(e.args),checkpoint:o,epoch:n,fromCursor:h,name:e.name,rowsPatch:X(c),type:"relay_shape_poke"}}async multicastShapePokes(e,s){const t=this.ownerRelaySet();if(t.size===0)return;const{cohort:o}=this.relayShapes();if(o.size===0)return;const n=this.host.currentCdcEpoch(),r=[];for(const a of o.values()){const h=this.buildShapePoke(a,I,e,s,n);h&&r.push(this.multicastToRelays(t,h,a))}await Promise.all(r)}async multicastToRelays(e,s,t){(await Promise.all([...e].map(async n=>(await this.requestRelayMessage(R(this.roleId.ownerKey,n),s))?.ok===!0))).includes(!1)&&this.rewindShapeCursor(t,s.fromCursor)}async proxyShapePokes(e,s){if(this.ownerRelaySet().size===0)return;const{proxies:t}=this.relayShapes();if(t.size===0)return;const o=this.host.currentCdcEpoch(),n=[];for(const r of t.values()){const a=this.buildShapePoke(r,r.identity,e,s,o);a&&n.push(this.proxyToRelay(a,r))}await Promise.all(n)}async proxyToRelay(e,s){(await this.requestRelayMessage(R(this.roleId.ownerKey,s.relayIndex),{...e,targetConnectionId:s.connectionId}))?.ok!==!0&&this.rewindShapeCursor(s,e.fromCursor)}buildShapeSeedFrames(e){const s={identity:e.identity,userId:e.userId};let t;try{t=this.host.resolveShape(e.name,e.args,s)}catch(l){const{body:p}=k(l,{fallbackCode:"SHAPE_RESOLVE_FAILED",redactedMessage:"shape resolution failed"});return{error:{code:p.code,message:p.message}}}if(t===void 0||t.global===!0)return{error:{code:"SHAPE_NOT_FOUND",message:`shape not relayable: ${e.name}`}};e.relayIndex!==void 0&&this.addRelayToSet(e.relayIndex);const{baseCheckpoint:o,cursor:n,epoch:r,reset:a,rowsPatch:h}=this.host.computeOpLogShapeSeed({args:e.args,name:e.name,sinceEpoch:e.sinceEpoch,sinceSeq:e.sinceSeq},t);let c=n;const{cohort:d,proxies:E}=this.relayShapes();if(this.isShapeRelayUniform(e.name,e.args)){const l=_(e.name,e.args);let p=d.get(l);p===void 0&&(p={args:e.args,cursor:n,key:l,name:e.name},d.set(l,p),A(this.host.sql(),p)),c=p.cursor}else if(e.relayIndex!==void 0&&e.connectionId!==void 0){const l=M(e.relayIndex,e.connectionId,e.subId),p={args:e.args,connectionId:e.connectionId,cursor:n,identity:s,key:l,name:e.name,relayIndex:e.relayIndex};E.set(l,p),A(this.host.sql(),p)}else return{error:{code:"RELAY_SHAPE_UNROUTABLE",message:`shape ${e.name} is per-socket on a relay, but the subscribe carries no ${e.relayIndex===void 0?"relay index":"connection id"}`}};const u=O([{reset:a,rowsPatch:h,shapeId:e.subId}],{baseCheckpoint:o,checkpoint:c,epoch:r,lastMutationId:void 0,pokeId:this.host.nextPokeId()});return{cursor:c,epoch:r,frames:u}}ensureRelayTables(){this.host.sql().exec("CREATE TABLE IF NOT EXISTS __lunora_relays (idx INTEGER PRIMARY KEY)"),this.host.sql().exec("CREATE TABLE IF NOT EXISTS __lunora_relay_binding (id INTEGER PRIMARY KEY, binding TEXT NOT NULL)"),$(this.host.sql())}bindingName(){const e=this.host.shardBinding();if(e!==void 0&&e!=="")return e!==this.recordedBinding&&(this.recordedBinding=e,this.ensureRelayTables(),this.host.sql().exec("INSERT INTO __lunora_relay_binding (id, binding) VALUES (1, ?) ON CONFLICT(id) DO UPDATE SET binding = excluded.binding",e)),e;if(this.recordedBinding!==void 0)return this.recordedBinding;try{const s=this.host.sql().exec("SELECT binding FROM __lunora_relay_binding WHERE id = 1").toArray();this.recordedBinding=s[0]?.binding}catch{this.recordedBinding=void 0}return this.recordedBinding}relayShapes(){const e=this.registryCache;if(e!==void 0)return e;this.ensureRelayTables();const s={cohort:new Map,proxies:new Map};for(const t of K(this.host.sql()))t.relayIndex===void 0||t.connectionId===void 0?s.cohort.set(t.key,{args:t.args,cursor:t.cursor,key:t.key,name:t.name}):s.proxies.set(t.key,{args:t.args,connectionId:t.connectionId,cursor:t.cursor,identity:t.identity??{},key:t.key,name:t.name,relayIndex:t.relayIndex});return this.registryCache=s,s}rewindShapeCursor(e,s){const t=e;t.cursor<=s||(t.cursor=s,w(this.host.sql(),t.key,s))}ownerRelaySet(){if(this.relaySetCache===void 0){this.ensureRelayTables();const e=this.host.sql().exec("SELECT idx FROM __lunora_relays").toArray();this.relaySetCache=new Set(e.map(s=>Number(s.idx)))}return this.relaySetCache}addRelayToSet(e){this.ensureRelayTables(),this.host.sql().exec("INSERT OR IGNORE INTO __lunora_relays (idx) VALUES (?)",e),this.ownerRelaySet().add(e)}removeRelayFromSet(e){this.ensureRelayTables(),this.host.sql().exec("DELETE FROM __lunora_relays WHERE idx = ?",e);const s=this.ownerRelaySet();s.delete(e);const{cohort:t,proxies:o}=this.relayShapes();for(const[n,r]of o)r.relayIndex===e&&o.delete(n);Y(this.host.sql(),e),s.size===0&&(t.clear(),this.shapeUniformCache.clear(),W(this.host.sql()))}probeShapeRelayUniform(e,s){let t;try{t=this.host.resolveShape(e,s,I)}catch{return!1}if(t===void 0||t.global===!0||this.host.rlsMetadata().policies.some(c=>c.on==="read"&&c.table===t.table)||this.tableHasAnyMask(t.table))return!1;const o=b(t.effectiveWhere),n=b(t.columns);let r=!1;const a=c=>{const d={groups:[`grp_${c}`],roles:[c],sub:`__lunora_probe_${c}__`};return{identity:new Proxy(d,{get:(u,l)=>typeof l=="symbol"||l in u?Reflect.get(u,l):`${c}:${l}`,getOwnPropertyDescriptor:(u,l)=>(r=!0,Reflect.getOwnPropertyDescriptor(u,l)),has:(u,l)=>typeof l=="symbol"?Reflect.has(u,l):!0,ownKeys:u=>(r=!0,Reflect.ownKeys(u))}),ip:`__lunora_probe_${c}__`,userId:`__lunora_probe_${c}__`}};return[I,a("a"),a("b")].every(c=>{let d;try{d=this.host.resolveShape(e,s,c)}catch{return!1}return d!==void 0&&d.global!==!0&&d.table===t.table&&b(d.effectiveWhere)===o&&b(d.columns)===n})&&!r}tableHasAnyMask(e){return this.host.maskMetadata().columns.some(s=>s.table===e)}}class le extends P{relayAnnounced=!1;relayMemoCache;shapeControl=new Map;constructor(e,s,t){super(e,{ownerKey:s,relayIndex:t})}async forwardWhisper(e,s){this.canAddressSiblings()&&await this.postRelayMessage(this.roleId.ownerKey,{frame:s,originRelay:this.roleId.relayIndex,topic:e,type:"relay_frame"})}onFlush(){return Promise.resolve()}async seedRelayShape(e,s,t,o){if(!this.canAddressSiblings())return{code:"RELAY_MISCONFIGURED",message:"relay cannot address its owner"};const{connectionId:n}=this.host.readAttachment(e),r={args:N(t.args??{}),connectionId:n,identity:o.identity,name:t.name,relayIndex:this.roleId.relayIndex,sinceEpoch:t.sinceEpoch,sinceSeq:t.sinceSeq,subId:s,type:"relay_shape_subscribe",userId:o.userId},a=await this.queueShapeControl(n,async()=>(await this.announce(),this.requestRelayMessage(this.roleId.ownerKey,r)));if(a===void 0)return{code:"RELAY_SEED_FAILED",message:"owner did not answer the shape seed"};let h;try{h=await a.json()}catch{return{code:"RELAY_SEED_FAILED",message:"malformed shape seed from owner"}}if(h.error!==void 0)return h.error;if(h.frames===void 0)return{code:"RELAY_SEED_FAILED",message:"owner returned no shape frames"};await V(e);for(const c of h.frames)x(e,c);return this.recordRelayShapeMemo(e,s,h.cursor??0,h.epoch),"ok"}async announce(){if(this.relayAnnounced||!this.canAddressSiblings())return;this.relayAnnounced=!0,(await this.requestRelayMessage(this.roleId.ownerKey,{relayIndex:this.roleId.relayIndex,type:"relay_attach"}))?.ok||(this.relayAnnounced=!1)}async announceDrain(e){this.host.getWebSockets().some(s=>s!==e)||(this.relayMemos().clear(),oe(this.host.sql()),this.canAddressSiblings()&&(this.relayAnnounced=!1,await this.postRelayMessage(this.roleId.ownerKey,{relayIndex:this.roleId.relayIndex,type:"relay_detach"})))}async releaseRelayShapes(e,s){const{connectionId:t}=this.host.readAttachment(e);t!==void 0&&this.forgetRelayShapeMemos(t,s),!(t===void 0||!this.canAddressSiblings())&&await this.queueShapeControl(t,async()=>this.postRelayMessage(this.roleId.ownerKey,{connectionId:t,relayIndex:this.roleId.relayIndex,...s===void 0?{}:{subId:s},type:"relay_shape_unsubscribe"}))}relayCount(){return 0}isShapeRelayUniform(){return!1}minShapeCursor(){}onAttach(){}onDetach(){}onWhisperFrame(){return Promise.resolve()}onShapeSubscribe(){return{error:{code:"RELAY_CANNOT_SEED",message:"a relay has no op-log to seed from"}}}onShapeUnsubscribe(){}onShapePoke(e){return this.deliverShapePoke(e)}async queueShapeControl(e,s){if(e===void 0)return s();const t=(this.shapeControl.get(e)??Promise.resolve()).then(s,s),o={},n=()=>{this.shapeControl.get(e)===o.chain&&this.shapeControl.delete(e)},r=t.then(n,n);return o.chain=r,this.shapeControl.set(e,r),t}relayMemos(){return this.relayMemoCache===void 0&&(Q(this.host.sql()),this.relayMemoCache=Z(this.host.sql())),this.relayMemoCache}connectionMemos(e){const s=this.relayMemos();let t=s.get(e);return t===void 0&&(t=new Map,s.set(e,t)),t}recordRelayShapeMemo(e,s,t,o){const{connectionId:n}=this.host.readAttachment(e);n!==void 0&&(this.connectionMemos(n).set(s,{cursor:t,epoch:o}),C(this.host.sql(),[{connectionId:n,cursor:t,epoch:o,subId:s}]))}forgetRelayShapeMemos(e,s){if(s===void 0){this.relayMemos().delete(e),se(this.host.sql(),e);return}this.relayMemos().get(e)?.delete(s),te(this.host.sql(),e,s)}deliverShapePoke(e){const s=_(e.name,e.args),t=[];let o=0,n=0;for(const r of this.host.getWebSockets()){const{connectionId:a,shapes:h}=this.host.readAttachment(r);if(h===void 0||a===void 0||e.targetConnectionId!==void 0&&a!==e.targetConnectionId)continue;const c=this.pokeSocketShapes(r,h,this.connectionMemos(a),e,s);n+=c.matched.length,o+=c.sent;for(const d of c.matched)t.push({connectionId:a,cursor:e.checkpoint,epoch:e.epoch,subId:d})}return C(this.host.sql(),t),{delivered:o,matched:n}}pokeSocketShapes(e,s,t,o,n){const r=[];let a=0;for(const[h,c]of Object.entries(s)){const d=t.get(h);if(_(c.name,c.args)!==n||!ie(d,o))continue;const u=O([{baseCheckpoint:d?.cursor,rowsPatch:o.rowsPatch,shapeId:h}],{baseCheckpoint:void 0,checkpoint:o.checkpoint,epoch:o.epoch,lastMutationId:void 0,pokeId:this.host.nextPokeId()},{preEncoded:!0}).map(l=>x(e,l)).every(Boolean);t.set(h,{cursor:o.checkpoint,epoch:o.epoch}),r.push(h),u&&(a+=1)}return{matched:r,sent:a}}}const Ie=i=>{const e=i.doName();if(e===void 0)return;const s=H(e);return s===void 0?new he(i,e):new le(i,s.ownerKey,s.relayIndex)};export{ne as DEFAULT_MAX_RELAYS,he as OwnerRelay,le as RelayMember,Ie as createRelayLink};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{LunoraError as y}from"@lunora/errors";import{D as st}from"./MAX_TOKEN_LENGTH-BakL9FUy-B3VwYY8C.mjs";import{c as wn,S as pn,l as Le,a as gn}from"./ctx-db-companions-w-CfeOda.mjs";import{sql as i}from"drizzle-orm";import{d as $n}from"./wire-codec-C-FpWm52.mjs";import{throwingScheduler as yn,aggregateSqlFunction as ke,normalizeCountArgument as En}from"./AGGREGATE_SQL_FUNCTION-DDEoMnJR.mjs";import{aggregateTableName as Ve,encodeAggregateKey as ze,readAggregateValue as Je}from"./aggregateTableName-C7o-gpms.mjs";import{mergeWhere as V,CountRlsUnsupportedError as Ye,selectIndexForGroupBy as mn,selectIndexForCount as Sn,selectIndexForAggregate as _n}from"./CountRlsUnsupportedError-BvsDqfO2.mjs";import{backfillSearchIndexesForTable as Rn,searchIndexCoversTable as Tn}from"./backfillAggregateIndexes-BG5-SC1q.mjs";import{backfillAggregateIndexes as Mr,backfillRankIndexes as Dr,backfillSearchIndexes as Lr}from"./backfillAggregateIndexes-BG5-SC1q.mjs";import{appendCdcChange as vn}from"./CDC_LOG_TABLE-vVheEulD.mjs";import{CDC_LOG_TABLE as Fr,applyCdcChanges as qr,bumpCdcEpoch as Br,cdcCanVouchFor as Wr,cdcSeqLeavingRows as Ur,cdcTouchesTables as Pr,cdcTrimmedError as Gr,compactCdcDocs as Hr,cursorBelowRetainedFloor as Or,minCdcReplayableSeq as Nr,minCdcSeq as jr,readCdcChangeKeys as Kr,readCdcChanges as Qr,readCdcCursor as Vr,readCdcEpoch as zr,trimCdcChanges as Jr}from"./CDC_LOG_TABLE-vVheEulD.mjs";import{allocateCommitSeq as An,COMMIT_SEQ_FIELD as In}from"./COMMIT_SEQ_FIELD-BUdOMG5y.mjs";import{isMemoryTable as _t}from"./clearMemoryTables-BGbmag2i.mjs";import{computeRankPage as Rt}from"./computeRankPage-DsQ16o1z.mjs";import{SCAN_DEP as G}from"./SCAN_DEP-D7qE3iUe.mjs";import{runDrizzle as O,runSql as _e}from"./runDrizzle-2ULFQR_k.mjs";import{D as oe,k as ae,r as ue,b as Fe,A as Xe,a as qe,e as Z,o as Cn,t as jt,j as Ue,q as Tt,i as xn,h as Kt,g as bn}from"./do-sql-Dvj8Yl5N.mjs";import{renderSql as Qt,unionAll as ct,WORKERD_SQLITE_LIMITS as Vt,sqliteInList as Mn}from"./param-DlozcSQu.mjs";import{coveringGeohashes as Dn,boundingBoxGeohashes as Ln,haversineMeters as kn,pointInBoundingBox as Fn}from"./GEO_DEFAULT_PRECISION-CqpQZ-J_.mjs";import{NotFoundError as qn}from"./NotFoundError-BhF7FeFr.mjs";import{softDeleteScope as le,normalizeOrderKeys as nt,uniqueIndexFields as zt,equalityPinnedFields as Bn,buildSeekWhere as Jt,decodeCursor as ot,applySelect as vt,encodeCursor as rt,tiebreakDirectionFor as Yt,buildSeekBeforeWhere as Wn}from"./CURSOR_PREFIX-Bn8SFoGd.mjs";import{rankTableName as At,sortColumnName as It,resolveRankPartition as Un,encodePartitionKey as Pn,RANK_TIEBREAK as Gn,rankPivotConditionSql as Hn}from"./RANK_TIEBREAK-BXDiMmkH.mjs";import{UNVOUCHABLE_DEP as Ct}from"./UNVOUCHABLE_DEP-C68htACn.mjs";import{indexKeysForRow as On,buildIndexRange as Nn}from"./buildIndexRange-NtciKq3M.mjs";import{deriveRelationEdges as jn,findRelated as Kn}from"./RELATED_DEFAULT_LIMIT-B9PH28Pn.mjs";import{assertFlatPredicate as Ze,resolveRelationPredicates as xt}from"./DEFAULT_MAX_RELATION_KEYS-XESc7TiB.mjs";import{runRowValidators as et,resolveWith as bt,relationHooks as Mt,applyOnDelete as Qn,fanOutScalarCounts as Vn}from"./applyOnDelete-7JZ4vR9r.mjs";import{guardWriter as zn}from"./RLS_UNWRAP_SYMBOL-BwwTbz3Q.mjs";import{quoteIdentifier as Re}from"./quoteIdentifier-CObIFRhb.mjs";import{m as Jn}from"./sql-projection-BB2lCbYV.mjs";import{createSystemReader as Yn}from"./createSystemReader-DcDLFfC-.mjs";import{ConflictError as me}from"./ConflictError-C8GtJmjS.mjs";import{runTriggers as Xn}from"./hasTrigger-CjlwI4le.mjs";import{c as ne,t as Ge,r as Pe,j as Se,i as Dt}from"./where-sql-x1YKldcq.mjs";import{CLIENT_WATERMARK_TABLE as Xr,advanceClientWatermark as Zr,migrateClientWatermark as ei,readClientWatermark as ti}from"./CLIENT_WATERMARK_TABLE-CRnrAnJ2.mjs";import{GLOBAL_SHAPE_SNAPSHOT_TABLE as oi,deleteGlobalShapeSnapshot as ri,deleteGlobalShapeSnapshotsForConnection as ii,migrateGlobalShapeSnapshot as si,readGlobalShapeSnapshot as ci,writeGlobalShapeSnapshot as ai}from"./GLOBAL_SHAPE_SNAPSHOT_TABLE-DSA6mzyx.mjs";import{IDEMPOTENCY_TABLE as li,readIdempotent as ui,trimIdempotent as fi,writeIdempotent as hi}from"./IDEMPOTENCY_TABLE-DOpm_oMF.mjs";import{runShardMigrations as pi}from"./runShardMigrations-CeT_SVrI.mjs";import{S as $i}from"./ctx-db-search-state-ruTuCsxa.mjs";import{selectShapeMembers as Ei,selectShapeRows as mi}from"./selectShapeMembers-CCZyZggM.mjs";import{serializeSqlValue as re}from"./serializeSqlValue-CjbhIHjJ.mjs";const Zn=o=>{const r=atob(o),t=Uint8Array.from(r,a=>a.codePointAt(0)??0);return new TextDecoder().decode(t)},eo=()=>new y("BAD_REQUEST","invalid cursor"),Lt=16,kt=8,Y=1024,at=(o,r)=>r.query(o),to=(o,r)=>{if(o.length===0)return 0;let t=0;for(const[a,d]of r.entries()){const w=a===r.length-1;let S=0;for(const R of o)(w?R.startsWith(d):R===d)&&(S+=1);if(S===0)return 0;t+=S}return t},no=(o,r)=>{if(!r)return{exact:!0,lower:o,upper:o};const t=[...o].at(-1)??"",a=(t.codePointAt(0)??0)+1;if(a>=55296&&a<=57343||a>1114111)return{exact:!0,lower:o,upper:o};const d=o.slice(0,o.length-t.length);return{exact:!1,lower:o,upper:d+String.fromCodePoint(a)}},oo=(o,r,t)=>{const a={eq:(d,w)=>{if(!o.definition.filterFields?.includes(d))throw new y("INTERNAL",`field "${d}" is not a filter field of search index "${o.indexName}" on table "${r}"`);if(o.filters.length>=kt)throw new y("BAD_REQUEST",`search index "${o.indexName}" on table "${r}": at most ${String(kt)} .eq() filters are supported per search query`);return o.filters.push({field:d,value:w}),a},search:(d,w)=>{const S=o;if(d!==S.definition.field)throw new y("INTERNAL",`search index "${S.indexName}" on table "${r}" indexes "${S.definition.field}", not "${d}"`);const R=at(w,t).length;if(R>Lt)throw new y("BAD_REQUEST",`search index "${S.indexName}" on table "${r}": at most ${String(Lt)} search terms are supported (got ${String(R)})`);return S.field=d,S.query=w,S.hasQuery=!0,a}};return a},ro=o=>{if(o.length>Y)throw new y("BAD_REQUEST",`more than ${String(Y)} documents match this search — narrow it with filters or read it a page at a time with .paginate()`)},io=o=>Math.min(o.offset+o.numItems+1,Y),so=o=>btoa(`search:${String(o)}`),co=o=>{let r;try{r=Zn(o)}catch{return}if(!r.startsWith("search:"))return;const t=Number(r.slice(7));return Number.isInteger(t)&&t>=0?t:void 0},ao=o=>{if(typeof o.endCursor=="string")throw new y("BAD_REQUEST","bounded (endCursor) pagination is not supported on search queries — relevance order has no stable range boundary");if(!Number.isFinite(o.numItems))throw new y("BAD_REQUEST",`search pagination needs a finite numItems, got ${String(o.numItems)}`);const r=Math.max(0,Math.floor(o.numItems)),t=o.cursor?co(o.cursor):0;if(t===void 0)throw eo();if(t+r>=Y)throw new y("BAD_REQUEST",`search pagination reaches the ${String(Y)}-document limit (offset ${String(t)} + ${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,Y-t-1))} or fewer, or narrow the query or the filters instead`);return{numItems:r,offset:t}},lo=(o,r)=>{const t=r.offset+r.numItems,a=r.numItems>0&&o.length>t;return{continueCursor:a?so(t):null,isDone:!a,page:o.slice(r.offset,t)}},uo=o=>{if(o===void 0)return Y+1;if(!Number.isFinite(o))return Y;const r=Math.max(0,Math.floor(o));if(r>Y)throw new y("BAD_REQUEST",`search returns at most ${String(Y)} documents (asked for ${String(r)}) — narrow the query or paginate instead`);return r},He=o=>{const r=new Map;return t=>{const a=r.get(t);if(a!==void 0)return a;const d=o(Re(t));return r.set(t,d),d}},fe=Re(oe),fo=He(o=>`INSERT INTO ${o} (id, _creationTime, ${fe}) VALUES (?, ?, ?)`),Ft=He(o=>`UPDATE ${o} SET ${fe} = ? WHERE id = ? AND ${fe} = ?`),ho=He(o=>`UPDATE ${o} SET _creationTime = ?, ${fe} = ? WHERE id = ? AND ${fe} = ?`),wo=He(o=>`DELETE FROM ${o} WHERE id = ? AND ${fe} = ?`),po="SELECT changes() AS changed",qt=new Map,go="",$o=o=>{const r=JSON.stringify(o),t=qt.get(r);if(t!==void 0)return t;const a=o.map(w=>i`SELECT ${i.raw(`'${w.replaceAll("'","''")}'`)} AS __t__, id, _creationTime, ${i.identifier(oe)} FROM ${i.identifier(w)} WHERE id = ${go}`),{sql:d}=Qt("sqlite",i`${ct(a)} LIMIT 1`);return qt.set(r,d),d},yo=(o,r)=>r.map(()=>o),Eo=/^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/iu,mo=o=>{if(!Eo.test(o))throw new y("INTERNAL",`invalid clientId ${JSON.stringify(o)}: a client-supplied row id must be a UUID`)},Bt=50,Xt=500,Be=Math.floor(Vt.boundParams/3),ye=Vt.boundParams,So=128,de=(o,r,t)=>{const a=r??Xt;if(o>a)throw new y("BATCH_LIMIT_EXCEEDED",`${t}: batch of ${String(o)} exceeds the limit of ${String(a)} (raise options.limit or chunk the call)`,{status:400})},_o=o=>{const r={eq:(t,a)=>(o.sqlConditions.push({comparator:"=",field:t,value:a}),r),gt:(t,a)=>(o.sqlConditions.push({comparator:">",field:t,value:a}),r),gte:(t,a)=>(o.sqlConditions.push({comparator:">=",field:t,value:a}),r),lt:(t,a)=>(o.sqlConditions.push({comparator:"<",field:t,value:a}),r),lte:(t,a)=>(o.sqlConditions.push({comparator:"<=",field:t,value:a}),r)};return r},Ro=o=>Math.max(o,Y),Zt=(o,r)=>{const t=o.filters.map(a=>i`${Z(a.field)} = ${re(a.value)}`);return r&&t.push(r),t},To=(o,r,t,a,d)=>{const w=at(t.query,st(t.definition.language));if(w.length===0)return[];const S=pn(r,t.indexName),R=`${S}__vocab`,E=w.length-1,k=w.map((q,_)=>{const F=no(q,_===E),j=F.exact?i`${i.identifier("term")} = ${F.lower}`:i`${i.identifier("term")} >= ${F.lower} AND ${i.identifier("term")} < ${F.upper}`;return i`SELECT ${i.identifier("doc")}, ${i.raw(String(_))} AS ${i.identifier("__term__")}, COUNT(*) AS ${i.identifier("__n__")} FROM ${i.identifier(R)} WHERE ${j} GROUP BY ${i.identifier("doc")}`}),$=w.map((q,_)=>i`SUM(CASE WHEN u.${i.identifier("__term__")} = ${i.raw(String(_))} THEN u.${i.identifier("__n__")} ELSE 0 END)`),v=i`SELECT f.${i.identifier(Le)} AS ${i.identifier(Le)}, ${i.join($,i` + `)} AS ${i.identifier("__score__")} FROM (${ct(k)}) u JOIN ${i.identifier(S)} f ON f.rowid = u.${i.identifier("doc")} GROUP BY f.${i.identifier(Le)} HAVING ${i.join($.map(q=>i`${q} > 0`),i` AND `)}`,A=Zt(t,d);let L=i`SELECT m.id, m._creationTime, m.${i.identifier(oe)}, s.${i.identifier("__score__")} AS ${i.identifier("__score__")} FROM (${v}) s JOIN ${i.identifier(r)} m ON m.id = s.${i.identifier(Le)}`;A.length>0&&(L=i`${L} WHERE ${i.join(A,i` AND `)}`),L=i`${L} ORDER BY s.${i.identifier("__score__")} DESC, m._creationTime DESC, m.id ASC LIMIT ${i.raw(String(a))}`;const N=[];for(const q of O(o,L)){const _=Kt(q);if(_){const F=q.__score__;N.push({document:_,score:typeof F=="number"?F:Number(F??0)})}}return N},vo=(o,r,t,a,d)=>{const w=st(t.definition.language),S=at(t.query,w);if(S.length===0)return[];const R=Zt(t,d);let E=i`SELECT id, _creationTime, ${i.identifier(oe)} FROM ${i.identifier(r)}`;R.length>0&&(E=i`${E} WHERE ${i.join(R,i` AND `)}`),E=i`${E} ORDER BY _creationTime DESC, id ASC LIMIT ${i.raw(String(Ro(a)))}`;const k=O(o,E).toArray(),$=[];for(const v of k){const A=Kt(v);if(!A)continue;const L=to(gn(A,t.definition),S);L>0&&$.push({creationTime:typeof A._creationTime=="number"?A._creationTime:0,doc:A,id:typeof A._id=="string"?A._id:"",score:L})}return $.sort((v,A)=>A.score-v.score||A.creationTime-v.creationTime||v.id.localeCompare(A.id)),$.slice(0,a).map(v=>({document:v.doc,score:v.score}))},tt=(o,r,t,a)=>{if(!Number.isFinite(o.lat)||o.lat<-90||o.lat>90||!Number.isFinite(o.lng)||o.lng<-180||o.lng>180)throw new y("BAD_REQUEST",`geo index "${a}" on table "${t}": ${r} must have a finite lat in [-90, 90] and lng in [-180, 180]`)},Ao=(o,r)=>{const t=o,a={near:(d,w)=>{if(t.within)throw new y("INTERNAL",`geo index "${t.indexName}" on table "${r}": call .near() or .within(), not both`);if(tt(d,".near() point",r,t.indexName),!Number.isFinite(w)||w<=0)throw new y("BAD_REQUEST",`geo index "${t.indexName}" on table "${r}": .near() radiusMeters must be a finite number > 0, got ${String(w)}`);return t.near={point:{lat:d.lat,lng:d.lng},radiusMeters:w},a},within:d=>{if(t.near)throw new y("INTERNAL",`geo index "${t.indexName}" on table "${r}": call .near() or .within(), not both`);if(tt(d.sw,".within() sw corner",r,t.indexName),tt(d.ne,".within() ne corner",r,t.indexName),d.sw.lat>d.ne.lat)throw new y("BAD_REQUEST",`geo index "${t.indexName}" on table "${r}": .within() corners are transposed (sw.lat > ne.lat)`);if(d.sw.lng>d.ne.lng)throw new y("BAD_REQUEST",`geo index "${t.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 t.within={ne:{lat:d.ne.lat,lng:d.ne.lng},sw:{lat:d.sw.lat,lng:d.sw.lng}},a}};return a},Io=(o,r)=>{const t=o[r];if(t===null||typeof t!="object")return;const{lat:a,lng:d}=t;return typeof a=="number"&&typeof d=="number"?{lat:a,lng:d}:void 0},Co=(o,r)=>{const t=Io(o,r.definition.field);if(!t)return;const a=typeof o._creationTime=="number"?o._creationTime:0;if(r.near){const d=kn(r.near.point,t);return d<=r.near.radiusMeters?{creationTime:a,distance:d}:void 0}return Fn(t,r.within)?{creationTime:a,distance:0}:void 0},xo=(o,r,t,a)=>{if(!t.near&&!t.within)throw new y("INTERNAL",`geo index "${t.indexName}" on table "${r}": call .near(point, radius) or .within(box)`);const d=t.near?Dn(t.near.point,t.near.radiusMeters):Ln(t.within),w=bn(r,t.indexName),S=d.map(v=>i`(g.${i.identifier("__geohash__")} >= ${v} AND g.${i.identifier("__geohash__")} < ${`${v}{`})`),R=[i`(${i.join(S,i` OR `)})`];a&&R.push(a);const E=i`SELECT m.id, m._creationTime, m.${i.identifier(oe)} FROM ${i.identifier(w)} g JOIN ${i.identifier(r)} m ON m.id = g.${i.identifier("__id__")} WHERE ${i.join(R,i` AND `)}`,k=O(o,E).toArray(),$=[];for(const v of k){const A=ue(v),L=A?Co(A,t):void 0;A&&L&&$.push({creationTime:L.creationTime,distance:L.distance,doc:A})}return $.sort((v,A)=>v.distance-A.distance||A.creationTime-v.creationTime),$},en=(o,r,t,a)=>{const d=[];for(const w of o)if(r.every(S=>S(a(w)))&&(d.push(w),typeof t=="number"&&d.length>=t))break;return d},bo=(o,r,t,a,d,w=()=>{})=>{const S=t.within!==void 0,R=xo(o,r,t,d).map(E=>({distanceMeters:S?null:E.distance,document:E.doc}));return w(R.length),typeof a=="number"?R.slice(0,Math.max(0,Math.floor(a))):R},tn=(o,r,t,a,d,w=()=>{})=>{const{geo:S}=t;if(!S)throw new y("INTERNAL","runGeoTerminalScored called without a staged geo query");const R=t.inMemoryFilters.length>0,E=bo(o,r,S,R?void 0:d,a,w);return R?en(E,t.inMemoryFilters,d,k=>k.document):E},nn=(o,r,t,a)=>{const d=`SELECT id, _creationTime, ${Re(oe)} FROM ${Re(o)}`,w=`ORDER BY ${t}${a===void 0?"":` LIMIT ${String(a)}`}`;return r===void 0?Pe(`${d} ${w}`):Se(`${d} WHERE `,r,` ${w}`)},Mo=(o,r,t,a,d,w=()=>{})=>tn(o,r,t,a,d,w).map(S=>S.document),Do=(o,r,t,a,d,w,S=()=>{})=>{const R=[];for(const v of t.sqlConditions)R.push(i`${Z(v.field)} ${i.raw(v.comparator)} ${re(v.value)}`);a&&R.push(a);let E=i`SELECT id, _creationTime, ${i.identifier(oe)} FROM ${i.identifier(r)}`;R.length>0&&(E=i`${E} WHERE ${i.join(R,i` AND `)}`),E=i`${E} ORDER BY ${d}`,typeof w=="number"&&t.inMemoryFilters.length===0&&(E=i`${E} LIMIT ${i.raw(String(Math.max(0,Math.floor(w))))}`);const k=O(o,E).toArray();S(k.length);const $=[];for(const v of k){const A=ue(v);if(A&&t.inMemoryFilters.every(L=>L(A))&&($.push(A),typeof w=="number"&&$.length>=w))break}return $},Ee={fieldRef:Z,serialize:re},on=(o,r)=>{const t=r===void 0?void 0:o.shape[r];return t!==void 0&&Jn(t)},Wt=(o,r)=>r.some(t=>on(o,t)),Ut=(o,r,t)=>{if(on(o,r))throw new y("BAD_REQUEST",`${t}: "${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)`)},dt={fieldRef:o=>Pe(Ue(o)),serialize:re},Lo=o=>{let r=0;const t=[],a={fieldRef:d=>Pe(Ue(d)),relationExists:d=>{const{childWhere:w,negated:S,parentTable:R,relation:E}=d,k=`__rel_${String(r)}`,$=t.at(-1)??R;r+=1,o(E.table,G);const v=E.kind==="one"?E.field:E.references,A=E.kind==="one"?E.references:E.field,L=Pe(`${Tt(k,A)} = ${Tt($,v)}`);t.push(k);const N=ne(w,a,Ge);t.pop();const q=N===void 0?L:Se(L," AND ",N),_=Se("EXISTS (SELECT 1 FROM ",Dt(E.table)," AS ",Dt(k)," WHERE ",q,")");return S?Se("NOT ",_):_},serialize:re};return a},rn=o=>{const r=o.map(t=>`${Ue(t.field)} ${t.direction==="desc"?"DESC":"ASC"}`);return o.some(t=>t.field==="_id"||t.field==="id")||r.push(`${Ue("id")} ${Yt(o)==="desc"?"DESC":"ASC"}`),r.join(", ")},ko=o=>{const r=o.map(t=>i`${Z(t.field)} ${i.raw(t.direction==="desc"?"DESC":"ASC")}`);return o.some(t=>t.field==="_id"||t.field==="id")||r.push(i`${Z("id")} ${i.raw(Yt(o)==="desc"?"DESC":"ASC")}`),i.join(r,i`, `)},Fo={"<":"lt","<=":"lte","=":"eq",">":"gt",">=":"gte"},sn=o=>new Set(o.sqlConditions.filter(r=>r.comparator==="=").map(r=>r.field)),qo=o=>{const r=sn(o);let t=0;for(;t<o.indexFields.length&&r.has(o.indexFields[t]??"");)t+=1;return o.indexFields.slice(t)},cn=(o,r)=>{const t=o.order,a=qo(o),{shape:d}=r;return a.length>0?nt(a.map(w=>({[w]:t})),d,{pinned:sn(o),uniqueBy:zt(r.indexes,d)}):nt([{_creationTime:t}],d)},Bo=(o,r,t,a)=>{const d=o.sqlConditions.map(w=>({[w.field]:{[Fo[w.comparator]??"eq"]:w.value}}));if(t&&d.push(Jt(r,ot(t))),a&&d.push(Wn(r,ot(a))),d.length!==0)return d.length===1?d[0]:{AND:d}},Wo=(o,r,t)=>{const a=[];for(const d of o){const w=ue(d);if(w&&r.every(S=>S(w))&&(a.push(w),t!==void 0&&a.length>t))break}return a},Uo=(o,r,t,a,d,w,S=()=>{})=>{const R=Math.max(0,Math.floor(d.numItems)),E=cn(a,t),k=typeof d.endCursor=="string",$=ne(Bo(a,E,d.cursor,d.endCursor),dt,Ge),v=w&&$?Se($," AND ",w):w??$,A=a.inMemoryFilters.length>0,L=nn(r,v,rn(E),A||k?void 0:R+1),N=_e(o,L.text,...L.params).toArray();S(N.length);const q=Wo(N,a.inMemoryFilters,A||k?void 0:R);if(k){const H=q.length>=2?q[Math.floor(q.length/2)-1]:void 0;return{continueCursor:d.endCursor??null,isDone:!0,page:q,splitCursor:H?rt(H,E):null}}const _=q.length>R,F=_?q.slice(0,R):q,j=F.at(-1);return{continueCursor:_&&j?rt(j,E):null,isDone:!_,page:F}};class Po extends y{constructor(r="unique() found more than one matching document"){super("NOT_UNIQUE",r,{name:"NotUniqueError"})}}const Go=/\s/u,Ho=String.fromCodePoint(0),Pt=(o,r,t)=>{if(!o.tables[r])throw new y("INTERNAL",`unknown table: ${r}`);return typeof t!="string"||t.length===0||Go.test(t)||t.includes(Ho)?null:t},Oo=(o,r,t,a=()=>{},d=()=>{},w=()=>{})=>{const S=r.tables[t];if(!S)throw new y("INTERNAL",`unknown table: ${t}`);const R=le(S.softDeleteMode,void 0),E=R?ne(R,Ee):void 0,k=R?ne(R,dt,Ge):void 0,$={indexFields:[],indexName:void 0,inMemoryFilters:[],order:"asc",sqlConditions:[]};let v=0;const A=m=>{const{search:C}=$;if(!C)throw new y("INTERNAL","runSearchFetch called without a staged search");Rn(o,t,S);const x=$.inMemoryFilters.length>0,D=uo(x?void 0:m),z=xn(o);if(z&&!Tn(o,t,C.definition))throw new y("SEARCH_INDEX_BUILDING",`search index "${C.indexName}" on table "${t}" 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 X=z?To(o,t,C,D,E):vo(o,t,C,D,E);return x?(v=X.length,en(X,$.inMemoryFilters,m,ce=>ce.document)):(m===void 0&&ro(X),X)},L=m=>A(m).map(C=>C.document),N=m=>{const C=ao(m);return lo(L(io(C)),C)},q=()=>ko(cn($,S)),_=()=>{if($.search||$.geo||$.indexName===void 0){d(void 0);return}d(Nn(t,$.indexName,$.indexFields,$.sqlConditions,re))},F=m=>{_();let C=0;const x=(()=>{if($.search){const D=L(m);return C=v,D}return $.geo?Mo(o,t,$,E,m,D=>{C=D}):Do(o,t,$,E,q(),m,D=>{C=D})})();return w(Math.max(C,x.length)),x},j=()=>{if(!$.search&&!$.geo)throw new y("INTERNAL",`ctx.db.query("${t}").collectWithScores() requires a staged .withSearchIndex(...) or .withGeoIndex(...)`);_();let m=0;const C=(()=>{if($.search){const x=A(void 0);return m=v,x}return tn(o,t,$,E,void 0,x=>{m=x})})();return w(Math.max(m,C.length)),C},H={async*[Symbol.asyncIterator](){if($.search){yield*F(void 0);return}const m=[...$.inMemoryFilters];let C;$.inMemoryFilters=[];try{for(;;){const x=await H.paginate({cursor:C??null,numItems:So});for(const D of x.page)m.every(z=>z(D))&&(yield D);if(x.isDone||x.continueCursor===null)return;C=x.continueCursor}}finally{$.inMemoryFilters=m}},async collect(){return F(void 0)},async collectWithScores(){return j()},filter(m){return $.inMemoryFilters.push(m),H},async first(){return F($.inMemoryFilters.length>0?void 0:1)[0]??null},order(m){return $.order=m==="desc"?"desc":"asc",H},async paginate(m){let C=0;if(_(),$.search){const D=N(m);return w(D.page.length),D}if($.geo)throw new y("INTERNAL","pagination is not supported on geo queries; use .take(n) or .collect()");const x=Uo(o,t,S,$,m,k,D=>{C=D});return w(Math.max(C,x.page.length)),x},async take(m){return F(m)},async unique(){const m=F($.inMemoryFilters.length>0?void 0:2);if(m.length>1)throw new Po(`unique() on table "${t}" matched ${String(m.length)} documents; expected at most one`);return m[0]??null},withGeoIndex(m,C){const x=(S.geoIndexes??[]).find(z=>z.name===m);if(!x)throw new y("INTERNAL",`unknown geo index "${m}" on table "${t}"`);a(t,m,"geo");const D={definition:x,indexName:m};if($.geo=D,C(Ao(D,t)),!D.near&&!D.within)throw new y("INTERNAL",`geo index "${m}" on table "${t}" requires a .near(point, radius) or .within(box) call`);return H},withIndex(m,C){const x=S.indexes.find(D=>D.name===m);if(!x)throw new y("INTERNAL",`unknown index "${m}" on table "${t}"`);return a(t,m,"index"),$.indexName=m,$.indexFields=x.fields,C&&C(_o($)),H},withSearchIndex(m,C){const x=(S.searchIndexes??[]).find(z=>z.name===m);if(!x)throw new y("INTERNAL",`unknown search index "${m}" on table "${t}"`);a(t,m,"search");const D={definition:x,field:x.field,filters:[],hasQuery:!1,indexName:m,query:""};if($.search=D,C(oo(D,t,st(x.language))),!D.hasQuery)throw new y("INTERNAL",`search index "${m}" on table "${t}" requires a .search(field, query) call`);return H}};return H},Gt=(o,r,t)=>{const a={...r};for(const[d,w]of jt(o)){if(w.serverDefault){a[d]=w.serverDefault({auth:t});continue}a[d]===void 0&&(w.defaultFn?a[d]=w.defaultFn():"defaultValue"in w&&(a[d]=w.defaultValue))}return a},Ht=(o,r,t,a)=>{const d=t;for(const[w,S]of jt(o)){if(S.serverDefault){w in r&&(d[w]=S.serverDefault({auth:a}));continue}S.onUpdateFn&&!(w in r)&&(d[w]=S.onUpdateFn())}},Ot=(o,r)=>{for(const t of Object.keys(r))if(r[t]===void 0)throw new y("INTERNAL",`Cannot ${o} field '${t}' to undefined — use null to clear a nullable field, or omit the key to leave it unchanged.`)},No=/unique constraint failed/i,jo=o=>o instanceof Error&&No.test(o.message),Ko=/string or blob too big/iu,Qo=(o,r)=>{if(!(!(o instanceof Error)||!Ko.test(o.message)))throw new y("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.`)},it=(o,r,t,a)=>{try{_e(o,t,...a)}catch(d){throw jo(d)?new me(`unique constraint violation on "${r}"`,"unique"):(Qo(d,r),d)}},We=(o,r,t,a)=>{if(it(o,r,t,a),_e(o,po).one().changed===0)throw new me(`optimistic concurrency conflict on "${r}" — the row changed during this mutation; refetch and retry`,"occ")},Nt=(o,r,t,a,d,w,S)=>{const R=[];for(let v=0;v<t.length+1;v+=1){const A=t[v],L=a[v],N=L?.direction==="desc"?"desc":"asc",q=A===void 0||L===void 0?i`${i.identifier(Gn)} < ${S}`:Hn(A,w[v],N,!1);if(q===void 0)continue;const _=[];for(let j=0;j<v;j+=1)_.push(i`${i.identifier(t[j])} IS ${w[j]}`);_.push(q);const[F]=_;R.push(_.length===1&&F!==void 0?F:i`(${i.join(_,i` AND `)})`)}const E=R.length>0?i.join(R,i` OR `):i`1 = 0`,k=O(o,i`SELECT COUNT(*) AS c FROM ${i.identifier(r)} WHERE ${i.identifier("__partition__")} = ${d} AND (${E})`).one(),$=O(o,i`SELECT COUNT(*) AS c FROM ${i.identifier(r)} WHERE ${i.identifier("__partition__")} = ${d}`).one();return{before:k.c,total:$.c}},Cr=o=>{const{sql:r}=o,{schema:t}=o,a=o.broadcast??(()=>{}),d=jn(t);let w;const S=()=>o.inTransaction?.()===!0,R=e=>t.tables[e]?.commitOrderedMode!==!0?{}:((w===void 0||!S())&&(w=An(r)),{[In]:w}),E=(e,...n)=>{const s=t.tables[e]?.indexes;if(!s||s.length===0)return;const f=[];for(const h of n)h&&f.push(...On(s,h,re));return f.length>0?f:void 0},{headroom:k}=o;let $=!1;const v=async e=>{const n=$;$=!0;try{return await e()}finally{$=n}},A=o.onRead??(()=>{}),L=e=>{_t(t.tables[e])&&A(Ct,Ct)},N=o.onReadRange??(e=>{A(e.table,G)}),q=e=>{L(e.table),N(e)},_=(e,n)=>{n!==void 0&&n!==G&&!$&&k?.recordRead(1),L(e),A(e,n)},F=o.onIndexUse??(()=>{}),j=o.onWrite??(()=>{}),H=e=>{$||k?.recordWrite(e)},m=async e=>{H(e.doc),await j(e)},{cache:C}=o,x=o.clock??(()=>Date.now()),D=o.idGenerator??(()=>crypto.randomUUID()),z=o.scheduler??yn,{globalDb:X}=o,ce=o.auth??{identity:null,userId:null},an=o.cdc??!1,Oe=z,dn=Yn({scheduler:typeof Oe.list=="function"&&typeof Oe.get=="function"?Oe:void 0,storage:o.storage}),he=(e,n,s,f)=>{an&&!_t(t.tables[e])&&vn(r,x(),e,n,s,f)},ie=e=>t.tables[e]?.shardMode?.kind==="global",lt=(e,n)=>{if(ie(e)){if(!X)throw new y("INTERNAL",`cross-backend ${n} for global table '${e}' requires a globalDb writer — pass one to createShardCtxDb({ globalDb })`);return X}return W},Ne=e=>lt(e,"cascade"),Q=(e,n)=>{if(ie(e)){if(!X)throw new y("INTERNAL",`${n} on global table '${e}' requires a globalDb writer — pass one to createShardCtxDb({ globalDb })`);return X}},ut=async(e,n,s,f,h)=>{h&&H(s);const u=await e.insert(n,s,f);return a({key:u,op:"insert",row:{...s,_id:u},table:n}),u},je=(e,n)=>lt(e,"relation load").findMany(e,n),ft=(e,n)=>(ie(e)&&_(e,G),je(e,n)),ln=e=>!ie(e.table),ht=o.relationExistsPushDown??"auto",wt=ht!=="never",{maxRelationKeys:pt}=o,Te=(e,n,s)=>xt(e,{fetcher:ft,maxRelationKeys:pt,relationBaseWhere:s,schema:t,tableName:n}),gt=async(e,n,s,f)=>{const h=Q(e,"relation grouped count");if(h)return _(e,G),Vn((B,I)=>h.count(B,I),e,n,s,f);const u=t.tables[e];if(!u)throw new y("INTERNAL",`unknown table: ${e}`);_(e,G);const c=le(u.softDeleteMode,void 0),l={[n]:{in:s}},p=V(V(l,f),c),T=await Te(p,e,void 0),g=ne(T,Ee),M=Z(n);let b=i`SELECT ${M} AS __fk__, COUNT(*) AS count FROM ${i.identifier(e)}`;g&&(b=i`${b} WHERE ${g}`),b=i`${b} GROUP BY ${M}`;const P=O(r,b).toArray();return new Map(P.map(B=>[B.__fk__,B.count]))};let ve=0;const $t=new Set;for(const[e,n]of Object.entries(t.tables))for(const s of Object.values(n.triggerMap??{}))$t.add(`${e} ${s.timing} ${s.op}`);const ee=(e,n,s)=>$t.has(`${e} ${n} ${s}`),te=async(e,n,s)=>{if(ve+=1,ve>Bt)throw ve-=1,new me(`trigger recursion exceeded ${String(Bt)} levels on "${s.table}" — check for a self-triggering write`,"trigger");try{await Xn({ctx:fn,event:s,op:n,schema:t,tableName:s.table,timing:e})}finally{ve-=1}},{ensureBackfilledForTable:we,ensureBackfilledIndex:Ke,ensureRankBackfilled:Qe,ensureRankBackfilledForTable:pe,syncAggregates:Ae,syncCompanionsForInsert:yt,syncGeo:Ie,syncRanks:ge,syncSearch:Ce}=wn({broadcast:a,indexKeysFor:(e,n)=>E(e,n),invalidateCache:(e,n,s)=>C?.invalidate(e,n,E(e,s)),recordCdc:he,schema:t,sql:r}),Et=(e,n,s)=>{const{shardMode:f}=n;if(f?.kind==="shardBy"&&!(f.field!==void 0&&(s.partitionBy??[]).includes(f.field)))throw Object.assign(new Error(`rank index "${s.name}" on "${e}" partitions across shards (shard key "${f.field??"?"}" is not in partitionBy) — a shard-local rank()/rankPage() would be wrong; roll it up through the Query Coordinator instead`),{code:"CROSS_SHARD_RANK_UNSUPPORTED",name:"LunoraError",status:400})},mt=e=>Object.entries(t.tables).filter(([,n])=>n.shardMode?.kind!=="global").map(([n])=>n).filter(n=>e===void 0||n===e),$e=e=>e===void 0||ie(e)?X:void 0,se=(e,n)=>{const s=mt(n);for(let f=0;f<s.length;f+=ye){const h=s.slice(f,f+ye),[u]=_e(r,$o(h),...yo(e,h)).toArray();if(!u)continue;const c=u.__t__,l=ue(u);if(typeof c!="string"||!l)return;const p=u[oe];return{docJson:typeof p=="string"?p:ae(p??{}),row:l,tableName:c}}},un=(e,n)=>{const s=[...new Set(e)],f=new Map;if(s.length===0)return f;const h=mt(n);for(let u=0;u<h.length;u+=ye){const c=h.slice(u,u+ye),l=Math.floor(ye/c.length),p=Mn(i`${i.identifier("id")}`,s,!1,l),T=c.map(g=>i`SELECT ${i.raw(`'${g.replaceAll("'","''")}'`)} AS __t__, id FROM ${i.identifier(g)} WHERE ${p}`);for(const g of O(r,ct(T))){const{id:M,__t__:b}=g;typeof b=="string"&&typeof M=="string"&&f.set(M,b)}}return f},St={assertRankPartitionLocal:Et,ensureRankBackfilled:Qe,onRead:_,rowToDocument:ue,schema:t,sql:r},W={system:dn,async aggregate(e,n){const s=Q(e,"aggregate");if(s)return _(e,G),s.aggregate(e,n);const f=t.tables[e];if(!f)throw new y("INTERNAL",`unknown table: ${e}`);if(ke(n.op),n.op==="count")return W.count(e,{baseWhere:n.baseWhere,relationBaseWhere:n.relationBaseWhere,restrictsCounts:n.restrictsCounts,where:n.where});if(!n.field)throw new y("INTERNAL",`aggregate(${e}, { op: "${n.op}" }): "field" is required for non-count reducers`);_(e,G);const h=le(f.softDeleteMode,void 0),u=V(V(n.baseWhere,n.where),h),c=await Te(u,e,n.relationBaseWhere),l=c!==u;if(f.aggregateIndexes&&!n.baseWhere&&!l&&(!h||Wt(f,[n.field]))){const B=_n(f.aggregateIndexes,n.op,n.field,n.where);if(B){Ke(e,B.index);const I=ze(B.index.by??[],B.key),K=Ve(e,B.index.name),J=O(r,i`SELECT ${Fe} AS value, ${Xe} AS count FROM ${i.identifier(K)} WHERE ${qe} = ${I}`).toArray()[0];return Je(n.op,J)}}Ut(f,n.field,`aggregate(${e}, { op: "${n.op}", field: "${n.field}" })`);const p=ne(c,Ee),T=ke(n.op),g=Z(n.field);let M=i`SELECT ${i.raw(T)}(${g}) AS value FROM ${i.identifier(e)}`;p&&(M=i`${M} WHERE ${p}`);const P=O(r,M).toArray()[0]?.value;return P??null},asId(e,n){const s=Pt(t,e,n);if(s===null)throw new y("BAD_REQUEST",`asId("${e}", …): "${n}" is not a valid id for table "${e}"`,{status:400});return s},async count(e,n){const s=Q(e,"count");if(s)return _(e,G),s.count(e,n);const f=t.tables[e];if(!f)throw new y("INTERNAL",`unknown table: ${e}`);const h=En(n);if(h.restrictsCounts)throw new Ye(e);_(e,G);const u=le(f.softDeleteMode,void 0),c=V(V(h.baseWhere,h.where),u),l=await Te(c,e,h.relationBaseWhere),p=l!==c;if(f.aggregateIndexes&&!h.baseWhere&&!p&&!u){const b=Sn(f.aggregateIndexes,h.where);if(b){Ke(e,b.index);const P=ze(b.index.by??[],b.key),B=Ve(e,b.index.name),I=O(r,i`SELECT ${Fe} AS value FROM ${i.identifier(B)} WHERE ${qe} = ${P}`).toArray();return I[0]===void 0?0:I[0].value??0}}const T=ne(l,Ee);let g=i`SELECT COUNT(*) AS count FROM ${i.identifier(e)}`;return T&&(g=i`${g} WHERE ${T}`),O(r,g).one().count},async delete(e,n,s){const f=se(e,n);if(!f){const g=$e(n);g&&(H(void 0),await g.delete(e,n,s));return}const{docJson:h,row:u,tableName:c}=f,l=t.tables[c],p=s?.hard===!0,T=!p&&l?.softDeleteMode?l.softDeleteMode.field:void 0;if(!(T&&u[T]!==null&&u[T]!==void 0)){if(ee(c,"before","delete")&&await te("before","delete",{id:e,op:"delete",previous:u,table:c}),await Qn({deletedId:e,deletedReference:g=>u[g],findHolders:async(g,M,b)=>(await Ne(g).findMany(g,{includeDeleted:p,where:{[M]:b}})).page,onCascade:(g,M)=>Ne(g).delete(M,void 0,s),onRestrict:g=>{throw new me(g,"restrict")},onSetNull:(g,M,b)=>Ne(g).patch(M,{[b]:null}),schema:t,tableName:c}),we(c),pe(c),T){const g={...u,...R(c),[T]:x(),_id:e};We(r,c,Ft(c),[ae(g),e,h]),Ce(c,e,g,u),Ie(c,e,void 0),Ae(c,u,g),ge(c,e,u,void 0),C?.invalidate(c,e,E(c,u,g)),he(c,e,"update",g),a({indexKeys:E(c,u,g),key:e,op:"update",row:g,table:c}),ee(c,"after","delete")&&await te("after","delete",{id:e,op:"delete",previous:u,table:c}),await m({id:e,op:"delete",table:c});return}We(r,c,wo(c),[e,h]),Ce(c,e,void 0),Ie(c,e,void 0),Ae(c,u,void 0),ge(c,e,u,void 0),C?.invalidate(c,e,E(c,u)),he(c,e,"delete"),a({indexKeys:E(c,u),key:e,op:"delete",table:c}),ee(c,"after","delete")&&await te("after","delete",{id:e,op:"delete",previous:u,table:c}),await m({id:e,op:"delete",table:c})}},async deleteAll(e,n){if(!t.tables[e])throw new y("INTERNAL",`unknown table: ${e}`);const s=Math.max(1,n?.chunkSize??Xt),f=n?.hard===void 0?void 0:{hard:n.hard},h=ie(e)?void 0:e;let u=0;return await v(async()=>{for(;;){const l=(await W.findMany(e,{limit:s})).page.map(p=>String(p._id));if(l.length===0)break;for(const p of l)await W.delete(p,h,f),u+=1;if(l.length<s)break}}),{deleted:u}},async deleteMany(e,n,s){de(e.length,n?.limit,"deleteMany");for(const f of e)await W.delete(f,s);return{deleted:e.length}},async deleteWhere(e,n,s){const u=(await(Q(e,"deleteWhere")??W).findMany(e,{where:n})).page.map(c=>String(c._id));if(de(u.length,s?.limit,"deleteWhere"),W.deleteMany===void 0)throw new y("INTERNAL",`ctx.db.${e}.deleteMany is unavailable: this writer has no batch delete`);return W.deleteMany(u,s)},async findFirst(e,n={}){return(await W.findMany(e,{...n,limit:1,omitContinueCursor:!0})).page[0]??null},async findFirstOrThrow(e,n={}){const s=await W.findFirst(e,n);if(s===null)throw new qn(`findFirstOrThrow: no "${e}" document matched`);return s},async findMany(e,n={}){const s=Q(e,"findMany");if(s)return _(e,G),s.findMany(e,n);const f=t.tables[e];if(!f)throw new y("INTERNAL",`unknown table: ${e}`);const h=!n.where&&!n.baseWhere;h?_(e,G):_(e);const u=nt(n.orderBy,f.shape,{pinned:Bn(n.where),uniqueBy:zt(f.indexes,f.shape)}),c=n.cursor?Jt(u,ot(n.cursor)):void 0;let l=V(n.baseWhere,n.where);l=V(l,le(f.softDeleteMode,n.includeDeleted)),l=await xt(l,{canPushExists:wt?ln:void 0,existsPushMode:ht==="always"?"always":"auto",fetcher:ft,maxRelationKeys:pt,relationBaseWhere:n.relationBaseWhere,schema:t,tableName:e}),c&&(l=l?{AND:[l,c]}:c);const p=wt?Lo(_):dt,T=ne(l,p,Ge),g=typeof n.limit=="number"?Math.max(0,Math.floor(n.limit)):void 0,M=nn(e,T,rn(u),g===void 0?void 0:g+1),b=_e(r,M.text,...M.params).toArray();h&&!$&&k?.recordRead(b.length);const P=[];for(const J of b){const U=ue(J);U&&(P.push(U),!h&&typeof U._id=="string"&&_(e,U._id))}if(g===void 0)return n.with&&await bt({groupedCounter:gt,fetcher:je,parents:P,...Mt(n),schema:t,tableName:e,with:n.with}),{continueCursor:null,isDone:!0,page:vt(P,n.select,n.with)};const B=P.length>g,I=B?P.slice(0,g):P,K=I.at(-1);return n.with&&await bt({fetcher:je,groupedCounter:gt,parents:I,...Mt(n),schema:t,tableName:e,with:n.with}),{continueCursor:B&&K&&n.omitContinueCursor!==!0?rt(K,u):null,isDone:!B,page:vt(I,n.select,n.with)}},async get(e,n){const s=se(e,n);if(!s){const f=$e(n);return f?f.get(e,n):null}return _(s.tableName,e),s.row},async lookupById(e,n){const s=se(e,n);return s?(_(s.tableName,e),{row:s.row,tableName:s.tableName}):null},async groupBy(e,n){const s=Q(e,"groupBy");if(s)return _(e,G),s.groupBy(e,n);const f=t.tables[e];if(!f)throw new y("INTERNAL",`unknown table: ${e}`);_(e,G);const h=n.agg??{op:"count"};if(ke(h.op),h.op!=="count"&&!h.field)throw new y("INTERNAL",`groupBy(${e}, { agg: { op: "${h.op}" } }): "field" is required for non-count reducers`);const u=le(f.softDeleteMode,void 0),c=V(V(n.baseWhere,n.where),u),l=await Te(c,e,n.relationBaseWhere),p=l!==c,T=[...n.by,h.field];if(f.aggregateIndexes&&!n.baseWhere&&!p&&(!u||Wt(f,T))){const I=mn(f.aggregateIndexes,h.op,h.field,n.by,n.where),K=I===void 0?0:Object.keys(I.partial).length,J=I?.index.by?.length??0;if(I&&(K===0||K===J)){Ke(e,I.index);const U=Ve(e,I.index.name),xe=Object.keys(I.partial),be=[];if(xe.length===(I.index.by??[]).length&&xe.length>0){const Me=ze(I.index.by??[],I.partial),De=O(r,i`SELECT ${Fe} AS value, ${Xe} AS count FROM ${i.identifier(U)} WHERE ${qe} = ${Me}`).toArray();return De.length>0&&be.push({key:{...I.partial},value:Je(h.op,De[0])}),be}const hn=O(r,i`SELECT ${qe} AS key, ${Fe} AS value, ${Xe} AS count FROM ${i.identifier(U)}`).toArray();for(const Me of hn){const De=$n(JSON.parse(Me.key));be.push({key:De,value:Je(h.op,Me)})}return be}}for(const I of T){if(I===void 0)continue;const K=I===h.field?`groupBy(${e}, { agg: { op: "${h.op}", field: "${I}" } })`:`groupBy(${e}, { by: [..."${I}"] })`;Ut(f,I,K)}const g=ne(l,Ee),M=n.by.map(I=>i`${Z(I)} AS ${i.identifier(I)}`);if(h.op==="count")M.push(i`COUNT(*) AS value`);else{const{field:I}=h;if(I===void 0)throw new y("INTERNAL",`groupBy(${e}, { agg: { op: "${h.op}" } }): "field" is required for non-count reducers`);M.push(i`${i.raw(ke(h.op))}(${Z(I)}) AS value`)}let b=i`SELECT ${i.join(M,i`, `)} FROM ${i.identifier(e)}`;g&&(b=i`${b} WHERE ${g}`),b=i`${b} GROUP BY ${i.join(n.by.map(I=>Z(I)),i`, `)}`;const P=O(r,b).toArray(),B=[];for(const I of P){const K={};for(const U of n.by)K[U]=Cn(f.shape[U],I[U]??null);const{value:J}=I;B.push({key:K,value:J==null?null:Number(J)})}return B},async insert(e,n,s){const f=Q(e,"insert");if(f)return ut(f,e,n,s,!0);const h=t.tables[e];if(!h)throw new y("INTERNAL",`unknown table: ${e}`);const u=Gt(h,n,ce);et(h,u);let c;s?.clientId!==void 0?(mo(s.clientId),c=s.clientId):s?.allowExplicitId&&typeof u._id=="string"?c=u._id:c=D();const l=s?.allowExplicitId&&typeof u._creationTime=="number"?u._creationTime:x(),p={...u,...R(e),_creationTime:l,_id:c};return ee(e,"before","insert")&&await te("before","insert",{doc:{...p},id:c,op:"insert",table:e}),we(e),pe(e),it(r,e,fo(e),[c,l,ae(p)]),yt(e,c,p),ee(e,"after","insert")&&await te("after","insert",{doc:p,id:c,op:"insert",table:e}),await m({doc:p,id:c,op:"insert",table:e}),c},async insertManyUnsafe(e,n,s){if(de(n.length,s?.limit,"insertManyUnsafe"),n.length===0)return[];const f=Q(e,"insert");if(f){const l=[];for(const p of n)H(p);for(const p of n){const T=await f.insert(e,p,{allowExplicitId:s?.allowExplicitId});a({key:T,op:"insert",row:{...p,_id:T},table:e}),l.push(T)}return l}const h=t.tables[e];if(!h)throw new y("INTERNAL",`unknown table: ${e}`);we(e),pe(e);const u=[];for(let l=0;l<n.length;l+=Be)u.push(R(e));const c=n.map((l,p)=>{const T=Gt(h,l,ce),g=s?.allowExplicitId===!0&&typeof T._id=="string"?T._id:D(),M=s?.allowExplicitId===!0&&typeof T._creationTime=="number"?T._creationTime:x(),b={...T,...u[Math.floor(p/Be)],_creationTime:M,_id:g};return{creationTime:M,document:b,id:g}});for(const l of c)H(l.document);for(let l=0;l<c.length;l+=Be){const p=i.join(c.slice(l,l+Be).map(g=>i`(${g.id}, ${g.creationTime}, ${ae(g.document)})`),i`, `),T=Qt("sqlite",i`INSERT INTO ${i.identifier(e)} (id, _creationTime, ${i.identifier(oe)}) VALUES ${p}`);it(r,e,T.sql,T.params)}for(const{document:l,id:p}of c)yt(e,p,l),await j({doc:l,id:p,op:"insert",table:e});return c.map(l=>l.id)},async insertMany(e,n,s){de(n.length,s?.limit,"insertMany");const f=s?.skipDuplicates===!0,h=[],u=Q(e,"insert");if(u)for(const l of n)H(l);const c=async l=>u?ut(u,e,l,void 0,!1):W.insert(e,l);for(const l of n)try{h.push(await c(l))}catch(p){if(f&&p instanceof me&&p.kind==="unique")h.push(null);else throw p}return h},normalizeId(e,n){return Pt(t,e,n)},async patch(e,n,s){const f=se(e,s);if(!f){const T=$e(s);if(T){H(n),await T.patch(e,n,s);return}throw new y("NOT_FOUND",`document not found: ${e}`)}const{docJson:h,row:u,tableName:c}=f,l=t.tables[c];if(!l)throw new y("INTERNAL",`unknown table: ${c}`);_(c,e),Ot("patch",n);const p={...u,...n,...R(c),_id:e};Ht(l,n,p,ce),et(l,p,!0),ee(c,"before","update")&&await te("before","update",{doc:{...p},id:e,op:"update",previous:u,table:c}),we(c),pe(c),We(r,c,Ft(c),[ae(p),e,h]),Ce(c,e,p,u),Ie(c,e,p),Ae(c,u,p),ge(c,e,u,p),C?.invalidate(c,e,E(c,u,p)),he(c,e,"update",p),a({indexKeys:E(c,u,p),key:e,op:"update",row:p,table:c}),ee(c,"after","update")&&await te("after","update",{doc:p,id:e,op:"update",previous:u,table:c}),await m({doc:p,id:e,op:"update",table:c})},async patchMany(e,n,s){de(e.length,n?.limit,"patchMany");for(const f of e)await W.patch(f.id,f.patch,s);return{patched:e.length}},async patchWhere(e,n,s){const u=(await(Q(e,"patchWhere")??W).findMany(e,{where:n.where})).page.map(c=>({id:String(c._id),patch:n.patch}));if(de(u.length,s?.limit,"patchWhere"),W.patchMany===void 0)throw new y("INTERNAL",`ctx.db.${e}.patchMany is unavailable: this writer has no batch patch`);return await W.patchMany(u,s),{patched:u.length}},async related(e,n){return Kn(W,d,e,n)},relationEdges:d,query(e){const n=Q(e,"query");return n?(_(e,G),n.query(e)):Oo(r,t,e,F,s=>{s?q(s):_(e,G)},s=>{$||k?.recordRead(s)})},async rank(e,n,s){const f=Q(e,"rank");if(f)return _(e,G),f.rank(e,n,s);F(e,n,"rank");const h=t.tables[e];if(!h)throw new y("INTERNAL",`unknown table: ${e}`);const u=h.rankIndexes?.find(U=>U.name===n);if(!u)throw new y("INTERNAL",`unknown rankIndex "${n}" on table "${e}"`);if(Et(e,h,u),s.restrictsCounts)throw new Ye(e);_(e,G),Qe(e,u);const c=typeof s.row=="string"?s.row:s.row._id;if(!c)return null;const l=At(e,u.name),p=u.sortBy.map((U,xe)=>It(xe)),T=p.map(U=>Re(U)).join(", "),g=O(r,i`SELECT ${i.identifier("__partition__")}, ${i.raw(T)} FROM ${i.identifier(l)} WHERE ${i.identifier("__id__")} = ${c}`).toArray(),[M]=g;if(M===void 0)return null;let b=M.__partition__;const P=V(s.baseWhere,s.where);Ze(P,t,e,"rank");const B=Un(u,P);if(B){const U=Pn(u.partitionBy??[],B);if(U!==b)return null;b=U}const I=p.map(U=>M[U]),{before:K,total:J}=Nt(r,l,p,u.sortBy,b,I,c);return{position:K+1,total:J}},async rankBefore(e,n,s){if(ie(e))throw new y("INTERNAL",`rankBefore is not supported on the global (.global()) table '${e}' — cross-shard rank cursors apply only to sharded tables`);const f=t.tables[e];if(!f)throw new y("INTERNAL",`unknown table: ${e}`);const h=f.rankIndexes?.find(p=>p.name===n);if(!h)throw new y("INTERNAL",`unknown rankIndex "${n}" on table "${e}"`);if(s.restrictsCounts)throw new Ye(e);_(e,G),Qe(e,h);const u=At(e,h.name),c=h.sortBy.map((p,T)=>It(T)),l=h.sortBy.map((p,T)=>re(s.sortValues[T]??null));return Nt(r,u,c,h.sortBy,s.partitionKey,l,s.rowId)},async rankPage(e,n,s={}){Ze(V(s.baseWhere,s.where),t,e,"rankPage");const f=Q(e,"rankPage");if(f)return _(e,G),f.rankPage(e,n,s);F(e,n,"rank");const{continueCursor:h,hasMore:u,rows:c}=Rt(St,e,n,s);return{continueCursor:h,isDone:!u,page:c.map(l=>l.doc)}},async rankPageRows(e,n,s={}){Ze(V(s.baseWhere,s.where),t,e,"rankPage"),F(e,n,"rank");const{directions:f,hasMore:h,rows:u}=Rt(St,e,n,s);return{directions:f,hasMore:h,rows:u}},async restore(e,n){const s=se(e,n);if(!s){const u=$e(n);if(u?.restore){await u.restore(e,n);return}throw new y("NOT_FOUND",`document not found: ${e}`)}const f=t.tables[s.tableName]?.softDeleteMode?.field;if(!f)throw new y("INTERNAL",`ctx.db.restore: table "${s.tableName}" is not a .softDelete() table`);const h=s.row[f]!==null&&s.row[f]!==void 0;await W.patch(e,{[f]:null},n),h&&ge(s.tableName,e,void 0,s.row)},async replace(e,n,s,f){const h=se(e,s);if(!h){const M=$e(s);if(M){H(n),await M.replace(e,n,s,f);return}throw new y("NOT_FOUND",`document not found: ${e}`)}const{docJson:u,row:c,tableName:l}=h,p=t.tables[l];if(!p)throw new y("INTERNAL",`unknown table: ${l}`);Ot("replace",n);const T=f?.allowExplicitId&&typeof n._creationTime=="number"?n._creationTime:x(),g={...n,...R(l),_creationTime:T,_id:e};Ht(p,n,g,ce),et(p,g),ee(l,"before","update")&&await te("before","update",{doc:{...g},id:e,op:"update",previous:c,table:l}),we(l),pe(l),We(r,l,ho(l),[T,ae(g),e,u]),Ce(l,e,g,c),Ie(l,e,g),Ae(l,c,g),ge(l,e,c,g),C?.invalidate(l,e,E(l,c,g)),he(l,e,"update",g),a({indexKeys:E(l,c,g),key:e,op:"update",row:g,table:l}),ee(l,"after","update")&&await te("after","update",{doc:g,id:e,op:"update",previous:c,table:l}),await m({doc:g,id:e,op:"update",table:l})},async wipeShard(e){const n=new Set(e?.exclude),s=e?.tables,f=Object.entries(t.tables).filter(([l,p])=>n.has(l)||s!==void 0&&!s.includes(l)?!1:p.shardMode?.kind!=="global").map(([l])=>l);if(s!==void 0){for(const l of s)if(!t.tables[l])throw new y("INTERNAL",`wipeShard: unknown table: ${l}`)}const h={};let u=0;const{deleteAll:c}=W;if(c===void 0)throw new y("INTERNAL","wipeShard: this writer has no deleteAll");for(const l of f){const p=await c(l,{...e?.chunkSize===void 0?{}:{chunkSize:e.chunkSize},hard:!0});h[l]=p.deleted,u+=p.deleted}return{deleted:u,tables:h}}},fn={db:W,scheduler:z};return o.enforceRls===!0?zn(W,t,(e,n)=>se(e,n)?.tableName,(e,n)=>un(e,n),d):W};export{Fr as CDC_LOG_TABLE,Xr as CLIENT_WATERMARK_TABLE,oi as GLOBAL_SHAPE_SNAPSHOT_TABLE,li as IDEMPOTENCY_TABLE,Po as NotUniqueError,$i as SEARCH_STATE_TABLE,Zr as advanceClientWatermark,qr as applyCdcChanges,Ot as assertNoExplicitUndefined,mo as assertValidClientId,Mr as backfillAggregateIndexes,Dr as backfillRankIndexes,Lr as backfillSearchIndexes,Br as bumpCdcEpoch,Wr as cdcCanVouchFor,Ur as cdcSeqLeavingRows,Pr as cdcTouchesTables,Gr as cdcTrimmedError,Hr as compactCdcDocs,Cr as createShardCtxDb,Or as cursorBelowRetainedFloor,ri as deleteGlobalShapeSnapshot,ii as deleteGlobalShapeSnapshotsForConnection,ei as migrateClientWatermark,si as migrateGlobalShapeSnapshot,Nr as minCdcReplayableSeq,jr as minCdcSeq,Pt as normalizeIdStructurally,Kr as readCdcChangeKeys,Qr as readCdcChanges,Vr as readCdcCursor,zr as readCdcEpoch,ti as readClientWatermark,ci as readGlobalShapeSnapshot,ui as readIdempotent,pi as runShardMigrations,Ei as selectShapeMembers,mi as selectShapeRows,Jr as trimCdcChanges,fi as trimIdempotent,ai as writeGlobalShapeSnapshot,hi as writeIdempotent};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{LunoraError as h}from"@lunora/errors";import{mergeWhere as I}from"./CountRlsUnsupportedError-BvsDqfO2.mjs";import{decodeCursor as S,CURSOR_PREFIX as v,toBase64 as B}from"./CURSOR_PREFIX-Bn8SFoGd.mjs";const O=4,C=1,L=50,$=200,T=1e4,x=.5,D=t=>{if(t.kind==="id"){const e=t._meta?.tableName;return typeof e=="string"&&e.length>0?{array:!1,targetTable:e}:void 0}if(t.kind!=="array"&&t.kind!=="optional")return;const n=t._meta?.inner,r=n===void 0?void 0:D(n);if(r!==void 0)return{array:r.array||t.kind==="array",targetTable:r.targetTable}},j=t=>{const n=[];for(const[r,e]of Object.entries(t.tables))for(const[s,o]of Object.entries(e.shape)){const a=D(o);a===void 0||t.tables[a.targetTable]===void 0||n.push({array:a.array,column:s,name:`${r}.${s}`,sourceTable:r,targetTable:a.targetTable})}return n},U=t=>v+B(JSON.stringify([t])),M=t=>{const[n]=S(t);if(typeof n!="number"||!Number.isInteger(n)||n<0)throw new h("BAD_REQUEST","invalid cursor");if(n>T)throw new h("BAD_REQUEST",`ctx.db.related: cursor offset ${String(n)} exceeds the maximum of ${String(T)} — narrow the walk with \`edges\` or \`direction\` instead of paging past it`);return n},k=(t,n,r,e)=>{if(t===void 0)return n;if(!Number.isInteger(t)||t<1||t>r)throw new h("BAD_REQUEST",`ctx.db.related: \`${e}\` must be an integer between 1 and ${String(r)}, got ${String(t)}`);return t},N=(t,n)=>{if(n===void 0)return[...t];const r=new Set(t.map(o=>o.name)),e=n.filter(o=>!r.has(o));if(e.length>0)throw new h("BAD_REQUEST",`ctx.db.related: unknown edge ${e.length===1?"name":"names"}: ${e.join(", ")}`);const s=new Set(n);return t.filter(o=>s.has(o.name))},W=(t,n)=>{const r=t[n.column];return n.array?Array.isArray(r)?r.filter(e=>typeof e=="string"&&e.length>0):[]:typeof r=="string"&&r.length>0?[r]:[]},A=async(t,n,r,e)=>{const s=await t.findMany(n,{limit:e.limit,omitContinueCursor:!0,where:I(r,e.relationBaseWhere?.(n))??r});return e.mask?.(n,s.page)??s.page},F={in:{keyColumn:t=>t.column,keysOf:(t,n)=>n.array||t.table!==n.targetTable?[]:[t.id],skipVisitedKeys:!1,table:t=>t.sourceTable},out:{keyColumn:()=>"_id",keysOf:(t,n)=>t.table===n.sourceTable?W(t.document,n):[],skipVisitedKeys:!0,table:t=>t.targetTable}},_=async(t,n,r,e,s)=>{const o=F[s],a=o.keyColumn(r),l=o.table(r),u=new Map;for(const c of n)for(const i of o.keysOf(c,r))!u.has(i)&&!(o.skipVisitedKeys&&e.visited.has(i))&&u.set(i,c);if(u.size===0)return[];const f=await A(t,l,{[a]:{in:[...u.keys()]}},e),m=[];for(const c of f){const i=c._id,g=c[a],d=typeof g=="string"?u.get(g):void 0;typeof i!="string"||d===void 0||e.visited.has(i)||(e.visited.add(i),m.push({document:c,id:i,path:[...d.path,r.name],pathIds:[...d.pathIds,i],table:l}))}return m},Q=async(t,n,r,e)=>{const s=[],o=()=>e.budget-s.length,a=()=>({limit:o(),mask:e.mask,relationBaseWhere:e.relationBaseWhere,visited:e.visited});for(const l of r)e.direction!=="in"&&o()>0&&s.push(...await _(t,n,l,a(),"out")),e.direction!=="out"&&o()>0&&s.push(...await _(t,n,l,a(),"in"));return s},H=async(t,n)=>{const r=n._id;if(typeof r=="string"&&r.length>0){const o=await t.lookupById?.(r);if(!o)throw new h("BAD_REQUEST","ctx.db.related: could not resolve the start document's table from its `_id` — pass `{ table, id }` instead");return{id:r,table:o.tableName}}const{id:e,table:s}=n;if(typeof s!="string"||s.length===0||typeof e!="string"||e.length===0)throw new h("BAD_REQUEST","ctx.db.related: `start` must be a loaded document or `{ table, id }`");return{id:e,table:s}},V=async(t,n,r,e={})=>{const s=k(e.depth,C,O,"depth"),o=k(e.limit,L,$,"limit"),a=e.cursor?M(e.cursor):0,l=e.direction??"both",u=N(n,e.edges),{id:f,table:m}=await H(t,r),[c]=await A(t,m,{_id:f},{limit:1,mask:e.relationMask,relationBaseWhere:e.relationBaseWhere,visited:new Set});if(c===void 0)throw new h("NOT_FOUND",`ctx.db.related: no "${m}" row with id ${f}`);const i=a+o+1,g=new Set([f]),d=[];let w=[{document:c,id:f,path:[],pathIds:[f],table:m}];for(let b=1;b<=s&&w.length>0&&d.length<i;b+=1){const p=await Q(t,w,u,{budget:i-d.length,direction:l,mask:e.relationMask,relationBaseWhere:e.relationBaseWhere,visited:g}),R=x**(b-1);for(const y of p)d.push({depth:b,document:y.document,path:y.path,pathIds:y.pathIds,score:R,table:y.table});w=p}const E=d.length<=a+o;return{continueCursor:E?null:U(a+o),isDone:E,nodes:d.slice(a,a+o)}};export{L as RELATED_DEFAULT_LIMIT,x as RELATED_DEPTH_DECAY,O as RELATED_MAX_DEPTH,$ as RELATED_MAX_LIMIT,T as RELATED_MAX_OFFSET,j as deriveRelationEdges,V as findRelated};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{LunoraError as R}from"@lunora/errors";import{findRelated as m}from"./RELATED_DEFAULT_LIMIT-B9PH28Pn.mjs";const M=Symbol.for("lunora.ctxdb.rls-unwrap");class S extends R{table;constructor(n){super("RLS_REQUIRED",`ctx.db access to "${n}" is denied: the schema is marked .rls("required"), so this table is protected. Apply RLS with .use(rls(policies)) in the procedure, or mark the table .public() to opt it out.`,{name:"RlsRequiredError"}),this.table=n}}const b=a=>Object.entries(a.tables).filter(([,n])=>n.shardMode?.kind!=="global").map(([n])=>n),E=(a,n,l)=>{const d=n?.tables,u=new Set(n?.exclude);for(const o of a)(d===void 0||d.includes(o))&&!u.has(o)&&l(o)},y={aggregate:"loop-gated",asId:"ungated",cdcChangedTables:"ungated",count:"loop-gated",delete:"id-gated",deleteAll:"loop-gated",deleteMany:"id-gated",deleteWhere:"inline-table-gated",findFirst:"loop-gated",findFirstOrThrow:"loop-gated",findMany:"loop-gated",get:"id-gated",groupBy:"loop-gated",insert:"loop-gated",insertMany:"loop-gated",insertManyUnsafe:"loop-gated",lookupById:"id-gated",normalizeId:"ungated",patch:"id-gated",patchMany:"id-gated",patchWhere:"inline-table-gated",query:"loop-gated",rank:"loop-gated",rankBefore:"loop-gated",rankPage:"loop-gated",rankPageRows:"loop-gated",related:"rebound",relationEdges:"ungated",replace:"id-gated",restore:"id-gated",system:"ungated",wipeShard:"sweep-gated"},O=Object.entries(y).filter(([,a])=>a==="loop-gated").map(([a])=>a),W={related:(a,n)=>(...l)=>{const[d,u]=l;return m(a,n,d,u)}},k=Object.entries(y).filter(([,a])=>a==="rebound").map(([a])=>a),v=(a,n,l)=>{for(const d of k)typeof n[d]=="function"&&(a[d]=W[d](a,l))},_=(a,n,l,d,u=[])=>{if(n.rlsMode!=="required")return a;const o=a,p=e=>{const t=n.tables[e];return t!==void 0&&t.isPublic!==!0},i=e=>{if(p(e))throw new S(e)},c=async(e,t)=>{if(t!==void 0){i(t);return}const r=await l(e);r!==void 0&&i(r)},f=async(e,t)=>{if(t!==void 0){i(t);return}if(!d){for(const s of e)await c(s,t);return}const r=await d([...new Set(e)],t);for(const s of e){const h=r.get(s);h!==void 0&&i(h)}},g={...a,delete:async(e,t,r)=>(await c(e,t),o.delete(e,t,r)),deleteMany:async(e,t,r)=>(await f(e,r),o.deleteMany(e,t,r)),deleteWhere:o.deleteWhere?async(e,t,r)=>(i(e),await o.deleteWhere?.(e,t,r)):void 0,get:async(e,t)=>(await c(e,t),o.get(e,t)),lookupById:async(e,t)=>(await c(e,t),o.lookupById?.(e,t)??null),patch:async(e,t,r)=>(await c(e,r),o.patch(e,t,r)),patchMany:async(e,t,r)=>(await f(e.map(s=>s.id),r),o.patchMany(e,t,r)),patchWhere:o.patchWhere?async(e,t,r)=>(i(e),await o.patchWhere?.(e,t,r)):void 0,replace:async(e,t,r,s)=>(await c(e,r),o.replace(e,t,r,s)),restore:async(e,t)=>(await c(e,t),o.restore?.(e,t))},w=o;for(const e of O){const t=w[e];typeof t=="function"&&(g[e]=(r,...s)=>(i(r),t.call(o,r,...s)))}if(v(g,o,u),o.wipeShard){const{wipeShard:e}=o;g.wipeShard=t=>(E(b(n),t,i),e.call(o,t))}return Object.defineProperty(g,M,{configurable:!0,enumerable:!1,value:a,writable:!1}),g};export{O as LOOP_GATED_METHODS,M as RLS_UNWRAP_SYMBOL,S as RlsRequiredError,y as WRITER_METHOD_GATING,_ as guardWriter};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{createShardCtxDb as v}from"./NotUniqueError-
|
|
1
|
+
import{createShardCtxDb as v}from"./NotUniqueError-BMom69SD.mjs";import{createRelayLink as I}from"./DEFAULT_MAX_RELAYS-Ng4SyJ7k.mjs";import{ConflictError as N}from"./ConflictError-C8GtJmjS.mjs";import{runShardMigrations as _}from"./runShardMigrations-CeT_SVrI.mjs";import{relayName as F}from"./DEFAULT_PROMOTION_THRESHOLDS-Bfx7KakS.mjs";const E=(C,m={})=>({_meta:{column:{notNull:!0,...m}},kind:C}),W=(C,m,O)=>{const{describe:S,expect:n,it:y}=O;S(`engine contract: ${C}`,()=>{S("optimistic concurrency",()=>{const b=u=>({tables:{items:{indexes:[],shape:{title:E("string"),version:E("number",{notNull:!1})},triggerMap:{clobber:{handler:()=>{u.exec(`UPDATE "items" SET "__doc__" = json_set("__doc__", '$.version', 99) WHERE "id" = 'i1'`)},op:"update",timing:"before"}}}}});y("raises a CONFLICT of kind `occ` when a write's snapshot is clobbered",async()=>{const{close:u,host:h}=m();try{const i=h.sql,l=b(i);_(i,l);const s=v({schema:l,sql:i});await s.insert("items",{_id:"i1",title:"first",version:1},{allowExplicitId:!0}),await n(s.patch("i1",{title:"second"})).rejects.toBeInstanceOf(N)}finally{u?.()}}),y("reports the conflict as CONFLICT/409 rather than retrying it away",async()=>{const{close:u,host:h}=m();try{const i=h.sql,l=b(i);_(i,l);const s=v({schema:l,sql:i});await s.insert("items",{_id:"i1",title:"first",version:1},{allowExplicitId:!0});let o;try{await s.patch("i1",{title:"second"})}catch(t){o=t}const e=o;n(e.code).toBe("CONFLICT"),n(e.kind).toBe("occ")}finally{u?.()}}),y("leaves the row readable and unchanged after a conflict",async()=>{const{close:u,host:h}=m();try{const i=h.sql,l=b(i);_(i,l);const s=v({schema:l,sql:i});await s.insert("items",{_id:"i1",title:"first",version:1},{allowExplicitId:!0});try{await s.patch("i1",{title:"second"})}catch{}const o=await s.get("i1");n(o?.title).toBe("first"),n(o?.version).toBe(99)}finally{u?.()}}),y("raises a CONFLICT of kind `trigger` when a trigger writes its own row through the db",async()=>{const{close:u,host:h}=m();try{const i=h.sql,l={tables:{items:{indexes:[],shape:{title:E("string"),version:E("number",{notNull:!1})},triggerMap:{recurse:{handler:async(t,a)=>{await t.db.patch(a.doc._id,{version:99})},op:"update",timing:"before"}}}}};_(i,l);const s=v({schema:l,sql:i});await s.insert("items",{_id:"i1",title:"first",version:1},{allowExplicitId:!0});let o;try{await s.patch("i1",{title:"second"})}catch(t){o=t}const e=o;n(e).toBeInstanceOf(N),n(e.code).toBe("CONFLICT"),n(e.kind).toBe("trigger")}finally{u?.()}})}),S("shape-poke ordering",()=>{const b="shard-a",u={args:{},name:"messages"},h=(e,t,a,r)=>e.accept(t?.()??{},{connectionId:a,shapes:{[r]:u}}),i=(e,t,a)=>{let r=0,d=0;const c=g=>()=>{throw new Error(`the relay poke path must not reach RelayHost.${g}`)},p={fetch:(g,q)=>{if(JSON.parse(q?.body??"{}").type!=="relay_shape_subscribe")return Promise.resolve(new Response(void 0,{status:204}));const B=a[d];if(d+=1,B===void 0)throw new Error("the relay asked for more seeds than this fixture supplies");return Promise.resolve(Response.json(B))}},k={get:()=>p,getByName:()=>p,idFromName:g=>g},w={buildShapeDiff:c("buildShapeDiff"),computeOpLogShapeSeed:c("computeOpLogShapeSeed"),currentCdcEpoch:c("currentCdcEpoch"),deliverWhisperLocal:c("deliverWhisperLocal"),doName:()=>F(b,0),env:()=>({SHARD:k}),getWebSockets:()=>e.getSockets(),maskMetadata:c("maskMetadata"),nextPokeId:()=>(r+=1,`poke-${String(r)}`),readAttachment:g=>g.deserializeAttachment?.(),recordShapePokeFanout:()=>{},resolveShape:c("resolveShape"),rlsMetadata:c("rlsMetadata"),shardBinding:()=>"SHARD",shardJurisdiction:()=>{},sql:()=>t},f=I(w);if(f===void 0)throw new Error("expected a relay link for a `…::relay::N` name");return f},l=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 r=await e.seedRelayShape(t,a,u,{identity:void 0,userId:void 0});if(r!=="ok")throw new Error(`seed failed: ${JSON.stringify(r)}`)},o=(e={})=>l({...u,checkpoint:20,epoch:"e1",fromCursor:10,rowsPatch:[{id:"r1",op:"upsert",value:{title:"hello"}}],type:"relay_shape_poke",...e});y("frames a poke as pokeStart → pokePart per shape → pokeEnd, under one poke id",async()=>{const{close:e,createSocket:t,host:a,readFrames:r,sockets:d}=m();try{const c=i(d,a.sql,[{cursor:10,epoch:"e1",frames:[]}]),p=h(d,t,"c-alice","s1");await s(c,p,"s1"),await c.handleControl(o());const w=(await r(p)).map(f=>JSON.parse(f));n(w.map(f=>f.type)).toStrictEqual(["pokeStart","pokePart","pokeEnd"]),n(new Set(w.map(f=>f.pokeId)).size).toBe(1),n(w[1]?.shapeId).toBe("s1"),n(w[2]?.checkpoint).toBe(20)}finally{e?.()}}),y("delivers a poke only to sockets whose cursor matches, and advances them past it",async()=>{const{close:e,createSocket:t,host:a,readFrames:r,sockets:d}=m();try{const c=i(d,a.sql,[{cursor:10,epoch:"e1",frames:[]},{cursor:7,epoch:"e1",frames:[]}]),p=h(d,t,"c-alice","s1"),k=h(d,t,"c-bob","s2");await s(c,p,"s1"),await s(c,k,"s2"),await c.handleControl(o());const w=await r(p);n(w.length).toBe(3);const f=await r(k);n(f.length).toBe(0),await c.handleControl(o());const g=await r(p);n(g.length).toBe(3)}finally{e?.()}}),y("skips a socket whose cursor matches under a different CDC epoch",async()=>{const{close:e,createSocket:t,host:a,readFrames:r,sockets:d}=m();try{const c=i(d,a.sql,[{cursor:10,epoch:"e1",frames:[]}]),p=h(d,t,"c-alice","s1");await s(c,p,"s1"),await c.handleControl(o({epoch:"e2"}));const k=await r(p);n(k.length).toBe(0),await c.handleControl(o());const w=await r(p);n(w.length).toBe(3)}finally{e?.()}})}),S("RLS identity under live subscription",()=>{const b="shard-a",u={args:{},name:"lobby-messages"},h={args:{},name:"my-orders"},i=s=>{const o=[],e=[],t={fetch:(d,c)=>(o.push(JSON.parse(c?.body??"{}")),Promise.resolve(new Response(void 0,{status:204})))},r=I({buildShapeDiff:()=>[{id:"r1",op:"upsert",value:{}}],computeOpLogShapeSeed:()=>({baseCheckpoint:void 0,cursor:10,epoch:"e1",reset:!0,rowsPatch:[]}),currentCdcEpoch:()=>"e1",deliverWhisperLocal:()=>0,doName:()=>b,env:()=>({SHARD:{get:()=>t,getByName:()=>t,idFromName:d=>d}}),getWebSockets:()=>[],maskMetadata:()=>({columns:[]}),nextPokeId:()=>"poke-1",readAttachment:()=>({}),recordShapePokeFanout:()=>{},resolveShape:(d,c,p)=>(e.push(p),d===h.name?{columns:["id"],effectiveWhere:{org:p?.identity?.org??"anonymous"},global:!1,table:"orders"}:{columns:["id"],effectiveWhere:{room:"lobby"},global:!1,table:"messages"}),rlsMetadata:()=>({policies:[]}),shardBinding:()=>"SHARD",shardJurisdiction:()=>{},sql:()=>s});if(r===void 0)throw new Error("expected an owner link for an un-suffixed DO name");return{owner:r,posts:o,resolvedUnder:e}},l=async(s,o)=>{await s.handleControl(new Request("https://owner.internal/_lunora/relay",{body:JSON.stringify({...o,connectionId:"c-alice",identity:{org:"acme"},relayIndex:0,subId:"s1",type:"relay_shape_subscribe",userId:"u1"}),headers:{"content-type":"application/json"},method:"POST"}))};y("seeds a subscriber under its own forwarded identity, never the anonymous one",async()=>{const{close:s,host:o}=m();try{const{owner:e,resolvedUnder:t}=i(o.sql);await l(e,h),n(t.some(a=>a?.userId==="u1"&&a.identity?.org==="acme")).toBe(!0)}finally{s?.()}}),y("routes an identity-scoped shape to a per-socket poke, not the cohort multicast",async()=>{const{close:s,host:o}=m();try{const{owner:e,posts:t}=i(o.sql);await l(e,h),t.length=0,await e.onFlush(new Set(["orders"]),20);const a=t.filter(r=>r.type==="relay_shape_poke");n(a.length).toBe(1),n(a[0]?.targetConnectionId).toBe("c-alice")}finally{s?.()}}),y("still multicasts an identity-blind shape to the whole cohort",async()=>{const{close:s,host:o}=m();try{const{owner:e,posts:t}=i(o.sql);await l(e,u),t.length=0,await e.onFlush(new Set(["messages"]),20);const a=t.filter(r=>r.type==="relay_shape_poke");n(a.length).toBe(1),n(a[0]?.targetConnectionId).toBeUndefined()}finally{s?.()}})})})};export{W as defineEngineContractSuite};
|
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.65",
|
|
4
4
|
"description": "Host-neutral reactive engine for Lunora: per-shard state, OCC, CDC, reactive subscriptions, and the poke protocol. Consumes @lunora/platform host contracts and can be mounted on any platform host.",
|
|
5
5
|
"keywords": [
|
|
6
6
|
"cloudflare",
|
|
@@ -48,8 +48,8 @@
|
|
|
48
48
|
"access": "public"
|
|
49
49
|
},
|
|
50
50
|
"dependencies": {
|
|
51
|
-
"@lunora/errors": "1.0.0-alpha.
|
|
52
|
-
"@lunora/platform": "1.0.0-alpha.
|
|
51
|
+
"@lunora/errors": "1.0.0-alpha.36",
|
|
52
|
+
"@lunora/platform": "1.0.0-alpha.30",
|
|
53
53
|
"drizzle-orm": "^0.45.2"
|
|
54
54
|
},
|
|
55
55
|
"engines": {
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{LunoraError as E}from"@lunora/errors";import{m as $,n as y}from"./do-sql-Dvj8Yl5N.mjs";import{quoteIdentifier as d}from"./quoteIdentifier-CObIFRhb.mjs";import{d as L}from"./wire-codec-C-FpWm52.mjs";const te="__lunora_admin__:",re="__lunora_relation__:",ne="__lunora_flags__:",se={applyCdc:"__lunora_admin__:applyCdc",aiAvailable:"__lunora_admin__:aiAvailable",aiChartConfig:"__lunora_admin__:aiChartConfig",aiGenerateSql:"__lunora_admin__:aiGenerateSql",aiTableFilter:"__lunora_admin__:aiTableFilter",assignIssue:"__lunora_admin__:assignIssue",backfillSearch:"__lunora_admin__:backfillSearch",backRelationCounts:"__lunora_admin__:backRelationCounts",cdcSync:"__lunora_admin__:cdcSync",clearCapturedMail:"__lunora_admin__:clearCapturedMail",clearQueueMessages:"__lunora_admin__:clearQueueMessages",clearTable:"__lunora_admin__:clearTable",createWorkflowInstance:"__lunora_admin__:createWorkflowInstance",deleteRows:"__lunora_admin__:deleteRows",describeTable:"__lunora_admin__:describeTable",describeTables:"__lunora_admin__:describeTables",explainIssue:"__lunora_admin__:explainIssue",exportShard:"__lunora_admin__:exportShard",facetColumn:"__lunora_admin__:facetColumn",getAdvisories:"__lunora_admin__:getAdvisories",getAdvisorProcedures:"__lunora_admin__:getAdvisorProcedures",getAuditLog:"__lunora_admin__:getAuditLog",getAuthMetrics:"__lunora_admin__:getAuthMetrics",getCapturedMail:"__lunora_admin__:getCapturedMail",getFanoutMetrics:"__lunora_admin__:getFanoutMetrics",getFunctionStats:"__lunora_admin__:getFunctionStats",getIssues:"__lunora_admin__:getIssues",getMetricHistory:"__lunora_admin__:getMetricHistory",getMetricSeries:"__lunora_admin__:getMetricSeries",listSubscriptions:"__lunora_admin__:listSubscriptions",listTableIndexes:"__lunora_admin__:listTableIndexes",listTablesIndexes:"__lunora_admin__:listTablesIndexes",getLogs:"__lunora_admin__:getLogs",getMetrics:"__lunora_admin__:getMetrics",getPitrBookmark:"__lunora_admin__:getPitrBookmark",getQueryInsights:"__lunora_admin__:getQueryInsights",getQueueMessages:"__lunora_admin__:getQueueMessages",getRequestLog:"__lunora_admin__:getRequestLog",getSecurityAudit:"__lunora_admin__:getSecurityAudit",getSettings:"__lunora_admin__:getSettings",getTraces:"__lunora_admin__:getTraces",getWorkflowInstanceStatus:"__lunora_admin__:getWorkflowInstanceStatus",ignoreIssue:"__lunora_admin__:ignoreIssue",importShard:"__lunora_admin__:importShard",listFlags:"__lunora_admin__:listFlags",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",recordAuthEvent:"__lunora_admin__:recordAuthEvent",recordContainerEvent:"__lunora_admin__:recordContainerEvent",recordMail:"__lunora_admin__:recordMail",recordQueueMessage:"__lunora_admin__:recordQueueMessage",replayQueueMessage:"__lunora_admin__:replayQueueMessage",resolveIssue:"__lunora_admin__:resolveIssue",rlsPolicies:"__lunora_admin__:rlsPolicies",schemaHistory:"__lunora_admin__:schemaHistory",schemaVersion:"__lunora_admin__:schemaVersion",runAs:"__lunora_admin__:runAs",runMigration:"__lunora_admin__:runMigration",runSql:"__lunora_admin__:runSql",sendQueueMessage:"__lunora_admin__:sendQueueMessage",sendTestMail:"__lunora_admin__:sendTestMail",setIssueSeverity:"__lunora_admin__:setIssueSeverity",storageOrphans:"__lunora_admin__:storageOrphans",storageReferences:"__lunora_admin__:storageReferences",storageRules:"__lunora_admin__:storageRules",studioFeatures:"__lunora_admin__:studioFeatures",writeRow:"__lunora_admin__:writeRow"},D=50,h=500,U=30,j=200,f="__doc__",O=e=>{try{const t=JSON.parse(e);return t!==null&&typeof t=="object"&&!Array.isArray(t)?t:void 0}catch{return}},W=e=>{const{[y]:t,...r}=e;return t===void 0?r:t===null||typeof t!="object"||Array.isArray(t)?{[y]:t,...r}:{...r,...L(t)}},q=(e,t)=>{if(!e.includes(f))return{columns:e,rows:t};const r=[];for(const s of t){const o=s[f],i=typeof o=="string"?O(o):void 0;if(i===void 0)return{columns:e,rows:t};const c=Object.fromEntries(Object.entries(s).filter(([u])=>u!==f));r.push({...c,...W(i)})}const n=e.filter(s=>s!==f),a=[],_=new Set(n);for(const s of r)for(const o of Object.keys(s))_.has(o)||(_.add(o),a.push(o));return{columns:[...n,...a],rows:r}},F=e=>`instr(lower(CAST(${e} AS TEXT)), lower(?)) > 0`,I=e=>e.startsWith("sqlite_")||e.startsWith("_cf_")||e.startsWith("__miniflare")||e.startsWith("__lunora")||e.includes("__fts_"),C=(e,t,r)=>Math.min(Math.max(e,t),r),P=(e,t)=>{const r=e.exec(`SELECT COUNT(*) AS c FROM ${t}`).one();return Number(r.c)},ae=e=>{const t=e.exec("SELECT name FROM sqlite_master WHERE type = 'table' ORDER BY name").toArray(),r=[];for(const{name:n}of t)I(n)||r.push({name:n,rowCount:P(e,d(n))});return r},x=(e,t)=>e.exec("SELECT name FROM sqlite_master WHERE type = 'table' AND name = ? LIMIT 1",t).toArray().length>0,A=(e,t)=>{if(I(t)||!x(e,t))throw new E("UNKNOWN_TABLE",`unknown table: ${t}`,{status:404})},M=(e,t)=>e.exec(`PRAGMA table_info(${t})`).toArray().map(r=>r.name),Q={eq:"=",gt:">",gte:">=",lt:"<",lte:"<=",ne:"<>"},B=e=>typeof e=="string"?e:typeof e=="number"||typeof e=="boolean"?String(e):"",v=(e,t)=>{const r=t.includes(e),n=t.includes(f);if(!(!r&&!n))return r?{expression:d(e),params:[]}:{expression:`json_extract(${d(f)}, ?)`,params:[`$.${$(e)}`]}},G=(e,t)=>{const r=v(e.column,t);if(r===void 0)return;const{expression:n,params:a}=r;return e.operator==="contains"?{params:[...a,B(e.value)],sql:F(n)}:{params:[...a,e.value],sql:`${n} ${Q[e.operator]} ?`}},H=/^(\d{4})(?:-(\d{2}))?(?:-(\d{2}))?$/u,X=e=>{const t=H.exec(e.trim());if(t===null)return;const r=Number(t[1]),n=t[2]===void 0?void 0:Number(t[2]),a=t[3]===void 0?void 0:Number(t[3]);if(n!==void 0&&(n<1||n>12)||a!==void 0&&(a<1||a>31)||r<100)return;const _=Date.UTC(r,(n??1)-1,a??1);if(a!==void 0&&new Date(_).getUTCDate()!==a)return;let s;return a!==void 0?s=Date.UTC(r,(n??1)-1,a+1):n===void 0?s=Date.UTC(r+1,0,1):s=Date.UTC(r,n,1),{from:_,to:s}},R=(e,t,r)=>{const n=[],a=[];if(t!==""&&e.length>0){const _=e.map(o=>F(d(o)));a.push(...e.map(()=>t));const s=X(t);if(s!==void 0)for(const o of e)_.push(`(${d(o)} >= ? AND ${d(o)} < ?)`),a.push(s.from,s.to);n.push(`(${_.join(" OR ")})`)}for(const _ of r??[]){const s=G(_,e);s!==void 0&&(n.push(`(${s.sql})`),a.push(...s.params))}return n.length===0?void 0:{parameters:a,where:n.join(" AND ")}},Y=(e,t)=>{if(e===void 0)return;const r=v(e.column,t);if(r===void 0)return;const n=e.direction==="desc"?"DESC":"ASC";return{params:r.params,sql:`${r.expression} ${n}`}},oe=(e,t)=>{const{table:r}=t;A(e,r);const n=C(Math.trunc(t.limit??D),1,h),a=Math.max(0,Math.trunc(t.offset??0)),_=d(r),s=M(e,_),o=t.search?.trim()??"",i=S=>{if(t.refs===void 0)return S;const T={};for(const w of S.columns){const k=t.refs[w];k!==void 0&&(T[w]=k)}return Object.keys(T).length>0?{...S,refs:T}:S},c=R(s,o,t.filters),u=Y(t.orderBy,s),l=c===void 0?"":` WHERE ${c.where}`,m=u===void 0?"":` ORDER BY ${u.sql}`,p=c?.parameters??[],g=u?.params??[];let b;t.skipCount||(b=c===void 0?P(e,_):Number(e.exec(`SELECT COUNT(*) AS c FROM ${_}${l}`,...p).one().c));const N=e.exec(`SELECT * FROM ${_}${l}${m} LIMIT ? OFFSET ?`,...p,...g,n,a).toArray();return i({...q(s,N),total:b})},_e=(e,t)=>{const{table:r}=t;A(e,r);const n=C(Math.trunc(t.limit??h),1,h),a=d(r),_=M(e,a),s=t.search?.trim()??"",o=R(_,s,t.filters),i=[],c=[];o!==void 0&&(i.push(o.where),c.push(...o.parameters)),t.after!==void 0&&(i.push("id > ?"),c.push(t.after));const u=i.length===0?"":` WHERE ${i.join(" AND ")}`,l=t.after===void 0?"":" ORDER BY id",m=e.exec(`SELECT id FROM ${a}${u}${l} LIMIT ?`,...c,n+1).toArray(),p=m.length>n,g=m.slice(0,n).map(b=>b.id);return{hasMore:p,ids:g}},K=(e,t,r)=>{const n=new Set(r.filter(_=>_!==f));if(!r.includes(f))return n;const a=e.exec(`SELECT ${d(f)} AS doc FROM ${t} LIMIT ?`,h).toArray();for(const{doc:_}of a){const s=typeof _=="string"?O(_):void 0;if(s!==void 0)for(const o of Object.keys(s))n.add(o)}return n},ie=(e,t)=>{const{column:r,table:n}=t;A(e,n);const a=d(n),_=M(e,a);if(!K(e,a,_).has(r))throw new E("UNKNOWN_COLUMN",`unknown column: ${r}`,{status:404});const s=v(r,_);if(s===void 0)throw new E("UNKNOWN_COLUMN",`unknown column: ${r}`,{status:404});const o=C(Math.trunc(t.limit??U),1,j),i=t.search?.trim()??"",c=R(_,i,t.filters),u=c===void 0?"":` WHERE ${c.where}`,l=c?.parameters??[],m=e.exec(`SELECT ${s.expression} AS value, COUNT(*) AS count FROM ${a}${u} GROUP BY ${s.expression} ORDER BY count DESC LIMIT ?`,...s.params,...l,...s.params,o+1).toArray();return{truncated:m.length>o,values:m.slice(0,o).map(g=>({count:Number(g.count),value:g.value}))}},ce=(e,t,r)=>{const n={},a=r.slice(0,h);for(const s of a)n[s]=[];if(a.length===0)return{references:n,storageColumns:t};const _=a.map(()=>"?").join(", ");for(const[s,o]of Object.entries(t)){if(I(s)||!x(e,s))continue;const i=d(s),c=M(e,i);for(const u of o){const l=v(u,c);if(l===void 0)continue;const m=e.exec(`SELECT id, ${l.expression} AS ref FROM ${i} WHERE ${l.expression} IN (${_})`,...l.params,...l.params,...a).toArray();for(const p of m)n[p.ref]?.push({column:u,id:p.id,table:s})}}return{references:n,storageColumns:t}},ue=e=>{const t=e.map((n,a)=>{const _=Object.values(n.subs??{}).map(s=>({args:s.args,functionPath:s.functionPath,table:s.table}));return{admin:n.admin===!0,id:a,subscriptions:_}}),r=t.reduce((n,a)=>n+a.subscriptions.length,0);return{connections:t,totalConnections:t.length,totalSubscriptions:r}},V=20,le=()=>({maxMs:0,passes:0,peakSocketsIterated:0,socketsDelivered:0,socketsIterated:0,totalMs:0}),de=()=>({run:0,served:0}),me=()=>({drains:0,pairsSkipped:0}),fe=(e,t,r)=>({drains:e.drains+t,pairsSkipped:e.pairsSkipped+r}),pe=(e,t,r)=>({run:e.run+t,served:e.served+r}),ge=(e,t,r,n)=>({maxMs:Math.max(e.maxMs,n),passes:e.passes+1,peakSocketsIterated:Math.max(e.peakSocketsIterated,t),socketsDelivered:e.socketsDelivered+r,socketsIterated:e.socketsIterated+t,totalMs:e.totalMs+n}),he=(e,t=V)=>{const r=new Map,n=new Map;for(const s of e){for(const o of Object.values(s.shapes??{})){const i=o.name??"(unknown shape)";r.set(i,(r.get(i)??0)+1)}for(const o of s.whispers??[])n.set(o,(n.get(o)??0)+1)}const a=[...[...r].map(([s,o])=>({kind:"shape",subscribers:o,topic:s})),...[...n].map(([s,o])=>({kind:"whisper",subscribers:o,topic:s}))];return a.sort((s,o)=>o.subscribers-s.subscribers||s.topic.localeCompare(o.topic)),{peakSubscribers:a[0]?.subscribers??0,topics:a.slice(0,t),totalConnections:e.length}};export{se as ADMIN_FUNCTIONS,te as ADMIN_FUNCTION_PREFIX,V as DEFAULT_FANOUT_TOPIC_LIMIT,ne as FLAGS_FUNCTION_PREFIX,h as MAX_PAGE_SIZE,re as RELATION_FUNCTION_PREFIX,le as createFanoutCounters,me as createGlobalPollCounters,de as createShapeProbeCounters,X as datePrefixRange,ie as facetColumn,ce as findStorageReferences,ae as listTables,oe as readTablePage,ge as recordFanoutPass,fe as recordGlobalPollPass,pe as recordShapeProbePass,_e as selectMatchingIds,he as summarizeFanoutTopics,ue as summarizeSubscriptions};
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{LunoraError as $}from"@lunora/errors";import{D as st}from"./MAX_TOKEN_LENGTH-BakL9FUy-B3VwYY8C.mjs";import{c as hn,S as wn,l as De,a as pn}from"./ctx-db-companions-w-CfeOda.mjs";import{sql as i}from"drizzle-orm";import{d as gn}from"./wire-codec-C-FpWm52.mjs";import{throwingScheduler as $n,aggregateSqlFunction as Le,normalizeCountArgument as yn}from"./AGGREGATE_SQL_FUNCTION-DDEoMnJR.mjs";import{aggregateTableName as Ve,encodeAggregateKey as ze,readAggregateValue as Je}from"./aggregateTableName-C7o-gpms.mjs";import{mergeWhere as z,CountRlsUnsupportedError as Ye,selectIndexForGroupBy as En,selectIndexForCount as mn,selectIndexForAggregate as Sn}from"./CountRlsUnsupportedError-BvsDqfO2.mjs";import{backfillSearchIndexesForTable as _n,searchIndexCoversTable as Rn}from"./backfillAggregateIndexes-BG5-SC1q.mjs";import{backfillAggregateIndexes as Ir,backfillRankIndexes as Cr,backfillSearchIndexes as xr}from"./backfillAggregateIndexes-BG5-SC1q.mjs";import{appendCdcChange as Tn}from"./CDC_LOG_TABLE-vVheEulD.mjs";import{CDC_LOG_TABLE as Mr,applyCdcChanges as Dr,bumpCdcEpoch as Lr,cdcCanVouchFor as kr,cdcSeqLeavingRows as Fr,cdcTouchesTables as qr,cdcTrimmedError as Br,compactCdcDocs as Wr,cursorBelowRetainedFloor as Ur,minCdcReplayableSeq as Pr,minCdcSeq as Gr,readCdcChangeKeys as Hr,readCdcChanges as Or,readCdcCursor as Nr,readCdcEpoch as jr,trimCdcChanges as Kr}from"./CDC_LOG_TABLE-vVheEulD.mjs";import{allocateCommitSeq as An,COMMIT_SEQ_FIELD as vn}from"./COMMIT_SEQ_FIELD-BUdOMG5y.mjs";import{isMemoryTable as _t}from"./clearMemoryTables-BGbmag2i.mjs";import{computeRankPage as Rt}from"./computeRankPage-DsQ16o1z.mjs";import{SCAN_DEP as H}from"./SCAN_DEP-D7qE3iUe.mjs";import{runDrizzle as N,runSql as Se}from"./runDrizzle-2ULFQR_k.mjs";import{D as oe,k as ce,r as le,b as ke,A as Xe,a as Fe,e as X,o as In,t as jt,j as We,q as Tt,i as Cn,h as Kt,g as xn}from"./do-sql-Dvj8Yl5N.mjs";import{renderSql as Qt,unionAll as ct,WORKERD_SQLITE_LIMITS as Vt,sqliteInList as bn}from"./param-DlozcSQu.mjs";import{coveringGeohashes as Mn,boundingBoxGeohashes as Dn,haversineMeters as Ln,pointInBoundingBox as kn}from"./GEO_DEFAULT_PRECISION-CqpQZ-J_.mjs";import{NotFoundError as Fn}from"./NotFoundError-BhF7FeFr.mjs";import{softDeleteScope as de,normalizeOrderKeys as nt,uniqueIndexFields as zt,equalityPinnedFields as qn,buildSeekWhere as Jt,decodeCursor as ot,applySelect as At,encodeCursor as rt,tiebreakDirectionFor as Yt,buildSeekBeforeWhere as Bn}from"./CURSOR_PREFIX-Bn8SFoGd.mjs";import{rankTableName as vt,sortColumnName as It,resolveRankPartition as Wn,encodePartitionKey as Un,RANK_TIEBREAK as Pn,rankPivotConditionSql as Gn}from"./RANK_TIEBREAK-BXDiMmkH.mjs";import{UNVOUCHABLE_DEP as Ct}from"./UNVOUCHABLE_DEP-C68htACn.mjs";import{indexKeysForRow as Hn,buildIndexRange as On}from"./buildIndexRange-NtciKq3M.mjs";import{assertFlatPredicate as Ze,resolveRelationPredicates as xt}from"./DEFAULT_MAX_RELATION_KEYS-XESc7TiB.mjs";import{runRowValidators as et,resolveWith as bt,relationHooks as Mt,applyOnDelete as Nn,fanOutScalarCounts as jn}from"./applyOnDelete-7JZ4vR9r.mjs";import{guardWriter as Kn}from"./RLS_UNWRAP_SYMBOL-BF5gi64E.mjs";import{quoteIdentifier as _e}from"./quoteIdentifier-CObIFRhb.mjs";import{m as Qn}from"./sql-projection-BB2lCbYV.mjs";import{createSystemReader as Vn}from"./createSystemReader-DcDLFfC-.mjs";import{ConflictError as Ee}from"./ConflictError-C8GtJmjS.mjs";import{runTriggers as zn}from"./hasTrigger-CjlwI4le.mjs";import{c as ne,t as Pe,r as Ue,j as me,i as Dt}from"./where-sql-x1YKldcq.mjs";import{CLIENT_WATERMARK_TABLE as Vr,advanceClientWatermark as zr,migrateClientWatermark as Jr,readClientWatermark as Yr}from"./CLIENT_WATERMARK_TABLE-CRnrAnJ2.mjs";import{GLOBAL_SHAPE_SNAPSHOT_TABLE as Zr,deleteGlobalShapeSnapshot as ei,deleteGlobalShapeSnapshotsForConnection as ti,migrateGlobalShapeSnapshot as ni,readGlobalShapeSnapshot as oi,writeGlobalShapeSnapshot as ri}from"./GLOBAL_SHAPE_SNAPSHOT_TABLE-DSA6mzyx.mjs";import{IDEMPOTENCY_TABLE as si,readIdempotent as ci,trimIdempotent as ai,writeIdempotent as di}from"./IDEMPOTENCY_TABLE-DOpm_oMF.mjs";import{runShardMigrations as ui}from"./runShardMigrations-CeT_SVrI.mjs";import{S as hi}from"./ctx-db-search-state-ruTuCsxa.mjs";import{selectShapeMembers as pi,selectShapeRows as gi}from"./selectShapeMembers-CCZyZggM.mjs";import{serializeSqlValue as re}from"./serializeSqlValue-CjbhIHjJ.mjs";const Jn=o=>{const r=atob(o),t=Uint8Array.from(r,a=>a.codePointAt(0)??0);return new TextDecoder().decode(t)},Yn=()=>new $("BAD_REQUEST","invalid cursor"),Lt=16,kt=8,Y=1024,at=(o,r)=>r.query(o),Xn=(o,r)=>{if(o.length===0)return 0;let t=0;for(const[a,d]of r.entries()){const w=a===r.length-1;let E=0;for(const S of o)(w?S.startsWith(d):S===d)&&(E+=1);if(E===0)return 0;t+=E}return t},Zn=(o,r)=>{if(!r)return{exact:!0,lower:o,upper:o};const t=[...o].at(-1)??"",a=(t.codePointAt(0)??0)+1;if(a>=55296&&a<=57343||a>1114111)return{exact:!0,lower:o,upper:o};const d=o.slice(0,o.length-t.length);return{exact:!1,lower:o,upper:d+String.fromCodePoint(a)}},eo=(o,r,t)=>{const a={eq:(d,w)=>{if(!o.definition.filterFields?.includes(d))throw new $("INTERNAL",`field "${d}" is not a filter field of search index "${o.indexName}" on table "${r}"`);if(o.filters.length>=kt)throw new $("BAD_REQUEST",`search index "${o.indexName}" on table "${r}": at most ${String(kt)} .eq() filters are supported per search query`);return o.filters.push({field:d,value:w}),a},search:(d,w)=>{const E=o;if(d!==E.definition.field)throw new $("INTERNAL",`search index "${E.indexName}" on table "${r}" indexes "${E.definition.field}", not "${d}"`);const S=at(w,t).length;if(S>Lt)throw new $("BAD_REQUEST",`search index "${E.indexName}" on table "${r}": at most ${String(Lt)} search terms are supported (got ${String(S)})`);return E.field=d,E.query=w,E.hasQuery=!0,a}};return a},to=o=>{if(o.length>Y)throw new $("BAD_REQUEST",`more than ${String(Y)} documents match this search — narrow it with filters or read it a page at a time with .paginate()`)},no=o=>Math.min(o.offset+o.numItems+1,Y),oo=o=>btoa(`search:${String(o)}`),ro=o=>{let r;try{r=Jn(o)}catch{return}if(!r.startsWith("search:"))return;const t=Number(r.slice(7));return Number.isInteger(t)&&t>=0?t:void 0},io=o=>{if(typeof o.endCursor=="string")throw new $("BAD_REQUEST","bounded (endCursor) pagination is not supported on search queries — relevance order has no stable range boundary");if(!Number.isFinite(o.numItems))throw new $("BAD_REQUEST",`search pagination needs a finite numItems, got ${String(o.numItems)}`);const r=Math.max(0,Math.floor(o.numItems)),t=o.cursor?ro(o.cursor):0;if(t===void 0)throw Yn();if(t+r>=Y)throw new $("BAD_REQUEST",`search pagination reaches the ${String(Y)}-document limit (offset ${String(t)} + ${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,Y-t-1))} or fewer, or narrow the query or the filters instead`);return{numItems:r,offset:t}},so=(o,r)=>{const t=r.offset+r.numItems,a=r.numItems>0&&o.length>t;return{continueCursor:a?oo(t):null,isDone:!a,page:o.slice(r.offset,t)}},co=o=>{if(o===void 0)return Y+1;if(!Number.isFinite(o))return Y;const r=Math.max(0,Math.floor(o));if(r>Y)throw new $("BAD_REQUEST",`search returns at most ${String(Y)} documents (asked for ${String(r)}) — narrow the query or paginate instead`);return r},Ge=o=>{const r=new Map;return t=>{const a=r.get(t);if(a!==void 0)return a;const d=o(_e(t));return r.set(t,d),d}},ue=_e(oe),ao=Ge(o=>`INSERT INTO ${o} (id, _creationTime, ${ue}) VALUES (?, ?, ?)`),Ft=Ge(o=>`UPDATE ${o} SET ${ue} = ? WHERE id = ? AND ${ue} = ?`),lo=Ge(o=>`UPDATE ${o} SET _creationTime = ?, ${ue} = ? WHERE id = ? AND ${ue} = ?`),uo=Ge(o=>`DELETE FROM ${o} WHERE id = ? AND ${ue} = ?`),fo="SELECT changes() AS changed",qt=new Map,ho="",wo=o=>{const r=JSON.stringify(o),t=qt.get(r);if(t!==void 0)return t;const a=o.map(w=>i`SELECT ${i.raw(`'${w.replaceAll("'","''")}'`)} AS __t__, id, _creationTime, ${i.identifier(oe)} FROM ${i.identifier(w)} WHERE id = ${ho}`),{sql:d}=Qt("sqlite",i`${ct(a)} LIMIT 1`);return qt.set(r,d),d},po=(o,r)=>r.map(()=>o),go=/^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/iu,$o=o=>{if(!go.test(o))throw new $("INTERNAL",`invalid clientId ${JSON.stringify(o)}: a client-supplied row id must be a UUID`)},Bt=50,Xt=500,qe=Math.floor(Vt.boundParams/3),$e=Vt.boundParams,yo=128,ae=(o,r,t)=>{const a=r??Xt;if(o>a)throw new $("BATCH_LIMIT_EXCEEDED",`${t}: batch of ${String(o)} exceeds the limit of ${String(a)} (raise options.limit or chunk the call)`,{status:400})},Eo=o=>{const r={eq:(t,a)=>(o.sqlConditions.push({comparator:"=",field:t,value:a}),r),gt:(t,a)=>(o.sqlConditions.push({comparator:">",field:t,value:a}),r),gte:(t,a)=>(o.sqlConditions.push({comparator:">=",field:t,value:a}),r),lt:(t,a)=>(o.sqlConditions.push({comparator:"<",field:t,value:a}),r),lte:(t,a)=>(o.sqlConditions.push({comparator:"<=",field:t,value:a}),r)};return r},mo=o=>Math.max(o,Y),Zt=(o,r)=>{const t=o.filters.map(a=>i`${X(a.field)} = ${re(a.value)}`);return r&&t.push(r),t},So=(o,r,t,a,d)=>{const w=at(t.query,st(t.definition.language));if(w.length===0)return[];const E=wn(r,t.indexName),S=`${E}__vocab`,_=w.length-1,D=w.map((R,k)=>{const q=Zn(R,k===_),U=q.exact?i`${i.identifier("term")} = ${q.lower}`:i`${i.identifier("term")} >= ${q.lower} AND ${i.identifier("term")} < ${q.upper}`;return i`SELECT ${i.identifier("doc")}, ${i.raw(String(k))} AS ${i.identifier("__term__")}, COUNT(*) AS ${i.identifier("__n__")} FROM ${i.identifier(S)} WHERE ${U} GROUP BY ${i.identifier("doc")}`}),y=w.map((R,k)=>i`SUM(CASE WHEN u.${i.identifier("__term__")} = ${i.raw(String(k))} THEN u.${i.identifier("__n__")} ELSE 0 END)`),A=i`SELECT f.${i.identifier(De)} AS ${i.identifier(De)}, ${i.join(y,i` + `)} AS ${i.identifier("__score__")} FROM (${ct(D)}) u JOIN ${i.identifier(E)} f ON f.rowid = u.${i.identifier("doc")} GROUP BY f.${i.identifier(De)} HAVING ${i.join(y.map(R=>i`${R} > 0`),i` AND `)}`,I=Zt(t,d);let F=i`SELECT m.id, m._creationTime, m.${i.identifier(oe)}, s.${i.identifier("__score__")} AS ${i.identifier("__score__")} FROM (${A}) s JOIN ${i.identifier(r)} m ON m.id = s.${i.identifier(De)}`;I.length>0&&(F=i`${F} WHERE ${i.join(I,i` AND `)}`),F=i`${F} ORDER BY s.${i.identifier("__score__")} DESC, m._creationTime DESC, m.id ASC LIMIT ${i.raw(String(a))}`;const j=[];for(const R of N(o,F)){const k=Kt(R);if(k){const q=R.__score__;j.push({document:k,score:typeof q=="number"?q:Number(q??0)})}}return j},_o=(o,r,t,a,d)=>{const w=st(t.definition.language),E=at(t.query,w);if(E.length===0)return[];const S=Zt(t,d);let _=i`SELECT id, _creationTime, ${i.identifier(oe)} FROM ${i.identifier(r)}`;S.length>0&&(_=i`${_} WHERE ${i.join(S,i` AND `)}`),_=i`${_} ORDER BY _creationTime DESC, id ASC LIMIT ${i.raw(String(mo(a)))}`;const D=N(o,_).toArray(),y=[];for(const A of D){const I=Kt(A);if(!I)continue;const F=Xn(pn(I,t.definition),E);F>0&&y.push({creationTime:typeof I._creationTime=="number"?I._creationTime:0,doc:I,id:typeof I._id=="string"?I._id:"",score:F})}return y.sort((A,I)=>I.score-A.score||I.creationTime-A.creationTime||A.id.localeCompare(I.id)),y.slice(0,a).map(A=>({document:A.doc,score:A.score}))},tt=(o,r,t,a)=>{if(!Number.isFinite(o.lat)||o.lat<-90||o.lat>90||!Number.isFinite(o.lng)||o.lng<-180||o.lng>180)throw new $("BAD_REQUEST",`geo index "${a}" on table "${t}": ${r} must have a finite lat in [-90, 90] and lng in [-180, 180]`)},Ro=(o,r)=>{const t=o,a={near:(d,w)=>{if(t.within)throw new $("INTERNAL",`geo index "${t.indexName}" on table "${r}": call .near() or .within(), not both`);if(tt(d,".near() point",r,t.indexName),!Number.isFinite(w)||w<=0)throw new $("BAD_REQUEST",`geo index "${t.indexName}" on table "${r}": .near() radiusMeters must be a finite number > 0, got ${String(w)}`);return t.near={point:{lat:d.lat,lng:d.lng},radiusMeters:w},a},within:d=>{if(t.near)throw new $("INTERNAL",`geo index "${t.indexName}" on table "${r}": call .near() or .within(), not both`);if(tt(d.sw,".within() sw corner",r,t.indexName),tt(d.ne,".within() ne corner",r,t.indexName),d.sw.lat>d.ne.lat)throw new $("BAD_REQUEST",`geo index "${t.indexName}" on table "${r}": .within() corners are transposed (sw.lat > ne.lat)`);if(d.sw.lng>d.ne.lng)throw new $("BAD_REQUEST",`geo index "${t.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 t.within={ne:{lat:d.ne.lat,lng:d.ne.lng},sw:{lat:d.sw.lat,lng:d.sw.lng}},a}};return a},To=(o,r)=>{const t=o[r];if(t===null||typeof t!="object")return;const{lat:a,lng:d}=t;return typeof a=="number"&&typeof d=="number"?{lat:a,lng:d}:void 0},Ao=(o,r)=>{const t=To(o,r.definition.field);if(!t)return;const a=typeof o._creationTime=="number"?o._creationTime:0;if(r.near){const d=Ln(r.near.point,t);return d<=r.near.radiusMeters?{creationTime:a,distance:d}:void 0}return kn(t,r.within)?{creationTime:a,distance:0}:void 0},vo=(o,r,t,a)=>{if(!t.near&&!t.within)throw new $("INTERNAL",`geo index "${t.indexName}" on table "${r}": call .near(point, radius) or .within(box)`);const d=t.near?Mn(t.near.point,t.near.radiusMeters):Dn(t.within),w=xn(r,t.indexName),E=d.map(A=>i`(g.${i.identifier("__geohash__")} >= ${A} AND g.${i.identifier("__geohash__")} < ${`${A}{`})`),S=[i`(${i.join(E,i` OR `)})`];a&&S.push(a);const _=i`SELECT m.id, m._creationTime, m.${i.identifier(oe)} FROM ${i.identifier(w)} g JOIN ${i.identifier(r)} m ON m.id = g.${i.identifier("__id__")} WHERE ${i.join(S,i` AND `)}`,D=N(o,_).toArray(),y=[];for(const A of D){const I=le(A),F=I?Ao(I,t):void 0;I&&F&&y.push({creationTime:F.creationTime,distance:F.distance,doc:I})}return y.sort((A,I)=>A.distance-I.distance||I.creationTime-A.creationTime),y},en=(o,r,t,a)=>{const d=[];for(const w of o)if(r.every(E=>E(a(w)))&&(d.push(w),typeof t=="number"&&d.length>=t))break;return d},Io=(o,r,t,a,d,w=()=>{})=>{const E=t.within!==void 0,S=vo(o,r,t,d).map(_=>({distanceMeters:E?null:_.distance,document:_.doc}));return w(S.length),typeof a=="number"?S.slice(0,Math.max(0,Math.floor(a))):S},tn=(o,r,t,a,d,w=()=>{})=>{const{geo:E}=t;if(!E)throw new $("INTERNAL","runGeoTerminalScored called without a staged geo query");const S=t.inMemoryFilters.length>0,_=Io(o,r,E,S?void 0:d,a,w);return S?en(_,t.inMemoryFilters,d,D=>D.document):_},nn=(o,r,t,a)=>{const d=`SELECT id, _creationTime, ${_e(oe)} FROM ${_e(o)}`,w=`ORDER BY ${t}${a===void 0?"":` LIMIT ${String(a)}`}`;return r===void 0?Ue(`${d} ${w}`):me(`${d} WHERE `,r,` ${w}`)},Co=(o,r,t,a,d,w=()=>{})=>tn(o,r,t,a,d,w).map(E=>E.document),xo=(o,r,t,a,d,w,E=()=>{})=>{const S=[];for(const A of t.sqlConditions)S.push(i`${X(A.field)} ${i.raw(A.comparator)} ${re(A.value)}`);a&&S.push(a);let _=i`SELECT id, _creationTime, ${i.identifier(oe)} FROM ${i.identifier(r)}`;S.length>0&&(_=i`${_} WHERE ${i.join(S,i` AND `)}`),_=i`${_} ORDER BY ${d}`,typeof w=="number"&&t.inMemoryFilters.length===0&&(_=i`${_} LIMIT ${i.raw(String(Math.max(0,Math.floor(w))))}`);const D=N(o,_).toArray();E(D.length);const y=[];for(const A of D){const I=le(A);if(I&&t.inMemoryFilters.every(F=>F(I))&&(y.push(I),typeof w=="number"&&y.length>=w))break}return y},ye={fieldRef:X,serialize:re},on=(o,r)=>{const t=r===void 0?void 0:o.shape[r];return t!==void 0&&Qn(t)},Wt=(o,r)=>r.some(t=>on(o,t)),Ut=(o,r,t)=>{if(on(o,r))throw new $("BAD_REQUEST",`${t}: "${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)`)},dt={fieldRef:o=>Ue(We(o)),serialize:re},bo=o=>{let r=0;const t=[],a={fieldRef:d=>Ue(We(d)),relationExists:d=>{const{childWhere:w,negated:E,parentTable:S,relation:_}=d,D=`__rel_${String(r)}`,y=t.at(-1)??S;r+=1,o(_.table,H);const A=_.kind==="one"?_.field:_.references,I=_.kind==="one"?_.references:_.field,F=Ue(`${Tt(D,I)} = ${Tt(y,A)}`);t.push(D);const j=ne(w,a,Pe);t.pop();const R=j===void 0?F:me(F," AND ",j),k=me("EXISTS (SELECT 1 FROM ",Dt(_.table)," AS ",Dt(D)," WHERE ",R,")");return E?me("NOT ",k):k},serialize:re};return a},rn=o=>{const r=o.map(t=>`${We(t.field)} ${t.direction==="desc"?"DESC":"ASC"}`);return o.some(t=>t.field==="_id"||t.field==="id")||r.push(`${We("id")} ${Yt(o)==="desc"?"DESC":"ASC"}`),r.join(", ")},Mo=o=>{const r=o.map(t=>i`${X(t.field)} ${i.raw(t.direction==="desc"?"DESC":"ASC")}`);return o.some(t=>t.field==="_id"||t.field==="id")||r.push(i`${X("id")} ${i.raw(Yt(o)==="desc"?"DESC":"ASC")}`),i.join(r,i`, `)},Do={"<":"lt","<=":"lte","=":"eq",">":"gt",">=":"gte"},sn=o=>new Set(o.sqlConditions.filter(r=>r.comparator==="=").map(r=>r.field)),Lo=o=>{const r=sn(o);let t=0;for(;t<o.indexFields.length&&r.has(o.indexFields[t]??"");)t+=1;return o.indexFields.slice(t)},cn=(o,r)=>{const t=o.order,a=Lo(o),{shape:d}=r;return a.length>0?nt(a.map(w=>({[w]:t})),d,{pinned:sn(o),uniqueBy:zt(r.indexes,d)}):nt([{_creationTime:t}],d)},ko=(o,r,t,a)=>{const d=o.sqlConditions.map(w=>({[w.field]:{[Do[w.comparator]??"eq"]:w.value}}));if(t&&d.push(Jt(r,ot(t))),a&&d.push(Bn(r,ot(a))),d.length!==0)return d.length===1?d[0]:{AND:d}},Fo=(o,r,t)=>{const a=[];for(const d of o){const w=le(d);if(w&&r.every(E=>E(w))&&(a.push(w),t!==void 0&&a.length>t))break}return a},qo=(o,r,t,a,d,w,E=()=>{})=>{const S=Math.max(0,Math.floor(d.numItems)),_=cn(a,t),D=typeof d.endCursor=="string",y=ne(ko(a,_,d.cursor,d.endCursor),dt,Pe),A=w&&y?me(y," AND ",w):w??y,I=a.inMemoryFilters.length>0,F=nn(r,A,rn(_),I||D?void 0:S+1),j=Se(o,F.text,...F.params).toArray();E(j.length);const R=Fo(j,a.inMemoryFilters,I||D?void 0:S);if(D){const O=R.length>=2?R[Math.floor(R.length/2)-1]:void 0;return{continueCursor:d.endCursor??null,isDone:!0,page:R,splitCursor:O?rt(O,_):null}}const k=R.length>S,q=k?R.slice(0,S):R,U=q.at(-1);return{continueCursor:k&&U?rt(U,_):null,isDone:!k,page:q}};class Bo extends ${constructor(r="unique() found more than one matching document"){super("NOT_UNIQUE",r,{name:"NotUniqueError"})}}const Wo=/\s/u,Uo=String.fromCodePoint(0),Pt=(o,r,t)=>{if(!o.tables[r])throw new $("INTERNAL",`unknown table: ${r}`);return typeof t!="string"||t.length===0||Wo.test(t)||t.includes(Uo)?null:t},Po=(o,r,t,a=()=>{},d=()=>{},w=()=>{})=>{const E=r.tables[t];if(!E)throw new $("INTERNAL",`unknown table: ${t}`);const S=de(E.softDeleteMode,void 0),_=S?ne(S,ye):void 0,D=S?ne(S,dt,Pe):void 0,y={indexFields:[],indexName:void 0,inMemoryFilters:[],order:"asc",sqlConditions:[]};let A=0;const I=m=>{const{search:C}=y;if(!C)throw new $("INTERNAL","runSearchFetch called without a staged search");_n(o,t,E);const M=y.inMemoryFilters.length>0,L=co(M?void 0:m),K=Cn(o);if(K&&!Rn(o,t,C.definition))throw new $("SEARCH_INDEX_BUILDING",`search index "${C.indexName}" on table "${t}" 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 Z=K?So(o,t,C,L,_):_o(o,t,C,L,_);return M?(A=Z.length,en(Z,y.inMemoryFilters,m,He=>He.document)):(m===void 0&&to(Z),Z)},F=m=>I(m).map(C=>C.document),j=m=>{const C=io(m);return so(F(no(C)),C)},R=()=>Mo(cn(y,E)),k=()=>{if(y.search||y.geo||y.indexName===void 0){d(void 0);return}d(On(t,y.indexName,y.indexFields,y.sqlConditions,re))},q=m=>{k();let C=0;const M=(()=>{if(y.search){const L=F(m);return C=A,L}return y.geo?Co(o,t,y,_,m,L=>{C=L}):xo(o,t,y,_,R(),m,L=>{C=L})})();return w(Math.max(C,M.length)),M},U=()=>{if(!y.search&&!y.geo)throw new $("INTERNAL",`ctx.db.query("${t}").collectWithScores() requires a staged .withSearchIndex(...) or .withGeoIndex(...)`);k();let m=0;const C=(()=>{if(y.search){const M=I(void 0);return m=A,M}return tn(o,t,y,_,void 0,M=>{m=M})})();return w(Math.max(m,C.length)),C},O={async*[Symbol.asyncIterator](){if(y.search){yield*q(void 0);return}const m=[...y.inMemoryFilters];let C;y.inMemoryFilters=[];try{for(;;){const M=await O.paginate({cursor:C??null,numItems:yo});for(const L of M.page)m.every(K=>K(L))&&(yield L);if(M.isDone||M.continueCursor===null)return;C=M.continueCursor}}finally{y.inMemoryFilters=m}},async collect(){return q(void 0)},async collectWithScores(){return U()},filter(m){return y.inMemoryFilters.push(m),O},async first(){return q(y.inMemoryFilters.length>0?void 0:1)[0]??null},order(m){return y.order=m==="desc"?"desc":"asc",O},async paginate(m){let C=0;if(k(),y.search){const L=j(m);return w(L.page.length),L}if(y.geo)throw new $("INTERNAL","pagination is not supported on geo queries; use .take(n) or .collect()");const M=qo(o,t,E,y,m,D,L=>{C=L});return w(Math.max(C,M.page.length)),M},async take(m){return q(m)},async unique(){const m=q(y.inMemoryFilters.length>0?void 0:2);if(m.length>1)throw new Bo(`unique() on table "${t}" matched ${String(m.length)} documents; expected at most one`);return m[0]??null},withGeoIndex(m,C){const M=(E.geoIndexes??[]).find(K=>K.name===m);if(!M)throw new $("INTERNAL",`unknown geo index "${m}" on table "${t}"`);a(t,m,"geo");const L={definition:M,indexName:m};if(y.geo=L,C(Ro(L,t)),!L.near&&!L.within)throw new $("INTERNAL",`geo index "${m}" on table "${t}" requires a .near(point, radius) or .within(box) call`);return O},withIndex(m,C){const M=E.indexes.find(L=>L.name===m);if(!M)throw new $("INTERNAL",`unknown index "${m}" on table "${t}"`);return a(t,m,"index"),y.indexName=m,y.indexFields=M.fields,C&&C(Eo(y)),O},withSearchIndex(m,C){const M=(E.searchIndexes??[]).find(K=>K.name===m);if(!M)throw new $("INTERNAL",`unknown search index "${m}" on table "${t}"`);a(t,m,"search");const L={definition:M,field:M.field,filters:[],hasQuery:!1,indexName:m,query:""};if(y.search=L,C(eo(L,t,st(M.language))),!L.hasQuery)throw new $("INTERNAL",`search index "${m}" on table "${t}" requires a .search(field, query) call`);return O}};return O},Gt=(o,r,t)=>{const a={...r};for(const[d,w]of jt(o)){if(w.serverDefault){a[d]=w.serverDefault({auth:t});continue}a[d]===void 0&&(w.defaultFn?a[d]=w.defaultFn():"defaultValue"in w&&(a[d]=w.defaultValue))}return a},Ht=(o,r,t,a)=>{const d=t;for(const[w,E]of jt(o)){if(E.serverDefault){w in r&&(d[w]=E.serverDefault({auth:a}));continue}E.onUpdateFn&&!(w in r)&&(d[w]=E.onUpdateFn())}},Ot=(o,r)=>{for(const t of Object.keys(r))if(r[t]===void 0)throw new $("INTERNAL",`Cannot ${o} field '${t}' to undefined — use null to clear a nullable field, or omit the key to leave it unchanged.`)},Go=/unique constraint failed/i,Ho=o=>o instanceof Error&&Go.test(o.message),Oo=/string or blob too big/iu,No=(o,r)=>{if(!(!(o instanceof Error)||!Oo.test(o.message)))throw new $("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.`)},it=(o,r,t,a)=>{try{Se(o,t,...a)}catch(d){throw Ho(d)?new Ee(`unique constraint violation on "${r}"`,"unique"):(No(d,r),d)}},Be=(o,r,t,a)=>{if(it(o,r,t,a),Se(o,fo).one().changed===0)throw new Ee(`optimistic concurrency conflict on "${r}" — the row changed during this mutation; refetch and retry`,"occ")},Nt=(o,r,t,a,d,w,E)=>{const S=[];for(let A=0;A<t.length+1;A+=1){const I=t[A],F=a[A],j=F?.direction==="desc"?"desc":"asc",R=I===void 0||F===void 0?i`${i.identifier(Pn)} < ${E}`:Gn(I,w[A],j,!1);if(R===void 0)continue;const k=[];for(let U=0;U<A;U+=1)k.push(i`${i.identifier(t[U])} IS ${w[U]}`);k.push(R);const[q]=k;S.push(k.length===1&&q!==void 0?q:i`(${i.join(k,i` AND `)})`)}const _=S.length>0?i.join(S,i` OR `):i`1 = 0`,D=N(o,i`SELECT COUNT(*) AS c FROM ${i.identifier(r)} WHERE ${i.identifier("__partition__")} = ${d} AND (${_})`).one(),y=N(o,i`SELECT COUNT(*) AS c FROM ${i.identifier(r)} WHERE ${i.identifier("__partition__")} = ${d}`).one();return{before:D.c,total:y.c}},Tr=o=>{const{sql:r}=o,{schema:t}=o,a=o.broadcast??(()=>{});let d;const w=()=>o.inTransaction?.()===!0,E=e=>t.tables[e]?.commitOrderedMode!==!0?{}:((d===void 0||!w())&&(d=An(r)),{[vn]:d}),S=(e,...n)=>{const s=t.tables[e]?.indexes;if(!s||s.length===0)return;const f=[];for(const h of n)h&&f.push(...Hn(s,h,re));return f.length>0?f:void 0},{headroom:_}=o;let D=!1;const y=async e=>{const n=D;D=!0;try{return await e()}finally{D=n}},A=o.onRead??(()=>{}),I=e=>{_t(t.tables[e])&&A(Ct,Ct)},F=o.onReadRange??(e=>{A(e.table,H)}),j=e=>{I(e.table),F(e)},R=(e,n)=>{n!==void 0&&n!==H&&!D&&_?.recordRead(1),I(e),A(e,n)},k=o.onIndexUse??(()=>{}),q=o.onWrite??(()=>{}),U=e=>{D||_?.recordWrite(e)},O=async e=>{U(e.doc),await q(e)},{cache:m}=o,C=o.clock??(()=>Date.now()),M=o.idGenerator??(()=>crypto.randomUUID()),L=o.scheduler??$n,{globalDb:K}=o,Z=o.auth??{identity:null,userId:null},He=o.cdc??!1,Oe=L,an=Vn({scheduler:typeof Oe.list=="function"&&typeof Oe.get=="function"?Oe:void 0,storage:o.storage}),fe=(e,n,s,f)=>{He&&!_t(t.tables[e])&&Tn(r,C(),e,n,s,f)},ie=e=>t.tables[e]?.shardMode?.kind==="global",lt=(e,n)=>{if(ie(e)){if(!K)throw new $("INTERNAL",`cross-backend ${n} for global table '${e}' requires a globalDb writer — pass one to createShardCtxDb({ globalDb })`);return K}return P},Ne=e=>lt(e,"cascade"),V=(e,n)=>{if(ie(e)){if(!K)throw new $("INTERNAL",`${n} on global table '${e}' requires a globalDb writer — pass one to createShardCtxDb({ globalDb })`);return K}},ut=async(e,n,s,f,h)=>{h&&U(s);const u=await e.insert(n,s,f);return a({key:u,op:"insert",row:{...s,_id:u},table:n}),u},je=(e,n)=>lt(e,"relation load").findMany(e,n),ft=(e,n)=>(ie(e)&&R(e,H),je(e,n)),dn=e=>!ie(e.table),ht=o.relationExistsPushDown??"auto",wt=ht!=="never",{maxRelationKeys:pt}=o,Re=(e,n,s)=>xt(e,{fetcher:ft,maxRelationKeys:pt,relationBaseWhere:s,schema:t,tableName:n}),gt=async(e,n,s,f)=>{const h=V(e,"relation grouped count");if(h)return R(e,H),jn((B,v)=>h.count(B,v),e,n,s,f);const u=t.tables[e];if(!u)throw new $("INTERNAL",`unknown table: ${e}`);R(e,H);const c=de(u.softDeleteMode,void 0),l={[n]:{in:s}},p=z(z(l,f),c),T=await Re(p,e,void 0),g=ne(T,ye),b=X(n);let x=i`SELECT ${b} AS __fk__, COUNT(*) AS count FROM ${i.identifier(e)}`;g&&(x=i`${x} WHERE ${g}`),x=i`${x} GROUP BY ${b}`;const G=N(r,x).toArray();return new Map(G.map(B=>[B.__fk__,B.count]))};let Te=0;const $t=new Set;for(const[e,n]of Object.entries(t.tables))for(const s of Object.values(n.triggerMap??{}))$t.add(`${e} ${s.timing} ${s.op}`);const ee=(e,n,s)=>$t.has(`${e} ${n} ${s}`),te=async(e,n,s)=>{if(Te+=1,Te>Bt)throw Te-=1,new Ee(`trigger recursion exceeded ${String(Bt)} levels on "${s.table}" — check for a self-triggering write`,"trigger");try{await zn({ctx:un,event:s,op:n,schema:t,tableName:s.table,timing:e})}finally{Te-=1}},{ensureBackfilledForTable:he,ensureBackfilledIndex:Ke,ensureRankBackfilled:Qe,ensureRankBackfilledForTable:we,syncAggregates:Ae,syncCompanionsForInsert:yt,syncGeo:ve,syncRanks:pe,syncSearch:Ie}=hn({broadcast:a,indexKeysFor:(e,n)=>S(e,n),invalidateCache:(e,n,s)=>m?.invalidate(e,n,S(e,s)),recordCdc:fe,schema:t,sql:r}),Et=(e,n,s)=>{const{shardMode:f}=n;if(f?.kind==="shardBy"&&!(f.field!==void 0&&(s.partitionBy??[]).includes(f.field)))throw Object.assign(new Error(`rank index "${s.name}" on "${e}" partitions across shards (shard key "${f.field??"?"}" is not in partitionBy) — a shard-local rank()/rankPage() would be wrong; roll it up through the Query Coordinator instead`),{code:"CROSS_SHARD_RANK_UNSUPPORTED",name:"LunoraError",status:400})},mt=e=>Object.entries(t.tables).filter(([,n])=>n.shardMode?.kind!=="global").map(([n])=>n).filter(n=>e===void 0||n===e),ge=e=>e===void 0||ie(e)?K:void 0,se=(e,n)=>{const s=mt(n);for(let f=0;f<s.length;f+=$e){const h=s.slice(f,f+$e),[u]=Se(r,wo(h),...po(e,h)).toArray();if(!u)continue;const c=u.__t__,l=le(u);if(typeof c!="string"||!l)return;const p=u[oe];return{docJson:typeof p=="string"?p:ce(p??{}),row:l,tableName:c}}},ln=(e,n)=>{const s=[...new Set(e)],f=new Map;if(s.length===0)return f;const h=mt(n);for(let u=0;u<h.length;u+=$e){const c=h.slice(u,u+$e),l=Math.floor($e/c.length),p=bn(i`${i.identifier("id")}`,s,!1,l),T=c.map(g=>i`SELECT ${i.raw(`'${g.replaceAll("'","''")}'`)} AS __t__, id FROM ${i.identifier(g)} WHERE ${p}`);for(const g of N(r,ct(T))){const{id:b,__t__:x}=g;typeof x=="string"&&typeof b=="string"&&f.set(b,x)}}return f},St={assertRankPartitionLocal:Et,ensureRankBackfilled:Qe,onRead:R,rowToDocument:le,schema:t,sql:r},P={system:an,async aggregate(e,n){const s=V(e,"aggregate");if(s)return R(e,H),s.aggregate(e,n);const f=t.tables[e];if(!f)throw new $("INTERNAL",`unknown table: ${e}`);if(Le(n.op),n.op==="count")return P.count(e,{baseWhere:n.baseWhere,relationBaseWhere:n.relationBaseWhere,restrictsCounts:n.restrictsCounts,where:n.where});if(!n.field)throw new $("INTERNAL",`aggregate(${e}, { op: "${n.op}" }): "field" is required for non-count reducers`);R(e,H);const h=de(f.softDeleteMode,void 0),u=z(z(n.baseWhere,n.where),h),c=await Re(u,e,n.relationBaseWhere),l=c!==u;if(f.aggregateIndexes&&!n.baseWhere&&!l&&(!h||Wt(f,[n.field]))){const B=Sn(f.aggregateIndexes,n.op,n.field,n.where);if(B){Ke(e,B.index);const v=ze(B.index.by??[],B.key),Q=Ve(e,B.index.name),J=N(r,i`SELECT ${ke} AS value, ${Xe} AS count FROM ${i.identifier(Q)} WHERE ${Fe} = ${v}`).toArray()[0];return Je(n.op,J)}}Ut(f,n.field,`aggregate(${e}, { op: "${n.op}", field: "${n.field}" })`);const p=ne(c,ye),T=Le(n.op),g=X(n.field);let b=i`SELECT ${i.raw(T)}(${g}) AS value FROM ${i.identifier(e)}`;p&&(b=i`${b} WHERE ${p}`);const G=N(r,b).toArray()[0]?.value;return G??null},asId(e,n){const s=Pt(t,e,n);if(s===null)throw new $("BAD_REQUEST",`asId("${e}", …): "${n}" is not a valid id for table "${e}"`,{status:400});return s},async count(e,n){const s=V(e,"count");if(s)return R(e,H),s.count(e,n);const f=t.tables[e];if(!f)throw new $("INTERNAL",`unknown table: ${e}`);const h=yn(n);if(h.restrictsCounts)throw new Ye(e);R(e,H);const u=de(f.softDeleteMode,void 0),c=z(z(h.baseWhere,h.where),u),l=await Re(c,e,h.relationBaseWhere),p=l!==c;if(f.aggregateIndexes&&!h.baseWhere&&!p&&!u){const x=mn(f.aggregateIndexes,h.where);if(x){Ke(e,x.index);const G=ze(x.index.by??[],x.key),B=Ve(e,x.index.name),v=N(r,i`SELECT ${ke} AS value FROM ${i.identifier(B)} WHERE ${Fe} = ${G}`).toArray();return v[0]===void 0?0:v[0].value??0}}const T=ne(l,ye);let g=i`SELECT COUNT(*) AS count FROM ${i.identifier(e)}`;return T&&(g=i`${g} WHERE ${T}`),N(r,g).one().count},async delete(e,n,s){const f=se(e,n);if(!f){const g=ge(n);g&&(U(void 0),await g.delete(e,n,s));return}const{docJson:h,row:u,tableName:c}=f,l=t.tables[c],p=s?.hard===!0,T=!p&&l?.softDeleteMode?l.softDeleteMode.field:void 0;if(!(T&&u[T]!==null&&u[T]!==void 0)){if(ee(c,"before","delete")&&await te("before","delete",{id:e,op:"delete",previous:u,table:c}),await Nn({deletedId:e,deletedReference:g=>u[g],findHolders:async(g,b,x)=>(await Ne(g).findMany(g,{includeDeleted:p,where:{[b]:x}})).page,onCascade:(g,b)=>Ne(g).delete(b,void 0,s),onRestrict:g=>{throw new Ee(g,"restrict")},onSetNull:(g,b,x)=>Ne(g).patch(b,{[x]:null}),schema:t,tableName:c}),he(c),we(c),T){const g={...u,...E(c),[T]:C(),_id:e};Be(r,c,Ft(c),[ce(g),e,h]),Ie(c,e,g,u),ve(c,e,void 0),Ae(c,u,g),pe(c,e,u,void 0),m?.invalidate(c,e,S(c,u,g)),fe(c,e,"update",g),a({indexKeys:S(c,u,g),key:e,op:"update",row:g,table:c}),ee(c,"after","delete")&&await te("after","delete",{id:e,op:"delete",previous:u,table:c}),await O({id:e,op:"delete",table:c});return}Be(r,c,uo(c),[e,h]),Ie(c,e,void 0),ve(c,e,void 0),Ae(c,u,void 0),pe(c,e,u,void 0),m?.invalidate(c,e,S(c,u)),fe(c,e,"delete"),a({indexKeys:S(c,u),key:e,op:"delete",table:c}),ee(c,"after","delete")&&await te("after","delete",{id:e,op:"delete",previous:u,table:c}),await O({id:e,op:"delete",table:c})}},async deleteAll(e,n){if(!t.tables[e])throw new $("INTERNAL",`unknown table: ${e}`);const s=Math.max(1,n?.chunkSize??Xt),f=n?.hard===void 0?void 0:{hard:n.hard},h=ie(e)?void 0:e;let u=0;return await y(async()=>{for(;;){const l=(await P.findMany(e,{limit:s})).page.map(p=>String(p._id));if(l.length===0)break;for(const p of l)await P.delete(p,h,f),u+=1;if(l.length<s)break}}),{deleted:u}},async deleteMany(e,n,s){ae(e.length,n?.limit,"deleteMany");for(const f of e)await P.delete(f,s);return{deleted:e.length}},async deleteWhere(e,n,s){const u=(await(V(e,"deleteWhere")??P).findMany(e,{where:n})).page.map(c=>String(c._id));if(ae(u.length,s?.limit,"deleteWhere"),P.deleteMany===void 0)throw new $("INTERNAL",`ctx.db.${e}.deleteMany is unavailable: this writer has no batch delete`);return P.deleteMany(u,s)},async findFirst(e,n={}){return(await P.findMany(e,{...n,limit:1,omitContinueCursor:!0})).page[0]??null},async findFirstOrThrow(e,n={}){const s=await P.findFirst(e,n);if(s===null)throw new Fn(`findFirstOrThrow: no "${e}" document matched`);return s},async findMany(e,n={}){const s=V(e,"findMany");if(s)return R(e,H),s.findMany(e,n);const f=t.tables[e];if(!f)throw new $("INTERNAL",`unknown table: ${e}`);const h=!n.where&&!n.baseWhere;h?R(e,H):R(e);const u=nt(n.orderBy,f.shape,{pinned:qn(n.where),uniqueBy:zt(f.indexes,f.shape)}),c=n.cursor?Jt(u,ot(n.cursor)):void 0;let l=z(n.baseWhere,n.where);l=z(l,de(f.softDeleteMode,n.includeDeleted)),l=await xt(l,{canPushExists:wt?dn:void 0,existsPushMode:ht==="always"?"always":"auto",fetcher:ft,maxRelationKeys:pt,relationBaseWhere:n.relationBaseWhere,schema:t,tableName:e}),c&&(l=l?{AND:[l,c]}:c);const p=wt?bo(R):dt,T=ne(l,p,Pe),g=typeof n.limit=="number"?Math.max(0,Math.floor(n.limit)):void 0,b=nn(e,T,rn(u),g===void 0?void 0:g+1),x=Se(r,b.text,...b.params).toArray();h&&!D&&_?.recordRead(x.length);const G=[];for(const J of x){const W=le(J);W&&(G.push(W),!h&&typeof W._id=="string"&&R(e,W._id))}if(g===void 0)return n.with&&await bt({groupedCounter:gt,fetcher:je,parents:G,...Mt(n),schema:t,tableName:e,with:n.with}),{continueCursor:null,isDone:!0,page:At(G,n.select,n.with)};const B=G.length>g,v=B?G.slice(0,g):G,Q=v.at(-1);return n.with&&await bt({fetcher:je,groupedCounter:gt,parents:v,...Mt(n),schema:t,tableName:e,with:n.with}),{continueCursor:B&&Q&&n.omitContinueCursor!==!0?rt(Q,u):null,isDone:!B,page:At(v,n.select,n.with)}},async get(e,n){const s=se(e,n);if(!s){const f=ge(n);return f?f.get(e,n):null}return R(s.tableName,e),s.row},async lookupById(e,n){const s=se(e,n);return s?(R(s.tableName,e),{row:s.row,tableName:s.tableName}):null},async groupBy(e,n){const s=V(e,"groupBy");if(s)return R(e,H),s.groupBy(e,n);const f=t.tables[e];if(!f)throw new $("INTERNAL",`unknown table: ${e}`);R(e,H);const h=n.agg??{op:"count"};if(Le(h.op),h.op!=="count"&&!h.field)throw new $("INTERNAL",`groupBy(${e}, { agg: { op: "${h.op}" } }): "field" is required for non-count reducers`);const u=de(f.softDeleteMode,void 0),c=z(z(n.baseWhere,n.where),u),l=await Re(c,e,n.relationBaseWhere),p=l!==c,T=[...n.by,h.field];if(f.aggregateIndexes&&!n.baseWhere&&!p&&(!u||Wt(f,T))){const v=En(f.aggregateIndexes,h.op,h.field,n.by,n.where),Q=v===void 0?0:Object.keys(v.partial).length,J=v?.index.by?.length??0;if(v&&(Q===0||Q===J)){Ke(e,v.index);const W=Ve(e,v.index.name),Ce=Object.keys(v.partial),xe=[];if(Ce.length===(v.index.by??[]).length&&Ce.length>0){const be=ze(v.index.by??[],v.partial),Me=N(r,i`SELECT ${ke} AS value, ${Xe} AS count FROM ${i.identifier(W)} WHERE ${Fe} = ${be}`).toArray();return Me.length>0&&xe.push({key:{...v.partial},value:Je(h.op,Me[0])}),xe}const fn=N(r,i`SELECT ${Fe} AS key, ${ke} AS value, ${Xe} AS count FROM ${i.identifier(W)}`).toArray();for(const be of fn){const Me=gn(JSON.parse(be.key));xe.push({key:Me,value:Je(h.op,be)})}return xe}}for(const v of T){if(v===void 0)continue;const Q=v===h.field?`groupBy(${e}, { agg: { op: "${h.op}", field: "${v}" } })`:`groupBy(${e}, { by: [..."${v}"] })`;Ut(f,v,Q)}const g=ne(l,ye),b=n.by.map(v=>i`${X(v)} AS ${i.identifier(v)}`);if(h.op==="count")b.push(i`COUNT(*) AS value`);else{const{field:v}=h;if(v===void 0)throw new $("INTERNAL",`groupBy(${e}, { agg: { op: "${h.op}" } }): "field" is required for non-count reducers`);b.push(i`${i.raw(Le(h.op))}(${X(v)}) AS value`)}let x=i`SELECT ${i.join(b,i`, `)} FROM ${i.identifier(e)}`;g&&(x=i`${x} WHERE ${g}`),x=i`${x} GROUP BY ${i.join(n.by.map(v=>X(v)),i`, `)}`;const G=N(r,x).toArray(),B=[];for(const v of G){const Q={};for(const W of n.by)Q[W]=In(f.shape[W],v[W]??null);const{value:J}=v;B.push({key:Q,value:J==null?null:Number(J)})}return B},async insert(e,n,s){const f=V(e,"insert");if(f)return ut(f,e,n,s,!0);const h=t.tables[e];if(!h)throw new $("INTERNAL",`unknown table: ${e}`);const u=Gt(h,n,Z);et(h,u);let c;s?.clientId!==void 0?($o(s.clientId),c=s.clientId):s?.allowExplicitId&&typeof u._id=="string"?c=u._id:c=M();const l=s?.allowExplicitId&&typeof u._creationTime=="number"?u._creationTime:C(),p={...u,...E(e),_creationTime:l,_id:c};return ee(e,"before","insert")&&await te("before","insert",{doc:{...p},id:c,op:"insert",table:e}),he(e),we(e),it(r,e,ao(e),[c,l,ce(p)]),yt(e,c,p),ee(e,"after","insert")&&await te("after","insert",{doc:p,id:c,op:"insert",table:e}),await O({doc:p,id:c,op:"insert",table:e}),c},async insertManyUnsafe(e,n,s){if(ae(n.length,s?.limit,"insertManyUnsafe"),n.length===0)return[];const f=V(e,"insert");if(f){const l=[];for(const p of n)U(p);for(const p of n){const T=await f.insert(e,p,{allowExplicitId:s?.allowExplicitId});a({key:T,op:"insert",row:{...p,_id:T},table:e}),l.push(T)}return l}const h=t.tables[e];if(!h)throw new $("INTERNAL",`unknown table: ${e}`);he(e),we(e);const u=[];for(let l=0;l<n.length;l+=qe)u.push(E(e));const c=n.map((l,p)=>{const T=Gt(h,l,Z),g=s?.allowExplicitId===!0&&typeof T._id=="string"?T._id:M(),b=s?.allowExplicitId===!0&&typeof T._creationTime=="number"?T._creationTime:C(),x={...T,...u[Math.floor(p/qe)],_creationTime:b,_id:g};return{creationTime:b,document:x,id:g}});for(const l of c)U(l.document);for(let l=0;l<c.length;l+=qe){const p=i.join(c.slice(l,l+qe).map(g=>i`(${g.id}, ${g.creationTime}, ${ce(g.document)})`),i`, `),T=Qt("sqlite",i`INSERT INTO ${i.identifier(e)} (id, _creationTime, ${i.identifier(oe)}) VALUES ${p}`);it(r,e,T.sql,T.params)}for(const{document:l,id:p}of c)yt(e,p,l),await q({doc:l,id:p,op:"insert",table:e});return c.map(l=>l.id)},async insertMany(e,n,s){ae(n.length,s?.limit,"insertMany");const f=s?.skipDuplicates===!0,h=[],u=V(e,"insert");if(u)for(const l of n)U(l);const c=async l=>u?ut(u,e,l,void 0,!1):P.insert(e,l);for(const l of n)try{h.push(await c(l))}catch(p){if(f&&p instanceof Ee&&p.kind==="unique")h.push(null);else throw p}return h},normalizeId(e,n){return Pt(t,e,n)},async patch(e,n,s){const f=se(e,s);if(!f){const T=ge(s);if(T){U(n),await T.patch(e,n,s);return}throw new $("NOT_FOUND",`document not found: ${e}`)}const{docJson:h,row:u,tableName:c}=f,l=t.tables[c];if(!l)throw new $("INTERNAL",`unknown table: ${c}`);R(c,e),Ot("patch",n);const p={...u,...n,...E(c),_id:e};Ht(l,n,p,Z),et(l,p,!0),ee(c,"before","update")&&await te("before","update",{doc:{...p},id:e,op:"update",previous:u,table:c}),he(c),we(c),Be(r,c,Ft(c),[ce(p),e,h]),Ie(c,e,p,u),ve(c,e,p),Ae(c,u,p),pe(c,e,u,p),m?.invalidate(c,e,S(c,u,p)),fe(c,e,"update",p),a({indexKeys:S(c,u,p),key:e,op:"update",row:p,table:c}),ee(c,"after","update")&&await te("after","update",{doc:p,id:e,op:"update",previous:u,table:c}),await O({doc:p,id:e,op:"update",table:c})},async patchMany(e,n,s){ae(e.length,n?.limit,"patchMany");for(const f of e)await P.patch(f.id,f.patch,s);return{patched:e.length}},async patchWhere(e,n,s){const u=(await(V(e,"patchWhere")??P).findMany(e,{where:n.where})).page.map(c=>({id:String(c._id),patch:n.patch}));if(ae(u.length,s?.limit,"patchWhere"),P.patchMany===void 0)throw new $("INTERNAL",`ctx.db.${e}.patchMany is unavailable: this writer has no batch patch`);return await P.patchMany(u,s),{patched:u.length}},query(e){const n=V(e,"query");return n?(R(e,H),n.query(e)):Po(r,t,e,k,s=>{s?j(s):R(e,H)},s=>{D||_?.recordRead(s)})},async rank(e,n,s){const f=V(e,"rank");if(f)return R(e,H),f.rank(e,n,s);k(e,n,"rank");const h=t.tables[e];if(!h)throw new $("INTERNAL",`unknown table: ${e}`);const u=h.rankIndexes?.find(W=>W.name===n);if(!u)throw new $("INTERNAL",`unknown rankIndex "${n}" on table "${e}"`);if(Et(e,h,u),s.restrictsCounts)throw new Ye(e);R(e,H),Qe(e,u);const c=typeof s.row=="string"?s.row:s.row._id;if(!c)return null;const l=vt(e,u.name),p=u.sortBy.map((W,Ce)=>It(Ce)),T=p.map(W=>_e(W)).join(", "),g=N(r,i`SELECT ${i.identifier("__partition__")}, ${i.raw(T)} FROM ${i.identifier(l)} WHERE ${i.identifier("__id__")} = ${c}`).toArray(),[b]=g;if(b===void 0)return null;let x=b.__partition__;const G=z(s.baseWhere,s.where);Ze(G,t,e,"rank");const B=Wn(u,G);if(B){const W=Un(u.partitionBy??[],B);if(W!==x)return null;x=W}const v=p.map(W=>b[W]),{before:Q,total:J}=Nt(r,l,p,u.sortBy,x,v,c);return{position:Q+1,total:J}},async rankBefore(e,n,s){if(ie(e))throw new $("INTERNAL",`rankBefore is not supported on the global (.global()) table '${e}' — cross-shard rank cursors apply only to sharded tables`);const f=t.tables[e];if(!f)throw new $("INTERNAL",`unknown table: ${e}`);const h=f.rankIndexes?.find(p=>p.name===n);if(!h)throw new $("INTERNAL",`unknown rankIndex "${n}" on table "${e}"`);if(s.restrictsCounts)throw new Ye(e);R(e,H),Qe(e,h);const u=vt(e,h.name),c=h.sortBy.map((p,T)=>It(T)),l=h.sortBy.map((p,T)=>re(s.sortValues[T]??null));return Nt(r,u,c,h.sortBy,s.partitionKey,l,s.rowId)},async rankPage(e,n,s={}){Ze(z(s.baseWhere,s.where),t,e,"rankPage");const f=V(e,"rankPage");if(f)return R(e,H),f.rankPage(e,n,s);k(e,n,"rank");const{continueCursor:h,hasMore:u,rows:c}=Rt(St,e,n,s);return{continueCursor:h,isDone:!u,page:c.map(l=>l.doc)}},async rankPageRows(e,n,s={}){Ze(z(s.baseWhere,s.where),t,e,"rankPage"),k(e,n,"rank");const{directions:f,hasMore:h,rows:u}=Rt(St,e,n,s);return{directions:f,hasMore:h,rows:u}},async restore(e,n){const s=se(e,n);if(!s){const u=ge(n);if(u?.restore){await u.restore(e,n);return}throw new $("NOT_FOUND",`document not found: ${e}`)}const f=t.tables[s.tableName]?.softDeleteMode?.field;if(!f)throw new $("INTERNAL",`ctx.db.restore: table "${s.tableName}" is not a .softDelete() table`);const h=s.row[f]!==null&&s.row[f]!==void 0;await P.patch(e,{[f]:null},n),h&&pe(s.tableName,e,void 0,s.row)},async replace(e,n,s,f){const h=se(e,s);if(!h){const b=ge(s);if(b){U(n),await b.replace(e,n,s,f);return}throw new $("NOT_FOUND",`document not found: ${e}`)}const{docJson:u,row:c,tableName:l}=h,p=t.tables[l];if(!p)throw new $("INTERNAL",`unknown table: ${l}`);Ot("replace",n);const T=f?.allowExplicitId&&typeof n._creationTime=="number"?n._creationTime:C(),g={...n,...E(l),_creationTime:T,_id:e};Ht(p,n,g,Z),et(p,g),ee(l,"before","update")&&await te("before","update",{doc:{...g},id:e,op:"update",previous:c,table:l}),he(l),we(l),Be(r,l,lo(l),[T,ce(g),e,u]),Ie(l,e,g,c),ve(l,e,g),Ae(l,c,g),pe(l,e,c,g),m?.invalidate(l,e,S(l,c,g)),fe(l,e,"update",g),a({indexKeys:S(l,c,g),key:e,op:"update",row:g,table:l}),ee(l,"after","update")&&await te("after","update",{doc:g,id:e,op:"update",previous:c,table:l}),await O({doc:g,id:e,op:"update",table:l})},async wipeShard(e){const n=new Set(e?.exclude),s=e?.tables,f=Object.entries(t.tables).filter(([l,p])=>n.has(l)||s!==void 0&&!s.includes(l)?!1:p.shardMode?.kind!=="global").map(([l])=>l);if(s!==void 0){for(const l of s)if(!t.tables[l])throw new $("INTERNAL",`wipeShard: unknown table: ${l}`)}const h={};let u=0;const{deleteAll:c}=P;if(c===void 0)throw new $("INTERNAL","wipeShard: this writer has no deleteAll");for(const l of f){const p=await c(l,{...e?.chunkSize===void 0?{}:{chunkSize:e.chunkSize},hard:!0});h[l]=p.deleted,u+=p.deleted}return{deleted:u,tables:h}}},un={db:P,scheduler:L};return o.enforceRls===!0?Kn(P,t,(e,n)=>se(e,n)?.tableName,(e,n)=>ln(e,n)):P};export{Mr as CDC_LOG_TABLE,Vr as CLIENT_WATERMARK_TABLE,Zr as GLOBAL_SHAPE_SNAPSHOT_TABLE,si as IDEMPOTENCY_TABLE,Bo as NotUniqueError,hi as SEARCH_STATE_TABLE,zr as advanceClientWatermark,Dr as applyCdcChanges,Ot as assertNoExplicitUndefined,$o as assertValidClientId,Ir as backfillAggregateIndexes,Cr as backfillRankIndexes,xr as backfillSearchIndexes,Lr as bumpCdcEpoch,kr as cdcCanVouchFor,Fr as cdcSeqLeavingRows,qr as cdcTouchesTables,Br as cdcTrimmedError,Wr as compactCdcDocs,Tr as createShardCtxDb,Ur as cursorBelowRetainedFloor,ei as deleteGlobalShapeSnapshot,ti as deleteGlobalShapeSnapshotsForConnection,Jr as migrateClientWatermark,ni as migrateGlobalShapeSnapshot,Pr as minCdcReplayableSeq,Gr as minCdcSeq,Pt as normalizeIdStructurally,Hr as readCdcChangeKeys,Or as readCdcChanges,Nr as readCdcCursor,jr as readCdcEpoch,Yr as readClientWatermark,oi as readGlobalShapeSnapshot,ci as readIdempotent,ui as runShardMigrations,pi as selectShapeMembers,gi as selectShapeRows,Kr as trimCdcChanges,ai as trimIdempotent,ri as writeGlobalShapeSnapshot,di as writeIdempotent};
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{LunoraError as y}from"@lunora/errors";const w=Symbol.for("lunora.ctxdb.rls-unwrap");class R extends y{table;constructor(n){super("RLS_REQUIRED",`ctx.db access to "${n}" is denied: the schema is marked .rls("required"), so this table is protected. Apply RLS with .use(rls(policies)) in the procedure, or mark the table .public() to opt it out.`,{name:"RlsRequiredError"}),this.table=n}}const m=o=>Object.entries(o.tables).filter(([,n])=>n.shardMode?.kind!=="global").map(([n])=>n),M=(o,n,g)=>{const l=n?.tables,a=new Set(n?.exclude);for(const c of o)(l===void 0||l.includes(c))&&!a.has(c)&&g(c)},S={aggregate:"loop-gated",asId:"ungated",cdcChangedTables:"ungated",count:"loop-gated",delete:"id-gated",deleteAll:"loop-gated",deleteMany:"id-gated",deleteWhere:"inline-table-gated",findFirst:"loop-gated",findFirstOrThrow:"loop-gated",findMany:"loop-gated",get:"id-gated",groupBy:"loop-gated",insert:"loop-gated",insertMany:"loop-gated",insertManyUnsafe:"loop-gated",lookupById:"id-gated",normalizeId:"ungated",patch:"id-gated",patchMany:"id-gated",patchWhere:"inline-table-gated",query:"loop-gated",rank:"loop-gated",rankBefore:"loop-gated",rankPage:"loop-gated",rankPageRows:"loop-gated",replace:"id-gated",restore:"id-gated",system:"ungated",wipeShard:"sweep-gated"},W=Object.entries(S).filter(([,o])=>o==="loop-gated").map(([o])=>o),k=(o,n,g,l)=>{if(n.rlsMode!=="required")return o;const a=o,c=e=>{const t=n.tables[e];return t!==void 0&&t.isPublic!==!0},d=e=>{if(c(e))throw new R(e)},s=async(e,t)=>{if(t!==void 0){d(t);return}const r=await g(e);r!==void 0&&d(r)},p=async(e,t)=>{if(t!==void 0){d(t);return}if(!l){for(const i of e)await s(i,t);return}const r=await l([...new Set(e)],t);for(const i of e){const h=r.get(i);h!==void 0&&d(h)}},u={...o,delete:async(e,t,r)=>(await s(e,t),a.delete(e,t,r)),deleteMany:async(e,t,r)=>(await p(e,r),a.deleteMany(e,t,r)),deleteWhere:a.deleteWhere?async(e,t,r)=>(d(e),await a.deleteWhere?.(e,t,r)):void 0,get:async(e,t)=>(await s(e,t),a.get(e,t)),lookupById:async(e,t)=>(await s(e,t),a.lookupById?.(e,t)??null),patch:async(e,t,r)=>(await s(e,r),a.patch(e,t,r)),patchMany:async(e,t,r)=>(await p(e.map(i=>i.id),r),a.patchMany(e,t,r)),patchWhere:a.patchWhere?async(e,t,r)=>(d(e),await a.patchWhere?.(e,t,r)):void 0,replace:async(e,t,r,i)=>(await s(e,r),a.replace(e,t,r,i)),restore:async(e,t)=>(await s(e,t),a.restore?.(e,t))},f=a;for(const e of W){const t=f[e];typeof t=="function"&&(u[e]=(r,...i)=>(d(r),t.call(a,r,...i)))}if(a.wipeShard){const{wipeShard:e}=a;u.wipeShard=t=>(M(m(n),t,d),e.call(a,t))}return Object.defineProperty(u,w,{configurable:!0,enumerable:!1,value:o,writable:!1}),u};export{W as LOOP_GATED_METHODS,w as RLS_UNWRAP_SYMBOL,R as RlsRequiredError,S as WRITER_METHOD_GATING,k as guardWriter};
|