stophy 1.4.0 → 1.4.2

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,6 +1,6 @@
1
1
  # Stophy for TypeScript
2
2
 
3
- Give your agents the live web from TypeScript. Every method and result is typed.
3
+ Search, read, and act on the web. This is the typed Stophy client for TypeScript and JavaScript.
4
4
 
5
5
  ## Install
6
6
 
@@ -8,135 +8,71 @@ Give your agents the live web from TypeScript. Every method and result is typed.
8
8
  npm install stophy
9
9
  ```
10
10
 
11
- ## Try it without a key
11
+ ## Example
12
12
 
13
13
  ```ts
14
14
  import { Stophy } from "stophy";
15
15
 
16
16
  const stophy = new Stophy();
17
-
18
17
  const page = await stophy.scrape({ url: "https://example.com", formats: ["markdown"] });
19
18
  console.log(page.data.markdown);
20
-
21
- const results = await stophy.search({ query: "bun runtime", limit: 3 });
22
- console.log(results.data?.web);
23
19
  ```
24
20
 
25
- `scrape`, `search`, `map` and `parse` work without a key, within a small free allowance, and so do `parsers`, `endpoints` and `signup`. Every other method throws a `StophyError` with the code `apiKeyRequired`.
26
-
27
- ## Use an API key
28
-
29
- Get a key at [stophy.dev/signup](https://stophy.dev/signup). Set it as `STOPHY_API_KEY`, or pass it in:
21
+ That call needs no key. Every method and result is typed, and each method sends one call to the [Stophy API](https://api.stophy.dev/v1/endpoints) and returns its JSON as is. `scrape` returns `{ success, data }`, and `map` returns `{ success, links }`.
30
22
 
31
- ```ts
32
- const stophy = new Stophy({ apiKey: "st_..." });
33
- ```
23
+ ## Pick a method
34
24
 
35
- `new Stophy("st_...")` works too.
25
+ | Method | Use it to |
26
+ | ------------------------- | ------------------------------------------------------------------------------- |
27
+ | `search` | Search the web, news, images, research papers or YouTube videos |
28
+ | `scrape` | Read one page as Markdown, HTML, links, a screenshot or JSON |
29
+ | `parsed` | Read a site's own data, such as Reddit posts or Google Maps places, as JSON |
30
+ | `map` | List the pages on a site, to find the right one before you read it |
31
+ | `parse` | Turn a PDF, Word, Excel or PowerPoint file, or a picture of text, into Markdown |
32
+ | `crawl`, `batch.scrape` | Read a whole section of a site, or a list of URLs, in the background |
33
+ | `extract` | Pull the fields you name from pages, each checked against the page |
34
+ | `browser.task` | Click through a public site in a cloud browser to search, filter or fill a form |
35
+ | `limits`, `usage`, `logs` | Read your balance, your all-time usage and your recent calls |
36
36
 
37
- Each method sends one call to the [Stophy API](https://api.stophy.dev/v1/endpoints) and returns its JSON as is. `scrape` returns `{ success, data }`, and `map` returns `{ success, links }`.
37
+ `limits` returns the balance in dollars as `balanceUsd`, with your rate limit. `scrape`, `search`, `map` and `parse` work without a key, within a small free allowance, and so do `parsers`, `endpoints` and `signup`. Every other method throws a `StophyError` with the code `apiKeyRequired`.
38
38
 
39
39
  ## Read a site with a parser
40
40
 
41
- A parser reads a site's page and returns its data as JSON: Reddit posts, Google Maps places, Amazon products, YouTube videos and more. Send the page URL and the parser's name:
42
-
43
- ```ts
44
- const places = await stophy.parsed(
45
- "google-maps",
46
- "https://www.google.com/maps/search/dentists+in+Ljubljana",
47
- );
48
- console.log(places.data.json);
49
- ```
50
-
51
- `parsed` calls `scrape` with the format `{ type: "json", parser }`. The parser name is typed, so your editor lists every parser. `await stophy.parsers()` returns each parser with the page it reads and what it returns.
52
-
53
- The third argument sends the parser's options, such as the next page:
54
-
55
- ```ts
56
- const next = await stophy.parsed(
57
- "google-maps",
58
- "https://www.google.com/maps/search/dentists+in+Ljubljana",
59
- { page: 2 },
60
- );
61
- ```
41
+ `parsed("google-maps", url)` calls `scrape` with the format `{ type: "json", parser }` and puts the result in `data.json`. The parser name is typed, so your editor lists every parser, and `await stophy.parsers()` returns each one with the page it reads and what it returns. The third argument sends the parser's options, such as `{ page: 2 }` for the next page. Paging needs an API key.
62
42
 
63
- Paging needs an API key.
43
+ ## Run a job in the background
64
44
 
65
- ## Crawl a site
45
+ `crawl`, `batch.scrape`, `extract` and `browser.task` answer at once with an `id`, which `browser.task` returns as `data.id` and the others return at the top level. Read the result with `crawl.status({ id })`, `batch.scrape.status({ id })`, `extract.result({ id })` or `browser.task.status({ id })`. `crawl` and `batch.scrape` also have `cancel({ id })`, which stops the job and keeps the pages already read.
66
46
 
67
- `crawl` answers at once with an id. Ask `crawl.status` for the pages:
47
+ A crawl `status` is `scraping` until it is `completed`. While pages are left to read, the answer has `next`, a link with a `cursor`. Send that cursor with the same id to get only the pages finished since. `extract.result` throws a `StophyError` with the code `notFound` until the result is ready. A job and its result are kept for 24 hours.
68
48
 
69
- ```ts
70
- const job = await stophy.crawl({ url: "https://bun.com/docs", limit: 20 });
71
- if (job.id) {
72
- const status = await stophy.crawl.status({ id: job.id });
73
- console.log(status.status, status.completed, status.total, status.data);
74
-
75
- const cursor = status.next && new URL(status.next).searchParams.get("cursor");
76
- if (cursor) {
77
- const more = await stophy.crawl.status({ id: job.id, cursor });
78
- console.log(more.data);
79
- }
80
- }
81
- ```
49
+ ## API key
82
50
 
83
- `status` is `scraping` until the crawl is `completed`. While pages are left to read, the answer has `next`, a link with a `cursor`. Send that cursor with the same id to get only the pages finished since. `crawl.cancel({ id })` stops the crawl and keeps the pages already read. A crawl and its pages are kept for 24 hours.
51
+ Get a key at [stophy.dev/signup](https://stophy.dev/signup). The client reads `STOPHY_API_KEY`, or you pass it in with `new Stophy({ apiKey: "st_..." })` or `new Stophy("st_...")`.
84
52
 
85
- `batch.scrape` takes a list of URLs and works the same way, with `batch.scrape.status` and `batch.scrape.cancel`.
53
+ | Option | Default | What it does |
54
+ | ------------ | ------------------------------------ | -------------------------------------------- |
55
+ | `apiKey` | `STOPHY_API_KEY` | Your API key |
56
+ | `baseUrl` | `STOPHY_BASE_URL`, or the Stophy API | The server to call |
57
+ | `maxRetries` | `2` | Retries per request. `0` turns retries off. |
58
+ | `timeoutMs` | `70000` | Time limit in milliseconds for each attempt. |
86
59
 
87
- ## Extract fields from pages
88
-
89
- ```ts
90
- const job = await stophy.extract({
91
- urls: ["https://example.com"],
92
- prompt: "What is this page for?",
93
- });
94
- if (job.id) {
95
- const result = await stophy.extract.result({ id: job.id });
96
- console.log(result.data, result.confidence);
97
- }
98
- ```
99
-
100
- `extract.result` throws a `StophyError` with the code `notFound` until the result is ready. Results are kept for 24 hours.
101
-
102
- ## Handle errors
103
-
104
- ```ts
105
- import { StophyError } from "stophy";
106
-
107
- try {
108
- await stophy.scrape({ url: "not a url" });
109
- } catch (error) {
110
- if (error instanceof StophyError) {
111
- console.log(error.code, error.message, error.retryable);
112
- }
113
- }
114
- ```
115
-
116
- `StophyError` has `code`, `message`, `retryable`, `retryAfterSeconds`, `status`, `requestId`, and `details`. The message says what went wrong and what to do next.
117
-
118
- The SDK retries network errors, timeouts, and every error the API marks `retryable`, and it waits as long as the API asks. If the API asks for a wait longer than 60 seconds, the SDK throws right away with `retryAfterSeconds` set.
60
+ Each method also takes `signal` to cancel the request, and `idempotencyKey` to choose the key of one `POST`.
119
61
 
120
- ## Options
62
+ ## Errors and retries
121
63
 
122
- | Option | Default | What it does |
123
- | ------------ | ------------------------------------ | --------------------------------------------------------------------------------------------- |
124
- | `apiKey` | `STOPHY_API_KEY` | Your API key |
125
- | `baseUrl` | `STOPHY_BASE_URL`, or the Stophy API | The server to call |
126
- | `maxRetries` | `2` | Retries per request. `0` turns retries off. |
127
- | `timeoutMs` | `70000` | Time limit for each attempt. A timed-out attempt is retried when the call carries an API key. |
64
+ A failed call throws a `StophyError`, which you import from `stophy`. It has `code`, `message`, `retryable`, `retryAfterSeconds`, `status`, `requestId` and `details`. The message says what went wrong and what to do next.
128
65
 
129
- Each method also takes `signal` to cancel the request, and `idempotencyKey` to choose the key of one `POST`.
66
+ The SDK retries eligible reads and writes. If a write may have run and the SDK cannot safely replay it, the SDK stops and sets `outcomeUnknown` on the error, even if the API marked it `retryable`. Check whether the work finished before sending a new request. If a retry would require waiting more than 60 seconds, the SDK throws with `retryAfterSeconds` set.
130
67
 
131
- ## Check your account
132
-
133
- ```ts
134
- const limits = await stophy.limits();
135
- const usage = await stophy.usage();
136
- const logs = await stophy.logs({ days: 7 });
137
- ```
68
+ ## Docs
138
69
 
139
- `limits` returns your balance in dollars as `balanceUsd`, and your rate limit. `usage` returns your all-time usage. `logs` returns your recent calls. All three need an API key.
70
+ - [TypeScript guide](https://docs.stophy.dev/sdks/typescript) covers the main methods with examples.
71
+ - [Quickstart](https://docs.stophy.dev/quickstart) makes a first request and reads the result.
72
+ - [Choose an API](https://docs.stophy.dev/introduction#choose-an-api) maps what you have to the call you need.
73
+ - [API reference](https://docs.stophy.dev/api-reference/introduction) lists every option of every call.
74
+ - [Errors](https://docs.stophy.dev/api-reference/errors) lists every error code, and [rate limits](https://docs.stophy.dev/production/rate-limits) explains the free allowance.
75
+ - [Pricing](https://docs.stophy.dev/account/pricing) lists what each call costs.
140
76
 
141
77
  ## License
142
78
 
package/dist/index.cjs CHANGED
@@ -107,7 +107,7 @@ var Surface = class {
107
107
  };
108
108
 
109
109
  // package.json
110
- var version = "1.4.0";
110
+ var version = "1.4.2";
111
111
 
112
112
  // src/errors.ts
113
113
  var StophyError = class extends Error {
@@ -151,7 +151,16 @@ var DEFAULT_BASE_URL = "https://api.stophy.dev";
151
151
  var DEFAULT_TIMEOUT_MS = 7e4;
152
152
  var MAX_RETRY_WAIT_SECONDS = 60;
153
153
  var RETRYABLE_STATUS = /* @__PURE__ */ new Set([429, 500, 502, 503, 504]);
154
- var JOB_STARTS = /* @__PURE__ */ new Set(["/v1/batch/scrape", "/v1/crawl"]);
154
+ var JOB_STARTS = /* @__PURE__ */ new Set(["/v1/agent", "/v1/batch/scrape", "/v1/crawl"]);
155
+ var BROWSER_TASK_STATUS = "/v1/browser/task/status";
156
+ var KEYLESS_READS = /* @__PURE__ */ new Set(["/v1/map", "/v1/parse", "/v1/scrape", "/v1/search"]);
157
+ var KEYED_POSTS = /* @__PURE__ */ new Set([
158
+ ...JOB_STARTS,
159
+ ...KEYLESS_READS,
160
+ BROWSER_TASK_STATUS,
161
+ "/v1/browser/task",
162
+ "/v1/extract"
163
+ ]);
155
164
  var USER_AGENT = `stophy-typescript/${version}`;
156
165
  function createCaller(options) {
157
166
  const baseFetch = options.fetch ?? globalThis.fetch;
@@ -171,9 +180,12 @@ function createCaller(options) {
171
180
  }
172
181
  headers.set("accept", "application/json");
173
182
  if (spec.body !== void 0) headers.set("content-type", "application/json");
174
- const key = spec.method === "POST" ? spec.options?.idempotencyKey ?? headers.get("idempotency-key") ?? crypto.randomUUID() : void 0;
175
- if (key !== void 0) headers.set("idempotency-key", key);
176
183
  const hasApiKey = headers.has("authorization");
184
+ const keyed = spec.method === "POST" && hasApiKey && KEYED_POSTS.has(spec.path);
185
+ const key = spec.method === "POST" ? spec.options?.idempotencyKey ?? headers.get("idempotency-key") ?? (keyed ? crypto.randomUUID() : void 0) : void 0;
186
+ if (key !== void 0) headers.set("idempotency-key", key);
187
+ const body = spec.body === void 0 ? void 0 : JSON.stringify(spec.body);
188
+ const protectedKey = keyed && answerIsKept(spec.path, parseJson(body ?? "")) ? key : void 0;
177
189
  const url = withQuery(`${baseUrl}${spec.path}`, spec.query);
178
190
  return send2(
179
191
  baseFetch,
@@ -181,15 +193,16 @@ function createCaller(options) {
181
193
  (signal) => ({
182
194
  method: spec.method,
183
195
  headers,
184
- body: spec.body === void 0 ? void 0 : JSON.stringify(spec.body),
196
+ body,
185
197
  signal
186
198
  }),
187
199
  spec.options?.signal,
188
200
  spec.method === "DELETE" ? { ...retry, maxRetries: 0 } : retry,
189
201
  {
190
- key: hasApiKey ? key : void 0,
202
+ key: protectedKey,
191
203
  hasApiKey,
192
- replayable: key === void 0 || !hasApiKey || answerIsKept(spec.path, parseJson(JSON.stringify(spec.body ?? null)))
204
+ path: spec.path,
205
+ replayable: spec.method !== "POST" || spec.path === BROWSER_TASK_STATUS || !hasApiKey && KEYLESS_READS.has(spec.path) || protectedKey !== void 0
193
206
  }
194
207
  );
195
208
  };
@@ -209,42 +222,71 @@ var NEVER_SENT = /* @__PURE__ */ new Set([
209
222
  "UND_ERR_CONNECT_TIMEOUT"
210
223
  ]);
211
224
  var requestMayHaveLeft = (error) => !NEVER_SENT.has(error.code ?? error.cause?.code ?? "");
225
+ var mayHaveRun = (error) => error.status === 408 || error.status >= 500 && error.code !== "busy";
212
226
  var SEND_AGAIN = "Check before you send it again as a new call, or send it again with the same Idempotency-Key in details.idempotencyKey.";
213
227
  function mayStillComplete(error, key) {
214
- return new StophyError(`${error.message} An earlier send may still complete. ${SEND_AGAIN}`, {
215
- status: error.status,
216
- code: error.code,
217
- retryable: error.retryable,
218
- retryAfterSeconds: error.retryAfterSeconds,
219
- requestId: error.requestId,
220
- details: { ...error.details, idempotencyKey: key }
228
+ return Object.assign(
229
+ new StophyError(`${error.message} An earlier send may still complete. ${SEND_AGAIN}`, {
230
+ status: error.status,
231
+ code: error.code,
232
+ retryable: error.retryable,
233
+ retryAfterSeconds: error.retryAfterSeconds,
234
+ requestId: error.requestId,
235
+ details: { ...error.details, idempotencyKey: key }
236
+ }),
237
+ { outcomeUnknown: true }
238
+ );
239
+ }
240
+ function abortReason(signal, key) {
241
+ const reason = signal.reason;
242
+ if (key === void 0) return reason;
243
+ const error = new Error(reason instanceof Error ? reason.message : "Stophy request cancelled", {
244
+ cause: reason
221
245
  });
246
+ if (reason instanceof Error) error.name = reason.name;
247
+ return Object.assign(error, { idempotencyKey: key, outcomeUnknown: true });
222
248
  }
223
249
  async function send2(baseFetch, url, init, signal, retry, plan) {
224
250
  let earlierSendLost = false;
225
- const mayHaveRun = (error) => error.status >= 500 && error.code !== "busy";
226
- const failWith = (error) => plan.key !== void 0 && earlierSendLost && mayHaveRun(error) ? mayStillComplete(error, plan.key) : error;
251
+ const failWith = (error) => plan.key !== void 0 && earlierSendLost ? mayStillComplete(error, plan.key) : error;
227
252
  for (let n = 0; ; n += 1) {
253
+ if (signal?.aborted) throw abortReason(signal, earlierSendLost ? plan.key : void 0);
228
254
  const deadline = withDeadline(signal, retry.timeoutMs);
229
255
  let waitMs;
230
256
  try {
231
- const response = await baseFetch(url, init(deadline.signal)).catch((error) => {
232
- if (signal?.aborted) throw error;
257
+ const answer = await baseFetch(url, init(deadline.signal)).then(async (response) => ({ response, text: await response.text() })).catch((error) => {
258
+ if (signal?.aborted) {
259
+ earlierSendLost ||= !(error instanceof Error) || requestMayHaveLeft(error);
260
+ throw abortReason(signal, earlierSendLost ? plan.key : void 0);
261
+ }
233
262
  const mayHaveLeft = requestMayHaveLeft(error);
234
263
  if (mayHaveLeft && !plan.replayable) throw Object.assign(error, { outcomeUnknown: true });
235
264
  if (error.name === "TimeoutError" && !plan.hasApiKey) throw error;
236
265
  if (n >= retry.maxRetries) {
237
- throw (mayHaveLeft || earlierSendLost) && plan.key !== void 0 ? Object.assign(error, { idempotencyKey: plan.key }) : error;
266
+ throw (mayHaveLeft || earlierSendLost) && plan.key !== void 0 ? Object.assign(error, { idempotencyKey: plan.key, outcomeUnknown: true }) : error;
238
267
  }
239
268
  earlierSendLost ||= mayHaveLeft;
240
269
  return void 0;
241
270
  });
242
- if (response === void 0) {
271
+ if (answer === void 0) {
243
272
  waitMs = backoffMs(n, retry.initialDelayMs);
244
- } else if (response.ok) {
245
- return await readBody(response);
246
273
  } else {
247
- const error = await errorFrom(response);
274
+ const { response, text } = answer;
275
+ if (response.ok) {
276
+ try {
277
+ return readBody(response, text);
278
+ } catch (error2) {
279
+ if (!(error2 instanceof StophyError)) throw error2;
280
+ earlierSendLost = true;
281
+ throw !plan.replayable ? Object.assign(error2, { outcomeUnknown: true }) : failWith(error2);
282
+ }
283
+ }
284
+ const error = errorFrom(response, text);
285
+ earlierSendLost ||= error.code === void 0 && mayHaveRun(error);
286
+ const definiteScrapeFailure = plan.path === "/v1/scrape" && (error.status === 504 && error.code === "sourceTimeout" || error.status === 503 && error.code === "sourceUnavailable");
287
+ if (!plan.replayable && mayHaveRun(error) && !definiteScrapeFailure) {
288
+ throw Object.assign(error, { outcomeUnknown: true });
289
+ }
248
290
  const seconds = error.retryAfterSeconds;
249
291
  if (!error.retryable || n >= retry.maxRetries) throw failWith(error);
250
292
  if (seconds !== void 0 && seconds > MAX_RETRY_WAIT_SECONDS) throw failWith(error);
@@ -253,7 +295,11 @@ async function send2(baseFetch, url, init, signal, retry, plan) {
253
295
  } finally {
254
296
  deadline.clear();
255
297
  }
256
- await sleep(waitMs, signal);
298
+ try {
299
+ await sleep(waitMs, signal);
300
+ } catch (error) {
301
+ throw signal?.aborted ? abortReason(signal, earlierSendLost ? plan.key : void 0) : error;
302
+ }
257
303
  }
258
304
  }
259
305
  function withDeadline(signal, timeoutMs) {
@@ -275,8 +321,7 @@ function withDeadline(signal, timeoutMs) {
275
321
  }
276
322
  };
277
323
  }
278
- async function readBody(response) {
279
- const text = await response.text();
324
+ function readBody(response, text) {
280
325
  if (!text) {
281
326
  throw failed(response, "Stophy returned an empty response", {});
282
327
  }
@@ -286,14 +331,13 @@ async function readBody(response) {
286
331
  throw failed(response, "Stophy returned a non-JSON response", {});
287
332
  }
288
333
  }
289
- async function errorFrom(response) {
290
- const text = await response.text();
334
+ function errorFrom(response, text) {
291
335
  const error = readError(text ? parseJson(text) : null);
292
336
  return failed(response, error.message ?? `Stophy request failed with status ${response.status}`, {
293
337
  code: error.code,
294
338
  retryable: error.retryable ?? RETRYABLE_STATUS.has(response.status),
295
339
  retryAfterSeconds: error.retryAfterSeconds ?? headerRetryAfter(response),
296
- requestId: headerRequestId(response) ?? error.requestId,
340
+ requestId: error.requestId ?? headerRequestId(response),
297
341
  details: error.details
298
342
  });
299
343
  }
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/bind.ts","../src/generated/surface.gen.ts","../package.json","../src/errors.ts","../src/json.ts","../src/transport.ts","../src/client.ts"],"names":["send"],"mappings":";;;;;AAOO,SAAS,IAAA,CAAqB,MAAc,IAAA,EAAc;AAC/D,EAAA,OAAO,CAAC,IAAA,EAAY,OAAA,KAClB,IAAA,CAAe,EAAE,QAAQ,MAAA,EAAQ,IAAA,EAAM,IAAA,EAAM,OAAA,EAAS,CAAA;AAC1D;AAEO,SA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AACD,IAAA,KAAA,CAAM,IAAI,CAAA;AAAA,EACZ;AAAA,EAEA,MAAA,CACE,MAAA,EACA,GAAA,EACA,OAAA,EACA,OAAA,EACyB;AACzB,IAAA,OAAO,IAAA,CAAK,MAAA,CAAO,EAAE,GAAA,EAAK,SAAS,CAAC,EAAE,IAAA,EAAM,MAAA,EAAQ,MAAA,EAAQ,OAAA,EAAS,CAAA,IAAK,OAAO,CAAA;AAAA,EACnF;AACF","file":"index.cjs","sourcesContent":["import type { Caller, Method, Query } from \"./transport\";\n\nexport interface RequestOptions {\n signal?: AbortSignal;\n idempotencyKey?: string;\n}\n\nexport function post<Body, Response>(path: string, call: Caller) {\n return (body: Body, options?: RequestOptions): Promise<Response> =>\n call<Response>({ method: \"POST\", path, body, options });\n}\n\nexport function postOptional<Body, Response>(path: string, call: Caller) {\n return (body?: Body, options?: RequestOptions): Promise<Response> =>\n call<Response>({ method: \"POST\", path, body: body ?? {}, options });\n}\n\nexport function send<Input extends Query, Response>(method: Method, path: string, call: Caller) {\n return (input: Input, options?: RequestOptions): Promise<Response> =>\n call<Response>({ method, ...fillPath(path, input), options });\n}\n\nexport function sendOptional<Input extends Query, Response>(\n method: Method,\n path: string,\n call: Caller,\n) {\n return (input?: Input, options?: RequestOptions): Promise<Response> =>\n call<Response>({ method, ...fillPath(path, input ?? {}), options });\n}\n\nexport function sendEmpty<Response>(method: Method, path: string, call: Caller) {\n return (options?: RequestOptions): Promise<Response> => call<Response>({ method, path, options });\n}\n\nfunction fillPath(template: string, input: Query) {\n const used = new Set<string>();\n const path = template.replaceAll(/\\{(\\w+)\\}/g, (_, name: string) => {\n const value = input[name];\n if (value === undefined) throw new TypeError(`Missing ${name} for ${template}`);\n used.add(name);\n return encodeURIComponent(String(value));\n });\n const query = Object.fromEntries(Object.entries(input).filter(([key]) => !used.has(key)));\n return { path, query };\n}\n","// Generated by scripts/gen-surface.ts. Do not edit.\n\nimport { post, postOptional, send, sendEmpty, sendOptional } from \"../bind\";\nimport type {\n\tBatchScrapeCancelData,\n\tBatchScrapeCancelResponse,\n\tBatchScrapeData,\n\tBatchScrapeResponse,\n\tBatchScrapeStatusData,\n\tBatchScrapeStatusResponse,\n\tBrowserTaskData,\n\tBrowserTaskResponse,\n\tBrowserTaskStatusData,\n\tBrowserTaskStatusResponse,\n\tCrawlCancelData,\n\tCrawlCancelResponse,\n\tCrawlData,\n\tCrawlResponse,\n\tCrawlStatusData,\n\tCrawlStatusResponse,\n\tExtractData,\n\tExtractResponse,\n\tExtractResultData,\n\tExtractResultResponse,\n\tGetLimitsResponse,\n\tGetLogsData,\n\tGetLogsResponse,\n\tGetUsageResponse,\n\tListEndpointsResponse,\n\tListParsersResponse,\n\tMapData,\n\tMapResponse,\n\tParseData,\n\tParseResponse,\n\tPollSignUpData,\n\tPollSignUpResponse,\n\tRevokeKeyResponse,\n\tScrapeData,\n\tScrapeResponse,\n\tSearchData,\n\tSearchDeveloperData,\n\tSearchDeveloperResponse,\n\tSearchResponse,\n\tSignUpData,\n\tSignUpResponse,\n} from \"./types.gen\";\nimport type { Caller } from \"../transport\";\n\nfunction bindSurface(call: Caller) {\n\treturn {\n\t\textract: Object.assign(postOptional<ExtractData[\"body\"], ExtractResponse>(\"/v1/extract\", call), {\n\t\t\t\tresult: send<ExtractResultData[\"path\"], ExtractResultResponse>(\"GET\", \"/v1/extract/{id}\", call),\n\t\t\t}),\n\t\tsignup: Object.assign(postOptional<SignUpData[\"body\"], SignUpResponse>(\"/v1/signup\", call), {\n\t\t\t\tpoll: post<PollSignUpData[\"body\"], PollSignUpResponse>(\"/v1/signup/poll\", call),\n\t\t\t}),\n\t\tlimits: sendEmpty<GetLimitsResponse>(\"GET\", \"/v1/limits\", call),\n\t\tusage: sendEmpty<GetUsageResponse>(\"GET\", \"/v1/usage\", call),\n\t\tlogs: sendOptional<NonNullable<GetLogsData[\"query\"]>, GetLogsResponse>(\"GET\", \"/v1/logs\", call),\n\t\tkey: {\n\t\t\trevoke: sendEmpty<RevokeKeyResponse>(\"DELETE\", \"/v1/key\", call),\n\t\t},\n\t\tparsers: sendEmpty<ListParsersResponse>(\"GET\", \"/v1/parsers\", call),\n\t\tendpoints: sendEmpty<ListEndpointsResponse>(\"GET\", \"/v1/endpoints\", call),\n\t\tsearch: Object.assign(post<SearchData[\"body\"], SearchResponse>(\"/v1/search\", call), {\n\t\t\t\tdeveloper: post<SearchDeveloperData[\"body\"], SearchDeveloperResponse>(\"/v1/search/developer\", call),\n\t\t\t}),\n\t\tscrape: post<ScrapeData[\"body\"], ScrapeResponse>(\"/v1/scrape\", call),\n\t\tbrowser: {\n\t\t\ttask: Object.assign(post<BrowserTaskData[\"body\"], BrowserTaskResponse>(\"/v1/browser/task\", call), {\n\t\t\t\t\tstatus: post<BrowserTaskStatusData[\"body\"], BrowserTaskStatusResponse>(\"/v1/browser/task/status\", call),\n\t\t\t\t}),\n\t\t},\n\t\tparse: postOptional<ParseData[\"body\"], ParseResponse>(\"/v1/parse\", call),\n\t\tmap: post<MapData[\"body\"], MapResponse>(\"/v1/map\", call),\n\t\tcrawl: Object.assign(post<CrawlData[\"body\"], CrawlResponse>(\"/v1/crawl\", call), {\n\t\t\t\tstatus: send<CrawlStatusData[\"path\"] & NonNullable<CrawlStatusData[\"query\"]>, CrawlStatusResponse>(\"GET\", \"/v1/crawl/{id}\", call),\n\t\t\t\tcancel: send<CrawlCancelData[\"path\"] & NonNullable<CrawlCancelData[\"query\"]>, CrawlCancelResponse>(\"DELETE\", \"/v1/crawl/{id}\", call),\n\t\t\t}),\n\t\tbatch: {\n\t\t\tscrape: Object.assign(post<BatchScrapeData[\"body\"], BatchScrapeResponse>(\"/v1/batch/scrape\", call), {\n\t\t\t\t\tstatus: send<BatchScrapeStatusData[\"path\"] & NonNullable<BatchScrapeStatusData[\"query\"]>, BatchScrapeStatusResponse>(\"GET\", \"/v1/batch/scrape/{id}\", call),\n\t\t\t\t\tcancel: send<BatchScrapeCancelData[\"path\"] & NonNullable<BatchScrapeCancelData[\"query\"]>, BatchScrapeCancelResponse>(\"DELETE\", \"/v1/batch/scrape/{id}\", call),\n\t\t\t\t}),\n\t\t},\n\t};\n}\n\ntype BoundSurface = ReturnType<typeof bindSurface>;\n\nexport class Surface {\n\treadonly extract: BoundSurface[\"extract\"];\n\treadonly signup: BoundSurface[\"signup\"];\n\treadonly limits: BoundSurface[\"limits\"];\n\treadonly usage: BoundSurface[\"usage\"];\n\treadonly logs: BoundSurface[\"logs\"];\n\treadonly key: BoundSurface[\"key\"];\n\treadonly parsers: BoundSurface[\"parsers\"];\n\treadonly endpoints: BoundSurface[\"endpoints\"];\n\treadonly search: BoundSurface[\"search\"];\n\treadonly scrape: BoundSurface[\"scrape\"];\n\treadonly browser: BoundSurface[\"browser\"];\n\treadonly parse: BoundSurface[\"parse\"];\n\treadonly map: BoundSurface[\"map\"];\n\treadonly crawl: BoundSurface[\"crawl\"];\n\treadonly batch: BoundSurface[\"batch\"];\n\n\tconstructor(call: Caller) {\n\t\tconst bound = bindSurface(call);\n\t\tthis.extract = bound.extract;\n\t\tthis.signup = bound.signup;\n\t\tthis.limits = bound.limits;\n\t\tthis.usage = bound.usage;\n\t\tthis.logs = bound.logs;\n\t\tthis.key = bound.key;\n\t\tthis.parsers = bound.parsers;\n\t\tthis.endpoints = bound.endpoints;\n\t\tthis.search = bound.search;\n\t\tthis.scrape = bound.scrape;\n\t\tthis.browser = bound.browser;\n\t\tthis.parse = bound.parse;\n\t\tthis.map = bound.map;\n\t\tthis.crawl = bound.crawl;\n\t\tthis.batch = bound.batch;\n\t}\n}\n","{\n \"name\": \"stophy\",\n \"version\": \"1.4.0\",\n \"description\": \"Give your agents the live web. One API to search the web, read what people say, and look up products, places, jobs and homes.\",\n \"keywords\": [\n \"ads\",\n \"ai-agents\",\n \"google-maps\",\n \"llm\",\n \"maps\",\n \"reddit\",\n \"scraping\",\n \"sdk\",\n \"stophy\",\n \"transcripts\",\n \"web-data\",\n \"web-search\",\n \"youtube\"\n ],\n \"homepage\": \"https://stophy.dev\",\n \"license\": \"MIT\",\n \"repository\": {\n \"type\": \"git\",\n \"url\": \"git+https://github.com/stophydotdev/stophy.git\",\n \"directory\": \"sdk/packages/typescript\"\n },\n \"files\": [\n \"dist\"\n ],\n \"type\": \"module\",\n \"main\": \"./dist/index.cjs\",\n \"module\": \"./dist/index.js\",\n \"types\": \"./dist/index.d.ts\",\n \"exports\": {\n \".\": {\n \"types\": \"./dist/index.d.ts\",\n \"import\": \"./dist/index.js\",\n \"require\": \"./dist/index.cjs\"\n }\n },\n \"scripts\": {\n \"generate\": \"openapi-ts && bun ../../scripts/gen-surface.ts\",\n \"build\": \"tsup\",\n \"test\": \"bun test ../../test/typescript\",\n \"check-types\": \"tsc --noEmit && tsc --noEmit -p tsconfig.tests.json\",\n \"prepublishOnly\": \"bun run generate && bun run build\"\n },\n \"devDependencies\": {\n \"@hey-api/client-fetch\": \"^0.10.2\",\n \"@hey-api/openapi-ts\": \"^0.64.0\",\n \"@types/bun\": \"^1.1.14\",\n \"prettier\": \"2.8.8\",\n \"tsup\": \"^8.3.5\",\n \"typescript\": \"^5.7.0\"\n }\n}\n","import type { _Error } from \"./generated/types.gen\";\nimport type { JsonValue } from \"./json\";\n\nexport type StophyErrorCode = _Error[\"code\"];\n\nexport class StophyError extends Error {\n readonly code?: string;\n readonly retryable: boolean;\n readonly retryAfterSeconds?: number;\n readonly status: number;\n readonly requestId?: string;\n readonly details: Record<string, JsonValue>;\n\n constructor(\n message: string,\n options: {\n status: number;\n code?: string;\n retryable: boolean;\n retryAfterSeconds?: number;\n requestId?: string;\n details?: Record<string, JsonValue>;\n },\n ) {\n super(message);\n this.name = \"StophyError\";\n this.status = options.status;\n this.code = options.code;\n this.retryable = options.retryable;\n this.retryAfterSeconds = options.retryAfterSeconds;\n this.requestId = options.requestId;\n this.details = options.details ?? {};\n }\n}\n","export type JsonValue = string | number | boolean | null | JsonValue[] | JsonObject;\n\nexport interface JsonObject {\n [key: string]: JsonValue;\n}\n\ntype MaybeJson = JsonValue | undefined;\n\nfunction tagOf(value: MaybeJson): string {\n return Object.prototype.toString.call(value);\n}\n\nexport function isString(value: MaybeJson): value is string {\n return tagOf(value) === \"[object String]\";\n}\n\nexport function isNumber(value: MaybeJson): value is number {\n return tagOf(value) === \"[object Number]\";\n}\n\nexport function isBoolean(value: MaybeJson): value is boolean {\n return value === true || value === false;\n}\n\nexport function isRecord(value: MaybeJson): value is JsonObject {\n return tagOf(value) === \"[object Object]\";\n}\n","import { version } from \"../package.json\";\nimport { StophyError } from \"./errors\";\nimport { isBoolean, isNumber, isRecord, isString, type JsonValue } from \"./json\";\n\nconst DEFAULT_BASE_URL = \"https://api.stophy.dev\";\nconst DEFAULT_TIMEOUT_MS = 70_000;\nconst MAX_RETRY_WAIT_SECONDS = 60;\nconst RETRYABLE_STATUS = new Set([429, 500, 502, 503, 504]);\nconst JOB_STARTS = new Set([\"/v1/batch/scrape\", \"/v1/crawl\"]);\nconst USER_AGENT = `stophy-typescript/${version}`;\n\nexport interface CallOptions {\n signal?: AbortSignal;\n idempotencyKey?: string;\n}\n\nexport type Method = \"GET\" | \"POST\" | \"DELETE\";\n\nexport type Query = Record<string, string | number | undefined>;\n\nexport interface RequestSpec {\n method: Method;\n path: string;\n body?: unknown;\n query?: Query;\n options?: CallOptions;\n}\n\nexport type Caller = <Result>(spec: RequestSpec) => Promise<Result>;\n\nexport type FetchLike = (input: RequestInfo | URL, init?: RequestInit) => Promise<Response>;\n\nexport interface TransportOptions {\n apiKey?: string;\n baseUrl?: string;\n fetch?: FetchLike;\n headers?: Record<string, string>;\n maxRetries?: number;\n retryInitialDelayMs?: number;\n timeoutMs?: number;\n}\n\nexport function createCaller(options: TransportOptions): Caller {\n const baseFetch: FetchLike = options.fetch ?? globalThis.fetch;\n const baseUrl = (options.baseUrl ?? DEFAULT_BASE_URL).replace(/\\/$/, \"\");\n const retry: RetryPolicy = {\n maxRetries: options.maxRetries ?? 2,\n initialDelayMs: options.retryInitialDelayMs ?? 500,\n timeoutMs: options.timeoutMs ?? DEFAULT_TIMEOUT_MS,\n };\n\n return async <Result>(spec: RequestSpec): Promise<Result> => {\n const headers = new Headers(options.headers);\n if (!(\"document\" in globalThis) && !headers.has(\"user-agent\")) {\n headers.set(\"user-agent\", USER_AGENT);\n }\n if (options.apiKey) {\n headers.set(\"authorization\", `Bearer ${options.apiKey}`);\n }\n headers.set(\"accept\", \"application/json\");\n if (spec.body !== undefined) headers.set(\"content-type\", \"application/json\");\n const key =\n spec.method === \"POST\"\n ? (spec.options?.idempotencyKey ?? headers.get(\"idempotency-key\") ?? crypto.randomUUID())\n : undefined;\n if (key !== undefined) headers.set(\"idempotency-key\", key);\n\n const hasApiKey = headers.has(\"authorization\");\n\n const url = withQuery(`${baseUrl}${spec.path}`, spec.query);\n return send<Result>(\n baseFetch,\n url,\n (signal) => ({\n method: spec.method,\n headers,\n body: spec.body === undefined ? undefined : JSON.stringify(spec.body),\n signal,\n }),\n spec.options?.signal,\n spec.method === \"DELETE\" ? { ...retry, maxRetries: 0 } : retry,\n {\n key: hasApiKey ? key : undefined,\n hasApiKey,\n replayable:\n key === undefined ||\n !hasApiKey ||\n answerIsKept(spec.path, parseJson(JSON.stringify(spec.body ?? null))),\n },\n );\n };\n}\n\ninterface RetryPolicy {\n maxRetries: number;\n initialDelayMs: number;\n timeoutMs: number;\n}\n\ninterface CallPlan {\n key: string | undefined;\n hasApiKey: boolean;\n replayable: boolean;\n}\n\nfunction answerIsKept(path: string, body: JsonValue): boolean {\n if (JOB_STARTS.has(path) || !isRecord(body)) return true;\n return ![body, body.scrapeOptions, body.options].some(\n (part) => isRecord(part) && part.zeroDataRetention === true,\n );\n}\n\ninterface NetworkError extends Error {\n code?: string;\n cause?: { code?: string };\n}\n\nconst NEVER_SENT = new Set([\n \"ECONNREFUSED\",\n \"ENOTFOUND\",\n \"EAI_AGAIN\",\n \"ENETUNREACH\",\n \"EHOSTUNREACH\",\n \"UND_ERR_CONNECT_TIMEOUT\",\n]);\n\nconst requestMayHaveLeft = (error: NetworkError) =>\n !NEVER_SENT.has(error.code ?? error.cause?.code ?? \"\");\n\nconst SEND_AGAIN =\n \"Check before you send it again as a new call, or send it again with the same Idempotency-Key in details.idempotencyKey.\";\n\nfunction mayStillComplete(error: StophyError, key: string): StophyError {\n return new StophyError(`${error.message} An earlier send may still complete. ${SEND_AGAIN}`, {\n status: error.status,\n code: error.code,\n retryable: error.retryable,\n retryAfterSeconds: error.retryAfterSeconds,\n requestId: error.requestId,\n details: { ...error.details, idempotencyKey: key },\n });\n}\n\nasync function send<Result>(\n baseFetch: FetchLike,\n url: string,\n init: (signal: AbortSignal) => RequestInit,\n signal: AbortSignal | undefined,\n retry: RetryPolicy,\n plan: CallPlan,\n): Promise<Result> {\n let earlierSendLost = false;\n const mayHaveRun = (error: StophyError) => error.status >= 500 && error.code !== \"busy\";\n const failWith = (error: StophyError) =>\n plan.key !== undefined && earlierSendLost && mayHaveRun(error)\n ? mayStillComplete(error, plan.key)\n : error;\n for (let n = 0; ; n += 1) {\n const deadline = withDeadline(signal, retry.timeoutMs);\n let waitMs: number;\n try {\n const response = await baseFetch(url, init(deadline.signal)).catch((error: NetworkError) => {\n if (signal?.aborted) throw error;\n const mayHaveLeft = requestMayHaveLeft(error);\n if (mayHaveLeft && !plan.replayable) throw Object.assign(error, { outcomeUnknown: true });\n if (error.name === \"TimeoutError\" && !plan.hasApiKey) throw error;\n if (n >= retry.maxRetries) {\n throw (mayHaveLeft || earlierSendLost) && plan.key !== undefined\n ? Object.assign(error, { idempotencyKey: plan.key })\n : error;\n }\n earlierSendLost ||= mayHaveLeft;\n return undefined;\n });\n if (response === undefined) {\n waitMs = backoffMs(n, retry.initialDelayMs);\n } else if (response.ok) {\n return await readBody<Result>(response);\n } else {\n const error = await errorFrom(response);\n const seconds = error.retryAfterSeconds;\n if (!error.retryable || n >= retry.maxRetries) throw failWith(error);\n if (seconds !== undefined && seconds > MAX_RETRY_WAIT_SECONDS) throw failWith(error);\n waitMs = seconds === undefined ? backoffMs(n, retry.initialDelayMs) : seconds * 1000;\n }\n } finally {\n deadline.clear();\n }\n await sleep(waitMs, signal);\n }\n}\n\nfunction withDeadline(signal: AbortSignal | undefined, timeoutMs: number) {\n const controller = new AbortController();\n const abort = () => controller.abort(signal?.reason);\n if (signal?.aborted) abort();\n else signal?.addEventListener(\"abort\", abort, { once: true });\n const timer = setTimeout(\n () =>\n controller.abort(\n new DOMException(`Stophy request timed out after ${timeoutMs} ms`, \"TimeoutError\"),\n ),\n timeoutMs,\n );\n return {\n signal: controller.signal,\n clear: () => {\n clearTimeout(timer);\n signal?.removeEventListener(\"abort\", abort);\n },\n };\n}\n\nasync function readBody<Result>(response: Response): Promise<Result> {\n const text = await response.text();\n if (!text) {\n throw failed(response, \"Stophy returned an empty response\", {});\n }\n try {\n return JSON.parse(text);\n } catch {\n throw failed(response, \"Stophy returned a non-JSON response\", {});\n }\n}\n\nasync function errorFrom(response: Response): Promise<StophyError> {\n const text = await response.text();\n const error = readError(text ? parseJson(text) : null);\n return failed(response, error.message ?? `Stophy request failed with status ${response.status}`, {\n code: error.code,\n retryable: error.retryable ?? RETRYABLE_STATUS.has(response.status),\n retryAfterSeconds: error.retryAfterSeconds ?? headerRetryAfter(response),\n requestId: headerRequestId(response) ?? error.requestId,\n details: error.details,\n });\n}\n\nfunction failed(\n response: Response,\n message: string,\n options: {\n code?: string;\n retryable?: boolean;\n retryAfterSeconds?: number;\n requestId?: string;\n details?: Record<string, JsonValue>;\n },\n): StophyError {\n return new StophyError(message, {\n status: response.status,\n code: options.code,\n retryable: options.retryable ?? false,\n retryAfterSeconds: options.retryAfterSeconds,\n requestId: options.requestId ?? headerRequestId(response),\n details: options.details,\n });\n}\n\ninterface ErrorFields {\n code?: string;\n message?: string;\n retryable?: boolean;\n retryAfterSeconds?: number;\n requestId?: string;\n details?: Record<string, JsonValue>;\n}\n\nfunction parseJson(text: string): JsonValue {\n try {\n return JSON.parse(text);\n } catch {\n return null;\n }\n}\n\nconst ENVELOPE_FIELDS = new Set([\n \"success\",\n \"error\",\n \"message\",\n \"code\",\n \"retryable\",\n \"retryAfterSeconds\",\n \"requestId\",\n]);\n\nfunction readError(body: JsonValue): ErrorFields {\n if (!isRecord(body)) return {};\n const fields = isRecord(body.error) ? body.error : body;\n return {\n code: isString(fields.code) ? fields.code : undefined,\n message: isString(fields.error)\n ? fields.error\n : isString(fields.message)\n ? fields.message\n : undefined,\n retryable: isBoolean(fields.retryable) ? fields.retryable : undefined,\n retryAfterSeconds: isNumber(fields.retryAfterSeconds) ? fields.retryAfterSeconds : undefined,\n requestId: isString(fields.requestId) ? fields.requestId : undefined,\n details: Object.fromEntries(\n Object.entries(fields).filter(([key]) => !ENVELOPE_FIELDS.has(key)),\n ),\n };\n}\n\nfunction headerRequestId(response: Response): string | undefined {\n return response.headers.get(\"x-request-id\") ?? undefined;\n}\n\nfunction headerRetryAfter(response: Response): number | undefined {\n const header = response.headers.get(\"retry-after\");\n if (!header) return undefined;\n const seconds = Number(header);\n if (Number.isFinite(seconds)) return seconds;\n const date = Date.parse(header);\n if (Number.isNaN(date)) return undefined;\n return Math.max(0, Math.ceil((date - Date.now()) / 1000));\n}\n\nfunction withQuery(url: string, query: Query | undefined): string {\n if (!query) return url;\n const params = new URLSearchParams();\n for (const [key, value] of Object.entries(query)) {\n if (value !== undefined) params.set(key, String(value));\n }\n const text = params.toString();\n return text ? `${url}?${text}` : url;\n}\n\nfunction backoffMs(attempt: number, base: number): number {\n const window = base * 2 ** attempt;\n return window / 2 + Math.random() * (window / 2);\n}\n\nfunction sleep(ms: number, signal: AbortSignal | undefined): Promise<void> {\n return new Promise((resolve, reject) => {\n if (signal?.aborted) return reject(signal.reason);\n const onAbort = () => {\n clearTimeout(timer);\n reject(signal?.reason);\n };\n const timer = setTimeout(() => {\n signal?.removeEventListener(\"abort\", onAbort);\n resolve();\n }, ms);\n signal?.addEventListener(\"abort\", onAbort, { once: true });\n });\n}\n","import type { RequestOptions } from \"./bind\";\nimport type { ParserName } from \"./generated/parsers.gen\";\nimport { Surface } from \"./generated/surface.gen\";\nimport type { ScrapeData, ScrapeResponse } from \"./generated/types.gen\";\nimport { type CallOptions, createCaller, type FetchLike } from \"./transport\";\n\nexport interface StophyOptions {\n apiKey?: string;\n baseUrl?: string;\n fetch?: FetchLike;\n headers?: Record<string, string>;\n maxRetries?: number;\n retryInitialDelayMs?: number;\n timeoutMs?: number;\n}\n\nexport type { CallOptions, FetchLike };\n\nexport type StophyClientInput = StophyOptions | string;\n\ntype JsonFormat = Extract<NonNullable<ScrapeData[\"body\"][\"formats\"]>[number], { type: \"json\" }>;\n\nexport type ParserOptions = NonNullable<JsonFormat[\"options\"]>;\n\nfunction env(name: string): string | undefined {\n return globalThis.process?.env[name];\n}\n\nexport class Stophy extends Surface {\n constructor(input: StophyClientInput = {}) {\n const options = input instanceof Object ? input : { apiKey: input };\n const apiKey = options.apiKey?.trim() || env(\"STOPHY_API_KEY\")?.trim();\n const call = createCaller({\n ...options,\n apiKey,\n baseUrl: options.baseUrl ?? env(\"STOPHY_BASE_URL\"),\n });\n super(call);\n }\n\n parsed(\n parser: ParserName,\n url: string,\n options?: ParserOptions,\n request?: RequestOptions,\n ): Promise<ScrapeResponse> {\n return this.scrape({ url, formats: [{ type: \"json\", parser, options }] }, request);\n }\n}\n"]}
1
+ {"version":3,"sources":["../src/bind.ts","../src/generated/surface.gen.ts","../package.json","../src/errors.ts","../src/json.ts","../src/transport.ts","../src/client.ts"],"names":["send","error"],"mappings":";;;;;AAOO,SAAS,IAAA,CAAqB,MAAc,IAAA,EAAc;AAC/D,EAAA,OAAO,CAAC,IAAA,EAAY,OAAA,KAClB,IAAA,CAAe,EAAE,QAAQ,MAAA,EAAQ,IAAA,EAAM,IAAA,EAAM,OAAA,EAAS,CAAA;AAC1D;AAEO,SAAS,YAAA,CAA6B,MAAc,IAAA,EAAc;AACvE,EAAA,OAAO,CAAC,IAAA,EAAa,OAAA,KACnB,IAAA,CAAe,EAAE,MAAA,EAAQ,MAAA,EAAQ,I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OAAA,EACA,OAAA,EACyB;AACzB,IAAA,OAAO,IAAA,CAAK,MAAA,CAAO,EAAE,GAAA,EAAK,SAAS,CAAC,EAAE,IAAA,EAAM,MAAA,EAAQ,MAAA,EAAQ,OAAA,EAAS,CAAA,IAAK,OAAO,CAAA;AAAA,EACnF;AACF","file":"index.cjs","sourcesContent":["import type { Caller, Method, Query } from \"./transport\";\n\nexport interface RequestOptions {\n signal?: AbortSignal;\n idempotencyKey?: string;\n}\n\nexport function post<Body, Response>(path: string, call: Caller) {\n return (body: Body, options?: RequestOptions): Promise<Response> =>\n call<Response>({ method: \"POST\", path, body, options });\n}\n\nexport function postOptional<Body, Response>(path: string, call: Caller) {\n return (body?: Body, options?: RequestOptions): Promise<Response> =>\n call<Response>({ method: \"POST\", path, body: body ?? {}, options });\n}\n\nexport function send<Input extends Query, Response>(method: Method, path: string, call: Caller) {\n return (input: Input, options?: RequestOptions): Promise<Response> =>\n call<Response>({ method, ...fillPath(path, input), options });\n}\n\nexport function sendOptional<Input extends Query, Response>(\n method: Method,\n path: string,\n call: Caller,\n) {\n return (input?: Input, options?: RequestOptions): Promise<Response> =>\n call<Response>({ method, ...fillPath(path, input ?? {}), options });\n}\n\nexport function sendEmpty<Response>(method: Method, path: string, call: Caller) {\n return (options?: RequestOptions): Promise<Response> => call<Response>({ method, path, options });\n}\n\nfunction fillPath(template: string, input: Query) {\n const used = new Set<string>();\n const path = template.replaceAll(/\\{(\\w+)\\}/g, (_, name: string) => {\n const value = input[name];\n if (value === undefined) throw new TypeError(`Missing ${name} for ${template}`);\n used.add(name);\n return encodeURIComponent(String(value));\n });\n const query = Object.fromEntries(Object.entries(input).filter(([key]) => !used.has(key)));\n return { path, query };\n}\n","// Generated by scripts/gen-surface.ts. Do not edit.\n\nimport { post, postOptional, send, sendEmpty, sendOptional } from \"../bind\";\nimport type {\n\tBatchScrapeCancelData,\n\tBatchScrapeCancelResponse,\n\tBatchScrapeData,\n\tBatchScrapeResponse,\n\tBatchScrapeStatusData,\n\tBatchScrapeStatusResponse,\n\tBrowserTaskData,\n\tBrowserTaskResponse,\n\tBrowserTaskStatusData,\n\tBrowserTaskStatusResponse,\n\tCrawlCancelData,\n\tCrawlCancelResponse,\n\tCrawlData,\n\tCrawlResponse,\n\tCrawlStatusData,\n\tCrawlStatusResponse,\n\tExtractData,\n\tExtractResponse,\n\tExtractResultData,\n\tExtractResultResponse,\n\tGetLimitsResponse,\n\tGetLogsData,\n\tGetLogsResponse,\n\tGetUsageResponse,\n\tListEndpointsResponse,\n\tListParsersResponse,\n\tMapData,\n\tMapResponse,\n\tParseData,\n\tParseResponse,\n\tPollSignUpData,\n\tPollSignUpResponse,\n\tRevokeKeyResponse,\n\tScrapeData,\n\tScrapeResponse,\n\tSearchData,\n\tSearchDeveloperData,\n\tSearchDeveloperResponse,\n\tSearchResponse,\n\tSignUpData,\n\tSignUpResponse,\n} from \"./types.gen\";\nimport type { Caller } from \"../transport\";\n\nfunction bindSurface(call: Caller) {\n\treturn {\n\t\textract: Object.assign(postOptional<ExtractData[\"body\"], ExtractResponse>(\"/v1/extract\", call), {\n\t\t\t\tresult: send<ExtractResultData[\"path\"], ExtractResultResponse>(\"GET\", \"/v1/extract/{id}\", call),\n\t\t\t}),\n\t\tsignup: Object.assign(postOptional<SignUpData[\"body\"], SignUpResponse>(\"/v1/signup\", call), {\n\t\t\t\tpoll: post<PollSignUpData[\"body\"], PollSignUpResponse>(\"/v1/signup/poll\", call),\n\t\t\t}),\n\t\tlimits: sendEmpty<GetLimitsResponse>(\"GET\", \"/v1/limits\", call),\n\t\tusage: sendEmpty<GetUsageResponse>(\"GET\", \"/v1/usage\", call),\n\t\tlogs: sendOptional<NonNullable<GetLogsData[\"query\"]>, GetLogsResponse>(\"GET\", \"/v1/logs\", call),\n\t\tkey: {\n\t\t\trevoke: sendEmpty<RevokeKeyResponse>(\"DELETE\", \"/v1/key\", call),\n\t\t},\n\t\tparsers: sendEmpty<ListParsersResponse>(\"GET\", \"/v1/parsers\", call),\n\t\tendpoints: sendEmpty<ListEndpointsResponse>(\"GET\", \"/v1/endpoints\", call),\n\t\tsearch: Object.assign(post<SearchData[\"body\"], SearchResponse>(\"/v1/search\", call), {\n\t\t\t\tdeveloper: post<SearchDeveloperData[\"body\"], SearchDeveloperResponse>(\"/v1/search/developer\", call),\n\t\t\t}),\n\t\tscrape: post<ScrapeData[\"body\"], ScrapeResponse>(\"/v1/scrape\", call),\n\t\tbrowser: {\n\t\t\ttask: Object.assign(post<BrowserTaskData[\"body\"], BrowserTaskResponse>(\"/v1/browser/task\", call), {\n\t\t\t\t\tstatus: post<BrowserTaskStatusData[\"body\"], BrowserTaskStatusResponse>(\"/v1/browser/task/status\", call),\n\t\t\t\t}),\n\t\t},\n\t\tparse: postOptional<ParseData[\"body\"], ParseResponse>(\"/v1/parse\", call),\n\t\tmap: post<MapData[\"body\"], MapResponse>(\"/v1/map\", call),\n\t\tcrawl: Object.assign(post<CrawlData[\"body\"], CrawlResponse>(\"/v1/crawl\", call), {\n\t\t\t\tstatus: send<CrawlStatusData[\"path\"] & NonNullable<CrawlStatusData[\"query\"]>, CrawlStatusResponse>(\"GET\", \"/v1/crawl/{id}\", call),\n\t\t\t\tcancel: send<CrawlCancelData[\"path\"] & NonNullable<CrawlCancelData[\"query\"]>, CrawlCancelResponse>(\"DELETE\", \"/v1/crawl/{id}\", call),\n\t\t\t}),\n\t\tbatch: {\n\t\t\tscrape: Object.assign(post<BatchScrapeData[\"body\"], BatchScrapeResponse>(\"/v1/batch/scrape\", call), {\n\t\t\t\t\tstatus: send<BatchScrapeStatusData[\"path\"] & NonNullable<BatchScrapeStatusData[\"query\"]>, BatchScrapeStatusResponse>(\"GET\", \"/v1/batch/scrape/{id}\", call),\n\t\t\t\t\tcancel: send<BatchScrapeCancelData[\"path\"] & NonNullable<BatchScrapeCancelData[\"query\"]>, BatchScrapeCancelResponse>(\"DELETE\", \"/v1/batch/scrape/{id}\", call),\n\t\t\t\t}),\n\t\t},\n\t};\n}\n\ntype BoundSurface = ReturnType<typeof bindSurface>;\n\nexport class Surface {\n\treadonly extract: BoundSurface[\"extract\"];\n\treadonly signup: BoundSurface[\"signup\"];\n\treadonly limits: BoundSurface[\"limits\"];\n\treadonly usage: BoundSurface[\"usage\"];\n\treadonly logs: BoundSurface[\"logs\"];\n\treadonly key: BoundSurface[\"key\"];\n\treadonly parsers: BoundSurface[\"parsers\"];\n\treadonly endpoints: BoundSurface[\"endpoints\"];\n\treadonly search: BoundSurface[\"search\"];\n\treadonly scrape: BoundSurface[\"scrape\"];\n\treadonly browser: BoundSurface[\"browser\"];\n\treadonly parse: BoundSurface[\"parse\"];\n\treadonly map: BoundSurface[\"map\"];\n\treadonly crawl: BoundSurface[\"crawl\"];\n\treadonly batch: BoundSurface[\"batch\"];\n\n\tconstructor(call: Caller) {\n\t\tconst bound = bindSurface(call);\n\t\tthis.extract = bound.extract;\n\t\tthis.signup = bound.signup;\n\t\tthis.limits = bound.limits;\n\t\tthis.usage = bound.usage;\n\t\tthis.logs = bound.logs;\n\t\tthis.key = bound.key;\n\t\tthis.parsers = bound.parsers;\n\t\tthis.endpoints = bound.endpoints;\n\t\tthis.search = bound.search;\n\t\tthis.scrape = bound.scrape;\n\t\tthis.browser = bound.browser;\n\t\tthis.parse = bound.parse;\n\t\tthis.map = bound.map;\n\t\tthis.crawl = bound.crawl;\n\t\tthis.batch = bound.batch;\n\t}\n}\n","{\n \"name\": \"stophy\",\n \"version\": \"1.4.2\",\n \"description\": \"Search, read, and act on the web. The Stophy client for TypeScript and JavaScript.\",\n \"keywords\": [\n \"ads\",\n \"ai-agents\",\n \"google-maps\",\n \"llm\",\n \"maps\",\n \"reddit\",\n \"scraping\",\n \"sdk\",\n \"stophy\",\n \"transcripts\",\n \"web-data\",\n \"web-search\",\n \"youtube\"\n ],\n \"homepage\": \"https://stophy.dev\",\n \"license\": \"MIT\",\n \"repository\": {\n \"type\": \"git\",\n \"url\": \"git+https://github.com/stophydotdev/stophy.git\",\n \"directory\": \"sdk/packages/typescript\"\n },\n \"files\": [\n \"dist\"\n ],\n \"type\": \"module\",\n \"main\": \"./dist/index.cjs\",\n \"module\": \"./dist/index.js\",\n \"types\": \"./dist/index.d.ts\",\n \"exports\": {\n \".\": {\n \"types\": \"./dist/index.d.ts\",\n \"import\": \"./dist/index.js\",\n \"require\": \"./dist/index.cjs\"\n }\n },\n \"scripts\": {\n \"generate\": \"openapi-ts && bun ../../scripts/gen-surface.ts\",\n \"build\": \"tsup\",\n \"test\": \"bun test ../../test/typescript\",\n \"check-types\": \"tsc --noEmit && tsc --noEmit -p tsconfig.tests.json\",\n \"prepublishOnly\": \"bun run generate && bun run build\"\n },\n \"devDependencies\": {\n \"@hey-api/client-fetch\": \"^0.10.2\",\n \"@hey-api/openapi-ts\": \"^0.64.0\",\n \"@types/bun\": \"^1.1.14\",\n \"prettier\": \"2.8.8\",\n \"tsup\": \"^8.3.5\",\n \"typescript\": \"^5.7.0\"\n }\n}\n","import type { _Error } from \"./generated/types.gen\";\nimport type { JsonValue } from \"./json\";\n\nexport type StophyErrorCode = _Error[\"code\"];\n\nexport class StophyError extends Error {\n readonly code?: string;\n readonly retryable: boolean;\n readonly retryAfterSeconds?: number;\n readonly status: number;\n readonly requestId?: string;\n readonly details: Record<string, JsonValue>;\n declare readonly outcomeUnknown?: true;\n\n constructor(\n message: string,\n options: {\n status: number;\n code?: string;\n retryable: boolean;\n retryAfterSeconds?: number;\n requestId?: string;\n details?: Record<string, JsonValue>;\n },\n ) {\n super(message);\n this.name = \"StophyError\";\n this.status = options.status;\n this.code = options.code;\n this.retryable = options.retryable;\n this.retryAfterSeconds = options.retryAfterSeconds;\n this.requestId = options.requestId;\n this.details = options.details ?? {};\n }\n}\n","export type JsonValue = string | number | boolean | null | JsonValue[] | JsonObject;\n\nexport interface JsonObject {\n [key: string]: JsonValue;\n}\n\ntype MaybeJson = JsonValue | undefined;\n\nfunction tagOf(value: MaybeJson): string {\n return Object.prototype.toString.call(value);\n}\n\nexport function isString(value: MaybeJson): value is string {\n return tagOf(value) === \"[object String]\";\n}\n\nexport function isNumber(value: MaybeJson): value is number {\n return tagOf(value) === \"[object Number]\";\n}\n\nexport function isBoolean(value: MaybeJson): value is boolean {\n return value === true || value === false;\n}\n\nexport function isRecord(value: MaybeJson): value is JsonObject {\n return tagOf(value) === \"[object Object]\";\n}\n","import { version } from \"../package.json\";\nimport { StophyError } from \"./errors\";\nimport { isBoolean, isNumber, isRecord, isString, type JsonValue } from \"./json\";\n\nconst DEFAULT_BASE_URL = \"https://api.stophy.dev\";\nconst DEFAULT_TIMEOUT_MS = 70_000;\nconst MAX_RETRY_WAIT_SECONDS = 60;\nconst RETRYABLE_STATUS = new Set([429, 500, 502, 503, 504]);\nconst JOB_STARTS = new Set([\"/v1/agent\", \"/v1/batch/scrape\", \"/v1/crawl\"]);\nconst BROWSER_TASK_STATUS = \"/v1/browser/task/status\";\nconst KEYLESS_READS = new Set([\"/v1/map\", \"/v1/parse\", \"/v1/scrape\", \"/v1/search\"]);\nconst KEYED_POSTS = new Set([\n ...JOB_STARTS,\n ...KEYLESS_READS,\n BROWSER_TASK_STATUS,\n \"/v1/browser/task\",\n \"/v1/extract\",\n]);\nconst USER_AGENT = `stophy-typescript/${version}`;\n\nexport interface CallOptions {\n signal?: AbortSignal;\n idempotencyKey?: string;\n}\n\nexport type Method = \"GET\" | \"POST\" | \"DELETE\";\n\nexport type Query = Record<string, string | number | undefined>;\n\nexport interface RequestSpec {\n method: Method;\n path: string;\n body?: unknown;\n query?: Query;\n options?: CallOptions;\n}\n\nexport type Caller = <Result>(spec: RequestSpec) => Promise<Result>;\n\nexport type FetchLike = (input: RequestInfo | URL, init?: RequestInit) => Promise<Response>;\n\nexport interface TransportOptions {\n apiKey?: string;\n baseUrl?: string;\n fetch?: FetchLike;\n headers?: Record<string, string>;\n maxRetries?: number;\n retryInitialDelayMs?: number;\n timeoutMs?: number;\n}\n\nexport function createCaller(options: TransportOptions): Caller {\n const baseFetch: FetchLike = options.fetch ?? globalThis.fetch;\n const baseUrl = (options.baseUrl ?? DEFAULT_BASE_URL).replace(/\\/$/, \"\");\n const retry: RetryPolicy = {\n maxRetries: options.maxRetries ?? 2,\n initialDelayMs: options.retryInitialDelayMs ?? 500,\n timeoutMs: options.timeoutMs ?? DEFAULT_TIMEOUT_MS,\n };\n\n return async <Result>(spec: RequestSpec): Promise<Result> => {\n const headers = new Headers(options.headers);\n if (!(\"document\" in globalThis) && !headers.has(\"user-agent\")) {\n headers.set(\"user-agent\", USER_AGENT);\n }\n if (options.apiKey) {\n headers.set(\"authorization\", `Bearer ${options.apiKey}`);\n }\n headers.set(\"accept\", \"application/json\");\n if (spec.body !== undefined) headers.set(\"content-type\", \"application/json\");\n const hasApiKey = headers.has(\"authorization\");\n const keyed = spec.method === \"POST\" && hasApiKey && KEYED_POSTS.has(spec.path);\n const key =\n spec.method === \"POST\"\n ? (spec.options?.idempotencyKey ??\n headers.get(\"idempotency-key\") ??\n (keyed ? crypto.randomUUID() : undefined))\n : undefined;\n if (key !== undefined) headers.set(\"idempotency-key\", key);\n\n const body = spec.body === undefined ? undefined : JSON.stringify(spec.body);\n const protectedKey = keyed && answerIsKept(spec.path, parseJson(body ?? \"\")) ? key : undefined;\n\n const url = withQuery(`${baseUrl}${spec.path}`, spec.query);\n return send<Result>(\n baseFetch,\n url,\n (signal) => ({\n method: spec.method,\n headers,\n body,\n signal,\n }),\n spec.options?.signal,\n spec.method === \"DELETE\" ? { ...retry, maxRetries: 0 } : retry,\n {\n key: protectedKey,\n hasApiKey,\n path: spec.path,\n replayable:\n spec.method !== \"POST\" ||\n spec.path === BROWSER_TASK_STATUS ||\n (!hasApiKey && KEYLESS_READS.has(spec.path)) ||\n protectedKey !== undefined,\n },\n );\n };\n}\n\ninterface RetryPolicy {\n maxRetries: number;\n initialDelayMs: number;\n timeoutMs: number;\n}\n\ninterface CallPlan {\n key: string | undefined;\n hasApiKey: boolean;\n path: string;\n replayable: boolean;\n}\n\nfunction answerIsKept(path: string, body: JsonValue): boolean {\n if (JOB_STARTS.has(path) || !isRecord(body)) return true;\n return ![body, body.scrapeOptions, body.options].some(\n (part) => isRecord(part) && part.zeroDataRetention === true,\n );\n}\n\ninterface NetworkError extends Error {\n code?: string;\n cause?: { code?: string };\n}\n\nconst NEVER_SENT = new Set([\n \"ECONNREFUSED\",\n \"ENOTFOUND\",\n \"EAI_AGAIN\",\n \"ENETUNREACH\",\n \"EHOSTUNREACH\",\n \"UND_ERR_CONNECT_TIMEOUT\",\n]);\n\nconst requestMayHaveLeft = (error: NetworkError) =>\n !NEVER_SENT.has(error.code ?? error.cause?.code ?? \"\");\n\nconst mayHaveRun = (error: StophyError) =>\n error.status === 408 || (error.status >= 500 && error.code !== \"busy\");\n\nconst SEND_AGAIN =\n \"Check before you send it again as a new call, or send it again with the same Idempotency-Key in details.idempotencyKey.\";\n\nfunction mayStillComplete(error: StophyError, key: string): StophyError {\n return Object.assign(\n new StophyError(`${error.message} An earlier send may still complete. ${SEND_AGAIN}`, {\n status: error.status,\n code: error.code,\n retryable: error.retryable,\n retryAfterSeconds: error.retryAfterSeconds,\n requestId: error.requestId,\n details: { ...error.details, idempotencyKey: key },\n }),\n { outcomeUnknown: true },\n );\n}\n\nfunction abortReason(signal: AbortSignal, key: string | undefined) {\n const reason: unknown = signal.reason;\n if (key === undefined) return reason;\n const error = new Error(reason instanceof Error ? reason.message : \"Stophy request cancelled\", {\n cause: reason,\n });\n if (reason instanceof Error) error.name = reason.name;\n return Object.assign(error, { idempotencyKey: key, outcomeUnknown: true });\n}\n\nasync function send<Result>(\n baseFetch: FetchLike,\n url: string,\n init: (signal: AbortSignal) => RequestInit,\n signal: AbortSignal | undefined,\n retry: RetryPolicy,\n plan: CallPlan,\n): Promise<Result> {\n let earlierSendLost = false;\n const failWith = (error: StophyError) =>\n plan.key !== undefined && earlierSendLost ? mayStillComplete(error, plan.key) : error;\n for (let n = 0; ; n += 1) {\n if (signal?.aborted) throw abortReason(signal, earlierSendLost ? plan.key : undefined);\n const deadline = withDeadline(signal, retry.timeoutMs);\n let waitMs: number;\n try {\n const answer = await baseFetch(url, init(deadline.signal))\n .then(async (response) => ({ response, text: await response.text() }))\n .catch((error: NetworkError) => {\n if (signal?.aborted) {\n earlierSendLost ||= !(error instanceof Error) || requestMayHaveLeft(error);\n throw abortReason(signal, earlierSendLost ? plan.key : undefined);\n }\n const mayHaveLeft = requestMayHaveLeft(error);\n if (mayHaveLeft && !plan.replayable) throw Object.assign(error, { outcomeUnknown: true });\n if (error.name === \"TimeoutError\" && !plan.hasApiKey) throw error;\n if (n >= retry.maxRetries) {\n throw (mayHaveLeft || earlierSendLost) && plan.key !== undefined\n ? Object.assign(error, { idempotencyKey: plan.key, outcomeUnknown: true })\n : error;\n }\n earlierSendLost ||= mayHaveLeft;\n return undefined;\n });\n if (answer === undefined) {\n waitMs = backoffMs(n, retry.initialDelayMs);\n } else {\n const { response, text } = answer;\n if (response.ok) {\n try {\n return readBody<Result>(response, text);\n } catch (error) {\n if (!(error instanceof StophyError)) throw error;\n earlierSendLost = true;\n throw !plan.replayable\n ? Object.assign(error, { outcomeUnknown: true })\n : failWith(error);\n }\n }\n const error = errorFrom(response, text);\n earlierSendLost ||= error.code === undefined && mayHaveRun(error);\n const definiteScrapeFailure =\n plan.path === \"/v1/scrape\" &&\n ((error.status === 504 && error.code === \"sourceTimeout\") ||\n (error.status === 503 && error.code === \"sourceUnavailable\"));\n if (!plan.replayable && mayHaveRun(error) && !definiteScrapeFailure) {\n throw Object.assign(error, { outcomeUnknown: true });\n }\n const seconds = error.retryAfterSeconds;\n if (!error.retryable || n >= retry.maxRetries) throw failWith(error);\n if (seconds !== undefined && seconds > MAX_RETRY_WAIT_SECONDS) throw failWith(error);\n waitMs = seconds === undefined ? backoffMs(n, retry.initialDelayMs) : seconds * 1000;\n }\n } finally {\n deadline.clear();\n }\n try {\n await sleep(waitMs, signal);\n } catch (error) {\n throw signal?.aborted ? abortReason(signal, earlierSendLost ? plan.key : undefined) : error;\n }\n }\n}\n\nfunction withDeadline(signal: AbortSignal | undefined, timeoutMs: number) {\n const controller = new AbortController();\n const abort = () => controller.abort(signal?.reason);\n if (signal?.aborted) abort();\n else signal?.addEventListener(\"abort\", abort, { once: true });\n const timer = setTimeout(\n () =>\n controller.abort(\n new DOMException(`Stophy request timed out after ${timeoutMs} ms`, \"TimeoutError\"),\n ),\n timeoutMs,\n );\n return {\n signal: controller.signal,\n clear: () => {\n clearTimeout(timer);\n signal?.removeEventListener(\"abort\", abort);\n },\n };\n}\n\nfunction readBody<Result>(response: Response, text: string): Result {\n if (!text) {\n throw failed(response, \"Stophy returned an empty response\", {});\n }\n try {\n return JSON.parse(text);\n } catch {\n throw failed(response, \"Stophy returned a non-JSON response\", {});\n }\n}\n\nfunction errorFrom(response: Response, text: string): StophyError {\n const error = readError(text ? parseJson(text) : null);\n return failed(response, error.message ?? `Stophy request failed with status ${response.status}`, {\n code: error.code,\n retryable: error.retryable ?? RETRYABLE_STATUS.has(response.status),\n retryAfterSeconds: error.retryAfterSeconds ?? headerRetryAfter(response),\n requestId: error.requestId ?? headerRequestId(response),\n details: error.details,\n });\n}\n\nfunction failed(\n response: Response,\n message: string,\n options: {\n code?: string;\n retryable?: boolean;\n retryAfterSeconds?: number;\n requestId?: string;\n details?: Record<string, JsonValue>;\n },\n): StophyError {\n return new StophyError(message, {\n status: response.status,\n code: options.code,\n retryable: options.retryable ?? false,\n retryAfterSeconds: options.retryAfterSeconds,\n requestId: options.requestId ?? headerRequestId(response),\n details: options.details,\n });\n}\n\ninterface ErrorFields {\n code?: string;\n message?: string;\n retryable?: boolean;\n retryAfterSeconds?: number;\n requestId?: string;\n details?: Record<string, JsonValue>;\n}\n\nfunction parseJson(text: string): JsonValue {\n try {\n return JSON.parse(text);\n } catch {\n return null;\n }\n}\n\nconst ENVELOPE_FIELDS = new Set([\n \"success\",\n \"error\",\n \"message\",\n \"code\",\n \"retryable\",\n \"retryAfterSeconds\",\n \"requestId\",\n]);\n\nfunction readError(body: JsonValue): ErrorFields {\n if (!isRecord(body)) return {};\n const fields = isRecord(body.error) ? body.error : body;\n return {\n code: isString(fields.code) ? fields.code : undefined,\n message: isString(fields.error)\n ? fields.error\n : isString(fields.message)\n ? fields.message\n : undefined,\n retryable: isBoolean(fields.retryable) ? fields.retryable : undefined,\n retryAfterSeconds: isNumber(fields.retryAfterSeconds) ? fields.retryAfterSeconds : undefined,\n requestId: isString(fields.requestId) ? fields.requestId : undefined,\n details: Object.fromEntries(\n Object.entries(fields).filter(([key]) => !ENVELOPE_FIELDS.has(key)),\n ),\n };\n}\n\nfunction headerRequestId(response: Response): string | undefined {\n return response.headers.get(\"x-request-id\") ?? undefined;\n}\n\nfunction headerRetryAfter(response: Response): number | undefined {\n const header = response.headers.get(\"retry-after\");\n if (!header) return undefined;\n const seconds = Number(header);\n if (Number.isFinite(seconds)) return seconds;\n const date = Date.parse(header);\n if (Number.isNaN(date)) return undefined;\n return Math.max(0, Math.ceil((date - Date.now()) / 1000));\n}\n\nfunction withQuery(url: string, query: Query | undefined): string {\n if (!query) return url;\n const params = new URLSearchParams();\n for (const [key, value] of Object.entries(query)) {\n if (value !== undefined) params.set(key, String(value));\n }\n const text = params.toString();\n return text ? `${url}?${text}` : url;\n}\n\nfunction backoffMs(attempt: number, base: number): number {\n const window = base * 2 ** attempt;\n return window / 2 + Math.random() * (window / 2);\n}\n\nfunction sleep(ms: number, signal: AbortSignal | undefined): Promise<void> {\n return new Promise((resolve, reject) => {\n if (signal?.aborted) return reject(signal.reason);\n const onAbort = () => {\n clearTimeout(timer);\n reject(signal?.reason);\n };\n const timer = setTimeout(() => {\n signal?.removeEventListener(\"abort\", onAbort);\n resolve();\n }, ms);\n signal?.addEventListener(\"abort\", onAbort, { once: true });\n });\n}\n","import type { RequestOptions } from \"./bind\";\nimport type { ParserName } from \"./generated/parsers.gen\";\nimport { Surface } from \"./generated/surface.gen\";\nimport type { ScrapeData, ScrapeResponse } from \"./generated/types.gen\";\nimport { type CallOptions, createCaller, type FetchLike } from \"./transport\";\n\nexport interface StophyOptions {\n apiKey?: string;\n baseUrl?: string;\n fetch?: FetchLike;\n headers?: Record<string, string>;\n maxRetries?: number;\n retryInitialDelayMs?: number;\n timeoutMs?: number;\n}\n\nexport type { CallOptions, FetchLike };\n\nexport type StophyClientInput = StophyOptions | string;\n\ntype JsonFormat = Extract<NonNullable<ScrapeData[\"body\"][\"formats\"]>[number], { type: \"json\" }>;\n\nexport type ParserOptions = NonNullable<JsonFormat[\"options\"]>;\n\nfunction env(name: string): string | undefined {\n return globalThis.process?.env[name];\n}\n\nexport class Stophy extends Surface {\n constructor(input: StophyClientInput = {}) {\n const options = input instanceof Object ? input : { apiKey: input };\n const apiKey = options.apiKey?.trim() || env(\"STOPHY_API_KEY\")?.trim();\n const call = createCaller({\n ...options,\n apiKey,\n baseUrl: options.baseUrl ?? env(\"STOPHY_BASE_URL\"),\n });\n super(call);\n }\n\n parsed(\n parser: ParserName,\n url: string,\n options?: ParserOptions,\n request?: RequestOptions,\n ): Promise<ScrapeResponse> {\n return this.scrape({ url, formats: [{ type: \"json\", parser, options }] }, request);\n }\n}\n"]}