apify-client 3.0.0-beta.1 → 3.0.0-beta.100

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 (131) hide show
  1. package/README.md +21 -5
  2. package/dist/apify_api_error.d.ts +64 -22
  3. package/dist/apify_api_error.js +100 -30
  4. package/dist/apify_client.d.ts +150 -35
  5. package/dist/apify_client.js +198 -118
  6. package/dist/apify_client_error.d.ts +10 -0
  7. package/dist/apify_client_error.js +10 -0
  8. package/dist/base/api_client.d.ts +9 -9
  9. package/dist/base/api_client.js +41 -45
  10. package/dist/base/resource_client.d.ts +24 -10
  11. package/dist/base/resource_client.js +78 -48
  12. package/dist/base/resource_collection_client.d.ts +15 -6
  13. package/dist/base/resource_collection_client.js +40 -21
  14. package/dist/body_parser.d.ts +3 -4
  15. package/dist/body_parser.js +20 -32
  16. package/dist/bundle.js +47 -52
  17. package/dist/bundle.js.map +1 -1
  18. package/dist/generated/api.d.ts +3363 -1185
  19. package/dist/generated/api.js +1 -2
  20. package/dist/generated/schemas.d.ts +8146 -0
  21. package/dist/generated/schemas.js +1866 -0
  22. package/dist/http_clients/axios.d.ts +61 -0
  23. package/dist/http_clients/axios.js +119 -0
  24. package/dist/http_clients/base.d.ts +391 -0
  25. package/dist/http_clients/base.js +650 -0
  26. package/dist/http_clients/index.d.ts +4 -0
  27. package/dist/http_clients/index.js +2 -0
  28. package/dist/http_compressors/base.d.ts +40 -0
  29. package/dist/http_compressors/base.js +9 -0
  30. package/dist/http_compressors/brotli.d.ts +33 -0
  31. package/dist/http_compressors/brotli.js +39 -0
  32. package/dist/http_compressors/gzip.d.ts +33 -0
  33. package/dist/http_compressors/gzip.js +39 -0
  34. package/dist/http_compressors/index.d.ts +8 -0
  35. package/dist/http_compressors/index.js +3 -0
  36. package/dist/http_compressors/resolve.d.ts +24 -0
  37. package/dist/http_compressors/resolve.js +30 -0
  38. package/dist/http_compressors/zstd.d.ts +34 -0
  39. package/dist/http_compressors/zstd.js +43 -0
  40. package/dist/index.d.ts +38 -32
  41. package/dist/index.js +36 -36
  42. package/dist/invalid_response_body_error.d.ts +14 -0
  43. package/dist/invalid_response_body_error.js +18 -0
  44. package/dist/lazy_schema.d.ts +8 -0
  45. package/dist/lazy_schema.js +11 -0
  46. package/dist/models.d.ts +196 -278
  47. package/dist/models.js +14 -15
  48. package/dist/resource_clients/actor.d.ts +115 -45
  49. package/dist/resource_clients/actor.js +187 -116
  50. package/dist/resource_clients/actor_collection.d.ts +21 -17
  51. package/dist/resource_clients/actor_collection.js +26 -21
  52. package/dist/resource_clients/actor_env_var.d.ts +13 -6
  53. package/dist/resource_clients/actor_env_var.js +21 -14
  54. package/dist/resource_clients/actor_env_var_collection.d.ts +18 -22
  55. package/dist/resource_clients/actor_env_var_collection.js +23 -20
  56. package/dist/resource_clients/actor_server.d.ts +149 -0
  57. package/dist/resource_clients/actor_server.js +199 -0
  58. package/dist/resource_clients/actor_version.d.ts +30 -10
  59. package/dist/resource_clients/actor_version.js +29 -23
  60. package/dist/resource_clients/actor_version_collection.d.ts +20 -21
  61. package/dist/resource_clients/actor_version_collection.js +25 -20
  62. package/dist/resource_clients/build.d.ts +24 -11
  63. package/dist/resource_clients/build.js +43 -26
  64. package/dist/resource_clients/build_collection.d.ts +10 -8
  65. package/dist/resource_clients/build_collection.js +13 -13
  66. package/dist/resource_clients/dataset.d.ts +87 -40
  67. package/dist/resource_clients/dataset.js +159 -175
  68. package/dist/resource_clients/dataset_collection.d.ts +13 -9
  69. package/dist/resource_clients/dataset_collection.js +29 -21
  70. package/dist/resource_clients/key_value_store.d.ts +110 -28
  71. package/dist/resource_clients/key_value_store.js +177 -99
  72. package/dist/resource_clients/key_value_store_collection.d.ts +13 -9
  73. package/dist/resource_clients/key_value_store_collection.js +29 -21
  74. package/dist/resource_clients/log.d.ts +42 -23
  75. package/dist/resource_clients/log.js +156 -85
  76. package/dist/resource_clients/request_queue.d.ts +77 -38
  77. package/dist/resource_clients/request_queue.js +251 -172
  78. package/dist/resource_clients/request_queue_collection.d.ts +12 -8
  79. package/dist/resource_clients/request_queue_collection.js +23 -20
  80. package/dist/resource_clients/run.d.ts +134 -34
  81. package/dist/resource_clients/run.js +225 -84
  82. package/dist/resource_clients/run_collection.d.ts +8 -6
  83. package/dist/resource_clients/run_collection.js +18 -18
  84. package/dist/resource_clients/schedule.d.ts +20 -11
  85. package/dist/resource_clients/schedule.js +36 -30
  86. package/dist/resource_clients/schedule_collection.d.ts +10 -6
  87. package/dist/resource_clients/schedule_collection.js +20 -17
  88. package/dist/resource_clients/store_collection.d.ts +9 -7
  89. package/dist/resource_clients/store_collection.js +18 -18
  90. package/dist/resource_clients/task.d.ts +44 -21
  91. package/dist/resource_clients/task.js +116 -86
  92. package/dist/resource_clients/task_collection.d.ts +13 -9
  93. package/dist/resource_clients/task_collection.js +19 -16
  94. package/dist/resource_clients/user.d.ts +22 -13
  95. package/dist/resource_clients/user.js +46 -47
  96. package/dist/resource_clients/webhook.d.ts +21 -12
  97. package/dist/resource_clients/webhook.js +35 -30
  98. package/dist/resource_clients/webhook_collection.d.ts +11 -7
  99. package/dist/resource_clients/webhook_collection.js +20 -17
  100. package/dist/resource_clients/webhook_dispatch.d.ts +9 -6
  101. package/dist/resource_clients/webhook_dispatch.js +11 -10
  102. package/dist/resource_clients/webhook_dispatch_collection.d.ts +7 -5
  103. package/dist/resource_clients/webhook_dispatch_collection.js +13 -13
  104. package/dist/response_validation_error.d.ts +27 -0
  105. package/dist/response_validation_error.js +38 -0
  106. package/dist/runtime/node.d.ts +6 -0
  107. package/dist/runtime/node.js +87 -0
  108. package/dist/runtime/types.d.ts +60 -0
  109. package/dist/runtime/types.js +1 -0
  110. package/dist/runtime/web.d.ts +5 -0
  111. package/dist/runtime/web.js +21 -0
  112. package/dist/schemas.d.ts +381 -0
  113. package/dist/schemas.js +37 -0
  114. package/dist/statistics.d.ts +1 -6
  115. package/dist/statistics.js +7 -11
  116. package/dist/timeouts.d.ts +84 -0
  117. package/dist/timeouts.js +37 -0
  118. package/dist/timezones.d.ts +1 -1
  119. package/dist/timezones.js +1 -2
  120. package/dist/utils.d.ts +99 -70
  121. package/dist/utils.js +251 -229
  122. package/dist/wait_for_resources.d.ts +8 -0
  123. package/dist/wait_for_resources.js +39 -0
  124. package/package.json +48 -47
  125. package/dist/argument_validation_error.d.ts +0 -17
  126. package/dist/argument_validation_error.js +0 -157
  127. package/dist/http_client.d.ts +0 -88
  128. package/dist/http_client.js +0 -260
  129. package/dist/index.mjs +0 -42
  130. package/dist/interceptors.d.ts +0 -19
  131. package/dist/interceptors.js +0 -110
package/README.md CHANGED
@@ -15,6 +15,7 @@ automatic retries and convenience functions that improve the experience of using
15
15
  - [Features](#features)
16
16
  - [Automatic parsing and error handling](#automatic-parsing-and-error-handling)
17
17
  - [Retries with exponential backoff](#retries-with-exponential-backoff)
18
+ - [Server Actors](#server-actors)
18
19
  - [Convenience functions and options](#convenience-functions-and-options)
19
20
  - [Usage concepts](#usage-concepts)
20
21
  - [Nested clients](#nested-clients)
@@ -26,7 +27,7 @@ automatic retries and convenience functions that improve the experience of using
26
27
  ## Quick Start
27
28
 
28
29
  ```js
29
- const { ApifyClient } = require('apify-client');
30
+ import { ApifyClient } from 'apify-client';
30
31
 
31
32
  const client = new ApifyClient({
32
33
  token: 'MY-APIFY-TOKEN',
@@ -47,7 +48,9 @@ Besides greatly simplifying the process of querying the Apify API, the client pr
47
48
  Based on the endpoint, the client automatically extracts the relevant data and returns it in the
48
49
  expected format. Date strings are automatically converted to `Date` objects. For exceptions,
49
50
  we throw an `ApifyApiError`, which wraps the plain JSON errors returned by API and enriches
50
- them with other context for easier debugging.
51
+ them with other context for easier debugging. The error is an instance of the subclass matching the
52
+ HTTP status code, such as `NotFoundError` or `RateLimitError`, so a `catch` block can tell them apart
53
+ with `instanceof`.
51
54
 
52
55
  ### Retries with exponential backoff
53
56
 
@@ -57,6 +60,17 @@ By default, it will retry up to 8 times. First retry will be attempted after ~50
57
60
  and so on. You can configure those parameters using the `maxRetries` and `minDelayBetweenRetriesMillis`
58
61
  options of the `ApifyClient` constructor.
59
62
 
63
+ ### Pluggable HTTP client
64
+
65
+ The client ships with an axios-based HTTP client and accepts a custom one. Extend `HttpClient`, implement
66
+ `sendRequest()` over the HTTP library of your choice and plug it in with `ApifyClient.withCustomHttpClient()`. The
67
+ custom client inherits the retries, timeouts, compression and error handling of the built-in one.
68
+
69
+ ### Server Actors
70
+
71
+ `client.actor(id).server()` returns a client for a Server Actor (formerly Actor Standby). It sends HTTP requests to
72
+ the Actor's web server with your token, and returns the server's URL and OpenAPI specification.
73
+
60
74
  ### Convenience functions and options
61
75
 
62
76
  Some actions can't be performed by the API itself, such as indefinite waiting for an actor run to finish
@@ -72,7 +86,7 @@ resources are created. There are two types of those clients. A client for manage
72
86
  resource and a client for a collection of resources.
73
87
 
74
88
  ```js
75
- const { ApifyClient } = require('apify-client');
89
+ import { ApifyClient } from 'apify-client';
76
90
  const apifyClient = new ApifyClient({ token: 'my-token' });
77
91
 
78
92
  // Collection clients do not require a parameter.
@@ -143,13 +157,15 @@ property to get only a subset of results. Other props are also available, depend
143
157
 
144
158
  ## Bundled environments
145
159
 
146
- The package includes a pre-built browser bundle that is automatically resolved by bundlers targeting browser environments. You can also import it explicitly via
160
+ The package includes a pre-built browser bundle that bundlers targeting browsers resolve automatically. You can also import it explicitly:
147
161
 
148
162
  ```typescript
149
163
  import { ApifyClient } from 'apify-client/browser';
150
164
  ```
151
165
 
152
- For edge runtimes like Cloudflare Workers, you may need to enable Node compatibility (e.g. `node_compat = true` in `wrangler.toml`). Note that some Node-specific features (streaming, proxy support) are not available in the bundle.
166
+ Only two parts of the client need Node.js built-ins: the HTTP agents and request compression. The `node` condition selects the Node.js implementation of those, and every other target gets one built on Web APIs. Log streaming, proxy support, and request compression are only available in Node.js.
167
+
168
+ For details, see [Bundled environments](https://docs.apify.com/api/client/js/docs/concepts/bundled-environments).
153
169
 
154
170
  ## API Reference
155
171
 
@@ -1,16 +1,29 @@
1
- import type { AxiosResponse } from 'axios';
1
+ import type { LiteralUnion } from 'type-fest';
2
+ import { ApifyClientError } from './apify_client_error.js';
3
+ import type { ApifyResponse } from './http_clients/base.js';
4
+ import type { ErrorType } from './models.js';
5
+ export type { ErrorType } from './models.js';
2
6
  /**
3
7
  * An `ApifyApiError` is thrown for successful HTTP requests that reach the API,
4
8
  * but the API responds with an error response. Typically, those are rate limit
5
9
  * errors and internal errors, which are automatically retried, or validation
6
10
  * errors, which are thrown immediately, because a correction by the user is
7
11
  * needed.
12
+ *
13
+ * The thrown error is an instance of the subclass matching the HTTP status code of the response:
14
+ * {@link InvalidRequestError} (400), {@link UnauthorizedError} (401), {@link ForbiddenError} (403),
15
+ * {@link NotFoundError} (404), {@link ConflictError} (409), {@link RateLimitError} (429) or
16
+ * {@link ServerError} (5xx). Any other status code is thrown as a plain `ApifyApiError`. Every
17
+ * subclass extends `ApifyApiError`, so `instanceof ApifyApiError` matches all of them. Errors that
18
+ * share a status code are told apart by their `type`.
8
19
  */
9
- export declare class ApifyApiError extends Error {
20
+ export declare class ApifyApiError extends ApifyClientError {
21
+ #private;
10
22
  name: string;
11
23
  /**
12
- * The invoked resource client and the method. Known issue: Sometimes it displays
13
- * as `unknown` because it can't be parsed from a stack trace.
24
+ * The resource client and the method parsed from the stack trace, such as `ActorClient.getResource`. A public
25
+ * method that delegates to a shared helper of its class is reported under the helper. The value is `unknown`
26
+ * when the stack trace cannot be parsed.
14
27
  */
15
28
  clientMethod: string;
16
29
  /**
@@ -18,9 +31,10 @@ export declare class ApifyApiError extends Error {
18
31
  */
19
32
  statusCode: number;
20
33
  /**
21
- * The type of the error, as returned by the API.
34
+ * The type of the error, as returned by the API. Typed as the known {@link ErrorType}
35
+ * values for autocompletion, while still accepting any string the API may return.
22
36
  */
23
- type?: string;
37
+ type?: LiteralUnion<ErrorType, string>;
24
38
  /**
25
39
  * Number of the API call attempt.
26
40
  */
@@ -45,22 +59,50 @@ export declare class ApifyApiError extends Error {
45
59
  /**
46
60
  * @hidden
47
61
  */
48
- constructor(response: AxiosResponse, attempt: number);
49
- private _safelyParsePathFromResponse;
50
- private _extractClientAndMethodFromStack;
62
+ constructor(response: ApifyResponse, attempt: number);
51
63
  /**
52
- * Creates a better looking and more informative stack that will be printed
53
- * out when API errors are thrown.
54
- *
55
- * Example:
56
- *
57
- * ApifyApiError: Actor task was not found
58
- * clientMethod: TaskClient.start
59
- * statusCode: 404
60
- * type: record-not-found
61
- * attempt: 1
62
- * httpMethod: post
63
- * path: /v2/actor-tasks/user~my-task/runs
64
+ * Creates the error for a failed response as an instance of the subclass matching its HTTP status code.
65
+ * @hidden
64
66
  */
65
- private _createApiStack;
67
+ static fromResponse(response: ApifyResponse, attempt: number): ApifyApiError;
68
+ }
69
+ /**
70
+ * Thrown when the Apify API responds with HTTP 400 Bad Request, typically because the request
71
+ * failed validation.
72
+ */
73
+ export declare class InvalidRequestError extends ApifyApiError {
74
+ }
75
+ /**
76
+ * Thrown when the Apify API responds with HTTP 401 Unauthorized, because the token is missing
77
+ * or invalid.
78
+ */
79
+ export declare class UnauthorizedError extends ApifyApiError {
80
+ }
81
+ /**
82
+ * Thrown when the Apify API responds with HTTP 403 Forbidden, because the token lacks the
83
+ * permission for the operation.
84
+ */
85
+ export declare class ForbiddenError extends ApifyApiError {
86
+ }
87
+ /**
88
+ * Thrown when the Apify API responds with HTTP 404 Not Found.
89
+ */
90
+ export declare class NotFoundError extends ApifyApiError {
91
+ }
92
+ /**
93
+ * Thrown when the Apify API responds with HTTP 409 Conflict.
94
+ */
95
+ export declare class ConflictError extends ApifyApiError {
96
+ }
97
+ /**
98
+ * Thrown when the Apify API responds with HTTP 429 Too Many Requests. The client retries such
99
+ * requests, so the error surfaces once the retries are exhausted.
100
+ */
101
+ export declare class RateLimitError extends ApifyApiError {
102
+ }
103
+ /**
104
+ * Thrown when the Apify API responds with an HTTP 5xx status. The client retries such requests,
105
+ * so the error surfaces once the retries are exhausted.
106
+ */
107
+ export declare class ServerError extends ApifyApiError {
66
108
  }
@@ -1,30 +1,42 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.ApifyApiError = void 0;
4
- const body_parser_1 = require("./body_parser");
5
- const utils_1 = require("./utils");
1
+ import { ApifyClientError } from './apify_client_error.js';
2
+ import { isBuffer } from './utils.js';
6
3
  /**
7
- * Examples of capturing groups for "...at ActorCollectionClient._list (/Users/..."
8
- * 0: "at ActorCollectionClient._list ("
4
+ * Examples of capturing groups for "...at ActorCollectionClient.listResources (/Users/..."
5
+ * 0: "at ActorCollectionClient.listResources ("
9
6
  * 1: undefined
10
7
  * 2: "ActorCollectionClient"
11
8
  * 3: undefined
12
- * 4: "list"
9
+ * 4: "listResources"
10
+ *
11
+ * The error is created inside the HTTP client's pipeline, whose frames sit above the resource client's. The
12
+ * pipeline's own methods are private, so V8 prints them with a `#` that no method name can match. Its public
13
+ * `call()` prints under the name of the transport's class, which can be anything, so the lookaheads skip a class
14
+ * named after `HttpClient` and the method `call`. A transport named `SomethingClient` whose `call()` override
15
+ * awaits a helper of its own is reported under that helper. `ActorClient.call()` and `TaskClient.call()` reach the
16
+ * pipeline through `start()`, whose frame sits closer to the error and matches first.
13
17
  * @private
14
18
  */
15
- const CLIENT_METHOD_REGEX = /at( async)? ([A-Za-z]+(Collection)?Client)\._?([A-Za-z]+) \(/;
19
+ const CLIENT_METHOD_REGEX = /at( async)? (?![A-Za-z]*HttpClient\.)([A-Za-z]+(Collection)?Client)\.(?!call \()([A-Za-z]+) \(/;
16
20
  /**
17
21
  * An `ApifyApiError` is thrown for successful HTTP requests that reach the API,
18
22
  * but the API responds with an error response. Typically, those are rate limit
19
23
  * errors and internal errors, which are automatically retried, or validation
20
24
  * errors, which are thrown immediately, because a correction by the user is
21
25
  * needed.
26
+ *
27
+ * The thrown error is an instance of the subclass matching the HTTP status code of the response:
28
+ * {@link InvalidRequestError} (400), {@link UnauthorizedError} (401), {@link ForbiddenError} (403),
29
+ * {@link NotFoundError} (404), {@link ConflictError} (409), {@link RateLimitError} (429) or
30
+ * {@link ServerError} (5xx). Any other status code is thrown as a plain `ApifyApiError`. Every
31
+ * subclass extends `ApifyApiError`, so `instanceof ApifyApiError` matches all of them. Errors that
32
+ * share a status code are told apart by their `type`.
22
33
  */
23
- class ApifyApiError extends Error {
34
+ export class ApifyApiError extends ApifyClientError {
24
35
  name;
25
36
  /**
26
- * The invoked resource client and the method. Known issue: Sometimes it displays
27
- * as `unknown` because it can't be parsed from a stack trace.
37
+ * The resource client and the method parsed from the stack trace, such as `ActorClient.getResource`. A public
38
+ * method that delegates to a shared helper of its class is reported under the helper. The value is `unknown`
39
+ * when the stack trace cannot be parsed.
28
40
  */
29
41
  clientMethod;
30
42
  /**
@@ -32,7 +44,8 @@ class ApifyApiError extends Error {
32
44
  */
33
45
  statusCode;
34
46
  /**
35
- * The type of the error, as returned by the API.
47
+ * The type of the error, as returned by the API. Typed as the known {@link ErrorType}
48
+ * values for autocompletion, while still accepting any string the API may return.
36
49
  */
37
50
  type;
38
51
  /**
@@ -64,14 +77,16 @@ class ApifyApiError extends Error {
64
77
  let type;
65
78
  let responseData = response.data;
66
79
  let errorData;
67
- // Some methods (e.g. downloadItems) set up forceBuffer on request response. If this request failed
68
- // the body buffer needs to parse to get the correct error.
69
- if ((0, utils_1.isBuffer)(responseData)) {
80
+ // A `responseType: 'buffer'` request (e.g. `downloadItems()`) and a failed streaming request, whose body
81
+ // `HttpClient` has read into a buffer, both arrive unparsed. Parse the body here to get at the error.
82
+ if (isBuffer(responseData)) {
83
+ const body = new TextDecoder().decode(response.data);
70
84
  try {
71
- responseData = JSON.parse((0, body_parser_1.isomorphicBufferToString)(response.data, 'utf-8'));
85
+ responseData = JSON.parse(body);
72
86
  }
73
87
  catch {
74
- // This can happen. The data in the response body are malformed.
88
+ // A body that is not JSON at all, such as an HTML error page from a proxy, is kept as text.
89
+ responseData = body;
75
90
  }
76
91
  }
77
92
  if (responseData && responseData.error) {
@@ -92,18 +107,26 @@ class ApifyApiError extends Error {
92
107
  }
93
108
  super(message);
94
109
  this.name = this.constructor.name;
95
- this.clientMethod = this._extractClientAndMethodFromStack();
110
+ this.clientMethod = this.#extractClientAndMethodFromStack();
96
111
  this.statusCode = response.status;
97
112
  this.type = type;
98
113
  this.attempt = attempt;
99
114
  this.httpMethod = response.config?.method;
100
- this.path = this._safelyParsePathFromResponse(response);
115
+ this.path = this.#safelyParsePathFromResponse(response);
101
116
  const stack = this.stack;
102
117
  this.originalStack = stack.slice(stack.indexOf('\n'));
103
- this.stack = this._createApiStack();
118
+ this.stack = this.#createApiStack();
104
119
  this.data = errorData;
105
120
  }
106
- _safelyParsePathFromResponse(response) {
121
+ /**
122
+ * Creates the error for a failed response as an instance of the subclass matching its HTTP status code.
123
+ * @hidden
124
+ */
125
+ static fromResponse(response, attempt) {
126
+ const ErrorClass = ERROR_CLASS_BY_STATUS[response.status] ?? (response.status >= 500 ? ServerError : ApifyApiError);
127
+ return new ErrorClass(response, attempt);
128
+ }
129
+ #safelyParsePathFromResponse(response) {
107
130
  const urlString = response.config?.url;
108
131
  let url;
109
132
  try {
@@ -114,11 +137,11 @@ class ApifyApiError extends Error {
114
137
  }
115
138
  return url.pathname + url.search;
116
139
  }
117
- _extractClientAndMethodFromStack() {
140
+ #extractClientAndMethodFromStack() {
118
141
  const match = this.stack.match(CLIENT_METHOD_REGEX);
119
- if (match)
120
- return `${match[2]}.${match[4]}`;
121
- return 'unknown';
142
+ if (!match)
143
+ return 'unknown';
144
+ return `${match[2]}.${match[4]}`;
122
145
  }
123
146
  /**
124
147
  * Creates a better looking and more informative stack that will be printed
@@ -126,15 +149,15 @@ class ApifyApiError extends Error {
126
149
  *
127
150
  * Example:
128
151
  *
129
- * ApifyApiError: Actor task was not found
152
+ * NotFoundError: Actor task was not found
130
153
  * clientMethod: TaskClient.start
131
154
  * statusCode: 404
132
155
  * type: record-not-found
133
156
  * attempt: 1
134
- * httpMethod: post
157
+ * httpMethod: POST
135
158
  * path: /v2/actor-tasks/user~my-task/runs
136
159
  */
137
- _createApiStack() {
160
+ #createApiStack() {
138
161
  const { name, ...props } = this;
139
162
  const stack = Object.entries(props)
140
163
  .map(([k, v]) => {
@@ -148,4 +171,51 @@ class ApifyApiError extends Error {
148
171
  return `${name}: ${this.message}\n${stack}`;
149
172
  }
150
173
  }
151
- exports.ApifyApiError = ApifyApiError;
174
+ /**
175
+ * Thrown when the Apify API responds with HTTP 400 Bad Request, typically because the request
176
+ * failed validation.
177
+ */
178
+ export class InvalidRequestError extends ApifyApiError {
179
+ }
180
+ /**
181
+ * Thrown when the Apify API responds with HTTP 401 Unauthorized, because the token is missing
182
+ * or invalid.
183
+ */
184
+ export class UnauthorizedError extends ApifyApiError {
185
+ }
186
+ /**
187
+ * Thrown when the Apify API responds with HTTP 403 Forbidden, because the token lacks the
188
+ * permission for the operation.
189
+ */
190
+ export class ForbiddenError extends ApifyApiError {
191
+ }
192
+ /**
193
+ * Thrown when the Apify API responds with HTTP 404 Not Found.
194
+ */
195
+ export class NotFoundError extends ApifyApiError {
196
+ }
197
+ /**
198
+ * Thrown when the Apify API responds with HTTP 409 Conflict.
199
+ */
200
+ export class ConflictError extends ApifyApiError {
201
+ }
202
+ /**
203
+ * Thrown when the Apify API responds with HTTP 429 Too Many Requests. The client retries such
204
+ * requests, so the error surfaces once the retries are exhausted.
205
+ */
206
+ export class RateLimitError extends ApifyApiError {
207
+ }
208
+ /**
209
+ * Thrown when the Apify API responds with an HTTP 5xx status. The client retries such requests,
210
+ * so the error surfaces once the retries are exhausted.
211
+ */
212
+ export class ServerError extends ApifyApiError {
213
+ }
214
+ const ERROR_CLASS_BY_STATUS = {
215
+ 400: InvalidRequestError,
216
+ 401: UnauthorizedError,
217
+ 403: ForbiddenError,
218
+ 404: NotFoundError,
219
+ 409: ConflictError,
220
+ 429: RateLimitError,
221
+ };
@@ -1,32 +1,32 @@
1
- import type { SetStatusMessageOptions } from '@crawlee/types';
2
1
  import type { Log } from '@apify/log';
3
- import { HttpClient } from './http_client';
4
- import type { RequestInterceptorFunction } from './interceptors';
5
- import { ActorClient } from './resource_clients/actor';
6
- import { ActorCollectionClient } from './resource_clients/actor_collection';
7
- import { BuildClient } from './resource_clients/build';
8
- import { BuildCollectionClient } from './resource_clients/build_collection';
9
- import { DatasetClient } from './resource_clients/dataset';
10
- import { DatasetCollectionClient } from './resource_clients/dataset_collection';
11
- import { KeyValueStoreClient } from './resource_clients/key_value_store';
12
- import { KeyValueStoreCollectionClient } from './resource_clients/key_value_store_collection';
13
- import { LogClient } from './resource_clients/log';
14
- import type { RequestQueueUserOptions } from './resource_clients/request_queue';
15
- import { RequestQueueClient } from './resource_clients/request_queue';
16
- import { RequestQueueCollectionClient } from './resource_clients/request_queue_collection';
17
- import { RunClient } from './resource_clients/run';
18
- import { RunCollectionClient } from './resource_clients/run_collection';
19
- import { ScheduleClient } from './resource_clients/schedule';
20
- import { ScheduleCollectionClient } from './resource_clients/schedule_collection';
21
- import { StoreCollectionClient } from './resource_clients/store_collection';
22
- import { TaskClient } from './resource_clients/task';
23
- import { TaskCollectionClient } from './resource_clients/task_collection';
24
- import { UserClient } from './resource_clients/user';
25
- import { WebhookClient } from './resource_clients/webhook';
26
- import { WebhookCollectionClient } from './resource_clients/webhook_collection';
27
- import { WebhookDispatchClient } from './resource_clients/webhook_dispatch';
28
- import { WebhookDispatchCollectionClient } from './resource_clients/webhook_dispatch_collection';
29
- import { Statistics } from './statistics';
2
+ import { HttpClient } from './http_clients/base.js';
3
+ import type { HttpCompressor } from './http_compressors/base.js';
4
+ import type { HttpCompressionAlgorithm } from './http_compressors/resolve.js';
5
+ import { ActorClient } from './resource_clients/actor.js';
6
+ import { ActorCollectionClient } from './resource_clients/actor_collection.js';
7
+ import { BuildClient } from './resource_clients/build.js';
8
+ import { BuildCollectionClient } from './resource_clients/build_collection.js';
9
+ import { DatasetClient } from './resource_clients/dataset.js';
10
+ import { DatasetCollectionClient } from './resource_clients/dataset_collection.js';
11
+ import { KeyValueStoreClient } from './resource_clients/key_value_store.js';
12
+ import { KeyValueStoreCollectionClient } from './resource_clients/key_value_store_collection.js';
13
+ import { LogClient } from './resource_clients/log.js';
14
+ import type { RequestQueueUserOptions } from './resource_clients/request_queue.js';
15
+ import { RequestQueueClient } from './resource_clients/request_queue.js';
16
+ import { RequestQueueCollectionClient } from './resource_clients/request_queue_collection.js';
17
+ import { RunClient } from './resource_clients/run.js';
18
+ import { RunCollectionClient } from './resource_clients/run_collection.js';
19
+ import { ScheduleClient } from './resource_clients/schedule.js';
20
+ import { ScheduleCollectionClient } from './resource_clients/schedule_collection.js';
21
+ import { StoreCollectionClient } from './resource_clients/store_collection.js';
22
+ import { TaskClient } from './resource_clients/task.js';
23
+ import { TaskCollectionClient } from './resource_clients/task_collection.js';
24
+ import { UserClient } from './resource_clients/user.js';
25
+ import { WebhookClient } from './resource_clients/webhook.js';
26
+ import { WebhookCollectionClient } from './resource_clients/webhook_collection.js';
27
+ import { WebhookDispatchClient } from './resource_clients/webhook_dispatch.js';
28
+ import { WebhookDispatchCollectionClient } from './resource_clients/webhook_dispatch_collection.js';
29
+ import { Statistics } from './statistics.js';
30
30
  /**
31
31
  * The official JavaScript client for the Apify API.
32
32
  *
@@ -49,17 +49,66 @@ import { Statistics } from './statistics';
49
49
  * @see https://docs.apify.com/api/v2
50
50
  */
51
51
  export declare class ApifyClient {
52
+ #private;
52
53
  baseUrl: string;
53
54
  /**
54
55
  * @since Added in 2.17.0
55
56
  */
56
57
  publicBaseUrl: string;
57
58
  token?: string;
59
+ /**
60
+ * Statistics of the API calls made through the client. With a custom HTTP client, this is the client's own
61
+ * `stats` object, so it only reflects what that client records.
62
+ */
58
63
  stats: Statistics;
59
64
  logger: Log;
60
- httpClient: HttpClient;
65
+ /**
66
+ * Creates a client that sends its requests through the built-in {@link AxiosHttpClient}, configured from
67
+ * `options`: the API token, retries, the timeout tiers, request compression and default headers. The HTTP
68
+ * client itself is created when {@link httpClient} is first read. To send the requests through a custom HTTP
69
+ * client, use {@link ApifyClient.withCustomHttpClient} instead.
70
+ *
71
+ * @param options - Configuration of the client and of its HTTP client.
72
+ * @throws {ArgumentValidationError} When an option is unknown or has an invalid value.
73
+ */
61
74
  constructor(options?: ApifyClientOptions);
62
- private _options;
75
+ /**
76
+ * Creates an `ApifyClient` that sends its requests through a custom HTTP client.
77
+ *
78
+ * The custom client owns its transport configuration: retries, timeouts, default headers and whatever its
79
+ * transport needs are set on the client itself. This is also how the built-in {@link AxiosHttpClient} is
80
+ * configured beyond what the constructor options offer, for example with axios request interceptors. The
81
+ * token is set as the client's `Authorization` header, unless the client already has one configured.
82
+ *
83
+ * @param options - The token, the API URLs and the HTTP client to use.
84
+ * @returns A client whose {@link httpClient} is the given one.
85
+ *
86
+ * @example
87
+ * ```javascript
88
+ * import { ApifyClient, HttpClient } from 'apify-client';
89
+ *
90
+ * class MyHttpClient extends HttpClient {
91
+ * async sendRequest({ method, url, headers, body, timeoutMillis, stream, signal }) {
92
+ * // Send the request with the HTTP library of your choice and return { status, headers, body }.
93
+ * }
94
+ * }
95
+ *
96
+ * const client = ApifyClient.withCustomHttpClient({ token: 'my-token', httpClient: new MyHttpClient() });
97
+ * ```
98
+ */
99
+ static withCustomHttpClient(options: ApifyClientCustomHttpClientOptions): ApifyClient;
100
+ /**
101
+ * The HTTP client the requests go through: the custom one when set through
102
+ * {@link ApifyClient.withCustomHttpClient}, and otherwise an {@link AxiosHttpClient} configured from the
103
+ * constructor options, created on first access. Assigning a client applies {@link token} to it through
104
+ * {@link HttpClient.setDefaultAuthorization} and points {@link stats} at its statistics, so the counters keep
105
+ * tracking the calls the client actually makes. Resource clients hold on to the HTTP client they were created
106
+ * with, so assign before reaching for them. Assigning does not close the client it replaces. A default client
107
+ * that already sent a request keeps its keep-alive agents open until {@link HttpClient.close} is called on it,
108
+ * so close it yourself, or assign before the first request.
109
+ */
110
+ get httpClient(): HttpClient;
111
+ set httpClient(httpClient: HttpClient);
63
112
  /**
64
113
  * Returns a client for managing Actors in your account.
65
114
  *
@@ -347,13 +396,41 @@ export declare class ApifyClient {
347
396
  */
348
397
  setStatusMessage(message: string, options?: SetStatusMessageOptions): Promise<void>;
349
398
  }
399
+ /**
400
+ * Options for {@apilink ApifyClient.setStatusMessage}. Structurally identical to crawlee's
401
+ * `SetStatusMessageOptions`, so the client stays a drop-in `StorageClient` implementation
402
+ * without a dependency on the crawlee packages.
403
+ */
404
+ export interface SetStatusMessageOptions {
405
+ /** If true, the status message is marked as the final one for the run. */
406
+ isStatusMessageTerminal?: boolean;
407
+ /** The log level for the status message. */
408
+ level?: 'DEBUG' | 'INFO' | 'WARNING' | 'ERROR';
409
+ }
350
410
  /**
351
411
  * Configuration options for ApifyClient.
352
412
  */
353
413
  export interface ApifyClientOptions {
354
- /** @default https://api.apify.com */
414
+ /**
415
+ * URL of the Apify API, with or without the `/v2` version path, which is appended when missing.
416
+ * @default https://api.apify.com
417
+ */
355
418
  baseUrl?: string;
356
419
  /**
420
+ * Compression of request bodies: the name of a built-in algorithm, or an {@link HttpCompressor} for a custom
421
+ * quality or algorithm. Bodies are compressed only in Node.js, and only when they are large enough to benefit
422
+ * and their content type does not already carry its own compression.
423
+ * @default 'brotli'
424
+ */
425
+ compression?: HttpCompressionAlgorithm | HttpCompressor;
426
+ /**
427
+ * Additional headers sent with every request, such as an integration platform marker. They win over the
428
+ * built-in defaults, and a header set on a single call wins over them.
429
+ */
430
+ headers?: Record<string, string>;
431
+ /**
432
+ * Publicly accessible URL of the Apify API, used in the URLs the client generates. Like `baseUrl`, with or
433
+ * without the `/v2` version path.
357
434
  * @default https://api.apify.com
358
435
  * @since Added in 2.17.0
359
436
  */
@@ -362,13 +439,51 @@ export interface ApifyClientOptions {
362
439
  maxRetries?: number;
363
440
  /** @default 500 */
364
441
  minDelayBetweenRetriesMillis?: number;
365
- /** @default [] */
366
- requestInterceptors?: RequestInterceptorFunction[];
367
- /** @default 360 */
368
- timeoutSecs?: number;
442
+ /**
443
+ * Duration of the `short` timeout tier, in seconds: simple metadata reads and writes.
444
+ * @default 5
445
+ */
446
+ timeoutShortSecs?: number;
447
+ /**
448
+ * Duration of the `medium` timeout tier, in seconds: listing, batch and trigger operations.
449
+ * @default 30
450
+ */
451
+ timeoutMediumSecs?: number;
452
+ /**
453
+ * Duration of the `long` timeout tier, in seconds: downloads, uploads and streaming.
454
+ * @default 360
455
+ */
456
+ timeoutLongSecs?: number;
457
+ /**
458
+ * Cap on the timeout of a single request attempt, in seconds. It bounds the doubling of the timeout across
459
+ * retries, and caps tier and per-call timeouts alike, so raise it to allow a request timeout above 360 s.
460
+ * @default 360
461
+ */
462
+ timeoutMaxSecs?: number;
369
463
  token?: string;
370
464
  /**
371
465
  * @since Added in 2.10.0
372
466
  */
373
467
  userAgentSuffix?: string | string[];
374
468
  }
469
+ /**
470
+ * Configuration options for {@link ApifyClient.withCustomHttpClient}. Retries, timeouts and headers are configured
471
+ * on the HTTP client itself.
472
+ */
473
+ export interface ApifyClientCustomHttpClientOptions {
474
+ /**
475
+ * URL of the Apify API, with or without the `/v2` version path, which is appended when missing.
476
+ * @default https://api.apify.com
477
+ */
478
+ baseUrl?: string;
479
+ /**
480
+ * Publicly accessible URL of the Apify API, used in the URLs the client generates. Like `baseUrl`, with or
481
+ * without the `/v2` version path.
482
+ * @default https://api.apify.com
483
+ */
484
+ publicBaseUrl?: string;
485
+ /** Set as the HTTP client's `Authorization` header, unless it already has one. */
486
+ token?: string;
487
+ /** The HTTP client to send the requests through. */
488
+ httpClient: HttpClient;
489
+ }