@howells/fieldwork-sdk 0.4.0 → 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 +34 -31
- package/dist/{adapter-CDY8qczv.d.ts → adapter-BgdfLBs-.d.ts} +85 -3
- package/dist/adapter-DWYJys20.js +8 -0
- package/dist/brave.d.ts +6 -1
- package/dist/brave.js +34 -14
- package/dist/browserbase.d.ts +8 -4
- package/dist/browserbase.js +16 -14
- package/dist/document-Dpj01mGx.js +51 -0
- package/dist/{errors-BiIBG9zN.js → errors-Yvk42oZH.js} +3 -1
- package/dist/exa.d.ts +7 -2
- package/dist/exa.js +31 -24
- package/dist/{fieldwork-DTNVIOzp.d.ts → fieldwork-CXNIcqSN.d.ts} +7 -1
- package/dist/firecrawl.d.ts +7 -2
- package/dist/firecrawl.js +114 -74
- package/dist/index.d.ts +5 -4
- package/dist/index.js +10 -4
- package/dist/llamaparse.d.ts +58 -0
- package/dist/llamaparse.js +286 -0
- package/dist/parallel.d.ts +7 -2
- package/dist/parallel.js +46 -40
- package/dist/{parse-CxOri73y.js → parse-D4SMt-Ip.js} +99 -30
- package/dist/perplexity.d.ts +16 -11
- package/dist/perplexity.js +145 -142
- package/dist/reducto.d.ts +31 -0
- package/dist/reducto.js +220 -0
- package/dist/{schema-EZlBkY5B.d.ts → schema-Cupy7-7q.d.ts} +1 -1
- package/dist/{schema-teOy7Od-.js → schema-DbSIABP0.js} +1 -1
- package/dist/serpapi.d.ts +6 -1
- package/dist/serpapi.js +17 -13
- package/dist/tavily.d.ts +7 -2
- package/dist/tavily.js +28 -24
- package/dist/tools.d.ts +5 -2
- package/dist/tools.js +62 -12
- package/package.json +14 -2
- package/dist/adapter-CEAQuT7F.js +0 -3
|
@@ -0,0 +1,51 @@
|
|
|
1
|
+
import { t as FieldworkError } from "./errors-Yvk42oZH.js";
|
|
2
|
+
// src/document.ts
|
|
3
|
+
/** Content types of the document files parsers commonly take, by extension. */
|
|
4
|
+
const MEDIA_TYPES = new Map(Object.entries({
|
|
5
|
+
csv: "text/csv",
|
|
6
|
+
doc: "application/msword",
|
|
7
|
+
docm: "application/vnd.ms-word.document.macroEnabled.12",
|
|
8
|
+
docx: "application/vnd.openxmlformats-officedocument.wordprocessingml.document",
|
|
9
|
+
epub: "application/epub+zip",
|
|
10
|
+
htm: "text/html",
|
|
11
|
+
html: "text/html",
|
|
12
|
+
odp: "application/vnd.oasis.opendocument.presentation",
|
|
13
|
+
ods: "application/vnd.oasis.opendocument.spreadsheet",
|
|
14
|
+
odt: "application/vnd.oasis.opendocument.text",
|
|
15
|
+
pdf: "application/pdf",
|
|
16
|
+
ppt: "application/vnd.ms-powerpoint",
|
|
17
|
+
pptm: "application/vnd.ms-powerpoint.presentation.macroEnabled.12",
|
|
18
|
+
pptx: "application/vnd.openxmlformats-officedocument.presentationml.presentation",
|
|
19
|
+
rtf: "application/rtf",
|
|
20
|
+
xhtml: "application/xhtml+xml",
|
|
21
|
+
xls: "application/vnd.ms-excel",
|
|
22
|
+
xlsb: "application/vnd.ms-excel.sheet.binary.macroEnabled.12",
|
|
23
|
+
xlsm: "application/vnd.ms-excel.sheet.macroEnabled.12",
|
|
24
|
+
xlsx: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"
|
|
25
|
+
}));
|
|
26
|
+
/** The content type the file's extension names, or undefined for one not listed. */
|
|
27
|
+
const mediaTypeOf = (name) => MEDIA_TYPES.get(name.split(".").pop()?.toLowerCase() ?? "");
|
|
28
|
+
/** Refuses a file larger than the provider takes, before it is sent. */
|
|
29
|
+
const refuseLarger = (provider, document, maxMegabytes) => {
|
|
30
|
+
const size = document.data instanceof Blob ? document.data.size : document.data.byteLength;
|
|
31
|
+
if (size > maxMegabytes * 1024 * 1024) throw new FieldworkError("InvalidRequest", `${provider} parses files up to ${maxMegabytes} MB; ${document.name} is ${(size / 1024 / 1024).toFixed(1)} MB`, { provider });
|
|
32
|
+
};
|
|
33
|
+
/** The file's bytes as a multipart part, with the content type its extension names. */
|
|
34
|
+
const documentPart = (document) => {
|
|
35
|
+
const part = document.data instanceof Uint8Array ? new Uint8Array(document.data) : document.data;
|
|
36
|
+
return new Blob([part], { type: mediaTypeOf(document.name) ?? "application/octet-stream" });
|
|
37
|
+
};
|
|
38
|
+
/** The smallest box that holds every one of `boxes`, or undefined when there are none. */
|
|
39
|
+
const enclosing = (boxes) => {
|
|
40
|
+
if (boxes.length <= 1) return boxes[0];
|
|
41
|
+
const left = Math.min(...boxes.map((box) => box.left));
|
|
42
|
+
const top = Math.min(...boxes.map((box) => box.top));
|
|
43
|
+
const right = Math.max(...boxes.map((box) => box.left + box.width));
|
|
44
|
+
return {
|
|
45
|
+
height: Math.max(...boxes.map((box) => box.top + box.height)) - top,
|
|
46
|
+
left,
|
|
47
|
+
top,
|
|
48
|
+
width: right - left
|
|
49
|
+
};
|
|
50
|
+
};
|
|
51
|
+
export { refuseLarger as a, mediaTypeOf as i, documentPart as n, enclosing as r, MEDIA_TYPES as t };
|
|
@@ -62,4 +62,6 @@ const codeForStatus = (status) => {
|
|
|
62
62
|
if (status === 400 || status === 422) return "InvalidRequest";
|
|
63
63
|
return "ProviderError";
|
|
64
64
|
};
|
|
65
|
-
|
|
65
|
+
/** A request refused before it is sent, with the provider's name leading the message. */
|
|
66
|
+
const invalidRequest = (provider, message) => new FieldworkError("InvalidRequest", `${provider} ${message}`, { provider });
|
|
67
|
+
export { withJob as i, codeForStatus as n, invalidRequest as r, FieldworkError as t };
|
package/dist/exa.d.ts
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import {
|
|
2
|
-
import { t as OutputSchema } from "./schema-
|
|
1
|
+
import { E as Extraction, F as MonitorEvents, I as MonitorInfo, L as MonitorSchedule, R as Page, Y as SearchResponse, a as RawClient, l as Answer, p as CallOptions, q as Research, t as Adapter, z as PageBatch } from "./adapter-BgdfLBs-.js";
|
|
2
|
+
import { t as OutputSchema } from "./schema-Cupy7-7q.js";
|
|
3
3
|
interface ExaConfig {
|
|
4
4
|
/** Defaults to the EXA_API_KEY environment variable. */
|
|
5
5
|
apiKey?: string;
|
|
@@ -191,5 +191,10 @@ interface ExaOperations {
|
|
|
191
191
|
research: <T = unknown>(question: string, options?: ExaResearchOptions<T>) => Promise<Research<T>>;
|
|
192
192
|
monitor: ExaMonitor;
|
|
193
193
|
}
|
|
194
|
+
/**
|
|
195
|
+
* An adapter for Exa: search, read, readMany, extract, answer, research and monitor. Pass it to `new Fieldwork({ adapter })`.
|
|
196
|
+
*
|
|
197
|
+
* Throws `Unauthorized` when neither `apiKey` nor `EXA_API_KEY` is set.
|
|
198
|
+
*/
|
|
194
199
|
export declare const exa: (config?: ExaConfig) => Adapter<"exa", ExaOperations, RawClient>;
|
|
195
200
|
export type { ExaAnswerOptions, ExaConfig, ExaExtractOptions, ExaHighlightOptions, ExaMonitor, ExaMonitorCreateOptions, ExaMonitorEventsOptions, ExaOperations, ExaOutputSchema, ExaReadManyOptions, ExaReadOptions, ExaResearchOptions, ExaSearchOptions, ExaWebhookEvent };
|
package/dist/exa.js
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
|
-
import { t as defineAdapter } from "./adapter-
|
|
2
|
-
import { t as FieldworkError } from "./errors-
|
|
3
|
-
import { A as
|
|
4
|
-
import { n as jsonSchemaOf, t as checkOutput } from "./schema-
|
|
1
|
+
import { t as defineAdapter } from "./adapter-DWYJys20.js";
|
|
2
|
+
import { r as invalidRequest, t as FieldworkError } from "./errors-Yvk42oZH.js";
|
|
3
|
+
import { A as citationsOf, B as uniqueCitations, C as createRawClient, D as segment, E as requireKey, L as record, M as hours, N as meta, O as callSettings, P as parseJson, S as withOriginal, _ as optionalStructure, a as looseObject, b as warningEntry, d as optionalId, f as optionalNumber, g as optionalStringOrNumber, h as optionalString, i as both, j as compact, l as optionalBoolean, m as optionalScalar, n as anything, r as arrayOf, s as optionalAnyString, t as Source, w as poll, z as requireJobId } from "./parse-D4SMt-Ip.js";
|
|
4
|
+
import { n as jsonSchemaOf, t as checkOutput } from "./schema-DbSIABP0.js";
|
|
5
5
|
import * as z from "zod/mini";
|
|
6
6
|
const DATE_ONLY = /^\d{4}-\d{2}-\d{2}$/u;
|
|
7
7
|
const DEEP_TYPES = /* @__PURE__ */ new Set([
|
|
@@ -9,9 +9,6 @@ const DEEP_TYPES = /* @__PURE__ */ new Set([
|
|
|
9
9
|
"deep",
|
|
10
10
|
"deep-reasoning"
|
|
11
11
|
]);
|
|
12
|
-
const invalid = (message) => {
|
|
13
|
-
throw new FieldworkError("InvalidRequest", `exa ${message}`, { provider: "exa" });
|
|
14
|
-
};
|
|
15
12
|
const dateTime = (value, endOfDay) => {
|
|
16
13
|
if (value === void 0 || !DATE_ONLY.test(value)) return value;
|
|
17
14
|
return endOfDay ? `${value}T23:59:59.999Z` : `${value}T00:00:00.000Z`;
|
|
@@ -37,12 +34,12 @@ const checkSearch = (o) => {
|
|
|
37
34
|
"summary",
|
|
38
35
|
"maxAge"
|
|
39
36
|
].filter((name) => o[name] !== void 0);
|
|
40
|
-
if (unsupported.length > 0)
|
|
37
|
+
if (unsupported.length > 0) throw invalidRequest("exa", `search type "lite" does not accept ${unsupported.join(", ")}`);
|
|
41
38
|
}
|
|
42
|
-
if (o.additionalQueries !== void 0 && !DEEP_TYPES.has(o.type ?? ""))
|
|
39
|
+
if (o.additionalQueries !== void 0 && !DEEP_TYPES.has(o.type ?? "")) throw invalidRequest("exa", "additionalQueries needs search type \"deep-lite\", \"deep\" or \"deep-reasoning\"");
|
|
43
40
|
const dated = o.publishedAfter !== void 0 || o.publishedBefore !== void 0;
|
|
44
|
-
if ((o.category === "company" || o.category === "people") && dated)
|
|
45
|
-
if (o.category === "people" && o.excludeDomains !== void 0)
|
|
41
|
+
if ((o.category === "company" || o.category === "people") && dated) throw invalidRequest("exa", `category "${o.category}" does not accept publishedAfter or publishedBefore`);
|
|
42
|
+
if (o.category === "people" && o.excludeDomains !== void 0) throw invalidRequest("exa", "category \"people\" does not accept excludeDomains");
|
|
46
43
|
};
|
|
47
44
|
const highlightsOption = (highlights) => typeof highlights === "object" ? compact({
|
|
48
45
|
maxCharacters: highlights.maxCharacters,
|
|
@@ -129,8 +126,8 @@ const runMeta = (run) => {
|
|
|
129
126
|
};
|
|
130
127
|
const checkResearch = (o) => {
|
|
131
128
|
const effort = o.effort ?? "auto";
|
|
132
|
-
if (o.maxCostDollars !== void 0 && effort !== "auto" && effort !== "ultra")
|
|
133
|
-
if (o.maxDurationSeconds !== void 0 && effort !== "ultra")
|
|
129
|
+
if (o.maxCostDollars !== void 0 && effort !== "auto" && effort !== "ultra") throw invalidRequest("exa", `maxCostDollars needs effort "auto" or "ultra", not "${effort}"`);
|
|
130
|
+
if (o.maxDurationSeconds !== void 0 && effort !== "ultra") throw invalidRequest("exa", `maxDurationSeconds needs effort "ultra", not "${effort}"`);
|
|
134
131
|
};
|
|
135
132
|
const researchBody = (question, o) => {
|
|
136
133
|
const budget = compact({
|
|
@@ -185,12 +182,12 @@ const researchResult = (id, entry, structured) => {
|
|
|
185
182
|
};
|
|
186
183
|
const intervalPeriod = (schedule) => {
|
|
187
184
|
const { every } = record(schedule);
|
|
188
|
-
if (typeof every !== "string")
|
|
185
|
+
if (typeof every !== "string") throw invalidRequest("exa", "monitors run on an interval of whole hours or days; Exa has no cron");
|
|
189
186
|
let value = every;
|
|
190
187
|
if (every === "hour") value = "1h";
|
|
191
188
|
else if (every === "day") value = "1d";
|
|
192
189
|
else if (every === "week") value = "7d";
|
|
193
|
-
if (!/^[1-9]\d*[hd]$/u.test(value))
|
|
190
|
+
if (!/^[1-9]\d*[hd]$/u.test(value)) throw invalidRequest("exa", `monitor schedule "${every}" is not whole hours or days, at least 1h`);
|
|
194
191
|
return value;
|
|
195
192
|
};
|
|
196
193
|
const period = (schedule) => schedule === void 0 ? void 0 : intervalPeriod(schedule);
|
|
@@ -358,6 +355,11 @@ const RunsPage = looseObject({
|
|
|
358
355
|
nextCursor: optionalString
|
|
359
356
|
});
|
|
360
357
|
// src/adapters/exa.ts
|
|
358
|
+
/**
|
|
359
|
+
* An adapter for Exa: search, read, readMany, extract, answer, research and monitor. Pass it to `new Fieldwork({ adapter })`.
|
|
360
|
+
*
|
|
361
|
+
* Throws `Unauthorized` when neither `apiKey` nor `EXA_API_KEY` is set.
|
|
362
|
+
*/
|
|
361
363
|
const exa = (config = {}) => {
|
|
362
364
|
const raw = createRawClient({
|
|
363
365
|
baseUrl: config.baseUrl ?? "https://api.exa.ai",
|
|
@@ -417,9 +419,14 @@ const exa = (config = {}) => {
|
|
|
417
419
|
})
|
|
418
420
|
});
|
|
419
421
|
const body = z.parse(AnswerResponse, response);
|
|
420
|
-
const { structure } = body.answer;
|
|
422
|
+
const { structure, text } = body.answer;
|
|
423
|
+
const answer = structure === void 0 ? text : JSON.stringify(structure);
|
|
424
|
+
if (answer === void 0 || answer === "") throw new FieldworkError("ProviderError", "exa returned no answer text", {
|
|
425
|
+
cause: response,
|
|
426
|
+
provider: "exa"
|
|
427
|
+
});
|
|
421
428
|
return compact({
|
|
422
|
-
answer
|
|
429
|
+
answer,
|
|
423
430
|
citations: uniqueCitations(citationsOf(body.citations)),
|
|
424
431
|
meta: responseMeta(body),
|
|
425
432
|
output: structure === void 0 ? void 0 : await checkOutput(o.schema, structure, { provider: "exa" }),
|
|
@@ -478,11 +485,11 @@ const exa = (config = {}) => {
|
|
|
478
485
|
},
|
|
479
486
|
async delete(id, options) {
|
|
480
487
|
const { call } = callSettings(options);
|
|
481
|
-
await raw.request("DELETE", `/monitors/${
|
|
488
|
+
await raw.request("DELETE", `/monitors/${segment(id)}`, call);
|
|
482
489
|
},
|
|
483
490
|
async events(id, options) {
|
|
484
491
|
const { call, rest: o } = callSettings(options);
|
|
485
|
-
const response = await raw.request("GET", `/monitors/${
|
|
492
|
+
const response = await raw.request("GET", `/monitors/${segment(id)}/runs`, {
|
|
486
493
|
...call,
|
|
487
494
|
query: {
|
|
488
495
|
cursor: o.cursor,
|
|
@@ -498,7 +505,7 @@ const exa = (config = {}) => {
|
|
|
498
505
|
},
|
|
499
506
|
async get(id, options) {
|
|
500
507
|
const { call } = callSettings(options);
|
|
501
|
-
return monitorInfo(z.parse(MonitorEntry, await raw.request("GET", `/monitors/${
|
|
508
|
+
return monitorInfo(z.parse(MonitorEntry, await raw.request("GET", `/monitors/${segment(id)}`, call)));
|
|
502
509
|
},
|
|
503
510
|
async list(options) {
|
|
504
511
|
const { call } = callSettings(options);
|
|
@@ -531,8 +538,8 @@ const exa = (config = {}) => {
|
|
|
531
538
|
},
|
|
532
539
|
async readMany(urls, options) {
|
|
533
540
|
const { call, rest: o } = callSettings(options);
|
|
534
|
-
if (urls.length === 0)
|
|
535
|
-
if (urls.length > 100)
|
|
541
|
+
if (urls.length === 0) throw invalidRequest("exa", "readMany needs at least one URL");
|
|
542
|
+
if (urls.length > 100) throw invalidRequest("exa", `readMany reads at most 100 URLs per call`);
|
|
536
543
|
const { body, response } = await fetchContents(urls, readBody(o), call);
|
|
537
544
|
return {
|
|
538
545
|
failed: failedStatuses(body.statuses).map((status) => ({
|
|
@@ -555,8 +562,8 @@ const exa = (config = {}) => {
|
|
|
555
562
|
...call,
|
|
556
563
|
body: researchBody(question, o)
|
|
557
564
|
})).id);
|
|
558
|
-
const run = await poll("exa", id, async () => {
|
|
559
|
-
const current = z.parse(RunEntry, await raw.request("GET", `/agent/runs/${
|
|
565
|
+
const run = await poll("exa", id, async (request) => {
|
|
566
|
+
const current = z.parse(RunEntry, await raw.request("GET", `/agent/runs/${segment(id)}`, request));
|
|
560
567
|
const { status } = current.value;
|
|
561
568
|
return status === "completed" || status === "failed" || status === "cancelled" ? current : void 0;
|
|
562
569
|
}, {
|
|
@@ -1,4 +1,5 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import { m as Capability, n as AnyAdapter } from "./adapter-BgdfLBs-.js";
|
|
2
|
+
/** Why a call failed. Branch on this, not on the message, which can change. */
|
|
2
3
|
type FieldworkErrorCode =
|
|
3
4
|
/** The adapter's provider does not offer this capability. */
|
|
4
5
|
"Unsupported" |
|
|
@@ -74,5 +75,10 @@ interface FieldworkBase<A extends AnyAdapter> {
|
|
|
74
75
|
* Tavily has no browser.
|
|
75
76
|
*/
|
|
76
77
|
type Fieldwork<A extends AnyAdapter> = FieldworkBase<A> & Readonly<A["operations"]>;
|
|
78
|
+
/**
|
|
79
|
+
* The client: `new Fieldwork({ adapter })` has exactly the methods its adapter offers.
|
|
80
|
+
*
|
|
81
|
+
* Check `supports` or `capabilities` before calling dynamically; a capability the provider lacks throws `Unsupported`.
|
|
82
|
+
*/
|
|
77
83
|
declare const Fieldwork: new <A extends AnyAdapter>(options: FieldworkOptions<A>) => Fieldwork<A>;
|
|
78
84
|
export { FieldworkErrorCode as i, FieldworkOptions as n, FieldworkError as r, Fieldwork as t };
|
package/dist/firecrawl.d.ts
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import {
|
|
2
|
-
import { t as OutputSchema } from "./schema-
|
|
1
|
+
import { B as ParsedDocument, C as DocumentInput, E as Extraction, F as MonitorEvents, I as MonitorInfo, K as Recency, L as MonitorSchedule, Q as SiteMap, R as Page, U as Product, Y as SearchResponse, _ as Crawl, a as RawClient, c as ActResult, d as BrowserSession, j as ImageSearch, p as CallOptions, q as Research, s as AccountUsage, t as Adapter, z as PageBatch } from "./adapter-BgdfLBs-.js";
|
|
2
|
+
import { t as OutputSchema } from "./schema-Cupy7-7q.js";
|
|
3
3
|
interface FirecrawlConfig {
|
|
4
4
|
/** Defaults to the FIRECRAWL_API_KEY environment variable. */
|
|
5
5
|
apiKey?: string;
|
|
@@ -321,5 +321,10 @@ interface FirecrawlOperations {
|
|
|
321
321
|
};
|
|
322
322
|
usage: (options?: CallOptions) => Promise<AccountUsage>;
|
|
323
323
|
}
|
|
324
|
+
/**
|
|
325
|
+
* 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 })`.
|
|
326
|
+
*
|
|
327
|
+
* Throws `Unauthorized` when neither `apiKey` nor `FIRECRAWL_API_KEY` is set.
|
|
328
|
+
*/
|
|
324
329
|
export declare const firecrawl: (config?: FirecrawlConfig) => Adapter<"firecrawl", FirecrawlOperations, RawClient>;
|
|
325
330
|
export type { FirecrawlActOptions, FirecrawlAction, FirecrawlBrowserOptions, FirecrawlConfig, FirecrawlCrawlOptions, FirecrawlExtractOptions, FirecrawlFormat, FirecrawlImagesOptions, FirecrawlMapOptions, FirecrawlMonitorOptions, FirecrawlOperations, FirecrawlPageOptions, FirecrawlPageSettings, FirecrawlParseOptions, FirecrawlParser, FirecrawlPdfParser, FirecrawlReadManyOptions, FirecrawlReadOptions, FirecrawlReadSettings, FirecrawlResearchOptions, FirecrawlSearchOptions, FirecrawlSessionSettings };
|
package/dist/firecrawl.js
CHANGED
|
@@ -1,12 +1,11 @@
|
|
|
1
|
-
import { t as defineAdapter } from "./adapter-
|
|
2
|
-
import {
|
|
3
|
-
import { C as createRawClient, E as
|
|
4
|
-
import { n as jsonSchemaOf, t as checkOutput } from "./schema-
|
|
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";
|
|
5
6
|
import * as z from "zod/mini";
|
|
6
7
|
// src/adapters/firecrawl/shared.ts
|
|
7
8
|
const provider = "firecrawl";
|
|
8
|
-
const invalid = (message) => new FieldworkError("InvalidRequest", message, { provider });
|
|
9
|
-
const segment = (id) => encodeURIComponent(id);
|
|
10
9
|
const country = (code) => code?.toUpperCase();
|
|
11
10
|
// src/adapters/firecrawl/schedule.ts
|
|
12
11
|
/** The fewest minutes Firecrawl allows between two checks of a monitor. */
|
|
@@ -46,11 +45,11 @@ const runGaps = (minutes, hours) => {
|
|
|
46
45
|
};
|
|
47
46
|
const checkCron = (cron) => {
|
|
48
47
|
const fields = cron.trim().split(/\s+/u);
|
|
49
|
-
if (fields.length !== 5) throw
|
|
48
|
+
if (fields.length !== 5) throw invalidRequest(provider, `needs a five-field cron expression, got "${cron}"`);
|
|
50
49
|
const [minuteField = "", hourField = ""] = fields;
|
|
51
50
|
const minutes = cronValues(minuteField, 59);
|
|
52
51
|
const hours = cronValues(hourField, 23);
|
|
53
|
-
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}"`);
|
|
54
53
|
return cron.trim();
|
|
55
54
|
};
|
|
56
55
|
const hourlyCron = (count) => {
|
|
@@ -67,39 +66,19 @@ const cronFor = (schedule) => {
|
|
|
67
66
|
const count = Number(groups?.count);
|
|
68
67
|
const cron = groups?.unit === "h" ? hourlyCron(count) : DAILY_CRON.get(count);
|
|
69
68
|
if (cron !== void 0) return cron;
|
|
70
|
-
throw
|
|
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`);
|
|
71
70
|
};
|
|
72
71
|
// src/adapters/firecrawl/request.ts
|
|
73
|
-
/** The largest file `/parse` takes. */
|
|
74
|
-
const
|
|
72
|
+
/** The largest file `/parse` takes, in megabytes. */
|
|
73
|
+
const MAX_PARSE_MB = 50;
|
|
75
74
|
/** Longest script `/interact/{id}/execute` runs, in seconds. */
|
|
76
75
|
const MAX_SCRIPT_SECONDS = 300;
|
|
77
|
-
/**
|
|
78
|
-
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;
|
|
79
80
|
/** The longest query a search monitor takes. */
|
|
80
81
|
const MAX_MONITOR_QUERY = 256;
|
|
81
|
-
const MEDIA_TYPES = new Map(Object.entries({
|
|
82
|
-
csv: "text/csv",
|
|
83
|
-
doc: "application/msword",
|
|
84
|
-
docm: "application/vnd.ms-word.document.macroEnabled.12",
|
|
85
|
-
docx: "application/vnd.openxmlformats-officedocument.wordprocessingml.document",
|
|
86
|
-
epub: "application/epub+zip",
|
|
87
|
-
htm: "text/html",
|
|
88
|
-
html: "text/html",
|
|
89
|
-
odp: "application/vnd.oasis.opendocument.presentation",
|
|
90
|
-
ods: "application/vnd.oasis.opendocument.spreadsheet",
|
|
91
|
-
odt: "application/vnd.oasis.opendocument.text",
|
|
92
|
-
pdf: "application/pdf",
|
|
93
|
-
ppt: "application/vnd.ms-powerpoint",
|
|
94
|
-
pptm: "application/vnd.ms-powerpoint.presentation.macroEnabled.12",
|
|
95
|
-
pptx: "application/vnd.openxmlformats-officedocument.presentationml.presentation",
|
|
96
|
-
rtf: "application/rtf",
|
|
97
|
-
xhtml: "application/xhtml+xml",
|
|
98
|
-
xls: "application/vnd.ms-excel",
|
|
99
|
-
xlsb: "application/vnd.ms-excel.sheet.binary.macroEnabled.12",
|
|
100
|
-
xlsm: "application/vnd.ms-excel.sheet.macroEnabled.12",
|
|
101
|
-
xlsx: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"
|
|
102
|
-
}));
|
|
103
82
|
const RECENCY = {
|
|
104
83
|
day: "d",
|
|
105
84
|
hour: "h",
|
|
@@ -140,7 +119,7 @@ const readBody = (o) => ({
|
|
|
140
119
|
});
|
|
141
120
|
const usDate = (value) => {
|
|
142
121
|
const groups = DATE.exec(value)?.groups;
|
|
143
|
-
if (!groups) throw
|
|
122
|
+
if (!groups) throw invalidRequest(provider, `needs dates as YYYY-MM-DD, got "${value}"`);
|
|
144
123
|
return `${groups.month}/${groups.day}/${groups.year}`;
|
|
145
124
|
};
|
|
146
125
|
const timeFilter = (o) => {
|
|
@@ -157,7 +136,7 @@ const timeFilter = (o) => {
|
|
|
157
136
|
};
|
|
158
137
|
const searchBody = (query, o) => {
|
|
159
138
|
refuseTogether(provider, o, "includeDomains", "excludeDomains");
|
|
160
|
-
if (o.categories?.includes("gov") === true && 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");
|
|
161
140
|
return compact({
|
|
162
141
|
categories: o.categories?.map((type) => ({ type })),
|
|
163
142
|
country: country(o.country),
|
|
@@ -234,7 +213,7 @@ const checkAct = (o, timeout) => {
|
|
|
234
213
|
]) refuseTogether(provider, o, "session", name);
|
|
235
214
|
if (timeout === void 0) return;
|
|
236
215
|
const seconds = Math.max(1, Math.ceil(timeout / 1e3));
|
|
237
|
-
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`);
|
|
238
217
|
return seconds;
|
|
239
218
|
};
|
|
240
219
|
const scriptRequest = (code, language, call, seconds) => ({
|
|
@@ -243,15 +222,14 @@ const scriptRequest = (code, language, call, seconds) => ({
|
|
|
243
222
|
language: language ?? "node",
|
|
244
223
|
timeout: seconds
|
|
245
224
|
}),
|
|
225
|
+
retries: call.retries,
|
|
246
226
|
signal: call.signal,
|
|
247
|
-
timeout: call.timeout === void 0 ? void 0 : call.timeout +
|
|
227
|
+
timeout: call.timeout === void 0 ? void 0 : call.timeout + REPORT_GRACE_MS
|
|
248
228
|
});
|
|
249
|
-
const parseForm = (document, o) => {
|
|
250
|
-
|
|
251
|
-
|
|
252
|
-
|
|
253
|
-
const size = document.data instanceof Blob ? document.data.size : document.data.byteLength;
|
|
254
|
-
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);
|
|
255
233
|
const parser = compact({
|
|
256
234
|
blocks: o.blocks,
|
|
257
235
|
maxPages: o.maxPages,
|
|
@@ -261,12 +239,12 @@ const parseForm = (document, o) => {
|
|
|
261
239
|
type: "pdf"
|
|
262
240
|
});
|
|
263
241
|
const form = new FormData();
|
|
264
|
-
form.set("options", JSON.stringify({
|
|
242
|
+
form.set("options", JSON.stringify(compact({
|
|
265
243
|
formats: ["markdown"],
|
|
266
|
-
parsers: [parser]
|
|
267
|
-
|
|
268
|
-
|
|
269
|
-
form.set("file",
|
|
244
|
+
parsers: [parser],
|
|
245
|
+
timeout
|
|
246
|
+
})));
|
|
247
|
+
form.set("file", documentPart(document), document.name);
|
|
270
248
|
return form;
|
|
271
249
|
};
|
|
272
250
|
const monitorTarget = (o) => {
|
|
@@ -277,14 +255,14 @@ const monitorTarget = (o) => {
|
|
|
277
255
|
o.excludeDomains
|
|
278
256
|
].some((value) => value !== void 0);
|
|
279
257
|
if (o.urls && o.urls.length > 0) {
|
|
280
|
-
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");
|
|
281
259
|
return {
|
|
282
260
|
type: "scrape",
|
|
283
261
|
urls: o.urls
|
|
284
262
|
};
|
|
285
263
|
}
|
|
286
|
-
if (o.query === void 0 || o.query === "") throw
|
|
287
|
-
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`);
|
|
288
266
|
return compact({
|
|
289
267
|
excludeDomains: o.excludeDomains,
|
|
290
268
|
includeDomains: o.includeDomains,
|
|
@@ -495,7 +473,7 @@ const researchResult = (id, started, entry) => {
|
|
|
495
473
|
stopReason: stopped ? run.stopReason ?? run.error ?? "failed" : void 0
|
|
496
474
|
});
|
|
497
475
|
};
|
|
498
|
-
const actResult = (entry, sessionId,
|
|
476
|
+
const actResult = (entry, sessionId, close) => {
|
|
499
477
|
const result = entry.value;
|
|
500
478
|
const stdout = result.stdout ?? "";
|
|
501
479
|
const failure = result.success === false ? "firecrawl reported that the script did not succeed" : void 0;
|
|
@@ -504,7 +482,10 @@ const actResult = (entry, sessionId, closed) => {
|
|
|
504
482
|
error: result.error ?? failure,
|
|
505
483
|
exitCode: result.exitCode,
|
|
506
484
|
killed: result.killed,
|
|
507
|
-
meta: meta({
|
|
485
|
+
meta: meta({
|
|
486
|
+
credits: close.closed?.creditsBilled,
|
|
487
|
+
warnings: close.failure
|
|
488
|
+
}),
|
|
508
489
|
raw: entry.original,
|
|
509
490
|
result: repeated ? void 0 : result.result,
|
|
510
491
|
sessionId,
|
|
@@ -522,6 +503,25 @@ const browserSession = (entry) => {
|
|
|
522
503
|
raw: entry.original
|
|
523
504
|
});
|
|
524
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
|
+
});
|
|
524
|
+
});
|
|
525
525
|
/** A parsed document; the caller adds `raw`. */
|
|
526
526
|
const parseResult = (body) => {
|
|
527
527
|
const { data } = body;
|
|
@@ -531,7 +531,7 @@ const parseResult = (body) => {
|
|
|
531
531
|
markdown: page.markdown ?? "",
|
|
532
532
|
pageNumber: Number(page.pageNumber)
|
|
533
533
|
})),
|
|
534
|
-
blocks: data.blocks,
|
|
534
|
+
blocks: data.blocks && documentBlocks(data.blocks),
|
|
535
535
|
pageCount: data.metadata.totalPages ?? data.metadata.numPages,
|
|
536
536
|
meta: pageMeta(data, body.warning.notes)
|
|
537
537
|
});
|
|
@@ -837,10 +837,19 @@ const ChecksResponse = looseObject({ data: arrayOf(withOriginal(looseObject({
|
|
|
837
837
|
totalPages: optionalNumber
|
|
838
838
|
})
|
|
839
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
|
+
});
|
|
840
849
|
/** `/parse`. */
|
|
841
850
|
const ParseResponse = looseObject({
|
|
842
851
|
data: looseObject({
|
|
843
|
-
blocks: optionalArrayOf(
|
|
852
|
+
blocks: optionalArrayOf(ParsePage),
|
|
844
853
|
markdown: optionalString,
|
|
845
854
|
metadata: looseObject(metadataShape),
|
|
846
855
|
pages: optionalArrayOf(looseObject({
|
|
@@ -858,6 +867,13 @@ const UsageResponse = looseObject({ data: looseObject({
|
|
|
858
867
|
remainingCredits: optionalNumber
|
|
859
868
|
}) });
|
|
860
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
|
+
*/
|
|
861
877
|
const firecrawl = (config = {}) => {
|
|
862
878
|
const baseUrl = config.baseUrl ?? "https://api.firecrawl.dev/v2";
|
|
863
879
|
const raw = createRawClient({
|
|
@@ -892,13 +908,13 @@ const firecrawl = (config = {}) => {
|
|
|
892
908
|
const path = `/${kind}/${segment(id)}`;
|
|
893
909
|
const get = async (schema, to) => {
|
|
894
910
|
try {
|
|
895
|
-
return z.parse(schema, await raw.request("GET", to,
|
|
911
|
+
return z.parse(schema, await raw.request("GET", to, call));
|
|
896
912
|
} catch (error) {
|
|
897
913
|
throw withJob(error, id);
|
|
898
914
|
}
|
|
899
915
|
};
|
|
900
|
-
const first = await poll(provider, id, async () => {
|
|
901
|
-
const status = z.parse(Batch, await raw.request("GET", path,
|
|
916
|
+
const first = await poll(provider, id, async (request) => {
|
|
917
|
+
const status = z.parse(Batch, await raw.request("GET", path, request));
|
|
902
918
|
const state = status.value.status;
|
|
903
919
|
if (state === "failed" || state === "cancelled") throw new FieldworkError("JobFailed", `firecrawl ${kind} ${id} ended ${state}`, {
|
|
904
920
|
cause: status.original,
|
|
@@ -928,6 +944,7 @@ const firecrawl = (config = {}) => {
|
|
|
928
944
|
const session = z.parse(Session, await raw.request("POST", "/interact", {
|
|
929
945
|
body: sessionBody(o),
|
|
930
946
|
creates: true,
|
|
947
|
+
retries: call.retries,
|
|
931
948
|
signal: call.signal
|
|
932
949
|
}));
|
|
933
950
|
return {
|
|
@@ -935,18 +952,33 @@ const firecrawl = (config = {}) => {
|
|
|
935
952
|
session
|
|
936
953
|
};
|
|
937
954
|
};
|
|
938
|
-
|
|
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) => {
|
|
939
962
|
try {
|
|
940
|
-
return
|
|
941
|
-
|
|
942
|
-
|
|
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
|
+
};
|
|
943
975
|
}
|
|
944
976
|
};
|
|
945
977
|
return defineAdapter({
|
|
946
978
|
name: provider,
|
|
947
979
|
operations: {
|
|
948
980
|
async act(code, options) {
|
|
949
|
-
const { call, rest: o } = callSettings(options);
|
|
981
|
+
const { call, rest: o } = callSettings(options, REPORT_GRACE_MS);
|
|
950
982
|
const seconds = checkAct(o, call.timeout);
|
|
951
983
|
const created = o.session === void 0;
|
|
952
984
|
const keep = o.keepSession ?? !created;
|
|
@@ -956,11 +988,18 @@ const firecrawl = (config = {}) => {
|
|
|
956
988
|
...scriptRequest(code, o.language, call, seconds),
|
|
957
989
|
creates: true
|
|
958
990
|
}));
|
|
959
|
-
|
|
960
|
-
|
|
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);
|
|
961
994
|
} catch (error) {
|
|
962
|
-
if (created
|
|
963
|
-
|
|
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
|
+
});
|
|
964
1003
|
}
|
|
965
1004
|
},
|
|
966
1005
|
browser: {
|
|
@@ -1062,7 +1101,7 @@ const firecrawl = (config = {}) => {
|
|
|
1062
1101
|
async events(id, options) {
|
|
1063
1102
|
const { call, rest: o } = callSettings(options);
|
|
1064
1103
|
const offset = Number(o.cursor ?? 0);
|
|
1065
|
-
if (!Number.isInteger(offset) || offset < 0) throw
|
|
1104
|
+
if (!Number.isInteger(offset) || offset < 0) throw invalidRequest(provider, `events cursor "${o.cursor}" is not valid`);
|
|
1066
1105
|
const response = await raw.request("GET", `/monitor/${segment(id)}/checks`, {
|
|
1067
1106
|
...call,
|
|
1068
1107
|
query: {
|
|
@@ -1097,11 +1136,12 @@ const firecrawl = (config = {}) => {
|
|
|
1097
1136
|
}
|
|
1098
1137
|
},
|
|
1099
1138
|
async parse(document, options) {
|
|
1100
|
-
const { call, rest: o } = callSettings(options);
|
|
1101
|
-
const form = parseForm(document, o);
|
|
1139
|
+
const { call, rest: o } = callSettings(options, REPORT_GRACE_MS);
|
|
1140
|
+
const form = parseForm(document, o, call.timeout);
|
|
1102
1141
|
const response = await raw.request("POST", "/parse", {
|
|
1103
1142
|
...call,
|
|
1104
|
-
form
|
|
1143
|
+
form,
|
|
1144
|
+
timeout: call.timeout === void 0 ? void 0 : call.timeout + REPORT_GRACE_MS
|
|
1105
1145
|
});
|
|
1106
1146
|
return {
|
|
1107
1147
|
...parseResult(z.parse(ParseResponse, response)),
|
|
@@ -1182,7 +1222,7 @@ const firecrawl = (config = {}) => {
|
|
|
1182
1222
|
body: researchBody(question, o)
|
|
1183
1223
|
}) : {});
|
|
1184
1224
|
const id = o.resume ?? requireJobId("firecrawl", started.value.id);
|
|
1185
|
-
const run = await poll(provider, id, async () => researchState(id, z.parse(AgentRun, await raw.request("GET", `/agent/${segment(id)}`,
|
|
1225
|
+
const run = await poll(provider, id, async (request) => researchState(id, z.parse(AgentRun, await raw.request("GET", `/agent/${segment(id)}`, request))), {
|
|
1186
1226
|
...call,
|
|
1187
1227
|
interval: o.interval
|
|
1188
1228
|
});
|