@atproto/crypto 0.0.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (47) hide show
  1. package/README.md +3 -0
  2. package/build.js +22 -0
  3. package/dist/aes.d.ts +8 -0
  4. package/dist/const.d.ts +5 -0
  5. package/dist/did.d.ts +7 -0
  6. package/dist/index.d.ts +12 -0
  7. package/dist/index.js +3955 -0
  8. package/dist/index.js.map +7 -0
  9. package/dist/multibase.d.ts +1 -0
  10. package/dist/p256/encoding.d.ts +2 -0
  11. package/dist/p256/keypair.d.ts +19 -0
  12. package/dist/p256/operations.d.ts +4 -0
  13. package/dist/p256/plugin.d.ts +3 -0
  14. package/dist/plugins.d.ts +2 -0
  15. package/dist/random.d.ts +4 -0
  16. package/dist/secp256k1/encoding.d.ts +2 -0
  17. package/dist/secp256k1/keypair.d.ts +19 -0
  18. package/dist/secp256k1/operations.d.ts +1 -0
  19. package/dist/secp256k1/plugin.d.ts +3 -0
  20. package/dist/sha.d.ts +3 -0
  21. package/dist/verify.d.ts +1 -0
  22. package/jest.config.js +6 -0
  23. package/package.json +29 -0
  24. package/src/aes.ts +64 -0
  25. package/src/const.ts +6 -0
  26. package/src/did.ts +56 -0
  27. package/src/index.ts +15 -0
  28. package/src/multibase.ts +26 -0
  29. package/src/p256/encoding.ts +81 -0
  30. package/src/p256/keypair.ts +85 -0
  31. package/src/p256/operations.ts +64 -0
  32. package/src/p256/plugin.ts +13 -0
  33. package/src/plugins.ts +6 -0
  34. package/src/random.ts +19 -0
  35. package/src/secp256k1/encoding.ts +16 -0
  36. package/src/secp256k1/keypair.ts +65 -0
  37. package/src/secp256k1/operations.ts +16 -0
  38. package/src/secp256k1/plugin.ts +11 -0
  39. package/src/sha.ts +28 -0
  40. package/src/verify.ts +15 -0
  41. package/tests/did.test.ts +95 -0
  42. package/tests/export.test.ts +50 -0
  43. package/tests/key-compression.test.ts +69 -0
  44. package/tsconfig.build.json +4 -0
  45. package/tsconfig.build.tsbuildinfo +1 -0
  46. package/tsconfig.json +9 -0
  47. package/update-pkg.js +14 -0
package/dist/index.js ADDED
@@ -0,0 +1,3955 @@
1
+ "use strict";
2
+ var __create = Object.create;
3
+ var __defProp = Object.defineProperty;
4
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
5
+ var __getOwnPropNames = Object.getOwnPropertyNames;
6
+ var __getProtoOf = Object.getPrototypeOf;
7
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
8
+ var __commonJS = (cb, mod2) => function __require() {
9
+ return mod2 || (0, cb[__getOwnPropNames(cb)[0]])((mod2 = { exports: {} }).exports, mod2), mod2.exports;
10
+ };
11
+ var __export = (target, all) => {
12
+ for (var name2 in all)
13
+ __defProp(target, name2, { get: all[name2], enumerable: true });
14
+ };
15
+ var __copyProps = (to, from3, except, desc) => {
16
+ if (from3 && typeof from3 === "object" || typeof from3 === "function") {
17
+ for (let key of __getOwnPropNames(from3))
18
+ if (!__hasOwnProp.call(to, key) && key !== except)
19
+ __defProp(to, key, { get: () => from3[key], enumerable: !(desc = __getOwnPropDesc(from3, key)) || desc.enumerable });
20
+ }
21
+ return to;
22
+ };
23
+ var __toESM = (mod2, isNodeMode, target) => (target = mod2 != null ? __create(__getProtoOf(mod2)) : {}, __copyProps(
24
+ isNodeMode || !mod2 || !mod2.__esModule ? __defProp(target, "default", { value: mod2, enumerable: true }) : target,
25
+ mod2
26
+ ));
27
+ var __toCommonJS = (mod2) => __copyProps(__defProp({}, "__esModule", { value: true }), mod2);
28
+
29
+ // ../../node_modules/big-integer/BigInteger.js
30
+ var require_BigInteger = __commonJS({
31
+ "../../node_modules/big-integer/BigInteger.js"(exports, module2) {
32
+ var bigInt2 = function(undefined2) {
33
+ "use strict";
34
+ var BASE = 1e7, LOG_BASE = 7, MAX_INT = 9007199254740992, MAX_INT_ARR = smallToArray(MAX_INT), DEFAULT_ALPHABET = "0123456789abcdefghijklmnopqrstuvwxyz";
35
+ var supportsNativeBigInt = typeof BigInt === "function";
36
+ function Integer(v, radix, alphabet2, caseSensitive) {
37
+ if (typeof v === "undefined")
38
+ return Integer[0];
39
+ if (typeof radix !== "undefined")
40
+ return +radix === 10 && !alphabet2 ? parseValue(v) : parseBase(v, radix, alphabet2, caseSensitive);
41
+ return parseValue(v);
42
+ }
43
+ function BigInteger(value, sign2) {
44
+ this.value = value;
45
+ this.sign = sign2;
46
+ this.isSmall = false;
47
+ }
48
+ BigInteger.prototype = Object.create(Integer.prototype);
49
+ function SmallInteger(value) {
50
+ this.value = value;
51
+ this.sign = value < 0;
52
+ this.isSmall = true;
53
+ }
54
+ SmallInteger.prototype = Object.create(Integer.prototype);
55
+ function NativeBigInt(value) {
56
+ this.value = value;
57
+ }
58
+ NativeBigInt.prototype = Object.create(Integer.prototype);
59
+ function isPrecise(n) {
60
+ return -MAX_INT < n && n < MAX_INT;
61
+ }
62
+ function smallToArray(n) {
63
+ if (n < 1e7)
64
+ return [n];
65
+ if (n < 1e14)
66
+ return [n % 1e7, Math.floor(n / 1e7)];
67
+ return [n % 1e7, Math.floor(n / 1e7) % 1e7, Math.floor(n / 1e14)];
68
+ }
69
+ function arrayToSmall(arr) {
70
+ trim(arr);
71
+ var length2 = arr.length;
72
+ if (length2 < 4 && compareAbs(arr, MAX_INT_ARR) < 0) {
73
+ switch (length2) {
74
+ case 0:
75
+ return 0;
76
+ case 1:
77
+ return arr[0];
78
+ case 2:
79
+ return arr[0] + arr[1] * BASE;
80
+ default:
81
+ return arr[0] + (arr[1] + arr[2] * BASE) * BASE;
82
+ }
83
+ }
84
+ return arr;
85
+ }
86
+ function trim(v) {
87
+ var i2 = v.length;
88
+ while (v[--i2] === 0)
89
+ ;
90
+ v.length = i2 + 1;
91
+ }
92
+ function createArray(length2) {
93
+ var x = new Array(length2);
94
+ var i2 = -1;
95
+ while (++i2 < length2) {
96
+ x[i2] = 0;
97
+ }
98
+ return x;
99
+ }
100
+ function truncate(n) {
101
+ if (n > 0)
102
+ return Math.floor(n);
103
+ return Math.ceil(n);
104
+ }
105
+ function add(a, b) {
106
+ var l_a = a.length, l_b = b.length, r = new Array(l_a), carry = 0, base3 = BASE, sum, i2;
107
+ for (i2 = 0; i2 < l_b; i2++) {
108
+ sum = a[i2] + b[i2] + carry;
109
+ carry = sum >= base3 ? 1 : 0;
110
+ r[i2] = sum - carry * base3;
111
+ }
112
+ while (i2 < l_a) {
113
+ sum = a[i2] + carry;
114
+ carry = sum === base3 ? 1 : 0;
115
+ r[i2++] = sum - carry * base3;
116
+ }
117
+ if (carry > 0)
118
+ r.push(carry);
119
+ return r;
120
+ }
121
+ function addAny(a, b) {
122
+ if (a.length >= b.length)
123
+ return add(a, b);
124
+ return add(b, a);
125
+ }
126
+ function addSmall(a, carry) {
127
+ var l = a.length, r = new Array(l), base3 = BASE, sum, i2;
128
+ for (i2 = 0; i2 < l; i2++) {
129
+ sum = a[i2] - base3 + carry;
130
+ carry = Math.floor(sum / base3);
131
+ r[i2] = sum - carry * base3;
132
+ carry += 1;
133
+ }
134
+ while (carry > 0) {
135
+ r[i2++] = carry % base3;
136
+ carry = Math.floor(carry / base3);
137
+ }
138
+ return r;
139
+ }
140
+ BigInteger.prototype.add = function(v) {
141
+ var n = parseValue(v);
142
+ if (this.sign !== n.sign) {
143
+ return this.subtract(n.negate());
144
+ }
145
+ var a = this.value, b = n.value;
146
+ if (n.isSmall) {
147
+ return new BigInteger(addSmall(a, Math.abs(b)), this.sign);
148
+ }
149
+ return new BigInteger(addAny(a, b), this.sign);
150
+ };
151
+ BigInteger.prototype.plus = BigInteger.prototype.add;
152
+ SmallInteger.prototype.add = function(v) {
153
+ var n = parseValue(v);
154
+ var a = this.value;
155
+ if (a < 0 !== n.sign) {
156
+ return this.subtract(n.negate());
157
+ }
158
+ var b = n.value;
159
+ if (n.isSmall) {
160
+ if (isPrecise(a + b))
161
+ return new SmallInteger(a + b);
162
+ b = smallToArray(Math.abs(b));
163
+ }
164
+ return new BigInteger(addSmall(b, Math.abs(a)), a < 0);
165
+ };
166
+ SmallInteger.prototype.plus = SmallInteger.prototype.add;
167
+ NativeBigInt.prototype.add = function(v) {
168
+ return new NativeBigInt(this.value + parseValue(v).value);
169
+ };
170
+ NativeBigInt.prototype.plus = NativeBigInt.prototype.add;
171
+ function subtract(a, b) {
172
+ var a_l = a.length, b_l = b.length, r = new Array(a_l), borrow = 0, base3 = BASE, i2, difference;
173
+ for (i2 = 0; i2 < b_l; i2++) {
174
+ difference = a[i2] - borrow - b[i2];
175
+ if (difference < 0) {
176
+ difference += base3;
177
+ borrow = 1;
178
+ } else
179
+ borrow = 0;
180
+ r[i2] = difference;
181
+ }
182
+ for (i2 = b_l; i2 < a_l; i2++) {
183
+ difference = a[i2] - borrow;
184
+ if (difference < 0)
185
+ difference += base3;
186
+ else {
187
+ r[i2++] = difference;
188
+ break;
189
+ }
190
+ r[i2] = difference;
191
+ }
192
+ for (; i2 < a_l; i2++) {
193
+ r[i2] = a[i2];
194
+ }
195
+ trim(r);
196
+ return r;
197
+ }
198
+ function subtractAny(a, b, sign2) {
199
+ var value;
200
+ if (compareAbs(a, b) >= 0) {
201
+ value = subtract(a, b);
202
+ } else {
203
+ value = subtract(b, a);
204
+ sign2 = !sign2;
205
+ }
206
+ value = arrayToSmall(value);
207
+ if (typeof value === "number") {
208
+ if (sign2)
209
+ value = -value;
210
+ return new SmallInteger(value);
211
+ }
212
+ return new BigInteger(value, sign2);
213
+ }
214
+ function subtractSmall(a, b, sign2) {
215
+ var l = a.length, r = new Array(l), carry = -b, base3 = BASE, i2, difference;
216
+ for (i2 = 0; i2 < l; i2++) {
217
+ difference = a[i2] + carry;
218
+ carry = Math.floor(difference / base3);
219
+ difference %= base3;
220
+ r[i2] = difference < 0 ? difference + base3 : difference;
221
+ }
222
+ r = arrayToSmall(r);
223
+ if (typeof r === "number") {
224
+ if (sign2)
225
+ r = -r;
226
+ return new SmallInteger(r);
227
+ }
228
+ return new BigInteger(r, sign2);
229
+ }
230
+ BigInteger.prototype.subtract = function(v) {
231
+ var n = parseValue(v);
232
+ if (this.sign !== n.sign) {
233
+ return this.add(n.negate());
234
+ }
235
+ var a = this.value, b = n.value;
236
+ if (n.isSmall)
237
+ return subtractSmall(a, Math.abs(b), this.sign);
238
+ return subtractAny(a, b, this.sign);
239
+ };
240
+ BigInteger.prototype.minus = BigInteger.prototype.subtract;
241
+ SmallInteger.prototype.subtract = function(v) {
242
+ var n = parseValue(v);
243
+ var a = this.value;
244
+ if (a < 0 !== n.sign) {
245
+ return this.add(n.negate());
246
+ }
247
+ var b = n.value;
248
+ if (n.isSmall) {
249
+ return new SmallInteger(a - b);
250
+ }
251
+ return subtractSmall(b, Math.abs(a), a >= 0);
252
+ };
253
+ SmallInteger.prototype.minus = SmallInteger.prototype.subtract;
254
+ NativeBigInt.prototype.subtract = function(v) {
255
+ return new NativeBigInt(this.value - parseValue(v).value);
256
+ };
257
+ NativeBigInt.prototype.minus = NativeBigInt.prototype.subtract;
258
+ BigInteger.prototype.negate = function() {
259
+ return new BigInteger(this.value, !this.sign);
260
+ };
261
+ SmallInteger.prototype.negate = function() {
262
+ var sign2 = this.sign;
263
+ var small = new SmallInteger(-this.value);
264
+ small.sign = !sign2;
265
+ return small;
266
+ };
267
+ NativeBigInt.prototype.negate = function() {
268
+ return new NativeBigInt(-this.value);
269
+ };
270
+ BigInteger.prototype.abs = function() {
271
+ return new BigInteger(this.value, false);
272
+ };
273
+ SmallInteger.prototype.abs = function() {
274
+ return new SmallInteger(Math.abs(this.value));
275
+ };
276
+ NativeBigInt.prototype.abs = function() {
277
+ return new NativeBigInt(this.value >= 0 ? this.value : -this.value);
278
+ };
279
+ function multiplyLong(a, b) {
280
+ var a_l = a.length, b_l = b.length, l = a_l + b_l, r = createArray(l), base3 = BASE, product, carry, i2, a_i, b_j;
281
+ for (i2 = 0; i2 < a_l; ++i2) {
282
+ a_i = a[i2];
283
+ for (var j = 0; j < b_l; ++j) {
284
+ b_j = b[j];
285
+ product = a_i * b_j + r[i2 + j];
286
+ carry = Math.floor(product / base3);
287
+ r[i2 + j] = product - carry * base3;
288
+ r[i2 + j + 1] += carry;
289
+ }
290
+ }
291
+ trim(r);
292
+ return r;
293
+ }
294
+ function multiplySmall(a, b) {
295
+ var l = a.length, r = new Array(l), base3 = BASE, carry = 0, product, i2;
296
+ for (i2 = 0; i2 < l; i2++) {
297
+ product = a[i2] * b + carry;
298
+ carry = Math.floor(product / base3);
299
+ r[i2] = product - carry * base3;
300
+ }
301
+ while (carry > 0) {
302
+ r[i2++] = carry % base3;
303
+ carry = Math.floor(carry / base3);
304
+ }
305
+ return r;
306
+ }
307
+ function shiftLeft(x, n) {
308
+ var r = [];
309
+ while (n-- > 0)
310
+ r.push(0);
311
+ return r.concat(x);
312
+ }
313
+ function multiplyKaratsuba(x, y) {
314
+ var n = Math.max(x.length, y.length);
315
+ if (n <= 30)
316
+ return multiplyLong(x, y);
317
+ n = Math.ceil(n / 2);
318
+ var b = x.slice(n), a = x.slice(0, n), d = y.slice(n), c = y.slice(0, n);
319
+ var ac = multiplyKaratsuba(a, c), bd = multiplyKaratsuba(b, d), abcd = multiplyKaratsuba(addAny(a, b), addAny(c, d));
320
+ var product = addAny(addAny(ac, shiftLeft(subtract(subtract(abcd, ac), bd), n)), shiftLeft(bd, 2 * n));
321
+ trim(product);
322
+ return product;
323
+ }
324
+ function useKaratsuba(l1, l2) {
325
+ return -0.012 * l1 - 0.012 * l2 + 15e-6 * l1 * l2 > 0;
326
+ }
327
+ BigInteger.prototype.multiply = function(v) {
328
+ var n = parseValue(v), a = this.value, b = n.value, sign2 = this.sign !== n.sign, abs;
329
+ if (n.isSmall) {
330
+ if (b === 0)
331
+ return Integer[0];
332
+ if (b === 1)
333
+ return this;
334
+ if (b === -1)
335
+ return this.negate();
336
+ abs = Math.abs(b);
337
+ if (abs < BASE) {
338
+ return new BigInteger(multiplySmall(a, abs), sign2);
339
+ }
340
+ b = smallToArray(abs);
341
+ }
342
+ if (useKaratsuba(a.length, b.length))
343
+ return new BigInteger(multiplyKaratsuba(a, b), sign2);
344
+ return new BigInteger(multiplyLong(a, b), sign2);
345
+ };
346
+ BigInteger.prototype.times = BigInteger.prototype.multiply;
347
+ function multiplySmallAndArray(a, b, sign2) {
348
+ if (a < BASE) {
349
+ return new BigInteger(multiplySmall(b, a), sign2);
350
+ }
351
+ return new BigInteger(multiplyLong(b, smallToArray(a)), sign2);
352
+ }
353
+ SmallInteger.prototype._multiplyBySmall = function(a) {
354
+ if (isPrecise(a.value * this.value)) {
355
+ return new SmallInteger(a.value * this.value);
356
+ }
357
+ return multiplySmallAndArray(Math.abs(a.value), smallToArray(Math.abs(this.value)), this.sign !== a.sign);
358
+ };
359
+ BigInteger.prototype._multiplyBySmall = function(a) {
360
+ if (a.value === 0)
361
+ return Integer[0];
362
+ if (a.value === 1)
363
+ return this;
364
+ if (a.value === -1)
365
+ return this.negate();
366
+ return multiplySmallAndArray(Math.abs(a.value), this.value, this.sign !== a.sign);
367
+ };
368
+ SmallInteger.prototype.multiply = function(v) {
369
+ return parseValue(v)._multiplyBySmall(this);
370
+ };
371
+ SmallInteger.prototype.times = SmallInteger.prototype.multiply;
372
+ NativeBigInt.prototype.multiply = function(v) {
373
+ return new NativeBigInt(this.value * parseValue(v).value);
374
+ };
375
+ NativeBigInt.prototype.times = NativeBigInt.prototype.multiply;
376
+ function square(a) {
377
+ var l = a.length, r = createArray(l + l), base3 = BASE, product, carry, i2, a_i, a_j;
378
+ for (i2 = 0; i2 < l; i2++) {
379
+ a_i = a[i2];
380
+ carry = 0 - a_i * a_i;
381
+ for (var j = i2; j < l; j++) {
382
+ a_j = a[j];
383
+ product = 2 * (a_i * a_j) + r[i2 + j] + carry;
384
+ carry = Math.floor(product / base3);
385
+ r[i2 + j] = product - carry * base3;
386
+ }
387
+ r[i2 + l] = carry;
388
+ }
389
+ trim(r);
390
+ return r;
391
+ }
392
+ BigInteger.prototype.square = function() {
393
+ return new BigInteger(square(this.value), false);
394
+ };
395
+ SmallInteger.prototype.square = function() {
396
+ var value = this.value * this.value;
397
+ if (isPrecise(value))
398
+ return new SmallInteger(value);
399
+ return new BigInteger(square(smallToArray(Math.abs(this.value))), false);
400
+ };
401
+ NativeBigInt.prototype.square = function(v) {
402
+ return new NativeBigInt(this.value * this.value);
403
+ };
404
+ function divMod1(a, b) {
405
+ var a_l = a.length, b_l = b.length, base3 = BASE, result = createArray(b.length), divisorMostSignificantDigit = b[b_l - 1], lambda = Math.ceil(base3 / (2 * divisorMostSignificantDigit)), remainder = multiplySmall(a, lambda), divisor = multiplySmall(b, lambda), quotientDigit, shift, carry, borrow, i2, l, q;
406
+ if (remainder.length <= a_l)
407
+ remainder.push(0);
408
+ divisor.push(0);
409
+ divisorMostSignificantDigit = divisor[b_l - 1];
410
+ for (shift = a_l - b_l; shift >= 0; shift--) {
411
+ quotientDigit = base3 - 1;
412
+ if (remainder[shift + b_l] !== divisorMostSignificantDigit) {
413
+ quotientDigit = Math.floor((remainder[shift + b_l] * base3 + remainder[shift + b_l - 1]) / divisorMostSignificantDigit);
414
+ }
415
+ carry = 0;
416
+ borrow = 0;
417
+ l = divisor.length;
418
+ for (i2 = 0; i2 < l; i2++) {
419
+ carry += quotientDigit * divisor[i2];
420
+ q = Math.floor(carry / base3);
421
+ borrow += remainder[shift + i2] - (carry - q * base3);
422
+ carry = q;
423
+ if (borrow < 0) {
424
+ remainder[shift + i2] = borrow + base3;
425
+ borrow = -1;
426
+ } else {
427
+ remainder[shift + i2] = borrow;
428
+ borrow = 0;
429
+ }
430
+ }
431
+ while (borrow !== 0) {
432
+ quotientDigit -= 1;
433
+ carry = 0;
434
+ for (i2 = 0; i2 < l; i2++) {
435
+ carry += remainder[shift + i2] - base3 + divisor[i2];
436
+ if (carry < 0) {
437
+ remainder[shift + i2] = carry + base3;
438
+ carry = 0;
439
+ } else {
440
+ remainder[shift + i2] = carry;
441
+ carry = 1;
442
+ }
443
+ }
444
+ borrow += carry;
445
+ }
446
+ result[shift] = quotientDigit;
447
+ }
448
+ remainder = divModSmall(remainder, lambda)[0];
449
+ return [arrayToSmall(result), arrayToSmall(remainder)];
450
+ }
451
+ function divMod2(a, b) {
452
+ var a_l = a.length, b_l = b.length, result = [], part = [], base3 = BASE, guess, xlen, highx, highy, check;
453
+ while (a_l) {
454
+ part.unshift(a[--a_l]);
455
+ trim(part);
456
+ if (compareAbs(part, b) < 0) {
457
+ result.push(0);
458
+ continue;
459
+ }
460
+ xlen = part.length;
461
+ highx = part[xlen - 1] * base3 + part[xlen - 2];
462
+ highy = b[b_l - 1] * base3 + b[b_l - 2];
463
+ if (xlen > b_l) {
464
+ highx = (highx + 1) * base3;
465
+ }
466
+ guess = Math.ceil(highx / highy);
467
+ do {
468
+ check = multiplySmall(b, guess);
469
+ if (compareAbs(check, part) <= 0)
470
+ break;
471
+ guess--;
472
+ } while (guess);
473
+ result.push(guess);
474
+ part = subtract(part, check);
475
+ }
476
+ result.reverse();
477
+ return [arrayToSmall(result), arrayToSmall(part)];
478
+ }
479
+ function divModSmall(value, lambda) {
480
+ var length2 = value.length, quotient = createArray(length2), base3 = BASE, i2, q, remainder, divisor;
481
+ remainder = 0;
482
+ for (i2 = length2 - 1; i2 >= 0; --i2) {
483
+ divisor = remainder * base3 + value[i2];
484
+ q = truncate(divisor / lambda);
485
+ remainder = divisor - q * lambda;
486
+ quotient[i2] = q | 0;
487
+ }
488
+ return [quotient, remainder | 0];
489
+ }
490
+ function divModAny(self2, v) {
491
+ var value, n = parseValue(v);
492
+ if (supportsNativeBigInt) {
493
+ return [new NativeBigInt(self2.value / n.value), new NativeBigInt(self2.value % n.value)];
494
+ }
495
+ var a = self2.value, b = n.value;
496
+ var quotient;
497
+ if (b === 0)
498
+ throw new Error("Cannot divide by zero");
499
+ if (self2.isSmall) {
500
+ if (n.isSmall) {
501
+ return [new SmallInteger(truncate(a / b)), new SmallInteger(a % b)];
502
+ }
503
+ return [Integer[0], self2];
504
+ }
505
+ if (n.isSmall) {
506
+ if (b === 1)
507
+ return [self2, Integer[0]];
508
+ if (b == -1)
509
+ return [self2.negate(), Integer[0]];
510
+ var abs = Math.abs(b);
511
+ if (abs < BASE) {
512
+ value = divModSmall(a, abs);
513
+ quotient = arrayToSmall(value[0]);
514
+ var remainder = value[1];
515
+ if (self2.sign)
516
+ remainder = -remainder;
517
+ if (typeof quotient === "number") {
518
+ if (self2.sign !== n.sign)
519
+ quotient = -quotient;
520
+ return [new SmallInteger(quotient), new SmallInteger(remainder)];
521
+ }
522
+ return [new BigInteger(quotient, self2.sign !== n.sign), new SmallInteger(remainder)];
523
+ }
524
+ b = smallToArray(abs);
525
+ }
526
+ var comparison = compareAbs(a, b);
527
+ if (comparison === -1)
528
+ return [Integer[0], self2];
529
+ if (comparison === 0)
530
+ return [Integer[self2.sign === n.sign ? 1 : -1], Integer[0]];
531
+ if (a.length + b.length <= 200)
532
+ value = divMod1(a, b);
533
+ else
534
+ value = divMod2(a, b);
535
+ quotient = value[0];
536
+ var qSign = self2.sign !== n.sign, mod2 = value[1], mSign = self2.sign;
537
+ if (typeof quotient === "number") {
538
+ if (qSign)
539
+ quotient = -quotient;
540
+ quotient = new SmallInteger(quotient);
541
+ } else
542
+ quotient = new BigInteger(quotient, qSign);
543
+ if (typeof mod2 === "number") {
544
+ if (mSign)
545
+ mod2 = -mod2;
546
+ mod2 = new SmallInteger(mod2);
547
+ } else
548
+ mod2 = new BigInteger(mod2, mSign);
549
+ return [quotient, mod2];
550
+ }
551
+ BigInteger.prototype.divmod = function(v) {
552
+ var result = divModAny(this, v);
553
+ return {
554
+ quotient: result[0],
555
+ remainder: result[1]
556
+ };
557
+ };
558
+ NativeBigInt.prototype.divmod = SmallInteger.prototype.divmod = BigInteger.prototype.divmod;
559
+ BigInteger.prototype.divide = function(v) {
560
+ return divModAny(this, v)[0];
561
+ };
562
+ NativeBigInt.prototype.over = NativeBigInt.prototype.divide = function(v) {
563
+ return new NativeBigInt(this.value / parseValue(v).value);
564
+ };
565
+ SmallInteger.prototype.over = SmallInteger.prototype.divide = BigInteger.prototype.over = BigInteger.prototype.divide;
566
+ BigInteger.prototype.mod = function(v) {
567
+ return divModAny(this, v)[1];
568
+ };
569
+ NativeBigInt.prototype.mod = NativeBigInt.prototype.remainder = function(v) {
570
+ return new NativeBigInt(this.value % parseValue(v).value);
571
+ };
572
+ SmallInteger.prototype.remainder = SmallInteger.prototype.mod = BigInteger.prototype.remainder = BigInteger.prototype.mod;
573
+ BigInteger.prototype.pow = function(v) {
574
+ var n = parseValue(v), a = this.value, b = n.value, value, x, y;
575
+ if (b === 0)
576
+ return Integer[1];
577
+ if (a === 0)
578
+ return Integer[0];
579
+ if (a === 1)
580
+ return Integer[1];
581
+ if (a === -1)
582
+ return n.isEven() ? Integer[1] : Integer[-1];
583
+ if (n.sign) {
584
+ return Integer[0];
585
+ }
586
+ if (!n.isSmall)
587
+ throw new Error("The exponent " + n.toString() + " is too large.");
588
+ if (this.isSmall) {
589
+ if (isPrecise(value = Math.pow(a, b)))
590
+ return new SmallInteger(truncate(value));
591
+ }
592
+ x = this;
593
+ y = Integer[1];
594
+ while (true) {
595
+ if (b & true) {
596
+ y = y.times(x);
597
+ --b;
598
+ }
599
+ if (b === 0)
600
+ break;
601
+ b /= 2;
602
+ x = x.square();
603
+ }
604
+ return y;
605
+ };
606
+ SmallInteger.prototype.pow = BigInteger.prototype.pow;
607
+ NativeBigInt.prototype.pow = function(v) {
608
+ var n = parseValue(v);
609
+ var a = this.value, b = n.value;
610
+ var _0 = BigInt(0), _1 = BigInt(1), _2 = BigInt(2);
611
+ if (b === _0)
612
+ return Integer[1];
613
+ if (a === _0)
614
+ return Integer[0];
615
+ if (a === _1)
616
+ return Integer[1];
617
+ if (a === BigInt(-1))
618
+ return n.isEven() ? Integer[1] : Integer[-1];
619
+ if (n.isNegative())
620
+ return new NativeBigInt(_0);
621
+ var x = this;
622
+ var y = Integer[1];
623
+ while (true) {
624
+ if ((b & _1) === _1) {
625
+ y = y.times(x);
626
+ --b;
627
+ }
628
+ if (b === _0)
629
+ break;
630
+ b /= _2;
631
+ x = x.square();
632
+ }
633
+ return y;
634
+ };
635
+ BigInteger.prototype.modPow = function(exp, mod2) {
636
+ exp = parseValue(exp);
637
+ mod2 = parseValue(mod2);
638
+ if (mod2.isZero())
639
+ throw new Error("Cannot take modPow with modulus 0");
640
+ var r = Integer[1], base3 = this.mod(mod2);
641
+ if (exp.isNegative()) {
642
+ exp = exp.multiply(Integer[-1]);
643
+ base3 = base3.modInv(mod2);
644
+ }
645
+ while (exp.isPositive()) {
646
+ if (base3.isZero())
647
+ return Integer[0];
648
+ if (exp.isOdd())
649
+ r = r.multiply(base3).mod(mod2);
650
+ exp = exp.divide(2);
651
+ base3 = base3.square().mod(mod2);
652
+ }
653
+ return r;
654
+ };
655
+ NativeBigInt.prototype.modPow = SmallInteger.prototype.modPow = BigInteger.prototype.modPow;
656
+ function compareAbs(a, b) {
657
+ if (a.length !== b.length) {
658
+ return a.length > b.length ? 1 : -1;
659
+ }
660
+ for (var i2 = a.length - 1; i2 >= 0; i2--) {
661
+ if (a[i2] !== b[i2])
662
+ return a[i2] > b[i2] ? 1 : -1;
663
+ }
664
+ return 0;
665
+ }
666
+ BigInteger.prototype.compareAbs = function(v) {
667
+ var n = parseValue(v), a = this.value, b = n.value;
668
+ if (n.isSmall)
669
+ return 1;
670
+ return compareAbs(a, b);
671
+ };
672
+ SmallInteger.prototype.compareAbs = function(v) {
673
+ var n = parseValue(v), a = Math.abs(this.value), b = n.value;
674
+ if (n.isSmall) {
675
+ b = Math.abs(b);
676
+ return a === b ? 0 : a > b ? 1 : -1;
677
+ }
678
+ return -1;
679
+ };
680
+ NativeBigInt.prototype.compareAbs = function(v) {
681
+ var a = this.value;
682
+ var b = parseValue(v).value;
683
+ a = a >= 0 ? a : -a;
684
+ b = b >= 0 ? b : -b;
685
+ return a === b ? 0 : a > b ? 1 : -1;
686
+ };
687
+ BigInteger.prototype.compare = function(v) {
688
+ if (v === Infinity) {
689
+ return -1;
690
+ }
691
+ if (v === -Infinity) {
692
+ return 1;
693
+ }
694
+ var n = parseValue(v), a = this.value, b = n.value;
695
+ if (this.sign !== n.sign) {
696
+ return n.sign ? 1 : -1;
697
+ }
698
+ if (n.isSmall) {
699
+ return this.sign ? -1 : 1;
700
+ }
701
+ return compareAbs(a, b) * (this.sign ? -1 : 1);
702
+ };
703
+ BigInteger.prototype.compareTo = BigInteger.prototype.compare;
704
+ SmallInteger.prototype.compare = function(v) {
705
+ if (v === Infinity) {
706
+ return -1;
707
+ }
708
+ if (v === -Infinity) {
709
+ return 1;
710
+ }
711
+ var n = parseValue(v), a = this.value, b = n.value;
712
+ if (n.isSmall) {
713
+ return a == b ? 0 : a > b ? 1 : -1;
714
+ }
715
+ if (a < 0 !== n.sign) {
716
+ return a < 0 ? -1 : 1;
717
+ }
718
+ return a < 0 ? 1 : -1;
719
+ };
720
+ SmallInteger.prototype.compareTo = SmallInteger.prototype.compare;
721
+ NativeBigInt.prototype.compare = function(v) {
722
+ if (v === Infinity) {
723
+ return -1;
724
+ }
725
+ if (v === -Infinity) {
726
+ return 1;
727
+ }
728
+ var a = this.value;
729
+ var b = parseValue(v).value;
730
+ return a === b ? 0 : a > b ? 1 : -1;
731
+ };
732
+ NativeBigInt.prototype.compareTo = NativeBigInt.prototype.compare;
733
+ BigInteger.prototype.equals = function(v) {
734
+ return this.compare(v) === 0;
735
+ };
736
+ NativeBigInt.prototype.eq = NativeBigInt.prototype.equals = SmallInteger.prototype.eq = SmallInteger.prototype.equals = BigInteger.prototype.eq = BigInteger.prototype.equals;
737
+ BigInteger.prototype.notEquals = function(v) {
738
+ return this.compare(v) !== 0;
739
+ };
740
+ NativeBigInt.prototype.neq = NativeBigInt.prototype.notEquals = SmallInteger.prototype.neq = SmallInteger.prototype.notEquals = BigInteger.prototype.neq = BigInteger.prototype.notEquals;
741
+ BigInteger.prototype.greater = function(v) {
742
+ return this.compare(v) > 0;
743
+ };
744
+ NativeBigInt.prototype.gt = NativeBigInt.prototype.greater = SmallInteger.prototype.gt = SmallInteger.prototype.greater = BigInteger.prototype.gt = BigInteger.prototype.greater;
745
+ BigInteger.prototype.lesser = function(v) {
746
+ return this.compare(v) < 0;
747
+ };
748
+ NativeBigInt.prototype.lt = NativeBigInt.prototype.lesser = SmallInteger.prototype.lt = SmallInteger.prototype.lesser = BigInteger.prototype.lt = BigInteger.prototype.lesser;
749
+ BigInteger.prototype.greaterOrEquals = function(v) {
750
+ return this.compare(v) >= 0;
751
+ };
752
+ NativeBigInt.prototype.geq = NativeBigInt.prototype.greaterOrEquals = SmallInteger.prototype.geq = SmallInteger.prototype.greaterOrEquals = BigInteger.prototype.geq = BigInteger.prototype.greaterOrEquals;
753
+ BigInteger.prototype.lesserOrEquals = function(v) {
754
+ return this.compare(v) <= 0;
755
+ };
756
+ NativeBigInt.prototype.leq = NativeBigInt.prototype.lesserOrEquals = SmallInteger.prototype.leq = SmallInteger.prototype.lesserOrEquals = BigInteger.prototype.leq = BigInteger.prototype.lesserOrEquals;
757
+ BigInteger.prototype.isEven = function() {
758
+ return (this.value[0] & 1) === 0;
759
+ };
760
+ SmallInteger.prototype.isEven = function() {
761
+ return (this.value & 1) === 0;
762
+ };
763
+ NativeBigInt.prototype.isEven = function() {
764
+ return (this.value & BigInt(1)) === BigInt(0);
765
+ };
766
+ BigInteger.prototype.isOdd = function() {
767
+ return (this.value[0] & 1) === 1;
768
+ };
769
+ SmallInteger.prototype.isOdd = function() {
770
+ return (this.value & 1) === 1;
771
+ };
772
+ NativeBigInt.prototype.isOdd = function() {
773
+ return (this.value & BigInt(1)) === BigInt(1);
774
+ };
775
+ BigInteger.prototype.isPositive = function() {
776
+ return !this.sign;
777
+ };
778
+ SmallInteger.prototype.isPositive = function() {
779
+ return this.value > 0;
780
+ };
781
+ NativeBigInt.prototype.isPositive = SmallInteger.prototype.isPositive;
782
+ BigInteger.prototype.isNegative = function() {
783
+ return this.sign;
784
+ };
785
+ SmallInteger.prototype.isNegative = function() {
786
+ return this.value < 0;
787
+ };
788
+ NativeBigInt.prototype.isNegative = SmallInteger.prototype.isNegative;
789
+ BigInteger.prototype.isUnit = function() {
790
+ return false;
791
+ };
792
+ SmallInteger.prototype.isUnit = function() {
793
+ return Math.abs(this.value) === 1;
794
+ };
795
+ NativeBigInt.prototype.isUnit = function() {
796
+ return this.abs().value === BigInt(1);
797
+ };
798
+ BigInteger.prototype.isZero = function() {
799
+ return false;
800
+ };
801
+ SmallInteger.prototype.isZero = function() {
802
+ return this.value === 0;
803
+ };
804
+ NativeBigInt.prototype.isZero = function() {
805
+ return this.value === BigInt(0);
806
+ };
807
+ BigInteger.prototype.isDivisibleBy = function(v) {
808
+ var n = parseValue(v);
809
+ if (n.isZero())
810
+ return false;
811
+ if (n.isUnit())
812
+ return true;
813
+ if (n.compareAbs(2) === 0)
814
+ return this.isEven();
815
+ return this.mod(n).isZero();
816
+ };
817
+ NativeBigInt.prototype.isDivisibleBy = SmallInteger.prototype.isDivisibleBy = BigInteger.prototype.isDivisibleBy;
818
+ function isBasicPrime(v) {
819
+ var n = v.abs();
820
+ if (n.isUnit())
821
+ return false;
822
+ if (n.equals(2) || n.equals(3) || n.equals(5))
823
+ return true;
824
+ if (n.isEven() || n.isDivisibleBy(3) || n.isDivisibleBy(5))
825
+ return false;
826
+ if (n.lesser(49))
827
+ return true;
828
+ }
829
+ function millerRabinTest(n, a) {
830
+ var nPrev = n.prev(), b = nPrev, r = 0, d, t, i2, x;
831
+ while (b.isEven())
832
+ b = b.divide(2), r++;
833
+ next:
834
+ for (i2 = 0; i2 < a.length; i2++) {
835
+ if (n.lesser(a[i2]))
836
+ continue;
837
+ x = bigInt2(a[i2]).modPow(b, n);
838
+ if (x.isUnit() || x.equals(nPrev))
839
+ continue;
840
+ for (d = r - 1; d != 0; d--) {
841
+ x = x.square().mod(n);
842
+ if (x.isUnit())
843
+ return false;
844
+ if (x.equals(nPrev))
845
+ continue next;
846
+ }
847
+ return false;
848
+ }
849
+ return true;
850
+ }
851
+ BigInteger.prototype.isPrime = function(strict) {
852
+ var isPrime = isBasicPrime(this);
853
+ if (isPrime !== undefined2)
854
+ return isPrime;
855
+ var n = this.abs();
856
+ var bits = n.bitLength();
857
+ if (bits <= 64)
858
+ return millerRabinTest(n, [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37]);
859
+ var logN = Math.log(2) * bits.toJSNumber();
860
+ var t = Math.ceil(strict === true ? 2 * Math.pow(logN, 2) : logN);
861
+ for (var a = [], i2 = 0; i2 < t; i2++) {
862
+ a.push(bigInt2(i2 + 2));
863
+ }
864
+ return millerRabinTest(n, a);
865
+ };
866
+ NativeBigInt.prototype.isPrime = SmallInteger.prototype.isPrime = BigInteger.prototype.isPrime;
867
+ BigInteger.prototype.isProbablePrime = function(iterations, rng) {
868
+ var isPrime = isBasicPrime(this);
869
+ if (isPrime !== undefined2)
870
+ return isPrime;
871
+ var n = this.abs();
872
+ var t = iterations === undefined2 ? 5 : iterations;
873
+ for (var a = [], i2 = 0; i2 < t; i2++) {
874
+ a.push(bigInt2.randBetween(2, n.minus(2), rng));
875
+ }
876
+ return millerRabinTest(n, a);
877
+ };
878
+ NativeBigInt.prototype.isProbablePrime = SmallInteger.prototype.isProbablePrime = BigInteger.prototype.isProbablePrime;
879
+ BigInteger.prototype.modInv = function(n) {
880
+ var t = bigInt2.zero, newT = bigInt2.one, r = parseValue(n), newR = this.abs(), q, lastT, lastR;
881
+ while (!newR.isZero()) {
882
+ q = r.divide(newR);
883
+ lastT = t;
884
+ lastR = r;
885
+ t = newT;
886
+ r = newR;
887
+ newT = lastT.subtract(q.multiply(newT));
888
+ newR = lastR.subtract(q.multiply(newR));
889
+ }
890
+ if (!r.isUnit())
891
+ throw new Error(this.toString() + " and " + n.toString() + " are not co-prime");
892
+ if (t.compare(0) === -1) {
893
+ t = t.add(n);
894
+ }
895
+ if (this.isNegative()) {
896
+ return t.negate();
897
+ }
898
+ return t;
899
+ };
900
+ NativeBigInt.prototype.modInv = SmallInteger.prototype.modInv = BigInteger.prototype.modInv;
901
+ BigInteger.prototype.next = function() {
902
+ var value = this.value;
903
+ if (this.sign) {
904
+ return subtractSmall(value, 1, this.sign);
905
+ }
906
+ return new BigInteger(addSmall(value, 1), this.sign);
907
+ };
908
+ SmallInteger.prototype.next = function() {
909
+ var value = this.value;
910
+ if (value + 1 < MAX_INT)
911
+ return new SmallInteger(value + 1);
912
+ return new BigInteger(MAX_INT_ARR, false);
913
+ };
914
+ NativeBigInt.prototype.next = function() {
915
+ return new NativeBigInt(this.value + BigInt(1));
916
+ };
917
+ BigInteger.prototype.prev = function() {
918
+ var value = this.value;
919
+ if (this.sign) {
920
+ return new BigInteger(addSmall(value, 1), true);
921
+ }
922
+ return subtractSmall(value, 1, this.sign);
923
+ };
924
+ SmallInteger.prototype.prev = function() {
925
+ var value = this.value;
926
+ if (value - 1 > -MAX_INT)
927
+ return new SmallInteger(value - 1);
928
+ return new BigInteger(MAX_INT_ARR, true);
929
+ };
930
+ NativeBigInt.prototype.prev = function() {
931
+ return new NativeBigInt(this.value - BigInt(1));
932
+ };
933
+ var powersOfTwo = [1];
934
+ while (2 * powersOfTwo[powersOfTwo.length - 1] <= BASE)
935
+ powersOfTwo.push(2 * powersOfTwo[powersOfTwo.length - 1]);
936
+ var powers2Length = powersOfTwo.length, highestPower2 = powersOfTwo[powers2Length - 1];
937
+ function shift_isSmall(n) {
938
+ return Math.abs(n) <= BASE;
939
+ }
940
+ BigInteger.prototype.shiftLeft = function(v) {
941
+ var n = parseValue(v).toJSNumber();
942
+ if (!shift_isSmall(n)) {
943
+ throw new Error(String(n) + " is too large for shifting.");
944
+ }
945
+ if (n < 0)
946
+ return this.shiftRight(-n);
947
+ var result = this;
948
+ if (result.isZero())
949
+ return result;
950
+ while (n >= powers2Length) {
951
+ result = result.multiply(highestPower2);
952
+ n -= powers2Length - 1;
953
+ }
954
+ return result.multiply(powersOfTwo[n]);
955
+ };
956
+ NativeBigInt.prototype.shiftLeft = SmallInteger.prototype.shiftLeft = BigInteger.prototype.shiftLeft;
957
+ BigInteger.prototype.shiftRight = function(v) {
958
+ var remQuo;
959
+ var n = parseValue(v).toJSNumber();
960
+ if (!shift_isSmall(n)) {
961
+ throw new Error(String(n) + " is too large for shifting.");
962
+ }
963
+ if (n < 0)
964
+ return this.shiftLeft(-n);
965
+ var result = this;
966
+ while (n >= powers2Length) {
967
+ if (result.isZero() || result.isNegative() && result.isUnit())
968
+ return result;
969
+ remQuo = divModAny(result, highestPower2);
970
+ result = remQuo[1].isNegative() ? remQuo[0].prev() : remQuo[0];
971
+ n -= powers2Length - 1;
972
+ }
973
+ remQuo = divModAny(result, powersOfTwo[n]);
974
+ return remQuo[1].isNegative() ? remQuo[0].prev() : remQuo[0];
975
+ };
976
+ NativeBigInt.prototype.shiftRight = SmallInteger.prototype.shiftRight = BigInteger.prototype.shiftRight;
977
+ function bitwise(x, y, fn) {
978
+ y = parseValue(y);
979
+ var xSign = x.isNegative(), ySign = y.isNegative();
980
+ var xRem = xSign ? x.not() : x, yRem = ySign ? y.not() : y;
981
+ var xDigit = 0, yDigit = 0;
982
+ var xDivMod = null, yDivMod = null;
983
+ var result = [];
984
+ while (!xRem.isZero() || !yRem.isZero()) {
985
+ xDivMod = divModAny(xRem, highestPower2);
986
+ xDigit = xDivMod[1].toJSNumber();
987
+ if (xSign) {
988
+ xDigit = highestPower2 - 1 - xDigit;
989
+ }
990
+ yDivMod = divModAny(yRem, highestPower2);
991
+ yDigit = yDivMod[1].toJSNumber();
992
+ if (ySign) {
993
+ yDigit = highestPower2 - 1 - yDigit;
994
+ }
995
+ xRem = xDivMod[0];
996
+ yRem = yDivMod[0];
997
+ result.push(fn(xDigit, yDigit));
998
+ }
999
+ var sum = fn(xSign ? 1 : 0, ySign ? 1 : 0) !== 0 ? bigInt2(-1) : bigInt2(0);
1000
+ for (var i2 = result.length - 1; i2 >= 0; i2 -= 1) {
1001
+ sum = sum.multiply(highestPower2).add(bigInt2(result[i2]));
1002
+ }
1003
+ return sum;
1004
+ }
1005
+ BigInteger.prototype.not = function() {
1006
+ return this.negate().prev();
1007
+ };
1008
+ NativeBigInt.prototype.not = SmallInteger.prototype.not = BigInteger.prototype.not;
1009
+ BigInteger.prototype.and = function(n) {
1010
+ return bitwise(this, n, function(a, b) {
1011
+ return a & b;
1012
+ });
1013
+ };
1014
+ NativeBigInt.prototype.and = SmallInteger.prototype.and = BigInteger.prototype.and;
1015
+ BigInteger.prototype.or = function(n) {
1016
+ return bitwise(this, n, function(a, b) {
1017
+ return a | b;
1018
+ });
1019
+ };
1020
+ NativeBigInt.prototype.or = SmallInteger.prototype.or = BigInteger.prototype.or;
1021
+ BigInteger.prototype.xor = function(n) {
1022
+ return bitwise(this, n, function(a, b) {
1023
+ return a ^ b;
1024
+ });
1025
+ };
1026
+ NativeBigInt.prototype.xor = SmallInteger.prototype.xor = BigInteger.prototype.xor;
1027
+ var LOBMASK_I = 1 << 30, LOBMASK_BI = (BASE & -BASE) * (BASE & -BASE) | LOBMASK_I;
1028
+ function roughLOB(n) {
1029
+ var v = n.value, x = typeof v === "number" ? v | LOBMASK_I : typeof v === "bigint" ? v | BigInt(LOBMASK_I) : v[0] + v[1] * BASE | LOBMASK_BI;
1030
+ return x & -x;
1031
+ }
1032
+ function integerLogarithm(value, base3) {
1033
+ if (base3.compareTo(value) <= 0) {
1034
+ var tmp = integerLogarithm(value, base3.square(base3));
1035
+ var p = tmp.p;
1036
+ var e = tmp.e;
1037
+ var t = p.multiply(base3);
1038
+ return t.compareTo(value) <= 0 ? { p: t, e: e * 2 + 1 } : { p, e: e * 2 };
1039
+ }
1040
+ return { p: bigInt2(1), e: 0 };
1041
+ }
1042
+ BigInteger.prototype.bitLength = function() {
1043
+ var n = this;
1044
+ if (n.compareTo(bigInt2(0)) < 0) {
1045
+ n = n.negate().subtract(bigInt2(1));
1046
+ }
1047
+ if (n.compareTo(bigInt2(0)) === 0) {
1048
+ return bigInt2(0);
1049
+ }
1050
+ return bigInt2(integerLogarithm(n, bigInt2(2)).e).add(bigInt2(1));
1051
+ };
1052
+ NativeBigInt.prototype.bitLength = SmallInteger.prototype.bitLength = BigInteger.prototype.bitLength;
1053
+ function max(a, b) {
1054
+ a = parseValue(a);
1055
+ b = parseValue(b);
1056
+ return a.greater(b) ? a : b;
1057
+ }
1058
+ function min(a, b) {
1059
+ a = parseValue(a);
1060
+ b = parseValue(b);
1061
+ return a.lesser(b) ? a : b;
1062
+ }
1063
+ function gcd(a, b) {
1064
+ a = parseValue(a).abs();
1065
+ b = parseValue(b).abs();
1066
+ if (a.equals(b))
1067
+ return a;
1068
+ if (a.isZero())
1069
+ return b;
1070
+ if (b.isZero())
1071
+ return a;
1072
+ var c = Integer[1], d, t;
1073
+ while (a.isEven() && b.isEven()) {
1074
+ d = min(roughLOB(a), roughLOB(b));
1075
+ a = a.divide(d);
1076
+ b = b.divide(d);
1077
+ c = c.multiply(d);
1078
+ }
1079
+ while (a.isEven()) {
1080
+ a = a.divide(roughLOB(a));
1081
+ }
1082
+ do {
1083
+ while (b.isEven()) {
1084
+ b = b.divide(roughLOB(b));
1085
+ }
1086
+ if (a.greater(b)) {
1087
+ t = b;
1088
+ b = a;
1089
+ a = t;
1090
+ }
1091
+ b = b.subtract(a);
1092
+ } while (!b.isZero());
1093
+ return c.isUnit() ? a : a.multiply(c);
1094
+ }
1095
+ function lcm(a, b) {
1096
+ a = parseValue(a).abs();
1097
+ b = parseValue(b).abs();
1098
+ return a.divide(gcd(a, b)).multiply(b);
1099
+ }
1100
+ function randBetween(a, b, rng) {
1101
+ a = parseValue(a);
1102
+ b = parseValue(b);
1103
+ var usedRNG = rng || Math.random;
1104
+ var low = min(a, b), high = max(a, b);
1105
+ var range = high.subtract(low).add(1);
1106
+ if (range.isSmall)
1107
+ return low.add(Math.floor(usedRNG() * range));
1108
+ var digits = toBase(range, BASE).value;
1109
+ var result = [], restricted = true;
1110
+ for (var i2 = 0; i2 < digits.length; i2++) {
1111
+ var top = restricted ? digits[i2] + (i2 + 1 < digits.length ? digits[i2 + 1] / BASE : 0) : BASE;
1112
+ var digit = truncate(usedRNG() * top);
1113
+ result.push(digit);
1114
+ if (digit < digits[i2])
1115
+ restricted = false;
1116
+ }
1117
+ return low.add(Integer.fromArray(result, BASE, false));
1118
+ }
1119
+ var parseBase = function(text, base3, alphabet2, caseSensitive) {
1120
+ alphabet2 = alphabet2 || DEFAULT_ALPHABET;
1121
+ text = String(text);
1122
+ if (!caseSensitive) {
1123
+ text = text.toLowerCase();
1124
+ alphabet2 = alphabet2.toLowerCase();
1125
+ }
1126
+ var length2 = text.length;
1127
+ var i2;
1128
+ var absBase = Math.abs(base3);
1129
+ var alphabetValues = {};
1130
+ for (i2 = 0; i2 < alphabet2.length; i2++) {
1131
+ alphabetValues[alphabet2[i2]] = i2;
1132
+ }
1133
+ for (i2 = 0; i2 < length2; i2++) {
1134
+ var c = text[i2];
1135
+ if (c === "-")
1136
+ continue;
1137
+ if (c in alphabetValues) {
1138
+ if (alphabetValues[c] >= absBase) {
1139
+ if (c === "1" && absBase === 1)
1140
+ continue;
1141
+ throw new Error(c + " is not a valid digit in base " + base3 + ".");
1142
+ }
1143
+ }
1144
+ }
1145
+ base3 = parseValue(base3);
1146
+ var digits = [];
1147
+ var isNegative = text[0] === "-";
1148
+ for (i2 = isNegative ? 1 : 0; i2 < text.length; i2++) {
1149
+ var c = text[i2];
1150
+ if (c in alphabetValues)
1151
+ digits.push(parseValue(alphabetValues[c]));
1152
+ else if (c === "<") {
1153
+ var start = i2;
1154
+ do {
1155
+ i2++;
1156
+ } while (text[i2] !== ">" && i2 < text.length);
1157
+ digits.push(parseValue(text.slice(start + 1, i2)));
1158
+ } else
1159
+ throw new Error(c + " is not a valid character");
1160
+ }
1161
+ return parseBaseFromArray(digits, base3, isNegative);
1162
+ };
1163
+ function parseBaseFromArray(digits, base3, isNegative) {
1164
+ var val = Integer[0], pow = Integer[1], i2;
1165
+ for (i2 = digits.length - 1; i2 >= 0; i2--) {
1166
+ val = val.add(digits[i2].times(pow));
1167
+ pow = pow.times(base3);
1168
+ }
1169
+ return isNegative ? val.negate() : val;
1170
+ }
1171
+ function stringify(digit, alphabet2) {
1172
+ alphabet2 = alphabet2 || DEFAULT_ALPHABET;
1173
+ if (digit < alphabet2.length) {
1174
+ return alphabet2[digit];
1175
+ }
1176
+ return "<" + digit + ">";
1177
+ }
1178
+ function toBase(n, base3) {
1179
+ base3 = bigInt2(base3);
1180
+ if (base3.isZero()) {
1181
+ if (n.isZero())
1182
+ return { value: [0], isNegative: false };
1183
+ throw new Error("Cannot convert nonzero numbers to base 0.");
1184
+ }
1185
+ if (base3.equals(-1)) {
1186
+ if (n.isZero())
1187
+ return { value: [0], isNegative: false };
1188
+ if (n.isNegative())
1189
+ return {
1190
+ value: [].concat.apply(
1191
+ [],
1192
+ Array.apply(null, Array(-n.toJSNumber())).map(Array.prototype.valueOf, [1, 0])
1193
+ ),
1194
+ isNegative: false
1195
+ };
1196
+ var arr = Array.apply(null, Array(n.toJSNumber() - 1)).map(Array.prototype.valueOf, [0, 1]);
1197
+ arr.unshift([1]);
1198
+ return {
1199
+ value: [].concat.apply([], arr),
1200
+ isNegative: false
1201
+ };
1202
+ }
1203
+ var neg = false;
1204
+ if (n.isNegative() && base3.isPositive()) {
1205
+ neg = true;
1206
+ n = n.abs();
1207
+ }
1208
+ if (base3.isUnit()) {
1209
+ if (n.isZero())
1210
+ return { value: [0], isNegative: false };
1211
+ return {
1212
+ value: Array.apply(null, Array(n.toJSNumber())).map(Number.prototype.valueOf, 1),
1213
+ isNegative: neg
1214
+ };
1215
+ }
1216
+ var out = [];
1217
+ var left = n, divmod;
1218
+ while (left.isNegative() || left.compareAbs(base3) >= 0) {
1219
+ divmod = left.divmod(base3);
1220
+ left = divmod.quotient;
1221
+ var digit = divmod.remainder;
1222
+ if (digit.isNegative()) {
1223
+ digit = base3.minus(digit).abs();
1224
+ left = left.next();
1225
+ }
1226
+ out.push(digit.toJSNumber());
1227
+ }
1228
+ out.push(left.toJSNumber());
1229
+ return { value: out.reverse(), isNegative: neg };
1230
+ }
1231
+ function toBaseString(n, base3, alphabet2) {
1232
+ var arr = toBase(n, base3);
1233
+ return (arr.isNegative ? "-" : "") + arr.value.map(function(x) {
1234
+ return stringify(x, alphabet2);
1235
+ }).join("");
1236
+ }
1237
+ BigInteger.prototype.toArray = function(radix) {
1238
+ return toBase(this, radix);
1239
+ };
1240
+ SmallInteger.prototype.toArray = function(radix) {
1241
+ return toBase(this, radix);
1242
+ };
1243
+ NativeBigInt.prototype.toArray = function(radix) {
1244
+ return toBase(this, radix);
1245
+ };
1246
+ BigInteger.prototype.toString = function(radix, alphabet2) {
1247
+ if (radix === undefined2)
1248
+ radix = 10;
1249
+ if (radix !== 10)
1250
+ return toBaseString(this, radix, alphabet2);
1251
+ var v = this.value, l = v.length, str = String(v[--l]), zeros = "0000000", digit;
1252
+ while (--l >= 0) {
1253
+ digit = String(v[l]);
1254
+ str += zeros.slice(digit.length) + digit;
1255
+ }
1256
+ var sign2 = this.sign ? "-" : "";
1257
+ return sign2 + str;
1258
+ };
1259
+ SmallInteger.prototype.toString = function(radix, alphabet2) {
1260
+ if (radix === undefined2)
1261
+ radix = 10;
1262
+ if (radix != 10)
1263
+ return toBaseString(this, radix, alphabet2);
1264
+ return String(this.value);
1265
+ };
1266
+ NativeBigInt.prototype.toString = SmallInteger.prototype.toString;
1267
+ NativeBigInt.prototype.toJSON = BigInteger.prototype.toJSON = SmallInteger.prototype.toJSON = function() {
1268
+ return this.toString();
1269
+ };
1270
+ BigInteger.prototype.valueOf = function() {
1271
+ return parseInt(this.toString(), 10);
1272
+ };
1273
+ BigInteger.prototype.toJSNumber = BigInteger.prototype.valueOf;
1274
+ SmallInteger.prototype.valueOf = function() {
1275
+ return this.value;
1276
+ };
1277
+ SmallInteger.prototype.toJSNumber = SmallInteger.prototype.valueOf;
1278
+ NativeBigInt.prototype.valueOf = NativeBigInt.prototype.toJSNumber = function() {
1279
+ return parseInt(this.toString(), 10);
1280
+ };
1281
+ function parseStringValue(v) {
1282
+ if (isPrecise(+v)) {
1283
+ var x = +v;
1284
+ if (x === truncate(x))
1285
+ return supportsNativeBigInt ? new NativeBigInt(BigInt(x)) : new SmallInteger(x);
1286
+ throw new Error("Invalid integer: " + v);
1287
+ }
1288
+ var sign2 = v[0] === "-";
1289
+ if (sign2)
1290
+ v = v.slice(1);
1291
+ var split = v.split(/e/i);
1292
+ if (split.length > 2)
1293
+ throw new Error("Invalid integer: " + split.join("e"));
1294
+ if (split.length === 2) {
1295
+ var exp = split[1];
1296
+ if (exp[0] === "+")
1297
+ exp = exp.slice(1);
1298
+ exp = +exp;
1299
+ if (exp !== truncate(exp) || !isPrecise(exp))
1300
+ throw new Error("Invalid integer: " + exp + " is not a valid exponent.");
1301
+ var text = split[0];
1302
+ var decimalPlace = text.indexOf(".");
1303
+ if (decimalPlace >= 0) {
1304
+ exp -= text.length - decimalPlace - 1;
1305
+ text = text.slice(0, decimalPlace) + text.slice(decimalPlace + 1);
1306
+ }
1307
+ if (exp < 0)
1308
+ throw new Error("Cannot include negative exponent part for integers");
1309
+ text += new Array(exp + 1).join("0");
1310
+ v = text;
1311
+ }
1312
+ var isValid = /^([0-9][0-9]*)$/.test(v);
1313
+ if (!isValid)
1314
+ throw new Error("Invalid integer: " + v);
1315
+ if (supportsNativeBigInt) {
1316
+ return new NativeBigInt(BigInt(sign2 ? "-" + v : v));
1317
+ }
1318
+ var r = [], max2 = v.length, l = LOG_BASE, min2 = max2 - l;
1319
+ while (max2 > 0) {
1320
+ r.push(+v.slice(min2, max2));
1321
+ min2 -= l;
1322
+ if (min2 < 0)
1323
+ min2 = 0;
1324
+ max2 -= l;
1325
+ }
1326
+ trim(r);
1327
+ return new BigInteger(r, sign2);
1328
+ }
1329
+ function parseNumberValue(v) {
1330
+ if (supportsNativeBigInt) {
1331
+ return new NativeBigInt(BigInt(v));
1332
+ }
1333
+ if (isPrecise(v)) {
1334
+ if (v !== truncate(v))
1335
+ throw new Error(v + " is not an integer.");
1336
+ return new SmallInteger(v);
1337
+ }
1338
+ return parseStringValue(v.toString());
1339
+ }
1340
+ function parseValue(v) {
1341
+ if (typeof v === "number") {
1342
+ return parseNumberValue(v);
1343
+ }
1344
+ if (typeof v === "string") {
1345
+ return parseStringValue(v);
1346
+ }
1347
+ if (typeof v === "bigint") {
1348
+ return new NativeBigInt(v);
1349
+ }
1350
+ return v;
1351
+ }
1352
+ for (var i = 0; i < 1e3; i++) {
1353
+ Integer[i] = parseValue(i);
1354
+ if (i > 0)
1355
+ Integer[-i] = parseValue(-i);
1356
+ }
1357
+ Integer.one = Integer[1];
1358
+ Integer.zero = Integer[0];
1359
+ Integer.minusOne = Integer[-1];
1360
+ Integer.max = max;
1361
+ Integer.min = min;
1362
+ Integer.gcd = gcd;
1363
+ Integer.lcm = lcm;
1364
+ Integer.isInstance = function(x) {
1365
+ return x instanceof BigInteger || x instanceof SmallInteger || x instanceof NativeBigInt;
1366
+ };
1367
+ Integer.randBetween = randBetween;
1368
+ Integer.fromArray = function(digits, base3, isNegative) {
1369
+ return parseBaseFromArray(digits.map(parseValue), parseValue(base3 || 10), isNegative);
1370
+ };
1371
+ return Integer;
1372
+ }();
1373
+ if (typeof module2 !== "undefined" && module2.hasOwnProperty("exports")) {
1374
+ module2.exports = bigInt2;
1375
+ }
1376
+ if (typeof define === "function" && define.amd) {
1377
+ define(function() {
1378
+ return bigInt2;
1379
+ });
1380
+ }
1381
+ }
1382
+ });
1383
+
1384
+ // src/index.ts
1385
+ var src_exports2 = {};
1386
+ __export(src_exports2, {
1387
+ AesKey: () => AesKey,
1388
+ BASE58_DID_PREFIX: () => BASE58_DID_PREFIX,
1389
+ DID_KEY_BASE58_PREFIX: () => DID_KEY_BASE58_PREFIX,
1390
+ EcdsaKeypair: () => EcdsaKeypair,
1391
+ P256_DID_PREFIX: () => P256_DID_PREFIX,
1392
+ P256_JWT_ALG: () => P256_JWT_ALG,
1393
+ SECP256K1_DID_PREFIX: () => SECP256K1_DID_PREFIX,
1394
+ SECP256K1_JWT_ALG: () => SECP256K1_JWT_ALG,
1395
+ Secp256k1Keypair: () => Secp256k1Keypair,
1396
+ formatDidKey: () => formatDidKey,
1397
+ multibaseToBytes: () => multibaseToBytes,
1398
+ p256Plugin: () => p256Plugin,
1399
+ parseDidKey: () => parseDidKey,
1400
+ randomBytes: () => randomBytes,
1401
+ randomIV: () => randomIV,
1402
+ randomStr: () => randomStr,
1403
+ secp256k1Plugin: () => secp256k1Plugin,
1404
+ sha256: () => sha2562,
1405
+ sha256Stream: () => sha256Stream,
1406
+ verifyDidSig: () => verifyDidSig3
1407
+ });
1408
+ module.exports = __toCommonJS(src_exports2);
1409
+
1410
+ // ../../node_modules/one-webcrypto/node.mjs
1411
+ var import_crypto = __toESM(require("crypto"), 1);
1412
+ var webcrypto = import_crypto.default.webcrypto;
1413
+
1414
+ // ../../node_modules/uint8arrays/esm/src/concat.js
1415
+ function concat(arrays, length2) {
1416
+ if (!length2) {
1417
+ length2 = arrays.reduce((acc, curr) => acc + curr.length, 0);
1418
+ }
1419
+ const output = new Uint8Array(length2);
1420
+ let offset = 0;
1421
+ for (const arr of arrays) {
1422
+ output.set(arr, offset);
1423
+ offset += arr.length;
1424
+ }
1425
+ return output;
1426
+ }
1427
+
1428
+ // ../../node_modules/uint8arrays/esm/src/equals.js
1429
+ function equals(a, b) {
1430
+ if (a === b) {
1431
+ return true;
1432
+ }
1433
+ if (a.byteLength !== b.byteLength) {
1434
+ return false;
1435
+ }
1436
+ for (let i = 0; i < a.byteLength; i++) {
1437
+ if (a[i] !== b[i]) {
1438
+ return false;
1439
+ }
1440
+ }
1441
+ return true;
1442
+ }
1443
+
1444
+ // ../../node_modules/multiformats/esm/src/bases/identity.js
1445
+ var identity_exports = {};
1446
+ __export(identity_exports, {
1447
+ identity: () => identity
1448
+ });
1449
+
1450
+ // ../../node_modules/multiformats/esm/vendor/base-x.js
1451
+ function base(ALPHABET, name2) {
1452
+ if (ALPHABET.length >= 255) {
1453
+ throw new TypeError("Alphabet too long");
1454
+ }
1455
+ var BASE_MAP = new Uint8Array(256);
1456
+ for (var j = 0; j < BASE_MAP.length; j++) {
1457
+ BASE_MAP[j] = 255;
1458
+ }
1459
+ for (var i = 0; i < ALPHABET.length; i++) {
1460
+ var x = ALPHABET.charAt(i);
1461
+ var xc = x.charCodeAt(0);
1462
+ if (BASE_MAP[xc] !== 255) {
1463
+ throw new TypeError(x + " is ambiguous");
1464
+ }
1465
+ BASE_MAP[xc] = i;
1466
+ }
1467
+ var BASE = ALPHABET.length;
1468
+ var LEADER = ALPHABET.charAt(0);
1469
+ var FACTOR = Math.log(BASE) / Math.log(256);
1470
+ var iFACTOR = Math.log(256) / Math.log(BASE);
1471
+ function encode5(source) {
1472
+ if (source instanceof Uint8Array)
1473
+ ;
1474
+ else if (ArrayBuffer.isView(source)) {
1475
+ source = new Uint8Array(source.buffer, source.byteOffset, source.byteLength);
1476
+ } else if (Array.isArray(source)) {
1477
+ source = Uint8Array.from(source);
1478
+ }
1479
+ if (!(source instanceof Uint8Array)) {
1480
+ throw new TypeError("Expected Uint8Array");
1481
+ }
1482
+ if (source.length === 0) {
1483
+ return "";
1484
+ }
1485
+ var zeroes = 0;
1486
+ var length2 = 0;
1487
+ var pbegin = 0;
1488
+ var pend = source.length;
1489
+ while (pbegin !== pend && source[pbegin] === 0) {
1490
+ pbegin++;
1491
+ zeroes++;
1492
+ }
1493
+ var size = (pend - pbegin) * iFACTOR + 1 >>> 0;
1494
+ var b58 = new Uint8Array(size);
1495
+ while (pbegin !== pend) {
1496
+ var carry = source[pbegin];
1497
+ var i2 = 0;
1498
+ for (var it1 = size - 1; (carry !== 0 || i2 < length2) && it1 !== -1; it1--, i2++) {
1499
+ carry += 256 * b58[it1] >>> 0;
1500
+ b58[it1] = carry % BASE >>> 0;
1501
+ carry = carry / BASE >>> 0;
1502
+ }
1503
+ if (carry !== 0) {
1504
+ throw new Error("Non-zero carry");
1505
+ }
1506
+ length2 = i2;
1507
+ pbegin++;
1508
+ }
1509
+ var it2 = size - length2;
1510
+ while (it2 !== size && b58[it2] === 0) {
1511
+ it2++;
1512
+ }
1513
+ var str = LEADER.repeat(zeroes);
1514
+ for (; it2 < size; ++it2) {
1515
+ str += ALPHABET.charAt(b58[it2]);
1516
+ }
1517
+ return str;
1518
+ }
1519
+ function decodeUnsafe(source) {
1520
+ if (typeof source !== "string") {
1521
+ throw new TypeError("Expected String");
1522
+ }
1523
+ if (source.length === 0) {
1524
+ return new Uint8Array();
1525
+ }
1526
+ var psz = 0;
1527
+ if (source[psz] === " ") {
1528
+ return;
1529
+ }
1530
+ var zeroes = 0;
1531
+ var length2 = 0;
1532
+ while (source[psz] === LEADER) {
1533
+ zeroes++;
1534
+ psz++;
1535
+ }
1536
+ var size = (source.length - psz) * FACTOR + 1 >>> 0;
1537
+ var b256 = new Uint8Array(size);
1538
+ while (source[psz]) {
1539
+ var carry = BASE_MAP[source.charCodeAt(psz)];
1540
+ if (carry === 255) {
1541
+ return;
1542
+ }
1543
+ var i2 = 0;
1544
+ for (var it3 = size - 1; (carry !== 0 || i2 < length2) && it3 !== -1; it3--, i2++) {
1545
+ carry += BASE * b256[it3] >>> 0;
1546
+ b256[it3] = carry % 256 >>> 0;
1547
+ carry = carry / 256 >>> 0;
1548
+ }
1549
+ if (carry !== 0) {
1550
+ throw new Error("Non-zero carry");
1551
+ }
1552
+ length2 = i2;
1553
+ psz++;
1554
+ }
1555
+ if (source[psz] === " ") {
1556
+ return;
1557
+ }
1558
+ var it4 = size - length2;
1559
+ while (it4 !== size && b256[it4] === 0) {
1560
+ it4++;
1561
+ }
1562
+ var vch = new Uint8Array(zeroes + (size - it4));
1563
+ var j2 = zeroes;
1564
+ while (it4 !== size) {
1565
+ vch[j2++] = b256[it4++];
1566
+ }
1567
+ return vch;
1568
+ }
1569
+ function decode6(string2) {
1570
+ var buffer = decodeUnsafe(string2);
1571
+ if (buffer) {
1572
+ return buffer;
1573
+ }
1574
+ throw new Error(`Non-${name2} character`);
1575
+ }
1576
+ return {
1577
+ encode: encode5,
1578
+ decodeUnsafe,
1579
+ decode: decode6
1580
+ };
1581
+ }
1582
+ var src = base;
1583
+ var _brrp__multiformats_scope_baseX = src;
1584
+ var base_x_default = _brrp__multiformats_scope_baseX;
1585
+
1586
+ // ../../node_modules/multiformats/esm/src/bytes.js
1587
+ var empty = new Uint8Array(0);
1588
+ var equals2 = (aa, bb) => {
1589
+ if (aa === bb)
1590
+ return true;
1591
+ if (aa.byteLength !== bb.byteLength) {
1592
+ return false;
1593
+ }
1594
+ for (let ii = 0; ii < aa.byteLength; ii++) {
1595
+ if (aa[ii] !== bb[ii]) {
1596
+ return false;
1597
+ }
1598
+ }
1599
+ return true;
1600
+ };
1601
+ var coerce = (o) => {
1602
+ if (o instanceof Uint8Array && o.constructor.name === "Uint8Array")
1603
+ return o;
1604
+ if (o instanceof ArrayBuffer)
1605
+ return new Uint8Array(o);
1606
+ if (ArrayBuffer.isView(o)) {
1607
+ return new Uint8Array(o.buffer, o.byteOffset, o.byteLength);
1608
+ }
1609
+ throw new Error("Unknown type, must be binary type");
1610
+ };
1611
+ var fromString = (str) => new TextEncoder().encode(str);
1612
+ var toString = (b) => new TextDecoder().decode(b);
1613
+
1614
+ // ../../node_modules/multiformats/esm/src/bases/base.js
1615
+ var Encoder = class {
1616
+ constructor(name2, prefix, baseEncode) {
1617
+ this.name = name2;
1618
+ this.prefix = prefix;
1619
+ this.baseEncode = baseEncode;
1620
+ }
1621
+ encode(bytes) {
1622
+ if (bytes instanceof Uint8Array) {
1623
+ return `${this.prefix}${this.baseEncode(bytes)}`;
1624
+ } else {
1625
+ throw Error("Unknown type, must be binary type");
1626
+ }
1627
+ }
1628
+ };
1629
+ var Decoder = class {
1630
+ constructor(name2, prefix, baseDecode) {
1631
+ this.name = name2;
1632
+ this.prefix = prefix;
1633
+ if (prefix.codePointAt(0) === void 0) {
1634
+ throw new Error("Invalid prefix character");
1635
+ }
1636
+ this.prefixCodePoint = prefix.codePointAt(0);
1637
+ this.baseDecode = baseDecode;
1638
+ }
1639
+ decode(text) {
1640
+ if (typeof text === "string") {
1641
+ if (text.codePointAt(0) !== this.prefixCodePoint) {
1642
+ throw Error(`Unable to decode multibase string ${JSON.stringify(text)}, ${this.name} decoder only supports inputs prefixed with ${this.prefix}`);
1643
+ }
1644
+ return this.baseDecode(text.slice(this.prefix.length));
1645
+ } else {
1646
+ throw Error("Can only multibase decode strings");
1647
+ }
1648
+ }
1649
+ or(decoder) {
1650
+ return or(this, decoder);
1651
+ }
1652
+ };
1653
+ var ComposedDecoder = class {
1654
+ constructor(decoders) {
1655
+ this.decoders = decoders;
1656
+ }
1657
+ or(decoder) {
1658
+ return or(this, decoder);
1659
+ }
1660
+ decode(input) {
1661
+ const prefix = input[0];
1662
+ const decoder = this.decoders[prefix];
1663
+ if (decoder) {
1664
+ return decoder.decode(input);
1665
+ } else {
1666
+ throw RangeError(`Unable to decode multibase string ${JSON.stringify(input)}, only inputs prefixed with ${Object.keys(this.decoders)} are supported`);
1667
+ }
1668
+ }
1669
+ };
1670
+ var or = (left, right) => new ComposedDecoder({
1671
+ ...left.decoders || { [left.prefix]: left },
1672
+ ...right.decoders || { [right.prefix]: right }
1673
+ });
1674
+ var Codec = class {
1675
+ constructor(name2, prefix, baseEncode, baseDecode) {
1676
+ this.name = name2;
1677
+ this.prefix = prefix;
1678
+ this.baseEncode = baseEncode;
1679
+ this.baseDecode = baseDecode;
1680
+ this.encoder = new Encoder(name2, prefix, baseEncode);
1681
+ this.decoder = new Decoder(name2, prefix, baseDecode);
1682
+ }
1683
+ encode(input) {
1684
+ return this.encoder.encode(input);
1685
+ }
1686
+ decode(input) {
1687
+ return this.decoder.decode(input);
1688
+ }
1689
+ };
1690
+ var from = ({ name: name2, prefix, encode: encode5, decode: decode6 }) => new Codec(name2, prefix, encode5, decode6);
1691
+ var baseX = ({ prefix, name: name2, alphabet: alphabet2 }) => {
1692
+ const { encode: encode5, decode: decode6 } = base_x_default(alphabet2, name2);
1693
+ return from({
1694
+ prefix,
1695
+ name: name2,
1696
+ encode: encode5,
1697
+ decode: (text) => coerce(decode6(text))
1698
+ });
1699
+ };
1700
+ var decode = (string2, alphabet2, bitsPerChar, name2) => {
1701
+ const codes = {};
1702
+ for (let i = 0; i < alphabet2.length; ++i) {
1703
+ codes[alphabet2[i]] = i;
1704
+ }
1705
+ let end = string2.length;
1706
+ while (string2[end - 1] === "=") {
1707
+ --end;
1708
+ }
1709
+ const out = new Uint8Array(end * bitsPerChar / 8 | 0);
1710
+ let bits = 0;
1711
+ let buffer = 0;
1712
+ let written = 0;
1713
+ for (let i = 0; i < end; ++i) {
1714
+ const value = codes[string2[i]];
1715
+ if (value === void 0) {
1716
+ throw new SyntaxError(`Non-${name2} character`);
1717
+ }
1718
+ buffer = buffer << bitsPerChar | value;
1719
+ bits += bitsPerChar;
1720
+ if (bits >= 8) {
1721
+ bits -= 8;
1722
+ out[written++] = 255 & buffer >> bits;
1723
+ }
1724
+ }
1725
+ if (bits >= bitsPerChar || 255 & buffer << 8 - bits) {
1726
+ throw new SyntaxError("Unexpected end of data");
1727
+ }
1728
+ return out;
1729
+ };
1730
+ var encode = (data, alphabet2, bitsPerChar) => {
1731
+ const pad = alphabet2[alphabet2.length - 1] === "=";
1732
+ const mask = (1 << bitsPerChar) - 1;
1733
+ let out = "";
1734
+ let bits = 0;
1735
+ let buffer = 0;
1736
+ for (let i = 0; i < data.length; ++i) {
1737
+ buffer = buffer << 8 | data[i];
1738
+ bits += 8;
1739
+ while (bits > bitsPerChar) {
1740
+ bits -= bitsPerChar;
1741
+ out += alphabet2[mask & buffer >> bits];
1742
+ }
1743
+ }
1744
+ if (bits) {
1745
+ out += alphabet2[mask & buffer << bitsPerChar - bits];
1746
+ }
1747
+ if (pad) {
1748
+ while (out.length * bitsPerChar & 7) {
1749
+ out += "=";
1750
+ }
1751
+ }
1752
+ return out;
1753
+ };
1754
+ var rfc4648 = ({ name: name2, prefix, bitsPerChar, alphabet: alphabet2 }) => {
1755
+ return from({
1756
+ prefix,
1757
+ name: name2,
1758
+ encode(input) {
1759
+ return encode(input, alphabet2, bitsPerChar);
1760
+ },
1761
+ decode(input) {
1762
+ return decode(input, alphabet2, bitsPerChar, name2);
1763
+ }
1764
+ });
1765
+ };
1766
+
1767
+ // ../../node_modules/multiformats/esm/src/bases/identity.js
1768
+ var identity = from({
1769
+ prefix: "\0",
1770
+ name: "identity",
1771
+ encode: (buf) => toString(buf),
1772
+ decode: (str) => fromString(str)
1773
+ });
1774
+
1775
+ // ../../node_modules/multiformats/esm/src/bases/base2.js
1776
+ var base2_exports = {};
1777
+ __export(base2_exports, {
1778
+ base2: () => base2
1779
+ });
1780
+ var base2 = rfc4648({
1781
+ prefix: "0",
1782
+ name: "base2",
1783
+ alphabet: "01",
1784
+ bitsPerChar: 1
1785
+ });
1786
+
1787
+ // ../../node_modules/multiformats/esm/src/bases/base8.js
1788
+ var base8_exports = {};
1789
+ __export(base8_exports, {
1790
+ base8: () => base8
1791
+ });
1792
+ var base8 = rfc4648({
1793
+ prefix: "7",
1794
+ name: "base8",
1795
+ alphabet: "01234567",
1796
+ bitsPerChar: 3
1797
+ });
1798
+
1799
+ // ../../node_modules/multiformats/esm/src/bases/base10.js
1800
+ var base10_exports = {};
1801
+ __export(base10_exports, {
1802
+ base10: () => base10
1803
+ });
1804
+ var base10 = baseX({
1805
+ prefix: "9",
1806
+ name: "base10",
1807
+ alphabet: "0123456789"
1808
+ });
1809
+
1810
+ // ../../node_modules/multiformats/esm/src/bases/base16.js
1811
+ var base16_exports = {};
1812
+ __export(base16_exports, {
1813
+ base16: () => base16,
1814
+ base16upper: () => base16upper
1815
+ });
1816
+ var base16 = rfc4648({
1817
+ prefix: "f",
1818
+ name: "base16",
1819
+ alphabet: "0123456789abcdef",
1820
+ bitsPerChar: 4
1821
+ });
1822
+ var base16upper = rfc4648({
1823
+ prefix: "F",
1824
+ name: "base16upper",
1825
+ alphabet: "0123456789ABCDEF",
1826
+ bitsPerChar: 4
1827
+ });
1828
+
1829
+ // ../../node_modules/multiformats/esm/src/bases/base32.js
1830
+ var base32_exports = {};
1831
+ __export(base32_exports, {
1832
+ base32: () => base32,
1833
+ base32hex: () => base32hex,
1834
+ base32hexpad: () => base32hexpad,
1835
+ base32hexpadupper: () => base32hexpadupper,
1836
+ base32hexupper: () => base32hexupper,
1837
+ base32pad: () => base32pad,
1838
+ base32padupper: () => base32padupper,
1839
+ base32upper: () => base32upper,
1840
+ base32z: () => base32z
1841
+ });
1842
+ var base32 = rfc4648({
1843
+ prefix: "b",
1844
+ name: "base32",
1845
+ alphabet: "abcdefghijklmnopqrstuvwxyz234567",
1846
+ bitsPerChar: 5
1847
+ });
1848
+ var base32upper = rfc4648({
1849
+ prefix: "B",
1850
+ name: "base32upper",
1851
+ alphabet: "ABCDEFGHIJKLMNOPQRSTUVWXYZ234567",
1852
+ bitsPerChar: 5
1853
+ });
1854
+ var base32pad = rfc4648({
1855
+ prefix: "c",
1856
+ name: "base32pad",
1857
+ alphabet: "abcdefghijklmnopqrstuvwxyz234567=",
1858
+ bitsPerChar: 5
1859
+ });
1860
+ var base32padupper = rfc4648({
1861
+ prefix: "C",
1862
+ name: "base32padupper",
1863
+ alphabet: "ABCDEFGHIJKLMNOPQRSTUVWXYZ234567=",
1864
+ bitsPerChar: 5
1865
+ });
1866
+ var base32hex = rfc4648({
1867
+ prefix: "v",
1868
+ name: "base32hex",
1869
+ alphabet: "0123456789abcdefghijklmnopqrstuv",
1870
+ bitsPerChar: 5
1871
+ });
1872
+ var base32hexupper = rfc4648({
1873
+ prefix: "V",
1874
+ name: "base32hexupper",
1875
+ alphabet: "0123456789ABCDEFGHIJKLMNOPQRSTUV",
1876
+ bitsPerChar: 5
1877
+ });
1878
+ var base32hexpad = rfc4648({
1879
+ prefix: "t",
1880
+ name: "base32hexpad",
1881
+ alphabet: "0123456789abcdefghijklmnopqrstuv=",
1882
+ bitsPerChar: 5
1883
+ });
1884
+ var base32hexpadupper = rfc4648({
1885
+ prefix: "T",
1886
+ name: "base32hexpadupper",
1887
+ alphabet: "0123456789ABCDEFGHIJKLMNOPQRSTUV=",
1888
+ bitsPerChar: 5
1889
+ });
1890
+ var base32z = rfc4648({
1891
+ prefix: "h",
1892
+ name: "base32z",
1893
+ alphabet: "ybndrfg8ejkmcpqxot1uwisza345h769",
1894
+ bitsPerChar: 5
1895
+ });
1896
+
1897
+ // ../../node_modules/multiformats/esm/src/bases/base36.js
1898
+ var base36_exports = {};
1899
+ __export(base36_exports, {
1900
+ base36: () => base36,
1901
+ base36upper: () => base36upper
1902
+ });
1903
+ var base36 = baseX({
1904
+ prefix: "k",
1905
+ name: "base36",
1906
+ alphabet: "0123456789abcdefghijklmnopqrstuvwxyz"
1907
+ });
1908
+ var base36upper = baseX({
1909
+ prefix: "K",
1910
+ name: "base36upper",
1911
+ alphabet: "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"
1912
+ });
1913
+
1914
+ // ../../node_modules/multiformats/esm/src/bases/base58.js
1915
+ var base58_exports = {};
1916
+ __export(base58_exports, {
1917
+ base58btc: () => base58btc,
1918
+ base58flickr: () => base58flickr
1919
+ });
1920
+ var base58btc = baseX({
1921
+ name: "base58btc",
1922
+ prefix: "z",
1923
+ alphabet: "123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"
1924
+ });
1925
+ var base58flickr = baseX({
1926
+ name: "base58flickr",
1927
+ prefix: "Z",
1928
+ alphabet: "123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ"
1929
+ });
1930
+
1931
+ // ../../node_modules/multiformats/esm/src/bases/base64.js
1932
+ var base64_exports = {};
1933
+ __export(base64_exports, {
1934
+ base64: () => base64,
1935
+ base64pad: () => base64pad,
1936
+ base64url: () => base64url,
1937
+ base64urlpad: () => base64urlpad
1938
+ });
1939
+ var base64 = rfc4648({
1940
+ prefix: "m",
1941
+ name: "base64",
1942
+ alphabet: "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",
1943
+ bitsPerChar: 6
1944
+ });
1945
+ var base64pad = rfc4648({
1946
+ prefix: "M",
1947
+ name: "base64pad",
1948
+ alphabet: "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",
1949
+ bitsPerChar: 6
1950
+ });
1951
+ var base64url = rfc4648({
1952
+ prefix: "u",
1953
+ name: "base64url",
1954
+ alphabet: "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_",
1955
+ bitsPerChar: 6
1956
+ });
1957
+ var base64urlpad = rfc4648({
1958
+ prefix: "U",
1959
+ name: "base64urlpad",
1960
+ alphabet: "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_=",
1961
+ bitsPerChar: 6
1962
+ });
1963
+
1964
+ // ../../node_modules/multiformats/esm/src/bases/base256emoji.js
1965
+ var base256emoji_exports = {};
1966
+ __export(base256emoji_exports, {
1967
+ base256emoji: () => base256emoji
1968
+ });
1969
+ var alphabet = Array.from("\u{1F680}\u{1FA90}\u2604\u{1F6F0}\u{1F30C}\u{1F311}\u{1F312}\u{1F313}\u{1F314}\u{1F315}\u{1F316}\u{1F317}\u{1F318}\u{1F30D}\u{1F30F}\u{1F30E}\u{1F409}\u2600\u{1F4BB}\u{1F5A5}\u{1F4BE}\u{1F4BF}\u{1F602}\u2764\u{1F60D}\u{1F923}\u{1F60A}\u{1F64F}\u{1F495}\u{1F62D}\u{1F618}\u{1F44D}\u{1F605}\u{1F44F}\u{1F601}\u{1F525}\u{1F970}\u{1F494}\u{1F496}\u{1F499}\u{1F622}\u{1F914}\u{1F606}\u{1F644}\u{1F4AA}\u{1F609}\u263A\u{1F44C}\u{1F917}\u{1F49C}\u{1F614}\u{1F60E}\u{1F607}\u{1F339}\u{1F926}\u{1F389}\u{1F49E}\u270C\u2728\u{1F937}\u{1F631}\u{1F60C}\u{1F338}\u{1F64C}\u{1F60B}\u{1F497}\u{1F49A}\u{1F60F}\u{1F49B}\u{1F642}\u{1F493}\u{1F929}\u{1F604}\u{1F600}\u{1F5A4}\u{1F603}\u{1F4AF}\u{1F648}\u{1F447}\u{1F3B6}\u{1F612}\u{1F92D}\u2763\u{1F61C}\u{1F48B}\u{1F440}\u{1F62A}\u{1F611}\u{1F4A5}\u{1F64B}\u{1F61E}\u{1F629}\u{1F621}\u{1F92A}\u{1F44A}\u{1F973}\u{1F625}\u{1F924}\u{1F449}\u{1F483}\u{1F633}\u270B\u{1F61A}\u{1F61D}\u{1F634}\u{1F31F}\u{1F62C}\u{1F643}\u{1F340}\u{1F337}\u{1F63B}\u{1F613}\u2B50\u2705\u{1F97A}\u{1F308}\u{1F608}\u{1F918}\u{1F4A6}\u2714\u{1F623}\u{1F3C3}\u{1F490}\u2639\u{1F38A}\u{1F498}\u{1F620}\u261D\u{1F615}\u{1F33A}\u{1F382}\u{1F33B}\u{1F610}\u{1F595}\u{1F49D}\u{1F64A}\u{1F639}\u{1F5E3}\u{1F4AB}\u{1F480}\u{1F451}\u{1F3B5}\u{1F91E}\u{1F61B}\u{1F534}\u{1F624}\u{1F33C}\u{1F62B}\u26BD\u{1F919}\u2615\u{1F3C6}\u{1F92B}\u{1F448}\u{1F62E}\u{1F646}\u{1F37B}\u{1F343}\u{1F436}\u{1F481}\u{1F632}\u{1F33F}\u{1F9E1}\u{1F381}\u26A1\u{1F31E}\u{1F388}\u274C\u270A\u{1F44B}\u{1F630}\u{1F928}\u{1F636}\u{1F91D}\u{1F6B6}\u{1F4B0}\u{1F353}\u{1F4A2}\u{1F91F}\u{1F641}\u{1F6A8}\u{1F4A8}\u{1F92C}\u2708\u{1F380}\u{1F37A}\u{1F913}\u{1F619}\u{1F49F}\u{1F331}\u{1F616}\u{1F476}\u{1F974}\u25B6\u27A1\u2753\u{1F48E}\u{1F4B8}\u2B07\u{1F628}\u{1F31A}\u{1F98B}\u{1F637}\u{1F57A}\u26A0\u{1F645}\u{1F61F}\u{1F635}\u{1F44E}\u{1F932}\u{1F920}\u{1F927}\u{1F4CC}\u{1F535}\u{1F485}\u{1F9D0}\u{1F43E}\u{1F352}\u{1F617}\u{1F911}\u{1F30A}\u{1F92F}\u{1F437}\u260E\u{1F4A7}\u{1F62F}\u{1F486}\u{1F446}\u{1F3A4}\u{1F647}\u{1F351}\u2744\u{1F334}\u{1F4A3}\u{1F438}\u{1F48C}\u{1F4CD}\u{1F940}\u{1F922}\u{1F445}\u{1F4A1}\u{1F4A9}\u{1F450}\u{1F4F8}\u{1F47B}\u{1F910}\u{1F92E}\u{1F3BC}\u{1F975}\u{1F6A9}\u{1F34E}\u{1F34A}\u{1F47C}\u{1F48D}\u{1F4E3}\u{1F942}");
1970
+ var alphabetBytesToChars = alphabet.reduce((p, c, i) => {
1971
+ p[i] = c;
1972
+ return p;
1973
+ }, []);
1974
+ var alphabetCharsToBytes = alphabet.reduce((p, c, i) => {
1975
+ p[c.codePointAt(0)] = i;
1976
+ return p;
1977
+ }, []);
1978
+ function encode2(data) {
1979
+ return data.reduce((p, c) => {
1980
+ p += alphabetBytesToChars[c];
1981
+ return p;
1982
+ }, "");
1983
+ }
1984
+ function decode2(str) {
1985
+ const byts = [];
1986
+ for (const char of str) {
1987
+ const byt = alphabetCharsToBytes[char.codePointAt(0)];
1988
+ if (byt === void 0) {
1989
+ throw new Error(`Non-base256emoji character: ${char}`);
1990
+ }
1991
+ byts.push(byt);
1992
+ }
1993
+ return new Uint8Array(byts);
1994
+ }
1995
+ var base256emoji = from({
1996
+ prefix: "\u{1F680}",
1997
+ name: "base256emoji",
1998
+ encode: encode2,
1999
+ decode: decode2
2000
+ });
2001
+
2002
+ // ../../node_modules/multiformats/esm/src/hashes/sha2.js
2003
+ var sha2_exports = {};
2004
+ __export(sha2_exports, {
2005
+ sha256: () => sha256,
2006
+ sha512: () => sha512
2007
+ });
2008
+ var import_crypto2 = __toESM(require("crypto"), 1);
2009
+
2010
+ // ../../node_modules/multiformats/esm/vendor/varint.js
2011
+ var encode_1 = encode3;
2012
+ var MSB = 128;
2013
+ var REST = 127;
2014
+ var MSBALL = ~REST;
2015
+ var INT = Math.pow(2, 31);
2016
+ function encode3(num, out, offset) {
2017
+ out = out || [];
2018
+ offset = offset || 0;
2019
+ var oldOffset = offset;
2020
+ while (num >= INT) {
2021
+ out[offset++] = num & 255 | MSB;
2022
+ num /= 128;
2023
+ }
2024
+ while (num & MSBALL) {
2025
+ out[offset++] = num & 255 | MSB;
2026
+ num >>>= 7;
2027
+ }
2028
+ out[offset] = num | 0;
2029
+ encode3.bytes = offset - oldOffset + 1;
2030
+ return out;
2031
+ }
2032
+ var decode3 = read;
2033
+ var MSB$1 = 128;
2034
+ var REST$1 = 127;
2035
+ function read(buf, offset) {
2036
+ var res = 0, offset = offset || 0, shift = 0, counter = offset, b, l = buf.length;
2037
+ do {
2038
+ if (counter >= l) {
2039
+ read.bytes = 0;
2040
+ throw new RangeError("Could not decode varint");
2041
+ }
2042
+ b = buf[counter++];
2043
+ res += shift < 28 ? (b & REST$1) << shift : (b & REST$1) * Math.pow(2, shift);
2044
+ shift += 7;
2045
+ } while (b >= MSB$1);
2046
+ read.bytes = counter - offset;
2047
+ return res;
2048
+ }
2049
+ var N1 = Math.pow(2, 7);
2050
+ var N2 = Math.pow(2, 14);
2051
+ var N3 = Math.pow(2, 21);
2052
+ var N4 = Math.pow(2, 28);
2053
+ var N5 = Math.pow(2, 35);
2054
+ var N6 = Math.pow(2, 42);
2055
+ var N7 = Math.pow(2, 49);
2056
+ var N8 = Math.pow(2, 56);
2057
+ var N9 = Math.pow(2, 63);
2058
+ var length = function(value) {
2059
+ return value < N1 ? 1 : value < N2 ? 2 : value < N3 ? 3 : value < N4 ? 4 : value < N5 ? 5 : value < N6 ? 6 : value < N7 ? 7 : value < N8 ? 8 : value < N9 ? 9 : 10;
2060
+ };
2061
+ var varint = {
2062
+ encode: encode_1,
2063
+ decode: decode3,
2064
+ encodingLength: length
2065
+ };
2066
+ var _brrp_varint = varint;
2067
+ var varint_default = _brrp_varint;
2068
+
2069
+ // ../../node_modules/multiformats/esm/src/varint.js
2070
+ var decode4 = (data, offset = 0) => {
2071
+ const code2 = varint_default.decode(data, offset);
2072
+ return [
2073
+ code2,
2074
+ varint_default.decode.bytes
2075
+ ];
2076
+ };
2077
+ var encodeTo = (int, target, offset = 0) => {
2078
+ varint_default.encode(int, target, offset);
2079
+ return target;
2080
+ };
2081
+ var encodingLength = (int) => {
2082
+ return varint_default.encodingLength(int);
2083
+ };
2084
+
2085
+ // ../../node_modules/multiformats/esm/src/hashes/digest.js
2086
+ var create = (code2, digest2) => {
2087
+ const size = digest2.byteLength;
2088
+ const sizeOffset = encodingLength(code2);
2089
+ const digestOffset = sizeOffset + encodingLength(size);
2090
+ const bytes = new Uint8Array(digestOffset + size);
2091
+ encodeTo(code2, bytes, 0);
2092
+ encodeTo(size, bytes, sizeOffset);
2093
+ bytes.set(digest2, digestOffset);
2094
+ return new Digest(code2, size, digest2, bytes);
2095
+ };
2096
+ var decode5 = (multihash) => {
2097
+ const bytes = coerce(multihash);
2098
+ const [code2, sizeOffset] = decode4(bytes);
2099
+ const [size, digestOffset] = decode4(bytes.subarray(sizeOffset));
2100
+ const digest2 = bytes.subarray(sizeOffset + digestOffset);
2101
+ if (digest2.byteLength !== size) {
2102
+ throw new Error("Incorrect length");
2103
+ }
2104
+ return new Digest(code2, size, digest2, bytes);
2105
+ };
2106
+ var equals3 = (a, b) => {
2107
+ if (a === b) {
2108
+ return true;
2109
+ } else {
2110
+ return a.code === b.code && a.size === b.size && equals2(a.bytes, b.bytes);
2111
+ }
2112
+ };
2113
+ var Digest = class {
2114
+ constructor(code2, size, digest2, bytes) {
2115
+ this.code = code2;
2116
+ this.size = size;
2117
+ this.digest = digest2;
2118
+ this.bytes = bytes;
2119
+ }
2120
+ };
2121
+
2122
+ // ../../node_modules/multiformats/esm/src/hashes/hasher.js
2123
+ var from2 = ({ name: name2, code: code2, encode: encode5 }) => new Hasher(name2, code2, encode5);
2124
+ var Hasher = class {
2125
+ constructor(name2, code2, encode5) {
2126
+ this.name = name2;
2127
+ this.code = code2;
2128
+ this.encode = encode5;
2129
+ }
2130
+ digest(input) {
2131
+ if (input instanceof Uint8Array) {
2132
+ const result = this.encode(input);
2133
+ return result instanceof Uint8Array ? create(this.code, result) : result.then((digest2) => create(this.code, digest2));
2134
+ } else {
2135
+ throw Error("Unknown type, must be binary type");
2136
+ }
2137
+ }
2138
+ };
2139
+
2140
+ // ../../node_modules/multiformats/esm/src/hashes/sha2.js
2141
+ var sha256 = from2({
2142
+ name: "sha2-256",
2143
+ code: 18,
2144
+ encode: (input) => coerce(import_crypto2.default.createHash("sha256").update(input).digest())
2145
+ });
2146
+ var sha512 = from2({
2147
+ name: "sha2-512",
2148
+ code: 19,
2149
+ encode: (input) => coerce(import_crypto2.default.createHash("sha512").update(input).digest())
2150
+ });
2151
+
2152
+ // ../../node_modules/multiformats/esm/src/hashes/identity.js
2153
+ var identity_exports2 = {};
2154
+ __export(identity_exports2, {
2155
+ identity: () => identity2
2156
+ });
2157
+ var code = 0;
2158
+ var name = "identity";
2159
+ var encode4 = coerce;
2160
+ var digest = (input) => create(code, encode4(input));
2161
+ var identity2 = {
2162
+ code,
2163
+ name,
2164
+ encode: encode4,
2165
+ digest
2166
+ };
2167
+
2168
+ // ../../node_modules/multiformats/esm/src/codecs/json.js
2169
+ var textEncoder = new TextEncoder();
2170
+ var textDecoder = new TextDecoder();
2171
+
2172
+ // ../../node_modules/multiformats/esm/src/cid.js
2173
+ var CID = class {
2174
+ constructor(version2, code2, multihash, bytes) {
2175
+ this.code = code2;
2176
+ this.version = version2;
2177
+ this.multihash = multihash;
2178
+ this.bytes = bytes;
2179
+ this.byteOffset = bytes.byteOffset;
2180
+ this.byteLength = bytes.byteLength;
2181
+ this.asCID = this;
2182
+ this._baseCache = /* @__PURE__ */ new Map();
2183
+ Object.defineProperties(this, {
2184
+ byteOffset: hidden,
2185
+ byteLength: hidden,
2186
+ code: readonly,
2187
+ version: readonly,
2188
+ multihash: readonly,
2189
+ bytes: readonly,
2190
+ _baseCache: hidden,
2191
+ asCID: hidden
2192
+ });
2193
+ }
2194
+ toV0() {
2195
+ switch (this.version) {
2196
+ case 0: {
2197
+ return this;
2198
+ }
2199
+ default: {
2200
+ const { code: code2, multihash } = this;
2201
+ if (code2 !== DAG_PB_CODE) {
2202
+ throw new Error("Cannot convert a non dag-pb CID to CIDv0");
2203
+ }
2204
+ if (multihash.code !== SHA_256_CODE) {
2205
+ throw new Error("Cannot convert non sha2-256 multihash CID to CIDv0");
2206
+ }
2207
+ return CID.createV0(multihash);
2208
+ }
2209
+ }
2210
+ }
2211
+ toV1() {
2212
+ switch (this.version) {
2213
+ case 0: {
2214
+ const { code: code2, digest: digest2 } = this.multihash;
2215
+ const multihash = create(code2, digest2);
2216
+ return CID.createV1(this.code, multihash);
2217
+ }
2218
+ case 1: {
2219
+ return this;
2220
+ }
2221
+ default: {
2222
+ throw Error(`Can not convert CID version ${this.version} to version 0. This is a bug please report`);
2223
+ }
2224
+ }
2225
+ }
2226
+ equals(other) {
2227
+ return other && this.code === other.code && this.version === other.version && equals3(this.multihash, other.multihash);
2228
+ }
2229
+ toString(base3) {
2230
+ const { bytes, version: version2, _baseCache } = this;
2231
+ switch (version2) {
2232
+ case 0:
2233
+ return toStringV0(bytes, _baseCache, base3 || base58btc.encoder);
2234
+ default:
2235
+ return toStringV1(bytes, _baseCache, base3 || base32.encoder);
2236
+ }
2237
+ }
2238
+ toJSON() {
2239
+ return {
2240
+ code: this.code,
2241
+ version: this.version,
2242
+ hash: this.multihash.bytes
2243
+ };
2244
+ }
2245
+ get [Symbol.toStringTag]() {
2246
+ return "CID";
2247
+ }
2248
+ [Symbol.for("nodejs.util.inspect.custom")]() {
2249
+ return "CID(" + this.toString() + ")";
2250
+ }
2251
+ static isCID(value) {
2252
+ deprecate(/^0\.0/, IS_CID_DEPRECATION);
2253
+ return !!(value && (value[cidSymbol] || value.asCID === value));
2254
+ }
2255
+ get toBaseEncodedString() {
2256
+ throw new Error("Deprecated, use .toString()");
2257
+ }
2258
+ get codec() {
2259
+ throw new Error('"codec" property is deprecated, use integer "code" property instead');
2260
+ }
2261
+ get buffer() {
2262
+ throw new Error("Deprecated .buffer property, use .bytes to get Uint8Array instead");
2263
+ }
2264
+ get multibaseName() {
2265
+ throw new Error('"multibaseName" property is deprecated');
2266
+ }
2267
+ get prefix() {
2268
+ throw new Error('"prefix" property is deprecated');
2269
+ }
2270
+ static asCID(value) {
2271
+ if (value instanceof CID) {
2272
+ return value;
2273
+ } else if (value != null && value.asCID === value) {
2274
+ const { version: version2, code: code2, multihash, bytes } = value;
2275
+ return new CID(version2, code2, multihash, bytes || encodeCID(version2, code2, multihash.bytes));
2276
+ } else if (value != null && value[cidSymbol] === true) {
2277
+ const { version: version2, multihash, code: code2 } = value;
2278
+ const digest2 = decode5(multihash);
2279
+ return CID.create(version2, code2, digest2);
2280
+ } else {
2281
+ return null;
2282
+ }
2283
+ }
2284
+ static create(version2, code2, digest2) {
2285
+ if (typeof code2 !== "number") {
2286
+ throw new Error("String codecs are no longer supported");
2287
+ }
2288
+ switch (version2) {
2289
+ case 0: {
2290
+ if (code2 !== DAG_PB_CODE) {
2291
+ throw new Error(`Version 0 CID must use dag-pb (code: ${DAG_PB_CODE}) block encoding`);
2292
+ } else {
2293
+ return new CID(version2, code2, digest2, digest2.bytes);
2294
+ }
2295
+ }
2296
+ case 1: {
2297
+ const bytes = encodeCID(version2, code2, digest2.bytes);
2298
+ return new CID(version2, code2, digest2, bytes);
2299
+ }
2300
+ default: {
2301
+ throw new Error("Invalid version");
2302
+ }
2303
+ }
2304
+ }
2305
+ static createV0(digest2) {
2306
+ return CID.create(0, DAG_PB_CODE, digest2);
2307
+ }
2308
+ static createV1(code2, digest2) {
2309
+ return CID.create(1, code2, digest2);
2310
+ }
2311
+ static decode(bytes) {
2312
+ const [cid, remainder] = CID.decodeFirst(bytes);
2313
+ if (remainder.length) {
2314
+ throw new Error("Incorrect length");
2315
+ }
2316
+ return cid;
2317
+ }
2318
+ static decodeFirst(bytes) {
2319
+ const specs = CID.inspectBytes(bytes);
2320
+ const prefixSize = specs.size - specs.multihashSize;
2321
+ const multihashBytes = coerce(bytes.subarray(prefixSize, prefixSize + specs.multihashSize));
2322
+ if (multihashBytes.byteLength !== specs.multihashSize) {
2323
+ throw new Error("Incorrect length");
2324
+ }
2325
+ const digestBytes = multihashBytes.subarray(specs.multihashSize - specs.digestSize);
2326
+ const digest2 = new Digest(specs.multihashCode, specs.digestSize, digestBytes, multihashBytes);
2327
+ const cid = specs.version === 0 ? CID.createV0(digest2) : CID.createV1(specs.codec, digest2);
2328
+ return [
2329
+ cid,
2330
+ bytes.subarray(specs.size)
2331
+ ];
2332
+ }
2333
+ static inspectBytes(initialBytes) {
2334
+ let offset = 0;
2335
+ const next = () => {
2336
+ const [i, length2] = decode4(initialBytes.subarray(offset));
2337
+ offset += length2;
2338
+ return i;
2339
+ };
2340
+ let version2 = next();
2341
+ let codec = DAG_PB_CODE;
2342
+ if (version2 === 18) {
2343
+ version2 = 0;
2344
+ offset = 0;
2345
+ } else if (version2 === 1) {
2346
+ codec = next();
2347
+ }
2348
+ if (version2 !== 0 && version2 !== 1) {
2349
+ throw new RangeError(`Invalid CID version ${version2}`);
2350
+ }
2351
+ const prefixSize = offset;
2352
+ const multihashCode = next();
2353
+ const digestSize = next();
2354
+ const size = offset + digestSize;
2355
+ const multihashSize = size - prefixSize;
2356
+ return {
2357
+ version: version2,
2358
+ codec,
2359
+ multihashCode,
2360
+ digestSize,
2361
+ multihashSize,
2362
+ size
2363
+ };
2364
+ }
2365
+ static parse(source, base3) {
2366
+ const [prefix, bytes] = parseCIDtoBytes(source, base3);
2367
+ const cid = CID.decode(bytes);
2368
+ cid._baseCache.set(prefix, source);
2369
+ return cid;
2370
+ }
2371
+ };
2372
+ var parseCIDtoBytes = (source, base3) => {
2373
+ switch (source[0]) {
2374
+ case "Q": {
2375
+ const decoder = base3 || base58btc;
2376
+ return [
2377
+ base58btc.prefix,
2378
+ decoder.decode(`${base58btc.prefix}${source}`)
2379
+ ];
2380
+ }
2381
+ case base58btc.prefix: {
2382
+ const decoder = base3 || base58btc;
2383
+ return [
2384
+ base58btc.prefix,
2385
+ decoder.decode(source)
2386
+ ];
2387
+ }
2388
+ case base32.prefix: {
2389
+ const decoder = base3 || base32;
2390
+ return [
2391
+ base32.prefix,
2392
+ decoder.decode(source)
2393
+ ];
2394
+ }
2395
+ default: {
2396
+ if (base3 == null) {
2397
+ throw Error("To parse non base32 or base58btc encoded CID multibase decoder must be provided");
2398
+ }
2399
+ return [
2400
+ source[0],
2401
+ base3.decode(source)
2402
+ ];
2403
+ }
2404
+ }
2405
+ };
2406
+ var toStringV0 = (bytes, cache, base3) => {
2407
+ const { prefix } = base3;
2408
+ if (prefix !== base58btc.prefix) {
2409
+ throw Error(`Cannot string encode V0 in ${base3.name} encoding`);
2410
+ }
2411
+ const cid = cache.get(prefix);
2412
+ if (cid == null) {
2413
+ const cid2 = base3.encode(bytes).slice(1);
2414
+ cache.set(prefix, cid2);
2415
+ return cid2;
2416
+ } else {
2417
+ return cid;
2418
+ }
2419
+ };
2420
+ var toStringV1 = (bytes, cache, base3) => {
2421
+ const { prefix } = base3;
2422
+ const cid = cache.get(prefix);
2423
+ if (cid == null) {
2424
+ const cid2 = base3.encode(bytes);
2425
+ cache.set(prefix, cid2);
2426
+ return cid2;
2427
+ } else {
2428
+ return cid;
2429
+ }
2430
+ };
2431
+ var DAG_PB_CODE = 112;
2432
+ var SHA_256_CODE = 18;
2433
+ var encodeCID = (version2, code2, multihash) => {
2434
+ const codeOffset = encodingLength(version2);
2435
+ const hashOffset = codeOffset + encodingLength(code2);
2436
+ const bytes = new Uint8Array(hashOffset + multihash.byteLength);
2437
+ encodeTo(version2, bytes, 0);
2438
+ encodeTo(code2, bytes, codeOffset);
2439
+ bytes.set(multihash, hashOffset);
2440
+ return bytes;
2441
+ };
2442
+ var cidSymbol = Symbol.for("@ipld/js-cid/CID");
2443
+ var readonly = {
2444
+ writable: false,
2445
+ configurable: false,
2446
+ enumerable: true
2447
+ };
2448
+ var hidden = {
2449
+ writable: false,
2450
+ enumerable: false,
2451
+ configurable: false
2452
+ };
2453
+ var version = "0.0.0-dev";
2454
+ var deprecate = (range, message) => {
2455
+ if (range.test(version)) {
2456
+ console.warn(message);
2457
+ } else {
2458
+ throw new Error(message);
2459
+ }
2460
+ };
2461
+ var IS_CID_DEPRECATION = `CID.isCID(v) is deprecated and will be removed in the next major release.
2462
+ Following code pattern:
2463
+
2464
+ if (CID.isCID(value)) {
2465
+ doSomethingWithCID(value)
2466
+ }
2467
+
2468
+ Is replaced with:
2469
+
2470
+ const cid = CID.asCID(value)
2471
+ if (cid) {
2472
+ // Make sure to use cid instead of value
2473
+ doSomethingWithCID(cid)
2474
+ }
2475
+ `;
2476
+
2477
+ // ../../node_modules/multiformats/esm/src/basics.js
2478
+ var bases = {
2479
+ ...identity_exports,
2480
+ ...base2_exports,
2481
+ ...base8_exports,
2482
+ ...base10_exports,
2483
+ ...base16_exports,
2484
+ ...base32_exports,
2485
+ ...base36_exports,
2486
+ ...base58_exports,
2487
+ ...base64_exports,
2488
+ ...base256emoji_exports
2489
+ };
2490
+ var hashes = {
2491
+ ...sha2_exports,
2492
+ ...identity_exports2
2493
+ };
2494
+
2495
+ // ../../node_modules/uint8arrays/esm/src/util/bases.js
2496
+ function createCodec(name2, prefix, encode5, decode6) {
2497
+ return {
2498
+ name: name2,
2499
+ prefix,
2500
+ encoder: {
2501
+ name: name2,
2502
+ prefix,
2503
+ encode: encode5
2504
+ },
2505
+ decoder: { decode: decode6 }
2506
+ };
2507
+ }
2508
+ var string = createCodec("utf8", "u", (buf) => {
2509
+ const decoder = new TextDecoder("utf8");
2510
+ return "u" + decoder.decode(buf);
2511
+ }, (str) => {
2512
+ const encoder = new TextEncoder();
2513
+ return encoder.encode(str.substring(1));
2514
+ });
2515
+ var ascii = createCodec("ascii", "a", (buf) => {
2516
+ let string2 = "a";
2517
+ for (let i = 0; i < buf.length; i++) {
2518
+ string2 += String.fromCharCode(buf[i]);
2519
+ }
2520
+ return string2;
2521
+ }, (str) => {
2522
+ str = str.substring(1);
2523
+ const buf = new Uint8Array(str.length);
2524
+ for (let i = 0; i < str.length; i++) {
2525
+ buf[i] = str.charCodeAt(i);
2526
+ }
2527
+ return buf;
2528
+ });
2529
+ var BASES = {
2530
+ utf8: string,
2531
+ "utf-8": string,
2532
+ hex: bases.base16,
2533
+ latin1: ascii,
2534
+ ascii,
2535
+ binary: ascii,
2536
+ ...bases
2537
+ };
2538
+ var bases_default = BASES;
2539
+
2540
+ // ../../node_modules/uint8arrays/esm/src/from-string.js
2541
+ function fromString2(string2, encoding = "utf8") {
2542
+ const base3 = bases_default[encoding];
2543
+ if (!base3) {
2544
+ throw new Error(`Unsupported encoding "${encoding}"`);
2545
+ }
2546
+ return base3.decoder.decode(`${base3.prefix}${string2}`);
2547
+ }
2548
+
2549
+ // ../../node_modules/uint8arrays/esm/src/to-string.js
2550
+ function toString2(array, encoding = "utf8") {
2551
+ const base3 = bases_default[encoding];
2552
+ if (!base3) {
2553
+ throw new Error(`Unsupported encoding "${encoding}"`);
2554
+ }
2555
+ return base3.encoder.encode(array).substring(1);
2556
+ }
2557
+
2558
+ // src/random.ts
2559
+ var randomBytes = (length2) => {
2560
+ return webcrypto.getRandomValues(new Uint8Array(length2));
2561
+ };
2562
+ var randomIV = () => {
2563
+ return randomBytes(12);
2564
+ };
2565
+ var randomStr = (byteLength, encoding) => {
2566
+ const bytes = randomBytes(byteLength);
2567
+ return toString2(bytes, encoding);
2568
+ };
2569
+
2570
+ // src/aes.ts
2571
+ var AesKey = class {
2572
+ constructor(key) {
2573
+ this.key = key;
2574
+ }
2575
+ static async create() {
2576
+ const key = await webcrypto.subtle.generateKey(
2577
+ {
2578
+ name: "AES-GCM",
2579
+ length: 256
2580
+ },
2581
+ true,
2582
+ ["encrypt", "decrypt"]
2583
+ );
2584
+ return new AesKey(key);
2585
+ }
2586
+ async encrypt(data) {
2587
+ const iv = randomIV();
2588
+ const dataBytes = fromString2(data, "utf8");
2589
+ const buf = await webcrypto.subtle.encrypt(
2590
+ {
2591
+ name: "AES-GCM",
2592
+ iv
2593
+ },
2594
+ this.key,
2595
+ dataBytes
2596
+ );
2597
+ const encryptedBytes = new Uint8Array(buf);
2598
+ const encrypted = toString2(
2599
+ concat([iv, encryptedBytes]),
2600
+ "base64pad"
2601
+ );
2602
+ return encrypted;
2603
+ }
2604
+ async decrypt(data) {
2605
+ const dataBytes = fromString2(data, "base64pad");
2606
+ const iv = dataBytes.slice(0, 12);
2607
+ const encrypted = dataBytes.slice(12);
2608
+ const buf = await webcrypto.subtle.decrypt(
2609
+ {
2610
+ name: "AES-GCM",
2611
+ iv
2612
+ },
2613
+ this.key,
2614
+ encrypted
2615
+ );
2616
+ const decryptedBytes = new Uint8Array(buf);
2617
+ return toString2(decryptedBytes, "utf8");
2618
+ }
2619
+ };
2620
+
2621
+ // src/const.ts
2622
+ var P256_DID_PREFIX = new Uint8Array([128, 36]);
2623
+ var SECP256K1_DID_PREFIX = new Uint8Array([231, 1]);
2624
+ var BASE58_DID_PREFIX = "did:key:z";
2625
+ var P256_JWT_ALG = "ES256";
2626
+ var SECP256K1_JWT_ALG = "ES256K";
2627
+
2628
+ // src/p256/encoding.ts
2629
+ var import_big_integer = __toESM(require_BigInteger());
2630
+ var compressPubkey = (pubkeyBytes) => {
2631
+ if (pubkeyBytes.length !== 65) {
2632
+ throw new Error("Expected 65 byte pubkey");
2633
+ } else if (pubkeyBytes[0] !== 4) {
2634
+ throw new Error("Expected first byte to be 0x04");
2635
+ }
2636
+ const x = pubkeyBytes.slice(1, 33);
2637
+ const y = pubkeyBytes.slice(33, 65);
2638
+ const out = new Uint8Array(x.length + 1);
2639
+ out[0] = 2 + (y[y.length - 1] & 1);
2640
+ out.set(x, 1);
2641
+ return out;
2642
+ };
2643
+ var decompressPubkey = (compressed) => {
2644
+ if (compressed.length !== 33) {
2645
+ throw new Error("Expected 33 byte compress pubkey");
2646
+ } else if (compressed[0] !== 2 && compressed[0] !== 3) {
2647
+ throw new Error("Expected first byte to be 0x02 or 0x03");
2648
+ }
2649
+ const two = (0, import_big_integer.default)(2);
2650
+ const prime = two.pow(256).subtract(two.pow(224)).add(two.pow(192)).add(two.pow(96)).subtract(1);
2651
+ const b = (0, import_big_integer.default)(
2652
+ "41058363725152142129326129780047268409114441015993725554835256314039467401291"
2653
+ );
2654
+ const pIdent = prime.add(1).divide(4);
2655
+ const signY = (0, import_big_integer.default)(compressed[0] - 2);
2656
+ const x = compressed.slice(1);
2657
+ const xBig = (0, import_big_integer.default)(toString2(x, "base10"));
2658
+ const maybeY = xBig.pow(3).subtract(xBig.multiply(3)).add(b).modPow(pIdent, prime);
2659
+ let yBig;
2660
+ if (maybeY.mod(2).equals(signY)) {
2661
+ yBig = maybeY;
2662
+ } else {
2663
+ yBig = prime.subtract(maybeY);
2664
+ }
2665
+ const y = fromString2(yBig.toString(10), "base10");
2666
+ const offset = 32 - y.length;
2667
+ const yPadded = new Uint8Array(32);
2668
+ yPadded.set(y, offset);
2669
+ const publicKey = concat([[4], x, yPadded]);
2670
+ return publicKey;
2671
+ };
2672
+
2673
+ // ../../node_modules/@noble/secp256k1/lib/esm/index.js
2674
+ var nodeCrypto = __toESM(require("crypto"), 1);
2675
+ var _0n = BigInt(0);
2676
+ var _1n = BigInt(1);
2677
+ var _2n = BigInt(2);
2678
+ var _3n = BigInt(3);
2679
+ var _8n = BigInt(8);
2680
+ var CURVE = Object.freeze({
2681
+ a: _0n,
2682
+ b: BigInt(7),
2683
+ P: BigInt("0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f"),
2684
+ n: BigInt("0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141"),
2685
+ h: _1n,
2686
+ Gx: BigInt("55066263022277343669578718895168534326250603453777594175500187360389116729240"),
2687
+ Gy: BigInt("32670510020758816978083085130507043184471273380659243275938904335757337482424"),
2688
+ beta: BigInt("0x7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee")
2689
+ });
2690
+ function weistrass(x) {
2691
+ const { a, b } = CURVE;
2692
+ const x2 = mod(x * x);
2693
+ const x3 = mod(x2 * x);
2694
+ return mod(x3 + a * x + b);
2695
+ }
2696
+ var USE_ENDOMORPHISM = CURVE.a === _0n;
2697
+ var ShaError = class extends Error {
2698
+ constructor(message) {
2699
+ super(message);
2700
+ }
2701
+ };
2702
+ var JacobianPoint = class {
2703
+ constructor(x, y, z) {
2704
+ this.x = x;
2705
+ this.y = y;
2706
+ this.z = z;
2707
+ }
2708
+ static fromAffine(p) {
2709
+ if (!(p instanceof Point)) {
2710
+ throw new TypeError("JacobianPoint#fromAffine: expected Point");
2711
+ }
2712
+ return new JacobianPoint(p.x, p.y, _1n);
2713
+ }
2714
+ static toAffineBatch(points) {
2715
+ const toInv = invertBatch(points.map((p) => p.z));
2716
+ return points.map((p, i) => p.toAffine(toInv[i]));
2717
+ }
2718
+ static normalizeZ(points) {
2719
+ return JacobianPoint.toAffineBatch(points).map(JacobianPoint.fromAffine);
2720
+ }
2721
+ equals(other) {
2722
+ if (!(other instanceof JacobianPoint))
2723
+ throw new TypeError("JacobianPoint expected");
2724
+ const { x: X1, y: Y1, z: Z1 } = this;
2725
+ const { x: X2, y: Y2, z: Z2 } = other;
2726
+ const Z1Z1 = mod(Z1 * Z1);
2727
+ const Z2Z2 = mod(Z2 * Z2);
2728
+ const U1 = mod(X1 * Z2Z2);
2729
+ const U2 = mod(X2 * Z1Z1);
2730
+ const S1 = mod(mod(Y1 * Z2) * Z2Z2);
2731
+ const S2 = mod(mod(Y2 * Z1) * Z1Z1);
2732
+ return U1 === U2 && S1 === S2;
2733
+ }
2734
+ negate() {
2735
+ return new JacobianPoint(this.x, mod(-this.y), this.z);
2736
+ }
2737
+ double() {
2738
+ const { x: X1, y: Y1, z: Z1 } = this;
2739
+ const A = mod(X1 * X1);
2740
+ const B = mod(Y1 * Y1);
2741
+ const C = mod(B * B);
2742
+ const x1b = X1 + B;
2743
+ const D = mod(_2n * (mod(x1b * x1b) - A - C));
2744
+ const E = mod(_3n * A);
2745
+ const F = mod(E * E);
2746
+ const X3 = mod(F - _2n * D);
2747
+ const Y3 = mod(E * (D - X3) - _8n * C);
2748
+ const Z3 = mod(_2n * Y1 * Z1);
2749
+ return new JacobianPoint(X3, Y3, Z3);
2750
+ }
2751
+ add(other) {
2752
+ if (!(other instanceof JacobianPoint))
2753
+ throw new TypeError("JacobianPoint expected");
2754
+ const { x: X1, y: Y1, z: Z1 } = this;
2755
+ const { x: X2, y: Y2, z: Z2 } = other;
2756
+ if (X2 === _0n || Y2 === _0n)
2757
+ return this;
2758
+ if (X1 === _0n || Y1 === _0n)
2759
+ return other;
2760
+ const Z1Z1 = mod(Z1 * Z1);
2761
+ const Z2Z2 = mod(Z2 * Z2);
2762
+ const U1 = mod(X1 * Z2Z2);
2763
+ const U2 = mod(X2 * Z1Z1);
2764
+ const S1 = mod(mod(Y1 * Z2) * Z2Z2);
2765
+ const S2 = mod(mod(Y2 * Z1) * Z1Z1);
2766
+ const H = mod(U2 - U1);
2767
+ const r = mod(S2 - S1);
2768
+ if (H === _0n) {
2769
+ if (r === _0n) {
2770
+ return this.double();
2771
+ } else {
2772
+ return JacobianPoint.ZERO;
2773
+ }
2774
+ }
2775
+ const HH = mod(H * H);
2776
+ const HHH = mod(H * HH);
2777
+ const V = mod(U1 * HH);
2778
+ const X3 = mod(r * r - HHH - _2n * V);
2779
+ const Y3 = mod(r * (V - X3) - S1 * HHH);
2780
+ const Z3 = mod(Z1 * Z2 * H);
2781
+ return new JacobianPoint(X3, Y3, Z3);
2782
+ }
2783
+ subtract(other) {
2784
+ return this.add(other.negate());
2785
+ }
2786
+ multiplyUnsafe(scalar) {
2787
+ const P0 = JacobianPoint.ZERO;
2788
+ if (typeof scalar === "bigint" && scalar === _0n)
2789
+ return P0;
2790
+ let n = normalizeScalar(scalar);
2791
+ if (n === _1n)
2792
+ return this;
2793
+ if (!USE_ENDOMORPHISM) {
2794
+ let p = P0;
2795
+ let d2 = this;
2796
+ while (n > _0n) {
2797
+ if (n & _1n)
2798
+ p = p.add(d2);
2799
+ d2 = d2.double();
2800
+ n >>= _1n;
2801
+ }
2802
+ return p;
2803
+ }
2804
+ let { k1neg, k1, k2neg, k2 } = splitScalarEndo(n);
2805
+ let k1p = P0;
2806
+ let k2p = P0;
2807
+ let d = this;
2808
+ while (k1 > _0n || k2 > _0n) {
2809
+ if (k1 & _1n)
2810
+ k1p = k1p.add(d);
2811
+ if (k2 & _1n)
2812
+ k2p = k2p.add(d);
2813
+ d = d.double();
2814
+ k1 >>= _1n;
2815
+ k2 >>= _1n;
2816
+ }
2817
+ if (k1neg)
2818
+ k1p = k1p.negate();
2819
+ if (k2neg)
2820
+ k2p = k2p.negate();
2821
+ k2p = new JacobianPoint(mod(k2p.x * CURVE.beta), k2p.y, k2p.z);
2822
+ return k1p.add(k2p);
2823
+ }
2824
+ precomputeWindow(W) {
2825
+ const windows = USE_ENDOMORPHISM ? 128 / W + 1 : 256 / W + 1;
2826
+ const points = [];
2827
+ let p = this;
2828
+ let base3 = p;
2829
+ for (let window = 0; window < windows; window++) {
2830
+ base3 = p;
2831
+ points.push(base3);
2832
+ for (let i = 1; i < 2 ** (W - 1); i++) {
2833
+ base3 = base3.add(p);
2834
+ points.push(base3);
2835
+ }
2836
+ p = base3.double();
2837
+ }
2838
+ return points;
2839
+ }
2840
+ wNAF(n, affinePoint) {
2841
+ if (!affinePoint && this.equals(JacobianPoint.BASE))
2842
+ affinePoint = Point.BASE;
2843
+ const W = affinePoint && affinePoint._WINDOW_SIZE || 1;
2844
+ if (256 % W) {
2845
+ throw new Error("Point#wNAF: Invalid precomputation window, must be power of 2");
2846
+ }
2847
+ let precomputes = affinePoint && pointPrecomputes.get(affinePoint);
2848
+ if (!precomputes) {
2849
+ precomputes = this.precomputeWindow(W);
2850
+ if (affinePoint && W !== 1) {
2851
+ precomputes = JacobianPoint.normalizeZ(precomputes);
2852
+ pointPrecomputes.set(affinePoint, precomputes);
2853
+ }
2854
+ }
2855
+ let p = JacobianPoint.ZERO;
2856
+ let f = JacobianPoint.ZERO;
2857
+ const windows = 1 + (USE_ENDOMORPHISM ? 128 / W : 256 / W);
2858
+ const windowSize = 2 ** (W - 1);
2859
+ const mask = BigInt(2 ** W - 1);
2860
+ const maxNumber = 2 ** W;
2861
+ const shiftBy = BigInt(W);
2862
+ for (let window = 0; window < windows; window++) {
2863
+ const offset = window * windowSize;
2864
+ let wbits = Number(n & mask);
2865
+ n >>= shiftBy;
2866
+ if (wbits > windowSize) {
2867
+ wbits -= maxNumber;
2868
+ n += _1n;
2869
+ }
2870
+ if (wbits === 0) {
2871
+ let pr = precomputes[offset];
2872
+ if (window % 2)
2873
+ pr = pr.negate();
2874
+ f = f.add(pr);
2875
+ } else {
2876
+ let cached = precomputes[offset + Math.abs(wbits) - 1];
2877
+ if (wbits < 0)
2878
+ cached = cached.negate();
2879
+ p = p.add(cached);
2880
+ }
2881
+ }
2882
+ return { p, f };
2883
+ }
2884
+ multiply(scalar, affinePoint) {
2885
+ let n = normalizeScalar(scalar);
2886
+ let point;
2887
+ let fake;
2888
+ if (USE_ENDOMORPHISM) {
2889
+ const { k1neg, k1, k2neg, k2 } = splitScalarEndo(n);
2890
+ let { p: k1p, f: f1p } = this.wNAF(k1, affinePoint);
2891
+ let { p: k2p, f: f2p } = this.wNAF(k2, affinePoint);
2892
+ if (k1neg)
2893
+ k1p = k1p.negate();
2894
+ if (k2neg)
2895
+ k2p = k2p.negate();
2896
+ k2p = new JacobianPoint(mod(k2p.x * CURVE.beta), k2p.y, k2p.z);
2897
+ point = k1p.add(k2p);
2898
+ fake = f1p.add(f2p);
2899
+ } else {
2900
+ const { p, f } = this.wNAF(n, affinePoint);
2901
+ point = p;
2902
+ fake = f;
2903
+ }
2904
+ return JacobianPoint.normalizeZ([point, fake])[0];
2905
+ }
2906
+ toAffine(invZ = invert(this.z)) {
2907
+ const { x, y, z } = this;
2908
+ const iz1 = invZ;
2909
+ const iz2 = mod(iz1 * iz1);
2910
+ const iz3 = mod(iz2 * iz1);
2911
+ const ax = mod(x * iz2);
2912
+ const ay = mod(y * iz3);
2913
+ const zz = mod(z * iz1);
2914
+ if (zz !== _1n)
2915
+ throw new Error("invZ was invalid");
2916
+ return new Point(ax, ay);
2917
+ }
2918
+ };
2919
+ JacobianPoint.BASE = new JacobianPoint(CURVE.Gx, CURVE.Gy, _1n);
2920
+ JacobianPoint.ZERO = new JacobianPoint(_0n, _1n, _0n);
2921
+ var pointPrecomputes = /* @__PURE__ */ new WeakMap();
2922
+ var Point = class {
2923
+ constructor(x, y) {
2924
+ this.x = x;
2925
+ this.y = y;
2926
+ }
2927
+ _setWindowSize(windowSize) {
2928
+ this._WINDOW_SIZE = windowSize;
2929
+ pointPrecomputes.delete(this);
2930
+ }
2931
+ hasEvenY() {
2932
+ return this.y % _2n === _0n;
2933
+ }
2934
+ static fromCompressedHex(bytes) {
2935
+ const isShort = bytes.length === 32;
2936
+ const x = bytesToNumber(isShort ? bytes : bytes.subarray(1));
2937
+ if (!isValidFieldElement(x))
2938
+ throw new Error("Point is not on curve");
2939
+ const y2 = weistrass(x);
2940
+ let y = sqrtMod(y2);
2941
+ const isYOdd = (y & _1n) === _1n;
2942
+ if (isShort) {
2943
+ if (isYOdd)
2944
+ y = mod(-y);
2945
+ } else {
2946
+ const isFirstByteOdd = (bytes[0] & 1) === 1;
2947
+ if (isFirstByteOdd !== isYOdd)
2948
+ y = mod(-y);
2949
+ }
2950
+ const point = new Point(x, y);
2951
+ point.assertValidity();
2952
+ return point;
2953
+ }
2954
+ static fromUncompressedHex(bytes) {
2955
+ const x = bytesToNumber(bytes.subarray(1, 33));
2956
+ const y = bytesToNumber(bytes.subarray(33, 65));
2957
+ const point = new Point(x, y);
2958
+ point.assertValidity();
2959
+ return point;
2960
+ }
2961
+ static fromHex(hex) {
2962
+ const bytes = ensureBytes(hex);
2963
+ const len = bytes.length;
2964
+ const header = bytes[0];
2965
+ if (len === 32 || len === 33 && (header === 2 || header === 3)) {
2966
+ return this.fromCompressedHex(bytes);
2967
+ }
2968
+ if (len === 65 && header === 4)
2969
+ return this.fromUncompressedHex(bytes);
2970
+ throw new Error(`Point.fromHex: received invalid point. Expected 32-33 compressed bytes or 65 uncompressed bytes, not ${len}`);
2971
+ }
2972
+ static fromPrivateKey(privateKey) {
2973
+ return Point.BASE.multiply(normalizePrivateKey(privateKey));
2974
+ }
2975
+ static fromSignature(msgHash, signature, recovery) {
2976
+ msgHash = ensureBytes(msgHash);
2977
+ const h = truncateHash(msgHash);
2978
+ const { r, s } = normalizeSignature(signature);
2979
+ if (recovery !== 0 && recovery !== 1) {
2980
+ throw new Error("Cannot recover signature: invalid recovery bit");
2981
+ }
2982
+ const prefix = recovery & 1 ? "03" : "02";
2983
+ const R = Point.fromHex(prefix + numTo32bStr(r));
2984
+ const { n } = CURVE;
2985
+ const rinv = invert(r, n);
2986
+ const u1 = mod(-h * rinv, n);
2987
+ const u2 = mod(s * rinv, n);
2988
+ const Q = Point.BASE.multiplyAndAddUnsafe(R, u1, u2);
2989
+ if (!Q)
2990
+ throw new Error("Cannot recover signature: point at infinify");
2991
+ Q.assertValidity();
2992
+ return Q;
2993
+ }
2994
+ toRawBytes(isCompressed = false) {
2995
+ return hexToBytes(this.toHex(isCompressed));
2996
+ }
2997
+ toHex(isCompressed = false) {
2998
+ const x = numTo32bStr(this.x);
2999
+ if (isCompressed) {
3000
+ const prefix = this.hasEvenY() ? "02" : "03";
3001
+ return `${prefix}${x}`;
3002
+ } else {
3003
+ return `04${x}${numTo32bStr(this.y)}`;
3004
+ }
3005
+ }
3006
+ toHexX() {
3007
+ return this.toHex(true).slice(2);
3008
+ }
3009
+ toRawX() {
3010
+ return this.toRawBytes(true).slice(1);
3011
+ }
3012
+ assertValidity() {
3013
+ const msg = "Point is not on elliptic curve";
3014
+ const { x, y } = this;
3015
+ if (!isValidFieldElement(x) || !isValidFieldElement(y))
3016
+ throw new Error(msg);
3017
+ const left = mod(y * y);
3018
+ const right = weistrass(x);
3019
+ if (mod(left - right) !== _0n)
3020
+ throw new Error(msg);
3021
+ }
3022
+ equals(other) {
3023
+ return this.x === other.x && this.y === other.y;
3024
+ }
3025
+ negate() {
3026
+ return new Point(this.x, mod(-this.y));
3027
+ }
3028
+ double() {
3029
+ return JacobianPoint.fromAffine(this).double().toAffine();
3030
+ }
3031
+ add(other) {
3032
+ return JacobianPoint.fromAffine(this).add(JacobianPoint.fromAffine(other)).toAffine();
3033
+ }
3034
+ subtract(other) {
3035
+ return this.add(other.negate());
3036
+ }
3037
+ multiply(scalar) {
3038
+ return JacobianPoint.fromAffine(this).multiply(scalar, this).toAffine();
3039
+ }
3040
+ multiplyAndAddUnsafe(Q, a, b) {
3041
+ const P = JacobianPoint.fromAffine(this);
3042
+ const aP = a === _0n || a === _1n || this !== Point.BASE ? P.multiplyUnsafe(a) : P.multiply(a);
3043
+ const bQ = JacobianPoint.fromAffine(Q).multiplyUnsafe(b);
3044
+ const sum = aP.add(bQ);
3045
+ return sum.equals(JacobianPoint.ZERO) ? void 0 : sum.toAffine();
3046
+ }
3047
+ };
3048
+ Point.BASE = new Point(CURVE.Gx, CURVE.Gy);
3049
+ Point.ZERO = new Point(_0n, _0n);
3050
+ function sliceDER(s) {
3051
+ return Number.parseInt(s[0], 16) >= 8 ? "00" + s : s;
3052
+ }
3053
+ function parseDERInt(data) {
3054
+ if (data.length < 2 || data[0] !== 2) {
3055
+ throw new Error(`Invalid signature integer tag: ${bytesToHex(data)}`);
3056
+ }
3057
+ const len = data[1];
3058
+ const res = data.subarray(2, len + 2);
3059
+ if (!len || res.length !== len) {
3060
+ throw new Error(`Invalid signature integer: wrong length`);
3061
+ }
3062
+ if (res[0] === 0 && res[1] <= 127) {
3063
+ throw new Error("Invalid signature integer: trailing length");
3064
+ }
3065
+ return { data: bytesToNumber(res), left: data.subarray(len + 2) };
3066
+ }
3067
+ function parseDERSignature(data) {
3068
+ if (data.length < 2 || data[0] != 48) {
3069
+ throw new Error(`Invalid signature tag: ${bytesToHex(data)}`);
3070
+ }
3071
+ if (data[1] !== data.length - 2) {
3072
+ throw new Error("Invalid signature: incorrect length");
3073
+ }
3074
+ const { data: r, left: sBytes } = parseDERInt(data.subarray(2));
3075
+ const { data: s, left: rBytesLeft } = parseDERInt(sBytes);
3076
+ if (rBytesLeft.length) {
3077
+ throw new Error(`Invalid signature: left bytes after parsing: ${bytesToHex(rBytesLeft)}`);
3078
+ }
3079
+ return { r, s };
3080
+ }
3081
+ var Signature = class {
3082
+ constructor(r, s) {
3083
+ this.r = r;
3084
+ this.s = s;
3085
+ this.assertValidity();
3086
+ }
3087
+ static fromCompact(hex) {
3088
+ const arr = hex instanceof Uint8Array;
3089
+ const name2 = "Signature.fromCompact";
3090
+ if (typeof hex !== "string" && !arr)
3091
+ throw new TypeError(`${name2}: Expected string or Uint8Array`);
3092
+ const str = arr ? bytesToHex(hex) : hex;
3093
+ if (str.length !== 128)
3094
+ throw new Error(`${name2}: Expected 64-byte hex`);
3095
+ return new Signature(hexToNumber(str.slice(0, 64)), hexToNumber(str.slice(64, 128)));
3096
+ }
3097
+ static fromDER(hex) {
3098
+ const arr = hex instanceof Uint8Array;
3099
+ if (typeof hex !== "string" && !arr)
3100
+ throw new TypeError(`Signature.fromDER: Expected string or Uint8Array`);
3101
+ const { r, s } = parseDERSignature(arr ? hex : hexToBytes(hex));
3102
+ return new Signature(r, s);
3103
+ }
3104
+ static fromHex(hex) {
3105
+ return this.fromDER(hex);
3106
+ }
3107
+ assertValidity() {
3108
+ const { r, s } = this;
3109
+ if (!isWithinCurveOrder(r))
3110
+ throw new Error("Invalid Signature: r must be 0 < r < n");
3111
+ if (!isWithinCurveOrder(s))
3112
+ throw new Error("Invalid Signature: s must be 0 < s < n");
3113
+ }
3114
+ hasHighS() {
3115
+ const HALF = CURVE.n >> _1n;
3116
+ return this.s > HALF;
3117
+ }
3118
+ normalizeS() {
3119
+ return this.hasHighS() ? new Signature(this.r, CURVE.n - this.s) : this;
3120
+ }
3121
+ toDERRawBytes(isCompressed = false) {
3122
+ return hexToBytes(this.toDERHex(isCompressed));
3123
+ }
3124
+ toDERHex(isCompressed = false) {
3125
+ const sHex = sliceDER(numberToHexUnpadded(this.s));
3126
+ if (isCompressed)
3127
+ return sHex;
3128
+ const rHex = sliceDER(numberToHexUnpadded(this.r));
3129
+ const rLen = numberToHexUnpadded(rHex.length / 2);
3130
+ const sLen = numberToHexUnpadded(sHex.length / 2);
3131
+ const length2 = numberToHexUnpadded(rHex.length / 2 + sHex.length / 2 + 4);
3132
+ return `30${length2}02${rLen}${rHex}02${sLen}${sHex}`;
3133
+ }
3134
+ toRawBytes() {
3135
+ return this.toDERRawBytes();
3136
+ }
3137
+ toHex() {
3138
+ return this.toDERHex();
3139
+ }
3140
+ toCompactRawBytes() {
3141
+ return hexToBytes(this.toCompactHex());
3142
+ }
3143
+ toCompactHex() {
3144
+ return numTo32bStr(this.r) + numTo32bStr(this.s);
3145
+ }
3146
+ };
3147
+ function concatBytes(...arrays) {
3148
+ if (!arrays.every((b) => b instanceof Uint8Array))
3149
+ throw new Error("Uint8Array list expected");
3150
+ if (arrays.length === 1)
3151
+ return arrays[0];
3152
+ const length2 = arrays.reduce((a, arr) => a + arr.length, 0);
3153
+ const result = new Uint8Array(length2);
3154
+ for (let i = 0, pad = 0; i < arrays.length; i++) {
3155
+ const arr = arrays[i];
3156
+ result.set(arr, pad);
3157
+ pad += arr.length;
3158
+ }
3159
+ return result;
3160
+ }
3161
+ var hexes = Array.from({ length: 256 }, (v, i) => i.toString(16).padStart(2, "0"));
3162
+ function bytesToHex(uint8a) {
3163
+ if (!(uint8a instanceof Uint8Array))
3164
+ throw new Error("Expected Uint8Array");
3165
+ let hex = "";
3166
+ for (let i = 0; i < uint8a.length; i++) {
3167
+ hex += hexes[uint8a[i]];
3168
+ }
3169
+ return hex;
3170
+ }
3171
+ var POW_2_256 = BigInt("0x10000000000000000000000000000000000000000000000000000000000000000");
3172
+ function numTo32bStr(num) {
3173
+ if (typeof num !== "bigint")
3174
+ throw new Error("Expected bigint");
3175
+ if (!(_0n <= num && num < POW_2_256))
3176
+ throw new Error("Expected number < 2^256");
3177
+ return num.toString(16).padStart(64, "0");
3178
+ }
3179
+ function numTo32b(num) {
3180
+ const b = hexToBytes(numTo32bStr(num));
3181
+ if (b.length !== 32)
3182
+ throw new Error("Error: expected 32 bytes");
3183
+ return b;
3184
+ }
3185
+ function numberToHexUnpadded(num) {
3186
+ const hex = num.toString(16);
3187
+ return hex.length & 1 ? `0${hex}` : hex;
3188
+ }
3189
+ function hexToNumber(hex) {
3190
+ if (typeof hex !== "string") {
3191
+ throw new TypeError("hexToNumber: expected string, got " + typeof hex);
3192
+ }
3193
+ return BigInt(`0x${hex}`);
3194
+ }
3195
+ function hexToBytes(hex) {
3196
+ if (typeof hex !== "string") {
3197
+ throw new TypeError("hexToBytes: expected string, got " + typeof hex);
3198
+ }
3199
+ if (hex.length % 2)
3200
+ throw new Error("hexToBytes: received invalid unpadded hex" + hex.length);
3201
+ const array = new Uint8Array(hex.length / 2);
3202
+ for (let i = 0; i < array.length; i++) {
3203
+ const j = i * 2;
3204
+ const hexByte = hex.slice(j, j + 2);
3205
+ const byte = Number.parseInt(hexByte, 16);
3206
+ if (Number.isNaN(byte) || byte < 0)
3207
+ throw new Error("Invalid byte sequence");
3208
+ array[i] = byte;
3209
+ }
3210
+ return array;
3211
+ }
3212
+ function bytesToNumber(bytes) {
3213
+ return hexToNumber(bytesToHex(bytes));
3214
+ }
3215
+ function ensureBytes(hex) {
3216
+ return hex instanceof Uint8Array ? Uint8Array.from(hex) : hexToBytes(hex);
3217
+ }
3218
+ function normalizeScalar(num) {
3219
+ if (typeof num === "number" && Number.isSafeInteger(num) && num > 0)
3220
+ return BigInt(num);
3221
+ if (typeof num === "bigint" && isWithinCurveOrder(num))
3222
+ return num;
3223
+ throw new TypeError("Expected valid private scalar: 0 < scalar < curve.n");
3224
+ }
3225
+ function mod(a, b = CURVE.P) {
3226
+ const result = a % b;
3227
+ return result >= _0n ? result : b + result;
3228
+ }
3229
+ function pow2(x, power) {
3230
+ const { P } = CURVE;
3231
+ let res = x;
3232
+ while (power-- > _0n) {
3233
+ res *= res;
3234
+ res %= P;
3235
+ }
3236
+ return res;
3237
+ }
3238
+ function sqrtMod(x) {
3239
+ const { P } = CURVE;
3240
+ const _6n = BigInt(6);
3241
+ const _11n = BigInt(11);
3242
+ const _22n = BigInt(22);
3243
+ const _23n = BigInt(23);
3244
+ const _44n = BigInt(44);
3245
+ const _88n = BigInt(88);
3246
+ const b2 = x * x * x % P;
3247
+ const b3 = b2 * b2 * x % P;
3248
+ const b6 = pow2(b3, _3n) * b3 % P;
3249
+ const b9 = pow2(b6, _3n) * b3 % P;
3250
+ const b11 = pow2(b9, _2n) * b2 % P;
3251
+ const b22 = pow2(b11, _11n) * b11 % P;
3252
+ const b44 = pow2(b22, _22n) * b22 % P;
3253
+ const b88 = pow2(b44, _44n) * b44 % P;
3254
+ const b176 = pow2(b88, _88n) * b88 % P;
3255
+ const b220 = pow2(b176, _44n) * b44 % P;
3256
+ const b223 = pow2(b220, _3n) * b3 % P;
3257
+ const t1 = pow2(b223, _23n) * b22 % P;
3258
+ const t2 = pow2(t1, _6n) * b2 % P;
3259
+ return pow2(t2, _2n);
3260
+ }
3261
+ function invert(number, modulo = CURVE.P) {
3262
+ if (number === _0n || modulo <= _0n) {
3263
+ throw new Error(`invert: expected positive integers, got n=${number} mod=${modulo}`);
3264
+ }
3265
+ let a = mod(number, modulo);
3266
+ let b = modulo;
3267
+ let x = _0n, y = _1n, u = _1n, v = _0n;
3268
+ while (a !== _0n) {
3269
+ const q = b / a;
3270
+ const r = b % a;
3271
+ const m = x - u * q;
3272
+ const n = y - v * q;
3273
+ b = a, a = r, x = u, y = v, u = m, v = n;
3274
+ }
3275
+ const gcd = b;
3276
+ if (gcd !== _1n)
3277
+ throw new Error("invert: does not exist");
3278
+ return mod(x, modulo);
3279
+ }
3280
+ function invertBatch(nums, p = CURVE.P) {
3281
+ const scratch = new Array(nums.length);
3282
+ const lastMultiplied = nums.reduce((acc, num, i) => {
3283
+ if (num === _0n)
3284
+ return acc;
3285
+ scratch[i] = acc;
3286
+ return mod(acc * num, p);
3287
+ }, _1n);
3288
+ const inverted = invert(lastMultiplied, p);
3289
+ nums.reduceRight((acc, num, i) => {
3290
+ if (num === _0n)
3291
+ return acc;
3292
+ scratch[i] = mod(acc * scratch[i], p);
3293
+ return mod(acc * num, p);
3294
+ }, inverted);
3295
+ return scratch;
3296
+ }
3297
+ var divNearest = (a, b) => (a + b / _2n) / b;
3298
+ var ENDO = {
3299
+ a1: BigInt("0x3086d221a7d46bcde86c90e49284eb15"),
3300
+ b1: -_1n * BigInt("0xe4437ed6010e88286f547fa90abfe4c3"),
3301
+ a2: BigInt("0x114ca50f7a8e2f3f657c1108d9d44cfd8"),
3302
+ b2: BigInt("0x3086d221a7d46bcde86c90e49284eb15"),
3303
+ POW_2_128: BigInt("0x100000000000000000000000000000000")
3304
+ };
3305
+ function splitScalarEndo(k) {
3306
+ const { n } = CURVE;
3307
+ const { a1, b1, a2, b2, POW_2_128 } = ENDO;
3308
+ const c1 = divNearest(b2 * k, n);
3309
+ const c2 = divNearest(-b1 * k, n);
3310
+ let k1 = mod(k - c1 * a1 - c2 * a2, n);
3311
+ let k2 = mod(-c1 * b1 - c2 * b2, n);
3312
+ const k1neg = k1 > POW_2_128;
3313
+ const k2neg = k2 > POW_2_128;
3314
+ if (k1neg)
3315
+ k1 = n - k1;
3316
+ if (k2neg)
3317
+ k2 = n - k2;
3318
+ if (k1 > POW_2_128 || k2 > POW_2_128) {
3319
+ throw new Error("splitScalarEndo: Endomorphism failed, k=" + k);
3320
+ }
3321
+ return { k1neg, k1, k2neg, k2 };
3322
+ }
3323
+ function truncateHash(hash) {
3324
+ const { n } = CURVE;
3325
+ const byteLength = hash.length;
3326
+ const delta = byteLength * 8 - 256;
3327
+ let h = bytesToNumber(hash);
3328
+ if (delta > 0)
3329
+ h = h >> BigInt(delta);
3330
+ if (h >= n)
3331
+ h -= n;
3332
+ return h;
3333
+ }
3334
+ var _sha256Sync;
3335
+ var _hmacSha256Sync;
3336
+ var HmacDrbg = class {
3337
+ constructor() {
3338
+ this.v = new Uint8Array(32).fill(1);
3339
+ this.k = new Uint8Array(32).fill(0);
3340
+ this.counter = 0;
3341
+ }
3342
+ hmac(...values) {
3343
+ return utils.hmacSha256(this.k, ...values);
3344
+ }
3345
+ hmacSync(...values) {
3346
+ return _hmacSha256Sync(this.k, ...values);
3347
+ }
3348
+ checkSync() {
3349
+ if (typeof _hmacSha256Sync !== "function")
3350
+ throw new ShaError("hmacSha256Sync needs to be set");
3351
+ }
3352
+ incr() {
3353
+ if (this.counter >= 1e3)
3354
+ throw new Error("Tried 1,000 k values for sign(), all were invalid");
3355
+ this.counter += 1;
3356
+ }
3357
+ async reseed(seed = new Uint8Array()) {
3358
+ this.k = await this.hmac(this.v, Uint8Array.from([0]), seed);
3359
+ this.v = await this.hmac(this.v);
3360
+ if (seed.length === 0)
3361
+ return;
3362
+ this.k = await this.hmac(this.v, Uint8Array.from([1]), seed);
3363
+ this.v = await this.hmac(this.v);
3364
+ }
3365
+ reseedSync(seed = new Uint8Array()) {
3366
+ this.checkSync();
3367
+ this.k = this.hmacSync(this.v, Uint8Array.from([0]), seed);
3368
+ this.v = this.hmacSync(this.v);
3369
+ if (seed.length === 0)
3370
+ return;
3371
+ this.k = this.hmacSync(this.v, Uint8Array.from([1]), seed);
3372
+ this.v = this.hmacSync(this.v);
3373
+ }
3374
+ async generate() {
3375
+ this.incr();
3376
+ this.v = await this.hmac(this.v);
3377
+ return this.v;
3378
+ }
3379
+ generateSync() {
3380
+ this.checkSync();
3381
+ this.incr();
3382
+ this.v = this.hmacSync(this.v);
3383
+ return this.v;
3384
+ }
3385
+ };
3386
+ function isWithinCurveOrder(num) {
3387
+ return _0n < num && num < CURVE.n;
3388
+ }
3389
+ function isValidFieldElement(num) {
3390
+ return _0n < num && num < CURVE.P;
3391
+ }
3392
+ function kmdToSig(kBytes, m, d) {
3393
+ const k = bytesToNumber(kBytes);
3394
+ if (!isWithinCurveOrder(k))
3395
+ return;
3396
+ const { n } = CURVE;
3397
+ const q = Point.BASE.multiply(k);
3398
+ const r = mod(q.x, n);
3399
+ if (r === _0n)
3400
+ return;
3401
+ const s = mod(invert(k, n) * mod(m + d * r, n), n);
3402
+ if (s === _0n)
3403
+ return;
3404
+ const sig = new Signature(r, s);
3405
+ const recovery = (q.x === sig.r ? 0 : 2) | Number(q.y & _1n);
3406
+ return { sig, recovery };
3407
+ }
3408
+ function normalizePrivateKey(key) {
3409
+ let num;
3410
+ if (typeof key === "bigint") {
3411
+ num = key;
3412
+ } else if (typeof key === "number" && Number.isSafeInteger(key) && key > 0) {
3413
+ num = BigInt(key);
3414
+ } else if (typeof key === "string") {
3415
+ if (key.length !== 64)
3416
+ throw new Error("Expected 32 bytes of private key");
3417
+ num = hexToNumber(key);
3418
+ } else if (key instanceof Uint8Array) {
3419
+ if (key.length !== 32)
3420
+ throw new Error("Expected 32 bytes of private key");
3421
+ num = bytesToNumber(key);
3422
+ } else {
3423
+ throw new TypeError("Expected valid private key");
3424
+ }
3425
+ if (!isWithinCurveOrder(num))
3426
+ throw new Error("Expected private key: 0 < key < n");
3427
+ return num;
3428
+ }
3429
+ function normalizePublicKey(publicKey) {
3430
+ if (publicKey instanceof Point) {
3431
+ publicKey.assertValidity();
3432
+ return publicKey;
3433
+ } else {
3434
+ return Point.fromHex(publicKey);
3435
+ }
3436
+ }
3437
+ function normalizeSignature(signature) {
3438
+ if (signature instanceof Signature) {
3439
+ signature.assertValidity();
3440
+ return signature;
3441
+ }
3442
+ try {
3443
+ return Signature.fromDER(signature);
3444
+ } catch (error) {
3445
+ return Signature.fromCompact(signature);
3446
+ }
3447
+ }
3448
+ function getPublicKey(privateKey, isCompressed = false) {
3449
+ return Point.fromPrivateKey(privateKey).toRawBytes(isCompressed);
3450
+ }
3451
+ function bits2int(bytes) {
3452
+ const slice = bytes.length > 32 ? bytes.slice(0, 32) : bytes;
3453
+ return bytesToNumber(slice);
3454
+ }
3455
+ function bits2octets(bytes) {
3456
+ const z1 = bits2int(bytes);
3457
+ const z2 = mod(z1, CURVE.n);
3458
+ return int2octets(z2 < _0n ? z1 : z2);
3459
+ }
3460
+ function int2octets(num) {
3461
+ return numTo32b(num);
3462
+ }
3463
+ function initSigArgs(msgHash, privateKey, extraEntropy) {
3464
+ if (msgHash == null)
3465
+ throw new Error(`sign: expected valid message hash, not "${msgHash}"`);
3466
+ const h1 = ensureBytes(msgHash);
3467
+ const d = normalizePrivateKey(privateKey);
3468
+ const seedArgs = [int2octets(d), bits2octets(h1)];
3469
+ if (extraEntropy != null) {
3470
+ if (extraEntropy === true)
3471
+ extraEntropy = utils.randomBytes(32);
3472
+ const e = ensureBytes(extraEntropy);
3473
+ if (e.length !== 32)
3474
+ throw new Error("sign: Expected 32 bytes of extra data");
3475
+ seedArgs.push(e);
3476
+ }
3477
+ const seed = concatBytes(...seedArgs);
3478
+ const m = bits2int(h1);
3479
+ return { seed, m, d };
3480
+ }
3481
+ function finalizeSig(recSig, opts) {
3482
+ let { sig, recovery } = recSig;
3483
+ const { canonical, der, recovered } = Object.assign({ canonical: true, der: true }, opts);
3484
+ if (canonical && sig.hasHighS()) {
3485
+ sig = sig.normalizeS();
3486
+ recovery ^= 1;
3487
+ }
3488
+ const hashed = der ? sig.toDERRawBytes() : sig.toCompactRawBytes();
3489
+ return recovered ? [hashed, recovery] : hashed;
3490
+ }
3491
+ async function sign(msgHash, privKey, opts = {}) {
3492
+ const { seed, m, d } = initSigArgs(msgHash, privKey, opts.extraEntropy);
3493
+ let sig;
3494
+ const drbg = new HmacDrbg();
3495
+ await drbg.reseed(seed);
3496
+ while (!(sig = kmdToSig(await drbg.generate(), m, d)))
3497
+ await drbg.reseed();
3498
+ return finalizeSig(sig, opts);
3499
+ }
3500
+ var vopts = { strict: true };
3501
+ function verify(signature, msgHash, publicKey, opts = vopts) {
3502
+ let sig;
3503
+ try {
3504
+ sig = normalizeSignature(signature);
3505
+ msgHash = ensureBytes(msgHash);
3506
+ } catch (error) {
3507
+ return false;
3508
+ }
3509
+ const { r, s } = sig;
3510
+ if (opts.strict && sig.hasHighS())
3511
+ return false;
3512
+ const h = truncateHash(msgHash);
3513
+ let P;
3514
+ try {
3515
+ P = normalizePublicKey(publicKey);
3516
+ } catch (error) {
3517
+ return false;
3518
+ }
3519
+ const { n } = CURVE;
3520
+ const sinv = invert(s, n);
3521
+ const u1 = mod(h * sinv, n);
3522
+ const u2 = mod(r * sinv, n);
3523
+ const R = Point.BASE.multiplyAndAddUnsafe(P, u1, u2);
3524
+ if (!R)
3525
+ return false;
3526
+ const v = mod(R.x, n);
3527
+ return v === r;
3528
+ }
3529
+ Point.BASE._setWindowSize(8);
3530
+ var crypto3 = {
3531
+ node: nodeCrypto,
3532
+ web: typeof self === "object" && "crypto" in self ? self.crypto : void 0
3533
+ };
3534
+ var TAGGED_HASH_PREFIXES = {};
3535
+ var utils = {
3536
+ bytesToHex,
3537
+ hexToBytes,
3538
+ concatBytes,
3539
+ mod,
3540
+ invert,
3541
+ isValidPrivateKey(privateKey) {
3542
+ try {
3543
+ normalizePrivateKey(privateKey);
3544
+ return true;
3545
+ } catch (error) {
3546
+ return false;
3547
+ }
3548
+ },
3549
+ _bigintTo32Bytes: numTo32b,
3550
+ _normalizePrivateKey: normalizePrivateKey,
3551
+ hashToPrivateKey: (hash) => {
3552
+ hash = ensureBytes(hash);
3553
+ if (hash.length < 40 || hash.length > 1024)
3554
+ throw new Error("Expected 40-1024 bytes of private key as per FIPS 186");
3555
+ const num = mod(bytesToNumber(hash), CURVE.n - _1n) + _1n;
3556
+ return numTo32b(num);
3557
+ },
3558
+ randomBytes: (bytesLength = 32) => {
3559
+ if (crypto3.web) {
3560
+ return crypto3.web.getRandomValues(new Uint8Array(bytesLength));
3561
+ } else if (crypto3.node) {
3562
+ const { randomBytes: randomBytes2 } = crypto3.node;
3563
+ return Uint8Array.from(randomBytes2(bytesLength));
3564
+ } else {
3565
+ throw new Error("The environment doesn't have randomBytes function");
3566
+ }
3567
+ },
3568
+ randomPrivateKey: () => {
3569
+ return utils.hashToPrivateKey(utils.randomBytes(40));
3570
+ },
3571
+ sha256: async (...messages) => {
3572
+ if (crypto3.web) {
3573
+ const buffer = await crypto3.web.subtle.digest("SHA-256", concatBytes(...messages));
3574
+ return new Uint8Array(buffer);
3575
+ } else if (crypto3.node) {
3576
+ const { createHash } = crypto3.node;
3577
+ const hash = createHash("sha256");
3578
+ messages.forEach((m) => hash.update(m));
3579
+ return Uint8Array.from(hash.digest());
3580
+ } else {
3581
+ throw new Error("The environment doesn't have sha256 function");
3582
+ }
3583
+ },
3584
+ hmacSha256: async (key, ...messages) => {
3585
+ if (crypto3.web) {
3586
+ const ckey = await crypto3.web.subtle.importKey("raw", key, { name: "HMAC", hash: { name: "SHA-256" } }, false, ["sign"]);
3587
+ const message = concatBytes(...messages);
3588
+ const buffer = await crypto3.web.subtle.sign("HMAC", ckey, message);
3589
+ return new Uint8Array(buffer);
3590
+ } else if (crypto3.node) {
3591
+ const { createHmac } = crypto3.node;
3592
+ const hash = createHmac("sha256", key);
3593
+ messages.forEach((m) => hash.update(m));
3594
+ return Uint8Array.from(hash.digest());
3595
+ } else {
3596
+ throw new Error("The environment doesn't have hmac-sha256 function");
3597
+ }
3598
+ },
3599
+ sha256Sync: void 0,
3600
+ hmacSha256Sync: void 0,
3601
+ taggedHash: async (tag, ...messages) => {
3602
+ let tagP = TAGGED_HASH_PREFIXES[tag];
3603
+ if (tagP === void 0) {
3604
+ const tagH = await utils.sha256(Uint8Array.from(tag, (c) => c.charCodeAt(0)));
3605
+ tagP = concatBytes(tagH, tagH);
3606
+ TAGGED_HASH_PREFIXES[tag] = tagP;
3607
+ }
3608
+ return utils.sha256(tagP, ...messages);
3609
+ },
3610
+ taggedHashSync: (tag, ...messages) => {
3611
+ if (typeof _sha256Sync !== "function")
3612
+ throw new ShaError("sha256Sync is undefined, you need to set it");
3613
+ let tagP = TAGGED_HASH_PREFIXES[tag];
3614
+ if (tagP === void 0) {
3615
+ const tagH = _sha256Sync(Uint8Array.from(tag, (c) => c.charCodeAt(0)));
3616
+ tagP = concatBytes(tagH, tagH);
3617
+ TAGGED_HASH_PREFIXES[tag] = tagP;
3618
+ }
3619
+ return _sha256Sync(tagP, ...messages);
3620
+ },
3621
+ precompute(windowSize = 8, point = Point.BASE) {
3622
+ const cached = point === Point.BASE ? point : new Point(point.x, point.y);
3623
+ cached._setWindowSize(windowSize);
3624
+ cached.multiply(_3n);
3625
+ return cached;
3626
+ }
3627
+ };
3628
+ Object.defineProperties(utils, {
3629
+ sha256Sync: {
3630
+ configurable: false,
3631
+ get() {
3632
+ return _sha256Sync;
3633
+ },
3634
+ set(val) {
3635
+ if (!_sha256Sync)
3636
+ _sha256Sync = val;
3637
+ }
3638
+ },
3639
+ hmacSha256Sync: {
3640
+ configurable: false,
3641
+ get() {
3642
+ return _hmacSha256Sync;
3643
+ },
3644
+ set(val) {
3645
+ if (!_hmacSha256Sync)
3646
+ _hmacSha256Sync = val;
3647
+ }
3648
+ }
3649
+ });
3650
+
3651
+ // src/secp256k1/encoding.ts
3652
+ var compressPubkey2 = (pubkeyBytes) => {
3653
+ const hex = utils.bytesToHex(pubkeyBytes);
3654
+ const point = Point.fromHex(hex);
3655
+ return point.toRawBytes(true);
3656
+ };
3657
+ var decompressPubkey2 = (compressed) => {
3658
+ if (compressed.length !== 33) {
3659
+ throw new Error("Expected 33 byte compress pubkey");
3660
+ }
3661
+ const hex = utils.bytesToHex(compressed);
3662
+ const point = Point.fromHex(hex);
3663
+ return point.toRawBytes(false);
3664
+ };
3665
+
3666
+ // src/p256/operations.ts
3667
+ var importKeypairJwk = async (jwk, exportable = false) => {
3668
+ const privateKey = await webcrypto.subtle.importKey(
3669
+ "jwk",
3670
+ jwk,
3671
+ { name: "ECDSA", namedCurve: "P-256" },
3672
+ exportable,
3673
+ ["sign"]
3674
+ );
3675
+ const { kty, crv, x, y } = jwk;
3676
+ const pubKeyJwk = { kty, crv, x, y };
3677
+ const publicKey = await webcrypto.subtle.importKey(
3678
+ "jwk",
3679
+ pubKeyJwk,
3680
+ { name: "ECDSA", namedCurve: "P-256" },
3681
+ true,
3682
+ ["verify"]
3683
+ );
3684
+ return { privateKey, publicKey };
3685
+ };
3686
+ var verifyDidSig = async (did, data, sig) => {
3687
+ const { jwtAlg, keyBytes } = parseDidKey(did);
3688
+ if (jwtAlg !== P256_JWT_ALG) {
3689
+ throw new Error(`Not a P-256 did:key: ${did}`);
3690
+ }
3691
+ return verify2(keyBytes, data, sig);
3692
+ };
3693
+ var verify2 = async (publicKey, data, sig) => {
3694
+ const importedKey = await importEcdsaPublicKey(publicKey);
3695
+ return webcrypto.subtle.verify(
3696
+ { name: "ECDSA", hash: { name: "SHA-256" } },
3697
+ importedKey,
3698
+ sig,
3699
+ data
3700
+ );
3701
+ };
3702
+ var importEcdsaPublicKey = async (keyBytes) => {
3703
+ return webcrypto.subtle.importKey(
3704
+ "raw",
3705
+ keyBytes,
3706
+ { name: "ECDSA", namedCurve: "P-256" },
3707
+ true,
3708
+ ["verify"]
3709
+ );
3710
+ };
3711
+
3712
+ // src/p256/plugin.ts
3713
+ var p256Plugin = {
3714
+ prefix: P256_DID_PREFIX,
3715
+ jwtAlg: P256_JWT_ALG,
3716
+ verifySignature: verifyDidSig
3717
+ };
3718
+ var plugin_default = p256Plugin;
3719
+
3720
+ // src/secp256k1/operations.ts
3721
+ var verifyDidSig2 = async (did, data, sig) => {
3722
+ const { jwtAlg, keyBytes } = parseDidKey(did);
3723
+ if (jwtAlg !== SECP256K1_JWT_ALG) {
3724
+ throw new Error(`Not a secp256k1 did:key: ${did}`);
3725
+ }
3726
+ const msgHash = await utils.sha256(data);
3727
+ return verify(sig, msgHash, keyBytes);
3728
+ };
3729
+
3730
+ // src/secp256k1/plugin.ts
3731
+ var secp256k1Plugin = {
3732
+ prefix: SECP256K1_DID_PREFIX,
3733
+ jwtAlg: SECP256K1_JWT_ALG,
3734
+ verifySignature: verifyDidSig2
3735
+ };
3736
+ var plugin_default2 = secp256k1Plugin;
3737
+
3738
+ // src/plugins.ts
3739
+ var plugins = [plugin_default, plugin_default2];
3740
+ var plugins_default = plugins;
3741
+
3742
+ // src/did.ts
3743
+ var DID_KEY_BASE58_PREFIX = "did:key:z";
3744
+ var parseDidKey = (did) => {
3745
+ if (!did.startsWith(DID_KEY_BASE58_PREFIX)) {
3746
+ throw new Error(`Incorrect prefix for did:key: ${did}`);
3747
+ }
3748
+ const prefixedBytes = fromString2(
3749
+ did.slice(DID_KEY_BASE58_PREFIX.length),
3750
+ "base58btc"
3751
+ );
3752
+ const plugin = plugins_default.find((p) => hasPrefix(prefixedBytes, p.prefix));
3753
+ if (!plugin) {
3754
+ throw new Error("Unsupported key type");
3755
+ }
3756
+ let keyBytes = prefixedBytes.slice(plugin.prefix.length);
3757
+ if (plugin.jwtAlg === P256_JWT_ALG) {
3758
+ keyBytes = decompressPubkey(keyBytes);
3759
+ } else if (plugin.jwtAlg === SECP256K1_JWT_ALG) {
3760
+ keyBytes = decompressPubkey2(keyBytes);
3761
+ }
3762
+ return {
3763
+ jwtAlg: plugin.jwtAlg,
3764
+ keyBytes
3765
+ };
3766
+ };
3767
+ var formatDidKey = (jwtAlg, keyBytes) => {
3768
+ const plugin = plugins_default.find((p) => p.jwtAlg === jwtAlg);
3769
+ if (!plugin) {
3770
+ throw new Error("Unsupported key type");
3771
+ }
3772
+ if (jwtAlg === P256_JWT_ALG) {
3773
+ keyBytes = compressPubkey(keyBytes);
3774
+ } else if (jwtAlg === SECP256K1_JWT_ALG) {
3775
+ keyBytes = compressPubkey2(keyBytes);
3776
+ }
3777
+ const prefixedBytes = concat([plugin.prefix, keyBytes]);
3778
+ return DID_KEY_BASE58_PREFIX + toString2(prefixedBytes, "base58btc");
3779
+ };
3780
+ var hasPrefix = (bytes, prefix) => {
3781
+ return equals(prefix, bytes.subarray(0, prefix.byteLength));
3782
+ };
3783
+
3784
+ // src/multibase.ts
3785
+ var multibaseToBytes = (mb) => {
3786
+ const base3 = mb[0];
3787
+ const key = mb.slice(1);
3788
+ switch (base3) {
3789
+ case "f":
3790
+ return fromString2(key, "base16");
3791
+ case "F":
3792
+ return fromString2(key, "base16upper");
3793
+ case "b":
3794
+ return fromString2(key, "base32");
3795
+ case "B":
3796
+ return fromString2(key, "base32upper");
3797
+ case "z":
3798
+ return fromString2(key, "base58btc");
3799
+ case "m":
3800
+ return fromString2(key, "base64");
3801
+ case "u":
3802
+ return fromString2(key, "base64url");
3803
+ case "U":
3804
+ return fromString2(key, "base64urlpad");
3805
+ default:
3806
+ throw new Error(`Unsupported multibase: :${mb}`);
3807
+ }
3808
+ };
3809
+
3810
+ // src/sha.ts
3811
+ var import_crypto3 = __toESM(require("crypto"));
3812
+ var sha2562 = async (input) => {
3813
+ const bytes = typeof input === "string" ? fromString2(input, "utf8") : input;
3814
+ const hash = await sha256.digest(bytes);
3815
+ return hash.digest;
3816
+ };
3817
+ var sha256Stream = async (stream) => {
3818
+ const hash = import_crypto3.default.createHash("sha256");
3819
+ try {
3820
+ for await (const chunk of stream) {
3821
+ hash.write(chunk);
3822
+ }
3823
+ } catch (err) {
3824
+ hash.end();
3825
+ throw err;
3826
+ }
3827
+ hash.end();
3828
+ return hash.read();
3829
+ };
3830
+
3831
+ // src/verify.ts
3832
+ var verifyDidSig3 = (did, data, sig) => {
3833
+ const parsed = parseDidKey(did);
3834
+ const plugin = plugins_default.find((p) => p.jwtAlg === parsed.jwtAlg);
3835
+ if (!plugin) {
3836
+ throw new Error(`Unsupported signature alg: :${parsed.jwtAlg}`);
3837
+ }
3838
+ return plugin.verifySignature(did, data, sig);
3839
+ };
3840
+
3841
+ // src/p256/keypair.ts
3842
+ var EcdsaKeypair = class {
3843
+ constructor(keypair, publicKey, exportable) {
3844
+ this.jwtAlg = P256_JWT_ALG;
3845
+ this.keypair = keypair;
3846
+ this.publicKey = publicKey;
3847
+ this.exportable = exportable;
3848
+ }
3849
+ static async create(opts) {
3850
+ const { exportable = false } = opts || {};
3851
+ const keypair = await webcrypto.subtle.generateKey(
3852
+ { name: "ECDSA", namedCurve: "P-256" },
3853
+ exportable,
3854
+ ["sign", "verify"]
3855
+ );
3856
+ const pubkeyBuf = await webcrypto.subtle.exportKey("raw", keypair.publicKey);
3857
+ const pubkeyBytes = new Uint8Array(pubkeyBuf);
3858
+ return new EcdsaKeypair(keypair, pubkeyBytes, exportable);
3859
+ }
3860
+ static async import(jwk, opts) {
3861
+ const { exportable = false } = opts || {};
3862
+ const keypair = await importKeypairJwk(jwk, exportable);
3863
+ const pubkeyBuf = await webcrypto.subtle.exportKey("raw", keypair.publicKey);
3864
+ const pubkeyBytes = new Uint8Array(pubkeyBuf);
3865
+ return new EcdsaKeypair(keypair, pubkeyBytes, exportable);
3866
+ }
3867
+ publicKeyBytes() {
3868
+ return this.publicKey;
3869
+ }
3870
+ publicKeyStr(encoding = "base64pad") {
3871
+ return toString2(this.publicKey, encoding);
3872
+ }
3873
+ did() {
3874
+ return formatDidKey(this.jwtAlg, this.publicKey);
3875
+ }
3876
+ async sign(msg) {
3877
+ const buf = await webcrypto.subtle.sign(
3878
+ { name: "ECDSA", hash: { name: "SHA-256" } },
3879
+ this.keypair.privateKey,
3880
+ msg.buffer
3881
+ );
3882
+ return new Uint8Array(buf);
3883
+ }
3884
+ async export() {
3885
+ if (!this.exportable) {
3886
+ throw new Error("Private key is not exportable");
3887
+ }
3888
+ const jwk = await webcrypto.subtle.exportKey("jwk", this.keypair.privateKey);
3889
+ return jwk;
3890
+ }
3891
+ };
3892
+
3893
+ // src/secp256k1/keypair.ts
3894
+ var Secp256k1Keypair = class {
3895
+ constructor(privateKey, exportable) {
3896
+ this.privateKey = privateKey;
3897
+ this.exportable = exportable;
3898
+ this.jwtAlg = SECP256K1_JWT_ALG;
3899
+ this.publicKey = getPublicKey(privateKey);
3900
+ }
3901
+ static async create(opts) {
3902
+ const { exportable = false } = opts || {};
3903
+ const privKey = utils.randomPrivateKey();
3904
+ return new Secp256k1Keypair(privKey, exportable);
3905
+ }
3906
+ static async import(privKey, opts) {
3907
+ const { exportable = false } = opts || {};
3908
+ const privKeyBytes = typeof privKey === "string" ? fromString2(privKey, "hex") : privKey;
3909
+ return new Secp256k1Keypair(privKeyBytes, exportable);
3910
+ }
3911
+ publicKeyBytes() {
3912
+ return this.publicKey;
3913
+ }
3914
+ publicKeyStr(encoding = "base64pad") {
3915
+ return toString2(this.publicKey, encoding);
3916
+ }
3917
+ did() {
3918
+ return formatDidKey(this.jwtAlg, this.publicKey);
3919
+ }
3920
+ async sign(msg) {
3921
+ const msgHash = await utils.sha256(msg);
3922
+ return sign(msgHash, this.privateKey, { der: false });
3923
+ }
3924
+ async export() {
3925
+ if (!this.exportable) {
3926
+ throw new Error("Private key is not exportable");
3927
+ }
3928
+ return this.privateKey;
3929
+ }
3930
+ };
3931
+ // Annotate the CommonJS export names for ESM import in node:
3932
+ 0 && (module.exports = {
3933
+ AesKey,
3934
+ BASE58_DID_PREFIX,
3935
+ DID_KEY_BASE58_PREFIX,
3936
+ EcdsaKeypair,
3937
+ P256_DID_PREFIX,
3938
+ P256_JWT_ALG,
3939
+ SECP256K1_DID_PREFIX,
3940
+ SECP256K1_JWT_ALG,
3941
+ Secp256k1Keypair,
3942
+ formatDidKey,
3943
+ multibaseToBytes,
3944
+ p256Plugin,
3945
+ parseDidKey,
3946
+ randomBytes,
3947
+ randomIV,
3948
+ randomStr,
3949
+ secp256k1Plugin,
3950
+ sha256,
3951
+ sha256Stream,
3952
+ verifyDidSig
3953
+ });
3954
+ /*! noble-secp256k1 - MIT License (c) 2019 Paul Miller (paulmillr.com) */
3955
+ //# sourceMappingURL=index.js.map