@howells/fieldwork-sdk 0.2.0 → 0.3.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,214 +0,0 @@
1
- import { n as codeForStatus, r as withJob, t as FieldworkError } from "./errors-pzPMh82H.js";
2
- // src/http.ts
3
- function createRawClient(config) {
4
- const doFetch = config.fetch ?? globalThis.fetch;
5
- return {
6
- provider: config.provider,
7
- baseUrl: config.baseUrl,
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
- let response;
23
- try {
24
- response = await doFetch(url, {
25
- method,
26
- headers,
27
- body,
28
- signal
29
- });
30
- } catch (error) {
31
- throw transportError(config.provider, error, options.signal);
32
- }
33
- const text = await response.text();
34
- const parsed = parseBody(text);
35
- if (!response.ok) throw new FieldworkError(codeForStatus(response.status), `${config.provider} ${method} ${path} returned ${response.status}: ${describe(parsed, text)}`, {
36
- provider: config.provider,
37
- status: response.status,
38
- retryAfter: retryAfterSeconds(response.headers.get("retry-after")),
39
- cause: parsed
40
- });
41
- return parsed;
42
- }
43
- };
44
- }
45
- function combineSignals(signal, timeout) {
46
- const signals = [signal, timeout === void 0 ? void 0 : AbortSignal.timeout(timeout)].filter((value) => value !== void 0);
47
- return signals.length <= 1 ? signals[0] : AbortSignal.any(signals);
48
- }
49
- function transportError(provider, error, signal) {
50
- if (signal?.aborted) return new FieldworkError("Aborted", `${provider} request was cancelled`, {
51
- provider,
52
- cause: error
53
- });
54
- if (error instanceof DOMException && error.name === "TimeoutError") return new FieldworkError("Timeout", `${provider} request timed out`, {
55
- provider,
56
- cause: error
57
- });
58
- return new FieldworkError("ProviderError", `${provider} request failed: ${String(error)}`, {
59
- provider,
60
- retryable: true,
61
- cause: error
62
- });
63
- }
64
- function parseBody(text) {
65
- if (text === "") return;
66
- try {
67
- return JSON.parse(text);
68
- } catch {
69
- return text;
70
- }
71
- }
72
- function describe(parsed, text) {
73
- if (parsed && typeof parsed === "object") {
74
- const record = parsed;
75
- for (const key of [
76
- "error",
77
- "message",
78
- "detail"
79
- ]) {
80
- const value = record[key];
81
- if (typeof value === "string") return value;
82
- if (value && typeof value === "object") return JSON.stringify(value).slice(0, 300);
83
- }
84
- }
85
- return text.slice(0, 300);
86
- }
87
- /** Retry-After is either a number of seconds or an HTTP date. */
88
- function retryAfterSeconds(header, now = Date.now()) {
89
- if (!header) return;
90
- const seconds = Number(header);
91
- if (Number.isFinite(seconds)) return seconds;
92
- const date = Date.parse(header);
93
- return Number.isNaN(date) ? void 0 : Math.max(0, Math.ceil((date - now) / 1e3));
94
- }
95
- /**
96
- * Calls `check` until it returns a value, waiting between calls. `check`
97
- * returns `undefined` while the job is still running. Every error raised while
98
- * waiting carries `jobId`, so the caller can resume the job instead of paying
99
- * for a second one.
100
- */
101
- async function poll(provider, jobId, check, options = {}) {
102
- const interval = options.interval ?? 2e3;
103
- const deadline = Date.now() + (options.timeout ?? 6e5);
104
- for (;;) {
105
- if (options.signal?.aborted) throw new FieldworkError("Aborted", `stopped waiting for ${provider} job ${jobId}; it may still be running`, {
106
- provider,
107
- jobId
108
- });
109
- let value;
110
- try {
111
- value = await check();
112
- } catch (error) {
113
- throw withJob(error, jobId);
114
- }
115
- if (value !== void 0) return value;
116
- if (Date.now() + interval > deadline) throw new FieldworkError("Timeout", `${provider} job ${jobId} did not finish in time; it may still be running`, {
117
- provider,
118
- jobId
119
- });
120
- await sleep(interval, options.signal);
121
- }
122
- }
123
- async function sleep(ms, signal) {
124
- await new Promise((resolve) => {
125
- const timer = setTimeout(resolve, ms);
126
- signal?.addEventListener("abort", () => {
127
- clearTimeout(timer);
128
- resolve();
129
- }, { once: true });
130
- });
131
- }
132
- /** Reads an API key from the adapter options or the environment. */
133
- function requireKey(provider, given, envName) {
134
- const key = given ?? process.env[envName];
135
- if (!key) throw new FieldworkError("Unauthorized", `${provider} needs an API key: pass apiKey or set ${envName}`, { provider });
136
- return key;
137
- }
138
- // src/util.ts
139
- function record(value) {
140
- return value && typeof value === "object" && !Array.isArray(value) ? value : {};
141
- }
142
- function list(value) {
143
- return Array.isArray(value) ? value : [];
144
- }
145
- function text(value) {
146
- return typeof value === "string" && value !== "" ? value : void 0;
147
- }
148
- function num(value) {
149
- return typeof value === "number" && Number.isFinite(value) ? value : void 0;
150
- }
151
- function strings(value) {
152
- const items = list(value).filter((item) => typeof item === "string");
153
- return items.length > 0 ? items : void 0;
154
- }
155
- /** Drops keys whose value is undefined, so request bodies carry only what was set. */
156
- function compact(value) {
157
- return Object.fromEntries(Object.entries(value).filter(([, item]) => item !== void 0));
158
- }
159
- /** Splits Fieldwork's own call settings from the provider options. */
160
- function callSettings(options) {
161
- const { signal, timeout, ...rest } = options ?? {};
162
- return {
163
- call: {
164
- signal,
165
- timeout
166
- },
167
- rest
168
- };
169
- }
170
- function parseJson(provider, value) {
171
- if (typeof value !== "string") return value;
172
- try {
173
- return JSON.parse(value);
174
- } catch (error) {
175
- throw new FieldworkError("ProviderError", `${provider} returned output that is not valid JSON`, {
176
- provider,
177
- cause: error
178
- });
179
- }
180
- }
181
- function uniqueCitations(all) {
182
- const seen = /* @__PURE__ */ new Map();
183
- for (const item of all) if (!seen.has(item.url)) seen.set(item.url, item);
184
- return [...seen.values()];
185
- }
186
- function citation(value) {
187
- const item = record(value);
188
- const url = text(item.url);
189
- if (!url) return;
190
- const excerpts = typeof item.excerpts === "string" ? [item.excerpts] : strings(item.excerpts);
191
- return compact({
192
- url,
193
- title: text(item.title),
194
- excerpts
195
- });
196
- }
197
- function citations(value) {
198
- return list(value).map((item) => citation(item)).filter((item) => item !== void 0);
199
- }
200
- /** The id of a job the provider just created; a missing id means the job cannot be followed. */
201
- function requireId(provider, value) {
202
- const id = typeof value === "number" ? String(value) : text(value);
203
- if (id === void 0) throw new FieldworkError("ProviderError", `${provider} did not return a job id`, {
204
- provider,
205
- cause: value
206
- });
207
- return id;
208
- }
209
- /** Any scalar as text, for values a provider may send as a string or a number. */
210
- function scalar(value) {
211
- if (typeof value === "string") return value;
212
- return typeof value === "number" || typeof value === "boolean" ? String(value) : void 0;
213
- }
214
- export { list as a, record as c, strings as d, text as f, requireKey as g, poll as h, compact as i, requireId as l, createRawClient as m, citation as n, num as o, uniqueCitations as p, citations as r, parseJson as s, callSettings as t, scalar as u };