@mrscraper/sdk 5.0.0 → 6.1.1

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,595 @@
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 clean Markdown. Browser rendering is optional. |
16
+ | [Get screenshot](#get-screenshot) | `getScreenshot` | Capture a base64 PNG screenshot of the full page, the first viewport, or a custom 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`, `waitForSelector`, `geoCode`, `maxAge`, and `maxRetries` (using the naming style shown below). Defaults are a 300-second timeout (up to 330) and a `maxAge` of 0 milliseconds, which always scrapes fresh; `maxAge` accepts up to 604800000 (7 days). `geoCode` and `maxRetries` are omitted unless set, so the API loads the page from the United States with no retry limit. Results are always saved to the dashboard (`saveResult=true`), and `tokenCap` is never sent. 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 JSON extraction also accept `browserRendering`, `warmStart`, and `blockResources`; HTML and Markdown also accept `action`. `browserRendering` is omitted unless set: the API loads the page without a browser first and switches to one if the request is blocked, while `true` always renders and `false` never does. Screenshots always render in a browser: Get screenshot sends `browserRendering=true`, and so does Scrape HTML whenever a screenshot is set.
48
67
 
49
- ```typescript
50
- import { writeFile } from "node:fs/promises";
51
- import { scraper_api } from "@mrscraper/sdk";
68
+ ### Fixed request fields
52
69
 
53
- const html = await scraper_api("https://books.toscrape.com/");
54
- console.log(html.data); // HTML string
70
+ Each service adds its documented fixed fields automatically, so they are not service parameters: `html=true` and `markdown=false` for HTML (plus `browserRendering=true` when a screenshot is set), `markdown=true`, `html=false`, and `screenshot=false` for Markdown, `browserRendering=true`, `html=false`, and `markdown=false` for screenshots, `action=brand-scraping` and `bundle=none` for brand, `agent=general` for JSON extraction, and `action=websearch` for search. HTML, Markdown, screenshots, and JSON extraction also always send `saveResult=true`.
55
71
 
56
- const combined = await scraper_api("https://books.toscrape.com/", {
57
- html: true,
58
- markdown: true,
59
- screenshot: true,
60
- proxy_country: "us",
61
- });
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"));
72
+ ## Service reference
73
+
74
+ ### Status
75
+
76
+ #### Description
77
+
78
+ Return the raw account status API response without summarizing, redacting body fields, or adding calculated fields.
79
+
80
+ #### Parameters
81
+
82
+ This service takes no service parameters. Authentication is configured separately.
83
+
84
+ The HTTP deadline is fixed at 600 seconds. It is not a service parameter.
85
+
86
+ #### Example
87
+
88
+ ```js
89
+ import { status } from "@mrscraper/sdk";
90
+
91
+ const result = await status();
92
+ console.log(result.data);
93
+ ```
94
+
95
+ #### Response
96
+
97
+ 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.
98
+
99
+ **Success response**
100
+
101
+ ```json
102
+ {
103
+ "status_code": 200,
104
+ "data": {
105
+ "message": "Example response",
106
+ "data": {
107
+ "id": "ACCOUNT_ID",
108
+ "tokenLimit": 100000,
109
+ "tokenUsage": 2500,
110
+ "stripeStatus": "active",
111
+ "user": {
112
+ "name": "Example user",
113
+ "email": "user@example.com",
114
+ "isVerified": true
115
+ },
116
+ "subscriptionItem": {
117
+ "name": "Example plan",
118
+ "tokenLimit": 100000
119
+ },
120
+ "scraperAllowance": {
121
+ "remaining": 97500,
122
+ "plans": [
123
+ {
124
+ "remaining": 97500
125
+ }
126
+ ]
127
+ }
128
+ }
129
+ },
130
+ "headers": {
131
+ "content-type": "application/json; charset=utf-8"
66
132
  }
67
133
  }
68
134
  ```
69
135
 
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`.
136
+ ### Scrape HTML
71
137
 
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:
138
+ #### Description
73
139
 
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'
140
+ Retrieve the raw HTML of a page. Browser rendering is optional.
141
+
142
+ #### Parameters
143
+
144
+ | Parameter | HTTP field | Type | Default | Description |
145
+ | ------------------ | ------------------ | ----------------- | -------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
146
+ | `url` | `url` | string | Required | Absolute HTTP or HTTPS URL of the page to process. |
147
+ | `browserRendering` | `browserRendering` | boolean | Omitted | Whether to load the page in a browser: true always does and false never does. Omit it to load the page without a browser first and switch to a browser automatically if the request is blocked. |
148
+ | `timeout` | `timeout` | number (integer) | `300` | Maximum seconds to wait for the scrape, from 1 to 330. The HTTP request allows 30 additional seconds. |
149
+ | `warmStart` | `warmStart` | boolean | `false` | Whether to open the site's home page first to warm the session before loading the target URL. |
150
+ | `blockResources` | `blockResources` | boolean | `false` | Whether to block images, fonts, and stylesheets while loading the page. |
151
+ | `waitForSelector` | `waitForSelector` | string | Omitted | CSS selector or text to wait for on the page before returning the result, up to 500 characters. |
152
+ | `action` | `action` | string | Omitted | Scraper action that routes the request or simply flags it, useful for separating analytics per domain. |
153
+ | `geoCode` | `geoCode` | string | Omitted | Two-letter country code to load the page from, sent in lowercase. |
154
+ | `maxAge` | `maxAge` | number (integer) | `0` | Return a cached result of the same request when it is newer than the selected age. A cached result costs the same tokens as the original scrape. |
155
+ | `maxRetries` | `maxRetries` | number (integer) | Omitted | Maximum number of retries, as a nonnegative integer. Omit this parameter for no limit. |
156
+ | `screenshot` | `screenshot` | `false` or string | `false` | Screenshot to capture with the HTML: false for none, full for the entire page, top for the first viewport, or a WIDTHxHEIGHT viewport from 100 to 3840 pixels with an optional -ZOOM percent from 25 to 300, such as 1280x800 or 1920x1080-75. Setting a screenshot also sends browserRendering=true. |
157
+
158
+ The request uses `html=true`, `markdown=false`, and `saveResult=true`. The screenshot is optional; setting one also sends `browserRendering=true`, because a screenshot needs a rendered page, and the response becomes JSON with `html` and `screenshot`.
159
+
160
+ #### Example
161
+
162
+ ```js
163
+ import { scrapeHtml } from "@mrscraper/sdk";
164
+
165
+ const result = await scrapeHtml("https://example.com", {
166
+ browserRendering: true,
167
+ warmStart: true,
168
+ waitForSelector: "body",
169
+ timeout: 120,
170
+ maxRetries: 0,
171
+ });
172
+ console.log(result.data);
173
+ ```
174
+
175
+ #### Response
176
+
177
+ The response body is HTML text. With a screenshot, the API returns JSON containing html and a base64 screenshot.
178
+
179
+ **Default HTML text**
180
+
181
+ ```json
182
+ {
183
+ "status_code": 200,
184
+ "data": "<html><body>Example page content...</body></html>",
185
+ "headers": {
186
+ "content-type": "text/html; charset=utf-8"
187
+ }
188
+ }
189
+ ```
190
+
191
+ **With a screenshot**
192
+
193
+ ```json
194
+ {
195
+ "status_code": 200,
196
+ "data": {
197
+ "html": "<html>...</html>",
198
+ "screenshot": "BASE64_IMAGE_DATA"
199
+ },
200
+ "headers": {
201
+ "content-type": "application/json; charset=utf-8"
202
+ }
203
+ }
84
204
  ```
85
205
 
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,
206
+ ### Scrape Markdown
207
+
208
+ #### Description
209
+
210
+ Retrieve a page as clean Markdown. Browser rendering is optional.
211
+
212
+ #### Parameters
213
+
214
+ | Parameter | HTTP field | Type | Default | Description |
215
+ | ------------------ | ------------------ | ---------------- | -------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
216
+ | `url` | `url` | string | Required | Absolute HTTP or HTTPS URL of the page to process. |
217
+ | `browserRendering` | `browserRendering` | boolean | Omitted | Whether to load the page in a browser: true always does and false never does. Omit it to load the page without a browser first and switch to a browser automatically if the request is blocked. |
218
+ | `timeout` | `timeout` | number (integer) | `300` | Maximum seconds to wait for the scrape, from 1 to 330. The HTTP request allows 30 additional seconds. |
219
+ | `warmStart` | `warmStart` | boolean | `false` | Whether to open the site's home page first to warm the session before loading the target URL. |
220
+ | `blockResources` | `blockResources` | boolean | `false` | Whether to block images, fonts, and stylesheets while loading the page. |
221
+ | `waitForSelector` | `waitForSelector` | string | Omitted | CSS selector or text to wait for on the page before returning the result, up to 500 characters. |
222
+ | `action` | `action` | string | Omitted | Scraper action that routes the request or simply flags it, useful for separating analytics per domain. |
223
+ | `geoCode` | `geoCode` | string | Omitted | Two-letter country code to load the page from, sent in lowercase. |
224
+ | `maxAge` | `maxAge` | number (integer) | `0` | Return a cached result of the same request when it is newer than the selected age. A cached result costs the same tokens as the original scrape. |
225
+ | `maxRetries` | `maxRetries` | number (integer) | Omitted | Maximum number of retries, as a nonnegative integer. Omit this parameter for no limit. |
226
+
227
+ The request uses `markdown=true`, `html=false`, `screenshot=false`, and `saveResult=true`.
228
+
229
+ #### Example
230
+
231
+ ```js
232
+ import { scrapeMarkdown } from "@mrscraper/sdk";
233
+
234
+ const result = await scrapeMarkdown("https://example.com", {
235
+ warmStart: true,
236
+ maxAge: 86400000,
115
237
  });
116
- for (const item of result.data.data) {
117
- console.log(item.rank, item.title, item.url);
238
+ console.log(result.data);
239
+ ```
240
+
241
+ #### Response
242
+
243
+ The response body is Markdown text.
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
+ }
118
254
  }
119
255
  ```
120
256
 
121
- The SDK sends this request:
257
+ ### Get screenshot
122
258
 
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
- }'
259
+ #### Description
260
+
261
+ Capture a base64 PNG screenshot of the full page, the first viewport, or a custom 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
+ | `screenshot` | `screenshot` | string | `"full"` | Screenshot area to capture: full for the entire scroll height, top for the first viewport, or a WIDTHxHEIGHT viewport from 100 to 3840 pixels with an optional -ZOOM percent from 25 to 300, such as 1280x800 or 1920x1080-75. |
269
+ | `timeout` | `timeout` | number (integer) | `300` | Maximum seconds to wait for the scrape, from 1 to 330. The HTTP request allows 30 additional seconds. |
270
+ | `waitForSelector` | `waitForSelector` | string | Omitted | CSS selector or text to wait for on the page before returning the result, up to 500 characters. |
271
+ | `geoCode` | `geoCode` | string | Omitted | Two-letter country code to load the page from, sent in lowercase. |
272
+ | `maxAge` | `maxAge` | number (integer) | `0` | Return a cached result of the same request when it is newer than the selected age. A cached result costs the same tokens as the original scrape. |
273
+ | `maxRetries` | `maxRetries` | number (integer) | Omitted | Maximum number of retries, as a nonnegative integer. Omit this parameter for no limit. |
274
+
275
+ The request uses `browserRendering=true`, `html=false`, `markdown=false`, and `saveResult=true`; these are not service parameters. `screenshot` defaults to `full` and also accepts `top` or a `WIDTHxHEIGHT[-ZOOM]` viewport. The API still includes the page HTML in the response.
276
+
277
+ #### Example
278
+
279
+ ```js
280
+ import { getScreenshot } from "@mrscraper/sdk";
281
+
282
+ const result = await getScreenshot("https://example.com", {
283
+ screenshot: "top",
284
+ timeout: 120,
285
+ });
286
+ console.log(result.data);
133
287
  ```
134
288
 
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`.
289
+ #### Response
136
290
 
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 |
291
+ The response body is JSON containing a base64 PNG screenshot and the page HTML, which the API includes even though html=false is sent.
144
292
 
145
- ## Account status
293
+ **Success response**
146
294
 
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.
295
+ ```json
296
+ {
297
+ "status_code": 200,
298
+ "data": {
299
+ "html": "<html>...</html>",
300
+ "screenshot": "BASE64_PNG_DATA"
301
+ },
302
+ "headers": {
303
+ "content-type": "application/json; charset=utf-8"
304
+ }
305
+ }
306
+ ```
307
+
308
+ ### Scrape brand
309
+
310
+ #### Description
311
+
312
+ Extract a website's colors, typography, logos, and social links as JSON.
313
+
314
+ #### Parameters
315
+
316
+ | Parameter | HTTP field | Type | Default | Description |
317
+ | --------- | ---------- | ------ | -------- | -------------------------------------------------- |
318
+ | `url` | `url` | string | Required | Absolute HTTP or HTTPS URL of the page to process. |
319
+
320
+ The HTTP deadline is fixed at 120 seconds. It is not a service parameter.
321
+
322
+ The request uses `action=brand-scraping` and `bundle=none`; page controls are not accepted.
323
+
324
+ #### Example
148
325
 
149
- ```typescript
150
- import { account } from "@mrscraper/sdk";
326
+ ```js
327
+ import { scrapeBrand } from "@mrscraper/sdk";
151
328
 
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);
329
+ const result = await scrapeBrand("https://example.com");
330
+ console.log(result.data);
156
331
  ```
157
332
 
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.
333
+ #### Response
334
+
335
+ 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.
336
+
337
+ **Success response**
338
+
339
+ ```json
340
+ {
341
+ "status_code": 200,
342
+ "data": {
343
+ "data": {
344
+ "job_id": "JOB_ID",
345
+ "status": "succeeded",
346
+ "url": "https://example.com",
347
+ "final_url": "https://example.com",
348
+ "brand": {
349
+ "name": "Example brand",
350
+ "colors": {
351
+ "background": "#ffffff",
352
+ "text": "#222222"
353
+ },
354
+ "typography": {
355
+ "body": {
356
+ "font_family": "Example font"
357
+ }
358
+ }
359
+ },
360
+ "error": null,
361
+ "bundle_url": null
362
+ },
363
+ "message": "Example response"
364
+ },
365
+ "headers": {
366
+ "content-type": "application/json"
367
+ }
368
+ }
369
+ ```
164
370
 
165
- ## Errors and types
371
+ ### Scrape JSON
166
372
 
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.
373
+ #### Description
168
374
 
169
- ```typescript
170
- import { scraper_api, MrScraperError } from "@mrscraper/sdk";
171
- import type { MrScraperResponse, ScraperApiData } from "@mrscraper/sdk";
375
+ Extract structured JSON from a page using a natural-language prompt. Append Json Schema: and a JSON schema to shape the output.
172
376
 
173
- try {
174
- const result: MrScraperResponse<ScraperApiData> = await scraper_api("https://example.com");
175
- console.log(result.data);
176
- } catch (error) {
177
- if (error instanceof MrScraperError) {
178
- console.error(error.status, error.message);
179
- } else {
180
- throw error;
377
+ #### Parameters
378
+
379
+ | Parameter | HTTP field | Type | Default | Description |
380
+ | ------------------ | ------------------ | ---------------- | --------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
381
+ | `url` | `url` | string | Required | Absolute HTTP or HTTPS URL of the page to process. |
382
+ | `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. |
383
+ | `html` | `html` | boolean | `true` | Whether to include the page HTML in the response. |
384
+ | `browserRendering` | `browserRendering` | boolean | Omitted | Whether to load the page in a browser: true always does and false never does. Omit it to load the page without a browser first and switch to a browser automatically if the request is blocked. |
385
+ | `timeout` | `timeout` | number (integer) | `300` | Maximum seconds to wait for the scrape, from 1 to 330. The HTTP request allows 30 additional seconds. |
386
+ | `warmStart` | `warmStart` | boolean | `false` | Whether to open the site's home page first to warm the session before loading the target URL. |
387
+ | `blockResources` | `blockResources` | boolean | `false` | Whether to block images, fonts, and stylesheets while loading the page. |
388
+ | `waitForSelector` | `waitForSelector` | string | Omitted | CSS selector or text to wait for on the page before returning the result, up to 500 characters. |
389
+ | `geoCode` | `geoCode` | string | Omitted | Two-letter country code to load the page from, sent in lowercase. |
390
+ | `maxAge` | `maxAge` | number (integer) | `0` | Return a cached result of the same request when it is newer than the selected age. A cached result costs the same tokens as the original scrape. |
391
+ | `maxRetries` | `maxRetries` | number (integer) | Omitted | Maximum number of retries, as a nonnegative integer. Omit this parameter for no limit. |
392
+ | `screenshot` | `screenshot` | boolean | `false` | Whether to include a base64 screenshot in the response. |
393
+
394
+ The request uses `agent=general`, `saveResult=true`, 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.
395
+
396
+ #### Example
397
+
398
+ ```js
399
+ import { scrapeJson } from "@mrscraper/sdk";
400
+
401
+ const result = await scrapeJson("https://example.com", {
402
+ prompt:
403
+ '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"]}}',
404
+ browserRendering: true,
405
+ });
406
+ console.log(result.data);
407
+ ```
408
+
409
+ #### Response
410
+
411
+ 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 contains the page HTML unless disabled; markdown and screenshot can be empty strings.
412
+
413
+ **Success response**
414
+
415
+ ```json
416
+ {
417
+ "status_code": 200,
418
+ "data": {
419
+ "success": true,
420
+ "data": [
421
+ {
422
+ "title": "Example item",
423
+ "price": "10.00"
424
+ }
425
+ ],
426
+ "thread_id": "THREAD_ID",
427
+ "token_usage": 1,
428
+ "html": "<html>...</html>",
429
+ "markdown": "",
430
+ "screenshot": "",
431
+ "status": "Results ready",
432
+ "error": "",
433
+ "runtime": 1.23,
434
+ "cookies": []
435
+ },
436
+ "headers": {
437
+ "content-type": "application/json"
181
438
  }
182
439
  }
183
440
  ```
184
441
 
185
- ## Develop
442
+ ### Web search
186
443
 
187
- ```bash
188
- npm ci
189
- npm test
190
- npm run build
444
+ #### Description
445
+
446
+ Search the web and return ranked results with titles, URLs, descriptions, and sources.
447
+
448
+ #### Parameters
449
+
450
+ | Parameter | HTTP field | Type | Default | Description |
451
+ | ------------ | ------------ | ---------------- | -------- | ------------------------------------------------------------------------------------------------- |
452
+ | `query` | `query` | string | Required | Search query text, trimmed before sending, containing 1 to 1000 characters. |
453
+ | `country` | `country` | string | Omitted | Two-letter country code to search from, sent in lowercase. |
454
+ | `numResults` | `numResults` | number (integer) | `10` | Number of search results to request, as an integer from 10 to 100. Fewer results may be returned. |
455
+
456
+ The HTTP deadline is fixed at 120 seconds. It is not a service parameter.
457
+
458
+ The request uses `action=websearch`. `country` is omitted unless set, so the API searches from the United States.
459
+
460
+ #### Example
461
+
462
+ ```js
463
+ import { webSearch } from "@mrscraper/sdk";
464
+
465
+ const result = await webSearch("site:example.com documentation", {
466
+ country: "id",
467
+ numResults: 20,
468
+ });
469
+ console.log(result.data);
191
470
  ```
192
471
 
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.
472
+ #### Response
473
+
474
+ The API body contains success, message, a data array, and tokenUsage. Each result includes rank, title, url, description, and source.
475
+
476
+ **Success response**
477
+
478
+ ```json
479
+ {
480
+ "status_code": 200,
481
+ "data": {
482
+ "success": true,
483
+ "message": "Example response",
484
+ "data": [
485
+ {
486
+ "rank": 1,
487
+ "title": "Example result",
488
+ "url": "https://example.com",
489
+ "description": "Example result description.",
490
+ "source": "example.com"
491
+ }
492
+ ],
493
+ "tokenUsage": 1
494
+ },
495
+ "headers": {
496
+ "content-type": "application/json; charset=utf-8"
497
+ }
498
+ }
499
+ ```
194
500
 
195
- ## Manual tests with a real token
501
+ ## Response format
196
502
 
197
- Run these commands from a source checkout. Build the SDK and configure your API token:
503
+ 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.
198
504
 
199
- ```bash
200
- npm run build
201
- export MRSCRAPER_API_TOKEN="YOUR_TOKEN"
505
+ ```json
506
+ {
507
+ "status_code": 200,
508
+ "data": "<html><body>Example page content...</body></html>",
509
+ "headers": {
510
+ "content-type": "text/html; charset=utf-8"
511
+ }
512
+ }
202
513
  ```
203
514
 
204
- The `file.js` helper calls the three public functions against the live API:
515
+ Responses are `MrScraperResponse<T>` objects. JSON becomes JavaScript values, text remains `string`, and binary remains `Buffer`. Sensitive response headers are removed for status.
205
516
 
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}'
517
+ ## Error handling
518
+
519
+ 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.
520
+
521
+ ```js
522
+ import { scrapeHtml, MrScraperError } from "@mrscraper/sdk";
523
+
524
+ try {
525
+ await scrapeHtml("https://example.com");
526
+ } catch (error) {
527
+ if (error instanceof MrScraperError)
528
+ console.error(error.status, error.message);
529
+ else throw error;
530
+ }
213
531
  ```
214
532
 
215
- Screenshots are saved under `manual-results/`; other responses are previewed. You can also call the built SDK directly:
533
+ ## Integration features
216
534
 
217
- ```bash
218
- node --input-type=module <<'NODE'
219
- import { account } from "./dist/index.js";
535
+ ### Configuration
536
+
537
+ Functions return promises and use camelCase options. Omit optional controls or use `undefined`; explicit `false` and `0` are preserved. TypeScript exports include `PageOptions`, `LoadingOptions`, `HtmlOptions`, `MarkdownOptions`, `ScreenshotOptions`, `JsonOptions`, `WebSearchOptions`, `StatusOptions`, and `MrScraperResponse<T>`.
538
+
539
+ ### Advanced usage
540
+
541
+ Supply a generic response body type when you know the returned API shape:
542
+
543
+ ```ts
544
+ import { scrapeJson } from "@mrscraper/sdk";
545
+ const result = await scrapeJson<{ data: { title: string } }>(
546
+ "https://example.com",
547
+ { prompt: "Extract the page title" },
548
+ );
549
+ console.log(result.data.data.title);
550
+ ```
551
+
552
+ Save screenshot JSON as an image when the API returns a base64 screenshot:
220
553
 
221
- const result = await account();
222
- console.log(result.status_code, result.data);
223
- NODE
554
+ ```js
555
+ import { getScreenshot } from "@mrscraper/sdk";
556
+ import { writeFile } from "node:fs/promises";
557
+ const result = await getScreenshot("https://example.com");
558
+ if (
559
+ typeof result.data === "object" &&
560
+ typeof result.data?.screenshot === "string"
561
+ ) {
562
+ await writeFile("page.png", Buffer.from(result.data.screenshot, "base64"));
563
+ }
224
564
  ```
225
565
 
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`.
566
+ ### Troubleshooting
567
+
568
+ Check environment credentials when authentication fails. Use camelCase option names rather than snake_case. Page timeouts are integers from 1 to 330; status and search do not expose timeout options.
569
+
570
+ ## Development and testing
227
571
 
228
- ## Publish manually to npm
572
+ ### Automated checks
229
573
 
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:
574
+ The automated suite checks service behavior without production API calls.
232
575
 
233
576
  ```bash
234
577
  npm ci
235
578
  npm test
236
- npm pack --dry-run
237
- npm publish --dry-run --access public
579
+ npm run build
238
580
  ```
239
581
 
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:
582
+ ### Manual checks
583
+
584
+ The following commands call the live API using your credentials and consume quota.
243
585
 
244
586
  ```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
587
+ npm run build
588
+ node file.js status
589
+ node file.js scrapeHtml https://example.com
590
+ node file.js webSearch "site:example.com documentation"
250
591
  ```
251
592
 
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
593
  ## License
258
594
 
259
- MIT — see [LICENSE](./LICENSE).
595
+ MIT. See [LICENSE](./LICENSE).