@zerodot/apify 1.0.0 → 1.1.0

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 (2) hide show
  1. package/dist/index.cjs +230 -24
  2. package/package.json +4 -4
package/dist/index.cjs CHANGED
@@ -27,7 +27,7 @@ const POLL_MAX_MS = 864e5;
27
27
  /** The most tries of one call. Wait 1, 2, 4, and 8 seconds between tries. */
28
28
  const TRIES = 5;
29
29
  const text = (value) => typeof value === "string" && value.trim() !== "" ? value.trim() : null;
30
- const isObject$2 = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
30
+ const isObject$3 = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
31
31
  /** The token of a credential: an API token or the access token of an OAuth2 sign-in. */
32
32
  function apifyAccess(credential) {
33
33
  if (credential?.type === "apify.apiKey") {
@@ -70,9 +70,9 @@ const HINTS = {
70
70
  */
71
71
  function errorFromBody(answer) {
72
72
  if (typeof answer === "string") return { message: text(answer)?.slice(0, 1e3) ?? void 0 };
73
- if (!isObject$2(answer)) return {};
73
+ if (!isObject$3(answer)) return {};
74
74
  const body = answer;
75
- const detail = isObject$2(body.error) ? body.error : {};
75
+ const detail = isObject$3(body.error) ? body.error : {};
76
76
  const message = text(detail.message) ?? text(body.error) ?? text(body.message) ?? text(answer.detail);
77
77
  const type = text(detail.type) ?? text(body.code);
78
78
  return {
@@ -178,8 +178,8 @@ function decodeBody(answer) {
178
178
  /** An Actor that needs a permission approval gives a link. The message names the link. */
179
179
  function approvalOf(error) {
180
180
  if (error.type !== "full-permission-actor-not-approved") return error;
181
- const body = isObject$2(error.data) ? error.data : {};
182
- const detail = isObject$2(body.error) ? body.error : {};
181
+ const body = isObject$3(error.data) ? error.data : {};
182
+ const detail = isObject$3(body.error) ? body.error : {};
183
183
  const link = text(detail.data?.approvalUrl);
184
184
  if (!link || !/^https?:\/\//.test(link)) return error;
185
185
  return new ApifyError(`${error.message}. Approve the permissions of the Actor at ${link}, then run it again`, error.status, error.type, error.data);
@@ -193,8 +193,8 @@ async function callApify(access, call, options) {
193
193
  }
194
194
  /** The `data` of an Apify answer, such as the run of a run call. */
195
195
  function dataOf(answer) {
196
- const data = isObject$2(answer) ? answer.data : void 0;
197
- return isObject$2(data) ? data : {};
196
+ const data = isObject$3(answer) ? answer.data : void 0;
197
+ return isObject$3(data) ? data : {};
198
198
  }
199
199
  /** Reads the run until it ends. The wait ends at the timeout of the run plus 5 minutes. */
200
200
  async function pollRun(access, runId, options) {
@@ -210,7 +210,7 @@ async function pollRun(access, runId, options) {
210
210
  }, options));
211
211
  if (TERMINAL_RUN_STATUSES.includes(String(run.status))) return run;
212
212
  if (!checked) {
213
- const runOptions = isObject$2(run.options) ? run.options : {};
213
+ const runOptions = isObject$3(run.options) ? run.options : {};
214
214
  const seconds = Number(runOptions.timeoutSecs);
215
215
  if (Number.isFinite(seconds) && seconds > 0) limit = seconds * 1e3 + POLL_BUFFER_MS;
216
216
  checked = true;
@@ -283,6 +283,138 @@ const apifyOAuth2Credential = {
283
283
  iconUrl: APIFY_ICON,
284
284
  test: check
285
285
  };
286
+ // src/loaders.ts
287
+ /** Checks the loader keys of a field. Spread the result in `.meta()`. */
288
+ const loadField = (field) => field;
289
+ /** Where the ID is in a URL of Apify Console. The editor keeps the group when a URL is pasted. */
290
+ const ACTOR_URL_PATTERN = "console\\.apify\\.com/actors/(?!tasks/|runs/)([A-Za-z0-9]+)(?:[/?#].*)?$";
291
+ const TASK_URL_PATTERN = "console\\.apify\\.com/actors/tasks/([A-Za-z0-9]+)(?:[/?#].*)?$";
292
+ const RUN_URL_PATTERN = "console\\.apify\\.com/actors(?:/[A-Za-z0-9]+)?/runs/([A-Za-z0-9]+)(?:[/?#].*)?$";
293
+ /** The size of a page. */
294
+ const PAGE = 100;
295
+ /** Apify can sort the Actors of the account by the last run. This list is one page of 1000. */
296
+ const ACTOR_PAGE = 1e3;
297
+ const isObject$2 = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
298
+ const str = (value) => typeof value === "string" ? value : "";
299
+ /** The items of a list answer of Apify, and the cursor of the next page (offset based). */
300
+ async function page(ctx, path, query) {
301
+ const offset = Number(ctx.cursor ?? 0) || 0;
302
+ const limit = Number(query.limit);
303
+ const answer = dataOf(await callApify(apifyAccess(ctx.credential), {
304
+ method: "GET",
305
+ path,
306
+ query: {
307
+ ...query,
308
+ offset
309
+ }
310
+ }, { signal: ctx.signal }));
311
+ const items = (Array.isArray(answer.items) ? answer.items : []).filter(isObject$2);
312
+ const total = typeof answer.total === "number" ? answer.total : void 0;
313
+ const count = typeof answer.count === "number" ? answer.count : items.length;
314
+ return {
315
+ items,
316
+ next: (total !== void 0 ? offset + count < total : count >= limit) && count > 0 ? String(offset + count) : null
317
+ };
318
+ }
319
+ /** Does the text match the search text, without case? */
320
+ const matcher = (search) => {
321
+ const term = (search ?? "").trim().toLowerCase();
322
+ return (...values) => term === "" || values.some((value) => str(value).toLowerCase().includes(term));
323
+ };
324
+ const actorOption = (actor) => ({
325
+ label: actor.title ? `${str(actor.title)} (${str(actor.username)}/${str(actor.name)})` : `${str(actor.username)}/${str(actor.name)}`,
326
+ value: str(actor.id),
327
+ description: str(actor.description) || str(actor.name)
328
+ });
329
+ /** The Actors that the account ran lately, newest run first. A search filters by title and name. */
330
+ async function recentActors(ctx) {
331
+ const { items, next } = await page(ctx, "/v2/acts", {
332
+ limit: ACTOR_PAGE,
333
+ sortBy: "stats.lastRunStartedAt",
334
+ desc: true
335
+ });
336
+ const matches = matcher(ctx.search);
337
+ return {
338
+ options: items.filter((a) => matches(a.title, a.name)).map(actorOption),
339
+ nextCursor: next
340
+ };
341
+ }
342
+ /** Choose from the Actors of the account, or from Apify Store (`actorSource`). */
343
+ const listActors = async (ctx) => {
344
+ if ((0, _zerodot_node_sdk.configValue)(ctx.config, (0, _zerodot_node_sdk.dependsOnPath)("actorSource", ctx.path)) !== "store") return await recentActors(ctx);
345
+ const { items, next } = await page(ctx, "/v2/store", {
346
+ limit: PAGE,
347
+ search: ctx.search?.trim() || void 0
348
+ });
349
+ return {
350
+ options: items.map(actorOption),
351
+ nextCursor: next
352
+ };
353
+ };
354
+ /** The Actors of the account, for the operations that read runs. */
355
+ const listUserActors = async (ctx) => await recentActors(ctx);
356
+ const listActorTasks = async (ctx) => {
357
+ const { items, next } = await page(ctx, "/v2/actor-tasks", { limit: PAGE });
358
+ const matches = matcher(ctx.search);
359
+ return {
360
+ options: items.filter((task) => matches(task.title, task.name)).map((task) => ({
361
+ label: str(task.title) || str(task.name),
362
+ value: str(task.id),
363
+ description: str(task.name)
364
+ })),
365
+ nextCursor: next
366
+ };
367
+ };
368
+ const listRuns = async (ctx) => {
369
+ const { items, next } = await page(ctx, "/v2/actor-runs", {
370
+ limit: PAGE,
371
+ desc: 1
372
+ });
373
+ return {
374
+ options: items.map((run) => {
375
+ const finished = str(run.finishedAt);
376
+ return {
377
+ label: [finished ? `${new Date(finished).toDateString()} ${new Date(finished).toLocaleTimeString()}` : void 0, str(run.status)].filter(Boolean).join(" - ") || str(run.id),
378
+ value: str(run.id),
379
+ description: str(run.status)
380
+ };
381
+ }),
382
+ nextCursor: next
383
+ };
384
+ };
385
+ const listKeyValueStores = async (ctx) => {
386
+ const { items, next } = await page(ctx, "/v2/key-value-stores", { limit: PAGE });
387
+ return {
388
+ options: items.map((store) => ({
389
+ label: str(store.name) || str(store.id),
390
+ value: str(store.id),
391
+ description: str(store.name) || void 0
392
+ })),
393
+ nextCursor: next
394
+ };
395
+ };
396
+ /** The keys of the store in `storeId`. Apify pages keys with `exclusiveStartKey`. */
397
+ const listRecordKeys = async (ctx) => {
398
+ const storeId = str((0, _zerodot_node_sdk.configValue)(ctx.config, (0, _zerodot_node_sdk.dependsOnPath)("storeId", ctx.path))).trim();
399
+ if (storeId === "") return [];
400
+ const answer = dataOf(await callApify(apifyAccess(ctx.credential), {
401
+ method: "GET",
402
+ path: `/v2/key-value-stores/${segment(storeId, "storeId")}/keys`,
403
+ query: {
404
+ limit: PAGE,
405
+ exclusiveStartKey: ctx.cursor
406
+ }
407
+ }, { signal: ctx.signal }));
408
+ const items = (Array.isArray(answer.items) ? answer.items : []).filter(isObject$2);
409
+ const next = answer.isTruncated === true ? str(answer.nextExclusiveStartKey) : "";
410
+ return {
411
+ options: items.map((item) => ({
412
+ label: str(item.key),
413
+ value: str(item.key)
414
+ })),
415
+ nextCursor: next || null
416
+ };
417
+ };
286
418
  // src/config.ts
287
419
  const AUTHENTICATIONS = ["apifyApi", "apifyOAuth2Api"];
288
420
  const AUTHENTICATION_LABELS = {
@@ -315,6 +447,11 @@ const OPERATIONS_OF = {
315
447
  keyValueStore: ["getRecord"]
316
448
  };
317
449
  const ALL_OPERATIONS = [...new Set(Object.values(OPERATIONS_OF).flat())];
450
+ const ACTOR_SOURCES = ["recentlyUsed", "store"];
451
+ const ACTOR_SOURCE_LABELS = {
452
+ recentlyUsed: "Recently Used Actors",
453
+ store: "Apify Store Actors"
454
+ };
318
455
  const RUN_STATUSES = [
319
456
  "ABORTED",
320
457
  "ABORTING",
@@ -439,6 +576,19 @@ const apifyConfig = zod.z.object({
439
576
  getRecord: "Get the value stored under a key"
440
577
  }
441
578
  }),
579
+ actorSource: zod.z.enum(ACTOR_SOURCES).default("recentlyUsed").meta({
580
+ showWhen: [{
581
+ resource: ["actor"],
582
+ operation: [
583
+ "run",
584
+ "runAndGetDataset",
585
+ "sendServerActorRequest"
586
+ ]
587
+ }],
588
+ title: "Actor Source",
589
+ description: "Choose whether to pick from your recently used Actors or from Apify Store",
590
+ labels: ACTOR_SOURCE_LABELS
591
+ }),
442
592
  actorId: zod.z.string().optional().meta({
443
593
  showWhen: [{
444
594
  resource: ["actor"],
@@ -450,7 +600,13 @@ const apifyConfig = zod.z.object({
450
600
  }],
451
601
  title: "Actor",
452
602
  description: "The ID of the Actor, as \"username~actor-name\" (for example \"apify~web-scraper\") or a plain Actor ID. A URL from Apify Console works too. Find Actors at https://apify.com/store",
453
- placeholder: "janedoe~my-actor"
603
+ placeholder: "janedoe~my-actor",
604
+ ...loadField({
605
+ loadOptions: "actors",
606
+ dependsOn: ["actorSource"],
607
+ searchable: true,
608
+ urlPattern: ACTOR_URL_PATTERN
609
+ })
454
610
  }),
455
611
  userActorId: zod.z.string().optional().meta({
456
612
  showWhen: [{
@@ -462,13 +618,23 @@ const apifyConfig = zod.z.object({
462
618
  }],
463
619
  title: "Actor",
464
620
  description: "The ID of the Actor, as \"username~actor-name\" or a plain Actor ID. A URL from Apify Console works too",
465
- placeholder: "janedoe~my-actor"
621
+ placeholder: "janedoe~my-actor",
622
+ ...loadField({
623
+ loadOptions: "userActors",
624
+ searchable: true,
625
+ urlPattern: ACTOR_URL_PATTERN
626
+ })
466
627
  }),
467
628
  actorTaskId: zod.z.string().optional().meta({
468
629
  ...on({ actorTask: ["run", "runAndGetDataset"] }),
469
630
  title: "Actor Task",
470
631
  description: "The ID of the task, as \"username~task-name\" or a plain task ID. A URL from Apify Console works too. Manage tasks at https://console.apify.com",
471
- placeholder: "janedoe~my-task"
632
+ placeholder: "janedoe~my-task",
633
+ ...loadField({
634
+ loadOptions: "actorTasks",
635
+ searchable: true,
636
+ urlPattern: TASK_URL_PATTERN
637
+ })
472
638
  }),
473
639
  useCustomBody: zod.z.boolean().default(false).meta({
474
640
  ...on({ actorTask: ["run", "runAndGetDataset"] }),
@@ -593,7 +759,11 @@ const apifyConfig = zod.z.object({
593
759
  operation: ["get"]
594
760
  },
595
761
  title: "Run ID",
596
- description: "The ID of the run. A URL from Apify Console works too"
762
+ description: "The ID of the run. A URL from Apify Console works too",
763
+ ...loadField({
764
+ loadOptions: "runs",
765
+ urlPattern: RUN_URL_PATTERN
766
+ })
597
767
  }),
598
768
  abortRunId: zod.z.string().optional().meta({
599
769
  showWhen: {
@@ -632,7 +802,8 @@ const apifyConfig = zod.z.object({
632
802
  resource: ["dataset"],
633
803
  operation: ["getItems"]
634
804
  },
635
- title: "Options"
805
+ title: "Options",
806
+ ui: "collection"
636
807
  }),
637
808
  storeId: zod.z.string().optional().meta({
638
809
  showWhen: {
@@ -640,7 +811,8 @@ const apifyConfig = zod.z.object({
640
811
  operation: ["getRecord"]
641
812
  },
642
813
  title: "Key-Value Store ID",
643
- description: "The ID of the key-value store"
814
+ description: "The ID of the key-value store",
815
+ ...loadField({ loadOptions: "keyValueStores" })
644
816
  }),
645
817
  recordKey: zod.z.string().optional().meta({
646
818
  showWhen: {
@@ -649,7 +821,11 @@ const apifyConfig = zod.z.object({
649
821
  },
650
822
  title: "Key-Value Store Record Key",
651
823
  description: "The key of the record",
652
- placeholder: "RECORD_KEY"
824
+ placeholder: "RECORD_KEY",
825
+ ...loadField({
826
+ loadOptions: "recordKeys",
827
+ dependsOn: ["storeId"]
828
+ })
653
829
  }),
654
830
  offset: zod.z.number().int().min(0).default(0).meta({
655
831
  ...pages,
@@ -1157,6 +1333,14 @@ var node_default = (0, _zerodot_node_sdk.defineNode)({
1157
1333
  offset: 0,
1158
1334
  limit: 50
1159
1335
  },
1336
+ loadOptions: {
1337
+ actors: listActors,
1338
+ userActors: listUserActors,
1339
+ actorTasks: listActorTasks,
1340
+ runs: listRuns,
1341
+ keyValueStores: listKeyValueStores,
1342
+ recordKeys: listRecordKeys
1343
+ },
1160
1344
  credentialTypes: [APIFY_API_CREDENTIAL, APIFY_OAUTH2_CREDENTIAL],
1161
1345
  credentialRules: {
1162
1346
  [APIFY_API_CREDENTIAL]: { showWhen: { authentication: ["apifyApi"] } },
@@ -1183,6 +1367,13 @@ const RUN_EVENTS = [
1183
1367
  "ACTOR.RUN.TIMED_OUT",
1184
1368
  "ACTOR.RUN.ABORTED"
1185
1369
  ];
1370
+ const EVENT_TYPES = [
1371
+ "ACTOR.RUN.ABORTED",
1372
+ "any",
1373
+ "ACTOR.RUN.FAILED",
1374
+ "ACTOR.RUN.SUCCEEDED",
1375
+ "ACTOR.RUN.TIMED_OUT"
1376
+ ];
1186
1377
  const triggerConfig = zod.z.object({
1187
1378
  authentication: zod.z.enum(AUTHENTICATIONS).default("apifyApi").meta({
1188
1379
  title: "Authentication",
@@ -1205,25 +1396,36 @@ const triggerConfig = zod.z.object({
1205
1396
  task: "Watch the runs of one saved task"
1206
1397
  }
1207
1398
  }),
1399
+ actorSource: zod.z.enum(ACTOR_SOURCES).default("recentlyUsed").meta({
1400
+ showWhen: { resource: ["actor"] },
1401
+ title: "Actor Source",
1402
+ description: "Choose whether to pick from your recently used Actors or from Apify Store",
1403
+ labels: ACTOR_SOURCE_LABELS
1404
+ }),
1208
1405
  actorId: zod.z.string().optional().meta({
1209
1406
  showWhen: { resource: ["actor"] },
1210
1407
  title: "Actor",
1211
1408
  description: "The ID of the Actor, as \"username~actor-name\" or a plain Actor ID. A URL from Apify Console works too",
1212
- placeholder: "janedoe~my-actor"
1409
+ placeholder: "janedoe~my-actor",
1410
+ ...loadField({
1411
+ loadOptions: "actors",
1412
+ dependsOn: ["actorSource"],
1413
+ searchable: true,
1414
+ urlPattern: ACTOR_URL_PATTERN
1415
+ })
1213
1416
  }),
1214
1417
  actorTaskId: zod.z.string().optional().meta({
1215
1418
  showWhen: { resource: ["task"] },
1216
1419
  title: "Saved Tasks Name or ID",
1217
1420
  description: "The ID of the task to watch, as \"username~task-name\" or a plain task ID. A URL from Apify Console works too",
1218
- placeholder: "janedoe~my-task"
1421
+ placeholder: "janedoe~my-task",
1422
+ ...loadField({
1423
+ loadOptions: "actorTasks",
1424
+ searchable: true,
1425
+ urlPattern: TASK_URL_PATTERN
1426
+ })
1219
1427
  }),
1220
- eventType: zod.z.array(zod.z.enum([
1221
- "ACTOR.RUN.ABORTED",
1222
- "any",
1223
- "ACTOR.RUN.FAILED",
1224
- "ACTOR.RUN.SUCCEEDED",
1225
- "ACTOR.RUN.TIMED_OUT"
1226
- ])).min(1).default(["ACTOR.RUN.SUCCEEDED"]).meta({
1428
+ eventType: zod.z.array(zod.z.enum(EVENT_TYPES)).min(1).default(["ACTOR.RUN.SUCCEEDED"]).meta({
1227
1429
  title: "Event Type",
1228
1430
  description: "The status of the run that starts the workflow",
1229
1431
  labels: {
@@ -1418,6 +1620,10 @@ const nodes = [(0, _zerodot_node_sdk.defineNode)({
1418
1620
  return null;
1419
1621
  }
1420
1622
  },
1623
+ loadOptions: {
1624
+ actors: listActors,
1625
+ actorTasks: listActorTasks
1626
+ },
1421
1627
  webhookTest: { hint: "A test run makes a webhook at Apify for the test address. Run the Actor or the task to send an event" }
1422
1628
  }), node_default];
1423
1629
  const credentialTypes = [apifyApiCredential, apifyOAuth2Credential];
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@zerodot/apify",
3
- "version": "1.0.0",
3
+ "version": "1.1.0",
4
4
  "description": "Run Apify Actors and tasks, get runs, dataset items, and key-value store records, fetch web pages, and start a workflow when a run of an Actor or task ends. Use it for web scraping and data extraction.",
5
5
  "license": "AGPL-3.0-only",
6
6
  "repository": {
@@ -21,7 +21,7 @@
21
21
  "apify.svg"
22
22
  ],
23
23
  "zerodot": {
24
- "sdk": "^1.2",
24
+ "sdk": "^1.7",
25
25
  "label": "Apify",
26
26
  "summary": "Actors, tasks, runs, datasets, records, and run events"
27
27
  },
@@ -30,12 +30,12 @@
30
30
  },
31
31
  "dependencies": {},
32
32
  "peerDependencies": {
33
- "@zerodot/node-sdk": "^1.2.0",
33
+ "@zerodot/node-sdk": "^1.7.0",
34
34
  "zod": "^4.0.0"
35
35
  },
36
36
  "devDependencies": {
37
37
  "@types/node": "26.6.5",
38
- "@zerodot/node-sdk": "^1.2.1",
38
+ "@zerodot/node-sdk": "^1.7.0",
39
39
  "tsdown": "0.23.2",
40
40
  "tsx": "4.23.15",
41
41
  "typescript": "7.0.2",