@opaquecash/stellar 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.
@@ -0,0 +1,2784 @@
1
+ import { secp256k1 } from '@noble/curves/secp256k1';
2
+ import { keccak_256 } from '@noble/hashes/sha3';
3
+ import { hkdf } from '@noble/hashes/hkdf';
4
+ import { sha256 } from '@noble/hashes/sha2';
5
+ import { Keypair, StrKey } from '@stellar/stellar-sdk';
6
+ import { buildPoseidon } from 'circomlibjs';
7
+
8
+ var __create = Object.create;
9
+ var __defProp = Object.defineProperty;
10
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
11
+ var __getOwnPropNames = Object.getOwnPropertyNames;
12
+ var __getProtoOf = Object.getPrototypeOf;
13
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
14
+ var __commonJS = (cb, mod) => function __require() {
15
+ return mod || (0, cb[__getOwnPropNames(cb)[0]])((mod = { exports: {} }).exports, mod), mod.exports;
16
+ };
17
+ var __copyProps = (to, from, except, desc) => {
18
+ if (from && typeof from === "object" || typeof from === "function") {
19
+ for (let key of __getOwnPropNames(from))
20
+ if (!__hasOwnProp.call(to, key) && key !== except)
21
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
22
+ }
23
+ return to;
24
+ };
25
+ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
26
+ // If the importer is in node compatibility mode or this is not an ESM
27
+ // file that has been converted to a CommonJS file using a Babel-
28
+ // compatible transform (i.e. "__esModule" has not been set), then set
29
+ // "default" to the CommonJS "module.exports" for node compatibility.
30
+ __defProp(target, "default", { value: mod, enumerable: true }) ,
31
+ mod
32
+ ));
33
+
34
+ // node_modules/base64-js/index.js
35
+ var require_base64_js = __commonJS({
36
+ "node_modules/base64-js/index.js"(exports) {
37
+ exports.byteLength = byteLength;
38
+ exports.toByteArray = toByteArray;
39
+ exports.fromByteArray = fromByteArray;
40
+ var lookup = [];
41
+ var revLookup = [];
42
+ var Arr = typeof Uint8Array !== "undefined" ? Uint8Array : Array;
43
+ var code = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
44
+ for (i = 0, len = code.length; i < len; ++i) {
45
+ lookup[i] = code[i];
46
+ revLookup[code.charCodeAt(i)] = i;
47
+ }
48
+ var i;
49
+ var len;
50
+ revLookup["-".charCodeAt(0)] = 62;
51
+ revLookup["_".charCodeAt(0)] = 63;
52
+ function getLens(b64) {
53
+ var len2 = b64.length;
54
+ if (len2 % 4 > 0) {
55
+ throw new Error("Invalid string. Length must be a multiple of 4");
56
+ }
57
+ var validLen = b64.indexOf("=");
58
+ if (validLen === -1) validLen = len2;
59
+ var placeHoldersLen = validLen === len2 ? 0 : 4 - validLen % 4;
60
+ return [validLen, placeHoldersLen];
61
+ }
62
+ function byteLength(b64) {
63
+ var lens = getLens(b64);
64
+ var validLen = lens[0];
65
+ var placeHoldersLen = lens[1];
66
+ return (validLen + placeHoldersLen) * 3 / 4 - placeHoldersLen;
67
+ }
68
+ function _byteLength(b64, validLen, placeHoldersLen) {
69
+ return (validLen + placeHoldersLen) * 3 / 4 - placeHoldersLen;
70
+ }
71
+ function toByteArray(b64) {
72
+ var tmp;
73
+ var lens = getLens(b64);
74
+ var validLen = lens[0];
75
+ var placeHoldersLen = lens[1];
76
+ var arr = new Arr(_byteLength(b64, validLen, placeHoldersLen));
77
+ var curByte = 0;
78
+ var len2 = placeHoldersLen > 0 ? validLen - 4 : validLen;
79
+ var i2;
80
+ for (i2 = 0; i2 < len2; i2 += 4) {
81
+ tmp = revLookup[b64.charCodeAt(i2)] << 18 | revLookup[b64.charCodeAt(i2 + 1)] << 12 | revLookup[b64.charCodeAt(i2 + 2)] << 6 | revLookup[b64.charCodeAt(i2 + 3)];
82
+ arr[curByte++] = tmp >> 16 & 255;
83
+ arr[curByte++] = tmp >> 8 & 255;
84
+ arr[curByte++] = tmp & 255;
85
+ }
86
+ if (placeHoldersLen === 2) {
87
+ tmp = revLookup[b64.charCodeAt(i2)] << 2 | revLookup[b64.charCodeAt(i2 + 1)] >> 4;
88
+ arr[curByte++] = tmp & 255;
89
+ }
90
+ if (placeHoldersLen === 1) {
91
+ tmp = revLookup[b64.charCodeAt(i2)] << 10 | revLookup[b64.charCodeAt(i2 + 1)] << 4 | revLookup[b64.charCodeAt(i2 + 2)] >> 2;
92
+ arr[curByte++] = tmp >> 8 & 255;
93
+ arr[curByte++] = tmp & 255;
94
+ }
95
+ return arr;
96
+ }
97
+ function tripletToBase64(num) {
98
+ return lookup[num >> 18 & 63] + lookup[num >> 12 & 63] + lookup[num >> 6 & 63] + lookup[num & 63];
99
+ }
100
+ function encodeChunk(uint8, start, end) {
101
+ var tmp;
102
+ var output = [];
103
+ for (var i2 = start; i2 < end; i2 += 3) {
104
+ tmp = (uint8[i2] << 16 & 16711680) + (uint8[i2 + 1] << 8 & 65280) + (uint8[i2 + 2] & 255);
105
+ output.push(tripletToBase64(tmp));
106
+ }
107
+ return output.join("");
108
+ }
109
+ function fromByteArray(uint8) {
110
+ var tmp;
111
+ var len2 = uint8.length;
112
+ var extraBytes = len2 % 3;
113
+ var parts = [];
114
+ var maxChunkLength = 16383;
115
+ for (var i2 = 0, len22 = len2 - extraBytes; i2 < len22; i2 += maxChunkLength) {
116
+ parts.push(encodeChunk(uint8, i2, i2 + maxChunkLength > len22 ? len22 : i2 + maxChunkLength));
117
+ }
118
+ if (extraBytes === 1) {
119
+ tmp = uint8[len2 - 1];
120
+ parts.push(
121
+ lookup[tmp >> 2] + lookup[tmp << 4 & 63] + "=="
122
+ );
123
+ } else if (extraBytes === 2) {
124
+ tmp = (uint8[len2 - 2] << 8) + uint8[len2 - 1];
125
+ parts.push(
126
+ lookup[tmp >> 10] + lookup[tmp >> 4 & 63] + lookup[tmp << 2 & 63] + "="
127
+ );
128
+ }
129
+ return parts.join("");
130
+ }
131
+ }
132
+ });
133
+
134
+ // node_modules/ieee754/index.js
135
+ var require_ieee754 = __commonJS({
136
+ "node_modules/ieee754/index.js"(exports) {
137
+ exports.read = function(buffer, offset, isLE, mLen, nBytes) {
138
+ var e, m;
139
+ var eLen = nBytes * 8 - mLen - 1;
140
+ var eMax = (1 << eLen) - 1;
141
+ var eBias = eMax >> 1;
142
+ var nBits = -7;
143
+ var i = isLE ? nBytes - 1 : 0;
144
+ var d = isLE ? -1 : 1;
145
+ var s = buffer[offset + i];
146
+ i += d;
147
+ e = s & (1 << -nBits) - 1;
148
+ s >>= -nBits;
149
+ nBits += eLen;
150
+ for (; nBits > 0; e = e * 256 + buffer[offset + i], i += d, nBits -= 8) {
151
+ }
152
+ m = e & (1 << -nBits) - 1;
153
+ e >>= -nBits;
154
+ nBits += mLen;
155
+ for (; nBits > 0; m = m * 256 + buffer[offset + i], i += d, nBits -= 8) {
156
+ }
157
+ if (e === 0) {
158
+ e = 1 - eBias;
159
+ } else if (e === eMax) {
160
+ return m ? NaN : (s ? -1 : 1) * Infinity;
161
+ } else {
162
+ m = m + Math.pow(2, mLen);
163
+ e = e - eBias;
164
+ }
165
+ return (s ? -1 : 1) * m * Math.pow(2, e - mLen);
166
+ };
167
+ exports.write = function(buffer, value, offset, isLE, mLen, nBytes) {
168
+ var e, m, c;
169
+ var eLen = nBytes * 8 - mLen - 1;
170
+ var eMax = (1 << eLen) - 1;
171
+ var eBias = eMax >> 1;
172
+ var rt = mLen === 23 ? Math.pow(2, -24) - Math.pow(2, -77) : 0;
173
+ var i = isLE ? 0 : nBytes - 1;
174
+ var d = isLE ? 1 : -1;
175
+ var s = value < 0 || value === 0 && 1 / value < 0 ? 1 : 0;
176
+ value = Math.abs(value);
177
+ if (isNaN(value) || value === Infinity) {
178
+ m = isNaN(value) ? 1 : 0;
179
+ e = eMax;
180
+ } else {
181
+ e = Math.floor(Math.log(value) / Math.LN2);
182
+ if (value * (c = Math.pow(2, -e)) < 1) {
183
+ e--;
184
+ c *= 2;
185
+ }
186
+ if (e + eBias >= 1) {
187
+ value += rt / c;
188
+ } else {
189
+ value += rt * Math.pow(2, 1 - eBias);
190
+ }
191
+ if (value * c >= 2) {
192
+ e++;
193
+ c /= 2;
194
+ }
195
+ if (e + eBias >= eMax) {
196
+ m = 0;
197
+ e = eMax;
198
+ } else if (e + eBias >= 1) {
199
+ m = (value * c - 1) * Math.pow(2, mLen);
200
+ e = e + eBias;
201
+ } else {
202
+ m = value * Math.pow(2, eBias - 1) * Math.pow(2, mLen);
203
+ e = 0;
204
+ }
205
+ }
206
+ for (; mLen >= 8; buffer[offset + i] = m & 255, i += d, m /= 256, mLen -= 8) {
207
+ }
208
+ e = e << mLen | m;
209
+ eLen += mLen;
210
+ for (; eLen > 0; buffer[offset + i] = e & 255, i += d, e /= 256, eLen -= 8) {
211
+ }
212
+ buffer[offset + i - d] |= s * 128;
213
+ };
214
+ }
215
+ });
216
+
217
+ // node_modules/buffer/index.js
218
+ var require_buffer = __commonJS({
219
+ "node_modules/buffer/index.js"(exports) {
220
+ var base64 = require_base64_js();
221
+ var ieee754 = require_ieee754();
222
+ var customInspectSymbol = typeof Symbol === "function" && typeof Symbol["for"] === "function" ? Symbol["for"]("nodejs.util.inspect.custom") : null;
223
+ exports.Buffer = Buffer2;
224
+ exports.SlowBuffer = SlowBuffer;
225
+ exports.INSPECT_MAX_BYTES = 50;
226
+ var K_MAX_LENGTH = 2147483647;
227
+ exports.kMaxLength = K_MAX_LENGTH;
228
+ Buffer2.TYPED_ARRAY_SUPPORT = typedArraySupport();
229
+ if (!Buffer2.TYPED_ARRAY_SUPPORT && typeof console !== "undefined" && typeof console.error === "function") {
230
+ console.error(
231
+ "This browser lacks typed array (Uint8Array) support which is required by `buffer` v5.x. Use `buffer` v4.x if you require old browser support."
232
+ );
233
+ }
234
+ function typedArraySupport() {
235
+ try {
236
+ const arr = new Uint8Array(1);
237
+ const proto = { foo: function() {
238
+ return 42;
239
+ } };
240
+ Object.setPrototypeOf(proto, Uint8Array.prototype);
241
+ Object.setPrototypeOf(arr, proto);
242
+ return arr.foo() === 42;
243
+ } catch (e) {
244
+ return false;
245
+ }
246
+ }
247
+ Object.defineProperty(Buffer2.prototype, "parent", {
248
+ enumerable: true,
249
+ get: function() {
250
+ if (!Buffer2.isBuffer(this)) return void 0;
251
+ return this.buffer;
252
+ }
253
+ });
254
+ Object.defineProperty(Buffer2.prototype, "offset", {
255
+ enumerable: true,
256
+ get: function() {
257
+ if (!Buffer2.isBuffer(this)) return void 0;
258
+ return this.byteOffset;
259
+ }
260
+ });
261
+ function createBuffer(length) {
262
+ if (length > K_MAX_LENGTH) {
263
+ throw new RangeError('The value "' + length + '" is invalid for option "size"');
264
+ }
265
+ const buf = new Uint8Array(length);
266
+ Object.setPrototypeOf(buf, Buffer2.prototype);
267
+ return buf;
268
+ }
269
+ function Buffer2(arg, encodingOrOffset, length) {
270
+ if (typeof arg === "number") {
271
+ if (typeof encodingOrOffset === "string") {
272
+ throw new TypeError(
273
+ 'The "string" argument must be of type string. Received type number'
274
+ );
275
+ }
276
+ return allocUnsafe(arg);
277
+ }
278
+ return from(arg, encodingOrOffset, length);
279
+ }
280
+ Buffer2.poolSize = 8192;
281
+ function from(value, encodingOrOffset, length) {
282
+ if (typeof value === "string") {
283
+ return fromString(value, encodingOrOffset);
284
+ }
285
+ if (ArrayBuffer.isView(value)) {
286
+ return fromArrayView(value);
287
+ }
288
+ if (value == null) {
289
+ throw new TypeError(
290
+ "The first argument must be one of type string, Buffer, ArrayBuffer, Array, or Array-like Object. Received type " + typeof value
291
+ );
292
+ }
293
+ if (isInstance(value, ArrayBuffer) || value && isInstance(value.buffer, ArrayBuffer)) {
294
+ return fromArrayBuffer(value, encodingOrOffset, length);
295
+ }
296
+ if (typeof SharedArrayBuffer !== "undefined" && (isInstance(value, SharedArrayBuffer) || value && isInstance(value.buffer, SharedArrayBuffer))) {
297
+ return fromArrayBuffer(value, encodingOrOffset, length);
298
+ }
299
+ if (typeof value === "number") {
300
+ throw new TypeError(
301
+ 'The "value" argument must not be of type number. Received type number'
302
+ );
303
+ }
304
+ const valueOf = value.valueOf && value.valueOf();
305
+ if (valueOf != null && valueOf !== value) {
306
+ return Buffer2.from(valueOf, encodingOrOffset, length);
307
+ }
308
+ const b = fromObject(value);
309
+ if (b) return b;
310
+ if (typeof Symbol !== "undefined" && Symbol.toPrimitive != null && typeof value[Symbol.toPrimitive] === "function") {
311
+ return Buffer2.from(value[Symbol.toPrimitive]("string"), encodingOrOffset, length);
312
+ }
313
+ throw new TypeError(
314
+ "The first argument must be one of type string, Buffer, ArrayBuffer, Array, or Array-like Object. Received type " + typeof value
315
+ );
316
+ }
317
+ Buffer2.from = function(value, encodingOrOffset, length) {
318
+ return from(value, encodingOrOffset, length);
319
+ };
320
+ Object.setPrototypeOf(Buffer2.prototype, Uint8Array.prototype);
321
+ Object.setPrototypeOf(Buffer2, Uint8Array);
322
+ function assertSize(size) {
323
+ if (typeof size !== "number") {
324
+ throw new TypeError('"size" argument must be of type number');
325
+ } else if (size < 0) {
326
+ throw new RangeError('The value "' + size + '" is invalid for option "size"');
327
+ }
328
+ }
329
+ function alloc(size, fill, encoding) {
330
+ assertSize(size);
331
+ if (size <= 0) {
332
+ return createBuffer(size);
333
+ }
334
+ if (fill !== void 0) {
335
+ return typeof encoding === "string" ? createBuffer(size).fill(fill, encoding) : createBuffer(size).fill(fill);
336
+ }
337
+ return createBuffer(size);
338
+ }
339
+ Buffer2.alloc = function(size, fill, encoding) {
340
+ return alloc(size, fill, encoding);
341
+ };
342
+ function allocUnsafe(size) {
343
+ assertSize(size);
344
+ return createBuffer(size < 0 ? 0 : checked(size) | 0);
345
+ }
346
+ Buffer2.allocUnsafe = function(size) {
347
+ return allocUnsafe(size);
348
+ };
349
+ Buffer2.allocUnsafeSlow = function(size) {
350
+ return allocUnsafe(size);
351
+ };
352
+ function fromString(string, encoding) {
353
+ if (typeof encoding !== "string" || encoding === "") {
354
+ encoding = "utf8";
355
+ }
356
+ if (!Buffer2.isEncoding(encoding)) {
357
+ throw new TypeError("Unknown encoding: " + encoding);
358
+ }
359
+ const length = byteLength(string, encoding) | 0;
360
+ let buf = createBuffer(length);
361
+ const actual = buf.write(string, encoding);
362
+ if (actual !== length) {
363
+ buf = buf.slice(0, actual);
364
+ }
365
+ return buf;
366
+ }
367
+ function fromArrayLike(array) {
368
+ const length = array.length < 0 ? 0 : checked(array.length) | 0;
369
+ const buf = createBuffer(length);
370
+ for (let i = 0; i < length; i += 1) {
371
+ buf[i] = array[i] & 255;
372
+ }
373
+ return buf;
374
+ }
375
+ function fromArrayView(arrayView) {
376
+ if (isInstance(arrayView, Uint8Array)) {
377
+ const copy = new Uint8Array(arrayView);
378
+ return fromArrayBuffer(copy.buffer, copy.byteOffset, copy.byteLength);
379
+ }
380
+ return fromArrayLike(arrayView);
381
+ }
382
+ function fromArrayBuffer(array, byteOffset, length) {
383
+ if (byteOffset < 0 || array.byteLength < byteOffset) {
384
+ throw new RangeError('"offset" is outside of buffer bounds');
385
+ }
386
+ if (array.byteLength < byteOffset + (length || 0)) {
387
+ throw new RangeError('"length" is outside of buffer bounds');
388
+ }
389
+ let buf;
390
+ if (byteOffset === void 0 && length === void 0) {
391
+ buf = new Uint8Array(array);
392
+ } else if (length === void 0) {
393
+ buf = new Uint8Array(array, byteOffset);
394
+ } else {
395
+ buf = new Uint8Array(array, byteOffset, length);
396
+ }
397
+ Object.setPrototypeOf(buf, Buffer2.prototype);
398
+ return buf;
399
+ }
400
+ function fromObject(obj) {
401
+ if (Buffer2.isBuffer(obj)) {
402
+ const len = checked(obj.length) | 0;
403
+ const buf = createBuffer(len);
404
+ if (buf.length === 0) {
405
+ return buf;
406
+ }
407
+ obj.copy(buf, 0, 0, len);
408
+ return buf;
409
+ }
410
+ if (obj.length !== void 0) {
411
+ if (typeof obj.length !== "number" || numberIsNaN(obj.length)) {
412
+ return createBuffer(0);
413
+ }
414
+ return fromArrayLike(obj);
415
+ }
416
+ if (obj.type === "Buffer" && Array.isArray(obj.data)) {
417
+ return fromArrayLike(obj.data);
418
+ }
419
+ }
420
+ function checked(length) {
421
+ if (length >= K_MAX_LENGTH) {
422
+ throw new RangeError("Attempt to allocate Buffer larger than maximum size: 0x" + K_MAX_LENGTH.toString(16) + " bytes");
423
+ }
424
+ return length | 0;
425
+ }
426
+ function SlowBuffer(length) {
427
+ if (+length != length) {
428
+ length = 0;
429
+ }
430
+ return Buffer2.alloc(+length);
431
+ }
432
+ Buffer2.isBuffer = function isBuffer(b) {
433
+ return b != null && b._isBuffer === true && b !== Buffer2.prototype;
434
+ };
435
+ Buffer2.compare = function compare(a, b) {
436
+ if (isInstance(a, Uint8Array)) a = Buffer2.from(a, a.offset, a.byteLength);
437
+ if (isInstance(b, Uint8Array)) b = Buffer2.from(b, b.offset, b.byteLength);
438
+ if (!Buffer2.isBuffer(a) || !Buffer2.isBuffer(b)) {
439
+ throw new TypeError(
440
+ 'The "buf1", "buf2" arguments must be one of type Buffer or Uint8Array'
441
+ );
442
+ }
443
+ if (a === b) return 0;
444
+ let x = a.length;
445
+ let y = b.length;
446
+ for (let i = 0, len = Math.min(x, y); i < len; ++i) {
447
+ if (a[i] !== b[i]) {
448
+ x = a[i];
449
+ y = b[i];
450
+ break;
451
+ }
452
+ }
453
+ if (x < y) return -1;
454
+ if (y < x) return 1;
455
+ return 0;
456
+ };
457
+ Buffer2.isEncoding = function isEncoding(encoding) {
458
+ switch (String(encoding).toLowerCase()) {
459
+ case "hex":
460
+ case "utf8":
461
+ case "utf-8":
462
+ case "ascii":
463
+ case "latin1":
464
+ case "binary":
465
+ case "base64":
466
+ case "ucs2":
467
+ case "ucs-2":
468
+ case "utf16le":
469
+ case "utf-16le":
470
+ return true;
471
+ default:
472
+ return false;
473
+ }
474
+ };
475
+ Buffer2.concat = function concat(list, length) {
476
+ if (!Array.isArray(list)) {
477
+ throw new TypeError('"list" argument must be an Array of Buffers');
478
+ }
479
+ if (list.length === 0) {
480
+ return Buffer2.alloc(0);
481
+ }
482
+ let i;
483
+ if (length === void 0) {
484
+ length = 0;
485
+ for (i = 0; i < list.length; ++i) {
486
+ length += list[i].length;
487
+ }
488
+ }
489
+ const buffer = Buffer2.allocUnsafe(length);
490
+ let pos = 0;
491
+ for (i = 0; i < list.length; ++i) {
492
+ let buf = list[i];
493
+ if (isInstance(buf, Uint8Array)) {
494
+ if (pos + buf.length > buffer.length) {
495
+ if (!Buffer2.isBuffer(buf)) buf = Buffer2.from(buf);
496
+ buf.copy(buffer, pos);
497
+ } else {
498
+ Uint8Array.prototype.set.call(
499
+ buffer,
500
+ buf,
501
+ pos
502
+ );
503
+ }
504
+ } else if (!Buffer2.isBuffer(buf)) {
505
+ throw new TypeError('"list" argument must be an Array of Buffers');
506
+ } else {
507
+ buf.copy(buffer, pos);
508
+ }
509
+ pos += buf.length;
510
+ }
511
+ return buffer;
512
+ };
513
+ function byteLength(string, encoding) {
514
+ if (Buffer2.isBuffer(string)) {
515
+ return string.length;
516
+ }
517
+ if (ArrayBuffer.isView(string) || isInstance(string, ArrayBuffer)) {
518
+ return string.byteLength;
519
+ }
520
+ if (typeof string !== "string") {
521
+ throw new TypeError(
522
+ 'The "string" argument must be one of type string, Buffer, or ArrayBuffer. Received type ' + typeof string
523
+ );
524
+ }
525
+ const len = string.length;
526
+ const mustMatch = arguments.length > 2 && arguments[2] === true;
527
+ if (!mustMatch && len === 0) return 0;
528
+ let loweredCase = false;
529
+ for (; ; ) {
530
+ switch (encoding) {
531
+ case "ascii":
532
+ case "latin1":
533
+ case "binary":
534
+ return len;
535
+ case "utf8":
536
+ case "utf-8":
537
+ return utf8ToBytes(string).length;
538
+ case "ucs2":
539
+ case "ucs-2":
540
+ case "utf16le":
541
+ case "utf-16le":
542
+ return len * 2;
543
+ case "hex":
544
+ return len >>> 1;
545
+ case "base64":
546
+ return base64ToBytes2(string).length;
547
+ default:
548
+ if (loweredCase) {
549
+ return mustMatch ? -1 : utf8ToBytes(string).length;
550
+ }
551
+ encoding = ("" + encoding).toLowerCase();
552
+ loweredCase = true;
553
+ }
554
+ }
555
+ }
556
+ Buffer2.byteLength = byteLength;
557
+ function slowToString(encoding, start, end) {
558
+ let loweredCase = false;
559
+ if (start === void 0 || start < 0) {
560
+ start = 0;
561
+ }
562
+ if (start > this.length) {
563
+ return "";
564
+ }
565
+ if (end === void 0 || end > this.length) {
566
+ end = this.length;
567
+ }
568
+ if (end <= 0) {
569
+ return "";
570
+ }
571
+ end >>>= 0;
572
+ start >>>= 0;
573
+ if (end <= start) {
574
+ return "";
575
+ }
576
+ if (!encoding) encoding = "utf8";
577
+ while (true) {
578
+ switch (encoding) {
579
+ case "hex":
580
+ return hexSlice(this, start, end);
581
+ case "utf8":
582
+ case "utf-8":
583
+ return utf8Slice(this, start, end);
584
+ case "ascii":
585
+ return asciiSlice(this, start, end);
586
+ case "latin1":
587
+ case "binary":
588
+ return latin1Slice(this, start, end);
589
+ case "base64":
590
+ return base64Slice(this, start, end);
591
+ case "ucs2":
592
+ case "ucs-2":
593
+ case "utf16le":
594
+ case "utf-16le":
595
+ return utf16leSlice(this, start, end);
596
+ default:
597
+ if (loweredCase) throw new TypeError("Unknown encoding: " + encoding);
598
+ encoding = (encoding + "").toLowerCase();
599
+ loweredCase = true;
600
+ }
601
+ }
602
+ }
603
+ Buffer2.prototype._isBuffer = true;
604
+ function swap(b, n, m) {
605
+ const i = b[n];
606
+ b[n] = b[m];
607
+ b[m] = i;
608
+ }
609
+ Buffer2.prototype.swap16 = function swap16() {
610
+ const len = this.length;
611
+ if (len % 2 !== 0) {
612
+ throw new RangeError("Buffer size must be a multiple of 16-bits");
613
+ }
614
+ for (let i = 0; i < len; i += 2) {
615
+ swap(this, i, i + 1);
616
+ }
617
+ return this;
618
+ };
619
+ Buffer2.prototype.swap32 = function swap32() {
620
+ const len = this.length;
621
+ if (len % 4 !== 0) {
622
+ throw new RangeError("Buffer size must be a multiple of 32-bits");
623
+ }
624
+ for (let i = 0; i < len; i += 4) {
625
+ swap(this, i, i + 3);
626
+ swap(this, i + 1, i + 2);
627
+ }
628
+ return this;
629
+ };
630
+ Buffer2.prototype.swap64 = function swap64() {
631
+ const len = this.length;
632
+ if (len % 8 !== 0) {
633
+ throw new RangeError("Buffer size must be a multiple of 64-bits");
634
+ }
635
+ for (let i = 0; i < len; i += 8) {
636
+ swap(this, i, i + 7);
637
+ swap(this, i + 1, i + 6);
638
+ swap(this, i + 2, i + 5);
639
+ swap(this, i + 3, i + 4);
640
+ }
641
+ return this;
642
+ };
643
+ Buffer2.prototype.toString = function toString() {
644
+ const length = this.length;
645
+ if (length === 0) return "";
646
+ if (arguments.length === 0) return utf8Slice(this, 0, length);
647
+ return slowToString.apply(this, arguments);
648
+ };
649
+ Buffer2.prototype.toLocaleString = Buffer2.prototype.toString;
650
+ Buffer2.prototype.equals = function equals(b) {
651
+ if (!Buffer2.isBuffer(b)) throw new TypeError("Argument must be a Buffer");
652
+ if (this === b) return true;
653
+ return Buffer2.compare(this, b) === 0;
654
+ };
655
+ Buffer2.prototype.inspect = function inspect() {
656
+ let str = "";
657
+ const max = exports.INSPECT_MAX_BYTES;
658
+ str = this.toString("hex", 0, max).replace(/(.{2})/g, "$1 ").trim();
659
+ if (this.length > max) str += " ... ";
660
+ return "<Buffer " + str + ">";
661
+ };
662
+ if (customInspectSymbol) {
663
+ Buffer2.prototype[customInspectSymbol] = Buffer2.prototype.inspect;
664
+ }
665
+ Buffer2.prototype.compare = function compare(target, start, end, thisStart, thisEnd) {
666
+ if (isInstance(target, Uint8Array)) {
667
+ target = Buffer2.from(target, target.offset, target.byteLength);
668
+ }
669
+ if (!Buffer2.isBuffer(target)) {
670
+ throw new TypeError(
671
+ 'The "target" argument must be one of type Buffer or Uint8Array. Received type ' + typeof target
672
+ );
673
+ }
674
+ if (start === void 0) {
675
+ start = 0;
676
+ }
677
+ if (end === void 0) {
678
+ end = target ? target.length : 0;
679
+ }
680
+ if (thisStart === void 0) {
681
+ thisStart = 0;
682
+ }
683
+ if (thisEnd === void 0) {
684
+ thisEnd = this.length;
685
+ }
686
+ if (start < 0 || end > target.length || thisStart < 0 || thisEnd > this.length) {
687
+ throw new RangeError("out of range index");
688
+ }
689
+ if (thisStart >= thisEnd && start >= end) {
690
+ return 0;
691
+ }
692
+ if (thisStart >= thisEnd) {
693
+ return -1;
694
+ }
695
+ if (start >= end) {
696
+ return 1;
697
+ }
698
+ start >>>= 0;
699
+ end >>>= 0;
700
+ thisStart >>>= 0;
701
+ thisEnd >>>= 0;
702
+ if (this === target) return 0;
703
+ let x = thisEnd - thisStart;
704
+ let y = end - start;
705
+ const len = Math.min(x, y);
706
+ const thisCopy = this.slice(thisStart, thisEnd);
707
+ const targetCopy = target.slice(start, end);
708
+ for (let i = 0; i < len; ++i) {
709
+ if (thisCopy[i] !== targetCopy[i]) {
710
+ x = thisCopy[i];
711
+ y = targetCopy[i];
712
+ break;
713
+ }
714
+ }
715
+ if (x < y) return -1;
716
+ if (y < x) return 1;
717
+ return 0;
718
+ };
719
+ function bidirectionalIndexOf(buffer, val, byteOffset, encoding, dir) {
720
+ if (buffer.length === 0) return -1;
721
+ if (typeof byteOffset === "string") {
722
+ encoding = byteOffset;
723
+ byteOffset = 0;
724
+ } else if (byteOffset > 2147483647) {
725
+ byteOffset = 2147483647;
726
+ } else if (byteOffset < -2147483648) {
727
+ byteOffset = -2147483648;
728
+ }
729
+ byteOffset = +byteOffset;
730
+ if (numberIsNaN(byteOffset)) {
731
+ byteOffset = dir ? 0 : buffer.length - 1;
732
+ }
733
+ if (byteOffset < 0) byteOffset = buffer.length + byteOffset;
734
+ if (byteOffset >= buffer.length) {
735
+ if (dir) return -1;
736
+ else byteOffset = buffer.length - 1;
737
+ } else if (byteOffset < 0) {
738
+ if (dir) byteOffset = 0;
739
+ else return -1;
740
+ }
741
+ if (typeof val === "string") {
742
+ val = Buffer2.from(val, encoding);
743
+ }
744
+ if (Buffer2.isBuffer(val)) {
745
+ if (val.length === 0) {
746
+ return -1;
747
+ }
748
+ return arrayIndexOf(buffer, val, byteOffset, encoding, dir);
749
+ } else if (typeof val === "number") {
750
+ val = val & 255;
751
+ if (typeof Uint8Array.prototype.indexOf === "function") {
752
+ if (dir) {
753
+ return Uint8Array.prototype.indexOf.call(buffer, val, byteOffset);
754
+ } else {
755
+ return Uint8Array.prototype.lastIndexOf.call(buffer, val, byteOffset);
756
+ }
757
+ }
758
+ return arrayIndexOf(buffer, [val], byteOffset, encoding, dir);
759
+ }
760
+ throw new TypeError("val must be string, number or Buffer");
761
+ }
762
+ function arrayIndexOf(arr, val, byteOffset, encoding, dir) {
763
+ let indexSize = 1;
764
+ let arrLength = arr.length;
765
+ let valLength = val.length;
766
+ if (encoding !== void 0) {
767
+ encoding = String(encoding).toLowerCase();
768
+ if (encoding === "ucs2" || encoding === "ucs-2" || encoding === "utf16le" || encoding === "utf-16le") {
769
+ if (arr.length < 2 || val.length < 2) {
770
+ return -1;
771
+ }
772
+ indexSize = 2;
773
+ arrLength /= 2;
774
+ valLength /= 2;
775
+ byteOffset /= 2;
776
+ }
777
+ }
778
+ function read(buf, i2) {
779
+ if (indexSize === 1) {
780
+ return buf[i2];
781
+ } else {
782
+ return buf.readUInt16BE(i2 * indexSize);
783
+ }
784
+ }
785
+ let i;
786
+ if (dir) {
787
+ let foundIndex = -1;
788
+ for (i = byteOffset; i < arrLength; i++) {
789
+ if (read(arr, i) === read(val, foundIndex === -1 ? 0 : i - foundIndex)) {
790
+ if (foundIndex === -1) foundIndex = i;
791
+ if (i - foundIndex + 1 === valLength) return foundIndex * indexSize;
792
+ } else {
793
+ if (foundIndex !== -1) i -= i - foundIndex;
794
+ foundIndex = -1;
795
+ }
796
+ }
797
+ } else {
798
+ if (byteOffset + valLength > arrLength) byteOffset = arrLength - valLength;
799
+ for (i = byteOffset; i >= 0; i--) {
800
+ let found = true;
801
+ for (let j = 0; j < valLength; j++) {
802
+ if (read(arr, i + j) !== read(val, j)) {
803
+ found = false;
804
+ break;
805
+ }
806
+ }
807
+ if (found) return i;
808
+ }
809
+ }
810
+ return -1;
811
+ }
812
+ Buffer2.prototype.includes = function includes(val, byteOffset, encoding) {
813
+ return this.indexOf(val, byteOffset, encoding) !== -1;
814
+ };
815
+ Buffer2.prototype.indexOf = function indexOf(val, byteOffset, encoding) {
816
+ return bidirectionalIndexOf(this, val, byteOffset, encoding, true);
817
+ };
818
+ Buffer2.prototype.lastIndexOf = function lastIndexOf(val, byteOffset, encoding) {
819
+ return bidirectionalIndexOf(this, val, byteOffset, encoding, false);
820
+ };
821
+ function hexWrite(buf, string, offset, length) {
822
+ offset = Number(offset) || 0;
823
+ const remaining = buf.length - offset;
824
+ if (!length) {
825
+ length = remaining;
826
+ } else {
827
+ length = Number(length);
828
+ if (length > remaining) {
829
+ length = remaining;
830
+ }
831
+ }
832
+ const strLen = string.length;
833
+ if (length > strLen / 2) {
834
+ length = strLen / 2;
835
+ }
836
+ let i;
837
+ for (i = 0; i < length; ++i) {
838
+ const parsed = parseInt(string.substr(i * 2, 2), 16);
839
+ if (numberIsNaN(parsed)) return i;
840
+ buf[offset + i] = parsed;
841
+ }
842
+ return i;
843
+ }
844
+ function utf8Write(buf, string, offset, length) {
845
+ return blitBuffer(utf8ToBytes(string, buf.length - offset), buf, offset, length);
846
+ }
847
+ function asciiWrite(buf, string, offset, length) {
848
+ return blitBuffer(asciiToBytes(string), buf, offset, length);
849
+ }
850
+ function base64Write(buf, string, offset, length) {
851
+ return blitBuffer(base64ToBytes2(string), buf, offset, length);
852
+ }
853
+ function ucs2Write(buf, string, offset, length) {
854
+ return blitBuffer(utf16leToBytes(string, buf.length - offset), buf, offset, length);
855
+ }
856
+ Buffer2.prototype.write = function write(string, offset, length, encoding) {
857
+ if (offset === void 0) {
858
+ encoding = "utf8";
859
+ length = this.length;
860
+ offset = 0;
861
+ } else if (length === void 0 && typeof offset === "string") {
862
+ encoding = offset;
863
+ length = this.length;
864
+ offset = 0;
865
+ } else if (isFinite(offset)) {
866
+ offset = offset >>> 0;
867
+ if (isFinite(length)) {
868
+ length = length >>> 0;
869
+ if (encoding === void 0) encoding = "utf8";
870
+ } else {
871
+ encoding = length;
872
+ length = void 0;
873
+ }
874
+ } else {
875
+ throw new Error(
876
+ "Buffer.write(string, encoding, offset[, length]) is no longer supported"
877
+ );
878
+ }
879
+ const remaining = this.length - offset;
880
+ if (length === void 0 || length > remaining) length = remaining;
881
+ if (string.length > 0 && (length < 0 || offset < 0) || offset > this.length) {
882
+ throw new RangeError("Attempt to write outside buffer bounds");
883
+ }
884
+ if (!encoding) encoding = "utf8";
885
+ let loweredCase = false;
886
+ for (; ; ) {
887
+ switch (encoding) {
888
+ case "hex":
889
+ return hexWrite(this, string, offset, length);
890
+ case "utf8":
891
+ case "utf-8":
892
+ return utf8Write(this, string, offset, length);
893
+ case "ascii":
894
+ case "latin1":
895
+ case "binary":
896
+ return asciiWrite(this, string, offset, length);
897
+ case "base64":
898
+ return base64Write(this, string, offset, length);
899
+ case "ucs2":
900
+ case "ucs-2":
901
+ case "utf16le":
902
+ case "utf-16le":
903
+ return ucs2Write(this, string, offset, length);
904
+ default:
905
+ if (loweredCase) throw new TypeError("Unknown encoding: " + encoding);
906
+ encoding = ("" + encoding).toLowerCase();
907
+ loweredCase = true;
908
+ }
909
+ }
910
+ };
911
+ Buffer2.prototype.toJSON = function toJSON() {
912
+ return {
913
+ type: "Buffer",
914
+ data: Array.prototype.slice.call(this._arr || this, 0)
915
+ };
916
+ };
917
+ function base64Slice(buf, start, end) {
918
+ if (start === 0 && end === buf.length) {
919
+ return base64.fromByteArray(buf);
920
+ } else {
921
+ return base64.fromByteArray(buf.slice(start, end));
922
+ }
923
+ }
924
+ function utf8Slice(buf, start, end) {
925
+ end = Math.min(buf.length, end);
926
+ const res = [];
927
+ let i = start;
928
+ while (i < end) {
929
+ const firstByte = buf[i];
930
+ let codePoint = null;
931
+ let bytesPerSequence = firstByte > 239 ? 4 : firstByte > 223 ? 3 : firstByte > 191 ? 2 : 1;
932
+ if (i + bytesPerSequence <= end) {
933
+ let secondByte, thirdByte, fourthByte, tempCodePoint;
934
+ switch (bytesPerSequence) {
935
+ case 1:
936
+ if (firstByte < 128) {
937
+ codePoint = firstByte;
938
+ }
939
+ break;
940
+ case 2:
941
+ secondByte = buf[i + 1];
942
+ if ((secondByte & 192) === 128) {
943
+ tempCodePoint = (firstByte & 31) << 6 | secondByte & 63;
944
+ if (tempCodePoint > 127) {
945
+ codePoint = tempCodePoint;
946
+ }
947
+ }
948
+ break;
949
+ case 3:
950
+ secondByte = buf[i + 1];
951
+ thirdByte = buf[i + 2];
952
+ if ((secondByte & 192) === 128 && (thirdByte & 192) === 128) {
953
+ tempCodePoint = (firstByte & 15) << 12 | (secondByte & 63) << 6 | thirdByte & 63;
954
+ if (tempCodePoint > 2047 && (tempCodePoint < 55296 || tempCodePoint > 57343)) {
955
+ codePoint = tempCodePoint;
956
+ }
957
+ }
958
+ break;
959
+ case 4:
960
+ secondByte = buf[i + 1];
961
+ thirdByte = buf[i + 2];
962
+ fourthByte = buf[i + 3];
963
+ if ((secondByte & 192) === 128 && (thirdByte & 192) === 128 && (fourthByte & 192) === 128) {
964
+ tempCodePoint = (firstByte & 15) << 18 | (secondByte & 63) << 12 | (thirdByte & 63) << 6 | fourthByte & 63;
965
+ if (tempCodePoint > 65535 && tempCodePoint < 1114112) {
966
+ codePoint = tempCodePoint;
967
+ }
968
+ }
969
+ }
970
+ }
971
+ if (codePoint === null) {
972
+ codePoint = 65533;
973
+ bytesPerSequence = 1;
974
+ } else if (codePoint > 65535) {
975
+ codePoint -= 65536;
976
+ res.push(codePoint >>> 10 & 1023 | 55296);
977
+ codePoint = 56320 | codePoint & 1023;
978
+ }
979
+ res.push(codePoint);
980
+ i += bytesPerSequence;
981
+ }
982
+ return decodeCodePointsArray(res);
983
+ }
984
+ var MAX_ARGUMENTS_LENGTH = 4096;
985
+ function decodeCodePointsArray(codePoints) {
986
+ const len = codePoints.length;
987
+ if (len <= MAX_ARGUMENTS_LENGTH) {
988
+ return String.fromCharCode.apply(String, codePoints);
989
+ }
990
+ let res = "";
991
+ let i = 0;
992
+ while (i < len) {
993
+ res += String.fromCharCode.apply(
994
+ String,
995
+ codePoints.slice(i, i += MAX_ARGUMENTS_LENGTH)
996
+ );
997
+ }
998
+ return res;
999
+ }
1000
+ function asciiSlice(buf, start, end) {
1001
+ let ret = "";
1002
+ end = Math.min(buf.length, end);
1003
+ for (let i = start; i < end; ++i) {
1004
+ ret += String.fromCharCode(buf[i] & 127);
1005
+ }
1006
+ return ret;
1007
+ }
1008
+ function latin1Slice(buf, start, end) {
1009
+ let ret = "";
1010
+ end = Math.min(buf.length, end);
1011
+ for (let i = start; i < end; ++i) {
1012
+ ret += String.fromCharCode(buf[i]);
1013
+ }
1014
+ return ret;
1015
+ }
1016
+ function hexSlice(buf, start, end) {
1017
+ const len = buf.length;
1018
+ if (!start || start < 0) start = 0;
1019
+ if (!end || end < 0 || end > len) end = len;
1020
+ let out = "";
1021
+ for (let i = start; i < end; ++i) {
1022
+ out += hexSliceLookupTable[buf[i]];
1023
+ }
1024
+ return out;
1025
+ }
1026
+ function utf16leSlice(buf, start, end) {
1027
+ const bytes = buf.slice(start, end);
1028
+ let res = "";
1029
+ for (let i = 0; i < bytes.length - 1; i += 2) {
1030
+ res += String.fromCharCode(bytes[i] + bytes[i + 1] * 256);
1031
+ }
1032
+ return res;
1033
+ }
1034
+ Buffer2.prototype.slice = function slice(start, end) {
1035
+ const len = this.length;
1036
+ start = ~~start;
1037
+ end = end === void 0 ? len : ~~end;
1038
+ if (start < 0) {
1039
+ start += len;
1040
+ if (start < 0) start = 0;
1041
+ } else if (start > len) {
1042
+ start = len;
1043
+ }
1044
+ if (end < 0) {
1045
+ end += len;
1046
+ if (end < 0) end = 0;
1047
+ } else if (end > len) {
1048
+ end = len;
1049
+ }
1050
+ if (end < start) end = start;
1051
+ const newBuf = this.subarray(start, end);
1052
+ Object.setPrototypeOf(newBuf, Buffer2.prototype);
1053
+ return newBuf;
1054
+ };
1055
+ function checkOffset(offset, ext, length) {
1056
+ if (offset % 1 !== 0 || offset < 0) throw new RangeError("offset is not uint");
1057
+ if (offset + ext > length) throw new RangeError("Trying to access beyond buffer length");
1058
+ }
1059
+ Buffer2.prototype.readUintLE = Buffer2.prototype.readUIntLE = function readUIntLE(offset, byteLength2, noAssert) {
1060
+ offset = offset >>> 0;
1061
+ byteLength2 = byteLength2 >>> 0;
1062
+ if (!noAssert) checkOffset(offset, byteLength2, this.length);
1063
+ let val = this[offset];
1064
+ let mul = 1;
1065
+ let i = 0;
1066
+ while (++i < byteLength2 && (mul *= 256)) {
1067
+ val += this[offset + i] * mul;
1068
+ }
1069
+ return val;
1070
+ };
1071
+ Buffer2.prototype.readUintBE = Buffer2.prototype.readUIntBE = function readUIntBE(offset, byteLength2, noAssert) {
1072
+ offset = offset >>> 0;
1073
+ byteLength2 = byteLength2 >>> 0;
1074
+ if (!noAssert) {
1075
+ checkOffset(offset, byteLength2, this.length);
1076
+ }
1077
+ let val = this[offset + --byteLength2];
1078
+ let mul = 1;
1079
+ while (byteLength2 > 0 && (mul *= 256)) {
1080
+ val += this[offset + --byteLength2] * mul;
1081
+ }
1082
+ return val;
1083
+ };
1084
+ Buffer2.prototype.readUint8 = Buffer2.prototype.readUInt8 = function readUInt8(offset, noAssert) {
1085
+ offset = offset >>> 0;
1086
+ if (!noAssert) checkOffset(offset, 1, this.length);
1087
+ return this[offset];
1088
+ };
1089
+ Buffer2.prototype.readUint16LE = Buffer2.prototype.readUInt16LE = function readUInt16LE(offset, noAssert) {
1090
+ offset = offset >>> 0;
1091
+ if (!noAssert) checkOffset(offset, 2, this.length);
1092
+ return this[offset] | this[offset + 1] << 8;
1093
+ };
1094
+ Buffer2.prototype.readUint16BE = Buffer2.prototype.readUInt16BE = function readUInt16BE(offset, noAssert) {
1095
+ offset = offset >>> 0;
1096
+ if (!noAssert) checkOffset(offset, 2, this.length);
1097
+ return this[offset] << 8 | this[offset + 1];
1098
+ };
1099
+ Buffer2.prototype.readUint32LE = Buffer2.prototype.readUInt32LE = function readUInt32LE(offset, noAssert) {
1100
+ offset = offset >>> 0;
1101
+ if (!noAssert) checkOffset(offset, 4, this.length);
1102
+ return (this[offset] | this[offset + 1] << 8 | this[offset + 2] << 16) + this[offset + 3] * 16777216;
1103
+ };
1104
+ Buffer2.prototype.readUint32BE = Buffer2.prototype.readUInt32BE = function readUInt32BE(offset, noAssert) {
1105
+ offset = offset >>> 0;
1106
+ if (!noAssert) checkOffset(offset, 4, this.length);
1107
+ return this[offset] * 16777216 + (this[offset + 1] << 16 | this[offset + 2] << 8 | this[offset + 3]);
1108
+ };
1109
+ Buffer2.prototype.readBigUInt64LE = defineBigIntMethod(function readBigUInt64LE(offset) {
1110
+ offset = offset >>> 0;
1111
+ validateNumber(offset, "offset");
1112
+ const first = this[offset];
1113
+ const last = this[offset + 7];
1114
+ if (first === void 0 || last === void 0) {
1115
+ boundsError(offset, this.length - 8);
1116
+ }
1117
+ const lo = first + this[++offset] * 2 ** 8 + this[++offset] * 2 ** 16 + this[++offset] * 2 ** 24;
1118
+ const hi = this[++offset] + this[++offset] * 2 ** 8 + this[++offset] * 2 ** 16 + last * 2 ** 24;
1119
+ return BigInt(lo) + (BigInt(hi) << BigInt(32));
1120
+ });
1121
+ Buffer2.prototype.readBigUInt64BE = defineBigIntMethod(function readBigUInt64BE(offset) {
1122
+ offset = offset >>> 0;
1123
+ validateNumber(offset, "offset");
1124
+ const first = this[offset];
1125
+ const last = this[offset + 7];
1126
+ if (first === void 0 || last === void 0) {
1127
+ boundsError(offset, this.length - 8);
1128
+ }
1129
+ const hi = first * 2 ** 24 + this[++offset] * 2 ** 16 + this[++offset] * 2 ** 8 + this[++offset];
1130
+ const lo = this[++offset] * 2 ** 24 + this[++offset] * 2 ** 16 + this[++offset] * 2 ** 8 + last;
1131
+ return (BigInt(hi) << BigInt(32)) + BigInt(lo);
1132
+ });
1133
+ Buffer2.prototype.readIntLE = function readIntLE(offset, byteLength2, noAssert) {
1134
+ offset = offset >>> 0;
1135
+ byteLength2 = byteLength2 >>> 0;
1136
+ if (!noAssert) checkOffset(offset, byteLength2, this.length);
1137
+ let val = this[offset];
1138
+ let mul = 1;
1139
+ let i = 0;
1140
+ while (++i < byteLength2 && (mul *= 256)) {
1141
+ val += this[offset + i] * mul;
1142
+ }
1143
+ mul *= 128;
1144
+ if (val >= mul) val -= Math.pow(2, 8 * byteLength2);
1145
+ return val;
1146
+ };
1147
+ Buffer2.prototype.readIntBE = function readIntBE(offset, byteLength2, noAssert) {
1148
+ offset = offset >>> 0;
1149
+ byteLength2 = byteLength2 >>> 0;
1150
+ if (!noAssert) checkOffset(offset, byteLength2, this.length);
1151
+ let i = byteLength2;
1152
+ let mul = 1;
1153
+ let val = this[offset + --i];
1154
+ while (i > 0 && (mul *= 256)) {
1155
+ val += this[offset + --i] * mul;
1156
+ }
1157
+ mul *= 128;
1158
+ if (val >= mul) val -= Math.pow(2, 8 * byteLength2);
1159
+ return val;
1160
+ };
1161
+ Buffer2.prototype.readInt8 = function readInt8(offset, noAssert) {
1162
+ offset = offset >>> 0;
1163
+ if (!noAssert) checkOffset(offset, 1, this.length);
1164
+ if (!(this[offset] & 128)) return this[offset];
1165
+ return (255 - this[offset] + 1) * -1;
1166
+ };
1167
+ Buffer2.prototype.readInt16LE = function readInt16LE(offset, noAssert) {
1168
+ offset = offset >>> 0;
1169
+ if (!noAssert) checkOffset(offset, 2, this.length);
1170
+ const val = this[offset] | this[offset + 1] << 8;
1171
+ return val & 32768 ? val | 4294901760 : val;
1172
+ };
1173
+ Buffer2.prototype.readInt16BE = function readInt16BE(offset, noAssert) {
1174
+ offset = offset >>> 0;
1175
+ if (!noAssert) checkOffset(offset, 2, this.length);
1176
+ const val = this[offset + 1] | this[offset] << 8;
1177
+ return val & 32768 ? val | 4294901760 : val;
1178
+ };
1179
+ Buffer2.prototype.readInt32LE = function readInt32LE(offset, noAssert) {
1180
+ offset = offset >>> 0;
1181
+ if (!noAssert) checkOffset(offset, 4, this.length);
1182
+ return this[offset] | this[offset + 1] << 8 | this[offset + 2] << 16 | this[offset + 3] << 24;
1183
+ };
1184
+ Buffer2.prototype.readInt32BE = function readInt32BE(offset, noAssert) {
1185
+ offset = offset >>> 0;
1186
+ if (!noAssert) checkOffset(offset, 4, this.length);
1187
+ return this[offset] << 24 | this[offset + 1] << 16 | this[offset + 2] << 8 | this[offset + 3];
1188
+ };
1189
+ Buffer2.prototype.readBigInt64LE = defineBigIntMethod(function readBigInt64LE(offset) {
1190
+ offset = offset >>> 0;
1191
+ validateNumber(offset, "offset");
1192
+ const first = this[offset];
1193
+ const last = this[offset + 7];
1194
+ if (first === void 0 || last === void 0) {
1195
+ boundsError(offset, this.length - 8);
1196
+ }
1197
+ const val = this[offset + 4] + this[offset + 5] * 2 ** 8 + this[offset + 6] * 2 ** 16 + (last << 24);
1198
+ return (BigInt(val) << BigInt(32)) + BigInt(first + this[++offset] * 2 ** 8 + this[++offset] * 2 ** 16 + this[++offset] * 2 ** 24);
1199
+ });
1200
+ Buffer2.prototype.readBigInt64BE = defineBigIntMethod(function readBigInt64BE(offset) {
1201
+ offset = offset >>> 0;
1202
+ validateNumber(offset, "offset");
1203
+ const first = this[offset];
1204
+ const last = this[offset + 7];
1205
+ if (first === void 0 || last === void 0) {
1206
+ boundsError(offset, this.length - 8);
1207
+ }
1208
+ const val = (first << 24) + // Overflow
1209
+ this[++offset] * 2 ** 16 + this[++offset] * 2 ** 8 + this[++offset];
1210
+ return (BigInt(val) << BigInt(32)) + BigInt(this[++offset] * 2 ** 24 + this[++offset] * 2 ** 16 + this[++offset] * 2 ** 8 + last);
1211
+ });
1212
+ Buffer2.prototype.readFloatLE = function readFloatLE(offset, noAssert) {
1213
+ offset = offset >>> 0;
1214
+ if (!noAssert) checkOffset(offset, 4, this.length);
1215
+ return ieee754.read(this, offset, true, 23, 4);
1216
+ };
1217
+ Buffer2.prototype.readFloatBE = function readFloatBE(offset, noAssert) {
1218
+ offset = offset >>> 0;
1219
+ if (!noAssert) checkOffset(offset, 4, this.length);
1220
+ return ieee754.read(this, offset, false, 23, 4);
1221
+ };
1222
+ Buffer2.prototype.readDoubleLE = function readDoubleLE(offset, noAssert) {
1223
+ offset = offset >>> 0;
1224
+ if (!noAssert) checkOffset(offset, 8, this.length);
1225
+ return ieee754.read(this, offset, true, 52, 8);
1226
+ };
1227
+ Buffer2.prototype.readDoubleBE = function readDoubleBE(offset, noAssert) {
1228
+ offset = offset >>> 0;
1229
+ if (!noAssert) checkOffset(offset, 8, this.length);
1230
+ return ieee754.read(this, offset, false, 52, 8);
1231
+ };
1232
+ function checkInt(buf, value, offset, ext, max, min) {
1233
+ if (!Buffer2.isBuffer(buf)) throw new TypeError('"buffer" argument must be a Buffer instance');
1234
+ if (value > max || value < min) throw new RangeError('"value" argument is out of bounds');
1235
+ if (offset + ext > buf.length) throw new RangeError("Index out of range");
1236
+ }
1237
+ Buffer2.prototype.writeUintLE = Buffer2.prototype.writeUIntLE = function writeUIntLE(value, offset, byteLength2, noAssert) {
1238
+ value = +value;
1239
+ offset = offset >>> 0;
1240
+ byteLength2 = byteLength2 >>> 0;
1241
+ if (!noAssert) {
1242
+ const maxBytes = Math.pow(2, 8 * byteLength2) - 1;
1243
+ checkInt(this, value, offset, byteLength2, maxBytes, 0);
1244
+ }
1245
+ let mul = 1;
1246
+ let i = 0;
1247
+ this[offset] = value & 255;
1248
+ while (++i < byteLength2 && (mul *= 256)) {
1249
+ this[offset + i] = value / mul & 255;
1250
+ }
1251
+ return offset + byteLength2;
1252
+ };
1253
+ Buffer2.prototype.writeUintBE = Buffer2.prototype.writeUIntBE = function writeUIntBE(value, offset, byteLength2, noAssert) {
1254
+ value = +value;
1255
+ offset = offset >>> 0;
1256
+ byteLength2 = byteLength2 >>> 0;
1257
+ if (!noAssert) {
1258
+ const maxBytes = Math.pow(2, 8 * byteLength2) - 1;
1259
+ checkInt(this, value, offset, byteLength2, maxBytes, 0);
1260
+ }
1261
+ let i = byteLength2 - 1;
1262
+ let mul = 1;
1263
+ this[offset + i] = value & 255;
1264
+ while (--i >= 0 && (mul *= 256)) {
1265
+ this[offset + i] = value / mul & 255;
1266
+ }
1267
+ return offset + byteLength2;
1268
+ };
1269
+ Buffer2.prototype.writeUint8 = Buffer2.prototype.writeUInt8 = function writeUInt8(value, offset, noAssert) {
1270
+ value = +value;
1271
+ offset = offset >>> 0;
1272
+ if (!noAssert) checkInt(this, value, offset, 1, 255, 0);
1273
+ this[offset] = value & 255;
1274
+ return offset + 1;
1275
+ };
1276
+ Buffer2.prototype.writeUint16LE = Buffer2.prototype.writeUInt16LE = function writeUInt16LE(value, offset, noAssert) {
1277
+ value = +value;
1278
+ offset = offset >>> 0;
1279
+ if (!noAssert) checkInt(this, value, offset, 2, 65535, 0);
1280
+ this[offset] = value & 255;
1281
+ this[offset + 1] = value >>> 8;
1282
+ return offset + 2;
1283
+ };
1284
+ Buffer2.prototype.writeUint16BE = Buffer2.prototype.writeUInt16BE = function writeUInt16BE(value, offset, noAssert) {
1285
+ value = +value;
1286
+ offset = offset >>> 0;
1287
+ if (!noAssert) checkInt(this, value, offset, 2, 65535, 0);
1288
+ this[offset] = value >>> 8;
1289
+ this[offset + 1] = value & 255;
1290
+ return offset + 2;
1291
+ };
1292
+ Buffer2.prototype.writeUint32LE = Buffer2.prototype.writeUInt32LE = function writeUInt32LE(value, offset, noAssert) {
1293
+ value = +value;
1294
+ offset = offset >>> 0;
1295
+ if (!noAssert) checkInt(this, value, offset, 4, 4294967295, 0);
1296
+ this[offset + 3] = value >>> 24;
1297
+ this[offset + 2] = value >>> 16;
1298
+ this[offset + 1] = value >>> 8;
1299
+ this[offset] = value & 255;
1300
+ return offset + 4;
1301
+ };
1302
+ Buffer2.prototype.writeUint32BE = Buffer2.prototype.writeUInt32BE = function writeUInt32BE(value, offset, noAssert) {
1303
+ value = +value;
1304
+ offset = offset >>> 0;
1305
+ if (!noAssert) checkInt(this, value, offset, 4, 4294967295, 0);
1306
+ this[offset] = value >>> 24;
1307
+ this[offset + 1] = value >>> 16;
1308
+ this[offset + 2] = value >>> 8;
1309
+ this[offset + 3] = value & 255;
1310
+ return offset + 4;
1311
+ };
1312
+ function wrtBigUInt64LE(buf, value, offset, min, max) {
1313
+ checkIntBI(value, min, max, buf, offset, 7);
1314
+ let lo = Number(value & BigInt(4294967295));
1315
+ buf[offset++] = lo;
1316
+ lo = lo >> 8;
1317
+ buf[offset++] = lo;
1318
+ lo = lo >> 8;
1319
+ buf[offset++] = lo;
1320
+ lo = lo >> 8;
1321
+ buf[offset++] = lo;
1322
+ let hi = Number(value >> BigInt(32) & BigInt(4294967295));
1323
+ buf[offset++] = hi;
1324
+ hi = hi >> 8;
1325
+ buf[offset++] = hi;
1326
+ hi = hi >> 8;
1327
+ buf[offset++] = hi;
1328
+ hi = hi >> 8;
1329
+ buf[offset++] = hi;
1330
+ return offset;
1331
+ }
1332
+ function wrtBigUInt64BE(buf, value, offset, min, max) {
1333
+ checkIntBI(value, min, max, buf, offset, 7);
1334
+ let lo = Number(value & BigInt(4294967295));
1335
+ buf[offset + 7] = lo;
1336
+ lo = lo >> 8;
1337
+ buf[offset + 6] = lo;
1338
+ lo = lo >> 8;
1339
+ buf[offset + 5] = lo;
1340
+ lo = lo >> 8;
1341
+ buf[offset + 4] = lo;
1342
+ let hi = Number(value >> BigInt(32) & BigInt(4294967295));
1343
+ buf[offset + 3] = hi;
1344
+ hi = hi >> 8;
1345
+ buf[offset + 2] = hi;
1346
+ hi = hi >> 8;
1347
+ buf[offset + 1] = hi;
1348
+ hi = hi >> 8;
1349
+ buf[offset] = hi;
1350
+ return offset + 8;
1351
+ }
1352
+ Buffer2.prototype.writeBigUInt64LE = defineBigIntMethod(function writeBigUInt64LE(value, offset = 0) {
1353
+ return wrtBigUInt64LE(this, value, offset, BigInt(0), BigInt("0xffffffffffffffff"));
1354
+ });
1355
+ Buffer2.prototype.writeBigUInt64BE = defineBigIntMethod(function writeBigUInt64BE(value, offset = 0) {
1356
+ return wrtBigUInt64BE(this, value, offset, BigInt(0), BigInt("0xffffffffffffffff"));
1357
+ });
1358
+ Buffer2.prototype.writeIntLE = function writeIntLE(value, offset, byteLength2, noAssert) {
1359
+ value = +value;
1360
+ offset = offset >>> 0;
1361
+ if (!noAssert) {
1362
+ const limit = Math.pow(2, 8 * byteLength2 - 1);
1363
+ checkInt(this, value, offset, byteLength2, limit - 1, -limit);
1364
+ }
1365
+ let i = 0;
1366
+ let mul = 1;
1367
+ let sub = 0;
1368
+ this[offset] = value & 255;
1369
+ while (++i < byteLength2 && (mul *= 256)) {
1370
+ if (value < 0 && sub === 0 && this[offset + i - 1] !== 0) {
1371
+ sub = 1;
1372
+ }
1373
+ this[offset + i] = (value / mul >> 0) - sub & 255;
1374
+ }
1375
+ return offset + byteLength2;
1376
+ };
1377
+ Buffer2.prototype.writeIntBE = function writeIntBE(value, offset, byteLength2, noAssert) {
1378
+ value = +value;
1379
+ offset = offset >>> 0;
1380
+ if (!noAssert) {
1381
+ const limit = Math.pow(2, 8 * byteLength2 - 1);
1382
+ checkInt(this, value, offset, byteLength2, limit - 1, -limit);
1383
+ }
1384
+ let i = byteLength2 - 1;
1385
+ let mul = 1;
1386
+ let sub = 0;
1387
+ this[offset + i] = value & 255;
1388
+ while (--i >= 0 && (mul *= 256)) {
1389
+ if (value < 0 && sub === 0 && this[offset + i + 1] !== 0) {
1390
+ sub = 1;
1391
+ }
1392
+ this[offset + i] = (value / mul >> 0) - sub & 255;
1393
+ }
1394
+ return offset + byteLength2;
1395
+ };
1396
+ Buffer2.prototype.writeInt8 = function writeInt8(value, offset, noAssert) {
1397
+ value = +value;
1398
+ offset = offset >>> 0;
1399
+ if (!noAssert) checkInt(this, value, offset, 1, 127, -128);
1400
+ if (value < 0) value = 255 + value + 1;
1401
+ this[offset] = value & 255;
1402
+ return offset + 1;
1403
+ };
1404
+ Buffer2.prototype.writeInt16LE = function writeInt16LE(value, offset, noAssert) {
1405
+ value = +value;
1406
+ offset = offset >>> 0;
1407
+ if (!noAssert) checkInt(this, value, offset, 2, 32767, -32768);
1408
+ this[offset] = value & 255;
1409
+ this[offset + 1] = value >>> 8;
1410
+ return offset + 2;
1411
+ };
1412
+ Buffer2.prototype.writeInt16BE = function writeInt16BE(value, offset, noAssert) {
1413
+ value = +value;
1414
+ offset = offset >>> 0;
1415
+ if (!noAssert) checkInt(this, value, offset, 2, 32767, -32768);
1416
+ this[offset] = value >>> 8;
1417
+ this[offset + 1] = value & 255;
1418
+ return offset + 2;
1419
+ };
1420
+ Buffer2.prototype.writeInt32LE = function writeInt32LE(value, offset, noAssert) {
1421
+ value = +value;
1422
+ offset = offset >>> 0;
1423
+ if (!noAssert) checkInt(this, value, offset, 4, 2147483647, -2147483648);
1424
+ this[offset] = value & 255;
1425
+ this[offset + 1] = value >>> 8;
1426
+ this[offset + 2] = value >>> 16;
1427
+ this[offset + 3] = value >>> 24;
1428
+ return offset + 4;
1429
+ };
1430
+ Buffer2.prototype.writeInt32BE = function writeInt32BE(value, offset, noAssert) {
1431
+ value = +value;
1432
+ offset = offset >>> 0;
1433
+ if (!noAssert) checkInt(this, value, offset, 4, 2147483647, -2147483648);
1434
+ if (value < 0) value = 4294967295 + value + 1;
1435
+ this[offset] = value >>> 24;
1436
+ this[offset + 1] = value >>> 16;
1437
+ this[offset + 2] = value >>> 8;
1438
+ this[offset + 3] = value & 255;
1439
+ return offset + 4;
1440
+ };
1441
+ Buffer2.prototype.writeBigInt64LE = defineBigIntMethod(function writeBigInt64LE(value, offset = 0) {
1442
+ return wrtBigUInt64LE(this, value, offset, -BigInt("0x8000000000000000"), BigInt("0x7fffffffffffffff"));
1443
+ });
1444
+ Buffer2.prototype.writeBigInt64BE = defineBigIntMethod(function writeBigInt64BE(value, offset = 0) {
1445
+ return wrtBigUInt64BE(this, value, offset, -BigInt("0x8000000000000000"), BigInt("0x7fffffffffffffff"));
1446
+ });
1447
+ function checkIEEE754(buf, value, offset, ext, max, min) {
1448
+ if (offset + ext > buf.length) throw new RangeError("Index out of range");
1449
+ if (offset < 0) throw new RangeError("Index out of range");
1450
+ }
1451
+ function writeFloat(buf, value, offset, littleEndian, noAssert) {
1452
+ value = +value;
1453
+ offset = offset >>> 0;
1454
+ if (!noAssert) {
1455
+ checkIEEE754(buf, value, offset, 4);
1456
+ }
1457
+ ieee754.write(buf, value, offset, littleEndian, 23, 4);
1458
+ return offset + 4;
1459
+ }
1460
+ Buffer2.prototype.writeFloatLE = function writeFloatLE(value, offset, noAssert) {
1461
+ return writeFloat(this, value, offset, true, noAssert);
1462
+ };
1463
+ Buffer2.prototype.writeFloatBE = function writeFloatBE(value, offset, noAssert) {
1464
+ return writeFloat(this, value, offset, false, noAssert);
1465
+ };
1466
+ function writeDouble(buf, value, offset, littleEndian, noAssert) {
1467
+ value = +value;
1468
+ offset = offset >>> 0;
1469
+ if (!noAssert) {
1470
+ checkIEEE754(buf, value, offset, 8);
1471
+ }
1472
+ ieee754.write(buf, value, offset, littleEndian, 52, 8);
1473
+ return offset + 8;
1474
+ }
1475
+ Buffer2.prototype.writeDoubleLE = function writeDoubleLE(value, offset, noAssert) {
1476
+ return writeDouble(this, value, offset, true, noAssert);
1477
+ };
1478
+ Buffer2.prototype.writeDoubleBE = function writeDoubleBE(value, offset, noAssert) {
1479
+ return writeDouble(this, value, offset, false, noAssert);
1480
+ };
1481
+ Buffer2.prototype.copy = function copy(target, targetStart, start, end) {
1482
+ if (!Buffer2.isBuffer(target)) throw new TypeError("argument should be a Buffer");
1483
+ if (!start) start = 0;
1484
+ if (!end && end !== 0) end = this.length;
1485
+ if (targetStart >= target.length) targetStart = target.length;
1486
+ if (!targetStart) targetStart = 0;
1487
+ if (end > 0 && end < start) end = start;
1488
+ if (end === start) return 0;
1489
+ if (target.length === 0 || this.length === 0) return 0;
1490
+ if (targetStart < 0) {
1491
+ throw new RangeError("targetStart out of bounds");
1492
+ }
1493
+ if (start < 0 || start >= this.length) throw new RangeError("Index out of range");
1494
+ if (end < 0) throw new RangeError("sourceEnd out of bounds");
1495
+ if (end > this.length) end = this.length;
1496
+ if (target.length - targetStart < end - start) {
1497
+ end = target.length - targetStart + start;
1498
+ }
1499
+ const len = end - start;
1500
+ if (this === target && typeof Uint8Array.prototype.copyWithin === "function") {
1501
+ this.copyWithin(targetStart, start, end);
1502
+ } else {
1503
+ Uint8Array.prototype.set.call(
1504
+ target,
1505
+ this.subarray(start, end),
1506
+ targetStart
1507
+ );
1508
+ }
1509
+ return len;
1510
+ };
1511
+ Buffer2.prototype.fill = function fill(val, start, end, encoding) {
1512
+ if (typeof val === "string") {
1513
+ if (typeof start === "string") {
1514
+ encoding = start;
1515
+ start = 0;
1516
+ end = this.length;
1517
+ } else if (typeof end === "string") {
1518
+ encoding = end;
1519
+ end = this.length;
1520
+ }
1521
+ if (encoding !== void 0 && typeof encoding !== "string") {
1522
+ throw new TypeError("encoding must be a string");
1523
+ }
1524
+ if (typeof encoding === "string" && !Buffer2.isEncoding(encoding)) {
1525
+ throw new TypeError("Unknown encoding: " + encoding);
1526
+ }
1527
+ if (val.length === 1) {
1528
+ const code = val.charCodeAt(0);
1529
+ if (encoding === "utf8" && code < 128 || encoding === "latin1") {
1530
+ val = code;
1531
+ }
1532
+ }
1533
+ } else if (typeof val === "number") {
1534
+ val = val & 255;
1535
+ } else if (typeof val === "boolean") {
1536
+ val = Number(val);
1537
+ }
1538
+ if (start < 0 || this.length < start || this.length < end) {
1539
+ throw new RangeError("Out of range index");
1540
+ }
1541
+ if (end <= start) {
1542
+ return this;
1543
+ }
1544
+ start = start >>> 0;
1545
+ end = end === void 0 ? this.length : end >>> 0;
1546
+ if (!val) val = 0;
1547
+ let i;
1548
+ if (typeof val === "number") {
1549
+ for (i = start; i < end; ++i) {
1550
+ this[i] = val;
1551
+ }
1552
+ } else {
1553
+ const bytes = Buffer2.isBuffer(val) ? val : Buffer2.from(val, encoding);
1554
+ const len = bytes.length;
1555
+ if (len === 0) {
1556
+ throw new TypeError('The value "' + val + '" is invalid for argument "value"');
1557
+ }
1558
+ for (i = 0; i < end - start; ++i) {
1559
+ this[i + start] = bytes[i % len];
1560
+ }
1561
+ }
1562
+ return this;
1563
+ };
1564
+ var errors = {};
1565
+ function E(sym, getMessage, Base) {
1566
+ errors[sym] = class NodeError extends Base {
1567
+ constructor() {
1568
+ super();
1569
+ Object.defineProperty(this, "message", {
1570
+ value: getMessage.apply(this, arguments),
1571
+ writable: true,
1572
+ configurable: true
1573
+ });
1574
+ this.name = `${this.name} [${sym}]`;
1575
+ this.stack;
1576
+ delete this.name;
1577
+ }
1578
+ get code() {
1579
+ return sym;
1580
+ }
1581
+ set code(value) {
1582
+ Object.defineProperty(this, "code", {
1583
+ configurable: true,
1584
+ enumerable: true,
1585
+ value,
1586
+ writable: true
1587
+ });
1588
+ }
1589
+ toString() {
1590
+ return `${this.name} [${sym}]: ${this.message}`;
1591
+ }
1592
+ };
1593
+ }
1594
+ E(
1595
+ "ERR_BUFFER_OUT_OF_BOUNDS",
1596
+ function(name) {
1597
+ if (name) {
1598
+ return `${name} is outside of buffer bounds`;
1599
+ }
1600
+ return "Attempt to access memory outside buffer bounds";
1601
+ },
1602
+ RangeError
1603
+ );
1604
+ E(
1605
+ "ERR_INVALID_ARG_TYPE",
1606
+ function(name, actual) {
1607
+ return `The "${name}" argument must be of type number. Received type ${typeof actual}`;
1608
+ },
1609
+ TypeError
1610
+ );
1611
+ E(
1612
+ "ERR_OUT_OF_RANGE",
1613
+ function(str, range, input) {
1614
+ let msg = `The value of "${str}" is out of range.`;
1615
+ let received = input;
1616
+ if (Number.isInteger(input) && Math.abs(input) > 2 ** 32) {
1617
+ received = addNumericalSeparator(String(input));
1618
+ } else if (typeof input === "bigint") {
1619
+ received = String(input);
1620
+ if (input > BigInt(2) ** BigInt(32) || input < -(BigInt(2) ** BigInt(32))) {
1621
+ received = addNumericalSeparator(received);
1622
+ }
1623
+ received += "n";
1624
+ }
1625
+ msg += ` It must be ${range}. Received ${received}`;
1626
+ return msg;
1627
+ },
1628
+ RangeError
1629
+ );
1630
+ function addNumericalSeparator(val) {
1631
+ let res = "";
1632
+ let i = val.length;
1633
+ const start = val[0] === "-" ? 1 : 0;
1634
+ for (; i >= start + 4; i -= 3) {
1635
+ res = `_${val.slice(i - 3, i)}${res}`;
1636
+ }
1637
+ return `${val.slice(0, i)}${res}`;
1638
+ }
1639
+ function checkBounds(buf, offset, byteLength2) {
1640
+ validateNumber(offset, "offset");
1641
+ if (buf[offset] === void 0 || buf[offset + byteLength2] === void 0) {
1642
+ boundsError(offset, buf.length - (byteLength2 + 1));
1643
+ }
1644
+ }
1645
+ function checkIntBI(value, min, max, buf, offset, byteLength2) {
1646
+ if (value > max || value < min) {
1647
+ const n = typeof min === "bigint" ? "n" : "";
1648
+ let range;
1649
+ {
1650
+ if (min === 0 || min === BigInt(0)) {
1651
+ range = `>= 0${n} and < 2${n} ** ${(byteLength2 + 1) * 8}${n}`;
1652
+ } else {
1653
+ range = `>= -(2${n} ** ${(byteLength2 + 1) * 8 - 1}${n}) and < 2 ** ${(byteLength2 + 1) * 8 - 1}${n}`;
1654
+ }
1655
+ }
1656
+ throw new errors.ERR_OUT_OF_RANGE("value", range, value);
1657
+ }
1658
+ checkBounds(buf, offset, byteLength2);
1659
+ }
1660
+ function validateNumber(value, name) {
1661
+ if (typeof value !== "number") {
1662
+ throw new errors.ERR_INVALID_ARG_TYPE(name, "number", value);
1663
+ }
1664
+ }
1665
+ function boundsError(value, length, type) {
1666
+ if (Math.floor(value) !== value) {
1667
+ validateNumber(value, type);
1668
+ throw new errors.ERR_OUT_OF_RANGE("offset", "an integer", value);
1669
+ }
1670
+ if (length < 0) {
1671
+ throw new errors.ERR_BUFFER_OUT_OF_BOUNDS();
1672
+ }
1673
+ throw new errors.ERR_OUT_OF_RANGE(
1674
+ "offset",
1675
+ `>= ${0} and <= ${length}`,
1676
+ value
1677
+ );
1678
+ }
1679
+ var INVALID_BASE64_RE = /[^+/0-9A-Za-z-_]/g;
1680
+ function base64clean(str) {
1681
+ str = str.split("=")[0];
1682
+ str = str.trim().replace(INVALID_BASE64_RE, "");
1683
+ if (str.length < 2) return "";
1684
+ while (str.length % 4 !== 0) {
1685
+ str = str + "=";
1686
+ }
1687
+ return str;
1688
+ }
1689
+ function utf8ToBytes(string, units) {
1690
+ units = units || Infinity;
1691
+ let codePoint;
1692
+ const length = string.length;
1693
+ let leadSurrogate = null;
1694
+ const bytes = [];
1695
+ for (let i = 0; i < length; ++i) {
1696
+ codePoint = string.charCodeAt(i);
1697
+ if (codePoint > 55295 && codePoint < 57344) {
1698
+ if (!leadSurrogate) {
1699
+ if (codePoint > 56319) {
1700
+ if ((units -= 3) > -1) bytes.push(239, 191, 189);
1701
+ continue;
1702
+ } else if (i + 1 === length) {
1703
+ if ((units -= 3) > -1) bytes.push(239, 191, 189);
1704
+ continue;
1705
+ }
1706
+ leadSurrogate = codePoint;
1707
+ continue;
1708
+ }
1709
+ if (codePoint < 56320) {
1710
+ if ((units -= 3) > -1) bytes.push(239, 191, 189);
1711
+ leadSurrogate = codePoint;
1712
+ continue;
1713
+ }
1714
+ codePoint = (leadSurrogate - 55296 << 10 | codePoint - 56320) + 65536;
1715
+ } else if (leadSurrogate) {
1716
+ if ((units -= 3) > -1) bytes.push(239, 191, 189);
1717
+ }
1718
+ leadSurrogate = null;
1719
+ if (codePoint < 128) {
1720
+ if ((units -= 1) < 0) break;
1721
+ bytes.push(codePoint);
1722
+ } else if (codePoint < 2048) {
1723
+ if ((units -= 2) < 0) break;
1724
+ bytes.push(
1725
+ codePoint >> 6 | 192,
1726
+ codePoint & 63 | 128
1727
+ );
1728
+ } else if (codePoint < 65536) {
1729
+ if ((units -= 3) < 0) break;
1730
+ bytes.push(
1731
+ codePoint >> 12 | 224,
1732
+ codePoint >> 6 & 63 | 128,
1733
+ codePoint & 63 | 128
1734
+ );
1735
+ } else if (codePoint < 1114112) {
1736
+ if ((units -= 4) < 0) break;
1737
+ bytes.push(
1738
+ codePoint >> 18 | 240,
1739
+ codePoint >> 12 & 63 | 128,
1740
+ codePoint >> 6 & 63 | 128,
1741
+ codePoint & 63 | 128
1742
+ );
1743
+ } else {
1744
+ throw new Error("Invalid code point");
1745
+ }
1746
+ }
1747
+ return bytes;
1748
+ }
1749
+ function asciiToBytes(str) {
1750
+ const byteArray = [];
1751
+ for (let i = 0; i < str.length; ++i) {
1752
+ byteArray.push(str.charCodeAt(i) & 255);
1753
+ }
1754
+ return byteArray;
1755
+ }
1756
+ function utf16leToBytes(str, units) {
1757
+ let c, hi, lo;
1758
+ const byteArray = [];
1759
+ for (let i = 0; i < str.length; ++i) {
1760
+ if ((units -= 2) < 0) break;
1761
+ c = str.charCodeAt(i);
1762
+ hi = c >> 8;
1763
+ lo = c % 256;
1764
+ byteArray.push(lo);
1765
+ byteArray.push(hi);
1766
+ }
1767
+ return byteArray;
1768
+ }
1769
+ function base64ToBytes2(str) {
1770
+ return base64.toByteArray(base64clean(str));
1771
+ }
1772
+ function blitBuffer(src, dst, offset, length) {
1773
+ let i;
1774
+ for (i = 0; i < length; ++i) {
1775
+ if (i + offset >= dst.length || i >= src.length) break;
1776
+ dst[i + offset] = src[i];
1777
+ }
1778
+ return i;
1779
+ }
1780
+ function isInstance(obj, type) {
1781
+ return obj instanceof type || obj != null && obj.constructor != null && obj.constructor.name != null && obj.constructor.name === type.name;
1782
+ }
1783
+ function numberIsNaN(obj) {
1784
+ return obj !== obj;
1785
+ }
1786
+ var hexSliceLookupTable = (function() {
1787
+ const alphabet = "0123456789abcdef";
1788
+ const table = new Array(256);
1789
+ for (let i = 0; i < 16; ++i) {
1790
+ const i16 = i * 16;
1791
+ for (let j = 0; j < 16; ++j) {
1792
+ table[i16 + j] = alphabet[i] + alphabet[j];
1793
+ }
1794
+ }
1795
+ return table;
1796
+ })();
1797
+ function defineBigIntMethod(fn) {
1798
+ return typeof BigInt === "undefined" ? BufferBigIntNotDefined : fn;
1799
+ }
1800
+ function BufferBigIntNotDefined() {
1801
+ throw new Error("BigInt not supported");
1802
+ }
1803
+ }
1804
+ });
1805
+
1806
+ // src/crypto/bytes.ts
1807
+ function hexToBytes(hex) {
1808
+ const h = hex.startsWith("0x") ? hex.slice(2) : hex;
1809
+ if (h.length % 2) throw new Error("Invalid hex length");
1810
+ const out = new Uint8Array(h.length / 2);
1811
+ for (let i = 0; i < out.length; i++) {
1812
+ out[i] = parseInt(h.slice(i * 2, i * 2 + 2), 16);
1813
+ }
1814
+ return out;
1815
+ }
1816
+ function bytesToHex(b) {
1817
+ return Array.from(b).map((x) => x.toString(16).padStart(2, "0")).join("");
1818
+ }
1819
+ function bytesToBigInt(b) {
1820
+ let x = 0n;
1821
+ for (let i = 0; i < b.length; i++) x = x << 8n | BigInt(b[i]);
1822
+ return x;
1823
+ }
1824
+ function bigIntToBytes32(value) {
1825
+ const out = new Uint8Array(32);
1826
+ let x = value;
1827
+ for (let i = 31; i >= 0; i--) {
1828
+ out[i] = Number(x & 0xffn);
1829
+ x >>= 8n;
1830
+ }
1831
+ return out;
1832
+ }
1833
+ function toHex32(v) {
1834
+ return "0x" + v.toString(16).padStart(64, "0");
1835
+ }
1836
+ function concatBytes(...arrays) {
1837
+ const total = arrays.reduce((n, a) => n + a.length, 0);
1838
+ const out = new Uint8Array(total);
1839
+ let off = 0;
1840
+ for (const a of arrays) {
1841
+ out.set(a, off);
1842
+ off += a.length;
1843
+ }
1844
+ return out;
1845
+ }
1846
+
1847
+ // src/crypto/amount.ts
1848
+ var MAX_DECIMALS = 7;
1849
+ function parseXlmToStroops(xlmString) {
1850
+ const trimmed = xlmString.trim();
1851
+ if (!trimmed) {
1852
+ throw new Error("XLM amount cannot be empty");
1853
+ }
1854
+ if (!/^-?\d+\.?\d*$/.test(trimmed)) {
1855
+ throw new Error(`Invalid XLM amount: ${trimmed}`);
1856
+ }
1857
+ const isNegative = trimmed.startsWith("-");
1858
+ const absolute = isNegative ? trimmed.slice(1) : trimmed;
1859
+ const parts = absolute.split(".");
1860
+ const integerPart = parts[0] || "0";
1861
+ const decimalPart = parts[1] || "";
1862
+ if (decimalPart.length > MAX_DECIMALS) {
1863
+ throw new Error(
1864
+ `XLM amount has too many decimal places (max ${MAX_DECIMALS}): ${trimmed}`
1865
+ );
1866
+ }
1867
+ const paddedDecimal = decimalPart.padEnd(MAX_DECIMALS, "0");
1868
+ const stroops = BigInt(integerPart + paddedDecimal);
1869
+ return isNegative ? -stroops : stroops;
1870
+ }
1871
+ function parseHorizonBalanceToStroops(balanceString) {
1872
+ if (!balanceString || balanceString.trim() === "") return 0n;
1873
+ try {
1874
+ return parseXlmToStroops(balanceString);
1875
+ } catch {
1876
+ return 0n;
1877
+ }
1878
+ }
1879
+ function formatStroopsToXlm(stroops) {
1880
+ const isNegative = stroops < 0n;
1881
+ const absolute = isNegative ? -stroops : stroops;
1882
+ const stroopsString = absolute.toString().padStart(MAX_DECIMALS + 1, "0");
1883
+ const integerPart = stroopsString.slice(0, -MAX_DECIMALS) || "0";
1884
+ const decimalPart = stroopsString.slice(-MAX_DECIMALS);
1885
+ const trimmedDecimal = decimalPart.replace(/0+$/, "");
1886
+ if (trimmedDecimal === "") {
1887
+ return isNegative ? `-${integerPart}` : integerPart;
1888
+ }
1889
+ return isNegative ? `-${integerPart}.${trimmedDecimal}` : `${integerPart}.${trimmedDecimal}`;
1890
+ }
1891
+ var formatXlm = formatStroopsToXlm;
1892
+ var CURVE = secp256k1;
1893
+ var DOMAIN = "opaque-cash-v1";
1894
+ var PROTOCOL_VERSION = "1";
1895
+ function buildDomainSeparatedMessage(opts) {
1896
+ return [
1897
+ `--- Opaque Protocol Key Derivation ---`,
1898
+ `App: Opaque Stellar`,
1899
+ `Origin: ${opts.origin}`,
1900
+ `Network: ${opts.networkPassphrase}`,
1901
+ `Wallet: ${opts.walletPublicKey}`,
1902
+ `Version: ${PROTOCOL_VERSION}`,
1903
+ `Purpose: ${opts.purpose}`,
1904
+ ``,
1905
+ `Warning: Signing this message authorizes key derivation for the Opaque protocol.`,
1906
+ `This is not a transaction and does not move funds.`,
1907
+ `Do not sign this message on untrusted sites or applications.`
1908
+ ].join("\n");
1909
+ }
1910
+ var LEGACY_SETUP_MESSAGE = "Sign this message to derive your Opaque Cash stealth keys on Stellar. This is not a transaction and does not move funds.";
1911
+ function deriveKeysFromSignature(signatureHex) {
1912
+ const sigBytes = typeof signatureHex === "string" ? signatureHex.startsWith("0x") ? signatureHex.slice(2) : signatureHex : signatureHex;
1913
+ const sig = typeof sigBytes === "string" ? hexToBytes(sigBytes) : sigBytes;
1914
+ const okm = hkdf(sha256, sig, void 0, DOMAIN, 64);
1915
+ return { viewingKey: okm.slice(0, 32), spendingKey: okm.slice(32, 64) };
1916
+ }
1917
+ function keysToStealthMetaAddress(viewingKey, spendingKey) {
1918
+ const V = CURVE.getPublicKey(viewingKey, true);
1919
+ const S = CURVE.getPublicKey(spendingKey, true);
1920
+ const metaAddress = new Uint8Array(V.length + S.length);
1921
+ metaAddress.set(V, 0);
1922
+ metaAddress.set(S, V.length);
1923
+ return { V, S, metaAddress };
1924
+ }
1925
+ function stealthMetaAddressToHex(metaAddress) {
1926
+ return "0x" + bytesToHex(metaAddress);
1927
+ }
1928
+ function parseStealthMetaAddress(metaHex) {
1929
+ const raw = typeof metaHex === "string" && metaHex.startsWith("0x") ? metaHex.slice(2) : metaHex;
1930
+ const bytes = hexToBytes(raw);
1931
+ if (bytes.length < 66) {
1932
+ throw new Error("Invalid stealth meta-address: expected 66 bytes");
1933
+ }
1934
+ return { viewPubKey: bytes.slice(0, 33), spendPubKey: bytes.slice(33, 66) };
1935
+ }
1936
+ function sharedSecretFromScalarAndPoint(privScalar, pointBytes) {
1937
+ const P = CURVE.ProjectivePoint.fromHex(pointBytes);
1938
+ const scalar = bytesToBigInt(privScalar) % CURVE.CURVE.n;
1939
+ if (scalar === 0n) throw new Error("Invalid scalar");
1940
+ return P.multiply(scalar).toRawBytes(true);
1941
+ }
1942
+ function hashSharedSecret(sharedSecret) {
1943
+ const sH = keccak_256(sharedSecret);
1944
+ return { sH, viewTag: sH[0] };
1945
+ }
1946
+ function stealthPointAndAddress(spendPubKey, sH) {
1947
+ const n = CURVE.CURVE.n;
1948
+ const sHMod = bytesToBigInt(sH) % n;
1949
+ if (sHMod === 0n) throw new Error("Invalid scalar from hash");
1950
+ const S_h = CURVE.ProjectivePoint.BASE.multiply(sHMod);
1951
+ const P_spend = CURVE.ProjectivePoint.fromHex(spendPubKey);
1952
+ const P_stealth = P_spend.add(S_h);
1953
+ const uncompressed = P_stealth.toRawBytes(false);
1954
+ const hash = keccak_256(uncompressed.slice(1));
1955
+ const addr = "0x" + bytesToHex(hash.slice(12));
1956
+ return { stealthAddress: addr, stealthPubKeyUncompressed: uncompressed };
1957
+ }
1958
+ function computeStealthAddressAndViewTag(recipientMetaAddressHex) {
1959
+ const { viewPubKey, spendPubKey } = parseStealthMetaAddress(
1960
+ recipientMetaAddressHex
1961
+ );
1962
+ const ephemeralPriv = CURVE.utils.randomPrivateKey();
1963
+ const ephemeralPubKey = CURVE.getPublicKey(ephemeralPriv, true);
1964
+ const shared = sharedSecretFromScalarAndPoint(ephemeralPriv, viewPubKey);
1965
+ const { sH, viewTag } = hashSharedSecret(shared);
1966
+ const { stealthAddress, stealthPubKeyUncompressed } = stealthPointAndAddress(
1967
+ spendPubKey,
1968
+ sH
1969
+ );
1970
+ const stealthStellarAddress = deriveStealthStellarAddress(
1971
+ stealthPubKeyUncompressed
1972
+ );
1973
+ return {
1974
+ ephemeralPriv,
1975
+ ephemeralPubKey,
1976
+ stealthAddress,
1977
+ stealthStellarAddress,
1978
+ viewTag,
1979
+ metadata: new Uint8Array([viewTag])
1980
+ };
1981
+ }
1982
+ function buildGhostAnnouncementPayload(recipientMetaAddressHex, ephemeralPrivKeyHex) {
1983
+ const { viewPubKey, spendPubKey } = parseStealthMetaAddress(
1984
+ recipientMetaAddressHex
1985
+ );
1986
+ const h = ephemeralPrivKeyHex.startsWith("0x") ? ephemeralPrivKeyHex.slice(2) : ephemeralPrivKeyHex;
1987
+ const ephemeralPriv = hexToBytes(h);
1988
+ if (ephemeralPriv.length !== 32) {
1989
+ throw new Error("Ephemeral private key must be 32 bytes.");
1990
+ }
1991
+ const ephemeralPubKey = CURVE.getPublicKey(ephemeralPriv, true);
1992
+ const shared = sharedSecretFromScalarAndPoint(ephemeralPriv, viewPubKey);
1993
+ const { sH, viewTag } = hashSharedSecret(shared);
1994
+ const { stealthAddress } = stealthPointAndAddress(spendPubKey, sH);
1995
+ return {
1996
+ stealthAddress,
1997
+ ephemeralPubKey,
1998
+ metadata: new Uint8Array([viewTag]),
1999
+ viewTag
2000
+ };
2001
+ }
2002
+ function recipientSharedSecretHash(viewingKey, ephemeralPubKey) {
2003
+ const shared = sharedSecretFromScalarAndPoint(viewingKey, ephemeralPubKey);
2004
+ return hashSharedSecret(shared);
2005
+ }
2006
+ function checkViewTagMatch(opts) {
2007
+ return recipientSharedSecretHash(opts.viewingKey, opts.ephemeralPubKey).viewTag === opts.viewTag;
2008
+ }
2009
+ function reconstructStealthPrivateKey(opts) {
2010
+ const n = CURVE.CURVE.n;
2011
+ const { sH } = recipientSharedSecretHash(opts.viewingKey, opts.ephemeralPubKey);
2012
+ const sHMod = bytesToBigInt(sH) % n;
2013
+ const spend = bytesToBigInt(opts.spendingKey) % n;
2014
+ const stealth = (spend + sHMod) % n;
2015
+ if (stealth === 0n) throw new Error("Reconstructed stealth key is zero");
2016
+ return bigIntToBytes32(stealth);
2017
+ }
2018
+ var ANNOUNCER_SALT = "opaque-announcer-v1";
2019
+ function deriveAnnouncerEphemeralKey(metaAddressHex) {
2020
+ const raw = typeof metaAddressHex === "string" && metaAddressHex.startsWith("0x") ? metaAddressHex.slice(2) : metaAddressHex;
2021
+ const seed = new TextEncoder().encode(raw + ANNOUNCER_SALT);
2022
+ const okm = hkdf(sha256, seed, void 0, "opaque-announcer-ephemeral", 32);
2023
+ const n = CURVE.CURVE.n;
2024
+ let scalar = bytesToBigInt(okm) % n;
2025
+ if (scalar === 0n) scalar = 1n;
2026
+ return bigIntToBytes32(scalar);
2027
+ }
2028
+ function deriveStealthStellarKeypair(stealthPubKeyUncompressed) {
2029
+ const domain = new TextEncoder().encode("opaque-stellar-stealth-v1");
2030
+ const input = new Uint8Array(domain.length + stealthPubKeyUncompressed.length);
2031
+ input.set(domain, 0);
2032
+ input.set(stealthPubKeyUncompressed, domain.length);
2033
+ const seed = sha256(input);
2034
+ return Keypair.fromRawEd25519Seed(Buffer.from(seed.slice(0, 32)));
2035
+ }
2036
+ function deriveStealthStellarAddress(stealthPubKeyUncompressed) {
2037
+ return deriveStealthStellarKeypair(stealthPubKeyUncompressed).publicKey();
2038
+ }
2039
+ function stealthIdFromPrivateKey(stealthPrivKey) {
2040
+ const uncompressed = CURVE.getPublicKey(stealthPrivKey, false);
2041
+ const hash = keccak_256(uncompressed.slice(1));
2042
+ return "0x" + bytesToHex(hash.slice(12));
2043
+ }
2044
+ function deriveStealthStellarAddressFromStealthPrivKey(stealthPrivKey) {
2045
+ return deriveStealthStellarAddress(CURVE.getPublicKey(stealthPrivKey, false));
2046
+ }
2047
+ function deriveStealthStellarKeypairFromStealthPrivKey(stealthPrivKey) {
2048
+ return deriveStealthStellarKeypair(CURVE.getPublicKey(stealthPrivKey, false));
2049
+ }
2050
+
2051
+ // src/crypto/scan.ts
2052
+ function scanAnnouncements(opts) {
2053
+ const matches = [];
2054
+ for (const announcement of opts.announcements) {
2055
+ if (!checkViewTagMatch({
2056
+ viewingKey: opts.viewingKey,
2057
+ ephemeralPubKey: announcement.ephemeralPubKey,
2058
+ viewTag: announcement.viewTag
2059
+ })) {
2060
+ continue;
2061
+ }
2062
+ const stealthPrivKey = reconstructStealthPrivateKey({
2063
+ viewingKey: opts.viewingKey,
2064
+ spendingKey: opts.spendingKey,
2065
+ ephemeralPubKey: announcement.ephemeralPubKey
2066
+ });
2067
+ if (stealthIdFromPrivateKey(stealthPrivKey).toLowerCase() !== announcement.stealthAddress.toLowerCase()) {
2068
+ continue;
2069
+ }
2070
+ matches.push({
2071
+ announcement,
2072
+ stealthPrivKey,
2073
+ stealthStellarAddress: deriveStealthStellarAddressFromStealthPrivKey(stealthPrivKey)
2074
+ });
2075
+ }
2076
+ return matches;
2077
+ }
2078
+ var POOL_TREE_DEPTH = 20;
2079
+ var BN254_R = 21888242871839275222246405745257275088548364400416034343698204186575808495617n;
2080
+ var _poseidon = null;
2081
+ async function getPoseidon() {
2082
+ if (!_poseidon) {
2083
+ if (typeof globalThis !== "undefined" && !("Buffer" in globalThis)) {
2084
+ const bufferPkg = await Promise.resolve().then(() => __toESM(require_buffer()));
2085
+ globalThis.Buffer = bufferPkg.Buffer;
2086
+ }
2087
+ _poseidon = await buildPoseidon();
2088
+ }
2089
+ return _poseidon;
2090
+ }
2091
+ function hashFields(poseidon, inputs) {
2092
+ return poseidon.F.toObject(poseidon(inputs));
2093
+ }
2094
+ function randomFieldElement() {
2095
+ const bytes = new Uint8Array(31);
2096
+ crypto.getRandomValues(bytes);
2097
+ let v = 0n;
2098
+ for (const b of bytes) v = (v << 8n) + BigInt(b);
2099
+ return (v % BN254_R).toString();
2100
+ }
2101
+ async function deriveDeposit(opts) {
2102
+ const poseidon = await getPoseidon();
2103
+ const h = (xs) => hashFields(poseidon, xs);
2104
+ const label = h([BigInt(opts.scope), BigInt(opts.leafIndex)]);
2105
+ const precommitment = h([opts.nullifier, opts.secret]);
2106
+ const commitment = h([opts.value, label, precommitment]);
2107
+ const nullifierHash = h([opts.nullifier]);
2108
+ return { label, precommitment, commitment, nullifierHash };
2109
+ }
2110
+ function newNoteSecrets() {
2111
+ return { nullifier: randomFieldElement(), secret: randomFieldElement() };
2112
+ }
2113
+ function unspentTotal(notes) {
2114
+ return notes.filter((n) => !n.spent).reduce((sum, n) => sum + BigInt(n.value), 0n);
2115
+ }
2116
+ var MAX_FIELDS = 16;
2117
+ var MAX_FIELD_NAME_LEN = 32;
2118
+ var MAX_STRING_VALUE_LEN = 128;
2119
+ var MAX_ATTESTATION_DATA_LEN = 512;
2120
+ var FIELD_TYPE_IDS = {
2121
+ bool: 0,
2122
+ u8: 1,
2123
+ u16: 2,
2124
+ u32: 3,
2125
+ u64: 4,
2126
+ string: 5,
2127
+ pubkey: 6
2128
+ };
2129
+ var SchemaParseError = class extends Error {
2130
+ constructor(message) {
2131
+ super(message);
2132
+ this.name = "SchemaParseError";
2133
+ }
2134
+ };
2135
+ var AttestationDataError = class extends Error {
2136
+ constructor(message) {
2137
+ super(message);
2138
+ this.name = "AttestationDataError";
2139
+ }
2140
+ };
2141
+ function isValidFieldName(name) {
2142
+ if (!name || name.length > MAX_FIELD_NAME_LEN) return false;
2143
+ return /^[a-zA-Z_][a-zA-Z0-9_]*$/.test(name);
2144
+ }
2145
+ function parseFieldDefinitions(fieldDefs) {
2146
+ const trimmed = fieldDefs.trim();
2147
+ if (!trimmed) throw new SchemaParseError("Field definitions cannot be empty");
2148
+ const fields = [];
2149
+ for (const segment of trimmed.split(",")) {
2150
+ const seg = segment.trim();
2151
+ if (!seg) throw new SchemaParseError("Malformed field segment");
2152
+ const spaceIdx = seg.indexOf(" ");
2153
+ if (spaceIdx === -1) {
2154
+ throw new SchemaParseError(
2155
+ 'Expected "type name" format (legacy "name:type" is not supported)'
2156
+ );
2157
+ }
2158
+ const type = seg.slice(0, spaceIdx).trim();
2159
+ const name = seg.slice(spaceIdx + 1).trim();
2160
+ if (name.includes(" ") || !Object.hasOwn(FIELD_TYPE_IDS, type)) {
2161
+ throw new SchemaParseError(`Invalid field type: ${type}`);
2162
+ }
2163
+ if (!isValidFieldName(name)) {
2164
+ throw new SchemaParseError(`Invalid field name: ${name}`);
2165
+ }
2166
+ if (fields.some((f) => f.name === name)) {
2167
+ throw new SchemaParseError(`Duplicate field name: ${name}`);
2168
+ }
2169
+ fields.push({ id: String(fields.length), name, type });
2170
+ if (fields.length > MAX_FIELDS) throw new SchemaParseError("Too many fields");
2171
+ }
2172
+ const canonical = fieldDefsToCanonicalString(fields);
2173
+ if (canonical.length > 256) {
2174
+ throw new SchemaParseError("Field definitions too long");
2175
+ }
2176
+ return fields;
2177
+ }
2178
+ function fieldDefsToCanonicalString(fields) {
2179
+ return fields.filter((f) => f.name.trim()).map((f) => `${f.type} ${f.name.trim()}`).join(",");
2180
+ }
2181
+ function encodeCanonicalFieldDefs(fields) {
2182
+ const parts = [fields.length];
2183
+ for (const f of fields) {
2184
+ const nameBytes = new TextEncoder().encode(f.name);
2185
+ parts.push(FIELD_TYPE_IDS[f.type], nameBytes.length, ...nameBytes);
2186
+ }
2187
+ return new Uint8Array(parts);
2188
+ }
2189
+ function addressToAuthorityBytes(address) {
2190
+ return Uint8Array.from(StrKey.decodeEd25519PublicKey(address));
2191
+ }
2192
+ async function computeSchemaIdFromBytes(authorityBytes, name, fieldDefinitions, version = 1) {
2193
+ const fields = parseFieldDefinitions(fieldDefinitions);
2194
+ const canonical = encodeCanonicalFieldDefs(fields);
2195
+ const encoder = new TextEncoder();
2196
+ const nameBytes = encoder.encode(name);
2197
+ const versionBytes = new Uint8Array(4);
2198
+ new DataView(versionBytes.buffer).setUint32(0, version, false);
2199
+ const combined = new Uint8Array(
2200
+ authorityBytes.length + nameBytes.length + versionBytes.length + canonical.length
2201
+ );
2202
+ let off = 0;
2203
+ combined.set(authorityBytes, off);
2204
+ off += authorityBytes.length;
2205
+ combined.set(nameBytes, off);
2206
+ off += nameBytes.length;
2207
+ combined.set(versionBytes, off);
2208
+ off += versionBytes.length;
2209
+ combined.set(canonical, off);
2210
+ const hashBuffer = await crypto.subtle.digest("SHA-256", combined);
2211
+ return new Uint8Array(hashBuffer);
2212
+ }
2213
+ async function computeSchemaId(authority, name, fieldDefinitions, version = 1) {
2214
+ return computeSchemaIdFromBytes(
2215
+ addressToAuthorityBytes(authority),
2216
+ name,
2217
+ fieldDefinitions,
2218
+ version
2219
+ );
2220
+ }
2221
+ function parseBool(value) {
2222
+ const v = value.trim();
2223
+ if (v === "true" || v === "1") return true;
2224
+ if (v === "false" || v === "0" || v === "") return false;
2225
+ throw new AttestationDataError(`Invalid bool: ${value}`);
2226
+ }
2227
+ function parseUint(value, max) {
2228
+ const v = value.trim();
2229
+ if (!v) return 0n;
2230
+ if (!/^\d+$/.test(v)) throw new AttestationDataError(`Invalid integer: ${value}`);
2231
+ const n = BigInt(v);
2232
+ if (n < 0n || n > max) {
2233
+ throw new AttestationDataError(`Integer out of range: ${value}`);
2234
+ }
2235
+ return n;
2236
+ }
2237
+ function parsePubkeyHex(value) {
2238
+ const hex = value.trim().replace(/^0x/i, "");
2239
+ if (hex.length !== 64) throw new AttestationDataError("Invalid pubkey hex");
2240
+ const out = new Uint8Array(32);
2241
+ for (let i = 0; i < 32; i++) {
2242
+ out[i] = parseInt(hex.slice(i * 2, i * 2 + 2), 16);
2243
+ }
2244
+ return out;
2245
+ }
2246
+ function encodeAttestationData(fieldValues, fieldDefs) {
2247
+ const parts = [];
2248
+ for (const field of fieldDefs) {
2249
+ const value = fieldValues[field.name] ?? "";
2250
+ switch (field.type) {
2251
+ case "bool":
2252
+ parts.push(new Uint8Array([parseBool(value) ? 1 : 0]));
2253
+ break;
2254
+ case "u8":
2255
+ parts.push(new Uint8Array([Number(parseUint(value, 255n))]));
2256
+ break;
2257
+ case "u16": {
2258
+ const buf = new Uint8Array(2);
2259
+ new DataView(buf.buffer).setUint16(0, Number(parseUint(value, 65535n)), false);
2260
+ parts.push(buf);
2261
+ break;
2262
+ }
2263
+ case "u32": {
2264
+ const buf = new Uint8Array(4);
2265
+ new DataView(buf.buffer).setUint32(0, Number(parseUint(value, 4294967295n)), false);
2266
+ parts.push(buf);
2267
+ break;
2268
+ }
2269
+ case "u64": {
2270
+ const buf = new Uint8Array(8);
2271
+ new DataView(buf.buffer).setBigUint64(
2272
+ 0,
2273
+ parseUint(value, 18446744073709551615n),
2274
+ false
2275
+ );
2276
+ parts.push(buf);
2277
+ break;
2278
+ }
2279
+ case "string": {
2280
+ const bytes = new TextEncoder().encode(value);
2281
+ if (bytes.length > MAX_STRING_VALUE_LEN) {
2282
+ throw new AttestationDataError("String value too long");
2283
+ }
2284
+ const len = new Uint8Array(2);
2285
+ new DataView(len.buffer).setUint16(0, bytes.length, false);
2286
+ parts.push(len, bytes);
2287
+ break;
2288
+ }
2289
+ case "pubkey":
2290
+ parts.push(parsePubkeyHex(value));
2291
+ break;
2292
+ default:
2293
+ throw new AttestationDataError(`Unsupported type: ${field.type}`);
2294
+ }
2295
+ }
2296
+ const total = parts.reduce((a, p) => a + p.length, 0);
2297
+ if (total > MAX_ATTESTATION_DATA_LEN) {
2298
+ throw new AttestationDataError("Attestation data too large");
2299
+ }
2300
+ const out = new Uint8Array(total);
2301
+ let offset = 0;
2302
+ for (const p of parts) {
2303
+ out.set(p, offset);
2304
+ offset += p.length;
2305
+ }
2306
+ return out;
2307
+ }
2308
+ function decodeAttestationData(data, fieldDefs) {
2309
+ const dec = new TextDecoder();
2310
+ const result = {};
2311
+ let offset = 0;
2312
+ for (const field of fieldDefs) {
2313
+ switch (field.type) {
2314
+ case "bool":
2315
+ if (offset >= data.length) throw new AttestationDataError("Truncated bool");
2316
+ result[field.name] = data[offset] === 1 ? "true" : "false";
2317
+ offset += 1;
2318
+ break;
2319
+ case "u8":
2320
+ if (offset >= data.length) throw new AttestationDataError("Truncated u8");
2321
+ result[field.name] = String(data[offset]);
2322
+ offset += 1;
2323
+ break;
2324
+ case "u16": {
2325
+ if (offset + 2 > data.length) throw new AttestationDataError("Truncated u16");
2326
+ result[field.name] = String(
2327
+ new DataView(data.buffer, data.byteOffset + offset, 2).getUint16(0, false)
2328
+ );
2329
+ offset += 2;
2330
+ break;
2331
+ }
2332
+ case "u32": {
2333
+ if (offset + 4 > data.length) throw new AttestationDataError("Truncated u32");
2334
+ result[field.name] = String(
2335
+ new DataView(data.buffer, data.byteOffset + offset, 4).getUint32(0, false)
2336
+ );
2337
+ offset += 4;
2338
+ break;
2339
+ }
2340
+ case "u64": {
2341
+ if (offset + 8 > data.length) throw new AttestationDataError("Truncated u64");
2342
+ result[field.name] = String(
2343
+ new DataView(data.buffer, data.byteOffset + offset, 8).getBigUint64(0, false)
2344
+ );
2345
+ offset += 8;
2346
+ break;
2347
+ }
2348
+ case "string": {
2349
+ if (offset + 2 > data.length) {
2350
+ throw new AttestationDataError("Truncated string length");
2351
+ }
2352
+ const len = new DataView(data.buffer, data.byteOffset + offset, 2).getUint16(0, false);
2353
+ offset += 2;
2354
+ if (offset + len > data.length) throw new AttestationDataError("Truncated string");
2355
+ result[field.name] = dec.decode(data.slice(offset, offset + len));
2356
+ offset += len;
2357
+ break;
2358
+ }
2359
+ case "pubkey": {
2360
+ if (offset + 32 > data.length) throw new AttestationDataError("Truncated pubkey");
2361
+ const slice = data.slice(offset, offset + 32);
2362
+ result[field.name] = "0x" + Array.from(slice).map((b) => b.toString(16).padStart(2, "0")).join("");
2363
+ offset += 32;
2364
+ break;
2365
+ }
2366
+ default:
2367
+ throw new AttestationDataError(`Unsupported type: ${field.type}`);
2368
+ }
2369
+ }
2370
+ if (offset !== data.length) {
2371
+ throw new AttestationDataError("Trailing bytes in attestation data");
2372
+ }
2373
+ return result;
2374
+ }
2375
+
2376
+ // src/crypto/backup.ts
2377
+ var PBKDF2_ITERATIONS = 6e5;
2378
+ var SALT_BYTES = 16;
2379
+ var IV_BYTES = 12;
2380
+ function toArrayBuffer(bytes) {
2381
+ const copy = new Uint8Array(bytes.byteLength);
2382
+ copy.set(bytes);
2383
+ return copy.buffer;
2384
+ }
2385
+ function bytesToBase64(bytes) {
2386
+ let binary = "";
2387
+ for (let i = 0; i < bytes.length; i += 1) binary += String.fromCharCode(bytes[i] ?? 0);
2388
+ return btoa(binary);
2389
+ }
2390
+ function base64ToBytes(base64) {
2391
+ const binary = atob(base64);
2392
+ const out = new Uint8Array(binary.length);
2393
+ for (let i = 0; i < binary.length; i += 1) out[i] = binary.charCodeAt(i);
2394
+ return out;
2395
+ }
2396
+ async function deriveKeyFromPassword(password, salt) {
2397
+ const encoder = new TextEncoder();
2398
+ const passwordKey = await crypto.subtle.importKey(
2399
+ "raw",
2400
+ toArrayBuffer(encoder.encode(password)),
2401
+ "PBKDF2",
2402
+ false,
2403
+ ["deriveKey"]
2404
+ );
2405
+ return crypto.subtle.deriveKey(
2406
+ {
2407
+ name: "PBKDF2",
2408
+ salt: toArrayBuffer(salt),
2409
+ iterations: PBKDF2_ITERATIONS,
2410
+ hash: "SHA-256"
2411
+ },
2412
+ passwordKey,
2413
+ { name: "AES-GCM", length: 256 },
2414
+ false,
2415
+ ["encrypt", "decrypt"]
2416
+ );
2417
+ }
2418
+ async function encryptField(plaintext, key) {
2419
+ const iv = crypto.getRandomValues(new Uint8Array(IV_BYTES));
2420
+ const encoded = new TextEncoder().encode(plaintext);
2421
+ const ciphertext = new Uint8Array(
2422
+ await crypto.subtle.encrypt(
2423
+ { name: "AES-GCM", iv: toArrayBuffer(iv) },
2424
+ key,
2425
+ encoded
2426
+ )
2427
+ );
2428
+ return `${bytesToBase64(iv)}:${bytesToBase64(ciphertext)}`;
2429
+ }
2430
+ async function decryptField(packed, key) {
2431
+ const [ivB64, ctB64] = packed.split(":");
2432
+ if (!ivB64 || !ctB64) throw new Error("Invalid encrypted field format");
2433
+ const iv = base64ToBytes(ivB64);
2434
+ const ciphertext = base64ToBytes(ctB64);
2435
+ const decrypted = await crypto.subtle.decrypt(
2436
+ { name: "AES-GCM", iv: toArrayBuffer(iv) },
2437
+ key,
2438
+ toArrayBuffer(ciphertext)
2439
+ );
2440
+ return new TextDecoder().decode(new Uint8Array(decrypted));
2441
+ }
2442
+ async function encryptGhostEntries(entries, password) {
2443
+ const salt = crypto.getRandomValues(new Uint8Array(SALT_BYTES));
2444
+ const key = await deriveKeyFromPassword(password, salt);
2445
+ const encrypted = [];
2446
+ for (const entry of entries) {
2447
+ encrypted.push({
2448
+ cluster: entry.cluster,
2449
+ stealthAddress: entry.stealthAddress,
2450
+ ephemeralPrivKeyEncrypted: entry.ephemeralPrivKeyHex ? await encryptField(entry.ephemeralPrivKeyHex, key) : void 0,
2451
+ createdAt: entry.createdAt
2452
+ });
2453
+ }
2454
+ return { version: 1, salt: bytesToBase64(salt), entries: encrypted };
2455
+ }
2456
+ async function decryptGhostEntries(payload, password) {
2457
+ if (payload.version !== 1) {
2458
+ throw new Error("Unsupported encrypted payload version");
2459
+ }
2460
+ const salt = base64ToBytes(payload.salt);
2461
+ const key = await deriveKeyFromPassword(password, salt);
2462
+ const decrypted = [];
2463
+ for (const entry of payload.entries) {
2464
+ decrypted.push({
2465
+ cluster: entry.cluster,
2466
+ stealthAddress: entry.stealthAddress,
2467
+ ephemeralPrivKeyHex: entry.ephemeralPrivKeyEncrypted ? await decryptField(entry.ephemeralPrivKeyEncrypted, key) : void 0,
2468
+ createdAt: entry.createdAt
2469
+ });
2470
+ }
2471
+ return decrypted;
2472
+ }
2473
+ async function exportEncryptedBackup(entries, password) {
2474
+ return JSON.stringify(await encryptGhostEntries(entries, password));
2475
+ }
2476
+ async function importEncryptedBackup(backupJson, password) {
2477
+ const payload = JSON.parse(backupJson);
2478
+ return decryptGhostEntries(payload, password);
2479
+ }
2480
+
2481
+ // src/crypto/payment-link.ts
2482
+ function isValidMetaAddress(metaAddress) {
2483
+ if (metaAddress.length !== 134) return false;
2484
+ if (!metaAddress.startsWith("0x")) return false;
2485
+ return /^[0-9a-fA-F]{132}$/.test(metaAddress.slice(2));
2486
+ }
2487
+ function isValidNetwork(network) {
2488
+ return ["testnet", "mainnet", "futurenet", "local"].includes(network);
2489
+ }
2490
+ function isValidStellarPublicKey(publicKey) {
2491
+ if (publicKey.length !== 56) return false;
2492
+ if (!publicKey.startsWith("G")) return false;
2493
+ return /^[A-Z2-7]{55}$/.test(publicKey);
2494
+ }
2495
+ function isValidAssetCode(assetCode) {
2496
+ if (assetCode.length < 1 || assetCode.length > 12) return false;
2497
+ return /^[a-zA-Z0-9]+$/.test(assetCode);
2498
+ }
2499
+ function isValidAmount(amount) {
2500
+ if (!amount) return false;
2501
+ const num = parseFloat(amount);
2502
+ if (isNaN(num) || num <= 0) return false;
2503
+ return /^[0-9]+(\.[0-9]+)?$/.test(amount);
2504
+ }
2505
+ function isValidIso8601(timestamp) {
2506
+ try {
2507
+ return !isNaN(new Date(timestamp).getTime());
2508
+ } catch {
2509
+ return false;
2510
+ }
2511
+ }
2512
+ function isValidUrl(url) {
2513
+ try {
2514
+ return new URL(url).protocol === "https:";
2515
+ } catch {
2516
+ return false;
2517
+ }
2518
+ }
2519
+ function encodePaymentLink(link) {
2520
+ if (!isValidMetaAddress(link.metaAddress)) {
2521
+ throw new Error("Invalid meta-address format");
2522
+ }
2523
+ if (!isValidNetwork(link.network)) {
2524
+ throw new Error("Invalid network identifier");
2525
+ }
2526
+ const uri = `opaque://v${link.version}/${link.network}/${link.metaAddress}`;
2527
+ const params = new URLSearchParams();
2528
+ if (link.params.amount) {
2529
+ if (!isValidAmount(link.params.amount)) throw new Error("Invalid amount format");
2530
+ params.set("amount", link.params.amount);
2531
+ }
2532
+ if (link.params.asset) {
2533
+ if (!isValidAssetCode(link.params.asset)) throw new Error("Invalid asset code");
2534
+ params.set("asset", link.params.asset);
2535
+ }
2536
+ if (link.params.issuer) {
2537
+ if (!isValidStellarPublicKey(link.params.issuer)) {
2538
+ throw new Error("Invalid issuer address");
2539
+ }
2540
+ params.set("issuer", link.params.issuer);
2541
+ }
2542
+ if (link.params.memo) params.set("memo", link.params.memo);
2543
+ if (link.params.sep) params.set("sep", link.params.sep);
2544
+ if (link.params.callback) {
2545
+ if (!isValidUrl(link.params.callback)) throw new Error("Invalid callback URL");
2546
+ params.set("callback", link.params.callback);
2547
+ }
2548
+ if (link.params.label) params.set("label", link.params.label);
2549
+ if (link.params.expires) {
2550
+ if (!isValidIso8601(link.params.expires)) {
2551
+ throw new Error("Invalid expiration timestamp");
2552
+ }
2553
+ params.set("expires", link.params.expires);
2554
+ }
2555
+ const queryString = params.toString();
2556
+ return queryString ? `${uri}?${queryString}` : uri;
2557
+ }
2558
+ function decodePaymentLink(linkString, configuredNetwork) {
2559
+ try {
2560
+ const url = new URL(linkString);
2561
+ if (url.protocol !== "opaque:") {
2562
+ return { error: { type: "INVALID_FORMAT", message: "Invalid protocol: must be opaque://" } };
2563
+ }
2564
+ const pathParts = [
2565
+ url.hostname,
2566
+ ...url.pathname.split("/").filter(Boolean)
2567
+ ].filter(Boolean);
2568
+ if (pathParts.length < 3) {
2569
+ return {
2570
+ error: {
2571
+ type: "INVALID_FORMAT",
2572
+ message: "Invalid path format: expected opaque://v{version}/{network}/{meta-address}"
2573
+ }
2574
+ };
2575
+ }
2576
+ const versionMatch = pathParts[0].match(/^v(\d+)$/);
2577
+ if (!versionMatch) {
2578
+ return { error: { type: "INVALID_FORMAT", message: "Invalid version format: expected v{number}" } };
2579
+ }
2580
+ const version = parseInt(versionMatch[1], 10);
2581
+ if (version !== 1) {
2582
+ return {
2583
+ error: {
2584
+ type: "UNSUPPORTED_VERSION",
2585
+ message: `Unsupported version: v${version}. Only v1 is currently supported.`
2586
+ }
2587
+ };
2588
+ }
2589
+ const network = pathParts[1];
2590
+ if (!isValidNetwork(network)) {
2591
+ return {
2592
+ error: {
2593
+ type: "INVALID_FORMAT",
2594
+ message: `Invalid network: ${network}. Must be one of: testnet, mainnet, futurenet, local`
2595
+ }
2596
+ };
2597
+ }
2598
+ if (configuredNetwork && network !== configuredNetwork) {
2599
+ return {
2600
+ error: {
2601
+ type: "NETWORK_MISMATCH",
2602
+ message: `Network mismatch: link is for ${network}, but app is configured for ${configuredNetwork}`,
2603
+ details: { linkNetwork: network, configuredNetwork }
2604
+ }
2605
+ };
2606
+ }
2607
+ const metaAddress = pathParts[2];
2608
+ if (!isValidMetaAddress(metaAddress)) {
2609
+ return {
2610
+ error: {
2611
+ type: "INVALID_META_ADDRESS",
2612
+ message: `Invalid meta-address format: ${metaAddress}. Expected 0x + 132 hex chars.`
2613
+ }
2614
+ };
2615
+ }
2616
+ const params = {};
2617
+ const searchParams = url.searchParams;
2618
+ if (searchParams.has("amount")) {
2619
+ const amount = searchParams.get("amount");
2620
+ if (!isValidAmount(amount)) {
2621
+ return { error: { type: "INVALID_PARAMETER", message: `Invalid amount parameter: ${amount}`, details: { parameter: "amount", value: amount } } };
2622
+ }
2623
+ params.amount = amount;
2624
+ }
2625
+ if (searchParams.has("asset")) {
2626
+ const asset = searchParams.get("asset");
2627
+ if (!isValidAssetCode(asset)) {
2628
+ return { error: { type: "INVALID_PARAMETER", message: `Invalid asset code: ${asset}`, details: { parameter: "asset", value: asset } } };
2629
+ }
2630
+ params.asset = asset;
2631
+ }
2632
+ if (searchParams.has("issuer")) {
2633
+ const issuer = searchParams.get("issuer");
2634
+ if (!isValidStellarPublicKey(issuer)) {
2635
+ return { error: { type: "INVALID_PARAMETER", message: `Invalid issuer address: ${issuer}`, details: { parameter: "issuer", value: issuer } } };
2636
+ }
2637
+ params.issuer = issuer;
2638
+ }
2639
+ if (searchParams.has("memo")) params.memo = searchParams.get("memo");
2640
+ if (searchParams.has("sep")) params.sep = searchParams.get("sep");
2641
+ if (searchParams.has("callback")) {
2642
+ const callback = searchParams.get("callback");
2643
+ if (!isValidUrl(callback)) {
2644
+ return { error: { type: "INVALID_PARAMETER", message: `Invalid callback URL: ${callback}`, details: { parameter: "callback", value: callback } } };
2645
+ }
2646
+ params.callback = callback;
2647
+ }
2648
+ if (searchParams.has("label")) params.label = searchParams.get("label");
2649
+ if (searchParams.has("expires")) {
2650
+ const expires = searchParams.get("expires");
2651
+ if (!isValidIso8601(expires)) {
2652
+ return { error: { type: "INVALID_PARAMETER", message: `Invalid expiration timestamp: ${expires}`, details: { parameter: "expires", value: expires } } };
2653
+ }
2654
+ params.expires = expires;
2655
+ }
2656
+ if (params.expires && new Date(params.expires) < /* @__PURE__ */ new Date()) {
2657
+ return { error: { type: "INVALID_PARAMETER", message: `Payment link has expired: ${params.expires}`, details: { parameter: "expires", value: params.expires } } };
2658
+ }
2659
+ return { link: { version, network, metaAddress, params } };
2660
+ } catch (error) {
2661
+ return {
2662
+ error: {
2663
+ type: "INVALID_FORMAT",
2664
+ message: `Failed to parse payment link: ${error instanceof Error ? error.message : String(error)}`,
2665
+ details: error
2666
+ }
2667
+ };
2668
+ }
2669
+ }
2670
+ function createPaymentLink(metaAddress, network, params = {}) {
2671
+ return encodePaymentLink({ version: 1, network, metaAddress, params });
2672
+ }
2673
+ function isOpaquePaymentLink(linkString) {
2674
+ try {
2675
+ return "link" in decodePaymentLink(linkString);
2676
+ } catch {
2677
+ return false;
2678
+ }
2679
+ }
2680
+ function convertLegacyLink(legacyLink, network, params = {}) {
2681
+ try {
2682
+ const url = new URL(legacyLink);
2683
+ const pathParts = url.pathname.split("/").filter(Boolean);
2684
+ const metaAddress = pathParts[pathParts.length - 1];
2685
+ if (!isValidMetaAddress(metaAddress)) return null;
2686
+ return createPaymentLink(metaAddress, network, params);
2687
+ } catch {
2688
+ return null;
2689
+ }
2690
+ }
2691
+
2692
+ // src/crypto/memo.ts
2693
+ var CUSTODIAL_ADDRESSES = Object.freeze({
2694
+ GA5XIGA5C7QTPTWXQHY6MCJRMTRZDOSHR6EFIBNDQTCQHG262N4GGKTM: {
2695
+ name: "Kraken",
2696
+ recommendedMemoType: "id"
2697
+ },
2698
+ GCGNWKCJ3KHRLPM3TMQN7IPVUMRPMYIPGKDPELDPRBMVUPLNZAJDK4VG: {
2699
+ name: "Binance",
2700
+ recommendedMemoType: "text"
2701
+ },
2702
+ GBJ65CCWNPGFNXIVRZMNQSGNXHJYM3O3HFK2CIHWXVKAFEWZNUQOH53I: {
2703
+ name: "Coinbase",
2704
+ recommendedMemoType: "text"
2705
+ },
2706
+ GDXBP3R6N62YR4MTEGEHDIJWQ6BIRYNG6UCV4XQEFKQGGYS7QUDXMJSX: {
2707
+ name: "KuCoin",
2708
+ recommendedMemoType: "text"
2709
+ }
2710
+ });
2711
+ function memoRiskFor(destination) {
2712
+ if (!destination) return { isKnownCustodian: false };
2713
+ const entry = CUSTODIAL_ADDRESSES[destination.trim()];
2714
+ if (!entry) return { isKnownCustodian: false };
2715
+ return {
2716
+ isKnownCustodian: true,
2717
+ custodianName: entry.name,
2718
+ recommendedMemoType: entry.recommendedMemoType
2719
+ };
2720
+ }
2721
+ function validateMemo(memoType, memo) {
2722
+ const value = (memo ?? "").trim();
2723
+ if (memoType === "none") {
2724
+ if (value.length > 0) {
2725
+ return { ok: false, error: "Memo must be empty when memo type is 'none'." };
2726
+ }
2727
+ return { ok: true };
2728
+ }
2729
+ if (value.length === 0) {
2730
+ return { ok: false, error: "Memo is required for this memo type." };
2731
+ }
2732
+ switch (memoType) {
2733
+ case "text": {
2734
+ const bytes = new TextEncoder().encode(value).byteLength;
2735
+ if (bytes > 28) {
2736
+ return { ok: false, error: "Text memo must be 28 UTF-8 bytes or fewer." };
2737
+ }
2738
+ return { ok: true };
2739
+ }
2740
+ case "id": {
2741
+ if (!/^\d+$/.test(value)) {
2742
+ return { ok: false, error: "ID memo must be a non-negative integer." };
2743
+ }
2744
+ try {
2745
+ const n = BigInt(value);
2746
+ if (n < 0n || n > 0xffffffffffffffffn) {
2747
+ return { ok: false, error: "ID memo must fit in an unsigned 64-bit integer." };
2748
+ }
2749
+ } catch {
2750
+ return { ok: false, error: "ID memo must be a non-negative integer." };
2751
+ }
2752
+ return { ok: true };
2753
+ }
2754
+ case "hash":
2755
+ case "return": {
2756
+ if (!/^[0-9a-fA-F]{64}$/.test(value)) {
2757
+ return { ok: false, error: "Hash/return memo must be 64 hexadecimal characters." };
2758
+ }
2759
+ return { ok: true };
2760
+ }
2761
+ }
2762
+ }
2763
+ function memoWarningCopy(risk, memo) {
2764
+ if (!risk.isKnownCustodian) return null;
2765
+ if (memo && memo.trim().length > 0) return null;
2766
+ return `Destination looks like ${risk.custodianName ?? "an exchange or custodian"}. Sending without a memo may result in lost funds.`;
2767
+ }
2768
+ /*! Bundled license information:
2769
+
2770
+ ieee754/index.js:
2771
+ (*! ieee754. BSD-3-Clause License. Feross Aboukhadijeh <https://feross.org/opensource> *)
2772
+
2773
+ buffer/index.js:
2774
+ (*!
2775
+ * The buffer module from node.js, for the browser.
2776
+ *
2777
+ * @author Feross Aboukhadijeh <https://feross.org>
2778
+ * @license MIT
2779
+ *)
2780
+ */
2781
+
2782
+ export { AttestationDataError, BN254_R, LEGACY_SETUP_MESSAGE, MAX_ATTESTATION_DATA_LEN, MAX_FIELDS, MAX_FIELD_NAME_LEN, MAX_STRING_VALUE_LEN, POOL_TREE_DEPTH, SchemaParseError, addressToAuthorityBytes, bigIntToBytes32, buildDomainSeparatedMessage, buildGhostAnnouncementPayload, bytesToBigInt, bytesToHex, checkViewTagMatch, computeSchemaId, computeSchemaIdFromBytes, computeStealthAddressAndViewTag, concatBytes, convertLegacyLink, createPaymentLink, decodeAttestationData, decodePaymentLink, decryptGhostEntries, deriveAnnouncerEphemeralKey, deriveDeposit, deriveKeysFromSignature, deriveStealthStellarAddress, deriveStealthStellarAddressFromStealthPrivKey, deriveStealthStellarKeypair, deriveStealthStellarKeypairFromStealthPrivKey, encodeAttestationData, encodeCanonicalFieldDefs, encodePaymentLink, encryptGhostEntries, exportEncryptedBackup, fieldDefsToCanonicalString, formatStroopsToXlm, formatXlm, getPoseidon, hashFields, hexToBytes, importEncryptedBackup, isOpaquePaymentLink, isValidAmount, isValidAssetCode, isValidIso8601, isValidMetaAddress, isValidNetwork, isValidStellarPublicKey, isValidUrl, keysToStealthMetaAddress, memoRiskFor, memoWarningCopy, newNoteSecrets, parseFieldDefinitions, parseHorizonBalanceToStroops, parseStealthMetaAddress, parseXlmToStroops, randomFieldElement, recipientSharedSecretHash, reconstructStealthPrivateKey, scanAnnouncements, stealthIdFromPrivateKey, stealthMetaAddressToHex, toHex32, unspentTotal, validateMemo };
2783
+ //# sourceMappingURL=index.js.map
2784
+ //# sourceMappingURL=index.js.map