@graffy/common 0.19.0 → 0.19.1-alpha.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (85) hide show
  1. package/coding/alphabet.js +5 -0
  2. package/coding/args.d.ts +5 -0
  3. package/coding/args.js +93 -0
  4. package/coding/base64.d.ts +2 -0
  5. package/coding/base64.js +41 -0
  6. package/coding/decodeTree.d.ts +2 -0
  7. package/coding/decodeTree.js +197 -0
  8. package/coding/decorate.js +211 -0
  9. package/coding/encodeTree.d.ts +2 -0
  10. package/coding/encodeTree.js +248 -0
  11. package/coding/id.js +4 -0
  12. package/coding/index.d.ts +8 -0
  13. package/{types/coding/index.d.ts → coding/index.js} +4 -4
  14. package/coding/number.d.ts +2 -0
  15. package/coding/number.js +39 -0
  16. package/coding/pack.d.ts +2 -0
  17. package/coding/pack.js +71 -0
  18. package/coding/path.d.ts +3 -0
  19. package/coding/path.js +41 -0
  20. package/coding/string.d.ts +2 -0
  21. package/coding/string.js +8 -0
  22. package/coding/struct.d.ts +11 -0
  23. package/coding/struct.js +163 -0
  24. package/index.d.ts +6 -0
  25. package/node/find.d.ts +2 -0
  26. package/node/find.js +14 -0
  27. package/node/index.d.ts +2 -0
  28. package/{types/node/index.d.ts → node/index.js} +1 -0
  29. package/node/types.d.ts +6 -0
  30. package/node/types.js +18 -0
  31. package/object.d.ts +4 -0
  32. package/object.js +86 -0
  33. package/ops/add.js +64 -0
  34. package/{types/ops → ops}/finalize.d.ts +1 -1
  35. package/ops/finalize.js +19 -0
  36. package/{types/ops → ops}/getKnown.d.ts +1 -4
  37. package/ops/getKnown.js +24 -0
  38. package/ops/index.d.ts +9 -0
  39. package/ops/merge.d.ts +3 -0
  40. package/ops/merge.js +112 -0
  41. package/ops/path.d.ts +6 -0
  42. package/ops/path.js +91 -0
  43. package/ops/setVersion.js +29 -0
  44. package/ops/sieve.d.ts +3 -0
  45. package/ops/sieve.js +193 -0
  46. package/{types/ops → ops}/slice.d.ts +2 -6
  47. package/ops/slice.js +153 -0
  48. package/ops/step.d.ts +6 -0
  49. package/ops/step.js +61 -0
  50. package/package.json +14 -8
  51. package/stream/index.d.ts +2 -0
  52. package/stream/makeWatcher.d.ts +10 -0
  53. package/stream/makeWatcher.js +19 -0
  54. package/stream/mergeStreams.js +20 -0
  55. package/util.d.ts +15 -0
  56. package/util.js +106 -0
  57. package/index.cjs +0 -1673
  58. package/index.mjs +0 -1673
  59. package/types/coding/args.d.ts +0 -5
  60. package/types/coding/base64.d.ts +0 -2
  61. package/types/coding/decodeTree.d.ts +0 -2
  62. package/types/coding/encodeTree.d.ts +0 -2
  63. package/types/coding/number.d.ts +0 -2
  64. package/types/coding/pack.d.ts +0 -2
  65. package/types/coding/path.d.ts +0 -3
  66. package/types/coding/string.d.ts +0 -2
  67. package/types/coding/struct.d.ts +0 -11
  68. package/types/node/find.d.ts +0 -2
  69. package/types/node/types.d.ts +0 -6
  70. package/types/object.d.ts +0 -4
  71. package/types/ops/merge.d.ts +0 -3
  72. package/types/ops/path.d.ts +0 -6
  73. package/types/ops/sieve.d.ts +0 -3
  74. package/types/ops/step.d.ts +0 -6
  75. package/types/stream/makeWatcher.d.ts +0 -16
  76. package/types/util.d.ts +0 -15
  77. package/{types/coding → coding}/alphabet.d.ts +0 -0
  78. package/{types/coding → coding}/decorate.d.ts +0 -0
  79. package/{types/coding → coding}/id.d.ts +0 -0
  80. package/{types/index.d.ts → index.js} +0 -0
  81. package/{types/ops → ops}/add.d.ts +0 -0
  82. package/{types/ops/index.d.ts → ops/index.js} +1 -1
  83. /package/{types/ops → ops}/setVersion.d.ts +0 -0
  84. /package/{types/stream/index.d.ts → stream/index.js} +0 -0
  85. /package/{types/stream → stream}/mergeStreams.d.ts +0 -0
package/index.cjs DELETED
@@ -1,1673 +0,0 @@
1
- "use strict";
2
- Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
3
- const debug = require("debug");
4
- const isEqual = require("lodash/isEqual.js");
5
- const stream = require("@graffy/stream");
6
- const mergeIterators = require("merge-async-iterators");
7
- const isDebugMode = debug("graffy*").enabled;
8
- const MIN_KEY = new Uint8Array();
9
- const MAX_KEY = new Uint8Array([255]);
10
- function isMinKey(key) {
11
- return key.length === 0;
12
- }
13
- function isMaxKey(key) {
14
- return key.length === 1 && key[0] === 255;
15
- }
16
- function err(message, { cause = null, ...args } = {}) {
17
- const e = new Error(message + (args ? ` ${JSON.stringify(args)}` : ""));
18
- e.cause = cause;
19
- throw e;
20
- }
21
- function errIf(message, condition, args) {
22
- if (condition) err(message, args);
23
- }
24
- function isEmpty(object) {
25
- for (const _ in object) return false;
26
- return true;
27
- }
28
- function isDef(value) {
29
- return typeof value !== "undefined";
30
- }
31
- function isPlainObject(arg) {
32
- return typeof arg === "object" && arg && !Array.isArray(arg) && !ArrayBuffer.isView(arg);
33
- }
34
- function clone$1(obj) {
35
- if (Array.isArray(obj)) {
36
- return obj.slice(0);
37
- }
38
- return { ...obj };
39
- }
40
- function cmp(a, b) {
41
- const l = a.length < b.length ? a.length : b.length;
42
- for (let i = 0; i < l; i++) {
43
- if (a[i] < b[i]) return -1;
44
- if (a[i] > b[i]) return 1;
45
- }
46
- if (a.length < b.length) return -1;
47
- if (a.length > b.length) return 1;
48
- return 0;
49
- }
50
- function find(items, compare2, first = 0, last = items.length) {
51
- let currentFirst = first;
52
- let currentLast = last;
53
- while (currentFirst < currentLast) {
54
- const ix = (currentFirst + currentLast) / 2 | 0;
55
- const d = compare2(items[ix]);
56
- if (d < 0) {
57
- currentFirst = ix + 1;
58
- } else if (d > 0) {
59
- currentLast = ix;
60
- } else {
61
- return ix;
62
- }
63
- }
64
- return currentFirst;
65
- }
66
- function stringify() {
67
- if (this?.length === 0) return "·";
68
- let str = "";
69
- let bull = false;
70
- this?.forEach?.((value, i) => {
71
- if (value >= 32 && value <= 126) {
72
- str += String.fromCharCode(value);
73
- bull = true;
74
- } else {
75
- str += (bull ? "·" : "") + `0${value.toString(16)}`.slice(-2) + (i < this.length - 1 ? "·" : "");
76
- bull = false;
77
- }
78
- });
79
- return str;
80
- }
81
- const inspectSymbol = /* @__PURE__ */ Symbol.for("nodejs.util.inspect.custom");
82
- function addStringify(buffer) {
83
- if (!isDebugMode) return buffer;
84
- if ("toJSON" in buffer || inspectSymbol in buffer) return buffer;
85
- buffer.toJSON = stringify;
86
- buffer.toString = stringify;
87
- buffer[inspectSymbol] = stringify;
88
- return buffer;
89
- }
90
- addStringify(MIN_KEY);
91
- addStringify(MAX_KEY);
92
- function keyStep(key) {
93
- if (isMinKey(key)) return { key, step: 1 };
94
- if (isMaxKey(key)) return { key, step: -1 };
95
- const l = key.length - 1;
96
- let newKey;
97
- let step;
98
- switch (key[l]) {
99
- case 0:
100
- newKey = key.slice(0, l);
101
- addStringify(newKey);
102
- step = 1;
103
- break;
104
- case 255:
105
- newKey = key.slice(0, l);
106
- addStringify(newKey);
107
- newKey[l - 1]++;
108
- step = -1;
109
- break;
110
- default:
111
- newKey = key;
112
- step = 0;
113
- }
114
- return { key: newKey, step };
115
- }
116
- function keyBefore(key) {
117
- if (isMinKey(key) || isMaxKey(key)) return key;
118
- const l = key.length - 1;
119
- let newKey;
120
- if (key[l] === 0) {
121
- newKey = key.slice(0, l);
122
- } else {
123
- newKey = new Uint8Array(l + 2);
124
- newKey.set(key, 0);
125
- newKey[l]--;
126
- newKey[l + 1] = 255;
127
- }
128
- addStringify(newKey);
129
- return newKey;
130
- }
131
- function keyAfter(key) {
132
- if (isMaxKey(key)) return key;
133
- const l = key.length - 1;
134
- let newKey;
135
- if (key[l] === 255) {
136
- newKey = key.slice(0, l);
137
- newKey[l - 1]++;
138
- } else {
139
- newKey = new Uint8Array(l + 2);
140
- newKey.set(key, 0);
141
- newKey[l + 1] = 0;
142
- }
143
- addStringify(newKey);
144
- return newKey;
145
- }
146
- function TwosComplement(view) {
147
- const lo = -view.getUint32(4) >>> 0;
148
- const carry = lo ? 0 : -1;
149
- const hi = ~view.getUint32(0) + carry >>> 0;
150
- view.setUint32(0, hi);
151
- view.setUint32(4, lo);
152
- }
153
- function encode$6(number) {
154
- const buffer = new ArrayBuffer(8);
155
- const view = new DataView(buffer);
156
- view.setFloat64(0, number);
157
- if (number < 0) {
158
- TwosComplement(view);
159
- } else {
160
- view.setUint8(0, view.getUint8(0) | 128);
161
- }
162
- return new Uint8Array(buffer);
163
- }
164
- function decode$6(u8Arr) {
165
- const copy = new Uint8Array(8);
166
- copy.set(u8Arr, 0);
167
- const { buffer, byteOffset, byteLength } = copy;
168
- const view = new DataView(buffer, byteOffset, byteLength);
169
- const high = view.getUint8(0);
170
- if (high & 128) {
171
- view.setUint8(0, high & 127);
172
- } else {
173
- TwosComplement(view);
174
- }
175
- return view.getFloat64(0);
176
- }
177
- const textEncoder = new TextEncoder();
178
- const textDecoder = new TextDecoder("utf-8");
179
- function encode$5(string) {
180
- return textEncoder.encode(string);
181
- }
182
- function decode$5(u8Arr) {
183
- return textDecoder.decode(u8Arr);
184
- }
185
- const END = 0;
186
- const NULL = 1;
187
- const FALSE = 2;
188
- const TRUE = 3;
189
- const NUM = 4;
190
- const STR = 5;
191
- const ARR = 6;
192
- const OBJ = 7;
193
- const EOK = 127;
194
- function encodeArray(array) {
195
- return [ARR, ...array.flatMap((value) => encodeParts(value)), END];
196
- }
197
- function encodeObject(object) {
198
- const keys = Object.keys(object).sort();
199
- return [
200
- OBJ,
201
- ...keys.flatMap((key) => [
202
- STR,
203
- encode$5(key),
204
- END,
205
- ...encodeParts(object[key])
206
- ]),
207
- END
208
- ];
209
- }
210
- function encodeParts(value) {
211
- if (value === null) return [NULL];
212
- if (value === false) return [FALSE];
213
- if (value === true) return [TRUE];
214
- if (typeof value === "number") return [NUM, encode$6(value)];
215
- if (typeof value === "string") return [STR, encode$5(value), END];
216
- if (Array.isArray(value)) return encodeArray(value);
217
- if (typeof value === "object") return encodeObject(value);
218
- return [NULL];
219
- }
220
- function encode$4(value) {
221
- const parts = encodeParts(value);
222
- while (parts[parts.length - 1] === END) parts.pop();
223
- const lastPart = parts[parts.length - 1];
224
- if (typeof lastPart !== "number") {
225
- let end = lastPart.length - 1;
226
- while (end >= 0 && !lastPart[end]) end--;
227
- if (lastPart[end] !== 255) {
228
- parts[parts.length - 1] = lastPart.slice(0, end + 1);
229
- } else {
230
- parts.push(EOK);
231
- }
232
- }
233
- const length = parts.reduce(
234
- (sum, part) => sum + (typeof part === "number" ? 1 : part.length),
235
- 0
236
- );
237
- const buffer = new Uint8Array(length);
238
- let i = 0;
239
- for (const part of parts) {
240
- if (typeof part === "number") {
241
- buffer[i] = part;
242
- i++;
243
- } else {
244
- buffer.set(part, i);
245
- i += part.length;
246
- }
247
- }
248
- addStringify(buffer);
249
- return buffer;
250
- }
251
- const nextKey = /* @__PURE__ */ new WeakMap();
252
- function decode$4(buffer) {
253
- let i = 0;
254
- const stack = [[]];
255
- function readString() {
256
- const start = i;
257
- while (i < buffer.length && buffer[i] !== END) i++;
258
- const str = decode$5(buffer.subarray(start, i));
259
- i++;
260
- return str;
261
- }
262
- function pushToken(type, value) {
263
- const current = stack[stack.length - 1];
264
- if (type === ARR || type === OBJ) stack.push(value);
265
- if (!current) return;
266
- if (Array.isArray(current)) {
267
- current.push(value);
268
- } else {
269
- if (nextKey.has(current)) {
270
- current[nextKey.get(current)] = value;
271
- nextKey.delete(current);
272
- } else {
273
- nextKey.set(current, value);
274
- }
275
- }
276
- }
277
- function popToken() {
278
- stack.pop();
279
- }
280
- while (i < buffer.length) {
281
- const type = buffer[i];
282
- const start = ++i;
283
- switch (type) {
284
- case EOK:
285
- return stack[0][0];
286
- case END:
287
- popToken();
288
- break;
289
- case NULL:
290
- pushToken(type, null);
291
- break;
292
- case FALSE:
293
- pushToken(type, false);
294
- break;
295
- case TRUE:
296
- pushToken(type, true);
297
- break;
298
- case NUM:
299
- i += 8;
300
- pushToken(type, decode$6(buffer.subarray(start, i)));
301
- break;
302
- case STR:
303
- pushToken(type, readString());
304
- break;
305
- case ARR:
306
- pushToken(type, []);
307
- break;
308
- case OBJ:
309
- pushToken(type, {});
310
- break;
311
- default:
312
- throw new Error(`Invalid byte ${type} at ${start}`);
313
- }
314
- }
315
- return stack[0][0];
316
- }
317
- function decodeBound(bound) {
318
- const { key, step } = keyStep(bound);
319
- if (isMinKey(key) || isMaxKey(key)) return { step };
320
- const value = decode$4(key);
321
- return { key: value, step };
322
- }
323
- const pageProps = {
324
- $all: 1,
325
- $first: 1,
326
- $last: 1,
327
- $after: 1,
328
- $before: 1,
329
- $since: 1,
330
- $until: 1,
331
- $cursor: 1
332
- };
333
- function splitArgs(arg) {
334
- const page = {};
335
- const filter = {};
336
- for (const p in arg) (p in pageProps ? page : filter)[p] = arg[p];
337
- return [
338
- isEmpty(page) ? void 0 : page,
339
- isEmpty(filter) ? void 0 : filter
340
- ];
341
- }
342
- function encode$3(arg) {
343
- if (!isPlainObject(arg)) return { key: encode$4(arg) };
344
- const [page, filter] = splitArgs(arg);
345
- errIf("page_and_filter", page && filter, arg);
346
- if (!page) return { key: encode$4(filter || {}) };
347
- const { $cursor, ...range } = page;
348
- const { $first, $all, $last, $after, $before, $since, $until } = range;
349
- const hasRange = !isEmpty(range);
350
- errIf("first_and_last", isDef($first) && isDef($last), arg);
351
- errIf("all_and_last", isDef($all) && isDef($last), arg);
352
- errIf("all_and_first", isDef($first) && isDef($all), arg);
353
- errIf("after_and_since", isDef($after) && isDef($since), arg);
354
- errIf("before_and_until", isDef($before) && isDef($until), arg);
355
- errIf("cursor_and_range_arg", isDef($cursor) && hasRange, arg);
356
- let [key, end] = hasRange ? [MIN_KEY, MAX_KEY] : [];
357
- if (isDef($cursor)) key = encode$4($cursor);
358
- if (isDef($after)) key = keyAfter(encode$4($after));
359
- if (isDef($before)) end = keyBefore(encode$4($before));
360
- if (isDef($since)) key = encode$4($since);
361
- if (isDef($until)) end = encode$4($until);
362
- if (isDef($last)) [key, end] = [end, key];
363
- const node = { key };
364
- if (isDef(end)) node.end = end;
365
- if ($first || $last) node.limit = $first || $last;
366
- return node;
367
- }
368
- function decode$3(node) {
369
- const { key, end, limit } = node;
370
- errIf("no_key", !isDef(key));
371
- errIf("limit_without_end", isDef(limit) && !isDef(end));
372
- const kParts = decodeBound(key);
373
- if (!isDef(end) || cmp(key, end) === 0) return kParts.key;
374
- const eParts = decodeBound(end);
375
- const reverse = cmp(key, end) > 0;
376
- const [lower, upper] = reverse ? [eParts, kParts] : [kParts, eParts];
377
- const args = {};
378
- if (limit) {
379
- args[reverse ? "$last" : "$first"] = limit;
380
- } else if (isMinKey(key) && isMaxKey(end) || isMinKey(end) && isMaxKey(key)) {
381
- args.$all = true;
382
- }
383
- if (isDef(lower.key) && !isMinKey(lower.key)) {
384
- args[lower.step === 1 ? "$after" : "$since"] = lower.key;
385
- }
386
- if (isDef(upper.key) && !isMaxKey(upper.key)) {
387
- args[upper.step === -1 ? "$before" : "$until"] = upper.key;
388
- }
389
- return args;
390
- }
391
- function findFirst(children, target, first, last) {
392
- return find(
393
- children,
394
- ({ key, end }) => {
395
- const keyCmp = cmp(key, target);
396
- const endCmp = end && cmp(end, target);
397
- if (end && keyCmp < 0 && endCmp >= 0) return 0;
398
- return keyCmp;
399
- },
400
- first,
401
- last
402
- );
403
- }
404
- function findLast(children, end, first, last) {
405
- const ix = findFirst(children, end, first, last);
406
- return children[ix] && cmp(children[ix].key, end) <= 0 ? ix + 1 : ix;
407
- }
408
- function isRange(node) {
409
- return node && typeof node.end !== "undefined";
410
- }
411
- function isBranch(node) {
412
- return node && typeof node.children !== "undefined";
413
- }
414
- function isPrefix(node) {
415
- return node?.prefix;
416
- }
417
- function isLink(node) {
418
- return node && typeof node.path !== "undefined";
419
- }
420
- function isOlder(node, version) {
421
- return typeof node.version !== "undefined" && node.version < version;
422
- }
423
- function isNewer(node, version) {
424
- return typeof node.version !== "undefined" && node.version > version;
425
- }
426
- function add(base, diff) {
427
- let changed = false;
428
- let index = 0;
429
- for (const node of diff) {
430
- const cmp2 = compare(node);
431
- const nodeIsBranch = isBranch(node);
432
- index = find(base, cmp2, index);
433
- const item = base[index];
434
- const itemIsBranch = isBranch(item);
435
- if (!item || cmp2(item)) {
436
- base.splice(index, 0, clone(node));
437
- changed = true;
438
- continue;
439
- }
440
- if (nodeIsBranch && itemIsBranch) {
441
- changed = add(item.children, node.children) || changed;
442
- } else if (nodeIsBranch) {
443
- continue;
444
- } else if (itemIsBranch) {
445
- item.value = node.value;
446
- changed = true;
447
- } else {
448
- item.value += node.value;
449
- }
450
- const size = itemIsBranch ? item.children.length : item.value;
451
- if (!size) {
452
- base.splice(index, 1);
453
- changed = true;
454
- }
455
- }
456
- return changed;
457
- }
458
- function compare(node) {
459
- return (item) => {
460
- const v = cmp(item.key, node.key) || compareValue(!!item.end, !!node.end) || item.end && cmp(item.end, node.end) || compareValue(item.limit, node.limit);
461
- return v;
462
- };
463
- }
464
- function compareValue(a, b) {
465
- if (a === b) return 0;
466
- return a < b ? -1 : 1;
467
- }
468
- function clone(node) {
469
- const copy = { ...node };
470
- if (node.children) copy.children = node.children.map((child) => clone(child));
471
- return copy;
472
- }
473
- function finalize(graph, query, version = Date.now()) {
474
- let result = [{ key: MIN_KEY, end: MAX_KEY, version: 0 }];
475
- merge(result, graph);
476
- if (query) result = slice(result, query).known || [];
477
- if (version !== false) result = setVersion(result, version, true);
478
- return result;
479
- }
480
- function getKnown(graph, version = 0) {
481
- const query = [];
482
- for (const { key, end, children } of graph) {
483
- const node = { key, version };
484
- if (end) {
485
- if (cmp(end, key) !== 0) node.end = end;
486
- node.value = 1;
487
- }
488
- if (children) {
489
- node.children = getKnown(children);
490
- } else {
491
- node.value = 1;
492
- }
493
- query.push(node);
494
- }
495
- return query;
496
- }
497
- function merge(current, changes) {
498
- let index = 0;
499
- if (typeof changes === "undefined") return current;
500
- for (const change of changes) {
501
- index = isRange(change) ? insertRange$1(current, change, index) : insertNode$1(current, change, index);
502
- }
503
- return current;
504
- }
505
- function insertRange$1(current, change, start = 0) {
506
- const { key, end } = change;
507
- const keyIx = findFirst(current, key, start);
508
- const endIx = findLast(current, end, keyIx);
509
- const insertions = [change];
510
- for (let i = keyIx; i < endIx; i++) {
511
- const node = current[i];
512
- if (isRange(node)) {
513
- insertions.push(...mergeRanges$1(insertions.pop(), node));
514
- } else {
515
- insertNode$1(insertions, node, insertions.length - 1);
516
- }
517
- }
518
- current.splice(keyIx, endIx - keyIx, ...insertions);
519
- return keyIx + insertions.length - 1;
520
- }
521
- function mergeRanges$1(base, node) {
522
- if (node.version < base.version) [node, base] = [base, node];
523
- return [
524
- cmp(base.key, node.key) < 0 && { ...base, end: keyBefore(node.key) },
525
- node,
526
- cmp(base.end, node.end) > 0 && { ...base, key: keyAfter(node.end) }
527
- ].filter(Boolean);
528
- }
529
- function insertNode$1(current, change, start = 0) {
530
- if (!current) throw new Error(`merge.insertNode: ${current}`);
531
- const key = change.key;
532
- const index = findFirst(current, key, start);
533
- const node = current[index];
534
- if (node && cmp(node.key, key) <= 0) {
535
- return isRange(node) ? insertNodeIntoRange$1(current, index, change) : updateNode$1(current, index, change);
536
- }
537
- current.splice(index, 0, change);
538
- return index + 1;
539
- }
540
- function insertNodeIntoRange$1(current, index, change) {
541
- const key = change.key;
542
- const range = current[index];
543
- const newChange = getNewer(change, range);
544
- if (!newChange) return;
545
- const insertions = [
546
- cmp(range.key, key) < 0 && { ...range, end: keyBefore(key) },
547
- newChange,
548
- cmp(range.end, key) > 0 && { ...range, key: keyAfter(key) }
549
- ].filter(Boolean);
550
- current.splice(index, 1, ...insertions);
551
- return index + insertions.length - 1;
552
- }
553
- function updateNode$1(current, index, change) {
554
- const node = current[index];
555
- if (isBranch(change) && isBranch(node)) {
556
- merge(node.children, change.children);
557
- } else if (isBranch(node)) {
558
- const newNode = getNewer(node, change);
559
- current[index] = newNode || change;
560
- } else {
561
- const newChange = getNewer(change, node);
562
- if (newChange) current[index] = newChange;
563
- }
564
- if (change.prefix) current[index].prefix = true;
565
- return index + 1;
566
- }
567
- function getNewer(node, base) {
568
- const { version } = base;
569
- if (isBranch(node)) {
570
- const children = [{ key: MIN_KEY, end: MAX_KEY, version }];
571
- merge(children, node.children);
572
- return children.length === 1 ? null : { ...node, children };
573
- }
574
- return node.version >= version ? node : null;
575
- }
576
- const IS_VAL = /* @__PURE__ */ Symbol("IS_VAL");
577
- function makeNode(seg, props2) {
578
- if (ArrayBuffer.isView(seg)) return { key: seg, ...props2 };
579
- return { ...seg, ...props2 };
580
- }
581
- function wrapValue(value, path, version = 0) {
582
- const node = makeNode(path[path.length - 1], { value, version });
583
- return wrap([node], path.slice(0, -1), version);
584
- }
585
- function wrap(children, path, version = 0, prefix = false) {
586
- if (!Array.isArray(path)) throw Error(`wrap.path_not_array ${path}`);
587
- if (!path.length) return children;
588
- let i = path.length - 1;
589
- if (!Array.isArray(children)) {
590
- children = [makeNode(path[i--], { value: children, version })];
591
- } else {
592
- if (!children.length) return;
593
- children = [makeNode(path[i--], { children, version })];
594
- }
595
- if (prefix) children[0].prefix = true;
596
- while (i >= 0) children = [makeNode(path[i--], { children, version })];
597
- return children;
598
- }
599
- function unwrap(tree, path) {
600
- if (!Array.isArray(path)) throw Error(`unwrap.path_not_array ${path}`);
601
- let children = tree;
602
- let node = { children };
603
- for (let i = 0; i < path.length; i++) {
604
- const key = path[i];
605
- if (!ArrayBuffer.isView(key)) throw Error("unwrap.ranges_unsupported");
606
- children = node.children;
607
- if (!children) return null;
608
- node = children[findFirst(children, key)];
609
- if (!node || cmp(node.key, key) > 0) return void 0;
610
- if (isRange(node)) return null;
611
- if (node.path) return unwrap(tree, node.path.concat(path.slice(i + 1)));
612
- }
613
- return getNodeValue(node);
614
- }
615
- function getNodeValue(node) {
616
- if (node.children) return node.children;
617
- if (node.value && typeof node.value === "object") {
618
- node.value[IS_VAL] = true;
619
- }
620
- return node.value;
621
- }
622
- function remove(children, path) {
623
- if (!Array.isArray(path)) throw Error(`del.path_not_array ${path}`);
624
- if (!children) return null;
625
- if (!path.length) return [];
626
- const key = path[0];
627
- const ix = findFirst(children, key);
628
- const node = children[ix];
629
- if (!node || cmp(node.key, key) > 0 || isRange(node)) return children;
630
- if (path.length === 1) {
631
- return children.slice(0, ix).concat(children.slice(ix + 1));
632
- }
633
- if (!isBranch(node)) return children;
634
- const filteredChildren = remove(node.children, path.slice(1));
635
- if (filteredChildren === children) return children;
636
- const filteredNode = filteredChildren.length ? { ...node, children: filteredChildren } : [];
637
- return children.slice(0, ix).concat(filteredNode, children.slice(ix + 1));
638
- }
639
- function setVersion(graph, version, onlyIfZero = false) {
640
- for (const node of graph) {
641
- if (!(onlyIfZero && node.version)) node.version = version;
642
- if (node.children) setVersion(node.children, version, onlyIfZero);
643
- }
644
- return graph;
645
- }
646
- function sieve(current, changes, result = []) {
647
- let index = 0;
648
- for (const change of changes) {
649
- index = isRange(change) ? insertRange(current, change, result, index) : insertNode(current, change, result, index);
650
- }
651
- return result;
652
- }
653
- function insertRange(current, change, result, start = 0) {
654
- const { key, end } = change;
655
- const keyIx = findFirst(current, key, start);
656
- const endIx = findLast(current, end, keyIx);
657
- if (keyIx === endIx && !(current[keyIx] && cmp(current[keyIx].key, end) <= 0 && cmp(current[keyIx].end || current[keyIx].key, key) >= 0)) {
658
- return keyIx;
659
- }
660
- const appliedChange = [];
661
- let currentKey = change.key;
662
- for (let i = keyIx; i < endIx; i++) {
663
- const node = current[i];
664
- if (isRange(node) && node.version >= 0) {
665
- if (cmp(node.key, currentKey) > 0) {
666
- appliedChange.push({
667
- key: currentKey,
668
- end: keyBefore(node.key),
669
- version: change.version
670
- });
671
- }
672
- currentKey = keyAfter(node.end);
673
- } else {
674
- if (getNewerChange(node, change)) {
675
- appliedChange.push({
676
- key: currentKey,
677
- end: keyBefore(node.key),
678
- version: change.version
679
- });
680
- currentKey = keyAfter(node.key);
681
- }
682
- }
683
- if (cmp(currentKey, change.end) >= 0) {
684
- break;
685
- }
686
- }
687
- if (cmp(currentKey, change.end) <= 0) {
688
- appliedChange.push({
689
- key: currentKey,
690
- end: change.end,
691
- version: change.version
692
- });
693
- }
694
- if (appliedChange.length) result.push(...appliedChange);
695
- const insertions = [change];
696
- for (let i = keyIx; i < endIx; i++) {
697
- const node = current[i];
698
- if (isRange(node)) {
699
- insertions.push(...mergeRanges(insertions.pop(), node));
700
- } else {
701
- insertNode(insertions, node, [], insertions.length - 1);
702
- }
703
- }
704
- current.splice(keyIx, endIx - keyIx, ...insertions);
705
- return keyIx + insertions.length - 1;
706
- }
707
- function mergeRanges(base, node) {
708
- if (node.version < base.version) [node, base] = [base, node];
709
- return [
710
- cmp(base.key, node.key) < 0 && { ...base, end: keyBefore(node.key) },
711
- node,
712
- cmp(base.end, node.end) > 0 && { ...base, key: keyAfter(node.end) }
713
- ].filter(Boolean);
714
- }
715
- function insertNode(current, change, result, start = 0) {
716
- const key = change.key;
717
- const index = findFirst(current, key, start);
718
- const node = current[index];
719
- if (node && cmp(node.key, key) <= 0) {
720
- return isRange(node) ? insertNodeIntoRange(current, index, change, result) : updateNode(current, index, change, result);
721
- }
722
- return index;
723
- }
724
- function insertNodeIntoRange(current, index, change, result) {
725
- const key = change.key;
726
- const range = current[index];
727
- const newChange = getNewerChange(change, range);
728
- const newNode = getNewerNode(change, range);
729
- if (!newChange) return;
730
- result.push(newChange);
731
- const insertions = [
732
- cmp(range.key, key) < 0 && { ...range, end: keyBefore(key) },
733
- newNode,
734
- cmp(range.end, key) > 0 && { ...range, key: keyAfter(key) }
735
- ].filter(Boolean);
736
- current.splice(index, 1, ...insertions);
737
- return index + insertions.length - 1;
738
- }
739
- function updateNode(current, index, change, result) {
740
- const node = current[index];
741
- if (isBranch(change) && isBranch(node)) {
742
- const nextResult = [];
743
- node.version = change.version;
744
- sieve(node.children, change.children, nextResult);
745
- if (nextResult.length) result.push({ ...change, children: nextResult });
746
- } else if (isBranch(node)) {
747
- const newNode = getNewerNode(node, change);
748
- current[index] = newNode || change;
749
- if (!newNode) result.push(change);
750
- } else {
751
- const newChange = getNewerChange(change, node);
752
- const newNode = getNewerNode(change, node);
753
- if (newNode) current[index] = newNode;
754
- if (newChange && (change.value !== node.value || !isPathEqual(change.path, node.path))) {
755
- result.push(newChange);
756
- }
757
- }
758
- return index + 1;
759
- }
760
- function isPathEqual(first, second) {
761
- if (!(first || second)) return true;
762
- if (!(first && second)) return false;
763
- if (first.length !== second.length) return false;
764
- for (let i = 0; i < first.length; i++) {
765
- if (first[i] !== second[i]) return false;
766
- }
767
- return true;
768
- }
769
- function getNewerNode(node, base) {
770
- if (isBranch(node)) {
771
- const emptyNode = { key: MIN_KEY, end: MAX_KEY, version: base.version };
772
- const children = [emptyNode];
773
- sieve(children, node.children);
774
- return children.length === 1 && children[0] === emptyNode ? null : { ...node, children };
775
- }
776
- return node.version >= base.version ? node : null;
777
- }
778
- function getNewerChange(node, base) {
779
- if (isBranch(node)) {
780
- const children = node.children.filter(
781
- (child) => getNewerChange(child, base)
782
- );
783
- return children.length && { ...node, children };
784
- }
785
- return node.version >= base.version ? node : null;
786
- }
787
- class Result {
788
- constructor(root) {
789
- this.root = root || this;
790
- }
791
- addKnown(node) {
792
- this.known = this.known || [];
793
- merge(this.known, [node]);
794
- }
795
- addUnknown(node) {
796
- this.unknown = this.unknown || [];
797
- this.unknown.push(node);
798
- }
799
- addLinked(children) {
800
- if (this.root !== this) return this.root.addLinked(children);
801
- this.linked = this.linked || [];
802
- add(this.linked, children);
803
- }
804
- }
805
- function slice(graph, query, root) {
806
- const result = new Result(root);
807
- let currentQuery = query;
808
- while (currentQuery) {
809
- let index = 0;
810
- for (const queryNode of currentQuery) {
811
- if (isRange(queryNode)) {
812
- sliceRange(graph, queryNode, result);
813
- } else {
814
- const key = queryNode.key;
815
- index = findFirst(graph, key);
816
- sliceNode(graph[index], queryNode, result);
817
- }
818
- }
819
- currentQuery = root ? void 0 : result.linked;
820
- delete result.linked;
821
- }
822
- delete result.root;
823
- return result;
824
- }
825
- function sliceNode(graph, query, result) {
826
- const { key, version } = query;
827
- const { root } = result;
828
- if (!graph || cmp(graph.key, key) > 0 || isOlder(graph, version)) {
829
- result.addUnknown(query);
830
- } else if (isRange(graph)) {
831
- if (isBranch(query)) {
832
- const { known } = slice(
833
- [{ key: MIN_KEY, end: MAX_KEY, version: graph.version }],
834
- query.children
835
- );
836
- result.addKnown({ key, version: graph.version, children: known });
837
- } else {
838
- result.addKnown({ key, end: key, version: graph.version });
839
- }
840
- } else if (isBranch(graph) && isBranch(query)) {
841
- const { known, unknown } = slice(graph.children, query.children, root);
842
- if (known) result.addKnown({ ...graph, children: known });
843
- if (unknown) result.addUnknown({ ...query, children: unknown });
844
- } else if (isLink(graph)) {
845
- result.addKnown(graph);
846
- if (graph.prefix && isRange(query)) {
847
- result.addLinked(wrap([query], graph.path, version, true));
848
- } else {
849
- result.addLinked(
850
- wrap(
851
- query.children || query.value,
852
- graph.path,
853
- version,
854
- graph.prefix || query.prefix
855
- )
856
- );
857
- }
858
- } else if (isBranch(graph)) {
859
- result.addKnown(graph);
860
- } else if (isBranch(query)) {
861
- const { known } = slice(
862
- [{ key: MIN_KEY, end: MAX_KEY, version: graph.version }],
863
- query.children
864
- );
865
- result.addKnown({ key, version: graph.version, children: known });
866
- } else {
867
- result.addKnown(graph);
868
- }
869
- }
870
- function sliceRange(graph, query, result) {
871
- let { key, end, limit = Number.POSITIVE_INFINITY, version } = query;
872
- const step = cmp(key, end) < 0 ? 1 : -1;
873
- if (isMinKey(graph[0].key) && graph[0].prefix && graph[0].children) {
874
- const { known, unknown } = slice(graph[0].children, [query], result.root);
875
- if (known) result.addKnown({ ...graph[0], children: known });
876
- if (unknown) result.addUnknown({ ...query[0], children: unknown });
877
- return;
878
- }
879
- if (cmp(key, end) < 0) {
880
- for (let i = findFirst(graph, key); cmp(key, end) <= 0 && limit > 0; i++) {
881
- const node = graph[i];
882
- if (!node || cmp(key, node.key) < 0 || isOlder(node, version)) break;
883
- if (isRange(node)) {
884
- result.addKnown(getOverlap(node, key, end));
885
- } else {
886
- sliceNode(node, { ...query, key }, result);
887
- limit--;
888
- }
889
- key = keyAfter(node.end || node.key);
890
- }
891
- } else {
892
- for (let i = findLast(graph, key) - 1; cmp(key, end) >= 0 && limit > 0; i--) {
893
- const node = graph[i];
894
- if (!node || cmp(key, node.end || node.key) > 0 || isOlder(node, version))
895
- break;
896
- if (isRange(node)) {
897
- result.addKnown(getOverlap(node, end, key));
898
- } else {
899
- sliceNode(node, { ...query, key }, result);
900
- limit--;
901
- }
902
- key = keyBefore(node.key);
903
- }
904
- }
905
- if (limit && (step < 0 ? cmp(key, end) > 0 : cmp(key, end) < 0)) {
906
- const unknown = { ...query, key, end, limit };
907
- result.addUnknown(unknown);
908
- }
909
- }
910
- function getOverlap(node, key, end) {
911
- if (cmp(node.key, key) >= 0 && cmp(node.end, end) <= 0) return node;
912
- return {
913
- ...node,
914
- key: cmp(node.key, key) > 0 ? node.key : key,
915
- end: cmp(node.end, end) < 0 ? node.end : end
916
- };
917
- }
918
- const PATH_SEPARATOR = ".";
919
- function encode$2(path) {
920
- if (typeof path === "string") {
921
- if (!path.length || path === PATH_SEPARATOR) return [];
922
- path = path.split(PATH_SEPARATOR);
923
- }
924
- if (!Array.isArray(path)) {
925
- throw Error(`encodePath.invalid:${JSON.stringify(path)}`);
926
- }
927
- function encodeSegment(seg) {
928
- if (ArrayBuffer.isView(seg)) return seg;
929
- const node = encode$3(seg);
930
- if (node.end) return node;
931
- return node.key;
932
- }
933
- if (isPlainObject(path[path.length - 1])) {
934
- const [page, filter] = splitArgs(path[path.length - 1]);
935
- if (page) path = path.slice(0, -1).concat([filter || MIN_KEY]);
936
- }
937
- return path.map(encodeSegment);
938
- }
939
- function decode$2(path) {
940
- if (!Array.isArray(path)) {
941
- throw Error(`decodePath.invalid:${JSON.stringify(path)}`);
942
- }
943
- return path.map((key) => decode$3({ key }));
944
- }
945
- function splitRef($ref) {
946
- if (!Array.isArray($ref)) return [];
947
- const tail = $ref[$ref.length - 1];
948
- if (!isPlainObject(tail)) return [];
949
- return splitArgs(tail);
950
- }
951
- const PRE_CHI_PUT = /* @__PURE__ */ Symbol("PREFIX_CHILDREN_$PUT");
952
- function decode$1(nodes = [], { isGraph } = {}) {
953
- function decodeChildren(nodes2) {
954
- let result = [];
955
- let allStrs = true;
956
- let allNums = true;
957
- function pushResult(...objects) {
958
- for (const object of objects) {
959
- if (isDef(object) && !Number.isInteger(object.$key)) allNums = false;
960
- if (isDef(object) && typeof object.$key !== "string") allStrs = false;
961
- }
962
- result.push(...objects);
963
- }
964
- const putRanges = [];
965
- const prefixChildPuts = [];
966
- let lastNode = null;
967
- function addPutRange({ key, end }) {
968
- if (lastNode) {
969
- if (lastNode.end) {
970
- if (cmp(key, keyAfter(lastNode.end)) === 0) {
971
- lastNode.end = end || key;
972
- return end && cmp(end, key) !== 0;
973
- }
974
- } else {
975
- if (cmp(key, keyAfter(lastNode.key)) === 0) {
976
- key = lastNode.key;
977
- }
978
- }
979
- }
980
- if (end && cmp(key, end) !== 0) {
981
- lastNode = { key, end };
982
- putRanges.push(lastNode);
983
- return true;
984
- }
985
- lastNode = { key };
986
- return false;
987
- }
988
- for (const node of nodes2) {
989
- if (isGraph && addPutRange(node)) continue;
990
- if (isPrefix(node)) {
991
- const decodedChildren = decodePrefixNode(node);
992
- if (PRE_CHI_PUT in decodedChildren) {
993
- prefixChildPuts.push(...decodedChildren[PRE_CHI_PUT]);
994
- }
995
- pushResult(...decodedChildren);
996
- } else if (isGraph && isRange(node)) pushResult(decodeRangeNode(node));
997
- else if (isBranch(node)) pushResult(decodeBranchNode(node));
998
- else if (isLink(node)) pushResult(decodeLinkNode(node));
999
- else pushResult(decodeLeafNode(node));
1000
- }
1001
- if (allStrs || allNums && putRanges.length === 1 && cmp(putRanges[0].key, 0) === 0 && cmp(putRanges[0].end, Number.POSITIVE_INFINITY) === 0) {
1002
- result = result.reduce(
1003
- (collection, item) => {
1004
- if (Array.isArray(item)) {
1005
- collection[item.$key] = item;
1006
- delete item.$key;
1007
- return collection;
1008
- }
1009
- let { $key, $val } = item;
1010
- delete item.$key;
1011
- delete item.$val;
1012
- if ($val === null) {
1013
- $val = { $val };
1014
- } else if (typeof $val === "object") {
1015
- $val = clone$1($val);
1016
- Object.defineProperty($val, "$val", { value: true });
1017
- }
1018
- collection[$key] = isDef($val) ? $val : !isEmpty(item) || item.$ref || item.$put ? item : isGraph ? null : true;
1019
- return collection;
1020
- },
1021
- allStrs ? {} : []
1022
- );
1023
- }
1024
- if (isGraph && putRanges.length) {
1025
- if (isMinKey(putRanges[0].key) && isMaxKey(putRanges[0].end)) {
1026
- Object.defineProperty(result, "$put", { value: true });
1027
- } else {
1028
- Object.defineProperty(result, "$put", {
1029
- value: putRanges.map((rNode) => decode$3(rNode)).concat(prefixChildPuts)
1030
- });
1031
- }
1032
- } else if (prefixChildPuts.length) {
1033
- Object.defineProperty(result, "$put", { value: prefixChildPuts });
1034
- }
1035
- return result;
1036
- }
1037
- function decodePrefixNode(node) {
1038
- let args = decode$3(node);
1039
- if (!args) args = {};
1040
- if (typeof args === "string") {
1041
- throw Error(`decode.unencoded_prefix: ${args}`);
1042
- }
1043
- if (isLink(node)) {
1044
- args.$all = true;
1045
- const $ref = decode$2(node.path);
1046
- const lastKey = $ref[$ref.length - 1];
1047
- if (typeof lastKey === "string") {
1048
- throw Error(`decode.unencoded_prefix_ref: ${node.path}`);
1049
- }
1050
- lastKey.$all = true;
1051
- const linkObject = { $key: args };
1052
- Object.defineProperty(linkObject, "$ref", { value: $ref });
1053
- return [linkObject];
1054
- }
1055
- const children = decodeChildren(node.children);
1056
- if (!Array.isArray(children)) {
1057
- throw Error(`decode.prefix_without_encoded_child_keys:${node.key}`);
1058
- }
1059
- for (const child of children) {
1060
- if (typeof child.$key === "string") {
1061
- throw Error(`decode.prefix_with_unencoded_child_key:${child.$key}`);
1062
- }
1063
- if (!splitArgs(child.$key)[0]) {
1064
- child.$key = { $cursor: child.$key };
1065
- }
1066
- child.$key = { ...args, ...child.$key };
1067
- }
1068
- if (children.$put === true) {
1069
- children[PRE_CHI_PUT] = [{ ...args, $all: true }];
1070
- } else if (Array.isArray(children.$put)) {
1071
- children[PRE_CHI_PUT] = children.$put.map((rarg) => ({
1072
- ...args,
1073
- ...rarg
1074
- }));
1075
- } else if (isDef(children.$put)) {
1076
- children[PRE_CHI_PUT] = [{ ...args, ...children.$put }];
1077
- }
1078
- return children;
1079
- }
1080
- function decodeBranchNode(node) {
1081
- const child = decodeChildren(node.children);
1082
- child.$key = decode$3(node);
1083
- return child;
1084
- }
1085
- function decodeLeafNode(node) {
1086
- const child = isGraph ? { $val: node.value } : {};
1087
- child.$key = decode$3(node);
1088
- return child;
1089
- }
1090
- function decodeRangeNode(node) {
1091
- if (cmp(node.key, node.end) === 0) {
1092
- return { $key: decode$3({ key: node.key }) };
1093
- }
1094
- }
1095
- function decodeLinkNode(node) {
1096
- const linkObject = { $key: decode$3(node) };
1097
- Object.defineProperty(linkObject, "$ref", { value: decode$2(node.path) });
1098
- return linkObject;
1099
- }
1100
- return decodeChildren(nodes);
1101
- }
1102
- function decodeGraph(graph) {
1103
- return decode$1(graph, { isGraph: true });
1104
- }
1105
- function decodeQuery(query) {
1106
- return decode$1(query, { isGraph: false });
1107
- }
1108
- const REF = /* @__PURE__ */ Symbol();
1109
- const PRE = /* @__PURE__ */ Symbol();
1110
- function decorate(rootGraph, rootQuery) {
1111
- function construct(plumGraph, query) {
1112
- if (plumGraph === null) return null;
1113
- if (!isDef(plumGraph)) plumGraph = [];
1114
- if (query.$key) query = [query];
1115
- let graph;
1116
- if (query.$ref) {
1117
- const { $ref, ...props2 } = query;
1118
- const [range, filter] = splitRef($ref);
1119
- const path = encode$2($ref);
1120
- const targetPlumGraph = unwrap(rootGraph, path);
1121
- if (targetPlumGraph) {
1122
- if (range) targetPlumGraph[PRE] = filter;
1123
- graph = construct(
1124
- targetPlumGraph,
1125
- range ? { $key: range, ...props2 } : props2
1126
- );
1127
- Object.defineProperty(graph, "$ref", { value: $ref });
1128
- }
1129
- } else if (Array.isArray(query)) {
1130
- let pageKey;
1131
- graph = query.flatMap((item, i) => {
1132
- if (!item?.$key) {
1133
- return construct(descend(plumGraph, i), item);
1134
- }
1135
- const { $key, $chi, ...props2 } = item;
1136
- const subQuery = $chi || (isEmpty(props2) ? 1 : props2);
1137
- if (!(isPlainObject($key) && splitArgs($key)[0])) {
1138
- return construct(descend(plumGraph, $key), subQuery);
1139
- }
1140
- if (pageKey) {
1141
- throw Error(
1142
- `decorate.multi_range_query:${JSON.stringify({ $key, pageKey })}`
1143
- );
1144
- }
1145
- pageKey = $key;
1146
- const children = slice2(plumGraph, $key);
1147
- return children.filter((node) => !isRange(node)).map((node) => {
1148
- const $key2 = decode$3(node);
1149
- const subResult = construct(getValue(node), subQuery);
1150
- if (typeof subResult === "object" && subResult) {
1151
- subResult.$key = children[PRE] && !isMinKey(children[PRE]) ? { ...children[PRE], $cursor: $key2 } : $key2;
1152
- }
1153
- return subResult;
1154
- });
1155
- });
1156
- if (pageKey) addPageMeta(graph, pageKey);
1157
- } else if (typeof query === "object") {
1158
- graph = {};
1159
- for (const prop in query) {
1160
- graph[prop] = construct(descend(plumGraph, prop), query[prop]);
1161
- }
1162
- } else if (query) {
1163
- if (Array.isArray(plumGraph) && !plumGraph.length) {
1164
- graph = void 0;
1165
- } else if (typeof plumGraph !== "object" || !plumGraph) {
1166
- graph = plumGraph;
1167
- } else if (plumGraph[IS_VAL]) {
1168
- graph = Array.isArray(plumGraph) ? plumGraph.slice(0) : { ...plumGraph };
1169
- graph.$val = true;
1170
- } else if (Array.isArray(plumGraph)) {
1171
- graph = deValNull(decodeGraph(plumGraph));
1172
- } else {
1173
- throw Error("decorate.unexpected_graph");
1174
- }
1175
- }
1176
- if (plumGraph[REF]) {
1177
- Object.defineProperty(graph, "$ref", {
1178
- value: decode$2(plumGraph[REF])
1179
- });
1180
- }
1181
- return graph;
1182
- }
1183
- function descend(children, $key) {
1184
- const key = ArrayBuffer.isView($key) ? $key : encode$3($key).key;
1185
- if (!Array.isArray(children)) return null;
1186
- const ix = findFirst(children, key);
1187
- const node = children[ix];
1188
- if (!node) return;
1189
- if (isRange(node) && node.end >= key) return null;
1190
- if (cmp(node.key, key) !== 0) return;
1191
- const result2 = getValue(node);
1192
- if (node.prefix) result2[PRE] = $key;
1193
- return result2;
1194
- }
1195
- function getValue(node) {
1196
- let result2;
1197
- if (node.path) {
1198
- result2 = unwrap(rootGraph, node.path);
1199
- if (typeof result2 === "object" && result2) result2[REF] = node.path;
1200
- } else {
1201
- result2 = getNodeValue(node);
1202
- }
1203
- return result2;
1204
- }
1205
- function slice2(children, $key) {
1206
- const [range, filter] = splitArgs($key);
1207
- if (isDef(filter)) {
1208
- children = descend(children, filter);
1209
- } else if (isMinKey(children[0].key) && children[0].prefix) {
1210
- children = descend(children, MIN_KEY);
1211
- }
1212
- const { key, end, limit = Number.POSITIVE_INFINITY } = encode$3(range);
1213
- const ix = findFirst(children, key);
1214
- let i = ix;
1215
- let result2;
1216
- if (cmp(key, end) < 0) {
1217
- for (let n = 0; i < children.length && n < limit; i++) {
1218
- if (!isRange(children[i])) n++;
1219
- }
1220
- result2 = children.slice(ix, i);
1221
- } else {
1222
- for (let n = 0; i >= 0 && n < limit; i--) {
1223
- if (!isRange(children[i])) n++;
1224
- }
1225
- result2 = children.slice(i + 1, ix + 1);
1226
- }
1227
- if (children[REF]) result2[REF] = children[REF];
1228
- if (children[PRE]) result2[PRE] = children[PRE];
1229
- return result2;
1230
- }
1231
- const result = construct(rootGraph, rootQuery);
1232
- return result;
1233
- }
1234
- function deValNull(graph) {
1235
- if (typeof graph !== "object" || !graph) return graph;
1236
- if ("$val" in graph && graph.$val !== true) return graph.$val;
1237
- for (const prop in graph) graph[prop] = deValNull(graph[prop]);
1238
- return graph;
1239
- }
1240
- function addPageMeta(graph, args) {
1241
- if (args.$all) {
1242
- Object.assign(graph, { $page: args, $prev: null, $next: null });
1243
- return;
1244
- }
1245
- const [{ $first, $last, ...bounds }, filter] = splitArgs(args);
1246
- const count = $first || $last;
1247
- const $page = { ...filter, ...bounds, $all: true };
1248
- if (graph.length === count) {
1249
- if ($first) {
1250
- const boundKey = graph[graph.length - 1].$key;
1251
- $page.$until = isDef(boundKey?.$cursor) ? boundKey.$cursor : boundKey;
1252
- delete $page.$before;
1253
- } else {
1254
- const boundKey = graph[0].$key;
1255
- $page.$since = isDef(boundKey?.$cursor) ? boundKey.$cursor : boundKey;
1256
- delete $page.$after;
1257
- }
1258
- }
1259
- const $prev = isDef($page.$after) ? { ...filter, $last: count, $until: $page.$after } : isDef($page.$since) ? { ...filter, $last: count, $before: $page.$since } : null;
1260
- const $next = isDef($page.$before) ? { ...filter, $first: count, $since: $page.$before } : isDef($page.$until) ? { ...filter, $first: count, $after: $page.$until } : null;
1261
- Object.assign(graph, { $page, $next, $prev });
1262
- }
1263
- const ROOT_KEY = /* @__PURE__ */ Symbol();
1264
- function encode$1(value, { version, isGraph } = {}) {
1265
- const links = [];
1266
- function pushLink($ref, $ver, props2, $val, $chi) {
1267
- const [range, _] = splitRef($ref);
1268
- const node = !isEmpty(props2) ? makeNode2(range ? [{ $key: range, ...props2 }] : props2, void 0, $ver) : isDef($chi) ? makeNode2(range ? [{ $key: range, $chi }] : $chi, void 0, $ver) : null;
1269
- const children = node ? node.children : isDef($val) ? $val : isGraph ? void 0 : 1;
1270
- if (children) {
1271
- links.push(wrap(children, encode$2($ref), $ver, !!range)[0]);
1272
- }
1273
- }
1274
- const combine = isGraph ? merge : add;
1275
- function makeNode2(object, key, ver, parentPuts = []) {
1276
- if (!isDef(object)) return;
1277
- const { $key, $ver, $ref, $val, $chi, $put, ...props2 } = object || {};
1278
- if (typeof object === "object" && object && !Array.isArray(object)) {
1279
- object = {
1280
- ...Object.fromEntries(
1281
- Object.entries({
1282
- $key,
1283
- $ver,
1284
- $ref,
1285
- $val,
1286
- $chi,
1287
- $put
1288
- }).filter(([_, val]) => isDef(val))
1289
- ),
1290
- ...props2
1291
- };
1292
- }
1293
- if (typeof object === "object" && object && isEmpty(object)) return;
1294
- if (isDef($ver)) ver = $ver;
1295
- if (isPlainObject($key)) {
1296
- const [page, filter] = splitArgs($key);
1297
- if (page) {
1298
- const foundPuts = parentPuts.filter(([_, putFilter]) => isEqual(filter, putFilter)).map(([range]) => range);
1299
- if (isGraph && !isDef(page.$cursor) && ($ref || $val || $chi || $put || !isEmpty(props2))) {
1300
- object.$key = filter || {};
1301
- object.$put = foundPuts;
1302
- const node2 = makeNode2(object, key, ver);
1303
- if (!filter) node2.key = MIN_KEY;
1304
- node2.prefix = true;
1305
- return node2;
1306
- }
1307
- if ((!isDef(key) || Number.isInteger(key)) && (filter || isDef(page.$cursor))) {
1308
- object.$key = isDef(page.$cursor) ? page.$cursor : page;
1309
- const wrapper = { $key: filter || {}, $chi: [object] };
1310
- if (isGraph) wrapper.$put = foundPuts;
1311
- const node2 = makeNode2(wrapper, key, ver);
1312
- if (!filter) node2.key = MIN_KEY;
1313
- node2.prefix = true;
1314
- return node2;
1315
- }
1316
- }
1317
- }
1318
- let putRange = [];
1319
- const prefixPuts = [];
1320
- if (Array.isArray(object) && !isDef($put) && !isDef($val) && !object.some((it) => isDef(it?.$key))) {
1321
- putRange = [encode$3({ $since: 0, $until: Number.POSITIVE_INFINITY })];
1322
- }
1323
- function classifyPut(put) {
1324
- const [range, filter] = splitArgs(put);
1325
- if (filter) {
1326
- prefixPuts.push([range, filter]);
1327
- } else {
1328
- putRange.push(encode$3(put));
1329
- }
1330
- }
1331
- if ($put === true) {
1332
- putRange = [{ key: MIN_KEY, end: MAX_KEY }];
1333
- } else if (Array.isArray($put)) {
1334
- $put.forEach(classifyPut);
1335
- } else if (isDef($put)) {
1336
- classifyPut($put);
1337
- }
1338
- if (isDef($key) && (Number.isInteger(key) || !isDef(key))) key = $key;
1339
- const node = key === ROOT_KEY || !isDef(key) ? {} : encode$3(key);
1340
- node.version = ver;
1341
- if (object === null) {
1342
- node.end = node.key;
1343
- } else if (isDef($key) && isDef(key) && key !== $key) {
1344
- node.children = [makeNode2(object, void 0, ver, prefixPuts)].filter(
1345
- Boolean
1346
- );
1347
- return node;
1348
- } else if ($ref) {
1349
- pushLink($ref, node.version, props2, $val, $chi);
1350
- if (!isGraph) return;
1351
- node.path = encode$2($ref);
1352
- } else if ($val === true) {
1353
- node.value = Array.isArray(object) ? clone$1(object) : props2;
1354
- } else if (isDef($val)) {
1355
- node.value = $val;
1356
- } else if (typeof object !== "object") {
1357
- node.value = isGraph || typeof object === "number" ? object : 1;
1358
- } else if (isDef($chi)) {
1359
- const children = $chi.map((obj) => makeNode2(obj, void 0, ver, prefixPuts)).filter(Boolean).sort((a, b) => cmp(a.key, b.key));
1360
- if (children.length) {
1361
- node.children = children;
1362
- }
1363
- } else if (Array.isArray(object)) {
1364
- const children = object.map((obj, i) => makeNode2(obj, i, ver, prefixPuts)).filter(Boolean).reduce((acc, it) => {
1365
- combine(acc, [it]);
1366
- return acc;
1367
- }, []);
1368
- if (children.length) {
1369
- node.children = children;
1370
- }
1371
- } else {
1372
- const children = Object.keys(props2).sort().map((key2) => makeNode2(object[key2], key2, ver)).filter(Boolean);
1373
- if (children.length) {
1374
- node.children = children;
1375
- } else if (putRange.length) ;
1376
- else if (isGraph) {
1377
- if (!(isDef($key) || isDef($put))) return;
1378
- if (node.key && !node.end) node.end = node.key;
1379
- } else {
1380
- if (!isDef($key)) return;
1381
- node.value = 1;
1382
- }
1383
- }
1384
- if (isGraph && putRange.length && !isDef(node.path) && !isDef(node.value)) {
1385
- const putRangeClone = putRange.map(({ key: key2, end }) => ({
1386
- key: key2,
1387
- end,
1388
- version: 0
1389
- }));
1390
- node.children = merge(putRangeClone, node.children || []);
1391
- }
1392
- if (
1393
- // (key === ROOT_KEY || isDef(node.key)) &&
1394
- node.children?.length || isDef(node.end) || isDef(node.value) || isDef(node.path)
1395
- ) {
1396
- return node;
1397
- }
1398
- }
1399
- if (value?.$key) value = [value];
1400
- const result = makeNode2(value, ROOT_KEY, version)?.children || [];
1401
- while (links.length) {
1402
- combine(result, [links.pop()]);
1403
- }
1404
- return result;
1405
- }
1406
- function encodeGraph(obj, version = Date.now()) {
1407
- const encoded = encode$1(obj, { version, isGraph: true });
1408
- const versioned = setVersion(encoded, version, true);
1409
- return versioned;
1410
- }
1411
- function encodeQuery(obj, version = 0) {
1412
- return encode$1(obj, { version, isGraph: false });
1413
- }
1414
- let customAlphabet = (alphabet, defaultSize = 21) => {
1415
- return (size = defaultSize) => {
1416
- let id2 = "";
1417
- let i = size | 0;
1418
- while (i--) {
1419
- id2 += alphabet[Math.random() * alphabet.length | 0];
1420
- }
1421
- return id2;
1422
- };
1423
- };
1424
- const alpha = "-0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ_abcdefghijklmnopqrstuvwxyz";
1425
- const id = customAlphabet(alpha, 20);
1426
- function getByte(view, offset) {
1427
- return offset < view.byteLength ? view.getUint8(offset) : 0;
1428
- }
1429
- function getChar(string, offset) {
1430
- return offset < string.length ? alpha.indexOf(string[offset]) : 0;
1431
- }
1432
- function encode(u8Arr) {
1433
- const { buffer, byteOffset, byteLength } = u8Arr;
1434
- const view = new DataView(buffer, byteOffset, byteLength);
1435
- let str = "";
1436
- for (let i = 0; i < view.byteLength; i += 3) {
1437
- let value = (getByte(view, i) << 16) + (getByte(view, i + 1) << 8) + getByte(view, i + 2);
1438
- let gstr = "";
1439
- for (let j = 0; j < 4; j++) {
1440
- gstr = alpha[value & 63] + gstr;
1441
- value = value >> 6 | 0;
1442
- }
1443
- str += gstr;
1444
- }
1445
- return str.substring(0, Math.ceil(view.byteLength * 4 / 3));
1446
- }
1447
- function decode(string, start = 0) {
1448
- const buffer = new ArrayBuffer(Math.floor((string.length - start) * 3 / 4));
1449
- const view = new DataView(buffer);
1450
- for (let i = start; i < string.length; i += 4) {
1451
- let value = (getChar(string, i) << 18) + (getChar(string, i + 1) << 12) + (getChar(string, i + 2) << 6) + getChar(string, i + 3);
1452
- for (let j = i * 3 / 4 + 2; j >= i * 3 / 4; j--) {
1453
- if (j < view.byteLength) view.setUint8(j, value & 255);
1454
- value = value >> 8 | 0;
1455
- }
1456
- }
1457
- return addStringify(new Uint8Array(buffer));
1458
- }
1459
- const props = [
1460
- "end",
1461
- "version",
1462
- "limit",
1463
- "value",
1464
- "path",
1465
- "prefix",
1466
- "children"
1467
- ];
1468
- function serializeKey(key) {
1469
- if (key[0] === STR) {
1470
- const last = key[key.length - 1];
1471
- if (last !== 0 && last !== 255) {
1472
- return decode$4(key);
1473
- }
1474
- }
1475
- return `\0${encode(key)}`;
1476
- }
1477
- function deserializeKey(key) {
1478
- if (key[0] === "\0") return decode(key.slice(1));
1479
- return encode$4(key);
1480
- }
1481
- function pack(children, parentVersion) {
1482
- if (!Array.isArray(children)) return children;
1483
- const array = children.map(
1484
- (node) => props.reduce(
1485
- (array2, prop, i) => {
1486
- if (!(prop in node)) return array2;
1487
- let value = node[prop];
1488
- if (prop === "version" && value === parentVersion) return array2;
1489
- if (prop === "children") value = pack(value, node.version);
1490
- if (prop === "end") value = serializeKey(value);
1491
- if (prop === "path") value = value.map(serializeKey);
1492
- array2[1] |= 1 << i;
1493
- array2.push(value);
1494
- return array2;
1495
- },
1496
- [serializeKey(node.key), 0]
1497
- )
1498
- );
1499
- return array;
1500
- }
1501
- function unpack(children, parentVersion) {
1502
- if (!Array.isArray(children)) return children;
1503
- const node = children.map(
1504
- ([key, type, ...values]) => props.reduce(
1505
- (node2, prop, i) => {
1506
- if (!(type & 1 << i)) return node2;
1507
- let value = values.shift();
1508
- if (prop === "children") value = unpack(value, node2.version);
1509
- if (prop === "end") value = deserializeKey(value);
1510
- if (prop === "path") value = value.map(deserializeKey);
1511
- node2[prop] = value;
1512
- return node2;
1513
- },
1514
- { key: deserializeKey(key), version: parentVersion }
1515
- )
1516
- );
1517
- return node;
1518
- }
1519
- function mergeObject(base, change) {
1520
- if (typeof change !== "object" || typeof base !== "object" || !base || !change) {
1521
- return change;
1522
- }
1523
- for (const prop in change) {
1524
- if (prop in base) {
1525
- const value = mergeObject(base[prop], change[prop]);
1526
- if (value === null) {
1527
- delete base[prop];
1528
- } else {
1529
- base[prop] = value;
1530
- }
1531
- } else {
1532
- base[prop] = change[prop];
1533
- }
1534
- }
1535
- return isEmpty(base) ? null : base;
1536
- }
1537
- function cloneObject(object) {
1538
- if (typeof object !== "object" || !object) {
1539
- return object;
1540
- }
1541
- const clone2 = {};
1542
- for (const prop in object) {
1543
- const value = cloneObject(object[prop]);
1544
- if (value === null) continue;
1545
- clone2[prop] = value;
1546
- }
1547
- return isEmpty(clone2) ? null : clone2;
1548
- }
1549
- function wrapObject(object, path) {
1550
- if (!Array.isArray(path)) throw Error(`wrapObject.path_not_array ${path}`);
1551
- for (let i = path.length - 1; i >= 0; i--) {
1552
- const $key = path[i];
1553
- if (typeof $key === "string") {
1554
- object = { [$key]: object };
1555
- } else if (Array.isArray(object)) {
1556
- object = [{ $key, $chi: object }];
1557
- } else {
1558
- object = [{ $key, ...object }];
1559
- }
1560
- }
1561
- return object;
1562
- }
1563
- function unwrapObject(object, path) {
1564
- if (!Array.isArray(path)) throw Error(`unwrapObject.path_not_array ${path}`);
1565
- for (let i = 0; i < path.length; i++) {
1566
- if (!object || typeof object !== "object") return;
1567
- const $key = path[i];
1568
- if (typeof $key === "string") {
1569
- if (Array.isArray(object)) {
1570
- throw Error(`unwrapObject.string_key_array:${$key}`);
1571
- }
1572
- object = object[$key];
1573
- } else {
1574
- if (!Array.isArray(object)) {
1575
- throw Error(`unwrapObject.arg_key_object:${JSON.stringify($key)}`);
1576
- }
1577
- const [page, filter] = splitArgs($key);
1578
- if (page && !page.$cursor) {
1579
- return object;
1580
- }
1581
- const target = page?.$cursor ? { ...filter, $cursor: page.$cursor } : filter;
1582
- object = object.find(({ $key: $key2 }) => isEqual($key2, target));
1583
- }
1584
- }
1585
- return object;
1586
- }
1587
- function makeWatcher() {
1588
- const listeners = /* @__PURE__ */ new Set();
1589
- function write(change) {
1590
- for (const push of listeners) push(change);
1591
- }
1592
- function watch(...args) {
1593
- return stream.makeStream((push, _end) => {
1594
- listeners.add(push);
1595
- if (args.length) Promise.resolve(args[0]).then(push);
1596
- return () => listeners.delete(push);
1597
- });
1598
- }
1599
- return { write, watch };
1600
- }
1601
- async function* mergeStreams(...streams) {
1602
- const firstValues = (await Promise.all(streams.map((stream2) => stream2.next()))).map((iter) => iter.value);
1603
- if (firstValues.some((value) => typeof value === "undefined")) {
1604
- yield void 0;
1605
- for (const value of firstValues) {
1606
- if (typeof value !== "undefined") yield value;
1607
- }
1608
- } else {
1609
- const merged = [];
1610
- for (const value of firstValues) merge(merged, value);
1611
- yield merged;
1612
- }
1613
- yield* mergeIterators(streams);
1614
- }
1615
- exports.IS_VAL = IS_VAL;
1616
- exports.MAX_KEY = MAX_KEY;
1617
- exports.MIN_KEY = MIN_KEY;
1618
- exports.add = add;
1619
- exports.addStringify = addStringify;
1620
- exports.clone = clone$1;
1621
- exports.cloneObject = cloneObject;
1622
- exports.cmp = cmp;
1623
- exports.decodeArgs = decode$3;
1624
- exports.decodeGraph = decodeGraph;
1625
- exports.decodePath = decode$2;
1626
- exports.decodeQuery = decodeQuery;
1627
- exports.decodeValue = decode$4;
1628
- exports.decorate = decorate;
1629
- exports.encodeArgs = encode$3;
1630
- exports.encodeGraph = encodeGraph;
1631
- exports.encodePath = encode$2;
1632
- exports.encodeQuery = encodeQuery;
1633
- exports.encodeValue = encode$4;
1634
- exports.err = err;
1635
- exports.errIf = errIf;
1636
- exports.finalize = finalize;
1637
- exports.find = find;
1638
- exports.findFirst = findFirst;
1639
- exports.findLast = findLast;
1640
- exports.getKnown = getKnown;
1641
- exports.getNodeValue = getNodeValue;
1642
- exports.isBranch = isBranch;
1643
- exports.isDef = isDef;
1644
- exports.isEmpty = isEmpty;
1645
- exports.isLink = isLink;
1646
- exports.isMaxKey = isMaxKey;
1647
- exports.isMinKey = isMinKey;
1648
- exports.isNewer = isNewer;
1649
- exports.isOlder = isOlder;
1650
- exports.isPlainObject = isPlainObject;
1651
- exports.isPrefix = isPrefix;
1652
- exports.isRange = isRange;
1653
- exports.keyAfter = keyAfter;
1654
- exports.keyBefore = keyBefore;
1655
- exports.keyStep = keyStep;
1656
- exports.makeId = id;
1657
- exports.makeWatcher = makeWatcher;
1658
- exports.merge = merge;
1659
- exports.mergeObject = mergeObject;
1660
- exports.mergeStreams = mergeStreams;
1661
- exports.pack = pack;
1662
- exports.remove = remove;
1663
- exports.setVersion = setVersion;
1664
- exports.sieve = sieve;
1665
- exports.slice = slice;
1666
- exports.splitArgs = splitArgs;
1667
- exports.splitRef = splitRef;
1668
- exports.unpack = unpack;
1669
- exports.unwrap = unwrap;
1670
- exports.unwrapObject = unwrapObject;
1671
- exports.wrap = wrap;
1672
- exports.wrapObject = wrapObject;
1673
- exports.wrapValue = wrapValue;