serpbit 0.1.0 → 0.2.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 +24 -1
- package/index.d.ts +73 -1
- package/index.js +67 -7
- package/package.json +1 -1
package/README.md
CHANGED
|
@@ -34,12 +34,35 @@ name them:
|
|
|
34
34
|
A method resolves to the API's JSON, or to a string with `output: "md"`. `sb.lastRequestId` and `sb.lastCredits`
|
|
35
35
|
give the last answer's id and the credits it spent.
|
|
36
36
|
|
|
37
|
+
## Browser API
|
|
38
|
+
|
|
39
|
+
Real browsers on residential connections, billed by the traffic they move (your browser plan's GB). The connect URL
|
|
40
|
+
opens a session when a client connects and ends it when the client goes:
|
|
41
|
+
|
|
42
|
+
```js
|
|
43
|
+
import { chromium } from "playwright";
|
|
44
|
+
import Serpbit from "serpbit";
|
|
45
|
+
|
|
46
|
+
const sb = new Serpbit();
|
|
47
|
+
const browser = await chromium.connectOverCDP(sb.browserConnectURL({ country: "de" }));
|
|
48
|
+
const page = browser.contexts()[0].pages()[0];
|
|
49
|
+
await page.goto("https://example.com");
|
|
50
|
+
```
|
|
51
|
+
|
|
52
|
+
Or open one yourself and keep it: `const s = await sb.createBrowserSession({ country: "us", engine: "auto", site:
|
|
53
|
+
"hermes.com" })` gives `s.ws_url` for Playwright or Puppeteer and `s.live_url` for a person to watch or take over; end
|
|
54
|
+
it with `sb.endBrowserSession(s.id)`. `engine: "auto"` picks the engine measured to pass the site. Saved profiles
|
|
55
|
+
keep cookies and logins between sessions: `createBrowserProfile`, then `profile` on a session.
|
|
56
|
+
|
|
37
57
|
## Errors and retries
|
|
38
58
|
|
|
39
59
|
A failed call rejects with a `SerpbitError`. The subclasses are:
|
|
40
60
|
- `BadRequestError` (400);
|
|
41
61
|
- `AuthenticationError` (401);
|
|
42
|
-
- `InsufficientCreditsError` (402);
|
|
62
|
+
- `InsufficientCreditsError` (402: no credits, or for the browser `out_of_traffic`);
|
|
63
|
+
- `PermissionDeniedError` (403);
|
|
64
|
+
- `NotFoundError` (404);
|
|
65
|
+
- `UnprocessableEntityError` (422, such as a CAPTCHA call with no widget on the page);
|
|
43
66
|
- `RateLimitError` (429, with `retryAfter`);
|
|
44
67
|
- `APIError` (5xx);
|
|
45
68
|
- `APIConnectionError`.
|
package/index.d.ts
CHANGED
|
@@ -8,6 +8,8 @@ export interface ClientOptions {
|
|
|
8
8
|
apiKey?: string;
|
|
9
9
|
/** Defaults to SERPBIT_BASE_URL, then https://api.serpbit.com. */
|
|
10
10
|
baseURL?: string;
|
|
11
|
+
/** The Browser API's connect host. Defaults to SERPBIT_CONNECT_URL, then wss://connect.serpbit.com. */
|
|
12
|
+
connectURL?: string;
|
|
11
13
|
/** Milliseconds a call may take, each attempt. Default 90000. */
|
|
12
14
|
timeout?: number;
|
|
13
15
|
/** Retries on 429 and 5xx, each with the same Idempotency-Key. Default 2. */
|
|
@@ -219,7 +221,71 @@ export declare class Serpbit {
|
|
|
219
221
|
batch(requests: BatchRequest[], options?: { webhook?: string } & RequestOptions): Promise<BatchSummary>;
|
|
220
222
|
getBatch(id: string, params?: RequestOptions): Promise<BatchSummary>;
|
|
221
223
|
batchResults(id: string, options?: { offset?: number; limit?: number } & RequestOptions): Promise<BatchResults>;
|
|
222
|
-
|
|
224
|
+
connectURL: string;
|
|
225
|
+
|
|
226
|
+
/** A URL that opens a browser session on connect and ends it on disconnect (Playwright, Puppeteer, browser-use). It holds the key. */
|
|
227
|
+
browserConnectURL(options?: BrowserSessionOptions): string;
|
|
228
|
+
/** Open a browser session; billed by the traffic it moves. */
|
|
229
|
+
createBrowserSession(options?: BrowserSessionOptions): Promise<BrowserSession>;
|
|
230
|
+
browserSessions(params?: Params): Promise<{ sessions: BrowserSession[] }>;
|
|
231
|
+
getBrowserSession(id: string): Promise<BrowserSession>;
|
|
232
|
+
/** End a session; its profile, if any, is saved. */
|
|
233
|
+
endBrowserSession(id: string): Promise<BrowserSession>;
|
|
234
|
+
/** Solve the CAPTCHA widget on a Chrome session's page now (Turnstile, reCAPTCHA v2); sessions also solve them on their own. Billed as traffic per solve. */
|
|
235
|
+
solveBrowserCaptcha(id: string): Promise<{ type: string; url: string; ms: number }>;
|
|
236
|
+
browserUsage(params?: Params): Promise<Record<string, unknown>>;
|
|
237
|
+
createBrowserProfile(options?: { country?: string; platform?: "linux" | "windows" | "macos"; engine?: "chrome" | "firefox"; name?: string }): Promise<BrowserProfile>;
|
|
238
|
+
browserProfiles(): Promise<{ profiles: BrowserProfile[] }>;
|
|
239
|
+
deleteBrowserProfile(id: string): Promise<unknown>;
|
|
240
|
+
request<T = unknown>(path: string, params?: Params, options?: { method?: "GET" | "POST" | "DELETE"; body?: unknown; retry?: boolean }): Promise<T>;
|
|
241
|
+
}
|
|
242
|
+
|
|
243
|
+
export interface BrowserSessionOptions {
|
|
244
|
+
/** Exit country, two letters. Default us. */
|
|
245
|
+
country?: string;
|
|
246
|
+
/** chrome (default), firefox, or auto: the engine measured to pass the site. */
|
|
247
|
+
engine?: "chrome" | "firefox" | "auto";
|
|
248
|
+
platform?: "linux" | "windows" | "macos";
|
|
249
|
+
/** The site the session is for, e.g. "example.com" or a URL: picks the engine with engine auto. */
|
|
250
|
+
site?: string;
|
|
251
|
+
/** A saved profile's id: start with its cookies and logins. */
|
|
252
|
+
profile?: string;
|
|
253
|
+
/** With profile: save it back at the end (default true). */
|
|
254
|
+
persist?: boolean;
|
|
255
|
+
/** Resource types not to load, e.g. ["image", "font", "media"] (Chrome). */
|
|
256
|
+
block?: string | string[];
|
|
257
|
+
/** Seconds, up to the plan's longest session. */
|
|
258
|
+
ttl_s?: number;
|
|
259
|
+
/** Chrome: solve Turnstile and reCAPTCHA v2 widgets on their own (default true; billed per solve). */
|
|
260
|
+
solve_captchas?: boolean;
|
|
261
|
+
}
|
|
262
|
+
|
|
263
|
+
export interface BrowserSession {
|
|
264
|
+
id: string;
|
|
265
|
+
state: "starting" | "active" | "ended";
|
|
266
|
+
country: string;
|
|
267
|
+
engine: "chrome" | "firefox";
|
|
268
|
+
platform: string;
|
|
269
|
+
ttl_s: number;
|
|
270
|
+
proxy_bytes: number;
|
|
271
|
+
billed_bytes: number;
|
|
272
|
+
browser_seconds: number;
|
|
273
|
+
cdp_url?: string;
|
|
274
|
+
ws_url?: string;
|
|
275
|
+
live_url?: string;
|
|
276
|
+
expires_at?: string;
|
|
277
|
+
end_reason?: string;
|
|
278
|
+
[k: string]: unknown;
|
|
279
|
+
}
|
|
280
|
+
|
|
281
|
+
export interface BrowserProfile {
|
|
282
|
+
id: string;
|
|
283
|
+
name?: string;
|
|
284
|
+
country: string;
|
|
285
|
+
platform: string;
|
|
286
|
+
saved_bytes?: number;
|
|
287
|
+
saved_at?: string;
|
|
288
|
+
[k: string]: unknown;
|
|
223
289
|
}
|
|
224
290
|
|
|
225
291
|
export interface BatchRequest {
|
|
@@ -270,6 +336,12 @@ export declare class SerpbitError extends Error {
|
|
|
270
336
|
export declare class BadRequestError extends SerpbitError {}
|
|
271
337
|
export declare class AuthenticationError extends SerpbitError {}
|
|
272
338
|
export declare class InsufficientCreditsError extends SerpbitError {}
|
|
339
|
+
/** 403: the key may not do this, such as a key that belongs to no account on the Browser API. */
|
|
340
|
+
export declare class PermissionDeniedError extends SerpbitError {}
|
|
341
|
+
/** 404: no such product, or no such browser session or profile on this account. */
|
|
342
|
+
export declare class NotFoundError extends SerpbitError {}
|
|
343
|
+
/** 422: a call that cannot be done, such as a CAPTCHA call on a page with no widget it solves. */
|
|
344
|
+
export declare class UnprocessableEntityError extends SerpbitError {}
|
|
273
345
|
export declare class RateLimitError extends SerpbitError { retryAfter?: number }
|
|
274
346
|
export declare class APIError extends SerpbitError {}
|
|
275
347
|
export declare class APIConnectionError extends SerpbitError {}
|
package/index.js
CHANGED
|
@@ -1,8 +1,9 @@
|
|
|
1
1
|
// Serpbit: Google results as data. A small client for https://api.serpbit.com on the platform's fetch (Node 18+,
|
|
2
2
|
// Deno, Bun, browsers), with no dependencies.
|
|
3
3
|
|
|
4
|
-
export const VERSION = "0.
|
|
4
|
+
export const VERSION = "0.2.0";
|
|
5
5
|
const DEFAULT_BASE_URL = "https://api.serpbit.com";
|
|
6
|
+
const DEFAULT_CONNECT_URL = "wss://connect.serpbit.com";
|
|
6
7
|
// A call is retried on these: the rate limit (after Retry-After), Google giving no page in time, our side failing.
|
|
7
8
|
const RETRY = new Set([429, 500, 502, 503, 504]);
|
|
8
9
|
|
|
@@ -20,6 +21,9 @@ export class SerpbitError extends Error {
|
|
|
20
21
|
export class BadRequestError extends SerpbitError {}
|
|
21
22
|
export class AuthenticationError extends SerpbitError {}
|
|
22
23
|
export class InsufficientCreditsError extends SerpbitError {}
|
|
24
|
+
export class PermissionDeniedError extends SerpbitError {}
|
|
25
|
+
export class NotFoundError extends SerpbitError {}
|
|
26
|
+
export class UnprocessableEntityError extends SerpbitError {}
|
|
23
27
|
export class RateLimitError extends SerpbitError {
|
|
24
28
|
constructor(message, opts = {}) {
|
|
25
29
|
super(message, opts);
|
|
@@ -33,6 +37,9 @@ function errorFor(status, message, opts) {
|
|
|
33
37
|
if (status === 400) return new BadRequestError(message, opts);
|
|
34
38
|
if (status === 401) return new AuthenticationError(message, opts);
|
|
35
39
|
if (status === 402) return new InsufficientCreditsError(message, opts);
|
|
40
|
+
if (status === 403) return new PermissionDeniedError(message, opts);
|
|
41
|
+
if (status === 404) return new NotFoundError(message, opts);
|
|
42
|
+
if (status === 422) return new UnprocessableEntityError(message, opts);
|
|
36
43
|
if (status === 429) return new RateLimitError(message, opts);
|
|
37
44
|
if (status >= 500) return new APIError(message, opts);
|
|
38
45
|
return new SerpbitError(message, opts);
|
|
@@ -44,12 +51,13 @@ export class Serpbit {
|
|
|
44
51
|
/**
|
|
45
52
|
* @param {{apiKey?: string, baseURL?: string, timeout?: number, maxRetries?: number, fetch?: typeof fetch}} [options]
|
|
46
53
|
*/
|
|
47
|
-
constructor({ apiKey, baseURL, timeout = 90_000, maxRetries = 2, fetch: f } = {}) {
|
|
54
|
+
constructor({ apiKey, baseURL, connectURL, timeout = 90_000, maxRetries = 2, fetch: f } = {}) {
|
|
48
55
|
this.apiKey = apiKey ?? env("SERPBIT_API_KEY");
|
|
49
56
|
if (!this.apiKey) {
|
|
50
57
|
throw new SerpbitError("no API key: pass apiKey or set SERPBIT_API_KEY (keys are made at https://app.serpbit.com/keys)");
|
|
51
58
|
}
|
|
52
59
|
this.baseURL = (baseURL ?? env("SERPBIT_BASE_URL") ?? DEFAULT_BASE_URL).replace(/\/+$/, "");
|
|
60
|
+
this.connectURL = (connectURL ?? env("SERPBIT_CONNECT_URL") ?? DEFAULT_CONNECT_URL).replace(/\/+$/, "");
|
|
53
61
|
this.timeout = timeout;
|
|
54
62
|
this.maxRetries = Math.max(0, maxRetries);
|
|
55
63
|
this.fetch = f ?? globalThis.fetch.bind(globalThis);
|
|
@@ -95,12 +103,58 @@ export class Serpbit {
|
|
|
95
103
|
return this.request("/v1/batches/" + encodeURIComponent(id) + "/results", { offset, limit, ...params });
|
|
96
104
|
}
|
|
97
105
|
|
|
106
|
+
/**
|
|
107
|
+
* A URL that opens a browser session when a client connects and ends it when the client goes: hand it to
|
|
108
|
+
* Playwright (chromium.connectOverCDP), Puppeteer (puppeteer.connect({ browserWSEndpoint })), browser-use or any
|
|
109
|
+
* client that takes a URL. Options are the session's: country, engine (chrome, firefox or auto), platform, site,
|
|
110
|
+
* profile, persist, block, ttl_s, solve_captchas. The URL holds the API key: keep it secret.
|
|
111
|
+
*/
|
|
112
|
+
browserConnectURL(options = {}) {
|
|
113
|
+
const q = new URLSearchParams({ key: this.apiKey });
|
|
114
|
+
for (const [k, v] of Object.entries(options)) {
|
|
115
|
+
// false goes in the URL too: persist and solve_captchas are on unless told otherwise.
|
|
116
|
+
if (v === undefined || v === null) continue;
|
|
117
|
+
q.set(k, typeof v === "boolean" ? String(v) : Array.isArray(v) ? v.join(",") : String(v));
|
|
118
|
+
}
|
|
119
|
+
return this.connectURL + "/?" + q.toString();
|
|
120
|
+
}
|
|
121
|
+
/**
|
|
122
|
+
* Open a browser session (POST /v1/browser/sessions): its ws_url for Playwright or Puppeteer, its live_url for a
|
|
123
|
+
* person to watch or take over. It runs until endBrowserSession, its plan's longest session or 10 minutes unused.
|
|
124
|
+
* Billed by the traffic it moves; a 402 (InsufficientCreditsError) means no browser traffic is left.
|
|
125
|
+
*/
|
|
126
|
+
createBrowserSession(options = {}) {
|
|
127
|
+
return this.request("/v1/browser/sessions", {}, { method: "POST", body: dropEmpty(options), retry: false });
|
|
128
|
+
}
|
|
129
|
+
/** The account's open sessions (GET /v1/browser/sessions). */
|
|
130
|
+
browserSessions(params) { return this.request("/v1/browser/sessions", { ...params }); }
|
|
131
|
+
/** A session, with the traffic it moved so far (GET /v1/browser/sessions/{id}). */
|
|
132
|
+
getBrowserSession(id) { return this.request("/v1/browser/sessions/" + encodeURIComponent(id)); }
|
|
133
|
+
/** End a session (DELETE /v1/browser/sessions/{id}); its profile, if any, is saved. Resolves to what it was billed. */
|
|
134
|
+
endBrowserSession(id) { return this.request("/v1/browser/sessions/" + encodeURIComponent(id), {}, { method: "DELETE" }); }
|
|
135
|
+
/** Solve the CAPTCHA widget on a Chrome session's page and put the answer in (POST /v1/browser/sessions/{id}/captcha):
|
|
136
|
+
* Cloudflare Turnstile, reCAPTCHA v2. Billed as traffic per solve. */
|
|
137
|
+
solveBrowserCaptcha(id) {
|
|
138
|
+
return this.request("/v1/browser/sessions/" + encodeURIComponent(id) + "/captcha", {}, { method: "POST", retry: false });
|
|
139
|
+
}
|
|
140
|
+
/** Browser traffic and sessions over time (GET /v1/browser/usage). */
|
|
141
|
+
browserUsage(params) { return this.request("/v1/browser/usage", { ...params }); }
|
|
142
|
+
/** A saved profile (POST /v1/browser/profiles): a session started with it keeps its cookies and logins. */
|
|
143
|
+
createBrowserProfile(options = {}) {
|
|
144
|
+
return this.request("/v1/browser/profiles", {}, { method: "POST", body: dropEmpty(options), retry: false });
|
|
145
|
+
}
|
|
146
|
+
/** The account's saved profiles (GET /v1/browser/profiles). */
|
|
147
|
+
browserProfiles() { return this.request("/v1/browser/profiles"); }
|
|
148
|
+
/** Delete a saved profile and its data (DELETE /v1/browser/profiles/{id}). */
|
|
149
|
+
deleteBrowserProfile(id) { return this.request("/v1/browser/profiles/" + encodeURIComponent(id), {}, { method: "DELETE" }); }
|
|
150
|
+
|
|
98
151
|
/**
|
|
99
152
|
* GET path with params: true is sent as true; undefined, null and false are left out; an array is joined by
|
|
100
153
|
* commas. Resolves to the JSON, or to a string with output "md". Every attempt carries one Idempotency-Key, so an
|
|
101
154
|
* answer lost on the way is given back free rather than billed again.
|
|
102
155
|
*/
|
|
103
|
-
async request(path, params = {}, { method = "GET", body } = {}) {
|
|
156
|
+
async request(path, params = {}, { method = "GET", body, retry = true } = {}) {
|
|
157
|
+
const retries = retry ? this.maxRetries : 0;
|
|
104
158
|
const { idempotencyKey, signal, ...rest } = params;
|
|
105
159
|
const query = new URLSearchParams();
|
|
106
160
|
for (const [k, v] of Object.entries(rest)) {
|
|
@@ -109,7 +163,7 @@ export class Serpbit {
|
|
|
109
163
|
}
|
|
110
164
|
const qs = query.toString();
|
|
111
165
|
const url = this.baseURL + path + (qs ? "?" + qs : "");
|
|
112
|
-
const key = idempotencyKey ?? (
|
|
166
|
+
const key = idempotencyKey ?? (retries ? randomKey() : undefined);
|
|
113
167
|
const headers = { Authorization: "Bearer " + this.apiKey, Accept: "application/json, text/markdown" };
|
|
114
168
|
if (key) headers["Idempotency-Key"] = key;
|
|
115
169
|
if (typeof window === "undefined") headers["User-Agent"] = "serpbit-js/" + VERSION;
|
|
@@ -128,7 +182,7 @@ export class Serpbit {
|
|
|
128
182
|
clearTimeout(timer);
|
|
129
183
|
signal?.removeEventListener("abort", onAbort);
|
|
130
184
|
if (signal?.aborted) throw err;
|
|
131
|
-
if (attempt <
|
|
185
|
+
if (attempt < retries) {
|
|
132
186
|
await sleep(backoff(attempt));
|
|
133
187
|
continue;
|
|
134
188
|
}
|
|
@@ -142,11 +196,13 @@ export class Serpbit {
|
|
|
142
196
|
this.lastRequestId = resp.headers.get("X-Request-Id") ?? undefined;
|
|
143
197
|
const credits = resp.headers.get("X-Credits");
|
|
144
198
|
this.lastCredits = credits === null ? undefined : Number(credits);
|
|
145
|
-
|
|
199
|
+
const json = (resp.headers.get("Content-Type") ?? "").startsWith("application/json");
|
|
200
|
+
if (!text) return json || resp.status === 204 ? {} : "";
|
|
201
|
+
return json ? JSON.parse(text) : text;
|
|
146
202
|
}
|
|
147
203
|
const ra = resp.headers.get("Retry-After");
|
|
148
204
|
const retryAfter = ra === null || Number.isNaN(Number(ra)) ? undefined : Number(ra);
|
|
149
|
-
if (RETRY.has(resp.status) && attempt <
|
|
205
|
+
if (RETRY.has(resp.status) && attempt < retries) {
|
|
150
206
|
await sleep(backoff(attempt, retryAfter));
|
|
151
207
|
continue;
|
|
152
208
|
}
|
|
@@ -184,6 +240,10 @@ export async function verifyWebhook(body, signature, apiKey, { tolerance = 300 }
|
|
|
184
240
|
return diff === 0;
|
|
185
241
|
}
|
|
186
242
|
|
|
243
|
+
function dropEmpty(o) {
|
|
244
|
+
return Object.fromEntries(Object.entries(o).filter(([, v]) => v !== undefined && v !== null));
|
|
245
|
+
}
|
|
246
|
+
|
|
187
247
|
function randomKey() {
|
|
188
248
|
if (globalThis.crypto?.randomUUID) return globalThis.crypto.randomUUID().replace(/-/g, "");
|
|
189
249
|
return Array.from({ length: 32 }, () => Math.floor(Math.random() * 16).toString(16)).join("");
|