@howells/fieldwork-sdk 0.2.0 → 0.3.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 +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 +850 -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-CYenIQQT.js +265 -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/brave.js
ADDED
|
@@ -0,0 +1,399 @@
|
|
|
1
|
+
import { t as defineAdapter } from "./adapter-CEAQuT7F.js";
|
|
2
|
+
import { t as FieldworkError } from "./errors-BiIBG9zN.js";
|
|
3
|
+
import { b as requireKey, c as num, d as record, f as refuseTogether, g as text, i as compact, o as list, s as meta, t as callSettings, v as createRawClient } from "./util-CYenIQQT.js";
|
|
4
|
+
// src/adapters/brave/parse.ts
|
|
5
|
+
const provider = "brave";
|
|
6
|
+
const FRESHNESS = {
|
|
7
|
+
day: "pd",
|
|
8
|
+
month: "pm",
|
|
9
|
+
week: "pw",
|
|
10
|
+
year: "py"
|
|
11
|
+
};
|
|
12
|
+
const SHARED = [
|
|
13
|
+
"limit",
|
|
14
|
+
"country",
|
|
15
|
+
"language",
|
|
16
|
+
"recency",
|
|
17
|
+
"publishedAfter",
|
|
18
|
+
"publishedBefore",
|
|
19
|
+
"safesearch"
|
|
20
|
+
];
|
|
21
|
+
/** The provider options each search endpoint takes; any other is refused. */
|
|
22
|
+
const ALLOWED = {
|
|
23
|
+
context: [
|
|
24
|
+
...SHARED,
|
|
25
|
+
"content",
|
|
26
|
+
"maxTokens",
|
|
27
|
+
"maxTokensPerUrl",
|
|
28
|
+
"relevance",
|
|
29
|
+
"sourceMetadata",
|
|
30
|
+
"operators",
|
|
31
|
+
"goggles"
|
|
32
|
+
],
|
|
33
|
+
news: [
|
|
34
|
+
...SHARED,
|
|
35
|
+
"vertical",
|
|
36
|
+
"offset",
|
|
37
|
+
"extraSnippets",
|
|
38
|
+
"spellcheck",
|
|
39
|
+
"uiLanguage",
|
|
40
|
+
"operators",
|
|
41
|
+
"goggles"
|
|
42
|
+
],
|
|
43
|
+
videos: [
|
|
44
|
+
...SHARED,
|
|
45
|
+
"vertical",
|
|
46
|
+
"offset",
|
|
47
|
+
"spellcheck",
|
|
48
|
+
"uiLanguage",
|
|
49
|
+
"operators"
|
|
50
|
+
],
|
|
51
|
+
web: [
|
|
52
|
+
...SHARED,
|
|
53
|
+
"vertical",
|
|
54
|
+
"content",
|
|
55
|
+
"offset",
|
|
56
|
+
"resultTypes",
|
|
57
|
+
"extraSnippets",
|
|
58
|
+
"spellcheck",
|
|
59
|
+
"uiLanguage",
|
|
60
|
+
"units",
|
|
61
|
+
"operators",
|
|
62
|
+
"goggles",
|
|
63
|
+
"textDecorations"
|
|
64
|
+
]
|
|
65
|
+
};
|
|
66
|
+
const invalid = (message) => new FieldworkError("InvalidRequest", `brave ${message}`, { provider });
|
|
67
|
+
const modeOf = (o) => {
|
|
68
|
+
if (o.content === true) return "context";
|
|
69
|
+
if (o.vertical === void 0 || o.vertical === "web") return "web";
|
|
70
|
+
if (o.vertical === "news" || o.vertical === "videos") return o.vertical;
|
|
71
|
+
throw invalid(`has no "${o.vertical}" search; use web, news or videos`);
|
|
72
|
+
};
|
|
73
|
+
const refuseUnsupported = (mode, o) => {
|
|
74
|
+
const refused = Object.keys(o).filter((name) => o[name] !== void 0 && !ALLOWED[mode].includes(name));
|
|
75
|
+
if (refused.length > 0) throw invalid(`${mode} search does not accept ${refused.join(", ")}`);
|
|
76
|
+
};
|
|
77
|
+
const today = () => (/* @__PURE__ */ new Date()).toISOString().slice(0, 10);
|
|
78
|
+
const freshness = (o) => {
|
|
79
|
+
refuseTogether(provider, o, "recency", "publishedAfter");
|
|
80
|
+
refuseTogether(provider, o, "recency", "publishedBefore");
|
|
81
|
+
if (o.recency !== void 0) {
|
|
82
|
+
const window = FRESHNESS[o.recency];
|
|
83
|
+
if (!window) throw invalid(`has no "${o.recency}" recency window; use day, week, month or year`);
|
|
84
|
+
return window;
|
|
85
|
+
}
|
|
86
|
+
if (o.publishedBefore !== void 0 && o.publishedAfter === void 0) throw invalid("needs publishedAfter with publishedBefore: its date range has two ends");
|
|
87
|
+
if (o.publishedAfter === void 0) return;
|
|
88
|
+
const after = o.publishedAfter;
|
|
89
|
+
const before = o.publishedBefore ?? today();
|
|
90
|
+
for (const date of [after, before]) if (!/^\d{4}-\d{2}-\d{2}$/u.test(date)) throw invalid(`dates must be YYYY-MM-DD, got "${date}"`);
|
|
91
|
+
return `${after}to${before}`;
|
|
92
|
+
};
|
|
93
|
+
const gogglesOf = (value) => {
|
|
94
|
+
if (value === void 0) return;
|
|
95
|
+
const all = Array.isArray(value) ? value : [value];
|
|
96
|
+
if (all.length > 3) throw invalid("accepts at most 3 goggles per search");
|
|
97
|
+
return all;
|
|
98
|
+
};
|
|
99
|
+
const withQuery = (path, params) => {
|
|
100
|
+
const search = new URLSearchParams();
|
|
101
|
+
for (const [key, value] of Object.entries(params)) {
|
|
102
|
+
if (value === void 0) continue;
|
|
103
|
+
for (const item of Array.isArray(value) ? value : [value]) search.append(key, String(item));
|
|
104
|
+
}
|
|
105
|
+
const query = search.toString();
|
|
106
|
+
return query === "" ? path : `${path}?${query}`;
|
|
107
|
+
};
|
|
108
|
+
const upper = (value) => value?.toUpperCase();
|
|
109
|
+
const lower = (value) => value?.toLowerCase();
|
|
110
|
+
const warningsOf = (query) => {
|
|
111
|
+
const q = record(query);
|
|
112
|
+
const warnings = [];
|
|
113
|
+
const altered = text(q.altered);
|
|
114
|
+
if (altered !== void 0) warnings.push(`brave searched the spell-corrected query "${altered}"`);
|
|
115
|
+
if (q.show_strict_warning === true) warnings.push("strict safe search hid some results");
|
|
116
|
+
return warnings;
|
|
117
|
+
};
|
|
118
|
+
const result = (item, kind) => {
|
|
119
|
+
const r = record(item);
|
|
120
|
+
const url = text(r.url);
|
|
121
|
+
if (url === void 0) return;
|
|
122
|
+
const thumbnail = record(r.thumbnail);
|
|
123
|
+
const extra = list(r.extra_snippets).filter((s) => typeof s === "string" && s !== "");
|
|
124
|
+
const snippet = [text(r.description), ...extra].filter((s) => s !== void 0).join("\n\n");
|
|
125
|
+
return compact({
|
|
126
|
+
favicon: text(record(r.meta_url).favicon),
|
|
127
|
+
image: text(thumbnail.original) ?? text(thumbnail.src),
|
|
128
|
+
kind,
|
|
129
|
+
publishedAt: text(r.page_age),
|
|
130
|
+
snippet: snippet === "" ? void 0 : snippet,
|
|
131
|
+
title: text(r.title),
|
|
132
|
+
url
|
|
133
|
+
});
|
|
134
|
+
};
|
|
135
|
+
const placeResult = (item) => {
|
|
136
|
+
const base = result(item, "place");
|
|
137
|
+
if (!base) return;
|
|
138
|
+
const r = record(item);
|
|
139
|
+
const [latitude, longitude] = list(r.coordinates);
|
|
140
|
+
const place = compact({
|
|
141
|
+
address: text(record(r.postal_address).displayAddress),
|
|
142
|
+
latitude: num(latitude),
|
|
143
|
+
longitude: num(longitude)
|
|
144
|
+
});
|
|
145
|
+
const rating = record(r.rating);
|
|
146
|
+
return compact({
|
|
147
|
+
...base,
|
|
148
|
+
place: Object.keys(place).length > 0 ? place : void 0,
|
|
149
|
+
rating: num(rating.ratingValue),
|
|
150
|
+
reviewCount: num(rating.reviewCount)
|
|
151
|
+
});
|
|
152
|
+
};
|
|
153
|
+
const section = (response, name, map) => list(record(response[name]).results).map((item) => map(item)).filter((item) => item !== void 0);
|
|
154
|
+
const contextResult = (item, kind, sources) => {
|
|
155
|
+
const r = record(item);
|
|
156
|
+
const url = text(r.url);
|
|
157
|
+
if (url === void 0) return;
|
|
158
|
+
const source = record(sources[url]);
|
|
159
|
+
const passages = list(r.snippets).filter((s) => typeof s === "string" && s !== "");
|
|
160
|
+
return compact({
|
|
161
|
+
content: passages.length > 0 ? passages.join("\n\n") : void 0,
|
|
162
|
+
favicon: text(source.favicon),
|
|
163
|
+
image: text(source.thumbnail),
|
|
164
|
+
kind,
|
|
165
|
+
snippet: text(source.description),
|
|
166
|
+
title: text(r.title) ?? text(r.name) ?? text(source.title),
|
|
167
|
+
url
|
|
168
|
+
});
|
|
169
|
+
};
|
|
170
|
+
const parseContext = (response) => {
|
|
171
|
+
const grounding = record(response.grounding);
|
|
172
|
+
const sources = record(response.sources);
|
|
173
|
+
const poi = record(grounding.poi);
|
|
174
|
+
return [
|
|
175
|
+
...list(grounding.generic).map((item) => contextResult(item, "web", sources)),
|
|
176
|
+
...Object.keys(poi).length > 0 ? [contextResult(poi, "place", sources)] : [],
|
|
177
|
+
...list(grounding.map).map((item) => contextResult(item, "place", sources))
|
|
178
|
+
].filter((item) => item !== void 0);
|
|
179
|
+
};
|
|
180
|
+
const completionText = (response) => {
|
|
181
|
+
if (typeof response === "string") {
|
|
182
|
+
let content = "";
|
|
183
|
+
for (const line of response.split(/\r?\n/u)) {
|
|
184
|
+
if (!line.startsWith("data:")) continue;
|
|
185
|
+
const payload = line.slice(5).trim();
|
|
186
|
+
if (payload === "" || payload === "[DONE]") continue;
|
|
187
|
+
try {
|
|
188
|
+
for (const choice of list(record(JSON.parse(payload)).choices)) {
|
|
189
|
+
const delta = text(record(record(choice).delta).content);
|
|
190
|
+
content += delta ?? "";
|
|
191
|
+
}
|
|
192
|
+
} catch {}
|
|
193
|
+
}
|
|
194
|
+
return content;
|
|
195
|
+
}
|
|
196
|
+
const choice = record(list(record(response).choices)[0]);
|
|
197
|
+
return text(record(choice.message).content) ?? text(record(choice.delta).content) ?? "";
|
|
198
|
+
};
|
|
199
|
+
const CITATION_TAG = /<citation>(?<body>[\s\S]*?)<\/citation>/gu;
|
|
200
|
+
const USAGE_TAG = /<usage>(?<body>[\s\S]*?)<\/usage>/gu;
|
|
201
|
+
const tagJson = (body) => {
|
|
202
|
+
try {
|
|
203
|
+
let value = JSON.parse(body);
|
|
204
|
+
if (typeof value === "string") value = JSON.parse(value);
|
|
205
|
+
return record(value);
|
|
206
|
+
} catch {
|
|
207
|
+
return;
|
|
208
|
+
}
|
|
209
|
+
};
|
|
210
|
+
const tagBodies = (content, tag) => [...content.matchAll(tag)].map((match) => tagJson(match.groups?.body ?? "")).filter((item) => item !== void 0);
|
|
211
|
+
const answerCitations = (content) => {
|
|
212
|
+
const byUrl = /* @__PURE__ */ new Map();
|
|
213
|
+
for (const item of tagBodies(content, CITATION_TAG)) {
|
|
214
|
+
const url = text(item.url);
|
|
215
|
+
if (url === void 0) continue;
|
|
216
|
+
const excerpts = byUrl.get(url) ?? [];
|
|
217
|
+
const snippet = text(item.snippet);
|
|
218
|
+
if (snippet !== void 0 && !excerpts.includes(snippet)) excerpts.push(snippet);
|
|
219
|
+
byUrl.set(url, excerpts);
|
|
220
|
+
}
|
|
221
|
+
return [...byUrl].map(([url, excerpts]) => compact({
|
|
222
|
+
excerpts: excerpts.length > 0 ? excerpts : void 0,
|
|
223
|
+
url
|
|
224
|
+
}));
|
|
225
|
+
};
|
|
226
|
+
// src/adapters/brave.ts
|
|
227
|
+
const brave = (config = {}) => {
|
|
228
|
+
const raw = createRawClient({
|
|
229
|
+
baseUrl: config.baseUrl ?? "https://api.search.brave.com/res/v1",
|
|
230
|
+
fetch: config.fetch,
|
|
231
|
+
headers: { "X-Subscription-Token": requireKey(provider, config.apiKey, "BRAVE_API_KEY") },
|
|
232
|
+
provider
|
|
233
|
+
});
|
|
234
|
+
return defineAdapter({
|
|
235
|
+
name: provider,
|
|
236
|
+
operations: {
|
|
237
|
+
async answer(question, options) {
|
|
238
|
+
const { call, rest: o } = callSettings(options);
|
|
239
|
+
const location = compact({
|
|
240
|
+
city: o.userLocation?.city,
|
|
241
|
+
country: upper(o.userLocation?.country),
|
|
242
|
+
region: o.userLocation?.region,
|
|
243
|
+
timezone: o.userLocation?.timezone
|
|
244
|
+
});
|
|
245
|
+
const searchOptions = compact({
|
|
246
|
+
search_context_size: o.searchContextSize,
|
|
247
|
+
user_location: Object.keys(location).length > 0 ? {
|
|
248
|
+
approximate: location,
|
|
249
|
+
type: "approximate"
|
|
250
|
+
} : void 0
|
|
251
|
+
});
|
|
252
|
+
const response = await raw.request("POST", "/chat/completions", {
|
|
253
|
+
...call,
|
|
254
|
+
body: compact({
|
|
255
|
+
country: upper(o.country),
|
|
256
|
+
enable_citations: true,
|
|
257
|
+
language: lower(o.language),
|
|
258
|
+
max_completion_tokens: o.maxTokens,
|
|
259
|
+
messages: [{
|
|
260
|
+
content: question,
|
|
261
|
+
role: "user"
|
|
262
|
+
}],
|
|
263
|
+
model: o.model,
|
|
264
|
+
safesearch: o.safesearch,
|
|
265
|
+
stream: true,
|
|
266
|
+
web_search_options: Object.keys(searchOptions).length > 0 ? searchOptions : void 0
|
|
267
|
+
})
|
|
268
|
+
});
|
|
269
|
+
const content = completionText(response);
|
|
270
|
+
const answer = content.replace(CITATION_TAG, "").replace(USAGE_TAG, "").trim();
|
|
271
|
+
if (answer === "") throw new FieldworkError("ProviderError", "brave returned no answer text", {
|
|
272
|
+
cause: response,
|
|
273
|
+
provider
|
|
274
|
+
});
|
|
275
|
+
const usage = tagBodies(content, USAGE_TAG).at(-1) ?? {};
|
|
276
|
+
return compact({
|
|
277
|
+
answer,
|
|
278
|
+
citations: answerCitations(content),
|
|
279
|
+
meta: meta({
|
|
280
|
+
costUsd: usage["X-Request-Total-Cost"],
|
|
281
|
+
units: {
|
|
282
|
+
queries: usage["X-Request-Queries"],
|
|
283
|
+
requests: usage["X-Request-Requests"],
|
|
284
|
+
tokensIn: usage["X-Request-Tokens-In"],
|
|
285
|
+
tokensOut: usage["X-Request-Tokens-Out"]
|
|
286
|
+
}
|
|
287
|
+
}),
|
|
288
|
+
raw: response
|
|
289
|
+
});
|
|
290
|
+
},
|
|
291
|
+
async images(query, options) {
|
|
292
|
+
const { call, rest: o } = callSettings(options);
|
|
293
|
+
const response = record(await raw.request("GET", withQuery("/images/search", {
|
|
294
|
+
count: o.limit,
|
|
295
|
+
country: upper(o.country),
|
|
296
|
+
q: query,
|
|
297
|
+
safesearch: o.safesearch,
|
|
298
|
+
search_lang: lower(o.language),
|
|
299
|
+
spellcheck: o.spellcheck
|
|
300
|
+
}), call));
|
|
301
|
+
const results = [];
|
|
302
|
+
let withoutImage = 0;
|
|
303
|
+
for (const item of list(response.results)) {
|
|
304
|
+
const r = record(item);
|
|
305
|
+
const properties = record(r.properties);
|
|
306
|
+
const url = text(properties.url);
|
|
307
|
+
if (url === void 0) {
|
|
308
|
+
withoutImage += 1;
|
|
309
|
+
continue;
|
|
310
|
+
}
|
|
311
|
+
results.push(compact({
|
|
312
|
+
height: num(properties.height),
|
|
313
|
+
sourceUrl: text(r.url),
|
|
314
|
+
thumbnailUrl: text(record(r.thumbnail).src),
|
|
315
|
+
title: text(r.title),
|
|
316
|
+
url,
|
|
317
|
+
width: num(properties.width)
|
|
318
|
+
}));
|
|
319
|
+
}
|
|
320
|
+
const warnings = [...warningsOf(response.query), ...withoutImage > 0 ? [`${withoutImage} results had no image URL and were left out`] : []];
|
|
321
|
+
return compact({
|
|
322
|
+
meta: meta({ warnings }),
|
|
323
|
+
raw: response,
|
|
324
|
+
results
|
|
325
|
+
});
|
|
326
|
+
},
|
|
327
|
+
async search(query, options) {
|
|
328
|
+
const { call, rest } = callSettings(options);
|
|
329
|
+
const o = rest;
|
|
330
|
+
const mode = modeOf(o);
|
|
331
|
+
refuseUnsupported(mode, o);
|
|
332
|
+
const window = freshness(o);
|
|
333
|
+
const goggles = gogglesOf(o.goggles);
|
|
334
|
+
const shared = {
|
|
335
|
+
count: o.limit,
|
|
336
|
+
country: upper(o.country),
|
|
337
|
+
freshness: window,
|
|
338
|
+
goggles,
|
|
339
|
+
operators: o.operators,
|
|
340
|
+
q: query,
|
|
341
|
+
safesearch: o.safesearch,
|
|
342
|
+
search_lang: lower(o.language)
|
|
343
|
+
};
|
|
344
|
+
if (mode === "context") {
|
|
345
|
+
const response = record(await raw.request("GET", withQuery("/llm/context", {
|
|
346
|
+
...shared,
|
|
347
|
+
context_threshold_mode: o.relevance,
|
|
348
|
+
enable_source_metadata: o.sourceMetadata,
|
|
349
|
+
maximum_number_of_tokens: o.maxTokens,
|
|
350
|
+
maximum_number_of_tokens_per_url: o.maxTokensPerUrl,
|
|
351
|
+
maximum_number_of_urls: o.limit
|
|
352
|
+
}), call));
|
|
353
|
+
return compact({
|
|
354
|
+
raw: response,
|
|
355
|
+
results: parseContext(response)
|
|
356
|
+
});
|
|
357
|
+
}
|
|
358
|
+
if (mode === "news" || mode === "videos") {
|
|
359
|
+
const response = record(await raw.request("GET", withQuery(`/${mode}/search`, {
|
|
360
|
+
...shared,
|
|
361
|
+
extra_snippets: mode === "news" ? o.extraSnippets : void 0,
|
|
362
|
+
offset: o.offset,
|
|
363
|
+
spellcheck: o.spellcheck,
|
|
364
|
+
ui_lang: o.uiLanguage
|
|
365
|
+
}), call));
|
|
366
|
+
const kind = mode === "news" ? "news" : "video";
|
|
367
|
+
return compact({
|
|
368
|
+
meta: meta({ warnings: warningsOf(response.query) }),
|
|
369
|
+
raw: response,
|
|
370
|
+
results: list(response.results).map((item) => result(item, kind)).filter((item) => item !== void 0)
|
|
371
|
+
});
|
|
372
|
+
}
|
|
373
|
+
const response = record(await raw.request("GET", withQuery("/web/search", {
|
|
374
|
+
...shared,
|
|
375
|
+
extra_snippets: o.extraSnippets,
|
|
376
|
+
offset: o.offset,
|
|
377
|
+
result_filter: o.resultTypes?.join(","),
|
|
378
|
+
spellcheck: o.spellcheck,
|
|
379
|
+
text_decorations: o.textDecorations ?? false,
|
|
380
|
+
ui_lang: o.uiLanguage,
|
|
381
|
+
units: o.units
|
|
382
|
+
}), call));
|
|
383
|
+
return compact({
|
|
384
|
+
meta: meta({ warnings: warningsOf(response.query) }),
|
|
385
|
+
raw: response,
|
|
386
|
+
results: [
|
|
387
|
+
...section(response, "web", (item) => result(item, "web")),
|
|
388
|
+
...section(response, "news", (item) => result(item, "news")),
|
|
389
|
+
...section(response, "discussions", (item) => result(item, "discussion")),
|
|
390
|
+
...section(response, "videos", (item) => result(item, "video")),
|
|
391
|
+
...section(response, "locations", placeResult)
|
|
392
|
+
]
|
|
393
|
+
});
|
|
394
|
+
}
|
|
395
|
+
},
|
|
396
|
+
raw
|
|
397
|
+
});
|
|
398
|
+
};
|
|
399
|
+
export { brave };
|
|
@@ -0,0 +1,128 @@
|
|
|
1
|
+
import { I as Page, a as RawClient, f as CallOptions, q as SearchResponse, s as AccountUsage, t as Adapter, u as BrowserSession } from "./adapter-DGehHCMo.js";
|
|
2
|
+
export interface BrowserbaseConfig {
|
|
3
|
+
/** Defaults to the BROWSERBASE_API_KEY environment variable. */
|
|
4
|
+
apiKey?: string;
|
|
5
|
+
/**
|
|
6
|
+
* The project that new browser sessions belong to and whose usage `usage`
|
|
7
|
+
* reads. Defaults to the BROWSERBASE_PROJECT_ID environment variable.
|
|
8
|
+
* Browserbase infers the project from the API key when it is not set, and
|
|
9
|
+
* `usage` then uses the key's only project.
|
|
10
|
+
*/
|
|
11
|
+
projectId?: string;
|
|
12
|
+
baseUrl?: string;
|
|
13
|
+
fetch?: typeof fetch;
|
|
14
|
+
}
|
|
15
|
+
/** Where Browserbase's proxy network exits, as a country with optional state and city. */
|
|
16
|
+
export interface BrowserbaseGeolocation {
|
|
17
|
+
/** ISO 3166-1 alpha-2 code, such as "US". */
|
|
18
|
+
country: string;
|
|
19
|
+
/** US state code such as "NY". Only valid when `country` is "US". */
|
|
20
|
+
state?: string;
|
|
21
|
+
city?: string;
|
|
22
|
+
}
|
|
23
|
+
export interface BrowserbaseReadOptions extends CallOptions {
|
|
24
|
+
/**
|
|
25
|
+
* "markdown" converts the page to Markdown (`Page.markdown`). "raw" returns
|
|
26
|
+
* the response body unchanged (`Page.rawHtml` for HTML). Defaults to
|
|
27
|
+
* "markdown". Fetch never runs JavaScript, reads at most 5 MB and cannot
|
|
28
|
+
* convert PDFs.
|
|
29
|
+
*/
|
|
30
|
+
format?: "markdown" | "raw";
|
|
31
|
+
/** Follow HTTP redirects. Browserbase defaults to false. */
|
|
32
|
+
allowRedirects?: boolean;
|
|
33
|
+
/** Skip TLS certificate verification, for self-signed or expired certificates. */
|
|
34
|
+
allowInsecureSsl?: boolean;
|
|
35
|
+
/**
|
|
36
|
+
* Send the request through Browserbase's proxy network: `true` for the
|
|
37
|
+
* default exit, or a geolocation. Not combinable with `country`.
|
|
38
|
+
*/
|
|
39
|
+
proxies?: boolean | {
|
|
40
|
+
geolocation?: BrowserbaseGeolocation;
|
|
41
|
+
};
|
|
42
|
+
/** ISO 3166-1 alpha-2 code. Sends the request through a proxy in that country. */
|
|
43
|
+
country?: string;
|
|
44
|
+
/** A context whose saved cookies are sent with the request. */
|
|
45
|
+
contextId?: string;
|
|
46
|
+
}
|
|
47
|
+
interface BrowserbaseSearchBase extends CallOptions {
|
|
48
|
+
/** Results to return, 1 to 25. */
|
|
49
|
+
limit?: number;
|
|
50
|
+
}
|
|
51
|
+
/**
|
|
52
|
+
* `mode` is accepted only together with `provider`, and each provider offers
|
|
53
|
+
* its own modes. Without `provider`, Browserbase uses Parallel's `advanced`.
|
|
54
|
+
*/
|
|
55
|
+
export type BrowserbaseSearchOptions = BrowserbaseSearchBase & ({
|
|
56
|
+
provider?: undefined;
|
|
57
|
+
mode?: undefined;
|
|
58
|
+
} | {
|
|
59
|
+
provider: "parallel";
|
|
60
|
+
mode?: "fast" | "advanced";
|
|
61
|
+
} | {
|
|
62
|
+
provider: "exa";
|
|
63
|
+
mode?: "fast" | "deep-lite" | "deep";
|
|
64
|
+
});
|
|
65
|
+
export type BrowserbaseProxy = {
|
|
66
|
+
type: "browserbase";
|
|
67
|
+
geolocation?: BrowserbaseGeolocation;
|
|
68
|
+
/** Use this proxy only for domains that match. */
|
|
69
|
+
domainPattern?: string;
|
|
70
|
+
} | {
|
|
71
|
+
type: "external";
|
|
72
|
+
server: string;
|
|
73
|
+
username?: string;
|
|
74
|
+
password?: string;
|
|
75
|
+
domainPattern?: string;
|
|
76
|
+
} | {
|
|
77
|
+
type: "none";
|
|
78
|
+
domainPattern?: string;
|
|
79
|
+
};
|
|
80
|
+
export interface BrowserbaseOpenOptions extends CallOptions {
|
|
81
|
+
region?: "us-west-2" | "us-east-1" | "eu-central-1" | "ap-southeast-1";
|
|
82
|
+
/** Keep the session open after the client disconnects. Hobby plan and above. */
|
|
83
|
+
keepAlive?: boolean;
|
|
84
|
+
/** Seconds the session may live, 60 to 21600. Browserbase defaults to the project's setting. */
|
|
85
|
+
ttl?: number;
|
|
86
|
+
/** A saved login state. `persist` writes changes made in this session back to it. */
|
|
87
|
+
context?: {
|
|
88
|
+
id: string;
|
|
89
|
+
persist?: boolean;
|
|
90
|
+
};
|
|
91
|
+
/** `true` for the default Browserbase proxy, or rules per domain. */
|
|
92
|
+
proxies?: boolean | BrowserbaseProxy[];
|
|
93
|
+
viewport?: {
|
|
94
|
+
width: number;
|
|
95
|
+
height: number;
|
|
96
|
+
};
|
|
97
|
+
blockAds?: boolean;
|
|
98
|
+
/** Browserbase defaults to true. */
|
|
99
|
+
solveCaptchas?: boolean;
|
|
100
|
+
captchaImageSelector?: string;
|
|
101
|
+
captchaInputSelector?: string;
|
|
102
|
+
/** Browserbase defaults to true. */
|
|
103
|
+
recordSession?: boolean;
|
|
104
|
+
/** Browserbase defaults to true. */
|
|
105
|
+
logSession?: boolean;
|
|
106
|
+
verified?: boolean;
|
|
107
|
+
os?: "windows" | "mac" | "linux" | "mobile" | "tablet";
|
|
108
|
+
/** Plain domains; main-frame navigation is limited to these and their subdomains. */
|
|
109
|
+
allowedDomains?: string[];
|
|
110
|
+
ignoreCertificateErrors?: boolean;
|
|
111
|
+
/** An uploaded browser extension. */
|
|
112
|
+
extensionId?: string;
|
|
113
|
+
/** A navigation policy of the project. */
|
|
114
|
+
riskPolicyId?: string;
|
|
115
|
+
/** Tags stored with the session, searchable in the dashboard. */
|
|
116
|
+
userMetadata?: Record<string, unknown>;
|
|
117
|
+
}
|
|
118
|
+
export interface BrowserbaseOperations {
|
|
119
|
+
search(query: string, options?: BrowserbaseSearchOptions): Promise<SearchResponse>;
|
|
120
|
+
read(url: string, options?: BrowserbaseReadOptions): Promise<Page>;
|
|
121
|
+
browser: {
|
|
122
|
+
open(options?: BrowserbaseOpenOptions): Promise<BrowserSession>;
|
|
123
|
+
close(id: string, options?: CallOptions): Promise<void>;
|
|
124
|
+
};
|
|
125
|
+
usage(options?: CallOptions): Promise<AccountUsage>;
|
|
126
|
+
}
|
|
127
|
+
export declare const browserbase: (config?: BrowserbaseConfig) => Adapter<"browserbase", BrowserbaseOperations, RawClient>;
|
|
128
|
+
export {};
|
|
@@ -0,0 +1,180 @@
|
|
|
1
|
+
import { t as defineAdapter } from "./adapter-CEAQuT7F.js";
|
|
2
|
+
import { t as FieldworkError } from "./errors-BiIBG9zN.js";
|
|
3
|
+
import { b as requireKey, c as num, d as record, f as refuseTogether, g as text, i as compact, o as list, p as requireId, s as meta, t as callSettings, v as createRawClient } from "./util-CYenIQQT.js";
|
|
4
|
+
// src/adapters/browserbase.ts
|
|
5
|
+
const SEARCH_MODES = {
|
|
6
|
+
exa: [
|
|
7
|
+
"fast",
|
|
8
|
+
"deep-lite",
|
|
9
|
+
"deep"
|
|
10
|
+
],
|
|
11
|
+
parallel: ["fast", "advanced"]
|
|
12
|
+
};
|
|
13
|
+
const browserbase = (config = {}) => {
|
|
14
|
+
const provider = "browserbase";
|
|
15
|
+
const raw = createRawClient({
|
|
16
|
+
baseUrl: config.baseUrl ?? "https://api.browserbase.com",
|
|
17
|
+
fetch: config.fetch,
|
|
18
|
+
headers: { "x-bb-api-key": requireKey(provider, config.apiKey, "BROWSERBASE_API_KEY") },
|
|
19
|
+
provider
|
|
20
|
+
});
|
|
21
|
+
const projectId = config.projectId ?? process.env.BROWSERBASE_PROJECT_ID;
|
|
22
|
+
const invalid = (message) => {
|
|
23
|
+
throw new FieldworkError("InvalidRequest", `${provider} ${message}`, { provider });
|
|
24
|
+
};
|
|
25
|
+
const fetchProxies = (o) => {
|
|
26
|
+
refuseTogether(provider, o, "proxies", "country");
|
|
27
|
+
const geolocation = o.country === void 0 ? void 0 : { country: o.country.toUpperCase() };
|
|
28
|
+
const proxies = o.proxies ?? (geolocation ? { geolocation } : void 0);
|
|
29
|
+
const place = typeof proxies === "object" ? proxies.geolocation : void 0;
|
|
30
|
+
if (place?.state && place.country.toUpperCase() !== "US") invalid("accepts a proxy state only with country US");
|
|
31
|
+
return proxies;
|
|
32
|
+
};
|
|
33
|
+
const liveView = async (id, call) => {
|
|
34
|
+
try {
|
|
35
|
+
const urls = record(await raw.request("GET", `/v1/sessions/${encodeURIComponent(id)}/debug`, call));
|
|
36
|
+
return { url: text(urls.debuggerFullscreenUrl) ?? text(urls.debuggerUrl) };
|
|
37
|
+
} catch (error) {
|
|
38
|
+
return { warning: `could not get the live view URL: ${error instanceof Error ? error.message : String(error)}` };
|
|
39
|
+
}
|
|
40
|
+
};
|
|
41
|
+
const operations = {
|
|
42
|
+
browser: {
|
|
43
|
+
async close(id, options) {
|
|
44
|
+
const { call } = callSettings(options);
|
|
45
|
+
await raw.request("POST", `/v1/sessions/${encodeURIComponent(id)}`, {
|
|
46
|
+
...call,
|
|
47
|
+
body: { status: "REQUEST_RELEASE" }
|
|
48
|
+
});
|
|
49
|
+
},
|
|
50
|
+
async open(options) {
|
|
51
|
+
const { call, rest: o } = callSettings(options);
|
|
52
|
+
const browserSettings = compact({
|
|
53
|
+
allowedDomains: o.allowedDomains,
|
|
54
|
+
blockAds: o.blockAds,
|
|
55
|
+
captchaImageSelector: o.captchaImageSelector,
|
|
56
|
+
captchaInputSelector: o.captchaInputSelector,
|
|
57
|
+
context: o.context ? compact({
|
|
58
|
+
id: o.context.id,
|
|
59
|
+
persist: o.context.persist
|
|
60
|
+
}) : void 0,
|
|
61
|
+
extensionId: o.extensionId,
|
|
62
|
+
ignoreCertificateErrors: o.ignoreCertificateErrors,
|
|
63
|
+
logSession: o.logSession,
|
|
64
|
+
os: o.os,
|
|
65
|
+
recordSession: o.recordSession,
|
|
66
|
+
riskPolicyId: o.riskPolicyId,
|
|
67
|
+
solveCaptchas: o.solveCaptchas,
|
|
68
|
+
verified: o.verified,
|
|
69
|
+
viewport: o.viewport
|
|
70
|
+
});
|
|
71
|
+
const session = record(await raw.request("POST", "/v1/sessions", {
|
|
72
|
+
...call,
|
|
73
|
+
body: compact({
|
|
74
|
+
browserSettings: Object.keys(browserSettings).length > 0 ? browserSettings : void 0,
|
|
75
|
+
keepAlive: o.keepAlive,
|
|
76
|
+
projectId,
|
|
77
|
+
proxies: o.proxies,
|
|
78
|
+
region: o.region,
|
|
79
|
+
timeout: o.ttl,
|
|
80
|
+
userMetadata: o.userMetadata
|
|
81
|
+
})
|
|
82
|
+
}));
|
|
83
|
+
const id = requireId(provider, session.id);
|
|
84
|
+
const view = await liveView(id, call);
|
|
85
|
+
return compact({
|
|
86
|
+
cdpUrl: text(session.connectUrl),
|
|
87
|
+
expiresAt: text(session.expiresAt),
|
|
88
|
+
id,
|
|
89
|
+
liveViewUrl: view.url,
|
|
90
|
+
meta: meta({ warnings: view.warning }),
|
|
91
|
+
raw: session
|
|
92
|
+
});
|
|
93
|
+
}
|
|
94
|
+
},
|
|
95
|
+
async read(url, options) {
|
|
96
|
+
const { call, rest: o } = callSettings(options);
|
|
97
|
+
const format = o.format ?? "markdown";
|
|
98
|
+
const response = record(await raw.request("POST", "/v1/fetch", {
|
|
99
|
+
...call,
|
|
100
|
+
body: compact({
|
|
101
|
+
allowInsecureSsl: o.allowInsecureSsl,
|
|
102
|
+
allowRedirects: o.allowRedirects,
|
|
103
|
+
contextId: o.contextId,
|
|
104
|
+
format,
|
|
105
|
+
proxies: fetchProxies(o),
|
|
106
|
+
url
|
|
107
|
+
})
|
|
108
|
+
}));
|
|
109
|
+
const content = typeof response.content === "string" ? response.content : void 0;
|
|
110
|
+
const binary = response.encoding === "base64";
|
|
111
|
+
const contentType = text(response.contentType) ?? "";
|
|
112
|
+
return compact({
|
|
113
|
+
markdown: format === "markdown" && !binary ? content : void 0,
|
|
114
|
+
meta: meta({
|
|
115
|
+
requestId: response.id,
|
|
116
|
+
warnings: binary ? ["the response is binary; its Base64 content is in raw"] : void 0
|
|
117
|
+
}),
|
|
118
|
+
raw: response,
|
|
119
|
+
rawHtml: format === "raw" && !binary && contentType.includes("html") ? content : void 0,
|
|
120
|
+
statusCode: num(response.statusCode),
|
|
121
|
+
url
|
|
122
|
+
});
|
|
123
|
+
},
|
|
124
|
+
async search(query, options) {
|
|
125
|
+
const { call, rest: o } = callSettings(options);
|
|
126
|
+
if (o.mode !== void 0) {
|
|
127
|
+
if (o.provider === void 0) invalid("accepts a search mode only together with provider");
|
|
128
|
+
const allowed = SEARCH_MODES[o.provider];
|
|
129
|
+
if (!allowed.includes(o.mode)) invalid(`search provider ${o.provider} has no mode ${o.mode}; use ${allowed.join(", ")}`);
|
|
130
|
+
}
|
|
131
|
+
const response = record(await raw.request("POST", "/v1/search", {
|
|
132
|
+
...call,
|
|
133
|
+
body: compact({
|
|
134
|
+
mode: o.mode,
|
|
135
|
+
numResults: o.limit,
|
|
136
|
+
provider: o.provider,
|
|
137
|
+
query
|
|
138
|
+
})
|
|
139
|
+
}));
|
|
140
|
+
return compact({
|
|
141
|
+
meta: meta({ requestId: response.requestId }),
|
|
142
|
+
raw: response,
|
|
143
|
+
results: list(response.results).map((item) => {
|
|
144
|
+
const result = record(item);
|
|
145
|
+
return compact({
|
|
146
|
+
author: text(result.author),
|
|
147
|
+
favicon: text(result.favicon),
|
|
148
|
+
image: text(result.image),
|
|
149
|
+
publishedAt: text(result.publishedDate),
|
|
150
|
+
title: text(result.title),
|
|
151
|
+
url: text(result.url) ?? ""
|
|
152
|
+
});
|
|
153
|
+
})
|
|
154
|
+
});
|
|
155
|
+
},
|
|
156
|
+
async usage(options) {
|
|
157
|
+
const { call } = callSettings(options);
|
|
158
|
+
const id = projectId ?? await onlyProject(call);
|
|
159
|
+
const response = record(await raw.request("GET", `/v1/projects/${encodeURIComponent(id)}/usage`, call));
|
|
160
|
+
return compact({
|
|
161
|
+
breakdown: compact({
|
|
162
|
+
browserMinutes: num(response.browserMinutes),
|
|
163
|
+
proxyBytes: num(response.proxyBytes)
|
|
164
|
+
}),
|
|
165
|
+
raw: response
|
|
166
|
+
});
|
|
167
|
+
}
|
|
168
|
+
};
|
|
169
|
+
const onlyProject = async (call) => {
|
|
170
|
+
const projects = list(await raw.request("GET", "/v1/projects", call));
|
|
171
|
+
if (projects.length !== 1) invalid(`usage needs a project: pass projectId or set BROWSERBASE_PROJECT_ID (this key has ${projects.length} projects)`);
|
|
172
|
+
return requireId(provider, record(projects[0]).id);
|
|
173
|
+
};
|
|
174
|
+
return defineAdapter({
|
|
175
|
+
name: provider,
|
|
176
|
+
operations,
|
|
177
|
+
raw
|
|
178
|
+
});
|
|
179
|
+
};
|
|
180
|
+
export { browserbase };
|