apify-client 3.0.0-beta.22 → 3.0.0-beta.24
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +6 -0
- package/dist/apify_api_error.d.ts +3 -3
- package/dist/apify_api_error.js +11 -4
- package/dist/apify_client.d.ts +79 -5
- package/dist/apify_client.js +92 -16
- package/dist/base/api_client.d.ts +1 -1
- package/dist/bundle.js +14 -14
- package/dist/bundle.js.map +1 -1
- package/dist/generated/schemas.d.ts +110 -110
- package/dist/http_clients/axios.d.ts +60 -0
- package/dist/http_clients/axios.js +117 -0
- package/dist/http_clients/base.d.ts +333 -0
- package/dist/http_clients/base.js +583 -0
- package/dist/http_clients/index.d.ts +4 -0
- package/dist/http_clients/index.js +2 -0
- package/dist/http_compressors/base.d.ts +40 -0
- package/dist/http_compressors/base.js +9 -0
- package/dist/http_compressors/brotli.d.ts +33 -0
- package/dist/http_compressors/brotli.js +39 -0
- package/dist/http_compressors/gzip.d.ts +33 -0
- package/dist/http_compressors/gzip.js +39 -0
- package/dist/http_compressors/index.d.ts +6 -0
- package/dist/http_compressors/index.js +2 -0
- package/dist/http_compressors/resolve.d.ts +23 -0
- package/dist/http_compressors/resolve.js +27 -0
- package/dist/index.d.ts +3 -1
- package/dist/index.js +3 -1
- package/dist/invalid_response_body_error.d.ts +13 -0
- package/dist/invalid_response_body_error.js +17 -0
- package/dist/resource_clients/actor.js +2 -4
- package/dist/resource_clients/dataset.js +4 -3
- package/dist/resource_clients/key_value_store.js +1 -1
- package/dist/resource_clients/run.d.ts +1 -1
- package/dist/resource_clients/run.js +1 -2
- package/dist/resource_clients/task.js +1 -2
- package/dist/runtime/node.js +10 -19
- package/dist/runtime/types.d.ts +12 -10
- package/dist/runtime/web.js +4 -3
- package/dist/utils.d.ts +14 -7
- package/dist/utils.js +9 -15
- package/package.json +1 -3
- package/dist/http_client.d.ts +0 -55
- package/dist/http_client.js +0 -260
- package/dist/interceptors.d.ts +0 -19
- package/dist/interceptors.js +0 -123
package/dist/http_client.js
DELETED
|
@@ -1,260 +0,0 @@
|
|
|
1
|
-
import retry from 'async-retry';
|
|
2
|
-
import axios, { AxiosHeaders } from 'axios';
|
|
3
|
-
import { APIFY_ENV_VARS } from '@apify/consts';
|
|
4
|
-
import { concatStreamToBuffer } from '@apify/utilities';
|
|
5
|
-
import { ApifyApiError } from './apify_api_error.js';
|
|
6
|
-
import { InvalidResponseBodyError, requestInterceptors, responseInterceptors } from './interceptors.js';
|
|
7
|
-
import { runtime } from '#runtime';
|
|
8
|
-
import { asArray, cast, getEnv, isStream, version } from './utils.js';
|
|
9
|
-
const RATE_LIMIT_EXCEEDED_STATUS_CODE = 429;
|
|
10
|
-
export class HttpClient {
|
|
11
|
-
stats;
|
|
12
|
-
maxRetries;
|
|
13
|
-
minDelayBetweenRetriesMillis;
|
|
14
|
-
userProvidedRequestInterceptors;
|
|
15
|
-
logger;
|
|
16
|
-
/** Duration of each timeout tier, in milliseconds. */
|
|
17
|
-
timeoutMillis;
|
|
18
|
-
/** Cap on the timeout of a single request attempt, in milliseconds. */
|
|
19
|
-
timeoutMaxMillis;
|
|
20
|
-
httpAgent;
|
|
21
|
-
httpsAgent;
|
|
22
|
-
axios;
|
|
23
|
-
workflowKey;
|
|
24
|
-
#httpAgentsPromise;
|
|
25
|
-
constructor(options) {
|
|
26
|
-
const { token } = options;
|
|
27
|
-
this.stats = options.apifyClientStats;
|
|
28
|
-
this.maxRetries = options.maxRetries;
|
|
29
|
-
this.minDelayBetweenRetriesMillis = options.minDelayBetweenRetriesMillis;
|
|
30
|
-
this.userProvidedRequestInterceptors = options.requestInterceptors;
|
|
31
|
-
this.timeoutMillis = {
|
|
32
|
-
short: options.timeoutShortSecs * 1000,
|
|
33
|
-
medium: options.timeoutMediumSecs * 1000,
|
|
34
|
-
long: options.timeoutLongSecs * 1000,
|
|
35
|
-
};
|
|
36
|
-
this.timeoutMaxMillis = options.timeoutMaxSecs * 1000;
|
|
37
|
-
this.logger = options.logger;
|
|
38
|
-
this.workflowKey = options.workflowKey || getEnv(APIFY_ENV_VARS.WORKFLOW_KEY);
|
|
39
|
-
this.axios = axios.create({
|
|
40
|
-
// Disable axios's built-in proxy handling since we're using custom agents
|
|
41
|
-
proxy: false,
|
|
42
|
-
paramsSerializer: (params) => {
|
|
43
|
-
const formattedParams = Object.entries(params)
|
|
44
|
-
.filter(([, value]) => value !== undefined)
|
|
45
|
-
.map(([key, value]) => {
|
|
46
|
-
if (value instanceof Date) {
|
|
47
|
-
return [key, value.toISOString()];
|
|
48
|
-
}
|
|
49
|
-
const updatedValue = typeof value === 'boolean' ? Number(value) : value;
|
|
50
|
-
return [key, String(updatedValue)];
|
|
51
|
-
});
|
|
52
|
-
return new URLSearchParams(formattedParams).toString();
|
|
53
|
-
},
|
|
54
|
-
validateStatus: null,
|
|
55
|
-
// Interceptors serialize requests and parse responses instead. Empty arrays rather than `undefined`,
|
|
56
|
-
// which axios fills in with its default transforms.
|
|
57
|
-
transformRequest: [],
|
|
58
|
-
transformResponse: [],
|
|
59
|
-
responseType: 'arraybuffer',
|
|
60
|
-
// Every request sets its own timeout in `createRequestHandler`, so the default only backs a raw
|
|
61
|
-
// `axios.request()` call.
|
|
62
|
-
timeout: this.timeoutMaxMillis,
|
|
63
|
-
// maxBodyLength needs to be Infinity, because -1 falls back to a 10 MB default
|
|
64
|
-
// from an axios subdependency - 'follow-redirects'
|
|
65
|
-
maxBodyLength: Infinity,
|
|
66
|
-
// maxContentLength must be -1, because Infinity will cause axios to run super slow
|
|
67
|
-
// thanks to a bug that's now fixed, but not released yet https://github.com/axios/axios/pull/3738
|
|
68
|
-
maxContentLength: -1,
|
|
69
|
-
});
|
|
70
|
-
// Clean all default headers because they only make a mess and their merging is difficult to understand and buggy.
|
|
71
|
-
this.axios.defaults.headers = new AxiosHeaders();
|
|
72
|
-
// If workflow key is available, pass it as a header
|
|
73
|
-
if (this.workflowKey) {
|
|
74
|
-
this.axios.defaults.headers['X-Apify-Workflow-Key'] = this.workflowKey;
|
|
75
|
-
}
|
|
76
|
-
// Attach Authorization header for all requests if token was provided
|
|
77
|
-
if (token) {
|
|
78
|
-
this.axios.defaults.headers.Authorization = `Bearer ${token}`;
|
|
79
|
-
}
|
|
80
|
-
// Browsers do not let a page set the header, so it is only sent where the runtime describes its platform.
|
|
81
|
-
if (runtime.platform) {
|
|
82
|
-
const isAtHome = !!getEnv(APIFY_ENV_VARS.IS_AT_HOME);
|
|
83
|
-
let userAgent = `ApifyClient/${version} (${runtime.platform}); isAtHome/${isAtHome}`;
|
|
84
|
-
if (options.userAgentSuffix) {
|
|
85
|
-
userAgent += `; ${asArray(options.userAgentSuffix).join('; ')}`;
|
|
86
|
-
}
|
|
87
|
-
this.axios.defaults.headers['User-Agent'] = userAgent;
|
|
88
|
-
}
|
|
89
|
-
requestInterceptors.forEach((i) => this.axios.interceptors.request.use(i));
|
|
90
|
-
this.userProvidedRequestInterceptors.forEach((i) => this.axios.interceptors.request.use(i));
|
|
91
|
-
responseInterceptors.forEach((i) => this.axios.interceptors.response.use(i));
|
|
92
|
-
}
|
|
93
|
-
async #ensureHttpAgents() {
|
|
94
|
-
this.#httpAgentsPromise ??= this.#initHttpAgents();
|
|
95
|
-
return this.#httpAgentsPromise;
|
|
96
|
-
}
|
|
97
|
-
async #initHttpAgents() {
|
|
98
|
-
const agents = await runtime.createHttpAgents({ timeoutMillis: this.timeoutMaxMillis });
|
|
99
|
-
if (!agents)
|
|
100
|
-
return;
|
|
101
|
-
this.httpAgent = agents.httpAgent;
|
|
102
|
-
this.httpsAgent = agents.httpsAgent;
|
|
103
|
-
this.axios.defaults.httpAgent = this.httpAgent;
|
|
104
|
-
this.axios.defaults.httpsAgent = this.httpsAgent;
|
|
105
|
-
}
|
|
106
|
-
async call(config) {
|
|
107
|
-
await this.#ensureHttpAgents();
|
|
108
|
-
this.stats.calls++;
|
|
109
|
-
const makeRequest = this.#createRequestHandler(config);
|
|
110
|
-
return retry(makeRequest, {
|
|
111
|
-
retries: this.maxRetries,
|
|
112
|
-
minTimeout: this.minDelayBetweenRetriesMillis,
|
|
113
|
-
onRetry: (error, attempt) => this.#onRequestRetry(error, attempt),
|
|
114
|
-
});
|
|
115
|
-
}
|
|
116
|
-
#informAboutStreamNoRetry() {
|
|
117
|
-
this.logger.warningOnce('Request body was a stream - retrying will not work, as part of it was already consumed.');
|
|
118
|
-
this.logger.warningOnce('If you want Apify client to handle retries for you, collect the stream into a buffer before sending it.');
|
|
119
|
-
}
|
|
120
|
-
/**
|
|
121
|
-
* Successful responses are returned, errors and unsuccessful
|
|
122
|
-
* status codes are retried. See the following functions for the
|
|
123
|
-
* retrying logic.
|
|
124
|
-
*/
|
|
125
|
-
#createRequestHandler(config) {
|
|
126
|
-
const { timeoutSecs = 'medium', ...axiosConfig } = config;
|
|
127
|
-
const makeRequest = async (stopTrying, attempt) => {
|
|
128
|
-
this.stats.requests++;
|
|
129
|
-
let response;
|
|
130
|
-
const requestIsStream = isStream(config.data);
|
|
131
|
-
try {
|
|
132
|
-
if (requestIsStream) {
|
|
133
|
-
// Handling redirects is not possible without buffering - part of the stream has already been sent and can't be recovered
|
|
134
|
-
// when server sends the redirect. Therefore we need to override this in Axios config to prevent it from buffering the body.
|
|
135
|
-
// see also axios/axios#1045
|
|
136
|
-
axiosConfig.maxRedirects = 0;
|
|
137
|
-
}
|
|
138
|
-
response = await this.axios.request({
|
|
139
|
-
...axiosConfig,
|
|
140
|
-
timeout: this.#computeTimeoutMillis(timeoutSecs, attempt),
|
|
141
|
-
});
|
|
142
|
-
if (this.#isStatusOk(response.status))
|
|
143
|
-
return response;
|
|
144
|
-
// A failed request with `responseType: 'stream'` carries the API error body in the stream. Read
|
|
145
|
-
// it so that `ApifyApiError` can parse it like any other error body. A body that cannot be read
|
|
146
|
-
// leaves the error without a message, which beats losing the status code to a stream error.
|
|
147
|
-
if (isStream(response.data)) {
|
|
148
|
-
response.data = await concatStreamToBuffer(response.data).catch(() => undefined);
|
|
149
|
-
}
|
|
150
|
-
}
|
|
151
|
-
catch (err) {
|
|
152
|
-
return cast(this.#handleRequestError(err, config, stopTrying));
|
|
153
|
-
}
|
|
154
|
-
if (response.status === RATE_LIMIT_EXCEEDED_STATUS_CODE) {
|
|
155
|
-
this.stats.addRateLimitError(attempt);
|
|
156
|
-
}
|
|
157
|
-
const apiError = ApifyApiError.fromResponse(response, attempt);
|
|
158
|
-
if (this.#isStatusCodeRetryable(response.status)) {
|
|
159
|
-
if (requestIsStream) {
|
|
160
|
-
this.#informAboutStreamNoRetry();
|
|
161
|
-
}
|
|
162
|
-
else {
|
|
163
|
-
// allow a retry
|
|
164
|
-
throw apiError;
|
|
165
|
-
}
|
|
166
|
-
}
|
|
167
|
-
stopTrying(apiError);
|
|
168
|
-
return response;
|
|
169
|
-
};
|
|
170
|
-
return makeRequest;
|
|
171
|
-
}
|
|
172
|
-
#isStatusOk(statusCode) {
|
|
173
|
-
return statusCode < 300;
|
|
174
|
-
}
|
|
175
|
-
/**
|
|
176
|
-
* Resolves `timeoutSecs` to the number of milliseconds the given attempt gets. A tier name resolves to
|
|
177
|
-
* its configured duration, a number is taken as seconds, and `'noTimeout'` becomes `0`, which axios reads
|
|
178
|
-
* as no timeout. The result doubles with each attempt and is capped at `timeoutMaxMillis`. A requested
|
|
179
|
-
* value above the cap is capped too, which warns once, since it does not take effect in full.
|
|
180
|
-
*/
|
|
181
|
-
#computeTimeoutMillis(timeoutSecs, attempt) {
|
|
182
|
-
if (timeoutSecs === 'noTimeout')
|
|
183
|
-
return 0;
|
|
184
|
-
const requestedMillis = typeof timeoutSecs === 'number' ? timeoutSecs * 1000 : this.timeoutMillis[timeoutSecs];
|
|
185
|
-
if (requestedMillis > this.timeoutMaxMillis) {
|
|
186
|
-
// `warningOnce` keys by message, so each requested value warns once.
|
|
187
|
-
this.logger.warningOnce(`The requested timeout of ${requestedMillis / 1000}s exceeds timeoutMaxSecs ` +
|
|
188
|
-
`(${this.timeoutMaxMillis / 1000}s) and is capped at it. ` +
|
|
189
|
-
'Raise timeoutMaxSecs on the client to allow longer request timeouts.');
|
|
190
|
-
}
|
|
191
|
-
return Math.min(requestedMillis * 2 ** (attempt - 1), this.timeoutMaxMillis);
|
|
192
|
-
}
|
|
193
|
-
/**
|
|
194
|
-
* Handles all unexpected errors that can happen, but are not
|
|
195
|
-
* Apify API typed errors. E.g. network errors, timeouts and so on.
|
|
196
|
-
*/
|
|
197
|
-
#handleRequestError(err, config, stopTrying) {
|
|
198
|
-
if (this.#isTimeoutError(err) && config.doNotRetryTimeouts) {
|
|
199
|
-
return stopTrying(err);
|
|
200
|
-
}
|
|
201
|
-
if (this.#isRetryableError(err)) {
|
|
202
|
-
if (isStream(config.data)) {
|
|
203
|
-
this.#informAboutStreamNoRetry();
|
|
204
|
-
}
|
|
205
|
-
else {
|
|
206
|
-
throw err;
|
|
207
|
-
}
|
|
208
|
-
}
|
|
209
|
-
return stopTrying(err);
|
|
210
|
-
}
|
|
211
|
-
/**
|
|
212
|
-
* Axios calls req.abort() on timeouts so timeout errors will
|
|
213
|
-
* have a code ECONNABORTED.
|
|
214
|
-
*/
|
|
215
|
-
#isTimeoutError(err) {
|
|
216
|
-
return err.code === 'ECONNABORTED';
|
|
217
|
-
}
|
|
218
|
-
/**
|
|
219
|
-
* We don't want to retry every exception thrown from Axios.
|
|
220
|
-
* The common denominator for retryable errors are network issues.
|
|
221
|
-
* @param {Error} err
|
|
222
|
-
* @private
|
|
223
|
-
*/
|
|
224
|
-
#isRetryableError(err) {
|
|
225
|
-
return this.#isNetworkError(err) || this.#isResponseBodyInvalid(err);
|
|
226
|
-
}
|
|
227
|
-
/**
|
|
228
|
-
* When a network connection to our API is interrupted in the middle of streaming
|
|
229
|
-
* a response, the request often does not fail, but simply contains
|
|
230
|
-
* an incomplete response. This can often be fixed by retrying.
|
|
231
|
-
*/
|
|
232
|
-
#isResponseBodyInvalid(err) {
|
|
233
|
-
return err instanceof InvalidResponseBodyError;
|
|
234
|
-
}
|
|
235
|
-
/**
|
|
236
|
-
* When a network request is attempted by axios and fails,
|
|
237
|
-
* it throws an AxiosError, which will have the request
|
|
238
|
-
* and config (and other) properties.
|
|
239
|
-
*/
|
|
240
|
-
#isNetworkError(err) {
|
|
241
|
-
const hasRequest = err.request && typeof err.request === 'object';
|
|
242
|
-
const hasConfig = err.config && typeof err.config === 'object';
|
|
243
|
-
return hasRequest && hasConfig;
|
|
244
|
-
}
|
|
245
|
-
/**
|
|
246
|
-
* We retry 429 (rate limit) and 500+.
|
|
247
|
-
* For status codes 300-499 (except 429) we do not retry the request,
|
|
248
|
-
* because it's probably caused by invalid url (redirect 3xx) or invalid user input (4xx).
|
|
249
|
-
*/
|
|
250
|
-
#isStatusCodeRetryable(statusCode) {
|
|
251
|
-
const isRateLimitError = statusCode === RATE_LIMIT_EXCEEDED_STATUS_CODE;
|
|
252
|
-
const isInternalError = statusCode >= 500;
|
|
253
|
-
return isRateLimitError || isInternalError;
|
|
254
|
-
}
|
|
255
|
-
#onRequestRetry(error, attempt) {
|
|
256
|
-
if (attempt === Math.round(this.maxRetries / 2)) {
|
|
257
|
-
this.logger.warning(`API request failed ${attempt} times. Max attempts: ${this.maxRetries + 1}.\nCause:${error.stack}`);
|
|
258
|
-
}
|
|
259
|
-
}
|
|
260
|
-
}
|
package/dist/interceptors.d.ts
DELETED
|
@@ -1,19 +0,0 @@
|
|
|
1
|
-
import type { AxiosInterceptorManager, AxiosResponse } from 'axios';
|
|
2
|
-
import type { ApifyRequestConfig, ApifyResponse } from './http_client.js';
|
|
3
|
-
/**
|
|
4
|
-
* This error exists for the quite common situation, where only a partial JSON response is received and
|
|
5
|
-
* an attempt to parse the JSON throws an error. In most cases this can be resolved by retrying the
|
|
6
|
-
* request. We do that by identifying this error in HttpClient.
|
|
7
|
-
*
|
|
8
|
-
* The properties mimic AxiosError for easier integration in HttpClient error handling.
|
|
9
|
-
*/
|
|
10
|
-
export declare class InvalidResponseBodyError extends Error {
|
|
11
|
-
code: string;
|
|
12
|
-
response: AxiosResponse;
|
|
13
|
-
cause: Error;
|
|
14
|
-
constructor(response: AxiosResponse, cause: Error);
|
|
15
|
-
}
|
|
16
|
-
export type RequestInterceptorFunction = Parameters<AxiosInterceptorManager<ApifyRequestConfig>['use']>[0];
|
|
17
|
-
export type ResponseInterceptorFunction = Parameters<AxiosInterceptorManager<ApifyResponse>['use']>[0];
|
|
18
|
-
export declare const requestInterceptors: RequestInterceptorFunction[];
|
|
19
|
-
export declare const responseInterceptors: ResponseInterceptorFunction[];
|
package/dist/interceptors.js
DELETED
|
@@ -1,123 +0,0 @@
|
|
|
1
|
-
import axios, { AxiosHeaders } from 'axios';
|
|
2
|
-
import contentTypeParser from 'content-type';
|
|
3
|
-
import { maybeParseBody } from './body_parser.js';
|
|
4
|
-
import { isCompressibleContentType, maybeCompressValue } from './utils.js';
|
|
5
|
-
/**
|
|
6
|
-
* This error exists for the quite common situation, where only a partial JSON response is received and
|
|
7
|
-
* an attempt to parse the JSON throws an error. In most cases this can be resolved by retrying the
|
|
8
|
-
* request. We do that by identifying this error in HttpClient.
|
|
9
|
-
*
|
|
10
|
-
* The properties mimic AxiosError for easier integration in HttpClient error handling.
|
|
11
|
-
*/
|
|
12
|
-
export class InvalidResponseBodyError extends Error {
|
|
13
|
-
code;
|
|
14
|
-
response;
|
|
15
|
-
constructor(response, cause) {
|
|
16
|
-
super(`Response body could not be parsed.\nCause:${cause.message}`);
|
|
17
|
-
this.name = this.constructor.name;
|
|
18
|
-
this.code = 'invalid-response-body';
|
|
19
|
-
this.response = response;
|
|
20
|
-
this.cause = cause;
|
|
21
|
-
}
|
|
22
|
-
}
|
|
23
|
-
/**
|
|
24
|
-
* Reads a request header regardless of the casing it was set with, since HTTP header names are case-insensitive
|
|
25
|
-
* while the config keeps whatever casing the caller used.
|
|
26
|
-
*/
|
|
27
|
-
function getHeader(config, name) {
|
|
28
|
-
const wanted = name.toLowerCase();
|
|
29
|
-
const key = Object.keys(config.headers ?? {}).find((candidate) => candidate.toLowerCase() === wanted);
|
|
30
|
-
const value = key === undefined ? undefined : config.headers?.[key];
|
|
31
|
-
return typeof value === 'string' ? value : undefined;
|
|
32
|
-
}
|
|
33
|
-
function serializeRequest(config) {
|
|
34
|
-
// A string body with an explicit content type is already serialized and goes out as it is. The axios default
|
|
35
|
-
// transform would otherwise parse a JSON one in full just to check that it is valid, which for a body assembled
|
|
36
|
-
// from thousands of pre-serialized requests costs about as much as serializing them did.
|
|
37
|
-
if (typeof config.data === 'string' && getHeader(config, 'content-type'))
|
|
38
|
-
return config;
|
|
39
|
-
const [defaultTransform] = axios.defaults.transformRequest;
|
|
40
|
-
// The function not only serializes data, but it also adds correct headers.
|
|
41
|
-
const data = defaultTransform(config.data, config.headers);
|
|
42
|
-
// Actor inputs can include functions and we don't want to omit those,
|
|
43
|
-
// because it's convenient for users. JSON.stringify removes them.
|
|
44
|
-
// It's a bit inefficient that we serialize the JSON twice, but I feel
|
|
45
|
-
// it's a small price to pay. The axios default transform does a lot
|
|
46
|
-
// of body type checks and we would have to copy all of them to the resource clients.
|
|
47
|
-
if (config.stringifyFunctions) {
|
|
48
|
-
const contentTypeHeader = getHeader(config, 'content-type');
|
|
49
|
-
try {
|
|
50
|
-
const type = contentTypeHeader ? contentTypeParser.parse(contentTypeHeader).type : undefined;
|
|
51
|
-
if (type === 'application/json' && typeof config.data === 'object') {
|
|
52
|
-
config.data = stringifyWithFunctions(config.data);
|
|
53
|
-
}
|
|
54
|
-
else {
|
|
55
|
-
config.data = data;
|
|
56
|
-
}
|
|
57
|
-
}
|
|
58
|
-
catch {
|
|
59
|
-
config.data = data;
|
|
60
|
-
}
|
|
61
|
-
}
|
|
62
|
-
else {
|
|
63
|
-
config.data = data;
|
|
64
|
-
}
|
|
65
|
-
return config;
|
|
66
|
-
}
|
|
67
|
-
function ensureHeadersPrototype(config) {
|
|
68
|
-
if (config.headers && !(config.headers instanceof AxiosHeaders)) {
|
|
69
|
-
Object.setPrototypeOf(config.headers, AxiosHeaders.prototype);
|
|
70
|
-
}
|
|
71
|
-
return config;
|
|
72
|
-
}
|
|
73
|
-
/**
|
|
74
|
-
* JSON.stringify() that serializes functions to string instead
|
|
75
|
-
* of replacing them with null or removing them.
|
|
76
|
-
*/
|
|
77
|
-
function stringifyWithFunctions(obj) {
|
|
78
|
-
return JSON.stringify(obj, (_key, value) => {
|
|
79
|
-
return typeof value === 'function' ? value.toString() : value;
|
|
80
|
-
});
|
|
81
|
-
}
|
|
82
|
-
async function maybeCompressRequest(config) {
|
|
83
|
-
// A caller-supplied encoding means the body is already encoded and the header describes it, so leave both alone.
|
|
84
|
-
if (getHeader(config, 'content-encoding'))
|
|
85
|
-
return config;
|
|
86
|
-
if (!isCompressibleContentType(getHeader(config, 'content-type')))
|
|
87
|
-
return config;
|
|
88
|
-
const maybeCompressed = await maybeCompressValue(config.data);
|
|
89
|
-
if (maybeCompressed) {
|
|
90
|
-
config.headers ??= {};
|
|
91
|
-
config.headers['content-encoding'] = maybeCompressed.encoding;
|
|
92
|
-
config.data = maybeCompressed.data;
|
|
93
|
-
}
|
|
94
|
-
return config;
|
|
95
|
-
}
|
|
96
|
-
function parseResponseData(response) {
|
|
97
|
-
if (!response.data || // Nothing to do here.
|
|
98
|
-
response.config.responseType !== 'arraybuffer' || // We don't want to parse custom response types.
|
|
99
|
-
response.config.forceBuffer // Apify custom property to prevent parsing of buffer.
|
|
100
|
-
) {
|
|
101
|
-
return response;
|
|
102
|
-
}
|
|
103
|
-
// A `Buffer` from the Node.js adapter and an `ArrayBuffer` from the browser ones both carry `byteLength`.
|
|
104
|
-
if (!response.data.byteLength) {
|
|
105
|
-
// undefined is better than an empty buffer
|
|
106
|
-
response.data = undefined;
|
|
107
|
-
return response;
|
|
108
|
-
}
|
|
109
|
-
const contentTypeHeader = response.headers['content-type'];
|
|
110
|
-
try {
|
|
111
|
-
response.data = maybeParseBody(response.data, contentTypeHeader);
|
|
112
|
-
}
|
|
113
|
-
catch (err) {
|
|
114
|
-
throw new InvalidResponseBodyError(response, err);
|
|
115
|
-
}
|
|
116
|
-
return response;
|
|
117
|
-
}
|
|
118
|
-
export const requestInterceptors = [
|
|
119
|
-
maybeCompressRequest,
|
|
120
|
-
serializeRequest,
|
|
121
|
-
ensureHeadersPrototype,
|
|
122
|
-
];
|
|
123
|
-
export const responseInterceptors = [parseResponseData];
|