apify 3.7.3-beta.97 → 4.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 (51) hide show
  1. package/README.md +1 -1
  2. package/dist/actor.d.ts +379 -139
  3. package/dist/actor.js +764 -500
  4. package/dist/apify_dataset_backend.d.ts +19 -0
  5. package/dist/apify_dataset_backend.js +77 -0
  6. package/dist/apify_file_system_storage_backend.d.ts +34 -0
  7. package/dist/apify_file_system_storage_backend.js +41 -0
  8. package/dist/apify_key_value_store_backend.d.ts +23 -0
  9. package/dist/apify_key_value_store_backend.js +56 -0
  10. package/dist/apify_request_queue_backend.d.ts +78 -0
  11. package/dist/apify_request_queue_backend.js +114 -0
  12. package/dist/apify_request_queue_shared_backend.d.ts +31 -0
  13. package/dist/apify_request_queue_shared_backend.js +193 -0
  14. package/dist/apify_request_queue_single_backend.d.ts +43 -0
  15. package/dist/apify_request_queue_single_backend.js +256 -0
  16. package/dist/apify_storage_backend.d.ts +90 -0
  17. package/dist/apify_storage_backend.js +210 -0
  18. package/dist/charging.d.ts +39 -44
  19. package/dist/charging.js +237 -293
  20. package/dist/charging_storage_backend.d.ts +53 -0
  21. package/dist/charging_storage_backend.js +105 -0
  22. package/dist/child_run_tracker.d.ts +88 -0
  23. package/dist/child_run_tracker.js +239 -0
  24. package/dist/configuration.d.ts +85 -144
  25. package/dist/configuration.js +138 -174
  26. package/dist/enqueue_links_filters.d.ts +29 -0
  27. package/dist/enqueue_links_filters.js +52 -0
  28. package/dist/errors.d.ts +31 -0
  29. package/dist/errors.js +22 -0
  30. package/dist/google_sheets.d.ts +12 -0
  31. package/dist/google_sheets.js +26 -0
  32. package/dist/index.d.ts +10 -4
  33. package/dist/index.js +12 -22
  34. package/dist/input-schemas.d.ts +1 -1
  35. package/dist/input-schemas.js +12 -18
  36. package/dist/platform_event_manager.d.ts +15 -10
  37. package/dist/platform_event_manager.js +193 -63
  38. package/dist/proxy_configuration.d.ts +52 -72
  39. package/dist/proxy_configuration.js +176 -221
  40. package/dist/smart_apify_storage_backend.d.ts +52 -0
  41. package/dist/smart_apify_storage_backend.js +73 -0
  42. package/dist/storage.d.ts +6 -24
  43. package/dist/storage.js +1 -79
  44. package/dist/utils.d.ts +30 -0
  45. package/dist/utils.js +81 -23
  46. package/package.json +38 -43
  47. package/dist/index.mjs +0 -19
  48. package/dist/key_value_store.d.ts +0 -16
  49. package/dist/key_value_store.js +0 -40
  50. package/dist/patched_apify_client.d.ts +0 -25
  51. package/dist/patched_apify_client.js +0 -75
package/dist/actor.js CHANGED
@@ -1,31 +1,54 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.Actor = exports.EXIT_CODES = void 0;
4
- const tslib_1 = require("tslib");
5
- const node_crypto_1 = require("node:crypto");
6
- const core_1 = require("@crawlee/core");
7
- const utils_1 = require("@crawlee/utils");
8
- const ow_1 = tslib_1.__importDefault(require("ow"));
9
- const consts_1 = require("@apify/consts");
10
- const input_secrets_1 = require("@apify/input_secrets");
11
- const log_1 = tslib_1.__importDefault(require("@apify/log"));
12
- const timeout_1 = require("@apify/timeout");
13
- const charging_js_1 = require("./charging.js");
14
- const configuration_js_1 = require("./configuration.js");
15
- const input_schemas_js_1 = require("./input-schemas.js");
16
- const key_value_store_js_1 = require("./key_value_store.js");
17
- const patched_apify_client_js_1 = require("./patched_apify_client.js");
18
- const platform_event_manager_js_1 = require("./platform_event_manager.js");
19
- const proxy_configuration_js_1 = require("./proxy_configuration.js");
20
- const storage_js_1 = require("./storage.js");
21
- const utils_js_1 = require("./utils.js");
1
+ import { createPrivateKey } from 'node:crypto';
2
+ import { readFile, stat } from 'node:fs/promises';
3
+ import { join } from 'node:path';
4
+ import { coerceBoolean, Dataset, EventType, KeyValueStore, MemoryStorageBackend, purgeDefaultStorages, rejectOperationInTransaction, RequestQueue, serviceLocator, } from '@crawlee/core';
5
+ import { sleep } from '@crawlee/utils';
6
+ import { ApifyClient } from 'apify-client';
7
+ import { z } from 'zod';
8
+ import { ACTOR_ENV_VARS, ACTOR_EVENT_NAMES, APIFY_ENV_VARS, INTEGER_ENV_VARS, } from '@apify/consts';
9
+ import { decryptInputSecrets } from '@apify/input_secrets';
10
+ import log from '@apify/log';
11
+ import { addTimeoutToPromise } from '@apify/timeout';
12
+ import { parseArgument } from '@apify/validations';
13
+ import { ApifyFileSystemStorageBackend } from './apify_file_system_storage_backend.js';
14
+ import { ApifyStorageBackend } from './apify_storage_backend.js';
15
+ import { ChargingManager, DEFAULT_DATASET_ITEM_EVENT } from './charging.js';
16
+ import { ChargingStorageBackend } from './charging_storage_backend.js';
17
+ import { ChildRunTracker } from './child_run_tracker.js';
18
+ import { Configuration } from './configuration.js';
19
+ import { ActorInputError } from './errors.js';
20
+ import { fixGoogleSheetsUrls } from './google_sheets.js';
21
+ import { getDefaultsFromInputSchema, noActorInputSchemaDefinedMarker, readInputSchema } from './input-schemas.js';
22
+ import { PlatformEventManager } from './platform_event_manager.js';
23
+ import { ProxyConfiguration } from './proxy_configuration.js';
24
+ import { SmartApifyStorageBackend } from './smart_apify_storage_backend.js';
25
+ import { BINARY_CONTENT_TYPE, checkCrawleeVersion, getSystemInfo, isNonEmptyObject, JSON_CONTENT_TYPE, parseInputValue, snakeCaseToCamelCase, } from './utils.js';
26
+ // `@apify/consts` has no boolean counterpart to `INTEGER_ENV_VARS`.
27
+ const BOOLEAN_ENV_VARS = [APIFY_ENV_VARS.USER_IS_PAYING];
28
+ // Still listed in `@apify/consts`, but no longer read by the SDK.
29
+ const IGNORED_ENV_VARS = [
30
+ APIFY_ENV_VARS.DISABLE_OUTDATED_WARNING,
31
+ APIFY_ENV_VARS.SDK_LATEST_VERSION,
32
+ ];
33
+ /**
34
+ * {@link parseInputValue} with the parser error wrapped as an {@link ActorInputError}, so a malformed
35
+ * JSON input reports where it came from.
36
+ */
37
+ function parseInput(value, contentType, source) {
38
+ try {
39
+ return parseInputValue(value, contentType);
40
+ }
41
+ catch (cause) {
42
+ throw new ActorInputError('PARSE_FAILED', `The input in ${source} is not valid JSON.`, { cause });
43
+ }
44
+ }
22
45
  /**
23
46
  * Exit codes for the Actor process.
24
47
  * The error codes must be in the range 1-128, to avoid collision with signal exits
25
48
  * and to ensure Docker will handle them correctly!
26
49
  * @internal should be removed if we decide to remove `Actor.main()`
27
50
  */
28
- exports.EXIT_CODES = {
51
+ export const EXIT_CODES = {
29
52
  SUCCESS: 0,
30
53
  ERROR_USER_FUNCTION_THREW: 91,
31
54
  ERROR_UNKNOWN: 92,
@@ -35,106 +58,87 @@ exports.EXIT_CODES = {
35
58
  * that will be used on the instance methods. Environment variables will have precedence over this configuration.
36
59
  * See {@link Configuration} for details about what can be configured and what are the default values.
37
60
  */
38
- class Actor {
61
+ export class Actor {
62
+ /** @internal */
63
+ static #instance;
64
+ #childRunTracker;
65
+ /**
66
+ * Configuration of this SDK instance (provided to its constructor). See {@link Configuration} for details.
67
+ * @internal
68
+ */
69
+ configuration;
70
+ /**
71
+ * Default {@link ApifyClient} instance.
72
+ * @internal
73
+ */
74
+ apifyClient;
75
+ /**
76
+ * Default {@link EventManager} instance.
77
+ * @internal
78
+ */
79
+ eventManager;
80
+ /**
81
+ * Whether the Actor instance was initialized. This is set by calling {@link Actor.init}.
82
+ */
83
+ initialized = false;
84
+ /**
85
+ * Set if the Actor called a method that requires the instance to be initialized, but did not do so.
86
+ * A call to `init` after this warning is emitted is considered an invalid state and will throw an error.
87
+ */
88
+ #warnedAboutMissingInitCall = false;
89
+ /**
90
+ * Set if the Actor is currently rebooting.
91
+ */
92
+ #isRebooting = false;
93
+ /**
94
+ * Set if the Actor is currently exiting. Prevents double-exit from graceful shutdown handlers.
95
+ */
96
+ #isExiting = false;
97
+ /**
98
+ * References to graceful shutdown handlers so they can be removed during cleanup.
99
+ */
100
+ #gracefulShutdownHandlers = {};
101
+ /**
102
+ * Reference to the crawlee status message forwarder, so it can be removed during cleanup.
103
+ */
104
+ #statusMessageForwarder;
105
+ #chargingManager;
106
+ /** Aborts the child runs started with `abortWithParent` on the `aborting` event. */
107
+ #abortChildRunsWithParent = async () => this.#childRunTracker.abortRunsWithParent(this.apifyClient);
108
+ /** How Apify platform request queues are consumed; set from {@link InitOptions.requestQueueAccess}. */
109
+ #requestQueueAccess = 'single';
110
+ /** Lazily built by the `#storageBackend` getter. */
111
+ #cachedStorageBackend;
112
+ /** Listeners registered via `on()` before `init()`; attached to the event manager by `init()`. */
113
+ #pendingListeners = [];
39
114
  constructor(options = {}) {
40
- /**
41
- * Configuration of this SDK instance (provided to its constructor). See {@link Configuration} for details.
42
- * @internal
43
- */
44
- Object.defineProperty(this, "config", {
45
- enumerable: true,
46
- configurable: true,
47
- writable: true,
48
- value: void 0
49
- });
50
- /**
51
- * Default {@link ApifyClient} instance.
52
- * @internal
53
- */
54
- Object.defineProperty(this, "apifyClient", {
55
- enumerable: true,
56
- configurable: true,
57
- writable: true,
58
- value: void 0
59
- });
60
- /**
61
- * Default {@link EventManager} instance.
62
- * @internal
63
- */
64
- Object.defineProperty(this, "eventManager", {
65
- enumerable: true,
66
- configurable: true,
67
- writable: true,
68
- value: void 0
69
- });
70
- /**
71
- * Whether the Actor instance was initialized. This is set by calling {@link Actor.init}.
72
- */
73
- Object.defineProperty(this, "initialized", {
74
- enumerable: true,
75
- configurable: true,
76
- writable: true,
77
- value: false
78
- });
79
- /**
80
- * Set if the Actor called a method that requires the instance to be initialized, but did not do so.
81
- * A call to `init` after this warning is emitted is considered an invalid state and will throw an error.
82
- */
83
- Object.defineProperty(this, "warnedAboutMissingInitCall", {
84
- enumerable: true,
85
- configurable: true,
86
- writable: true,
87
- value: false
88
- });
89
- /**
90
- * Set if the Actor is currently rebooting.
91
- */
92
- Object.defineProperty(this, "isRebooting", {
93
- enumerable: true,
94
- configurable: true,
95
- writable: true,
96
- value: false
97
- });
98
- /**
99
- * Set if the Actor is currently exiting. Prevents double-exit from graceful shutdown handlers.
100
- */
101
- Object.defineProperty(this, "isExiting", {
102
- enumerable: true,
103
- configurable: true,
104
- writable: true,
105
- value: false
106
- });
107
- /**
108
- * References to graceful shutdown handlers so they can be removed during cleanup.
109
- */
110
- Object.defineProperty(this, "gracefulShutdownHandlers", {
111
- enumerable: true,
112
- configurable: true,
113
- writable: true,
114
- value: {}
115
- });
116
- Object.defineProperty(this, "chargingManager", {
117
- enumerable: true,
118
- configurable: true,
119
- writable: true,
120
- value: void 0
121
- });
122
- /**
123
- * Tracks which aliased storages have been purged during this session,
124
- * so we only purge them once (on first open) when running locally.
125
- * @internal
126
- */
127
- Object.defineProperty(this, "purgedStorageAliases", {
128
- enumerable: true,
129
- configurable: true,
130
- writable: true,
131
- value: new Set()
132
- });
133
- // use default configuration object if nothing overridden (it fallbacks to env vars)
134
- this.config = Object.keys(options).length === 0 ? configuration_js_1.Configuration.getGlobalConfig() : new configuration_js_1.Configuration(options);
115
+ const { configuration, ...configOptions } = options;
116
+ if (configuration) {
117
+ // BYO Configuration takes precedence; field-level overrides are
118
+ // ignored to keep the contract unambiguous. It must be the SDK's
119
+ // Configuration subclass, not a bare crawlee one — env-var
120
+ // resolution is driven by the subclass's `static fields`
121
+ // (`apifyConfigFields`) at construction, so a crawlee instance
122
+ // would silently expose none of the `APIFY_*`/`ACTOR_*` values.
123
+ if (!(configuration instanceof Configuration)) {
124
+ throw new Error('Actor `configuration` must be an Apify SDK Configuration (imported from `apify`), ' +
125
+ 'not a crawlee Configuration, otherwise APIFY_*/ACTOR_* environment variables are not resolved.');
126
+ }
127
+ this.configuration = configuration;
128
+ }
129
+ else if (Object.keys(configOptions).length === 0) {
130
+ // use default configuration object if nothing overridden (it fallbacks to env vars)
131
+ this.configuration = Configuration.getGlobalConfiguration();
132
+ }
133
+ else {
134
+ this.configuration = new Configuration(configOptions);
135
+ }
135
136
  this.apifyClient = this.newClient();
136
- this.eventManager = new platform_event_manager_js_1.PlatformEventManager(this.config);
137
- this.chargingManager = new charging_js_1.ChargingManager(this.config, this.apifyClient);
137
+ this.eventManager = new PlatformEventManager(this.configuration, {
138
+ [ACTOR_EVENT_NAMES.ABORTING]: this.#abortChildRunsWithParent,
139
+ });
140
+ this.#chargingManager = new ChargingManager(this.configuration, this.apifyClient);
141
+ this.#childRunTracker = new ChildRunTracker();
138
142
  }
139
143
  /**
140
144
  * Runs the main user function that performs the job of the Actor
@@ -171,24 +175,22 @@ class Actor {
171
175
  *
172
176
  * If the user function returns a promise, it is considered asynchronous:
173
177
  * ```js
174
- * import { gotScraping } from 'got-scraping';
175
- *
176
178
  * await Actor.main(() => {
177
179
  * // My asynchronous function that returns a promise
178
- * return gotScraping('http://www.example.com').then((html) => {
179
- * console.log(html);
180
- * });
180
+ * return fetch('http://www.example.com')
181
+ * .then((response) => response.text())
182
+ * .then((html) => {
183
+ * console.log(html);
184
+ * });
181
185
  * });
182
186
  * ```
183
187
  *
184
188
  * To simplify your code, you can take advantage of the `async`/`await` keywords:
185
189
  *
186
190
  * ```js
187
- * import { gotScraping } from 'got-scraping';
188
- *
189
191
  * await Actor.main(async () => {
190
192
  * // My asynchronous function
191
- * const html = await request('http://www.example.com');
193
+ * const html = await fetch('http://www.example.com').then((response) => response.text());
192
194
  * console.log(html);
193
195
  * });
194
196
  * ```
@@ -210,10 +212,8 @@ class Actor {
210
212
  await this.exit(options);
211
213
  }
212
214
  catch (err) {
213
- log_1.default.exception(err, err.message);
214
- await this.exit({
215
- exitCode: exports.EXIT_CODES.ERROR_USER_FUNCTION_THREW,
216
- });
215
+ log.exception(err, err.message);
216
+ await this.exit({ ...options, exitCode: EXIT_CODES.ERROR_USER_FUNCTION_THREW });
217
217
  }
218
218
  return ret;
219
219
  })();
@@ -223,99 +223,121 @@ class Actor {
223
223
  */
224
224
  async init(options = {}) {
225
225
  if (this.initialized) {
226
- log_1.default.debug(`Actor SDK was already initialized`);
226
+ log.debug(`Actor SDK was already initialized`);
227
227
  return;
228
228
  }
229
229
  // If the warning about forgotten init call was emitted, we will not continue the init procedure.
230
- if (this.warnedAboutMissingInitCall) {
230
+ if (this.#warnedAboutMissingInitCall) {
231
231
  throw new Error([
232
232
  'Actor.init() was called after a method that would access a storage client was used.',
233
233
  'This in an invalid state. Please make sure to call Actor.init() before such methods are called.',
234
234
  ].join('\n'));
235
235
  }
236
236
  this.initialized = true;
237
- (0, utils_js_1.checkCrawleeVersion)();
238
- log_1.default.info('System info', (0, utils_js_1.getSystemInfo)());
239
- // reset global config instance to respect APIFY_ prefixed env vars
240
- core_1.Configuration.globalConfig = configuration_js_1.Configuration.getGlobalConfig();
237
+ checkCrawleeVersion();
238
+ log.info('System info', getSystemInfo());
239
+ // Register this Actor's config as the global one so crawlee storages and
240
+ // the event manager resolve the same instance (`availableMemoryRatio` /
241
+ // `disableBrowserSandbox` at-home defaults now live in `Configuration`).
242
+ serviceLocator.setConfiguration(this.configuration);
243
+ this.#requestQueueAccess = options.requestQueueAccess ?? 'single';
241
244
  if (this.isAtHome()) {
242
- this.config.set('availableMemoryRatio', 1);
243
- this.config.set('disableBrowserSandbox', true); // for browser launcher, adds `--no-sandbox` to args
244
- this.config.useStorageClient(this.apifyClient);
245
- this.config.useEventManager(this.eventManager);
245
+ serviceLocator.setEventManager(this.eventManager);
246
+ }
247
+ if (!serviceLocator.getServicesIfSet().storageBackend) {
248
+ this.installStorageBackend(options.storage ?? this.#storageBackend);
246
249
  }
247
250
  else if (options.storage) {
248
- this.config.useStorageClient(options.storage);
251
+ this.installStorageBackend(options.storage);
249
252
  }
250
- // Init the event manager the config uses
251
- await this.config.getEventManager().init();
252
- log_1.default.debug(`Events initialized`);
253
253
  // Register handlers for aborting and migrating events for automatic graceful shutdown.
254
254
  // - aborting: calls Actor.exit() to terminate the run gracefully
255
255
  // - migrating: calls Actor.reboot() to speed up migration (the run continues on a new worker)
256
256
  // Using setTimeout to avoid deadlock with waitForAllListenersToComplete() in exit()/reboot()
257
257
  if (options.gracefulShutdown !== false) {
258
258
  const delay = options.gracefulShutdownDelayMillis ?? 0;
259
- this.gracefulShutdownHandlers.aborting = () => {
259
+ this.#gracefulShutdownHandlers.aborting = () => {
260
260
  setTimeout(() => {
261
261
  this.exit().catch((err) => {
262
- log_1.default.exception(err, 'Failed to exit gracefully');
262
+ log.exception(err, 'Failed to exit gracefully');
263
263
  });
264
264
  }, delay);
265
265
  };
266
- this.on(consts_1.ACTOR_EVENT_NAMES.ABORTING, this.gracefulShutdownHandlers.aborting);
267
- this.gracefulShutdownHandlers.migrating = () => {
266
+ this.on(ACTOR_EVENT_NAMES.ABORTING, this.#gracefulShutdownHandlers.aborting);
267
+ this.#gracefulShutdownHandlers.migrating = () => {
268
268
  setTimeout(() => {
269
269
  this.reboot().catch((err) => {
270
- log_1.default.exception(err, 'Failed to reboot on migration');
270
+ log.exception(err, 'Failed to reboot on migration');
271
271
  });
272
272
  }, delay);
273
273
  };
274
- this.on(consts_1.ACTOR_EVENT_NAMES.MIGRATING, this.gracefulShutdownHandlers.migrating);
274
+ this.on(ACTOR_EVENT_NAMES.MIGRATING, this.#gracefulShutdownHandlers.migrating);
275
+ }
276
+ // Crawlee crawlers, for instance, broadcast their status messages as `statusMessage` events.
277
+ this.#statusMessageForwarder = async ({ message, isStatusMessageTerminal }) => this.#updateRunStatusMessage(message, isStatusMessageTerminal);
278
+ this.on(EventType.STATUS_MESSAGE, this.#statusMessageForwarder);
279
+ // Attach listeners queued before init(), then connect to the platform events only after all handlers
280
+ // are registered, so that an event sent right after the connection opens (e.g. an already pending
281
+ // `aborting`) is not missed.
282
+ const events = serviceLocator.getEventManager();
283
+ if (this.#pendingListeners.length > 0) {
284
+ for (const [event, listener] of this.#pendingListeners) {
285
+ events.on(event, listener);
286
+ }
287
+ log.debug(`Attached ${this.#pendingListeners.length} listener(s) registered before Actor.init()`);
288
+ this.#pendingListeners = [];
275
289
  }
276
- await (0, core_1.purgeDefaultStorages)({
277
- config: this.config,
290
+ await events.init();
291
+ log.debug(`Events initialized`);
292
+ await purgeDefaultStorages({
293
+ configuration: this.configuration,
278
294
  onlyPurgeOnce: true,
279
295
  });
280
- log_1.default.debug(`Default storages purged`);
281
- configuration_js_1.Configuration.storage.enterWith(this.config);
282
- await this.chargingManager.init();
283
- log_1.default.debug(`ChargingManager initialized`, this.chargingManager.getPricingInfo());
296
+ log.debug(`Default storages purged`);
297
+ await this.#childRunTracker.load();
298
+ await this.#chargingManager.init();
299
+ log.debug(`ChargingManager initialized`, this.#chargingManager.getPricingInfo());
300
+ // Only knowable once the pricing is loaded. Reachable with a caller-supplied backend or one
301
+ // registered with crawlee directly; the storages the Actor installs itself are wrapped.
302
+ if (this.#chargingManager.isPayPerEvent && !this.#chargesDefaultDatasetItems()) {
303
+ log.warning('Items pushed to the default dataset will not be charged for, because this run does not use Apify ' +
304
+ 'storage - the platform only counts items it stores itself.');
305
+ }
284
306
  }
285
307
  /**
286
308
  * @ignore
287
309
  */
288
310
  async exit(messageOrOptions, options = {}) {
289
311
  // Prevent double-exit from graceful shutdown handlers
290
- if (this.isExiting) {
291
- log_1.default.debug('Actor.exit() called while already exiting, skipping');
312
+ if (this.#isExiting) {
313
+ log.debug('Actor.exit() called while already exiting, skipping');
292
314
  return;
293
315
  }
294
- this.isExiting = true;
316
+ this.#isExiting = true;
295
317
  options =
296
318
  typeof messageOrOptions === 'string'
297
319
  ? { ...options, statusMessage: messageOrOptions }
298
320
  : { ...messageOrOptions, ...options };
299
- options.exit ?? (options.exit = true);
300
- options.exitCode ?? (options.exitCode = exports.EXIT_CODES.SUCCESS);
301
- options.timeoutSecs ?? (options.timeoutSecs = 30);
302
- this._ensureActorInit('exit');
303
- const client = this.config.getStorageClient();
304
- const events = this.config.getEventManager();
321
+ options.exit ??= true;
322
+ options.exitCode ??= EXIT_CODES.SUCCESS;
323
+ options.timeoutSecs ??= 30;
324
+ this.ensureActorInit('exit');
325
+ const client = serviceLocator.getStorageBackend();
326
+ const events = serviceLocator.getEventManager();
305
327
  // Remove graceful shutdown handlers to prevent them from interfering with exit
306
- if (this.gracefulShutdownHandlers.aborting) {
307
- this.off(consts_1.ACTOR_EVENT_NAMES.ABORTING, this.gracefulShutdownHandlers.aborting);
328
+ if (this.#gracefulShutdownHandlers.aborting) {
329
+ this.off(ACTOR_EVENT_NAMES.ABORTING, this.#gracefulShutdownHandlers.aborting);
308
330
  }
309
- if (this.gracefulShutdownHandlers.migrating) {
310
- this.off(consts_1.ACTOR_EVENT_NAMES.MIGRATING, this.gracefulShutdownHandlers.migrating);
331
+ if (this.#gracefulShutdownHandlers.migrating) {
332
+ this.off(ACTOR_EVENT_NAMES.MIGRATING, this.#gracefulShutdownHandlers.migrating);
311
333
  }
312
334
  // Close the event manager and emit the final PERSIST_STATE event
313
335
  await events.close();
314
- log_1.default.debug(`Events closed`);
336
+ log.debug(`Events closed`);
315
337
  // Emit the exit event
316
- events.emit("exit" /* EventType.EXIT */, options);
338
+ events.emit(EventType.EXIT, options);
317
339
  // Wait for all event listeners to be processed
318
- log_1.default.debug(`Waiting for all event listeners to complete their execution (with ${options.timeoutSecs} seconds timeout)`);
340
+ log.debug(`Waiting for all event listeners to complete their execution (with ${options.timeoutSecs} seconds timeout)`);
319
341
  if (options.exit) {
320
342
  // `addTimeoutToPromise` is a cooperative timeout. This ensures that the process exits
321
343
  // after the timeout, even if the event listeners don't trigger the timeout.
@@ -323,13 +345,18 @@ class Actor {
323
345
  process.exit(options.exitCode);
324
346
  }, options.timeoutSecs * 1000);
325
347
  }
326
- await (0, timeout_1.addTimeoutToPromise)(async () => {
348
+ await addTimeoutToPromise(async () => {
327
349
  await events.waitForAllListenersToComplete();
350
+ // The final status messages have been forwarded by now; stop listening so
351
+ // that a periodic one can't overwrite the terminal message set below.
352
+ if (this.#statusMessageForwarder) {
353
+ this.off(EventType.STATUS_MESSAGE, this.#statusMessageForwarder);
354
+ }
328
355
  if (client.teardown) {
329
356
  let finished = false;
330
357
  setTimeout(() => {
331
358
  if (!finished) {
332
- log_1.default.info('Waiting for the storage to write its state to file system.');
359
+ log.info('Waiting for the storage to write its state to file system.');
333
360
  }
334
361
  }, 1000);
335
362
  await client.teardown();
@@ -341,7 +368,7 @@ class Actor {
341
368
  level: options.exitCode > 0 ? 'ERROR' : 'INFO',
342
369
  });
343
370
  // Waiting 1ms is enough for the network request to be sent. We don't need to wait for the response.
344
- await Promise.race([statusMessagePromise, (0, utils_1.sleep)(1)]);
371
+ await Promise.race([statusMessagePromise, sleep(1)]);
345
372
  }
346
373
  }, options.timeoutSecs * 1000, `Waiting for all event listeners to complete their execution timed out after ${options.timeoutSecs} seconds`).catch(() => {
347
374
  if (options.exit) {
@@ -350,7 +377,7 @@ class Actor {
350
377
  });
351
378
  // Reset the flag so the instance can be reused (e.g., in tests or when exit is false).
352
379
  // When process.exit() actually terminates the process, this line is never reached - which is fine.
353
- this.isExiting = false;
380
+ this.#isExiting = false;
354
381
  if (!options.exit) {
355
382
  return;
356
383
  }
@@ -360,19 +387,30 @@ class Actor {
360
387
  * @ignore
361
388
  */
362
389
  async fail(messageOrOptions, options = {}) {
363
- return this.exit(messageOrOptions, { exitCode: 1, ...options });
390
+ const exitCode = options.exitCode ?? (typeof messageOrOptions === 'object' ? messageOrOptions.exitCode : undefined) ?? 1;
391
+ return this.exit(messageOrOptions, { ...options, exitCode });
364
392
  }
365
393
  /**
366
394
  * @ignore
367
395
  */
368
396
  on(event, listener) {
369
- this.config.getEventManager().on(event, listener);
397
+ // Before init() the service locator must stay untouched, otherwise it
398
+ // creates a default Configuration that init() then conflicts with.
399
+ if (!this.initialized) {
400
+ this.#pendingListeners.push([event, listener]);
401
+ return;
402
+ }
403
+ serviceLocator.getEventManager().on(event, listener);
370
404
  }
371
405
  /**
372
406
  * @ignore
373
407
  */
374
408
  off(event, listener) {
375
- this.config.getEventManager().off(event, listener);
409
+ if (!this.initialized) {
410
+ this.#pendingListeners = this.#pendingListeners.filter(([pendingEvent, pendingListener]) => pendingEvent !== event || (listener !== undefined && pendingListener !== listener));
411
+ return;
412
+ }
413
+ serviceLocator.getEventManager().off(event, listener);
376
414
  }
377
415
  /**
378
416
  * Runs an Actor on the Apify platform using the current user account (determined by the `APIFY_TOKEN` environment variable).
@@ -392,17 +430,33 @@ class Actor {
392
430
  * @param actorId
393
431
  * Allowed formats are `username/actor-name`, `userId/actor-name` or Actor ID.
394
432
  * @param [input]
395
- * Input for the Actor. If it is an object, it will be stringified to
396
- * JSON and its content type set to `application/json; charset=utf-8`.
397
- * Otherwise the `options.contentType` parameter must be provided.
433
+ * Input for the Actor. A plain object is stringified to JSON with content type
434
+ * `application/json; charset=utf-8`. A `Buffer` is sent as-is and needs `options.contentType`.
398
435
  * @param [options]
399
436
  * @ignore
400
437
  */
401
438
  async call(actorId, input, options = {}) {
402
- const timeout = options.timeout === 'inherit' ? this.getRemainingTimeSecs() : options.timeout;
403
- const { token, ...rest } = options;
439
+ const runTimeoutSecs = options.timeout === 'inherit' ? this.getRemainingTimeSecs() : options.timeout;
440
+ const { token, timeout: _timeout, runName, abortWithParent = false, ...rest } = options;
404
441
  const client = token ? this.newClient({ token }) : this.apifyClient;
405
- return client.actor(actorId).call(input, { ...rest, timeout });
442
+ if (abortWithParent && !runName)
443
+ throw new Error('`abortWithParent` requires `runName`.');
444
+ if (!runName)
445
+ return client.actor(actorId).call(input, { ...rest, runTimeoutSecs });
446
+ const { waitSecs, log, timeoutSecs = 'noTimeout', signal, ...otherOptions } = rest;
447
+ const startOptions = { ...otherOptions, runTimeoutSecs, timeoutSecs, signal };
448
+ const { run, resumed } = await this.#childRunTracker.startOrResumeChildRun(client, runName, { type: 'actor', id: actorId, input }, startOptions, abortWithParent, async () => client.actor(actorId).start(input, startOptions));
449
+ // The earlier part of a resumed run's log was already redirected before the migration.
450
+ const streamedLog = await client.run(run.id).getStreamedLog({ toLog: log, fromStart: !resumed, signal });
451
+ streamedLog?.start();
452
+ try {
453
+ const finishedRun = await client.run(run.id).waitForFinish({ waitSecs, timeoutSecs, signal });
454
+ await this.#childRunTracker.update(runName, finishedRun);
455
+ return finishedRun;
456
+ }
457
+ finally {
458
+ await streamedLog?.stop();
459
+ }
406
460
  }
407
461
  /**
408
462
  * Runs an Actor on the Apify platform using the current user account (determined by the `APIFY_TOKEN` environment variable),
@@ -422,17 +476,22 @@ class Actor {
422
476
  * @param actorId
423
477
  * Allowed formats are `username/actor-name`, `userId/actor-name` or Actor ID.
424
478
  * @param [input]
425
- * Input for the Actor. If it is an object, it will be stringified to
426
- * JSON and its content type set to `application/json; charset=utf-8`.
427
- * Otherwise the `options.contentType` parameter must be provided.
479
+ * Input for the Actor. A plain object is stringified to JSON with content type
480
+ * `application/json; charset=utf-8`. A `Buffer` is sent as-is and needs `options.contentType`.
428
481
  * @param [options]
429
482
  * @ignore
430
483
  */
431
484
  async start(actorId, input, options = {}) {
432
- const timeout = options.timeout === 'inherit' ? this.getRemainingTimeSecs() : options.timeout;
433
- const { token, ...rest } = options;
485
+ const runTimeoutSecs = options.timeout === 'inherit' ? this.getRemainingTimeSecs() : options.timeout;
486
+ const { token, timeout: _timeout, runName, abortWithParent = false, ...rest } = options;
434
487
  const client = token ? this.newClient({ token }) : this.apifyClient;
435
- return client.actor(actorId).start(input, { ...rest, timeout });
488
+ if (abortWithParent && !runName)
489
+ throw new Error('`abortWithParent` requires `runName`.');
490
+ if (!runName)
491
+ return client.actor(actorId).start(input, { ...rest, runTimeoutSecs });
492
+ const startOptions = { ...rest, runTimeoutSecs };
493
+ const { run } = await this.#childRunTracker.startOrResumeChildRun(client, runName, { type: 'actor', id: actorId, input }, startOptions, abortWithParent, async () => client.actor(actorId).start(input, startOptions));
494
+ return run;
436
495
  }
437
496
  /**
438
497
  * Aborts given Actor run on the Apify platform using the current user account (determined by the `APIFY_TOKEN` environment variable).
@@ -452,12 +511,35 @@ class Actor {
452
511
  async abort(runId, options = {}) {
453
512
  const { token, statusMessage, ...rest } = options;
454
513
  const client = token ? this.newClient({ token }) : this.apifyClient;
514
+ const runClient = client.run(runId);
455
515
  if (statusMessage) {
456
- await this.setStatusMessage(statusMessage, {
457
- isStatusMessageTerminal: true,
458
- });
516
+ await runClient.update({ statusMessage, isStatusMessageTerminal: true });
459
517
  }
460
- return client.run(runId).abort(rest);
518
+ return runClient.abort(rest);
519
+ }
520
+ /**
521
+ * Resurrects a finished Actor run on the Apify platform using the current user account (determined by the `APIFY_TOKEN` environment variable).
522
+ *
523
+ * Only finished runs (SUCCEEDED, FAILED, ABORTED or TIMED-OUT) can be resurrected. The run goes back to the RUNNING
524
+ * status and keeps its default storages. Options you leave out keep the values of the original run.
525
+ *
526
+ * The result of the function is an {@link ActorRun} object that contains details about the Actor run.
527
+ *
528
+ * For more information about Actors, read the
529
+ * [documentation](https://docs.apify.com/actor).
530
+ *
531
+ * **Example usage:**
532
+ *
533
+ * ```js
534
+ * const run = await Actor.resurrect(runId);
535
+ * ```
536
+ * @ignore
537
+ */
538
+ async resurrect(runId, options = {}) {
539
+ const runTimeoutSecs = options.timeout === 'inherit' ? this.getRemainingTimeSecs() : options.timeout;
540
+ const { token, timeout: _timeout, ...rest } = options;
541
+ const client = token ? this.newClient({ token }) : this.apifyClient;
542
+ return client.run(runId).resurrect({ ...rest, runTimeoutSecs });
461
543
  }
462
544
  /**
463
545
  * Runs an actor task on the Apify platform using the current user account (determined by the `APIFY_TOKEN` environment variable).
@@ -486,10 +568,70 @@ class Actor {
486
568
  * @ignore
487
569
  */
488
570
  async callTask(taskId, input, options = {}) {
489
- const timeout = options.timeout === 'inherit' ? this.getRemainingTimeSecs() : options.timeout;
490
- const { token, ...rest } = options;
571
+ const runTimeoutSecs = options.timeout === 'inherit' ? this.getRemainingTimeSecs() : options.timeout;
572
+ const { token, timeout: _timeout, runName, abortWithParent = false, ...rest } = options;
491
573
  const client = token ? this.newClient({ token }) : this.apifyClient;
492
- return client.task(taskId).call(input, { ...rest, timeout });
574
+ if (abortWithParent && !runName)
575
+ throw new Error('`abortWithParent` requires `runName`.');
576
+ if (!runName)
577
+ return client.task(taskId).call(input, { ...rest, runTimeoutSecs });
578
+ const { waitSecs, timeoutSecs = 'noTimeout', signal, ...otherOptions } = rest;
579
+ const startOptions = { ...otherOptions, runTimeoutSecs, timeoutSecs, signal };
580
+ const { run } = await this.#childRunTracker.startOrResumeChildRun(client, runName, { type: 'task', id: taskId, input }, startOptions, abortWithParent, async () => client.task(taskId).start(input, startOptions));
581
+ const finishedRun = await client.run(run.id).waitForFinish({ waitSecs, timeoutSecs, signal });
582
+ await this.#childRunTracker.update(runName, finishedRun);
583
+ return finishedRun;
584
+ }
585
+ /**
586
+ * Clients for the child runs started with the `runName` option, keyed by that name, including the runs started
587
+ * before a migration or resurrection of this run. Each client points to the current run under its name.
588
+ *
589
+ * ```js
590
+ * await Actor.childRuns['my-child'].waitForFinish();
591
+ * ```
592
+ *
593
+ * A run started with a custom `token` uses that token, except for a run started before a migration or
594
+ * resurrection, which uses the default client. The tracked runs, including the earlier runs replaced
595
+ * under the same name, are stored in the default key-value store under the `__ACTOR_CHILD_RUNS` key.
596
+ */
597
+ get childRuns() {
598
+ this.ensureActorInit('childRuns');
599
+ return this.#childRunTracker.getRunClients(this.apifyClient);
600
+ }
601
+ /**
602
+ * Runs an Actor task on the Apify platform using the current user account (determined by the `APIFY_TOKEN` environment variable),
603
+ * unlike `Actor.callTask`, this method just starts the run without waiting for finish.
604
+ *
605
+ * The result of the function is an {@link ActorRun} object that contains details about the Actor run.
606
+ *
607
+ * For more information about Actor tasks, read the [documentation](https://docs.apify.com/tasks).
608
+ *
609
+ * **Example usage:**
610
+ *
611
+ * ```js
612
+ * const run = await Actor.startTask('bob/some-task');
613
+ * ```
614
+ *
615
+ * @param taskId
616
+ * Allowed formats are `username/task-name`, `userId/task-name` or task ID.
617
+ * @param [input]
618
+ * Input overrides for the Actor task. If it is an object, it will be stringified to
619
+ * JSON and its content type set to `application/json; charset=utf-8`.
620
+ * Provided input will be merged with Actor task input.
621
+ * @param [options]
622
+ * @ignore
623
+ */
624
+ async startTask(taskId, input, options = {}) {
625
+ const runTimeoutSecs = options.timeout === 'inherit' ? this.getRemainingTimeSecs() : options.timeout;
626
+ const { token, timeout: _timeout, runName, abortWithParent = false, ...rest } = options;
627
+ const client = token ? this.newClient({ token }) : this.apifyClient;
628
+ if (abortWithParent && !runName)
629
+ throw new Error('`abortWithParent` requires `runName`.');
630
+ if (!runName)
631
+ return client.task(taskId).start(input, { ...rest, runTimeoutSecs });
632
+ const startOptions = { ...rest, runTimeoutSecs };
633
+ const { run } = await this.#childRunTracker.startOrResumeChildRun(client, runName, { type: 'task', id: taskId, input }, startOptions, abortWithParent, async () => client.task(taskId).start(input, startOptions));
634
+ return run;
493
635
  }
494
636
  /**
495
637
  * Transforms this Actor run to an Actor run of a given Actor. The system stops the current container and starts
@@ -499,22 +641,21 @@ class Actor {
499
641
  * @param targetActorId
500
642
  * Either `username/actor-name` or Actor ID of an Actor to which we want to metamorph.
501
643
  * @param [input]
502
- * Input for the Actor. If it is an object, it will be stringified to
503
- * JSON and its content type set to `application/json; charset=utf-8`.
504
- * Otherwise, the `options.contentType` parameter must be provided.
644
+ * Input for the Actor. A plain object is stringified to JSON with content type
645
+ * `application/json; charset=utf-8`. A `Buffer` is sent as-is and needs `options.contentType`.
505
646
  * @param [options]
506
647
  * @ignore
507
648
  */
508
649
  async metamorph(targetActorId, input, options = {}) {
509
650
  if (!this.isAtHome()) {
510
- log_1.default.warning('Actor.metamorph() is only supported when running on the Apify platform.');
651
+ log.warning('Actor.metamorph() is only supported when running on the Apify platform.');
511
652
  return;
512
653
  }
513
- const { customAfterSleepMillis = this.config.get('metamorphAfterSleepMillis'), ...metamorphOpts } = options;
514
- const runId = this.config.get('actorRunId');
654
+ const { customAfterSleepMillis = this.configuration.metamorphAfterSleepMillis, ...metamorphOpts } = options;
655
+ const runId = this.configuration.actorRunId;
515
656
  await this.apifyClient.run(runId).metamorph(targetActorId, input, metamorphOpts);
516
657
  // Wait some time for container to be stopped.
517
- await (0, utils_1.sleep)(customAfterSleepMillis);
658
+ await sleep(customAfterSleepMillis);
518
659
  }
519
660
  /**
520
661
  * Internally reboots this Actor. The system stops the current container and starts
@@ -524,34 +665,34 @@ class Actor {
524
665
  * @ignore
525
666
  */
526
667
  async reboot(options = {}) {
527
- this._ensureActorInit('reboot');
668
+ this.ensureActorInit('reboot');
528
669
  if (!this.isAtHome()) {
529
- log_1.default.warning('Actor.reboot() is only supported when running on the Apify platform.');
670
+ log.warning('Actor.reboot() is only supported when running on the Apify platform.');
530
671
  return;
531
672
  }
532
- if (this.isRebooting) {
533
- log_1.default.debug('Actor is already rebooting, skipping the additional reboot call.');
673
+ if (this.#isRebooting) {
674
+ log.debug('Actor is already rebooting, skipping the additional reboot call.');
534
675
  return;
535
676
  }
536
- this.isRebooting = true;
677
+ this.#isRebooting = true;
537
678
  // Waiting for all the listeners to finish, as `.reboot()` kills the container.
538
679
  await Promise.all([
539
680
  // `persistState` for individual RequestLists, RequestQueue... instances to be persisted
540
- ...this.config
681
+ ...serviceLocator
541
682
  .getEventManager()
542
- .listeners("persistState" /* EventType.PERSIST_STATE */)
683
+ .listeners(EventType.PERSIST_STATE)
543
684
  .map(async (x) => x({})),
544
685
  // `migrating` to pause Apify crawlers
545
- ...this.config
686
+ ...serviceLocator
546
687
  .getEventManager()
547
- .listeners("migrating" /* EventType.MIGRATING */)
688
+ .listeners(EventType.MIGRATING)
548
689
  .map(async (x) => x({})),
549
690
  ]);
550
- const runId = this.config.get('actorRunId');
691
+ const runId = this.configuration.actorRunId;
551
692
  await this.apifyClient.run(runId).reboot();
552
693
  // Wait some time for container to be stopped.
553
- const { customAfterSleepMillis = this.config.get('metamorphAfterSleepMillis') } = options;
554
- await (0, utils_1.sleep)(customAfterSleepMillis);
694
+ const { customAfterSleepMillis = this.configuration.metamorphAfterSleepMillis } = options;
695
+ await sleep(customAfterSleepMillis);
555
696
  }
556
697
  /**
557
698
  * Creates an ad-hoc webhook for the current Actor run, which lets you receive a notification when the Actor run finished or failed.
@@ -566,25 +707,27 @@ class Actor {
566
707
  * @ignore
567
708
  */
568
709
  async addWebhook(options) {
569
- (0, ow_1.default)(options, ow_1.default.object.exactShape({
570
- eventTypes: ow_1.default.array.ofType(ow_1.default.string),
571
- requestUrl: ow_1.default.string,
572
- payloadTemplate: ow_1.default.optional.string,
573
- idempotencyKey: ow_1.default.optional.string,
574
- headersTemplate: ow_1.default.optional.string,
575
- description: ow_1.default.optional.string,
576
- ignoreSslErrors: ow_1.default.optional.boolean,
577
- doNotRetry: ow_1.default.optional.boolean,
578
- shouldInterpolateStrings: ow_1.default.optional.boolean,
579
- isApifyIntegration: ow_1.default.optional.boolean,
580
- }));
710
+ parseArgument(options, z
711
+ .object({
712
+ eventTypes: z.array(z.string()),
713
+ requestUrl: z.string(),
714
+ payloadTemplate: z.string().optional(),
715
+ idempotencyKey: z.string().optional(),
716
+ headersTemplate: z.string().optional(),
717
+ description: z.string().optional(),
718
+ ignoreSslErrors: z.boolean().optional(),
719
+ doNotRetry: z.boolean().optional(),
720
+ shouldInterpolateStrings: z.boolean().optional(),
721
+ isApifyIntegration: z.boolean().optional(),
722
+ })
723
+ .strict());
581
724
  if (!this.isAtHome()) {
582
- log_1.default.warning('Actor.addWebhook() is only supported when running on the Apify platform. The webhook will not be invoked.');
725
+ log.warning('Actor.addWebhook() is only supported when running on the Apify platform. The webhook will not be invoked.');
583
726
  return undefined;
584
727
  }
585
- const runId = this.config.get('actorRunId');
728
+ const runId = this.configuration.actorRunId;
586
729
  if (!runId) {
587
- throw new Error(`Environment variable ${consts_1.ACTOR_ENV_VARS.RUN_ID} is not set!`);
730
+ throw new Error(`Environment variable ${ACTOR_ENV_VARS.RUN_ID} is not set!`);
588
731
  }
589
732
  return this.apifyClient.webhooks().create({
590
733
  ...options,
@@ -597,45 +740,47 @@ class Actor {
597
740
  /**
598
741
  * Sets the status message for the current Actor run.
599
742
  *
600
- * @returns The return value is the Run object.
743
+ * @returns The updated Run object, or `undefined` when no run was updated: when run locally,
744
+ * or when the update failed or timed out (a warning is logged in that case).
601
745
  * For more information, see the [Actor Runs](https://docs.apify.com/api/v2#/reference/actor-runs/) API endpoints.
602
746
  * @ignore
603
747
  */
604
748
  async setStatusMessage(statusMessage, options) {
605
749
  const { isStatusMessageTerminal, level } = options || {};
606
- (0, ow_1.default)(statusMessage, ow_1.default.string);
607
- (0, ow_1.default)(isStatusMessageTerminal, ow_1.default.optional.boolean);
608
- this._ensureActorInit('setStatusMessage');
750
+ parseArgument(statusMessage, z.string());
751
+ parseArgument(isStatusMessageTerminal, z.boolean().optional());
752
+ this.ensureActorInit('setStatusMessage');
609
753
  const loggedStatusMessage = `[Status message]: ${statusMessage}`;
610
754
  switch (level) {
611
755
  case 'DEBUG':
612
- log_1.default.debug(loggedStatusMessage);
756
+ log.debug(loggedStatusMessage);
613
757
  break;
614
758
  case 'WARNING':
615
- log_1.default.warning(loggedStatusMessage);
759
+ log.warning(loggedStatusMessage);
616
760
  break;
617
761
  case 'ERROR':
618
- log_1.default.error(loggedStatusMessage);
762
+ log.error(loggedStatusMessage);
619
763
  break;
620
764
  default:
621
- log_1.default.info(loggedStatusMessage);
765
+ log.info(loggedStatusMessage);
622
766
  break;
623
767
  }
624
- const client = this.config.getStorageClient();
625
- // just to be sure, this should be fast
626
- await (0, timeout_1.addTimeoutToPromise)(async () => client.setStatusMessage(statusMessage, {
627
- isStatusMessageTerminal,
628
- level,
629
- }), 1000, 'Setting status message timed out after 1s').catch((e) => log_1.default.warning(e.message));
630
- const runId = this.config.get('actorRunId');
631
- if (runId) {
632
- // just to be sure, this should be fast
633
- const run = await (0, timeout_1.addTimeoutToPromise)(async () => this.apifyClient.run(runId).get(), 1000, 'Getting the current run timed out after 1s').catch((e) => log_1.default.warning(e.message));
634
- if (run) {
635
- return run;
636
- }
768
+ return this.#updateRunStatusMessage(statusMessage, isStatusMessageTerminal);
769
+ }
770
+ /**
771
+ * Propagates a status message to the current run, without logging it locally.
772
+ * Resolves `undefined` when there is no run to update, or when the update failed or timed out.
773
+ */
774
+ async #updateRunStatusMessage(statusMessage, isStatusMessageTerminal) {
775
+ const runId = this.configuration.actorRunId;
776
+ if (!runId) {
777
+ return undefined;
637
778
  }
638
- return {};
779
+ // just to be sure, this should be fast
780
+ return addTimeoutToPromise(async () => this.apifyClient.run(runId).update({ statusMessage, isStatusMessageTerminal }), 1000, 'Setting status message timed out after 1s').catch((e) => {
781
+ log.warning(e.message);
782
+ return undefined;
783
+ });
639
784
  }
640
785
  /**
641
786
  * Stores an object or an array of objects to the default {@link Dataset} of the current Actor run.
@@ -657,27 +802,63 @@ class Actor {
657
802
  * **IMPORTANT**: Make sure to use the `await` keyword when calling `pushData()`,
658
803
  * otherwise the Actor process might finish before the data are stored!
659
804
  *
805
+ * Inside a crawlee storage transaction, the items are stored - and charged for - at commit time,
806
+ * so the returned counts are zero and charging for an explicit `eventName` is rejected outright.
807
+ *
660
808
  * @param item Object or array of objects containing data to be stored in the default dataset.
661
809
  * The objects must be serializable to JSON and the JSON representation of each object must be smaller than 9MB.
662
810
  * @param eventName If provided, the method will attempt to charge for the event for each pushed item.
663
811
  * @ignore
664
812
  */
665
813
  async pushData(item, eventName) {
666
- this._ensureActorInit('pushData');
814
+ this.ensureActorInit('pushData');
667
815
  if (eventName?.startsWith('apify-')) {
668
816
  throw new Error(`Cannot charge for synthetic event '${eventName}' manually`);
669
817
  }
818
+ if (eventName !== undefined) {
819
+ rejectOperationInTransaction(`Actor.pushData() with the event name '${eventName}'`, 'the items are stored when the transaction commits, but the charge happens right away, ' +
820
+ 'so a rolled-back request would be billed for items that were never stored.');
821
+ }
670
822
  const dataset = await this.openDataset();
671
- // Two code paths for charging:
672
- // 1. Intercepted client: PatchedDatasetClient intercepts pushItems() calls, handling charging
673
- // internally. This is needed because Crawlee's Dataset may call pushItems() directly,
674
- // bypassing Actor.pushData(). We propagate eventName via AsyncLocalStorage context.
675
- // 2. Direct charging: When using a non-patched client (e.g., forceCloud option or custom client),
676
- // we handle charging here before delegating to the dataset.
677
- if (this.usesPushDataInterception(dataset)) {
678
- return await this.pushDataViaInterceptedClient(dataset, item, eventName);
823
+ const items = Array.isArray(item) ? item : [item];
824
+ // `Actor.pushData()` historically worked even without calling `Actor.init()`.
825
+ // In that case, charging isn't configured, so just push the data through.
826
+ if (!this.#chargingManager.isInitialized) {
827
+ await dataset.pushData(items);
828
+ return { eventChargeLimitReached: false, chargedCount: 0, chargeableWithinLimit: {} };
679
829
  }
680
- return await this.pushDataWithExplicitCharging(dataset, item, eventName);
830
+ // The reservation below and the charge that acts on it have to stay under one lock, so that
831
+ // a concurrent push cannot charge in between. The dataset backend re-enters the same lock to
832
+ // charge the synthetic per-item event.
833
+ return await this.#chargingManager.withChargeLock(async () => {
834
+ if (eventName === undefined) {
835
+ // Nothing to charge here - the dataset backend charges the synthetic event for
836
+ // whatever it stores, so the result is read back off the charging state.
837
+ const chargedBefore = this.#chargingManager.getChargedEventCount(DEFAULT_DATASET_ITEM_EVENT);
838
+ await dataset.pushData(items);
839
+ return {
840
+ eventChargeLimitReached: this.#chargingManager.isEventChargeLimitReached(DEFAULT_DATASET_ITEM_EVENT),
841
+ chargedCount: this.#chargingManager.getChargedEventCount(DEFAULT_DATASET_ITEM_EVENT) - chargedBefore,
842
+ chargeableWithinLimit: this.#chargingManager.calculateChargeableWithinLimit(),
843
+ };
844
+ }
845
+ const limit = this.#chargingManager.calculatePushDataLimit(items.length, {
846
+ eventName,
847
+ // Pushing one item charges the synthetic per-item event too when the dataset backend
848
+ // is the charging one, so that price is part of what an item costs here. Only the Actor's
849
+ // own backend wraps the default dataset for charging, a caller-supplied one is left as is.
850
+ isDefaultDataset: serviceLocator.getStorageBackend() === this.#cachedStorageBackend,
851
+ });
852
+ if (limit === 0) {
853
+ return {
854
+ eventChargeLimitReached: items.length > 0,
855
+ chargedCount: 0,
856
+ chargeableWithinLimit: this.#chargingManager.calculateChargeableWithinLimit(),
857
+ };
858
+ }
859
+ await dataset.pushData(limit < items.length ? items.slice(0, limit) : items);
860
+ return await this.#chargingManager.charge({ eventName, count: limit });
861
+ });
681
862
  }
682
863
  /**
683
864
  * Opens a dataset and returns a promise resolving to an instance of the {@link Dataset} class.
@@ -691,50 +872,24 @@ class Actor {
691
872
  * @param [datasetIdOrName]
692
873
  * ID, name, or alias of the dataset to be opened. If `null` or `undefined`,
693
874
  * the function returns the default dataset associated with the Actor run.
694
- * You can also pass `{ alias: 'name' }` to open a dataset defined in the Actor's schema storages,
695
- * `{ id: 'abc' }` to open by explicit ID, or `{ name: 'abc' }` to open by explicit name.
875
+ * You can also pass `{ alias: 'abc' }` to open a run-scoped storage, `{ id: 'abc' }` to open by
876
+ * explicit ID, or `{ name: 'abc' }` to open by explicit name.
696
877
  * @param [options]
697
878
  * @ignore
698
879
  */
699
880
  async openDataset(datasetIdOrName, options = {}) {
700
- (0, ow_1.default)(options, ow_1.default.object.exactShape({
701
- forceCloud: ow_1.default.optional.boolean,
702
- }));
703
- this._ensureActorInit('openDataset');
704
- return this._openStorage(core_1.Dataset, datasetIdOrName, options);
881
+ parseArgument(options, z.object({ forceCloud: z.boolean().optional() }).strict());
882
+ this.ensureActorInit('openDataset');
883
+ return Dataset.open(datasetIdOrName ?? null, {
884
+ storageBackend: options.forceCloud
885
+ ? this.#storageBackend.getSuitableStorageBackend({ forceCloud: true })
886
+ : undefined,
887
+ });
705
888
  }
706
- /**
707
- * Gets a value from the default {@link KeyValueStore} associated with the current Actor run.
708
- *
709
- * This is just a convenient shortcut for {@link KeyValueStore.getValue}.
710
- * For example, calling the following code:
711
- * ```js
712
- * const value = await Actor.getValue('my-key');
713
- * ```
714
- *
715
- * is equivalent to:
716
- * ```js
717
- * const store = await Actor.openKeyValueStore();
718
- * const value = await store.getValue('my-key');
719
- * ```
720
- *
721
- * To store the value to the default key-value store, you can use the {@link Actor.setValue} function.
722
- *
723
- * For more information, see {@link Actor.openKeyValueStore}
724
- * and {@link KeyValueStore.getValue}.
725
- *
726
- * @param key Unique record key.
727
- * @returns
728
- * Returns a promise that resolves to an object, string
729
- * or [`Buffer`](https://nodejs.org/api/buffer.html), depending
730
- * on the MIME content type of the record, or `null`
731
- * if the record is missing.
732
- * @ignore
733
- */
734
- async getValue(key) {
735
- this._ensureActorInit('getValue');
889
+ async getValue(key, defaultValue) {
890
+ this.ensureActorInit('getValue');
736
891
  const store = await this.openKeyValueStore();
737
- return store.getValue(key);
892
+ return store.getValue(key, defaultValue);
738
893
  }
739
894
  /**
740
895
  * Stores or deletes a value in the default {@link KeyValueStore} associated with the current Actor run.
@@ -768,24 +923,28 @@ class Actor {
768
923
  * @ignore
769
924
  */
770
925
  async setValue(key, value, options = {}) {
771
- this._ensureActorInit('setValue');
926
+ this.ensureActorInit('setValue');
772
927
  const store = await this.openKeyValueStore();
773
928
  return store.setValue(key, value, options);
774
929
  }
775
930
  /**
776
931
  * Gets the Actor input value from the default {@link KeyValueStore} associated with the current Actor run.
777
932
  *
778
- * This is just a convenient shortcut for [`keyValueStore.getValue('INPUT')`](core/class/KeyValueStore#getValue).
779
- * For example, calling the following code:
780
- * ```js
781
- * const input = await Actor.getInput();
782
- * ```
933
+ * The input is the record stored under the configured input key (`ACTOR_INPUT_KEY`, default `INPUT`).
934
+ * A record stored as `application/octet-stream` — which is what a local input file without an
935
+ * extension is read as — is parsed with JSON5 when it parses, and returned as a `Buffer` otherwise.
783
936
  *
784
- * is equivalent to:
785
- * ```js
786
- * const store = await Actor.openKeyValueStore();
787
- * await store.getValue('INPUT');
788
- * ```
937
+ * When running locally, the input may instead be a `<inputKey>` or `<inputKey>.json` file in the current
938
+ * working directory. A storage backend that doesn't read the default key-value store's directory under
939
+ * the storage directory (e.g. in-memory storage) also gets the file `apify run` writes there.
940
+ *
941
+ * Google Sheets sharing links in `requestsFromUrl` entries (from the "Link remote text file" option) are
942
+ * replaced with the links of their CSV exports.
943
+ *
944
+ * Throws an {@link ActorInputError} when no input is found (`code: 'NOT_FOUND'`), when the input is
945
+ * found in more than one place (`'MULTIPLE_FILES'`), when a JSON input does not parse
946
+ * (`'PARSE_FAILED'`) or when its secret fields cannot be decrypted (`'DECRYPTION_FAILED'`). If your
947
+ * Actor can run without input, catch the `'NOT_FOUND'` case and rethrow the rest.
789
948
  *
790
949
  * Note that the `getInput()` function does not cache the value read from the key-value store.
791
950
  * If you need to use the input multiple times in your Actor,
@@ -797,40 +956,85 @@ class Actor {
797
956
  * @returns
798
957
  * Returns a promise that resolves to an object, string
799
958
  * or [`Buffer`](https://nodejs.org/api/buffer.html), depending
800
- * on the MIME content type of the record, or `null`
801
- * if the record is missing.
959
+ * on the MIME content type of the record.
960
+ * @throws {ActorInputError} When the input cannot be produced; see `code`.
802
961
  * @ignore
803
962
  */
804
963
  async getInput() {
805
- this._ensureActorInit('getInput');
806
- const inputSecretsPrivateKeyFile = this.config.get('inputSecretsPrivateKeyFile');
807
- const inputSecretsPrivateKeyPassphrase = this.config.get('inputSecretsPrivateKeyPassphrase');
808
- const rawInput = await this.getValue(this.config.get('inputKey'));
964
+ this.ensureActorInit('getInput');
965
+ const { inputKey, inputSecretsPrivateKeyFile, inputSecretsPrivateKeyPassphrase, storageDir, defaultKeyValueStoreId, } = this.configuration;
966
+ // Where `apify run` writes the input (apify-cli `getLocalKeyValueStorePath`).
967
+ const defaultStoreDir = join(storageDir, 'key_value_stores', defaultKeyValueStoreId);
968
+ const store = await this.openKeyValueStore();
969
+ const record = await store.getRecord(inputKey);
970
+ // Not a conflict check: under the file-system backend the record *is* the store directory's file.
971
+ const storeInput = record
972
+ ? parseInput(record.value, record.contentType, `the "${inputKey}" record of the default key-value store`)
973
+ : await this.readInputFromDirectory(inputKey, defaultStoreDir, 'default key-value store directory');
974
+ const cwdInput = await this.readInputFromDirectory(inputKey, process.cwd(), 'working directory');
975
+ if (storeInput != null && cwdInput != null) {
976
+ throw new ActorInputError('MULTIPLE_FILES', `Found the input both in the default key-value store and in a "${inputKey}" or "${inputKey}.json" file in the working directory. Keep only one of them.`);
977
+ }
978
+ const rawInput = storeInput ?? cwdInput;
979
+ if (rawInput == null) {
980
+ const locations = [`the "${inputKey}" record of the default key-value store`];
981
+ if (!this.configuration.isAtHome) {
982
+ locations.push(`a "${inputKey}" or "${inputKey}.json" file in the working or default key-value store directory`);
983
+ }
984
+ throw new ActorInputError('NOT_FOUND', `Input does not exist. Expected ${locations.join(' or ')}.`);
985
+ }
809
986
  let input = rawInput;
810
- if (ow_1.default.isValid(rawInput, ow_1.default.object.nonEmpty) &&
811
- inputSecretsPrivateKeyFile &&
812
- inputSecretsPrivateKeyPassphrase) {
813
- const privateKey = (0, node_crypto_1.createPrivateKey)({
814
- key: Buffer.from(inputSecretsPrivateKeyFile, 'base64'),
815
- passphrase: inputSecretsPrivateKeyPassphrase,
816
- });
817
- input = (0, input_secrets_1.decryptInputSecrets)({ input: rawInput, privateKey });
987
+ if (isNonEmptyObject(rawInput) && inputSecretsPrivateKeyFile && inputSecretsPrivateKeyPassphrase) {
988
+ try {
989
+ const privateKey = createPrivateKey({
990
+ key: Buffer.from(inputSecretsPrivateKeyFile, 'base64'),
991
+ passphrase: inputSecretsPrivateKeyPassphrase,
992
+ });
993
+ input = decryptInputSecrets({ input: rawInput, privateKey });
994
+ }
995
+ catch (cause) {
996
+ throw new ActorInputError('DECRYPTION_FAILED', 'Failed to decrypt the secret fields of the input.', {
997
+ cause,
998
+ });
999
+ }
818
1000
  }
819
- if (ow_1.default.isValid(input, ow_1.default.object.nonEmpty) && !Buffer.isBuffer(input)) {
820
- input = await this.inferDefaultsFromInputSchema(input);
1001
+ if (isNonEmptyObject(input) && !Buffer.isBuffer(input)) {
1002
+ input = fixGoogleSheetsUrls(await this.inferDefaultsFromInputSchema(input));
821
1003
  }
822
1004
  return input;
823
1005
  }
824
1006
  /**
825
- * Gets the Actor input value just like the {@link Actor.getInput} method,
826
- * but throws if it is not found.
1007
+ * Reads the input from a `<inputKey>` or `<inputKey>.json` file in the given directory, for local runs
1008
+ * whose default key-value store holds no input record. Mirrors how `ApifyFileSystemStorageBackend` adopts
1009
+ * such files inside the store directory: the `.json` file is JSON, the bare one is bytes that
1010
+ * {@link parseInputValue} tries as JSON5. Both files present is an error rather than a guess.
1011
+ *
1012
+ * @returns `undefined` when running on the platform or when neither file exists.
827
1013
  */
828
- async getInputOrThrow() {
829
- const input = await this.getInput();
830
- if (input == null) {
831
- throw new Error('Input does not exist');
1014
+ async readInputFromDirectory(inputKey, directory, label) {
1015
+ if (this.configuration.isAtHome) {
1016
+ return undefined;
832
1017
  }
833
- return input;
1018
+ const candidates = [
1019
+ { filename: inputKey, contentType: BINARY_CONTENT_TYPE },
1020
+ { filename: `${inputKey}.json`, contentType: JSON_CONTENT_TYPE },
1021
+ ];
1022
+ const found = [];
1023
+ for (const candidate of candidates) {
1024
+ const path = join(directory, candidate.filename);
1025
+ const stats = await stat(path).catch(() => null);
1026
+ if (stats?.isFile()) {
1027
+ found.push({ ...candidate, path });
1028
+ }
1029
+ }
1030
+ if (found.length > 1) {
1031
+ throw new ActorInputError('MULTIPLE_FILES', `Found multiple input files in the ${label}: ${found.map((file) => `"${file.filename}"`).join(', ')}. Keep only one of them.`);
1032
+ }
1033
+ if (found.length === 0) {
1034
+ return undefined;
1035
+ }
1036
+ const [file] = found;
1037
+ return parseInput(await readFile(file.path), file.contentType, `the "${file.filename}" file in the ${label}`);
834
1038
  }
835
1039
  /**
836
1040
  * Opens a key-value store and returns a promise resolving to an instance of the {@link KeyValueStore} class.
@@ -842,18 +1046,21 @@ class Actor {
842
1046
  * For more details and code examples, see the {@link KeyValueStore} class.
843
1047
  *
844
1048
  * @param [storeIdOrName]
845
- * ID or name of the key-value store to be opened. If `null` or `undefined`,
1049
+ * ID, name, or alias of the key-value store to be opened. If `null` or `undefined`,
846
1050
  * the function returns the default key-value store associated with the Actor run.
847
- * You can also pass `{ id: 'abc' }` to open by explicit ID, or `{ name: 'abc' }` to open by explicit name.
1051
+ * You can also pass `{ alias: 'abc' }` to open a run-scoped storage, `{ id: 'abc' }` to open by
1052
+ * explicit ID, or `{ name: 'abc' }` to open by explicit name.
848
1053
  * @param [options]
849
1054
  * @ignore
850
1055
  */
851
1056
  async openKeyValueStore(storeIdOrName, options = {}) {
852
- (0, ow_1.default)(options, ow_1.default.object.exactShape({
853
- forceCloud: ow_1.default.optional.boolean,
854
- }));
855
- this._ensureActorInit('openKeyValueStore');
856
- return this._openStorage(key_value_store_js_1.KeyValueStore, storeIdOrName, options);
1057
+ parseArgument(options, z.object({ forceCloud: z.boolean().optional() }).strict());
1058
+ this.ensureActorInit('openKeyValueStore');
1059
+ return KeyValueStore.open(storeIdOrName ?? null, {
1060
+ storageBackend: options.forceCloud
1061
+ ? this.#storageBackend.getSuitableStorageBackend({ forceCloud: true })
1062
+ : undefined,
1063
+ });
857
1064
  }
858
1065
  /**
859
1066
  * Opens a request queue and returns a promise resolving to an instance
@@ -867,21 +1074,21 @@ class Actor {
867
1074
  * For more details and code examples, see the {@link RequestQueue} class.
868
1075
  *
869
1076
  * @param [queueIdOrName]
870
- * ID or name of the request queue to be opened. If `null` or `undefined`,
1077
+ * ID, name, or alias of the request queue to be opened. If `null` or `undefined`,
871
1078
  * the function returns the default request queue associated with the Actor run.
872
- * You can also pass `{ id: 'abc' }` to open by explicit ID, or `{ name: 'abc' }` to open by explicit name.
1079
+ * You can also pass `{ alias: 'abc' }` to open a run-scoped storage, `{ id: 'abc' }` to open by
1080
+ * explicit ID, or `{ name: 'abc' }` to open by explicit name.
873
1081
  * @param [options]
874
1082
  * @ignore
875
1083
  */
876
1084
  async openRequestQueue(queueIdOrName, options = {}) {
877
- (0, ow_1.default)(options, ow_1.default.object.exactShape({
878
- forceCloud: ow_1.default.optional.boolean,
879
- }));
880
- this._ensureActorInit('openRequestQueue');
881
- const queue = await this._openStorage(core_1.RequestQueue, queueIdOrName, options);
882
- // eslint-disable-next-line dot-notation
883
- queue['initialCount'] = (await queue.client.get())?.totalRequestCount ?? 0;
884
- return queue;
1085
+ parseArgument(options, z.object({ forceCloud: z.boolean().optional() }).strict());
1086
+ this.ensureActorInit('openRequestQueue');
1087
+ return RequestQueue.open(queueIdOrName ?? null, {
1088
+ storageBackend: options.forceCloud
1089
+ ? this.#storageBackend.getSuitableStorageBackend({ forceCloud: true })
1090
+ : undefined,
1091
+ });
885
1092
  }
886
1093
  /**
887
1094
  * Creates a proxy configuration and returns a promise resolving to an instance
@@ -932,7 +1139,7 @@ class Actor {
932
1139
  if (dontUseApifyProxy && dontUseCustomProxies) {
933
1140
  return undefined;
934
1141
  }
935
- const proxyConfiguration = new proxy_configuration_js_1.ProxyConfiguration(options, this.config);
1142
+ const proxyConfiguration = new ProxyConfiguration(options, this.configuration);
936
1143
  if (await proxyConfiguration.initialize({ checkAccess })) {
937
1144
  return proxyConfiguration;
938
1145
  }
@@ -956,23 +1163,23 @@ class Actor {
956
1163
  * @ignore
957
1164
  */
958
1165
  async charge(options) {
959
- this._ensureActorInit('charge');
960
- return this.chargingManager.charge(options);
1166
+ this.ensureActorInit('charge');
1167
+ return this.#chargingManager.charge(options);
961
1168
  }
962
1169
  /**
963
1170
  * Retrieve the charging manager to access granular pricing information.
964
1171
  * @ignore
965
1172
  */
966
1173
  getChargingManager() {
967
- this._ensureActorInit('getChargingManager');
968
- return this.chargingManager;
1174
+ this.ensureActorInit('getChargingManager');
1175
+ return this.#chargingManager;
969
1176
  }
970
1177
  /**
971
1178
  * Modifies Actor env vars so parsing respects the structure of {@link ApifyEnv} interface.
972
1179
  */
973
1180
  getModifiedActorEnvVars() {
974
1181
  const modifiedActorEnvVars = {};
975
- Object.entries(consts_1.ACTOR_ENV_VARS).forEach(([k, v]) => {
1182
+ Object.entries(ACTOR_ENV_VARS).forEach(([k, v]) => {
976
1183
  // Prepend `ACTOR_` to env vars so ApifyEnv structure is preserved
977
1184
  if (['ID', 'RUN_ID', 'TASK_ID'].includes(k)) {
978
1185
  modifiedActorEnvVars[`ACTOR_${k}`] = v;
@@ -996,20 +1203,25 @@ class Actor {
996
1203
  const env = process.env || {};
997
1204
  const envVars = {};
998
1205
  for (const [shortName, fullName] of Object.entries({
999
- ...consts_1.APIFY_ENV_VARS,
1206
+ ...APIFY_ENV_VARS,
1000
1207
  ...this.getModifiedActorEnvVars(),
1001
1208
  })) {
1002
- const camelCaseName = (0, utils_1.snakeCaseToCamelCase)(shortName);
1209
+ if (IGNORED_ENV_VARS.includes(fullName))
1210
+ continue;
1211
+ const camelCaseName = snakeCaseToCamelCase(shortName);
1003
1212
  let value = env[fullName];
1004
- // Parse dates and integers.
1005
- if (value && fullName.endsWith('_AT')) {
1213
+ // Parse booleans, dates and integers.
1214
+ if (BOOLEAN_ENV_VARS.includes(fullName)) {
1215
+ value = !!value && coerceBoolean.parse(value);
1216
+ }
1217
+ else if (value && fullName.endsWith('_AT')) {
1006
1218
  const unix = Date.parse(value);
1007
1219
  value = unix > 0 ? new Date(unix) : undefined;
1008
1220
  }
1009
- else if (consts_1.INTEGER_ENV_VARS.includes(fullName)) {
1221
+ else if (INTEGER_ENV_VARS.includes(fullName)) {
1010
1222
  value = parseInt(value, 10);
1011
1223
  }
1012
- Reflect.set(envVars, camelCaseName, value || value === 0 ? value : null);
1224
+ Reflect.set(envVars, camelCaseName, value || value === 0 || value === false ? value : null);
1013
1225
  }
1014
1226
  return envVars;
1015
1227
  }
@@ -1022,20 +1234,15 @@ class Actor {
1022
1234
  * @ignore
1023
1235
  */
1024
1236
  newClient(options = {}) {
1025
- const { storageDir, ...storageClientOptions } = this.config.get('storageClientOptions');
1026
- const { apifyVersion, crawleeVersion } = (0, utils_js_1.getSystemInfo)();
1027
- return (0, patched_apify_client_js_1.createPatchedApifyClient)({
1028
- baseUrl: this.config.get('apiBaseUrl'),
1029
- publicBaseUrl: this.config.get('apiPublicBaseUrl'),
1030
- token: this.config.get('token'),
1237
+ const { storageDir, ...storageClientOptions } = (this.configuration.storageClientOptions ?? {});
1238
+ const { apifyVersion, crawleeVersion } = getSystemInfo();
1239
+ return new ApifyClient({
1240
+ baseUrl: this.configuration.apiBaseUrl,
1241
+ publicBaseUrl: this.configuration.apiPublicBaseUrl,
1242
+ token: this.configuration.token,
1031
1243
  userAgentSuffix: [`SDK/${apifyVersion}`, `Crawlee/${crawleeVersion}`],
1032
1244
  ...storageClientOptions,
1033
1245
  ...options, // allow overriding the instance configuration
1034
- }, {
1035
- config: this.config,
1036
- // Hand over the raw manager rather than the public getChargingManager(), which
1037
- // warns about a missing init() — a standalone client is a supported use case.
1038
- getChargingManager: () => this.chargingManager,
1039
1246
  });
1040
1247
  }
1041
1248
  /**
@@ -1043,7 +1250,7 @@ class Actor {
1043
1250
  * @ignore
1044
1251
  */
1045
1252
  isAtHome() {
1046
- return !!process.env[consts_1.APIFY_ENV_VARS.IS_AT_HOME];
1253
+ return !!process.env[APIFY_ENV_VARS.IS_AT_HOME];
1047
1254
  }
1048
1255
  /**
1049
1256
  * Easily create and manage state values. All state values are automatically persisted.
@@ -1055,9 +1262,9 @@ class Actor {
1055
1262
  * @param options An optional object parameter where a custom `keyValueStoreName` and `config` can be passed in.
1056
1263
  */
1057
1264
  async useState(name, defaultValue = {}, options) {
1058
- this._ensureActorInit('useState');
1059
- const kvStore = await key_value_store_js_1.KeyValueStore.open(options?.keyValueStoreName, {
1060
- config: options?.config || configuration_js_1.Configuration.getGlobalConfig(),
1265
+ this.ensureActorInit('useState');
1266
+ const kvStore = await KeyValueStore.open(options?.keyValueStoreName, {
1267
+ configuration: options?.configuration ?? this.configuration,
1061
1268
  });
1062
1269
  return kvStore.getAutoSavedValue(name || 'APIFY_GLOBAL_STATE', defaultValue);
1063
1270
  }
@@ -1108,24 +1315,22 @@ class Actor {
1108
1315
  *
1109
1316
  * If the user function returns a promise, it is considered asynchronous:
1110
1317
  * ```js
1111
- * import { gotScraping } from 'got-scraping';
1112
- *
1113
1318
  * await Actor.main(() => {
1114
1319
  * // My asynchronous function that returns a promise
1115
- * return gotScraping('http://www.example.com').then((html) => {
1116
- * console.log(html);
1117
- * });
1320
+ * return fetch('http://www.example.com')
1321
+ * .then((response) => response.text())
1322
+ * .then((html) => {
1323
+ * console.log(html);
1324
+ * });
1118
1325
  * });
1119
1326
  * ```
1120
1327
  *
1121
1328
  * To simplify your code, you can take advantage of the `async`/`await` keywords:
1122
1329
  *
1123
1330
  * ```js
1124
- * import { gotScraping } from 'got-scraping';
1125
- *
1126
1331
  * await Actor.main(async () => {
1127
1332
  * // My asynchronous function
1128
- * const html = await gotScraping('http://www.example.com');
1333
+ * const html = await fetch('http://www.example.com').then((response) => response.text());
1129
1334
  * console.log(html);
1130
1335
  * });
1131
1336
  * ```
@@ -1153,11 +1358,9 @@ class Actor {
1153
1358
  * behavior by setting `options.gracefulShutdown` to `false`.
1154
1359
  *
1155
1360
  * ```js
1156
- * import { gotScraping } from 'got-scraping';
1157
- *
1158
1361
  * await Actor.init();
1159
1362
  *
1160
- * const html = await gotScraping('http://www.example.com');
1363
+ * const html = await fetch('http://www.example.com').then((response) => response.text());
1161
1364
  * console.log(html);
1162
1365
  *
1163
1366
  * await Actor.exit();
@@ -1208,9 +1411,8 @@ class Actor {
1208
1411
  * @param actorId
1209
1412
  * Allowed formats are `username/actor-name`, `userId/actor-name` or Actor ID.
1210
1413
  * @param [input]
1211
- * Input for the Actor. If it is an object, it will be stringified to
1212
- * JSON and its content type set to `application/json; charset=utf-8`.
1213
- * Otherwise the `options.contentType` parameter must be provided.
1414
+ * Input for the Actor. A plain object is stringified to JSON with content type
1415
+ * `application/json; charset=utf-8`. A `Buffer` is sent as-is and needs `options.contentType`.
1214
1416
  * @param [options]
1215
1417
  */
1216
1418
  static async call(actorId, input, options = {}) {
@@ -1244,6 +1446,31 @@ class Actor {
1244
1446
  static async callTask(taskId, input, options = {}) {
1245
1447
  return Actor.getDefaultInstance().callTask(taskId, input, options);
1246
1448
  }
1449
+ /**
1450
+ * Runs an Actor task on the Apify platform using the current user account (determined by the `APIFY_TOKEN` environment variable),
1451
+ * unlike `Actor.callTask`, this method just starts the run without waiting for finish.
1452
+ *
1453
+ * The result of the function is an {@link ActorRun} object that contains details about the Actor run.
1454
+ *
1455
+ * For more information about Actor tasks, read the [documentation](https://docs.apify.com/tasks).
1456
+ *
1457
+ * **Example usage:**
1458
+ *
1459
+ * ```js
1460
+ * const run = await Actor.startTask('bob/some-task');
1461
+ * ```
1462
+ *
1463
+ * @param taskId
1464
+ * Allowed formats are `username/task-name`, `userId/task-name` or task ID.
1465
+ * @param [input]
1466
+ * Input overrides for the Actor task. If it is an object, it will be stringified to
1467
+ * JSON and its content type set to `application/json; charset=utf-8`.
1468
+ * Provided input will be merged with Actor task input.
1469
+ * @param [options]
1470
+ */
1471
+ static async startTask(taskId, input, options = {}) {
1472
+ return Actor.getDefaultInstance().startTask(taskId, input, options);
1473
+ }
1247
1474
  /**
1248
1475
  * Runs an Actor on the Apify platform using the current user account (determined by the `APIFY_TOKEN` environment variable),
1249
1476
  * unlike `Actor.call`, this method just starts the run without waiting for finish.
@@ -1262,14 +1489,28 @@ class Actor {
1262
1489
  * @param actorId
1263
1490
  * Allowed formats are `username/actor-name`, `userId/actor-name` or Actor ID.
1264
1491
  * @param [input]
1265
- * Input for the Actor. If it is an object, it will be stringified to
1266
- * JSON and its content type set to `application/json; charset=utf-8`.
1267
- * Otherwise the `options.contentType` parameter must be provided.
1492
+ * Input for the Actor. A plain object is stringified to JSON with content type
1493
+ * `application/json; charset=utf-8`. A `Buffer` is sent as-is and needs `options.contentType`.
1268
1494
  * @param [options]
1269
1495
  */
1270
1496
  static async start(actorId, input, options = {}) {
1271
1497
  return Actor.getDefaultInstance().start(actorId, input, options);
1272
1498
  }
1499
+ /**
1500
+ * Clients for the child runs started with the `runName` option, keyed by that name, including the runs started
1501
+ * before a migration or resurrection of this run. Each client points to the current run under its name.
1502
+ *
1503
+ * ```js
1504
+ * await Actor.childRuns['my-child'].waitForFinish();
1505
+ * ```
1506
+ *
1507
+ * A run started with a custom `token` uses that token, except for a run started before a migration or
1508
+ * resurrection, which uses the default client. The tracked runs, including the earlier runs replaced
1509
+ * under the same name, are stored in the default key-value store under the `__ACTOR_CHILD_RUNS` key.
1510
+ */
1511
+ static get childRuns() {
1512
+ return Actor.getDefaultInstance().childRuns;
1513
+ }
1273
1514
  /**
1274
1515
  * Aborts given Actor run on the Apify platform using the current user account (determined by the `APIFY_TOKEN` environment variable).
1275
1516
  *
@@ -1287,6 +1528,26 @@ class Actor {
1287
1528
  static async abort(runId, options = {}) {
1288
1529
  return Actor.getDefaultInstance().abort(runId, options);
1289
1530
  }
1531
+ /**
1532
+ * Resurrects a finished Actor run on the Apify platform using the current user account (determined by the `APIFY_TOKEN` environment variable).
1533
+ *
1534
+ * Only finished runs (SUCCEEDED, FAILED, ABORTED or TIMED-OUT) can be resurrected. The run goes back to the RUNNING
1535
+ * status and keeps its default storages. Options you leave out keep the values of the original run.
1536
+ *
1537
+ * The result of the function is an {@link ActorRun} object that contains details about the Actor run.
1538
+ *
1539
+ * For more information about Actors, read the
1540
+ * [documentation](https://docs.apify.com/actor).
1541
+ *
1542
+ * **Example usage:**
1543
+ *
1544
+ * ```js
1545
+ * const run = await Actor.resurrect(runId);
1546
+ * ```
1547
+ */
1548
+ static async resurrect(runId, options = {}) {
1549
+ return Actor.getDefaultInstance().resurrect(runId, options);
1550
+ }
1290
1551
  /**
1291
1552
  * Transforms this Actor run to an Actor run of a given Actor. The system stops the current container and starts
1292
1553
  * the new container instead. All the default storages are preserved and the new input is stored under the `INPUT-METAMORPH-1` key
@@ -1295,9 +1556,8 @@ class Actor {
1295
1556
  * @param targetActorId
1296
1557
  * Either `username/actor-name` or Actor ID of an Actor to which we want to metamorph.
1297
1558
  * @param [input]
1298
- * Input for the Actor. If it is an object, it will be stringified to
1299
- * JSON and its content type set to `application/json; charset=utf-8`.
1300
- * Otherwise, the `options.contentType` parameter must be provided.
1559
+ * Input for the Actor. A plain object is stringified to JSON with content type
1560
+ * `application/json; charset=utf-8`. A `Buffer` is sent as-is and needs `options.contentType`.
1301
1561
  * @param [options]
1302
1562
  */
1303
1563
  static async metamorph(targetActorId, input, options = {}) {
@@ -1332,7 +1592,8 @@ class Actor {
1332
1592
  * @param [options]
1333
1593
  * @param [options.isStatusMessageTerminal] If `true`, the status message will be marked as terminal.
1334
1594
  * This is required for the last status message of the run. Default value is `false`.
1335
- * @returns The return value is the Run object. When run locally, this method returns empty object (`{}`).
1595
+ * @returns The updated Run object, or `undefined` when no run was updated: when run locally,
1596
+ * or when the update failed or timed out (a warning is logged in that case).
1336
1597
  * For more information, see the [Actor Runs](https://docs.apify.com/api/v2#/reference/actor-runs/) API endpoints.
1337
1598
  */
1338
1599
  static async setStatusMessage(statusMessage, options) {
@@ -1380,42 +1641,15 @@ class Actor {
1380
1641
  * @param [datasetIdOrName]
1381
1642
  * ID, name, or alias of the dataset to be opened. If `null` or `undefined`,
1382
1643
  * the function returns the default dataset associated with the Actor run.
1383
- * You can also pass `{ alias: 'name' }` to open a dataset defined in the Actor's schema storages,
1384
- * `{ id: 'abc' }` to open by explicit ID, or `{ name: 'abc' }` to open by explicit name.
1644
+ * You can also pass `{ alias: 'abc' }` to open a run-scoped storage, `{ id: 'abc' }` to open by
1645
+ * explicit ID, or `{ name: 'abc' }` to open by explicit name.
1385
1646
  * @param [options]
1386
1647
  */
1387
1648
  static async openDataset(datasetIdOrName, options = {}) {
1388
1649
  return Actor.getDefaultInstance().openDataset(datasetIdOrName, options);
1389
1650
  }
1390
- /**
1391
- * Gets a value from the default {@link KeyValueStore} associated with the current Actor run.
1392
- *
1393
- * This is just a convenient shortcut for {@link KeyValueStore.getValue}.
1394
- * For example, calling the following code:
1395
- * ```js
1396
- * const value = await Actor.getValue('my-key');
1397
- * ```
1398
- *
1399
- * is equivalent to:
1400
- * ```js
1401
- * const store = await Actor.openKeyValueStore();
1402
- * const value = await store.getValue('my-key');
1403
- * ```
1404
- *
1405
- * To store the value to the default key-value store, you can use the {@link Actor.setValue} function.
1406
- *
1407
- * For more information, see {@link Actor.openKeyValueStore}
1408
- * and {@link KeyValueStore.getValue}.
1409
- *
1410
- * @param key Unique record key.
1411
- * @returns
1412
- * Returns a promise that resolves to an object, string
1413
- * or [`Buffer`](https://nodejs.org/api/buffer.html), depending
1414
- * on the MIME content type of the record, or `null`
1415
- * if the record is missing.
1416
- */
1417
- static async getValue(key) {
1418
- return Actor.getDefaultInstance().getValue(key);
1651
+ static async getValue(key, defaultValue) {
1652
+ return Actor.getDefaultInstance().getValue(key, defaultValue);
1419
1653
  }
1420
1654
  /**
1421
1655
  * Stores or deletes a value in the default {@link KeyValueStore} associated with the current Actor run.
@@ -1453,16 +1687,31 @@ class Actor {
1453
1687
  /**
1454
1688
  * Gets the Actor input value from the default {@link KeyValueStore} associated with the current Actor run.
1455
1689
  *
1456
- * This is just a convenient shortcut for {@link KeyValueStore.getValue | `keyValueStore.getValue('INPUT')`}.
1457
- * For example, calling the following code:
1690
+ * The input is the record stored under the configured input key (`ACTOR_INPUT_KEY`, default `INPUT`):
1458
1691
  * ```js
1459
1692
  * const input = await Actor.getInput();
1460
1693
  * ```
1461
1694
  *
1462
- * is equivalent to:
1695
+ * A record stored as `application/octet-stream` — which is what a local input file without an
1696
+ * extension is read as — is parsed with JSON5 when it parses, and returned as a `Buffer` otherwise.
1697
+ *
1698
+ * When running locally, the input may instead be a `<inputKey>` or `<inputKey>.json` file in the current
1699
+ * working directory.
1700
+ *
1701
+ * Google Sheets sharing links in `requestsFromUrl` entries (from the "Link remote text file" option) are
1702
+ * replaced with the links of their CSV exports.
1703
+ *
1704
+ * Throws an {@link ActorInputError} when no input is found (`code: 'NOT_FOUND'`), when the input is
1705
+ * found in more than one place (`'MULTIPLE_FILES'`), when a JSON input does not parse
1706
+ * (`'PARSE_FAILED'`) or when its secret fields cannot be decrypted (`'DECRYPTION_FAILED'`). If your
1707
+ * Actor can run without input, catch the `'NOT_FOUND'` case and rethrow the rest:
1463
1708
  * ```js
1464
- * const store = await Actor.openKeyValueStore();
1465
- * await store.getValue('INPUT');
1709
+ * let input = {};
1710
+ * try {
1711
+ * input = await Actor.getInput();
1712
+ * } catch (error) {
1713
+ * if (!(error instanceof ActorInputError) || error.code !== 'NOT_FOUND') throw error;
1714
+ * }
1466
1715
  * ```
1467
1716
  *
1468
1717
  * Note that the `getInput()` function does not cache the value read from the key-value store.
@@ -1474,19 +1723,12 @@ class Actor {
1474
1723
  * @returns
1475
1724
  * Returns a promise that resolves to an object, string
1476
1725
  * or [`Buffer`](https://nodejs.org/api/buffer.html), depending
1477
- * on the MIME content type of the record, or `null`
1478
- * if the record is missing.
1726
+ * on the MIME content type of the record.
1727
+ * @throws {ActorInputError} When the input cannot be produced; see `code`.
1479
1728
  */
1480
1729
  static async getInput() {
1481
1730
  return Actor.getDefaultInstance().getInput();
1482
1731
  }
1483
- /**
1484
- * Gets the Actor input value just like the {@link Actor.getInput} method,
1485
- * but throws if it is not found.
1486
- */
1487
- static async getInputOrThrow() {
1488
- return Actor.getDefaultInstance().getInputOrThrow();
1489
- }
1490
1732
  /**
1491
1733
  * Opens a key-value store and returns a promise resolving to an instance of the {@link KeyValueStore} class.
1492
1734
  *
@@ -1622,69 +1864,92 @@ class Actor {
1622
1864
  return Actor.getDefaultInstance().apifyClient;
1623
1865
  }
1624
1866
  /** Default {@link Configuration} instance. */
1625
- static get config() {
1626
- return Actor.getDefaultInstance().config;
1867
+ static get configuration() {
1868
+ return Actor.getDefaultInstance().configuration;
1627
1869
  }
1628
1870
  /** @internal */
1629
1871
  static getDefaultInstance() {
1630
- this._instance ?? (this._instance = new Actor());
1631
- return this._instance;
1872
+ Actor.#instance ??= new Actor();
1873
+ return Actor.#instance;
1632
1874
  }
1633
- usesPushDataInterception(dataset) {
1634
- return Boolean(dataset.client[patched_apify_client_js_1.USES_PUSH_DATA_INTERCEPTION]);
1875
+ /**
1876
+ * Replaces or clears the cached default instance returned by {@link Actor.getDefaultInstance}.
1877
+ * @internal
1878
+ */
1879
+ static setDefaultInstance(instance) {
1880
+ Actor.#instance = instance;
1635
1881
  }
1636
- async pushDataViaInterceptedClient(dataset, item, eventName) {
1637
- // PatchedDatasetClient will handle charging and item limiting.
1638
- // We only need to propagate `eventName` and (optionally) return aggregated charge info.
1639
- const context = {
1640
- eventName,
1882
+ /**
1883
+ * The backend the Actor installs unless the caller brings one: Apify platform storage on the
1884
+ * platform, crawlee's local default outside of it.
1885
+ *
1886
+ * Both sides are wrapped for dataset-item charging - crawlee's local default stands in for
1887
+ * Apify storage, so local pay-per-event testing stays faithful. A caller-supplied backend
1888
+ * (`Actor.init({ storage })`) is billed nothing and is installed unwrapped, in place of this.
1889
+ *
1890
+ * One instance per Actor: a second platform backend would mint unnamed storages of its own for
1891
+ * aliases this one has already resolved.
1892
+ */
1893
+ get #storageBackend() {
1894
+ const charging = {
1895
+ configuration: this.configuration,
1896
+ getChargingManager: () => this.#chargingManager,
1641
1897
  };
1642
- await patched_apify_client_js_1.pushDataChargingContext.run(context, async () => {
1643
- await dataset.pushData(item);
1644
- });
1645
- return (context.chargeResult ?? {
1646
- eventChargeLimitReached: false,
1647
- chargedCount: 0,
1648
- chargeableWithinLimit: {},
1649
- });
1898
+ return (this.#cachedStorageBackend ??= new SmartApifyStorageBackend({
1899
+ cloudStorageBackend: new ChargingStorageBackend(new ApifyStorageBackend(this.apifyClient, {
1900
+ configuration: this.configuration,
1901
+ requestQueueAccess: this.#requestQueueAccess,
1902
+ }), charging),
1903
+ localStorageBackend: new ChargingStorageBackend(this.createLocalStorageBackend(), charging),
1904
+ configuration: this.configuration,
1905
+ }));
1650
1906
  }
1651
- async pushDataWithExplicitCharging(dataset, items, explicitEventName) {
1652
- // `Actor.pushData()` historically worked even without calling `Actor.init()`.
1653
- // In that case, charging isn't configured, so just push the data through.
1654
- if (!this.initialized && explicitEventName === undefined) {
1655
- await dataset.pushData(items);
1656
- return {
1657
- eventChargeLimitReached: false,
1658
- chargedCount: 0,
1659
- chargeableWithinLimit: {},
1660
- };
1907
+ /**
1908
+ * The same choice crawlee's `ServiceLocator` makes for its implicit default backend, with the
1909
+ * input-aware {@link ApifyFileSystemStorageBackend} in place of crawlee's — crawlee has no
1910
+ * notion of a run input.
1911
+ */
1912
+ createLocalStorageBackend() {
1913
+ const { persistStorage, storageDir, inputKey } = this.configuration;
1914
+ const logger = serviceLocator.getLogger();
1915
+ if (!persistStorage) {
1916
+ return new MemoryStorageBackend({ logger: logger.child({ prefix: 'MemoryStorageBackend' }) });
1661
1917
  }
1662
- const isDefaultDataset = dataset.id === this.config.get('defaultDatasetId');
1663
- return (0, charging_js_1.pushDataAndCharge)({
1664
- chargingManager: this.chargingManager,
1665
- items,
1666
- eventName: explicitEventName,
1667
- isDefaultDataset,
1668
- pushFn: async (limitedItems) => dataset.pushData(limitedItems),
1918
+ return new ApifyFileSystemStorageBackend({
1919
+ localDataDirectory: storageDir,
1920
+ inputKey,
1921
+ logger: logger.child({ prefix: 'ApifyFileSystemStorageBackend' }),
1669
1922
  });
1670
1923
  }
1671
- async _openStorage(storageClass, identifier, options = {}) {
1672
- return (0, storage_js_1.openStorage)(storageClass, identifier, {
1673
- config: this.config,
1674
- client: options.forceCloud ? this.apifyClient : undefined,
1675
- purgedStorageAliases: this.purgedStorageAliases,
1676
- });
1924
+ /** Whether items reaching the run's default dataset are counted for pay-per-event charging. */
1925
+ #chargesDefaultDatasetItems() {
1926
+ const installed = serviceLocator.getStorageBackend();
1927
+ return installed instanceof SmartApifyStorageBackend || installed instanceof ChargingStorageBackend;
1928
+ }
1929
+ /**
1930
+ * crawlee's service locator is set-once, so a backend registered before `init()` wins and the
1931
+ * Actor cannot install its own over it. Replaces the resulting `ServiceConflictError` with the
1932
+ * way out.
1933
+ */
1934
+ installStorageBackend(backend) {
1935
+ try {
1936
+ serviceLocator.setStorageBackend(backend);
1937
+ }
1938
+ catch (error) {
1939
+ throw new Error('A storage backend is already registered with crawlee, so the Actor cannot install its own. Pass it ' +
1940
+ 'as `Actor.init({ storage })` instead of calling `serviceLocator.setStorageBackend()`.', { cause: error });
1941
+ }
1677
1942
  }
1678
- _ensureActorInit(methodCalled) {
1943
+ ensureActorInit(methodCalled) {
1679
1944
  // If we already warned the user once, don't do it again to prevent spam
1680
- if (this.warnedAboutMissingInitCall) {
1945
+ if (this.#warnedAboutMissingInitCall) {
1681
1946
  return;
1682
1947
  }
1683
1948
  if (this.initialized) {
1684
1949
  return;
1685
1950
  }
1686
- this.warnedAboutMissingInitCall = true;
1687
- log_1.default.warning([
1951
+ this.#warnedAboutMissingInitCall = true;
1952
+ log.warning([
1688
1953
  `Actor.${methodCalled}() was called but the Actor instance was not initialized.`,
1689
1954
  'Did you forget to call Actor.init()?',
1690
1955
  ].join('\n'));
@@ -1702,7 +1967,7 @@ class Actor {
1702
1967
  if (this.isAtHome() && env.timeoutAt !== null) {
1703
1968
  return Math.max(Math.ceil((env.timeoutAt.getTime() - Date.now()) / 1000), MINIMUM_API_TIMEOUT_SECS);
1704
1969
  }
1705
- log_1.default.warning('Using `inherit` argument is only possible when the Actor is running on the Apify platform and when the ' +
1970
+ log.warning('Using `inherit` argument is only possible when the Actor is running on the Apify platform and when the ' +
1706
1971
  'timeout for the Actor run is set.');
1707
1972
  return undefined;
1708
1973
  }
@@ -1713,17 +1978,16 @@ class Actor {
1713
1978
  return input;
1714
1979
  }
1715
1980
  // On local, we can get the input schema from the local config
1716
- const inputSchema = (0, input_schemas_js_1.readInputSchema)();
1981
+ const inputSchema = readInputSchema();
1717
1982
  // Don't emit warning if there is no input schema defined
1718
- if (inputSchema === input_schemas_js_1.noActorInputSchemaDefinedMarker) {
1983
+ if (inputSchema === noActorInputSchemaDefinedMarker) {
1719
1984
  return input;
1720
1985
  }
1721
1986
  if (!inputSchema) {
1722
- log_1.default.warning('Failed to find the input schema for the local run of this Actor. Your input will be missing fields that have default values set if they are missing from the input you are using.');
1987
+ log.warning('Failed to find the input schema for the local run of this Actor. Your input will be missing fields that have default values set if they are missing from the input you are using.');
1723
1988
  return input;
1724
1989
  }
1725
- const defaults = (0, input_schemas_js_1.getDefaultsFromInputSchema)(inputSchema);
1990
+ const defaults = getDefaultsFromInputSchema(inputSchema);
1726
1991
  return { ...defaults, ...input };
1727
1992
  }
1728
1993
  }
1729
- exports.Actor = Actor;