@howells/fieldwork-sdk 0.3.1 → 0.4.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,287 +0,0 @@
1
- import { n as codeForStatus, r as withJob, t as FieldworkError } from "./errors-BiIBG9zN.js";
2
- // src/http.ts
3
- const createRawClient = (config) => {
4
- const doFetch = config.fetch ?? globalThis.fetch;
5
- return {
6
- baseUrl: config.baseUrl,
7
- provider: config.provider,
8
- async request(method, path, options = {}) {
9
- const url = new URL(config.baseUrl.replace(/\/$/u, "") + path);
10
- for (const [key, value] of Object.entries(options.query ?? {})) if (value !== void 0) url.searchParams.set(key, String(value));
11
- const headers = new Headers({
12
- accept: "application/json",
13
- ...config.headers
14
- });
15
- let body;
16
- if (options.form) body = options.form;
17
- else if (options.body !== void 0) {
18
- headers.set("content-type", "application/json");
19
- body = JSON.stringify(options.body);
20
- }
21
- const signal = combineSignals(options.signal, options.timeout);
22
- const send = async (request) => {
23
- try {
24
- return await doFetch(request.url, {
25
- body: request.body,
26
- headers,
27
- method: request.method,
28
- redirect: "manual",
29
- signal
30
- });
31
- } catch (error) {
32
- throw transportError(config.provider, error, options.signal);
33
- }
34
- };
35
- const response = await followRedirects(config.provider, send, {
36
- body,
37
- method,
38
- url
39
- });
40
- const text = await response.text();
41
- const parsed = parseBody(text);
42
- if (!response.ok) throw new FieldworkError(codeForStatus(response.status), `${config.provider} ${method} ${path} returned ${response.status}: ${describe(parsed, text)}`, {
43
- cause: parsed,
44
- provider: config.provider,
45
- retryAfter: retryAfterSeconds(response.headers.get("retry-after")),
46
- status: response.status
47
- });
48
- return parsed;
49
- }
50
- };
51
- };
52
- const REDIRECTS = /* @__PURE__ */ new Set([
53
- 301,
54
- 302,
55
- 303,
56
- 307,
57
- 308
58
- ]);
59
- const MAX_REDIRECTS = 5;
60
- /**
61
- * Follows a provider's redirects only within its own origin, so the key in
62
- * the request's headers or query never reaches another host. A redirect to
63
- * another origin, scheme or port fails before anything is sent there.
64
- */
65
- const followRedirects = async (provider, send, first) => {
66
- let hop = first;
67
- for (let count = 0; count <= MAX_REDIRECTS; count += 1) {
68
- const response = await send(hop);
69
- if (response.type === "opaqueredirect") throw new FieldworkError("ProviderError", `${provider} redirected the request, and this runtime hides where to; Fieldwork does not follow it`, { provider });
70
- const location = response.headers.get("location");
71
- if (!REDIRECTS.has(response.status) || location === null) return response;
72
- const target = new URL(location, hop.url);
73
- if (target.origin !== first.url.origin) throw new FieldworkError("ProviderError", `${provider} redirected the request to ${target.origin}; Fieldwork follows redirects only within ${first.url.origin}, so the key was not sent`, {
74
- provider,
75
- status: response.status
76
- });
77
- hop = response.status === 303 || (response.status === 301 || response.status === 302) && hop.method === "POST" ? {
78
- body: void 0,
79
- method: "GET",
80
- url: target
81
- } : {
82
- ...hop,
83
- url: target
84
- };
85
- }
86
- throw new FieldworkError("ProviderError", `${provider} redirected the request more than ${MAX_REDIRECTS} times`, { provider });
87
- };
88
- const combineSignals = (signal, timeout) => {
89
- const signals = [signal, timeout === void 0 ? void 0 : AbortSignal.timeout(timeout)].filter((value) => value !== void 0);
90
- return signals.length <= 1 ? signals[0] : AbortSignal.any(signals);
91
- };
92
- const transportError = (provider, error, signal) => {
93
- if (signal?.aborted) return new FieldworkError("Aborted", `${provider} request was cancelled`, {
94
- cause: error,
95
- provider
96
- });
97
- if (error instanceof DOMException && error.name === "TimeoutError") return new FieldworkError("Timeout", `${provider} request timed out`, {
98
- cause: error,
99
- provider
100
- });
101
- return new FieldworkError("ProviderError", `${provider} request failed: ${String(error)}`, {
102
- cause: error,
103
- provider,
104
- retryable: true
105
- });
106
- };
107
- const parseBody = (text) => {
108
- if (text === "") return;
109
- try {
110
- return JSON.parse(text);
111
- } catch {
112
- return text;
113
- }
114
- };
115
- const describe = (parsed, text) => {
116
- if (parsed && typeof parsed === "object") {
117
- const record = parsed;
118
- for (const key of [
119
- "error",
120
- "message",
121
- "detail"
122
- ]) {
123
- const value = record[key];
124
- if (typeof value === "string") return value;
125
- if (value && typeof value === "object") return JSON.stringify(value).slice(0, 300);
126
- }
127
- }
128
- return text.slice(0, 300);
129
- };
130
- const retryAfterSeconds = (header, now = Date.now()) => {
131
- if (!header) return;
132
- const seconds = Number(header);
133
- if (Number.isFinite(seconds)) return seconds;
134
- const date = Date.parse(header);
135
- return Number.isNaN(date) ? void 0 : Math.max(0, Math.ceil((date - now) / 1e3));
136
- };
137
- const poll = async (provider, jobId, check, options = {}) => {
138
- const interval = options.interval ?? 2e3;
139
- const deadline = Date.now() + (options.timeout ?? 6e5);
140
- for (;;) {
141
- if (options.signal?.aborted) throw new FieldworkError("Aborted", `stopped waiting for ${provider} job ${jobId}; it may still be running`, {
142
- jobId,
143
- provider
144
- });
145
- let value;
146
- try {
147
- value = await check();
148
- } catch (error) {
149
- throw withJob(error, jobId);
150
- }
151
- if (value !== void 0) return value;
152
- if (Date.now() + interval > deadline) throw new FieldworkError("Timeout", `${provider} job ${jobId} did not finish in time; it may still be running`, {
153
- jobId,
154
- provider
155
- });
156
- await sleep(interval, options.signal);
157
- }
158
- };
159
- const sleep = async (ms, signal) => {
160
- await new Promise((resolve) => {
161
- const timer = setTimeout(resolve, ms);
162
- signal?.addEventListener("abort", () => {
163
- clearTimeout(timer);
164
- resolve();
165
- }, { once: true });
166
- });
167
- };
168
- const requireKey = (provider, given, envName) => {
169
- const key = given ?? process.env[envName];
170
- if (!key) throw new FieldworkError("Unauthorized", `${provider} needs an API key: pass apiKey or set ${envName}`, { provider });
171
- return key;
172
- };
173
- // src/util.ts
174
- const record = (value) => value && typeof value === "object" && !Array.isArray(value) ? value : {};
175
- const list = (value) => Array.isArray(value) ? value : [];
176
- const text = (value) => typeof value === "string" && value !== "" ? value : void 0;
177
- const num = (value) => typeof value === "number" && Number.isFinite(value) ? value : void 0;
178
- const strings = (value) => {
179
- const items = list(value).filter((item) => typeof item === "string");
180
- return items.length > 0 ? items : void 0;
181
- };
182
- const compact = (value) => Object.fromEntries(Object.entries(value).filter(([, item]) => item !== void 0));
183
- const callSettings = (options) => {
184
- const { signal, timeout, ...rest } = options ?? {};
185
- return {
186
- call: {
187
- signal,
188
- timeout
189
- },
190
- rest
191
- };
192
- };
193
- const parseJson = (provider, value) => {
194
- if (typeof value !== "string") return value;
195
- try {
196
- return JSON.parse(value);
197
- } catch (error) {
198
- throw new FieldworkError("ProviderError", `${provider} returned output that is not valid JSON`, {
199
- cause: error,
200
- provider
201
- });
202
- }
203
- };
204
- const uniqueCitations = (all) => {
205
- const seen = /* @__PURE__ */ new Map();
206
- for (const item of all) if (!seen.has(item.url)) seen.set(item.url, item);
207
- return [...seen.values()];
208
- };
209
- const citation = (value) => {
210
- const item = record(value);
211
- const url = text(item.url);
212
- if (!url) return;
213
- const excerpts = typeof item.excerpts === "string" ? [item.excerpts] : strings(item.excerpts);
214
- return compact({
215
- excerpts,
216
- title: text(item.title),
217
- url
218
- });
219
- };
220
- const citations = (value) => list(value).map((item) => citation(item)).filter((item) => item !== void 0);
221
- const requireId = (provider, value) => {
222
- const id = typeof value === "number" ? String(value) : text(value);
223
- if (id === void 0) throw new FieldworkError("ProviderError", `${provider} did not return a job id`, {
224
- cause: value,
225
- provider
226
- });
227
- return id;
228
- };
229
- const scalar = (value) => {
230
- if (typeof value === "string") return value;
231
- return typeof value === "number" || typeof value === "boolean" ? String(value) : void 0;
232
- };
233
- const meta = (parts) => {
234
- const units = Object.fromEntries(Object.entries(parts.units ?? {}).filter((entry) => typeof entry[1] === "number" && Number.isFinite(entry[1])));
235
- const usage = compact({
236
- costUsd: num(parts.costUsd),
237
- credits: num(parts.credits),
238
- units: Object.keys(units).length > 0 ? units : void 0
239
- });
240
- const warnings = typeof parts.warnings === "string" ? [parts.warnings] : list(parts.warnings).map((item) => typeof item === "string" ? item : text(record(item).message) ?? text(record(item).detail)).filter((item) => item !== void 0);
241
- const result = compact({
242
- requestId: scalar(parts.requestId),
243
- usage: Object.keys(usage).length > 0 ? usage : void 0,
244
- warnings: warnings.length > 0 ? warnings : void 0
245
- });
246
- return Object.keys(result).length > 0 ? result : void 0;
247
- };
248
- const productImages = (value) => {
249
- const items = list(value).map((item) => {
250
- if (typeof item === "string") return item === "" ? void 0 : { url: item };
251
- const image = record(item);
252
- const url = text(image.url) ?? text(image.src);
253
- return url ? compact({
254
- alt: text(image.alt),
255
- url
256
- }) : void 0;
257
- }).filter((item) => item !== void 0);
258
- return items.length > 0 ? items : void 0;
259
- };
260
- const refuseTogether = (provider, options, ...names) => {
261
- const set = names.filter((name) => options[name] !== void 0);
262
- if (set.length > 1) throw new FieldworkError("InvalidRequest", `${provider} does not accept ${set.join(" and ")} together; pass one`, { provider });
263
- };
264
- const hours = (seconds) => seconds === void 0 ? void 0 : seconds < 0 ? -1 : Math.ceil(seconds / 3600);
265
- /** Statuses that mean the page is not there, so a read of it has no page to return. */
266
- const GONE = /* @__PURE__ */ new Set([404, 410]);
267
- /**
268
- * A read whose page answered 404 or 410 fails as NotFound, as it does on
269
- * providers that return no page at all, instead of returning the error page
270
- * as if it were the content.
271
- */
272
- const presentPage = (provider, page) => {
273
- if (page.statusCode !== void 0 && GONE.has(page.statusCode)) throw new FieldworkError("NotFound", `${provider} could not read ${page.url}: the page returned ${page.statusCode}`, {
274
- provider,
275
- status: page.statusCode
276
- });
277
- return page;
278
- };
279
- /** Splits a batch's pages into those present and those that answered 404 or 410. */
280
- const presentPages = (pages) => ({
281
- gone: pages.filter((page) => page.statusCode !== void 0 && GONE.has(page.statusCode)).map((page) => ({
282
- error: `the page returned ${page.statusCode}`,
283
- url: page.url
284
- })),
285
- pages: pages.filter((page) => page.statusCode === void 0 || !GONE.has(page.statusCode))
286
- });
287
- export { requireKey as S, strings as _, hours as a, createRawClient as b, num as c, presentPages as d, productImages as f, scalar as g, requireId as h, compact as i, parseJson as l, refuseTogether as m, citation as n, list as o, record as p, citations as r, meta as s, callSettings as t, presentPage as u, text as v, poll as x, uniqueCitations as y };