@cfp-studio/iframe 18.0.0 → 18.2.0

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.mjs CHANGED
@@ -1,991 +1,769 @@
1
- var assertNever$1 = {};
2
-
3
- Object.defineProperty(assertNever$1, "__esModule", { value: true });
4
- var assertNever_2 = assertNever$1.assertNever = assertNever;
5
- /**
6
- * Helper function for exhaustive checks of discriminated unions.
7
- * https://basarat.gitbooks.io/typescript/docs/types/discriminated-unions.html
8
- *
9
- * @example
10
- *
11
- * type A = {type: 'a'};
12
- * type B = {type: 'b'};
13
- * type Union = A | B;
14
- *
15
- * function doSomething(arg: Union) {
16
- * if (arg.type === 'a') {
17
- * return something;
18
- * }
19
- *
20
- * if (arg.type === 'b') {
21
- * return somethingElse;
22
- * }
23
- *
24
- * // TS will error if there are other types in the union
25
- * // Will throw an Error when called at runtime.
26
- * // Use `assertNever(arg, true)` instead to fail silently.
27
- * return assertNever(arg);
28
- * }
29
- */
30
- function assertNever(value, errorMessageOrNoThrow) {
31
- if (typeof errorMessageOrNoThrow === 'string') {
32
- throw new Error(errorMessageOrNoThrow);
33
- }
34
- if (typeof errorMessageOrNoThrow === 'function') {
35
- throw new Error(errorMessageOrNoThrow(value));
36
- }
37
- if (errorMessageOrNoThrow) {
38
- return value;
39
- }
40
- throw new Error("Unhandled discriminated union member: ".concat(JSON.stringify(value)));
41
- }
42
- assertNever$1.default = assertNever;
43
-
44
- // src/utils/env.ts
1
+ //#region \0rolldown/runtime.js
2
+ var __commonJSMin = (cb, mod) => () => (mod || cb((mod = { exports: {} }).exports, mod), mod.exports);
3
+ //#endregion
4
+ //#region ../node_modules/.pnpm/immer@10.1.1/node_modules/immer/dist/immer.mjs
5
+ var import_assert_never = (/* @__PURE__ */ __commonJSMin(((exports) => {
6
+ Object.defineProperty(exports, "__esModule", { value: true });
7
+ exports.assertNever = assertNever;
8
+ /**
9
+ * Helper function for exhaustive checks of discriminated unions.
10
+ * https://basarat.gitbooks.io/typescript/docs/types/discriminated-unions.html
11
+ *
12
+ * @example
13
+ *
14
+ * type A = {type: 'a'};
15
+ * type B = {type: 'b'};
16
+ * type Union = A | B;
17
+ *
18
+ * function doSomething(arg: Union) {
19
+ * if (arg.type === 'a') {
20
+ * return something;
21
+ * }
22
+ *
23
+ * if (arg.type === 'b') {
24
+ * return somethingElse;
25
+ * }
26
+ *
27
+ * // TS will error if there are other types in the union
28
+ * // Will throw an Error when called at runtime.
29
+ * // Use `assertNever(arg, true)` instead to fail silently.
30
+ * return assertNever(arg);
31
+ * }
32
+ */
33
+ function assertNever(value, errorMessageOrNoThrow) {
34
+ if (typeof errorMessageOrNoThrow === "string") throw new Error(errorMessageOrNoThrow);
35
+ if (typeof errorMessageOrNoThrow === "function") throw new Error(errorMessageOrNoThrow(value));
36
+ if (errorMessageOrNoThrow) return value;
37
+ throw new Error("Unhandled discriminated union member: ".concat(JSON.stringify(value)));
38
+ }
39
+ })))();
45
40
  var NOTHING = Symbol.for("immer-nothing");
46
41
  var DRAFTABLE = Symbol.for("immer-draftable");
47
42
  var DRAFT_STATE = Symbol.for("immer-state");
48
-
49
- // src/utils/errors.ts
50
43
  var errors = process.env.NODE_ENV !== "production" ? [
51
- // All error codes, starting by 0:
52
- function(plugin) {
53
- return `The plugin for '${plugin}' has not been loaded into Immer. To enable the plugin, import and call \`enable${plugin}()\` when initializing your application.`;
54
- },
55
- function(thing) {
56
- 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}'`;
57
- },
58
- "This object has been frozen and should not be mutated",
59
- function(data) {
60
- return "Cannot use a proxy that has been revoked. Did you pass an object from inside an immer function to an async process? " + data;
61
- },
62
- "An immer producer returned a new value *and* modified its draft. Either return a new value *or* modify the draft.",
63
- "Immer forbids circular references",
64
- "The first or second argument to `produce` must be a function",
65
- "The third argument to `produce` must be a function or undefined",
66
- "First argument to `createDraft` must be a plain object, an array, or an immerable object",
67
- "First argument to `finishDraft` must be a draft returned by `createDraft`",
68
- function(thing) {
69
- return `'current' expects a draft, got: ${thing}`;
70
- },
71
- "Object.defineProperty() cannot be used on an Immer draft",
72
- "Object.setPrototypeOf() cannot be used on an Immer draft",
73
- "Immer only supports deleting array indices",
74
- "Immer only supports setting array indices and the 'length' property",
75
- function(thing) {
76
- return `'original' expects a draft, got: ${thing}`;
77
- }
78
- // Note: if more errors are added, the errorOffset in Patches.ts should be increased
79
- // See Patches.ts for additional errors
44
+ function(plugin) {
45
+ return `The plugin for '${plugin}' has not been loaded into Immer. To enable the plugin, import and call \`enable${plugin}()\` when initializing your application.`;
46
+ },
47
+ function(thing) {
48
+ 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}'`;
49
+ },
50
+ "This object has been frozen and should not be mutated",
51
+ function(data) {
52
+ return "Cannot use a proxy that has been revoked. Did you pass an object from inside an immer function to an async process? " + data;
53
+ },
54
+ "An immer producer returned a new value *and* modified its draft. Either return a new value *or* modify the draft.",
55
+ "Immer forbids circular references",
56
+ "The first or second argument to `produce` must be a function",
57
+ "The third argument to `produce` must be a function or undefined",
58
+ "First argument to `createDraft` must be a plain object, an array, or an immerable object",
59
+ "First argument to `finishDraft` must be a draft returned by `createDraft`",
60
+ function(thing) {
61
+ return `'current' expects a draft, got: ${thing}`;
62
+ },
63
+ "Object.defineProperty() cannot be used on an Immer draft",
64
+ "Object.setPrototypeOf() cannot be used on an Immer draft",
65
+ "Immer only supports deleting array indices",
66
+ "Immer only supports setting array indices and the 'length' property",
67
+ function(thing) {
68
+ return `'original' expects a draft, got: ${thing}`;
69
+ }
80
70
  ] : [];
81
71
  function die(error, ...args) {
82
- if (process.env.NODE_ENV !== "production") {
83
- const e = errors[error];
84
- const msg = typeof e === "function" ? e.apply(null, args) : e;
85
- throw new Error(`[Immer] ${msg}`);
86
- }
87
- throw new Error(
88
- `[Immer] minified error nr: ${error}. Full error at: https://bit.ly/3cXEKWf`
89
- );
90
- }
91
-
92
- // src/utils/common.ts
72
+ if (process.env.NODE_ENV !== "production") {
73
+ const e = errors[error];
74
+ const msg = typeof e === "function" ? e.apply(null, args) : e;
75
+ throw new Error(`[Immer] ${msg}`);
76
+ }
77
+ throw new Error(`[Immer] minified error nr: ${error}. Full error at: https://bit.ly/3cXEKWf`);
78
+ }
93
79
  var getPrototypeOf = Object.getPrototypeOf;
94
80
  function isDraft(value) {
95
- return !!value && !!value[DRAFT_STATE];
81
+ return !!value && !!value[DRAFT_STATE];
96
82
  }
97
83
  function isDraftable(value) {
98
- if (!value)
99
- return false;
100
- return isPlainObject(value) || Array.isArray(value) || !!value[DRAFTABLE] || !!value.constructor?.[DRAFTABLE] || isMap(value) || isSet(value);
84
+ if (!value) return false;
85
+ return isPlainObject(value) || Array.isArray(value) || !!value[DRAFTABLE] || !!value.constructor?.[DRAFTABLE] || isMap(value) || isSet(value);
101
86
  }
102
87
  var objectCtorString = Object.prototype.constructor.toString();
103
88
  function isPlainObject(value) {
104
- if (!value || typeof value !== "object")
105
- return false;
106
- const proto = getPrototypeOf(value);
107
- if (proto === null) {
108
- return true;
109
- }
110
- const Ctor = Object.hasOwnProperty.call(proto, "constructor") && proto.constructor;
111
- if (Ctor === Object)
112
- return true;
113
- return typeof Ctor == "function" && Function.toString.call(Ctor) === objectCtorString;
89
+ if (!value || typeof value !== "object") return false;
90
+ const proto = getPrototypeOf(value);
91
+ if (proto === null) return true;
92
+ const Ctor = Object.hasOwnProperty.call(proto, "constructor") && proto.constructor;
93
+ if (Ctor === Object) return true;
94
+ return typeof Ctor == "function" && Function.toString.call(Ctor) === objectCtorString;
114
95
  }
115
96
  function each(obj, iter) {
116
- if (getArchtype(obj) === 0 /* Object */) {
117
- Reflect.ownKeys(obj).forEach((key) => {
118
- iter(key, obj[key], obj);
119
- });
120
- } else {
121
- obj.forEach((entry, index) => iter(index, entry, obj));
122
- }
97
+ if (getArchtype(obj) === 0) Reflect.ownKeys(obj).forEach((key) => {
98
+ iter(key, obj[key], obj);
99
+ });
100
+ else obj.forEach((entry, index) => iter(index, entry, obj));
123
101
  }
124
102
  function getArchtype(thing) {
125
- const state = thing[DRAFT_STATE];
126
- return state ? state.type_ : Array.isArray(thing) ? 1 /* Array */ : isMap(thing) ? 2 /* Map */ : isSet(thing) ? 3 /* Set */ : 0 /* Object */;
103
+ const state = thing[DRAFT_STATE];
104
+ return state ? state.type_ : Array.isArray(thing) ? 1 : isMap(thing) ? 2 : isSet(thing) ? 3 : 0;
127
105
  }
128
106
  function has(thing, prop) {
129
- return getArchtype(thing) === 2 /* Map */ ? thing.has(prop) : Object.prototype.hasOwnProperty.call(thing, prop);
107
+ return getArchtype(thing) === 2 ? thing.has(prop) : Object.prototype.hasOwnProperty.call(thing, prop);
130
108
  }
131
109
  function set(thing, propOrOldValue, value) {
132
- const t = getArchtype(thing);
133
- if (t === 2 /* Map */)
134
- thing.set(propOrOldValue, value);
135
- else if (t === 3 /* Set */) {
136
- thing.add(value);
137
- } else
138
- thing[propOrOldValue] = value;
110
+ const t = getArchtype(thing);
111
+ if (t === 2) thing.set(propOrOldValue, value);
112
+ else if (t === 3) thing.add(value);
113
+ else thing[propOrOldValue] = value;
139
114
  }
140
115
  function is(x, y) {
141
- if (x === y) {
142
- return x !== 0 || 1 / x === 1 / y;
143
- } else {
144
- return x !== x && y !== y;
145
- }
116
+ if (x === y) return x !== 0 || 1 / x === 1 / y;
117
+ else return x !== x && y !== y;
146
118
  }
147
119
  function isMap(target) {
148
- return target instanceof Map;
120
+ return target instanceof Map;
149
121
  }
150
122
  function isSet(target) {
151
- return target instanceof Set;
123
+ return target instanceof Set;
152
124
  }
153
125
  function latest(state) {
154
- return state.copy_ || state.base_;
126
+ return state.copy_ || state.base_;
155
127
  }
156
128
  function shallowCopy(base, strict) {
157
- if (isMap(base)) {
158
- return new Map(base);
159
- }
160
- if (isSet(base)) {
161
- return new Set(base);
162
- }
163
- if (Array.isArray(base))
164
- return Array.prototype.slice.call(base);
165
- const isPlain = isPlainObject(base);
166
- if (strict === true || strict === "class_only" && !isPlain) {
167
- const descriptors = Object.getOwnPropertyDescriptors(base);
168
- delete descriptors[DRAFT_STATE];
169
- let keys = Reflect.ownKeys(descriptors);
170
- for (let i = 0; i < keys.length; i++) {
171
- const key = keys[i];
172
- const desc = descriptors[key];
173
- if (desc.writable === false) {
174
- desc.writable = true;
175
- desc.configurable = true;
176
- }
177
- if (desc.get || desc.set)
178
- descriptors[key] = {
179
- configurable: true,
180
- writable: true,
181
- // could live with !!desc.set as well here...
182
- enumerable: desc.enumerable,
183
- value: base[key]
184
- };
185
- }
186
- return Object.create(getPrototypeOf(base), descriptors);
187
- } else {
188
- const proto = getPrototypeOf(base);
189
- if (proto !== null && isPlain) {
190
- return { ...base };
191
- }
192
- const obj = Object.create(proto);
193
- return Object.assign(obj, base);
194
- }
129
+ if (isMap(base)) return new Map(base);
130
+ if (isSet(base)) return new Set(base);
131
+ if (Array.isArray(base)) return Array.prototype.slice.call(base);
132
+ const isPlain = isPlainObject(base);
133
+ if (strict === true || strict === "class_only" && !isPlain) {
134
+ const descriptors = Object.getOwnPropertyDescriptors(base);
135
+ delete descriptors[DRAFT_STATE];
136
+ let keys = Reflect.ownKeys(descriptors);
137
+ for (let i = 0; i < keys.length; i++) {
138
+ const key = keys[i];
139
+ const desc = descriptors[key];
140
+ if (desc.writable === false) {
141
+ desc.writable = true;
142
+ desc.configurable = true;
143
+ }
144
+ if (desc.get || desc.set) descriptors[key] = {
145
+ configurable: true,
146
+ writable: true,
147
+ enumerable: desc.enumerable,
148
+ value: base[key]
149
+ };
150
+ }
151
+ return Object.create(getPrototypeOf(base), descriptors);
152
+ } else {
153
+ const proto = getPrototypeOf(base);
154
+ if (proto !== null && isPlain) return { ...base };
155
+ const obj = Object.create(proto);
156
+ return Object.assign(obj, base);
157
+ }
195
158
  }
196
159
  function freeze(obj, deep = false) {
197
- if (isFrozen(obj) || isDraft(obj) || !isDraftable(obj))
198
- return obj;
199
- if (getArchtype(obj) > 1) {
200
- obj.set = obj.add = obj.clear = obj.delete = dontMutateFrozenCollections;
201
- }
202
- Object.freeze(obj);
203
- if (deep)
204
- Object.entries(obj).forEach(([key, value]) => freeze(value, true));
205
- return obj;
160
+ if (isFrozen(obj) || isDraft(obj) || !isDraftable(obj)) return obj;
161
+ if (getArchtype(obj) > 1) obj.set = obj.add = obj.clear = obj.delete = dontMutateFrozenCollections;
162
+ Object.freeze(obj);
163
+ if (deep) Object.entries(obj).forEach(([key, value]) => freeze(value, true));
164
+ return obj;
206
165
  }
207
166
  function dontMutateFrozenCollections() {
208
- die(2);
167
+ die(2);
209
168
  }
210
169
  function isFrozen(obj) {
211
- return Object.isFrozen(obj);
170
+ return Object.isFrozen(obj);
212
171
  }
213
-
214
- // src/utils/plugins.ts
215
172
  var plugins = {};
216
173
  function getPlugin(pluginKey) {
217
- const plugin = plugins[pluginKey];
218
- if (!plugin) {
219
- die(0, pluginKey);
220
- }
221
- return plugin;
222
- }
223
-
224
- // src/core/scope.ts
174
+ const plugin = plugins[pluginKey];
175
+ if (!plugin) die(0, pluginKey);
176
+ return plugin;
177
+ }
225
178
  var currentScope;
226
179
  function getCurrentScope() {
227
- return currentScope;
180
+ return currentScope;
228
181
  }
229
182
  function createScope(parent_, immer_) {
230
- return {
231
- drafts_: [],
232
- parent_,
233
- immer_,
234
- // Whenever the modified draft contains a draft from another scope, we
235
- // need to prevent auto-freezing so the unowned draft can be finalized.
236
- canAutoFreeze_: true,
237
- unfinalizedDrafts_: 0
238
- };
183
+ return {
184
+ drafts_: [],
185
+ parent_,
186
+ immer_,
187
+ canAutoFreeze_: true,
188
+ unfinalizedDrafts_: 0
189
+ };
239
190
  }
240
191
  function usePatchesInScope(scope, patchListener) {
241
- if (patchListener) {
242
- getPlugin("Patches");
243
- scope.patches_ = [];
244
- scope.inversePatches_ = [];
245
- scope.patchListener_ = patchListener;
246
- }
192
+ if (patchListener) {
193
+ getPlugin("Patches");
194
+ scope.patches_ = [];
195
+ scope.inversePatches_ = [];
196
+ scope.patchListener_ = patchListener;
197
+ }
247
198
  }
248
199
  function revokeScope(scope) {
249
- leaveScope(scope);
250
- scope.drafts_.forEach(revokeDraft);
251
- scope.drafts_ = null;
200
+ leaveScope(scope);
201
+ scope.drafts_.forEach(revokeDraft);
202
+ scope.drafts_ = null;
252
203
  }
253
204
  function leaveScope(scope) {
254
- if (scope === currentScope) {
255
- currentScope = scope.parent_;
256
- }
205
+ if (scope === currentScope) currentScope = scope.parent_;
257
206
  }
258
207
  function enterScope(immer2) {
259
- return currentScope = createScope(currentScope, immer2);
208
+ return currentScope = createScope(currentScope, immer2);
260
209
  }
261
210
  function revokeDraft(draft) {
262
- const state = draft[DRAFT_STATE];
263
- if (state.type_ === 0 /* Object */ || state.type_ === 1 /* Array */)
264
- state.revoke_();
265
- else
266
- state.revoked_ = true;
267
- }
268
-
269
- // src/core/finalize.ts
211
+ const state = draft[DRAFT_STATE];
212
+ if (state.type_ === 0 || state.type_ === 1) state.revoke_();
213
+ else state.revoked_ = true;
214
+ }
270
215
  function processResult(result, scope) {
271
- scope.unfinalizedDrafts_ = scope.drafts_.length;
272
- const baseDraft = scope.drafts_[0];
273
- const isReplaced = result !== void 0 && result !== baseDraft;
274
- if (isReplaced) {
275
- if (baseDraft[DRAFT_STATE].modified_) {
276
- revokeScope(scope);
277
- die(4);
278
- }
279
- if (isDraftable(result)) {
280
- result = finalize(scope, result);
281
- if (!scope.parent_)
282
- maybeFreeze(scope, result);
283
- }
284
- if (scope.patches_) {
285
- getPlugin("Patches").generateReplacementPatches_(
286
- baseDraft[DRAFT_STATE].base_,
287
- result,
288
- scope.patches_,
289
- scope.inversePatches_
290
- );
291
- }
292
- } else {
293
- result = finalize(scope, baseDraft, []);
294
- }
295
- revokeScope(scope);
296
- if (scope.patches_) {
297
- scope.patchListener_(scope.patches_, scope.inversePatches_);
298
- }
299
- return result !== NOTHING ? result : void 0;
216
+ scope.unfinalizedDrafts_ = scope.drafts_.length;
217
+ const baseDraft = scope.drafts_[0];
218
+ if (result !== void 0 && result !== baseDraft) {
219
+ if (baseDraft[DRAFT_STATE].modified_) {
220
+ revokeScope(scope);
221
+ die(4);
222
+ }
223
+ if (isDraftable(result)) {
224
+ result = finalize(scope, result);
225
+ if (!scope.parent_) maybeFreeze(scope, result);
226
+ }
227
+ if (scope.patches_) getPlugin("Patches").generateReplacementPatches_(baseDraft[DRAFT_STATE].base_, result, scope.patches_, scope.inversePatches_);
228
+ } else result = finalize(scope, baseDraft, []);
229
+ revokeScope(scope);
230
+ if (scope.patches_) scope.patchListener_(scope.patches_, scope.inversePatches_);
231
+ return result !== NOTHING ? result : void 0;
300
232
  }
301
233
  function finalize(rootScope, value, path) {
302
- if (isFrozen(value))
303
- return value;
304
- const state = value[DRAFT_STATE];
305
- if (!state) {
306
- each(
307
- value,
308
- (key, childValue) => finalizeProperty(rootScope, state, value, key, childValue, path)
309
- );
310
- return value;
311
- }
312
- if (state.scope_ !== rootScope)
313
- return value;
314
- if (!state.modified_) {
315
- maybeFreeze(rootScope, state.base_, true);
316
- return state.base_;
317
- }
318
- if (!state.finalized_) {
319
- state.finalized_ = true;
320
- state.scope_.unfinalizedDrafts_--;
321
- const result = state.copy_;
322
- let resultEach = result;
323
- let isSet2 = false;
324
- if (state.type_ === 3 /* Set */) {
325
- resultEach = new Set(result);
326
- result.clear();
327
- isSet2 = true;
328
- }
329
- each(
330
- resultEach,
331
- (key, childValue) => finalizeProperty(rootScope, state, result, key, childValue, path, isSet2)
332
- );
333
- maybeFreeze(rootScope, result, false);
334
- if (path && rootScope.patches_) {
335
- getPlugin("Patches").generatePatches_(
336
- state,
337
- path,
338
- rootScope.patches_,
339
- rootScope.inversePatches_
340
- );
341
- }
342
- }
343
- return state.copy_;
234
+ if (isFrozen(value)) return value;
235
+ const state = value[DRAFT_STATE];
236
+ if (!state) {
237
+ each(value, (key, childValue) => finalizeProperty(rootScope, state, value, key, childValue, path));
238
+ return value;
239
+ }
240
+ if (state.scope_ !== rootScope) return value;
241
+ if (!state.modified_) {
242
+ maybeFreeze(rootScope, state.base_, true);
243
+ return state.base_;
244
+ }
245
+ if (!state.finalized_) {
246
+ state.finalized_ = true;
247
+ state.scope_.unfinalizedDrafts_--;
248
+ const result = state.copy_;
249
+ let resultEach = result;
250
+ let isSet2 = false;
251
+ if (state.type_ === 3) {
252
+ resultEach = new Set(result);
253
+ result.clear();
254
+ isSet2 = true;
255
+ }
256
+ each(resultEach, (key, childValue) => finalizeProperty(rootScope, state, result, key, childValue, path, isSet2));
257
+ maybeFreeze(rootScope, result, false);
258
+ if (path && rootScope.patches_) getPlugin("Patches").generatePatches_(state, path, rootScope.patches_, rootScope.inversePatches_);
259
+ }
260
+ return state.copy_;
344
261
  }
345
262
  function finalizeProperty(rootScope, parentState, targetObject, prop, childValue, rootPath, targetIsSet) {
346
- if (process.env.NODE_ENV !== "production" && childValue === targetObject)
347
- die(5);
348
- if (isDraft(childValue)) {
349
- const path = rootPath && parentState && parentState.type_ !== 3 /* Set */ && // Set objects are atomic since they have no keys.
350
- !has(parentState.assigned_, prop) ? rootPath.concat(prop) : void 0;
351
- const res = finalize(rootScope, childValue, path);
352
- set(targetObject, prop, res);
353
- if (isDraft(res)) {
354
- rootScope.canAutoFreeze_ = false;
355
- } else
356
- return;
357
- } else if (targetIsSet) {
358
- targetObject.add(childValue);
359
- }
360
- if (isDraftable(childValue) && !isFrozen(childValue)) {
361
- if (!rootScope.immer_.autoFreeze_ && rootScope.unfinalizedDrafts_ < 1) {
362
- return;
363
- }
364
- finalize(rootScope, childValue);
365
- if ((!parentState || !parentState.scope_.parent_) && typeof prop !== "symbol" && Object.prototype.propertyIsEnumerable.call(targetObject, prop))
366
- maybeFreeze(rootScope, childValue);
367
- }
263
+ if (process.env.NODE_ENV !== "production" && childValue === targetObject) die(5);
264
+ if (isDraft(childValue)) {
265
+ const res = finalize(rootScope, childValue, rootPath && parentState && parentState.type_ !== 3 && !has(parentState.assigned_, prop) ? rootPath.concat(prop) : void 0);
266
+ set(targetObject, prop, res);
267
+ if (isDraft(res)) rootScope.canAutoFreeze_ = false;
268
+ else return;
269
+ } else if (targetIsSet) targetObject.add(childValue);
270
+ if (isDraftable(childValue) && !isFrozen(childValue)) {
271
+ if (!rootScope.immer_.autoFreeze_ && rootScope.unfinalizedDrafts_ < 1) return;
272
+ finalize(rootScope, childValue);
273
+ if ((!parentState || !parentState.scope_.parent_) && typeof prop !== "symbol" && Object.prototype.propertyIsEnumerable.call(targetObject, prop)) maybeFreeze(rootScope, childValue);
274
+ }
368
275
  }
369
276
  function maybeFreeze(scope, value, deep = false) {
370
- if (!scope.parent_ && scope.immer_.autoFreeze_ && scope.canAutoFreeze_) {
371
- freeze(value, deep);
372
- }
277
+ if (!scope.parent_ && scope.immer_.autoFreeze_ && scope.canAutoFreeze_) freeze(value, deep);
373
278
  }
374
-
375
- // src/core/proxy.ts
376
279
  function createProxyProxy(base, parent) {
377
- const isArray = Array.isArray(base);
378
- const state = {
379
- type_: isArray ? 1 /* Array */ : 0 /* Object */,
380
- // Track which produce call this is associated with.
381
- scope_: parent ? parent.scope_ : getCurrentScope(),
382
- // True for both shallow and deep changes.
383
- modified_: false,
384
- // Used during finalization.
385
- finalized_: false,
386
- // Track which properties have been assigned (true) or deleted (false).
387
- assigned_: {},
388
- // The parent draft state.
389
- parent_: parent,
390
- // The base state.
391
- base_: base,
392
- // The base proxy.
393
- draft_: null,
394
- // set below
395
- // The base copy with any updated values.
396
- copy_: null,
397
- // Called by the `produce` function.
398
- revoke_: null,
399
- isManual_: false
400
- };
401
- let target = state;
402
- let traps = objectTraps;
403
- if (isArray) {
404
- target = [state];
405
- traps = arrayTraps;
406
- }
407
- const { revoke, proxy } = Proxy.revocable(target, traps);
408
- state.draft_ = proxy;
409
- state.revoke_ = revoke;
410
- return proxy;
280
+ const isArray = Array.isArray(base);
281
+ const state = {
282
+ type_: isArray ? 1 : 0,
283
+ scope_: parent ? parent.scope_ : getCurrentScope(),
284
+ modified_: false,
285
+ finalized_: false,
286
+ assigned_: {},
287
+ parent_: parent,
288
+ base_: base,
289
+ draft_: null,
290
+ copy_: null,
291
+ revoke_: null,
292
+ isManual_: false
293
+ };
294
+ let target = state;
295
+ let traps = objectTraps;
296
+ if (isArray) {
297
+ target = [state];
298
+ traps = arrayTraps;
299
+ }
300
+ const { revoke, proxy } = Proxy.revocable(target, traps);
301
+ state.draft_ = proxy;
302
+ state.revoke_ = revoke;
303
+ return proxy;
411
304
  }
412
305
  var objectTraps = {
413
- get(state, prop) {
414
- if (prop === DRAFT_STATE)
415
- return state;
416
- const source = latest(state);
417
- if (!has(source, prop)) {
418
- return readPropFromProto(state, source, prop);
419
- }
420
- const value = source[prop];
421
- if (state.finalized_ || !isDraftable(value)) {
422
- return value;
423
- }
424
- if (value === peek(state.base_, prop)) {
425
- prepareCopy(state);
426
- return state.copy_[prop] = createProxy(value, state);
427
- }
428
- return value;
429
- },
430
- has(state, prop) {
431
- return prop in latest(state);
432
- },
433
- ownKeys(state) {
434
- return Reflect.ownKeys(latest(state));
435
- },
436
- set(state, prop, value) {
437
- const desc = getDescriptorFromProto(latest(state), prop);
438
- if (desc?.set) {
439
- desc.set.call(state.draft_, value);
440
- return true;
441
- }
442
- if (!state.modified_) {
443
- const current2 = peek(latest(state), prop);
444
- const currentState = current2?.[DRAFT_STATE];
445
- if (currentState && currentState.base_ === value) {
446
- state.copy_[prop] = value;
447
- state.assigned_[prop] = false;
448
- return true;
449
- }
450
- if (is(value, current2) && (value !== void 0 || has(state.base_, prop)))
451
- return true;
452
- prepareCopy(state);
453
- markChanged(state);
454
- }
455
- if (state.copy_[prop] === value && // special case: handle new props with value 'undefined'
456
- (value !== void 0 || prop in state.copy_) || // special case: NaN
457
- Number.isNaN(value) && Number.isNaN(state.copy_[prop]))
458
- return true;
459
- state.copy_[prop] = value;
460
- state.assigned_[prop] = true;
461
- return true;
462
- },
463
- deleteProperty(state, prop) {
464
- if (peek(state.base_, prop) !== void 0 || prop in state.base_) {
465
- state.assigned_[prop] = false;
466
- prepareCopy(state);
467
- markChanged(state);
468
- } else {
469
- delete state.assigned_[prop];
470
- }
471
- if (state.copy_) {
472
- delete state.copy_[prop];
473
- }
474
- return true;
475
- },
476
- // Note: We never coerce `desc.value` into an Immer draft, because we can't make
477
- // the same guarantee in ES5 mode.
478
- getOwnPropertyDescriptor(state, prop) {
479
- const owner = latest(state);
480
- const desc = Reflect.getOwnPropertyDescriptor(owner, prop);
481
- if (!desc)
482
- return desc;
483
- return {
484
- writable: true,
485
- configurable: state.type_ !== 1 /* Array */ || prop !== "length",
486
- enumerable: desc.enumerable,
487
- value: owner[prop]
488
- };
489
- },
490
- defineProperty() {
491
- die(11);
492
- },
493
- getPrototypeOf(state) {
494
- return getPrototypeOf(state.base_);
495
- },
496
- setPrototypeOf() {
497
- die(12);
498
- }
306
+ get(state, prop) {
307
+ if (prop === DRAFT_STATE) return state;
308
+ const source = latest(state);
309
+ if (!has(source, prop)) return readPropFromProto(state, source, prop);
310
+ const value = source[prop];
311
+ if (state.finalized_ || !isDraftable(value)) return value;
312
+ if (value === peek(state.base_, prop)) {
313
+ prepareCopy(state);
314
+ return state.copy_[prop] = createProxy(value, state);
315
+ }
316
+ return value;
317
+ },
318
+ has(state, prop) {
319
+ return prop in latest(state);
320
+ },
321
+ ownKeys(state) {
322
+ return Reflect.ownKeys(latest(state));
323
+ },
324
+ set(state, prop, value) {
325
+ const desc = getDescriptorFromProto(latest(state), prop);
326
+ if (desc?.set) {
327
+ desc.set.call(state.draft_, value);
328
+ return true;
329
+ }
330
+ if (!state.modified_) {
331
+ const current2 = peek(latest(state), prop);
332
+ const currentState = current2?.[DRAFT_STATE];
333
+ if (currentState && currentState.base_ === value) {
334
+ state.copy_[prop] = value;
335
+ state.assigned_[prop] = false;
336
+ return true;
337
+ }
338
+ if (is(value, current2) && (value !== void 0 || has(state.base_, prop))) return true;
339
+ prepareCopy(state);
340
+ markChanged(state);
341
+ }
342
+ if (state.copy_[prop] === value && (value !== void 0 || prop in state.copy_) || Number.isNaN(value) && Number.isNaN(state.copy_[prop])) return true;
343
+ state.copy_[prop] = value;
344
+ state.assigned_[prop] = true;
345
+ return true;
346
+ },
347
+ deleteProperty(state, prop) {
348
+ if (peek(state.base_, prop) !== void 0 || prop in state.base_) {
349
+ state.assigned_[prop] = false;
350
+ prepareCopy(state);
351
+ markChanged(state);
352
+ } else delete state.assigned_[prop];
353
+ if (state.copy_) delete state.copy_[prop];
354
+ return true;
355
+ },
356
+ getOwnPropertyDescriptor(state, prop) {
357
+ const owner = latest(state);
358
+ const desc = Reflect.getOwnPropertyDescriptor(owner, prop);
359
+ if (!desc) return desc;
360
+ return {
361
+ writable: true,
362
+ configurable: state.type_ !== 1 || prop !== "length",
363
+ enumerable: desc.enumerable,
364
+ value: owner[prop]
365
+ };
366
+ },
367
+ defineProperty() {
368
+ die(11);
369
+ },
370
+ getPrototypeOf(state) {
371
+ return getPrototypeOf(state.base_);
372
+ },
373
+ setPrototypeOf() {
374
+ die(12);
375
+ }
499
376
  };
500
377
  var arrayTraps = {};
501
378
  each(objectTraps, (key, fn) => {
502
- arrayTraps[key] = function() {
503
- arguments[0] = arguments[0][0];
504
- return fn.apply(this, arguments);
505
- };
379
+ arrayTraps[key] = function() {
380
+ arguments[0] = arguments[0][0];
381
+ return fn.apply(this, arguments);
382
+ };
506
383
  });
507
384
  arrayTraps.deleteProperty = function(state, prop) {
508
- if (process.env.NODE_ENV !== "production" && isNaN(parseInt(prop)))
509
- die(13);
510
- return arrayTraps.set.call(this, state, prop, void 0);
385
+ if (process.env.NODE_ENV !== "production" && isNaN(parseInt(prop))) die(13);
386
+ return arrayTraps.set.call(this, state, prop, void 0);
511
387
  };
512
388
  arrayTraps.set = function(state, prop, value) {
513
- if (process.env.NODE_ENV !== "production" && prop !== "length" && isNaN(parseInt(prop)))
514
- die(14);
515
- return objectTraps.set.call(this, state[0], prop, value, state[0]);
389
+ if (process.env.NODE_ENV !== "production" && prop !== "length" && isNaN(parseInt(prop))) die(14);
390
+ return objectTraps.set.call(this, state[0], prop, value, state[0]);
516
391
  };
517
392
  function peek(draft, prop) {
518
- const state = draft[DRAFT_STATE];
519
- const source = state ? latest(state) : draft;
520
- return source[prop];
393
+ const state = draft[DRAFT_STATE];
394
+ return (state ? latest(state) : draft)[prop];
521
395
  }
522
396
  function readPropFromProto(state, source, prop) {
523
- const desc = getDescriptorFromProto(source, prop);
524
- return desc ? `value` in desc ? desc.value : (
525
- // This is a very special case, if the prop is a getter defined by the
526
- // prototype, we should invoke it with the draft as context!
527
- desc.get?.call(state.draft_)
528
- ) : void 0;
397
+ const desc = getDescriptorFromProto(source, prop);
398
+ return desc ? `value` in desc ? desc.value : desc.get?.call(state.draft_) : void 0;
529
399
  }
530
400
  function getDescriptorFromProto(source, prop) {
531
- if (!(prop in source))
532
- return void 0;
533
- let proto = getPrototypeOf(source);
534
- while (proto) {
535
- const desc = Object.getOwnPropertyDescriptor(proto, prop);
536
- if (desc)
537
- return desc;
538
- proto = getPrototypeOf(proto);
539
- }
540
- return void 0;
401
+ if (!(prop in source)) return void 0;
402
+ let proto = getPrototypeOf(source);
403
+ while (proto) {
404
+ const desc = Object.getOwnPropertyDescriptor(proto, prop);
405
+ if (desc) return desc;
406
+ proto = getPrototypeOf(proto);
407
+ }
541
408
  }
542
409
  function markChanged(state) {
543
- if (!state.modified_) {
544
- state.modified_ = true;
545
- if (state.parent_) {
546
- markChanged(state.parent_);
547
- }
548
- }
410
+ if (!state.modified_) {
411
+ state.modified_ = true;
412
+ if (state.parent_) markChanged(state.parent_);
413
+ }
549
414
  }
550
415
  function prepareCopy(state) {
551
- if (!state.copy_) {
552
- state.copy_ = shallowCopy(
553
- state.base_,
554
- state.scope_.immer_.useStrictShallowCopy_
555
- );
556
- }
557
- }
558
-
559
- // src/core/immerClass.ts
416
+ if (!state.copy_) state.copy_ = shallowCopy(state.base_, state.scope_.immer_.useStrictShallowCopy_);
417
+ }
560
418
  var Immer2 = class {
561
- constructor(config) {
562
- this.autoFreeze_ = true;
563
- this.useStrictShallowCopy_ = false;
564
- /**
565
- * The `produce` function takes a value and a "recipe function" (whose
566
- * return value often depends on the base state). The recipe function is
567
- * free to mutate its first argument however it wants. All mutations are
568
- * only ever applied to a __copy__ of the base state.
569
- *
570
- * Pass only a function to create a "curried producer" which relieves you
571
- * from passing the recipe function every time.
572
- *
573
- * Only plain objects and arrays are made mutable. All other objects are
574
- * considered uncopyable.
575
- *
576
- * Note: This function is __bound__ to its `Immer` instance.
577
- *
578
- * @param {any} base - the initial state
579
- * @param {Function} recipe - function that receives a proxy of the base state as first argument and which can be freely modified
580
- * @param {Function} patchListener - optional function that will be called with all the patches produced here
581
- * @returns {any} a new state, or the initial state if nothing was modified
582
- */
583
- this.produce = (base, recipe, patchListener) => {
584
- if (typeof base === "function" && typeof recipe !== "function") {
585
- const defaultBase = recipe;
586
- recipe = base;
587
- const self = this;
588
- return function curriedProduce(base2 = defaultBase, ...args) {
589
- return self.produce(base2, (draft) => recipe.call(this, draft, ...args));
590
- };
591
- }
592
- if (typeof recipe !== "function")
593
- die(6);
594
- if (patchListener !== void 0 && typeof patchListener !== "function")
595
- die(7);
596
- let result;
597
- if (isDraftable(base)) {
598
- const scope = enterScope(this);
599
- const proxy = createProxy(base, void 0);
600
- let hasError = true;
601
- try {
602
- result = recipe(proxy);
603
- hasError = false;
604
- } finally {
605
- if (hasError)
606
- revokeScope(scope);
607
- else
608
- leaveScope(scope);
609
- }
610
- usePatchesInScope(scope, patchListener);
611
- return processResult(result, scope);
612
- } else if (!base || typeof base !== "object") {
613
- result = recipe(base);
614
- if (result === void 0)
615
- result = base;
616
- if (result === NOTHING)
617
- result = void 0;
618
- if (this.autoFreeze_)
619
- freeze(result, true);
620
- if (patchListener) {
621
- const p = [];
622
- const ip = [];
623
- getPlugin("Patches").generateReplacementPatches_(base, result, p, ip);
624
- patchListener(p, ip);
625
- }
626
- return result;
627
- } else
628
- die(1, base);
629
- };
630
- this.produceWithPatches = (base, recipe) => {
631
- if (typeof base === "function") {
632
- return (state, ...args) => this.produceWithPatches(state, (draft) => base(draft, ...args));
633
- }
634
- let patches, inversePatches;
635
- const result = this.produce(base, recipe, (p, ip) => {
636
- patches = p;
637
- inversePatches = ip;
638
- });
639
- return [result, patches, inversePatches];
640
- };
641
- if (typeof config?.autoFreeze === "boolean")
642
- this.setAutoFreeze(config.autoFreeze);
643
- if (typeof config?.useStrictShallowCopy === "boolean")
644
- this.setUseStrictShallowCopy(config.useStrictShallowCopy);
645
- }
646
- createDraft(base) {
647
- if (!isDraftable(base))
648
- die(8);
649
- if (isDraft(base))
650
- base = current(base);
651
- const scope = enterScope(this);
652
- const proxy = createProxy(base, void 0);
653
- proxy[DRAFT_STATE].isManual_ = true;
654
- leaveScope(scope);
655
- return proxy;
656
- }
657
- finishDraft(draft, patchListener) {
658
- const state = draft && draft[DRAFT_STATE];
659
- if (!state || !state.isManual_)
660
- die(9);
661
- const { scope_: scope } = state;
662
- usePatchesInScope(scope, patchListener);
663
- return processResult(void 0, scope);
664
- }
665
- /**
666
- * Pass true to automatically freeze all copies created by Immer.
667
- *
668
- * By default, auto-freezing is enabled.
669
- */
670
- setAutoFreeze(value) {
671
- this.autoFreeze_ = value;
672
- }
673
- /**
674
- * Pass true to enable strict shallow copy.
675
- *
676
- * By default, immer does not copy the object descriptors such as getter, setter and non-enumrable properties.
677
- */
678
- setUseStrictShallowCopy(value) {
679
- this.useStrictShallowCopy_ = value;
680
- }
681
- applyPatches(base, patches) {
682
- let i;
683
- for (i = patches.length - 1; i >= 0; i--) {
684
- const patch = patches[i];
685
- if (patch.path.length === 0 && patch.op === "replace") {
686
- base = patch.value;
687
- break;
688
- }
689
- }
690
- if (i > -1) {
691
- patches = patches.slice(i + 1);
692
- }
693
- const applyPatchesImpl = getPlugin("Patches").applyPatches_;
694
- if (isDraft(base)) {
695
- return applyPatchesImpl(base, patches);
696
- }
697
- return this.produce(
698
- base,
699
- (draft) => applyPatchesImpl(draft, patches)
700
- );
701
- }
419
+ constructor(config) {
420
+ this.autoFreeze_ = true;
421
+ this.useStrictShallowCopy_ = false;
422
+ /**
423
+ * The `produce` function takes a value and a "recipe function" (whose
424
+ * return value often depends on the base state). The recipe function is
425
+ * free to mutate its first argument however it wants. All mutations are
426
+ * only ever applied to a __copy__ of the base state.
427
+ *
428
+ * Pass only a function to create a "curried producer" which relieves you
429
+ * from passing the recipe function every time.
430
+ *
431
+ * Only plain objects and arrays are made mutable. All other objects are
432
+ * considered uncopyable.
433
+ *
434
+ * Note: This function is __bound__ to its `Immer` instance.
435
+ *
436
+ * @param {any} base - the initial state
437
+ * @param {Function} recipe - function that receives a proxy of the base state as first argument and which can be freely modified
438
+ * @param {Function} patchListener - optional function that will be called with all the patches produced here
439
+ * @returns {any} a new state, or the initial state if nothing was modified
440
+ */
441
+ this.produce = (base, recipe, patchListener) => {
442
+ if (typeof base === "function" && typeof recipe !== "function") {
443
+ const defaultBase = recipe;
444
+ recipe = base;
445
+ const self = this;
446
+ return function curriedProduce(base2 = defaultBase, ...args) {
447
+ return self.produce(base2, (draft) => recipe.call(this, draft, ...args));
448
+ };
449
+ }
450
+ if (typeof recipe !== "function") die(6);
451
+ if (patchListener !== void 0 && typeof patchListener !== "function") die(7);
452
+ let result;
453
+ if (isDraftable(base)) {
454
+ const scope = enterScope(this);
455
+ const proxy = createProxy(base, void 0);
456
+ let hasError = true;
457
+ try {
458
+ result = recipe(proxy);
459
+ hasError = false;
460
+ } finally {
461
+ if (hasError) revokeScope(scope);
462
+ else leaveScope(scope);
463
+ }
464
+ usePatchesInScope(scope, patchListener);
465
+ return processResult(result, scope);
466
+ } else if (!base || typeof base !== "object") {
467
+ result = recipe(base);
468
+ if (result === void 0) result = base;
469
+ if (result === NOTHING) result = void 0;
470
+ if (this.autoFreeze_) freeze(result, true);
471
+ if (patchListener) {
472
+ const p = [];
473
+ const ip = [];
474
+ getPlugin("Patches").generateReplacementPatches_(base, result, p, ip);
475
+ patchListener(p, ip);
476
+ }
477
+ return result;
478
+ } else die(1, base);
479
+ };
480
+ this.produceWithPatches = (base, recipe) => {
481
+ if (typeof base === "function") return (state, ...args) => this.produceWithPatches(state, (draft) => base(draft, ...args));
482
+ let patches, inversePatches;
483
+ return [
484
+ this.produce(base, recipe, (p, ip) => {
485
+ patches = p;
486
+ inversePatches = ip;
487
+ }),
488
+ patches,
489
+ inversePatches
490
+ ];
491
+ };
492
+ if (typeof config?.autoFreeze === "boolean") this.setAutoFreeze(config.autoFreeze);
493
+ if (typeof config?.useStrictShallowCopy === "boolean") this.setUseStrictShallowCopy(config.useStrictShallowCopy);
494
+ }
495
+ createDraft(base) {
496
+ if (!isDraftable(base)) die(8);
497
+ if (isDraft(base)) base = current(base);
498
+ const scope = enterScope(this);
499
+ const proxy = createProxy(base, void 0);
500
+ proxy[DRAFT_STATE].isManual_ = true;
501
+ leaveScope(scope);
502
+ return proxy;
503
+ }
504
+ finishDraft(draft, patchListener) {
505
+ const state = draft && draft[DRAFT_STATE];
506
+ if (!state || !state.isManual_) die(9);
507
+ const { scope_: scope } = state;
508
+ usePatchesInScope(scope, patchListener);
509
+ return processResult(void 0, scope);
510
+ }
511
+ /**
512
+ * Pass true to automatically freeze all copies created by Immer.
513
+ *
514
+ * By default, auto-freezing is enabled.
515
+ */
516
+ setAutoFreeze(value) {
517
+ this.autoFreeze_ = value;
518
+ }
519
+ /**
520
+ * Pass true to enable strict shallow copy.
521
+ *
522
+ * By default, immer does not copy the object descriptors such as getter, setter and non-enumrable properties.
523
+ */
524
+ setUseStrictShallowCopy(value) {
525
+ this.useStrictShallowCopy_ = value;
526
+ }
527
+ applyPatches(base, patches) {
528
+ let i;
529
+ for (i = patches.length - 1; i >= 0; i--) {
530
+ const patch = patches[i];
531
+ if (patch.path.length === 0 && patch.op === "replace") {
532
+ base = patch.value;
533
+ break;
534
+ }
535
+ }
536
+ if (i > -1) patches = patches.slice(i + 1);
537
+ const applyPatchesImpl = getPlugin("Patches").applyPatches_;
538
+ if (isDraft(base)) return applyPatchesImpl(base, patches);
539
+ return this.produce(base, (draft) => applyPatchesImpl(draft, patches));
540
+ }
702
541
  };
703
542
  function createProxy(value, parent) {
704
- const draft = isMap(value) ? getPlugin("MapSet").proxyMap_(value, parent) : isSet(value) ? getPlugin("MapSet").proxySet_(value, parent) : createProxyProxy(value, parent);
705
- const scope = parent ? parent.scope_ : getCurrentScope();
706
- scope.drafts_.push(draft);
707
- return draft;
543
+ const draft = isMap(value) ? getPlugin("MapSet").proxyMap_(value, parent) : isSet(value) ? getPlugin("MapSet").proxySet_(value, parent) : createProxyProxy(value, parent);
544
+ (parent ? parent.scope_ : getCurrentScope()).drafts_.push(draft);
545
+ return draft;
708
546
  }
709
-
710
- // src/core/current.ts
711
547
  function current(value) {
712
- if (!isDraft(value))
713
- die(10, value);
714
- return currentImpl(value);
548
+ if (!isDraft(value)) die(10, value);
549
+ return currentImpl(value);
715
550
  }
716
551
  function currentImpl(value) {
717
- if (!isDraftable(value) || isFrozen(value))
718
- return value;
719
- const state = value[DRAFT_STATE];
720
- let copy;
721
- if (state) {
722
- if (!state.modified_)
723
- return state.base_;
724
- state.finalized_ = true;
725
- copy = shallowCopy(value, state.scope_.immer_.useStrictShallowCopy_);
726
- } else {
727
- copy = shallowCopy(value, true);
728
- }
729
- each(copy, (key, childValue) => {
730
- set(copy, key, currentImpl(childValue));
731
- });
732
- if (state) {
733
- state.finalized_ = false;
734
- }
735
- return copy;
736
- }
737
-
738
- // src/immer.ts
552
+ if (!isDraftable(value) || isFrozen(value)) return value;
553
+ const state = value[DRAFT_STATE];
554
+ let copy;
555
+ if (state) {
556
+ if (!state.modified_) return state.base_;
557
+ state.finalized_ = true;
558
+ copy = shallowCopy(value, state.scope_.immer_.useStrictShallowCopy_);
559
+ } else copy = shallowCopy(value, true);
560
+ each(copy, (key, childValue) => {
561
+ set(copy, key, currentImpl(childValue));
562
+ });
563
+ if (state) state.finalized_ = false;
564
+ return copy;
565
+ }
739
566
  var immer = new Immer2();
740
567
  var produce = immer.produce;
741
- immer.produceWithPatches.bind(
742
- immer
743
- );
568
+ immer.produceWithPatches.bind(immer);
744
569
  immer.setAutoFreeze.bind(immer);
745
570
  immer.setUseStrictShallowCopy.bind(immer);
746
571
  immer.applyPatches.bind(immer);
747
572
  immer.createDraft.bind(immer);
748
573
  immer.finishDraft.bind(immer);
749
-
750
- var __defProp = Object.defineProperty;
751
- var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
752
- var __publicField = (obj, key, value) => {
753
- __defNormalProp(obj, typeof key !== "symbol" ? key + "" : key, value);
754
- return value;
755
- };
574
+ //#endregion
575
+ //#region src/index.ts
576
+ /**
577
+ * 创建预览 iframe 控制器
578
+ * @param options - 创建控制器的选项
579
+ * @returns 预览 iframe 控制器实例
580
+ */
756
581
  function createController(options) {
757
- const controller = new PreviewIframeControllerImpl(options);
758
- window.__PREVIEWJS_CONTROLLER__ = controller;
759
- return controller;
760
- }
761
- class PreviewIframeControllerImpl {
762
- /**
763
- * 构造函数
764
- * @param options - 创建控制器的选项
765
- */
766
- constructor(options) {
767
- this.options = options;
768
- /**
769
- * 最后一次渲染的信息
770
- */
771
- __publicField(this, "lastRender", null);
772
- /**
773
- * 初始化状态
774
- */
775
- __publicField(this, "bootstrapStatus", "pending");
776
- /**
777
- * 期望渲染的超时定时器
778
- */
779
- // biome-ignore lint/suspicious/noExplicitAny: <explanation>
780
- __publicField(this, "expectRenderTimeout");
781
- /**
782
- * 预览 iframe 的当前状态
783
- */
784
- __publicField(this, "state", {
785
- loading: false,
786
- rendered: false,
787
- errors: [],
788
- logs: [],
789
- actions: []
790
- });
791
- /**
792
- * Vite 预更新前的日志长度
793
- */
794
- __publicField(this, "onViteBeforeUpdateLogsLength", 0);
795
- /**
796
- * Vite 预更新前的错误长度
797
- */
798
- __publicField(this, "onViteBeforeUpdateErrorsLength", 0);
799
- }
800
- /**
801
- * 渲染预览
802
- * @param previewableId - 可预览项的 ID
803
- * @param options - 渲染选项
804
- */
805
- async render(previewableId, options) {
806
- const previousRender = this.lastRender;
807
- this.lastRender = { previewableId, options };
808
- if (previousRender?.previewableId !== previewableId || this.bootstrapStatus === "failure") {
809
- this.resetIframe(previewableId);
810
- return;
811
- }
812
- const iframeWindow = this.options.getIframe()?.contentWindow;
813
- if (!iframeWindow || this.bootstrapStatus !== "success") {
814
- return;
815
- }
816
- if (!iframeWindow.__PREVIEWJS_IFRAME__.render) {
817
- iframeWindow.__PREVIEWJS_IFRAME__.reportEvent({
818
- kind: "error",
819
- source: "renderer",
820
- message: "Iframe was bootstrapped but not fully initialised.\n\nPlease report this at https://github.com/fwouts/previewjs."
821
- });
822
- return;
823
- }
824
- const renderPromise = iframeWindow.__PREVIEWJS_IFRAME__.render(options);
825
- this.clearExpectRenderTimeout();
826
- this.expectRenderTimeout = setTimeout(() => {
827
- console.warn(
828
- "Expected render did not occur after 5 seconds. Reloading iframe..."
829
- );
830
- this.resetIframe(previewableId);
831
- }, 5e3);
832
- await renderPromise;
833
- }
834
- /**
835
- * 重置 iframe
836
- * @param id - 可预览项的 ID
837
- */
838
- resetIframe(id) {
839
- const iframe = this.options.getIframe();
840
- if (!iframe) {
841
- return;
842
- }
843
- iframe.src = `/${id}/?t=${Date.now()}`;
844
- this.bootstrapStatus = "not-started";
845
- }
846
- /**
847
- * 处理预览事件
848
- * @param event - 预览事件对象
849
- */
850
- onPreviewEvent(event) {
851
- if (this.bootstrapStatus === "not-started") {
852
- if (event.kind !== "bootstrapping") {
853
- return;
854
- }
855
- }
856
- switch (event.kind) {
857
- case "bootstrapping":
858
- this.bootstrapStatus = "pending";
859
- break;
860
- case "bootstrapped":
861
- this.bootstrapStatus = "success";
862
- this.onViteBeforeUpdateLogsLength = 0;
863
- this.onViteBeforeUpdateErrorsLength = 0;
864
- this.updateState((state) => {
865
- state.loading = true;
866
- state.rendered = false;
867
- state.errors = [];
868
- state.logs = [];
869
- });
870
- if (this.lastRender) {
871
- this.render(
872
- this.lastRender.previewableId,
873
- this.lastRender.options
874
- ).catch(
875
- // eslint-disable-next-line no-console
876
- console.error
877
- );
878
- }
879
- break;
880
- case "vite-before-reload":
881
- this.updateState((state) => {
882
- state.logs = [];
883
- state.errors = [];
884
- });
885
- if (this.lastRender) {
886
- this.resetIframe(this.lastRender.previewableId);
887
- }
888
- break;
889
- case "vite-before-update":
890
- this.onViteBeforeUpdateLogsLength = this.state.logs.length;
891
- this.updateState((state) => {
892
- for (const update of event.payload.updates) {
893
- state.errors = state.errors.filter(
894
- (e) => e.source !== "hmr" || e.modulePath !== update.acceptedPath
895
- );
896
- }
897
- });
898
- this.onViteBeforeUpdateErrorsLength = this.state.errors.length;
899
- break;
900
- case "vite-invalidate":
901
- this.updateState((state) => {
902
- this.onViteBeforeUpdateLogsLength = 0;
903
- this.onViteBeforeUpdateErrorsLength = 0;
904
- state.logs = [];
905
- });
906
- break;
907
- case "vite-after-update":
908
- this.updateState((state) => {
909
- const logsSliceStart = this.onViteBeforeUpdateLogsLength;
910
- const errorsSliceStart = this.onViteBeforeUpdateErrorsLength;
911
- this.onViteBeforeUpdateLogsLength = 0;
912
- this.onViteBeforeUpdateErrorsLength = 0;
913
- state.logs = state.logs.slice(logsSliceStart);
914
- state.errors = state.errors.slice(errorsSliceStart);
915
- });
916
- break;
917
- case "before-render":
918
- this.updateState((state) => {
919
- this.onViteBeforeUpdateLogsLength = 0;
920
- state.logs = [];
921
- });
922
- break;
923
- case "rendered": {
924
- this.updateState((state) => {
925
- state.loading = false;
926
- state.rendered = true;
927
- });
928
- this.clearExpectRenderTimeout();
929
- break;
930
- }
931
- case "error":
932
- this.updateState((state) => {
933
- state.loading = false;
934
- if (event.source === "vite" && event.message.includes(
935
- "Failed to fetch dynamically imported module"
936
- ) && state.errors.find((e) => e.source === "vite")) {
937
- return;
938
- }
939
- state.errors = state.errors.filter((e) => e.source !== event.source);
940
- state.errors.push(event);
941
- });
942
- this.clearExpectRenderTimeout();
943
- if (this.bootstrapStatus === "pending") {
944
- this.bootstrapStatus = "failure";
945
- }
946
- break;
947
- case "log-message":
948
- this.updateState((state) => {
949
- state.logs.push(event);
950
- });
951
- break;
952
- case "action":
953
- this.updateState((state) => {
954
- state.actions.push(event);
955
- });
956
- break;
957
- case "toggle-inspect": {
958
- console.log("\u89E6\u53D1toggle-inspect", event.enabled);
959
- const window2 = this.options.getIframe()?.contentWindow;
960
- if (window2) {
961
- window2.__PREVIEWJS_IFRAME__.toggleInspect = event.enabled;
962
- window2.__PREVIEWJS_IFRAME__.refresh({
963
- refetchWrapperModule: true
964
- });
965
- }
966
- break;
967
- }
968
- default:
969
- throw assertNever_2(event);
970
- }
971
- }
972
- /**
973
- * 更新状态
974
- * @param stateModifier - 状态修改函数
975
- */
976
- updateState(stateModifier) {
977
- this.state = produce(this.state, stateModifier);
978
- this.options.onStateUpdate?.(this.state);
979
- }
980
- /**
981
- * 清除期望渲染的超时定时器
982
- */
983
- clearExpectRenderTimeout() {
984
- if (this.expectRenderTimeout) {
985
- clearTimeout(this.expectRenderTimeout);
986
- this.expectRenderTimeout = null;
987
- }
988
- }
989
- }
990
-
582
+ const controller = new PreviewIframeControllerImpl(options);
583
+ window.__PREVIEWJS_CONTROLLER__ = controller;
584
+ return controller;
585
+ }
586
+ /**
587
+ * 预览 iframe 控制器的实现类
588
+ */
589
+ var PreviewIframeControllerImpl = class {
590
+ /**
591
+ * 构造函数
592
+ * @param options - 创建控制器的选项
593
+ */
594
+ constructor(options) {
595
+ this.options = options;
596
+ this.lastRender = null;
597
+ this.bootstrapStatus = "pending";
598
+ this.state = {
599
+ loading: false,
600
+ rendered: false,
601
+ errors: [],
602
+ logs: [],
603
+ actions: []
604
+ };
605
+ this.onViteBeforeUpdateLogsLength = 0;
606
+ this.onViteBeforeUpdateErrorsLength = 0;
607
+ }
608
+ /**
609
+ * 渲染预览
610
+ * @param previewableId - 可预览项的 ID
611
+ * @param options - 渲染选项
612
+ */
613
+ async render(previewableId, options) {
614
+ const previousRender = this.lastRender;
615
+ this.lastRender = {
616
+ previewableId,
617
+ options
618
+ };
619
+ if (previousRender?.previewableId !== previewableId || this.bootstrapStatus === "failure") {
620
+ this.resetIframe(previewableId);
621
+ return;
622
+ }
623
+ const iframeWindow = this.options.getIframe()?.contentWindow;
624
+ if (!iframeWindow || this.bootstrapStatus !== "success") return;
625
+ if (!iframeWindow.__PREVIEWJS_IFRAME__.render) {
626
+ iframeWindow.__PREVIEWJS_IFRAME__.reportEvent({
627
+ kind: "error",
628
+ source: "renderer",
629
+ message: "Iframe was bootstrapped but not fully initialised."
630
+ });
631
+ return;
632
+ }
633
+ const renderPromise = iframeWindow.__PREVIEWJS_IFRAME__.render(options);
634
+ this.clearExpectRenderTimeout();
635
+ this.expectRenderTimeout = setTimeout(() => {
636
+ console.warn("Expected render did not occur after 5 seconds. Reloading iframe...");
637
+ this.resetIframe(previewableId);
638
+ }, 5e3);
639
+ await renderPromise;
640
+ }
641
+ /**
642
+ * 重置 iframe
643
+ * @param id - 可预览项的 ID
644
+ */
645
+ resetIframe(id) {
646
+ const iframe = this.options.getIframe();
647
+ if (!iframe) return;
648
+ iframe.src = `/${id}/?t=${Date.now()}`;
649
+ this.bootstrapStatus = "not-started";
650
+ }
651
+ /**
652
+ * 处理预览事件
653
+ * @param event - 预览事件对象
654
+ */
655
+ onPreviewEvent(event) {
656
+ if (this.bootstrapStatus === "not-started") {
657
+ if (event.kind !== "bootstrapping") return;
658
+ }
659
+ switch (event.kind) {
660
+ case "bootstrapping":
661
+ this.bootstrapStatus = "pending";
662
+ break;
663
+ case "bootstrapped":
664
+ this.bootstrapStatus = "success";
665
+ this.onViteBeforeUpdateLogsLength = 0;
666
+ this.onViteBeforeUpdateErrorsLength = 0;
667
+ this.updateState((state) => {
668
+ state.loading = true;
669
+ state.rendered = false;
670
+ state.errors = [];
671
+ state.logs = [];
672
+ });
673
+ if (this.lastRender) this.render(this.lastRender.previewableId, this.lastRender.options).catch(console.error);
674
+ break;
675
+ case "vite-before-reload":
676
+ this.updateState((state) => {
677
+ state.logs = [];
678
+ state.errors = [];
679
+ });
680
+ if (this.lastRender) this.resetIframe(this.lastRender.previewableId);
681
+ break;
682
+ case "vite-before-update":
683
+ this.onViteBeforeUpdateLogsLength = this.state.logs.length;
684
+ this.updateState((state) => {
685
+ for (const update of event.payload.updates) state.errors = state.errors.filter((e) => e.source !== "hmr" || e.modulePath !== update.acceptedPath);
686
+ });
687
+ this.onViteBeforeUpdateErrorsLength = this.state.errors.length;
688
+ break;
689
+ case "vite-invalidate":
690
+ this.updateState((state) => {
691
+ this.onViteBeforeUpdateLogsLength = 0;
692
+ this.onViteBeforeUpdateErrorsLength = 0;
693
+ state.logs = [];
694
+ });
695
+ break;
696
+ case "vite-after-update":
697
+ this.updateState((state) => {
698
+ const logsSliceStart = this.onViteBeforeUpdateLogsLength;
699
+ const errorsSliceStart = this.onViteBeforeUpdateErrorsLength;
700
+ this.onViteBeforeUpdateLogsLength = 0;
701
+ this.onViteBeforeUpdateErrorsLength = 0;
702
+ state.logs = state.logs.slice(logsSliceStart);
703
+ state.errors = state.errors.slice(errorsSliceStart);
704
+ });
705
+ break;
706
+ case "before-render":
707
+ this.updateState((state) => {
708
+ this.onViteBeforeUpdateLogsLength = 0;
709
+ state.logs = [];
710
+ });
711
+ break;
712
+ case "rendered":
713
+ this.updateState((state) => {
714
+ state.loading = false;
715
+ state.rendered = true;
716
+ });
717
+ this.clearExpectRenderTimeout();
718
+ break;
719
+ case "error":
720
+ this.updateState((state) => {
721
+ state.loading = false;
722
+ if (event.source === "vite" && event.message.includes("Failed to fetch dynamically imported module") && state.errors.find((e) => e.source === "vite")) return;
723
+ state.errors = state.errors.filter((e) => e.source !== event.source);
724
+ state.errors.push(event);
725
+ });
726
+ this.clearExpectRenderTimeout();
727
+ if (this.bootstrapStatus === "pending") this.bootstrapStatus = "failure";
728
+ break;
729
+ case "log-message":
730
+ this.updateState((state) => {
731
+ state.logs.push(event);
732
+ });
733
+ break;
734
+ case "action":
735
+ this.updateState((state) => {
736
+ state.actions.push(event);
737
+ });
738
+ break;
739
+ case "toggle-inspect": {
740
+ const window = this.options.getIframe()?.contentWindow;
741
+ if (window) {
742
+ window.__PREVIEWJS_IFRAME__.toggleInspect = event.enabled;
743
+ window.__PREVIEWJS_IFRAME__.refresh({ refetchWrapperModule: true });
744
+ }
745
+ break;
746
+ }
747
+ default: throw (0, import_assert_never.assertNever)(event);
748
+ }
749
+ }
750
+ /**
751
+ * 更新状态
752
+ * @param stateModifier - 状态修改函数
753
+ */
754
+ updateState(stateModifier) {
755
+ this.state = produce(this.state, stateModifier);
756
+ this.options.onStateUpdate?.(this.state);
757
+ }
758
+ /**
759
+ * 清除期望渲染的超时定时器
760
+ */
761
+ clearExpectRenderTimeout() {
762
+ if (this.expectRenderTimeout) {
763
+ clearTimeout(this.expectRenderTimeout);
764
+ this.expectRenderTimeout = null;
765
+ }
766
+ }
767
+ };
768
+ //#endregion
991
769
  export { createController };