@howells/fieldwork-sdk 0.3.1 → 0.5.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.
- package/README.md +66 -33
- package/dist/{adapter-DGehHCMo.d.ts → adapter-BgdfLBs-.d.ts} +101 -5
- package/dist/adapter-DWYJys20.js +8 -0
- package/dist/brave.d.ts +11 -4
- package/dist/brave.js +230 -127
- package/dist/browserbase.d.ts +15 -9
- package/dist/browserbase.js +97 -49
- package/dist/document-Dpj01mGx.js +51 -0
- package/dist/{errors-BiIBG9zN.js → errors-Yvk42oZH.js} +3 -1
- package/dist/exa.d.ts +28 -19
- package/dist/exa.js +324 -177
- package/dist/{fieldwork-B3x3cxDJ.d.ts → fieldwork-CXNIcqSN.d.ts} +9 -3
- package/dist/firecrawl.d.ts +33 -25
- package/dist/firecrawl.js +688 -364
- package/dist/index.d.ts +5 -3
- package/dist/index.js +33 -13
- package/dist/llamaparse.d.ts +58 -0
- package/dist/llamaparse.js +286 -0
- package/dist/parallel.d.ts +36 -26
- package/dist/parallel.js +440 -230
- package/dist/parse-D4SMt-Ip.js +510 -0
- package/dist/perplexity.d.ts +25 -16
- package/dist/perplexity.js +210 -139
- package/dist/reducto.d.ts +31 -0
- package/dist/reducto.js +220 -0
- package/dist/schema-Cupy7-7q.d.ts +90 -0
- package/dist/schema-DbSIABP0.js +45 -0
- package/dist/serpapi.d.ts +12 -4
- package/dist/serpapi.js +280 -174
- package/dist/tavily.d.ts +20 -12
- package/dist/tavily.js +209 -131
- package/dist/tools.d.ts +5 -2
- package/dist/tools.js +62 -12
- package/dist/util-DhYr1OS3.d.ts +1 -0
- package/package.json +17 -2
- package/dist/adapter-CEAQuT7F.js +0 -3
- package/dist/util-YaZYZDSk.js +0 -287
package/dist/firecrawl.js
CHANGED
|
@@ -1,11 +1,11 @@
|
|
|
1
|
-
import { t as defineAdapter } from "./adapter-
|
|
2
|
-
import {
|
|
3
|
-
import {
|
|
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";
|
|
6
|
+
import * as z from "zod/mini";
|
|
4
7
|
// src/adapters/firecrawl/shared.ts
|
|
5
8
|
const provider = "firecrawl";
|
|
6
|
-
const invalid = (message) => new FieldworkError("InvalidRequest", message, { provider });
|
|
7
|
-
const segment = (id) => encodeURIComponent(id);
|
|
8
|
-
const warnings = (...values) => values.flatMap((value) => typeof value === "string" ? [value] : list(value).map(String));
|
|
9
9
|
const country = (code) => code?.toUpperCase();
|
|
10
10
|
// src/adapters/firecrawl/schedule.ts
|
|
11
11
|
/** The fewest minutes Firecrawl allows between two checks of a monitor. */
|
|
@@ -40,16 +40,16 @@ const runGaps = (minutes, hours) => {
|
|
|
40
40
|
const gaps = minutes.slice(1).map((minute, index) => minute - (minutes[index] ?? 0));
|
|
41
41
|
const [first] = minutes;
|
|
42
42
|
const last = minutes.at(-1);
|
|
43
|
-
if (hours?.some((hour) => hours.includes((hour + 1) % 24)) && first !== void 0 && last !== void 0) gaps.push(60 - last + first);
|
|
43
|
+
if (hours?.some((hour) => hours.includes((hour + 1) % 24)) === true && first !== void 0 && last !== void 0) gaps.push(60 - last + first);
|
|
44
44
|
return gaps;
|
|
45
45
|
};
|
|
46
46
|
const checkCron = (cron) => {
|
|
47
47
|
const fields = cron.trim().split(/\s+/u);
|
|
48
|
-
if (fields.length !== 5) throw
|
|
48
|
+
if (fields.length !== 5) throw invalidRequest(provider, `needs a five-field cron expression, got "${cron}"`);
|
|
49
49
|
const [minuteField = "", hourField = ""] = fields;
|
|
50
50
|
const minutes = cronValues(minuteField, 59);
|
|
51
51
|
const hours = cronValues(hourField, 23);
|
|
52
|
-
if (minutes && runGaps(minutes, hours).some((gap) => gap < MIN_MINUTES)) throw
|
|
52
|
+
if (minutes && runGaps(minutes, hours).some((gap) => gap < MIN_MINUTES)) throw invalidRequest(provider, `monitors run at most every ${MIN_MINUTES} minutes, got "${cron}"`);
|
|
53
53
|
return cron.trim();
|
|
54
54
|
};
|
|
55
55
|
const hourlyCron = (count) => {
|
|
@@ -61,44 +61,24 @@ const cronFor = (schedule) => {
|
|
|
61
61
|
if ("cron" in schedule) return checkCron(schedule.cron);
|
|
62
62
|
const every = schedule.every;
|
|
63
63
|
const named = NAMED_CRON.get(every);
|
|
64
|
-
if (named) return named;
|
|
64
|
+
if (named !== void 0) return named;
|
|
65
65
|
const groups = INTERVAL.exec(every)?.groups;
|
|
66
66
|
const count = Number(groups?.count);
|
|
67
67
|
const cron = groups?.unit === "h" ? hourlyCron(count) : DAILY_CRON.get(count);
|
|
68
|
-
if (cron) return cron;
|
|
69
|
-
throw
|
|
68
|
+
if (cron !== void 0) return cron;
|
|
69
|
+
throw invalidRequest(provider, `cannot run a monitor every "${every}"; use hour, day, week, a number of hours that divides 24, 1d, 7d or a cron expression`);
|
|
70
70
|
};
|
|
71
71
|
// src/adapters/firecrawl/request.ts
|
|
72
|
-
/** The largest file `/parse` takes. */
|
|
73
|
-
const
|
|
72
|
+
/** The largest file `/parse` takes, in megabytes. */
|
|
73
|
+
const MAX_PARSE_MB = 50;
|
|
74
74
|
/** Longest script `/interact/{id}/execute` runs, in seconds. */
|
|
75
75
|
const MAX_SCRIPT_SECONDS = 300;
|
|
76
|
-
/**
|
|
77
|
-
const
|
|
76
|
+
/** Longest `/parse` runs, in milliseconds. */
|
|
77
|
+
const MAX_PARSE_MS = 3e5;
|
|
78
|
+
/** Milliseconds a request outlives Firecrawl's own limit, so Firecrawl reports the timeout itself. */
|
|
79
|
+
const REPORT_GRACE_MS = 1e4;
|
|
78
80
|
/** The longest query a search monitor takes. */
|
|
79
81
|
const MAX_MONITOR_QUERY = 256;
|
|
80
|
-
const MEDIA_TYPES = new Map(Object.entries({
|
|
81
|
-
csv: "text/csv",
|
|
82
|
-
doc: "application/msword",
|
|
83
|
-
docm: "application/vnd.ms-word.document.macroEnabled.12",
|
|
84
|
-
docx: "application/vnd.openxmlformats-officedocument.wordprocessingml.document",
|
|
85
|
-
epub: "application/epub+zip",
|
|
86
|
-
htm: "text/html",
|
|
87
|
-
html: "text/html",
|
|
88
|
-
odp: "application/vnd.oasis.opendocument.presentation",
|
|
89
|
-
ods: "application/vnd.oasis.opendocument.spreadsheet",
|
|
90
|
-
odt: "application/vnd.oasis.opendocument.text",
|
|
91
|
-
pdf: "application/pdf",
|
|
92
|
-
ppt: "application/vnd.ms-powerpoint",
|
|
93
|
-
pptm: "application/vnd.ms-powerpoint.presentation.macroEnabled.12",
|
|
94
|
-
pptx: "application/vnd.openxmlformats-officedocument.presentationml.presentation",
|
|
95
|
-
rtf: "application/rtf",
|
|
96
|
-
xhtml: "application/xhtml+xml",
|
|
97
|
-
xls: "application/vnd.ms-excel",
|
|
98
|
-
xlsb: "application/vnd.ms-excel.sheet.binary.macroEnabled.12",
|
|
99
|
-
xlsm: "application/vnd.ms-excel.sheet.macroEnabled.12",
|
|
100
|
-
xlsx: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"
|
|
101
|
-
}));
|
|
102
82
|
const RECENCY = {
|
|
103
83
|
day: "d",
|
|
104
84
|
hour: "h",
|
|
@@ -139,7 +119,7 @@ const readBody = (o) => ({
|
|
|
139
119
|
});
|
|
140
120
|
const usDate = (value) => {
|
|
141
121
|
const groups = DATE.exec(value)?.groups;
|
|
142
|
-
if (!groups) throw
|
|
122
|
+
if (!groups) throw invalidRequest(provider, `needs dates as YYYY-MM-DD, got "${value}"`);
|
|
143
123
|
return `${groups.month}/${groups.day}/${groups.year}`;
|
|
144
124
|
};
|
|
145
125
|
const timeFilter = (o) => {
|
|
@@ -156,7 +136,7 @@ const timeFilter = (o) => {
|
|
|
156
136
|
};
|
|
157
137
|
const searchBody = (query, o) => {
|
|
158
138
|
refuseTogether(provider, o, "includeDomains", "excludeDomains");
|
|
159
|
-
if (o.categories?.includes("gov") && o.categories.length > 1) throw
|
|
139
|
+
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");
|
|
160
140
|
return compact({
|
|
161
141
|
categories: o.categories?.map((type) => ({ type })),
|
|
162
142
|
country: country(o.country),
|
|
@@ -167,7 +147,7 @@ const searchBody = (query, o) => {
|
|
|
167
147
|
location: o.location,
|
|
168
148
|
query,
|
|
169
149
|
safe: o.safe,
|
|
170
|
-
scrapeOptions: o.content ? { formats: ["markdown"] } : void 0,
|
|
150
|
+
scrapeOptions: o.content === true ? { formats: ["markdown"] } : void 0,
|
|
171
151
|
sources: o.sources?.map((type) => ({ type })),
|
|
172
152
|
tbs: timeFilter(o)
|
|
173
153
|
});
|
|
@@ -209,18 +189,18 @@ const crawlBody = (url, o) => compact({
|
|
|
209
189
|
});
|
|
210
190
|
const researchBody = (question, o) => compact({
|
|
211
191
|
effort: o.effort,
|
|
212
|
-
location: o.country ? { country: country(o.country) }
|
|
192
|
+
location: o.country === void 0 || o.country === "" ? void 0 : { country: country(o.country) },
|
|
213
193
|
maxCredits: o.maxCredits,
|
|
214
194
|
model: o.model,
|
|
215
195
|
prompt: question,
|
|
216
|
-
schema: o.schema,
|
|
196
|
+
schema: o.schema === void 0 ? void 0 : jsonSchemaOf(o.schema),
|
|
217
197
|
strictConstrainToURLs: o.strictConstrainToURLs,
|
|
218
198
|
threadId: o.continueFrom,
|
|
219
199
|
urls: o.urls
|
|
220
200
|
});
|
|
221
201
|
const sessionBody = (o) => compact({
|
|
222
202
|
activityTtl: o.activityTtl ?? o.ttl,
|
|
223
|
-
location: o.country ? { country: country(o.country) }
|
|
203
|
+
location: o.country === void 0 || o.country === "" ? void 0 : { country: country(o.country) },
|
|
224
204
|
profile: o.profile,
|
|
225
205
|
ttl: o.ttl
|
|
226
206
|
});
|
|
@@ -233,7 +213,7 @@ const checkAct = (o, timeout) => {
|
|
|
233
213
|
]) refuseTogether(provider, o, "session", name);
|
|
234
214
|
if (timeout === void 0) return;
|
|
235
215
|
const seconds = Math.max(1, Math.ceil(timeout / 1e3));
|
|
236
|
-
if (seconds > MAX_SCRIPT_SECONDS) throw
|
|
216
|
+
if (seconds > MAX_SCRIPT_SECONDS) throw invalidRequest(provider, `runs a script for at most ${MAX_SCRIPT_SECONDS} seconds`);
|
|
237
217
|
return seconds;
|
|
238
218
|
};
|
|
239
219
|
const scriptRequest = (code, language, call, seconds) => ({
|
|
@@ -242,15 +222,14 @@ const scriptRequest = (code, language, call, seconds) => ({
|
|
|
242
222
|
language: language ?? "node",
|
|
243
223
|
timeout: seconds
|
|
244
224
|
}),
|
|
225
|
+
retries: call.retries,
|
|
245
226
|
signal: call.signal,
|
|
246
|
-
timeout: call.timeout === void 0 ? void 0 : call.timeout +
|
|
227
|
+
timeout: call.timeout === void 0 ? void 0 : call.timeout + REPORT_GRACE_MS
|
|
247
228
|
});
|
|
248
|
-
const parseForm = (document, o) => {
|
|
249
|
-
|
|
250
|
-
|
|
251
|
-
|
|
252
|
-
const size = document.data instanceof Blob ? document.data.size : document.data.byteLength;
|
|
253
|
-
if (size > MAX_PARSE_BYTES) throw invalid(`firecrawl parses files up to 50 MB; ${document.name} is ${(size / 1024 / 1024).toFixed(1)} MB`);
|
|
229
|
+
const parseForm = (document, o, timeout) => {
|
|
230
|
+
if (timeout !== void 0 && timeout > MAX_PARSE_MS) throw invalidRequest(provider, `parses for at most ${MAX_PARSE_MS / 1e3} seconds`);
|
|
231
|
+
if (mediaTypeOf(document.name) === void 0) throw invalidRequest(provider, `parses ${[...MEDIA_TYPES.keys()].join(", ")} files, not "${document.name}"`);
|
|
232
|
+
refuseLarger(provider, document, MAX_PARSE_MB);
|
|
254
233
|
const parser = compact({
|
|
255
234
|
blocks: o.blocks,
|
|
256
235
|
maxPages: o.maxPages,
|
|
@@ -260,11 +239,12 @@ const parseForm = (document, o) => {
|
|
|
260
239
|
type: "pdf"
|
|
261
240
|
});
|
|
262
241
|
const form = new FormData();
|
|
263
|
-
form.set("options", JSON.stringify({
|
|
242
|
+
form.set("options", JSON.stringify(compact({
|
|
264
243
|
formats: ["markdown"],
|
|
265
|
-
parsers: [parser]
|
|
266
|
-
|
|
267
|
-
|
|
244
|
+
parsers: [parser],
|
|
245
|
+
timeout
|
|
246
|
+
})));
|
|
247
|
+
form.set("file", documentPart(document), document.name);
|
|
268
248
|
return form;
|
|
269
249
|
};
|
|
270
250
|
const monitorTarget = (o) => {
|
|
@@ -275,14 +255,14 @@ const monitorTarget = (o) => {
|
|
|
275
255
|
o.excludeDomains
|
|
276
256
|
].some((value) => value !== void 0);
|
|
277
257
|
if (o.urls && o.urls.length > 0) {
|
|
278
|
-
if (searchOnly) throw
|
|
258
|
+
if (searchOnly) throw invalidRequest(provider, "applies searchWindow, maxResults and the domain lists to search monitors, which take a query and no urls");
|
|
279
259
|
return {
|
|
280
260
|
type: "scrape",
|
|
281
261
|
urls: o.urls
|
|
282
262
|
};
|
|
283
263
|
}
|
|
284
|
-
if (
|
|
285
|
-
if (o.query.length > MAX_MONITOR_QUERY) throw
|
|
264
|
+
if (o.query === void 0 || o.query === "") throw invalidRequest(provider, "monitors need urls to watch or a query");
|
|
265
|
+
if (o.query.length > MAX_MONITOR_QUERY) throw invalidRequest(provider, `searches queries of up to ${MAX_MONITOR_QUERY} characters; pass urls to watch pages with a longer query`);
|
|
286
266
|
return compact({
|
|
287
267
|
excludeDomains: o.excludeDomains,
|
|
288
268
|
includeDomains: o.includeDomains,
|
|
@@ -303,7 +283,7 @@ const monitorBody = (o) => {
|
|
|
303
283
|
timezone: o.timezone
|
|
304
284
|
}),
|
|
305
285
|
targets: [target],
|
|
306
|
-
webhook: o.webhookUrl ? { url: o.webhookUrl }
|
|
286
|
+
webhook: o.webhookUrl === void 0 || o.webhookUrl === "" ? void 0 : { url: o.webhookUrl }
|
|
307
287
|
});
|
|
308
288
|
};
|
|
309
289
|
// src/adapters/firecrawl/response.ts
|
|
@@ -315,84 +295,70 @@ const PAPER_URLS = /* @__PURE__ */ new Map([
|
|
|
315
295
|
["doi", (id) => `https://doi.org/${id}`]
|
|
316
296
|
]);
|
|
317
297
|
const LANGUAGE = /^(?<code>[a-z]{2})(?:[-_]|$)/u;
|
|
318
|
-
|
|
319
|
-
const
|
|
298
|
+
/** The list, or undefined when it is empty. */
|
|
299
|
+
const some = (items) => items.length > 0 ? [...items] : void 0;
|
|
300
|
+
const languageCode = (value) => LANGUAGE.exec(value?.toLowerCase() ?? "")?.groups?.code;
|
|
320
301
|
const excerptsOf = (data) => {
|
|
321
|
-
const
|
|
322
|
-
|
|
323
|
-
const answer = text(data.answer);
|
|
324
|
-
return highlights ?? (answer ? [answer] : void 0);
|
|
325
|
-
};
|
|
326
|
-
const pageMeta = (top, data) => {
|
|
327
|
-
const metadata = record(data.metadata);
|
|
328
|
-
return meta({
|
|
329
|
-
credits: metadata.creditsUsed,
|
|
330
|
-
requestId: metadata.scrapeId,
|
|
331
|
-
warnings: warnings(data.warning, top.warning)
|
|
332
|
-
});
|
|
302
|
+
const { list, text } = data.highlights;
|
|
303
|
+
return (text === void 0 ? some(list) : [text]) ?? (data.answer === void 0 ? void 0 : [data.answer]);
|
|
333
304
|
};
|
|
334
|
-
const
|
|
335
|
-
|
|
305
|
+
const pageMeta = (data, topNotes) => meta({
|
|
306
|
+
credits: data.metadata.creditsUsed,
|
|
307
|
+
requestId: data.metadata.scrapeId,
|
|
308
|
+
warnings: [...data.warning.notes, ...topNotes]
|
|
309
|
+
});
|
|
310
|
+
/** A page from scraped data; the caller adds `raw`. `topNotes` are the warnings of the whole response. */
|
|
311
|
+
const toPage = (data, fallbackUrl, topNotes = []) => {
|
|
312
|
+
const { metadata } = data;
|
|
336
313
|
return compact({
|
|
337
|
-
author:
|
|
338
|
-
description:
|
|
314
|
+
author: metadata.author,
|
|
315
|
+
description: metadata.description,
|
|
339
316
|
excerpts: excerptsOf(data),
|
|
340
|
-
favicon:
|
|
341
|
-
html:
|
|
342
|
-
image:
|
|
343
|
-
images:
|
|
317
|
+
favicon: metadata.favicon,
|
|
318
|
+
html: data.html,
|
|
319
|
+
image: metadata.ogImage ?? metadata["og:image"],
|
|
320
|
+
images: some(data.images),
|
|
344
321
|
language: languageCode(metadata.language),
|
|
345
|
-
links:
|
|
346
|
-
markdown:
|
|
347
|
-
meta: pageMeta(
|
|
348
|
-
publishedAt:
|
|
349
|
-
|
|
350
|
-
|
|
351
|
-
|
|
352
|
-
|
|
353
|
-
|
|
354
|
-
|
|
355
|
-
url: text(metadata.url) ?? text(metadata.sourceURL) ?? fallbackUrl
|
|
322
|
+
links: some(data.links),
|
|
323
|
+
markdown: data.markdown,
|
|
324
|
+
meta: pageMeta(data, topNotes),
|
|
325
|
+
publishedAt: metadata.publishedTime ?? metadata["article:published_time"],
|
|
326
|
+
rawHtml: data.rawHtml,
|
|
327
|
+
screenshot: data.screenshot,
|
|
328
|
+
statusCode: metadata.statusCode,
|
|
329
|
+
summary: data.summary,
|
|
330
|
+
title: metadata.title,
|
|
331
|
+
url: metadata.url ?? metadata.sourceURL ?? fallbackUrl
|
|
356
332
|
});
|
|
357
333
|
};
|
|
358
|
-
const price = (
|
|
359
|
-
const item = record(value);
|
|
334
|
+
const price = (item) => {
|
|
360
335
|
const result = compact({
|
|
361
|
-
amount:
|
|
362
|
-
currency:
|
|
363
|
-
formatted:
|
|
336
|
+
amount: item.amount,
|
|
337
|
+
currency: item.currency,
|
|
338
|
+
formatted: item.formatted
|
|
364
339
|
});
|
|
365
340
|
return Object.keys(result).length > 0 ? result : void 0;
|
|
366
341
|
};
|
|
367
|
-
const gtin = (variant) =>
|
|
368
|
-
|
|
369
|
-
|
|
370
|
-
|
|
371
|
-
|
|
372
|
-
|
|
373
|
-
|
|
374
|
-
|
|
375
|
-
|
|
376
|
-
|
|
377
|
-
}
|
|
378
|
-
};
|
|
379
|
-
const toVariant = (value) => {
|
|
380
|
-
const variant = record(value);
|
|
381
|
-
const availability = record(variant.availability);
|
|
382
|
-
const values = Object.fromEntries(Object.entries(record(variant.values)).flatMap(([key, item]) => {
|
|
383
|
-
const option = scalar(item);
|
|
384
|
-
return option === void 0 ? [] : [[key, option]];
|
|
385
|
-
}));
|
|
342
|
+
const gtin = (variant) => [
|
|
343
|
+
variant.gtin,
|
|
344
|
+
variant.gtin14,
|
|
345
|
+
variant.gtin13,
|
|
346
|
+
variant.gtin12,
|
|
347
|
+
variant.gtin8
|
|
348
|
+
].find((value) => value !== void 0 && value !== "");
|
|
349
|
+
const images = (found) => some(found.filter((image) => image !== void 0));
|
|
350
|
+
const toVariant = (variant) => {
|
|
351
|
+
const values = Object.fromEntries(Object.entries(variant.values).flatMap(([key, item]) => item === void 0 ? [] : [[key, item]]));
|
|
386
352
|
return compact({
|
|
387
|
-
availability:
|
|
353
|
+
availability: variant.availability.text,
|
|
388
354
|
gtin: gtin(variant),
|
|
389
|
-
id:
|
|
390
|
-
images:
|
|
391
|
-
inStock:
|
|
392
|
-
originalPrice: price(
|
|
355
|
+
id: variant.id,
|
|
356
|
+
images: images(variant.images),
|
|
357
|
+
inStock: variant.availability.inStock,
|
|
358
|
+
originalPrice: price(variant.sale.originalPrice),
|
|
393
359
|
price: price(variant.price),
|
|
394
|
-
sku:
|
|
395
|
-
title:
|
|
360
|
+
sku: variant.sku,
|
|
361
|
+
title: variant.title,
|
|
396
362
|
values: Object.keys(values).length > 0 ? values : void 0
|
|
397
363
|
});
|
|
398
364
|
};
|
|
@@ -401,244 +367,535 @@ const allImages = (variants) => {
|
|
|
401
367
|
for (const image of variants.flatMap((variant) => variant.images ?? [])) if (!seen.has(image.url)) seen.set(image.url, image);
|
|
402
368
|
return seen.size > 0 ? [...seen.values()] : void 0;
|
|
403
369
|
};
|
|
404
|
-
|
|
405
|
-
|
|
406
|
-
|
|
407
|
-
|
|
408
|
-
|
|
409
|
-
provider
|
|
410
|
-
});
|
|
411
|
-
}
|
|
412
|
-
const product = record(data.product);
|
|
413
|
-
const variants = list(product.variants).map((variant) => toVariant(variant));
|
|
370
|
+
/** The product on a scraped page; the caller adds `raw`. Undefined when the page has none. */
|
|
371
|
+
const toProduct = (body) => {
|
|
372
|
+
const { product } = body.data;
|
|
373
|
+
if (product === void 0) return;
|
|
374
|
+
const variants = product.variants.map((variant) => toVariant(variant));
|
|
414
375
|
return compact({
|
|
415
|
-
brand:
|
|
416
|
-
category:
|
|
417
|
-
description:
|
|
418
|
-
images:
|
|
419
|
-
meta: pageMeta(
|
|
420
|
-
|
|
421
|
-
|
|
422
|
-
url: text(product.url),
|
|
376
|
+
brand: product.brand,
|
|
377
|
+
category: product.category,
|
|
378
|
+
description: product.description,
|
|
379
|
+
images: images(product.images) ?? allImages(variants),
|
|
380
|
+
meta: pageMeta(body.data, body.warning.notes),
|
|
381
|
+
title: product.title,
|
|
382
|
+
url: product.url,
|
|
423
383
|
variants
|
|
424
384
|
});
|
|
425
385
|
};
|
|
426
|
-
|
|
427
|
-
|
|
428
|
-
|
|
429
|
-
|
|
430
|
-
|
|
431
|
-
|
|
432
|
-
|
|
433
|
-
|
|
434
|
-
|
|
435
|
-
|
|
436
|
-
|
|
437
|
-
|
|
438
|
-
const
|
|
439
|
-
const
|
|
440
|
-
const paperId = text(paper.paperId) ?? "";
|
|
441
|
-
const primary = text(paper.primaryId) ?? paperId;
|
|
386
|
+
/** Why a page has no product: the warning it carries, if any. */
|
|
387
|
+
const noProductReason = (body) => body.data.warning.text ?? body.warning.text;
|
|
388
|
+
const searchItem = (result, kind) => compact({
|
|
389
|
+
content: result.markdown,
|
|
390
|
+
image: result.imageUrl,
|
|
391
|
+
kind: result.category ?? kind,
|
|
392
|
+
publishedAt: result.date,
|
|
393
|
+
snippet: result.description ?? result.snippet,
|
|
394
|
+
title: result.title,
|
|
395
|
+
url: result.url ?? ""
|
|
396
|
+
});
|
|
397
|
+
const paperItem = (paper) => {
|
|
398
|
+
const paperId = paper.paperId ?? "";
|
|
399
|
+
const primary = paper.primaryId ?? paperId;
|
|
442
400
|
const colon = primary.indexOf(":");
|
|
443
401
|
const resolve = colon > 0 ? PAPER_URLS.get(primary.slice(0, colon)) : void 0;
|
|
444
402
|
return compact({
|
|
445
403
|
kind: "research",
|
|
446
|
-
score:
|
|
447
|
-
snippet:
|
|
448
|
-
title:
|
|
404
|
+
score: paper.score,
|
|
405
|
+
snippet: paper.abstract,
|
|
406
|
+
title: paper.title,
|
|
449
407
|
url: paperId.startsWith("web:") ? paperId.slice(4) : resolve?.(primary.slice(colon + 1)) ?? primary
|
|
450
408
|
});
|
|
451
409
|
};
|
|
452
|
-
const imageItems = (
|
|
453
|
-
const
|
|
454
|
-
|
|
455
|
-
|
|
456
|
-
|
|
457
|
-
|
|
458
|
-
title: text(image.title),
|
|
410
|
+
const imageItems = (found) => found.flatMap((image) => {
|
|
411
|
+
const { imageUrl: url } = image;
|
|
412
|
+
return url === void 0 ? [] : [compact({
|
|
413
|
+
height: image.imageHeight,
|
|
414
|
+
sourceUrl: image.url,
|
|
415
|
+
title: image.title,
|
|
459
416
|
url,
|
|
460
|
-
width:
|
|
461
|
-
})]
|
|
417
|
+
width: image.imageWidth
|
|
418
|
+
})];
|
|
462
419
|
});
|
|
463
|
-
const searchMeta = (
|
|
464
|
-
credits:
|
|
465
|
-
requestId:
|
|
466
|
-
warnings:
|
|
420
|
+
const searchMeta = (body) => meta({
|
|
421
|
+
credits: body.creditsUsed,
|
|
422
|
+
requestId: body.id,
|
|
423
|
+
warnings: [...body.warning, ...body.warnings]
|
|
467
424
|
});
|
|
468
|
-
|
|
469
|
-
|
|
425
|
+
/** The results of a search; the caller adds `raw`. */
|
|
426
|
+
const searchResult = (body) => {
|
|
427
|
+
const { data } = body;
|
|
470
428
|
return compact({
|
|
471
|
-
images:
|
|
472
|
-
meta: searchMeta(
|
|
473
|
-
raw: response,
|
|
429
|
+
images: data.images === void 0 ? void 0 : imageItems(data.images),
|
|
430
|
+
meta: searchMeta(body),
|
|
474
431
|
results: [
|
|
475
|
-
...
|
|
476
|
-
...
|
|
477
|
-
...
|
|
432
|
+
...data.web.map((item) => searchItem(item, "web")),
|
|
433
|
+
...data.news.map((item) => searchItem(item, "news")),
|
|
434
|
+
...data.research.map((item) => paperItem(item))
|
|
478
435
|
]
|
|
479
436
|
});
|
|
480
437
|
};
|
|
481
|
-
const imagesResult = (
|
|
482
|
-
meta: searchMeta(
|
|
483
|
-
|
|
484
|
-
results: imageItems(record(response.data).images)
|
|
485
|
-
});
|
|
486
|
-
const failedPages = (errors) => list(errors.errors).map((item) => {
|
|
487
|
-
const entry = record(item);
|
|
488
|
-
return {
|
|
489
|
-
error: text(entry.error) ?? "unknown error",
|
|
490
|
-
url: text(entry.url) ?? ""
|
|
491
|
-
};
|
|
438
|
+
const imagesResult = (body) => compact({
|
|
439
|
+
meta: searchMeta(body),
|
|
440
|
+
results: imageItems(body.data.images ?? [])
|
|
492
441
|
});
|
|
493
|
-
const
|
|
494
|
-
|
|
442
|
+
const failedPages = (errors) => errors.value.errors.map((entry) => ({
|
|
443
|
+
error: entry.error ?? "unknown error",
|
|
444
|
+
url: entry.url ?? ""
|
|
445
|
+
}));
|
|
446
|
+
const researchState = (id, entry) => {
|
|
447
|
+
const status = entry.value;
|
|
448
|
+
const state = status.status;
|
|
495
449
|
const hasPartial = status.partial !== void 0 && status.partial !== null;
|
|
496
450
|
const done = state === "completed" || state === "failed" && hasPartial;
|
|
497
|
-
if (!done && (state === "failed" || state === "cancelled")) throw new FieldworkError("JobFailed", `firecrawl research run ${id} ${state}: ${
|
|
498
|
-
cause:
|
|
451
|
+
if (!done && (state === "failed" || state === "cancelled")) throw new FieldworkError("JobFailed", `firecrawl research run ${id} ${state}: ${status.error ?? status.stopReason ?? "no reason given"}`, {
|
|
452
|
+
cause: entry.original,
|
|
499
453
|
provider
|
|
500
454
|
});
|
|
501
|
-
return done ?
|
|
455
|
+
return done ? entry : void 0;
|
|
502
456
|
};
|
|
503
|
-
const researchResult = (id, started,
|
|
457
|
+
const researchResult = (id, started, entry) => {
|
|
458
|
+
const run = entry.value;
|
|
504
459
|
const stopped = run.status === "failed";
|
|
505
460
|
const status = stopped ? "partial" : "completed";
|
|
506
461
|
return compact({
|
|
507
|
-
continuationId:
|
|
462
|
+
continuationId: run.threadId ?? started.value.threadId,
|
|
508
463
|
id,
|
|
509
464
|
meta: meta({
|
|
510
465
|
credits: run.creditsUsed,
|
|
511
466
|
requestId: id,
|
|
512
|
-
warnings: stopped ? [run.message, run.partialSchemaValid === false ? "the partial output does not match the schema" : void 0] : void 0
|
|
467
|
+
warnings: stopped ? [run.message.note, run.partialSchemaValid === false ? "the partial output does not match the schema" : void 0].filter((note) => note !== void 0) : void 0
|
|
513
468
|
}),
|
|
514
|
-
output: stopped ? run.partial : run.data ?? run.message,
|
|
515
|
-
raw:
|
|
469
|
+
output: stopped ? run.partial : run.data ?? run.message.value,
|
|
470
|
+
raw: entry.original,
|
|
516
471
|
sources: [],
|
|
517
472
|
status,
|
|
518
|
-
stopReason: stopped ?
|
|
473
|
+
stopReason: stopped ? run.stopReason ?? run.error ?? "failed" : void 0
|
|
519
474
|
});
|
|
520
475
|
};
|
|
521
|
-
const actResult = (
|
|
522
|
-
const
|
|
476
|
+
const actResult = (entry, sessionId, close) => {
|
|
477
|
+
const result = entry.value;
|
|
478
|
+
const stdout = result.stdout ?? "";
|
|
523
479
|
const failure = result.success === false ? "firecrawl reported that the script did not succeed" : void 0;
|
|
524
480
|
const repeated = result.result === "" || result.result === null || result.result === stdout;
|
|
525
481
|
return compact({
|
|
526
|
-
error:
|
|
527
|
-
exitCode:
|
|
528
|
-
killed:
|
|
529
|
-
meta: meta({
|
|
530
|
-
|
|
482
|
+
error: result.error ?? failure,
|
|
483
|
+
exitCode: result.exitCode,
|
|
484
|
+
killed: result.killed,
|
|
485
|
+
meta: meta({
|
|
486
|
+
credits: close.closed?.creditsBilled,
|
|
487
|
+
warnings: close.failure
|
|
488
|
+
}),
|
|
489
|
+
raw: entry.original,
|
|
531
490
|
result: repeated ? void 0 : result.result,
|
|
532
491
|
sessionId,
|
|
533
|
-
stderr:
|
|
492
|
+
stderr: result.stderr ?? "",
|
|
534
493
|
stdout
|
|
535
494
|
});
|
|
536
495
|
};
|
|
537
|
-
const browserSession = (
|
|
538
|
-
|
|
539
|
-
|
|
540
|
-
|
|
541
|
-
|
|
542
|
-
|
|
496
|
+
const browserSession = (entry) => {
|
|
497
|
+
const session = entry.value;
|
|
498
|
+
return compact({
|
|
499
|
+
cdpUrl: session.cdpUrl,
|
|
500
|
+
expiresAt: session.expiresAt,
|
|
501
|
+
id: requireJobId(provider, session.id),
|
|
502
|
+
liveViewUrl: session.liveViewUrl,
|
|
503
|
+
raw: entry.original
|
|
504
|
+
});
|
|
505
|
+
};
|
|
506
|
+
/** Firecrawl's blocks, a page at a time; a page without a number is left out. */
|
|
507
|
+
const documentBlocks = (pages) => pages.flatMap((entry) => {
|
|
508
|
+
const page = entry.pageNumber;
|
|
509
|
+
if (page === void 0) return [];
|
|
510
|
+
return entry.items.map((item) => {
|
|
511
|
+
const [x0, y0, x1, y1] = item.bbox;
|
|
512
|
+
return compact({
|
|
513
|
+
box: item.bbox.length === 4 && x0 !== void 0 && y0 !== void 0 && x1 !== void 0 && y1 !== void 0 ? {
|
|
514
|
+
height: y1 - y0,
|
|
515
|
+
left: x0,
|
|
516
|
+
top: y0,
|
|
517
|
+
width: x1 - x0
|
|
518
|
+
} : void 0,
|
|
519
|
+
page,
|
|
520
|
+
text: item.content ?? "",
|
|
521
|
+
type: item.type ?? "unknown"
|
|
522
|
+
});
|
|
523
|
+
});
|
|
543
524
|
});
|
|
544
|
-
|
|
545
|
-
|
|
546
|
-
const
|
|
525
|
+
/** A parsed document; the caller adds `raw`. */
|
|
526
|
+
const parseResult = (body) => {
|
|
527
|
+
const { data } = body;
|
|
547
528
|
return compact({
|
|
548
|
-
markdown:
|
|
549
|
-
pages:
|
|
550
|
-
markdown:
|
|
551
|
-
pageNumber: Number(
|
|
552
|
-
}))
|
|
553
|
-
blocks:
|
|
554
|
-
pageCount:
|
|
555
|
-
meta: pageMeta(
|
|
556
|
-
raw: response
|
|
529
|
+
markdown: data.markdown ?? "",
|
|
530
|
+
pages: data.pages?.map((page) => ({
|
|
531
|
+
markdown: page.markdown ?? "",
|
|
532
|
+
pageNumber: Number(page.pageNumber)
|
|
533
|
+
})),
|
|
534
|
+
blocks: data.blocks && documentBlocks(data.blocks),
|
|
535
|
+
pageCount: data.metadata.totalPages ?? data.metadata.numPages,
|
|
536
|
+
meta: pageMeta(data, body.warning.notes)
|
|
557
537
|
});
|
|
558
538
|
};
|
|
559
539
|
const watching = (monitor) => {
|
|
560
|
-
|
|
561
|
-
|
|
562
|
-
|
|
563
|
-
if (target.type === "
|
|
564
|
-
|
|
565
|
-
return strings(target.queries) ?? [];
|
|
540
|
+
if (monitor.goal !== void 0) return monitor.goal;
|
|
541
|
+
return monitor.targets.flatMap((target) => {
|
|
542
|
+
if (target.type === "scrape") return target.urls;
|
|
543
|
+
if (target.type === "crawl") return [target.url];
|
|
544
|
+
return target.queries;
|
|
566
545
|
}).filter((item) => item !== void 0).join(", ") || void 0;
|
|
567
546
|
};
|
|
568
|
-
const monitorInfo = (
|
|
569
|
-
const monitor =
|
|
570
|
-
const schedule = record(monitor.schedule);
|
|
547
|
+
const monitorInfo = (entry) => {
|
|
548
|
+
const monitor = entry.value;
|
|
571
549
|
return compact({
|
|
572
|
-
createdAt:
|
|
573
|
-
id:
|
|
574
|
-
raw:
|
|
575
|
-
schedule:
|
|
576
|
-
status:
|
|
550
|
+
createdAt: monitor.createdAt,
|
|
551
|
+
id: requireJobId(provider, monitor.id),
|
|
552
|
+
raw: entry.original,
|
|
553
|
+
schedule: monitor.schedule.cron ?? monitor.schedule.text,
|
|
554
|
+
status: monitor.status,
|
|
577
555
|
watch: watching(monitor),
|
|
578
|
-
webhookUrl:
|
|
556
|
+
webhookUrl: monitor.webhook.url
|
|
579
557
|
});
|
|
580
558
|
};
|
|
581
|
-
const checkEvent = (
|
|
582
|
-
const
|
|
559
|
+
const checkEvent = (entry) => {
|
|
560
|
+
const check = entry.value;
|
|
561
|
+
const { summary } = check;
|
|
583
562
|
const counts = [
|
|
584
563
|
"changed",
|
|
585
564
|
"new",
|
|
586
565
|
"removed",
|
|
587
566
|
"error"
|
|
588
567
|
].flatMap((key) => {
|
|
589
|
-
const count =
|
|
568
|
+
const count = summary[key];
|
|
590
569
|
return count === void 0 ? [] : [`${count} ${key}`];
|
|
591
570
|
});
|
|
592
|
-
const pages =
|
|
571
|
+
const pages = summary.totalPages;
|
|
593
572
|
const of = pages === void 0 ? "" : ` of ${pages} pages`;
|
|
594
573
|
return compact({
|
|
595
|
-
at:
|
|
596
|
-
id:
|
|
597
|
-
raw:
|
|
574
|
+
at: check.finishedAt ?? check.startedAt ?? check.scheduledFor ?? check.createdAt,
|
|
575
|
+
id: check.id,
|
|
576
|
+
raw: entry.original,
|
|
598
577
|
summary: [
|
|
599
|
-
|
|
578
|
+
check.status,
|
|
600
579
|
counts.length > 0 ? `${counts.join(", ")}${of}` : void 0,
|
|
601
|
-
|
|
580
|
+
check.error
|
|
602
581
|
].filter((part) => part !== void 0).join(": ")
|
|
603
582
|
});
|
|
604
583
|
};
|
|
605
|
-
|
|
606
|
-
|
|
607
|
-
|
|
608
|
-
|
|
609
|
-
|
|
610
|
-
|
|
611
|
-
|
|
612
|
-
|
|
613
|
-
|
|
614
|
-
|
|
615
|
-
|
|
616
|
-
|
|
617
|
-
|
|
618
|
-
|
|
619
|
-
|
|
584
|
+
/** One page of a monitor's checks; the caller adds `raw`. */
|
|
585
|
+
const monitorEvents = (checks, offset) => compact({
|
|
586
|
+
events: checks.map((check) => checkEvent(check)),
|
|
587
|
+
next: checks.length === 100 ? String(offset + checks.length) : void 0
|
|
588
|
+
});
|
|
589
|
+
/** The account's credit usage; the caller adds `raw`. */
|
|
590
|
+
const usageResult = (body) => compact({
|
|
591
|
+
limit: body.data.planCredits,
|
|
592
|
+
periodEnd: body.data.billingPeriodEnd,
|
|
593
|
+
remaining: body.data.remainingCredits
|
|
594
|
+
});
|
|
595
|
+
// src/adapters/firecrawl/shapes.ts
|
|
596
|
+
/**
|
|
597
|
+
* Warnings as text: a string is one warning (an empty one too); an array gives
|
|
598
|
+
* every entry as a string, whatever it is; anything else gives none.
|
|
599
|
+
*/
|
|
600
|
+
const Notes = z.union([z.pipe(z.string(), z.transform((note) => [note])), arrayOf(z.pipe(z.unknown(), z.transform(String)))]);
|
|
601
|
+
/** A warning, as its text when it is a non-empty string and as the list of warnings it amounts to. */
|
|
602
|
+
const Warning = z.pipe(both(optionalString, Notes), z.transform(({ first, second }) => ({
|
|
603
|
+
notes: second,
|
|
604
|
+
text: first
|
|
605
|
+
})));
|
|
606
|
+
/** A product image: a bare URL, or an object with a URL (or `src`) and a description. One without a URL reads as undefined. */
|
|
607
|
+
const Image = z.union([z.pipe(z.string(), z.transform((url) => url === "" ? void 0 : { url })), z.pipe(looseObject({
|
|
608
|
+
alt: optionalString,
|
|
609
|
+
src: optionalString,
|
|
610
|
+
url: optionalString
|
|
611
|
+
}), z.transform((image) => {
|
|
612
|
+
const url = image.url ?? image.src;
|
|
613
|
+
return url === void 0 ? void 0 : compact({
|
|
614
|
+
alt: image.alt,
|
|
615
|
+
url
|
|
620
616
|
});
|
|
617
|
+
}))]);
|
|
618
|
+
/** A price. The amount is a string or a number, read as a string. */
|
|
619
|
+
const Price = looseObject({
|
|
620
|
+
amount: optionalId,
|
|
621
|
+
currency: optionalString,
|
|
622
|
+
formatted: optionalString
|
|
623
|
+
});
|
|
624
|
+
const Variant = looseObject({
|
|
625
|
+
availability: looseObject({
|
|
626
|
+
inStock: optionalBoolean,
|
|
627
|
+
text: optionalString
|
|
628
|
+
}),
|
|
629
|
+
gtin: optionalScalar,
|
|
630
|
+
gtin12: optionalScalar,
|
|
631
|
+
gtin13: optionalScalar,
|
|
632
|
+
gtin14: optionalScalar,
|
|
633
|
+
gtin8: optionalScalar,
|
|
634
|
+
id: optionalString,
|
|
635
|
+
images: arrayOf(Image),
|
|
636
|
+
price: Price,
|
|
637
|
+
sale: looseObject({ originalPrice: Price }),
|
|
638
|
+
sku: optionalString,
|
|
639
|
+
title: optionalString,
|
|
640
|
+
values: recordOf(optionalScalar)
|
|
641
|
+
});
|
|
642
|
+
/** The metadata of a scraped page, and of a parsed document. */
|
|
643
|
+
const metadataShape = {
|
|
644
|
+
"article:published_time": optionalString,
|
|
645
|
+
author: optionalFirstString,
|
|
646
|
+
creditsUsed: optionalNumber,
|
|
647
|
+
description: optionalFirstString,
|
|
648
|
+
favicon: optionalString,
|
|
649
|
+
language: optionalFirstString,
|
|
650
|
+
numPages: optionalNumber,
|
|
651
|
+
"og:image": optionalFirstString,
|
|
652
|
+
ogImage: optionalFirstString,
|
|
653
|
+
publishedTime: optionalString,
|
|
654
|
+
scrapeId: optionalScalar,
|
|
655
|
+
sourceURL: optionalString,
|
|
656
|
+
statusCode: optionalNumber,
|
|
657
|
+
title: optionalFirstString,
|
|
658
|
+
totalPages: optionalNumber,
|
|
659
|
+
url: optionalString
|
|
621
660
|
};
|
|
661
|
+
/** What a scrape returns for one page. `json` is kept as it arrived. */
|
|
662
|
+
const PageData = looseObject({
|
|
663
|
+
answer: optionalString,
|
|
664
|
+
highlights: z.pipe(both(optionalString, arrayOf(z.string())), z.transform(({ first, second }) => ({
|
|
665
|
+
list: second,
|
|
666
|
+
text: first
|
|
667
|
+
}))),
|
|
668
|
+
html: optionalString,
|
|
669
|
+
images: arrayOf(z.string()),
|
|
670
|
+
json: anything,
|
|
671
|
+
links: arrayOf(z.string()),
|
|
672
|
+
markdown: optionalString,
|
|
673
|
+
metadata: looseObject(metadataShape),
|
|
674
|
+
product: optionalObject({
|
|
675
|
+
brand: optionalString,
|
|
676
|
+
category: optionalString,
|
|
677
|
+
description: optionalString,
|
|
678
|
+
images: arrayOf(Image),
|
|
679
|
+
title: optionalString,
|
|
680
|
+
url: optionalString,
|
|
681
|
+
variants: arrayOf(Variant)
|
|
682
|
+
}),
|
|
683
|
+
rawHtml: optionalString,
|
|
684
|
+
screenshot: optionalString,
|
|
685
|
+
summary: optionalString,
|
|
686
|
+
warning: Warning
|
|
687
|
+
});
|
|
688
|
+
/** `/scrape`. */
|
|
689
|
+
const ScrapeResponse = looseObject({
|
|
690
|
+
data: PageData,
|
|
691
|
+
warning: Warning
|
|
692
|
+
});
|
|
693
|
+
/** A page of a crawl or batch, beside the entry as it arrived. */
|
|
694
|
+
const PageEntry = withOriginal(PageData);
|
|
695
|
+
/** A crawl or batch while it runs, and each batch of its pages, beside the response as it arrived. */
|
|
696
|
+
const Batch = withOriginal(looseObject({
|
|
697
|
+
creditsUsed: optionalNumber,
|
|
698
|
+
data: arrayOf(PageEntry),
|
|
699
|
+
next: optionalString,
|
|
700
|
+
status: optionalString,
|
|
701
|
+
total: optionalNumber
|
|
702
|
+
}));
|
|
703
|
+
/** The pages a crawl or batch could not read. */
|
|
704
|
+
const BatchErrors = withOriginal(looseObject({
|
|
705
|
+
errors: arrayOf(looseObject({
|
|
706
|
+
error: optionalString,
|
|
707
|
+
url: optionalString
|
|
708
|
+
})),
|
|
709
|
+
robotsBlocked: arrayOf(z.string())
|
|
710
|
+
}));
|
|
711
|
+
/** The reply to starting a crawl. */
|
|
712
|
+
const CrawlStart = looseObject({ id: withOriginal(optionalId) });
|
|
713
|
+
/** The reply to starting a batch scrape or an agent run, beside the response as it arrived. */
|
|
714
|
+
const RunStart = withOriginal(looseObject({
|
|
715
|
+
id: withOriginal(optionalId),
|
|
716
|
+
invalidURLs: arrayOf(z.string()),
|
|
717
|
+
threadId: optionalString
|
|
718
|
+
}));
|
|
719
|
+
/** An agent run while it is polled. */
|
|
720
|
+
const AgentRun = withOriginal(looseObject({
|
|
721
|
+
creditsUsed: optionalNumber,
|
|
722
|
+
data: anything,
|
|
723
|
+
error: optionalString,
|
|
724
|
+
message: z.pipe(both(anything, warningEntry), z.transform(({ first, second }) => ({
|
|
725
|
+
note: second,
|
|
726
|
+
value: first
|
|
727
|
+
}))),
|
|
728
|
+
partial: anything,
|
|
729
|
+
partialSchemaValid: optionalBoolean,
|
|
730
|
+
status: optionalString,
|
|
731
|
+
stopReason: optionalString,
|
|
732
|
+
threadId: optionalString
|
|
733
|
+
}));
|
|
734
|
+
/** A browser session as opened, beside the response as it arrived. */
|
|
735
|
+
const Session = withOriginal(looseObject({
|
|
736
|
+
cdpUrl: optionalString,
|
|
737
|
+
expiresAt: optionalString,
|
|
738
|
+
id: withOriginal(optionalId),
|
|
739
|
+
liveViewUrl: optionalString
|
|
740
|
+
}));
|
|
741
|
+
/** A script's outcome, beside the response as it arrived. */
|
|
742
|
+
const Execution = withOriginal(looseObject({
|
|
743
|
+
error: optionalString,
|
|
744
|
+
exitCode: optionalNumber,
|
|
745
|
+
killed: optionalBoolean,
|
|
746
|
+
result: anything,
|
|
747
|
+
stderr: optionalString,
|
|
748
|
+
stdout: optionalString,
|
|
749
|
+
success: optionalBoolean
|
|
750
|
+
}));
|
|
751
|
+
/** What closing a session billed. */
|
|
752
|
+
const Closed = looseObject({ creditsBilled: optionalNumber });
|
|
753
|
+
const WebItem = looseObject({
|
|
754
|
+
category: optionalString,
|
|
755
|
+
date: optionalString,
|
|
756
|
+
description: optionalString,
|
|
757
|
+
imageUrl: optionalString,
|
|
758
|
+
markdown: optionalString,
|
|
759
|
+
snippet: optionalString,
|
|
760
|
+
title: optionalString,
|
|
761
|
+
url: optionalString
|
|
762
|
+
});
|
|
763
|
+
const Paper = looseObject({
|
|
764
|
+
abstract: optionalString,
|
|
765
|
+
paperId: optionalString,
|
|
766
|
+
primaryId: optionalString,
|
|
767
|
+
score: optionalNumber,
|
|
768
|
+
title: optionalString
|
|
769
|
+
});
|
|
770
|
+
const ImageItem = looseObject({
|
|
771
|
+
imageHeight: optionalNumber,
|
|
772
|
+
imageUrl: optionalString,
|
|
773
|
+
imageWidth: optionalNumber,
|
|
774
|
+
title: optionalString,
|
|
775
|
+
url: optionalString
|
|
776
|
+
});
|
|
777
|
+
/** `/search`. */
|
|
778
|
+
const SearchResponse = looseObject({
|
|
779
|
+
creditsUsed: optionalNumber,
|
|
780
|
+
data: looseObject({
|
|
781
|
+
images: optionalArrayOf(ImageItem),
|
|
782
|
+
news: arrayOf(WebItem),
|
|
783
|
+
research: arrayOf(Paper),
|
|
784
|
+
web: arrayOf(WebItem)
|
|
785
|
+
}),
|
|
786
|
+
id: optionalScalar,
|
|
787
|
+
warning: Notes,
|
|
788
|
+
warnings: Notes
|
|
789
|
+
});
|
|
790
|
+
/** `/map`: each link is a bare URL or an object. */
|
|
791
|
+
const MapResponse = looseObject({ links: arrayOf(z.union([z.pipe(z.string(), z.transform((url) => ({ url }))), z.pipe(looseObject({
|
|
792
|
+
description: optionalString,
|
|
793
|
+
title: optionalString,
|
|
794
|
+
url: optionalString
|
|
795
|
+
}), z.transform((link) => compact({
|
|
796
|
+
description: link.description,
|
|
797
|
+
title: link.title,
|
|
798
|
+
url: link.url ?? ""
|
|
799
|
+
})))])) });
|
|
800
|
+
const Monitor = looseObject({
|
|
801
|
+
createdAt: optionalString,
|
|
802
|
+
goal: optionalString,
|
|
803
|
+
id: withOriginal(optionalId),
|
|
804
|
+
schedule: looseObject({
|
|
805
|
+
cron: optionalString,
|
|
806
|
+
text: optionalString
|
|
807
|
+
}),
|
|
808
|
+
status: optionalString,
|
|
809
|
+
targets: arrayOf(looseObject({
|
|
810
|
+
queries: arrayOf(z.string()),
|
|
811
|
+
type: optionalString,
|
|
812
|
+
url: optionalString,
|
|
813
|
+
urls: arrayOf(z.string())
|
|
814
|
+
})),
|
|
815
|
+
webhook: looseObject({ url: optionalString })
|
|
816
|
+
});
|
|
817
|
+
/** A monitor beside the entry as it arrived. */
|
|
818
|
+
const MonitorEntry = withOriginal(Monitor);
|
|
819
|
+
/** The reply to creating or getting a monitor. */
|
|
820
|
+
const MonitorResponse = looseObject({ data: MonitorEntry });
|
|
821
|
+
/** One page of monitors. */
|
|
822
|
+
const MonitorsResponse = looseObject({ data: arrayOf(MonitorEntry) });
|
|
823
|
+
/** One page of a monitor's checks, each beside its entry as it arrived. */
|
|
824
|
+
const ChecksResponse = looseObject({ data: arrayOf(withOriginal(looseObject({
|
|
825
|
+
createdAt: optionalString,
|
|
826
|
+
error: optionalString,
|
|
827
|
+
finishedAt: optionalString,
|
|
828
|
+
id: optionalString,
|
|
829
|
+
scheduledFor: optionalString,
|
|
830
|
+
startedAt: optionalString,
|
|
831
|
+
status: optionalString,
|
|
832
|
+
summary: looseObject({
|
|
833
|
+
changed: optionalNumber,
|
|
834
|
+
error: optionalNumber,
|
|
835
|
+
new: optionalNumber,
|
|
836
|
+
removed: optionalNumber,
|
|
837
|
+
totalPages: optionalNumber
|
|
838
|
+
})
|
|
839
|
+
}))) });
|
|
840
|
+
/** A page of `/parse` blocks; each box is `[x0, y0, x1, y1]` in fractions of the page. */
|
|
841
|
+
const ParsePage = looseObject({
|
|
842
|
+
items: arrayOf(looseObject({
|
|
843
|
+
bbox: arrayOf(z.number()),
|
|
844
|
+
content: optionalAnyString,
|
|
845
|
+
type: optionalString
|
|
846
|
+
})),
|
|
847
|
+
pageNumber: optionalNumber
|
|
848
|
+
});
|
|
849
|
+
/** `/parse`. */
|
|
850
|
+
const ParseResponse = looseObject({
|
|
851
|
+
data: looseObject({
|
|
852
|
+
blocks: optionalArrayOf(ParsePage),
|
|
853
|
+
markdown: optionalString,
|
|
854
|
+
metadata: looseObject(metadataShape),
|
|
855
|
+
pages: optionalArrayOf(looseObject({
|
|
856
|
+
markdown: optionalString,
|
|
857
|
+
pageNumber: anything
|
|
858
|
+
})),
|
|
859
|
+
warning: Warning
|
|
860
|
+
}),
|
|
861
|
+
warning: Warning
|
|
862
|
+
});
|
|
863
|
+
/** `/team/credit-usage`. */
|
|
864
|
+
const UsageResponse = looseObject({ data: looseObject({
|
|
865
|
+
billingPeriodEnd: optionalString,
|
|
866
|
+
planCredits: optionalNumber,
|
|
867
|
+
remainingCredits: optionalNumber
|
|
868
|
+
}) });
|
|
622
869
|
// src/adapters/firecrawl.ts
|
|
870
|
+
/** How long closing a session may take, apart from the call's own deadline. */
|
|
871
|
+
const CLOSE_TIMEOUT = 15e3;
|
|
872
|
+
/**
|
|
873
|
+
* An adapter for Firecrawl: search, images, read, readMany, extract, product, map, crawl, research, act, browser, parse, monitor and usage. Pass it to `new Fieldwork({ adapter })`.
|
|
874
|
+
*
|
|
875
|
+
* Throws `Unauthorized` when neither `apiKey` nor `FIRECRAWL_API_KEY` is set.
|
|
876
|
+
*/
|
|
623
877
|
const firecrawl = (config = {}) => {
|
|
624
878
|
const baseUrl = config.baseUrl ?? "https://api.firecrawl.dev/v2";
|
|
625
879
|
const raw = createRawClient({
|
|
626
880
|
baseUrl,
|
|
627
881
|
fetch: config.fetch,
|
|
628
882
|
headers: { authorization: `Bearer ${requireKey(provider, config.apiKey, "FIRECRAWL_API_KEY")}` },
|
|
629
|
-
provider
|
|
883
|
+
provider,
|
|
884
|
+
retries: config.retries
|
|
630
885
|
});
|
|
631
886
|
const scrape = async (url, formats, settings, call) => {
|
|
632
|
-
const response =
|
|
887
|
+
const response = await raw.request("POST", "/scrape", {
|
|
633
888
|
...call,
|
|
634
889
|
body: {
|
|
635
890
|
formats,
|
|
636
891
|
url,
|
|
637
892
|
...pageBody(settings)
|
|
638
893
|
}
|
|
639
|
-
})
|
|
894
|
+
});
|
|
895
|
+
const body = z.parse(ScrapeResponse, response);
|
|
640
896
|
return {
|
|
641
|
-
|
|
897
|
+
body,
|
|
898
|
+
data: body.data,
|
|
642
899
|
response
|
|
643
900
|
};
|
|
644
901
|
};
|
|
@@ -649,18 +906,18 @@ const firecrawl = (config = {}) => {
|
|
|
649
906
|
};
|
|
650
907
|
const finished = async (kind, id, call, interval) => {
|
|
651
908
|
const path = `/${kind}/${segment(id)}`;
|
|
652
|
-
const get = async (to) => {
|
|
909
|
+
const get = async (schema, to) => {
|
|
653
910
|
try {
|
|
654
|
-
return
|
|
911
|
+
return z.parse(schema, await raw.request("GET", to, call));
|
|
655
912
|
} catch (error) {
|
|
656
913
|
throw withJob(error, id);
|
|
657
914
|
}
|
|
658
915
|
};
|
|
659
|
-
const first = await poll(provider, id, async () => {
|
|
660
|
-
const status =
|
|
661
|
-
const state =
|
|
916
|
+
const first = await poll(provider, id, async (request) => {
|
|
917
|
+
const status = z.parse(Batch, await raw.request("GET", path, request));
|
|
918
|
+
const state = status.value.status;
|
|
662
919
|
if (state === "failed" || state === "cancelled") throw new FieldworkError("JobFailed", `firecrawl ${kind} ${id} ended ${state}`, {
|
|
663
|
-
cause: status,
|
|
920
|
+
cause: status.original,
|
|
664
921
|
provider
|
|
665
922
|
});
|
|
666
923
|
return state === "completed" ? status : void 0;
|
|
@@ -669,13 +926,13 @@ const firecrawl = (config = {}) => {
|
|
|
669
926
|
interval
|
|
670
927
|
});
|
|
671
928
|
const batches = [first];
|
|
672
|
-
let next =
|
|
673
|
-
while (next) {
|
|
674
|
-
const batch = await get(pathOf(next));
|
|
929
|
+
let { next } = first.value;
|
|
930
|
+
while (next !== void 0) {
|
|
931
|
+
const batch = await get(Batch, pathOf(next));
|
|
675
932
|
batches.push(batch);
|
|
676
|
-
next =
|
|
933
|
+
({next} = batch.value);
|
|
677
934
|
}
|
|
678
|
-
const errors = await get(`${path}/errors`);
|
|
935
|
+
const errors = await get(BatchErrors, `${path}/errors`);
|
|
679
936
|
return {
|
|
680
937
|
batches,
|
|
681
938
|
errors,
|
|
@@ -684,38 +941,65 @@ const firecrawl = (config = {}) => {
|
|
|
684
941
|
};
|
|
685
942
|
};
|
|
686
943
|
const openSession = async (o, call) => {
|
|
687
|
-
const
|
|
944
|
+
const session = z.parse(Session, await raw.request("POST", "/interact", {
|
|
688
945
|
body: sessionBody(o),
|
|
946
|
+
creates: true,
|
|
947
|
+
retries: call.retries,
|
|
689
948
|
signal: call.signal
|
|
690
949
|
}));
|
|
691
950
|
return {
|
|
692
|
-
id:
|
|
693
|
-
|
|
951
|
+
id: requireJobId(provider, session.value.id),
|
|
952
|
+
session
|
|
694
953
|
};
|
|
695
954
|
};
|
|
696
|
-
|
|
955
|
+
/**
|
|
956
|
+
* Closes a session so it stops billing. It runs on its own deadline, so a
|
|
957
|
+
* call that was cancelled or timed out still closes what it opened. A
|
|
958
|
+
* failure is returned rather than thrown: the caller reports it with the
|
|
959
|
+
* session id, so the session can still be closed by hand.
|
|
960
|
+
*/
|
|
961
|
+
const closeSession = async (id, call) => {
|
|
697
962
|
try {
|
|
698
|
-
return
|
|
699
|
-
|
|
700
|
-
|
|
963
|
+
return {
|
|
964
|
+
closed: z.parse(Closed, await raw.request("DELETE", `/interact/${segment(id)}`, {
|
|
965
|
+
retries: call.retries,
|
|
966
|
+
signal: AbortSignal.timeout(CLOSE_TIMEOUT)
|
|
967
|
+
})),
|
|
968
|
+
failure: void 0
|
|
969
|
+
};
|
|
970
|
+
} catch (error) {
|
|
971
|
+
return {
|
|
972
|
+
closed: void 0,
|
|
973
|
+
failure: `firecrawl could not close session ${id}, which may still bill: ${error instanceof Error ? error.message : String(error)}. Close it with DELETE /interact/${id}`
|
|
974
|
+
};
|
|
701
975
|
}
|
|
702
976
|
};
|
|
703
977
|
return defineAdapter({
|
|
704
978
|
name: provider,
|
|
705
979
|
operations: {
|
|
706
980
|
async act(code, options) {
|
|
707
|
-
const { call, rest: o } = callSettings(options);
|
|
981
|
+
const { call, rest: o } = callSettings(options, REPORT_GRACE_MS);
|
|
708
982
|
const seconds = checkAct(o, call.timeout);
|
|
709
983
|
const created = o.session === void 0;
|
|
710
984
|
const keep = o.keepSession ?? !created;
|
|
711
985
|
const { id } = o.session === void 0 ? await openSession(o, call) : { id: o.session };
|
|
712
986
|
try {
|
|
713
|
-
const result =
|
|
714
|
-
|
|
715
|
-
|
|
987
|
+
const result = z.parse(Execution, await raw.request("POST", `/interact/${segment(id)}/execute`, {
|
|
988
|
+
...scriptRequest(code, o.language, call, seconds),
|
|
989
|
+
creates: true
|
|
990
|
+
}));
|
|
991
|
+
if (keep) return actResult(result, id, {});
|
|
992
|
+
const close = await closeSession(id, call);
|
|
993
|
+
return actResult(result, close.failure === void 0 ? void 0 : id, close);
|
|
716
994
|
} catch (error) {
|
|
717
|
-
if (created
|
|
718
|
-
|
|
995
|
+
if (!created && keep) throw error;
|
|
996
|
+
const close = await closeSession(id, call);
|
|
997
|
+
if (close.failure === void 0 || !(error instanceof FieldworkError)) throw error;
|
|
998
|
+
throw new FieldworkError(error.code, `${error.message}; ${close.failure}`, {
|
|
999
|
+
cause: error,
|
|
1000
|
+
provider,
|
|
1001
|
+
status: error.status
|
|
1002
|
+
});
|
|
719
1003
|
}
|
|
720
1004
|
},
|
|
721
1005
|
browser: {
|
|
@@ -725,85 +1009,86 @@ const firecrawl = (config = {}) => {
|
|
|
725
1009
|
},
|
|
726
1010
|
async open(options) {
|
|
727
1011
|
const { call, rest: o } = callSettings(options);
|
|
728
|
-
const {
|
|
729
|
-
return browserSession(
|
|
1012
|
+
const { session } = await openSession(o, call);
|
|
1013
|
+
return browserSession(session);
|
|
730
1014
|
}
|
|
731
1015
|
},
|
|
732
1016
|
async crawl(url, options) {
|
|
733
1017
|
const { call, rest: o } = callSettings(options);
|
|
734
|
-
const id = o.resume ??
|
|
1018
|
+
const id = o.resume ?? requireJobId("firecrawl", z.parse(CrawlStart, await raw.request("POST", "/crawl", {
|
|
1019
|
+
creates: true,
|
|
735
1020
|
...call,
|
|
736
1021
|
body: crawlBody(url, o)
|
|
737
1022
|
})).id);
|
|
738
1023
|
const job = await finished("crawl", id, call, o.interval);
|
|
1024
|
+
const { robotsBlocked } = job.errors.value;
|
|
739
1025
|
return compact({
|
|
740
1026
|
failed: job.failed,
|
|
741
1027
|
id,
|
|
742
1028
|
meta: meta({
|
|
743
|
-
credits: job.first.creditsUsed,
|
|
1029
|
+
credits: job.first.value.creditsUsed,
|
|
744
1030
|
requestId: id
|
|
745
1031
|
}),
|
|
746
|
-
pages: job.batches.flatMap((batch) =>
|
|
1032
|
+
pages: job.batches.flatMap((batch) => batch.value.data.map((item) => ({
|
|
1033
|
+
...toPage(item.value, url),
|
|
1034
|
+
raw: item.original
|
|
1035
|
+
}))),
|
|
747
1036
|
raw: {
|
|
748
|
-
batches: job.batches,
|
|
749
|
-
errors: job.errors
|
|
1037
|
+
batches: job.batches.map((batch) => batch.original),
|
|
1038
|
+
errors: job.errors.original
|
|
750
1039
|
},
|
|
751
|
-
robotsBlocked:
|
|
752
|
-
total:
|
|
1040
|
+
robotsBlocked: robotsBlocked.length > 0 ? robotsBlocked : void 0,
|
|
1041
|
+
total: job.first.value.total
|
|
753
1042
|
});
|
|
754
1043
|
},
|
|
755
1044
|
async extract(url, options) {
|
|
756
1045
|
const { call, rest: o } = callSettings(options);
|
|
757
1046
|
const { schema, prompt, ...page } = o;
|
|
758
|
-
const { response, data } = await scrape(url, [compact({
|
|
1047
|
+
const { body, response, data } = await scrape(url, [compact({
|
|
759
1048
|
prompt,
|
|
760
|
-
schema,
|
|
1049
|
+
schema: jsonSchemaOf(schema),
|
|
761
1050
|
type: "json"
|
|
762
1051
|
})], page, call);
|
|
763
1052
|
if (data.json === void 0) {
|
|
764
|
-
const why =
|
|
765
|
-
throw new FieldworkError("ProviderError", `firecrawl returned no JSON for ${url}${why ? `: ${why}`
|
|
1053
|
+
const why = data.warning.text;
|
|
1054
|
+
throw new FieldworkError("ProviderError", `firecrawl returned no JSON for ${url}${why === void 0 ? "" : `: ${why}`}`, {
|
|
766
1055
|
cause: response,
|
|
767
1056
|
provider
|
|
768
1057
|
});
|
|
769
1058
|
}
|
|
770
1059
|
return compact({
|
|
771
|
-
data: data.json,
|
|
772
|
-
meta: pageMeta(
|
|
1060
|
+
data: await checkOutput(schema, data.json, { provider }),
|
|
1061
|
+
meta: pageMeta(data, body.warning.notes),
|
|
773
1062
|
raw: response
|
|
774
1063
|
});
|
|
775
1064
|
},
|
|
776
1065
|
async images(query, options) {
|
|
777
1066
|
const { call, rest: o } = callSettings(options);
|
|
778
|
-
const response =
|
|
1067
|
+
const response = await raw.request("POST", "/search", {
|
|
779
1068
|
...call,
|
|
780
1069
|
body: imagesBody(query, o)
|
|
781
|
-
})
|
|
782
|
-
return
|
|
1070
|
+
});
|
|
1071
|
+
return {
|
|
1072
|
+
...imagesResult(z.parse(SearchResponse, response)),
|
|
1073
|
+
raw: response
|
|
1074
|
+
};
|
|
783
1075
|
},
|
|
784
1076
|
async map(url, options) {
|
|
785
1077
|
const { call, rest: o } = callSettings(options);
|
|
786
|
-
const response =
|
|
1078
|
+
const response = await raw.request("POST", "/map", {
|
|
787
1079
|
...call,
|
|
788
1080
|
body: mapBody(url, o)
|
|
789
|
-
})
|
|
1081
|
+
});
|
|
790
1082
|
return {
|
|
791
|
-
links:
|
|
792
|
-
if (typeof item === "string") return { url: item };
|
|
793
|
-
const link = record(item);
|
|
794
|
-
return compact({
|
|
795
|
-
description: text(link.description),
|
|
796
|
-
title: text(link.title),
|
|
797
|
-
url: text(link.url) ?? ""
|
|
798
|
-
});
|
|
799
|
-
}),
|
|
1083
|
+
links: z.parse(MapResponse, response).links,
|
|
800
1084
|
raw: response
|
|
801
1085
|
};
|
|
802
1086
|
},
|
|
803
1087
|
monitor: {
|
|
804
1088
|
async create(options) {
|
|
805
1089
|
const { call, rest: o } = callSettings(options);
|
|
806
|
-
const response =
|
|
1090
|
+
const response = z.parse(MonitorResponse, await raw.request("POST", "/monitor", {
|
|
1091
|
+
creates: true,
|
|
807
1092
|
...call,
|
|
808
1093
|
body: monitorBody(o)
|
|
809
1094
|
}));
|
|
@@ -816,61 +1101,82 @@ const firecrawl = (config = {}) => {
|
|
|
816
1101
|
async events(id, options) {
|
|
817
1102
|
const { call, rest: o } = callSettings(options);
|
|
818
1103
|
const offset = Number(o.cursor ?? 0);
|
|
819
|
-
if (!Number.isInteger(offset) || offset < 0) throw
|
|
820
|
-
const response =
|
|
1104
|
+
if (!Number.isInteger(offset) || offset < 0) throw invalidRequest(provider, `events cursor "${o.cursor}" is not valid`);
|
|
1105
|
+
const response = await raw.request("GET", `/monitor/${segment(id)}/checks`, {
|
|
821
1106
|
...call,
|
|
822
1107
|
query: {
|
|
823
1108
|
limit: 100,
|
|
824
1109
|
offset
|
|
825
1110
|
}
|
|
826
|
-
})
|
|
827
|
-
return
|
|
1111
|
+
});
|
|
1112
|
+
return {
|
|
1113
|
+
...monitorEvents(z.parse(ChecksResponse, response).data, offset),
|
|
1114
|
+
raw: response
|
|
1115
|
+
};
|
|
828
1116
|
},
|
|
829
1117
|
async get(id, options) {
|
|
830
1118
|
const { call } = callSettings(options);
|
|
831
|
-
const response =
|
|
1119
|
+
const response = z.parse(MonitorResponse, await raw.request("GET", `/monitor/${segment(id)}`, call));
|
|
832
1120
|
return monitorInfo(response.data);
|
|
833
1121
|
},
|
|
834
1122
|
async list(options) {
|
|
835
1123
|
const { call } = callSettings(options);
|
|
836
1124
|
const monitors = [];
|
|
837
1125
|
for (;;) {
|
|
838
|
-
const
|
|
1126
|
+
const page = z.parse(MonitorsResponse, await raw.request("GET", "/monitor", {
|
|
839
1127
|
...call,
|
|
840
1128
|
query: {
|
|
841
1129
|
limit: 100,
|
|
842
1130
|
offset: monitors.length
|
|
843
1131
|
}
|
|
844
|
-
}));
|
|
845
|
-
|
|
846
|
-
monitors.push(...page.map((item) => monitorInfo(item)));
|
|
1132
|
+
})).data;
|
|
1133
|
+
monitors.push(...page.map((entry) => monitorInfo(entry)));
|
|
847
1134
|
if (page.length < 100) return monitors;
|
|
848
1135
|
}
|
|
849
1136
|
}
|
|
850
1137
|
},
|
|
851
1138
|
async parse(document, options) {
|
|
852
|
-
const { call, rest: o } = callSettings(options);
|
|
853
|
-
const form = parseForm(document, o);
|
|
854
|
-
const response =
|
|
1139
|
+
const { call, rest: o } = callSettings(options, REPORT_GRACE_MS);
|
|
1140
|
+
const form = parseForm(document, o, call.timeout);
|
|
1141
|
+
const response = await raw.request("POST", "/parse", {
|
|
855
1142
|
...call,
|
|
856
|
-
form
|
|
857
|
-
|
|
858
|
-
|
|
1143
|
+
form,
|
|
1144
|
+
timeout: call.timeout === void 0 ? void 0 : call.timeout + REPORT_GRACE_MS
|
|
1145
|
+
});
|
|
1146
|
+
return {
|
|
1147
|
+
...parseResult(z.parse(ParseResponse, response)),
|
|
1148
|
+
raw: response
|
|
1149
|
+
};
|
|
859
1150
|
},
|
|
860
1151
|
async product(url, options) {
|
|
861
1152
|
const { call, rest: o } = callSettings(options);
|
|
862
|
-
const {
|
|
863
|
-
|
|
1153
|
+
const { body, response } = await scrape(url, ["product"], o, call);
|
|
1154
|
+
const product = toProduct(body);
|
|
1155
|
+
if (product === void 0) {
|
|
1156
|
+
const why = noProductReason(body);
|
|
1157
|
+
throw new FieldworkError("NotFound", `firecrawl found no product on ${url}${why === void 0 ? "" : `: ${why}`}`, {
|
|
1158
|
+
cause: response,
|
|
1159
|
+
provider
|
|
1160
|
+
});
|
|
1161
|
+
}
|
|
1162
|
+
return {
|
|
1163
|
+
...product,
|
|
1164
|
+
raw: response
|
|
1165
|
+
};
|
|
864
1166
|
},
|
|
865
1167
|
async read(url, options) {
|
|
866
1168
|
const { call, rest: o } = callSettings(options);
|
|
867
|
-
const {
|
|
868
|
-
return presentPage(provider,
|
|
1169
|
+
const { body, data, response } = await scrape(url, readFormats(o), o, call);
|
|
1170
|
+
return presentPage(provider, {
|
|
1171
|
+
...toPage(data, url, body.warning.notes),
|
|
1172
|
+
raw: response
|
|
1173
|
+
});
|
|
869
1174
|
},
|
|
870
1175
|
async readMany(urls, options) {
|
|
871
1176
|
const { call, rest: o } = callSettings(options);
|
|
872
1177
|
const { interval, resume, maxConcurrency, ignoreInvalidURLs, ...read } = o;
|
|
873
|
-
const started = resume === void 0 ?
|
|
1178
|
+
const started = z.parse(RunStart, resume === void 0 ? await raw.request("POST", "/batch/scrape", {
|
|
1179
|
+
creates: true,
|
|
874
1180
|
...call,
|
|
875
1181
|
body: compact({
|
|
876
1182
|
urls,
|
|
@@ -878,14 +1184,17 @@ const firecrawl = (config = {}) => {
|
|
|
878
1184
|
maxConcurrency,
|
|
879
1185
|
ignoreInvalidURLs
|
|
880
1186
|
})
|
|
881
|
-
})
|
|
882
|
-
const id = resume ??
|
|
1187
|
+
}) : {});
|
|
1188
|
+
const id = resume ?? requireJobId("firecrawl", started.value.id);
|
|
883
1189
|
const job = await finished("batch/scrape", id, call, interval);
|
|
884
|
-
const rejected =
|
|
1190
|
+
const rejected = started.value.invalidURLs.map((url) => ({
|
|
885
1191
|
error: "invalid URL",
|
|
886
1192
|
url
|
|
887
1193
|
}));
|
|
888
|
-
const { pages, gone } = presentPages(job.batches.flatMap((batch) =>
|
|
1194
|
+
const { pages, gone } = presentPages(job.batches.flatMap((batch) => batch.value.data.map((item) => ({
|
|
1195
|
+
...toPage(item.value, ""),
|
|
1196
|
+
raw: item.original
|
|
1197
|
+
}))));
|
|
889
1198
|
return compact({
|
|
890
1199
|
failed: [
|
|
891
1200
|
...job.failed,
|
|
@@ -894,41 +1203,56 @@ const firecrawl = (config = {}) => {
|
|
|
894
1203
|
],
|
|
895
1204
|
id,
|
|
896
1205
|
meta: meta({
|
|
897
|
-
credits: job.first.creditsUsed,
|
|
1206
|
+
credits: job.first.value.creditsUsed,
|
|
898
1207
|
requestId: id
|
|
899
1208
|
}),
|
|
900
1209
|
pages,
|
|
901
1210
|
raw: {
|
|
902
|
-
batches: job.batches,
|
|
903
|
-
errors: job.errors,
|
|
904
|
-
started
|
|
1211
|
+
batches: job.batches.map((batch) => batch.original),
|
|
1212
|
+
errors: job.errors.original,
|
|
1213
|
+
started: started.original
|
|
905
1214
|
}
|
|
906
1215
|
});
|
|
907
1216
|
},
|
|
908
1217
|
async research(question, options) {
|
|
909
1218
|
const { call, rest: o } = callSettings(options);
|
|
910
|
-
const started = o.resume === void 0 ?
|
|
1219
|
+
const started = z.parse(RunStart, o.resume === void 0 ? await raw.request("POST", "/agent", {
|
|
1220
|
+
creates: true,
|
|
911
1221
|
...call,
|
|
912
1222
|
body: researchBody(question, o)
|
|
913
|
-
})
|
|
914
|
-
const id = o.resume ??
|
|
915
|
-
const run = await poll(provider, id, async () => researchState(id,
|
|
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))), {
|
|
916
1226
|
...call,
|
|
917
1227
|
interval: o.interval
|
|
918
1228
|
});
|
|
919
|
-
|
|
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
|
+
};
|
|
920
1237
|
},
|
|
921
1238
|
async search(query, options) {
|
|
922
1239
|
const { call, rest: o } = callSettings(options);
|
|
923
|
-
const response =
|
|
1240
|
+
const response = await raw.request("POST", "/search", {
|
|
924
1241
|
...call,
|
|
925
1242
|
body: searchBody(query, o)
|
|
926
|
-
})
|
|
927
|
-
return
|
|
1243
|
+
});
|
|
1244
|
+
return {
|
|
1245
|
+
...searchResult(z.parse(SearchResponse, response)),
|
|
1246
|
+
raw: response
|
|
1247
|
+
};
|
|
928
1248
|
},
|
|
929
1249
|
async usage(options) {
|
|
930
1250
|
const { call } = callSettings(options);
|
|
931
|
-
|
|
1251
|
+
const response = await raw.request("GET", "/team/credit-usage", call);
|
|
1252
|
+
return {
|
|
1253
|
+
...usageResult(z.parse(UsageResponse, response)),
|
|
1254
|
+
raw: response
|
|
1255
|
+
};
|
|
932
1256
|
}
|
|
933
1257
|
},
|
|
934
1258
|
raw
|