@repost/client 0.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -0
- package/README.md +93 -0
- package/dist/cjs/index.cjs +1049 -0
- package/dist/cjs/index.cjs.map +1 -0
- package/dist/cjs/types/index.d.ts +5 -0
- package/dist/cjs/types/serialize.d.ts +10 -0
- package/dist/cjs/types/transport.d.ts +28 -0
- package/dist/cjs/types/types.d.ts +123 -0
- package/dist/cjs/types/webhooks.d.ts +13 -0
- package/dist/esm/index.mjs +1042 -0
- package/dist/esm/index.mjs.map +1 -0
- package/index.d.ts +4 -0
- package/index.js +13 -0
- package/index.mjs +6 -0
- package/package.json +66 -0
- package/runtime/index.d.ts +4 -0
- package/runtime/index.js +7 -0
- package/runtime/index.mjs +2 -0
- package/scripts/postinstall.js +78 -0
|
@@ -0,0 +1,1049 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
|
|
3
|
+
var commonjsGlobal = typeof globalThis !== 'undefined' ? globalThis : typeof window !== 'undefined' ? window : typeof global !== 'undefined' ? global : typeof self !== 'undefined' ? self : {};
|
|
4
|
+
|
|
5
|
+
var src = {};
|
|
6
|
+
|
|
7
|
+
var sha3$1 = {};
|
|
8
|
+
|
|
9
|
+
var _u64 = {};
|
|
10
|
+
|
|
11
|
+
Object.defineProperty(_u64, "__esModule", { value: true });
|
|
12
|
+
_u64.toBig = _u64.shrSL = _u64.shrSH = _u64.rotrSL = _u64.rotrSH = _u64.rotrBL = _u64.rotrBH = _u64.rotr32L = _u64.rotr32H = _u64.rotlSL = _u64.rotlSH = _u64.rotlBL = _u64.rotlBH = _u64.add5L = _u64.add5H = _u64.add4L = _u64.add4H = _u64.add3L = _u64.add3H = void 0;
|
|
13
|
+
_u64.add = add;
|
|
14
|
+
_u64.fromBig = fromBig;
|
|
15
|
+
_u64.split = split;
|
|
16
|
+
/**
|
|
17
|
+
* Internal helpers for u64. BigUint64Array is too slow as per 2025, so we implement it using Uint32Array.
|
|
18
|
+
* @todo re-check https://issues.chromium.org/issues/42212588
|
|
19
|
+
* @module
|
|
20
|
+
*/
|
|
21
|
+
const U32_MASK64 = /* @__PURE__ */ BigInt(2 ** 32 - 1);
|
|
22
|
+
const _32n = /* @__PURE__ */ BigInt(32);
|
|
23
|
+
function fromBig(n, le = false) {
|
|
24
|
+
if (le)
|
|
25
|
+
return { h: Number(n & U32_MASK64), l: Number((n >> _32n) & U32_MASK64) };
|
|
26
|
+
return { h: Number((n >> _32n) & U32_MASK64) | 0, l: Number(n & U32_MASK64) | 0 };
|
|
27
|
+
}
|
|
28
|
+
function split(lst, le = false) {
|
|
29
|
+
const len = lst.length;
|
|
30
|
+
let Ah = new Uint32Array(len);
|
|
31
|
+
let Al = new Uint32Array(len);
|
|
32
|
+
for (let i = 0; i < len; i++) {
|
|
33
|
+
const { h, l } = fromBig(lst[i], le);
|
|
34
|
+
[Ah[i], Al[i]] = [h, l];
|
|
35
|
+
}
|
|
36
|
+
return [Ah, Al];
|
|
37
|
+
}
|
|
38
|
+
const toBig = (h, l) => (BigInt(h >>> 0) << _32n) | BigInt(l >>> 0);
|
|
39
|
+
_u64.toBig = toBig;
|
|
40
|
+
// for Shift in [0, 32)
|
|
41
|
+
const shrSH = (h, _l, s) => h >>> s;
|
|
42
|
+
_u64.shrSH = shrSH;
|
|
43
|
+
const shrSL = (h, l, s) => (h << (32 - s)) | (l >>> s);
|
|
44
|
+
_u64.shrSL = shrSL;
|
|
45
|
+
// Right rotate for Shift in [1, 32)
|
|
46
|
+
const rotrSH = (h, l, s) => (h >>> s) | (l << (32 - s));
|
|
47
|
+
_u64.rotrSH = rotrSH;
|
|
48
|
+
const rotrSL = (h, l, s) => (h << (32 - s)) | (l >>> s);
|
|
49
|
+
_u64.rotrSL = rotrSL;
|
|
50
|
+
// Right rotate for Shift in (32, 64), NOTE: 32 is special case.
|
|
51
|
+
const rotrBH = (h, l, s) => (h << (64 - s)) | (l >>> (s - 32));
|
|
52
|
+
_u64.rotrBH = rotrBH;
|
|
53
|
+
const rotrBL = (h, l, s) => (h >>> (s - 32)) | (l << (64 - s));
|
|
54
|
+
_u64.rotrBL = rotrBL;
|
|
55
|
+
// Right rotate for shift===32 (just swaps l&h)
|
|
56
|
+
const rotr32H = (_h, l) => l;
|
|
57
|
+
_u64.rotr32H = rotr32H;
|
|
58
|
+
const rotr32L = (h, _l) => h;
|
|
59
|
+
_u64.rotr32L = rotr32L;
|
|
60
|
+
// Left rotate for Shift in [1, 32)
|
|
61
|
+
const rotlSH = (h, l, s) => (h << s) | (l >>> (32 - s));
|
|
62
|
+
_u64.rotlSH = rotlSH;
|
|
63
|
+
const rotlSL = (h, l, s) => (l << s) | (h >>> (32 - s));
|
|
64
|
+
_u64.rotlSL = rotlSL;
|
|
65
|
+
// Left rotate for Shift in (32, 64), NOTE: 32 is special case.
|
|
66
|
+
const rotlBH = (h, l, s) => (l << (s - 32)) | (h >>> (64 - s));
|
|
67
|
+
_u64.rotlBH = rotlBH;
|
|
68
|
+
const rotlBL = (h, l, s) => (h << (s - 32)) | (l >>> (64 - s));
|
|
69
|
+
_u64.rotlBL = rotlBL;
|
|
70
|
+
// JS uses 32-bit signed integers for bitwise operations which means we cannot
|
|
71
|
+
// simple take carry out of low bit sum by shift, we need to use division.
|
|
72
|
+
function add(Ah, Al, Bh, Bl) {
|
|
73
|
+
const l = (Al >>> 0) + (Bl >>> 0);
|
|
74
|
+
return { h: (Ah + Bh + ((l / 2 ** 32) | 0)) | 0, l: l | 0 };
|
|
75
|
+
}
|
|
76
|
+
// Addition with more than 2 elements
|
|
77
|
+
const add3L = (Al, Bl, Cl) => (Al >>> 0) + (Bl >>> 0) + (Cl >>> 0);
|
|
78
|
+
_u64.add3L = add3L;
|
|
79
|
+
const add3H = (low, Ah, Bh, Ch) => (Ah + Bh + Ch + ((low / 2 ** 32) | 0)) | 0;
|
|
80
|
+
_u64.add3H = add3H;
|
|
81
|
+
const add4L = (Al, Bl, Cl, Dl) => (Al >>> 0) + (Bl >>> 0) + (Cl >>> 0) + (Dl >>> 0);
|
|
82
|
+
_u64.add4L = add4L;
|
|
83
|
+
const add4H = (low, Ah, Bh, Ch, Dh) => (Ah + Bh + Ch + Dh + ((low / 2 ** 32) | 0)) | 0;
|
|
84
|
+
_u64.add4H = add4H;
|
|
85
|
+
const add5L = (Al, Bl, Cl, Dl, El) => (Al >>> 0) + (Bl >>> 0) + (Cl >>> 0) + (Dl >>> 0) + (El >>> 0);
|
|
86
|
+
_u64.add5L = add5L;
|
|
87
|
+
const add5H = (low, Ah, Bh, Ch, Dh, Eh) => (Ah + Bh + Ch + Dh + Eh + ((low / 2 ** 32) | 0)) | 0;
|
|
88
|
+
_u64.add5H = add5H;
|
|
89
|
+
// prettier-ignore
|
|
90
|
+
const u64 = {
|
|
91
|
+
fromBig, split, toBig,
|
|
92
|
+
shrSH, shrSL,
|
|
93
|
+
rotrSH, rotrSL, rotrBH, rotrBL,
|
|
94
|
+
rotr32H, rotr32L,
|
|
95
|
+
rotlSH, rotlSL, rotlBH, rotlBL,
|
|
96
|
+
add, add3L, add3H, add4L, add4H, add5H, add5L,
|
|
97
|
+
};
|
|
98
|
+
_u64.default = u64;
|
|
99
|
+
|
|
100
|
+
var utils = {};
|
|
101
|
+
|
|
102
|
+
var crypto$1 = {};
|
|
103
|
+
|
|
104
|
+
Object.defineProperty(crypto$1, "__esModule", { value: true });
|
|
105
|
+
crypto$1.crypto = void 0;
|
|
106
|
+
crypto$1.crypto = typeof globalThis === 'object' && 'crypto' in globalThis ? globalThis.crypto : undefined;
|
|
107
|
+
|
|
108
|
+
(function (exports) {
|
|
109
|
+
/**
|
|
110
|
+
* Utilities for hex, bytes, CSPRNG.
|
|
111
|
+
* @module
|
|
112
|
+
*/
|
|
113
|
+
/*! noble-hashes - MIT License (c) 2022 Paul Miller (paulmillr.com) */
|
|
114
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
115
|
+
exports.wrapXOFConstructorWithOpts = exports.wrapConstructorWithOpts = exports.wrapConstructor = exports.Hash = exports.nextTick = exports.swap32IfBE = exports.byteSwapIfBE = exports.swap8IfBE = exports.isLE = void 0;
|
|
116
|
+
exports.isBytes = isBytes;
|
|
117
|
+
exports.anumber = anumber;
|
|
118
|
+
exports.abytes = abytes;
|
|
119
|
+
exports.ahash = ahash;
|
|
120
|
+
exports.aexists = aexists;
|
|
121
|
+
exports.aoutput = aoutput;
|
|
122
|
+
exports.u8 = u8;
|
|
123
|
+
exports.u32 = u32;
|
|
124
|
+
exports.clean = clean;
|
|
125
|
+
exports.createView = createView;
|
|
126
|
+
exports.rotr = rotr;
|
|
127
|
+
exports.rotl = rotl;
|
|
128
|
+
exports.byteSwap = byteSwap;
|
|
129
|
+
exports.byteSwap32 = byteSwap32;
|
|
130
|
+
exports.bytesToHex = bytesToHex;
|
|
131
|
+
exports.hexToBytes = hexToBytes;
|
|
132
|
+
exports.asyncLoop = asyncLoop;
|
|
133
|
+
exports.utf8ToBytes = utf8ToBytes;
|
|
134
|
+
exports.bytesToUtf8 = bytesToUtf8;
|
|
135
|
+
exports.toBytes = toBytes;
|
|
136
|
+
exports.kdfInputToBytes = kdfInputToBytes;
|
|
137
|
+
exports.concatBytes = concatBytes;
|
|
138
|
+
exports.checkOpts = checkOpts;
|
|
139
|
+
exports.createHasher = createHasher;
|
|
140
|
+
exports.createOptHasher = createOptHasher;
|
|
141
|
+
exports.createXOFer = createXOFer;
|
|
142
|
+
exports.randomBytes = randomBytes;
|
|
143
|
+
// We use WebCrypto aka globalThis.crypto, which exists in browsers and node.js 16+.
|
|
144
|
+
// node.js versions earlier than v19 don't declare it in global scope.
|
|
145
|
+
// For node.js, package.json#exports field mapping rewrites import
|
|
146
|
+
// from `crypto` to `cryptoNode`, which imports native module.
|
|
147
|
+
// Makes the utils un-importable in browsers without a bundler.
|
|
148
|
+
// Once node.js 18 is deprecated (2025-04-30), we can just drop the import.
|
|
149
|
+
const crypto_1 = crypto$1;
|
|
150
|
+
/** Checks if something is Uint8Array. Be careful: nodejs Buffer will return true. */
|
|
151
|
+
function isBytes(a) {
|
|
152
|
+
return a instanceof Uint8Array || (ArrayBuffer.isView(a) && a.constructor.name === 'Uint8Array');
|
|
153
|
+
}
|
|
154
|
+
/** Asserts something is positive integer. */
|
|
155
|
+
function anumber(n) {
|
|
156
|
+
if (!Number.isSafeInteger(n) || n < 0)
|
|
157
|
+
throw new Error('positive integer expected, got ' + n);
|
|
158
|
+
}
|
|
159
|
+
/** Asserts something is Uint8Array. */
|
|
160
|
+
function abytes(b, ...lengths) {
|
|
161
|
+
if (!isBytes(b))
|
|
162
|
+
throw new Error('Uint8Array expected');
|
|
163
|
+
if (lengths.length > 0 && !lengths.includes(b.length))
|
|
164
|
+
throw new Error('Uint8Array expected of length ' + lengths + ', got length=' + b.length);
|
|
165
|
+
}
|
|
166
|
+
/** Asserts something is hash */
|
|
167
|
+
function ahash(h) {
|
|
168
|
+
if (typeof h !== 'function' || typeof h.create !== 'function')
|
|
169
|
+
throw new Error('Hash should be wrapped by utils.createHasher');
|
|
170
|
+
anumber(h.outputLen);
|
|
171
|
+
anumber(h.blockLen);
|
|
172
|
+
}
|
|
173
|
+
/** Asserts a hash instance has not been destroyed / finished */
|
|
174
|
+
function aexists(instance, checkFinished = true) {
|
|
175
|
+
if (instance.destroyed)
|
|
176
|
+
throw new Error('Hash instance has been destroyed');
|
|
177
|
+
if (checkFinished && instance.finished)
|
|
178
|
+
throw new Error('Hash#digest() has already been called');
|
|
179
|
+
}
|
|
180
|
+
/** Asserts output is properly-sized byte array */
|
|
181
|
+
function aoutput(out, instance) {
|
|
182
|
+
abytes(out);
|
|
183
|
+
const min = instance.outputLen;
|
|
184
|
+
if (out.length < min) {
|
|
185
|
+
throw new Error('digestInto() expects output buffer of length at least ' + min);
|
|
186
|
+
}
|
|
187
|
+
}
|
|
188
|
+
/** Cast u8 / u16 / u32 to u8. */
|
|
189
|
+
function u8(arr) {
|
|
190
|
+
return new Uint8Array(arr.buffer, arr.byteOffset, arr.byteLength);
|
|
191
|
+
}
|
|
192
|
+
/** Cast u8 / u16 / u32 to u32. */
|
|
193
|
+
function u32(arr) {
|
|
194
|
+
return new Uint32Array(arr.buffer, arr.byteOffset, Math.floor(arr.byteLength / 4));
|
|
195
|
+
}
|
|
196
|
+
/** Zeroize a byte array. Warning: JS provides no guarantees. */
|
|
197
|
+
function clean(...arrays) {
|
|
198
|
+
for (let i = 0; i < arrays.length; i++) {
|
|
199
|
+
arrays[i].fill(0);
|
|
200
|
+
}
|
|
201
|
+
}
|
|
202
|
+
/** Create DataView of an array for easy byte-level manipulation. */
|
|
203
|
+
function createView(arr) {
|
|
204
|
+
return new DataView(arr.buffer, arr.byteOffset, arr.byteLength);
|
|
205
|
+
}
|
|
206
|
+
/** The rotate right (circular right shift) operation for uint32 */
|
|
207
|
+
function rotr(word, shift) {
|
|
208
|
+
return (word << (32 - shift)) | (word >>> shift);
|
|
209
|
+
}
|
|
210
|
+
/** The rotate left (circular left shift) operation for uint32 */
|
|
211
|
+
function rotl(word, shift) {
|
|
212
|
+
return (word << shift) | ((word >>> (32 - shift)) >>> 0);
|
|
213
|
+
}
|
|
214
|
+
/** Is current platform little-endian? Most are. Big-Endian platform: IBM */
|
|
215
|
+
exports.isLE = (() => new Uint8Array(new Uint32Array([0x11223344]).buffer)[0] === 0x44)();
|
|
216
|
+
/** The byte swap operation for uint32 */
|
|
217
|
+
function byteSwap(word) {
|
|
218
|
+
return (((word << 24) & 0xff000000) |
|
|
219
|
+
((word << 8) & 0xff0000) |
|
|
220
|
+
((word >>> 8) & 0xff00) |
|
|
221
|
+
((word >>> 24) & 0xff));
|
|
222
|
+
}
|
|
223
|
+
/** Conditionally byte swap if on a big-endian platform */
|
|
224
|
+
exports.swap8IfBE = exports.isLE
|
|
225
|
+
? (n) => n
|
|
226
|
+
: (n) => byteSwap(n);
|
|
227
|
+
/** @deprecated */
|
|
228
|
+
exports.byteSwapIfBE = exports.swap8IfBE;
|
|
229
|
+
/** In place byte swap for Uint32Array */
|
|
230
|
+
function byteSwap32(arr) {
|
|
231
|
+
for (let i = 0; i < arr.length; i++) {
|
|
232
|
+
arr[i] = byteSwap(arr[i]);
|
|
233
|
+
}
|
|
234
|
+
return arr;
|
|
235
|
+
}
|
|
236
|
+
exports.swap32IfBE = exports.isLE
|
|
237
|
+
? (u) => u
|
|
238
|
+
: byteSwap32;
|
|
239
|
+
// Built-in hex conversion https://caniuse.com/mdn-javascript_builtins_uint8array_fromhex
|
|
240
|
+
const hasHexBuiltin = /* @__PURE__ */ (() =>
|
|
241
|
+
// @ts-ignore
|
|
242
|
+
typeof Uint8Array.from([]).toHex === 'function' && typeof Uint8Array.fromHex === 'function')();
|
|
243
|
+
// Array where index 0xf0 (240) is mapped to string 'f0'
|
|
244
|
+
const hexes = /* @__PURE__ */ Array.from({ length: 256 }, (_, i) => i.toString(16).padStart(2, '0'));
|
|
245
|
+
/**
|
|
246
|
+
* Convert byte array to hex string. Uses built-in function, when available.
|
|
247
|
+
* @example bytesToHex(Uint8Array.from([0xca, 0xfe, 0x01, 0x23])) // 'cafe0123'
|
|
248
|
+
*/
|
|
249
|
+
function bytesToHex(bytes) {
|
|
250
|
+
abytes(bytes);
|
|
251
|
+
// @ts-ignore
|
|
252
|
+
if (hasHexBuiltin)
|
|
253
|
+
return bytes.toHex();
|
|
254
|
+
// pre-caching improves the speed 6x
|
|
255
|
+
let hex = '';
|
|
256
|
+
for (let i = 0; i < bytes.length; i++) {
|
|
257
|
+
hex += hexes[bytes[i]];
|
|
258
|
+
}
|
|
259
|
+
return hex;
|
|
260
|
+
}
|
|
261
|
+
// We use optimized technique to convert hex string to byte array
|
|
262
|
+
const asciis = { _0: 48, _9: 57, A: 65, F: 70, a: 97, f: 102 };
|
|
263
|
+
function asciiToBase16(ch) {
|
|
264
|
+
if (ch >= asciis._0 && ch <= asciis._9)
|
|
265
|
+
return ch - asciis._0; // '2' => 50-48
|
|
266
|
+
if (ch >= asciis.A && ch <= asciis.F)
|
|
267
|
+
return ch - (asciis.A - 10); // 'B' => 66-(65-10)
|
|
268
|
+
if (ch >= asciis.a && ch <= asciis.f)
|
|
269
|
+
return ch - (asciis.a - 10); // 'b' => 98-(97-10)
|
|
270
|
+
return;
|
|
271
|
+
}
|
|
272
|
+
/**
|
|
273
|
+
* Convert hex string to byte array. Uses built-in function, when available.
|
|
274
|
+
* @example hexToBytes('cafe0123') // Uint8Array.from([0xca, 0xfe, 0x01, 0x23])
|
|
275
|
+
*/
|
|
276
|
+
function hexToBytes(hex) {
|
|
277
|
+
if (typeof hex !== 'string')
|
|
278
|
+
throw new Error('hex string expected, got ' + typeof hex);
|
|
279
|
+
// @ts-ignore
|
|
280
|
+
if (hasHexBuiltin)
|
|
281
|
+
return Uint8Array.fromHex(hex);
|
|
282
|
+
const hl = hex.length;
|
|
283
|
+
const al = hl / 2;
|
|
284
|
+
if (hl % 2)
|
|
285
|
+
throw new Error('hex string expected, got unpadded hex of length ' + hl);
|
|
286
|
+
const array = new Uint8Array(al);
|
|
287
|
+
for (let ai = 0, hi = 0; ai < al; ai++, hi += 2) {
|
|
288
|
+
const n1 = asciiToBase16(hex.charCodeAt(hi));
|
|
289
|
+
const n2 = asciiToBase16(hex.charCodeAt(hi + 1));
|
|
290
|
+
if (n1 === undefined || n2 === undefined) {
|
|
291
|
+
const char = hex[hi] + hex[hi + 1];
|
|
292
|
+
throw new Error('hex string expected, got non-hex character "' + char + '" at index ' + hi);
|
|
293
|
+
}
|
|
294
|
+
array[ai] = n1 * 16 + n2; // multiply first octet, e.g. 'a3' => 10*16+3 => 160 + 3 => 163
|
|
295
|
+
}
|
|
296
|
+
return array;
|
|
297
|
+
}
|
|
298
|
+
/**
|
|
299
|
+
* There is no setImmediate in browser and setTimeout is slow.
|
|
300
|
+
* Call of async fn will return Promise, which will be fullfiled only on
|
|
301
|
+
* next scheduler queue processing step and this is exactly what we need.
|
|
302
|
+
*/
|
|
303
|
+
const nextTick = async () => { };
|
|
304
|
+
exports.nextTick = nextTick;
|
|
305
|
+
/** Returns control to thread each 'tick' ms to avoid blocking. */
|
|
306
|
+
async function asyncLoop(iters, tick, cb) {
|
|
307
|
+
let ts = Date.now();
|
|
308
|
+
for (let i = 0; i < iters; i++) {
|
|
309
|
+
cb(i);
|
|
310
|
+
// Date.now() is not monotonic, so in case if clock goes backwards we return return control too
|
|
311
|
+
const diff = Date.now() - ts;
|
|
312
|
+
if (diff >= 0 && diff < tick)
|
|
313
|
+
continue;
|
|
314
|
+
await (0, exports.nextTick)();
|
|
315
|
+
ts += diff;
|
|
316
|
+
}
|
|
317
|
+
}
|
|
318
|
+
/**
|
|
319
|
+
* Converts string to bytes using UTF8 encoding.
|
|
320
|
+
* @example utf8ToBytes('abc') // Uint8Array.from([97, 98, 99])
|
|
321
|
+
*/
|
|
322
|
+
function utf8ToBytes(str) {
|
|
323
|
+
if (typeof str !== 'string')
|
|
324
|
+
throw new Error('string expected');
|
|
325
|
+
return new Uint8Array(new TextEncoder().encode(str)); // https://bugzil.la/1681809
|
|
326
|
+
}
|
|
327
|
+
/**
|
|
328
|
+
* Converts bytes to string using UTF8 encoding.
|
|
329
|
+
* @example bytesToUtf8(Uint8Array.from([97, 98, 99])) // 'abc'
|
|
330
|
+
*/
|
|
331
|
+
function bytesToUtf8(bytes) {
|
|
332
|
+
return new TextDecoder().decode(bytes);
|
|
333
|
+
}
|
|
334
|
+
/**
|
|
335
|
+
* Normalizes (non-hex) string or Uint8Array to Uint8Array.
|
|
336
|
+
* Warning: when Uint8Array is passed, it would NOT get copied.
|
|
337
|
+
* Keep in mind for future mutable operations.
|
|
338
|
+
*/
|
|
339
|
+
function toBytes(data) {
|
|
340
|
+
if (typeof data === 'string')
|
|
341
|
+
data = utf8ToBytes(data);
|
|
342
|
+
abytes(data);
|
|
343
|
+
return data;
|
|
344
|
+
}
|
|
345
|
+
/**
|
|
346
|
+
* Helper for KDFs: consumes uint8array or string.
|
|
347
|
+
* When string is passed, does utf8 decoding, using TextDecoder.
|
|
348
|
+
*/
|
|
349
|
+
function kdfInputToBytes(data) {
|
|
350
|
+
if (typeof data === 'string')
|
|
351
|
+
data = utf8ToBytes(data);
|
|
352
|
+
abytes(data);
|
|
353
|
+
return data;
|
|
354
|
+
}
|
|
355
|
+
/** Copies several Uint8Arrays into one. */
|
|
356
|
+
function concatBytes(...arrays) {
|
|
357
|
+
let sum = 0;
|
|
358
|
+
for (let i = 0; i < arrays.length; i++) {
|
|
359
|
+
const a = arrays[i];
|
|
360
|
+
abytes(a);
|
|
361
|
+
sum += a.length;
|
|
362
|
+
}
|
|
363
|
+
const res = new Uint8Array(sum);
|
|
364
|
+
for (let i = 0, pad = 0; i < arrays.length; i++) {
|
|
365
|
+
const a = arrays[i];
|
|
366
|
+
res.set(a, pad);
|
|
367
|
+
pad += a.length;
|
|
368
|
+
}
|
|
369
|
+
return res;
|
|
370
|
+
}
|
|
371
|
+
function checkOpts(defaults, opts) {
|
|
372
|
+
if (opts !== undefined && {}.toString.call(opts) !== '[object Object]')
|
|
373
|
+
throw new Error('options should be object or undefined');
|
|
374
|
+
const merged = Object.assign(defaults, opts);
|
|
375
|
+
return merged;
|
|
376
|
+
}
|
|
377
|
+
/** For runtime check if class implements interface */
|
|
378
|
+
class Hash {
|
|
379
|
+
}
|
|
380
|
+
exports.Hash = Hash;
|
|
381
|
+
/** Wraps hash function, creating an interface on top of it */
|
|
382
|
+
function createHasher(hashCons) {
|
|
383
|
+
const hashC = (msg) => hashCons().update(toBytes(msg)).digest();
|
|
384
|
+
const tmp = hashCons();
|
|
385
|
+
hashC.outputLen = tmp.outputLen;
|
|
386
|
+
hashC.blockLen = tmp.blockLen;
|
|
387
|
+
hashC.create = () => hashCons();
|
|
388
|
+
return hashC;
|
|
389
|
+
}
|
|
390
|
+
function createOptHasher(hashCons) {
|
|
391
|
+
const hashC = (msg, opts) => hashCons(opts).update(toBytes(msg)).digest();
|
|
392
|
+
const tmp = hashCons({});
|
|
393
|
+
hashC.outputLen = tmp.outputLen;
|
|
394
|
+
hashC.blockLen = tmp.blockLen;
|
|
395
|
+
hashC.create = (opts) => hashCons(opts);
|
|
396
|
+
return hashC;
|
|
397
|
+
}
|
|
398
|
+
function createXOFer(hashCons) {
|
|
399
|
+
const hashC = (msg, opts) => hashCons(opts).update(toBytes(msg)).digest();
|
|
400
|
+
const tmp = hashCons({});
|
|
401
|
+
hashC.outputLen = tmp.outputLen;
|
|
402
|
+
hashC.blockLen = tmp.blockLen;
|
|
403
|
+
hashC.create = (opts) => hashCons(opts);
|
|
404
|
+
return hashC;
|
|
405
|
+
}
|
|
406
|
+
exports.wrapConstructor = createHasher;
|
|
407
|
+
exports.wrapConstructorWithOpts = createOptHasher;
|
|
408
|
+
exports.wrapXOFConstructorWithOpts = createXOFer;
|
|
409
|
+
/** Cryptographically secure PRNG. Uses internal OS-level `crypto.getRandomValues`. */
|
|
410
|
+
function randomBytes(bytesLength = 32) {
|
|
411
|
+
if (crypto_1.crypto && typeof crypto_1.crypto.getRandomValues === 'function') {
|
|
412
|
+
return crypto_1.crypto.getRandomValues(new Uint8Array(bytesLength));
|
|
413
|
+
}
|
|
414
|
+
// Legacy Node.js compatibility
|
|
415
|
+
if (crypto_1.crypto && typeof crypto_1.crypto.randomBytes === 'function') {
|
|
416
|
+
return Uint8Array.from(crypto_1.crypto.randomBytes(bytesLength));
|
|
417
|
+
}
|
|
418
|
+
throw new Error('crypto.getRandomValues must be defined');
|
|
419
|
+
}
|
|
420
|
+
|
|
421
|
+
} (utils));
|
|
422
|
+
|
|
423
|
+
Object.defineProperty(sha3$1, "__esModule", { value: true });
|
|
424
|
+
sha3$1.shake256 = sha3$1.shake128 = sha3$1.keccak_512 = sha3$1.keccak_384 = sha3$1.keccak_256 = sha3$1.keccak_224 = sha3$1.sha3_512 = sha3$1.sha3_384 = sha3$1.sha3_256 = sha3$1.sha3_224 = sha3$1.Keccak = void 0;
|
|
425
|
+
sha3$1.keccakP = keccakP;
|
|
426
|
+
/**
|
|
427
|
+
* SHA3 (keccak) hash function, based on a new "Sponge function" design.
|
|
428
|
+
* Different from older hashes, the internal state is bigger than output size.
|
|
429
|
+
*
|
|
430
|
+
* Check out [FIPS-202](https://nvlpubs.nist.gov/nistpubs/FIPS/NIST.FIPS.202.pdf),
|
|
431
|
+
* [Website](https://keccak.team/keccak.html),
|
|
432
|
+
* [the differences between SHA-3 and Keccak](https://crypto.stackexchange.com/questions/15727/what-are-the-key-differences-between-the-draft-sha-3-standard-and-the-keccak-sub).
|
|
433
|
+
*
|
|
434
|
+
* Check out `sha3-addons` module for cSHAKE, k12, and others.
|
|
435
|
+
* @module
|
|
436
|
+
*/
|
|
437
|
+
const _u64_ts_1 = _u64;
|
|
438
|
+
// prettier-ignore
|
|
439
|
+
const utils_ts_1 = utils;
|
|
440
|
+
// No __PURE__ annotations in sha3 header:
|
|
441
|
+
// EVERYTHING is in fact used on every export.
|
|
442
|
+
// Various per round constants calculations
|
|
443
|
+
const _0n = BigInt(0);
|
|
444
|
+
const _1n = BigInt(1);
|
|
445
|
+
const _2n = BigInt(2);
|
|
446
|
+
const _7n = BigInt(7);
|
|
447
|
+
const _256n = BigInt(256);
|
|
448
|
+
const _0x71n = BigInt(0x71);
|
|
449
|
+
const SHA3_PI = [];
|
|
450
|
+
const SHA3_ROTL = [];
|
|
451
|
+
const _SHA3_IOTA = [];
|
|
452
|
+
for (let round = 0, R = _1n, x = 1, y = 0; round < 24; round++) {
|
|
453
|
+
// Pi
|
|
454
|
+
[x, y] = [y, (2 * x + 3 * y) % 5];
|
|
455
|
+
SHA3_PI.push(2 * (5 * y + x));
|
|
456
|
+
// Rotational
|
|
457
|
+
SHA3_ROTL.push((((round + 1) * (round + 2)) / 2) % 64);
|
|
458
|
+
// Iota
|
|
459
|
+
let t = _0n;
|
|
460
|
+
for (let j = 0; j < 7; j++) {
|
|
461
|
+
R = ((R << _1n) ^ ((R >> _7n) * _0x71n)) % _256n;
|
|
462
|
+
if (R & _2n)
|
|
463
|
+
t ^= _1n << ((_1n << /* @__PURE__ */ BigInt(j)) - _1n);
|
|
464
|
+
}
|
|
465
|
+
_SHA3_IOTA.push(t);
|
|
466
|
+
}
|
|
467
|
+
const IOTAS = (0, _u64_ts_1.split)(_SHA3_IOTA, true);
|
|
468
|
+
const SHA3_IOTA_H = IOTAS[0];
|
|
469
|
+
const SHA3_IOTA_L = IOTAS[1];
|
|
470
|
+
// Left rotation (without 0, 32, 64)
|
|
471
|
+
const rotlH = (h, l, s) => (s > 32 ? (0, _u64_ts_1.rotlBH)(h, l, s) : (0, _u64_ts_1.rotlSH)(h, l, s));
|
|
472
|
+
const rotlL = (h, l, s) => (s > 32 ? (0, _u64_ts_1.rotlBL)(h, l, s) : (0, _u64_ts_1.rotlSL)(h, l, s));
|
|
473
|
+
/** `keccakf1600` internal function, additionally allows to adjust round count. */
|
|
474
|
+
function keccakP(s, rounds = 24) {
|
|
475
|
+
const B = new Uint32Array(5 * 2);
|
|
476
|
+
// NOTE: all indices are x2 since we store state as u32 instead of u64 (bigints to slow in js)
|
|
477
|
+
for (let round = 24 - rounds; round < 24; round++) {
|
|
478
|
+
// Theta θ
|
|
479
|
+
for (let x = 0; x < 10; x++)
|
|
480
|
+
B[x] = s[x] ^ s[x + 10] ^ s[x + 20] ^ s[x + 30] ^ s[x + 40];
|
|
481
|
+
for (let x = 0; x < 10; x += 2) {
|
|
482
|
+
const idx1 = (x + 8) % 10;
|
|
483
|
+
const idx0 = (x + 2) % 10;
|
|
484
|
+
const B0 = B[idx0];
|
|
485
|
+
const B1 = B[idx0 + 1];
|
|
486
|
+
const Th = rotlH(B0, B1, 1) ^ B[idx1];
|
|
487
|
+
const Tl = rotlL(B0, B1, 1) ^ B[idx1 + 1];
|
|
488
|
+
for (let y = 0; y < 50; y += 10) {
|
|
489
|
+
s[x + y] ^= Th;
|
|
490
|
+
s[x + y + 1] ^= Tl;
|
|
491
|
+
}
|
|
492
|
+
}
|
|
493
|
+
// Rho (ρ) and Pi (π)
|
|
494
|
+
let curH = s[2];
|
|
495
|
+
let curL = s[3];
|
|
496
|
+
for (let t = 0; t < 24; t++) {
|
|
497
|
+
const shift = SHA3_ROTL[t];
|
|
498
|
+
const Th = rotlH(curH, curL, shift);
|
|
499
|
+
const Tl = rotlL(curH, curL, shift);
|
|
500
|
+
const PI = SHA3_PI[t];
|
|
501
|
+
curH = s[PI];
|
|
502
|
+
curL = s[PI + 1];
|
|
503
|
+
s[PI] = Th;
|
|
504
|
+
s[PI + 1] = Tl;
|
|
505
|
+
}
|
|
506
|
+
// Chi (χ)
|
|
507
|
+
for (let y = 0; y < 50; y += 10) {
|
|
508
|
+
for (let x = 0; x < 10; x++)
|
|
509
|
+
B[x] = s[y + x];
|
|
510
|
+
for (let x = 0; x < 10; x++)
|
|
511
|
+
s[y + x] ^= ~B[(x + 2) % 10] & B[(x + 4) % 10];
|
|
512
|
+
}
|
|
513
|
+
// Iota (ι)
|
|
514
|
+
s[0] ^= SHA3_IOTA_H[round];
|
|
515
|
+
s[1] ^= SHA3_IOTA_L[round];
|
|
516
|
+
}
|
|
517
|
+
(0, utils_ts_1.clean)(B);
|
|
518
|
+
}
|
|
519
|
+
/** Keccak sponge function. */
|
|
520
|
+
class Keccak extends utils_ts_1.Hash {
|
|
521
|
+
// NOTE: we accept arguments in bytes instead of bits here.
|
|
522
|
+
constructor(blockLen, suffix, outputLen, enableXOF = false, rounds = 24) {
|
|
523
|
+
super();
|
|
524
|
+
this.pos = 0;
|
|
525
|
+
this.posOut = 0;
|
|
526
|
+
this.finished = false;
|
|
527
|
+
this.destroyed = false;
|
|
528
|
+
this.enableXOF = false;
|
|
529
|
+
this.blockLen = blockLen;
|
|
530
|
+
this.suffix = suffix;
|
|
531
|
+
this.outputLen = outputLen;
|
|
532
|
+
this.enableXOF = enableXOF;
|
|
533
|
+
this.rounds = rounds;
|
|
534
|
+
// Can be passed from user as dkLen
|
|
535
|
+
(0, utils_ts_1.anumber)(outputLen);
|
|
536
|
+
// 1600 = 5x5 matrix of 64bit. 1600 bits === 200 bytes
|
|
537
|
+
// 0 < blockLen < 200
|
|
538
|
+
if (!(0 < blockLen && blockLen < 200))
|
|
539
|
+
throw new Error('only keccak-f1600 function is supported');
|
|
540
|
+
this.state = new Uint8Array(200);
|
|
541
|
+
this.state32 = (0, utils_ts_1.u32)(this.state);
|
|
542
|
+
}
|
|
543
|
+
clone() {
|
|
544
|
+
return this._cloneInto();
|
|
545
|
+
}
|
|
546
|
+
keccak() {
|
|
547
|
+
(0, utils_ts_1.swap32IfBE)(this.state32);
|
|
548
|
+
keccakP(this.state32, this.rounds);
|
|
549
|
+
(0, utils_ts_1.swap32IfBE)(this.state32);
|
|
550
|
+
this.posOut = 0;
|
|
551
|
+
this.pos = 0;
|
|
552
|
+
}
|
|
553
|
+
update(data) {
|
|
554
|
+
(0, utils_ts_1.aexists)(this);
|
|
555
|
+
data = (0, utils_ts_1.toBytes)(data);
|
|
556
|
+
(0, utils_ts_1.abytes)(data);
|
|
557
|
+
const { blockLen, state } = this;
|
|
558
|
+
const len = data.length;
|
|
559
|
+
for (let pos = 0; pos < len;) {
|
|
560
|
+
const take = Math.min(blockLen - this.pos, len - pos);
|
|
561
|
+
for (let i = 0; i < take; i++)
|
|
562
|
+
state[this.pos++] ^= data[pos++];
|
|
563
|
+
if (this.pos === blockLen)
|
|
564
|
+
this.keccak();
|
|
565
|
+
}
|
|
566
|
+
return this;
|
|
567
|
+
}
|
|
568
|
+
finish() {
|
|
569
|
+
if (this.finished)
|
|
570
|
+
return;
|
|
571
|
+
this.finished = true;
|
|
572
|
+
const { state, suffix, pos, blockLen } = this;
|
|
573
|
+
// Do the padding
|
|
574
|
+
state[pos] ^= suffix;
|
|
575
|
+
if ((suffix & 0x80) !== 0 && pos === blockLen - 1)
|
|
576
|
+
this.keccak();
|
|
577
|
+
state[blockLen - 1] ^= 0x80;
|
|
578
|
+
this.keccak();
|
|
579
|
+
}
|
|
580
|
+
writeInto(out) {
|
|
581
|
+
(0, utils_ts_1.aexists)(this, false);
|
|
582
|
+
(0, utils_ts_1.abytes)(out);
|
|
583
|
+
this.finish();
|
|
584
|
+
const bufferOut = this.state;
|
|
585
|
+
const { blockLen } = this;
|
|
586
|
+
for (let pos = 0, len = out.length; pos < len;) {
|
|
587
|
+
if (this.posOut >= blockLen)
|
|
588
|
+
this.keccak();
|
|
589
|
+
const take = Math.min(blockLen - this.posOut, len - pos);
|
|
590
|
+
out.set(bufferOut.subarray(this.posOut, this.posOut + take), pos);
|
|
591
|
+
this.posOut += take;
|
|
592
|
+
pos += take;
|
|
593
|
+
}
|
|
594
|
+
return out;
|
|
595
|
+
}
|
|
596
|
+
xofInto(out) {
|
|
597
|
+
// Sha3/Keccak usage with XOF is probably mistake, only SHAKE instances can do XOF
|
|
598
|
+
if (!this.enableXOF)
|
|
599
|
+
throw new Error('XOF is not possible for this instance');
|
|
600
|
+
return this.writeInto(out);
|
|
601
|
+
}
|
|
602
|
+
xof(bytes) {
|
|
603
|
+
(0, utils_ts_1.anumber)(bytes);
|
|
604
|
+
return this.xofInto(new Uint8Array(bytes));
|
|
605
|
+
}
|
|
606
|
+
digestInto(out) {
|
|
607
|
+
(0, utils_ts_1.aoutput)(out, this);
|
|
608
|
+
if (this.finished)
|
|
609
|
+
throw new Error('digest() was already called');
|
|
610
|
+
this.writeInto(out);
|
|
611
|
+
this.destroy();
|
|
612
|
+
return out;
|
|
613
|
+
}
|
|
614
|
+
digest() {
|
|
615
|
+
return this.digestInto(new Uint8Array(this.outputLen));
|
|
616
|
+
}
|
|
617
|
+
destroy() {
|
|
618
|
+
this.destroyed = true;
|
|
619
|
+
(0, utils_ts_1.clean)(this.state);
|
|
620
|
+
}
|
|
621
|
+
_cloneInto(to) {
|
|
622
|
+
const { blockLen, suffix, outputLen, rounds, enableXOF } = this;
|
|
623
|
+
to || (to = new Keccak(blockLen, suffix, outputLen, enableXOF, rounds));
|
|
624
|
+
to.state32.set(this.state32);
|
|
625
|
+
to.pos = this.pos;
|
|
626
|
+
to.posOut = this.posOut;
|
|
627
|
+
to.finished = this.finished;
|
|
628
|
+
to.rounds = rounds;
|
|
629
|
+
// Suffix can change in cSHAKE
|
|
630
|
+
to.suffix = suffix;
|
|
631
|
+
to.outputLen = outputLen;
|
|
632
|
+
to.enableXOF = enableXOF;
|
|
633
|
+
to.destroyed = this.destroyed;
|
|
634
|
+
return to;
|
|
635
|
+
}
|
|
636
|
+
}
|
|
637
|
+
sha3$1.Keccak = Keccak;
|
|
638
|
+
const gen = (suffix, blockLen, outputLen) => (0, utils_ts_1.createHasher)(() => new Keccak(blockLen, suffix, outputLen));
|
|
639
|
+
/** SHA3-224 hash function. */
|
|
640
|
+
sha3$1.sha3_224 = (() => gen(0x06, 144, 224 / 8))();
|
|
641
|
+
/** SHA3-256 hash function. Different from keccak-256. */
|
|
642
|
+
sha3$1.sha3_256 = (() => gen(0x06, 136, 256 / 8))();
|
|
643
|
+
/** SHA3-384 hash function. */
|
|
644
|
+
sha3$1.sha3_384 = (() => gen(0x06, 104, 384 / 8))();
|
|
645
|
+
/** SHA3-512 hash function. */
|
|
646
|
+
sha3$1.sha3_512 = (() => gen(0x06, 72, 512 / 8))();
|
|
647
|
+
/** keccak-224 hash function. */
|
|
648
|
+
sha3$1.keccak_224 = (() => gen(0x01, 144, 224 / 8))();
|
|
649
|
+
/** keccak-256 hash function. Different from SHA3-256. */
|
|
650
|
+
sha3$1.keccak_256 = (() => gen(0x01, 136, 256 / 8))();
|
|
651
|
+
/** keccak-384 hash function. */
|
|
652
|
+
sha3$1.keccak_384 = (() => gen(0x01, 104, 384 / 8))();
|
|
653
|
+
/** keccak-512 hash function. */
|
|
654
|
+
sha3$1.keccak_512 = (() => gen(0x01, 72, 512 / 8))();
|
|
655
|
+
const genShake = (suffix, blockLen, outputLen) => (0, utils_ts_1.createXOFer)((opts = {}) => new Keccak(blockLen, suffix, opts.dkLen === undefined ? outputLen : opts.dkLen, true));
|
|
656
|
+
/** SHAKE128 XOF with 128-bit security. */
|
|
657
|
+
sha3$1.shake128 = (() => genShake(0x1f, 168, 128 / 8))();
|
|
658
|
+
/** SHAKE256 XOF with 256-bit security. */
|
|
659
|
+
sha3$1.shake256 = (() => genShake(0x1f, 136, 256 / 8))();
|
|
660
|
+
|
|
661
|
+
/* global global, window, module */
|
|
662
|
+
|
|
663
|
+
const { sha3_512: sha3 } = sha3$1;
|
|
664
|
+
|
|
665
|
+
const defaultLength = 24;
|
|
666
|
+
const bigLength = 32;
|
|
667
|
+
|
|
668
|
+
const createEntropy = (length = 4, random = Math.random) => {
|
|
669
|
+
let entropy = "";
|
|
670
|
+
|
|
671
|
+
while (entropy.length < length) {
|
|
672
|
+
entropy = entropy + Math.floor(random() * 36).toString(36);
|
|
673
|
+
}
|
|
674
|
+
return entropy;
|
|
675
|
+
};
|
|
676
|
+
|
|
677
|
+
/*
|
|
678
|
+
* Adapted from https://github.com/juanelas/bigint-conversion
|
|
679
|
+
* MIT License Copyright (c) 2018 Juan Hernández Serrano
|
|
680
|
+
*/
|
|
681
|
+
function bufToBigInt(buf) {
|
|
682
|
+
let bits = 8n;
|
|
683
|
+
|
|
684
|
+
let value = 0n;
|
|
685
|
+
for (const i of buf.values()) {
|
|
686
|
+
const bi = BigInt(i);
|
|
687
|
+
value = (value << bits) + bi;
|
|
688
|
+
}
|
|
689
|
+
return value;
|
|
690
|
+
}
|
|
691
|
+
|
|
692
|
+
const hash = (input = "") => {
|
|
693
|
+
// Drop the first character because it will bias the histogram
|
|
694
|
+
// to the left.
|
|
695
|
+
return bufToBigInt(sha3(input)).toString(36).slice(1);
|
|
696
|
+
};
|
|
697
|
+
|
|
698
|
+
const alphabet = Array.from({ length: 26 }, (x, i) =>
|
|
699
|
+
String.fromCharCode(i + 97)
|
|
700
|
+
);
|
|
701
|
+
|
|
702
|
+
const randomLetter = (random) =>
|
|
703
|
+
alphabet[Math.floor(random() * alphabet.length)];
|
|
704
|
+
|
|
705
|
+
/*
|
|
706
|
+
This is a fingerprint of the host environment. It is used to help
|
|
707
|
+
prevent collisions when generating ids in a distributed system.
|
|
708
|
+
If no global object is available, you can pass in your own, or fall back
|
|
709
|
+
on a random string.
|
|
710
|
+
*/
|
|
711
|
+
const createFingerprint = ({
|
|
712
|
+
globalObj = typeof commonjsGlobal !== "undefined"
|
|
713
|
+
? commonjsGlobal
|
|
714
|
+
: typeof window !== "undefined"
|
|
715
|
+
? window
|
|
716
|
+
: {},
|
|
717
|
+
random = Math.random,
|
|
718
|
+
} = {}) => {
|
|
719
|
+
const globals = Object.keys(globalObj).toString();
|
|
720
|
+
const sourceString = globals.length
|
|
721
|
+
? globals + createEntropy(bigLength, random)
|
|
722
|
+
: createEntropy(bigLength, random);
|
|
723
|
+
|
|
724
|
+
return hash(sourceString).substring(0, bigLength);
|
|
725
|
+
};
|
|
726
|
+
|
|
727
|
+
const createCounter = (count) => () => {
|
|
728
|
+
return count++;
|
|
729
|
+
};
|
|
730
|
+
|
|
731
|
+
// ~22k hosts before 50% chance of initial counter collision
|
|
732
|
+
// with a remaining counter range of 9.0e+15 in JavaScript.
|
|
733
|
+
const initialCountMax = 476782367;
|
|
734
|
+
|
|
735
|
+
const init = ({
|
|
736
|
+
// Fallback if the user does not pass in a CSPRNG. This should be OK
|
|
737
|
+
// because we don't rely solely on the random number generator for entropy.
|
|
738
|
+
// We also use the host fingerprint, current time, and a session counter.
|
|
739
|
+
random = Math.random,
|
|
740
|
+
counter = createCounter(Math.floor(random() * initialCountMax)),
|
|
741
|
+
length = defaultLength,
|
|
742
|
+
fingerprint = createFingerprint({ random }),
|
|
743
|
+
} = {}) => {
|
|
744
|
+
return function cuid2() {
|
|
745
|
+
const firstLetter = randomLetter(random);
|
|
746
|
+
|
|
747
|
+
// If we're lucky, the `.toString(36)` calls may reduce hashing rounds
|
|
748
|
+
// by shortening the input to the hash function a little.
|
|
749
|
+
const time = Date.now().toString(36);
|
|
750
|
+
const count = counter().toString(36);
|
|
751
|
+
|
|
752
|
+
// The salt should be long enough to be globally unique across the full
|
|
753
|
+
// length of the hash. For simplicity, we use the same length as the
|
|
754
|
+
// intended id output.
|
|
755
|
+
const salt = createEntropy(length, random);
|
|
756
|
+
const hashInput = `${time + salt + count + fingerprint}`;
|
|
757
|
+
|
|
758
|
+
return `${firstLetter + hash(hashInput).substring(1, length)}`;
|
|
759
|
+
};
|
|
760
|
+
};
|
|
761
|
+
|
|
762
|
+
const createId$1 = init();
|
|
763
|
+
|
|
764
|
+
const isCuid = (id, { minLength = 2, maxLength = bigLength } = {}) => {
|
|
765
|
+
const length = id.length;
|
|
766
|
+
const regex = /^[0-9a-z]+$/;
|
|
767
|
+
|
|
768
|
+
try {
|
|
769
|
+
if (
|
|
770
|
+
typeof id === "string" &&
|
|
771
|
+
length >= minLength &&
|
|
772
|
+
length <= maxLength &&
|
|
773
|
+
regex.test(id)
|
|
774
|
+
)
|
|
775
|
+
return true;
|
|
776
|
+
} finally {
|
|
777
|
+
}
|
|
778
|
+
|
|
779
|
+
return false;
|
|
780
|
+
};
|
|
781
|
+
|
|
782
|
+
src.getConstants = () => ({ defaultLength, bigLength });
|
|
783
|
+
src.init = init;
|
|
784
|
+
src.createId = createId$1;
|
|
785
|
+
src.bufToBigInt = bufToBigInt;
|
|
786
|
+
src.createCounter = createCounter;
|
|
787
|
+
src.createFingerprint = createFingerprint;
|
|
788
|
+
src.isCuid = isCuid;
|
|
789
|
+
|
|
790
|
+
const { createId} = src;
|
|
791
|
+
|
|
792
|
+
var createId_1 = createId;
|
|
793
|
+
|
|
794
|
+
/**
|
|
795
|
+
* Serialize a send input into its wire payload, driven by the generated model
|
|
796
|
+
* descriptors: fields are emitted in declaration order under their `@map`'d
|
|
797
|
+
* wire names, absent fields with an `@default` are injected (literals
|
|
798
|
+
* verbatim, `now()`/`uuid()`/`cuid()` generated at send time), absent optional
|
|
799
|
+
* fields are omitted, nested models recurse, and enum members serialize to
|
|
800
|
+
* their (possibly `@map`'d) wire values.
|
|
801
|
+
*/
|
|
802
|
+
function serializeModel(models, modelName, data) {
|
|
803
|
+
const descriptor = models[modelName];
|
|
804
|
+
if (!descriptor) {
|
|
805
|
+
throw new Error(`@repost/client: no serialization descriptor for model \`${modelName}\`.`);
|
|
806
|
+
}
|
|
807
|
+
if (typeof data !== "object" || data === null || Array.isArray(data)) {
|
|
808
|
+
const got = data === null ? "null" : Array.isArray(data) ? "an array" : typeof data;
|
|
809
|
+
throw new Error(`@repost/client: expected an object for model \`${modelName}\`, got ${got}.`);
|
|
810
|
+
}
|
|
811
|
+
const input = data;
|
|
812
|
+
const payload = {};
|
|
813
|
+
for (const field of descriptor.fields) {
|
|
814
|
+
let value = input[field.name];
|
|
815
|
+
if (value === undefined) {
|
|
816
|
+
if (!field.default)
|
|
817
|
+
continue; // optional and absent — omitted from the wire
|
|
818
|
+
value = resolveDefault(field.default);
|
|
819
|
+
}
|
|
820
|
+
payload[field.wire ?? field.name] = serializeValue(models, field, value);
|
|
821
|
+
}
|
|
822
|
+
return payload;
|
|
823
|
+
}
|
|
824
|
+
function serializeValue(models, field, value) {
|
|
825
|
+
if (field.list && Array.isArray(value)) {
|
|
826
|
+
return value.map((item) => serializeItem(models, field, item));
|
|
827
|
+
}
|
|
828
|
+
return serializeItem(models, field, value);
|
|
829
|
+
}
|
|
830
|
+
function serializeItem(models, field, value) {
|
|
831
|
+
if (field.model) {
|
|
832
|
+
return serializeModel(models, field.model, value);
|
|
833
|
+
}
|
|
834
|
+
if (field.enum) {
|
|
835
|
+
const wire = field.enum[value];
|
|
836
|
+
return wire === undefined ? value : wire;
|
|
837
|
+
}
|
|
838
|
+
return value;
|
|
839
|
+
}
|
|
840
|
+
function resolveDefault(spec) {
|
|
841
|
+
switch (spec.kind) {
|
|
842
|
+
case "literal":
|
|
843
|
+
return spec.value;
|
|
844
|
+
case "now":
|
|
845
|
+
return new Date().toISOString();
|
|
846
|
+
case "uuid":
|
|
847
|
+
return crypto.randomUUID();
|
|
848
|
+
case "cuid":
|
|
849
|
+
return createId_1();
|
|
850
|
+
}
|
|
851
|
+
}
|
|
852
|
+
|
|
853
|
+
const DEFAULT_API_URL = "https://api.repost.sh";
|
|
854
|
+
const RETRY_AFTER_CAP_MS = 60000;
|
|
855
|
+
const DEFAULT_TIMEOUT_MS = 30000;
|
|
856
|
+
/** The publish API's body cap (publish-api handler.go `MaxBodyBytes`). */
|
|
857
|
+
const MAX_PAYLOAD_BYTES = 1 << 20;
|
|
858
|
+
/** A publish rejected or failed by the Repost API. */
|
|
859
|
+
class RepostPublishError extends Error {
|
|
860
|
+
constructor(message, status, body) {
|
|
861
|
+
super(message);
|
|
862
|
+
this.name = "RepostPublishError";
|
|
863
|
+
this.status = status;
|
|
864
|
+
this.body = body;
|
|
865
|
+
}
|
|
866
|
+
}
|
|
867
|
+
/**
|
|
868
|
+
* The HTTP transport against Repost's publish API (workstream A).
|
|
869
|
+
*
|
|
870
|
+
* One idempotency key is minted per send() and reused across internal
|
|
871
|
+
* retries, so retrying is always safe: the server deduplicates. Retryable
|
|
872
|
+
* outcomes are network errors, 5xx, 429, and 409 (a concurrent duplicate
|
|
873
|
+
* still in flight); Retry-After is honored when present.
|
|
874
|
+
*/
|
|
875
|
+
function createHttpTransport(options = {}) {
|
|
876
|
+
// Resolved per call, not bound at construction: the default `httpTransport`
|
|
877
|
+
// is a module-level singleton, and eager binding would freeze whatever
|
|
878
|
+
// `globalThis.fetch` was at import time — invisible to later patching
|
|
879
|
+
// (APM instrumentation, test stubs, polyfills).
|
|
880
|
+
const fetchImpl = options.fetch ?? ((input, init) => globalThis.fetch(input, init));
|
|
881
|
+
const maxRetries = options.maxRetries ?? 3;
|
|
882
|
+
const baseDelayMs = options.baseDelayMs ?? 250;
|
|
883
|
+
const timeoutMs = options.timeoutMs ?? DEFAULT_TIMEOUT_MS;
|
|
884
|
+
return {
|
|
885
|
+
async send(request) {
|
|
886
|
+
const base = (request.apiUrl ?? DEFAULT_API_URL).replace(/\/+$/, "");
|
|
887
|
+
const url = `${base}/v1/messages`;
|
|
888
|
+
const idempotencyKey = request.idempotencyKey ?? generateIdempotencyKey();
|
|
889
|
+
const body = JSON.stringify({
|
|
890
|
+
type: request.envelope.type,
|
|
891
|
+
customerId: request.customerId,
|
|
892
|
+
timestamp: request.envelope.timestamp,
|
|
893
|
+
data: request.envelope.data,
|
|
894
|
+
});
|
|
895
|
+
// The API rejects oversized bodies with a 413; failing before the first
|
|
896
|
+
// attempt gives the caller the byte count instead of burned retries.
|
|
897
|
+
const bodyBytes = new TextEncoder().encode(body).length;
|
|
898
|
+
if (bodyBytes > MAX_PAYLOAD_BYTES) {
|
|
899
|
+
throw new RepostPublishError(`publish body is ${bodyBytes} bytes, over the API's 1 MiB (${MAX_PAYLOAD_BYTES}-byte) limit`);
|
|
900
|
+
}
|
|
901
|
+
let lastError = new RepostPublishError("publish failed before any attempt");
|
|
902
|
+
let retryAfterMs;
|
|
903
|
+
for (let attempt = 0; attempt <= maxRetries; attempt++) {
|
|
904
|
+
if (attempt > 0) {
|
|
905
|
+
await sleep(retryDelayMs(attempt, baseDelayMs, retryAfterMs));
|
|
906
|
+
}
|
|
907
|
+
// One timeout budget covers the attempt end to end — connect,
|
|
908
|
+
// response headers, and body reads — so a hung connection can never
|
|
909
|
+
// block send() past timeoutMs.
|
|
910
|
+
const signal = AbortSignal.timeout(timeoutMs);
|
|
911
|
+
let response;
|
|
912
|
+
try {
|
|
913
|
+
response = await fetchImpl(url, {
|
|
914
|
+
method: "POST",
|
|
915
|
+
headers: {
|
|
916
|
+
authorization: `Bearer ${request.token}`,
|
|
917
|
+
"content-type": "application/json",
|
|
918
|
+
"idempotency-key": idempotencyKey,
|
|
919
|
+
},
|
|
920
|
+
body,
|
|
921
|
+
signal,
|
|
922
|
+
});
|
|
923
|
+
}
|
|
924
|
+
catch (error) {
|
|
925
|
+
lastError = new RepostPublishError(describeAttemptFailure(error, timeoutMs));
|
|
926
|
+
continue;
|
|
927
|
+
}
|
|
928
|
+
if (response.ok) {
|
|
929
|
+
try {
|
|
930
|
+
return (await response.json());
|
|
931
|
+
}
|
|
932
|
+
catch (error) {
|
|
933
|
+
lastError = new RepostPublishError(describeAttemptFailure(error, timeoutMs));
|
|
934
|
+
continue;
|
|
935
|
+
}
|
|
936
|
+
}
|
|
937
|
+
const errorBody = await response.json().catch(() => undefined);
|
|
938
|
+
retryAfterMs = parseRetryAfterMs(response.headers.get("retry-after"));
|
|
939
|
+
lastError = new RepostPublishError(`publish failed with status ${response.status}`, response.status, errorBody);
|
|
940
|
+
const retryable = response.status >= 500 || response.status === 429 || response.status === 409;
|
|
941
|
+
if (!retryable) {
|
|
942
|
+
throw lastError;
|
|
943
|
+
}
|
|
944
|
+
}
|
|
945
|
+
throw lastError;
|
|
946
|
+
},
|
|
947
|
+
};
|
|
948
|
+
}
|
|
949
|
+
/** Render an attempt failure, distinguishing our own timeout abort. */
|
|
950
|
+
function describeAttemptFailure(error, timeoutMs) {
|
|
951
|
+
// AbortSignal.timeout rejects with TimeoutError; some fetch mocks and older
|
|
952
|
+
// runtimes surface plain AbortError for an aborted signal.
|
|
953
|
+
if (error instanceof Error && (error.name === "TimeoutError" || error.name === "AbortError")) {
|
|
954
|
+
return `publish attempt timed out after ${timeoutMs}ms`;
|
|
955
|
+
}
|
|
956
|
+
return `publish request failed: ${String(error)}`;
|
|
957
|
+
}
|
|
958
|
+
/** The default transport: real HTTP against the publish API. */
|
|
959
|
+
const httpTransport = createHttpTransport();
|
|
960
|
+
function generateIdempotencyKey() {
|
|
961
|
+
const cryptoObj = globalThis.crypto;
|
|
962
|
+
if (typeof cryptoObj.randomUUID === "function") {
|
|
963
|
+
return cryptoObj.randomUUID();
|
|
964
|
+
}
|
|
965
|
+
return `${Date.now().toString(36)}-${Math.random().toString(36).slice(2)}-${Math.random().toString(36).slice(2)}`;
|
|
966
|
+
}
|
|
967
|
+
function retryDelayMs(attempt, baseDelayMs, retryAfterMs) {
|
|
968
|
+
const backoff = baseDelayMs * 2 ** (attempt - 1) * (0.5 + Math.random() * 0.5);
|
|
969
|
+
if (retryAfterMs !== undefined && retryAfterMs > backoff) {
|
|
970
|
+
return Math.min(retryAfterMs, RETRY_AFTER_CAP_MS);
|
|
971
|
+
}
|
|
972
|
+
return backoff;
|
|
973
|
+
}
|
|
974
|
+
function parseRetryAfterMs(header) {
|
|
975
|
+
if (header === null)
|
|
976
|
+
return undefined;
|
|
977
|
+
const seconds = Number(header);
|
|
978
|
+
if (Number.isFinite(seconds) && seconds >= 0) {
|
|
979
|
+
return seconds * 1000;
|
|
980
|
+
}
|
|
981
|
+
return undefined;
|
|
982
|
+
}
|
|
983
|
+
function sleep(ms) {
|
|
984
|
+
return new Promise((resolve) => setTimeout(resolve, ms));
|
|
985
|
+
}
|
|
986
|
+
|
|
987
|
+
/**
|
|
988
|
+
* No-network transport for tests: echoes the envelope identity as a typed
|
|
989
|
+
* `SendResult` with a fixed stub message id.
|
|
990
|
+
*/
|
|
991
|
+
const stubTransport = {
|
|
992
|
+
async send(request) {
|
|
993
|
+
return {
|
|
994
|
+
id: "msg_stub",
|
|
995
|
+
type: request.envelope.type,
|
|
996
|
+
customerId: request.customerId,
|
|
997
|
+
timestamp: request.envelope.timestamp,
|
|
998
|
+
};
|
|
999
|
+
},
|
|
1000
|
+
};
|
|
1001
|
+
/**
|
|
1002
|
+
* Build the webhooks method tree from the generated schema descriptor. The
|
|
1003
|
+
* generated client instantiates this as its typed `Webhooks` interface — the
|
|
1004
|
+
* tree shape is guaranteed by codegen, which emits interface and descriptors
|
|
1005
|
+
* from the same catalog.
|
|
1006
|
+
*/
|
|
1007
|
+
function buildWebhooks(options, schema) {
|
|
1008
|
+
const tree = {};
|
|
1009
|
+
for (const [group, members] of Object.entries(schema.webhooks)) {
|
|
1010
|
+
const groupTree = {};
|
|
1011
|
+
for (const [member, event] of Object.entries(members)) {
|
|
1012
|
+
groupTree[member] = (input) => send(options, schema, event, input);
|
|
1013
|
+
}
|
|
1014
|
+
tree[group] = groupTree;
|
|
1015
|
+
}
|
|
1016
|
+
return tree;
|
|
1017
|
+
}
|
|
1018
|
+
async function send(options, schema, event, input) {
|
|
1019
|
+
// Lazy configuration: resolved (and enforced) at send time, not construction.
|
|
1020
|
+
// First defined value wins: the apiKey option, the deprecated token option,
|
|
1021
|
+
// REPOST_SEND_API_KEY (the standard `.env` variable), then legacy REPOST_TOKEN.
|
|
1022
|
+
const apiKey = options.apiKey ?? options.token ?? process.env.REPOST_SEND_API_KEY ?? process.env.REPOST_TOKEN;
|
|
1023
|
+
if (!apiKey) {
|
|
1024
|
+
throw new Error("@repost/client: missing API key. Pass `apiKey` to createRepostClient() or set the REPOST_SEND_API_KEY environment variable (scaffolded in `.env` by `repost schema init`; create a key with your environment in the dashboard).");
|
|
1025
|
+
}
|
|
1026
|
+
const apiUrl = options.apiUrl ?? process.env.REPOST_API_URL;
|
|
1027
|
+
// The Standard Webhooks envelope: { type, timestamp, data }.
|
|
1028
|
+
const envelope = {
|
|
1029
|
+
type: event.type,
|
|
1030
|
+
timestamp: new Date().toISOString(),
|
|
1031
|
+
data: serializeModel(schema.models, event.model, input.data),
|
|
1032
|
+
};
|
|
1033
|
+
const transport = options.transport ?? httpTransport;
|
|
1034
|
+
return transport.send({
|
|
1035
|
+
token: apiKey,
|
|
1036
|
+
apiUrl,
|
|
1037
|
+
customerId: input.customerId,
|
|
1038
|
+
idempotencyKey: input.idempotencyKey,
|
|
1039
|
+
envelope,
|
|
1040
|
+
});
|
|
1041
|
+
}
|
|
1042
|
+
|
|
1043
|
+
exports.RepostPublishError = RepostPublishError;
|
|
1044
|
+
exports.buildWebhooks = buildWebhooks;
|
|
1045
|
+
exports.createHttpTransport = createHttpTransport;
|
|
1046
|
+
exports.httpTransport = httpTransport;
|
|
1047
|
+
exports.serializeModel = serializeModel;
|
|
1048
|
+
exports.stubTransport = stubTransport;
|
|
1049
|
+
//# sourceMappingURL=index.cjs.map
|