modern-treasury 0.0.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/.eslintrc.js +10 -0
- package/.prettierrc +6 -0
- package/LICENSE +7 -0
- package/README.md +198 -0
- package/build +10 -0
- package/core.ts +746 -0
- package/dist/cjs/core.d.ts +215 -0
- package/dist/cjs/core.js +815 -0
- package/dist/cjs/core.js.map +1 -0
- package/dist/cjs/index.d.ts +118 -0
- package/dist/cjs/index.js +128 -0
- package/dist/cjs/index.js.map +1 -0
- package/dist/cjs/pagination.d.ts +14 -0
- package/dist/cjs/pagination.js +22 -0
- package/dist/cjs/pagination.js.map +1 -0
- package/dist/cjs/resource.d.ts +11 -0
- package/dist/cjs/resource.js +16 -0
- package/dist/cjs/resource.js.map +1 -0
- package/dist/cjs/resources/counterparties.d.ts +500 -0
- package/dist/cjs/resources/counterparties.js +57 -0
- package/dist/cjs/resources/counterparties.js.map +1 -0
- package/dist/cjs/resources/documents.d.ts +66 -0
- package/dist/cjs/resources/documents.js +23 -0
- package/dist/cjs/resources/documents.js.map +1 -0
- package/dist/cjs/resources/events.d.ts +53 -0
- package/dist/cjs/resources/events.js +22 -0
- package/dist/cjs/resources/events.js.map +1 -0
- package/dist/cjs/resources/expected-payments.d.ts +928 -0
- package/dist/cjs/resources/expected-payments.js +31 -0
- package/dist/cjs/resources/expected-payments.js.map +1 -0
- package/dist/cjs/resources/external-accounts.d.ts +597 -0
- package/dist/cjs/resources/external-accounts.js +51 -0
- package/dist/cjs/resources/external-accounts.js.map +1 -0
- package/dist/cjs/resources/incoming-payment-details.d.ts +487 -0
- package/dist/cjs/resources/incoming-payment-details.js +35 -0
- package/dist/cjs/resources/incoming-payment-details.js.map +1 -0
- package/dist/cjs/resources/index.d.ts +15 -0
- package/dist/cjs/resources/index.js +46 -0
- package/dist/cjs/resources/index.js.map +1 -0
- package/dist/cjs/resources/internal-accounts.d.ts +666 -0
- package/dist/cjs/resources/internal-accounts.js +31 -0
- package/dist/cjs/resources/internal-accounts.js.map +1 -0
- package/dist/cjs/resources/line-items.d.ts +90 -0
- package/dist/cjs/resources/line-items.js +38 -0
- package/dist/cjs/resources/line-items.js.map +1 -0
- package/dist/cjs/resources/paper-items.d.ts +279 -0
- package/dist/cjs/resources/paper-items.js +25 -0
- package/dist/cjs/resources/paper-items.js.map +1 -0
- package/dist/cjs/resources/payment-orders/index.d.ts +2 -0
- package/dist/cjs/resources/payment-orders/index.js +33 -0
- package/dist/cjs/resources/payment-orders/index.js.map +1 -0
- package/dist/cjs/resources/payment-orders/payment-orders.d.ts +2180 -0
- package/dist/cjs/resources/payment-orders/payment-orders.js +56 -0
- package/dist/cjs/resources/payment-orders/payment-orders.js.map +1 -0
- package/dist/cjs/resources/payment-orders/reversals.d.ts +46 -0
- package/dist/cjs/resources/payment-orders/reversals.js +23 -0
- package/dist/cjs/resources/payment-orders/reversals.js.map +1 -0
- package/dist/cjs/resources/returns.d.ts +487 -0
- package/dist/cjs/resources/returns.js +31 -0
- package/dist/cjs/resources/returns.js.map +1 -0
- package/dist/cjs/resources/top-level.d.ts +3 -0
- package/dist/cjs/resources/top-level.js +4 -0
- package/dist/cjs/resources/top-level.js.map +1 -0
- package/dist/cjs/resources/transactions.d.ts +377 -0
- package/dist/cjs/resources/transactions.js +31 -0
- package/dist/cjs/resources/transactions.js.map +1 -0
- package/dist/cjs/resources/validations.d.ts +97 -0
- package/dist/cjs/resources/validations.js +16 -0
- package/dist/cjs/resources/validations.js.map +1 -0
- package/dist/cjs/resources/webhooks.d.ts +31 -0
- package/dist/cjs/resources/webhooks.js +44 -0
- package/dist/cjs/resources/webhooks.js.map +1 -0
- package/dist/cjs/tests/api-resources/counterparties.test.d.ts +1 -0
- package/dist/cjs/tests/api-resources/counterparties.test.js +275 -0
- package/dist/cjs/tests/api-resources/counterparties.test.js.map +1 -0
- package/dist/cjs/tests/api-resources/documents.test.d.ts +1 -0
- package/dist/cjs/tests/api-resources/documents.test.js +78 -0
- package/dist/cjs/tests/api-resources/documents.test.js.map +1 -0
- package/dist/cjs/tests/api-resources/events.test.d.ts +1 -0
- package/dist/cjs/tests/api-resources/events.test.js +100 -0
- package/dist/cjs/tests/api-resources/events.test.js.map +1 -0
- package/dist/cjs/tests/api-resources/expected-payments.test.d.ts +1 -0
- package/dist/cjs/tests/api-resources/expected-payments.test.js +176 -0
- package/dist/cjs/tests/api-resources/expected-payments.test.js.map +1 -0
- package/dist/cjs/tests/api-resources/external-accounts.test.d.ts +1 -0
- package/dist/cjs/tests/api-resources/external-accounts.test.js +248 -0
- package/dist/cjs/tests/api-resources/external-accounts.test.js.map +1 -0
- package/dist/cjs/tests/api-resources/incoming-payment-details.test.d.ts +1 -0
- package/dist/cjs/tests/api-resources/incoming-payment-details.test.js +130 -0
- package/dist/cjs/tests/api-resources/incoming-payment-details.test.js.map +1 -0
- package/dist/cjs/tests/api-resources/internal-accounts.test.d.ts +1 -0
- package/dist/cjs/tests/api-resources/internal-accounts.test.js +144 -0
- package/dist/cjs/tests/api-resources/internal-accounts.test.js.map +1 -0
- package/dist/cjs/tests/api-resources/line-items.test.d.ts +1 -0
- package/dist/cjs/tests/api-resources/line-items.test.js +123 -0
- package/dist/cjs/tests/api-resources/line-items.test.js.map +1 -0
- package/dist/cjs/tests/api-resources/paper-items.test.d.ts +1 -0
- package/dist/cjs/tests/api-resources/paper-items.test.js +96 -0
- package/dist/cjs/tests/api-resources/paper-items.test.js.map +1 -0
- package/dist/cjs/tests/api-resources/payment-orders/payment-orders.test.d.ts +1 -0
- package/dist/cjs/tests/api-resources/payment-orders/payment-orders.test.js +77 -0
- package/dist/cjs/tests/api-resources/payment-orders/payment-orders.test.js.map +1 -0
- package/dist/cjs/tests/api-resources/returns.test.d.ts +1 -0
- package/dist/cjs/tests/api-resources/returns.test.js +116 -0
- package/dist/cjs/tests/api-resources/returns.test.js.map +1 -0
- package/dist/cjs/tests/api-resources/top-level.test.d.ts +1 -0
- package/dist/cjs/tests/api-resources/top-level.test.js +59 -0
- package/dist/cjs/tests/api-resources/top-level.test.js.map +1 -0
- package/dist/cjs/tests/api-resources/transactions.test.d.ts +1 -0
- package/dist/cjs/tests/api-resources/transactions.test.js +134 -0
- package/dist/cjs/tests/api-resources/transactions.test.js.map +1 -0
- package/dist/cjs/tests/api-resources/validations.test.d.ts +1 -0
- package/dist/cjs/tests/api-resources/validations.test.js +62 -0
- package/dist/cjs/tests/api-resources/validations.test.js.map +1 -0
- package/dist/cjs/tests/api-resources/webhooks.test.d.ts +1 -0
- package/dist/cjs/tests/api-resources/webhooks.test.js +100 -0
- package/dist/cjs/tests/api-resources/webhooks.test.js.map +1 -0
- package/dist/cjs/tests/form.test.d.ts +1 -0
- package/dist/cjs/tests/form.test.js +61 -0
- package/dist/cjs/tests/form.test.js.map +1 -0
- package/dist/cjs/tests/index.test.d.ts +1 -0
- package/dist/cjs/tests/index.test.js +57 -0
- package/dist/cjs/tests/index.test.js.map +1 -0
- package/dist/cjs/tests/responses.test.d.ts +1 -0
- package/dist/cjs/tests/responses.test.js +60 -0
- package/dist/cjs/tests/responses.test.js.map +1 -0
- package/index.ts +175 -0
- package/jest.config.js +8 -0
- package/package.json +47 -0
- package/pagination.ts +36 -0
- package/resource.ts +22 -0
- package/resources/counterparties.ts +666 -0
- package/resources/documents.ts +97 -0
- package/resources/events.ts +86 -0
- package/resources/expected-payments.ts +1016 -0
- package/resources/external-accounts.ts +762 -0
- package/resources/incoming-payment-details.ts +592 -0
- package/resources/index.ts +16 -0
- package/resources/internal-accounts.ts +774 -0
- package/resources/line-items.ts +138 -0
- package/resources/paper-items.ts +317 -0
- package/resources/payment-orders/index.ts +3 -0
- package/resources/payment-orders/payment-orders.ts +2486 -0
- package/resources/payment-orders/reversals.ts +72 -0
- package/resources/returns.ts +545 -0
- package/resources/top-level.ts +5 -0
- package/resources/transactions.ts +441 -0
- package/resources/validations.ts +115 -0
- package/resources/webhooks.ts +48 -0
- package/tests/api-resources/counterparties.test.ts +237 -0
- package/tests/api-resources/documents.test.ts +40 -0
- package/tests/api-resources/events.test.ts +62 -0
- package/tests/api-resources/expected-payments.test.ts +138 -0
- package/tests/api-resources/external-accounts.test.ts +210 -0
- package/tests/api-resources/incoming-payment-details.test.ts +92 -0
- package/tests/api-resources/internal-accounts.test.ts +103 -0
- package/tests/api-resources/line-items.test.ts +85 -0
- package/tests/api-resources/paper-items.test.ts +58 -0
- package/tests/api-resources/payment-orders/payment-orders.test.ts +39 -0
- package/tests/api-resources/returns.test.ts +78 -0
- package/tests/api-resources/top-level.test.ts +21 -0
- package/tests/api-resources/transactions.test.ts +96 -0
- package/tests/api-resources/validations.test.ts +24 -0
- package/tests/api-resources/webhooks.test.ts +102 -0
- package/tests/form.test.ts +27 -0
- package/tests/index.test.ts +62 -0
- package/tests/responses.test.ts +25 -0
- package/tsconfig.cjs.json +8 -0
- package/tsconfig.json +36 -0
package/core.ts
ADDED
|
@@ -0,0 +1,746 @@
|
|
|
1
|
+
import qs from 'qs';
|
|
2
|
+
import pkgUp from 'pkg-up';
|
|
3
|
+
|
|
4
|
+
import type { Agent } from 'http';
|
|
5
|
+
import type NodeFetch from 'node-fetch';
|
|
6
|
+
import type { RequestInfo, RequestInit, Response } from 'node-fetch';
|
|
7
|
+
import type KeepAliveAgent from 'agentkeepalive';
|
|
8
|
+
import { AbortController } from 'abort-controller';
|
|
9
|
+
import { FormData, File, Blob } from 'formdata-node';
|
|
10
|
+
import { FormDataEncoder } from 'form-data-encoder';
|
|
11
|
+
|
|
12
|
+
import { Readable } from 'stream';
|
|
13
|
+
|
|
14
|
+
const isNode = typeof process !== 'undefined';
|
|
15
|
+
let nodeFetch: typeof NodeFetch | undefined = undefined;
|
|
16
|
+
let getDefaultAgent = (_url: string): Agent | undefined => undefined;
|
|
17
|
+
if (isNode) {
|
|
18
|
+
/* eslint-disable @typescript-eslint/no-var-requires */
|
|
19
|
+
nodeFetch = require('node-fetch');
|
|
20
|
+
const HttpAgent: typeof KeepAliveAgent = require('agentkeepalive');
|
|
21
|
+
const HttpsAgent = HttpAgent.HttpsAgent;
|
|
22
|
+
/* eslint-enable @typescript-eslint/no-var-requires */
|
|
23
|
+
|
|
24
|
+
const defaultHttpAgent = new HttpAgent({ keepAlive: true });
|
|
25
|
+
const defaultHttpsAgent = new HttpsAgent({ keepAlive: true });
|
|
26
|
+
getDefaultAgent = (url: string) => (url.startsWith('https') ? defaultHttpsAgent : defaultHttpAgent);
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
const DEFAULT_MAX_RETRIES = 2;
|
|
30
|
+
const DEFAULT_TIMEOUT = 60 * 1000; // 60s
|
|
31
|
+
|
|
32
|
+
export abstract class APIClient {
|
|
33
|
+
apiKey: string | null;
|
|
34
|
+
baseURL: string;
|
|
35
|
+
maxRetries: number;
|
|
36
|
+
timeout: number;
|
|
37
|
+
httpAgent: Agent | undefined;
|
|
38
|
+
|
|
39
|
+
private fetch: typeof NodeFetch;
|
|
40
|
+
protected idempotencyHeader?: string;
|
|
41
|
+
|
|
42
|
+
constructor({
|
|
43
|
+
apiKey,
|
|
44
|
+
baseURL,
|
|
45
|
+
maxRetries = DEFAULT_MAX_RETRIES,
|
|
46
|
+
timeout = DEFAULT_TIMEOUT,
|
|
47
|
+
httpAgent,
|
|
48
|
+
}: {
|
|
49
|
+
apiKey: string | null;
|
|
50
|
+
baseURL: string;
|
|
51
|
+
maxRetries?: number;
|
|
52
|
+
timeout: number | undefined;
|
|
53
|
+
httpAgent: Agent | undefined;
|
|
54
|
+
}) {
|
|
55
|
+
this.apiKey = apiKey;
|
|
56
|
+
this.baseURL = baseURL;
|
|
57
|
+
this.maxRetries = validatePositiveInteger('maxRetries', maxRetries);
|
|
58
|
+
this.timeout = validatePositiveInteger('timeout', timeout);
|
|
59
|
+
this.httpAgent = httpAgent;
|
|
60
|
+
|
|
61
|
+
if (isNode) {
|
|
62
|
+
this.fetch = nodeFetch!;
|
|
63
|
+
} else {
|
|
64
|
+
// For other environments, use a global fetch function expected to already be present
|
|
65
|
+
if (typeof fetch === 'undefined' || typeof fetch !== 'function') {
|
|
66
|
+
throw new Error(
|
|
67
|
+
`Unexpected; running in a non-Node environment without a global "fetch" function defined.`,
|
|
68
|
+
);
|
|
69
|
+
}
|
|
70
|
+
// For now, we just pretend that Fetch is the same type as NodeFetch.
|
|
71
|
+
this.fetch = fetch as unknown as typeof NodeFetch;
|
|
72
|
+
}
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
protected authHeaders(): Headers {
|
|
76
|
+
return {};
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
/**
|
|
80
|
+
* Override this to add your own default headers, for example:
|
|
81
|
+
*
|
|
82
|
+
* {
|
|
83
|
+
* ...super.defaultHeaders(),
|
|
84
|
+
* Authorization: 'Bearer 123',
|
|
85
|
+
* }
|
|
86
|
+
*/
|
|
87
|
+
protected defaultHeaders(): Headers {
|
|
88
|
+
return {
|
|
89
|
+
Accept: 'application/json',
|
|
90
|
+
'Content-Type': 'application/json',
|
|
91
|
+
'User-Agent': this.getUserAgent(),
|
|
92
|
+
'X-Stainless-Client-User-Agent': getPlatformPropertiesJSON(),
|
|
93
|
+
...this.authHeaders(),
|
|
94
|
+
};
|
|
95
|
+
}
|
|
96
|
+
|
|
97
|
+
/**
|
|
98
|
+
* Override this to add your own qs.stringify options, for example:
|
|
99
|
+
*
|
|
100
|
+
* {
|
|
101
|
+
* ...super.qsOptions(),
|
|
102
|
+
* strictNullHandling: true,
|
|
103
|
+
* }
|
|
104
|
+
*/
|
|
105
|
+
protected qsOptions(): qs.IStringifyOptions | undefined {
|
|
106
|
+
return {};
|
|
107
|
+
}
|
|
108
|
+
|
|
109
|
+
protected defaultIdempotencyKey(): string {
|
|
110
|
+
return `stainless-node-retry-${uuid4()}`;
|
|
111
|
+
}
|
|
112
|
+
|
|
113
|
+
get<Req, Rsp>(path: string, opts?: RequestOptions<Req>): Promise<Rsp> {
|
|
114
|
+
return this.request({ method: 'get', path, ...opts });
|
|
115
|
+
}
|
|
116
|
+
post<Req, Rsp>(path: string, opts?: RequestOptions<Req>): Promise<Rsp> {
|
|
117
|
+
return this.request({ method: 'post', path, ...opts });
|
|
118
|
+
}
|
|
119
|
+
patch<Req, Rsp>(path: string, opts?: RequestOptions<Req>): Promise<Rsp> {
|
|
120
|
+
return this.request({ method: 'patch', path, ...opts });
|
|
121
|
+
}
|
|
122
|
+
put<Req, Rsp>(path: string, opts?: RequestOptions<Req>): Promise<Rsp> {
|
|
123
|
+
return this.request({ method: 'put', path, ...opts });
|
|
124
|
+
}
|
|
125
|
+
delete<Req, Rsp>(path: string, opts?: RequestOptions<Req>): Promise<Rsp> {
|
|
126
|
+
return this.request({ method: 'delete', path, ...opts });
|
|
127
|
+
}
|
|
128
|
+
|
|
129
|
+
getAPIList<Item, PageClass extends AbstractPage<Item> = AbstractPage<Item>>(
|
|
130
|
+
path: string,
|
|
131
|
+
Page: new (...args: any[]) => PageClass,
|
|
132
|
+
opts?: RequestOptions<any>,
|
|
133
|
+
): PagePromise<PageClass> {
|
|
134
|
+
return this.requestAPIList(Page, { method: 'get', path, ...opts });
|
|
135
|
+
}
|
|
136
|
+
|
|
137
|
+
async request<Req, Rsp>(
|
|
138
|
+
options: FinalRequestOptions<Req>,
|
|
139
|
+
retriesRemaining = options.maxRetries ?? this.maxRetries,
|
|
140
|
+
): Promise<APIResponse<Rsp>> {
|
|
141
|
+
const { method, path, query, headers: headers = {} } = options;
|
|
142
|
+
const body =
|
|
143
|
+
options.body instanceof Readable
|
|
144
|
+
? options.body
|
|
145
|
+
: options.body
|
|
146
|
+
? JSON.stringify(options.body, null, 2)
|
|
147
|
+
: null;
|
|
148
|
+
const contentLength = typeof body === 'string' ? body.length.toString() : null;
|
|
149
|
+
|
|
150
|
+
const url = this.buildURL(path!, query);
|
|
151
|
+
const httpAgent = options.httpAgent ?? this.httpAgent ?? getDefaultAgent(url);
|
|
152
|
+
const timeout = options.timeout ?? this.timeout;
|
|
153
|
+
validatePositiveInteger('timeout', timeout);
|
|
154
|
+
|
|
155
|
+
if (this.idempotencyHeader && method !== 'get') {
|
|
156
|
+
if (!options.idempotencyKey) options.idempotencyKey = this.defaultIdempotencyKey();
|
|
157
|
+
headers[this.idempotencyHeader] = options.idempotencyKey;
|
|
158
|
+
}
|
|
159
|
+
|
|
160
|
+
const req: RequestInit = {
|
|
161
|
+
method,
|
|
162
|
+
...(body && { body }),
|
|
163
|
+
headers: {
|
|
164
|
+
...(contentLength && { 'Content-Length': contentLength }),
|
|
165
|
+
...this.defaultHeaders(),
|
|
166
|
+
...headers,
|
|
167
|
+
},
|
|
168
|
+
...(httpAgent && { agent: httpAgent }),
|
|
169
|
+
};
|
|
170
|
+
|
|
171
|
+
this.debug('request', url, options, req.headers);
|
|
172
|
+
|
|
173
|
+
const response = await this.fetchWithTimeout(url, req, timeout).catch(castToError);
|
|
174
|
+
|
|
175
|
+
if (response instanceof Error) {
|
|
176
|
+
if (retriesRemaining) return this.retryRequest(options, retriesRemaining);
|
|
177
|
+
if (response.name === 'AbortError') throw new APIConnectionTimeoutError();
|
|
178
|
+
throw new APIConnectionError({ cause: response });
|
|
179
|
+
}
|
|
180
|
+
|
|
181
|
+
const responseHeaders = createResponseHeaders(response.headers);
|
|
182
|
+
|
|
183
|
+
if (!response.ok) {
|
|
184
|
+
if (retriesRemaining && this.shouldRetry(response)) {
|
|
185
|
+
return this.retryRequest(options, retriesRemaining, responseHeaders);
|
|
186
|
+
}
|
|
187
|
+
|
|
188
|
+
const errText = await response.text().catch(() => 'Unknown');
|
|
189
|
+
const errJSON = safeJSON(errText);
|
|
190
|
+
const errMessage = errJSON ? undefined : errText;
|
|
191
|
+
|
|
192
|
+
this.debug('response', response.status, url, responseHeaders, errMessage);
|
|
193
|
+
|
|
194
|
+
const err = APIError.generate(response.status, errJSON, errMessage, responseHeaders);
|
|
195
|
+
|
|
196
|
+
throw err;
|
|
197
|
+
}
|
|
198
|
+
|
|
199
|
+
const contentType = response.headers.get('content-type');
|
|
200
|
+
if (contentType?.includes('application/json')) {
|
|
201
|
+
const json = await response.json();
|
|
202
|
+
|
|
203
|
+
Object.defineProperty(json, 'responseHeaders', {
|
|
204
|
+
enumerable: false,
|
|
205
|
+
writable: false,
|
|
206
|
+
value: responseHeaders,
|
|
207
|
+
});
|
|
208
|
+
|
|
209
|
+
this.debug('response', response.status, url, responseHeaders, json);
|
|
210
|
+
|
|
211
|
+
return json as APIResponse<Rsp>;
|
|
212
|
+
} else {
|
|
213
|
+
// TODO handle blob, arraybuffer, other content types, etc.
|
|
214
|
+
const text = response.text();
|
|
215
|
+
this.debug('response', response.status, url, responseHeaders, text);
|
|
216
|
+
return text as Promise<any>;
|
|
217
|
+
}
|
|
218
|
+
}
|
|
219
|
+
|
|
220
|
+
requestAPIList<Item = unknown, PageClass extends AbstractPage<Item> = AbstractPage<Item>>(
|
|
221
|
+
Page: new (...args: ConstructorParameters<typeof AbstractPage>) => PageClass,
|
|
222
|
+
options: FinalRequestOptions,
|
|
223
|
+
): PagePromise<PageClass> {
|
|
224
|
+
const requestPromise = this.request(options) as Promise<APIResponse<unknown>>;
|
|
225
|
+
return new PagePromise(this, requestPromise, options, Page);
|
|
226
|
+
}
|
|
227
|
+
|
|
228
|
+
buildURL<Req>(path: string, query: Req | undefined): string {
|
|
229
|
+
const url = isAbsoluteURL(path) ? new URL(path) : new URL(this.baseURL + path);
|
|
230
|
+
|
|
231
|
+
if (query) {
|
|
232
|
+
url.search = qs.stringify(query, this.qsOptions());
|
|
233
|
+
}
|
|
234
|
+
|
|
235
|
+
return url.toString();
|
|
236
|
+
}
|
|
237
|
+
|
|
238
|
+
async fetchWithTimeout(url: RequestInfo, { signal, ...options }: RequestInit = {}, ms: number) {
|
|
239
|
+
const controller = new AbortController();
|
|
240
|
+
if (signal) signal.addEventListener('abort', controller.abort);
|
|
241
|
+
|
|
242
|
+
const timeout = setTimeout(() => controller.abort(), ms);
|
|
243
|
+
|
|
244
|
+
return this.fetch(url, { signal: controller.signal as any, ...options }).finally(() => {
|
|
245
|
+
clearTimeout(timeout);
|
|
246
|
+
});
|
|
247
|
+
}
|
|
248
|
+
|
|
249
|
+
private shouldRetry(response: Response): boolean {
|
|
250
|
+
// Note this is not a standard header.
|
|
251
|
+
const shouldRetryHeader = response.headers.get('x-should-retry');
|
|
252
|
+
|
|
253
|
+
// If the server explicitly says whether or not to retry, obey.
|
|
254
|
+
if (shouldRetryHeader === 'true') return true;
|
|
255
|
+
if (shouldRetryHeader === 'false') return false;
|
|
256
|
+
|
|
257
|
+
// Retry on lock timeouts.
|
|
258
|
+
if (response.status === 409) return true;
|
|
259
|
+
|
|
260
|
+
// Retry on rate limits.
|
|
261
|
+
if (response.status === 429) return true;
|
|
262
|
+
|
|
263
|
+
// Retry internal errors.
|
|
264
|
+
if (response.status >= 500) return true;
|
|
265
|
+
|
|
266
|
+
return false;
|
|
267
|
+
}
|
|
268
|
+
|
|
269
|
+
private async retryRequest<Req, Rsp>(
|
|
270
|
+
options: FinalRequestOptions<Req>,
|
|
271
|
+
retriesRemaining: number,
|
|
272
|
+
responseHeaders?: Headers | undefined,
|
|
273
|
+
): Promise<Rsp> {
|
|
274
|
+
retriesRemaining -= 1;
|
|
275
|
+
|
|
276
|
+
// About the Retry-After header: https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Retry-After
|
|
277
|
+
//
|
|
278
|
+
// TODO: we may want to handle the case where the header is using the http-date syntax: "Retry-After: <http-date>".
|
|
279
|
+
// See https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Retry-After#syntax for details.
|
|
280
|
+
const retryAfter = parseInt(responseHeaders?.['retry-after'] || '');
|
|
281
|
+
|
|
282
|
+
const maxRetries = options.maxRetries ?? this.maxRetries;
|
|
283
|
+
const timeout = this.calculateRetryTimeoutSeconds(retriesRemaining, retryAfter, maxRetries) * 1000;
|
|
284
|
+
await sleep(timeout);
|
|
285
|
+
|
|
286
|
+
return this.request(options, retriesRemaining);
|
|
287
|
+
}
|
|
288
|
+
|
|
289
|
+
private calculateRetryTimeoutSeconds(
|
|
290
|
+
retriesRemaining: number,
|
|
291
|
+
retryAfter: number,
|
|
292
|
+
maxRetries: number,
|
|
293
|
+
): number {
|
|
294
|
+
const initialRetryDelay = 0.5;
|
|
295
|
+
const maxRetryDelay = 2;
|
|
296
|
+
|
|
297
|
+
// If the API asks us to wait a certain amount of time (and it's a reasonable amount),
|
|
298
|
+
// just do what it says.
|
|
299
|
+
if (Number.isInteger(retryAfter) && retryAfter <= 60) {
|
|
300
|
+
return retryAfter;
|
|
301
|
+
}
|
|
302
|
+
|
|
303
|
+
const numRetries = maxRetries - retriesRemaining;
|
|
304
|
+
|
|
305
|
+
// Apply exponential backoff, but not more than the max.
|
|
306
|
+
const sleepSeconds = Math.min(initialRetryDelay * Math.pow(numRetries - 1, 2), maxRetryDelay);
|
|
307
|
+
|
|
308
|
+
// Apply some jitter, plus-or-minus half a second.
|
|
309
|
+
const jitter = Math.random() - 0.5;
|
|
310
|
+
|
|
311
|
+
return sleepSeconds + jitter;
|
|
312
|
+
}
|
|
313
|
+
|
|
314
|
+
private getUserAgent(): string {
|
|
315
|
+
const packageVersion = getPackageVersion();
|
|
316
|
+
return `${this.constructor.name}/JS ${packageVersion}`;
|
|
317
|
+
}
|
|
318
|
+
|
|
319
|
+
private debug(action: string, ...args: any[]) {
|
|
320
|
+
if (process.env['DEBUG'] === 'true') {
|
|
321
|
+
console.log(`${this.constructor.name}:DEBUG:${action}`, ...args);
|
|
322
|
+
}
|
|
323
|
+
}
|
|
324
|
+
}
|
|
325
|
+
|
|
326
|
+
export class APIResource {
|
|
327
|
+
protected client: APIClient;
|
|
328
|
+
constructor(client: APIClient) {
|
|
329
|
+
this.client = client;
|
|
330
|
+
|
|
331
|
+
this.get = client.get.bind(client);
|
|
332
|
+
this.post = client.post.bind(client);
|
|
333
|
+
this.patch = client.patch.bind(client);
|
|
334
|
+
this.put = client.put.bind(client);
|
|
335
|
+
this.delete = client.delete.bind(client);
|
|
336
|
+
this.getAPIList = client.getAPIList.bind(client);
|
|
337
|
+
}
|
|
338
|
+
|
|
339
|
+
protected get: APIClient['get'];
|
|
340
|
+
protected post: APIClient['post'];
|
|
341
|
+
protected patch: APIClient['patch'];
|
|
342
|
+
protected put: APIClient['put'];
|
|
343
|
+
protected delete: APIClient['delete'];
|
|
344
|
+
protected getAPIList: APIClient['getAPIList'];
|
|
345
|
+
}
|
|
346
|
+
|
|
347
|
+
export abstract class AbstractPage<Item> implements AsyncIterable<Item> {
|
|
348
|
+
#client: APIClient;
|
|
349
|
+
protected options: FinalRequestOptions;
|
|
350
|
+
|
|
351
|
+
constructor(client: APIClient, response: APIResponse<unknown>, options: FinalRequestOptions) {
|
|
352
|
+
this.#client = client;
|
|
353
|
+
this.options = options;
|
|
354
|
+
}
|
|
355
|
+
|
|
356
|
+
abstract nextPageParams(): Partial<Record<string, unknown>> | null;
|
|
357
|
+
|
|
358
|
+
abstract getPaginatedItems(): Item[];
|
|
359
|
+
|
|
360
|
+
hasNextPage(): boolean {
|
|
361
|
+
const items = this.getPaginatedItems();
|
|
362
|
+
if (!items.length) return false;
|
|
363
|
+
return this.nextPageParams() != null;
|
|
364
|
+
}
|
|
365
|
+
|
|
366
|
+
async getNextPage(): Promise<AbstractPage<Item>> {
|
|
367
|
+
const nextQuery = this.nextPageParams();
|
|
368
|
+
if (!nextQuery) {
|
|
369
|
+
throw new Error(
|
|
370
|
+
'No next page expected; please check `.hasNextPage()` before calling `.getNextPage()`.',
|
|
371
|
+
);
|
|
372
|
+
}
|
|
373
|
+
const nextOptions = { ...this.options, query: { ...this.options.query, ...nextQuery } };
|
|
374
|
+
return await this.#client.requestAPIList(this.constructor as any, nextOptions);
|
|
375
|
+
}
|
|
376
|
+
|
|
377
|
+
async *iterPages() {
|
|
378
|
+
// eslint-disable-next-line @typescript-eslint/no-this-alias
|
|
379
|
+
let page: AbstractPage<Item> = this;
|
|
380
|
+
yield page;
|
|
381
|
+
while (page.hasNextPage()) {
|
|
382
|
+
page = await page.getNextPage();
|
|
383
|
+
yield page;
|
|
384
|
+
}
|
|
385
|
+
}
|
|
386
|
+
|
|
387
|
+
async *[Symbol.asyncIterator]() {
|
|
388
|
+
for await (const page of this.iterPages()) {
|
|
389
|
+
for (const item of page.getPaginatedItems()) {
|
|
390
|
+
yield item;
|
|
391
|
+
}
|
|
392
|
+
}
|
|
393
|
+
}
|
|
394
|
+
}
|
|
395
|
+
|
|
396
|
+
export class PagePromise<
|
|
397
|
+
PageClass extends AbstractPage<Item>,
|
|
398
|
+
Item = ReturnType<PageClass['getPaginatedItems']>[number],
|
|
399
|
+
>
|
|
400
|
+
extends Promise<PageClass>
|
|
401
|
+
implements AsyncIterable<Item>
|
|
402
|
+
{
|
|
403
|
+
/**
|
|
404
|
+
* This subclass of Promise will resolve to an instantiated Page once the request completes.
|
|
405
|
+
*/
|
|
406
|
+
constructor(
|
|
407
|
+
client: APIClient,
|
|
408
|
+
requestPromise: Promise<APIResponse<unknown>>,
|
|
409
|
+
options: FinalRequestOptions,
|
|
410
|
+
Page: new (...args: ConstructorParameters<typeof AbstractPage>) => PageClass,
|
|
411
|
+
) {
|
|
412
|
+
super((resolve, reject) =>
|
|
413
|
+
requestPromise.then((response) => resolve(new Page(client, response, options))).catch(reject),
|
|
414
|
+
);
|
|
415
|
+
}
|
|
416
|
+
|
|
417
|
+
/**
|
|
418
|
+
* Enable subclassing Promise.
|
|
419
|
+
* Ref: https://stackoverflow.com/a/60328122
|
|
420
|
+
*/
|
|
421
|
+
static get [Symbol.species]() {
|
|
422
|
+
return Promise;
|
|
423
|
+
}
|
|
424
|
+
|
|
425
|
+
/**
|
|
426
|
+
* Allow auto-paginating iteration on an unawaited list call, eg:
|
|
427
|
+
*
|
|
428
|
+
* for await (const item of client.items.list()) {
|
|
429
|
+
* console.log(item)
|
|
430
|
+
* }
|
|
431
|
+
*/
|
|
432
|
+
async *[Symbol.asyncIterator]() {
|
|
433
|
+
const page = await this;
|
|
434
|
+
for await (const item of page) {
|
|
435
|
+
yield item;
|
|
436
|
+
}
|
|
437
|
+
}
|
|
438
|
+
}
|
|
439
|
+
|
|
440
|
+
export const createResponseHeaders = (
|
|
441
|
+
headers: Awaited<ReturnType<typeof NodeFetch>>['headers'],
|
|
442
|
+
): Record<string, string> => {
|
|
443
|
+
return new Proxy(Object.fromEntries(headers.entries()), {
|
|
444
|
+
get(target, name) {
|
|
445
|
+
const key = name.toString();
|
|
446
|
+
return target[key.toLowerCase()] || target[key];
|
|
447
|
+
},
|
|
448
|
+
});
|
|
449
|
+
};
|
|
450
|
+
|
|
451
|
+
type HTTPMethod = 'get' | 'post' | 'put' | 'patch' | 'delete';
|
|
452
|
+
|
|
453
|
+
export type Headers = Record<string, string | null | undefined>;
|
|
454
|
+
export type KeysEnum<T> = { [P in keyof Required<T>]: true };
|
|
455
|
+
|
|
456
|
+
export type RequestOptions<Req extends {} = Record<string, unknown> | Readable> = {
|
|
457
|
+
method?: HTTPMethod;
|
|
458
|
+
path?: string;
|
|
459
|
+
query?: Req | undefined;
|
|
460
|
+
body?: Req | undefined;
|
|
461
|
+
headers?: Headers | undefined;
|
|
462
|
+
|
|
463
|
+
maxRetries?: number;
|
|
464
|
+
timeout?: number;
|
|
465
|
+
httpAgent?: Agent;
|
|
466
|
+
};
|
|
467
|
+
|
|
468
|
+
// This is required so that we can determine if a given object matches the RequestOptions
|
|
469
|
+
// type at runtime. While this requires duplication, it is enforced by the TypeScript
|
|
470
|
+
// compiler such that any missing / extraneous keys will cause an error.
|
|
471
|
+
const requestOptionsKeys: KeysEnum<RequestOptions> = {
|
|
472
|
+
method: true,
|
|
473
|
+
path: true,
|
|
474
|
+
query: true,
|
|
475
|
+
body: true,
|
|
476
|
+
headers: true,
|
|
477
|
+
|
|
478
|
+
maxRetries: true,
|
|
479
|
+
timeout: true,
|
|
480
|
+
httpAgent: true,
|
|
481
|
+
};
|
|
482
|
+
|
|
483
|
+
export const isRequestOptions = (obj: unknown): obj is RequestOptions => {
|
|
484
|
+
return (
|
|
485
|
+
typeof obj === 'object' &&
|
|
486
|
+
obj !== null &&
|
|
487
|
+
!isEmptyObj(obj) &&
|
|
488
|
+
Object.keys(obj).every((k) => hasOwn(requestOptionsKeys, k))
|
|
489
|
+
);
|
|
490
|
+
};
|
|
491
|
+
|
|
492
|
+
export type FinalRequestOptions<Req extends {} = Record<string, unknown> | Readable> = RequestOptions<Req> & {
|
|
493
|
+
method: HTTPMethod;
|
|
494
|
+
path: string;
|
|
495
|
+
idempotencyKey?: string;
|
|
496
|
+
};
|
|
497
|
+
|
|
498
|
+
export type APIResponse<T> = T & {
|
|
499
|
+
responseHeaders: Headers;
|
|
500
|
+
};
|
|
501
|
+
|
|
502
|
+
export class APIError extends Error {
|
|
503
|
+
readonly status: number | undefined;
|
|
504
|
+
readonly headers: Headers | undefined;
|
|
505
|
+
readonly error: Object | undefined;
|
|
506
|
+
|
|
507
|
+
constructor(
|
|
508
|
+
status: number | undefined,
|
|
509
|
+
error: Object | undefined,
|
|
510
|
+
message: string | undefined,
|
|
511
|
+
headers: Headers | undefined,
|
|
512
|
+
) {
|
|
513
|
+
super(message || (error as any)?.message);
|
|
514
|
+
this.status = status;
|
|
515
|
+
this.headers = headers;
|
|
516
|
+
this.error = error;
|
|
517
|
+
}
|
|
518
|
+
|
|
519
|
+
static generate(
|
|
520
|
+
status: number | undefined,
|
|
521
|
+
error: Object | undefined,
|
|
522
|
+
message: string | undefined,
|
|
523
|
+
headers: Headers | undefined,
|
|
524
|
+
) {
|
|
525
|
+
if (!status) return new APIConnectionError({ cause: castToError(error) });
|
|
526
|
+
|
|
527
|
+
if (status === 400) return new BadRequestError(status, error, message, headers);
|
|
528
|
+
if (status === 401) return new AuthenticationError(status, error, message, headers);
|
|
529
|
+
if (status === 403) return new PermissionDeniedError(status, error, message, headers);
|
|
530
|
+
if (status === 404) return new NotFoundError(status, error, message, headers);
|
|
531
|
+
if (status === 409) return new ConflictError(status, error, message, headers);
|
|
532
|
+
if (status === 422) return new UnprocessableEntityError(status, error, message, headers);
|
|
533
|
+
if (status === 429) return new RateLimitError(status, error, message, headers);
|
|
534
|
+
if (status >= 500) return new InternalServerError(status, error, message, headers);
|
|
535
|
+
|
|
536
|
+
return new APIError(status, error, message, headers);
|
|
537
|
+
}
|
|
538
|
+
}
|
|
539
|
+
|
|
540
|
+
export class BadRequestError extends APIError {
|
|
541
|
+
override readonly status: 400 = 400;
|
|
542
|
+
}
|
|
543
|
+
export class AuthenticationError extends APIError {
|
|
544
|
+
override readonly status: 401 = 401;
|
|
545
|
+
}
|
|
546
|
+
export class PermissionDeniedError extends APIError {
|
|
547
|
+
override readonly status: 403 = 403;
|
|
548
|
+
}
|
|
549
|
+
export class NotFoundError extends APIError {
|
|
550
|
+
override readonly status: 404 = 404;
|
|
551
|
+
}
|
|
552
|
+
export class ConflictError extends APIError {
|
|
553
|
+
override readonly status: 409 = 409;
|
|
554
|
+
}
|
|
555
|
+
export class UnprocessableEntityError extends APIError {
|
|
556
|
+
override readonly status: 422 = 422;
|
|
557
|
+
}
|
|
558
|
+
export class RateLimitError extends APIError {
|
|
559
|
+
override readonly status: 429 = 429;
|
|
560
|
+
}
|
|
561
|
+
export class InternalServerError extends APIError {}
|
|
562
|
+
|
|
563
|
+
export class APIConnectionError extends APIError {
|
|
564
|
+
override readonly status: undefined = undefined;
|
|
565
|
+
|
|
566
|
+
constructor({ message, cause }: { message?: string; cause?: Error | undefined }) {
|
|
567
|
+
super(undefined, undefined, message || 'Connection error.', undefined);
|
|
568
|
+
// eslint-disable-next-line
|
|
569
|
+
// @ts-ignore
|
|
570
|
+
if (cause) this.cause = cause;
|
|
571
|
+
}
|
|
572
|
+
}
|
|
573
|
+
|
|
574
|
+
export class APIConnectionTimeoutError extends APIConnectionError {
|
|
575
|
+
constructor() {
|
|
576
|
+
super({ message: 'Request timed out.' });
|
|
577
|
+
}
|
|
578
|
+
}
|
|
579
|
+
|
|
580
|
+
let _packageVersion: string;
|
|
581
|
+
const getPackageVersion = (): string => {
|
|
582
|
+
try {
|
|
583
|
+
// eslint-disable-next-line @typescript-eslint/no-var-requires
|
|
584
|
+
return (_packageVersion ??= require(pkgUp.sync()!).version);
|
|
585
|
+
} catch (e) {
|
|
586
|
+
console.debug(`Ignoring error while determing package version ${e}`);
|
|
587
|
+
return (_packageVersion = 'unknown');
|
|
588
|
+
}
|
|
589
|
+
};
|
|
590
|
+
|
|
591
|
+
declare const Deno: any;
|
|
592
|
+
type PlatformProperties = {
|
|
593
|
+
lang: 'js';
|
|
594
|
+
packageVersion: string;
|
|
595
|
+
os: string;
|
|
596
|
+
arch: string;
|
|
597
|
+
runtime: 'node' | 'deno';
|
|
598
|
+
runtimeVersion: string;
|
|
599
|
+
};
|
|
600
|
+
const getPlatformProperties = (): PlatformProperties | void => {
|
|
601
|
+
if (typeof process !== 'undefined') {
|
|
602
|
+
return {
|
|
603
|
+
lang: 'js',
|
|
604
|
+
packageVersion: getPackageVersion(),
|
|
605
|
+
os: process.platform,
|
|
606
|
+
arch: process.arch,
|
|
607
|
+
runtime: 'node',
|
|
608
|
+
runtimeVersion: process.version,
|
|
609
|
+
};
|
|
610
|
+
}
|
|
611
|
+
if (typeof Deno !== 'undefined') {
|
|
612
|
+
return {
|
|
613
|
+
lang: 'js',
|
|
614
|
+
packageVersion: getPackageVersion(),
|
|
615
|
+
os: Deno.build.os,
|
|
616
|
+
arch: Deno.build.arch,
|
|
617
|
+
runtime: 'deno',
|
|
618
|
+
runtimeVersion: Deno.version,
|
|
619
|
+
};
|
|
620
|
+
}
|
|
621
|
+
// TODO add support for Cloudflare workers, browsers, etc.
|
|
622
|
+
};
|
|
623
|
+
|
|
624
|
+
let _platformPropertiesJSON: string;
|
|
625
|
+
const getPlatformPropertiesJSON = () => {
|
|
626
|
+
return (_platformPropertiesJSON ??= JSON.stringify(getPlatformProperties())) || '';
|
|
627
|
+
};
|
|
628
|
+
|
|
629
|
+
const safeJSON = (text: string) => {
|
|
630
|
+
try {
|
|
631
|
+
return JSON.parse(text);
|
|
632
|
+
} catch (err) {
|
|
633
|
+
return undefined;
|
|
634
|
+
}
|
|
635
|
+
};
|
|
636
|
+
|
|
637
|
+
// https://stackoverflow.com/a/19709846
|
|
638
|
+
const startsWithSchemeRegexp = new RegExp('^(?:[a-z]+:)?//', 'i');
|
|
639
|
+
const isAbsoluteURL = (url: string): boolean => {
|
|
640
|
+
return startsWithSchemeRegexp.test(url);
|
|
641
|
+
};
|
|
642
|
+
|
|
643
|
+
const sleep = (ms: number) => new Promise((resolve) => setTimeout(resolve, ms));
|
|
644
|
+
|
|
645
|
+
const validatePositiveInteger = (name: string, n: number) => {
|
|
646
|
+
if (!Number.isInteger(n)) {
|
|
647
|
+
throw new Error(`${name} must be an integer`);
|
|
648
|
+
}
|
|
649
|
+
if (n < 0) {
|
|
650
|
+
throw new Error(`${name} must be a positive integer`);
|
|
651
|
+
}
|
|
652
|
+
return n;
|
|
653
|
+
};
|
|
654
|
+
|
|
655
|
+
const castToError = (err: any): Error => {
|
|
656
|
+
if (err instanceof Error) return err;
|
|
657
|
+
return new Error(err);
|
|
658
|
+
};
|
|
659
|
+
|
|
660
|
+
const validateFormValue = (value: unknown): string | number | boolean | File | Blob => {
|
|
661
|
+
if (
|
|
662
|
+
typeof value === 'string' ||
|
|
663
|
+
typeof value === 'number' ||
|
|
664
|
+
typeof value === 'boolean' ||
|
|
665
|
+
value instanceof File ||
|
|
666
|
+
value instanceof Blob
|
|
667
|
+
) {
|
|
668
|
+
return value;
|
|
669
|
+
}
|
|
670
|
+
|
|
671
|
+
if (value == null) {
|
|
672
|
+
throw new TypeError(
|
|
673
|
+
`null is not a valid form data value, if you want to pass null then you need to use the string 'null'`,
|
|
674
|
+
);
|
|
675
|
+
}
|
|
676
|
+
|
|
677
|
+
throw new TypeError(
|
|
678
|
+
`Invalid value given to form, expected a string, number, boolean, File or Blob but got ${value} instead`,
|
|
679
|
+
);
|
|
680
|
+
};
|
|
681
|
+
|
|
682
|
+
export const multipartFormRequestOptions = <T = Record<string, unknown>>(
|
|
683
|
+
opts: RequestOptions<T>,
|
|
684
|
+
): RequestOptions<T | Readable> => {
|
|
685
|
+
const form = new FormData();
|
|
686
|
+
Object.entries(opts.body || {}).forEach(
|
|
687
|
+
([key, value]) => value !== undefined && form.set(key, validateFormValue(value)),
|
|
688
|
+
);
|
|
689
|
+
const encoder = new FormDataEncoder(form);
|
|
690
|
+
return {
|
|
691
|
+
...opts,
|
|
692
|
+
headers: { ...opts.headers, ...encoder.headers, 'Content-Length': encoder.contentLength },
|
|
693
|
+
body: Readable.from(encoder),
|
|
694
|
+
};
|
|
695
|
+
};
|
|
696
|
+
|
|
697
|
+
export const coerceInteger = (value: unknown): number => {
|
|
698
|
+
if (typeof value === 'number') return Math.round(value);
|
|
699
|
+
if (typeof value === 'string') return parseInt(value);
|
|
700
|
+
|
|
701
|
+
throw new Error(`Could not coerce ${value} (type: ${typeof value}) into a number`);
|
|
702
|
+
};
|
|
703
|
+
|
|
704
|
+
// https://stackoverflow.com/a/34491287
|
|
705
|
+
export function isEmptyObj(obj: Object | null | undefined): boolean {
|
|
706
|
+
if (!obj) return true;
|
|
707
|
+
for (const _k in obj) return false;
|
|
708
|
+
return true;
|
|
709
|
+
}
|
|
710
|
+
|
|
711
|
+
// https://eslint.org/docs/latest/rules/no-prototype-builtins
|
|
712
|
+
export function hasOwn(obj: Object, key: string): boolean {
|
|
713
|
+
return Object.prototype.hasOwnProperty.call(obj, key);
|
|
714
|
+
}
|
|
715
|
+
|
|
716
|
+
/**
|
|
717
|
+
* https://stackoverflow.com/a/2117523
|
|
718
|
+
*/
|
|
719
|
+
const uuid4 = () => {
|
|
720
|
+
return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, (c) => {
|
|
721
|
+
const r = (Math.random() * 16) | 0;
|
|
722
|
+
const v = c === 'x' ? r : (r & 0x3) | 0x8;
|
|
723
|
+
return v.toString(16);
|
|
724
|
+
});
|
|
725
|
+
};
|
|
726
|
+
|
|
727
|
+
export interface HeadersProtocol {
|
|
728
|
+
get: (header: string) => string | null | undefined;
|
|
729
|
+
}
|
|
730
|
+
export type HeadersLike = Record<string, string | string[] | undefined> | HeadersProtocol;
|
|
731
|
+
|
|
732
|
+
export const isHeadersProtocol = (headers: any): headers is HeadersProtocol => {
|
|
733
|
+
return typeof headers?.get === 'function';
|
|
734
|
+
};
|
|
735
|
+
|
|
736
|
+
export const getHeader = (headers: HeadersLike, key: string): string | null | undefined => {
|
|
737
|
+
const lowerKey = key.toLowerCase();
|
|
738
|
+
if (isHeadersProtocol(headers)) return headers.get(key) || headers.get(lowerKey);
|
|
739
|
+
const value = headers[key] || headers[lowerKey];
|
|
740
|
+
if (Array.isArray(value)) {
|
|
741
|
+
if (value.length <= 1) return value[0];
|
|
742
|
+
console.warn(`Received ${value.length} entries for the ${key} header, using the first entry.`);
|
|
743
|
+
return value[0];
|
|
744
|
+
}
|
|
745
|
+
return value;
|
|
746
|
+
};
|