apify-client 3.0.0-rc.0 → 3.0.0-rc.2

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 (66) hide show
  1. package/README.md +10 -2
  2. package/dist/apify_api_error.d.ts +4 -3
  3. package/dist/apify_api_error.js +2 -1
  4. package/dist/apify_client.d.ts +8 -8
  5. package/dist/apify_client.js +10 -10
  6. package/dist/apify_client_error.d.ts +10 -0
  7. package/dist/apify_client_error.js +10 -0
  8. package/dist/axios.d.ts +2 -0
  9. package/dist/axios.js +1 -0
  10. package/dist/base/api_client.js +8 -20
  11. package/dist/base/resource_client.js +8 -8
  12. package/dist/body_parser.d.ts +1 -1
  13. package/dist/bundle.js +31 -30
  14. package/dist/bundle.js.map +1 -1
  15. package/dist/generated/api.d.ts +2427 -725
  16. package/dist/generated/schemas.d.ts +1868 -274
  17. package/dist/generated/schemas.js +437 -79
  18. package/dist/http_clients/axios.d.ts +35 -15
  19. package/dist/http_clients/axios.js +80 -32
  20. package/dist/http_clients/base.d.ts +105 -34
  21. package/dist/http_clients/base.js +169 -52
  22. package/dist/http_clients/fetch.d.ts +53 -0
  23. package/dist/http_clients/fetch.js +219 -0
  24. package/dist/http_clients/index.d.ts +2 -2
  25. package/dist/http_clients/index.js +1 -1
  26. package/dist/http_compressors/index.d.ts +2 -0
  27. package/dist/http_compressors/index.js +1 -0
  28. package/dist/http_compressors/resolve.d.ts +4 -3
  29. package/dist/http_compressors/resolve.js +4 -1
  30. package/dist/http_compressors/zstd.d.ts +34 -0
  31. package/dist/http_compressors/zstd.js +43 -0
  32. package/dist/index.d.ts +3 -1
  33. package/dist/index.js +2 -0
  34. package/dist/invalid_response_body_error.d.ts +5 -4
  35. package/dist/invalid_response_body_error.js +5 -4
  36. package/dist/models.d.ts +30 -61
  37. package/dist/resource_clients/actor.d.ts +33 -2
  38. package/dist/resource_clients/actor.js +46 -3
  39. package/dist/resource_clients/actor_server.d.ts +149 -0
  40. package/dist/resource_clients/actor_server.js +195 -0
  41. package/dist/resource_clients/actor_version.d.ts +7 -1
  42. package/dist/resource_clients/actor_version.js +3 -2
  43. package/dist/resource_clients/actor_version_collection.d.ts +2 -1
  44. package/dist/resource_clients/actor_version_collection.js +3 -2
  45. package/dist/resource_clients/dataset.d.ts +33 -5
  46. package/dist/resource_clients/dataset.js +12 -54
  47. package/dist/resource_clients/key_value_store.d.ts +63 -22
  48. package/dist/resource_clients/key_value_store.js +62 -19
  49. package/dist/resource_clients/log.d.ts +32 -7
  50. package/dist/resource_clients/log.js +11 -14
  51. package/dist/resource_clients/request_queue.d.ts +9 -0
  52. package/dist/resource_clients/request_queue.js +9 -6
  53. package/dist/resource_clients/run.d.ts +15 -2
  54. package/dist/resource_clients/run.js +12 -5
  55. package/dist/resource_clients/store_collection.d.ts +4 -0
  56. package/dist/resource_clients/task.js +3 -3
  57. package/dist/response_validation_error.d.ts +2 -1
  58. package/dist/response_validation_error.js +2 -1
  59. package/dist/runtime/node.js +79 -17
  60. package/dist/runtime/types.d.ts +35 -5
  61. package/dist/runtime/web.js +43 -1
  62. package/dist/schemas.d.ts +369 -3
  63. package/dist/schemas.js +25 -3
  64. package/dist/utils.d.ts +52 -27
  65. package/dist/utils.js +45 -25
  66. package/package.json +42 -30
@@ -13,6 +13,7 @@ const EMPTY_LOG_STREAM_RETRY_MILLIS = 500;
13
13
  /** Upper bound on the pause between reopens of an empty log stream. */
14
14
  const EMPTY_LOG_STREAM_MAX_RETRY_MILLIS = 5_000;
15
15
  const logOptionsSchema = z.strictObject({ raw: z.boolean().optional(), ...timeoutOptionsShape });
16
+ const logGetOptionsSchema = logOptionsSchema.extend({ buffer: z.boolean().optional() });
16
17
  /** How long `StreamedLog.stop()` waits for lines already in flight before aborting the log stream request. */
17
18
  const STOP_GRACE_MILLIS = 1000;
18
19
  /**
@@ -30,6 +31,9 @@ const STOP_GRACE_MILLIS = 1000;
30
31
  * const log = await runClient.log().get();
31
32
  * console.log(log);
32
33
  *
34
+ * // Get the log content as raw bytes
35
+ * const logBuffer = await runClient.log().get({ buffer: true });
36
+ *
33
37
  * // Stream the log in real-time
34
38
  * const stream = await runClient.log().stream();
35
39
  * stream.on('line', (line) => console.log(line));
@@ -47,18 +51,8 @@ export class LogClient extends ResourceClient {
47
51
  ...options,
48
52
  });
49
53
  }
50
- /**
51
- * Retrieves the log as a string.
52
- *
53
- * @param options - Log retrieval options.
54
- * @param options.raw - If `true`, returns raw log content without any processing. Default is `false`.
55
- * @param options.timeoutSecs - Timeout for the API request. Default is `'long'`.
56
- * @returns The log content as a string, or `undefined` if it does not exist. A chained client such as
57
- * `run.log()` throws an `ApifyApiError` on a 404, since the run itself may be what is missing.
58
- * @see https://docs.apify.com/api/v2/log-get
59
- */
60
54
  async get(options = {}) {
61
- const { timeoutSecs = 'long', signal, ...params } = parseArgument(options, logOptionsSchema, 'LogOptions');
55
+ const { timeoutSecs = 'long', signal, buffer, ...params } = parseArgument(options, logGetOptionsSchema, 'LogGetOptions');
62
56
  const requestOpts = {
63
57
  url: this.buildUrl(),
64
58
  method: 'GET',
@@ -66,6 +60,8 @@ export class LogClient extends ResourceClient {
66
60
  timeoutSecs,
67
61
  signal,
68
62
  };
63
+ if (buffer)
64
+ requestOpts.responseType = 'buffer';
69
65
  try {
70
66
  const response = await this.httpClient.call(requestOpts);
71
67
  return cast(response.data);
@@ -76,12 +72,12 @@ export class LogClient extends ResourceClient {
76
72
  return undefined;
77
73
  }
78
74
  /**
79
- * Retrieves the log as a Readable stream. Only works in Node.js.
75
+ * Retrieves the log as a web ReadableStream of Uint8Array chunks.
80
76
  *
81
77
  * @param options - Log retrieval options.
82
78
  * @param options.raw - If `true`, returns raw log content without any processing. Default is `false`.
83
79
  * @param options.timeoutSecs - Timeout for the API request. Default is `'long'`.
84
- * @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
85
81
  * `run.log()` throws an `ApifyApiError` on a 404, since the run itself may be what is missing.
86
82
  * @see https://docs.apify.com/api/v2/log-get
87
83
  */
@@ -231,7 +227,8 @@ export class StreamedLog {
231
227
  }
232
228
  // A stream opened during stop() would be cut after its first chunk, so read the log in one request.
233
229
  if (this.#stopLogging) {
234
- logStream.destroy();
230
+ // Cancelling a stream that has already failed rejects with its error.
231
+ await logStream.cancel().catch(() => { });
235
232
  continue;
236
233
  }
237
234
  lastChunkRemainder = await this.#logStreamChunks(logStream, signal);
@@ -301,6 +301,8 @@ export declare class RequestQueueClient extends ResourceClient {
301
301
  * queue contents.
302
302
  *
303
303
  * @param options - Pagination options
304
+ * @param options.chunkSize - Maximum number of requests fetched per API call when iterating across pages. `limit`
305
+ * then caps the total across all pages.
304
306
  * @param options.timeoutSecs - Timeout for each API request. Default is `'medium'`.
305
307
  * @returns List of requests with pagination information
306
308
  * @see https://docs.apify.com/api/v2/request-queue-requests-get
@@ -383,6 +385,13 @@ export type RequestQueueListRequestsFilter = 'locked' | 'pending';
383
385
  */
384
386
  export interface RequestQueueClientListRequestsOptions extends TimeoutOptions {
385
387
  limit?: number;
388
+ /**
389
+ * Maximum number of requests returned in one API response. When the call is iterated with `for await`, the iterator
390
+ * fetches requests in chunks of this size and yields them one by one, until `limit` is reached or the RQ is
391
+ * exhausted. Awaiting the call returns only the first chunk. Without it, the API's default page size
392
+ * applies.
393
+ */
394
+ chunkSize?: number;
386
395
  /**
387
396
  * @since Added in 2.23.2
388
397
  */
@@ -5,7 +5,7 @@ import { ResourceClient } from '../base/resource_client.js';
5
5
  import { ResponseValidationError } from '../response_validation_error.js';
6
6
  import * as schemas from '../schemas.js';
7
7
  import { optionalSignalSchema, optionalTimeoutSchema, timeoutOptionsSchema, timeoutOptionsShape } from '../timeouts.js';
8
- import { anyObjectSchema, catchNotFoundOrThrow, isNonArrayObject, parseArgument, parseResponse, RequestQueuePaginationIterator, sleep, splitIntoJsonArrayBatches, utf8ByteLength, } from '../utils.js';
8
+ import { anyObjectSchema, catchNotFoundOrThrow, isNonArrayObject, minForLimitParam, parseArgument, parseResponse, RequestQueuePaginationIterator, sleep, splitIntoJsonArrayBatches, utf8ByteLength, } from '../utils.js';
9
9
  const DEFAULT_PARALLEL_BATCH_ADD_REQUESTS = 5;
10
10
  const DEFAULT_UNPROCESSED_RETRIES_BATCH_ADD_REQUESTS = 3;
11
11
  const DEFAULT_MIN_DELAY_BETWEEN_UNPROCESSED_REQUESTS_RETRIES_MILLIS = 500;
@@ -39,6 +39,7 @@ const prolongRequestLockOptionsSchema = z.strictObject({
39
39
  const requestFilterSchema = z.array(z.enum(['locked', 'pending'])).min(1);
40
40
  const listRequestsOptionsSchema = z.strictObject({
41
41
  limit: z.number().min(0).optional(),
42
+ chunkSize: z.number().positive().optional(),
42
43
  cursor: z.string().optional(),
43
44
  filter: requestFilterSchema.optional(),
44
45
  ...timeoutOptionsShape,
@@ -622,15 +623,17 @@ export class RequestQueueClient extends ResourceClient {
622
623
  * queue contents.
623
624
  *
624
625
  * @param options - Pagination options
626
+ * @param options.chunkSize - Maximum number of requests fetched per API call when iterating across pages. `limit`
627
+ * then caps the total across all pages.
625
628
  * @param options.timeoutSecs - Timeout for each API request. Default is `'medium'`.
626
629
  * @returns List of requests with pagination information
627
630
  * @see https://docs.apify.com/api/v2/request-queue-requests-get
628
631
  * @since Added in 2.5.1
629
632
  */
630
633
  listRequests(options = {}) {
631
- // `timeoutSecs` and `signal` apply to every page request; they are not API parameters, so they must not reach
632
- // the query string.
633
- const { timeoutSecs, signal, ...parsed } = parseArgument(options, listRequestsOptionsSchema, 'RequestQueueClientListRequestsOptions');
634
+ // `chunkSize` only sizes the page requests, and `timeoutSecs` and `signal` apply to every one of them; none of
635
+ // them is an API parameter, so they must not reach the query string.
636
+ const { chunkSize, timeoutSecs, signal, ...parsed } = parseArgument(options, listRequestsOptionsSchema, 'RequestQueueClientListRequestsOptions');
634
637
  const pageTimeout = this.#resolveTimeout(timeoutSecs, 'medium');
635
638
  const getPaginatedList = async (rqListOptions = {}) => {
636
639
  const response = await this.httpClient.call({
@@ -646,7 +649,7 @@ export class RequestQueueClient extends ResourceClient {
646
649
  });
647
650
  return parseResponse(response, schemas.ListOfRequests());
648
651
  };
649
- const paginatedListPromise = getPaginatedList(parsed);
652
+ const paginatedListPromise = getPaginatedList({ ...parsed, limit: minForLimitParam(parsed.limit, chunkSize) });
650
653
  async function* asyncGenerator() {
651
654
  let currentPage = await paginatedListPromise;
652
655
  yield* currentPage.items;
@@ -659,7 +662,7 @@ export class RequestQueueClient extends ResourceClient {
659
662
  ) {
660
663
  const newOptions = {
661
664
  ...parsed,
662
- limit: remainingItems,
665
+ limit: minForLimitParam(remainingItems, chunkSize),
663
666
  cursor: currentPage.nextCursor,
664
667
  };
665
668
  currentPage = await getPaginatedList(newOptions);
@@ -94,6 +94,9 @@ export declare class RunClient extends ResourceClient {
94
94
  * and resource allocation. The run effectively becomes a run of the target Actor with new input.
95
95
  * This is useful for chaining Actor executions or implementing complex workflows.
96
96
  *
97
+ * Only the run itself can metamorph: the client must use the run's own API token, which the run gets
98
+ * in the `APIFY_TOKEN` environment variable. With any other token, the API rejects the request.
99
+ *
97
100
  * @param targetActorId - ID or username/name of the target Actor
98
101
  * @param input - Input for the target Actor: an object or array serialized to JSON, or raw bytes sent as they
99
102
  * are. Omit it to metamorph without input.
@@ -105,8 +108,9 @@ export declare class RunClient extends ResourceClient {
105
108
  *
106
109
  * @example
107
110
  * ```javascript
108
- * // Transform current run into another Actor
109
- * const metamorphedRun = await client.run('original-run-id').metamorph(
111
+ * // Inside the run: transform it into another Actor
112
+ * const client = new ApifyClient({ token: process.env.APIFY_TOKEN });
113
+ * const metamorphedRun = await client.run(process.env.ACTOR_RUN_ID).metamorph(
110
114
  * 'target-actor-id',
111
115
  * { url: 'https://example.com' }
112
116
  * );
@@ -186,6 +190,7 @@ export declare class RunClient extends ResourceClient {
186
190
  * @param options.eventName - **Required.** Name of the event to charge for.
187
191
  * @param options.count - Number of times to charge the event. Default is 1.
188
192
  * @param options.idempotencyKey - Optional key to ensure the charge is not duplicated. If not provided, one is auto-generated.
193
+ * @param options.requestId - ID of the Server Actor request being charged, from the `X-Actor-Request-ID` header of the incoming request. Required for multi-tenant Server Actor runs.
189
194
  * @param options.timeoutSecs - Timeout for the API request. Default is `'short'`.
190
195
  * @returns Empty response object.
191
196
  * @see https://docs.apify.com/api/v2/post-charge-run
@@ -411,6 +416,12 @@ export interface RunChargeOptions extends TimeoutOptions {
411
416
  count?: number;
412
417
  /** Defaults to runId-eventName-timestamp */
413
418
  idempotencyKey?: string;
419
+ /**
420
+ * ID of the Server Actor request being charged, taken from the `X-Actor-Request-ID` header of the incoming request.
421
+ * Required for multi-tenant Server Actor runs, where it maps the charge to the caller's account instead of the account that started the run.
422
+ * Ignored elsewhere.
423
+ */
424
+ requestId?: string;
414
425
  }
415
426
  /**
416
427
  * Options for waiting for a Run to finish.
@@ -427,6 +438,8 @@ export interface RunWaitForFinishOptions extends TimeoutOptions {
427
438
  * Options for iterating over the items of a run's default dataset while the run is still producing them.
428
439
  */
429
440
  export interface RunIterateDatasetItemsOptions extends PaginationOptions, TimeoutOptions {
441
+ /** Maximum number of dataset rows requested per API call. Default is 1000. */
442
+ chunkSize?: number;
430
443
  /** If `true`, returns only non-empty items and skips hidden fields. */
431
444
  clean?: boolean;
432
445
  /** Field names to include in the items. Omits all other fields. */
@@ -5,7 +5,7 @@ import { ResourceClient } from '../base/resource_client.js';
5
5
  import * as schemas from '../schemas.js';
6
6
  import { optionalSignalSchema, optionalTimeoutSchema, timeoutOptionsSchema, timeoutOptionsShape } from '../timeouts.js';
7
7
  import { runtime } from '#runtime';
8
- import { anyObjectSchema, paginationOptionsShape, parseArgument, parseResponse, SCANNED_COUNT } from '../utils.js';
8
+ import { anyObjectSchema, paginationOptionsShape, parseArgument, parseResponse } from '../utils.js';
9
9
  import { DatasetClient } from './dataset.js';
10
10
  import { KeyValueStoreClient } from './key_value_store.js';
11
11
  import { LogClient, LoggerActorRedirect, StreamedLog } from './log.js';
@@ -32,6 +32,7 @@ const chargeOptionsSchema = z.strictObject({
32
32
  eventName: z.string(),
33
33
  count: z.number().default(1),
34
34
  idempotencyKey: z.string().optional(),
35
+ requestId: z.string().optional(),
35
36
  ...timeoutOptionsShape,
36
37
  });
37
38
  const waitForFinishOptionsSchema = z.strictObject({ waitSecs: z.number().optional(), ...timeoutOptionsShape });
@@ -152,6 +153,9 @@ export class RunClient extends ResourceClient {
152
153
  * and resource allocation. The run effectively becomes a run of the target Actor with new input.
153
154
  * This is useful for chaining Actor executions or implementing complex workflows.
154
155
  *
156
+ * Only the run itself can metamorph: the client must use the run's own API token, which the run gets
157
+ * in the `APIFY_TOKEN` environment variable. With any other token, the API rejects the request.
158
+ *
155
159
  * @param targetActorId - ID or username/name of the target Actor
156
160
  * @param input - Input for the target Actor: an object or array serialized to JSON, or raw bytes sent as they
157
161
  * are. Omit it to metamorph without input.
@@ -163,8 +167,9 @@ export class RunClient extends ResourceClient {
163
167
  *
164
168
  * @example
165
169
  * ```javascript
166
- * // Transform current run into another Actor
167
- * const metamorphedRun = await client.run('original-run-id').metamorph(
170
+ * // Inside the run: transform it into another Actor
171
+ * const client = new ApifyClient({ token: process.env.APIFY_TOKEN });
172
+ * const metamorphedRun = await client.run(process.env.ACTOR_RUN_ID).metamorph(
168
173
  * 'target-actor-id',
169
174
  * { url: 'https://example.com' }
170
175
  * );
@@ -294,13 +299,14 @@ export class RunClient extends ResourceClient {
294
299
  * @param options.eventName - **Required.** Name of the event to charge for.
295
300
  * @param options.count - Number of times to charge the event. Default is 1.
296
301
  * @param options.idempotencyKey - Optional key to ensure the charge is not duplicated. If not provided, one is auto-generated.
302
+ * @param options.requestId - ID of the Server Actor request being charged, from the `X-Actor-Request-ID` header of the incoming request. Required for multi-tenant Server Actor runs.
297
303
  * @param options.timeoutSecs - Timeout for the API request. Default is `'short'`.
298
304
  * @returns Empty response object.
299
305
  * @see https://docs.apify.com/api/v2/post-charge-run
300
306
  * @since Added in 2.11.0
301
307
  */
302
308
  async charge(options) {
303
- const { eventName, count, idempotencyKey: providedIdempotencyKey, timeoutSecs = 'short', signal, } = parseArgument(options, chargeOptionsSchema, 'RunChargeOptions');
309
+ const { eventName, count, idempotencyKey: providedIdempotencyKey, timeoutSecs = 'short', requestId, signal, } = parseArgument(options, chargeOptionsSchema, 'RunChargeOptions');
304
310
  /** To avoid duplicates during the same milisecond, doesn't need to by crypto-secure. */
305
311
  const randomSuffix = (Math.random() + 1).toString(36).slice(3, 8);
306
312
  const idempotencyKey = providedIdempotencyKey ?? `${this.id}-${eventName}-${Date.now()}-${randomSuffix}`;
@@ -310,6 +316,7 @@ export class RunClient extends ResourceClient {
310
316
  data: {
311
317
  eventName,
312
318
  count,
319
+ requestId,
313
320
  },
314
321
  headers: {
315
322
  [RUN_CHARGE_IDEMPOTENCY_HEADER]: idempotencyKey,
@@ -534,7 +541,7 @@ export class RunClient extends ResourceClient {
534
541
  yield* page.items;
535
542
  // Only an empty page marks the end, as filters can shorten a full one. A page that `clean`, `skipEmpty` or
536
543
  // `unwind` emptied past a lagging `itemCount` reports no scanned rows either, so a plain read checks.
537
- const isEmpty = page.items.length === 0 && !page[SCANNED_COUNT];
544
+ const isEmpty = page.count === 0;
538
545
  if (isEmpty &&
539
546
  (!(clean || skipEmpty || unwind?.length) ||
540
547
  (await datasetClient.listItems({ offset: position, limit: 1, timeoutSecs, signal })).items
@@ -58,6 +58,10 @@ export declare class StoreCollectionClient extends ResourceCollectionClient {
58
58
  */
59
59
  export interface StoreCollectionListOptions extends PaginationOptions, TimeoutOptions {
60
60
  search?: string;
61
+ /**
62
+ * @deprecated The API ignores this option. Results are ordered by relevance when `search` is used, and by Store
63
+ * position otherwise. Sort the results on the client if you need a different order.
64
+ */
61
65
  sortBy?: string;
62
66
  category?: string;
63
67
  username?: string;
@@ -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
  /**
@@ -1,4 +1,5 @@
1
1
  import type { z } from 'zod';
2
+ import { ApifyClientError } from './apify_client_error.js';
2
3
  /**
3
4
  * Thrown when an API response does not match the schema the client expects for it.
4
5
  *
@@ -12,7 +13,7 @@ import type { z } from 'zod';
12
13
  * {@link https://zod.dev | zod} issues are available on `issues`, and the original `ZodError` on `cause`,
13
14
  * for programmatic inspection.
14
15
  */
15
- export declare class ResponseValidationError extends Error {
16
+ export declare class ResponseValidationError extends ApifyClientError {
16
17
  /** Structured issues from the underlying schema check. */
17
18
  readonly issues: z.ZodError['issues'];
18
19
  /** HTTP method of the request whose response failed validation, upper-cased. */
@@ -1,4 +1,5 @@
1
1
  import { ArgumentValidationError } from '@apify/validations';
2
+ import { ApifyClientError } from './apify_client_error.js';
2
3
  const REPORT_HINT = 'The API returned something its OpenAPI specification does not describe. ' +
3
4
  'Please report this at https://github.com/apify/apify-client-js/issues.';
4
5
  /**
@@ -14,7 +15,7 @@ const REPORT_HINT = 'The API returned something its OpenAPI specification does n
14
15
  * {@link https://zod.dev | zod} issues are available on `issues`, and the original `ZodError` on `cause`,
15
16
  * for programmatic inspection.
16
17
  */
17
- export class ResponseValidationError extends Error {
18
+ export class ResponseValidationError extends ApifyClientError {
18
19
  /** Structured issues from the underlying schema check. */
19
20
  issues;
20
21
  /** HTTP method of the request whose response failed validation, upper-cased. */
@@ -1,27 +1,36 @@
1
+ import http from 'node:http';
2
+ import https from 'node:https';
1
3
  import os from 'node:os';
2
- import { brotliCompress, constants, gzip } from 'node:zlib';
4
+ import { Readable } from 'node:stream';
5
+ import { brotliCompress, constants, gzip, zstdCompress } from 'node:zlib';
6
+ const isBunOrDeno = Boolean(process.versions.bun || process.versions.deno);
3
7
  /**
4
8
  * The Node.js implementation of {@link Runtime}. Deno and Bun resolve the `node` condition too and
5
9
  * provide the built-ins it uses.
6
10
  */
7
11
  export const runtime = {
8
12
  isNode: true,
13
+ fetchFailsWithCause: !isBunOrDeno,
9
14
  platform: `${os.platform()}; Node/${process.version}`,
10
15
  async compress(data, { algorithm, quality }) {
11
16
  return new Promise((resolve, reject) => {
12
17
  const done = (error, result) => (error ? reject(error) : resolve(result));
13
- if (algorithm === 'br') {
14
- brotliCompress(data, { params: { [constants.BROTLI_PARAM_QUALITY]: quality } }, done);
15
- }
16
- else {
17
- gzip(data, { level: quality }, done);
18
+ switch (algorithm) {
19
+ case 'br':
20
+ brotliCompress(data, { params: { [constants.BROTLI_PARAM_QUALITY]: quality } }, done);
21
+ break;
22
+ case 'gzip':
23
+ gzip(data, { level: quality }, done);
24
+ break;
25
+ case 'zstd':
26
+ zstdCompress(data, { params: { [constants.ZSTD_c_compressionLevel]: quality } }, done);
27
+ break;
28
+ default:
29
+ reject(new Error(`Unrecognized compression algorithm: ${String(algorithm)}`));
18
30
  }
19
31
  });
20
32
  },
21
33
  async createHttpAgents({ timeoutMillis }) {
22
- // Loaded on the first request rather than with the client: the proxy support pulls in a sizeable
23
- // dependency tree that a client which never sends a request should not pay for.
24
- const { ProxyAgent } = await import('proxy-agent');
25
34
  // We want to keep sockets alive for better performance.
26
35
  const agentOptions = {
27
36
  keepAlive: true,
@@ -36,14 +45,67 @@ export const runtime = {
36
45
  maxFreeSockets: 256,
37
46
  // LIFO scheduling - reuse most recently used sockets for better performance
38
47
  scheduling: 'lifo',
48
+ // Disable Nagle's algorithm for lower latency. The agent hands the option to `net.createConnection()`.
49
+ noDelay: true,
39
50
  };
40
- // ProxyAgent picks the proxy up from the environment variables and supports CONNECT tunneling.
41
- const agent = new ProxyAgent(agentOptions);
42
- // Disable Nagle's algorithm for lower latency
43
- // This sends data immediately instead of buffering small packets
44
- agent.on('socket', (socket) => {
45
- socket.setNoDelay(true);
46
- });
47
- return { httpAgent: agent, httpsAgent: agent };
51
+ return { httpAgent: new http.Agent(agentOptions), httpsAgent: new https.Agent(agentOptions) };
52
+ },
53
+ streamToWeb(stream) {
54
+ return Readable.toWeb(stream);
55
+ },
56
+ unusedProxyHint() {
57
+ const names = ['HTTP_PROXY', 'HTTPS_PROXY', 'http_proxy', 'https_proxy'].filter((name) => process.env[name]);
58
+ if (names.length === 0)
59
+ return undefined;
60
+ // The `fetch` of Bun and Deno reads these variables on its own.
61
+ if (isBunOrDeno)
62
+ return undefined;
63
+ const [major, minor] = process.versions.node.split('.').map(Number);
64
+ const supported = major >= 24 || (major === 22 && minor >= 21);
65
+ const flags = [...process.execArgv, ...(process.env.NODE_OPTIONS ?? '').split(/\s+/)];
66
+ const enabled = process.env.NODE_USE_ENV_PROXY === '1' || flags.includes('--use-env-proxy');
67
+ // An older Node.js ignores the switch, so the proxy stays unused there even with it set.
68
+ if (supported && enabled)
69
+ return undefined;
70
+ const fix = supported
71
+ ? 'Start Node.js with NODE_USE_ENV_PROXY=1 to send the requests through it.'
72
+ : `Node.js ${process.versions.node} cannot route fetch() through it: upgrade to Node.js 22.21 or 24, ` +
73
+ 'then start it with NODE_USE_ENV_PROXY=1.';
74
+ return (`The request failed, and the proxy set in ${names[0]} was not used, since fetch() in Node.js ignores the ` +
75
+ `proxy environment variables by default. ${fix} ` +
76
+ 'See https://docs.apify.com/api/client/js/docs/concepts/custom-http-clients#proxies for the other options.');
77
+ },
78
+ openBlobBody(blob, onSourceError) {
79
+ return Readable.from(readBlob(blob, onSourceError), { objectMode: false });
80
+ },
81
+ openStreamBody(stream) {
82
+ return Readable.fromWeb(stream);
48
83
  },
49
84
  };
85
+ /**
86
+ * Yields the bytes of a blob. Ending the iteration early, which destroying the `Readable` around it does, cancels
87
+ * the read and releases a file the blob reads from. Only a failing read is reported: an error the `Readable` is
88
+ * destroyed with is thrown in at the `yield` and belongs to the transport. A `for await` loop would surface both at
89
+ * the same place, so the loop calls `next()` itself to catch only the read.
90
+ */
91
+ async function* readBlob(blob, onSourceError) {
92
+ const chunks = blob.stream()[Symbol.asyncIterator]();
93
+ try {
94
+ while (true) {
95
+ let chunk;
96
+ try {
97
+ chunk = await chunks.next();
98
+ }
99
+ catch (error) {
100
+ onSourceError(error);
101
+ throw error;
102
+ }
103
+ if (chunk.done)
104
+ return;
105
+ yield chunk.value;
106
+ }
107
+ }
108
+ finally {
109
+ await chunks.return?.();
110
+ }
111
+ }
@@ -1,17 +1,18 @@
1
1
  import type http from 'node:http';
2
2
  import type https from 'node:https';
3
+ import type { Readable } from 'node:stream';
3
4
  /**
4
5
  * What to compress a request body with, as the built-in `HttpCompressor` implementations ask for it.
5
6
  * @internal
6
7
  */
7
8
  export interface CompressionOptions {
8
9
  /** Algorithm to compress with, named by the `Content-Encoding` value it produces. */
9
- algorithm: 'br' | 'gzip';
10
+ algorithm: 'br' | 'gzip' | 'zstd';
10
11
  /** Compression level, in the range the algorithm defines. */
11
12
  quality: number;
12
13
  }
13
14
  /**
14
- * The agents axios's Node.js adapter sends requests through.
15
+ * The agents the Node.js adapter of axios sends requests through.
15
16
  * @internal
16
17
  */
17
18
  export interface HttpAgents {
@@ -28,9 +29,14 @@ export interface Runtime {
28
29
  /**
29
30
  * Whether the Node.js implementation was selected, which the `node` condition settles when `#runtime` is
30
31
  * resolved - so a Node.js application bundled for a browser or a neutral target reports `false`. Log
31
- * streaming, the `stream` record option and request body compression are gated on it.
32
+ * redirection and request body compression are gated on it.
32
33
  */
33
34
  isNode: boolean;
35
+ /**
36
+ * Whether a failed `fetch` rejects with a `TypeError` that names the network error as its `cause`, which is
37
+ * what Node.js does. Bun and Deno resolve the `node` condition too, and their `fetch` does not.
38
+ */
39
+ fetchFailsWithCause: boolean;
34
40
  /**
35
41
  * The platform part of the `User-Agent` header, or `undefined` where the runtime does not let a client
36
42
  * set that header (browsers).
@@ -43,10 +49,34 @@ export interface Runtime {
43
49
  */
44
50
  compress(data: Uint8Array, options: CompressionOptions): Promise<Buffer>;
45
51
  /**
46
- * Creates the agents axios's Node.js adapter sends requests through, or resolves to `undefined` where
47
- * axios does not use agents.
52
+ * Creates the keep-alive agents the Node.js adapter of axios sends requests through, or resolves to `undefined`
53
+ * where axios does not use agents.
48
54
  */
49
55
  createHttpAgents(options: {
50
56
  timeoutMillis: number;
51
57
  }): Promise<HttpAgents | undefined>;
58
+ /**
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
+ */
62
+ streamToWeb(stream: Readable): ReadableStream<Uint8Array>;
63
+ /**
64
+ * Explains how to make `fetch` use the proxy named in the environment variables, or returns `undefined` when
65
+ * none is set, the runtime already honors them, or it has no environment to read.
66
+ */
67
+ unusedProxyHint(): string | undefined;
68
+ /**
69
+ * Opens a `Blob` request body for one attempt. The Node.js implementation reads the blob into a `Readable` and
70
+ * reports an error the blob raises while it is read to `onSourceError` before the stream fails with it, so the
71
+ * pipeline can tell a failing source apart from a failing connection. The Web API one returns the blob itself,
72
+ * which `fetch` and `XMLHttpRequest` read on their own, and never calls `onSourceError`.
73
+ */
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>;
52
82
  }
@@ -3,9 +3,10 @@
3
3
  */
4
4
  export const runtime = {
5
5
  isNode: false,
6
+ fetchFailsWithCause: false,
6
7
  // Browsers do not let a page set the `User-Agent` header.
7
8
  platform: undefined,
8
- // No request compression: brotli and gzip have no Web API, and a `content-encoding` request header is not
9
+ // No request compression: brotli, gzip and zstd have no Web API, and a `content-encoding` request header is not
9
10
  // on the list of headers the Apify API allows in a cross-origin request, so a browser would fail the
10
11
  // preflight. The client compresses in Node.js alone, so nothing reaches this.
11
12
  async compress() {
@@ -15,4 +16,45 @@ export const runtime = {
15
16
  async createHttpAgents() {
16
17
  return undefined;
17
18
  },
19
+ streamToWeb() {
20
+ throw new Error('A Readable stream is only available in Node.js.');
21
+ },
22
+ // A browser applies the proxy settings of the system on its own.
23
+ unusedProxyHint() {
24
+ return undefined;
25
+ },
26
+ openBlobBody(blob) {
27
+ return blob;
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
+ },
18
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
+ }