@howells/fieldwork-sdk 0.5.1 → 0.6.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.
@@ -1,17 +1,13 @@
1
1
  import { t as defineAdapter } from "./adapter-DWYJys20.js";
2
- import { r as invalidRequest, t as FieldworkError } from "./errors-Yvk42oZH.js";
3
- import { A as citationOf, B as requireJobId, C as createRawClient, E as segment, F as parseJson, M as compact, P as meta, S as withOriginal, T as requireKey, V as uniqueCitations, a as looseObject, d as optionalId, f as optionalNumber, h as optionalString, i as both, k as callSettings, m as optionalScalar, n as anything, r as arrayOf, t as Source, v as recordOf, y as sourceShape, z as refuseTogether } from "./parse-n8MmaK1x.js";
4
- import { t as runJob } from "./job-BGTwH3F-.js";
5
- import { n as jsonSchemaOf, t as checkOutput } from "./schema-DbSIABP0.js";
2
+ import { r as invalidRequest, t as FieldworkError } from "./errors-DROZyb9T.js";
3
+ import { A as citationOf, C as createRawClient, E as segment, F as parseJson, M as compact, P as meta, S as withOriginal, T as requireKey, V as uniqueCitations, a as looseObject, d as optionalId, f as optionalNumber, h as optionalString, i as both, k as callSettings, m as optionalScalar, n as anything, r as arrayOf, t as Source, v as recordOf, y as sourceShape, z as refuseTogether } from "./parse-COHKvfH9.js";
4
+ import { i as startJob, r as runJob, t as jobState } from "./job-CWHOfhP_.js";
5
+ import { n as jsonSchemaOf, t as checkOutput } from "./schema-BYcXgfuZ.js";
6
6
  import * as z from "zod/mini";
7
7
  // src/adapters/perplexity/parse.ts
8
+ /** The name this adapter reports in errors and results. */
8
9
  const provider = "perplexity";
9
- const TERMINAL = /* @__PURE__ */ new Set([
10
- "completed",
11
- "failed",
12
- "incomplete",
13
- "cancelled"
14
- ]);
10
+ /** Perplexity's MM/DD/YYYY form of a YYYY-MM-DD date. Refuses any other format. */
15
11
  const usDate = (name, date) => {
16
12
  if (date === void 0) return date;
17
13
  const match = /^(?<year>\d{4})-(?<month>\d{2})-(?<day>\d{2})$/u.exec(date);
@@ -19,6 +15,10 @@ const usDate = (name, date) => {
19
15
  const { year, month, day } = match.groups;
20
16
  return `${month}/${day}/${year}`;
21
17
  };
18
+ /**
19
+ * The filter fields `/search` and the `web_search` tool share. Refuses both domain
20
+ * lists together, since Perplexity has one list and marks exclusions with `-`.
21
+ */
22
22
  const filterFields = (o) => {
23
23
  refuseTogether(provider, { ...o }, "includeDomains", "excludeDomains");
24
24
  const domains = o.includeDomains ?? o.excludeDomains?.map((d) => `-${d}`);
@@ -31,6 +31,10 @@ const filterFields = (o) => {
31
31
  search_recency_filter: o.recency
32
32
  });
33
33
  };
34
+ /**
35
+ * The `web_search` tool with the filters and `country` (as the user's location), or
36
+ * undefined when none is set, so the effort's own tool applies.
37
+ */
34
38
  const webSearchTool = (o) => {
35
39
  const filters = filterFields(o);
36
40
  const tool = compact({
@@ -40,14 +44,23 @@ const webSearchTool = (o) => {
40
44
  });
41
45
  return Object.keys(tool).length > 1 ? tool : void 0;
42
46
  };
47
+ /** Lower-cased language codes as a list, or undefined when there are none. */
43
48
  const languageCodes = (language) => {
44
49
  const codes = [language ?? []].flat().map((code) => code.toLowerCase());
45
50
  return codes.length > 0 ? codes : void 0;
46
51
  };
52
+ /**
53
+ * `JobFailed` once the run has an id, else `RateLimited` for a rate-limit error,
54
+ * else `ProviderError`.
55
+ */
47
56
  const errorCode = (jobId, rateLimited) => {
48
57
  if (jobId !== void 0 && jobId !== "") return "JobFailed";
49
58
  return rateLimited ? "RateLimited" : "ProviderError";
50
59
  };
60
+ /**
61
+ * The error for an Agent response that failed, was cancelled or has no text. It
62
+ * carries `jobId` when given and is retryable for rate-limit and overloaded errors.
63
+ */
51
64
  const responseError = (run, jobId) => {
52
65
  const { error, status } = run.value;
53
66
  const { type } = error;
@@ -60,7 +73,16 @@ const responseError = (run, jobId) => {
60
73
  retryable: rateLimited || type === "overloaded"
61
74
  });
62
75
  };
76
+ /**
77
+ * The citations in message annotations. Only `url_citation` annotations, or ones
78
+ * with no type, count.
79
+ */
63
80
  const annotated = (annotations) => annotations.filter((found) => found.type === void 0 || found.type === "url_citation").map((found) => citationOf(found)).filter((source) => source !== void 0);
81
+ /**
82
+ * Reads an Agent response. `text` joins every message part. `cited` is the unique
83
+ * sources annotating that text. `retrieved` is the unique pages the run's
84
+ * `search_results` and `fetch_url_results` returned, as title and URL only.
85
+ */
64
86
  const readResponse = (body) => {
65
87
  const parts = [];
66
88
  const cited = [];
@@ -87,6 +109,10 @@ const readResponse = (body) => {
87
109
  text: parts.join("")
88
110
  };
89
111
  };
112
+ /**
113
+ * Meta from an Agent response: cost in USD, token units and the id as `requestId`.
114
+ * `warnings` is one message.
115
+ */
90
116
  const responseMeta = (body, warnings) => {
91
117
  const { usage } = body;
92
118
  const input = usage.input_tokens_details;
@@ -104,6 +130,7 @@ const responseMeta = (body, warnings) => {
104
130
  warnings
105
131
  });
106
132
  };
133
+ /** The Agent `response_format` for a schema, named "output", or undefined. */
107
134
  const responseFormat = (schema) => schema ? {
108
135
  json_schema: {
109
136
  name: "output",
@@ -111,11 +138,21 @@ const responseFormat = (schema) => schema ? {
111
138
  },
112
139
  type: "json_schema"
113
140
  } : void 0;
141
+ /**
142
+ * The decision `state`. A string, object or array goes through as it is; a number
143
+ * or boolean is sent as text; anything else is refused.
144
+ */
114
145
  const decisionState = (context) => {
115
146
  if (typeof context === "string" || typeof context === "object" && context) return context;
116
147
  if (typeof context === "number" || typeof context === "boolean") return String(context);
117
148
  throw invalidRequest(provider, "decide needs a context: a string, object or array");
118
149
  };
150
+ /**
151
+ * The effort, model, step and tool fields of a research run. Refuses `models`
152
+ * outside one to five. With `model` or `models` and no `effort`, the run is built
153
+ * directly: `maxSteps` or 10 steps, with `web_search` and `fetch_url` tools.
154
+ * Otherwise the effort defaults to "high" and a tool is sent only to carry filters.
155
+ */
119
156
  const researchSetup = (o) => {
120
157
  if (o.models && (o.models.length < 1 || o.models.length > 5)) throw invalidRequest(provider, "models takes one to five models");
121
158
  const searchTool = webSearchTool(o);
@@ -133,6 +170,11 @@ const researchSetup = (o) => {
133
170
  tools: searchTool ? [searchTool] : void 0
134
171
  };
135
172
  };
173
+ /**
174
+ * A research run's output: the reply text, or its parsed JSON when a schema is set.
175
+ * Invalid JSON from a completed run throws the parse error; from a run cut short it
176
+ * throws `JobFailed`.
177
+ */
136
178
  const researchOutput = (run, reply, schema) => {
137
179
  if (!schema) return reply;
138
180
  const { status } = run.value;
@@ -146,6 +188,11 @@ const researchOutput = (run, reply, schema) => {
146
188
  });
147
189
  }
148
190
  };
191
+ /**
192
+ * Perplexity's form of a normalized decision question: `yesno` is `noul`, `choice`
193
+ * takes its choices as criteria with no descriptions, and `score` takes the scale's
194
+ * labels, in order, as criteria.
195
+ */
149
196
  const decisionQuestion = (question) => {
150
197
  if (question.type === "yesno") return {
151
198
  instructions: question.question,
@@ -162,13 +209,25 @@ const decisionQuestion = (question) => {
162
209
  type: "score"
163
210
  };
164
211
  };
165
- const decisionAnswer = (found, scores) => {
166
- if (found.type === "noul") return compact({ probability: found.noul });
212
+ /**
213
+ * One decision answer in the shape its question asks for, or undefined when
214
+ * Perplexity left out the part the question needs: a `yesno` answer's `noul`,
215
+ * or a `choice` or `score` answer's choice. `noul` gives a `probability`.
216
+ * Otherwise the probabilities without undefined entries; for a score,
217
+ * Perplexity's level indexes are renamed to the scale's keys. `choice` is
218
+ * Perplexity's, else the most likely.
219
+ */
220
+ const decisionAnswer = (found, question) => {
221
+ if (question.type === "yesno") return found.noul === void 0 ? void 0 : { probability: found.noul };
167
222
  let probabilities = Object.fromEntries(Object.entries(found.probabilities).filter((entry) => entry[1] !== void 0));
168
- if (found.type === "score") probabilities = Object.fromEntries(Object.entries(probabilities).map(([index, probability]) => [scores?.[Number(index)] ?? index, probability]));
223
+ if (question.type === "score") {
224
+ const scores = Object.keys(question.scale);
225
+ probabilities = Object.fromEntries(Object.entries(probabilities).map(([index, probability]) => [scores[Number(index)] ?? index, probability]));
226
+ }
169
227
  const top = Object.entries(probabilities).toSorted((a, b) => b[1] - a[1])[0]?.[0];
170
- return compact({
171
- choice: found.choice ?? top,
228
+ const choice = found.choice ?? top;
229
+ return choice === void 0 ? void 0 : compact({
230
+ choice,
172
231
  confidence: found.confidence,
173
232
  probabilities
174
233
  });
@@ -190,10 +249,15 @@ const Annotation = looseObject({
190
249
  ...sourceShape,
191
250
  type: anything
192
251
  });
252
+ /** One part of a message's content. */
193
253
  const MessagePart = looseObject({
194
254
  annotations: arrayOf(Annotation),
195
255
  text: optionalString
196
256
  });
257
+ /**
258
+ * One item of an Agent response's `output`: a `message` with `content`, or a list
259
+ * of pages in `results` (`search_results`) or `contents` (`fetch_url_results`).
260
+ */
197
261
  const OutputEntry = looseObject({
198
262
  content: arrayOf(MessagePart),
199
263
  contents: arrayOf(Source),
@@ -225,6 +289,10 @@ const Agent = looseObject({
225
289
  const AgentRun = withOriginal(Agent);
226
290
  /** The reply to starting a run: its id as a string, and as it arrived. */
227
291
  const AgentStart = looseObject({ id: withOriginal(optionalId) });
292
+ /**
293
+ * One decision answer. `noul` is a yes/no probability; `probabilities` is keyed by
294
+ * choice, or by zero-based score level.
295
+ */
228
296
  const DecisionAnswer = looseObject({
229
297
  choice: optionalString,
230
298
  confidence: optionalNumber,
@@ -241,11 +309,17 @@ const DecisionsResponse = looseObject({
241
309
  })
242
310
  });
243
311
  // src/adapters/perplexity.ts
312
+ /**
313
+ * `/search`. The query and any `queries` go in one request and come back as one
314
+ * flat list. Refuses more than five queries in all, and a `limit` over 20, or
315
+ * over 50 when `searchType` is "people".
316
+ */
244
317
  const search = async (raw, query, options) => {
245
318
  const { call, rest: o } = callSettings(options);
246
319
  const queries = [query, ...o.queries ?? []];
247
320
  if (queries.length > 5) throw invalidRequest(provider, `search takes at most 5 queries in one request, got ${queries.length}`);
248
- if (o.limit !== void 0 && o.limit > 20 && o.searchType !== "people") throw invalidRequest(provider, "search returns at most 20 results unless searchType is \"people\"");
321
+ const maxResults = o.searchType === "people" ? 50 : 20;
322
+ if (o.limit !== void 0 && o.limit > maxResults) throw invalidRequest(provider, "search returns at most 20 results, or 50 when searchType is \"people\"");
249
323
  const response = await raw.request("POST", "/search", {
250
324
  ...call,
251
325
  body: compact({
@@ -272,6 +346,11 @@ const search = async (raw, query, options) => {
272
346
  }))
273
347
  };
274
348
  };
349
+ /**
350
+ * A synchronous Agent API call at the "fast" effort unless `effort` says
351
+ * otherwise. An `incomplete` response returns its text with a warning; a failed or
352
+ * cancelled one, or one with no text, throws.
353
+ */
275
354
  const answer = async (raw, question, options) => {
276
355
  const { call, rest: o } = callSettings(options);
277
356
  const run = z.parse(AgentRun, await raw.request("POST", "/v1/agent", {
@@ -296,29 +375,49 @@ const answer = async (raw, question, options) => {
296
375
  raw: run.original
297
376
  });
298
377
  };
299
- const startResearch = async (raw, question, o, call) => {
300
- const created = z.parse(AgentStart, await raw.request("POST", "/v1/agent", {
301
- creates: true,
302
- ...call,
303
- body: compact({
304
- ...researchSetup(o),
305
- background: true,
306
- input: question,
307
- instructions: o.instructions,
308
- language_preference: o.languagePreference,
309
- max_output_tokens: o.maxOutputTokens,
310
- previous_response_id: o.continueFrom,
311
- response_format: responseFormat(o.schema)
312
- })
313
- }));
314
- return requireJobId(provider, created.id);
378
+ /**
379
+ * Perplexity's run statuses, always sent (docs.perplexity.ai/api-reference/agent-get).
380
+ * An incomplete or cancelled run can still carry text, so it counts as
381
+ * finished and `research` decides what it amounts to.
382
+ */
383
+ const RESEARCH_STATES = {
384
+ done: [
385
+ "completed",
386
+ "incomplete",
387
+ "cancelled"
388
+ ],
389
+ failed: ["failed"],
390
+ running: ["queued", "in_progress"]
315
391
  };
392
+ /** Starts a background Agent API run and returns its id. */
393
+ const startResearch = async (raw, question, o, call) => await startJob(raw, "/v1/agent", {
394
+ ...call,
395
+ body: compact({
396
+ ...researchSetup(o),
397
+ background: true,
398
+ input: question,
399
+ instructions: o.instructions,
400
+ language_preference: o.languagePreference,
401
+ max_output_tokens: o.maxOutputTokens,
402
+ previous_response_id: o.continueFrom,
403
+ response_format: responseFormat(o.schema)
404
+ })
405
+ }, AgentStart, (reply) => reply.id);
406
+ /**
407
+ * Polls a research run until it reaches a terminal status. A `completed` run
408
+ * returns `completed`. An `incomplete` or `cancelled` one that left text returns
409
+ * `partial` with that status as `stopReason`. A `failed` run, or one with no text,
410
+ * throws `JobFailed`. The run's id is also its `continuationId`.
411
+ */
316
412
  const research = async (raw, question, options) => {
317
413
  const { call, rest: o } = callSettings(options);
318
414
  return await runJob(provider, {
319
415
  check: async (id, request) => {
320
416
  const found = z.parse(AgentRun, await raw.request("GET", `/v1/agent/${segment(id)}`, request));
321
- return TERMINAL.has(found.value.status ?? "") ? found : void 0;
417
+ return jobState("perplexity", id, RESEARCH_STATES, {
418
+ original: found.original,
419
+ value: found.value.status
420
+ }) === "running" ? void 0 : found;
322
421
  },
323
422
  finish: async (run, id) => {
324
423
  const { status } = run.value;
@@ -343,6 +442,10 @@ const research = async (raw, question, options) => {
343
442
  resume: o.resume
344
443
  });
345
444
  };
445
+ /**
446
+ * `/v1/decisions`. Perplexity returns no citations, so `citations` is always empty.
447
+ * Score answers are keyed by the caller's scale keys.
448
+ */
346
449
  const decide = async (raw, context, questions, options) => {
347
450
  const { call, rest: o } = callSettings(options);
348
451
  const response = await raw.request("POST", "/v1/decisions", {
@@ -355,10 +458,17 @@ const decide = async (raw, context, questions, options) => {
355
458
  });
356
459
  const body = z.parse(DecisionsResponse, response);
357
460
  const answers = {};
358
- for (const [name, value] of Object.entries(body.answers)) {
359
- const question = questions[name];
360
- answers[name] = decisionAnswer(value, question?.type === "score" ? Object.keys(question.scale) : void 0);
461
+ const unanswered = [];
462
+ for (const [name, question] of Object.entries(questions)) {
463
+ const found = Object.hasOwn(body.answers, name) ? body.answers[name] : void 0;
464
+ const decided = found && decisionAnswer(found, question);
465
+ if (decided === void 0) unanswered.push(name);
466
+ else answers[name] = decided;
361
467
  }
468
+ if (unanswered.length > 0) throw new FieldworkError("ProviderError", `perplexity returned no complete answer for ${unanswered.join(", ")}`, {
469
+ cause: response,
470
+ provider
471
+ });
362
472
  const { usage } = body;
363
473
  return {
364
474
  answers,
package/dist/reducto.d.ts CHANGED
@@ -1,12 +1,16 @@
1
- import { B as ParsedDocument, C as DocumentInput, a as RawClient, p as CallOptions, t as Adapter } from "./adapter-BgdfLBs-.js";
1
+ import { B as ParsedDocument, C as DocumentInput, a as RawClient, p as CallOptions, t as Adapter } from "./adapter-Bh8EIrNe.js";
2
+ /** Settings for `reducto()`. */
2
3
  export interface ReductoConfig {
3
4
  /** Defaults to the REDUCTO_API_KEY environment variable. */
4
5
  apiKey?: string;
6
+ /** Defaults to https://platform.reducto.ai. */
5
7
  baseUrl?: string;
8
+ /** Defaults to the global `fetch`. It also downloads a large result from the URL Reducto stores it at. A test passes a fake. */
6
9
  fetch?: typeof fetch;
7
10
  /** Repeats of a request that can succeed on repeat; 2 unless set. `0` turns retrying off. */
8
11
  retries?: number;
9
12
  }
13
+ /** Options for `parse`. */
10
14
  export interface ReductoParseOptions extends CallOptions {
11
15
  /** Return layout blocks with positions. */
12
16
  blocks?: boolean;
@@ -20,8 +24,18 @@ export interface ReductoParseOptions extends CallOptions {
20
24
  /** Milliseconds between checks. Defaults to 2000. */
21
25
  interval?: number;
22
26
  }
27
+ /** Options for collecting an earlier parse by its id, without the file. */
28
+ export type ReductoResumeOptions = Omit<ReductoParseOptions, "resume"> & {
29
+ resume: string;
30
+ };
31
+ /** What the Reducto adapter offers. */
23
32
  export interface ReductoOperations {
24
- parse: (document: DocumentInput, options?: ReductoParseOptions) => Promise<ParsedDocument>;
33
+ parse: {
34
+ /** Uploads the file, starts the parse and waits for it. An error after the parse starts carries `jobId`. */
35
+ (document: DocumentInput, options?: ReductoParseOptions): Promise<ParsedDocument>;
36
+ /** Collects an earlier parse by its id, without sending the file again. */
37
+ (options: ReductoResumeOptions): Promise<ParsedDocument>;
38
+ };
25
39
  }
26
40
  /**
27
41
  * An adapter for Reducto: parse. Pass it to `new Fieldwork({ adapter })`.
package/dist/reducto.js CHANGED
@@ -1,8 +1,8 @@
1
1
  import { t as defineAdapter } from "./adapter-DWYJys20.js";
2
- import { a as refuseLarger, n as documentPart } from "./document-Dpj01mGx.js";
3
- import { t as FieldworkError } from "./errors-Yvk42oZH.js";
4
- import { B as requireJobId, C as createRawClient, E as segment, F as parseJson, M as compact, P as meta, S as withOriginal, T as requireKey, a as looseObject, d as optionalId, f as optionalNumber, h as optionalString, k as callSettings, r as arrayOf, s as optionalAnyString, w as readSigned } from "./parse-n8MmaK1x.js";
5
- import { t as runJob } from "./job-BGTwH3F-.js";
2
+ import { a as refuseLarger, n as documentPart } from "./document-Clmi51Sf.js";
3
+ import { t as FieldworkError } from "./errors-DROZyb9T.js";
4
+ import { B as requireJobId, C as createRawClient, E as segment, F as parseJson, M as compact, P as meta, S as withOriginal, T as requireKey, a as looseObject, d as optionalId, f as optionalNumber, h as optionalString, k as callSettings, r as arrayOf, s as optionalAnyString, w as readSigned } from "./parse-COHKvfH9.js";
5
+ import { i as startJob, r as runJob, t as jobState } from "./job-CWHOfhP_.js";
6
6
  import * as z from "zod/mini";
7
7
  // src/adapters/reducto/response.ts
8
8
  /** A box in fractions of the page, from its top-left corner. `page` counts the pages parsed; `original_page` the file's. */
@@ -14,6 +14,7 @@ const FractionBox = looseObject({
14
14
  top: optionalNumber,
15
15
  width: optionalNumber
16
16
  });
17
+ /** A layout block. `extra` holds the word and cell citations, which the `return_citations` setting asks for. */
17
18
  const Block = looseObject({
18
19
  bbox: FractionBox,
19
20
  content: optionalAnyString,
@@ -106,6 +107,7 @@ const documentBlocks = (output) => output.chunks.flatMap((chunk) => chunk.blocks
106
107
  const provider = "reducto";
107
108
  /** The largest file `/upload` takes, in megabytes. */
108
109
  const MAX_UPLOAD_MB = 100;
110
+ /** Uploads the file, then starts the parse, and returns the job id. Refuses a file over the size limit before sending. */
109
111
  const startParse = async (raw, document, o, call) => {
110
112
  refuseLarger(provider, document, MAX_UPLOAD_MB);
111
113
  const form = new FormData();
@@ -115,26 +117,34 @@ const startParse = async (raw, document, o, call) => {
115
117
  ...call,
116
118
  form
117
119
  }));
118
- const started = z.parse(ParseStart, await raw.request("POST", "/parse_async", {
119
- creates: true,
120
+ return await startJob(raw, "/parse_async", {
120
121
  ...call,
121
122
  body: compact({
122
123
  input: requireJobId(provider, uploaded.file_id),
123
124
  settings: o.wordBoxes === true ? { return_citations: true } : void 0
124
125
  })
125
- }));
126
- return requireJobId(provider, started.job_id);
126
+ }, ParseStart, (reply) => reply.job_id);
127
127
  };
128
- const finished = (found) => {
128
+ const JOB_STATES = {
129
+ done: ["Completed"],
130
+ failed: ["Failed"],
131
+ running: ["Pending", "Idle"]
132
+ };
133
+ /** The result once the job has completed, undefined while it runs; throws `JobFailed` when Reducto reports a failure. */
134
+ const finished = (id, found) => {
129
135
  const { error, reason, status } = found.value;
130
- if (status === "Failed") {
136
+ const state = jobState(provider, id, JOB_STATES, {
137
+ original: found.original,
138
+ value: status
139
+ });
140
+ if (state === "failed") {
131
141
  const why = reason ?? error.message;
132
142
  throw new FieldworkError("JobFailed", `reducto job failed${why === void 0 ? "" : `: ${why}`}`, {
133
143
  cause: found.original,
134
144
  provider
135
145
  });
136
146
  }
137
- return status === "Completed" ? found : void 0;
147
+ return state === "done" ? found : void 0;
138
148
  };
139
149
  /** The parse output, fetched from where Reducto put it when it was too large to return. */
140
150
  const outputOf = async (found, options) => {
@@ -160,7 +170,7 @@ const outputOf = async (found, options) => {
160
170
  const parse = async (raw, document, options, fetchImpl) => {
161
171
  const { call, rest: o } = callSettings(options);
162
172
  return await runJob(provider, {
163
- check: async (id, request) => finished(z.parse(JobResponse, await raw.request("GET", `/job/${segment(id)}`, request))),
173
+ check: async (id, request) => finished(id, z.parse(JobResponse, await raw.request("GET", `/job/${segment(id)}`, request))),
164
174
  finish: async (found, id) => {
165
175
  const { output, stored } = await outputOf(found, {
166
176
  fetch: fetchImpl,
@@ -186,7 +196,10 @@ const parse = async (raw, document, options, fetchImpl) => {
186
196
  }
187
197
  });
188
198
  },
189
- start: async () => await startParse(raw, document, o, call)
199
+ start: async () => {
200
+ if (document === void 0) throw new FieldworkError("InvalidRequest", "parse needs a document, or resume with the id of an earlier parse", { provider });
201
+ return await startParse(raw, document, o, call);
202
+ }
190
203
  }, {
191
204
  ...call,
192
205
  interval: o.interval,
@@ -208,8 +221,8 @@ const reducto = (config = {}) => {
208
221
  });
209
222
  return defineAdapter({
210
223
  name: provider,
211
- operations: { async parse(document, options) {
212
- return await parse(raw, document, options, config.fetch);
224
+ operations: { async parse(first, options) {
225
+ return "resume" in first ? await parse(raw, void 0, first, config.fetch) : await parse(raw, first, options, config.fetch);
213
226
  } },
214
227
  raw
215
228
  });
@@ -1,4 +1,4 @@
1
- import { M as JsonSchema } from "./adapter-BgdfLBs-.js";
1
+ import { M as JsonSchema } from "./adapter-Bh8EIrNe.js";
2
2
  /** Vendor-specific parameters a schema library may accept. */
3
3
  type LibraryOptions = JsonSchema;
4
4
  /** The path segment interface of an issue. */
@@ -1,10 +1,13 @@
1
- import { t as FieldworkError } from "./errors-Yvk42oZH.js";
1
+ import { t as FieldworkError } from "./errors-DROZyb9T.js";
2
2
  // src/schema.ts
3
3
  const isStandard = (schema) => "~standard" in schema;
4
4
  /**
5
5
  * The JSON Schema to send to a provider. A plain JSON Schema passes through as
6
6
  * given; a Standard Schema is converted to `target`, without its `$schema` key,
7
7
  * because the provider's docs, not the library, say which dialect it reads.
8
+ *
9
+ * Throws `InvalidRequest`, with the library's error as `cause`, when the
10
+ * library cannot write the schema as `target`.
8
11
  */
9
12
  const jsonSchemaOf = (schema, target = "draft-2020-12") => {
10
13
  if (!isStandard(schema)) return schema;
@@ -27,9 +30,10 @@ const describeIssues = (issues) => {
27
30
  };
28
31
  /**
29
32
  * The provider's structured output as the caller's type. A Standard Schema
30
- * checks it and throws `ProviderError` listing the first issues with their
31
- * paths; the value returned is the schema's own output, so transforms and
32
- * defaults apply. A plain JSON Schema, or no schema, leaves it unchecked.
33
+ * checks it and throws `ProviderError` listing the first three issues with
34
+ * their paths, not `retryable` and carrying the context's `jobId`; the value
35
+ * returned is the schema's own output, so transforms and defaults apply. A
36
+ * plain JSON Schema, or no schema, leaves it unchecked.
33
37
  */
34
38
  const checkOutput = async (schema, value, context) => {
35
39
  if (schema === void 0 || !isStandard(schema)) return value;
package/dist/serpapi.d.ts CHANGED
@@ -1,9 +1,15 @@
1
- import { K as Recency, Y as SearchResponse, a as RawClient, j as ImageSearch, p as CallOptions, s as AccountUsage, t as Adapter } from "./adapter-BgdfLBs-.js";
1
+ import { K as Recency, Y as SearchResponse, a as RawClient, j as ImageSearch, p as CallOptions, s as AccountUsage, t as Adapter } from "./adapter-Bh8EIrNe.js";
2
2
  import "./util-DhYr1OS3.js";
3
+ /** Settings for `serpapi()`. */
3
4
  interface SerpApiConfig {
4
5
  /** Defaults to the SERPAPI_API_KEY environment variable. */
5
6
  apiKey?: string;
7
+ /** Defaults to https://serpapi.com. */
6
8
  baseUrl?: string;
9
+ /**
10
+ * Used in place of the global `fetch`. The API key is added to each request's URL
11
+ * before it is called.
12
+ */
7
13
  fetch?: typeof fetch;
8
14
  /** Repeats of a request that can succeed on repeat; 2 unless set. `0` turns retrying off. */
9
15
  retries?: number;
@@ -16,7 +22,11 @@ interface SerpApiBaseOptions extends CallOptions {
16
22
  */
17
23
  noCache?: boolean;
18
24
  }
19
- /** Google web search: `GET /search?engine=google`, organic results and the answer box. */
25
+ /**
26
+ * Google web search: `GET /search?engine=google`, organic results and the answer
27
+ * box. This is the default engine. `limit` is refused: SerpApi documents no
28
+ * result count for Google.
29
+ */
20
30
  interface SerpApiGoogleOptions extends SerpApiBaseOptions {
21
31
  engine?: "google";
22
32
  /** ISO 3166-1 alpha-2 code such as "GB"; sent as `gl` ("uk" for GB, as SerpApi documents). */
@@ -27,9 +37,9 @@ interface SerpApiGoogleOptions extends SerpApiBaseOptions {
27
37
  location?: string;
28
38
  /** Sent as `tbs` `qdr`. Not allowed with `publishedAfter` or `publishedBefore`. */
29
39
  recency?: Recency;
30
- /** YYYY-MM-DD. Sent as `tbs` `cdr`. */
40
+ /** YYYY-MM-DD. Sent as `tbs` `cdr`; either end may be given alone. */
31
41
  publishedAfter?: string;
32
- /** YYYY-MM-DD. Sent as `tbs` `cdr`. */
42
+ /** YYYY-MM-DD. Sent as `tbs` `cdr`; either end may be given alone. */
33
43
  publishedBefore?: string;
34
44
  safe?: "active" | "off";
35
45
  device?: Device;
@@ -138,9 +148,18 @@ interface SerpApiDuckDuckGoOptions extends SerpApiBaseOptions {
138
148
  publishedBefore?: string;
139
149
  start?: number;
140
150
  }
151
+ /**
152
+ * The options of `search`, chosen by `engine` (Google when it is left out). Each
153
+ * engine takes only the options it documents; any other set option is refused
154
+ * before sending. The per-engine mapping is in `ENGINES`.
155
+ */
141
156
  type SerpApiSearchOptions = SerpApiGoogleOptions | SerpApiNewsOptions | SerpApiShoppingOptions | SerpApiMapsOptions | SerpApiScholarOptions | SerpApiPatentsOptions | SerpApiBingOptions | SerpApiDuckDuckGoOptions;
157
+ /** The engine names `search` accepts. */
142
158
  type SerpApiEngine = NonNullable<SerpApiSearchOptions["engine"]>;
143
- /** Google Images: `engine=google_images`. */
159
+ /**
160
+ * Options for `images`, which always uses `engine=google_images`. `limit` is
161
+ * refused: SerpApi documents no result count for it.
162
+ */
144
163
  interface SerpApiImagesOptions extends SerpApiBaseOptions {
145
164
  country?: string;
146
165
  language?: string;
@@ -166,6 +185,7 @@ interface SerpApiImagesOptions extends SerpApiBaseOptions {
166
185
  /** Sent as `licenses`: f, fc, fm, fmc, cl or ol. */
167
186
  license?: "f" | "fc" | "fm" | "fmc" | "cl" | "ol";
168
187
  }
188
+ /** What SerpApi offers: search, images and usage. */
169
189
  interface SerpApiOperations {
170
190
  search: (query: string, options?: SerpApiSearchOptions) => Promise<SearchResponse>;
171
191
  images: (query: string, options?: SerpApiImagesOptions) => Promise<ImageSearch>;