@howells/fieldwork-sdk 0.3.1 → 0.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.
@@ -0,0 +1,220 @@
1
+ import { t as defineAdapter } from "./adapter-DWYJys20.js";
2
+ import { a as refuseLarger, n as documentPart } from "./document-Dpj01mGx.js";
3
+ import { i as withJob, t as FieldworkError } from "./errors-Yvk42oZH.js";
4
+ import { C as createRawClient, D as segment, E as requireKey, N as meta, O as callSettings, P as parseJson, S as withOriginal, T as readSigned, a as looseObject, d as optionalId, f as optionalNumber, h as optionalString, j as compact, r as arrayOf, s as optionalAnyString, w as poll, z as requireJobId } from "./parse-D4SMt-Ip.js";
5
+ import * as z from "zod/mini";
6
+ // src/adapters/reducto/response.ts
7
+ /** A box in fractions of the page, from its top-left corner. `page` counts the pages parsed; `original_page` the file's. */
8
+ const FractionBox = looseObject({
9
+ height: optionalNumber,
10
+ left: optionalNumber,
11
+ original_page: optionalNumber,
12
+ page: optionalNumber,
13
+ top: optionalNumber,
14
+ width: optionalNumber
15
+ });
16
+ const Block = looseObject({
17
+ bbox: FractionBox,
18
+ content: optionalAnyString,
19
+ extra: looseObject({
20
+ cell_citations: arrayOf(looseObject({
21
+ bbox: FractionBox,
22
+ col_idx: arrayOf(z.number()),
23
+ row_idx: arrayOf(z.number()),
24
+ text: optionalAnyString
25
+ })),
26
+ word_citations: arrayOf(looseObject({
27
+ bbox: FractionBox,
28
+ text: optionalAnyString
29
+ }))
30
+ }),
31
+ type: optionalString
32
+ });
33
+ /** The parse output: in full, or, when large, a URL to fetch it from. */
34
+ const ParseOutput = looseObject({
35
+ chunks: arrayOf(looseObject({
36
+ blocks: arrayOf(Block),
37
+ content: optionalAnyString
38
+ })),
39
+ type: optionalString,
40
+ url: optionalString
41
+ });
42
+ /** `POST /upload`. */
43
+ const UploadResponse = looseObject({ file_id: withOriginal(optionalString) });
44
+ /** `POST /parse_async`. */
45
+ const ParseStart = looseObject({ job_id: withOriginal(optionalId) });
46
+ /** `GET /job/{id}`, as it arrived beside the value read from it. */
47
+ const JobResponse = withOriginal(looseObject({
48
+ error: looseObject({ message: optionalString }),
49
+ reason: optionalString,
50
+ result: looseObject({
51
+ result: ParseOutput,
52
+ usage: looseObject({
53
+ credits: optionalNumber,
54
+ num_pages: optionalNumber
55
+ })
56
+ }),
57
+ status: optionalString
58
+ }));
59
+ const boxOf = (box) => {
60
+ const { height, left, top, width } = box;
61
+ if (left === void 0 || top === void 0 || width === void 0 || height === void 0) return;
62
+ return {
63
+ height,
64
+ left,
65
+ top,
66
+ width
67
+ };
68
+ };
69
+ const cellOf = (cell) => {
70
+ const row = Math.min(...cell.row_idx);
71
+ const column = Math.min(...cell.col_idx);
72
+ if (!Number.isFinite(row) || !Number.isFinite(column)) return [];
73
+ return [compact({
74
+ box: boxOf(cell.bbox),
75
+ column,
76
+ columnSpan: cell.col_idx.length > 1 ? cell.col_idx.length : void 0,
77
+ row,
78
+ rowSpan: cell.row_idx.length > 1 ? cell.row_idx.length : void 0,
79
+ text: cell.text ?? ""
80
+ })];
81
+ };
82
+ const blockOf = (block) => {
83
+ const page = block.bbox.original_page ?? block.bbox.page;
84
+ if (page === void 0) return [];
85
+ const words = block.extra.word_citations.flatMap((word) => {
86
+ const box = boxOf(word.bbox);
87
+ return box === void 0 ? [] : [{
88
+ box,
89
+ text: word.text ?? ""
90
+ }];
91
+ });
92
+ const cells = block.extra.cell_citations.flatMap((cell) => cellOf(cell));
93
+ return [compact({
94
+ box: boxOf(block.bbox),
95
+ cells: cells.length > 0 ? cells : void 0,
96
+ page,
97
+ text: block.content ?? "",
98
+ type: block.type ?? "unknown",
99
+ words: words.length > 0 ? words : void 0
100
+ })];
101
+ };
102
+ /** Every chunk's blocks, in order, each on the file's own page number. */
103
+ const documentBlocks = (output) => output.chunks.flatMap((chunk) => chunk.blocks.flatMap((block) => blockOf(block)));
104
+ // src/adapters/reducto.ts
105
+ const provider = "reducto";
106
+ /** The largest file `/upload` takes, in megabytes. */
107
+ const MAX_UPLOAD_MB = 100;
108
+ const startParse = async (raw, document, o, call) => {
109
+ if (o.resume !== void 0) return o.resume;
110
+ refuseLarger(provider, document, MAX_UPLOAD_MB);
111
+ const form = new FormData();
112
+ form.set("file", documentPart(document), document.name);
113
+ const uploaded = z.parse(UploadResponse, await raw.request("POST", "/upload", {
114
+ creates: true,
115
+ ...call,
116
+ form
117
+ }));
118
+ const started = z.parse(ParseStart, await raw.request("POST", "/parse_async", {
119
+ creates: true,
120
+ ...call,
121
+ body: compact({
122
+ input: requireJobId(provider, uploaded.file_id),
123
+ settings: o.wordBoxes === true ? { return_citations: true } : void 0
124
+ })
125
+ }));
126
+ return requireJobId(provider, started.job_id);
127
+ };
128
+ const finished = (found, id) => {
129
+ const { error, reason, status } = found.value;
130
+ if (status === "Failed") {
131
+ const why = reason ?? error.message;
132
+ throw new FieldworkError("JobFailed", `reducto job failed${why === void 0 ? "" : `: ${why}`}`, {
133
+ cause: found.original,
134
+ jobId: id,
135
+ provider
136
+ });
137
+ }
138
+ return status === "Completed" ? found : void 0;
139
+ };
140
+ /** The parse output, fetched from where Reducto put it when it was too large to return. */
141
+ const outputOf = async (found, id, options) => {
142
+ const output = found.value.result.result;
143
+ if (output.type === "full") return {
144
+ output,
145
+ stored: void 0
146
+ };
147
+ if (output.type !== "url") throw new FieldworkError("ProviderError", `reducto returned a result of type ${output.type ?? "(none)"}; Fieldwork reads "full" and "url"`, {
148
+ cause: found.original,
149
+ jobId: id,
150
+ provider
151
+ });
152
+ if (output.url === void 0) throw new FieldworkError("ProviderError", "reducto stored the result without saying where", {
153
+ cause: found.original,
154
+ jobId: id,
155
+ provider
156
+ });
157
+ try {
158
+ const stored = parseJson(provider, await readSigned(provider, output.url, options));
159
+ return {
160
+ output: z.parse(ParseOutput, stored),
161
+ stored
162
+ };
163
+ } catch (error) {
164
+ throw withJob(error, id);
165
+ }
166
+ };
167
+ const parse = async (raw, document, options, fetchImpl) => {
168
+ const { call, rest: o } = callSettings(options);
169
+ const id = await startParse(raw, document, o, call);
170
+ const found = await poll(provider, id, async (request) => finished(z.parse(JobResponse, await raw.request("GET", `/job/${segment(id)}`, request)), id), {
171
+ ...call,
172
+ interval: o.interval
173
+ });
174
+ const { output, stored } = await outputOf(found, id, {
175
+ fetch: fetchImpl,
176
+ signal: call.signal
177
+ });
178
+ if (output.chunks.length === 0) throw new FieldworkError("ProviderError", `reducto finished job ${id} without any chunks of output`, {
179
+ cause: stored ?? found.original,
180
+ jobId: id,
181
+ provider
182
+ });
183
+ const { usage } = found.value.result;
184
+ return compact({
185
+ blocks: o.blocks === true || o.wordBoxes === true ? documentBlocks(output) : void 0,
186
+ id,
187
+ markdown: output.chunks.map((chunk) => chunk.content ?? "").join("\n\n"),
188
+ meta: meta({
189
+ credits: usage.credits,
190
+ units: { pages: usage.num_pages }
191
+ }),
192
+ pageCount: usage.num_pages,
193
+ raw: stored === void 0 ? found.original : {
194
+ job: found.original,
195
+ stored
196
+ }
197
+ });
198
+ };
199
+ /**
200
+ * An adapter for Reducto: parse. Pass it to `new Fieldwork({ adapter })`.
201
+ *
202
+ * Throws `Unauthorized` when neither `apiKey` nor `REDUCTO_API_KEY` is set.
203
+ */
204
+ const reducto = (config = {}) => {
205
+ const raw = createRawClient({
206
+ baseUrl: config.baseUrl ?? "https://platform.reducto.ai",
207
+ fetch: config.fetch,
208
+ headers: { authorization: `Bearer ${requireKey(provider, config.apiKey, "REDUCTO_API_KEY")}` },
209
+ provider,
210
+ retries: config.retries
211
+ });
212
+ return defineAdapter({
213
+ name: provider,
214
+ operations: { async parse(document, options) {
215
+ return await parse(raw, document, options, config.fetch);
216
+ } },
217
+ raw
218
+ });
219
+ };
220
+ export { reducto };
@@ -0,0 +1,90 @@
1
+ import { M as JsonSchema } from "./adapter-BgdfLBs-.js";
2
+ /** Vendor-specific parameters a schema library may accept. */
3
+ type LibraryOptions = JsonSchema;
4
+ /** The path segment interface of an issue. */
5
+ interface StandardSchemaPathSegment {
6
+ /** The key representing a path segment. */
7
+ readonly key: PropertyKey;
8
+ }
9
+ /** The issue interface of a failed validation. */
10
+ interface StandardSchemaIssue {
11
+ /** The error message of the issue. */
12
+ readonly message: string;
13
+ /** The path of the issue, if any. */
14
+ readonly path?: readonly (PropertyKey | StandardSchemaPathSegment)[];
15
+ }
16
+ /** The result interface if validation succeeds. */
17
+ interface StandardSchemaSuccess<Output> {
18
+ /** The typed output value. */
19
+ readonly value: Output;
20
+ /** The absence of issues indicates success. */
21
+ readonly issues?: undefined;
22
+ }
23
+ /** The result interface if validation fails. */
24
+ interface StandardSchemaFailure {
25
+ /** The issues of failed validation. */
26
+ readonly issues: readonly StandardSchemaIssue[];
27
+ }
28
+ /** The result interface of the validate function. */
29
+ type StandardSchemaResult<Output> = StandardSchemaSuccess<Output> | StandardSchemaFailure;
30
+ /** The options of the validate function. */
31
+ interface StandardSchemaOptions {
32
+ /** Implicit support for additional vendor-specific parameters, if needed. */
33
+ readonly libraryOptions?: LibraryOptions;
34
+ }
35
+ /** The Standard types interface. */
36
+ interface StandardTypes<Input = unknown, Output = Input> {
37
+ /** The input type of the schema. */
38
+ readonly input: Input;
39
+ /** The output type of the schema. */
40
+ readonly output: Output;
41
+ }
42
+ /** The Standard properties shared by both interfaces. */
43
+ interface StandardTypedProps<Input = unknown, Output = Input> {
44
+ /** The version number of the standard. */
45
+ readonly version: 1;
46
+ /** The vendor name of the schema library. */
47
+ readonly vendor: string;
48
+ /** Inferred types associated with the schema. */
49
+ readonly types?: StandardTypes<Input, Output> | undefined;
50
+ }
51
+ /** The Standard Schema properties interface. */
52
+ interface StandardSchemaProps<Input = unknown, Output = Input> extends StandardTypedProps<Input, Output> {
53
+ /** Validates a value. `OutputSchema` fixes `Input` to `unknown`, as the spec has it. */
54
+ readonly validate: (value: Input, options?: StandardSchemaOptions) => StandardSchemaResult<Output> | Promise<StandardSchemaResult<Output>>;
55
+ }
56
+ /**
57
+ * The target version of the generated JSON Schema. Libraries should support
58
+ * `"draft-2020-12"` and `"draft-07"`.
59
+ */
60
+ type StandardJSONSchemaTarget = "draft-2020-12" | "draft-07" | "openapi-3.0" | (string & {});
61
+ /** The options for the input/output methods. */
62
+ interface StandardJSONSchemaOptions {
63
+ /** The target version of the generated JSON Schema. */
64
+ readonly target: StandardJSONSchemaTarget;
65
+ /** Implicit support for additional vendor-specific parameters, if needed. */
66
+ readonly libraryOptions?: LibraryOptions;
67
+ }
68
+ /** The Standard JSON Schema converter interface. */
69
+ interface StandardJSONSchemaConverter {
70
+ /** Converts the input type to JSON Schema. May throw if conversion is not supported. */
71
+ readonly input: (options: StandardJSONSchemaOptions) => JsonSchema;
72
+ /** Converts the output type to JSON Schema. May throw if conversion is not supported. */
73
+ readonly output: (options: StandardJSONSchemaOptions) => JsonSchema;
74
+ }
75
+ /** The Standard JSON Schema properties interface. */
76
+ interface StandardJSONSchemaProps<Input = unknown, Output = Input> extends StandardTypedProps<Input, Output> {
77
+ /** Methods for generating the input/output JSON Schema. */
78
+ readonly jsonSchema: StandardJSONSchemaConverter;
79
+ }
80
+ /** A schema that both validates and describes itself: Zod, Valibot and ArkType. */
81
+ interface StandardSchemaWithJSON<Input = unknown, Output = Input> {
82
+ readonly "~standard": StandardSchemaProps<Input, Output> & StandardJSONSchemaProps<Input, Output>;
83
+ }
84
+ /**
85
+ * The shape of a structured output: a plain JSON Schema, or a Standard Schema
86
+ * with JSON Schema support. A Standard Schema gives the result its type and
87
+ * checks the provider's output against it; a plain JSON Schema does neither.
88
+ */
89
+ type OutputSchema<T> = JsonSchema | StandardSchemaWithJSON<unknown, T>;
90
+ export { StandardSchemaWithJSON as n, OutputSchema as t };
@@ -0,0 +1,45 @@
1
+ import { t as FieldworkError } from "./errors-Yvk42oZH.js";
2
+ // src/schema.ts
3
+ const isStandard = (schema) => "~standard" in schema;
4
+ /**
5
+ * The JSON Schema to send to a provider. A plain JSON Schema passes through as
6
+ * given; a Standard Schema is converted to `target`, without its `$schema` key,
7
+ * because the provider's docs, not the library, say which dialect it reads.
8
+ */
9
+ const jsonSchemaOf = (schema, target = "draft-2020-12") => {
10
+ if (!isStandard(schema)) return schema;
11
+ try {
12
+ const converted = schema["~standard"].jsonSchema.input({ target });
13
+ return Object.fromEntries(Object.entries(converted).filter(([key]) => key !== "$schema"));
14
+ } catch (error) {
15
+ throw new FieldworkError("InvalidRequest", `the ${schema["~standard"].vendor} schema cannot be written as ${target} JSON Schema: ${error instanceof Error ? error.message : String(error)}`, { cause: error });
16
+ }
17
+ };
18
+ const MAX_ISSUES = 3;
19
+ const pathOf = (issue) => {
20
+ const segments = (issue.path ?? []).map((segment) => String(segment instanceof Object ? segment.key : segment));
21
+ return segments.length > 0 ? segments.join(".") : "(root)";
22
+ };
23
+ const describeIssues = (issues) => {
24
+ const shown = issues.slice(0, MAX_ISSUES).map((issue) => `${pathOf(issue)}: ${issue.message}`);
25
+ const more = issues.length - shown.length;
26
+ return `${shown.join("; ")}${more > 0 ? `; and ${more} more` : ""}`;
27
+ };
28
+ /**
29
+ * 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
+ */
34
+ const checkOutput = async (schema, value, context) => {
35
+ if (schema === void 0 || !isStandard(schema)) return value;
36
+ const result = await schema["~standard"].validate(value);
37
+ if (result.issues !== void 0) throw new FieldworkError("ProviderError", `${context.provider} returned output that does not match the schema: ${describeIssues(result.issues)}`, {
38
+ cause: result.issues,
39
+ jobId: context.jobId,
40
+ provider: context.provider,
41
+ retryable: false
42
+ });
43
+ return result.value;
44
+ };
45
+ export { jsonSchemaOf as n, checkOutput as t };
package/dist/serpapi.d.ts CHANGED
@@ -1,9 +1,12 @@
1
- import { W as Recency, a as RawClient, f as CallOptions, k as ImageSearch, q as SearchResponse, s as AccountUsage, t as Adapter } from "./adapter-DGehHCMo.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-BgdfLBs-.js";
2
+ import "./util-DhYr1OS3.js";
2
3
  interface SerpApiConfig {
3
4
  /** Defaults to the SERPAPI_API_KEY environment variable. */
4
5
  apiKey?: string;
5
6
  baseUrl?: string;
6
7
  fetch?: typeof fetch;
8
+ /** Repeats of a request that can succeed on repeat; 2 unless set. `0` turns retrying off. */
9
+ retries?: number;
7
10
  }
8
11
  type Device = "desktop" | "tablet" | "mobile";
9
12
  interface SerpApiBaseOptions extends CallOptions {
@@ -164,9 +167,14 @@ interface SerpApiImagesOptions extends SerpApiBaseOptions {
164
167
  license?: "f" | "fc" | "fm" | "fmc" | "cl" | "ol";
165
168
  }
166
169
  interface SerpApiOperations {
167
- search(query: string, options?: SerpApiSearchOptions): Promise<SearchResponse>;
168
- images(query: string, options?: SerpApiImagesOptions): Promise<ImageSearch>;
169
- usage(options?: CallOptions): Promise<AccountUsage>;
170
+ search: (query: string, options?: SerpApiSearchOptions) => Promise<SearchResponse>;
171
+ images: (query: string, options?: SerpApiImagesOptions) => Promise<ImageSearch>;
172
+ usage: (options?: CallOptions) => Promise<AccountUsage>;
170
173
  }
174
+ /**
175
+ * An adapter for SerpApi: search, images and usage. Pass it to `new Fieldwork({ adapter })`.
176
+ *
177
+ * Throws `Unauthorized` when neither `apiKey` nor `SERPAPI_API_KEY` is set.
178
+ */
171
179
  export declare const serpapi: (config?: SerpApiConfig) => Adapter<"serpapi", SerpApiOperations, RawClient>;
172
180
  export type { SerpApiBingOptions, SerpApiConfig, SerpApiDuckDuckGoOptions, SerpApiEngine, SerpApiGoogleOptions, SerpApiImagesOptions, SerpApiMapsOptions, SerpApiNewsOptions, SerpApiOperations, SerpApiPatentsOptions, SerpApiScholarOptions, SerpApiSearchOptions, SerpApiShoppingOptions };