document-model 1.0.55 → 1.1.0-debug.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (74) hide show
  1. package/CHANGELOG.md +19 -0
  2. package/dist/browser/cjs/document-model.js +21 -1
  3. package/dist/browser/cjs/document-model.js.map +1 -0
  4. package/dist/browser/cjs/document.js +15 -1
  5. package/dist/browser/cjs/document.js.map +1 -0
  6. package/dist/browser/cjs/index.js +18 -1
  7. package/dist/browser/cjs/index.js.map +1 -0
  8. package/dist/browser/cjs/internal/index-CaJbS06G.js +2339 -0
  9. package/dist/browser/cjs/internal/index-CaJbS06G.js.map +1 -0
  10. package/dist/browser/cjs/internal/index-kKIg6qNB.js +44 -0
  11. package/dist/browser/cjs/internal/index-kKIg6qNB.js.map +1 -0
  12. package/dist/browser/cjs/internal/object-B6dSDhtS.js +4109 -0
  13. package/dist/browser/cjs/internal/object-B6dSDhtS.js.map +1 -0
  14. package/dist/browser/es/document-model.js +16 -15
  15. package/dist/browser/es/document-model.js.map +1 -0
  16. package/dist/browser/es/document.js +10 -9
  17. package/dist/browser/es/document.js.map +1 -0
  18. package/dist/browser/es/index.js +13 -11
  19. package/dist/browser/es/index.js.map +1 -0
  20. package/dist/browser/es/internal/index-B1lQN59e.js +2340 -0
  21. package/dist/browser/es/internal/index-B1lQN59e.js.map +1 -0
  22. package/dist/browser/es/internal/index-Bu0CkmrW.js +45 -0
  23. package/dist/browser/es/internal/index-Bu0CkmrW.js.map +1 -0
  24. package/dist/browser/es/internal/object-9mR1JlXD.js +4110 -0
  25. package/dist/browser/es/internal/object-9mR1JlXD.js.map +1 -0
  26. package/dist/browser/src/document/reducer.d.ts +13 -2
  27. package/dist/browser/src/document/utils/base.d.ts +1 -1
  28. package/dist/browser/src/document/utils/document-helpers.d.ts +53 -0
  29. package/dist/browser/src/document/utils/index.d.ts +1 -0
  30. package/dist/node/cjs/document-model.js +25 -1
  31. package/dist/node/cjs/document-model.js.map +1 -0
  32. package/dist/node/cjs/document.js +19 -1
  33. package/dist/node/cjs/document.js.map +1 -0
  34. package/dist/node/cjs/index.js +22 -1
  35. package/dist/node/cjs/index.js.map +1 -0
  36. package/dist/node/cjs/internal/index-AqiVmL0w.js +44 -0
  37. package/dist/node/cjs/internal/index-AqiVmL0w.js.map +1 -0
  38. package/dist/node/cjs/internal/index-ajqhOWQ1.js +2343 -0
  39. package/dist/node/cjs/internal/index-ajqhOWQ1.js.map +1 -0
  40. package/dist/node/cjs/internal/object-D_9h7jBN.js +2111 -0
  41. package/dist/node/cjs/internal/object-D_9h7jBN.js.map +1 -0
  42. package/dist/node/es/document-model.js +16 -15
  43. package/dist/node/es/document-model.js.map +1 -0
  44. package/dist/node/es/document.js +11 -10
  45. package/dist/node/es/document.js.map +1 -0
  46. package/dist/node/es/index.js +14 -12
  47. package/dist/node/es/index.js.map +1 -0
  48. package/dist/node/es/internal/index-Bh_09edy.js +2344 -0
  49. package/dist/node/es/internal/index-Bh_09edy.js.map +1 -0
  50. package/dist/node/es/internal/index-s6NFw7Kq.js +45 -0
  51. package/dist/node/es/internal/index-s6NFw7Kq.js.map +1 -0
  52. package/dist/node/es/internal/object-CbITi4iq.js +2112 -0
  53. package/dist/node/es/internal/object-CbITi4iq.js.map +1 -0
  54. package/dist/node/src/document/reducer.d.ts +13 -2
  55. package/dist/node/src/document/utils/base.d.ts +1 -1
  56. package/dist/node/src/document/utils/document-helpers.d.ts +53 -0
  57. package/dist/node/src/document/utils/index.d.ts +1 -0
  58. package/dist/src/document/reducer.d.ts +13 -2
  59. package/dist/src/document/utils/base.d.ts +1 -1
  60. package/dist/src/document/utils/document-helpers.d.ts +53 -0
  61. package/dist/src/document/utils/index.d.ts +1 -0
  62. package/package.json +7 -2
  63. package/dist/browser/cjs/internal/index-C_OFq7P5.js +0 -22
  64. package/dist/browser/cjs/internal/index-Dwhv4k_6.js +0 -1
  65. package/dist/browser/cjs/internal/object-CeLE3akL.js +0 -25
  66. package/dist/browser/es/internal/index-DvHnaqeu.js +0 -2104
  67. package/dist/browser/es/internal/index-Xcvn-MUq.js +0 -42
  68. package/dist/browser/es/internal/object-BDWVt0Zy.js +0 -2504
  69. package/dist/node/cjs/internal/index-Bi9yeV3W.js +0 -1
  70. package/dist/node/cjs/internal/index-GZsLKtHl.js +0 -22
  71. package/dist/node/cjs/internal/object-CnhDksx1.js +0 -20
  72. package/dist/node/es/internal/index-B6iEYnbQ.js +0 -42
  73. package/dist/node/es/internal/index-Chx4C-Xl.js +0 -2108
  74. package/dist/node/es/internal/object-CnV5hY_A.js +0 -1402
@@ -0,0 +1,4110 @@
1
+ var __defProp = Object.defineProperty;
2
+ var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
3
+ var __publicField = (obj, key, value) => {
4
+ __defNormalProp(obj, typeof key !== "symbol" ? key + "" : key, value);
5
+ return value;
6
+ };
7
+ import { produce, castDraft, castImmutable, freeze } from "immer";
8
+ import { z } from "zod";
9
+ import JSZip from "jszip";
10
+ const isDefinedNonNullAny = (v) => v !== void 0 && v !== null;
11
+ const definedNonNullAnySchema = z.any().refine((v) => isDefinedNonNullAny(v));
12
+ const Load_StateSchema = z.enum(["LOAD_STATE"]);
13
+ const PruneSchema = z.enum(["PRUNE"]);
14
+ const RedoSchema = z.enum(["REDO"]);
15
+ const Set_NameSchema = z.enum(["SET_NAME"]);
16
+ const UndoSchema = z.enum(["UNDO"]);
17
+ function ActionSchema() {
18
+ return z.object({
19
+ __typename: z.literal("Action").optional(),
20
+ type: z.string()
21
+ });
22
+ }
23
+ function OperationScopeSchema() {
24
+ return z.literal("global").or(z.literal("local"));
25
+ }
26
+ function BaseActionSchema() {
27
+ return z.union([
28
+ LoadStateActionSchema(),
29
+ PruneActionSchema(),
30
+ RedoActionSchema(),
31
+ SetNameActionSchema(),
32
+ UndoActionSchema()
33
+ ]);
34
+ }
35
+ function DocumentFileSchema() {
36
+ return z.object({
37
+ __typename: z.literal("DocumentFile").optional(),
38
+ data: z.string(),
39
+ extension: z.string().nullable(),
40
+ fileName: z.string().nullable(),
41
+ mimeType: z.string()
42
+ });
43
+ }
44
+ function LoadStateActionSchema() {
45
+ return z.object({
46
+ input: z.lazy(() => LoadStateActionInputSchema()),
47
+ type: Load_StateSchema,
48
+ scope: OperationScopeSchema()
49
+ });
50
+ }
51
+ function LoadStateActionInputSchema() {
52
+ return z.object({
53
+ operations: z.number(),
54
+ state: z.lazy(() => LoadStateActionStateInputSchema())
55
+ });
56
+ }
57
+ function LoadStateActionStateInputSchema() {
58
+ return z.object({
59
+ data: z.unknown().nullish(),
60
+ name: z.string()
61
+ });
62
+ }
63
+ function OperationSchema() {
64
+ return z.object({
65
+ __typename: z.literal("Operation").optional(),
66
+ hash: z.string(),
67
+ index: z.number(),
68
+ timestamp: z.string().datetime(),
69
+ type: z.string()
70
+ });
71
+ }
72
+ function PruneActionSchema() {
73
+ return z.object({
74
+ input: z.lazy(() => PruneActionInputSchema()),
75
+ type: PruneSchema,
76
+ scope: OperationScopeSchema()
77
+ });
78
+ }
79
+ function PruneActionInputSchema() {
80
+ return z.object({
81
+ end: z.number().nullish(),
82
+ start: z.number().nullish()
83
+ });
84
+ }
85
+ const RedoActionInputSchema = z.number;
86
+ function RedoActionSchema() {
87
+ return z.object({
88
+ input: RedoActionInputSchema(),
89
+ type: RedoSchema,
90
+ scope: OperationScopeSchema()
91
+ });
92
+ }
93
+ const SetNameActionInputSchema = z.string;
94
+ function SetNameActionSchema() {
95
+ return z.object({
96
+ input: SetNameActionInputSchema(),
97
+ type: Set_NameSchema,
98
+ scope: z.literal("global")
99
+ });
100
+ }
101
+ function SetNameOperationSchema() {
102
+ return z.object({
103
+ __typename: z.literal("SetNameOperation").optional(),
104
+ hash: z.string(),
105
+ index: z.number(),
106
+ input: z.string(),
107
+ timestamp: z.string().datetime(),
108
+ type: z.string()
109
+ });
110
+ }
111
+ const UndoActionInputSchema = z.number;
112
+ function UndoActionSchema() {
113
+ return z.object({
114
+ input: UndoActionInputSchema(),
115
+ type: UndoSchema,
116
+ scope: OperationScopeSchema()
117
+ });
118
+ }
119
+ const zod = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({
120
+ __proto__: null,
121
+ ActionSchema,
122
+ BaseActionSchema,
123
+ DocumentFileSchema,
124
+ LoadStateActionInputSchema,
125
+ LoadStateActionSchema,
126
+ LoadStateActionStateInputSchema,
127
+ Load_StateSchema,
128
+ OperationSchema,
129
+ OperationScopeSchema,
130
+ PruneActionInputSchema,
131
+ PruneActionSchema,
132
+ PruneSchema,
133
+ RedoActionInputSchema,
134
+ RedoActionSchema,
135
+ RedoSchema,
136
+ SetNameActionInputSchema,
137
+ SetNameActionSchema,
138
+ SetNameOperationSchema,
139
+ Set_NameSchema,
140
+ UndoActionInputSchema,
141
+ UndoActionSchema,
142
+ UndoSchema,
143
+ definedNonNullAnySchema,
144
+ isDefinedNonNullAny
145
+ }, Symbol.toStringTag, { value: "Module" }));
146
+ function getDefaultExportFromCjs(x) {
147
+ return x && x.__esModule && Object.prototype.hasOwnProperty.call(x, "default") ? x["default"] : x;
148
+ }
149
+ var safeStableStringify = { exports: {} };
150
+ (function(module, exports) {
151
+ const { hasOwnProperty } = Object.prototype;
152
+ const stringify = configure();
153
+ stringify.configure = configure;
154
+ stringify.stringify = stringify;
155
+ stringify.default = stringify;
156
+ exports.stringify = stringify;
157
+ exports.configure = configure;
158
+ module.exports = stringify;
159
+ const strEscapeSequencesRegExp = /[\u0000-\u001f\u0022\u005c\ud800-\udfff]|[\ud800-\udbff](?![\udc00-\udfff])|(?:[^\ud800-\udbff]|^)[\udc00-\udfff]/;
160
+ function strEscape(str) {
161
+ if (str.length < 5e3 && !strEscapeSequencesRegExp.test(str)) {
162
+ return `"${str}"`;
163
+ }
164
+ return JSON.stringify(str);
165
+ }
166
+ function insertSort(array) {
167
+ if (array.length > 200) {
168
+ return array.sort();
169
+ }
170
+ for (let i = 1; i < array.length; i++) {
171
+ const currentValue = array[i];
172
+ let position = i;
173
+ while (position !== 0 && array[position - 1] > currentValue) {
174
+ array[position] = array[position - 1];
175
+ position--;
176
+ }
177
+ array[position] = currentValue;
178
+ }
179
+ return array;
180
+ }
181
+ const typedArrayPrototypeGetSymbolToStringTag = Object.getOwnPropertyDescriptor(
182
+ Object.getPrototypeOf(
183
+ Object.getPrototypeOf(
184
+ new Int8Array()
185
+ )
186
+ ),
187
+ Symbol.toStringTag
188
+ ).get;
189
+ function isTypedArrayWithEntries(value) {
190
+ return typedArrayPrototypeGetSymbolToStringTag.call(value) !== void 0 && value.length !== 0;
191
+ }
192
+ function stringifyTypedArray(array, separator, maximumBreadth) {
193
+ if (array.length < maximumBreadth) {
194
+ maximumBreadth = array.length;
195
+ }
196
+ const whitespace = separator === "," ? "" : " ";
197
+ let res = `"0":${whitespace}${array[0]}`;
198
+ for (let i = 1; i < maximumBreadth; i++) {
199
+ res += `${separator}"${i}":${whitespace}${array[i]}`;
200
+ }
201
+ return res;
202
+ }
203
+ function getCircularValueOption(options) {
204
+ if (hasOwnProperty.call(options, "circularValue")) {
205
+ const circularValue = options.circularValue;
206
+ if (typeof circularValue === "string") {
207
+ return `"${circularValue}"`;
208
+ }
209
+ if (circularValue == null) {
210
+ return circularValue;
211
+ }
212
+ if (circularValue === Error || circularValue === TypeError) {
213
+ return {
214
+ toString() {
215
+ throw new TypeError("Converting circular structure to JSON");
216
+ }
217
+ };
218
+ }
219
+ throw new TypeError('The "circularValue" argument must be of type string or the value null or undefined');
220
+ }
221
+ return '"[Circular]"';
222
+ }
223
+ function getBooleanOption(options, key) {
224
+ let value;
225
+ if (hasOwnProperty.call(options, key)) {
226
+ value = options[key];
227
+ if (typeof value !== "boolean") {
228
+ throw new TypeError(`The "${key}" argument must be of type boolean`);
229
+ }
230
+ }
231
+ return value === void 0 ? true : value;
232
+ }
233
+ function getPositiveIntegerOption(options, key) {
234
+ let value;
235
+ if (hasOwnProperty.call(options, key)) {
236
+ value = options[key];
237
+ if (typeof value !== "number") {
238
+ throw new TypeError(`The "${key}" argument must be of type number`);
239
+ }
240
+ if (!Number.isInteger(value)) {
241
+ throw new TypeError(`The "${key}" argument must be an integer`);
242
+ }
243
+ if (value < 1) {
244
+ throw new RangeError(`The "${key}" argument must be >= 1`);
245
+ }
246
+ }
247
+ return value === void 0 ? Infinity : value;
248
+ }
249
+ function getItemCount(number) {
250
+ if (number === 1) {
251
+ return "1 item";
252
+ }
253
+ return `${number} items`;
254
+ }
255
+ function getUniqueReplacerSet(replacerArray) {
256
+ const replacerSet = /* @__PURE__ */ new Set();
257
+ for (const value of replacerArray) {
258
+ if (typeof value === "string" || typeof value === "number") {
259
+ replacerSet.add(String(value));
260
+ }
261
+ }
262
+ return replacerSet;
263
+ }
264
+ function getStrictOption(options) {
265
+ if (hasOwnProperty.call(options, "strict")) {
266
+ const value = options.strict;
267
+ if (typeof value !== "boolean") {
268
+ throw new TypeError('The "strict" argument must be of type boolean');
269
+ }
270
+ if (value) {
271
+ return (value2) => {
272
+ let message = `Object can not safely be stringified. Received type ${typeof value2}`;
273
+ if (typeof value2 !== "function")
274
+ message += ` (${value2.toString()})`;
275
+ throw new Error(message);
276
+ };
277
+ }
278
+ }
279
+ }
280
+ function configure(options) {
281
+ options = { ...options };
282
+ const fail = getStrictOption(options);
283
+ if (fail) {
284
+ if (options.bigint === void 0) {
285
+ options.bigint = false;
286
+ }
287
+ if (!("circularValue" in options)) {
288
+ options.circularValue = Error;
289
+ }
290
+ }
291
+ const circularValue = getCircularValueOption(options);
292
+ const bigint = getBooleanOption(options, "bigint");
293
+ const deterministic = getBooleanOption(options, "deterministic");
294
+ const maximumDepth = getPositiveIntegerOption(options, "maximumDepth");
295
+ const maximumBreadth = getPositiveIntegerOption(options, "maximumBreadth");
296
+ function stringifyFnReplacer(key, parent, stack, replacer, spacer, indentation) {
297
+ let value = parent[key];
298
+ if (typeof value === "object" && value !== null && typeof value.toJSON === "function") {
299
+ value = value.toJSON(key);
300
+ }
301
+ value = replacer.call(parent, key, value);
302
+ switch (typeof value) {
303
+ case "string":
304
+ return strEscape(value);
305
+ case "object": {
306
+ if (value === null) {
307
+ return "null";
308
+ }
309
+ if (stack.indexOf(value) !== -1) {
310
+ return circularValue;
311
+ }
312
+ let res = "";
313
+ let join = ",";
314
+ const originalIndentation = indentation;
315
+ if (Array.isArray(value)) {
316
+ if (value.length === 0) {
317
+ return "[]";
318
+ }
319
+ if (maximumDepth < stack.length + 1) {
320
+ return '"[Array]"';
321
+ }
322
+ stack.push(value);
323
+ if (spacer !== "") {
324
+ indentation += spacer;
325
+ res += `
326
+ ${indentation}`;
327
+ join = `,
328
+ ${indentation}`;
329
+ }
330
+ const maximumValuesToStringify = Math.min(value.length, maximumBreadth);
331
+ let i = 0;
332
+ for (; i < maximumValuesToStringify - 1; i++) {
333
+ const tmp2 = stringifyFnReplacer(String(i), value, stack, replacer, spacer, indentation);
334
+ res += tmp2 !== void 0 ? tmp2 : "null";
335
+ res += join;
336
+ }
337
+ const tmp = stringifyFnReplacer(String(i), value, stack, replacer, spacer, indentation);
338
+ res += tmp !== void 0 ? tmp : "null";
339
+ if (value.length - 1 > maximumBreadth) {
340
+ const removedKeys = value.length - maximumBreadth - 1;
341
+ res += `${join}"... ${getItemCount(removedKeys)} not stringified"`;
342
+ }
343
+ if (spacer !== "") {
344
+ res += `
345
+ ${originalIndentation}`;
346
+ }
347
+ stack.pop();
348
+ return `[${res}]`;
349
+ }
350
+ let keys = Object.keys(value);
351
+ const keyLength = keys.length;
352
+ if (keyLength === 0) {
353
+ return "{}";
354
+ }
355
+ if (maximumDepth < stack.length + 1) {
356
+ return '"[Object]"';
357
+ }
358
+ let whitespace = "";
359
+ let separator = "";
360
+ if (spacer !== "") {
361
+ indentation += spacer;
362
+ join = `,
363
+ ${indentation}`;
364
+ whitespace = " ";
365
+ }
366
+ const maximumPropertiesToStringify = Math.min(keyLength, maximumBreadth);
367
+ if (deterministic && !isTypedArrayWithEntries(value)) {
368
+ keys = insertSort(keys);
369
+ }
370
+ stack.push(value);
371
+ for (let i = 0; i < maximumPropertiesToStringify; i++) {
372
+ const key2 = keys[i];
373
+ const tmp = stringifyFnReplacer(key2, value, stack, replacer, spacer, indentation);
374
+ if (tmp !== void 0) {
375
+ res += `${separator}${strEscape(key2)}:${whitespace}${tmp}`;
376
+ separator = join;
377
+ }
378
+ }
379
+ if (keyLength > maximumBreadth) {
380
+ const removedKeys = keyLength - maximumBreadth;
381
+ res += `${separator}"...":${whitespace}"${getItemCount(removedKeys)} not stringified"`;
382
+ separator = join;
383
+ }
384
+ if (spacer !== "" && separator.length > 1) {
385
+ res = `
386
+ ${indentation}${res}
387
+ ${originalIndentation}`;
388
+ }
389
+ stack.pop();
390
+ return `{${res}}`;
391
+ }
392
+ case "number":
393
+ return isFinite(value) ? String(value) : fail ? fail(value) : "null";
394
+ case "boolean":
395
+ return value === true ? "true" : "false";
396
+ case "undefined":
397
+ return void 0;
398
+ case "bigint":
399
+ if (bigint) {
400
+ return String(value);
401
+ }
402
+ default:
403
+ return fail ? fail(value) : void 0;
404
+ }
405
+ }
406
+ function stringifyArrayReplacer(key, value, stack, replacer, spacer, indentation) {
407
+ if (typeof value === "object" && value !== null && typeof value.toJSON === "function") {
408
+ value = value.toJSON(key);
409
+ }
410
+ switch (typeof value) {
411
+ case "string":
412
+ return strEscape(value);
413
+ case "object": {
414
+ if (value === null) {
415
+ return "null";
416
+ }
417
+ if (stack.indexOf(value) !== -1) {
418
+ return circularValue;
419
+ }
420
+ const originalIndentation = indentation;
421
+ let res = "";
422
+ let join = ",";
423
+ if (Array.isArray(value)) {
424
+ if (value.length === 0) {
425
+ return "[]";
426
+ }
427
+ if (maximumDepth < stack.length + 1) {
428
+ return '"[Array]"';
429
+ }
430
+ stack.push(value);
431
+ if (spacer !== "") {
432
+ indentation += spacer;
433
+ res += `
434
+ ${indentation}`;
435
+ join = `,
436
+ ${indentation}`;
437
+ }
438
+ const maximumValuesToStringify = Math.min(value.length, maximumBreadth);
439
+ let i = 0;
440
+ for (; i < maximumValuesToStringify - 1; i++) {
441
+ const tmp2 = stringifyArrayReplacer(String(i), value[i], stack, replacer, spacer, indentation);
442
+ res += tmp2 !== void 0 ? tmp2 : "null";
443
+ res += join;
444
+ }
445
+ const tmp = stringifyArrayReplacer(String(i), value[i], stack, replacer, spacer, indentation);
446
+ res += tmp !== void 0 ? tmp : "null";
447
+ if (value.length - 1 > maximumBreadth) {
448
+ const removedKeys = value.length - maximumBreadth - 1;
449
+ res += `${join}"... ${getItemCount(removedKeys)} not stringified"`;
450
+ }
451
+ if (spacer !== "") {
452
+ res += `
453
+ ${originalIndentation}`;
454
+ }
455
+ stack.pop();
456
+ return `[${res}]`;
457
+ }
458
+ stack.push(value);
459
+ let whitespace = "";
460
+ if (spacer !== "") {
461
+ indentation += spacer;
462
+ join = `,
463
+ ${indentation}`;
464
+ whitespace = " ";
465
+ }
466
+ let separator = "";
467
+ for (const key2 of replacer) {
468
+ const tmp = stringifyArrayReplacer(key2, value[key2], stack, replacer, spacer, indentation);
469
+ if (tmp !== void 0) {
470
+ res += `${separator}${strEscape(key2)}:${whitespace}${tmp}`;
471
+ separator = join;
472
+ }
473
+ }
474
+ if (spacer !== "" && separator.length > 1) {
475
+ res = `
476
+ ${indentation}${res}
477
+ ${originalIndentation}`;
478
+ }
479
+ stack.pop();
480
+ return `{${res}}`;
481
+ }
482
+ case "number":
483
+ return isFinite(value) ? String(value) : fail ? fail(value) : "null";
484
+ case "boolean":
485
+ return value === true ? "true" : "false";
486
+ case "undefined":
487
+ return void 0;
488
+ case "bigint":
489
+ if (bigint) {
490
+ return String(value);
491
+ }
492
+ default:
493
+ return fail ? fail(value) : void 0;
494
+ }
495
+ }
496
+ function stringifyIndent(key, value, stack, spacer, indentation) {
497
+ switch (typeof value) {
498
+ case "string":
499
+ return strEscape(value);
500
+ case "object": {
501
+ if (value === null) {
502
+ return "null";
503
+ }
504
+ if (typeof value.toJSON === "function") {
505
+ value = value.toJSON(key);
506
+ if (typeof value !== "object") {
507
+ return stringifyIndent(key, value, stack, spacer, indentation);
508
+ }
509
+ if (value === null) {
510
+ return "null";
511
+ }
512
+ }
513
+ if (stack.indexOf(value) !== -1) {
514
+ return circularValue;
515
+ }
516
+ const originalIndentation = indentation;
517
+ if (Array.isArray(value)) {
518
+ if (value.length === 0) {
519
+ return "[]";
520
+ }
521
+ if (maximumDepth < stack.length + 1) {
522
+ return '"[Array]"';
523
+ }
524
+ stack.push(value);
525
+ indentation += spacer;
526
+ let res2 = `
527
+ ${indentation}`;
528
+ const join2 = `,
529
+ ${indentation}`;
530
+ const maximumValuesToStringify = Math.min(value.length, maximumBreadth);
531
+ let i = 0;
532
+ for (; i < maximumValuesToStringify - 1; i++) {
533
+ const tmp2 = stringifyIndent(String(i), value[i], stack, spacer, indentation);
534
+ res2 += tmp2 !== void 0 ? tmp2 : "null";
535
+ res2 += join2;
536
+ }
537
+ const tmp = stringifyIndent(String(i), value[i], stack, spacer, indentation);
538
+ res2 += tmp !== void 0 ? tmp : "null";
539
+ if (value.length - 1 > maximumBreadth) {
540
+ const removedKeys = value.length - maximumBreadth - 1;
541
+ res2 += `${join2}"... ${getItemCount(removedKeys)} not stringified"`;
542
+ }
543
+ res2 += `
544
+ ${originalIndentation}`;
545
+ stack.pop();
546
+ return `[${res2}]`;
547
+ }
548
+ let keys = Object.keys(value);
549
+ const keyLength = keys.length;
550
+ if (keyLength === 0) {
551
+ return "{}";
552
+ }
553
+ if (maximumDepth < stack.length + 1) {
554
+ return '"[Object]"';
555
+ }
556
+ indentation += spacer;
557
+ const join = `,
558
+ ${indentation}`;
559
+ let res = "";
560
+ let separator = "";
561
+ let maximumPropertiesToStringify = Math.min(keyLength, maximumBreadth);
562
+ if (isTypedArrayWithEntries(value)) {
563
+ res += stringifyTypedArray(value, join, maximumBreadth);
564
+ keys = keys.slice(value.length);
565
+ maximumPropertiesToStringify -= value.length;
566
+ separator = join;
567
+ }
568
+ if (deterministic) {
569
+ keys = insertSort(keys);
570
+ }
571
+ stack.push(value);
572
+ for (let i = 0; i < maximumPropertiesToStringify; i++) {
573
+ const key2 = keys[i];
574
+ const tmp = stringifyIndent(key2, value[key2], stack, spacer, indentation);
575
+ if (tmp !== void 0) {
576
+ res += `${separator}${strEscape(key2)}: ${tmp}`;
577
+ separator = join;
578
+ }
579
+ }
580
+ if (keyLength > maximumBreadth) {
581
+ const removedKeys = keyLength - maximumBreadth;
582
+ res += `${separator}"...": "${getItemCount(removedKeys)} not stringified"`;
583
+ separator = join;
584
+ }
585
+ if (separator !== "") {
586
+ res = `
587
+ ${indentation}${res}
588
+ ${originalIndentation}`;
589
+ }
590
+ stack.pop();
591
+ return `{${res}}`;
592
+ }
593
+ case "number":
594
+ return isFinite(value) ? String(value) : fail ? fail(value) : "null";
595
+ case "boolean":
596
+ return value === true ? "true" : "false";
597
+ case "undefined":
598
+ return void 0;
599
+ case "bigint":
600
+ if (bigint) {
601
+ return String(value);
602
+ }
603
+ default:
604
+ return fail ? fail(value) : void 0;
605
+ }
606
+ }
607
+ function stringifySimple(key, value, stack) {
608
+ switch (typeof value) {
609
+ case "string":
610
+ return strEscape(value);
611
+ case "object": {
612
+ if (value === null) {
613
+ return "null";
614
+ }
615
+ if (typeof value.toJSON === "function") {
616
+ value = value.toJSON(key);
617
+ if (typeof value !== "object") {
618
+ return stringifySimple(key, value, stack);
619
+ }
620
+ if (value === null) {
621
+ return "null";
622
+ }
623
+ }
624
+ if (stack.indexOf(value) !== -1) {
625
+ return circularValue;
626
+ }
627
+ let res = "";
628
+ if (Array.isArray(value)) {
629
+ if (value.length === 0) {
630
+ return "[]";
631
+ }
632
+ if (maximumDepth < stack.length + 1) {
633
+ return '"[Array]"';
634
+ }
635
+ stack.push(value);
636
+ const maximumValuesToStringify = Math.min(value.length, maximumBreadth);
637
+ let i = 0;
638
+ for (; i < maximumValuesToStringify - 1; i++) {
639
+ const tmp2 = stringifySimple(String(i), value[i], stack);
640
+ res += tmp2 !== void 0 ? tmp2 : "null";
641
+ res += ",";
642
+ }
643
+ const tmp = stringifySimple(String(i), value[i], stack);
644
+ res += tmp !== void 0 ? tmp : "null";
645
+ if (value.length - 1 > maximumBreadth) {
646
+ const removedKeys = value.length - maximumBreadth - 1;
647
+ res += `,"... ${getItemCount(removedKeys)} not stringified"`;
648
+ }
649
+ stack.pop();
650
+ return `[${res}]`;
651
+ }
652
+ let keys = Object.keys(value);
653
+ const keyLength = keys.length;
654
+ if (keyLength === 0) {
655
+ return "{}";
656
+ }
657
+ if (maximumDepth < stack.length + 1) {
658
+ return '"[Object]"';
659
+ }
660
+ let separator = "";
661
+ let maximumPropertiesToStringify = Math.min(keyLength, maximumBreadth);
662
+ if (isTypedArrayWithEntries(value)) {
663
+ res += stringifyTypedArray(value, ",", maximumBreadth);
664
+ keys = keys.slice(value.length);
665
+ maximumPropertiesToStringify -= value.length;
666
+ separator = ",";
667
+ }
668
+ if (deterministic) {
669
+ keys = insertSort(keys);
670
+ }
671
+ stack.push(value);
672
+ for (let i = 0; i < maximumPropertiesToStringify; i++) {
673
+ const key2 = keys[i];
674
+ const tmp = stringifySimple(key2, value[key2], stack);
675
+ if (tmp !== void 0) {
676
+ res += `${separator}${strEscape(key2)}:${tmp}`;
677
+ separator = ",";
678
+ }
679
+ }
680
+ if (keyLength > maximumBreadth) {
681
+ const removedKeys = keyLength - maximumBreadth;
682
+ res += `${separator}"...":"${getItemCount(removedKeys)} not stringified"`;
683
+ }
684
+ stack.pop();
685
+ return `{${res}}`;
686
+ }
687
+ case "number":
688
+ return isFinite(value) ? String(value) : fail ? fail(value) : "null";
689
+ case "boolean":
690
+ return value === true ? "true" : "false";
691
+ case "undefined":
692
+ return void 0;
693
+ case "bigint":
694
+ if (bigint) {
695
+ return String(value);
696
+ }
697
+ default:
698
+ return fail ? fail(value) : void 0;
699
+ }
700
+ }
701
+ function stringify2(value, replacer, space) {
702
+ if (arguments.length > 1) {
703
+ let spacer = "";
704
+ if (typeof space === "number") {
705
+ spacer = " ".repeat(Math.min(space, 10));
706
+ } else if (typeof space === "string") {
707
+ spacer = space.slice(0, 10);
708
+ }
709
+ if (replacer != null) {
710
+ if (typeof replacer === "function") {
711
+ return stringifyFnReplacer("", { "": value }, [], replacer, spacer, "");
712
+ }
713
+ if (Array.isArray(replacer)) {
714
+ return stringifyArrayReplacer("", value, [], getUniqueReplacerSet(replacer), spacer, "");
715
+ }
716
+ }
717
+ if (spacer.length !== 0) {
718
+ return stringifyIndent("", value, [], spacer, "");
719
+ }
720
+ }
721
+ return stringifySimple("", value, []);
722
+ }
723
+ return stringify2;
724
+ }
725
+ })(safeStableStringify, safeStableStringify.exports);
726
+ var safeStableStringifyExports = safeStableStringify.exports;
727
+ const cjsModule = /* @__PURE__ */ getDefaultExportFromCjs(safeStableStringifyExports);
728
+ cjsModule.configure;
729
+ function setNameOperation(document, name) {
730
+ return { ...document, name };
731
+ }
732
+ function undoOperation(document, action, skip) {
733
+ const { scope, input } = action;
734
+ const defaultResult = {
735
+ document,
736
+ action,
737
+ skip
738
+ };
739
+ return produce(defaultResult, (draft) => {
740
+ if (draft.document.operations[scope].length < 1) {
741
+ throw new Error(
742
+ `Cannot undo: no operations in history for scope "${scope}"`
743
+ );
744
+ }
745
+ if (input < 1) {
746
+ throw new Error(
747
+ `Invalid UNDO action: input value must be greater than 0`
748
+ );
749
+ }
750
+ if (draft.skip > 0) {
751
+ throw new Error(
752
+ `Cannot undo: skip value from reducer cannot be used with UNDO action`
753
+ );
754
+ }
755
+ const lastOperation = draft.document.operations[scope].at(-1);
756
+ const isLatestOpNOOP = lastOperation && lastOperation.type === "NOOP" && lastOperation.skip > 0;
757
+ draft.skip += input;
758
+ if (isLatestOpNOOP) {
759
+ draft.skip += lastOperation.skip;
760
+ const preLastOperation = draft.document.operations[scope][draft.document.operations[scope].length - 2];
761
+ if (preLastOperation && lastOperation.index - preLastOperation.index === 1) {
762
+ draft.document.operations[scope].pop();
763
+ }
764
+ }
765
+ if (draft.document.operations[scope].length < draft.skip) {
766
+ throw new Error(
767
+ `Cannot undo: you can't undo more operations than the ones in the scope history`
768
+ );
769
+ }
770
+ const operationsLastIndex = draft.document.operations[scope].length - 1;
771
+ let skippedOpsLeft = input;
772
+ let index = isLatestOpNOOP ? operationsLastIndex - lastOperation.skip : operationsLastIndex;
773
+ while (skippedOpsLeft > 0 && index >= 0) {
774
+ const op = draft.document.operations[scope][index];
775
+ if (!op) {
776
+ skippedOpsLeft--;
777
+ index--;
778
+ continue;
779
+ }
780
+ if (op.type === "NOOP" && op.skip > 0) {
781
+ index = index - (op.skip + 1);
782
+ draft.skip += op.skip + 1;
783
+ } else {
784
+ draft.document.clipboard.push({ ...op });
785
+ skippedOpsLeft--;
786
+ index--;
787
+ }
788
+ }
789
+ draft.action = noop(scope);
790
+ });
791
+ }
792
+ function redoOperation(document, action, skip) {
793
+ const { scope, input } = action;
794
+ const defaultResult = {
795
+ document,
796
+ action,
797
+ skip
798
+ };
799
+ return produce(defaultResult, (draft) => {
800
+ if (draft.skip > 0) {
801
+ throw new Error(
802
+ `Cannot redo: skip value from reducer cannot be used with REDO action`
803
+ );
804
+ }
805
+ if (input > 1) {
806
+ throw new Error(
807
+ `Cannot redo: you can only redo one operation at a time`
808
+ );
809
+ }
810
+ if (input < 1) {
811
+ throw new Error(`Invalid REDO action: invalid redo input value`);
812
+ }
813
+ if (draft.document.clipboard.length < 1) {
814
+ throw new Error(`Cannot redo: no operations in the clipboard`);
815
+ }
816
+ const operationIndex = draft.document.clipboard.findLastIndex(
817
+ (op) => op.scope === scope
818
+ );
819
+ if (operationIndex < 0) {
820
+ throw new Error(
821
+ `Cannot redo: no operations in clipboard for scope "${scope}"`
822
+ );
823
+ }
824
+ const operation = draft.document.clipboard.splice(operationIndex, 1)[0];
825
+ draft.action = castDraft({
826
+ type: operation.type,
827
+ scope: operation.scope,
828
+ input: operation.input
829
+ });
830
+ });
831
+ }
832
+ function pruneOperation(document, action, wrappedReducer) {
833
+ const { scope } = action;
834
+ const operations = document.operations[scope];
835
+ let {
836
+ input: { start, end }
837
+ } = action;
838
+ start = start || 0;
839
+ end = end || operations.length;
840
+ const actionsToPrune = operations.slice(start, end);
841
+ const actionsToKeepStart = operations.slice(0, start);
842
+ const actionsToKeepEnd = operations.slice(end);
843
+ const newDocument = replayOperations(
844
+ document.initialState,
845
+ {
846
+ ...document.operations,
847
+ [scope]: actionsToKeepStart.concat(actionsToPrune)
848
+ },
849
+ wrappedReducer
850
+ );
851
+ const { name, state: newState } = newDocument;
852
+ const loadStateIndex = actionsToKeepStart.length;
853
+ const loadStateTimestamp = actionsToKeepStart.length ? actionsToKeepStart[actionsToKeepStart.length - 1].timestamp : actionsToKeepEnd.length ? actionsToKeepEnd[0].timestamp : (/* @__PURE__ */ new Date()).toISOString();
854
+ return replayOperations(
855
+ document.initialState,
856
+ {
857
+ ...document.operations,
858
+ [scope]: [
859
+ ...actionsToKeepStart,
860
+ {
861
+ ...loadState(
862
+ { name, state: newState },
863
+ actionsToPrune.length
864
+ ),
865
+ timestamp: loadStateTimestamp,
866
+ index: loadStateIndex,
867
+ hash: hashDocument({ state: newState }, "global")
868
+ },
869
+ ...actionsToKeepEnd.map((action2, index) => ({
870
+ ...action2,
871
+ index: loadStateIndex + index + 1
872
+ }))
873
+ ]
874
+ },
875
+ wrappedReducer
876
+ );
877
+ }
878
+ function loadStateOperation(oldDocument, newDocument) {
879
+ return {
880
+ ...oldDocument,
881
+ name: newDocument.name,
882
+ state: newDocument.state ?? { global: {}, local: {} }
883
+ };
884
+ }
885
+ const SET_NAME = "SET_NAME";
886
+ const UNDO = "UNDO";
887
+ const REDO = "REDO";
888
+ const PRUNE = "PRUNE";
889
+ const LOAD_STATE = "LOAD_STATE";
890
+ const NOOP = "NOOP";
891
+ const types = { "application/andrew-inset": ["ez"], "application/appinstaller": ["appinstaller"], "application/applixware": ["aw"], "application/appx": ["appx"], "application/appxbundle": ["appxbundle"], "application/atom+xml": ["atom"], "application/atomcat+xml": ["atomcat"], "application/atomdeleted+xml": ["atomdeleted"], "application/atomsvc+xml": ["atomsvc"], "application/atsc-dwd+xml": ["dwd"], "application/atsc-held+xml": ["held"], "application/atsc-rsat+xml": ["rsat"], "application/automationml-aml+xml": ["aml"], "application/automationml-amlx+zip": ["amlx"], "application/bdoc": ["bdoc"], "application/calendar+xml": ["xcs"], "application/ccxml+xml": ["ccxml"], "application/cdfx+xml": ["cdfx"], "application/cdmi-capability": ["cdmia"], "application/cdmi-container": ["cdmic"], "application/cdmi-domain": ["cdmid"], "application/cdmi-object": ["cdmio"], "application/cdmi-queue": ["cdmiq"], "application/cpl+xml": ["cpl"], "application/cu-seeme": ["cu"], "application/cwl": ["cwl"], "application/dash+xml": ["mpd"], "application/dash-patch+xml": ["mpp"], "application/davmount+xml": ["davmount"], "application/docbook+xml": ["dbk"], "application/dssc+der": ["dssc"], "application/dssc+xml": ["xdssc"], "application/ecmascript": ["ecma"], "application/emma+xml": ["emma"], "application/emotionml+xml": ["emotionml"], "application/epub+zip": ["epub"], "application/exi": ["exi"], "application/express": ["exp"], "application/fdf": ["fdf"], "application/fdt+xml": ["fdt"], "application/font-tdpfr": ["pfr"], "application/geo+json": ["geojson"], "application/gml+xml": ["gml"], "application/gpx+xml": ["gpx"], "application/gxf": ["gxf"], "application/gzip": ["gz"], "application/hjson": ["hjson"], "application/hyperstudio": ["stk"], "application/inkml+xml": ["ink", "inkml"], "application/ipfix": ["ipfix"], "application/its+xml": ["its"], "application/java-archive": ["jar", "war", "ear"], "application/java-serialized-object": ["ser"], "application/java-vm": ["class"], "application/javascript": ["*js"], "application/json": ["json", "map"], "application/json5": ["json5"], "application/jsonml+json": ["jsonml"], "application/ld+json": ["jsonld"], "application/lgr+xml": ["lgr"], "application/lost+xml": ["lostxml"], "application/mac-binhex40": ["hqx"], "application/mac-compactpro": ["cpt"], "application/mads+xml": ["mads"], "application/manifest+json": ["webmanifest"], "application/marc": ["mrc"], "application/marcxml+xml": ["mrcx"], "application/mathematica": ["ma", "nb", "mb"], "application/mathml+xml": ["mathml"], "application/mbox": ["mbox"], "application/media-policy-dataset+xml": ["mpf"], "application/mediaservercontrol+xml": ["mscml"], "application/metalink+xml": ["metalink"], "application/metalink4+xml": ["meta4"], "application/mets+xml": ["mets"], "application/mmt-aei+xml": ["maei"], "application/mmt-usd+xml": ["musd"], "application/mods+xml": ["mods"], "application/mp21": ["m21", "mp21"], "application/mp4": ["*mp4", "*mpg4", "mp4s", "m4p"], "application/msix": ["msix"], "application/msixbundle": ["msixbundle"], "application/msword": ["doc", "dot"], "application/mxf": ["mxf"], "application/n-quads": ["nq"], "application/n-triples": ["nt"], "application/node": ["cjs"], "application/octet-stream": ["bin", "dms", "lrf", "mar", "so", "dist", "distz", "pkg", "bpk", "dump", "elc", "deploy", "exe", "dll", "deb", "dmg", "iso", "img", "msi", "msp", "msm", "buffer"], "application/oda": ["oda"], "application/oebps-package+xml": ["opf"], "application/ogg": ["ogx"], "application/omdoc+xml": ["omdoc"], "application/onenote": ["onetoc", "onetoc2", "onetmp", "onepkg"], "application/oxps": ["oxps"], "application/p2p-overlay+xml": ["relo"], "application/patch-ops-error+xml": ["xer"], "application/pdf": ["pdf"], "application/pgp-encrypted": ["pgp"], "application/pgp-keys": ["asc"], "application/pgp-signature": ["sig", "*asc"], "application/pics-rules": ["prf"], "application/pkcs10": ["p10"], "application/pkcs7-mime": ["p7m", "p7c"], "application/pkcs7-signature": ["p7s"], "application/pkcs8": ["p8"], "application/pkix-attr-cert": ["ac"], "application/pkix-cert": ["cer"], "application/pkix-crl": ["crl"], "application/pkix-pkipath": ["pkipath"], "application/pkixcmp": ["pki"], "application/pls+xml": ["pls"], "application/postscript": ["ai", "eps", "ps"], "application/provenance+xml": ["provx"], "application/pskc+xml": ["pskcxml"], "application/raml+yaml": ["raml"], "application/rdf+xml": ["rdf", "owl"], "application/reginfo+xml": ["rif"], "application/relax-ng-compact-syntax": ["rnc"], "application/resource-lists+xml": ["rl"], "application/resource-lists-diff+xml": ["rld"], "application/rls-services+xml": ["rs"], "application/route-apd+xml": ["rapd"], "application/route-s-tsid+xml": ["sls"], "application/route-usd+xml": ["rusd"], "application/rpki-ghostbusters": ["gbr"], "application/rpki-manifest": ["mft"], "application/rpki-roa": ["roa"], "application/rsd+xml": ["rsd"], "application/rss+xml": ["rss"], "application/rtf": ["rtf"], "application/sbml+xml": ["sbml"], "application/scvp-cv-request": ["scq"], "application/scvp-cv-response": ["scs"], "application/scvp-vp-request": ["spq"], "application/scvp-vp-response": ["spp"], "application/sdp": ["sdp"], "application/senml+xml": ["senmlx"], "application/sensml+xml": ["sensmlx"], "application/set-payment-initiation": ["setpay"], "application/set-registration-initiation": ["setreg"], "application/shf+xml": ["shf"], "application/sieve": ["siv", "sieve"], "application/smil+xml": ["smi", "smil"], "application/sparql-query": ["rq"], "application/sparql-results+xml": ["srx"], "application/sql": ["sql"], "application/srgs": ["gram"], "application/srgs+xml": ["grxml"], "application/sru+xml": ["sru"], "application/ssdl+xml": ["ssdl"], "application/ssml+xml": ["ssml"], "application/swid+xml": ["swidtag"], "application/tei+xml": ["tei", "teicorpus"], "application/thraud+xml": ["tfi"], "application/timestamped-data": ["tsd"], "application/toml": ["toml"], "application/trig": ["trig"], "application/ttml+xml": ["ttml"], "application/ubjson": ["ubj"], "application/urc-ressheet+xml": ["rsheet"], "application/urc-targetdesc+xml": ["td"], "application/voicexml+xml": ["vxml"], "application/wasm": ["wasm"], "application/watcherinfo+xml": ["wif"], "application/widget": ["wgt"], "application/winhlp": ["hlp"], "application/wsdl+xml": ["wsdl"], "application/wspolicy+xml": ["wspolicy"], "application/xaml+xml": ["xaml"], "application/xcap-att+xml": ["xav"], "application/xcap-caps+xml": ["xca"], "application/xcap-diff+xml": ["xdf"], "application/xcap-el+xml": ["xel"], "application/xcap-ns+xml": ["xns"], "application/xenc+xml": ["xenc"], "application/xfdf": ["xfdf"], "application/xhtml+xml": ["xhtml", "xht"], "application/xliff+xml": ["xlf"], "application/xml": ["xml", "xsl", "xsd", "rng"], "application/xml-dtd": ["dtd"], "application/xop+xml": ["xop"], "application/xproc+xml": ["xpl"], "application/xslt+xml": ["*xsl", "xslt"], "application/xspf+xml": ["xspf"], "application/xv+xml": ["mxml", "xhvml", "xvml", "xvm"], "application/yang": ["yang"], "application/yin+xml": ["yin"], "application/zip": ["zip"], "audio/3gpp": ["*3gpp"], "audio/aac": ["adts", "aac"], "audio/adpcm": ["adp"], "audio/amr": ["amr"], "audio/basic": ["au", "snd"], "audio/midi": ["mid", "midi", "kar", "rmi"], "audio/mobile-xmf": ["mxmf"], "audio/mp3": ["*mp3"], "audio/mp4": ["m4a", "mp4a"], "audio/mpeg": ["mpga", "mp2", "mp2a", "mp3", "m2a", "m3a"], "audio/ogg": ["oga", "ogg", "spx", "opus"], "audio/s3m": ["s3m"], "audio/silk": ["sil"], "audio/wav": ["wav"], "audio/wave": ["*wav"], "audio/webm": ["weba"], "audio/xm": ["xm"], "font/collection": ["ttc"], "font/otf": ["otf"], "font/ttf": ["ttf"], "font/woff": ["woff"], "font/woff2": ["woff2"], "image/aces": ["exr"], "image/apng": ["apng"], "image/avci": ["avci"], "image/avcs": ["avcs"], "image/avif": ["avif"], "image/bmp": ["bmp", "dib"], "image/cgm": ["cgm"], "image/dicom-rle": ["drle"], "image/dpx": ["dpx"], "image/emf": ["emf"], "image/fits": ["fits"], "image/g3fax": ["g3"], "image/gif": ["gif"], "image/heic": ["heic"], "image/heic-sequence": ["heics"], "image/heif": ["heif"], "image/heif-sequence": ["heifs"], "image/hej2k": ["hej2"], "image/hsj2": ["hsj2"], "image/ief": ["ief"], "image/jls": ["jls"], "image/jp2": ["jp2", "jpg2"], "image/jpeg": ["jpeg", "jpg", "jpe"], "image/jph": ["jph"], "image/jphc": ["jhc"], "image/jpm": ["jpm", "jpgm"], "image/jpx": ["jpx", "jpf"], "image/jxr": ["jxr"], "image/jxra": ["jxra"], "image/jxrs": ["jxrs"], "image/jxs": ["jxs"], "image/jxsc": ["jxsc"], "image/jxsi": ["jxsi"], "image/jxss": ["jxss"], "image/ktx": ["ktx"], "image/ktx2": ["ktx2"], "image/png": ["png"], "image/sgi": ["sgi"], "image/svg+xml": ["svg", "svgz"], "image/t38": ["t38"], "image/tiff": ["tif", "tiff"], "image/tiff-fx": ["tfx"], "image/webp": ["webp"], "image/wmf": ["wmf"], "message/disposition-notification": ["disposition-notification"], "message/global": ["u8msg"], "message/global-delivery-status": ["u8dsn"], "message/global-disposition-notification": ["u8mdn"], "message/global-headers": ["u8hdr"], "message/rfc822": ["eml", "mime"], "model/3mf": ["3mf"], "model/gltf+json": ["gltf"], "model/gltf-binary": ["glb"], "model/iges": ["igs", "iges"], "model/jt": ["jt"], "model/mesh": ["msh", "mesh", "silo"], "model/mtl": ["mtl"], "model/obj": ["obj"], "model/prc": ["prc"], "model/step+xml": ["stpx"], "model/step+zip": ["stpz"], "model/step-xml+zip": ["stpxz"], "model/stl": ["stl"], "model/u3d": ["u3d"], "model/vrml": ["wrl", "vrml"], "model/x3d+binary": ["*x3db", "x3dbz"], "model/x3d+fastinfoset": ["x3db"], "model/x3d+vrml": ["*x3dv", "x3dvz"], "model/x3d+xml": ["x3d", "x3dz"], "model/x3d-vrml": ["x3dv"], "text/cache-manifest": ["appcache", "manifest"], "text/calendar": ["ics", "ifb"], "text/coffeescript": ["coffee", "litcoffee"], "text/css": ["css"], "text/csv": ["csv"], "text/html": ["html", "htm", "shtml"], "text/jade": ["jade"], "text/javascript": ["js", "mjs"], "text/jsx": ["jsx"], "text/less": ["less"], "text/markdown": ["md", "markdown"], "text/mathml": ["mml"], "text/mdx": ["mdx"], "text/n3": ["n3"], "text/plain": ["txt", "text", "conf", "def", "list", "log", "in", "ini"], "text/richtext": ["rtx"], "text/rtf": ["*rtf"], "text/sgml": ["sgml", "sgm"], "text/shex": ["shex"], "text/slim": ["slim", "slm"], "text/spdx": ["spdx"], "text/stylus": ["stylus", "styl"], "text/tab-separated-values": ["tsv"], "text/troff": ["t", "tr", "roff", "man", "me", "ms"], "text/turtle": ["ttl"], "text/uri-list": ["uri", "uris", "urls"], "text/vcard": ["vcard"], "text/vtt": ["vtt"], "text/wgsl": ["wgsl"], "text/xml": ["*xml"], "text/yaml": ["yaml", "yml"], "video/3gpp": ["3gp", "3gpp"], "video/3gpp2": ["3g2"], "video/h261": ["h261"], "video/h263": ["h263"], "video/h264": ["h264"], "video/iso.segment": ["m4s"], "video/jpeg": ["jpgv"], "video/jpm": ["*jpm", "*jpgm"], "video/mj2": ["mj2", "mjp2"], "video/mp2t": ["ts"], "video/mp4": ["mp4", "mp4v", "mpg4"], "video/mpeg": ["mpeg", "mpg", "mpe", "m1v", "m2v"], "video/ogg": ["ogv"], "video/quicktime": ["qt", "mov"], "video/webm": ["webm"] };
892
+ Object.freeze(types);
893
+ var __classPrivateFieldGet = function(receiver, state, kind, f) {
894
+ if (kind === "a" && !f)
895
+ throw new TypeError("Private accessor was defined without a getter");
896
+ if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver))
897
+ throw new TypeError("Cannot read private member from an object whose class did not declare it");
898
+ return kind === "m" ? f : kind === "a" ? f.call(receiver) : f ? f.value : state.get(receiver);
899
+ };
900
+ var _Mime_extensionToType, _Mime_typeToExtension, _Mime_typeToExtensions;
901
+ class Mime {
902
+ constructor(...args) {
903
+ _Mime_extensionToType.set(this, /* @__PURE__ */ new Map());
904
+ _Mime_typeToExtension.set(this, /* @__PURE__ */ new Map());
905
+ _Mime_typeToExtensions.set(this, /* @__PURE__ */ new Map());
906
+ for (const arg of args) {
907
+ this.define(arg);
908
+ }
909
+ }
910
+ define(typeMap, force = false) {
911
+ for (let [type, extensions] of Object.entries(typeMap)) {
912
+ type = type.toLowerCase();
913
+ extensions = extensions.map((ext) => ext.toLowerCase());
914
+ if (!__classPrivateFieldGet(this, _Mime_typeToExtensions, "f").has(type)) {
915
+ __classPrivateFieldGet(this, _Mime_typeToExtensions, "f").set(type, /* @__PURE__ */ new Set());
916
+ }
917
+ const allExtensions = __classPrivateFieldGet(this, _Mime_typeToExtensions, "f").get(type);
918
+ let first = true;
919
+ for (let extension of extensions) {
920
+ const starred = extension.startsWith("*");
921
+ extension = starred ? extension.slice(1) : extension;
922
+ allExtensions == null ? void 0 : allExtensions.add(extension);
923
+ if (first) {
924
+ __classPrivateFieldGet(this, _Mime_typeToExtension, "f").set(type, extension);
925
+ }
926
+ first = false;
927
+ if (starred)
928
+ continue;
929
+ const currentType = __classPrivateFieldGet(this, _Mime_extensionToType, "f").get(extension);
930
+ if (currentType && currentType != type && !force) {
931
+ throw new Error(`"${type} -> ${extension}" conflicts with "${currentType} -> ${extension}". Pass \`force=true\` to override this definition.`);
932
+ }
933
+ __classPrivateFieldGet(this, _Mime_extensionToType, "f").set(extension, type);
934
+ }
935
+ }
936
+ return this;
937
+ }
938
+ getType(path) {
939
+ if (typeof path !== "string")
940
+ return null;
941
+ const last = path.replace(/^.*[/\\]/, "").toLowerCase();
942
+ const ext = last.replace(/^.*\./, "").toLowerCase();
943
+ const hasPath = last.length < path.length;
944
+ const hasDot = ext.length < last.length - 1;
945
+ if (!hasDot && hasPath)
946
+ return null;
947
+ return __classPrivateFieldGet(this, _Mime_extensionToType, "f").get(ext) ?? null;
948
+ }
949
+ getExtension(type) {
950
+ var _a;
951
+ if (typeof type !== "string")
952
+ return null;
953
+ type = (_a = type == null ? void 0 : type.split) == null ? void 0 : _a.call(type, ";")[0];
954
+ return (type && __classPrivateFieldGet(this, _Mime_typeToExtension, "f").get(type.trim().toLowerCase())) ?? null;
955
+ }
956
+ getAllExtensions(type) {
957
+ if (typeof type !== "string")
958
+ return null;
959
+ return __classPrivateFieldGet(this, _Mime_typeToExtensions, "f").get(type.toLowerCase()) ?? null;
960
+ }
961
+ _freeze() {
962
+ this.define = () => {
963
+ throw new Error("define() not allowed for built-in Mime objects. See https://github.com/broofa/mime/blob/main/README.md#custom-mime-instances");
964
+ };
965
+ Object.freeze(this);
966
+ for (const extensions of __classPrivateFieldGet(this, _Mime_typeToExtensions, "f").values()) {
967
+ Object.freeze(extensions);
968
+ }
969
+ return this;
970
+ }
971
+ _getTestState() {
972
+ return {
973
+ types: __classPrivateFieldGet(this, _Mime_extensionToType, "f"),
974
+ extensions: __classPrivateFieldGet(this, _Mime_typeToExtension, "f")
975
+ };
976
+ }
977
+ }
978
+ _Mime_extensionToType = /* @__PURE__ */ new WeakMap(), _Mime_typeToExtension = /* @__PURE__ */ new WeakMap(), _Mime_typeToExtensions = /* @__PURE__ */ new WeakMap();
979
+ const mime = new Mime(types)._freeze();
980
+ var inherits_browser = { exports: {} };
981
+ if (typeof Object.create === "function") {
982
+ inherits_browser.exports = function inherits2(ctor, superCtor) {
983
+ if (superCtor) {
984
+ ctor.super_ = superCtor;
985
+ ctor.prototype = Object.create(superCtor.prototype, {
986
+ constructor: {
987
+ value: ctor,
988
+ enumerable: false,
989
+ writable: true,
990
+ configurable: true
991
+ }
992
+ });
993
+ }
994
+ };
995
+ } else {
996
+ inherits_browser.exports = function inherits2(ctor, superCtor) {
997
+ if (superCtor) {
998
+ ctor.super_ = superCtor;
999
+ var TempCtor = function() {
1000
+ };
1001
+ TempCtor.prototype = superCtor.prototype;
1002
+ ctor.prototype = new TempCtor();
1003
+ ctor.prototype.constructor = ctor;
1004
+ }
1005
+ };
1006
+ }
1007
+ var inherits_browserExports = inherits_browser.exports;
1008
+ var safeBuffer = { exports: {} };
1009
+ var buffer = {};
1010
+ var base64Js = {};
1011
+ base64Js.byteLength = byteLength;
1012
+ base64Js.toByteArray = toByteArray;
1013
+ base64Js.fromByteArray = fromByteArray;
1014
+ var lookup = [];
1015
+ var revLookup = [];
1016
+ var Arr = typeof Uint8Array !== "undefined" ? Uint8Array : Array;
1017
+ var code = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
1018
+ for (var i = 0, len = code.length; i < len; ++i) {
1019
+ lookup[i] = code[i];
1020
+ revLookup[code.charCodeAt(i)] = i;
1021
+ }
1022
+ revLookup["-".charCodeAt(0)] = 62;
1023
+ revLookup["_".charCodeAt(0)] = 63;
1024
+ function getLens(b64) {
1025
+ var len = b64.length;
1026
+ if (len % 4 > 0) {
1027
+ throw new Error("Invalid string. Length must be a multiple of 4");
1028
+ }
1029
+ var validLen = b64.indexOf("=");
1030
+ if (validLen === -1)
1031
+ validLen = len;
1032
+ var placeHoldersLen = validLen === len ? 0 : 4 - validLen % 4;
1033
+ return [validLen, placeHoldersLen];
1034
+ }
1035
+ function byteLength(b64) {
1036
+ var lens = getLens(b64);
1037
+ var validLen = lens[0];
1038
+ var placeHoldersLen = lens[1];
1039
+ return (validLen + placeHoldersLen) * 3 / 4 - placeHoldersLen;
1040
+ }
1041
+ function _byteLength(b64, validLen, placeHoldersLen) {
1042
+ return (validLen + placeHoldersLen) * 3 / 4 - placeHoldersLen;
1043
+ }
1044
+ function toByteArray(b64) {
1045
+ var tmp;
1046
+ var lens = getLens(b64);
1047
+ var validLen = lens[0];
1048
+ var placeHoldersLen = lens[1];
1049
+ var arr = new Arr(_byteLength(b64, validLen, placeHoldersLen));
1050
+ var curByte = 0;
1051
+ var len = placeHoldersLen > 0 ? validLen - 4 : validLen;
1052
+ var i;
1053
+ for (i = 0; i < len; i += 4) {
1054
+ tmp = revLookup[b64.charCodeAt(i)] << 18 | revLookup[b64.charCodeAt(i + 1)] << 12 | revLookup[b64.charCodeAt(i + 2)] << 6 | revLookup[b64.charCodeAt(i + 3)];
1055
+ arr[curByte++] = tmp >> 16 & 255;
1056
+ arr[curByte++] = tmp >> 8 & 255;
1057
+ arr[curByte++] = tmp & 255;
1058
+ }
1059
+ if (placeHoldersLen === 2) {
1060
+ tmp = revLookup[b64.charCodeAt(i)] << 2 | revLookup[b64.charCodeAt(i + 1)] >> 4;
1061
+ arr[curByte++] = tmp & 255;
1062
+ }
1063
+ if (placeHoldersLen === 1) {
1064
+ tmp = revLookup[b64.charCodeAt(i)] << 10 | revLookup[b64.charCodeAt(i + 1)] << 4 | revLookup[b64.charCodeAt(i + 2)] >> 2;
1065
+ arr[curByte++] = tmp >> 8 & 255;
1066
+ arr[curByte++] = tmp & 255;
1067
+ }
1068
+ return arr;
1069
+ }
1070
+ function tripletToBase64(num) {
1071
+ return lookup[num >> 18 & 63] + lookup[num >> 12 & 63] + lookup[num >> 6 & 63] + lookup[num & 63];
1072
+ }
1073
+ function encodeChunk(uint8, start, end) {
1074
+ var tmp;
1075
+ var output = [];
1076
+ for (var i = start; i < end; i += 3) {
1077
+ tmp = (uint8[i] << 16 & 16711680) + (uint8[i + 1] << 8 & 65280) + (uint8[i + 2] & 255);
1078
+ output.push(tripletToBase64(tmp));
1079
+ }
1080
+ return output.join("");
1081
+ }
1082
+ function fromByteArray(uint8) {
1083
+ var tmp;
1084
+ var len = uint8.length;
1085
+ var extraBytes = len % 3;
1086
+ var parts = [];
1087
+ var maxChunkLength = 16383;
1088
+ for (var i = 0, len2 = len - extraBytes; i < len2; i += maxChunkLength) {
1089
+ parts.push(encodeChunk(uint8, i, i + maxChunkLength > len2 ? len2 : i + maxChunkLength));
1090
+ }
1091
+ if (extraBytes === 1) {
1092
+ tmp = uint8[len - 1];
1093
+ parts.push(
1094
+ lookup[tmp >> 2] + lookup[tmp << 4 & 63] + "=="
1095
+ );
1096
+ } else if (extraBytes === 2) {
1097
+ tmp = (uint8[len - 2] << 8) + uint8[len - 1];
1098
+ parts.push(
1099
+ lookup[tmp >> 10] + lookup[tmp >> 4 & 63] + lookup[tmp << 2 & 63] + "="
1100
+ );
1101
+ }
1102
+ return parts.join("");
1103
+ }
1104
+ var ieee754 = {};
1105
+ /*! ieee754. BSD-3-Clause License. Feross Aboukhadijeh <https://feross.org/opensource> */
1106
+ ieee754.read = function(buffer2, offset, isLE, mLen, nBytes) {
1107
+ var e, m;
1108
+ var eLen = nBytes * 8 - mLen - 1;
1109
+ var eMax = (1 << eLen) - 1;
1110
+ var eBias = eMax >> 1;
1111
+ var nBits = -7;
1112
+ var i = isLE ? nBytes - 1 : 0;
1113
+ var d = isLE ? -1 : 1;
1114
+ var s = buffer2[offset + i];
1115
+ i += d;
1116
+ e = s & (1 << -nBits) - 1;
1117
+ s >>= -nBits;
1118
+ nBits += eLen;
1119
+ for (; nBits > 0; e = e * 256 + buffer2[offset + i], i += d, nBits -= 8) {
1120
+ }
1121
+ m = e & (1 << -nBits) - 1;
1122
+ e >>= -nBits;
1123
+ nBits += mLen;
1124
+ for (; nBits > 0; m = m * 256 + buffer2[offset + i], i += d, nBits -= 8) {
1125
+ }
1126
+ if (e === 0) {
1127
+ e = 1 - eBias;
1128
+ } else if (e === eMax) {
1129
+ return m ? NaN : (s ? -1 : 1) * Infinity;
1130
+ } else {
1131
+ m = m + Math.pow(2, mLen);
1132
+ e = e - eBias;
1133
+ }
1134
+ return (s ? -1 : 1) * m * Math.pow(2, e - mLen);
1135
+ };
1136
+ ieee754.write = function(buffer2, value, offset, isLE, mLen, nBytes) {
1137
+ var e, m, c;
1138
+ var eLen = nBytes * 8 - mLen - 1;
1139
+ var eMax = (1 << eLen) - 1;
1140
+ var eBias = eMax >> 1;
1141
+ var rt = mLen === 23 ? Math.pow(2, -24) - Math.pow(2, -77) : 0;
1142
+ var i = isLE ? 0 : nBytes - 1;
1143
+ var d = isLE ? 1 : -1;
1144
+ var s = value < 0 || value === 0 && 1 / value < 0 ? 1 : 0;
1145
+ value = Math.abs(value);
1146
+ if (isNaN(value) || value === Infinity) {
1147
+ m = isNaN(value) ? 1 : 0;
1148
+ e = eMax;
1149
+ } else {
1150
+ e = Math.floor(Math.log(value) / Math.LN2);
1151
+ if (value * (c = Math.pow(2, -e)) < 1) {
1152
+ e--;
1153
+ c *= 2;
1154
+ }
1155
+ if (e + eBias >= 1) {
1156
+ value += rt / c;
1157
+ } else {
1158
+ value += rt * Math.pow(2, 1 - eBias);
1159
+ }
1160
+ if (value * c >= 2) {
1161
+ e++;
1162
+ c /= 2;
1163
+ }
1164
+ if (e + eBias >= eMax) {
1165
+ m = 0;
1166
+ e = eMax;
1167
+ } else if (e + eBias >= 1) {
1168
+ m = (value * c - 1) * Math.pow(2, mLen);
1169
+ e = e + eBias;
1170
+ } else {
1171
+ m = value * Math.pow(2, eBias - 1) * Math.pow(2, mLen);
1172
+ e = 0;
1173
+ }
1174
+ }
1175
+ for (; mLen >= 8; buffer2[offset + i] = m & 255, i += d, m /= 256, mLen -= 8) {
1176
+ }
1177
+ e = e << mLen | m;
1178
+ eLen += mLen;
1179
+ for (; eLen > 0; buffer2[offset + i] = e & 255, i += d, e /= 256, eLen -= 8) {
1180
+ }
1181
+ buffer2[offset + i - d] |= s * 128;
1182
+ };
1183
+ /*!
1184
+ * The buffer module from node.js, for the browser.
1185
+ *
1186
+ * @author Feross Aboukhadijeh <https://feross.org>
1187
+ * @license MIT
1188
+ */
1189
+ (function(exports) {
1190
+ var base64 = base64Js;
1191
+ var ieee754$1 = ieee754;
1192
+ var customInspectSymbol = typeof Symbol === "function" && typeof Symbol["for"] === "function" ? Symbol["for"]("nodejs.util.inspect.custom") : null;
1193
+ exports.Buffer = Buffer3;
1194
+ exports.SlowBuffer = SlowBuffer;
1195
+ exports.INSPECT_MAX_BYTES = 50;
1196
+ var K_MAX_LENGTH = 2147483647;
1197
+ exports.kMaxLength = K_MAX_LENGTH;
1198
+ Buffer3.TYPED_ARRAY_SUPPORT = typedArraySupport();
1199
+ if (!Buffer3.TYPED_ARRAY_SUPPORT && typeof console !== "undefined" && typeof console.error === "function") {
1200
+ console.error(
1201
+ "This browser lacks typed array (Uint8Array) support which is required by `buffer` v5.x. Use `buffer` v4.x if you require old browser support."
1202
+ );
1203
+ }
1204
+ function typedArraySupport() {
1205
+ try {
1206
+ var arr = new Uint8Array(1);
1207
+ var proto = { foo: function() {
1208
+ return 42;
1209
+ } };
1210
+ Object.setPrototypeOf(proto, Uint8Array.prototype);
1211
+ Object.setPrototypeOf(arr, proto);
1212
+ return arr.foo() === 42;
1213
+ } catch (e) {
1214
+ return false;
1215
+ }
1216
+ }
1217
+ Object.defineProperty(Buffer3.prototype, "parent", {
1218
+ enumerable: true,
1219
+ get: function() {
1220
+ if (!Buffer3.isBuffer(this))
1221
+ return void 0;
1222
+ return this.buffer;
1223
+ }
1224
+ });
1225
+ Object.defineProperty(Buffer3.prototype, "offset", {
1226
+ enumerable: true,
1227
+ get: function() {
1228
+ if (!Buffer3.isBuffer(this))
1229
+ return void 0;
1230
+ return this.byteOffset;
1231
+ }
1232
+ });
1233
+ function createBuffer(length) {
1234
+ if (length > K_MAX_LENGTH) {
1235
+ throw new RangeError('The value "' + length + '" is invalid for option "size"');
1236
+ }
1237
+ var buf = new Uint8Array(length);
1238
+ Object.setPrototypeOf(buf, Buffer3.prototype);
1239
+ return buf;
1240
+ }
1241
+ function Buffer3(arg, encodingOrOffset, length) {
1242
+ if (typeof arg === "number") {
1243
+ if (typeof encodingOrOffset === "string") {
1244
+ throw new TypeError(
1245
+ 'The "string" argument must be of type string. Received type number'
1246
+ );
1247
+ }
1248
+ return allocUnsafe(arg);
1249
+ }
1250
+ return from(arg, encodingOrOffset, length);
1251
+ }
1252
+ Buffer3.poolSize = 8192;
1253
+ function from(value, encodingOrOffset, length) {
1254
+ if (typeof value === "string") {
1255
+ return fromString(value, encodingOrOffset);
1256
+ }
1257
+ if (ArrayBuffer.isView(value)) {
1258
+ return fromArrayView(value);
1259
+ }
1260
+ if (value == null) {
1261
+ throw new TypeError(
1262
+ "The first argument must be one of type string, Buffer, ArrayBuffer, Array, or Array-like Object. Received type " + typeof value
1263
+ );
1264
+ }
1265
+ if (isInstance(value, ArrayBuffer) || value && isInstance(value.buffer, ArrayBuffer)) {
1266
+ return fromArrayBuffer(value, encodingOrOffset, length);
1267
+ }
1268
+ if (typeof SharedArrayBuffer !== "undefined" && (isInstance(value, SharedArrayBuffer) || value && isInstance(value.buffer, SharedArrayBuffer))) {
1269
+ return fromArrayBuffer(value, encodingOrOffset, length);
1270
+ }
1271
+ if (typeof value === "number") {
1272
+ throw new TypeError(
1273
+ 'The "value" argument must not be of type number. Received type number'
1274
+ );
1275
+ }
1276
+ var valueOf = value.valueOf && value.valueOf();
1277
+ if (valueOf != null && valueOf !== value) {
1278
+ return Buffer3.from(valueOf, encodingOrOffset, length);
1279
+ }
1280
+ var b = fromObject(value);
1281
+ if (b)
1282
+ return b;
1283
+ if (typeof Symbol !== "undefined" && Symbol.toPrimitive != null && typeof value[Symbol.toPrimitive] === "function") {
1284
+ return Buffer3.from(
1285
+ value[Symbol.toPrimitive]("string"),
1286
+ encodingOrOffset,
1287
+ length
1288
+ );
1289
+ }
1290
+ throw new TypeError(
1291
+ "The first argument must be one of type string, Buffer, ArrayBuffer, Array, or Array-like Object. Received type " + typeof value
1292
+ );
1293
+ }
1294
+ Buffer3.from = function(value, encodingOrOffset, length) {
1295
+ return from(value, encodingOrOffset, length);
1296
+ };
1297
+ Object.setPrototypeOf(Buffer3.prototype, Uint8Array.prototype);
1298
+ Object.setPrototypeOf(Buffer3, Uint8Array);
1299
+ function assertSize(size) {
1300
+ if (typeof size !== "number") {
1301
+ throw new TypeError('"size" argument must be of type number');
1302
+ } else if (size < 0) {
1303
+ throw new RangeError('The value "' + size + '" is invalid for option "size"');
1304
+ }
1305
+ }
1306
+ function alloc(size, fill, encoding) {
1307
+ assertSize(size);
1308
+ if (size <= 0) {
1309
+ return createBuffer(size);
1310
+ }
1311
+ if (fill !== void 0) {
1312
+ return typeof encoding === "string" ? createBuffer(size).fill(fill, encoding) : createBuffer(size).fill(fill);
1313
+ }
1314
+ return createBuffer(size);
1315
+ }
1316
+ Buffer3.alloc = function(size, fill, encoding) {
1317
+ return alloc(size, fill, encoding);
1318
+ };
1319
+ function allocUnsafe(size) {
1320
+ assertSize(size);
1321
+ return createBuffer(size < 0 ? 0 : checked(size) | 0);
1322
+ }
1323
+ Buffer3.allocUnsafe = function(size) {
1324
+ return allocUnsafe(size);
1325
+ };
1326
+ Buffer3.allocUnsafeSlow = function(size) {
1327
+ return allocUnsafe(size);
1328
+ };
1329
+ function fromString(string, encoding) {
1330
+ if (typeof encoding !== "string" || encoding === "") {
1331
+ encoding = "utf8";
1332
+ }
1333
+ if (!Buffer3.isEncoding(encoding)) {
1334
+ throw new TypeError("Unknown encoding: " + encoding);
1335
+ }
1336
+ var length = byteLength2(string, encoding) | 0;
1337
+ var buf = createBuffer(length);
1338
+ var actual = buf.write(string, encoding);
1339
+ if (actual !== length) {
1340
+ buf = buf.slice(0, actual);
1341
+ }
1342
+ return buf;
1343
+ }
1344
+ function fromArrayLike(array) {
1345
+ var length = array.length < 0 ? 0 : checked(array.length) | 0;
1346
+ var buf = createBuffer(length);
1347
+ for (var i = 0; i < length; i += 1) {
1348
+ buf[i] = array[i] & 255;
1349
+ }
1350
+ return buf;
1351
+ }
1352
+ function fromArrayView(arrayView) {
1353
+ if (isInstance(arrayView, Uint8Array)) {
1354
+ var copy = new Uint8Array(arrayView);
1355
+ return fromArrayBuffer(copy.buffer, copy.byteOffset, copy.byteLength);
1356
+ }
1357
+ return fromArrayLike(arrayView);
1358
+ }
1359
+ function fromArrayBuffer(array, byteOffset, length) {
1360
+ if (byteOffset < 0 || array.byteLength < byteOffset) {
1361
+ throw new RangeError('"offset" is outside of buffer bounds');
1362
+ }
1363
+ if (array.byteLength < byteOffset + (length || 0)) {
1364
+ throw new RangeError('"length" is outside of buffer bounds');
1365
+ }
1366
+ var buf;
1367
+ if (byteOffset === void 0 && length === void 0) {
1368
+ buf = new Uint8Array(array);
1369
+ } else if (length === void 0) {
1370
+ buf = new Uint8Array(array, byteOffset);
1371
+ } else {
1372
+ buf = new Uint8Array(array, byteOffset, length);
1373
+ }
1374
+ Object.setPrototypeOf(buf, Buffer3.prototype);
1375
+ return buf;
1376
+ }
1377
+ function fromObject(obj) {
1378
+ if (Buffer3.isBuffer(obj)) {
1379
+ var len = checked(obj.length) | 0;
1380
+ var buf = createBuffer(len);
1381
+ if (buf.length === 0) {
1382
+ return buf;
1383
+ }
1384
+ obj.copy(buf, 0, 0, len);
1385
+ return buf;
1386
+ }
1387
+ if (obj.length !== void 0) {
1388
+ if (typeof obj.length !== "number" || numberIsNaN(obj.length)) {
1389
+ return createBuffer(0);
1390
+ }
1391
+ return fromArrayLike(obj);
1392
+ }
1393
+ if (obj.type === "Buffer" && Array.isArray(obj.data)) {
1394
+ return fromArrayLike(obj.data);
1395
+ }
1396
+ }
1397
+ function checked(length) {
1398
+ if (length >= K_MAX_LENGTH) {
1399
+ throw new RangeError("Attempt to allocate Buffer larger than maximum size: 0x" + K_MAX_LENGTH.toString(16) + " bytes");
1400
+ }
1401
+ return length | 0;
1402
+ }
1403
+ function SlowBuffer(length) {
1404
+ if (+length != length) {
1405
+ length = 0;
1406
+ }
1407
+ return Buffer3.alloc(+length);
1408
+ }
1409
+ Buffer3.isBuffer = function isBuffer(b) {
1410
+ return b != null && b._isBuffer === true && b !== Buffer3.prototype;
1411
+ };
1412
+ Buffer3.compare = function compare(a, b) {
1413
+ if (isInstance(a, Uint8Array))
1414
+ a = Buffer3.from(a, a.offset, a.byteLength);
1415
+ if (isInstance(b, Uint8Array))
1416
+ b = Buffer3.from(b, b.offset, b.byteLength);
1417
+ if (!Buffer3.isBuffer(a) || !Buffer3.isBuffer(b)) {
1418
+ throw new TypeError(
1419
+ 'The "buf1", "buf2" arguments must be one of type Buffer or Uint8Array'
1420
+ );
1421
+ }
1422
+ if (a === b)
1423
+ return 0;
1424
+ var x = a.length;
1425
+ var y = b.length;
1426
+ for (var i = 0, len = Math.min(x, y); i < len; ++i) {
1427
+ if (a[i] !== b[i]) {
1428
+ x = a[i];
1429
+ y = b[i];
1430
+ break;
1431
+ }
1432
+ }
1433
+ if (x < y)
1434
+ return -1;
1435
+ if (y < x)
1436
+ return 1;
1437
+ return 0;
1438
+ };
1439
+ Buffer3.isEncoding = function isEncoding(encoding) {
1440
+ switch (String(encoding).toLowerCase()) {
1441
+ case "hex":
1442
+ case "utf8":
1443
+ case "utf-8":
1444
+ case "ascii":
1445
+ case "latin1":
1446
+ case "binary":
1447
+ case "base64":
1448
+ case "ucs2":
1449
+ case "ucs-2":
1450
+ case "utf16le":
1451
+ case "utf-16le":
1452
+ return true;
1453
+ default:
1454
+ return false;
1455
+ }
1456
+ };
1457
+ Buffer3.concat = function concat(list, length) {
1458
+ if (!Array.isArray(list)) {
1459
+ throw new TypeError('"list" argument must be an Array of Buffers');
1460
+ }
1461
+ if (list.length === 0) {
1462
+ return Buffer3.alloc(0);
1463
+ }
1464
+ var i;
1465
+ if (length === void 0) {
1466
+ length = 0;
1467
+ for (i = 0; i < list.length; ++i) {
1468
+ length += list[i].length;
1469
+ }
1470
+ }
1471
+ var buffer2 = Buffer3.allocUnsafe(length);
1472
+ var pos = 0;
1473
+ for (i = 0; i < list.length; ++i) {
1474
+ var buf = list[i];
1475
+ if (isInstance(buf, Uint8Array)) {
1476
+ if (pos + buf.length > buffer2.length) {
1477
+ Buffer3.from(buf).copy(buffer2, pos);
1478
+ } else {
1479
+ Uint8Array.prototype.set.call(
1480
+ buffer2,
1481
+ buf,
1482
+ pos
1483
+ );
1484
+ }
1485
+ } else if (!Buffer3.isBuffer(buf)) {
1486
+ throw new TypeError('"list" argument must be an Array of Buffers');
1487
+ } else {
1488
+ buf.copy(buffer2, pos);
1489
+ }
1490
+ pos += buf.length;
1491
+ }
1492
+ return buffer2;
1493
+ };
1494
+ function byteLength2(string, encoding) {
1495
+ if (Buffer3.isBuffer(string)) {
1496
+ return string.length;
1497
+ }
1498
+ if (ArrayBuffer.isView(string) || isInstance(string, ArrayBuffer)) {
1499
+ return string.byteLength;
1500
+ }
1501
+ if (typeof string !== "string") {
1502
+ throw new TypeError(
1503
+ 'The "string" argument must be one of type string, Buffer, or ArrayBuffer. Received type ' + typeof string
1504
+ );
1505
+ }
1506
+ var len = string.length;
1507
+ var mustMatch = arguments.length > 2 && arguments[2] === true;
1508
+ if (!mustMatch && len === 0)
1509
+ return 0;
1510
+ var loweredCase = false;
1511
+ for (; ; ) {
1512
+ switch (encoding) {
1513
+ case "ascii":
1514
+ case "latin1":
1515
+ case "binary":
1516
+ return len;
1517
+ case "utf8":
1518
+ case "utf-8":
1519
+ return utf8ToBytes(string).length;
1520
+ case "ucs2":
1521
+ case "ucs-2":
1522
+ case "utf16le":
1523
+ case "utf-16le":
1524
+ return len * 2;
1525
+ case "hex":
1526
+ return len >>> 1;
1527
+ case "base64":
1528
+ return base64ToBytes(string).length;
1529
+ default:
1530
+ if (loweredCase) {
1531
+ return mustMatch ? -1 : utf8ToBytes(string).length;
1532
+ }
1533
+ encoding = ("" + encoding).toLowerCase();
1534
+ loweredCase = true;
1535
+ }
1536
+ }
1537
+ }
1538
+ Buffer3.byteLength = byteLength2;
1539
+ function slowToString(encoding, start, end) {
1540
+ var loweredCase = false;
1541
+ if (start === void 0 || start < 0) {
1542
+ start = 0;
1543
+ }
1544
+ if (start > this.length) {
1545
+ return "";
1546
+ }
1547
+ if (end === void 0 || end > this.length) {
1548
+ end = this.length;
1549
+ }
1550
+ if (end <= 0) {
1551
+ return "";
1552
+ }
1553
+ end >>>= 0;
1554
+ start >>>= 0;
1555
+ if (end <= start) {
1556
+ return "";
1557
+ }
1558
+ if (!encoding)
1559
+ encoding = "utf8";
1560
+ while (true) {
1561
+ switch (encoding) {
1562
+ case "hex":
1563
+ return hexSlice(this, start, end);
1564
+ case "utf8":
1565
+ case "utf-8":
1566
+ return utf8Slice(this, start, end);
1567
+ case "ascii":
1568
+ return asciiSlice(this, start, end);
1569
+ case "latin1":
1570
+ case "binary":
1571
+ return latin1Slice(this, start, end);
1572
+ case "base64":
1573
+ return base64Slice(this, start, end);
1574
+ case "ucs2":
1575
+ case "ucs-2":
1576
+ case "utf16le":
1577
+ case "utf-16le":
1578
+ return utf16leSlice(this, start, end);
1579
+ default:
1580
+ if (loweredCase)
1581
+ throw new TypeError("Unknown encoding: " + encoding);
1582
+ encoding = (encoding + "").toLowerCase();
1583
+ loweredCase = true;
1584
+ }
1585
+ }
1586
+ }
1587
+ Buffer3.prototype._isBuffer = true;
1588
+ function swap(b, n, m) {
1589
+ var i = b[n];
1590
+ b[n] = b[m];
1591
+ b[m] = i;
1592
+ }
1593
+ Buffer3.prototype.swap16 = function swap16() {
1594
+ var len = this.length;
1595
+ if (len % 2 !== 0) {
1596
+ throw new RangeError("Buffer size must be a multiple of 16-bits");
1597
+ }
1598
+ for (var i = 0; i < len; i += 2) {
1599
+ swap(this, i, i + 1);
1600
+ }
1601
+ return this;
1602
+ };
1603
+ Buffer3.prototype.swap32 = function swap32() {
1604
+ var len = this.length;
1605
+ if (len % 4 !== 0) {
1606
+ throw new RangeError("Buffer size must be a multiple of 32-bits");
1607
+ }
1608
+ for (var i = 0; i < len; i += 4) {
1609
+ swap(this, i, i + 3);
1610
+ swap(this, i + 1, i + 2);
1611
+ }
1612
+ return this;
1613
+ };
1614
+ Buffer3.prototype.swap64 = function swap64() {
1615
+ var len = this.length;
1616
+ if (len % 8 !== 0) {
1617
+ throw new RangeError("Buffer size must be a multiple of 64-bits");
1618
+ }
1619
+ for (var i = 0; i < len; i += 8) {
1620
+ swap(this, i, i + 7);
1621
+ swap(this, i + 1, i + 6);
1622
+ swap(this, i + 2, i + 5);
1623
+ swap(this, i + 3, i + 4);
1624
+ }
1625
+ return this;
1626
+ };
1627
+ Buffer3.prototype.toString = function toString() {
1628
+ var length = this.length;
1629
+ if (length === 0)
1630
+ return "";
1631
+ if (arguments.length === 0)
1632
+ return utf8Slice(this, 0, length);
1633
+ return slowToString.apply(this, arguments);
1634
+ };
1635
+ Buffer3.prototype.toLocaleString = Buffer3.prototype.toString;
1636
+ Buffer3.prototype.equals = function equals(b) {
1637
+ if (!Buffer3.isBuffer(b))
1638
+ throw new TypeError("Argument must be a Buffer");
1639
+ if (this === b)
1640
+ return true;
1641
+ return Buffer3.compare(this, b) === 0;
1642
+ };
1643
+ Buffer3.prototype.inspect = function inspect() {
1644
+ var str = "";
1645
+ var max = exports.INSPECT_MAX_BYTES;
1646
+ str = this.toString("hex", 0, max).replace(/(.{2})/g, "$1 ").trim();
1647
+ if (this.length > max)
1648
+ str += " ... ";
1649
+ return "<Buffer " + str + ">";
1650
+ };
1651
+ if (customInspectSymbol) {
1652
+ Buffer3.prototype[customInspectSymbol] = Buffer3.prototype.inspect;
1653
+ }
1654
+ Buffer3.prototype.compare = function compare(target, start, end, thisStart, thisEnd) {
1655
+ if (isInstance(target, Uint8Array)) {
1656
+ target = Buffer3.from(target, target.offset, target.byteLength);
1657
+ }
1658
+ if (!Buffer3.isBuffer(target)) {
1659
+ throw new TypeError(
1660
+ 'The "target" argument must be one of type Buffer or Uint8Array. Received type ' + typeof target
1661
+ );
1662
+ }
1663
+ if (start === void 0) {
1664
+ start = 0;
1665
+ }
1666
+ if (end === void 0) {
1667
+ end = target ? target.length : 0;
1668
+ }
1669
+ if (thisStart === void 0) {
1670
+ thisStart = 0;
1671
+ }
1672
+ if (thisEnd === void 0) {
1673
+ thisEnd = this.length;
1674
+ }
1675
+ if (start < 0 || end > target.length || thisStart < 0 || thisEnd > this.length) {
1676
+ throw new RangeError("out of range index");
1677
+ }
1678
+ if (thisStart >= thisEnd && start >= end) {
1679
+ return 0;
1680
+ }
1681
+ if (thisStart >= thisEnd) {
1682
+ return -1;
1683
+ }
1684
+ if (start >= end) {
1685
+ return 1;
1686
+ }
1687
+ start >>>= 0;
1688
+ end >>>= 0;
1689
+ thisStart >>>= 0;
1690
+ thisEnd >>>= 0;
1691
+ if (this === target)
1692
+ return 0;
1693
+ var x = thisEnd - thisStart;
1694
+ var y = end - start;
1695
+ var len = Math.min(x, y);
1696
+ var thisCopy = this.slice(thisStart, thisEnd);
1697
+ var targetCopy = target.slice(start, end);
1698
+ for (var i = 0; i < len; ++i) {
1699
+ if (thisCopy[i] !== targetCopy[i]) {
1700
+ x = thisCopy[i];
1701
+ y = targetCopy[i];
1702
+ break;
1703
+ }
1704
+ }
1705
+ if (x < y)
1706
+ return -1;
1707
+ if (y < x)
1708
+ return 1;
1709
+ return 0;
1710
+ };
1711
+ function bidirectionalIndexOf(buffer2, val, byteOffset, encoding, dir) {
1712
+ if (buffer2.length === 0)
1713
+ return -1;
1714
+ if (typeof byteOffset === "string") {
1715
+ encoding = byteOffset;
1716
+ byteOffset = 0;
1717
+ } else if (byteOffset > 2147483647) {
1718
+ byteOffset = 2147483647;
1719
+ } else if (byteOffset < -2147483648) {
1720
+ byteOffset = -2147483648;
1721
+ }
1722
+ byteOffset = +byteOffset;
1723
+ if (numberIsNaN(byteOffset)) {
1724
+ byteOffset = dir ? 0 : buffer2.length - 1;
1725
+ }
1726
+ if (byteOffset < 0)
1727
+ byteOffset = buffer2.length + byteOffset;
1728
+ if (byteOffset >= buffer2.length) {
1729
+ if (dir)
1730
+ return -1;
1731
+ else
1732
+ byteOffset = buffer2.length - 1;
1733
+ } else if (byteOffset < 0) {
1734
+ if (dir)
1735
+ byteOffset = 0;
1736
+ else
1737
+ return -1;
1738
+ }
1739
+ if (typeof val === "string") {
1740
+ val = Buffer3.from(val, encoding);
1741
+ }
1742
+ if (Buffer3.isBuffer(val)) {
1743
+ if (val.length === 0) {
1744
+ return -1;
1745
+ }
1746
+ return arrayIndexOf(buffer2, val, byteOffset, encoding, dir);
1747
+ } else if (typeof val === "number") {
1748
+ val = val & 255;
1749
+ if (typeof Uint8Array.prototype.indexOf === "function") {
1750
+ if (dir) {
1751
+ return Uint8Array.prototype.indexOf.call(buffer2, val, byteOffset);
1752
+ } else {
1753
+ return Uint8Array.prototype.lastIndexOf.call(buffer2, val, byteOffset);
1754
+ }
1755
+ }
1756
+ return arrayIndexOf(buffer2, [val], byteOffset, encoding, dir);
1757
+ }
1758
+ throw new TypeError("val must be string, number or Buffer");
1759
+ }
1760
+ function arrayIndexOf(arr, val, byteOffset, encoding, dir) {
1761
+ var indexSize = 1;
1762
+ var arrLength = arr.length;
1763
+ var valLength = val.length;
1764
+ if (encoding !== void 0) {
1765
+ encoding = String(encoding).toLowerCase();
1766
+ if (encoding === "ucs2" || encoding === "ucs-2" || encoding === "utf16le" || encoding === "utf-16le") {
1767
+ if (arr.length < 2 || val.length < 2) {
1768
+ return -1;
1769
+ }
1770
+ indexSize = 2;
1771
+ arrLength /= 2;
1772
+ valLength /= 2;
1773
+ byteOffset /= 2;
1774
+ }
1775
+ }
1776
+ function read(buf, i2) {
1777
+ if (indexSize === 1) {
1778
+ return buf[i2];
1779
+ } else {
1780
+ return buf.readUInt16BE(i2 * indexSize);
1781
+ }
1782
+ }
1783
+ var i;
1784
+ if (dir) {
1785
+ var foundIndex = -1;
1786
+ for (i = byteOffset; i < arrLength; i++) {
1787
+ if (read(arr, i) === read(val, foundIndex === -1 ? 0 : i - foundIndex)) {
1788
+ if (foundIndex === -1)
1789
+ foundIndex = i;
1790
+ if (i - foundIndex + 1 === valLength)
1791
+ return foundIndex * indexSize;
1792
+ } else {
1793
+ if (foundIndex !== -1)
1794
+ i -= i - foundIndex;
1795
+ foundIndex = -1;
1796
+ }
1797
+ }
1798
+ } else {
1799
+ if (byteOffset + valLength > arrLength)
1800
+ byteOffset = arrLength - valLength;
1801
+ for (i = byteOffset; i >= 0; i--) {
1802
+ var found = true;
1803
+ for (var j = 0; j < valLength; j++) {
1804
+ if (read(arr, i + j) !== read(val, j)) {
1805
+ found = false;
1806
+ break;
1807
+ }
1808
+ }
1809
+ if (found)
1810
+ return i;
1811
+ }
1812
+ }
1813
+ return -1;
1814
+ }
1815
+ Buffer3.prototype.includes = function includes(val, byteOffset, encoding) {
1816
+ return this.indexOf(val, byteOffset, encoding) !== -1;
1817
+ };
1818
+ Buffer3.prototype.indexOf = function indexOf(val, byteOffset, encoding) {
1819
+ return bidirectionalIndexOf(this, val, byteOffset, encoding, true);
1820
+ };
1821
+ Buffer3.prototype.lastIndexOf = function lastIndexOf(val, byteOffset, encoding) {
1822
+ return bidirectionalIndexOf(this, val, byteOffset, encoding, false);
1823
+ };
1824
+ function hexWrite(buf, string, offset, length) {
1825
+ offset = Number(offset) || 0;
1826
+ var remaining = buf.length - offset;
1827
+ if (!length) {
1828
+ length = remaining;
1829
+ } else {
1830
+ length = Number(length);
1831
+ if (length > remaining) {
1832
+ length = remaining;
1833
+ }
1834
+ }
1835
+ var strLen = string.length;
1836
+ if (length > strLen / 2) {
1837
+ length = strLen / 2;
1838
+ }
1839
+ for (var i = 0; i < length; ++i) {
1840
+ var parsed = parseInt(string.substr(i * 2, 2), 16);
1841
+ if (numberIsNaN(parsed))
1842
+ return i;
1843
+ buf[offset + i] = parsed;
1844
+ }
1845
+ return i;
1846
+ }
1847
+ function utf8Write(buf, string, offset, length) {
1848
+ return blitBuffer(utf8ToBytes(string, buf.length - offset), buf, offset, length);
1849
+ }
1850
+ function asciiWrite(buf, string, offset, length) {
1851
+ return blitBuffer(asciiToBytes(string), buf, offset, length);
1852
+ }
1853
+ function base64Write(buf, string, offset, length) {
1854
+ return blitBuffer(base64ToBytes(string), buf, offset, length);
1855
+ }
1856
+ function ucs2Write(buf, string, offset, length) {
1857
+ return blitBuffer(utf16leToBytes(string, buf.length - offset), buf, offset, length);
1858
+ }
1859
+ Buffer3.prototype.write = function write(string, offset, length, encoding) {
1860
+ if (offset === void 0) {
1861
+ encoding = "utf8";
1862
+ length = this.length;
1863
+ offset = 0;
1864
+ } else if (length === void 0 && typeof offset === "string") {
1865
+ encoding = offset;
1866
+ length = this.length;
1867
+ offset = 0;
1868
+ } else if (isFinite(offset)) {
1869
+ offset = offset >>> 0;
1870
+ if (isFinite(length)) {
1871
+ length = length >>> 0;
1872
+ if (encoding === void 0)
1873
+ encoding = "utf8";
1874
+ } else {
1875
+ encoding = length;
1876
+ length = void 0;
1877
+ }
1878
+ } else {
1879
+ throw new Error(
1880
+ "Buffer.write(string, encoding, offset[, length]) is no longer supported"
1881
+ );
1882
+ }
1883
+ var remaining = this.length - offset;
1884
+ if (length === void 0 || length > remaining)
1885
+ length = remaining;
1886
+ if (string.length > 0 && (length < 0 || offset < 0) || offset > this.length) {
1887
+ throw new RangeError("Attempt to write outside buffer bounds");
1888
+ }
1889
+ if (!encoding)
1890
+ encoding = "utf8";
1891
+ var loweredCase = false;
1892
+ for (; ; ) {
1893
+ switch (encoding) {
1894
+ case "hex":
1895
+ return hexWrite(this, string, offset, length);
1896
+ case "utf8":
1897
+ case "utf-8":
1898
+ return utf8Write(this, string, offset, length);
1899
+ case "ascii":
1900
+ case "latin1":
1901
+ case "binary":
1902
+ return asciiWrite(this, string, offset, length);
1903
+ case "base64":
1904
+ return base64Write(this, string, offset, length);
1905
+ case "ucs2":
1906
+ case "ucs-2":
1907
+ case "utf16le":
1908
+ case "utf-16le":
1909
+ return ucs2Write(this, string, offset, length);
1910
+ default:
1911
+ if (loweredCase)
1912
+ throw new TypeError("Unknown encoding: " + encoding);
1913
+ encoding = ("" + encoding).toLowerCase();
1914
+ loweredCase = true;
1915
+ }
1916
+ }
1917
+ };
1918
+ Buffer3.prototype.toJSON = function toJSON() {
1919
+ return {
1920
+ type: "Buffer",
1921
+ data: Array.prototype.slice.call(this._arr || this, 0)
1922
+ };
1923
+ };
1924
+ function base64Slice(buf, start, end) {
1925
+ if (start === 0 && end === buf.length) {
1926
+ return base64.fromByteArray(buf);
1927
+ } else {
1928
+ return base64.fromByteArray(buf.slice(start, end));
1929
+ }
1930
+ }
1931
+ function utf8Slice(buf, start, end) {
1932
+ end = Math.min(buf.length, end);
1933
+ var res = [];
1934
+ var i = start;
1935
+ while (i < end) {
1936
+ var firstByte = buf[i];
1937
+ var codePoint = null;
1938
+ var bytesPerSequence = firstByte > 239 ? 4 : firstByte > 223 ? 3 : firstByte > 191 ? 2 : 1;
1939
+ if (i + bytesPerSequence <= end) {
1940
+ var secondByte, thirdByte, fourthByte, tempCodePoint;
1941
+ switch (bytesPerSequence) {
1942
+ case 1:
1943
+ if (firstByte < 128) {
1944
+ codePoint = firstByte;
1945
+ }
1946
+ break;
1947
+ case 2:
1948
+ secondByte = buf[i + 1];
1949
+ if ((secondByte & 192) === 128) {
1950
+ tempCodePoint = (firstByte & 31) << 6 | secondByte & 63;
1951
+ if (tempCodePoint > 127) {
1952
+ codePoint = tempCodePoint;
1953
+ }
1954
+ }
1955
+ break;
1956
+ case 3:
1957
+ secondByte = buf[i + 1];
1958
+ thirdByte = buf[i + 2];
1959
+ if ((secondByte & 192) === 128 && (thirdByte & 192) === 128) {
1960
+ tempCodePoint = (firstByte & 15) << 12 | (secondByte & 63) << 6 | thirdByte & 63;
1961
+ if (tempCodePoint > 2047 && (tempCodePoint < 55296 || tempCodePoint > 57343)) {
1962
+ codePoint = tempCodePoint;
1963
+ }
1964
+ }
1965
+ break;
1966
+ case 4:
1967
+ secondByte = buf[i + 1];
1968
+ thirdByte = buf[i + 2];
1969
+ fourthByte = buf[i + 3];
1970
+ if ((secondByte & 192) === 128 && (thirdByte & 192) === 128 && (fourthByte & 192) === 128) {
1971
+ tempCodePoint = (firstByte & 15) << 18 | (secondByte & 63) << 12 | (thirdByte & 63) << 6 | fourthByte & 63;
1972
+ if (tempCodePoint > 65535 && tempCodePoint < 1114112) {
1973
+ codePoint = tempCodePoint;
1974
+ }
1975
+ }
1976
+ }
1977
+ }
1978
+ if (codePoint === null) {
1979
+ codePoint = 65533;
1980
+ bytesPerSequence = 1;
1981
+ } else if (codePoint > 65535) {
1982
+ codePoint -= 65536;
1983
+ res.push(codePoint >>> 10 & 1023 | 55296);
1984
+ codePoint = 56320 | codePoint & 1023;
1985
+ }
1986
+ res.push(codePoint);
1987
+ i += bytesPerSequence;
1988
+ }
1989
+ return decodeCodePointsArray(res);
1990
+ }
1991
+ var MAX_ARGUMENTS_LENGTH = 4096;
1992
+ function decodeCodePointsArray(codePoints) {
1993
+ var len = codePoints.length;
1994
+ if (len <= MAX_ARGUMENTS_LENGTH) {
1995
+ return String.fromCharCode.apply(String, codePoints);
1996
+ }
1997
+ var res = "";
1998
+ var i = 0;
1999
+ while (i < len) {
2000
+ res += String.fromCharCode.apply(
2001
+ String,
2002
+ codePoints.slice(i, i += MAX_ARGUMENTS_LENGTH)
2003
+ );
2004
+ }
2005
+ return res;
2006
+ }
2007
+ function asciiSlice(buf, start, end) {
2008
+ var ret = "";
2009
+ end = Math.min(buf.length, end);
2010
+ for (var i = start; i < end; ++i) {
2011
+ ret += String.fromCharCode(buf[i] & 127);
2012
+ }
2013
+ return ret;
2014
+ }
2015
+ function latin1Slice(buf, start, end) {
2016
+ var ret = "";
2017
+ end = Math.min(buf.length, end);
2018
+ for (var i = start; i < end; ++i) {
2019
+ ret += String.fromCharCode(buf[i]);
2020
+ }
2021
+ return ret;
2022
+ }
2023
+ function hexSlice(buf, start, end) {
2024
+ var len = buf.length;
2025
+ if (!start || start < 0)
2026
+ start = 0;
2027
+ if (!end || end < 0 || end > len)
2028
+ end = len;
2029
+ var out = "";
2030
+ for (var i = start; i < end; ++i) {
2031
+ out += hexSliceLookupTable[buf[i]];
2032
+ }
2033
+ return out;
2034
+ }
2035
+ function utf16leSlice(buf, start, end) {
2036
+ var bytes = buf.slice(start, end);
2037
+ var res = "";
2038
+ for (var i = 0; i < bytes.length - 1; i += 2) {
2039
+ res += String.fromCharCode(bytes[i] + bytes[i + 1] * 256);
2040
+ }
2041
+ return res;
2042
+ }
2043
+ Buffer3.prototype.slice = function slice(start, end) {
2044
+ var len = this.length;
2045
+ start = ~~start;
2046
+ end = end === void 0 ? len : ~~end;
2047
+ if (start < 0) {
2048
+ start += len;
2049
+ if (start < 0)
2050
+ start = 0;
2051
+ } else if (start > len) {
2052
+ start = len;
2053
+ }
2054
+ if (end < 0) {
2055
+ end += len;
2056
+ if (end < 0)
2057
+ end = 0;
2058
+ } else if (end > len) {
2059
+ end = len;
2060
+ }
2061
+ if (end < start)
2062
+ end = start;
2063
+ var newBuf = this.subarray(start, end);
2064
+ Object.setPrototypeOf(newBuf, Buffer3.prototype);
2065
+ return newBuf;
2066
+ };
2067
+ function checkOffset(offset, ext, length) {
2068
+ if (offset % 1 !== 0 || offset < 0)
2069
+ throw new RangeError("offset is not uint");
2070
+ if (offset + ext > length)
2071
+ throw new RangeError("Trying to access beyond buffer length");
2072
+ }
2073
+ Buffer3.prototype.readUintLE = Buffer3.prototype.readUIntLE = function readUIntLE(offset, byteLength3, noAssert) {
2074
+ offset = offset >>> 0;
2075
+ byteLength3 = byteLength3 >>> 0;
2076
+ if (!noAssert)
2077
+ checkOffset(offset, byteLength3, this.length);
2078
+ var val = this[offset];
2079
+ var mul = 1;
2080
+ var i = 0;
2081
+ while (++i < byteLength3 && (mul *= 256)) {
2082
+ val += this[offset + i] * mul;
2083
+ }
2084
+ return val;
2085
+ };
2086
+ Buffer3.prototype.readUintBE = Buffer3.prototype.readUIntBE = function readUIntBE(offset, byteLength3, noAssert) {
2087
+ offset = offset >>> 0;
2088
+ byteLength3 = byteLength3 >>> 0;
2089
+ if (!noAssert) {
2090
+ checkOffset(offset, byteLength3, this.length);
2091
+ }
2092
+ var val = this[offset + --byteLength3];
2093
+ var mul = 1;
2094
+ while (byteLength3 > 0 && (mul *= 256)) {
2095
+ val += this[offset + --byteLength3] * mul;
2096
+ }
2097
+ return val;
2098
+ };
2099
+ Buffer3.prototype.readUint8 = Buffer3.prototype.readUInt8 = function readUInt8(offset, noAssert) {
2100
+ offset = offset >>> 0;
2101
+ if (!noAssert)
2102
+ checkOffset(offset, 1, this.length);
2103
+ return this[offset];
2104
+ };
2105
+ Buffer3.prototype.readUint16LE = Buffer3.prototype.readUInt16LE = function readUInt16LE(offset, noAssert) {
2106
+ offset = offset >>> 0;
2107
+ if (!noAssert)
2108
+ checkOffset(offset, 2, this.length);
2109
+ return this[offset] | this[offset + 1] << 8;
2110
+ };
2111
+ Buffer3.prototype.readUint16BE = Buffer3.prototype.readUInt16BE = function readUInt16BE(offset, noAssert) {
2112
+ offset = offset >>> 0;
2113
+ if (!noAssert)
2114
+ checkOffset(offset, 2, this.length);
2115
+ return this[offset] << 8 | this[offset + 1];
2116
+ };
2117
+ Buffer3.prototype.readUint32LE = Buffer3.prototype.readUInt32LE = function readUInt32LE(offset, noAssert) {
2118
+ offset = offset >>> 0;
2119
+ if (!noAssert)
2120
+ checkOffset(offset, 4, this.length);
2121
+ return (this[offset] | this[offset + 1] << 8 | this[offset + 2] << 16) + this[offset + 3] * 16777216;
2122
+ };
2123
+ Buffer3.prototype.readUint32BE = Buffer3.prototype.readUInt32BE = function readUInt32BE(offset, noAssert) {
2124
+ offset = offset >>> 0;
2125
+ if (!noAssert)
2126
+ checkOffset(offset, 4, this.length);
2127
+ return this[offset] * 16777216 + (this[offset + 1] << 16 | this[offset + 2] << 8 | this[offset + 3]);
2128
+ };
2129
+ Buffer3.prototype.readIntLE = function readIntLE(offset, byteLength3, noAssert) {
2130
+ offset = offset >>> 0;
2131
+ byteLength3 = byteLength3 >>> 0;
2132
+ if (!noAssert)
2133
+ checkOffset(offset, byteLength3, this.length);
2134
+ var val = this[offset];
2135
+ var mul = 1;
2136
+ var i = 0;
2137
+ while (++i < byteLength3 && (mul *= 256)) {
2138
+ val += this[offset + i] * mul;
2139
+ }
2140
+ mul *= 128;
2141
+ if (val >= mul)
2142
+ val -= Math.pow(2, 8 * byteLength3);
2143
+ return val;
2144
+ };
2145
+ Buffer3.prototype.readIntBE = function readIntBE(offset, byteLength3, noAssert) {
2146
+ offset = offset >>> 0;
2147
+ byteLength3 = byteLength3 >>> 0;
2148
+ if (!noAssert)
2149
+ checkOffset(offset, byteLength3, this.length);
2150
+ var i = byteLength3;
2151
+ var mul = 1;
2152
+ var val = this[offset + --i];
2153
+ while (i > 0 && (mul *= 256)) {
2154
+ val += this[offset + --i] * mul;
2155
+ }
2156
+ mul *= 128;
2157
+ if (val >= mul)
2158
+ val -= Math.pow(2, 8 * byteLength3);
2159
+ return val;
2160
+ };
2161
+ Buffer3.prototype.readInt8 = function readInt8(offset, noAssert) {
2162
+ offset = offset >>> 0;
2163
+ if (!noAssert)
2164
+ checkOffset(offset, 1, this.length);
2165
+ if (!(this[offset] & 128))
2166
+ return this[offset];
2167
+ return (255 - this[offset] + 1) * -1;
2168
+ };
2169
+ Buffer3.prototype.readInt16LE = function readInt16LE(offset, noAssert) {
2170
+ offset = offset >>> 0;
2171
+ if (!noAssert)
2172
+ checkOffset(offset, 2, this.length);
2173
+ var val = this[offset] | this[offset + 1] << 8;
2174
+ return val & 32768 ? val | 4294901760 : val;
2175
+ };
2176
+ Buffer3.prototype.readInt16BE = function readInt16BE(offset, noAssert) {
2177
+ offset = offset >>> 0;
2178
+ if (!noAssert)
2179
+ checkOffset(offset, 2, this.length);
2180
+ var val = this[offset + 1] | this[offset] << 8;
2181
+ return val & 32768 ? val | 4294901760 : val;
2182
+ };
2183
+ Buffer3.prototype.readInt32LE = function readInt32LE(offset, noAssert) {
2184
+ offset = offset >>> 0;
2185
+ if (!noAssert)
2186
+ checkOffset(offset, 4, this.length);
2187
+ return this[offset] | this[offset + 1] << 8 | this[offset + 2] << 16 | this[offset + 3] << 24;
2188
+ };
2189
+ Buffer3.prototype.readInt32BE = function readInt32BE(offset, noAssert) {
2190
+ offset = offset >>> 0;
2191
+ if (!noAssert)
2192
+ checkOffset(offset, 4, this.length);
2193
+ return this[offset] << 24 | this[offset + 1] << 16 | this[offset + 2] << 8 | this[offset + 3];
2194
+ };
2195
+ Buffer3.prototype.readFloatLE = function readFloatLE(offset, noAssert) {
2196
+ offset = offset >>> 0;
2197
+ if (!noAssert)
2198
+ checkOffset(offset, 4, this.length);
2199
+ return ieee754$1.read(this, offset, true, 23, 4);
2200
+ };
2201
+ Buffer3.prototype.readFloatBE = function readFloatBE(offset, noAssert) {
2202
+ offset = offset >>> 0;
2203
+ if (!noAssert)
2204
+ checkOffset(offset, 4, this.length);
2205
+ return ieee754$1.read(this, offset, false, 23, 4);
2206
+ };
2207
+ Buffer3.prototype.readDoubleLE = function readDoubleLE(offset, noAssert) {
2208
+ offset = offset >>> 0;
2209
+ if (!noAssert)
2210
+ checkOffset(offset, 8, this.length);
2211
+ return ieee754$1.read(this, offset, true, 52, 8);
2212
+ };
2213
+ Buffer3.prototype.readDoubleBE = function readDoubleBE(offset, noAssert) {
2214
+ offset = offset >>> 0;
2215
+ if (!noAssert)
2216
+ checkOffset(offset, 8, this.length);
2217
+ return ieee754$1.read(this, offset, false, 52, 8);
2218
+ };
2219
+ function checkInt(buf, value, offset, ext, max, min) {
2220
+ if (!Buffer3.isBuffer(buf))
2221
+ throw new TypeError('"buffer" argument must be a Buffer instance');
2222
+ if (value > max || value < min)
2223
+ throw new RangeError('"value" argument is out of bounds');
2224
+ if (offset + ext > buf.length)
2225
+ throw new RangeError("Index out of range");
2226
+ }
2227
+ Buffer3.prototype.writeUintLE = Buffer3.prototype.writeUIntLE = function writeUIntLE(value, offset, byteLength3, noAssert) {
2228
+ value = +value;
2229
+ offset = offset >>> 0;
2230
+ byteLength3 = byteLength3 >>> 0;
2231
+ if (!noAssert) {
2232
+ var maxBytes = Math.pow(2, 8 * byteLength3) - 1;
2233
+ checkInt(this, value, offset, byteLength3, maxBytes, 0);
2234
+ }
2235
+ var mul = 1;
2236
+ var i = 0;
2237
+ this[offset] = value & 255;
2238
+ while (++i < byteLength3 && (mul *= 256)) {
2239
+ this[offset + i] = value / mul & 255;
2240
+ }
2241
+ return offset + byteLength3;
2242
+ };
2243
+ Buffer3.prototype.writeUintBE = Buffer3.prototype.writeUIntBE = function writeUIntBE(value, offset, byteLength3, noAssert) {
2244
+ value = +value;
2245
+ offset = offset >>> 0;
2246
+ byteLength3 = byteLength3 >>> 0;
2247
+ if (!noAssert) {
2248
+ var maxBytes = Math.pow(2, 8 * byteLength3) - 1;
2249
+ checkInt(this, value, offset, byteLength3, maxBytes, 0);
2250
+ }
2251
+ var i = byteLength3 - 1;
2252
+ var mul = 1;
2253
+ this[offset + i] = value & 255;
2254
+ while (--i >= 0 && (mul *= 256)) {
2255
+ this[offset + i] = value / mul & 255;
2256
+ }
2257
+ return offset + byteLength3;
2258
+ };
2259
+ Buffer3.prototype.writeUint8 = Buffer3.prototype.writeUInt8 = function writeUInt8(value, offset, noAssert) {
2260
+ value = +value;
2261
+ offset = offset >>> 0;
2262
+ if (!noAssert)
2263
+ checkInt(this, value, offset, 1, 255, 0);
2264
+ this[offset] = value & 255;
2265
+ return offset + 1;
2266
+ };
2267
+ Buffer3.prototype.writeUint16LE = Buffer3.prototype.writeUInt16LE = function writeUInt16LE(value, offset, noAssert) {
2268
+ value = +value;
2269
+ offset = offset >>> 0;
2270
+ if (!noAssert)
2271
+ checkInt(this, value, offset, 2, 65535, 0);
2272
+ this[offset] = value & 255;
2273
+ this[offset + 1] = value >>> 8;
2274
+ return offset + 2;
2275
+ };
2276
+ Buffer3.prototype.writeUint16BE = Buffer3.prototype.writeUInt16BE = function writeUInt16BE(value, offset, noAssert) {
2277
+ value = +value;
2278
+ offset = offset >>> 0;
2279
+ if (!noAssert)
2280
+ checkInt(this, value, offset, 2, 65535, 0);
2281
+ this[offset] = value >>> 8;
2282
+ this[offset + 1] = value & 255;
2283
+ return offset + 2;
2284
+ };
2285
+ Buffer3.prototype.writeUint32LE = Buffer3.prototype.writeUInt32LE = function writeUInt32LE(value, offset, noAssert) {
2286
+ value = +value;
2287
+ offset = offset >>> 0;
2288
+ if (!noAssert)
2289
+ checkInt(this, value, offset, 4, 4294967295, 0);
2290
+ this[offset + 3] = value >>> 24;
2291
+ this[offset + 2] = value >>> 16;
2292
+ this[offset + 1] = value >>> 8;
2293
+ this[offset] = value & 255;
2294
+ return offset + 4;
2295
+ };
2296
+ Buffer3.prototype.writeUint32BE = Buffer3.prototype.writeUInt32BE = function writeUInt32BE(value, offset, noAssert) {
2297
+ value = +value;
2298
+ offset = offset >>> 0;
2299
+ if (!noAssert)
2300
+ checkInt(this, value, offset, 4, 4294967295, 0);
2301
+ this[offset] = value >>> 24;
2302
+ this[offset + 1] = value >>> 16;
2303
+ this[offset + 2] = value >>> 8;
2304
+ this[offset + 3] = value & 255;
2305
+ return offset + 4;
2306
+ };
2307
+ Buffer3.prototype.writeIntLE = function writeIntLE(value, offset, byteLength3, noAssert) {
2308
+ value = +value;
2309
+ offset = offset >>> 0;
2310
+ if (!noAssert) {
2311
+ var limit = Math.pow(2, 8 * byteLength3 - 1);
2312
+ checkInt(this, value, offset, byteLength3, limit - 1, -limit);
2313
+ }
2314
+ var i = 0;
2315
+ var mul = 1;
2316
+ var sub = 0;
2317
+ this[offset] = value & 255;
2318
+ while (++i < byteLength3 && (mul *= 256)) {
2319
+ if (value < 0 && sub === 0 && this[offset + i - 1] !== 0) {
2320
+ sub = 1;
2321
+ }
2322
+ this[offset + i] = (value / mul >> 0) - sub & 255;
2323
+ }
2324
+ return offset + byteLength3;
2325
+ };
2326
+ Buffer3.prototype.writeIntBE = function writeIntBE(value, offset, byteLength3, noAssert) {
2327
+ value = +value;
2328
+ offset = offset >>> 0;
2329
+ if (!noAssert) {
2330
+ var limit = Math.pow(2, 8 * byteLength3 - 1);
2331
+ checkInt(this, value, offset, byteLength3, limit - 1, -limit);
2332
+ }
2333
+ var i = byteLength3 - 1;
2334
+ var mul = 1;
2335
+ var sub = 0;
2336
+ this[offset + i] = value & 255;
2337
+ while (--i >= 0 && (mul *= 256)) {
2338
+ if (value < 0 && sub === 0 && this[offset + i + 1] !== 0) {
2339
+ sub = 1;
2340
+ }
2341
+ this[offset + i] = (value / mul >> 0) - sub & 255;
2342
+ }
2343
+ return offset + byteLength3;
2344
+ };
2345
+ Buffer3.prototype.writeInt8 = function writeInt8(value, offset, noAssert) {
2346
+ value = +value;
2347
+ offset = offset >>> 0;
2348
+ if (!noAssert)
2349
+ checkInt(this, value, offset, 1, 127, -128);
2350
+ if (value < 0)
2351
+ value = 255 + value + 1;
2352
+ this[offset] = value & 255;
2353
+ return offset + 1;
2354
+ };
2355
+ Buffer3.prototype.writeInt16LE = function writeInt16LE(value, offset, noAssert) {
2356
+ value = +value;
2357
+ offset = offset >>> 0;
2358
+ if (!noAssert)
2359
+ checkInt(this, value, offset, 2, 32767, -32768);
2360
+ this[offset] = value & 255;
2361
+ this[offset + 1] = value >>> 8;
2362
+ return offset + 2;
2363
+ };
2364
+ Buffer3.prototype.writeInt16BE = function writeInt16BE(value, offset, noAssert) {
2365
+ value = +value;
2366
+ offset = offset >>> 0;
2367
+ if (!noAssert)
2368
+ checkInt(this, value, offset, 2, 32767, -32768);
2369
+ this[offset] = value >>> 8;
2370
+ this[offset + 1] = value & 255;
2371
+ return offset + 2;
2372
+ };
2373
+ Buffer3.prototype.writeInt32LE = function writeInt32LE(value, offset, noAssert) {
2374
+ value = +value;
2375
+ offset = offset >>> 0;
2376
+ if (!noAssert)
2377
+ checkInt(this, value, offset, 4, 2147483647, -2147483648);
2378
+ this[offset] = value & 255;
2379
+ this[offset + 1] = value >>> 8;
2380
+ this[offset + 2] = value >>> 16;
2381
+ this[offset + 3] = value >>> 24;
2382
+ return offset + 4;
2383
+ };
2384
+ Buffer3.prototype.writeInt32BE = function writeInt32BE(value, offset, noAssert) {
2385
+ value = +value;
2386
+ offset = offset >>> 0;
2387
+ if (!noAssert)
2388
+ checkInt(this, value, offset, 4, 2147483647, -2147483648);
2389
+ if (value < 0)
2390
+ value = 4294967295 + value + 1;
2391
+ this[offset] = value >>> 24;
2392
+ this[offset + 1] = value >>> 16;
2393
+ this[offset + 2] = value >>> 8;
2394
+ this[offset + 3] = value & 255;
2395
+ return offset + 4;
2396
+ };
2397
+ function checkIEEE754(buf, value, offset, ext, max, min) {
2398
+ if (offset + ext > buf.length)
2399
+ throw new RangeError("Index out of range");
2400
+ if (offset < 0)
2401
+ throw new RangeError("Index out of range");
2402
+ }
2403
+ function writeFloat(buf, value, offset, littleEndian, noAssert) {
2404
+ value = +value;
2405
+ offset = offset >>> 0;
2406
+ if (!noAssert) {
2407
+ checkIEEE754(buf, value, offset, 4);
2408
+ }
2409
+ ieee754$1.write(buf, value, offset, littleEndian, 23, 4);
2410
+ return offset + 4;
2411
+ }
2412
+ Buffer3.prototype.writeFloatLE = function writeFloatLE(value, offset, noAssert) {
2413
+ return writeFloat(this, value, offset, true, noAssert);
2414
+ };
2415
+ Buffer3.prototype.writeFloatBE = function writeFloatBE(value, offset, noAssert) {
2416
+ return writeFloat(this, value, offset, false, noAssert);
2417
+ };
2418
+ function writeDouble(buf, value, offset, littleEndian, noAssert) {
2419
+ value = +value;
2420
+ offset = offset >>> 0;
2421
+ if (!noAssert) {
2422
+ checkIEEE754(buf, value, offset, 8);
2423
+ }
2424
+ ieee754$1.write(buf, value, offset, littleEndian, 52, 8);
2425
+ return offset + 8;
2426
+ }
2427
+ Buffer3.prototype.writeDoubleLE = function writeDoubleLE(value, offset, noAssert) {
2428
+ return writeDouble(this, value, offset, true, noAssert);
2429
+ };
2430
+ Buffer3.prototype.writeDoubleBE = function writeDoubleBE(value, offset, noAssert) {
2431
+ return writeDouble(this, value, offset, false, noAssert);
2432
+ };
2433
+ Buffer3.prototype.copy = function copy(target, targetStart, start, end) {
2434
+ if (!Buffer3.isBuffer(target))
2435
+ throw new TypeError("argument should be a Buffer");
2436
+ if (!start)
2437
+ start = 0;
2438
+ if (!end && end !== 0)
2439
+ end = this.length;
2440
+ if (targetStart >= target.length)
2441
+ targetStart = target.length;
2442
+ if (!targetStart)
2443
+ targetStart = 0;
2444
+ if (end > 0 && end < start)
2445
+ end = start;
2446
+ if (end === start)
2447
+ return 0;
2448
+ if (target.length === 0 || this.length === 0)
2449
+ return 0;
2450
+ if (targetStart < 0) {
2451
+ throw new RangeError("targetStart out of bounds");
2452
+ }
2453
+ if (start < 0 || start >= this.length)
2454
+ throw new RangeError("Index out of range");
2455
+ if (end < 0)
2456
+ throw new RangeError("sourceEnd out of bounds");
2457
+ if (end > this.length)
2458
+ end = this.length;
2459
+ if (target.length - targetStart < end - start) {
2460
+ end = target.length - targetStart + start;
2461
+ }
2462
+ var len = end - start;
2463
+ if (this === target && typeof Uint8Array.prototype.copyWithin === "function") {
2464
+ this.copyWithin(targetStart, start, end);
2465
+ } else {
2466
+ Uint8Array.prototype.set.call(
2467
+ target,
2468
+ this.subarray(start, end),
2469
+ targetStart
2470
+ );
2471
+ }
2472
+ return len;
2473
+ };
2474
+ Buffer3.prototype.fill = function fill(val, start, end, encoding) {
2475
+ if (typeof val === "string") {
2476
+ if (typeof start === "string") {
2477
+ encoding = start;
2478
+ start = 0;
2479
+ end = this.length;
2480
+ } else if (typeof end === "string") {
2481
+ encoding = end;
2482
+ end = this.length;
2483
+ }
2484
+ if (encoding !== void 0 && typeof encoding !== "string") {
2485
+ throw new TypeError("encoding must be a string");
2486
+ }
2487
+ if (typeof encoding === "string" && !Buffer3.isEncoding(encoding)) {
2488
+ throw new TypeError("Unknown encoding: " + encoding);
2489
+ }
2490
+ if (val.length === 1) {
2491
+ var code2 = val.charCodeAt(0);
2492
+ if (encoding === "utf8" && code2 < 128 || encoding === "latin1") {
2493
+ val = code2;
2494
+ }
2495
+ }
2496
+ } else if (typeof val === "number") {
2497
+ val = val & 255;
2498
+ } else if (typeof val === "boolean") {
2499
+ val = Number(val);
2500
+ }
2501
+ if (start < 0 || this.length < start || this.length < end) {
2502
+ throw new RangeError("Out of range index");
2503
+ }
2504
+ if (end <= start) {
2505
+ return this;
2506
+ }
2507
+ start = start >>> 0;
2508
+ end = end === void 0 ? this.length : end >>> 0;
2509
+ if (!val)
2510
+ val = 0;
2511
+ var i;
2512
+ if (typeof val === "number") {
2513
+ for (i = start; i < end; ++i) {
2514
+ this[i] = val;
2515
+ }
2516
+ } else {
2517
+ var bytes = Buffer3.isBuffer(val) ? val : Buffer3.from(val, encoding);
2518
+ var len = bytes.length;
2519
+ if (len === 0) {
2520
+ throw new TypeError('The value "' + val + '" is invalid for argument "value"');
2521
+ }
2522
+ for (i = 0; i < end - start; ++i) {
2523
+ this[i + start] = bytes[i % len];
2524
+ }
2525
+ }
2526
+ return this;
2527
+ };
2528
+ var INVALID_BASE64_RE = /[^+/0-9A-Za-z-_]/g;
2529
+ function base64clean(str) {
2530
+ str = str.split("=")[0];
2531
+ str = str.trim().replace(INVALID_BASE64_RE, "");
2532
+ if (str.length < 2)
2533
+ return "";
2534
+ while (str.length % 4 !== 0) {
2535
+ str = str + "=";
2536
+ }
2537
+ return str;
2538
+ }
2539
+ function utf8ToBytes(string, units) {
2540
+ units = units || Infinity;
2541
+ var codePoint;
2542
+ var length = string.length;
2543
+ var leadSurrogate = null;
2544
+ var bytes = [];
2545
+ for (var i = 0; i < length; ++i) {
2546
+ codePoint = string.charCodeAt(i);
2547
+ if (codePoint > 55295 && codePoint < 57344) {
2548
+ if (!leadSurrogate) {
2549
+ if (codePoint > 56319) {
2550
+ if ((units -= 3) > -1)
2551
+ bytes.push(239, 191, 189);
2552
+ continue;
2553
+ } else if (i + 1 === length) {
2554
+ if ((units -= 3) > -1)
2555
+ bytes.push(239, 191, 189);
2556
+ continue;
2557
+ }
2558
+ leadSurrogate = codePoint;
2559
+ continue;
2560
+ }
2561
+ if (codePoint < 56320) {
2562
+ if ((units -= 3) > -1)
2563
+ bytes.push(239, 191, 189);
2564
+ leadSurrogate = codePoint;
2565
+ continue;
2566
+ }
2567
+ codePoint = (leadSurrogate - 55296 << 10 | codePoint - 56320) + 65536;
2568
+ } else if (leadSurrogate) {
2569
+ if ((units -= 3) > -1)
2570
+ bytes.push(239, 191, 189);
2571
+ }
2572
+ leadSurrogate = null;
2573
+ if (codePoint < 128) {
2574
+ if ((units -= 1) < 0)
2575
+ break;
2576
+ bytes.push(codePoint);
2577
+ } else if (codePoint < 2048) {
2578
+ if ((units -= 2) < 0)
2579
+ break;
2580
+ bytes.push(
2581
+ codePoint >> 6 | 192,
2582
+ codePoint & 63 | 128
2583
+ );
2584
+ } else if (codePoint < 65536) {
2585
+ if ((units -= 3) < 0)
2586
+ break;
2587
+ bytes.push(
2588
+ codePoint >> 12 | 224,
2589
+ codePoint >> 6 & 63 | 128,
2590
+ codePoint & 63 | 128
2591
+ );
2592
+ } else if (codePoint < 1114112) {
2593
+ if ((units -= 4) < 0)
2594
+ break;
2595
+ bytes.push(
2596
+ codePoint >> 18 | 240,
2597
+ codePoint >> 12 & 63 | 128,
2598
+ codePoint >> 6 & 63 | 128,
2599
+ codePoint & 63 | 128
2600
+ );
2601
+ } else {
2602
+ throw new Error("Invalid code point");
2603
+ }
2604
+ }
2605
+ return bytes;
2606
+ }
2607
+ function asciiToBytes(str) {
2608
+ var byteArray = [];
2609
+ for (var i = 0; i < str.length; ++i) {
2610
+ byteArray.push(str.charCodeAt(i) & 255);
2611
+ }
2612
+ return byteArray;
2613
+ }
2614
+ function utf16leToBytes(str, units) {
2615
+ var c, hi, lo;
2616
+ var byteArray = [];
2617
+ for (var i = 0; i < str.length; ++i) {
2618
+ if ((units -= 2) < 0)
2619
+ break;
2620
+ c = str.charCodeAt(i);
2621
+ hi = c >> 8;
2622
+ lo = c % 256;
2623
+ byteArray.push(lo);
2624
+ byteArray.push(hi);
2625
+ }
2626
+ return byteArray;
2627
+ }
2628
+ function base64ToBytes(str) {
2629
+ return base64.toByteArray(base64clean(str));
2630
+ }
2631
+ function blitBuffer(src, dst, offset, length) {
2632
+ for (var i = 0; i < length; ++i) {
2633
+ if (i + offset >= dst.length || i >= src.length)
2634
+ break;
2635
+ dst[i + offset] = src[i];
2636
+ }
2637
+ return i;
2638
+ }
2639
+ function isInstance(obj, type) {
2640
+ return obj instanceof type || obj != null && obj.constructor != null && obj.constructor.name != null && obj.constructor.name === type.name;
2641
+ }
2642
+ function numberIsNaN(obj) {
2643
+ return obj !== obj;
2644
+ }
2645
+ var hexSliceLookupTable = function() {
2646
+ var alphabet = "0123456789abcdef";
2647
+ var table = new Array(256);
2648
+ for (var i = 0; i < 16; ++i) {
2649
+ var i16 = i * 16;
2650
+ for (var j = 0; j < 16; ++j) {
2651
+ table[i16 + j] = alphabet[i] + alphabet[j];
2652
+ }
2653
+ }
2654
+ return table;
2655
+ }();
2656
+ })(buffer);
2657
+ /*! safe-buffer. MIT License. Feross Aboukhadijeh <https://feross.org/opensource> */
2658
+ (function(module, exports) {
2659
+ var buffer$1 = buffer;
2660
+ var Buffer3 = buffer$1.Buffer;
2661
+ function copyProps(src, dst) {
2662
+ for (var key in src) {
2663
+ dst[key] = src[key];
2664
+ }
2665
+ }
2666
+ if (Buffer3.from && Buffer3.alloc && Buffer3.allocUnsafe && Buffer3.allocUnsafeSlow) {
2667
+ module.exports = buffer$1;
2668
+ } else {
2669
+ copyProps(buffer$1, exports);
2670
+ exports.Buffer = SafeBuffer;
2671
+ }
2672
+ function SafeBuffer(arg, encodingOrOffset, length) {
2673
+ return Buffer3(arg, encodingOrOffset, length);
2674
+ }
2675
+ SafeBuffer.prototype = Object.create(Buffer3.prototype);
2676
+ copyProps(Buffer3, SafeBuffer);
2677
+ SafeBuffer.from = function(arg, encodingOrOffset, length) {
2678
+ if (typeof arg === "number") {
2679
+ throw new TypeError("Argument must not be a number");
2680
+ }
2681
+ return Buffer3(arg, encodingOrOffset, length);
2682
+ };
2683
+ SafeBuffer.alloc = function(size, fill, encoding) {
2684
+ if (typeof size !== "number") {
2685
+ throw new TypeError("Argument must be a number");
2686
+ }
2687
+ var buf = Buffer3(size);
2688
+ if (fill !== void 0) {
2689
+ if (typeof encoding === "string") {
2690
+ buf.fill(fill, encoding);
2691
+ } else {
2692
+ buf.fill(fill);
2693
+ }
2694
+ } else {
2695
+ buf.fill(0);
2696
+ }
2697
+ return buf;
2698
+ };
2699
+ SafeBuffer.allocUnsafe = function(size) {
2700
+ if (typeof size !== "number") {
2701
+ throw new TypeError("Argument must be a number");
2702
+ }
2703
+ return Buffer3(size);
2704
+ };
2705
+ SafeBuffer.allocUnsafeSlow = function(size) {
2706
+ if (typeof size !== "number") {
2707
+ throw new TypeError("Argument must be a number");
2708
+ }
2709
+ return buffer$1.SlowBuffer(size);
2710
+ };
2711
+ })(safeBuffer, safeBuffer.exports);
2712
+ var safeBufferExports = safeBuffer.exports;
2713
+ var Buffer$2 = safeBufferExports.Buffer;
2714
+ function Hash$2(blockSize, finalSize) {
2715
+ this._block = Buffer$2.alloc(blockSize);
2716
+ this._finalSize = finalSize;
2717
+ this._blockSize = blockSize;
2718
+ this._len = 0;
2719
+ }
2720
+ Hash$2.prototype.update = function(data, enc) {
2721
+ if (typeof data === "string") {
2722
+ enc = enc || "utf8";
2723
+ data = Buffer$2.from(data, enc);
2724
+ }
2725
+ var block = this._block;
2726
+ var blockSize = this._blockSize;
2727
+ var length = data.length;
2728
+ var accum = this._len;
2729
+ for (var offset = 0; offset < length; ) {
2730
+ var assigned = accum % blockSize;
2731
+ var remainder = Math.min(length - offset, blockSize - assigned);
2732
+ for (var i = 0; i < remainder; i++) {
2733
+ block[assigned + i] = data[offset + i];
2734
+ }
2735
+ accum += remainder;
2736
+ offset += remainder;
2737
+ if (accum % blockSize === 0) {
2738
+ this._update(block);
2739
+ }
2740
+ }
2741
+ this._len += length;
2742
+ return this;
2743
+ };
2744
+ Hash$2.prototype.digest = function(enc) {
2745
+ var rem = this._len % this._blockSize;
2746
+ this._block[rem] = 128;
2747
+ this._block.fill(0, rem + 1);
2748
+ if (rem >= this._finalSize) {
2749
+ this._update(this._block);
2750
+ this._block.fill(0);
2751
+ }
2752
+ var bits = this._len * 8;
2753
+ if (bits <= 4294967295) {
2754
+ this._block.writeUInt32BE(bits, this._blockSize - 4);
2755
+ } else {
2756
+ var lowBits = (bits & 4294967295) >>> 0;
2757
+ var highBits = (bits - lowBits) / 4294967296;
2758
+ this._block.writeUInt32BE(highBits, this._blockSize - 8);
2759
+ this._block.writeUInt32BE(lowBits, this._blockSize - 4);
2760
+ }
2761
+ this._update(this._block);
2762
+ var hash2 = this._hash();
2763
+ return enc ? hash2.toString(enc) : hash2;
2764
+ };
2765
+ Hash$2.prototype._update = function() {
2766
+ throw new Error("_update must be implemented by subclass");
2767
+ };
2768
+ var hash$1 = Hash$2;
2769
+ var inherits$1 = inherits_browserExports;
2770
+ var Hash$1 = hash$1;
2771
+ var Buffer$1 = safeBufferExports.Buffer;
2772
+ var K$1 = [
2773
+ 1518500249,
2774
+ 1859775393,
2775
+ 2400959708 | 0,
2776
+ 3395469782 | 0
2777
+ ];
2778
+ var W$1 = new Array(80);
2779
+ function Sha1() {
2780
+ this.init();
2781
+ this._w = W$1;
2782
+ Hash$1.call(this, 64, 56);
2783
+ }
2784
+ inherits$1(Sha1, Hash$1);
2785
+ Sha1.prototype.init = function() {
2786
+ this._a = 1732584193;
2787
+ this._b = 4023233417;
2788
+ this._c = 2562383102;
2789
+ this._d = 271733878;
2790
+ this._e = 3285377520;
2791
+ return this;
2792
+ };
2793
+ function rotl1(num) {
2794
+ return num << 1 | num >>> 31;
2795
+ }
2796
+ function rotl5(num) {
2797
+ return num << 5 | num >>> 27;
2798
+ }
2799
+ function rotl30(num) {
2800
+ return num << 30 | num >>> 2;
2801
+ }
2802
+ function ft(s, b, c, d) {
2803
+ if (s === 0)
2804
+ return b & c | ~b & d;
2805
+ if (s === 2)
2806
+ return b & c | b & d | c & d;
2807
+ return b ^ c ^ d;
2808
+ }
2809
+ Sha1.prototype._update = function(M) {
2810
+ var W2 = this._w;
2811
+ var a = this._a | 0;
2812
+ var b = this._b | 0;
2813
+ var c = this._c | 0;
2814
+ var d = this._d | 0;
2815
+ var e = this._e | 0;
2816
+ for (var i = 0; i < 16; ++i)
2817
+ W2[i] = M.readInt32BE(i * 4);
2818
+ for (; i < 80; ++i)
2819
+ W2[i] = rotl1(W2[i - 3] ^ W2[i - 8] ^ W2[i - 14] ^ W2[i - 16]);
2820
+ for (var j = 0; j < 80; ++j) {
2821
+ var s = ~~(j / 20);
2822
+ var t = rotl5(a) + ft(s, b, c, d) + e + W2[j] + K$1[s] | 0;
2823
+ e = d;
2824
+ d = c;
2825
+ c = rotl30(b);
2826
+ b = a;
2827
+ a = t;
2828
+ }
2829
+ this._a = a + this._a | 0;
2830
+ this._b = b + this._b | 0;
2831
+ this._c = c + this._c | 0;
2832
+ this._d = d + this._d | 0;
2833
+ this._e = e + this._e | 0;
2834
+ };
2835
+ Sha1.prototype._hash = function() {
2836
+ var H = Buffer$1.allocUnsafe(20);
2837
+ H.writeInt32BE(this._a | 0, 0);
2838
+ H.writeInt32BE(this._b | 0, 4);
2839
+ H.writeInt32BE(this._c | 0, 8);
2840
+ H.writeInt32BE(this._d | 0, 12);
2841
+ H.writeInt32BE(this._e | 0, 16);
2842
+ return H;
2843
+ };
2844
+ var sha1 = Sha1;
2845
+ const Sha1$1 = /* @__PURE__ */ getDefaultExportFromCjs(sha1);
2846
+ var inherits = inherits_browserExports;
2847
+ var Hash = hash$1;
2848
+ var Buffer2 = safeBufferExports.Buffer;
2849
+ var K = [
2850
+ 1116352408,
2851
+ 1899447441,
2852
+ 3049323471,
2853
+ 3921009573,
2854
+ 961987163,
2855
+ 1508970993,
2856
+ 2453635748,
2857
+ 2870763221,
2858
+ 3624381080,
2859
+ 310598401,
2860
+ 607225278,
2861
+ 1426881987,
2862
+ 1925078388,
2863
+ 2162078206,
2864
+ 2614888103,
2865
+ 3248222580,
2866
+ 3835390401,
2867
+ 4022224774,
2868
+ 264347078,
2869
+ 604807628,
2870
+ 770255983,
2871
+ 1249150122,
2872
+ 1555081692,
2873
+ 1996064986,
2874
+ 2554220882,
2875
+ 2821834349,
2876
+ 2952996808,
2877
+ 3210313671,
2878
+ 3336571891,
2879
+ 3584528711,
2880
+ 113926993,
2881
+ 338241895,
2882
+ 666307205,
2883
+ 773529912,
2884
+ 1294757372,
2885
+ 1396182291,
2886
+ 1695183700,
2887
+ 1986661051,
2888
+ 2177026350,
2889
+ 2456956037,
2890
+ 2730485921,
2891
+ 2820302411,
2892
+ 3259730800,
2893
+ 3345764771,
2894
+ 3516065817,
2895
+ 3600352804,
2896
+ 4094571909,
2897
+ 275423344,
2898
+ 430227734,
2899
+ 506948616,
2900
+ 659060556,
2901
+ 883997877,
2902
+ 958139571,
2903
+ 1322822218,
2904
+ 1537002063,
2905
+ 1747873779,
2906
+ 1955562222,
2907
+ 2024104815,
2908
+ 2227730452,
2909
+ 2361852424,
2910
+ 2428436474,
2911
+ 2756734187,
2912
+ 3204031479,
2913
+ 3329325298
2914
+ ];
2915
+ var W = new Array(64);
2916
+ function Sha256() {
2917
+ this.init();
2918
+ this._w = W;
2919
+ Hash.call(this, 64, 56);
2920
+ }
2921
+ inherits(Sha256, Hash);
2922
+ Sha256.prototype.init = function() {
2923
+ this._a = 1779033703;
2924
+ this._b = 3144134277;
2925
+ this._c = 1013904242;
2926
+ this._d = 2773480762;
2927
+ this._e = 1359893119;
2928
+ this._f = 2600822924;
2929
+ this._g = 528734635;
2930
+ this._h = 1541459225;
2931
+ return this;
2932
+ };
2933
+ function ch(x, y, z2) {
2934
+ return z2 ^ x & (y ^ z2);
2935
+ }
2936
+ function maj(x, y, z2) {
2937
+ return x & y | z2 & (x | y);
2938
+ }
2939
+ function sigma0(x) {
2940
+ return (x >>> 2 | x << 30) ^ (x >>> 13 | x << 19) ^ (x >>> 22 | x << 10);
2941
+ }
2942
+ function sigma1(x) {
2943
+ return (x >>> 6 | x << 26) ^ (x >>> 11 | x << 21) ^ (x >>> 25 | x << 7);
2944
+ }
2945
+ function gamma0(x) {
2946
+ return (x >>> 7 | x << 25) ^ (x >>> 18 | x << 14) ^ x >>> 3;
2947
+ }
2948
+ function gamma1(x) {
2949
+ return (x >>> 17 | x << 15) ^ (x >>> 19 | x << 13) ^ x >>> 10;
2950
+ }
2951
+ Sha256.prototype._update = function(M) {
2952
+ var W2 = this._w;
2953
+ var a = this._a | 0;
2954
+ var b = this._b | 0;
2955
+ var c = this._c | 0;
2956
+ var d = this._d | 0;
2957
+ var e = this._e | 0;
2958
+ var f = this._f | 0;
2959
+ var g = this._g | 0;
2960
+ var h = this._h | 0;
2961
+ for (var i = 0; i < 16; ++i)
2962
+ W2[i] = M.readInt32BE(i * 4);
2963
+ for (; i < 64; ++i)
2964
+ W2[i] = gamma1(W2[i - 2]) + W2[i - 7] + gamma0(W2[i - 15]) + W2[i - 16] | 0;
2965
+ for (var j = 0; j < 64; ++j) {
2966
+ var T1 = h + sigma1(e) + ch(e, f, g) + K[j] + W2[j] | 0;
2967
+ var T2 = sigma0(a) + maj(a, b, c) | 0;
2968
+ h = g;
2969
+ g = f;
2970
+ f = e;
2971
+ e = d + T1 | 0;
2972
+ d = c;
2973
+ c = b;
2974
+ b = a;
2975
+ a = T1 + T2 | 0;
2976
+ }
2977
+ this._a = a + this._a | 0;
2978
+ this._b = b + this._b | 0;
2979
+ this._c = c + this._c | 0;
2980
+ this._d = d + this._d | 0;
2981
+ this._e = e + this._e | 0;
2982
+ this._f = f + this._f | 0;
2983
+ this._g = g + this._g | 0;
2984
+ this._h = h + this._h | 0;
2985
+ };
2986
+ Sha256.prototype._hash = function() {
2987
+ var H = Buffer2.allocUnsafe(32);
2988
+ H.writeInt32BE(this._a, 0);
2989
+ H.writeInt32BE(this._b, 4);
2990
+ H.writeInt32BE(this._c, 8);
2991
+ H.writeInt32BE(this._d, 12);
2992
+ H.writeInt32BE(this._e, 16);
2993
+ H.writeInt32BE(this._f, 20);
2994
+ H.writeInt32BE(this._g, 24);
2995
+ H.writeInt32BE(this._h, 28);
2996
+ return H;
2997
+ };
2998
+ var sha256 = Sha256;
2999
+ const Sha256$1 = /* @__PURE__ */ getDefaultExportFromCjs(sha256);
3000
+ const FileSystemError = new Error("File system not available.");
3001
+ function writeFile(path, name, stream) {
3002
+ throw FileSystemError;
3003
+ }
3004
+ function readFile(path) {
3005
+ throw FileSystemError;
3006
+ }
3007
+ function fetchFile(url) {
3008
+ throw FileSystemError;
3009
+ }
3010
+ const getFile = async (file) => {
3011
+ return readFile();
3012
+ };
3013
+ const hashAlgorithms = {
3014
+ sha1: Sha1$1,
3015
+ sha256: Sha256$1
3016
+ };
3017
+ const hash = (data, algorithm = "sha1") => {
3018
+ if (!["sha1", "sha256"].includes(algorithm)) {
3019
+ throw new Error("Hashing algorithm not supported: Available: sha1, sha256");
3020
+ }
3021
+ const Algorithm = hashAlgorithms[algorithm];
3022
+ const sha = new Algorithm();
3023
+ return sha.update(data).digest("base64");
3024
+ };
3025
+ function validateOperations(operations) {
3026
+ const errors = [];
3027
+ const scopes = Object.keys(operations);
3028
+ for (const scope of scopes) {
3029
+ const ops = operations[scope].sort((a, b) => a.index - b.index);
3030
+ for (let i = 0; i < ops.length; i++) {
3031
+ if (ops[i].index !== i) {
3032
+ errors.push({
3033
+ message: `Invalid operation index ${ops[i].index} at position ${i}`,
3034
+ details: {
3035
+ position: i,
3036
+ operation: ops[i],
3037
+ scope: ops[i].scope
3038
+ }
3039
+ });
3040
+ }
3041
+ }
3042
+ }
3043
+ return errors;
3044
+ }
3045
+ const createZip = async (document) => {
3046
+ const zip = new JSZip();
3047
+ const { name, revision, documentType, created, lastModified } = document;
3048
+ const header = {
3049
+ name,
3050
+ revision,
3051
+ documentType,
3052
+ created,
3053
+ lastModified
3054
+ };
3055
+ zip.file("header.json", JSON.stringify(header, null, 2));
3056
+ zip.file(
3057
+ "state.json",
3058
+ JSON.stringify(document.initialState || {}, null, 2)
3059
+ );
3060
+ zip.file("operations.json", JSON.stringify(document.operations, null, 2));
3061
+ const attachments = Object.keys(document.attachments);
3062
+ attachments.forEach((key) => {
3063
+ const { data, ...attributes } = document.attachments[key];
3064
+ zip.file(key, data, {
3065
+ base64: true,
3066
+ createFolders: true,
3067
+ comment: JSON.stringify(attributes)
3068
+ });
3069
+ });
3070
+ return zip;
3071
+ };
3072
+ const saveToFile = async (document, path, extension, name) => {
3073
+ const zip = await createZip(document);
3074
+ await zip.generateAsync({
3075
+ type: "uint8array",
3076
+ streamFiles: true
3077
+ });
3078
+ const fileName = name ?? document.name;
3079
+ const fileExtension = `.${extension}.zip`;
3080
+ return writeFile(
3081
+ path,
3082
+ fileName.endsWith(fileExtension) ? fileName : `${fileName}${fileExtension}`
3083
+ );
3084
+ };
3085
+ const saveToFileHandle = async (document, input) => {
3086
+ const zip = await createZip(document);
3087
+ const blob = await zip.generateAsync({ type: "blob" });
3088
+ const writable = await input.createWritable();
3089
+ await writable.write(blob);
3090
+ await writable.close();
3091
+ };
3092
+ const loadFromFile = async (path, reducer, options) => {
3093
+ const file = readFile();
3094
+ return loadFromInput(file, reducer, options);
3095
+ };
3096
+ const loadFromInput = async (input, reducer, options) => {
3097
+ const zip = new JSZip();
3098
+ await zip.loadAsync(input);
3099
+ return loadFromZip(zip, reducer, options);
3100
+ };
3101
+ async function loadFromZip(zip, reducer, options) {
3102
+ const initialStateZip = zip.file("state.json");
3103
+ if (!initialStateZip) {
3104
+ throw new Error("Initial state not found");
3105
+ }
3106
+ const initialStateStr = await initialStateZip.async("string");
3107
+ const initialState = JSON.parse(initialStateStr);
3108
+ const headerZip = zip.file("header.json");
3109
+ let header = void 0;
3110
+ if (headerZip) {
3111
+ header = JSON.parse(await headerZip.async("string"));
3112
+ }
3113
+ const operationsZip = zip.file("operations.json");
3114
+ if (!operationsZip) {
3115
+ throw new Error("Operations history not found");
3116
+ }
3117
+ const operations = JSON.parse(
3118
+ await operationsZip.async("string")
3119
+ );
3120
+ const operationsError = validateOperations(operations);
3121
+ if (operationsError.length) {
3122
+ const errorMessages = operationsError.map((err) => err.message);
3123
+ throw new Error(errorMessages.join("\n"));
3124
+ }
3125
+ let result = replayDocument(
3126
+ initialState,
3127
+ operations,
3128
+ reducer,
3129
+ void 0,
3130
+ header,
3131
+ {},
3132
+ options
3133
+ );
3134
+ if (header) {
3135
+ result = {
3136
+ ...result,
3137
+ ...header
3138
+ };
3139
+ }
3140
+ return result;
3141
+ }
3142
+ function getFileAttributes(file) {
3143
+ const extension = file.replace(/^.*\./, "") || void 0;
3144
+ const fileName = file.replace(/^.*[/\\]/, "") || void 0;
3145
+ return { extension, fileName };
3146
+ }
3147
+ async function getRemoteFile(url) {
3148
+ const { buffer: buffer2, mimeType = "application/octet-stream" } = await fetchFile();
3149
+ const attributes = getFileAttributes(url);
3150
+ const data = buffer2.toString("base64");
3151
+ return {
3152
+ data,
3153
+ hash: hash(data),
3154
+ mimeType,
3155
+ ...attributes
3156
+ };
3157
+ }
3158
+ async function getLocalFile(path) {
3159
+ const buffer2 = await getFile();
3160
+ const mimeType = mime.getType(path) || "application/octet-stream";
3161
+ const attributes = getFileAttributes(path);
3162
+ const data = buffer2.toString("base64");
3163
+ return { data, hash: hash(data), mimeType, ...attributes };
3164
+ }
3165
+ var IntegrityIssueType = /* @__PURE__ */ ((IntegrityIssueType2) => {
3166
+ IntegrityIssueType2["UNEXPECTED_INDEX"] = "UNEXPECTED_INDEX";
3167
+ return IntegrityIssueType2;
3168
+ })(IntegrityIssueType || {});
3169
+ var IntegrityIssueSubType = /* @__PURE__ */ ((IntegrityIssueSubType2) => {
3170
+ IntegrityIssueSubType2["DUPLICATED_INDEX"] = "DUPLICATED_INDEX";
3171
+ IntegrityIssueSubType2["MISSING_INDEX"] = "MISSING_INDEX";
3172
+ return IntegrityIssueSubType2;
3173
+ })(IntegrityIssueSubType || {});
3174
+ function checkCleanedOperationsIntegrity(sortedOperations) {
3175
+ const result = [];
3176
+ let currentIndex = -1;
3177
+ for (const nextOperation of sortedOperations) {
3178
+ const nextIndex = nextOperation.index - nextOperation.skip;
3179
+ if (nextIndex !== currentIndex + 1) {
3180
+ result.push({
3181
+ operation: {
3182
+ index: nextOperation.index,
3183
+ skip: nextOperation.skip
3184
+ },
3185
+ issue: "UNEXPECTED_INDEX",
3186
+ category: nextIndex > currentIndex + 1 ? "MISSING_INDEX" : "DUPLICATED_INDEX",
3187
+ message: `Expected index ${currentIndex + 1} with skip 0 or equivalent, got index ${nextOperation.index} with skip ${nextOperation.skip}`
3188
+ });
3189
+ }
3190
+ currentIndex = nextOperation.index;
3191
+ }
3192
+ return result;
3193
+ }
3194
+ function garbageCollect(sortedOperations) {
3195
+ var _a, _b, _c;
3196
+ const result = [];
3197
+ let i = sortedOperations.length - 1;
3198
+ while (i > -1) {
3199
+ result.unshift(sortedOperations[i]);
3200
+ const skipUntil = (((_a = sortedOperations[i]) == null ? void 0 : _a.index) || 0) - (((_b = sortedOperations[i]) == null ? void 0 : _b.skip) || 0) - 1;
3201
+ let j = i - 1;
3202
+ while (j > -1 && (((_c = sortedOperations[j]) == null ? void 0 : _c.index) || 0) > skipUntil) {
3203
+ j--;
3204
+ }
3205
+ i = j;
3206
+ }
3207
+ return result;
3208
+ }
3209
+ function addUndo(sortedOperations) {
3210
+ const operationsCopy = [...sortedOperations];
3211
+ const latestOperation = operationsCopy[operationsCopy.length - 1];
3212
+ if (!latestOperation)
3213
+ return operationsCopy;
3214
+ if (latestOperation.type === "NOOP") {
3215
+ operationsCopy.push({
3216
+ ...latestOperation,
3217
+ index: latestOperation.index,
3218
+ type: "NOOP",
3219
+ skip: nextSkipNumber(sortedOperations)
3220
+ });
3221
+ } else {
3222
+ operationsCopy.push({
3223
+ type: "NOOP",
3224
+ index: latestOperation.index + 1,
3225
+ timestamp: (/* @__PURE__ */ new Date()).toISOString(),
3226
+ input: {},
3227
+ skip: 1,
3228
+ scope: latestOperation.scope,
3229
+ hash: latestOperation.hash
3230
+ });
3231
+ }
3232
+ return operationsCopy;
3233
+ }
3234
+ function sortOperations$1(operations) {
3235
+ return operations.slice().sort((a, b) => a.skip - b.skip).sort((a, b) => a.index - b.index);
3236
+ }
3237
+ const reshuffleByTimestamp = (startIndex, opsA, opsB) => {
3238
+ return [...opsA, ...opsB].sort(
3239
+ (a, b) => new Date(a.timestamp).getTime() - new Date(b.timestamp).getTime()
3240
+ ).map((op, i) => ({
3241
+ ...op,
3242
+ index: startIndex.index + i,
3243
+ skip: i === 0 ? startIndex.skip : 0
3244
+ }));
3245
+ };
3246
+ const reshuffleByTimestampAndIndex = (startIndex, opsA, opsB) => {
3247
+ return [...opsA, ...opsB].sort(
3248
+ (a, b) => new Date(a.timestamp).getTime() - new Date(b.timestamp).getTime()
3249
+ ).sort((a, b) => a.index - b.index).map((op, i) => ({
3250
+ ...op,
3251
+ index: startIndex.index + i,
3252
+ skip: i === 0 ? startIndex.skip : 0
3253
+ }));
3254
+ };
3255
+ function operationsAreEqual(op1, op2) {
3256
+ return cjsModule(op1) === cjsModule(op2);
3257
+ }
3258
+ function attachBranch(trunk, newBranch) {
3259
+ const trunkCopy = garbageCollect(sortOperations$1(trunk.slice()));
3260
+ const newOperations = garbageCollect(sortOperations$1(newBranch.slice()));
3261
+ if (trunkCopy.length < 1) {
3262
+ return [newOperations, []];
3263
+ }
3264
+ const result = [];
3265
+ let enteredBranch = false;
3266
+ while (newOperations.length > 0) {
3267
+ const newOperationCandidate = newOperations[0];
3268
+ let nextTrunkOperation = trunkCopy.shift();
3269
+ while (nextTrunkOperation && precedes(nextTrunkOperation, newOperationCandidate)) {
3270
+ result.push(nextTrunkOperation);
3271
+ nextTrunkOperation = trunkCopy.shift();
3272
+ }
3273
+ if (!nextTrunkOperation) {
3274
+ enteredBranch = true;
3275
+ } else if (!enteredBranch) {
3276
+ if (operationsAreEqual(nextTrunkOperation, newOperationCandidate)) {
3277
+ newOperations.shift();
3278
+ result.push(nextTrunkOperation);
3279
+ } else {
3280
+ trunkCopy.unshift(nextTrunkOperation);
3281
+ enteredBranch = true;
3282
+ }
3283
+ }
3284
+ if (enteredBranch) {
3285
+ let nextAppend = newOperations.shift();
3286
+ while (nextAppend) {
3287
+ result.push(nextAppend);
3288
+ nextAppend = newOperations.shift();
3289
+ }
3290
+ }
3291
+ }
3292
+ if (!enteredBranch) {
3293
+ let nextAppend = trunkCopy.shift();
3294
+ while (nextAppend) {
3295
+ result.push(nextAppend);
3296
+ nextAppend = trunkCopy.shift();
3297
+ }
3298
+ }
3299
+ return [garbageCollect(result), trunkCopy];
3300
+ }
3301
+ function precedes(op1, op2) {
3302
+ return op1.index < op2.index || op1.index === op2.index && op1.skip < op2.skip;
3303
+ }
3304
+ function split(sortedTargetOperations, sortedMergeOperations) {
3305
+ const commonOperations = [];
3306
+ const targetDiffOperations = [];
3307
+ const mergeDiffOperations = [];
3308
+ const maxLength = Math.max(
3309
+ sortedTargetOperations.length,
3310
+ sortedMergeOperations.length
3311
+ );
3312
+ let splitHappened = false;
3313
+ for (let i = 0; i < maxLength; i++) {
3314
+ const targetOperation = sortedTargetOperations[i];
3315
+ const mergeOperation = sortedMergeOperations[i];
3316
+ if (targetOperation && mergeOperation) {
3317
+ if (!splitHappened && operationsAreEqual(targetOperation, mergeOperation)) {
3318
+ commonOperations.push(targetOperation);
3319
+ } else {
3320
+ splitHappened = true;
3321
+ targetDiffOperations.push(targetOperation);
3322
+ mergeDiffOperations.push(mergeOperation);
3323
+ }
3324
+ } else if (targetOperation) {
3325
+ targetDiffOperations.push(targetOperation);
3326
+ } else if (mergeOperation) {
3327
+ mergeDiffOperations.push(mergeOperation);
3328
+ }
3329
+ }
3330
+ return [commonOperations, targetDiffOperations, mergeDiffOperations];
3331
+ }
3332
+ function merge(sortedTargetOperations, sortedMergeOperations, reshuffle) {
3333
+ const [_commonOperations, _targetOperations, _mergeOperations] = split(
3334
+ garbageCollect(sortedTargetOperations),
3335
+ garbageCollect(sortedMergeOperations)
3336
+ );
3337
+ const maxCommonIndex = getMaxIndex(_commonOperations);
3338
+ const nextIndex = 1 + Math.max(
3339
+ maxCommonIndex,
3340
+ getMaxIndex(_targetOperations),
3341
+ getMaxIndex(_mergeOperations)
3342
+ );
3343
+ const newOperationHistory = reshuffle(
3344
+ {
3345
+ index: nextIndex,
3346
+ skip: nextIndex - (maxCommonIndex + 1)
3347
+ },
3348
+ _targetOperations,
3349
+ _mergeOperations
3350
+ );
3351
+ return _commonOperations.concat(newOperationHistory);
3352
+ }
3353
+ function getMaxIndex(sortedOperations) {
3354
+ const lastElement = sortedOperations[sortedOperations.length - 1];
3355
+ if (!lastElement) {
3356
+ return -1;
3357
+ }
3358
+ return lastElement.index;
3359
+ }
3360
+ function nextSkipNumber(sortedOperations) {
3361
+ var _a, _b, _c;
3362
+ if (sortedOperations.length < 1) {
3363
+ return -1;
3364
+ }
3365
+ const cleanedOperations = garbageCollect(sortedOperations);
3366
+ let nextSkip = (((_a = cleanedOperations[cleanedOperations.length - 1]) == null ? void 0 : _a.skip) || 0) + 1;
3367
+ if (cleanedOperations.length > 1) {
3368
+ nextSkip += ((_b = cleanedOperations[cleanedOperations.length - 2]) == null ? void 0 : _b.skip) || 0;
3369
+ }
3370
+ return (((_c = cleanedOperations[cleanedOperations.length - 1]) == null ? void 0 : _c.index) || -1) < nextSkip ? -1 : nextSkip;
3371
+ }
3372
+ const checkOperationsIntegrity = (operations) => {
3373
+ return checkCleanedOperationsIntegrity(
3374
+ garbageCollect(sortOperations$1(operations))
3375
+ );
3376
+ };
3377
+ const groupOperationsByScope = (operations) => {
3378
+ const result = operations.reduce((acc, operation) => {
3379
+ var _a;
3380
+ if (!acc[operation.scope]) {
3381
+ acc[operation.scope] = [];
3382
+ }
3383
+ (_a = acc[operation.scope]) == null ? void 0 : _a.push(operation);
3384
+ return acc;
3385
+ }, {});
3386
+ return result;
3387
+ };
3388
+ const prepareOperations = (operationsHistory, newOperations) => {
3389
+ var _a;
3390
+ const result = {
3391
+ integrityIssues: [],
3392
+ validOperations: [],
3393
+ invalidOperations: [],
3394
+ duplicatedOperations: []
3395
+ };
3396
+ const sortedOperationsHistory = sortOperations$1(operationsHistory);
3397
+ const sortedOperations = sortOperations$1(newOperations);
3398
+ const integrityErrors = checkCleanedOperationsIntegrity([
3399
+ ...sortedOperationsHistory,
3400
+ ...sortedOperations
3401
+ ]);
3402
+ const missingIndexErrors = integrityErrors.filter(
3403
+ (integrityIssue) => integrityIssue.category === "MISSING_INDEX"
3404
+ /* MISSING_INDEX */
3405
+ );
3406
+ const firstMissingIndexOperation = (_a = [...missingIndexErrors].sort((a, b) => b.operation.index - a.operation.index).pop()) == null ? void 0 : _a.operation;
3407
+ for (const newOperation of sortedOperations) {
3408
+ if (firstMissingIndexOperation && newOperation.index >= firstMissingIndexOperation.index) {
3409
+ result.invalidOperations.push(newOperation);
3410
+ continue;
3411
+ }
3412
+ const isDuplicatedOperation = integrityErrors.some((integrityError) => {
3413
+ return integrityError.operation.index === newOperation.index && integrityError.operation.skip === newOperation.skip && integrityError.category === "DUPLICATED_INDEX";
3414
+ });
3415
+ if (isDuplicatedOperation) {
3416
+ result.duplicatedOperations.push(newOperation);
3417
+ continue;
3418
+ }
3419
+ result.validOperations.push(newOperation);
3420
+ }
3421
+ result.integrityIssues.push(...integrityErrors);
3422
+ return result;
3423
+ };
3424
+ function removeExistingOperations(newOperations, operationsHistory) {
3425
+ return newOperations.filter((newOperation) => {
3426
+ return !operationsHistory.some((historyOperation) => {
3427
+ return newOperation.type === "NOOP" && newOperation.skip === 0 && newOperation.index === historyOperation.index || newOperation.index === historyOperation.index && newOperation.skip === historyOperation.skip && newOperation.scope === historyOperation.scope && newOperation.hash === historyOperation.hash && newOperation.type === historyOperation.type;
3428
+ });
3429
+ });
3430
+ }
3431
+ function skipHeaderOperations(operations, skipHeaderOperation) {
3432
+ const [lastOperation] = sortOperations$1(operations).slice(-1);
3433
+ const lastIndex = (lastOperation == null ? void 0 : lastOperation.index) ?? -1;
3434
+ const nextIndex = lastIndex + 1;
3435
+ const skipOperationIndex = {
3436
+ ...skipHeaderOperation,
3437
+ index: skipHeaderOperation.index ?? nextIndex
3438
+ };
3439
+ if (skipOperationIndex.index < lastIndex) {
3440
+ throw new Error(
3441
+ `The skip header operation index must be greater than or equal to ${lastIndex}`
3442
+ );
3443
+ }
3444
+ const clearedOperations = garbageCollect(
3445
+ sortOperations$1([...operations, skipOperationIndex])
3446
+ );
3447
+ return (clearedOperations || []).slice(0, -1);
3448
+ }
3449
+ function grabageCollectDocumentOperations(documentOperations) {
3450
+ const clearedOperations = Object.entries(documentOperations).reduce(
3451
+ (acc, entry) => {
3452
+ const [scope, ops] = entry;
3453
+ return {
3454
+ ...acc,
3455
+ [scope]: garbageCollect(sortOperations$1(ops))
3456
+ };
3457
+ },
3458
+ {}
3459
+ );
3460
+ return {
3461
+ ...clearedOperations
3462
+ };
3463
+ }
3464
+ const documentHelpers = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({
3465
+ __proto__: null,
3466
+ IntegrityIssueSubType,
3467
+ IntegrityIssueType,
3468
+ addUndo,
3469
+ attachBranch,
3470
+ checkCleanedOperationsIntegrity,
3471
+ checkOperationsIntegrity,
3472
+ garbageCollect,
3473
+ grabageCollectDocumentOperations,
3474
+ groupOperationsByScope,
3475
+ merge,
3476
+ nextSkipNumber,
3477
+ operationsAreEqual,
3478
+ precedes,
3479
+ prepareOperations,
3480
+ removeExistingOperations,
3481
+ reshuffleByTimestamp,
3482
+ reshuffleByTimestampAndIndex,
3483
+ skipHeaderOperations,
3484
+ sortOperations: sortOperations$1,
3485
+ split
3486
+ }, Symbol.toStringTag, { value: "Module" }));
3487
+ function getNextRevision(document, action) {
3488
+ let latestOperation;
3489
+ if ("index" in action) {
3490
+ latestOperation = { ...action };
3491
+ } else {
3492
+ latestOperation = document.operations[action.scope].at(-1);
3493
+ }
3494
+ return ((latestOperation == null ? void 0 : latestOperation.index) ?? -1) + 1;
3495
+ }
3496
+ function updateHeader(document, action) {
3497
+ return {
3498
+ ...document,
3499
+ revision: {
3500
+ ...document.revision,
3501
+ [action.scope]: getNextRevision(document, action)
3502
+ },
3503
+ lastModified: (/* @__PURE__ */ new Date()).toISOString()
3504
+ };
3505
+ }
3506
+ function updateOperations(document, action, skip = 0) {
3507
+ if ([UNDO, REDO, PRUNE].includes(action.type)) {
3508
+ return document;
3509
+ }
3510
+ const { scope } = action;
3511
+ const operations = document.operations[scope].slice(
3512
+ 0,
3513
+ document.revision[scope]
3514
+ );
3515
+ const latestOperation = [...operations].pop();
3516
+ let nextIndex = ((latestOperation == null ? void 0 : latestOperation.index) ?? -1) + 1;
3517
+ if ("index" in action) {
3518
+ if (action.index - skip > nextIndex) {
3519
+ throw new Error(
3520
+ `Missing operations: expected ${nextIndex} with skip 0 or equivalent, got index ${action.index} with skip ${skip}`
3521
+ );
3522
+ }
3523
+ nextIndex = action.index;
3524
+ }
3525
+ operations.push({
3526
+ ...action,
3527
+ index: nextIndex,
3528
+ timestamp: (/* @__PURE__ */ new Date()).toISOString(),
3529
+ hash: "",
3530
+ scope,
3531
+ skip,
3532
+ error: void 0
3533
+ });
3534
+ return {
3535
+ ...document,
3536
+ operations: { ...document.operations, [scope]: operations }
3537
+ };
3538
+ }
3539
+ function updateDocument(document, action, skip = 0) {
3540
+ let newDocument = updateOperations(document, action, skip);
3541
+ newDocument = updateHeader(newDocument, action);
3542
+ return newDocument;
3543
+ }
3544
+ function _baseReducer(document, action, wrappedReducer) {
3545
+ BaseActionSchema().parse(action);
3546
+ switch (action.type) {
3547
+ case SET_NAME:
3548
+ return setNameOperation(document, action.input);
3549
+ case PRUNE:
3550
+ return pruneOperation(document, action, wrappedReducer);
3551
+ case LOAD_STATE:
3552
+ return loadStateOperation(document, action.input.state);
3553
+ default:
3554
+ return document;
3555
+ }
3556
+ }
3557
+ function processUndoRedo(document, action, skip) {
3558
+ switch (action.type) {
3559
+ case UNDO:
3560
+ return undoOperation(document, action, skip);
3561
+ case REDO:
3562
+ return redoOperation(document, action, skip);
3563
+ default:
3564
+ return { document, action, skip };
3565
+ }
3566
+ }
3567
+ function processSkipOperation(document, action, customReducer, skipValue) {
3568
+ const scope = action.scope;
3569
+ const latestOperation = document.operations[scope].at(-1);
3570
+ if (!latestOperation)
3571
+ return document;
3572
+ const documentOperations = grabageCollectDocumentOperations(
3573
+ {
3574
+ ...document.operations,
3575
+ [scope]: skipHeaderOperations(
3576
+ document.operations[scope],
3577
+ latestOperation
3578
+ )
3579
+ }
3580
+ );
3581
+ const { state } = replayOperations(
3582
+ document.initialState,
3583
+ documentOperations,
3584
+ customReducer,
3585
+ void 0,
3586
+ void 0,
3587
+ void 0
3588
+ );
3589
+ return {
3590
+ ...document,
3591
+ state,
3592
+ operations: grabageCollectDocumentOperations({
3593
+ ...document.operations
3594
+ })
3595
+ };
3596
+ }
3597
+ function baseReducer(document, action, customReducer, dispatch, options = {}) {
3598
+ const { skip, ignoreSkipOperations = false, reuseHash = false } = options;
3599
+ const _action = { ...action };
3600
+ const skipValue = skip || 0;
3601
+ let newDocument = { ...document };
3602
+ const shouldProcessSkipOperation = !ignoreSkipOperations && (skipValue > 0 || "index" in _action && _action.skip > 0);
3603
+ if (isBaseAction(_action)) {
3604
+ newDocument = _baseReducer(newDocument, _action, customReducer);
3605
+ }
3606
+ newDocument = updateDocument(newDocument, _action, skipValue);
3607
+ if (shouldProcessSkipOperation) {
3608
+ newDocument = processSkipOperation(
3609
+ newDocument,
3610
+ _action,
3611
+ customReducer
3612
+ );
3613
+ }
3614
+ newDocument = produce(newDocument, (draft) => {
3615
+ try {
3616
+ const returnedDraft = customReducer(
3617
+ draft.state,
3618
+ _action,
3619
+ dispatch
3620
+ );
3621
+ if (returnedDraft) {
3622
+ return castDraft({
3623
+ ...newDocument,
3624
+ // clipboard: [...clipboardValue],
3625
+ state: returnedDraft
3626
+ });
3627
+ } else {
3628
+ }
3629
+ } catch (error) {
3630
+ const lastOperationIndex = newDocument.operations[_action.scope].length - 1;
3631
+ draft.operations[_action.scope][lastOperationIndex].error = error.message;
3632
+ draft.operations[_action.scope][lastOperationIndex].skip = 0;
3633
+ if (shouldProcessSkipOperation) {
3634
+ draft.state = castDraft({ ...document.state });
3635
+ draft.operations = castDraft({
3636
+ ...document.operations,
3637
+ [_action.scope]: [
3638
+ ...document.operations[_action.scope],
3639
+ {
3640
+ ...draft.operations[_action.scope][lastOperationIndex]
3641
+ }
3642
+ ]
3643
+ });
3644
+ }
3645
+ }
3646
+ });
3647
+ return produce(newDocument, (draft) => {
3648
+ if ([UNDO, REDO, PRUNE].includes(_action.type)) {
3649
+ return draft;
3650
+ }
3651
+ const scope = _action.scope || "global";
3652
+ const hash2 = reuseHash && Object.prototype.hasOwnProperty.call(_action, "hash") ? _action.hash : hashDocument(draft, scope);
3653
+ draft.operations[scope][draft.operations[scope].length - 1].hash = hash2;
3654
+ if (!isBaseAction(_action) && _action.attachments) {
3655
+ _action.attachments.forEach((attachment) => {
3656
+ const { hash: hash22, ...file } = attachment;
3657
+ draft.attachments[hash22] = {
3658
+ ...file
3659
+ };
3660
+ });
3661
+ }
3662
+ });
3663
+ }
3664
+ function isNoopOperation(op) {
3665
+ return op.type === NOOP && op.skip !== void 0 && op.skip > 0 && op.hash !== void 0;
3666
+ }
3667
+ function isUndoRedo(action) {
3668
+ return [UNDO, REDO].includes(action.type);
3669
+ }
3670
+ function isBaseAction(action) {
3671
+ return [SET_NAME, UNDO, REDO, PRUNE, LOAD_STATE].includes(action.type);
3672
+ }
3673
+ function createAction(type, input, attachments, validator, scope = "global") {
3674
+ if (!type) {
3675
+ throw new Error("Empty action type");
3676
+ }
3677
+ if (typeof type !== "string") {
3678
+ throw new Error(`Invalid action type: ${JSON.stringify(type)}`);
3679
+ }
3680
+ const action = { type, input, scope };
3681
+ if (attachments) {
3682
+ action.attachments = attachments;
3683
+ }
3684
+ try {
3685
+ validator == null ? void 0 : validator().parse(action.input);
3686
+ } catch (error) {
3687
+ throw new Error(`Invalid action input: ${error}`);
3688
+ }
3689
+ return action;
3690
+ }
3691
+ function createReducer(reducer, documentReducer = baseReducer) {
3692
+ return (document, action, dispatch, options) => {
3693
+ return documentReducer(document, action, reducer, dispatch, options);
3694
+ };
3695
+ }
3696
+ const createExtendedState = (initialState, createState) => {
3697
+ return {
3698
+ name: "",
3699
+ documentType: "",
3700
+ revision: {
3701
+ global: 0,
3702
+ local: 0
3703
+ },
3704
+ created: (/* @__PURE__ */ new Date()).toISOString(),
3705
+ lastModified: (/* @__PURE__ */ new Date()).toISOString(),
3706
+ attachments: {},
3707
+ ...initialState,
3708
+ state: (createState == null ? void 0 : createState(initialState == null ? void 0 : initialState.state)) ?? ((initialState == null ? void 0 : initialState.state) ?? { global: {}, local: {} })
3709
+ };
3710
+ };
3711
+ const createDocument = (initialState, createState) => {
3712
+ const state = createExtendedState(
3713
+ initialState,
3714
+ createState
3715
+ );
3716
+ return {
3717
+ ...state,
3718
+ initialState: state,
3719
+ operations: { global: [], local: [] },
3720
+ clipboard: []
3721
+ };
3722
+ };
3723
+ const hashDocument = (document, scope = "global") => {
3724
+ return hash(cjsModule(document.state[scope] || ""));
3725
+ };
3726
+ const hashKey = (date, randomLimit = 1e3) => {
3727
+ const random = Math.random() * randomLimit;
3728
+ return hash(`${(date ?? /* @__PURE__ */ new Date()).toISOString()}${random}`);
3729
+ };
3730
+ function readOnly(value) {
3731
+ return castImmutable(freeze(value, true));
3732
+ }
3733
+ function mapSkippedOperations(operations, skippedHeadOperations) {
3734
+ const ops = [...operations];
3735
+ let skipped = skippedHeadOperations || 0;
3736
+ let latestOpIndex = ops.length > 0 ? ops[ops.length - 1].index : 0;
3737
+ const scopeOpsWithIgnore = [];
3738
+ for (const operation of ops.reverse()) {
3739
+ if (skipped > 0) {
3740
+ const operationsDiff = latestOpIndex - operation.index;
3741
+ skipped -= operationsDiff;
3742
+ }
3743
+ if (skipped < 0) {
3744
+ throw new Error("Invalid operation index, missing operations");
3745
+ }
3746
+ const mappedOp = {
3747
+ ignore: skipped > 0,
3748
+ operation
3749
+ };
3750
+ const operationSkip = operation.skip > 0 ? operation.skip + 1 : 0;
3751
+ if (operationSkip > 0 && operationSkip > skipped) {
3752
+ const skipDiff = operationSkip - skipped;
3753
+ skipped = skipped + skipDiff;
3754
+ }
3755
+ latestOpIndex = operation.index;
3756
+ scopeOpsWithIgnore.push(mappedOp);
3757
+ }
3758
+ return scopeOpsWithIgnore.reverse();
3759
+ }
3760
+ function calculateSkipsLeft(operations, currentIndex, skip) {
3761
+ const sortedOperations = operations.slice().sort((a, b) => a.skip - b.skip).sort((a, b) => a.index - b.index);
3762
+ let skipsLeft = skip;
3763
+ let skipsToPerform = 0;
3764
+ let lastIndex = currentIndex;
3765
+ for (const operation of sortedOperations.reverse()) {
3766
+ const distance = lastIndex - operation.index;
3767
+ skipsLeft = skipsLeft - distance;
3768
+ if (skipsLeft > -1) {
3769
+ skipsToPerform++;
3770
+ lastIndex = operation.index;
3771
+ } else {
3772
+ break;
3773
+ }
3774
+ }
3775
+ return skipsToPerform;
3776
+ }
3777
+ function sortOperations(operations) {
3778
+ return Object.values(operations).flatMap((array) => array).sort(
3779
+ (a, b) => new Date(a.timestamp).getTime() - new Date(b.timestamp).getTime()
3780
+ );
3781
+ }
3782
+ function sortMappedOperations(operations) {
3783
+ return Object.values(operations).flatMap((array) => array).sort(
3784
+ (a, b) => new Date(a.operation.timestamp).getTime() - new Date(b.operation.timestamp).getTime()
3785
+ );
3786
+ }
3787
+ function replayOperations(initialState, clearedOperations, reducer, dispatch, header, documentReducer = baseReducer, skipHeaderOperations2 = {}, options) {
3788
+ const wrappedReducer = createReducer(reducer, documentReducer);
3789
+ return replayDocument(
3790
+ initialState,
3791
+ clearedOperations,
3792
+ wrappedReducer,
3793
+ dispatch,
3794
+ header,
3795
+ skipHeaderOperations2,
3796
+ options
3797
+ );
3798
+ }
3799
+ function replayDocument(initialState, operations, reducer, dispatch, header, skipHeaderOperations2 = {}, options) {
3800
+ const checkHashes = (options == null ? void 0 : options.checkHashes) ?? true;
3801
+ const document = createDocument(initialState);
3802
+ const flatOperations = Object.values(operations).flat();
3803
+ const result = flatOperations.reduce((document2, operation) => {
3804
+ const doc = reducer(document2, operation, dispatch, {
3805
+ skip: operation.skip,
3806
+ ignoreSkipOperations: true,
3807
+ reuseHash: !checkHashes
3808
+ });
3809
+ return doc;
3810
+ }, document);
3811
+ if (!checkHashes) {
3812
+ for (const scope of Object.keys(result.state)) {
3813
+ for (let i = flatOperations.length - 1; i >= 0; i--) {
3814
+ const operation = flatOperations[i];
3815
+ if (operation.scope !== scope) {
3816
+ continue;
3817
+ }
3818
+ if (operation.hash !== hashDocument(result, scope)) {
3819
+ throw new Error(`Hash mismatch for scope ${scope}`);
3820
+ } else {
3821
+ break;
3822
+ }
3823
+ }
3824
+ }
3825
+ }
3826
+ const resultOperations = Object.keys(
3827
+ result.operations
3828
+ ).reduce(
3829
+ (acc, key) => {
3830
+ const scope = key;
3831
+ return {
3832
+ ...acc,
3833
+ [scope]: [
3834
+ ...result.operations[scope].map((operation, index) => {
3835
+ var _a;
3836
+ return {
3837
+ ...operation,
3838
+ timestamp: ((_a = operations[scope][index]) == null ? void 0 : _a.timestamp) ?? operation.timestamp
3839
+ };
3840
+ })
3841
+ ]
3842
+ };
3843
+ },
3844
+ { global: [], local: [] }
3845
+ );
3846
+ const lastModified = Object.values(resultOperations).reduce((acc, curr) => {
3847
+ const operation = curr[curr.length - 1];
3848
+ if ((operation == null ? void 0 : operation.timestamp) > acc) {
3849
+ acc = operation.timestamp;
3850
+ }
3851
+ return acc;
3852
+ }, initialState.lastModified);
3853
+ return { ...result, operations: resultOperations, lastModified };
3854
+ }
3855
+ function isSameDocument(documentA, documentB) {
3856
+ return cjsModule(documentA) === cjsModule(documentB);
3857
+ }
3858
+ const setName = (name) => createAction(
3859
+ "SET_NAME",
3860
+ name,
3861
+ void 0,
3862
+ SetNameActionInputSchema,
3863
+ void 0
3864
+ );
3865
+ const undo = (skip = 1, scope = "global") => createAction(
3866
+ "UNDO",
3867
+ skip,
3868
+ void 0,
3869
+ UndoActionInputSchema,
3870
+ scope
3871
+ );
3872
+ const redo = (count = 1, scope = "global") => createAction(
3873
+ "REDO",
3874
+ count,
3875
+ void 0,
3876
+ RedoActionInputSchema,
3877
+ scope
3878
+ );
3879
+ const prune = (start, end, scope = "global") => createAction(
3880
+ "PRUNE",
3881
+ { start, end },
3882
+ void 0,
3883
+ PruneActionInputSchema,
3884
+ scope
3885
+ );
3886
+ const loadState = (state, operations) => createAction(
3887
+ "LOAD_STATE",
3888
+ { state, operations },
3889
+ void 0,
3890
+ LoadStateActionInputSchema
3891
+ );
3892
+ const noop = (scope = "global") => createAction("NOOP", {}, void 0, void 0, scope);
3893
+ const BaseActions = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({
3894
+ __proto__: null,
3895
+ loadState,
3896
+ noop,
3897
+ prune,
3898
+ redo,
3899
+ setName,
3900
+ undo
3901
+ }, Symbol.toStringTag, { value: "Module" }));
3902
+ class BaseDocument {
3903
+ /**
3904
+ * Constructs a BaseDocument instance with an initial state.
3905
+ * @param reducer - The reducer function that updates the state.
3906
+ * @param document - The initial state of the document.
3907
+ */
3908
+ constructor(reducer, document, signalDispatch) {
3909
+ __publicField(this, "_document");
3910
+ __publicField(this, "_reducer");
3911
+ __publicField(this, "_signalDispatch");
3912
+ this._reducer = reducer;
3913
+ this._document = document;
3914
+ this._signalDispatch = signalDispatch;
3915
+ }
3916
+ /**
3917
+ * Dispatches an action to update the state of the document.
3918
+ * @param action - The action to dispatch.
3919
+ * @returns The Document instance.
3920
+ */
3921
+ dispatch(action, options) {
3922
+ this._document = this._reducer(
3923
+ this._document,
3924
+ action,
3925
+ this._signalDispatch,
3926
+ options
3927
+ );
3928
+ return this;
3929
+ }
3930
+ /**
3931
+ * Saves the state of the document to a file.
3932
+ * @param path - The file path where the state should be saved.
3933
+ * @param extension - The file extension to use when saving the state.
3934
+ * @returns The file path where the state was saved.
3935
+ */
3936
+ saveToFile(path, extension, name) {
3937
+ return saveToFile(this._document, path, extension, name);
3938
+ }
3939
+ /**
3940
+ * Loads the state of the document from a file.
3941
+ * @param path - The file path where the state is stored.
3942
+ */
3943
+ async loadFromFile(path) {
3944
+ this._document = await loadFromFile(path, this._reducer);
3945
+ }
3946
+ /**
3947
+ * Loads the state of the document from a file and returns it.
3948
+ * @param path - The file path where the state is stored.
3949
+ * @param reducer - The reducer function that updates the state.
3950
+ * @returns The state of the document.
3951
+ */
3952
+ static async stateFromFile(path, reducer) {
3953
+ const state = await loadFromFile(path, reducer);
3954
+ return state;
3955
+ }
3956
+ /**
3957
+ * Gets the current state of the document.
3958
+ */
3959
+ get state() {
3960
+ return readOnly(this._document.state);
3961
+ }
3962
+ /**
3963
+ * Gets the list of operations performed on the document.
3964
+ */
3965
+ get operations() {
3966
+ return readOnly(this._document.operations);
3967
+ }
3968
+ /**
3969
+ * Gets the name of the document.
3970
+ */
3971
+ get name() {
3972
+ return this._document.name;
3973
+ }
3974
+ /**
3975
+ * Gets the type of document.
3976
+ */
3977
+ get documentType() {
3978
+ return this._document.documentType;
3979
+ }
3980
+ /**
3981
+ * Gets the timestamp of the date the document was created.
3982
+ */
3983
+ get created() {
3984
+ return this._document.created;
3985
+ }
3986
+ /**
3987
+ * Gets the timestamp of the date the document was last modified.
3988
+ */
3989
+ get lastModified() {
3990
+ return this._document.lastModified;
3991
+ }
3992
+ /**
3993
+ * Gets the global revision number of the document.
3994
+ */
3995
+ get revision() {
3996
+ return this._document.revision.global;
3997
+ }
3998
+ getRevision(scope) {
3999
+ return this._document.revision[scope];
4000
+ }
4001
+ /**
4002
+ * Gets the initial state of the document.
4003
+ */
4004
+ get initialState() {
4005
+ return readOnly(this._document.initialState);
4006
+ }
4007
+ /**
4008
+ * Returns the current document as an object
4009
+ */
4010
+ toDocument() {
4011
+ return readOnly(this._document);
4012
+ }
4013
+ /**
4014
+ * Gets the attachment associated with the given key.
4015
+ * @param attachment - The key of the attachment to retrieve.
4016
+ */
4017
+ getAttachment(attachment) {
4018
+ return this._document.attachments[attachment];
4019
+ }
4020
+ /**
4021
+ * Sets the name of the document.
4022
+ * @param name - The new name of the document.
4023
+ */
4024
+ setName(name) {
4025
+ this.dispatch(setName(name));
4026
+ return this;
4027
+ }
4028
+ /**
4029
+ * Reverts a number of actions from the document.
4030
+ * @param count - The number of actions to revert.
4031
+ */
4032
+ undo(count) {
4033
+ this.dispatch(undo(count));
4034
+ return this;
4035
+ }
4036
+ /**
4037
+ * Reapplies a number of actions to the document.
4038
+ * @param count - The number of actions to reapply.
4039
+ */
4040
+ redo(count) {
4041
+ this.dispatch(redo(count));
4042
+ return this;
4043
+ }
4044
+ /**
4045
+ * Removes a range of operations from the document.
4046
+ * @param start - The starting index of the range to remove.
4047
+ * @param end - The ending index of the range to remove.
4048
+ */
4049
+ prune(start, end) {
4050
+ this.dispatch(prune(start, end));
4051
+ return this;
4052
+ }
4053
+ /**
4054
+ * Loads a document state and a set of operations.
4055
+ * @param state - The state to load.
4056
+ * @param operations - The operations to apply to the document.
4057
+ */
4058
+ loadState(state, operations) {
4059
+ this.dispatch(loadState(state, operations));
4060
+ return this;
4061
+ }
4062
+ }
4063
+ function applyMixins(derivedCtor, constructors) {
4064
+ constructors.forEach((baseCtor) => {
4065
+ Object.getOwnPropertyNames(baseCtor.prototype).forEach((name) => {
4066
+ Object.defineProperty(
4067
+ // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access
4068
+ derivedCtor.prototype,
4069
+ name,
4070
+ // eslint-disable-next-line @typescript-eslint/no-unsafe-argument, @typescript-eslint/no-unsafe-member-access
4071
+ Object.getOwnPropertyDescriptor(baseCtor.prototype, name) || /* @__PURE__ */ Object.create(null)
4072
+ );
4073
+ });
4074
+ });
4075
+ }
4076
+ export {
4077
+ sortOperations as A,
4078
+ BaseDocument as B,
4079
+ validateOperations as C,
4080
+ baseReducer as D,
4081
+ processUndoRedo as E,
4082
+ zod as F,
4083
+ createExtendedState as a,
4084
+ createDocument as b,
4085
+ createReducer as c,
4086
+ saveToFileHandle as d,
4087
+ loadFromInput as e,
4088
+ createAction as f,
4089
+ applyMixins as g,
4090
+ BaseActions as h,
4091
+ isBaseAction as i,
4092
+ calculateSkipsLeft as j,
4093
+ createZip as k,
4094
+ loadFromFile as l,
4095
+ documentHelpers as m,
4096
+ getLocalFile as n,
4097
+ getRemoteFile as o,
4098
+ hashDocument as p,
4099
+ hashKey as q,
4100
+ isNoopOperation as r,
4101
+ saveToFile as s,
4102
+ isSameDocument as t,
4103
+ isUndoRedo as u,
4104
+ mapSkippedOperations as v,
4105
+ readOnly as w,
4106
+ replayDocument as x,
4107
+ replayOperations as y,
4108
+ sortMappedOperations as z
4109
+ };
4110
+ //# sourceMappingURL=object-9mR1JlXD.js.map