@howells/fieldwork-sdk 0.2.0 → 0.3.1
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 +104 -38
- package/dist/adapter-CEAQuT7F.js +3 -0
- package/dist/adapter-DGehHCMo.d.ts +470 -0
- package/dist/brave.d.ts +164 -0
- package/dist/brave.js +399 -0
- package/dist/browserbase.d.ts +128 -0
- package/dist/browserbase.js +180 -0
- package/dist/{errors-pzPMh82H.js → errors-BiIBG9zN.js} +14 -18
- package/dist/exa.d.ts +150 -24
- package/dist/exa.js +427 -119
- package/dist/{fieldwork-nPzWEelg.d.ts → fieldwork-B3x3cxDJ.d.ts} +5 -5
- package/dist/firecrawl.d.ts +220 -28
- package/dist/firecrawl.js +855 -233
- package/dist/index.d.ts +11 -5
- package/dist/index.js +53 -35
- package/dist/parallel.d.ts +188 -19
- package/dist/parallel.js +644 -113
- package/dist/perplexity.d.ts +78 -22
- package/dist/perplexity.js +318 -92
- package/dist/serpapi.d.ts +172 -0
- package/dist/serpapi.js +517 -0
- package/dist/tavily.d.ts +104 -31
- package/dist/tavily.js +347 -102
- package/dist/tools.d.ts +42 -14
- package/dist/tools.js +1274 -484
- package/dist/types-CnomnF-6.js +27 -0
- package/dist/util-YaZYZDSk.js +287 -0
- package/package.json +19 -3
- package/dist/adapter-C_kRm6TT.d.ts +0 -178
- package/dist/adapter-D-6-GFhJ.js +0 -5
- package/dist/util-D0PLE6Rl.d.ts +0 -2
- package/dist/util-DgcIZI2K.js +0 -214
package/dist/firecrawl.js
CHANGED
|
@@ -1,315 +1,937 @@
|
|
|
1
|
-
import { t as defineAdapter } from "./adapter-
|
|
2
|
-
import { r as withJob, t as FieldworkError } from "./errors-
|
|
3
|
-
import {
|
|
4
|
-
// src/adapters/firecrawl.ts
|
|
5
|
-
|
|
1
|
+
import { t as defineAdapter } from "./adapter-CEAQuT7F.js";
|
|
2
|
+
import { r as withJob, t as FieldworkError } from "./errors-BiIBG9zN.js";
|
|
3
|
+
import { S as requireKey, _ as strings, b as createRawClient, c as num, d as presentPages, f as productImages, g as scalar, h as requireId, i as compact, m as refuseTogether, o as list, p as record, s as meta, t as callSettings, u as presentPage, v as text, x as poll } from "./util-YaZYZDSk.js";
|
|
4
|
+
// src/adapters/firecrawl/shared.ts
|
|
5
|
+
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
|
+
const country = (code) => code?.toUpperCase();
|
|
10
|
+
// src/adapters/firecrawl/schedule.ts
|
|
11
|
+
/** The fewest minutes Firecrawl allows between two checks of a monitor. */
|
|
12
|
+
const MIN_MINUTES = 5;
|
|
13
|
+
const NAMED_CRON = /* @__PURE__ */ new Map([
|
|
14
|
+
["hour", "0 * * * *"],
|
|
15
|
+
["day", "0 0 * * *"],
|
|
16
|
+
["week", "0 0 * * 0"]
|
|
17
|
+
]);
|
|
18
|
+
const DAILY_CRON = /* @__PURE__ */ new Map([[1, "0 0 * * *"], [7, "0 0 * * 0"]]);
|
|
19
|
+
const CRON_PART = /^(?:\*|(?<from>\d+)(?:-(?<to>\d+))?)(?:\/(?<step>\d+))?$/u;
|
|
20
|
+
const INTERVAL = /^(?<count>\d+)(?<unit>[hd])$/u;
|
|
21
|
+
const rangeEnd = (groups, wildcard, from, max) => {
|
|
22
|
+
if (wildcard || groups.to === void 0 && groups.step !== void 0) return max;
|
|
23
|
+
return groups.to === void 0 ? from : Number(groups.to);
|
|
24
|
+
};
|
|
25
|
+
const cronValues = (field, max) => {
|
|
26
|
+
const values = /* @__PURE__ */ new Set();
|
|
27
|
+
for (const part of field.split(",")) {
|
|
28
|
+
const groups = CRON_PART.exec(part)?.groups;
|
|
29
|
+
if (!groups) return;
|
|
30
|
+
const wildcard = part.startsWith("*");
|
|
31
|
+
const from = wildcard ? 0 : Number(groups.from);
|
|
32
|
+
const to = rangeEnd(groups, wildcard, from, max);
|
|
33
|
+
const step = Number(groups.step ?? 1);
|
|
34
|
+
if (step < 1 || from > to || to > max) return;
|
|
35
|
+
for (let value = from; value <= to; value += step) values.add(value);
|
|
36
|
+
}
|
|
37
|
+
return [...values].toSorted((a, b) => a - b);
|
|
38
|
+
};
|
|
39
|
+
const runGaps = (minutes, hours) => {
|
|
40
|
+
const gaps = minutes.slice(1).map((minute, index) => minute - (minutes[index] ?? 0));
|
|
41
|
+
const [first] = minutes;
|
|
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);
|
|
44
|
+
return gaps;
|
|
45
|
+
};
|
|
46
|
+
const checkCron = (cron) => {
|
|
47
|
+
const fields = cron.trim().split(/\s+/u);
|
|
48
|
+
if (fields.length !== 5) throw invalid(`firecrawl needs a five-field cron expression, got "${cron}"`);
|
|
49
|
+
const [minuteField = "", hourField = ""] = fields;
|
|
50
|
+
const minutes = cronValues(minuteField, 59);
|
|
51
|
+
const hours = cronValues(hourField, 23);
|
|
52
|
+
if (minutes && runGaps(minutes, hours).some((gap) => gap < MIN_MINUTES)) throw invalid(`firecrawl monitors run at most every ${MIN_MINUTES} minutes, got "${cron}"`);
|
|
53
|
+
return cron.trim();
|
|
54
|
+
};
|
|
55
|
+
const hourlyCron = (count) => {
|
|
56
|
+
if (!Number.isInteger(count) || count < 1 || 24 % count !== 0) return;
|
|
57
|
+
if (count === 1) return "0 * * * *";
|
|
58
|
+
return count === 24 ? "0 0 * * *" : `0 */${count} * * *`;
|
|
59
|
+
};
|
|
60
|
+
const cronFor = (schedule) => {
|
|
61
|
+
if ("cron" in schedule) return checkCron(schedule.cron);
|
|
62
|
+
const every = schedule.every;
|
|
63
|
+
const named = NAMED_CRON.get(every);
|
|
64
|
+
if (named) return named;
|
|
65
|
+
const groups = INTERVAL.exec(every)?.groups;
|
|
66
|
+
const count = Number(groups?.count);
|
|
67
|
+
const cron = groups?.unit === "h" ? hourlyCron(count) : DAILY_CRON.get(count);
|
|
68
|
+
if (cron) return cron;
|
|
69
|
+
throw invalid(`firecrawl cannot run a monitor every "${every}"; use hour, day, week, a number of hours that divides 24, 1d, 7d or a cron expression`);
|
|
70
|
+
};
|
|
71
|
+
// src/adapters/firecrawl/request.ts
|
|
72
|
+
/** The largest file `/parse` takes. */
|
|
73
|
+
const MAX_PARSE_BYTES = 52428800;
|
|
74
|
+
/** Longest script `/interact/{id}/execute` runs, in seconds. */
|
|
75
|
+
const MAX_SCRIPT_SECONDS = 300;
|
|
76
|
+
/** Milliseconds the request outlives the script's own limit, so a killed script reports back. */
|
|
77
|
+
const SCRIPT_GRACE_MS = 1e4;
|
|
78
|
+
/** The longest query a search monitor takes. */
|
|
79
|
+
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
|
+
const RECENCY = {
|
|
103
|
+
day: "d",
|
|
104
|
+
hour: "h",
|
|
105
|
+
month: "m",
|
|
106
|
+
week: "w",
|
|
107
|
+
year: "y"
|
|
108
|
+
};
|
|
109
|
+
const DATE = /^(?<year>\d{4})-(?<month>\d{2})-(?<day>\d{2})$/u;
|
|
110
|
+
const pageBody = (o) => compact({
|
|
111
|
+
actions: o.actions,
|
|
112
|
+
excludeTags: o.excludeTags,
|
|
113
|
+
includeTags: o.includeTags,
|
|
114
|
+
location: o.location,
|
|
115
|
+
maxAge: o.maxAge === void 0 ? void 0 : Math.round(o.maxAge * 1e3),
|
|
116
|
+
mobile: o.mobile,
|
|
117
|
+
onlyMainContent: o.onlyMainContent,
|
|
118
|
+
parsers: o.parsers,
|
|
119
|
+
proxy: o.proxy,
|
|
120
|
+
waitFor: o.waitFor
|
|
121
|
+
});
|
|
122
|
+
const readFormats = (o) => {
|
|
123
|
+
const query = o.query === void 0 ? [] : [o.queryFormat === "question" ? {
|
|
124
|
+
question: o.query,
|
|
125
|
+
type: "question"
|
|
126
|
+
} : {
|
|
127
|
+
query: o.query,
|
|
128
|
+
type: "highlights"
|
|
129
|
+
}];
|
|
130
|
+
return [
|
|
131
|
+
"markdown",
|
|
132
|
+
...o.include ?? [],
|
|
133
|
+
...query
|
|
134
|
+
];
|
|
135
|
+
};
|
|
136
|
+
const readBody = (o) => ({
|
|
137
|
+
formats: readFormats(o),
|
|
138
|
+
...pageBody(o)
|
|
139
|
+
});
|
|
140
|
+
const usDate = (value) => {
|
|
141
|
+
const groups = DATE.exec(value)?.groups;
|
|
142
|
+
if (!groups) throw invalid(`firecrawl needs dates as YYYY-MM-DD, got "${value}"`);
|
|
143
|
+
return `${groups.month}/${groups.day}/${groups.year}`;
|
|
144
|
+
};
|
|
145
|
+
const timeFilter = (o) => {
|
|
146
|
+
refuseTogether(provider, o, "tbs", "recency", "publishedAfter");
|
|
147
|
+
refuseTogether(provider, o, "tbs", "recency", "publishedBefore");
|
|
148
|
+
if (o.tbs !== void 0) return o.tbs;
|
|
149
|
+
if (o.recency !== void 0) return `qdr:${RECENCY[o.recency]}`;
|
|
150
|
+
if (o.publishedAfter === void 0 && o.publishedBefore === void 0) return;
|
|
151
|
+
return [
|
|
152
|
+
"cdr:1",
|
|
153
|
+
o.publishedAfter === void 0 ? void 0 : `cd_min:${usDate(o.publishedAfter)}`,
|
|
154
|
+
o.publishedBefore === void 0 ? void 0 : `cd_max:${usDate(o.publishedBefore)}`
|
|
155
|
+
].filter((part) => part !== void 0).join(",");
|
|
156
|
+
};
|
|
157
|
+
const searchBody = (query, o) => {
|
|
158
|
+
refuseTogether(provider, o, "includeDomains", "excludeDomains");
|
|
159
|
+
if (o.categories?.includes("gov") && o.categories.length > 1) throw invalid("firecrawl searches the gov category on its own; do not combine it with another category");
|
|
6
160
|
return compact({
|
|
7
|
-
|
|
8
|
-
|
|
9
|
-
|
|
10
|
-
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
proxy: o.proxy,
|
|
161
|
+
categories: o.categories?.map((type) => ({ type })),
|
|
162
|
+
country: country(o.country),
|
|
163
|
+
excludeDomains: o.excludeDomains,
|
|
164
|
+
ignoreInvalidURLs: o.ignoreInvalidURLs,
|
|
165
|
+
includeDomains: o.includeDomains,
|
|
166
|
+
limit: o.limit,
|
|
14
167
|
location: o.location,
|
|
15
|
-
|
|
168
|
+
query,
|
|
169
|
+
safe: o.safe,
|
|
170
|
+
scrapeOptions: o.content ? { formats: ["markdown"] } : void 0,
|
|
171
|
+
sources: o.sources?.map((type) => ({ type })),
|
|
172
|
+
tbs: timeFilter(o)
|
|
173
|
+
});
|
|
174
|
+
};
|
|
175
|
+
const imagesBody = (query, o) => compact({
|
|
176
|
+
country: country(o.country),
|
|
177
|
+
limit: o.limit,
|
|
178
|
+
location: o.location,
|
|
179
|
+
query,
|
|
180
|
+
safe: o.safe,
|
|
181
|
+
sources: [{ type: "images" }]
|
|
182
|
+
});
|
|
183
|
+
const mapBody = (url, o) => compact({
|
|
184
|
+
ignoreCache: o.ignoreCache,
|
|
185
|
+
ignoreQueryParameters: o.ignoreQueryParameters,
|
|
186
|
+
includeSubdomains: o.includeSubdomains,
|
|
187
|
+
limit: o.limit,
|
|
188
|
+
location: o.location,
|
|
189
|
+
search: o.search,
|
|
190
|
+
sitemap: o.sitemap,
|
|
191
|
+
url
|
|
192
|
+
});
|
|
193
|
+
const crawlBody = (url, o) => compact({
|
|
194
|
+
allowExternalLinks: o.allowExternalLinks,
|
|
195
|
+
allowSubdomains: o.allowSubdomains,
|
|
196
|
+
crawlEntireDomain: o.crawlEntireDomain,
|
|
197
|
+
delay: o.delay,
|
|
198
|
+
excludePaths: o.excludePaths,
|
|
199
|
+
ignoreQueryParameters: o.ignoreQueryParameters,
|
|
200
|
+
includePaths: o.includePaths,
|
|
201
|
+
limit: o.limit,
|
|
202
|
+
maxConcurrency: o.maxConcurrency,
|
|
203
|
+
maxDiscoveryDepth: o.maxDiscoveryDepth,
|
|
204
|
+
prompt: o.prompt,
|
|
205
|
+
regexOnFullURL: o.regexOnFullURL,
|
|
206
|
+
scrapeOptions: o.scrapeOptions ? readBody(o.scrapeOptions) : void 0,
|
|
207
|
+
sitemap: o.sitemap,
|
|
208
|
+
url
|
|
209
|
+
});
|
|
210
|
+
const researchBody = (question, o) => compact({
|
|
211
|
+
effort: o.effort,
|
|
212
|
+
location: o.country ? { country: country(o.country) } : void 0,
|
|
213
|
+
maxCredits: o.maxCredits,
|
|
214
|
+
model: o.model,
|
|
215
|
+
prompt: question,
|
|
216
|
+
schema: o.schema,
|
|
217
|
+
strictConstrainToURLs: o.strictConstrainToURLs,
|
|
218
|
+
threadId: o.continueFrom,
|
|
219
|
+
urls: o.urls
|
|
220
|
+
});
|
|
221
|
+
const sessionBody = (o) => compact({
|
|
222
|
+
activityTtl: o.activityTtl ?? o.ttl,
|
|
223
|
+
location: o.country ? { country: country(o.country) } : void 0,
|
|
224
|
+
profile: o.profile,
|
|
225
|
+
ttl: o.ttl
|
|
226
|
+
});
|
|
227
|
+
const checkAct = (o, timeout) => {
|
|
228
|
+
for (const name of [
|
|
229
|
+
"ttl",
|
|
230
|
+
"activityTtl",
|
|
231
|
+
"profile",
|
|
232
|
+
"country"
|
|
233
|
+
]) refuseTogether(provider, o, "session", name);
|
|
234
|
+
if (timeout === void 0) return;
|
|
235
|
+
const seconds = Math.max(1, Math.ceil(timeout / 1e3));
|
|
236
|
+
if (seconds > MAX_SCRIPT_SECONDS) throw invalid(`firecrawl runs a script for at most ${MAX_SCRIPT_SECONDS} seconds`);
|
|
237
|
+
return seconds;
|
|
238
|
+
};
|
|
239
|
+
const scriptRequest = (code, language, call, seconds) => ({
|
|
240
|
+
body: compact({
|
|
241
|
+
code,
|
|
242
|
+
language: language ?? "node",
|
|
243
|
+
timeout: seconds
|
|
244
|
+
}),
|
|
245
|
+
signal: call.signal,
|
|
246
|
+
timeout: call.timeout === void 0 ? void 0 : call.timeout + SCRIPT_GRACE_MS
|
|
247
|
+
});
|
|
248
|
+
const parseForm = (document, o) => {
|
|
249
|
+
const extension = document.name.split(".").pop()?.toLowerCase() ?? "";
|
|
250
|
+
const mediaType = MEDIA_TYPES.get(extension);
|
|
251
|
+
if (!mediaType) throw invalid(`firecrawl parses ${[...MEDIA_TYPES.keys()].join(", ")} files, not "${document.name}"`);
|
|
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`);
|
|
254
|
+
const parser = compact({
|
|
255
|
+
blocks: o.blocks,
|
|
256
|
+
maxPages: o.maxPages,
|
|
257
|
+
mode: o.mode,
|
|
258
|
+
pageMarkers: o.pageMarkers,
|
|
259
|
+
pages: o.pages,
|
|
260
|
+
type: "pdf"
|
|
16
261
|
});
|
|
17
|
-
|
|
18
|
-
|
|
262
|
+
const form = new FormData();
|
|
263
|
+
form.set("options", JSON.stringify({
|
|
264
|
+
formats: ["markdown"],
|
|
265
|
+
parsers: [parser]
|
|
266
|
+
}));
|
|
267
|
+
form.set("file", new Blob([document.data], { type: mediaType }), document.name);
|
|
268
|
+
return form;
|
|
269
|
+
};
|
|
270
|
+
const monitorTarget = (o) => {
|
|
271
|
+
const searchOnly = [
|
|
272
|
+
o.searchWindow,
|
|
273
|
+
o.maxResults,
|
|
274
|
+
o.includeDomains,
|
|
275
|
+
o.excludeDomains
|
|
276
|
+
].some((value) => value !== void 0);
|
|
277
|
+
if (o.urls && o.urls.length > 0) {
|
|
278
|
+
if (searchOnly) throw invalid("firecrawl applies searchWindow, maxResults and the domain lists to search monitors, which take a query and no urls");
|
|
279
|
+
return {
|
|
280
|
+
type: "scrape",
|
|
281
|
+
urls: o.urls
|
|
282
|
+
};
|
|
283
|
+
}
|
|
284
|
+
if (!o.query) throw invalid("firecrawl monitors need urls to watch or a query");
|
|
285
|
+
if (o.query.length > MAX_MONITOR_QUERY) throw invalid(`firecrawl searches queries of up to ${MAX_MONITOR_QUERY} characters; pass urls to watch pages with a longer query`);
|
|
286
|
+
return compact({
|
|
287
|
+
excludeDomains: o.excludeDomains,
|
|
288
|
+
includeDomains: o.includeDomains,
|
|
289
|
+
maxResults: o.maxResults,
|
|
290
|
+
queries: [o.query],
|
|
291
|
+
searchWindow: o.searchWindow,
|
|
292
|
+
type: "search"
|
|
293
|
+
});
|
|
294
|
+
};
|
|
295
|
+
const monitorBody = (o) => {
|
|
296
|
+
const target = monitorTarget(o);
|
|
297
|
+
return compact({
|
|
298
|
+
goal: o.query,
|
|
299
|
+
name: (o.name ?? o.query ?? o.urls?.[0] ?? "monitor").slice(0, 256),
|
|
300
|
+
retentionDays: o.retentionDays,
|
|
301
|
+
schedule: compact({
|
|
302
|
+
cron: cronFor(o.schedule),
|
|
303
|
+
timezone: o.timezone
|
|
304
|
+
}),
|
|
305
|
+
targets: [target],
|
|
306
|
+
webhook: o.webhookUrl ? { url: o.webhookUrl } : void 0
|
|
307
|
+
});
|
|
308
|
+
};
|
|
309
|
+
// src/adapters/firecrawl/response.ts
|
|
310
|
+
/** Where each paper source's records live on the web, for results that carry only ids. */
|
|
311
|
+
const PAPER_URLS = /* @__PURE__ */ new Map([
|
|
312
|
+
["arxiv", (id) => `https://arxiv.org/abs/${id}`],
|
|
313
|
+
["pmid", (id) => `https://pubmed.ncbi.nlm.nih.gov/${id}/`],
|
|
314
|
+
["pmcid", (id) => `https://pmc.ncbi.nlm.nih.gov/articles/${id}/`],
|
|
315
|
+
["doi", (id) => `https://doi.org/${id}`]
|
|
316
|
+
]);
|
|
317
|
+
const LANGUAGE = /^(?<code>[a-z]{2})(?:[-_]|$)/u;
|
|
318
|
+
const firstText = (value) => Array.isArray(value) ? text(value.find((item) => typeof item === "string" && item !== "")) : text(value);
|
|
319
|
+
const languageCode = (value) => LANGUAGE.exec(firstText(value)?.toLowerCase() ?? "")?.groups?.code;
|
|
320
|
+
const excerptsOf = (data) => {
|
|
321
|
+
const highlight = text(data.highlights);
|
|
322
|
+
const highlights = highlight ? [highlight] : strings(data.highlights);
|
|
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
|
+
});
|
|
333
|
+
};
|
|
334
|
+
const toPage = (data, fallbackUrl, raw, top = {}) => {
|
|
19
335
|
const metadata = record(data.metadata);
|
|
20
336
|
return compact({
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
|
|
337
|
+
author: firstText(metadata.author),
|
|
338
|
+
description: firstText(metadata.description),
|
|
339
|
+
excerpts: excerptsOf(data),
|
|
340
|
+
favicon: text(metadata.favicon),
|
|
24
341
|
html: text(data.html),
|
|
25
|
-
|
|
26
|
-
links: strings(data.links),
|
|
342
|
+
image: firstText(metadata.ogImage) ?? firstText(metadata["og:image"]),
|
|
27
343
|
images: strings(data.images),
|
|
28
|
-
|
|
344
|
+
language: languageCode(metadata.language),
|
|
345
|
+
links: strings(data.links),
|
|
346
|
+
markdown: text(data.markdown),
|
|
347
|
+
meta: pageMeta(top, data),
|
|
348
|
+
publishedAt: text(metadata.publishedTime) ?? text(metadata["article:published_time"]),
|
|
349
|
+
raw,
|
|
350
|
+
rawHtml: text(data.rawHtml),
|
|
351
|
+
screenshot: text(data.screenshot),
|
|
352
|
+
statusCode: num(metadata.statusCode),
|
|
353
|
+
summary: text(data.summary),
|
|
354
|
+
title: firstText(metadata.title),
|
|
355
|
+
url: text(metadata.url) ?? text(metadata.sourceURL) ?? fallbackUrl
|
|
356
|
+
});
|
|
357
|
+
};
|
|
358
|
+
const price = (value) => {
|
|
359
|
+
const item = record(value);
|
|
360
|
+
const result = compact({
|
|
361
|
+
amount: text(item.amount) ?? num(item.amount)?.toString(),
|
|
362
|
+
currency: text(item.currency),
|
|
363
|
+
formatted: text(item.formatted)
|
|
29
364
|
});
|
|
30
|
-
|
|
31
|
-
|
|
365
|
+
return Object.keys(result).length > 0 ? result : void 0;
|
|
366
|
+
};
|
|
367
|
+
const gtin = (variant) => {
|
|
368
|
+
for (const key of [
|
|
369
|
+
"gtin",
|
|
370
|
+
"gtin14",
|
|
371
|
+
"gtin13",
|
|
372
|
+
"gtin12",
|
|
373
|
+
"gtin8"
|
|
374
|
+
]) {
|
|
375
|
+
const value = scalar(variant[key]);
|
|
376
|
+
if (value) return value;
|
|
377
|
+
}
|
|
378
|
+
};
|
|
379
|
+
const toVariant = (value) => {
|
|
32
380
|
const variant = record(value);
|
|
33
|
-
const
|
|
34
|
-
const values = record(variant.values)
|
|
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
|
+
}));
|
|
35
386
|
return compact({
|
|
387
|
+
availability: text(availability.text),
|
|
388
|
+
gtin: gtin(variant),
|
|
36
389
|
id: text(variant.id),
|
|
390
|
+
images: productImages(variant.images),
|
|
391
|
+
inStock: typeof availability.inStock === "boolean" ? availability.inStock : void 0,
|
|
392
|
+
originalPrice: price(record(variant.sale).originalPrice),
|
|
393
|
+
price: price(variant.price),
|
|
37
394
|
sku: text(variant.sku),
|
|
38
395
|
title: text(variant.title),
|
|
39
|
-
values: Object.keys(values).length > 0 ?
|
|
40
|
-
price: variant.price ? compact({
|
|
41
|
-
amount: text(price.amount) ?? num(price.amount)?.toString(),
|
|
42
|
-
currency: text(price.currency)
|
|
43
|
-
}) : void 0,
|
|
44
|
-
inStock: typeof record(variant.availability).inStock === "boolean" ? record(variant.availability).inStock : void 0,
|
|
45
|
-
images: strings(variant.images)
|
|
396
|
+
values: Object.keys(values).length > 0 ? values : void 0
|
|
46
397
|
});
|
|
47
|
-
}
|
|
48
|
-
const
|
|
49
|
-
|
|
50
|
-
|
|
51
|
-
|
|
52
|
-
|
|
53
|
-
|
|
54
|
-
|
|
55
|
-
|
|
56
|
-
|
|
57
|
-
|
|
58
|
-
|
|
59
|
-
|
|
60
|
-
|
|
61
|
-
const
|
|
62
|
-
|
|
63
|
-
|
|
64
|
-
|
|
65
|
-
|
|
398
|
+
};
|
|
399
|
+
const allImages = (variants) => {
|
|
400
|
+
const seen = /* @__PURE__ */ new Map();
|
|
401
|
+
for (const image of variants.flatMap((variant) => variant.images ?? [])) if (!seen.has(image.url)) seen.set(image.url, image);
|
|
402
|
+
return seen.size > 0 ? [...seen.values()] : void 0;
|
|
403
|
+
};
|
|
404
|
+
const toProduct = (url, response, data) => {
|
|
405
|
+
if (!data.product) {
|
|
406
|
+
const why = text(data.warning) ?? text(response.warning);
|
|
407
|
+
throw new FieldworkError("NotFound", `firecrawl found no product on ${url}${why ? `: ${why}` : ""}`, {
|
|
408
|
+
cause: response,
|
|
409
|
+
provider
|
|
410
|
+
});
|
|
411
|
+
}
|
|
412
|
+
const product = record(data.product);
|
|
413
|
+
const variants = list(product.variants).map((variant) => toVariant(variant));
|
|
414
|
+
return compact({
|
|
415
|
+
brand: text(product.brand),
|
|
416
|
+
category: text(product.category),
|
|
417
|
+
description: text(product.description),
|
|
418
|
+
images: productImages(product.images) ?? allImages(variants),
|
|
419
|
+
meta: pageMeta(response, data),
|
|
420
|
+
raw: response,
|
|
421
|
+
title: text(product.title),
|
|
422
|
+
url: text(product.url),
|
|
423
|
+
variants
|
|
424
|
+
});
|
|
425
|
+
};
|
|
426
|
+
const searchItem = (item, kind) => {
|
|
427
|
+
const result = record(item);
|
|
428
|
+
return compact({
|
|
429
|
+
content: text(result.markdown),
|
|
430
|
+
image: text(result.imageUrl),
|
|
431
|
+
kind: text(result.category) ?? kind,
|
|
432
|
+
publishedAt: text(result.date),
|
|
433
|
+
snippet: text(result.description) ?? text(result.snippet),
|
|
434
|
+
title: text(result.title),
|
|
435
|
+
url: text(result.url) ?? ""
|
|
436
|
+
});
|
|
437
|
+
};
|
|
438
|
+
const paperItem = (item) => {
|
|
439
|
+
const paper = record(item);
|
|
440
|
+
const paperId = text(paper.paperId) ?? "";
|
|
441
|
+
const primary = text(paper.primaryId) ?? paperId;
|
|
442
|
+
const colon = primary.indexOf(":");
|
|
443
|
+
const resolve = colon > 0 ? PAPER_URLS.get(primary.slice(0, colon)) : void 0;
|
|
444
|
+
return compact({
|
|
445
|
+
kind: "research",
|
|
446
|
+
score: num(paper.score),
|
|
447
|
+
snippet: text(paper.abstract),
|
|
448
|
+
title: text(paper.title),
|
|
449
|
+
url: paperId.startsWith("web:") ? paperId.slice(4) : resolve?.(primary.slice(colon + 1)) ?? primary
|
|
450
|
+
});
|
|
451
|
+
};
|
|
452
|
+
const imageItems = (value) => list(value).flatMap((item) => {
|
|
453
|
+
const image = record(item);
|
|
454
|
+
const url = text(image.imageUrl);
|
|
455
|
+
return url ? [compact({
|
|
456
|
+
height: num(image.imageHeight),
|
|
457
|
+
sourceUrl: text(image.url),
|
|
458
|
+
title: text(image.title),
|
|
459
|
+
url,
|
|
460
|
+
width: num(image.imageWidth)
|
|
461
|
+
})] : [];
|
|
462
|
+
});
|
|
463
|
+
const searchMeta = (response) => meta({
|
|
464
|
+
credits: response.creditsUsed,
|
|
465
|
+
requestId: response.id,
|
|
466
|
+
warnings: warnings(response.warning, response.warnings)
|
|
467
|
+
});
|
|
468
|
+
const searchResult = (response) => {
|
|
469
|
+
const data = record(response.data);
|
|
470
|
+
return compact({
|
|
471
|
+
images: Array.isArray(data.images) ? imageItems(data.images) : void 0,
|
|
472
|
+
meta: searchMeta(response),
|
|
473
|
+
raw: response,
|
|
474
|
+
results: [
|
|
475
|
+
...list(data.web).map((item) => searchItem(item, "web")),
|
|
476
|
+
...list(data.news).map((item) => searchItem(item, "news")),
|
|
477
|
+
...list(data.research).map((item) => paperItem(item))
|
|
478
|
+
]
|
|
479
|
+
});
|
|
480
|
+
};
|
|
481
|
+
const imagesResult = (response) => compact({
|
|
482
|
+
meta: searchMeta(response),
|
|
483
|
+
raw: response,
|
|
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
|
+
};
|
|
492
|
+
});
|
|
493
|
+
const researchState = (id, status) => {
|
|
494
|
+
const state = text(status.status);
|
|
495
|
+
const hasPartial = status.partial !== void 0 && status.partial !== null;
|
|
496
|
+
const done = state === "completed" || state === "failed" && hasPartial;
|
|
497
|
+
if (!done && (state === "failed" || state === "cancelled")) throw new FieldworkError("JobFailed", `firecrawl research run ${id} ${state}: ${text(status.error) ?? text(status.stopReason) ?? "no reason given"}`, {
|
|
498
|
+
cause: status,
|
|
499
|
+
provider
|
|
500
|
+
});
|
|
501
|
+
return done ? status : void 0;
|
|
502
|
+
};
|
|
503
|
+
const researchResult = (id, started, run) => {
|
|
504
|
+
const stopped = run.status === "failed";
|
|
505
|
+
const status = stopped ? "partial" : "completed";
|
|
506
|
+
return compact({
|
|
507
|
+
continuationId: text(run.threadId) ?? text(started.threadId),
|
|
508
|
+
id,
|
|
509
|
+
meta: meta({
|
|
510
|
+
credits: run.creditsUsed,
|
|
511
|
+
requestId: id,
|
|
512
|
+
warnings: stopped ? [run.message, run.partialSchemaValid === false ? "the partial output does not match the schema" : void 0] : void 0
|
|
513
|
+
}),
|
|
514
|
+
output: stopped ? run.partial : run.data ?? run.message,
|
|
515
|
+
raw: run,
|
|
516
|
+
sources: [],
|
|
517
|
+
status,
|
|
518
|
+
stopReason: stopped ? text(run.stopReason) ?? text(run.error) ?? "failed" : void 0
|
|
519
|
+
});
|
|
520
|
+
};
|
|
521
|
+
const actResult = (result, sessionId, closed) => {
|
|
522
|
+
const stdout = text(result.stdout) ?? "";
|
|
523
|
+
const failure = result.success === false ? "firecrawl reported that the script did not succeed" : void 0;
|
|
524
|
+
const repeated = result.result === "" || result.result === null || result.result === stdout;
|
|
525
|
+
return compact({
|
|
526
|
+
error: text(result.error) ?? failure,
|
|
527
|
+
exitCode: num(result.exitCode),
|
|
528
|
+
killed: typeof result.killed === "boolean" ? result.killed : void 0,
|
|
529
|
+
meta: meta({ credits: closed?.creditsBilled }),
|
|
530
|
+
raw: result,
|
|
531
|
+
result: repeated ? void 0 : result.result,
|
|
532
|
+
sessionId,
|
|
533
|
+
stderr: text(result.stderr) ?? "",
|
|
534
|
+
stdout
|
|
535
|
+
});
|
|
536
|
+
};
|
|
537
|
+
const browserSession = (response) => compact({
|
|
538
|
+
cdpUrl: text(response.cdpUrl),
|
|
539
|
+
expiresAt: text(response.expiresAt),
|
|
540
|
+
id: requireId(provider, response.id),
|
|
541
|
+
liveViewUrl: text(response.liveViewUrl),
|
|
542
|
+
raw: response
|
|
543
|
+
});
|
|
544
|
+
const parseResult = (response) => {
|
|
545
|
+
const data = record(response.data);
|
|
546
|
+
const metadata = record(data.metadata);
|
|
547
|
+
return compact({
|
|
548
|
+
markdown: text(data.markdown) ?? "",
|
|
549
|
+
pages: Array.isArray(data.pages) ? list(data.pages).map((page) => ({
|
|
550
|
+
markdown: text(record(page).markdown) ?? "",
|
|
551
|
+
pageNumber: Number(record(page).pageNumber)
|
|
552
|
+
})) : void 0,
|
|
553
|
+
blocks: Array.isArray(data.blocks) ? data.blocks : void 0,
|
|
554
|
+
pageCount: num(metadata.totalPages) ?? num(metadata.numPages),
|
|
555
|
+
meta: pageMeta(response, data),
|
|
556
|
+
raw: response
|
|
557
|
+
});
|
|
558
|
+
};
|
|
559
|
+
const watching = (monitor) => {
|
|
560
|
+
const goal = text(monitor.goal);
|
|
561
|
+
if (goal) return goal;
|
|
562
|
+
return list(monitor.targets).map((item) => record(item)).flatMap((target) => {
|
|
563
|
+
if (target.type === "scrape") return strings(target.urls) ?? [];
|
|
564
|
+
if (target.type === "crawl") return [text(target.url)];
|
|
565
|
+
return strings(target.queries) ?? [];
|
|
566
|
+
}).filter((item) => item !== void 0).join(", ") || void 0;
|
|
567
|
+
};
|
|
568
|
+
const monitorInfo = (value) => {
|
|
569
|
+
const monitor = record(value);
|
|
570
|
+
const schedule = record(monitor.schedule);
|
|
571
|
+
return compact({
|
|
572
|
+
createdAt: text(monitor.createdAt),
|
|
573
|
+
id: requireId(provider, monitor.id),
|
|
574
|
+
raw: monitor,
|
|
575
|
+
schedule: text(schedule.cron) ?? text(schedule.text),
|
|
576
|
+
status: text(monitor.status),
|
|
577
|
+
watch: watching(monitor),
|
|
578
|
+
webhookUrl: text(record(monitor.webhook).url)
|
|
579
|
+
});
|
|
580
|
+
};
|
|
581
|
+
const checkEvent = (check) => {
|
|
582
|
+
const summary = record(check.summary);
|
|
583
|
+
const counts = [
|
|
584
|
+
"changed",
|
|
585
|
+
"new",
|
|
586
|
+
"removed",
|
|
587
|
+
"error"
|
|
588
|
+
].flatMap((key) => {
|
|
589
|
+
const count = num(summary[key]);
|
|
590
|
+
return count === void 0 ? [] : [`${count} ${key}`];
|
|
591
|
+
});
|
|
592
|
+
const pages = num(summary.totalPages);
|
|
593
|
+
const of = pages === void 0 ? "" : ` of ${pages} pages`;
|
|
594
|
+
return compact({
|
|
595
|
+
at: text(check.finishedAt) ?? text(check.startedAt) ?? text(check.scheduledFor) ?? text(check.createdAt),
|
|
596
|
+
id: text(check.id),
|
|
597
|
+
raw: check,
|
|
598
|
+
summary: [
|
|
599
|
+
text(check.status),
|
|
600
|
+
counts.length > 0 ? `${counts.join(", ")}${of}` : void 0,
|
|
601
|
+
text(check.error)
|
|
602
|
+
].filter((part) => part !== void 0).join(": ")
|
|
603
|
+
});
|
|
604
|
+
};
|
|
605
|
+
const monitorEvents = (response, offset) => {
|
|
606
|
+
const checks = list(response.data).map((item) => record(item));
|
|
607
|
+
return compact({
|
|
608
|
+
events: checks.map((check) => checkEvent(check)),
|
|
609
|
+
next: checks.length === 100 ? String(offset + checks.length) : void 0,
|
|
610
|
+
raw: response
|
|
611
|
+
});
|
|
612
|
+
};
|
|
613
|
+
const usageResult = (response) => {
|
|
614
|
+
const data = record(response.data);
|
|
615
|
+
return compact({
|
|
616
|
+
limit: num(data.planCredits),
|
|
617
|
+
periodEnd: text(data.billingPeriodEnd),
|
|
618
|
+
raw: response,
|
|
619
|
+
remaining: num(data.remainingCredits)
|
|
620
|
+
});
|
|
621
|
+
};
|
|
622
|
+
// src/adapters/firecrawl.ts
|
|
623
|
+
const firecrawl = (config = {}) => {
|
|
66
624
|
const baseUrl = config.baseUrl ?? "https://api.firecrawl.dev/v2";
|
|
67
625
|
const raw = createRawClient({
|
|
68
|
-
provider,
|
|
69
626
|
baseUrl,
|
|
627
|
+
fetch: config.fetch,
|
|
70
628
|
headers: { authorization: `Bearer ${requireKey(provider, config.apiKey, "FIRECRAWL_API_KEY")}` },
|
|
71
|
-
|
|
629
|
+
provider
|
|
72
630
|
});
|
|
73
|
-
async
|
|
631
|
+
const scrape = async (url, formats, settings, call) => {
|
|
74
632
|
const response = record(await raw.request("POST", "/scrape", {
|
|
75
633
|
...call,
|
|
76
634
|
body: {
|
|
77
|
-
url,
|
|
78
635
|
formats,
|
|
79
|
-
|
|
636
|
+
url,
|
|
637
|
+
...pageBody(settings)
|
|
80
638
|
}
|
|
81
639
|
}));
|
|
82
640
|
return {
|
|
83
|
-
response,
|
|
84
|
-
|
|
641
|
+
data: record(response.data),
|
|
642
|
+
response
|
|
85
643
|
};
|
|
86
|
-
}
|
|
644
|
+
};
|
|
645
|
+
const pathOf = (link) => {
|
|
646
|
+
const next = new URL(link);
|
|
647
|
+
const base = new URL(baseUrl).pathname.replace(/\/$/u, "");
|
|
648
|
+
return next.pathname.slice(base.length) + next.search;
|
|
649
|
+
};
|
|
650
|
+
const finished = async (kind, id, call, interval) => {
|
|
651
|
+
const path = `/${kind}/${segment(id)}`;
|
|
652
|
+
const get = async (to) => {
|
|
653
|
+
try {
|
|
654
|
+
return record(await raw.request("GET", to, { signal: call.signal }));
|
|
655
|
+
} catch (error) {
|
|
656
|
+
throw withJob(error, id);
|
|
657
|
+
}
|
|
658
|
+
};
|
|
659
|
+
const first = await poll(provider, id, async () => {
|
|
660
|
+
const status = record(await raw.request("GET", path, { signal: call.signal }));
|
|
661
|
+
const state = text(status.status);
|
|
662
|
+
if (state === "failed" || state === "cancelled") throw new FieldworkError("JobFailed", `firecrawl ${kind} ${id} ended ${state}`, {
|
|
663
|
+
cause: status,
|
|
664
|
+
provider
|
|
665
|
+
});
|
|
666
|
+
return state === "completed" ? status : void 0;
|
|
667
|
+
}, {
|
|
668
|
+
...call,
|
|
669
|
+
interval
|
|
670
|
+
});
|
|
671
|
+
const batches = [first];
|
|
672
|
+
let next = text(first.next);
|
|
673
|
+
while (next) {
|
|
674
|
+
const batch = await get(pathOf(next));
|
|
675
|
+
batches.push(batch);
|
|
676
|
+
next = text(batch.next);
|
|
677
|
+
}
|
|
678
|
+
const errors = await get(`${path}/errors`);
|
|
679
|
+
return {
|
|
680
|
+
batches,
|
|
681
|
+
errors,
|
|
682
|
+
failed: failedPages(errors),
|
|
683
|
+
first
|
|
684
|
+
};
|
|
685
|
+
};
|
|
686
|
+
const openSession = async (o, call) => {
|
|
687
|
+
const response = record(await raw.request("POST", "/interact", {
|
|
688
|
+
body: sessionBody(o),
|
|
689
|
+
signal: call.signal
|
|
690
|
+
}));
|
|
691
|
+
return {
|
|
692
|
+
id: requireId(provider, response.id),
|
|
693
|
+
response
|
|
694
|
+
};
|
|
695
|
+
};
|
|
696
|
+
const closeQuietly = async (id, call) => {
|
|
697
|
+
try {
|
|
698
|
+
return record(await raw.request("DELETE", `/interact/${segment(id)}`, { signal: call.signal }));
|
|
699
|
+
} catch {
|
|
700
|
+
return null;
|
|
701
|
+
}
|
|
702
|
+
};
|
|
87
703
|
return defineAdapter({
|
|
88
704
|
name: provider,
|
|
89
705
|
operations: {
|
|
90
|
-
async
|
|
706
|
+
async act(code, options) {
|
|
91
707
|
const { call, rest: o } = callSettings(options);
|
|
92
|
-
const
|
|
93
|
-
|
|
94
|
-
|
|
95
|
-
|
|
96
|
-
|
|
97
|
-
|
|
98
|
-
|
|
99
|
-
|
|
100
|
-
|
|
101
|
-
|
|
102
|
-
|
|
103
|
-
|
|
104
|
-
scrapeOptions: o.content ? { formats: ["markdown"] } : void 0
|
|
105
|
-
})
|
|
106
|
-
}));
|
|
107
|
-
const data = record(response.data);
|
|
108
|
-
return {
|
|
109
|
-
results: [...list(data.web), ...list(data.news)].map((item) => {
|
|
110
|
-
const result = record(item);
|
|
111
|
-
return compact({
|
|
112
|
-
url: text(result.url) ?? "",
|
|
113
|
-
title: text(result.title),
|
|
114
|
-
snippet: text(result.description) ?? text(result.snippet),
|
|
115
|
-
content: text(result.markdown),
|
|
116
|
-
publishedAt: text(result.date)
|
|
117
|
-
});
|
|
118
|
-
}),
|
|
119
|
-
raw: response
|
|
120
|
-
};
|
|
708
|
+
const seconds = checkAct(o, call.timeout);
|
|
709
|
+
const created = o.session === void 0;
|
|
710
|
+
const keep = o.keepSession ?? !created;
|
|
711
|
+
const { id } = o.session === void 0 ? await openSession(o, call) : { id: o.session };
|
|
712
|
+
try {
|
|
713
|
+
const result = record(await raw.request("POST", `/interact/${segment(id)}/execute`, scriptRequest(code, o.language, call, seconds)));
|
|
714
|
+
const closed = keep ? null : await closeQuietly(id, call);
|
|
715
|
+
return actResult(result, keep ? id : void 0, closed);
|
|
716
|
+
} catch (error) {
|
|
717
|
+
if (created || !keep) await closeQuietly(id, call);
|
|
718
|
+
throw error;
|
|
719
|
+
}
|
|
121
720
|
},
|
|
122
|
-
|
|
721
|
+
browser: {
|
|
722
|
+
async close(id, options) {
|
|
723
|
+
const { call } = callSettings(options);
|
|
724
|
+
await raw.request("DELETE", `/interact/${segment(id)}`, call);
|
|
725
|
+
},
|
|
726
|
+
async open(options) {
|
|
727
|
+
const { call, rest: o } = callSettings(options);
|
|
728
|
+
const { response } = await openSession(o, call);
|
|
729
|
+
return browserSession(response);
|
|
730
|
+
}
|
|
731
|
+
},
|
|
732
|
+
async crawl(url, options) {
|
|
123
733
|
const { call, rest: o } = callSettings(options);
|
|
124
|
-
const
|
|
125
|
-
|
|
126
|
-
|
|
734
|
+
const id = o.resume ?? requireId("firecrawl", record(await raw.request("POST", "/crawl", {
|
|
735
|
+
...call,
|
|
736
|
+
body: crawlBody(url, o)
|
|
737
|
+
})).id);
|
|
738
|
+
const job = await finished("crawl", id, call, o.interval);
|
|
739
|
+
return compact({
|
|
740
|
+
failed: job.failed,
|
|
741
|
+
id,
|
|
742
|
+
meta: meta({
|
|
743
|
+
credits: job.first.creditsUsed,
|
|
744
|
+
requestId: id
|
|
745
|
+
}),
|
|
746
|
+
pages: job.batches.flatMap((batch) => list(batch.data).map((item) => toPage(record(item), url, item))),
|
|
747
|
+
raw: {
|
|
748
|
+
batches: job.batches,
|
|
749
|
+
errors: job.errors
|
|
750
|
+
},
|
|
751
|
+
robotsBlocked: strings(job.errors.robotsBlocked),
|
|
752
|
+
total: num(job.first.total)
|
|
753
|
+
});
|
|
127
754
|
},
|
|
128
755
|
async extract(url, options) {
|
|
129
756
|
const { call, rest: o } = callSettings(options);
|
|
130
757
|
const { schema, prompt, ...page } = o;
|
|
131
758
|
const { response, data } = await scrape(url, [compact({
|
|
132
|
-
|
|
759
|
+
prompt,
|
|
133
760
|
schema,
|
|
134
|
-
|
|
761
|
+
type: "json"
|
|
135
762
|
})], page, call);
|
|
136
|
-
if (data.json === void 0)
|
|
137
|
-
|
|
138
|
-
|
|
139
|
-
|
|
140
|
-
|
|
763
|
+
if (data.json === void 0) {
|
|
764
|
+
const why = text(data.warning);
|
|
765
|
+
throw new FieldworkError("ProviderError", `firecrawl returned no JSON for ${url}${why ? `: ${why}` : ""}`, {
|
|
766
|
+
cause: response,
|
|
767
|
+
provider
|
|
768
|
+
});
|
|
769
|
+
}
|
|
770
|
+
return compact({
|
|
141
771
|
data: data.json,
|
|
772
|
+
meta: pageMeta(response, data),
|
|
142
773
|
raw: response
|
|
143
|
-
};
|
|
774
|
+
});
|
|
144
775
|
},
|
|
145
|
-
async
|
|
776
|
+
async images(query, options) {
|
|
146
777
|
const { call, rest: o } = callSettings(options);
|
|
147
|
-
const
|
|
148
|
-
|
|
149
|
-
|
|
150
|
-
|
|
151
|
-
|
|
152
|
-
const product = record(data.product);
|
|
153
|
-
return compact({
|
|
154
|
-
title: text(product.title),
|
|
155
|
-
brand: text(product.brand),
|
|
156
|
-
category: text(product.category),
|
|
157
|
-
description: text(product.description),
|
|
158
|
-
url: text(product.url),
|
|
159
|
-
variants: list(product.variants).map((variant) => toVariant(variant)),
|
|
160
|
-
raw: response
|
|
161
|
-
});
|
|
778
|
+
const response = record(await raw.request("POST", "/search", {
|
|
779
|
+
...call,
|
|
780
|
+
body: imagesBody(query, o)
|
|
781
|
+
}));
|
|
782
|
+
return imagesResult(response);
|
|
162
783
|
},
|
|
163
784
|
async map(url, options) {
|
|
164
785
|
const { call, rest: o } = callSettings(options);
|
|
165
786
|
const response = record(await raw.request("POST", "/map", {
|
|
166
787
|
...call,
|
|
167
|
-
body:
|
|
168
|
-
url,
|
|
169
|
-
...o
|
|
170
|
-
})
|
|
788
|
+
body: mapBody(url, o)
|
|
171
789
|
}));
|
|
172
790
|
return {
|
|
173
791
|
links: list(response.links).map((item) => {
|
|
174
792
|
if (typeof item === "string") return { url: item };
|
|
175
793
|
const link = record(item);
|
|
176
794
|
return compact({
|
|
177
|
-
|
|
795
|
+
description: text(link.description),
|
|
178
796
|
title: text(link.title),
|
|
179
|
-
|
|
797
|
+
url: text(link.url) ?? ""
|
|
180
798
|
});
|
|
181
799
|
}),
|
|
182
800
|
raw: response
|
|
183
801
|
};
|
|
184
802
|
},
|
|
185
|
-
|
|
186
|
-
|
|
187
|
-
|
|
188
|
-
|
|
189
|
-
|
|
190
|
-
|
|
191
|
-
url,
|
|
192
|
-
...body
|
|
193
|
-
})
|
|
194
|
-
})).id);
|
|
195
|
-
const first = await poll(provider, id, async () => {
|
|
196
|
-
const status = record(await raw.request("GET", `/crawl/${id}`, { signal: call.signal }));
|
|
197
|
-
if (status.status === "failed" || status.status === "cancelled") throw new FieldworkError("JobFailed", `firecrawl crawl ${id} ended ${text(status.status) ?? "unknown"}`, {
|
|
198
|
-
provider,
|
|
199
|
-
cause: status
|
|
200
|
-
});
|
|
201
|
-
return status.status === "completed" ? status : void 0;
|
|
202
|
-
}, {
|
|
203
|
-
...call,
|
|
204
|
-
interval
|
|
205
|
-
});
|
|
206
|
-
const batches = [first];
|
|
207
|
-
let next = text(first.next);
|
|
208
|
-
while (next) {
|
|
209
|
-
const nextUrl = new URL(next);
|
|
210
|
-
const path = nextUrl.pathname.slice(new URL(baseUrl).pathname.replace(/\/$/u, "").length) + nextUrl.search;
|
|
211
|
-
const batch = record(await raw.request("GET", path, { signal: call.signal }).catch((error) => {
|
|
212
|
-
throw withJob(error, id);
|
|
803
|
+
monitor: {
|
|
804
|
+
async create(options) {
|
|
805
|
+
const { call, rest: o } = callSettings(options);
|
|
806
|
+
const response = record(await raw.request("POST", "/monitor", {
|
|
807
|
+
...call,
|
|
808
|
+
body: monitorBody(o)
|
|
213
809
|
}));
|
|
214
|
-
|
|
215
|
-
|
|
810
|
+
return monitorInfo(response.data);
|
|
811
|
+
},
|
|
812
|
+
async delete(id, options) {
|
|
813
|
+
const { call } = callSettings(options);
|
|
814
|
+
await raw.request("DELETE", `/monitor/${segment(id)}`, call);
|
|
815
|
+
},
|
|
816
|
+
async events(id, options) {
|
|
817
|
+
const { call, rest: o } = callSettings(options);
|
|
818
|
+
const offset = Number(o.cursor ?? 0);
|
|
819
|
+
if (!Number.isInteger(offset) || offset < 0) throw invalid(`firecrawl events cursor "${o.cursor}" is not valid`);
|
|
820
|
+
const response = record(await raw.request("GET", `/monitor/${segment(id)}/checks`, {
|
|
821
|
+
...call,
|
|
822
|
+
query: {
|
|
823
|
+
limit: 100,
|
|
824
|
+
offset
|
|
825
|
+
}
|
|
826
|
+
}));
|
|
827
|
+
return monitorEvents(response, offset);
|
|
828
|
+
},
|
|
829
|
+
async get(id, options) {
|
|
830
|
+
const { call } = callSettings(options);
|
|
831
|
+
const response = record(await raw.request("GET", `/monitor/${segment(id)}`, call));
|
|
832
|
+
return monitorInfo(response.data);
|
|
833
|
+
},
|
|
834
|
+
async list(options) {
|
|
835
|
+
const { call } = callSettings(options);
|
|
836
|
+
const monitors = [];
|
|
837
|
+
for (;;) {
|
|
838
|
+
const response = record(await raw.request("GET", "/monitor", {
|
|
839
|
+
...call,
|
|
840
|
+
query: {
|
|
841
|
+
limit: 100,
|
|
842
|
+
offset: monitors.length
|
|
843
|
+
}
|
|
844
|
+
}));
|
|
845
|
+
const page = list(response.data);
|
|
846
|
+
monitors.push(...page.map((item) => monitorInfo(item)));
|
|
847
|
+
if (page.length < 100) return monitors;
|
|
848
|
+
}
|
|
216
849
|
}
|
|
217
|
-
return {
|
|
218
|
-
pages: batches.flatMap((batch) => list(batch.data).map((item) => toPage(record(item), url, item))),
|
|
219
|
-
raw: batches
|
|
220
|
-
};
|
|
221
850
|
},
|
|
222
|
-
async
|
|
851
|
+
async parse(document, options) {
|
|
223
852
|
const { call, rest: o } = callSettings(options);
|
|
224
|
-
const
|
|
225
|
-
const
|
|
226
|
-
...call,
|
|
227
|
-
body: compact({
|
|
228
|
-
prompt: question,
|
|
229
|
-
...body
|
|
230
|
-
})
|
|
231
|
-
})).id);
|
|
232
|
-
const run = await poll(provider, id, async () => {
|
|
233
|
-
const status = record(await raw.request("GET", `/agent/${id}`, { signal: call.signal }));
|
|
234
|
-
if (status.status === "failed") throw new FieldworkError("JobFailed", `firecrawl research run ${id} failed: ${text(status.error) ?? "no reason given"}`, {
|
|
235
|
-
provider,
|
|
236
|
-
cause: status
|
|
237
|
-
});
|
|
238
|
-
return status.status === "completed" ? status : void 0;
|
|
239
|
-
}, {
|
|
853
|
+
const form = parseForm(document, o);
|
|
854
|
+
const response = record(await raw.request("POST", "/parse", {
|
|
240
855
|
...call,
|
|
241
|
-
|
|
242
|
-
});
|
|
243
|
-
return
|
|
244
|
-
id,
|
|
245
|
-
output: run.data,
|
|
246
|
-
sources: [],
|
|
247
|
-
raw: run
|
|
248
|
-
};
|
|
856
|
+
form
|
|
857
|
+
}));
|
|
858
|
+
return parseResult(response);
|
|
249
859
|
},
|
|
250
|
-
async
|
|
860
|
+
async product(url, options) {
|
|
251
861
|
const { call, rest: o } = callSettings(options);
|
|
252
|
-
const
|
|
862
|
+
const { response, data } = await scrape(url, ["product"], o, call);
|
|
863
|
+
return toProduct(url, response, data);
|
|
864
|
+
},
|
|
865
|
+
async read(url, options) {
|
|
866
|
+
const { call, rest: o } = callSettings(options);
|
|
867
|
+
const { response, data } = await scrape(url, readFormats(o), o, call);
|
|
868
|
+
return presentPage(provider, toPage(data, url, response, response));
|
|
869
|
+
},
|
|
870
|
+
async readMany(urls, options) {
|
|
871
|
+
const { call, rest: o } = callSettings(options);
|
|
872
|
+
const { interval, resume, maxConcurrency, ignoreInvalidURLs, ...read } = o;
|
|
873
|
+
const started = resume === void 0 ? record(await raw.request("POST", "/batch/scrape", {
|
|
253
874
|
...call,
|
|
254
875
|
body: compact({
|
|
255
|
-
|
|
256
|
-
|
|
257
|
-
|
|
876
|
+
urls,
|
|
877
|
+
...readBody(read),
|
|
878
|
+
maxConcurrency,
|
|
879
|
+
ignoreInvalidURLs
|
|
258
880
|
})
|
|
881
|
+
})) : {};
|
|
882
|
+
const id = resume ?? requireId("firecrawl", started.id);
|
|
883
|
+
const job = await finished("batch/scrape", id, call, interval);
|
|
884
|
+
const rejected = (strings(started.invalidURLs) ?? []).map((url) => ({
|
|
885
|
+
error: "invalid URL",
|
|
886
|
+
url
|
|
259
887
|
}));
|
|
260
|
-
const
|
|
261
|
-
|
|
262
|
-
|
|
263
|
-
...
|
|
264
|
-
|
|
265
|
-
|
|
266
|
-
|
|
267
|
-
|
|
268
|
-
|
|
269
|
-
|
|
270
|
-
|
|
271
|
-
|
|
272
|
-
|
|
273
|
-
|
|
274
|
-
|
|
275
|
-
|
|
276
|
-
|
|
277
|
-
|
|
278
|
-
|
|
279
|
-
}
|
|
888
|
+
const { pages, gone } = presentPages(job.batches.flatMap((batch) => list(batch.data).map((item) => toPage(record(item), "", item))));
|
|
889
|
+
return compact({
|
|
890
|
+
failed: [
|
|
891
|
+
...job.failed,
|
|
892
|
+
...rejected,
|
|
893
|
+
...gone
|
|
894
|
+
],
|
|
895
|
+
id,
|
|
896
|
+
meta: meta({
|
|
897
|
+
credits: job.first.creditsUsed,
|
|
898
|
+
requestId: id
|
|
899
|
+
}),
|
|
900
|
+
pages,
|
|
901
|
+
raw: {
|
|
902
|
+
batches: job.batches,
|
|
903
|
+
errors: job.errors,
|
|
904
|
+
started
|
|
905
|
+
}
|
|
906
|
+
});
|
|
280
907
|
},
|
|
281
|
-
async
|
|
908
|
+
async research(question, options) {
|
|
282
909
|
const { call, rest: o } = callSettings(options);
|
|
283
|
-
const
|
|
284
|
-
|
|
285
|
-
|
|
286
|
-
|
|
287
|
-
|
|
288
|
-
|
|
910
|
+
const started = o.resume === void 0 ? record(await raw.request("POST", "/agent", {
|
|
911
|
+
...call,
|
|
912
|
+
body: researchBody(question, o)
|
|
913
|
+
})) : {};
|
|
914
|
+
const id = o.resume ?? requireId("firecrawl", started.id);
|
|
915
|
+
const run = await poll(provider, id, async () => researchState(id, record(await raw.request("GET", `/agent/${segment(id)}`, { signal: call.signal }))), {
|
|
916
|
+
...call,
|
|
917
|
+
interval: o.interval
|
|
289
918
|
});
|
|
290
|
-
|
|
291
|
-
|
|
292
|
-
|
|
293
|
-
|
|
294
|
-
|
|
295
|
-
form.set("file", toBlob(document.data, document.name), document.name);
|
|
296
|
-
const response = record(await raw.request("POST", "/parse", {
|
|
919
|
+
return researchResult(id, started, run);
|
|
920
|
+
},
|
|
921
|
+
async search(query, options) {
|
|
922
|
+
const { call, rest: o } = callSettings(options);
|
|
923
|
+
const response = record(await raw.request("POST", "/search", {
|
|
297
924
|
...call,
|
|
298
|
-
|
|
925
|
+
body: searchBody(query, o)
|
|
299
926
|
}));
|
|
300
|
-
|
|
301
|
-
|
|
302
|
-
|
|
303
|
-
|
|
304
|
-
|
|
305
|
-
markdown: text(record(page).markdown) ?? ""
|
|
306
|
-
})) : void 0,
|
|
307
|
-
blocks: Array.isArray(data.blocks) ? data.blocks : void 0,
|
|
308
|
-
raw: response
|
|
309
|
-
});
|
|
927
|
+
return searchResult(response);
|
|
928
|
+
},
|
|
929
|
+
async usage(options) {
|
|
930
|
+
const { call } = callSettings(options);
|
|
931
|
+
return usageResult(record(await raw.request("GET", "/team/credit-usage", call)));
|
|
310
932
|
}
|
|
311
933
|
},
|
|
312
934
|
raw
|
|
313
935
|
});
|
|
314
|
-
}
|
|
936
|
+
};
|
|
315
937
|
export { firecrawl };
|