apify-client 3.0.0-beta.114 → 3.0.0-beta.116

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.
@@ -29,7 +29,8 @@ export interface AxiosHttpClientOptions extends HttpClientOptions {
29
29
  * next to the client.
30
30
  *
31
31
  * It inherits the request pipeline from {@link HttpClient} and adds the transport: in Node.js, keep-alive agents;
32
- * in the browser, the XHR adapter of axios, or its fetch adapter for a request that must not follow redirects.
32
+ * in the browser, the XHR adapter of axios, or its fetch adapter for a request that must not follow redirects or
33
+ * that asks for a streamed response.
33
34
  * Network errors are retried, timeouts included, and a stream body is sent without following redirects, since the
34
35
  * part of it already sent could not be replayed. The proxy environment variables are not read: pass a proxy agent
35
36
  * in {@link AxiosHttpClientOptions.httpAgent} and {@link AxiosHttpClientOptions.httpsAgent} instead.
@@ -58,8 +59,8 @@ export declare class AxiosHttpClient extends HttpClient {
58
59
  isTimeoutError(error: unknown): boolean;
59
60
  /**
60
61
  * A network failure is an axios error that carries the request it was sending: a connection that could not be
61
- * made, dropped mid-way or timed out. Errors raised before a request exists, such as an invalid URL, are not
62
- * retried.
62
+ * made, dropped mid-way or timed out, or the `TimeoutError` this client ends a late streamed response outside
63
+ * Node.js with. Errors raised before a request exists, such as an invalid URL, are not retried.
63
64
  */
64
65
  isRetryableTransportError(error: unknown): boolean;
65
66
  /**
@@ -71,7 +72,9 @@ export declare class AxiosHttpClient extends HttpClient {
71
72
  * Sends the request through axios and hands the raw response back. A stream body is sent without following
72
73
  * redirects, since the part of it already sent could not be replayed, and so is a request with
73
74
  * `followRedirects: false`. Outside Node.js, such a request goes through `fetch`, since the browser follows the
74
- * redirects of an XHR itself, and a redirect response fails the request: `fetch` hides it from the page.
75
+ * redirects of an XHR itself, and a redirect response fails the request: `fetch` hides it from the page. A
76
+ * request for a streamed response goes through `fetch` there too, since an XHR cannot stream one, and its
77
+ * timeout covers the wait for the headers only.
75
78
  */
76
79
  sendRequest(request: HttpRequest): Promise<HttpResponse>;
77
80
  }
@@ -1,7 +1,7 @@
1
1
  import axios, { AxiosError, AxiosHeaders } from 'axios';
2
2
  import { runtime } from '#runtime';
3
3
  import { ApifyClientError } from '../apify_client_error.js';
4
- import { isStream } from '../utils.js';
4
+ import { isAnyStream, isWebStream } from '../utils.js';
5
5
  import { HttpClient } from './base.js';
6
6
  /**
7
7
  * An HTTP client for {@link ApifyClient} built on [axios](https://axios-http.com), which was the transport of the
@@ -9,7 +9,8 @@ import { HttpClient } from './base.js';
9
9
  * next to the client.
10
10
  *
11
11
  * It inherits the request pipeline from {@link HttpClient} and adds the transport: in Node.js, keep-alive agents;
12
- * in the browser, the XHR adapter of axios, or its fetch adapter for a request that must not follow redirects.
12
+ * in the browser, the XHR adapter of axios, or its fetch adapter for a request that must not follow redirects or
13
+ * that asks for a streamed response.
13
14
  * Network errors are retried, timeouts included, and a stream body is sent without following redirects, since the
14
15
  * part of it already sent could not be replayed. The proxy environment variables are not read: pass a proxy agent
15
16
  * in {@link AxiosHttpClientOptions.httpAgent} and {@link AxiosHttpClientOptions.httpsAgent} instead.
@@ -71,10 +72,12 @@ export class AxiosHttpClient extends HttpClient {
71
72
  }
72
73
  /**
73
74
  * A network failure is an axios error that carries the request it was sending: a connection that could not be
74
- * made, dropped mid-way or timed out. Errors raised before a request exists, such as an invalid URL, are not
75
- * retried.
75
+ * made, dropped mid-way or timed out, or the `TimeoutError` this client ends a late streamed response outside
76
+ * Node.js with. Errors raised before a request exists, such as an invalid URL, are not retried.
76
77
  */
77
78
  isRetryableTransportError(error) {
79
+ if (super.isTimeoutError(error))
80
+ return true;
78
81
  if (!axios.isAxiosError(error))
79
82
  return false;
80
83
  return typeof error.request === 'object' && error.request !== null && error.config != null;
@@ -93,27 +96,44 @@ export class AxiosHttpClient extends HttpClient {
93
96
  * Sends the request through axios and hands the raw response back. A stream body is sent without following
94
97
  * redirects, since the part of it already sent could not be replayed, and so is a request with
95
98
  * `followRedirects: false`. Outside Node.js, such a request goes through `fetch`, since the browser follows the
96
- * redirects of an XHR itself, and a redirect response fails the request: `fetch` hides it from the page.
99
+ * redirects of an XHR itself, and a redirect response fails the request: `fetch` hides it from the page. A
100
+ * request for a streamed response goes through `fetch` there too, since an XHR cannot stream one, and its
101
+ * timeout covers the wait for the headers only.
97
102
  */
98
103
  async sendRequest(request) {
99
104
  await this.#ensureHttpAgents();
100
- const { method, url, headers, body, timeoutMillis, stream, followRedirects, signal } = request;
101
- const useFetch = !followRedirects && !runtime.isNode;
102
- const response = await this.axios.request({
105
+ const { method, url, headers, timeoutMillis, stream, followRedirects, signal } = request;
106
+ // The Node.js adapter of axios refuses a web stream, and an XHR cannot send one either.
107
+ const body = runtime.isNode && isWebStream(request.body) ? runtime.openStreamBody(request.body) : request.body;
108
+ const useFetch = (!followRedirects || stream || isWebStream(body)) && !runtime.isNode;
109
+ // The fetch adapter keeps the axios timeout running until a streamed response is read to its end.
110
+ const headersTimeout = useFetch && stream && timeoutMillis !== undefined ? new AbortController() : undefined;
111
+ const headersTimer = headersTimeout &&
112
+ setTimeout(() => {
113
+ headersTimeout.abort(new DOMException(`timeout of ${timeoutMillis}ms exceeded`, 'TimeoutError'));
114
+ }, timeoutMillis);
115
+ const signals = [signal, headersTimeout?.signal].filter((item) => item !== undefined);
116
+ const response = await this.axios
117
+ .request({
103
118
  method,
104
119
  url,
105
120
  // The fetch adapter adds a `User-Agent` of its own otherwise, which a browser lists in the CORS preflight.
106
121
  headers: useFetch ? { 'User-Agent': null, ...headers } : headers,
107
122
  data: body,
108
123
  // Axios reads 0 as no timeout.
109
- timeout: timeoutMillis ?? 0,
110
- signal,
124
+ timeout: headersTimeout ? 0 : (timeoutMillis ?? 0),
125
+ signal: signals.length > 1 ? AbortSignal.any(signals) : signals[0],
111
126
  responseType: stream ? 'stream' : 'arraybuffer',
112
127
  // See axios/axios#1045 for why axios must not buffer a stream body to follow redirects. The fetch
113
128
  // adapter turns this into `redirect: 'manual'`.
114
- ...(isStream(body) || !followRedirects ? { maxRedirects: 0 } : {}),
129
+ ...(isAnyStream(body) || !followRedirects ? { maxRedirects: 0 } : {}),
115
130
  ...(useFetch ? { adapter: 'fetch' } : {}),
116
- });
131
+ })
132
+ .catch((error) => {
133
+ // Axios reports any abort as a cancellation.
134
+ throw headersTimeout?.signal.aborted ? headersTimeout.signal.reason : error;
135
+ })
136
+ .finally(() => clearTimeout(headersTimer));
117
137
  // `redirect: 'manual'` resolves to an opaque response with status 0 instead of the redirect.
118
138
  if (useFetch && response.status === 0) {
119
139
  throw new ApifyClientError(`${method} ${url} responded with a redirect, which the client does not follow.`);
@@ -121,7 +141,8 @@ export class AxiosHttpClient extends HttpClient {
121
141
  return {
122
142
  status: response.status,
123
143
  headers: AxiosHeaders.from(response.headers).toJSON(),
124
- body: response.data,
144
+ // `fetch` has no body stream for a response without a body, such as a 204.
145
+ body: (response.data ?? (stream ? new Blob([]).stream() : undefined)),
125
146
  };
126
147
  }
127
148
  async #ensureHttpAgents() {
@@ -29,20 +29,24 @@ export type HttpResponseHeaders = Record<string, string | string[] | undefined>;
29
29
  * A request body as the transport receives it: already serialized, and compressed when that paid off. A `Readable`
30
30
  * is passed through untouched and is only available in Node.js. A `Blob` body reaches a Node.js transport as a
31
31
  * fresh `Readable` over its bytes for every attempt, and a transport in any other runtime as the `Blob` itself.
32
+ * A web `ReadableStream` body reaches a Node.js transport as a `Readable` too, and a transport in any other
33
+ * runtime as the stream itself.
32
34
  */
33
- export type HttpRequestBody = string | Buffer | ArrayBuffer | ArrayBufferView | Readable | Blob;
35
+ export type HttpRequestBody = string | Buffer | ArrayBuffer | ArrayBufferView | Readable | ReadableStream<Uint8Array> | Blob;
34
36
  /**
35
- * A response body as the transport hands it back: the raw bytes, a `Readable` when the request asked for a streamed
36
- * response, or `undefined` when the response carried no body.
37
+ * A response body as the transport hands it back: the raw bytes, a web `ReadableStream` or a `Readable` when the
38
+ * request asked for a streamed response, or `undefined` when the response carried no body. The pipeline hands the bytes
39
+ * on as a `Uint8Array` (a `Buffer` in Node.js) and the stream as a web `ReadableStream`, whichever of the
40
+ * types they arrive in.
37
41
  */
38
- export type HttpResponseBody = Buffer | ArrayBuffer | Readable | undefined;
42
+ export type HttpResponseBody = Uint8Array | ArrayBuffer | Readable | ReadableStream<Uint8Array> | undefined;
39
43
  /**
40
44
  * How {@link HttpClient.call} hands back the response body.
41
45
  *
42
46
  * - `parsed` (the default) decodes it by content type: JSON becomes an object, text and XML become a string, anything
43
- * else stays a `Buffer` (an `ArrayBuffer` in the browser).
44
- * - `buffer` skips the decoding and hands back the raw bytes.
45
- * - `stream` hands back a `Readable` with the body unread. Node.js only.
47
+ * else stays a `Uint8Array`.
48
+ * - `buffer` skips the decoding and hands back the raw bytes as a `Uint8Array`.
49
+ * - `stream` hands back the body unread, as a web `ReadableStream` of `Uint8Array` chunks.
46
50
  */
47
51
  export type ApifyResponseType = 'parsed' | 'buffer' | 'stream';
48
52
  /**
@@ -63,10 +67,11 @@ export interface ApifyRequestConfig {
63
67
  /**
64
68
  * Request body. A plain object or array is serialized to JSON and sent as `application/json`, or form-encoded
65
69
  * when a `Content-Type: application/x-www-form-urlencoded` header asks for it. A string, binary value
66
- * (`Buffer`, `ArrayBuffer`, typed array) or `Readable` is sent as it is, and `URLSearchParams` is sent
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.
70
+ * (`Buffer`, `ArrayBuffer`, typed array) or stream (`Readable`, web `ReadableStream`) is sent as it is, and
71
+ * `URLSearchParams` is sent form-encoded. A `Blob` or `File`, such as one from `fs.openAsBlob()`, is streamed
72
+ * without being held in memory, under its own `type` when no `Content-Type` header is set. A `FormData` is
73
+ * rejected with a `TypeError`, since serializing one would send an empty body, and so is a web `ReadableStream`
74
+ * in a browser that cannot send one.
70
75
  */
71
76
  data?: unknown;
72
77
  /**
@@ -157,7 +162,7 @@ export interface HttpRequest {
157
162
  * `timeoutSecs: 'noTimeout'` asks for.
158
163
  */
159
164
  timeoutMillis?: number;
160
- /** Whether to hand the body back unread as a `Readable`, so the caller can stream it. */
165
+ /** Whether to hand the body back unread as a stream. The caller always gets a web `ReadableStream`. */
161
166
  stream: boolean;
162
167
  /**
163
168
  * Whether to follow redirects. With `false`, return a redirect response as it is: the request carries a token
@@ -178,7 +183,7 @@ export interface HttpResponse {
178
183
  status: number;
179
184
  /** Response headers keyed by lowercase header name. */
180
185
  headers: HttpResponseHeaders;
181
- /** The body as raw bytes, or unread as a `Readable` when the request asked for a stream. */
186
+ /** The body as raw bytes, or unread as a stream: a web `ReadableStream`, or a `Readable` the pipeline converts. */
182
187
  body: HttpResponseBody;
183
188
  }
184
189
  /**
@@ -257,7 +262,7 @@ export interface HttpClientOptions {
257
262
  * return {
258
263
  * status: response.status,
259
264
  * headers: Object.fromEntries(response.headers),
260
- * body: Buffer.from(await response.arrayBuffer()),
265
+ * body: await response.arrayBuffer(),
261
266
  * };
262
267
  * }
263
268
  *
@@ -345,11 +350,11 @@ export declare abstract class HttpClient {
345
350
  * Network errors the transport classifies as retryable, rate limits (HTTP 429) and server errors (HTTP 5xx)
346
351
  * are retried up to {@link maxRetries} times, and `config.retryStatusCodes` picks other statuses to retry. Any
347
352
  * other error status is thrown as {@link ApifyApiError} right away, or returned when `config.throwOnErrorStatus`
348
- * is `false`. A request whose body is a `Readable` is never retried, since part of the stream has already been
349
- * consumed by the time the failure shows. A `Blob` body is read again for every attempt, so it is retried like
350
- * any other, unless reading the blob itself fails: that error is thrown right away, with the transport error
351
- * as its `cause` when that error does not already wrap it. Aborting `config.signal` ends the attempt in flight,
352
- * skips the remaining retries and rejects the call with the signal's `reason`.
353
+ * is `false`. A request whose body is a `Readable` or a web `ReadableStream` is never retried, since part of the
354
+ * stream has already been consumed by the time the failure shows. A `Blob` body is read again for every attempt,
355
+ * so it is retried like any other, unless reading the blob itself fails: that error is thrown right away, with
356
+ * the transport error as its `cause` when that error does not already wrap it. Aborting `config.signal` ends the
357
+ * attempt in flight, skips the remaining retries and rejects the call with the signal's `reason`.
353
358
  *
354
359
  * @template T - Type of the parsed response body.
355
360
  * @param config - The request to make.
@@ -1,7 +1,6 @@
1
1
  import { z } from 'zod';
2
2
  import { APIFY_ENV_VARS } from '@apify/consts';
3
3
  import log from '@apify/log';
4
- import { concatStreamToBuffer } from '@apify/utilities';
5
4
  import { ApifyApiError } from '../apify_api_error.js';
6
5
  import { maybeParseBody } from '../body_parser.js';
7
6
  import { resolveCompressor } from '../http_compressors/resolve.js';
@@ -9,7 +8,7 @@ import { InvalidResponseBodyError } from '../invalid_response_body_error.js';
9
8
  import { Statistics } from '../statistics.js';
10
9
  import { DEFAULT_TIMEOUT_LONG_SECS, DEFAULT_TIMEOUT_MAX_SECS, DEFAULT_TIMEOUT_MEDIUM_SECS, DEFAULT_TIMEOUT_SHORT_SECS, } from '../timeouts.js';
11
10
  import { runtime } from '#runtime';
12
- import { asArray, getEnv, isBlob, isBuffer, isCompressibleContentType, isStream, MIN_COMPRESS_BYTES, parseArgument, sleep, toBytes, version, } from '../utils.js';
11
+ import { asArray, getEnv, isAnyStream, isBlob, isBuffer, isCompressibleContentType, isStream, isWebStream, MIN_COMPRESS_BYTES, parseArgument, sleep, toBytes, version, } from '../utils.js';
13
12
  export const DEFAULT_MAX_RETRIES = 8;
14
13
  export const DEFAULT_MIN_DELAY_BETWEEN_RETRIES_MILLIS = 500;
15
14
  const RATE_LIMIT_EXCEEDED_STATUS_CODE = 429;
@@ -29,7 +28,7 @@ export const httpClientOptionsShape = {
29
28
  };
30
29
  const httpClientOptionsSchema = z.looseObject(httpClientOptionsShape).partial();
31
30
  /** Objects whose payload does not live in their own enumerable keys, so JSON serialization loses it. */
32
- const UNSERIALIZABLE_OBJECT_TAGS = new Set(['FormData', 'ReadableStream']);
31
+ const UNSERIALIZABLE_OBJECT_TAGS = new Set(['FormData']);
33
32
  /**
34
33
  * Base class for the HTTP clients used by {@link ApifyClient}.
35
34
  *
@@ -68,7 +67,7 @@ const UNSERIALIZABLE_OBJECT_TAGS = new Set(['FormData', 'ReadableStream']);
68
67
  * return {
69
68
  * status: response.status,
70
69
  * headers: Object.fromEntries(response.headers),
71
- * body: Buffer.from(await response.arrayBuffer()),
70
+ * body: await response.arrayBuffer(),
72
71
  * };
73
72
  * }
74
73
  *
@@ -196,11 +195,11 @@ export class HttpClient {
196
195
  * Network errors the transport classifies as retryable, rate limits (HTTP 429) and server errors (HTTP 5xx)
197
196
  * are retried up to {@link maxRetries} times, and `config.retryStatusCodes` picks other statuses to retry. Any
198
197
  * other error status is thrown as {@link ApifyApiError} right away, or returned when `config.throwOnErrorStatus`
199
- * is `false`. A request whose body is a `Readable` is never retried, since part of the stream has already been
200
- * consumed by the time the failure shows. A `Blob` body is read again for every attempt, so it is retried like
201
- * any other, unless reading the blob itself fails: that error is thrown right away, with the transport error
202
- * as its `cause` when that error does not already wrap it. Aborting `config.signal` ends the attempt in flight,
203
- * skips the remaining retries and rejects the call with the signal's `reason`.
198
+ * is `false`. A request whose body is a `Readable` or a web `ReadableStream` is never retried, since part of the
199
+ * stream has already been consumed by the time the failure shows. A `Blob` body is read again for every attempt,
200
+ * so it is retried like any other, unless reading the blob itself fails: that error is thrown right away, with
201
+ * the transport error as its `cause` when that error does not already wrap it. Aborting `config.signal` ends the
202
+ * attempt in flight, skips the remaining retries and rejects the call with the signal's `reason`.
204
203
  *
205
204
  * @template T - Type of the parsed response body.
206
205
  * @param config - The request to make.
@@ -213,7 +212,15 @@ export class HttpClient {
213
212
  this.stats.calls++;
214
213
  const { headers, body } = await this.prepareRequest(config);
215
214
  const url = this.buildUrl(config.url, config.params);
216
- return this.#retryWithExpBackoff(async (stopRetrying, attempt) => this.#makeRequest({ config, url, headers, body, attempt, stopRetrying }), config.signal);
215
+ try {
216
+ return await this.#retryWithExpBackoff(async (stopRetrying, attempt) => this.#makeRequest({ config, url, headers, body, attempt, stopRetrying }), config.signal);
217
+ }
218
+ catch (error) {
219
+ // A transport may leave the `Readable` opened over a web stream unread, and the stream locked for good.
220
+ if (isWebStream(config.data) && isStream(body))
221
+ body.destroy();
222
+ throw error;
223
+ }
217
224
  }
218
225
  /**
219
226
  * Prepares the headers and the body of a request.
@@ -327,7 +334,7 @@ export class HttpClient {
327
334
  async #makeRequest(options) {
328
335
  const { config, url, headers, body, attempt, stopRetrying } = options;
329
336
  this.stats.requests++;
330
- const requestIsStream = isStream(config.data);
337
+ const requestIsStream = isAnyStream(config.data);
331
338
  // The transport reports a failure of the blob as an error of its own, which may pass as transient.
332
339
  let sourceFailure;
333
340
  const attemptBody = isBlob(body)
@@ -371,12 +378,17 @@ export class HttpClient {
371
378
  const shouldReturnError = isError &&
372
379
  config.throwOnErrorStatus === false &&
373
380
  (!isRetryable || requestIsStream || attempt > this.maxRetries);
381
+ // Transports return whichever stream and binary type their HTTP library has, and callers get the web ones.
382
+ if (isStream(response.body))
383
+ response.body = runtime.streamToWeb(response.body);
374
384
  // A failed streaming request carries the API error body in the stream, so read it and let
375
385
  // `ApifyApiError` parse it like any other error body. A body that cannot be read leaves the error
376
386
  // without a message, which beats losing the status code to a stream error.
377
- if (isError && !shouldReturnError && isStream(response.body)) {
378
- response.body = await concatStreamToBuffer(response.body).catch(() => undefined);
387
+ if (isError && !shouldReturnError && isWebStream(response.body)) {
388
+ response.body = await new Response(response.body).arrayBuffer().catch(() => undefined);
379
389
  }
390
+ if (isBuffer(response.body))
391
+ response.body = toResponseBytes(response.body);
380
392
  let data;
381
393
  try {
382
394
  data = this.#parseResponseBody(response, config);
@@ -425,7 +437,7 @@ export class HttpClient {
425
437
  const { body } = response;
426
438
  if (config.responseType === 'stream' || config.responseType === 'buffer')
427
439
  return body;
428
- if (body === undefined || isStream(body))
440
+ if (body === undefined || !isBuffer(body))
429
441
  return body;
430
442
  if (body.byteLength === 0)
431
443
  return undefined;
@@ -450,7 +462,7 @@ export class HttpClient {
450
462
  stopRetrying();
451
463
  return;
452
464
  }
453
- if (isStream(config.data)) {
465
+ if (isAnyStream(config.data)) {
454
466
  this.#informAboutStreamNoRetry();
455
467
  stopRetrying();
456
468
  }
@@ -554,6 +566,13 @@ function withCause(error, cause) {
554
566
  error.cause = cause;
555
567
  return error;
556
568
  }
569
+ /** Views response bytes as a `Uint8Array` without copying them: a `Buffer` in Node.js, which v2 callers rely on. */
570
+ function toResponseBytes(body) {
571
+ if (runtime.isNode && Buffer.isBuffer(body))
572
+ return body;
573
+ const bytes = toBytes(body);
574
+ return runtime.isNode ? Buffer.from(bytes.buffer, bytes.byteOffset, bytes.byteLength) : bytes;
575
+ }
557
576
  function headerValue(value) {
558
577
  return Array.isArray(value) ? value[0] : value;
559
578
  }
@@ -572,6 +591,8 @@ function serializeBody(data, headers, stringifyFunctions) {
572
591
  return undefined;
573
592
  if (isStream(data))
574
593
  return data;
594
+ if (isWebStream(data))
595
+ return runtime.openStreamBody(data);
575
596
  if (isBlob(data)) {
576
597
  if (getHeader(headers, 'content-type') === undefined && data.type)
577
598
  headers['Content-Type'] = data.type;
@@ -11,7 +11,8 @@ export interface FetchHttpClientOptions extends HttpClientOptions {
11
11
  /**
12
12
  * The `fetch` implementation the requests go through. Pass a wrapper around the global `fetch` to adjust every
13
13
  * request, or the `fetch` of another library, such as `undici` with a dispatcher of your own, to control the
14
- * connections. A stream body reaches it as an async iterable of byte chunks, or as the stream itself in Bun.
14
+ * connections. A stream body reaches it as an async iterable of byte chunks, or as the stream itself in Bun. In a
15
+ * browser or an edge runtime, a web `ReadableStream` body reaches it as a web stream.
15
16
  * @default globalThis.fetch
16
17
  */
17
18
  fetch?: FetchFunction;
@@ -1,6 +1,6 @@
1
1
  import { runtime } from '#runtime';
2
2
  import { ApifyClientError } from '../apify_client_error.js';
3
- import { isStream } from '../utils.js';
3
+ import { isAnyStream, isStream, isWebStream } from '../utils.js';
4
4
  import { HttpClient } from './base.js';
5
5
  /** Error codes of the timeouts that Node.js reports as the `cause` of a failed `fetch`. */
6
6
  const TIMEOUT_ERROR_CODES = new Set([
@@ -81,21 +81,22 @@ export class FetchHttpClient extends HttpClient {
81
81
  timer = setTimeout(() => timeout.abort(new DOMException(`timeout of ${timeoutMillis}ms exceeded`, 'TimeoutError')), timeoutMillis);
82
82
  };
83
83
  restartTimeout();
84
+ let sentBody;
84
85
  try {
85
86
  // Browsers and Deno reject an invalid URL with the same bare `TypeError` as a network failure.
86
87
  const baseUrl = globalThis.location?.href;
87
88
  if (!runtime.fetchFailsWithCause && !URL.canParse(url, baseUrl)) {
88
89
  throw Object.assign(new TypeError(`Invalid URL: ${url}`), { code: 'ERR_INVALID_URL' });
89
90
  }
91
+ sentBody = trackProgress(body, restartTimeout);
90
92
  const response = await (this.#fetch ?? globalThis.fetch)(url, {
91
93
  method,
92
94
  headers,
93
- // Node.js reads an async iterable, which the DOM types do not know about.
94
- body: (isStream(body) && !isBun ? withProgress(body, restartTimeout) : body),
95
- redirect: followRedirects && !isStream(body) ? 'follow' : 'manual',
95
+ body: sentBody,
96
+ redirect: followRedirects && !isAnyStream(body) ? 'follow' : 'manual',
96
97
  signal: signal ? AbortSignal.any([signal, timeout.signal]) : timeout.signal,
97
98
  // Required for a stream body, and ignored for any other.
98
- ...(isStream(body) ? { duplex: 'half' } : {}),
99
+ ...(isAnyStream(body) ? { duplex: 'half' } : {}),
99
100
  });
100
101
  // `redirect: 'manual'` resolves to an opaque response with status 0 in a browser.
101
102
  if (response.type === 'opaqueredirect') {
@@ -105,10 +106,13 @@ export class FetchHttpClient extends HttpClient {
105
106
  status: response.status,
106
107
  headers: toResponseHeaders(response.headers),
107
108
  // The timeout covers a streamed response only until its headers, and the caller's signal throughout.
108
- body: stream ? runtime.readableFromWeb(response.body) : await readBody(response, restartTimeout),
109
+ body: stream ? (response.body ?? new Blob([]).stream()) : await readBody(response, restartTimeout),
109
110
  };
110
111
  }
111
112
  catch (error) {
113
+ // A `fetch` that refused the request never took the body over, which keeps the caller's stream locked.
114
+ if (isWebStream(sentBody) && !sentBody.locked)
115
+ sentBody.cancel(error).catch(() => { });
112
116
  if (!this.#fetch && this.isRetryableTransportError(error))
113
117
  this.#warnAboutUnusedProxy();
114
118
  throw error;
@@ -129,6 +133,15 @@ export class FetchHttpClient extends HttpClient {
129
133
  const isBun = 'Bun' in globalThis;
130
134
  /** A larger chunk of a stream body is passed on in pieces, since a `Blob` held in memory arrives as a single one. */
131
135
  const MAX_BODY_CHUNK_BYTES = 64 * 1024;
136
+ /** Makes a stream body report every chunk that `fetch` reads from it, and leaves any other body as it is. */
137
+ function trackProgress(body, onChunk) {
138
+ if (isWebStream(body))
139
+ return withWebProgress(body, onChunk);
140
+ // Node.js reads an async iterable, which the DOM types do not know about.
141
+ if (isStream(body) && !isBun)
142
+ return withProgress(body, onChunk);
143
+ return body;
144
+ }
132
145
  /** Passes a stream body on piece by piece, so that a large upload counts as alive for as long as it is being read. */
133
146
  async function* withProgress(body, onChunk) {
134
147
  for await (const chunk of body) {
@@ -145,6 +158,29 @@ async function* withProgress(body, onChunk) {
145
158
  }
146
159
  }
147
160
  }
161
+ /** Does for a web stream body what {@link withProgress} does for an async iterable. */
162
+ function withWebProgress(body, onChunk) {
163
+ const reader = body.getReader();
164
+ let rest;
165
+ return new ReadableStream({
166
+ async pull(controller) {
167
+ if (!rest?.byteLength) {
168
+ const { done, value } = await reader.read();
169
+ if (done)
170
+ return controller.close();
171
+ rest = value;
172
+ }
173
+ onChunk();
174
+ controller.enqueue(rest.subarray(0, MAX_BODY_CHUNK_BYTES));
175
+ rest = rest.subarray(MAX_BODY_CHUNK_BYTES);
176
+ },
177
+ async cancel(reason) {
178
+ await reader.cancel(reason);
179
+ },
180
+ },
181
+ // Reads a piece only once `fetch` asks for it.
182
+ { highWaterMark: 0 });
183
+ }
148
184
  /**
149
185
  * Reads the response body chunk by chunk, so that a large download counts as alive for as long as bytes arrive.
150
186
  */
@@ -163,7 +199,7 @@ async function readBody(response, onChunk) {
163
199
  bytes.set(chunk, offset);
164
200
  offset += chunk.byteLength;
165
201
  }
166
- return runtime.isNode ? Buffer.from(bytes.buffer) : bytes.buffer;
202
+ return bytes;
167
203
  }
168
204
  function toResponseHeaders(headers) {
169
205
  const result = Object.fromEntries(headers);
@@ -413,7 +413,8 @@ export interface ActorStartOptions extends TimeoutOptions {
413
413
  * A run that requests more memory than the whole memory limit of the account is rejected with
414
414
  * `actor-memory-limit-exceeded` as well and never starts, so `true` retries it forever.
415
415
  *
416
- * A `Readable` input can't be sent twice, so its start is never retried and the first rejection is thrown.
416
+ * A stream input (`Readable` or web `ReadableStream`) can't be sent twice, so its start is never retried and the
417
+ * first rejection is thrown.
417
418
  */
418
419
  waitForResources?: boolean | number;
419
420
  }
@@ -4,7 +4,7 @@ import { Log } from '@apify/log';
4
4
  import { ResourceClient } from '../base/resource_client.js';
5
5
  import * as schemas from '../schemas.js';
6
6
  import { timeoutOptionsSchema, timeoutOptionsShape } from '../timeouts.js';
7
- import { anyObjectSchema, isStream, parseArgument, parseResponse, stringifyWebhooksToBase64 } from '../utils.js';
7
+ import { anyObjectSchema, isAnyStream, parseArgument, parseResponse, stringifyWebhooksToBase64 } from '../utils.js';
8
8
  import { startWaitingForResources } from '../wait_for_resources.js';
9
9
  import { ActorServerClient } from './actor_server.js';
10
10
  import { ActorVersionClient } from './actor_version.js';
@@ -196,8 +196,8 @@ export class ActorClient extends ResourceClient {
196
196
  'content-type': parsed.contentType,
197
197
  };
198
198
  }
199
- // A `Readable` input is consumed by the first attempt, so a retry would start the run with an empty input.
200
- const response = await startWaitingForResources(async () => this.httpClient.call(request), isStream(input) ? false : waitForResources, this.httpClient.logger, signal);
199
+ // A stream input is consumed by the first attempt, so a retry would start the run with an empty input.
200
+ const response = await startWaitingForResources(async () => this.httpClient.call(request), isAnyStream(input) ? false : waitForResources, this.httpClient.logger, signal);
201
201
  return parseResponse(response, schemas.Run());
202
202
  }
203
203
  /**
@@ -1,4 +1,3 @@
1
- import type { Readable } from 'node:stream';
2
1
  import type { ApiClientSubResourceOptions } from '../base/api_client.js';
3
2
  import { ResourceClient } from '../base/resource_client.js';
4
3
  import type { ApifyResponse, ApifyResponseType, HttpMethod } from '../http_clients/index.js';
@@ -85,15 +84,15 @@ export declare class ActorServerClient extends ResourceClient {
85
84
  * @param options.params - Query parameters of the request, converted the same way as for API calls.
86
85
  * @param options.headers - Additional headers of the request.
87
86
  * @param options.data - Request body, serialized the same way as for API calls: a plain object or array is sent
88
- * as JSON, and a string or binary value as it is.
87
+ * as JSON, and a string, binary value or stream (`Readable`, web `ReadableStream`) as it is.
89
88
  * @param options.parentRequestId - The `X-Actor-Request-ID` header of the request your Server Actor is handling,
90
89
  * sent on as the same header so the called Actor charges at that request's pricing tier.
91
90
  * @param options.compression - Compression algorithm for the request body, as a name or an {@link HttpCompressor}.
92
91
  * The body is compressed under the same conditions as for API calls. Set it only if the Actor's server decodes
93
92
  * the resulting `Content-Encoding`.
94
93
  * @param options.responseType - How to return the response body: `'parsed'` by its content type, `'buffer'` as
95
- * raw bytes, or `'stream'` as a Readable stream with the body unread. A stream holds its connection open until
96
- * you consume it to the end or destroy it. Node.js only. Default is `'parsed'`.
94
+ * raw bytes in a Uint8Array, or `'stream'` as a web ReadableStream with the body unread. A stream holds its
95
+ * connection open until you consume it to the end or cancel it. Default is `'parsed'`.
97
96
  * @param options.timeoutSecs - Timeout for the HTTP request. Default is `'long'`. With `'stream'`, it bounds the
98
97
  * wait for the server to start responding.
99
98
  * @returns The response of the Actor's server, with the body in the form `responseType` asks for. An error
@@ -109,10 +108,10 @@ export declare class ActorServerClient extends ResourceClient {
109
108
  }): Promise<ApifyResponse<T>>;
110
109
  request(path: string, options: ActorServerRequestOptions & {
111
110
  responseType: 'buffer';
112
- }): Promise<ApifyResponse<Buffer>>;
111
+ }): Promise<ApifyResponse<Uint8Array>>;
113
112
  request(path: string, options: ActorServerRequestOptions & {
114
113
  responseType: 'stream';
115
- }): Promise<ApifyResponse<Readable>>;
114
+ }): Promise<ApifyResponse<ReadableStream<Uint8Array>>>;
116
115
  request(path?: string, options?: ActorServerRequestOptions): Promise<ApifyResponse>;
117
116
  }
118
117
  /**
@@ -142,8 +141,8 @@ export interface ActorServerRequestOptions extends TimeoutOptions {
142
141
  */
143
142
  compression?: HttpCompressionAlgorithm | HttpCompressor;
144
143
  /**
145
- * How to return the response body: `'parsed'` by its content type, `'buffer'` as raw bytes, or `'stream'` as a
146
- * Readable stream with the body unread. Node.js only.
144
+ * How to return the response body: `'parsed'` by its content type, `'buffer'` as raw bytes in a Uint8Array, or
145
+ * `'stream'` as a web ReadableStream with the body unread.
147
146
  * @default 'parsed'
148
147
  */
149
148
  responseType?: ApifyResponseType;
@@ -5,7 +5,6 @@ import { mergeHeaders } from '../http_clients/base.js';
5
5
  import { compressionSchema, resolveCompressor } from '../http_compressors/resolve.js';
6
6
  import * as schemas from '../schemas.js';
7
7
  import { timeoutOptionsSchema, timeoutOptionsShape } from '../timeouts.js';
8
- import { runtime } from '#runtime';
9
8
  import { parseArgument, parseResponse } from '../utils.js';
10
9
  import { BuildClient } from './build.js';
11
10
  import { BuildCollectionClient } from './build_collection.js';
@@ -154,9 +153,6 @@ export class ActorServerClient extends ResourceClient {
154
153
  async request(path = '/', options = {}) {
155
154
  parseArgument(path, z.string());
156
155
  const { method = 'GET', params, headers, data, parentRequestId, compression, responseType, timeoutSecs = 'long', signal, } = parseArgument(options, requestOptionsSchema, 'ActorServerRequestOptions');
157
- if (responseType === 'stream' && !runtime.isNode) {
158
- throw new Error("The 'stream' response type can only be used in Node.js environment.");
159
- }
160
156
  const serverUrl = await this.getUrl({ signal });
161
157
  const serverPath = path.split('#')[0].replace(/^\/+/, '');
162
158
  return this.httpClient.call({