apify 4.0.0-beta.71 → 4.0.0-beta.73

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.
package/dist/actor.d.ts CHANGED
@@ -115,9 +115,9 @@ export interface ApifyEnv {
115
115
  */
116
116
  userId: string | null;
117
117
  /**
118
- * If it is `1`, it means that the user who started the Actor is a paying user. (APIFY_USER_IS_PAYING)
118
+ * Whether the user who started the Actor is a paying user. `false` when not set. (APIFY_USER_IS_PAYING)
119
119
  */
120
- userIsPaying: string | null;
120
+ userIsPaying: boolean;
121
121
  /**
122
122
  * Authentication token representing privileges given to the Actor run,
123
123
  * it can be passed to various Apify APIs (APIFY_TOKEN)
@@ -778,11 +778,12 @@ export declare class Actor<Data extends Dictionary = Dictionary> {
778
778
  * A record stored as `application/octet-stream` — which is what a local input file without an
779
779
  * extension is read as — is parsed with JSON5 when it parses, and returned as a `Buffer` otherwise.
780
780
  *
781
- * When running locally and the store holds no such record, the input is read from a `<inputKey>` or
782
- * `<inputKey>.json` file in the current working directory, then in the storage directory.
781
+ * When running locally, the input may instead be a `<inputKey>` or `<inputKey>.json` file in the current
782
+ * working directory. A storage backend that doesn't read the default key-value store's directory under
783
+ * the storage directory (e.g. in-memory storage) also gets the file `apify run` writes there.
783
784
  *
784
- * Throws an {@link ActorInputError} when no input is found (`code: 'NOT_FOUND'`), when both input
785
- * files exist in the working/storage directory (`'MULTIPLE_FILES'`), when a JSON input does not parse
785
+ * Throws an {@link ActorInputError} when no input is found (`code: 'NOT_FOUND'`), when the input is
786
+ * found in more than one place (`'MULTIPLE_FILES'`), when a JSON input does not parse
786
787
  * (`'PARSE_FAILED'`) or when its secret fields cannot be decrypted (`'DECRYPTION_FAILED'`). If your
787
788
  * Actor can run without input, catch the `'NOT_FOUND'` case and rethrow the rest.
788
789
  *
@@ -1414,11 +1415,11 @@ export declare class Actor<Data extends Dictionary = Dictionary> {
1414
1415
  * A record stored as `application/octet-stream` — which is what a local input file without an
1415
1416
  * extension is read as — is parsed with JSON5 when it parses, and returned as a `Buffer` otherwise.
1416
1417
  *
1417
- * When running locally and the store holds no such record, the input is read from a `<inputKey>` or
1418
- * `<inputKey>.json` file in the current working directory instead.
1418
+ * When running locally, the input may instead be a `<inputKey>` or `<inputKey>.json` file in the current
1419
+ * working directory.
1419
1420
  *
1420
- * Throws an {@link ActorInputError} when no input is found (`code: 'NOT_FOUND'`), when both input
1421
- * files exist in the working directory (`'MULTIPLE_FILES'`), when a JSON input does not parse
1421
+ * Throws an {@link ActorInputError} when no input is found (`code: 'NOT_FOUND'`), when the input is
1422
+ * found in more than one place (`'MULTIPLE_FILES'`), when a JSON input does not parse
1422
1423
  * (`'PARSE_FAILED'`) or when its secret fields cannot be decrypted (`'DECRYPTION_FAILED'`). If your
1423
1424
  * Actor can run without input, catch the `'NOT_FOUND'` case and rethrow the rest:
1424
1425
  * ```js
package/dist/actor.js CHANGED
@@ -1,7 +1,7 @@
1
1
  import { createPrivateKey } from 'node:crypto';
2
2
  import { readFile, stat } from 'node:fs/promises';
3
3
  import { join } from 'node:path';
4
- import { Dataset, EventType, KeyValueStore, MemoryStorageBackend, purgeDefaultStorages, rejectOperationInTransaction, RequestQueue, serviceLocator, } from '@crawlee/core';
4
+ import { coerceBoolean, Dataset, EventType, KeyValueStore, MemoryStorageBackend, purgeDefaultStorages, rejectOperationInTransaction, RequestQueue, serviceLocator, } from '@crawlee/core';
5
5
  import { sleep } from '@crawlee/utils';
6
6
  import { ApifyClient } from 'apify-client';
7
7
  import { z } from 'zod';
@@ -22,6 +22,8 @@ import { PlatformEventManager } from './platform_event_manager.js';
22
22
  import { ProxyConfiguration } from './proxy_configuration.js';
23
23
  import { SmartApifyStorageBackend } from './smart_apify_storage_backend.js';
24
24
  import { BINARY_CONTENT_TYPE, checkCrawleeVersion, getSystemInfo, isNonEmptyObject, JSON_CONTENT_TYPE, parseInputValue, printOutdatedSdkWarning, snakeCaseToCamelCase, } from './utils.js';
25
+ // `@apify/consts` has no boolean counterpart to `INTEGER_ENV_VARS`.
26
+ const BOOLEAN_ENV_VARS = [APIFY_ENV_VARS.USER_IS_PAYING];
25
27
  /**
26
28
  * {@link parseInputValue} with the parser error wrapped as an {@link ActorInputError}, so a malformed
27
29
  * JSON input reports where it came from.
@@ -99,6 +101,8 @@ export class Actor {
99
101
  #requestQueueAccess = 'single';
100
102
  /** Lazily built by the `#storageBackend` getter. */
101
103
  #cachedStorageBackend;
104
+ /** Listeners registered via `on()` before `init()`; attached to the event manager by `init()`. */
105
+ #pendingListeners = [];
102
106
  constructor(options = {}) {
103
107
  const { configuration, ...configOptions } = options;
104
108
  if (configuration) {
@@ -263,9 +267,18 @@ export class Actor {
263
267
  // Crawlee crawlers, for instance, broadcast their status messages as `statusMessage` events.
264
268
  this.#statusMessageForwarder = async ({ message, isStatusMessageTerminal }) => this.#updateRunStatusMessage(message, isStatusMessageTerminal);
265
269
  this.on(EventType.STATUS_MESSAGE, this.#statusMessageForwarder);
266
- // Connect to the platform events only after the handlers above are registered, so that an event sent
267
- // right after the connection opens (e.g. an already pending `aborting`) is not missed.
268
- await serviceLocator.getEventManager().init();
270
+ // Attach listeners queued before init(), then connect to the platform events only after all handlers
271
+ // are registered, so that an event sent right after the connection opens (e.g. an already pending
272
+ // `aborting`) is not missed.
273
+ const events = serviceLocator.getEventManager();
274
+ if (this.#pendingListeners.length > 0) {
275
+ for (const [event, listener] of this.#pendingListeners) {
276
+ events.on(event, listener);
277
+ }
278
+ log.debug(`Attached ${this.#pendingListeners.length} listener(s) registered before Actor.init()`);
279
+ this.#pendingListeners = [];
280
+ }
281
+ await events.init();
269
282
  log.debug(`Events initialized`);
270
283
  await purgeDefaultStorages({
271
284
  configuration: this.configuration,
@@ -372,12 +385,22 @@ export class Actor {
372
385
  * @ignore
373
386
  */
374
387
  on(event, listener) {
388
+ // Before init() the service locator must stay untouched, otherwise it
389
+ // creates a default Configuration that init() then conflicts with.
390
+ if (!this.initialized) {
391
+ this.#pendingListeners.push([event, listener]);
392
+ return;
393
+ }
375
394
  serviceLocator.getEventManager().on(event, listener);
376
395
  }
377
396
  /**
378
397
  * @ignore
379
398
  */
380
399
  off(event, listener) {
400
+ if (!this.initialized) {
401
+ this.#pendingListeners = this.#pendingListeners.filter(([pendingEvent, pendingListener]) => pendingEvent !== event || (listener !== undefined && pendingListener !== listener));
402
+ return;
403
+ }
381
404
  serviceLocator.getEventManager().off(event, listener);
382
405
  }
383
406
  /**
@@ -475,12 +498,11 @@ export class Actor {
475
498
  async abort(runId, options = {}) {
476
499
  const { token, statusMessage, ...rest } = options;
477
500
  const client = token ? this.newClient({ token }) : this.apifyClient;
501
+ const runClient = client.run(runId);
478
502
  if (statusMessage) {
479
- await this.setStatusMessage(statusMessage, {
480
- isStatusMessageTerminal: true,
481
- });
503
+ await runClient.update({ statusMessage, isStatusMessageTerminal: true });
482
504
  }
483
- return client.run(runId).abort(rest);
505
+ return runClient.abort(rest);
484
506
  }
485
507
  /**
486
508
  * Resurrects a finished Actor run on the Apify platform using the current user account (determined by the `APIFY_TOKEN` environment variable).
@@ -895,11 +917,12 @@ export class Actor {
895
917
  * A record stored as `application/octet-stream` — which is what a local input file without an
896
918
  * extension is read as — is parsed with JSON5 when it parses, and returned as a `Buffer` otherwise.
897
919
  *
898
- * When running locally and the store holds no such record, the input is read from a `<inputKey>` or
899
- * `<inputKey>.json` file in the current working directory, then in the storage directory.
920
+ * When running locally, the input may instead be a `<inputKey>` or `<inputKey>.json` file in the current
921
+ * working directory. A storage backend that doesn't read the default key-value store's directory under
922
+ * the storage directory (e.g. in-memory storage) also gets the file `apify run` writes there.
900
923
  *
901
- * Throws an {@link ActorInputError} when no input is found (`code: 'NOT_FOUND'`), when both input
902
- * files exist in the working/storage directory (`'MULTIPLE_FILES'`), when a JSON input does not parse
924
+ * Throws an {@link ActorInputError} when no input is found (`code: 'NOT_FOUND'`), when the input is
925
+ * found in more than one place (`'MULTIPLE_FILES'`), when a JSON input does not parse
903
926
  * (`'PARSE_FAILED'`) or when its secret fields cannot be decrypted (`'DECRYPTION_FAILED'`). If your
904
927
  * Actor can run without input, catch the `'NOT_FOUND'` case and rethrow the rest.
905
928
  *
@@ -919,17 +942,24 @@ export class Actor {
919
942
  */
920
943
  async getInput() {
921
944
  this.ensureActorInit('getInput');
922
- const { inputKey, inputSecretsPrivateKeyFile, inputSecretsPrivateKeyPassphrase } = this.configuration;
945
+ const { inputKey, inputSecretsPrivateKeyFile, inputSecretsPrivateKeyPassphrase, storageDir, defaultKeyValueStoreId, } = this.configuration;
946
+ // Where `apify run` writes the input (apify-cli `getLocalKeyValueStorePath`).
947
+ const defaultStoreDir = join(storageDir, 'key_value_stores', defaultKeyValueStoreId);
923
948
  const store = await this.openKeyValueStore();
924
949
  const record = await store.getRecord(inputKey);
925
- const rawInput = record
950
+ // Not a conflict check: under the file-system backend the record *is* the store directory's file.
951
+ const storeInput = record
926
952
  ? parseInput(record.value, record.contentType, `the "${inputKey}" record of the default key-value store`)
927
- : ((await this.readInputFromDirectory(inputKey, process.cwd(), 'working directory')) ??
928
- (await this.readInputFromDirectory(inputKey, this.configuration.storageDir, 'storage directory')));
953
+ : await this.readInputFromDirectory(inputKey, defaultStoreDir, 'default key-value store directory');
954
+ const cwdInput = await this.readInputFromDirectory(inputKey, process.cwd(), 'working directory');
955
+ if (storeInput != null && cwdInput != null) {
956
+ 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.`);
957
+ }
958
+ const rawInput = storeInput ?? cwdInput;
929
959
  if (rawInput == null) {
930
960
  const locations = [`the "${inputKey}" record of the default key-value store`];
931
961
  if (!this.configuration.isAtHome) {
932
- locations.push(`a "${inputKey}" or "${inputKey}.json" file in the working or storage directory`);
962
+ locations.push(`a "${inputKey}" or "${inputKey}.json" file in the working or default key-value store directory`);
933
963
  }
934
964
  throw new ActorInputError('NOT_FOUND', `Input does not exist. Expected ${locations.join(' or ')}.`);
935
965
  }
@@ -1158,15 +1188,18 @@ export class Actor {
1158
1188
  })) {
1159
1189
  const camelCaseName = snakeCaseToCamelCase(shortName);
1160
1190
  let value = env[fullName];
1161
- // Parse dates and integers.
1162
- if (value && fullName.endsWith('_AT')) {
1191
+ // Parse booleans, dates and integers.
1192
+ if (BOOLEAN_ENV_VARS.includes(fullName)) {
1193
+ value = !!value && coerceBoolean.parse(value);
1194
+ }
1195
+ else if (value && fullName.endsWith('_AT')) {
1163
1196
  const unix = Date.parse(value);
1164
1197
  value = unix > 0 ? new Date(unix) : undefined;
1165
1198
  }
1166
1199
  else if (INTEGER_ENV_VARS.includes(fullName)) {
1167
1200
  value = parseInt(value, 10);
1168
1201
  }
1169
- Reflect.set(envVars, camelCaseName, value || value === 0 ? value : null);
1202
+ Reflect.set(envVars, camelCaseName, value || value === 0 || value === false ? value : null);
1170
1203
  }
1171
1204
  return envVars;
1172
1205
  }
@@ -1640,11 +1673,11 @@ export class Actor {
1640
1673
  * A record stored as `application/octet-stream` — which is what a local input file without an
1641
1674
  * extension is read as — is parsed with JSON5 when it parses, and returned as a `Buffer` otherwise.
1642
1675
  *
1643
- * When running locally and the store holds no such record, the input is read from a `<inputKey>` or
1644
- * `<inputKey>.json` file in the current working directory instead.
1676
+ * When running locally, the input may instead be a `<inputKey>` or `<inputKey>.json` file in the current
1677
+ * working directory.
1645
1678
  *
1646
- * Throws an {@link ActorInputError} when no input is found (`code: 'NOT_FOUND'`), when both input
1647
- * files exist in the working directory (`'MULTIPLE_FILES'`), when a JSON input does not parse
1679
+ * Throws an {@link ActorInputError} when no input is found (`code: 'NOT_FOUND'`), when the input is
1680
+ * found in more than one place (`'MULTIPLE_FILES'`), when a JSON input does not parse
1648
1681
  * (`'PARSE_FAILED'`) or when its secret fields cannot be decrypted (`'DECRYPTION_FAILED'`). If your
1649
1682
  * Actor can run without input, catch the `'NOT_FOUND'` case and rethrow the rest:
1650
1683
  * ```js
@@ -41,7 +41,7 @@ export declare const apifyConfigFields: {
41
41
  standbyUrl: ConfigField<z.ZodOptional<z.ZodString>>;
42
42
  isAtHome: ConfigField<z.ZodDefault<z.ZodPreprocess<z.ZodBoolean, unknown>>>;
43
43
  userId: ConfigField<z.ZodOptional<z.ZodString>>;
44
- userIsPaying: ConfigField<z.ZodOptional<z.ZodString>>;
44
+ userIsPaying: ConfigField<z.ZodDefault<z.ZodPreprocess<z.ZodBoolean, unknown>>>;
45
45
  actorPermissionLevel: ConfigField<z.ZodOptional<z.ZodString>>;
46
46
  inputSecretsPrivateKeyPassphrase: ConfigField<z.ZodOptional<z.ZodString>>;
47
47
  inputSecretsPrivateKeyFile: ConfigField<z.ZodOptional<z.ZodString>>;
@@ -121,6 +121,7 @@ export interface Configuration extends ApifyResolvedConfigValues {
121
121
  * `proxyPort` | `APIFY_PROXY_PORT` | `8000`
122
122
  * `proxyStatusUrl` | `APIFY_PROXY_STATUS_URL` | `'http://proxy.apify.com'`
123
123
  * `userId` | `APIFY_USER_ID` | -
124
+ * `userIsPaying` | `APIFY_USER_IS_PAYING` | `false`
124
125
  * `xvfb` | `APIFY_XVFB` | -
125
126
  * `standbyPort` | `ACTOR_STANDBY_PORT` | `4321`
126
127
  * `standbyUrl` | `ACTOR_STANDBY_URL` | -
@@ -85,7 +85,7 @@ export const apifyConfigFields = {
85
85
  standbyUrl: field(z.string().optional(), ACTOR_ENV_VARS.STANDBY_URL),
86
86
  isAtHome: field(coerceBoolean.default(false), APIFY_ENV_VARS.IS_AT_HOME),
87
87
  userId: field(z.string().optional(), APIFY_ENV_VARS.USER_ID),
88
- userIsPaying: field(z.string().optional(), APIFY_ENV_VARS.USER_IS_PAYING),
88
+ userIsPaying: field(coerceBoolean.default(false), APIFY_ENV_VARS.USER_IS_PAYING),
89
89
  actorPermissionLevel: field(z.string().optional(), ACTOR_ENV_VARS.PERMISSION_LEVEL),
90
90
  inputSecretsPrivateKeyPassphrase: field(z.string().optional(), APIFY_ENV_VARS.INPUT_SECRETS_PRIVATE_KEY_PASSPHRASE),
91
91
  inputSecretsPrivateKeyFile: field(z.string().optional(), APIFY_ENV_VARS.INPUT_SECRETS_PRIVATE_KEY_FILE),
@@ -164,6 +164,7 @@ export const apifyConfigFields = {
164
164
  * `proxyPort` | `APIFY_PROXY_PORT` | `8000`
165
165
  * `proxyStatusUrl` | `APIFY_PROXY_STATUS_URL` | `'http://proxy.apify.com'`
166
166
  * `userId` | `APIFY_USER_ID` | -
167
+ * `userIsPaying` | `APIFY_USER_IS_PAYING` | `false`
167
168
  * `xvfb` | `APIFY_XVFB` | -
168
169
  * `standbyPort` | `ACTOR_STANDBY_PORT` | `4321`
169
170
  * `standbyUrl` | `ACTOR_STANDBY_URL` | -
package/dist/errors.d.ts CHANGED
@@ -1,8 +1,8 @@
1
1
  /** Why {@link Actor.getInput} could not produce the input. */
2
2
  export type ActorInputErrorCode =
3
- /** No input record in the default key-value store, and locally no input file in the working directory either. */
3
+ /** No input record in the default key-value store, and locally no input file either. */
4
4
  'NOT_FOUND'
5
- /** Both `<inputKey>` and `<inputKey>.json` exist in the working directory, so neither is picked. */
5
+ /** The input is in more than one place — both `<inputKey>` and `<inputKey>.json` in one directory, or in the store and in the working directory — so none is picked. */
6
6
  | 'MULTIPLE_FILES'
7
7
  /** The secret fields of the input could not be decrypted; `cause` holds the underlying error. */
8
8
  | 'DECRYPTION_FAILED'
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "apify",
3
- "version": "4.0.0-beta.71",
3
+ "version": "4.0.0-beta.73",
4
4
  "description": "The scalable web crawling and scraping library for JavaScript/Node.js. Enables development of data extraction and web automation jobs (not only) with headless Chrome and Puppeteer.",
5
5
  "engines": {
6
6
  "node": ">=22.13.0"