state-jet 1.0.9 → 1.0.10

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.cjs CHANGED
@@ -1,36 +1,1099 @@
1
- "use strict";
1
+ 'use strict';
2
+
3
+ var require$$0 = require('react');
4
+
5
+ // src/utils/env.ts
6
+ var NOTHING = Symbol.for("immer-nothing");
7
+ var DRAFTABLE = Symbol.for("immer-draftable");
8
+ var DRAFT_STATE = Symbol.for("immer-state");
9
+
10
+ // src/utils/errors.ts
11
+ var errors = process.env.NODE_ENV !== "production" ? [
12
+ // All error codes, starting by 0:
13
+ function(plugin) {
14
+ return `The plugin for '${plugin}' has not been loaded into Immer. To enable the plugin, import and call \`enable${plugin}()\` when initializing your application.`;
15
+ },
16
+ function(thing) {
17
+ return `produce can only be called on things that are draftable: plain objects, arrays, Map, Set or classes that are marked with '[immerable]: true'. Got '${thing}'`;
18
+ },
19
+ "This object has been frozen and should not be mutated",
20
+ function(data) {
21
+ return "Cannot use a proxy that has been revoked. Did you pass an object from inside an immer function to an async process? " + data;
22
+ },
23
+ "An immer producer returned a new value *and* modified its draft. Either return a new value *or* modify the draft.",
24
+ "Immer forbids circular references",
25
+ "The first or second argument to `produce` must be a function",
26
+ "The third argument to `produce` must be a function or undefined",
27
+ "First argument to `createDraft` must be a plain object, an array, or an immerable object",
28
+ "First argument to `finishDraft` must be a draft returned by `createDraft`",
29
+ function(thing) {
30
+ return `'current' expects a draft, got: ${thing}`;
31
+ },
32
+ "Object.defineProperty() cannot be used on an Immer draft",
33
+ "Object.setPrototypeOf() cannot be used on an Immer draft",
34
+ "Immer only supports deleting array indices",
35
+ "Immer only supports setting array indices and the 'length' property",
36
+ function(thing) {
37
+ return `'original' expects a draft, got: ${thing}`;
38
+ }
39
+ // Note: if more errors are added, the errorOffset in Patches.ts should be increased
40
+ // See Patches.ts for additional errors
41
+ ] : [];
42
+ function die(error, ...args) {
43
+ if (process.env.NODE_ENV !== "production") {
44
+ const e = errors[error];
45
+ const msg = typeof e === "function" ? e.apply(null, args) : e;
46
+ throw new Error(`[Immer] ${msg}`);
47
+ }
48
+ throw new Error(
49
+ `[Immer] minified error nr: ${error}. Full error at: https://bit.ly/3cXEKWf`
50
+ );
51
+ }
52
+
53
+ // src/utils/common.ts
54
+ var getPrototypeOf = Object.getPrototypeOf;
55
+ function isDraft(value) {
56
+ return !!value && !!value[DRAFT_STATE];
57
+ }
58
+ function isDraftable(value) {
59
+ if (!value)
60
+ return false;
61
+ return isPlainObject(value) || Array.isArray(value) || !!value[DRAFTABLE] || !!value.constructor?.[DRAFTABLE] || isMap(value) || isSet(value);
62
+ }
63
+ var objectCtorString = Object.prototype.constructor.toString();
64
+ function isPlainObject(value) {
65
+ if (!value || typeof value !== "object")
66
+ return false;
67
+ const proto = getPrototypeOf(value);
68
+ if (proto === null) {
69
+ return true;
70
+ }
71
+ const Ctor = Object.hasOwnProperty.call(proto, "constructor") && proto.constructor;
72
+ if (Ctor === Object)
73
+ return true;
74
+ return typeof Ctor == "function" && Function.toString.call(Ctor) === objectCtorString;
75
+ }
76
+ function each(obj, iter) {
77
+ if (getArchtype(obj) === 0 /* Object */) {
78
+ Reflect.ownKeys(obj).forEach((key) => {
79
+ iter(key, obj[key], obj);
80
+ });
81
+ } else {
82
+ obj.forEach((entry, index) => iter(index, entry, obj));
83
+ }
84
+ }
85
+ function getArchtype(thing) {
86
+ const state = thing[DRAFT_STATE];
87
+ return state ? state.type_ : Array.isArray(thing) ? 1 /* Array */ : isMap(thing) ? 2 /* Map */ : isSet(thing) ? 3 /* Set */ : 0 /* Object */;
88
+ }
89
+ function has(thing, prop) {
90
+ return getArchtype(thing) === 2 /* Map */ ? thing.has(prop) : Object.prototype.hasOwnProperty.call(thing, prop);
91
+ }
92
+ function set(thing, propOrOldValue, value) {
93
+ const t = getArchtype(thing);
94
+ if (t === 2 /* Map */)
95
+ thing.set(propOrOldValue, value);
96
+ else if (t === 3 /* Set */) {
97
+ thing.add(value);
98
+ } else
99
+ thing[propOrOldValue] = value;
100
+ }
101
+ function is(x, y) {
102
+ if (x === y) {
103
+ return x !== 0 || 1 / x === 1 / y;
104
+ } else {
105
+ return x !== x && y !== y;
106
+ }
107
+ }
108
+ function isMap(target) {
109
+ return target instanceof Map;
110
+ }
111
+ function isSet(target) {
112
+ return target instanceof Set;
113
+ }
114
+ function latest(state) {
115
+ return state.copy_ || state.base_;
116
+ }
117
+ function shallowCopy(base, strict) {
118
+ if (isMap(base)) {
119
+ return new Map(base);
120
+ }
121
+ if (isSet(base)) {
122
+ return new Set(base);
123
+ }
124
+ if (Array.isArray(base))
125
+ return Array.prototype.slice.call(base);
126
+ const isPlain = isPlainObject(base);
127
+ if (strict === true || strict === "class_only" && !isPlain) {
128
+ const descriptors = Object.getOwnPropertyDescriptors(base);
129
+ delete descriptors[DRAFT_STATE];
130
+ let keys = Reflect.ownKeys(descriptors);
131
+ for (let i = 0; i < keys.length; i++) {
132
+ const key = keys[i];
133
+ const desc = descriptors[key];
134
+ if (desc.writable === false) {
135
+ desc.writable = true;
136
+ desc.configurable = true;
137
+ }
138
+ if (desc.get || desc.set)
139
+ descriptors[key] = {
140
+ configurable: true,
141
+ writable: true,
142
+ // could live with !!desc.set as well here...
143
+ enumerable: desc.enumerable,
144
+ value: base[key]
145
+ };
146
+ }
147
+ return Object.create(getPrototypeOf(base), descriptors);
148
+ } else {
149
+ const proto = getPrototypeOf(base);
150
+ if (proto !== null && isPlain) {
151
+ return { ...base };
152
+ }
153
+ const obj = Object.create(proto);
154
+ return Object.assign(obj, base);
155
+ }
156
+ }
157
+ function freeze(obj, deep = false) {
158
+ if (isFrozen(obj) || isDraft(obj) || !isDraftable(obj))
159
+ return obj;
160
+ if (getArchtype(obj) > 1) {
161
+ obj.set = obj.add = obj.clear = obj.delete = dontMutateFrozenCollections;
162
+ }
163
+ Object.freeze(obj);
164
+ if (deep)
165
+ Object.entries(obj).forEach(([key, value]) => freeze(value, true));
166
+ return obj;
167
+ }
168
+ function dontMutateFrozenCollections() {
169
+ die(2);
170
+ }
171
+ function isFrozen(obj) {
172
+ return Object.isFrozen(obj);
173
+ }
174
+
175
+ // src/utils/plugins.ts
176
+ var plugins = {};
177
+ function getPlugin(pluginKey) {
178
+ const plugin = plugins[pluginKey];
179
+ if (!plugin) {
180
+ die(0, pluginKey);
181
+ }
182
+ return plugin;
183
+ }
184
+
185
+ // src/core/scope.ts
186
+ var currentScope;
187
+ function getCurrentScope() {
188
+ return currentScope;
189
+ }
190
+ function createScope(parent_, immer_) {
191
+ return {
192
+ drafts_: [],
193
+ parent_,
194
+ immer_,
195
+ // Whenever the modified draft contains a draft from another scope, we
196
+ // need to prevent auto-freezing so the unowned draft can be finalized.
197
+ canAutoFreeze_: true,
198
+ unfinalizedDrafts_: 0
199
+ };
200
+ }
201
+ function usePatchesInScope(scope, patchListener) {
202
+ if (patchListener) {
203
+ getPlugin("Patches");
204
+ scope.patches_ = [];
205
+ scope.inversePatches_ = [];
206
+ scope.patchListener_ = patchListener;
207
+ }
208
+ }
209
+ function revokeScope(scope) {
210
+ leaveScope(scope);
211
+ scope.drafts_.forEach(revokeDraft);
212
+ scope.drafts_ = null;
213
+ }
214
+ function leaveScope(scope) {
215
+ if (scope === currentScope) {
216
+ currentScope = scope.parent_;
217
+ }
218
+ }
219
+ function enterScope(immer2) {
220
+ return currentScope = createScope(currentScope, immer2);
221
+ }
222
+ function revokeDraft(draft) {
223
+ const state = draft[DRAFT_STATE];
224
+ if (state.type_ === 0 /* Object */ || state.type_ === 1 /* Array */)
225
+ state.revoke_();
226
+ else
227
+ state.revoked_ = true;
228
+ }
229
+
230
+ // src/core/finalize.ts
231
+ function processResult(result, scope) {
232
+ scope.unfinalizedDrafts_ = scope.drafts_.length;
233
+ const baseDraft = scope.drafts_[0];
234
+ const isReplaced = result !== void 0 && result !== baseDraft;
235
+ if (isReplaced) {
236
+ if (baseDraft[DRAFT_STATE].modified_) {
237
+ revokeScope(scope);
238
+ die(4);
239
+ }
240
+ if (isDraftable(result)) {
241
+ result = finalize(scope, result);
242
+ if (!scope.parent_)
243
+ maybeFreeze(scope, result);
244
+ }
245
+ if (scope.patches_) {
246
+ getPlugin("Patches").generateReplacementPatches_(
247
+ baseDraft[DRAFT_STATE].base_,
248
+ result,
249
+ scope.patches_,
250
+ scope.inversePatches_
251
+ );
252
+ }
253
+ } else {
254
+ result = finalize(scope, baseDraft, []);
255
+ }
256
+ revokeScope(scope);
257
+ if (scope.patches_) {
258
+ scope.patchListener_(scope.patches_, scope.inversePatches_);
259
+ }
260
+ return result !== NOTHING ? result : void 0;
261
+ }
262
+ function finalize(rootScope, value, path) {
263
+ if (isFrozen(value))
264
+ return value;
265
+ const state = value[DRAFT_STATE];
266
+ if (!state) {
267
+ each(
268
+ value,
269
+ (key, childValue) => finalizeProperty(rootScope, state, value, key, childValue, path)
270
+ );
271
+ return value;
272
+ }
273
+ if (state.scope_ !== rootScope)
274
+ return value;
275
+ if (!state.modified_) {
276
+ maybeFreeze(rootScope, state.base_, true);
277
+ return state.base_;
278
+ }
279
+ if (!state.finalized_) {
280
+ state.finalized_ = true;
281
+ state.scope_.unfinalizedDrafts_--;
282
+ const result = state.copy_;
283
+ let resultEach = result;
284
+ let isSet2 = false;
285
+ if (state.type_ === 3 /* Set */) {
286
+ resultEach = new Set(result);
287
+ result.clear();
288
+ isSet2 = true;
289
+ }
290
+ each(
291
+ resultEach,
292
+ (key, childValue) => finalizeProperty(rootScope, state, result, key, childValue, path, isSet2)
293
+ );
294
+ maybeFreeze(rootScope, result, false);
295
+ if (path && rootScope.patches_) {
296
+ getPlugin("Patches").generatePatches_(
297
+ state,
298
+ path,
299
+ rootScope.patches_,
300
+ rootScope.inversePatches_
301
+ );
302
+ }
303
+ }
304
+ return state.copy_;
305
+ }
306
+ function finalizeProperty(rootScope, parentState, targetObject, prop, childValue, rootPath, targetIsSet) {
307
+ if (process.env.NODE_ENV !== "production" && childValue === targetObject)
308
+ die(5);
309
+ if (isDraft(childValue)) {
310
+ const path = rootPath && parentState && parentState.type_ !== 3 /* Set */ && // Set objects are atomic since they have no keys.
311
+ !has(parentState.assigned_, prop) ? rootPath.concat(prop) : void 0;
312
+ const res = finalize(rootScope, childValue, path);
313
+ set(targetObject, prop, res);
314
+ if (isDraft(res)) {
315
+ rootScope.canAutoFreeze_ = false;
316
+ } else
317
+ return;
318
+ } else if (targetIsSet) {
319
+ targetObject.add(childValue);
320
+ }
321
+ if (isDraftable(childValue) && !isFrozen(childValue)) {
322
+ if (!rootScope.immer_.autoFreeze_ && rootScope.unfinalizedDrafts_ < 1) {
323
+ return;
324
+ }
325
+ finalize(rootScope, childValue);
326
+ if ((!parentState || !parentState.scope_.parent_) && typeof prop !== "symbol" && Object.prototype.propertyIsEnumerable.call(targetObject, prop))
327
+ maybeFreeze(rootScope, childValue);
328
+ }
329
+ }
330
+ function maybeFreeze(scope, value, deep = false) {
331
+ if (!scope.parent_ && scope.immer_.autoFreeze_ && scope.canAutoFreeze_) {
332
+ freeze(value, deep);
333
+ }
334
+ }
335
+
336
+ // src/core/proxy.ts
337
+ function createProxyProxy(base, parent) {
338
+ const isArray = Array.isArray(base);
339
+ const state = {
340
+ type_: isArray ? 1 /* Array */ : 0 /* Object */,
341
+ // Track which produce call this is associated with.
342
+ scope_: parent ? parent.scope_ : getCurrentScope(),
343
+ // True for both shallow and deep changes.
344
+ modified_: false,
345
+ // Used during finalization.
346
+ finalized_: false,
347
+ // Track which properties have been assigned (true) or deleted (false).
348
+ assigned_: {},
349
+ // The parent draft state.
350
+ parent_: parent,
351
+ // The base state.
352
+ base_: base,
353
+ // The base proxy.
354
+ draft_: null,
355
+ // set below
356
+ // The base copy with any updated values.
357
+ copy_: null,
358
+ // Called by the `produce` function.
359
+ revoke_: null,
360
+ isManual_: false
361
+ };
362
+ let target = state;
363
+ let traps = objectTraps;
364
+ if (isArray) {
365
+ target = [state];
366
+ traps = arrayTraps;
367
+ }
368
+ const { revoke, proxy } = Proxy.revocable(target, traps);
369
+ state.draft_ = proxy;
370
+ state.revoke_ = revoke;
371
+ return proxy;
372
+ }
373
+ var objectTraps = {
374
+ get(state, prop) {
375
+ if (prop === DRAFT_STATE)
376
+ return state;
377
+ const source = latest(state);
378
+ if (!has(source, prop)) {
379
+ return readPropFromProto(state, source, prop);
380
+ }
381
+ const value = source[prop];
382
+ if (state.finalized_ || !isDraftable(value)) {
383
+ return value;
384
+ }
385
+ if (value === peek(state.base_, prop)) {
386
+ prepareCopy(state);
387
+ return state.copy_[prop] = createProxy(value, state);
388
+ }
389
+ return value;
390
+ },
391
+ has(state, prop) {
392
+ return prop in latest(state);
393
+ },
394
+ ownKeys(state) {
395
+ return Reflect.ownKeys(latest(state));
396
+ },
397
+ set(state, prop, value) {
398
+ const desc = getDescriptorFromProto(latest(state), prop);
399
+ if (desc?.set) {
400
+ desc.set.call(state.draft_, value);
401
+ return true;
402
+ }
403
+ if (!state.modified_) {
404
+ const current2 = peek(latest(state), prop);
405
+ const currentState = current2?.[DRAFT_STATE];
406
+ if (currentState && currentState.base_ === value) {
407
+ state.copy_[prop] = value;
408
+ state.assigned_[prop] = false;
409
+ return true;
410
+ }
411
+ if (is(value, current2) && (value !== void 0 || has(state.base_, prop)))
412
+ return true;
413
+ prepareCopy(state);
414
+ markChanged(state);
415
+ }
416
+ if (state.copy_[prop] === value && // special case: handle new props with value 'undefined'
417
+ (value !== void 0 || prop in state.copy_) || // special case: NaN
418
+ Number.isNaN(value) && Number.isNaN(state.copy_[prop]))
419
+ return true;
420
+ state.copy_[prop] = value;
421
+ state.assigned_[prop] = true;
422
+ return true;
423
+ },
424
+ deleteProperty(state, prop) {
425
+ if (peek(state.base_, prop) !== void 0 || prop in state.base_) {
426
+ state.assigned_[prop] = false;
427
+ prepareCopy(state);
428
+ markChanged(state);
429
+ } else {
430
+ delete state.assigned_[prop];
431
+ }
432
+ if (state.copy_) {
433
+ delete state.copy_[prop];
434
+ }
435
+ return true;
436
+ },
437
+ // Note: We never coerce `desc.value` into an Immer draft, because we can't make
438
+ // the same guarantee in ES5 mode.
439
+ getOwnPropertyDescriptor(state, prop) {
440
+ const owner = latest(state);
441
+ const desc = Reflect.getOwnPropertyDescriptor(owner, prop);
442
+ if (!desc)
443
+ return desc;
444
+ return {
445
+ writable: true,
446
+ configurable: state.type_ !== 1 /* Array */ || prop !== "length",
447
+ enumerable: desc.enumerable,
448
+ value: owner[prop]
449
+ };
450
+ },
451
+ defineProperty() {
452
+ die(11);
453
+ },
454
+ getPrototypeOf(state) {
455
+ return getPrototypeOf(state.base_);
456
+ },
457
+ setPrototypeOf() {
458
+ die(12);
459
+ }
460
+ };
461
+ var arrayTraps = {};
462
+ each(objectTraps, (key, fn) => {
463
+ arrayTraps[key] = function() {
464
+ arguments[0] = arguments[0][0];
465
+ return fn.apply(this, arguments);
466
+ };
467
+ });
468
+ arrayTraps.deleteProperty = function(state, prop) {
469
+ if (process.env.NODE_ENV !== "production" && isNaN(parseInt(prop)))
470
+ die(13);
471
+ return arrayTraps.set.call(this, state, prop, void 0);
472
+ };
473
+ arrayTraps.set = function(state, prop, value) {
474
+ if (process.env.NODE_ENV !== "production" && prop !== "length" && isNaN(parseInt(prop)))
475
+ die(14);
476
+ return objectTraps.set.call(this, state[0], prop, value, state[0]);
477
+ };
478
+ function peek(draft, prop) {
479
+ const state = draft[DRAFT_STATE];
480
+ const source = state ? latest(state) : draft;
481
+ return source[prop];
482
+ }
483
+ function readPropFromProto(state, source, prop) {
484
+ const desc = getDescriptorFromProto(source, prop);
485
+ return desc ? `value` in desc ? desc.value : (
486
+ // This is a very special case, if the prop is a getter defined by the
487
+ // prototype, we should invoke it with the draft as context!
488
+ desc.get?.call(state.draft_)
489
+ ) : void 0;
490
+ }
491
+ function getDescriptorFromProto(source, prop) {
492
+ if (!(prop in source))
493
+ return void 0;
494
+ let proto = getPrototypeOf(source);
495
+ while (proto) {
496
+ const desc = Object.getOwnPropertyDescriptor(proto, prop);
497
+ if (desc)
498
+ return desc;
499
+ proto = getPrototypeOf(proto);
500
+ }
501
+ return void 0;
502
+ }
503
+ function markChanged(state) {
504
+ if (!state.modified_) {
505
+ state.modified_ = true;
506
+ if (state.parent_) {
507
+ markChanged(state.parent_);
508
+ }
509
+ }
510
+ }
511
+ function prepareCopy(state) {
512
+ if (!state.copy_) {
513
+ state.copy_ = shallowCopy(
514
+ state.base_,
515
+ state.scope_.immer_.useStrictShallowCopy_
516
+ );
517
+ }
518
+ }
519
+
520
+ // src/core/immerClass.ts
521
+ var Immer2 = class {
522
+ constructor(config) {
523
+ this.autoFreeze_ = true;
524
+ this.useStrictShallowCopy_ = false;
525
+ /**
526
+ * The `produce` function takes a value and a "recipe function" (whose
527
+ * return value often depends on the base state). The recipe function is
528
+ * free to mutate its first argument however it wants. All mutations are
529
+ * only ever applied to a __copy__ of the base state.
530
+ *
531
+ * Pass only a function to create a "curried producer" which relieves you
532
+ * from passing the recipe function every time.
533
+ *
534
+ * Only plain objects and arrays are made mutable. All other objects are
535
+ * considered uncopyable.
536
+ *
537
+ * Note: This function is __bound__ to its `Immer` instance.
538
+ *
539
+ * @param {any} base - the initial state
540
+ * @param {Function} recipe - function that receives a proxy of the base state as first argument and which can be freely modified
541
+ * @param {Function} patchListener - optional function that will be called with all the patches produced here
542
+ * @returns {any} a new state, or the initial state if nothing was modified
543
+ */
544
+ this.produce = (base, recipe, patchListener) => {
545
+ if (typeof base === "function" && typeof recipe !== "function") {
546
+ const defaultBase = recipe;
547
+ recipe = base;
548
+ const self = this;
549
+ return function curriedProduce(base2 = defaultBase, ...args) {
550
+ return self.produce(base2, (draft) => recipe.call(this, draft, ...args));
551
+ };
552
+ }
553
+ if (typeof recipe !== "function")
554
+ die(6);
555
+ if (patchListener !== void 0 && typeof patchListener !== "function")
556
+ die(7);
557
+ let result;
558
+ if (isDraftable(base)) {
559
+ const scope = enterScope(this);
560
+ const proxy = createProxy(base, void 0);
561
+ let hasError = true;
562
+ try {
563
+ result = recipe(proxy);
564
+ hasError = false;
565
+ } finally {
566
+ if (hasError)
567
+ revokeScope(scope);
568
+ else
569
+ leaveScope(scope);
570
+ }
571
+ usePatchesInScope(scope, patchListener);
572
+ return processResult(result, scope);
573
+ } else if (!base || typeof base !== "object") {
574
+ result = recipe(base);
575
+ if (result === void 0)
576
+ result = base;
577
+ if (result === NOTHING)
578
+ result = void 0;
579
+ if (this.autoFreeze_)
580
+ freeze(result, true);
581
+ if (patchListener) {
582
+ const p = [];
583
+ const ip = [];
584
+ getPlugin("Patches").generateReplacementPatches_(base, result, p, ip);
585
+ patchListener(p, ip);
586
+ }
587
+ return result;
588
+ } else
589
+ die(1, base);
590
+ };
591
+ this.produceWithPatches = (base, recipe) => {
592
+ if (typeof base === "function") {
593
+ return (state, ...args) => this.produceWithPatches(state, (draft) => base(draft, ...args));
594
+ }
595
+ let patches, inversePatches;
596
+ const result = this.produce(base, recipe, (p, ip) => {
597
+ patches = p;
598
+ inversePatches = ip;
599
+ });
600
+ return [result, patches, inversePatches];
601
+ };
602
+ if (typeof config?.autoFreeze === "boolean")
603
+ this.setAutoFreeze(config.autoFreeze);
604
+ if (typeof config?.useStrictShallowCopy === "boolean")
605
+ this.setUseStrictShallowCopy(config.useStrictShallowCopy);
606
+ }
607
+ createDraft(base) {
608
+ if (!isDraftable(base))
609
+ die(8);
610
+ if (isDraft(base))
611
+ base = current(base);
612
+ const scope = enterScope(this);
613
+ const proxy = createProxy(base, void 0);
614
+ proxy[DRAFT_STATE].isManual_ = true;
615
+ leaveScope(scope);
616
+ return proxy;
617
+ }
618
+ finishDraft(draft, patchListener) {
619
+ const state = draft && draft[DRAFT_STATE];
620
+ if (!state || !state.isManual_)
621
+ die(9);
622
+ const { scope_: scope } = state;
623
+ usePatchesInScope(scope, patchListener);
624
+ return processResult(void 0, scope);
625
+ }
626
+ /**
627
+ * Pass true to automatically freeze all copies created by Immer.
628
+ *
629
+ * By default, auto-freezing is enabled.
630
+ */
631
+ setAutoFreeze(value) {
632
+ this.autoFreeze_ = value;
633
+ }
634
+ /**
635
+ * Pass true to enable strict shallow copy.
636
+ *
637
+ * By default, immer does not copy the object descriptors such as getter, setter and non-enumrable properties.
638
+ */
639
+ setUseStrictShallowCopy(value) {
640
+ this.useStrictShallowCopy_ = value;
641
+ }
642
+ applyPatches(base, patches) {
643
+ let i;
644
+ for (i = patches.length - 1; i >= 0; i--) {
645
+ const patch = patches[i];
646
+ if (patch.path.length === 0 && patch.op === "replace") {
647
+ base = patch.value;
648
+ break;
649
+ }
650
+ }
651
+ if (i > -1) {
652
+ patches = patches.slice(i + 1);
653
+ }
654
+ const applyPatchesImpl = getPlugin("Patches").applyPatches_;
655
+ if (isDraft(base)) {
656
+ return applyPatchesImpl(base, patches);
657
+ }
658
+ return this.produce(
659
+ base,
660
+ (draft) => applyPatchesImpl(draft, patches)
661
+ );
662
+ }
663
+ };
664
+ function createProxy(value, parent) {
665
+ const draft = isMap(value) ? getPlugin("MapSet").proxyMap_(value, parent) : isSet(value) ? getPlugin("MapSet").proxySet_(value, parent) : createProxyProxy(value, parent);
666
+ const scope = parent ? parent.scope_ : getCurrentScope();
667
+ scope.drafts_.push(draft);
668
+ return draft;
669
+ }
670
+
671
+ // src/core/current.ts
672
+ function current(value) {
673
+ if (!isDraft(value))
674
+ die(10, value);
675
+ return currentImpl(value);
676
+ }
677
+ function currentImpl(value) {
678
+ if (!isDraftable(value) || isFrozen(value))
679
+ return value;
680
+ const state = value[DRAFT_STATE];
681
+ let copy;
682
+ if (state) {
683
+ if (!state.modified_)
684
+ return state.base_;
685
+ state.finalized_ = true;
686
+ copy = shallowCopy(value, state.scope_.immer_.useStrictShallowCopy_);
687
+ } else {
688
+ copy = shallowCopy(value, true);
689
+ }
690
+ each(copy, (key, childValue) => {
691
+ set(copy, key, currentImpl(childValue));
692
+ });
693
+ if (state) {
694
+ state.finalized_ = false;
695
+ }
696
+ return copy;
697
+ }
698
+
699
+ // src/immer.ts
700
+ var immer = new Immer2();
701
+ var produce = immer.produce;
702
+ immer.produceWithPatches.bind(
703
+ immer
704
+ );
705
+ immer.setAutoFreeze.bind(immer);
706
+ immer.setUseStrictShallowCopy.bind(immer);
707
+ immer.applyPatches.bind(immer);
708
+ immer.createDraft.bind(immer);
709
+ immer.finishDraft.bind(immer);
710
+
711
+ const saveState = (key, value, encrypt = false) => {
712
+ if (typeof window !== "undefined") {
713
+ let data = JSON.stringify(value);
714
+ if (encrypt) data = btoa(data);
715
+ localStorage.setItem(key, data);
716
+ }
717
+ };
718
+ const restoreState = (key) => {
719
+ if (typeof window !== "undefined") {
720
+ const data = localStorage.getItem(key);
721
+ return data ? JSON.parse(atob(data)) : void 0;
722
+ }
723
+ };
724
+
725
+ var shim = {exports: {}};
726
+
727
+ var useSyncExternalStoreShim_production = {};
728
+
729
+ /**
730
+ * @license React
731
+ * use-sync-external-store-shim.production.js
732
+ *
733
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
734
+ *
735
+ * This source code is licensed under the MIT license found in the
736
+ * LICENSE file in the root directory of this source tree.
737
+ */
738
+
739
+ var hasRequiredUseSyncExternalStoreShim_production;
740
+
741
+ function requireUseSyncExternalStoreShim_production () {
742
+ if (hasRequiredUseSyncExternalStoreShim_production) return useSyncExternalStoreShim_production;
743
+ hasRequiredUseSyncExternalStoreShim_production = 1;
744
+ var React = require$$0;
745
+ function is(x, y) {
746
+ return (x === y && (0 !== x || 1 / x === 1 / y)) || (x !== x && y !== y);
747
+ }
748
+ var objectIs = "function" === typeof Object.is ? Object.is : is,
749
+ useState = React.useState,
750
+ useEffect = React.useEffect,
751
+ useLayoutEffect = React.useLayoutEffect,
752
+ useDebugValue = React.useDebugValue;
753
+ function useSyncExternalStore$2(subscribe, getSnapshot) {
754
+ var value = getSnapshot(),
755
+ _useState = useState({ inst: { value: value, getSnapshot: getSnapshot } }),
756
+ inst = _useState[0].inst,
757
+ forceUpdate = _useState[1];
758
+ useLayoutEffect(
759
+ function () {
760
+ inst.value = value;
761
+ inst.getSnapshot = getSnapshot;
762
+ checkIfSnapshotChanged(inst) && forceUpdate({ inst: inst });
763
+ },
764
+ [subscribe, value, getSnapshot]
765
+ );
766
+ useEffect(
767
+ function () {
768
+ checkIfSnapshotChanged(inst) && forceUpdate({ inst: inst });
769
+ return subscribe(function () {
770
+ checkIfSnapshotChanged(inst) && forceUpdate({ inst: inst });
771
+ });
772
+ },
773
+ [subscribe]
774
+ );
775
+ useDebugValue(value);
776
+ return value;
777
+ }
778
+ function checkIfSnapshotChanged(inst) {
779
+ var latestGetSnapshot = inst.getSnapshot;
780
+ inst = inst.value;
781
+ try {
782
+ var nextValue = latestGetSnapshot();
783
+ return !objectIs(inst, nextValue);
784
+ } catch (error) {
785
+ return !0;
786
+ }
787
+ }
788
+ function useSyncExternalStore$1(subscribe, getSnapshot) {
789
+ return getSnapshot();
790
+ }
791
+ var shim =
792
+ "undefined" === typeof window ||
793
+ "undefined" === typeof window.document ||
794
+ "undefined" === typeof window.document.createElement
795
+ ? useSyncExternalStore$1
796
+ : useSyncExternalStore$2;
797
+ useSyncExternalStoreShim_production.useSyncExternalStore =
798
+ void 0 !== React.useSyncExternalStore ? React.useSyncExternalStore : shim;
799
+ return useSyncExternalStoreShim_production;
800
+ }
801
+
802
+ var useSyncExternalStoreShim_development = {};
803
+
804
+ /**
805
+ * @license React
806
+ * use-sync-external-store-shim.development.js
807
+ *
808
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
809
+ *
810
+ * This source code is licensed under the MIT license found in the
811
+ * LICENSE file in the root directory of this source tree.
812
+ */
813
+
814
+ var hasRequiredUseSyncExternalStoreShim_development;
815
+
816
+ function requireUseSyncExternalStoreShim_development () {
817
+ if (hasRequiredUseSyncExternalStoreShim_development) return useSyncExternalStoreShim_development;
818
+ hasRequiredUseSyncExternalStoreShim_development = 1;
819
+ "production" !== process.env.NODE_ENV &&
820
+ (function () {
821
+ function is(x, y) {
822
+ return (x === y && (0 !== x || 1 / x === 1 / y)) || (x !== x && y !== y);
823
+ }
824
+ function useSyncExternalStore$2(subscribe, getSnapshot) {
825
+ didWarnOld18Alpha ||
826
+ void 0 === React.startTransition ||
827
+ ((didWarnOld18Alpha = !0),
828
+ console.error(
829
+ "You are using an outdated, pre-release alpha of React 18 that does not support useSyncExternalStore. The use-sync-external-store shim will not work correctly. Upgrade to a newer pre-release."
830
+ ));
831
+ var value = getSnapshot();
832
+ if (!didWarnUncachedGetSnapshot) {
833
+ var cachedValue = getSnapshot();
834
+ objectIs(value, cachedValue) ||
835
+ (console.error(
836
+ "The result of getSnapshot should be cached to avoid an infinite loop"
837
+ ),
838
+ (didWarnUncachedGetSnapshot = !0));
839
+ }
840
+ cachedValue = useState({
841
+ inst: { value: value, getSnapshot: getSnapshot }
842
+ });
843
+ var inst = cachedValue[0].inst,
844
+ forceUpdate = cachedValue[1];
845
+ useLayoutEffect(
846
+ function () {
847
+ inst.value = value;
848
+ inst.getSnapshot = getSnapshot;
849
+ checkIfSnapshotChanged(inst) && forceUpdate({ inst: inst });
850
+ },
851
+ [subscribe, value, getSnapshot]
852
+ );
853
+ useEffect(
854
+ function () {
855
+ checkIfSnapshotChanged(inst) && forceUpdate({ inst: inst });
856
+ return subscribe(function () {
857
+ checkIfSnapshotChanged(inst) && forceUpdate({ inst: inst });
858
+ });
859
+ },
860
+ [subscribe]
861
+ );
862
+ useDebugValue(value);
863
+ return value;
864
+ }
865
+ function checkIfSnapshotChanged(inst) {
866
+ var latestGetSnapshot = inst.getSnapshot;
867
+ inst = inst.value;
868
+ try {
869
+ var nextValue = latestGetSnapshot();
870
+ return !objectIs(inst, nextValue);
871
+ } catch (error) {
872
+ return !0;
873
+ }
874
+ }
875
+ function useSyncExternalStore$1(subscribe, getSnapshot) {
876
+ return getSnapshot();
877
+ }
878
+ "undefined" !== typeof __REACT_DEVTOOLS_GLOBAL_HOOK__ &&
879
+ "function" ===
880
+ typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.registerInternalModuleStart &&
881
+ __REACT_DEVTOOLS_GLOBAL_HOOK__.registerInternalModuleStart(Error());
882
+ var React = require$$0,
883
+ objectIs = "function" === typeof Object.is ? Object.is : is,
884
+ useState = React.useState,
885
+ useEffect = React.useEffect,
886
+ useLayoutEffect = React.useLayoutEffect,
887
+ useDebugValue = React.useDebugValue,
888
+ didWarnOld18Alpha = !1,
889
+ didWarnUncachedGetSnapshot = !1,
890
+ shim =
891
+ "undefined" === typeof window ||
892
+ "undefined" === typeof window.document ||
893
+ "undefined" === typeof window.document.createElement
894
+ ? useSyncExternalStore$1
895
+ : useSyncExternalStore$2;
896
+ useSyncExternalStoreShim_development.useSyncExternalStore =
897
+ void 0 !== React.useSyncExternalStore ? React.useSyncExternalStore : shim;
898
+ "undefined" !== typeof __REACT_DEVTOOLS_GLOBAL_HOOK__ &&
899
+ "function" ===
900
+ typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.registerInternalModuleStop &&
901
+ __REACT_DEVTOOLS_GLOBAL_HOOK__.registerInternalModuleStop(Error());
902
+ })();
903
+ return useSyncExternalStoreShim_development;
904
+ }
905
+
906
+ var hasRequiredShim;
907
+
908
+ function requireShim () {
909
+ if (hasRequiredShim) return shim.exports;
910
+ hasRequiredShim = 1;
911
+
912
+ if (process.env.NODE_ENV === 'production') {
913
+ shim.exports = requireUseSyncExternalStoreShim_production();
914
+ } else {
915
+ shim.exports = requireUseSyncExternalStoreShim_development();
916
+ }
917
+ return shim.exports;
918
+ }
919
+
920
+ var shimExports = requireShim();
921
+
922
+ const stateHistory = {};
923
+ const stateIndex = {};
924
+ const performanceData = {};
925
+ const devtoolsEnabled = typeof window !== "undefined" && window.__STATE_JET_DEVTOOLS__;
926
+ const notifyDevTools = (key, value) => {
927
+ if (!stateHistory[key]) stateHistory[key] = [];
928
+ if (stateIndex[key] === void 0) stateIndex[key] = -1;
929
+ stateHistory[key] = stateHistory[key].slice(0, stateIndex[key] + 1);
930
+ stateHistory[key].push(value);
931
+ stateIndex[key]++;
932
+ if (devtoolsEnabled && window.__STATE_JET_DEVTOOLS__.updateState) {
933
+ window.__STATE_JET_DEVTOOLS__.updateState(key, value, stateHistory[key]);
934
+ }
935
+ };
936
+ const measurePerformance = (key, callback) => {
937
+ const start = performance.now();
938
+ callback();
939
+ const duration = performance.now() - start;
940
+ if (!performanceData[key]) performanceData[key] = [];
941
+ performanceData[key].push(duration);
942
+ if (devtoolsEnabled && window.__STATE_JET_DEVTOOLS__.updatePerformance) {
943
+ window.__STATE_JET_DEVTOOLS__.updatePerformance(key, duration);
944
+ }
945
+ };
946
+ const undoState = (key) => {
947
+ if (stateIndex[key] > 0) {
948
+ stateIndex[key]--;
949
+ return stateHistory[key][stateIndex[key]];
950
+ }
951
+ };
952
+ const redoState = (key) => {
953
+ if (stateIndex[key] < stateHistory[key].length - 1) {
954
+ stateIndex[key]++;
955
+ return stateHistory[key][stateIndex[key]];
956
+ }
957
+ };
958
+
959
+ const getGlobalThis = () => {
960
+ if (typeof globalThis === "object" && globalThis) return globalThis;
961
+ if (typeof self === "object" && self) return self;
962
+ if (typeof window === "object" && window) return window;
963
+ throw new Error("Unable to locate global `this`");
964
+ };
965
+ const globalObject = getGlobalThis();
966
+
967
+ const store = /* @__PURE__ */ new Map();
968
+ const pendingUpdates = /* @__PURE__ */ new Map();
969
+ const history = {};
970
+ const useStateGlobal = (key, initialValue, options) => {
971
+ if (!store.has(key)) {
972
+ store.set(key, { value: initialValue, listeners: /* @__PURE__ */ new Set() });
973
+ if (options == null ? void 0 : options.persist) restoreState(key);
974
+ }
975
+ const state = store.get(key);
976
+ const undo = () => {
977
+ var _a;
978
+ if ((_a = history[key]) == null ? void 0 : _a.past.length) {
979
+ history[key].future.unshift(history[key].present);
980
+ history[key].present = history[key].past.pop();
981
+ state.value = history[key].present;
982
+ state.listeners.forEach((listener) => listener());
983
+ undoState(key);
984
+ }
985
+ };
986
+ const batchUpdate = () => {
987
+ pendingUpdates.forEach((newValue, key2) => {
988
+ var _a;
989
+ let nextValue = newValue;
990
+ let stateValue = state.value;
991
+ if (!history[key2]) {
992
+ history[key2] = { past: [], present: stateValue, future: [] };
993
+ }
994
+ history[key2].past.push(stateValue);
995
+ history[key2].present = newValue;
996
+ history[key2].future = [];
997
+ (_a = options == null ? void 0 : options.middleware) == null ? void 0 : _a.forEach((mw) => {
998
+ const result = mw(key2, stateValue, nextValue);
999
+ if (result !== void 0) nextValue = result;
1000
+ });
1001
+ if (typeof nextValue === "function") {
1002
+ state.value = produce(state.value, nextValue);
1003
+ } else if (stateValue !== nextValue) {
1004
+ state.value = nextValue;
1005
+ state.listeners.forEach((listener) => listener());
1006
+ notifyDevTools(key2, nextValue);
1007
+ measurePerformance(key2, () => {
1008
+ });
1009
+ if (options == null ? void 0 : options.persist) saveState(key2, nextValue, options.encrypt);
1010
+ }
1011
+ });
1012
+ pendingUpdates.clear();
1013
+ };
1014
+ const redo = () => {
1015
+ var _a;
1016
+ if ((_a = history[key]) == null ? void 0 : _a.future.length) {
1017
+ history[key].past.push(history[key].present);
1018
+ history[key].present = history[key].future.shift();
1019
+ state.value = history[key].present;
1020
+ state.listeners.forEach((listener) => listener());
1021
+ redoState(key);
1022
+ }
1023
+ };
1024
+ const useStore = () => {
1025
+ return shimExports.useSyncExternalStore(
1026
+ (callback) => {
1027
+ state.listeners.add(callback);
1028
+ return () => state.listeners.delete(callback);
1029
+ },
1030
+ () => state.value
1031
+ );
1032
+ };
1033
+ const set = (newValue) => {
1034
+ var _a, _b;
1035
+ pendingUpdates.set(key, newValue);
1036
+ if ((_b = (_a = globalObject) == null ? void 0 : _a.window) == null ? void 0 : _b.requestAnimationFrame) globalObject.window.requestAnimationFrame(batchUpdate);
1037
+ };
1038
+ return {
1039
+ useStore,
1040
+ set,
1041
+ undo,
1042
+ redo
1043
+ };
1044
+ };
1045
+
1046
+ const optimisticUpdate = (setState, apiCall, fallback) => {
1047
+ const prevState = setState.useStore();
1048
+ setState.set(apiCall(prevState));
1049
+ apiCall().catch(() => setState.set(fallback ? fallback(prevState) : prevState));
1050
+ };
1051
+
1052
+ const encrypt = (data) => btoa(JSON.stringify(data));
1053
+ const decrypt = (data) => JSON.parse(atob(data));
1054
+ const saveEncryptedState = (key, value) => {
1055
+ localStorage.setItem(key, encrypt(value));
1056
+ };
1057
+ const loadEncryptedState = (key) => {
1058
+ const data = localStorage.getItem(key);
1059
+ return data ? decrypt(data) : null;
1060
+ };
1061
+
2
1062
  var __defProp = Object.defineProperty;
3
- var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
4
- var __getOwnPropNames = Object.getOwnPropertyNames;
1063
+ var __defProps = Object.defineProperties;
1064
+ var __getOwnPropDescs = Object.getOwnPropertyDescriptors;
1065
+ var __getOwnPropSymbols = Object.getOwnPropertySymbols;
5
1066
  var __hasOwnProp = Object.prototype.hasOwnProperty;
6
- var __export = (target, all) => {
7
- for (var name in all)
8
- __defProp(target, name, { get: all[name], enumerable: true });
9
- };
10
- var __copyProps = (to, from, except, desc) => {
11
- if (from && typeof from === "object" || typeof from === "function") {
12
- for (let key of __getOwnPropNames(from))
13
- if (!__hasOwnProp.call(to, key) && key !== except)
14
- __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
15
- }
16
- return to;
17
- };
18
- var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
19
- var index_exports = {};
20
- __export(index_exports, {
21
- decrypt: () => import_encryption.decrypt,
22
- encrypt: () => import_encryption.encrypt,
23
- loadEncryptedState: () => import_encryption.loadEncryptedState,
24
- optimisticUpdate: () => import_optimistic.optimisticUpdate,
25
- restoreState: () => import_persistence.restoreState,
26
- saveEncryptedState: () => import_encryption.saveEncryptedState,
27
- saveState: () => import_persistence.saveState,
28
- syncCRDT: () => import_crdt.syncCRDT,
29
- useStateGlobal: () => import_store.useStateGlobal
30
- });
31
- module.exports = __toCommonJS(index_exports);
32
- var import_store = require("./store");
33
- var import_persistence = require("./persistence");
34
- var import_optimistic = require("./optimistic");
35
- var import_encryption = require("./encryption");
36
- var import_crdt = require("./crdt");
1067
+ var __propIsEnum = Object.prototype.propertyIsEnumerable;
1068
+ var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
1069
+ var __spreadValues = (a, b) => {
1070
+ for (var prop in b || (b = {}))
1071
+ if (__hasOwnProp.call(b, prop))
1072
+ __defNormalProp(a, prop, b[prop]);
1073
+ if (__getOwnPropSymbols)
1074
+ for (var prop of __getOwnPropSymbols(b)) {
1075
+ if (__propIsEnum.call(b, prop))
1076
+ __defNormalProp(a, prop, b[prop]);
1077
+ }
1078
+ return a;
1079
+ };
1080
+ var __spreadProps = (a, b) => __defProps(a, __getOwnPropDescs(b));
1081
+ const mergeCRDT = (localState, remoteState) => {
1082
+ return __spreadProps(__spreadValues(__spreadValues({}, localState), remoteState), { lastUpdated: Date.now() });
1083
+ };
1084
+ const syncCRDT = (key, remoteState) => {
1085
+ const localState = useStateGlobal(key).useStore();
1086
+ const merged = mergeCRDT(localState, remoteState);
1087
+ useStateGlobal(key).set(merged);
1088
+ };
1089
+
1090
+ exports.decrypt = decrypt;
1091
+ exports.encrypt = encrypt;
1092
+ exports.loadEncryptedState = loadEncryptedState;
1093
+ exports.optimisticUpdate = optimisticUpdate;
1094
+ exports.restoreState = restoreState;
1095
+ exports.saveEncryptedState = saveEncryptedState;
1096
+ exports.saveState = saveState;
1097
+ exports.syncCRDT = syncCRDT;
1098
+ exports.useStateGlobal = useStateGlobal;
1099
+ //# sourceMappingURL=index.cjs.map