serpbit 0.0.0-stage → 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.
Files changed (5) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +88 -2
  3. package/index.d.ts +349 -0
  4. package/index.js +259 -0
  5. package/package.json +27 -4
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Serpbit
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,89 @@
1
- # Temporary Holding Version
1
+ # serpbit
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ Google Search, News, Shopping, Images, Videos, Maps, Autocomplete and AI Mode as data, from
4
+ [Serpbit](https://serpbit.com). No dependencies: it uses the platform's `fetch` (Node 18+, Deno, Bun, browsers),
5
+ and comes with TypeScript types.
6
+
7
+ ```sh
8
+ npm install serpbit
9
+ ```
10
+
11
+ ```js
12
+ import Serpbit from "serpbit";
13
+
14
+ const sb = new Serpbit(); // reads SERPBIT_API_KEY; make a key at https://app.serpbit.com/keys
15
+
16
+ const answer = await sb.search("espresso grinder", { gl: "de", hl: "de", pages: 2 });
17
+ for (const r of answer.organic) console.log(r.position, r.title, r.url);
18
+
19
+ // The first three results' pages, as Markdown text: 1 credit a page read.
20
+ const read = await sb.search("how to descale an espresso machine", { content: 3 });
21
+ console.log(read.organic[0].content?.text?.slice(0, 500));
22
+
23
+ // Markdown instead of JSON, for a language model's context.
24
+ console.log(await sb.news("wildfire", { sort: "date", output: "md" }));
25
+ ```
26
+
27
+ Every door of the API has a method: `search`, `news`, `shopping`, `shoppingProduct`, `images`, `videos`, `maps`,
28
+ `autocomplete`, `aiMode`. The second argument holds the door's parameters, as the [docs](https://serpbit.com/docs/)
29
+ name them:
30
+ - `true` is sent as `true`;
31
+ - `undefined`, `null` and `false` are left out;
32
+ - an array is joined with commas.
33
+
34
+ A method resolves to the API's JSON, or to a string with `output: "md"`. `sb.lastRequestId` and `sb.lastCredits`
35
+ give the last answer's id and the credits it spent.
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
+
57
+ ## Errors and retries
58
+
59
+ A failed call rejects with a `SerpbitError`. The subclasses are:
60
+ - `BadRequestError` (400);
61
+ - `AuthenticationError` (401);
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);
66
+ - `RateLimitError` (429, with `retryAfter`);
67
+ - `APIError` (5xx);
68
+ - `APIConnectionError`.
69
+
70
+ Each carries `status`, `code` and `requestId`. Quote the `requestId` to support.
71
+
72
+ Calls are retried twice on 429 and 5xx (set with `maxRetries`), waiting as `Retry-After` says. Every attempt of one
73
+ call carries the same `Idempotency-Key`, so an answer lost on the way is given back free instead of being billed
74
+ twice. Pass `idempotencyKey` to use your own, and `signal` to cancel a call.
75
+
76
+ Keep the key on a server: an API key in a browser page is anyone's to read.
77
+
78
+ ## Batches
79
+
80
+ ```js
81
+ const b = await sb.batch(keywords.map((kw) => ({ path: "/v1/search", params: { q: kw, gl: "us" }, id: kw })),
82
+ { webhook: "https://example.com/serpbit" });
83
+ await sb.getBatch(b.id); // status, and each call's
84
+ await sb.batchResults(b.id, { offset: 0 }); // the answers, 100 at a time, for a day after it ends
85
+
86
+ // In your webhook: check the event is Serpbit's before you trust it (pass the raw body).
87
+ import { verifyWebhook } from "serpbit";
88
+ const ok = await verifyWebhook(rawBody, req.headers["serpbit-signature"], apiKey);
89
+ ```
package/index.d.ts ADDED
@@ -0,0 +1,349 @@
1
+ // Types of the Serpbit API's answers: the fields most code reads. Every answer may carry more; see
2
+ // https://serpbit.com/docs/ for all of them.
3
+
4
+ export declare const VERSION: string;
5
+
6
+ export interface ClientOptions {
7
+ /** Defaults to the SERPBIT_API_KEY environment variable. */
8
+ apiKey?: string;
9
+ /** Defaults to SERPBIT_BASE_URL, then https://api.serpbit.com. */
10
+ baseURL?: string;
11
+ /** The Browser API's connect host. Defaults to SERPBIT_CONNECT_URL, then wss://connect.serpbit.com. */
12
+ connectURL?: string;
13
+ /** Milliseconds a call may take, each attempt. Default 90000. */
14
+ timeout?: number;
15
+ /** Retries on 429 and 5xx, each with the same Idempotency-Key. Default 2. */
16
+ maxRetries?: number;
17
+ /** A fetch of your own (a proxy, a test). */
18
+ fetch?: typeof fetch;
19
+ }
20
+
21
+ /** Any parameter of a door, as the docs name it: true is sent as true; undefined, null and false are left out. */
22
+ export type ParamValue = string | number | boolean | null | undefined | ReadonlyArray<string | number>;
23
+
24
+ export interface RequestOptions {
25
+ idempotencyKey?: string;
26
+ signal?: AbortSignal;
27
+ }
28
+
29
+ export interface SearchParams extends RequestOptions {
30
+ gl?: string;
31
+ hl?: string;
32
+ location?: string;
33
+ uule?: string;
34
+ device?: "desktop" | "mobile" | "iphone" | "ipad";
35
+ pages?: number;
36
+ num?: number;
37
+ start?: number;
38
+ /** Read the first N results' pages as text (1 credit a page read); true reads 10. */
39
+ content?: number | boolean;
40
+ content_chars?: number;
41
+ ai_overview?: boolean;
42
+ safe?: "off" | "active";
43
+ lr?: string;
44
+ tbs?: string;
45
+ nfpr?: boolean | 1 | 0;
46
+ filter?: 0 | 1;
47
+ html?: boolean;
48
+ no_cache?: boolean;
49
+ output?: "json" | "md";
50
+ [param: string]: ParamValue | AbortSignal;
51
+ }
52
+
53
+ export interface Meta { elapsed_ms: number; credits: number }
54
+ export interface Page { page: number; results: number; html?: string }
55
+ export interface Pagination { next_start: number | null }
56
+
57
+ /** A result's page read as text (content=N), or why it could not be read. */
58
+ export interface Content {
59
+ url?: string;
60
+ title?: string;
61
+ byline?: string;
62
+ site_name?: string;
63
+ published_at?: string;
64
+ lang?: string;
65
+ /** The page's main text as Markdown. */
66
+ text?: string;
67
+ chars?: number;
68
+ truncated?: boolean;
69
+ error?: "timeout" | "blocked" | "not_found" | "not_html" | "unreadable" | "unresolved" | "failed";
70
+ }
71
+
72
+ export interface OrganicResult {
73
+ position: number;
74
+ page: number;
75
+ title: string;
76
+ url: string;
77
+ domain?: string;
78
+ displayed_url?: string;
79
+ snippet?: string;
80
+ content?: Content;
81
+ }
82
+
83
+ export interface SearchResponse {
84
+ request_id: string;
85
+ search: Record<string, unknown>;
86
+ ai_overview?: { text: string; sources?: Array<{ title: string; url: string }>; [k: string]: unknown };
87
+ organic: OrganicResult[];
88
+ related_questions?: unknown[];
89
+ related_searches?: unknown[];
90
+ knowledge_graph?: Record<string, unknown>;
91
+ top_stories?: unknown[];
92
+ showing_results_for?: string;
93
+ pages: Page[];
94
+ pagination: Pagination;
95
+ meta: Meta;
96
+ [k: string]: unknown;
97
+ }
98
+
99
+ export interface NewsArticle {
100
+ position: number;
101
+ page: number;
102
+ title: string;
103
+ url: string;
104
+ domain?: string;
105
+ source?: string;
106
+ date?: string;
107
+ published_at?: string;
108
+ snippet?: string;
109
+ thumbnail?: string;
110
+ story_id?: string;
111
+ content?: Content;
112
+ }
113
+ export interface NewsResponse {
114
+ request_id: string; search: Record<string, unknown>; news: NewsArticle[]; pages: Page[]; pagination: Pagination;
115
+ meta: Meta; [k: string]: unknown;
116
+ }
117
+
118
+ export interface ShoppingProduct {
119
+ position: number;
120
+ page: number;
121
+ title: string;
122
+ product_id?: string;
123
+ product_link?: string;
124
+ source?: string;
125
+ price?: string;
126
+ extracted_price?: number;
127
+ old_price?: string;
128
+ rating?: number;
129
+ reviews?: number;
130
+ delivery?: string;
131
+ thumbnail?: string;
132
+ [k: string]: unknown;
133
+ }
134
+ export interface ShoppingResponse {
135
+ request_id: string; search: Record<string, unknown>; shopping: ShoppingProduct[]; filters?: unknown[]; pages: Page[];
136
+ pagination: Pagination; meta: Meta; [k: string]: unknown;
137
+ }
138
+
139
+ export interface Image {
140
+ position: number; page: number; title: string; url: string; source?: string; original?: string;
141
+ original_width?: number; original_height?: number; thumbnail?: string; [k: string]: unknown;
142
+ }
143
+ export interface ImagesResponse {
144
+ request_id: string; search: Record<string, unknown>; images: Image[]; suggested_searches?: Array<{ name: string; q: string }>;
145
+ pages: Page[]; pagination: Pagination; meta: Meta; [k: string]: unknown;
146
+ }
147
+
148
+ export interface Video {
149
+ position: number; page: number; title: string; url: string; snippet?: string; duration?: string; duration_seconds?: number;
150
+ platform?: string; channel?: string; date?: string; thumbnail?: string; video_id?: string;
151
+ }
152
+ export interface VideosResponse {
153
+ request_id: string; search: Record<string, unknown>; videos: Video[]; pages: Page[]; pagination: Pagination; meta: Meta;
154
+ [k: string]: unknown;
155
+ }
156
+
157
+ export interface Place {
158
+ position: number; page: number; title: string; link?: string; place_id?: string; rating?: number; reviews?: number;
159
+ price?: string; type?: string; address?: string; hours?: string; phone?: string; website?: string;
160
+ gps_coordinates?: { latitude: number; longitude: number }; [k: string]: unknown;
161
+ }
162
+ export interface MapsResponse {
163
+ request_id: string; search: Record<string, unknown>; places: Place[]; pages: Page[]; pagination: Pagination; meta: Meta;
164
+ [k: string]: unknown;
165
+ }
166
+
167
+ export interface AutocompleteResponse {
168
+ request_id: string;
169
+ search: Record<string, unknown>;
170
+ suggestions: Array<{ position: number; value: string; type?: string; relevance?: number; [k: string]: unknown }>;
171
+ meta: Meta;
172
+ [k: string]: unknown;
173
+ }
174
+
175
+ export interface AIModeResponse {
176
+ request_id: string;
177
+ search: Record<string, unknown>;
178
+ text_blocks: unknown[];
179
+ references: Array<{ title?: string; link?: string; snippet?: string; source?: string; [k: string]: unknown }>;
180
+ local_results?: unknown[];
181
+ markdown: string;
182
+ meta: Meta;
183
+ [k: string]: unknown;
184
+ }
185
+
186
+ export interface ProductResponse {
187
+ request_id: string; search: Record<string, unknown>; product: Record<string, unknown>; sellers: unknown[];
188
+ sellers_count: number; complete: boolean; meta: Meta; [k: string]: unknown;
189
+ }
190
+
191
+ type Md<P> = P & { output: "md" };
192
+ type Params = { [param: string]: ParamValue | AbortSignal } & RequestOptions;
193
+
194
+ export declare class Serpbit {
195
+ constructor(options?: ClientOptions);
196
+ apiKey: string;
197
+ baseURL: string;
198
+ timeout: number;
199
+ maxRetries: number;
200
+ lastRequestId?: string;
201
+ lastCredits?: number;
202
+
203
+ search(q: string | undefined, params: Md<SearchParams>): Promise<string>;
204
+ search(q?: string, params?: SearchParams): Promise<SearchResponse>;
205
+ news(q: string, params: Md<SearchParams>): Promise<string>;
206
+ news(q: string, params?: SearchParams): Promise<NewsResponse>;
207
+ shopping(q: string, params: Md<Params>): Promise<string>;
208
+ shopping(q: string, params?: Params): Promise<ShoppingResponse>;
209
+ shoppingProduct(productId: string | undefined, params: Md<Params>): Promise<string>;
210
+ shoppingProduct(productId?: string, params?: Params): Promise<ProductResponse>;
211
+ images(q: string, params: Md<Params>): Promise<string>;
212
+ images(q: string, params?: Params): Promise<ImagesResponse>;
213
+ videos(q: string, params: Md<Params>): Promise<string>;
214
+ videos(q: string, params?: Params): Promise<VideosResponse>;
215
+ maps(q: string, params: Md<Params>): Promise<string>;
216
+ maps(q: string, params?: Params): Promise<MapsResponse>;
217
+ autocomplete(q: string, params?: Params): Promise<AutocompleteResponse>;
218
+ aiMode(q: string, params: Md<Params>): Promise<string>;
219
+ aiMode(q: string, params?: Params): Promise<AIModeResponse>;
220
+ /** Start a batch of up to 1,000 calls; answers go to the webhook and stay readable a day after it ends. */
221
+ batch(requests: BatchRequest[], options?: { webhook?: string } & RequestOptions): Promise<BatchSummary>;
222
+ getBatch(id: string, params?: RequestOptions): Promise<BatchSummary>;
223
+ batchResults(id: string, options?: { offset?: number; limit?: number } & RequestOptions): Promise<BatchResults>;
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;
289
+ }
290
+
291
+ export interface BatchRequest {
292
+ path: "/v1/search" | "/v1/news" | "/v1/shopping" | "/v1/shopping/product" | "/v1/images" | "/v1/videos" | "/v1/maps" | "/v1/autocomplete" | "/v1/ai-mode";
293
+ params?: { [param: string]: ParamValue };
294
+ /** Your own reference, echoed with the answer. */
295
+ id?: string;
296
+ }
297
+ export interface BatchItem {
298
+ index: number;
299
+ id?: string;
300
+ path: string;
301
+ /** The call's HTTP status; absent while it waits or runs. */
302
+ status?: number;
303
+ credits?: number;
304
+ request_id?: string;
305
+ /** With a webhook: whether it took the answer. */
306
+ delivered?: boolean;
307
+ /** The API's answer, or its error: as the call's own door gives it. */
308
+ answer?: unknown;
309
+ }
310
+ export interface BatchSummary {
311
+ id: string;
312
+ status: "running" | "completed";
313
+ total: number;
314
+ done: number;
315
+ succeeded: number;
316
+ failed: number;
317
+ credits: number;
318
+ webhook?: string;
319
+ created_at: string;
320
+ completed_at?: string;
321
+ expires_at?: string;
322
+ items?: BatchItem[];
323
+ }
324
+ export interface BatchResults extends BatchSummary { offset: number; limit: number; items: BatchItem[] }
325
+
326
+ /** Whether a webhook's raw body is Serpbit's: its Serpbit-Signature checked with the API key that started the batch. */
327
+ export declare function verifyWebhook(body: string | ArrayBuffer | Uint8Array, signature: string | null | undefined, apiKey: string,
328
+ options?: { tolerance?: number }): Promise<boolean>;
329
+
330
+ export declare class SerpbitError extends Error {
331
+ status?: number;
332
+ code?: string;
333
+ requestId?: string;
334
+ body?: Record<string, unknown>;
335
+ }
336
+ export declare class BadRequestError extends SerpbitError {}
337
+ export declare class AuthenticationError extends SerpbitError {}
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 {}
345
+ export declare class RateLimitError extends SerpbitError { retryAfter?: number }
346
+ export declare class APIError extends SerpbitError {}
347
+ export declare class APIConnectionError extends SerpbitError {}
348
+
349
+ export default Serpbit;
package/index.js ADDED
@@ -0,0 +1,259 @@
1
+ // Serpbit: Google results as data. A small client for https://api.serpbit.com on the platform's fetch (Node 18+,
2
+ // Deno, Bun, browsers), with no dependencies.
3
+
4
+ export const VERSION = "0.2.0";
5
+ const DEFAULT_BASE_URL = "https://api.serpbit.com";
6
+ const DEFAULT_CONNECT_URL = "wss://connect.serpbit.com";
7
+ // A call is retried on these: the rate limit (after Retry-After), Google giving no page in time, our side failing.
8
+ const RETRY = new Set([429, 500, 502, 503, 504]);
9
+
10
+ /** A call that did not answer: status, code and requestId are the API's (requestId is what support asks for). */
11
+ export class SerpbitError extends Error {
12
+ constructor(message, { status, code, requestId, body } = {}) {
13
+ super(message);
14
+ this.name = new.target.name;
15
+ this.status = status;
16
+ this.code = code;
17
+ this.requestId = requestId;
18
+ this.body = body;
19
+ }
20
+ }
21
+ export class BadRequestError extends SerpbitError {}
22
+ export class AuthenticationError extends SerpbitError {}
23
+ export class InsufficientCreditsError extends SerpbitError {}
24
+ export class PermissionDeniedError extends SerpbitError {}
25
+ export class NotFoundError extends SerpbitError {}
26
+ export class UnprocessableEntityError extends SerpbitError {}
27
+ export class RateLimitError extends SerpbitError {
28
+ constructor(message, opts = {}) {
29
+ super(message, opts);
30
+ this.retryAfter = opts.retryAfter;
31
+ }
32
+ }
33
+ export class APIError extends SerpbitError {}
34
+ export class APIConnectionError extends SerpbitError {}
35
+
36
+ function errorFor(status, message, opts) {
37
+ if (status === 400) return new BadRequestError(message, opts);
38
+ if (status === 401) return new AuthenticationError(message, opts);
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);
43
+ if (status === 429) return new RateLimitError(message, opts);
44
+ if (status >= 500) return new APIError(message, opts);
45
+ return new SerpbitError(message, opts);
46
+ }
47
+
48
+ const env = (name) => (typeof process !== "undefined" && process.env ? process.env[name] : undefined);
49
+
50
+ export class Serpbit {
51
+ /**
52
+ * @param {{apiKey?: string, baseURL?: string, timeout?: number, maxRetries?: number, fetch?: typeof fetch}} [options]
53
+ */
54
+ constructor({ apiKey, baseURL, connectURL, timeout = 90_000, maxRetries = 2, fetch: f } = {}) {
55
+ this.apiKey = apiKey ?? env("SERPBIT_API_KEY");
56
+ if (!this.apiKey) {
57
+ throw new SerpbitError("no API key: pass apiKey or set SERPBIT_API_KEY (keys are made at https://app.serpbit.com/keys)");
58
+ }
59
+ this.baseURL = (baseURL ?? env("SERPBIT_BASE_URL") ?? DEFAULT_BASE_URL).replace(/\/+$/, "");
60
+ this.connectURL = (connectURL ?? env("SERPBIT_CONNECT_URL") ?? DEFAULT_CONNECT_URL).replace(/\/+$/, "");
61
+ this.timeout = timeout;
62
+ this.maxRetries = Math.max(0, maxRetries);
63
+ this.fetch = f ?? globalThis.fetch.bind(globalThis);
64
+ // The last answer's id and credits, from its headers: a Markdown answer has no JSON to carry them.
65
+ this.lastRequestId = undefined;
66
+ this.lastCredits = undefined;
67
+ }
68
+
69
+ /** Google's results page (/v1/search). `url` takes a Google results address instead of `q`. */
70
+ search(q, params) { return this.request("/v1/search", { q, ...params }); }
71
+ /** Google's News tab (/v1/news). */
72
+ news(q, params) { return this.request("/v1/news", { q, ...params }); }
73
+ /** Google's Shopping tab (/v1/shopping). */
74
+ shopping(q, params) { return this.request("/v1/shopping", { q, ...params }); }
75
+ /** One product and every store's offer (/v1/shopping/product). */
76
+ shoppingProduct(productId, params) { return this.request("/v1/shopping/product", { product_id: productId, ...params }); }
77
+ /** Google's Images tab (/v1/images). */
78
+ images(q, params) { return this.request("/v1/images", { q, ...params }); }
79
+ /** Google's Videos tab (/v1/videos). */
80
+ videos(q, params) { return this.request("/v1/videos", { q, ...params }); }
81
+ /** Places as Google Maps lists them (/v1/maps). */
82
+ maps(q, params) { return this.request("/v1/maps", { q, ...params }); }
83
+ /** Google's search-box suggestions (/v1/autocomplete). */
84
+ autocomplete(q, params) { return this.request("/v1/autocomplete", { q, ...params }); }
85
+ /** Google's AI Mode answer with its sources (/v1/ai-mode). */
86
+ aiMode(q, params) { return this.request("/v1/ai-mode", { q, ...params }); }
87
+
88
+ /**
89
+ * Start a batch of up to 1,000 calls (POST /v1/batches), each { path: "/v1/search", params: {...}, id }. The calls
90
+ * run in the background at the key's limits; each answer goes to the webhook as it comes (check it with
91
+ * verifyWebhook) and stays readable with batchResults for a day after the batch ends.
92
+ */
93
+ batch(requests, { webhook, idempotencyKey, signal } = {}) {
94
+ const clean = (params = {}) => Object.fromEntries(Object.entries(params).filter(([, v]) => v !== undefined && v !== null && v !== false));
95
+ const body = { requests: requests.map((r) => ({ ...r, params: clean(r.params) })) };
96
+ if (webhook) body.webhook = webhook;
97
+ return this.request("/v1/batches", { idempotencyKey, signal }, { method: "POST", body });
98
+ }
99
+ /** A batch's state and each call's status (GET /v1/batches/{id}). */
100
+ getBatch(id, params) { return this.request("/v1/batches/" + encodeURIComponent(id), { ...params }); }
101
+ /** A batch's answers, limit (at most 100) from offset (GET /v1/batches/{id}/results). */
102
+ batchResults(id, { offset = 0, limit = 100, ...params } = {}) {
103
+ return this.request("/v1/batches/" + encodeURIComponent(id) + "/results", { offset, limit, ...params });
104
+ }
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
+
151
+ /**
152
+ * GET path with params: true is sent as true; undefined, null and false are left out; an array is joined by
153
+ * commas. Resolves to the JSON, or to a string with output "md". Every attempt carries one Idempotency-Key, so an
154
+ * answer lost on the way is given back free rather than billed again.
155
+ */
156
+ async request(path, params = {}, { method = "GET", body, retry = true } = {}) {
157
+ const retries = retry ? this.maxRetries : 0;
158
+ const { idempotencyKey, signal, ...rest } = params;
159
+ const query = new URLSearchParams();
160
+ for (const [k, v] of Object.entries(rest)) {
161
+ if (v === undefined || v === null || v === false) continue;
162
+ query.set(k, v === true ? "true" : Array.isArray(v) ? v.join(",") : String(v));
163
+ }
164
+ const qs = query.toString();
165
+ const url = this.baseURL + path + (qs ? "?" + qs : "");
166
+ const key = idempotencyKey ?? (retries ? randomKey() : undefined);
167
+ const headers = { Authorization: "Bearer " + this.apiKey, Accept: "application/json, text/markdown" };
168
+ if (key) headers["Idempotency-Key"] = key;
169
+ if (typeof window === "undefined") headers["User-Agent"] = "serpbit-js/" + VERSION;
170
+ const payload = body === undefined ? undefined : JSON.stringify(body);
171
+ if (payload !== undefined) headers["Content-Type"] = "application/json";
172
+
173
+ for (let attempt = 0; ; attempt++) {
174
+ const ctl = new AbortController();
175
+ const timer = setTimeout(() => ctl.abort(new Error("timed out")), this.timeout);
176
+ const onAbort = () => ctl.abort(signal.reason);
177
+ signal?.addEventListener("abort", onAbort, { once: true });
178
+ let resp;
179
+ try {
180
+ resp = await this.fetch(url, { method, headers, body: payload, signal: ctl.signal });
181
+ } catch (err) {
182
+ clearTimeout(timer);
183
+ signal?.removeEventListener("abort", onAbort);
184
+ if (signal?.aborted) throw err;
185
+ if (attempt < retries) {
186
+ await sleep(backoff(attempt));
187
+ continue;
188
+ }
189
+ throw new APIConnectionError(`could not reach ${this.baseURL}: ${err?.message ?? err}`);
190
+ }
191
+ const text = await resp.text().finally(() => {
192
+ clearTimeout(timer);
193
+ signal?.removeEventListener("abort", onAbort);
194
+ });
195
+ if (resp.ok) {
196
+ this.lastRequestId = resp.headers.get("X-Request-Id") ?? undefined;
197
+ const credits = resp.headers.get("X-Credits");
198
+ this.lastCredits = credits === null ? undefined : Number(credits);
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;
202
+ }
203
+ const ra = resp.headers.get("Retry-After");
204
+ const retryAfter = ra === null || Number.isNaN(Number(ra)) ? undefined : Number(ra);
205
+ if (RETRY.has(resp.status) && attempt < retries) {
206
+ await sleep(backoff(attempt, retryAfter));
207
+ continue;
208
+ }
209
+ let body = {};
210
+ try {
211
+ body = JSON.parse(text);
212
+ } catch {}
213
+ throw errorFor(resp.status, body.message || `the API answered ${resp.status}`, {
214
+ status: resp.status, code: body.error, requestId: body.request_id ?? resp.headers.get("X-Request-Id") ?? undefined,
215
+ body, retryAfter,
216
+ });
217
+ }
218
+ }
219
+ }
220
+
221
+ /**
222
+ * Whether a webhook's body is Serpbit's: its Serpbit-Signature header ("t=<unix>,v1=<hex>") is the HMAC-SHA256 of
223
+ * "t.body" with the API key that started the batch, sent within tolerance seconds. Pass the raw body as received.
224
+ */
225
+ export async function verifyWebhook(body, signature, apiKey, { tolerance = 300 } = {}) {
226
+ if (!signature || !apiKey) return false;
227
+ const parts = Object.fromEntries(String(signature).split(",").map((p) => p.split("=", 2)));
228
+ const ts = parts.t ?? "", sig = parts.v1 ?? "";
229
+ if (!/^\d+$/.test(ts) || !sig) return false;
230
+ if (tolerance && Math.abs(Date.now() / 1000 - Number(ts)) > tolerance) return false;
231
+ const subtle = globalThis.crypto?.subtle ?? (await import("node:crypto")).webcrypto.subtle;
232
+ const enc = new TextEncoder();
233
+ const raw = typeof body === "string" ? enc.encode(body) : new Uint8Array(body);
234
+ const key = await subtle.importKey("raw", enc.encode(apiKey), { name: "HMAC", hash: "SHA-256" }, false, ["sign"]);
235
+ const msg = new Uint8Array([...enc.encode(ts + "."), ...raw]);
236
+ const want = Array.from(new Uint8Array(await subtle.sign("HMAC", key, msg)), (b) => b.toString(16).padStart(2, "0")).join("");
237
+ if (want.length !== sig.length) return false;
238
+ let diff = 0;
239
+ for (let i = 0; i < want.length; i++) diff |= want.charCodeAt(i) ^ sig.charCodeAt(i);
240
+ return diff === 0;
241
+ }
242
+
243
+ function dropEmpty(o) {
244
+ return Object.fromEntries(Object.entries(o).filter(([, v]) => v !== undefined && v !== null));
245
+ }
246
+
247
+ function randomKey() {
248
+ if (globalThis.crypto?.randomUUID) return globalThis.crypto.randomUUID().replace(/-/g, "");
249
+ return Array.from({ length: 32 }, () => Math.floor(Math.random() * 16).toString(16)).join("");
250
+ }
251
+
252
+ function backoff(attempt, retryAfter) {
253
+ if (retryAfter !== undefined) return Math.min(retryAfter, 60) * 1000;
254
+ return Math.min(500 * 2 ** attempt, 8000) * (0.75 + Math.random() / 2);
255
+ }
256
+
257
+ const sleep = (ms) => new Promise((r) => setTimeout(r, ms));
258
+
259
+ export default Serpbit;
package/package.json CHANGED
@@ -1,6 +1,29 @@
1
1
  {
2
2
  "name": "serpbit",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.2.0",
4
+ "description": "Google Search, News, Shopping, Images, Videos, Maps, Autocomplete and AI Mode as data: the Serpbit API client.",
5
+ "type": "module",
6
+ "exports": {
7
+ ".": {
8
+ "types": "./index.d.ts",
9
+ "default": "./index.js"
10
+ }
11
+ },
12
+ "main": "./index.js",
13
+ "types": "./index.d.ts",
14
+ "files": ["index.js", "index.d.ts", "README.md", "LICENSE"],
15
+ "engines": {
16
+ "node": ">=18"
17
+ },
18
+ "scripts": {
19
+ "test": "node --test test/client.test.js"
20
+ },
21
+ "keywords": ["serp", "google search api", "serp api", "web search", "ai agents", "rag", "mcp"],
22
+ "homepage": "https://serpbit.com",
23
+ "bugs": {
24
+ "email": "support@serpbit.com"
25
+ },
26
+ "author": "Serpbit <support@serpbit.com>",
27
+ "license": "MIT",
28
+ "sideEffects": false
29
+ }