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.
@@ -1,4 +1,3 @@
1
- import type { Readable } from 'node:stream';
2
1
  import type { STORAGE_GENERAL_ACCESS } from '@apify/consts';
3
2
  import type { ApiClientSubResourceOptions } from '../base/api_client.js';
4
3
  import { ResourceClient } from '../base/resource_client.js';
@@ -132,12 +131,12 @@ export declare class DatasetClient<Data extends Record<string | number, any> = R
132
131
  *
133
132
  * Unlike {@link listItems} which returns a {@link PaginatedList} with an array of individual
134
133
  * dataset items, this method returns the items serialized to the provided format
135
- * (JSON, CSV, Excel, etc.) as a Buffer. Useful for exporting data for further processing.
134
+ * (JSON, CSV, Excel, etc.) as a Uint8Array. Useful for exporting data for further processing.
136
135
  *
137
- * In Node.js you can use the `stream` option to get a Readable stream, so a large export is processed in chunks
138
- * without holding all of it in memory. The stream holds its connection open until you consume it to the end or
139
- * destroy it. Iterating it with `for await` or passing it to `pipeline()` from `node:stream/promises` does either
140
- * one for you.
136
+ * You can use the `stream` option to get a web ReadableStream, so a large export is processed in chunks without
137
+ * holding all of it in memory. The stream holds its connection open until you consume it to the end or cancel
138
+ * it. Iterating it with `for await` or piping it with `pipeTo()` does either one for you. In Node.js,
139
+ * `Readable.fromWeb()` turns it into a Readable.
141
140
  *
142
141
  * @param format - Output format: `'json'`, `'jsonl'`, `'csv'`, `'xlsx'`, `'xml'`, `'rss'`, or `'html'`
143
142
  * @param options - Download and formatting options (extends all options from {@link listItems})
@@ -149,12 +148,12 @@ export declare class DatasetClient<Data extends Record<string | number, any> = R
149
148
  * @param options.xmlRow - Name of the XML element for each item. Default is `'item'`.
150
149
  * @param options.fields - Array of field names to include in the export.
151
150
  * @param options.omit - Array of field names to exclude from the export.
152
- * @param options.stream - If `true`, the items are returned as a Readable stream. Node.js only.
151
+ * @param options.stream - If `true`, the items are returned as a web ReadableStream.
153
152
  * @param options.timeoutSecs - Timeout for the API request. Default is `'long'`. With `stream`, it bounds the
154
- * wait for the API to start responding; once the stream is returned, it only limits inactivity: the stream errors
155
- * if no data arrives for that long. To stop the download early or cap its total duration, destroy the stream or
156
- * abort `signal`.
157
- * @returns Buffer containing the serialized data in the specified format, or a Readable stream of it with `stream`
153
+ * wait for the API to start responding. To stop the download early or cap its total duration, cancel the stream
154
+ * or abort `signal`.
155
+ * @returns Uint8Array containing the serialized data in the specified format, or a web ReadableStream of it with
156
+ * `stream`
158
157
  * @see https://docs.apify.com/api/v2/dataset-items-get
159
158
  *
160
159
  * @example
@@ -185,11 +184,11 @@ export declare class DatasetClient<Data extends Record<string | number, any> = R
185
184
  */
186
185
  downloadItems(format: `${DownloadItemsFormat}`, options?: DatasetClientDownloadItemsOptions & {
187
186
  stream?: false;
188
- }): Promise<Buffer>;
187
+ }): Promise<Uint8Array>;
189
188
  downloadItems(format: `${DownloadItemsFormat}`, options: DatasetClientDownloadItemsOptions & {
190
189
  stream: true;
191
- }): Promise<Readable>;
192
- downloadItems(format: `${DownloadItemsFormat}`, options?: DatasetClientDownloadItemsOptions): Promise<Buffer | Readable>;
190
+ }): Promise<ReadableStream<Uint8Array>>;
191
+ downloadItems(format: `${DownloadItemsFormat}`, options?: DatasetClientDownloadItemsOptions): Promise<Uint8Array | ReadableStream<Uint8Array>>;
193
192
  /**
194
193
  * Stores one or more items into the dataset.
195
194
  *
@@ -343,7 +342,7 @@ export interface DatasetClientDownloadItemsOptions extends Omit<DatasetClientLis
343
342
  xmlRoot?: string;
344
343
  xmlRow?: string;
345
344
  /**
346
- * If `true`, the items are returned as a Readable stream. Node.js only.
345
+ * If `true`, the items are returned as a web ReadableStream.
347
346
  * @default false
348
347
  */
349
348
  stream?: boolean;
@@ -3,7 +3,6 @@ import { createStorageContentSignatureAsync } from '@apify/utilities';
3
3
  import { ResourceClient } from '../base/resource_client.js';
4
4
  import * as schemas from '../schemas.js';
5
5
  import { timeoutOptionsSchema, timeoutOptionsShape } from '../timeouts.js';
6
- import { runtime } from '#runtime';
7
6
  import { anyObjectSchema, applyQueryParamsToUrl, cast, isNonArrayObject, paginationOptionsShape, parseArgument, parseResponse, } from '../utils.js';
8
7
  /**
9
8
  * Supported formats for downloading dataset items.
@@ -218,9 +217,6 @@ export class DatasetClient extends ResourceClient {
218
217
  async downloadItems(format, options = {}) {
219
218
  parseArgument(format, itemFormatSchema);
220
219
  const { timeoutSecs = 'long', signal, stream, ...query } = parseArgument(options, downloadItemsOptionsSchema, 'DatasetClientDownloadItemsOptions');
221
- if (stream && !runtime.isNode) {
222
- throw new Error('The stream option can only be used in Node.js environment.');
223
- }
224
220
  const { data } = await this.httpClient.call({
225
221
  url: this.buildUrl('items'),
226
222
  method: 'GET',
@@ -178,22 +178,21 @@ export declare class KeyValueStoreClient extends ResourceClient {
178
178
  recordExists(key: string, options?: TimeoutOptions): Promise<boolean>;
179
179
  /**
180
180
  * By default, the value is parsed by the record's content type: `application/json` is parsed into a value,
181
- * `text/*` and `application/*xml` are decoded to a string, and anything else is returned as a Buffer (Node.js)
182
- * or ArrayBuffer (browser). A record whose body does not parse as its content type claims, such as a non-JSON
181
+ * `text/*` and `application/*xml` are decoded to a string, and anything else is returned as a Uint8Array.
182
+ * A record whose body does not parse as its content type claims, such as a non-JSON
183
183
  * string stored under `application/json`, makes the call throw an {@link InvalidResponseBodyError}, which
184
184
  * carries the raw body in `error.response`.
185
185
  *
186
- * You can use the `buffer` option to get the value in a Buffer (Node.js)
187
- * or ArrayBuffer (browser) format, which skips the parsing. In Node.js (not in browser) you can also
188
- * use the `stream` option to get a Readable stream.
186
+ * You can use the `buffer` option to get the value as a Uint8Array, which skips the parsing. You can also
187
+ * use the `stream` option to get the value unread, as a web ReadableStream.
189
188
  *
190
189
  * When the record does not exist, the function resolves to `undefined`. It does
191
190
  * NOT resolve to a `KeyValueStoreRecord` with an `undefined` value.
192
191
  *
193
192
  * @param key - The record key
194
193
  * @param options - Retrieval options
195
- * @param options.buffer - If `true`, the value is returned as a Buffer (Node.js) or ArrayBuffer (browser).
196
- * @param options.stream - If `true`, the value is returned as a Readable stream. Node.js only.
194
+ * @param options.buffer - If `true`, the value is returned as a Uint8Array.
195
+ * @param options.stream - If `true`, the value is returned as a web ReadableStream.
197
196
  * @param options.signature - Signature of a public URL, for reading a record without a token.
198
197
  * @param options.timeoutSecs - Timeout for the API request. Default is `'long'`.
199
198
  * @see https://docs.apify.com/api/v2/key-value-store-record-get
@@ -210,15 +209,17 @@ export declare class KeyValueStoreClient extends ResourceClient {
210
209
  * A string is sent as it is, even under `application/json`, so a string stored under a JSON content type has
211
210
  * to be valid JSON already, or {@link getRecord} fails to parse it back.
212
211
  *
213
- * **Note about streams:** If the value is a stream object (has `.pipe` and `.on` methods),
214
- * the upload cannot be retried on failure or follow redirects. For reliable uploads of a file,
215
- * pass a `Blob` from `fs.openAsBlob()` instead: it is read again for every attempt and never held
216
- * in memory whole.
212
+ * **Note about streams:** If the value is a stream, either a Node.js `Readable` or a web `ReadableStream`
213
+ * such as the `value` that {@link getRecord} returns with the `stream` option, the upload cannot be retried
214
+ * on failure or follow redirects. For reliable uploads of a file, pass a `Blob` from `fs.openAsBlob()`
215
+ * instead: it is read again for every attempt and never held in memory whole. A browser sends a web
216
+ * `ReadableStream` only over HTTP/2 or later, and only if it supports streaming request bodies at all:
217
+ * where it doesn't, the call throws a `TypeError`.
217
218
  *
218
219
  * @param record - The record to store
219
220
  * @param record.key - Record key (unique identifier)
220
- * @param record.value - Record value (a JSON-serializable value, Buffer, ArrayBuffer, typed array, Blob, or
221
- * Readable)
221
+ * @param record.value - Record value (a JSON-serializable value, Buffer, ArrayBuffer, typed array, Blob,
222
+ * Readable, or web ReadableStream)
222
223
  * @param record.contentType - Optional MIME type. Auto-detected if not provided:
223
224
  * - Objects: `'application/json; charset=utf-8'`
224
225
  * - Strings: `'text/plain; charset=utf-8'`
@@ -353,10 +354,10 @@ export interface KeyValueClientGetRecordOptions extends TimeoutOptions {
353
354
  * A value that `setRecord` accepts.
354
355
  *
355
356
  * Anything JSON-serializable, or binary content the client uploads as bytes instead of JSON-encoding
356
- * it: a `Buffer`, an `ArrayBuffer`, a typed array, a `Blob`, or a readable stream. `Buffer` is a
357
- * `Uint8Array`, so `TypedArray` covers it.
357
+ * it: a `Buffer`, an `ArrayBuffer`, a typed array, a `Blob`, a Node.js `Readable`, or a web `ReadableStream`.
358
+ * `Buffer` is a `Uint8Array`, so `TypedArray` covers it.
358
359
  */
359
- export type KeyValueStoreRecordValue = JsonValue | ArrayBuffer | TypedArray | Blob | Readable;
360
+ export type KeyValueStoreRecordValue = JsonValue | ArrayBuffer | TypedArray | Blob | Readable | ReadableStream<Uint8Array>;
360
361
  /**
361
362
  * Represents a record (key-value pair) in a Key-Value Store.
362
363
  *
@@ -387,8 +388,8 @@ export interface KeyValueStoreRecordOptions extends TimeoutOptions {
387
388
  /**
388
389
  * Helper type to determine the return type based on getRecord options.
389
390
  *
390
- * Returns Readable if stream option is true, Buffer if buffer option is true,
391
+ * Returns a web ReadableStream if stream option is true, Uint8Array if buffer option is true,
391
392
  * otherwise returns JsonValue.
392
393
  * @since Added in 2.0.6
393
394
  */
394
- export type ReturnTypeFromOptions<Options extends KeyValueClientGetRecordOptions> = Options['stream'] extends true ? Readable : Options['buffer'] extends true ? Buffer : JsonValue;
395
+ export type ReturnTypeFromOptions<Options extends KeyValueClientGetRecordOptions> = Options['stream'] extends true ? ReadableStream<Uint8Array> : Options['buffer'] extends true ? Uint8Array : JsonValue;
@@ -5,7 +5,7 @@ import { ResourceClient } from '../base/resource_client.js';
5
5
  import * as schemas from '../schemas.js';
6
6
  import { timeoutOptionsSchema, timeoutOptionsShape } from '../timeouts.js';
7
7
  import { runtime } from '#runtime';
8
- import { anyObjectSchema, applyQueryParamsToUrl, catchNotFoundOrThrow, isBlob, isBuffer, isStream, minForLimitParam, parseArgument, parseResponse, } from '../utils.js';
8
+ import { anyObjectSchema, applyQueryParamsToUrl, catchNotFoundOrThrow, isAnyStream, isBlob, isBuffer, minForLimitParam, parseArgument, parseResponse, } from '../utils.js';
9
9
  const listKeysOptionsSchema = z.strictObject({
10
10
  limit: z.number().min(0).optional(),
11
11
  chunkSize: z.number().positive().optional(),
@@ -320,9 +320,6 @@ export class KeyValueStoreClient extends ResourceClient {
320
320
  async getRecord(key, options = {}) {
321
321
  parseArgument(key, keySchema);
322
322
  const parsed = parseArgument(options, getRecordOptionsSchema, 'KeyValueClientGetRecordOptions');
323
- if (parsed.stream && !runtime.isNode) {
324
- throw new Error('The stream option can only be used in Node.js environment.');
325
- }
326
323
  if ('disableRedirect' in parsed) {
327
324
  log.deprecated('The disableRedirect option for getRecord() is deprecated. ' +
328
325
  'It has no effect and will be removed in the following major release.');
@@ -364,15 +361,17 @@ export class KeyValueStoreClient extends ResourceClient {
364
361
  * A string is sent as it is, even under `application/json`, so a string stored under a JSON content type has
365
362
  * to be valid JSON already, or {@link getRecord} fails to parse it back.
366
363
  *
367
- * **Note about streams:** If the value is a stream object (has `.pipe` and `.on` methods),
368
- * the upload cannot be retried on failure or follow redirects. For reliable uploads of a file,
369
- * pass a `Blob` from `fs.openAsBlob()` instead: it is read again for every attempt and never held
370
- * in memory whole.
364
+ * **Note about streams:** If the value is a stream, either a Node.js `Readable` or a web `ReadableStream`
365
+ * such as the `value` that {@link getRecord} returns with the `stream` option, the upload cannot be retried
366
+ * on failure or follow redirects. For reliable uploads of a file, pass a `Blob` from `fs.openAsBlob()`
367
+ * instead: it is read again for every attempt and never held in memory whole. A browser sends a web
368
+ * `ReadableStream` only over HTTP/2 or later, and only if it supports streaming request bodies at all:
369
+ * where it doesn't, the call throws a `TypeError`.
371
370
  *
372
371
  * @param record - The record to store
373
372
  * @param record.key - Record key (unique identifier)
374
- * @param record.value - Record value (a JSON-serializable value, Buffer, ArrayBuffer, typed array, Blob, or
375
- * Readable)
373
+ * @param record.value - Record value (a JSON-serializable value, Buffer, ArrayBuffer, typed array, Blob,
374
+ * Readable, or web ReadableStream)
376
375
  * @param record.contentType - Optional MIME type. Auto-detected if not provided:
377
376
  * - Objects: `'application/json; charset=utf-8'`
378
377
  * - Strings: `'text/plain; charset=utf-8'`
@@ -439,7 +438,7 @@ export class KeyValueStoreClient extends ResourceClient {
439
438
  if (contentEncoding !== undefined && !runtime.isNode) {
440
439
  throw new Error('The contentEncoding option can only be used in Node.js environment.');
441
440
  }
442
- const isBinaryValue = isStream(value) || isBuffer(value) || isBlob(value);
441
+ const isBinaryValue = isAnyStream(value) || isBuffer(value) || isBlob(value);
443
442
  // The client forwards the header without inspecting the body, so a string or a value serialized to JSON, which
444
443
  // cannot hold compressed bytes, would be stored under an encoding that misdescribes it.
445
444
  const declaresCompression = contentEncoding !== undefined && contentEncoding.trim().toLowerCase() !== 'identity';
@@ -1,4 +1,3 @@
1
- import type { Readable } from 'node:stream';
2
1
  import type { Log } from '@apify/log';
3
2
  import { Logger, LogLevel } from '@apify/log';
4
3
  import type { ApiClientSubResourceOptions } from '../base/api_client.js';
@@ -37,13 +36,13 @@ export declare class LogClient extends ResourceClient {
37
36
  /**
38
37
  * Retrieves the log as a string.
39
38
  *
40
- * The `buffer` option only selects the return type: the bytes come back as a Buffer (Node.js) or ArrayBuffer
41
- * (browser), not decoded to a string. Either way the whole log is downloaded in one response; to read it
42
- * incrementally, use {@link LogClient.stream}.
39
+ * The `buffer` option only selects the return type: the bytes come back as a Uint8Array, not decoded to a
40
+ * string. Either way the whole log is downloaded in one response; to read it incrementally, use
41
+ * {@link LogClient.stream}.
43
42
  *
44
43
  * @param options - Log retrieval options.
45
44
  * @param options.raw - If `true`, returns raw log content without any processing. Default is `false`.
46
- * @param options.buffer - If `true`, the log is returned as a Buffer (Node.js) or ArrayBuffer (browser) instead of a
45
+ * @param options.buffer - If `true`, the log is returned as a Uint8Array instead of a
47
46
  * string. It does not change how the log is fetched.
48
47
  * @param options.timeoutSecs - Timeout for the API request. Default is `'long'`.
49
48
  * @returns The log content, or `undefined` if it does not exist. A chained client such as `run.log()` throws an
@@ -55,19 +54,19 @@ export declare class LogClient extends ResourceClient {
55
54
  }): Promise<string | undefined>;
56
55
  get(options: LogGetOptions & {
57
56
  buffer: true;
58
- }): Promise<Buffer | undefined>;
59
- get(options?: LogGetOptions): Promise<string | Buffer | undefined>;
57
+ }): Promise<Uint8Array | undefined>;
58
+ get(options?: LogGetOptions): Promise<string | Uint8Array | undefined>;
60
59
  /**
61
- * Retrieves the log as a Readable stream. Only works in Node.js.
60
+ * Retrieves the log as a web ReadableStream of Uint8Array chunks.
62
61
  *
63
62
  * @param options - Log retrieval options.
64
63
  * @param options.raw - If `true`, returns raw log content without any processing. Default is `false`.
65
64
  * @param options.timeoutSecs - Timeout for the API request. Default is `'long'`.
66
- * @returns The log content as a Readable stream, or `undefined` if it does not exist. A chained client such as
65
+ * @returns The log content as a web ReadableStream, or `undefined` if it does not exist. A chained client such as
67
66
  * `run.log()` throws an `ApifyApiError` on a 404, since the run itself may be what is missing.
68
67
  * @see https://docs.apify.com/api/v2/log-get
69
68
  */
70
- stream(options?: LogOptions): Promise<Readable | undefined>;
69
+ stream(options?: LogOptions): Promise<ReadableStream<Uint8Array> | undefined>;
71
70
  }
72
71
  /**
73
72
  * @since Added in 2.20.0
@@ -81,7 +80,7 @@ export interface LogOptions extends TimeoutOptions {
81
80
  */
82
81
  export interface LogGetOptions extends LogOptions {
83
82
  /**
84
- * If `true`, the log is returned as a Buffer (Node.js) or ArrayBuffer (browser) instead of a string. It only selects
83
+ * If `true`, the log is returned as a Uint8Array instead of a string. It only selects
85
84
  * the return type; to read the log incrementally, use {@link LogClient.stream}.
86
85
  * @default false
87
86
  */
@@ -72,12 +72,12 @@ export class LogClient extends ResourceClient {
72
72
  return undefined;
73
73
  }
74
74
  /**
75
- * Retrieves the log as a Readable stream. Only works in Node.js.
75
+ * Retrieves the log as a web ReadableStream of Uint8Array chunks.
76
76
  *
77
77
  * @param options - Log retrieval options.
78
78
  * @param options.raw - If `true`, returns raw log content without any processing. Default is `false`.
79
79
  * @param options.timeoutSecs - Timeout for the API request. Default is `'long'`.
80
- * @returns The log content as a Readable stream, or `undefined` if it does not exist. A chained client such as
80
+ * @returns The log content as a web ReadableStream, or `undefined` if it does not exist. A chained client such as
81
81
  * `run.log()` throws an `ApifyApiError` on a 404, since the run itself may be what is missing.
82
82
  * @see https://docs.apify.com/api/v2/log-get
83
83
  */
@@ -227,7 +227,8 @@ export class StreamedLog {
227
227
  }
228
228
  // A stream opened during stop() would be cut after its first chunk, so read the log in one request.
229
229
  if (this.#stopLogging) {
230
- logStream.destroy();
230
+ // Cancelling a stream that has already failed rejects with its error.
231
+ await logStream.cancel().catch(() => { });
231
232
  continue;
232
233
  }
233
234
  lastChunkRemainder = await this.#logStreamChunks(logStream, signal);
@@ -3,7 +3,7 @@ import { ACT_JOB_STATUSES, META_ORIGINS } from '@apify/consts';
3
3
  import { ResourceClient } from '../base/resource_client.js';
4
4
  import * as schemas from '../schemas.js';
5
5
  import { timeoutOptionsSchema, timeoutOptionsShape } from '../timeouts.js';
6
- import { anyObjectSchema, cast, isStream, parseArgument, parseResponse, stringifyWebhooksToBase64 } from '../utils.js';
6
+ import { anyObjectSchema, cast, isAnyStream, parseArgument, parseResponse, stringifyWebhooksToBase64, } from '../utils.js';
7
7
  import { startWaitingForResources } from '../wait_for_resources.js';
8
8
  import { RunClient } from './run.js';
9
9
  import { RunCollectionClient } from './run_collection.js';
@@ -186,8 +186,8 @@ export class TaskClient extends ResourceClient {
186
186
  timeoutSecs: this.timeoutForWaitForFinish(timeoutSecs, 'medium', waitForFinish),
187
187
  signal,
188
188
  };
189
- // A `Readable` input is consumed by the first attempt, so a retry would start the run with an empty input.
190
- const response = await startWaitingForResources(async () => this.httpClient.call(request), isStream(input) ? false : waitForResources, this.httpClient.logger, signal);
189
+ // A stream input is consumed by the first attempt, so a retry would start the run with an empty input.
190
+ const response = await startWaitingForResources(async () => this.httpClient.call(request), isAnyStream(input) ? false : waitForResources, this.httpClient.logger, signal);
191
191
  return parseResponse(response, schemas.Run());
192
192
  }
193
193
  /**
@@ -50,10 +50,8 @@ export const runtime = {
50
50
  };
51
51
  return { httpAgent: new http.Agent(agentOptions), httpsAgent: new https.Agent(agentOptions) };
52
52
  },
53
- readableFromWeb(body) {
54
- if (!body)
55
- return Readable.from([]);
56
- return Readable.fromWeb(body);
53
+ streamToWeb(stream) {
54
+ return Readable.toWeb(stream);
57
55
  },
58
56
  unusedProxyHint() {
59
57
  const names = ['HTTP_PROXY', 'HTTPS_PROXY', 'http_proxy', 'https_proxy'].filter((name) => process.env[name]);
@@ -80,6 +78,9 @@ export const runtime = {
80
78
  openBlobBody(blob, onSourceError) {
81
79
  return Readable.from(readBlob(blob, onSourceError), { objectMode: false });
82
80
  },
81
+ openStreamBody(stream) {
82
+ return Readable.fromWeb(stream);
83
+ },
83
84
  };
84
85
  /**
85
86
  * Yields the bytes of a blob. Ending the iteration early, which destroying the `Readable` around it does, cancels
@@ -29,7 +29,7 @@ export interface Runtime {
29
29
  /**
30
30
  * Whether the Node.js implementation was selected, which the `node` condition settles when `#runtime` is
31
31
  * resolved - so a Node.js application bundled for a browser or a neutral target reports `false`. Log
32
- * streaming, the `stream` record option and request body compression are gated on it.
32
+ * redirection and request body compression are gated on it.
33
33
  */
34
34
  isNode: boolean;
35
35
  /**
@@ -56,10 +56,10 @@ export interface Runtime {
56
56
  timeoutMillis: number;
57
57
  }): Promise<HttpAgents | undefined>;
58
58
  /**
59
- * Wraps the body of a `fetch` response in a `Readable`, an empty one for a response without a body. Throws
60
- * where the runtime has no `Readable`, since streamed responses are a Node.js feature.
59
+ * Turns the `Readable` a transport returned for a streamed response into the web stream the callers get.
60
+ * Throws where the runtime has no `Readable`, since no transport can return one there.
61
61
  */
62
- readableFromWeb(body: ReadableStream<Uint8Array> | null): Readable;
62
+ streamToWeb(stream: Readable): ReadableStream<Uint8Array>;
63
63
  /**
64
64
  * Explains how to make `fetch` use the proxy named in the environment variables, or returns `undefined` when
65
65
  * none is set, the runtime already honors them, or it has no environment to read.
@@ -72,4 +72,11 @@ export interface Runtime {
72
72
  * which `fetch` and `XMLHttpRequest` read on their own, and never calls `onSourceError`.
73
73
  */
74
74
  openBlobBody(blob: Blob, onSourceError: (error: unknown) => void): Readable | Blob;
75
+ /**
76
+ * Opens a web `ReadableStream` request body. The Node.js implementation wraps it in a `Readable`, the one
77
+ * stream type every Node.js transport sends. The Web API one returns the stream itself, and throws a
78
+ * `TypeError` where `fetch` cannot send a stream body: such a browser would send the text
79
+ * `[object ReadableStream]` instead.
80
+ */
81
+ openStreamBody(stream: ReadableStream<Uint8Array>): Readable | ReadableStream<Uint8Array>;
75
82
  }
@@ -16,8 +16,8 @@ export const runtime = {
16
16
  async createHttpAgents() {
17
17
  return undefined;
18
18
  },
19
- readableFromWeb() {
20
- throw new Error('Streamed responses are only available in Node.js.');
19
+ streamToWeb() {
20
+ throw new Error('A Readable stream is only available in Node.js.');
21
21
  },
22
22
  // A browser applies the proxy settings of the system on its own.
23
23
  unusedProxyHint() {
@@ -26,4 +26,35 @@ export const runtime = {
26
26
  openBlobBody(blob) {
27
27
  return blob;
28
28
  },
29
+ openStreamBody(stream) {
30
+ if (!canSendStreamBody()) {
31
+ throw new TypeError('This runtime cannot send a ReadableStream as a request body. ' +
32
+ 'Read it into a Blob or bytes first, for example with `await new Response(stream).blob()`.');
33
+ }
34
+ return stream;
35
+ },
29
36
  };
37
+ /**
38
+ * Whether `fetch` sends a `ReadableStream` body as a stream. A runtime that does not, such as Firefox and Safari,
39
+ * never reads the `duplex` option and sends the stream converted to a string, under a text content type.
40
+ */
41
+ function canSendStreamBody() {
42
+ // Cloudflare Workers, Deno and Bun stream such a body too, without ever reading `duplex`.
43
+ if (/^(Cloudflare-Workers$|Deno\/|Bun\/)/.test(globalThis.navigator?.userAgent ?? ''))
44
+ return true;
45
+ let duplexRead = false;
46
+ try {
47
+ const request = new Request('https://api.apify.com', {
48
+ method: 'POST',
49
+ body: new ReadableStream(),
50
+ get duplex() {
51
+ duplexRead = true;
52
+ return 'half';
53
+ },
54
+ });
55
+ return duplexRead && !request.headers.has('content-type');
56
+ }
57
+ catch {
58
+ return false;
59
+ }
60
+ }
package/dist/utils.d.ts CHANGED
@@ -105,7 +105,16 @@ export declare function isBuffer(value: unknown): value is Buffer | ArrayBuffer
105
105
  * request, so a request with a blob body can be retried.
106
106
  */
107
107
  export declare function isBlob(value: unknown): value is Blob;
108
+ /**
109
+ * Whether a value is a web `ReadableStream`, which is what the callers get for a streamed response and may pass
110
+ * on as a request body.
111
+ */
112
+ export declare function isWebStream(value: unknown): value is ReadableStream<Uint8Array>;
108
113
  export declare function isStream(value: unknown): value is Readable;
114
+ /**
115
+ * Whether a value is a stream of either kind, which a request can send only once.
116
+ */
117
+ export declare function isAnyStream(value: unknown): value is Readable | ReadableStream<Uint8Array>;
109
118
  /**
110
119
  * Helper class to create async iterators from paginated list endpoints.
111
120
  */
package/dist/utils.js CHANGED
@@ -246,12 +246,25 @@ export function isBlob(value) {
246
246
  function isTagged(value, tag) {
247
247
  return Object.prototype.toString.call(value) === `[object ${tag}]`;
248
248
  }
249
+ /**
250
+ * Whether a value is a web `ReadableStream`, which is what the callers get for a streamed response and may pass
251
+ * on as a request body.
252
+ */
253
+ export function isWebStream(value) {
254
+ return isTagged(value, 'ReadableStream');
255
+ }
249
256
  export function isStream(value) {
250
257
  if (value === null || typeof value !== 'object')
251
258
  return false;
252
259
  const { on, pipe } = value;
253
260
  return typeof on === 'function' && typeof pipe === 'function';
254
261
  }
262
+ /**
263
+ * Whether a value is a stream of either kind, which a request can send only once.
264
+ */
265
+ export function isAnyStream(value) {
266
+ return isStream(value) || isWebStream(value);
267
+ }
255
268
  /**
256
269
  * Helper class to create async iterators from paginated list endpoints.
257
270
  */
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "apify-client",
3
- "version": "3.0.0-beta.114",
3
+ "version": "3.0.0-beta.116",
4
4
  "description": "Apify API client for JavaScript",
5
5
  "engines": {
6
6
  "node": ">=22.15.0"
@@ -101,6 +101,7 @@
101
101
  "compression": "^1.8.2",
102
102
  "esbuild": "0.28.2",
103
103
  "express": "^5.3.0",
104
+ "miniflare": "4.20260730.0",
104
105
  "oxfmt": "0.80.0",
105
106
  "oxlint": "1.93.0",
106
107
  "oxlint-tsgolint": "7.0.2007",