@noy-db/hub 0.2.0-pre.30 → 0.2.0-pre.31

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 (143) hide show
  1. package/dist/adapter/index.d.ts +9 -0
  2. package/dist/adapter/index.js +14 -0
  3. package/dist/attestation/index.d.ts +1 -1
  4. package/dist/attestation/index.js +3 -3
  5. package/dist/blobs/index.d.ts +3 -3
  6. package/dist/bundle/index.d.ts +3 -3
  7. package/dist/bundle/index.js +1 -1
  8. package/dist/{chunk-Y6YUWZTS.js → chunk-L5HHBOMS.js} +2 -2
  9. package/dist/{chunk-BVKLJBJJ.js → chunk-W5NVNJDX.js} +2 -1
  10. package/dist/{chunk-BVKLJBJJ.js.map → chunk-W5NVNJDX.js.map} +1 -1
  11. package/dist/consent/index.d.ts +2 -2
  12. package/dist/{decrypt-partition-Mhjh6nnG.d.ts → decrypt-partition-CXS5KopB.d.ts} +1 -1
  13. package/dist/derivations/index.d.ts +3 -3
  14. package/dist/{dev-unlock-DJ3IhgY9.d.ts → dev-unlock-CnHTTVea.d.ts} +1 -1
  15. package/dist/guards/index.d.ts +3 -3
  16. package/dist/{hash-DLwkYf1d.d.ts → hash-oc5paYl0.d.ts} +1 -1
  17. package/dist/history/index.d.ts +3 -3
  18. package/dist/i18n/index.d.ts +2 -2
  19. package/dist/{index-CMRIx_zx.d.ts → index-BmhGztUi.d.ts} +1 -1
  20. package/dist/index.d.ts +11 -11
  21. package/dist/index.js +2 -2
  22. package/dist/kernel/index.d.ts +2 -2
  23. package/dist/materialized-views/index.d.ts +3 -3
  24. package/dist/{mime-magic-CacDBwYp.d.ts → mime-magic-JeLKHRng.d.ts} +1 -1
  25. package/dist/{noydb-5MIBD77B.js → noydb-NAU2DTFP.js} +2 -2
  26. package/dist/noydb-NAU2DTFP.js.map +1 -0
  27. package/dist/overlay-views/index.d.ts +3 -3
  28. package/dist/periods/index.d.ts +2 -2
  29. package/dist/session/index.d.ts +3 -3
  30. package/dist/shadow/index.d.ts +2 -2
  31. package/dist/snapshots/index.d.ts +2 -2
  32. package/dist/store/index.d.ts +2 -2
  33. package/dist/sync/index.d.ts +1 -1
  34. package/dist/team/index.d.ts +2 -2
  35. package/dist/{transition-guard-J04-jime.d.ts → transition-guard-Dy3NioQr.d.ts} +1 -1
  36. package/dist/tx/index.d.ts +2 -2
  37. package/dist/{with-materialized-view-DNfzC5lH.d.ts → with-materialized-view-DIVeez0W.d.ts} +1 -1
  38. package/dist/{with-overlayed-view-qk3lbhOd.d.ts → with-overlayed-view-DVZrc5Hb.d.ts} +1 -1
  39. package/dist/{with-rollup-Dd3_ZG4b.d.ts → with-rollup-CbU-O4wP.d.ts} +1 -1
  40. package/package.json +62 -221
  41. package/dist/aggregate/index.cjs +0 -1144
  42. package/dist/aggregate/index.cjs.map +0 -1
  43. package/dist/aggregate/index.d.cts +0 -39
  44. package/dist/attestation/index.cjs +0 -305
  45. package/dist/attestation/index.cjs.map +0 -1
  46. package/dist/attestation/index.d.cts +0 -54
  47. package/dist/blobs/index.cjs +0 -1967
  48. package/dist/blobs/index.cjs.map +0 -1
  49. package/dist/blobs/index.d.cts +0 -48
  50. package/dist/bundle/index.cjs +0 -41045
  51. package/dist/bundle/index.cjs.map +0 -1
  52. package/dist/bundle/index.d.cts +0 -187
  53. package/dist/consent/index.cjs +0 -204
  54. package/dist/consent/index.cjs.map +0 -1
  55. package/dist/consent/index.d.cts +0 -27
  56. package/dist/crdt/index.cjs +0 -152
  57. package/dist/crdt/index.cjs.map +0 -1
  58. package/dist/crdt/index.d.cts +0 -30
  59. package/dist/decrypt-partition-C0iDpbSd.d.cts +0 -558
  60. package/dist/derivations/index.cjs +0 -469
  61. package/dist/derivations/index.cjs.map +0 -1
  62. package/dist/derivations/index.d.cts +0 -74
  63. package/dist/dev-unlock-0Z6yxfS7.d.cts +0 -263
  64. package/dist/discriminant-BN9REW3o.d.cts +0 -60
  65. package/dist/errors-BAWO5Z5a.d.cts +0 -1500
  66. package/dist/forget/index.cjs +0 -43
  67. package/dist/forget/index.cjs.map +0 -1
  68. package/dist/forget/index.d.cts +0 -1
  69. package/dist/guards/index.cjs +0 -455
  70. package/dist/guards/index.cjs.map +0 -1
  71. package/dist/guards/index.d.cts +0 -39
  72. package/dist/hash-Db8ncXGr.d.cts +0 -63
  73. package/dist/history/index.cjs +0 -1245
  74. package/dist/history/index.cjs.map +0 -1
  75. package/dist/history/index.d.cts +0 -65
  76. package/dist/i18n/index.cjs +0 -1280
  77. package/dist/i18n/index.cjs.map +0 -1
  78. package/dist/i18n/index.d.cts +0 -41
  79. package/dist/index-BMmajblo.d.cts +0 -362
  80. package/dist/index-C1SC1EPe.d.cts +0 -1325
  81. package/dist/index-xJEPkvMb.d.cts +0 -93
  82. package/dist/index.cjs +0 -48100
  83. package/dist/index.cjs.map +0 -1
  84. package/dist/index.d.cts +0 -1050
  85. package/dist/indexing/index.cjs +0 -803
  86. package/dist/indexing/index.cjs.map +0 -1
  87. package/dist/indexing/index.d.cts +0 -36
  88. package/dist/kernel/index.cjs +0 -751
  89. package/dist/kernel/index.cjs.map +0 -1
  90. package/dist/kernel/index.d.cts +0 -11
  91. package/dist/lazy-builder-eYZzLEL1.d.cts +0 -304
  92. package/dist/materialized-views/index.cjs +0 -1518
  93. package/dist/materialized-views/index.cjs.map +0 -1
  94. package/dist/materialized-views/index.d.cts +0 -187
  95. package/dist/mime-magic-sdMzsfVK.d.cts +0 -103
  96. package/dist/overlay-views/index.cjs +0 -399
  97. package/dist/overlay-views/index.cjs.map +0 -1
  98. package/dist/overlay-views/index.d.cts +0 -102
  99. package/dist/periods/index.cjs +0 -1041
  100. package/dist/periods/index.cjs.map +0 -1
  101. package/dist/periods/index.d.cts +0 -24
  102. package/dist/predicate-BmhBSPCH.d.cts +0 -267
  103. package/dist/query/index.cjs +0 -3480
  104. package/dist/query/index.cjs.map +0 -1
  105. package/dist/query/index.d.cts +0 -4
  106. package/dist/sealed-record/index.cjs +0 -139
  107. package/dist/sealed-record/index.cjs.map +0 -1
  108. package/dist/sealed-record/index.d.cts +0 -123
  109. package/dist/session/index.cjs +0 -495
  110. package/dist/session/index.cjs.map +0 -1
  111. package/dist/session/index.d.cts +0 -48
  112. package/dist/shadow/index.cjs +0 -133
  113. package/dist/shadow/index.cjs.map +0 -1
  114. package/dist/shadow/index.d.cts +0 -19
  115. package/dist/snapshots/index.cjs +0 -937
  116. package/dist/snapshots/index.cjs.map +0 -1
  117. package/dist/snapshots/index.d.cts +0 -30
  118. package/dist/store/index.cjs +0 -1091
  119. package/dist/store/index.cjs.map +0 -1
  120. package/dist/store/index.d.cts +0 -501
  121. package/dist/strategy-BSxFXGzb.d.cts +0 -110
  122. package/dist/strategy-mJExw4LQ.d.cts +0 -1069
  123. package/dist/sync/index.cjs +0 -1062
  124. package/dist/sync/index.cjs.map +0 -1
  125. package/dist/sync/index.d.cts +0 -45
  126. package/dist/team/index.cjs +0 -2805
  127. package/dist/team/index.cjs.map +0 -1
  128. package/dist/team/index.d.cts +0 -120
  129. package/dist/transition-guard-tWZIsaXe.d.cts +0 -165
  130. package/dist/tx/index.cjs +0 -614
  131. package/dist/tx/index.cjs.map +0 -1
  132. package/dist/tx/index.d.cts +0 -39
  133. package/dist/types-CdVfiQgt.d.cts +0 -15275
  134. package/dist/ulid-DRH25k3y.d.cts +0 -66
  135. package/dist/util/index.cjs +0 -237
  136. package/dist/util/index.cjs.map +0 -1
  137. package/dist/util/index.d.cts +0 -79
  138. package/dist/with-materialized-view-DfgPcvi9.d.cts +0 -27
  139. package/dist/with-overlayed-view-Cvfkx1lg.d.cts +0 -13
  140. package/dist/with-rollup-nIxo7h9z.d.cts +0 -47
  141. /package/dist/{noydb-5MIBD77B.js.map → adapter/index.js.map} +0 -0
  142. /package/dist/{chunk-Y6YUWZTS.js.map → chunk-L5HHBOMS.js.map} +0 -0
  143. /package/dist/{types-DHn9lEP0.d.ts → index-DHn9lEP0.d.ts} +0 -0
@@ -1,803 +0,0 @@
1
- "use strict";
2
- var __defProp = Object.defineProperty;
3
- var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
4
- var __getOwnPropNames = Object.getOwnPropertyNames;
5
- var __hasOwnProp = Object.prototype.hasOwnProperty;
6
- var __export = (target, all) => {
7
- for (var name in all)
8
- __defProp(target, name, { get: all[name], enumerable: true });
9
- };
10
- var __copyProps = (to, from, except, desc) => {
11
- if (from && typeof from === "object" || typeof from === "function") {
12
- for (let key of __getOwnPropNames(from))
13
- if (!__hasOwnProp.call(to, key) && key !== except)
14
- __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
15
- }
16
- return to;
17
- };
18
- var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
19
-
20
- // src/indexing/index.ts
21
- var indexing_exports = {};
22
- __export(indexing_exports, {
23
- COMPOSITE_DELIMITER: () => COMPOSITE_DELIMITER,
24
- CollectionIndexes: () => CollectionIndexes,
25
- IDX_PREFIX: () => IDX_PREFIX,
26
- LazyQuery: () => LazyQuery,
27
- PersistedCollectionIndex: () => PersistedCollectionIndex,
28
- compositeKey: () => compositeKey,
29
- decodeIdxId: () => decodeIdxId,
30
- encodeIdxId: () => encodeIdxId,
31
- isIdxId: () => isIdxId,
32
- withIndexing: () => withIndexing
33
- });
34
- module.exports = __toCommonJS(indexing_exports);
35
-
36
- // src/errors.ts
37
- var NoydbError = class extends Error {
38
- /** Machine-readable error code. Stable across library versions. */
39
- code;
40
- constructor(code, message) {
41
- super(message);
42
- this.name = "NoydbError";
43
- this.code = code;
44
- }
45
- };
46
- var IndexRequiredError = class extends NoydbError {
47
- collection;
48
- touchedFields;
49
- missingFields;
50
- constructor(args) {
51
- super(
52
- "INDEX_REQUIRED",
53
- `Collection "${args.collection}": query references unindexed fields in lazy mode (missing: ${args.missingFields.join(", ")}). Declare an index on each field, or use collection.scan() for non-indexed iteration.`
54
- );
55
- this.name = "IndexRequiredError";
56
- this.collection = args.collection;
57
- this.touchedFields = [...args.touchedFields];
58
- this.missingFields = [...args.missingFields];
59
- }
60
- };
61
-
62
- // src/money/where.ts
63
- function isMoneyValueObject(v) {
64
- return typeof v === "object" && v !== null && "currency" in v;
65
- }
66
- function readStored(actual, operand) {
67
- let amount;
68
- let currency;
69
- if (operand.mode === "fixed") {
70
- if (typeof actual !== "string" && typeof actual !== "number") return null;
71
- amount = actual;
72
- currency = operand.entries[0]?.currency ?? "";
73
- } else {
74
- if (!isMoneyValueObject(actual)) return null;
75
- if (typeof actual.currency !== "string") return null;
76
- amount = actual.amount;
77
- currency = actual.currency;
78
- }
79
- if (typeof amount !== "string" && typeof amount !== "number") return null;
80
- try {
81
- return { scaled: BigInt(amount).toString(), currency };
82
- } catch {
83
- return null;
84
- }
85
- }
86
- function evaluateMoneyClause(actual, op, operand) {
87
- const stored = readStored(actual, operand);
88
- if (stored === null) return op === "!=";
89
- const a = BigInt(stored.scaled);
90
- if (op === "in") {
91
- return operand.entries.some(
92
- (e2) => e2.currency === stored.currency && BigInt(e2.scaled) === a
93
- );
94
- }
95
- if (op === "between") {
96
- const [lo, hi] = operand.entries;
97
- if (!lo || !hi || lo.currency !== stored.currency) return false;
98
- return a >= BigInt(lo.scaled) && a <= BigInt(hi.scaled);
99
- }
100
- const e = operand.entries[0];
101
- if (!e) return false;
102
- if (e.currency !== stored.currency) return op === "!=";
103
- const b = BigInt(e.scaled);
104
- switch (op) {
105
- case "==":
106
- return a === b;
107
- case "!=":
108
- return a !== b;
109
- case "<":
110
- return a < b;
111
- case "<=":
112
- return a <= b;
113
- case ">":
114
- return a > b;
115
- case ">=":
116
- return a >= b;
117
- default:
118
- return false;
119
- }
120
- }
121
-
122
- // src/query/predicate.ts
123
- function readPath(record, path) {
124
- if (record === null || record === void 0) return void 0;
125
- if (!path.includes(".")) {
126
- return record[path];
127
- }
128
- const segments = path.split(".");
129
- let cursor = record;
130
- for (const segment of segments) {
131
- if (cursor === null || cursor === void 0) return void 0;
132
- cursor = cursor[segment];
133
- }
134
- return cursor;
135
- }
136
- function evaluateFieldClause(record, clause) {
137
- const actual = readPath(record, clause.field);
138
- const { op, value } = clause;
139
- if (clause.money) return evaluateMoneyClause(actual, op, clause.money);
140
- switch (op) {
141
- case "==":
142
- return actual === value;
143
- case "!=":
144
- return actual !== value;
145
- case "<":
146
- return isComparable(actual, value) && actual < value;
147
- case "<=":
148
- return isComparable(actual, value) && actual <= value;
149
- case ">":
150
- return isComparable(actual, value) && actual > value;
151
- case ">=":
152
- return isComparable(actual, value) && actual >= value;
153
- case "in":
154
- return Array.isArray(value) && value.includes(actual);
155
- case "contains":
156
- if (typeof actual === "string") return typeof value === "string" && actual.includes(value);
157
- if (Array.isArray(actual)) return actual.includes(value);
158
- return false;
159
- case "startsWith":
160
- return typeof actual === "string" && typeof value === "string" && actual.startsWith(value);
161
- case "between": {
162
- if (!Array.isArray(value) || value.length !== 2) return false;
163
- const [lo, hi] = value;
164
- if (!isComparable(actual, lo) || !isComparable(actual, hi)) return false;
165
- return actual >= lo && actual <= hi;
166
- }
167
- default: {
168
- const _exhaustive = op;
169
- void _exhaustive;
170
- return false;
171
- }
172
- }
173
- }
174
- function isComparable(a, b) {
175
- if (typeof a === "number" && typeof b === "number") return true;
176
- if (typeof a === "string" && typeof b === "string") return true;
177
- if (a instanceof Date && b instanceof Date) return true;
178
- return false;
179
- }
180
- function evaluateClause(record, clause, fnRecord) {
181
- switch (clause.type) {
182
- case "field":
183
- return evaluateFieldClause(record, clause);
184
- case "filter":
185
- return clause.fn(fnRecord !== void 0 ? fnRecord : record);
186
- case "wherePredicate":
187
- return clause.fn(fnRecord !== void 0 ? fnRecord : record, clause.ctx);
188
- case "crossJoin":
189
- throw new Error(
190
- `evaluateClause: 'crossJoin' clauses are expansion primitives and are not evaluated per-record. This is a query planner routing error \u2014 crossJoin clauses must be extracted from the clause list before calling evaluateClause or filterRecords.`
191
- );
192
- case "group":
193
- if (clause.op === "and") {
194
- for (const child of clause.clauses) {
195
- if (!evaluateClause(record, child, fnRecord)) return false;
196
- }
197
- return true;
198
- } else {
199
- for (const child of clause.clauses) {
200
- if (evaluateClause(record, child, fnRecord)) return true;
201
- }
202
- return false;
203
- }
204
- }
205
- }
206
-
207
- // src/indexing/eager-indexes.ts
208
- var CollectionIndexes = class {
209
- indexes = /* @__PURE__ */ new Map();
210
- /**
211
- * Declare an index. Subsequent record additions are tracked under it.
212
- * Calling this twice for the same field is a no-op (idempotent).
213
- */
214
- declare(field) {
215
- if (this.indexes.has(field)) return;
216
- this.indexes.set(field, { field, buckets: /* @__PURE__ */ new Map() });
217
- }
218
- /** True if the given field has a declared index. */
219
- has(field) {
220
- return this.indexes.has(field);
221
- }
222
- /** All declared field names, in declaration order. */
223
- fields() {
224
- return [...this.indexes.keys()];
225
- }
226
- /**
227
- * Build all declared indexes from a snapshot of records.
228
- * Called once per hydration. O(N × indexes.size).
229
- */
230
- build(records) {
231
- for (const idx of this.indexes.values()) {
232
- idx.buckets.clear();
233
- for (const { id, record } of records) {
234
- addToIndex(idx, id, record);
235
- }
236
- }
237
- }
238
- /**
239
- * Insert or update a single record across all indexes.
240
- * Called by `Collection.put()` after the encrypted write succeeds.
241
- *
242
- * If `previousRecord` is provided, the record is removed from any old
243
- * buckets first — this is the update path. Pass `null` for fresh adds.
244
- */
245
- upsert(id, newRecord, previousRecord) {
246
- if (this.indexes.size === 0) return;
247
- if (previousRecord !== null) {
248
- this.remove(id, previousRecord);
249
- }
250
- for (const idx of this.indexes.values()) {
251
- addToIndex(idx, id, newRecord);
252
- }
253
- }
254
- /**
255
- * Remove a record from all indexes. Called by `Collection.delete()`
256
- * (and as the first half of `upsert` for the update path).
257
- */
258
- remove(id, record) {
259
- if (this.indexes.size === 0) return;
260
- for (const idx of this.indexes.values()) {
261
- removeFromIndex(idx, id, record);
262
- }
263
- }
264
- /** Drop all index data. Called when the collection is invalidated. */
265
- clear() {
266
- for (const idx of this.indexes.values()) {
267
- idx.buckets.clear();
268
- }
269
- }
270
- /**
271
- * Equality lookup: return the set of record ids whose `field` matches
272
- * the given value. Returns `null` if no index covers the field — the
273
- * caller should fall back to a linear scan.
274
- *
275
- * The returned Set is a reference to the index's internal storage —
276
- * callers must NOT mutate it.
277
- */
278
- lookupEqual(field, value) {
279
- const idx = this.indexes.get(field);
280
- if (!idx) return null;
281
- const key = stringifyKey(value);
282
- return idx.buckets.get(key) ?? EMPTY_SET;
283
- }
284
- /**
285
- * Set lookup: return the union of record ids whose `field` matches any
286
- * of the given values. Returns `null` if no index covers the field.
287
- */
288
- lookupIn(field, values) {
289
- const idx = this.indexes.get(field);
290
- if (!idx) return null;
291
- const out = /* @__PURE__ */ new Set();
292
- for (const value of values) {
293
- const key = stringifyKey(value);
294
- const bucket = idx.buckets.get(key);
295
- if (bucket) {
296
- for (const id of bucket) out.add(id);
297
- }
298
- }
299
- return out;
300
- }
301
- };
302
- var EMPTY_SET = /* @__PURE__ */ new Set();
303
- function stringifyKey(value) {
304
- if (value === null || value === void 0) return "\0NULL\0";
305
- if (typeof value === "string") return value;
306
- if (typeof value === "number" || typeof value === "boolean") return String(value);
307
- if (value instanceof Date) return value.toISOString();
308
- return "\0OBJECT\0";
309
- }
310
- function addToIndex(idx, id, record) {
311
- const value = readPath(record, idx.field);
312
- if (value === null || value === void 0) return;
313
- const key = stringifyKey(value);
314
- let bucket = idx.buckets.get(key);
315
- if (!bucket) {
316
- bucket = /* @__PURE__ */ new Set();
317
- idx.buckets.set(key, bucket);
318
- }
319
- bucket.add(id);
320
- }
321
- function removeFromIndex(idx, id, record) {
322
- const value = readPath(record, idx.field);
323
- if (value === null || value === void 0) return;
324
- const key = stringifyKey(value);
325
- const bucket = idx.buckets.get(key);
326
- if (!bucket) return;
327
- bucket.delete(id);
328
- if (bucket.size === 0) idx.buckets.delete(key);
329
- }
330
-
331
- // src/indexing/persisted-indexes.ts
332
- var IDX_PREFIX = "_idx/";
333
- function encodeIdxId(field, recordId) {
334
- return `${IDX_PREFIX}${field}/${recordId}`;
335
- }
336
- function decodeIdxId(id) {
337
- if (!id.startsWith(IDX_PREFIX)) return null;
338
- const rest = id.slice(IDX_PREFIX.length);
339
- const firstSlash = rest.indexOf("/");
340
- if (firstSlash <= 0) return null;
341
- const field = rest.slice(0, firstSlash);
342
- const recordId = rest.slice(firstSlash + 1);
343
- if (recordId.length === 0) return null;
344
- return { field, recordId };
345
- }
346
- function isIdxId(id) {
347
- return decodeIdxId(id) !== null;
348
- }
349
- var COMPOSITE_DELIMITER = "|";
350
- function compositeKey(fields) {
351
- return fields.join(COMPOSITE_DELIMITER);
352
- }
353
- var PersistedCollectionIndex = class {
354
- indexes = /* @__PURE__ */ new Map();
355
- defs = /* @__PURE__ */ new Map();
356
- /**
357
- * Declare a single-field index. Subsequent `upsert` / `ingest` calls
358
- * populate the in-memory mirror; calls before `declare` are no-ops
359
- * (tolerant bulk-load ordering). Idempotent.
360
- */
361
- declare(field) {
362
- if (this.indexes.has(field)) return;
363
- this.indexes.set(field, { buckets: /* @__PURE__ */ new Map(), values: /* @__PURE__ */ new Map() });
364
- this.defs.set(field, { kind: "single", field, key: field });
365
- }
366
- /**
367
- * Declare a composite (multi-field) index. The synthetic
368
- * key is `fields.join('|')`; it doubles as the in-memory map key and
369
- * the `_idx/<key>/<recordId>` side-car field segment. Callers upsert
370
- * and lookup via the same `key` as single-field indexes, just with a
371
- * tuple value (JSON-stringified for bucketing).
372
- */
373
- declareComposite(fields) {
374
- if (fields.length === 0) {
375
- throw new Error("declareComposite: fields array must be non-empty");
376
- }
377
- for (const f of fields) {
378
- if (f.includes(COMPOSITE_DELIMITER)) {
379
- throw new Error(
380
- `declareComposite: field "${f}" contains the composite delimiter "${COMPOSITE_DELIMITER}" \u2014 pick a different field name or open an issue to add hash-based composite keys.`
381
- );
382
- }
383
- }
384
- const key = compositeKey(fields);
385
- if (this.indexes.has(key)) return;
386
- this.indexes.set(key, { buckets: /* @__PURE__ */ new Map(), values: /* @__PURE__ */ new Map() });
387
- this.defs.set(key, { kind: "composite", fields: [...fields], key });
388
- }
389
- /**
390
- * Every declared index's structured definition. Collection walks this
391
- * when materialising side-cars on put/delete so it can extract a
392
- * single-field value or a composite tuple appropriately.
393
- */
394
- definitions() {
395
- return [...this.defs.values()];
396
- }
397
- /** True if `field` has been declared as indexable on this mirror. */
398
- has(field) {
399
- return this.indexes.has(field);
400
- }
401
- /** All declared field names, in declaration order. */
402
- fields() {
403
- return [...this.indexes.keys()];
404
- }
405
- /**
406
- * Bulk-load the mirror from decrypted index bodies. Intended to be
407
- * called once per field after reading the collection's `_idx/<field>/*`
408
- * side-cars. Safe to call twice with the same rows — bucket Sets
409
- * deduplicate recordIds. If `field` is not declared, this is a no-op
410
- * (tolerates the case where bulk-load runs before `declare()` lands).
411
- */
412
- ingest(field, rows) {
413
- const state = this.indexes.get(field);
414
- if (!state) return;
415
- for (const row of rows) {
416
- addToState(state, row.recordId, row.value);
417
- }
418
- }
419
- /**
420
- * Incrementally update a record's index entry for one field. Called by
421
- * `Collection.put()` after the main write succeeds. If
422
- * `previousValue` is non-null, the record is removed from the old
423
- * bucket first — this is the update path. Pass `null` for fresh adds.
424
- * No-op if the field is not declared.
425
- */
426
- upsert(recordId, field, newValue, previousValue) {
427
- const state = this.indexes.get(field);
428
- if (!state) return;
429
- if (previousValue !== null && previousValue !== void 0) {
430
- removeFromState(state, recordId, previousValue);
431
- }
432
- addToState(state, recordId, newValue);
433
- }
434
- /**
435
- * Remove a record from the index for one field. Called by
436
- * `Collection.delete()`. No-op if the field is not declared or
437
- * the record isn't in the bucket. Empty buckets are dropped to keep
438
- * the Map clean.
439
- */
440
- remove(recordId, field, value) {
441
- const state = this.indexes.get(field);
442
- if (!state) return;
443
- removeFromState(state, recordId, value);
444
- }
445
- /**
446
- * Drop all bucket data while preserving field declarations. Called on
447
- * invalidation (incoming sync changes, keyring rotation) — the next
448
- * query re-populates via `ingest`.
449
- */
450
- clear() {
451
- for (const state of this.indexes.values()) {
452
- state.buckets.clear();
453
- state.values.clear();
454
- }
455
- }
456
- /**
457
- * Equality lookup — return the set of record ids whose `field` matches
458
- * `value`. Returns `null` if the field is not declared (caller falls
459
- * back to scan or throws `IndexRequiredError`). Returns a shared empty
460
- * set if the field is declared but no record matches — that set MUST
461
- * NOT be mutated by the caller.
462
- */
463
- lookupEqual(field, value) {
464
- const state = this.indexes.get(field);
465
- if (!state) return null;
466
- const key = stringifyKey2(value);
467
- return state.buckets.get(key) ?? EMPTY_SET2;
468
- }
469
- /**
470
- * Set lookup — return the union of record ids whose `field` matches any
471
- * of `values`. Returns `null` if the field is not declared. Returns a
472
- * fresh (non-shared) Set — safe for the caller to mutate.
473
- */
474
- lookupIn(field, values) {
475
- const state = this.indexes.get(field);
476
- if (!state) return null;
477
- const out = /* @__PURE__ */ new Set();
478
- for (const value of values) {
479
- const bucket = state.buckets.get(stringifyKey2(value));
480
- if (bucket) for (const id of bucket) out.add(id);
481
- }
482
- return out;
483
- }
484
- /**
485
- * Range lookup. Return record ids whose indexed value
486
- * satisfies the predicate. Comparison happens on the ORIGINAL TYPED
487
- * value carried in `state.values` — so numeric `<` sorts numerically,
488
- * not lexicographically on `String(n)`. Returns `null` if the field
489
- * is not declared.
490
- *
491
- * Supported ops: `'<'`, `'<='`, `'>'`, `'>='`, `'between'`. For
492
- * `'between'`, `value` is `[lo, hi]` and both bounds are inclusive
493
- * (matches the eager-mode operator contract in `predicate.ts`).
494
- */
495
- lookupRange(field, op, value) {
496
- const state = this.indexes.get(field);
497
- if (!state) return null;
498
- const out = /* @__PURE__ */ new Set();
499
- for (const [recordId, live] of state.values) {
500
- if (live === void 0 || live === null) continue;
501
- if (matchesRange(live, op, value)) out.add(recordId);
502
- }
503
- return out;
504
- }
505
- /**
506
- * Sorted iteration — return every entry on `field` as an
507
- * `OrderedEntry[]`, sorted by the ORIGINAL TYPED value (no more
508
- * `'10' < '2'` surprises on numeric fields). Consumers paginate with
509
- * a numeric offset. `OrderedEntry.value` is the typed value.
510
- */
511
- orderedBy(field, dir) {
512
- const state = this.indexes.get(field);
513
- if (!state) return null;
514
- const entries = [];
515
- for (const [recordId, value] of state.values) {
516
- entries.push({ recordId, value });
517
- }
518
- entries.sort((a, b) => compareTyped(a.value, b.value));
519
- if (dir === "desc") entries.reverse();
520
- return entries;
521
- }
522
- };
523
- var EMPTY_SET2 = /* @__PURE__ */ new Set();
524
- function stringifyKey2(value) {
525
- if (value === null || value === void 0) return "\0NULL\0";
526
- if (typeof value === "string") return value;
527
- if (typeof value === "number" || typeof value === "boolean") return String(value);
528
- if (value instanceof Date) return value.toISOString();
529
- if (Array.isArray(value)) {
530
- const parts = [];
531
- for (const el of value) parts.push(stringifyKey2(el));
532
- return JSON.stringify(parts);
533
- }
534
- return "\0OBJECT\0";
535
- }
536
- function addToState(state, recordId, value) {
537
- if (value === null || value === void 0) return;
538
- const key = stringifyKey2(value);
539
- let bucket = state.buckets.get(key);
540
- if (!bucket) {
541
- bucket = /* @__PURE__ */ new Set();
542
- state.buckets.set(key, bucket);
543
- }
544
- bucket.add(recordId);
545
- state.values.set(recordId, value);
546
- }
547
- function removeFromState(state, recordId, value) {
548
- if (value === null || value === void 0) return;
549
- const key = stringifyKey2(value);
550
- const bucket = state.buckets.get(key);
551
- if (bucket) {
552
- bucket.delete(recordId);
553
- if (bucket.size === 0) state.buckets.delete(key);
554
- }
555
- state.values.delete(recordId);
556
- }
557
- function matchesRange(live, op, bound) {
558
- if (op === "between") {
559
- if (!Array.isArray(bound) || bound.length !== 2) return false;
560
- return compareTyped(live, bound[0]) >= 0 && compareTyped(live, bound[1]) <= 0;
561
- }
562
- const cmp = compareTyped(live, bound);
563
- switch (op) {
564
- case "<":
565
- return cmp < 0;
566
- case "<=":
567
- return cmp <= 0;
568
- case ">":
569
- return cmp > 0;
570
- case ">=":
571
- return cmp >= 0;
572
- }
573
- }
574
- function compareTyped(a, b) {
575
- if (a === void 0 || a === null) return b === void 0 || b === null ? 0 : 1;
576
- if (b === void 0 || b === null) return -1;
577
- if (typeof a === "number" && typeof b === "number") return a - b;
578
- if (a instanceof Date && b instanceof Date) return a.getTime() - b.getTime();
579
- if (typeof a === "string" && typeof b === "string") return a < b ? -1 : a > b ? 1 : 0;
580
- if (typeof a === "boolean" && typeof b === "boolean") {
581
- return a === b ? 0 : a ? 1 : -1;
582
- }
583
- return 0;
584
- }
585
-
586
- // src/indexing/active.ts
587
- function withIndexing() {
588
- return {
589
- createState({ defs, lazy }) {
590
- if (lazy) {
591
- const persisted = new PersistedCollectionIndex();
592
- declareAll(persisted, defs);
593
- return makeLazyState(persisted);
594
- }
595
- const eager = new CollectionIndexes();
596
- for (const def of defs) {
597
- if (typeof def === "string") {
598
- eager.declare(def);
599
- } else if (Array.isArray(def)) {
600
- for (const f of def) eager.declare(f);
601
- } else {
602
- for (const f of def.fields) eager.declare(f);
603
- }
604
- }
605
- return makeEagerState(eager);
606
- }
607
- };
608
- }
609
- function declareAll(persisted, defs) {
610
- for (const def of defs) {
611
- if (typeof def === "string") {
612
- persisted.declare(def);
613
- } else if (Array.isArray(def)) {
614
- persisted.declareComposite(def);
615
- } else {
616
- persisted.declareComposite(def.fields);
617
- }
618
- }
619
- }
620
- function makeEagerState(eager) {
621
- return {
622
- isEnabled: true,
623
- getEagerIndexes: () => eager,
624
- getPersistedIndexes: () => null
625
- };
626
- }
627
- function makeLazyState(persisted) {
628
- return {
629
- isEnabled: true,
630
- getEagerIndexes: () => null,
631
- getPersistedIndexes: () => persisted
632
- };
633
- }
634
-
635
- // src/indexing/lazy-builder.ts
636
- var EMPTY_PLAN = {
637
- clauses: [],
638
- orderBy: [],
639
- limit: void 0,
640
- offset: 0
641
- };
642
- var LazyQuery = class _LazyQuery {
643
- source;
644
- plan;
645
- constructor(source, plan = EMPTY_PLAN) {
646
- this.source = source;
647
- this.plan = plan;
648
- }
649
- where(field, op, value) {
650
- const clause = { type: "field", field, op, value };
651
- return new _LazyQuery(this.source, {
652
- ...this.plan,
653
- clauses: [...this.plan.clauses, clause]
654
- });
655
- }
656
- orderBy(field, direction = "asc") {
657
- return new _LazyQuery(this.source, {
658
- ...this.plan,
659
- orderBy: [...this.plan.orderBy, { field, direction }]
660
- });
661
- }
662
- limit(n) {
663
- return new _LazyQuery(this.source, { ...this.plan, limit: n });
664
- }
665
- offset(n) {
666
- return new _LazyQuery(this.source, { ...this.plan, offset: n });
667
- }
668
- async toArray() {
669
- await this.source.ensurePersistedIndexesLoaded();
670
- const touchedFields = collectTouchedFields(this.plan);
671
- const missingFields = touchedFields.filter((f) => !isFieldIndexed(f, this.source.persistedIndexes));
672
- if (missingFields.length > 0) {
673
- throw new IndexRequiredError({
674
- collection: this.source.collectionName,
675
- touchedFields,
676
- missingFields
677
- });
678
- }
679
- const candidateIds = this.resolveCandidateIds();
680
- if (candidateIds === null) {
681
- throw new IndexRequiredError({
682
- collection: this.source.collectionName,
683
- touchedFields,
684
- missingFields: touchedFields
685
- });
686
- }
687
- const records = [];
688
- for (const id of candidateIds) {
689
- const record = await this.source.getRecord(id);
690
- if (record === null) continue;
691
- if (!matchesAll(record, this.plan.clauses)) continue;
692
- records.push(record);
693
- }
694
- const sorted = this.plan.orderBy.length > 0 ? sortRecords(records, this.plan.orderBy) : records;
695
- const offset = this.plan.offset > 0 ? this.plan.offset : 0;
696
- const limited = this.plan.limit === void 0 ? sorted.slice(offset) : sorted.slice(offset, offset + this.plan.limit);
697
- return limited;
698
- }
699
- async first() {
700
- const out = await this.limit(1).toArray();
701
- return out.length > 0 ? out[0] : null;
702
- }
703
- async count() {
704
- const out = await this.toArray();
705
- return out.length;
706
- }
707
- /**
708
- * Resolve the candidate record-id set to decrypt. Returns null when the
709
- * query has no usable driver — no `==`/`in` clause and no `orderBy`
710
- * clause that can scope the scan. Callers interpret null as
711
- * IndexRequiredError (see `toArray`).
712
- */
713
- resolveCandidateIds() {
714
- const idx = this.source.persistedIndexes;
715
- const eqMap = /* @__PURE__ */ new Map();
716
- for (const clause of this.plan.clauses) {
717
- if (clause.op === "==") eqMap.set(clause.field, clause.value);
718
- }
719
- if (eqMap.size >= 2) {
720
- for (const def of idx.definitions()) {
721
- if (def.kind !== "composite") continue;
722
- if (def.fields.every((f) => eqMap.has(f))) {
723
- const tuple = def.fields.map((f) => eqMap.get(f));
724
- const ids = idx.lookupEqual(def.key, tuple);
725
- if (ids) return [...ids];
726
- }
727
- }
728
- }
729
- for (const clause of this.plan.clauses) {
730
- if (clause.op === "==") {
731
- const ids = idx.lookupEqual(clause.field, clause.value);
732
- if (ids) return [...ids];
733
- } else if (clause.op === "in" && Array.isArray(clause.value)) {
734
- const ids = idx.lookupIn(clause.field, clause.value);
735
- if (ids) return [...ids];
736
- } else if (isRangeOp(clause.op)) {
737
- const ids = idx.lookupRange(clause.field, clause.op, clause.value);
738
- if (ids) return [...ids];
739
- }
740
- }
741
- if (this.plan.orderBy.length > 0) {
742
- const primary = this.plan.orderBy[0];
743
- const entries = idx.orderedBy(primary.field, primary.direction);
744
- if (entries) return entries.map((e) => e.recordId);
745
- }
746
- return null;
747
- }
748
- };
749
- function isFieldIndexed(field, idx) {
750
- if (idx.has(field)) return true;
751
- for (const def of idx.definitions()) {
752
- if (def.kind === "composite" && def.fields.includes(field)) return true;
753
- }
754
- return false;
755
- }
756
- function isRangeOp(op) {
757
- return op === "<" || op === "<=" || op === ">" || op === ">=" || op === "between";
758
- }
759
- function collectTouchedFields(plan) {
760
- const seen = /* @__PURE__ */ new Set();
761
- for (const c of plan.clauses) seen.add(c.field);
762
- for (const o of plan.orderBy) seen.add(o.field);
763
- return [...seen];
764
- }
765
- function matchesAll(record, clauses) {
766
- for (const c of clauses) {
767
- if (!evaluateClause(record, c)) return false;
768
- }
769
- return true;
770
- }
771
- function sortRecords(records, orderBy) {
772
- return [...records].sort((a, b) => {
773
- for (const { field, direction } of orderBy) {
774
- const av = readPath(a, field);
775
- const bv = readPath(b, field);
776
- const cmp = compareValues(av, bv);
777
- if (cmp !== 0) return direction === "asc" ? cmp : -cmp;
778
- }
779
- return 0;
780
- });
781
- }
782
- function compareValues(a, b) {
783
- if (a === void 0 || a === null) return b === void 0 || b === null ? 0 : 1;
784
- if (b === void 0 || b === null) return -1;
785
- if (typeof a === "number" && typeof b === "number") return a - b;
786
- if (typeof a === "string" && typeof b === "string") return a < b ? -1 : a > b ? 1 : 0;
787
- if (a instanceof Date && b instanceof Date) return a.getTime() - b.getTime();
788
- return 0;
789
- }
790
- // Annotate the CommonJS export names for ESM import in node:
791
- 0 && (module.exports = {
792
- COMPOSITE_DELIMITER,
793
- CollectionIndexes,
794
- IDX_PREFIX,
795
- LazyQuery,
796
- PersistedCollectionIndex,
797
- compositeKey,
798
- decodeIdxId,
799
- encodeIdxId,
800
- isIdxId,
801
- withIndexing
802
- });
803
- //# sourceMappingURL=index.cjs.map