@vitejs/devtools-kit 0.1.3 → 0.1.5

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.
@@ -0,0 +1,928 @@
1
+ import { createEventEmitter } from "./utils/events.js";
2
+ import { nanoid } from "./utils/nanoid.js";
3
+ //#region ../../node_modules/.pnpm/immer@11.1.4/node_modules/immer/dist/immer.mjs
4
+ var NOTHING = Symbol.for("immer-nothing");
5
+ var DRAFTABLE = Symbol.for("immer-draftable");
6
+ var DRAFT_STATE = Symbol.for("immer-state");
7
+ var errors = process.env.NODE_ENV !== "production" ? [
8
+ function(plugin) {
9
+ return `The plugin for '${plugin}' has not been loaded into Immer. To enable the plugin, import and call \`enable${plugin}()\` when initializing your application.`;
10
+ },
11
+ function(thing) {
12
+ 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}'`;
13
+ },
14
+ "This object has been frozen and should not be mutated",
15
+ function(data) {
16
+ return "Cannot use a proxy that has been revoked. Did you pass an object from inside an immer function to an async process? " + data;
17
+ },
18
+ "An immer producer returned a new value *and* modified its draft. Either return a new value *or* modify the draft.",
19
+ "Immer forbids circular references",
20
+ "The first or second argument to `produce` must be a function",
21
+ "The third argument to `produce` must be a function or undefined",
22
+ "First argument to `createDraft` must be a plain object, an array, or an immerable object",
23
+ "First argument to `finishDraft` must be a draft returned by `createDraft`",
24
+ function(thing) {
25
+ return `'current' expects a draft, got: ${thing}`;
26
+ },
27
+ "Object.defineProperty() cannot be used on an Immer draft",
28
+ "Object.setPrototypeOf() cannot be used on an Immer draft",
29
+ "Immer only supports deleting array indices",
30
+ "Immer only supports setting array indices and the 'length' property",
31
+ function(thing) {
32
+ return `'original' expects a draft, got: ${thing}`;
33
+ }
34
+ ] : [];
35
+ function die(error, ...args) {
36
+ if (process.env.NODE_ENV !== "production") {
37
+ const e = errors[error];
38
+ const msg = isFunction(e) ? e.apply(null, args) : e;
39
+ throw new Error(`[Immer] ${msg}`);
40
+ }
41
+ throw new Error(`[Immer] minified error nr: ${error}. Full error at: https://bit.ly/3cXEKWf`);
42
+ }
43
+ var O = Object;
44
+ var getPrototypeOf = O.getPrototypeOf;
45
+ var CONSTRUCTOR = "constructor";
46
+ var PROTOTYPE = "prototype";
47
+ var CONFIGURABLE = "configurable";
48
+ var ENUMERABLE = "enumerable";
49
+ var WRITABLE = "writable";
50
+ var VALUE = "value";
51
+ var isDraft = (value) => !!value && !!value[DRAFT_STATE];
52
+ function isDraftable(value) {
53
+ if (!value) return false;
54
+ return isPlainObject(value) || isArray(value) || !!value[DRAFTABLE] || !!value[CONSTRUCTOR]?.[DRAFTABLE] || isMap(value) || isSet(value);
55
+ }
56
+ var objectCtorString = O[PROTOTYPE][CONSTRUCTOR].toString();
57
+ var cachedCtorStrings = /* @__PURE__ */ new WeakMap();
58
+ function isPlainObject(value) {
59
+ if (!value || !isObjectish(value)) return false;
60
+ const proto = getPrototypeOf(value);
61
+ if (proto === null || proto === O[PROTOTYPE]) return true;
62
+ const Ctor = O.hasOwnProperty.call(proto, CONSTRUCTOR) && proto[CONSTRUCTOR];
63
+ if (Ctor === Object) return true;
64
+ if (!isFunction(Ctor)) return false;
65
+ let ctorString = cachedCtorStrings.get(Ctor);
66
+ if (ctorString === void 0) {
67
+ ctorString = Function.toString.call(Ctor);
68
+ cachedCtorStrings.set(Ctor, ctorString);
69
+ }
70
+ return ctorString === objectCtorString;
71
+ }
72
+ function each(obj, iter, strict = true) {
73
+ if (getArchtype(obj) === 0) (strict ? Reflect.ownKeys(obj) : O.keys(obj)).forEach((key) => {
74
+ iter(key, obj[key], obj);
75
+ });
76
+ else obj.forEach((entry, index) => iter(index, entry, obj));
77
+ }
78
+ function getArchtype(thing) {
79
+ const state = thing[DRAFT_STATE];
80
+ return state ? state.type_ : isArray(thing) ? 1 : isMap(thing) ? 2 : isSet(thing) ? 3 : 0;
81
+ }
82
+ var has = (thing, prop, type = getArchtype(thing)) => type === 2 ? thing.has(prop) : O[PROTOTYPE].hasOwnProperty.call(thing, prop);
83
+ var get = (thing, prop, type = getArchtype(thing)) => type === 2 ? thing.get(prop) : thing[prop];
84
+ var set = (thing, propOrOldValue, value, type = getArchtype(thing)) => {
85
+ if (type === 2) thing.set(propOrOldValue, value);
86
+ else if (type === 3) thing.add(value);
87
+ else thing[propOrOldValue] = value;
88
+ };
89
+ function is(x, y) {
90
+ if (x === y) return x !== 0 || 1 / x === 1 / y;
91
+ else return x !== x && y !== y;
92
+ }
93
+ var isArray = Array.isArray;
94
+ var isMap = (target) => target instanceof Map;
95
+ var isSet = (target) => target instanceof Set;
96
+ var isObjectish = (target) => typeof target === "object";
97
+ var isFunction = (target) => typeof target === "function";
98
+ var isBoolean = (target) => typeof target === "boolean";
99
+ function isArrayIndex(value) {
100
+ const n = +value;
101
+ return Number.isInteger(n) && String(n) === value;
102
+ }
103
+ var getProxyDraft = (value) => {
104
+ if (!isObjectish(value)) return null;
105
+ return value?.[DRAFT_STATE];
106
+ };
107
+ var latest = (state) => state.copy_ || state.base_;
108
+ var getFinalValue = (state) => state.modified_ ? state.copy_ : state.base_;
109
+ function shallowCopy(base, strict) {
110
+ if (isMap(base)) return new Map(base);
111
+ if (isSet(base)) return new Set(base);
112
+ if (isArray(base)) return Array[PROTOTYPE].slice.call(base);
113
+ const isPlain = isPlainObject(base);
114
+ if (strict === true || strict === "class_only" && !isPlain) {
115
+ const descriptors = O.getOwnPropertyDescriptors(base);
116
+ delete descriptors[DRAFT_STATE];
117
+ let keys = Reflect.ownKeys(descriptors);
118
+ for (let i = 0; i < keys.length; i++) {
119
+ const key = keys[i];
120
+ const desc = descriptors[key];
121
+ if (desc[WRITABLE] === false) {
122
+ desc[WRITABLE] = true;
123
+ desc[CONFIGURABLE] = true;
124
+ }
125
+ if (desc.get || desc.set) descriptors[key] = {
126
+ [CONFIGURABLE]: true,
127
+ [WRITABLE]: true,
128
+ [ENUMERABLE]: desc[ENUMERABLE],
129
+ [VALUE]: base[key]
130
+ };
131
+ }
132
+ return O.create(getPrototypeOf(base), descriptors);
133
+ } else {
134
+ const proto = getPrototypeOf(base);
135
+ if (proto !== null && isPlain) return { ...base };
136
+ const obj = O.create(proto);
137
+ return O.assign(obj, base);
138
+ }
139
+ }
140
+ function freeze(obj, deep = false) {
141
+ if (isFrozen(obj) || isDraft(obj) || !isDraftable(obj)) return obj;
142
+ if (getArchtype(obj) > 1) O.defineProperties(obj, {
143
+ set: dontMutateMethodOverride,
144
+ add: dontMutateMethodOverride,
145
+ clear: dontMutateMethodOverride,
146
+ delete: dontMutateMethodOverride
147
+ });
148
+ O.freeze(obj);
149
+ if (deep) each(obj, (_key, value) => {
150
+ freeze(value, true);
151
+ }, false);
152
+ return obj;
153
+ }
154
+ function dontMutateFrozenCollections() {
155
+ die(2);
156
+ }
157
+ var dontMutateMethodOverride = { [VALUE]: dontMutateFrozenCollections };
158
+ function isFrozen(obj) {
159
+ if (obj === null || !isObjectish(obj)) return true;
160
+ return O.isFrozen(obj);
161
+ }
162
+ var PluginMapSet = "MapSet";
163
+ var PluginPatches = "Patches";
164
+ var PluginArrayMethods = "ArrayMethods";
165
+ var plugins = {};
166
+ function getPlugin(pluginKey) {
167
+ const plugin = plugins[pluginKey];
168
+ if (!plugin) die(0, pluginKey);
169
+ return plugin;
170
+ }
171
+ var isPluginLoaded = (pluginKey) => !!plugins[pluginKey];
172
+ function loadPlugin(pluginKey, implementation) {
173
+ if (!plugins[pluginKey]) plugins[pluginKey] = implementation;
174
+ }
175
+ var currentScope;
176
+ var getCurrentScope = () => currentScope;
177
+ var createScope = (parent_, immer_) => ({
178
+ drafts_: [],
179
+ parent_,
180
+ immer_,
181
+ canAutoFreeze_: true,
182
+ unfinalizedDrafts_: 0,
183
+ handledSet_: /* @__PURE__ */ new Set(),
184
+ processedForPatches_: /* @__PURE__ */ new Set(),
185
+ mapSetPlugin_: isPluginLoaded(PluginMapSet) ? getPlugin(PluginMapSet) : void 0,
186
+ arrayMethodsPlugin_: isPluginLoaded(PluginArrayMethods) ? getPlugin(PluginArrayMethods) : void 0
187
+ });
188
+ function usePatchesInScope(scope, patchListener) {
189
+ if (patchListener) {
190
+ scope.patchPlugin_ = getPlugin(PluginPatches);
191
+ scope.patches_ = [];
192
+ scope.inversePatches_ = [];
193
+ scope.patchListener_ = patchListener;
194
+ }
195
+ }
196
+ function revokeScope(scope) {
197
+ leaveScope(scope);
198
+ scope.drafts_.forEach(revokeDraft);
199
+ scope.drafts_ = null;
200
+ }
201
+ function leaveScope(scope) {
202
+ if (scope === currentScope) currentScope = scope.parent_;
203
+ }
204
+ var enterScope = (immer2) => currentScope = createScope(currentScope, immer2);
205
+ function revokeDraft(draft) {
206
+ const state = draft[DRAFT_STATE];
207
+ if (state.type_ === 0 || state.type_ === 1) state.revoke_();
208
+ else state.revoked_ = true;
209
+ }
210
+ function processResult(result, scope) {
211
+ scope.unfinalizedDrafts_ = scope.drafts_.length;
212
+ const baseDraft = scope.drafts_[0];
213
+ if (result !== void 0 && result !== baseDraft) {
214
+ if (baseDraft[DRAFT_STATE].modified_) {
215
+ revokeScope(scope);
216
+ die(4);
217
+ }
218
+ if (isDraftable(result)) result = finalize(scope, result);
219
+ const { patchPlugin_ } = scope;
220
+ if (patchPlugin_) patchPlugin_.generateReplacementPatches_(baseDraft[DRAFT_STATE].base_, result, scope);
221
+ } else result = finalize(scope, baseDraft);
222
+ maybeFreeze(scope, result, true);
223
+ revokeScope(scope);
224
+ if (scope.patches_) scope.patchListener_(scope.patches_, scope.inversePatches_);
225
+ return result !== NOTHING ? result : void 0;
226
+ }
227
+ function finalize(rootScope, value) {
228
+ if (isFrozen(value)) return value;
229
+ const state = value[DRAFT_STATE];
230
+ if (!state) return handleValue(value, rootScope.handledSet_, rootScope);
231
+ if (!isSameScope(state, rootScope)) return value;
232
+ if (!state.modified_) return state.base_;
233
+ if (!state.finalized_) {
234
+ const { callbacks_ } = state;
235
+ if (callbacks_) while (callbacks_.length > 0) callbacks_.pop()(rootScope);
236
+ generatePatchesAndFinalize(state, rootScope);
237
+ }
238
+ return state.copy_;
239
+ }
240
+ function maybeFreeze(scope, value, deep = false) {
241
+ if (!scope.parent_ && scope.immer_.autoFreeze_ && scope.canAutoFreeze_) freeze(value, deep);
242
+ }
243
+ function markStateFinalized(state) {
244
+ state.finalized_ = true;
245
+ state.scope_.unfinalizedDrafts_--;
246
+ }
247
+ var isSameScope = (state, rootScope) => state.scope_ === rootScope;
248
+ var EMPTY_LOCATIONS_RESULT = [];
249
+ function updateDraftInParent(parent, draftValue, finalizedValue, originalKey) {
250
+ const parentCopy = latest(parent);
251
+ const parentType = parent.type_;
252
+ if (originalKey !== void 0) {
253
+ if (get(parentCopy, originalKey, parentType) === draftValue) {
254
+ set(parentCopy, originalKey, finalizedValue, parentType);
255
+ return;
256
+ }
257
+ }
258
+ if (!parent.draftLocations_) {
259
+ const draftLocations = parent.draftLocations_ = /* @__PURE__ */ new Map();
260
+ each(parentCopy, (key, value) => {
261
+ if (isDraft(value)) {
262
+ const keys = draftLocations.get(value) || [];
263
+ keys.push(key);
264
+ draftLocations.set(value, keys);
265
+ }
266
+ });
267
+ }
268
+ const locations = parent.draftLocations_.get(draftValue) ?? EMPTY_LOCATIONS_RESULT;
269
+ for (const location of locations) set(parentCopy, location, finalizedValue, parentType);
270
+ }
271
+ function registerChildFinalizationCallback(parent, child, key) {
272
+ parent.callbacks_.push(function childCleanup(rootScope) {
273
+ const state = child;
274
+ if (!state || !isSameScope(state, rootScope)) return;
275
+ rootScope.mapSetPlugin_?.fixSetContents(state);
276
+ const finalizedValue = getFinalValue(state);
277
+ updateDraftInParent(parent, state.draft_ ?? state, finalizedValue, key);
278
+ generatePatchesAndFinalize(state, rootScope);
279
+ });
280
+ }
281
+ function generatePatchesAndFinalize(state, rootScope) {
282
+ if (state.modified_ && !state.finalized_ && (state.type_ === 3 || state.type_ === 1 && state.allIndicesReassigned_ || (state.assigned_?.size ?? 0) > 0)) {
283
+ const { patchPlugin_ } = rootScope;
284
+ if (patchPlugin_) {
285
+ const basePath = patchPlugin_.getPath(state);
286
+ if (basePath) patchPlugin_.generatePatches_(state, basePath, rootScope);
287
+ }
288
+ markStateFinalized(state);
289
+ }
290
+ }
291
+ function handleCrossReference(target, key, value) {
292
+ const { scope_ } = target;
293
+ if (isDraft(value)) {
294
+ const state = value[DRAFT_STATE];
295
+ if (isSameScope(state, scope_)) state.callbacks_.push(function crossReferenceCleanup() {
296
+ prepareCopy(target);
297
+ updateDraftInParent(target, value, getFinalValue(state), key);
298
+ });
299
+ } else if (isDraftable(value)) target.callbacks_.push(function nestedDraftCleanup() {
300
+ const targetCopy = latest(target);
301
+ if (target.type_ === 3) {
302
+ if (targetCopy.has(value)) handleValue(value, scope_.handledSet_, scope_);
303
+ } else if (get(targetCopy, key, target.type_) === value) {
304
+ if (scope_.drafts_.length > 1 && (target.assigned_.get(key) ?? false) === true && target.copy_) handleValue(get(target.copy_, key, target.type_), scope_.handledSet_, scope_);
305
+ }
306
+ });
307
+ }
308
+ function handleValue(target, handledSet, rootScope) {
309
+ if (!rootScope.immer_.autoFreeze_ && rootScope.unfinalizedDrafts_ < 1) return target;
310
+ if (isDraft(target) || handledSet.has(target) || !isDraftable(target) || isFrozen(target)) return target;
311
+ handledSet.add(target);
312
+ each(target, (key, value) => {
313
+ if (isDraft(value)) {
314
+ const state = value[DRAFT_STATE];
315
+ if (isSameScope(state, rootScope)) {
316
+ set(target, key, getFinalValue(state), target.type_);
317
+ markStateFinalized(state);
318
+ }
319
+ } else if (isDraftable(value)) handleValue(value, handledSet, rootScope);
320
+ });
321
+ return target;
322
+ }
323
+ function createProxyProxy(base, parent) {
324
+ const baseIsArray = isArray(base);
325
+ const state = {
326
+ type_: baseIsArray ? 1 : 0,
327
+ scope_: parent ? parent.scope_ : getCurrentScope(),
328
+ modified_: false,
329
+ finalized_: false,
330
+ assigned_: void 0,
331
+ parent_: parent,
332
+ base_: base,
333
+ draft_: null,
334
+ copy_: null,
335
+ revoke_: null,
336
+ isManual_: false,
337
+ callbacks_: void 0
338
+ };
339
+ let target = state;
340
+ let traps = objectTraps;
341
+ if (baseIsArray) {
342
+ target = [state];
343
+ traps = arrayTraps;
344
+ }
345
+ const { revoke, proxy } = Proxy.revocable(target, traps);
346
+ state.draft_ = proxy;
347
+ state.revoke_ = revoke;
348
+ return [proxy, state];
349
+ }
350
+ var objectTraps = {
351
+ get(state, prop) {
352
+ if (prop === DRAFT_STATE) return state;
353
+ let arrayPlugin = state.scope_.arrayMethodsPlugin_;
354
+ const isArrayWithStringProp = state.type_ === 1 && typeof prop === "string";
355
+ if (isArrayWithStringProp) {
356
+ if (arrayPlugin?.isArrayOperationMethod(prop)) return arrayPlugin.createMethodInterceptor(state, prop);
357
+ }
358
+ const source = latest(state);
359
+ if (!has(source, prop, state.type_)) return readPropFromProto(state, source, prop);
360
+ const value = source[prop];
361
+ if (state.finalized_ || !isDraftable(value)) return value;
362
+ if (isArrayWithStringProp && state.operationMethod && arrayPlugin?.isMutatingArrayMethod(state.operationMethod) && isArrayIndex(prop)) return value;
363
+ if (value === peek(state.base_, prop)) {
364
+ prepareCopy(state);
365
+ const childKey = state.type_ === 1 ? +prop : prop;
366
+ const childDraft = createProxy(state.scope_, value, state, childKey);
367
+ return state.copy_[childKey] = childDraft;
368
+ }
369
+ return value;
370
+ },
371
+ has(state, prop) {
372
+ return prop in latest(state);
373
+ },
374
+ ownKeys(state) {
375
+ return Reflect.ownKeys(latest(state));
376
+ },
377
+ set(state, prop, value) {
378
+ const desc = getDescriptorFromProto(latest(state), prop);
379
+ if (desc?.set) {
380
+ desc.set.call(state.draft_, value);
381
+ return true;
382
+ }
383
+ if (!state.modified_) {
384
+ const current2 = peek(latest(state), prop);
385
+ const currentState = current2?.[DRAFT_STATE];
386
+ if (currentState && currentState.base_ === value) {
387
+ state.copy_[prop] = value;
388
+ state.assigned_.set(prop, false);
389
+ return true;
390
+ }
391
+ if (is(value, current2) && (value !== void 0 || has(state.base_, prop, state.type_))) return true;
392
+ prepareCopy(state);
393
+ markChanged(state);
394
+ }
395
+ if (state.copy_[prop] === value && (value !== void 0 || prop in state.copy_) || Number.isNaN(value) && Number.isNaN(state.copy_[prop])) return true;
396
+ state.copy_[prop] = value;
397
+ state.assigned_.set(prop, true);
398
+ handleCrossReference(state, prop, value);
399
+ return true;
400
+ },
401
+ deleteProperty(state, prop) {
402
+ prepareCopy(state);
403
+ if (peek(state.base_, prop) !== void 0 || prop in state.base_) {
404
+ state.assigned_.set(prop, false);
405
+ markChanged(state);
406
+ } else state.assigned_.delete(prop);
407
+ if (state.copy_) delete state.copy_[prop];
408
+ return true;
409
+ },
410
+ getOwnPropertyDescriptor(state, prop) {
411
+ const owner = latest(state);
412
+ const desc = Reflect.getOwnPropertyDescriptor(owner, prop);
413
+ if (!desc) return desc;
414
+ return {
415
+ [WRITABLE]: true,
416
+ [CONFIGURABLE]: state.type_ !== 1 || prop !== "length",
417
+ [ENUMERABLE]: desc[ENUMERABLE],
418
+ [VALUE]: owner[prop]
419
+ };
420
+ },
421
+ defineProperty() {
422
+ die(11);
423
+ },
424
+ getPrototypeOf(state) {
425
+ return getPrototypeOf(state.base_);
426
+ },
427
+ setPrototypeOf() {
428
+ die(12);
429
+ }
430
+ };
431
+ var arrayTraps = {};
432
+ for (let key in objectTraps) {
433
+ let fn = objectTraps[key];
434
+ arrayTraps[key] = function() {
435
+ const args = arguments;
436
+ args[0] = args[0][0];
437
+ return fn.apply(this, args);
438
+ };
439
+ }
440
+ arrayTraps.deleteProperty = function(state, prop) {
441
+ if (process.env.NODE_ENV !== "production" && isNaN(parseInt(prop))) die(13);
442
+ return arrayTraps.set.call(this, state, prop, void 0);
443
+ };
444
+ arrayTraps.set = function(state, prop, value) {
445
+ if (process.env.NODE_ENV !== "production" && prop !== "length" && isNaN(parseInt(prop))) die(14);
446
+ return objectTraps.set.call(this, state[0], prop, value, state[0]);
447
+ };
448
+ function peek(draft, prop) {
449
+ const state = draft[DRAFT_STATE];
450
+ return (state ? latest(state) : draft)[prop];
451
+ }
452
+ function readPropFromProto(state, source, prop) {
453
+ const desc = getDescriptorFromProto(source, prop);
454
+ return desc ? VALUE in desc ? desc[VALUE] : desc.get?.call(state.draft_) : void 0;
455
+ }
456
+ function getDescriptorFromProto(source, prop) {
457
+ if (!(prop in source)) return void 0;
458
+ let proto = getPrototypeOf(source);
459
+ while (proto) {
460
+ const desc = Object.getOwnPropertyDescriptor(proto, prop);
461
+ if (desc) return desc;
462
+ proto = getPrototypeOf(proto);
463
+ }
464
+ }
465
+ function markChanged(state) {
466
+ if (!state.modified_) {
467
+ state.modified_ = true;
468
+ if (state.parent_) markChanged(state.parent_);
469
+ }
470
+ }
471
+ function prepareCopy(state) {
472
+ if (!state.copy_) {
473
+ state.assigned_ = /* @__PURE__ */ new Map();
474
+ state.copy_ = shallowCopy(state.base_, state.scope_.immer_.useStrictShallowCopy_);
475
+ }
476
+ }
477
+ var Immer2 = class {
478
+ constructor(config) {
479
+ this.autoFreeze_ = true;
480
+ this.useStrictShallowCopy_ = false;
481
+ this.useStrictIteration_ = false;
482
+ /**
483
+ * The `produce` function takes a value and a "recipe function" (whose
484
+ * return value often depends on the base state). The recipe function is
485
+ * free to mutate its first argument however it wants. All mutations are
486
+ * only ever applied to a __copy__ of the base state.
487
+ *
488
+ * Pass only a function to create a "curried producer" which relieves you
489
+ * from passing the recipe function every time.
490
+ *
491
+ * Only plain objects and arrays are made mutable. All other objects are
492
+ * considered uncopyable.
493
+ *
494
+ * Note: This function is __bound__ to its `Immer` instance.
495
+ *
496
+ * @param {any} base - the initial state
497
+ * @param {Function} recipe - function that receives a proxy of the base state as first argument and which can be freely modified
498
+ * @param {Function} patchListener - optional function that will be called with all the patches produced here
499
+ * @returns {any} a new state, or the initial state if nothing was modified
500
+ */
501
+ this.produce = (base, recipe, patchListener) => {
502
+ if (isFunction(base) && !isFunction(recipe)) {
503
+ const defaultBase = recipe;
504
+ recipe = base;
505
+ const self = this;
506
+ return function curriedProduce(base2 = defaultBase, ...args) {
507
+ return self.produce(base2, (draft) => recipe.call(this, draft, ...args));
508
+ };
509
+ }
510
+ if (!isFunction(recipe)) die(6);
511
+ if (patchListener !== void 0 && !isFunction(patchListener)) die(7);
512
+ let result;
513
+ if (isDraftable(base)) {
514
+ const scope = enterScope(this);
515
+ const proxy = createProxy(scope, base, void 0);
516
+ let hasError = true;
517
+ try {
518
+ result = recipe(proxy);
519
+ hasError = false;
520
+ } finally {
521
+ if (hasError) revokeScope(scope);
522
+ else leaveScope(scope);
523
+ }
524
+ usePatchesInScope(scope, patchListener);
525
+ return processResult(result, scope);
526
+ } else if (!base || !isObjectish(base)) {
527
+ result = recipe(base);
528
+ if (result === void 0) result = base;
529
+ if (result === NOTHING) result = void 0;
530
+ if (this.autoFreeze_) freeze(result, true);
531
+ if (patchListener) {
532
+ const p = [];
533
+ const ip = [];
534
+ getPlugin(PluginPatches).generateReplacementPatches_(base, result, {
535
+ patches_: p,
536
+ inversePatches_: ip
537
+ });
538
+ patchListener(p, ip);
539
+ }
540
+ return result;
541
+ } else die(1, base);
542
+ };
543
+ this.produceWithPatches = (base, recipe) => {
544
+ if (isFunction(base)) return (state, ...args) => this.produceWithPatches(state, (draft) => base(draft, ...args));
545
+ let patches, inversePatches;
546
+ return [
547
+ this.produce(base, recipe, (p, ip) => {
548
+ patches = p;
549
+ inversePatches = ip;
550
+ }),
551
+ patches,
552
+ inversePatches
553
+ ];
554
+ };
555
+ if (isBoolean(config?.autoFreeze)) this.setAutoFreeze(config.autoFreeze);
556
+ if (isBoolean(config?.useStrictShallowCopy)) this.setUseStrictShallowCopy(config.useStrictShallowCopy);
557
+ if (isBoolean(config?.useStrictIteration)) this.setUseStrictIteration(config.useStrictIteration);
558
+ }
559
+ createDraft(base) {
560
+ if (!isDraftable(base)) die(8);
561
+ if (isDraft(base)) base = current(base);
562
+ const scope = enterScope(this);
563
+ const proxy = createProxy(scope, base, void 0);
564
+ proxy[DRAFT_STATE].isManual_ = true;
565
+ leaveScope(scope);
566
+ return proxy;
567
+ }
568
+ finishDraft(draft, patchListener) {
569
+ const state = draft && draft[DRAFT_STATE];
570
+ if (!state || !state.isManual_) die(9);
571
+ const { scope_: scope } = state;
572
+ usePatchesInScope(scope, patchListener);
573
+ return processResult(void 0, scope);
574
+ }
575
+ /**
576
+ * Pass true to automatically freeze all copies created by Immer.
577
+ *
578
+ * By default, auto-freezing is enabled.
579
+ */
580
+ setAutoFreeze(value) {
581
+ this.autoFreeze_ = value;
582
+ }
583
+ /**
584
+ * Pass true to enable strict shallow copy.
585
+ *
586
+ * By default, immer does not copy the object descriptors such as getter, setter and non-enumrable properties.
587
+ */
588
+ setUseStrictShallowCopy(value) {
589
+ this.useStrictShallowCopy_ = value;
590
+ }
591
+ /**
592
+ * Pass false to use faster iteration that skips non-enumerable properties
593
+ * but still handles symbols for compatibility.
594
+ *
595
+ * By default, strict iteration is enabled (includes all own properties).
596
+ */
597
+ setUseStrictIteration(value) {
598
+ this.useStrictIteration_ = value;
599
+ }
600
+ shouldUseStrictIteration() {
601
+ return this.useStrictIteration_;
602
+ }
603
+ applyPatches(base, patches) {
604
+ let i;
605
+ for (i = patches.length - 1; i >= 0; i--) {
606
+ const patch = patches[i];
607
+ if (patch.path.length === 0 && patch.op === "replace") {
608
+ base = patch.value;
609
+ break;
610
+ }
611
+ }
612
+ if (i > -1) patches = patches.slice(i + 1);
613
+ const applyPatchesImpl = getPlugin(PluginPatches).applyPatches_;
614
+ if (isDraft(base)) return applyPatchesImpl(base, patches);
615
+ return this.produce(base, (draft) => applyPatchesImpl(draft, patches));
616
+ }
617
+ };
618
+ function createProxy(rootScope, value, parent, key) {
619
+ const [draft, state] = isMap(value) ? getPlugin(PluginMapSet).proxyMap_(value, parent) : isSet(value) ? getPlugin(PluginMapSet).proxySet_(value, parent) : createProxyProxy(value, parent);
620
+ (parent?.scope_ ?? getCurrentScope()).drafts_.push(draft);
621
+ state.callbacks_ = parent?.callbacks_ ?? [];
622
+ state.key_ = key;
623
+ if (parent && key !== void 0) registerChildFinalizationCallback(parent, state, key);
624
+ else state.callbacks_.push(function rootDraftCleanup(rootScope2) {
625
+ rootScope2.mapSetPlugin_?.fixSetContents(state);
626
+ const { patchPlugin_ } = rootScope2;
627
+ if (state.modified_ && patchPlugin_) patchPlugin_.generatePatches_(state, [], rootScope2);
628
+ });
629
+ return draft;
630
+ }
631
+ function current(value) {
632
+ if (!isDraft(value)) die(10, value);
633
+ return currentImpl(value);
634
+ }
635
+ function currentImpl(value) {
636
+ if (!isDraftable(value) || isFrozen(value)) return value;
637
+ const state = value[DRAFT_STATE];
638
+ let copy;
639
+ let strict = true;
640
+ if (state) {
641
+ if (!state.modified_) return state.base_;
642
+ state.finalized_ = true;
643
+ copy = shallowCopy(value, state.scope_.immer_.useStrictShallowCopy_);
644
+ strict = state.scope_.immer_.shouldUseStrictIteration();
645
+ } else copy = shallowCopy(value, true);
646
+ each(copy, (key, childValue) => {
647
+ set(copy, key, currentImpl(childValue));
648
+ }, strict);
649
+ if (state) state.finalized_ = false;
650
+ return copy;
651
+ }
652
+ function enablePatches() {
653
+ const errorOffset = 16;
654
+ if (process.env.NODE_ENV !== "production") errors.push("Sets cannot have \"replace\" patches.", function(op) {
655
+ return "Unsupported patch operation: " + op;
656
+ }, function(path) {
657
+ return "Cannot apply patch, path doesn't resolve: " + path;
658
+ }, "Patching reserved attributes like __proto__, prototype and constructor is not allowed");
659
+ function getPath(state, path = []) {
660
+ if (state.key_ !== void 0) {
661
+ const parentCopy = state.parent_.copy_ ?? state.parent_.base_;
662
+ const proxyDraft = getProxyDraft(get(parentCopy, state.key_));
663
+ const valueAtKey = get(parentCopy, state.key_);
664
+ if (valueAtKey === void 0) return null;
665
+ if (valueAtKey !== state.draft_ && valueAtKey !== state.base_ && valueAtKey !== state.copy_) return null;
666
+ if (proxyDraft != null && proxyDraft.base_ !== state.base_) return null;
667
+ const isSet2 = state.parent_.type_ === 3;
668
+ let key;
669
+ if (isSet2) {
670
+ const setParent = state.parent_;
671
+ key = Array.from(setParent.drafts_.keys()).indexOf(state.key_);
672
+ } else key = state.key_;
673
+ if (!(isSet2 && parentCopy.size > key || has(parentCopy, key))) return null;
674
+ path.push(key);
675
+ }
676
+ if (state.parent_) return getPath(state.parent_, path);
677
+ path.reverse();
678
+ try {
679
+ resolvePath(state.copy_, path);
680
+ } catch (e) {
681
+ return null;
682
+ }
683
+ return path;
684
+ }
685
+ function resolvePath(base, path) {
686
+ let current2 = base;
687
+ for (let i = 0; i < path.length - 1; i++) {
688
+ const key = path[i];
689
+ current2 = get(current2, key);
690
+ if (!isObjectish(current2) || current2 === null) throw new Error(`Cannot resolve path at '${path.join("/")}'`);
691
+ }
692
+ return current2;
693
+ }
694
+ const REPLACE = "replace";
695
+ const ADD = "add";
696
+ const REMOVE = "remove";
697
+ function generatePatches_(state, basePath, scope) {
698
+ if (state.scope_.processedForPatches_.has(state)) return;
699
+ state.scope_.processedForPatches_.add(state);
700
+ const { patches_, inversePatches_ } = scope;
701
+ switch (state.type_) {
702
+ case 0:
703
+ case 2: return generatePatchesFromAssigned(state, basePath, patches_, inversePatches_);
704
+ case 1: return generateArrayPatches(state, basePath, patches_, inversePatches_);
705
+ case 3: return generateSetPatches(state, basePath, patches_, inversePatches_);
706
+ }
707
+ }
708
+ function generateArrayPatches(state, basePath, patches, inversePatches) {
709
+ let { base_, assigned_ } = state;
710
+ let copy_ = state.copy_;
711
+ if (copy_.length < base_.length) {
712
+ [base_, copy_] = [copy_, base_];
713
+ [patches, inversePatches] = [inversePatches, patches];
714
+ }
715
+ const allReassigned = state.allIndicesReassigned_ === true;
716
+ for (let i = 0; i < base_.length; i++) {
717
+ const copiedItem = copy_[i];
718
+ const baseItem = base_[i];
719
+ if ((allReassigned || assigned_?.get(i.toString())) && copiedItem !== baseItem) {
720
+ const childState = copiedItem?.[DRAFT_STATE];
721
+ if (childState && childState.modified_) continue;
722
+ const path = basePath.concat([i]);
723
+ patches.push({
724
+ op: REPLACE,
725
+ path,
726
+ value: clonePatchValueIfNeeded(copiedItem)
727
+ });
728
+ inversePatches.push({
729
+ op: REPLACE,
730
+ path,
731
+ value: clonePatchValueIfNeeded(baseItem)
732
+ });
733
+ }
734
+ }
735
+ for (let i = base_.length; i < copy_.length; i++) {
736
+ const path = basePath.concat([i]);
737
+ patches.push({
738
+ op: ADD,
739
+ path,
740
+ value: clonePatchValueIfNeeded(copy_[i])
741
+ });
742
+ }
743
+ for (let i = copy_.length - 1; base_.length <= i; --i) {
744
+ const path = basePath.concat([i]);
745
+ inversePatches.push({
746
+ op: REMOVE,
747
+ path
748
+ });
749
+ }
750
+ }
751
+ function generatePatchesFromAssigned(state, basePath, patches, inversePatches) {
752
+ const { base_, copy_, type_ } = state;
753
+ each(state.assigned_, (key, assignedValue) => {
754
+ const origValue = get(base_, key, type_);
755
+ const value = get(copy_, key, type_);
756
+ const op = !assignedValue ? REMOVE : has(base_, key) ? REPLACE : ADD;
757
+ if (origValue === value && op === REPLACE) return;
758
+ const path = basePath.concat(key);
759
+ patches.push(op === REMOVE ? {
760
+ op,
761
+ path
762
+ } : {
763
+ op,
764
+ path,
765
+ value: clonePatchValueIfNeeded(value)
766
+ });
767
+ inversePatches.push(op === ADD ? {
768
+ op: REMOVE,
769
+ path
770
+ } : op === REMOVE ? {
771
+ op: ADD,
772
+ path,
773
+ value: clonePatchValueIfNeeded(origValue)
774
+ } : {
775
+ op: REPLACE,
776
+ path,
777
+ value: clonePatchValueIfNeeded(origValue)
778
+ });
779
+ });
780
+ }
781
+ function generateSetPatches(state, basePath, patches, inversePatches) {
782
+ let { base_, copy_ } = state;
783
+ let i = 0;
784
+ base_.forEach((value) => {
785
+ if (!copy_.has(value)) {
786
+ const path = basePath.concat([i]);
787
+ patches.push({
788
+ op: REMOVE,
789
+ path,
790
+ value
791
+ });
792
+ inversePatches.unshift({
793
+ op: ADD,
794
+ path,
795
+ value
796
+ });
797
+ }
798
+ i++;
799
+ });
800
+ i = 0;
801
+ copy_.forEach((value) => {
802
+ if (!base_.has(value)) {
803
+ const path = basePath.concat([i]);
804
+ patches.push({
805
+ op: ADD,
806
+ path,
807
+ value
808
+ });
809
+ inversePatches.unshift({
810
+ op: REMOVE,
811
+ path,
812
+ value
813
+ });
814
+ }
815
+ i++;
816
+ });
817
+ }
818
+ function generateReplacementPatches_(baseValue, replacement, scope) {
819
+ const { patches_, inversePatches_ } = scope;
820
+ patches_.push({
821
+ op: REPLACE,
822
+ path: [],
823
+ value: replacement === NOTHING ? void 0 : replacement
824
+ });
825
+ inversePatches_.push({
826
+ op: REPLACE,
827
+ path: [],
828
+ value: baseValue
829
+ });
830
+ }
831
+ function applyPatches_(draft, patches) {
832
+ patches.forEach((patch) => {
833
+ const { path, op } = patch;
834
+ let base = draft;
835
+ for (let i = 0; i < path.length - 1; i++) {
836
+ const parentType = getArchtype(base);
837
+ let p = path[i];
838
+ if (typeof p !== "string" && typeof p !== "number") p = "" + p;
839
+ if ((parentType === 0 || parentType === 1) && (p === "__proto__" || p === CONSTRUCTOR)) die(errorOffset + 3);
840
+ if (isFunction(base) && p === PROTOTYPE) die(errorOffset + 3);
841
+ base = get(base, p);
842
+ if (!isObjectish(base)) die(errorOffset + 2, path.join("/"));
843
+ }
844
+ const type = getArchtype(base);
845
+ const value = deepClonePatchValue(patch.value);
846
+ const key = path[path.length - 1];
847
+ switch (op) {
848
+ case REPLACE: switch (type) {
849
+ case 2: return base.set(key, value);
850
+ case 3: die(errorOffset);
851
+ default: return base[key] = value;
852
+ }
853
+ case ADD: switch (type) {
854
+ case 1: return key === "-" ? base.push(value) : base.splice(key, 0, value);
855
+ case 2: return base.set(key, value);
856
+ case 3: return base.add(value);
857
+ default: return base[key] = value;
858
+ }
859
+ case REMOVE: switch (type) {
860
+ case 1: return base.splice(key, 1);
861
+ case 2: return base.delete(key);
862
+ case 3: return base.delete(patch.value);
863
+ default: return delete base[key];
864
+ }
865
+ default: die(errorOffset + 1, op);
866
+ }
867
+ });
868
+ return draft;
869
+ }
870
+ function deepClonePatchValue(obj) {
871
+ if (!isDraftable(obj)) return obj;
872
+ if (isArray(obj)) return obj.map(deepClonePatchValue);
873
+ if (isMap(obj)) return new Map(Array.from(obj.entries()).map(([k, v]) => [k, deepClonePatchValue(v)]));
874
+ if (isSet(obj)) return new Set(Array.from(obj).map(deepClonePatchValue));
875
+ const cloned = Object.create(getPrototypeOf(obj));
876
+ for (const key in obj) cloned[key] = deepClonePatchValue(obj[key]);
877
+ if (has(obj, DRAFTABLE)) cloned[DRAFTABLE] = obj[DRAFTABLE];
878
+ return cloned;
879
+ }
880
+ function clonePatchValueIfNeeded(obj) {
881
+ if (isDraft(obj)) return deepClonePatchValue(obj);
882
+ else return obj;
883
+ }
884
+ loadPlugin(PluginPatches, {
885
+ applyPatches_,
886
+ generatePatches_,
887
+ generateReplacementPatches_,
888
+ getPath
889
+ });
890
+ }
891
+ var immer = new Immer2();
892
+ var produce = immer.produce;
893
+ var produceWithPatches = /* @__PURE__ */ immer.produceWithPatches.bind(immer);
894
+ var applyPatches = /* @__PURE__ */ immer.applyPatches.bind(immer);
895
+ //#endregion
896
+ //#region src/utils/shared-state.ts
897
+ function createSharedState(options) {
898
+ const { enablePatches: enablePatches$1 = false } = options;
899
+ const events = createEventEmitter();
900
+ let state = options.initialValue;
901
+ const syncIds = /* @__PURE__ */ new Set();
902
+ return {
903
+ on: events.on,
904
+ value: () => state,
905
+ patch: (patches, syncId = nanoid()) => {
906
+ if (syncIds.has(syncId)) return;
907
+ enablePatches();
908
+ state = applyPatches(state, patches);
909
+ syncIds.add(syncId);
910
+ events.emit("updated", state, void 0, syncId);
911
+ },
912
+ mutate: (fn, syncId = nanoid()) => {
913
+ if (syncIds.has(syncId)) return;
914
+ syncIds.add(syncId);
915
+ if (enablePatches$1) {
916
+ const [newState, patches] = produceWithPatches(state, fn);
917
+ state = newState;
918
+ events.emit("updated", state, patches, syncId);
919
+ } else {
920
+ state = produce(state, fn);
921
+ events.emit("updated", state, void 0, syncId);
922
+ }
923
+ },
924
+ syncIds
925
+ };
926
+ }
927
+ //#endregion
928
+ export { createSharedState as t };