@mrscraper/sdk 5.0.0 → 6.0.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 CHANGED
@@ -1,259 +1,606 @@
1
- # @mrscraper/sdk
1
+ # MrScraper Node SDK
2
2
 
3
- ![](./mrscraper.jpeg)
3
+ ![MrScraper](./mrscraper.jpeg)
4
4
 
5
- Node.js SDK for [MrScraper](https://mrscraper.com) page scraping, Web Search, and account status. Requires Node.js 18 or newer and ES modules.
5
+ An async JavaScript and TypeScript SDK for the seven MrScraper services.
6
6
 
7
- ## Install and authenticate
7
+ ## Overview
8
+
9
+ Seven services share the same descriptions, parameter meanings, and defaults across the CLI, SDKs, and integrations. Names, types, authentication, and code examples follow each surface's conventions. See the [API Reference](https://docs.mrscraper.com/docs/api/overview).
10
+
11
+ | Service | Public name | Description |
12
+ | ----------------------------------- | ---------------- | ------------------------------------------------------------------------------------------------------------------------------- |
13
+ | [Status](#status) | `status` | Return the raw account status API response without summarizing, redacting body fields, or adding calculated fields. |
14
+ | [Scrape HTML](#scrape-html) | `scrapeHtml` | Retrieve the raw HTML of a page. Browser rendering is optional. |
15
+ | [Scrape Markdown](#scrape-markdown) | `scrapeMarkdown` | Retrieve a page as Markdown. Including HTML also enables browser rendering and returns both outputs as JSON. |
16
+ | [Get screenshot](#get-screenshot) | `getScreenshot` | Capture a base64 screenshot of the full page or top viewport. Browser rendering is always enabled. |
17
+ | [Scrape brand](#scrape-brand) | `scrapeBrand` | Extract a website's colors, typography, logos, and social links as JSON. |
18
+ | [Scrape JSON](#scrape-json) | `scrapeJson` | Extract structured JSON from a page using a natural-language prompt. Append Json Schema: and a JSON schema to shape the output. |
19
+ | [Web search](#web-search) | `webSearch` | Search the web and return ranked results with titles, URLs, descriptions, and sources. |
20
+
21
+ ## Installation
22
+
23
+ Requires Node.js 18 or newer. Examples use ES modules; save executable examples as `.mjs` files or set `"type": "module"` in your package.
8
24
 
9
25
  ```bash
10
26
  npm install @mrscraper/sdk
27
+ ```
28
+
29
+ ## Authentication
30
+
31
+ Obtain an API key from [the MrScraper app](https://app.mrscraper.com/api-tokens). API key used to authenticate the request.
32
+
33
+ ```bash
11
34
  export MRSCRAPER_API_TOKEN="YOUR_TOKEN"
12
35
  ```
13
36
 
14
- The SDK reads `MRSCRAPER_API_TOKEN` automatically. You can instead pass `token` in any call's options object. All functions are async and return `{ status_code, data, headers }`. JSON responses are parsed, HTML and other text remain strings, and binary responses are returned as Node.js `Buffer` values in `data`.
37
+ Each function accepts an optional `token: string` in its options. Precedence is a nonempty explicit token, `MRSCRAPER_API_TOKEN`, then `MRSCRAPER_API_KEY`. Credentials are sent in headers, never in the request URL.
15
38
 
16
- ## Public functions
39
+ ## Quickstart
17
40
 
18
- | Function | Purpose |
19
- |----------|---------|
20
- | `scraper_api(url, options?)` | Fetch a public web page as rendered HTML, Markdown, screenshot, or a combination |
21
- | `web_search(query, options?)` | Search the web for real-time results: website URLs, titles, and descriptions |
22
- | `account(options?)` | Read account identity, subscription, quota, and rate limits |
41
+ ```js
42
+ import { scrapeHtml } from "@mrscraper/sdk";
23
43
 
24
- The package also exports `MrScraperError` and the TypeScript types `ScraperApiOptions`, `ScraperApiData`, `WebSearchOptions`, `WebSearchResponse`, `WebSearchResult`, `AccountOptions`, `AccountSummary`, and `MrScraperResponse`.
44
+ const result = await scrapeHtml("https://example.com", {
45
+ browserRendering: true,
46
+ warmStart: true,
47
+ waitForSelector: "body",
48
+ timeout: 120,
49
+ maxRetries: 0,
50
+ });
51
+ console.log(result.data);
52
+ ```
25
53
 
26
- ### Migrating from 4.x to 5.0
54
+ Examples use `example.com` as the sample target. Replace it for your use case. Live scraping and search calls consume account quota.
27
55
 
28
- Version 5.0.0 returns to three public functions. The format-specific functions from 4.x (`scraper_html`, `scraper_markdown`, `get_screenshot`, `scraper_json`, `scraper_multiple_page`, `scraper_sitemap`, `scrape_brand`, and `get_brand`) and their option types are no longer exported. Use `scraper_api` with output flags instead:
56
+ Response examples show selected keys and types observed in live API responses. Values are placeholders; page content, base64 images, and arrays are abbreviated. Actual responses may contain additional fields.
29
57
 
30
- | 4.x call | 5.0 replacement |
31
- |----------|-----------------|
32
- | `scraper_html(url, options)` | `scraper_api(url, options)` |
33
- | `scraper_markdown(url, options)` | `scraper_api(url, { ...options, html: false, markdown: true })` |
34
- | `get_screenshot(url, { full_page: false })` | `scraper_api(url, { html: false, screenshot: true })` |
35
- | `web_search(query, { region: "us" })` | `web_search(query, { country: "us" })` |
36
- | `ScraperOptions` type | `ScraperApiOptions` |
58
+ ## Shared parameters
37
59
 
38
- Other changes:
60
+ ### Page controls
39
61
 
40
- - `scraper_api` sends a `GET` request with the target URL, page options, `maxRetries`, and `tokenCap` in the query string. Multiple outputs can be requested in one call.
41
- - A screenshot from `scraper_api` is a base64-encoded image (JPEG) in `data.screenshot`, not a `Buffer`.
42
- - `web_search` now calls the MrScraper API with `action: "websearch"`. Its first argument is the search query, and it accepts `country` and `num_results` (10 to 100). The `raw`, `format`, `region`, `language`, `page`, and `render_js` options and search URL input are removed. Results are returned as JSON.
43
- - `account` is unchanged.
62
+ HTML, Markdown, screenshots, and JSON extraction share `url`, `timeout`, `geoCode`, `proxyCountry`, `super`, `waitUntil`, `proxy`, `maxRetries`, and `saveResult` (using the naming style shown below). Page defaults are 300 seconds, US geolocation/proxy country, real-device routing off, and dashboard saving off. Omitted retry limits mean no limit. Exact types, defaults, and standard descriptions appear in each service table.
44
63
 
45
- ## Scraper API
64
+ ### Loading controls
46
65
 
47
- Fetch a public web page as rendered HTML, Markdown, screenshot, or a combination. Common controls support JavaScript rendering, geolocation, proxies, cookies, custom target headers, and waiting for page content.
66
+ HTML, Markdown, and screenshots additionally accept `blockResources`, `waitForSelector`, and `returnCookie`. JSON extraction does not accept these controls. Browser rendering is optional for HTML, Markdown, and JSON; screenshots always enable it. Markdown with HTML also enables browser rendering.
48
67
 
49
- ```typescript
50
- import { writeFile } from "node:fs/promises";
51
- import { scraper_api } from "@mrscraper/sdk";
68
+ ## Service reference
69
+
70
+ ### Status
71
+
72
+ #### Description
73
+
74
+ Return the raw account status API response without summarizing, redacting body fields, or adding calculated fields.
75
+
76
+ #### Parameters
52
77
 
53
- const html = await scraper_api("https://books.toscrape.com/");
54
- console.log(html.data); // HTML string
78
+ This service takes no service parameters. Authentication is configured separately.
55
79
 
56
- const combined = await scraper_api("https://books.toscrape.com/", {
80
+ The HTTP deadline is fixed at 600 seconds. It is not a service parameter.
81
+
82
+ #### Example
83
+
84
+ ```js
85
+ import { status } from "@mrscraper/sdk";
86
+
87
+ const result = await status();
88
+ console.log(result.data);
89
+ ```
90
+
91
+ #### Response
92
+
93
+ The API body contains message and data. Account details remain nested in data, including subscriptionItem and scraperAllowance. The response envelope therefore exposes account details at data.data. Sensitive response headers are removed.
94
+
95
+ **Success response**
96
+
97
+ ```json
98
+ {
99
+ "status_code": 200,
100
+ "data": {
101
+ "message": "Example response",
102
+ "data": {
103
+ "id": "ACCOUNT_ID",
104
+ "tokenLimit": 100000,
105
+ "tokenUsage": 2500,
106
+ "stripeStatus": "active",
107
+ "user": {
108
+ "name": "Example user",
109
+ "email": "user@example.com",
110
+ "isVerified": true
111
+ },
112
+ "subscriptionItem": {
113
+ "name": "Example plan",
114
+ "tokenLimit": 100000
115
+ },
116
+ "scraperAllowance": {
117
+ "remaining": 97500,
118
+ "plans": [
119
+ {
120
+ "remaining": 97500
121
+ }
122
+ ]
123
+ }
124
+ }
125
+ },
126
+ "headers": {
127
+ "content-type": "application/json; charset=utf-8"
128
+ }
129
+ }
130
+ ```
131
+
132
+ ### Scrape HTML
133
+
134
+ #### Description
135
+
136
+ Retrieve the raw HTML of a page. Browser rendering is optional.
137
+
138
+ #### Parameters
139
+
140
+ | Parameter | HTTP field | Type | Default | Description |
141
+ | ------------------ | ------------------ | ------------------------------------------------------------------ | -------------------- | ----------------------------------------------------------------------------------------------- |
142
+ | `url` | `url` | string | Required | Absolute HTTP or HTTPS URL of the page to process. |
143
+ | `timeout` | `timeout` | number (integer) | `300` | Page load timeout in seconds, from 1 to 300. The HTTP request allows 30 additional seconds. |
144
+ | `geoCode` | `geoCode` | string | `"us"` | Two-letter country code to load the page from, sent in lowercase. |
145
+ | `proxyCountry` | `proxyCountry` | string | `"us"` | Two-letter country code of the proxy server, sent in lowercase. |
146
+ | `super` | `super` | boolean | `false` | Whether to route the request through real devices. |
147
+ | `waitUntil` | `waitUntil` | string: `domcontentloaded`, `load`, `networkidle0`, `networkidle2` | `"domcontentloaded"` | Navigation completion event to wait for: domcontentloaded, load, networkidle0, or networkidle2. |
148
+ | `proxy` | `proxy` | string | Omitted | Custom proxy URL used to load the page. |
149
+ | `maxRetries` | `maxRetries` | number (integer) | Omitted | Maximum number of retries, as a nonnegative integer. Omit this parameter for no limit. |
150
+ | `saveResult` | `saveResult` | boolean | `false` | Whether to save the result to the dashboard Result tab. |
151
+ | `blockResources` | `blockResources` | boolean | `false` | Whether to block images, fonts, and stylesheets while loading the page. |
152
+ | `waitForSelector` | `waitForSelector` | string | Omitted | Wait for the page to contain the specified CSS selector before returning the result. |
153
+ | `returnCookie` | `returnCookie` | boolean | `false` | Whether to include browser session cookies in the response. |
154
+ | `browserRendering` | `browserRendering` | boolean | `false` | Whether to render the page in a browser before returning the result. |
155
+ | `warmStart` | `warmStart` | boolean | `false` | Whether to enable warm start for more reliable scraping, at the cost of additional latency. |
156
+
157
+ #### Example
158
+
159
+ ```js
160
+ import { scrapeHtml } from "@mrscraper/sdk";
161
+
162
+ const result = await scrapeHtml("https://example.com", {
163
+ browserRendering: true,
164
+ warmStart: true,
165
+ waitForSelector: "body",
166
+ timeout: 120,
167
+ maxRetries: 0,
168
+ });
169
+ console.log(result.data);
170
+ ```
171
+
172
+ #### Response
173
+
174
+ The default response body is HTML text. Additional controls can cause the API to return JSON; the returned structure is preserved.
175
+
176
+ **Success response**
177
+
178
+ ```json
179
+ {
180
+ "status_code": 200,
181
+ "data": "<html><body>Example page content...</body></html>",
182
+ "headers": {
183
+ "content-type": "text/html; charset=utf-8"
184
+ }
185
+ }
186
+ ```
187
+
188
+ ### Scrape Markdown
189
+
190
+ #### Description
191
+
192
+ Retrieve a page as Markdown. Including HTML also enables browser rendering and returns both outputs as JSON.
193
+
194
+ #### Parameters
195
+
196
+ | Parameter | HTTP field | Type | Default | Description |
197
+ | ------------------ | ------------------ | ------------------------------------------------------------------ | -------------------- | ----------------------------------------------------------------------------------------------- |
198
+ | `url` | `url` | string | Required | Absolute HTTP or HTTPS URL of the page to process. |
199
+ | `timeout` | `timeout` | number (integer) | `300` | Page load timeout in seconds, from 1 to 300. The HTTP request allows 30 additional seconds. |
200
+ | `geoCode` | `geoCode` | string | `"us"` | Two-letter country code to load the page from, sent in lowercase. |
201
+ | `proxyCountry` | `proxyCountry` | string | `"us"` | Two-letter country code of the proxy server, sent in lowercase. |
202
+ | `super` | `super` | boolean | `false` | Whether to route the request through real devices. |
203
+ | `waitUntil` | `waitUntil` | string: `domcontentloaded`, `load`, `networkidle0`, `networkidle2` | `"domcontentloaded"` | Navigation completion event to wait for: domcontentloaded, load, networkidle0, or networkidle2. |
204
+ | `proxy` | `proxy` | string | Omitted | Custom proxy URL used to load the page. |
205
+ | `maxRetries` | `maxRetries` | number (integer) | Omitted | Maximum number of retries, as a nonnegative integer. Omit this parameter for no limit. |
206
+ | `saveResult` | `saveResult` | boolean | `false` | Whether to save the result to the dashboard Result tab. |
207
+ | `blockResources` | `blockResources` | boolean | `false` | Whether to block images, fonts, and stylesheets while loading the page. |
208
+ | `waitForSelector` | `waitForSelector` | string | Omitted | Wait for the page to contain the specified CSS selector before returning the result. |
209
+ | `returnCookie` | `returnCookie` | boolean | `false` | Whether to include browser session cookies in the response. |
210
+ | `browserRendering` | `browserRendering` | boolean | `false` | Whether to render the page in a browser before returning the result. |
211
+ | `warmStart` | `warmStart` | boolean | `false` | Whether to enable warm start for more reliable scraping, at the cost of additional latency. |
212
+ | `html` | `html` | boolean | `false` | Whether to include the page HTML in the response. |
213
+
214
+ #### Example
215
+
216
+ ```js
217
+ import { scrapeMarkdown } from "@mrscraper/sdk";
218
+
219
+ const result = await scrapeMarkdown("https://example.com", {
57
220
  html: true,
221
+ warmStart: true,
222
+ });
223
+ console.log(result.data);
224
+ ```
225
+
226
+ #### Response
227
+
228
+ The default response body is Markdown text. Enabling HTML returns JSON containing both HTML and Markdown.
229
+
230
+ **With html enabled**
231
+
232
+ ```json
233
+ {
234
+ "status_code": 200,
235
+ "data": {
236
+ "html": "<html>...</html>",
237
+ "markdown": "# Example page\n\n..."
238
+ },
239
+ "headers": {
240
+ "content-type": "application/json"
241
+ }
242
+ }
243
+ ```
244
+
245
+ **Default Markdown text**
246
+
247
+ ```json
248
+ {
249
+ "status_code": 200,
250
+ "data": "# Example page\n\nExample Markdown content...",
251
+ "headers": {
252
+ "content-type": "text/markdown; charset=utf-8"
253
+ }
254
+ }
255
+ ```
256
+
257
+ ### Get screenshot
258
+
259
+ #### Description
260
+
261
+ Capture a base64 screenshot of the full page or top viewport. Browser rendering is always enabled.
262
+
263
+ #### Parameters
264
+
265
+ | Parameter | HTTP field | Type | Default | Description |
266
+ | ----------------- | ----------------- | ------------------------------------------------------------------ | -------------------- | ----------------------------------------------------------------------------------------------- |
267
+ | `url` | `url` | string | Required | Absolute HTTP or HTTPS URL of the page to process. |
268
+ | `timeout` | `timeout` | number (integer) | `300` | Page load timeout in seconds, from 1 to 300. The HTTP request allows 30 additional seconds. |
269
+ | `geoCode` | `geoCode` | string | `"us"` | Two-letter country code to load the page from, sent in lowercase. |
270
+ | `proxyCountry` | `proxyCountry` | string | `"us"` | Two-letter country code of the proxy server, sent in lowercase. |
271
+ | `super` | `super` | boolean | `false` | Whether to route the request through real devices. |
272
+ | `waitUntil` | `waitUntil` | string: `domcontentloaded`, `load`, `networkidle0`, `networkidle2` | `"domcontentloaded"` | Navigation completion event to wait for: domcontentloaded, load, networkidle0, or networkidle2. |
273
+ | `proxy` | `proxy` | string | Omitted | Custom proxy URL used to load the page. |
274
+ | `maxRetries` | `maxRetries` | number (integer) | Omitted | Maximum number of retries, as a nonnegative integer. Omit this parameter for no limit. |
275
+ | `saveResult` | `saveResult` | boolean | `false` | Whether to save the result to the dashboard Result tab. |
276
+ | `blockResources` | `blockResources` | boolean | `false` | Whether to block images, fonts, and stylesheets while loading the page. |
277
+ | `waitForSelector` | `waitForSelector` | string | Omitted | Wait for the page to contain the specified CSS selector before returning the result. |
278
+ | `returnCookie` | `returnCookie` | boolean | `false` | Whether to include browser session cookies in the response. |
279
+ | `screenshot` | `screenshot` | string: `full`, `top` | `"full"` | Screenshot area to capture: full for the entire page or top for the top viewport. |
280
+ | `html` | `html` | boolean | `true` | Whether to include the page HTML in the response. |
281
+ | `markdown` | `markdown` | boolean | `false` | Whether to include the page Markdown in the response. |
282
+
283
+ #### Example
284
+
285
+ ```js
286
+ import { getScreenshot } from "@mrscraper/sdk";
287
+
288
+ const result = await getScreenshot("https://example.com", {
289
+ screenshot: "top",
290
+ html: false,
58
291
  markdown: true,
59
- screenshot: true,
60
- proxy_country: "us",
61
292
  });
62
- if (typeof combined.data !== "string") {
63
- console.log(combined.data.markdown);
64
- if (combined.data.screenshot) {
65
- await writeFile("page.jpg", Buffer.from(combined.data.screenshot, "base64"));
293
+ console.log(result.data);
294
+ ```
295
+
296
+ #### Response
297
+
298
+ The response body contains a base64 screenshot and requested page outputs. The API can still include HTML when HTML output is disabled.
299
+
300
+ **Success response**
301
+
302
+ ```json
303
+ {
304
+ "status_code": 200,
305
+ "data": {
306
+ "html": "<html>...</html>",
307
+ "screenshot": "BASE64_PNG_DATA",
308
+ "markdown": "# Example page\n\n..."
309
+ },
310
+ "headers": {
311
+ "content-type": "application/json; charset=utf-8"
66
312
  }
67
313
  }
68
314
  ```
69
315
 
70
- Requesting only HTML (the default) returns the page as a string. Requesting Markdown or a screenshot returns an object with an entry for each requested output, such as `{ html, markdown, screenshot }`, where `screenshot` is a base64-encoded JPEG image. At least one of `html`, `markdown`, or `screenshot` must be `true`.
316
+ ### Scrape brand
71
317
 
72
- The SDK sends a `GET` request to `https://api.mrscraper.com` with the API token in the `x-api-token` header and every option, including the target `url`, in the query string:
318
+ #### Description
73
319
 
74
- ```bash
75
- curl --get 'https://api.mrscraper.com' \
76
- --header 'x-api-token: {MRSCRAPER_API_TOKEN}' \
77
- --data-urlencode 'token={MRSCRAPER_API_TOKEN}' \
78
- --data-urlencode 'url=https://books.toscrape.com/' \
79
- --data-urlencode 'html=true' \
80
- --data-urlencode 'markdown=false' \
81
- --data-urlencode 'timeout=120' \
82
- --data-urlencode 'geoCode=US' \
83
- --data-urlencode 'maxRetries=3'
320
+ Extract a website's colors, typography, logos, and social links as JSON.
321
+
322
+ #### Parameters
323
+
324
+ | Parameter | HTTP field | Type | Default | Description |
325
+ | --------- | ---------- | ------ | -------- | -------------------------------------------------- |
326
+ | `url` | `url` | string | Required | Absolute HTTP or HTTPS URL of the page to process. |
327
+
328
+ The HTTP deadline is fixed at 120 seconds. It is not a service parameter.
329
+
330
+ The request uses `action=brand-scraping` and `bundle=none`; page controls are not accepted.
331
+
332
+ #### Example
333
+
334
+ ```js
335
+ import { scrapeBrand } from "@mrscraper/sdk";
336
+
337
+ const result = await scrapeBrand("https://example.com");
338
+ console.log(result.data);
84
339
  ```
85
340
 
86
- | Option | Default | Description |
87
- |--------|---------|-------------|
88
- | `token` | Environment variable | API token override |
89
- | `html`, `markdown`, `screenshot` | `true`, `false`, `false` | Outputs to return; combine as needed. `screenshot: true` enables browser rendering. |
90
- | `timeout` | `120` | Page timeout in seconds, from 1 to 300; the HTTP timeout is 30 seconds longer |
91
- | `geo_code`, `proxy_country` | `"US"`, unset | Geolocation country code and optional proxy country |
92
- | `browser_rendering` | unset | `true` to force a browser, `false` to disable it, unset for automatic selection |
93
- | `super` | `false` | Enable real device routing |
94
- | `use_proxy`, `proxy` | `true`, unset | Allow a proxy or supply `username:password@host:port` |
95
- | `home_page` | `false` | Visit the site's root before the target page (sent as `warmStart`) |
96
- | `wait_for_selector`, `wait_until` | unset | Wait for a CSS selector or a page lifecycle event such as `"domcontentloaded"` |
97
- | `block_resources`, `bypass_proxy` | `false`, `false` | Block images, CSS, and fonts, or enable proxy bypass behavior |
98
- | `cookie_jar`, `headers` | unset | Cookie configuration string and target request headers; `headers` accepts an object or JSON string |
99
- | `max_retries`, `token_cap` | `3`, unset | Nonnegative integer retry count and optional token budget |
100
- | `stream` | unset | Request a streamed response, buffered into the normal return value |
101
- | `discard_token_secret` | `""` | Value for the `x-discard-token-secret` request header |
102
-
103
- Unset options use the service defaults. Explicit `false`, `0`, and empty strings are preserved where supported.
104
-
105
- ## Web Search
106
-
107
- Search the web for real-time results: website URLs, titles, and descriptions.
108
-
109
- ```typescript
110
- import { web_search } from "@mrscraper/sdk";
111
-
112
- const result = await web_search("e-menessaptieka.lv linkedin", {
113
- country: "us",
114
- num_results: 10,
115
- });
116
- for (const item of result.data.data) {
117
- console.log(item.rank, item.title, item.url);
341
+ #### Response
342
+
343
+ The API body contains message and a data object with job_id, status, url, final_url, brand, and error. Brand details are available at data.data.brand in the response envelope.
344
+
345
+ **Success response**
346
+
347
+ ```json
348
+ {
349
+ "status_code": 200,
350
+ "data": {
351
+ "data": {
352
+ "job_id": "JOB_ID",
353
+ "status": "succeeded",
354
+ "url": "https://example.com",
355
+ "final_url": "https://example.com",
356
+ "brand": {
357
+ "name": "Example brand",
358
+ "colors": {
359
+ "background": "#ffffff",
360
+ "text": "#222222"
361
+ },
362
+ "typography": {
363
+ "body": {
364
+ "font_family": "Example font"
365
+ }
366
+ }
367
+ },
368
+ "error": null,
369
+ "bundle_url": null
370
+ },
371
+ "message": "Example response"
372
+ },
373
+ "headers": {
374
+ "content-type": "application/json"
375
+ }
118
376
  }
119
377
  ```
120
378
 
121
- The SDK sends this request:
379
+ ### Scrape JSON
122
380
 
123
- ```bash
124
- curl --location 'https://api.mrscraper.com' \
125
- --header 'x-api-token: {MRSCRAPER_API_TOKEN}' \
126
- --header 'Content-Type: application/json' \
127
- --data '{
128
- "action": "websearch",
129
- "query": "e-menessaptieka.lv linkedin",
130
- "country": "us",
131
- "numResults": 10
132
- }'
381
+ #### Description
382
+
383
+ Extract structured JSON from a page using a natural-language prompt. Append Json Schema: and a JSON schema to shape the output.
384
+
385
+ #### Parameters
386
+
387
+ | Parameter | HTTP field | Type | Default | Description |
388
+ | ------------------ | ------------------ | ------------------------------------------------------------------ | --------------------------------------------- | ------------------------------------------------------------------------------------------------------- |
389
+ | `url` | `url` | string | Required | Absolute HTTP or HTTPS URL of the page to process. |
390
+ | `timeout` | `timeout` | number (integer) | `300` | Page load timeout in seconds, from 1 to 300. The HTTP request allows 30 additional seconds. |
391
+ | `geoCode` | `geoCode` | string | `"us"` | Two-letter country code to load the page from, sent in lowercase. |
392
+ | `proxyCountry` | `proxyCountry` | string | `"us"` | Two-letter country code of the proxy server, sent in lowercase. |
393
+ | `super` | `super` | boolean | `false` | Whether to route the request through real devices. |
394
+ | `waitUntil` | `waitUntil` | string: `domcontentloaded`, `load`, `networkidle0`, `networkidle2` | `"domcontentloaded"` | Navigation completion event to wait for: domcontentloaded, load, networkidle0, or networkidle2. |
395
+ | `proxy` | `proxy` | string | Omitted | Custom proxy URL used to load the page. |
396
+ | `maxRetries` | `maxRetries` | number (integer) | Omitted | Maximum number of retries, as a nonnegative integer. Omit this parameter for no limit. |
397
+ | `saveResult` | `saveResult` | boolean | `false` | Whether to save the result to the dashboard Result tab. |
398
+ | `prompt` | `prompt` | string | `"Extract all data as complete as possible."` | Instructions describing the data to extract. Append Json Schema: and a JSON schema to shape the output. |
399
+ | `browserRendering` | `browserRendering` | boolean | `false` | Whether to render the page in a browser before returning the result. |
400
+ | `html` | `html` | boolean | `false` | Whether to include the page HTML in the response. |
401
+ | `screenshot` | `screenshot` | boolean | `false` | Whether to include a base64 screenshot in the response. |
402
+
403
+ The request uses `agent=general` and GET. If the encoded URL exceeds 8,000 characters, it switches to POST with `url`, `prompt`, and `agent` in the body; page controls remain in the query.
404
+
405
+ #### Example
406
+
407
+ ```js
408
+ import { scrapeJson } from "@mrscraper/sdk";
409
+
410
+ const result = await scrapeJson("https://example.com", {
411
+ prompt:
412
+ 'Extract the first 2 items with title and price. Json Schema: {"type":"array","items":{"type":"object","properties":{"title":{"type":"string"},"price":{"type":"string"}},"required":["title","price"]}}',
413
+ browserRendering: true,
414
+ });
415
+ console.log(result.data);
133
416
  ```
134
417
 
135
- `result.data` is a `WebSearchResponse` with `success`, `message`, and `data`. Each item in `data` is a `WebSearchResult` with `rank`, `title`, `url`, `description`, and `source`.
418
+ #### Response
419
+
420
+ Extraction results are in the API body's data field and follow the requested schema. Response metadata includes thread_id, token_usage, status, error, runtime, and cookies. html, markdown, and screenshot can be empty strings when not requested.
421
+
422
+ **Success response**
423
+
424
+ ```json
425
+ {
426
+ "status_code": 200,
427
+ "data": {
428
+ "success": true,
429
+ "data": [
430
+ {
431
+ "title": "Example item",
432
+ "price": "10.00"
433
+ }
434
+ ],
435
+ "thread_id": "THREAD_ID",
436
+ "token_usage": 1,
437
+ "html": "",
438
+ "markdown": "",
439
+ "screenshot": "",
440
+ "status": "Results ready",
441
+ "error": "",
442
+ "runtime": 1.23,
443
+ "cookies": []
444
+ },
445
+ "headers": {
446
+ "content-type": "application/json"
447
+ }
448
+ }
449
+ ```
450
+
451
+ ### Web search
452
+
453
+ #### Description
454
+
455
+ Search the web and return ranked results with titles, URLs, descriptions, and sources.
136
456
 
137
- | Option | Default | Description |
138
- |--------|---------|-------------|
139
- | `query` | Required first argument | The search query; must not be empty |
140
- | `token` | Environment variable | API token override |
141
- | `country` | unset | Country code for localized results, such as `"us"`; omitted to use the service default |
142
- | `num_results` | `10` | Number of results, an integer from 10 to 100 (sent as `numResults`) |
143
- | `timeout` | `600` | HTTP request timeout in seconds |
457
+ #### Parameters
144
458
 
145
- ## Account status
459
+ | Parameter | HTTP field | Type | Default | Description |
460
+ | ------------ | ------------ | ---------------- | -------- | ------------------------------------------------------------------------------------------------- |
461
+ | `query` | `query` | string | Required | Search query text, trimmed before sending, containing 1 to 1000 characters. |
462
+ | `country` | `country` | string | `"us"` | Two-letter country code to search from, sent in lowercase. |
463
+ | `numResults` | `numResults` | number (integer) | `10` | Number of search results to request, as an integer from 10 to 100. Fewer results may be returned. |
146
464
 
147
- Account returns an overview of the account associated with your API token, including user identity, subscription status, token usage, remaining quota, and rate limits. Use it to monitor consumption and check available tokens before running scraping or search jobs.
465
+ The HTTP deadline is fixed at 120 seconds. It is not a service parameter.
148
466
 
149
- ```typescript
150
- import { account } from "@mrscraper/sdk";
467
+ #### Example
151
468
 
152
- const result = await account(); // Optional: { token: "YOUR_TOKEN", timeout: 30 }
153
- console.log(result.data.subscription_status);
154
- console.log(result.data.token_remaining);
155
- console.log(result.data.user.email);
469
+ ```js
470
+ import { webSearch } from "@mrscraper/sdk";
471
+
472
+ const result = await webSearch("site:example.com documentation", {
473
+ country: "id",
474
+ numResults: 20,
475
+ });
476
+ console.log(result.data);
477
+ ```
478
+
479
+ #### Response
480
+
481
+ The API body contains success, message, a data array, and tokenUsage. Each result includes rank, title, url, description, and source.
482
+
483
+ **Success response**
484
+
485
+ ```json
486
+ {
487
+ "status_code": 200,
488
+ "data": {
489
+ "success": true,
490
+ "message": "Example response",
491
+ "data": [
492
+ {
493
+ "rank": 1,
494
+ "title": "Example result",
495
+ "url": "https://example.com",
496
+ "description": "Example result description.",
497
+ "source": "example.com"
498
+ }
499
+ ],
500
+ "tokenUsage": 1
501
+ },
502
+ "headers": {
503
+ "content-type": "application/json; charset=utf-8"
504
+ }
505
+ }
506
+ ```
507
+
508
+ ## Response format
509
+
510
+ Successful services use an envelope containing `status_code`, `data`, and `headers`. The `data` field contains the API response body; its field names are not converted to the SDK's naming style. Status preserves the complete body without adding summary fields.
511
+
512
+ ```json
513
+ {
514
+ "status_code": 200,
515
+ "data": "<html><body>Example page content...</body></html>",
516
+ "headers": {
517
+ "content-type": "text/html; charset=utf-8"
518
+ }
519
+ }
156
520
  ```
157
521
 
158
- `account` checks the account associated with the configured API token. The timeout defaults to 30 seconds
159
- and must be positive. `data` is an `AccountSummary` with `subscription_status`,
160
- `enterprise`, `token_usage`, `token_limit`, `token_remaining`, `usage_percent`,
161
- `rate_limit`, `rate_ttl`, `auto_renew`, `ends_at`, and `user` (`name`, `email`,
162
- `verified`). Remaining tokens are clamped to zero when usage exceeds the limit.
163
- API keys, billing identifiers, and sensitive response headers are excluded.
522
+ Responses are `MrScraperResponse<T>` objects. JSON becomes JavaScript values, text remains `string`, and binary remains `Buffer`. Sensitive response headers are removed for status.
164
523
 
165
- ## Errors and types
524
+ ## Error handling
166
525
 
167
- All functions reject with `MrScraperError` for API, authentication, network, and timeout errors. `status` contains the HTTP status for API errors and is `undefined` for network errors. Invalid options throw `TypeError` or `RangeError` before any request is sent.
526
+ Authentication, HTTP, network, and timeout failures throw `MrScraperError`. Its `status` property is the HTTP status when available. Invalid arguments throw `TypeError` or `RangeError` before the request.
168
527
 
169
- ```typescript
170
- import { scraper_api, MrScraperError } from "@mrscraper/sdk";
171
- import type { MrScraperResponse, ScraperApiData } from "@mrscraper/sdk";
528
+ ```js
529
+ import { scrapeHtml, MrScraperError } from "@mrscraper/sdk";
172
530
 
173
531
  try {
174
- const result: MrScraperResponse<ScraperApiData> = await scraper_api("https://example.com");
175
- console.log(result.data);
532
+ await scrapeHtml("https://example.com");
176
533
  } catch (error) {
177
- if (error instanceof MrScraperError) {
534
+ if (error instanceof MrScraperError)
178
535
  console.error(error.status, error.message);
179
- } else {
180
- throw error;
181
- }
536
+ else throw error;
182
537
  }
183
538
  ```
184
539
 
185
- ## Develop
540
+ ## Integration features
186
541
 
187
- ```bash
188
- npm ci
189
- npm test
190
- npm run build
191
- ```
542
+ ### Configuration
192
543
 
193
- `npm test` builds the SDK, checks TypeScript usage, and runs response-mock and local HTTP contract tests. It does not call the live API or require a token.
544
+ Functions return promises and use camelCase options. Omit optional controls or use `undefined`; explicit `false` and `0` are preserved. TypeScript exports include `PageOptions`, `HtmlOptions`, `MarkdownOptions`, `ScreenshotOptions`, `JsonOptions`, `WebSearchOptions`, `StatusOptions`, and `MrScraperResponse<T>`.
194
545
 
195
- ## Manual tests with a real token
546
+ ### Advanced usage
196
547
 
197
- Run these commands from a source checkout. Build the SDK and configure your API token:
548
+ Supply a generic response body type when you know the returned API shape:
198
549
 
199
- ```bash
200
- npm run build
201
- export MRSCRAPER_API_TOKEN="YOUR_TOKEN"
550
+ ```ts
551
+ import { scrapeJson } from "@mrscraper/sdk";
552
+ const result = await scrapeJson<{ data: { title: string } }>(
553
+ "https://example.com",
554
+ { prompt: "Extract the page title" },
555
+ );
556
+ console.log(result.data.data.title);
202
557
  ```
203
558
 
204
- The `file.js` helper calls the three public functions against the live API:
559
+ Save screenshot JSON as an image when the API returns a base64 screenshot:
205
560
 
206
- ```bash
207
- node file.js --help
208
- node file.js # account, scraper_api (HTML), and web_search
209
- node file.js account
210
- node file.js scraper_api "https://books.toscrape.com/"
211
- node file.js scraper_api "https://books.toscrape.com/" '{"markdown":true,"screenshot":true}'
212
- node file.js web_search "e-menessaptieka.lv linkedin" '{"country":"us","num_results":10}'
561
+ ```js
562
+ import { getScreenshot } from "@mrscraper/sdk";
563
+ import { writeFile } from "node:fs/promises";
564
+ const result = await getScreenshot("https://example.com");
565
+ if (
566
+ typeof result.data === "object" &&
567
+ typeof result.data?.screenshot === "string"
568
+ ) {
569
+ await writeFile("page.png", Buffer.from(result.data.screenshot, "base64"));
570
+ }
213
571
  ```
214
572
 
215
- Screenshots are saved under `manual-results/`; other responses are previewed. You can also call the built SDK directly:
573
+ ### Troubleshooting
216
574
 
217
- ```bash
218
- node --input-type=module <<'NODE'
219
- import { account } from "./dist/index.js";
575
+ Check environment credentials when authentication fails. Use camelCase option names and `super`, rather than old snake_case options or `superMode`. Page timeouts are integers from 1 to 300; status and search do not expose timeout options.
220
576
 
221
- const result = await account();
222
- console.log(result.status_code, result.data);
223
- NODE
224
- ```
577
+ ## Migration
225
578
 
226
- These commands make live API requests, print the HTTP status and response data, and exit with a nonzero status on errors. To run the other examples from a checkout, replace imports from `@mrscraper/sdk` with `./dist/index.js`.
579
+ Replace `account()` with `status()` and read the raw API body. Remove status/search timeout options and rename `superMode` to `super`. Replace combined scraper calls with `scrapeHtml`, `scrapeMarkdown`, or `getScreenshot`; use camelCase options. Replace `full_page` with `screenshot: "full"` or `"top"`. Search uses `query`, `country`, and `numResults`.
227
580
 
228
- ## Publish manually to npm
581
+ ## Development and testing
229
582
 
230
- This checkout prepares version **5.0.0**, a major release that removes the 4.x
231
- format-specific functions. Publishing remains manual. Validate and preview the package:
583
+ ### Automated checks
584
+
585
+ The automated suite checks service behavior without production API calls.
232
586
 
233
587
  ```bash
234
588
  npm ci
235
589
  npm test
236
- npm pack --dry-run
237
- npm publish --dry-run --access public
590
+ npm run build
238
591
  ```
239
592
 
240
- The package includes `dist/`, `README.md`, `LICENSE`, `mrscraper.jpeg`, and
241
- `package.json`. The `files` list excludes the local `file.js` helper. Commit
242
- and push the release files, then publish with your npm account:
593
+ ### Manual checks
594
+
595
+ The following commands call the live API using your credentials and consume quota.
243
596
 
244
597
  ```bash
245
- npm login
246
- npm whoami
247
- npm publish --access public
248
- npm view @mrscraper/sdk version
249
- npm view @mrscraper/sdk dist-tags --json
598
+ npm run build
599
+ node file.js status
600
+ node file.js scrapeHtml https://example.com
601
+ node file.js webSearch "site:example.com documentation"
250
602
  ```
251
603
 
252
- Complete npm's browser login and two-factor authentication prompts. The
253
- `prepublishOnly` script rebuilds `dist` before publishing. Each version can be
254
- published only once. For later releases, update `package.json` and
255
- `package-lock.json` together with a new version before validating and publishing.
256
-
257
604
  ## License
258
605
 
259
- MIT — see [LICENSE](./LICENSE).
606
+ MIT. See [LICENSE](./LICENSE).