stophy 1.4.1 → 1.5.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +7 -7
- package/dist/index.cjs +156 -38
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +66 -80
- package/dist/index.d.ts +66 -80
- package/dist/index.js +156 -38
- package/dist/index.js.map +1 -1
- package/package.json +1 -1
package/dist/index.js
CHANGED
|
@@ -102,9 +102,6 @@ var Surface = class {
|
|
|
102
102
|
}
|
|
103
103
|
};
|
|
104
104
|
|
|
105
|
-
// package.json
|
|
106
|
-
var version = "1.4.1";
|
|
107
|
-
|
|
108
105
|
// src/errors.ts
|
|
109
106
|
var StophyError = class extends Error {
|
|
110
107
|
code;
|
|
@@ -125,6 +122,9 @@ var StophyError = class extends Error {
|
|
|
125
122
|
}
|
|
126
123
|
};
|
|
127
124
|
|
|
125
|
+
// package.json
|
|
126
|
+
var version = "1.5.0";
|
|
127
|
+
|
|
128
128
|
// src/json.ts
|
|
129
129
|
function tagOf(value) {
|
|
130
130
|
return Object.prototype.toString.call(value);
|
|
@@ -147,7 +147,16 @@ var DEFAULT_BASE_URL = "https://api.stophy.dev";
|
|
|
147
147
|
var DEFAULT_TIMEOUT_MS = 7e4;
|
|
148
148
|
var MAX_RETRY_WAIT_SECONDS = 60;
|
|
149
149
|
var RETRYABLE_STATUS = /* @__PURE__ */ new Set([429, 500, 502, 503, 504]);
|
|
150
|
-
var JOB_STARTS = /* @__PURE__ */ new Set(["/v1/batch/scrape", "/v1/crawl"]);
|
|
150
|
+
var JOB_STARTS = /* @__PURE__ */ new Set(["/v1/agent", "/v1/batch/scrape", "/v1/crawl"]);
|
|
151
|
+
var BROWSER_TASK_STATUS = "/v1/browser/task/status";
|
|
152
|
+
var KEYLESS_READS = /* @__PURE__ */ new Set(["/v1/map", "/v1/parse", "/v1/scrape", "/v1/search"]);
|
|
153
|
+
var KEYED_POSTS = /* @__PURE__ */ new Set([
|
|
154
|
+
...JOB_STARTS,
|
|
155
|
+
...KEYLESS_READS,
|
|
156
|
+
BROWSER_TASK_STATUS,
|
|
157
|
+
"/v1/browser/task",
|
|
158
|
+
"/v1/extract"
|
|
159
|
+
]);
|
|
151
160
|
var USER_AGENT = `stophy-typescript/${version}`;
|
|
152
161
|
function createCaller(options) {
|
|
153
162
|
const baseFetch = options.fetch ?? globalThis.fetch;
|
|
@@ -167,9 +176,12 @@ function createCaller(options) {
|
|
|
167
176
|
}
|
|
168
177
|
headers.set("accept", "application/json");
|
|
169
178
|
if (spec.body !== void 0) headers.set("content-type", "application/json");
|
|
170
|
-
const key = spec.method === "POST" ? spec.options?.idempotencyKey ?? headers.get("idempotency-key") ?? crypto.randomUUID() : void 0;
|
|
171
|
-
if (key !== void 0) headers.set("idempotency-key", key);
|
|
172
179
|
const hasApiKey = headers.has("authorization");
|
|
180
|
+
const keyed = spec.method === "POST" && hasApiKey && KEYED_POSTS.has(spec.path);
|
|
181
|
+
const key = spec.method === "POST" ? spec.options?.idempotencyKey ?? headers.get("idempotency-key") ?? (keyed ? crypto.randomUUID() : void 0) : void 0;
|
|
182
|
+
if (key !== void 0) headers.set("idempotency-key", key);
|
|
183
|
+
const body = spec.body === void 0 ? void 0 : JSON.stringify(spec.body);
|
|
184
|
+
const protectedKey = keyed && answerIsKept(spec.path, parseJson(body ?? "")) ? key : void 0;
|
|
173
185
|
const url = withQuery(`${baseUrl}${spec.path}`, spec.query);
|
|
174
186
|
return send2(
|
|
175
187
|
baseFetch,
|
|
@@ -177,15 +189,16 @@ function createCaller(options) {
|
|
|
177
189
|
(signal) => ({
|
|
178
190
|
method: spec.method,
|
|
179
191
|
headers,
|
|
180
|
-
body
|
|
192
|
+
body,
|
|
181
193
|
signal
|
|
182
194
|
}),
|
|
183
195
|
spec.options?.signal,
|
|
184
196
|
spec.method === "DELETE" ? { ...retry, maxRetries: 0 } : retry,
|
|
185
197
|
{
|
|
186
|
-
key:
|
|
198
|
+
key: protectedKey,
|
|
187
199
|
hasApiKey,
|
|
188
|
-
|
|
200
|
+
path: spec.path,
|
|
201
|
+
replayable: spec.method !== "POST" || spec.path === BROWSER_TASK_STATUS || !hasApiKey && KEYLESS_READS.has(spec.path) || protectedKey !== void 0
|
|
189
202
|
}
|
|
190
203
|
);
|
|
191
204
|
};
|
|
@@ -205,42 +218,71 @@ var NEVER_SENT = /* @__PURE__ */ new Set([
|
|
|
205
218
|
"UND_ERR_CONNECT_TIMEOUT"
|
|
206
219
|
]);
|
|
207
220
|
var requestMayHaveLeft = (error) => !NEVER_SENT.has(error.code ?? error.cause?.code ?? "");
|
|
221
|
+
var mayHaveRun = (error) => error.status === 408 || error.status >= 500 && error.code !== "busy";
|
|
208
222
|
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.";
|
|
209
223
|
function mayStillComplete(error, key) {
|
|
210
|
-
return
|
|
211
|
-
|
|
212
|
-
|
|
213
|
-
|
|
214
|
-
|
|
215
|
-
|
|
216
|
-
|
|
224
|
+
return Object.assign(
|
|
225
|
+
new StophyError(`${error.message} An earlier send may still complete. ${SEND_AGAIN}`, {
|
|
226
|
+
status: error.status,
|
|
227
|
+
code: error.code,
|
|
228
|
+
retryable: error.retryable,
|
|
229
|
+
retryAfterSeconds: error.retryAfterSeconds,
|
|
230
|
+
requestId: error.requestId,
|
|
231
|
+
details: { ...error.details, idempotencyKey: key }
|
|
232
|
+
}),
|
|
233
|
+
{ outcomeUnknown: true }
|
|
234
|
+
);
|
|
235
|
+
}
|
|
236
|
+
function abortReason(signal, key) {
|
|
237
|
+
const reason = signal.reason;
|
|
238
|
+
if (key === void 0) return reason;
|
|
239
|
+
const error = new Error(reason instanceof Error ? reason.message : "Stophy request cancelled", {
|
|
240
|
+
cause: reason
|
|
217
241
|
});
|
|
242
|
+
if (reason instanceof Error) error.name = reason.name;
|
|
243
|
+
return Object.assign(error, { idempotencyKey: key, outcomeUnknown: true });
|
|
218
244
|
}
|
|
219
245
|
async function send2(baseFetch, url, init, signal, retry, plan) {
|
|
220
246
|
let earlierSendLost = false;
|
|
221
|
-
const
|
|
222
|
-
const failWith = (error) => plan.key !== void 0 && earlierSendLost && mayHaveRun(error) ? mayStillComplete(error, plan.key) : error;
|
|
247
|
+
const failWith = (error) => plan.key !== void 0 && earlierSendLost ? mayStillComplete(error, plan.key) : error;
|
|
223
248
|
for (let n = 0; ; n += 1) {
|
|
249
|
+
if (signal?.aborted) throw abortReason(signal, earlierSendLost ? plan.key : void 0);
|
|
224
250
|
const deadline = withDeadline(signal, retry.timeoutMs);
|
|
225
251
|
let waitMs;
|
|
226
252
|
try {
|
|
227
|
-
const
|
|
228
|
-
if (signal?.aborted)
|
|
253
|
+
const answer = await baseFetch(url, init(deadline.signal)).then(async (response) => ({ response, text: await response.text() })).catch((error) => {
|
|
254
|
+
if (signal?.aborted) {
|
|
255
|
+
earlierSendLost ||= !(error instanceof Error) || requestMayHaveLeft(error);
|
|
256
|
+
throw abortReason(signal, earlierSendLost ? plan.key : void 0);
|
|
257
|
+
}
|
|
229
258
|
const mayHaveLeft = requestMayHaveLeft(error);
|
|
230
259
|
if (mayHaveLeft && !plan.replayable) throw Object.assign(error, { outcomeUnknown: true });
|
|
231
260
|
if (error.name === "TimeoutError" && !plan.hasApiKey) throw error;
|
|
232
261
|
if (n >= retry.maxRetries) {
|
|
233
|
-
throw (mayHaveLeft || earlierSendLost) && plan.key !== void 0 ? Object.assign(error, { idempotencyKey: plan.key }) : error;
|
|
262
|
+
throw (mayHaveLeft || earlierSendLost) && plan.key !== void 0 ? Object.assign(error, { idempotencyKey: plan.key, outcomeUnknown: true }) : error;
|
|
234
263
|
}
|
|
235
264
|
earlierSendLost ||= mayHaveLeft;
|
|
236
265
|
return void 0;
|
|
237
266
|
});
|
|
238
|
-
if (
|
|
267
|
+
if (answer === void 0) {
|
|
239
268
|
waitMs = backoffMs(n, retry.initialDelayMs);
|
|
240
|
-
} else if (response.ok) {
|
|
241
|
-
return await readBody(response);
|
|
242
269
|
} else {
|
|
243
|
-
const
|
|
270
|
+
const { response, text } = answer;
|
|
271
|
+
if (response.ok) {
|
|
272
|
+
try {
|
|
273
|
+
return readBody(response, text);
|
|
274
|
+
} catch (error2) {
|
|
275
|
+
if (!(error2 instanceof StophyError)) throw error2;
|
|
276
|
+
earlierSendLost = true;
|
|
277
|
+
throw !plan.replayable ? Object.assign(error2, { outcomeUnknown: true }) : failWith(error2);
|
|
278
|
+
}
|
|
279
|
+
}
|
|
280
|
+
const error = errorFrom(response, text);
|
|
281
|
+
earlierSendLost ||= error.code === void 0 && mayHaveRun(error);
|
|
282
|
+
const definiteScrapeFailure = plan.path === "/v1/scrape" && (error.status === 504 && error.code === "sourceTimeout" || error.status === 503 && error.code === "sourceUnavailable");
|
|
283
|
+
if (!plan.replayable && mayHaveRun(error) && !definiteScrapeFailure) {
|
|
284
|
+
throw Object.assign(error, { outcomeUnknown: true });
|
|
285
|
+
}
|
|
244
286
|
const seconds = error.retryAfterSeconds;
|
|
245
287
|
if (!error.retryable || n >= retry.maxRetries) throw failWith(error);
|
|
246
288
|
if (seconds !== void 0 && seconds > MAX_RETRY_WAIT_SECONDS) throw failWith(error);
|
|
@@ -249,20 +291,19 @@ async function send2(baseFetch, url, init, signal, retry, plan) {
|
|
|
249
291
|
} finally {
|
|
250
292
|
deadline.clear();
|
|
251
293
|
}
|
|
252
|
-
|
|
294
|
+
try {
|
|
295
|
+
await sleep(waitMs, signal);
|
|
296
|
+
} catch (error) {
|
|
297
|
+
throw signal?.aborted ? abortReason(signal, earlierSendLost ? plan.key : void 0) : error;
|
|
298
|
+
}
|
|
253
299
|
}
|
|
254
300
|
}
|
|
255
|
-
function withDeadline(signal, timeoutMs) {
|
|
301
|
+
function withDeadline(signal, timeoutMs, reason = () => new DOMException(`Stophy request timed out after ${timeoutMs} ms`, "TimeoutError")) {
|
|
256
302
|
const controller = new AbortController();
|
|
257
303
|
const abort = () => controller.abort(signal?.reason);
|
|
258
304
|
if (signal?.aborted) abort();
|
|
259
305
|
else signal?.addEventListener("abort", abort, { once: true });
|
|
260
|
-
const timer = setTimeout(
|
|
261
|
-
() => controller.abort(
|
|
262
|
-
new DOMException(`Stophy request timed out after ${timeoutMs} ms`, "TimeoutError")
|
|
263
|
-
),
|
|
264
|
-
timeoutMs
|
|
265
|
-
);
|
|
306
|
+
const timer = setTimeout(() => controller.abort(reason()), timeoutMs);
|
|
266
307
|
return {
|
|
267
308
|
signal: controller.signal,
|
|
268
309
|
clear: () => {
|
|
@@ -271,8 +312,7 @@ function withDeadline(signal, timeoutMs) {
|
|
|
271
312
|
}
|
|
272
313
|
};
|
|
273
314
|
}
|
|
274
|
-
|
|
275
|
-
const text = await response.text();
|
|
315
|
+
function readBody(response, text) {
|
|
276
316
|
if (!text) {
|
|
277
317
|
throw failed(response, "Stophy returned an empty response", {});
|
|
278
318
|
}
|
|
@@ -282,14 +322,13 @@ async function readBody(response) {
|
|
|
282
322
|
throw failed(response, "Stophy returned a non-JSON response", {});
|
|
283
323
|
}
|
|
284
324
|
}
|
|
285
|
-
|
|
286
|
-
const text = await response.text();
|
|
325
|
+
function errorFrom(response, text) {
|
|
287
326
|
const error = readError(text ? parseJson(text) : null);
|
|
288
327
|
return failed(response, error.message ?? `Stophy request failed with status ${response.status}`, {
|
|
289
328
|
code: error.code,
|
|
290
329
|
retryable: error.retryable ?? RETRYABLE_STATUS.has(response.status),
|
|
291
330
|
retryAfterSeconds: error.retryAfterSeconds ?? headerRetryAfter(response),
|
|
292
|
-
requestId: headerRequestId(response)
|
|
331
|
+
requestId: error.requestId ?? headerRequestId(response),
|
|
293
332
|
details: error.details
|
|
294
333
|
});
|
|
295
334
|
}
|
|
@@ -373,6 +412,73 @@ function sleep(ms, signal) {
|
|
|
373
412
|
});
|
|
374
413
|
}
|
|
375
414
|
|
|
415
|
+
// src/results.ts
|
|
416
|
+
var START = "ck_start";
|
|
417
|
+
var ENDED = /* @__PURE__ */ new Set(["completed", "failed", "cancelled"]);
|
|
418
|
+
var DEFAULT_POLL_MS = 2e3;
|
|
419
|
+
var DEFAULT_TIMEOUT_MS2 = 15 * 6e4;
|
|
420
|
+
async function* checkpointResults(readPage, options = {}) {
|
|
421
|
+
const { signal, onCheckpoint } = options;
|
|
422
|
+
const pollMs = options.pollIntervalMs ?? DEFAULT_POLL_MS;
|
|
423
|
+
const deadline = performance.now() + (options.timeoutMs ?? DEFAULT_TIMEOUT_MS2);
|
|
424
|
+
let checkpoint = options.checkpoint ?? START;
|
|
425
|
+
for (; ; ) {
|
|
426
|
+
signal?.throwIfAborted();
|
|
427
|
+
const remaining = deadline - performance.now();
|
|
428
|
+
if (remaining <= 0) throw resultsTimeout(checkpoint);
|
|
429
|
+
const page = await readWithinBudget(readPage, checkpoint, remaining, signal);
|
|
430
|
+
if (performance.now() >= deadline) throw resultsTimeout(checkpoint);
|
|
431
|
+
if (page.checkpoint === void 0) {
|
|
432
|
+
throw new StophyError("The job's answer carried no checkpoint to resume from.", {
|
|
433
|
+
status: 0,
|
|
434
|
+
code: "checkpointMissing",
|
|
435
|
+
retryable: false
|
|
436
|
+
});
|
|
437
|
+
}
|
|
438
|
+
const results = page.data ?? [];
|
|
439
|
+
yield* results;
|
|
440
|
+
checkpoint = page.checkpoint;
|
|
441
|
+
onCheckpoint?.(checkpoint);
|
|
442
|
+
if (results.length > 0) continue;
|
|
443
|
+
if (ENDED.has(page.status)) return { status: page.status, checkpoint };
|
|
444
|
+
if (performance.now() + pollMs >= deadline) throw resultsTimeout(checkpoint);
|
|
445
|
+
await sleep2(pollMs, signal);
|
|
446
|
+
}
|
|
447
|
+
}
|
|
448
|
+
function resultsTimeout(checkpoint) {
|
|
449
|
+
return new StophyError("Gave up waiting for more results. Resume with the checkpoint.", {
|
|
450
|
+
status: 0,
|
|
451
|
+
code: "resultsTimeout",
|
|
452
|
+
retryable: true,
|
|
453
|
+
details: { checkpoint }
|
|
454
|
+
});
|
|
455
|
+
}
|
|
456
|
+
async function readWithinBudget(readPage, checkpoint, remaining, signal) {
|
|
457
|
+
if (remaining > 2147483647) return readPage(checkpoint, { signal });
|
|
458
|
+
const call = withDeadline(signal, remaining, () => resultsTimeout(checkpoint));
|
|
459
|
+
try {
|
|
460
|
+
const page = await readPage(checkpoint, { signal: call.signal });
|
|
461
|
+
call.signal.throwIfAborted();
|
|
462
|
+
return page;
|
|
463
|
+
} finally {
|
|
464
|
+
call.clear();
|
|
465
|
+
}
|
|
466
|
+
}
|
|
467
|
+
function sleep2(ms, signal) {
|
|
468
|
+
return new Promise((resolve, reject) => {
|
|
469
|
+
if (signal?.aborted) return reject(signal.reason);
|
|
470
|
+
const onAbort = () => {
|
|
471
|
+
clearTimeout(timer);
|
|
472
|
+
reject(signal?.reason);
|
|
473
|
+
};
|
|
474
|
+
const timer = setTimeout(() => {
|
|
475
|
+
signal?.removeEventListener("abort", onAbort);
|
|
476
|
+
resolve();
|
|
477
|
+
}, ms);
|
|
478
|
+
signal?.addEventListener("abort", onAbort, { once: true });
|
|
479
|
+
});
|
|
480
|
+
}
|
|
481
|
+
|
|
376
482
|
// src/client.ts
|
|
377
483
|
function env(name) {
|
|
378
484
|
return globalThis.process?.env[name];
|
|
@@ -388,6 +494,18 @@ var Stophy = class extends Surface {
|
|
|
388
494
|
});
|
|
389
495
|
super(call);
|
|
390
496
|
}
|
|
497
|
+
crawlResults(id, options) {
|
|
498
|
+
return checkpointResults(
|
|
499
|
+
(checkpoint, call) => this.crawl.status({ id, checkpoint }, call),
|
|
500
|
+
options
|
|
501
|
+
);
|
|
502
|
+
}
|
|
503
|
+
batchScrapeResults(id, options) {
|
|
504
|
+
return checkpointResults(
|
|
505
|
+
(checkpoint, call) => this.batch.scrape.status({ id, checkpoint }, call),
|
|
506
|
+
options
|
|
507
|
+
);
|
|
508
|
+
}
|
|
391
509
|
parsed(parser, url, options, request) {
|
|
392
510
|
return this.scrape({ url, formats: [{ type: "json", parser, options }] }, request);
|
|
393
511
|
}
|
package/dist/index.js.map
CHANGED
|
@@ -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,SAAS,YAAA,CAA6B,MAAc,IAAA,EAAc;AACvE,EAAA,OAAO,CAAC,IAAA,EAAa,OAAA,KACnB,IAAA,CAAe,EAAE,MAAA,EAAQ,MAAA,EAAQ,IAAA,EAAM,IAAA,EAAM,IAAA,IAAQ,EAAC,EAAG,SAAS,CAAA;AACtE;AAEO,SAAS,IAAA,CAAoC,MAAA,EAAgB,IAAA,EAAc,IAAA,EAAc;AAC9F,EAAA,OAAO,CAAC,KAAA,EAAc,OAAA,KACpB,IAAA,CAAe,EAAE,MAAA,EAAQ,GAAG,QAAA,CAAS,IAAA,EAAM,KAAK,CAAA,EAAG,OAAA,EAAS,CAAA;AAChE;AAEO,SAAS,YAAA,CACd,MAAA,EACA,IAAA,EACA,IAAA,EACA;AACA,EAAA,OAAO,CAAC,KAAA,EAAe,OAAA,KACrB,IAAA,CAAe,EAAE,MAAA,EAAQ,GAAG,QAAA,CAAS,IAAA,EAAM,KAAA,IAAS,EAAE,CAAA,EAAG,SAAS,CAAA;AACtE;AAEO,SAAS,SAAA,CAAoB,MAAA,EAAgB,IAAA,EAAc,IAAA,EAAc;AAC9E,EAAA,OAAO,CAAC,OAAA,KAAgD,IAAA,CAAe,EAAE,MAAA,EAAQ,IAAA,EAAM,SAAS,CAAA;AAClG;AAEA,SAAS,QAAA,CAAS,UAAkB,KAAA,EAAc;AAChD,EAAA,MAAM,IAAA,uBAAW,GAAA,EAAY;AAC7B,EAAA,MAAM,OAAO,QAAA,CAAS,UAAA,CAAW,YAAA,EA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KAAA,GAAQ,EAAE,QAAQ,KAAA,EAAM;AAClE,IAAA,MAAM,MAAA,GAAS,QAAQ,MAAA,EAAQ,IAAA,MAAU,GAAA,CAAI,gBAAgB,GAAG,IAAA,EAAK;AACrE,IAAA,MAAM,OAAO,YAAA,CAAa;AAAA,MACxB,GAAG,OAAA;AAAA,MACH,MAAA;AAAA,MACA,OAAA,EAAS,OAAA,CAAQ,OAAA,IAAW,GAAA,CAAI,iBAAiB;AAAA,KAClD,CAAA;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.js","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.1\",\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\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","../src/errors.ts","../package.json","../src/json.ts","../src/transport.ts","../src/results.ts","../src/client.ts"],"names":["send","error","DEFAULT_TIMEOUT_M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AA,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.js","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","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","{\n \"name\": \"stophy\",\n \"version\": \"1.5.0\",\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","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\nexport function withDeadline(\n signal: AbortSignal | undefined,\n timeoutMs: number,\n reason = (): Error =>\n new DOMException(`Stophy request timed out after ${timeoutMs} ms`, \"TimeoutError\"),\n) {\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(() => controller.abort(reason()), timeoutMs);\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 { StophyError } from \"./errors\";\nimport { type CallOptions, withDeadline } from \"./transport\";\n\nconst START = \"ck_start\";\nconst ENDED = new Set([\"completed\", \"failed\", \"cancelled\"]);\nconst DEFAULT_POLL_MS = 2_000;\nconst DEFAULT_TIMEOUT_MS = 15 * 60_000;\n\nexport interface ResultsOptions {\n checkpoint?: string;\n pollIntervalMs?: number;\n timeoutMs?: number;\n signal?: AbortSignal;\n onCheckpoint?: (checkpoint: string) => void;\n}\n\nexport interface ResultsEnd {\n status: string;\n checkpoint: string;\n}\n\ninterface StatusPage<Item> {\n status: string;\n checkpoint?: string;\n data?: Item[];\n}\n\nexport type ReadPage<Item> = (checkpoint: string, call: CallOptions) => Promise<StatusPage<Item>>;\n\nexport async function* checkpointResults<Item>(\n readPage: ReadPage<Item>,\n options: ResultsOptions = {},\n): AsyncGenerator<Item, ResultsEnd> {\n const { signal, onCheckpoint } = options;\n const pollMs = options.pollIntervalMs ?? DEFAULT_POLL_MS;\n const deadline = performance.now() + (options.timeoutMs ?? DEFAULT_TIMEOUT_MS);\n let checkpoint = options.checkpoint ?? START;\n\n for (;;) {\n signal?.throwIfAborted();\n const remaining = deadline - performance.now();\n if (remaining <= 0) throw resultsTimeout(checkpoint);\n const page = await readWithinBudget(readPage, checkpoint, remaining, signal);\n if (performance.now() >= deadline) throw resultsTimeout(checkpoint);\n if (page.checkpoint === undefined) {\n throw new StophyError(\"The job's answer carried no checkpoint to resume from.\", {\n status: 0,\n code: \"checkpointMissing\",\n retryable: false,\n });\n }\n const results = page.data ?? [];\n yield* results;\n checkpoint = page.checkpoint;\n onCheckpoint?.(checkpoint);\n if (results.length > 0) continue;\n if (ENDED.has(page.status)) return { status: page.status, checkpoint };\n if (performance.now() + pollMs >= deadline) throw resultsTimeout(checkpoint);\n await sleep(pollMs, signal);\n }\n}\n\nfunction resultsTimeout(checkpoint: string): StophyError {\n return new StophyError(\"Gave up waiting for more results. Resume with the checkpoint.\", {\n status: 0,\n code: \"resultsTimeout\",\n retryable: true,\n details: { checkpoint },\n });\n}\n\nasync function readWithinBudget<Item>(\n readPage: ReadPage<Item>,\n checkpoint: string,\n remaining: number,\n signal: AbortSignal | undefined,\n): Promise<StatusPage<Item>> {\n if (remaining > 2_147_483_647) return readPage(checkpoint, { signal });\n const call = withDeadline(signal, remaining, () => resultsTimeout(checkpoint));\n try {\n const page = await readPage(checkpoint, { signal: call.signal });\n call.signal.throwIfAborted();\n return page;\n } finally {\n call.clear();\n }\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 {\n BatchScrapeStatusResponse,\n CrawlStatusResponse,\n ScrapeData,\n ScrapeResponse,\n} from \"./generated/types.gen\";\nimport { checkpointResults, type ResultsEnd, type ResultsOptions } from \"./results\";\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 crawlResults(\n id: string,\n options?: ResultsOptions,\n ): AsyncGenerator<NonNullable<CrawlStatusResponse[\"data\"]>[number], ResultsEnd> {\n return checkpointResults(\n (checkpoint, call) => this.crawl.status({ id, checkpoint }, call),\n options,\n );\n }\n\n batchScrapeResults(\n id: string,\n options?: ResultsOptions,\n ): AsyncGenerator<NonNullable<BatchScrapeStatusResponse[\"data\"]>[number], ResultsEnd> {\n return checkpointResults(\n (checkpoint, call) => this.batch.scrape.status({ id, checkpoint }, call),\n options,\n );\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"]}
|