arrowbase 0.1.1

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.
@@ -0,0 +1,1802 @@
1
+ import { C as Collection, S as SyncConfig, I as InsertMutationFn, U as UpdateMutationFn, D as DeleteMutationFn, R as RowValue, b as IndexConstructor, c as CreateCollectionConfig, d as CreateOptimisticActionsOptions, T as Transaction, P as PacedMutationsConfig, e as DebounceStrategyOptions, f as DebounceStrategy, Q as QueueStrategyOptions, g as QueueStrategy, h as ThrottleStrategyOptions, i as ThrottleStrategy, L as LocalOnlyCollectionConfig, j as LocalOnlyCollectionOptionsResult, k as LocalStorageCollectionConfig, l as LocalStorageCollectionOptionsResult, m as QueryIR, n as Select, B as BasicExpression$1, A as Aggregate, o as IncludesSubquery, W as Where, H as Having, G as GroupBy, O as OrderBy, p as RootRefProxy, q as SingleRowRefProxy, r as ToArrayWrapper, s as ConcatToArrayWrapper, M as MaterializeWrapper, t as CompareOptions, u as PropRef, v as IncludesMaterialization, w as LoadSubsetOptions, x as UtilsRecord, y as StringCollationConfig, z as ChangeMessage, E as SubscribeChangesOptions, F as CollectionSubscription, J as BaseIndex, K as IndexOperation, N as RangeQueryOptions, V as IndexInterface, X as OrderByDirection, Y as IndexStats, Z as CollectionStatus, _ as BBox, $ as Point, a0 as OperatorName, a as CompiledSchema, a1 as ColumnTypeName } from './collection-DGlKgOGi.js';
2
+ export { a2 as BaseStrategy, a3 as BatchStrategy, a4 as BatchStrategyOptions, a5 as ChangeEmitter, a6 as ChangeEvent, a7 as ChangeListener, a8 as ChangeMessageOrDeleteKeyMessage, a9 as ChangeOp, aa as ClearStorageFn, ab as CollectionEvents, ac as CollectionMutationFnParams, ad as CollectionOptions, ae as CollectionRef, af as CollectionStatusChangeEvent, ag as CollectionSubscribersChangeEvent, ah as CollectionTruncateEvent, ai as ColumnDef, aj as ColumnTypeCode, ak as CompiledColumn, al as CurrentStateAsChangesOptions, am as Deferred, an as DeleteKeyMessage, ao as DeleteMutationFnParams, ap as Dictionary, aq as Fn, ar as From, as as Func, at as GetStorageSizeFn, au as INCLUDES_SCALAR_FIELD, av as IR, aw as IndexOptions, ax as InsertConfig, ay as InsertMutationFnParams, az as Join, aA as JoinClause, aB as Limit, aC as LineString, aD as LoadSubsetFn, aE as LocalOnlyCollectionUtils, aF as LocalStorageCollectionUtils, aG as MutationFn, aH as MutationFnParams, aI as NamespacedRow, aJ as NonEmptyArray, aK as Offset, aL as OperationConfig, aM as OperationType, aN as OptimisticChangeMessage, aO as OrderByClause, aP as Parser, aQ as PendingMutation, aR as Polygon, aS as QueryRef, aT as Ref, aU as RefLeaf, aV as RefProxy, aW as ResolveTransactionChanges, aX as SchemaInput, aY as StorageApi, aZ as StorageEventApi, a_ as Strategy, a$ as StrategyOptions, b0 as Transaction, b1 as TransactionCollectionLike, b2 as TransactionConfig, b3 as TransactionState, b4 as TransactionWithMutations, b5 as UnloadSubsetFn, b6 as UpdateMutationFnParams, b7 as Value, b8 as ValueOf, b9 as ValuesHeap, ba as VirtualPropsRefProxy, bb as add, bc as and, bd as avg, be as byteWidthOf, bf as caseWhen, bg as coalesce, bh as comparisonFunctions, bi as concat, bj as count, bk as createRefProxy, bl as createRefProxyWithSelected, bm as createResidualWhere, bn as createSingleRowRefProxy, bo as createTransaction, bp as defineSchema, bq as divide, br as eq, bs as followRef, bt as getActiveTransaction, bu as getHavingExpression, bv as getWhereExpression, bw as gt, bx as gte, by as ilike, bz as inArray, bA as isDictionary, bB as isExpressionLike, bC as isNull, bD as isRefProxy, bE as isResidualWhere, bF as isUndefined, bG as isVariableWidth, bH as length, bI as like, bJ as lower, bK as lt, bL as lte, bM as materialize, bN as max, bO as min, bP as multiply, bQ as not, bR as operators, bS as or, bT as subtract, bU as sum, bV as toArray, bW as toExpression, bX as upper, bY as val } from './collection-DGlKgOGi.js';
3
+ import { Q as Query$1, P as Predicate$1, O as OrderSpec, S as SortDir } from './query-CzV9E57Y.js';
4
+ export { C as ColumnRef, F as FilterExpr, a as FilterScalar, I as InNode, b as QueryExecutor, c as QuerySnapshot, d as StringOp, e as StringOpNode, f as StringOpOptions, g as f, h as fAnd, i as fContains, j as fEndsWith, k as fEq, l as fGt, m as fGte, n as fInArray, o as fIsNotNull, p as fIsNull, q as fLike, r as fLt, s as fLte, t as fMatches, u as fNeq, v as fNot, w as fOr, x as fStartsWith, y as query, z as run } from './query-CzV9E57Y.js';
5
+ import { D as Delta, S as SyncAdapter } from './types-CSoU6uED.js';
6
+ export { a as DeltaOp } from './types-CSoU6uED.js';
7
+ import { IR } from '@tanstack/db';
8
+
9
+ /**
10
+ * Layer-E metadata attached to Collections created through createCollection().
11
+ * Kept separate from createCollection.ts so collection mutation wiring can read
12
+ * handlers without creating a circular import.
13
+ */
14
+ interface CollectionMetadata {
15
+ sync?: SyncConfig;
16
+ onInsert?: InsertMutationFn;
17
+ onUpdate?: UpdateMutationFn;
18
+ onDelete?: DeleteMutationFn;
19
+ getKey?: (item: RowValue) => number | string;
20
+ gcTime?: number;
21
+ startSync?: boolean;
22
+ syncMode?: 'eager' | 'on-demand';
23
+ autoIndex?: 'off' | 'eager';
24
+ defaultIndexType?: IndexConstructor;
25
+ }
26
+ declare function getCollectionMetadata(collection: Collection): Readonly<CollectionMetadata> | undefined;
27
+
28
+ /**
29
+ * `createCollection` — `@tanstack/db`-compatible top-level factory.
30
+ *
31
+ * Mirrors the shape of `@tanstack/db`'s `createCollection(options)`
32
+ * but adapts it to ArrowBase's columnar store:
33
+ *
34
+ * - `schema` must be a `CompiledSchema` (Layer C will accept
35
+ * `StandardSchemaV1` and auto-compile).
36
+ * - `capacity` is required (ArrowBase is fixed-capacity).
37
+ * - `sync` / `onInsert` / `onUpdate` / `onDelete` are stored on the
38
+ * Collection as "Layer-E metadata"; Layer E wires them into the
39
+ * transaction flow. Accepting + storing them now keeps the API
40
+ * drop-in-swap-capable even before the behavior lands.
41
+ *
42
+ * Returns a `Collection` instance — same class as `Collection.create`.
43
+ *
44
+ * This is the Layer-B public entry point for ArrowBase users who want
45
+ * to write their import as `import { createCollection } from 'arrowbase'`
46
+ * and have it behave just like the TanStack DB import.
47
+ */
48
+
49
+ /**
50
+ * Construct a new Collection from a TanStack-DB-shaped config.
51
+ *
52
+ * @example
53
+ * ```ts
54
+ * import { compileSchema, defineSchema, createCollection } from 'arrowbase';
55
+ *
56
+ * const schema = compileSchema(defineSchema({
57
+ * name: 'todos',
58
+ * columns: {
59
+ * __id: { type: 'uint32' },
60
+ * title: { type: 'utf8' },
61
+ * done: { type: 'bool' },
62
+ * },
63
+ * }));
64
+ *
65
+ * const todos = createCollection({
66
+ * schema,
67
+ * capacity: 10_000,
68
+ * id: 'todos',
69
+ * getKey: (t) => t.__id as number,
70
+ * });
71
+ * ```
72
+ */
73
+ declare function createCollection<T extends object = RowValue, TKey extends string | number = number>(config: CreateCollectionConfig<T, TKey>): Collection;
74
+
75
+ /**
76
+ * Creates an optimistic action that opens a transaction per call.
77
+ *
78
+ * `onMutate` runs synchronously inside the transaction's ambient scope so
79
+ * collection writes are captured optimistically. `mutationFn` receives the same
80
+ * variables during commit.
81
+ */
82
+ declare function createOptimisticAction<TVariables = unknown, T extends object = Record<string, unknown>>(options: CreateOptimisticActionsOptions<TVariables, T>): (variables: TVariables) => Transaction<T>;
83
+
84
+ /**
85
+ * Creates a paced mutation helper with pluggable timing strategy.
86
+ *
87
+ * Optimistic writes run immediately inside an ambient transaction. Non-queue
88
+ * strategies coalesce calls into one pending transaction until the strategy
89
+ * invokes its callback. Queue strategies capture one transaction per call.
90
+ */
91
+ declare function createPacedMutations<TVariables = unknown, T extends object = Record<string, unknown>>(config: PacedMutationsConfig<TVariables, T>): (variables: TVariables) => Transaction<T>;
92
+
93
+ declare function debounceStrategy(options: DebounceStrategyOptions): DebounceStrategy;
94
+ declare function throttleStrategy(options: ThrottleStrategyOptions): ThrottleStrategy;
95
+ declare function queueStrategy(options?: QueueStrategyOptions): QueueStrategy;
96
+
97
+ declare function localOnlyCollectionOptions<T extends object = Record<string, unknown>, TKey extends string | number = string | number>(config: LocalOnlyCollectionConfig<T, TKey>): LocalOnlyCollectionOptionsResult<T, TKey>;
98
+
99
+ declare function localStorageCollectionOptions<T extends object = Record<string, unknown>, TKey extends string | number = string | number>(config: LocalStorageCollectionConfig<T, TKey>): LocalStorageCollectionOptionsResult<T, TKey>;
100
+
101
+ /**
102
+ * Maps a uint32 primary key to its dense row index. Phase 1 uses a JS Map;
103
+ * a SAB-resident open-addressed hash map is planned for cross-worker
104
+ * visibility in a later phase.
105
+ *
106
+ * `TOMBSTONE` (0xffffffff) is reserved as a sentinel for "no row".
107
+ */
108
+ declare const TOMBSTONE_ROW = 4294967295;
109
+ declare class RowIndex {
110
+ private map;
111
+ get size(): number;
112
+ /** Return the row index for `id`, or undefined if absent. */
113
+ lookup(id: number): number | undefined;
114
+ /** Same as lookup but throws if absent. */
115
+ require(id: number): number;
116
+ /** Insert `id → row`. Returns false if `id` already existed. */
117
+ insert(id: number, row: number): boolean;
118
+ /** Remove mapping for `id`. Returns the previous row index, or undefined. */
119
+ remove(id: number): number | undefined;
120
+ /** Iterate `[id, row]` pairs. */
121
+ entries(): IterableIterator<[number, number]>;
122
+ /** Remove every mapping. */
123
+ clear(): void;
124
+ }
125
+
126
+ type UndoOp = 'insert' | 'update' | 'delete';
127
+ /**
128
+ * A single reversible mutation. Stored in the undo ring so rollback can
129
+ * replay it in reverse.
130
+ *
131
+ * For v1 we keep the payload as plain JS objects (column name → prior JS
132
+ * value). Memory cost is O(touched columns) per mutation. A later phase may
133
+ * pack the payload into a per-row binary diff.
134
+ */
135
+ interface UndoRecord {
136
+ /** Monotonic id assigned by the ring; also the generation for rollback markers. */
137
+ readonly seq: number;
138
+ readonly op: UndoOp;
139
+ readonly rowId: number;
140
+ /** Row slot that was used. */
141
+ readonly row: number;
142
+ /** Previous values, keyed by column name. Empty for `insert`. */
143
+ readonly prev: Readonly<Record<string, unknown>>;
144
+ /** Full row snapshot for `delete` so re-insert can restore it. */
145
+ readonly snapshot?: Readonly<Record<string, unknown>>;
146
+ }
147
+ /**
148
+ * Fixed-capacity circular buffer of UndoRecords.
149
+ *
150
+ * When the ring wraps, the oldest entries are silently overwritten. Rollback
151
+ * to a `mark()` that has been overwritten throws `UndoError` so callers know
152
+ * the rollback is no longer possible.
153
+ */
154
+ declare class UndoRing {
155
+ readonly capacity: number;
156
+ private records;
157
+ private head;
158
+ private count;
159
+ private seqCounter;
160
+ constructor(capacity: number);
161
+ get size(): number;
162
+ /** Next seq that will be assigned. */
163
+ get nextSeq(): number;
164
+ /** Push a new record; returns its seq. */
165
+ push(op: UndoOp, rowId: number, row: number, prev: Record<string, unknown>, snapshot?: Record<string, unknown>): number;
166
+ /** Oldest valid seq currently in the ring, or -1 if empty. */
167
+ oldestSeq(): number;
168
+ /** Return a stable mark for the next seq to be written. */
169
+ mark(): number;
170
+ /**
171
+ * Drain records pushed at or after `mark`, newest-first. Used by `rollback`.
172
+ * Throws if `mark` has been overwritten by ring wrap.
173
+ */
174
+ drainSince(mark: number): UndoRecord[];
175
+ private oldestSeqOrZero;
176
+ /** Clear the ring without resetting seqCounter. */
177
+ clear(): void;
178
+ }
179
+
180
+ /**
181
+ * Query builder — `@tanstack/db` parity (Layer C.4).
182
+ *
183
+ * This module ports the non-incremental builder surface from
184
+ * `@tanstack/db@0.6.16`: a chainable `BaseQueryBuilder` that emits
185
+ * the QueryIR defined in `ir.ts`. Compiler/runtime execution lands in
186
+ * later Layer-C tasks; this file only builds validated IR.
187
+ */
188
+
189
+ type ContextSchema = Record<string, unknown>;
190
+ type Prettify<T> = {
191
+ [K in keyof T]: T[K];
192
+ } & {};
193
+ type JoinType$1 = 'left' | 'right' | 'inner' | 'outer' | 'full' | 'cross';
194
+ interface Context {
195
+ baseSchema: ContextSchema;
196
+ schema: ContextSchema;
197
+ fromSourceName?: string;
198
+ hasJoins?: boolean;
199
+ joinTypes?: Record<string, JoinType$1>;
200
+ result?: unknown;
201
+ hasResult?: boolean;
202
+ singleResult?: boolean;
203
+ }
204
+ type EmptyContext = {
205
+ baseSchema: {};
206
+ schema: {};
207
+ hasJoins: false;
208
+ hasResult: false;
209
+ };
210
+ type QuerySource = Collection | BaseQueryBuilder<any>;
211
+ type SourceRecord = Record<string, QuerySource>;
212
+ type Source = SourceRecord;
213
+ type InferCollectionType<T> = T extends Collection ? Record<string, unknown> : never;
214
+ type GetResult<TContext extends Context> = TContext extends {
215
+ hasResult: true;
216
+ result: infer TResult;
217
+ } ? TResult : TContext extends {
218
+ hasJoins: true;
219
+ schema: infer TSchema;
220
+ } ? TSchema : TContext extends {
221
+ schema: infer TSchema;
222
+ fromSourceName: infer TAlias;
223
+ } ? TAlias extends keyof TSchema ? TSchema[TAlias] : TSchema : unknown;
224
+ type InferResultType<TContext extends Context> = TContext extends {
225
+ singleResult: true;
226
+ } ? GetResult<TContext> | undefined : Array<GetResult<TContext>>;
227
+ type ExtractContext<T> = T extends {
228
+ readonly __context: infer TContext;
229
+ } ? TContext extends Context ? TContext : never : never;
230
+ type QueryResult<T> = T extends {
231
+ readonly __context: infer TContext;
232
+ } ? TContext extends Context ? GetResult<TContext> : never : never;
233
+ type SchemaFromSource<T extends SourceRecord> = Prettify<{
234
+ [K in keyof T & string]: T[K] extends BaseQueryBuilder<infer TContext> ? GetResult<TContext> : T[K] extends Collection ? InferCollectionType<T[K]> : Record<string, unknown>;
235
+ }>;
236
+ type ApplyJoinOptionalityToMergedSchema<TExistingSchema extends ContextSchema, TNewSchema extends ContextSchema, TJoinType extends JoinType$1, TFromSourceName extends string> = Prettify<{
237
+ [K in keyof TExistingSchema]: K extends TFromSourceName ? TJoinType extends 'right' | 'full' ? TExistingSchema[K] | undefined : TExistingSchema[K] : TExistingSchema[K];
238
+ } & {
239
+ [K in keyof TNewSchema]: TJoinType extends 'left' | 'full' ? TNewSchema[K] | undefined : TNewSchema[K];
240
+ }>;
241
+ type PreserveResultFlags<TContext extends Context> = (TContext extends {
242
+ result: infer TResult;
243
+ hasResult: true;
244
+ } ? {
245
+ result: TResult;
246
+ hasResult: true;
247
+ } : {}) & (TContext extends {
248
+ singleResult: true;
249
+ } ? {
250
+ singleResult: true;
251
+ } : {});
252
+ type MergeContextForJoinCallback<TContext extends Context, TNewSchema extends ContextSchema> = Prettify<{
253
+ baseSchema: TContext['baseSchema'];
254
+ schema: Prettify<TContext['schema'] & TNewSchema>;
255
+ fromSourceName: TContext['fromSourceName'] & string;
256
+ hasJoins: true;
257
+ } & PreserveResultFlags<TContext>>;
258
+ type MergeContextWithJoinType<TContext extends Context, TNewSchema extends ContextSchema, TJoinType extends JoinType$1> = Prettify<{
259
+ baseSchema: TContext['baseSchema'];
260
+ schema: ApplyJoinOptionalityToMergedSchema<TContext['schema'], TNewSchema, TJoinType, TContext['fromSourceName'] & string>;
261
+ fromSourceName: TContext['fromSourceName'] & string;
262
+ hasJoins: true;
263
+ joinTypes: (TContext['joinTypes'] extends Record<string, JoinType$1> ? TContext['joinTypes'] : {}) & {
264
+ [K in keyof TNewSchema & string]: TJoinType;
265
+ };
266
+ } & PreserveResultFlags<TContext>>;
267
+ type ResultTypeFromSelectValue<TValue> = TValue extends BasicExpression$1<infer TResult> ? TResult : TValue extends Aggregate<infer TResult> ? TResult : TValue extends ToArrayWrapper<infer TResult> ? Array<TResult> : TValue extends ConcatToArrayWrapper<any> ? string : TValue extends MaterializeWrapper<infer TResult, infer TSingle> ? TSingle extends true ? TResult | undefined : Array<TResult> : TValue extends BaseQueryBuilder<any> ? Array<QueryResult<TValue>> : TValue;
268
+ type ResultTypeFromSelect<TSelect> = TSelect extends BasicExpression$1<any> | Aggregate<any> | ToArrayWrapper<any> | ConcatToArrayWrapper<any> | MaterializeWrapper<any, any> | BaseQueryBuilder<any> ? ResultTypeFromSelectValue<TSelect> : TSelect extends Record<string, unknown> ? {
269
+ [K in keyof TSelect]: ResultTypeFromSelect<TSelect[K]>;
270
+ } : ResultTypeFromSelectValue<TSelect>;
271
+ type WithResult<TContext extends Context, TResult> = {
272
+ baseSchema: TContext['baseSchema'];
273
+ schema: TContext['schema'];
274
+ result: TResult;
275
+ hasResult: true;
276
+ } & (TContext extends {
277
+ fromSourceName: infer TAlias;
278
+ } ? {
279
+ fromSourceName: TAlias & string;
280
+ } : {}) & (TContext extends {
281
+ hasJoins: infer THasJoins;
282
+ } ? {
283
+ hasJoins: THasJoins & boolean;
284
+ } : {}) & (TContext extends {
285
+ joinTypes: infer TJoinTypes;
286
+ } ? {
287
+ joinTypes: TJoinTypes & Record<string, JoinType$1>;
288
+ } : {}) & (TContext extends {
289
+ singleResult: infer TSingle;
290
+ } ? {
291
+ singleResult: TSingle & boolean;
292
+ } : {});
293
+ type InitialQueryBuilder = Pick<BaseQueryBuilder<EmptyContext>, 'from'>;
294
+ type QueryBuilder<TContext extends Context = Context> = Omit<BaseQueryBuilder<TContext>, 'from' | '_getQuery'>;
295
+ type RefsForContext<TContext extends Context> = RefContext<TContext> & (TContext extends {
296
+ hasResult: true;
297
+ result: infer TResult;
298
+ } ? {
299
+ $selected: SingleRowRefProxy<TResult & Record<string, unknown>> & Record<string, any>;
300
+ } : {});
301
+ type WhereCallback<TContext extends Context> = (refs: RefsForContext<TContext>) => unknown;
302
+ type SelectObject<T extends Record<string, unknown> = Record<string, unknown>> = T;
303
+ type OrderByCallback<TContext extends Context> = (refs: RefsForContext<TContext>) => unknown;
304
+ type GroupByCallback<TContext extends Context> = (refs: RefsForContext<TContext>) => unknown;
305
+ type JoinOnCallback<TContext extends Context> = (refs: RefsForContext<TContext>) => unknown;
306
+ type FunctionalHavingRow<TContext extends Context> = TContext['schema'] & (TContext extends {
307
+ hasResult: true;
308
+ result: infer TResult;
309
+ } ? {
310
+ $selected: TResult;
311
+ } : {});
312
+ type RefContext<_TContext extends Context> = RootRefProxy<any> & Record<string, any>;
313
+ type HavingCallback<TContext extends Context> = (refs: RefsForContext<TContext>) => unknown;
314
+ type JoinCallback<TContext extends Context> = JoinOnCallback<TContext>;
315
+ type OrderByOptions = 'asc' | 'desc' | (Partial<CompareOptions> & {
316
+ direction?: 'asc' | 'desc';
317
+ nulls?: 'first' | 'last';
318
+ });
319
+ type QueryDraft = Omit<Partial<QueryIR>, 'select' | 'where' | 'having' | 'groupBy' | 'orderBy' | 'join' | 'fnSelect' | 'fnWhere' | 'fnHaving'> & {
320
+ select?: Select | BasicExpression$1 | Aggregate | IncludesSubquery | undefined;
321
+ where?: Array<Where> | undefined;
322
+ having?: Array<Having> | undefined;
323
+ groupBy?: GroupBy | undefined;
324
+ orderBy?: OrderBy | undefined;
325
+ join?: QueryIR['join'] | undefined;
326
+ fnSelect?: ((row: Record<string, unknown>) => unknown) | undefined;
327
+ fnWhere?: Array<(row: Record<string, unknown>) => unknown> | undefined;
328
+ fnHaving?: Array<(row: Record<string, unknown>) => unknown> | undefined;
329
+ };
330
+ declare class BaseQueryBuilder<TContext extends Context = EmptyContext> {
331
+ /** Phantom type carrier for structural result/context inference. */
332
+ readonly __context: TContext;
333
+ private readonly query;
334
+ constructor(query?: QueryDraft);
335
+ from<TSource extends SourceRecord>(source: TSource): BaseQueryBuilder<{
336
+ baseSchema: SchemaFromSource<TSource>;
337
+ schema: SchemaFromSource<TSource>;
338
+ fromSourceName: keyof TSource & string;
339
+ hasJoins: false;
340
+ }>;
341
+ join<TSource extends SourceRecord, TJoinType extends JoinType$1 = 'left'>(source: TSource, onCallback: JoinCallback<MergeContextForJoinCallback<TContext, SchemaFromSource<TSource>>>, type?: TJoinType): BaseQueryBuilder<MergeContextWithJoinType<TContext, SchemaFromSource<TSource>, TJoinType>>;
342
+ innerJoin<TSource extends SourceRecord>(source: TSource, onCallback: JoinCallback<MergeContextForJoinCallback<TContext, SchemaFromSource<TSource>>>): BaseQueryBuilder<MergeContextWithJoinType<TContext, SchemaFromSource<TSource>, 'inner'>>;
343
+ leftJoin<TSource extends SourceRecord>(source: TSource, onCallback: JoinCallback<MergeContextForJoinCallback<TContext, SchemaFromSource<TSource>>>): BaseQueryBuilder<MergeContextWithJoinType<TContext, SchemaFromSource<TSource>, 'left'>>;
344
+ rightJoin<TSource extends SourceRecord>(source: TSource, onCallback: JoinCallback<MergeContextForJoinCallback<TContext, SchemaFromSource<TSource>>>): BaseQueryBuilder<MergeContextWithJoinType<TContext, SchemaFromSource<TSource>, 'right'>>;
345
+ fullJoin<TSource extends SourceRecord>(source: TSource, onCallback: JoinCallback<MergeContextForJoinCallback<TContext, SchemaFromSource<TSource>>>): BaseQueryBuilder<MergeContextWithJoinType<TContext, SchemaFromSource<TSource>, 'full'>>;
346
+ where(callback: WhereCallback<TContext>): BaseQueryBuilder<TContext>;
347
+ select<TSelect>(callback: (refs: RefsForContext<TContext>) => TSelect): BaseQueryBuilder<WithResult<TContext, ResultTypeFromSelect<TSelect>>>;
348
+ groupBy(callback: GroupByCallback<TContext>): BaseQueryBuilder<TContext>;
349
+ having(callback: HavingCallback<TContext>): BaseQueryBuilder<TContext>;
350
+ orderBy(callback: OrderByCallback<TContext>, options?: OrderByOptions): BaseQueryBuilder<TContext>;
351
+ limit(limit: number): BaseQueryBuilder<TContext>;
352
+ offset(offset: number): BaseQueryBuilder<TContext>;
353
+ distinct(): BaseQueryBuilder<TContext>;
354
+ findOne(): BaseQueryBuilder<TContext & {
355
+ singleResult: true;
356
+ }>;
357
+ get fn(): {
358
+ select: <TFuncSelectResult>(callback: (row: TContext['schema']) => TFuncSelectResult) => BaseQueryBuilder<WithResult<TContext, TFuncSelectResult>>;
359
+ where: (callback: (row: TContext['schema']) => unknown) => BaseQueryBuilder<TContext>;
360
+ having: (callback: (row: FunctionalHavingRow<TContext>) => unknown) => BaseQueryBuilder<TContext>;
361
+ };
362
+ _getQuery(): QueryIR;
363
+ private appendJoin;
364
+ private aliases;
365
+ }
366
+ declare const Query: typeof BaseQueryBuilder;
367
+ declare function buildQuery<TQuery extends BaseQueryBuilder<any>>(fn: (q: InitialQueryBuilder) => TQuery): QueryIR;
368
+ declare function getQueryIR(builder: BaseQueryBuilder<any>): QueryIR;
369
+
370
+ /**
371
+ * QueryIR compiler — Layer C.5.
372
+ *
373
+ * Executes the TanStack-compatible QueryIR produced by builder.ts
374
+ * against ArrowBase collections. This is intentionally a coarse
375
+ * batch compiler: `runCollection()` materializes a result array, and
376
+ * `runLive()` re-runs the whole query on any upstream collection
377
+ * change. Layer F replaces that coarse invalidation with IVM.
378
+ */
379
+
380
+ type ResultRow = unknown;
381
+ type CompiledExpression = (row: Record<string, unknown>) => unknown;
382
+ interface IncludesCompilationResult {
383
+ pipeline: Array<ResultRow>;
384
+ fieldName: string;
385
+ correlationField: PropRef;
386
+ childCorrelationField: PropRef;
387
+ hasOrderBy: boolean;
388
+ childCompilationResult: CompilationResult;
389
+ parentProjection?: Array<PropRef>;
390
+ materialization: IncludesMaterialization;
391
+ scalarField?: string;
392
+ }
393
+ interface CompilationResult {
394
+ collectionId: string;
395
+ pipeline: Array<ResultRow>;
396
+ sourceWhereClauses: Map<string, BasicExpression$1<boolean>>;
397
+ aliasToCollectionId: Record<string, string>;
398
+ aliasRemapping: Record<string, string>;
399
+ includes?: Array<IncludesCompilationResult>;
400
+ }
401
+ /** Execute a QueryIR once and return dense result rows. */
402
+ declare function runCollection(ir: QueryIR): Array<ResultRow>;
403
+ /**
404
+ * Compile QueryIR into a stable Layer-C result envelope. The pipeline is
405
+ * the current batch-compiler output; metadata mirrors TanStack's compiler
406
+ * shape so optimizer/conformance code has the same public handles.
407
+ */
408
+ declare function compileQuery(rawQuery: QueryIR, ..._unused: Array<unknown>): CompilationResult;
409
+ /**
410
+ * Coarse live runner: emit initial result, then re-run after any
411
+ * upstream source mutation. Returns unsubscribe.
412
+ */
413
+ declare function runLive(ir: QueryIR, callback: (rows: Array<ResultRow>) => void): () => void;
414
+ /** Compile a scalar expression evaluator over a namespaced row. */
415
+ declare function compileExpression(expr: BasicExpression$1): CompiledExpression;
416
+ /** Compile a scalar expression over a plain single row. */
417
+ declare function compileSingleRowExpression(expr: BasicExpression$1): CompiledExpression;
418
+ /** TanStack truthiness helper: only literal `true` passes filters. */
419
+ declare function toBooleanPredicate(value: unknown): boolean;
420
+
421
+ /**
422
+ * Conservative Layer-C subset check. Exact predicates are subsets of each other;
423
+ * an undefined superset means "all rows", so any subset matches.
424
+ */
425
+ declare function isWhereSubset(subset: BasicExpression$1<boolean> | undefined, superset: BasicExpression$1<boolean> | undefined): boolean;
426
+ /** Combine predicates with OR. Kept intentionally simple until Layer D optimizer work. */
427
+ declare function unionWherePredicates(predicates: Array<BasicExpression$1<boolean>>): BasicExpression$1<boolean>;
428
+ /** Return `fromPredicate AND NOT(subtractPredicate)` when both are present. */
429
+ declare function minusWherePredicates(fromPredicate: BasicExpression$1<boolean> | undefined, subtractPredicate: BasicExpression$1<boolean> | undefined): BasicExpression$1<boolean> | null;
430
+ /** Order subset is satisfied when the requested order is a prefix of the loaded order. */
431
+ declare function isOrderBySubset(subset: OrderBy | undefined, superset: OrderBy | undefined): boolean;
432
+ /** Limited request is a subset of an equal/larger or unlimited loaded request. */
433
+ declare function isLimitSubset(subset: number | undefined, superset: number | undefined): boolean;
434
+ /** Offset+limit subset over half-open ranges [offset, offset + limit). */
435
+ declare function isOffsetLimitSubset(subset: {
436
+ offset?: number;
437
+ limit?: number;
438
+ }, superset: {
439
+ offset?: number;
440
+ limit?: number;
441
+ }): boolean;
442
+ /** Combined predicate subset check used by subset-load dedupe. */
443
+ declare function isPredicateSubset(subset: LoadSubsetOptions, superset: LoadSubsetOptions): boolean;
444
+
445
+ /**
446
+ * Deduplicated wrapper for loadSubset. Conservative Layer-C version:
447
+ * skips requests already covered by completed loads; async calls are tracked
448
+ * after resolution. Layer D/F can replace this with richer predicate algebra.
449
+ */
450
+ declare class DeduplicatedLoadSubset {
451
+ private readonly _loadSubset;
452
+ private readonly onDeduplicate;
453
+ private loaded;
454
+ private generation;
455
+ constructor(opts: {
456
+ loadSubset: (options: LoadSubsetOptions) => true | Promise<void>;
457
+ onDeduplicate?: (options: LoadSubsetOptions) => void;
458
+ });
459
+ loadSubset: (options: LoadSubsetOptions) => true | Promise<void>;
460
+ reset(): void;
461
+ }
462
+
463
+ /**
464
+ * queryOnce — Layer C.6.
465
+ *
466
+ * Thin TanStack-compatible one-shot query helper. The upstream runtime
467
+ * builds a live query collection, preloads it, reads rows, then cleans
468
+ * up. ArrowBase's Layer-C equivalent can run the QueryIR compiler
469
+ * directly because live collection wrapping lands in C.7.
470
+ */
471
+
472
+ type QueryOnceResult<TQuery extends BaseQueryBuilder<any>> = ExtractContext<TQuery> extends {
473
+ singleResult: true;
474
+ } ? QueryResult<TQuery> | undefined : Array<QueryResult<TQuery>>;
475
+ type QueryOnceQuery<TQuery extends BaseQueryBuilder<any>> = ((q: InitialQueryBuilder) => TQuery) | TQuery;
476
+ /** Configuration options for queryOnce. */
477
+ interface QueryOnceConfig<TQuery extends BaseQueryBuilder<any> = BaseQueryBuilder<any>> {
478
+ /** Query builder callback or pre-built query builder. */
479
+ query: QueryOnceQuery<TQuery>;
480
+ }
481
+ /** Execute a one-shot query builder callback and return its result rows. */
482
+ declare function queryOnce<TQuery extends BaseQueryBuilder<any>>(queryFn: (q: InitialQueryBuilder) => TQuery): Promise<QueryOnceResult<TQuery>>;
483
+ /** Execute a one-shot query from a config object. */
484
+ declare function queryOnce<TQuery extends BaseQueryBuilder<any>>(config: QueryOnceConfig<TQuery>): Promise<QueryOnceResult<TQuery>>;
485
+
486
+ interface ColumnarBackendStats {
487
+ readonly backend: 'columnar-differential';
488
+ sourceHandles: number;
489
+ sourceRowsMaterialized: number;
490
+ outputRowsMaterialized: number;
491
+ additions: number;
492
+ retractions: number;
493
+ spatialIndexUsed: boolean;
494
+ }
495
+
496
+ /**
497
+ * TanStack-compatible live query collection backed by signed,
498
+ * differential updates for the structural query subset. Queries outside
499
+ * that subset retain the batch compiler as a correctness fallback.
500
+ */
501
+
502
+ interface WindowOptions {
503
+ offset?: number;
504
+ limit?: number;
505
+ }
506
+ declare const LIVE_QUERY_INTERNAL: unique symbol;
507
+ interface LiveQueryInternalUtils {
508
+ getBuilder: () => LiveQueryController;
509
+ getBackendStats: () => ColumnarBackendStats | {
510
+ readonly backend: 'batch';
511
+ };
512
+ hasCustomGetKey: boolean;
513
+ hasJoins: boolean;
514
+ hasDistinct: boolean;
515
+ }
516
+ type LiveQueryCollectionUtils = UtilsRecord & {
517
+ getRunCount: () => number;
518
+ setWindow: (options: WindowOptions) => true | Promise<void>;
519
+ getWindow: () => {
520
+ offset: number;
521
+ limit: number;
522
+ } | undefined;
523
+ [LIVE_QUERY_INTERNAL]: LiveQueryInternalUtils;
524
+ };
525
+ type LiveQueryKey = string | number;
526
+ type LiveQueryRow = Record<string, unknown>;
527
+ interface LiveQueryCollectionConfig<TQuery extends BaseQueryBuilder<any> = BaseQueryBuilder<any>, TResult extends object = QueryResult<TQuery> extends object ? QueryResult<TQuery> : LiveQueryRow> {
528
+ id?: string;
529
+ query: ((q: InitialQueryBuilder) => TQuery) | TQuery;
530
+ getKey?: (item: TResult) => LiveQueryKey;
531
+ utils?: UtilsRecord;
532
+ schema?: unknown;
533
+ capacity?: number;
534
+ gcTime?: number;
535
+ startSync?: boolean;
536
+ singleResult?: true;
537
+ defaultStringCollation?: StringCollationConfig;
538
+ onInsert?: unknown;
539
+ onUpdate?: unknown;
540
+ onDelete?: unknown;
541
+ }
542
+ interface LiveQueryCollectionOptions<TQuery extends BaseQueryBuilder<any> = BaseQueryBuilder<any>, TResult extends object = QueryResult<TQuery> extends object ? QueryResult<TQuery> : LiveQueryRow> {
543
+ id: string;
544
+ query: ((q: InitialQueryBuilder) => TQuery) | TQuery;
545
+ queryIR: QueryIR;
546
+ getKey?: (item: TResult) => LiveQueryKey;
547
+ utils: LiveQueryCollectionUtils;
548
+ schema?: unknown;
549
+ capacity?: number;
550
+ gcTime: number;
551
+ startSync?: boolean;
552
+ singleResult?: true;
553
+ defaultStringCollation?: StringCollationConfig;
554
+ onInsert?: unknown;
555
+ onUpdate?: unknown;
556
+ onDelete?: unknown;
557
+ controller: LiveQueryController;
558
+ }
559
+ type LiveQueryChange = ChangeMessage<LiveQueryRow, LiveQueryKey>;
560
+ type LowLevelListener = (event: {
561
+ op: 'insert' | 'update' | 'delete' | 'reset';
562
+ changes: Array<LiveQueryChange>;
563
+ globalVersion: number;
564
+ }) => void;
565
+ declare class LiveQueryController {
566
+ readonly id: string;
567
+ readonly query: QueryIR;
568
+ readonly hasCustomGetKey: boolean;
569
+ readonly hasJoins: boolean;
570
+ readonly hasDistinct: boolean;
571
+ readonly compareOptions: StringCollationConfig | undefined;
572
+ private readonly keyFn;
573
+ private _runCount;
574
+ private _window;
575
+ private onWindowChange;
576
+ private backendStats;
577
+ constructor(options: {
578
+ id: string;
579
+ query: QueryIR;
580
+ getKey?: (item: LiveQueryRow) => LiveQueryKey;
581
+ compareOptions?: StringCollationConfig;
582
+ });
583
+ getRunCount(): number;
584
+ recordRun(): void;
585
+ setBackendStats(provider: () => ColumnarBackendStats | {
586
+ readonly backend: 'batch';
587
+ }): void;
588
+ getBackendStats(): ColumnarBackendStats | {
589
+ readonly backend: 'batch';
590
+ };
591
+ setWindow(options: WindowOptions): true;
592
+ getWindow(): {
593
+ offset: number;
594
+ limit: number;
595
+ } | undefined;
596
+ getEffectiveQuery(): QueryIR;
597
+ setWindowChangeListener(listener: (() => void) | undefined): void;
598
+ runRows(): Array<LiveQueryRow>;
599
+ getKey(row: LiveQueryRow, index: number): LiveQueryKey;
600
+ private effectiveQuery;
601
+ }
602
+ declare class LiveQueryCollection<TRow extends LiveQueryRow = LiveQueryRow, TKey extends LiveQueryKey = LiveQueryKey, TUtils extends UtilsRecord = {}> {
603
+ readonly id: string;
604
+ readonly utils: LiveQueryCollectionUtils & TUtils;
605
+ readonly compareOptions: StringCollationConfig;
606
+ readonly config: LiveQueryCollectionOptions;
607
+ private readonly controller;
608
+ private readonly sourceUnsubs;
609
+ private readonly listeners;
610
+ private readonly lowLevelListeners;
611
+ private rowsCache;
612
+ private stateCache;
613
+ private ivmPlan;
614
+ private _subscriberCount;
615
+ private _status;
616
+ private _globalVersion;
617
+ constructor(options: LiveQueryCollectionOptions<any, any>, customUtils?: TUtils);
618
+ get status(): 'ready' | 'cleaned-up';
619
+ get size(): number;
620
+ get rowCount(): number;
621
+ get globalVersion(): number;
622
+ get subscriberCount(): number;
623
+ get state(): Map<TKey, TRow>;
624
+ get toArray(): Array<TRow>;
625
+ get(key: TKey): TRow | undefined;
626
+ has(key: TKey): boolean;
627
+ keys(): IterableIterator<TKey>;
628
+ values(): IterableIterator<TRow>;
629
+ entries(): IterableIterator<[TKey, TRow]>;
630
+ forEach(callback: (value: TRow, key: TKey, index: number) => void): void;
631
+ map<U>(callback: (value: TRow, key: TKey, index: number) => U): Array<U>;
632
+ currentStateAsChanges(): Array<ChangeMessage<TRow, TKey>>;
633
+ subscribeChanges(callback: (changes: Array<ChangeMessage<TRow, TKey>>) => void, options?: SubscribeChangesOptions): CollectionSubscription;
634
+ subscribe(listener: LowLevelListener): () => void;
635
+ preload(): Promise<void>;
636
+ stateWhenReady(): Promise<Map<TKey, TRow>>;
637
+ toArrayWhenReady(): Promise<Array<TRow>>;
638
+ isReady(): boolean;
639
+ startSyncImmediate(): void;
640
+ cleanup(): Promise<void>;
641
+ private recompute;
642
+ private resetForWindowChange;
643
+ private seedIvmPlan;
644
+ private applyIvmChanges;
645
+ private applyWeightsToPlan;
646
+ private applyWeightedOutputChanges;
647
+ private replaceCachedRow;
648
+ private removeCachedRow;
649
+ private replaceRows;
650
+ private sortRows;
651
+ private emitChanges;
652
+ }
653
+ declare function liveQueryCollectionOptions<TQuery extends BaseQueryBuilder<any>, TResult extends object = QueryResult<TQuery> extends object ? QueryResult<TQuery> : LiveQueryRow>(config: LiveQueryCollectionConfig<TQuery, TResult>): LiveQueryCollectionOptions<TQuery, TResult>;
654
+ declare function createLiveQueryCollection<TQuery extends BaseQueryBuilder<any>, TContext = ExtractContext<TQuery>, TResult extends object = QueryResult<TQuery> extends object ? QueryResult<TQuery> : LiveQueryRow, TUtils extends UtilsRecord = {}>(query: ((q: InitialQueryBuilder) => TQuery)): LiveQueryCollection<TResult & LiveQueryRow, LiveQueryKey, {}> & {
655
+ utils: LiveQueryCollectionUtils;
656
+ };
657
+ declare function createLiveQueryCollection<TQuery extends BaseQueryBuilder<any>, TContext = ExtractContext<TQuery>, TResult extends object = QueryResult<TQuery> extends object ? QueryResult<TQuery> : LiveQueryRow, TUtils extends UtilsRecord = {}>(config: LiveQueryCollectionConfig<TQuery, TResult> & {
658
+ utils?: TUtils;
659
+ }): LiveQueryCollection<TResult & LiveQueryRow, LiveQueryKey, TUtils> & {
660
+ utils: LiveQueryCollectionUtils & TUtils;
661
+ };
662
+
663
+ /** Options for BasicIndex. */
664
+ interface BasicIndexOptions {
665
+ compareFn?: (a: unknown, b: unknown) => number;
666
+ compareOptions?: CompareOptions;
667
+ }
668
+ /**
669
+ * Basic index using Map + sorted array.
670
+ *
671
+ * Map gives O(1) equality lookup; sorted values give simple range/take support.
672
+ */
673
+ declare class BasicIndex<TKey extends string | number = string | number> extends BaseIndex<TKey> {
674
+ readonly supportedOperations: Set<"eq" | "gt" | "gte" | "lt" | "lte" | "in" | "like" | "ilike">;
675
+ private valueMap;
676
+ private sortedValues;
677
+ private indexedKeys;
678
+ private compareFn;
679
+ constructor(id: number, expression: BasicExpression$1, name?: string, options?: BasicIndexOptions);
680
+ protected initialize(_options?: BasicIndexOptions): void;
681
+ add(key: TKey, item: unknown): void;
682
+ remove(key: TKey, item: unknown): void;
683
+ update(key: TKey, oldItem: unknown, newItem: unknown): void;
684
+ build(entries: Iterable<[TKey, unknown]>): void;
685
+ clear(): void;
686
+ lookup(operation: IndexOperation, value: unknown): Set<TKey>;
687
+ get keyCount(): number;
688
+ equalityLookup(value: unknown): Set<TKey>;
689
+ rangeQuery(options?: RangeQueryOptions): Set<TKey>;
690
+ rangeQueryReversed(options?: RangeQueryOptions): Set<TKey>;
691
+ take(n: number, from?: unknown, filterFn?: (key: TKey) => boolean): Array<TKey>;
692
+ takeReversed(n: number, from?: unknown, filterFn?: (key: TKey) => boolean): Array<TKey>;
693
+ takeFromStart(n: number, filterFn?: (key: TKey) => boolean): Array<TKey>;
694
+ takeReversedFromEnd(n: number, filterFn?: (key: TKey) => boolean): Array<TKey>;
695
+ inArrayLookup(values: Array<unknown>): Set<TKey>;
696
+ get indexedKeysSet(): Set<TKey>;
697
+ get orderedEntriesArray(): Array<[unknown, Set<TKey>]>;
698
+ get orderedEntriesArrayReversed(): Array<[unknown, Set<TKey>]>;
699
+ get valueMapData(): Map<unknown, Set<TKey>>;
700
+ private takeKeysForValue;
701
+ }
702
+
703
+ /** Options for BTreeIndex. */
704
+ interface BTreeIndexOptions extends BasicIndexOptions {
705
+ }
706
+ /**
707
+ * Sorted index API-compatible with TanStack's BTreeIndex.
708
+ *
709
+ * ArrowBase keeps the implementation compact for D.1 by reusing the same
710
+ * sorted-value map as BasicIndex; D.2 plugs this into query planning, and future
711
+ * work can swap internals without changing the public contract.
712
+ */
713
+ declare class BTreeIndex<TKey extends string | number = string | number> extends BasicIndex<TKey> {
714
+ constructor(id: number, expression: BasicExpression$1, name?: string, options?: BTreeIndexOptions);
715
+ }
716
+
717
+ /** View of an existing index with traversal/comparison direction reversed. */
718
+ declare class ReverseIndex<TKey extends string | number = string | number> implements IndexInterface<TKey> {
719
+ private readonly originalIndex;
720
+ constructor(originalIndex: IndexInterface<TKey>);
721
+ lookup(operation: IndexOperation, value: unknown): Set<TKey>;
722
+ rangeQuery(options?: RangeQueryOptions): Set<TKey>;
723
+ rangeQueryReversed(options?: RangeQueryOptions): Set<TKey>;
724
+ take(n: number, from?: unknown, filterFn?: (key: TKey) => boolean): Array<TKey>;
725
+ takeFromStart(n: number, filterFn?: (key: TKey) => boolean): Array<TKey>;
726
+ takeReversed(n: number, from?: unknown, filterFn?: (key: TKey) => boolean): Array<TKey>;
727
+ takeReversedFromEnd(n: number, filterFn?: (key: TKey) => boolean): Array<TKey>;
728
+ get orderedEntriesArray(): Array<[unknown, Set<TKey>]>;
729
+ get orderedEntriesArrayReversed(): Array<[unknown, Set<TKey>]>;
730
+ supports(operation: IndexOperation): boolean;
731
+ matchesField(fieldPath: Array<string>): boolean;
732
+ matchesCompareOptions(compareOptions: CompareOptions): boolean;
733
+ matchesDirection(direction: OrderByDirection): boolean;
734
+ getStats(): IndexStats;
735
+ add(key: TKey, item: unknown): void;
736
+ remove(key: TKey, item: unknown): void;
737
+ update(key: TKey, oldItem: unknown, newItem: unknown): void;
738
+ build(entries: Iterable<[TKey, unknown]>): void;
739
+ clear(): void;
740
+ get keyCount(): number;
741
+ equalityLookup(value: unknown): Set<TKey>;
742
+ inArrayLookup(values: Array<unknown>): Set<TKey>;
743
+ get indexedKeysSet(): Set<TKey>;
744
+ get valueMapData(): Map<unknown, Set<TKey>>;
745
+ }
746
+
747
+ interface IndexInfo<T extends object = Record<string, unknown>> {
748
+ index: IndexInterface<number>;
749
+ collection?: Collection;
750
+ expression?: BasicExpression$1;
751
+ fieldPath?: Array<string>;
752
+ sample?: T;
753
+ }
754
+ interface OptimizationResult<T extends object = Record<string, unknown>> {
755
+ canOptimize: boolean;
756
+ matchingKeys: Set<number>;
757
+ indexes: Array<IndexInterface<number>>;
758
+ residualExpression?: BasicExpression$1;
759
+ }
760
+ type IndexSource<T extends object = Record<string, unknown>> = (Collection & {
761
+ indexes: ReadonlyMap<unknown, IndexInterface<number> | IndexInfo<T>>;
762
+ }) | ReadonlyMap<unknown, IndexInterface<number> | IndexInfo<T>>;
763
+ declare function findIndexForField<T extends object = Record<string, unknown>>(source: IndexSource<T>, fieldName: string | Array<string>, valueOrCompareOptions?: unknown | CompareOptions, operation?: IndexOperation, compareOptions?: CompareOptions): IndexInterface<number> | undefined;
764
+ declare function optimizeExpressionWithIndexes<T extends object = Record<string, unknown>>(expression: BasicExpression$1, source: IndexSource<T>, _rowMap?: Map<number, T>, _collection?: Collection, _lazyCollection?: Collection): OptimizationResult<T>;
765
+
766
+ /**
767
+ * Index Dev Mode — TanStack DB parity (Layer D.3).
768
+ *
769
+ * Tracks slow query patterns and emits index suggestions in non-production
770
+ * builds. Public root exports intentionally mirror @tanstack/db@0.6.16.
771
+ */
772
+ interface IndexDevModeConfig {
773
+ /** Enable dev mode index suggestions. */
774
+ enabled: boolean;
775
+ /** Suggest indexes when collection has more than this many items. */
776
+ collectionSizeThreshold: number;
777
+ /** Suggest indexes when queries take longer than this many milliseconds. */
778
+ slowQueryThresholdMs: number;
779
+ /** Custom handler for index suggestions. */
780
+ onSuggestion: ((suggestion: IndexSuggestion) => void) | null;
781
+ }
782
+ interface IndexSuggestion {
783
+ type: 'collection-size' | 'slow-query' | 'frequent-field';
784
+ collectionId: string;
785
+ fieldPath: Array<string>;
786
+ message: string;
787
+ collectionSize?: number;
788
+ queryTimeMs?: number;
789
+ queryCount?: number;
790
+ }
791
+ interface QueryPattern {
792
+ fieldPath: Array<string>;
793
+ queryCount: number;
794
+ totalTimeMs: number;
795
+ avgTimeMs: number;
796
+ }
797
+ /** Configure dev mode for index suggestions. */
798
+ declare function configureIndexDevMode(config: Partial<IndexDevModeConfig>): void;
799
+ /** Get current dev mode configuration. */
800
+ declare function getIndexDevModeConfig(): IndexDevModeConfig;
801
+ /** Check if dev mode is enabled. */
802
+ declare function isDevModeEnabled(): boolean;
803
+ /** Track a query for dev mode analysis. */
804
+ declare function trackQuery(collectionId: string, fieldPath: Array<string>, executionTimeMs: number): void;
805
+ /** Clear query pattern tracking (useful for tests). */
806
+ declare function clearQueryPatterns(): void;
807
+ /** Get query patterns (useful for debugging/testing). */
808
+ declare function getQueryPatterns(): Map<string, QueryPattern>;
809
+
810
+ /**
811
+ * Dependency-tracking row proxy for filter predicates.
812
+ *
813
+ * The query engine calls `trackRow(realRow, deps)` to wrap a concrete row
814
+ * JS object before passing it to the user's predicate. Every property read
815
+ * adds the key to `deps` so the query can record which columns it observes.
816
+ *
817
+ * Known limitations:
818
+ * - Only string-keyed reads are recorded. Symbol reads (Symbol.iterator,
819
+ * Symbol.toPrimitive, etc.) are forwarded to the underlying row and
820
+ * ignored for dep tracking.
821
+ * - If the predicate reads nested objects (lists, structs), only the
822
+ * top-level column name is recorded. That matches the granularity of
823
+ * our column-level invalidation anyway.
824
+ * - Returning the underlying scalar value directly means JS operators
825
+ * (`===`, `>`, arithmetic) behave as the user expects.
826
+ */
827
+ type DepSet = Set<string>;
828
+ declare function trackRow<T extends object>(row: T, deps: DepSet): T;
829
+
830
+ interface LiveQueryStatusFlags {
831
+ isLoading: boolean;
832
+ isReady: boolean;
833
+ isIdle: boolean;
834
+ isError: boolean;
835
+ isCleanedUp: boolean;
836
+ }
837
+ declare function isCollection(value: unknown): boolean;
838
+ declare function isSingleResultCollection(collection: {
839
+ config?: {
840
+ singleResult?: boolean;
841
+ };
842
+ }): boolean;
843
+ declare function getLiveQueryStatusFlags(status: CollectionStatus): LiveQueryStatusFlags;
844
+
845
+ declare function safeRandomUUID(): string;
846
+
847
+ declare function bboxIntersects(geometry: unknown, bbox: BBox): BasicExpression$1<boolean>;
848
+ declare function bboxWithin(geometry: unknown, bbox: BBox): BasicExpression$1<boolean>;
849
+ declare function dwithin(geometry: unknown, point: Point, meters: number): BasicExpression$1<boolean>;
850
+ declare function within(point: unknown, polygon: unknown): BasicExpression$1<boolean>;
851
+ declare function contains(polygon: unknown, point: unknown): BasicExpression$1<boolean>;
852
+
853
+ /** Field path extracted from a query expression. */
854
+ type FieldPath = Array<string>;
855
+ /** Simple field/operator/value comparison extracted from a WHERE expression. */
856
+ interface SimpleComparison {
857
+ field: FieldPath;
858
+ operator: string;
859
+ value?: unknown;
860
+ }
861
+ /** Custom parser hooks for WHERE expression conversion. */
862
+ interface ParseWhereOptions<T = unknown> {
863
+ handlers: Partial<Record<OperatorName | string, (...args: Array<any>) => T>>;
864
+ onUnknownOperator?: (operator: string, args: Array<unknown>) => T;
865
+ }
866
+ /** Parsed ORDER BY field + compare options. */
867
+ interface ParsedOrderBy {
868
+ field: FieldPath;
869
+ direction: 'asc' | 'desc';
870
+ nulls: 'first' | 'last';
871
+ stringSort?: 'lexical' | 'locale';
872
+ locale?: string;
873
+ localeOptions?: object;
874
+ }
875
+ /** Extracts the field path from a PropRef expression. */
876
+ declare function extractFieldPath(expr: BasicExpression$1): FieldPath | null;
877
+ /** Extracts the literal value from a Value expression. */
878
+ declare function extractValue(expr: BasicExpression$1): unknown;
879
+ /** Walks a scalar expression tree depth-first. */
880
+ declare function walkExpression(expr: BasicExpression$1 | undefined | null, visitor: (node: BasicExpression$1) => void): void;
881
+ /** Parses a WHERE expression through user-supplied operator handlers. */
882
+ declare function parseWhereExpression<T = unknown>(expr: BasicExpression$1<boolean> | undefined | null, options: ParseWhereOptions<T>): T | null;
883
+ /** Parses ORDER BY IR clauses into field/direction/null-order records. */
884
+ declare function parseOrderByExpression(orderBy: OrderBy | undefined | null): Array<ParsedOrderBy>;
885
+ /** Extracts simple AND-ed field comparisons from a WHERE expression. */
886
+ declare function extractSimpleComparisons(expr: BasicExpression$1<boolean> | undefined | null): Array<SimpleComparison>;
887
+ /** Parses load-subset options into filters/sorts/limit. */
888
+ declare function parseLoadSubsetOptions(options: {
889
+ where?: BasicExpression$1<boolean>;
890
+ orderBy?: OrderBy;
891
+ limit?: number;
892
+ } | undefined | null): {
893
+ filters: Array<SimpleComparison>;
894
+ sorts: Array<ParsedOrderBy>;
895
+ limit?: number;
896
+ };
897
+
898
+ /**
899
+ * Hash-join across two collections.
900
+ *
901
+ * Given a "left" Query and a "right" Collection, emit the equi-join of
902
+ * left.rows × right.rows on a pair of key columns. The right side is
903
+ * hashed; the left side (post-filter) probes into the hash. We pick the
904
+ * right side as the build side unconditionally — callers can reorder
905
+ * manually if they know which side is smaller.
906
+ *
907
+ * ### Join types
908
+ *
909
+ * - `inner` — emit only matched pairs.
910
+ * - `left` — emit every left row; unmatched get `{ [as]: null }`.
911
+ * - `right` — emit every right row; unmatched right get no left
912
+ * columns at all (they are `undefined`, not `null` —
913
+ * matching SQL's NULL-on-projection semantics when
914
+ * consumers read absent left columns).
915
+ * - `full` — union of left and right.
916
+ *
917
+ * ### Output row shape
918
+ *
919
+ * Nested, not flattened:
920
+ *
921
+ * { ...leftRow, [as]: rightRow }
922
+ *
923
+ * This avoids column-name collisions cleanly and keeps the output row
924
+ * shape independent of the two schemas (useful for TypeScript generics
925
+ * later). Selection, filtering, and ordering after the join all work
926
+ * against this nested shape via bracket/dot access on the row object.
927
+ *
928
+ * Unmatched markers:
929
+ *
930
+ * - `left`/`full`, left row with no right match → `{...leftRow, [as]: null}`.
931
+ * Use `row[as] === null` to detect "no match".
932
+ * - `right`/`full`, right row with no left match → `{[as]: rightRow}`.
933
+ * Left columns are absent; access yields `undefined`.
934
+ *
935
+ * ### Pipeline
936
+ *
937
+ * 1. Run left's vectorized filter kernel to shrink the left ordinal set.
938
+ * 2. Materialize left rows (only the columns needed for the probe +
939
+ * downstream filter/select/order).
940
+ * 3. Build a Map<keyValue, rightOrdinal[]> from the right side.
941
+ * 4. Probe: for each left row, emit one joined row per matching right
942
+ * ordinal. Right rows are lazily materialized. For left/full, emit
943
+ * an unmatched left row when there are no matches.
944
+ * 5. For right/full, iterate the right side and emit any ordinal not
945
+ * previously matched.
946
+ * 6. Apply post-join filter / sort / limit in plain JS (v1).
947
+ *
948
+ * ### Reactivity
949
+ *
950
+ * JoinExecutor subscribes to BOTH collections. Any mutation on either
951
+ * side invalidates the cached snapshot. No incremental updates in v1.
952
+ *
953
+ * ### Non-goals (v1)
954
+ *
955
+ * - Multi-column join keys. Single column per side.
956
+ * - Vectorized post-join filter. We materialize then filter in JS.
957
+ * - Incremental recompute. Any change on either side triggers a full
958
+ * rebuild of the hash + probe.
959
+ */
960
+
961
+ type JoinType = 'inner' | 'left' | 'right' | 'full';
962
+ interface JoinOn {
963
+ /** Column on the left (probe) side. */
964
+ readonly left: string;
965
+ /** Column on the right (build) side. */
966
+ readonly right: string;
967
+ }
968
+ interface JoinSpec {
969
+ readonly on: JoinOn;
970
+ /** Namespace under which the right row is attached in the output. */
971
+ readonly as: string;
972
+ /**
973
+ * Join type. Defaults to `'inner'`. `'left'` / `'right'` / `'full'`
974
+ * emit null-padded rows for unmatched sides:
975
+ * - `left` — every left row is emitted; right side is `null` if no match.
976
+ * - `right` — every right row is emitted; left columns absent if no match.
977
+ * - `full` — union of left and right.
978
+ */
979
+ readonly type?: JoinType;
980
+ }
981
+ interface JoinedQuerySnapshot<TRow extends RowValue = RowValue> {
982
+ readonly rows: readonly TRow[];
983
+ /** `Math.max(left.globalVersion, right.globalVersion)` at snapshot time. */
984
+ readonly version: number;
985
+ }
986
+ /**
987
+ * A query plan with one join. Mirrors the Query builder API shape for
988
+ * the operations that make sense post-join: `where`, `select`,
989
+ * `orderBy`, `limit`, `offset`. Nested keys are addressed with dot
990
+ * notation in selection/order (e.g., `'user.name'`).
991
+ */
992
+ declare class JoinQuery<TRow extends RowValue = RowValue> {
993
+ readonly left: Query$1;
994
+ readonly right: Collection;
995
+ readonly spec: JoinSpec;
996
+ readonly predicate: Predicate$1 | null;
997
+ readonly selection: readonly string[] | null;
998
+ readonly order: readonly OrderSpec[];
999
+ readonly limitN: number | null;
1000
+ readonly offsetN: number;
1001
+ constructor(left: Query$1, right: Collection, spec: JoinSpec, predicate?: Predicate$1 | null, selection?: readonly string[] | null, order?: readonly OrderSpec[], limitN?: number | null, offsetN?: number);
1002
+ /**
1003
+ * Post-join filter. The predicate receives a fully-formed joined
1004
+ * row (with `row[spec.as]` as the nested right side).
1005
+ */
1006
+ where(predicate: Predicate$1): JoinQuery<TRow>;
1007
+ /**
1008
+ * Project columns. Paths may be plain column names (from the left
1009
+ * side) or `'<as>.<col>'` for the right side.
1010
+ */
1011
+ select(columns: readonly string[]): JoinQuery<TRow>;
1012
+ orderBy(column: string, dir?: SortDir): JoinQuery<TRow>;
1013
+ limit(n: number): JoinQuery<TRow>;
1014
+ offset(n: number): JoinQuery<TRow>;
1015
+ private requireKnownPath;
1016
+ }
1017
+ /**
1018
+ * Build + probe executor. Re-runs on any mutation to either collection.
1019
+ * Caches the last snapshot keyed by (leftVersion, rightVersion).
1020
+ */
1021
+ declare class JoinExecutor<TRow extends RowValue = RowValue> {
1022
+ readonly plan: JoinQuery<TRow>;
1023
+ private cached;
1024
+ private cachedLeftVersion;
1025
+ private cachedRightVersion;
1026
+ constructor(plan: JoinQuery<TRow>);
1027
+ dispose(): void;
1028
+ snapshot(): JoinedQuerySnapshot<TRow>;
1029
+ subscribe(listener: (snap: JoinedQuerySnapshot<TRow>) => void): () => void;
1030
+ /**
1031
+ * v1 reactivity is coarse: any mutation on either side triggers a
1032
+ * full recompute. We still filter out no-op events (e.g., a column
1033
+ * change on the left that isn't observed by the join). That's
1034
+ * conservative enough — joins touch at minimum the two key columns
1035
+ * plus every left/right column referenced in predicate/select/order.
1036
+ */
1037
+ private shouldReact;
1038
+ /**
1039
+ * We don't know which collection an event came from inside the
1040
+ * listener's lexical scope once both are wired up — but the fix is
1041
+ * simple: observe the UNION of both sides' watched columns. Extra
1042
+ * recompute is cheap relative to a miss.
1043
+ */
1044
+ private observedColumnsForEventSide;
1045
+ private recompute;
1046
+ private leftColumnsToRead;
1047
+ private rightColumnsToRead;
1048
+ }
1049
+ /**
1050
+ * Attach a join to a Query. Returns a JoinQuery that supports the
1051
+ * post-join builder surface (where / select / orderBy / limit / offset).
1052
+ * Chaining a second `.join()` is **not** supported in v1 — only one
1053
+ * join per query plan.
1054
+ */
1055
+ declare function join<TLeft extends RowValue, TRight extends RowValue>(left: Query$1<TLeft>, right: Collection, spec: JoinSpec): JoinQuery<TLeft & Record<string, TRight>>;
1056
+ /** Build an executor for a JoinQuery. */
1057
+ declare function runJoin<TRow extends RowValue = RowValue>(plan: JoinQuery<TRow>): JoinExecutor<TRow>;
1058
+
1059
+ /**
1060
+ * A Segment wraps a single SharedArrayBuffer (or ArrayBuffer fallback) and
1061
+ * manages bump allocation inside it. Allocations are 64-byte aligned to
1062
+ * satisfy Arrow buffer alignment.
1063
+ *
1064
+ * Phase 1 uses only a bump allocator; freelist / compaction lands later.
1065
+ */
1066
+ declare class Segment {
1067
+ readonly buffer: SharedArrayBuffer | ArrayBuffer;
1068
+ readonly byteLength: number;
1069
+ private cursor;
1070
+ constructor(buffer: SharedArrayBuffer | ArrayBuffer,
1071
+ /** Initial cursor position. Useful when rehydrating from a handoff. */
1072
+ initialCursor?: number);
1073
+ /** Remaining byte capacity from the current cursor. */
1074
+ get remaining(): number;
1075
+ /** Current bump cursor (byte offset of next allocation). */
1076
+ get used(): number;
1077
+ /**
1078
+ * Allocate `byteLength` bytes aligned to `alignment` (default Arrow 64B).
1079
+ * Returns the starting byte offset inside `buffer`.
1080
+ * Throws `OutOfSpaceError` if the segment cannot fit the request.
1081
+ */
1082
+ allocate(byteLength: number, alignment?: number): number;
1083
+ /** Return the underlying buffer as a typed view slice (copies the handle only). */
1084
+ u8View(offset?: number, byteLength?: number): Uint8Array;
1085
+ i32View(offset?: number, length?: number): Int32Array;
1086
+ }
1087
+ /** Create a Segment backed by SAB if available, else a plain ArrayBuffer. */
1088
+ declare function createSegment(byteLength: number): Segment;
1089
+
1090
+ /**
1091
+ * Helpers for atomic / packed 64-bit access and seqlock-style reads.
1092
+ *
1093
+ * Phase 1 is single-writer within a process; these helpers exist so we can
1094
+ * evolve toward multi-writer and cross-worker use without refactoring the
1095
+ * collection layer.
1096
+ */
1097
+ /** Align a byte offset up to the given power-of-two boundary. */
1098
+ declare function alignUp(value: number, alignment: number): number;
1099
+ /** Arrow buffer alignment — 64 bytes per Arrow columnar format spec. */
1100
+ declare const ARROW_ALIGN = 64;
1101
+
1102
+ /**
1103
+ * Custom binary snapshot format for ArrowBase collections.
1104
+ *
1105
+ * Layout:
1106
+ * [ magic 'ARBS' | formatVersion u32 | schemaJsonLength u32 |
1107
+ * schemaJson utf-8 bytes |
1108
+ * per-column sections, in declaration order:
1109
+ * validity bytes (pad to 8B)
1110
+ * primary buffer bytes (pad to 8B)
1111
+ * heap bytes (pad to 8B, only for utf8/binary)
1112
+ * ]
1113
+ *
1114
+ * Dictionary tables (per dict_utf8 column) are stored as a string array
1115
+ * inside schemaJson because they are small compared to the value buffers.
1116
+ * Geo columns store only authoritative coordinate buffers; bbox caches are
1117
+ * derived and rebuilt on import.
1118
+ *
1119
+ * This format is intentionally not Arrow IPC: it captures ArrowBase's
1120
+ * ranged-offset layout directly so round-trip preserves O(1)-update
1121
+ * semantics without rebuilding dense offsets.
1122
+ */
1123
+ declare const SNAPSHOT_MAGIC = 1396855361;
1124
+ declare const SNAPSHOT_FORMAT_VERSION = 3;
1125
+ /** Alignment pad applied to each section boundary in the snapshot. */
1126
+ declare const SNAPSHOT_ALIGN = 8;
1127
+ declare function alignSnapshot(offset: number): number;
1128
+ /** Per-column metadata stored in the JSON header. */
1129
+ interface SnapshotColumnMeta {
1130
+ readonly name: string;
1131
+ readonly type: string;
1132
+ readonly nullable: boolean;
1133
+ readonly validityBytes: number;
1134
+ readonly primaryBytes: number;
1135
+ readonly heapBytes?: number;
1136
+ /** Ordered dictionary values for dict_utf8 columns. */
1137
+ readonly dictionary?: readonly string[];
1138
+ /**
1139
+ * For list columns: the child-element meta + the number of child
1140
+ * elements written (used to size the child buffers precisely). The
1141
+ * child's `validityBytes`/`primaryBytes`/`heapBytes` describe its
1142
+ * own storage sections; they are emitted right after the parent
1143
+ * offsets section.
1144
+ */
1145
+ readonly listChildElements?: number;
1146
+ readonly listChild?: SnapshotColumnMeta;
1147
+ /**
1148
+ * For struct columns: the per-field metas. Each field is serialized
1149
+ * as a regular column section (validity + primary + optional heap
1150
+ * + optional dictionary) directly after the struct parent's
1151
+ * validity section.
1152
+ */
1153
+ readonly fields?: readonly SnapshotColumnMeta[];
1154
+ }
1155
+ /** JSON payload embedded in the snapshot header. */
1156
+ interface SnapshotHeaderJson {
1157
+ readonly schemaName: string;
1158
+ readonly primaryKey: string;
1159
+ readonly capacity: number;
1160
+ readonly rowCursor: number;
1161
+ readonly columns: readonly SnapshotColumnMeta[];
1162
+ readonly globalVersion: number;
1163
+ /** Opaque tag the caller may set; not interpreted by the reader. */
1164
+ readonly tag?: string;
1165
+ }
1166
+
1167
+ /**
1168
+ * Serialize a collection to a self-describing binary snapshot.
1169
+ *
1170
+ * Format v2 captures list + struct columns via nested metadata in the
1171
+ * JSON header plus inline child/field buffer sections:
1172
+ *
1173
+ * [ magic 'ARBS' | formatVersion u32 | schemaJsonLength u32 |
1174
+ * schemaJson utf-8 bytes |
1175
+ * per-column section (emitted recursively in declaration order) ]
1176
+ *
1177
+ * A leaf column section is `validity | primary | heap?` (each padded to
1178
+ * 8 bytes). A list column section is `validity | offsets | childLeafSection`.
1179
+ * A struct column section is `validity | field1Section | field2Section ...`.
1180
+ */
1181
+ declare function exportSnapshot(abColl: Collection, options?: {
1182
+ tag?: string;
1183
+ }): ArrayBuffer;
1184
+ /**
1185
+ * Parse a snapshot header without touching payload bytes. Useful for
1186
+ * verifying a snapshot's schema fingerprint before committing to
1187
+ * importing it.
1188
+ */
1189
+ declare function readSnapshotHeader(buffer: ArrayBuffer): SnapshotHeaderJson;
1190
+ /**
1191
+ * Import a snapshot buffer into a fresh Collection. Row data is
1192
+ * re-inserted through the normal mutation path so every invariant
1193
+ * (row index, dictionary intern, validity bitmap, list child heap,
1194
+ * struct field buffers) is rebuilt consistently.
1195
+ */
1196
+ declare function importSnapshot(buffer: ArrayBuffer, factory: (schema: CompiledSchema, capacity: number) => Collection): Collection;
1197
+ /**
1198
+ * Parses per-row values out of a snapshot without materializing a fresh
1199
+ * Collection. Supports leaf, list, and struct columns (format v2).
1200
+ */
1201
+ declare class SnapshotRowDecoder {
1202
+ private readonly sections;
1203
+ constructor(buffer: ArrayBuffer, header: SnapshotHeaderJson);
1204
+ /** Returns a RowValue for the given row index, or null if the row
1205
+ * is soft-deleted AND the primary key column holds 0 (tombstone). */
1206
+ read(row: number): RowValue | null;
1207
+ private readValue;
1208
+ private readListValue;
1209
+ private readStructValue;
1210
+ }
1211
+
1212
+ /**
1213
+ * Records outgoing deltas from a Collection so a SyncAdapter can push
1214
+ * them to a remote. Attaches to the collection's change feed on
1215
+ * construction; call `dispose()` when done.
1216
+ *
1217
+ * `bufferLimit` caps the number of retained deltas — when exceeded the
1218
+ * oldest entries are discarded. Consumers that may fall arbitrarily
1219
+ * behind must call `drainSince(version)` fast enough, or they will see
1220
+ * their cursor predate the log's oldest entry (surfaced as an empty
1221
+ * return; a persistence-backed adapter should then resync via
1222
+ * snapshot).
1223
+ *
1224
+ * `compact` and `rollback` events cannot be represented as incremental
1225
+ * deltas. Callers receive a `{ type: 'resync', version }` sentinel via
1226
+ * `onResync(listener)`, which prompts them to snapshot-sync instead of
1227
+ * stream deltas.
1228
+ */
1229
+ interface ChangeLogOptions {
1230
+ /** Max deltas retained. Default 65536. */
1231
+ bufferLimit?: number;
1232
+ }
1233
+ type ResyncListener = (event: {
1234
+ version: number;
1235
+ }) => void;
1236
+ declare class ChangeLog {
1237
+ private readonly abColl;
1238
+ private readonly deltas;
1239
+ private readonly bufferLimit;
1240
+ private resyncListeners;
1241
+ private readonly unsubscribe;
1242
+ constructor(abColl: Collection, opts?: ChangeLogOptions);
1243
+ dispose(): void;
1244
+ /** Returns deltas with `version > sinceVersion`, in order. */
1245
+ drainSince(sinceVersion: number): {
1246
+ deltas: Delta[];
1247
+ upTo: number;
1248
+ };
1249
+ /** Current number of retained deltas. */
1250
+ get size(): number;
1251
+ /** Register a resync listener (called on compact/rollback). */
1252
+ onResync(listener: ResyncListener): () => void;
1253
+ private onChange;
1254
+ private push;
1255
+ }
1256
+
1257
+ /**
1258
+ * Apply an ordered list of deltas to a Collection, preserving order.
1259
+ *
1260
+ * Semantics:
1261
+ * - insert → Collection.insert(delta.value). Duplicate key throws;
1262
+ * caller may want to retry via update. v1 is strict.
1263
+ * - update → Collection.update(delta.key, delta.value).
1264
+ * - delete → Collection.delete(delta.key). Missing key is ignored.
1265
+ *
1266
+ * Inserts with a key that already exists (because the local side wrote
1267
+ * to the same key after the delta was emitted) are promoted to updates
1268
+ * by default (TanStack DB does the same thing in its sync write path).
1269
+ *
1270
+ * Returns the highest version applied (or -Infinity if the list was empty).
1271
+ */
1272
+ declare function applyDeltas(abColl: Collection, deltas: readonly Delta[]): number;
1273
+ /**
1274
+ * In-memory sync adapter suitable for tests and same-process mirroring.
1275
+ *
1276
+ * Wraps two (or more) sides of a sync pair via a shared in-memory log.
1277
+ * Each side gets its own `MemorySyncAdapter` instance that reads/writes
1278
+ * the same log. `pull(since)` returns deltas newer than the cursor;
1279
+ * `push(deltas)` appends to the log; `apply(deltas)` writes through to
1280
+ * the local Collection.
1281
+ *
1282
+ * This is *not* a replica-set: there is no ordering guarantee beyond
1283
+ * what callers themselves impose via `push` order. Last writer wins.
1284
+ */
1285
+ declare class MemorySyncAdapter implements SyncAdapter {
1286
+ private readonly local;
1287
+ private readonly log;
1288
+ /** Optional outbound change log; if provided, local mutations
1289
+ * auto-push into the shared log. */
1290
+ private readonly outbound?;
1291
+ constructor(local: Collection, log: SharedDeltaLog,
1292
+ /** Optional outbound change log; if provided, local mutations
1293
+ * auto-push into the shared log. */
1294
+ outbound?: ChangeLog | undefined);
1295
+ private disposeLocalListener;
1296
+ dispose(): void;
1297
+ apply(deltas: readonly Delta[]): Promise<void>;
1298
+ pull(sinceVersion: number): Promise<{
1299
+ deltas: Delta[];
1300
+ upTo: number;
1301
+ }>;
1302
+ push(deltas: readonly Delta[]): Promise<void>;
1303
+ }
1304
+ /**
1305
+ * Shared log of deltas for `MemorySyncAdapter`. Ordering is preserved
1306
+ * by append order. No compaction — the log grows unboundedly. Tests
1307
+ * only.
1308
+ */
1309
+ declare class SharedDeltaLog {
1310
+ private readonly entries;
1311
+ push(deltas: readonly Delta[]): void;
1312
+ drainSince(sinceVersion: number): {
1313
+ deltas: Delta[];
1314
+ upTo: number;
1315
+ };
1316
+ get size(): number;
1317
+ }
1318
+
1319
+ /**
1320
+ * Devtools-facing introspection snapshot of a Collection. Framework-free
1321
+ * JSON — a future UI panel can render it without importing ArrowBase
1322
+ * internals.
1323
+ */
1324
+ interface CollectionDescription {
1325
+ readonly schemaName: string;
1326
+ readonly primaryKey: string;
1327
+ readonly capacity: number;
1328
+ readonly rowCount: number;
1329
+ readonly liveRowCount: number;
1330
+ readonly globalVersion: number;
1331
+ readonly hasSoftDelete: boolean;
1332
+ readonly schemaFingerprint: string;
1333
+ readonly columns: readonly ColumnDescription[];
1334
+ }
1335
+ interface ColumnDescription {
1336
+ readonly name: string;
1337
+ readonly type: ColumnTypeName;
1338
+ readonly nullable: boolean;
1339
+ readonly version: number;
1340
+ /** Count of rows whose validity bit is unset (for nullable columns). */
1341
+ readonly nullCount: number;
1342
+ /** Only present for utf8 / binary columns. */
1343
+ readonly heap?: {
1344
+ usedBytes: number;
1345
+ capacityBytes: number;
1346
+ };
1347
+ /** Only present for dict_utf8 columns. */
1348
+ readonly dictionary?: {
1349
+ entries: number;
1350
+ sampleEntries: readonly string[];
1351
+ };
1352
+ }
1353
+ /**
1354
+ * Return a structured description of a Collection for devtools /
1355
+ * logging. Cheap to call — reads cached counters and allocates a small
1356
+ * JS object. Safe to call on a hot path.
1357
+ */
1358
+ declare function describeCollection(abColl: Collection): CollectionDescription;
1359
+
1360
+ /**
1361
+ * TanStack DB → ArrowBase push-down: translate a `BasicExpression<boolean>`
1362
+ * into an ArrowBase predicate `(row) => boolean` when possible.
1363
+ *
1364
+ * v1 recognises:
1365
+ * - eq(prop, literal) → row[col] === lit
1366
+ * - eq(literal, prop) → row[col] === lit
1367
+ * - and(a, b, ...) → every translated arg
1368
+ * - or(a, b, ...) → some translated arg
1369
+ * - not(a) → !translated arg
1370
+ *
1371
+ * Any expression containing a node type that is not one of the above
1372
+ * causes the translator to return `null`. Callers should treat `null`
1373
+ * as "not pushable" and either fall back to full scan or let TanStack
1374
+ * DB's own evaluator run against the materialized rows.
1375
+ *
1376
+ * `PropRef` paths are taken as `[alias, column]` when length === 2, or
1377
+ * `[column]` when length === 1. Anything deeper (nested struct fields)
1378
+ * is not supported in v1.
1379
+ */
1380
+
1381
+ type BasicExpression<T = unknown> = IR.BasicExpression<T>;
1382
+ type Predicate = (row: RowValue) => boolean;
1383
+ /**
1384
+ * Attempt to translate a TanStack DB expression into an ArrowBase
1385
+ * predicate. Returns `null` if the expression is not pushable.
1386
+ */
1387
+ declare function pushDown(expr: BasicExpression<boolean> | undefined, knownColumns: ReadonlySet<string>): Predicate | null;
1388
+
1389
+ type DeltaType = 'enter' | 'exit' | 'update';
1390
+ type DeltaEvent<TRow extends object = Record<string, unknown>, TKey extends string | number = string | number> = {
1391
+ type: 'enter';
1392
+ key: TKey;
1393
+ value: TRow;
1394
+ metadata?: Record<string, unknown>;
1395
+ } | {
1396
+ type: 'exit';
1397
+ key: TKey;
1398
+ value: TRow;
1399
+ metadata?: Record<string, unknown>;
1400
+ } | {
1401
+ type: 'update';
1402
+ key: TKey;
1403
+ value: TRow;
1404
+ previousValue: TRow;
1405
+ metadata?: Record<string, unknown>;
1406
+ };
1407
+ interface EffectContext {
1408
+ effectId: string;
1409
+ signal: AbortSignal;
1410
+ }
1411
+ type EffectQueryInput = ((q: InitialQueryBuilder) => QueryBuilder<any>) | QueryBuilder<any>;
1412
+ type EffectEventHandler<TRow extends object = Record<string, unknown>, TKey extends string | number = string | number> = (event: DeltaEvent<TRow, TKey>, ctx: EffectContext) => void | Promise<void>;
1413
+ type EffectBatchHandler<TRow extends object = Record<string, unknown>, TKey extends string | number = string | number> = (events: Array<DeltaEvent<TRow, TKey>>, ctx: EffectContext) => void | Promise<void>;
1414
+ interface EffectConfig<TRow extends object = Record<string, unknown>, TKey extends string | number = string | number> {
1415
+ id?: string;
1416
+ query: EffectQueryInput;
1417
+ onEnter?: EffectEventHandler<TRow, TKey>;
1418
+ onUpdate?: EffectEventHandler<TRow, TKey>;
1419
+ onExit?: EffectEventHandler<TRow, TKey>;
1420
+ onBatch?: EffectBatchHandler<TRow, TKey>;
1421
+ onError?: (error: Error, event: DeltaEvent<TRow, TKey>) => void;
1422
+ onSourceError?: (error: Error) => void;
1423
+ skipInitial?: boolean;
1424
+ }
1425
+ interface Effect {
1426
+ dispose: () => Promise<void>;
1427
+ readonly disposed: boolean;
1428
+ }
1429
+ declare function createEffect<TRow extends object = Record<string, unknown>, TKey extends string | number = string | number>(config: EffectConfig<TRow, TKey>): Effect;
1430
+
1431
+ declare const DEFAULT_COMPARE_OPTIONS: {
1432
+ readonly direction: "asc";
1433
+ readonly nulls: "first";
1434
+ readonly stringSort: "locale";
1435
+ };
1436
+ declare function isTemporal(value: unknown): boolean;
1437
+ declare function deepEquals(a: unknown, b: unknown): boolean;
1438
+
1439
+ declare class SortedMap<TKey extends string | number, TValue> {
1440
+ private comparator?;
1441
+ private map;
1442
+ private sortedKeys;
1443
+ constructor(comparator?: ((a: TValue, b: TValue) => number) | undefined);
1444
+ private indexOf;
1445
+ set(key: TKey, value: TValue): this;
1446
+ get(key: TKey): TValue | undefined;
1447
+ delete(key: TKey): boolean;
1448
+ has(key: TKey): boolean;
1449
+ clear(): void;
1450
+ get size(): number;
1451
+ [Symbol.iterator](): IterableIterator<[TKey, TValue]>;
1452
+ entries(): IterableIterator<[TKey, TValue]>;
1453
+ keys(): IterableIterator<TKey>;
1454
+ values(): IterableIterator<TValue>;
1455
+ forEach(callbackfn: (value: TValue, key: TKey, map: Map<TKey, TValue>) => void): void;
1456
+ }
1457
+
1458
+ interface ChangeTracker<T extends object> {
1459
+ originalObject: T;
1460
+ modified: boolean;
1461
+ copy_: T;
1462
+ proxyCount: number;
1463
+ assigned_: Record<string | symbol, boolean>;
1464
+ parent?: {
1465
+ tracker: ChangeTracker<Record<string | symbol, unknown>>;
1466
+ prop: string | symbol;
1467
+ } | undefined;
1468
+ target: T;
1469
+ }
1470
+ declare function createChangeProxy<T extends Record<string | symbol, any | undefined>>(target: T, parent?: {
1471
+ tracker: ChangeTracker<Record<string | symbol, unknown>>;
1472
+ prop: string | symbol;
1473
+ }): {
1474
+ proxy: T;
1475
+ getChanges: () => Record<string | symbol, any>;
1476
+ };
1477
+ declare function createArrayChangeProxy<T extends object>(targets: Array<T>): {
1478
+ proxies: Array<T>;
1479
+ getChanges: () => Array<Record<string | symbol, unknown>>;
1480
+ };
1481
+ declare function withChangeTracking<T extends object>(target: T, callback: (proxy: T) => void): Record<string | symbol, unknown>;
1482
+ declare function withArrayChangeTracking<T extends object>(targets: Array<T>, callback: (proxies: Array<T>) => void): Array<Record<string | symbol, unknown>>;
1483
+
1484
+ type VirtualOrigin = 'local' | 'remote';
1485
+ interface VirtualRowProps<TKey extends string | number = string | number> {
1486
+ readonly $synced: boolean;
1487
+ readonly $origin: VirtualOrigin;
1488
+ readonly $key: TKey;
1489
+ readonly $collectionId: string;
1490
+ }
1491
+ type WithVirtualProps<T extends object, TKey extends string | number = string | number> = T & VirtualRowProps<TKey>;
1492
+ type WithoutVirtualProps<T> = Omit<T, keyof VirtualRowProps>;
1493
+ declare const VIRTUAL_PROP_NAMES: readonly ["$synced", "$origin", "$key", "$collectionId"];
1494
+ declare function hasVirtualProps(value: unknown): value is VirtualRowProps<string | number>;
1495
+ declare function createVirtualProps<TKey extends string | number>(key: TKey, collectionId: string, isSynced: boolean, origin: VirtualOrigin): VirtualRowProps<TKey>;
1496
+ declare function enrichRowWithVirtualProps<T extends object, TKey extends string | number>(row: T, key: TKey, collectionId: string, computeSynced: () => boolean, computeOrigin: () => VirtualOrigin): WithVirtualProps<T, TKey>;
1497
+ declare function computeAggregateVirtualProps<TKey extends string | number>(rows: Array<Partial<VirtualRowProps<string | number>>>, groupKey: TKey, collectionId: string): VirtualRowProps<TKey>;
1498
+ declare function isVirtualPropName(name: string): boolean;
1499
+ declare function hasVirtualPropPath(path: Array<string>): boolean;
1500
+
1501
+ /** Error types thrown by ArrowBase and TanStack-compatible surfaces. */
1502
+ declare class ArrowBaseError extends Error {
1503
+ readonly code: string;
1504
+ constructor(message: string, code: string);
1505
+ }
1506
+ declare class TanStackDBError extends ArrowBaseError {
1507
+ constructor(message: string, code?: string);
1508
+ }
1509
+ declare class NonRetriableError extends TanStackDBError {
1510
+ constructor(message: string);
1511
+ }
1512
+ interface SchemaIssue {
1513
+ message: string;
1514
+ path: unknown;
1515
+ }
1516
+ declare class SchemaValidationError extends TanStackDBError {
1517
+ readonly type: 'insert' | 'update';
1518
+ readonly issues: Array<SchemaIssue>;
1519
+ constructor(type: 'insert' | 'update', issues: Array<SchemaIssue>, message?: string);
1520
+ }
1521
+ declare class DuplicateDbInstanceError extends TanStackDBError {
1522
+ constructor();
1523
+ }
1524
+ declare class SchemaError extends ArrowBaseError {
1525
+ constructor(message: string);
1526
+ }
1527
+ declare class AllocatorError extends ArrowBaseError {
1528
+ constructor(message: string);
1529
+ }
1530
+ declare class OutOfSpaceError extends AllocatorError {
1531
+ constructor(message?: string);
1532
+ }
1533
+ declare class NotFoundError extends ArrowBaseError {
1534
+ constructor(message: string);
1535
+ }
1536
+ declare class UndoError extends ArrowBaseError {
1537
+ constructor(message: string);
1538
+ }
1539
+ declare class ValidationError extends ArrowBaseError {
1540
+ constructor(message: string);
1541
+ }
1542
+ declare class PersistenceError extends ArrowBaseError {
1543
+ constructor(message: string);
1544
+ }
1545
+ declare class CollectionConfigurationError extends TanStackDBError {
1546
+ constructor(message: string);
1547
+ }
1548
+ declare class CollectionRequiresConfigError extends CollectionConfigurationError {
1549
+ constructor();
1550
+ }
1551
+ declare class CollectionRequiresSyncConfigError extends CollectionConfigurationError {
1552
+ constructor();
1553
+ }
1554
+ declare class InvalidSchemaError extends CollectionConfigurationError {
1555
+ constructor();
1556
+ }
1557
+ declare class SchemaMustBeSynchronousError extends CollectionConfigurationError {
1558
+ constructor();
1559
+ }
1560
+ declare class CollectionStateError extends TanStackDBError {
1561
+ constructor(message: string);
1562
+ }
1563
+ declare class CollectionInErrorStateError extends CollectionStateError {
1564
+ constructor(operation: string, collectionId: string);
1565
+ }
1566
+ declare class InvalidCollectionStatusTransitionError extends CollectionStateError {
1567
+ constructor(from: string, to: string, collectionId: string);
1568
+ }
1569
+ declare class CollectionIsInErrorStateError extends CollectionStateError {
1570
+ constructor();
1571
+ }
1572
+ declare class NegativeActiveSubscribersError extends CollectionStateError {
1573
+ constructor();
1574
+ }
1575
+ declare class CollectionOperationError extends TanStackDBError {
1576
+ constructor(message: string);
1577
+ }
1578
+ declare class UndefinedKeyError extends CollectionOperationError {
1579
+ constructor(item: unknown);
1580
+ }
1581
+ declare class InvalidKeyError extends CollectionOperationError {
1582
+ constructor(key: unknown, item: unknown);
1583
+ }
1584
+ declare class DuplicateKeyError extends CollectionOperationError {
1585
+ constructor(key: string | number);
1586
+ }
1587
+ declare class DuplicateKeySyncError extends CollectionOperationError {
1588
+ constructor(key: string | number, collectionId: string, options?: {
1589
+ hasCustomGetKey?: boolean;
1590
+ hasDistinct?: boolean;
1591
+ hasJoins?: boolean;
1592
+ });
1593
+ }
1594
+ declare class MissingUpdateArgumentError extends CollectionOperationError {
1595
+ constructor();
1596
+ }
1597
+ declare class NoKeysPassedToUpdateError extends CollectionOperationError {
1598
+ constructor();
1599
+ }
1600
+ declare class UpdateKeyNotFoundError extends CollectionOperationError {
1601
+ constructor(key: string | number);
1602
+ }
1603
+ declare class KeyUpdateNotAllowedError extends CollectionOperationError {
1604
+ constructor(originalKey: string | number, newKey: string | number);
1605
+ }
1606
+ declare class NoKeysPassedToDeleteError extends CollectionOperationError {
1607
+ constructor();
1608
+ }
1609
+ declare class DeleteKeyNotFoundError extends CollectionOperationError {
1610
+ constructor(key: string | number);
1611
+ }
1612
+ declare class MissingHandlerError extends TanStackDBError {
1613
+ constructor(message: string);
1614
+ }
1615
+ declare class MissingInsertHandlerError extends MissingHandlerError {
1616
+ constructor();
1617
+ }
1618
+ declare class MissingUpdateHandlerError extends MissingHandlerError {
1619
+ constructor();
1620
+ }
1621
+ declare class MissingDeleteHandlerError extends MissingHandlerError {
1622
+ constructor();
1623
+ }
1624
+ declare class TransactionError extends TanStackDBError {
1625
+ constructor(message: string);
1626
+ }
1627
+ declare class MissingMutationFunctionError extends TransactionError {
1628
+ constructor();
1629
+ }
1630
+ declare class OnMutateMustBeSynchronousError extends TransactionError {
1631
+ constructor();
1632
+ }
1633
+ declare class TransactionNotPendingMutateError extends TransactionError {
1634
+ constructor();
1635
+ }
1636
+ declare class TransactionAlreadyCompletedRollbackError extends TransactionError {
1637
+ constructor();
1638
+ }
1639
+ declare class TransactionNotPendingCommitError extends TransactionError {
1640
+ constructor();
1641
+ }
1642
+ declare class NoPendingSyncTransactionWriteError extends TransactionError {
1643
+ constructor();
1644
+ }
1645
+ declare class SyncTransactionAlreadyCommittedWriteError extends TransactionError {
1646
+ constructor();
1647
+ }
1648
+ declare class NoPendingSyncTransactionCommitError extends TransactionError {
1649
+ constructor();
1650
+ }
1651
+ declare class SyncTransactionAlreadyCommittedError extends TransactionError {
1652
+ constructor();
1653
+ }
1654
+ declare class QueryBuilderError extends TanStackDBError {
1655
+ constructor(message: string);
1656
+ }
1657
+ declare class OnlyOneSourceAllowedError extends QueryBuilderError {
1658
+ constructor(context: string);
1659
+ }
1660
+ declare class SubQueryMustHaveFromClauseError extends QueryBuilderError {
1661
+ constructor(context: string);
1662
+ }
1663
+ declare class InvalidSourceError extends QueryBuilderError {
1664
+ constructor(alias: string);
1665
+ }
1666
+ declare class InvalidSourceTypeError extends QueryBuilderError {
1667
+ constructor(context: string, type: string);
1668
+ }
1669
+ declare class JoinConditionMustBeEqualityError extends QueryBuilderError {
1670
+ constructor();
1671
+ }
1672
+ declare class QueryMustHaveFromClauseError extends QueryBuilderError {
1673
+ constructor();
1674
+ }
1675
+ declare class InvalidWhereExpressionError extends QueryBuilderError {
1676
+ constructor(valueType: string);
1677
+ }
1678
+ declare class QueryCompilationError extends TanStackDBError {
1679
+ constructor(message: string);
1680
+ }
1681
+ declare class UnsafeAliasPathError extends QueryCompilationError {
1682
+ constructor(segment: string);
1683
+ }
1684
+ declare class DistinctRequiresSelectError extends QueryCompilationError {
1685
+ constructor();
1686
+ }
1687
+ declare class FnSelectWithGroupByError extends QueryCompilationError {
1688
+ constructor();
1689
+ }
1690
+ declare class UnsupportedRootScalarSelectError extends QueryCompilationError {
1691
+ constructor();
1692
+ }
1693
+ declare class HavingRequiresGroupByError extends QueryCompilationError {
1694
+ constructor();
1695
+ }
1696
+ declare class LimitOffsetRequireOrderByError extends QueryCompilationError {
1697
+ constructor();
1698
+ }
1699
+ declare class CollectionInputNotFoundError extends QueryCompilationError {
1700
+ constructor(alias: string, collectionId?: string, availableKeys?: Array<string>);
1701
+ }
1702
+ declare class DuplicateAliasInSubqueryError extends QueryCompilationError {
1703
+ constructor(alias: string, parentAliases: Array<string>);
1704
+ }
1705
+ declare class UnsupportedFromTypeError extends QueryCompilationError {
1706
+ constructor(type: string);
1707
+ }
1708
+ declare class UnknownExpressionTypeError extends QueryCompilationError {
1709
+ constructor(type: string);
1710
+ }
1711
+ declare class EmptyReferencePathError extends QueryCompilationError {
1712
+ constructor();
1713
+ }
1714
+ declare class UnknownFunctionError extends QueryCompilationError {
1715
+ constructor(functionName: string);
1716
+ }
1717
+ declare class JoinCollectionNotFoundError extends QueryCompilationError {
1718
+ constructor(collectionId: string);
1719
+ }
1720
+ declare class JoinError extends TanStackDBError {
1721
+ constructor(message: string);
1722
+ }
1723
+ declare class UnsupportedJoinTypeError extends JoinError {
1724
+ constructor(joinType: string);
1725
+ }
1726
+ declare class InvalidJoinConditionSameSourceError extends JoinError {
1727
+ constructor(sourceAlias: string);
1728
+ }
1729
+ declare class InvalidJoinConditionSourceMismatchError extends JoinError {
1730
+ constructor();
1731
+ }
1732
+ declare class InvalidJoinConditionLeftSourceError extends JoinError {
1733
+ constructor(sourceAlias: string);
1734
+ }
1735
+ declare class InvalidJoinConditionRightSourceError extends JoinError {
1736
+ constructor(sourceAlias: string);
1737
+ }
1738
+ declare class InvalidJoinCondition extends JoinError {
1739
+ constructor();
1740
+ }
1741
+ declare class UnsupportedJoinSourceTypeError extends JoinError {
1742
+ constructor(type: string);
1743
+ }
1744
+ declare class GroupByError extends TanStackDBError {
1745
+ constructor(message: string);
1746
+ }
1747
+ declare class NonAggregateExpressionNotInGroupByError extends GroupByError {
1748
+ constructor(alias: string);
1749
+ }
1750
+ declare class UnsupportedAggregateFunctionError extends GroupByError {
1751
+ constructor(functionName: string);
1752
+ }
1753
+ declare class AggregateFunctionNotInSelectError extends GroupByError {
1754
+ constructor(functionName: string);
1755
+ }
1756
+ declare class UnknownHavingExpressionTypeError extends GroupByError {
1757
+ constructor(type: string);
1758
+ }
1759
+ declare class StorageError extends TanStackDBError {
1760
+ constructor(message: string);
1761
+ }
1762
+ declare class SerializationError extends StorageError {
1763
+ constructor(operation: string, originalError: unknown);
1764
+ }
1765
+ declare class LocalStorageCollectionError extends StorageError {
1766
+ constructor(message: string);
1767
+ }
1768
+ declare class StorageKeyRequiredError extends LocalStorageCollectionError {
1769
+ constructor();
1770
+ }
1771
+ declare class InvalidStorageDataFormatError extends LocalStorageCollectionError {
1772
+ constructor(storageKey: string, key: string);
1773
+ }
1774
+ declare class InvalidStorageObjectFormatError extends LocalStorageCollectionError {
1775
+ constructor(storageKey: string);
1776
+ }
1777
+ declare class SyncCleanupError extends TanStackDBError {
1778
+ constructor(collectionId: string, error: unknown);
1779
+ }
1780
+ declare class QueryOptimizerError extends TanStackDBError {
1781
+ constructor(message: string);
1782
+ }
1783
+ declare class CannotCombineEmptyExpressionListError extends QueryOptimizerError {
1784
+ constructor();
1785
+ }
1786
+ declare class WhereClauseConversionError extends QueryOptimizerError {
1787
+ constructor(collectionId: string, alias: string);
1788
+ }
1789
+ declare class SubscriptionNotFoundError extends QueryCompilationError {
1790
+ constructor(resolvedAlias: string, originalAlias: string, collectionId: string, availableAliases: Array<string>);
1791
+ }
1792
+ declare class AggregateNotSupportedError extends QueryCompilationError {
1793
+ constructor();
1794
+ }
1795
+ declare class MissingAliasInputsError extends QueryCompilationError {
1796
+ constructor(missingAliases: Array<string>);
1797
+ }
1798
+ declare class SetWindowRequiresOrderByError extends QueryCompilationError {
1799
+ constructor();
1800
+ }
1801
+
1802
+ export { ARROW_ALIGN, Aggregate, AggregateFunctionNotInSelectError, AggregateNotSupportedError, AllocatorError, type ApplyJoinOptionalityToMergedSchema, ArrowBaseError, BBox, BTreeIndex, type BTreeIndexOptions, RangeQueryOptions as BTreeRangeQueryOptions, BaseIndex, BaseQueryBuilder, BasicExpression$1 as BasicExpression, BasicIndex, type BasicIndexOptions, CannotCombineEmptyExpressionListError, ChangeLog, type ChangeLogOptions, ChangeMessage, type ChangeTracker, Collection, CollectionConfigurationError, type CollectionDescription, Collection as CollectionImpl, CollectionInErrorStateError, CollectionInputNotFoundError, CollectionIsInErrorStateError, CollectionOperationError, CollectionRequiresConfigError, CollectionRequiresSyncConfigError, CollectionStateError, CollectionStatus, CollectionSubscription, type ColumnDescription, ColumnTypeName, CompareOptions, type CompilationResult, type CompiledExpression, CompiledSchema, ConcatToArrayWrapper, type Context, type ContextSchema, CreateCollectionConfig, CreateOptimisticActionsOptions, DEFAULT_COMPARE_OPTIONS, DebounceStrategy, DebounceStrategyOptions, DeduplicatedLoadSubset, DeduplicatedLoadSubset as DeduplicatedLoadSubsetType, DeleteKeyNotFoundError, DeleteMutationFn, Delta, type DeltaEvent, type DeltaType, type DepSet, DistinctRequiresSelectError, DuplicateAliasInSubqueryError, DuplicateDbInstanceError, DuplicateKeyError, DuplicateKeySyncError, type Effect, type EffectConfig, type EffectContext, type EffectQueryInput, type EmptyContext, EmptyReferencePathError, type ExtractContext, type FieldPath, FnSelectWithGroupByError, type FunctionalHavingRow, type GetResult, GroupBy, type GroupByCallback, GroupByError, Having, HavingRequiresGroupByError, type IncludesCompilationResult, IncludesMaterialization, IncludesSubquery, IndexConstructor, type IndexDevModeConfig, type IndexInfo, IndexInterface, IndexOperation, IndexOperation as IndexOperationType, IndexStats, type IndexSuggestion, type InferCollectionType, type InferResultType, type InitialQueryBuilder, InsertMutationFn, InvalidCollectionStatusTransitionError, InvalidJoinCondition, InvalidJoinConditionLeftSourceError, InvalidJoinConditionRightSourceError, InvalidJoinConditionSameSourceError, InvalidJoinConditionSourceMismatchError, InvalidKeyError, InvalidSchemaError, InvalidSourceError, InvalidSourceTypeError, InvalidStorageDataFormatError, InvalidStorageObjectFormatError, InvalidWhereExpressionError, JoinCollectionNotFoundError, JoinConditionMustBeEqualityError, JoinError, JoinExecutor, type JoinOn, type JoinOnCallback, JoinQuery, type JoinSpec, type JoinType, type JoinedQuerySnapshot, KeyUpdateNotAllowedError, LIVE_QUERY_INTERNAL, LimitOffsetRequireOrderByError, LiveQueryCollection, type LiveQueryCollectionConfig, type LiveQueryCollectionOptions, type LiveQueryCollectionUtils, LiveQueryController, type LiveQueryInternalUtils, type LiveQueryKey, type LiveQueryRow, type LiveQueryStatusFlags, LoadSubsetOptions, LocalOnlyCollectionConfig, LocalOnlyCollectionOptionsResult, LocalStorageCollectionConfig, LocalStorageCollectionError, LocalStorageCollectionOptionsResult, MaterializeWrapper, MemorySyncAdapter, type MergeContextForJoinCallback, type MergeContextWithJoinType, MissingAliasInputsError, MissingDeleteHandlerError, MissingHandlerError, MissingInsertHandlerError, MissingMutationFunctionError, MissingUpdateArgumentError, MissingUpdateHandlerError, NegativeActiveSubscribersError, NoKeysPassedToDeleteError, NoKeysPassedToUpdateError, NoPendingSyncTransactionCommitError, NoPendingSyncTransactionWriteError, NonAggregateExpressionNotInGroupByError, NonRetriableError, NotFoundError, OnMutateMustBeSynchronousError, OnlyOneSourceAllowedError, OperatorName, type OptimizationResult, OrderBy, type OrderByCallback, OrderByDirection, type OrderByOptions, OrderSpec, OutOfSpaceError, PacedMutationsConfig, type ParseWhereOptions, type ParsedOrderBy, PersistenceError, Point, Predicate$1 as Predicate, type Prettify, PropRef, type Predicate as PushDownPredicate, Query, type QueryBuilder, QueryBuilderError, QueryCompilationError, QueryIR, QueryMustHaveFromClauseError, type QueryOnceConfig, type QueryOnceQuery, type QueryOnceResult, QueryOptimizerError, type QueryPattern, type QueryResult, type QuerySource, QueueStrategy, QueueStrategyOptions, RangeQueryOptions, type RefsForContext, type ResultRow, type ResultTypeFromSelect, type ResyncListener, ReverseIndex, RootRefProxy, RowIndex, RowValue, SNAPSHOT_ALIGN, SNAPSHOT_FORMAT_VERSION, SNAPSHOT_MAGIC, SchemaError, type SchemaFromSource, SchemaMustBeSynchronousError, SchemaValidationError, Segment, Select, type SelectObject, SerializationError, SetWindowRequiresOrderByError, SharedDeltaLog, type SimpleComparison, SingleRowRefProxy, type SnapshotColumnMeta, type SnapshotHeaderJson, SnapshotRowDecoder, SortDir, SortedMap, type Source, type SourceRecord, StorageError, StorageKeyRequiredError, StringCollationConfig, SubQueryMustHaveFromClauseError, SubscribeChangesOptions, SubscriptionNotFoundError, SyncAdapter, SyncCleanupError, SyncConfig, SyncTransactionAlreadyCommittedError, SyncTransactionAlreadyCommittedWriteError, TOMBSTONE_ROW, TanStackDBError, ThrottleStrategy, ThrottleStrategyOptions, ToArrayWrapper, TransactionAlreadyCompletedRollbackError, TransactionError, TransactionNotPendingCommitError, TransactionNotPendingMutateError, UndefinedKeyError, UndoError, type UndoOp, type UndoRecord, UndoRing, UnknownExpressionTypeError, UnknownFunctionError, UnknownHavingExpressionTypeError, UnsafeAliasPathError, UnsupportedAggregateFunctionError, UnsupportedFromTypeError, UnsupportedJoinSourceTypeError, UnsupportedJoinTypeError, UnsupportedRootScalarSelectError, UpdateKeyNotFoundError, UpdateMutationFn, UtilsRecord, VIRTUAL_PROP_NAMES, ValidationError, type VirtualOrigin, type VirtualRowProps, Where, type WhereCallback, WhereClauseConversionError, type WindowOptions, type WithResult, type WithVirtualProps, type WithoutVirtualProps, alignSnapshot, alignUp, applyDeltas, bboxIntersects, bboxWithin, buildQuery, clearQueryPatterns, compileExpression, compileQuery, compileSingleRowExpression, computeAggregateVirtualProps, configureIndexDevMode, contains, createArrayChangeProxy, createChangeProxy, createCollection, createEffect, createLiveQueryCollection, createOptimisticAction, createPacedMutations, createSegment, createVirtualProps, debounceStrategy, deepEquals, describeCollection, dwithin, enrichRowWithVirtualProps, exportSnapshot, extractFieldPath, extractSimpleComparisons, extractValue, findIndexForField, getCollectionMetadata, getIndexDevModeConfig, getLiveQueryStatusFlags, getQueryIR, getQueryPatterns, hasVirtualPropPath, hasVirtualProps, importSnapshot, isCollection, isDevModeEnabled, isLimitSubset, isOffsetLimitSubset, isOrderBySubset, isPredicateSubset, isSingleResultCollection, isTemporal, isVirtualPropName, isWhereSubset, join, liveQueryCollectionOptions, localOnlyCollectionOptions, localStorageCollectionOptions, minusWherePredicates, optimizeExpressionWithIndexes, parseLoadSubsetOptions, parseOrderByExpression, parseWhereExpression, pushDown, queryOnce, queueStrategy, readSnapshotHeader, runCollection, runJoin, runLive, safeRandomUUID, throttleStrategy, toBooleanPredicate, trackQuery, trackRow, unionWherePredicates, walkExpression, withArrayChangeTracking, withChangeTracking, within };