@easyslip/sdk 0.0.0-stage → 1.0.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 +8 -0
- package/LICENSE +21 -0
- package/README.md +595 -2
- package/README.th.md +610 -0
- package/dist/cjs/client.d.ts +59 -0
- package/dist/cjs/client.js +150 -0
- package/dist/cjs/core/call.d.ts +18 -0
- package/dist/cjs/core/call.js +60 -0
- package/dist/cjs/core/error-codes.d.ts +8 -0
- package/dist/cjs/core/error-codes.js +87 -0
- package/dist/cjs/core/errors.d.ts +162 -0
- package/dist/cjs/core/errors.js +210 -0
- package/dist/cjs/core/files.d.ts +20 -0
- package/dist/cjs/core/files.js +131 -0
- package/dist/cjs/core/http.d.ts +65 -0
- package/dist/cjs/core/http.js +242 -0
- package/dist/cjs/core/meta.d.ts +33 -0
- package/dist/cjs/core/meta.js +52 -0
- package/dist/cjs/core/redact.d.ts +43 -0
- package/dist/cjs/core/redact.js +208 -0
- package/dist/cjs/core/runtime.d.ts +16 -0
- package/dist/cjs/core/runtime.js +86 -0
- package/dist/cjs/core/settings.d.ts +19 -0
- package/dist/cjs/core/settings.js +22 -0
- package/dist/cjs/core/sha256.d.ts +6 -0
- package/dist/cjs/core/sha256.js +101 -0
- package/dist/cjs/index.d.ts +13 -0
- package/dist/cjs/index.js +55 -0
- package/dist/cjs/models.d.ts +398 -0
- package/dist/cjs/models.js +234 -0
- package/dist/cjs/package.json +1 -0
- package/dist/cjs/resources/bank-accounts.d.ts +63 -0
- package/dist/cjs/resources/bank-accounts.js +126 -0
- package/dist/cjs/resources/banks.d.ts +10 -0
- package/dist/cjs/resources/banks.js +22 -0
- package/dist/cjs/resources/jobs.d.ts +64 -0
- package/dist/cjs/resources/jobs.js +177 -0
- package/dist/cjs/resources/v1.d.ts +88 -0
- package/dist/cjs/resources/v1.js +137 -0
- package/dist/cjs/resources/verify.d.ts +39 -0
- package/dist/cjs/resources/verify.js +105 -0
- package/dist/cjs/version.d.ts +2 -0
- package/dist/cjs/version.js +5 -0
- package/dist/cjs/webhooks.d.ts +26 -0
- package/dist/cjs/webhooks.js +92 -0
- package/dist/esm/client.d.ts +59 -0
- package/dist/esm/client.js +146 -0
- package/dist/esm/core/call.d.ts +18 -0
- package/dist/esm/core/call.js +52 -0
- package/dist/esm/core/error-codes.d.ts +8 -0
- package/dist/esm/core/error-codes.js +84 -0
- package/dist/esm/core/errors.d.ts +162 -0
- package/dist/esm/core/errors.js +184 -0
- package/dist/esm/core/files.d.ts +20 -0
- package/dist/esm/core/files.js +126 -0
- package/dist/esm/core/http.d.ts +65 -0
- package/dist/esm/core/http.js +235 -0
- package/dist/esm/core/meta.d.ts +33 -0
- package/dist/esm/core/meta.js +45 -0
- package/dist/esm/core/redact.d.ts +43 -0
- package/dist/esm/core/redact.js +198 -0
- package/dist/esm/core/runtime.d.ts +16 -0
- package/dist/esm/core/runtime.js +47 -0
- package/dist/esm/core/settings.d.ts +19 -0
- package/dist/esm/core/settings.js +19 -0
- package/dist/esm/core/sha256.d.ts +6 -0
- package/dist/esm/core/sha256.js +96 -0
- package/dist/esm/index.d.ts +13 -0
- package/dist/esm/index.js +7 -0
- package/dist/esm/models.d.ts +398 -0
- package/dist/esm/models.js +228 -0
- package/dist/esm/package.json +1 -0
- package/dist/esm/resources/bank-accounts.d.ts +63 -0
- package/dist/esm/resources/bank-accounts.js +122 -0
- package/dist/esm/resources/banks.d.ts +10 -0
- package/dist/esm/resources/banks.js +18 -0
- package/dist/esm/resources/jobs.d.ts +64 -0
- package/dist/esm/resources/jobs.js +173 -0
- package/dist/esm/resources/v1.d.ts +88 -0
- package/dist/esm/resources/v1.js +133 -0
- package/dist/esm/resources/verify.d.ts +39 -0
- package/dist/esm/resources/verify.js +100 -0
- package/dist/esm/version.d.ts +2 -0
- package/dist/esm/version.js +2 -0
- package/dist/esm/webhooks.d.ts +26 -0
- package/dist/esm/webhooks.js +86 -0
- package/package.json +80 -5
|
@@ -0,0 +1,235 @@
|
|
|
1
|
+
import { parseModel } from '../models.js';
|
|
2
|
+
import { errorCodes, statusFallback } from './error-codes.js';
|
|
3
|
+
import { apiErrorClass, NetworkError, RequestTimeoutError, } from './errors.js';
|
|
4
|
+
import { headersToRecord, rateLimitFrom, requestIdFrom, retryAfterFrom, } from './meta.js';
|
|
5
|
+
import { noRedact, redactBody, redactHeaders, redactor, sanitizeCause, } from './redact.js';
|
|
6
|
+
const RETRY_STATUS = new Set([500, 502, 503, 504]);
|
|
7
|
+
const MAX_RETRY_AFTER_SECONDS = 60;
|
|
8
|
+
// Error codes that mean the request bytes never left this machine.
|
|
9
|
+
const CONNECT_CODES = new Set([
|
|
10
|
+
'ECONNREFUSED',
|
|
11
|
+
'ENOTFOUND',
|
|
12
|
+
'EAI_AGAIN',
|
|
13
|
+
'EAI_NONAME',
|
|
14
|
+
'EAI_FAIL',
|
|
15
|
+
'EHOSTUNREACH',
|
|
16
|
+
'ENETUNREACH',
|
|
17
|
+
'EADDRNOTAVAIL',
|
|
18
|
+
'UND_ERR_CONNECT_TIMEOUT',
|
|
19
|
+
'ConnectionRefused',
|
|
20
|
+
'FailedToOpenSocket',
|
|
21
|
+
'DNSException',
|
|
22
|
+
]);
|
|
23
|
+
function errorCodesOf(error, depth = 0) {
|
|
24
|
+
if (!error || typeof error !== 'object' || depth > 3)
|
|
25
|
+
return [];
|
|
26
|
+
const e = error;
|
|
27
|
+
const out = typeof e.code === 'string' ? [e.code] : [];
|
|
28
|
+
out.push(...errorCodesOf(e.cause, depth + 1));
|
|
29
|
+
if (Array.isArray(e.errors))
|
|
30
|
+
for (const inner of e.errors)
|
|
31
|
+
out.push(...errorCodesOf(inner, depth + 1));
|
|
32
|
+
return out;
|
|
33
|
+
}
|
|
34
|
+
/** True when a fetch failure happened before the request was sent (DNS, connect, TLS). */
|
|
35
|
+
export function isConnectFailure(error) {
|
|
36
|
+
return errorCodesOf(error).some((code) => CONNECT_CODES.has(code) ||
|
|
37
|
+
code.startsWith('ERR_TLS_') ||
|
|
38
|
+
code.startsWith('ERR_SSL_') ||
|
|
39
|
+
code.includes('CERT') ||
|
|
40
|
+
code.startsWith('UNABLE_TO_'));
|
|
41
|
+
}
|
|
42
|
+
/** Backoff before retry number `attempt` (0-based), in milliseconds. */
|
|
43
|
+
export function backoffDelay(attempt, random = Math.random) {
|
|
44
|
+
const base = Math.min(8000, 500 * 2 ** attempt);
|
|
45
|
+
return base * (0.5 + random() * 0.5);
|
|
46
|
+
}
|
|
47
|
+
function parseJson(text) {
|
|
48
|
+
if (!text)
|
|
49
|
+
return undefined;
|
|
50
|
+
try {
|
|
51
|
+
return JSON.parse(text);
|
|
52
|
+
}
|
|
53
|
+
catch {
|
|
54
|
+
return undefined;
|
|
55
|
+
}
|
|
56
|
+
}
|
|
57
|
+
function isObject(value) {
|
|
58
|
+
return value !== null && typeof value === 'object' && !Array.isArray(value);
|
|
59
|
+
}
|
|
60
|
+
function errorFromResponse(api, status, headers, text, parsed, duplicateSlip, redact) {
|
|
61
|
+
// Every field below is read from the redacted body.
|
|
62
|
+
const { rawBody, body } = redactBody(text, parsed, redact);
|
|
63
|
+
let code = null;
|
|
64
|
+
let message = '';
|
|
65
|
+
let details = null;
|
|
66
|
+
let slipData;
|
|
67
|
+
if (isObject(body)) {
|
|
68
|
+
if (api === 'v2' && isObject(body.error)) {
|
|
69
|
+
if (typeof body.error.code === 'string')
|
|
70
|
+
code = body.error.code;
|
|
71
|
+
if (typeof body.error.message === 'string')
|
|
72
|
+
message = body.error.message;
|
|
73
|
+
}
|
|
74
|
+
else if (api === 'v1') {
|
|
75
|
+
if (typeof body.message === 'string') {
|
|
76
|
+
code = body.message;
|
|
77
|
+
message = body.message;
|
|
78
|
+
}
|
|
79
|
+
if (typeof body.details === 'string' || Array.isArray(body.details)) {
|
|
80
|
+
details = body.details;
|
|
81
|
+
}
|
|
82
|
+
slipData = body.data;
|
|
83
|
+
}
|
|
84
|
+
else if (typeof body.message === 'string') {
|
|
85
|
+
message = body.message;
|
|
86
|
+
}
|
|
87
|
+
}
|
|
88
|
+
const className = (code !== null ? errorCodes[api][code] : undefined) ??
|
|
89
|
+
statusFallback[status] ??
|
|
90
|
+
(status >= 500 ? 'ServerError' : 'ApiError');
|
|
91
|
+
const ErrorClass = apiErrorClass(className);
|
|
92
|
+
const slip = className === 'DuplicateSlipError' && isObject(slipData)
|
|
93
|
+
? parseModel(duplicateSlip ?? 'BankSlip', slipData)
|
|
94
|
+
: null;
|
|
95
|
+
const safeHeaders = redactHeaders(headers, redact);
|
|
96
|
+
return new ErrorClass({
|
|
97
|
+
status,
|
|
98
|
+
code,
|
|
99
|
+
message: message || `HTTP ${status}`,
|
|
100
|
+
requestId: requestIdFrom(safeHeaders),
|
|
101
|
+
rawBody,
|
|
102
|
+
sensitiveRawBody: text,
|
|
103
|
+
headers: safeHeaders,
|
|
104
|
+
details,
|
|
105
|
+
retryAfter: retryAfterFrom(headers),
|
|
106
|
+
rateLimit: rateLimitFrom(headers),
|
|
107
|
+
slip,
|
|
108
|
+
});
|
|
109
|
+
}
|
|
110
|
+
/**
|
|
111
|
+
* Turns one HTTP response into `{ data, meta }`, or throws the mapped {@link ApiError}.
|
|
112
|
+
* `redact` removes the API key from everything taken from the response.
|
|
113
|
+
* Exported for the conformance tests; SDK users never need it.
|
|
114
|
+
*/
|
|
115
|
+
export function decodeResponse(api, status, rawHeaders, text, duplicateSlip, redact = noRedact) {
|
|
116
|
+
const headers = headersToRecord(rawHeaders);
|
|
117
|
+
const body = parseJson(text);
|
|
118
|
+
const ok = status >= 200 && status < 300;
|
|
119
|
+
const successEnvelope = isObject(body) && (api === 'v2' ? body.success === true : 'data' in body);
|
|
120
|
+
if (!ok || !successEnvelope) {
|
|
121
|
+
throw errorFromResponse(api, status, headers, text, body, duplicateSlip, redact);
|
|
122
|
+
}
|
|
123
|
+
const safeHeaders = redactHeaders(headers, redact);
|
|
124
|
+
const meta = {
|
|
125
|
+
status,
|
|
126
|
+
requestId: requestIdFrom(safeHeaders),
|
|
127
|
+
message: api === 'v2' && typeof body.message === 'string' ? redact.text(body.message) : null,
|
|
128
|
+
rateLimit: rateLimitFrom(headers),
|
|
129
|
+
headers: safeHeaders,
|
|
130
|
+
};
|
|
131
|
+
return { data: body.data, meta };
|
|
132
|
+
}
|
|
133
|
+
/** Sends requests with auth, timeouts and the retry rules. Holds the API key privately. */
|
|
134
|
+
export class Transport {
|
|
135
|
+
#config;
|
|
136
|
+
constructor(config) {
|
|
137
|
+
this.#config = config;
|
|
138
|
+
}
|
|
139
|
+
get config() {
|
|
140
|
+
const { apiKey: _apiKey, ...rest } = this.#config;
|
|
141
|
+
return rest;
|
|
142
|
+
}
|
|
143
|
+
#url(spec) {
|
|
144
|
+
const base = (spec.api === 'v1' ? this.#config.v1BaseUrl : this.#config.v2BaseUrl).replace(/\/+$/, '');
|
|
145
|
+
const params = new URLSearchParams();
|
|
146
|
+
for (const [key, value] of Object.entries(spec.query ?? {})) {
|
|
147
|
+
if (value !== undefined)
|
|
148
|
+
params.append(key, value);
|
|
149
|
+
}
|
|
150
|
+
const qs = params.toString();
|
|
151
|
+
return `${base}${spec.path}${qs ? `?${qs}` : ''}`;
|
|
152
|
+
}
|
|
153
|
+
async request(spec) {
|
|
154
|
+
const config = this.#config;
|
|
155
|
+
const maxRetries = Math.max(0, spec.maxRetries ?? config.maxRetries);
|
|
156
|
+
const timeout = spec.timeout ?? config.timeout;
|
|
157
|
+
const url = this.#url(spec);
|
|
158
|
+
const apiKey = await config.apiKey();
|
|
159
|
+
const redact = redactor(apiKey);
|
|
160
|
+
const headers = {
|
|
161
|
+
Authorization: `Bearer ${apiKey}`,
|
|
162
|
+
Accept: 'application/json',
|
|
163
|
+
'User-Agent': config.userAgent,
|
|
164
|
+
};
|
|
165
|
+
let body;
|
|
166
|
+
if (spec.form) {
|
|
167
|
+
body = spec.form;
|
|
168
|
+
}
|
|
169
|
+
else if (spec.json !== undefined) {
|
|
170
|
+
body = JSON.stringify(spec.json);
|
|
171
|
+
headers['Content-Type'] = 'application/json';
|
|
172
|
+
}
|
|
173
|
+
for (let attempt = 0;; attempt++) {
|
|
174
|
+
spec.signal?.throwIfAborted();
|
|
175
|
+
const controller = new AbortController();
|
|
176
|
+
let timedOut = false;
|
|
177
|
+
const timer = setTimeout(() => {
|
|
178
|
+
timedOut = true;
|
|
179
|
+
controller.abort();
|
|
180
|
+
}, timeout);
|
|
181
|
+
const onAbort = () => controller.abort(spec.signal?.reason);
|
|
182
|
+
spec.signal?.addEventListener('abort', onAbort, { once: true });
|
|
183
|
+
let status;
|
|
184
|
+
let responseHeaders;
|
|
185
|
+
let text;
|
|
186
|
+
try {
|
|
187
|
+
const response = await config.fetch(url, {
|
|
188
|
+
method: spec.method,
|
|
189
|
+
headers,
|
|
190
|
+
body,
|
|
191
|
+
signal: controller.signal,
|
|
192
|
+
});
|
|
193
|
+
status = response.status;
|
|
194
|
+
responseHeaders = response.headers;
|
|
195
|
+
text = await response.text();
|
|
196
|
+
}
|
|
197
|
+
catch (rawCause) {
|
|
198
|
+
if (spec.signal?.aborted)
|
|
199
|
+
throw spec.signal.reason;
|
|
200
|
+
// Classified from the original below; only the sanitized copy is kept.
|
|
201
|
+
const cause = sanitizeCause(rawCause, redact);
|
|
202
|
+
const error = timedOut
|
|
203
|
+
? new RequestTimeoutError(`no response within ${timeout} ms`, { cause })
|
|
204
|
+
: new NetworkError(`request failed: ${cause.message}`, { cause });
|
|
205
|
+
const retryable = attempt < maxRetries &&
|
|
206
|
+
(spec.retry === 'safe' || (!timedOut && isConnectFailure(rawCause)));
|
|
207
|
+
if (!retryable)
|
|
208
|
+
throw error;
|
|
209
|
+
spec.signal?.throwIfAborted();
|
|
210
|
+
await config.sleep(backoffDelay(attempt, config.random), spec.signal);
|
|
211
|
+
continue;
|
|
212
|
+
}
|
|
213
|
+
finally {
|
|
214
|
+
clearTimeout(timer);
|
|
215
|
+
spec.signal?.removeEventListener('abort', onAbort);
|
|
216
|
+
}
|
|
217
|
+
try {
|
|
218
|
+
return decodeResponse(spec.api, status, responseHeaders, text, spec.duplicateSlip, redact);
|
|
219
|
+
}
|
|
220
|
+
catch (error) {
|
|
221
|
+
const apiError = error;
|
|
222
|
+
const retryable = attempt < maxRetries &&
|
|
223
|
+
(status === 429 || (spec.retry === 'safe' && RETRY_STATUS.has(status)));
|
|
224
|
+
if (!retryable)
|
|
225
|
+
throw apiError;
|
|
226
|
+
const retryAfter = apiError.retryAfter;
|
|
227
|
+
if (retryAfter !== null && retryAfter > MAX_RETRY_AFTER_SECONDS)
|
|
228
|
+
throw apiError;
|
|
229
|
+
const delay = retryAfter !== null ? retryAfter * 1000 : backoffDelay(attempt, config.random);
|
|
230
|
+
spec.signal?.throwIfAborted();
|
|
231
|
+
await config.sleep(delay, spec.signal);
|
|
232
|
+
}
|
|
233
|
+
}
|
|
234
|
+
}
|
|
235
|
+
}
|
|
@@ -0,0 +1,33 @@
|
|
|
1
|
+
/** Rate limit counters from the `X-RateLimit-*` response headers. */
|
|
2
|
+
export interface RateLimit {
|
|
3
|
+
/** Requests allowed in the current window. */
|
|
4
|
+
readonly limit: number;
|
|
5
|
+
/** Requests left in the current window. */
|
|
6
|
+
readonly remaining: number;
|
|
7
|
+
/** When the window resets, as the API sends it (Unix seconds). */
|
|
8
|
+
readonly reset: number;
|
|
9
|
+
}
|
|
10
|
+
/** Response details that are not part of the returned data. */
|
|
11
|
+
export interface ResponseMeta {
|
|
12
|
+
/** HTTP status code. */
|
|
13
|
+
readonly status: number;
|
|
14
|
+
/** `x-request-id` header, else `cf-ray`, else null. Quote it when you contact support. */
|
|
15
|
+
readonly requestId: string | null;
|
|
16
|
+
/** The v2 envelope `message`, when the API sent one. */
|
|
17
|
+
readonly message: string | null;
|
|
18
|
+
/** Rate limit counters, when the API sent all three headers. */
|
|
19
|
+
readonly rateLimit: RateLimit | null;
|
|
20
|
+
/** Response headers with lower-case names. */
|
|
21
|
+
readonly headers: Readonly<Record<string, string>>;
|
|
22
|
+
}
|
|
23
|
+
/** A returned value with its response details on the non-enumerable `meta` property. */
|
|
24
|
+
export type WithMeta<T> = T & {
|
|
25
|
+
readonly meta: ResponseMeta;
|
|
26
|
+
};
|
|
27
|
+
/** Attaches `meta` without making it part of the value's JSON or its enumerable keys. */
|
|
28
|
+
export declare function attachMeta<T extends object>(value: T, meta: ResponseMeta): WithMeta<T>;
|
|
29
|
+
export declare function headersToRecord(headers: Headers | Record<string, string>): Record<string, string>;
|
|
30
|
+
export declare function requestIdFrom(headers: Readonly<Record<string, string>>): string | null;
|
|
31
|
+
export declare function rateLimitFrom(headers: Readonly<Record<string, string>>): RateLimit | null;
|
|
32
|
+
/** Seconds from a `Retry-After` header (delta seconds or HTTP date), or null. */
|
|
33
|
+
export declare function retryAfterFrom(headers: Readonly<Record<string, string>>, now?: number): number | null;
|
|
@@ -0,0 +1,45 @@
|
|
|
1
|
+
/** Attaches `meta` without making it part of the value's JSON or its enumerable keys. */
|
|
2
|
+
export function attachMeta(value, meta) {
|
|
3
|
+
Object.defineProperty(value, 'meta', { value: meta, enumerable: false });
|
|
4
|
+
return value;
|
|
5
|
+
}
|
|
6
|
+
export function headersToRecord(headers) {
|
|
7
|
+
const out = {};
|
|
8
|
+
if (headers instanceof Headers) {
|
|
9
|
+
headers.forEach((value, key) => {
|
|
10
|
+
out[key.toLowerCase()] = value;
|
|
11
|
+
});
|
|
12
|
+
return out;
|
|
13
|
+
}
|
|
14
|
+
for (const [key, value] of Object.entries(headers))
|
|
15
|
+
out[key.toLowerCase()] = value;
|
|
16
|
+
return out;
|
|
17
|
+
}
|
|
18
|
+
export function requestIdFrom(headers) {
|
|
19
|
+
return headers['x-request-id'] || headers['cf-ray'] || null;
|
|
20
|
+
}
|
|
21
|
+
function toInt(value) {
|
|
22
|
+
if (value === undefined || !/^\s*-?\d+\s*$/.test(value))
|
|
23
|
+
return null;
|
|
24
|
+
return Number.parseInt(value, 10);
|
|
25
|
+
}
|
|
26
|
+
export function rateLimitFrom(headers) {
|
|
27
|
+
const limit = toInt(headers['x-ratelimit-limit']);
|
|
28
|
+
const remaining = toInt(headers['x-ratelimit-remaining']);
|
|
29
|
+
const reset = toInt(headers['x-ratelimit-reset']);
|
|
30
|
+
if (limit === null || remaining === null || reset === null)
|
|
31
|
+
return null;
|
|
32
|
+
return { limit, remaining, reset };
|
|
33
|
+
}
|
|
34
|
+
/** Seconds from a `Retry-After` header (delta seconds or HTTP date), or null. */
|
|
35
|
+
export function retryAfterFrom(headers, now = Date.now()) {
|
|
36
|
+
const raw = headers['retry-after']?.trim();
|
|
37
|
+
if (!raw)
|
|
38
|
+
return null;
|
|
39
|
+
if (/^\d+$/.test(raw))
|
|
40
|
+
return Number.parseInt(raw, 10);
|
|
41
|
+
const at = Date.parse(raw);
|
|
42
|
+
if (Number.isNaN(at))
|
|
43
|
+
return null;
|
|
44
|
+
return Math.max(0, Math.ceil((at - now) / 1000));
|
|
45
|
+
}
|
|
@@ -0,0 +1,43 @@
|
|
|
1
|
+
/** What the SDK puts where it removed the API key or an Authorization value. */
|
|
2
|
+
export declare const REDACTED = "[REDACTED]";
|
|
3
|
+
/** Removes one API key. */
|
|
4
|
+
export interface Redactor {
|
|
5
|
+
/**
|
|
6
|
+
* Raw and percent-encoded spans of the key become `[REDACTED]`; if a decoded view
|
|
7
|
+
* of the result still carries the key, the whole text becomes `[REDACTED]`.
|
|
8
|
+
*/
|
|
9
|
+
text(value: string): string;
|
|
10
|
+
/** Whether the text or one of its decoded views contains the key. */
|
|
11
|
+
carries(value: string): boolean;
|
|
12
|
+
}
|
|
13
|
+
export declare const noRedact: Redactor;
|
|
14
|
+
/** `%HH` (either hex case) becomes that byte; runs of bytes are read as UTF-8. */
|
|
15
|
+
export declare function percentDecode(text: string): string;
|
|
16
|
+
/** JSON string unescaping: `\uXXXX` (either hex case) and the short escapes. */
|
|
17
|
+
export declare function jsonUnescape(text: string): string;
|
|
18
|
+
/** Builds the redactor for one API key. Keys shorter than 4 characters are left alone. */
|
|
19
|
+
export declare function redactor(apiKey: string): Redactor;
|
|
20
|
+
/**
|
|
21
|
+
* Authorization and Proxy-Authorization are always `[REDACTED]`; any other value that
|
|
22
|
+
* carries the key becomes `[REDACTED]` as a whole.
|
|
23
|
+
*/
|
|
24
|
+
export declare function redactHeaders(headers: Readonly<Record<string, string>>, redact: Redactor): Record<string, string>;
|
|
25
|
+
/**
|
|
26
|
+
* Applies `text` to every string of a parsed JSON value, object keys included. Returns the
|
|
27
|
+
* same value when nothing changed.
|
|
28
|
+
*/
|
|
29
|
+
export declare function redactJson(value: unknown, redact: Redactor): unknown;
|
|
30
|
+
/**
|
|
31
|
+
* Redaction of a whole body: `body` is `text` parsed as JSON (undefined when it is not JSON). Returns
|
|
32
|
+
* the body that may be shown and the redacted parsed value.
|
|
33
|
+
*/
|
|
34
|
+
export declare function redactBody(text: string, body: unknown, redact: Redactor): {
|
|
35
|
+
rawBody: string;
|
|
36
|
+
body: unknown;
|
|
37
|
+
};
|
|
38
|
+
/**
|
|
39
|
+
* A sanitized copy of a transport failure. It holds the type name, the message after `text`,
|
|
40
|
+
* `code` and `errno` when they are strings or numbers, and the sanitized copy of the
|
|
41
|
+
* original's own cause (at most 3 levels). Never the original or any other property.
|
|
42
|
+
*/
|
|
43
|
+
export declare function sanitizeCause(cause: unknown, redact: Redactor, depth?: number): Error;
|
|
@@ -0,0 +1,198 @@
|
|
|
1
|
+
// Removes the configured API key from everything the SDK takes from a response or a transport
|
|
2
|
+
// error. The key is found by decoding, not by listing encodings.
|
|
3
|
+
/** What the SDK puts where it removed the API key or an Authorization value. */
|
|
4
|
+
export const REDACTED = '[REDACTED]';
|
|
5
|
+
const AUTH_HEADERS = new Set(['authorization', 'proxy-authorization']);
|
|
6
|
+
const MAX_CAUSE_DEPTH = 3;
|
|
7
|
+
export const noRedact = { text: (value) => value, carries: () => false };
|
|
8
|
+
const utf8 = new TextDecoder();
|
|
9
|
+
/** `%HH` (either hex case) becomes that byte; runs of bytes are read as UTF-8. */
|
|
10
|
+
export function percentDecode(text) {
|
|
11
|
+
if (!text.includes('%'))
|
|
12
|
+
return text;
|
|
13
|
+
return text.replace(/(?:%[0-9a-fA-F]{2})+/g, (run) => {
|
|
14
|
+
const bytes = new Uint8Array(run.length / 3);
|
|
15
|
+
for (let i = 0; i < bytes.length; i++) {
|
|
16
|
+
bytes[i] = Number.parseInt(run.slice(i * 3 + 1, i * 3 + 3), 16);
|
|
17
|
+
}
|
|
18
|
+
return utf8.decode(bytes);
|
|
19
|
+
});
|
|
20
|
+
}
|
|
21
|
+
const JSON_ESCAPES = {
|
|
22
|
+
'"': '"',
|
|
23
|
+
'\\': '\\',
|
|
24
|
+
'/': '/',
|
|
25
|
+
b: '\b',
|
|
26
|
+
f: '\f',
|
|
27
|
+
n: '\n',
|
|
28
|
+
r: '\r',
|
|
29
|
+
t: '\t',
|
|
30
|
+
};
|
|
31
|
+
/** JSON string unescaping: `\uXXXX` (either hex case) and the short escapes. */
|
|
32
|
+
export function jsonUnescape(text) {
|
|
33
|
+
if (!text.includes('\\'))
|
|
34
|
+
return text;
|
|
35
|
+
return text.replace(/\\(u[0-9a-fA-F]{4}|["\\/bfnrt])/g, (_, seq) => seq.length === 5
|
|
36
|
+
? String.fromCharCode(Number.parseInt(seq.slice(1), 16))
|
|
37
|
+
: JSON_ESCAPES[seq]);
|
|
38
|
+
}
|
|
39
|
+
/** Matches the key with any subset of its characters percent-encoded, in either hex case. */
|
|
40
|
+
function percentPattern(apiKey) {
|
|
41
|
+
const hex = (byte) => [...byte.toString(16).padStart(2, '0')]
|
|
42
|
+
.map((d) => (/[a-f]/.test(d) ? `[${d}${d.toUpperCase()}]` : d))
|
|
43
|
+
.join('');
|
|
44
|
+
const parts = [...apiKey].map((char) => {
|
|
45
|
+
const literal = char.replace(/[.*+?^${}()|[\]\\/-]/g, '\\$&');
|
|
46
|
+
const encoded = [...new TextEncoder().encode(char)].map((b) => `%${hex(b)}`).join('');
|
|
47
|
+
return `(?:${literal}|${encoded})`;
|
|
48
|
+
});
|
|
49
|
+
return new RegExp(parts.join(''), 'g');
|
|
50
|
+
}
|
|
51
|
+
/** Builds the redactor for one API key. Keys shorter than 4 characters are left alone. */
|
|
52
|
+
export function redactor(apiKey) {
|
|
53
|
+
if (apiKey.length < 4)
|
|
54
|
+
return noRedact;
|
|
55
|
+
const pattern = percentPattern(apiKey);
|
|
56
|
+
const carries = (value) => {
|
|
57
|
+
// The text, its percent-decoding, its JSON unescaping, and each applied to the other,
|
|
58
|
+
// one level deep.
|
|
59
|
+
let views = [value];
|
|
60
|
+
const seen = new Set(views);
|
|
61
|
+
for (let level = 0; level <= 3; level++) {
|
|
62
|
+
if (views.some((view) => view.includes(apiKey)))
|
|
63
|
+
return true;
|
|
64
|
+
const next = [];
|
|
65
|
+
for (const view of views) {
|
|
66
|
+
for (const decoded of [percentDecode(view), jsonUnescape(view)]) {
|
|
67
|
+
if (!seen.has(decoded)) {
|
|
68
|
+
seen.add(decoded);
|
|
69
|
+
next.push(decoded);
|
|
70
|
+
}
|
|
71
|
+
}
|
|
72
|
+
}
|
|
73
|
+
if (next.length === 0)
|
|
74
|
+
return false;
|
|
75
|
+
views = next;
|
|
76
|
+
}
|
|
77
|
+
return false;
|
|
78
|
+
};
|
|
79
|
+
return {
|
|
80
|
+
carries,
|
|
81
|
+
text(value) {
|
|
82
|
+
if (!value)
|
|
83
|
+
return value;
|
|
84
|
+
const out = value.replace(pattern, REDACTED);
|
|
85
|
+
return carries(out) ? REDACTED : out;
|
|
86
|
+
},
|
|
87
|
+
};
|
|
88
|
+
}
|
|
89
|
+
/**
|
|
90
|
+
* Authorization and Proxy-Authorization are always `[REDACTED]`; any other value that
|
|
91
|
+
* carries the key becomes `[REDACTED]` as a whole.
|
|
92
|
+
*/
|
|
93
|
+
export function redactHeaders(headers, redact) {
|
|
94
|
+
const out = {};
|
|
95
|
+
for (const [name, value] of Object.entries(headers)) {
|
|
96
|
+
out[name] = AUTH_HEADERS.has(name.toLowerCase()) || redact.carries(value) ? REDACTED : value;
|
|
97
|
+
}
|
|
98
|
+
return out;
|
|
99
|
+
}
|
|
100
|
+
function defineValue(target, key, value) {
|
|
101
|
+
Object.defineProperty(target, key, {
|
|
102
|
+
value,
|
|
103
|
+
enumerable: true,
|
|
104
|
+
writable: true,
|
|
105
|
+
configurable: true,
|
|
106
|
+
});
|
|
107
|
+
}
|
|
108
|
+
/**
|
|
109
|
+
* Applies `text` to every string of a parsed JSON value, object keys included. Returns the
|
|
110
|
+
* same value when nothing changed.
|
|
111
|
+
*/
|
|
112
|
+
export function redactJson(value, redact) {
|
|
113
|
+
if (typeof value === 'string')
|
|
114
|
+
return redact.text(value);
|
|
115
|
+
if (Array.isArray(value)) {
|
|
116
|
+
const out = value.map((item) => redactJson(item, redact));
|
|
117
|
+
return out.some((item, i) => item !== value[i]) ? out : value;
|
|
118
|
+
}
|
|
119
|
+
if (value === null || typeof value !== 'object')
|
|
120
|
+
return value;
|
|
121
|
+
let changed = false;
|
|
122
|
+
const out = {};
|
|
123
|
+
for (const [key, item] of Object.entries(value)) {
|
|
124
|
+
const safeKey = redact.text(key);
|
|
125
|
+
const safeItem = redactJson(item, redact);
|
|
126
|
+
if (safeKey !== key || safeItem !== item)
|
|
127
|
+
changed = true;
|
|
128
|
+
// defineProperty, so a "__proto__" key stays a plain key
|
|
129
|
+
defineValue(out, safeKey, safeItem);
|
|
130
|
+
}
|
|
131
|
+
return changed ? out : value;
|
|
132
|
+
}
|
|
133
|
+
/**
|
|
134
|
+
* Redaction of a whole body: `body` is `text` parsed as JSON (undefined when it is not JSON). Returns
|
|
135
|
+
* the body that may be shown and the redacted parsed value.
|
|
136
|
+
*/
|
|
137
|
+
export function redactBody(text, body, redact) {
|
|
138
|
+
if (body === undefined)
|
|
139
|
+
return { rawBody: redact.text(text), body };
|
|
140
|
+
const safe = redactJson(body, redact);
|
|
141
|
+
return { rawBody: safe === body ? text : JSON.stringify(safe), body: safe };
|
|
142
|
+
}
|
|
143
|
+
function read(source, key) {
|
|
144
|
+
try {
|
|
145
|
+
return source[key];
|
|
146
|
+
}
|
|
147
|
+
catch {
|
|
148
|
+
return undefined;
|
|
149
|
+
}
|
|
150
|
+
}
|
|
151
|
+
function typeName(source) {
|
|
152
|
+
if (source instanceof Error)
|
|
153
|
+
return String(read(source, 'name') ?? 'Error');
|
|
154
|
+
if (source === null)
|
|
155
|
+
return 'null';
|
|
156
|
+
if (typeof source !== 'object')
|
|
157
|
+
return typeof source;
|
|
158
|
+
const ctor = read(source, 'constructor');
|
|
159
|
+
return typeof ctor?.name === 'string' && ctor.name ? ctor.name : 'Object';
|
|
160
|
+
}
|
|
161
|
+
function messageOf(source) {
|
|
162
|
+
if (typeof source === 'string')
|
|
163
|
+
return source;
|
|
164
|
+
const message = read(source, 'message');
|
|
165
|
+
if (typeof message === 'string')
|
|
166
|
+
return message;
|
|
167
|
+
if (source instanceof Error || (source !== null && typeof source === 'object'))
|
|
168
|
+
return '';
|
|
169
|
+
return String(source);
|
|
170
|
+
}
|
|
171
|
+
/**
|
|
172
|
+
* A sanitized copy of a transport failure. It holds the type name, the message after `text`,
|
|
173
|
+
* `code` and `errno` when they are strings or numbers, and the sanitized copy of the
|
|
174
|
+
* original's own cause (at most 3 levels). Never the original or any other property.
|
|
175
|
+
*/
|
|
176
|
+
export function sanitizeCause(cause, redact, depth = 1) {
|
|
177
|
+
const copy = new Error(redact.text(messageOf(cause)));
|
|
178
|
+
copy.name = redact.text(typeName(cause));
|
|
179
|
+
copy.stack = `${copy.name}: ${copy.message}`;
|
|
180
|
+
for (const field of ['code', 'errno']) {
|
|
181
|
+
const value = cause !== null && typeof cause === 'object' ? read(cause, field) : undefined;
|
|
182
|
+
if (typeof value === 'string')
|
|
183
|
+
defineValue(copy, field, redact.text(value));
|
|
184
|
+
else if (typeof value === 'number') {
|
|
185
|
+
defineValue(copy, field, redact.carries(String(value)) ? REDACTED : value);
|
|
186
|
+
}
|
|
187
|
+
}
|
|
188
|
+
const inner = cause !== null && typeof cause === 'object' ? read(cause, 'cause') : undefined;
|
|
189
|
+
if (inner !== undefined && depth < MAX_CAUSE_DEPTH) {
|
|
190
|
+
Object.defineProperty(copy, 'cause', {
|
|
191
|
+
value: sanitizeCause(inner, redact, depth + 1),
|
|
192
|
+
enumerable: false,
|
|
193
|
+
writable: true,
|
|
194
|
+
configurable: true,
|
|
195
|
+
});
|
|
196
|
+
}
|
|
197
|
+
return copy;
|
|
198
|
+
}
|
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
/** Reads an environment variable, or undefined when the runtime has none or denies access. */
|
|
2
|
+
export declare function readEnv(name: string): string | undefined;
|
|
3
|
+
/** `<runtime>/<version>` for the User-Agent header. */
|
|
4
|
+
export declare function runtimeToken(): string;
|
|
5
|
+
interface FsPromises {
|
|
6
|
+
readFile(path: string | URL): Promise<Uint8Array>;
|
|
7
|
+
stat(path: string | URL): Promise<{
|
|
8
|
+
size: number;
|
|
9
|
+
isFile(): boolean;
|
|
10
|
+
}>;
|
|
11
|
+
}
|
|
12
|
+
/** `node:fs/promises`, or null on runtimes without a file system. */
|
|
13
|
+
export declare function loadFs(): Promise<FsPromises | null>;
|
|
14
|
+
/** Waits `ms` milliseconds; rejects with the signal's reason when it aborts first. */
|
|
15
|
+
export declare function sleep(ms: number, signal?: AbortSignal): Promise<void>;
|
|
16
|
+
export {};
|
|
@@ -0,0 +1,47 @@
|
|
|
1
|
+
// Small runtime probes that work on Node, Bun, Deno and edge runtimes without type packages.
|
|
2
|
+
const g = globalThis;
|
|
3
|
+
/** Reads an environment variable, or undefined when the runtime has none or denies access. */
|
|
4
|
+
export function readEnv(name) {
|
|
5
|
+
try {
|
|
6
|
+
if (g.Deno?.env)
|
|
7
|
+
return g.Deno.env.get(name) || undefined;
|
|
8
|
+
return g.process?.env?.[name] || undefined;
|
|
9
|
+
}
|
|
10
|
+
catch {
|
|
11
|
+
return undefined;
|
|
12
|
+
}
|
|
13
|
+
}
|
|
14
|
+
/** `<runtime>/<version>` for the User-Agent header. */
|
|
15
|
+
export function runtimeToken() {
|
|
16
|
+
if (g.Bun?.version)
|
|
17
|
+
return `bun/${g.Bun.version}`;
|
|
18
|
+
if (g.Deno?.version?.deno)
|
|
19
|
+
return `deno/${g.Deno.version.deno}`;
|
|
20
|
+
if (g.process?.versions?.node)
|
|
21
|
+
return `node/${g.process.versions.node}`;
|
|
22
|
+
return 'edge/unknown';
|
|
23
|
+
}
|
|
24
|
+
let fsPromise;
|
|
25
|
+
/** `node:fs/promises`, or null on runtimes without a file system. */
|
|
26
|
+
export function loadFs() {
|
|
27
|
+
fsPromise ??= import('node:fs/promises').then((mod) => mod.default ?? mod, () => null);
|
|
28
|
+
return fsPromise;
|
|
29
|
+
}
|
|
30
|
+
/** Waits `ms` milliseconds; rejects with the signal's reason when it aborts first. */
|
|
31
|
+
export function sleep(ms, signal) {
|
|
32
|
+
return new Promise((resolve, reject) => {
|
|
33
|
+
if (signal?.aborted) {
|
|
34
|
+
reject(signal.reason);
|
|
35
|
+
return;
|
|
36
|
+
}
|
|
37
|
+
const onAbort = () => {
|
|
38
|
+
clearTimeout(timer);
|
|
39
|
+
reject(signal?.reason);
|
|
40
|
+
};
|
|
41
|
+
const timer = setTimeout(() => {
|
|
42
|
+
signal?.removeEventListener('abort', onAbort);
|
|
43
|
+
resolve();
|
|
44
|
+
}, ms);
|
|
45
|
+
signal?.addEventListener('abort', onAbort, { once: true });
|
|
46
|
+
});
|
|
47
|
+
}
|
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
/** Default hosts, environment variable names and header names the SDK uses. */
|
|
2
|
+
export declare const settings: {
|
|
3
|
+
readonly baseUrls: {
|
|
4
|
+
readonly v1: 'https://api.easyslip.com/v1';
|
|
5
|
+
readonly v2: 'https://api.easyslip.com/v2';
|
|
6
|
+
};
|
|
7
|
+
readonly userAgentProduct: 'easyslip-js';
|
|
8
|
+
readonly webhook: {
|
|
9
|
+
readonly signatureHeader: 'X-EasySlip-Signature';
|
|
10
|
+
readonly signaturePrefix: 'sha256=';
|
|
11
|
+
};
|
|
12
|
+
readonly env: {
|
|
13
|
+
readonly apiKey: 'EASYSLIP_API_KEY';
|
|
14
|
+
readonly apiKeyFile: 'EASYSLIP_API_KEY_FILE';
|
|
15
|
+
readonly webhookSecret: 'EASYSLIP_WEBHOOK_SECRET';
|
|
16
|
+
readonly v1BaseUrl: 'EASYSLIP_V1_BASE_URL';
|
|
17
|
+
readonly v2BaseUrl: 'EASYSLIP_V2_BASE_URL';
|
|
18
|
+
};
|
|
19
|
+
};
|
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
/** Default hosts, environment variable names and header names the SDK uses. */
|
|
2
|
+
export const settings = {
|
|
3
|
+
baseUrls: {
|
|
4
|
+
v1: 'https://api.easyslip.com/v1',
|
|
5
|
+
v2: 'https://api.easyslip.com/v2',
|
|
6
|
+
},
|
|
7
|
+
userAgentProduct: 'easyslip-js',
|
|
8
|
+
webhook: {
|
|
9
|
+
signatureHeader: 'X-EasySlip-Signature',
|
|
10
|
+
signaturePrefix: 'sha256=',
|
|
11
|
+
},
|
|
12
|
+
env: {
|
|
13
|
+
apiKey: 'EASYSLIP_API_KEY',
|
|
14
|
+
apiKeyFile: 'EASYSLIP_API_KEY_FILE',
|
|
15
|
+
webhookSecret: 'EASYSLIP_WEBHOOK_SECRET',
|
|
16
|
+
v1BaseUrl: 'EASYSLIP_V1_BASE_URL',
|
|
17
|
+
v2BaseUrl: 'EASYSLIP_V2_BASE_URL',
|
|
18
|
+
},
|
|
19
|
+
};
|
|
@@ -0,0 +1,6 @@
|
|
|
1
|
+
/** SHA-256 digest of `data`. */
|
|
2
|
+
export declare function sha256(data: Uint8Array): Uint8Array;
|
|
3
|
+
/** HMAC-SHA256 of `message` under `key`. */
|
|
4
|
+
export declare function hmacSha256(key: Uint8Array, message: Uint8Array): Uint8Array;
|
|
5
|
+
/** Lower-case hex of `bytes`. */
|
|
6
|
+
export declare function toHex(bytes: Uint8Array): string;
|