@arcote.tech/arc-react 0.0.5 → 0.0.7

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 (2) hide show
  1. package/dist/index.js +7 -1647
  2. package/package.json +3 -3
package/dist/index.js CHANGED
@@ -1,1651 +1,7 @@
1
- // ../../node_modules/mutative/dist/mutative.esm.mjs
2
- function latest(proxyDraft) {
3
- var _a;
4
- return (_a = proxyDraft.copy) !== null && _a !== undefined ? _a : proxyDraft.original;
5
- }
6
- function isDraft(target) {
7
- return !!getProxyDraft(target);
8
- }
9
- function getProxyDraft(value) {
10
- if (typeof value !== "object")
11
- return null;
12
- return value === null || value === undefined ? undefined : value[PROXY_DRAFT];
13
- }
14
- function getValue(value) {
15
- var _a;
16
- const proxyDraft = getProxyDraft(value);
17
- return proxyDraft ? (_a = proxyDraft.copy) !== null && _a !== undefined ? _a : proxyDraft.original : value;
18
- }
19
- function isDraftable(value, options) {
20
- if (!value || typeof value !== "object")
21
- return false;
22
- let markResult;
23
- return Object.getPrototypeOf(value) === Object.prototype || Array.isArray(value) || value instanceof Map || value instanceof Set || !!(options === null || options === undefined ? undefined : options.mark) && ((markResult = options.mark(value, dataTypes)) === dataTypes.immutable || typeof markResult === "function");
24
- }
25
- function getPath(target, path = []) {
26
- if (Object.hasOwnProperty.call(target, "key")) {
27
- const proxyDraft = getProxyDraft(get(target.parent.copy, target.key));
28
- if (proxyDraft !== null && (proxyDraft === null || proxyDraft === undefined ? undefined : proxyDraft.original) !== target.original) {
29
- return null;
30
- }
31
- path.push(target.parent.type === 3 ? Array.from(target.parent.setMap.keys()).indexOf(target.key) : target.key);
32
- }
33
- if (target.parent) {
34
- return getPath(target.parent, path);
35
- }
36
- return path.reverse();
37
- }
38
- function getType(target) {
39
- if (Array.isArray(target))
40
- return 1;
41
- if (target instanceof Map)
42
- return 2;
43
- if (target instanceof Set)
44
- return 3;
45
- return 0;
46
- }
47
- function get(target, key) {
48
- return getType(target) === 2 ? target.get(key) : target[key];
49
- }
50
- function set(target, key, value) {
51
- const type = getType(target);
52
- if (type === 2) {
53
- target.set(key, value);
54
- } else {
55
- target[key] = value;
56
- }
57
- }
58
- function peek(target, key) {
59
- const state = getProxyDraft(target);
60
- const source = state ? latest(state) : target;
61
- return source[key];
62
- }
63
- function isEqual(x, y) {
64
- if (x === y) {
65
- return x !== 0 || 1 / x === 1 / y;
66
- } else {
67
- return x !== x && y !== y;
68
- }
69
- }
70
- function revokeProxy(proxyDraft) {
71
- if (!proxyDraft)
72
- return;
73
- while (proxyDraft.finalities.revoke.length > 0) {
74
- const revoke = proxyDraft.finalities.revoke.pop();
75
- revoke();
76
- }
77
- }
78
- function escapePath(path, pathAsArray) {
79
- return pathAsArray ? path : [""].concat(path).map((_item) => {
80
- const item = `${_item}`;
81
- if (item.indexOf("/") === -1 && item.indexOf("~") === -1)
82
- return item;
83
- return item.replace(/~/g, "~0").replace(/\//g, "~1");
84
- }).join("/");
85
- }
86
- function unescapePath(path) {
87
- if (Array.isArray(path))
88
- return path;
89
- return path.split("/").map((_item) => _item.replace(/~1/g, "/").replace(/~0/g, "~")).slice(1);
90
- }
91
- function strictCopy(target) {
92
- const copy = Object.create(Object.getPrototypeOf(target));
93
- Reflect.ownKeys(target).forEach((key) => {
94
- let desc = Reflect.getOwnPropertyDescriptor(target, key);
95
- if (desc.enumerable && desc.configurable && desc.writable) {
96
- copy[key] = target[key];
97
- return;
98
- }
99
- if (!desc.writable) {
100
- desc.writable = true;
101
- desc.configurable = true;
102
- }
103
- if (desc.get || desc.set)
104
- desc = {
105
- configurable: true,
106
- writable: true,
107
- enumerable: desc.enumerable,
108
- value: target[key]
109
- };
110
- Reflect.defineProperty(copy, key, desc);
111
- });
112
- return copy;
113
- }
114
- function shallowCopy(original, options) {
115
- let markResult;
116
- if (Array.isArray(original)) {
117
- return Array.prototype.concat.call(original);
118
- } else if (original instanceof Set) {
119
- return new Set(original.values());
120
- } else if (original instanceof Map) {
121
- return new Map(original);
122
- } else if ((options === null || options === undefined ? undefined : options.mark) && (markResult = options.mark(original, dataTypes), markResult !== undefined) && markResult !== dataTypes.mutable) {
123
- if (markResult === dataTypes.immutable) {
124
- return strictCopy(original);
125
- } else if (typeof markResult === "function") {
126
- if (options.enablePatches || options.enableAutoFreeze) {
127
- throw new Error(`You can't use mark and patches or auto freeze together.`);
128
- }
129
- return markResult();
130
- }
131
- throw new Error(`Unsupported mark result: ${markResult}`);
132
- } else if (typeof original === "object" && Object.getPrototypeOf(original) === Object.prototype) {
133
- const copy = {};
134
- Object.keys(original).forEach((key) => {
135
- copy[key] = original[key];
136
- });
137
- Object.getOwnPropertySymbols(original).forEach((key) => {
138
- if (propIsEnum.call(original, key)) {
139
- copy[key] = original[key];
140
- }
141
- });
142
- return copy;
143
- } else {
144
- throw new Error(`Please check mark() to ensure that it is a stable marker draftable function.`);
145
- }
146
- }
147
- function ensureShallowCopy(target) {
148
- if (target.copy)
149
- return;
150
- target.copy = shallowCopy(target.original, target.options);
151
- }
152
- function deepClone(target) {
153
- if (!isDraftable(target))
154
- return getValue(target);
155
- if (Array.isArray(target))
156
- return target.map(deepClone);
157
- if (target instanceof Map)
158
- return new Map(Array.from(target.entries()).map(([k, v]) => [k, deepClone(v)]));
159
- if (target instanceof Set)
160
- return new Set(Array.from(target).map(deepClone));
161
- const copy = Object.create(Object.getPrototypeOf(target));
162
- for (const key in target)
163
- copy[key] = deepClone(target[key]);
164
- return copy;
165
- }
166
- function cloneIfNeeded(target) {
167
- return isDraft(target) ? deepClone(target) : target;
168
- }
169
- function markChanged(proxyDraft) {
170
- var _a;
171
- proxyDraft.assignedMap = (_a = proxyDraft.assignedMap) !== null && _a !== undefined ? _a : new Map;
172
- if (!proxyDraft.operated) {
173
- proxyDraft.operated = true;
174
- if (proxyDraft.parent) {
175
- markChanged(proxyDraft.parent);
176
- }
177
- }
178
- }
179
- function throwFrozenError() {
180
- throw new Error("Cannot modify frozen object");
181
- }
182
- function deepFreeze(target, subKey, updatedValues, stack, keys) {
183
- {
184
- updatedValues = updatedValues !== null && updatedValues !== undefined ? updatedValues : new WeakMap;
185
- stack = stack !== null && stack !== undefined ? stack : [];
186
- keys = keys !== null && keys !== undefined ? keys : [];
187
- const value = updatedValues.has(target) ? updatedValues.get(target) : target;
188
- if (stack.length > 0) {
189
- const index = stack.indexOf(value);
190
- if (value && typeof value === "object" && index !== -1) {
191
- if (stack[0] === value) {
192
- throw new Error(`Forbids circular reference`);
193
- }
194
- throw new Error(`Forbids circular reference: ~/${keys.slice(0, index).map((key, index2) => {
195
- if (typeof key === "symbol")
196
- return `[${key.toString()}]`;
197
- const parent = stack[index2];
198
- if (typeof key === "object" && (parent instanceof Map || parent instanceof Set))
199
- return Array.from(parent.keys()).indexOf(key);
200
- return key;
201
- }).join("/")}`);
202
- }
203
- stack.push(value);
204
- keys.push(subKey);
205
- } else {
206
- stack.push(value);
207
- }
208
- }
209
- if (Object.isFrozen(target) || isDraft(target)) {
210
- {
211
- stack.pop();
212
- keys.pop();
213
- }
214
- return;
215
- }
216
- const type = getType(target);
217
- switch (type) {
218
- case 2:
219
- for (const [key, value] of target) {
220
- deepFreeze(key, key, updatedValues, stack, keys);
221
- deepFreeze(value, key, updatedValues, stack, keys);
222
- }
223
- target.set = target.clear = target.delete = throwFrozenError;
224
- break;
225
- case 3:
226
- for (const value of target) {
227
- deepFreeze(value, value, updatedValues, stack, keys);
228
- }
229
- target.add = target.clear = target.delete = throwFrozenError;
230
- break;
231
- case 1:
232
- Object.freeze(target);
233
- let index = 0;
234
- for (const value of target) {
235
- deepFreeze(value, index, updatedValues, stack, keys);
236
- index += 1;
237
- }
238
- break;
239
- default:
240
- Object.freeze(target);
241
- Object.keys(target).forEach((name) => {
242
- const value = target[name];
243
- deepFreeze(value, name, updatedValues, stack, keys);
244
- });
245
- }
246
- {
247
- stack.pop();
248
- keys.pop();
249
- }
250
- }
251
- function has(target, key) {
252
- return target instanceof Map ? target.has(key) : Object.prototype.hasOwnProperty.call(target, key);
253
- }
254
- function getDescriptor(target, key) {
255
- if (key in target) {
256
- let prototype = Reflect.getPrototypeOf(target);
257
- while (prototype) {
258
- const descriptor = Reflect.getOwnPropertyDescriptor(prototype, key);
259
- if (descriptor)
260
- return descriptor;
261
- prototype = Reflect.getPrototypeOf(prototype);
262
- }
263
- }
264
- return;
265
- }
266
- function forEach(target, iter) {
267
- const type = getType(target);
268
- if (type === 0) {
269
- Reflect.ownKeys(target).forEach((key) => {
270
- iter(key, target[key], target);
271
- });
272
- } else if (type === 1) {
273
- let index = 0;
274
- for (const entry of target) {
275
- iter(index, entry, target);
276
- index += 1;
277
- }
278
- } else {
279
- target.forEach((entry, index) => iter(index, entry, target));
280
- }
281
- }
282
- function handleValue(target, handledSet, options) {
283
- if (isDraft(target) || !isDraftable(target, options) || handledSet.has(target) || Object.isFrozen(target))
284
- return;
285
- const isSet = target instanceof Set;
286
- const setMap = isSet ? new Map : undefined;
287
- handledSet.add(target);
288
- forEach(target, (key, value) => {
289
- var _a;
290
- if (isDraft(value)) {
291
- const proxyDraft = getProxyDraft(value);
292
- ensureShallowCopy(proxyDraft);
293
- const updatedValue = ((_a = proxyDraft.assignedMap) === null || _a === undefined ? undefined : _a.size) || proxyDraft.operated ? proxyDraft.copy : proxyDraft.original;
294
- set(isSet ? setMap : target, key, updatedValue);
295
- } else {
296
- handleValue(value, handledSet, options);
297
- }
298
- });
299
- if (setMap) {
300
- const set2 = target;
301
- const values = Array.from(set2);
302
- set2.clear();
303
- values.forEach((value) => {
304
- set2.add(setMap.has(value) ? setMap.get(value) : value);
305
- });
306
- }
307
- }
308
- function finalizeAssigned(proxyDraft, key) {
309
- const copy = proxyDraft.type === 3 ? proxyDraft.setMap : proxyDraft.copy;
310
- if (proxyDraft.finalities.revoke.length > 1 && proxyDraft.assignedMap.get(key) && copy) {
311
- handleValue(get(copy, key), proxyDraft.finalities.handledSet, proxyDraft.options);
312
- }
313
- }
314
- function finalizeSetValue(target) {
315
- if (target.type === 3 && target.copy) {
316
- target.copy.clear();
317
- target.setMap.forEach((value) => {
318
- target.copy.add(getValue(value));
319
- });
320
- }
321
- }
322
- function finalizePatches(target, generatePatches, patches, inversePatches) {
323
- const shouldFinalize = target.operated && target.assignedMap && target.assignedMap.size > 0 && !target.finalized;
324
- if (shouldFinalize) {
325
- if (patches && inversePatches) {
326
- const basePath = getPath(target);
327
- if (basePath) {
328
- generatePatches(target, basePath, patches, inversePatches);
329
- }
330
- }
331
- target.finalized = true;
332
- }
333
- }
334
- function markFinalization(target, key, value, generatePatches) {
335
- const proxyDraft = getProxyDraft(value);
336
- if (proxyDraft) {
337
- if (!proxyDraft.callbacks) {
338
- proxyDraft.callbacks = [];
339
- }
340
- proxyDraft.callbacks.push((patches, inversePatches) => {
341
- var _a;
342
- const copy = target.type === 3 ? target.setMap : target.copy;
343
- if (isEqual(get(copy, key), value)) {
344
- let updatedValue = proxyDraft.original;
345
- if (proxyDraft.copy) {
346
- updatedValue = proxyDraft.copy;
347
- }
348
- finalizeSetValue(target);
349
- finalizePatches(target, generatePatches, patches, inversePatches);
350
- if (target.options.enableAutoFreeze) {
351
- target.options.updatedValues = (_a = target.options.updatedValues) !== null && _a !== undefined ? _a : new WeakMap;
352
- target.options.updatedValues.set(updatedValue, proxyDraft.original);
353
- }
354
- set(copy, key, updatedValue);
355
- }
356
- });
357
- if (target.options.enableAutoFreeze) {
358
- if (proxyDraft.finalities !== target.finalities) {
359
- target.options.enableAutoFreeze = false;
360
- }
361
- }
362
- }
363
- if (isDraftable(value, target.options)) {
364
- target.finalities.draft.push(() => {
365
- const copy = target.type === 3 ? target.setMap : target.copy;
366
- if (isEqual(get(copy, key), value)) {
367
- finalizeAssigned(target, key);
368
- }
369
- });
370
- }
371
- }
372
- function generateArrayPatches(proxyState, basePath, patches, inversePatches, pathAsArray) {
373
- let { original, assignedMap, options } = proxyState;
374
- let copy = proxyState.copy;
375
- if (copy.length < original.length) {
376
- [original, copy] = [copy, original];
377
- [patches, inversePatches] = [inversePatches, patches];
378
- }
379
- for (let index = 0;index < original.length; index += 1) {
380
- if (assignedMap.get(index.toString()) && copy[index] !== original[index]) {
381
- const _path = basePath.concat([index]);
382
- const path = escapePath(_path, pathAsArray);
383
- patches.push({
384
- op: Operation.Replace,
385
- path,
386
- value: cloneIfNeeded(copy[index])
387
- });
388
- inversePatches.push({
389
- op: Operation.Replace,
390
- path,
391
- value: cloneIfNeeded(original[index])
392
- });
393
- }
394
- }
395
- for (let index = original.length;index < copy.length; index += 1) {
396
- const _path = basePath.concat([index]);
397
- const path = escapePath(_path, pathAsArray);
398
- patches.push({
399
- op: Operation.Add,
400
- path,
401
- value: cloneIfNeeded(copy[index])
402
- });
403
- }
404
- if (original.length < copy.length) {
405
- const { arrayLengthAssignment = true } = options.enablePatches;
406
- if (arrayLengthAssignment) {
407
- const _path = basePath.concat(["length"]);
408
- const path = escapePath(_path, pathAsArray);
409
- inversePatches.push({
410
- op: Operation.Replace,
411
- path,
412
- value: original.length
413
- });
414
- } else {
415
- for (let index = copy.length;original.length < index; index -= 1) {
416
- const _path = basePath.concat([index - 1]);
417
- const path = escapePath(_path, pathAsArray);
418
- inversePatches.push({
419
- op: Operation.Remove,
420
- path
421
- });
422
- }
423
- }
424
- }
425
- }
426
- function generatePatchesFromAssigned({ original, copy, assignedMap }, basePath, patches, inversePatches, pathAsArray) {
427
- assignedMap.forEach((assignedValue, key) => {
428
- const originalValue = get(original, key);
429
- const value = cloneIfNeeded(get(copy, key));
430
- const op = !assignedValue ? Operation.Remove : has(original, key) ? Operation.Replace : Operation.Add;
431
- if (isEqual(originalValue, value) && op === Operation.Replace)
432
- return;
433
- const _path = basePath.concat(key);
434
- const path = escapePath(_path, pathAsArray);
435
- patches.push(op === Operation.Remove ? { op, path } : { op, path, value });
436
- inversePatches.push(op === Operation.Add ? { op: Operation.Remove, path } : op === Operation.Remove ? { op: Operation.Add, path, value: originalValue } : { op: Operation.Replace, path, value: originalValue });
437
- });
438
- }
439
- function generateSetPatches({ original, copy }, basePath, patches, inversePatches, pathAsArray) {
440
- let index = 0;
441
- original.forEach((value) => {
442
- if (!copy.has(value)) {
443
- const _path = basePath.concat([index]);
444
- const path = escapePath(_path, pathAsArray);
445
- patches.push({
446
- op: Operation.Remove,
447
- path,
448
- value
449
- });
450
- inversePatches.unshift({
451
- op: Operation.Add,
452
- path,
453
- value
454
- });
455
- }
456
- index += 1;
457
- });
458
- index = 0;
459
- copy.forEach((value) => {
460
- if (!original.has(value)) {
461
- const _path = basePath.concat([index]);
462
- const path = escapePath(_path, pathAsArray);
463
- patches.push({
464
- op: Operation.Add,
465
- path,
466
- value
467
- });
468
- inversePatches.unshift({
469
- op: Operation.Remove,
470
- path,
471
- value
472
- });
473
- }
474
- index += 1;
475
- });
476
- }
477
- function generatePatches(proxyState, basePath, patches, inversePatches) {
478
- const { pathAsArray = true } = proxyState.options.enablePatches;
479
- switch (proxyState.type) {
480
- case 0:
481
- case 2:
482
- return generatePatchesFromAssigned(proxyState, basePath, patches, inversePatches, pathAsArray);
483
- case 1:
484
- return generateArrayPatches(proxyState, basePath, patches, inversePatches, pathAsArray);
485
- case 3:
486
- return generateSetPatches(proxyState, basePath, patches, inversePatches, pathAsArray);
487
- }
488
- }
489
- function createDraft(createDraftOptions) {
490
- const { original, parentDraft, key, finalities, options } = createDraftOptions;
491
- const type = getType(original);
492
- const proxyDraft = {
493
- type,
494
- finalized: false,
495
- parent: parentDraft,
496
- original,
497
- copy: null,
498
- proxy: null,
499
- finalities,
500
- options,
501
- setMap: type === 3 ? new Map(original.entries()) : undefined
502
- };
503
- if (key || "key" in createDraftOptions) {
504
- proxyDraft.key = key;
505
- }
506
- const { proxy, revoke } = Proxy.revocable(type === 1 ? Object.assign([], proxyDraft) : proxyDraft, proxyHandler);
507
- finalities.revoke.push(revoke);
508
- draftsCache.add(proxy);
509
- proxyDraft.proxy = proxy;
510
- if (parentDraft) {
511
- const target = parentDraft;
512
- target.finalities.draft.push((patches, inversePatches) => {
513
- var _a, _b;
514
- const oldProxyDraft = getProxyDraft(proxy);
515
- let copy = target.type === 3 ? target.setMap : target.copy;
516
- const draft = get(copy, key);
517
- const proxyDraft2 = getProxyDraft(draft);
518
- if (proxyDraft2) {
519
- let updatedValue = proxyDraft2.original;
520
- if (proxyDraft2.operated) {
521
- updatedValue = getValue(draft);
522
- }
523
- finalizeSetValue(proxyDraft2);
524
- finalizePatches(proxyDraft2, generatePatches, patches, inversePatches);
525
- if (target.options.enableAutoFreeze) {
526
- target.options.updatedValues = (_a = target.options.updatedValues) !== null && _a !== undefined ? _a : new WeakMap;
527
- target.options.updatedValues.set(updatedValue, proxyDraft2.original);
528
- }
529
- set(copy, key, updatedValue);
530
- }
531
- (_b = oldProxyDraft.callbacks) === null || _b === undefined || _b.forEach((callback) => {
532
- callback(patches, inversePatches);
533
- });
534
- });
535
- } else {
536
- const target = getProxyDraft(proxy);
537
- target.finalities.draft.push((patches, inversePatches) => {
538
- finalizeSetValue(target);
539
- finalizePatches(target, generatePatches, patches, inversePatches);
540
- });
541
- }
542
- return proxy;
543
- }
544
- function finalizeDraft(result, returnedValue, patches, inversePatches, enableAutoFreeze) {
545
- var _a;
546
- const proxyDraft = getProxyDraft(result);
547
- const original = (_a = proxyDraft === null || proxyDraft === undefined ? undefined : proxyDraft.original) !== null && _a !== undefined ? _a : result;
548
- const hasReturnedValue = !!returnedValue.length;
549
- if (proxyDraft === null || proxyDraft === undefined ? undefined : proxyDraft.operated) {
550
- while (proxyDraft.finalities.draft.length > 0) {
551
- const finalize = proxyDraft.finalities.draft.pop();
552
- finalize(patches, inversePatches);
553
- }
554
- }
555
- const state = hasReturnedValue ? returnedValue[0] : proxyDraft ? proxyDraft.operated ? proxyDraft.copy : proxyDraft.original : result;
556
- if (proxyDraft)
557
- revokeProxy(proxyDraft);
558
- if (enableAutoFreeze) {
559
- deepFreeze(state, state, proxyDraft === null || proxyDraft === undefined ? undefined : proxyDraft.options.updatedValues);
560
- }
561
- return [
562
- state,
563
- patches && hasReturnedValue ? [{ op: Operation.Replace, path: [], value: returnedValue[0] }] : patches,
564
- inversePatches && hasReturnedValue ? [{ op: Operation.Replace, path: [], value: original }] : inversePatches
565
- ];
566
- }
567
- function draftify(baseState, options) {
568
- var _a;
569
- const finalities = {
570
- draft: [],
571
- revoke: [],
572
- handledSet: new WeakSet
573
- };
574
- let patches;
575
- let inversePatches;
576
- if (options.enablePatches) {
577
- patches = [];
578
- inversePatches = [];
579
- }
580
- const isMutable = ((_a = options.mark) === null || _a === undefined ? undefined : _a.call(options, baseState, dataTypes)) === dataTypes.mutable || !isDraftable(baseState, options);
581
- const draft = isMutable ? baseState : createDraft({
582
- original: baseState,
583
- parentDraft: null,
584
- finalities,
585
- options
586
- });
587
- return [
588
- draft,
589
- (returnedValue = []) => {
590
- const [finalizedState, finalizedPatches, finalizedInversePatches] = finalizeDraft(draft, returnedValue, patches, inversePatches, options.enableAutoFreeze);
591
- return options.enablePatches ? [finalizedState, finalizedPatches, finalizedInversePatches] : finalizedState;
592
- }
593
- ];
594
- }
595
- function handleReturnValue(options) {
596
- const { rootDraft, value, useRawReturn = false, isRoot = true } = options;
597
- forEach(value, (key, item, source) => {
598
- const proxyDraft = getProxyDraft(item);
599
- if (proxyDraft && rootDraft && proxyDraft.finalities === rootDraft.finalities) {
600
- options.isContainDraft = true;
601
- const currentValue = proxyDraft.original;
602
- if (source instanceof Set) {
603
- const arr = Array.from(source);
604
- source.clear();
605
- arr.forEach((_item) => source.add(key === _item ? currentValue : _item));
606
- } else {
607
- set(source, key, currentValue);
608
- }
609
- } else if (typeof item === "object" && item !== null) {
610
- options.value = item;
611
- options.isRoot = false;
612
- handleReturnValue(options);
613
- }
614
- });
615
- if (isRoot) {
616
- if (!options.isContainDraft)
617
- console.warn(`The return value does not contain any draft, please use 'rawReturn()' to wrap the return value to improve performance.`);
618
- if (useRawReturn) {
619
- console.warn(`The return value contains drafts, please don't use 'rawReturn()' to wrap the return value.`);
620
- }
621
- }
622
- }
623
- function getCurrent(target) {
624
- const proxyDraft = getProxyDraft(target);
625
- if (!isDraftable(target, proxyDraft === null || proxyDraft === undefined ? undefined : proxyDraft.options))
626
- return target;
627
- const type = getType(target);
628
- if (proxyDraft && !proxyDraft.operated)
629
- return proxyDraft.original;
630
- let currentValue;
631
- function ensureShallowCopy2() {
632
- currentValue = type === 2 ? new Map(target) : type === 3 ? Array.from(proxyDraft.setMap.values()) : shallowCopy(target, proxyDraft === null || proxyDraft === undefined ? undefined : proxyDraft.options);
633
- }
634
- if (proxyDraft) {
635
- proxyDraft.finalized = true;
636
- try {
637
- ensureShallowCopy2();
638
- } finally {
639
- proxyDraft.finalized = false;
640
- }
641
- } else {
642
- currentValue = target;
643
- }
644
- forEach(currentValue, (key, value) => {
645
- if (proxyDraft && isEqual(get(proxyDraft.original, key), value))
646
- return;
647
- const newValue = getCurrent(value);
648
- if (newValue !== value) {
649
- if (currentValue === target)
650
- ensureShallowCopy2();
651
- set(currentValue, key, newValue);
652
- }
653
- });
654
- return type === 3 ? new Set(currentValue) : currentValue;
655
- }
656
- function current(target) {
657
- if (!isDraft(target)) {
658
- throw new Error(`current() is only used for Draft, parameter: ${target}`);
659
- }
660
- return getCurrent(target);
661
- }
662
- function apply(state, patches, applyOptions) {
663
- let i;
664
- for (i = patches.length - 1;i >= 0; i -= 1) {
665
- const { value, op, path } = patches[i];
666
- if (!path.length && op === Operation.Replace || path === "" && op === Operation.Add) {
667
- state = value;
668
- break;
669
- }
670
- }
671
- if (i > -1) {
672
- patches = patches.slice(i + 1);
673
- }
674
- const mutate = (draft) => {
675
- patches.forEach((patch) => {
676
- const { path: _path, op } = patch;
677
- const path = unescapePath(_path);
678
- let base = draft;
679
- for (let index = 0;index < path.length - 1; index += 1) {
680
- const parentType = getType(base);
681
- let key2 = path[index];
682
- if (typeof key2 !== "string" && typeof key2 !== "number") {
683
- key2 = String(key2);
684
- }
685
- if ((parentType === 0 || parentType === 1) && (key2 === "__proto__" || key2 === "constructor") || typeof base === "function" && key2 === "prototype") {
686
- throw new Error(`Patching reserved attributes like __proto__ and constructor is not allowed.`);
687
- }
688
- base = get(getType(base) === 3 ? Array.from(base) : base, key2);
689
- if (typeof base !== "object") {
690
- throw new Error(`Cannot apply patch at '${path.join("/")}'.`);
691
- }
692
- }
693
- const type = getType(base);
694
- const value = deepClone(patch.value);
695
- const key = path[path.length - 1];
696
- switch (op) {
697
- case Operation.Replace:
698
- switch (type) {
699
- case 2:
700
- return base.set(key, value);
701
- case 3:
702
- throw new Error(`Cannot apply replace patch to set.`);
703
- default:
704
- return base[key] = value;
705
- }
706
- case Operation.Add:
707
- switch (type) {
708
- case 1:
709
- return key === "-" ? base.push(value) : base.splice(key, 0, value);
710
- case 2:
711
- return base.set(key, value);
712
- case 3:
713
- return base.add(value);
714
- default:
715
- return base[key] = value;
716
- }
717
- case Operation.Remove:
718
- switch (type) {
719
- case 1:
720
- return base.splice(key, 1);
721
- case 2:
722
- return base.delete(key);
723
- case 3:
724
- return base.delete(patch.value);
725
- default:
726
- return delete base[key];
727
- }
728
- default:
729
- throw new Error(`Unsupported patch operation: ${op}.`);
730
- }
731
- });
732
- };
733
- if (isDraft(state)) {
734
- if (applyOptions !== undefined) {
735
- throw new Error(`Cannot apply patches with options to a draft.`);
736
- }
737
- mutate(state);
738
- return state;
739
- }
740
- return create(state, mutate, Object.assign(Object.assign({}, applyOptions), { enablePatches: false }));
741
- }
742
- var Operation = {
743
- Remove: "remove",
744
- Replace: "replace",
745
- Add: "add"
746
- };
747
- var PROXY_DRAFT = Symbol.for("__MUTATIVE_PROXY_DRAFT__");
748
- var RAW_RETURN_SYMBOL = Symbol("__MUTATIVE_RAW_RETURN_SYMBOL__");
749
- var iteratorSymbol = Symbol.iterator;
750
- var dataTypes = {
751
- mutable: "mutable",
752
- immutable: "immutable"
753
- };
754
- var internal = {};
755
- var propIsEnum = Object.prototype.propertyIsEnumerable;
756
- var readable = false;
757
- var checkReadable = (value, options, ignoreCheckDraftable = false) => {
758
- if (typeof value === "object" && value !== null && (!isDraftable(value, options) || ignoreCheckDraftable) && !readable) {
759
- throw new Error(`Strict mode: Mutable data cannot be accessed directly, please use 'unsafe(callback)' wrap.`);
760
- }
761
- };
762
- var mapHandler = {
763
- get size() {
764
- const current2 = latest(getProxyDraft(this));
765
- return current2.size;
766
- },
767
- has(key) {
768
- return latest(getProxyDraft(this)).has(key);
769
- },
770
- set(key, value) {
771
- const target = getProxyDraft(this);
772
- const source = latest(target);
773
- if (!source.has(key) || !isEqual(source.get(key), value)) {
774
- ensureShallowCopy(target);
775
- markChanged(target);
776
- target.assignedMap.set(key, true);
777
- target.copy.set(key, value);
778
- markFinalization(target, key, value, generatePatches);
779
- }
780
- return this;
781
- },
782
- delete(key) {
783
- if (!this.has(key)) {
784
- return false;
785
- }
786
- const target = getProxyDraft(this);
787
- ensureShallowCopy(target);
788
- markChanged(target);
789
- if (target.original.has(key)) {
790
- target.assignedMap.set(key, false);
791
- } else {
792
- target.assignedMap.delete(key);
793
- }
794
- target.copy.delete(key);
795
- return true;
796
- },
797
- clear() {
798
- const target = getProxyDraft(this);
799
- if (!this.size)
800
- return;
801
- ensureShallowCopy(target);
802
- markChanged(target);
803
- target.assignedMap = new Map;
804
- for (const [key] of target.original) {
805
- target.assignedMap.set(key, false);
806
- }
807
- target.copy.clear();
808
- },
809
- forEach(callback, thisArg) {
810
- const target = getProxyDraft(this);
811
- latest(target).forEach((_value, _key) => {
812
- callback.call(thisArg, this.get(_key), _key, this);
813
- });
814
- },
815
- get(key) {
816
- var _a, _b;
817
- const target = getProxyDraft(this);
818
- const value = latest(target).get(key);
819
- const mutable = ((_b = (_a = target.options).mark) === null || _b === undefined ? undefined : _b.call(_a, value, dataTypes)) === dataTypes.mutable;
820
- if (target.options.strict) {
821
- checkReadable(value, target.options, mutable);
822
- }
823
- if (mutable) {
824
- return value;
825
- }
826
- if (target.finalized || !isDraftable(value, target.options)) {
827
- return value;
828
- }
829
- if (value !== target.original.get(key)) {
830
- return value;
831
- }
832
- const draft = internal.createDraft({
833
- original: value,
834
- parentDraft: target,
835
- key,
836
- finalities: target.finalities,
837
- options: target.options
838
- });
839
- ensureShallowCopy(target);
840
- target.copy.set(key, draft);
841
- return draft;
842
- },
843
- keys() {
844
- return latest(getProxyDraft(this)).keys();
845
- },
846
- values() {
847
- const iterator = this.keys();
848
- return {
849
- [iteratorSymbol]: () => this.values(),
850
- next: () => {
851
- const result = iterator.next();
852
- if (result.done)
853
- return result;
854
- const value = this.get(result.value);
855
- return {
856
- done: false,
857
- value
858
- };
859
- }
860
- };
861
- },
862
- entries() {
863
- const iterator = this.keys();
864
- return {
865
- [iteratorSymbol]: () => this.entries(),
866
- next: () => {
867
- const result = iterator.next();
868
- if (result.done)
869
- return result;
870
- const value = this.get(result.value);
871
- return {
872
- done: false,
873
- value: [result.value, value]
874
- };
875
- }
876
- };
877
- },
878
- [iteratorSymbol]() {
879
- return this.entries();
880
- }
881
- };
882
- var mapHandlerKeys = Reflect.ownKeys(mapHandler);
883
- var getNextIterator = (target, iterator, { isValuesIterator }) => () => {
884
- var _a, _b;
885
- const result = iterator.next();
886
- if (result.done)
887
- return result;
888
- const key = result.value;
889
- let value = target.setMap.get(key);
890
- const currentDraft = getProxyDraft(value);
891
- const mutable = ((_b = (_a = target.options).mark) === null || _b === undefined ? undefined : _b.call(_a, value, dataTypes)) === dataTypes.mutable;
892
- if (target.options.strict) {
893
- checkReadable(key, target.options, mutable);
894
- }
895
- if (!mutable && !currentDraft && isDraftable(key, target.options) && !target.finalized && target.original.has(key)) {
896
- const proxy = internal.createDraft({
897
- original: key,
898
- parentDraft: target,
899
- key,
900
- finalities: target.finalities,
901
- options: target.options
902
- });
903
- target.setMap.set(key, proxy);
904
- value = proxy;
905
- } else if (currentDraft) {
906
- value = currentDraft.proxy;
907
- }
908
- return {
909
- done: false,
910
- value: isValuesIterator ? value : [value, value]
911
- };
912
- };
913
- var setHandler = {
914
- get size() {
915
- const target = getProxyDraft(this);
916
- return target.setMap.size;
917
- },
918
- has(value) {
919
- const target = getProxyDraft(this);
920
- if (target.setMap.has(value))
921
- return true;
922
- ensureShallowCopy(target);
923
- const valueProxyDraft = getProxyDraft(value);
924
- if (valueProxyDraft && target.setMap.has(valueProxyDraft.original))
925
- return true;
926
- return false;
927
- },
928
- add(value) {
929
- const target = getProxyDraft(this);
930
- if (!this.has(value)) {
931
- ensureShallowCopy(target);
932
- markChanged(target);
933
- target.assignedMap.set(value, true);
934
- target.setMap.set(value, value);
935
- markFinalization(target, value, value, generatePatches);
936
- }
937
- return this;
938
- },
939
- delete(value) {
940
- if (!this.has(value)) {
941
- return false;
942
- }
943
- const target = getProxyDraft(this);
944
- ensureShallowCopy(target);
945
- markChanged(target);
946
- const valueProxyDraft = getProxyDraft(value);
947
- if (valueProxyDraft && target.setMap.has(valueProxyDraft.original)) {
948
- target.assignedMap.set(valueProxyDraft.original, false);
949
- return target.setMap.delete(valueProxyDraft.original);
950
- }
951
- if (!valueProxyDraft && target.setMap.has(value)) {
952
- target.assignedMap.set(value, false);
953
- } else {
954
- target.assignedMap.delete(value);
955
- }
956
- return target.setMap.delete(value);
957
- },
958
- clear() {
959
- if (!this.size)
960
- return;
961
- const target = getProxyDraft(this);
962
- ensureShallowCopy(target);
963
- markChanged(target);
964
- for (const value of target.original) {
965
- target.assignedMap.set(value, false);
966
- }
967
- target.setMap.clear();
968
- },
969
- values() {
970
- const target = getProxyDraft(this);
971
- ensureShallowCopy(target);
972
- const iterator = target.setMap.keys();
973
- return {
974
- [Symbol.iterator]: () => this.values(),
975
- next: getNextIterator(target, iterator, { isValuesIterator: true })
976
- };
977
- },
978
- entries() {
979
- const target = getProxyDraft(this);
980
- ensureShallowCopy(target);
981
- const iterator = target.setMap.keys();
982
- return {
983
- [Symbol.iterator]: () => this.entries(),
984
- next: getNextIterator(target, iterator, {
985
- isValuesIterator: false
986
- })
987
- };
988
- },
989
- keys() {
990
- return this.values();
991
- },
992
- [iteratorSymbol]() {
993
- return this.values();
994
- },
995
- forEach(callback, thisArg) {
996
- const iterator = this.values();
997
- let result = iterator.next();
998
- while (!result.done) {
999
- callback.call(thisArg, result.value, result.value, this);
1000
- result = iterator.next();
1001
- }
1002
- }
1003
- };
1004
- var setHandlerKeys = Reflect.ownKeys(setHandler);
1005
- var draftsCache = new WeakSet;
1006
- var proxyHandler = {
1007
- get(target, key, receiver) {
1008
- var _a, _b;
1009
- const copy = (_a = target.copy) === null || _a === undefined ? undefined : _a[key];
1010
- if (copy && draftsCache.has(copy)) {
1011
- return copy;
1012
- }
1013
- if (key === PROXY_DRAFT)
1014
- return target;
1015
- let markResult;
1016
- if (target.options.mark) {
1017
- const value2 = key === "size" && (target.original instanceof Map || target.original instanceof Set) ? Reflect.get(target.original, key) : Reflect.get(target.original, key, receiver);
1018
- markResult = target.options.mark(value2, dataTypes);
1019
- if (markResult === dataTypes.mutable) {
1020
- if (target.options.strict) {
1021
- checkReadable(value2, target.options, true);
1022
- }
1023
- return value2;
1024
- }
1025
- }
1026
- const source = latest(target);
1027
- if (source instanceof Map && mapHandlerKeys.includes(key)) {
1028
- if (key === "size") {
1029
- return Object.getOwnPropertyDescriptor(mapHandler, "size").get.call(target.proxy);
1030
- }
1031
- const handle = mapHandler[key];
1032
- if (handle) {
1033
- return handle.bind(target.proxy);
1034
- }
1035
- }
1036
- if (source instanceof Set && setHandlerKeys.includes(key)) {
1037
- if (key === "size") {
1038
- return Object.getOwnPropertyDescriptor(setHandler, "size").get.call(target.proxy);
1039
- }
1040
- const handle = setHandler[key];
1041
- if (handle) {
1042
- return handle.bind(target.proxy);
1043
- }
1044
- }
1045
- if (!has(source, key)) {
1046
- const desc = getDescriptor(source, key);
1047
- return desc ? `value` in desc ? desc.value : (_b = desc.get) === null || _b === undefined ? undefined : _b.call(target.proxy) : undefined;
1048
- }
1049
- const value = source[key];
1050
- if (target.options.strict) {
1051
- checkReadable(value, target.options);
1052
- }
1053
- if (target.finalized || !isDraftable(value, target.options)) {
1054
- return value;
1055
- }
1056
- if (value === peek(target.original, key)) {
1057
- ensureShallowCopy(target);
1058
- target.copy[key] = createDraft({
1059
- original: target.original[key],
1060
- parentDraft: target,
1061
- key: target.type === 1 ? Number(key) : key,
1062
- finalities: target.finalities,
1063
- options: target.options
1064
- });
1065
- if (typeof markResult === "function") {
1066
- const subProxyDraft = getProxyDraft(target.copy[key]);
1067
- ensureShallowCopy(subProxyDraft);
1068
- markChanged(subProxyDraft);
1069
- return subProxyDraft.copy;
1070
- }
1071
- return target.copy[key];
1072
- }
1073
- return value;
1074
- },
1075
- set(target, key, value) {
1076
- var _a;
1077
- if (target.type === 3 || target.type === 2) {
1078
- throw new Error(`Map/Set draft does not support any property assignment.`);
1079
- }
1080
- let _key;
1081
- if (target.type === 1 && key !== "length" && !(Number.isInteger(_key = Number(key)) && _key >= 0 && (key === 0 || _key === 0 || String(_key) === String(key)))) {
1082
- throw new Error(`Only supports setting array indices and the 'length' property.`);
1083
- }
1084
- const desc = getDescriptor(latest(target), key);
1085
- if (desc === null || desc === undefined ? undefined : desc.set) {
1086
- desc.set.call(target.proxy, value);
1087
- return true;
1088
- }
1089
- const current2 = peek(latest(target), key);
1090
- const currentProxyDraft = getProxyDraft(current2);
1091
- if (currentProxyDraft && isEqual(currentProxyDraft.original, value)) {
1092
- target.copy[key] = value;
1093
- target.assignedMap = (_a = target.assignedMap) !== null && _a !== undefined ? _a : new Map;
1094
- target.assignedMap.set(key, false);
1095
- return true;
1096
- }
1097
- if (isEqual(value, current2) && (value !== undefined || has(target.original, key)))
1098
- return true;
1099
- ensureShallowCopy(target);
1100
- markChanged(target);
1101
- if (has(target.original, key) && isEqual(value, target.original[key])) {
1102
- target.assignedMap.delete(key);
1103
- } else {
1104
- target.assignedMap.set(key, true);
1105
- }
1106
- target.copy[key] = value;
1107
- markFinalization(target, key, value, generatePatches);
1108
- return true;
1109
- },
1110
- has(target, key) {
1111
- return key in latest(target);
1112
- },
1113
- ownKeys(target) {
1114
- return Reflect.ownKeys(latest(target));
1115
- },
1116
- getOwnPropertyDescriptor(target, key) {
1117
- const source = latest(target);
1118
- const descriptor = Reflect.getOwnPropertyDescriptor(source, key);
1119
- if (!descriptor)
1120
- return descriptor;
1121
- return {
1122
- writable: true,
1123
- configurable: target.type !== 1 || key !== "length",
1124
- enumerable: descriptor.enumerable,
1125
- value: source[key]
1126
- };
1127
- },
1128
- getPrototypeOf(target) {
1129
- return Reflect.getPrototypeOf(target.original);
1130
- },
1131
- setPrototypeOf() {
1132
- throw new Error(`Cannot call 'setPrototypeOf()' on drafts`);
1133
- },
1134
- defineProperty() {
1135
- throw new Error(`Cannot call 'defineProperty()' on drafts`);
1136
- },
1137
- deleteProperty(target, key) {
1138
- var _a;
1139
- if (target.type === 1) {
1140
- return proxyHandler.set.call(this, target, key, undefined, target.proxy);
1141
- }
1142
- if (peek(target.original, key) !== undefined || key in target.original) {
1143
- ensureShallowCopy(target);
1144
- markChanged(target);
1145
- target.assignedMap.set(key, false);
1146
- } else {
1147
- target.assignedMap = (_a = target.assignedMap) !== null && _a !== undefined ? _a : new Map;
1148
- target.assignedMap.delete(key);
1149
- }
1150
- if (target.copy)
1151
- delete target.copy[key];
1152
- return true;
1153
- }
1154
- };
1155
- internal.createDraft = createDraft;
1156
- var makeCreator = (arg) => {
1157
- if (arg !== undefined && Object.prototype.toString.call(arg) !== "[object Object]") {
1158
- throw new Error(`Invalid options: ${String(arg)}, 'options' should be an object.`);
1159
- }
1160
- return function create(arg0, arg1, arg2) {
1161
- var _a, _b, _c;
1162
- if (typeof arg0 === "function" && typeof arg1 !== "function") {
1163
- return function(base2, ...args) {
1164
- return create(base2, (draft2) => arg0.call(this, draft2, ...args), arg1);
1165
- };
1166
- }
1167
- const base = arg0;
1168
- const mutate = arg1;
1169
- let options = arg2;
1170
- if (typeof arg1 !== "function") {
1171
- options = arg1;
1172
- }
1173
- if (options !== undefined && Object.prototype.toString.call(options) !== "[object Object]") {
1174
- throw new Error(`Invalid options: ${options}, 'options' should be an object.`);
1175
- }
1176
- options = Object.assign(Object.assign({}, arg), options);
1177
- const state = isDraft(base) ? current(base) : base;
1178
- const mark = Array.isArray(options.mark) ? (value, types) => {
1179
- for (const mark2 of options.mark) {
1180
- if (typeof mark2 !== "function") {
1181
- throw new Error(`Invalid mark: ${mark2}, 'mark' should be a function.`);
1182
- }
1183
- const result2 = mark2(value, types);
1184
- if (result2) {
1185
- return result2;
1186
- }
1187
- }
1188
- return;
1189
- } : options.mark;
1190
- const enablePatches = (_a = options.enablePatches) !== null && _a !== undefined ? _a : false;
1191
- const strict = (_b = options.strict) !== null && _b !== undefined ? _b : false;
1192
- const enableAutoFreeze = (_c = options.enableAutoFreeze) !== null && _c !== undefined ? _c : false;
1193
- const _options = {
1194
- enableAutoFreeze,
1195
- mark,
1196
- strict,
1197
- enablePatches
1198
- };
1199
- if (!isDraftable(state, _options) && typeof state === "object" && state !== null) {
1200
- throw new Error(`Invalid base state: create() only supports plain objects, arrays, Set, Map or using mark() to mark the state as immutable.`);
1201
- }
1202
- const [draft, finalize] = draftify(state, _options);
1203
- if (typeof arg1 !== "function") {
1204
- if (!isDraftable(state, _options)) {
1205
- throw new Error(`Invalid base state: create() only supports plain objects, arrays, Set, Map or using mark() to mark the state as immutable.`);
1206
- }
1207
- return [draft, finalize];
1208
- }
1209
- let result;
1210
- try {
1211
- result = mutate(draft);
1212
- } catch (error) {
1213
- revokeProxy(getProxyDraft(draft));
1214
- throw error;
1215
- }
1216
- const returnValue = (value) => {
1217
- const proxyDraft = getProxyDraft(draft);
1218
- if (!isDraft(value)) {
1219
- if (value !== undefined && !isEqual(value, draft) && (proxyDraft === null || proxyDraft === undefined ? undefined : proxyDraft.operated)) {
1220
- throw new Error(`Either the value is returned as a new non-draft value, or only the draft is modified without returning any value.`);
1221
- }
1222
- const rawReturnValue = value === null || value === undefined ? undefined : value[RAW_RETURN_SYMBOL];
1223
- if (rawReturnValue) {
1224
- const _value = rawReturnValue[0];
1225
- if (_options.strict && typeof value === "object" && value !== null) {
1226
- handleReturnValue({
1227
- rootDraft: proxyDraft,
1228
- value,
1229
- useRawReturn: true
1230
- });
1231
- }
1232
- return finalize([_value]);
1233
- }
1234
- if (value !== undefined) {
1235
- if (typeof value === "object" && value !== null) {
1236
- handleReturnValue({ rootDraft: proxyDraft, value });
1237
- }
1238
- return finalize([value]);
1239
- }
1240
- }
1241
- if (value === draft || value === undefined) {
1242
- return finalize([]);
1243
- }
1244
- const returnedProxyDraft = getProxyDraft(value);
1245
- if (_options === returnedProxyDraft.options) {
1246
- if (returnedProxyDraft.operated) {
1247
- throw new Error(`Cannot return a modified child draft.`);
1248
- }
1249
- return finalize([current(value)]);
1250
- }
1251
- return finalize([value]);
1252
- };
1253
- if (result instanceof Promise) {
1254
- return result.then(returnValue, (error) => {
1255
- revokeProxy(getProxyDraft(draft));
1256
- throw error;
1257
- });
1258
- }
1259
- return returnValue(result);
1260
- };
1261
- };
1262
- var create = makeCreator();
1263
- var constructorString = Object.prototype.constructor.toString();
1264
-
1265
- // /Users/pkrasinski/Projects/arcote.tech/arc/node_modules/@arcote.tech/arc/dist/index.js
1266
- import {BehaviorSubject, debounceTime, Subject} from "rxjs";
1267
- import {Subject as Subject2} from "rxjs";
1268
- function model(context3, dependencies) {
1269
- return new ArcModel(context3, dependencies.dbAdapterFactory, dependencies.rtcAdapterFactory);
1270
- }
1271
- class ArcCollectionQuery {
1272
- collection;
1273
- result$ = new Subject;
1274
- resultQueue$;
1275
- subscriptions = [];
1276
- constructor(collection) {
1277
- this.collection = collection;
1278
- }
1279
- getLastResult() {
1280
- return this.resultQueue$.getValue();
1281
- }
1282
- async run(db, changes$) {
1283
- const subscription = changes$.subscribe(this.changeHandler.bind(this));
1284
- this.subscriptions.push(subscription);
1285
- const transaction = await db.readTransaction([this.collection]);
1286
- const result = await this.fetch(transaction);
1287
- this.resultQueue$ = new BehaviorSubject(result);
1288
- const subscriptionDebounce = this.resultQueue$.pipe(debounceTime(50)).subscribe(this.result$);
1289
- this.subscriptions.push(subscriptionDebounce);
1290
- }
1291
- changeHandler(change) {
1292
- if (change.collection !== this.collection.name)
1293
- return;
1294
- if (!this.resultQueue$)
1295
- return;
1296
- const response = this.onChange(change);
1297
- if (response !== false)
1298
- this.nextResult(response);
1299
- }
1300
- unsubscribe() {
1301
- this.subscriptions.forEach((sub) => sub.unsubscribe());
1302
- }
1303
- nextResult(result) {
1304
- if (!this.resultQueue$)
1305
- return console.warn("Weird, it shouldn't happen :/");
1306
- this.resultQueue$.next(result);
1307
- }
1308
- isUnsubscribed() {
1309
- return this.subscriptions.every((sub) => sub.closed);
1310
- }
1311
- }
1312
-
1313
- class QueryCollectionResult {
1314
- result;
1315
- constructor(result) {
1316
- this.result = result;
1317
- }
1318
- get(id) {
1319
- return this.result.find((r) => r._id === id);
1320
- }
1321
- map(callbackfn) {
1322
- return this.result.map(callbackfn);
1323
- }
1324
- toArray() {
1325
- return this.result;
1326
- }
1327
- }
1328
-
1329
- class ArcManyItemsQuery extends ArcCollectionQuery {
1330
- filterFn;
1331
- sortFn;
1332
- constructor(collection, filterFn, sortFn) {
1333
- super(collection);
1334
- this.filterFn = filterFn;
1335
- this.sortFn = sortFn;
1336
- }
1337
- onChange(change) {
1338
- const lastResult = this.getLastResult();
1339
- const lastResultAsArray = lastResult.toArray();
1340
- const index = lastResultAsArray.findIndex((e) => e._id === (change.type === "delete" ? change.id : change.body._id));
1341
- const isInLastResult = index !== -1;
1342
- const shouldBeInTheResult = change.type !== "delete" && this.checkItem(change.body);
1343
- if (isInLastResult && shouldBeInTheResult)
1344
- return this.createResult(lastResultAsArray.toSpliced(index, 1, change.body));
1345
- else if (isInLastResult && (change.type === "delete" || !shouldBeInTheResult))
1346
- return this.createResult(lastResultAsArray.toSpliced(index, 1));
1347
- else if (!isInLastResult && shouldBeInTheResult)
1348
- return this.createResult(lastResultAsArray.concat(change.body));
1349
- return false;
1350
- }
1351
- createResult(result) {
1352
- if (this.sortFn)
1353
- return new QueryCollectionResult(result.sort(this.sortFn));
1354
- return new QueryCollectionResult(result);
1355
- }
1356
- createFiltredResult(result) {
1357
- if (this.filterFn)
1358
- return this.createResult(result.filter(this.filterFn));
1359
- return this.createResult(result);
1360
- }
1361
- checkItem(item) {
1362
- if (this.filterFn)
1363
- return this.filterFn(item);
1364
- return true;
1365
- }
1366
- }
1367
-
1368
- class ArcAllItemsQuery extends ArcManyItemsQuery {
1369
- async fetch(transaction) {
1370
- return this.createFiltredResult(await transaction.findAll(this.collection));
1371
- }
1372
- }
1373
-
1374
- class ArcQueryBuilder {
1375
- }
1376
-
1377
- class ArcManyItemsQueryBuilder extends ArcQueryBuilder {
1378
- filterFn;
1379
- sortFn;
1380
- filter(callback) {
1381
- this.filterFn = callback;
1382
- return this;
1383
- }
1384
- sort(callback) {
1385
- this.sortFn = callback;
1386
- return this;
1387
- }
1388
- }
1389
-
1390
- class ArcAllItemsQueryBuilder extends ArcManyItemsQueryBuilder {
1391
- collection;
1392
- constructor(collection) {
1393
- super();
1394
- this.collection = collection;
1395
- }
1396
- toQuery() {
1397
- return new ArcAllItemsQuery(this.collection, this.filterFn, this.sortFn);
1398
- }
1399
- }
1400
-
1401
- class ArcIndexedItemsQuery extends ArcManyItemsQuery {
1402
- index;
1403
- data;
1404
- filterFn;
1405
- sortFn;
1406
- constructor(collection, index, data, filterFn, sortFn) {
1407
- super(collection, filterFn, sortFn);
1408
- this.index = index;
1409
- this.data = data;
1410
- this.filterFn = filterFn;
1411
- this.sortFn = sortFn;
1412
- }
1413
- checkItem(item) {
1414
- if (!super.checkItem(item))
1415
- return false;
1416
- const notCorrect = Object.entries(this.data).find(([key, value]) => item[key] !== value);
1417
- if (notCorrect)
1418
- return false;
1419
- return true;
1420
- }
1421
- async fetch(transaction) {
1422
- return this.createFiltredResult(await transaction.findByIndex(this.collection, this.index, this.data));
1423
- }
1424
- }
1425
-
1426
- class ArcIndexedItemsQueryBuilder extends ArcManyItemsQueryBuilder {
1427
- collection;
1428
- index;
1429
- data;
1430
- constructor(collection, index, data) {
1431
- super();
1432
- this.collection = collection;
1433
- this.index = index;
1434
- this.data = data;
1435
- }
1436
- toQuery() {
1437
- return new ArcIndexedItemsQuery(this.collection, this.index, this.data, this.filterFn, this.sortFn);
1438
- }
1439
- }
1440
-
1441
- class ArcOneItemQuery extends ArcCollectionQuery {
1442
- id;
1443
- constructor(collection, id) {
1444
- super(collection);
1445
- this.id = id;
1446
- }
1447
- onChange(change) {
1448
- if (change.type === "delete" && change.id === this.id)
1449
- return;
1450
- if (change.type === "set" && change.body._id === this.id)
1451
- return change.body;
1452
- return false;
1453
- }
1454
- fetch(transaction) {
1455
- if (!this.id)
1456
- return;
1457
- return transaction.findById(this.collection, this.id);
1458
- }
1459
- }
1460
-
1461
- class ArcOneItemQueryBuilder extends ArcQueryBuilder {
1462
- collection;
1463
- id;
1464
- constructor(collection, id) {
1465
- super();
1466
- this.collection = collection;
1467
- this.id = id;
1468
- }
1469
- toQuery() {
1470
- return new ArcOneItemQuery(this.collection, this.id);
1471
- }
1472
- }
1473
-
1474
- class ArcCollection {
1475
- name;
1476
- id;
1477
- schema;
1478
- constructor(name, id, schema) {
1479
- this.name = name;
1480
- this.id = id;
1481
- this.schema = schema;
1482
- }
1483
- serialize(data) {
1484
- return {
1485
- _id: this.id.serialize(data._id),
1486
- ...this.schema.serialize(data)
1487
- };
1488
- }
1489
- deserialize(data) {
1490
- return {
1491
- _id: this.id.deserialize(data._id),
1492
- ...this.schema.deserialize(data)
1493
- };
1494
- }
1495
- queryBuilder() {
1496
- return {
1497
- all: () => new ArcAllItemsQueryBuilder(this),
1498
- one: (id) => new ArcOneItemQueryBuilder(this, id)
1499
- };
1500
- }
1501
- commandContext(transaction, changes, getDraft) {
1502
- return {
1503
- add: (data) => {
1504
- const id = this.id.generate();
1505
- const parsed = this.schema.parse(data);
1506
- const body = {
1507
- _id: id,
1508
- ...parsed
1509
- };
1510
- changes.push({ type: "set", collection: this.name, body });
1511
- return { id };
1512
- },
1513
- remove: (id) => {
1514
- changes.push({ type: "delete", collection: this.name, id });
1515
- return { success: true };
1516
- },
1517
- set: (id, data) => {
1518
- const parsed = this.schema.parse(data);
1519
- const body = {
1520
- _id: id,
1521
- ...parsed
1522
- };
1523
- changes.push({ type: "set", collection: this.name, body });
1524
- return { success: true };
1525
- },
1526
- one: async (id) => {
1527
- const object = await transaction.findById(this, id);
1528
- return getDraft(this.name, object);
1529
- }
1530
- };
1531
- }
1532
- async applyChange(transaction, change, events) {
1533
- switch (change.type) {
1534
- case "set":
1535
- await transaction.set(this, change.body);
1536
- events.push(change);
1537
- break;
1538
- case "delete":
1539
- await transaction.remove(this, change.id);
1540
- events.push(change);
1541
- break;
1542
- case "mutate":
1543
- const existingObject = await transaction.findById(this, change.id);
1544
- if (existingObject) {
1545
- const updatedObject = apply(existingObject, change.patches);
1546
- await transaction.set(this, updatedObject);
1547
- events.push({
1548
- type: "set",
1549
- collection: change.collection,
1550
- body: updatedObject
1551
- });
1552
- }
1553
- break;
1554
- }
1555
- }
1556
- indexBy(indexes) {
1557
- return new ArcIndexedCollection(this.name, this.id, this.schema, indexes);
1558
- }
1559
- }
1560
-
1561
- class ArcIndexedCollection extends ArcCollection {
1562
- indexes;
1563
- constructor(name, id, schema, indexes) {
1564
- super(name, id, schema);
1565
- this.indexes = indexes;
1566
- }
1567
- queryBuilder() {
1568
- const superQueryBuilder = super.queryBuilder();
1569
- return new Proxy({}, {
1570
- get: (target, name) => {
1571
- if (name in superQueryBuilder)
1572
- return superQueryBuilder[name];
1573
- if (!(name in this.indexes)) {
1574
- throw new Error(`Index "${name}" not found in collection "${this.name}"`);
1575
- }
1576
- return (data) => new ArcIndexedItemsQueryBuilder(this, name, data);
1577
- }
1578
- });
1579
- }
1580
- }
1581
- class ArcModel {
1582
- context3;
1583
- rtc;
1584
- dbAdapterPromise;
1585
- changes$ = new Subject2;
1586
- constructor(context3, dbAdapterFactory, rtcAdapterFactory) {
1587
- this.context = context3;
1588
- this.rtc = rtcAdapterFactory(this);
1589
- this.dbAdapterPromise = dbAdapterFactory(this.context);
1590
- }
1591
- query(queryFactory) {
1592
- const queryBuilder = this.context.queryBuilder();
1593
- const query = queryFactory(queryBuilder).toQuery();
1594
- this.runQuery(query);
1595
- return query;
1596
- }
1597
- async runQuery(query) {
1598
- if (query instanceof ArcCollectionQuery) {
1599
- const dbAdapter = await this.dbAdapterPromise;
1600
- query.run(dbAdapter, this.changes$);
1601
- }
1602
- }
1603
- commands() {
1604
- return new Proxy({}, {
1605
- get: (target, name) => {
1606
- if (name in this.context.commands) {
1607
- return async (...args) => {
1608
- const { result } = await this.executeCommand(this.context.commands[name], ...args);
1609
- return result;
1610
- };
1611
- }
1612
- console.warn(`Command '${name}' not found in the context.`);
1613
- return;
1614
- }
1615
- });
1616
- }
1617
- async executeCommand(command, ...args) {
1618
- const dbAdapter = await this.dbAdapterPromise;
1619
- const transaction = await dbAdapter.readWriteTransaction(this.context.collections);
1620
- const { context: context3, finalize } = await this.context.commandContext(transaction);
1621
- const result = await command(context3, ...args);
1622
- const changes = await finalize();
1623
- await this.applyChangesForTransaction(transaction, changes);
1624
- this.rtc.commandExecuted(command.name, changes);
1625
- return { changes, result };
1626
- }
1627
- async applyChangesForTransaction(transaction, changes) {
1628
- const events = [];
1629
- for (const change of changes) {
1630
- await this.context.applyChange(transaction, change, events);
1631
- }
1632
- await transaction.commit();
1633
- events.forEach((change) => this.notifyChange(change));
1634
- }
1635
- notifyChange(change) {
1636
- this.changes$.next(change);
1637
- }
1638
- async applyChanges(changes) {
1639
- const dbAdapter = await this.dbAdapterPromise;
1640
- const transaction = await dbAdapter.readWriteTransaction(this.context.collections);
1641
- await this.applyChangesForTransaction(transaction, changes);
1642
- }
1643
- getCollection(name) {
1644
- return this.context.collectionsMap[name];
1645
- }
1646
- }
1647
-
1648
1
  // idb.ts
2
+ import {
3
+ ArcIndexedCollection
4
+ } from "@arcote.tech/arc";
1649
5
  var idbAdapterFactory = (name, version) => (context) => new Promise((resolve, reject) => {
1650
6
  const dbRequest = indexedDB.open(name, version);
1651
7
  dbRequest.addEventListener("error", (err) => {
@@ -1761,6 +117,10 @@ class IDBAdapter {
1761
117
  }
1762
118
  }
1763
119
  // reactModel.tsx
120
+ import {
121
+ ArcCollectionQuery,
122
+ model
123
+ } from "@arcote.tech/arc";
1764
124
  import {createContext, useContext, useEffect, useRef, useState} from "react";
1765
125
  import {
1766
126
  jsxDEV