@easyslip/sdk 1.0.1 → 1.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +7 -0
- package/README.md +8 -6
- package/README.th.md +8 -6
- package/dist/cjs/index.js +2039 -54
- package/dist/cjs/models.d.ts +16 -7
- package/dist/cjs/resources/v1.d.ts +2 -0
- package/dist/cjs/resources/verify.d.ts +2 -0
- package/dist/cjs/version.d.ts +1 -1
- package/dist/esm/index.js +1997 -7
- package/dist/esm/models.d.ts +16 -7
- package/dist/esm/resources/v1.d.ts +2 -0
- package/dist/esm/resources/verify.d.ts +2 -0
- package/dist/esm/version.d.ts +1 -1
- package/package.json +12 -14
- package/dist/cjs/client.js +0 -150
- package/dist/cjs/core/call.js +0 -60
- package/dist/cjs/core/error-codes.js +0 -87
- package/dist/cjs/core/errors.js +0 -210
- package/dist/cjs/core/files.js +0 -131
- package/dist/cjs/core/http.js +0 -242
- package/dist/cjs/core/meta.js +0 -52
- package/dist/cjs/core/redact.js +0 -208
- package/dist/cjs/core/runtime.js +0 -86
- package/dist/cjs/core/settings.js +0 -22
- package/dist/cjs/core/sha256.js +0 -101
- package/dist/cjs/models.js +0 -234
- package/dist/cjs/resources/bank-accounts.js +0 -126
- package/dist/cjs/resources/banks.js +0 -22
- package/dist/cjs/resources/jobs.js +0 -177
- package/dist/cjs/resources/v1.js +0 -137
- package/dist/cjs/resources/verify.js +0 -105
- package/dist/cjs/version.js +0 -5
- package/dist/cjs/webhooks.js +0 -92
- package/dist/esm/client.js +0 -146
- package/dist/esm/core/call.js +0 -52
- package/dist/esm/core/error-codes.js +0 -84
- package/dist/esm/core/errors.js +0 -184
- package/dist/esm/core/files.js +0 -126
- package/dist/esm/core/http.js +0 -235
- package/dist/esm/core/meta.js +0 -45
- package/dist/esm/core/redact.js +0 -198
- package/dist/esm/core/runtime.js +0 -47
- package/dist/esm/core/settings.js +0 -19
- package/dist/esm/core/sha256.js +0 -96
- package/dist/esm/models.js +0 -228
- package/dist/esm/resources/bank-accounts.js +0 -122
- package/dist/esm/resources/banks.js +0 -18
- package/dist/esm/resources/jobs.js +0 -173
- package/dist/esm/resources/v1.js +0 -133
- package/dist/esm/resources/verify.js +0 -100
- package/dist/esm/version.js +0 -2
- package/dist/esm/webhooks.js +0 -86
package/dist/cjs/core/files.js
DELETED
|
@@ -1,131 +0,0 @@
|
|
|
1
|
-
"use strict";
|
|
2
|
-
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
-
exports.MAX_IMAGE_BYTES = void 0;
|
|
4
|
-
exports.sniffImageType = sniffImageType;
|
|
5
|
-
exports.prepareFile = prepareFile;
|
|
6
|
-
const errors_js_1 = require("./errors.js");
|
|
7
|
-
const runtime_js_1 = require("./runtime.js");
|
|
8
|
-
/** Largest image the API accepts, in bytes (4 MB). */
|
|
9
|
-
exports.MAX_IMAGE_BYTES = 4 * 1024 * 1024;
|
|
10
|
-
const types = [
|
|
11
|
-
{
|
|
12
|
-
type: 'image/jpeg',
|
|
13
|
-
ext: 'jpg',
|
|
14
|
-
test: (b) => b[0] === 0xff && b[1] === 0xd8 && b[2] === 0xff,
|
|
15
|
-
},
|
|
16
|
-
{
|
|
17
|
-
type: 'image/png',
|
|
18
|
-
ext: 'png',
|
|
19
|
-
test: (b) => b[0] === 0x89 && b[1] === 0x50 && b[2] === 0x4e && b[3] === 0x47,
|
|
20
|
-
},
|
|
21
|
-
{
|
|
22
|
-
type: 'image/gif',
|
|
23
|
-
ext: 'gif',
|
|
24
|
-
test: (b) => b[0] === 0x47 && b[1] === 0x49 && b[2] === 0x46 && b[3] === 0x38,
|
|
25
|
-
},
|
|
26
|
-
{
|
|
27
|
-
type: 'image/webp',
|
|
28
|
-
ext: 'webp',
|
|
29
|
-
test: (b) => ascii(b, 0, 4) === 'RIFF' && ascii(b, 8, 12) === 'WEBP' && b.length >= 12,
|
|
30
|
-
},
|
|
31
|
-
];
|
|
32
|
-
function ascii(bytes, start, end) {
|
|
33
|
-
return String.fromCharCode(...bytes.subarray(start, end));
|
|
34
|
-
}
|
|
35
|
-
/** Image type from the first bytes, or null when it is not JPEG, PNG, GIF or WebP. */
|
|
36
|
-
function sniffImageType(bytes) {
|
|
37
|
-
const hit = types.find((t) => t.test(bytes));
|
|
38
|
-
return hit ? { type: hit.type, ext: hit.ext } : null;
|
|
39
|
-
}
|
|
40
|
-
function tooLarge(size) {
|
|
41
|
-
return new errors_js_1.InputError('FILE_TOO_LARGE', `file is ${size} bytes; the API accepts at most ${exports.MAX_IMAGE_BYTES} bytes`);
|
|
42
|
-
}
|
|
43
|
-
async function collect(chunks, maxBytes) {
|
|
44
|
-
const parts = [];
|
|
45
|
-
let size = 0;
|
|
46
|
-
const encoder = new TextEncoder();
|
|
47
|
-
for await (const chunk of chunks) {
|
|
48
|
-
const part = typeof chunk === 'string' ? encoder.encode(chunk) : chunk;
|
|
49
|
-
size += part.byteLength;
|
|
50
|
-
if (size > maxBytes)
|
|
51
|
-
throw tooLarge(size);
|
|
52
|
-
parts.push(part);
|
|
53
|
-
}
|
|
54
|
-
const out = new Uint8Array(size);
|
|
55
|
-
let offset = 0;
|
|
56
|
-
for (const part of parts) {
|
|
57
|
-
out.set(part, offset);
|
|
58
|
-
offset += part.byteLength;
|
|
59
|
-
}
|
|
60
|
-
return out;
|
|
61
|
-
}
|
|
62
|
-
async function* readStream(stream) {
|
|
63
|
-
const reader = stream.getReader();
|
|
64
|
-
try {
|
|
65
|
-
while (true) {
|
|
66
|
-
const { done, value } = await reader.read();
|
|
67
|
-
if (done)
|
|
68
|
-
return;
|
|
69
|
-
yield value;
|
|
70
|
-
}
|
|
71
|
-
}
|
|
72
|
-
finally {
|
|
73
|
-
reader.releaseLock();
|
|
74
|
-
}
|
|
75
|
-
}
|
|
76
|
-
async function readPath(path, maxBytes) {
|
|
77
|
-
const fs = await (0, runtime_js_1.loadFs)();
|
|
78
|
-
if (!fs) {
|
|
79
|
-
throw new errors_js_1.InputError('FILE_NOT_READABLE', 'file paths need a runtime with a file system; pass bytes, a Blob or a stream');
|
|
80
|
-
}
|
|
81
|
-
let info;
|
|
82
|
-
try {
|
|
83
|
-
info = await fs.stat(path);
|
|
84
|
-
}
|
|
85
|
-
catch (cause) {
|
|
86
|
-
throw new errors_js_1.InputError('FILE_NOT_READABLE', `cannot read ${String(path)}`, { cause });
|
|
87
|
-
}
|
|
88
|
-
if (!info.isFile())
|
|
89
|
-
throw new errors_js_1.InputError('FILE_NOT_READABLE', `not a file: ${String(path)}`);
|
|
90
|
-
if (info.size > maxBytes)
|
|
91
|
-
throw tooLarge(info.size);
|
|
92
|
-
try {
|
|
93
|
-
return await fs.readFile(path);
|
|
94
|
-
}
|
|
95
|
-
catch (cause) {
|
|
96
|
-
throw new errors_js_1.InputError('FILE_NOT_READABLE', `cannot read ${String(path)}`, { cause });
|
|
97
|
-
}
|
|
98
|
-
}
|
|
99
|
-
async function readBytes(input, maxBytes) {
|
|
100
|
-
if (typeof input === 'string' || input instanceof URL)
|
|
101
|
-
return readPath(input, maxBytes);
|
|
102
|
-
if (input instanceof Uint8Array)
|
|
103
|
-
return input;
|
|
104
|
-
if (input instanceof ArrayBuffer)
|
|
105
|
-
return new Uint8Array(input);
|
|
106
|
-
if (typeof Blob !== 'undefined' && input instanceof Blob) {
|
|
107
|
-
if (input.size > maxBytes)
|
|
108
|
-
throw tooLarge(input.size);
|
|
109
|
-
return new Uint8Array(await input.arrayBuffer());
|
|
110
|
-
}
|
|
111
|
-
if (typeof ReadableStream !== 'undefined' && input instanceof ReadableStream) {
|
|
112
|
-
return collect(readStream(input), maxBytes);
|
|
113
|
-
}
|
|
114
|
-
if (input && typeof input[Symbol.asyncIterator] === 'function') {
|
|
115
|
-
return collect(input, maxBytes);
|
|
116
|
-
}
|
|
117
|
-
throw new errors_js_1.InputError('INVALID_ARGUMENT', 'file must be a path, URL, Uint8Array, ArrayBuffer, Blob or stream');
|
|
118
|
-
}
|
|
119
|
-
/** Reads an image input, checks its size and type, and names it `slip.<ext>`. */
|
|
120
|
-
async function prepareFile(input, maxBytes = exports.MAX_IMAGE_BYTES) {
|
|
121
|
-
const raw = await readBytes(input, maxBytes);
|
|
122
|
-
if (raw.byteLength === 0)
|
|
123
|
-
throw new errors_js_1.InputError('EMPTY_FILE', 'file is empty');
|
|
124
|
-
if (raw.byteLength > maxBytes)
|
|
125
|
-
throw tooLarge(raw.byteLength);
|
|
126
|
-
const kind = sniffImageType(raw);
|
|
127
|
-
if (!kind) {
|
|
128
|
-
throw new errors_js_1.InputError('UNSUPPORTED_FILE_TYPE', 'file is not a JPEG, PNG, GIF or WebP image');
|
|
129
|
-
}
|
|
130
|
-
return { bytes: new Uint8Array(raw), contentType: kind.type, filename: `slip.${kind.ext}` };
|
|
131
|
-
}
|
package/dist/cjs/core/http.js
DELETED
|
@@ -1,242 +0,0 @@
|
|
|
1
|
-
"use strict";
|
|
2
|
-
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
-
exports.Transport = void 0;
|
|
4
|
-
exports.isConnectFailure = isConnectFailure;
|
|
5
|
-
exports.backoffDelay = backoffDelay;
|
|
6
|
-
exports.decodeResponse = decodeResponse;
|
|
7
|
-
const models_js_1 = require("../models.js");
|
|
8
|
-
const error_codes_js_1 = require("./error-codes.js");
|
|
9
|
-
const errors_js_1 = require("./errors.js");
|
|
10
|
-
const meta_js_1 = require("./meta.js");
|
|
11
|
-
const redact_js_1 = require("./redact.js");
|
|
12
|
-
const RETRY_STATUS = new Set([500, 502, 503, 504]);
|
|
13
|
-
const MAX_RETRY_AFTER_SECONDS = 60;
|
|
14
|
-
// Error codes that mean the request bytes never left this machine.
|
|
15
|
-
const CONNECT_CODES = new Set([
|
|
16
|
-
'ECONNREFUSED',
|
|
17
|
-
'ENOTFOUND',
|
|
18
|
-
'EAI_AGAIN',
|
|
19
|
-
'EAI_NONAME',
|
|
20
|
-
'EAI_FAIL',
|
|
21
|
-
'EHOSTUNREACH',
|
|
22
|
-
'ENETUNREACH',
|
|
23
|
-
'EADDRNOTAVAIL',
|
|
24
|
-
'UND_ERR_CONNECT_TIMEOUT',
|
|
25
|
-
'ConnectionRefused',
|
|
26
|
-
'FailedToOpenSocket',
|
|
27
|
-
'DNSException',
|
|
28
|
-
]);
|
|
29
|
-
function errorCodesOf(error, depth = 0) {
|
|
30
|
-
if (!error || typeof error !== 'object' || depth > 3)
|
|
31
|
-
return [];
|
|
32
|
-
const e = error;
|
|
33
|
-
const out = typeof e.code === 'string' ? [e.code] : [];
|
|
34
|
-
out.push(...errorCodesOf(e.cause, depth + 1));
|
|
35
|
-
if (Array.isArray(e.errors))
|
|
36
|
-
for (const inner of e.errors)
|
|
37
|
-
out.push(...errorCodesOf(inner, depth + 1));
|
|
38
|
-
return out;
|
|
39
|
-
}
|
|
40
|
-
/** True when a fetch failure happened before the request was sent (DNS, connect, TLS). */
|
|
41
|
-
function isConnectFailure(error) {
|
|
42
|
-
return errorCodesOf(error).some((code) => CONNECT_CODES.has(code) ||
|
|
43
|
-
code.startsWith('ERR_TLS_') ||
|
|
44
|
-
code.startsWith('ERR_SSL_') ||
|
|
45
|
-
code.includes('CERT') ||
|
|
46
|
-
code.startsWith('UNABLE_TO_'));
|
|
47
|
-
}
|
|
48
|
-
/** Backoff before retry number `attempt` (0-based), in milliseconds. */
|
|
49
|
-
function backoffDelay(attempt, random = Math.random) {
|
|
50
|
-
const base = Math.min(8000, 500 * 2 ** attempt);
|
|
51
|
-
return base * (0.5 + random() * 0.5);
|
|
52
|
-
}
|
|
53
|
-
function parseJson(text) {
|
|
54
|
-
if (!text)
|
|
55
|
-
return undefined;
|
|
56
|
-
try {
|
|
57
|
-
return JSON.parse(text);
|
|
58
|
-
}
|
|
59
|
-
catch {
|
|
60
|
-
return undefined;
|
|
61
|
-
}
|
|
62
|
-
}
|
|
63
|
-
function isObject(value) {
|
|
64
|
-
return value !== null && typeof value === 'object' && !Array.isArray(value);
|
|
65
|
-
}
|
|
66
|
-
function errorFromResponse(api, status, headers, text, parsed, duplicateSlip, redact) {
|
|
67
|
-
// Every field below is read from the redacted body.
|
|
68
|
-
const { rawBody, body } = (0, redact_js_1.redactBody)(text, parsed, redact);
|
|
69
|
-
let code = null;
|
|
70
|
-
let message = '';
|
|
71
|
-
let details = null;
|
|
72
|
-
let slipData;
|
|
73
|
-
if (isObject(body)) {
|
|
74
|
-
if (api === 'v2' && isObject(body.error)) {
|
|
75
|
-
if (typeof body.error.code === 'string')
|
|
76
|
-
code = body.error.code;
|
|
77
|
-
if (typeof body.error.message === 'string')
|
|
78
|
-
message = body.error.message;
|
|
79
|
-
}
|
|
80
|
-
else if (api === 'v1') {
|
|
81
|
-
if (typeof body.message === 'string') {
|
|
82
|
-
code = body.message;
|
|
83
|
-
message = body.message;
|
|
84
|
-
}
|
|
85
|
-
if (typeof body.details === 'string' || Array.isArray(body.details)) {
|
|
86
|
-
details = body.details;
|
|
87
|
-
}
|
|
88
|
-
slipData = body.data;
|
|
89
|
-
}
|
|
90
|
-
else if (typeof body.message === 'string') {
|
|
91
|
-
message = body.message;
|
|
92
|
-
}
|
|
93
|
-
}
|
|
94
|
-
const className = (code !== null ? error_codes_js_1.errorCodes[api][code] : undefined) ??
|
|
95
|
-
error_codes_js_1.statusFallback[status] ??
|
|
96
|
-
(status >= 500 ? 'ServerError' : 'ApiError');
|
|
97
|
-
const ErrorClass = (0, errors_js_1.apiErrorClass)(className);
|
|
98
|
-
const slip = className === 'DuplicateSlipError' && isObject(slipData)
|
|
99
|
-
? (0, models_js_1.parseModel)(duplicateSlip ?? 'BankSlip', slipData)
|
|
100
|
-
: null;
|
|
101
|
-
const safeHeaders = (0, redact_js_1.redactHeaders)(headers, redact);
|
|
102
|
-
return new ErrorClass({
|
|
103
|
-
status,
|
|
104
|
-
code,
|
|
105
|
-
message: message || `HTTP ${status}`,
|
|
106
|
-
requestId: (0, meta_js_1.requestIdFrom)(safeHeaders),
|
|
107
|
-
rawBody,
|
|
108
|
-
sensitiveRawBody: text,
|
|
109
|
-
headers: safeHeaders,
|
|
110
|
-
details,
|
|
111
|
-
retryAfter: (0, meta_js_1.retryAfterFrom)(headers),
|
|
112
|
-
rateLimit: (0, meta_js_1.rateLimitFrom)(headers),
|
|
113
|
-
slip,
|
|
114
|
-
});
|
|
115
|
-
}
|
|
116
|
-
/**
|
|
117
|
-
* Turns one HTTP response into `{ data, meta }`, or throws the mapped {@link ApiError}.
|
|
118
|
-
* `redact` removes the API key from everything taken from the response.
|
|
119
|
-
* Exported for the conformance tests; SDK users never need it.
|
|
120
|
-
*/
|
|
121
|
-
function decodeResponse(api, status, rawHeaders, text, duplicateSlip, redact = redact_js_1.noRedact) {
|
|
122
|
-
const headers = (0, meta_js_1.headersToRecord)(rawHeaders);
|
|
123
|
-
const body = parseJson(text);
|
|
124
|
-
const ok = status >= 200 && status < 300;
|
|
125
|
-
const successEnvelope = isObject(body) && (api === 'v2' ? body.success === true : 'data' in body);
|
|
126
|
-
if (!ok || !successEnvelope) {
|
|
127
|
-
throw errorFromResponse(api, status, headers, text, body, duplicateSlip, redact);
|
|
128
|
-
}
|
|
129
|
-
const safeHeaders = (0, redact_js_1.redactHeaders)(headers, redact);
|
|
130
|
-
const meta = {
|
|
131
|
-
status,
|
|
132
|
-
requestId: (0, meta_js_1.requestIdFrom)(safeHeaders),
|
|
133
|
-
message: api === 'v2' && typeof body.message === 'string' ? redact.text(body.message) : null,
|
|
134
|
-
rateLimit: (0, meta_js_1.rateLimitFrom)(headers),
|
|
135
|
-
headers: safeHeaders,
|
|
136
|
-
};
|
|
137
|
-
return { data: body.data, meta };
|
|
138
|
-
}
|
|
139
|
-
/** Sends requests with auth, timeouts and the retry rules. Holds the API key privately. */
|
|
140
|
-
class Transport {
|
|
141
|
-
#config;
|
|
142
|
-
constructor(config) {
|
|
143
|
-
this.#config = config;
|
|
144
|
-
}
|
|
145
|
-
get config() {
|
|
146
|
-
const { apiKey: _apiKey, ...rest } = this.#config;
|
|
147
|
-
return rest;
|
|
148
|
-
}
|
|
149
|
-
#url(spec) {
|
|
150
|
-
const base = (spec.api === 'v1' ? this.#config.v1BaseUrl : this.#config.v2BaseUrl).replace(/\/+$/, '');
|
|
151
|
-
const params = new URLSearchParams();
|
|
152
|
-
for (const [key, value] of Object.entries(spec.query ?? {})) {
|
|
153
|
-
if (value !== undefined)
|
|
154
|
-
params.append(key, value);
|
|
155
|
-
}
|
|
156
|
-
const qs = params.toString();
|
|
157
|
-
return `${base}${spec.path}${qs ? `?${qs}` : ''}`;
|
|
158
|
-
}
|
|
159
|
-
async request(spec) {
|
|
160
|
-
const config = this.#config;
|
|
161
|
-
const maxRetries = Math.max(0, spec.maxRetries ?? config.maxRetries);
|
|
162
|
-
const timeout = spec.timeout ?? config.timeout;
|
|
163
|
-
const url = this.#url(spec);
|
|
164
|
-
const apiKey = await config.apiKey();
|
|
165
|
-
const redact = (0, redact_js_1.redactor)(apiKey);
|
|
166
|
-
const headers = {
|
|
167
|
-
Authorization: `Bearer ${apiKey}`,
|
|
168
|
-
Accept: 'application/json',
|
|
169
|
-
'User-Agent': config.userAgent,
|
|
170
|
-
};
|
|
171
|
-
let body;
|
|
172
|
-
if (spec.form) {
|
|
173
|
-
body = spec.form;
|
|
174
|
-
}
|
|
175
|
-
else if (spec.json !== undefined) {
|
|
176
|
-
body = JSON.stringify(spec.json);
|
|
177
|
-
headers['Content-Type'] = 'application/json';
|
|
178
|
-
}
|
|
179
|
-
for (let attempt = 0;; attempt++) {
|
|
180
|
-
spec.signal?.throwIfAborted();
|
|
181
|
-
const controller = new AbortController();
|
|
182
|
-
let timedOut = false;
|
|
183
|
-
const timer = setTimeout(() => {
|
|
184
|
-
timedOut = true;
|
|
185
|
-
controller.abort();
|
|
186
|
-
}, timeout);
|
|
187
|
-
const onAbort = () => controller.abort(spec.signal?.reason);
|
|
188
|
-
spec.signal?.addEventListener('abort', onAbort, { once: true });
|
|
189
|
-
let status;
|
|
190
|
-
let responseHeaders;
|
|
191
|
-
let text;
|
|
192
|
-
try {
|
|
193
|
-
const response = await config.fetch(url, {
|
|
194
|
-
method: spec.method,
|
|
195
|
-
headers,
|
|
196
|
-
body,
|
|
197
|
-
signal: controller.signal,
|
|
198
|
-
});
|
|
199
|
-
status = response.status;
|
|
200
|
-
responseHeaders = response.headers;
|
|
201
|
-
text = await response.text();
|
|
202
|
-
}
|
|
203
|
-
catch (rawCause) {
|
|
204
|
-
if (spec.signal?.aborted)
|
|
205
|
-
throw spec.signal.reason;
|
|
206
|
-
// Classified from the original below; only the sanitized copy is kept.
|
|
207
|
-
const cause = (0, redact_js_1.sanitizeCause)(rawCause, redact);
|
|
208
|
-
const error = timedOut
|
|
209
|
-
? new errors_js_1.RequestTimeoutError(`no response within ${timeout} ms`, { cause })
|
|
210
|
-
: new errors_js_1.NetworkError(`request failed: ${cause.message}`, { cause });
|
|
211
|
-
const retryable = attempt < maxRetries &&
|
|
212
|
-
(spec.retry === 'safe' || (!timedOut && isConnectFailure(rawCause)));
|
|
213
|
-
if (!retryable)
|
|
214
|
-
throw error;
|
|
215
|
-
spec.signal?.throwIfAborted();
|
|
216
|
-
await config.sleep(backoffDelay(attempt, config.random), spec.signal);
|
|
217
|
-
continue;
|
|
218
|
-
}
|
|
219
|
-
finally {
|
|
220
|
-
clearTimeout(timer);
|
|
221
|
-
spec.signal?.removeEventListener('abort', onAbort);
|
|
222
|
-
}
|
|
223
|
-
try {
|
|
224
|
-
return decodeResponse(spec.api, status, responseHeaders, text, spec.duplicateSlip, redact);
|
|
225
|
-
}
|
|
226
|
-
catch (error) {
|
|
227
|
-
const apiError = error;
|
|
228
|
-
const retryable = attempt < maxRetries &&
|
|
229
|
-
(status === 429 || (spec.retry === 'safe' && RETRY_STATUS.has(status)));
|
|
230
|
-
if (!retryable)
|
|
231
|
-
throw apiError;
|
|
232
|
-
const retryAfter = apiError.retryAfter;
|
|
233
|
-
if (retryAfter !== null && retryAfter > MAX_RETRY_AFTER_SECONDS)
|
|
234
|
-
throw apiError;
|
|
235
|
-
const delay = retryAfter !== null ? retryAfter * 1000 : backoffDelay(attempt, config.random);
|
|
236
|
-
spec.signal?.throwIfAborted();
|
|
237
|
-
await config.sleep(delay, spec.signal);
|
|
238
|
-
}
|
|
239
|
-
}
|
|
240
|
-
}
|
|
241
|
-
}
|
|
242
|
-
exports.Transport = Transport;
|
package/dist/cjs/core/meta.js
DELETED
|
@@ -1,52 +0,0 @@
|
|
|
1
|
-
"use strict";
|
|
2
|
-
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
-
exports.attachMeta = attachMeta;
|
|
4
|
-
exports.headersToRecord = headersToRecord;
|
|
5
|
-
exports.requestIdFrom = requestIdFrom;
|
|
6
|
-
exports.rateLimitFrom = rateLimitFrom;
|
|
7
|
-
exports.retryAfterFrom = retryAfterFrom;
|
|
8
|
-
/** Attaches `meta` without making it part of the value's JSON or its enumerable keys. */
|
|
9
|
-
function attachMeta(value, meta) {
|
|
10
|
-
Object.defineProperty(value, 'meta', { value: meta, enumerable: false });
|
|
11
|
-
return value;
|
|
12
|
-
}
|
|
13
|
-
function headersToRecord(headers) {
|
|
14
|
-
const out = {};
|
|
15
|
-
if (headers instanceof Headers) {
|
|
16
|
-
headers.forEach((value, key) => {
|
|
17
|
-
out[key.toLowerCase()] = value;
|
|
18
|
-
});
|
|
19
|
-
return out;
|
|
20
|
-
}
|
|
21
|
-
for (const [key, value] of Object.entries(headers))
|
|
22
|
-
out[key.toLowerCase()] = value;
|
|
23
|
-
return out;
|
|
24
|
-
}
|
|
25
|
-
function requestIdFrom(headers) {
|
|
26
|
-
return headers['x-request-id'] || headers['cf-ray'] || null;
|
|
27
|
-
}
|
|
28
|
-
function toInt(value) {
|
|
29
|
-
if (value === undefined || !/^\s*-?\d+\s*$/.test(value))
|
|
30
|
-
return null;
|
|
31
|
-
return Number.parseInt(value, 10);
|
|
32
|
-
}
|
|
33
|
-
function rateLimitFrom(headers) {
|
|
34
|
-
const limit = toInt(headers['x-ratelimit-limit']);
|
|
35
|
-
const remaining = toInt(headers['x-ratelimit-remaining']);
|
|
36
|
-
const reset = toInt(headers['x-ratelimit-reset']);
|
|
37
|
-
if (limit === null || remaining === null || reset === null)
|
|
38
|
-
return null;
|
|
39
|
-
return { limit, remaining, reset };
|
|
40
|
-
}
|
|
41
|
-
/** Seconds from a `Retry-After` header (delta seconds or HTTP date), or null. */
|
|
42
|
-
function retryAfterFrom(headers, now = Date.now()) {
|
|
43
|
-
const raw = headers['retry-after']?.trim();
|
|
44
|
-
if (!raw)
|
|
45
|
-
return null;
|
|
46
|
-
if (/^\d+$/.test(raw))
|
|
47
|
-
return Number.parseInt(raw, 10);
|
|
48
|
-
const at = Date.parse(raw);
|
|
49
|
-
if (Number.isNaN(at))
|
|
50
|
-
return null;
|
|
51
|
-
return Math.max(0, Math.ceil((at - now) / 1000));
|
|
52
|
-
}
|
package/dist/cjs/core/redact.js
DELETED
|
@@ -1,208 +0,0 @@
|
|
|
1
|
-
"use strict";
|
|
2
|
-
// Removes the configured API key from everything the SDK takes from a response or a transport
|
|
3
|
-
// error. The key is found by decoding, not by listing encodings.
|
|
4
|
-
Object.defineProperty(exports, "__esModule", { value: true });
|
|
5
|
-
exports.noRedact = exports.REDACTED = void 0;
|
|
6
|
-
exports.percentDecode = percentDecode;
|
|
7
|
-
exports.jsonUnescape = jsonUnescape;
|
|
8
|
-
exports.redactor = redactor;
|
|
9
|
-
exports.redactHeaders = redactHeaders;
|
|
10
|
-
exports.redactJson = redactJson;
|
|
11
|
-
exports.redactBody = redactBody;
|
|
12
|
-
exports.sanitizeCause = sanitizeCause;
|
|
13
|
-
/** What the SDK puts where it removed the API key or an Authorization value. */
|
|
14
|
-
exports.REDACTED = '[REDACTED]';
|
|
15
|
-
const AUTH_HEADERS = new Set(['authorization', 'proxy-authorization']);
|
|
16
|
-
const MAX_CAUSE_DEPTH = 3;
|
|
17
|
-
exports.noRedact = { text: (value) => value, carries: () => false };
|
|
18
|
-
const utf8 = new TextDecoder();
|
|
19
|
-
/** `%HH` (either hex case) becomes that byte; runs of bytes are read as UTF-8. */
|
|
20
|
-
function percentDecode(text) {
|
|
21
|
-
if (!text.includes('%'))
|
|
22
|
-
return text;
|
|
23
|
-
return text.replace(/(?:%[0-9a-fA-F]{2})+/g, (run) => {
|
|
24
|
-
const bytes = new Uint8Array(run.length / 3);
|
|
25
|
-
for (let i = 0; i < bytes.length; i++) {
|
|
26
|
-
bytes[i] = Number.parseInt(run.slice(i * 3 + 1, i * 3 + 3), 16);
|
|
27
|
-
}
|
|
28
|
-
return utf8.decode(bytes);
|
|
29
|
-
});
|
|
30
|
-
}
|
|
31
|
-
const JSON_ESCAPES = {
|
|
32
|
-
'"': '"',
|
|
33
|
-
'\\': '\\',
|
|
34
|
-
'/': '/',
|
|
35
|
-
b: '\b',
|
|
36
|
-
f: '\f',
|
|
37
|
-
n: '\n',
|
|
38
|
-
r: '\r',
|
|
39
|
-
t: '\t',
|
|
40
|
-
};
|
|
41
|
-
/** JSON string unescaping: `\uXXXX` (either hex case) and the short escapes. */
|
|
42
|
-
function jsonUnescape(text) {
|
|
43
|
-
if (!text.includes('\\'))
|
|
44
|
-
return text;
|
|
45
|
-
return text.replace(/\\(u[0-9a-fA-F]{4}|["\\/bfnrt])/g, (_, seq) => seq.length === 5
|
|
46
|
-
? String.fromCharCode(Number.parseInt(seq.slice(1), 16))
|
|
47
|
-
: JSON_ESCAPES[seq]);
|
|
48
|
-
}
|
|
49
|
-
/** Matches the key with any subset of its characters percent-encoded, in either hex case. */
|
|
50
|
-
function percentPattern(apiKey) {
|
|
51
|
-
const hex = (byte) => [...byte.toString(16).padStart(2, '0')]
|
|
52
|
-
.map((d) => (/[a-f]/.test(d) ? `[${d}${d.toUpperCase()}]` : d))
|
|
53
|
-
.join('');
|
|
54
|
-
const parts = [...apiKey].map((char) => {
|
|
55
|
-
const literal = char.replace(/[.*+?^${}()|[\]\\/-]/g, '\\$&');
|
|
56
|
-
const encoded = [...new TextEncoder().encode(char)].map((b) => `%${hex(b)}`).join('');
|
|
57
|
-
return `(?:${literal}|${encoded})`;
|
|
58
|
-
});
|
|
59
|
-
return new RegExp(parts.join(''), 'g');
|
|
60
|
-
}
|
|
61
|
-
/** Builds the redactor for one API key. Keys shorter than 4 characters are left alone. */
|
|
62
|
-
function redactor(apiKey) {
|
|
63
|
-
if (apiKey.length < 4)
|
|
64
|
-
return exports.noRedact;
|
|
65
|
-
const pattern = percentPattern(apiKey);
|
|
66
|
-
const carries = (value) => {
|
|
67
|
-
// The text, its percent-decoding, its JSON unescaping, and each applied to the other,
|
|
68
|
-
// one level deep.
|
|
69
|
-
let views = [value];
|
|
70
|
-
const seen = new Set(views);
|
|
71
|
-
for (let level = 0; level <= 3; level++) {
|
|
72
|
-
if (views.some((view) => view.includes(apiKey)))
|
|
73
|
-
return true;
|
|
74
|
-
const next = [];
|
|
75
|
-
for (const view of views) {
|
|
76
|
-
for (const decoded of [percentDecode(view), jsonUnescape(view)]) {
|
|
77
|
-
if (!seen.has(decoded)) {
|
|
78
|
-
seen.add(decoded);
|
|
79
|
-
next.push(decoded);
|
|
80
|
-
}
|
|
81
|
-
}
|
|
82
|
-
}
|
|
83
|
-
if (next.length === 0)
|
|
84
|
-
return false;
|
|
85
|
-
views = next;
|
|
86
|
-
}
|
|
87
|
-
return false;
|
|
88
|
-
};
|
|
89
|
-
return {
|
|
90
|
-
carries,
|
|
91
|
-
text(value) {
|
|
92
|
-
if (!value)
|
|
93
|
-
return value;
|
|
94
|
-
const out = value.replace(pattern, exports.REDACTED);
|
|
95
|
-
return carries(out) ? exports.REDACTED : out;
|
|
96
|
-
},
|
|
97
|
-
};
|
|
98
|
-
}
|
|
99
|
-
/**
|
|
100
|
-
* Authorization and Proxy-Authorization are always `[REDACTED]`; any other value that
|
|
101
|
-
* carries the key becomes `[REDACTED]` as a whole.
|
|
102
|
-
*/
|
|
103
|
-
function redactHeaders(headers, redact) {
|
|
104
|
-
const out = {};
|
|
105
|
-
for (const [name, value] of Object.entries(headers)) {
|
|
106
|
-
out[name] = AUTH_HEADERS.has(name.toLowerCase()) || redact.carries(value) ? exports.REDACTED : value;
|
|
107
|
-
}
|
|
108
|
-
return out;
|
|
109
|
-
}
|
|
110
|
-
function defineValue(target, key, value) {
|
|
111
|
-
Object.defineProperty(target, key, {
|
|
112
|
-
value,
|
|
113
|
-
enumerable: true,
|
|
114
|
-
writable: true,
|
|
115
|
-
configurable: true,
|
|
116
|
-
});
|
|
117
|
-
}
|
|
118
|
-
/**
|
|
119
|
-
* Applies `text` to every string of a parsed JSON value, object keys included. Returns the
|
|
120
|
-
* same value when nothing changed.
|
|
121
|
-
*/
|
|
122
|
-
function redactJson(value, redact) {
|
|
123
|
-
if (typeof value === 'string')
|
|
124
|
-
return redact.text(value);
|
|
125
|
-
if (Array.isArray(value)) {
|
|
126
|
-
const out = value.map((item) => redactJson(item, redact));
|
|
127
|
-
return out.some((item, i) => item !== value[i]) ? out : value;
|
|
128
|
-
}
|
|
129
|
-
if (value === null || typeof value !== 'object')
|
|
130
|
-
return value;
|
|
131
|
-
let changed = false;
|
|
132
|
-
const out = {};
|
|
133
|
-
for (const [key, item] of Object.entries(value)) {
|
|
134
|
-
const safeKey = redact.text(key);
|
|
135
|
-
const safeItem = redactJson(item, redact);
|
|
136
|
-
if (safeKey !== key || safeItem !== item)
|
|
137
|
-
changed = true;
|
|
138
|
-
// defineProperty, so a "__proto__" key stays a plain key
|
|
139
|
-
defineValue(out, safeKey, safeItem);
|
|
140
|
-
}
|
|
141
|
-
return changed ? out : value;
|
|
142
|
-
}
|
|
143
|
-
/**
|
|
144
|
-
* Redaction of a whole body: `body` is `text` parsed as JSON (undefined when it is not JSON). Returns
|
|
145
|
-
* the body that may be shown and the redacted parsed value.
|
|
146
|
-
*/
|
|
147
|
-
function redactBody(text, body, redact) {
|
|
148
|
-
if (body === undefined)
|
|
149
|
-
return { rawBody: redact.text(text), body };
|
|
150
|
-
const safe = redactJson(body, redact);
|
|
151
|
-
return { rawBody: safe === body ? text : JSON.stringify(safe), body: safe };
|
|
152
|
-
}
|
|
153
|
-
function read(source, key) {
|
|
154
|
-
try {
|
|
155
|
-
return source[key];
|
|
156
|
-
}
|
|
157
|
-
catch {
|
|
158
|
-
return undefined;
|
|
159
|
-
}
|
|
160
|
-
}
|
|
161
|
-
function typeName(source) {
|
|
162
|
-
if (source instanceof Error)
|
|
163
|
-
return String(read(source, 'name') ?? 'Error');
|
|
164
|
-
if (source === null)
|
|
165
|
-
return 'null';
|
|
166
|
-
if (typeof source !== 'object')
|
|
167
|
-
return typeof source;
|
|
168
|
-
const ctor = read(source, 'constructor');
|
|
169
|
-
return typeof ctor?.name === 'string' && ctor.name ? ctor.name : 'Object';
|
|
170
|
-
}
|
|
171
|
-
function messageOf(source) {
|
|
172
|
-
if (typeof source === 'string')
|
|
173
|
-
return source;
|
|
174
|
-
const message = read(source, 'message');
|
|
175
|
-
if (typeof message === 'string')
|
|
176
|
-
return message;
|
|
177
|
-
if (source instanceof Error || (source !== null && typeof source === 'object'))
|
|
178
|
-
return '';
|
|
179
|
-
return String(source);
|
|
180
|
-
}
|
|
181
|
-
/**
|
|
182
|
-
* A sanitized copy of a transport failure. It holds the type name, the message after `text`,
|
|
183
|
-
* `code` and `errno` when they are strings or numbers, and the sanitized copy of the
|
|
184
|
-
* original's own cause (at most 3 levels). Never the original or any other property.
|
|
185
|
-
*/
|
|
186
|
-
function sanitizeCause(cause, redact, depth = 1) {
|
|
187
|
-
const copy = new Error(redact.text(messageOf(cause)));
|
|
188
|
-
copy.name = redact.text(typeName(cause));
|
|
189
|
-
copy.stack = `${copy.name}: ${copy.message}`;
|
|
190
|
-
for (const field of ['code', 'errno']) {
|
|
191
|
-
const value = cause !== null && typeof cause === 'object' ? read(cause, field) : undefined;
|
|
192
|
-
if (typeof value === 'string')
|
|
193
|
-
defineValue(copy, field, redact.text(value));
|
|
194
|
-
else if (typeof value === 'number') {
|
|
195
|
-
defineValue(copy, field, redact.carries(String(value)) ? exports.REDACTED : value);
|
|
196
|
-
}
|
|
197
|
-
}
|
|
198
|
-
const inner = cause !== null && typeof cause === 'object' ? read(cause, 'cause') : undefined;
|
|
199
|
-
if (inner !== undefined && depth < MAX_CAUSE_DEPTH) {
|
|
200
|
-
Object.defineProperty(copy, 'cause', {
|
|
201
|
-
value: sanitizeCause(inner, redact, depth + 1),
|
|
202
|
-
enumerable: false,
|
|
203
|
-
writable: true,
|
|
204
|
-
configurable: true,
|
|
205
|
-
});
|
|
206
|
-
}
|
|
207
|
-
return copy;
|
|
208
|
-
}
|