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
@@ -1,3 +1,4 @@
1
+ import type { ValueOf } from '@apify/consts';
1
2
  import { ACTOR_JOB_STATUSES, ACTOR_PERMISSION_LEVEL, META_ORIGINS } from '@apify/consts';
2
3
  import { Log } from '@apify/log';
3
4
  import type { ApiClientSubResourceOptions } from '../base/api_client.js';
@@ -5,6 +6,7 @@ import { ResourceClient } from '../base/resource_client.js';
5
6
  import type { ActorResource, Run } from '../models.js';
6
7
  import type { TimeoutOptions } from '../timeouts.js';
7
8
  import type { Dictionary } from '../utils.js';
9
+ import { ActorServerClient } from './actor_server.js';
8
10
  import { ActorVersionClient } from './actor_version.js';
9
11
  import { ActorVersionCollectionClient } from './actor_version_collection.js';
10
12
  import type { Build, BuildClientGetOptions } from './build.js';
@@ -14,7 +16,6 @@ import { RunClient } from './run.js';
14
16
  import { RunCollectionClient } from './run_collection.js';
15
17
  import type { WebhookUpdateData } from './webhook.js';
16
18
  import { WebhookCollectionClient } from './webhook_collection.js';
17
- import type { ValueOf } from 'type-fest';
18
19
  export type { ActorResource, ActorChargeEvent, ActorChargeEvents, ActorDefinition, ActorRunPricingInfo, ActorRunStorageIds, ActorStandby, ActorStats, DefaultRunOptions, ExampleRunInput, FlatPricePerMonthActorPricingInfo, FreeActorPricingInfo, RunMetamorphEvent, PayPerEventActorPricingInfo, PricePerDatasetItemActorPricingInfo, Run, RunMeta, RunOptions, RunListItem, RunStats, RunUsage, TaggedBuildInfo, TaggedBuilds, TieredPricingPerDatasetItem, TieredPricingPerDatasetItemEntry, TieredPricingPerEvent, TieredPricingPerEventEntry, } from '../models.js';
19
20
  /**
20
21
  * Client for managing a specific Actor.
@@ -37,6 +38,7 @@ export type { ActorResource, ActorChargeEvent, ActorChargeEvents, ActorDefinitio
37
38
  * @see https://docs.apify.com/platform/actors
38
39
  */
39
40
  export declare class ActorClient extends ResourceClient {
41
+ #private;
40
42
  /**
41
43
  * @hidden
42
44
  */
@@ -293,6 +295,34 @@ export declare class ActorClient extends ResourceClient {
293
295
  * @see https://docs.apify.com/api/v2/act-webhooks-get
294
296
  */
295
297
  webhooks(): WebhookCollectionClient;
298
+ /**
299
+ * Returns a client for the server interface of this Actor.
300
+ *
301
+ * A Server Actor runs a web server, its server interface, that is called over HTTP without starting a run for
302
+ * each call. Server Actors were formerly called Actor Standby, and {@link standby} is a deprecated alias of this
303
+ * method. Every call returns the same client, so the server URL it fetches is reused.
304
+ *
305
+ * @returns The client for the server interface of this Actor
306
+ * @see https://docs.apify.com/platform/actors/running/standby
307
+ *
308
+ * @example
309
+ * ```javascript
310
+ * const response = await client.actor('username/actor-name').server().request('/search', {
311
+ * params: { q: 'apify' },
312
+ * });
313
+ * ```
314
+ */
315
+ server(): ActorServerClient;
316
+ /**
317
+ * Returns a client for the server interface of this Actor in Standby mode.
318
+ *
319
+ * Named after Actor Standby, the former name of Server Actors.
320
+ *
321
+ * @deprecated Use {@link server} instead. Will be removed in v4.
322
+ * @returns The client for the server interface of this Actor
323
+ * @see https://docs.apify.com/platform/actors/running/standby
324
+ */
325
+ standby(): ActorServerClient;
296
326
  }
297
327
  /**
298
328
  * Fields that can be updated when modifying an Actor.
@@ -383,7 +413,8 @@ export interface ActorStartOptions extends TimeoutOptions {
383
413
  * A run that requests more memory than the whole memory limit of the account is rejected with
384
414
  * `actor-memory-limit-exceeded` as well and never starts, so `true` retries it forever.
385
415
  *
386
- * 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.
387
418
  */
388
419
  waitForResources?: boolean | number;
389
420
  }
@@ -4,8 +4,9 @@ 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
+ import { ActorServerClient } from './actor_server.js';
9
10
  import { ActorVersionClient } from './actor_version.js';
10
11
  import { ActorVersionCollectionClient } from './actor_version_collection.js';
11
12
  import { BuildClient } from './build.js';
@@ -81,6 +82,7 @@ const lastRunOptionsSchema = z.strictObject({
81
82
  * @see https://docs.apify.com/platform/actors
82
83
  */
83
84
  export class ActorClient extends ResourceClient {
85
+ #serverClient;
84
86
  /**
85
87
  * @hidden
86
88
  */
@@ -194,8 +196,8 @@ export class ActorClient extends ResourceClient {
194
196
  'content-type': parsed.contentType,
195
197
  };
196
198
  }
197
- // A `Readable` input is consumed by the first attempt, so a retry would start the run with an empty input.
198
- 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);
199
201
  return parseResponse(response, schemas.Run());
200
202
  }
201
203
  /**
@@ -475,4 +477,45 @@ export class ActorClient extends ResourceClient {
475
477
  webhooks() {
476
478
  return new WebhookCollectionClient(this.subResourceOptions());
477
479
  }
480
+ /**
481
+ * Returns a client for the server interface of this Actor.
482
+ *
483
+ * A Server Actor runs a web server, its server interface, that is called over HTTP without starting a run for
484
+ * each call. Server Actors were formerly called Actor Standby, and {@link standby} is a deprecated alias of this
485
+ * method. Every call returns the same client, so the server URL it fetches is reused.
486
+ *
487
+ * @returns The client for the server interface of this Actor
488
+ * @see https://docs.apify.com/platform/actors/running/standby
489
+ *
490
+ * @example
491
+ * ```javascript
492
+ * const response = await client.actor('username/actor-name').server().request('/search', {
493
+ * params: { q: 'apify' },
494
+ * });
495
+ * ```
496
+ */
497
+ server() {
498
+ this.#serverClient ??= new ActorServerClient({
499
+ baseUrl: this.baseUrl,
500
+ publicBaseUrl: this.publicBaseUrl,
501
+ apifyClient: this.apifyClient,
502
+ httpClient: this.httpClient,
503
+ id: this.id,
504
+ params: this.params,
505
+ });
506
+ return this.#serverClient;
507
+ }
508
+ /**
509
+ * Returns a client for the server interface of this Actor in Standby mode.
510
+ *
511
+ * Named after Actor Standby, the former name of Server Actors.
512
+ *
513
+ * @deprecated Use {@link server} instead. Will be removed in v4.
514
+ * @returns The client for the server interface of this Actor
515
+ * @see https://docs.apify.com/platform/actors/running/standby
516
+ */
517
+ standby() {
518
+ this.httpClient.logger.deprecated('`standby()` is deprecated and will be removed in v4. Use `server()` instead.');
519
+ return this.server();
520
+ }
478
521
  }
@@ -0,0 +1,149 @@
1
+ import type { ApiClientSubResourceOptions } from '../base/api_client.js';
2
+ import { ResourceClient } from '../base/resource_client.js';
3
+ import type { ApifyResponse, ApifyResponseType, HttpMethod } from '../http_clients/index.js';
4
+ import type { HttpCompressor } from '../http_compressors/base.js';
5
+ import type { HttpCompressionAlgorithm } from '../http_compressors/resolve.js';
6
+ import type { TimeoutOptions } from '../timeouts.js';
7
+ /**
8
+ * Client for the server interface of a specific Actor.
9
+ *
10
+ * Provides methods to work with the web server of a Server Actor, such as sending it requests or getting its OpenAPI
11
+ * specification. Get an instance with {@link ActorClient.server}.
12
+ *
13
+ * @example
14
+ * ```javascript
15
+ * const client = new ApifyClient({ token: 'my-token' });
16
+ * const actorServerClient = client.actor('username/actor-name').server();
17
+ *
18
+ * const response = await actorServerClient.request('/search', { params: { q: 'apify' } });
19
+ * console.log(response.data);
20
+ * ```
21
+ *
22
+ * @see https://docs.apify.com/platform/actors/running/standby
23
+ */
24
+ export declare class ActorServerClient extends ResourceClient {
25
+ #private;
26
+ /**
27
+ * @hidden
28
+ */
29
+ constructor(options: ApiClientSubResourceOptions);
30
+ /**
31
+ * Returns the URL of the Actor's server.
32
+ *
33
+ * The URL is the Actor's `standbyUrl`, fetched from the API by the first call of this method or
34
+ * {@link getOpenApiSpec} and reused by later calls on this client. Use it to call the server with another HTTP
35
+ * client, for example one generated from the server's OpenAPI specification.
36
+ *
37
+ * @param options - Request options
38
+ * @param options.timeoutSecs - Timeout for the API request. Default is `'short'`.
39
+ * @returns The URL of the Actor's server
40
+ * @throws {ApifyClientError} When the Actor is not a Server Actor.
41
+ * @throws {NotFoundError} When the Actor does not exist.
42
+ * @see https://docs.apify.com/platform/actors/running/standby
43
+ */
44
+ getUrl(options?: TimeoutOptions): Promise<string>;
45
+ /**
46
+ * Returns the OpenAPI specification of the Actor's server.
47
+ *
48
+ * The specification is the web server schema from the Actor's definition, taken from the build that serves the
49
+ * server interface: the build set in `actorStandby.build`, or `latest` if none is set. Use it to generate an HTTP
50
+ * client for the server, and point that client at the URL returned by {@link getUrl}.
51
+ *
52
+ * @param options - Request options
53
+ * @param options.timeoutSecs - Timeout for each API request. Default is `'short'`.
54
+ * @returns The OpenAPI specification of the Actor's server, or `undefined` if the Actor's definition doesn't
55
+ * include one
56
+ * @throws {ApifyClientError} When the Actor is not a Server Actor, or the build that serves its server interface
57
+ * doesn't exist.
58
+ * @throws {NotFoundError} When the Actor does not exist.
59
+ * @see https://docs.apify.com/platform/actors/development/actor-definition/web-server-schema
60
+ */
61
+ getOpenApiSpec(options?: TimeoutOptions): Promise<Record<string, unknown> | undefined>;
62
+ /**
63
+ * Sends an HTTP request to the Actor's server.
64
+ *
65
+ * The request goes to the URL returned by {@link getUrl} and carries the client's token in the
66
+ * `X-Apify-Authorization` header, which the platform consumes, so it never reaches the Actor's code. Headers you
67
+ * pass, `Authorization` included, reach the Actor's server as they are. The first request to an idle Actor waits
68
+ * for the platform to start a server run, which is why the timeout defaults to `'long'`.
69
+ *
70
+ * The method resolves to any response of the server, error statuses included. A rate-limit (429) or Service
71
+ * Unavailable (503) response is retried with the client's retry settings, and the last one is returned once the
72
+ * retries run out. The Actor's code can return these statuses too, and then it gets the request again. A redirect
73
+ * is returned as it is, since following it would send the token to a host the Actor's code picked. In a
74
+ * browser the redirect response can't be read, so the request fails with an {@link ApifyClientError} instead.
75
+ * Request bodies are sent uncompressed unless `compression` is set, since the Actor's server may not decode a
76
+ * compressed body.
77
+ *
78
+ * @template T - Type of the parsed response body.
79
+ * @param path - The path on the Actor's server, for example `/search`. It is always resolved against the server
80
+ * URL, so the request, and the token with it, can't be sent to another host. Pass the query in `params`. A
81
+ * fragment (`#...`) is dropped, since it's never sent to the server.
82
+ * @param options - Request options
83
+ * @param options.method - HTTP method of the request. Default is `'GET'`.
84
+ * @param options.params - Query parameters of the request, converted the same way as for API calls.
85
+ * @param options.headers - Additional headers of the request.
86
+ * @param options.data - Request body, serialized the same way as for API calls: a plain object or array is sent
87
+ * as JSON, and a string, binary value or stream (`Readable`, web `ReadableStream`) as it is.
88
+ * @param options.parentRequestId - The `X-Actor-Request-ID` header of the request your Server Actor is handling,
89
+ * sent on as the same header so the called Actor charges at that request's pricing tier.
90
+ * @param options.compression - Compression algorithm for the request body, as a name or an {@link HttpCompressor}.
91
+ * The body is compressed under the same conditions as for API calls. Set it only if the Actor's server decodes
92
+ * the resulting `Content-Encoding`.
93
+ * @param options.responseType - How to return the response body: `'parsed'` by its content type, `'buffer'` as
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'`.
96
+ * @param options.timeoutSecs - Timeout for the HTTP request. Default is `'long'`. With `'stream'`, it bounds the
97
+ * wait for the server to start responding.
98
+ * @returns The response of the Actor's server, with the body in the form `responseType` asks for. An error
99
+ * response whose body doesn't parse as its content type comes with the raw bytes in `data`.
100
+ * @throws {ApifyClientError} When the Actor is not a Server Actor.
101
+ * @throws {InvalidResponseBodyError} When a success response's body doesn't parse as its content type, with
102
+ * `responseType: 'parsed'`.
103
+ * @throws {NotFoundError} When the Actor does not exist.
104
+ * @see https://docs.apify.com/platform/actors/running/standby
105
+ */
106
+ request<T = any>(path?: string, options?: ActorServerRequestOptions & {
107
+ responseType?: 'parsed';
108
+ }): Promise<ApifyResponse<T>>;
109
+ request(path: string, options: ActorServerRequestOptions & {
110
+ responseType: 'buffer';
111
+ }): Promise<ApifyResponse<Uint8Array>>;
112
+ request(path: string, options: ActorServerRequestOptions & {
113
+ responseType: 'stream';
114
+ }): Promise<ApifyResponse<ReadableStream<Uint8Array>>>;
115
+ request(path?: string, options?: ActorServerRequestOptions): Promise<ApifyResponse>;
116
+ }
117
+ /**
118
+ * Options of {@link ActorServerClient.request}.
119
+ */
120
+ export interface ActorServerRequestOptions extends TimeoutOptions {
121
+ /** HTTP method of the request. @default 'GET' */
122
+ method?: HttpMethod;
123
+ /** Query parameters of the request, converted the same way as for API calls. */
124
+ params?: Record<string, unknown>;
125
+ /** Additional headers of the request. */
126
+ headers?: Record<string, string>;
127
+ /**
128
+ * Request body, serialized the same way as for API calls: a plain object or array is sent as JSON, and a string
129
+ * or binary value as it is.
130
+ */
131
+ data?: unknown;
132
+ /**
133
+ * The `X-Actor-Request-ID` header of the request your Server Actor is handling. It's sent on as the same header,
134
+ * so the called Actor charges at that request's pricing tier.
135
+ * @see https://docs.apify.com/platform/actors/development/programming-interface/standby#compose-server-actors
136
+ */
137
+ parentRequestId?: string;
138
+ /**
139
+ * Compression algorithm for the request body, as a name or an {@link HttpCompressor}. The body is sent
140
+ * uncompressed when it's not set, since the Actor's server may not decode a compressed body.
141
+ */
142
+ compression?: HttpCompressionAlgorithm | HttpCompressor;
143
+ /**
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.
146
+ * @default 'parsed'
147
+ */
148
+ responseType?: ApifyResponseType;
149
+ }
@@ -0,0 +1,195 @@
1
+ import { z } from 'zod';
2
+ import { ApifyClientError } from '../apify_client_error.js';
3
+ import { ResourceClient } from '../base/resource_client.js';
4
+ import { mergeHeaders } from '../http_clients/base.js';
5
+ import { compressionSchema, resolveCompressor } from '../http_compressors/resolve.js';
6
+ import * as schemas from '../schemas.js';
7
+ import { timeoutOptionsSchema, timeoutOptionsShape } from '../timeouts.js';
8
+ import { parseArgument, parseResponse } from '../utils.js';
9
+ import { BuildClient } from './build.js';
10
+ import { BuildCollectionClient } from './build_collection.js';
11
+ /**
12
+ * Statuses a server request is retried on. The platform answers with them when it can't pass a request to a server
13
+ * run, so a retry usually doesn't run the Actor's code again. An Actor that returns one itself gets the request again.
14
+ */
15
+ const SERVER_RETRY_STATUS_CODES = [429, 503];
16
+ const BUILD_NUMBER_PATTERN = /^(\d+)\.(\d+)\.(\d+)$/;
17
+ /**
18
+ * Splits a build number like `0.1.23` into its version and sequence number, or returns `undefined` for anything else.
19
+ */
20
+ function parseBuildNumber(buildNumber) {
21
+ const match = BUILD_NUMBER_PATTERN.exec(buildNumber ?? '');
22
+ if (!match)
23
+ return undefined;
24
+ return [Number(match[1]), Number(match[2]), Number(match[3])];
25
+ }
26
+ /**
27
+ * Returns whether `buildNumber` belongs to the same version as `target` and comes before it. Builds are listed newest
28
+ * first and the sequence numbers of a version grow over time, so meeting such a build means the target doesn't exist.
29
+ */
30
+ function isOlderBuild(buildNumber, target) {
31
+ const parsed = parseBuildNumber(buildNumber);
32
+ return parsed !== undefined && parsed[0] === target[0] && parsed[1] === target[1] && parsed[2] < target[2];
33
+ }
34
+ const requestOptionsSchema = z.strictObject({
35
+ method: z
36
+ .enum(['GET', 'HEAD', 'POST', 'PUT', 'DELETE', 'CONNECT', 'OPTIONS', 'TRACE', 'PATCH'])
37
+ .optional(),
38
+ params: z.record(z.string(), z.unknown()).optional(),
39
+ headers: z.record(z.string(), z.string()).optional(),
40
+ data: z.unknown().optional(),
41
+ parentRequestId: z.string().optional(),
42
+ compression: compressionSchema.optional(),
43
+ responseType: z.enum(['parsed', 'buffer', 'stream']).optional(),
44
+ ...timeoutOptionsShape,
45
+ });
46
+ /**
47
+ * Client for the server interface of a specific Actor.
48
+ *
49
+ * Provides methods to work with the web server of a Server Actor, such as sending it requests or getting its OpenAPI
50
+ * specification. Get an instance with {@link ActorClient.server}.
51
+ *
52
+ * @example
53
+ * ```javascript
54
+ * const client = new ApifyClient({ token: 'my-token' });
55
+ * const actorServerClient = client.actor('username/actor-name').server();
56
+ *
57
+ * const response = await actorServerClient.request('/search', { params: { q: 'apify' } });
58
+ * console.log(response.data);
59
+ * ```
60
+ *
61
+ * @see https://docs.apify.com/platform/actors/running/standby
62
+ */
63
+ export class ActorServerClient extends ResourceClient {
64
+ /**
65
+ * The server URL. Getting it takes an API call for the Actor, so it's cached for {@link getUrl} and
66
+ * {@link request}. It's pending while the first lookup runs, so concurrent first calls share one API request.
67
+ */
68
+ #url;
69
+ /**
70
+ * @hidden
71
+ */
72
+ constructor(options) {
73
+ super({
74
+ resourcePath: 'actors',
75
+ ...options,
76
+ });
77
+ }
78
+ /**
79
+ * Returns the URL of the Actor's server.
80
+ *
81
+ * The URL is the Actor's `standbyUrl`, fetched from the API by the first call of this method or
82
+ * {@link getOpenApiSpec} and reused by later calls on this client. Use it to call the server with another HTTP
83
+ * client, for example one generated from the server's OpenAPI specification.
84
+ *
85
+ * @param options - Request options
86
+ * @param options.timeoutSecs - Timeout for the API request. Default is `'short'`.
87
+ * @returns The URL of the Actor's server
88
+ * @throws {ApifyClientError} When the Actor is not a Server Actor.
89
+ * @throws {NotFoundError} When the Actor does not exist.
90
+ * @see https://docs.apify.com/platform/actors/running/standby
91
+ */
92
+ async getUrl(options = {}) {
93
+ const { timeoutSecs = 'short', signal } = parseArgument(options, timeoutOptionsSchema, 'TimeoutOptions');
94
+ const url = (this.#url ??= this.#getServerActor(timeoutSecs, signal).then((actor) => actor.standbyUrl));
95
+ try {
96
+ return await url;
97
+ }
98
+ catch (err) {
99
+ // A failed lookup is not kept, so the next call tries again.
100
+ if (this.#url === url)
101
+ this.#url = undefined;
102
+ throw err;
103
+ }
104
+ }
105
+ /**
106
+ * Returns the OpenAPI specification of the Actor's server.
107
+ *
108
+ * The specification is the web server schema from the Actor's definition, taken from the build that serves the
109
+ * server interface: the build set in `actorStandby.build`, or `latest` if none is set. Use it to generate an HTTP
110
+ * client for the server, and point that client at the URL returned by {@link getUrl}.
111
+ *
112
+ * @param options - Request options
113
+ * @param options.timeoutSecs - Timeout for each API request. Default is `'short'`.
114
+ * @returns The OpenAPI specification of the Actor's server, or `undefined` if the Actor's definition doesn't
115
+ * include one
116
+ * @throws {ApifyClientError} When the Actor is not a Server Actor, or the build that serves its server interface
117
+ * doesn't exist.
118
+ * @throws {NotFoundError} When the Actor does not exist.
119
+ * @see https://docs.apify.com/platform/actors/development/actor-definition/web-server-schema
120
+ */
121
+ async getOpenApiSpec(options = {}) {
122
+ const { timeoutSecs = 'short', signal } = parseArgument(options, timeoutOptionsSchema, 'TimeoutOptions');
123
+ const actor = await this.#getServerActor(timeoutSecs, signal);
124
+ const buildRef = actor.actorStandby?.build || 'latest';
125
+ let buildId = actor.taggedBuilds?.[buildRef]?.buildId ?? undefined;
126
+ const targetBuildNumber = parseBuildNumber(buildRef);
127
+ if (buildId === undefined && targetBuildNumber !== undefined) {
128
+ // Not a tag, so look `buildRef` up as a build number, which the API can't resolve directly.
129
+ const builds = new BuildCollectionClient(this.subResourceOptions({ resourcePath: 'builds' }));
130
+ for await (const build of builds.list({ desc: true, timeoutSecs, signal })) {
131
+ if (build.buildNumber === buildRef) {
132
+ buildId = build.id;
133
+ break;
134
+ }
135
+ if (isOlderBuild(build.buildNumber, targetBuildNumber))
136
+ break;
137
+ }
138
+ }
139
+ const build = buildId === undefined
140
+ ? undefined
141
+ : await new BuildClient({
142
+ baseUrl: this.apifyClient.baseUrl,
143
+ publicBaseUrl: this.apifyClient.publicBaseUrl,
144
+ httpClient: this.httpClient,
145
+ apifyClient: this.apifyClient,
146
+ id: buildId,
147
+ }).get({ timeoutSecs, signal });
148
+ if (build === undefined) {
149
+ throw new ApifyClientError(`Build ${buildRef} of Actor ${this.id} does not exist.`);
150
+ }
151
+ return build.actorDefinition?.webServerSchema;
152
+ }
153
+ async request(path = '/', options = {}) {
154
+ parseArgument(path, z.string());
155
+ const { method = 'GET', params, headers, data, parentRequestId, compression, responseType, timeoutSecs = 'long', signal, } = parseArgument(options, requestOptionsSchema, 'ActorServerRequestOptions');
156
+ const serverUrl = await this.getUrl({ signal });
157
+ const serverPath = path.split('#')[0].replace(/^\/+/, '');
158
+ return this.httpClient.call({
159
+ url: `${serverUrl.replace(/\/+$/, '')}/${serverPath}`,
160
+ method,
161
+ params,
162
+ headers: parentRequestId === undefined
163
+ ? headers
164
+ : mergeHeaders(headers ?? {}, { 'X-Actor-Request-ID': parentRequestId }),
165
+ data,
166
+ compression: compression === undefined ? false : resolveCompressor(compression),
167
+ authorizationHeader: 'X-Apify-Authorization',
168
+ throwOnErrorStatus: false,
169
+ retryStatusCodes: SERVER_RETRY_STATUS_CODES,
170
+ retryTransportErrors: false,
171
+ followRedirects: false,
172
+ responseType,
173
+ timeoutSecs,
174
+ signal,
175
+ });
176
+ }
177
+ /**
178
+ * Fetches the Actor, checks that it is a Server Actor, and caches its server URL.
179
+ */
180
+ async #getServerActor(timeoutSecs, signal) {
181
+ const response = await this.httpClient.call({
182
+ url: this.buildUrl(),
183
+ method: 'GET',
184
+ params: this.buildParams(),
185
+ timeoutSecs,
186
+ signal,
187
+ });
188
+ const actor = parseResponse(response, schemas.ActorResource());
189
+ if (!actor.standbyUrl) {
190
+ throw new ApifyClientError(`Actor ${this.id} is not a Server Actor.`);
191
+ }
192
+ this.#url = Promise.resolve(actor.standbyUrl);
193
+ return actor;
194
+ }
195
+ }
@@ -46,7 +46,8 @@ export declare class ActorVersionClient extends ResourceClient {
46
46
  *
47
47
  * @param newFields - Fields to update.
48
48
  * @param options - Request options
49
- * @param options.timeoutSecs - Timeout for the API request. Default is `'short'`.
49
+ * @param options.timeoutSecs - Timeout for the API request. Default is `'long'`, since the version can carry
50
+ * its source files.
50
51
  * @returns The updated Actor version object.
51
52
  * @see https://docs.apify.com/api/v2/act-version-put
52
53
  */
@@ -83,5 +84,10 @@ export declare class ActorVersionClient extends ResourceClient {
83
84
  * All of them are optional, because the endpoint leaves untouched whatever the payload does not
84
85
  * mention. The version union enforces the pairing: a `sourceType` can only be sent next to the
85
86
  * source location it implies, never next to one of the other three.
87
+ *
88
+ * On a `SOURCE_FILES` or `TARBALL` version, `actorPath: null` removes the stored path. So does an
89
+ * update that sends `sourceType`, `sourceFiles`, or `tarballUrl` without `actorPath`, so send it
90
+ * again with every upload. The API rejects an `actorPath` on a version of any other source type,
91
+ * also when the update leaves out `sourceType`, because it then checks the stored source type.
86
92
  */
87
93
  export type ActorVersionUpdateData = Partial<Version>;
@@ -55,13 +55,14 @@ export class ActorVersionClient extends ResourceClient {
55
55
  *
56
56
  * @param newFields - Fields to update.
57
57
  * @param options - Request options
58
- * @param options.timeoutSecs - Timeout for the API request. Default is `'short'`.
58
+ * @param options.timeoutSecs - Timeout for the API request. Default is `'long'`, since the version can carry
59
+ * its source files.
59
60
  * @returns The updated Actor version object.
60
61
  * @see https://docs.apify.com/api/v2/act-version-put
61
62
  */
62
63
  async update(newFields, options = {}) {
63
64
  parseArgument(newFields, anyObjectSchema);
64
- const { timeoutSecs = 'short', signal } = parseArgument(options, timeoutOptionsSchema, 'TimeoutOptions');
65
+ const { timeoutSecs = 'long', signal } = parseArgument(options, timeoutOptionsSchema, 'TimeoutOptions');
65
66
  return this.updateResource(schemas.Version(), newFields, timeoutSecs, signal);
66
67
  }
67
68
  /**
@@ -60,7 +60,8 @@ export declare class ActorVersionCollectionClient extends ResourceCollectionClie
60
60
  *
61
61
  * @param actorVersion - The Actor version data.
62
62
  * @param options - Request options
63
- * @param options.timeoutSecs - Timeout for the API request. Default is `'short'`.
63
+ * @param options.timeoutSecs - Timeout for the API request. Default is `'long'`, since the version can carry
64
+ * its source files.
64
65
  * @returns The created Actor version object.
65
66
  * @see https://docs.apify.com/api/v2/act-versions-post
66
67
  */
@@ -68,13 +68,14 @@ export class ActorVersionCollectionClient extends ResourceCollectionClient {
68
68
  *
69
69
  * @param actorVersion - The Actor version data.
70
70
  * @param options - Request options
71
- * @param options.timeoutSecs - Timeout for the API request. Default is `'short'`.
71
+ * @param options.timeoutSecs - Timeout for the API request. Default is `'long'`, since the version can carry
72
+ * its source files.
72
73
  * @returns The created Actor version object.
73
74
  * @see https://docs.apify.com/api/v2/act-versions-post
74
75
  */
75
76
  async create(actorVersion, options = {}) {
76
77
  parseArgument(actorVersion, actorVersionSchema);
77
- const { timeoutSecs = 'short', signal } = parseArgument(options, timeoutOptionsSchema, 'TimeoutOptions');
78
+ const { timeoutSecs = 'long', signal } = parseArgument(options, timeoutOptionsSchema, 'TimeoutOptions');
78
79
  return this.createResource(schemas.Version(), actorVersion, timeoutSecs, signal);
79
80
  }
80
81
  }
@@ -89,6 +89,7 @@ export declare class DatasetClient<Data extends Record<string | number, any> = R
89
89
  * @param options - Options for listing items
90
90
  * @param options.limit - Maximum number of items to return. Default is all items.
91
91
  * @param options.chunkSize - Maximum number of items returned in one API response. Relevant in the context of asyncIterator.
92
+ * Without it, iteration loads the whole dataset, or all `limit` items, in one response.
92
93
  * @param options.offset - Number of items to skip from the beginning. Default is 0.
93
94
  * @param options.desc - If `true`, items are returned in descending order (newest first). Default is `false`.
94
95
  * @param options.fields - Array of field names to include in the results. Omits all other fields.
@@ -130,7 +131,12 @@ export declare class DatasetClient<Data extends Record<string | number, any> = R
130
131
  *
131
132
  * Unlike {@link listItems} which returns a {@link PaginatedList} with an array of individual
132
133
  * dataset items, this method returns the items serialized to the provided format
133
- * (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.
135
+ *
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.
134
140
  *
135
141
  * @param format - Output format: `'json'`, `'jsonl'`, `'csv'`, `'xlsx'`, `'xml'`, `'rss'`, or `'html'`
136
142
  * @param options - Download and formatting options (extends all options from {@link listItems})
@@ -142,8 +148,12 @@ export declare class DatasetClient<Data extends Record<string | number, any> = R
142
148
  * @param options.xmlRow - Name of the XML element for each item. Default is `'item'`.
143
149
  * @param options.fields - Array of field names to include in the export.
144
150
  * @param options.omit - Array of field names to exclude from the export.
145
- * @param options.timeoutSecs - Timeout for the API request. Default is `'long'`.
146
- * @returns Buffer containing the serialized data in the specified format
151
+ * @param options.stream - If `true`, the items are returned as a web ReadableStream.
152
+ * @param options.timeoutSecs - Timeout for the API request. Default is `'long'`. With `stream`, it bounds the
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`
147
157
  * @see https://docs.apify.com/api/v2/dataset-items-get
148
158
  *
149
159
  * @example
@@ -164,9 +174,21 @@ export declare class DatasetClient<Data extends Record<string | number, any> = R
164
174
  * xmlRoot: 'products',
165
175
  * xmlRow: 'product'
166
176
  * });
177
+ *
178
+ * // Stream a CSV export straight to a file
179
+ * const { createWriteStream } = require('node:fs');
180
+ * const { pipeline } = require('node:stream/promises');
181
+ * const stream = await client.dataset('my-dataset').downloadItems('csv', { stream: true });
182
+ * await pipeline(stream, createWriteStream('output.csv'));
167
183
  * ```
168
184
  */
169
- downloadItems(format: `${DownloadItemsFormat}`, options?: DatasetClientDownloadItemsOptions): Promise<Buffer>;
185
+ downloadItems(format: `${DownloadItemsFormat}`, options?: DatasetClientDownloadItemsOptions & {
186
+ stream?: false;
187
+ }): Promise<Uint8Array>;
188
+ downloadItems(format: `${DownloadItemsFormat}`, options: DatasetClientDownloadItemsOptions & {
189
+ stream: true;
190
+ }): Promise<ReadableStream<Uint8Array>>;
191
+ downloadItems(format: `${DownloadItemsFormat}`, options?: DatasetClientDownloadItemsOptions): Promise<Uint8Array | ReadableStream<Uint8Array>>;
170
192
  /**
171
193
  * Stores one or more items into the dataset.
172
194
  *
@@ -221,7 +243,8 @@ export declare class DatasetClient<Data extends Record<string | number, any> = R
221
243
  * This is useful for sharing dataset results with external services or users.
222
244
  *
223
245
  * @param options - URL generation options (extends all options from {@link listItems})
224
- * @param options.expiresInSecs - Number of seconds until the signed URL expires. If omitted, the URL never expires.
246
+ * @param options.expiresInSecs - Number of seconds until the signed URL expires. Must be positive. If omitted, the URL
247
+ * never expires.
225
248
  * @param options.fields - Array of field names to include in the response.
226
249
  * @param options.format - Format of the items served by the URL. Defaults to `json`.
227
250
  * @param options.limit - Maximum number of items to return.
@@ -318,4 +341,9 @@ export interface DatasetClientDownloadItemsOptions extends Omit<DatasetClientLis
318
341
  skipHeaderRow?: boolean;
319
342
  xmlRoot?: string;
320
343
  xmlRow?: string;
344
+ /**
345
+ * If `true`, the items are returned as a web ReadableStream.
346
+ * @default false
347
+ */
348
+ stream?: boolean;
321
349
  }