stophy 1.3.0 → 1.4.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,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:
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.
42
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
- ```
43
+ ## Run a job in the background
50
44
 
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.
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.
52
46
 
53
- The third argument sends the parser's options, such as the next page:
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.
54
48
 
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
- ```
49
+ ## API key
62
50
 
63
- Paging needs an API key.
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_...")`.
64
52
 
65
- ## Crawl a site
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 for each attempt. A timed-out attempt is retried when the call carries an API key. |
66
59
 
67
- `crawl` answers at once with an id. Ask `crawl.status` for the pages:
60
+ Each method also takes `signal` to cancel the request, and `idempotencyKey` to choose the key of one `POST`.
68
61
 
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
- ```
62
+ ## Errors and retries
82
63
 
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.
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.
84
65
 
85
- `batch.scrape` takes a list of URLs and works the same way, with `batch.scrape.status` and `batch.scrape.cancel`.
66
+ The client 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, it throws right away with `retryAfterSeconds` set.
86
67
 
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`, and `requestId`. The message says what went wrong and what to do next.
117
-
118
- The SDK retries network errors and the HTTP statuses 429, 500, 502, 503, and 504, 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.
119
-
120
- ## Options
121
-
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 not retried. |
128
-
129
- Each method also takes `signal` to cancel the request.
130
-
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 credits as `balanceCredits`, 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
@@ -33,9 +33,7 @@ function fillPath(template, input) {
33
33
  // src/generated/surface.gen.ts
34
34
  function bindSurface(call) {
35
35
  return {
36
- endpoints: sendEmpty("GET", "/v1/endpoints", call),
37
- parsers: sendEmpty("GET", "/v1/parsers", call),
38
- extract: Object.assign(post("/v1/extract", call), {
36
+ extract: Object.assign(postOptional("/v1/extract", call), {
39
37
  result: send("GET", "/v1/extract/{id}", call)
40
38
  }),
41
39
  signup: Object.assign(postOptional("/v1/signup", call), {
@@ -47,14 +45,18 @@ function bindSurface(call) {
47
45
  key: {
48
46
  revoke: sendEmpty("DELETE", "/v1/key", call)
49
47
  },
50
- search: post("/v1/search", call),
48
+ parsers: sendEmpty("GET", "/v1/parsers", call),
49
+ endpoints: sendEmpty("GET", "/v1/endpoints", call),
50
+ search: Object.assign(post("/v1/search", call), {
51
+ developer: post("/v1/search/developer", call)
52
+ }),
51
53
  scrape: post("/v1/scrape", call),
52
54
  browser: {
53
55
  task: Object.assign(post("/v1/browser/task", call), {
54
56
  status: post("/v1/browser/task/status", call)
55
57
  })
56
58
  },
57
- parse: post("/v1/parse", call),
59
+ parse: postOptional("/v1/parse", call),
58
60
  map: post("/v1/map", call),
59
61
  crawl: Object.assign(post("/v1/crawl", call), {
60
62
  status: send("GET", "/v1/crawl/{id}", call),
@@ -69,14 +71,14 @@ function bindSurface(call) {
69
71
  };
70
72
  }
71
73
  var Surface = class {
72
- endpoints;
73
- parsers;
74
74
  extract;
75
75
  signup;
76
76
  limits;
77
77
  usage;
78
78
  logs;
79
79
  key;
80
+ parsers;
81
+ endpoints;
80
82
  search;
81
83
  scrape;
82
84
  browser;
@@ -86,14 +88,14 @@ var Surface = class {
86
88
  batch;
87
89
  constructor(call) {
88
90
  const bound = bindSurface(call);
89
- this.endpoints = bound.endpoints;
90
- this.parsers = bound.parsers;
91
91
  this.extract = bound.extract;
92
92
  this.signup = bound.signup;
93
93
  this.limits = bound.limits;
94
94
  this.usage = bound.usage;
95
95
  this.logs = bound.logs;
96
96
  this.key = bound.key;
97
+ this.parsers = bound.parsers;
98
+ this.endpoints = bound.endpoints;
97
99
  this.search = bound.search;
98
100
  this.scrape = bound.scrape;
99
101
  this.browser = bound.browser;
@@ -105,7 +107,7 @@ var Surface = class {
105
107
  };
106
108
 
107
109
  // package.json
108
- var version = "1.3.0";
110
+ var version = "1.4.1";
109
111
 
110
112
  // src/errors.ts
111
113
  var StophyError = class extends Error {
@@ -114,6 +116,7 @@ var StophyError = class extends Error {
114
116
  retryAfterSeconds;
115
117
  status;
116
118
  requestId;
119
+ details;
117
120
  constructor(message, options) {
118
121
  super(message);
119
122
  this.name = "StophyError";
@@ -122,6 +125,7 @@ var StophyError = class extends Error {
122
125
  this.retryable = options.retryable;
123
126
  this.retryAfterSeconds = options.retryAfterSeconds;
124
127
  this.requestId = options.requestId;
128
+ this.details = options.details ?? {};
125
129
  }
126
130
  };
127
131
 
@@ -135,6 +139,9 @@ function isString(value) {
135
139
  function isNumber(value) {
136
140
  return tagOf(value) === "[object Number]";
137
141
  }
142
+ function isBoolean(value) {
143
+ return value === true || value === false;
144
+ }
138
145
  function isRecord(value) {
139
146
  return tagOf(value) === "[object Object]";
140
147
  }
@@ -144,6 +151,7 @@ var DEFAULT_BASE_URL = "https://api.stophy.dev";
144
151
  var DEFAULT_TIMEOUT_MS = 7e4;
145
152
  var MAX_RETRY_WAIT_SECONDS = 60;
146
153
  var RETRYABLE_STATUS = /* @__PURE__ */ new Set([429, 500, 502, 503, 504]);
154
+ var JOB_STARTS = /* @__PURE__ */ new Set(["/v1/batch/scrape", "/v1/crawl"]);
147
155
  var USER_AGENT = `stophy-typescript/${version}`;
148
156
  function createCaller(options) {
149
157
  const baseFetch = options.fetch ?? globalThis.fetch;
@@ -163,6 +171,9 @@ function createCaller(options) {
163
171
  }
164
172
  headers.set("accept", "application/json");
165
173
  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
+ const hasApiKey = headers.has("authorization");
166
177
  const url = withQuery(`${baseUrl}${spec.path}`, spec.query);
167
178
  return send2(
168
179
  baseFetch,
@@ -174,35 +185,75 @@ function createCaller(options) {
174
185
  signal
175
186
  }),
176
187
  spec.options?.signal,
177
- spec.method === "DELETE" ? { ...retry, maxRetries: 0 } : retry
188
+ spec.method === "DELETE" ? { ...retry, maxRetries: 0 } : retry,
189
+ {
190
+ key: hasApiKey ? key : void 0,
191
+ hasApiKey,
192
+ replayable: key === void 0 || !hasApiKey || answerIsKept(spec.path, parseJson(JSON.stringify(spec.body ?? null)))
193
+ }
178
194
  );
179
195
  };
180
196
  }
181
- async function send2(baseFetch, url, init, signal, retry) {
197
+ function answerIsKept(path, body) {
198
+ if (JOB_STARTS.has(path) || !isRecord(body)) return true;
199
+ return ![body, body.scrapeOptions, body.options].some(
200
+ (part) => isRecord(part) && part.zeroDataRetention === true
201
+ );
202
+ }
203
+ var NEVER_SENT = /* @__PURE__ */ new Set([
204
+ "ECONNREFUSED",
205
+ "ENOTFOUND",
206
+ "EAI_AGAIN",
207
+ "ENETUNREACH",
208
+ "EHOSTUNREACH",
209
+ "UND_ERR_CONNECT_TIMEOUT"
210
+ ]);
211
+ var requestMayHaveLeft = (error) => !NEVER_SENT.has(error.code ?? error.cause?.code ?? "");
212
+ 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
+ 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 }
221
+ });
222
+ }
223
+ async function send2(baseFetch, url, init, signal, retry, plan) {
224
+ 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;
182
227
  for (let n = 0; ; n += 1) {
183
228
  const deadline = withDeadline(signal, retry.timeoutMs);
184
229
  let waitMs;
185
230
  try {
186
231
  const response = await baseFetch(url, init(deadline.signal)).catch((error) => {
187
- if (deadline.signal.aborted || n >= retry.maxRetries) throw error;
232
+ if (signal?.aborted) throw error;
233
+ const mayHaveLeft = requestMayHaveLeft(error);
234
+ if (mayHaveLeft && !plan.replayable) throw Object.assign(error, { outcomeUnknown: true });
235
+ if (error.name === "TimeoutError" && !plan.hasApiKey) throw error;
236
+ if (n >= retry.maxRetries) {
237
+ throw (mayHaveLeft || earlierSendLost) && plan.key !== void 0 ? Object.assign(error, { idempotencyKey: plan.key }) : error;
238
+ }
239
+ earlierSendLost ||= mayHaveLeft;
188
240
  return void 0;
189
241
  });
190
242
  if (response === void 0) {
191
243
  waitMs = backoffMs(n, retry.initialDelayMs);
192
- } else if (n < retry.maxRetries && RETRYABLE_STATUS.has(response.status)) {
244
+ } else if (response.ok) {
245
+ return await readBody(response);
246
+ } else {
193
247
  const error = await errorFrom(response);
194
248
  const seconds = error.retryAfterSeconds;
195
- if (seconds !== void 0 && seconds > MAX_RETRY_WAIT_SECONDS) {
196
- throw error;
197
- }
249
+ if (!error.retryable || n >= retry.maxRetries) throw failWith(error);
250
+ if (seconds !== void 0 && seconds > MAX_RETRY_WAIT_SECONDS) throw failWith(error);
198
251
  waitMs = seconds === void 0 ? backoffMs(n, retry.initialDelayMs) : seconds * 1e3;
199
- } else {
200
- return await readBody(response);
201
252
  }
202
253
  } finally {
203
254
  deadline.clear();
204
255
  }
205
- await sleep(waitMs);
256
+ await sleep(waitMs, signal);
206
257
  }
207
258
  }
208
259
  function withDeadline(signal, timeoutMs) {
@@ -225,7 +276,6 @@ function withDeadline(signal, timeoutMs) {
225
276
  };
226
277
  }
227
278
  async function readBody(response) {
228
- if (!response.ok) throw await errorFrom(response);
229
279
  const text = await response.text();
230
280
  if (!text) {
231
281
  throw failed(response, "Stophy returned an empty response", {});
@@ -239,11 +289,12 @@ async function readBody(response) {
239
289
  async function errorFrom(response) {
240
290
  const text = await response.text();
241
291
  const error = readError(text ? parseJson(text) : null);
242
- const retryAfterSeconds = error.retryAfterSeconds ?? headerRetryAfter(response);
243
292
  return failed(response, error.message ?? `Stophy request failed with status ${response.status}`, {
244
293
  code: error.code,
245
- retryable: RETRYABLE_STATUS.has(response.status),
246
- retryAfterSeconds
294
+ retryable: error.retryable ?? RETRYABLE_STATUS.has(response.status),
295
+ retryAfterSeconds: error.retryAfterSeconds ?? headerRetryAfter(response),
296
+ requestId: headerRequestId(response) ?? error.requestId,
297
+ details: error.details
247
298
  });
248
299
  }
249
300
  function failed(response, message, options) {
@@ -252,7 +303,8 @@ function failed(response, message, options) {
252
303
  code: options.code,
253
304
  retryable: options.retryable ?? false,
254
305
  retryAfterSeconds: options.retryAfterSeconds,
255
- requestId: options.requestId ?? headerRequestId(response)
306
+ requestId: options.requestId ?? headerRequestId(response),
307
+ details: options.details
256
308
  });
257
309
  }
258
310
  function parseJson(text) {
@@ -262,12 +314,27 @@ function parseJson(text) {
262
314
  return null;
263
315
  }
264
316
  }
317
+ var ENVELOPE_FIELDS = /* @__PURE__ */ new Set([
318
+ "success",
319
+ "error",
320
+ "message",
321
+ "code",
322
+ "retryable",
323
+ "retryAfterSeconds",
324
+ "requestId"
325
+ ]);
265
326
  function readError(body) {
266
327
  if (!isRecord(body)) return {};
328
+ const fields = isRecord(body.error) ? body.error : body;
267
329
  return {
268
- code: isString(body.code) ? body.code : void 0,
269
- message: isString(body.error) ? body.error : void 0,
270
- retryAfterSeconds: isNumber(body.retryAfterSeconds) ? body.retryAfterSeconds : void 0
330
+ code: isString(fields.code) ? fields.code : void 0,
331
+ message: isString(fields.error) ? fields.error : isString(fields.message) ? fields.message : void 0,
332
+ retryable: isBoolean(fields.retryable) ? fields.retryable : void 0,
333
+ retryAfterSeconds: isNumber(fields.retryAfterSeconds) ? fields.retryAfterSeconds : void 0,
334
+ requestId: isString(fields.requestId) ? fields.requestId : void 0,
335
+ details: Object.fromEntries(
336
+ Object.entries(fields).filter(([key]) => !ENVELOPE_FIELDS.has(key))
337
+ )
271
338
  };
272
339
  }
273
340
  function headerRequestId(response) {
@@ -295,8 +362,19 @@ function backoffMs(attempt, base) {
295
362
  const window = base * 2 ** attempt;
296
363
  return window / 2 + Math.random() * (window / 2);
297
364
  }
298
- function sleep(ms) {
299
- return new Promise((resolve) => setTimeout(resolve, ms));
365
+ function sleep(ms, signal) {
366
+ return new Promise((resolve, reject) => {
367
+ if (signal?.aborted) return reject(signal.reason);
368
+ const onAbort = () => {
369
+ clearTimeout(timer);
370
+ reject(signal?.reason);
371
+ };
372
+ const timer = setTimeout(() => {
373
+ signal?.removeEventListener("abort", onAbort);
374
+ resolve();
375
+ }, ms);
376
+ signal?.addEventListener("abort", onAbort, { once: true });
377
+ });
300
378
  }
301
379
 
302
380
  // src/client.ts