@camunda8/sdk 8.8.17 → 8.8.18
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/dist/admin/lib/AdminApiClient.js +2 -3
- package/dist/admin/lib/AdminApiClient.js.map +1 -1
- package/dist/c8/lib/CamundaRestClient.d.ts +22 -4
- package/dist/c8/lib/CamundaRestClient.js +125 -33
- package/dist/c8/lib/CamundaRestClient.js.map +1 -1
- package/dist/c8/lib/TrackedGot.d.ts +3 -3
- package/dist/c8/lib/TrackedGot.js +3 -3
- package/dist/c8/lib/TrackedGot.js.map +1 -1
- package/dist/lib/Configuration.d.ts +1 -1
- package/dist/lib/Configuration.js.map +1 -1
- package/dist/lib/GotErrors.d.ts +5 -5
- package/dist/lib/GotErrors.js +3 -37
- package/dist/lib/GotErrors.js.map +1 -1
- package/dist/lib/GotHooks.d.ts +5 -26
- package/dist/lib/GotHooks.js +8 -46
- package/dist/lib/GotHooks.js.map +1 -1
- package/dist/lib/HttpClient.d.ts +194 -0
- package/dist/lib/HttpClient.js +749 -0
- package/dist/lib/HttpClient.js.map +1 -0
- package/dist/lib/index.d.ts +2 -0
- package/dist/lib/index.js +9 -1
- package/dist/lib/index.js.map +1 -1
- package/dist/modeler/lib/ModelerAPIClient.js +2 -3
- package/dist/modeler/lib/ModelerAPIClient.js.map +1 -1
- package/dist/oauth/lib/CookieAuthProvider.d.ts +2 -2
- package/dist/oauth/lib/CookieAuthProvider.js +2 -6
- package/dist/oauth/lib/CookieAuthProvider.js.map +1 -1
- package/dist/oauth/lib/OAuthProvider.js +2 -3
- package/dist/oauth/lib/OAuthProvider.js.map +1 -1
- package/dist/operate/lib/OperateApiClient.js +2 -6
- package/dist/operate/lib/OperateApiClient.js.map +1 -1
- package/dist/optimize/lib/OptimizeApiClient.d.ts +2 -2
- package/dist/optimize/lib/OptimizeApiClient.js +2 -6
- package/dist/optimize/lib/OptimizeApiClient.js.map +1 -1
- package/dist/optimize/lib/ReportResults.d.ts +2 -2
- package/dist/tasklist/lib/TasklistApiClient.js +2 -6
- package/dist/tasklist/lib/TasklistApiClient.js.map +1 -1
- package/dist/zeebe/lib/cancelProcesses.js +8 -0
- package/dist/zeebe/lib/cancelProcesses.js.map +1 -1
- package/package.json +11 -6
|
@@ -0,0 +1,749 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.FormData = exports.http = exports.defaultCalculateDelay = exports.parseRetryAfter = exports.DEFAULT_RETRY_ERROR_CODES = exports.ParseError = exports.CancelError = exports.TimeoutError = exports.HTTPError = exports.RequestError = void 0;
|
|
4
|
+
exports.mergeOptions = mergeOptions;
|
|
5
|
+
exports.getDispatcher = getDispatcher;
|
|
6
|
+
exports.createHttpClient = createHttpClient;
|
|
7
|
+
/* eslint-disable @typescript-eslint/no-explicit-any */
|
|
8
|
+
/**
|
|
9
|
+
* Minimal got-compatible HTTP client built on undici's `request` API.
|
|
10
|
+
*
|
|
11
|
+
* This replaces got 11 (see https://github.com/camunda/camunda-8-js-sdk/issues/837).
|
|
12
|
+
* It deliberately mirrors the subset of the got API used by this SDK
|
|
13
|
+
* (`client(url, options)`, verb helpers, `.extend()`, `.json()/.text()/.buffer()`,
|
|
14
|
+
* `.cancel()`, hooks, retry, timeouts, TLS options) so that call sites and the
|
|
15
|
+
* public `middleware` / `HTTPError` shapes stay compatible.
|
|
16
|
+
*
|
|
17
|
+
* We use the `undici` package's own `request`, `Agent` and `FormData` (rather than the
|
|
18
|
+
* Node.js globals) so that the TLS dispatcher and request implementation always match,
|
|
19
|
+
* independent of the Node.js-bundled undici version.
|
|
20
|
+
*
|
|
21
|
+
* `request` rather than `fetch`: fetch applies browser-only rules that got 11 did
|
|
22
|
+
* not (e.g. refusing fetch-spec "bad ports" such as 6000 or 6666), which would be
|
|
23
|
+
* a behavioural break for SDK users. Redirects are followed by the redirect
|
|
24
|
+
* interceptor, matching got 11's default.
|
|
25
|
+
*/
|
|
26
|
+
const node_crypto_1 = require("node:crypto");
|
|
27
|
+
const node_http_1 = require("node:http");
|
|
28
|
+
const node_stream_1 = require("node:stream");
|
|
29
|
+
const undici_1 = require("undici");
|
|
30
|
+
Object.defineProperty(exports, "FormData", { enumerable: true, get: function () { return undici_1.FormData; } });
|
|
31
|
+
/* ------------------------------------------------------------------ */
|
|
32
|
+
/* Errors */
|
|
33
|
+
/* ------------------------------------------------------------------ */
|
|
34
|
+
class RequestError extends Error {
|
|
35
|
+
constructor(message, { code, options, response, cause, }) {
|
|
36
|
+
super(message);
|
|
37
|
+
this.name = 'RequestError';
|
|
38
|
+
this.code = code ?? 'ERR_GOT_REQUEST_ERROR';
|
|
39
|
+
// Keep these non-enumerable-ish payloads accessible as in got
|
|
40
|
+
this.options = options;
|
|
41
|
+
this.request = { options };
|
|
42
|
+
this.response = response;
|
|
43
|
+
if (cause !== undefined) {
|
|
44
|
+
Object.defineProperty(this, 'cause', {
|
|
45
|
+
value: cause,
|
|
46
|
+
enumerable: false,
|
|
47
|
+
writable: true,
|
|
48
|
+
configurable: true,
|
|
49
|
+
});
|
|
50
|
+
}
|
|
51
|
+
Object.defineProperty(this, 'options', { enumerable: false });
|
|
52
|
+
Object.defineProperty(this, 'request', { enumerable: false });
|
|
53
|
+
Object.defineProperty(this, 'response', { enumerable: false });
|
|
54
|
+
}
|
|
55
|
+
}
|
|
56
|
+
exports.RequestError = RequestError;
|
|
57
|
+
class HTTPError extends RequestError {
|
|
58
|
+
constructor(response, options) {
|
|
59
|
+
super(`Response code ${response.statusCode} (${response.statusMessage})`, {
|
|
60
|
+
code: 'ERR_NON_2XX_3XX_RESPONSE',
|
|
61
|
+
options: options ?? response.request.options,
|
|
62
|
+
response,
|
|
63
|
+
});
|
|
64
|
+
this.name = 'HTTPError';
|
|
65
|
+
}
|
|
66
|
+
}
|
|
67
|
+
exports.HTTPError = HTTPError;
|
|
68
|
+
class TimeoutError extends RequestError {
|
|
69
|
+
constructor(ms, options) {
|
|
70
|
+
super(`Timeout awaiting 'request' for ${ms}ms`, {
|
|
71
|
+
code: 'ETIMEDOUT',
|
|
72
|
+
options,
|
|
73
|
+
});
|
|
74
|
+
this.event = 'request';
|
|
75
|
+
this.name = 'TimeoutError';
|
|
76
|
+
}
|
|
77
|
+
}
|
|
78
|
+
exports.TimeoutError = TimeoutError;
|
|
79
|
+
class CancelError extends RequestError {
|
|
80
|
+
constructor(reason, options) {
|
|
81
|
+
super(reason ?? 'Promise was canceled', { code: 'ERR_CANCELED', options });
|
|
82
|
+
this.name = 'CancelError';
|
|
83
|
+
}
|
|
84
|
+
get isCanceled() {
|
|
85
|
+
return true;
|
|
86
|
+
}
|
|
87
|
+
}
|
|
88
|
+
exports.CancelError = CancelError;
|
|
89
|
+
class ParseError extends RequestError {
|
|
90
|
+
constructor(cause, response) {
|
|
91
|
+
super(`${cause.message} in "${response.request.options.url.toString()}"`, {
|
|
92
|
+
code: 'ERR_BODY_PARSE_FAILURE',
|
|
93
|
+
options: response.request.options,
|
|
94
|
+
response,
|
|
95
|
+
cause,
|
|
96
|
+
});
|
|
97
|
+
this.name = 'ParseError';
|
|
98
|
+
}
|
|
99
|
+
}
|
|
100
|
+
exports.ParseError = ParseError;
|
|
101
|
+
/* ------------------------------------------------------------------ */
|
|
102
|
+
/* Defaults */
|
|
103
|
+
/* ------------------------------------------------------------------ */
|
|
104
|
+
/** Network error codes that are retried (got 11 defaults plus undici/Node 24 codes). */
|
|
105
|
+
exports.DEFAULT_RETRY_ERROR_CODES = [
|
|
106
|
+
'ETIMEDOUT',
|
|
107
|
+
'ECONNRESET',
|
|
108
|
+
'EADDRINUSE',
|
|
109
|
+
'ECONNREFUSED',
|
|
110
|
+
'EPIPE',
|
|
111
|
+
'ENOTFOUND',
|
|
112
|
+
'ENETUNREACH',
|
|
113
|
+
'EAI_AGAIN',
|
|
114
|
+
// Node 24.21+ surfaces some refused/closed connections with this code
|
|
115
|
+
'ERR_SOCKET_CLOSED_BEFORE_CONNECTION',
|
|
116
|
+
'UND_ERR_SOCKET',
|
|
117
|
+
'UND_ERR_CONNECT_TIMEOUT',
|
|
118
|
+
];
|
|
119
|
+
const RETRY_AFTER_STATUS_CODES = [413, 429, 503];
|
|
120
|
+
/**
|
|
121
|
+
* Parse a `Retry-After` header (delta-seconds or an HTTP-date) into milliseconds.
|
|
122
|
+
* Returns `undefined` when the error carries no response, the status is not one
|
|
123
|
+
* that uses `Retry-After`, or the header is absent.
|
|
124
|
+
*/
|
|
125
|
+
const parseRetryAfter = (error) => {
|
|
126
|
+
if (!error.response ||
|
|
127
|
+
!RETRY_AFTER_STATUS_CODES.includes(error.response.statusCode)) {
|
|
128
|
+
return undefined;
|
|
129
|
+
}
|
|
130
|
+
const header = error.response.headers['retry-after'];
|
|
131
|
+
const value = Array.isArray(header) ? header[0] : header;
|
|
132
|
+
if (!value)
|
|
133
|
+
return undefined;
|
|
134
|
+
const seconds = Number(value);
|
|
135
|
+
if (!Number.isNaN(seconds))
|
|
136
|
+
return seconds * 1000;
|
|
137
|
+
// An HTTP-date Retry-After; a malformed date must be treated as absent
|
|
138
|
+
// (returning NaN here would later collapse to a NaN delay that silently
|
|
139
|
+
// stops retrying instead of falling back to exponential backoff).
|
|
140
|
+
const date = Date.parse(value);
|
|
141
|
+
return Number.isNaN(date) ? undefined : date - Date.now();
|
|
142
|
+
};
|
|
143
|
+
exports.parseRetryAfter = parseRetryAfter;
|
|
144
|
+
/** got 11-compatible default backoff: 2^(n-1) * 1000ms + up to 100ms jitter, honouring Retry-After. */
|
|
145
|
+
const defaultCalculateDelay = ({ attemptCount, retryOptions, error, retryAfter, }) => {
|
|
146
|
+
if (attemptCount > retryOptions.limit)
|
|
147
|
+
return 0;
|
|
148
|
+
const hasMethod = retryOptions.methods
|
|
149
|
+
.map((m) => m.toUpperCase())
|
|
150
|
+
.includes(error.options.method.toUpperCase());
|
|
151
|
+
const hasErrorCode = retryOptions.errorCodes.includes(error.code);
|
|
152
|
+
const hasStatusCode = !!error.response &&
|
|
153
|
+
retryOptions.statusCodes.includes(error.response.statusCode);
|
|
154
|
+
if (!hasMethod || (!hasErrorCode && !hasStatusCode))
|
|
155
|
+
return 0;
|
|
156
|
+
if (error.response &&
|
|
157
|
+
RETRY_AFTER_STATUS_CODES.includes(error.response.statusCode)) {
|
|
158
|
+
const after = retryAfter ?? (0, exports.parseRetryAfter)(error);
|
|
159
|
+
if (after !== undefined) {
|
|
160
|
+
if (retryOptions.maxRetryAfter !== undefined &&
|
|
161
|
+
after > retryOptions.maxRetryAfter) {
|
|
162
|
+
return 0;
|
|
163
|
+
}
|
|
164
|
+
// Retry-After: 0 means "retry now" - a 0 delay would mean "do not retry"
|
|
165
|
+
return Math.max(1, after);
|
|
166
|
+
}
|
|
167
|
+
if (error.response.statusCode === 413)
|
|
168
|
+
return 0;
|
|
169
|
+
}
|
|
170
|
+
const noise = Math.random() * 100;
|
|
171
|
+
return 2 ** (attemptCount - 1) * 1000 + noise;
|
|
172
|
+
};
|
|
173
|
+
exports.defaultCalculateDelay = defaultCalculateDelay;
|
|
174
|
+
const DEFAULT_RETRY = {
|
|
175
|
+
limit: 2,
|
|
176
|
+
methods: ['GET', 'PUT', 'HEAD', 'DELETE', 'OPTIONS', 'TRACE'],
|
|
177
|
+
statusCodes: [408, 413, 429, 500, 502, 503, 504, 521, 522, 524],
|
|
178
|
+
errorCodes: exports.DEFAULT_RETRY_ERROR_CODES,
|
|
179
|
+
maxRetryAfter: undefined,
|
|
180
|
+
calculateDelay: exports.defaultCalculateDelay,
|
|
181
|
+
};
|
|
182
|
+
/* ------------------------------------------------------------------ */
|
|
183
|
+
/* Option merging / normalisation */
|
|
184
|
+
/* ------------------------------------------------------------------ */
|
|
185
|
+
function lowerCaseHeaders(headers) {
|
|
186
|
+
const out = {};
|
|
187
|
+
if (!headers)
|
|
188
|
+
return out;
|
|
189
|
+
for (const [k, v] of Object.entries(headers)) {
|
|
190
|
+
if (v === undefined || v === null)
|
|
191
|
+
continue;
|
|
192
|
+
out[k.toLowerCase()] = Array.isArray(v) ? v.join(', ') : String(v);
|
|
193
|
+
}
|
|
194
|
+
return out;
|
|
195
|
+
}
|
|
196
|
+
function toSearchParams(sp) {
|
|
197
|
+
if (sp === undefined)
|
|
198
|
+
return new URLSearchParams();
|
|
199
|
+
if (typeof sp === 'string' || sp instanceof URLSearchParams) {
|
|
200
|
+
return new URLSearchParams(sp);
|
|
201
|
+
}
|
|
202
|
+
const out = new URLSearchParams();
|
|
203
|
+
for (const [k, v] of Object.entries(sp)) {
|
|
204
|
+
if (v === undefined)
|
|
205
|
+
continue;
|
|
206
|
+
out.append(k, v === null ? '' : String(v));
|
|
207
|
+
}
|
|
208
|
+
return out;
|
|
209
|
+
}
|
|
210
|
+
function normalizeRetry(base, override) {
|
|
211
|
+
if (override === undefined)
|
|
212
|
+
return base;
|
|
213
|
+
const b = typeof base === 'number' ? { limit: base } : (base ?? {});
|
|
214
|
+
const o = typeof override === 'number' ? { limit: override } : override;
|
|
215
|
+
return { ...b, ...o };
|
|
216
|
+
}
|
|
217
|
+
/** Merge two option objects with got.extend()-like semantics. */
|
|
218
|
+
function mergeOptions(base, override = {}) {
|
|
219
|
+
const merged = { ...base, ...override };
|
|
220
|
+
merged.headers = { ...(base.headers ?? {}), ...(override.headers ?? {}) };
|
|
221
|
+
merged.context = { ...(base.context ?? {}), ...(override.context ?? {}) };
|
|
222
|
+
merged.https = { ...(base.https ?? {}), ...(override.https ?? {}) };
|
|
223
|
+
merged.retry = normalizeRetry(base.retry, override.retry);
|
|
224
|
+
if (base.searchParams !== undefined || override.searchParams !== undefined) {
|
|
225
|
+
const sp = toSearchParams(base.searchParams);
|
|
226
|
+
const overrideSp = toSearchParams(override.searchParams);
|
|
227
|
+
// Drop each overridden base key once, then append all override entries so
|
|
228
|
+
// repeated params (e.g. tag=a&tag=b) survive instead of collapsing to one.
|
|
229
|
+
for (const key of new Set(overrideSp.keys())) {
|
|
230
|
+
sp.delete(key);
|
|
231
|
+
}
|
|
232
|
+
overrideSp.forEach((v, k) => sp.append(k, v));
|
|
233
|
+
merged.searchParams = sp;
|
|
234
|
+
}
|
|
235
|
+
merged.hooks = {
|
|
236
|
+
beforeRequest: [
|
|
237
|
+
...(base.hooks?.beforeRequest ?? []),
|
|
238
|
+
...(override.hooks?.beforeRequest ?? []),
|
|
239
|
+
],
|
|
240
|
+
beforeRetry: [
|
|
241
|
+
...(base.hooks?.beforeRetry ?? []),
|
|
242
|
+
...(override.hooks?.beforeRetry ?? []),
|
|
243
|
+
],
|
|
244
|
+
beforeError: [
|
|
245
|
+
...(base.hooks?.beforeError ?? []),
|
|
246
|
+
...(override.hooks?.beforeError ?? []),
|
|
247
|
+
],
|
|
248
|
+
afterResponse: [
|
|
249
|
+
...(base.hooks?.afterResponse ?? []),
|
|
250
|
+
...(override.hooks?.afterResponse ?? []),
|
|
251
|
+
],
|
|
252
|
+
};
|
|
253
|
+
merged.handlers = [...(base.handlers ?? []), ...(override.handlers ?? [])];
|
|
254
|
+
return merged;
|
|
255
|
+
}
|
|
256
|
+
function resolveUrl(input, prefixUrl) {
|
|
257
|
+
if (input instanceof URL)
|
|
258
|
+
return new URL(input.toString());
|
|
259
|
+
if (/^[a-z][a-z\d+\-.]*:\/\//i.test(input))
|
|
260
|
+
return new URL(input);
|
|
261
|
+
if (!prefixUrl) {
|
|
262
|
+
throw new TypeError(`Invalid URL: ${input} (no prefixUrl configured)`);
|
|
263
|
+
}
|
|
264
|
+
const prefix = prefixUrl.endsWith('/') ? prefixUrl : `${prefixUrl}/`;
|
|
265
|
+
const path = input.startsWith('/') ? input.slice(1) : input;
|
|
266
|
+
// got builds prefixUrl + path as a plain string concatenation
|
|
267
|
+
return new URL(prefix + path);
|
|
268
|
+
}
|
|
269
|
+
function normalize(url, options) {
|
|
270
|
+
const resolved = resolveUrl(url, options.prefixUrl);
|
|
271
|
+
const extra = toSearchParams(options.searchParams);
|
|
272
|
+
// Drop each overridden URL key once, then append all option entries so
|
|
273
|
+
// repeated params (e.g. tag=a&tag=b) survive instead of collapsing to one.
|
|
274
|
+
for (const key of new Set(extra.keys())) {
|
|
275
|
+
resolved.searchParams.delete(key);
|
|
276
|
+
}
|
|
277
|
+
extra.forEach((v, k) => resolved.searchParams.append(k, v));
|
|
278
|
+
const headers = lowerCaseHeaders(options.headers);
|
|
279
|
+
let body = options.body;
|
|
280
|
+
if (options.json !== undefined) {
|
|
281
|
+
body = JSON.stringify(options.json);
|
|
282
|
+
headers['content-type'] ?? (headers['content-type'] = 'application/json');
|
|
283
|
+
}
|
|
284
|
+
else if (options.form !== undefined) {
|
|
285
|
+
body = toSearchParams(options.form).toString();
|
|
286
|
+
headers['content-type'] ?? (headers['content-type'] = 'application/x-www-form-urlencoded');
|
|
287
|
+
}
|
|
288
|
+
if (body instanceof undici_1.FormData) {
|
|
289
|
+
// fetch must set the multipart boundary itself
|
|
290
|
+
delete headers['content-type'];
|
|
291
|
+
}
|
|
292
|
+
if ((options.username || options.password) &&
|
|
293
|
+
headers['authorization'] === undefined) {
|
|
294
|
+
headers['authorization'] = `Basic ${Buffer.from(`${options.username ?? ''}:${options.password ?? ''}`).toString('base64')}`;
|
|
295
|
+
}
|
|
296
|
+
const retryInput = options.retry;
|
|
297
|
+
const retry = typeof retryInput === 'number'
|
|
298
|
+
? { ...DEFAULT_RETRY, limit: retryInput }
|
|
299
|
+
: { ...DEFAULT_RETRY, ...(retryInput ?? {}) };
|
|
300
|
+
const timeout = typeof options.timeout === 'number'
|
|
301
|
+
? { request: options.timeout }
|
|
302
|
+
: { ...(options.timeout ?? {}) };
|
|
303
|
+
// got 11 caps Retry-After at the request timeout when maxRetryAfter is unset;
|
|
304
|
+
// otherwise a huge `Retry-After` (e.g. 3600s) would sleep far past the timeout.
|
|
305
|
+
if (retry.maxRetryAfter === undefined && timeout.request !== undefined) {
|
|
306
|
+
retry.maxRetryAfter = timeout.request;
|
|
307
|
+
}
|
|
308
|
+
return {
|
|
309
|
+
method: (options.method ?? 'GET').toUpperCase(),
|
|
310
|
+
url: resolved,
|
|
311
|
+
prefixUrl: options.prefixUrl ?? '',
|
|
312
|
+
headers,
|
|
313
|
+
body,
|
|
314
|
+
json: options.json,
|
|
315
|
+
parseJson: options.parseJson ?? JSON.parse,
|
|
316
|
+
retry,
|
|
317
|
+
timeout,
|
|
318
|
+
throwHttpErrors: options.throwHttpErrors ?? true,
|
|
319
|
+
context: { ...(options.context ?? {}) },
|
|
320
|
+
https: { ...(options.https ?? {}) },
|
|
321
|
+
hooks: {
|
|
322
|
+
beforeRequest: [...(options.hooks?.beforeRequest ?? [])],
|
|
323
|
+
beforeRetry: [...(options.hooks?.beforeRetry ?? [])],
|
|
324
|
+
beforeError: [...(options.hooks?.beforeError ?? [])],
|
|
325
|
+
afterResponse: [...(options.hooks?.afterResponse ?? [])],
|
|
326
|
+
},
|
|
327
|
+
};
|
|
328
|
+
}
|
|
329
|
+
/* ------------------------------------------------------------------ */
|
|
330
|
+
/* TLS dispatcher */
|
|
331
|
+
/* ------------------------------------------------------------------ */
|
|
332
|
+
/**
|
|
333
|
+
* Dispatcher cache: outer key fingerprints the PEM material, inner key is the
|
|
334
|
+
* raw passphrase. The passphrase is a secret, so it is used as an in-memory
|
|
335
|
+
* map key only and never hashed or serialised into a string key.
|
|
336
|
+
*/
|
|
337
|
+
const dispatcherCache = new Map();
|
|
338
|
+
function pemKey(value) {
|
|
339
|
+
if (value === undefined || value === null)
|
|
340
|
+
return '';
|
|
341
|
+
if (Array.isArray(value))
|
|
342
|
+
return value.map(pemKey).join('|');
|
|
343
|
+
return (0, node_crypto_1.createHash)('sha256')
|
|
344
|
+
.update(Buffer.isBuffer(value) ? value : String(value))
|
|
345
|
+
.digest('hex');
|
|
346
|
+
}
|
|
347
|
+
/** Returns an undici Agent configured for custom CA / mTLS, or undefined for the default dispatcher. */
|
|
348
|
+
function getTlsDispatcher(https) {
|
|
349
|
+
const cert = https.certificate ?? https.cert;
|
|
350
|
+
const { certificateAuthority: ca, key, passphrase, rejectUnauthorized, } = https;
|
|
351
|
+
if (ca === undefined &&
|
|
352
|
+
cert === undefined &&
|
|
353
|
+
key === undefined &&
|
|
354
|
+
rejectUnauthorized === undefined) {
|
|
355
|
+
return undefined;
|
|
356
|
+
}
|
|
357
|
+
const cacheKey = [
|
|
358
|
+
pemKey(ca),
|
|
359
|
+
pemKey(cert),
|
|
360
|
+
pemKey(key),
|
|
361
|
+
String(rejectUnauthorized),
|
|
362
|
+
].join(':');
|
|
363
|
+
let byPassphrase = dispatcherCache.get(cacheKey);
|
|
364
|
+
if (!byPassphrase) {
|
|
365
|
+
byPassphrase = new Map();
|
|
366
|
+
dispatcherCache.set(cacheKey, byPassphrase);
|
|
367
|
+
}
|
|
368
|
+
let dispatcher = byPassphrase.get(passphrase);
|
|
369
|
+
if (!dispatcher) {
|
|
370
|
+
dispatcher = new undici_1.Agent({
|
|
371
|
+
connect: {
|
|
372
|
+
ca: ca,
|
|
373
|
+
cert: cert,
|
|
374
|
+
key: key,
|
|
375
|
+
passphrase,
|
|
376
|
+
...(rejectUnauthorized === undefined ? {} : { rejectUnauthorized }),
|
|
377
|
+
},
|
|
378
|
+
});
|
|
379
|
+
byPassphrase.set(passphrase, dispatcher);
|
|
380
|
+
}
|
|
381
|
+
return dispatcher;
|
|
382
|
+
}
|
|
383
|
+
const MAX_REDIRECTS = 10; // got 11 default
|
|
384
|
+
/**
|
|
385
|
+
* Default (non-TLS-customised) dispatcher, owned by this package's undici.
|
|
386
|
+
* We deliberately do not use getGlobalDispatcher(): the process-global
|
|
387
|
+
* dispatcher belongs to Node's bundled undici, whose version varies by Node
|
|
388
|
+
* release (6.x on Node 22), and composing this package's interceptors onto
|
|
389
|
+
* it fails with UND_ERR_INVALID_ARG ("invalid onError method").
|
|
390
|
+
*/
|
|
391
|
+
let defaultAgent;
|
|
392
|
+
const redirectingDispatchers = new WeakMap();
|
|
393
|
+
/**
|
|
394
|
+
* Returns the dispatcher for a request: the TLS-configured Agent (or the global
|
|
395
|
+
* package-owned default Agent) composed with redirect following, as got 11 followed redirects.
|
|
396
|
+
*/
|
|
397
|
+
function getDispatcher(https) {
|
|
398
|
+
const base = getTlsDispatcher(https) ?? (defaultAgent ?? (defaultAgent = new undici_1.Agent()));
|
|
399
|
+
let composed = redirectingDispatchers.get(base);
|
|
400
|
+
if (!composed) {
|
|
401
|
+
composed = base.compose(undici_1.interceptors.redirect({ maxRedirections: MAX_REDIRECTS }));
|
|
402
|
+
redirectingDispatchers.set(base, composed);
|
|
403
|
+
}
|
|
404
|
+
return composed;
|
|
405
|
+
}
|
|
406
|
+
/* ------------------------------------------------------------------ */
|
|
407
|
+
/* Request execution */
|
|
408
|
+
/* ------------------------------------------------------------------ */
|
|
409
|
+
/** Extract a Node/undici error code from a transport failure (walking any cause chain). */
|
|
410
|
+
function networkErrorCode(err) {
|
|
411
|
+
let e = err;
|
|
412
|
+
for (let i = 0; i < 5 && e; i++) {
|
|
413
|
+
if (typeof e.code === 'string')
|
|
414
|
+
return e.code;
|
|
415
|
+
e = e.cause;
|
|
416
|
+
}
|
|
417
|
+
return undefined;
|
|
418
|
+
}
|
|
419
|
+
function networkErrorMessage(err) {
|
|
420
|
+
let e = err;
|
|
421
|
+
let msg = err?.message ?? String(err);
|
|
422
|
+
for (let i = 0; i < 5 && e?.cause; i++) {
|
|
423
|
+
e = e.cause;
|
|
424
|
+
if (e?.message)
|
|
425
|
+
msg = e.message;
|
|
426
|
+
}
|
|
427
|
+
return msg;
|
|
428
|
+
}
|
|
429
|
+
function sleep(ms, signal) {
|
|
430
|
+
return new Promise((resolve, reject) => {
|
|
431
|
+
if (signal.aborted)
|
|
432
|
+
return reject(signal.reason);
|
|
433
|
+
const t = setTimeout(() => {
|
|
434
|
+
signal.removeEventListener('abort', onAbort);
|
|
435
|
+
resolve();
|
|
436
|
+
}, ms);
|
|
437
|
+
const onAbort = () => {
|
|
438
|
+
clearTimeout(t);
|
|
439
|
+
reject(signal.reason);
|
|
440
|
+
};
|
|
441
|
+
signal.addEventListener('abort', onAbort, { once: true });
|
|
442
|
+
});
|
|
443
|
+
}
|
|
444
|
+
function responseHeaders(h) {
|
|
445
|
+
const out = {};
|
|
446
|
+
for (const [key, value] of Object.entries(h ?? {})) {
|
|
447
|
+
if (value === undefined)
|
|
448
|
+
continue;
|
|
449
|
+
const k = key.toLowerCase();
|
|
450
|
+
if (k === 'set-cookie') {
|
|
451
|
+
out[k] = Array.isArray(value) ? value : [value];
|
|
452
|
+
}
|
|
453
|
+
else {
|
|
454
|
+
out[k] = Array.isArray(value) ? value.join(', ') : value;
|
|
455
|
+
}
|
|
456
|
+
}
|
|
457
|
+
return out;
|
|
458
|
+
}
|
|
459
|
+
/** Turn a beforeRequest short-circuit return value into a Response. */
|
|
460
|
+
function fromResponseLike(like, options, retryCount) {
|
|
461
|
+
const rawBody = Buffer.isBuffer(like.body)
|
|
462
|
+
? like.body
|
|
463
|
+
: Buffer.from(like.body ?? '', 'utf8');
|
|
464
|
+
return {
|
|
465
|
+
statusCode: like.statusCode,
|
|
466
|
+
statusMessage: like.statusMessage ?? node_http_1.STATUS_CODES[like.statusCode] ?? '',
|
|
467
|
+
headers: responseHeaders(like.headers),
|
|
468
|
+
body: rawBody.toString('utf8'),
|
|
469
|
+
rawBody,
|
|
470
|
+
url: options.url.toString(),
|
|
471
|
+
ok: like.statusCode >= 200 && like.statusCode < 300,
|
|
472
|
+
retryCount,
|
|
473
|
+
request: { options },
|
|
474
|
+
};
|
|
475
|
+
}
|
|
476
|
+
function isResponseLike(value) {
|
|
477
|
+
return (typeof value === 'object' &&
|
|
478
|
+
value !== null &&
|
|
479
|
+
typeof value.statusCode === 'number');
|
|
480
|
+
}
|
|
481
|
+
async function applyBeforeError(error, options) {
|
|
482
|
+
let e = error;
|
|
483
|
+
for (const hook of options.hooks.beforeError) {
|
|
484
|
+
e = await hook(e);
|
|
485
|
+
}
|
|
486
|
+
return e;
|
|
487
|
+
}
|
|
488
|
+
/**
|
|
489
|
+
* Encode the request body for undici's `request`. FormData is serialised
|
|
490
|
+
* per attempt (so retries resend it) via the WHATWG Response body extractor,
|
|
491
|
+
* which streams Blob parts lazily and supplies the multipart boundary.
|
|
492
|
+
*/
|
|
493
|
+
function encodeBody(options) {
|
|
494
|
+
if (options.method === 'GET' || options.method === 'HEAD') {
|
|
495
|
+
return { body: undefined, headers: options.headers };
|
|
496
|
+
}
|
|
497
|
+
const body = options.body;
|
|
498
|
+
if (body instanceof undici_1.FormData) {
|
|
499
|
+
const encoded = new undici_1.Response(body);
|
|
500
|
+
return {
|
|
501
|
+
body: encoded.body ? node_stream_1.Readable.fromWeb(encoded.body) : undefined,
|
|
502
|
+
headers: {
|
|
503
|
+
...options.headers,
|
|
504
|
+
'content-type': encoded.headers.get('content-type'),
|
|
505
|
+
},
|
|
506
|
+
};
|
|
507
|
+
}
|
|
508
|
+
if (body instanceof URLSearchParams) {
|
|
509
|
+
return { body: body.toString(), headers: options.headers };
|
|
510
|
+
}
|
|
511
|
+
return { body, headers: options.headers };
|
|
512
|
+
}
|
|
513
|
+
async function executeOnce(options, cancelSignal, retryCount, shortCircuit) {
|
|
514
|
+
const timeoutMs = options.timeout.request;
|
|
515
|
+
const timeoutController = new AbortController();
|
|
516
|
+
const timer = timeoutMs !== undefined && !shortCircuit
|
|
517
|
+
? setTimeout(() => timeoutController.abort(new TimeoutError(timeoutMs, options)), timeoutMs)
|
|
518
|
+
: undefined;
|
|
519
|
+
const signal = AbortSignal.any([cancelSignal, timeoutController.signal]);
|
|
520
|
+
const rethrowAbort = () => {
|
|
521
|
+
if (timeoutController.signal.aborted)
|
|
522
|
+
throw timeoutController.signal.reason;
|
|
523
|
+
if (cancelSignal.aborted)
|
|
524
|
+
throw cancelSignal.reason;
|
|
525
|
+
};
|
|
526
|
+
try {
|
|
527
|
+
let response;
|
|
528
|
+
if (shortCircuit) {
|
|
529
|
+
response = fromResponseLike(shortCircuit, options, retryCount);
|
|
530
|
+
}
|
|
531
|
+
else {
|
|
532
|
+
let res;
|
|
533
|
+
try {
|
|
534
|
+
const { body, headers } = encodeBody(options);
|
|
535
|
+
res = await (0, undici_1.request)(options.url, {
|
|
536
|
+
method: options.method,
|
|
537
|
+
headers,
|
|
538
|
+
body,
|
|
539
|
+
signal,
|
|
540
|
+
dispatcher: getDispatcher(options.https),
|
|
541
|
+
});
|
|
542
|
+
}
|
|
543
|
+
catch (err) {
|
|
544
|
+
rethrowAbort();
|
|
545
|
+
throw new RequestError(networkErrorMessage(err), {
|
|
546
|
+
code: networkErrorCode(err),
|
|
547
|
+
options,
|
|
548
|
+
cause: err,
|
|
549
|
+
});
|
|
550
|
+
}
|
|
551
|
+
let rawBody;
|
|
552
|
+
try {
|
|
553
|
+
rawBody = Buffer.from(await res.body.arrayBuffer());
|
|
554
|
+
}
|
|
555
|
+
catch (err) {
|
|
556
|
+
rethrowAbort();
|
|
557
|
+
throw new RequestError(networkErrorMessage(err), {
|
|
558
|
+
code: networkErrorCode(err) ?? 'ERR_READING_RESPONSE_STREAM',
|
|
559
|
+
options,
|
|
560
|
+
cause: err,
|
|
561
|
+
});
|
|
562
|
+
}
|
|
563
|
+
response = {
|
|
564
|
+
statusCode: res.statusCode,
|
|
565
|
+
statusMessage: node_http_1.STATUS_CODES[res.statusCode] ?? '',
|
|
566
|
+
headers: responseHeaders(res.headers),
|
|
567
|
+
body: rawBody.toString('utf8'),
|
|
568
|
+
rawBody,
|
|
569
|
+
url: options.url.toString(),
|
|
570
|
+
ok: res.statusCode >= 200 && res.statusCode < 300,
|
|
571
|
+
retryCount,
|
|
572
|
+
request: { options },
|
|
573
|
+
};
|
|
574
|
+
}
|
|
575
|
+
for (const hook of options.hooks.afterResponse) {
|
|
576
|
+
response = await hook(response);
|
|
577
|
+
}
|
|
578
|
+
// Evaluate the final response returned by the hooks (a hook may recover a
|
|
579
|
+
// 5xx into a success), not the original status. With redirects followed,
|
|
580
|
+
// got treats only 2xx and 304 as successful.
|
|
581
|
+
const status = response.statusCode;
|
|
582
|
+
const isOk = (status >= 200 && status < 300) || status === 304;
|
|
583
|
+
if (!isOk) {
|
|
584
|
+
throw new HTTPError(response, options);
|
|
585
|
+
}
|
|
586
|
+
return response;
|
|
587
|
+
}
|
|
588
|
+
finally {
|
|
589
|
+
if (timer)
|
|
590
|
+
clearTimeout(timer);
|
|
591
|
+
}
|
|
592
|
+
}
|
|
593
|
+
async function executeWithRetry(options, cancelSignal) {
|
|
594
|
+
let attempt = 0;
|
|
595
|
+
for (;;) {
|
|
596
|
+
try {
|
|
597
|
+
// Run beforeRequest middleware before every attempt (including retries)
|
|
598
|
+
// so hooks that refresh signatures, timestamps or attempt-specific
|
|
599
|
+
// headers see fresh state on each try, as got does.
|
|
600
|
+
// As in got 11, a hook that returns a response short-circuits the
|
|
601
|
+
// network call; later hooks are skipped.
|
|
602
|
+
let shortCircuit;
|
|
603
|
+
for (const hook of options.hooks.beforeRequest) {
|
|
604
|
+
const result = await hook(options);
|
|
605
|
+
if (isResponseLike(result)) {
|
|
606
|
+
shortCircuit = result;
|
|
607
|
+
break;
|
|
608
|
+
}
|
|
609
|
+
}
|
|
610
|
+
return await executeOnce(options, cancelSignal, attempt, shortCircuit);
|
|
611
|
+
}
|
|
612
|
+
catch (err) {
|
|
613
|
+
if (err instanceof CancelError || cancelSignal.aborted) {
|
|
614
|
+
throw err instanceof CancelError
|
|
615
|
+
? err
|
|
616
|
+
: new CancelError(undefined, options);
|
|
617
|
+
}
|
|
618
|
+
const error = err instanceof RequestError
|
|
619
|
+
? err
|
|
620
|
+
: new RequestError(err?.message ?? String(err), {
|
|
621
|
+
options,
|
|
622
|
+
cause: err,
|
|
623
|
+
});
|
|
624
|
+
attempt++;
|
|
625
|
+
// Do not swallow exceptions from a user-supplied calculateDelay:
|
|
626
|
+
// let them propagate so the outer error path wraps them with request
|
|
627
|
+
// context and runs beforeError, instead of masking a configuration or
|
|
628
|
+
// programming failure behind the unrelated request error.
|
|
629
|
+
const retryAfter = (0, exports.parseRetryAfter)(error);
|
|
630
|
+
const computedValue = (0, exports.defaultCalculateDelay)({
|
|
631
|
+
attemptCount: attempt,
|
|
632
|
+
retryOptions: options.retry,
|
|
633
|
+
error,
|
|
634
|
+
computedValue: 0,
|
|
635
|
+
retryAfter,
|
|
636
|
+
});
|
|
637
|
+
const delay = options.retry.calculateDelay === exports.defaultCalculateDelay
|
|
638
|
+
? computedValue
|
|
639
|
+
: await options.retry.calculateDelay({
|
|
640
|
+
attemptCount: attempt,
|
|
641
|
+
retryOptions: options.retry,
|
|
642
|
+
error,
|
|
643
|
+
computedValue,
|
|
644
|
+
retryAfter,
|
|
645
|
+
});
|
|
646
|
+
if (!delay || delay <= 0) {
|
|
647
|
+
// Retries are exhausted (or this status/error is not retriable).
|
|
648
|
+
// When the caller opted out of throwing on HTTP errors, hand back
|
|
649
|
+
// the final response instead of throwing — but only for HTTP status
|
|
650
|
+
// errors, which carry a response. Network/parse/cancel errors still
|
|
651
|
+
// throw.
|
|
652
|
+
if (!options.throwHttpErrors &&
|
|
653
|
+
error instanceof HTTPError &&
|
|
654
|
+
error.response) {
|
|
655
|
+
return error.response;
|
|
656
|
+
}
|
|
657
|
+
throw error;
|
|
658
|
+
}
|
|
659
|
+
// beforeRetry hooks may throw to abort retrying
|
|
660
|
+
for (const hook of options.hooks.beforeRetry) {
|
|
661
|
+
await hook(options, error, attempt);
|
|
662
|
+
}
|
|
663
|
+
await sleep(delay, cancelSignal).catch(() => {
|
|
664
|
+
throw new CancelError(undefined, options);
|
|
665
|
+
});
|
|
666
|
+
}
|
|
667
|
+
}
|
|
668
|
+
}
|
|
669
|
+
function createResponsePromise(options, handlers) {
|
|
670
|
+
const controller = new AbortController();
|
|
671
|
+
let canceled = false;
|
|
672
|
+
const core = (async () => {
|
|
673
|
+
try {
|
|
674
|
+
// Run handlers inside the try so a throwing handler (e.g. beforeCallHook)
|
|
675
|
+
// is enriched by beforeError like hook/transport failures, not returned raw.
|
|
676
|
+
for (const handler of handlers) {
|
|
677
|
+
handler(options);
|
|
678
|
+
}
|
|
679
|
+
return await executeWithRetry(options, controller.signal);
|
|
680
|
+
}
|
|
681
|
+
catch (err) {
|
|
682
|
+
if (err instanceof CancelError)
|
|
683
|
+
throw err;
|
|
684
|
+
// Hook errors (beforeRequest/beforeRetry/afterResponse) may be ordinary
|
|
685
|
+
// Error objects with no `.options`; wrap them so beforeError hooks that
|
|
686
|
+
// read `error.options` don't mask the original error with a TypeError.
|
|
687
|
+
const requestError = err instanceof RequestError
|
|
688
|
+
? err
|
|
689
|
+
: new RequestError(err?.message ?? String(err), {
|
|
690
|
+
options,
|
|
691
|
+
cause: err,
|
|
692
|
+
});
|
|
693
|
+
throw await applyBeforeError(requestError, options);
|
|
694
|
+
}
|
|
695
|
+
})();
|
|
696
|
+
const parse = async () => {
|
|
697
|
+
const response = await core;
|
|
698
|
+
if (response.body === '')
|
|
699
|
+
return '';
|
|
700
|
+
try {
|
|
701
|
+
return options.parseJson(response.body);
|
|
702
|
+
}
|
|
703
|
+
catch (e) {
|
|
704
|
+
throw await applyBeforeError(new ParseError(e, response), options);
|
|
705
|
+
}
|
|
706
|
+
};
|
|
707
|
+
const promise = core;
|
|
708
|
+
Object.defineProperties(promise, {
|
|
709
|
+
json: { value: parse },
|
|
710
|
+
text: { value: () => core.then((r) => r.body) },
|
|
711
|
+
buffer: { value: () => core.then((r) => r.rawBody) },
|
|
712
|
+
cancel: {
|
|
713
|
+
value: (reason) => {
|
|
714
|
+
if (canceled)
|
|
715
|
+
return;
|
|
716
|
+
canceled = true;
|
|
717
|
+
controller.abort(new CancelError(reason, options));
|
|
718
|
+
},
|
|
719
|
+
},
|
|
720
|
+
isCanceled: { get: () => canceled },
|
|
721
|
+
});
|
|
722
|
+
return promise;
|
|
723
|
+
}
|
|
724
|
+
/* ------------------------------------------------------------------ */
|
|
725
|
+
/* Client factory */
|
|
726
|
+
/* ------------------------------------------------------------------ */
|
|
727
|
+
function createHttpClient(defaults = {}) {
|
|
728
|
+
const request = (url, options = {}) => {
|
|
729
|
+
const merged = mergeOptions(defaults, options);
|
|
730
|
+
const normalized = normalize(url, merged);
|
|
731
|
+
return createResponsePromise(normalized, merged.handlers ?? []);
|
|
732
|
+
};
|
|
733
|
+
const verb = (method) => (url, options) => request(url, { ...options, method });
|
|
734
|
+
const client = request;
|
|
735
|
+
Object.assign(client, {
|
|
736
|
+
get: verb('GET'),
|
|
737
|
+
post: verb('POST'),
|
|
738
|
+
put: verb('PUT'),
|
|
739
|
+
patch: verb('PATCH'),
|
|
740
|
+
delete: verb('DELETE'),
|
|
741
|
+
head: verb('HEAD'),
|
|
742
|
+
extend: (options) => createHttpClient(mergeOptions(defaults, options)),
|
|
743
|
+
});
|
|
744
|
+
Object.defineProperty(client, 'defaults', { value: defaults });
|
|
745
|
+
return client;
|
|
746
|
+
}
|
|
747
|
+
/** Default client, analogous to `import got from 'got'`. */
|
|
748
|
+
exports.http = createHttpClient();
|
|
749
|
+
//# sourceMappingURL=HttpClient.js.map
|