nitro-patcher 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (44) hide show
  1. package/LICENSE +674 -0
  2. package/README.md +22 -0
  3. package/dist/browser.d.ts +34 -0
  4. package/dist/browser.js +4616 -0
  5. package/dist/browser.js.LEGAL.txt +147 -0
  6. package/dist/browser.js.map +7 -0
  7. package/dist/chunk-ANN47R34.js +1 -0
  8. package/dist/chunk-ANN47R34.js.map +1 -0
  9. package/dist/chunk-GFF67HX4.js +1181 -0
  10. package/dist/chunk-GFF67HX4.js.map +1 -0
  11. package/dist/chunk-L7ZM4LLP.js +396 -0
  12. package/dist/chunk-L7ZM4LLP.js.map +1 -0
  13. package/dist/cli.d.ts +1 -0
  14. package/dist/cli.js +76 -0
  15. package/dist/cli.js.map +1 -0
  16. package/dist/index.d.ts +2 -0
  17. package/dist/index.js +56 -0
  18. package/dist/index.js.map +1 -0
  19. package/dist/nitro-helper.d.ts +315 -0
  20. package/dist/nitro-helper.js +44 -0
  21. package/dist/nitro-helper.js.map +1 -0
  22. package/dist/nitro-patch-helper.d.ts +46 -0
  23. package/dist/nitro-patch-helper.js +16 -0
  24. package/dist/nitro-patch-helper.js.map +1 -0
  25. package/package.json +86 -0
  26. package/src/browser/buffer.ts +1 -0
  27. package/src/browser.ts +60 -0
  28. package/src/cli.ts +76 -0
  29. package/src/index.ts +2 -0
  30. package/src/nitro/banner.ts +77 -0
  31. package/src/nitro/binary.ts +80 -0
  32. package/src/nitro/blz.ts +163 -0
  33. package/src/nitro/crc.ts +23 -0
  34. package/src/nitro/crypto.ts +178 -0
  35. package/src/nitro/filesystem.ts +183 -0
  36. package/src/nitro/header.ts +254 -0
  37. package/src/nitro/nds-file.ts +285 -0
  38. package/src/nitro/twl.ts +338 -0
  39. package/src/nitro-helper.ts +14 -0
  40. package/src/nitro-patch-helper.ts +95 -0
  41. package/src/patch/xdelta.ts +214 -0
  42. package/src/patch/zip.ts +206 -0
  43. package/src/runtime/browser.ts +40 -0
  44. package/src/runtime/node.ts +28 -0
@@ -0,0 +1,4616 @@
1
+ var __create = Object.create;
2
+ var __defProp = Object.defineProperty;
3
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
4
+ var __getOwnPropNames = Object.getOwnPropertyNames;
5
+ var __getProtoOf = Object.getPrototypeOf;
6
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
7
+ var __esm = (fn, res) => function __init() {
8
+ return fn && (res = (0, fn[__getOwnPropNames(fn)[0]])(fn = 0)), res;
9
+ };
10
+ var __commonJS = (cb, mod) => function __require() {
11
+ return mod || (0, cb[__getOwnPropNames(cb)[0]])((mod = { exports: {} }).exports, mod), mod.exports;
12
+ };
13
+ var __copyProps = (to, from, except, desc) => {
14
+ if (from && typeof from === "object" || typeof from === "function") {
15
+ for (let key2 of __getOwnPropNames(from))
16
+ if (!__hasOwnProp.call(to, key2) && key2 !== except)
17
+ __defProp(to, key2, { get: () => from[key2], enumerable: !(desc = __getOwnPropDesc(from, key2)) || desc.enumerable });
18
+ }
19
+ return to;
20
+ };
21
+ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
22
+ // If the importer is in node compatibility mode or this is not an ESM
23
+ // file that has been converted to a CommonJS file using a Babel-
24
+ // compatible transform (i.e. "__esModule" has not been set), then set
25
+ // "default" to the CommonJS "module.exports" for node compatibility.
26
+ isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
27
+ mod
28
+ ));
29
+
30
+ // node_modules/.pnpm/base64-js@1.5.1/node_modules/base64-js/index.js
31
+ var require_base64_js = __commonJS({
32
+ "node_modules/.pnpm/base64-js@1.5.1/node_modules/base64-js/index.js"(exports) {
33
+ "use strict";
34
+ init_buffer();
35
+ exports.byteLength = byteLength;
36
+ exports.toByteArray = toByteArray;
37
+ exports.fromByteArray = fromByteArray;
38
+ var lookup = [];
39
+ var revLookup = [];
40
+ var Arr = typeof Uint8Array !== "undefined" ? Uint8Array : Array;
41
+ var code = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
42
+ for (i = 0, len = code.length; i < len; ++i) {
43
+ lookup[i] = code[i];
44
+ revLookup[code.charCodeAt(i)] = i;
45
+ }
46
+ var i;
47
+ var len;
48
+ revLookup["-".charCodeAt(0)] = 62;
49
+ revLookup["_".charCodeAt(0)] = 63;
50
+ function getLens(b64) {
51
+ var len2 = b64.length;
52
+ if (len2 % 4 > 0) {
53
+ throw new Error("Invalid string. Length must be a multiple of 4");
54
+ }
55
+ var validLen = b64.indexOf("=");
56
+ if (validLen === -1) validLen = len2;
57
+ var placeHoldersLen = validLen === len2 ? 0 : 4 - validLen % 4;
58
+ return [validLen, placeHoldersLen];
59
+ }
60
+ function byteLength(b64) {
61
+ var lens = getLens(b64);
62
+ var validLen = lens[0];
63
+ var placeHoldersLen = lens[1];
64
+ return (validLen + placeHoldersLen) * 3 / 4 - placeHoldersLen;
65
+ }
66
+ function _byteLength(b64, validLen, placeHoldersLen) {
67
+ return (validLen + placeHoldersLen) * 3 / 4 - placeHoldersLen;
68
+ }
69
+ function toByteArray(b64) {
70
+ var tmp;
71
+ var lens = getLens(b64);
72
+ var validLen = lens[0];
73
+ var placeHoldersLen = lens[1];
74
+ var arr = new Arr(_byteLength(b64, validLen, placeHoldersLen));
75
+ var curByte = 0;
76
+ var len2 = placeHoldersLen > 0 ? validLen - 4 : validLen;
77
+ var i2;
78
+ for (i2 = 0; i2 < len2; i2 += 4) {
79
+ tmp = revLookup[b64.charCodeAt(i2)] << 18 | revLookup[b64.charCodeAt(i2 + 1)] << 12 | revLookup[b64.charCodeAt(i2 + 2)] << 6 | revLookup[b64.charCodeAt(i2 + 3)];
80
+ arr[curByte++] = tmp >> 16 & 255;
81
+ arr[curByte++] = tmp >> 8 & 255;
82
+ arr[curByte++] = tmp & 255;
83
+ }
84
+ if (placeHoldersLen === 2) {
85
+ tmp = revLookup[b64.charCodeAt(i2)] << 2 | revLookup[b64.charCodeAt(i2 + 1)] >> 4;
86
+ arr[curByte++] = tmp & 255;
87
+ }
88
+ if (placeHoldersLen === 1) {
89
+ tmp = revLookup[b64.charCodeAt(i2)] << 10 | revLookup[b64.charCodeAt(i2 + 1)] << 4 | revLookup[b64.charCodeAt(i2 + 2)] >> 2;
90
+ arr[curByte++] = tmp >> 8 & 255;
91
+ arr[curByte++] = tmp & 255;
92
+ }
93
+ return arr;
94
+ }
95
+ function tripletToBase64(num) {
96
+ return lookup[num >> 18 & 63] + lookup[num >> 12 & 63] + lookup[num >> 6 & 63] + lookup[num & 63];
97
+ }
98
+ function encodeChunk(uint8, start, end) {
99
+ var tmp;
100
+ var output = [];
101
+ for (var i2 = start; i2 < end; i2 += 3) {
102
+ tmp = (uint8[i2] << 16 & 16711680) + (uint8[i2 + 1] << 8 & 65280) + (uint8[i2 + 2] & 255);
103
+ output.push(tripletToBase64(tmp));
104
+ }
105
+ return output.join("");
106
+ }
107
+ function fromByteArray(uint8) {
108
+ var tmp;
109
+ var len2 = uint8.length;
110
+ var extraBytes = len2 % 3;
111
+ var parts = [];
112
+ var maxChunkLength = 16383;
113
+ for (var i2 = 0, len22 = len2 - extraBytes; i2 < len22; i2 += maxChunkLength) {
114
+ parts.push(encodeChunk(uint8, i2, i2 + maxChunkLength > len22 ? len22 : i2 + maxChunkLength));
115
+ }
116
+ if (extraBytes === 1) {
117
+ tmp = uint8[len2 - 1];
118
+ parts.push(
119
+ lookup[tmp >> 2] + lookup[tmp << 4 & 63] + "=="
120
+ );
121
+ } else if (extraBytes === 2) {
122
+ tmp = (uint8[len2 - 2] << 8) + uint8[len2 - 1];
123
+ parts.push(
124
+ lookup[tmp >> 10] + lookup[tmp >> 4 & 63] + lookup[tmp << 2 & 63] + "="
125
+ );
126
+ }
127
+ return parts.join("");
128
+ }
129
+ }
130
+ });
131
+
132
+ // node_modules/.pnpm/ieee754@1.2.1/node_modules/ieee754/index.js
133
+ var require_ieee754 = __commonJS({
134
+ "node_modules/.pnpm/ieee754@1.2.1/node_modules/ieee754/index.js"(exports) {
135
+ init_buffer();
136
+ exports.read = function(buffer, offset, isLE2, mLen, nBytes) {
137
+ var e, m;
138
+ var eLen = nBytes * 8 - mLen - 1;
139
+ var eMax = (1 << eLen) - 1;
140
+ var eBias = eMax >> 1;
141
+ var nBits = -7;
142
+ var i = isLE2 ? nBytes - 1 : 0;
143
+ var d = isLE2 ? -1 : 1;
144
+ var s = buffer[offset + i];
145
+ i += d;
146
+ e = s & (1 << -nBits) - 1;
147
+ s >>= -nBits;
148
+ nBits += eLen;
149
+ for (; nBits > 0; e = e * 256 + buffer[offset + i], i += d, nBits -= 8) {
150
+ }
151
+ m = e & (1 << -nBits) - 1;
152
+ e >>= -nBits;
153
+ nBits += mLen;
154
+ for (; nBits > 0; m = m * 256 + buffer[offset + i], i += d, nBits -= 8) {
155
+ }
156
+ if (e === 0) {
157
+ e = 1 - eBias;
158
+ } else if (e === eMax) {
159
+ return m ? NaN : (s ? -1 : 1) * Infinity;
160
+ } else {
161
+ m = m + Math.pow(2, mLen);
162
+ e = e - eBias;
163
+ }
164
+ return (s ? -1 : 1) * m * Math.pow(2, e - mLen);
165
+ };
166
+ exports.write = function(buffer, value, offset, isLE2, mLen, nBytes) {
167
+ var e, m, c;
168
+ var eLen = nBytes * 8 - mLen - 1;
169
+ var eMax = (1 << eLen) - 1;
170
+ var eBias = eMax >> 1;
171
+ var rt = mLen === 23 ? Math.pow(2, -24) - Math.pow(2, -77) : 0;
172
+ var i = isLE2 ? 0 : nBytes - 1;
173
+ var d = isLE2 ? 1 : -1;
174
+ var s = value < 0 || value === 0 && 1 / value < 0 ? 1 : 0;
175
+ value = Math.abs(value);
176
+ if (isNaN(value) || value === Infinity) {
177
+ m = isNaN(value) ? 1 : 0;
178
+ e = eMax;
179
+ } else {
180
+ e = Math.floor(Math.log(value) / Math.LN2);
181
+ if (value * (c = Math.pow(2, -e)) < 1) {
182
+ e--;
183
+ c *= 2;
184
+ }
185
+ if (e + eBias >= 1) {
186
+ value += rt / c;
187
+ } else {
188
+ value += rt * Math.pow(2, 1 - eBias);
189
+ }
190
+ if (value * c >= 2) {
191
+ e++;
192
+ c /= 2;
193
+ }
194
+ if (e + eBias >= eMax) {
195
+ m = 0;
196
+ e = eMax;
197
+ } else if (e + eBias >= 1) {
198
+ m = (value * c - 1) * Math.pow(2, mLen);
199
+ e = e + eBias;
200
+ } else {
201
+ m = value * Math.pow(2, eBias - 1) * Math.pow(2, mLen);
202
+ e = 0;
203
+ }
204
+ }
205
+ for (; mLen >= 8; buffer[offset + i] = m & 255, i += d, m /= 256, mLen -= 8) {
206
+ }
207
+ e = e << mLen | m;
208
+ eLen += mLen;
209
+ for (; eLen > 0; buffer[offset + i] = e & 255, i += d, e /= 256, eLen -= 8) {
210
+ }
211
+ buffer[offset + i - d] |= s * 128;
212
+ };
213
+ }
214
+ });
215
+
216
+ // node_modules/.pnpm/buffer@6.0.3/node_modules/buffer/index.js
217
+ var require_buffer = __commonJS({
218
+ "node_modules/.pnpm/buffer@6.0.3/node_modules/buffer/index.js"(exports) {
219
+ "use strict";
220
+ init_buffer();
221
+ var base64 = require_base64_js();
222
+ var ieee754 = require_ieee754();
223
+ var customInspectSymbol = typeof Symbol === "function" && typeof Symbol["for"] === "function" ? Symbol["for"]("nodejs.util.inspect.custom") : null;
224
+ exports.Buffer = Buffer3;
225
+ exports.SlowBuffer = SlowBuffer;
226
+ exports.INSPECT_MAX_BYTES = 50;
227
+ var K_MAX_LENGTH = 2147483647;
228
+ exports.kMaxLength = K_MAX_LENGTH;
229
+ Buffer3.TYPED_ARRAY_SUPPORT = typedArraySupport();
230
+ if (!Buffer3.TYPED_ARRAY_SUPPORT && typeof console !== "undefined" && typeof console.error === "function") {
231
+ console.error(
232
+ "This browser lacks typed array (Uint8Array) support which is required by `buffer` v5.x. Use `buffer` v4.x if you require old browser support."
233
+ );
234
+ }
235
+ function typedArraySupport() {
236
+ try {
237
+ const arr = new Uint8Array(1);
238
+ const proto = { foo: function() {
239
+ return 42;
240
+ } };
241
+ Object.setPrototypeOf(proto, Uint8Array.prototype);
242
+ Object.setPrototypeOf(arr, proto);
243
+ return arr.foo() === 42;
244
+ } catch (e) {
245
+ return false;
246
+ }
247
+ }
248
+ Object.defineProperty(Buffer3.prototype, "parent", {
249
+ enumerable: true,
250
+ get: function() {
251
+ if (!Buffer3.isBuffer(this)) return void 0;
252
+ return this.buffer;
253
+ }
254
+ });
255
+ Object.defineProperty(Buffer3.prototype, "offset", {
256
+ enumerable: true,
257
+ get: function() {
258
+ if (!Buffer3.isBuffer(this)) return void 0;
259
+ return this.byteOffset;
260
+ }
261
+ });
262
+ function createBuffer(length) {
263
+ if (length > K_MAX_LENGTH) {
264
+ throw new RangeError('The value "' + length + '" is invalid for option "size"');
265
+ }
266
+ const buf = new Uint8Array(length);
267
+ Object.setPrototypeOf(buf, Buffer3.prototype);
268
+ return buf;
269
+ }
270
+ function Buffer3(arg, encodingOrOffset, length) {
271
+ if (typeof arg === "number") {
272
+ if (typeof encodingOrOffset === "string") {
273
+ throw new TypeError(
274
+ 'The "string" argument must be of type string. Received type number'
275
+ );
276
+ }
277
+ return allocUnsafe(arg);
278
+ }
279
+ return from(arg, encodingOrOffset, length);
280
+ }
281
+ Buffer3.poolSize = 8192;
282
+ function from(value, encodingOrOffset, length) {
283
+ if (typeof value === "string") {
284
+ return fromString(value, encodingOrOffset);
285
+ }
286
+ if (ArrayBuffer.isView(value)) {
287
+ return fromArrayView(value);
288
+ }
289
+ if (value == null) {
290
+ throw new TypeError(
291
+ "The first argument must be one of type string, Buffer, ArrayBuffer, Array, or Array-like Object. Received type " + typeof value
292
+ );
293
+ }
294
+ if (isInstance(value, ArrayBuffer) || value && isInstance(value.buffer, ArrayBuffer)) {
295
+ return fromArrayBuffer(value, encodingOrOffset, length);
296
+ }
297
+ if (typeof SharedArrayBuffer !== "undefined" && (isInstance(value, SharedArrayBuffer) || value && isInstance(value.buffer, SharedArrayBuffer))) {
298
+ return fromArrayBuffer(value, encodingOrOffset, length);
299
+ }
300
+ if (typeof value === "number") {
301
+ throw new TypeError(
302
+ 'The "value" argument must not be of type number. Received type number'
303
+ );
304
+ }
305
+ const valueOf = value.valueOf && value.valueOf();
306
+ if (valueOf != null && valueOf !== value) {
307
+ return Buffer3.from(valueOf, encodingOrOffset, length);
308
+ }
309
+ const b = fromObject(value);
310
+ if (b) return b;
311
+ if (typeof Symbol !== "undefined" && Symbol.toPrimitive != null && typeof value[Symbol.toPrimitive] === "function") {
312
+ return Buffer3.from(value[Symbol.toPrimitive]("string"), encodingOrOffset, length);
313
+ }
314
+ throw new TypeError(
315
+ "The first argument must be one of type string, Buffer, ArrayBuffer, Array, or Array-like Object. Received type " + typeof value
316
+ );
317
+ }
318
+ Buffer3.from = function(value, encodingOrOffset, length) {
319
+ return from(value, encodingOrOffset, length);
320
+ };
321
+ Object.setPrototypeOf(Buffer3.prototype, Uint8Array.prototype);
322
+ Object.setPrototypeOf(Buffer3, Uint8Array);
323
+ function assertSize(size) {
324
+ if (typeof size !== "number") {
325
+ throw new TypeError('"size" argument must be of type number');
326
+ } else if (size < 0) {
327
+ throw new RangeError('The value "' + size + '" is invalid for option "size"');
328
+ }
329
+ }
330
+ function alloc(size, fill, encoding) {
331
+ assertSize(size);
332
+ if (size <= 0) {
333
+ return createBuffer(size);
334
+ }
335
+ if (fill !== void 0) {
336
+ return typeof encoding === "string" ? createBuffer(size).fill(fill, encoding) : createBuffer(size).fill(fill);
337
+ }
338
+ return createBuffer(size);
339
+ }
340
+ Buffer3.alloc = function(size, fill, encoding) {
341
+ return alloc(size, fill, encoding);
342
+ };
343
+ function allocUnsafe(size) {
344
+ assertSize(size);
345
+ return createBuffer(size < 0 ? 0 : checked(size) | 0);
346
+ }
347
+ Buffer3.allocUnsafe = function(size) {
348
+ return allocUnsafe(size);
349
+ };
350
+ Buffer3.allocUnsafeSlow = function(size) {
351
+ return allocUnsafe(size);
352
+ };
353
+ function fromString(string, encoding) {
354
+ if (typeof encoding !== "string" || encoding === "") {
355
+ encoding = "utf8";
356
+ }
357
+ if (!Buffer3.isEncoding(encoding)) {
358
+ throw new TypeError("Unknown encoding: " + encoding);
359
+ }
360
+ const length = byteLength(string, encoding) | 0;
361
+ let buf = createBuffer(length);
362
+ const actual = buf.write(string, encoding);
363
+ if (actual !== length) {
364
+ buf = buf.slice(0, actual);
365
+ }
366
+ return buf;
367
+ }
368
+ function fromArrayLike(array) {
369
+ const length = array.length < 0 ? 0 : checked(array.length) | 0;
370
+ const buf = createBuffer(length);
371
+ for (let i = 0; i < length; i += 1) {
372
+ buf[i] = array[i] & 255;
373
+ }
374
+ return buf;
375
+ }
376
+ function fromArrayView(arrayView) {
377
+ if (isInstance(arrayView, Uint8Array)) {
378
+ const copy = new Uint8Array(arrayView);
379
+ return fromArrayBuffer(copy.buffer, copy.byteOffset, copy.byteLength);
380
+ }
381
+ return fromArrayLike(arrayView);
382
+ }
383
+ function fromArrayBuffer(array, byteOffset, length) {
384
+ if (byteOffset < 0 || array.byteLength < byteOffset) {
385
+ throw new RangeError('"offset" is outside of buffer bounds');
386
+ }
387
+ if (array.byteLength < byteOffset + (length || 0)) {
388
+ throw new RangeError('"length" is outside of buffer bounds');
389
+ }
390
+ let buf;
391
+ if (byteOffset === void 0 && length === void 0) {
392
+ buf = new Uint8Array(array);
393
+ } else if (length === void 0) {
394
+ buf = new Uint8Array(array, byteOffset);
395
+ } else {
396
+ buf = new Uint8Array(array, byteOffset, length);
397
+ }
398
+ Object.setPrototypeOf(buf, Buffer3.prototype);
399
+ return buf;
400
+ }
401
+ function fromObject(obj) {
402
+ if (Buffer3.isBuffer(obj)) {
403
+ const len = checked(obj.length) | 0;
404
+ const buf = createBuffer(len);
405
+ if (buf.length === 0) {
406
+ return buf;
407
+ }
408
+ obj.copy(buf, 0, 0, len);
409
+ return buf;
410
+ }
411
+ if (obj.length !== void 0) {
412
+ if (typeof obj.length !== "number" || numberIsNaN(obj.length)) {
413
+ return createBuffer(0);
414
+ }
415
+ return fromArrayLike(obj);
416
+ }
417
+ if (obj.type === "Buffer" && Array.isArray(obj.data)) {
418
+ return fromArrayLike(obj.data);
419
+ }
420
+ }
421
+ function checked(length) {
422
+ if (length >= K_MAX_LENGTH) {
423
+ throw new RangeError("Attempt to allocate Buffer larger than maximum size: 0x" + K_MAX_LENGTH.toString(16) + " bytes");
424
+ }
425
+ return length | 0;
426
+ }
427
+ function SlowBuffer(length) {
428
+ if (+length != length) {
429
+ length = 0;
430
+ }
431
+ return Buffer3.alloc(+length);
432
+ }
433
+ Buffer3.isBuffer = function isBuffer(b) {
434
+ return b != null && b._isBuffer === true && b !== Buffer3.prototype;
435
+ };
436
+ Buffer3.compare = function compare(a, b) {
437
+ if (isInstance(a, Uint8Array)) a = Buffer3.from(a, a.offset, a.byteLength);
438
+ if (isInstance(b, Uint8Array)) b = Buffer3.from(b, b.offset, b.byteLength);
439
+ if (!Buffer3.isBuffer(a) || !Buffer3.isBuffer(b)) {
440
+ throw new TypeError(
441
+ 'The "buf1", "buf2" arguments must be one of type Buffer or Uint8Array'
442
+ );
443
+ }
444
+ if (a === b) return 0;
445
+ let x = a.length;
446
+ let y = b.length;
447
+ for (let i = 0, len = Math.min(x, y); i < len; ++i) {
448
+ if (a[i] !== b[i]) {
449
+ x = a[i];
450
+ y = b[i];
451
+ break;
452
+ }
453
+ }
454
+ if (x < y) return -1;
455
+ if (y < x) return 1;
456
+ return 0;
457
+ };
458
+ Buffer3.isEncoding = function isEncoding(encoding) {
459
+ switch (String(encoding).toLowerCase()) {
460
+ case "hex":
461
+ case "utf8":
462
+ case "utf-8":
463
+ case "ascii":
464
+ case "latin1":
465
+ case "binary":
466
+ case "base64":
467
+ case "ucs2":
468
+ case "ucs-2":
469
+ case "utf16le":
470
+ case "utf-16le":
471
+ return true;
472
+ default:
473
+ return false;
474
+ }
475
+ };
476
+ Buffer3.concat = function concat(list, length) {
477
+ if (!Array.isArray(list)) {
478
+ throw new TypeError('"list" argument must be an Array of Buffers');
479
+ }
480
+ if (list.length === 0) {
481
+ return Buffer3.alloc(0);
482
+ }
483
+ let i;
484
+ if (length === void 0) {
485
+ length = 0;
486
+ for (i = 0; i < list.length; ++i) {
487
+ length += list[i].length;
488
+ }
489
+ }
490
+ const buffer = Buffer3.allocUnsafe(length);
491
+ let pos = 0;
492
+ for (i = 0; i < list.length; ++i) {
493
+ let buf = list[i];
494
+ if (isInstance(buf, Uint8Array)) {
495
+ if (pos + buf.length > buffer.length) {
496
+ if (!Buffer3.isBuffer(buf)) buf = Buffer3.from(buf);
497
+ buf.copy(buffer, pos);
498
+ } else {
499
+ Uint8Array.prototype.set.call(
500
+ buffer,
501
+ buf,
502
+ pos
503
+ );
504
+ }
505
+ } else if (!Buffer3.isBuffer(buf)) {
506
+ throw new TypeError('"list" argument must be an Array of Buffers');
507
+ } else {
508
+ buf.copy(buffer, pos);
509
+ }
510
+ pos += buf.length;
511
+ }
512
+ return buffer;
513
+ };
514
+ function byteLength(string, encoding) {
515
+ if (Buffer3.isBuffer(string)) {
516
+ return string.length;
517
+ }
518
+ if (ArrayBuffer.isView(string) || isInstance(string, ArrayBuffer)) {
519
+ return string.byteLength;
520
+ }
521
+ if (typeof string !== "string") {
522
+ throw new TypeError(
523
+ 'The "string" argument must be one of type string, Buffer, or ArrayBuffer. Received type ' + typeof string
524
+ );
525
+ }
526
+ const len = string.length;
527
+ const mustMatch = arguments.length > 2 && arguments[2] === true;
528
+ if (!mustMatch && len === 0) return 0;
529
+ let loweredCase = false;
530
+ for (; ; ) {
531
+ switch (encoding) {
532
+ case "ascii":
533
+ case "latin1":
534
+ case "binary":
535
+ return len;
536
+ case "utf8":
537
+ case "utf-8":
538
+ return utf8ToBytes(string).length;
539
+ case "ucs2":
540
+ case "ucs-2":
541
+ case "utf16le":
542
+ case "utf-16le":
543
+ return len * 2;
544
+ case "hex":
545
+ return len >>> 1;
546
+ case "base64":
547
+ return base64ToBytes(string).length;
548
+ default:
549
+ if (loweredCase) {
550
+ return mustMatch ? -1 : utf8ToBytes(string).length;
551
+ }
552
+ encoding = ("" + encoding).toLowerCase();
553
+ loweredCase = true;
554
+ }
555
+ }
556
+ }
557
+ Buffer3.byteLength = byteLength;
558
+ function slowToString(encoding, start, end) {
559
+ let loweredCase = false;
560
+ if (start === void 0 || start < 0) {
561
+ start = 0;
562
+ }
563
+ if (start > this.length) {
564
+ return "";
565
+ }
566
+ if (end === void 0 || end > this.length) {
567
+ end = this.length;
568
+ }
569
+ if (end <= 0) {
570
+ return "";
571
+ }
572
+ end >>>= 0;
573
+ start >>>= 0;
574
+ if (end <= start) {
575
+ return "";
576
+ }
577
+ if (!encoding) encoding = "utf8";
578
+ while (true) {
579
+ switch (encoding) {
580
+ case "hex":
581
+ return hexSlice(this, start, end);
582
+ case "utf8":
583
+ case "utf-8":
584
+ return utf8Slice(this, start, end);
585
+ case "ascii":
586
+ return asciiSlice(this, start, end);
587
+ case "latin1":
588
+ case "binary":
589
+ return latin1Slice(this, start, end);
590
+ case "base64":
591
+ return base64Slice(this, start, end);
592
+ case "ucs2":
593
+ case "ucs-2":
594
+ case "utf16le":
595
+ case "utf-16le":
596
+ return utf16leSlice(this, start, end);
597
+ default:
598
+ if (loweredCase) throw new TypeError("Unknown encoding: " + encoding);
599
+ encoding = (encoding + "").toLowerCase();
600
+ loweredCase = true;
601
+ }
602
+ }
603
+ }
604
+ Buffer3.prototype._isBuffer = true;
605
+ function swap(b, n, m) {
606
+ const i = b[n];
607
+ b[n] = b[m];
608
+ b[m] = i;
609
+ }
610
+ Buffer3.prototype.swap16 = function swap16() {
611
+ const len = this.length;
612
+ if (len % 2 !== 0) {
613
+ throw new RangeError("Buffer size must be a multiple of 16-bits");
614
+ }
615
+ for (let i = 0; i < len; i += 2) {
616
+ swap(this, i, i + 1);
617
+ }
618
+ return this;
619
+ };
620
+ Buffer3.prototype.swap32 = function swap32() {
621
+ const len = this.length;
622
+ if (len % 4 !== 0) {
623
+ throw new RangeError("Buffer size must be a multiple of 32-bits");
624
+ }
625
+ for (let i = 0; i < len; i += 4) {
626
+ swap(this, i, i + 3);
627
+ swap(this, i + 1, i + 2);
628
+ }
629
+ return this;
630
+ };
631
+ Buffer3.prototype.swap64 = function swap64() {
632
+ const len = this.length;
633
+ if (len % 8 !== 0) {
634
+ throw new RangeError("Buffer size must be a multiple of 64-bits");
635
+ }
636
+ for (let i = 0; i < len; i += 8) {
637
+ swap(this, i, i + 7);
638
+ swap(this, i + 1, i + 6);
639
+ swap(this, i + 2, i + 5);
640
+ swap(this, i + 3, i + 4);
641
+ }
642
+ return this;
643
+ };
644
+ Buffer3.prototype.toString = function toString() {
645
+ const length = this.length;
646
+ if (length === 0) return "";
647
+ if (arguments.length === 0) return utf8Slice(this, 0, length);
648
+ return slowToString.apply(this, arguments);
649
+ };
650
+ Buffer3.prototype.toLocaleString = Buffer3.prototype.toString;
651
+ Buffer3.prototype.equals = function equals(b) {
652
+ if (!Buffer3.isBuffer(b)) throw new TypeError("Argument must be a Buffer");
653
+ if (this === b) return true;
654
+ return Buffer3.compare(this, b) === 0;
655
+ };
656
+ Buffer3.prototype.inspect = function inspect() {
657
+ let str = "";
658
+ const max2 = exports.INSPECT_MAX_BYTES;
659
+ str = this.toString("hex", 0, max2).replace(/(.{2})/g, "$1 ").trim();
660
+ if (this.length > max2) str += " ... ";
661
+ return "<Buffer " + str + ">";
662
+ };
663
+ if (customInspectSymbol) {
664
+ Buffer3.prototype[customInspectSymbol] = Buffer3.prototype.inspect;
665
+ }
666
+ Buffer3.prototype.compare = function compare(target, start, end, thisStart, thisEnd) {
667
+ if (isInstance(target, Uint8Array)) {
668
+ target = Buffer3.from(target, target.offset, target.byteLength);
669
+ }
670
+ if (!Buffer3.isBuffer(target)) {
671
+ throw new TypeError(
672
+ 'The "target" argument must be one of type Buffer or Uint8Array. Received type ' + typeof target
673
+ );
674
+ }
675
+ if (start === void 0) {
676
+ start = 0;
677
+ }
678
+ if (end === void 0) {
679
+ end = target ? target.length : 0;
680
+ }
681
+ if (thisStart === void 0) {
682
+ thisStart = 0;
683
+ }
684
+ if (thisEnd === void 0) {
685
+ thisEnd = this.length;
686
+ }
687
+ if (start < 0 || end > target.length || thisStart < 0 || thisEnd > this.length) {
688
+ throw new RangeError("out of range index");
689
+ }
690
+ if (thisStart >= thisEnd && start >= end) {
691
+ return 0;
692
+ }
693
+ if (thisStart >= thisEnd) {
694
+ return -1;
695
+ }
696
+ if (start >= end) {
697
+ return 1;
698
+ }
699
+ start >>>= 0;
700
+ end >>>= 0;
701
+ thisStart >>>= 0;
702
+ thisEnd >>>= 0;
703
+ if (this === target) return 0;
704
+ let x = thisEnd - thisStart;
705
+ let y = end - start;
706
+ const len = Math.min(x, y);
707
+ const thisCopy = this.slice(thisStart, thisEnd);
708
+ const targetCopy = target.slice(start, end);
709
+ for (let i = 0; i < len; ++i) {
710
+ if (thisCopy[i] !== targetCopy[i]) {
711
+ x = thisCopy[i];
712
+ y = targetCopy[i];
713
+ break;
714
+ }
715
+ }
716
+ if (x < y) return -1;
717
+ if (y < x) return 1;
718
+ return 0;
719
+ };
720
+ function bidirectionalIndexOf(buffer, val, byteOffset, encoding, dir) {
721
+ if (buffer.length === 0) return -1;
722
+ if (typeof byteOffset === "string") {
723
+ encoding = byteOffset;
724
+ byteOffset = 0;
725
+ } else if (byteOffset > 2147483647) {
726
+ byteOffset = 2147483647;
727
+ } else if (byteOffset < -2147483648) {
728
+ byteOffset = -2147483648;
729
+ }
730
+ byteOffset = +byteOffset;
731
+ if (numberIsNaN(byteOffset)) {
732
+ byteOffset = dir ? 0 : buffer.length - 1;
733
+ }
734
+ if (byteOffset < 0) byteOffset = buffer.length + byteOffset;
735
+ if (byteOffset >= buffer.length) {
736
+ if (dir) return -1;
737
+ else byteOffset = buffer.length - 1;
738
+ } else if (byteOffset < 0) {
739
+ if (dir) byteOffset = 0;
740
+ else return -1;
741
+ }
742
+ if (typeof val === "string") {
743
+ val = Buffer3.from(val, encoding);
744
+ }
745
+ if (Buffer3.isBuffer(val)) {
746
+ if (val.length === 0) {
747
+ return -1;
748
+ }
749
+ return arrayIndexOf(buffer, val, byteOffset, encoding, dir);
750
+ } else if (typeof val === "number") {
751
+ val = val & 255;
752
+ if (typeof Uint8Array.prototype.indexOf === "function") {
753
+ if (dir) {
754
+ return Uint8Array.prototype.indexOf.call(buffer, val, byteOffset);
755
+ } else {
756
+ return Uint8Array.prototype.lastIndexOf.call(buffer, val, byteOffset);
757
+ }
758
+ }
759
+ return arrayIndexOf(buffer, [val], byteOffset, encoding, dir);
760
+ }
761
+ throw new TypeError("val must be string, number or Buffer");
762
+ }
763
+ function arrayIndexOf(arr, val, byteOffset, encoding, dir) {
764
+ let indexSize = 1;
765
+ let arrLength = arr.length;
766
+ let valLength = val.length;
767
+ if (encoding !== void 0) {
768
+ encoding = String(encoding).toLowerCase();
769
+ if (encoding === "ucs2" || encoding === "ucs-2" || encoding === "utf16le" || encoding === "utf-16le") {
770
+ if (arr.length < 2 || val.length < 2) {
771
+ return -1;
772
+ }
773
+ indexSize = 2;
774
+ arrLength /= 2;
775
+ valLength /= 2;
776
+ byteOffset /= 2;
777
+ }
778
+ }
779
+ function read(buf, i2) {
780
+ if (indexSize === 1) {
781
+ return buf[i2];
782
+ } else {
783
+ return buf.readUInt16BE(i2 * indexSize);
784
+ }
785
+ }
786
+ let i;
787
+ if (dir) {
788
+ let foundIndex = -1;
789
+ for (i = byteOffset; i < arrLength; i++) {
790
+ if (read(arr, i) === read(val, foundIndex === -1 ? 0 : i - foundIndex)) {
791
+ if (foundIndex === -1) foundIndex = i;
792
+ if (i - foundIndex + 1 === valLength) return foundIndex * indexSize;
793
+ } else {
794
+ if (foundIndex !== -1) i -= i - foundIndex;
795
+ foundIndex = -1;
796
+ }
797
+ }
798
+ } else {
799
+ if (byteOffset + valLength > arrLength) byteOffset = arrLength - valLength;
800
+ for (i = byteOffset; i >= 0; i--) {
801
+ let found = true;
802
+ for (let j = 0; j < valLength; j++) {
803
+ if (read(arr, i + j) !== read(val, j)) {
804
+ found = false;
805
+ break;
806
+ }
807
+ }
808
+ if (found) return i;
809
+ }
810
+ }
811
+ return -1;
812
+ }
813
+ Buffer3.prototype.includes = function includes(val, byteOffset, encoding) {
814
+ return this.indexOf(val, byteOffset, encoding) !== -1;
815
+ };
816
+ Buffer3.prototype.indexOf = function indexOf(val, byteOffset, encoding) {
817
+ return bidirectionalIndexOf(this, val, byteOffset, encoding, true);
818
+ };
819
+ Buffer3.prototype.lastIndexOf = function lastIndexOf(val, byteOffset, encoding) {
820
+ return bidirectionalIndexOf(this, val, byteOffset, encoding, false);
821
+ };
822
+ function hexWrite(buf, string, offset, length) {
823
+ offset = Number(offset) || 0;
824
+ const remaining = buf.length - offset;
825
+ if (!length) {
826
+ length = remaining;
827
+ } else {
828
+ length = Number(length);
829
+ if (length > remaining) {
830
+ length = remaining;
831
+ }
832
+ }
833
+ const strLen = string.length;
834
+ if (length > strLen / 2) {
835
+ length = strLen / 2;
836
+ }
837
+ let i;
838
+ for (i = 0; i < length; ++i) {
839
+ const parsed = parseInt(string.substr(i * 2, 2), 16);
840
+ if (numberIsNaN(parsed)) return i;
841
+ buf[offset + i] = parsed;
842
+ }
843
+ return i;
844
+ }
845
+ function utf8Write(buf, string, offset, length) {
846
+ return blitBuffer(utf8ToBytes(string, buf.length - offset), buf, offset, length);
847
+ }
848
+ function asciiWrite(buf, string, offset, length) {
849
+ return blitBuffer(asciiToBytes(string), buf, offset, length);
850
+ }
851
+ function base64Write(buf, string, offset, length) {
852
+ return blitBuffer(base64ToBytes(string), buf, offset, length);
853
+ }
854
+ function ucs2Write(buf, string, offset, length) {
855
+ return blitBuffer(utf16leToBytes(string, buf.length - offset), buf, offset, length);
856
+ }
857
+ Buffer3.prototype.write = function write(string, offset, length, encoding) {
858
+ if (offset === void 0) {
859
+ encoding = "utf8";
860
+ length = this.length;
861
+ offset = 0;
862
+ } else if (length === void 0 && typeof offset === "string") {
863
+ encoding = offset;
864
+ length = this.length;
865
+ offset = 0;
866
+ } else if (isFinite(offset)) {
867
+ offset = offset >>> 0;
868
+ if (isFinite(length)) {
869
+ length = length >>> 0;
870
+ if (encoding === void 0) encoding = "utf8";
871
+ } else {
872
+ encoding = length;
873
+ length = void 0;
874
+ }
875
+ } else {
876
+ throw new Error(
877
+ "Buffer.write(string, encoding, offset[, length]) is no longer supported"
878
+ );
879
+ }
880
+ const remaining = this.length - offset;
881
+ if (length === void 0 || length > remaining) length = remaining;
882
+ if (string.length > 0 && (length < 0 || offset < 0) || offset > this.length) {
883
+ throw new RangeError("Attempt to write outside buffer bounds");
884
+ }
885
+ if (!encoding) encoding = "utf8";
886
+ let loweredCase = false;
887
+ for (; ; ) {
888
+ switch (encoding) {
889
+ case "hex":
890
+ return hexWrite(this, string, offset, length);
891
+ case "utf8":
892
+ case "utf-8":
893
+ return utf8Write(this, string, offset, length);
894
+ case "ascii":
895
+ case "latin1":
896
+ case "binary":
897
+ return asciiWrite(this, string, offset, length);
898
+ case "base64":
899
+ return base64Write(this, string, offset, length);
900
+ case "ucs2":
901
+ case "ucs-2":
902
+ case "utf16le":
903
+ case "utf-16le":
904
+ return ucs2Write(this, string, offset, length);
905
+ default:
906
+ if (loweredCase) throw new TypeError("Unknown encoding: " + encoding);
907
+ encoding = ("" + encoding).toLowerCase();
908
+ loweredCase = true;
909
+ }
910
+ }
911
+ };
912
+ Buffer3.prototype.toJSON = function toJSON() {
913
+ return {
914
+ type: "Buffer",
915
+ data: Array.prototype.slice.call(this._arr || this, 0)
916
+ };
917
+ };
918
+ function base64Slice(buf, start, end) {
919
+ if (start === 0 && end === buf.length) {
920
+ return base64.fromByteArray(buf);
921
+ } else {
922
+ return base64.fromByteArray(buf.slice(start, end));
923
+ }
924
+ }
925
+ function utf8Slice(buf, start, end) {
926
+ end = Math.min(buf.length, end);
927
+ const res = [];
928
+ let i = start;
929
+ while (i < end) {
930
+ const firstByte = buf[i];
931
+ let codePoint = null;
932
+ let bytesPerSequence = firstByte > 239 ? 4 : firstByte > 223 ? 3 : firstByte > 191 ? 2 : 1;
933
+ if (i + bytesPerSequence <= end) {
934
+ let secondByte, thirdByte, fourthByte, tempCodePoint;
935
+ switch (bytesPerSequence) {
936
+ case 1:
937
+ if (firstByte < 128) {
938
+ codePoint = firstByte;
939
+ }
940
+ break;
941
+ case 2:
942
+ secondByte = buf[i + 1];
943
+ if ((secondByte & 192) === 128) {
944
+ tempCodePoint = (firstByte & 31) << 6 | secondByte & 63;
945
+ if (tempCodePoint > 127) {
946
+ codePoint = tempCodePoint;
947
+ }
948
+ }
949
+ break;
950
+ case 3:
951
+ secondByte = buf[i + 1];
952
+ thirdByte = buf[i + 2];
953
+ if ((secondByte & 192) === 128 && (thirdByte & 192) === 128) {
954
+ tempCodePoint = (firstByte & 15) << 12 | (secondByte & 63) << 6 | thirdByte & 63;
955
+ if (tempCodePoint > 2047 && (tempCodePoint < 55296 || tempCodePoint > 57343)) {
956
+ codePoint = tempCodePoint;
957
+ }
958
+ }
959
+ break;
960
+ case 4:
961
+ secondByte = buf[i + 1];
962
+ thirdByte = buf[i + 2];
963
+ fourthByte = buf[i + 3];
964
+ if ((secondByte & 192) === 128 && (thirdByte & 192) === 128 && (fourthByte & 192) === 128) {
965
+ tempCodePoint = (firstByte & 15) << 18 | (secondByte & 63) << 12 | (thirdByte & 63) << 6 | fourthByte & 63;
966
+ if (tempCodePoint > 65535 && tempCodePoint < 1114112) {
967
+ codePoint = tempCodePoint;
968
+ }
969
+ }
970
+ }
971
+ }
972
+ if (codePoint === null) {
973
+ codePoint = 65533;
974
+ bytesPerSequence = 1;
975
+ } else if (codePoint > 65535) {
976
+ codePoint -= 65536;
977
+ res.push(codePoint >>> 10 & 1023 | 55296);
978
+ codePoint = 56320 | codePoint & 1023;
979
+ }
980
+ res.push(codePoint);
981
+ i += bytesPerSequence;
982
+ }
983
+ return decodeCodePointsArray(res);
984
+ }
985
+ var MAX_ARGUMENTS_LENGTH = 4096;
986
+ function decodeCodePointsArray(codePoints) {
987
+ const len = codePoints.length;
988
+ if (len <= MAX_ARGUMENTS_LENGTH) {
989
+ return String.fromCharCode.apply(String, codePoints);
990
+ }
991
+ let res = "";
992
+ let i = 0;
993
+ while (i < len) {
994
+ res += String.fromCharCode.apply(
995
+ String,
996
+ codePoints.slice(i, i += MAX_ARGUMENTS_LENGTH)
997
+ );
998
+ }
999
+ return res;
1000
+ }
1001
+ function asciiSlice(buf, start, end) {
1002
+ let ret = "";
1003
+ end = Math.min(buf.length, end);
1004
+ for (let i = start; i < end; ++i) {
1005
+ ret += String.fromCharCode(buf[i] & 127);
1006
+ }
1007
+ return ret;
1008
+ }
1009
+ function latin1Slice(buf, start, end) {
1010
+ let ret = "";
1011
+ end = Math.min(buf.length, end);
1012
+ for (let i = start; i < end; ++i) {
1013
+ ret += String.fromCharCode(buf[i]);
1014
+ }
1015
+ return ret;
1016
+ }
1017
+ function hexSlice(buf, start, end) {
1018
+ const len = buf.length;
1019
+ if (!start || start < 0) start = 0;
1020
+ if (!end || end < 0 || end > len) end = len;
1021
+ let out = "";
1022
+ for (let i = start; i < end; ++i) {
1023
+ out += hexSliceLookupTable[buf[i]];
1024
+ }
1025
+ return out;
1026
+ }
1027
+ function utf16leSlice(buf, start, end) {
1028
+ const bytes2 = buf.slice(start, end);
1029
+ let res = "";
1030
+ for (let i = 0; i < bytes2.length - 1; i += 2) {
1031
+ res += String.fromCharCode(bytes2[i] + bytes2[i + 1] * 256);
1032
+ }
1033
+ return res;
1034
+ }
1035
+ Buffer3.prototype.slice = function slice2(start, end) {
1036
+ const len = this.length;
1037
+ start = ~~start;
1038
+ end = end === void 0 ? len : ~~end;
1039
+ if (start < 0) {
1040
+ start += len;
1041
+ if (start < 0) start = 0;
1042
+ } else if (start > len) {
1043
+ start = len;
1044
+ }
1045
+ if (end < 0) {
1046
+ end += len;
1047
+ if (end < 0) end = 0;
1048
+ } else if (end > len) {
1049
+ end = len;
1050
+ }
1051
+ if (end < start) end = start;
1052
+ const newBuf = this.subarray(start, end);
1053
+ Object.setPrototypeOf(newBuf, Buffer3.prototype);
1054
+ return newBuf;
1055
+ };
1056
+ function checkOffset(offset, ext, length) {
1057
+ if (offset % 1 !== 0 || offset < 0) throw new RangeError("offset is not uint");
1058
+ if (offset + ext > length) throw new RangeError("Trying to access beyond buffer length");
1059
+ }
1060
+ Buffer3.prototype.readUintLE = Buffer3.prototype.readUIntLE = function readUIntLE(offset, byteLength2, noAssert) {
1061
+ offset = offset >>> 0;
1062
+ byteLength2 = byteLength2 >>> 0;
1063
+ if (!noAssert) checkOffset(offset, byteLength2, this.length);
1064
+ let val = this[offset];
1065
+ let mul3 = 1;
1066
+ let i = 0;
1067
+ while (++i < byteLength2 && (mul3 *= 256)) {
1068
+ val += this[offset + i] * mul3;
1069
+ }
1070
+ return val;
1071
+ };
1072
+ Buffer3.prototype.readUintBE = Buffer3.prototype.readUIntBE = function readUIntBE(offset, byteLength2, noAssert) {
1073
+ offset = offset >>> 0;
1074
+ byteLength2 = byteLength2 >>> 0;
1075
+ if (!noAssert) {
1076
+ checkOffset(offset, byteLength2, this.length);
1077
+ }
1078
+ let val = this[offset + --byteLength2];
1079
+ let mul3 = 1;
1080
+ while (byteLength2 > 0 && (mul3 *= 256)) {
1081
+ val += this[offset + --byteLength2] * mul3;
1082
+ }
1083
+ return val;
1084
+ };
1085
+ Buffer3.prototype.readUint8 = Buffer3.prototype.readUInt8 = function readUInt8(offset, noAssert) {
1086
+ offset = offset >>> 0;
1087
+ if (!noAssert) checkOffset(offset, 1, this.length);
1088
+ return this[offset];
1089
+ };
1090
+ Buffer3.prototype.readUint16LE = Buffer3.prototype.readUInt16LE = function readUInt16LE(offset, noAssert) {
1091
+ offset = offset >>> 0;
1092
+ if (!noAssert) checkOffset(offset, 2, this.length);
1093
+ return this[offset] | this[offset + 1] << 8;
1094
+ };
1095
+ Buffer3.prototype.readUint16BE = Buffer3.prototype.readUInt16BE = function readUInt16BE(offset, noAssert) {
1096
+ offset = offset >>> 0;
1097
+ if (!noAssert) checkOffset(offset, 2, this.length);
1098
+ return this[offset] << 8 | this[offset + 1];
1099
+ };
1100
+ Buffer3.prototype.readUint32LE = Buffer3.prototype.readUInt32LE = function readUInt32LE(offset, noAssert) {
1101
+ offset = offset >>> 0;
1102
+ if (!noAssert) checkOffset(offset, 4, this.length);
1103
+ return (this[offset] | this[offset + 1] << 8 | this[offset + 2] << 16) + this[offset + 3] * 16777216;
1104
+ };
1105
+ Buffer3.prototype.readUint32BE = Buffer3.prototype.readUInt32BE = function readUInt32BE(offset, noAssert) {
1106
+ offset = offset >>> 0;
1107
+ if (!noAssert) checkOffset(offset, 4, this.length);
1108
+ return this[offset] * 16777216 + (this[offset + 1] << 16 | this[offset + 2] << 8 | this[offset + 3]);
1109
+ };
1110
+ Buffer3.prototype.readBigUInt64LE = defineBigIntMethod(function readBigUInt64LE(offset) {
1111
+ offset = offset >>> 0;
1112
+ validateNumber(offset, "offset");
1113
+ const first = this[offset];
1114
+ const last = this[offset + 7];
1115
+ if (first === void 0 || last === void 0) {
1116
+ boundsError(offset, this.length - 8);
1117
+ }
1118
+ const lo = first + this[++offset] * 2 ** 8 + this[++offset] * 2 ** 16 + this[++offset] * 2 ** 24;
1119
+ const hi = this[++offset] + this[++offset] * 2 ** 8 + this[++offset] * 2 ** 16 + last * 2 ** 24;
1120
+ return BigInt(lo) + (BigInt(hi) << BigInt(32));
1121
+ });
1122
+ Buffer3.prototype.readBigUInt64BE = defineBigIntMethod(function readBigUInt64BE(offset) {
1123
+ offset = offset >>> 0;
1124
+ validateNumber(offset, "offset");
1125
+ const first = this[offset];
1126
+ const last = this[offset + 7];
1127
+ if (first === void 0 || last === void 0) {
1128
+ boundsError(offset, this.length - 8);
1129
+ }
1130
+ const hi = first * 2 ** 24 + this[++offset] * 2 ** 16 + this[++offset] * 2 ** 8 + this[++offset];
1131
+ const lo = this[++offset] * 2 ** 24 + this[++offset] * 2 ** 16 + this[++offset] * 2 ** 8 + last;
1132
+ return (BigInt(hi) << BigInt(32)) + BigInt(lo);
1133
+ });
1134
+ Buffer3.prototype.readIntLE = function readIntLE(offset, byteLength2, noAssert) {
1135
+ offset = offset >>> 0;
1136
+ byteLength2 = byteLength2 >>> 0;
1137
+ if (!noAssert) checkOffset(offset, byteLength2, this.length);
1138
+ let val = this[offset];
1139
+ let mul3 = 1;
1140
+ let i = 0;
1141
+ while (++i < byteLength2 && (mul3 *= 256)) {
1142
+ val += this[offset + i] * mul3;
1143
+ }
1144
+ mul3 *= 128;
1145
+ if (val >= mul3) val -= Math.pow(2, 8 * byteLength2);
1146
+ return val;
1147
+ };
1148
+ Buffer3.prototype.readIntBE = function readIntBE(offset, byteLength2, noAssert) {
1149
+ offset = offset >>> 0;
1150
+ byteLength2 = byteLength2 >>> 0;
1151
+ if (!noAssert) checkOffset(offset, byteLength2, this.length);
1152
+ let i = byteLength2;
1153
+ let mul3 = 1;
1154
+ let val = this[offset + --i];
1155
+ while (i > 0 && (mul3 *= 256)) {
1156
+ val += this[offset + --i] * mul3;
1157
+ }
1158
+ mul3 *= 128;
1159
+ if (val >= mul3) val -= Math.pow(2, 8 * byteLength2);
1160
+ return val;
1161
+ };
1162
+ Buffer3.prototype.readInt8 = function readInt8(offset, noAssert) {
1163
+ offset = offset >>> 0;
1164
+ if (!noAssert) checkOffset(offset, 1, this.length);
1165
+ if (!(this[offset] & 128)) return this[offset];
1166
+ return (255 - this[offset] + 1) * -1;
1167
+ };
1168
+ Buffer3.prototype.readInt16LE = function readInt16LE(offset, noAssert) {
1169
+ offset = offset >>> 0;
1170
+ if (!noAssert) checkOffset(offset, 2, this.length);
1171
+ const val = this[offset] | this[offset + 1] << 8;
1172
+ return val & 32768 ? val | 4294901760 : val;
1173
+ };
1174
+ Buffer3.prototype.readInt16BE = function readInt16BE(offset, noAssert) {
1175
+ offset = offset >>> 0;
1176
+ if (!noAssert) checkOffset(offset, 2, this.length);
1177
+ const val = this[offset + 1] | this[offset] << 8;
1178
+ return val & 32768 ? val | 4294901760 : val;
1179
+ };
1180
+ Buffer3.prototype.readInt32LE = function readInt32LE(offset, noAssert) {
1181
+ offset = offset >>> 0;
1182
+ if (!noAssert) checkOffset(offset, 4, this.length);
1183
+ return this[offset] | this[offset + 1] << 8 | this[offset + 2] << 16 | this[offset + 3] << 24;
1184
+ };
1185
+ Buffer3.prototype.readInt32BE = function readInt32BE(offset, noAssert) {
1186
+ offset = offset >>> 0;
1187
+ if (!noAssert) checkOffset(offset, 4, this.length);
1188
+ return this[offset] << 24 | this[offset + 1] << 16 | this[offset + 2] << 8 | this[offset + 3];
1189
+ };
1190
+ Buffer3.prototype.readBigInt64LE = defineBigIntMethod(function readBigInt64LE(offset) {
1191
+ offset = offset >>> 0;
1192
+ validateNumber(offset, "offset");
1193
+ const first = this[offset];
1194
+ const last = this[offset + 7];
1195
+ if (first === void 0 || last === void 0) {
1196
+ boundsError(offset, this.length - 8);
1197
+ }
1198
+ const val = this[offset + 4] + this[offset + 5] * 2 ** 8 + this[offset + 6] * 2 ** 16 + (last << 24);
1199
+ return (BigInt(val) << BigInt(32)) + BigInt(first + this[++offset] * 2 ** 8 + this[++offset] * 2 ** 16 + this[++offset] * 2 ** 24);
1200
+ });
1201
+ Buffer3.prototype.readBigInt64BE = defineBigIntMethod(function readBigInt64BE(offset) {
1202
+ offset = offset >>> 0;
1203
+ validateNumber(offset, "offset");
1204
+ const first = this[offset];
1205
+ const last = this[offset + 7];
1206
+ if (first === void 0 || last === void 0) {
1207
+ boundsError(offset, this.length - 8);
1208
+ }
1209
+ const val = (first << 24) + // Overflow
1210
+ this[++offset] * 2 ** 16 + this[++offset] * 2 ** 8 + this[++offset];
1211
+ return (BigInt(val) << BigInt(32)) + BigInt(this[++offset] * 2 ** 24 + this[++offset] * 2 ** 16 + this[++offset] * 2 ** 8 + last);
1212
+ });
1213
+ Buffer3.prototype.readFloatLE = function readFloatLE(offset, noAssert) {
1214
+ offset = offset >>> 0;
1215
+ if (!noAssert) checkOffset(offset, 4, this.length);
1216
+ return ieee754.read(this, offset, true, 23, 4);
1217
+ };
1218
+ Buffer3.prototype.readFloatBE = function readFloatBE(offset, noAssert) {
1219
+ offset = offset >>> 0;
1220
+ if (!noAssert) checkOffset(offset, 4, this.length);
1221
+ return ieee754.read(this, offset, false, 23, 4);
1222
+ };
1223
+ Buffer3.prototype.readDoubleLE = function readDoubleLE(offset, noAssert) {
1224
+ offset = offset >>> 0;
1225
+ if (!noAssert) checkOffset(offset, 8, this.length);
1226
+ return ieee754.read(this, offset, true, 52, 8);
1227
+ };
1228
+ Buffer3.prototype.readDoubleBE = function readDoubleBE(offset, noAssert) {
1229
+ offset = offset >>> 0;
1230
+ if (!noAssert) checkOffset(offset, 8, this.length);
1231
+ return ieee754.read(this, offset, false, 52, 8);
1232
+ };
1233
+ function checkInt(buf, value, offset, ext, max2, min) {
1234
+ if (!Buffer3.isBuffer(buf)) throw new TypeError('"buffer" argument must be a Buffer instance');
1235
+ if (value > max2 || value < min) throw new RangeError('"value" argument is out of bounds');
1236
+ if (offset + ext > buf.length) throw new RangeError("Index out of range");
1237
+ }
1238
+ Buffer3.prototype.writeUintLE = Buffer3.prototype.writeUIntLE = function writeUIntLE(value, offset, byteLength2, noAssert) {
1239
+ value = +value;
1240
+ offset = offset >>> 0;
1241
+ byteLength2 = byteLength2 >>> 0;
1242
+ if (!noAssert) {
1243
+ const maxBytes = Math.pow(2, 8 * byteLength2) - 1;
1244
+ checkInt(this, value, offset, byteLength2, maxBytes, 0);
1245
+ }
1246
+ let mul3 = 1;
1247
+ let i = 0;
1248
+ this[offset] = value & 255;
1249
+ while (++i < byteLength2 && (mul3 *= 256)) {
1250
+ this[offset + i] = value / mul3 & 255;
1251
+ }
1252
+ return offset + byteLength2;
1253
+ };
1254
+ Buffer3.prototype.writeUintBE = Buffer3.prototype.writeUIntBE = function writeUIntBE(value, offset, byteLength2, noAssert) {
1255
+ value = +value;
1256
+ offset = offset >>> 0;
1257
+ byteLength2 = byteLength2 >>> 0;
1258
+ if (!noAssert) {
1259
+ const maxBytes = Math.pow(2, 8 * byteLength2) - 1;
1260
+ checkInt(this, value, offset, byteLength2, maxBytes, 0);
1261
+ }
1262
+ let i = byteLength2 - 1;
1263
+ let mul3 = 1;
1264
+ this[offset + i] = value & 255;
1265
+ while (--i >= 0 && (mul3 *= 256)) {
1266
+ this[offset + i] = value / mul3 & 255;
1267
+ }
1268
+ return offset + byteLength2;
1269
+ };
1270
+ Buffer3.prototype.writeUint8 = Buffer3.prototype.writeUInt8 = function writeUInt8(value, offset, noAssert) {
1271
+ value = +value;
1272
+ offset = offset >>> 0;
1273
+ if (!noAssert) checkInt(this, value, offset, 1, 255, 0);
1274
+ this[offset] = value & 255;
1275
+ return offset + 1;
1276
+ };
1277
+ Buffer3.prototype.writeUint16LE = Buffer3.prototype.writeUInt16LE = function writeUInt16LE(value, offset, noAssert) {
1278
+ value = +value;
1279
+ offset = offset >>> 0;
1280
+ if (!noAssert) checkInt(this, value, offset, 2, 65535, 0);
1281
+ this[offset] = value & 255;
1282
+ this[offset + 1] = value >>> 8;
1283
+ return offset + 2;
1284
+ };
1285
+ Buffer3.prototype.writeUint16BE = Buffer3.prototype.writeUInt16BE = function writeUInt16BE(value, offset, noAssert) {
1286
+ value = +value;
1287
+ offset = offset >>> 0;
1288
+ if (!noAssert) checkInt(this, value, offset, 2, 65535, 0);
1289
+ this[offset] = value >>> 8;
1290
+ this[offset + 1] = value & 255;
1291
+ return offset + 2;
1292
+ };
1293
+ Buffer3.prototype.writeUint32LE = Buffer3.prototype.writeUInt32LE = function writeUInt32LE(value, offset, noAssert) {
1294
+ value = +value;
1295
+ offset = offset >>> 0;
1296
+ if (!noAssert) checkInt(this, value, offset, 4, 4294967295, 0);
1297
+ this[offset + 3] = value >>> 24;
1298
+ this[offset + 2] = value >>> 16;
1299
+ this[offset + 1] = value >>> 8;
1300
+ this[offset] = value & 255;
1301
+ return offset + 4;
1302
+ };
1303
+ Buffer3.prototype.writeUint32BE = Buffer3.prototype.writeUInt32BE = function writeUInt32BE(value, offset, noAssert) {
1304
+ value = +value;
1305
+ offset = offset >>> 0;
1306
+ if (!noAssert) checkInt(this, value, offset, 4, 4294967295, 0);
1307
+ this[offset] = value >>> 24;
1308
+ this[offset + 1] = value >>> 16;
1309
+ this[offset + 2] = value >>> 8;
1310
+ this[offset + 3] = value & 255;
1311
+ return offset + 4;
1312
+ };
1313
+ function wrtBigUInt64LE(buf, value, offset, min, max2) {
1314
+ checkIntBI(value, min, max2, buf, offset, 7);
1315
+ let lo = Number(value & BigInt(4294967295));
1316
+ buf[offset++] = lo;
1317
+ lo = lo >> 8;
1318
+ buf[offset++] = lo;
1319
+ lo = lo >> 8;
1320
+ buf[offset++] = lo;
1321
+ lo = lo >> 8;
1322
+ buf[offset++] = lo;
1323
+ let hi = Number(value >> BigInt(32) & BigInt(4294967295));
1324
+ buf[offset++] = hi;
1325
+ hi = hi >> 8;
1326
+ buf[offset++] = hi;
1327
+ hi = hi >> 8;
1328
+ buf[offset++] = hi;
1329
+ hi = hi >> 8;
1330
+ buf[offset++] = hi;
1331
+ return offset;
1332
+ }
1333
+ function wrtBigUInt64BE(buf, value, offset, min, max2) {
1334
+ checkIntBI(value, min, max2, buf, offset, 7);
1335
+ let lo = Number(value & BigInt(4294967295));
1336
+ buf[offset + 7] = lo;
1337
+ lo = lo >> 8;
1338
+ buf[offset + 6] = lo;
1339
+ lo = lo >> 8;
1340
+ buf[offset + 5] = lo;
1341
+ lo = lo >> 8;
1342
+ buf[offset + 4] = lo;
1343
+ let hi = Number(value >> BigInt(32) & BigInt(4294967295));
1344
+ buf[offset + 3] = hi;
1345
+ hi = hi >> 8;
1346
+ buf[offset + 2] = hi;
1347
+ hi = hi >> 8;
1348
+ buf[offset + 1] = hi;
1349
+ hi = hi >> 8;
1350
+ buf[offset] = hi;
1351
+ return offset + 8;
1352
+ }
1353
+ Buffer3.prototype.writeBigUInt64LE = defineBigIntMethod(function writeBigUInt64LE(value, offset = 0) {
1354
+ return wrtBigUInt64LE(this, value, offset, BigInt(0), BigInt("0xffffffffffffffff"));
1355
+ });
1356
+ Buffer3.prototype.writeBigUInt64BE = defineBigIntMethod(function writeBigUInt64BE(value, offset = 0) {
1357
+ return wrtBigUInt64BE(this, value, offset, BigInt(0), BigInt("0xffffffffffffffff"));
1358
+ });
1359
+ Buffer3.prototype.writeIntLE = function writeIntLE(value, offset, byteLength2, noAssert) {
1360
+ value = +value;
1361
+ offset = offset >>> 0;
1362
+ if (!noAssert) {
1363
+ const limit2 = Math.pow(2, 8 * byteLength2 - 1);
1364
+ checkInt(this, value, offset, byteLength2, limit2 - 1, -limit2);
1365
+ }
1366
+ let i = 0;
1367
+ let mul3 = 1;
1368
+ let sub = 0;
1369
+ this[offset] = value & 255;
1370
+ while (++i < byteLength2 && (mul3 *= 256)) {
1371
+ if (value < 0 && sub === 0 && this[offset + i - 1] !== 0) {
1372
+ sub = 1;
1373
+ }
1374
+ this[offset + i] = (value / mul3 >> 0) - sub & 255;
1375
+ }
1376
+ return offset + byteLength2;
1377
+ };
1378
+ Buffer3.prototype.writeIntBE = function writeIntBE(value, offset, byteLength2, noAssert) {
1379
+ value = +value;
1380
+ offset = offset >>> 0;
1381
+ if (!noAssert) {
1382
+ const limit2 = Math.pow(2, 8 * byteLength2 - 1);
1383
+ checkInt(this, value, offset, byteLength2, limit2 - 1, -limit2);
1384
+ }
1385
+ let i = byteLength2 - 1;
1386
+ let mul3 = 1;
1387
+ let sub = 0;
1388
+ this[offset + i] = value & 255;
1389
+ while (--i >= 0 && (mul3 *= 256)) {
1390
+ if (value < 0 && sub === 0 && this[offset + i + 1] !== 0) {
1391
+ sub = 1;
1392
+ }
1393
+ this[offset + i] = (value / mul3 >> 0) - sub & 255;
1394
+ }
1395
+ return offset + byteLength2;
1396
+ };
1397
+ Buffer3.prototype.writeInt8 = function writeInt8(value, offset, noAssert) {
1398
+ value = +value;
1399
+ offset = offset >>> 0;
1400
+ if (!noAssert) checkInt(this, value, offset, 1, 127, -128);
1401
+ if (value < 0) value = 255 + value + 1;
1402
+ this[offset] = value & 255;
1403
+ return offset + 1;
1404
+ };
1405
+ Buffer3.prototype.writeInt16LE = function writeInt16LE(value, offset, noAssert) {
1406
+ value = +value;
1407
+ offset = offset >>> 0;
1408
+ if (!noAssert) checkInt(this, value, offset, 2, 32767, -32768);
1409
+ this[offset] = value & 255;
1410
+ this[offset + 1] = value >>> 8;
1411
+ return offset + 2;
1412
+ };
1413
+ Buffer3.prototype.writeInt16BE = function writeInt16BE(value, offset, noAssert) {
1414
+ value = +value;
1415
+ offset = offset >>> 0;
1416
+ if (!noAssert) checkInt(this, value, offset, 2, 32767, -32768);
1417
+ this[offset] = value >>> 8;
1418
+ this[offset + 1] = value & 255;
1419
+ return offset + 2;
1420
+ };
1421
+ Buffer3.prototype.writeInt32LE = function writeInt32LE(value, offset, noAssert) {
1422
+ value = +value;
1423
+ offset = offset >>> 0;
1424
+ if (!noAssert) checkInt(this, value, offset, 4, 2147483647, -2147483648);
1425
+ this[offset] = value & 255;
1426
+ this[offset + 1] = value >>> 8;
1427
+ this[offset + 2] = value >>> 16;
1428
+ this[offset + 3] = value >>> 24;
1429
+ return offset + 4;
1430
+ };
1431
+ Buffer3.prototype.writeInt32BE = function writeInt32BE(value, offset, noAssert) {
1432
+ value = +value;
1433
+ offset = offset >>> 0;
1434
+ if (!noAssert) checkInt(this, value, offset, 4, 2147483647, -2147483648);
1435
+ if (value < 0) value = 4294967295 + value + 1;
1436
+ this[offset] = value >>> 24;
1437
+ this[offset + 1] = value >>> 16;
1438
+ this[offset + 2] = value >>> 8;
1439
+ this[offset + 3] = value & 255;
1440
+ return offset + 4;
1441
+ };
1442
+ Buffer3.prototype.writeBigInt64LE = defineBigIntMethod(function writeBigInt64LE(value, offset = 0) {
1443
+ return wrtBigUInt64LE(this, value, offset, -BigInt("0x8000000000000000"), BigInt("0x7fffffffffffffff"));
1444
+ });
1445
+ Buffer3.prototype.writeBigInt64BE = defineBigIntMethod(function writeBigInt64BE(value, offset = 0) {
1446
+ return wrtBigUInt64BE(this, value, offset, -BigInt("0x8000000000000000"), BigInt("0x7fffffffffffffff"));
1447
+ });
1448
+ function checkIEEE754(buf, value, offset, ext, max2, min) {
1449
+ if (offset + ext > buf.length) throw new RangeError("Index out of range");
1450
+ if (offset < 0) throw new RangeError("Index out of range");
1451
+ }
1452
+ function writeFloat(buf, value, offset, littleEndian, noAssert) {
1453
+ value = +value;
1454
+ offset = offset >>> 0;
1455
+ if (!noAssert) {
1456
+ checkIEEE754(buf, value, offset, 4, 34028234663852886e22, -34028234663852886e22);
1457
+ }
1458
+ ieee754.write(buf, value, offset, littleEndian, 23, 4);
1459
+ return offset + 4;
1460
+ }
1461
+ Buffer3.prototype.writeFloatLE = function writeFloatLE(value, offset, noAssert) {
1462
+ return writeFloat(this, value, offset, true, noAssert);
1463
+ };
1464
+ Buffer3.prototype.writeFloatBE = function writeFloatBE(value, offset, noAssert) {
1465
+ return writeFloat(this, value, offset, false, noAssert);
1466
+ };
1467
+ function writeDouble(buf, value, offset, littleEndian, noAssert) {
1468
+ value = +value;
1469
+ offset = offset >>> 0;
1470
+ if (!noAssert) {
1471
+ checkIEEE754(buf, value, offset, 8, 17976931348623157e292, -17976931348623157e292);
1472
+ }
1473
+ ieee754.write(buf, value, offset, littleEndian, 52, 8);
1474
+ return offset + 8;
1475
+ }
1476
+ Buffer3.prototype.writeDoubleLE = function writeDoubleLE(value, offset, noAssert) {
1477
+ return writeDouble(this, value, offset, true, noAssert);
1478
+ };
1479
+ Buffer3.prototype.writeDoubleBE = function writeDoubleBE(value, offset, noAssert) {
1480
+ return writeDouble(this, value, offset, false, noAssert);
1481
+ };
1482
+ Buffer3.prototype.copy = function copy(target, targetStart, start, end) {
1483
+ if (!Buffer3.isBuffer(target)) throw new TypeError("argument should be a Buffer");
1484
+ if (!start) start = 0;
1485
+ if (!end && end !== 0) end = this.length;
1486
+ if (targetStart >= target.length) targetStart = target.length;
1487
+ if (!targetStart) targetStart = 0;
1488
+ if (end > 0 && end < start) end = start;
1489
+ if (end === start) return 0;
1490
+ if (target.length === 0 || this.length === 0) return 0;
1491
+ if (targetStart < 0) {
1492
+ throw new RangeError("targetStart out of bounds");
1493
+ }
1494
+ if (start < 0 || start >= this.length) throw new RangeError("Index out of range");
1495
+ if (end < 0) throw new RangeError("sourceEnd out of bounds");
1496
+ if (end > this.length) end = this.length;
1497
+ if (target.length - targetStart < end - start) {
1498
+ end = target.length - targetStart + start;
1499
+ }
1500
+ const len = end - start;
1501
+ if (this === target && typeof Uint8Array.prototype.copyWithin === "function") {
1502
+ this.copyWithin(targetStart, start, end);
1503
+ } else {
1504
+ Uint8Array.prototype.set.call(
1505
+ target,
1506
+ this.subarray(start, end),
1507
+ targetStart
1508
+ );
1509
+ }
1510
+ return len;
1511
+ };
1512
+ Buffer3.prototype.fill = function fill(val, start, end, encoding) {
1513
+ if (typeof val === "string") {
1514
+ if (typeof start === "string") {
1515
+ encoding = start;
1516
+ start = 0;
1517
+ end = this.length;
1518
+ } else if (typeof end === "string") {
1519
+ encoding = end;
1520
+ end = this.length;
1521
+ }
1522
+ if (encoding !== void 0 && typeof encoding !== "string") {
1523
+ throw new TypeError("encoding must be a string");
1524
+ }
1525
+ if (typeof encoding === "string" && !Buffer3.isEncoding(encoding)) {
1526
+ throw new TypeError("Unknown encoding: " + encoding);
1527
+ }
1528
+ if (val.length === 1) {
1529
+ const code = val.charCodeAt(0);
1530
+ if (encoding === "utf8" && code < 128 || encoding === "latin1") {
1531
+ val = code;
1532
+ }
1533
+ }
1534
+ } else if (typeof val === "number") {
1535
+ val = val & 255;
1536
+ } else if (typeof val === "boolean") {
1537
+ val = Number(val);
1538
+ }
1539
+ if (start < 0 || this.length < start || this.length < end) {
1540
+ throw new RangeError("Out of range index");
1541
+ }
1542
+ if (end <= start) {
1543
+ return this;
1544
+ }
1545
+ start = start >>> 0;
1546
+ end = end === void 0 ? this.length : end >>> 0;
1547
+ if (!val) val = 0;
1548
+ let i;
1549
+ if (typeof val === "number") {
1550
+ for (i = start; i < end; ++i) {
1551
+ this[i] = val;
1552
+ }
1553
+ } else {
1554
+ const bytes2 = Buffer3.isBuffer(val) ? val : Buffer3.from(val, encoding);
1555
+ const len = bytes2.length;
1556
+ if (len === 0) {
1557
+ throw new TypeError('The value "' + val + '" is invalid for argument "value"');
1558
+ }
1559
+ for (i = 0; i < end - start; ++i) {
1560
+ this[i + start] = bytes2[i % len];
1561
+ }
1562
+ }
1563
+ return this;
1564
+ };
1565
+ var errors = {};
1566
+ function E(sym, getMessage, Base) {
1567
+ errors[sym] = class NodeError extends Base {
1568
+ constructor() {
1569
+ super();
1570
+ Object.defineProperty(this, "message", {
1571
+ value: getMessage.apply(this, arguments),
1572
+ writable: true,
1573
+ configurable: true
1574
+ });
1575
+ this.name = `${this.name} [${sym}]`;
1576
+ this.stack;
1577
+ delete this.name;
1578
+ }
1579
+ get code() {
1580
+ return sym;
1581
+ }
1582
+ set code(value) {
1583
+ Object.defineProperty(this, "code", {
1584
+ configurable: true,
1585
+ enumerable: true,
1586
+ value,
1587
+ writable: true
1588
+ });
1589
+ }
1590
+ toString() {
1591
+ return `${this.name} [${sym}]: ${this.message}`;
1592
+ }
1593
+ };
1594
+ }
1595
+ E(
1596
+ "ERR_BUFFER_OUT_OF_BOUNDS",
1597
+ function(name) {
1598
+ if (name) {
1599
+ return `${name} is outside of buffer bounds`;
1600
+ }
1601
+ return "Attempt to access memory outside buffer bounds";
1602
+ },
1603
+ RangeError
1604
+ );
1605
+ E(
1606
+ "ERR_INVALID_ARG_TYPE",
1607
+ function(name, actual) {
1608
+ return `The "${name}" argument must be of type number. Received type ${typeof actual}`;
1609
+ },
1610
+ TypeError
1611
+ );
1612
+ E(
1613
+ "ERR_OUT_OF_RANGE",
1614
+ function(str, range2, input) {
1615
+ let msg = `The value of "${str}" is out of range.`;
1616
+ let received = input;
1617
+ if (Number.isInteger(input) && Math.abs(input) > 2 ** 32) {
1618
+ received = addNumericalSeparator(String(input));
1619
+ } else if (typeof input === "bigint") {
1620
+ received = String(input);
1621
+ if (input > BigInt(2) ** BigInt(32) || input < -(BigInt(2) ** BigInt(32))) {
1622
+ received = addNumericalSeparator(received);
1623
+ }
1624
+ received += "n";
1625
+ }
1626
+ msg += ` It must be ${range2}. Received ${received}`;
1627
+ return msg;
1628
+ },
1629
+ RangeError
1630
+ );
1631
+ function addNumericalSeparator(val) {
1632
+ let res = "";
1633
+ let i = val.length;
1634
+ const start = val[0] === "-" ? 1 : 0;
1635
+ for (; i >= start + 4; i -= 3) {
1636
+ res = `_${val.slice(i - 3, i)}${res}`;
1637
+ }
1638
+ return `${val.slice(0, i)}${res}`;
1639
+ }
1640
+ function checkBounds(buf, offset, byteLength2) {
1641
+ validateNumber(offset, "offset");
1642
+ if (buf[offset] === void 0 || buf[offset + byteLength2] === void 0) {
1643
+ boundsError(offset, buf.length - (byteLength2 + 1));
1644
+ }
1645
+ }
1646
+ function checkIntBI(value, min, max2, buf, offset, byteLength2) {
1647
+ if (value > max2 || value < min) {
1648
+ const n = typeof min === "bigint" ? "n" : "";
1649
+ let range2;
1650
+ if (byteLength2 > 3) {
1651
+ if (min === 0 || min === BigInt(0)) {
1652
+ range2 = `>= 0${n} and < 2${n} ** ${(byteLength2 + 1) * 8}${n}`;
1653
+ } else {
1654
+ range2 = `>= -(2${n} ** ${(byteLength2 + 1) * 8 - 1}${n}) and < 2 ** ${(byteLength2 + 1) * 8 - 1}${n}`;
1655
+ }
1656
+ } else {
1657
+ range2 = `>= ${min}${n} and <= ${max2}${n}`;
1658
+ }
1659
+ throw new errors.ERR_OUT_OF_RANGE("value", range2, value);
1660
+ }
1661
+ checkBounds(buf, offset, byteLength2);
1662
+ }
1663
+ function validateNumber(value, name) {
1664
+ if (typeof value !== "number") {
1665
+ throw new errors.ERR_INVALID_ARG_TYPE(name, "number", value);
1666
+ }
1667
+ }
1668
+ function boundsError(value, length, type) {
1669
+ if (Math.floor(value) !== value) {
1670
+ validateNumber(value, type);
1671
+ throw new errors.ERR_OUT_OF_RANGE(type || "offset", "an integer", value);
1672
+ }
1673
+ if (length < 0) {
1674
+ throw new errors.ERR_BUFFER_OUT_OF_BOUNDS();
1675
+ }
1676
+ throw new errors.ERR_OUT_OF_RANGE(
1677
+ type || "offset",
1678
+ `>= ${type ? 1 : 0} and <= ${length}`,
1679
+ value
1680
+ );
1681
+ }
1682
+ var INVALID_BASE64_RE = /[^+/0-9A-Za-z-_]/g;
1683
+ function base64clean(str) {
1684
+ str = str.split("=")[0];
1685
+ str = str.trim().replace(INVALID_BASE64_RE, "");
1686
+ if (str.length < 2) return "";
1687
+ while (str.length % 4 !== 0) {
1688
+ str = str + "=";
1689
+ }
1690
+ return str;
1691
+ }
1692
+ function utf8ToBytes(string, units) {
1693
+ units = units || Infinity;
1694
+ let codePoint;
1695
+ const length = string.length;
1696
+ let leadSurrogate = null;
1697
+ const bytes2 = [];
1698
+ for (let i = 0; i < length; ++i) {
1699
+ codePoint = string.charCodeAt(i);
1700
+ if (codePoint > 55295 && codePoint < 57344) {
1701
+ if (!leadSurrogate) {
1702
+ if (codePoint > 56319) {
1703
+ if ((units -= 3) > -1) bytes2.push(239, 191, 189);
1704
+ continue;
1705
+ } else if (i + 1 === length) {
1706
+ if ((units -= 3) > -1) bytes2.push(239, 191, 189);
1707
+ continue;
1708
+ }
1709
+ leadSurrogate = codePoint;
1710
+ continue;
1711
+ }
1712
+ if (codePoint < 56320) {
1713
+ if ((units -= 3) > -1) bytes2.push(239, 191, 189);
1714
+ leadSurrogate = codePoint;
1715
+ continue;
1716
+ }
1717
+ codePoint = (leadSurrogate - 55296 << 10 | codePoint - 56320) + 65536;
1718
+ } else if (leadSurrogate) {
1719
+ if ((units -= 3) > -1) bytes2.push(239, 191, 189);
1720
+ }
1721
+ leadSurrogate = null;
1722
+ if (codePoint < 128) {
1723
+ if ((units -= 1) < 0) break;
1724
+ bytes2.push(codePoint);
1725
+ } else if (codePoint < 2048) {
1726
+ if ((units -= 2) < 0) break;
1727
+ bytes2.push(
1728
+ codePoint >> 6 | 192,
1729
+ codePoint & 63 | 128
1730
+ );
1731
+ } else if (codePoint < 65536) {
1732
+ if ((units -= 3) < 0) break;
1733
+ bytes2.push(
1734
+ codePoint >> 12 | 224,
1735
+ codePoint >> 6 & 63 | 128,
1736
+ codePoint & 63 | 128
1737
+ );
1738
+ } else if (codePoint < 1114112) {
1739
+ if ((units -= 4) < 0) break;
1740
+ bytes2.push(
1741
+ codePoint >> 18 | 240,
1742
+ codePoint >> 12 & 63 | 128,
1743
+ codePoint >> 6 & 63 | 128,
1744
+ codePoint & 63 | 128
1745
+ );
1746
+ } else {
1747
+ throw new Error("Invalid code point");
1748
+ }
1749
+ }
1750
+ return bytes2;
1751
+ }
1752
+ function asciiToBytes(str) {
1753
+ const byteArray = [];
1754
+ for (let i = 0; i < str.length; ++i) {
1755
+ byteArray.push(str.charCodeAt(i) & 255);
1756
+ }
1757
+ return byteArray;
1758
+ }
1759
+ function utf16leToBytes(str, units) {
1760
+ let c, hi, lo;
1761
+ const byteArray = [];
1762
+ for (let i = 0; i < str.length; ++i) {
1763
+ if ((units -= 2) < 0) break;
1764
+ c = str.charCodeAt(i);
1765
+ hi = c >> 8;
1766
+ lo = c % 256;
1767
+ byteArray.push(lo);
1768
+ byteArray.push(hi);
1769
+ }
1770
+ return byteArray;
1771
+ }
1772
+ function base64ToBytes(str) {
1773
+ return base64.toByteArray(base64clean(str));
1774
+ }
1775
+ function blitBuffer(src, dst, offset, length) {
1776
+ let i;
1777
+ for (i = 0; i < length; ++i) {
1778
+ if (i + offset >= dst.length || i >= src.length) break;
1779
+ dst[i + offset] = src[i];
1780
+ }
1781
+ return i;
1782
+ }
1783
+ function isInstance(obj, type) {
1784
+ return obj instanceof type || obj != null && obj.constructor != null && obj.constructor.name != null && obj.constructor.name === type.name;
1785
+ }
1786
+ function numberIsNaN(obj) {
1787
+ return obj !== obj;
1788
+ }
1789
+ var hexSliceLookupTable = (function() {
1790
+ const alphabet = "0123456789abcdef";
1791
+ const table2 = new Array(256);
1792
+ for (let i = 0; i < 16; ++i) {
1793
+ const i16 = i * 16;
1794
+ for (let j = 0; j < 16; ++j) {
1795
+ table2[i16 + j] = alphabet[i] + alphabet[j];
1796
+ }
1797
+ }
1798
+ return table2;
1799
+ })();
1800
+ function defineBigIntMethod(fn) {
1801
+ return typeof BigInt === "undefined" ? BufferBigIntNotDefined : fn;
1802
+ }
1803
+ function BufferBigIntNotDefined() {
1804
+ throw new Error("BigInt not supported");
1805
+ }
1806
+ }
1807
+ });
1808
+
1809
+ // src/browser/buffer.ts
1810
+ var import_buffer;
1811
+ var init_buffer = __esm({
1812
+ "src/browser/buffer.ts"() {
1813
+ "use strict";
1814
+ import_buffer = __toESM(require_buffer(), 1);
1815
+ }
1816
+ });
1817
+
1818
+ // src/browser.ts
1819
+ init_buffer();
1820
+
1821
+ // src/nitro/nds-file.ts
1822
+ init_buffer();
1823
+
1824
+ // src/runtime/browser.ts
1825
+ init_buffer();
1826
+
1827
+ // node_modules/.pnpm/@noble+hashes@2.4.0/node_modules/@noble/hashes/legacy.js
1828
+ init_buffer();
1829
+
1830
+ // node_modules/.pnpm/@noble+hashes@2.4.0/node_modules/@noble/hashes/_md.js
1831
+ init_buffer();
1832
+
1833
+ // node_modules/.pnpm/@noble+hashes@2.4.0/node_modules/@noble/hashes/_u64.js
1834
+ init_buffer();
1835
+ var fromNumH = (n) => n / 2 ** 32 | 0;
1836
+ var fromNumL = (n) => n >>> 0;
1837
+ function setU64FromNum(view, byteOffset, n, isLE2) {
1838
+ const h = fromNumH(n);
1839
+ const l = fromNumL(n);
1840
+ view.setUint32(byteOffset, isLE2 ? l : h, isLE2);
1841
+ view.setUint32(byteOffset + 4, isLE2 ? h : l, isLE2);
1842
+ }
1843
+
1844
+ // node_modules/.pnpm/@noble+hashes@2.4.0/node_modules/@noble/hashes/utils.js
1845
+ init_buffer();
1846
+ function isBytes(a) {
1847
+ return a instanceof Uint8Array || ArrayBuffer.isView(a) && a.constructor.name === "Uint8Array" && "BYTES_PER_ELEMENT" in a && a.BYTES_PER_ELEMENT === 1;
1848
+ }
1849
+ var atitle = (title) => title ? `"${title}" ` : "";
1850
+ function anumber(n, title = "") {
1851
+ if (typeof n !== "number")
1852
+ throw new TypeError(atitle(title) + "expected number, got " + typeof n);
1853
+ if (!Number.isSafeInteger(n) || n < 0)
1854
+ throw new RangeError(atitle(title) + "expected integer >= 0, got " + n);
1855
+ return n;
1856
+ }
1857
+ function abytes(value, length, title = "") {
1858
+ if (isBytes(value) && (length === void 0 || value.length === length))
1859
+ return value;
1860
+ if (length !== void 0)
1861
+ anumber(length, "length");
1862
+ const bytes2 = isBytes(value);
1863
+ const ofLen = length !== void 0 ? ` of length ${length}` : "";
1864
+ const got = bytes2 ? `length=${value.length}` : `type=${typeof value}`;
1865
+ const message = atitle(title) + "expected Uint8Array" + ofLen + ", got " + got;
1866
+ if (!bytes2)
1867
+ throw new TypeError(message);
1868
+ throw new RangeError(message);
1869
+ }
1870
+ function ahash(h) {
1871
+ if (typeof h !== "function" || typeof h.create !== "function")
1872
+ throw new TypeError("expected hash wrapped by utils.createHasher");
1873
+ anumber(h.outputLen);
1874
+ anumber(h.blockLen);
1875
+ if (h.outputLen < 1 || h.blockLen < 1)
1876
+ throw new Error("hash blockLen / outputLen must be >= 1");
1877
+ }
1878
+ var aobject = (value, label) => {
1879
+ if (value === null || typeof value !== "object" || Array.isArray(value))
1880
+ throw new TypeError((label === "object" ? "" : `"${label}" `) + "expected object, got type=" + typeof value);
1881
+ };
1882
+ var aopts = (value, label) => {
1883
+ aobject(value, label);
1884
+ const proto = Object.getPrototypeOf(value);
1885
+ if (proto !== Object.prototype && proto !== null)
1886
+ throw new TypeError(`"${label}" expected plain object`);
1887
+ if (Object.hasOwn(value, "__proto__"))
1888
+ throw new TypeError(`"${label}.__proto__" is not allowed`);
1889
+ };
1890
+ function aexists(instance, checkFinished = true) {
1891
+ if (instance.destroyed)
1892
+ throw new Error("hash was destroyed");
1893
+ if (checkFinished && instance.finished)
1894
+ throw new Error("digest() was already called");
1895
+ }
1896
+ function aoutput(out, instance) {
1897
+ abytes(out, void 0, "output");
1898
+ const min = instance.outputLen;
1899
+ if (!(out.length >= min)) {
1900
+ throw new RangeError('"output" expected length >= ' + min);
1901
+ }
1902
+ }
1903
+ function clean(...arrays) {
1904
+ for (let i = 0; i < arrays.length; i++) {
1905
+ arrays[i].fill(0);
1906
+ }
1907
+ }
1908
+ function createView(arr) {
1909
+ return new DataView(arr.buffer, arr.byteOffset, arr.byteLength);
1910
+ }
1911
+ function rotl(word, shift) {
1912
+ return word << shift | word >>> 32 - shift >>> 0;
1913
+ }
1914
+ function checkOpts(defaults, opts, title = "opts") {
1915
+ aopts(defaults, "defaults");
1916
+ if (opts !== void 0)
1917
+ aopts(opts, title);
1918
+ const merged = Object.assign(/* @__PURE__ */ Object.create(null), defaults, opts);
1919
+ return merged;
1920
+ }
1921
+ function createHasher(hashCons, info = {}) {
1922
+ if (typeof hashCons !== "function")
1923
+ throw new TypeError('"hashCons" expected function, got type=' + typeof hashCons);
1924
+ info = checkOpts({}, info, "info");
1925
+ const hashC = (msg, opts) => hashCons(opts).update(msg).digest();
1926
+ const tmp = hashCons(void 0);
1927
+ hashC.outputLen = tmp.outputLen;
1928
+ hashC.blockLen = tmp.blockLen;
1929
+ hashC.canXOF = tmp.canXOF;
1930
+ hashC.create = (opts) => hashCons(opts);
1931
+ Object.assign(hashC, info);
1932
+ return Object.freeze(hashC);
1933
+ }
1934
+
1935
+ // node_modules/.pnpm/@noble+hashes@2.4.0/node_modules/@noble/hashes/_md.js
1936
+ function Chi(a, b, c) {
1937
+ return a & b ^ ~a & c;
1938
+ }
1939
+ function Maj(a, b, c) {
1940
+ return a & b ^ a & c ^ b & c;
1941
+ }
1942
+ var HashMD = class {
1943
+ blockLen;
1944
+ outputLen;
1945
+ canXOF = false;
1946
+ padOffset;
1947
+ isLE;
1948
+ // For partial updates less than block size
1949
+ buffer;
1950
+ view;
1951
+ finished = false;
1952
+ length = 0;
1953
+ pos = 0;
1954
+ destroyed = false;
1955
+ constructor(blockLen, outputLen, padOffset, isLE2) {
1956
+ this.blockLen = blockLen;
1957
+ this.outputLen = outputLen;
1958
+ this.padOffset = padOffset;
1959
+ this.isLE = isLE2;
1960
+ this.buffer = new Uint8Array(blockLen);
1961
+ this.view = createView(this.buffer);
1962
+ }
1963
+ update(data) {
1964
+ aexists(this);
1965
+ abytes(data);
1966
+ const { view, buffer, blockLen } = this;
1967
+ const len = data.length;
1968
+ let processed = false;
1969
+ for (let pos = 0; pos < len; ) {
1970
+ const take = Math.min(blockLen - this.pos, len - pos);
1971
+ if (take === blockLen) {
1972
+ const dataView = createView(data);
1973
+ for (; blockLen <= len - pos; pos += blockLen)
1974
+ this.process(dataView, pos);
1975
+ processed = true;
1976
+ continue;
1977
+ }
1978
+ buffer.set(pos === 0 && take === len ? data : data.subarray(pos, pos + take), this.pos);
1979
+ this.pos += take;
1980
+ pos += take;
1981
+ if (this.pos === blockLen) {
1982
+ this.process(view, 0);
1983
+ this.pos = 0;
1984
+ processed = true;
1985
+ }
1986
+ }
1987
+ this.length += data.length;
1988
+ if (processed)
1989
+ this.roundClean();
1990
+ return this;
1991
+ }
1992
+ digestInto(out) {
1993
+ aexists(this);
1994
+ aoutput(out, this);
1995
+ this.finished = true;
1996
+ const { buffer, view, blockLen, isLE: isLE2 } = this;
1997
+ let { pos } = this;
1998
+ buffer[pos++] = 128;
1999
+ buffer.fill(0, pos);
2000
+ if (this.padOffset > blockLen - pos) {
2001
+ this.process(view, 0);
2002
+ buffer.fill(0);
2003
+ }
2004
+ setU64FromNum(view, blockLen - 8, this.length * 8, isLE2);
2005
+ this.process(view, 0);
2006
+ this.roundClean();
2007
+ const oview = out === buffer ? view : createView(out);
2008
+ const len = this.outputLen;
2009
+ const outLen = len / 4;
2010
+ const state = this.get();
2011
+ if (len % 4 || outLen > state.length)
2012
+ throw new Error("invalid outputLen");
2013
+ for (let i = 0; i < outLen; i++)
2014
+ oview.setUint32(4 * i, state[i], isLE2);
2015
+ }
2016
+ digest() {
2017
+ const { buffer, outputLen } = this;
2018
+ this.digestInto(buffer);
2019
+ const res = buffer.slice(0, outputLen);
2020
+ this.destroy();
2021
+ return res;
2022
+ }
2023
+ _cloneIntoMeta(to) {
2024
+ const { buffer, length, finished, destroyed, pos } = this;
2025
+ to.destroyed = destroyed;
2026
+ to.finished = finished;
2027
+ to.length = length;
2028
+ to.pos = pos;
2029
+ if (pos)
2030
+ to.buffer.set(buffer);
2031
+ return to;
2032
+ }
2033
+ clone() {
2034
+ return this._cloneInto();
2035
+ }
2036
+ };
2037
+
2038
+ // node_modules/.pnpm/@noble+hashes@2.4.0/node_modules/@noble/hashes/legacy.js
2039
+ var SHA1_IV = /* @__PURE__ */ Uint32Array.from([
2040
+ 1732584193,
2041
+ 4023233417,
2042
+ 2562383102,
2043
+ 271733878,
2044
+ 3285377520
2045
+ ]);
2046
+ var SHA1_W = /* @__PURE__ */ new Uint32Array(80);
2047
+ var _SHA1 = class extends HashMD {
2048
+ A = SHA1_IV[0] | 0;
2049
+ B = SHA1_IV[1] | 0;
2050
+ C = SHA1_IV[2] | 0;
2051
+ D = SHA1_IV[3] | 0;
2052
+ E = SHA1_IV[4] | 0;
2053
+ constructor() {
2054
+ super(64, 20, 8, false);
2055
+ }
2056
+ get() {
2057
+ const { A, B, C, D, E } = this;
2058
+ return [A, B, C, D, E];
2059
+ }
2060
+ set(A, B, C, D, E) {
2061
+ this.A = A | 0;
2062
+ this.B = B | 0;
2063
+ this.C = C | 0;
2064
+ this.D = D | 0;
2065
+ this.E = E | 0;
2066
+ }
2067
+ _cloneInto(to) {
2068
+ (to ||= new this.constructor()).set(...this.get());
2069
+ return this._cloneIntoMeta(to);
2070
+ }
2071
+ process(view, offset) {
2072
+ for (let i = 0; i < 16; i++, offset += 4)
2073
+ SHA1_W[i] = view.getUint32(offset, false);
2074
+ for (let i = 16; i < 80; i++)
2075
+ SHA1_W[i] = rotl(SHA1_W[i - 3] ^ SHA1_W[i - 8] ^ SHA1_W[i - 14] ^ SHA1_W[i - 16], 1);
2076
+ let { A, B, C, D, E } = this;
2077
+ for (let i = 0; i < 80; i++) {
2078
+ let F, K2;
2079
+ if (i < 20) {
2080
+ F = Chi(B, C, D);
2081
+ K2 = 1518500249;
2082
+ } else if (i < 40) {
2083
+ F = B ^ C ^ D;
2084
+ K2 = 1859775393;
2085
+ } else if (i < 60) {
2086
+ F = Maj(B, C, D);
2087
+ K2 = 2400959708;
2088
+ } else {
2089
+ F = B ^ C ^ D;
2090
+ K2 = 3395469782;
2091
+ }
2092
+ const T = rotl(A, 5) + F + E + K2 + SHA1_W[i] | 0;
2093
+ E = D;
2094
+ D = C;
2095
+ C = rotl(B, 30);
2096
+ B = A;
2097
+ A = T;
2098
+ }
2099
+ A = A + this.A | 0;
2100
+ B = B + this.B | 0;
2101
+ C = C + this.C | 0;
2102
+ D = D + this.D | 0;
2103
+ E = E + this.E | 0;
2104
+ this.set(A, B, C, D, E);
2105
+ }
2106
+ roundClean() {
2107
+ clean(SHA1_W);
2108
+ }
2109
+ destroy() {
2110
+ this.destroyed = true;
2111
+ this.set(0, 0, 0, 0, 0);
2112
+ clean(this.buffer);
2113
+ }
2114
+ };
2115
+ var sha1 = /* @__PURE__ */ createHasher(() => new _SHA1());
2116
+ var p32 = /* @__PURE__ */ Math.pow(2, 32);
2117
+ var K = /* @__PURE__ */ Array.from({ length: 64 }, (_, i) => Math.floor(p32 * Math.abs(Math.sin(i + 1))));
2118
+ var MD5_IV = /* @__PURE__ */ SHA1_IV.slice(0, 4);
2119
+ var MD5_W = /* @__PURE__ */ new Uint32Array(16);
2120
+ var MD5_SHIFTS = /* @__PURE__ */ (() => {
2121
+ const S = [
2122
+ [7, 12, 17, 22],
2123
+ [5, 9, 14, 20],
2124
+ [4, 11, 16, 23],
2125
+ [6, 10, 15, 21]
2126
+ ];
2127
+ return Uint8Array.from({ length: 64 }, (_, i) => S[Math.floor(i / 16)][i % 4]);
2128
+ })();
2129
+ var _MD5 = class extends HashMD {
2130
+ A = MD5_IV[0] | 0;
2131
+ B = MD5_IV[1] | 0;
2132
+ C = MD5_IV[2] | 0;
2133
+ D = MD5_IV[3] | 0;
2134
+ constructor() {
2135
+ super(64, 16, 8, true);
2136
+ }
2137
+ get() {
2138
+ const { A, B, C, D } = this;
2139
+ return [A, B, C, D];
2140
+ }
2141
+ set(A, B, C, D) {
2142
+ this.A = A | 0;
2143
+ this.B = B | 0;
2144
+ this.C = C | 0;
2145
+ this.D = D | 0;
2146
+ }
2147
+ _cloneInto(to) {
2148
+ (to ||= new this.constructor()).set(...this.get());
2149
+ return this._cloneIntoMeta(to);
2150
+ }
2151
+ process(view, offset) {
2152
+ for (let i = 0; i < 16; i++, offset += 4)
2153
+ MD5_W[i] = view.getUint32(offset, true);
2154
+ let { A, B, C, D } = this;
2155
+ for (let i = 0; i < 64; i++) {
2156
+ let F, g;
2157
+ if (i < 16) {
2158
+ F = Chi(B, C, D);
2159
+ g = i;
2160
+ } else if (i < 32) {
2161
+ F = Chi(D, B, C);
2162
+ g = (5 * i + 1) % 16;
2163
+ } else if (i < 48) {
2164
+ F = B ^ C ^ D;
2165
+ g = (3 * i + 5) % 16;
2166
+ } else {
2167
+ F = C ^ (B | ~D);
2168
+ g = 7 * i % 16;
2169
+ }
2170
+ F = F + A + K[i] + MD5_W[g];
2171
+ A = D;
2172
+ D = C;
2173
+ C = B;
2174
+ B = B + rotl(F, MD5_SHIFTS[i]);
2175
+ }
2176
+ A = A + this.A | 0;
2177
+ B = B + this.B | 0;
2178
+ C = C + this.C | 0;
2179
+ D = D + this.D | 0;
2180
+ this.set(A, B, C, D);
2181
+ }
2182
+ roundClean() {
2183
+ clean(MD5_W);
2184
+ }
2185
+ destroy() {
2186
+ this.destroyed = true;
2187
+ this.set(0, 0, 0, 0);
2188
+ clean(this.buffer);
2189
+ }
2190
+ };
2191
+ var md5 = /* @__PURE__ */ createHasher(() => new _MD5());
2192
+
2193
+ // node_modules/.pnpm/@noble+hashes@2.4.0/node_modules/@noble/hashes/hmac.js
2194
+ init_buffer();
2195
+ var _HMAC = class {
2196
+ oHash;
2197
+ iHash;
2198
+ blockLen;
2199
+ outputLen;
2200
+ canXOF = false;
2201
+ finished = false;
2202
+ destroyed = false;
2203
+ constructor(hash2, key2) {
2204
+ ahash(hash2);
2205
+ abytes(key2, void 0, "key");
2206
+ this.iHash = hash2.create();
2207
+ if (typeof this.iHash.update !== "function")
2208
+ throw new Error("expected Hash instance");
2209
+ this.blockLen = this.iHash.blockLen;
2210
+ this.outputLen = this.iHash.outputLen;
2211
+ const blockLen = this.blockLen;
2212
+ const pad = new Uint8Array(blockLen);
2213
+ pad.set(key2.length > blockLen ? hash2.create().update(key2).digest() : key2);
2214
+ for (let i = 0; i < pad.length; i++)
2215
+ pad[i] ^= 54;
2216
+ this.iHash.update(pad);
2217
+ this.oHash = hash2.create();
2218
+ for (let i = 0; i < pad.length; i++)
2219
+ pad[i] ^= 54 ^ 92;
2220
+ this.oHash.update(pad);
2221
+ clean(pad);
2222
+ }
2223
+ update(buf) {
2224
+ aexists(this);
2225
+ this.iHash.update(buf);
2226
+ return this;
2227
+ }
2228
+ digestInto(out) {
2229
+ aexists(this);
2230
+ aoutput(out, this);
2231
+ this.finished = true;
2232
+ const buf = out.subarray(0, this.outputLen);
2233
+ this.iHash.digestInto(buf);
2234
+ this.oHash.update(buf);
2235
+ this.oHash.digestInto(buf);
2236
+ this.destroy();
2237
+ }
2238
+ digest() {
2239
+ const out = new Uint8Array(this.oHash.outputLen);
2240
+ this.digestInto(out);
2241
+ return out;
2242
+ }
2243
+ _cloneInto(to) {
2244
+ to ||= Object.create(Object.getPrototypeOf(this), {});
2245
+ const { oHash, iHash, finished, destroyed, blockLen, outputLen, canXOF } = this;
2246
+ to = to;
2247
+ to.finished = finished;
2248
+ to.destroyed = destroyed;
2249
+ to.blockLen = blockLen;
2250
+ to.outputLen = outputLen;
2251
+ to.canXOF = canXOF;
2252
+ to.oHash = oHash._cloneInto(to.oHash);
2253
+ to.iHash = iHash._cloneInto(to.iHash);
2254
+ return to;
2255
+ }
2256
+ clone() {
2257
+ return this._cloneInto();
2258
+ }
2259
+ destroy() {
2260
+ this.destroyed = true;
2261
+ this.oHash.destroy();
2262
+ this.iHash.destroy();
2263
+ }
2264
+ };
2265
+ var hmac = /* @__PURE__ */ (() => {
2266
+ const hmac_ = ((hash2, key2, message) => new _HMAC(hash2, key2).update(message).digest());
2267
+ hmac_.create = (hash2, key2) => new _HMAC(hash2, key2);
2268
+ return hmac_;
2269
+ })();
2270
+
2271
+ // node_modules/.pnpm/@noble+ciphers@2.4.0/node_modules/@noble/ciphers/aes.js
2272
+ init_buffer();
2273
+
2274
+ // node_modules/.pnpm/@noble+ciphers@2.4.0/node_modules/@noble/ciphers/utils.js
2275
+ init_buffer();
2276
+ function isBytes2(a) {
2277
+ return a instanceof Uint8Array || ArrayBuffer.isView(a) && a.constructor.name === "Uint8Array" && "BYTES_PER_ELEMENT" in a && a.BYTES_PER_ELEMENT === 1;
2278
+ }
2279
+ var atitle2 = (title) => title ? `"${title}" ` : "";
2280
+ function anumber2(n, title = "") {
2281
+ if (typeof n !== "number")
2282
+ throw new TypeError(atitle2(title) + "expected number, got " + typeof n);
2283
+ if (!Number.isSafeInteger(n) || n < 0)
2284
+ throw new RangeError(atitle2(title) + "expected integer >= 0, got " + n);
2285
+ return n;
2286
+ }
2287
+ function abytes2(value, length, title = "") {
2288
+ if (isBytes2(value) && (length === void 0 || value.length === length))
2289
+ return value;
2290
+ if (length !== void 0)
2291
+ anumber2(length, "length");
2292
+ const bytes2 = isBytes2(value);
2293
+ const ofLen = length !== void 0 ? ` of length ${length}` : "";
2294
+ const got = bytes2 ? `length=${value.length}` : `type=${typeof value}`;
2295
+ const message = atitle2(title) + "expected Uint8Array" + ofLen + ", got " + got;
2296
+ if (!bytes2)
2297
+ throw new TypeError(message);
2298
+ throw new RangeError(message);
2299
+ }
2300
+ function u32(arr) {
2301
+ return new Uint32Array(arr.buffer, arr.byteOffset, Math.floor(arr.byteLength / 4));
2302
+ }
2303
+ function clean2(...arrays) {
2304
+ for (let i = 0; i < arrays.length; i++) {
2305
+ arrays[i].fill(0);
2306
+ }
2307
+ }
2308
+ var isLE = /* @__PURE__ */ (() => new Uint8Array(new Uint32Array([287454020]).buffer)[0] === 68)();
2309
+ function byteSwap(word) {
2310
+ return word << 24 & 4278190080 | word << 8 & 16711680 | word >>> 8 & 65280 | word >>> 24 & 255;
2311
+ }
2312
+ function byteSwap32(arr) {
2313
+ for (let i = 0; i < arr.length; i++) {
2314
+ arr[i] = byteSwap(arr[i]);
2315
+ }
2316
+ return arr;
2317
+ }
2318
+ var swap32IfBE = isLE ? (u) => u : byteSwap32;
2319
+ function overlapBytes(a, b) {
2320
+ if (!a.byteLength || !b.byteLength)
2321
+ return false;
2322
+ return a.buffer === b.buffer && // best we can do, may fail with an obscure Proxy
2323
+ a.byteOffset < b.byteOffset + b.byteLength && // a starts before b end
2324
+ b.byteOffset < a.byteOffset + a.byteLength;
2325
+ }
2326
+ function complexOverlapBytes(input, output) {
2327
+ if (overlapBytes(input, output) && input.byteOffset < output.byteOffset)
2328
+ throw new Error("complex overlap of input and output is not supported");
2329
+ }
2330
+ var wrapCipher = /* @__NO_SIDE_EFFECTS__ */ (params, constructor) => {
2331
+ function wrappedCipher(key2, ...args) {
2332
+ abytes2(key2, void 0, "key");
2333
+ if (params.nonceLength !== void 0) {
2334
+ const nonce = args[0];
2335
+ abytes2(nonce, params.varSizeNonce ? void 0 : params.nonceLength, "nonce");
2336
+ }
2337
+ const tagl = params.tagLength;
2338
+ const aadStart = params.nonceLength !== void 0 ? 1 : 0;
2339
+ if (!params.withAAD) {
2340
+ for (let i = aadStart; i < args.length; i++)
2341
+ if (isBytes2(args[i]))
2342
+ throw new Error("AAD not supported");
2343
+ }
2344
+ if (params.withAAD && args[aadStart] !== void 0)
2345
+ abytes2(args[aadStart], void 0, "AAD");
2346
+ const cipher = constructor(key2, ...args);
2347
+ const checkOutput = (fnLength, output) => {
2348
+ if (output !== void 0) {
2349
+ if (fnLength !== 2)
2350
+ throw new Error("cipher output not supported");
2351
+ abytes2(output, void 0, "output");
2352
+ }
2353
+ };
2354
+ let called = false;
2355
+ const wrCipher = {
2356
+ encrypt(data, output) {
2357
+ if (called)
2358
+ throw new Error("cannot encrypt() twice with same key + nonce");
2359
+ called = true;
2360
+ abytes2(data, void 0, "data");
2361
+ checkOutput(cipher.encrypt.length, output);
2362
+ return cipher.encrypt(data, output);
2363
+ },
2364
+ decrypt(data, output) {
2365
+ abytes2(data, void 0, "data");
2366
+ if (tagl && data.length < tagl)
2367
+ throw new Error('"ciphertext" expected length >= tagLength=' + tagl);
2368
+ checkOutput(cipher.decrypt.length, output);
2369
+ return cipher.decrypt(data, output);
2370
+ }
2371
+ };
2372
+ return wrCipher;
2373
+ }
2374
+ Object.assign(wrappedCipher, params);
2375
+ return wrappedCipher;
2376
+ };
2377
+ function getOutput(expectedLength, out, onlyAligned = true) {
2378
+ if (out === void 0)
2379
+ return new Uint8Array(expectedLength);
2380
+ abytes2(out, expectedLength, "output");
2381
+ if (onlyAligned && !isAligned32(out))
2382
+ throw new Error("invalid output, must be aligned");
2383
+ return out;
2384
+ }
2385
+ function isAligned32(bytes2) {
2386
+ return bytes2.byteOffset % 4 === 0;
2387
+ }
2388
+ function copyBytes(bytes2) {
2389
+ return Uint8Array.from(abytes2(bytes2));
2390
+ }
2391
+
2392
+ // node_modules/.pnpm/@noble+ciphers@2.4.0/node_modules/@noble/ciphers/aes.js
2393
+ var BLOCK_SIZE = 16;
2394
+ var POLY = 283;
2395
+ function validateKeyLength(key2) {
2396
+ if (![16, 24, 32].includes(key2.length))
2397
+ throw new Error('"aes key" expected Uint8Array of length 16/24/32, got length=' + key2.length);
2398
+ }
2399
+ function mul2(n) {
2400
+ return n << 1 ^ POLY & -(n >> 7);
2401
+ }
2402
+ function mul(a, b) {
2403
+ let res = 0;
2404
+ for (; b > 0; b >>= 1) {
2405
+ res ^= a & -(b & 1);
2406
+ a = mul2(a);
2407
+ }
2408
+ return res;
2409
+ }
2410
+ var sbox = /* @__PURE__ */ (() => {
2411
+ const t = new Uint8Array(256);
2412
+ for (let i = 0, x = 1; i < 256; i++, x ^= mul2(x))
2413
+ t[i] = x;
2414
+ const box = new Uint8Array(256);
2415
+ box[0] = 99;
2416
+ for (let i = 0; i < 255; i++) {
2417
+ let x = t[255 - i];
2418
+ x |= x << 8;
2419
+ box[t[i]] = (x ^ x >> 4 ^ x >> 5 ^ x >> 6 ^ x >> 7 ^ 99) & 255;
2420
+ }
2421
+ clean2(t);
2422
+ return box;
2423
+ })();
2424
+ var invSbox = /* @__PURE__ */ sbox.map((_, j) => sbox.indexOf(j));
2425
+ var rotr32_8 = (n) => n << 24 | n >>> 8;
2426
+ var rotl32_8 = (n) => n << 8 | n >>> 24;
2427
+ function genTtable(sbox2, fn) {
2428
+ if (sbox2.length !== 256)
2429
+ throw new Error("wrong sbox length");
2430
+ const T0 = new Uint32Array(256).map((_, j) => fn(sbox2[j]));
2431
+ const T1 = T0.map(rotl32_8);
2432
+ const T2 = T1.map(rotl32_8);
2433
+ const T3 = T2.map(rotl32_8);
2434
+ const T01 = new Uint32Array(256 * 256);
2435
+ const T23 = new Uint32Array(256 * 256);
2436
+ const sbox22 = new Uint16Array(256 * 256);
2437
+ for (let i = 0; i < 256; i++) {
2438
+ for (let j = 0; j < 256; j++) {
2439
+ const idx = i * 256 + j;
2440
+ T01[idx] = T0[i] ^ T1[j];
2441
+ T23[idx] = T2[i] ^ T3[j];
2442
+ sbox22[idx] = sbox2[i] << 8 | sbox2[j];
2443
+ }
2444
+ }
2445
+ return { sbox: sbox2, sbox2: sbox22, T0, T1, T2, T3, T01, T23 };
2446
+ }
2447
+ var tableEncoding = /* @__PURE__ */ genTtable(sbox, (s) => mul(s, 3) << 24 | s << 16 | s << 8 | mul(s, 2));
2448
+ var tableDecoding = /* @__PURE__ */ genTtable(invSbox, (s) => mul(s, 11) << 24 | mul(s, 13) << 16 | mul(s, 9) << 8 | mul(s, 14));
2449
+ var xPowers = /* @__PURE__ */ (() => {
2450
+ const p = new Uint8Array(16);
2451
+ for (let i = 0, x = 1; i < 16; i++, x = mul2(x))
2452
+ p[i] = x;
2453
+ return p;
2454
+ })();
2455
+ function expandKeyLE(key2) {
2456
+ abytes2(key2);
2457
+ const len = key2.length;
2458
+ validateKeyLength(key2);
2459
+ const { sbox2 } = tableEncoding;
2460
+ const toClean = [];
2461
+ if (!isLE || !isAligned32(key2))
2462
+ toClean.push(key2 = copyBytes(key2));
2463
+ const k32 = swap32IfBE(u32(key2));
2464
+ const Nk = k32.length;
2465
+ const subByte = (n) => applySbox(sbox2, n, n, n, n);
2466
+ const xk = new Uint32Array(len + 28);
2467
+ xk.set(k32);
2468
+ for (let i = Nk; i < xk.length; i++) {
2469
+ let t = xk[i - 1];
2470
+ if (i % Nk === 0)
2471
+ t = subByte(rotr32_8(t)) ^ xPowers[i / Nk - 1];
2472
+ else if (Nk > 6 && i % Nk === 4)
2473
+ t = subByte(t);
2474
+ xk[i] = xk[i - Nk] ^ t;
2475
+ }
2476
+ clean2(...toClean);
2477
+ return xk;
2478
+ }
2479
+ function expandKeyDecLE(key2) {
2480
+ const encKey = expandKeyLE(key2);
2481
+ const xk = encKey.slice();
2482
+ const Nk = encKey.length;
2483
+ const { sbox2 } = tableEncoding;
2484
+ const { T0, T1, T2, T3 } = tableDecoding;
2485
+ for (let i = 0; i < Nk; i += 4) {
2486
+ for (let j = 0; j < 4; j++)
2487
+ xk[i + j] = encKey[Nk - i - 4 + j];
2488
+ }
2489
+ clean2(encKey);
2490
+ for (let i = 4; i < Nk - 4; i++) {
2491
+ const x = xk[i];
2492
+ const w = applySbox(sbox2, x, x, x, x);
2493
+ xk[i] = T0[w & 255] ^ T1[w >>> 8 & 255] ^ T2[w >>> 16 & 255] ^ T3[w >>> 24];
2494
+ }
2495
+ return xk;
2496
+ }
2497
+ function apply0123(T01, T23, s0, s1, s2, s3) {
2498
+ return T01[s0 << 8 & 65280 | s1 >>> 8 & 255] ^ T23[s2 >>> 8 & 65280 | s3 >>> 24 & 255];
2499
+ }
2500
+ function applySbox(sbox2, s0, s1, s2, s3) {
2501
+ return sbox2[s0 & 255 | s1 & 65280] | sbox2[s2 >>> 16 & 255 | s3 >>> 16 & 65280] << 16;
2502
+ }
2503
+ function encrypt(xk, s0, s1, s2, s3) {
2504
+ const { sbox2, T01, T23 } = tableEncoding;
2505
+ let k = 0;
2506
+ s0 ^= xk[k++], s1 ^= xk[k++], s2 ^= xk[k++], s3 ^= xk[k++];
2507
+ const rounds = xk.length / 4 - 2;
2508
+ for (let i = 0; i < rounds; i++) {
2509
+ const t02 = xk[k++] ^ apply0123(T01, T23, s0, s1, s2, s3);
2510
+ const t12 = xk[k++] ^ apply0123(T01, T23, s1, s2, s3, s0);
2511
+ const t22 = xk[k++] ^ apply0123(T01, T23, s2, s3, s0, s1);
2512
+ const t32 = xk[k++] ^ apply0123(T01, T23, s3, s0, s1, s2);
2513
+ s0 = t02, s1 = t12, s2 = t22, s3 = t32;
2514
+ }
2515
+ const t0 = xk[k++] ^ applySbox(sbox2, s0, s1, s2, s3);
2516
+ const t1 = xk[k++] ^ applySbox(sbox2, s1, s2, s3, s0);
2517
+ const t2 = xk[k++] ^ applySbox(sbox2, s2, s3, s0, s1);
2518
+ const t3 = xk[k++] ^ applySbox(sbox2, s3, s0, s1, s2);
2519
+ return { s0: t0, s1: t1, s2: t2, s3: t3 };
2520
+ }
2521
+ function decrypt(xk, s0, s1, s2, s3) {
2522
+ const { sbox2, T01, T23 } = tableDecoding;
2523
+ let k = 0;
2524
+ s0 ^= xk[k++], s1 ^= xk[k++], s2 ^= xk[k++], s3 ^= xk[k++];
2525
+ const rounds = xk.length / 4 - 2;
2526
+ for (let i = 0; i < rounds; i++) {
2527
+ const t02 = xk[k++] ^ apply0123(T01, T23, s0, s3, s2, s1);
2528
+ const t12 = xk[k++] ^ apply0123(T01, T23, s1, s0, s3, s2);
2529
+ const t22 = xk[k++] ^ apply0123(T01, T23, s2, s1, s0, s3);
2530
+ const t32 = xk[k++] ^ apply0123(T01, T23, s3, s2, s1, s0);
2531
+ s0 = t02, s1 = t12, s2 = t22, s3 = t32;
2532
+ }
2533
+ const t0 = xk[k++] ^ applySbox(sbox2, s0, s3, s2, s1);
2534
+ const t1 = xk[k++] ^ applySbox(sbox2, s1, s0, s3, s2);
2535
+ const t2 = xk[k++] ^ applySbox(sbox2, s2, s1, s0, s3);
2536
+ const t3 = xk[k++] ^ applySbox(sbox2, s3, s2, s1, s0);
2537
+ return { s0: t0, s1: t1, s2: t2, s3: t3 };
2538
+ }
2539
+ function validateBlockDecrypt(data, dst) {
2540
+ abytes2(data);
2541
+ if (data.length % BLOCK_SIZE !== 0) {
2542
+ throw new Error("ciphertext must be multiple of " + BLOCK_SIZE);
2543
+ }
2544
+ if (dst !== void 0) {
2545
+ getOutput(data.length, dst);
2546
+ complexOverlapBytes(data, dst);
2547
+ }
2548
+ }
2549
+ function validateBlockEncrypt(plaintext, pkcs5, dst) {
2550
+ abytes2(plaintext);
2551
+ let outLen = plaintext.length;
2552
+ const remaining = outLen % BLOCK_SIZE;
2553
+ if (!pkcs5 && remaining !== 0)
2554
+ throw new Error("plaintext must be multiple of " + BLOCK_SIZE);
2555
+ if (pkcs5) {
2556
+ let left = BLOCK_SIZE - remaining;
2557
+ if (!left)
2558
+ left = BLOCK_SIZE;
2559
+ outLen = outLen + left;
2560
+ }
2561
+ if (dst !== void 0) {
2562
+ getOutput(outLen, dst);
2563
+ complexOverlapBytes(plaintext, dst);
2564
+ }
2565
+ return outLen;
2566
+ }
2567
+ function prepareBlockEncrypt(plaintext, outLen, dst) {
2568
+ if (dst === void 0)
2569
+ dst = new Uint8Array(outLen);
2570
+ if (!isLE || !isAligned32(plaintext))
2571
+ plaintext = copyBytes(plaintext);
2572
+ const o = u32(dst);
2573
+ return { b: plaintext, o, out: dst };
2574
+ }
2575
+ function validatePKCS(data, pkcs5) {
2576
+ if (!pkcs5)
2577
+ return data;
2578
+ const len = data.length;
2579
+ if (len === 0)
2580
+ throw new Error("pkcs7: empty ciphertext not allowed");
2581
+ const lastByte = data[len - 1];
2582
+ let valid = 1;
2583
+ valid &= lastByte - 1 >>> 31 ^ 1;
2584
+ valid &= 16 - lastByte >>> 31 ^ 1;
2585
+ for (let i = 0; i < 16; i++) {
2586
+ const shouldCheck = i - lastByte >>> 31;
2587
+ const eq = (data[len - 1 - i] ^ lastByte) === 0 ? 1 : 0;
2588
+ valid &= eq | shouldCheck ^ 1;
2589
+ }
2590
+ if (!valid)
2591
+ throw new Error("aes: bad decrypt");
2592
+ return data.subarray(0, len - lastByte);
2593
+ }
2594
+ function padPCKS(left) {
2595
+ const tmp = new Uint8Array(16);
2596
+ const tmp32 = u32(tmp);
2597
+ tmp.set(left);
2598
+ const paddingByte = BLOCK_SIZE - left.length;
2599
+ for (let i = BLOCK_SIZE - paddingByte; i < BLOCK_SIZE; i++)
2600
+ tmp[i] = paddingByte;
2601
+ return tmp32;
2602
+ }
2603
+ var ecb = /* @__PURE__ */ wrapCipher({ blockSize: 16 }, function aesecb(key2, opts = {}) {
2604
+ const pkcs5 = !opts.disablePadding;
2605
+ return {
2606
+ encrypt(plaintext, dst) {
2607
+ const outLen = validateBlockEncrypt(plaintext, pkcs5, dst);
2608
+ const xk = expandKeyLE(key2);
2609
+ const { b: input, o, out: _out } = prepareBlockEncrypt(plaintext, outLen, dst);
2610
+ const b = u32(input);
2611
+ swap32IfBE(b);
2612
+ let i = 0;
2613
+ for (; i + 4 <= b.length; ) {
2614
+ const { s0, s1, s2, s3 } = encrypt(xk, b[i + 0], b[i + 1], b[i + 2], b[i + 3]);
2615
+ o[i++] = s0, o[i++] = s1, o[i++] = s2, o[i++] = s3;
2616
+ }
2617
+ if (pkcs5) {
2618
+ const tmp32 = padPCKS(plaintext.subarray(i * 4));
2619
+ swap32IfBE(tmp32);
2620
+ const { s0, s1, s2, s3 } = encrypt(xk, tmp32[0], tmp32[1], tmp32[2], tmp32[3]);
2621
+ o[i++] = s0, o[i++] = s1, o[i++] = s2, o[i++] = s3;
2622
+ clean2(tmp32);
2623
+ }
2624
+ swap32IfBE(o);
2625
+ clean2(xk);
2626
+ if (input !== plaintext)
2627
+ clean2(input);
2628
+ return _out;
2629
+ },
2630
+ decrypt(ciphertext, dst) {
2631
+ validateBlockDecrypt(ciphertext, dst);
2632
+ const xk = expandKeyDecLE(key2);
2633
+ if (dst === void 0)
2634
+ dst = new Uint8Array(ciphertext.length);
2635
+ const toClean = [xk];
2636
+ if (!isLE || !isAligned32(ciphertext))
2637
+ toClean.push(ciphertext = copyBytes(ciphertext));
2638
+ const b = u32(ciphertext);
2639
+ const o = u32(dst);
2640
+ swap32IfBE(b);
2641
+ for (let i = 0; i + 4 <= b.length; ) {
2642
+ const { s0, s1, s2, s3 } = decrypt(xk, b[i + 0], b[i + 1], b[i + 2], b[i + 3]);
2643
+ o[i++] = s0, o[i++] = s1, o[i++] = s2, o[i++] = s3;
2644
+ }
2645
+ swap32IfBE(o);
2646
+ clean2(...toClean);
2647
+ return validatePKCS(dst, pkcs5);
2648
+ }
2649
+ };
2650
+ });
2651
+
2652
+ // node_modules/.pnpm/fflate@0.8.3/node_modules/fflate/esm/browser.js
2653
+ init_buffer();
2654
+ var u82 = Uint8Array;
2655
+ var u16 = Uint16Array;
2656
+ var i32 = Int32Array;
2657
+ var fleb = new u82([
2658
+ 0,
2659
+ 0,
2660
+ 0,
2661
+ 0,
2662
+ 0,
2663
+ 0,
2664
+ 0,
2665
+ 0,
2666
+ 1,
2667
+ 1,
2668
+ 1,
2669
+ 1,
2670
+ 2,
2671
+ 2,
2672
+ 2,
2673
+ 2,
2674
+ 3,
2675
+ 3,
2676
+ 3,
2677
+ 3,
2678
+ 4,
2679
+ 4,
2680
+ 4,
2681
+ 4,
2682
+ 5,
2683
+ 5,
2684
+ 5,
2685
+ 5,
2686
+ 0,
2687
+ /* unused */
2688
+ 0,
2689
+ 0,
2690
+ /* impossible */
2691
+ 0
2692
+ ]);
2693
+ var fdeb = new u82([
2694
+ 0,
2695
+ 0,
2696
+ 0,
2697
+ 0,
2698
+ 1,
2699
+ 1,
2700
+ 2,
2701
+ 2,
2702
+ 3,
2703
+ 3,
2704
+ 4,
2705
+ 4,
2706
+ 5,
2707
+ 5,
2708
+ 6,
2709
+ 6,
2710
+ 7,
2711
+ 7,
2712
+ 8,
2713
+ 8,
2714
+ 9,
2715
+ 9,
2716
+ 10,
2717
+ 10,
2718
+ 11,
2719
+ 11,
2720
+ 12,
2721
+ 12,
2722
+ 13,
2723
+ 13,
2724
+ /* unused */
2725
+ 0,
2726
+ 0
2727
+ ]);
2728
+ var clim = new u82([16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15]);
2729
+ var freb = function(eb, start) {
2730
+ var b = new u16(31);
2731
+ for (var i = 0; i < 31; ++i) {
2732
+ b[i] = start += 1 << eb[i - 1];
2733
+ }
2734
+ var r = new i32(b[30]);
2735
+ for (var i = 1; i < 30; ++i) {
2736
+ for (var j = b[i]; j < b[i + 1]; ++j) {
2737
+ r[j] = j - b[i] << 5 | i;
2738
+ }
2739
+ }
2740
+ return { b, r };
2741
+ };
2742
+ var _a = freb(fleb, 2);
2743
+ var fl = _a.b;
2744
+ var revfl = _a.r;
2745
+ fl[28] = 258, revfl[258] = 28;
2746
+ var _b = freb(fdeb, 0);
2747
+ var fd = _b.b;
2748
+ var revfd = _b.r;
2749
+ var rev = new u16(32768);
2750
+ for (i = 0; i < 32768; ++i) {
2751
+ x = (i & 43690) >> 1 | (i & 21845) << 1;
2752
+ x = (x & 52428) >> 2 | (x & 13107) << 2;
2753
+ x = (x & 61680) >> 4 | (x & 3855) << 4;
2754
+ rev[i] = ((x & 65280) >> 8 | (x & 255) << 8) >> 1;
2755
+ }
2756
+ var x;
2757
+ var i;
2758
+ var hMap = (function(cd, mb, r) {
2759
+ var s = cd.length;
2760
+ var i = 0;
2761
+ var l = new u16(mb);
2762
+ for (; i < s; ++i) {
2763
+ if (cd[i])
2764
+ ++l[cd[i] - 1];
2765
+ }
2766
+ var le = new u16(mb);
2767
+ for (i = 1; i < mb; ++i) {
2768
+ le[i] = le[i - 1] + l[i - 1] << 1;
2769
+ }
2770
+ var co;
2771
+ if (r) {
2772
+ co = new u16(1 << mb);
2773
+ var rvb = 15 - mb;
2774
+ for (i = 0; i < s; ++i) {
2775
+ if (cd[i]) {
2776
+ var sv = i << 4 | cd[i];
2777
+ var r_1 = mb - cd[i];
2778
+ var v = le[cd[i] - 1]++ << r_1;
2779
+ for (var m = v | (1 << r_1) - 1; v <= m; ++v) {
2780
+ co[rev[v] >> rvb] = sv;
2781
+ }
2782
+ }
2783
+ }
2784
+ } else {
2785
+ co = new u16(s);
2786
+ for (i = 0; i < s; ++i) {
2787
+ if (cd[i]) {
2788
+ co[i] = rev[le[cd[i] - 1]++] >> 15 - cd[i];
2789
+ }
2790
+ }
2791
+ }
2792
+ return co;
2793
+ });
2794
+ var flt = new u82(288);
2795
+ for (i = 0; i < 144; ++i)
2796
+ flt[i] = 8;
2797
+ var i;
2798
+ for (i = 144; i < 256; ++i)
2799
+ flt[i] = 9;
2800
+ var i;
2801
+ for (i = 256; i < 280; ++i)
2802
+ flt[i] = 7;
2803
+ var i;
2804
+ for (i = 280; i < 288; ++i)
2805
+ flt[i] = 8;
2806
+ var i;
2807
+ var fdt = new u82(32);
2808
+ for (i = 0; i < 32; ++i)
2809
+ fdt[i] = 5;
2810
+ var i;
2811
+ var flrm = /* @__PURE__ */ hMap(flt, 9, 1);
2812
+ var fdrm = /* @__PURE__ */ hMap(fdt, 5, 1);
2813
+ var max = function(a) {
2814
+ var m = a[0];
2815
+ for (var i = 1; i < a.length; ++i) {
2816
+ if (a[i] > m)
2817
+ m = a[i];
2818
+ }
2819
+ return m;
2820
+ };
2821
+ var bits = function(d, p, m) {
2822
+ var o = p / 8 | 0;
2823
+ return (d[o] | d[o + 1] << 8) >> (p & 7) & m;
2824
+ };
2825
+ var bits16 = function(d, p) {
2826
+ var o = p / 8 | 0;
2827
+ return (d[o] | d[o + 1] << 8 | d[o + 2] << 16) >> (p & 7);
2828
+ };
2829
+ var shft = function(p) {
2830
+ return (p + 7) / 8 | 0;
2831
+ };
2832
+ var slc = function(v, s, e) {
2833
+ if (s == null || s < 0)
2834
+ s = 0;
2835
+ if (e == null || e > v.length)
2836
+ e = v.length;
2837
+ return new u82(v.subarray(s, e));
2838
+ };
2839
+ var ec = [
2840
+ "unexpected EOF",
2841
+ "invalid block type",
2842
+ "invalid length/literal",
2843
+ "invalid distance",
2844
+ "stream finished",
2845
+ "no stream handler",
2846
+ ,
2847
+ // determined by compression function
2848
+ "no callback",
2849
+ "invalid UTF-8 data",
2850
+ "extra field too long",
2851
+ "date not in range 1980-2099",
2852
+ "filename too long",
2853
+ "stream finishing",
2854
+ "invalid zip data"
2855
+ // determined by unknown compression method
2856
+ ];
2857
+ var err = function(ind, msg, nt) {
2858
+ var e = new Error(msg || ec[ind]);
2859
+ e.code = ind;
2860
+ if (Error.captureStackTrace)
2861
+ Error.captureStackTrace(e, err);
2862
+ if (!nt)
2863
+ throw e;
2864
+ return e;
2865
+ };
2866
+ var inflt = function(dat, st, buf, dict) {
2867
+ var sl = dat.length, dl = dict ? dict.length : 0;
2868
+ if (!sl || st.f && !st.l)
2869
+ return buf || new u82(0);
2870
+ var noBuf = !buf;
2871
+ var resize = noBuf || st.i != 2;
2872
+ var noSt = st.i;
2873
+ if (noBuf)
2874
+ buf = new u82(sl * 3);
2875
+ var cbuf = function(l2) {
2876
+ var bl = buf.length;
2877
+ if (l2 > bl) {
2878
+ var nbuf = new u82(Math.max(bl * 2, l2));
2879
+ nbuf.set(buf);
2880
+ buf = nbuf;
2881
+ }
2882
+ };
2883
+ var final = st.f || 0, pos = st.p || 0, bt = st.b || 0, lm = st.l, dm = st.d, lbt = st.m, dbt = st.n;
2884
+ var tbts = sl * 8;
2885
+ do {
2886
+ if (!lm) {
2887
+ final = bits(dat, pos, 1);
2888
+ var type = bits(dat, pos + 1, 3);
2889
+ pos += 3;
2890
+ if (!type) {
2891
+ var s = shft(pos) + 4, l = dat[s - 4] | dat[s - 3] << 8, t = s + l;
2892
+ if (t > sl) {
2893
+ if (noSt)
2894
+ err(0);
2895
+ break;
2896
+ }
2897
+ if (resize)
2898
+ cbuf(bt + l);
2899
+ buf.set(dat.subarray(s, t), bt);
2900
+ st.b = bt += l, st.p = pos = t * 8, st.f = final;
2901
+ continue;
2902
+ } else if (type == 1)
2903
+ lm = flrm, dm = fdrm, lbt = 9, dbt = 5;
2904
+ else if (type == 2) {
2905
+ var hLit = bits(dat, pos, 31) + 257, hcLen = bits(dat, pos + 10, 15) + 4;
2906
+ var tl = hLit + bits(dat, pos + 5, 31) + 1;
2907
+ pos += 14;
2908
+ var ldt = new u82(tl);
2909
+ var clt = new u82(19);
2910
+ for (var i = 0; i < hcLen; ++i) {
2911
+ clt[clim[i]] = bits(dat, pos + i * 3, 7);
2912
+ }
2913
+ pos += hcLen * 3;
2914
+ var clb = max(clt), clbmsk = (1 << clb) - 1;
2915
+ var clm = hMap(clt, clb, 1);
2916
+ for (var i = 0; i < tl; ) {
2917
+ var r = clm[bits(dat, pos, clbmsk)];
2918
+ pos += r & 15;
2919
+ var s = r >> 4;
2920
+ if (s < 16) {
2921
+ ldt[i++] = s;
2922
+ } else {
2923
+ var c = 0, n = 0;
2924
+ if (s == 16)
2925
+ n = 3 + bits(dat, pos, 3), pos += 2, c = ldt[i - 1];
2926
+ else if (s == 17)
2927
+ n = 3 + bits(dat, pos, 7), pos += 3;
2928
+ else if (s == 18)
2929
+ n = 11 + bits(dat, pos, 127), pos += 7;
2930
+ while (n--)
2931
+ ldt[i++] = c;
2932
+ }
2933
+ }
2934
+ var lt = ldt.subarray(0, hLit), dt = ldt.subarray(hLit);
2935
+ lbt = max(lt);
2936
+ dbt = max(dt);
2937
+ lm = hMap(lt, lbt, 1);
2938
+ dm = hMap(dt, dbt, 1);
2939
+ } else
2940
+ err(1);
2941
+ if (pos > tbts) {
2942
+ if (noSt)
2943
+ err(0);
2944
+ break;
2945
+ }
2946
+ }
2947
+ if (resize)
2948
+ cbuf(bt + 131072);
2949
+ var lms = (1 << lbt) - 1, dms = (1 << dbt) - 1;
2950
+ var lpos = pos;
2951
+ for (; ; lpos = pos) {
2952
+ var c = lm[bits16(dat, pos) & lms], sym = c >> 4;
2953
+ pos += c & 15;
2954
+ if (pos > tbts) {
2955
+ if (noSt)
2956
+ err(0);
2957
+ break;
2958
+ }
2959
+ if (!c)
2960
+ err(2);
2961
+ if (sym < 256)
2962
+ buf[bt++] = sym;
2963
+ else if (sym == 256) {
2964
+ lpos = pos, lm = null;
2965
+ break;
2966
+ } else {
2967
+ var add = sym - 254;
2968
+ if (sym > 264) {
2969
+ var i = sym - 257, b = fleb[i];
2970
+ add = bits(dat, pos, (1 << b) - 1) + fl[i];
2971
+ pos += b;
2972
+ }
2973
+ var d = dm[bits16(dat, pos) & dms], dsym = d >> 4;
2974
+ if (!d)
2975
+ err(3);
2976
+ pos += d & 15;
2977
+ var dt = fd[dsym];
2978
+ if (dsym > 3) {
2979
+ var b = fdeb[dsym];
2980
+ dt += bits16(dat, pos) & (1 << b) - 1, pos += b;
2981
+ }
2982
+ if (pos > tbts) {
2983
+ if (noSt)
2984
+ err(0);
2985
+ break;
2986
+ }
2987
+ if (resize)
2988
+ cbuf(bt + 131072);
2989
+ var end = bt + add;
2990
+ if (bt < dt) {
2991
+ var shift = dl - dt, dend = Math.min(dt, end);
2992
+ if (shift + bt < 0)
2993
+ err(3);
2994
+ for (; bt < dend; ++bt)
2995
+ buf[bt] = dict[shift + bt];
2996
+ }
2997
+ for (; bt < end; ++bt)
2998
+ buf[bt] = buf[bt - dt];
2999
+ }
3000
+ }
3001
+ st.l = lm, st.p = lpos, st.b = bt, st.f = final;
3002
+ if (lm)
3003
+ final = 1, st.m = lbt, st.d = dm, st.n = dbt;
3004
+ } while (!final);
3005
+ return bt != buf.length && noBuf ? slc(buf, 0, bt) : buf.subarray(0, bt);
3006
+ };
3007
+ var et = /* @__PURE__ */ new u82(0);
3008
+ var Inflate = /* @__PURE__ */ (function() {
3009
+ function Inflate2(opts, cb) {
3010
+ if (typeof opts == "function")
3011
+ cb = opts, opts = {};
3012
+ this.ondata = cb;
3013
+ var dict = opts && opts.dictionary && opts.dictionary.subarray(-32768);
3014
+ this.s = { i: 0, b: dict ? dict.length : 0 };
3015
+ this.o = new u82(32768);
3016
+ this.p = new u82(0);
3017
+ if (dict)
3018
+ this.o.set(dict);
3019
+ }
3020
+ Inflate2.prototype.e = function(c) {
3021
+ if (!this.ondata)
3022
+ err(5);
3023
+ if (this.d)
3024
+ err(4);
3025
+ if (!this.p.length)
3026
+ this.p = c;
3027
+ else if (c.length) {
3028
+ var n = new u82(this.p.length + c.length);
3029
+ n.set(this.p), n.set(c, this.p.length), this.p = n;
3030
+ }
3031
+ };
3032
+ Inflate2.prototype.c = function(final) {
3033
+ this.s.i = +(this.d = final || false);
3034
+ var bts = this.s.b;
3035
+ var dt = inflt(this.p, this.s, this.o);
3036
+ this.ondata(slc(dt, bts, this.s.b), this.d);
3037
+ this.o = slc(dt, this.s.b - 32768), this.s.b = this.o.length;
3038
+ this.p = slc(this.p, this.s.p / 8 | 0), this.s.p &= 7;
3039
+ };
3040
+ Inflate2.prototype.push = function(chunk, final) {
3041
+ this.e(chunk), this.c(final);
3042
+ };
3043
+ return Inflate2;
3044
+ })();
3045
+ var td = typeof TextDecoder != "undefined" && /* @__PURE__ */ new TextDecoder();
3046
+ var tds = 0;
3047
+ try {
3048
+ td.decode(et, { stream: true });
3049
+ tds = 1;
3050
+ } catch (e) {
3051
+ }
3052
+
3053
+ // src/runtime/browser.ts
3054
+ var hashDigest = (algorithm, data) => import_buffer.Buffer.from((algorithm === "md5" ? md5 : sha1)(data));
3055
+ var hmacSha1 = (key2, data) => import_buffer.Buffer.from(hmac(sha1, key2, data));
3056
+ var createAesBlockCipher = (key2) => (block) => import_buffer.Buffer.from(ecb(key2, { disablePadding: true }).encrypt(block));
3057
+ var inflateRawSync = (data, options) => {
3058
+ const output = import_buffer.Buffer.alloc(options.maxOutputLength);
3059
+ let length = 0;
3060
+ const stream = new Inflate((chunk) => {
3061
+ if (chunk.length > output.length - length)
3062
+ throw new RangeError("Inflated data exceeds declared size");
3063
+ output.set(chunk, length);
3064
+ length += chunk.length;
3065
+ });
3066
+ for (let offset = 0; offset < data.length; offset += 1024) {
3067
+ stream.push(data.subarray(offset, offset + 1024), offset + 1024 >= data.length);
3068
+ }
3069
+ if (!data.length) stream.push(data, true);
3070
+ return output.subarray(0, length);
3071
+ };
3072
+ var nodeOnly = () => {
3073
+ throw new Error("Filesystem and RSA APIs are only available in the Node entry");
3074
+ };
3075
+ var readFile = nodeOnly;
3076
+ var writeFile = nodeOnly;
3077
+ var readFileSync = nodeOnly;
3078
+
3079
+ // src/nitro/binary.ts
3080
+ init_buffer();
3081
+ var DEFAULT_MAX_SIZE = 1073741824;
3082
+ var bytes = (value, name = "input") => {
3083
+ if (!(value instanceof Uint8Array)) throw new TypeError(`${name} must be a Buffer or Uint8Array`);
3084
+ return import_buffer.Buffer.from(value.buffer, value.byteOffset, value.byteLength);
3085
+ };
3086
+ var range = (buffer, offset, size, name = "binary data") => {
3087
+ if (!Number.isSafeInteger(offset) || !Number.isSafeInteger(size) || offset < 0 || size < 0 || offset + size > buffer.length) {
3088
+ throw new RangeError(
3089
+ `Invalid ${name} range: offset=${offset}, size=${size}, available=${buffer.length}`
3090
+ );
3091
+ }
3092
+ return buffer.subarray(offset, offset + size);
3093
+ };
3094
+ var align = (value, alignment = 512) => {
3095
+ return Math.ceil(value / alignment) * alignment;
3096
+ };
3097
+ var BinaryWriter = class {
3098
+ maxSize;
3099
+ buffer;
3100
+ position;
3101
+ length;
3102
+ constructor(initialSize = 65536, maxSize = DEFAULT_MAX_SIZE) {
3103
+ if (!Number.isSafeInteger(maxSize) || maxSize < 1 || maxSize > 4294967295)
3104
+ throw new RangeError("Invalid output size limit");
3105
+ this.maxSize = maxSize;
3106
+ this.buffer = import_buffer.Buffer.alloc(Math.min(initialSize, maxSize));
3107
+ this.position = 0;
3108
+ this.length = 0;
3109
+ }
3110
+ ensure(end) {
3111
+ if (!Number.isSafeInteger(end) || end < 0 || end > this.maxSize)
3112
+ throw new RangeError(`Output exceeds size limit (${this.maxSize} bytes)`);
3113
+ if (end <= this.buffer.length) return;
3114
+ const next = import_buffer.Buffer.alloc(Math.min(this.maxSize, Math.max(end, this.buffer.length * 2, 1024)));
3115
+ this.buffer.copy(next, 0, 0, this.length);
3116
+ this.buffer = next;
3117
+ }
3118
+ write(data) {
3119
+ data = bytes(data);
3120
+ if (!Number.isSafeInteger(this.position) || this.position < 0)
3121
+ throw new RangeError("Invalid writer position");
3122
+ this.ensure(this.position + data.length);
3123
+ bytes(data).copy(this.buffer, this.position);
3124
+ this.position += data.length;
3125
+ this.length = Math.max(this.length, this.position);
3126
+ }
3127
+ fillTo(end, fill = 255) {
3128
+ this.ensure(end);
3129
+ if (end <= this.position) return;
3130
+ this.buffer.fill(fill, this.position, end);
3131
+ this.position = end;
3132
+ this.length = Math.max(this.length, end);
3133
+ }
3134
+ pad(alignment, fill = 255) {
3135
+ this.fillTo(align(this.position, alignment), fill);
3136
+ }
3137
+ toBuffer() {
3138
+ return this.buffer.subarray(0, this.length);
3139
+ }
3140
+ };
3141
+
3142
+ // src/nitro/header.ts
3143
+ init_buffer();
3144
+
3145
+ // src/nitro/crc.ts
3146
+ init_buffer();
3147
+ var table16 = new Uint16Array(256);
3148
+ var table32 = new Uint32Array(256);
3149
+ for (let i = 0; i < 256; i++) {
3150
+ let a = i, b = i;
3151
+ for (let bit = 0; bit < 8; bit++) {
3152
+ a = a >>> 1 ^ (a & 1 ? 40961 : 0);
3153
+ b = b >>> 1 ^ (b & 1 ? 3988292384 : 0);
3154
+ }
3155
+ table16[i] = a;
3156
+ table32[i] = b;
3157
+ }
3158
+ var crc16 = (data, initial = 65535) => {
3159
+ let crc = initial;
3160
+ for (const byte of data) crc = crc >>> 8 ^ table16[(crc ^ byte) & 255];
3161
+ return crc;
3162
+ };
3163
+ var crc32 = (data) => {
3164
+ let crc = 4294967295;
3165
+ for (const byte of data) crc = crc >>> 8 ^ table32[(crc ^ byte) & 255];
3166
+ return (crc ^ 4294967295) >>> 0;
3167
+ };
3168
+
3169
+ // src/nitro/crypto.ts
3170
+ init_buffer();
3171
+ var KEY1 = import_buffer.Buffer.from(
3172
+ "99D5205F5744F5B96E19A4D99E6A5A94D8AEF1EB4175E23A9382D03233EE31D5CC57619A3706A21B793972F555AEF6BE5F1B69FBE59DF1E9CE2CD9A15E3205E6FED3FECFD462040D8BF5ECB72B6079BB1295310D6E3FDA2B8884F0F13D127E254522F1BB24061A0611ADDF288B6481342BEB332999AAF2BD9C14959D9FF7F58C7297A1299DD15FCF664D071ADED34A4B85C9A7A31795053A3D490ABF0A898BA24A8249DD2790F10BE9EB1C6A83764505BA817061173F4BDEAECFAB3957F23A564811AD8A40E1453FFA9B0254CAA693FBEF4DFE6FA3D8879C08BAD5486A8D2DFD6E15F874BDBE528B18228A9EFB7437071B366C4A19BA4262B97991107B676596FE0223E8EE998C773E5C86644D6D7886A54F65E21EB2DF5A0AD07E0814B071ACBDDB831CB9D7A162CDC6637C5269C3E6BF75CE12445D2104FAFBD33C381163D4958541494609F2084311DC1F76C0156D1F3C6370EA87806CC3BD638BC2372137DCEE09232E376A4D7390F75030AC1C92041023914FD207AA683E4F9AC964606AC81421F3D62241124424CFE68A56DD0D534DE1851E8C525A9C1984C20357F16FE300BE58F64CEDD521649C1FBE55033C4ADCFFAAC9DAE05D5EBFE6DEF5D8B1F8FF36B3B9626795DB315F37ED4C70679990B518316C3D9999E442DAD3254213A0AED7706CB155CFC7D746D54361173D4428E93385D5D0A293AA25121FFBC50B46F597765645A6BE87B1946BE8B1FE3399AE1F3E6C39711D09009037E4103E7574FF8C833BB0F1B0F90105474295F1D6AC7E38E69E9574263FB4685018D04330B44C4BE368BFE54DB6958B0AA074253277CFA1F72CD871135AABEAC951E80DEEEFE9937E19A71E433881162CA148E373CC29216CD35DCEA0D9617143A01513B56492CF2A19DCADB7A59F8665F81A9FE7FBF7FDB8136C27DB6FDF351CF78D2C5B9B12AB386406CCDE31E84E751164E3FAEAEB3454C2AD3F34EB932C7D26369D56F35AE1F6B398634A9E3283E49A84607D902E130EEE934B36A285EC1638E8880602BFF0A03AEDD76A9A73E157CFF844B8DC2E2359D1DF9552719961A04BD57F6E78BAA9C530D34086329D320C9C37B7022FBA5498A9C41304C98DBEC8E75D97502E93D622590C27BC2292E0A7200F936F7F4C9FD3B5A62A0B7467497D1026CBD1C58671E78CA09CE95BB21AF601EE8C9E5E83F21ADBE6E5EA845976D27CF68DA5493648C21652BB83A374B9070C3BFF6128E161E9E4EF6E15AA4EBAE85D0596BB3256B0FB72520F0EC84225657689AFF2DE1027F0014B74A79707D5265454091F820A867D30390EB3269B0B57BB360631AFFD79FCD930102B0CB3E19BD77BDC5FEFD2F813454D4775BD46963C7E75F33EB567C59A3BB05B296BDE805BC81505B131B6CE49DDAD84B5AE60DC67313430FE4EBD802FA6BF63392186D9357F1668220554E990268C076C51A43155D70907A83E2E5366C1F8F27BC4F258CFF187C5A2E7278F308758A064622318B9887CFACEC498AEAD17CC4A5BF3E948D556D30DF2C892738CDBD72F56AC81F992694DC632F6E6C08D21E276806111BCDC6C93AF19699BD0BFB9319F0267A351EE8306227B0CAB494240B8D5017DCE5EF7555339C59946D8879FBAF764B4E39AFAA16D90681030CA8A54A79F60C319F56B0D7A5198E6984351B4D635E94FC3DF0F7BD62F5CBD3A156119F14BCBAADC6D64C9D3C61E56EF384C50718675CC0D0D4EE928F6065D701BAAD345CFA839AC95A62EB4E422D474A8375F487A04CCA54C40D828B428080D1C725241F07D47193A534E5884626B93B58A81214E0DDCB43FA2C6FCC92B40DA3804E95E5A866B0C22258568118D7C921D95554DAB8EBBDAA6E6B751B6325A0541DD052A0A5650911747CCC9E67EB5614ADB736751C833F5DA6E742E54C3370D6DAF08E8158A5FE25921CDA8DE0C065A776B5FDB18653EC850DE78E0B882B35D4E7232074FC13423BA96B7674EA4281E3462EB2D6A70E92F42C4704E5A319CF95B4728AADA716F381FB378C4926B1C9EF6359AB74D0EBFCC1829410348355D55D02BC629AF5C6074698E5E9B7CD4BD7B44647D3F925D69B61F004BD48335CF7E644E17AE8DD52E9A28124E2E2B49085CAEC64685AE41611E6F82D25137161F0BF659A49ACA5AAF0DD4338B2063F184805CCBCF08B4B9D31605BD6283319B5651989FBAB25BAAB2226B2CB5D448FA632B5F58FA61FA6409BB38E0B89D9260A80D676F0E37F50D019FC277D4FEECF1733039E07DF56198E42C2855045655DB2F6BECE55806B664806A2A1A4E5B0FD8C40A2E5219D962F53048BE8C7B4F389BA2C3AFC9D3C7C1624186B96121576F994FC1BACE7BB53B4D5E8A8B44575F135F706D5B2947DC38E2EC045565122AE81743E18EDD2AB3E294F7096E5CE6EB8AF86D89495448F52FADBFEA944BCAFC3987825F8A01F275F2E671D6D842DEF12D1D28A6887EA3A0471D30D9A371DF491CCB01F836B1F2F022585D456BBDA0BBB28842C78C28CE93E8906308907C893CF57DB7042D4F555116FD7E79E8BEC1F212D4F8B4840523A0CCD22BFDE1ABAD0DD1556C2341944D77374F05280CBF17B312676C8CC35AF741842A6DD09412272CB4ED9C4DEC478297D567B91B9DC055077EE58EE2A8E73E12E40E3A2A455534A2F92D5A1BAB527C83105F55D2F15A432BC6A7A4891595E8B44B9DF875E39F60785BD6E60D44E62106BD472253A400AD8D43138539F7AAFC38AF7BEDFCE42B5450984CFC8580F7DF3C8022E194DADE24C6B07A3938DC0FA1A7F4F96F6318578B84412A2ED453F2D9000FD0DD996E19A60AD0EC5B5824ABC0CB0665EC1A1338940A67032F3FF7E377447733C61439D0E3C0A20879BB409957410B0190CDE1CC4867DBB3AF8874F34C828F72B1B52329C4126C19FC8E46A49CC4256587D36DBE8A93110338ED832BF346A493EA3B53851DCED4F1088327EDFC9B1A18BCF98BAEDC24AB5038E9724B1022177B465DAB5964F340AEF8BBE5C8F926034E557DEBEBFEF739E6E00A11BE2E28FF98EDC0C9425642C3FD00F6AF87A25B013F329247959A72A5323DAE6BD09B07D24992E3784AFAA1067DF241CF77740414B20C86846416D5BB51A1E56FF1D1F2E2F75F58204DB857C7CFDDC5D8BE763DF65F7EE72A8B88241B383F0E412377F5F04BD40C1FFAA40B805FCF45F6E0DA2F345953FB203C52625E35B562FE8B6063E3865A151A6ED14745BC32B4EB6738ABE46E333AB5EDA3AD67E04E4195EE626271261D31EF6230AFD782ACC2DC0504F59707BF11592307C06402E897E53EAF18AC59A68B4A33901C6E7C9C207E4C3C3E6164BBC56B7C7E3E9FC54C9FEA73F5D789C04CF4FBF42DEC141B51D5C112C810DF0B4A8B9CBC93456A3E3E7DC1A9BACDC1B407E4E1688643B26D38F3FB0C5C663771DE56EF6EA0104065A798F7D0BE0EC83736EC10CA7C9CAB841E051776021C4F52AA5FC1C6A056B9D80484444DA759D8DE60E6380E058F03E13B6D8104336F300BCE69052133FB26BB897DB6AE877E5107E0ACF7960A6BF9C45C1DE44447B85EFAE3788455424B485EF77D4735861D2B430503EC8AB81E063C760C481A43A7B78AED1E13C643EE10EFDBECFB3C83B29544EFD854514E2D11441DFB36591E7A34C1C3CA570061EA67A5169B55D055E17FD936D24076AEDC01CEB07A83D5CB2098EC6BC1729234F3825737628A32360C9043AEAE5C9B788E136502FD6871C1FEB031A02482B0C3B17969A7F5D2EBD082C032DC9EC7263C6D8D98C1BB22D4D00F33EC3EB9CCE1DC6A4C7736141CF9BF819F285F71853229907548C4B34ACED8448F142FFD4057EFAA0875D946D1D66E32551FC318FE841FFC84D5FF715E1B48C386950E280827D33883717B4C8063549A56B0ACCF80CA3109EFFEF3BEAF247EA6FE533FC28D4A3368D122A666AD7BEADEB643B0A1259500A33F7546141144ECD795BC92F04FA916536297602A0F41F17124BEEE947F08CD6093B3855B07003FD80F28839AD1699FD1DA2EC39001A2B96B4E2A669DDAAEA6EA2AD3682F0C0C9CD28C4AEDE29E57659D0987A3B4C4325DC9D4322BB1E0711E644DE69071E31E40ED7DF3840EEDC87876AEC0712772BB05EA0264FBF3486BB542933FED9F1353D2F7FE2AEC1D4725DB3C9186C68EF011FD237436F7A4F59E7A7E535044D447CAD3EB386DE6D971947F4AC6694B11F452EA22FE8AB036678B59E8E6802AEB650413EEECDC9E5FB1EC056A59E69F5E596B89BFF71ACA44F95B6A718503E42962E0706F41C4CFB2B1CCE37EA607A887E77F8493DB524B6CEC7EDDD4244810699F046074E64818F3E42CB94F2E507ADFD454692B8BA7F3CEFF1FF33E26013917958489B0F04C4B82919FC44BAC9DA574AF1725C9CA32D3BC898A8489CC0DAE7CA2DB9C6A7891EEEA765D4E8760F5691567D402CFAF483607EABF6F662D068FC49AFEF9F6908775B8F7AD0F76105A3D59B02EB3C7352CCC70562BCBE33796C52F461B8A2246C788A726329861DF86228AF41C2F87A109AACCA9AED3BD00451C9A5487865287EFFF1E8FA18FC1895C351BDA2D3A2C16B2C2F156E278C16B6397C5568FC9327F2CAAAFA6A8AC20912288DEE4608BF94B42251AE37F9C2C19893A7E05D436CC6958C2C1328B2F9085EB7A3950A5A12792C566B0204F587E5583432B45E29CE4D812902C168356167903B3AD2D61181A131F37E2E19C737B80D5FD2D5187FC7BAAD71F2C7A8EAFF48DBBCD95117C720BEE6FE2B9AFDE3783DE8C8D620567B796C68D56B60DD762BAD64636BD8EC8E6EA2A6C1014FF6B5BFA823C46B1304346518A7D9B923E83795B555DB26C5ECE90628E5398C90D6DE52D57CDC58157BAE1E8B88F72E54F13DCEA9D711510B21188D509D47F5B657F2C3B384C1168508DFB9EB059BF9480894AC51A18128953D14A1029E88C1CECB6EA46C7178B251531A8A26B43B19DE2DB0B879BB011040E71D2297789820A66417F1D0B48FF72BB24FDC248A19BFE7B7FCE88DB86D9853B1CB0DCA83307BF512EE30E9A00971E06C097439DD8B645C486675F00F8889AA4529EC7AA8A8375ECC518AECEC32F1A2BF918FFAE1AF5530BB53351A7FDE8A8E1A264B622174380CC0AD8AE3BBA40D7D9924A89DF0410EE9B182B6A77698A68F4F9B9A221156EE61E3B0362309B60417E259B9E8FC5521008F8C269A1211188375E793566FF1042186EED97B66B1C4E36E56D7DB4E4BF20B9E0053A69D5B8E3D5DCE0B9AC533E07A457AD77FF4818762AAC492A8E47756D9F676330358C390539D56F643A5BADCA0BBB82529945B193363699AF13204436D8024409399285FF4A4A9787A663D7C7B5B524ED0FB46F0C585214D9A67BD379BC3858A1BD3B8406D81A06FD6BA8EA4B69280437AD8299FB0E1B85BDA85D73CDDC58750ABE636C48E74CE4302B0460B915D8DA8681758F96D48D1C5D70857C1C677BD50867A6CE4B0A6670B7E563D45B8A82EA1067CAE2F4EF17852F2A5F8A9782F86AD63410EAEBC95C3CE149F846EBDEBDF6A992F1AAA6A018B03AD30F1FF36FFF31454344D3509AF7880996C1CE76CCF22C2CBAAD82778F1884C0D2079C3690834E0BA54F433E04AB784FD6FB09012490DA6F3C3A610D7F694AEB2B3002B4DBE084A9ECD735BF377D8558CEA94EE480C7A8D3306748EB29AF2F746AB4A73F0F3F92AFF3CAACAF4BD994C043CA810D2F48A1B027D5D2EF4B0585A3DE4D93303CF0BB4A8F30274CEBE33E64ED9A2F3BF182F0BAF4CF7F40CBB0E17FBCAA57D3C974F2FA430D22D0F4774E93D785701F99BFB6DE35F130A75E71F06B012D7B64F033530A3988F36B3AA66B35D22F43CD02FDB5E9BC5BAAD8A4197E0E5D94819E6F77ADD60E749396E7C4185FADF519",
3173
+ "hex"
3174
+ );
3175
+ var aes128CtrCrypt = (key2, counter, data) => {
3176
+ if (key2.length !== 16 || counter.length !== 16)
3177
+ throw new RangeError("AES key and counter must have 16 bytes");
3178
+ const ctr = import_buffer.Buffer.from(counter).reverse();
3179
+ const aes = createAesBlockCipher(import_buffer.Buffer.from(key2).reverse());
3180
+ const output = import_buffer.Buffer.alloc(data.length);
3181
+ for (let p = 0; p < data.length; p += 16) {
3182
+ const mask = aes(ctr);
3183
+ for (let j = 0; j < 16 && p + j < data.length; j++) output[p + j] = data[p + j] ^ mask[15 - j];
3184
+ for (let j = 15; j >= 0; j--) {
3185
+ ctr[j] = ctr[j] + 1 & 255;
3186
+ if (ctr[j]) break;
3187
+ }
3188
+ }
3189
+ return output;
3190
+ };
3191
+ var modcryptKey = (header) => {
3192
+ if (typeof header.gameCode !== "string" || header.gameCode.length !== 4)
3193
+ throw new Error("Expected four-character game code");
3194
+ if (header.twlInternalFlags & 4 || (header.appflags?.[3] ?? 0) & 128) {
3195
+ const key2 = import_buffer.Buffer.alloc(16);
3196
+ key2.write(header.gameTitle, 0, 12, "ascii");
3197
+ key2.write(header.gameCode, 12, 4, "ascii");
3198
+ return key2;
3199
+ }
3200
+ if (!header.hmac_arm9i || header.hmac_arm9i.length < 16)
3201
+ throw new Error("Missing ARM9i HMAC for modcrypt key");
3202
+ const x = import_buffer.Buffer.from(
3203
+ "Nintendo" + header.gameCode + [...header.gameCode].reverse().join(""),
3204
+ "ascii"
3205
+ );
3206
+ for (let i = 0; i < 16; i++) x[i] ^= header.hmac_arm9i[i];
3207
+ const mask = (1n << 128n) - 1n;
3208
+ let v = x.readBigUInt64LE(0) | x.readBigUInt64LE(8) << 64n;
3209
+ v = v + 0xfffefb4e295902582a680f5f1a4f3e79n & mask;
3210
+ v = (v << 42n | v >> 86n) & mask;
3211
+ const out = import_buffer.Buffer.alloc(16);
3212
+ out.writeBigUInt64LE(v & (1n << 64n) - 1n);
3213
+ out.writeBigUInt64LE(v >> 64n, 8);
3214
+ return out;
3215
+ };
3216
+ var encryptSecureArea = (gameCode, input) => {
3217
+ if (typeof gameCode !== "string" || gameCode.length !== 4)
3218
+ throw new Error("Expected four-character game code");
3219
+ if (input.length < 2048) throw new RangeError("Secure area must contain at least 0x800 bytes");
3220
+ const output = import_buffer.Buffer.from(input);
3221
+ let magic = new Uint32Array(1042);
3222
+ let args = [0, 0, 0];
3223
+ function encrypt2(a2, b2) {
3224
+ for (let i = 0; i < 16; i++) {
3225
+ const c = (magic[i] ^ a2) >>> 0;
3226
+ const sum = magic[18 + (c >>> 24)] + magic[274 + (c >>> 16 & 255)] >>> 0;
3227
+ const f = magic[786 + (c & 255)] + (magic[530 + (c >>> 8 & 255)] ^ sum) >>> 0;
3228
+ a2 = (b2 ^ f) >>> 0;
3229
+ b2 = c;
3230
+ }
3231
+ return [(b2 ^ magic[17]) >>> 0, (a2 ^ magic[16]) >>> 0];
3232
+ }
3233
+ function init2() {
3234
+ [args[2], args[1]] = encrypt2(args[2], args[1]);
3235
+ [args[1], args[0]] = encrypt2(args[1], args[0]);
3236
+ const key2 = import_buffer.Buffer.alloc(12);
3237
+ args.forEach((v, i) => key2.writeUInt32LE(v, i * 4));
3238
+ for (let j = 0; j < 18; j++) magic[j] ^= key2.readUInt32BE(j * 4 & 7);
3239
+ let a2 = 0, b2 = 0;
3240
+ for (let i = 0; i < 1042; i += 2) {
3241
+ [a2, b2] = encrypt2(a2, b2);
3242
+ magic[i] = a2;
3243
+ magic[i + 1] = b2;
3244
+ }
3245
+ }
3246
+ function init1() {
3247
+ magic = Uint32Array.from({ length: 1042 }, (_, i) => KEY1.readUInt32LE(i * 4));
3248
+ const code = import_buffer.Buffer.from(gameCode, "ascii").readUInt32LE();
3249
+ args = [code, code >>> 1, code << 1 >>> 0];
3250
+ init2();
3251
+ init2();
3252
+ }
3253
+ init1();
3254
+ args[1] = args[1] << 1 >>> 0;
3255
+ args[2] >>>= 1;
3256
+ init2();
3257
+ for (let p = 8; p < 2048; p += 8) {
3258
+ const [b2, a2] = encrypt2(output.readUInt32LE(p + 4), output.readUInt32LE(p));
3259
+ output.writeUInt32LE(a2, p);
3260
+ output.writeUInt32LE(b2, p + 4);
3261
+ }
3262
+ let [b, a] = encrypt2(1784827769, 1919118949);
3263
+ init1();
3264
+ [b, a] = encrypt2(b, a);
3265
+ output.writeUInt32LE(a, 0);
3266
+ output.writeUInt32LE(b, 4);
3267
+ return output;
3268
+ };
3269
+
3270
+ // src/nitro/header.ts
3271
+ var UnitCode = Object.freeze({ NDS: 0, NDS_DSi: 2, DSi: 3 });
3272
+ var Header = class {
3273
+ raw;
3274
+ trimmedRom;
3275
+ doublePadding;
3276
+ nitrocode;
3277
+ decrypted;
3278
+ headerCRC;
3279
+ logoCRC;
3280
+ secureCRC;
3281
+ dlp_signature;
3282
+ constructor(input) {
3283
+ const data = bytes(input, "header");
3284
+ range(data, 0, 368, "header");
3285
+ const size = data.readUInt32LE(132);
3286
+ if (size < 368 || size > data.length) throw new RangeError(`Invalid header size: ${size}`);
3287
+ this.raw = import_buffer.Buffer.from(data.subarray(0, size));
3288
+ if (this.unitCode & 2 && size > 512) range(this.raw, 0, 4096, "DSi header");
3289
+ this.trimmedRom = this.total_rom_size ? this.total_rom_size >= data.length : data.length !== this.size;
3290
+ this.doublePadding = this.ARM9size % 1024 < 512 && this.ARM7romOffset % 1024 === 0 && this.ARM9overlayOffset % 1024 === 0 || this.ARM7size % 1024 < 512 && this.FNToffset % 1024 === 0 && this.ARM7overlayOffset % 1024 === 0 || this.FNTsize % 1024 < 512 && this.FAToffset % 1024 === 0 || this.FATsize % 1024 < 512 && this.bannerOffset % 1024 === 0;
3291
+ const nitroOffset = this.ARM9romOffset + this.ARM9size;
3292
+ this.nitrocode = nitroOffset >= size && nitroOffset + 4 <= data.length && data.readUInt32LE(nitroOffset) === 3737126433;
3293
+ this.decrypted = data.length >= 16392 && data.readBigUInt64LE(16384) === 0xe7ffdeffe7ffdeffn;
3294
+ this.headerCRC = crc16(this.raw.subarray(0, 350)) === this.headerCRC16;
3295
+ this.logoCRC = crc16(this.logo) === this.logoCRC16;
3296
+ const secure = data.subarray(16384, 32768);
3297
+ this.secureCRC = secure.length > 0 && crc16(this.decrypted ? encryptSecureArea(this.gameCode, secure) : secure) === this.secureCRC16;
3298
+ this.dlp_signature = import_buffer.Buffer.alloc(0);
3299
+ if (this.ROMsize >= size && this.ROMsize + 136 <= data.length && data.readUInt32LE(this.ROMsize) === 90977) {
3300
+ this.dlp_signature = import_buffer.Buffer.from(data.subarray(this.ROMsize, this.ROMsize + 136));
3301
+ }
3302
+ }
3303
+ get size() {
3304
+ return 2 ** (17 + this.raw[20]);
3305
+ }
3306
+ set size(value) {
3307
+ const power = Math.log2(value);
3308
+ if (!Number.isInteger(power) || power < 17 || power > 32)
3309
+ throw new RangeError("ROM capacity must be a power of two from 128 KiB to 4 GiB");
3310
+ this.raw[20] = power - 17;
3311
+ }
3312
+ toBuffer() {
3313
+ const data = import_buffer.Buffer.from(this.raw);
3314
+ data.writeUInt16LE(crc16(data.subarray(192, 348)), 348);
3315
+ data.writeUInt16LE(crc16(data.subarray(0, 350)), 350);
3316
+ return data;
3317
+ }
3318
+ toString() {
3319
+ return `NDS header: ${this.gameTitle.replace(/\0+$/, "")} (${this.gameCode})`;
3320
+ }
3321
+ };
3322
+ function field(name, offset, length, type = "buffer", dsi = false) {
3323
+ Object.defineProperty(Header.prototype, name, {
3324
+ enumerable: true,
3325
+ get() {
3326
+ if (dsi && (!(this.unitCode & 2) || this.raw.length <= 512))
3327
+ return type === "buffer" ? import_buffer.Buffer.alloc(length) : 0;
3328
+ const data = range(this.raw, offset, length, `header ${name}`);
3329
+ if (type === "string") return data.toString("latin1");
3330
+ if (type === "buffer") return data;
3331
+ return length === 8 ? data.readBigUInt64LE() : data.readUIntLE(0, length);
3332
+ },
3333
+ set(value) {
3334
+ const target = range(this.raw, offset, length, `header ${name}`);
3335
+ if (type === "string") {
3336
+ if (typeof value !== "string" || import_buffer.Buffer.byteLength(value, "latin1") > length)
3337
+ throw new TypeError(`Invalid ${name}`);
3338
+ target.fill(0);
3339
+ target.write(value, "latin1");
3340
+ } else if (type === "buffer") {
3341
+ if (!(value instanceof Uint8Array)) throw new TypeError(`Invalid ${name}`);
3342
+ const source = bytes(value, name);
3343
+ if (source.length !== length) throw new RangeError(`${name} must contain ${length} bytes`);
3344
+ source.copy(target);
3345
+ } else if (length === 8) {
3346
+ if (typeof value !== "bigint") throw new TypeError(`Invalid ${name}`);
3347
+ target.writeBigUInt64LE(value);
3348
+ } else {
3349
+ if (typeof value !== "number") throw new TypeError(`Invalid ${name}`);
3350
+ target.writeUIntLE(value, 0, length);
3351
+ }
3352
+ }
3353
+ });
3354
+ }
3355
+ field("gameTitle", 0, 12, "string");
3356
+ field("gameCode", 12, 4, "string");
3357
+ field("makerCode", 16, 2, "string");
3358
+ for (const [name, offset] of Object.entries({
3359
+ unitCode: 18,
3360
+ encryptionSeed: 19,
3361
+ twlInternalFlags: 28,
3362
+ permitsFlags: 29,
3363
+ ROMversion: 30,
3364
+ internalFlags: 31
3365
+ }))
3366
+ field(name, offset, 1, "number");
3367
+ field("reserved", 21, 7);
3368
+ var ntr32 = "ARM9romOffset ARM9entryAddress ARM9ramAddress ARM9size ARM7romOffset ARM7entryAddress ARM7ramAddress ARM7size FNToffset FNTsize FAToffset FATsize ARM9overlayOffset ARM9overlaySize ARM7overlayOffset ARM7overlaySize flagsRead flagsInit bannerOffset".split(
3369
+ " "
3370
+ );
3371
+ ntr32.forEach((name, i) => field(name, 32 + i * 4, 4, "number"));
3372
+ field("secureCRC16", 108, 2, "number");
3373
+ field("ROMtimeout", 110, 2, "number");
3374
+ field("ARM9autoload", 112, 4, "number");
3375
+ field("ARM7autoload", 116, 4, "number");
3376
+ field("secureDisable", 120, 8, "number");
3377
+ field("ROMsize", 128, 4, "number");
3378
+ field("headerSize", 132, 4, "number");
3379
+ field("reserved2", 136, 56);
3380
+ field("logo", 192, 156);
3381
+ field("logoCRC16", 348, 2, "number");
3382
+ field("headerCRC16", 350, 2, "number");
3383
+ "debug_romOffset debug_size debug_ramAddress reserved3".split(" ").forEach((name, i) => field(name, 352 + i * 4, 4, "number"));
3384
+ field("appflags", 444, 4, "buffer", true);
3385
+ "mbk9_wramcnt_setting region_flags access_control scfg_ext_mask".split(" ").forEach((name, i) => field(name, 428 + i * 4, 4, "number", true));
3386
+ var twl32 = "dsi9_rom_offset offset_0x1C4 dsi9_ram_address dsi9_size dsi7_rom_offset offset_0x1D4 dsi7_ram_address dsi7_size digest_ntr_start digest_ntr_size digest_twl_start digest_twl_size sector_hashtable_start sector_hashtable_size block_hashtable_start block_hashtable_size digest_sector_size digest_block_sectorcount banner_size offset_0x20C total_rom_size offset_0x214 offset_0x218 offset_0x21C modcrypt1_start modcrypt1_size modcrypt2_start modcrypt2_size tid_low tid_high public_sav_size private_sav_size".split(
3387
+ " "
3388
+ );
3389
+ twl32.forEach((name, i) => field(name, 448 + i * 4, 4, "number", true));
3390
+ "hmac_arm9 hmac_arm7 hmac_digest_master hmac_icon_title hmac_arm9i hmac_arm7i".split(" ").forEach((name, i) => field(name, 768 + i * 20, 20, "buffer", true));
3391
+ field("hmac_arm9_no_secure", 928, 20, "buffer", true);
3392
+ field("rsa_signature", 3968, 128, "buffer", true);
3393
+
3394
+ // src/nitro/banner.ts
3395
+ init_buffer();
3396
+ var titles = [
3397
+ "japaneseTitle",
3398
+ "englishTitle",
3399
+ "frenchTitle",
3400
+ "germanTitle",
3401
+ "italianTitle",
3402
+ "spanishTitle",
3403
+ "chineseTitle",
3404
+ "koreanTitle"
3405
+ ];
3406
+ var Banner = class {
3407
+ version;
3408
+ raw;
3409
+ bannerCRC;
3410
+ tileData;
3411
+ palette;
3412
+ japaneseTitle = "";
3413
+ englishTitle = "";
3414
+ frenchTitle = "";
3415
+ germanTitle = "";
3416
+ italianTitle = "";
3417
+ spanishTitle = "";
3418
+ chineseTitle = "";
3419
+ koreanTitle = "";
3420
+ constructor(input, offset = 0, hardSize = 0) {
3421
+ const data = bytes(input, "banner");
3422
+ this.version = range(data, offset, 2, "banner").readUInt16LE();
3423
+ let size = this.getDefSize(hardSize);
3424
+ if (this.version >>> 8 === 1)
3425
+ size = hardSize > 0 && hardSize !== 4294967295 ? Math.min(hardSize, 9152) : 9152;
3426
+ this.raw = import_buffer.Buffer.from(range(data, offset, size, "banner"));
3427
+ this.bannerCRC = crc16(this.raw.subarray(32, 2112)) === this.raw.readUInt16LE(2);
3428
+ this.tileData = import_buffer.Buffer.from(this.raw.subarray(32, 544));
3429
+ this.palette = import_buffer.Buffer.from(this.raw.subarray(544, 576));
3430
+ for (const [i, title] of titles.entries())
3431
+ this[title] = i < this.titleCount ? this.raw.subarray(576 + i * 256, 832 + i * 256).toString("utf16le").split("\0")[0] : "";
3432
+ }
3433
+ get titleCount() {
3434
+ return this.version >= 3 ? 8 : this.version >= 2 ? 7 : 6;
3435
+ }
3436
+ getDefSize(hardSize = 0) {
3437
+ if (this.version === 2) return 2368;
3438
+ if (this.version === 3) return 2624;
3439
+ if (this.version === 259) return hardSize > 0 && hardSize !== 4294967295 ? hardSize : 9152;
3440
+ return 2112;
3441
+ }
3442
+ toBuffer() {
3443
+ const output = import_buffer.Buffer.from(this.raw);
3444
+ output.writeUInt16LE(this.version);
3445
+ if (this.tileData.length !== 512 || this.palette.length !== 32)
3446
+ throw new RangeError("Invalid banner icon size");
3447
+ this.tileData.copy(output, 32);
3448
+ this.palette.copy(output, 544);
3449
+ for (let i = 0; i < this.titleCount; i++) {
3450
+ const text = import_buffer.Buffer.from(this[titles[i]], "utf16le");
3451
+ if (text.length > 256)
3452
+ throw new RangeError(`Banner ${titles[i]} exceeds 128 UTF-16 code units`);
3453
+ output.fill(0, 576 + i * 256, 832 + i * 256);
3454
+ text.copy(output, 576 + i * 256);
3455
+ }
3456
+ output.writeUInt16LE(crc16(output.subarray(32, 2112)), 2);
3457
+ if (this.version >= 2) output.writeUInt16LE(crc16(output.subarray(32, 2368)), 4);
3458
+ if (this.version >= 3) output.writeUInt16LE(crc16(output.subarray(32, 2624)), 6);
3459
+ if (this.version >>> 8 >= 1) output.writeUInt16LE(crc16(output.subarray(4672, 9152)), 8);
3460
+ return output;
3461
+ }
3462
+ };
3463
+
3464
+ // src/nitro/filesystem.ts
3465
+ init_buffer();
3466
+ var FileAllocationTable = class {
3467
+ entries;
3468
+ sortedIDs;
3469
+ constructor(input, offset, size) {
3470
+ const data = bytes(input);
3471
+ const table2 = range(data, offset, size, "FAT");
3472
+ if (size % 8 || size / 8 > 65535) throw new Error("Invalid FAT entry count");
3473
+ this.entries = [];
3474
+ for (let p = 0; p < size; p += 8) {
3475
+ const start = table2.readUInt32LE(p), end = table2.readUInt32LE(p + 4);
3476
+ range(data, start, end - start, `FAT entry ${p / 8}`);
3477
+ this.entries.push({ id: p / 8, offset: start, size: end - start });
3478
+ }
3479
+ this.sortedIDs = [...this.entries].sort((a, b) => a.offset - b.offset || a.id - b.id).map((entry) => entry.id);
3480
+ }
3481
+ };
3482
+ var FileNameTable = class _FileNameTable {
3483
+ root;
3484
+ constructor(fat, input, offset, size) {
3485
+ const table2 = range(bytes(input), offset, size, "FNT");
3486
+ range(table2, 0, 8, "FNT root directory");
3487
+ const count = table2.readUInt16LE(6);
3488
+ if (count < 1 || count > 4096) throw new Error("Invalid FNT directory count");
3489
+ range(table2, 0, count * 8, "FNT directory table");
3490
+ const decoder = new TextDecoder("shift_jis");
3491
+ const visited = /* @__PURE__ */ new Set();
3492
+ const fileIds = /* @__PURE__ */ new Set();
3493
+ const parse = (index, name, depth) => {
3494
+ if (depth > 256 || index >= count || visited.has(index))
3495
+ throw new Error("Invalid FNT directory tree or cycle");
3496
+ visited.add(index);
3497
+ let cursor = table2.readUInt32LE(index * 8);
3498
+ let fileId = table2.readUInt16LE(index * 8 + 4);
3499
+ if (cursor < count * 8) throw new Error("FNT directory names overlap directory table");
3500
+ const folder = {
3501
+ name,
3502
+ id: index === 0 ? 65535 : 61440 + index,
3503
+ files: [],
3504
+ folders: []
3505
+ };
3506
+ const names = /* @__PURE__ */ new Set();
3507
+ while (true) {
3508
+ const tag = range(table2, cursor++, 1, "FNT name")[0];
3509
+ if (!tag) break;
3510
+ const length = tag & 127;
3511
+ if (!length) throw new Error("Empty FNT directory name");
3512
+ const filename2 = decoder.decode(range(table2, cursor, length, "FNT filename"));
3513
+ cursor += length;
3514
+ if (filename2.includes("/") || filename2.includes("\\") || filename2.includes("\0") || filename2 === "." || filename2 === "..")
3515
+ throw new Error("Invalid FNT path component");
3516
+ const normalized = filename2.toLowerCase();
3517
+ if (names.has(normalized)) throw new Error(`Duplicate FNT path: ${filename2}`);
3518
+ names.add(normalized);
3519
+ if (tag & 128) {
3520
+ const id = range(table2, cursor, 2, "FNT directory id").readUInt16LE();
3521
+ cursor += 2;
3522
+ if (id < 61440) throw new Error("Invalid FNT directory id");
3523
+ folder.folders.push(parse(id & 4095, filename2, depth + 1));
3524
+ } else {
3525
+ const entry = fat.entries[fileId++];
3526
+ if (!entry) throw new Error("FNT file id is outside FAT");
3527
+ if (fileIds.has(entry.id)) throw new Error(`Duplicate FNT file id: ${entry.id}`);
3528
+ fileIds.add(entry.id);
3529
+ folder.files.push({ name: filename2, ...entry });
3530
+ }
3531
+ }
3532
+ return folder;
3533
+ };
3534
+ this.root = { name: "root", id: 65535, files: [], folders: [parse(0, "data", 0)] };
3535
+ }
3536
+ static findFile(id, folder) {
3537
+ for (const file of folder.files) if (file.id === id) return file;
3538
+ for (const subfolder of folder.folders) {
3539
+ const file = _FileNameTable.findFile(id, subfolder);
3540
+ if (file) return file;
3541
+ }
3542
+ return void 0;
3543
+ }
3544
+ };
3545
+ var overlayFields = [
3546
+ "overlayId",
3547
+ "ramAddress",
3548
+ "ramSize",
3549
+ "bssSize",
3550
+ "staticInitialiserStartAddress",
3551
+ "staticInitialiserEndAddress",
3552
+ "fileId",
3553
+ "reserved"
3554
+ ];
3555
+ var OverlayTable = class {
3556
+ constructor(input, offset, size, isArm9) {
3557
+ this.isArm9 = isArm9;
3558
+ if (!size) return;
3559
+ const table2 = range(bytes(input), offset, size, "overlay table");
3560
+ if (size % 32) throw new Error("Invalid overlay table size");
3561
+ for (let p = 0; p < size; p += 32) {
3562
+ if (table2.readUInt32LE(p) === 4294967295) break;
3563
+ this.entries.push({
3564
+ overlayId: table2.readUInt32LE(p),
3565
+ ramAddress: table2.readUInt32LE(p + 4),
3566
+ ramSize: table2.readUInt32LE(p + 8),
3567
+ bssSize: table2.readUInt32LE(p + 12),
3568
+ staticInitialiserStartAddress: table2.readUInt32LE(p + 16),
3569
+ staticInitialiserEndAddress: table2.readUInt32LE(p + 20),
3570
+ fileId: table2.readUInt32LE(p + 24),
3571
+ reserved: table2.readUInt32LE(p + 28)
3572
+ });
3573
+ }
3574
+ }
3575
+ entries = [];
3576
+ readBasicOverlays(fat) {
3577
+ return this.entries.map((item) => {
3578
+ const file = fat.entries[item.fileId];
3579
+ if (!file) throw new Error("Overlay file id is outside FAT");
3580
+ return {
3581
+ ...file,
3582
+ name: `overlay${this.isArm9 ? "" : "7"}_${String(item.overlayId).padStart(4, "0")}.bin`
3583
+ };
3584
+ });
3585
+ }
3586
+ toBuffer() {
3587
+ const data = import_buffer.Buffer.alloc(this.entries.length * 32);
3588
+ this.entries.forEach(
3589
+ (entry, i) => overlayFields.forEach((field2, j) => data.writeUInt32LE(entry[field2], i * 32 + j * 4))
3590
+ );
3591
+ return data;
3592
+ }
3593
+ };
3594
+
3595
+ // src/nitro/twl.ts
3596
+ init_buffer();
3597
+
3598
+ // src/nitro/blz.ts
3599
+ init_buffer();
3600
+ var decompressBLZ = (input, maxSize = 268435456) => {
3601
+ if (input.length < 8) throw new Error("BLZ footer is truncated");
3602
+ const diff = input.readUInt32LE(input.length - 4);
3603
+ const packed = input.readUInt32LE(input.length - 8), header = packed >>> 24, length = packed & 16777215;
3604
+ const size = input.length + diff, prefix = input.length - length;
3605
+ if (header < 8 || header > length || length > input.length || size > maxSize)
3606
+ throw new Error("Invalid BLZ size or footer");
3607
+ const out = import_buffer.Buffer.alloc(size);
3608
+ input.copy(out, 0, 0, prefix);
3609
+ let src = input.length - header, dst = size;
3610
+ while (src > prefix) {
3611
+ const flags = input[--src];
3612
+ for (let bit = 128; bit && src > prefix; bit >>= 1) {
3613
+ if (!(flags & bit)) {
3614
+ if (dst <= prefix) throw new Error("BLZ output overflow");
3615
+ out[--dst] = input[--src];
3616
+ } else {
3617
+ if (src - 2 < prefix) throw new Error("Truncated BLZ reference");
3618
+ const high = input[--src], low = input[--src];
3619
+ const count = (high >>> 4) + 3, offset = ((high & 15) << 8 | low) + 3;
3620
+ if (dst - count < prefix || dst - 1 + offset >= size)
3621
+ throw new Error("Invalid BLZ reference");
3622
+ for (let j = 0; j < count; j++) {
3623
+ --dst;
3624
+ out[dst] = out[dst + offset];
3625
+ }
3626
+ }
3627
+ }
3628
+ }
3629
+ if (dst !== prefix) throw new Error("BLZ decompressed size mismatch");
3630
+ return out;
3631
+ };
3632
+ var compressBLZ = (input) => {
3633
+ if (input.length > 16777215) throw new Error("BLZ input exceeds 24-bit format limit");
3634
+ const temp = import_buffer.Buffer.alloc(input.length);
3635
+ let src = input.length, dst = input.length;
3636
+ const heads = new Int32Array(256).fill(-1);
3637
+ const next = new Int32Array(input.length);
3638
+ let indexedFrom = input.length;
3639
+ while (src > 0) {
3640
+ if (dst < 1) return import_buffer.Buffer.alloc(0);
3641
+ const flagPos = --dst;
3642
+ let flags = 0;
3643
+ for (let bit = 0; bit < 8; bit++) {
3644
+ flags <<= 1;
3645
+ if (!src) continue;
3646
+ while (indexedFrom > src) {
3647
+ const p = --indexedFrom;
3648
+ next[p] = heads[input[p]];
3649
+ heads[input[p]] = p;
3650
+ }
3651
+ const maxCount = Math.min(src, 18);
3652
+ let best = 0, offset = 0;
3653
+ for (let p = heads[input[src - 1]]; p >= 0; p = next[p]) {
3654
+ const d = p - src + 1;
3655
+ if (d > 4098) break;
3656
+ let n = 0;
3657
+ const limit2 = Math.min(d, maxCount);
3658
+ while (n < limit2 && input[src - 1 - n] === input[src + d - 1 - n]) n++;
3659
+ if (n > best) {
3660
+ best = n;
3661
+ offset = d;
3662
+ if (best === maxCount) break;
3663
+ }
3664
+ }
3665
+ if (best < 3) {
3666
+ if (dst < 1) return import_buffer.Buffer.alloc(0);
3667
+ temp[--dst] = input[--src];
3668
+ } else {
3669
+ if (dst < 2) return import_buffer.Buffer.alloc(0);
3670
+ src -= best;
3671
+ dst -= 2;
3672
+ temp[dst] = offset - 3 & 255;
3673
+ temp[dst + 1] = best - 3 << 4 | offset - 3 >>> 8;
3674
+ flags |= 1;
3675
+ }
3676
+ }
3677
+ temp[flagPos] = flags;
3678
+ }
3679
+ let packed = temp.subarray(dst), sourcePos = input.length, compressedPos = packed.length, prefix = 0, skip = 0;
3680
+ outer: while (sourcePos > 0) {
3681
+ const flags = packed[--compressedPos];
3682
+ for (let bit = 128; bit && sourcePos > 0; bit >>= 1) {
3683
+ if (!(flags & bit)) {
3684
+ compressedPos--;
3685
+ sourcePos--;
3686
+ } else {
3687
+ sourcePos -= (packed[compressedPos - 1] >>> 4) + 3;
3688
+ compressedPos -= 2;
3689
+ if (sourcePos < compressedPos) {
3690
+ prefix = sourcePos;
3691
+ skip = compressedPos;
3692
+ break outer;
3693
+ }
3694
+ }
3695
+ }
3696
+ }
3697
+ packed = import_buffer.Buffer.concat([input.subarray(0, prefix), packed.subarray(skip)]);
3698
+ const aligned = Math.ceil(packed.length / 4) * 4, finalSize = aligned + 8;
3699
+ if (finalSize >= input.length) return import_buffer.Buffer.alloc(0);
3700
+ const out = import_buffer.Buffer.alloc(finalSize, 255);
3701
+ packed.copy(out);
3702
+ const header = finalSize - packed.length, length = packed.length - prefix + header;
3703
+ out.writeUInt32LE((header << 24 | length) >>> 0, finalSize - 8);
3704
+ out.writeUInt32LE(input.length - finalSize, finalSize - 4);
3705
+ return out;
3706
+ };
3707
+ var decompressArm9 = (data, header) => {
3708
+ if (data.length < 24) throw new Error("ARM9 data too short");
3709
+ const nitro = data.readUInt32LE(12) === 3737126433 ? 12 : 0;
3710
+ const init = header.reserved2.readUInt32LE(0) & 16383;
3711
+ const ptr = init ? data.readUInt32LE(init + 20) : header.ARM9ramAddress + header.ARM9size;
3712
+ const compressed = ptr > header.ARM9ramAddress && ptr + nitro >= header.ARM9ramAddress + data.length;
3713
+ return {
3714
+ compressed,
3715
+ data: compressed ? import_buffer.Buffer.concat([
3716
+ decompressBLZ(data.subarray(0, data.length - nitro)),
3717
+ data.subarray(data.length - nitro)
3718
+ ]) : import_buffer.Buffer.from(data)
3719
+ };
3720
+ };
3721
+ var compressArm9 = (data, header, postSize = 0) => {
3722
+ if (data.length < 16384) throw new Error("ARM9 secure area is truncated");
3723
+ const nitro = data.readUInt32LE(12) === 3737126433 ? 12 : 0;
3724
+ const packed = compressBLZ(data.subarray(16384, data.length - nitro));
3725
+ if (!packed.length) throw new Error("ARM9 BLZ compression produced no smaller representation");
3726
+ const out = import_buffer.Buffer.concat([data.subarray(0, 16384), packed, data.subarray(data.length - nitro)]);
3727
+ const init = header.reserved2.readUInt32LE(0) & 16383;
3728
+ if (init) out.writeUInt32LE(out.length - postSize + header.ARM9ramAddress, init + 20);
3729
+ return out;
3730
+ };
3731
+
3732
+ // src/nitro/twl.ts
3733
+ var HMAC_SHA1_KEY = import_buffer.Buffer.from(
3734
+ "2106c0deba98ce3fa692e39d46f2ed0176e3cc08562363facad4ecdf9a6278348f6d633cfe22ca9220889723d2cfaec232678dfeca836498acfd3e3787465824",
3735
+ "hex"
3736
+ );
3737
+ var hash = (data) => hmacSha1(HMAC_SHA1_KEY, data);
3738
+ function slice(data, start, size, label) {
3739
+ if (!Number.isSafeInteger(start) || !Number.isSafeInteger(size) || start < 0 || size < 0 || start + size > data.length)
3740
+ throw new RangeError(`${label} outside data range`);
3741
+ return data.subarray(start, start + size);
3742
+ }
3743
+ function validate(h) {
3744
+ for (const field2 of [
3745
+ "digest_ntr_start",
3746
+ "digest_ntr_size",
3747
+ "digest_twl_start",
3748
+ "digest_twl_size",
3749
+ "sector_hashtable_start",
3750
+ "sector_hashtable_size",
3751
+ "block_hashtable_start",
3752
+ "block_hashtable_size",
3753
+ "dsi9_rom_offset",
3754
+ "dsi9_size",
3755
+ "dsi7_rom_offset",
3756
+ "dsi7_size",
3757
+ "modcrypt1_start",
3758
+ "modcrypt1_size",
3759
+ "modcrypt2_start",
3760
+ "modcrypt2_size",
3761
+ "total_rom_size"
3762
+ ]) {
3763
+ if (!Number.isSafeInteger(h[field2]) || h[field2] < 0 || h[field2] > 4294967295) {
3764
+ throw new Error(`Invalid TWL ${field2}`);
3765
+ }
3766
+ }
3767
+ const s = h.digest_sector_size;
3768
+ if (!Number.isSafeInteger(s) || s <= 0 || s > 16384 || 16384 % s)
3769
+ throw new Error("Invalid TWL digest sector size");
3770
+ if (!Number.isSafeInteger(h.digest_block_sectorcount) || h.digest_block_sectorcount <= 0 || h.digest_block_sectorcount > 1048576)
3771
+ throw new Error("Invalid TWL digest block sector count");
3772
+ if (h.digest_ntr_size < 16384 || h.digest_ntr_size % s || h.digest_twl_size % s)
3773
+ throw new Error("Invalid TWL digest region size");
3774
+ const hashes = (h.digest_ntr_size + h.digest_twl_size) / s;
3775
+ if (hashes * 20 > h.sector_hashtable_size || Math.ceil(h.sector_hashtable_size / (h.digest_block_sectorcount * 20)) * 20 > h.block_hashtable_size)
3776
+ throw new Error("TWL hash tables are too small");
3777
+ }
3778
+ var TWL = class {
3779
+ firstDSiHashOffset;
3780
+ dsiHashSize;
3781
+ Hashtable1Data;
3782
+ Hashtable2Data;
3783
+ Header2Data;
3784
+ Overlays9Sha1Hmac;
3785
+ twlEncrypted;
3786
+ DSi9Data;
3787
+ DSi7Data;
3788
+ constructor(header, overlays, original) {
3789
+ validate(header);
3790
+ const h = header;
3791
+ this.firstDSiHashOffset = h.digest_ntr_size / h.digest_sector_size * 20;
3792
+ this.dsiHashSize = h.digest_twl_size / h.digest_sector_size * 20;
3793
+ this.Hashtable1Data = import_buffer.Buffer.from(
3794
+ slice(original, h.sector_hashtable_start, h.sector_hashtable_size, "Sector hash table")
3795
+ );
3796
+ this.Hashtable2Data = import_buffer.Buffer.from(
3797
+ slice(original, h.block_hashtable_start, h.block_hashtable_size, "Block hash table")
3798
+ );
3799
+ this.DSi9Data = import_buffer.Buffer.from(
3800
+ slice(original, h.dsi9_rom_offset, Math.max(h.modcrypt1_size, h.dsi9_size), "ARM9i")
3801
+ );
3802
+ this.DSi7Data = import_buffer.Buffer.from(
3803
+ slice(original, h.dsi7_rom_offset, Math.max(h.modcrypt2_size, h.dsi7_size), "ARM7i")
3804
+ );
3805
+ this.Header2Data = h.trimmedRom ? null : Array.from(
3806
+ { length: 3 },
3807
+ (_, i) => import_buffer.Buffer.from(
3808
+ slice(original, h.digest_twl_start - 12288 + 4096 * i, 4096, "Secondary header")
3809
+ )
3810
+ );
3811
+ this.Overlays9Sha1Hmac = overlays.map(
3812
+ (o) => hash(slice(original, o.offset, o.size, "ARM9 overlay"))
3813
+ );
3814
+ let encrypted = false;
3815
+ const modcryptStart = [
3816
+ { start: h.modcrypt1_start, size: h.modcrypt1_size },
3817
+ { start: h.modcrypt2_start, size: h.modcrypt2_size }
3818
+ ].find(
3819
+ ({ start, size }) => size > 0 && start >= h.digest_twl_start && start < 4294967295
3820
+ )?.start;
3821
+ if (modcryptStart !== void 0) {
3822
+ const index = Math.floor((modcryptStart - h.digest_twl_start) / h.digest_sector_size);
3823
+ const actual = hash(
3824
+ slice(
3825
+ original,
3826
+ h.digest_twl_start + index * h.digest_sector_size,
3827
+ h.digest_sector_size,
3828
+ "Modcrypt sector"
3829
+ )
3830
+ );
3831
+ encrypted = !actual.equals(
3832
+ slice(
3833
+ this.Hashtable1Data,
3834
+ this.firstDSiHashOffset + index * 20,
3835
+ 20,
3836
+ "Modcrypt sector hash"
3837
+ )
3838
+ );
3839
+ }
3840
+ if (encrypted) this.cryptSections(h);
3841
+ this.twlEncrypted = !!(h.twlInternalFlags & 2);
3842
+ }
3843
+ cryptSections(h, writer) {
3844
+ const key2 = modcryptKey(h);
3845
+ for (const [id, data, start, counter] of [
3846
+ [1, this.DSi9Data, h.dsi9_rom_offset, h.hmac_arm9],
3847
+ [2, this.DSi7Data, h.dsi7_rom_offset, h.hmac_arm7]
3848
+ ]) {
3849
+ const size = h[`modcrypt${id}_size`];
3850
+ if (!size) continue;
3851
+ const off = h[`modcrypt${id}_start`] - start;
3852
+ const result = aes128CtrCrypt(
3853
+ key2,
3854
+ slice(counter, 0, 16, "Modcrypt counter"),
3855
+ slice(data, off, size, "Modcrypt payload")
3856
+ );
3857
+ if (writer) {
3858
+ writer.position = start + off;
3859
+ writer.write(result);
3860
+ } else result.copy(data, off);
3861
+ }
3862
+ }
3863
+ importArm9iData(data, offset = 0, size) {
3864
+ this.DSi9Data = this.importData(data, offset, size);
3865
+ }
3866
+ importArm7iData(data, offset = 0, size) {
3867
+ this.DSi7Data = this.importData(data, offset, size);
3868
+ }
3869
+ importData(data, offset, size) {
3870
+ if (typeof data === "string") data = readFileSync(data);
3871
+ size ??= data.length - offset;
3872
+ const src = slice(data, offset, size, "DSi import");
3873
+ const out = import_buffer.Buffer.alloc(Math.ceil(size / 16) * 16, 255);
3874
+ src.copy(out);
3875
+ return out;
3876
+ }
3877
+ updateOverlays9Sha1Hmac(arm9Data, header, overlays) {
3878
+ if (overlays.length !== this.Overlays9Sha1Hmac.length)
3879
+ throw new Error("Changing ARM9 overlay count is unsupported");
3880
+ const hashes = overlays.map(hash);
3881
+ if (hashes.every((h, i) => h.equals(this.Overlays9Sha1Hmac[i]))) return import_buffer.Buffer.from(arm9Data);
3882
+ const init = header.reserved2.readUInt32LE(0) & 16383;
3883
+ const hdrptr = arm9Data.readUInt32LE(init + 20) - header.ARM9ramAddress;
3884
+ const unpacked = decompressArm9(arm9Data, header);
3885
+ const end = unpacked.data.readUInt32LE(init + 8) - header.ARM9ramAddress;
3886
+ let found = -1;
3887
+ for (let p = Math.min(end - hashes.length * 20, unpacked.data.length - hashes.length * 20); p >= 0; p--) {
3888
+ if (unpacked.data.subarray(p, p + 20).equals(this.Overlays9Sha1Hmac[0])) {
3889
+ found = p;
3890
+ break;
3891
+ }
3892
+ }
3893
+ if (found < 0)
3894
+ throw new Error("ARM9 overlay hashes changed but original hash table was not found");
3895
+ hashes.forEach((h, i) => h.copy(unpacked.data, found + i * 20));
3896
+ return unpacked.compressed ? compressArm9(unpacked.data, header, arm9Data.length - hdrptr) : unpacked.data;
3897
+ }
3898
+ writeTo(writer, h) {
3899
+ validate(h);
3900
+ if (writer.position > h.sector_hashtable_start) {
3901
+ throw new Error("NTR output overlaps the fixed DSi sector hash table");
3902
+ }
3903
+ if (h.sector_hashtable_start + h.sector_hashtable_size > h.block_hashtable_start || h.block_hashtable_start + h.block_hashtable_size > h.dsi9_rom_offset || h.dsi9_rom_offset + this.DSi9Data.length > h.dsi7_rom_offset || h.dsi7_rom_offset + this.DSi7Data.length > h.total_rom_size) {
3904
+ throw new Error("DSi sections overlap or exceed the ROM size");
3905
+ }
3906
+ const fill = (end) => {
3907
+ if (writer.position < end) writer.fillTo(end, 255);
3908
+ };
3909
+ fill(h.sector_hashtable_start);
3910
+ writer.position = h.sector_hashtable_start + h.sector_hashtable_size;
3911
+ fill(h.block_hashtable_start);
3912
+ writer.position = h.block_hashtable_start + h.block_hashtable_size;
3913
+ fill(h.dsi9_rom_offset);
3914
+ if (this.Header2Data && !h.trimmedRom) {
3915
+ writer.position = h.digest_twl_start - 12288;
3916
+ this.Header2Data.forEach((b) => writer.write(b));
3917
+ }
3918
+ writer.position = h.dsi9_rom_offset;
3919
+ writer.write(this.DSi9Data);
3920
+ fill(h.dsi7_rom_offset);
3921
+ writer.position = h.dsi7_rom_offset;
3922
+ writer.write(this.DSi7Data);
3923
+ fill(h.total_rom_size);
3924
+ const finalPosition = writer.position;
3925
+ const read = (p, n) => slice(writer.buffer.subarray(0, writer.length), p, n, "TWL output digest");
3926
+ let secure = import_buffer.Buffer.from(read(h.digest_ntr_start, 16384));
3927
+ if (h.decrypted) secure = encryptSecureArea(h.gameCode, secure);
3928
+ let index = 0;
3929
+ const put = (b) => {
3930
+ writer.position = h.sector_hashtable_start + index++ * 20;
3931
+ writer.write(hash(b));
3932
+ };
3933
+ for (let p = 0; p < 16384; p += h.digest_sector_size)
3934
+ put(secure.subarray(p, p + h.digest_sector_size));
3935
+ for (let p = h.digest_ntr_start + 16384; p < h.digest_ntr_start + h.digest_ntr_size; p += h.digest_sector_size)
3936
+ put(read(p, h.digest_sector_size));
3937
+ for (let p = h.digest_twl_start; p < h.digest_twl_start + h.digest_twl_size; p += h.digest_sector_size)
3938
+ put(read(p, h.digest_sector_size));
3939
+ index = 0;
3940
+ for (let p = h.sector_hashtable_start; p < h.sector_hashtable_start + h.sector_hashtable_size; p += h.digest_block_sectorcount * 20) {
3941
+ const digest = hash(read(p, h.digest_block_sectorcount * 20));
3942
+ writer.position = h.block_hashtable_start + index++ * 20;
3943
+ writer.write(digest);
3944
+ }
3945
+ h.hmac_digest_master = hash(read(h.block_hashtable_start, h.block_hashtable_size));
3946
+ if (this.twlEncrypted) this.cryptSections(h, writer);
3947
+ writer.position = finalPosition;
3948
+ return h.hmac_digest_master;
3949
+ }
3950
+ };
3951
+
3952
+ // src/nitro/nds-file.ts
3953
+ var key = (path) => path.replaceAll("\\", "/").toLowerCase();
3954
+ var NDSFile = class _NDSFile {
3955
+ original;
3956
+ header;
3957
+ banner;
3958
+ fatTable;
3959
+ fntTable;
3960
+ overlay9Table;
3961
+ overlay7Table;
3962
+ root;
3963
+ twl;
3964
+ warnings = [];
3965
+ paths = /* @__PURE__ */ new Map();
3966
+ maxOutputSize;
3967
+ constructor(input, options = {}) {
3968
+ this.original = bytes(input, "ROM");
3969
+ this.maxOutputSize = options.maxOutputSize ?? DEFAULT_MAX_SIZE;
3970
+ this.header = new Header(this.original);
3971
+ const h = this.header;
3972
+ range(this.original, h.ARM9romOffset, h.ARM9size + (h.nitrocode ? 12 : 0), "ARM9");
3973
+ range(this.original, h.ARM7romOffset, h.ARM7size, "ARM7");
3974
+ this.banner = new Banner(this.original, h.bannerOffset, h.banner_size);
3975
+ this.fatTable = new FileAllocationTable(this.original, h.FAToffset, h.FATsize);
3976
+ this.fntTable = new FileNameTable(this.fatTable, this.original, h.FNToffset, h.FNTsize);
3977
+ this.root = this.fntTable.root;
3978
+ this.overlay9Table = new OverlayTable(
3979
+ this.original,
3980
+ h.ARM9overlayOffset,
3981
+ h.ARM9overlaySize,
3982
+ true
3983
+ );
3984
+ this.overlay7Table = new OverlayTable(
3985
+ this.original,
3986
+ h.ARM7overlayOffset,
3987
+ h.ARM7overlaySize,
3988
+ false
3989
+ );
3990
+ const arm9Overlays = this.overlay9Table.readBasicOverlays(this.fatTable);
3991
+ this.root.folders.push({
3992
+ name: "overlay",
3993
+ id: 65535,
3994
+ files: [...arm9Overlays, ...this.overlay7Table.readBasicOverlays(this.fatTable)],
3995
+ folders: []
3996
+ });
3997
+ const system = (name, offset, size) => {
3998
+ range(this.original, offset, size, name);
3999
+ this.root.files.push({ name, id: 65535, offset, size });
4000
+ };
4001
+ system("header.bin", 0, h.headerSize);
4002
+ system("banner.bin", h.bannerOffset, this.banner.raw.length);
4003
+ system("fnt.bin", h.FNToffset, h.FNTsize);
4004
+ system("fat.bin", h.FAToffset, h.FATsize);
4005
+ system("arm9.bin", h.ARM9romOffset, h.ARM9size + (h.nitrocode ? 12 : 0));
4006
+ system("arm7.bin", h.ARM7romOffset, h.ARM7size);
4007
+ if (h.ARM9overlaySize) system("overarm9.bin", h.ARM9overlayOffset, h.ARM9overlaySize);
4008
+ if (h.ARM7overlaySize) system("overarm7.bin", h.ARM7overlayOffset, h.ARM7overlaySize);
4009
+ const visit = (folder, prefix) => {
4010
+ for (const file of folder.files) {
4011
+ const path = prefix + file.name;
4012
+ if (this.paths.has(key(path))) throw new Error(`Duplicate ROM path: ${path}`);
4013
+ this.paths.set(key(path), { path, file });
4014
+ }
4015
+ for (const child of folder.folders) visit(child, prefix + child.name + "/");
4016
+ };
4017
+ visit(this.root, "");
4018
+ if (h.unitCode & 2 && h.twlInternalFlags & 1 && h.tid_high && h.tid_high !== 4294967295) {
4019
+ this.twl = new TWL(h, arm9Overlays, this.original);
4020
+ }
4021
+ }
4022
+ static async fromFile(path, options = {}) {
4023
+ return new _NDSFile(await readFile(path), options);
4024
+ }
4025
+ get data() {
4026
+ return this.root.folders[0];
4027
+ }
4028
+ get overlay() {
4029
+ return this.root.folders[1];
4030
+ }
4031
+ listFiles() {
4032
+ return [...this.paths.values()].map(({ path, file }) => ({
4033
+ path,
4034
+ id: file.id,
4035
+ offset: file.offset,
4036
+ size: file.replacement?.length ?? file.size
4037
+ }));
4038
+ }
4039
+ hasFile(path) {
4040
+ return this.paths.has(key(path));
4041
+ }
4042
+ getFile(path) {
4043
+ const entry = this.paths.get(key(path));
4044
+ if (!entry) throw new Error(`ROM file not found: ${path}`);
4045
+ return import_buffer.Buffer.from(this.fileBytes(entry.file));
4046
+ }
4047
+ /** Replace an existing file. Adding or deleting filesystem entries is not supported. */
4048
+ replaceFile(path, content) {
4049
+ const entry = this.paths.get(key(path));
4050
+ if (!entry) throw new Error(`ROM file not found: ${path}`);
4051
+ entry.file.replacement = import_buffer.Buffer.from(bytes(content));
4052
+ }
4053
+ fileBytes(file) {
4054
+ return file.replacement ?? range(this.original, file.offset, file.size, file.name);
4055
+ }
4056
+ /** Rebuild offsets, allocation table, CRCs and ROM padding. Safe to call repeatedly. */
4057
+ toBuffer() {
4058
+ const fntReplacement = this.root.files.find((file) => file.name === "fnt.bin")?.replacement;
4059
+ if (fntReplacement) {
4060
+ const replacementTree = new FileNameTable(
4061
+ this.fatTable,
4062
+ fntReplacement,
4063
+ 0,
4064
+ fntReplacement.length
4065
+ );
4066
+ const collect = (folder) => [...folder.files.map((file) => file.id), ...folder.folders.flatMap(collect)].sort(
4067
+ (a, b) => a - b
4068
+ );
4069
+ if (collect(replacementTree.root).join(",") !== collect(this.data).join(","))
4070
+ throw new Error("Replacement FNT must preserve existing file IDs");
4071
+ }
4072
+ const h = new Header(this.header.toBuffer());
4073
+ h.nitrocode = this.header.nitrocode;
4074
+ h.decrypted = this.header.decrypted;
4075
+ h.trimmedRom = this.header.trimmedRom;
4076
+ h.dlp_signature = this.header.dlp_signature;
4077
+ const writer = new BinaryWriter(65536, this.maxOutputSize);
4078
+ const system = (name) => {
4079
+ const file = this.root.files.find((file2) => file2.name === name);
4080
+ if (!file) throw new Error(`Missing ROM system file: ${name}`);
4081
+ return file;
4082
+ };
4083
+ const replacedHeader = system("header.bin").replacement;
4084
+ if (replacedHeader) {
4085
+ const replacement = new Header(replacedHeader);
4086
+ h.gameTitle = replacement.gameTitle;
4087
+ h.gameCode = replacement.gameCode;
4088
+ }
4089
+ const placements = /* @__PURE__ */ new Map();
4090
+ const write = (file, padding = true) => {
4091
+ const start = writer.position;
4092
+ writer.write(this.fileBytes(file));
4093
+ if (file.id !== 65535) placements.set(file.id, { start, end: writer.position });
4094
+ if (padding) writer.pad(512);
4095
+ };
4096
+ const overlayIds = /* @__PURE__ */ new Set();
4097
+ const writeOverlays = (arm92) => {
4098
+ const originalTable = arm92 ? this.overlay9Table : this.overlay7Table;
4099
+ const name = arm92 ? "overarm9.bin" : "overarm7.bin";
4100
+ const entry = this.root.files.find((file) => file.name === name);
4101
+ if (!entry) return;
4102
+ const raw = entry.replacement ?? originalTable.toBuffer();
4103
+ const table2 = new OverlayTable(raw, 0, raw.length, arm92);
4104
+ const files = this.overlay.files.filter((file) => file.name.startsWith(arm92 ? "overlay_" : "overlay7_")).sort((a, b) => a.id - b.id);
4105
+ for (const file of files) {
4106
+ const item = table2.entries.find((item2) => item2.fileId === file.id);
4107
+ if (!item) throw new Error(`Replacement overlay table is missing file id ${file.id}`);
4108
+ const size = this.fileBytes(file).length;
4109
+ if (item.reserved >>> 24 & 1 || !arm92 && item.reserved > 0)
4110
+ item.reserved = (item.reserved & 4278190080 | size & 16777215) >>> 0;
4111
+ overlayIds.add(file.id);
4112
+ }
4113
+ if (table2.entries.length !== files.length)
4114
+ throw new Error("Changing overlay file count is unsupported");
4115
+ const encoded = table2.toBuffer();
4116
+ if (arm92) {
4117
+ h.ARM9overlayOffset = writer.position;
4118
+ h.ARM9overlaySize = encoded.length;
4119
+ } else {
4120
+ h.ARM7overlayOffset = writer.position;
4121
+ h.ARM7overlaySize = encoded.length;
4122
+ }
4123
+ writer.write(encoded);
4124
+ writer.pad(512);
4125
+ for (const file of files) write(file);
4126
+ };
4127
+ writer.position = h.headerSize;
4128
+ h.ARM9romOffset = writer.position;
4129
+ const arm9 = system("arm9.bin");
4130
+ const arm9Bytes = this.fileBytes(arm9);
4131
+ if (arm9.replacement) {
4132
+ h.nitrocode = arm9Bytes.length >= 12 && arm9Bytes.readUInt32LE(arm9Bytes.length - 12) === 3737126433;
4133
+ }
4134
+ h.ARM9size = arm9Bytes.length - (h.nitrocode ? 12 : 0);
4135
+ write(arm9);
4136
+ h.ARM9overlayOffset = 0;
4137
+ writeOverlays(true);
4138
+ h.ARM7romOffset = writer.position;
4139
+ h.ARM7size = this.fileBytes(system("arm7.bin")).length;
4140
+ write(system("arm7.bin"));
4141
+ h.ARM7overlayOffset = 0;
4142
+ writeOverlays(false);
4143
+ h.FNToffset = writer.position;
4144
+ h.FNTsize = this.fileBytes(system("fnt.bin")).length;
4145
+ write(system("fnt.bin"));
4146
+ h.FAToffset = writer.position;
4147
+ h.FATsize = this.fatTable.entries.length * 8;
4148
+ writer.write(import_buffer.Buffer.alloc(h.FATsize));
4149
+ writer.pad(512);
4150
+ h.bannerOffset = writer.position;
4151
+ const bannerFile = system("banner.bin");
4152
+ const banner = bannerFile.replacement ? new Banner(bannerFile.replacement, 0, bannerFile.replacement.length) : this.banner;
4153
+ const bannerBytes = banner.toBuffer();
4154
+ if (h.unitCode & 2 && h.headerSize > 512) h.banner_size = bannerBytes.length;
4155
+ writer.write(bannerBytes);
4156
+ writer.pad(512);
4157
+ for (const [index, id] of this.fatTable.sortedIDs.entries()) {
4158
+ if (overlayIds.has(id)) continue;
4159
+ const file = FileNameTable.findFile(id, this.root);
4160
+ if (file) write(file, index < this.fatTable.sortedIDs.length - 1);
4161
+ else {
4162
+ const entry = this.fatTable.entries[id];
4163
+ if (entry.size > 0) {
4164
+ write({ ...entry, name: `FAT entry ${id}` }, index < this.fatTable.sortedIDs.length - 1);
4165
+ }
4166
+ }
4167
+ }
4168
+ const logicalEnd = writer.position;
4169
+ const fat = import_buffer.Buffer.alloc(h.FATsize);
4170
+ for (const [id, location] of placements) {
4171
+ fat.writeUInt32LE(location.start, id * 8);
4172
+ fat.writeUInt32LE(location.end, id * 8 + 4);
4173
+ }
4174
+ writer.position = h.FAToffset;
4175
+ writer.write(fat);
4176
+ writer.position = logicalEnd;
4177
+ h.decrypted = writer.length >= 16392 && writer.buffer.readBigUInt64LE(16384) === 0xe7ffdeffe7ffdeffn;
4178
+ if (this.twl) this.twl.writeTo(writer, h);
4179
+ h.ROMsize = writer.position;
4180
+ h.size = 2 ** Math.ceil(Math.log2(Math.max(h.ROMsize + h.dlp_signature.length, 131072)));
4181
+ const secure = writer.toBuffer().subarray(16384, 32768);
4182
+ h.secureCRC16 = crc16(h.decrypted ? encryptSecureArea(h.gameCode, secure) : secure);
4183
+ writer.position = 0;
4184
+ writer.write(h.toBuffer());
4185
+ writer.position = h.ROMsize;
4186
+ writer.write(h.dlp_signature);
4187
+ writer.fillTo(h.size);
4188
+ return writer.toBuffer();
4189
+ }
4190
+ async saveAs(path) {
4191
+ await writeFile(path, this.toBuffer());
4192
+ }
4193
+ };
4194
+
4195
+ // src/nitro-patch-helper.ts
4196
+ init_buffer();
4197
+
4198
+ // src/patch/zip.ts
4199
+ init_buffer();
4200
+ var fail = (message) => {
4201
+ throw new Error(`ZIP: ${message}`);
4202
+ };
4203
+ var utf8 = new TextDecoder("utf-8", { fatal: true });
4204
+ var cp437 = "\xC7\xFC\xE9\xE2\xE4\xE0\xE5\xE7\xEA\xEB\xE8\xEF\xEE\xEC\xC4\xC5\xC9\xE6\xC6\xF4\xF6\xF2\xFB\xF9\xFF\xD6\xDC\xA2\xA3\xA5\u20A7\u0192\xE1\xED\xF3\xFA\xF1\xD1\xAA\xBA\xBF\u2310\xAC\xBD\xBC\xA1\xAB\xBB\u2591\u2592\u2593\u2502\u2524\u2561\u2562\u2556\u2555\u2563\u2551\u2557\u255D\u255C\u255B\u2510\u2514\u2534\u252C\u251C\u2500\u253C\u255E\u255F\u255A\u2554\u2569\u2566\u2560\u2550\u256C\u2567\u2568\u2564\u2565\u2559\u2558\u2552\u2553\u256B\u256A\u2518\u250C\u2588\u2584\u258C\u2590\u2580\u03B1\xDF\u0393\u03C0\u03A3\u03C3\xB5\u03C4\u03A6\u0398\u03A9\u03B4\u221E\u03C6\u03B5\u2229\u2261\xB1\u2265\u2264\u2320\u2321\xF7\u2248\xB0\u2219\xB7\u221A\u207F\xB2\u25A0\xA0";
4205
+ function decodeUtf8(bytes2) {
4206
+ try {
4207
+ return utf8.decode(bytes2);
4208
+ } catch {
4209
+ return fail("invalid UTF-8 filename");
4210
+ }
4211
+ }
4212
+ function boundOption(value, fallback, label) {
4213
+ value ??= fallback;
4214
+ if (!Number.isSafeInteger(value) || value < 0)
4215
+ throw new RangeError(`${label} must be a non-negative safe integer`);
4216
+ return value;
4217
+ }
4218
+ function checkRange(bytes2, offset, length, end = bytes2.length) {
4219
+ if (offset < 0 || offset > end || length > end - offset)
4220
+ fail(`truncated or out-of-bounds record at ${offset} (length ${length})`);
4221
+ }
4222
+ function extras(bytes2) {
4223
+ const fields = /* @__PURE__ */ new Map();
4224
+ let offset = 0;
4225
+ while (offset < bytes2.length) {
4226
+ checkRange(bytes2, offset, 4);
4227
+ const id = bytes2.readUInt16LE(offset), length = bytes2.readUInt16LE(offset + 2);
4228
+ offset += 4;
4229
+ checkRange(bytes2, offset, length);
4230
+ if (id === 1) fail("ZIP64 archives are unsupported");
4231
+ fields.set(id, bytes2.subarray(offset, offset + length));
4232
+ offset += length;
4233
+ }
4234
+ return fields;
4235
+ }
4236
+ function filename(raw, flags, fields) {
4237
+ if (flags & 2048) return decodeUtf8(raw);
4238
+ const unicode = fields.get(28789);
4239
+ if (unicode && unicode.length >= 5 && unicode[0] === 1 && unicode.readUInt32LE(1) === crc32(raw))
4240
+ return decodeUtf8(unicode.subarray(5));
4241
+ let result = "";
4242
+ for (const byte of raw) result += byte < 128 ? String.fromCharCode(byte) : cp437[byte - 128];
4243
+ return result;
4244
+ }
4245
+ var readZip = (input, options = {}) => {
4246
+ if (!(input instanceof Uint8Array))
4247
+ throw new TypeError("ZIP input must be a Buffer or Uint8Array");
4248
+ const bytes2 = import_buffer.Buffer.from(input.buffer, input.byteOffset, input.byteLength);
4249
+ const maxSize = boundOption(
4250
+ options.maxUncompressedSize,
4251
+ 1024 * 1024 * 1024,
4252
+ "maxUncompressedSize"
4253
+ );
4254
+ const maxEntries = boundOption(options.maxEntries, 1e5, "maxEntries");
4255
+ let eocd = -1;
4256
+ for (let offset2 = bytes2.length - 22; offset2 >= Math.max(0, bytes2.length - 65557); offset2--) {
4257
+ if (bytes2.readUInt32LE(offset2) === 101010256 && offset2 + 22 + bytes2.readUInt16LE(offset2 + 20) === bytes2.length) {
4258
+ eocd = offset2;
4259
+ break;
4260
+ }
4261
+ }
4262
+ if (eocd < 0) fail("end of central directory not found or truncated");
4263
+ const disk = bytes2.readUInt16LE(eocd + 4), centralDisk = bytes2.readUInt16LE(eocd + 6);
4264
+ const diskEntries = bytes2.readUInt16LE(eocd + 8), count = bytes2.readUInt16LE(eocd + 10);
4265
+ const centralSize = bytes2.readUInt32LE(eocd + 12), centralOffset = bytes2.readUInt32LE(eocd + 16);
4266
+ if (count === 65535 || diskEntries === 65535 || centralSize === 4294967295 || centralOffset === 4294967295 || eocd >= 20 && bytes2.readUInt32LE(eocd - 20) === 117853008)
4267
+ fail("ZIP64 archives are unsupported");
4268
+ if (disk || centralDisk || diskEntries !== count)
4269
+ fail("split or multiple-disk archives are unsupported");
4270
+ if (count > maxEntries) fail(`entry count exceeds limit ${maxEntries}`);
4271
+ checkRange(bytes2, centralOffset, centralSize, eocd);
4272
+ if (centralOffset + centralSize !== eocd) fail("central directory size/offset mismatch");
4273
+ if (count > Math.floor(centralSize / 46)) fail("entry count exceeds central directory size");
4274
+ const result = /* @__PURE__ */ new Map();
4275
+ const ranges = [];
4276
+ let offset = centralOffset, totalSize = 0;
4277
+ for (let index = 0; index < count; index++) {
4278
+ checkRange(bytes2, offset, 46, eocd);
4279
+ if (bytes2.readUInt32LE(offset) !== 33639248) fail("invalid central directory signature");
4280
+ const flags = bytes2.readUInt16LE(offset + 8), method = bytes2.readUInt16LE(offset + 10);
4281
+ const checksum = bytes2.readUInt32LE(offset + 16), compressedSize = bytes2.readUInt32LE(offset + 20), size = bytes2.readUInt32LE(offset + 24);
4282
+ const nameLength = bytes2.readUInt16LE(offset + 28), extraLength = bytes2.readUInt16LE(offset + 30), commentLength = bytes2.readUInt16LE(offset + 32);
4283
+ const startDisk = bytes2.readUInt16LE(offset + 34), localOffset = bytes2.readUInt32LE(offset + 42);
4284
+ if (size === 4294967295 || compressedSize === 4294967295 || localOffset === 4294967295 || startDisk === 65535)
4285
+ fail("ZIP64 entry is unsupported");
4286
+ if (startDisk) fail("split or multiple-disk entry is unsupported");
4287
+ if (flags & 8257) fail("encrypted entries are unsupported");
4288
+ if (flags & ~2062) fail("unsupported general purpose flags");
4289
+ if (method !== 0 && method !== 8) fail(`unsupported compression method ${method}`);
4290
+ if (size > maxSize - totalSize) fail(`uncompressed size exceeds limit ${maxSize}`);
4291
+ totalSize += size;
4292
+ checkRange(bytes2, offset + 46, nameLength + extraLength + commentLength, eocd);
4293
+ const rawName = bytes2.subarray(offset + 46, offset + 46 + nameLength);
4294
+ const fields = extras(
4295
+ bytes2.subarray(offset + 46 + nameLength, offset + 46 + nameLength + extraLength)
4296
+ );
4297
+ const name = filename(rawName, flags, fields).replaceAll("\\", "/").toLowerCase();
4298
+ offset += 46 + nameLength + extraLength + commentLength;
4299
+ checkRange(bytes2, localOffset, 30, centralOffset);
4300
+ if (bytes2.readUInt32LE(localOffset) !== 67324752) fail("invalid local header signature");
4301
+ if (bytes2.readUInt16LE(localOffset + 6) !== flags || bytes2.readUInt16LE(localOffset + 8) !== method)
4302
+ fail("local header flags/compression method mismatch");
4303
+ const localNameLength = bytes2.readUInt16LE(localOffset + 26), localExtraLength = bytes2.readUInt16LE(localOffset + 28);
4304
+ const dataOffset = localOffset + 30 + localNameLength + localExtraLength;
4305
+ checkRange(bytes2, localOffset + 30, localNameLength + localExtraLength, centralOffset);
4306
+ if (!rawName.equals(bytes2.subarray(localOffset + 30, localOffset + 30 + localNameLength)))
4307
+ fail("local filename differs from central directory");
4308
+ extras(bytes2.subarray(localOffset + 30 + localNameLength, dataOffset));
4309
+ if (!(flags & 8) && (bytes2.readUInt32LE(localOffset + 14) !== checksum || bytes2.readUInt32LE(localOffset + 18) !== compressedSize || bytes2.readUInt32LE(localOffset + 22) !== size))
4310
+ fail("local header CRC/size mismatch");
4311
+ checkRange(bytes2, dataOffset, compressedSize, centralOffset);
4312
+ let dataEnd = dataOffset + compressedSize;
4313
+ if (flags & 8) {
4314
+ checkRange(bytes2, dataEnd, 12, centralOffset);
4315
+ const matches = (at) => at + 12 <= centralOffset && bytes2.readUInt32LE(at) === checksum && bytes2.readUInt32LE(at + 4) === compressedSize && bytes2.readUInt32LE(at + 8) === size;
4316
+ if (matches(dataEnd)) dataEnd += 12;
4317
+ else if (bytes2.readUInt32LE(dataEnd) === 134695760 && matches(dataEnd + 4)) dataEnd += 16;
4318
+ else fail("data descriptor CRC/size mismatch");
4319
+ }
4320
+ ranges.push({ start: localOffset, end: dataEnd });
4321
+ const compressed = bytes2.subarray(dataOffset, dataOffset + compressedSize);
4322
+ let data;
4323
+ if (method === 0) {
4324
+ if (compressedSize !== size) fail("stored entry compressed/uncompressed size mismatch");
4325
+ data = import_buffer.Buffer.from(compressed);
4326
+ } else {
4327
+ try {
4328
+ data = inflateRawSync(compressed, { maxOutputLength: Math.max(1, size) });
4329
+ } catch (error) {
4330
+ return fail(
4331
+ `cannot inflate entry ${JSON.stringify(name)} within declared size: ${error instanceof Error ? error.message : String(error)}`
4332
+ );
4333
+ }
4334
+ }
4335
+ if (data.length !== size) fail(`uncompressed size mismatch for ${JSON.stringify(name)}`);
4336
+ if (crc32(data) !== checksum) fail(`CRC32 mismatch for ${JSON.stringify(name)}`);
4337
+ if (name && !name.endsWith("/")) result.set(name, data);
4338
+ }
4339
+ if (offset !== eocd) fail("central directory entry count/length mismatch");
4340
+ ranges.sort((a, b) => a.start - b.start);
4341
+ for (let i = 1; i < ranges.length; i++)
4342
+ if (ranges[i].start < ranges[i - 1].end) fail("overlapping local entry ranges");
4343
+ return result;
4344
+ };
4345
+
4346
+ // src/patch/xdelta.ts
4347
+ init_buffer();
4348
+ var UINT32_MAX = 4294967295;
4349
+ var fail2 = (message) => {
4350
+ throw new Error(`VCDIFF: ${message}`);
4351
+ };
4352
+ var Reader = class {
4353
+ constructor(bytes2, label = "patch") {
4354
+ this.bytes = bytes2;
4355
+ this.label = label;
4356
+ }
4357
+ pos = 0;
4358
+ get remaining() {
4359
+ return this.bytes.length - this.pos;
4360
+ }
4361
+ byte() {
4362
+ if (!this.remaining) fail2(`truncated ${this.label}`);
4363
+ return this.bytes[this.pos++];
4364
+ }
4365
+ integer() {
4366
+ let value = 0;
4367
+ for (let count = 0; count < 5; count++) {
4368
+ const byte = this.byte();
4369
+ value = value * 128 + (byte & 127);
4370
+ if (value > UINT32_MAX) fail2(`integer exceeds 32-bit limit in ${this.label}`);
4371
+ if (!(byte & 128)) return value;
4372
+ }
4373
+ return fail2(`invalid variable-length integer in ${this.label}`);
4374
+ }
4375
+ take(size) {
4376
+ if (size > this.remaining)
4377
+ fail2(`truncated ${this.label}: requested ${size} bytes, ${this.remaining} remain`);
4378
+ const result = this.bytes.subarray(this.pos, this.pos + size);
4379
+ this.pos += size;
4380
+ return result;
4381
+ }
4382
+ };
4383
+ var table = [];
4384
+ var op = (type, size, mode = 0) => ({ type, size, mode });
4385
+ table.push([op("RUN", 0)]);
4386
+ for (let size = 0; size <= 17; size++) table.push([op("ADD", size)]);
4387
+ for (let mode = 0; mode <= 8; mode++) {
4388
+ table.push([op("COPY", 0, mode)]);
4389
+ for (let size = 4; size <= 18; size++) table.push([op("COPY", size, mode)]);
4390
+ }
4391
+ for (let mode = 0; mode <= 5; mode++) {
4392
+ for (let add = 1; add <= 4; add++) {
4393
+ for (let copy = 4; copy <= 6; copy++) table.push([op("ADD", add), op("COPY", copy, mode)]);
4394
+ }
4395
+ }
4396
+ for (let mode = 6; mode <= 8; mode++) {
4397
+ for (let add = 1; add <= 4; add++) table.push([op("ADD", add), op("COPY", 4, mode)]);
4398
+ }
4399
+ for (let mode = 0; mode <= 8; mode++) table.push([op("COPY", 4, mode), op("ADD", 1)]);
4400
+ function adler32(bytes2) {
4401
+ let a = 1, b = 0;
4402
+ for (let start = 0; start < bytes2.length; start += 5552) {
4403
+ const end = Math.min(start + 5552, bytes2.length);
4404
+ for (let i = start; i < end; i++) {
4405
+ a += bytes2[i];
4406
+ b += a;
4407
+ }
4408
+ a %= 65521;
4409
+ b %= 65521;
4410
+ }
4411
+ return b * 65536 + a >>> 0;
4412
+ }
4413
+ function asBuffer(value, name) {
4414
+ if (!(value instanceof Uint8Array)) throw new TypeError(`${name} must be a Buffer or Uint8Array`);
4415
+ return import_buffer.Buffer.from(value.buffer, value.byteOffset, value.byteLength);
4416
+ }
4417
+ function limit(value, fallback, name) {
4418
+ value ??= fallback;
4419
+ if (!Number.isSafeInteger(value) || value < 0 || value > UINT32_MAX)
4420
+ throw new RangeError(`${name} must be an integer between 0 and ${UINT32_MAX}`);
4421
+ return value;
4422
+ }
4423
+ var decodeXdelta = (source, patch, options = {}) => {
4424
+ const sourceBytes = asBuffer(source, "source");
4425
+ const reader = new Reader(asBuffer(patch, "patch"));
4426
+ const maxOutput = limit(options.maxOutputSize, 1024 * 1024 * 1024, "maxOutputSize");
4427
+ const maxWindow = limit(options.maxWindowSize, 16 * 1024 * 1024, "maxWindowSize");
4428
+ if (!reader.take(3).equals(import_buffer.Buffer.from([214, 195, 196]))) fail2("invalid file signature");
4429
+ if (reader.byte() !== 0) fail2("unsupported version (expected 0)");
4430
+ const header = reader.byte();
4431
+ if (header & ~7) fail2("unrecognized header indicator bits");
4432
+ if (header & 1)
4433
+ fail2("secondary compression is unsupported; recreate the patch using xdelta3 -S none");
4434
+ if (header & 2) fail2("custom code table is unsupported");
4435
+ if (header & 4) reader.take(reader.integer());
4436
+ const windows = [];
4437
+ let total = 0;
4438
+ while (reader.remaining) {
4439
+ const indicator = reader.byte();
4440
+ if (indicator & ~7 || (indicator & 3) === 3)
4441
+ fail2("invalid window indicator: source and target are mutually exclusive");
4442
+ let dictionary = import_buffer.Buffer.alloc(0);
4443
+ if (indicator & 3) {
4444
+ const length = reader.integer();
4445
+ const offset = reader.integer();
4446
+ const available = indicator & 1 ? sourceBytes.length : total;
4447
+ if (offset > available || length > available - offset)
4448
+ fail2("source segment exceeds available source/target bounds");
4449
+ if (indicator & 1) dictionary = sourceBytes.subarray(offset, offset + length);
4450
+ else {
4451
+ dictionary = import_buffer.Buffer.allocUnsafe(length);
4452
+ let base = 0;
4453
+ for (const previous of windows) {
4454
+ const start = Math.max(offset, base), end = Math.min(offset + length, base + previous.length);
4455
+ if (end > start) previous.copy(dictionary, start - offset, start - base, end - base);
4456
+ base += previous.length;
4457
+ if (base >= offset + length) break;
4458
+ }
4459
+ }
4460
+ }
4461
+ const deltaLength = reader.integer();
4462
+ const delta = new Reader(reader.take(deltaLength), "delta window");
4463
+ const targetLength = delta.integer();
4464
+ if (targetLength > maxWindow)
4465
+ fail2(`window size ${targetLength} exceeds maximum limit ${maxWindow}`);
4466
+ if (targetLength > maxOutput - total) fail2(`output size exceeds maximum limit ${maxOutput}`);
4467
+ if (dictionary.length + targetLength > UINT32_MAX)
4468
+ fail2("window address space exceeds 32-bit limit");
4469
+ const compressed = delta.byte();
4470
+ if (compressed & ~7) fail2("unrecognized delta indicator bits");
4471
+ if (compressed) fail2("secondary compression in delta sections is unsupported");
4472
+ const dataLength = delta.integer(), instructionLength = delta.integer(), addressLength = delta.integer();
4473
+ const checksum = indicator & 4 ? delta.take(4).readUInt32BE() : null;
4474
+ const data = new Reader(delta.take(dataLength), "data section");
4475
+ const instructions = new Reader(delta.take(instructionLength), "instruction section");
4476
+ const addresses = new Reader(delta.take(addressLength), "address section");
4477
+ if (delta.remaining) fail2("delta encoding length does not match section lengths");
4478
+ const target = import_buffer.Buffer.allocUnsafe(targetLength);
4479
+ const near = new Uint32Array(4), same = new Uint32Array(768);
4480
+ let nearIndex = 0, position = 0;
4481
+ while (instructions.remaining) {
4482
+ const operations = table[instructions.byte()];
4483
+ for (const { type, size: fixedSize, mode } of operations) {
4484
+ const size = fixedSize || instructions.integer();
4485
+ if (size > targetLength - position) fail2(`${type} size exceeds target window length`);
4486
+ if (type === "ADD") {
4487
+ data.take(size).copy(target, position);
4488
+ } else if (type === "RUN") {
4489
+ target.fill(data.byte(), position, position + size);
4490
+ } else {
4491
+ const here = dictionary.length + position;
4492
+ let address;
4493
+ if (mode === 0) address = addresses.integer();
4494
+ else if (mode === 1) address = here - addresses.integer();
4495
+ else if (mode < 6) address = near[mode - 2] + addresses.integer();
4496
+ else address = same[(mode - 6) * 256 + addresses.byte()];
4497
+ if (address < 0 || address >= here)
4498
+ fail2(`COPY address ${address} is outside decoded address space ${here}`);
4499
+ near[nearIndex] = address;
4500
+ nearIndex = (nearIndex + 1) % near.length;
4501
+ same[address % same.length] = address;
4502
+ let copied = 0;
4503
+ if (address < dictionary.length) {
4504
+ copied = Math.min(size, dictionary.length - address);
4505
+ dictionary.copy(target, position, address, address + copied);
4506
+ }
4507
+ const from = Math.max(0, address - dictionary.length);
4508
+ while (copied < size) {
4509
+ const count = Math.min(size - copied, position + copied - from);
4510
+ if (count <= 0) fail2("COPY references unavailable target bytes");
4511
+ target.copy(target, position + copied, from, from + count);
4512
+ copied += count;
4513
+ }
4514
+ }
4515
+ position += size;
4516
+ }
4517
+ }
4518
+ if (position !== targetLength)
4519
+ fail2(`target window length mismatch: decoded ${position}, expected ${targetLength}`);
4520
+ if (data.remaining || addresses.remaining) fail2("unused bytes in data/address section");
4521
+ if (checksum !== null && adler32(target) !== checksum) fail2("Adler32 checksum mismatch");
4522
+ windows.push(target);
4523
+ total += targetLength;
4524
+ }
4525
+ return import_buffer.Buffer.concat(windows, total);
4526
+ };
4527
+
4528
+ // src/nitro-patch-helper.ts
4529
+ var PatchReturnValue = Object.freeze({
4530
+ SUCCESS: "SUCCESS",
4531
+ MD5_MISMATCH: "MD5_MISMATCH"
4532
+ });
4533
+ var md52 = (data) => hashDigest("md5", data).toString("hex");
4534
+ var patchBuffer = (original, patch, options = {}) => {
4535
+ const input = bytes(original, "original ROM");
4536
+ const patches = readZip(patch, options);
4537
+ const inputMd5 = md52(input);
4538
+ const preprocessing = patches.get(`preprocessing/${inputMd5}.xdelta`);
4539
+ const rom = new NDSFile(
4540
+ preprocessing ? decodeXdelta(input, preprocessing, options) : input,
4541
+ options
4542
+ );
4543
+ let matched = true;
4544
+ const md5File = patches.get("md5.txt");
4545
+ if (md5File) {
4546
+ matched = false;
4547
+ for (const line of md5File.toString("utf8").split("\n")) {
4548
+ const expected = line.trim();
4549
+ if (!expected || expected.startsWith("#")) continue;
4550
+ if (expected.length !== 32) throw new Error("md5.txt \u683C\u5F0F\u9519\u8BEF\uFF0C\u53EF\u80FD\u662F\u56E0\u4E3A\u8865\u4E01\u5305\u5DF2\u635F\u574F\u3002");
4551
+ if (expected.toLowerCase() === inputMd5) {
4552
+ matched = true;
4553
+ break;
4554
+ }
4555
+ }
4556
+ }
4557
+ for (const { path } of rom.listFiles()) {
4558
+ const normalized = path.replaceAll("\\", "/").toLowerCase();
4559
+ const delta = patches.get(`xdelta/${normalized}`);
4560
+ const replacement = delta ? decodeXdelta(rom.getFile(path), delta, options) : patches.get(normalized);
4561
+ if (replacement) rom.replaceFile(path, replacement);
4562
+ }
4563
+ const buffer = rom.toBuffer();
4564
+ return {
4565
+ buffer,
4566
+ returnValue: matched ? PatchReturnValue.SUCCESS : PatchReturnValue.MD5_MISMATCH,
4567
+ inputMd5,
4568
+ outputMd5: md52(buffer)
4569
+ };
4570
+ };
4571
+ var patchIt = async (originalPath, patchPath, options = {}) => {
4572
+ const [original, patch] = await Promise.all([readFile(originalPath), readFile(patchPath)]);
4573
+ return patchBuffer(original, patch, options);
4574
+ };
4575
+ var PatchHelper = Object.freeze({ patchBuffer, patchIt });
4576
+
4577
+ // src/browser.ts
4578
+ var inspectRom = (bytes2) => {
4579
+ const rom = new NDSFile(bytes2);
4580
+ return {
4581
+ gameTitle: rom.header.gameTitle,
4582
+ gameCode: rom.header.gameCode,
4583
+ size: bytes2.byteLength,
4584
+ fileCount: rom.listFiles().length,
4585
+ checksums: {
4586
+ header: rom.header.headerCRC,
4587
+ logo: rom.header.logoCRC,
4588
+ secureArea: rom.header.secureCRC,
4589
+ banner: rom.banner.bannerCRC
4590
+ }
4591
+ };
4592
+ };
4593
+ var patchBuffer2 = (original, archive, options = {}) => {
4594
+ const result = patchBuffer(original, archive, options);
4595
+ const buffer = new Uint8Array(
4596
+ result.buffer.buffer,
4597
+ result.buffer.byteOffset,
4598
+ result.buffer.byteLength
4599
+ );
4600
+ return {
4601
+ buffer,
4602
+ returnValue: result.returnValue,
4603
+ inputMd5: result.inputMd5,
4604
+ outputMd5: result.outputMd5
4605
+ };
4606
+ };
4607
+ var PatchHelper2 = Object.freeze({ patchBuffer: patchBuffer2 });
4608
+ var NitroHelper = Object.freeze({ inspectRom });
4609
+ export {
4610
+ NitroHelper,
4611
+ PatchHelper2 as PatchHelper,
4612
+ inspectRom,
4613
+ patchBuffer2 as patchBuffer
4614
+ };
4615
+ /*! For license information please see browser.js.LEGAL.txt */
4616
+ //# sourceMappingURL=browser.js.map