apify-client 3.0.0-rc.0 → 3.0.0-rc.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.
Files changed (52) hide show
  1. package/README.md +6 -0
  2. package/dist/apify_api_error.d.ts +2 -1
  3. package/dist/apify_api_error.js +2 -1
  4. package/dist/apify_client_error.d.ts +10 -0
  5. package/dist/apify_client_error.js +10 -0
  6. package/dist/base/api_client.js +8 -20
  7. package/dist/base/resource_client.js +8 -8
  8. package/dist/bundle.js +13 -13
  9. package/dist/bundle.js.map +1 -1
  10. package/dist/generated/api.d.ts +2300 -690
  11. package/dist/generated/schemas.d.ts +1720 -246
  12. package/dist/generated/schemas.js +416 -75
  13. package/dist/http_clients/axios.d.ts +2 -1
  14. package/dist/http_clients/axios.js +6 -4
  15. package/dist/http_clients/base.d.ts +80 -20
  16. package/dist/http_clients/base.js +127 -40
  17. package/dist/http_compressors/index.d.ts +2 -0
  18. package/dist/http_compressors/index.js +1 -0
  19. package/dist/http_compressors/resolve.d.ts +4 -3
  20. package/dist/http_compressors/resolve.js +4 -1
  21. package/dist/http_compressors/zstd.d.ts +34 -0
  22. package/dist/http_compressors/zstd.js +43 -0
  23. package/dist/index.d.ts +2 -0
  24. package/dist/index.js +2 -0
  25. package/dist/invalid_response_body_error.d.ts +5 -4
  26. package/dist/invalid_response_body_error.js +5 -4
  27. package/dist/models.d.ts +30 -61
  28. package/dist/resource_clients/actor.d.ts +30 -0
  29. package/dist/resource_clients/actor.js +43 -0
  30. package/dist/resource_clients/actor_server.d.ts +149 -0
  31. package/dist/resource_clients/actor_server.js +199 -0
  32. package/dist/resource_clients/actor_version.d.ts +5 -0
  33. package/dist/resource_clients/dataset.d.ts +33 -4
  34. package/dist/resource_clients/dataset.js +16 -54
  35. package/dist/resource_clients/key_value_store.d.ts +51 -11
  36. package/dist/resource_clients/key_value_store.js +59 -15
  37. package/dist/resource_clients/log.d.ts +29 -3
  38. package/dist/resource_clients/log.js +7 -11
  39. package/dist/resource_clients/request_queue.d.ts +9 -0
  40. package/dist/resource_clients/request_queue.js +9 -6
  41. package/dist/resource_clients/run.d.ts +9 -0
  42. package/dist/resource_clients/run.js +6 -3
  43. package/dist/response_validation_error.d.ts +2 -1
  44. package/dist/response_validation_error.js +2 -1
  45. package/dist/runtime/node.js +44 -6
  46. package/dist/runtime/types.d.ts +9 -1
  47. package/dist/runtime/web.js +4 -1
  48. package/dist/schemas.d.ts +369 -3
  49. package/dist/schemas.js +25 -3
  50. package/dist/utils.d.ts +23 -26
  51. package/dist/utils.js +32 -25
  52. package/package.json +23 -23
@@ -54,7 +54,8 @@ export declare class AxiosHttpClient extends HttpClient {
54
54
  close(): Promise<void>;
55
55
  /**
56
56
  * Sends the request through axios and hands the raw response back. A stream body is sent without following
57
- * redirects, since the part of it already sent could not be replayed.
57
+ * redirects, since the part of it already sent could not be replayed, and so is a request with
58
+ * `followRedirects: false`. In the browser, the browser follows redirects itself.
58
59
  */
59
60
  sendRequest(request: HttpRequest): Promise<HttpResponse>;
60
61
  }
@@ -78,11 +78,12 @@ export class AxiosHttpClient extends HttpClient {
78
78
  }
79
79
  /**
80
80
  * Sends the request through axios and hands the raw response back. A stream body is sent without following
81
- * redirects, since the part of it already sent could not be replayed.
81
+ * redirects, since the part of it already sent could not be replayed, and so is a request with
82
+ * `followRedirects: false`. In the browser, the browser follows redirects itself.
82
83
  */
83
84
  async sendRequest(request) {
84
85
  await this.#ensureHttpAgents();
85
- const { method, url, headers, body, timeoutMillis, stream, signal } = request;
86
+ const { method, url, headers, body, timeoutMillis, stream, followRedirects, signal } = request;
86
87
  const response = await this.axios.request({
87
88
  method,
88
89
  url,
@@ -92,8 +93,9 @@ export class AxiosHttpClient extends HttpClient {
92
93
  timeout: timeoutMillis ?? 0,
93
94
  signal,
94
95
  responseType: stream ? 'stream' : 'arraybuffer',
95
- // See axios/axios#1045 for why axios must not buffer a stream body to follow redirects.
96
- ...(isStream(body) ? { maxRedirects: 0 } : {}),
96
+ // See axios/axios#1045 for why axios must not buffer a stream body to follow redirects. The XHR adapter
97
+ // ignores `maxRedirects`, since the browser follows redirects itself.
98
+ ...(isStream(body) || !followRedirects ? { maxRedirects: 0 } : {}),
97
99
  });
98
100
  return {
99
101
  status: response.status,
@@ -27,9 +27,10 @@ export declare const httpClientOptionsShape: {
27
27
  export type HttpResponseHeaders = Record<string, string | string[] | undefined>;
28
28
  /**
29
29
  * A request body as the transport receives it: already serialized, and compressed when that paid off. A `Readable`
30
- * is passed through untouched and is only available in Node.js.
30
+ * is passed through untouched and is only available in Node.js. A `Blob` body reaches a Node.js transport as a
31
+ * fresh `Readable` over its bytes for every attempt, and a transport in any other runtime as the `Blob` itself.
31
32
  */
32
- export type HttpRequestBody = string | Buffer | ArrayBuffer | ArrayBufferView | Readable;
33
+ export type HttpRequestBody = string | Buffer | ArrayBuffer | ArrayBufferView | Readable | Blob;
33
34
  /**
34
35
  * A response body as the transport hands it back: the raw bytes, a `Readable` when the request asked for a streamed
35
36
  * response, or `undefined` when the response carried no body.
@@ -63,8 +64,9 @@ export interface ApifyRequestConfig {
63
64
  * Request body. A plain object or array is serialized to JSON and sent as `application/json`, or form-encoded
64
65
  * when a `Content-Type: application/x-www-form-urlencoded` header asks for it. A string, binary value
65
66
  * (`Buffer`, `ArrayBuffer`, typed array) or `Readable` is sent as it is, and `URLSearchParams` is sent
66
- * form-encoded. A `Blob`, `File`, `FormData` or web `ReadableStream` is rejected with a `TypeError`, since
67
- * serializing one would send an empty body.
67
+ * form-encoded. A `Blob` or `File`, such as one from `fs.openAsBlob()`, is streamed without being held in
68
+ * memory, under its own `type` when no `Content-Type` header is set. A `FormData` or web `ReadableStream` is
69
+ * rejected with a `TypeError`, since serializing one would send an empty body.
68
70
  */
69
71
  data?: unknown;
70
72
  /**
@@ -82,6 +84,40 @@ export interface ApifyRequestConfig {
82
84
  stringifyFunctions?: boolean;
83
85
  /** Give up on the first transport timeout instead of retrying it. */
84
86
  doNotRetryTimeouts?: boolean;
87
+ /**
88
+ * How to compress the request body: an {@link HttpCompressor} for this request only, or `false` to send the body
89
+ * uncompressed. Defaults to the client's {@link HttpClient.httpCompressor}.
90
+ */
91
+ compression?: HttpCompressor | false;
92
+ /**
93
+ * Header that carries the client's API token for this request. The Apify API reads `Authorization`. Actor
94
+ * servers also accept `X-Apify-Authorization`, which the platform removes before the request reaches the Actor,
95
+ * so the `Authorization` header stays free for the Actor's own authentication. A per-request header of either
96
+ * name still wins.
97
+ * @default 'Authorization'
98
+ */
99
+ authorizationHeader?: 'Authorization' | 'X-Apify-Authorization';
100
+ /**
101
+ * Whether an error status throws {@link ApifyApiError}. With `false`, the call resolves to the error response
102
+ * once no retry follows, and a rate limit (429) doesn't count toward the client's statistics, which track the
103
+ * API's rate limits.
104
+ * @default true
105
+ */
106
+ throwOnErrorStatus?: boolean;
107
+ /** Status codes to retry. Defaults to rate limits (429) and server errors (5xx). */
108
+ retryStatusCodes?: readonly number[];
109
+ /**
110
+ * Whether transport errors, timeouts included, are retried. With `false`, the first one fails the call, since the
111
+ * request may have reached the server before it failed.
112
+ * @default true
113
+ */
114
+ retryTransportErrors?: boolean;
115
+ /**
116
+ * Whether the transport follows redirects. With `false`, a redirect response is handled like an error status, so
117
+ * headers that carry the token never go to a host the server picked.
118
+ * @default true
119
+ */
120
+ followRedirects?: boolean;
85
121
  /**
86
122
  * Aborts the call. Once the signal aborts, the attempt in flight is ended, no retry follows, and the call
87
123
  * rejects with the signal's `reason`.
@@ -89,7 +125,8 @@ export interface ApifyRequestConfig {
89
125
  signal?: AbortSignal;
90
126
  }
91
127
  /**
92
- * A successful response as {@link HttpClient.call} resolves to it.
128
+ * A response as {@link HttpClient.call} resolves to it: a success, or an error response when the request sets
129
+ * {@link ApifyRequestConfig.throwOnErrorStatus} to `false`.
93
130
  *
94
131
  * @template T - Type of the parsed body.
95
132
  */
@@ -122,6 +159,11 @@ export interface HttpRequest {
122
159
  timeoutMillis?: number;
123
160
  /** Whether to hand the body back unread as a `Readable`, so the caller can stream it. */
124
161
  stream: boolean;
162
+ /**
163
+ * Whether to follow redirects. With `false`, return a redirect response as it is: the request carries a token
164
+ * that must not follow a redirect to another host.
165
+ */
166
+ followRedirects: boolean;
125
167
  /**
126
168
  * The caller's abort signal, to hand to the HTTP library alongside the timeout. The pipeline stops retrying
127
169
  * once it aborts, so the transport only has to end the request in flight.
@@ -189,8 +231,13 @@ export interface HttpClientOptions {
189
231
  *
190
232
  * Overriding {@link call} itself is also supported and bypasses the transport hooks entirely. Such a client has
191
233
  * to send the default headers from `defaultHeaders` with every request, otherwise the `Authorization` header never
192
- * reaches the API. The protected helpers `prepareRequest()`, `buildUrl()` and `computeTimeoutMillis()` stay
193
- * available to it.
234
+ * reaches the API. It also has to honor the per-request options {@link ApifyRequestConfig.compression},
235
+ * {@link ApifyRequestConfig.authorizationHeader}, {@link ApifyRequestConfig.throwOnErrorStatus},
236
+ * {@link ApifyRequestConfig.retryStatusCodes}, {@link ApifyRequestConfig.retryTransportErrors} and
237
+ * {@link ApifyRequestConfig.followRedirects}.
238
+ * {@link ActorServerClient.request} relies on them to keep the token away from the Actor's code, to return the
239
+ * server's error responses and to avoid sending a request to the Actor twice. The protected helpers
240
+ * `prepareRequest()`, `buildUrl()` and `computeTimeoutMillis()` stay available to it.
194
241
  *
195
242
  * @example
196
243
  * ```javascript
@@ -278,7 +325,9 @@ export declare abstract class HttpClient {
278
325
  * The inherited {@link call} needs it, so every transport has to implement it. Let the library's errors
279
326
  * propagate unwrapped: {@link call} classifies them through {@link isRetryableTransportError} and
280
327
  * {@link isTimeoutError}. Return error responses as they are too, the pipeline turns them into
281
- * {@link ApifyApiError} and decides whether to retry.
328
+ * {@link ApifyApiError} and decides whether to retry. Reject when the connection drops before the body is
329
+ * complete: the pipeline takes a returned body as whole and does not retry one that fails to parse. When
330
+ * `request.followRedirects` is `false`, return a redirect response as it is, since the request carries a token.
282
331
  *
283
332
  * @param request - The request to send, with the headers merged, the body serialized and the query encoded.
284
333
  * @returns The response, with the body unread when `request.stream` is set and as raw bytes otherwise.
@@ -288,26 +337,32 @@ export declare abstract class HttpClient {
288
337
  * Makes an API request with automatic retries and exponential backoff.
289
338
  *
290
339
  * Network errors the transport classifies as retryable, rate limits (HTTP 429) and server errors (HTTP 5xx)
291
- * are retried up to {@link maxRetries} times. Any other error status is thrown as {@link ApifyApiError} right
292
- * away. A request whose body is a `Readable` is never retried, since part of the stream has already been
293
- * consumed by the time the failure shows. Aborting `config.signal` ends the attempt in flight, skips the
294
- * remaining retries and rejects the call with the signal's `reason`.
340
+ * are retried up to {@link maxRetries} times, and `config.retryStatusCodes` picks other statuses to retry. Any
341
+ * other error status is thrown as {@link ApifyApiError} right away, or returned when `config.throwOnErrorStatus`
342
+ * is `false`. A request whose body is a `Readable` is never retried, since part of the stream has already been
343
+ * consumed by the time the failure shows. A `Blob` body is read again for every attempt, so it is retried like
344
+ * any other, unless reading the blob itself fails: that error is thrown right away, with the transport error
345
+ * as its `cause` when that error does not already wrap it. Aborting `config.signal` ends the attempt in flight,
346
+ * skips the remaining retries and rejects the call with the signal's `reason`.
295
347
  *
296
348
  * @template T - Type of the parsed response body.
297
349
  * @param config - The request to make.
298
- * @returns The successful response.
299
- * @throws {ApifyApiError} When the API responds with an error status the retries could not fix.
350
+ * @returns The successful response, or the error response when `config.throwOnErrorStatus` is `false`.
351
+ * @throws {ApifyApiError} When the API responds with an error status the retries could not fix, unless
352
+ * `config.throwOnErrorStatus` is `false`.
300
353
  */
301
354
  call<T = any>(config: ApifyRequestConfig): Promise<ApifyResponse<T>>;
302
355
  /**
303
356
  * Prepares the headers and the body of a request.
304
357
  *
305
- * Merges the client's default headers with the per-request ones, header names compared case-insensitively and
306
- * the per-request values winning. Serializes an object body to JSON, setting `Content-Type: application/json`
307
- * unless the caller supplied a content type. Runs the body through {@link httpCompressor} unless a
308
- * `Content-Encoding` header is already set, the body is too small, or its content type says the payload is
309
- * already compressed. A caller-supplied `Content-Encoding` is forwarded as it is, which is how a pre-encoded
310
- * body is uploaded, and `Content-Encoding: identity` opts a single request out of compression.
358
+ * Merges the client's default headers with the per-request ones, header names compared case-insensitively and the
359
+ * per-request values winning, after moving the default `Authorization` header to `X-Apify-Authorization` when
360
+ * `config.authorizationHeader` asks for it. Serializes an object body to JSON, setting
361
+ * `Content-Type: application/json` unless the caller supplied a content type. Runs the body through
362
+ * {@link httpCompressor}, or the compressor in `config.compression`, unless `config.compression` is `false`, a
363
+ * `Content-Encoding` header is already set, the body is too small, or its content type says the payload is already
364
+ * compressed. A caller-supplied `Content-Encoding` is forwarded as it is, which is how a pre-encoded body is
365
+ * uploaded, and `Content-Encoding: identity` opts a single request out of compression.
311
366
  */
312
367
  protected prepareRequest(config: ApifyRequestConfig): Promise<{
313
368
  headers: Record<string, string>;
@@ -329,3 +384,8 @@ export declare abstract class HttpClient {
329
384
  */
330
385
  protected computeTimeoutMillis(attempt: number, timeoutSecs?: Timeout): number | undefined;
331
386
  }
387
+ /**
388
+ * Merges two header records, header names compared case-insensitively. A header from `override` replaces a
389
+ * same-named header in `base` whatever the casing of either, and keeps the casing it was passed with.
390
+ */
391
+ export declare function mergeHeaders(base: Record<string, string>, override?: Record<string, string>): Record<string, string>;
@@ -9,7 +9,7 @@ import { InvalidResponseBodyError } from '../invalid_response_body_error.js';
9
9
  import { Statistics } from '../statistics.js';
10
10
  import { DEFAULT_TIMEOUT_LONG_SECS, DEFAULT_TIMEOUT_MAX_SECS, DEFAULT_TIMEOUT_MEDIUM_SECS, DEFAULT_TIMEOUT_SHORT_SECS, } from '../timeouts.js';
11
11
  import { runtime } from '#runtime';
12
- import { asArray, getEnv, isBuffer, isCompressibleContentType, isStream, MIN_COMPRESS_BYTES, parseArgument, sleep, toBytes, version, } from '../utils.js';
12
+ import { asArray, getEnv, isBlob, isBuffer, isCompressibleContentType, isStream, MIN_COMPRESS_BYTES, parseArgument, sleep, toBytes, version, } from '../utils.js';
13
13
  export const DEFAULT_MAX_RETRIES = 8;
14
14
  export const DEFAULT_MIN_DELAY_BETWEEN_RETRIES_MILLIS = 500;
15
15
  const RATE_LIMIT_EXCEEDED_STATUS_CODE = 429;
@@ -29,7 +29,7 @@ export const httpClientOptionsShape = {
29
29
  };
30
30
  const httpClientOptionsSchema = z.looseObject(httpClientOptionsShape).partial();
31
31
  /** Objects whose payload does not live in their own enumerable keys, so JSON serialization loses it. */
32
- const UNSERIALIZABLE_OBJECT_TAGS = new Set(['Blob', 'File', 'FormData', 'ReadableStream']);
32
+ const UNSERIALIZABLE_OBJECT_TAGS = new Set(['FormData', 'ReadableStream']);
33
33
  /**
34
34
  * Base class for the HTTP clients used by {@link ApifyClient}.
35
35
  *
@@ -42,8 +42,13 @@ const UNSERIALIZABLE_OBJECT_TAGS = new Set(['Blob', 'File', 'FormData', 'Readabl
42
42
  *
43
43
  * Overriding {@link call} itself is also supported and bypasses the transport hooks entirely. Such a client has
44
44
  * to send the default headers from `defaultHeaders` with every request, otherwise the `Authorization` header never
45
- * reaches the API. The protected helpers `prepareRequest()`, `buildUrl()` and `computeTimeoutMillis()` stay
46
- * available to it.
45
+ * reaches the API. It also has to honor the per-request options {@link ApifyRequestConfig.compression},
46
+ * {@link ApifyRequestConfig.authorizationHeader}, {@link ApifyRequestConfig.throwOnErrorStatus},
47
+ * {@link ApifyRequestConfig.retryStatusCodes}, {@link ApifyRequestConfig.retryTransportErrors} and
48
+ * {@link ApifyRequestConfig.followRedirects}.
49
+ * {@link ActorServerClient.request} relies on them to keep the token away from the Actor's code, to return the
50
+ * server's error responses and to avoid sending a request to the Actor twice. The protected helpers
51
+ * `prepareRequest()`, `buildUrl()` and `computeTimeoutMillis()` stay available to it.
47
52
  *
48
53
  * @example
49
54
  * ```javascript
@@ -169,7 +174,9 @@ export class HttpClient {
169
174
  * The inherited {@link call} needs it, so every transport has to implement it. Let the library's errors
170
175
  * propagate unwrapped: {@link call} classifies them through {@link isRetryableTransportError} and
171
176
  * {@link isTimeoutError}. Return error responses as they are too, the pipeline turns them into
172
- * {@link ApifyApiError} and decides whether to retry.
177
+ * {@link ApifyApiError} and decides whether to retry. Reject when the connection drops before the body is
178
+ * complete: the pipeline takes a returned body as whole and does not retry one that fails to parse. When
179
+ * `request.followRedirects` is `false`, return a redirect response as it is, since the request carries a token.
173
180
  *
174
181
  * @param request - The request to send, with the headers merged, the body serialized and the query encoded.
175
182
  * @returns The response, with the body unread when `request.stream` is set and as raw bytes otherwise.
@@ -181,15 +188,19 @@ export class HttpClient {
181
188
  * Makes an API request with automatic retries and exponential backoff.
182
189
  *
183
190
  * Network errors the transport classifies as retryable, rate limits (HTTP 429) and server errors (HTTP 5xx)
184
- * are retried up to {@link maxRetries} times. Any other error status is thrown as {@link ApifyApiError} right
185
- * away. A request whose body is a `Readable` is never retried, since part of the stream has already been
186
- * consumed by the time the failure shows. Aborting `config.signal` ends the attempt in flight, skips the
187
- * remaining retries and rejects the call with the signal's `reason`.
191
+ * are retried up to {@link maxRetries} times, and `config.retryStatusCodes` picks other statuses to retry. Any
192
+ * other error status is thrown as {@link ApifyApiError} right away, or returned when `config.throwOnErrorStatus`
193
+ * is `false`. A request whose body is a `Readable` is never retried, since part of the stream has already been
194
+ * consumed by the time the failure shows. A `Blob` body is read again for every attempt, so it is retried like
195
+ * any other, unless reading the blob itself fails: that error is thrown right away, with the transport error
196
+ * as its `cause` when that error does not already wrap it. Aborting `config.signal` ends the attempt in flight,
197
+ * skips the remaining retries and rejects the call with the signal's `reason`.
188
198
  *
189
199
  * @template T - Type of the parsed response body.
190
200
  * @param config - The request to make.
191
- * @returns The successful response.
192
- * @throws {ApifyApiError} When the API responds with an error status the retries could not fix.
201
+ * @returns The successful response, or the error response when `config.throwOnErrorStatus` is `false`.
202
+ * @throws {ApifyApiError} When the API responds with an error status the retries could not fix, unless
203
+ * `config.throwOnErrorStatus` is `false`.
193
204
  */
194
205
  async call(config) {
195
206
  config.signal?.throwIfAborted();
@@ -201,24 +212,32 @@ export class HttpClient {
201
212
  /**
202
213
  * Prepares the headers and the body of a request.
203
214
  *
204
- * Merges the client's default headers with the per-request ones, header names compared case-insensitively and
205
- * the per-request values winning. Serializes an object body to JSON, setting `Content-Type: application/json`
206
- * unless the caller supplied a content type. Runs the body through {@link httpCompressor} unless a
207
- * `Content-Encoding` header is already set, the body is too small, or its content type says the payload is
208
- * already compressed. A caller-supplied `Content-Encoding` is forwarded as it is, which is how a pre-encoded
209
- * body is uploaded, and `Content-Encoding: identity` opts a single request out of compression.
215
+ * Merges the client's default headers with the per-request ones, header names compared case-insensitively and the
216
+ * per-request values winning, after moving the default `Authorization` header to `X-Apify-Authorization` when
217
+ * `config.authorizationHeader` asks for it. Serializes an object body to JSON, setting
218
+ * `Content-Type: application/json` unless the caller supplied a content type. Runs the body through
219
+ * {@link httpCompressor}, or the compressor in `config.compression`, unless `config.compression` is `false`, a
220
+ * `Content-Encoding` header is already set, the body is too small, or its content type says the payload is already
221
+ * compressed. A caller-supplied `Content-Encoding` is forwarded as it is, which is how a pre-encoded body is
222
+ * uploaded, and `Content-Encoding: identity` opts a single request out of compression.
210
223
  */
211
224
  async prepareRequest(config) {
212
- let headers = mergeHeaders(this.defaultHeaders, config.headers);
225
+ let headers = mergeHeaders(withAuthorizationHeader(this.defaultHeaders, config.authorizationHeader), config.headers);
213
226
  let body = serializeBody(config.data, headers, config.stringifyFunctions);
214
- const bytes = compressibleBytes(body, headers);
227
+ const compressor = config.compression ?? this.httpCompressor;
228
+ const bytes = compressor && compressibleBytes(body, headers);
215
229
  if (bytes) {
216
- body = await this.httpCompressor.compress(Buffer.from(bytes.buffer, bytes.byteOffset, bytes.byteLength));
230
+ body = await compressor.compress(Buffer.from(bytes.buffer, bytes.byteOffset, bytes.byteLength));
217
231
  // Compressing changes the body length, so a `Content-Length` the caller set describes the wrong body
218
232
  // and would leave the server waiting for bytes that never arrive.
219
- headers = mergeHeaders(headers, { 'Content-Encoding': this.httpCompressor.contentEncoding });
233
+ headers = mergeHeaders(headers, { 'Content-Encoding': compressor.contentEncoding });
220
234
  deleteHeader(headers, 'content-length');
221
235
  }
236
+ // A blob reaches a Node.js transport as a stream, which would go out chunked without a known length.
237
+ // Browsers set the header themselves and refuse to let a page set it.
238
+ if (isBlob(body) && runtime.isNode) {
239
+ headers = mergeHeaders(headers, { 'Content-Length': String(body.size) });
240
+ }
222
241
  return { headers, body };
223
242
  }
224
243
  /**
@@ -296,35 +315,60 @@ export class HttpClient {
296
315
  }
297
316
  /**
298
317
  * Executes one attempt: sends the request, decodes the body and turns an error status into {@link ApifyApiError}.
299
- * Throws for anything that is not a success, and flags the failure as final through `stopRetrying()` when a
300
- * retry could not fix it.
318
+ * Throws for anything that is not a success, unless `config.throwOnErrorStatus` is `false` and no retry follows,
319
+ * and flags the failure as final through `stopRetrying()` when a retry could not fix it.
301
320
  */
302
321
  async #makeRequest(options) {
303
322
  const { config, url, headers, body, attempt, stopRetrying } = options;
304
323
  this.stats.requests++;
305
324
  const requestIsStream = isStream(config.data);
325
+ // The transport reports a failure of the blob as an error of its own, which may pass as transient.
326
+ let sourceFailure;
327
+ const attemptBody = isBlob(body)
328
+ ? runtime.openBlobBody(body, (error) => {
329
+ sourceFailure = { error };
330
+ })
331
+ : body;
306
332
  let response;
307
333
  try {
308
334
  response = await this.sendRequest({
309
335
  method: config.method,
310
336
  url,
311
337
  headers,
312
- body,
338
+ body: attemptBody,
313
339
  timeoutMillis: this.computeTimeoutMillis(attempt, config.timeoutSecs),
314
340
  stream: config.responseType === 'stream',
341
+ followRedirects: config.followRedirects ?? true,
315
342
  signal: config.signal,
316
343
  });
317
344
  }
318
345
  catch (err) {
319
346
  // Every HTTP library reports an abort with an error of its own, so the caller gets the reason instead.
320
347
  config.signal?.throwIfAborted();
348
+ if (sourceFailure) {
349
+ // Sending the body again cannot fix its source.
350
+ stopRetrying();
351
+ throw withCause(sourceFailure.error, err);
352
+ }
321
353
  this.#handleRequestError(err, config, stopRetrying);
322
354
  throw err;
323
355
  }
356
+ finally {
357
+ // A transport may stop reading the body early, for example on an error response sent before the whole
358
+ // body arrived, which would leave the blob's file open.
359
+ if (attemptBody !== body && isStream(attemptBody))
360
+ attemptBody.destroy();
361
+ }
362
+ const isError = response.status >= 300;
363
+ const isRetryable = isError && this.#isStatusCodeRetryable(response.status, config.retryStatusCodes);
364
+ // An error response goes back to the caller as it is once no retry follows, which a stream body rules out.
365
+ const shouldReturnError = isError &&
366
+ config.throwOnErrorStatus === false &&
367
+ (!isRetryable || requestIsStream || attempt > this.maxRetries);
324
368
  // A failed streaming request carries the API error body in the stream, so read it and let
325
369
  // `ApifyApiError` parse it like any other error body. A body that cannot be read leaves the error
326
370
  // without a message, which beats losing the status code to a stream error.
327
- if (response.status >= 300 && isStream(response.body)) {
371
+ if (isError && !shouldReturnError && isStream(response.body)) {
328
372
  response.body = await concatStreamToBuffer(response.body).catch(() => undefined);
329
373
  }
330
374
  let data;
@@ -332,12 +376,14 @@ export class HttpClient {
332
376
  data = this.#parseResponseBody(response, config);
333
377
  }
334
378
  catch (err) {
335
- // A body that does not parse is usually a connection dropped mid-response, which a retry fixes.
336
- if (requestIsStream) {
337
- this.#informAboutStreamNoRetry();
379
+ // The body of a success arrived in full, since a transfer cut short fails in `sendRequest()`, so a
380
+ // retry would get the same body back.
381
+ if (!isError) {
338
382
  stopRetrying();
383
+ throw err;
339
384
  }
340
- throw err;
385
+ // An error status is reported by its code, and `ApifyApiError` makes what it can of the raw body.
386
+ data = response.body;
341
387
  }
342
388
  const apifyResponse = {
343
389
  status: response.status,
@@ -345,13 +391,17 @@ export class HttpClient {
345
391
  data: data,
346
392
  config,
347
393
  };
348
- if (response.status < 300)
394
+ if (!isError)
349
395
  return apifyResponse;
350
- if (response.status === RATE_LIMIT_EXCEEDED_STATUS_CODE) {
396
+ // The statistics track the API's rate limits. Only API calls throw on an error status, so a call with
397
+ // `throwOnErrorStatus: false` is taken for a non-API one and its 429s stay out of the statistics.
398
+ if (response.status === RATE_LIMIT_EXCEEDED_STATUS_CODE && config.throwOnErrorStatus !== false) {
351
399
  this.stats.addRateLimitError(attempt);
352
400
  }
401
+ if (shouldReturnError)
402
+ return apifyResponse;
353
403
  const apiError = ApifyApiError.fromResponse(apifyResponse, attempt);
354
- if (!this.#isStatusCodeRetryable(response.status)) {
404
+ if (!isRetryable) {
355
405
  stopRetrying();
356
406
  }
357
407
  else if (requestIsStream) {
@@ -381,15 +431,16 @@ export class HttpClient {
381
431
  }
382
432
  }
383
433
  /**
384
- * Decides whether a transport error ends the call. Timeouts the request opted out of retrying and errors the
385
- * transport does not classify as retryable are final, and so is any error on a request with a stream body.
434
+ * Decides whether a transport error ends the call. Timeouts the request opted out of retrying, any error on a
435
+ * request that retries no transport errors, errors the transport does not classify as retryable and any error on
436
+ * a request with a stream body are final.
386
437
  */
387
438
  #handleRequestError(err, config, stopRetrying) {
388
439
  if (config.doNotRetryTimeouts && this.isTimeoutError(err)) {
389
440
  stopRetrying();
390
441
  return;
391
442
  }
392
- if (!this.isRetryableTransportError(err)) {
443
+ if (config.retryTransportErrors === false || !this.isRetryableTransportError(err)) {
393
444
  stopRetrying();
394
445
  return;
395
446
  }
@@ -399,10 +450,13 @@ export class HttpClient {
399
450
  }
400
451
  }
401
452
  /**
402
- * Rate limits (429) and server errors (500+) are retried. Anything else in 300-499 is a redirect the client
403
- * cannot follow or invalid input, which repeating the request cannot fix.
453
+ * Rate limits (429) and server errors (500+) are retried, unless the request lists its own `retryStatusCodes`.
454
+ * Anything else in 300-499 is a redirect the client cannot follow or invalid input, which repeating the request
455
+ * cannot fix.
404
456
  */
405
- #isStatusCodeRetryable(statusCode) {
457
+ #isStatusCodeRetryable(statusCode, retryStatusCodes) {
458
+ if (retryStatusCodes)
459
+ return retryStatusCodes.includes(statusCode);
406
460
  return statusCode === RATE_LIMIT_EXCEEDED_STATUS_CODE || statusCode >= 500;
407
461
  }
408
462
  #informAboutStreamNoRetry() {
@@ -427,7 +481,7 @@ function getHeader(headers, name) {
427
481
  * Merges two header records, header names compared case-insensitively. A header from `override` replaces a
428
482
  * same-named header in `base` whatever the casing of either, and keeps the casing it was passed with.
429
483
  */
430
- function mergeHeaders(base, override) {
484
+ export function mergeHeaders(base, override) {
431
485
  const merged = { ...base };
432
486
  for (const [key, value] of Object.entries(override ?? {})) {
433
487
  for (const existing of Object.keys(merged)) {
@@ -438,6 +492,18 @@ function mergeHeaders(base, override) {
438
492
  }
439
493
  return merged;
440
494
  }
495
+ /**
496
+ * Moves the `Authorization` header of `headers` to the header named `name`, or returns `headers` unchanged when
497
+ * `name` is `Authorization`.
498
+ */
499
+ function withAuthorizationHeader(headers, name = 'Authorization') {
500
+ const authorization = getHeader(headers, 'authorization');
501
+ if (name === 'Authorization' || authorization === undefined)
502
+ return headers;
503
+ const moved = { ...headers };
504
+ deleteHeader(moved, 'authorization');
505
+ return mergeHeaders(moved, { [name]: authorization });
506
+ }
441
507
  /**
442
508
  * Removes a header by name, compared case-insensitively.
443
509
  */
@@ -451,7 +517,7 @@ function deleteHeader(headers, name) {
451
517
  /**
452
518
  * Views a serialized body as the bytes to compress, or `undefined` when compressing it would not pay off: the
453
519
  * caller already labeled the body with a `Content-Encoding`, its content type carries its own compression, it is
454
- * a stream or smaller than {@link MIN_COMPRESS_BYTES}, or the runtime has no compression to offer.
520
+ * a stream or a blob, it is smaller than {@link MIN_COMPRESS_BYTES}, or the runtime has no compression to offer.
455
521
  */
456
522
  function compressibleBytes(body, headers) {
457
523
  if (body === undefined || !runtime.isNode)
@@ -463,6 +529,22 @@ function compressibleBytes(body, headers) {
463
529
  const bytes = toBytes(body);
464
530
  return bytes && bytes.byteLength >= MIN_COMPRESS_BYTES ? bytes : undefined;
465
531
  }
532
+ /**
533
+ * Sets `cause` on an error that has none, and returns the error. A `cause` that already wraps the error, as an axios
534
+ * error wraps the error of its request body, is left out, since linking it would make the chain circular.
535
+ */
536
+ function withCause(error, cause) {
537
+ if (!(error instanceof Error) || error.cause !== undefined)
538
+ return error;
539
+ const seen = new Set();
540
+ for (let link = cause; link instanceof Error && !seen.has(link); link = link.cause) {
541
+ if (link === error)
542
+ return error;
543
+ seen.add(link);
544
+ }
545
+ error.cause = cause;
546
+ return error;
547
+ }
466
548
  function headerValue(value) {
467
549
  return Array.isArray(value) ? value[0] : value;
468
550
  }
@@ -481,6 +563,11 @@ function serializeBody(data, headers, stringifyFunctions) {
481
563
  return undefined;
482
564
  if (isStream(data))
483
565
  return data;
566
+ if (isBlob(data)) {
567
+ if (getHeader(headers, 'content-type') === undefined && data.type)
568
+ headers['Content-Type'] = data.type;
569
+ return data;
570
+ }
484
571
  if (isBuffer(data)) {
485
572
  // The axios Node.js adapter refuses a body that is neither a `Buffer`, an `ArrayBuffer` nor a string.
486
573
  if (!runtime.isNode || Buffer.isBuffer(data))
@@ -4,3 +4,5 @@ export type { BrotliHttpCompressorOptions } from './brotli.js';
4
4
  export { GzipHttpCompressor } from './gzip.js';
5
5
  export type { GzipHttpCompressorOptions } from './gzip.js';
6
6
  export type { HttpCompressionAlgorithm } from './resolve.js';
7
+ export { ZstdHttpCompressor } from './zstd.js';
8
+ export type { ZstdHttpCompressorOptions } from './zstd.js';
@@ -1,2 +1,3 @@
1
1
  export { BrotliHttpCompressor } from './brotli.js';
2
2
  export { GzipHttpCompressor } from './gzip.js';
3
+ export { ZstdHttpCompressor } from './zstd.js';
@@ -3,10 +3,10 @@ import type { HttpCompressor } from './base.js';
3
3
  /**
4
4
  * Compression algorithms the `compression` option of {@link ApifyClient} accepts by name. Each name selects the
5
5
  * matching built-in compressor with its default quality: `'brotli'` a {@link BrotliHttpCompressor}, `'gzip'` a
6
- * {@link GzipHttpCompressor}. The Apify API also accepts `deflate` and `identity`, which a custom
7
- * {@link HttpCompressor} covers.
6
+ * {@link GzipHttpCompressor}, `'zstd'` a {@link ZstdHttpCompressor}. The Apify API also accepts `deflate` and
7
+ * `identity`, which a custom {@link HttpCompressor} covers.
8
8
  */
9
- export type HttpCompressionAlgorithm = 'brotli' | 'gzip';
9
+ export type HttpCompressionAlgorithm = 'brotli' | 'gzip' | 'zstd';
10
10
  /**
11
11
  * Schema of the `compression` option: an algorithm name or an {@link HttpCompressor}.
12
12
  * @internal
@@ -14,6 +14,7 @@ export type HttpCompressionAlgorithm = 'brotli' | 'gzip';
14
14
  export declare const compressionSchema: z.ZodUnion<readonly [z.ZodEnum<{
15
15
  brotli: "brotli";
16
16
  gzip: "gzip";
17
+ zstd: "zstd";
17
18
  }>, z.ZodCustom<HttpCompressor, HttpCompressor>]>;
18
19
  /**
19
20
  * Turns the `compression` option into a ready-to-use {@link HttpCompressor}: a name into the matching built-in
@@ -2,12 +2,13 @@ import { z } from 'zod';
2
2
  import { httpCompressorSchema } from './base.js';
3
3
  import { BrotliHttpCompressor } from './brotli.js';
4
4
  import { GzipHttpCompressor } from './gzip.js';
5
+ import { ZstdHttpCompressor } from './zstd.js';
5
6
  /**
6
7
  * Schema of the `compression` option: an algorithm name or an {@link HttpCompressor}.
7
8
  * @internal
8
9
  */
9
10
  export const compressionSchema = z.union([
10
- z.enum(['brotli', 'gzip']),
11
+ z.enum(['brotli', 'gzip', 'zstd']),
11
12
  httpCompressorSchema,
12
13
  ]);
13
14
  /**
@@ -23,5 +24,7 @@ export function resolveCompressor(compression) {
23
24
  return new GzipHttpCompressor();
24
25
  case 'brotli':
25
26
  return new BrotliHttpCompressor();
27
+ case 'zstd':
28
+ return new ZstdHttpCompressor();
26
29
  }
27
30
  }
@@ -0,0 +1,34 @@
1
+ import type { HttpCompressor } from './base.js';
2
+ /**
3
+ * Compresses request bodies using zstd.
4
+ *
5
+ * Built on the `node:zlib` module, so it works wherever the client runs on Node.js.
6
+ *
7
+ * @example
8
+ * ```javascript
9
+ * import { ApifyClient, ZstdHttpCompressor } from 'apify-client';
10
+ *
11
+ * const client = new ApifyClient({ token: 'my-token', compression: new ZstdHttpCompressor({ quality: 19 }) });
12
+ * ```
13
+ */
14
+ export declare class ZstdHttpCompressor implements HttpCompressor {
15
+ #private;
16
+ readonly contentEncoding = "zstd";
17
+ /**
18
+ * @param options - Compressor options.
19
+ * @throws {ArgumentValidationError} If `quality` is out of the valid range.
20
+ */
21
+ constructor(options?: ZstdHttpCompressorOptions);
22
+ compress(data: Buffer): Promise<Buffer>;
23
+ }
24
+ /**
25
+ * Options for {@link ZstdHttpCompressor}.
26
+ */
27
+ export interface ZstdHttpCompressorOptions {
28
+ /**
29
+ * Compression level, from `1` (the fastest) to `19` (the best compression). zstd's levels 20 to 22 are not
30
+ * accepted: their window exceeds the 8 MB that HTTP decoders are required to support.
31
+ * @default 3
32
+ */
33
+ quality?: number;
34
+ }