better-convex 0.6.3 → 0.7.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (47) hide show
  1. package/dist/aggregate/index.d.ts +388 -0
  2. package/dist/aggregate/index.js +37 -0
  3. package/dist/{auth-client → auth/client}/index.js +1 -1
  4. package/dist/auth/http/index.d.ts +63 -0
  5. package/dist/auth/http/index.js +429 -0
  6. package/dist/auth/index.d.ts +19001 -185
  7. package/dist/auth/index.js +373 -686
  8. package/dist/{auth-nextjs → auth/nextjs}/index.d.ts +3 -4
  9. package/dist/{auth-nextjs → auth/nextjs}/index.js +3 -5
  10. package/dist/{caller-factory-B1FvYSKr.js → caller-factory-Dmgv8MLS.js} +15 -12
  11. package/dist/cli.mjs +2601 -13
  12. package/dist/codegen-Cz1idI3-.mjs +969 -0
  13. package/dist/{create-schema-orm-DplxTtYj.js → create-schema-orm-69VF4CFV.js} +4 -3
  14. package/dist/crpc/index.d.ts +2 -2
  15. package/dist/crpc/index.js +3 -3
  16. package/dist/{http-types-BRLY10NX.d.ts → http-types-BCf2wCgp.d.ts} +25 -25
  17. package/dist/meta-utils-DDVYp9Xf.js +117 -0
  18. package/dist/orm/index.d.ts +4 -3012
  19. package/dist/orm/index.js +9631 -2
  20. package/dist/{index-BQkhP2ny.d.ts → procedure-caller-CcjtUFvL.d.ts} +211 -74
  21. package/dist/query-context-BDSis9rT.js +1518 -0
  22. package/dist/query-context-DGExXZIV.d.ts +42 -0
  23. package/dist/react/index.d.ts +31 -35
  24. package/dist/react/index.js +145 -58
  25. package/dist/rsc/index.d.ts +4 -7
  26. package/dist/rsc/index.js +14 -10
  27. package/dist/runtime-B9xQFY8W.js +2280 -0
  28. package/dist/server/index.d.ts +3 -4
  29. package/dist/server/index.js +384 -10
  30. package/dist/{types-o-5rYcTr.d.ts → types-CIBGEYXq.d.ts} +4 -3
  31. package/dist/types-DgwvxKbT.d.ts +4 -0
  32. package/dist/watcher.mjs +8 -8
  33. package/dist/where-clause-compiler-CRP-i1Qa.d.ts +3463 -0
  34. package/package.json +14 -10
  35. package/dist/codegen-DkpPBVPn.mjs +0 -189
  36. package/dist/context-utils-DSuX99Da.d.ts +0 -17
  37. package/dist/meta-utils-DCpLSBWB.js +0 -41
  38. package/dist/orm-CleikBIV.js +0 -8820
  39. /package/dist/{auth-client → auth/client}/index.d.ts +0 -0
  40. /package/dist/{auth-config → auth/config}/index.d.ts +0 -0
  41. /package/dist/{auth-config → auth/config}/index.js +0 -0
  42. /package/dist/{create-schema-DhWXOhnU.js → create-schema-BdZOL6ns.js} +0 -0
  43. /package/dist/{customFunctions-C1okqCzL.js → customFunctions-CZnCwoR3.js} +0 -0
  44. /package/dist/{error-BZUhlhYz.js → error-Be4OcwwD.js} +0 -0
  45. /package/dist/{query-options-BL1Q0X7q.js → query-options-B0c1b6pZ.js} +0 -0
  46. /package/dist/{transformer-CTNSPjwp.js → transformer-Dh0w2py0.js} +0 -0
  47. /package/dist/{types-jftzhhuc.d.ts → types-DwGkkq2s.d.ts} +0 -0
@@ -0,0 +1,2280 @@
1
+ import { ConvexError, convexToJson, jsonToConvex, v } from "convex/values";
2
+
3
+ //#region src/aggregate-core/compare.ts
4
+ function compareValues$1(k1, k2) {
5
+ return compareAsTuples(makeComparable(k1), makeComparable(k2));
6
+ }
7
+ function compareAsTuples(a, b) {
8
+ if (a[0] === b[0]) return compareSameTypeValues(a[1], b[1]);
9
+ if (a[0] < b[0]) return -1;
10
+ return 1;
11
+ }
12
+ function compareSameTypeValues(v1, v2) {
13
+ if (v1 === void 0 || v1 === null) return 0;
14
+ if (typeof v1 === "bigint" || typeof v1 === "number" || typeof v1 === "boolean" || typeof v1 === "string") return v1 < v2 ? -1 : v1 === v2 ? 0 : 1;
15
+ if (!Array.isArray(v1) || !Array.isArray(v2)) throw new Error(`Unexpected type ${v1}`);
16
+ for (let i = 0; i < v1.length && i < v2.length; i++) {
17
+ const cmp = compareAsTuples(v1[i], v2[i]);
18
+ if (cmp !== 0) return cmp;
19
+ }
20
+ if (v1.length < v2.length) return -1;
21
+ if (v1.length > v2.length) return 1;
22
+ return 0;
23
+ }
24
+ function makeComparable(v) {
25
+ if (v === void 0) return [0, void 0];
26
+ if (v === null) return [1, null];
27
+ if (typeof v === "bigint") return [2, v];
28
+ if (typeof v === "number") {
29
+ if (Number.isNaN(v)) return [3.5, 0];
30
+ return [3, v];
31
+ }
32
+ if (typeof v === "boolean") return [4, v];
33
+ if (typeof v === "string") return [5, v];
34
+ if (v instanceof ArrayBuffer) return [6, Array.from(new Uint8Array(v)).map(makeComparable)];
35
+ if (Array.isArray(v)) return [7, v.map(makeComparable)];
36
+ return [8, Object.keys(v).sort().map((k) => [k, v[k]]).map(makeComparable)];
37
+ }
38
+
39
+ //#endregion
40
+ //#region src/orm/builders/column-builder.ts
41
+ /**
42
+ * entityKind symbol for runtime type checking
43
+ * Following Drizzle's pattern for type guards
44
+ */
45
+ const entityKind = Symbol.for("better-convex:entityKind");
46
+ /**
47
+ * Base ColumnBuilder abstract class
48
+ *
49
+ * All column builders inherit from this class.
50
+ * Implements chaining methods and stores runtime config.
51
+ */
52
+ var ColumnBuilder = class {
53
+ static [entityKind] = "ColumnBuilder";
54
+ [entityKind] = "ColumnBuilder";
55
+ /**
56
+ * Runtime configuration - actual mutable state
57
+ */
58
+ config;
59
+ constructor(name, dataType, columnType) {
60
+ this.config = {
61
+ name,
62
+ notNull: false,
63
+ default: void 0,
64
+ hasDefault: false,
65
+ primaryKey: false,
66
+ isUnique: false,
67
+ uniqueName: void 0,
68
+ uniqueNulls: void 0,
69
+ foreignKeyConfigs: [],
70
+ dataType,
71
+ columnType
72
+ };
73
+ }
74
+ /**
75
+ * Mark column as NOT NULL
76
+ * Returns type-branded instance with notNull: true
77
+ */
78
+ notNull() {
79
+ this.config.notNull = true;
80
+ return this;
81
+ }
82
+ /**
83
+ * Override the TypeScript type for this column.
84
+ * Mirrors Drizzle's $type() (type-only, no runtime validation changes).
85
+ */
86
+ $type() {
87
+ return this;
88
+ }
89
+ /**
90
+ * Set default value for column
91
+ * Makes field optional on insert
92
+ */
93
+ default(value) {
94
+ this.config.default = value;
95
+ this.config.hasDefault = true;
96
+ return this;
97
+ }
98
+ /**
99
+ * Set default function for column (runtime evaluated on insert).
100
+ * Mirrors Drizzle's $defaultFn() / $default().
101
+ */
102
+ $defaultFn(fn) {
103
+ this.config.defaultFn = fn;
104
+ return this;
105
+ }
106
+ /**
107
+ * Alias of $defaultFn for Drizzle parity.
108
+ */
109
+ $default(fn) {
110
+ return this.$defaultFn(fn);
111
+ }
112
+ /**
113
+ * Set on-update function for column (runtime evaluated on update).
114
+ * Mirrors Drizzle's $onUpdateFn() / $onUpdate().
115
+ */
116
+ $onUpdateFn(fn) {
117
+ this.config.onUpdateFn = fn;
118
+ return this;
119
+ }
120
+ /**
121
+ * Alias of $onUpdateFn for Drizzle parity.
122
+ */
123
+ $onUpdate(fn) {
124
+ return this.$onUpdateFn(fn);
125
+ }
126
+ /**
127
+ * Mark column as primary key
128
+ * Implies NOT NULL
129
+ */
130
+ primaryKey() {
131
+ this.config.primaryKey = true;
132
+ this.config.notNull = true;
133
+ return this;
134
+ }
135
+ /**
136
+ * Mark column as UNIQUE
137
+ * Mirrors Drizzle column unique API
138
+ */
139
+ unique(name, config) {
140
+ this.config.isUnique = true;
141
+ this.config.uniqueName = name;
142
+ this.config.uniqueNulls = config?.nulls;
143
+ return this;
144
+ }
145
+ /**
146
+ * Define a foreign key reference
147
+ * Mirrors Drizzle column references() API
148
+ */
149
+ references(ref, config = {}) {
150
+ this.config.foreignKeyConfigs.push({
151
+ ref,
152
+ config
153
+ });
154
+ return this;
155
+ }
156
+ };
157
+
158
+ //#endregion
159
+ //#region src/orm/builders/convex-column-builder.ts
160
+ /**
161
+ * Convex-specific column builder base class
162
+ *
163
+ * All Convex column builders (ConvexTextBuilder, ConvexIntegerBuilder, etc.)
164
+ * inherit from this class.
165
+ */
166
+ var ConvexColumnBuilder = class extends ColumnBuilder {
167
+ static [entityKind] = "ConvexColumnBuilder";
168
+ };
169
+
170
+ //#endregion
171
+ //#region src/orm/builders/custom.ts
172
+ var ConvexCustomBuilder = class extends ConvexColumnBuilder {
173
+ static [entityKind] = "ConvexCustomBuilder";
174
+ constructor(name, validator) {
175
+ super(name, "any", "ConvexCustom");
176
+ this.config.validator = validator;
177
+ }
178
+ get convexValidator() {
179
+ const validator = this.config.validator;
180
+ if (this.config.notNull) return validator;
181
+ return v.optional(v.union(v.null(), validator));
182
+ }
183
+ build() {
184
+ return this.convexValidator;
185
+ }
186
+ };
187
+ function custom(a, b) {
188
+ if (b !== void 0) return new ConvexCustomBuilder(a, b);
189
+ return new ConvexCustomBuilder("", a);
190
+ }
191
+ /**
192
+ * Convenience wrapper for Convex "JSON" values.
193
+ *
194
+ * Note: This is Convex JSON (runtime `v.any()`), not SQL JSON/JSONB.
195
+ */
196
+ function json() {
197
+ return custom(v.any()).$type();
198
+ }
199
+
200
+ //#endregion
201
+ //#region src/orm/builders/id.ts
202
+ /**
203
+ * ID column builder class
204
+ * Compiles to v.id(tableName) or v.optional(v.id(tableName))
205
+ */
206
+ var ConvexIdBuilder = class extends ConvexColumnBuilder {
207
+ static [entityKind] = "ConvexIdBuilder";
208
+ constructor(name, tableName) {
209
+ super(name, "string", "ConvexId");
210
+ this.tableName = tableName;
211
+ this.config.referenceTable = tableName;
212
+ }
213
+ /**
214
+ * Expose Convex validator for schema integration
215
+ */
216
+ get convexValidator() {
217
+ if (this.config.notNull) return v.id(this.tableName);
218
+ return v.optional(v.union(v.null(), v.id(this.tableName)));
219
+ }
220
+ /**
221
+ * Compile to Convex validator
222
+ * .notNull() → v.id(tableName)
223
+ * nullable → v.optional(v.id(tableName))
224
+ */
225
+ build() {
226
+ return this.convexValidator;
227
+ }
228
+ };
229
+ function id(tableName) {
230
+ return new ConvexIdBuilder("", tableName);
231
+ }
232
+
233
+ //#endregion
234
+ //#region src/orm/builders/number.ts
235
+ /**
236
+ * Number column builder class
237
+ * Compiles to v.number() or v.optional(v.number())
238
+ */
239
+ var ConvexNumberBuilder = class extends ConvexColumnBuilder {
240
+ static [entityKind] = "ConvexNumberBuilder";
241
+ constructor(name) {
242
+ super(name, "number", "ConvexNumber");
243
+ }
244
+ /**
245
+ * Expose Convex validator for schema integration
246
+ */
247
+ get convexValidator() {
248
+ if (this.config.notNull) return v.number();
249
+ return v.optional(v.union(v.null(), v.number()));
250
+ }
251
+ /**
252
+ * Compile to Convex validator
253
+ * .notNull() → v.number()
254
+ * nullable → v.optional(v.number())
255
+ */
256
+ build() {
257
+ return this.convexValidator;
258
+ }
259
+ };
260
+ function integer(name) {
261
+ return new ConvexNumberBuilder(name ?? "");
262
+ }
263
+
264
+ //#endregion
265
+ //#region src/orm/builders/system-fields.ts
266
+ /**
267
+ * System Fields - Convex-provided fields available on all documents
268
+ *
269
+ * id: Document ID (string, backed by internal Convex _id)
270
+ * createdAt: Creation timestamp alias (backed by internal Convex _creationTime)
271
+ *
272
+ * These are automatically added to every Convex table.
273
+ */
274
+ var ConvexSystemIdBuilder = class extends ColumnBuilder {
275
+ static [entityKind] = "ConvexSystemIdBuilder";
276
+ [entityKind] = "ConvexSystemIdBuilder";
277
+ constructor() {
278
+ super("_id", "string", "ConvexSystemId");
279
+ this.config.notNull = true;
280
+ }
281
+ build() {
282
+ return v.string();
283
+ }
284
+ /**
285
+ * Convex validator - runtime access
286
+ * System fields use v.string() for _id
287
+ */
288
+ get convexValidator() {
289
+ return this.build();
290
+ }
291
+ };
292
+ var ConvexSystemCreationTimeBuilder = class extends ColumnBuilder {
293
+ static [entityKind] = "ConvexSystemCreationTimeBuilder";
294
+ [entityKind] = "ConvexSystemCreationTimeBuilder";
295
+ constructor() {
296
+ super("_creationTime", "number", "ConvexSystemCreationTime");
297
+ this.config.notNull = true;
298
+ }
299
+ build() {
300
+ return v.number();
301
+ }
302
+ /**
303
+ * Convex validator - runtime access
304
+ * System fields use v.number() for _creationTime
305
+ */
306
+ get convexValidator() {
307
+ return this.build();
308
+ }
309
+ };
310
+ var ConvexSystemCreatedAtBuilder = class extends ColumnBuilder {
311
+ static [entityKind] = "ConvexSystemCreatedAtBuilder";
312
+ [entityKind] = "ConvexSystemCreatedAtBuilder";
313
+ constructor() {
314
+ super("_creationTime", "number", "ConvexSystemCreatedAt");
315
+ this.config.notNull = true;
316
+ }
317
+ build() {
318
+ return v.number();
319
+ }
320
+ get convexValidator() {
321
+ return this.build();
322
+ }
323
+ };
324
+ function createSystemFields(tableName) {
325
+ const id = new ConvexSystemIdBuilder();
326
+ const creationTime = new ConvexSystemCreationTimeBuilder();
327
+ const createdAt = new ConvexSystemCreatedAtBuilder();
328
+ id.config.tableName = tableName;
329
+ creationTime.config.tableName = tableName;
330
+ createdAt.config.tableName = tableName;
331
+ return {
332
+ id,
333
+ _creationTime: creationTime,
334
+ createdAt
335
+ };
336
+ }
337
+
338
+ //#endregion
339
+ //#region src/orm/builders/text.ts
340
+ /**
341
+ * Text column builder class
342
+ * Compiles to v.string() or v.optional(v.string())
343
+ */
344
+ var ConvexTextBuilder = class extends ConvexColumnBuilder {
345
+ static [entityKind] = "ConvexTextBuilder";
346
+ constructor(name) {
347
+ super(name, "string", "ConvexText");
348
+ }
349
+ /**
350
+ * Expose Convex validator for schema integration
351
+ */
352
+ get convexValidator() {
353
+ if (this.config.notNull) return v.string();
354
+ return v.optional(v.union(v.null(), v.string()));
355
+ }
356
+ /**
357
+ * Compile to Convex validator
358
+ * .notNull() → v.string()
359
+ * nullable → v.optional(v.string())
360
+ */
361
+ build() {
362
+ return this.convexValidator;
363
+ }
364
+ };
365
+ function text(name) {
366
+ return new ConvexTextBuilder(name ?? "");
367
+ }
368
+
369
+ //#endregion
370
+ //#region src/orm/indexes.ts
371
+ var ConvexIndexBuilderOn = class {
372
+ static [entityKind] = "ConvexIndexBuilderOn";
373
+ [entityKind] = "ConvexIndexBuilderOn";
374
+ constructor(name, unique) {
375
+ this.name = name;
376
+ this.unique = unique;
377
+ }
378
+ on(...columns) {
379
+ return new ConvexIndexBuilder(this.name, columns, this.unique);
380
+ }
381
+ };
382
+ var ConvexIndexBuilder = class {
383
+ static [entityKind] = "ConvexIndexBuilder";
384
+ [entityKind] = "ConvexIndexBuilder";
385
+ config;
386
+ constructor(name, columns, unique) {
387
+ this.config = {
388
+ name,
389
+ columns,
390
+ unique,
391
+ where: void 0
392
+ };
393
+ }
394
+ /**
395
+ * Partial index conditions are not supported in Convex.
396
+ * This method is kept for Drizzle API parity.
397
+ */
398
+ where(condition) {
399
+ this.config.where = condition;
400
+ return this;
401
+ }
402
+ };
403
+ var ConvexSearchIndexBuilderOn = class {
404
+ static [entityKind] = "ConvexSearchIndexBuilderOn";
405
+ [entityKind] = "ConvexSearchIndexBuilderOn";
406
+ constructor(name) {
407
+ this.name = name;
408
+ }
409
+ on(searchField) {
410
+ return new ConvexSearchIndexBuilder(this.name, searchField);
411
+ }
412
+ };
413
+ var ConvexSearchIndexBuilder = class {
414
+ static [entityKind] = "ConvexSearchIndexBuilder";
415
+ [entityKind] = "ConvexSearchIndexBuilder";
416
+ config;
417
+ constructor(name, searchField) {
418
+ this.config = {
419
+ name,
420
+ searchField,
421
+ filterFields: [],
422
+ staged: false
423
+ };
424
+ }
425
+ filter(...fields) {
426
+ this.config.filterFields = fields;
427
+ return this;
428
+ }
429
+ staged() {
430
+ this.config.staged = true;
431
+ return this;
432
+ }
433
+ };
434
+ var ConvexVectorIndexBuilderOn = class {
435
+ static [entityKind] = "ConvexVectorIndexBuilderOn";
436
+ [entityKind] = "ConvexVectorIndexBuilderOn";
437
+ constructor(name) {
438
+ this.name = name;
439
+ }
440
+ on(vectorField) {
441
+ return new ConvexVectorIndexBuilder(this.name, vectorField);
442
+ }
443
+ };
444
+ var ConvexAggregateIndexBuilderOn = class {
445
+ static [entityKind] = "ConvexAggregateIndexBuilderOn";
446
+ [entityKind] = "ConvexAggregateIndexBuilderOn";
447
+ constructor(name) {
448
+ this.name = name;
449
+ }
450
+ on(...columns) {
451
+ return new ConvexAggregateIndexBuilder(this.name, columns);
452
+ }
453
+ all() {
454
+ return new ConvexAggregateIndexBuilder(this.name, []);
455
+ }
456
+ };
457
+ var ConvexAggregateIndexBuilder = class {
458
+ static [entityKind] = "ConvexAggregateIndexBuilder";
459
+ [entityKind] = "ConvexAggregateIndexBuilder";
460
+ config;
461
+ constructor(name, columns) {
462
+ this.config = {
463
+ name,
464
+ columns,
465
+ countFields: [],
466
+ sumFields: [],
467
+ avgFields: [],
468
+ minFields: [],
469
+ maxFields: []
470
+ };
471
+ }
472
+ count(...fields) {
473
+ this.config.countFields = [...this.config.countFields, ...fields];
474
+ return this;
475
+ }
476
+ sum(...fields) {
477
+ this.config.sumFields = [...this.config.sumFields, ...fields];
478
+ return this;
479
+ }
480
+ avg(...fields) {
481
+ this.config.avgFields = [...this.config.avgFields, ...fields];
482
+ return this;
483
+ }
484
+ min(...fields) {
485
+ this.config.minFields = [...this.config.minFields, ...fields];
486
+ return this;
487
+ }
488
+ max(...fields) {
489
+ this.config.maxFields = [...this.config.maxFields, ...fields];
490
+ return this;
491
+ }
492
+ };
493
+ var ConvexRankIndexBuilderOn = class {
494
+ static [entityKind] = "ConvexRankIndexBuilderOn";
495
+ [entityKind] = "ConvexRankIndexBuilderOn";
496
+ constructor(name) {
497
+ this.name = name;
498
+ }
499
+ partitionBy(...columns) {
500
+ return new ConvexRankIndexBuilder(this.name, columns, []);
501
+ }
502
+ all() {
503
+ return new ConvexRankIndexBuilder(this.name, [], []);
504
+ }
505
+ };
506
+ var ConvexRankIndexBuilder = class {
507
+ static [entityKind] = "ConvexRankIndexBuilder";
508
+ [entityKind] = "ConvexRankIndexBuilder";
509
+ config;
510
+ constructor(name, partitionColumns, orderColumns) {
511
+ this.config = {
512
+ name,
513
+ partitionColumns,
514
+ orderColumns,
515
+ sumField: void 0
516
+ };
517
+ }
518
+ orderBy(...columns) {
519
+ this.config.orderColumns = columns.map((entry) => {
520
+ if (entry && typeof entry === "object" && "column" in entry && "direction" in entry) {
521
+ const builder = entry.column?.builder;
522
+ if (!builder) throw new Error("rankIndex orderBy() expected a column builder.");
523
+ return {
524
+ column: builder,
525
+ direction: entry.direction
526
+ };
527
+ }
528
+ return {
529
+ column: entry,
530
+ direction: "asc"
531
+ };
532
+ });
533
+ return this;
534
+ }
535
+ sum(field) {
536
+ this.config.sumField = field;
537
+ return this;
538
+ }
539
+ };
540
+ var ConvexVectorIndexBuilder = class {
541
+ static [entityKind] = "ConvexVectorIndexBuilder";
542
+ [entityKind] = "ConvexVectorIndexBuilder";
543
+ config;
544
+ constructor(name, vectorField) {
545
+ this.config = {
546
+ name,
547
+ vectorField,
548
+ dimensions: void 0,
549
+ filterFields: [],
550
+ staged: false
551
+ };
552
+ }
553
+ dimensions(dimensions) {
554
+ if (!Number.isInteger(dimensions)) throw new Error(`Vector index '${this.config.name}' dimensions must be an integer, got ${dimensions}`);
555
+ if (dimensions <= 0) throw new Error(`Vector index '${this.config.name}' dimensions must be positive, got ${dimensions}`);
556
+ if (dimensions > 1e4) console.warn(`Vector index '${this.config.name}' has unusually large dimensions (${dimensions}). Common values: 768, 1536, 3072`);
557
+ this.config.dimensions = dimensions;
558
+ return this;
559
+ }
560
+ filter(...fields) {
561
+ this.config.filterFields = fields;
562
+ return this;
563
+ }
564
+ staged() {
565
+ this.config.staged = true;
566
+ return this;
567
+ }
568
+ };
569
+ function index(name) {
570
+ return new ConvexIndexBuilderOn(name, false);
571
+ }
572
+ function uniqueIndex(name) {
573
+ return new ConvexIndexBuilderOn(name, true);
574
+ }
575
+ function searchIndex(name) {
576
+ return new ConvexSearchIndexBuilderOn(name);
577
+ }
578
+ function vectorIndex(name) {
579
+ return new ConvexVectorIndexBuilderOn(name);
580
+ }
581
+ function aggregateIndex(name) {
582
+ return new ConvexAggregateIndexBuilderOn(name);
583
+ }
584
+ function rankIndex(name) {
585
+ return new ConvexRankIndexBuilderOn(name);
586
+ }
587
+
588
+ //#endregion
589
+ //#region src/orm/rls/policies.ts
590
+ var RlsPolicy = class {
591
+ static [entityKind] = "RlsPolicy";
592
+ [entityKind] = "RlsPolicy";
593
+ as;
594
+ for;
595
+ to;
596
+ using;
597
+ withCheck;
598
+ /** @internal */
599
+ _linkedTable;
600
+ constructor(name, config) {
601
+ this.name = name;
602
+ if (config) {
603
+ this.as = config.as;
604
+ this.for = config.for;
605
+ this.to = config.to;
606
+ this.using = config.using;
607
+ this.withCheck = config.withCheck;
608
+ }
609
+ }
610
+ link(table) {
611
+ this._linkedTable = table;
612
+ return this;
613
+ }
614
+ };
615
+ function rlsPolicy(name, config) {
616
+ return new RlsPolicy(name, config);
617
+ }
618
+ function isRlsPolicy(value) {
619
+ return !!value && typeof value === "object" && value[entityKind] === "RlsPolicy";
620
+ }
621
+
622
+ //#endregion
623
+ //#region src/orm/symbols.ts
624
+ const TableName = Symbol.for("better-convex:TableName");
625
+ const Columns = Symbol.for("better-convex:Columns");
626
+ const Brand = Symbol.for("better-convex:Brand");
627
+ const Relations = Symbol.for("better-convex:Relations");
628
+ const OrmContext = Symbol.for("better-convex:OrmContext");
629
+ const RlsPolicies = Symbol.for("better-convex:RlsPolicies");
630
+ const EnableRLS = Symbol.for("better-convex:EnableRLS");
631
+ const TableDeleteConfig = Symbol.for("better-convex:TableDeleteConfig");
632
+ const OrmSchemaOptions = Symbol.for("better-convex:OrmSchemaOptions");
633
+ const OrmSchemaDefinition = Symbol.for("better-convex:OrmSchemaDefinition");
634
+
635
+ //#endregion
636
+ //#region src/orm/table.ts
637
+ /**
638
+ * Reserved Convex system table names that cannot be used
639
+ */
640
+ const RESERVED_TABLES = new Set(["_storage", "_scheduled_functions"]);
641
+ const RESERVED_COLUMN_NAMES = new Set([
642
+ "id",
643
+ "_id",
644
+ "_creationTime"
645
+ ]);
646
+ /**
647
+ * Valid table name pattern: starts with letter/underscore, contains only alphanumeric and underscore
648
+ */
649
+ const TABLE_NAME_REGEX = /^[a-zA-Z_][a-zA-Z0-9_]*$/;
650
+ /**
651
+ * Validate table name against Convex constraints
652
+ */
653
+ function validateTableName(name) {
654
+ if (RESERVED_TABLES.has(name)) throw new Error(`Table name '${name}' is reserved. System tables cannot be redefined.`);
655
+ if (!TABLE_NAME_REGEX.test(name)) throw new Error(`Invalid table name '${name}'. Must start with letter, contain only alphanumeric and underscore.`);
656
+ }
657
+ /**
658
+ * Create a Convex object validator from column builders
659
+ *
660
+ * Extracts .convexValidator from each column and creates v.object({...})
661
+ * This is the core factory that bridges ORM columns to Convex validators.
662
+ *
663
+ * @param columns - Record of column name to column builder
664
+ * @returns Convex object validator
665
+ */
666
+ function createValidatorFromColumns(columns) {
667
+ const validatorFields = Object.fromEntries(Object.entries(columns).map(([key, builder]) => [key, builder.convexValidator]));
668
+ return v.object(validatorFields);
669
+ }
670
+ var ConvexDeletionBuilder = class {
671
+ static [entityKind] = "ConvexDeletionBuilder";
672
+ [entityKind] = "ConvexDeletionBuilder";
673
+ constructor(config) {
674
+ this.config = config;
675
+ }
676
+ };
677
+ function deletion(mode, options) {
678
+ if (options?.delayMs !== void 0) {
679
+ if (mode !== "scheduled") throw new Error("deletion() delayMs is only supported for 'scheduled'.");
680
+ if (!Number.isInteger(options.delayMs) || options.delayMs < 0) throw new Error("deletion() delayMs must be a non-negative integer when mode is 'scheduled'.");
681
+ }
682
+ return new ConvexDeletionBuilder({
683
+ mode,
684
+ delayMs: options?.delayMs
685
+ });
686
+ }
687
+ function isConvexIndexBuilder(value) {
688
+ return typeof value === "object" && value !== null && value[entityKind] === "ConvexIndexBuilder";
689
+ }
690
+ function isConvexIndexBuilderOn(value) {
691
+ return typeof value === "object" && value !== null && value[entityKind] === "ConvexIndexBuilderOn";
692
+ }
693
+ function isConvexAggregateIndexBuilder(value) {
694
+ return typeof value === "object" && value !== null && value[entityKind] === "ConvexAggregateIndexBuilder";
695
+ }
696
+ function isConvexAggregateIndexBuilderOn(value) {
697
+ return typeof value === "object" && value !== null && value[entityKind] === "ConvexAggregateIndexBuilderOn";
698
+ }
699
+ function isConvexRankIndexBuilderOn(value) {
700
+ return typeof value === "object" && value !== null && value[entityKind] === "ConvexRankIndexBuilderOn";
701
+ }
702
+ function isConvexRankIndexBuilder(value) {
703
+ return typeof value === "object" && value !== null && value[entityKind] === "ConvexRankIndexBuilder";
704
+ }
705
+ function isConvexUniqueConstraintBuilderOn(value) {
706
+ return typeof value === "object" && value !== null && value[entityKind] === "ConvexUniqueConstraintBuilderOn";
707
+ }
708
+ function isConvexForeignKeyBuilder(value) {
709
+ return typeof value === "object" && value !== null && value[entityKind] === "ConvexForeignKeyBuilder";
710
+ }
711
+ function isConvexCheckBuilder(value) {
712
+ return typeof value === "object" && value !== null && value[entityKind] === "ConvexCheckBuilder";
713
+ }
714
+ function isConvexSearchIndexBuilderOn(value) {
715
+ return typeof value === "object" && value !== null && value[entityKind] === "ConvexSearchIndexBuilderOn";
716
+ }
717
+ function isConvexUniqueConstraintBuilder(value) {
718
+ return typeof value === "object" && value !== null && value[entityKind] === "ConvexUniqueConstraintBuilder";
719
+ }
720
+ function isConvexSearchIndexBuilder(value) {
721
+ return typeof value === "object" && value !== null && value[entityKind] === "ConvexSearchIndexBuilder";
722
+ }
723
+ function isConvexVectorIndexBuilderOn(value) {
724
+ return typeof value === "object" && value !== null && value[entityKind] === "ConvexVectorIndexBuilderOn";
725
+ }
726
+ function isConvexVectorIndexBuilder(value) {
727
+ return typeof value === "object" && value !== null && value[entityKind] === "ConvexVectorIndexBuilder";
728
+ }
729
+ function isConvexDeletionBuilder(value) {
730
+ return typeof value === "object" && value !== null && value[entityKind] === "ConvexDeletionBuilder";
731
+ }
732
+ function isConvexLifecycleBuilder(value) {
733
+ return typeof value === "object" && value !== null && value[entityKind] === "ConvexLifecycleBuilder";
734
+ }
735
+ function getColumnName(column) {
736
+ const config = column.config;
737
+ if (!config?.name) throw new Error("Invalid index column: expected a convexTable column builder.");
738
+ return config.name;
739
+ }
740
+ function getColumnType(column) {
741
+ return column.config?.columnType;
742
+ }
743
+ function getColumnDimensions(column) {
744
+ return column.config?.dimensions;
745
+ }
746
+ function getColumnTableName(column) {
747
+ const config = column.config;
748
+ return config?.tableName ?? config?.referenceTable;
749
+ }
750
+ function getColumnTable(column) {
751
+ return column.config?.table;
752
+ }
753
+ function getUniqueIndexName(tableName, fields, explicitName) {
754
+ if (explicitName) return explicitName;
755
+ return `${tableName}_${fields.join("_")}_unique`;
756
+ }
757
+ function assertColumnInTable(column, expectedTable, context) {
758
+ const tableName = getColumnTableName(column);
759
+ if (tableName && tableName !== expectedTable) throw new Error(`${context} references column from '${tableName}', but belongs to '${expectedTable}'.`);
760
+ return getColumnName(column);
761
+ }
762
+ function assertNoReservedCreatedAtIndexFields(fields, context) {
763
+ if (fields.includes("createdAt")) throw new Error(`${context} cannot use 'createdAt'. 'createdAt' is reserved and maps to internal '_creationTime'.`);
764
+ }
765
+ function assertSearchFieldType(column, indexName) {
766
+ const columnType = getColumnType(column) ?? "unknown";
767
+ if (columnType !== "ConvexText") throw new Error(`Search index '${indexName}' only supports text() columns. Field '${getColumnName(column)}' is type '${columnType}'.`);
768
+ }
769
+ function assertVectorFieldType(column, indexName) {
770
+ const columnType = getColumnType(column) ?? "unknown";
771
+ if (columnType !== "ConvexVector") throw new Error(`Vector index '${indexName}' requires a vector() column. Field '${getColumnName(column)}' is type '${columnType}'.`);
772
+ }
773
+ function assertAggregateSumFieldType(column, indexName) {
774
+ const columnType = getColumnType(column) ?? "unknown";
775
+ if (!["ConvexNumber", "ConvexTimestamp"].includes(columnType)) throw new Error(`aggregateIndex '${indexName}' sum() supports integer()/timestamp() columns only. Field '${getColumnName(column)}' is type '${columnType}'.`);
776
+ }
777
+ function assertAggregateAvgFieldType(column, indexName) {
778
+ const columnType = getColumnType(column) ?? "unknown";
779
+ if (!["ConvexNumber", "ConvexTimestamp"].includes(columnType)) throw new Error(`aggregateIndex '${indexName}' avg() supports integer()/timestamp() columns only. Field '${getColumnName(column)}' is type '${columnType}'.`);
780
+ }
781
+ function assertAggregateComparableFieldType(column, indexName, method) {
782
+ const columnType = getColumnType(column) ?? "unknown";
783
+ if (![
784
+ "ConvexNumber",
785
+ "ConvexTimestamp",
786
+ "ConvexDate",
787
+ "ConvexText",
788
+ "ConvexBoolean",
789
+ "ConvexId"
790
+ ].includes(columnType)) throw new Error(`aggregateIndex '${indexName}' ${method}() does not support column type '${columnType}' on '${getColumnName(column)}'.`);
791
+ }
792
+ function assertRankOrderFieldType(column, indexName) {
793
+ const columnType = getColumnType(column) ?? "unknown";
794
+ if (![
795
+ "ConvexNumber",
796
+ "ConvexTimestamp",
797
+ "ConvexDate"
798
+ ].includes(columnType)) throw new Error(`rankIndex '${indexName}' orderBy() supports integer()/timestamp()/date() columns only. Field '${getColumnName(column)}' is type '${columnType}'.`);
799
+ }
800
+ const dedupeFieldNames = (fields) => [...new Set(fields)];
801
+ function applyExtraConfig(table, config) {
802
+ if (!config) return;
803
+ const entries = Array.isArray(config) ? config : Object.values(config);
804
+ for (const entry of entries) {
805
+ if (isConvexIndexBuilderOn(entry)) throw new Error(`Invalid index definition on '${table.tableName}'. Did you forget to call .on(...)?`);
806
+ if (isConvexUniqueConstraintBuilderOn(entry)) throw new Error(`Invalid unique constraint definition on '${table.tableName}'. Did you forget to call .on(...)?`);
807
+ if (isConvexAggregateIndexBuilderOn(entry)) throw new Error(`Invalid aggregate index definition on '${table.tableName}'. Did you forget to call .on(...) or .all()?`);
808
+ if (isConvexRankIndexBuilderOn(entry)) throw new Error(`Invalid rank index definition on '${table.tableName}'. Did you forget to call .partitionBy(...) or .all()?`);
809
+ if (isConvexSearchIndexBuilderOn(entry)) throw new Error(`Invalid search index definition on '${table.tableName}'. Did you forget to call .on(...)?`);
810
+ if (isConvexVectorIndexBuilderOn(entry)) throw new Error(`Invalid vector index definition on '${table.tableName}'. Did you forget to call .on(...)?`);
811
+ if (isRlsPolicy(entry)) {
812
+ const target = entry._linkedTable ?? table;
813
+ if (typeof target.addRlsPolicy === "function") target.addRlsPolicy(entry);
814
+ else {
815
+ const policies = target[RlsPolicies] ?? [];
816
+ policies.push(entry);
817
+ target[RlsPolicies] = policies;
818
+ target[EnableRLS] = true;
819
+ }
820
+ continue;
821
+ }
822
+ if (isConvexDeletionBuilder(entry)) {
823
+ if (table[TableDeleteConfig]) throw new Error(`Only one deletion(...) config can be defined for '${table.tableName}'.`);
824
+ table[TableDeleteConfig] = {
825
+ mode: entry.config.mode,
826
+ delayMs: entry.config.delayMs
827
+ };
828
+ continue;
829
+ }
830
+ if (isConvexLifecycleBuilder(entry)) throw new Error(`Lifecycle hooks are no longer supported inside convexTable('${table.tableName}', ..., extraConfig). Export schema triggers with defineTriggers(relations, { ... }) from schema.ts.`);
831
+ if (isConvexIndexBuilder(entry)) {
832
+ const { name, columns, unique, where } = entry.config;
833
+ if (where) throw new Error(`Convex does not support partial indexes. Remove .where(...) from index '${name}'.`);
834
+ if (unique) {}
835
+ const fields = columns.map((column) => assertColumnInTable(column, table.tableName, `Index '${name}'`));
836
+ assertNoReservedCreatedAtIndexFields(fields, `Index '${name}'`);
837
+ table.addIndex(name, fields);
838
+ if (unique) table.addUniqueIndex(name, fields, false);
839
+ continue;
840
+ }
841
+ if (isConvexAggregateIndexBuilder(entry)) {
842
+ const { name, columns, countFields, sumFields, avgFields, minFields, maxFields } = entry.config;
843
+ const fields = columns.map((column) => assertColumnInTable(column, table.tableName, `Aggregate index '${name}'`));
844
+ assertNoReservedCreatedAtIndexFields(fields, `Aggregate index '${name}'`);
845
+ const resolvedCountFields = dedupeFieldNames(countFields.map((column) => assertColumnInTable(column, table.tableName, `Aggregate index '${name}' count`)));
846
+ assertNoReservedCreatedAtIndexFields(resolvedCountFields, `Aggregate index '${name}' count`);
847
+ const resolvedSumFields = dedupeFieldNames(sumFields.map((column) => {
848
+ const field = assertColumnInTable(column, table.tableName, `Aggregate index '${name}' sum`);
849
+ assertAggregateSumFieldType(column, name);
850
+ return field;
851
+ }));
852
+ assertNoReservedCreatedAtIndexFields(resolvedSumFields, `Aggregate index '${name}' sum`);
853
+ const resolvedAvgFields = dedupeFieldNames(avgFields.map((column) => {
854
+ const field = assertColumnInTable(column, table.tableName, `Aggregate index '${name}' avg`);
855
+ assertAggregateAvgFieldType(column, name);
856
+ return field;
857
+ }));
858
+ assertNoReservedCreatedAtIndexFields(resolvedAvgFields, `Aggregate index '${name}' avg`);
859
+ const resolvedMinFields = dedupeFieldNames(minFields.map((column) => {
860
+ const field = assertColumnInTable(column, table.tableName, `Aggregate index '${name}' min`);
861
+ assertAggregateComparableFieldType(column, name, "min");
862
+ return field;
863
+ }));
864
+ assertNoReservedCreatedAtIndexFields(resolvedMinFields, `Aggregate index '${name}' min`);
865
+ const resolvedMaxFields = dedupeFieldNames(maxFields.map((column) => {
866
+ const field = assertColumnInTable(column, table.tableName, `Aggregate index '${name}' max`);
867
+ assertAggregateComparableFieldType(column, name, "max");
868
+ return field;
869
+ }));
870
+ assertNoReservedCreatedAtIndexFields(resolvedMaxFields, `Aggregate index '${name}' max`);
871
+ table.addAggregateIndex(name, {
872
+ fields,
873
+ countFields: resolvedCountFields,
874
+ sumFields: resolvedSumFields,
875
+ avgFields: resolvedAvgFields,
876
+ minFields: resolvedMinFields,
877
+ maxFields: resolvedMaxFields
878
+ });
879
+ continue;
880
+ }
881
+ if (isConvexRankIndexBuilder(entry)) {
882
+ const { name, partitionColumns, orderColumns, sumField } = entry.config;
883
+ if (!orderColumns.length) throw new Error(`rankIndex '${name}' on '${table.tableName}' must declare at least one orderBy(...) column.`);
884
+ const resolvedPartitionFields = dedupeFieldNames(partitionColumns.map((column) => assertColumnInTable(column, table.tableName, `rankIndex '${name}'`)));
885
+ assertNoReservedCreatedAtIndexFields(resolvedPartitionFields, `rankIndex '${name}' partitionBy`);
886
+ const resolvedOrderFields = orderColumns.map((entry) => {
887
+ const field = assertColumnInTable(entry.column, table.tableName, `rankIndex '${name}' orderBy`);
888
+ assertNoReservedCreatedAtIndexFields([field], `rankIndex '${name}'`);
889
+ assertRankOrderFieldType(entry.column, name);
890
+ return {
891
+ field,
892
+ direction: entry.direction
893
+ };
894
+ });
895
+ const resolvedSumField = sumField ? (() => {
896
+ const field = assertColumnInTable(sumField, table.tableName, `rankIndex '${name}' sum`);
897
+ assertNoReservedCreatedAtIndexFields([field], `rankIndex '${name}'`);
898
+ assertAggregateSumFieldType(sumField, name);
899
+ return field;
900
+ })() : void 0;
901
+ table.addRankIndex(name, {
902
+ partitionFields: resolvedPartitionFields,
903
+ orderFields: resolvedOrderFields,
904
+ sumField: resolvedSumField
905
+ });
906
+ continue;
907
+ }
908
+ if (isConvexUniqueConstraintBuilder(entry)) {
909
+ const { name, columns, nullsNotDistinct } = entry.config;
910
+ const fields = columns.map((column) => assertColumnInTable(column, table.tableName, "Unique constraint"));
911
+ assertNoReservedCreatedAtIndexFields(fields, "Unique constraint");
912
+ const indexName = getUniqueIndexName(table.tableName, fields, name);
913
+ table.addIndex(indexName, fields);
914
+ table.addUniqueIndex(indexName, fields, nullsNotDistinct);
915
+ continue;
916
+ }
917
+ if (isConvexForeignKeyBuilder(entry)) {
918
+ const { name, columns, foreignColumns, onDelete, onUpdate } = entry.config;
919
+ if (columns.length === 0 || foreignColumns.length === 0) throw new Error(`Foreign key on '${table.tableName}' requires at least one column.`);
920
+ if (columns.length !== foreignColumns.length) throw new Error(`Foreign key on '${table.tableName}' must specify matching columns and foreignColumns.`);
921
+ const localFields = columns.map((column) => assertColumnInTable(column, table.tableName, "Foreign key"));
922
+ const foreignTableName = getColumnTableName(foreignColumns[0]);
923
+ if (!foreignTableName) throw new Error(`Foreign key on '${table.tableName}' references a column without a table.`);
924
+ const foreignTable = getColumnTable(foreignColumns[0]);
925
+ const foreignFields = foreignColumns.map((column) => {
926
+ const tableName = getColumnTableName(column);
927
+ if (tableName && tableName !== foreignTableName) throw new Error(`Foreign key on '${table.tableName}' mixes foreign columns from '${foreignTableName}' and '${tableName}'.`);
928
+ return getColumnName(column);
929
+ });
930
+ table.addForeignKey({
931
+ name,
932
+ columns: localFields,
933
+ foreignTableName,
934
+ foreignTable,
935
+ foreignColumns: foreignFields,
936
+ onDelete,
937
+ onUpdate
938
+ });
939
+ continue;
940
+ }
941
+ if (isConvexCheckBuilder(entry)) {
942
+ const { name, expression } = entry.config;
943
+ table.addCheck(name, expression);
944
+ continue;
945
+ }
946
+ if (isConvexSearchIndexBuilder(entry)) {
947
+ const { name, searchField, filterFields, staged } = entry.config;
948
+ const searchFieldName = assertColumnInTable(searchField, table.tableName, `Search index '${name}'`);
949
+ assertNoReservedCreatedAtIndexFields([searchFieldName], `Search index '${name}'`);
950
+ assertSearchFieldType(searchField, name);
951
+ const filterFieldNames = filterFields.map((field) => assertColumnInTable(field, table.tableName, `Search index '${name}'`));
952
+ assertNoReservedCreatedAtIndexFields(filterFieldNames, `Search index '${name}'`);
953
+ table.addSearchIndex(name, {
954
+ searchField: searchFieldName,
955
+ filterFields: filterFieldNames,
956
+ staged
957
+ });
958
+ continue;
959
+ }
960
+ if (isConvexVectorIndexBuilder(entry)) {
961
+ const { name, vectorField, dimensions, filterFields, staged } = entry.config;
962
+ if (dimensions === void 0) throw new Error(`Vector index '${name}' is missing dimensions. Call .dimensions(n) before using.`);
963
+ const vectorFieldName = assertColumnInTable(vectorField, table.tableName, `Vector index '${name}'`);
964
+ assertNoReservedCreatedAtIndexFields([vectorFieldName], `Vector index '${name}'`);
965
+ assertVectorFieldType(vectorField, name);
966
+ const columnDimensions = getColumnDimensions(vectorField);
967
+ if (columnDimensions !== void 0 && columnDimensions !== dimensions) throw new Error(`Vector index '${name}' dimensions (${dimensions}) do not match vector column '${vectorFieldName}' dimensions (${columnDimensions}).`);
968
+ const filterFieldNames = filterFields.map((field) => assertColumnInTable(field, table.tableName, `Vector index '${name}'`));
969
+ assertNoReservedCreatedAtIndexFields(filterFieldNames, `Vector index '${name}'`);
970
+ table.addVectorIndex(name, {
971
+ vectorField: vectorFieldName,
972
+ dimensions,
973
+ filterFields: filterFieldNames,
974
+ staged
975
+ });
976
+ continue;
977
+ }
978
+ throw new Error(`Unsupported extra config value in convexTable('${table.tableName}').`);
979
+ }
980
+ }
981
+ /**
982
+ * ConvexTable implementation class
983
+ * Provides all properties required by Convex's TableDefinition
984
+ *
985
+ * Following convex-ents pattern:
986
+ * - Private fields for indexes (matches TableDefinition structure)
987
+ * - Duck typing (defineSchema only checks object shape)
988
+ * - Direct validator storage (no re-wrapping)
989
+ */
990
+ var ConvexTableImpl = class {
991
+ /**
992
+ * Required by TableDefinition
993
+ * Public validator property containing v.object({...}) with all column validators
994
+ */
995
+ validator;
996
+ /**
997
+ * TableDefinition private fields
998
+ * These satisfy structural typing requirements for defineSchema()
999
+ */
1000
+ indexes = [];
1001
+ uniqueIndexes = [];
1002
+ aggregateIndexes = [];
1003
+ rankIndexes = [];
1004
+ foreignKeys = [];
1005
+ deferredForeignKeys = [];
1006
+ deferredForeignKeysResolved = false;
1007
+ stagedDbIndexes = [];
1008
+ searchIndexes = [];
1009
+ stagedSearchIndexes = [];
1010
+ vectorIndexes = [];
1011
+ stagedVectorIndexes = [];
1012
+ checks = [];
1013
+ /**
1014
+ * Symbol-based metadata storage
1015
+ */
1016
+ [TableName];
1017
+ [Columns];
1018
+ [Brand] = "ConvexTable";
1019
+ [EnableRLS] = false;
1020
+ [RlsPolicies] = [];
1021
+ [TableDeleteConfig];
1022
+ /**
1023
+ * Public tableName for convenience
1024
+ */
1025
+ tableName;
1026
+ constructor(name, columns) {
1027
+ validateTableName(name);
1028
+ for (const columnName of Object.keys(columns)) if (RESERVED_COLUMN_NAMES.has(columnName)) throw new Error(`Column name '${columnName}' is reserved. System fields are managed by Convex ORM.`);
1029
+ this[TableName] = name;
1030
+ const namedColumns = Object.fromEntries(Object.entries(columns).map(([columnName, builder]) => {
1031
+ builder.config.name = columnName;
1032
+ builder.config.tableName = name;
1033
+ builder.config.table = this;
1034
+ return [columnName, builder];
1035
+ }));
1036
+ this[Columns] = namedColumns;
1037
+ this.tableName = name;
1038
+ this.validator = createValidatorFromColumns(namedColumns);
1039
+ for (const [columnName, builder] of Object.entries(namedColumns)) {
1040
+ const config = builder.config;
1041
+ if (config?.isUnique) {
1042
+ const indexName = getUniqueIndexName(name, [columnName], config.uniqueName);
1043
+ const nullsNotDistinct = config.uniqueNulls === "not distinct";
1044
+ this.addIndex(indexName, [columnName]);
1045
+ this.addUniqueIndex(indexName, [columnName], nullsNotDistinct);
1046
+ }
1047
+ if (config?.referenceTable && (!config.foreignKeyConfigs || config.foreignKeyConfigs.length === 0)) this.addForeignKey({
1048
+ name: void 0,
1049
+ columns: [columnName],
1050
+ foreignTableName: config.referenceTable,
1051
+ foreignColumns: ["_id"]
1052
+ });
1053
+ if (config?.foreignKeyConfigs?.length) for (const foreignConfig of config.foreignKeyConfigs) this.deferredForeignKeys.push({
1054
+ localColumnName: columnName,
1055
+ ref: foreignConfig.ref,
1056
+ config: foreignConfig.config
1057
+ });
1058
+ }
1059
+ }
1060
+ /**
1061
+ * Internal: add index to table from builder extraConfig
1062
+ *
1063
+ */
1064
+ addIndex(name, fields) {
1065
+ this.indexes.push({
1066
+ indexDescriptor: name,
1067
+ fields
1068
+ });
1069
+ }
1070
+ /**
1071
+ * Internal: add unique index metadata for runtime enforcement
1072
+ */
1073
+ addUniqueIndex(name, fields, nullsNotDistinct) {
1074
+ this.uniqueIndexes.push({
1075
+ name,
1076
+ fields,
1077
+ nullsNotDistinct
1078
+ });
1079
+ }
1080
+ addAggregateIndex(name, config) {
1081
+ if (this.aggregateIndexes.some((index) => index.name === name) || this.rankIndexes.some((index) => index.name === name)) throw new Error(`Duplicate aggregate index '${name}' on '${this.tableName}'.`);
1082
+ this.aggregateIndexes.push({
1083
+ name,
1084
+ fields: config.fields,
1085
+ countFields: config.countFields,
1086
+ sumFields: config.sumFields,
1087
+ avgFields: config.avgFields,
1088
+ minFields: config.minFields,
1089
+ maxFields: config.maxFields
1090
+ });
1091
+ }
1092
+ addRankIndex(name, config) {
1093
+ if (this.rankIndexes.some((index) => index.name === name) || this.aggregateIndexes.some((index) => index.name === name)) throw new Error(`Duplicate aggregate index '${name}' on '${this.tableName}'.`);
1094
+ this.rankIndexes.push({
1095
+ name,
1096
+ partitionFields: config.partitionFields,
1097
+ orderFields: config.orderFields,
1098
+ sumField: config.sumField
1099
+ });
1100
+ }
1101
+ getAggregateIndexes() {
1102
+ return [...this.aggregateIndexes];
1103
+ }
1104
+ getRankIndexes() {
1105
+ return [...this.rankIndexes];
1106
+ }
1107
+ /**
1108
+ * Internal: expose unique index metadata for mutation enforcement
1109
+ */
1110
+ getUniqueIndexes() {
1111
+ return this.uniqueIndexes;
1112
+ }
1113
+ /**
1114
+ * Internal: expose index metadata for runtime enforcement
1115
+ */
1116
+ getIndexes() {
1117
+ return this.indexes.map((entry) => ({
1118
+ name: entry.indexDescriptor,
1119
+ fields: entry.fields
1120
+ }));
1121
+ }
1122
+ /**
1123
+ * Internal: expose search index metadata for runtime query execution
1124
+ */
1125
+ getSearchIndexes() {
1126
+ return this.searchIndexes.map((entry) => ({
1127
+ name: entry.indexDescriptor,
1128
+ searchField: entry.searchField,
1129
+ filterFields: entry.filterFields
1130
+ }));
1131
+ }
1132
+ /**
1133
+ * Internal: expose vector index metadata for runtime query execution
1134
+ */
1135
+ getVectorIndexes() {
1136
+ return this.vectorIndexes.map((entry) => ({
1137
+ name: entry.indexDescriptor,
1138
+ vectorField: entry.vectorField,
1139
+ dimensions: entry.dimensions,
1140
+ filterFields: entry.filterFields
1141
+ }));
1142
+ }
1143
+ /**
1144
+ * Internal: attach an RLS policy to this table
1145
+ */
1146
+ addRlsPolicy(policy) {
1147
+ this[RlsPolicies].push(policy);
1148
+ this[EnableRLS] = true;
1149
+ }
1150
+ /**
1151
+ * Internal: return attached RLS policies
1152
+ */
1153
+ getRlsPolicies() {
1154
+ return this[RlsPolicies];
1155
+ }
1156
+ /**
1157
+ * Internal: check if RLS is enabled on this table
1158
+ */
1159
+ isRlsEnabled() {
1160
+ return this[EnableRLS];
1161
+ }
1162
+ /**
1163
+ * Internal: add foreign key metadata for runtime enforcement
1164
+ */
1165
+ addForeignKey(definition) {
1166
+ const matches = (existing) => {
1167
+ if (existing.foreignTableName !== definition.foreignTableName) return false;
1168
+ if (existing.columns.length !== definition.columns.length) return false;
1169
+ if (existing.foreignColumns.length !== definition.foreignColumns.length) return false;
1170
+ for (let i = 0; i < existing.columns.length; i++) if (existing.columns[i] !== definition.columns[i]) return false;
1171
+ for (let i = 0; i < existing.foreignColumns.length; i++) if (existing.foreignColumns[i] !== definition.foreignColumns[i]) return false;
1172
+ return true;
1173
+ };
1174
+ this.foreignKeys = this.foreignKeys.filter((existing) => !matches(existing));
1175
+ this.foreignKeys.push(definition);
1176
+ }
1177
+ resolveDeferredForeignKeys() {
1178
+ if (this.deferredForeignKeysResolved) return;
1179
+ this.deferredForeignKeysResolved = true;
1180
+ for (const deferred of this.deferredForeignKeys) {
1181
+ let foreignColumn;
1182
+ try {
1183
+ foreignColumn = deferred.ref();
1184
+ } catch (error) {
1185
+ const reason = error instanceof Error ? ` ${error.message}` : "";
1186
+ throw new Error(`Failed to resolve foreign key reference for '${this.tableName}.${deferred.localColumnName}'. Use references(() => targetTable.column) after both tables are declared.${reason}`);
1187
+ }
1188
+ const foreignTableName = getColumnTableName(foreignColumn);
1189
+ if (!foreignTableName) throw new Error(`Foreign key on '${this.tableName}.${deferred.localColumnName}' references a column without a table. Use references(() => targetTable.column).`);
1190
+ const foreignTable = getColumnTable(foreignColumn);
1191
+ if (!foreignTable) throw new Error(`Foreign key on '${this.tableName}.${deferred.localColumnName}' references a column without table metadata. Replace references(() => id('tableName')) with references(() => table.id).`);
1192
+ const foreignColumnName = getColumnName(foreignColumn);
1193
+ this.addForeignKey({
1194
+ name: deferred.config.name,
1195
+ columns: [deferred.localColumnName],
1196
+ foreignTableName,
1197
+ foreignTable,
1198
+ foreignColumns: [foreignColumnName],
1199
+ onDelete: deferred.config.onDelete,
1200
+ onUpdate: deferred.config.onUpdate
1201
+ });
1202
+ }
1203
+ this.deferredForeignKeys = [];
1204
+ }
1205
+ /**
1206
+ * Internal: expose foreign key metadata for mutation enforcement
1207
+ */
1208
+ getForeignKeys() {
1209
+ this.resolveDeferredForeignKeys();
1210
+ return this.foreignKeys;
1211
+ }
1212
+ addCheck(name, expression) {
1213
+ this.checks.push({
1214
+ name,
1215
+ expression
1216
+ });
1217
+ }
1218
+ getChecks() {
1219
+ return this.checks;
1220
+ }
1221
+ /**
1222
+ * Internal: add search index to table from builder extraConfig
1223
+ */
1224
+ addSearchIndex(name, config) {
1225
+ const entry = {
1226
+ indexDescriptor: name,
1227
+ searchField: config.searchField,
1228
+ filterFields: config.filterFields ?? []
1229
+ };
1230
+ if (config.staged) this.stagedSearchIndexes.push(entry);
1231
+ else this.searchIndexes.push(entry);
1232
+ }
1233
+ /**
1234
+ * Internal: add vector index to table from builder extraConfig
1235
+ */
1236
+ addVectorIndex(name, config) {
1237
+ const entry = {
1238
+ indexDescriptor: name,
1239
+ vectorField: config.vectorField,
1240
+ dimensions: config.dimensions,
1241
+ filterFields: config.filterFields ?? []
1242
+ };
1243
+ if (config.staged) this.stagedVectorIndexes.push(entry);
1244
+ else this.vectorIndexes.push(entry);
1245
+ }
1246
+ /**
1247
+ * Export the contents of this definition for Convex schema tooling.
1248
+ * Mirrors convex/server TableDefinition.export().
1249
+ */
1250
+ export() {
1251
+ const documentType = this.validator.json;
1252
+ if (typeof documentType !== "object") throw new Error("Invalid validator: please make sure that the parameter of `defineTable` is valid (see https://docs.convex.dev/database/schemas)");
1253
+ return {
1254
+ indexes: this.indexes,
1255
+ stagedDbIndexes: this.stagedDbIndexes,
1256
+ searchIndexes: this.searchIndexes,
1257
+ stagedSearchIndexes: this.stagedSearchIndexes,
1258
+ vectorIndexes: this.vectorIndexes,
1259
+ stagedVectorIndexes: this.stagedVectorIndexes,
1260
+ documentType
1261
+ };
1262
+ }
1263
+ };
1264
+ const convexTableInternal = (name, columns, extraConfig) => {
1265
+ const rawTable = new ConvexTableImpl(name, columns);
1266
+ const systemFields = createSystemFields(name);
1267
+ for (const builder of Object.values(systemFields)) builder.config.table = rawTable;
1268
+ const table = Object.assign(rawTable, systemFields, rawTable[Columns]);
1269
+ const internalCreationTime = systemFields._creationTime;
1270
+ if (Object.hasOwn(table, "_creationTime")) table._creationTime = void 0;
1271
+ Object.defineProperty(table, "_creationTime", {
1272
+ value: internalCreationTime,
1273
+ enumerable: false,
1274
+ configurable: true,
1275
+ writable: false
1276
+ });
1277
+ Object.defineProperty(table, "_id", {
1278
+ value: systemFields.id,
1279
+ enumerable: false,
1280
+ configurable: true,
1281
+ writable: false
1282
+ });
1283
+ applyExtraConfig(rawTable, extraConfig?.(table));
1284
+ return table;
1285
+ };
1286
+ const convexTableWithRLS = (name, columns, extraConfig) => {
1287
+ const table = convexTableInternal(name, columns, extraConfig);
1288
+ table[EnableRLS] = true;
1289
+ return table;
1290
+ };
1291
+ const convexTable = Object.assign(convexTableInternal, { withRLS: convexTableWithRLS });
1292
+
1293
+ //#endregion
1294
+ //#region src/aggregate-core/schema.ts
1295
+ const AGGREGATE_TREE_TABLE = "aggregate_rank_tree";
1296
+ const AGGREGATE_NODE_TABLE = "aggregate_rank_node";
1297
+ const aggregateCounterValidator = v.object({
1298
+ count: v.number(),
1299
+ sum: v.number()
1300
+ });
1301
+ const aggregateItemValidator = v.object({
1302
+ k: v.any(),
1303
+ v: v.any(),
1304
+ s: v.number()
1305
+ });
1306
+ const aggregateTreeTable = convexTable(AGGREGATE_TREE_TABLE, {
1307
+ aggregateName: text().notNull(),
1308
+ maxNodeSize: integer().notNull(),
1309
+ namespace: custom(v.any()),
1310
+ root: id(AGGREGATE_NODE_TABLE).notNull()
1311
+ }, (tree) => [index("by_namespace").on(tree.namespace), index("by_aggregate_name").on(tree.aggregateName)]);
1312
+ const aggregateNodeTable = convexTable(AGGREGATE_NODE_TABLE, {
1313
+ aggregate: custom(aggregateCounterValidator),
1314
+ items: custom(v.array(aggregateItemValidator)).notNull(),
1315
+ subtrees: custom(v.array(v.string())).notNull()
1316
+ });
1317
+ const aggregateStorageTables = {
1318
+ [AGGREGATE_NODE_TABLE]: aggregateNodeTable,
1319
+ [AGGREGATE_TREE_TABLE]: aggregateTreeTable
1320
+ };
1321
+
1322
+ //#endregion
1323
+ //#region src/aggregate-core/btree.ts
1324
+ const DEFAULT_MAX_NODE_SIZE = 16;
1325
+ const LEGACY_AGGREGATE_NAME = "__legacy__";
1326
+ function p(v) {
1327
+ try {
1328
+ return JSON.stringify(v);
1329
+ } catch {
1330
+ return String(v);
1331
+ }
1332
+ }
1333
+ function log(s) {}
1334
+ function aggregateNameFromNamespace(namespace) {
1335
+ if (Array.isArray(namespace) && namespace.length === 3 && typeof namespace[0] === "string" && (namespace[2] === 0 || namespace[2] === 1)) return namespace[0];
1336
+ return LEGACY_AGGREGATE_NAME;
1337
+ }
1338
+ async function insertHandler(ctx, args) {
1339
+ const tree = await getOrCreateTree(ctx.db, args.namespace, DEFAULT_MAX_NODE_SIZE, true);
1340
+ const summand = args.summand ?? 0;
1341
+ const pushUp = await insertIntoNode(ctx, args.namespace, tree.root, {
1342
+ k: args.key,
1343
+ v: args.value,
1344
+ s: summand
1345
+ });
1346
+ if (pushUp) {
1347
+ const total = pushUp.leftSubtreeCount && pushUp.rightSubtreeCount && add(add(pushUp.leftSubtreeCount, pushUp.rightSubtreeCount), itemAggregate(pushUp.item));
1348
+ const newRoot = await ctx.db.insert(AGGREGATE_NODE_TABLE, {
1349
+ items: [pushUp.item],
1350
+ subtrees: [pushUp.leftSubtree, pushUp.rightSubtree],
1351
+ aggregate: total
1352
+ });
1353
+ await ctx.db.patch(tree._id, { root: newRoot });
1354
+ }
1355
+ }
1356
+ async function deleteHandler(ctx, args) {
1357
+ const tree = await getOrCreateTree(ctx.db, args.namespace, DEFAULT_MAX_NODE_SIZE, true);
1358
+ await deleteFromNode(ctx, args.namespace, tree.root, args.key);
1359
+ const root = await ctx.db.get(tree.root);
1360
+ if (root.items.length === 0 && root.subtrees.length === 1) {
1361
+ log(`collapsing root ${root._id} because its only child is ${root.subtrees[0]}`);
1362
+ await ctx.db.patch(tree._id, { root: root.subtrees[0] });
1363
+ if (root.aggregate === void 0) await ctx.db.patch(root.subtrees[0], { aggregate: void 0 });
1364
+ await ctx.db.delete(root._id);
1365
+ }
1366
+ }
1367
+ async function MAX_NODE_SIZE(ctx, namespace) {
1368
+ return (await mustGetTree(ctx.db, namespace)).maxNodeSize;
1369
+ }
1370
+ async function MIN_NODE_SIZE(ctx, namespace) {
1371
+ const max = await MAX_NODE_SIZE(ctx, namespace);
1372
+ if (max % 2 !== 0 || max < 4) throw new Error("MAX_NODE_SIZE must be even and at least 4");
1373
+ return max / 2;
1374
+ }
1375
+ async function aggregateBetweenHandler(ctx, args) {
1376
+ const tree = await getTree(ctx.db, args.namespace);
1377
+ if (tree === null) return {
1378
+ count: 0,
1379
+ sum: 0
1380
+ };
1381
+ return await aggregateBetweenInNode(ctx.db, tree.root, args.k1, args.k2);
1382
+ }
1383
+ async function filterBetween(db, node, k1, k2) {
1384
+ const n = await db.get(node);
1385
+ const included = [];
1386
+ function includeSubtree(i, unboundedRight) {
1387
+ const unboundedLeft = k1 === void 0 || included.length > 0;
1388
+ if (unboundedLeft && unboundedRight) included.push({
1389
+ type: "subtree",
1390
+ subtree: n.subtrees[i]
1391
+ });
1392
+ else included.push(filterBetween(db, n.subtrees[i], unboundedLeft ? void 0 : k1, unboundedRight ? void 0 : k2));
1393
+ }
1394
+ let done = false;
1395
+ for (let i = 0; i < n.items.length; i++) {
1396
+ const k1IsLeft = k1 === void 0 || compareKeys(k1, n.items[i].k) === -1;
1397
+ const k2IsRight = k2 === void 0 || compareKeys(k2, n.items[i].k) === 1;
1398
+ if (k1IsLeft && n.subtrees.length > 0) includeSubtree(i, k2IsRight);
1399
+ if (!k2IsRight) {
1400
+ done = true;
1401
+ break;
1402
+ }
1403
+ if (k1IsLeft) included.push({
1404
+ type: "item",
1405
+ item: n.items[i]
1406
+ });
1407
+ }
1408
+ if (!done && n.subtrees.length > 0) includeSubtree(n.subtrees.length - 1, k2 === void 0);
1409
+ return (await Promise.all(included)).flat(1);
1410
+ }
1411
+ async function aggregateBetweenInNode(db, node, k1, k2) {
1412
+ const filtered = await filterBetween(db, node, k1, k2);
1413
+ const counts = await Promise.all(filtered.map(async (included) => {
1414
+ if (included.type === "item") return itemAggregate(included.item);
1415
+ return await nodeAggregate(db, await db.get(included.subtree));
1416
+ }));
1417
+ let count = {
1418
+ count: 0,
1419
+ sum: 0
1420
+ };
1421
+ for (const c of counts) count = add(count, c);
1422
+ return count;
1423
+ }
1424
+ async function atOffsetHandler(ctx, args) {
1425
+ if (args.offset < 0) throw new Error("offset must be non-negative");
1426
+ if (!Number.isInteger(args.offset)) throw new Error("offset must be an integer");
1427
+ const tree = await getTree(ctx.db, args.namespace);
1428
+ if (tree === null) throw new ConvexError("tree is empty");
1429
+ return await atOffsetInNode(ctx.db, tree.root, args.offset, args.k1, args.k2);
1430
+ }
1431
+ async function atNegativeOffsetHandler(ctx, args) {
1432
+ if (args.offset < 0) throw new Error("offset must be non-negative");
1433
+ if (!Number.isInteger(args.offset)) throw new Error("offset must be an integer");
1434
+ const tree = await getTree(ctx.db, args.namespace);
1435
+ if (tree === null) throw new ConvexError("tree is empty");
1436
+ return await negativeOffsetInNode(ctx.db, tree.root, args.offset, args.k1, args.k2);
1437
+ }
1438
+ async function offsetHandler(ctx, args) {
1439
+ return (await aggregateBetweenHandler(ctx, {
1440
+ k1: args.k1,
1441
+ k2: args.key,
1442
+ namespace: args.namespace
1443
+ })).count;
1444
+ }
1445
+ async function offsetUntilHandler(ctx, args) {
1446
+ return (await aggregateBetweenHandler(ctx, {
1447
+ k1: args.key,
1448
+ k2: args.k2,
1449
+ namespace: args.namespace
1450
+ })).count;
1451
+ }
1452
+ async function deleteFromNode(ctx, namespace, node, key) {
1453
+ let n = await ctx.db.get(node);
1454
+ let foundItem = null;
1455
+ let i = 0;
1456
+ for (; i < n.items.length; i++) {
1457
+ const compare = compareKeys(key, n.items[i].k);
1458
+ if (compare === -1) break;
1459
+ if (compare === 0) {
1460
+ log(`found key ${p(key)} in node ${n._id}`);
1461
+ if (n.subtrees.length === 0) {
1462
+ await ctx.db.patch(node, {
1463
+ items: [...n.items.slice(0, i), ...n.items.slice(i + 1)],
1464
+ aggregate: n.aggregate && sub(n.aggregate, itemAggregate(n.items[i]))
1465
+ });
1466
+ return n.items[i];
1467
+ }
1468
+ const predecessor = await negativeOffsetInNode(ctx.db, n.subtrees[i], 0);
1469
+ log(`replacing ${p(key)} with predecessor ${p(predecessor.k)}`);
1470
+ foundItem = n.items[i];
1471
+ await ctx.db.patch(node, {
1472
+ items: [
1473
+ ...n.items.slice(0, i),
1474
+ predecessor,
1475
+ ...n.items.slice(i + 1)
1476
+ ],
1477
+ aggregate: n.aggregate && sub(add(n.aggregate, itemAggregate(predecessor)), itemAggregate(n.items[i]))
1478
+ });
1479
+ n = await ctx.db.get(node);
1480
+ key = predecessor.k;
1481
+ break;
1482
+ }
1483
+ }
1484
+ if (n.subtrees.length === 0) throw new ConvexError({
1485
+ code: "DELETE_MISSING_KEY",
1486
+ message: `key ${p(key)} not found in node ${n._id}`
1487
+ });
1488
+ const deleted = await deleteFromNode(ctx, namespace, n.subtrees[i], key);
1489
+ if (!deleted) return null;
1490
+ if (!foundItem) foundItem = deleted;
1491
+ const newAggregate = n.aggregate && sub(n.aggregate, itemAggregate(deleted));
1492
+ if (newAggregate) await ctx.db.patch(node, { aggregate: newAggregate });
1493
+ const deficientSubtree = await ctx.db.get(n.subtrees[i]);
1494
+ const minNodeSize = await MIN_NODE_SIZE(ctx, namespace);
1495
+ if (deficientSubtree.items.length < minNodeSize) {
1496
+ log(`deficient subtree ${deficientSubtree._id}`);
1497
+ if (i > 0) {
1498
+ const leftSibling = await ctx.db.get(n.subtrees[i - 1]);
1499
+ if (leftSibling.items.length > minNodeSize) {
1500
+ log(`rotating right with left sibling ${leftSibling._id}`);
1501
+ const grandchild = leftSibling.subtrees.length ? await ctx.db.get(leftSibling.subtrees[leftSibling.subtrees.length - 1]) : null;
1502
+ const grandchildCount = grandchild ? grandchild.aggregate : {
1503
+ count: 0,
1504
+ sum: 0
1505
+ };
1506
+ await ctx.db.patch(deficientSubtree._id, {
1507
+ items: [n.items[i - 1], ...deficientSubtree.items],
1508
+ subtrees: grandchild ? [grandchild._id, ...deficientSubtree.subtrees] : [],
1509
+ aggregate: deficientSubtree.aggregate && grandchildCount && add(add(deficientSubtree.aggregate, grandchildCount), itemAggregate(n.items[i - 1]))
1510
+ });
1511
+ await ctx.db.patch(leftSibling._id, {
1512
+ items: leftSibling.items.slice(0, leftSibling.items.length - 1),
1513
+ subtrees: grandchild ? leftSibling.subtrees.slice(0, leftSibling.subtrees.length - 1) : [],
1514
+ aggregate: leftSibling.aggregate && grandchildCount && sub(sub(leftSibling.aggregate, grandchildCount), itemAggregate(leftSibling.items[leftSibling.items.length - 1]))
1515
+ });
1516
+ await ctx.db.patch(node, { items: [
1517
+ ...n.items.slice(0, i - 1),
1518
+ leftSibling.items[leftSibling.items.length - 1],
1519
+ ...n.items.slice(i)
1520
+ ] });
1521
+ return foundItem;
1522
+ }
1523
+ }
1524
+ if (i < n.subtrees.length - 1) {
1525
+ const rightSibling = await ctx.db.get(n.subtrees[i + 1]);
1526
+ if (rightSibling.items.length > minNodeSize) {
1527
+ log(`rotating left with right sibling ${rightSibling._id}`);
1528
+ const grandchild = rightSibling.subtrees.length ? await ctx.db.get(rightSibling.subtrees[0]) : null;
1529
+ const grandchildCount = grandchild ? grandchild.aggregate : {
1530
+ count: 0,
1531
+ sum: 0
1532
+ };
1533
+ await ctx.db.patch(deficientSubtree._id, {
1534
+ items: [...deficientSubtree.items, n.items[i]],
1535
+ subtrees: grandchild ? [...deficientSubtree.subtrees, grandchild._id] : [],
1536
+ aggregate: deficientSubtree.aggregate && grandchildCount && add(add(deficientSubtree.aggregate, grandchildCount), itemAggregate(n.items[i]))
1537
+ });
1538
+ await ctx.db.patch(rightSibling._id, {
1539
+ items: rightSibling.items.slice(1),
1540
+ subtrees: grandchild ? rightSibling.subtrees.slice(1) : [],
1541
+ aggregate: rightSibling.aggregate && grandchildCount && sub(sub(rightSibling.aggregate, grandchildCount), itemAggregate(rightSibling.items[0]))
1542
+ });
1543
+ await ctx.db.patch(node, { items: [
1544
+ ...n.items.slice(0, i),
1545
+ rightSibling.items[0],
1546
+ ...n.items.slice(i + 1)
1547
+ ] });
1548
+ return foundItem;
1549
+ }
1550
+ }
1551
+ if (i > 0) {
1552
+ log("merging with left sibling");
1553
+ await mergeNodes(ctx.db, n, i - 1);
1554
+ } else {
1555
+ log("merging with right sibling");
1556
+ await mergeNodes(ctx.db, n, i);
1557
+ }
1558
+ }
1559
+ return foundItem;
1560
+ }
1561
+ async function mergeNodes(db, parent, leftIndex) {
1562
+ const left = await db.get(parent.subtrees[leftIndex]);
1563
+ const right = await db.get(parent.subtrees[leftIndex + 1]);
1564
+ log(`merging ${right._id} into ${left._id}`);
1565
+ await db.patch(left._id, {
1566
+ items: [
1567
+ ...left.items,
1568
+ parent.items[leftIndex],
1569
+ ...right.items
1570
+ ],
1571
+ subtrees: [...left.subtrees, ...right.subtrees],
1572
+ aggregate: left.aggregate && right.aggregate && add(add(left.aggregate, right.aggregate), itemAggregate(parent.items[leftIndex]))
1573
+ });
1574
+ await db.patch(parent._id, {
1575
+ items: [...parent.items.slice(0, leftIndex), ...parent.items.slice(leftIndex + 1)],
1576
+ subtrees: [...parent.subtrees.slice(0, leftIndex + 1), ...parent.subtrees.slice(leftIndex + 2)]
1577
+ });
1578
+ await db.delete(right._id);
1579
+ }
1580
+ async function negativeOffsetInNode(db, node, index, k1, k2) {
1581
+ const filtered = await filterBetween(db, node, k1, k2);
1582
+ for (const included of filtered.reverse()) if (included.type === "item") {
1583
+ if (index === 0) return included.item;
1584
+ index -= 1;
1585
+ } else {
1586
+ const subtreeCount = (await nodeAggregate(db, await db.get(included.subtree))).count;
1587
+ if (index < subtreeCount) return await negativeOffsetInNode(db, included.subtree, index);
1588
+ index -= subtreeCount;
1589
+ }
1590
+ throw new ConvexError(`negative offset exceeded count by ${index} (in node ${node})`);
1591
+ }
1592
+ async function atOffsetInNode(db, node, index, k1, k2) {
1593
+ const filtered = await filterBetween(db, node, k1, k2);
1594
+ for (const included of filtered) if (included.type === "item") {
1595
+ if (index === 0) return included.item;
1596
+ index -= 1;
1597
+ } else {
1598
+ const subtreeCount = (await nodeAggregate(db, await db.get(included.subtree))).count;
1599
+ if (index < subtreeCount) return await atOffsetInNode(db, included.subtree, index);
1600
+ index -= subtreeCount;
1601
+ }
1602
+ throw new ConvexError(`offset exceeded count by ${index} (in node ${node})`);
1603
+ }
1604
+ function itemAggregate(item) {
1605
+ return {
1606
+ count: 1,
1607
+ sum: item.s
1608
+ };
1609
+ }
1610
+ function nodeCounts(node) {
1611
+ return node.items.map(itemAggregate);
1612
+ }
1613
+ async function subtreeCounts(db, node) {
1614
+ return await Promise.all(node.subtrees.map(async (subtree) => {
1615
+ return nodeAggregate(db, await db.get(subtree));
1616
+ }));
1617
+ }
1618
+ async function nodeAggregate(db, node) {
1619
+ if (node.aggregate !== void 0) return node.aggregate;
1620
+ const subCounts = await subtreeCounts(db, node);
1621
+ return add(accumulate(nodeCounts(node)), accumulate(subCounts));
1622
+ }
1623
+ function add(a, b) {
1624
+ return {
1625
+ count: a.count + b.count,
1626
+ sum: a.sum + b.sum
1627
+ };
1628
+ }
1629
+ function sub(a, b) {
1630
+ return {
1631
+ count: a.count - b.count,
1632
+ sum: a.sum - b.sum
1633
+ };
1634
+ }
1635
+ function accumulate(nums) {
1636
+ return nums.reduce(add, {
1637
+ count: 0,
1638
+ sum: 0
1639
+ });
1640
+ }
1641
+ async function insertIntoNode(ctx, namespace, node, item) {
1642
+ const n = await ctx.db.get(node);
1643
+ let i = 0;
1644
+ for (; i < n.items.length; i++) {
1645
+ const compare = compareKeys(item.k, n.items[i].k);
1646
+ if (compare === -1) break;
1647
+ if (compare === 0) throw new ConvexError(`key ${p(item.k)} already exists in node ${n._id}`);
1648
+ }
1649
+ if (n.subtrees.length > 0) {
1650
+ const pushUp = await insertIntoNode(ctx, namespace, n.subtrees[i], item);
1651
+ if (pushUp) await ctx.db.patch(node, {
1652
+ items: [
1653
+ ...n.items.slice(0, i),
1654
+ pushUp.item,
1655
+ ...n.items.slice(i)
1656
+ ],
1657
+ subtrees: [
1658
+ ...n.subtrees.slice(0, i),
1659
+ pushUp.leftSubtree,
1660
+ pushUp.rightSubtree,
1661
+ ...n.subtrees.slice(i + 1)
1662
+ ]
1663
+ });
1664
+ } else await ctx.db.patch(node, { items: [
1665
+ ...n.items.slice(0, i),
1666
+ item,
1667
+ ...n.items.slice(i)
1668
+ ] });
1669
+ const newAggregate = n.aggregate && add(n.aggregate, itemAggregate(item));
1670
+ if (newAggregate) await ctx.db.patch(node, { aggregate: newAggregate });
1671
+ const newN = await ctx.db.get(node);
1672
+ const maxNodeSize = await MAX_NODE_SIZE(ctx, namespace);
1673
+ const minNodeSize = await MIN_NODE_SIZE(ctx, namespace);
1674
+ if (newN.items.length > maxNodeSize) {
1675
+ if (newN.items.length !== maxNodeSize + 1 || newN.items.length !== 2 * minNodeSize + 1) throw new Error(`bad ${newN.items.length}`);
1676
+ log(`splitting node ${newN._id} at ${newN.items[minNodeSize].k}`);
1677
+ const topLevel = nodeCounts(newN);
1678
+ const subCounts = await subtreeCounts(ctx.db, newN);
1679
+ const leftCount = add(accumulate(topLevel.slice(0, minNodeSize)), accumulate(subCounts.length ? subCounts.slice(0, minNodeSize + 1) : []));
1680
+ const rightCount = add(accumulate(topLevel.slice(minNodeSize + 1)), accumulate(subCounts.length ? subCounts.slice(minNodeSize + 1) : []));
1681
+ if (newN.aggregate && leftCount.count + rightCount.count + 1 !== newN.aggregate.count) throw new Error(`bad count split ${leftCount.count} ${rightCount.count} ${newN.aggregate.count}`);
1682
+ if (newN.aggregate && Math.abs(leftCount.sum + rightCount.sum + newN.items[minNodeSize].s - newN.aggregate.sum) > 1e-5) throw new Error(`bad sum split ${leftCount.sum} ${rightCount.sum} ${newN.items[minNodeSize].s} ${newN.aggregate.sum}`);
1683
+ await ctx.db.patch(node, {
1684
+ items: newN.items.slice(0, minNodeSize),
1685
+ subtrees: newN.subtrees.length ? newN.subtrees.slice(0, minNodeSize + 1) : [],
1686
+ aggregate: leftCount
1687
+ });
1688
+ const splitN = await ctx.db.insert(AGGREGATE_NODE_TABLE, {
1689
+ items: newN.items.slice(minNodeSize + 1),
1690
+ subtrees: newN.subtrees.length ? newN.subtrees.slice(minNodeSize + 1) : [],
1691
+ aggregate: rightCount
1692
+ });
1693
+ return {
1694
+ item: newN.items[minNodeSize],
1695
+ leftSubtree: node,
1696
+ rightSubtree: splitN,
1697
+ leftSubtreeCount: newN.aggregate && leftCount,
1698
+ rightSubtreeCount: newN.aggregate && rightCount
1699
+ };
1700
+ }
1701
+ return null;
1702
+ }
1703
+ function compareKeys(k1, k2) {
1704
+ return compareValues$1(k1, k2);
1705
+ }
1706
+ async function getTree(db, namespace) {
1707
+ return await db.query(AGGREGATE_TREE_TABLE).withIndex("by_namespace", (q) => q.eq("namespace", namespace)).unique();
1708
+ }
1709
+ async function mustGetTree(db, namespace) {
1710
+ const tree = await getTree(db, namespace);
1711
+ if (!tree) throw new Error("btree not initialized");
1712
+ return tree;
1713
+ }
1714
+ async function getOrCreateTree(db, namespace, maxNodeSize, rootLazy) {
1715
+ const originalTree = await getTree(db, namespace);
1716
+ const aggregateName = aggregateNameFromNamespace(namespace);
1717
+ if (originalTree) {
1718
+ if (originalTree.aggregateName !== aggregateName) {
1719
+ await db.patch(originalTree._id, { aggregateName });
1720
+ return {
1721
+ ...originalTree,
1722
+ aggregateName
1723
+ };
1724
+ }
1725
+ return originalTree;
1726
+ }
1727
+ const root = await db.insert(AGGREGATE_NODE_TABLE, {
1728
+ items: [],
1729
+ subtrees: [],
1730
+ aggregate: {
1731
+ count: 0,
1732
+ sum: 0
1733
+ }
1734
+ });
1735
+ const effectiveMaxNodeSize = maxNodeSize ?? await MAX_NODE_SIZE({ db }, void 0) ?? DEFAULT_MAX_NODE_SIZE;
1736
+ const effectiveRootLazy = rootLazy ?? await isRootLazy(db, void 0) ?? true;
1737
+ const id = await db.insert(AGGREGATE_TREE_TABLE, {
1738
+ aggregateName,
1739
+ root,
1740
+ maxNodeSize: effectiveMaxNodeSize,
1741
+ namespace
1742
+ });
1743
+ const newTree = await db.get(id);
1744
+ await MIN_NODE_SIZE({ db }, namespace);
1745
+ if (effectiveRootLazy) await db.patch(root, { aggregate: void 0 });
1746
+ return newTree;
1747
+ }
1748
+ async function isRootLazy(db, namespace) {
1749
+ const tree = await getTree(db, namespace);
1750
+ if (!tree) return true;
1751
+ return (await db.get(tree.root))?.aggregate === void 0;
1752
+ }
1753
+ async function deleteTreeNodes(db, node) {
1754
+ const current = await db.get(node);
1755
+ if (!current) return;
1756
+ for (const subtree of current.subtrees) await deleteTreeNodes(db, subtree);
1757
+ await db.delete(node);
1758
+ }
1759
+ async function clearTree(db, args) {
1760
+ const tree = await getTree(db, args.namespace);
1761
+ let existingRootLazy = true;
1762
+ let existingMaxNodeSize = DEFAULT_MAX_NODE_SIZE;
1763
+ if (tree) {
1764
+ await db.delete(tree._id);
1765
+ const root = await db.get(tree.root);
1766
+ if (root) {
1767
+ existingRootLazy = root.aggregate === void 0;
1768
+ await deleteTreeNodes(db, tree.root);
1769
+ }
1770
+ existingMaxNodeSize = tree.maxNodeSize;
1771
+ }
1772
+ await getOrCreateTree(db, args.namespace, args.maxNodeSize ?? existingMaxNodeSize, args.rootLazy ?? existingRootLazy);
1773
+ }
1774
+ async function paginateHandler(ctx, args) {
1775
+ const tree = await getTree(ctx.db, args.namespace);
1776
+ if (tree === null) return {
1777
+ page: [],
1778
+ cursor: "",
1779
+ isDone: true
1780
+ };
1781
+ return await paginateInNode(ctx.db, tree.root, args.limit, args.order, args.cursor, args.k1, args.k2);
1782
+ }
1783
+ async function paginateInNode(db, node, limit, order, cursor, k1, k2) {
1784
+ if (limit <= 0) throw new ConvexError("limit must be positive");
1785
+ if (cursor !== void 0 && cursor.length === 0) return {
1786
+ page: [],
1787
+ cursor: "",
1788
+ isDone: true
1789
+ };
1790
+ const items = [];
1791
+ const filtered = await filterBetween(db, node, cursor === void 0 || order === "desc" ? k1 : jsonToConvex(JSON.parse(cursor)), cursor === void 0 || order === "asc" ? k2 : jsonToConvex(JSON.parse(cursor)));
1792
+ if (order === "desc") filtered.reverse();
1793
+ for (const included of filtered) {
1794
+ if (items.length >= limit) return {
1795
+ page: items,
1796
+ cursor: JSON.stringify(convexToJson(items[items.length - 1].k)),
1797
+ isDone: false
1798
+ };
1799
+ if (included.type === "item") items.push(included.item);
1800
+ else {
1801
+ const { page, cursor: newCursor, isDone } = await paginateInNode(db, included.subtree, limit - items.length, order);
1802
+ items.push(...page);
1803
+ if (!isDone) return {
1804
+ page: items,
1805
+ cursor: newCursor,
1806
+ isDone: false
1807
+ };
1808
+ }
1809
+ }
1810
+ return {
1811
+ page: items,
1812
+ cursor: "",
1813
+ isDone: true
1814
+ };
1815
+ }
1816
+ async function paginateNamespacesHandler(ctx, args) {
1817
+ if (args.cursor === "endcursor") return {
1818
+ page: [],
1819
+ cursor: "endcursor",
1820
+ isDone: true
1821
+ };
1822
+ const { page: trees, continueCursor, isDone } = await (args.aggregateName === void 0 ? ctx.db.query(AGGREGATE_TREE_TABLE) : ctx.db.query(AGGREGATE_TREE_TABLE).withIndex("by_aggregate_name", (q) => q.eq("aggregateName", args.aggregateName))).paginate({
1823
+ cursor: args.cursor ?? null,
1824
+ numItems: args.limit
1825
+ });
1826
+ return {
1827
+ page: trees.map((t) => t.namespace ?? null),
1828
+ cursor: isDone ? "endcursor" : continueCursor ?? "endcursor",
1829
+ isDone
1830
+ };
1831
+ }
1832
+ async function aggregateBetweenBatchHandler(ctx, args) {
1833
+ return await Promise.all(args.queries.map((query) => aggregateBetweenHandler(ctx, query)));
1834
+ }
1835
+ async function atOffsetBatchHandler(ctx, args) {
1836
+ return await Promise.all(args.queries.map((query) => query.offset >= 0 ? atOffsetHandler(ctx, query) : atNegativeOffsetHandler(ctx, {
1837
+ ...query,
1838
+ offset: -query.offset - 1
1839
+ })));
1840
+ }
1841
+
1842
+ //#endregion
1843
+ //#region src/aggregate-core/positions.ts
1844
+ const BEFORE_ALL_IDS = null;
1845
+ const AFTER_ALL_IDS = [];
1846
+ function explodeKey(key) {
1847
+ if (Array.isArray(key)) {
1848
+ const exploded = [""];
1849
+ for (const item of key) {
1850
+ exploded.push(item);
1851
+ exploded.push("");
1852
+ }
1853
+ return exploded;
1854
+ }
1855
+ return key;
1856
+ }
1857
+ function implodeKey(k) {
1858
+ if (Array.isArray(k)) {
1859
+ const imploded = [];
1860
+ for (let i = 1; i < k.length; i += 2) imploded.push(k[i]);
1861
+ return imploded;
1862
+ }
1863
+ return k;
1864
+ }
1865
+ function keyToPosition(key, id) {
1866
+ return [
1867
+ explodeKey(key),
1868
+ id,
1869
+ ""
1870
+ ];
1871
+ }
1872
+ function positionToKey(position) {
1873
+ return {
1874
+ key: implodeKey(position[0]),
1875
+ id: position[1]
1876
+ };
1877
+ }
1878
+ function boundsToPositions(bounds) {
1879
+ if (bounds === void 0) return {};
1880
+ if ("eq" in bounds) return {
1881
+ k1: boundToPosition("lower", {
1882
+ key: bounds.eq,
1883
+ inclusive: true
1884
+ }),
1885
+ k2: boundToPosition("upper", {
1886
+ key: bounds.eq,
1887
+ inclusive: true
1888
+ })
1889
+ };
1890
+ if ("prefix" in bounds) {
1891
+ const prefix = bounds.prefix;
1892
+ const exploded = [];
1893
+ for (const item of prefix) {
1894
+ exploded.push("");
1895
+ exploded.push(item);
1896
+ }
1897
+ return {
1898
+ k1: [
1899
+ exploded.concat([BEFORE_ALL_IDS]),
1900
+ BEFORE_ALL_IDS,
1901
+ BEFORE_ALL_IDS
1902
+ ],
1903
+ k2: [
1904
+ exploded.concat([AFTER_ALL_IDS]),
1905
+ AFTER_ALL_IDS,
1906
+ AFTER_ALL_IDS
1907
+ ]
1908
+ };
1909
+ }
1910
+ return {
1911
+ k1: boundToPosition("lower", bounds.lower),
1912
+ k2: boundToPosition("upper", bounds.upper)
1913
+ };
1914
+ }
1915
+ function boundToPosition(direction, bound) {
1916
+ if (bound === void 0) return;
1917
+ if (direction === "lower") return [
1918
+ explodeKey(bound.key),
1919
+ bound.id ?? (bound.inclusive ? BEFORE_ALL_IDS : AFTER_ALL_IDS),
1920
+ bound.inclusive ? BEFORE_ALL_IDS : AFTER_ALL_IDS
1921
+ ];
1922
+ return [
1923
+ explodeKey(bound.key),
1924
+ bound.id ?? (bound.inclusive ? AFTER_ALL_IDS : BEFORE_ALL_IDS),
1925
+ bound.inclusive ? AFTER_ALL_IDS : BEFORE_ALL_IDS
1926
+ ];
1927
+ }
1928
+
1929
+ //#endregion
1930
+ //#region src/aggregate-core/runtime.ts
1931
+ const INTERNAL_NAMESPACE_MARKER_MISSING = 0;
1932
+ const INTERNAL_NAMESPACE_MARKER_PRESENT = 1;
1933
+ const encodeNamespace = (aggregateName, namespace) => [
1934
+ aggregateName,
1935
+ namespace === void 0 ? null : namespace,
1936
+ namespace === void 0 ? INTERNAL_NAMESPACE_MARKER_MISSING : INTERNAL_NAMESPACE_MARKER_PRESENT
1937
+ ];
1938
+ const isInternalNamespace = (value) => Array.isArray(value) && value.length === 3 && typeof value[0] === "string" && (value[2] === INTERNAL_NAMESPACE_MARKER_MISSING || value[2] === INTERNAL_NAMESPACE_MARKER_PRESENT);
1939
+ const decodeNamespace = (namespace) => {
1940
+ if (namespace[2] === INTERNAL_NAMESPACE_MARKER_MISSING) return;
1941
+ return namespace[1];
1942
+ };
1943
+ const namespaceForOpts = (aggregateName, opts) => encodeNamespace(aggregateName, namespaceFromOpts(opts));
1944
+ const namespaceForArg = (aggregateName, args) => encodeNamespace(aggregateName, namespaceFromArg(args));
1945
+ /**
1946
+ * Write data to be aggregated, and read aggregated data.
1947
+ */
1948
+ var Aggregate = class {
1949
+ constructor(aggregateName) {
1950
+ this.aggregateName = aggregateName;
1951
+ }
1952
+ async count(ctx, ...opts) {
1953
+ return (await aggregateBetweenHandler({ db: ctx.db }, {
1954
+ ...boundsToPositions(opts[0]?.bounds),
1955
+ namespace: namespaceForOpts(this.aggregateName, opts)
1956
+ })).count;
1957
+ }
1958
+ async countBatch(ctx, queries) {
1959
+ return (await aggregateBetweenBatchHandler({ db: ctx.db }, { queries: queries.map((query) => {
1960
+ if (!query) throw new Error("You must pass bounds and/or namespace");
1961
+ return {
1962
+ ...boundsToPositions(query.bounds),
1963
+ namespace: namespaceForArg(this.aggregateName, query)
1964
+ };
1965
+ }) })).map((result) => result.count);
1966
+ }
1967
+ async sum(ctx, ...opts) {
1968
+ return (await aggregateBetweenHandler({ db: ctx.db }, {
1969
+ ...boundsToPositions(opts[0]?.bounds),
1970
+ namespace: namespaceForOpts(this.aggregateName, opts)
1971
+ })).sum;
1972
+ }
1973
+ async sumBatch(ctx, queries) {
1974
+ return (await aggregateBetweenBatchHandler({ db: ctx.db }, { queries: queries.map((query) => {
1975
+ if (!query) throw new Error("You must pass bounds and/or namespace");
1976
+ return {
1977
+ ...boundsToPositions(query.bounds),
1978
+ namespace: namespaceForArg(this.aggregateName, query)
1979
+ };
1980
+ }) })).map((result) => result.sum);
1981
+ }
1982
+ async at(ctx, offset, ...opts) {
1983
+ const encodedNamespace = namespaceForOpts(this.aggregateName, opts);
1984
+ return btreeItemToAggregateItem(offset < 0 ? await atNegativeOffsetHandler({ db: ctx.db }, {
1985
+ ...boundsToPositions(opts[0]?.bounds),
1986
+ namespace: encodedNamespace,
1987
+ offset: -offset - 1
1988
+ }) : await atOffsetHandler({ db: ctx.db }, {
1989
+ ...boundsToPositions(opts[0]?.bounds),
1990
+ namespace: encodedNamespace,
1991
+ offset
1992
+ }));
1993
+ }
1994
+ async atBatch(ctx, queries) {
1995
+ return (await atOffsetBatchHandler({ db: ctx.db }, { queries: queries.map((query) => ({
1996
+ ...boundsToPositions(query.bounds),
1997
+ namespace: namespaceForArg(this.aggregateName, query),
1998
+ offset: query.offset
1999
+ })) })).map(btreeItemToAggregateItem);
2000
+ }
2001
+ async indexOf(ctx, key, ...opts) {
2002
+ const { k1, k2 } = boundsToPositions(opts[0]?.bounds);
2003
+ const namespace = namespaceForOpts(this.aggregateName, opts);
2004
+ if (opts[0]?.order === "desc") return offsetUntilHandler({ db: ctx.db }, {
2005
+ k2,
2006
+ key: boundToPosition("upper", {
2007
+ id: opts[0]?.id,
2008
+ inclusive: true,
2009
+ key
2010
+ }),
2011
+ namespace
2012
+ });
2013
+ return offsetHandler({ db: ctx.db }, {
2014
+ k1,
2015
+ key: boundToPosition("lower", {
2016
+ id: opts[0]?.id,
2017
+ inclusive: true,
2018
+ key
2019
+ }),
2020
+ namespace
2021
+ });
2022
+ }
2023
+ async offsetOf(ctx, key, namespace, id, bounds) {
2024
+ return this.indexOf(ctx, key, {
2025
+ bounds,
2026
+ id,
2027
+ namespace,
2028
+ order: "asc"
2029
+ });
2030
+ }
2031
+ async offsetUntil(ctx, key, namespace, id, bounds) {
2032
+ return this.indexOf(ctx, key, {
2033
+ bounds,
2034
+ id,
2035
+ namespace,
2036
+ order: "desc"
2037
+ });
2038
+ }
2039
+ async min(ctx, ...opts) {
2040
+ const { page } = await this.paginate(ctx, {
2041
+ bounds: opts[0]?.bounds,
2042
+ namespace: namespaceFromOpts(opts),
2043
+ order: "asc",
2044
+ pageSize: 1
2045
+ });
2046
+ return page[0] ?? null;
2047
+ }
2048
+ async max(ctx, ...opts) {
2049
+ const { page } = await this.paginate(ctx, {
2050
+ bounds: opts[0]?.bounds,
2051
+ namespace: namespaceFromOpts(opts),
2052
+ order: "desc",
2053
+ pageSize: 1
2054
+ });
2055
+ return page[0] ?? null;
2056
+ }
2057
+ async random(ctx, ...opts) {
2058
+ const count = await this.count(ctx, ...opts);
2059
+ if (count === 0) return null;
2060
+ return this.at(ctx, Math.floor(Math.random() * count), ...opts);
2061
+ }
2062
+ async paginate(ctx, ...opts) {
2063
+ const result = await paginateHandler({ db: ctx.db }, {
2064
+ ...boundsToPositions(opts[0]?.bounds),
2065
+ cursor: opts[0]?.cursor,
2066
+ limit: opts[0]?.pageSize ?? 100,
2067
+ namespace: namespaceForOpts(this.aggregateName, opts),
2068
+ order: opts[0]?.order ?? "asc"
2069
+ });
2070
+ return {
2071
+ cursor: result.cursor,
2072
+ isDone: result.isDone,
2073
+ page: result.page.map(btreeItemToAggregateItem)
2074
+ };
2075
+ }
2076
+ async *iter(ctx, ...opts) {
2077
+ const bounds = opts[0]?.bounds;
2078
+ const namespace = namespaceFromOpts(opts);
2079
+ const order = opts[0]?.order ?? "asc";
2080
+ const pageSize = opts[0]?.pageSize ?? 100;
2081
+ let cursor;
2082
+ let isDone = false;
2083
+ while (!isDone) {
2084
+ const page = await this.paginate(ctx, {
2085
+ bounds,
2086
+ cursor,
2087
+ namespace,
2088
+ order,
2089
+ pageSize
2090
+ });
2091
+ for (const item of page.page) yield item;
2092
+ cursor = page.cursor;
2093
+ isDone = page.isDone;
2094
+ }
2095
+ }
2096
+ async _insert(ctx, namespace, key, id, summand) {
2097
+ await insertHandler({ db: ctx.db }, {
2098
+ key: keyToPosition(key, id),
2099
+ namespace: namespaceForArg(this.aggregateName, { namespace }),
2100
+ summand,
2101
+ value: id
2102
+ });
2103
+ }
2104
+ async _delete(ctx, namespace, key, id) {
2105
+ await deleteHandler({ db: ctx.db }, {
2106
+ key: keyToPosition(key, id),
2107
+ namespace: namespaceForArg(this.aggregateName, { namespace })
2108
+ });
2109
+ }
2110
+ async _replace(ctx, currentNamespace, currentKey, newNamespace, newKey, id, summand) {
2111
+ await deleteHandler({ db: ctx.db }, {
2112
+ key: keyToPosition(currentKey, id),
2113
+ namespace: namespaceForArg(this.aggregateName, { namespace: currentNamespace })
2114
+ });
2115
+ await insertHandler({ db: ctx.db }, {
2116
+ key: keyToPosition(newKey, id),
2117
+ namespace: namespaceForArg(this.aggregateName, { namespace: newNamespace }),
2118
+ summand,
2119
+ value: id
2120
+ });
2121
+ }
2122
+ async _insertIfDoesNotExist(ctx, namespace, key, id, summand) {
2123
+ await this._replaceOrInsert(ctx, namespace, key, namespace, key, id, summand);
2124
+ }
2125
+ async _deleteIfExists(ctx, namespace, key, id) {
2126
+ try {
2127
+ await this._delete(ctx, namespace, key, id);
2128
+ } catch (error) {
2129
+ if (error instanceof ConvexError && error.data?.code === "DELETE_MISSING_KEY") return;
2130
+ throw error;
2131
+ }
2132
+ }
2133
+ async _replaceOrInsert(ctx, currentNamespace, currentKey, newNamespace, newKey, id, summand) {
2134
+ try {
2135
+ await this._delete(ctx, currentNamespace, currentKey, id);
2136
+ } catch (error) {
2137
+ if (!(error instanceof ConvexError && error.data?.code === "DELETE_MISSING_KEY")) throw error;
2138
+ }
2139
+ await this._insert(ctx, newNamespace, newKey, id, summand);
2140
+ }
2141
+ async clear(ctx, ...opts) {
2142
+ await clearTree(ctx.db, {
2143
+ maxNodeSize: opts[0]?.maxNodeSize,
2144
+ namespace: namespaceForOpts(this.aggregateName, opts),
2145
+ rootLazy: opts[0]?.rootLazy
2146
+ });
2147
+ }
2148
+ async makeRootLazy(ctx, namespace) {
2149
+ const tree = await getOrCreateTree(ctx.db, namespaceForArg(this.aggregateName, { namespace }));
2150
+ await ctx.db.patch(tree.root, { aggregate: void 0 });
2151
+ }
2152
+ async paginateNamespaces(ctx, cursor, pageSize = 100) {
2153
+ const result = await paginateNamespacesHandler({ db: ctx.db }, {
2154
+ aggregateName: this.aggregateName,
2155
+ cursor,
2156
+ limit: pageSize
2157
+ });
2158
+ const page = [];
2159
+ for (const namespace of result.page) {
2160
+ if (!isInternalNamespace(namespace)) continue;
2161
+ if (namespace[0] !== this.aggregateName) continue;
2162
+ page.push(decodeNamespace(namespace));
2163
+ }
2164
+ return {
2165
+ cursor: result.cursor,
2166
+ isDone: result.isDone,
2167
+ page
2168
+ };
2169
+ }
2170
+ async *iterNamespaces(ctx, pageSize = 100) {
2171
+ let cursor;
2172
+ let isDone = false;
2173
+ while (!isDone) {
2174
+ const page = await this.paginateNamespaces(ctx, cursor, pageSize);
2175
+ for (const namespace of page.page) yield namespace;
2176
+ cursor = page.cursor;
2177
+ isDone = page.isDone;
2178
+ }
2179
+ }
2180
+ async clearAll(ctx, opts) {
2181
+ for await (const namespace of this.iterNamespaces(ctx)) await this.clear(ctx, {
2182
+ ...opts,
2183
+ namespace
2184
+ });
2185
+ await this.clear(ctx, {
2186
+ ...opts,
2187
+ namespace: void 0
2188
+ });
2189
+ }
2190
+ async makeAllRootsLazy(ctx) {
2191
+ for await (const namespace of this.iterNamespaces(ctx)) await this.makeRootLazy(ctx, namespace);
2192
+ }
2193
+ };
2194
+ var DirectAggregate = class extends Aggregate {
2195
+ constructor(config) {
2196
+ super(config.name);
2197
+ }
2198
+ async insert(ctx, args) {
2199
+ await this._insert(ctx, namespaceFromArg(args), args.key, args.id, args.sumValue);
2200
+ }
2201
+ async delete(ctx, args) {
2202
+ await this._delete(ctx, namespaceFromArg(args), args.key, args.id);
2203
+ }
2204
+ async replace(ctx, currentItem, newItem) {
2205
+ await this._replace(ctx, namespaceFromArg(currentItem), currentItem.key, namespaceFromArg(newItem), newItem.key, currentItem.id, newItem.sumValue);
2206
+ }
2207
+ async insertIfDoesNotExist(ctx, args) {
2208
+ await this._insertIfDoesNotExist(ctx, namespaceFromArg(args), args.key, args.id, args.sumValue);
2209
+ }
2210
+ async deleteIfExists(ctx, args) {
2211
+ await this._deleteIfExists(ctx, namespaceFromArg(args), args.key, args.id);
2212
+ }
2213
+ async replaceOrInsert(ctx, currentItem, newItem) {
2214
+ await this._replaceOrInsert(ctx, namespaceFromArg(currentItem), currentItem.key, namespaceFromArg(newItem), newItem.key, currentItem.id, newItem.sumValue);
2215
+ }
2216
+ };
2217
+ var TableAggregate = class extends Aggregate {
2218
+ constructor(options) {
2219
+ super(options.name);
2220
+ this.options = options;
2221
+ }
2222
+ options;
2223
+ async insert(ctx, doc) {
2224
+ await this._insert(ctx, this.options.namespace?.(doc), this.options.sortKey(doc), doc._id, this.options.sumValue?.(doc));
2225
+ }
2226
+ async delete(ctx, doc) {
2227
+ await this._delete(ctx, this.options.namespace?.(doc), this.options.sortKey(doc), doc._id);
2228
+ }
2229
+ async replace(ctx, oldDoc, newDoc) {
2230
+ await this._replace(ctx, this.options.namespace?.(oldDoc), this.options.sortKey(oldDoc), this.options.namespace?.(newDoc), this.options.sortKey(newDoc), newDoc._id, this.options.sumValue?.(newDoc));
2231
+ }
2232
+ async insertIfDoesNotExist(ctx, doc) {
2233
+ await this._insertIfDoesNotExist(ctx, this.options.namespace?.(doc), this.options.sortKey(doc), doc._id, this.options.sumValue?.(doc));
2234
+ }
2235
+ async deleteIfExists(ctx, doc) {
2236
+ await this._deleteIfExists(ctx, this.options.namespace?.(doc), this.options.sortKey(doc), doc._id);
2237
+ }
2238
+ async replaceOrInsert(ctx, oldDoc, newDoc) {
2239
+ await this._replaceOrInsert(ctx, this.options.namespace?.(oldDoc), this.options.sortKey(oldDoc), this.options.namespace?.(newDoc), this.options.sortKey(newDoc), newDoc._id, this.options.sumValue?.(newDoc));
2240
+ }
2241
+ async indexOfDoc(ctx, doc, opts) {
2242
+ return this.indexOf(ctx, this.options.sortKey(doc), {
2243
+ namespace: this.options.namespace?.(doc),
2244
+ ...opts
2245
+ });
2246
+ }
2247
+ trigger() {
2248
+ return async (ctx, change) => {
2249
+ if (change.operation === "insert") await this.insert(ctx, change.newDoc);
2250
+ else if (change.operation === "update") await this.replace(ctx, change.oldDoc, change.newDoc);
2251
+ else if (change.operation === "delete") await this.delete(ctx, change.oldDoc);
2252
+ };
2253
+ }
2254
+ idempotentTrigger() {
2255
+ return async (ctx, change) => {
2256
+ if (change.operation === "insert") await this.insertIfDoesNotExist(ctx, change.newDoc);
2257
+ else if (change.operation === "update") await this.replaceOrInsert(ctx, change.oldDoc, change.newDoc);
2258
+ else if (change.operation === "delete") await this.deleteIfExists(ctx, change.oldDoc);
2259
+ };
2260
+ }
2261
+ };
2262
+ function btreeItemToAggregateItem({ k, s }) {
2263
+ const { key, id } = positionToKey(k);
2264
+ return {
2265
+ id,
2266
+ key,
2267
+ sumValue: s
2268
+ };
2269
+ }
2270
+ function namespaceFromArg(args) {
2271
+ if ("namespace" in args) return args.namespace;
2272
+ }
2273
+ function namespaceFromOpts(opts) {
2274
+ if (opts.length === 0) return;
2275
+ const [{ namespace }] = opts;
2276
+ return namespace;
2277
+ }
2278
+
2279
+ //#endregion
2280
+ export { entityKind as A, text as C, custom as D, id as E, json as O, vectorIndex as S, integer as T, aggregateIndex as _, deletion as a, searchIndex as b, EnableRLS as c, OrmSchemaOptions as d, RlsPolicies as f, rlsPolicy as g, RlsPolicy as h, convexTable as i, ConvexColumnBuilder as k, OrmContext as l, TableName as m, TableAggregate as n, Brand as o, TableDeleteConfig as p, aggregateStorageTables as r, Columns as s, DirectAggregate as t, OrmSchemaDefinition as u, index as v, createSystemFields as w, uniqueIndex as x, rankIndex as y };