@howells/fieldwork-sdk 0.5.0 → 0.5.2

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/firecrawl.js CHANGED
@@ -1,11 +1,13 @@
1
1
  import { t as defineAdapter } from "./adapter-DWYJys20.js";
2
- import { i as withJob, r as invalidRequest, t as FieldworkError } from "./errors-Yvk42oZH.js";
3
- import { C as createRawClient, D as segment, E as requireKey, F as presentPage, I as presentPages, N as meta, O as callSettings, R as refuseTogether, S as withOriginal, a as looseObject, b as warningEntry, c as optionalArrayOf, d as optionalId, f as optionalNumber, h as optionalString, i as both, j as compact, l as optionalBoolean, m as optionalScalar, n as anything, p as optionalObject, r as arrayOf, s as optionalAnyString, u as optionalFirstString, v as recordOf, w as poll, z as requireJobId } from "./parse-D4SMt-Ip.js";
4
- import { n as jsonSchemaOf, t as checkOutput } from "./schema-DbSIABP0.js";
5
- import { a as refuseLarger, i as mediaTypeOf, n as documentPart, t as MEDIA_TYPES } from "./document-Dpj01mGx.js";
2
+ import { r as invalidRequest, t as FieldworkError } from "./errors-DROZyb9T.js";
3
+ import { B as requireJobId, C as createRawClient, E as segment, I as presentPage, L as presentPages, M as compact, P as meta, S as withOriginal, T as requireKey, a as looseObject, b as warningEntry, c as optionalArrayOf, d as optionalId, f as optionalNumber, h as optionalString, i as both, k as callSettings, l as optionalBoolean, m as optionalScalar, n as anything, p as optionalObject, r as arrayOf, s as optionalAnyString, u as optionalFirstString, v as recordOf, z as refuseTogether } from "./parse-BY3R0oWO.js";
4
+ import { t as runJob } from "./job-DVsmQMKP.js";
5
+ import { n as jsonSchemaOf, t as checkOutput } from "./schema-BYcXgfuZ.js";
6
+ import { a as refuseLarger, i as mediaTypeOf, n as documentPart, t as MEDIA_TYPES } from "./document-CjMeBtV5.js";
6
7
  import * as z from "zod/mini";
7
8
  // src/adapters/firecrawl/shared.ts
8
9
  const provider = "firecrawl";
10
+ /** A country code in upper case, as sent to Firecrawl. */
9
11
  const country = (code) => code?.toUpperCase();
10
12
  // src/adapters/firecrawl/schedule.ts
11
13
  /** The fewest minutes Firecrawl allows between two checks of a monitor. */
@@ -15,6 +17,7 @@ const NAMED_CRON = /* @__PURE__ */ new Map([
15
17
  ["day", "0 0 * * *"],
16
18
  ["week", "0 0 * * 0"]
17
19
  ]);
20
+ /** The day counts that have a cron: every day, and every seven days (Sunday). */
18
21
  const DAILY_CRON = /* @__PURE__ */ new Map([[1, "0 0 * * *"], [7, "0 0 * * 0"]]);
19
22
  const CRON_PART = /^(?:\*|(?<from>\d+)(?:-(?<to>\d+))?)(?:\/(?<step>\d+))?$/u;
20
23
  const INTERVAL = /^(?<count>\d+)(?<unit>[hd])$/u;
@@ -22,6 +25,7 @@ const rangeEnd = (groups, wildcard, from, max) => {
22
25
  if (wildcard || groups.to === void 0 && groups.step !== void 0) return max;
23
26
  return groups.to === void 0 ? from : Number(groups.to);
24
27
  };
28
+ /** The sorted values a minute or hour field matches (lists, ranges and steps), or undefined for a field it cannot read, such as one with names. */
25
29
  const cronValues = (field, max) => {
26
30
  const values = /* @__PURE__ */ new Set();
27
31
  for (const part of field.split(",")) {
@@ -36,6 +40,7 @@ const cronValues = (field, max) => {
36
40
  }
37
41
  return [...values].toSorted((a, b) => a - b);
38
42
  };
43
+ /** The minutes between runs within an hour, and across the hour boundary when two consecutive hours both run. */
39
44
  const runGaps = (minutes, hours) => {
40
45
  const gaps = minutes.slice(1).map((minute, index) => minute - (minutes[index] ?? 0));
41
46
  const [first] = minutes;
@@ -43,6 +48,11 @@ const runGaps = (minutes, hours) => {
43
48
  if (hours?.some((hour) => hours.includes((hour + 1) % 24)) === true && first !== void 0 && last !== void 0) gaps.push(60 - last + first);
44
49
  return gaps;
45
50
  };
51
+ /**
52
+ * Refuses an expression that is not five fields, or that can run less than
53
+ * `MIN_MINUTES` apart. A minute or hour field `cronValues` cannot read is not
54
+ * checked.
55
+ */
46
56
  const checkCron = (cron) => {
47
57
  const fields = cron.trim().split(/\s+/u);
48
58
  if (fields.length !== 5) throw invalidRequest(provider, `needs a five-field cron expression, got "${cron}"`);
@@ -52,11 +62,18 @@ const checkCron = (cron) => {
52
62
  if (minutes && runGaps(minutes, hours).some((gap) => gap < MIN_MINUTES)) throw invalidRequest(provider, `monitors run at most every ${MIN_MINUTES} minutes, got "${cron}"`);
53
63
  return cron.trim();
54
64
  };
65
+ /** The cron for every `count` hours. Only counts that divide 24 have one. */
55
66
  const hourlyCron = (count) => {
56
67
  if (!Number.isInteger(count) || count < 1 || 24 % count !== 0) return;
57
68
  if (count === 1) return "0 * * * *";
58
69
  return count === 24 ? "0 0 * * *" : `0 */${count} * * *`;
59
70
  };
71
+ /**
72
+ * The cron expression for a schedule. A cron is checked and passed through. A
73
+ * named interval becomes a cron: `hour` (on the hour), `day`, `1d` (midnight),
74
+ * `week`, `7d` (midnight on Sunday), or `Nh` for an N that divides 24. Throws
75
+ * `InvalidRequest` for any other interval.
76
+ */
60
77
  const cronFor = (schedule) => {
61
78
  if ("cron" in schedule) return checkCron(schedule.cron);
62
79
  const every = schedule.every;
@@ -79,6 +96,7 @@ const MAX_PARSE_MS = 3e5;
79
96
  const REPORT_GRACE_MS = 1e4;
80
97
  /** The longest query a search monitor takes. */
81
98
  const MAX_MONITOR_QUERY = 256;
99
+ /** Firecrawl's `qdr:` units, for each named recency window. */
82
100
  const RECENCY = {
83
101
  day: "d",
84
102
  hour: "h",
@@ -87,6 +105,7 @@ const RECENCY = {
87
105
  year: "y"
88
106
  };
89
107
  const DATE = /^(?<year>\d{4})-(?<month>\d{2})-(?<day>\d{2})$/u;
108
+ /** The page-fetching fields every scrape takes. `maxAge` goes out in milliseconds, and the rest as they are. */
90
109
  const pageBody = (o) => compact({
91
110
  actions: o.actions,
92
111
  excludeTags: o.excludeTags,
@@ -99,6 +118,7 @@ const pageBody = (o) => compact({
99
118
  proxy: o.proxy,
100
119
  waitFor: o.waitFor
101
120
  });
121
+ /** The formats a read asks for: Markdown always, then `include`, then `query` as highlights (the default) or a question. */
102
122
  const readFormats = (o) => {
103
123
  const query = o.query === void 0 ? [] : [o.queryFormat === "question" ? {
104
124
  question: o.query,
@@ -113,15 +133,22 @@ const readFormats = (o) => {
113
133
  ...query
114
134
  ];
115
135
  };
136
+ /** The scrape body for a read: its formats and page settings. */
116
137
  const readBody = (o) => ({
117
138
  formats: readFormats(o),
118
139
  ...pageBody(o)
119
140
  });
141
+ /** Firecrawl's date filter takes MM/DD/YYYY; the options take YYYY-MM-DD. */
120
142
  const usDate = (value) => {
121
143
  const groups = DATE.exec(value)?.groups;
122
144
  if (!groups) throw invalidRequest(provider, `needs dates as YYYY-MM-DD, got "${value}"`);
123
145
  return `${groups.month}/${groups.day}/${groups.year}`;
124
146
  };
147
+ /**
148
+ * The `tbs` time filter: `tbs` as given, else `recency` as `qdr:`, else the
149
+ * published dates as a `cdr:1` range with `cd_min` and `cd_max`. Refuses
150
+ * `tbs`, `recency` and the dates in combination.
151
+ */
125
152
  const timeFilter = (o) => {
126
153
  refuseTogether(provider, o, "tbs", "recency", "publishedAfter");
127
154
  refuseTogether(provider, o, "tbs", "recency", "publishedBefore");
@@ -134,6 +161,7 @@ const timeFilter = (o) => {
134
161
  o.publishedBefore === void 0 ? void 0 : `cd_max:${usDate(o.publishedBefore)}`
135
162
  ].filter((part) => part !== void 0).join(",");
136
163
  };
164
+ /** The `/search` body. `content` asks for each result's Markdown. Refuses `includeDomains` with `excludeDomains`, and `gov` with another category. */
137
165
  const searchBody = (query, o) => {
138
166
  refuseTogether(provider, o, "includeDomains", "excludeDomains");
139
167
  if (o.categories?.includes("gov") === true && o.categories.length > 1) throw invalidRequest(provider, "searches the gov category on its own; do not combine it with another category");
@@ -152,6 +180,7 @@ const searchBody = (query, o) => {
152
180
  tbs: timeFilter(o)
153
181
  });
154
182
  };
183
+ /** The `/search` body for images: the `images` source alone. */
155
184
  const imagesBody = (query, o) => compact({
156
185
  country: country(o.country),
157
186
  limit: o.limit,
@@ -170,6 +199,7 @@ const mapBody = (url, o) => compact({
170
199
  sitemap: o.sitemap,
171
200
  url
172
201
  });
202
+ /** The `/crawl` body. `scrapeOptions` is built like a read's body. */
173
203
  const crawlBody = (url, o) => compact({
174
204
  allowExternalLinks: o.allowExternalLinks,
175
205
  allowSubdomains: o.allowSubdomains,
@@ -187,6 +217,7 @@ const crawlBody = (url, o) => compact({
187
217
  sitemap: o.sitemap,
188
218
  url
189
219
  });
220
+ /** The `/agent` body. `continueFrom` is sent as `threadId`, and `country` as `location`. */
190
221
  const researchBody = (question, o) => compact({
191
222
  effort: o.effort,
192
223
  location: o.country === void 0 || o.country === "" ? void 0 : { country: country(o.country) },
@@ -198,12 +229,18 @@ const researchBody = (question, o) => compact({
198
229
  threadId: o.continueFrom,
199
230
  urls: o.urls
200
231
  });
232
+ /** The body that opens a browser session. `activityTtl` falls back to `ttl`. */
201
233
  const sessionBody = (o) => compact({
202
234
  activityTtl: o.activityTtl ?? o.ttl,
203
235
  location: o.country === void 0 || o.country === "" ? void 0 : { country: country(o.country) },
204
236
  profile: o.profile,
205
237
  ttl: o.ttl
206
238
  });
239
+ /**
240
+ * Refuses session settings given together with `session`, since that session
241
+ * is already open. Returns the call's `timeout` as whole seconds for the
242
+ * script's limit (at least 1), and refuses one over `MAX_SCRIPT_SECONDS`.
243
+ */
207
244
  const checkAct = (o, timeout) => {
208
245
  for (const name of [
209
246
  "ttl",
@@ -216,6 +253,11 @@ const checkAct = (o, timeout) => {
216
253
  if (seconds > MAX_SCRIPT_SECONDS) throw invalidRequest(provider, `runs a script for at most ${MAX_SCRIPT_SECONDS} seconds`);
217
254
  return seconds;
218
255
  };
256
+ /**
257
+ * The request that runs a script. The request waits `REPORT_GRACE_MS` longer
258
+ * than the script's own limit, so Firecrawl reports a timeout before the client
259
+ * gives up.
260
+ */
219
261
  const scriptRequest = (code, language, call, seconds) => ({
220
262
  body: compact({
221
263
  code,
@@ -226,6 +268,10 @@ const scriptRequest = (code, language, call, seconds) => ({
226
268
  signal: call.signal,
227
269
  timeout: call.timeout === void 0 ? void 0 : call.timeout + REPORT_GRACE_MS
228
270
  });
271
+ /**
272
+ * The multipart body of a `/parse` call. Refuses a file type it does not know,
273
+ * a file over `MAX_PARSE_MB` and a `timeout` over `MAX_PARSE_MS`.
274
+ */
229
275
  const parseForm = (document, o, timeout) => {
230
276
  if (timeout !== void 0 && timeout > MAX_PARSE_MS) throw invalidRequest(provider, `parses for at most ${MAX_PARSE_MS / 1e3} seconds`);
231
277
  if (mediaTypeOf(document.name) === void 0) throw invalidRequest(provider, `parses ${[...MEDIA_TYPES.keys()].join(", ")} files, not "${document.name}"`);
@@ -247,6 +293,11 @@ const parseForm = (document, o, timeout) => {
247
293
  form.set("file", documentPart(document), document.name);
248
294
  return form;
249
295
  };
296
+ /**
297
+ * A monitor's target: a scrape of `urls`, or a search for `query`. Refuses
298
+ * search-only options with `urls`, no `urls` and no `query`, and a search query
299
+ * over `MAX_MONITOR_QUERY` characters.
300
+ */
250
301
  const monitorTarget = (o) => {
251
302
  const searchOnly = [
252
303
  o.searchWindow,
@@ -272,6 +323,7 @@ const monitorTarget = (o) => {
272
323
  type: "search"
273
324
  });
274
325
  };
326
+ /** The `/monitor` body. `query` is also the monitor's `goal`, and the name defaults to the query or first URL, cut to 256 characters. */
275
327
  const monitorBody = (o) => {
276
328
  const target = monitorTarget(o);
277
329
  return compact({
@@ -297,11 +349,14 @@ const PAPER_URLS = /* @__PURE__ */ new Map([
297
349
  const LANGUAGE = /^(?<code>[a-z]{2})(?:[-_]|$)/u;
298
350
  /** The list, or undefined when it is empty. */
299
351
  const some = (items) => items.length > 0 ? [...items] : void 0;
352
+ /** The two-letter code of a locale such as `en-GB` or `en_GB`. */
300
353
  const languageCode = (value) => LANGUAGE.exec(value?.toLowerCase() ?? "")?.groups?.code;
354
+ /** The passages for a page: the `highlights` text, else the highlight list, else the written `answer` of a `question` query. */
301
355
  const excerptsOf = (data) => {
302
356
  const { list, text } = data.highlights;
303
357
  return (text === void 0 ? some(list) : [text]) ?? (data.answer === void 0 ? void 0 : [data.answer]);
304
358
  };
359
+ /** The credits and scrape id of a page, with its warnings and those of the whole response. */
305
360
  const pageMeta = (data, topNotes) => meta({
306
361
  credits: data.metadata.creditsUsed,
307
362
  requestId: data.metadata.scrapeId,
@@ -331,6 +386,7 @@ const toPage = (data, fallbackUrl, topNotes = []) => {
331
386
  url: metadata.url ?? metadata.sourceURL ?? fallbackUrl
332
387
  });
333
388
  };
389
+ /** A price; undefined when Firecrawl gave none of its fields. */
334
390
  const price = (item) => {
335
391
  const result = compact({
336
392
  amount: item.amount,
@@ -339,6 +395,7 @@ const price = (item) => {
339
395
  });
340
396
  return Object.keys(result).length > 0 ? result : void 0;
341
397
  };
398
+ /** The first non-empty GTIN, from `gtin` then the 14, 13, 12 and 8 digit forms. */
342
399
  const gtin = (variant) => [
343
400
  variant.gtin,
344
401
  variant.gtin14,
@@ -362,6 +419,7 @@ const toVariant = (variant) => {
362
419
  values: Object.keys(values).length > 0 ? values : void 0
363
420
  });
364
421
  };
422
+ /** The variants' images without repeats, by URL. Used when the product lists none of its own. */
365
423
  const allImages = (variants) => {
366
424
  const seen = /* @__PURE__ */ new Map();
367
425
  for (const image of variants.flatMap((variant) => variant.images ?? [])) if (!seen.has(image.url)) seen.set(image.url, image);
@@ -385,6 +443,7 @@ const toProduct = (body) => {
385
443
  };
386
444
  /** Why a page has no product: the warning it carries, if any. */
387
445
  const noProductReason = (body) => body.data.warning.text ?? body.warning.text;
446
+ /** A web or news result. `kind` is the result's own category, else its source; `snippet` is its description, else its snippet. */
388
447
  const searchItem = (result, kind) => compact({
389
448
  content: result.markdown,
390
449
  image: result.imageUrl,
@@ -394,6 +453,11 @@ const searchItem = (result, kind) => compact({
394
453
  title: result.title,
395
454
  url: result.url ?? ""
396
455
  });
456
+ /**
457
+ * A research result. Papers carry ids rather than URLs: a `web:` id holds the
458
+ * URL itself, and an `arxiv`, `pmid`, `pmcid` or `doi` id resolves through
459
+ * `PAPER_URLS`. Any other id is used as it is.
460
+ */
397
461
  const paperItem = (paper) => {
398
462
  const paperId = paper.paperId ?? "";
399
463
  const primary = paper.primaryId ?? paperId;
@@ -407,6 +471,7 @@ const paperItem = (paper) => {
407
471
  url: paperId.startsWith("web:") ? paperId.slice(4) : resolve?.(primary.slice(colon + 1)) ?? primary
408
472
  });
409
473
  };
474
+ /** Image results. `sourceUrl` is the page the image is on; an item without an image URL is dropped. */
410
475
  const imageItems = (found) => found.flatMap((image) => {
411
476
  const { imageUrl: url } = image;
412
477
  return url === void 0 ? [] : [compact({
@@ -417,12 +482,13 @@ const imageItems = (found) => found.flatMap((image) => {
417
482
  width: image.imageWidth
418
483
  })];
419
484
  });
485
+ /** The credits, request id and warnings of a search. */
420
486
  const searchMeta = (body) => meta({
421
487
  credits: body.creditsUsed,
422
488
  requestId: body.id,
423
489
  warnings: [...body.warning, ...body.warnings]
424
490
  });
425
- /** The results of a search; the caller adds `raw`. */
491
+ /** The results of a search, web then news then research; the caller adds `raw`. Images are kept apart in `images`. */
426
492
  const searchResult = (body) => {
427
493
  const { data } = body;
428
494
  return compact({
@@ -435,14 +501,21 @@ const searchResult = (body) => {
435
501
  ]
436
502
  });
437
503
  };
504
+ /** The image results of a search for images; the caller adds `raw`. */
438
505
  const imagesResult = (body) => compact({
439
506
  meta: searchMeta(body),
440
507
  results: imageItems(body.data.images ?? [])
441
508
  });
509
+ /** The pages a crawl or batch could not read. */
442
510
  const failedPages = (errors) => errors.value.errors.map((entry) => ({
443
511
  error: entry.error ?? "unknown error",
444
512
  url: entry.url ?? ""
445
513
  }));
514
+ /**
515
+ * The run when it has finished, undefined while it runs. A `failed` run that
516
+ * left partial output counts as finished; any other `failed` or `cancelled`
517
+ * run throws `JobFailed`.
518
+ */
446
519
  const researchState = (id, entry) => {
447
520
  const status = entry.value;
448
521
  const state = status.status;
@@ -454,6 +527,12 @@ const researchState = (id, entry) => {
454
527
  });
455
528
  return done ? entry : void 0;
456
529
  };
530
+ /**
531
+ * The result of a finished run. A `failed` run with partial output is
532
+ * `partial`, with that output and a `stopReason`; any other is `completed`
533
+ * with `data`, else the message. `sources` is always empty. The continuation
534
+ * id is the run's thread.
535
+ */
457
536
  const researchResult = (id, started, entry) => {
458
537
  const run = entry.value;
459
538
  const stopped = run.status === "failed";
@@ -473,6 +552,10 @@ const researchResult = (id, started, entry) => {
473
552
  stopReason: stopped ? run.stopReason ?? run.error ?? "failed" : void 0
474
553
  });
475
554
  };
555
+ /**
556
+ * The outcome of a script. `sessionId` is set only when the session is still
557
+ * open or could not be closed; `close` is what closing it returned.
558
+ */
476
559
  const actResult = (entry, sessionId, close) => {
477
560
  const result = entry.value;
478
561
  const stdout = result.stdout ?? "";
@@ -493,6 +576,7 @@ const actResult = (entry, sessionId, close) => {
493
576
  stdout
494
577
  });
495
578
  };
579
+ /** An open browser session. Throws `ProviderError` when Firecrawl returned no id. */
496
580
  const browserSession = (entry) => {
497
581
  const session = entry.value;
498
582
  return compact({
@@ -503,7 +587,7 @@ const browserSession = (entry) => {
503
587
  raw: entry.original
504
588
  });
505
589
  };
506
- /** Firecrawl's blocks, a page at a time; a page without a number is left out. */
590
+ /** Firecrawl's blocks, a page at a time; a page without a number is left out. `box` is set only when `bbox` has four numbers. */
507
591
  const documentBlocks = (pages) => pages.flatMap((entry) => {
508
592
  const page = entry.pageNumber;
509
593
  if (page === void 0) return [];
@@ -536,6 +620,7 @@ const parseResult = (body) => {
536
620
  meta: pageMeta(data, body.warning.notes)
537
621
  });
538
622
  };
623
+ /** What a monitor watches: its goal, else its target URLs or queries joined with commas. */
539
624
  const watching = (monitor) => {
540
625
  if (monitor.goal !== void 0) return monitor.goal;
541
626
  return monitor.targets.flatMap((target) => {
@@ -544,6 +629,7 @@ const watching = (monitor) => {
544
629
  return target.queries;
545
630
  }).filter((item) => item !== void 0).join(", ") || void 0;
546
631
  };
632
+ /** A monitor. `schedule` is its cron expression, else Firecrawl's text for it. */
547
633
  const monitorInfo = (entry) => {
548
634
  const monitor = entry.value;
549
635
  return compact({
@@ -556,6 +642,11 @@ const monitorInfo = (entry) => {
556
642
  webhookUrl: monitor.webhook.url
557
643
  });
558
644
  };
645
+ /**
646
+ * One check of a monitor as an event. The summary reads like
647
+ * `completed: 2 changed, 1 new of 40 pages`, and the time is when the check
648
+ * finished, else started, was scheduled or was created.
649
+ */
559
650
  const checkEvent = (entry) => {
560
651
  const check = entry.value;
561
652
  const { summary } = check;
@@ -581,7 +672,12 @@ const checkEvent = (entry) => {
581
672
  ].filter((part) => part !== void 0).join(": ")
582
673
  });
583
674
  };
584
- /** One page of a monitor's checks; the caller adds `raw`. */
675
+ /**
676
+ * One page of a monitor's checks; the caller adds `raw`. The cursor is the
677
+ * offset of the next page, set only when this page is full. Firecrawl caps a
678
+ * page at 100 and reports no total, so when the checks end exactly on a page
679
+ * boundary the cursor leads to an empty page.
680
+ */
585
681
  const monitorEvents = (checks, offset) => compact({
586
682
  events: checks.map((check) => checkEvent(check)),
587
683
  next: checks.length === 100 ? String(offset + checks.length) : void 0
@@ -621,6 +717,7 @@ const Price = looseObject({
621
717
  currency: optionalString,
622
718
  formatted: optionalString
623
719
  });
720
+ /** A product variant. GTINs arrive in several widths, so each is read apart; `values` maps option names to values. */
624
721
  const Variant = looseObject({
625
722
  availability: looseObject({
626
723
  inStock: optionalBoolean,
@@ -750,6 +847,7 @@ const Execution = withOriginal(looseObject({
750
847
  }));
751
848
  /** What closing a session billed. */
752
849
  const Closed = looseObject({ creditsBilled: optionalNumber });
850
+ /** A web or news search result. */
753
851
  const WebItem = looseObject({
754
852
  category: optionalString,
755
853
  date: optionalString,
@@ -760,6 +858,7 @@ const WebItem = looseObject({
760
858
  title: optionalString,
761
859
  url: optionalString
762
860
  });
861
+ /** A research search result. It carries ids, not a URL. */
763
862
  const Paper = looseObject({
764
863
  abstract: optionalString,
765
864
  paperId: optionalString,
@@ -767,6 +866,7 @@ const Paper = looseObject({
767
866
  score: optionalNumber,
768
867
  title: optionalString
769
868
  });
869
+ /** An image search result: `imageUrl` is the image and `url` the page it is on. */
770
870
  const ImageItem = looseObject({
771
871
  imageHeight: optionalNumber,
772
872
  imageUrl: optionalString,
@@ -797,6 +897,7 @@ const MapResponse = looseObject({ links: arrayOf(z.union([z.pipe(z.string(), z.t
797
897
  title: link.title,
798
898
  url: link.url ?? ""
799
899
  })))])) });
900
+ /** A monitor. Its targets are a scrape (`urls`), a crawl (`url`) or a search (`queries`). */
800
901
  const Monitor = looseObject({
801
902
  createdAt: optionalString,
802
903
  goal: optionalString,
@@ -883,6 +984,7 @@ const firecrawl = (config = {}) => {
883
984
  provider,
884
985
  retries: config.retries
885
986
  });
987
+ /** Scrapes one URL with the formats and page settings given. */
886
988
  const scrape = async (url, formats, settings, call) => {
887
989
  const response = await raw.request("POST", "/scrape", {
888
990
  ...call,
@@ -899,47 +1001,50 @@ const firecrawl = (config = {}) => {
899
1001
  response
900
1002
  };
901
1003
  };
1004
+ /** The path of a `next` link, relative to the base URL, so the next page of results goes through the same client. */
902
1005
  const pathOf = (link) => {
903
1006
  const next = new URL(link);
904
1007
  const base = new URL(baseUrl).pathname.replace(/\/$/u, "");
905
1008
  return next.pathname.slice(base.length) + next.search;
906
1009
  };
907
- const finished = async (kind, id, call, interval) => {
908
- const path = `/${kind}/${segment(id)}`;
909
- const get = async (schema, to) => {
910
- try {
911
- return z.parse(schema, await raw.request("GET", to, call));
912
- } catch (error) {
913
- throw withJob(error, id);
914
- }
915
- };
916
- const first = await poll(provider, id, async (request) => {
917
- const status = z.parse(Batch, await raw.request("GET", path, request));
1010
+ /**
1011
+ * Runs a crawl or batch scrape: waits for it, then reads every page of its
1012
+ * results and the pages that failed.
1013
+ */
1014
+ const batchJob = async (kind, start, settings, finish) => await runJob(provider, {
1015
+ check: async (id, request) => {
1016
+ const status = z.parse(Batch, await raw.request("GET", `/${kind}/${segment(id)}`, request));
918
1017
  const state = status.value.status;
919
1018
  if (state === "failed" || state === "cancelled") throw new FieldworkError("JobFailed", `firecrawl ${kind} ${id} ended ${state}`, {
920
1019
  cause: status.original,
921
1020
  provider
922
1021
  });
923
1022
  return state === "completed" ? status : void 0;
924
- }, {
925
- ...call,
926
- interval
927
- });
928
- const batches = [first];
929
- let { next } = first.value;
930
- while (next !== void 0) {
931
- const batch = await get(Batch, pathOf(next));
932
- batches.push(batch);
933
- ({next} = batch.value);
934
- }
935
- const errors = await get(BatchErrors, `${path}/errors`);
936
- return {
937
- batches,
938
- errors,
939
- failed: failedPages(errors),
940
- first
941
- };
942
- };
1023
+ },
1024
+ finish: async (first, id) => {
1025
+ const path = `/${kind}/${segment(id)}`;
1026
+ const request = {
1027
+ retries: settings.retries,
1028
+ signal: settings.signal
1029
+ };
1030
+ const batches = [first];
1031
+ let { next } = first.value;
1032
+ while (next !== void 0) {
1033
+ const batch = z.parse(Batch, await raw.request("GET", pathOf(next), request));
1034
+ batches.push(batch);
1035
+ ({next} = batch.value);
1036
+ }
1037
+ const errors = z.parse(BatchErrors, await raw.request("GET", `${path}/errors`, request));
1038
+ return finish({
1039
+ batches,
1040
+ errors,
1041
+ failed: failedPages(errors),
1042
+ first
1043
+ }, id);
1044
+ },
1045
+ start
1046
+ }, settings);
1047
+ /** Opens a browser session. Only a rate limit is retried, since after any other failure the session may already be open and billing. */
943
1048
  const openSession = async (o, call) => {
944
1049
  const session = z.parse(Session, await raw.request("POST", "/interact", {
945
1050
  body: sessionBody(o),
@@ -1015,30 +1120,34 @@ const firecrawl = (config = {}) => {
1015
1120
  },
1016
1121
  async crawl(url, options) {
1017
1122
  const { call, rest: o } = callSettings(options);
1018
- const id = o.resume ?? requireJobId("firecrawl", z.parse(CrawlStart, await raw.request("POST", "/crawl", {
1123
+ return await batchJob("crawl", async () => requireJobId(provider, z.parse(CrawlStart, await raw.request("POST", "/crawl", {
1019
1124
  creates: true,
1020
1125
  ...call,
1021
1126
  body: crawlBody(url, o)
1022
- })).id);
1023
- const job = await finished("crawl", id, call, o.interval);
1024
- const { robotsBlocked } = job.errors.value;
1025
- return compact({
1026
- failed: job.failed,
1027
- id,
1028
- meta: meta({
1029
- credits: job.first.value.creditsUsed,
1030
- requestId: id
1031
- }),
1032
- pages: job.batches.flatMap((batch) => batch.value.data.map((item) => ({
1033
- ...toPage(item.value, url),
1034
- raw: item.original
1035
- }))),
1036
- raw: {
1037
- batches: job.batches.map((batch) => batch.original),
1038
- errors: job.errors.original
1039
- },
1040
- robotsBlocked: robotsBlocked.length > 0 ? robotsBlocked : void 0,
1041
- total: job.first.value.total
1127
+ })).id), {
1128
+ ...call,
1129
+ interval: o.interval,
1130
+ resume: o.resume
1131
+ }, (job, id) => {
1132
+ const { robotsBlocked } = job.errors.value;
1133
+ return compact({
1134
+ failed: job.failed,
1135
+ id,
1136
+ meta: meta({
1137
+ credits: job.first.value.creditsUsed,
1138
+ requestId: id
1139
+ }),
1140
+ pages: job.batches.flatMap((batch) => batch.value.data.map((item) => ({
1141
+ ...toPage(item.value, url),
1142
+ raw: item.original
1143
+ }))),
1144
+ raw: {
1145
+ batches: job.batches.map((batch) => batch.original),
1146
+ errors: job.errors.original
1147
+ },
1148
+ robotsBlocked: robotsBlocked.length > 0 ? robotsBlocked : void 0,
1149
+ total: job.first.value.total
1150
+ });
1042
1151
  });
1043
1152
  },
1044
1153
  async extract(url, options) {
@@ -1175,65 +1284,77 @@ const firecrawl = (config = {}) => {
1175
1284
  async readMany(urls, options) {
1176
1285
  const { call, rest: o } = callSettings(options);
1177
1286
  const { interval, resume, maxConcurrency, ignoreInvalidURLs, ...read } = o;
1178
- const started = z.parse(RunStart, resume === void 0 ? await raw.request("POST", "/batch/scrape", {
1179
- creates: true,
1287
+ let started = z.parse(RunStart, {});
1288
+ return await batchJob("batch/scrape", async () => {
1289
+ started = z.parse(RunStart, await raw.request("POST", "/batch/scrape", {
1290
+ creates: true,
1291
+ ...call,
1292
+ body: compact({
1293
+ urls,
1294
+ ...readBody(read),
1295
+ maxConcurrency,
1296
+ ignoreInvalidURLs
1297
+ })
1298
+ }));
1299
+ return requireJobId(provider, started.value.id);
1300
+ }, {
1180
1301
  ...call,
1181
- body: compact({
1182
- urls,
1183
- ...readBody(read),
1184
- maxConcurrency,
1185
- ignoreInvalidURLs
1186
- })
1187
- }) : {});
1188
- const id = resume ?? requireJobId("firecrawl", started.value.id);
1189
- const job = await finished("batch/scrape", id, call, interval);
1190
- const rejected = started.value.invalidURLs.map((url) => ({
1191
- error: "invalid URL",
1192
- url
1193
- }));
1194
- const { pages, gone } = presentPages(job.batches.flatMap((batch) => batch.value.data.map((item) => ({
1195
- ...toPage(item.value, ""),
1196
- raw: item.original
1197
- }))));
1198
- return compact({
1199
- failed: [
1200
- ...job.failed,
1201
- ...rejected,
1202
- ...gone
1203
- ],
1204
- id,
1205
- meta: meta({
1206
- credits: job.first.value.creditsUsed,
1207
- requestId: id
1208
- }),
1209
- pages,
1210
- raw: {
1211
- batches: job.batches.map((batch) => batch.original),
1212
- errors: job.errors.original,
1213
- started: started.original
1214
- }
1302
+ interval,
1303
+ resume
1304
+ }, (job, id) => {
1305
+ const rejected = started.value.invalidURLs.map((url) => ({
1306
+ error: "invalid URL",
1307
+ url
1308
+ }));
1309
+ const { pages, gone } = presentPages(job.batches.flatMap((batch) => batch.value.data.map((item) => ({
1310
+ ...toPage(item.value, ""),
1311
+ raw: item.original
1312
+ }))));
1313
+ return compact({
1314
+ failed: [
1315
+ ...job.failed,
1316
+ ...rejected,
1317
+ ...gone
1318
+ ],
1319
+ id,
1320
+ meta: meta({
1321
+ credits: job.first.value.creditsUsed,
1322
+ requestId: id
1323
+ }),
1324
+ pages,
1325
+ raw: {
1326
+ batches: job.batches.map((batch) => batch.original),
1327
+ errors: job.errors.original,
1328
+ started: started.original
1329
+ }
1330
+ });
1215
1331
  });
1216
1332
  },
1217
1333
  async research(question, options) {
1218
1334
  const { call, rest: o } = callSettings(options);
1219
- const started = z.parse(RunStart, o.resume === void 0 ? await raw.request("POST", "/agent", {
1220
- creates: true,
1221
- ...call,
1222
- body: researchBody(question, o)
1223
- }) : {});
1224
- const id = o.resume ?? requireJobId("firecrawl", started.value.id);
1225
- const run = await poll(provider, id, async (request) => researchState(id, z.parse(AgentRun, await raw.request("GET", `/agent/${segment(id)}`, request))), {
1335
+ let started = z.parse(RunStart, {});
1336
+ return await runJob(provider, {
1337
+ check: async (id, request) => researchState(id, z.parse(AgentRun, await raw.request("GET", `/agent/${segment(id)}`, request))),
1338
+ finish: async (run, id) => {
1339
+ const result = researchResult(id, started, run);
1340
+ return {
1341
+ ...result,
1342
+ output: await checkOutput(o.schema, result.output, { provider })
1343
+ };
1344
+ },
1345
+ start: async () => {
1346
+ started = z.parse(RunStart, await raw.request("POST", "/agent", {
1347
+ creates: true,
1348
+ ...call,
1349
+ body: researchBody(question, o)
1350
+ }));
1351
+ return requireJobId(provider, started.value.id);
1352
+ }
1353
+ }, {
1226
1354
  ...call,
1227
- interval: o.interval
1355
+ interval: o.interval,
1356
+ resume: o.resume
1228
1357
  });
1229
- const result = researchResult(id, started, run);
1230
- return {
1231
- ...result,
1232
- output: await checkOutput(o.schema, result.output, {
1233
- jobId: id,
1234
- provider
1235
- })
1236
- };
1237
1358
  },
1238
1359
  async search(query, options) {
1239
1360
  const { call, rest: o } = callSettings(options);