defuss-db 1.1.3 → 2.0.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.
package/dist/index.cjs CHANGED
@@ -1,72 +1,908 @@
1
1
  'use strict';
2
2
 
3
+ class AggregationBuilder {
4
+ baseSource;
5
+ joins;
6
+ operations;
7
+ constructor(baseSource, joins = [], operations = []) {
8
+ this.baseSource = baseSource;
9
+ this.joins = joins;
10
+ this.operations = operations;
11
+ }
12
+ join(source, spec) {
13
+ assertUniqueAlias(this.getSourceAliases(), source.as);
14
+ return new AggregationBuilder(
15
+ this.baseSource,
16
+ [
17
+ ...this.joins,
18
+ {
19
+ source,
20
+ spec: {
21
+ type: spec.type ?? "left",
22
+ left: spec.left,
23
+ right: spec.right
24
+ }
25
+ }
26
+ ],
27
+ this.operations
28
+ );
29
+ }
30
+ project(mapping) {
31
+ return new AggregationBuilder(
32
+ this.baseSource,
33
+ this.joins,
34
+ [
35
+ ...this.operations,
36
+ {
37
+ kind: "project",
38
+ mapping
39
+ }
40
+ ]
41
+ );
42
+ }
43
+ alias(mapping) {
44
+ return new AggregationBuilder(
45
+ this.baseSource,
46
+ this.joins,
47
+ [
48
+ ...this.operations,
49
+ {
50
+ kind: "alias",
51
+ mapping
52
+ }
53
+ ]
54
+ );
55
+ }
56
+ compute(field, resolver) {
57
+ return new AggregationBuilder(
58
+ this.baseSource,
59
+ this.joins,
60
+ [
61
+ ...this.operations,
62
+ {
63
+ kind: "compute",
64
+ field,
65
+ resolver
66
+ }
67
+ ]
68
+ );
69
+ }
70
+ computeMany(mapping) {
71
+ return new AggregationBuilder(
72
+ this.baseSource,
73
+ this.joins,
74
+ [
75
+ ...this.operations,
76
+ {
77
+ kind: "computeMany",
78
+ mapping
79
+ }
80
+ ]
81
+ );
82
+ }
83
+ mapRows(mapper) {
84
+ return new AggregationBuilder(this.baseSource, this.joins, [
85
+ ...this.operations,
86
+ {
87
+ kind: "mapRows",
88
+ mapper
89
+ }
90
+ ]);
91
+ }
92
+ removeFields(paths) {
93
+ return new AggregationBuilder(this.baseSource, this.joins, [
94
+ ...this.operations,
95
+ {
96
+ kind: "removeFields",
97
+ paths
98
+ }
99
+ ]);
100
+ }
101
+ mergeConsecutive(merger) {
102
+ return new AggregationBuilder(this.baseSource, this.joins, [
103
+ ...this.operations,
104
+ {
105
+ kind: "mergeConsecutive",
106
+ merger
107
+ }
108
+ ]);
109
+ }
110
+ distinctBy(selector, options = {}) {
111
+ return new AggregationBuilder(this.baseSource, this.joins, [
112
+ ...this.operations,
113
+ {
114
+ kind: "distinctBy",
115
+ selector,
116
+ options
117
+ }
118
+ ]);
119
+ }
120
+ groupBy(keys, reducers) {
121
+ return new AggregationBuilder(this.baseSource, this.joins, [
122
+ ...this.operations,
123
+ {
124
+ kind: "groupBy",
125
+ keys,
126
+ reducers
127
+ }
128
+ ]);
129
+ }
130
+ sortBy(input) {
131
+ return new AggregationBuilder(this.baseSource, this.joins, [
132
+ ...this.operations,
133
+ isSortComparator(input) ? {
134
+ kind: "sortBy",
135
+ comparator: input
136
+ } : {
137
+ kind: "sortBy",
138
+ specs: normalizeSortSpecs(
139
+ input
140
+ )
141
+ }
142
+ ]);
143
+ }
144
+ async execute() {
145
+ const sources = await this.loadSourceRows();
146
+ let rows = sources[this.baseSource.as].map((row) => ({
147
+ [this.baseSource.as]: row
148
+ }));
149
+ for (const join of this.joins) {
150
+ rows = applyJoin(rows, sources[join.source.as], join);
151
+ }
152
+ for (const operation of this.operations) {
153
+ rows = await this.applyOperation(rows, sources, operation);
154
+ }
155
+ return rows;
156
+ }
157
+ getSourceAliases() {
158
+ return [this.baseSource.as, ...this.joins.map((join) => join.source.as)];
159
+ }
160
+ async loadSourceRows() {
161
+ const loadedEntries = await Promise.all(
162
+ [this.baseSource, ...this.joins.map((join) => join.source)].map(async (source) => [
163
+ source.as,
164
+ await loadSourceRows(source)
165
+ ])
166
+ );
167
+ return Object.fromEntries(loadedEntries);
168
+ }
169
+ async applyOperation(rows, sources, operation) {
170
+ switch (operation.kind) {
171
+ case "project":
172
+ return mapRowsSequentially(
173
+ rows,
174
+ sources,
175
+ this,
176
+ async (row, context) => resolveProjection(operation.mapping, row, context)
177
+ );
178
+ case "alias":
179
+ return mapRowsSequentially(rows, sources, this, async (row, context) => ({
180
+ ...row,
181
+ ...await resolveProjection(operation.mapping, row, context)
182
+ }));
183
+ case "compute":
184
+ return mapRowsSequentially(rows, sources, this, async (row, context) => ({
185
+ ...row,
186
+ [operation.field]: await resolveValue(operation.resolver, row, context)
187
+ }));
188
+ case "computeMany":
189
+ return mapRowsSequentially(rows, sources, this, async (row, context) => ({
190
+ ...row,
191
+ ...await resolveProjection(operation.mapping, row, context)
192
+ }));
193
+ case "mapRows":
194
+ return mapRowsSequentially(rows, sources, this, operation.mapper);
195
+ case "removeFields":
196
+ return mapRowsSequentially(rows, sources, this, async (row, context) => {
197
+ const paths = await resolveRemovePaths(operation.paths, row, context);
198
+ return removePathsFromRow(row, paths);
199
+ });
200
+ case "mergeConsecutive":
201
+ return mergeRowsSequentially(rows, sources, this, operation.merger);
202
+ case "distinctBy":
203
+ return distinctRows(rows, sources, this, operation.selector, operation.options);
204
+ case "groupBy":
205
+ return groupRows(rows, sources, this, operation.keys, operation.reducers);
206
+ case "sortBy":
207
+ return sortRows(rows, sources, this, operation);
208
+ }
209
+ }
210
+ }
211
+ function createAggregation(input, options) {
212
+ const baseSource = normalizeBaseSource(input, options);
213
+ assertUniqueAlias([], baseSource.as);
214
+ return new AggregationBuilder(
215
+ baseSource
216
+ );
217
+ }
218
+ function countRows() {
219
+ return (rows) => rows.length;
220
+ }
221
+ function sumBy(resolver) {
222
+ return async (rows, context) => {
223
+ let total = 0;
224
+ for (let index = 0; index < rows.length; index += 1) {
225
+ const value = await resolveValue(
226
+ resolver,
227
+ rows[index],
228
+ createRowContext(index, rows, context.sources, context.aggregation)
229
+ );
230
+ if (typeof value === "number") {
231
+ total += value;
232
+ }
233
+ }
234
+ return total;
235
+ };
236
+ }
237
+ function avgBy(resolver) {
238
+ return async (rows, context) => {
239
+ let total = 0;
240
+ let count = 0;
241
+ for (let index = 0; index < rows.length; index += 1) {
242
+ const value = await resolveValue(
243
+ resolver,
244
+ rows[index],
245
+ createRowContext(index, rows, context.sources, context.aggregation)
246
+ );
247
+ if (typeof value === "number") {
248
+ total += value;
249
+ count += 1;
250
+ }
251
+ }
252
+ return count === 0 ? 0 : total / count;
253
+ };
254
+ }
255
+ function minBy(resolver) {
256
+ return async (rows, context) => {
257
+ let minimum = void 0;
258
+ for (let index = 0; index < rows.length; index += 1) {
259
+ const value = await resolveValue(
260
+ resolver,
261
+ rows[index],
262
+ createRowContext(index, rows, context.sources, context.aggregation)
263
+ );
264
+ if (minimum === void 0 || compareSortValues(value, minimum, "asc") < 0) {
265
+ minimum = value;
266
+ }
267
+ }
268
+ return minimum;
269
+ };
270
+ }
271
+ function maxBy(resolver) {
272
+ return async (rows, context) => {
273
+ let maximum = void 0;
274
+ for (let index = 0; index < rows.length; index += 1) {
275
+ const value = await resolveValue(
276
+ resolver,
277
+ rows[index],
278
+ createRowContext(index, rows, context.sources, context.aggregation)
279
+ );
280
+ if (maximum === void 0 || compareSortValues(value, maximum, "desc") < 0) {
281
+ maximum = value;
282
+ }
283
+ }
284
+ return maximum;
285
+ };
286
+ }
287
+ function firstBy(resolver) {
288
+ return async (rows, context) => {
289
+ const row = rows[0];
290
+ if (!row) {
291
+ return void 0;
292
+ }
293
+ if (!resolver) {
294
+ return row;
295
+ }
296
+ return resolveValue(
297
+ resolver,
298
+ row,
299
+ createRowContext(0, rows, context.sources, context.aggregation)
300
+ );
301
+ };
302
+ }
303
+ function lastBy(resolver) {
304
+ return async (rows, context) => {
305
+ const index = rows.length - 1;
306
+ const row = rows[index];
307
+ if (!row) {
308
+ return void 0;
309
+ }
310
+ if (!resolver) {
311
+ return row;
312
+ }
313
+ return resolveValue(
314
+ resolver,
315
+ row,
316
+ createRowContext(index, rows, context.sources, context.aggregation)
317
+ );
318
+ };
319
+ }
320
+ const aggregationReducers = {
321
+ count: countRows,
322
+ sum: sumBy,
323
+ avg: avgBy,
324
+ min: minBy,
325
+ max: maxBy,
326
+ first: firstBy,
327
+ last: lastBy
328
+ };
329
+ function normalizeBaseSource(input, options) {
330
+ if (isAggregationSource(input)) {
331
+ return input;
332
+ }
333
+ if (isAggregationTable(input)) {
334
+ const table = input;
335
+ return {
336
+ table,
337
+ as: options?.as ?? "base",
338
+ where: options?.where
339
+ };
340
+ }
341
+ return {
342
+ rows: input,
343
+ as: options?.as ?? "base"
344
+ };
345
+ }
346
+ function isAggregationTable(value) {
347
+ return typeof value === "object" && value !== null && "find" in value && "definition" in value && typeof value.find === "function";
348
+ }
349
+ function isAggregationSource(value) {
350
+ return typeof value === "object" && value !== null && "as" in value && ("table" in value && isAggregationTable(value.table) || "rows" in value);
351
+ }
352
+ async function loadSourceRows(source) {
353
+ if ("table" in source) {
354
+ return source.table.find(source.where ?? {});
355
+ }
356
+ const loadedRows = typeof source.rows === "function" ? await source.rows() : await source.rows;
357
+ return [...loadedRows];
358
+ }
359
+ async function mapRowsSequentially(rows, sources, aggregation, mapper) {
360
+ const nextRows = [];
361
+ for (let index = 0; index < rows.length; index += 1) {
362
+ nextRows.push(
363
+ await mapper(rows[index], createRowContext(index, rows, sources, aggregation))
364
+ );
365
+ }
366
+ return nextRows;
367
+ }
368
+ async function resolveProjection(mapping, row, context) {
369
+ const projected = {};
370
+ for (const [field, resolver] of Object.entries(mapping)) {
371
+ projected[field] = await resolveValue(resolver, row, context);
372
+ }
373
+ return projected;
374
+ }
375
+ async function resolveValue(resolver, row, context) {
376
+ if (typeof resolver === "string") {
377
+ return getValueAtPath(row, resolver);
378
+ }
379
+ return resolver(row, context);
380
+ }
381
+ async function resolveRemovePaths(paths, row, context) {
382
+ if (Array.isArray(paths)) {
383
+ return paths;
384
+ }
385
+ return paths(row, context);
386
+ }
387
+ async function mergeRowsSequentially(rows, sources, aggregation, merger) {
388
+ const nextRows = [];
389
+ for (let index = 0; index < rows.length; index += 1) {
390
+ const currentRow = rows[index];
391
+ if (nextRows.length === 0) {
392
+ nextRows.push(currentRow);
393
+ continue;
394
+ }
395
+ const merged = await merger(nextRows[nextRows.length - 1], currentRow, {
396
+ index,
397
+ rows,
398
+ sources,
399
+ aggregation
400
+ });
401
+ if (merged === null || merged === void 0) {
402
+ nextRows.push(currentRow);
403
+ continue;
404
+ }
405
+ nextRows[nextRows.length - 1] = merged;
406
+ }
407
+ return nextRows;
408
+ }
409
+ async function distinctRows(rows, sources, aggregation, selector, options) {
410
+ const keep = options.keep ?? "first";
411
+ if (keep === "last") {
412
+ const lastSeen = /* @__PURE__ */ new Map();
413
+ const keys = [];
414
+ for (let index = 0; index < rows.length; index += 1) {
415
+ const key = await resolveDistinctKey(
416
+ selector,
417
+ rows[index],
418
+ createRowContext(index, rows, sources, aggregation)
419
+ );
420
+ keys.push(key);
421
+ lastSeen.set(key, index);
422
+ }
423
+ return rows.filter((_, index) => lastSeen.get(keys[index]) === index);
424
+ }
425
+ const nextRows = [];
426
+ const seen = /* @__PURE__ */ new Set();
427
+ for (let index = 0; index < rows.length; index += 1) {
428
+ const key = await resolveDistinctKey(
429
+ selector,
430
+ rows[index],
431
+ createRowContext(index, rows, sources, aggregation)
432
+ );
433
+ if (seen.has(key)) {
434
+ continue;
435
+ }
436
+ seen.add(key);
437
+ nextRows.push(rows[index]);
438
+ }
439
+ return nextRows;
440
+ }
441
+ async function groupRows(rows, sources, aggregation, keys, reducers) {
442
+ const groups = /* @__PURE__ */ new Map();
443
+ for (let index = 0; index < rows.length; index += 1) {
444
+ const row = rows[index];
445
+ const keyRow = await resolveGroupKeyRow(
446
+ keys,
447
+ row,
448
+ createRowContext(index, rows, sources, aggregation)
449
+ );
450
+ const serializedKey = await serializeKeyParts([keyRow]);
451
+ const existing = groups.get(serializedKey);
452
+ if (existing) {
453
+ existing.rows.push(row);
454
+ continue;
455
+ }
456
+ groups.set(serializedKey, {
457
+ key: keyRow,
458
+ rows: [row]
459
+ });
460
+ }
461
+ const nextRows = [];
462
+ for (const group of groups.values()) {
463
+ const groupedRow = { ...group.key };
464
+ const groupContext = {
465
+ key: group.key,
466
+ rows: group.rows,
467
+ sources,
468
+ aggregation
469
+ };
470
+ for (const [field, reducer] of Object.entries(reducers)) {
471
+ groupedRow[field] = await reducer(group.rows, groupContext);
472
+ }
473
+ nextRows.push(groupedRow);
474
+ }
475
+ return nextRows;
476
+ }
477
+ async function sortRows(rows, sources, aggregation, operation) {
478
+ if (operation.comparator) {
479
+ return stableSortAsync(
480
+ rows,
481
+ async (left, right) => operation.comparator(left, right, {
482
+ rows,
483
+ sources,
484
+ aggregation
485
+ })
486
+ );
487
+ }
488
+ const specs = operation.specs ?? [];
489
+ if (specs.length === 0) {
490
+ return [...rows];
491
+ }
492
+ const decorated = await Promise.all(
493
+ rows.map(async (row, index) => ({
494
+ row,
495
+ index,
496
+ keys: await Promise.all(
497
+ specs.map(
498
+ (spec) => resolveSortValue(spec, row, createRowContext(index, rows, sources, aggregation))
499
+ )
500
+ )
501
+ }))
502
+ );
503
+ decorated.sort((left, right) => {
504
+ for (let index = 0; index < specs.length; index += 1) {
505
+ const compared = compareSortValues(
506
+ left.keys[index],
507
+ right.keys[index],
508
+ specs[index].direction ?? "asc"
509
+ );
510
+ if (compared !== 0) {
511
+ return compared;
512
+ }
513
+ }
514
+ return left.index - right.index;
515
+ });
516
+ return decorated.map((entry) => entry.row);
517
+ }
518
+ function applyJoin(currentRows, joinedRows, join) {
519
+ if (join.spec.type === "right") {
520
+ return applyRightJoin(currentRows, joinedRows, join);
521
+ }
522
+ const nextRows = [];
523
+ for (const currentRow of currentRows) {
524
+ const matches = joinedRows.filter(
525
+ (joinedRow) => valuesEqual(
526
+ getValueAtPath(currentRow, join.spec.left),
527
+ getValueAtPath(joinedRow, join.spec.right)
528
+ )
529
+ );
530
+ if (matches.length === 0) {
531
+ if (join.spec.type === "left") {
532
+ nextRows.push({
533
+ ...currentRow,
534
+ [join.source.as]: null
535
+ });
536
+ }
537
+ continue;
538
+ }
539
+ for (const match of matches) {
540
+ nextRows.push({
541
+ ...currentRow,
542
+ [join.source.as]: match
543
+ });
544
+ }
545
+ }
546
+ return nextRows;
547
+ }
548
+ function applyRightJoin(currentRows, joinedRows, join) {
549
+ const nextRows = [];
550
+ const currentRowTemplate = currentRows[0];
551
+ for (const joinedRow of joinedRows) {
552
+ const matches = currentRows.filter(
553
+ (currentRow) => valuesEqual(
554
+ getValueAtPath(currentRow, join.spec.left),
555
+ getValueAtPath(joinedRow, join.spec.right)
556
+ )
557
+ );
558
+ if (matches.length === 0) {
559
+ nextRows.push({
560
+ ...createNullRow(currentRowTemplate),
561
+ [join.source.as]: joinedRow
562
+ });
563
+ continue;
564
+ }
565
+ for (const match of matches) {
566
+ nextRows.push({
567
+ ...match,
568
+ [join.source.as]: joinedRow
569
+ });
570
+ }
571
+ }
572
+ return nextRows;
573
+ }
574
+ function createNullRow(row) {
575
+ if (!row) {
576
+ return {};
577
+ }
578
+ const nextRow = {};
579
+ for (const key of Object.keys(row)) {
580
+ nextRow[key] = null;
581
+ }
582
+ return nextRow;
583
+ }
584
+ function removePathsFromRow(row, paths) {
585
+ let nextRow = row;
586
+ for (const path of paths) {
587
+ nextRow = removePath(nextRow, path);
588
+ }
589
+ return nextRow;
590
+ }
591
+ function removePath(row, path) {
592
+ const segments = path.split(".").filter(Boolean);
593
+ if (segments.length === 0) {
594
+ return row;
595
+ }
596
+ const nextRow = cloneContainer(row);
597
+ let sourceCursor = row;
598
+ let targetCursor = nextRow;
599
+ for (let index = 0; index < segments.length - 1; index += 1) {
600
+ if (sourceCursor === null || sourceCursor === void 0 || typeof sourceCursor !== "object") {
601
+ return nextRow;
602
+ }
603
+ const segment = segments[index];
604
+ const sourceValue = sourceCursor[segment];
605
+ if (sourceValue === null || sourceValue === void 0 || typeof sourceValue !== "object") {
606
+ return nextRow;
607
+ }
608
+ targetCursor[segment] = cloneContainer(sourceValue);
609
+ targetCursor = targetCursor[segment];
610
+ sourceCursor = sourceValue;
611
+ }
612
+ delete targetCursor[segments[segments.length - 1]];
613
+ return nextRow;
614
+ }
615
+ function getValueAtPath(target, path) {
616
+ if (!path) {
617
+ return void 0;
618
+ }
619
+ let current = target;
620
+ for (const segment of path.split(".").filter(Boolean)) {
621
+ if (current === null) {
622
+ return null;
623
+ }
624
+ if (current === void 0 || typeof current !== "object") {
625
+ return void 0;
626
+ }
627
+ current = current[segment];
628
+ }
629
+ return current;
630
+ }
631
+ async function resolveDistinctKey(selector, row, context) {
632
+ if (typeof selector === "string") {
633
+ return serializeKeyParts([getValueAtPath(row, selector)]);
634
+ }
635
+ if (Array.isArray(selector)) {
636
+ return serializeKeyParts(selector.map((path) => getValueAtPath(row, path)));
637
+ }
638
+ const resolved = await selector(row, context);
639
+ return serializeKeyParts(Array.isArray(resolved) ? resolved : [resolved]);
640
+ }
641
+ async function resolveGroupKeyRow(keys, row, context) {
642
+ if (typeof keys === "string") {
643
+ return {
644
+ [keys]: getValueAtPath(row, keys)
645
+ };
646
+ }
647
+ if (Array.isArray(keys)) {
648
+ const keyRow = {};
649
+ for (const key of keys) {
650
+ keyRow[key] = getValueAtPath(row, key);
651
+ }
652
+ return keyRow;
653
+ }
654
+ return resolveProjection(keys, row, context);
655
+ }
656
+ async function resolveSortValue(spec, row, context) {
657
+ if (isFieldSortSpec(spec)) {
658
+ return getValueAtPath(row, spec.field);
659
+ }
660
+ return resolveValue(spec.by, row, context);
661
+ }
662
+ function isFieldSortSpec(spec) {
663
+ return "field" in spec;
664
+ }
665
+ function isSortComparator(value) {
666
+ return typeof value === "function";
667
+ }
668
+ function normalizeSortSpecs(input) {
669
+ if (Array.isArray(input)) {
670
+ return [...input];
671
+ }
672
+ return [input];
673
+ }
674
+ async function stableSortAsync(rows, comparator) {
675
+ if (rows.length <= 1) {
676
+ return [...rows];
677
+ }
678
+ const midpoint = Math.floor(rows.length / 2);
679
+ const leftRows = await stableSortAsync(rows.slice(0, midpoint), comparator);
680
+ const rightRows = await stableSortAsync(rows.slice(midpoint), comparator);
681
+ return mergeSortedRows(leftRows, rightRows, comparator);
682
+ }
683
+ async function mergeSortedRows(leftRows, rightRows, comparator) {
684
+ const merged = [];
685
+ let leftIndex = 0;
686
+ let rightIndex = 0;
687
+ while (leftIndex < leftRows.length && rightIndex < rightRows.length) {
688
+ if (await comparator(leftRows[leftIndex], rightRows[rightIndex]) <= 0) {
689
+ merged.push(leftRows[leftIndex]);
690
+ leftIndex += 1;
691
+ continue;
692
+ }
693
+ merged.push(rightRows[rightIndex]);
694
+ rightIndex += 1;
695
+ }
696
+ return [...merged, ...leftRows.slice(leftIndex), ...rightRows.slice(rightIndex)];
697
+ }
698
+ function compareSortValues(left, right, direction) {
699
+ const factor = direction === "desc" ? -1 : 1;
700
+ if (left === right) {
701
+ return 0;
702
+ }
703
+ if (left === null || left === void 0) {
704
+ return 1 * factor;
705
+ }
706
+ if (right === null || right === void 0) {
707
+ return -1 * factor;
708
+ }
709
+ if (left instanceof Date && right instanceof Date) {
710
+ return comparePrimitiveValues(left.getTime(), right.getTime()) * factor;
711
+ }
712
+ if (typeof left === "number" && typeof right === "number") {
713
+ return comparePrimitiveValues(left, right) * factor;
714
+ }
715
+ if (typeof left === "bigint" && typeof right === "bigint") {
716
+ return comparePrimitiveValues(left, right) * factor;
717
+ }
718
+ if (typeof left === "boolean" && typeof right === "boolean") {
719
+ return comparePrimitiveValues(Number(left), Number(right)) * factor;
720
+ }
721
+ return String(left).localeCompare(String(right)) * factor;
722
+ }
723
+ function comparePrimitiveValues(left, right) {
724
+ if (left < right) {
725
+ return -1;
726
+ }
727
+ if (left > right) {
728
+ return 1;
729
+ }
730
+ return 0;
731
+ }
732
+ async function serializeKeyParts(parts) {
733
+ const normalized = await Promise.all(parts.map((part) => normalizeKeyPart(part)));
734
+ return JSON.stringify(normalized);
735
+ }
736
+ async function normalizeKeyPart(value) {
737
+ if (value instanceof Date) {
738
+ return {
739
+ __defussType: "date",
740
+ value: value.toISOString()
741
+ };
742
+ }
743
+ if (typeof value === "bigint") {
744
+ return {
745
+ __defussType: "bigint",
746
+ value: String(value)
747
+ };
748
+ }
749
+ if (value instanceof ArrayBuffer) {
750
+ return {
751
+ __defussType: "arraybuffer",
752
+ value: Array.from(new Uint8Array(value))
753
+ };
754
+ }
755
+ if (isBlobLike(value)) {
756
+ return {
757
+ __defussType: "blob",
758
+ type: value.type,
759
+ value: Array.from(new Uint8Array(await value.arrayBuffer()))
760
+ };
761
+ }
762
+ if (Array.isArray(value)) {
763
+ return Promise.all(value.map((item) => normalizeKeyPart(item)));
764
+ }
765
+ if (typeof value === "object" && value !== null) {
766
+ const entries = await Promise.all(
767
+ Object.entries(value).sort(([left], [right]) => left.localeCompare(right)).map(async ([key, nestedValue]) => [key, await normalizeKeyPart(nestedValue)])
768
+ );
769
+ return Object.fromEntries(entries);
770
+ }
771
+ return value;
772
+ }
773
+ function valuesEqual(left, right) {
774
+ if (left instanceof Date && right instanceof Date) {
775
+ return left.getTime() === right.getTime();
776
+ }
777
+ if (left instanceof ArrayBuffer && right instanceof ArrayBuffer) {
778
+ if (left.byteLength !== right.byteLength) {
779
+ return false;
780
+ }
781
+ const leftView = new Uint8Array(left);
782
+ const rightView = new Uint8Array(right);
783
+ for (let index = 0; index < leftView.length; index += 1) {
784
+ if (leftView[index] !== rightView[index]) {
785
+ return false;
786
+ }
787
+ }
788
+ return true;
789
+ }
790
+ return left === right;
791
+ }
792
+ function createRowContext(index, rows, sources, aggregation) {
793
+ return {
794
+ index,
795
+ rows,
796
+ sources,
797
+ aggregation
798
+ };
799
+ }
800
+ function cloneContainer(value) {
801
+ if (Array.isArray(value)) {
802
+ return [...value];
803
+ }
804
+ return { ...value };
805
+ }
806
+ function isBlobLike(value) {
807
+ return typeof value === "object" && value !== null && typeof value.arrayBuffer === "function" && typeof value.slice === "function" && typeof value.type === "string";
808
+ }
809
+ function assertUniqueAlias(existingAliases, alias) {
810
+ if (!alias.trim()) {
811
+ throw new Error("defuss-db aggregation: source aliases must be non-empty.");
812
+ }
813
+ if (existingAliases.includes(alias)) {
814
+ throw new Error(`defuss-db aggregation: source alias '${alias}' is already in use.`);
815
+ }
816
+ }
817
+
3
818
  class DefussTable {
4
819
  provider;
5
- tableName;
820
+ definition;
6
821
  /**
7
- * Initializes the DefussTable with the specified table name and provider.
822
+ * Initializes the DefussTable with the specified table definition and provider.
8
823
  * @param provider - The DefussProvider instance.
9
- * @param tableName - The name of the table.
824
+ * @param definition - The table definition.
10
825
  */
11
- constructor(provider, tableName) {
826
+ constructor(provider, definition) {
12
827
  this.provider = provider;
13
- this.tableName = tableName;
828
+ this.definition = definition;
14
829
  }
15
830
  /**
16
831
  * Creates the table if it doesn't exist.
17
832
  */
18
833
  async init() {
19
- await this.provider.createTable(this.tableName);
834
+ await this.provider.ensureTable(this.definition);
20
835
  }
21
836
  /**
22
- * Inserts an item into the table with dynamic indices.
837
+ * Inserts an item into the table.
23
838
  * @param value - The item to insert.
24
- * @param indexData - A JSON object representing dynamic indices.
25
839
  * @returns The primary key of the inserted row.
26
840
  */
27
- async insert(value, indexData) {
28
- return this.provider.insert(this.tableName, value, indexData);
841
+ async insert(value) {
842
+ return this.provider.insert(this.definition, value);
29
843
  }
30
844
  /**
31
- * Finds items based on provided index data.
32
- * @param indexData - A JSON object representing dynamic indices. All fields are optional.
845
+ * Finds items based on the provided selector.
846
+ * @param selector - A selector over real value fields. All fields are optional.
33
847
  * @returns An array of matching items.
34
848
  */
35
- async find(indexData = {}) {
36
- return this.provider.find(this.tableName, indexData);
849
+ async find(selector = {}) {
850
+ return this.provider.find(this.definition, selector);
37
851
  }
38
852
  /**
39
- * Finds a single item based on provided index data.
40
- * @param indexData - A JSON object representing dynamic indices. All fields are optional.
853
+ * Finds a single item based on the provided selector.
854
+ * @param selector - A selector over real value fields. All fields are optional.
41
855
  * @returns The first matching item or null if not found.
42
856
  */
43
- async findOne(indexData = {}) {
44
- return this.provider.findOne(this.tableName, indexData);
857
+ async findOne(selector = {}) {
858
+ return this.provider.findOne(this.definition, selector);
45
859
  }
46
860
  /**
47
- * Updates items based on provided index data.
48
- * @param indexData - A JSON object representing dynamic indices. All fields are optional.
861
+ * Updates items based on the provided selector.
862
+ * @param selector - A selector over real value fields.
49
863
  * @param dataToUpdate - A JSON object representing fields to update.
50
864
  */
51
- async update(indexData, dataToUpdate) {
52
- await this.provider.update(this.tableName, indexData, dataToUpdate);
865
+ async update(selector, dataToUpdate) {
866
+ await this.provider.update(this.definition, selector, dataToUpdate);
53
867
  }
54
868
  /**
55
- * Deletes items based on provided index data.
56
- * @param indexData - A JSON object representing dynamic indices. All fields are optional.
869
+ * Deletes items based on the provided selector.
870
+ * @param selector - A selector over real value fields.
57
871
  */
58
- async delete(indexData) {
59
- await this.provider.delete(this.tableName, indexData);
872
+ async delete(selector) {
873
+ await this.provider.delete(this.definition, selector);
60
874
  }
61
875
  /**
62
- * Upserts an item into the table based on index data.
876
+ * Upserts an item into the table based on the provided selector.
877
+ * @param selector - A non-empty selector resolving to `id` or a declared unique index.
63
878
  * @param value - The item to insert or update.
64
- * @param indexData - A JSON object representing dynamic indices used to identify the record.
65
879
  * @returns The primary key of the upserted row.
66
880
  */
67
- async upsert(value, indexData) {
68
- return this.provider.upsert(this.tableName, value, indexData);
881
+ async upsert(selector, value) {
882
+ return this.provider.upsert(this.definition, selector, value);
69
883
  }
884
+ /**
885
+ * Starts a provider-agnostic aggregation pipeline rooted in this table.
886
+ * Any `where` selector is applied before rows enter the aggregation layer.
887
+ */
888
+ aggregate(options) {
889
+ return createAggregation(this, options);
890
+ }
891
+ }
892
+
893
+ function defineTable(definition) {
894
+ return definition;
70
895
  }
71
896
 
897
+ exports.AggregationBuilder = AggregationBuilder;
72
898
  exports.DefussTable = DefussTable;
899
+ exports.aggregationReducers = aggregationReducers;
900
+ exports.avgBy = avgBy;
901
+ exports.countRows = countRows;
902
+ exports.createAggregation = createAggregation;
903
+ exports.defineTable = defineTable;
904
+ exports.firstBy = firstBy;
905
+ exports.lastBy = lastBy;
906
+ exports.maxBy = maxBy;
907
+ exports.minBy = minBy;
908
+ exports.sumBy = sumBy;