apify-client 3.0.0-beta.12 → 3.0.0-beta.120

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 (128) hide show
  1. package/README.md +23 -2
  2. package/dist/apify_api_error.d.ts +14 -28
  3. package/dist/apify_api_error.js +33 -23
  4. package/dist/apify_client.d.ts +125 -10
  5. package/dist/apify_client.js +133 -48
  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.d.ts +7 -7
  11. package/dist/base/api_client.js +36 -36
  12. package/dist/base/resource_client.d.ts +13 -8
  13. package/dist/base/resource_client.js +60 -34
  14. package/dist/base/resource_collection_client.d.ts +12 -4
  15. package/dist/base/resource_collection_client.js +34 -11
  16. package/dist/body_parser.d.ts +4 -5
  17. package/dist/body_parser.js +19 -26
  18. package/dist/bundle.js +41 -35
  19. package/dist/bundle.js.map +1 -1
  20. package/dist/generated/api.d.ts +3259 -1060
  21. package/dist/generated/schemas.d.ts +2608 -1028
  22. package/dist/generated/schemas.js +600 -238
  23. package/dist/http_clients/axios.d.ts +80 -0
  24. package/dist/http_clients/axios.js +165 -0
  25. package/dist/http_clients/base.d.ts +402 -0
  26. package/dist/http_clients/base.js +680 -0
  27. package/dist/http_clients/fetch.d.ts +53 -0
  28. package/dist/http_clients/fetch.js +219 -0
  29. package/dist/http_clients/index.d.ts +4 -0
  30. package/dist/http_clients/index.js +2 -0
  31. package/dist/http_compressors/base.d.ts +40 -0
  32. package/dist/http_compressors/base.js +9 -0
  33. package/dist/http_compressors/brotli.d.ts +33 -0
  34. package/dist/http_compressors/brotli.js +39 -0
  35. package/dist/http_compressors/gzip.d.ts +33 -0
  36. package/dist/http_compressors/gzip.js +39 -0
  37. package/dist/http_compressors/index.d.ts +8 -0
  38. package/dist/http_compressors/index.js +3 -0
  39. package/dist/http_compressors/resolve.d.ts +24 -0
  40. package/dist/http_compressors/resolve.js +30 -0
  41. package/dist/http_compressors/zstd.d.ts +34 -0
  42. package/dist/http_compressors/zstd.js +43 -0
  43. package/dist/index.d.ts +7 -2
  44. package/dist/index.js +5 -1
  45. package/dist/invalid_response_body_error.d.ts +14 -0
  46. package/dist/invalid_response_body_error.js +18 -0
  47. package/dist/models.d.ts +177 -240
  48. package/dist/models.js +6 -4
  49. package/dist/resource_clients/actor.d.ts +94 -23
  50. package/dist/resource_clients/actor.js +129 -43
  51. package/dist/resource_clients/actor_collection.d.ts +15 -11
  52. package/dist/resource_clients/actor_collection.js +9 -3
  53. package/dist/resource_clients/actor_env_var.d.ts +11 -4
  54. package/dist/resource_clients/actor_env_var.js +16 -6
  55. package/dist/resource_clients/actor_env_var_collection.d.ts +9 -4
  56. package/dist/resource_clients/actor_env_var_collection.js +11 -4
  57. package/dist/resource_clients/actor_server.d.ts +149 -0
  58. package/dist/resource_clients/actor_server.js +195 -0
  59. package/dist/resource_clients/actor_version.d.ts +19 -6
  60. package/dist/resource_clients/actor_version.js +19 -8
  61. package/dist/resource_clients/actor_version_collection.d.ts +10 -4
  62. package/dist/resource_clients/actor_version_collection.js +12 -4
  63. package/dist/resource_clients/build.d.ts +18 -7
  64. package/dist/resource_clients/build.js +33 -15
  65. package/dist/resource_clients/build_collection.d.ts +7 -5
  66. package/dist/resource_clients/build_collection.js +4 -1
  67. package/dist/resource_clients/dataset.d.ts +83 -37
  68. package/dist/resource_clients/dataset.js +99 -109
  69. package/dist/resource_clients/dataset_collection.d.ts +10 -6
  70. package/dist/resource_clients/dataset_collection.js +13 -2
  71. package/dist/resource_clients/key_value_store.d.ts +108 -33
  72. package/dist/resource_clients/key_value_store.js +134 -53
  73. package/dist/resource_clients/key_value_store_collection.d.ts +10 -6
  74. package/dist/resource_clients/key_value_store_collection.js +13 -2
  75. package/dist/resource_clients/log.d.ts +41 -25
  76. package/dist/resource_clients/log.js +142 -65
  77. package/dist/resource_clients/request_queue.d.ts +77 -31
  78. package/dist/resource_clients/request_queue.js +178 -93
  79. package/dist/resource_clients/request_queue_collection.d.ts +9 -5
  80. package/dist/resource_clients/request_queue_collection.js +9 -3
  81. package/dist/resource_clients/run.d.ts +119 -29
  82. package/dist/resource_clients/run.js +188 -49
  83. package/dist/resource_clients/run_collection.d.ts +5 -3
  84. package/dist/resource_clients/run_collection.js +4 -1
  85. package/dist/resource_clients/schedule.d.ts +15 -6
  86. package/dist/resource_clients/schedule.js +25 -10
  87. package/dist/resource_clients/schedule_collection.d.ts +6 -2
  88. package/dist/resource_clients/schedule_collection.js +9 -3
  89. package/dist/resource_clients/store_collection.d.ts +10 -4
  90. package/dist/resource_clients/store_collection.js +4 -1
  91. package/dist/resource_clients/task.d.ts +35 -12
  92. package/dist/resource_clients/task.js +75 -35
  93. package/dist/resource_clients/task_collection.d.ts +9 -5
  94. package/dist/resource_clients/task_collection.js +9 -3
  95. package/dist/resource_clients/user.d.ts +16 -7
  96. package/dist/resource_clients/user.js +34 -16
  97. package/dist/resource_clients/webhook.d.ts +16 -7
  98. package/dist/resource_clients/webhook.js +25 -10
  99. package/dist/resource_clients/webhook_collection.d.ts +8 -4
  100. package/dist/resource_clients/webhook_collection.js +9 -3
  101. package/dist/resource_clients/webhook_dispatch.d.ts +4 -1
  102. package/dist/resource_clients/webhook_dispatch.js +7 -2
  103. package/dist/resource_clients/webhook_dispatch_collection.d.ts +3 -1
  104. package/dist/resource_clients/webhook_dispatch_collection.js +4 -1
  105. package/dist/response_validation_error.d.ts +2 -1
  106. package/dist/response_validation_error.js +2 -1
  107. package/dist/runtime/node.d.ts +6 -0
  108. package/dist/runtime/node.js +111 -0
  109. package/dist/runtime/types.d.ts +82 -0
  110. package/dist/runtime/types.js +1 -0
  111. package/dist/runtime/web.d.ts +5 -0
  112. package/dist/runtime/web.js +60 -0
  113. package/dist/schemas.d.ts +372 -4
  114. package/dist/schemas.js +26 -4
  115. package/dist/statistics.d.ts +1 -6
  116. package/dist/statistics.js +2 -2
  117. package/dist/timeouts.d.ts +84 -0
  118. package/dist/timeouts.js +37 -0
  119. package/dist/timezones.d.ts +1 -1
  120. package/dist/utils.d.ts +115 -61
  121. package/dist/utils.js +220 -161
  122. package/dist/wait_for_resources.d.ts +8 -0
  123. package/dist/wait_for_resources.js +39 -0
  124. package/package.json +53 -38
  125. package/dist/http_client.d.ts +0 -88
  126. package/dist/http_client.js +0 -255
  127. package/dist/interceptors.d.ts +0 -19
  128. package/dist/interceptors.js +0 -105
@@ -1,34 +1,53 @@
1
1
  import { z } from 'zod';
2
+ import { ACT_JOB_TERMINAL_STATUSES } from '@apify/consts';
2
3
  import { LEVELS, Log } from '@apify/log';
3
4
  import { ResourceClient } from '../base/resource_client.js';
4
5
  import * as schemas from '../schemas.js';
5
- import { anyObjectSchema, isNode, parseArgument, parseResponse } from '../utils.js';
6
+ import { optionalSignalSchema, optionalTimeoutSchema, timeoutOptionsSchema, timeoutOptionsShape } from '../timeouts.js';
7
+ import { runtime } from '#runtime';
8
+ import { anyObjectSchema, paginationOptionsShape, parseArgument, parseResponse } from '../utils.js';
6
9
  import { DatasetClient } from './dataset.js';
7
10
  import { KeyValueStoreClient } from './key_value_store.js';
8
11
  import { LogClient, LoggerActorRedirect, StreamedLog } from './log.js';
9
12
  import { RequestQueueClient } from './request_queue.js';
10
13
  const RUN_CHARGE_IDEMPOTENCY_HEADER = 'idempotency-key';
11
- const getOptionsSchema = z.strictObject({ waitForFinish: z.number().optional() });
12
- const abortOptionsSchema = z.strictObject({ gracefully: z.boolean().optional() });
14
+ const getOptionsSchema = z.strictObject({ waitForFinish: z.number().optional(), ...timeoutOptionsShape });
15
+ const abortOptionsSchema = z.strictObject({ gracefully: z.boolean().optional(), ...timeoutOptionsShape });
13
16
  const targetActorIdSchema = z.string();
14
17
  const metamorphOptionsSchema = z.strictObject({
15
18
  contentType: z.string().optional(),
16
19
  build: z.string().optional(),
20
+ ...timeoutOptionsShape,
17
21
  });
18
22
  const resurrectOptionsSchema = z.strictObject({
19
23
  build: z.string().optional(),
20
24
  memory: z.number().optional(),
21
- timeout: z.number().optional(),
25
+ runTimeoutSecs: z.number().optional(),
22
26
  maxItems: z.number().optional(),
23
27
  maxTotalChargeUsd: z.number().optional(),
24
28
  restartOnError: z.boolean().optional(),
29
+ ...timeoutOptionsShape,
25
30
  });
26
31
  const chargeOptionsSchema = z.strictObject({
27
32
  eventName: z.string(),
28
33
  count: z.number().default(1),
29
34
  idempotencyKey: z.string().optional(),
35
+ requestId: z.string().optional(),
36
+ ...timeoutOptionsShape,
30
37
  });
31
- const waitForFinishOptionsSchema = z.strictObject({ waitSecs: z.number().optional() });
38
+ const waitForFinishOptionsSchema = z.strictObject({ waitSecs: z.number().optional(), ...timeoutOptionsShape });
39
+ const iterateDatasetItemsOptionsSchema = z.strictObject({
40
+ clean: z.boolean().optional(),
41
+ fields: z.array(z.string()).optional(),
42
+ omit: z.array(z.string()).optional(),
43
+ ...paginationOptionsShape,
44
+ skipEmpty: z.boolean().optional(),
45
+ skipHidden: z.boolean().optional(),
46
+ unwind: z.array(z.string()).optional(),
47
+ pollIntervalSecs: z.number().min(0).optional(),
48
+ ...timeoutOptionsShape,
49
+ });
50
+ const DEFAULT_ITERATE_CHUNK_SIZE = 1000;
32
51
  /**
33
52
  * Client for managing a specific Actor run.
34
53
  *
@@ -67,7 +86,9 @@ export class RunClient extends ResourceClient {
67
86
  *
68
87
  * @param options - Get options
69
88
  * @param options.waitForFinish - Maximum time to wait (in seconds, max 60s) for the run to finish on the API side before returning. Default is 0 (returns immediately).
70
- * @returns The ActorRun object, or `undefined` if it does not exist
89
+ * @param options.timeoutSecs - Timeout for the API request. Default is `'short'`, extended to cover `waitForFinish`
90
+ * when the API is asked to hold the response.
91
+ * @returns The Run object, or `undefined` if it does not exist
71
92
  * @see https://docs.apify.com/api/v2/actor-run-get
72
93
  *
73
94
  * @example
@@ -81,15 +102,16 @@ export class RunClient extends ResourceClient {
81
102
  * ```
82
103
  */
83
104
  async get(options = {}) {
84
- const parsed = parseArgument(options, getOptionsSchema, 'RunGetOptions');
85
- return this._get(schemas.Run(), parsed);
105
+ const { timeoutSecs, signal, ...params } = parseArgument(options, getOptionsSchema, 'RunGetOptions');
106
+ return this.getResource(schemas.Run(), params, this.timeoutForWaitForFinish(timeoutSecs, 'short', params.waitForFinish), signal);
86
107
  }
87
108
  /**
88
109
  * Aborts the Actor run.
89
110
  *
90
111
  * @param options - Abort options
91
112
  * @param options.gracefully - If `true`, the Actor run will abort gracefully - it can send status messages and perform cleanup. Default is `false` (immediate abort).
92
- * @returns The updated ActorRun object with `ABORTING` or `ABORTED` status
113
+ * @param options.timeoutSecs - Timeout for the API request. Default is `'medium'`.
114
+ * @returns The updated Run object with `ABORTING` or `ABORTED` status
93
115
  * @see https://docs.apify.com/api/v2/actor-run-abort-post
94
116
  *
95
117
  * @example
@@ -102,22 +124,27 @@ export class RunClient extends ResourceClient {
102
124
  * ```
103
125
  */
104
126
  async abort(options = {}) {
105
- const parsed = parseArgument(options, abortOptionsSchema, 'RunAbortOptions');
127
+ const { timeoutSecs = 'medium', signal, ...params } = parseArgument(options, abortOptionsSchema, 'RunAbortOptions');
106
128
  const response = await this.httpClient.call({
107
- url: this._url('abort'),
129
+ url: this.buildUrl('abort'),
108
130
  method: 'POST',
109
- params: this._params(parsed),
131
+ params: this.buildParams(params),
132
+ timeoutSecs,
133
+ signal,
110
134
  });
111
135
  return parseResponse(response, schemas.Run());
112
136
  }
113
137
  /**
114
138
  * Deletes the Actor run.
115
139
  *
140
+ * @param options - Request options
141
+ * @param options.timeoutSecs - Timeout for the API request. Default is `'short'`.
116
142
  * @see https://docs.apify.com/api/v2/actor-run-delete
117
143
  * @since Added in 2.8.1
118
144
  */
119
- async delete() {
120
- return this._delete();
145
+ async delete(options = {}) {
146
+ const { timeoutSecs = 'short', signal } = parseArgument(options, timeoutOptionsSchema, 'TimeoutOptions');
147
+ return this.deleteResource(timeoutSecs, signal);
121
148
  }
122
149
  /**
123
150
  * Transforms the Actor run into a run of another Actor (metamorph).
@@ -126,17 +153,23 @@ export class RunClient extends ResourceClient {
126
153
  * and resource allocation. The run effectively becomes a run of the target Actor with new input.
127
154
  * This is useful for chaining Actor executions or implementing complex workflows.
128
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
+ *
129
159
  * @param targetActorId - ID or username/name of the target Actor
130
- * @param input - Input for the target Actor, serialized to JSON. Omit it to metamorph without input.
160
+ * @param input - Input for the target Actor: an object or array serialized to JSON, or raw bytes sent as they
161
+ * are. Omit it to metamorph without input.
131
162
  * @param options - Metamorph options
132
163
  * @param options.build - Tag or number of the target Actor's build to run. Default is the target Actor's default build.
133
- * @returns The metamorphed ActorRun object (same ID, but now running the target Actor)
164
+ * @param options.timeoutSecs - Timeout for the API request. Default is `'medium'`.
165
+ * @returns The metamorphed Run object (same ID, but now running the target Actor)
134
166
  * @see https://docs.apify.com/api/v2/actor-run-metamorph-post
135
167
  *
136
168
  * @example
137
169
  * ```javascript
138
- * // Transform current run into another Actor
139
- * 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(
140
173
  * 'target-actor-id',
141
174
  * { url: 'https://example.com' }
142
175
  * );
@@ -146,21 +179,20 @@ export class RunClient extends ResourceClient {
146
179
  async metamorph(targetActorId, input, options = {}) {
147
180
  parseArgument(targetActorId, targetActorIdSchema);
148
181
  const parsed = parseArgument(options, metamorphOptionsSchema, 'RunMetamorphOptions');
149
- const safeTargetActorId = this._toSafeId(targetActorId);
182
+ const safeTargetActorId = this.toSafeId(targetActorId);
150
183
  const params = {
151
184
  targetActorId: safeTargetActorId,
152
185
  build: parsed.build,
153
186
  };
154
187
  const request = {
155
- url: this._url('metamorph'),
188
+ url: this.buildUrl('metamorph'),
156
189
  method: 'POST',
157
190
  data: input,
158
- params: this._params(params),
159
- // Apify internal property. Tells the request serialization interceptor
160
- // to stringify functions to JSON, instead of omitting them.
161
- // TODO: remove this ts-expect-error once we have defined custom Apify axios configs
162
- // @ts-expect-error Custom Apify property
191
+ params: this.buildParams(params),
192
+ // Actor input may carry page functions, which plain JSON serialization would drop.
163
193
  stringifyFunctions: true,
194
+ timeoutSecs: parsed.timeoutSecs ?? 'medium',
195
+ signal: parsed.signal,
164
196
  };
165
197
  if (parsed.contentType) {
166
198
  request.headers = {
@@ -177,7 +209,9 @@ export class RunClient extends ResourceClient {
177
209
  * This can be useful to recover from certain errors or to force the Actor to restart
178
210
  * with a fresh environment.
179
211
  *
180
- * @returns The updated ActorRun object
212
+ * @param options - Request options
213
+ * @param options.timeoutSecs - Timeout for the API request. Default is `'medium'`.
214
+ * @returns The updated Run object
181
215
  * @see https://docs.apify.com/api/v2/actor-run-reboot-post
182
216
  *
183
217
  * @example
@@ -186,10 +220,13 @@ export class RunClient extends ResourceClient {
186
220
  * ```
187
221
  * @since Added in 2.8.0
188
222
  */
189
- async reboot() {
223
+ async reboot(options = {}) {
224
+ const { timeoutSecs = 'medium', signal } = parseArgument(options, timeoutOptionsSchema, 'TimeoutOptions');
190
225
  const request = {
191
- url: this._url('reboot'),
226
+ url: this.buildUrl('reboot'),
192
227
  method: 'POST',
228
+ timeoutSecs,
229
+ signal,
193
230
  };
194
231
  const response = await this.httpClient.call(request);
195
232
  return parseResponse(response, schemas.Run());
@@ -201,7 +238,9 @@ export class RunClient extends ResourceClient {
201
238
  * @param newFields.statusMessage - Custom status message to display (e.g., "Processing page 10/100")
202
239
  * @param newFields.isStatusMessageTerminal - If `true`, the status message is final and won't be overwritten. Default is `false`.
203
240
  * @param newFields.generalAccess - General resource access level ('FOLLOW_USER_SETTING', 'ANYONE_WITH_ID_CAN_READ' or 'RESTRICTED')
204
- * @returns The updated ActorRun object
241
+ * @param options - Request options
242
+ * @param options.timeoutSecs - Timeout for the API request. Default is `'short'`.
243
+ * @returns The updated Run object
205
244
  *
206
245
  * @example
207
246
  * ```javascript
@@ -212,9 +251,10 @@ export class RunClient extends ResourceClient {
212
251
  * ```
213
252
  * @since Added in 2.6.0
214
253
  */
215
- async update(newFields) {
254
+ async update(newFields, options = {}) {
216
255
  parseArgument(newFields, anyObjectSchema);
217
- return this._update(schemas.Run(), newFields);
256
+ const { timeoutSecs = 'short', signal } = parseArgument(options, timeoutOptionsSchema, 'TimeoutOptions');
257
+ return this.updateResource(schemas.Run(), newFields, timeoutSecs, signal);
218
258
  }
219
259
  /**
220
260
  * Resurrects a finished Actor run, starting it again with the same settings.
@@ -225,11 +265,12 @@ export class RunClient extends ResourceClient {
225
265
  * @param options - Resurrection options (override original run settings)
226
266
  * @param options.build - Tag or number of the build to use. If not provided, uses the original run's build.
227
267
  * @param options.memory - Memory in megabytes. If not provided, uses the original run's memory.
228
- * @param options.timeout - Timeout in seconds. If not provided, uses the original run's timeout.
268
+ * @param options.runTimeoutSecs - Timeout for the resurrected run in seconds. If not provided, uses the original run's timeout.
229
269
  * @param options.maxItems - Maximum number of dataset items (pay-per-result Actors).
230
270
  * @param options.maxTotalChargeUsd - Maximum cost in USD (pay-per-event Actors).
231
271
  * @param options.restartOnError - Whether to restart on error.
232
- * @returns The new (resurrected) ActorRun object
272
+ * @param options.timeoutSecs - Timeout for the API request. Default is `'medium'`.
273
+ * @returns The new (resurrected) Run object
233
274
  * @see https://docs.apify.com/api/v2/post-resurrect-run
234
275
  *
235
276
  * @example
@@ -240,11 +281,14 @@ export class RunClient extends ResourceClient {
240
281
  * ```
241
282
  */
242
283
  async resurrect(options = {}) {
243
- const parsed = parseArgument(options, resurrectOptionsSchema, 'RunResurrectOptions');
284
+ const { timeoutSecs = 'medium', signal, runTimeoutSecs, ...params } = parseArgument(options, resurrectOptionsSchema, 'RunResurrectOptions');
244
285
  const response = await this.httpClient.call({
245
- url: this._url('resurrect'),
286
+ url: this.buildUrl('resurrect'),
246
287
  method: 'POST',
247
- params: this._params(parsed),
288
+ // The API's `timeout` parameter bounds the run, not the request.
289
+ params: this.buildParams({ ...params, timeout: runTimeoutSecs }),
290
+ timeoutSecs,
291
+ signal,
248
292
  });
249
293
  return parseResponse(response, schemas.Run());
250
294
  }
@@ -255,25 +299,30 @@ export class RunClient extends ResourceClient {
255
299
  * @param options.eventName - **Required.** Name of the event to charge for.
256
300
  * @param options.count - Number of times to charge the event. Default is 1.
257
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.
303
+ * @param options.timeoutSecs - Timeout for the API request. Default is `'short'`.
258
304
  * @returns Empty response object.
259
305
  * @see https://docs.apify.com/api/v2/post-charge-run
260
306
  * @since Added in 2.11.0
261
307
  */
262
308
  async charge(options) {
263
- const { eventName, count, idempotencyKey: providedIdempotencyKey, } = parseArgument(options, chargeOptionsSchema, 'RunChargeOptions');
309
+ const { eventName, count, idempotencyKey: providedIdempotencyKey, timeoutSecs = 'short', requestId, signal, } = parseArgument(options, chargeOptionsSchema, 'RunChargeOptions');
264
310
  /** To avoid duplicates during the same milisecond, doesn't need to by crypto-secure. */
265
311
  const randomSuffix = (Math.random() + 1).toString(36).slice(3, 8);
266
312
  const idempotencyKey = providedIdempotencyKey ?? `${this.id}-${eventName}-${Date.now()}-${randomSuffix}`;
267
313
  const request = {
268
- url: this._url('charge'),
314
+ url: this.buildUrl('charge'),
269
315
  method: 'POST',
270
316
  data: {
271
317
  eventName,
272
318
  count,
319
+ requestId,
273
320
  },
274
321
  headers: {
275
322
  [RUN_CHARGE_IDEMPOTENCY_HEADER]: idempotencyKey,
276
323
  },
324
+ timeoutSecs,
325
+ signal,
277
326
  };
278
327
  const response = await this.httpClient.call(request);
279
328
  return response;
@@ -288,10 +337,12 @@ export class RunClient extends ResourceClient {
288
337
  * Unlike the `waitForFinish` parameter in {@link get}, this method can wait indefinitely
289
338
  * by polling the run status. It uses the `waitForFinish` parameter internally (max 60s per call)
290
339
  * and continuously polls until the run finishes or the timeout is reached.
340
+ * Rejects with a {@link NotFoundError} if the run keeps returning 404 for 3 seconds.
291
341
  *
292
342
  * @param options - Wait options
293
343
  * @param options.waitSecs - Maximum time to wait for the run to finish, in seconds. If the limit is reached, the returned promise resolves to a run object that will have status `READY` or `RUNNING`. If omitted, waits indefinitely.
294
- * @returns The ActorRun object (finished or still running if timeout was reached)
344
+ * @param options.timeoutSecs - Timeout for each polling API request. Default is `'noTimeout'`.
345
+ * @returns The Run object (finished or still running if the timeout was reached)
295
346
  *
296
347
  * @example
297
348
  * ```javascript
@@ -308,7 +359,7 @@ export class RunClient extends ResourceClient {
308
359
  */
309
360
  async waitForFinish(options = {}) {
310
361
  const parsed = parseArgument(options, waitForFinishOptionsSchema, 'RunWaitForFinishOptions');
311
- return this._waitForFinish(schemas.Run(), parsed);
362
+ return this.waitForJobFinish(schemas.Run(), parsed);
312
363
  }
313
364
  /**
314
365
  * Returns a client for the default dataset of this Actor run.
@@ -325,7 +376,7 @@ export class RunClient extends ResourceClient {
325
376
  * ```
326
377
  */
327
378
  dataset() {
328
- return new DatasetClient(this._subResourceOptions({
379
+ return new DatasetClient(this.subResourceOptions({
329
380
  resourcePath: 'dataset',
330
381
  }));
331
382
  }
@@ -345,7 +396,7 @@ export class RunClient extends ResourceClient {
345
396
  * ```
346
397
  */
347
398
  keyValueStore() {
348
- return new KeyValueStoreClient(this._subResourceOptions({
399
+ return new KeyValueStoreClient(this.subResourceOptions({
349
400
  resourcePath: 'key-value-store',
350
401
  }));
351
402
  }
@@ -365,7 +416,7 @@ export class RunClient extends ResourceClient {
365
416
  * ```
366
417
  */
367
418
  requestQueue() {
368
- return new RequestQueueClient(this._subResourceOptions({
419
+ return new RequestQueueClient(this.subResourceOptions({
369
420
  resourcePath: 'request-queue',
370
421
  }));
371
422
  }
@@ -385,33 +436,121 @@ export class RunClient extends ResourceClient {
385
436
  * ```
386
437
  */
387
438
  log() {
388
- return new LogClient(this._subResourceOptions({
439
+ return new LogClient(this.subResourceOptions({
389
440
  resourcePath: 'log',
390
441
  }));
391
442
  }
392
443
  /**
393
444
  * Get StreamedLog for convenient streaming of the run log and their redirection.
445
+ *
446
+ * @param options - Streaming options
447
+ * @param options.toLog - Log instance to redirect the run log to. Use `'default'` for a preconfigured one, or `null` to disable the redirection.
448
+ * @param options.fromStart - If `true`, the log is streamed from its beginning. Default is `true`.
449
+ * @param options.timeoutSecs - Timeout for the API requests that fetch the run and its Actor. Default is `'long'`.
394
450
  * @since Added in 2.20.0
395
451
  */
396
452
  async getStreamedLog(options = {}) {
397
- const { fromStart = true } = options;
453
+ parseArgument(options.timeoutSecs, optionalTimeoutSchema);
454
+ parseArgument(options.signal, optionalSignalSchema);
455
+ const { fromStart = true, timeoutSecs = 'long', signal } = options;
398
456
  let { toLog } = options;
399
- if (toLog === null || !isNode()) {
457
+ if (toLog === null || !runtime.isNode) {
400
458
  // Explicitly no logging or not in Node.js
401
459
  return undefined;
402
460
  }
403
461
  if (toLog === undefined || toLog === 'default') {
404
462
  // Create default StreamedLog
405
463
  // Get actor name and run id
406
- const runData = await this.get();
464
+ const runData = await this.get({ timeoutSecs, signal });
407
465
  const runId = runData?.id ?? '';
408
466
  const actorId = runData?.actId ?? '';
409
467
  // `apifyClient.actor()` rejects an empty ID, which is what a run that could not be read leaves here.
410
- const actorData = actorId ? await this.apifyClient.actor(actorId).get() : undefined;
468
+ const actorData = actorId ? await this.apifyClient.actor(actorId).get({ timeoutSecs, signal }) : undefined;
411
469
  const actorName = actorData?.name ?? '';
412
470
  const name = [actorName, `runId:${runId}`].filter(Boolean).join(' ');
413
471
  toLog = new Log({ level: LEVELS.DEBUG, prefix: `${name} -> `, logger: new LoggerActorRedirect() });
414
472
  }
415
- return new StreamedLog({ logClient: this.log(), toLog, fromStart });
473
+ return new StreamedLog({ logClient: this.log(), toLog, fromStart, signal });
474
+ }
475
+ /**
476
+ * Iterates over the items of the run's default dataset while the run is still producing them.
477
+ *
478
+ * While the run has not finished, each poll yields the rows below the dataset's `itemCount` and then waits up to
479
+ * `pollIntervalSecs` for the run to finish, so the last rows are read as soon as it does. Each page is requested
480
+ * with a `limit` that ends at `itemCount`, so it covers exactly the rows it asks for, whatever the filters or
481
+ * `unwind` do to the items. `itemCount` lags a few seconds behind
482
+ * the pushed items, so once the run reaches a terminal status, the rows past it are read a page at a time until
483
+ * none are left, and the iterator returns. On a `lastRun()` client, the iterator sticks to the run that its first
484
+ * request resolves to.
485
+ *
486
+ * @param options - Iteration options
487
+ * @param options.offset - Number of rows to skip from the beginning. Default is 0.
488
+ * @param options.limit - Maximum number of dataset rows to scan. Fewer items are yielded when filters drop some,
489
+ * more when `unwind` splits a row into several. Default is no limit.
490
+ * @param options.clean - If `true`, returns only non-empty items and skips hidden fields. Default is `false`.
491
+ * @param options.fields - Array of field names to include in the results. Omits all other fields.
492
+ * @param options.omit - Array of field names to exclude from the results.
493
+ * @param options.unwind - Array of field names to unwind. Each array value creates a separate item.
494
+ * @param options.skipEmpty - If `true`, skips empty items. Default is `false`.
495
+ * @param options.skipHidden - If `true`, skips hidden fields (fields starting with `#`). Default is `false`.
496
+ * @param options.chunkSize - Maximum number of dataset rows requested per API call. Default is 1000.
497
+ * @param options.pollIntervalSecs - How long to wait for the run to finish between polls, in seconds. Default is 5.
498
+ * @param options.timeoutSecs - Timeout for each API request. Default is `'long'`.
499
+ * @returns An async iterable of the dataset items
500
+ * @see https://docs.apify.com/api/v2/dataset-items-get
501
+ *
502
+ * @example
503
+ * ```javascript
504
+ * for await (const item of client.run('run-id').iterateDatasetItems()) {
505
+ * console.log(item);
506
+ * }
507
+ * ```
508
+ */
509
+ async *iterateDatasetItems(options = {}) {
510
+ const { offset, limit, chunkSize, pollIntervalSecs = 5, timeoutSecs = 'long', signal, ...itemOptions } = parseArgument(options, iterateDatasetItemsOptionsSchema, 'RunIterateDatasetItemsOptions');
511
+ const pageSize = chunkSize || DEFAULT_ITERATE_CHUNK_SIZE;
512
+ let position = offset ?? 0;
513
+ const end = limit ? position + limit : undefined;
514
+ let run = await this.get({ timeoutSecs, signal });
515
+ // A `lastRun()` client resolves `runs/last` on each request, so a newer run would swap the dataset mid-iteration.
516
+ const runClient = run && run.id !== this.id ? this.apifyClient.run(run.id) : this;
517
+ const datasetClient = runClient.dataset();
518
+ const listPage = async (pageOffset, pageLimit) => datasetClient.listItems({ ...itemOptions, offset: pageOffset, limit: pageLimit, timeoutSecs, signal });
519
+ while (true) {
520
+ const isFinished = !run || ACT_JOB_TERMINAL_STATUSES.includes(run.status);
521
+ const dataset = await datasetClient.get({ timeoutSecs, signal });
522
+ let itemCount = dataset?.itemCount ?? 0;
523
+ if (end !== undefined)
524
+ itemCount = Math.min(itemCount, end);
525
+ while (position < itemCount) {
526
+ const pageLimit = Math.min(pageSize, itemCount - position);
527
+ const page = await listPage(position, pageLimit);
528
+ yield* page.items;
529
+ position += pageLimit;
530
+ }
531
+ if (end !== undefined && position >= end)
532
+ return;
533
+ if (isFinished)
534
+ break;
535
+ run = await runClient.waitForFinish({ waitSecs: pollIntervalSecs, timeoutSecs, signal });
536
+ }
537
+ const { clean, skipEmpty, unwind } = itemOptions;
538
+ while (true) {
539
+ const pageLimit = end !== undefined ? Math.min(pageSize, end - position) : pageSize;
540
+ const page = await listPage(position, pageLimit);
541
+ yield* page.items;
542
+ // Only an empty page marks the end, as filters can shorten a full one. A page that `clean`, `skipEmpty` or
543
+ // `unwind` emptied past a lagging `itemCount` reports no scanned rows either, so a plain read checks.
544
+ const isEmpty = page.count === 0;
545
+ if (isEmpty &&
546
+ (!(clean || skipEmpty || unwind?.length) ||
547
+ (await datasetClient.listItems({ offset: position, limit: 1, timeoutSecs, signal })).items
548
+ .length === 0)) {
549
+ return;
550
+ }
551
+ position += pageLimit;
552
+ if (end !== undefined && position >= end)
553
+ return;
554
+ }
416
555
  }
417
556
  }
@@ -1,8 +1,9 @@
1
1
  import { ACTOR_JOB_STATUSES } from '@apify/consts';
2
2
  import type { ApiClientOptionsWithOptionalResourcePath } from '../base/api_client.js';
3
3
  import { ResourceCollectionClient } from '../base/resource_collection_client.js';
4
+ import type { TimeoutOptions } from '../timeouts.js';
4
5
  import type { PaginatedIterator, PaginationOptions } from '../utils.js';
5
- import type { ActorRunListItem } from './actor.js';
6
+ import type { RunListItem } from './actor.js';
6
7
  /**
7
8
  * Client for managing the collection of Actor runs.
8
9
  *
@@ -46,12 +47,13 @@ export declare class RunCollectionClient extends ResourceCollectionClient {
46
47
  * ```
47
48
  *
48
49
  * @param options - Pagination and filtering options.
50
+ * @param options.timeoutSecs - Timeout for each API request. Default is `'medium'`.
49
51
  * @returns A paginated iterator of Actor runs.
50
52
  * @see https://docs.apify.com/api/v2/actor-runs-get
51
53
  */
52
- list(options?: RunCollectionListOptions): PaginatedIterator<ActorRunListItem>;
54
+ list(options?: RunCollectionListOptions): PaginatedIterator<RunListItem>;
53
55
  }
54
- export interface RunCollectionListOptions extends PaginationOptions {
56
+ export interface RunCollectionListOptions extends PaginationOptions, TimeoutOptions {
55
57
  desc?: boolean;
56
58
  status?: (typeof ACTOR_JOB_STATUSES)[keyof typeof ACTOR_JOB_STATUSES] | (typeof ACTOR_JOB_STATUSES)[keyof typeof ACTOR_JOB_STATUSES][];
57
59
  /**
@@ -2,6 +2,7 @@ import { z } from 'zod';
2
2
  import { ACTOR_JOB_STATUSES } from '@apify/consts';
3
3
  import { ResourceCollectionClient } from '../base/resource_collection_client.js';
4
4
  import * as schemas from '../schemas.js';
5
+ import { timeoutOptionsShape } from '../timeouts.js';
5
6
  import { paginationOptionsShape, parseArgument } from '../utils.js';
6
7
  const jobStatusSchema = z.enum(ACTOR_JOB_STATUSES);
7
8
  const listOptionsSchema = z.strictObject({
@@ -10,6 +11,7 @@ const listOptionsSchema = z.strictObject({
10
11
  status: z.union([jobStatusSchema, z.array(jobStatusSchema)]).optional(),
11
12
  startedBefore: z.union([z.date(), z.string()]).optional(),
12
13
  startedAfter: z.union([z.date(), z.string()]).optional(),
14
+ ...timeoutOptionsShape,
13
15
  });
14
16
  /**
15
17
  * Client for managing the collection of Actor runs.
@@ -59,11 +61,12 @@ export class RunCollectionClient extends ResourceCollectionClient {
59
61
  * ```
60
62
  *
61
63
  * @param options - Pagination and filtering options.
64
+ * @param options.timeoutSecs - Timeout for each API request. Default is `'medium'`.
62
65
  * @returns A paginated iterator of Actor runs.
63
66
  * @see https://docs.apify.com/api/v2/actor-runs-get
64
67
  */
65
68
  list(options = {}) {
66
69
  const parsed = parseArgument(options, listOptionsSchema, 'RunCollectionListOptions');
67
- return this._listPaginated(schemas.ListOfRuns(), parsed);
70
+ return this.listResourcesPaginated(schemas.ListOfRuns(), parsed, 'medium');
68
71
  }
69
72
  }
@@ -1,8 +1,9 @@
1
1
  import type { ApiClientSubResourceOptions } from '../base/api_client.js';
2
2
  import { ResourceClient } from '../base/resource_client.js';
3
- import type { Schedule, ScheduleAction, ScheduleInvoked } from '../models.js';
3
+ import type { Schedule, ScheduleAction, ScheduleLogEntry } from '../models.js';
4
+ import type { TimeoutOptions } from '../timeouts.js';
4
5
  import type { DistributiveOptional } from '../utils.js';
5
- export type { Schedule, ScheduleAction, ScheduleActionRunActor, ScheduleActionRunActorTask, ScheduledActorRunInput, ScheduledActorRunOptions, ScheduleInvoked, } from '../models.js';
6
+ export type { Schedule, ScheduleAction, ScheduleActionRunActor, ScheduleActionRunActorTask, ScheduleActionRunInput, ScheduleLogEntry, TaskOptions, } from '../models.js';
6
7
  export { ScheduleActions } from '../models.js';
7
8
  /**
8
9
  * Client for managing a specific Schedule.
@@ -35,31 +36,39 @@ export declare class ScheduleClient extends ResourceClient {
35
36
  /**
36
37
  * Retrieves the schedule.
37
38
  *
39
+ * @param options - Request options
40
+ * @param options.timeoutSecs - Timeout for the API request. Default is `'short'`.
38
41
  * @returns The schedule object, or `undefined` if it does not exist.
39
42
  * @see https://docs.apify.com/api/v2/schedule-get
40
43
  */
41
- get(): Promise<Schedule | undefined>;
44
+ get(options?: TimeoutOptions): Promise<Schedule | undefined>;
42
45
  /**
43
46
  * Updates the schedule with the specified fields.
44
47
  *
45
48
  * @param newFields - Fields to update.
49
+ * @param options - Request options
50
+ * @param options.timeoutSecs - Timeout for the API request. Default is `'short'`.
46
51
  * @returns The updated schedule object.
47
52
  * @see https://docs.apify.com/api/v2/schedule-put
48
53
  */
49
- update(newFields: ScheduleCreateOrUpdateData): Promise<Schedule>;
54
+ update(newFields: ScheduleCreateOrUpdateData, options?: TimeoutOptions): Promise<Schedule>;
50
55
  /**
51
56
  * Deletes the schedule.
52
57
  *
58
+ * @param options - Request options
59
+ * @param options.timeoutSecs - Timeout for the API request. Default is `'short'`.
53
60
  * @see https://docs.apify.com/api/v2/schedule-delete
54
61
  */
55
- delete(): Promise<void>;
62
+ delete(options?: TimeoutOptions): Promise<void>;
56
63
  /**
57
64
  * Retrieves the schedule's log.
58
65
  *
66
+ * @param options - Request options
67
+ * @param options.timeoutSecs - Timeout for the API request. Default is `'medium'`.
59
68
  * @returns The schedule log, one entry per invocation.
60
69
  * @see https://docs.apify.com/api/v2/schedule-log-get
61
70
  */
62
- getLog(): Promise<ScheduleInvoked[]>;
71
+ getLog(options?: TimeoutOptions): Promise<ScheduleLogEntry[]>;
63
72
  }
64
73
  /**
65
74
  * Data for creating or updating a Schedule.