@repost/client 0.2.0 → 0.4.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/README.md +15 -85
- package/dist/cjs/index-e0zw7VDH.cjs +2987 -0
- package/dist/cjs/index-e0zw7VDH.cjs.map +1 -0
- package/dist/cjs/index.cjs +23 -1046
- package/dist/cjs/index.cjs.map +1 -1
- package/dist/cjs/node-Dd92VNS7.cjs +841 -0
- package/dist/cjs/node-Dd92VNS7.cjs.map +1 -0
- package/dist/cjs/observer-dykSFHYi.cjs +69 -0
- package/dist/cjs/observer-dykSFHYi.cjs.map +1 -0
- package/dist/cjs/otel/index.cjs +99 -0
- package/dist/cjs/otel/index.cjs.map +1 -0
- package/dist/cjs/testing/index.cjs +257 -0
- package/dist/cjs/testing/index.cjs.map +1 -0
- package/dist/cjs/types/config.d.ts +28 -0
- package/dist/cjs/types/errors.d.ts +83 -0
- package/dist/cjs/types/index.d.ts +8 -3
- package/dist/cjs/types/observer.d.ts +44 -0
- package/dist/cjs/types/operation-events.d.ts +8 -0
- package/dist/cjs/types/operation-input.d.ts +5 -0
- package/dist/cjs/types/operation-policy.d.ts +23 -0
- package/dist/cjs/types/operation.d.ts +14 -0
- package/dist/cjs/types/otel/index.d.ts +2 -0
- package/dist/cjs/types/otel/metrics.d.ts +5 -0
- package/dist/cjs/types/otel/telemetry.d.ts +5 -0
- package/dist/cjs/types/runtime-state.d.ts +45 -0
- package/dist/cjs/types/serialize.d.ts +9 -3
- package/dist/cjs/types/telemetry.d.ts +43 -0
- package/dist/cjs/types/testing/deterministic.d.ts +19 -0
- package/dist/cjs/types/testing/index.d.ts +16 -0
- package/dist/cjs/types/testing/manual-clock.d.ts +12 -0
- package/dist/cjs/types/testing/recording-observer.d.ts +11 -0
- package/dist/cjs/types/testing/stub-transport.d.ts +35 -0
- package/dist/cjs/types/transport/connect-proxy.d.ts +30 -0
- package/dist/cjs/types/transport/failure.d.ts +7 -0
- package/dist/cjs/types/transport/framing.d.ts +8 -0
- package/dist/cjs/types/transport/h2.d.ts +3 -0
- package/dist/cjs/types/transport/node.d.ts +3 -0
- package/dist/cjs/types/transport/response-reader.d.ts +6 -0
- package/dist/cjs/types/transport/strict-json.d.ts +5 -0
- package/dist/cjs/types/transport/tls.d.ts +14 -0
- package/dist/cjs/types/transport/undici-compat.d.ts +47 -0
- package/dist/cjs/types/transport.d.ts +42 -19
- package/dist/cjs/types/types.d.ts +146 -23
- package/dist/cjs/types/version.d.ts +2 -0
- package/dist/cjs/types/webhooks.d.ts +15 -0
- package/dist/cjs/version-CGqSWJir.cjs +7 -0
- package/dist/cjs/version-CGqSWJir.cjs.map +1 -0
- package/dist/esm/index-DRD5FBax.mjs +2967 -0
- package/dist/esm/index-DRD5FBax.mjs.map +1 -0
- package/dist/esm/index.mjs +3 -1041
- package/dist/esm/index.mjs.map +1 -1
- package/dist/esm/node-BAJt_qhB.mjs +839 -0
- package/dist/esm/node-BAJt_qhB.mjs.map +1 -0
- package/dist/esm/observer-Dns2X4wE.mjs +66 -0
- package/dist/esm/observer-Dns2X4wE.mjs.map +1 -0
- package/dist/esm/otel/index.mjs +96 -0
- package/dist/esm/otel/index.mjs.map +1 -0
- package/dist/esm/testing/index.mjs +248 -0
- package/dist/esm/testing/index.mjs.map +1 -0
- package/dist/esm/version-Dp5vd2nu.mjs +5 -0
- package/dist/esm/version-Dp5vd2nu.mjs.map +1 -0
- package/index.d.ts +1 -1
- package/index.js +3 -4
- package/index.mjs +1 -1
- package/otel/index.d.ts +1 -0
- package/otel/index.js +3 -0
- package/otel/index.mjs +1 -0
- package/package.json +38 -9
- package/runtime/index.d.ts +1 -1
- package/runtime/index.js +2 -2
- package/runtime/index.mjs +1 -1
- package/scripts/postinstall.js +2 -2
- package/testing/index.d.ts +1 -0
- package/testing/index.js +3 -0
- package/testing/index.mjs +1 -0
|
@@ -0,0 +1,2967 @@
|
|
|
1
|
+
import { P as PACKAGE_VERSION } from './version-Dp5vd2nu.mjs';
|
|
2
|
+
import { O as ObserverDispatcher } from './observer-Dns2X4wE.mjs';
|
|
3
|
+
|
|
4
|
+
var commonjsGlobal = typeof globalThis !== 'undefined' ? globalThis : typeof window !== 'undefined' ? window : typeof global !== 'undefined' ? global : typeof self !== 'undefined' ? self : {};
|
|
5
|
+
|
|
6
|
+
var src = {};
|
|
7
|
+
|
|
8
|
+
var sha3$1 = {};
|
|
9
|
+
|
|
10
|
+
var _u64 = {};
|
|
11
|
+
|
|
12
|
+
Object.defineProperty(_u64, "__esModule", { value: true });
|
|
13
|
+
_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;
|
|
14
|
+
_u64.add = add;
|
|
15
|
+
_u64.fromBig = fromBig;
|
|
16
|
+
_u64.split = split;
|
|
17
|
+
/**
|
|
18
|
+
* Internal helpers for u64. BigUint64Array is too slow as per 2025, so we implement it using Uint32Array.
|
|
19
|
+
* @todo re-check https://issues.chromium.org/issues/42212588
|
|
20
|
+
* @module
|
|
21
|
+
*/
|
|
22
|
+
const U32_MASK64 = /* @__PURE__ */ BigInt(2 ** 32 - 1);
|
|
23
|
+
const _32n = /* @__PURE__ */ BigInt(32);
|
|
24
|
+
function fromBig(n, le = false) {
|
|
25
|
+
if (le)
|
|
26
|
+
return { h: Number(n & U32_MASK64), l: Number((n >> _32n) & U32_MASK64) };
|
|
27
|
+
return { h: Number((n >> _32n) & U32_MASK64) | 0, l: Number(n & U32_MASK64) | 0 };
|
|
28
|
+
}
|
|
29
|
+
function split(lst, le = false) {
|
|
30
|
+
const len = lst.length;
|
|
31
|
+
let Ah = new Uint32Array(len);
|
|
32
|
+
let Al = new Uint32Array(len);
|
|
33
|
+
for (let i = 0; i < len; i++) {
|
|
34
|
+
const { h, l } = fromBig(lst[i], le);
|
|
35
|
+
[Ah[i], Al[i]] = [h, l];
|
|
36
|
+
}
|
|
37
|
+
return [Ah, Al];
|
|
38
|
+
}
|
|
39
|
+
const toBig = (h, l) => (BigInt(h >>> 0) << _32n) | BigInt(l >>> 0);
|
|
40
|
+
_u64.toBig = toBig;
|
|
41
|
+
// for Shift in [0, 32)
|
|
42
|
+
const shrSH = (h, _l, s) => h >>> s;
|
|
43
|
+
_u64.shrSH = shrSH;
|
|
44
|
+
const shrSL = (h, l, s) => (h << (32 - s)) | (l >>> s);
|
|
45
|
+
_u64.shrSL = shrSL;
|
|
46
|
+
// Right rotate for Shift in [1, 32)
|
|
47
|
+
const rotrSH = (h, l, s) => (h >>> s) | (l << (32 - s));
|
|
48
|
+
_u64.rotrSH = rotrSH;
|
|
49
|
+
const rotrSL = (h, l, s) => (h << (32 - s)) | (l >>> s);
|
|
50
|
+
_u64.rotrSL = rotrSL;
|
|
51
|
+
// Right rotate for Shift in (32, 64), NOTE: 32 is special case.
|
|
52
|
+
const rotrBH = (h, l, s) => (h << (64 - s)) | (l >>> (s - 32));
|
|
53
|
+
_u64.rotrBH = rotrBH;
|
|
54
|
+
const rotrBL = (h, l, s) => (h >>> (s - 32)) | (l << (64 - s));
|
|
55
|
+
_u64.rotrBL = rotrBL;
|
|
56
|
+
// Right rotate for shift===32 (just swaps l&h)
|
|
57
|
+
const rotr32H = (_h, l) => l;
|
|
58
|
+
_u64.rotr32H = rotr32H;
|
|
59
|
+
const rotr32L = (h, _l) => h;
|
|
60
|
+
_u64.rotr32L = rotr32L;
|
|
61
|
+
// Left rotate for Shift in [1, 32)
|
|
62
|
+
const rotlSH = (h, l, s) => (h << s) | (l >>> (32 - s));
|
|
63
|
+
_u64.rotlSH = rotlSH;
|
|
64
|
+
const rotlSL = (h, l, s) => (l << s) | (h >>> (32 - s));
|
|
65
|
+
_u64.rotlSL = rotlSL;
|
|
66
|
+
// Left rotate for Shift in (32, 64), NOTE: 32 is special case.
|
|
67
|
+
const rotlBH = (h, l, s) => (l << (s - 32)) | (h >>> (64 - s));
|
|
68
|
+
_u64.rotlBH = rotlBH;
|
|
69
|
+
const rotlBL = (h, l, s) => (h << (s - 32)) | (l >>> (64 - s));
|
|
70
|
+
_u64.rotlBL = rotlBL;
|
|
71
|
+
// JS uses 32-bit signed integers for bitwise operations which means we cannot
|
|
72
|
+
// simple take carry out of low bit sum by shift, we need to use division.
|
|
73
|
+
function add(Ah, Al, Bh, Bl) {
|
|
74
|
+
const l = (Al >>> 0) + (Bl >>> 0);
|
|
75
|
+
return { h: (Ah + Bh + ((l / 2 ** 32) | 0)) | 0, l: l | 0 };
|
|
76
|
+
}
|
|
77
|
+
// Addition with more than 2 elements
|
|
78
|
+
const add3L = (Al, Bl, Cl) => (Al >>> 0) + (Bl >>> 0) + (Cl >>> 0);
|
|
79
|
+
_u64.add3L = add3L;
|
|
80
|
+
const add3H = (low, Ah, Bh, Ch) => (Ah + Bh + Ch + ((low / 2 ** 32) | 0)) | 0;
|
|
81
|
+
_u64.add3H = add3H;
|
|
82
|
+
const add4L = (Al, Bl, Cl, Dl) => (Al >>> 0) + (Bl >>> 0) + (Cl >>> 0) + (Dl >>> 0);
|
|
83
|
+
_u64.add4L = add4L;
|
|
84
|
+
const add4H = (low, Ah, Bh, Ch, Dh) => (Ah + Bh + Ch + Dh + ((low / 2 ** 32) | 0)) | 0;
|
|
85
|
+
_u64.add4H = add4H;
|
|
86
|
+
const add5L = (Al, Bl, Cl, Dl, El) => (Al >>> 0) + (Bl >>> 0) + (Cl >>> 0) + (Dl >>> 0) + (El >>> 0);
|
|
87
|
+
_u64.add5L = add5L;
|
|
88
|
+
const add5H = (low, Ah, Bh, Ch, Dh, Eh) => (Ah + Bh + Ch + Dh + Eh + ((low / 2 ** 32) | 0)) | 0;
|
|
89
|
+
_u64.add5H = add5H;
|
|
90
|
+
// prettier-ignore
|
|
91
|
+
const u64 = {
|
|
92
|
+
fromBig, split, toBig,
|
|
93
|
+
shrSH, shrSL,
|
|
94
|
+
rotrSH, rotrSL, rotrBH, rotrBL,
|
|
95
|
+
rotr32H, rotr32L,
|
|
96
|
+
rotlSH, rotlSL, rotlBH, rotlBL,
|
|
97
|
+
add, add3L, add3H, add4L, add4H, add5H, add5L,
|
|
98
|
+
};
|
|
99
|
+
_u64.default = u64;
|
|
100
|
+
|
|
101
|
+
var utils = {};
|
|
102
|
+
|
|
103
|
+
var crypto$1 = {};
|
|
104
|
+
|
|
105
|
+
Object.defineProperty(crypto$1, "__esModule", { value: true });
|
|
106
|
+
crypto$1.crypto = void 0;
|
|
107
|
+
crypto$1.crypto = typeof globalThis === 'object' && 'crypto' in globalThis ? globalThis.crypto : undefined;
|
|
108
|
+
|
|
109
|
+
(function (exports) {
|
|
110
|
+
/**
|
|
111
|
+
* Utilities for hex, bytes, CSPRNG.
|
|
112
|
+
* @module
|
|
113
|
+
*/
|
|
114
|
+
/*! noble-hashes - MIT License (c) 2022 Paul Miller (paulmillr.com) */
|
|
115
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
116
|
+
exports.wrapXOFConstructorWithOpts = exports.wrapConstructorWithOpts = exports.wrapConstructor = exports.Hash = exports.nextTick = exports.swap32IfBE = exports.byteSwapIfBE = exports.swap8IfBE = exports.isLE = void 0;
|
|
117
|
+
exports.isBytes = isBytes;
|
|
118
|
+
exports.anumber = anumber;
|
|
119
|
+
exports.abytes = abytes;
|
|
120
|
+
exports.ahash = ahash;
|
|
121
|
+
exports.aexists = aexists;
|
|
122
|
+
exports.aoutput = aoutput;
|
|
123
|
+
exports.u8 = u8;
|
|
124
|
+
exports.u32 = u32;
|
|
125
|
+
exports.clean = clean;
|
|
126
|
+
exports.createView = createView;
|
|
127
|
+
exports.rotr = rotr;
|
|
128
|
+
exports.rotl = rotl;
|
|
129
|
+
exports.byteSwap = byteSwap;
|
|
130
|
+
exports.byteSwap32 = byteSwap32;
|
|
131
|
+
exports.bytesToHex = bytesToHex;
|
|
132
|
+
exports.hexToBytes = hexToBytes;
|
|
133
|
+
exports.asyncLoop = asyncLoop;
|
|
134
|
+
exports.utf8ToBytes = utf8ToBytes;
|
|
135
|
+
exports.bytesToUtf8 = bytesToUtf8;
|
|
136
|
+
exports.toBytes = toBytes;
|
|
137
|
+
exports.kdfInputToBytes = kdfInputToBytes;
|
|
138
|
+
exports.concatBytes = concatBytes;
|
|
139
|
+
exports.checkOpts = checkOpts;
|
|
140
|
+
exports.createHasher = createHasher;
|
|
141
|
+
exports.createOptHasher = createOptHasher;
|
|
142
|
+
exports.createXOFer = createXOFer;
|
|
143
|
+
exports.randomBytes = randomBytes;
|
|
144
|
+
// We use WebCrypto aka globalThis.crypto, which exists in browsers and node.js 16+.
|
|
145
|
+
// node.js versions earlier than v19 don't declare it in global scope.
|
|
146
|
+
// For node.js, package.json#exports field mapping rewrites import
|
|
147
|
+
// from `crypto` to `cryptoNode`, which imports native module.
|
|
148
|
+
// Makes the utils un-importable in browsers without a bundler.
|
|
149
|
+
// Once node.js 18 is deprecated (2025-04-30), we can just drop the import.
|
|
150
|
+
const crypto_1 = crypto$1;
|
|
151
|
+
/** Checks if something is Uint8Array. Be careful: nodejs Buffer will return true. */
|
|
152
|
+
function isBytes(a) {
|
|
153
|
+
return a instanceof Uint8Array || (ArrayBuffer.isView(a) && a.constructor.name === 'Uint8Array');
|
|
154
|
+
}
|
|
155
|
+
/** Asserts something is positive integer. */
|
|
156
|
+
function anumber(n) {
|
|
157
|
+
if (!Number.isSafeInteger(n) || n < 0)
|
|
158
|
+
throw new Error('positive integer expected, got ' + n);
|
|
159
|
+
}
|
|
160
|
+
/** Asserts something is Uint8Array. */
|
|
161
|
+
function abytes(b, ...lengths) {
|
|
162
|
+
if (!isBytes(b))
|
|
163
|
+
throw new Error('Uint8Array expected');
|
|
164
|
+
if (lengths.length > 0 && !lengths.includes(b.length))
|
|
165
|
+
throw new Error('Uint8Array expected of length ' + lengths + ', got length=' + b.length);
|
|
166
|
+
}
|
|
167
|
+
/** Asserts something is hash */
|
|
168
|
+
function ahash(h) {
|
|
169
|
+
if (typeof h !== 'function' || typeof h.create !== 'function')
|
|
170
|
+
throw new Error('Hash should be wrapped by utils.createHasher');
|
|
171
|
+
anumber(h.outputLen);
|
|
172
|
+
anumber(h.blockLen);
|
|
173
|
+
}
|
|
174
|
+
/** Asserts a hash instance has not been destroyed / finished */
|
|
175
|
+
function aexists(instance, checkFinished = true) {
|
|
176
|
+
if (instance.destroyed)
|
|
177
|
+
throw new Error('Hash instance has been destroyed');
|
|
178
|
+
if (checkFinished && instance.finished)
|
|
179
|
+
throw new Error('Hash#digest() has already been called');
|
|
180
|
+
}
|
|
181
|
+
/** Asserts output is properly-sized byte array */
|
|
182
|
+
function aoutput(out, instance) {
|
|
183
|
+
abytes(out);
|
|
184
|
+
const min = instance.outputLen;
|
|
185
|
+
if (out.length < min) {
|
|
186
|
+
throw new Error('digestInto() expects output buffer of length at least ' + min);
|
|
187
|
+
}
|
|
188
|
+
}
|
|
189
|
+
/** Cast u8 / u16 / u32 to u8. */
|
|
190
|
+
function u8(arr) {
|
|
191
|
+
return new Uint8Array(arr.buffer, arr.byteOffset, arr.byteLength);
|
|
192
|
+
}
|
|
193
|
+
/** Cast u8 / u16 / u32 to u32. */
|
|
194
|
+
function u32(arr) {
|
|
195
|
+
return new Uint32Array(arr.buffer, arr.byteOffset, Math.floor(arr.byteLength / 4));
|
|
196
|
+
}
|
|
197
|
+
/** Zeroize a byte array. Warning: JS provides no guarantees. */
|
|
198
|
+
function clean(...arrays) {
|
|
199
|
+
for (let i = 0; i < arrays.length; i++) {
|
|
200
|
+
arrays[i].fill(0);
|
|
201
|
+
}
|
|
202
|
+
}
|
|
203
|
+
/** Create DataView of an array for easy byte-level manipulation. */
|
|
204
|
+
function createView(arr) {
|
|
205
|
+
return new DataView(arr.buffer, arr.byteOffset, arr.byteLength);
|
|
206
|
+
}
|
|
207
|
+
/** The rotate right (circular right shift) operation for uint32 */
|
|
208
|
+
function rotr(word, shift) {
|
|
209
|
+
return (word << (32 - shift)) | (word >>> shift);
|
|
210
|
+
}
|
|
211
|
+
/** The rotate left (circular left shift) operation for uint32 */
|
|
212
|
+
function rotl(word, shift) {
|
|
213
|
+
return (word << shift) | ((word >>> (32 - shift)) >>> 0);
|
|
214
|
+
}
|
|
215
|
+
/** Is current platform little-endian? Most are. Big-Endian platform: IBM */
|
|
216
|
+
exports.isLE = (() => new Uint8Array(new Uint32Array([0x11223344]).buffer)[0] === 0x44)();
|
|
217
|
+
/** The byte swap operation for uint32 */
|
|
218
|
+
function byteSwap(word) {
|
|
219
|
+
return (((word << 24) & 0xff000000) |
|
|
220
|
+
((word << 8) & 0xff0000) |
|
|
221
|
+
((word >>> 8) & 0xff00) |
|
|
222
|
+
((word >>> 24) & 0xff));
|
|
223
|
+
}
|
|
224
|
+
/** Conditionally byte swap if on a big-endian platform */
|
|
225
|
+
exports.swap8IfBE = exports.isLE
|
|
226
|
+
? (n) => n
|
|
227
|
+
: (n) => byteSwap(n);
|
|
228
|
+
/** @deprecated */
|
|
229
|
+
exports.byteSwapIfBE = exports.swap8IfBE;
|
|
230
|
+
/** In place byte swap for Uint32Array */
|
|
231
|
+
function byteSwap32(arr) {
|
|
232
|
+
for (let i = 0; i < arr.length; i++) {
|
|
233
|
+
arr[i] = byteSwap(arr[i]);
|
|
234
|
+
}
|
|
235
|
+
return arr;
|
|
236
|
+
}
|
|
237
|
+
exports.swap32IfBE = exports.isLE
|
|
238
|
+
? (u) => u
|
|
239
|
+
: byteSwap32;
|
|
240
|
+
// Built-in hex conversion https://caniuse.com/mdn-javascript_builtins_uint8array_fromhex
|
|
241
|
+
const hasHexBuiltin = /* @__PURE__ */ (() =>
|
|
242
|
+
// @ts-ignore
|
|
243
|
+
typeof Uint8Array.from([]).toHex === 'function' && typeof Uint8Array.fromHex === 'function')();
|
|
244
|
+
// Array where index 0xf0 (240) is mapped to string 'f0'
|
|
245
|
+
const hexes = /* @__PURE__ */ Array.from({ length: 256 }, (_, i) => i.toString(16).padStart(2, '0'));
|
|
246
|
+
/**
|
|
247
|
+
* Convert byte array to hex string. Uses built-in function, when available.
|
|
248
|
+
* @example bytesToHex(Uint8Array.from([0xca, 0xfe, 0x01, 0x23])) // 'cafe0123'
|
|
249
|
+
*/
|
|
250
|
+
function bytesToHex(bytes) {
|
|
251
|
+
abytes(bytes);
|
|
252
|
+
// @ts-ignore
|
|
253
|
+
if (hasHexBuiltin)
|
|
254
|
+
return bytes.toHex();
|
|
255
|
+
// pre-caching improves the speed 6x
|
|
256
|
+
let hex = '';
|
|
257
|
+
for (let i = 0; i < bytes.length; i++) {
|
|
258
|
+
hex += hexes[bytes[i]];
|
|
259
|
+
}
|
|
260
|
+
return hex;
|
|
261
|
+
}
|
|
262
|
+
// We use optimized technique to convert hex string to byte array
|
|
263
|
+
const asciis = { _0: 48, _9: 57, A: 65, F: 70, a: 97, f: 102 };
|
|
264
|
+
function asciiToBase16(ch) {
|
|
265
|
+
if (ch >= asciis._0 && ch <= asciis._9)
|
|
266
|
+
return ch - asciis._0; // '2' => 50-48
|
|
267
|
+
if (ch >= asciis.A && ch <= asciis.F)
|
|
268
|
+
return ch - (asciis.A - 10); // 'B' => 66-(65-10)
|
|
269
|
+
if (ch >= asciis.a && ch <= asciis.f)
|
|
270
|
+
return ch - (asciis.a - 10); // 'b' => 98-(97-10)
|
|
271
|
+
return;
|
|
272
|
+
}
|
|
273
|
+
/**
|
|
274
|
+
* Convert hex string to byte array. Uses built-in function, when available.
|
|
275
|
+
* @example hexToBytes('cafe0123') // Uint8Array.from([0xca, 0xfe, 0x01, 0x23])
|
|
276
|
+
*/
|
|
277
|
+
function hexToBytes(hex) {
|
|
278
|
+
if (typeof hex !== 'string')
|
|
279
|
+
throw new Error('hex string expected, got ' + typeof hex);
|
|
280
|
+
// @ts-ignore
|
|
281
|
+
if (hasHexBuiltin)
|
|
282
|
+
return Uint8Array.fromHex(hex);
|
|
283
|
+
const hl = hex.length;
|
|
284
|
+
const al = hl / 2;
|
|
285
|
+
if (hl % 2)
|
|
286
|
+
throw new Error('hex string expected, got unpadded hex of length ' + hl);
|
|
287
|
+
const array = new Uint8Array(al);
|
|
288
|
+
for (let ai = 0, hi = 0; ai < al; ai++, hi += 2) {
|
|
289
|
+
const n1 = asciiToBase16(hex.charCodeAt(hi));
|
|
290
|
+
const n2 = asciiToBase16(hex.charCodeAt(hi + 1));
|
|
291
|
+
if (n1 === undefined || n2 === undefined) {
|
|
292
|
+
const char = hex[hi] + hex[hi + 1];
|
|
293
|
+
throw new Error('hex string expected, got non-hex character "' + char + '" at index ' + hi);
|
|
294
|
+
}
|
|
295
|
+
array[ai] = n1 * 16 + n2; // multiply first octet, e.g. 'a3' => 10*16+3 => 160 + 3 => 163
|
|
296
|
+
}
|
|
297
|
+
return array;
|
|
298
|
+
}
|
|
299
|
+
/**
|
|
300
|
+
* There is no setImmediate in browser and setTimeout is slow.
|
|
301
|
+
* Call of async fn will return Promise, which will be fullfiled only on
|
|
302
|
+
* next scheduler queue processing step and this is exactly what we need.
|
|
303
|
+
*/
|
|
304
|
+
const nextTick = async () => { };
|
|
305
|
+
exports.nextTick = nextTick;
|
|
306
|
+
/** Returns control to thread each 'tick' ms to avoid blocking. */
|
|
307
|
+
async function asyncLoop(iters, tick, cb) {
|
|
308
|
+
let ts = Date.now();
|
|
309
|
+
for (let i = 0; i < iters; i++) {
|
|
310
|
+
cb(i);
|
|
311
|
+
// Date.now() is not monotonic, so in case if clock goes backwards we return return control too
|
|
312
|
+
const diff = Date.now() - ts;
|
|
313
|
+
if (diff >= 0 && diff < tick)
|
|
314
|
+
continue;
|
|
315
|
+
await (0, exports.nextTick)();
|
|
316
|
+
ts += diff;
|
|
317
|
+
}
|
|
318
|
+
}
|
|
319
|
+
/**
|
|
320
|
+
* Converts string to bytes using UTF8 encoding.
|
|
321
|
+
* @example utf8ToBytes('abc') // Uint8Array.from([97, 98, 99])
|
|
322
|
+
*/
|
|
323
|
+
function utf8ToBytes(str) {
|
|
324
|
+
if (typeof str !== 'string')
|
|
325
|
+
throw new Error('string expected');
|
|
326
|
+
return new Uint8Array(new TextEncoder().encode(str)); // https://bugzil.la/1681809
|
|
327
|
+
}
|
|
328
|
+
/**
|
|
329
|
+
* Converts bytes to string using UTF8 encoding.
|
|
330
|
+
* @example bytesToUtf8(Uint8Array.from([97, 98, 99])) // 'abc'
|
|
331
|
+
*/
|
|
332
|
+
function bytesToUtf8(bytes) {
|
|
333
|
+
return new TextDecoder().decode(bytes);
|
|
334
|
+
}
|
|
335
|
+
/**
|
|
336
|
+
* Normalizes (non-hex) string or Uint8Array to Uint8Array.
|
|
337
|
+
* Warning: when Uint8Array is passed, it would NOT get copied.
|
|
338
|
+
* Keep in mind for future mutable operations.
|
|
339
|
+
*/
|
|
340
|
+
function toBytes(data) {
|
|
341
|
+
if (typeof data === 'string')
|
|
342
|
+
data = utf8ToBytes(data);
|
|
343
|
+
abytes(data);
|
|
344
|
+
return data;
|
|
345
|
+
}
|
|
346
|
+
/**
|
|
347
|
+
* Helper for KDFs: consumes uint8array or string.
|
|
348
|
+
* When string is passed, does utf8 decoding, using TextDecoder.
|
|
349
|
+
*/
|
|
350
|
+
function kdfInputToBytes(data) {
|
|
351
|
+
if (typeof data === 'string')
|
|
352
|
+
data = utf8ToBytes(data);
|
|
353
|
+
abytes(data);
|
|
354
|
+
return data;
|
|
355
|
+
}
|
|
356
|
+
/** Copies several Uint8Arrays into one. */
|
|
357
|
+
function concatBytes(...arrays) {
|
|
358
|
+
let sum = 0;
|
|
359
|
+
for (let i = 0; i < arrays.length; i++) {
|
|
360
|
+
const a = arrays[i];
|
|
361
|
+
abytes(a);
|
|
362
|
+
sum += a.length;
|
|
363
|
+
}
|
|
364
|
+
const res = new Uint8Array(sum);
|
|
365
|
+
for (let i = 0, pad = 0; i < arrays.length; i++) {
|
|
366
|
+
const a = arrays[i];
|
|
367
|
+
res.set(a, pad);
|
|
368
|
+
pad += a.length;
|
|
369
|
+
}
|
|
370
|
+
return res;
|
|
371
|
+
}
|
|
372
|
+
function checkOpts(defaults, opts) {
|
|
373
|
+
if (opts !== undefined && {}.toString.call(opts) !== '[object Object]')
|
|
374
|
+
throw new Error('options should be object or undefined');
|
|
375
|
+
const merged = Object.assign(defaults, opts);
|
|
376
|
+
return merged;
|
|
377
|
+
}
|
|
378
|
+
/** For runtime check if class implements interface */
|
|
379
|
+
class Hash {
|
|
380
|
+
}
|
|
381
|
+
exports.Hash = Hash;
|
|
382
|
+
/** Wraps hash function, creating an interface on top of it */
|
|
383
|
+
function createHasher(hashCons) {
|
|
384
|
+
const hashC = (msg) => hashCons().update(toBytes(msg)).digest();
|
|
385
|
+
const tmp = hashCons();
|
|
386
|
+
hashC.outputLen = tmp.outputLen;
|
|
387
|
+
hashC.blockLen = tmp.blockLen;
|
|
388
|
+
hashC.create = () => hashCons();
|
|
389
|
+
return hashC;
|
|
390
|
+
}
|
|
391
|
+
function createOptHasher(hashCons) {
|
|
392
|
+
const hashC = (msg, opts) => hashCons(opts).update(toBytes(msg)).digest();
|
|
393
|
+
const tmp = hashCons({});
|
|
394
|
+
hashC.outputLen = tmp.outputLen;
|
|
395
|
+
hashC.blockLen = tmp.blockLen;
|
|
396
|
+
hashC.create = (opts) => hashCons(opts);
|
|
397
|
+
return hashC;
|
|
398
|
+
}
|
|
399
|
+
function createXOFer(hashCons) {
|
|
400
|
+
const hashC = (msg, opts) => hashCons(opts).update(toBytes(msg)).digest();
|
|
401
|
+
const tmp = hashCons({});
|
|
402
|
+
hashC.outputLen = tmp.outputLen;
|
|
403
|
+
hashC.blockLen = tmp.blockLen;
|
|
404
|
+
hashC.create = (opts) => hashCons(opts);
|
|
405
|
+
return hashC;
|
|
406
|
+
}
|
|
407
|
+
exports.wrapConstructor = createHasher;
|
|
408
|
+
exports.wrapConstructorWithOpts = createOptHasher;
|
|
409
|
+
exports.wrapXOFConstructorWithOpts = createXOFer;
|
|
410
|
+
/** Cryptographically secure PRNG. Uses internal OS-level `crypto.getRandomValues`. */
|
|
411
|
+
function randomBytes(bytesLength = 32) {
|
|
412
|
+
if (crypto_1.crypto && typeof crypto_1.crypto.getRandomValues === 'function') {
|
|
413
|
+
return crypto_1.crypto.getRandomValues(new Uint8Array(bytesLength));
|
|
414
|
+
}
|
|
415
|
+
// Legacy Node.js compatibility
|
|
416
|
+
if (crypto_1.crypto && typeof crypto_1.crypto.randomBytes === 'function') {
|
|
417
|
+
return Uint8Array.from(crypto_1.crypto.randomBytes(bytesLength));
|
|
418
|
+
}
|
|
419
|
+
throw new Error('crypto.getRandomValues must be defined');
|
|
420
|
+
}
|
|
421
|
+
|
|
422
|
+
} (utils));
|
|
423
|
+
|
|
424
|
+
Object.defineProperty(sha3$1, "__esModule", { value: true });
|
|
425
|
+
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;
|
|
426
|
+
sha3$1.keccakP = keccakP;
|
|
427
|
+
/**
|
|
428
|
+
* SHA3 (keccak) hash function, based on a new "Sponge function" design.
|
|
429
|
+
* Different from older hashes, the internal state is bigger than output size.
|
|
430
|
+
*
|
|
431
|
+
* Check out [FIPS-202](https://nvlpubs.nist.gov/nistpubs/FIPS/NIST.FIPS.202.pdf),
|
|
432
|
+
* [Website](https://keccak.team/keccak.html),
|
|
433
|
+
* [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).
|
|
434
|
+
*
|
|
435
|
+
* Check out `sha3-addons` module for cSHAKE, k12, and others.
|
|
436
|
+
* @module
|
|
437
|
+
*/
|
|
438
|
+
const _u64_ts_1 = _u64;
|
|
439
|
+
// prettier-ignore
|
|
440
|
+
const utils_ts_1 = utils;
|
|
441
|
+
// No __PURE__ annotations in sha3 header:
|
|
442
|
+
// EVERYTHING is in fact used on every export.
|
|
443
|
+
// Various per round constants calculations
|
|
444
|
+
const _0n = BigInt(0);
|
|
445
|
+
const _1n = BigInt(1);
|
|
446
|
+
const _2n = BigInt(2);
|
|
447
|
+
const _7n = BigInt(7);
|
|
448
|
+
const _256n = BigInt(256);
|
|
449
|
+
const _0x71n = BigInt(0x71);
|
|
450
|
+
const SHA3_PI = [];
|
|
451
|
+
const SHA3_ROTL = [];
|
|
452
|
+
const _SHA3_IOTA = [];
|
|
453
|
+
for (let round = 0, R = _1n, x = 1, y = 0; round < 24; round++) {
|
|
454
|
+
// Pi
|
|
455
|
+
[x, y] = [y, (2 * x + 3 * y) % 5];
|
|
456
|
+
SHA3_PI.push(2 * (5 * y + x));
|
|
457
|
+
// Rotational
|
|
458
|
+
SHA3_ROTL.push((((round + 1) * (round + 2)) / 2) % 64);
|
|
459
|
+
// Iota
|
|
460
|
+
let t = _0n;
|
|
461
|
+
for (let j = 0; j < 7; j++) {
|
|
462
|
+
R = ((R << _1n) ^ ((R >> _7n) * _0x71n)) % _256n;
|
|
463
|
+
if (R & _2n)
|
|
464
|
+
t ^= _1n << ((_1n << /* @__PURE__ */ BigInt(j)) - _1n);
|
|
465
|
+
}
|
|
466
|
+
_SHA3_IOTA.push(t);
|
|
467
|
+
}
|
|
468
|
+
const IOTAS = (0, _u64_ts_1.split)(_SHA3_IOTA, true);
|
|
469
|
+
const SHA3_IOTA_H = IOTAS[0];
|
|
470
|
+
const SHA3_IOTA_L = IOTAS[1];
|
|
471
|
+
// Left rotation (without 0, 32, 64)
|
|
472
|
+
const rotlH = (h, l, s) => (s > 32 ? (0, _u64_ts_1.rotlBH)(h, l, s) : (0, _u64_ts_1.rotlSH)(h, l, s));
|
|
473
|
+
const rotlL = (h, l, s) => (s > 32 ? (0, _u64_ts_1.rotlBL)(h, l, s) : (0, _u64_ts_1.rotlSL)(h, l, s));
|
|
474
|
+
/** `keccakf1600` internal function, additionally allows to adjust round count. */
|
|
475
|
+
function keccakP(s, rounds = 24) {
|
|
476
|
+
const B = new Uint32Array(5 * 2);
|
|
477
|
+
// NOTE: all indices are x2 since we store state as u32 instead of u64 (bigints to slow in js)
|
|
478
|
+
for (let round = 24 - rounds; round < 24; round++) {
|
|
479
|
+
// Theta θ
|
|
480
|
+
for (let x = 0; x < 10; x++)
|
|
481
|
+
B[x] = s[x] ^ s[x + 10] ^ s[x + 20] ^ s[x + 30] ^ s[x + 40];
|
|
482
|
+
for (let x = 0; x < 10; x += 2) {
|
|
483
|
+
const idx1 = (x + 8) % 10;
|
|
484
|
+
const idx0 = (x + 2) % 10;
|
|
485
|
+
const B0 = B[idx0];
|
|
486
|
+
const B1 = B[idx0 + 1];
|
|
487
|
+
const Th = rotlH(B0, B1, 1) ^ B[idx1];
|
|
488
|
+
const Tl = rotlL(B0, B1, 1) ^ B[idx1 + 1];
|
|
489
|
+
for (let y = 0; y < 50; y += 10) {
|
|
490
|
+
s[x + y] ^= Th;
|
|
491
|
+
s[x + y + 1] ^= Tl;
|
|
492
|
+
}
|
|
493
|
+
}
|
|
494
|
+
// Rho (ρ) and Pi (π)
|
|
495
|
+
let curH = s[2];
|
|
496
|
+
let curL = s[3];
|
|
497
|
+
for (let t = 0; t < 24; t++) {
|
|
498
|
+
const shift = SHA3_ROTL[t];
|
|
499
|
+
const Th = rotlH(curH, curL, shift);
|
|
500
|
+
const Tl = rotlL(curH, curL, shift);
|
|
501
|
+
const PI = SHA3_PI[t];
|
|
502
|
+
curH = s[PI];
|
|
503
|
+
curL = s[PI + 1];
|
|
504
|
+
s[PI] = Th;
|
|
505
|
+
s[PI + 1] = Tl;
|
|
506
|
+
}
|
|
507
|
+
// Chi (χ)
|
|
508
|
+
for (let y = 0; y < 50; y += 10) {
|
|
509
|
+
for (let x = 0; x < 10; x++)
|
|
510
|
+
B[x] = s[y + x];
|
|
511
|
+
for (let x = 0; x < 10; x++)
|
|
512
|
+
s[y + x] ^= ~B[(x + 2) % 10] & B[(x + 4) % 10];
|
|
513
|
+
}
|
|
514
|
+
// Iota (ι)
|
|
515
|
+
s[0] ^= SHA3_IOTA_H[round];
|
|
516
|
+
s[1] ^= SHA3_IOTA_L[round];
|
|
517
|
+
}
|
|
518
|
+
(0, utils_ts_1.clean)(B);
|
|
519
|
+
}
|
|
520
|
+
/** Keccak sponge function. */
|
|
521
|
+
class Keccak extends utils_ts_1.Hash {
|
|
522
|
+
// NOTE: we accept arguments in bytes instead of bits here.
|
|
523
|
+
constructor(blockLen, suffix, outputLen, enableXOF = false, rounds = 24) {
|
|
524
|
+
super();
|
|
525
|
+
this.pos = 0;
|
|
526
|
+
this.posOut = 0;
|
|
527
|
+
this.finished = false;
|
|
528
|
+
this.destroyed = false;
|
|
529
|
+
this.enableXOF = false;
|
|
530
|
+
this.blockLen = blockLen;
|
|
531
|
+
this.suffix = suffix;
|
|
532
|
+
this.outputLen = outputLen;
|
|
533
|
+
this.enableXOF = enableXOF;
|
|
534
|
+
this.rounds = rounds;
|
|
535
|
+
// Can be passed from user as dkLen
|
|
536
|
+
(0, utils_ts_1.anumber)(outputLen);
|
|
537
|
+
// 1600 = 5x5 matrix of 64bit. 1600 bits === 200 bytes
|
|
538
|
+
// 0 < blockLen < 200
|
|
539
|
+
if (!(0 < blockLen && blockLen < 200))
|
|
540
|
+
throw new Error('only keccak-f1600 function is supported');
|
|
541
|
+
this.state = new Uint8Array(200);
|
|
542
|
+
this.state32 = (0, utils_ts_1.u32)(this.state);
|
|
543
|
+
}
|
|
544
|
+
clone() {
|
|
545
|
+
return this._cloneInto();
|
|
546
|
+
}
|
|
547
|
+
keccak() {
|
|
548
|
+
(0, utils_ts_1.swap32IfBE)(this.state32);
|
|
549
|
+
keccakP(this.state32, this.rounds);
|
|
550
|
+
(0, utils_ts_1.swap32IfBE)(this.state32);
|
|
551
|
+
this.posOut = 0;
|
|
552
|
+
this.pos = 0;
|
|
553
|
+
}
|
|
554
|
+
update(data) {
|
|
555
|
+
(0, utils_ts_1.aexists)(this);
|
|
556
|
+
data = (0, utils_ts_1.toBytes)(data);
|
|
557
|
+
(0, utils_ts_1.abytes)(data);
|
|
558
|
+
const { blockLen, state } = this;
|
|
559
|
+
const len = data.length;
|
|
560
|
+
for (let pos = 0; pos < len;) {
|
|
561
|
+
const take = Math.min(blockLen - this.pos, len - pos);
|
|
562
|
+
for (let i = 0; i < take; i++)
|
|
563
|
+
state[this.pos++] ^= data[pos++];
|
|
564
|
+
if (this.pos === blockLen)
|
|
565
|
+
this.keccak();
|
|
566
|
+
}
|
|
567
|
+
return this;
|
|
568
|
+
}
|
|
569
|
+
finish() {
|
|
570
|
+
if (this.finished)
|
|
571
|
+
return;
|
|
572
|
+
this.finished = true;
|
|
573
|
+
const { state, suffix, pos, blockLen } = this;
|
|
574
|
+
// Do the padding
|
|
575
|
+
state[pos] ^= suffix;
|
|
576
|
+
if ((suffix & 0x80) !== 0 && pos === blockLen - 1)
|
|
577
|
+
this.keccak();
|
|
578
|
+
state[blockLen - 1] ^= 0x80;
|
|
579
|
+
this.keccak();
|
|
580
|
+
}
|
|
581
|
+
writeInto(out) {
|
|
582
|
+
(0, utils_ts_1.aexists)(this, false);
|
|
583
|
+
(0, utils_ts_1.abytes)(out);
|
|
584
|
+
this.finish();
|
|
585
|
+
const bufferOut = this.state;
|
|
586
|
+
const { blockLen } = this;
|
|
587
|
+
for (let pos = 0, len = out.length; pos < len;) {
|
|
588
|
+
if (this.posOut >= blockLen)
|
|
589
|
+
this.keccak();
|
|
590
|
+
const take = Math.min(blockLen - this.posOut, len - pos);
|
|
591
|
+
out.set(bufferOut.subarray(this.posOut, this.posOut + take), pos);
|
|
592
|
+
this.posOut += take;
|
|
593
|
+
pos += take;
|
|
594
|
+
}
|
|
595
|
+
return out;
|
|
596
|
+
}
|
|
597
|
+
xofInto(out) {
|
|
598
|
+
// Sha3/Keccak usage with XOF is probably mistake, only SHAKE instances can do XOF
|
|
599
|
+
if (!this.enableXOF)
|
|
600
|
+
throw new Error('XOF is not possible for this instance');
|
|
601
|
+
return this.writeInto(out);
|
|
602
|
+
}
|
|
603
|
+
xof(bytes) {
|
|
604
|
+
(0, utils_ts_1.anumber)(bytes);
|
|
605
|
+
return this.xofInto(new Uint8Array(bytes));
|
|
606
|
+
}
|
|
607
|
+
digestInto(out) {
|
|
608
|
+
(0, utils_ts_1.aoutput)(out, this);
|
|
609
|
+
if (this.finished)
|
|
610
|
+
throw new Error('digest() was already called');
|
|
611
|
+
this.writeInto(out);
|
|
612
|
+
this.destroy();
|
|
613
|
+
return out;
|
|
614
|
+
}
|
|
615
|
+
digest() {
|
|
616
|
+
return this.digestInto(new Uint8Array(this.outputLen));
|
|
617
|
+
}
|
|
618
|
+
destroy() {
|
|
619
|
+
this.destroyed = true;
|
|
620
|
+
(0, utils_ts_1.clean)(this.state);
|
|
621
|
+
}
|
|
622
|
+
_cloneInto(to) {
|
|
623
|
+
const { blockLen, suffix, outputLen, rounds, enableXOF } = this;
|
|
624
|
+
to || (to = new Keccak(blockLen, suffix, outputLen, enableXOF, rounds));
|
|
625
|
+
to.state32.set(this.state32);
|
|
626
|
+
to.pos = this.pos;
|
|
627
|
+
to.posOut = this.posOut;
|
|
628
|
+
to.finished = this.finished;
|
|
629
|
+
to.rounds = rounds;
|
|
630
|
+
// Suffix can change in cSHAKE
|
|
631
|
+
to.suffix = suffix;
|
|
632
|
+
to.outputLen = outputLen;
|
|
633
|
+
to.enableXOF = enableXOF;
|
|
634
|
+
to.destroyed = this.destroyed;
|
|
635
|
+
return to;
|
|
636
|
+
}
|
|
637
|
+
}
|
|
638
|
+
sha3$1.Keccak = Keccak;
|
|
639
|
+
const gen = (suffix, blockLen, outputLen) => (0, utils_ts_1.createHasher)(() => new Keccak(blockLen, suffix, outputLen));
|
|
640
|
+
/** SHA3-224 hash function. */
|
|
641
|
+
sha3$1.sha3_224 = (() => gen(0x06, 144, 224 / 8))();
|
|
642
|
+
/** SHA3-256 hash function. Different from keccak-256. */
|
|
643
|
+
sha3$1.sha3_256 = (() => gen(0x06, 136, 256 / 8))();
|
|
644
|
+
/** SHA3-384 hash function. */
|
|
645
|
+
sha3$1.sha3_384 = (() => gen(0x06, 104, 384 / 8))();
|
|
646
|
+
/** SHA3-512 hash function. */
|
|
647
|
+
sha3$1.sha3_512 = (() => gen(0x06, 72, 512 / 8))();
|
|
648
|
+
/** keccak-224 hash function. */
|
|
649
|
+
sha3$1.keccak_224 = (() => gen(0x01, 144, 224 / 8))();
|
|
650
|
+
/** keccak-256 hash function. Different from SHA3-256. */
|
|
651
|
+
sha3$1.keccak_256 = (() => gen(0x01, 136, 256 / 8))();
|
|
652
|
+
/** keccak-384 hash function. */
|
|
653
|
+
sha3$1.keccak_384 = (() => gen(0x01, 104, 384 / 8))();
|
|
654
|
+
/** keccak-512 hash function. */
|
|
655
|
+
sha3$1.keccak_512 = (() => gen(0x01, 72, 512 / 8))();
|
|
656
|
+
const genShake = (suffix, blockLen, outputLen) => (0, utils_ts_1.createXOFer)((opts = {}) => new Keccak(blockLen, suffix, opts.dkLen === undefined ? outputLen : opts.dkLen, true));
|
|
657
|
+
/** SHAKE128 XOF with 128-bit security. */
|
|
658
|
+
sha3$1.shake128 = (() => genShake(0x1f, 168, 128 / 8))();
|
|
659
|
+
/** SHAKE256 XOF with 256-bit security. */
|
|
660
|
+
sha3$1.shake256 = (() => genShake(0x1f, 136, 256 / 8))();
|
|
661
|
+
|
|
662
|
+
/* global global, window, module */
|
|
663
|
+
|
|
664
|
+
const { sha3_512: sha3 } = sha3$1;
|
|
665
|
+
|
|
666
|
+
const defaultLength = 24;
|
|
667
|
+
const bigLength = 32;
|
|
668
|
+
|
|
669
|
+
const createEntropy = (length = 4, random = Math.random) => {
|
|
670
|
+
let entropy = "";
|
|
671
|
+
|
|
672
|
+
while (entropy.length < length) {
|
|
673
|
+
entropy = entropy + Math.floor(random() * 36).toString(36);
|
|
674
|
+
}
|
|
675
|
+
return entropy;
|
|
676
|
+
};
|
|
677
|
+
|
|
678
|
+
/*
|
|
679
|
+
* Adapted from https://github.com/juanelas/bigint-conversion
|
|
680
|
+
* MIT License Copyright (c) 2018 Juan Hernández Serrano
|
|
681
|
+
*/
|
|
682
|
+
function bufToBigInt(buf) {
|
|
683
|
+
let bits = 8n;
|
|
684
|
+
|
|
685
|
+
let value = 0n;
|
|
686
|
+
for (const i of buf.values()) {
|
|
687
|
+
const bi = BigInt(i);
|
|
688
|
+
value = (value << bits) + bi;
|
|
689
|
+
}
|
|
690
|
+
return value;
|
|
691
|
+
}
|
|
692
|
+
|
|
693
|
+
const hash = (input = "") => {
|
|
694
|
+
// Drop the first character because it will bias the histogram
|
|
695
|
+
// to the left.
|
|
696
|
+
return bufToBigInt(sha3(input)).toString(36).slice(1);
|
|
697
|
+
};
|
|
698
|
+
|
|
699
|
+
const alphabet = Array.from({ length: 26 }, (x, i) =>
|
|
700
|
+
String.fromCharCode(i + 97)
|
|
701
|
+
);
|
|
702
|
+
|
|
703
|
+
const randomLetter = (random) =>
|
|
704
|
+
alphabet[Math.floor(random() * alphabet.length)];
|
|
705
|
+
|
|
706
|
+
/*
|
|
707
|
+
This is a fingerprint of the host environment. It is used to help
|
|
708
|
+
prevent collisions when generating ids in a distributed system.
|
|
709
|
+
If no global object is available, you can pass in your own, or fall back
|
|
710
|
+
on a random string.
|
|
711
|
+
*/
|
|
712
|
+
const createFingerprint = ({
|
|
713
|
+
globalObj = typeof commonjsGlobal !== "undefined"
|
|
714
|
+
? commonjsGlobal
|
|
715
|
+
: typeof window !== "undefined"
|
|
716
|
+
? window
|
|
717
|
+
: {},
|
|
718
|
+
random = Math.random,
|
|
719
|
+
} = {}) => {
|
|
720
|
+
const globals = Object.keys(globalObj).toString();
|
|
721
|
+
const sourceString = globals.length
|
|
722
|
+
? globals + createEntropy(bigLength, random)
|
|
723
|
+
: createEntropy(bigLength, random);
|
|
724
|
+
|
|
725
|
+
return hash(sourceString).substring(0, bigLength);
|
|
726
|
+
};
|
|
727
|
+
|
|
728
|
+
const createCounter = (count) => () => {
|
|
729
|
+
return count++;
|
|
730
|
+
};
|
|
731
|
+
|
|
732
|
+
// ~22k hosts before 50% chance of initial counter collision
|
|
733
|
+
// with a remaining counter range of 9.0e+15 in JavaScript.
|
|
734
|
+
const initialCountMax = 476782367;
|
|
735
|
+
|
|
736
|
+
const init = ({
|
|
737
|
+
// Fallback if the user does not pass in a CSPRNG. This should be OK
|
|
738
|
+
// because we don't rely solely on the random number generator for entropy.
|
|
739
|
+
// We also use the host fingerprint, current time, and a session counter.
|
|
740
|
+
random = Math.random,
|
|
741
|
+
counter = createCounter(Math.floor(random() * initialCountMax)),
|
|
742
|
+
length = defaultLength,
|
|
743
|
+
fingerprint = createFingerprint({ random }),
|
|
744
|
+
} = {}) => {
|
|
745
|
+
return function cuid2() {
|
|
746
|
+
const firstLetter = randomLetter(random);
|
|
747
|
+
|
|
748
|
+
// If we're lucky, the `.toString(36)` calls may reduce hashing rounds
|
|
749
|
+
// by shortening the input to the hash function a little.
|
|
750
|
+
const time = Date.now().toString(36);
|
|
751
|
+
const count = counter().toString(36);
|
|
752
|
+
|
|
753
|
+
// The salt should be long enough to be globally unique across the full
|
|
754
|
+
// length of the hash. For simplicity, we use the same length as the
|
|
755
|
+
// intended id output.
|
|
756
|
+
const salt = createEntropy(length, random);
|
|
757
|
+
const hashInput = `${time + salt + count + fingerprint}`;
|
|
758
|
+
|
|
759
|
+
return `${firstLetter + hash(hashInput).substring(1, length)}`;
|
|
760
|
+
};
|
|
761
|
+
};
|
|
762
|
+
|
|
763
|
+
const createId$1 = init();
|
|
764
|
+
|
|
765
|
+
const isCuid = (id, { minLength = 2, maxLength = bigLength } = {}) => {
|
|
766
|
+
const length = id.length;
|
|
767
|
+
const regex = /^[0-9a-z]+$/;
|
|
768
|
+
|
|
769
|
+
try {
|
|
770
|
+
if (
|
|
771
|
+
typeof id === "string" &&
|
|
772
|
+
length >= minLength &&
|
|
773
|
+
length <= maxLength &&
|
|
774
|
+
regex.test(id)
|
|
775
|
+
)
|
|
776
|
+
return true;
|
|
777
|
+
} finally {
|
|
778
|
+
}
|
|
779
|
+
|
|
780
|
+
return false;
|
|
781
|
+
};
|
|
782
|
+
|
|
783
|
+
src.getConstants = () => ({ defaultLength, bigLength });
|
|
784
|
+
src.init = init;
|
|
785
|
+
src.createId = createId$1;
|
|
786
|
+
src.bufToBigInt = bufToBigInt;
|
|
787
|
+
src.createCounter = createCounter;
|
|
788
|
+
src.createFingerprint = createFingerprint;
|
|
789
|
+
src.isCuid = isCuid;
|
|
790
|
+
|
|
791
|
+
const { createId} = src;
|
|
792
|
+
|
|
793
|
+
var createId_1 = createId;
|
|
794
|
+
|
|
795
|
+
const errorCatalog = Object.freeze({
|
|
796
|
+
CONFIGURATION: "Invalid transport configuration",
|
|
797
|
+
CLOSED: "Client is closed",
|
|
798
|
+
VALIDATION: "Message validation failed",
|
|
799
|
+
SERIALIZATION: "Message serialization failed",
|
|
800
|
+
REQUEST_TOO_LARGE: "Request exceeds the size limit",
|
|
801
|
+
DNS: "DNS resolution failed",
|
|
802
|
+
CONNECT: "Connection failed",
|
|
803
|
+
PROXY: "Proxy connection failed",
|
|
804
|
+
TLS: "TLS negotiation failed",
|
|
805
|
+
IO: "Transport I/O failed",
|
|
806
|
+
ATTEMPT_TIMEOUT: "Transport attempt timed out",
|
|
807
|
+
OPERATION_DEADLINE: "Operation deadline exceeded",
|
|
808
|
+
CANCELLED: "Operation cancelled",
|
|
809
|
+
OVERLOADED: "Transport is at capacity",
|
|
810
|
+
RATE_LIMITED: "Request was rate limited",
|
|
811
|
+
HTTP_REJECTED: "Request was rejected",
|
|
812
|
+
SERVER_FAILURE: "Server failed to process the request",
|
|
813
|
+
RESPONSE_TOO_LARGE: "Response exceeds the size limit",
|
|
814
|
+
RESPONSE_PROTOCOL: "Response protocol is invalid",
|
|
815
|
+
DESCRIPTOR_VERSION: "Descriptor version is not supported",
|
|
816
|
+
});
|
|
817
|
+
const REMEDIATION_ERROR_CODES = new Set([
|
|
818
|
+
"DNS",
|
|
819
|
+
"CONNECT",
|
|
820
|
+
"PROXY",
|
|
821
|
+
"TLS",
|
|
822
|
+
"IO",
|
|
823
|
+
"ATTEMPT_TIMEOUT",
|
|
824
|
+
]);
|
|
825
|
+
class RepostError extends Error {
|
|
826
|
+
constructor(details) {
|
|
827
|
+
super(errorCatalog[details.errorCode]);
|
|
828
|
+
this.name = new.target.name;
|
|
829
|
+
this.errorCode = details.errorCode;
|
|
830
|
+
this.deliveryState = details.deliveryState;
|
|
831
|
+
this.retryable = details.retryable ?? false;
|
|
832
|
+
this.operationId = details.operationId ?? null;
|
|
833
|
+
this.idempotencyKey = details.idempotencyKey ?? null;
|
|
834
|
+
this.attemptCount = details.attemptCount ?? 0;
|
|
835
|
+
this.httpStatus = details.httpStatus ?? null;
|
|
836
|
+
this.failureReason = details.failureReason ?? null;
|
|
837
|
+
this.causeCategory = details.causeCategory ?? null;
|
|
838
|
+
this.compressedBytes = details.compressedBytes ?? 0;
|
|
839
|
+
this.decompressedBytes = details.decompressedBytes ?? 0;
|
|
840
|
+
this.responseHeaderFields = details.responseHeaderFields ?? 0;
|
|
841
|
+
this.responseHeaderBytes = details.responseHeaderBytes ?? 0;
|
|
842
|
+
this.truncated = details.truncated ?? false;
|
|
843
|
+
this.validationIssues = Object.freeze([...(details.validationIssues ?? [])]);
|
|
844
|
+
this.configurationIssues = Object.freeze([...(details.configurationIssues ?? [])]);
|
|
845
|
+
this.closeFailureCount = details.closeFailureCount ?? 0;
|
|
846
|
+
this.closeFailureCategories = Object.freeze([...(details.closeFailureCategories ?? [])]);
|
|
847
|
+
this.issueCount = details.issueCount ?? this.validationIssues.length + this.configurationIssues.length;
|
|
848
|
+
this.issuesTruncated = details.issuesTruncated ?? false;
|
|
849
|
+
this.remediationKey = details.remediationKey ?? remediationKey(details.errorCode, this.failureReason);
|
|
850
|
+
}
|
|
851
|
+
isRetryable() { return this.retryable; }
|
|
852
|
+
}
|
|
853
|
+
function remediationKey(code, reason) {
|
|
854
|
+
if (!REMEDIATION_ERROR_CODES.has(code))
|
|
855
|
+
return null;
|
|
856
|
+
if (reason === "CONNECTION_RESET")
|
|
857
|
+
return "network.connection.reset";
|
|
858
|
+
if (reason === "TLS_UNTRUSTED")
|
|
859
|
+
return "network.tls.untrusted";
|
|
860
|
+
if (reason === "TLS_HOSTNAME_MISMATCH")
|
|
861
|
+
return "network.tls.hostname-mismatch";
|
|
862
|
+
if (reason === "TLS_NEGOTIATION")
|
|
863
|
+
return "network.tls.negotiation";
|
|
864
|
+
if (reason === "PROXY_AUTH_REQUIRED")
|
|
865
|
+
return "network.proxy.auth-required";
|
|
866
|
+
return reason === "UNKNOWN" ? "network.unknown" : null;
|
|
867
|
+
}
|
|
868
|
+
class RepostConfigurationError extends RepostError {
|
|
869
|
+
}
|
|
870
|
+
class RepostValidationError extends RepostError {
|
|
871
|
+
}
|
|
872
|
+
class RepostSerializationError extends RepostError {
|
|
873
|
+
}
|
|
874
|
+
class RepostTransportError extends RepostError {
|
|
875
|
+
}
|
|
876
|
+
class RepostPublishError extends RepostError {
|
|
877
|
+
constructor(detailsOrMessage, status, body) {
|
|
878
|
+
const details = typeof detailsOrMessage === "string"
|
|
879
|
+
? legacyPublishDetails(status, body)
|
|
880
|
+
: detailsOrMessage;
|
|
881
|
+
super(details);
|
|
882
|
+
this.status = this.httpStatus ?? undefined;
|
|
883
|
+
this.body = details.body;
|
|
884
|
+
}
|
|
885
|
+
}
|
|
886
|
+
class RepostDescriptorVersionError extends RepostError {
|
|
887
|
+
}
|
|
888
|
+
function legacyPublishDetails(status, body) {
|
|
889
|
+
let errorCode = "HTTP_REJECTED";
|
|
890
|
+
if (status === undefined)
|
|
891
|
+
errorCode = "IO";
|
|
892
|
+
else if (status === 429)
|
|
893
|
+
errorCode = "RATE_LIMITED";
|
|
894
|
+
else if (status >= 500)
|
|
895
|
+
errorCode = "SERVER_FAILURE";
|
|
896
|
+
let deliveryState = "POSSIBLY_SENT";
|
|
897
|
+
if (status === undefined)
|
|
898
|
+
deliveryState = "NOT_SENT";
|
|
899
|
+
else if (status >= 400 && status < 500 && status !== 409 && status !== 429)
|
|
900
|
+
deliveryState = "REJECTED";
|
|
901
|
+
return {
|
|
902
|
+
errorCode,
|
|
903
|
+
deliveryState,
|
|
904
|
+
retryable: status === undefined || status === 409 || status === 429 || status >= 500,
|
|
905
|
+
httpStatus: status,
|
|
906
|
+
body,
|
|
907
|
+
};
|
|
908
|
+
}
|
|
909
|
+
|
|
910
|
+
const encoder$4 = new TextEncoder();
|
|
911
|
+
const MAX_ISSUES = 32;
|
|
912
|
+
const MAX_ISSUE_COUNT = 2147483647;
|
|
913
|
+
const MAX_ISSUE_PATH_BYTES = 1024;
|
|
914
|
+
const MAX_TOTAL_ISSUE_PATH_BYTES = 16384;
|
|
915
|
+
const TRUNCATION_MARKER = ".<truncated>";
|
|
916
|
+
/** Fill the runtime's injectable clock and ID generators with real defaults. */
|
|
917
|
+
function resolveGenerators(generators) {
|
|
918
|
+
return {
|
|
919
|
+
now: generators?.now ?? (() => new Date().toISOString()),
|
|
920
|
+
uuid: generators?.uuid ?? (() => crypto.randomUUID()),
|
|
921
|
+
cuid: generators?.cuid ?? (() => createId_1()),
|
|
922
|
+
};
|
|
923
|
+
}
|
|
924
|
+
/**
|
|
925
|
+
* Serialize a send input into its wire payload, driven by the generated model
|
|
926
|
+
* descriptors: fields are emitted in declaration order under their `@map`'d
|
|
927
|
+
* wire names, absent fields with an `@default` are injected (literals
|
|
928
|
+
* verbatim, `now()`/`uuid()`/`cuid()` generated at send time), absent optional
|
|
929
|
+
* fields are omitted, nested models recurse, and enum members serialize to
|
|
930
|
+
* their (possibly `@map`'d) wire values. `generators` overrides the clock and
|
|
931
|
+
* id sources for deterministic tests (the conformance suite's seam).
|
|
932
|
+
*/
|
|
933
|
+
function serializeModel(models, modelName, data, generators, enums = {}) {
|
|
934
|
+
validateModelDescriptors(models, enums);
|
|
935
|
+
const collector = new ValidationCollector();
|
|
936
|
+
let payload = {};
|
|
937
|
+
try {
|
|
938
|
+
payload = serializeModelAt(models, modelName, data, generators, enums, "$", collector);
|
|
939
|
+
}
|
|
940
|
+
catch (error) {
|
|
941
|
+
if (!(error instanceof ValidationFault))
|
|
942
|
+
throw error;
|
|
943
|
+
collector.add(error);
|
|
944
|
+
}
|
|
945
|
+
collector.throwIfAny();
|
|
946
|
+
return payload;
|
|
947
|
+
}
|
|
948
|
+
function serializeModelAt(models, modelName, data, generators, enums, path, collector) {
|
|
949
|
+
const descriptor = models[modelName];
|
|
950
|
+
if (!descriptor) {
|
|
951
|
+
throw new Error(`@repost/client: no serialization descriptor for model \`${modelName}\`.`);
|
|
952
|
+
}
|
|
953
|
+
if (typeof data !== "object" || data === null || Array.isArray(data)) {
|
|
954
|
+
if (typeof data === "bigint" || typeof data === "symbol" || typeof data === "function") {
|
|
955
|
+
validationError("INVALID_JSON", path, "value is not representable as JSON");
|
|
956
|
+
}
|
|
957
|
+
let got = typeof data;
|
|
958
|
+
if (data === null)
|
|
959
|
+
got = "null";
|
|
960
|
+
else if (Array.isArray(data))
|
|
961
|
+
got = "an array";
|
|
962
|
+
throw new Error(`@repost/client: expected an object for model \`${modelName}\`, got ${got}.`);
|
|
963
|
+
}
|
|
964
|
+
const input = data;
|
|
965
|
+
const payload = {};
|
|
966
|
+
for (const field of descriptor.fields) {
|
|
967
|
+
try {
|
|
968
|
+
const schemaName = "schemaName" in field ? field.schemaName : field.name;
|
|
969
|
+
const fieldPath = appendPath(path, schemaName);
|
|
970
|
+
let value = input[schemaName];
|
|
971
|
+
if (value === undefined) {
|
|
972
|
+
if (field.default) {
|
|
973
|
+
value = resolveDefault(field.default, generators);
|
|
974
|
+
}
|
|
975
|
+
else if ("requiredInInput" in field && field.requiredInInput) {
|
|
976
|
+
validationError("REQUIRED", fieldPath, "required field is absent");
|
|
977
|
+
}
|
|
978
|
+
else {
|
|
979
|
+
continue;
|
|
980
|
+
}
|
|
981
|
+
}
|
|
982
|
+
if (value === null && "nullableInInput" in field && !field.nullableInInput) {
|
|
983
|
+
validationError("NULL_NOT_ALLOWED", fieldPath, "null is not allowed");
|
|
984
|
+
}
|
|
985
|
+
const wireName = "wireName" in field ? field.wireName : field.wire ?? field.name;
|
|
986
|
+
payload[wireName] = serializeValue(models, field, value, generators, enums, fieldPath, collector);
|
|
987
|
+
}
|
|
988
|
+
catch (error) {
|
|
989
|
+
if (!(error instanceof ValidationFault))
|
|
990
|
+
throw error;
|
|
991
|
+
collector.add(error);
|
|
992
|
+
}
|
|
993
|
+
}
|
|
994
|
+
return payload;
|
|
995
|
+
}
|
|
996
|
+
function serializeValue(models, field, value, generators, enums, path, collector) {
|
|
997
|
+
if (value === null)
|
|
998
|
+
return null;
|
|
999
|
+
if (field.list) {
|
|
1000
|
+
if (Array.isArray(value)) {
|
|
1001
|
+
return value.map((item, index) => {
|
|
1002
|
+
const itemPath = `${path}[${index}]`;
|
|
1003
|
+
try {
|
|
1004
|
+
if (item === undefined)
|
|
1005
|
+
validationError("REQUIRED", itemPath, "required list element is absent");
|
|
1006
|
+
if (item === null && "scalarKind" in field) {
|
|
1007
|
+
validationError("NULL_NOT_ALLOWED", itemPath, "null list elements are not allowed");
|
|
1008
|
+
}
|
|
1009
|
+
return serializeItem(models, field, item, generators, enums, itemPath, collector);
|
|
1010
|
+
}
|
|
1011
|
+
catch (error) {
|
|
1012
|
+
if (!(error instanceof ValidationFault))
|
|
1013
|
+
throw error;
|
|
1014
|
+
collector.add(error);
|
|
1015
|
+
return undefined;
|
|
1016
|
+
}
|
|
1017
|
+
});
|
|
1018
|
+
}
|
|
1019
|
+
if ("scalarKind" in field) {
|
|
1020
|
+
validationError("TYPE_MISMATCH", path, "expected a list");
|
|
1021
|
+
}
|
|
1022
|
+
}
|
|
1023
|
+
return serializeItem(models, field, value, generators, enums, path, collector);
|
|
1024
|
+
}
|
|
1025
|
+
function serializeItem(models, field, value, generators, enums, path, collector) {
|
|
1026
|
+
let model;
|
|
1027
|
+
if ("scalarKind" in field && field.scalarKind === "model")
|
|
1028
|
+
model = field.descriptorId;
|
|
1029
|
+
else if ("model" in field)
|
|
1030
|
+
model = field.model;
|
|
1031
|
+
if (model) {
|
|
1032
|
+
return serializeModelAt(models, model, value, generators, enums, path, collector);
|
|
1033
|
+
}
|
|
1034
|
+
let enumValues;
|
|
1035
|
+
if ("scalarKind" in field && field.scalarKind === "enum") {
|
|
1036
|
+
enumValues = enums[field.descriptorId ?? ""];
|
|
1037
|
+
}
|
|
1038
|
+
else if ("enum" in field) {
|
|
1039
|
+
enumValues = field.enum;
|
|
1040
|
+
}
|
|
1041
|
+
if (enumValues) {
|
|
1042
|
+
if (typeof value !== "string")
|
|
1043
|
+
validationError("TYPE_MISMATCH", path, "expected an enum member");
|
|
1044
|
+
const wire = enumValues[value];
|
|
1045
|
+
if (wire === undefined) {
|
|
1046
|
+
if (!("scalarKind" in field))
|
|
1047
|
+
return value;
|
|
1048
|
+
validationError("INVALID_ENUM", path, "unknown enum member");
|
|
1049
|
+
}
|
|
1050
|
+
return wire;
|
|
1051
|
+
}
|
|
1052
|
+
if ("scalarKind" in field) {
|
|
1053
|
+
return validateScalar(field.scalarKind, value, path);
|
|
1054
|
+
}
|
|
1055
|
+
return value;
|
|
1056
|
+
}
|
|
1057
|
+
function validateScalar(kind, value, path) {
|
|
1058
|
+
switch (kind) {
|
|
1059
|
+
case "string":
|
|
1060
|
+
if (typeof value !== "string")
|
|
1061
|
+
validationError("TYPE_MISMATCH", path, "expected a string");
|
|
1062
|
+
if (hasUnpairedSurrogate(value))
|
|
1063
|
+
validationError("INVALID_UNICODE", path, "unpaired UTF-16 surrogates are not allowed");
|
|
1064
|
+
return value;
|
|
1065
|
+
case "boolean":
|
|
1066
|
+
if (typeof value !== "boolean")
|
|
1067
|
+
validationError("TYPE_MISMATCH", path, "expected a boolean");
|
|
1068
|
+
return value;
|
|
1069
|
+
case "int64":
|
|
1070
|
+
if (typeof value !== "number")
|
|
1071
|
+
validationError("TYPE_MISMATCH", path, "expected an integer");
|
|
1072
|
+
if (!Number.isFinite(value))
|
|
1073
|
+
validationError("NON_FINITE_NUMBER", path, "non-finite numbers are not allowed");
|
|
1074
|
+
if (!Number.isSafeInteger(value))
|
|
1075
|
+
validationError("OUT_OF_RANGE", path, "integer is outside the safe range");
|
|
1076
|
+
return value;
|
|
1077
|
+
case "float64":
|
|
1078
|
+
if (typeof value !== "number")
|
|
1079
|
+
validationError("TYPE_MISMATCH", path, "expected a number");
|
|
1080
|
+
if (!Number.isFinite(value))
|
|
1081
|
+
validationError("NON_FINITE_NUMBER", path, "non-finite numbers are not allowed");
|
|
1082
|
+
return value;
|
|
1083
|
+
case "datetime":
|
|
1084
|
+
if (typeof value !== "string")
|
|
1085
|
+
validationError("TYPE_MISMATCH", path, "expected a datetime string");
|
|
1086
|
+
if (!/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}\.\d{3}Z$/u.test(value)
|
|
1087
|
+
|| Number.isNaN(Date.parse(value))
|
|
1088
|
+
|| new Date(value).toISOString() !== value) {
|
|
1089
|
+
validationError("INVALID_DATETIME", path, "expected an ISO-8601 UTC datetime");
|
|
1090
|
+
}
|
|
1091
|
+
return value;
|
|
1092
|
+
case "json":
|
|
1093
|
+
return canonicalJson(value, path, new Set());
|
|
1094
|
+
default:
|
|
1095
|
+
return value;
|
|
1096
|
+
}
|
|
1097
|
+
}
|
|
1098
|
+
function canonicalJson(value, path, activeAncestors) {
|
|
1099
|
+
if (typeof value === "number" && !Number.isFinite(value)) {
|
|
1100
|
+
validationError("NON_FINITE_NUMBER", path, "non-finite numbers are not allowed");
|
|
1101
|
+
}
|
|
1102
|
+
if (typeof value === "string") {
|
|
1103
|
+
if (hasUnpairedSurrogate(value))
|
|
1104
|
+
validationError("INVALID_UNICODE", path, "unpaired UTF-16 surrogates are not allowed");
|
|
1105
|
+
return value;
|
|
1106
|
+
}
|
|
1107
|
+
if (value === null || typeof value === "boolean" || typeof value === "number")
|
|
1108
|
+
return value;
|
|
1109
|
+
if (typeof value !== "object")
|
|
1110
|
+
validationError("INVALID_JSON", path, "value is not representable as JSON");
|
|
1111
|
+
if (activeAncestors.has(value)) {
|
|
1112
|
+
validationError("INVALID_JSON", path, "cyclic JSON values are not allowed");
|
|
1113
|
+
}
|
|
1114
|
+
if (value instanceof Map) {
|
|
1115
|
+
activeAncestors.add(value);
|
|
1116
|
+
try {
|
|
1117
|
+
const entries = [...value.entries()];
|
|
1118
|
+
for (const [key] of entries) {
|
|
1119
|
+
if (typeof key !== "string")
|
|
1120
|
+
validationError("INVALID_JSON", `${path}[{*}]`, "map keys must be strings");
|
|
1121
|
+
if (hasUnpairedSurrogate(key))
|
|
1122
|
+
validationError("INVALID_UNICODE", `${path}[{*}]`, "map key contains an unpaired UTF-16 surrogate");
|
|
1123
|
+
}
|
|
1124
|
+
const result = {};
|
|
1125
|
+
for (const [key, entry] of entries.sort(([left], [right]) => compareUtf8Bytes(left, right))) {
|
|
1126
|
+
result[key] = canonicalJson(entry, `${path}[{*}]`, activeAncestors);
|
|
1127
|
+
}
|
|
1128
|
+
return result;
|
|
1129
|
+
}
|
|
1130
|
+
finally {
|
|
1131
|
+
activeAncestors.delete(value);
|
|
1132
|
+
}
|
|
1133
|
+
}
|
|
1134
|
+
activeAncestors.add(value);
|
|
1135
|
+
try {
|
|
1136
|
+
if (Array.isArray(value)) {
|
|
1137
|
+
return value.map((item, index) => canonicalJson(item, `${path}[${index}]`, activeAncestors));
|
|
1138
|
+
}
|
|
1139
|
+
const record = value;
|
|
1140
|
+
const result = {};
|
|
1141
|
+
const keys = Object.keys(record);
|
|
1142
|
+
if (keys.some(hasUnpairedSurrogate))
|
|
1143
|
+
validationError("INVALID_UNICODE", `${path}[{*}]`, "map key contains an unpaired UTF-16 surrogate");
|
|
1144
|
+
for (const key of keys.sort(compareUtf8Bytes)) {
|
|
1145
|
+
result[key] = canonicalJson(record[key], `${path}[{*}]`, activeAncestors);
|
|
1146
|
+
}
|
|
1147
|
+
return result;
|
|
1148
|
+
}
|
|
1149
|
+
finally {
|
|
1150
|
+
activeAncestors.delete(value);
|
|
1151
|
+
}
|
|
1152
|
+
}
|
|
1153
|
+
function compareUtf8Bytes(left, right) {
|
|
1154
|
+
const leftBytes = encoder$4.encode(left);
|
|
1155
|
+
const rightBytes = encoder$4.encode(right);
|
|
1156
|
+
const length = Math.min(leftBytes.length, rightBytes.length);
|
|
1157
|
+
for (let index = 0; index < length; index += 1) {
|
|
1158
|
+
const difference = (leftBytes[index] ?? 0) - (rightBytes[index] ?? 0);
|
|
1159
|
+
if (difference !== 0)
|
|
1160
|
+
return difference;
|
|
1161
|
+
}
|
|
1162
|
+
return leftBytes.length - rightBytes.length;
|
|
1163
|
+
}
|
|
1164
|
+
function hasUnpairedSurrogate(value) {
|
|
1165
|
+
for (let index = 0; index < value.length; index += 1) {
|
|
1166
|
+
const code = value.charCodeAt(index);
|
|
1167
|
+
if (code >= 0xd800 && code <= 0xdbff) {
|
|
1168
|
+
const next = value.charCodeAt(index + 1);
|
|
1169
|
+
if (!(next >= 0xdc00 && next <= 0xdfff))
|
|
1170
|
+
return true;
|
|
1171
|
+
index += 1;
|
|
1172
|
+
}
|
|
1173
|
+
else if (code >= 0xdc00 && code <= 0xdfff) {
|
|
1174
|
+
return true;
|
|
1175
|
+
}
|
|
1176
|
+
}
|
|
1177
|
+
return false;
|
|
1178
|
+
}
|
|
1179
|
+
function compareUnicodeScalarValues(left, right) {
|
|
1180
|
+
const leftScalars = Array.from(left, (value) => value.codePointAt(0) ?? 0);
|
|
1181
|
+
const rightScalars = Array.from(right, (value) => value.codePointAt(0) ?? 0);
|
|
1182
|
+
const length = Math.min(leftScalars.length, rightScalars.length);
|
|
1183
|
+
for (let index = 0; index < length; index += 1) {
|
|
1184
|
+
const difference = (leftScalars[index] ?? 0) - (rightScalars[index] ?? 0);
|
|
1185
|
+
if (difference !== 0)
|
|
1186
|
+
return difference;
|
|
1187
|
+
}
|
|
1188
|
+
return leftScalars.length - rightScalars.length;
|
|
1189
|
+
}
|
|
1190
|
+
const SCALAR_KINDS = new Set([
|
|
1191
|
+
"string",
|
|
1192
|
+
"boolean",
|
|
1193
|
+
"int64",
|
|
1194
|
+
"float64",
|
|
1195
|
+
"datetime",
|
|
1196
|
+
"json",
|
|
1197
|
+
"enum",
|
|
1198
|
+
"model",
|
|
1199
|
+
]);
|
|
1200
|
+
function validateModelDescriptors(models, enums) {
|
|
1201
|
+
for (const modelName of Object.keys(models).sort(compareUnicodeScalarValues)) {
|
|
1202
|
+
const model = models[modelName];
|
|
1203
|
+
if (!model)
|
|
1204
|
+
continue;
|
|
1205
|
+
model.fields.forEach((field, index) => {
|
|
1206
|
+
if (!("scalarKind" in field))
|
|
1207
|
+
return;
|
|
1208
|
+
const inputPath = appendPath("$", field.schemaName);
|
|
1209
|
+
if (!SCALAR_KINDS.has(String(field.scalarKind))) {
|
|
1210
|
+
descriptorError("UNKNOWN_SCALAR_KIND", inputPath, `unknown scalar kind '${String(field.scalarKind)}'`);
|
|
1211
|
+
}
|
|
1212
|
+
if (field.scalarKind !== "enum" && field.scalarKind !== "model")
|
|
1213
|
+
return;
|
|
1214
|
+
const referencePath = `${appendPath("$.models", modelName)}.fields[${index}].descriptorId`;
|
|
1215
|
+
const registry = field.scalarKind === "enum" ? enums : models;
|
|
1216
|
+
if (!field.descriptorId || !Object.prototype.hasOwnProperty.call(registry, field.descriptorId)) {
|
|
1217
|
+
descriptorError("INVALID_DESCRIPTOR_REFERENCE", referencePath, `${field.scalarKind} descriptor '${field.descriptorId ?? ""}' does not exist`);
|
|
1218
|
+
}
|
|
1219
|
+
});
|
|
1220
|
+
}
|
|
1221
|
+
}
|
|
1222
|
+
function descriptorError(code, path, message) {
|
|
1223
|
+
throw new Error(`@repost/client: [${code}] ${path}: ${message}.`);
|
|
1224
|
+
}
|
|
1225
|
+
function appendPath(path, key) {
|
|
1226
|
+
return /^[A-Za-z_$][A-Za-z0-9_$]*$/.test(key)
|
|
1227
|
+
? `${path}.${key}`
|
|
1228
|
+
: `${path}[${JSON.stringify(key)}]`;
|
|
1229
|
+
}
|
|
1230
|
+
function validationError(code, path, message) {
|
|
1231
|
+
throw new ValidationFault(validationIssueCode(code), path, message);
|
|
1232
|
+
}
|
|
1233
|
+
class ValidationFault extends Error {
|
|
1234
|
+
constructor(code, path, detail) {
|
|
1235
|
+
super(`@repost/client: [${code}] ${path}: ${detail}.`);
|
|
1236
|
+
this.code = code;
|
|
1237
|
+
this.path = path;
|
|
1238
|
+
this.detail = detail;
|
|
1239
|
+
}
|
|
1240
|
+
}
|
|
1241
|
+
class ValidationCollector {
|
|
1242
|
+
constructor() {
|
|
1243
|
+
this.issues = [];
|
|
1244
|
+
this.issueCount = 0;
|
|
1245
|
+
this.retainedPathBytes = 0;
|
|
1246
|
+
}
|
|
1247
|
+
add(fault) {
|
|
1248
|
+
this.issueCount = Math.min(this.issueCount + 1, MAX_ISSUE_COUNT);
|
|
1249
|
+
if (this.issues.length >= MAX_ISSUES)
|
|
1250
|
+
return;
|
|
1251
|
+
const path = truncateIssuePath(fault.path);
|
|
1252
|
+
const pathBytes = encoder$4.encode(path).length;
|
|
1253
|
+
if (this.retainedPathBytes + pathBytes > MAX_TOTAL_ISSUE_PATH_BYTES)
|
|
1254
|
+
return;
|
|
1255
|
+
this.retainedPathBytes += pathBytes;
|
|
1256
|
+
this.issues.push({ code: fault.code, path, message: fault.message });
|
|
1257
|
+
}
|
|
1258
|
+
throwIfAny() {
|
|
1259
|
+
if (this.issueCount === 0)
|
|
1260
|
+
return;
|
|
1261
|
+
throw new RepostValidationError({
|
|
1262
|
+
errorCode: "VALIDATION",
|
|
1263
|
+
deliveryState: "NOT_SENT",
|
|
1264
|
+
validationIssues: this.issues,
|
|
1265
|
+
issueCount: this.issueCount,
|
|
1266
|
+
issuesTruncated: this.issueCount !== this.issues.length,
|
|
1267
|
+
});
|
|
1268
|
+
}
|
|
1269
|
+
}
|
|
1270
|
+
function validationIssueCode(code) {
|
|
1271
|
+
if (code === "REQUIRED_FIELD")
|
|
1272
|
+
return "REQUIRED";
|
|
1273
|
+
if (code === "NULL_LIST_ELEMENT")
|
|
1274
|
+
return "NULL_NOT_ALLOWED";
|
|
1275
|
+
if (code === "NON_FINITE_NUMBER")
|
|
1276
|
+
return "NON_FINITE";
|
|
1277
|
+
if (code === "UNKNOWN_SCALAR_KIND" || code === "INVALID_DESCRIPTOR_REFERENCE")
|
|
1278
|
+
return "TYPE_MISMATCH";
|
|
1279
|
+
return code;
|
|
1280
|
+
}
|
|
1281
|
+
function truncateIssuePath(path) {
|
|
1282
|
+
if (encoder$4.encode(path).length <= MAX_ISSUE_PATH_BYTES)
|
|
1283
|
+
return path;
|
|
1284
|
+
let retained = "$";
|
|
1285
|
+
const segments = path.slice(1).match(/(?:\.[A-Za-z_$][A-Za-z0-9_$]*|\[(?:0|[1-9][0-9]*)\]|\[\{\*\}\])/gu) ?? [];
|
|
1286
|
+
for (const segment of segments) {
|
|
1287
|
+
if (encoder$4.encode(retained + segment + TRUNCATION_MARKER).length > MAX_ISSUE_PATH_BYTES)
|
|
1288
|
+
break;
|
|
1289
|
+
retained += segment;
|
|
1290
|
+
}
|
|
1291
|
+
return retained + TRUNCATION_MARKER;
|
|
1292
|
+
}
|
|
1293
|
+
function resolveDefault(spec, generators) {
|
|
1294
|
+
const resolved = resolveGenerators(generators);
|
|
1295
|
+
switch (spec.kind) {
|
|
1296
|
+
case "literal":
|
|
1297
|
+
return spec.value;
|
|
1298
|
+
case "now":
|
|
1299
|
+
return resolved.now();
|
|
1300
|
+
case "uuid":
|
|
1301
|
+
return resolved.uuid();
|
|
1302
|
+
case "cuid":
|
|
1303
|
+
return resolved.cuid();
|
|
1304
|
+
}
|
|
1305
|
+
}
|
|
1306
|
+
|
|
1307
|
+
function classifyNetworkFailure(error, committed = false) {
|
|
1308
|
+
const code = errorCode(error);
|
|
1309
|
+
if (code === "ENOTFOUND" || code === "EAI_AGAIN") {
|
|
1310
|
+
return { kind: "failure", code: "DNS", reason: code === "ENOTFOUND" ? "DNS_NOT_FOUND" : "DNS_TIMEOUT", committed: false };
|
|
1311
|
+
}
|
|
1312
|
+
if (code === "ECONNREFUSED" || code === "UND_ERR_CONNECT_TIMEOUT") {
|
|
1313
|
+
return { kind: "failure", code: "CONNECT", reason: code === "ECONNREFUSED" ? "CONNECT_REFUSED" : "CONNECT_TIMEOUT", committed: false };
|
|
1314
|
+
}
|
|
1315
|
+
if (code === "CERT_HAS_EXPIRED")
|
|
1316
|
+
return { kind: "failure", code: "TLS", reason: "TLS_CERTIFICATE_EXPIRED", committed };
|
|
1317
|
+
if (code === "CERT_NOT_YET_VALID")
|
|
1318
|
+
return { kind: "failure", code: "TLS", reason: "TLS_CERTIFICATE_NOT_YET_VALID", committed };
|
|
1319
|
+
if (code === "ERR_TLS_CERT_ALTNAME_INVALID")
|
|
1320
|
+
return { kind: "failure", code: "TLS", reason: "TLS_HOSTNAME_MISMATCH", committed };
|
|
1321
|
+
if (code === "DEPTH_ZERO_SELF_SIGNED_CERT" || code === "UNABLE_TO_VERIFY_LEAF_SIGNATURE" || code === "SELF_SIGNED_CERT_IN_CHAIN") {
|
|
1322
|
+
return { kind: "failure", code: "TLS", reason: "TLS_UNTRUSTED", committed };
|
|
1323
|
+
}
|
|
1324
|
+
if (code.startsWith("ERR_TLS") || code.startsWith("ERR_SSL")) {
|
|
1325
|
+
return { kind: "failure", code: "TLS", reason: "TLS_NEGOTIATION", committed };
|
|
1326
|
+
}
|
|
1327
|
+
if (code === "REPOST_DNS_RESOLVER") {
|
|
1328
|
+
return { kind: "failure", code: "DNS", reason: "UNKNOWN", committed: false, causeCategory: "DNS_RESOLVER", retryable: false };
|
|
1329
|
+
}
|
|
1330
|
+
if (code === "REPOST_PROXY_AUTH_REQUIRED") {
|
|
1331
|
+
return { kind: "failure", code: "PROXY", reason: "PROXY_AUTH_REQUIRED", committed: false, retryable: false };
|
|
1332
|
+
}
|
|
1333
|
+
if (code === "REPOST_PROXY_CREDENTIAL_PROVIDER") {
|
|
1334
|
+
return { kind: "failure", code: "PROXY", reason: "PROXY_AUTH_REQUIRED", committed: false, causeCategory: "PROXY_CREDENTIAL_PROVIDER", retryable: false };
|
|
1335
|
+
}
|
|
1336
|
+
if (code === "REPOST_PROXY_CONNECT_FAILED") {
|
|
1337
|
+
return { kind: "failure", code: "PROXY", reason: "PROXY_CONNECT_FAILED", committed: false };
|
|
1338
|
+
}
|
|
1339
|
+
return null;
|
|
1340
|
+
}
|
|
1341
|
+
function errorCode(error) {
|
|
1342
|
+
if (!error || typeof error !== "object")
|
|
1343
|
+
return "";
|
|
1344
|
+
const direct = error.code;
|
|
1345
|
+
if (typeof direct === "string")
|
|
1346
|
+
return direct;
|
|
1347
|
+
const cause = error.cause;
|
|
1348
|
+
return cause === error ? "" : errorCode(cause);
|
|
1349
|
+
}
|
|
1350
|
+
|
|
1351
|
+
const RESPONSE_LIMIT_BYTES$1 = 1048576;
|
|
1352
|
+
/** Portable one-attempt fetch transport. Retry and deadlines belong to the runtime. */
|
|
1353
|
+
function createHttpTransport(options = {}) {
|
|
1354
|
+
rejectRuntimeOptions(options);
|
|
1355
|
+
return {
|
|
1356
|
+
async send(request) {
|
|
1357
|
+
const fetchImpl = options.fetch ?? ((input, init) => globalThis.fetch(input, init));
|
|
1358
|
+
const requestHeaders = new Headers();
|
|
1359
|
+
for (const [name, value] of request.headers)
|
|
1360
|
+
requestHeaders.append(name, value);
|
|
1361
|
+
request.commitTracker.markCommitted();
|
|
1362
|
+
try {
|
|
1363
|
+
const response = await fetchImpl(request.url, {
|
|
1364
|
+
method: "POST",
|
|
1365
|
+
headers: requestHeaders,
|
|
1366
|
+
body: Uint8Array.from(request.bodyBytes).buffer,
|
|
1367
|
+
redirect: "manual",
|
|
1368
|
+
signal: request.signal,
|
|
1369
|
+
});
|
|
1370
|
+
const headers = {};
|
|
1371
|
+
response.headers.forEach((value, name) => {
|
|
1372
|
+
var _a;
|
|
1373
|
+
(headers[_a = name.toLowerCase()] ?? (headers[_a] = [])).push(value);
|
|
1374
|
+
});
|
|
1375
|
+
const { bytes, truncated } = await readBounded(response.body, RESPONSE_LIMIT_BYTES$1);
|
|
1376
|
+
return {
|
|
1377
|
+
kind: "response",
|
|
1378
|
+
status: response.status,
|
|
1379
|
+
headers,
|
|
1380
|
+
bodyBytes: bytes,
|
|
1381
|
+
compressedBytes: bytes.length,
|
|
1382
|
+
decompressedBytes: bytes.length,
|
|
1383
|
+
truncated,
|
|
1384
|
+
};
|
|
1385
|
+
}
|
|
1386
|
+
catch (error) {
|
|
1387
|
+
return classifyFetchFailure(error, request.commitTracker.committed);
|
|
1388
|
+
}
|
|
1389
|
+
},
|
|
1390
|
+
};
|
|
1391
|
+
}
|
|
1392
|
+
/** Explicit portable transport for edge/worker runtimes. */
|
|
1393
|
+
const createFetchTransport = createHttpTransport;
|
|
1394
|
+
/** Selects the production Node lane; the package supports Node 20 and newer. */
|
|
1395
|
+
function resolveDefaultTransport(options = {}) {
|
|
1396
|
+
return createNodeTransport(options);
|
|
1397
|
+
}
|
|
1398
|
+
/** Production Node transport, loaded on first use so fetch-only bundles omit Undici. */
|
|
1399
|
+
function createNodeTransport(options = {}) {
|
|
1400
|
+
rejectRuntimeOptions(options);
|
|
1401
|
+
let loaded;
|
|
1402
|
+
const load = () => loaded ?? (loaded = import('./node-BAJt_qhB.mjs').then((module) => module.createNodeTransport(options)));
|
|
1403
|
+
return {
|
|
1404
|
+
async send(request) {
|
|
1405
|
+
return (await load()).send(request);
|
|
1406
|
+
},
|
|
1407
|
+
async close() {
|
|
1408
|
+
if (loaded)
|
|
1409
|
+
await (await loaded).close?.();
|
|
1410
|
+
},
|
|
1411
|
+
};
|
|
1412
|
+
}
|
|
1413
|
+
/** @deprecated Prefer the runtime-selected transport. */
|
|
1414
|
+
const httpTransport = createHttpTransport();
|
|
1415
|
+
function rejectRuntimeOptions(options) {
|
|
1416
|
+
if (options.maxRetries === undefined && options.baseDelayMs === undefined && options.timeoutMs === undefined)
|
|
1417
|
+
return;
|
|
1418
|
+
throw new RepostConfigurationError({
|
|
1419
|
+
errorCode: "CONFIGURATION",
|
|
1420
|
+
deliveryState: "NOT_SENT",
|
|
1421
|
+
configurationIssues: [{ code: "UNSUPPORTED", optionKeys: ["HTTP_TRANSPORT_OPTIONS"] }],
|
|
1422
|
+
});
|
|
1423
|
+
}
|
|
1424
|
+
async function readBounded(stream, limit) {
|
|
1425
|
+
if (!stream)
|
|
1426
|
+
return { bytes: new Uint8Array(), truncated: false };
|
|
1427
|
+
const reader = stream.getReader();
|
|
1428
|
+
const chunks = [];
|
|
1429
|
+
let total = 0;
|
|
1430
|
+
try {
|
|
1431
|
+
while (true) {
|
|
1432
|
+
const { done, value } = await reader.read();
|
|
1433
|
+
if (done)
|
|
1434
|
+
break;
|
|
1435
|
+
if (!value)
|
|
1436
|
+
continue;
|
|
1437
|
+
const room = limit - total;
|
|
1438
|
+
if (value.length > room) {
|
|
1439
|
+
if (room > 0)
|
|
1440
|
+
chunks.push(value.slice(0, room));
|
|
1441
|
+
total = limit;
|
|
1442
|
+
await reader.cancel();
|
|
1443
|
+
return { bytes: concatenate(chunks, total), truncated: true };
|
|
1444
|
+
}
|
|
1445
|
+
chunks.push(value);
|
|
1446
|
+
total += value.length;
|
|
1447
|
+
}
|
|
1448
|
+
return { bytes: concatenate(chunks, total), truncated: false };
|
|
1449
|
+
}
|
|
1450
|
+
finally {
|
|
1451
|
+
reader.releaseLock();
|
|
1452
|
+
}
|
|
1453
|
+
}
|
|
1454
|
+
function concatenate(chunks, total) {
|
|
1455
|
+
const bytes = new Uint8Array(total);
|
|
1456
|
+
let offset = 0;
|
|
1457
|
+
for (const chunk of chunks) {
|
|
1458
|
+
bytes.set(chunk, offset);
|
|
1459
|
+
offset += chunk.length;
|
|
1460
|
+
}
|
|
1461
|
+
return bytes;
|
|
1462
|
+
}
|
|
1463
|
+
function classifyFetchFailure(error, committed) {
|
|
1464
|
+
const classified = classifyNetworkFailure(error, committed);
|
|
1465
|
+
if (classified)
|
|
1466
|
+
return classified;
|
|
1467
|
+
if (error instanceof Error && (error.name === "TimeoutError" || error.name === "AbortError")) {
|
|
1468
|
+
return { kind: "failure", code: "ATTEMPT_TIMEOUT", reason: null, committed };
|
|
1469
|
+
}
|
|
1470
|
+
const code = errorCode(error);
|
|
1471
|
+
let reason = "UNKNOWN";
|
|
1472
|
+
if (code === "ECONNRESET")
|
|
1473
|
+
reason = "CONNECTION_RESET";
|
|
1474
|
+
else if (code === "UND_ERR_SOCKET")
|
|
1475
|
+
reason = "CONNECTION_CLOSED";
|
|
1476
|
+
return { kind: "failure", code: "IO", reason, committed };
|
|
1477
|
+
}
|
|
1478
|
+
|
|
1479
|
+
const DEFAULT_API_URL = "https://api.repost.sh";
|
|
1480
|
+
const MAX_DURATION_MS = 9223372036854;
|
|
1481
|
+
const encoder$3 = new TextEncoder();
|
|
1482
|
+
function snapshotOptions(options) {
|
|
1483
|
+
if (options.apiKey !== undefined && options.apiKeyProvider !== undefined) {
|
|
1484
|
+
invalid("CONFLICT", ["API_KEY", "API_KEY_PROVIDER"]);
|
|
1485
|
+
}
|
|
1486
|
+
if (options.transport !== undefined && options.httpTransportOptions !== undefined) {
|
|
1487
|
+
invalid("CONFLICT", ["HTTP_TRANSPORT_OPTIONS", "TRANSPORT"]);
|
|
1488
|
+
}
|
|
1489
|
+
const attemptTimeoutMs = duration(options.attemptTimeoutMs ?? options.httpTransportOptions?.timeoutMs ?? 30000, "ATTEMPT_TIMEOUT");
|
|
1490
|
+
const operationTimeoutMs = duration(options.operationTimeoutMs ?? 120000, "OPERATION_TIMEOUT");
|
|
1491
|
+
const connectTimeoutMs = duration(options.connectTimeoutMs ?? 10000, "CONNECT_TIMEOUT");
|
|
1492
|
+
const retryBaseDelayMs = duration(options.retryBaseDelayMs ?? options.httpTransportOptions?.baseDelayMs ?? 250, "RETRY_BASE_DELAY");
|
|
1493
|
+
const retryMaxDelayMs = duration(options.retryMaxDelayMs ?? 60000, "RETRY_MAX_DELAY");
|
|
1494
|
+
if (options.retryBaseDelayMs !== undefined && options.retryMaxDelayMs !== undefined && retryBaseDelayMs > retryMaxDelayMs) {
|
|
1495
|
+
invalid("CONFLICT", ["RETRY_BASE_DELAY", "RETRY_MAX_DELAY"]);
|
|
1496
|
+
}
|
|
1497
|
+
const maxAttempts = integerRange(options.maxAttempts ?? ((options.httpTransportOptions?.maxRetries ?? 3) + 1), 1, 10, "MAX_ATTEMPTS");
|
|
1498
|
+
const maxInFlightOperations = integerRange(options.maxInFlightOperations ?? 256, 1, 65536, "MAX_IN_FLIGHT_OPERATIONS");
|
|
1499
|
+
const maxBufferedBytes = integerRange(options.maxBufferedBytes ?? 67108864, 4194304, 1073741824, "MAX_BUFFERED_BYTES");
|
|
1500
|
+
if (options.userAgentSuffix !== undefined && !/^[\x21-\x7e](?:[\x20-\x7e]{0,254}[\x21-\x7e])?$/.test(options.userAgentSuffix)) {
|
|
1501
|
+
invalid("INVALID_VALUE", ["USER_AGENT_SUFFIX"]);
|
|
1502
|
+
}
|
|
1503
|
+
const fixedApiKey = options.apiKey ?? options.token;
|
|
1504
|
+
if (fixedApiKey !== undefined && (!/^[\x20-\x7e]{1,4096}$/.test(fixedApiKey) || !/[^ ]/.test(fixedApiKey))) {
|
|
1505
|
+
invalid("INVALID_VALUE", ["API_KEY"]);
|
|
1506
|
+
}
|
|
1507
|
+
const apiKey = fixedApiKey ?? process.env.REPOST_SEND_API_KEY ?? process.env.REPOST_TOKEN;
|
|
1508
|
+
return Object.freeze({
|
|
1509
|
+
apiKey,
|
|
1510
|
+
apiKeyProvider: options.apiKeyProvider,
|
|
1511
|
+
apiUrl: canonicalizeBaseUrl(options.apiUrl ?? process.env.REPOST_API_URL ?? DEFAULT_API_URL),
|
|
1512
|
+
transport: options.transport,
|
|
1513
|
+
httpTransportOptions: snapshotHttpTransportOptions(options.httpTransportOptions),
|
|
1514
|
+
generators: options.generators && Object.freeze({ ...options.generators }),
|
|
1515
|
+
attemptTimeoutMs,
|
|
1516
|
+
operationTimeoutMs,
|
|
1517
|
+
connectTimeoutMs,
|
|
1518
|
+
maxAttempts,
|
|
1519
|
+
retryBaseDelayMs,
|
|
1520
|
+
retryMaxDelayMs,
|
|
1521
|
+
maxInFlightOperations,
|
|
1522
|
+
maxBufferedBytes,
|
|
1523
|
+
idempotencyKeyGenerator: options.idempotencyKeyGenerator ?? (() => createId_1()),
|
|
1524
|
+
retryEntropy: options.retryEntropy ?? cryptoRetryEntropy,
|
|
1525
|
+
monotonicClock: options.monotonicClock ?? (() => performance.now()),
|
|
1526
|
+
wallClock: options.wallClock ?? (() => Date.now()),
|
|
1527
|
+
scheduler: options.scheduler ?? realScheduler,
|
|
1528
|
+
userAgent: `repost-client-typescript/${PACKAGE_VERSION}${options.userAgentSuffix ? ` ${options.userAgentSuffix}` : ""}`,
|
|
1529
|
+
observer: options.observer,
|
|
1530
|
+
telemetry: options.telemetry,
|
|
1531
|
+
});
|
|
1532
|
+
}
|
|
1533
|
+
function snapshotHttpTransportOptions(options) {
|
|
1534
|
+
if (!options)
|
|
1535
|
+
return undefined;
|
|
1536
|
+
const { maxRetries: _maxRetries, baseDelayMs: _baseDelayMs, timeoutMs: _timeoutMs, ...transportOptions } = options;
|
|
1537
|
+
return Object.freeze({
|
|
1538
|
+
...transportOptions,
|
|
1539
|
+
tls: options.tls && Object.freeze({
|
|
1540
|
+
...options.tls,
|
|
1541
|
+
caCertificates: options.tls.caCertificates && Object.freeze([...options.tls.caCertificates]),
|
|
1542
|
+
ciphers: options.tls.ciphers && Object.freeze([...options.tls.ciphers]),
|
|
1543
|
+
clientCertificate: options.tls.clientCertificate && Object.freeze({ ...options.tls.clientCertificate }),
|
|
1544
|
+
}),
|
|
1545
|
+
proxy: options.proxy && Object.freeze({ ...options.proxy }),
|
|
1546
|
+
});
|
|
1547
|
+
}
|
|
1548
|
+
function canonicalizeBaseUrl(raw) {
|
|
1549
|
+
if (encoder$3.encode(raw).length > 2048 || !/^[\x00-\x7f]+$/.test(raw))
|
|
1550
|
+
invalid("INVALID_VALUE", ["BASE_URI"]);
|
|
1551
|
+
const match = /^(https?):\/\/([^/?#]+)(\/[^?#]*)?$/.exec(raw);
|
|
1552
|
+
if (!match)
|
|
1553
|
+
invalid("INVALID_VALUE", ["BASE_URI"]);
|
|
1554
|
+
const [, scheme, authority, rawPath = ""] = match;
|
|
1555
|
+
if (authority.length === 0 || encoder$3.encode(authority).length > 512 || authority.includes("@"))
|
|
1556
|
+
invalid("INVALID_VALUE", ["BASE_URI"]);
|
|
1557
|
+
const { host, port } = parseAuthority(authority);
|
|
1558
|
+
if (host !== host.toLowerCase() || !validHost(scheme, host))
|
|
1559
|
+
invalid("INVALID_VALUE", ["BASE_URI"]);
|
|
1560
|
+
if (port !== undefined) {
|
|
1561
|
+
if (/^-?[0-9]+$/u.test(port) && (Number(port) < 1 || Number(port) > 65535))
|
|
1562
|
+
invalid("OUT_OF_RANGE", ["BASE_URI"]);
|
|
1563
|
+
if (!/^[1-9][0-9]*$/u.test(port))
|
|
1564
|
+
invalid("INVALID_VALUE", ["BASE_URI"]);
|
|
1565
|
+
}
|
|
1566
|
+
if (encoder$3.encode(rawPath).length > 1536 || !validPath(rawPath))
|
|
1567
|
+
invalid("INVALID_VALUE", ["BASE_URI"]);
|
|
1568
|
+
const path = rawPath.replace(/\/+$/, "");
|
|
1569
|
+
const base = `${scheme}://${authority}${path}`;
|
|
1570
|
+
const endpoint = path.endsWith("/v1/messages") ? base : `${base}/v1/messages`;
|
|
1571
|
+
if (encoder$3.encode(new URL(endpoint).pathname).length > 2048 || encoder$3.encode(endpoint).length > 4096)
|
|
1572
|
+
invalid("INVALID_VALUE", ["BASE_URI"]);
|
|
1573
|
+
return base;
|
|
1574
|
+
}
|
|
1575
|
+
function endpointUrl(base) {
|
|
1576
|
+
return base.endsWith("/v1/messages") ? base : `${base}/v1/messages`;
|
|
1577
|
+
}
|
|
1578
|
+
function duration(value, key) {
|
|
1579
|
+
if (!Number.isSafeInteger(value) || value < 1 || value > MAX_DURATION_MS)
|
|
1580
|
+
invalid("OUT_OF_RANGE", [key]);
|
|
1581
|
+
return value;
|
|
1582
|
+
}
|
|
1583
|
+
function integerRange(value, min, max, key) {
|
|
1584
|
+
if (!Number.isSafeInteger(value) || value < min || value > max)
|
|
1585
|
+
invalid("OUT_OF_RANGE", [key]);
|
|
1586
|
+
return value;
|
|
1587
|
+
}
|
|
1588
|
+
function parseAuthority(authority) {
|
|
1589
|
+
if (authority.startsWith("[")) {
|
|
1590
|
+
const end = authority.indexOf("]");
|
|
1591
|
+
if (end < 0)
|
|
1592
|
+
invalid("INVALID_VALUE", ["BASE_URI"]);
|
|
1593
|
+
const suffix = authority.slice(end + 1);
|
|
1594
|
+
if (suffix !== "" && !suffix.startsWith(":"))
|
|
1595
|
+
invalid("INVALID_VALUE", ["BASE_URI"]);
|
|
1596
|
+
return { host: authority.slice(0, end + 1), port: suffix === "" ? undefined : suffix.slice(1) };
|
|
1597
|
+
}
|
|
1598
|
+
const colon = authority.lastIndexOf(":");
|
|
1599
|
+
if (colon < 0)
|
|
1600
|
+
return { host: authority };
|
|
1601
|
+
if (authority.indexOf(":") !== colon)
|
|
1602
|
+
invalid("INVALID_VALUE", ["BASE_URI"]);
|
|
1603
|
+
return { host: authority.slice(0, colon), port: authority.slice(colon + 1) };
|
|
1604
|
+
}
|
|
1605
|
+
function validHost(scheme, host) {
|
|
1606
|
+
if (scheme === "http") {
|
|
1607
|
+
if (host === "localhost" || host === "[::1]")
|
|
1608
|
+
return true;
|
|
1609
|
+
const parts = host.split(".");
|
|
1610
|
+
return parts.length === 4
|
|
1611
|
+
&& parts.every((part) => /^(0|[1-9][0-9]{0,2})$/.test(part) && Number(part) <= 255)
|
|
1612
|
+
&& parts[0] === "127";
|
|
1613
|
+
}
|
|
1614
|
+
if (host.startsWith("[")) {
|
|
1615
|
+
try {
|
|
1616
|
+
return new URL(`https://${host}`).hostname === host;
|
|
1617
|
+
}
|
|
1618
|
+
catch {
|
|
1619
|
+
return false;
|
|
1620
|
+
}
|
|
1621
|
+
}
|
|
1622
|
+
if (!/^[a-z0-9.-]+$/.test(host) || host.endsWith(".") || host.includes(".."))
|
|
1623
|
+
return false;
|
|
1624
|
+
const parts = host.split(".");
|
|
1625
|
+
if (parts.every((part) => /^[0-9]+$/.test(part))) {
|
|
1626
|
+
return parts.length === 4
|
|
1627
|
+
&& parts.every((part) => /^(0|[1-9][0-9]{0,2})$/.test(part) && Number(part) <= 255);
|
|
1628
|
+
}
|
|
1629
|
+
return parts.every((part) => /^[a-z0-9](?:[a-z0-9-]*[a-z0-9])?$/.test(part));
|
|
1630
|
+
}
|
|
1631
|
+
function validPath(path) {
|
|
1632
|
+
if (!/^(?:[A-Za-z0-9._~!$&'()*+,;=:@/-]|%[0-9A-F]{2})*$/.test(path))
|
|
1633
|
+
return false;
|
|
1634
|
+
if (/%(?:2F|5C)/.test(path))
|
|
1635
|
+
return false;
|
|
1636
|
+
return !path.split("/").some((segment) => segment === "." || segment === "..");
|
|
1637
|
+
}
|
|
1638
|
+
function invalid(code, optionKeys) {
|
|
1639
|
+
throw new RepostConfigurationError({
|
|
1640
|
+
errorCode: "CONFIGURATION",
|
|
1641
|
+
deliveryState: "NOT_SENT",
|
|
1642
|
+
configurationIssues: [{ code, optionKeys }],
|
|
1643
|
+
});
|
|
1644
|
+
}
|
|
1645
|
+
const cryptoRetryEntropy = {
|
|
1646
|
+
nextInt(exclusiveBound) {
|
|
1647
|
+
if (!Number.isSafeInteger(exclusiveBound) || exclusiveBound < 1 || exclusiveBound > 4294967296)
|
|
1648
|
+
throw new RangeError("invalid entropy bound");
|
|
1649
|
+
const limit = Math.floor(4294967296 / exclusiveBound) * exclusiveBound;
|
|
1650
|
+
const sample = new Uint32Array(1);
|
|
1651
|
+
do
|
|
1652
|
+
crypto.getRandomValues(sample);
|
|
1653
|
+
while ((sample[0] ?? 0) >= limit);
|
|
1654
|
+
return (sample[0] ?? 0) % exclusiveBound;
|
|
1655
|
+
},
|
|
1656
|
+
};
|
|
1657
|
+
const realScheduler = {
|
|
1658
|
+
sleep(ms, signal) {
|
|
1659
|
+
return new Promise((resolve, reject) => {
|
|
1660
|
+
if (signal?.aborted)
|
|
1661
|
+
return reject(signal.reason);
|
|
1662
|
+
const timer = setTimeout(resolve, ms);
|
|
1663
|
+
signal?.addEventListener("abort", () => {
|
|
1664
|
+
clearTimeout(timer);
|
|
1665
|
+
reject(signal.reason);
|
|
1666
|
+
}, { once: true });
|
|
1667
|
+
});
|
|
1668
|
+
},
|
|
1669
|
+
};
|
|
1670
|
+
|
|
1671
|
+
function observerEvent(kind, operationId, timestampMs, values = {}) {
|
|
1672
|
+
return Object.freeze({
|
|
1673
|
+
schemaVersion: 1,
|
|
1674
|
+
kind,
|
|
1675
|
+
operationId,
|
|
1676
|
+
timestampMs,
|
|
1677
|
+
attemptNumber: null,
|
|
1678
|
+
durationMs: null,
|
|
1679
|
+
outcome: null,
|
|
1680
|
+
errorCode: null,
|
|
1681
|
+
deliveryState: null,
|
|
1682
|
+
httpStatusClass: null,
|
|
1683
|
+
retryDelayMs: null,
|
|
1684
|
+
operationStartedAtMs: null,
|
|
1685
|
+
operationEndedAtMs: null,
|
|
1686
|
+
attemptSummaries: Object.freeze([]),
|
|
1687
|
+
...values,
|
|
1688
|
+
});
|
|
1689
|
+
}
|
|
1690
|
+
function attemptSummary(attemptNumber, outcome, error, attempt, durationMs) {
|
|
1691
|
+
let httpStatusClass = null;
|
|
1692
|
+
if (attempt.kind === "response")
|
|
1693
|
+
httpStatusClass = statusClass(attempt.status);
|
|
1694
|
+
else if (attempt.httpStatus !== undefined && attempt.httpStatus !== null) {
|
|
1695
|
+
httpStatusClass = statusClass(attempt.httpStatus);
|
|
1696
|
+
}
|
|
1697
|
+
return Object.freeze({
|
|
1698
|
+
attemptNumber,
|
|
1699
|
+
outcome,
|
|
1700
|
+
errorCode: error?.errorCode ?? null,
|
|
1701
|
+
deliveryState: error?.deliveryState ?? (outcome === "ACCEPTED" ? "ACCEPTED" : null),
|
|
1702
|
+
httpStatusClass,
|
|
1703
|
+
durationMs: Math.max(0, durationMs),
|
|
1704
|
+
});
|
|
1705
|
+
}
|
|
1706
|
+
function statusClass(status) {
|
|
1707
|
+
if (status < 200)
|
|
1708
|
+
return "INFORMATIONAL";
|
|
1709
|
+
if (status < 300)
|
|
1710
|
+
return "SUCCESS";
|
|
1711
|
+
if (status < 400)
|
|
1712
|
+
return "REDIRECT";
|
|
1713
|
+
if (status < 500)
|
|
1714
|
+
return "CLIENT_ERROR";
|
|
1715
|
+
return "SERVER_ERROR";
|
|
1716
|
+
}
|
|
1717
|
+
function telemetryAttemptEnd(summary) {
|
|
1718
|
+
return {
|
|
1719
|
+
httpStatusClass: summary.httpStatusClass,
|
|
1720
|
+
outcome: summary.outcome,
|
|
1721
|
+
errorCode: summary.errorCode,
|
|
1722
|
+
durationMs: summary.durationMs,
|
|
1723
|
+
};
|
|
1724
|
+
}
|
|
1725
|
+
|
|
1726
|
+
const encoder$2 = new TextEncoder();
|
|
1727
|
+
async function resolveCredential(config, operationId) {
|
|
1728
|
+
let credential = config.apiKey;
|
|
1729
|
+
if (config.apiKeyProvider) {
|
|
1730
|
+
try {
|
|
1731
|
+
credential = await config.apiKeyProvider();
|
|
1732
|
+
}
|
|
1733
|
+
catch {
|
|
1734
|
+
throw new RepostConfigurationError({
|
|
1735
|
+
errorCode: "CONFIGURATION", deliveryState: "NOT_SENT", operationId,
|
|
1736
|
+
causeCategory: "API_KEY_PROVIDER",
|
|
1737
|
+
configurationIssues: [{ code: "INVALID_VALUE", optionKeys: ["API_KEY_PROVIDER"] }],
|
|
1738
|
+
});
|
|
1739
|
+
}
|
|
1740
|
+
}
|
|
1741
|
+
if (credential === undefined) {
|
|
1742
|
+
throw new RepostConfigurationError({
|
|
1743
|
+
errorCode: "CONFIGURATION", deliveryState: "NOT_SENT", operationId,
|
|
1744
|
+
configurationIssues: [{ code: "MISSING", optionKeys: ["API_KEY"] }],
|
|
1745
|
+
});
|
|
1746
|
+
}
|
|
1747
|
+
if (typeof credential !== "string" || !/^[\x20-\x7e]{1,4096}$/.test(credential) || !/[^ ]/.test(credential)) {
|
|
1748
|
+
throw new RepostConfigurationError({
|
|
1749
|
+
errorCode: "CONFIGURATION", deliveryState: "NOT_SENT", operationId,
|
|
1750
|
+
configurationIssues: [{ code: "INVALID_VALUE", optionKeys: [config.apiKeyProvider ? "API_KEY_PROVIDER" : "API_KEY"] }],
|
|
1751
|
+
});
|
|
1752
|
+
}
|
|
1753
|
+
return credential;
|
|
1754
|
+
}
|
|
1755
|
+
function resolveIdempotencyKey(config, supplied, operationId) {
|
|
1756
|
+
let key = supplied;
|
|
1757
|
+
if (key === undefined) {
|
|
1758
|
+
if (config.idempotencyKeyGenerator === false) {
|
|
1759
|
+
throw new RepostConfigurationError({
|
|
1760
|
+
errorCode: "CONFIGURATION", deliveryState: "NOT_SENT", operationId,
|
|
1761
|
+
configurationIssues: [{ code: "CONFLICT", optionKeys: ["MAX_ATTEMPTS", "IDEMPOTENCY_KEY_GENERATOR"] }],
|
|
1762
|
+
});
|
|
1763
|
+
}
|
|
1764
|
+
try {
|
|
1765
|
+
key = config.idempotencyKeyGenerator();
|
|
1766
|
+
}
|
|
1767
|
+
catch {
|
|
1768
|
+
throw new RepostConfigurationError({
|
|
1769
|
+
errorCode: "CONFIGURATION", deliveryState: "NOT_SENT", operationId,
|
|
1770
|
+
causeCategory: "IDEMPOTENCY_GENERATOR",
|
|
1771
|
+
configurationIssues: [{ code: "INVALID_VALUE", optionKeys: ["IDEMPOTENCY_KEY_GENERATOR"] }],
|
|
1772
|
+
});
|
|
1773
|
+
}
|
|
1774
|
+
}
|
|
1775
|
+
if (typeof key !== "string" || !/^[\x21-\x7e](?:[\x20-\x7e]{0,253}[\x21-\x7e])?$/.test(key)) {
|
|
1776
|
+
if (supplied !== undefined) {
|
|
1777
|
+
throw new RepostValidationError({
|
|
1778
|
+
errorCode: "VALIDATION",
|
|
1779
|
+
deliveryState: "NOT_SENT",
|
|
1780
|
+
operationId,
|
|
1781
|
+
validationIssues: [{
|
|
1782
|
+
code: typeof key === "string" && encoder$2.encode(key).length > 255 ? "COLLECTION_LIMIT" : "INVALID_UNICODE",
|
|
1783
|
+
path: "$",
|
|
1784
|
+
message: "@repost/client: invalid idempotency key.",
|
|
1785
|
+
}],
|
|
1786
|
+
});
|
|
1787
|
+
}
|
|
1788
|
+
throw new RepostConfigurationError({
|
|
1789
|
+
errorCode: "CONFIGURATION", deliveryState: "NOT_SENT", operationId,
|
|
1790
|
+
configurationIssues: [{ code: "INVALID_VALUE", optionKeys: ["IDEMPOTENCY_KEY_GENERATOR"] }],
|
|
1791
|
+
});
|
|
1792
|
+
}
|
|
1793
|
+
return key;
|
|
1794
|
+
}
|
|
1795
|
+
function serializeForSend(schema, event, data, generators, operationId, idempotencyKey) {
|
|
1796
|
+
try {
|
|
1797
|
+
return serializeModel(schema.models, event.model, data, generators, schema.enums);
|
|
1798
|
+
}
|
|
1799
|
+
catch (error) {
|
|
1800
|
+
if (error instanceof RepostValidationError) {
|
|
1801
|
+
throw new RepostValidationError({
|
|
1802
|
+
errorCode: "VALIDATION",
|
|
1803
|
+
deliveryState: "NOT_SENT",
|
|
1804
|
+
operationId,
|
|
1805
|
+
idempotencyKey,
|
|
1806
|
+
validationIssues: error.validationIssues,
|
|
1807
|
+
issueCount: error.issueCount,
|
|
1808
|
+
issuesTruncated: error.issuesTruncated,
|
|
1809
|
+
});
|
|
1810
|
+
}
|
|
1811
|
+
if (error instanceof RepostError)
|
|
1812
|
+
throw error;
|
|
1813
|
+
const message = error instanceof Error ? error.message : "@repost/client: [TYPE_MISMATCH] $: invalid input.";
|
|
1814
|
+
const match = /\[([A-Z_]+)] ([^:]+): (.+)/.exec(message);
|
|
1815
|
+
throw new RepostValidationError({
|
|
1816
|
+
errorCode: "VALIDATION", deliveryState: "NOT_SENT", operationId, idempotencyKey,
|
|
1817
|
+
validationIssues: [{
|
|
1818
|
+
code: validationCode(match?.[1]),
|
|
1819
|
+
path: match?.[2] ?? "$",
|
|
1820
|
+
message,
|
|
1821
|
+
}],
|
|
1822
|
+
});
|
|
1823
|
+
}
|
|
1824
|
+
}
|
|
1825
|
+
function validationCode(code) {
|
|
1826
|
+
if (code === "REQUIRED_FIELD")
|
|
1827
|
+
return "REQUIRED";
|
|
1828
|
+
if (code === "NULL_NOT_ALLOWED" || code === "NULL_LIST_ELEMENT")
|
|
1829
|
+
return "NULL_NOT_ALLOWED";
|
|
1830
|
+
if (code === "NON_FINITE_NUMBER")
|
|
1831
|
+
return "NON_FINITE";
|
|
1832
|
+
if (code === "OUT_OF_RANGE")
|
|
1833
|
+
return "OUT_OF_RANGE";
|
|
1834
|
+
if (code === "INVALID_DATETIME")
|
|
1835
|
+
return "INVALID_DATETIME";
|
|
1836
|
+
if (code === "INVALID_ENUM")
|
|
1837
|
+
return "INVALID_ENUM";
|
|
1838
|
+
if (code === "INVALID_JSON")
|
|
1839
|
+
return "INVALID_JSON";
|
|
1840
|
+
if (code === "INVALID_UNICODE")
|
|
1841
|
+
return "INVALID_UNICODE";
|
|
1842
|
+
if (code === "COLLECTION_LIMIT")
|
|
1843
|
+
return "COLLECTION_LIMIT";
|
|
1844
|
+
if (code === "CYCLE")
|
|
1845
|
+
return "CYCLE";
|
|
1846
|
+
return "TYPE_MISMATCH";
|
|
1847
|
+
}
|
|
1848
|
+
|
|
1849
|
+
const MAX_DEPTH = 32;
|
|
1850
|
+
const MAX_TOKENS = 10000;
|
|
1851
|
+
const MAX_FIELD_NAME_BYTES = 64;
|
|
1852
|
+
const MAX_STRING_BYTES = 8192;
|
|
1853
|
+
const MAX_STRING_CHARS = 8192;
|
|
1854
|
+
const MAX_NUMBER_CHARS = 128;
|
|
1855
|
+
const MAX_MEMBERS = 16;
|
|
1856
|
+
const encoder$1 = new TextEncoder();
|
|
1857
|
+
class StrictJsonSyntaxError extends Error {
|
|
1858
|
+
}
|
|
1859
|
+
class StrictJsonLimitError extends Error {
|
|
1860
|
+
}
|
|
1861
|
+
function parseStrictJson(bytes) {
|
|
1862
|
+
if (bytes.length >= 3 && bytes[0] === 0xef && bytes[1] === 0xbb && bytes[2] === 0xbf) {
|
|
1863
|
+
throw new StrictJsonSyntaxError("UTF-8 BOM is not allowed");
|
|
1864
|
+
}
|
|
1865
|
+
let text;
|
|
1866
|
+
try {
|
|
1867
|
+
text = new TextDecoder("utf-8", { fatal: true }).decode(bytes);
|
|
1868
|
+
}
|
|
1869
|
+
catch {
|
|
1870
|
+
throw new StrictJsonSyntaxError("response is not scalar-valid UTF-8");
|
|
1871
|
+
}
|
|
1872
|
+
new Scanner(text).parse();
|
|
1873
|
+
try {
|
|
1874
|
+
return JSON.parse(text);
|
|
1875
|
+
}
|
|
1876
|
+
catch {
|
|
1877
|
+
throw new StrictJsonSyntaxError("malformed JSON");
|
|
1878
|
+
}
|
|
1879
|
+
}
|
|
1880
|
+
class Scanner {
|
|
1881
|
+
constructor(text) {
|
|
1882
|
+
this.text = text;
|
|
1883
|
+
this.index = 0;
|
|
1884
|
+
this.tokens = 0;
|
|
1885
|
+
}
|
|
1886
|
+
parse() {
|
|
1887
|
+
this.whitespace();
|
|
1888
|
+
this.value(0);
|
|
1889
|
+
this.whitespace();
|
|
1890
|
+
if (this.index !== this.text.length)
|
|
1891
|
+
this.syntax();
|
|
1892
|
+
}
|
|
1893
|
+
value(depth) {
|
|
1894
|
+
this.whitespace();
|
|
1895
|
+
const char = this.text[this.index];
|
|
1896
|
+
if (char === "{") {
|
|
1897
|
+
this.object(depth + 1);
|
|
1898
|
+
return;
|
|
1899
|
+
}
|
|
1900
|
+
if (char === "[") {
|
|
1901
|
+
this.array(depth + 1);
|
|
1902
|
+
return;
|
|
1903
|
+
}
|
|
1904
|
+
if (char === '"') {
|
|
1905
|
+
this.token();
|
|
1906
|
+
this.string(false);
|
|
1907
|
+
return;
|
|
1908
|
+
}
|
|
1909
|
+
if (char === "t") {
|
|
1910
|
+
this.scalar("true");
|
|
1911
|
+
return;
|
|
1912
|
+
}
|
|
1913
|
+
if (char === "f") {
|
|
1914
|
+
this.scalar("false");
|
|
1915
|
+
return;
|
|
1916
|
+
}
|
|
1917
|
+
if (char === "n") {
|
|
1918
|
+
this.scalar("null");
|
|
1919
|
+
return;
|
|
1920
|
+
}
|
|
1921
|
+
this.number();
|
|
1922
|
+
}
|
|
1923
|
+
object(depth) {
|
|
1924
|
+
this.depth(depth);
|
|
1925
|
+
this.token();
|
|
1926
|
+
this.index += 1;
|
|
1927
|
+
this.whitespace();
|
|
1928
|
+
if (this.text[this.index] === "}") {
|
|
1929
|
+
this.index += 1;
|
|
1930
|
+
this.token();
|
|
1931
|
+
return;
|
|
1932
|
+
}
|
|
1933
|
+
const keys = new Set();
|
|
1934
|
+
let members = 0;
|
|
1935
|
+
while (this.index < this.text.length) {
|
|
1936
|
+
this.whitespace();
|
|
1937
|
+
if (this.text[this.index] !== '"')
|
|
1938
|
+
this.syntax();
|
|
1939
|
+
this.token();
|
|
1940
|
+
const key = this.string(true);
|
|
1941
|
+
if (keys.has(key))
|
|
1942
|
+
throw new StrictJsonSyntaxError("duplicate object key");
|
|
1943
|
+
keys.add(key);
|
|
1944
|
+
members += 1;
|
|
1945
|
+
if (members > MAX_MEMBERS)
|
|
1946
|
+
this.limit("object members");
|
|
1947
|
+
this.whitespace();
|
|
1948
|
+
if (this.text[this.index] !== ":")
|
|
1949
|
+
this.syntax();
|
|
1950
|
+
this.index += 1;
|
|
1951
|
+
this.value(depth);
|
|
1952
|
+
this.whitespace();
|
|
1953
|
+
if (this.text[this.index] === "}") {
|
|
1954
|
+
this.index += 1;
|
|
1955
|
+
this.token();
|
|
1956
|
+
return;
|
|
1957
|
+
}
|
|
1958
|
+
if (this.text[this.index] !== ",")
|
|
1959
|
+
this.syntax();
|
|
1960
|
+
this.index += 1;
|
|
1961
|
+
}
|
|
1962
|
+
this.syntax();
|
|
1963
|
+
}
|
|
1964
|
+
array(depth) {
|
|
1965
|
+
this.depth(depth);
|
|
1966
|
+
this.token();
|
|
1967
|
+
this.index += 1;
|
|
1968
|
+
this.whitespace();
|
|
1969
|
+
if (this.text[this.index] === "]") {
|
|
1970
|
+
this.index += 1;
|
|
1971
|
+
this.token();
|
|
1972
|
+
return;
|
|
1973
|
+
}
|
|
1974
|
+
while (this.index < this.text.length) {
|
|
1975
|
+
this.value(depth);
|
|
1976
|
+
this.whitespace();
|
|
1977
|
+
if (this.text[this.index] === "]") {
|
|
1978
|
+
this.index += 1;
|
|
1979
|
+
this.token();
|
|
1980
|
+
return;
|
|
1981
|
+
}
|
|
1982
|
+
if (this.text[this.index] !== ",")
|
|
1983
|
+
this.syntax();
|
|
1984
|
+
this.index += 1;
|
|
1985
|
+
}
|
|
1986
|
+
this.syntax();
|
|
1987
|
+
}
|
|
1988
|
+
string(fieldName) {
|
|
1989
|
+
const start = this.index;
|
|
1990
|
+
this.index += 1;
|
|
1991
|
+
while (this.index < this.text.length) {
|
|
1992
|
+
const char = this.text[this.index];
|
|
1993
|
+
if (char === "\\")
|
|
1994
|
+
this.index += 2;
|
|
1995
|
+
else if (char === '"') {
|
|
1996
|
+
this.index += 1;
|
|
1997
|
+
let value;
|
|
1998
|
+
try {
|
|
1999
|
+
value = JSON.parse(this.text.slice(start, this.index));
|
|
2000
|
+
}
|
|
2001
|
+
catch {
|
|
2002
|
+
this.syntax();
|
|
2003
|
+
}
|
|
2004
|
+
let chars = 0;
|
|
2005
|
+
for (let offset = 0; offset < value.length; offset += 1) {
|
|
2006
|
+
const unit = value.charCodeAt(offset);
|
|
2007
|
+
if (unit >= 0xd800 && unit <= 0xdbff) {
|
|
2008
|
+
const next = value.charCodeAt(offset + 1);
|
|
2009
|
+
if (!(next >= 0xdc00 && next <= 0xdfff))
|
|
2010
|
+
this.syntax();
|
|
2011
|
+
offset += 1;
|
|
2012
|
+
}
|
|
2013
|
+
else if (unit >= 0xdc00 && unit <= 0xdfff)
|
|
2014
|
+
this.syntax();
|
|
2015
|
+
chars += 1;
|
|
2016
|
+
}
|
|
2017
|
+
const byteLength = encoder$1.encode(value).length;
|
|
2018
|
+
if (fieldName ? byteLength > MAX_FIELD_NAME_BYTES : byteLength > MAX_STRING_BYTES || chars > MAX_STRING_CHARS) {
|
|
2019
|
+
this.limit(fieldName ? "field name" : "string scalar");
|
|
2020
|
+
}
|
|
2021
|
+
return value;
|
|
2022
|
+
}
|
|
2023
|
+
else {
|
|
2024
|
+
if ((char?.charCodeAt(0) ?? 0) < 0x20)
|
|
2025
|
+
this.syntax();
|
|
2026
|
+
this.index += 1;
|
|
2027
|
+
}
|
|
2028
|
+
}
|
|
2029
|
+
this.syntax();
|
|
2030
|
+
}
|
|
2031
|
+
scalar(value) {
|
|
2032
|
+
this.token();
|
|
2033
|
+
if (!this.text.startsWith(value, this.index))
|
|
2034
|
+
this.syntax();
|
|
2035
|
+
this.index += value.length;
|
|
2036
|
+
}
|
|
2037
|
+
number() {
|
|
2038
|
+
const match = /^-?(?:0|[1-9][0-9]*)(?:\.[0-9]+)?(?:[eE][+-]?[0-9]+)?/u.exec(this.text.slice(this.index));
|
|
2039
|
+
if (!match)
|
|
2040
|
+
this.syntax();
|
|
2041
|
+
this.token();
|
|
2042
|
+
if (match[0].length > MAX_NUMBER_CHARS)
|
|
2043
|
+
this.limit("number token");
|
|
2044
|
+
this.index += match[0].length;
|
|
2045
|
+
}
|
|
2046
|
+
whitespace() {
|
|
2047
|
+
while (/^[\x20\x09\x0a\x0d]$/u.test(this.text[this.index] ?? ""))
|
|
2048
|
+
this.index += 1;
|
|
2049
|
+
}
|
|
2050
|
+
token() {
|
|
2051
|
+
this.tokens += 1;
|
|
2052
|
+
if (this.tokens > MAX_TOKENS)
|
|
2053
|
+
this.limit("tokens");
|
|
2054
|
+
}
|
|
2055
|
+
depth(depth) {
|
|
2056
|
+
if (depth > MAX_DEPTH)
|
|
2057
|
+
this.limit("nesting depth");
|
|
2058
|
+
}
|
|
2059
|
+
syntax() { throw new StrictJsonSyntaxError("malformed JSON"); }
|
|
2060
|
+
limit(name) { throw new StrictJsonLimitError(`JSON ${name} limit exceeded`); }
|
|
2061
|
+
}
|
|
2062
|
+
|
|
2063
|
+
const RESPONSE_LIMIT_BYTES = 1048576;
|
|
2064
|
+
function classifyOutcome(outcome, priorPossible) {
|
|
2065
|
+
if (outcome.kind === "failure") {
|
|
2066
|
+
const retryable = outcome.retryable
|
|
2067
|
+
?? (outcome.code !== "TLS" && !(outcome.code === "PROXY" && outcome.reason === "PROXY_AUTH_REQUIRED"));
|
|
2068
|
+
const possible = priorPossible || outcome.committed;
|
|
2069
|
+
return { code: outcome.code, retryable, deliveryState: possible ? "POSSIBLY_SENT" : "NOT_SENT", reason: outcome.reason, acceptancePossible: possible };
|
|
2070
|
+
}
|
|
2071
|
+
if (outcome.protocolError) {
|
|
2072
|
+
return { code: "RESPONSE_PROTOCOL", retryable: false, deliveryState: "POSSIBLY_SENT", reason: null, acceptancePossible: true };
|
|
2073
|
+
}
|
|
2074
|
+
if (outcome.proxyError) {
|
|
2075
|
+
return { code: "PROXY", retryable: false, deliveryState: "NOT_SENT", reason: "UNKNOWN", acceptancePossible: false };
|
|
2076
|
+
}
|
|
2077
|
+
const status = outcome.status;
|
|
2078
|
+
if (status >= 200 && status <= 299) {
|
|
2079
|
+
if (outcome.truncated
|
|
2080
|
+
|| (!outcome.transportLimitsApplied && outcome.compressedBytes > RESPONSE_LIMIT_BYTES)
|
|
2081
|
+
|| (!outcome.transportLimitsApplied && outcome.decompressedBytes > RESPONSE_LIMIT_BYTES)
|
|
2082
|
+
|| outcome.limitExceeded
|
|
2083
|
+
|| (!outcome.transportLimitsApplied && outcome.compressedBytes > 0 && outcome.decompressedBytes > outcome.compressedBytes * 100)) {
|
|
2084
|
+
return { code: "RESPONSE_TOO_LARGE", retryable: false, deliveryState: "POSSIBLY_SENT", reason: null, acceptancePossible: true };
|
|
2085
|
+
}
|
|
2086
|
+
return { code: "RESPONSE_PROTOCOL", retryable: true, deliveryState: "POSSIBLY_SENT", reason: null, acceptancePossible: true };
|
|
2087
|
+
}
|
|
2088
|
+
if (status === 429)
|
|
2089
|
+
return { code: "RATE_LIMITED", retryable: !outcome.nonRetryable, deliveryState: priorPossible ? "POSSIBLY_SENT" : "REJECTED", reason: null, acceptancePossible: priorPossible };
|
|
2090
|
+
if (status === 409)
|
|
2091
|
+
return { code: "HTTP_REJECTED", retryable: !outcome.nonRetryable, deliveryState: "POSSIBLY_SENT", reason: null, acceptancePossible: true };
|
|
2092
|
+
if (status >= 300 && status < 400)
|
|
2093
|
+
return { code: "HTTP_REJECTED", retryable: false, deliveryState: "REJECTED", reason: null, acceptancePossible: priorPossible };
|
|
2094
|
+
if (status >= 500)
|
|
2095
|
+
return { code: "SERVER_FAILURE", retryable: !outcome.nonRetryable, deliveryState: "POSSIBLY_SENT", reason: null, acceptancePossible: true };
|
|
2096
|
+
if (status >= 400)
|
|
2097
|
+
return { code: "HTTP_REJECTED", retryable: false, deliveryState: "REJECTED", reason: null, acceptancePossible: priorPossible };
|
|
2098
|
+
return { code: "RESPONSE_PROTOCOL", retryable: false, deliveryState: "POSSIBLY_SENT", reason: null, acceptancePossible: true };
|
|
2099
|
+
}
|
|
2100
|
+
function validateAcceptedResponse(outcome, envelope, customerId) {
|
|
2101
|
+
if (outcome.bodyBytes.length > RESPONSE_LIMIT_BYTES
|
|
2102
|
+
|| (!outcome.transportLimitsApplied && outcome.compressedBytes > RESPONSE_LIMIT_BYTES)
|
|
2103
|
+
|| (!outcome.transportLimitsApplied && outcome.decompressedBytes > RESPONSE_LIMIT_BYTES))
|
|
2104
|
+
return null;
|
|
2105
|
+
const contentTypes = headerValues(outcome.headers, "content-type");
|
|
2106
|
+
if (contentTypes.length !== 1
|
|
2107
|
+
|| !/^[\t ]*application\/json[\t ]*(?:;[\t ]*charset[\t ]*=[\t ]*(?:utf-8|"utf-8")[\t ]*)?$/i.test(contentTypes[0] ?? ""))
|
|
2108
|
+
return null;
|
|
2109
|
+
try {
|
|
2110
|
+
const value = parseStrictJson(outcome.bodyBytes);
|
|
2111
|
+
if (!value || typeof value !== "object" || Array.isArray(value))
|
|
2112
|
+
return null;
|
|
2113
|
+
if (typeof value.id !== "string" || !/^msg_[A-Za-z0-9_-]{1,124}$/.test(value.id))
|
|
2114
|
+
return null;
|
|
2115
|
+
if (value.type !== envelope.type || value.customerId !== customerId || value.timestamp !== envelope.timestamp)
|
|
2116
|
+
return null;
|
|
2117
|
+
return Object.freeze({ id: value.id, type: envelope.type, customerId, timestamp: envelope.timestamp });
|
|
2118
|
+
}
|
|
2119
|
+
catch (error) {
|
|
2120
|
+
if (error instanceof StrictJsonLimitError)
|
|
2121
|
+
return "LIMIT_EXCEEDED";
|
|
2122
|
+
return null;
|
|
2123
|
+
}
|
|
2124
|
+
}
|
|
2125
|
+
function headerValues(headers, name) {
|
|
2126
|
+
const entry = Object.entries(headers).find(([key]) => key.toLowerCase() === name);
|
|
2127
|
+
return entry?.[1] ?? [];
|
|
2128
|
+
}
|
|
2129
|
+
function parseRetryAfter(headers, wallNow) {
|
|
2130
|
+
const values = headerValues(headers, "retry-after");
|
|
2131
|
+
if (values.length === 0 || values.some((value) => value !== values[0]))
|
|
2132
|
+
return null;
|
|
2133
|
+
const value = values[0] ?? "";
|
|
2134
|
+
if (/^[0-9]+$/.test(value)) {
|
|
2135
|
+
const ms = Number(value) * 1000;
|
|
2136
|
+
return Number.isSafeInteger(ms) ? ms : null;
|
|
2137
|
+
}
|
|
2138
|
+
const parsed = Date.parse(value);
|
|
2139
|
+
return Number.isFinite(parsed) && parsed > wallNow ? parsed - wallNow : null;
|
|
2140
|
+
}
|
|
2141
|
+
function publicError(code, deliveryState, retryable, operationId, idempotencyKey, attemptCount, outcome, failureReason) {
|
|
2142
|
+
let causeCategory = null;
|
|
2143
|
+
if (outcome.kind === "failure")
|
|
2144
|
+
causeCategory = outcome.causeCategory ?? null;
|
|
2145
|
+
else if (outcome.proxyError)
|
|
2146
|
+
causeCategory = "HTTP_RUNTIME";
|
|
2147
|
+
const details = {
|
|
2148
|
+
errorCode: code,
|
|
2149
|
+
deliveryState,
|
|
2150
|
+
retryable,
|
|
2151
|
+
operationId,
|
|
2152
|
+
idempotencyKey,
|
|
2153
|
+
attemptCount,
|
|
2154
|
+
...responseDetails(outcome),
|
|
2155
|
+
failureReason,
|
|
2156
|
+
causeCategory,
|
|
2157
|
+
body: publishBody(outcome),
|
|
2158
|
+
};
|
|
2159
|
+
if (code === "CONFIGURATION")
|
|
2160
|
+
return new RepostConfigurationError(details);
|
|
2161
|
+
switch (code) {
|
|
2162
|
+
case "DNS":
|
|
2163
|
+
case "CONNECT":
|
|
2164
|
+
case "PROXY":
|
|
2165
|
+
case "TLS":
|
|
2166
|
+
case "IO":
|
|
2167
|
+
case "ATTEMPT_TIMEOUT":
|
|
2168
|
+
case "OPERATION_DEADLINE":
|
|
2169
|
+
case "CANCELLED":
|
|
2170
|
+
case "OVERLOADED":
|
|
2171
|
+
return new RepostTransportError(details);
|
|
2172
|
+
default:
|
|
2173
|
+
return new RepostPublishError(details);
|
|
2174
|
+
}
|
|
2175
|
+
}
|
|
2176
|
+
function publishBody(outcome) {
|
|
2177
|
+
if (outcome.kind !== "response" || outcome.bodyBytes.length === 0)
|
|
2178
|
+
return undefined;
|
|
2179
|
+
try {
|
|
2180
|
+
return JSON.parse(new TextDecoder("utf-8", { fatal: true }).decode(outcome.bodyBytes));
|
|
2181
|
+
}
|
|
2182
|
+
catch {
|
|
2183
|
+
return undefined;
|
|
2184
|
+
}
|
|
2185
|
+
}
|
|
2186
|
+
function cancelled(operationId, idempotencyKey, attemptCount, committed, outcome = null) {
|
|
2187
|
+
return new RepostTransportError({
|
|
2188
|
+
errorCode: "CANCELLED", deliveryState: committed ? "CANCELLED_UNKNOWN" : "NOT_SENT",
|
|
2189
|
+
operationId, idempotencyKey, attemptCount,
|
|
2190
|
+
...responseDetails(outcome),
|
|
2191
|
+
});
|
|
2192
|
+
}
|
|
2193
|
+
function closed(operationId, idempotencyKey, attemptCount, committed, outcome = null) {
|
|
2194
|
+
return new RepostTransportError({
|
|
2195
|
+
errorCode: "CLOSED", deliveryState: committed ? "CANCELLED_UNKNOWN" : "NOT_SENT",
|
|
2196
|
+
operationId, idempotencyKey, attemptCount,
|
|
2197
|
+
...responseDetails(outcome),
|
|
2198
|
+
});
|
|
2199
|
+
}
|
|
2200
|
+
function deadlineError(operationId, idempotencyKey, attemptCount, committed, outcome = null) {
|
|
2201
|
+
return new RepostTransportError({
|
|
2202
|
+
errorCode: "OPERATION_DEADLINE", deliveryState: committed ? "POSSIBLY_SENT" : "NOT_SENT",
|
|
2203
|
+
operationId, idempotencyKey, attemptCount,
|
|
2204
|
+
...responseDetails(outcome),
|
|
2205
|
+
});
|
|
2206
|
+
}
|
|
2207
|
+
function responseDetails(outcome) {
|
|
2208
|
+
if (!outcome) {
|
|
2209
|
+
return { httpStatus: null, compressedBytes: 0, decompressedBytes: 0, truncated: false, responseHeaderFields: 0, responseHeaderBytes: 0 };
|
|
2210
|
+
}
|
|
2211
|
+
const exposeHeaderLimit = outcome.kind === "response" && outcome.headerLimitExceeded;
|
|
2212
|
+
return {
|
|
2213
|
+
httpStatus: outcome.kind === "response" ? outcome.status : outcome.httpStatus ?? null,
|
|
2214
|
+
compressedBytes: outcome.compressedBytes ?? 0,
|
|
2215
|
+
decompressedBytes: outcome.decompressedBytes ?? 0,
|
|
2216
|
+
truncated: outcome.truncated ?? false,
|
|
2217
|
+
responseHeaderFields: exposeHeaderLimit ? outcome.responseHeaderFields ?? 0 : 0,
|
|
2218
|
+
responseHeaderBytes: exposeHeaderLimit ? outcome.responseHeaderBytes ?? 0 : 0,
|
|
2219
|
+
};
|
|
2220
|
+
}
|
|
2221
|
+
|
|
2222
|
+
class TelemetryInvoker {
|
|
2223
|
+
constructor(telemetry) {
|
|
2224
|
+
this.telemetry = telemetry;
|
|
2225
|
+
}
|
|
2226
|
+
capture() {
|
|
2227
|
+
if (!this.telemetry)
|
|
2228
|
+
return null;
|
|
2229
|
+
try {
|
|
2230
|
+
return this.telemetry.captureContext();
|
|
2231
|
+
}
|
|
2232
|
+
catch {
|
|
2233
|
+
return null;
|
|
2234
|
+
}
|
|
2235
|
+
}
|
|
2236
|
+
startOperation(parent, start) {
|
|
2237
|
+
if (!this.telemetry || parent === null)
|
|
2238
|
+
return null;
|
|
2239
|
+
try {
|
|
2240
|
+
return this.telemetry.startOperation(parent, start);
|
|
2241
|
+
}
|
|
2242
|
+
catch {
|
|
2243
|
+
return null;
|
|
2244
|
+
}
|
|
2245
|
+
}
|
|
2246
|
+
startAttempt(operation, start) {
|
|
2247
|
+
if (!operation)
|
|
2248
|
+
return null;
|
|
2249
|
+
try {
|
|
2250
|
+
return operation.startAttempt(start);
|
|
2251
|
+
}
|
|
2252
|
+
catch {
|
|
2253
|
+
return null;
|
|
2254
|
+
}
|
|
2255
|
+
}
|
|
2256
|
+
headers(attempt) {
|
|
2257
|
+
if (!attempt)
|
|
2258
|
+
return [];
|
|
2259
|
+
try {
|
|
2260
|
+
const headers = attempt.propagationHeaders();
|
|
2261
|
+
if (!headers?.traceparent)
|
|
2262
|
+
return [];
|
|
2263
|
+
return Object.freeze([
|
|
2264
|
+
Object.freeze(["traceparent", headers.traceparent]),
|
|
2265
|
+
...(headers.tracestate ? [Object.freeze(["tracestate", headers.tracestate])] : []),
|
|
2266
|
+
]);
|
|
2267
|
+
}
|
|
2268
|
+
catch {
|
|
2269
|
+
return [];
|
|
2270
|
+
}
|
|
2271
|
+
}
|
|
2272
|
+
endAttempt(attempt, end) {
|
|
2273
|
+
if (!attempt)
|
|
2274
|
+
return;
|
|
2275
|
+
try {
|
|
2276
|
+
attempt.end(end);
|
|
2277
|
+
}
|
|
2278
|
+
catch { /* Telemetry must not affect delivery. */ }
|
|
2279
|
+
}
|
|
2280
|
+
endOperation(operation, end) {
|
|
2281
|
+
if (!operation)
|
|
2282
|
+
return;
|
|
2283
|
+
try {
|
|
2284
|
+
operation.end(end);
|
|
2285
|
+
}
|
|
2286
|
+
catch { /* Telemetry must not affect delivery. */ }
|
|
2287
|
+
}
|
|
2288
|
+
}
|
|
2289
|
+
|
|
2290
|
+
const REQUEST_LIMIT_BYTES = 1048576;
|
|
2291
|
+
const encoder = new TextEncoder();
|
|
2292
|
+
function createSendOperation(config, schema, state) {
|
|
2293
|
+
const ownsTransport = config.transport === undefined;
|
|
2294
|
+
const transport = config.transport ?? resolveDefaultTransport(config.httpTransportOptions);
|
|
2295
|
+
const observers = new ObserverDispatcher(config.observer, state);
|
|
2296
|
+
const telemetry = new TelemetryInvoker(config.telemetry);
|
|
2297
|
+
let transportCloseStarted = false;
|
|
2298
|
+
return {
|
|
2299
|
+
send: (event, input) => createOperationPromise(config, schema, state, transport, observers, telemetry, event, input),
|
|
2300
|
+
close() {
|
|
2301
|
+
state.close();
|
|
2302
|
+
if (!ownsTransport || transportCloseStarted)
|
|
2303
|
+
return;
|
|
2304
|
+
transportCloseStarted = true;
|
|
2305
|
+
try {
|
|
2306
|
+
const closing = transport.close?.();
|
|
2307
|
+
if (closing)
|
|
2308
|
+
void Promise.resolve(closing).catch(() => undefined);
|
|
2309
|
+
}
|
|
2310
|
+
catch {
|
|
2311
|
+
// Runtime closure is final even when an owned transport cannot close cleanly.
|
|
2312
|
+
}
|
|
2313
|
+
},
|
|
2314
|
+
};
|
|
2315
|
+
}
|
|
2316
|
+
function createOperationPromise(config, schema, state, transport, observers, telemetry, event, input) {
|
|
2317
|
+
const cancellation = new AbortController();
|
|
2318
|
+
const signal = input.signal ? AbortSignal.any([input.signal, cancellation.signal]) : cancellation.signal;
|
|
2319
|
+
const metadata = { operationId: null, idempotencyKey: null, attemptCount: 0, httpStatus: null };
|
|
2320
|
+
const execution = send(config, schema, state, transport, observers, telemetry, event, { ...input, signal }, metadata);
|
|
2321
|
+
const outcome = execution.then((result) => Object.freeze({
|
|
2322
|
+
operationId: metadata.operationId,
|
|
2323
|
+
code: "OK",
|
|
2324
|
+
deliveryState: "ACCEPTED",
|
|
2325
|
+
attemptCount: metadata.attemptCount,
|
|
2326
|
+
httpStatus: metadata.httpStatus,
|
|
2327
|
+
idempotencyKey: metadata.idempotencyKey,
|
|
2328
|
+
result,
|
|
2329
|
+
error: null,
|
|
2330
|
+
}), (error) => {
|
|
2331
|
+
const failure = error instanceof RepostError ? error : null;
|
|
2332
|
+
return Object.freeze({
|
|
2333
|
+
operationId: failure?.operationId ?? null,
|
|
2334
|
+
code: failure?.errorCode ?? "IO",
|
|
2335
|
+
deliveryState: failure?.deliveryState ?? "NOT_SENT",
|
|
2336
|
+
attemptCount: failure?.attemptCount ?? 0,
|
|
2337
|
+
httpStatus: failure?.httpStatus ?? metadata.httpStatus,
|
|
2338
|
+
idempotencyKey: failure?.idempotencyKey ?? null,
|
|
2339
|
+
result: null,
|
|
2340
|
+
error: failure,
|
|
2341
|
+
});
|
|
2342
|
+
});
|
|
2343
|
+
const primary = execution.catch((error) => {
|
|
2344
|
+
if (error instanceof RepostError && error.errorCode === "CANCELLED" && signal.aborted)
|
|
2345
|
+
throw signal.reason;
|
|
2346
|
+
throw error;
|
|
2347
|
+
});
|
|
2348
|
+
Object.defineProperties(primary, {
|
|
2349
|
+
outcome: { value: outcome, enumerable: false, writable: false, configurable: false },
|
|
2350
|
+
cancel: {
|
|
2351
|
+
value: () => cancellation.abort(new DOMException("This operation was aborted", "AbortError")),
|
|
2352
|
+
enumerable: false,
|
|
2353
|
+
writable: false,
|
|
2354
|
+
configurable: false,
|
|
2355
|
+
},
|
|
2356
|
+
});
|
|
2357
|
+
return primary;
|
|
2358
|
+
}
|
|
2359
|
+
async function send(config, schema, state, transport, observers, telemetry, event, input, metadata) {
|
|
2360
|
+
const startedAt = config.monotonicClock();
|
|
2361
|
+
const deadline = saturatingDeadline(startedAt, config.operationTimeoutMs);
|
|
2362
|
+
const deadlineAuthority = operationDeadline(config.operationTimeoutMs);
|
|
2363
|
+
if (state.isClosing())
|
|
2364
|
+
throw closed(null, null, 0, false);
|
|
2365
|
+
const operationId = `op_${crypto.randomUUID()}`;
|
|
2366
|
+
metadata.operationId = operationId;
|
|
2367
|
+
observers.emit(observerEvent("operation.start", operationId, startedAt));
|
|
2368
|
+
const admission = state.admit();
|
|
2369
|
+
if (!admission) {
|
|
2370
|
+
if (state.isClosing())
|
|
2371
|
+
throw closed(null, null, 0, false);
|
|
2372
|
+
const error = new RepostTransportError({
|
|
2373
|
+
errorCode: "OVERLOADED", deliveryState: "NOT_SENT", operationId,
|
|
2374
|
+
});
|
|
2375
|
+
const endedAt = config.monotonicClock();
|
|
2376
|
+
observers.emit(observerEvent("operation.end", operationId, endedAt, {
|
|
2377
|
+
durationMs: Math.max(0, endedAt - startedAt),
|
|
2378
|
+
outcome: "FAILED",
|
|
2379
|
+
errorCode: "OVERLOADED",
|
|
2380
|
+
deliveryState: "NOT_SENT",
|
|
2381
|
+
}));
|
|
2382
|
+
throw error;
|
|
2383
|
+
}
|
|
2384
|
+
let idempotencyKey = null;
|
|
2385
|
+
let attemptCount = 0;
|
|
2386
|
+
let acceptancePossible = false;
|
|
2387
|
+
let lastOutcome = null;
|
|
2388
|
+
let terminal = null;
|
|
2389
|
+
const summaries = [];
|
|
2390
|
+
let telemetryOperation = null;
|
|
2391
|
+
try {
|
|
2392
|
+
const capturedContext = telemetry.capture();
|
|
2393
|
+
telemetryOperation = telemetry.startOperation(capturedContext, { startedAtMs: startedAt });
|
|
2394
|
+
let credential;
|
|
2395
|
+
try {
|
|
2396
|
+
credential = await interruptible(resolveCredential(config, operationId), [
|
|
2397
|
+
admission.signal,
|
|
2398
|
+
...(input.signal && !input.signal.aborted ? [input.signal] : []),
|
|
2399
|
+
deadlineAuthority.signal,
|
|
2400
|
+
]);
|
|
2401
|
+
}
|
|
2402
|
+
catch (error) {
|
|
2403
|
+
if (admission.signal.aborted)
|
|
2404
|
+
throw closed(operationId, null, 0, false);
|
|
2405
|
+
if (input.signal?.aborted)
|
|
2406
|
+
throw cancelled(operationId, null, 0, false);
|
|
2407
|
+
if (deadlineAuthority.signal.aborted)
|
|
2408
|
+
throw deadlineError(operationId, null, 0, false);
|
|
2409
|
+
throw error;
|
|
2410
|
+
}
|
|
2411
|
+
idempotencyKey = resolveIdempotencyKey(config, input.idempotencyKey, operationId);
|
|
2412
|
+
metadata.idempotencyKey = idempotencyKey;
|
|
2413
|
+
const resolved = resolveGenerators(config.generators);
|
|
2414
|
+
const operationNow = resolved.now();
|
|
2415
|
+
const envelope = {
|
|
2416
|
+
type: event.type,
|
|
2417
|
+
timestamp: operationNow,
|
|
2418
|
+
data: serializeForSend(schema, event, input.data, { ...resolved, now: () => operationNow }, operationId, idempotencyKey),
|
|
2419
|
+
};
|
|
2420
|
+
let bodyBytes;
|
|
2421
|
+
try {
|
|
2422
|
+
bodyBytes = encoder.encode(JSON.stringify({
|
|
2423
|
+
type: envelope.type,
|
|
2424
|
+
customerId: input.customerId,
|
|
2425
|
+
timestamp: envelope.timestamp,
|
|
2426
|
+
data: envelope.data,
|
|
2427
|
+
}));
|
|
2428
|
+
}
|
|
2429
|
+
catch {
|
|
2430
|
+
throw new RepostSerializationError({
|
|
2431
|
+
errorCode: "SERIALIZATION", deliveryState: "NOT_SENT", operationId, idempotencyKey,
|
|
2432
|
+
});
|
|
2433
|
+
}
|
|
2434
|
+
if (bodyBytes.length > REQUEST_LIMIT_BYTES) {
|
|
2435
|
+
throw new RepostSerializationError({
|
|
2436
|
+
errorCode: "REQUEST_TOO_LARGE", deliveryState: "NOT_SENT", operationId, idempotencyKey,
|
|
2437
|
+
});
|
|
2438
|
+
}
|
|
2439
|
+
admission.retainSerializedRequest(bodyBytes.length);
|
|
2440
|
+
if (input.signal?.aborted)
|
|
2441
|
+
throw cancelled(operationId, idempotencyKey, 0, false);
|
|
2442
|
+
for (let attemptNumber = 1; attemptNumber <= config.maxAttempts; attemptNumber += 1) {
|
|
2443
|
+
const remaining = deadline - config.monotonicClock();
|
|
2444
|
+
if (remaining <= 0)
|
|
2445
|
+
throw deadlineError(operationId, idempotencyKey, attemptCount, acceptancePossible, lastOutcome);
|
|
2446
|
+
attemptCount = attemptNumber;
|
|
2447
|
+
metadata.attemptCount = attemptNumber;
|
|
2448
|
+
let committed = false;
|
|
2449
|
+
const attemptTimeoutMs = Math.min(config.attemptTimeoutMs, remaining);
|
|
2450
|
+
const timeoutSignal = AbortSignal.timeout(Math.max(1, Math.ceil(attemptTimeoutMs)));
|
|
2451
|
+
const signal = AbortSignal.any([
|
|
2452
|
+
admission.signal,
|
|
2453
|
+
deadlineAuthority.signal,
|
|
2454
|
+
timeoutSignal,
|
|
2455
|
+
...(input.signal ? [input.signal] : []),
|
|
2456
|
+
]);
|
|
2457
|
+
const headers = [
|
|
2458
|
+
["authorization", `Bearer ${credential}`],
|
|
2459
|
+
["content-type", "application/json"],
|
|
2460
|
+
["accept-encoding", "gzip"],
|
|
2461
|
+
["user-agent", config.userAgent],
|
|
2462
|
+
["idempotency-key", idempotencyKey],
|
|
2463
|
+
];
|
|
2464
|
+
const attemptStartedAt = config.monotonicClock();
|
|
2465
|
+
const telemetryAttempt = telemetry.startAttempt(telemetryOperation, { startedAtMs: attemptStartedAt, attemptNumber });
|
|
2466
|
+
headers.push(...telemetry.headers(telemetryAttempt));
|
|
2467
|
+
const request = {
|
|
2468
|
+
url: endpointUrl(config.apiUrl),
|
|
2469
|
+
headers,
|
|
2470
|
+
bodyBytes,
|
|
2471
|
+
attemptNumber,
|
|
2472
|
+
connectTimeoutMs: Math.min(config.connectTimeoutMs, attemptTimeoutMs),
|
|
2473
|
+
attemptTimeoutMs,
|
|
2474
|
+
signal,
|
|
2475
|
+
commitTracker: {
|
|
2476
|
+
get committed() { return committed; },
|
|
2477
|
+
markCommitted() { committed = true; },
|
|
2478
|
+
},
|
|
2479
|
+
};
|
|
2480
|
+
observers.emit(observerEvent("attempt.start", operationId, attemptStartedAt, { attemptNumber }));
|
|
2481
|
+
const outcome = await invokeTransport(transport, request, input.signal, timeoutSignal, config.transport !== undefined);
|
|
2482
|
+
lastOutcome = outcome;
|
|
2483
|
+
if (outcome.kind === "response")
|
|
2484
|
+
metadata.httpStatus = outcome.status;
|
|
2485
|
+
else if (outcome.httpStatus !== undefined && outcome.httpStatus !== null)
|
|
2486
|
+
metadata.httpStatus = outcome.httpStatus;
|
|
2487
|
+
if (outcome.kind === "response" && outcome.headerLimitExceeded)
|
|
2488
|
+
state.responseHeaderLimitFailed();
|
|
2489
|
+
if (admission.signal.aborted) {
|
|
2490
|
+
closeResponse(outcome, state);
|
|
2491
|
+
const error = closed(operationId, idempotencyKey, attemptCount, committed || acceptancePossible, outcome);
|
|
2492
|
+
const endedAt = config.monotonicClock();
|
|
2493
|
+
const summary = attemptSummary(attemptNumber, "CLOSED", error, outcome, endedAt - attemptStartedAt);
|
|
2494
|
+
telemetry.endAttempt(telemetryAttempt, telemetryAttemptEnd(summary));
|
|
2495
|
+
summaries.push(summary);
|
|
2496
|
+
observers.emit(observerEvent("attempt.end", operationId, endedAt, summary));
|
|
2497
|
+
throw error;
|
|
2498
|
+
}
|
|
2499
|
+
if (input.signal?.aborted) {
|
|
2500
|
+
closeResponse(outcome, state);
|
|
2501
|
+
const error = cancelled(operationId, idempotencyKey, attemptCount, committed || acceptancePossible, outcome);
|
|
2502
|
+
const endedAt = config.monotonicClock();
|
|
2503
|
+
const summary = attemptSummary(attemptNumber, "CANCELLED", error, outcome, endedAt - attemptStartedAt);
|
|
2504
|
+
telemetry.endAttempt(telemetryAttempt, telemetryAttemptEnd(summary));
|
|
2505
|
+
summaries.push(summary);
|
|
2506
|
+
observers.emit(observerEvent("attempt.end", operationId, endedAt, summary));
|
|
2507
|
+
throw error;
|
|
2508
|
+
}
|
|
2509
|
+
if (deadlineAuthority.signal.aborted || config.monotonicClock() >= deadline) {
|
|
2510
|
+
closeResponse(outcome, state);
|
|
2511
|
+
const error = deadlineError(operationId, idempotencyKey, attemptCount, committed || acceptancePossible, outcome);
|
|
2512
|
+
const endedAt = config.monotonicClock();
|
|
2513
|
+
const summary = attemptSummary(attemptNumber, "FAILED", error, outcome, endedAt - attemptStartedAt);
|
|
2514
|
+
telemetry.endAttempt(telemetryAttempt, telemetryAttemptEnd(summary));
|
|
2515
|
+
summaries.push(summary);
|
|
2516
|
+
observers.emit(observerEvent("attempt.end", operationId, endedAt, summary));
|
|
2517
|
+
throw error;
|
|
2518
|
+
}
|
|
2519
|
+
let classifiedOutcome = outcome;
|
|
2520
|
+
if (outcome.kind === "response" && outcome.status >= 200 && outcome.status <= 299) {
|
|
2521
|
+
const result = validateAcceptedResponse(outcome, envelope, input.customerId);
|
|
2522
|
+
if (result === "LIMIT_EXCEEDED") {
|
|
2523
|
+
classifiedOutcome = { ...outcome, limitExceeded: true };
|
|
2524
|
+
}
|
|
2525
|
+
else if (result) {
|
|
2526
|
+
const endedAt = config.monotonicClock();
|
|
2527
|
+
const summary = attemptSummary(attemptNumber, "ACCEPTED", null, outcome, endedAt - attemptStartedAt);
|
|
2528
|
+
telemetry.endAttempt(telemetryAttempt, telemetryAttemptEnd(summary));
|
|
2529
|
+
summaries.push(summary);
|
|
2530
|
+
observers.emit(observerEvent("attempt.end", operationId, endedAt, summary));
|
|
2531
|
+
closeResponse(outcome, state);
|
|
2532
|
+
terminal = { outcome: "ACCEPTED", error: null, deliveryState: "ACCEPTED" };
|
|
2533
|
+
return result;
|
|
2534
|
+
}
|
|
2535
|
+
}
|
|
2536
|
+
const failure = classifyOutcome(classifiedOutcome, acceptancePossible);
|
|
2537
|
+
acceptancePossible || (acceptancePossible = failure.acceptancePossible);
|
|
2538
|
+
const attemptError = publicError(failure.code, failure.deliveryState, failure.retryable, operationId, idempotencyKey, attemptNumber, classifiedOutcome, failure.reason);
|
|
2539
|
+
const attemptEndedAt = config.monotonicClock();
|
|
2540
|
+
let attemptObserverOutcome = "FAILED";
|
|
2541
|
+
if (failure.retryable)
|
|
2542
|
+
attemptObserverOutcome = "RETRYABLE_FAILURE";
|
|
2543
|
+
else if (failure.deliveryState === "REJECTED")
|
|
2544
|
+
attemptObserverOutcome = "REJECTED";
|
|
2545
|
+
const summary = attemptSummary(attemptNumber, attemptObserverOutcome, attemptError, classifiedOutcome, attemptEndedAt - attemptStartedAt);
|
|
2546
|
+
telemetry.endAttempt(telemetryAttempt, telemetryAttemptEnd(summary));
|
|
2547
|
+
summaries.push(summary);
|
|
2548
|
+
observers.emit(observerEvent("attempt.end", operationId, attemptEndedAt, summary));
|
|
2549
|
+
closeResponse(classifiedOutcome, state);
|
|
2550
|
+
if (!failure.retryable || attemptNumber === config.maxAttempts) {
|
|
2551
|
+
if (failure.deliveryState === "REJECTED" && acceptancePossible) {
|
|
2552
|
+
throw publicError(failure.code, "POSSIBLY_SENT", failure.retryable, operationId, idempotencyKey, attemptNumber, classifiedOutcome, failure.reason);
|
|
2553
|
+
}
|
|
2554
|
+
throw attemptError;
|
|
2555
|
+
}
|
|
2556
|
+
const now = config.monotonicClock();
|
|
2557
|
+
const retryRemaining = deadline - now;
|
|
2558
|
+
if (retryRemaining <= 0)
|
|
2559
|
+
throw deadlineError(operationId, idempotencyKey, attemptNumber, acceptancePossible, lastOutcome);
|
|
2560
|
+
const exponential = Math.min(config.retryMaxDelayMs, config.retryBaseDelayMs * 2 ** Math.min(attemptNumber - 1, 52));
|
|
2561
|
+
const cap = Math.max(0, Math.min(exponential, retryRemaining));
|
|
2562
|
+
let jitter;
|
|
2563
|
+
try {
|
|
2564
|
+
jitter = config.retryEntropy.nextInt(Math.floor(cap) + 1);
|
|
2565
|
+
}
|
|
2566
|
+
catch {
|
|
2567
|
+
throw new RepostConfigurationError({
|
|
2568
|
+
errorCode: "CONFIGURATION",
|
|
2569
|
+
deliveryState: acceptancePossible ? "POSSIBLY_SENT" : "NOT_SENT",
|
|
2570
|
+
operationId,
|
|
2571
|
+
idempotencyKey,
|
|
2572
|
+
attemptCount,
|
|
2573
|
+
causeCategory: "RETRY_ENTROPY",
|
|
2574
|
+
configurationIssues: [{ code: "INVALID_VALUE", optionKeys: ["RETRY_ENTROPY"] }],
|
|
2575
|
+
...responseDetails(lastOutcome),
|
|
2576
|
+
});
|
|
2577
|
+
}
|
|
2578
|
+
if (!Number.isInteger(jitter) || jitter < 0 || jitter > cap) {
|
|
2579
|
+
throw new RepostConfigurationError({
|
|
2580
|
+
errorCode: "CONFIGURATION",
|
|
2581
|
+
deliveryState: acceptancePossible ? "POSSIBLY_SENT" : "NOT_SENT",
|
|
2582
|
+
operationId,
|
|
2583
|
+
idempotencyKey,
|
|
2584
|
+
attemptCount,
|
|
2585
|
+
configurationIssues: [{ code: "INVALID_VALUE", optionKeys: ["RETRY_ENTROPY"] }],
|
|
2586
|
+
...responseDetails(lastOutcome),
|
|
2587
|
+
});
|
|
2588
|
+
}
|
|
2589
|
+
let retryAfter = null;
|
|
2590
|
+
if (classifiedOutcome.kind === "response") {
|
|
2591
|
+
retryAfter = classifiedOutcome.retryAfterDelayMs
|
|
2592
|
+
?? parseRetryAfter(classifiedOutcome.headers, config.wallClock());
|
|
2593
|
+
}
|
|
2594
|
+
const delay = retryAfter === null ? jitter : Math.max(jitter, Math.min(retryAfter, 60000, retryRemaining));
|
|
2595
|
+
observers.emit(observerEvent("retry.delay", operationId, config.monotonicClock(), {
|
|
2596
|
+
attemptNumber: attemptNumber + 1,
|
|
2597
|
+
retryDelayMs: delay,
|
|
2598
|
+
outcome: "RETRYABLE_FAILURE",
|
|
2599
|
+
errorCode: failure.code,
|
|
2600
|
+
deliveryState: failure.deliveryState,
|
|
2601
|
+
httpStatusClass: classifiedOutcome.kind === "response" ? statusClass(classifiedOutcome.status) : null,
|
|
2602
|
+
}));
|
|
2603
|
+
try {
|
|
2604
|
+
const sleepSignal = AbortSignal.any([
|
|
2605
|
+
admission.signal,
|
|
2606
|
+
deadlineAuthority.signal,
|
|
2607
|
+
...(input.signal ? [input.signal] : []),
|
|
2608
|
+
]);
|
|
2609
|
+
await config.scheduler.sleep(delay, sleepSignal);
|
|
2610
|
+
}
|
|
2611
|
+
catch {
|
|
2612
|
+
if (admission.signal.aborted)
|
|
2613
|
+
throw closed(operationId, idempotencyKey, attemptCount, acceptancePossible, lastOutcome);
|
|
2614
|
+
if (input.signal?.aborted)
|
|
2615
|
+
throw cancelled(operationId, idempotencyKey, attemptCount, acceptancePossible, lastOutcome);
|
|
2616
|
+
if (deadlineAuthority.signal.aborted || config.monotonicClock() >= deadline) {
|
|
2617
|
+
throw deadlineError(operationId, idempotencyKey, attemptCount, acceptancePossible, lastOutcome);
|
|
2618
|
+
}
|
|
2619
|
+
throw new RepostTransportError({
|
|
2620
|
+
errorCode: "IO",
|
|
2621
|
+
deliveryState: acceptancePossible ? "POSSIBLY_SENT" : "NOT_SENT",
|
|
2622
|
+
operationId,
|
|
2623
|
+
idempotencyKey,
|
|
2624
|
+
attemptCount,
|
|
2625
|
+
causeCategory: "UNKNOWN",
|
|
2626
|
+
...responseDetails(lastOutcome),
|
|
2627
|
+
});
|
|
2628
|
+
}
|
|
2629
|
+
}
|
|
2630
|
+
throw deadlineError(operationId, idempotencyKey, attemptCount, acceptancePossible, lastOutcome);
|
|
2631
|
+
}
|
|
2632
|
+
catch (error) {
|
|
2633
|
+
const failure = error instanceof RepostError
|
|
2634
|
+
? error
|
|
2635
|
+
: new RepostTransportError({
|
|
2636
|
+
errorCode: "IO", deliveryState: acceptancePossible ? "POSSIBLY_SENT" : "NOT_SENT",
|
|
2637
|
+
operationId, idempotencyKey, attemptCount, causeCategory: "UNKNOWN",
|
|
2638
|
+
});
|
|
2639
|
+
let terminalOutcome = "FAILED";
|
|
2640
|
+
if (failure.errorCode === "CANCELLED")
|
|
2641
|
+
terminalOutcome = "CANCELLED";
|
|
2642
|
+
else if (failure.deliveryState === "REJECTED")
|
|
2643
|
+
terminalOutcome = "REJECTED";
|
|
2644
|
+
terminal = {
|
|
2645
|
+
outcome: terminalOutcome,
|
|
2646
|
+
error: failure,
|
|
2647
|
+
deliveryState: failure.deliveryState,
|
|
2648
|
+
};
|
|
2649
|
+
if (failure.errorCode === "CANCELLED") {
|
|
2650
|
+
observers.emit(observerEvent("operation.cancel", operationId, config.monotonicClock(), {
|
|
2651
|
+
attemptNumber: attemptCount || null,
|
|
2652
|
+
outcome: "CANCELLED",
|
|
2653
|
+
errorCode: "CANCELLED",
|
|
2654
|
+
deliveryState: failure.deliveryState,
|
|
2655
|
+
}));
|
|
2656
|
+
}
|
|
2657
|
+
throw failure;
|
|
2658
|
+
}
|
|
2659
|
+
finally {
|
|
2660
|
+
deadlineAuthority.clear();
|
|
2661
|
+
admission.release();
|
|
2662
|
+
if (terminal) {
|
|
2663
|
+
const endedAt = config.monotonicClock();
|
|
2664
|
+
let terminalHttpStatusClass = null;
|
|
2665
|
+
if (terminal.error?.httpStatus)
|
|
2666
|
+
terminalHttpStatusClass = statusClass(terminal.error.httpStatus);
|
|
2667
|
+
else if (terminal.outcome === "ACCEPTED")
|
|
2668
|
+
terminalHttpStatusClass = "SUCCESS";
|
|
2669
|
+
telemetry.endOperation(telemetryOperation, {
|
|
2670
|
+
outcome: terminal.outcome,
|
|
2671
|
+
errorCode: terminal.error?.errorCode ?? null,
|
|
2672
|
+
durationMs: Math.max(0, endedAt - startedAt),
|
|
2673
|
+
});
|
|
2674
|
+
observers.emit(observerEvent("operation.end", operationId, endedAt, {
|
|
2675
|
+
durationMs: Math.max(0, endedAt - startedAt),
|
|
2676
|
+
outcome: terminal.outcome,
|
|
2677
|
+
errorCode: terminal.error?.errorCode ?? null,
|
|
2678
|
+
deliveryState: terminal.deliveryState,
|
|
2679
|
+
httpStatusClass: terminalHttpStatusClass,
|
|
2680
|
+
operationStartedAtMs: startedAt,
|
|
2681
|
+
operationEndedAtMs: endedAt,
|
|
2682
|
+
attemptSummaries: Object.freeze([...summaries]),
|
|
2683
|
+
}));
|
|
2684
|
+
}
|
|
2685
|
+
}
|
|
2686
|
+
}
|
|
2687
|
+
async function invokeTransport(transport, request, callerSignal, timeoutSignal, customTransport) {
|
|
2688
|
+
try {
|
|
2689
|
+
const outcome = await Promise.race([
|
|
2690
|
+
transport.send(request),
|
|
2691
|
+
new Promise((_, reject) => request.signal.addEventListener("abort", () => reject(request.signal.reason), { once: true })),
|
|
2692
|
+
]);
|
|
2693
|
+
if (!outcome || (outcome.kind !== "response" && outcome.kind !== "failure"))
|
|
2694
|
+
throw new TypeError("invalid custom transport outcome");
|
|
2695
|
+
return outcome;
|
|
2696
|
+
}
|
|
2697
|
+
catch {
|
|
2698
|
+
if (callerSignal?.aborted) {
|
|
2699
|
+
return { kind: "failure", code: "IO", reason: "UNKNOWN", committed: request.commitTracker.committed };
|
|
2700
|
+
}
|
|
2701
|
+
if (timeoutSignal.aborted) {
|
|
2702
|
+
return { kind: "failure", code: "ATTEMPT_TIMEOUT", reason: "UNKNOWN", committed: request.commitTracker.committed, causeCategory: "HTTP_RUNTIME" };
|
|
2703
|
+
}
|
|
2704
|
+
return {
|
|
2705
|
+
kind: "failure",
|
|
2706
|
+
code: "IO",
|
|
2707
|
+
reason: "UNKNOWN",
|
|
2708
|
+
committed: customTransport || request.commitTracker.committed,
|
|
2709
|
+
causeCategory: customTransport ? "CUSTOM_TRANSPORT" : "HTTP_RUNTIME",
|
|
2710
|
+
retryable: false,
|
|
2711
|
+
};
|
|
2712
|
+
}
|
|
2713
|
+
}
|
|
2714
|
+
function closeResponse(outcome, state) {
|
|
2715
|
+
if (outcome.kind !== "response" || !outcome.close)
|
|
2716
|
+
return;
|
|
2717
|
+
try {
|
|
2718
|
+
const closing = outcome.close();
|
|
2719
|
+
if (closing)
|
|
2720
|
+
void Promise.resolve(closing).catch(() => state.responseCloseFailed());
|
|
2721
|
+
}
|
|
2722
|
+
catch {
|
|
2723
|
+
state.responseCloseFailed();
|
|
2724
|
+
}
|
|
2725
|
+
}
|
|
2726
|
+
function saturatingDeadline(start, duration) {
|
|
2727
|
+
const deadline = start + duration;
|
|
2728
|
+
return Number.isFinite(deadline) ? Math.min(Number.MAX_SAFE_INTEGER, deadline) : Number.MAX_SAFE_INTEGER;
|
|
2729
|
+
}
|
|
2730
|
+
function operationDeadline(durationMs) {
|
|
2731
|
+
const controller = new AbortController();
|
|
2732
|
+
let timer;
|
|
2733
|
+
let remaining = durationMs;
|
|
2734
|
+
const arm = () => {
|
|
2735
|
+
const delay = Math.min(remaining, 2147483647);
|
|
2736
|
+
timer = setTimeout(() => {
|
|
2737
|
+
remaining -= delay;
|
|
2738
|
+
if (remaining <= 0)
|
|
2739
|
+
controller.abort();
|
|
2740
|
+
else
|
|
2741
|
+
arm();
|
|
2742
|
+
}, delay);
|
|
2743
|
+
};
|
|
2744
|
+
arm();
|
|
2745
|
+
return { signal: controller.signal, clear: () => clearTimeout(timer) };
|
|
2746
|
+
}
|
|
2747
|
+
function interruptible(work, signals) {
|
|
2748
|
+
return new Promise((resolve, reject) => {
|
|
2749
|
+
const abort = (signal) => {
|
|
2750
|
+
cleanup();
|
|
2751
|
+
reject(signal.reason);
|
|
2752
|
+
};
|
|
2753
|
+
const listeners = signals.map((signal) => [signal, () => abort(signal)]);
|
|
2754
|
+
const cleanup = () => listeners.forEach(([signal, listener]) => signal.removeEventListener("abort", listener));
|
|
2755
|
+
for (const [signal, listener] of listeners) {
|
|
2756
|
+
if (signal.aborted)
|
|
2757
|
+
return abort(signal);
|
|
2758
|
+
signal.addEventListener("abort", listener, { once: true });
|
|
2759
|
+
}
|
|
2760
|
+
work.then((value) => { cleanup(); resolve(value); }, (error) => { cleanup(); reject(error); });
|
|
2761
|
+
});
|
|
2762
|
+
}
|
|
2763
|
+
|
|
2764
|
+
const PORTABLE_OPERATION_WORKSPACE_BYTES = 2359296;
|
|
2765
|
+
const REQUEST_WORKSPACE_BYTES = 1048576;
|
|
2766
|
+
class RuntimeState {
|
|
2767
|
+
constructor(maxInFlightOperations, maxBufferedBytes) {
|
|
2768
|
+
this.maxInFlightOperations = maxInFlightOperations;
|
|
2769
|
+
this.maxBufferedBytes = maxBufferedBytes;
|
|
2770
|
+
this.inFlightOperations = 0;
|
|
2771
|
+
this.bufferedBytes = 0;
|
|
2772
|
+
this.concurrencyOverloadRejections = 0;
|
|
2773
|
+
this.requestByteOverloadRejections = 0;
|
|
2774
|
+
this.responseHeaderLimitFailures = 0;
|
|
2775
|
+
this.responseCloseFailures = 0;
|
|
2776
|
+
this.droppedObserverEvents = 0;
|
|
2777
|
+
this.observerFailures = 0;
|
|
2778
|
+
this.closing = false;
|
|
2779
|
+
this.closed = false;
|
|
2780
|
+
this.active = new Set();
|
|
2781
|
+
}
|
|
2782
|
+
admit() {
|
|
2783
|
+
if (this.closing)
|
|
2784
|
+
return null;
|
|
2785
|
+
if (this.inFlightOperations >= this.maxInFlightOperations) {
|
|
2786
|
+
this.concurrencyOverloadRejections = saturatingAdd(this.concurrencyOverloadRejections);
|
|
2787
|
+
return null;
|
|
2788
|
+
}
|
|
2789
|
+
if (this.bufferedBytes + PORTABLE_OPERATION_WORKSPACE_BYTES > this.maxBufferedBytes) {
|
|
2790
|
+
this.requestByteOverloadRejections = saturatingAdd(this.requestByteOverloadRejections);
|
|
2791
|
+
return null;
|
|
2792
|
+
}
|
|
2793
|
+
const controller = new AbortController();
|
|
2794
|
+
this.active.add(controller);
|
|
2795
|
+
this.inFlightOperations += 1;
|
|
2796
|
+
this.bufferedBytes += PORTABLE_OPERATION_WORKSPACE_BYTES;
|
|
2797
|
+
let retained = PORTABLE_OPERATION_WORKSPACE_BYTES;
|
|
2798
|
+
let released = false;
|
|
2799
|
+
return {
|
|
2800
|
+
signal: controller.signal,
|
|
2801
|
+
retainSerializedRequest: (bodyBytes) => {
|
|
2802
|
+
const releasedBytes = REQUEST_WORKSPACE_BYTES - bodyBytes;
|
|
2803
|
+
if (releasedBytes > 0) {
|
|
2804
|
+
retained -= releasedBytes;
|
|
2805
|
+
this.bufferedBytes -= releasedBytes;
|
|
2806
|
+
}
|
|
2807
|
+
},
|
|
2808
|
+
release: () => {
|
|
2809
|
+
if (released)
|
|
2810
|
+
return;
|
|
2811
|
+
released = true;
|
|
2812
|
+
this.inFlightOperations -= 1;
|
|
2813
|
+
this.bufferedBytes -= retained;
|
|
2814
|
+
this.active.delete(controller);
|
|
2815
|
+
if (this.closing && this.inFlightOperations === 0)
|
|
2816
|
+
this.closed = true;
|
|
2817
|
+
},
|
|
2818
|
+
};
|
|
2819
|
+
}
|
|
2820
|
+
isClosing() { return this.closing; }
|
|
2821
|
+
close() {
|
|
2822
|
+
if (this.closing)
|
|
2823
|
+
return;
|
|
2824
|
+
this.closing = true;
|
|
2825
|
+
for (const controller of this.active)
|
|
2826
|
+
controller.abort();
|
|
2827
|
+
if (this.inFlightOperations === 0)
|
|
2828
|
+
this.closed = true;
|
|
2829
|
+
}
|
|
2830
|
+
diagnostics() {
|
|
2831
|
+
return Object.freeze({
|
|
2832
|
+
inFlightOperations: this.inFlightOperations,
|
|
2833
|
+
bufferedBytes: this.bufferedBytes,
|
|
2834
|
+
concurrencyOverloadRejections: this.concurrencyOverloadRejections,
|
|
2835
|
+
requestByteOverloadRejections: this.requestByteOverloadRejections,
|
|
2836
|
+
responseByteOverloadRejections: 0,
|
|
2837
|
+
responseHeaderLimitFailures: this.responseHeaderLimitFailures,
|
|
2838
|
+
executorOverloadRejections: 0,
|
|
2839
|
+
schedulerOverloadRejections: 0,
|
|
2840
|
+
responseCloseFailures: this.responseCloseFailures,
|
|
2841
|
+
droppedObserverEvents: this.droppedObserverEvents,
|
|
2842
|
+
observerFailures: this.observerFailures,
|
|
2843
|
+
closed: this.closed,
|
|
2844
|
+
});
|
|
2845
|
+
}
|
|
2846
|
+
observerDropped() { this.droppedObserverEvents = saturatingAdd(this.droppedObserverEvents); }
|
|
2847
|
+
observerFailed() { this.observerFailures = saturatingAdd(this.observerFailures); }
|
|
2848
|
+
responseHeaderLimitFailed() { this.responseHeaderLimitFailures = saturatingAdd(this.responseHeaderLimitFailures); }
|
|
2849
|
+
responseCloseFailed() { this.responseCloseFailures = saturatingAdd(this.responseCloseFailures); }
|
|
2850
|
+
seedDiagnosticCounter(counter, value) {
|
|
2851
|
+
if (!Number.isSafeInteger(value) || value < 0)
|
|
2852
|
+
throw new TypeError("invalid diagnostics counter seed");
|
|
2853
|
+
if (counter !== "concurrencyOverloadRejections")
|
|
2854
|
+
throw new TypeError("invalid diagnostics counter");
|
|
2855
|
+
this.concurrencyOverloadRejections = value;
|
|
2856
|
+
}
|
|
2857
|
+
}
|
|
2858
|
+
function saturatingAdd(value) {
|
|
2859
|
+
return Math.min(Number.MAX_SAFE_INTEGER, value + 1);
|
|
2860
|
+
}
|
|
2861
|
+
|
|
2862
|
+
/**
|
|
2863
|
+
* The descriptor-format version this runtime implements. Generated clients
|
|
2864
|
+
* declare the version they were emitted for; [`buildWebhooks`] refuses a
|
|
2865
|
+
* mismatch at construction — never silently at send time. Bumped only on a
|
|
2866
|
+
* wire-breaking change to the descriptor contract (see
|
|
2867
|
+
* sdk/conformance/CONTRACT.md and the conformance-vector freeze policy).
|
|
2868
|
+
*/
|
|
2869
|
+
const DESCRIPTOR_FORMAT_VERSION = 2;
|
|
2870
|
+
/** Warn-once latch for pre-versioning generated packages. */
|
|
2871
|
+
let warnedPreVersioning = false;
|
|
2872
|
+
/**
|
|
2873
|
+
* No-network transport for tests: echoes the envelope identity as a typed
|
|
2874
|
+
* `SendResult` with a fixed stub message id.
|
|
2875
|
+
*/
|
|
2876
|
+
const stubTransport = {
|
|
2877
|
+
async send(request) {
|
|
2878
|
+
request.commitTracker.markCommitted();
|
|
2879
|
+
const sent = JSON.parse(new TextDecoder().decode(request.bodyBytes));
|
|
2880
|
+
const bodyBytes = new TextEncoder().encode(JSON.stringify({ id: "msg_stub", ...sent }));
|
|
2881
|
+
return {
|
|
2882
|
+
kind: "response",
|
|
2883
|
+
status: 202,
|
|
2884
|
+
headers: { "content-type": ["application/json"] },
|
|
2885
|
+
bodyBytes,
|
|
2886
|
+
compressedBytes: bodyBytes.length,
|
|
2887
|
+
decompressedBytes: bodyBytes.length,
|
|
2888
|
+
truncated: false,
|
|
2889
|
+
};
|
|
2890
|
+
},
|
|
2891
|
+
};
|
|
2892
|
+
/**
|
|
2893
|
+
* Build the webhooks method tree from the generated schema descriptor. The
|
|
2894
|
+
* generated client instantiates this as its typed `Webhooks` interface — the
|
|
2895
|
+
* tree shape is guaranteed by codegen, which emits interface and descriptors
|
|
2896
|
+
* from the same catalog.
|
|
2897
|
+
*/
|
|
2898
|
+
function buildWebhooks(options, schema) {
|
|
2899
|
+
return buildRuntime(options, schema).webhooks;
|
|
2900
|
+
}
|
|
2901
|
+
/** Build the generated webhooks tree and its credential-free diagnostics surface. */
|
|
2902
|
+
function buildClient(options, schema) {
|
|
2903
|
+
const runtime = buildRuntime(options, schema);
|
|
2904
|
+
return Object.freeze({
|
|
2905
|
+
webhooks: runtime.webhooks,
|
|
2906
|
+
diagnostics: () => runtime.state.diagnostics(),
|
|
2907
|
+
close: runtime.close,
|
|
2908
|
+
[Symbol.for("@repost/client diagnostics seed")]: (counter, value) => {
|
|
2909
|
+
runtime.state.seedDiagnosticCounter(counter, value);
|
|
2910
|
+
},
|
|
2911
|
+
});
|
|
2912
|
+
}
|
|
2913
|
+
function buildRuntime(options, schema) {
|
|
2914
|
+
assertDescriptorFormat(schema.descriptorFormatVersion);
|
|
2915
|
+
if (schema.descriptorFormatVersion === DESCRIPTOR_FORMAT_VERSION) {
|
|
2916
|
+
assertDescriptorShape(schema);
|
|
2917
|
+
}
|
|
2918
|
+
const snapshot = snapshotOptions(options);
|
|
2919
|
+
const state = new RuntimeState(snapshot.maxInFlightOperations, snapshot.maxBufferedBytes);
|
|
2920
|
+
const operations = createSendOperation(snapshot, schema, state);
|
|
2921
|
+
const tree = {};
|
|
2922
|
+
for (const [group, members] of Object.entries(schema.webhooks)) {
|
|
2923
|
+
const groupTree = {};
|
|
2924
|
+
for (const [member, event] of Object.entries(members)) {
|
|
2925
|
+
groupTree[member] = (input) => operations.send(event, input);
|
|
2926
|
+
}
|
|
2927
|
+
tree[group] = groupTree;
|
|
2928
|
+
}
|
|
2929
|
+
return { webhooks: tree, state, close: operations.close };
|
|
2930
|
+
}
|
|
2931
|
+
function assertDescriptorShape(schema) {
|
|
2932
|
+
validateModelDescriptors(schema.models, schema.enums);
|
|
2933
|
+
for (const group of Object.keys(schema.webhooks).sort(compareUnicodeScalarValues)) {
|
|
2934
|
+
const members = schema.webhooks[group];
|
|
2935
|
+
if (!members)
|
|
2936
|
+
continue;
|
|
2937
|
+
for (const member of Object.keys(members).sort(compareUnicodeScalarValues)) {
|
|
2938
|
+
const event = members[member];
|
|
2939
|
+
if (event && !Object.prototype.hasOwnProperty.call(schema.models, event.model)) {
|
|
2940
|
+
const path = `${appendPath(appendPath("$.webhooks", group), member)}.model`;
|
|
2941
|
+
throw new Error(`@repost/client: [INVALID_DESCRIPTOR_REFERENCE] ${path}: model descriptor '${event.model}' does not exist.`);
|
|
2942
|
+
}
|
|
2943
|
+
}
|
|
2944
|
+
}
|
|
2945
|
+
}
|
|
2946
|
+
/**
|
|
2947
|
+
* Refuse a generated client whose descriptor format this runtime does not
|
|
2948
|
+
* implement, with the concrete fix per direction. A package generated before
|
|
2949
|
+
* versioning existed declares nothing — accepted with a one-time warning for
|
|
2950
|
+
* one release.
|
|
2951
|
+
*/
|
|
2952
|
+
function assertDescriptorFormat(declared) {
|
|
2953
|
+
if (declared === DESCRIPTOR_FORMAT_VERSION) {
|
|
2954
|
+
return;
|
|
2955
|
+
}
|
|
2956
|
+
if (declared === undefined) {
|
|
2957
|
+
if (!warnedPreVersioning) {
|
|
2958
|
+
warnedPreVersioning = true;
|
|
2959
|
+
console.warn("@repost/client: this generated client predates descriptor-format versioning; regenerate it with `repost schema generate`. Support for unversioned clients will be removed in a future release.");
|
|
2960
|
+
}
|
|
2961
|
+
return;
|
|
2962
|
+
}
|
|
2963
|
+
throw new RepostDescriptorVersionError({ errorCode: "DESCRIPTOR_VERSION", deliveryState: "NOT_SENT" });
|
|
2964
|
+
}
|
|
2965
|
+
|
|
2966
|
+
export { DESCRIPTOR_FORMAT_VERSION as D, RepostPublishError as R, createFetchTransport as a, createHttpTransport as b, classifyNetworkFailure as c, createNodeTransport as d, errorCode as e, RepostConfigurationError as f, RepostDescriptorVersionError as g, httpTransport as h, RepostError as i, RepostSerializationError as j, RepostTransportError as k, RepostValidationError as l, errorCatalog as m, buildClient as n, buildWebhooks as o, stubTransport as p, serializeModel as s };
|
|
2967
|
+
//# sourceMappingURL=index-DRD5FBax.mjs.map
|