@xberg-io/sdk 0.0.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.
- package/README.md +163 -9
- package/dist/index.d.ts +30306 -0
- package/dist/index.d.ts.map +1 -0
- package/dist/index.js +1303 -0
- package/dist/index.js.map +1 -0
- package/package.json +41 -4
package/dist/index.js
ADDED
|
@@ -0,0 +1,1303 @@
|
|
|
1
|
+
import createOpenApiClient from "openapi-fetch";
|
|
2
|
+
|
|
3
|
+
//#region src/errors.ts
|
|
4
|
+
var XbergError = class extends Error {
|
|
5
|
+
status;
|
|
6
|
+
body;
|
|
7
|
+
constructor(message, options) {
|
|
8
|
+
const errorInit = options.cause === void 0 ? {} : { cause: options.cause };
|
|
9
|
+
super(message, errorInit);
|
|
10
|
+
this.name = "XbergError";
|
|
11
|
+
this.status = options.status;
|
|
12
|
+
this.body = options.body;
|
|
13
|
+
}
|
|
14
|
+
};
|
|
15
|
+
var AuthError = class extends XbergError {
|
|
16
|
+
constructor(message, options) {
|
|
17
|
+
super(message, options);
|
|
18
|
+
this.name = "AuthError";
|
|
19
|
+
}
|
|
20
|
+
};
|
|
21
|
+
var RateLimitError = class extends XbergError {
|
|
22
|
+
retryAfter;
|
|
23
|
+
constructor(message, options) {
|
|
24
|
+
super(message, options);
|
|
25
|
+
this.name = "RateLimitError";
|
|
26
|
+
if (options.retryAfter !== void 0) this.retryAfter = options.retryAfter;
|
|
27
|
+
}
|
|
28
|
+
};
|
|
29
|
+
var ValidationError = class extends XbergError {
|
|
30
|
+
constructor(message, options) {
|
|
31
|
+
super(message, options);
|
|
32
|
+
this.name = "ValidationError";
|
|
33
|
+
}
|
|
34
|
+
};
|
|
35
|
+
var NotFoundError = class extends XbergError {
|
|
36
|
+
constructor(message, options) {
|
|
37
|
+
super(message, options);
|
|
38
|
+
this.name = "NotFoundError";
|
|
39
|
+
}
|
|
40
|
+
};
|
|
41
|
+
var ServerError = class extends XbergError {
|
|
42
|
+
constructor(message, options) {
|
|
43
|
+
super(message, options);
|
|
44
|
+
this.name = "ServerError";
|
|
45
|
+
}
|
|
46
|
+
};
|
|
47
|
+
var TimeoutError = class extends XbergError {
|
|
48
|
+
constructor(message, options) {
|
|
49
|
+
super(message, options);
|
|
50
|
+
this.name = "TimeoutError";
|
|
51
|
+
}
|
|
52
|
+
};
|
|
53
|
+
/**
|
|
54
|
+
* Map an HTTP response status to the matching error subclass and throw it.
|
|
55
|
+
*
|
|
56
|
+
* Always throws — call as `throw await raiseForStatus(response)` if you want
|
|
57
|
+
* the type system to see the unreachable code, otherwise just `await`. Both
|
|
58
|
+
* 401 and 403 map to {@link AuthError} — the API uses 403 for a
|
|
59
|
+
* valid-but-forbidden principal.
|
|
60
|
+
*/
|
|
61
|
+
async function raiseForStatus(response) {
|
|
62
|
+
const body = await readBody(response);
|
|
63
|
+
const message = extractErrorMessage(body) ?? `Request failed with status ${response.status}`;
|
|
64
|
+
const options = {
|
|
65
|
+
status: response.status,
|
|
66
|
+
body
|
|
67
|
+
};
|
|
68
|
+
if (response.status === 401 || response.status === 403) throw new AuthError(message, options);
|
|
69
|
+
if (response.status === 404) throw new NotFoundError(message, options);
|
|
70
|
+
if (response.status === 429) {
|
|
71
|
+
const retryAfter = parseRetryAfter(response.headers.get("retry-after"));
|
|
72
|
+
throw new RateLimitError(message, retryAfter === void 0 ? options : {
|
|
73
|
+
...options,
|
|
74
|
+
retryAfter
|
|
75
|
+
});
|
|
76
|
+
}
|
|
77
|
+
if (response.status >= 400 && response.status < 500) throw new ValidationError(message, options);
|
|
78
|
+
if (response.status >= 500) throw new ServerError(message, options);
|
|
79
|
+
throw new XbergError(message, options);
|
|
80
|
+
}
|
|
81
|
+
async function readBody(response) {
|
|
82
|
+
if ((response.headers.get("content-type") ?? "").includes("application/json")) try {
|
|
83
|
+
return await response.json();
|
|
84
|
+
} catch {
|
|
85
|
+
return;
|
|
86
|
+
}
|
|
87
|
+
try {
|
|
88
|
+
const text = await response.text();
|
|
89
|
+
return text === "" ? void 0 : text;
|
|
90
|
+
} catch {
|
|
91
|
+
return;
|
|
92
|
+
}
|
|
93
|
+
}
|
|
94
|
+
function extractErrorMessage(body) {
|
|
95
|
+
if (typeof body === "string" && body.length > 0) return body;
|
|
96
|
+
if (body !== null && typeof body === "object") {
|
|
97
|
+
const record = body;
|
|
98
|
+
const error = record["error"];
|
|
99
|
+
if (typeof error === "string" && error.length > 0) return error;
|
|
100
|
+
const message = record["message"];
|
|
101
|
+
if (typeof message === "string" && message.length > 0) return message;
|
|
102
|
+
}
|
|
103
|
+
}
|
|
104
|
+
function parseRetryAfter(value) {
|
|
105
|
+
if (value === null) return;
|
|
106
|
+
const seconds = Number(value);
|
|
107
|
+
if (Number.isFinite(seconds) && seconds >= 0) return seconds;
|
|
108
|
+
const parsed = Date.parse(value);
|
|
109
|
+
if (Number.isNaN(parsed)) return;
|
|
110
|
+
return Math.max(0, Math.ceil((parsed - Date.now()) / 1e3));
|
|
111
|
+
}
|
|
112
|
+
|
|
113
|
+
//#endregion
|
|
114
|
+
//#region src/_internal.ts
|
|
115
|
+
/**
|
|
116
|
+
* Internal helpers for {@link XbergClient}: base-URL resolution, query-string
|
|
117
|
+
* and backoff arithmetic, the file-to-`Blob` conversion the multipart request
|
|
118
|
+
* paths need, and the event-stream frame decoder `streamCrawlEvents` reads its
|
|
119
|
+
* response through. Not part of the public API — of the names here only
|
|
120
|
+
* {@link FileLike} and {@link BackoffStrategy} are re-exported, via `client.ts`,
|
|
121
|
+
* because they appear in public client signatures.
|
|
122
|
+
*/
|
|
123
|
+
const DEFAULT_ENTERPRISE_BASE_URL = "https://api.xberg.io";
|
|
124
|
+
const DEFAULT_RETRY_BACKOFF_CAP_MS = 3e4;
|
|
125
|
+
const DEFAULT_BACKOFF_FACTOR = 2;
|
|
126
|
+
/**
|
|
127
|
+
* Caps an event-stream frame. The frames this endpoint sends are a few hundred
|
|
128
|
+
* bytes; the cap exists so a server that never closes a frame cannot grow this
|
|
129
|
+
* decoder without bound.
|
|
130
|
+
*
|
|
131
|
+
* It is applied twice, because one application does not cover the other: to the
|
|
132
|
+
* pending line, so one endless line cannot fill memory, and to the running
|
|
133
|
+
* total of a frame's `data:` fields, so an endless succession of shorter lines
|
|
134
|
+
* never followed by the blank line that would close the frame cannot either.
|
|
135
|
+
*/
|
|
136
|
+
const MAX_EVENT_STREAM_FRAME_BYTES = 1 << 20;
|
|
137
|
+
/**
|
|
138
|
+
* Resolve the effective base URL, enforcing that Pro requires an explicit one.
|
|
139
|
+
*/
|
|
140
|
+
function resolveBaseUrl(baseUrl, target) {
|
|
141
|
+
if (baseUrl !== void 0) return baseUrl.replace(/\/+$/, "");
|
|
142
|
+
if (target === "pro") throw new XbergError("Xberg Pro has no default base URL (its spec ships no servers block); pass baseUrl pointing at your Pro instance.", {
|
|
143
|
+
status: 0,
|
|
144
|
+
body: null
|
|
145
|
+
});
|
|
146
|
+
return DEFAULT_ENTERPRISE_BASE_URL;
|
|
147
|
+
}
|
|
148
|
+
/**
|
|
149
|
+
* Resolve the base URL of the Enterprise control plane, defaulting to the data plane's.
|
|
150
|
+
*
|
|
151
|
+
* Enterprise runs the control plane (projects, API keys, integrations, RAG
|
|
152
|
+
* config, members, invitations, managed webhooks, usage, analytics, billing) as
|
|
153
|
+
* a second binary on its own origin; Pro serves it from the same one. The
|
|
154
|
+
* default therefore has to be `baseUrl`, exactly as the console's
|
|
155
|
+
* `NEXT_PUBLIC_BACKEND_API_URL` is same-origin unless set — anything else would
|
|
156
|
+
* break every Pro control-plane call the moment this option existed.
|
|
157
|
+
*/
|
|
158
|
+
function resolveControlPlaneBaseUrl(controlPlaneBaseUrl, baseUrl) {
|
|
159
|
+
if (controlPlaneBaseUrl !== void 0) return controlPlaneBaseUrl.replace(/\/+$/, "");
|
|
160
|
+
return baseUrl;
|
|
161
|
+
}
|
|
162
|
+
function defaultSleep(ms) {
|
|
163
|
+
return new Promise((resolve) => {
|
|
164
|
+
setTimeout(resolve, ms);
|
|
165
|
+
});
|
|
166
|
+
}
|
|
167
|
+
function buildQueryString(params) {
|
|
168
|
+
if (params === void 0) return "";
|
|
169
|
+
const search = new URLSearchParams();
|
|
170
|
+
for (const [key, value] of Object.entries(params)) if (value !== void 0) search.append(key, String(value));
|
|
171
|
+
const query = search.toString();
|
|
172
|
+
return query.length > 0 ? `?${query}` : "";
|
|
173
|
+
}
|
|
174
|
+
function nextBackoffInterval(current, strategy) {
|
|
175
|
+
if (strategy === "constant") return current;
|
|
176
|
+
return Math.min(current * DEFAULT_BACKOFF_FACTOR, DEFAULT_RETRY_BACKOFF_CAP_MS);
|
|
177
|
+
}
|
|
178
|
+
function parseRetryAfterHeader(value) {
|
|
179
|
+
if (value === null) return;
|
|
180
|
+
const seconds = Number(value);
|
|
181
|
+
if (Number.isFinite(seconds) && seconds >= 0) return seconds;
|
|
182
|
+
const parsed = Date.parse(value);
|
|
183
|
+
if (Number.isNaN(parsed)) return;
|
|
184
|
+
return Math.max(0, Math.ceil((parsed - Date.now()) / 1e3));
|
|
185
|
+
}
|
|
186
|
+
/** Convert a {@link FileLike} input into a `Blob` plus best-guess filename. */
|
|
187
|
+
function toBlob(file) {
|
|
188
|
+
if (typeof File !== "undefined" && file instanceof File) return {
|
|
189
|
+
blob: file,
|
|
190
|
+
filename: file.name
|
|
191
|
+
};
|
|
192
|
+
if (file instanceof Blob) return {
|
|
193
|
+
blob: file,
|
|
194
|
+
filename: "upload.bin"
|
|
195
|
+
};
|
|
196
|
+
if (file instanceof Uint8Array) return {
|
|
197
|
+
blob: new Blob([new Uint8Array(file)], { type: "application/octet-stream" }),
|
|
198
|
+
filename: "upload.bin"
|
|
199
|
+
};
|
|
200
|
+
const wrapper = file;
|
|
201
|
+
const name = wrapper.name ?? "upload.bin";
|
|
202
|
+
const mimeType = wrapper.mimeType ?? guessMimeType(name);
|
|
203
|
+
if (wrapper.data instanceof Blob) return {
|
|
204
|
+
blob: wrapper.data,
|
|
205
|
+
filename: name
|
|
206
|
+
};
|
|
207
|
+
return {
|
|
208
|
+
blob: new Blob([new Uint8Array(wrapper.data)], { type: mimeType }),
|
|
209
|
+
filename: name
|
|
210
|
+
};
|
|
211
|
+
}
|
|
212
|
+
function guessMimeType(filename) {
|
|
213
|
+
const lower = filename.toLowerCase();
|
|
214
|
+
if (lower.endsWith(".csv")) return "text/csv";
|
|
215
|
+
if (lower.endsWith(".md")) return "text/markdown";
|
|
216
|
+
if (lower.endsWith(".pdf")) return "application/pdf";
|
|
217
|
+
if (lower.endsWith(".txt")) return "text/plain";
|
|
218
|
+
if (lower.endsWith(".docx")) return "application/vnd.openxmlformats-officedocument.wordprocessingml.document";
|
|
219
|
+
return "application/octet-stream";
|
|
220
|
+
}
|
|
221
|
+
/** Guess a display name for a file (used to populate `Job.filename`). */
|
|
222
|
+
function describeFile(file) {
|
|
223
|
+
if (typeof File !== "undefined" && file instanceof File) return file.name;
|
|
224
|
+
if (file instanceof Blob || file instanceof Uint8Array) return "upload.bin";
|
|
225
|
+
return file.name ?? "upload.bin";
|
|
226
|
+
}
|
|
227
|
+
/**
|
|
228
|
+
* Incremental decoder for a `text/event-stream` body, fed the decoded text of
|
|
229
|
+
* each network chunk.
|
|
230
|
+
*
|
|
231
|
+
* Implements the parts of the WHATWG event-stream parser this endpoint can
|
|
232
|
+
* exercise. A frame is terminated by a *blank line*, not by a newline: its
|
|
233
|
+
* payload is every `data:` field it carried, joined with `\n`. Lines opening
|
|
234
|
+
* with `:` are comments — the endpoint's 15s heartbeat is one — and
|
|
235
|
+
* `event:`/`id:`/`retry:` fields are accepted and ignored. A single space
|
|
236
|
+
* after a field's colon is framing, not value, so it is stripped.
|
|
237
|
+
*
|
|
238
|
+
* All of which is why this exists instead of `JSON.parse` per line: against a
|
|
239
|
+
* server that happens to emit one compact frame per line the naive version
|
|
240
|
+
* passes every test, then silently drops every multi-line payload and throws
|
|
241
|
+
* on the first heartbeat against a real one. Chunk boundaries fall wherever
|
|
242
|
+
* the network puts them, so lines are also reassembled here rather than
|
|
243
|
+
* assumed to arrive whole.
|
|
244
|
+
*/
|
|
245
|
+
var EventStreamDecoder = class {
|
|
246
|
+
buffer = "";
|
|
247
|
+
data = [];
|
|
248
|
+
/** Running length of the frame being assembled, reset with `data` on dispatch. */
|
|
249
|
+
size = 0;
|
|
250
|
+
/** Consume one chunk of decoded text, returning the payload of every frame it completed. */
|
|
251
|
+
push(chunk) {
|
|
252
|
+
this.buffer += chunk;
|
|
253
|
+
const payloads = [];
|
|
254
|
+
for (;;) {
|
|
255
|
+
const boundary = this.nextLineBoundary();
|
|
256
|
+
if (boundary === void 0) {
|
|
257
|
+
if (this.buffer.length > MAX_EVENT_STREAM_FRAME_BYTES) throw new XbergError(`Crawl event stream sent a line longer than ${MAX_EVENT_STREAM_FRAME_BYTES} bytes`, {
|
|
258
|
+
status: 0,
|
|
259
|
+
body: null
|
|
260
|
+
});
|
|
261
|
+
return payloads;
|
|
262
|
+
}
|
|
263
|
+
const line = this.buffer.slice(0, boundary.index);
|
|
264
|
+
this.buffer = this.buffer.slice(boundary.index + boundary.width);
|
|
265
|
+
const payload = this.feed(line);
|
|
266
|
+
if (payload !== void 0) payloads.push(payload);
|
|
267
|
+
}
|
|
268
|
+
}
|
|
269
|
+
/**
|
|
270
|
+
* Locate the next `\n`, `\r\n` or `\r` in the buffer. A trailing `\r` is
|
|
271
|
+
* reported as "no boundary yet": it may be the first half of a `\r\n` the
|
|
272
|
+
* network split across two chunks, and treating it as a terminator there
|
|
273
|
+
* would dispatch a frame one line early.
|
|
274
|
+
*/
|
|
275
|
+
nextLineBoundary() {
|
|
276
|
+
for (let index = 0; index < this.buffer.length; index += 1) {
|
|
277
|
+
const character = this.buffer[index];
|
|
278
|
+
if (character === "\n") return {
|
|
279
|
+
index,
|
|
280
|
+
width: 1
|
|
281
|
+
};
|
|
282
|
+
if (character === "\r") {
|
|
283
|
+
if (index === this.buffer.length - 1) return;
|
|
284
|
+
return {
|
|
285
|
+
index,
|
|
286
|
+
width: this.buffer[index + 1] === "\n" ? 2 : 1
|
|
287
|
+
};
|
|
288
|
+
}
|
|
289
|
+
}
|
|
290
|
+
}
|
|
291
|
+
/** Consume one terminator-stripped line, returning a payload if it completed a frame. */
|
|
292
|
+
feed(line) {
|
|
293
|
+
if (line === "") return this.dispatch();
|
|
294
|
+
if (line.startsWith(":")) return;
|
|
295
|
+
const colon = line.indexOf(":");
|
|
296
|
+
const field = colon === -1 ? line : line.slice(0, colon);
|
|
297
|
+
let value = colon === -1 ? "" : line.slice(colon + 1);
|
|
298
|
+
if (value.startsWith(" ")) value = value.slice(1);
|
|
299
|
+
if (field === "data") {
|
|
300
|
+
this.size += value.length + 1;
|
|
301
|
+
if (this.size > MAX_EVENT_STREAM_FRAME_BYTES) throw new XbergError(`Crawl event frame exceeded ${MAX_EVENT_STREAM_FRAME_BYTES} bytes before the stream closed it`, {
|
|
302
|
+
status: 0,
|
|
303
|
+
body: null
|
|
304
|
+
});
|
|
305
|
+
this.data.push(value);
|
|
306
|
+
}
|
|
307
|
+
}
|
|
308
|
+
/** Emit the buffered `data` payload, or nothing when the blank line closed no frame. */
|
|
309
|
+
dispatch() {
|
|
310
|
+
if (this.data.length === 0) return;
|
|
311
|
+
const payload = this.data.join("\n");
|
|
312
|
+
this.data = [];
|
|
313
|
+
this.size = 0;
|
|
314
|
+
return payload;
|
|
315
|
+
}
|
|
316
|
+
};
|
|
317
|
+
|
|
318
|
+
//#endregion
|
|
319
|
+
//#region src/types.ts
|
|
320
|
+
/**
|
|
321
|
+
* Terminal job statuses — once observed, polling stops and the job result is
|
|
322
|
+
* returned (or thrown, for `failed`/`cancelled`).
|
|
323
|
+
*/
|
|
324
|
+
const TERMINAL_JOB_STATUSES = [
|
|
325
|
+
"completed",
|
|
326
|
+
"partial_success",
|
|
327
|
+
"failed",
|
|
328
|
+
"cancelled"
|
|
329
|
+
];
|
|
330
|
+
/**
|
|
331
|
+
* Job statuses that indicate a successful extraction. Used to distinguish a
|
|
332
|
+
* "completed but check warnings" result from a hard failure.
|
|
333
|
+
*/
|
|
334
|
+
const SUCCESS_JOB_STATUSES = ["completed", "partial_success"];
|
|
335
|
+
|
|
336
|
+
//#endregion
|
|
337
|
+
//#region src/version.ts
|
|
338
|
+
/**
|
|
339
|
+
* Package version, synced from the repo-root `VERSION` file by
|
|
340
|
+
* `scripts/sync-versions.py`. Used to build the `User-Agent` header. ~keep
|
|
341
|
+
*/
|
|
342
|
+
const VERSION = "0.4.0";
|
|
343
|
+
|
|
344
|
+
//#endregion
|
|
345
|
+
//#region src/client.ts
|
|
346
|
+
/**
|
|
347
|
+
* High-level dual-target client for the Xberg Enterprise and Xberg Pro HTTP APIs.
|
|
348
|
+
*
|
|
349
|
+
* One {@link XbergClient} speaks to either product. The shared surface —
|
|
350
|
+
* extraction, jobs (including job results), audit, curated presets, and the RAG
|
|
351
|
+
* API — is written once and carries no tier gate. Tier-specific methods are
|
|
352
|
+
* capability-gated: they probe the connected instance (`GET /healthz`'s `tier`,
|
|
353
|
+
* or an explicit `target`) and throw a clear error instead of a raw 404 when
|
|
354
|
+
* invoked against the wrong tier.
|
|
355
|
+
*
|
|
356
|
+
* Both products authenticate identically: `Authorization: Bearer {apiKey}`.
|
|
357
|
+
* Enterprise defaults `baseUrl` to `https://api.xberg.io`; Pro has no default
|
|
358
|
+
* (its spec ships no servers block) and requires an explicit one.
|
|
359
|
+
*
|
|
360
|
+
* Enterprise splits into two binaries — the data plane `baseUrl` addresses and a
|
|
361
|
+
* control plane (projects, API keys, integrations) on its own origin — while Pro
|
|
362
|
+
* serves both from one. `controlPlaneBaseUrl` records the origin of the second
|
|
363
|
+
* and defaults to `baseUrl`; no method routes there yet, so today it is
|
|
364
|
+
* configuration held for the control-plane operations that have not landed.
|
|
365
|
+
*/
|
|
366
|
+
const USER_AGENT = `xberg-io-sdk-typescript/${VERSION}`;
|
|
367
|
+
const DEFAULT_TIMEOUT_MS = 3e4;
|
|
368
|
+
const DEFAULT_POLL_INTERVAL_MS = 1e3;
|
|
369
|
+
const DEFAULT_WAIT_TIMEOUT_MS = 5 * 6e4;
|
|
370
|
+
const DEFAULT_RETRY_STATUSES = [
|
|
371
|
+
429,
|
|
372
|
+
502,
|
|
373
|
+
503,
|
|
374
|
+
504
|
|
375
|
+
];
|
|
376
|
+
const DEFAULT_RETRY_BACKOFF_BASE_MS = 200;
|
|
377
|
+
/**
|
|
378
|
+
* Saved presets are the one shared resource whose *path* differs per tier:
|
|
379
|
+
* Enterprise serves `/v1/saved_presets` (underscore), Pro `/v1/saved-presets`
|
|
380
|
+
* (hyphen). The request and response schemas are identical.
|
|
381
|
+
*/
|
|
382
|
+
const SAVED_PRESETS_PATH_ENTERPRISE = "/v1/saved_presets";
|
|
383
|
+
const SAVED_PRESETS_PATH_PRO = "/v1/saved-presets";
|
|
384
|
+
const AUTO_TUNE_PATH = "/v1/auto-tune";
|
|
385
|
+
const TUNING_PROFILES_PATH = "/v1/tuning-profiles";
|
|
386
|
+
const ENRICH_PATH = "/v1/enrich";
|
|
387
|
+
const EXTRACTIONS_PATH = "/v1/extractions";
|
|
388
|
+
const DOCUMENTS_PATH = "/v1/documents";
|
|
389
|
+
const JOBS_PATH = "/v1/jobs";
|
|
390
|
+
const CRAWL_JOBS_PATH = "/v1/crawl-jobs";
|
|
391
|
+
/** Media type of the crawl-event stream, sent as `Accept` and served as `Content-Type`. */
|
|
392
|
+
const EVENT_STREAM_MEDIA_TYPE = "text/event-stream";
|
|
393
|
+
/** The `kind` values `CrawlEventV1` declares. A frame carrying anything else is rejected. */
|
|
394
|
+
const CRAWL_EVENT_KINDS = new Set([
|
|
395
|
+
"page",
|
|
396
|
+
"discovered",
|
|
397
|
+
"complete",
|
|
398
|
+
"error"
|
|
399
|
+
]);
|
|
400
|
+
/**
|
|
401
|
+
* High-level dual-target client. Construct with `new XbergClient({ apiKey })`.
|
|
402
|
+
*/
|
|
403
|
+
var XbergClient = class {
|
|
404
|
+
baseUrl;
|
|
405
|
+
/**
|
|
406
|
+
* Origin the control-plane surface will be addressed at. Same as `baseUrl`
|
|
407
|
+
* unless overridden. No request is routed there yet — see
|
|
408
|
+
* {@link XbergClientOptions.controlPlaneBaseUrl}.
|
|
409
|
+
*/
|
|
410
|
+
controlPlaneBaseUrl;
|
|
411
|
+
headers;
|
|
412
|
+
fetchImpl;
|
|
413
|
+
timeoutMs;
|
|
414
|
+
retries;
|
|
415
|
+
retryOn;
|
|
416
|
+
retryBackoff;
|
|
417
|
+
sleep;
|
|
418
|
+
target;
|
|
419
|
+
probedTier;
|
|
420
|
+
/** In-flight `/healthz` probe, memoised so concurrent callers share one request (single-flight). */
|
|
421
|
+
tierProbe;
|
|
422
|
+
/** Underlying `openapi-fetch` client — exposed for advanced use. */
|
|
423
|
+
raw;
|
|
424
|
+
constructor(options = {}) {
|
|
425
|
+
if (options.target !== void 0) this.target = options.target;
|
|
426
|
+
this.baseUrl = resolveBaseUrl(options.baseUrl, options.target);
|
|
427
|
+
this.controlPlaneBaseUrl = resolveControlPlaneBaseUrl(options.controlPlaneBaseUrl, this.baseUrl);
|
|
428
|
+
this.fetchImpl = options.fetch ?? fetch;
|
|
429
|
+
this.timeoutMs = options.timeoutMs ?? DEFAULT_TIMEOUT_MS;
|
|
430
|
+
this.retries = options.retries ?? 0;
|
|
431
|
+
this.retryOn = options.retryOn ?? DEFAULT_RETRY_STATUSES;
|
|
432
|
+
this.retryBackoff = options.retryBackoff ?? "exponential";
|
|
433
|
+
this.sleep = options.sleep ?? defaultSleep;
|
|
434
|
+
this.headers = {
|
|
435
|
+
"User-Agent": USER_AGENT,
|
|
436
|
+
...options.headers
|
|
437
|
+
};
|
|
438
|
+
if (options.apiKey !== void 0) this.headers["Authorization"] = `Bearer ${options.apiKey}`;
|
|
439
|
+
this.raw = createOpenApiClient({
|
|
440
|
+
baseUrl: this.baseUrl,
|
|
441
|
+
headers: this.headers,
|
|
442
|
+
fetch: this.fetchImpl
|
|
443
|
+
});
|
|
444
|
+
}
|
|
445
|
+
/**
|
|
446
|
+
* Submit a single document for extraction. Returns the initial {@link Job}
|
|
447
|
+
* record (still pending — call `waitForJob` to await completion).
|
|
448
|
+
*/
|
|
449
|
+
async extract(params) {
|
|
450
|
+
const jobs = await this.extractBatch({
|
|
451
|
+
files: [params.file],
|
|
452
|
+
...params.options !== void 0 ? { options: params.options } : {},
|
|
453
|
+
...params.webhook !== void 0 ? { webhook: params.webhook } : {},
|
|
454
|
+
...params.config !== void 0 ? { configs: [params.config] } : {}
|
|
455
|
+
});
|
|
456
|
+
const first = jobs[0];
|
|
457
|
+
if (first === void 0) throw new XbergError("Server did not return any job IDs", {
|
|
458
|
+
status: 500,
|
|
459
|
+
body: { jobs }
|
|
460
|
+
});
|
|
461
|
+
return first;
|
|
462
|
+
}
|
|
463
|
+
/**
|
|
464
|
+
* Submit multiple documents in a single multipart request. Returns one
|
|
465
|
+
* {@link Job} per file, in the same order.
|
|
466
|
+
*/
|
|
467
|
+
async extractBatch(params) {
|
|
468
|
+
if (params.files.length === 0) throw new XbergError("extractBatch called with no files", {
|
|
469
|
+
status: 400,
|
|
470
|
+
body: null
|
|
471
|
+
});
|
|
472
|
+
const form = new FormData();
|
|
473
|
+
const filenames = [];
|
|
474
|
+
for (const file of params.files) {
|
|
475
|
+
const { blob, filename } = toBlob(file);
|
|
476
|
+
form.append("file", blob, filename);
|
|
477
|
+
filenames.push(filename);
|
|
478
|
+
}
|
|
479
|
+
if (params.options !== void 0) form.append("options", JSON.stringify(params.options));
|
|
480
|
+
if (params.webhook !== void 0) form.append("webhook", JSON.stringify(params.webhook));
|
|
481
|
+
appendPerFileConfigs(form, filenames, params.configs);
|
|
482
|
+
const body = await this.requestJson("POST", "/v1/extract", { body: form });
|
|
483
|
+
const jobIds = body.job_ids ?? [];
|
|
484
|
+
const now = (/* @__PURE__ */ new Date()).toISOString();
|
|
485
|
+
return params.files.map((file, index) => {
|
|
486
|
+
const id = jobIds[index];
|
|
487
|
+
if (id === void 0) throw new XbergError(`Server returned ${jobIds.length} job IDs for ${params.files.length} files`, {
|
|
488
|
+
status: 500,
|
|
489
|
+
body
|
|
490
|
+
});
|
|
491
|
+
return {
|
|
492
|
+
id,
|
|
493
|
+
filename: describeFile(file),
|
|
494
|
+
status: "pending",
|
|
495
|
+
created_at: now
|
|
496
|
+
};
|
|
497
|
+
});
|
|
498
|
+
}
|
|
499
|
+
/** Fetch the current state of a job. */
|
|
500
|
+
async getJob(jobId) {
|
|
501
|
+
return await this.requestJson("GET", `${JOBS_PATH}/${encodeURIComponent(jobId)}`);
|
|
502
|
+
}
|
|
503
|
+
/**
|
|
504
|
+
* Fetch a job's stored result document (`GET /v1/jobs/{id}/result`).
|
|
505
|
+
*
|
|
506
|
+
* Declared by both tiers with an identical `JobResult` envelope; the
|
|
507
|
+
* extracted documents live in `results`. Distinct from {@link getJob}, which
|
|
508
|
+
* returns the job's metadata record.
|
|
509
|
+
*/
|
|
510
|
+
async getJobResult(jobId) {
|
|
511
|
+
return await this.requestJson("GET", `${JOBS_PATH}/${encodeURIComponent(jobId)}/result`);
|
|
512
|
+
}
|
|
513
|
+
/** List jobs (paginated) via `GET /v1/jobs`. */
|
|
514
|
+
async listJobs(params = {}) {
|
|
515
|
+
return await this.requestJson("GET", JOBS_PATH, { params: {
|
|
516
|
+
limit: params.limit,
|
|
517
|
+
offset: params.offset
|
|
518
|
+
} });
|
|
519
|
+
}
|
|
520
|
+
/**
|
|
521
|
+
* Cancel a job (`DELETE /v1/jobs/{id}`). Idempotent: both a successful
|
|
522
|
+
* cancellation and a job that already reached a terminal status answer
|
|
523
|
+
* `204`.
|
|
524
|
+
*/
|
|
525
|
+
async cancelJob(jobId) {
|
|
526
|
+
await this.requestJson("DELETE", `${JOBS_PATH}/${encodeURIComponent(jobId)}`);
|
|
527
|
+
}
|
|
528
|
+
/**
|
|
529
|
+
* Poll {@link getJob} until the job reaches a terminal status. Throws
|
|
530
|
+
* {@link TimeoutError} if the wait exceeds `timeoutMs`. Throws
|
|
531
|
+
* {@link XbergError} if the terminal status is `failed` or `cancelled`.
|
|
532
|
+
*/
|
|
533
|
+
async waitForJob(jobId, options = {}) {
|
|
534
|
+
const timeoutMs = options.timeoutMs ?? DEFAULT_WAIT_TIMEOUT_MS;
|
|
535
|
+
const initialInterval = options.pollIntervalMs ?? DEFAULT_POLL_INTERVAL_MS;
|
|
536
|
+
const backoff = options.backoff ?? "exponential";
|
|
537
|
+
const start = Date.now();
|
|
538
|
+
let interval = initialInterval;
|
|
539
|
+
for (;;) {
|
|
540
|
+
const job = await this.getJob(jobId);
|
|
541
|
+
if (TERMINAL_JOB_STATUSES.includes(job.status)) {
|
|
542
|
+
if (SUCCESS_JOB_STATUSES.includes(job.status)) return job;
|
|
543
|
+
throw new XbergError(`Job ${jobId} ended with status ${job.status}`, {
|
|
544
|
+
status: 200,
|
|
545
|
+
body: job
|
|
546
|
+
});
|
|
547
|
+
}
|
|
548
|
+
const remaining = timeoutMs - (Date.now() - start);
|
|
549
|
+
if (remaining <= 0) throw new TimeoutError(`Timed out waiting for job ${jobId} after ${timeoutMs}ms`, {
|
|
550
|
+
status: 408,
|
|
551
|
+
body: job
|
|
552
|
+
});
|
|
553
|
+
const delay = Math.min(interval, remaining);
|
|
554
|
+
await this.sleep(delay);
|
|
555
|
+
if (backoff === "exponential") interval = Math.min(interval * DEFAULT_BACKOFF_FACTOR, DEFAULT_RETRY_BACKOFF_CAP_MS);
|
|
556
|
+
}
|
|
557
|
+
}
|
|
558
|
+
/** Wait for many jobs in parallel. */
|
|
559
|
+
async waitForJobs(jobIds, options = {}) {
|
|
560
|
+
return await Promise.all(jobIds.map((id) => this.waitForJob(id, options)));
|
|
561
|
+
}
|
|
562
|
+
/** Convenience: extract one file and await its result. */
|
|
563
|
+
async extractAndWait(params) {
|
|
564
|
+
const extractParams = {
|
|
565
|
+
file: params.file,
|
|
566
|
+
...params.options !== void 0 ? { options: params.options } : {},
|
|
567
|
+
...params.webhook !== void 0 ? { webhook: params.webhook } : {},
|
|
568
|
+
...params.config !== void 0 ? { config: params.config } : {}
|
|
569
|
+
};
|
|
570
|
+
const job = await this.extract(extractParams);
|
|
571
|
+
const waitOptions = {
|
|
572
|
+
...params.timeoutMs !== void 0 ? { timeoutMs: params.timeoutMs } : {},
|
|
573
|
+
...params.pollIntervalMs !== void 0 ? { pollIntervalMs: params.pollIntervalMs } : {},
|
|
574
|
+
...params.backoff !== void 0 ? { backoff: params.backoff } : {}
|
|
575
|
+
};
|
|
576
|
+
return this.waitForJob(job.id, waitOptions);
|
|
577
|
+
}
|
|
578
|
+
/** Fetch audit-log entries via `GET /v1/audit`. */
|
|
579
|
+
async audit(params = {}) {
|
|
580
|
+
return await this.requestJson("GET", "/v1/audit", { params: {
|
|
581
|
+
action: params.action,
|
|
582
|
+
limit: params.limit,
|
|
583
|
+
offset: params.offset
|
|
584
|
+
} });
|
|
585
|
+
}
|
|
586
|
+
/** List the read-only curated presets (`GET /v1/presets`). */
|
|
587
|
+
async presets() {
|
|
588
|
+
return await this.requestJson("GET", "/v1/presets");
|
|
589
|
+
}
|
|
590
|
+
/** Fetch one curated preset in full (`GET /v1/presets/{id}`). */
|
|
591
|
+
async getPreset(presetId) {
|
|
592
|
+
return await this.requestJson("GET", `/v1/presets/${encodeURIComponent(presetId)}`);
|
|
593
|
+
}
|
|
594
|
+
/**
|
|
595
|
+
* Download a preset's bundled sample file
|
|
596
|
+
* (`GET /v1/presets/{id}/sample/{name}`). The response is raw bytes, not
|
|
597
|
+
* JSON.
|
|
598
|
+
*/
|
|
599
|
+
async getPresetSample(presetId, name) {
|
|
600
|
+
const path = `/v1/presets/${encodeURIComponent(presetId)}/sample/${encodeURIComponent(name)}`;
|
|
601
|
+
return await this.requestBytes("GET", path);
|
|
602
|
+
}
|
|
603
|
+
/** List RAG collections (`GET /v1/rag/collections`). */
|
|
604
|
+
async listRagCollections() {
|
|
605
|
+
return await this.requestJson("GET", "/v1/rag/collections");
|
|
606
|
+
}
|
|
607
|
+
/** Create a RAG collection (`POST /v1/rag/collections`). */
|
|
608
|
+
async createRagCollection(body) {
|
|
609
|
+
return await this.requestJson("POST", "/v1/rag/collections", { json: body });
|
|
610
|
+
}
|
|
611
|
+
/** Fetch a RAG collection (`GET /v1/rag/collections/{name}`). */
|
|
612
|
+
async getRagCollection(name) {
|
|
613
|
+
return await this.requestJson("GET", `/v1/rag/collections/${encodeURIComponent(name)}`);
|
|
614
|
+
}
|
|
615
|
+
/** Delete a RAG collection (`DELETE /v1/rag/collections/{name}`). The spec documents a 204 with no content. */
|
|
616
|
+
async deleteRagCollection(name) {
|
|
617
|
+
await this.requestJson("DELETE", `/v1/rag/collections/${encodeURIComponent(name)}`);
|
|
618
|
+
}
|
|
619
|
+
/** Add documents to a RAG collection (`POST /v1/rag/collections/{name}/documents`). */
|
|
620
|
+
async addRagDocuments(name, body) {
|
|
621
|
+
return await this.requestJson("POST", `/v1/rag/collections/${encodeURIComponent(name)}/documents`, { json: body });
|
|
622
|
+
}
|
|
623
|
+
/**
|
|
624
|
+
* Delete documents from a RAG collection, by ID list or metadata filter
|
|
625
|
+
* (`DELETE /v1/rag/collections/{name}/documents`). Unlike
|
|
626
|
+
* {@link deleteRagCollection}, this answers `200` with a body reporting how
|
|
627
|
+
* many documents were removed.
|
|
628
|
+
*/
|
|
629
|
+
async deleteRagDocuments(name, body) {
|
|
630
|
+
return await this.requestJson("DELETE", `/v1/rag/collections/${encodeURIComponent(name)}/documents`, { json: body });
|
|
631
|
+
}
|
|
632
|
+
/** Reindex a RAG document (`POST /v1/rag/collections/{name}/documents/{id}/reindex`). */
|
|
633
|
+
async reindexRagDocument(name, documentId, body) {
|
|
634
|
+
const path = `/v1/rag/collections/${encodeURIComponent(name)}/documents/${encodeURIComponent(documentId)}/reindex`;
|
|
635
|
+
return await this.requestJson("POST", path, body !== void 0 ? { json: body } : {});
|
|
636
|
+
}
|
|
637
|
+
/** Retrieve chunks from a RAG collection (`POST /v1/rag/collections/{name}/retrieve`). */
|
|
638
|
+
async ragRetrieve(name, body) {
|
|
639
|
+
return await this.requestJson("POST", `/v1/rag/collections/${encodeURIComponent(name)}/retrieve`, { json: body });
|
|
640
|
+
}
|
|
641
|
+
/** Kick off an embedding migration (`POST /v1/rag/collections/{name}/migrate-embeddings`). */
|
|
642
|
+
async migrateRagEmbeddings(name, body) {
|
|
643
|
+
return await this.requestJson("POST", `/v1/rag/collections/${encodeURIComponent(name)}/migrate-embeddings`, { json: body });
|
|
644
|
+
}
|
|
645
|
+
/** Poll an embedding-migration job (`GET .../migrate-embeddings/{jobId}`). */
|
|
646
|
+
async getRagMigrationJob(name, jobId) {
|
|
647
|
+
const path = `/v1/rag/collections/${encodeURIComponent(name)}/migrate-embeddings/${encodeURIComponent(jobId)}`;
|
|
648
|
+
return await this.requestJson("GET", path);
|
|
649
|
+
}
|
|
650
|
+
/** Fetch a RAG job's status (`GET /v1/rag/jobs/{jobId}`). */
|
|
651
|
+
async getRagJob(jobId) {
|
|
652
|
+
return await this.requestJson("GET", `/v1/rag/jobs/${encodeURIComponent(jobId)}`);
|
|
653
|
+
}
|
|
654
|
+
/** List the project's saved presets (`GET /v1/saved_presets`, `/v1/saved-presets` on Pro). */
|
|
655
|
+
async listSavedPresets(params = {}) {
|
|
656
|
+
const path = await this.savedPresetsPath();
|
|
657
|
+
return await this.requestJson("GET", path, { params: {
|
|
658
|
+
limit: params.limit,
|
|
659
|
+
offset: params.offset
|
|
660
|
+
} });
|
|
661
|
+
}
|
|
662
|
+
/** Create a saved preset (`POST /v1/saved_presets`, `/v1/saved-presets` on Pro). */
|
|
663
|
+
async createSavedPreset(body) {
|
|
664
|
+
const path = await this.savedPresetsPath();
|
|
665
|
+
return await this.requestJson("POST", path, { json: body });
|
|
666
|
+
}
|
|
667
|
+
/** Fetch one saved preset (`GET /v1/saved_presets/{presetId}`, `/v1/saved-presets/{id}` on Pro). */
|
|
668
|
+
async getSavedPreset(presetId) {
|
|
669
|
+
const path = await this.savedPresetsPath(presetId);
|
|
670
|
+
return await this.requestJson("GET", path);
|
|
671
|
+
}
|
|
672
|
+
/** Update a saved preset (`PATCH /v1/saved_presets/{presetId}`, `/v1/saved-presets/{id}` on Pro). */
|
|
673
|
+
async updateSavedPreset(presetId, body) {
|
|
674
|
+
const path = await this.savedPresetsPath(presetId);
|
|
675
|
+
return await this.requestJson("PATCH", path, { json: body });
|
|
676
|
+
}
|
|
677
|
+
/** Delete a saved preset (`DELETE /v1/saved_presets/{presetId}`, `/v1/saved-presets/{id}` on Pro). */
|
|
678
|
+
async deleteSavedPreset(presetId) {
|
|
679
|
+
const path = await this.savedPresetsPath(presetId);
|
|
680
|
+
await this.requestJson("DELETE", path);
|
|
681
|
+
}
|
|
682
|
+
/** List the project's auto-tune jobs (`GET /v1/auto-tune`). */
|
|
683
|
+
async listAutoTuneJobs(params = {}) {
|
|
684
|
+
return await this.requestJson("GET", AUTO_TUNE_PATH, { params: {
|
|
685
|
+
limit: params.limit,
|
|
686
|
+
offset: params.offset
|
|
687
|
+
} });
|
|
688
|
+
}
|
|
689
|
+
/**
|
|
690
|
+
* Submit an auto-tune job (`POST /v1/auto-tune`). Sent as `multipart/form-data`:
|
|
691
|
+
* a JSON `request` part plus one binary `file` part per document.
|
|
692
|
+
*/
|
|
693
|
+
async submitAutoTune(params) {
|
|
694
|
+
if (params.files.length === 0) throw new XbergError("submitAutoTune called with no files", {
|
|
695
|
+
status: 400,
|
|
696
|
+
body: null
|
|
697
|
+
});
|
|
698
|
+
const form = new FormData();
|
|
699
|
+
form.append("request", JSON.stringify(params.request));
|
|
700
|
+
for (const file of params.files) {
|
|
701
|
+
const { blob, filename } = toBlob(file);
|
|
702
|
+
form.append("file", blob, filename);
|
|
703
|
+
}
|
|
704
|
+
return await this.requestJson("POST", AUTO_TUNE_PATH, { body: form });
|
|
705
|
+
}
|
|
706
|
+
/** Fetch the deployment's tunable knobs and OCR backends (`GET /v1/auto-tune/capabilities`). */
|
|
707
|
+
async getAutoTuneCapabilities() {
|
|
708
|
+
return await this.requestJson("GET", `${AUTO_TUNE_PATH}/capabilities`);
|
|
709
|
+
}
|
|
710
|
+
/** Fetch an auto-tune job's status (`GET /v1/auto-tune/{id}`). */
|
|
711
|
+
async getAutoTuneStatus(autoTuneJobId) {
|
|
712
|
+
return await this.requestJson("GET", this.autoTunePath(autoTuneJobId));
|
|
713
|
+
}
|
|
714
|
+
/** Delete an auto-tune job (`DELETE /v1/auto-tune/{id}`). */
|
|
715
|
+
async deleteAutoTuneJob(autoTuneJobId) {
|
|
716
|
+
await this.requestJson("DELETE", this.autoTunePath(autoTuneJobId));
|
|
717
|
+
}
|
|
718
|
+
/** Promote an auto-tune result to a named tuning profile (`POST /v1/auto-tune/{id}/promote`). */
|
|
719
|
+
async promoteAutoTuneProfile(autoTuneJobId, body) {
|
|
720
|
+
return await this.requestJson("POST", `${this.autoTunePath(autoTuneJobId)}/promote`, { json: body });
|
|
721
|
+
}
|
|
722
|
+
/** Fetch a completed auto-tune job's result (`GET /v1/auto-tune/{id}/result`). */
|
|
723
|
+
async getAutoTuneResult(autoTuneJobId) {
|
|
724
|
+
return await this.requestJson("GET", `${this.autoTunePath(autoTuneJobId)}/result`);
|
|
725
|
+
}
|
|
726
|
+
/** List the project's tuning profiles (`GET /v1/tuning-profiles`). */
|
|
727
|
+
async listTuningProfiles(params = {}) {
|
|
728
|
+
return await this.requestJson("GET", TUNING_PROFILES_PATH, { params: {
|
|
729
|
+
limit: params.limit,
|
|
730
|
+
offset: params.offset
|
|
731
|
+
} });
|
|
732
|
+
}
|
|
733
|
+
/** Fetch one tuning profile (`GET /v1/tuning-profiles/{id}`). */
|
|
734
|
+
async getTuningProfile(profileId) {
|
|
735
|
+
return await this.requestJson("GET", this.tuningProfilePath(profileId));
|
|
736
|
+
}
|
|
737
|
+
/** Delete a tuning profile (`DELETE /v1/tuning-profiles/{id}`). */
|
|
738
|
+
async deleteTuningProfile(profileId) {
|
|
739
|
+
await this.requestJson("DELETE", this.tuningProfilePath(profileId));
|
|
740
|
+
}
|
|
741
|
+
/** Pro only: fetch the instance's accepted auth methods (`GET /auth/config`). */
|
|
742
|
+
async authConfig() {
|
|
743
|
+
await this.requireTier("pro", "authConfig");
|
|
744
|
+
return this.requestJson("GET", "/auth/config");
|
|
745
|
+
}
|
|
746
|
+
/** Pro only: exchange a verified OIDC ID token for a Pro session JWT (`POST /auth/login`). */
|
|
747
|
+
async login(body) {
|
|
748
|
+
await this.requireTier("pro", "login");
|
|
749
|
+
return this.requestJson("POST", "/auth/login", { json: body });
|
|
750
|
+
}
|
|
751
|
+
/** Pro only: fetch a project's RAG config (`GET /v1/projects/{projectId}/rag-config`). */
|
|
752
|
+
async getRagConfig(projectId) {
|
|
753
|
+
await this.requireTier("pro", "getRagConfig");
|
|
754
|
+
return this.requestJson("GET", `/v1/projects/${encodeURIComponent(projectId)}/rag-config`);
|
|
755
|
+
}
|
|
756
|
+
/** Pro only: update a project's RAG config (`PUT /v1/projects/{projectId}/rag-config`). */
|
|
757
|
+
async setRagConfig(projectId, body) {
|
|
758
|
+
await this.requireTier("pro", "setRagConfig");
|
|
759
|
+
return this.requestJson("PUT", `/v1/projects/${encodeURIComponent(projectId)}/rag-config`, { json: body });
|
|
760
|
+
}
|
|
761
|
+
/** Pro only: list the caller's projects (`GET /v1/projects`). */
|
|
762
|
+
async listProjects(params = {}) {
|
|
763
|
+
await this.requireTier("pro", "listProjects");
|
|
764
|
+
return this.requestJson("GET", "/v1/projects", { params: {
|
|
765
|
+
limit: params.limit,
|
|
766
|
+
offset: params.offset
|
|
767
|
+
} });
|
|
768
|
+
}
|
|
769
|
+
/** Pro only: create a project owned by the caller (`POST /v1/projects`). */
|
|
770
|
+
async createProject(body) {
|
|
771
|
+
await this.requireTier("pro", "createProject");
|
|
772
|
+
return this.requestJson("POST", "/v1/projects", { json: body });
|
|
773
|
+
}
|
|
774
|
+
/** Pro only: list a project's API keys (`GET /v1/projects/{projectId}/api-keys`). */
|
|
775
|
+
async listApiKeys(projectId, params = {}) {
|
|
776
|
+
await this.requireTier("pro", "listApiKeys");
|
|
777
|
+
return this.requestJson("GET", `${this.projectPath(projectId)}/api-keys`, { params: {
|
|
778
|
+
limit: params.limit,
|
|
779
|
+
offset: params.offset
|
|
780
|
+
} });
|
|
781
|
+
}
|
|
782
|
+
/** Pro only: mint an API key for a project (`POST /v1/projects/{projectId}/api-keys`). */
|
|
783
|
+
async createApiKey(projectId, body) {
|
|
784
|
+
await this.requireTier("pro", "createApiKey");
|
|
785
|
+
return this.requestJson("POST", `${this.projectPath(projectId)}/api-keys`, { json: body });
|
|
786
|
+
}
|
|
787
|
+
/** Pro only: revoke an API key (`DELETE /v1/projects/{projectId}/api-keys/{keyId}`). */
|
|
788
|
+
async revokeApiKey(projectId, keyId) {
|
|
789
|
+
await this.requireTier("pro", "revokeApiKey");
|
|
790
|
+
await this.requestJson("DELETE", `${this.projectPath(projectId)}/api-keys/${encodeURIComponent(keyId)}`);
|
|
791
|
+
}
|
|
792
|
+
/** Pro only: list a project's integrations (`GET /v1/projects/{projectId}/integrations`). */
|
|
793
|
+
async listIntegrations(projectId, params = {}) {
|
|
794
|
+
await this.requireTier("pro", "listIntegrations");
|
|
795
|
+
return this.requestJson("GET", `${this.projectPath(projectId)}/integrations`, { params: {
|
|
796
|
+
limit: params.limit,
|
|
797
|
+
offset: params.offset
|
|
798
|
+
} });
|
|
799
|
+
}
|
|
800
|
+
/** Pro only: create an integration (`POST /v1/projects/{projectId}/integrations`). */
|
|
801
|
+
async createIntegration(projectId, body) {
|
|
802
|
+
await this.requireTier("pro", "createIntegration");
|
|
803
|
+
return this.requestJson("POST", `${this.projectPath(projectId)}/integrations`, { json: body });
|
|
804
|
+
}
|
|
805
|
+
/** Pro only: fetch one integration (`GET .../integrations/{integrationId}`). */
|
|
806
|
+
async getIntegration(projectId, integrationId) {
|
|
807
|
+
await this.requireTier("pro", "getIntegration");
|
|
808
|
+
return this.requestJson("GET", this.integrationPath(projectId, integrationId));
|
|
809
|
+
}
|
|
810
|
+
/** Pro only: delete an integration (`DELETE .../integrations/{integrationId}`). */
|
|
811
|
+
async deleteIntegration(projectId, integrationId) {
|
|
812
|
+
await this.requireTier("pro", "deleteIntegration");
|
|
813
|
+
await this.requestJson("DELETE", this.integrationPath(projectId, integrationId));
|
|
814
|
+
}
|
|
815
|
+
/**
|
|
816
|
+
* Pro only: begin the OAuth flow for an integration
|
|
817
|
+
* (`POST .../integrations/{integrationId}/connect`). Returns the provider
|
|
818
|
+
* authorize URL to redirect the user to.
|
|
819
|
+
*/
|
|
820
|
+
async connectIntegration(projectId, integrationId) {
|
|
821
|
+
await this.requireTier("pro", "connectIntegration");
|
|
822
|
+
return this.requestJson("POST", `${this.integrationPath(projectId, integrationId)}/connect`);
|
|
823
|
+
}
|
|
824
|
+
/** Pro only: revoke an integration's OAuth connection (`POST .../disconnect`). */
|
|
825
|
+
async disconnectIntegration(projectId, integrationId) {
|
|
826
|
+
await this.requireTier("pro", "disconnectIntegration");
|
|
827
|
+
await this.requestJson("POST", `${this.integrationPath(projectId, integrationId)}/disconnect`);
|
|
828
|
+
}
|
|
829
|
+
/** Pro only: list the documents an integration exposes (`GET .../documents`). */
|
|
830
|
+
async listIntegrationDocuments(projectId, integrationId, params = {}) {
|
|
831
|
+
await this.requireTier("pro", "listIntegrationDocuments");
|
|
832
|
+
return this.requestJson("GET", `${this.integrationPath(projectId, integrationId)}/documents`, { params: {
|
|
833
|
+
mime_types: params.mimeTypes,
|
|
834
|
+
folder_id: params.folderId,
|
|
835
|
+
max_results: params.maxResults
|
|
836
|
+
} });
|
|
837
|
+
}
|
|
838
|
+
/**
|
|
839
|
+
* Pro only: download one document from an integration
|
|
840
|
+
* (`GET .../documents/{documentId}`). The response is raw bytes, not JSON.
|
|
841
|
+
*/
|
|
842
|
+
async fetchIntegrationDocument(projectId, integrationId, documentId) {
|
|
843
|
+
await this.requireTier("pro", "fetchIntegrationDocument");
|
|
844
|
+
const path = `${this.integrationPath(projectId, integrationId)}/documents/${encodeURIComponent(documentId)}`;
|
|
845
|
+
return this.requestBytes("GET", path);
|
|
846
|
+
}
|
|
847
|
+
/**
|
|
848
|
+
* Enterprise only: fetch a document's latest version with its extraction
|
|
849
|
+
* result (`GET /v1/documents/{documentId}`). The spec declares an inline
|
|
850
|
+
* schema, so the body is returned untyped.
|
|
851
|
+
*/
|
|
852
|
+
async getDocument(documentId) {
|
|
853
|
+
await this.requireTier("enterprise", "getDocument");
|
|
854
|
+
return this.requestJson("GET", this.documentPath(documentId));
|
|
855
|
+
}
|
|
856
|
+
/** Enterprise only: list a document's versions (`GET /v1/documents/{id}/versions`). */
|
|
857
|
+
async versions(documentId) {
|
|
858
|
+
await this.requireTier("enterprise", "versions");
|
|
859
|
+
return this.requestJson("GET", `${this.documentPath(documentId)}/versions`);
|
|
860
|
+
}
|
|
861
|
+
/**
|
|
862
|
+
* Enterprise only: diff document versions (`GET /v1/documents/{id}/diff`).
|
|
863
|
+
*
|
|
864
|
+
* Computed inline when the server can afford it (`200`, {@link DiffResponse}
|
|
865
|
+
* in `result.body`), or queued for async computation when it can't (`202`,
|
|
866
|
+
* a {@link DiffAsyncAccepted} job envelope in `result.body`) — the same
|
|
867
|
+
* fallback {@link getDiffJob} polls. Narrow on `result.status`:
|
|
868
|
+
*
|
|
869
|
+
* ```ts
|
|
870
|
+
* const result = await client.diff(documentId);
|
|
871
|
+
* if (result.status === 200) {
|
|
872
|
+
* // result.body: DiffResponse
|
|
873
|
+
* } else {
|
|
874
|
+
* // result.body: DiffAsyncAccepted — poll getDiffJob(documentId, result.body.diff_job_id)
|
|
875
|
+
* }
|
|
876
|
+
* ```
|
|
877
|
+
*/
|
|
878
|
+
async diff(documentId, params) {
|
|
879
|
+
await this.requireTier("enterprise", "diff");
|
|
880
|
+
const init = params !== void 0 ? { params } : {};
|
|
881
|
+
const { status, body } = await this.requestJsonWithStatus("GET", `${this.documentPath(documentId)}/diff`, init);
|
|
882
|
+
return toDiffResult(status, body);
|
|
883
|
+
}
|
|
884
|
+
/**
|
|
885
|
+
* Enterprise only: poll a diff job (`GET /v1/documents/{id}/diff/{diffJobId}`).
|
|
886
|
+
*
|
|
887
|
+
* Returns the same {@link DiffResult} union as {@link diff}: `200` once the
|
|
888
|
+
* job has finished (`result.body`: {@link DiffResponse}), `202` while it is
|
|
889
|
+
* still pending (`result.body`: {@link DiffAsyncAccepted}). Narrow on
|
|
890
|
+
* `result.status` as shown in {@link diff}'s TSDoc.
|
|
891
|
+
*/
|
|
892
|
+
async getDiffJob(documentId, diffJobId) {
|
|
893
|
+
await this.requireTier("enterprise", "getDiffJob");
|
|
894
|
+
const path = `${this.documentPath(documentId)}/diff/${encodeURIComponent(diffJobId)}`;
|
|
895
|
+
const { status, body } = await this.requestJsonWithStatus("GET", path);
|
|
896
|
+
return toDiffResult(status, body);
|
|
897
|
+
}
|
|
898
|
+
/** Enterprise only: list the project's extraction events (`GET /v1/extractions`). */
|
|
899
|
+
async listExtractionEvents(params = {}) {
|
|
900
|
+
await this.requireTier("enterprise", "listExtractionEvents");
|
|
901
|
+
return this.requestJson("GET", EXTRACTIONS_PATH, { params: {
|
|
902
|
+
days: params.days,
|
|
903
|
+
limit: params.limit,
|
|
904
|
+
offset: params.offset
|
|
905
|
+
} });
|
|
906
|
+
}
|
|
907
|
+
/**
|
|
908
|
+
* Enterprise only: download one rendered page of an extraction job
|
|
909
|
+
* (`GET /v1/jobs/{jobId}/pages/{pageNumber}`). The response is a PNG image —
|
|
910
|
+
* raw bytes, not JSON. `pageNumber` is 1-indexed.
|
|
911
|
+
*/
|
|
912
|
+
async getJobPage(jobId, pageNumber) {
|
|
913
|
+
await this.requireTier("enterprise", "getJobPage");
|
|
914
|
+
const path = `${JOBS_PATH}/${encodeURIComponent(jobId)}/pages/${encodeURIComponent(String(pageNumber))}`;
|
|
915
|
+
return this.requestBytes("GET", path);
|
|
916
|
+
}
|
|
917
|
+
/** Enterprise only: submit text for enrichment (`POST /v1/enrich`). */
|
|
918
|
+
async submitEnrich(body) {
|
|
919
|
+
await this.requireTier("enterprise", "submitEnrich");
|
|
920
|
+
return this.requestJson("POST", ENRICH_PATH, { json: body });
|
|
921
|
+
}
|
|
922
|
+
/** Enterprise only: fetch an enrichment job's status (`GET /v1/enrich/{jobId}`). */
|
|
923
|
+
async getEnrichStatus(jobId) {
|
|
924
|
+
await this.requireTier("enterprise", "getEnrichStatus");
|
|
925
|
+
return this.requestJson("GET", `${ENRICH_PATH}/${encodeURIComponent(jobId)}`);
|
|
926
|
+
}
|
|
927
|
+
/**
|
|
928
|
+
* Enterprise only: stream a crawl job's events
|
|
929
|
+
* (`GET /v1/crawl-jobs/{crawlJobId}/events`, Server-Sent Events).
|
|
930
|
+
*
|
|
931
|
+
* Returns an `AsyncIterable` of the `kind`-discriminated {@link CrawlEvent}
|
|
932
|
+
* union; the server closes the stream after the `complete` event.
|
|
933
|
+
*
|
|
934
|
+
* ```ts
|
|
935
|
+
* for await (const event of client.streamCrawlEvents(crawlJobId)) {
|
|
936
|
+
* if (event.kind === "page") {
|
|
937
|
+
* console.log(event.url, event.status_code);
|
|
938
|
+
* }
|
|
939
|
+
* }
|
|
940
|
+
* ```
|
|
941
|
+
*
|
|
942
|
+
* Nothing is requested — not even the `/healthz` tier probe — until
|
|
943
|
+
* iteration begins, and the response body is cancelled when iteration ends:
|
|
944
|
+
* on `complete`, on `break`/`return` out of the loop, on a thrown error, or
|
|
945
|
+
* when `options.signal` aborts. A stream is idle between events by design,
|
|
946
|
+
* so unlike every other method here it carries no request timeout and is not
|
|
947
|
+
* routed through the retry engine — a retried subscription would redeliver
|
|
948
|
+
* every event the caller had already handled.
|
|
949
|
+
*/
|
|
950
|
+
streamCrawlEvents(crawlJobId, options = {}) {
|
|
951
|
+
const path = `${CRAWL_JOBS_PATH}/${encodeURIComponent(crawlJobId)}/events`;
|
|
952
|
+
const open = async () => {
|
|
953
|
+
await this.requireTier("enterprise", "streamCrawlEvents");
|
|
954
|
+
return this.openEventStream(path, options.signal);
|
|
955
|
+
};
|
|
956
|
+
return { [Symbol.asyncIterator]: () => iterateCrawlEvents(open) };
|
|
957
|
+
}
|
|
958
|
+
/** Enterprise only: request a presigned upload URL (`POST /v1/uploads/presign`). */
|
|
959
|
+
async presignUpload(body) {
|
|
960
|
+
await this.requireTier("enterprise", "presignUpload");
|
|
961
|
+
return this.requestJson("POST", "/v1/uploads/presign", { json: body });
|
|
962
|
+
}
|
|
963
|
+
/** Enterprise only: confirm a presigned upload (`POST /v1/uploads/confirm`). */
|
|
964
|
+
async confirmUpload(body) {
|
|
965
|
+
await this.requireTier("enterprise", "confirmUpload");
|
|
966
|
+
return this.requestJson("POST", "/v1/uploads/confirm", { json: body });
|
|
967
|
+
}
|
|
968
|
+
/** Enterprise only: fetch usage/metering data (`GET /v1/usage`). */
|
|
969
|
+
async usage(params) {
|
|
970
|
+
await this.requireTier("enterprise", "usage");
|
|
971
|
+
const init = params !== void 0 ? { params } : {};
|
|
972
|
+
return this.requestJson("GET", "/v1/usage", init);
|
|
973
|
+
}
|
|
974
|
+
/** Build `/v1/projects/{projectId}` with the id percent-encoded. */
|
|
975
|
+
projectPath(projectId) {
|
|
976
|
+
return `/v1/projects/${encodeURIComponent(projectId)}`;
|
|
977
|
+
}
|
|
978
|
+
/** Build `/v1/projects/{projectId}/integrations/{integrationId}`. */
|
|
979
|
+
integrationPath(projectId, integrationId) {
|
|
980
|
+
return `${this.projectPath(projectId)}/integrations/${encodeURIComponent(integrationId)}`;
|
|
981
|
+
}
|
|
982
|
+
/** Build `/v1/documents/{documentId}` with the id percent-encoded. */
|
|
983
|
+
documentPath(documentId) {
|
|
984
|
+
return `${DOCUMENTS_PATH}/${encodeURIComponent(documentId)}`;
|
|
985
|
+
}
|
|
986
|
+
/** Build `/v1/auto-tune/{id}` with the id percent-encoded. */
|
|
987
|
+
autoTunePath(autoTuneJobId) {
|
|
988
|
+
return `${AUTO_TUNE_PATH}/${encodeURIComponent(autoTuneJobId)}`;
|
|
989
|
+
}
|
|
990
|
+
/** Build `/v1/tuning-profiles/{id}` with the id percent-encoded. */
|
|
991
|
+
tuningProfilePath(profileId) {
|
|
992
|
+
return `${TUNING_PROFILES_PATH}/${encodeURIComponent(profileId)}`;
|
|
993
|
+
}
|
|
994
|
+
/**
|
|
995
|
+
* Resolve the tier and render the saved-preset path in that tier's spelling:
|
|
996
|
+
* `/v1/saved-presets` on Pro, `/v1/saved_presets` everywhere else. Pass a
|
|
997
|
+
* `presetId` for the single-preset routes.
|
|
998
|
+
*/
|
|
999
|
+
async savedPresetsPath(presetId) {
|
|
1000
|
+
const base = await this.resolveTier() === "pro" ? SAVED_PRESETS_PATH_PRO : SAVED_PRESETS_PATH_ENTERPRISE;
|
|
1001
|
+
return presetId === void 0 ? base : `${base}/${encodeURIComponent(presetId)}`;
|
|
1002
|
+
}
|
|
1003
|
+
/**
|
|
1004
|
+
* Return the effective tier — an explicit `target` if set, else probed from
|
|
1005
|
+
* `/healthz` and cached after the first *successful* probe. A probe that
|
|
1006
|
+
* fails (missing, `null`, or unrecognised `tier`) is not cached, so the
|
|
1007
|
+
* next call retries instead of being stuck with a poisoned result for the
|
|
1008
|
+
* client's lifetime. Concurrent callers share a single in-flight probe.
|
|
1009
|
+
*/
|
|
1010
|
+
async resolveTier() {
|
|
1011
|
+
if (this.target !== void 0) return this.target;
|
|
1012
|
+
if (this.probedTier !== void 0) return this.probedTier;
|
|
1013
|
+
if (this.tierProbe === void 0) this.tierProbe = this.probeTier();
|
|
1014
|
+
try {
|
|
1015
|
+
const tier = await this.tierProbe;
|
|
1016
|
+
this.probedTier = tier;
|
|
1017
|
+
return tier;
|
|
1018
|
+
} finally {
|
|
1019
|
+
this.tierProbe = void 0;
|
|
1020
|
+
}
|
|
1021
|
+
}
|
|
1022
|
+
/**
|
|
1023
|
+
* Issue the `/healthz` capability probe. Only `"enterprise"` and `"pro"` —
|
|
1024
|
+
* the tier values the specs actually declare — are accepted; anything else
|
|
1025
|
+
* (missing `tier`, `null`, or an unrecognised string) throws instead of
|
|
1026
|
+
* being treated as a usable result.
|
|
1027
|
+
*/
|
|
1028
|
+
async probeTier() {
|
|
1029
|
+
const body = await this.requestJson("GET", "/healthz");
|
|
1030
|
+
const tier = body?.tier;
|
|
1031
|
+
if (tier === "enterprise" || tier === "pro") return tier;
|
|
1032
|
+
throw new XbergError(`/healthz returned an unrecognised tier (${JSON.stringify(tier ?? null)}); expected "enterprise" or "pro"`, {
|
|
1033
|
+
status: 0,
|
|
1034
|
+
body
|
|
1035
|
+
});
|
|
1036
|
+
}
|
|
1037
|
+
/** Throw a clear error when the connected tier does not match the required one. */
|
|
1038
|
+
async requireTier(required, methodName) {
|
|
1039
|
+
const tier = await this.resolveTier();
|
|
1040
|
+
if (tier !== required) throw new XbergError(`${methodName}() is not available on the '${tier}' tier (requires the '${required}' tier)`, {
|
|
1041
|
+
status: 0,
|
|
1042
|
+
body: null
|
|
1043
|
+
});
|
|
1044
|
+
}
|
|
1045
|
+
/** Issue a request, raise on non-2xx, and decode the JSON body (undefined for empty bodies). */
|
|
1046
|
+
async requestJson(method, path, init = {}) {
|
|
1047
|
+
const { body } = await this.requestJsonWithStatus(method, path, init);
|
|
1048
|
+
return body;
|
|
1049
|
+
}
|
|
1050
|
+
/**
|
|
1051
|
+
* Like {@link requestJson}, but also returns the response's status code.
|
|
1052
|
+
* Used by endpoints whose 2xx responses carry different schemas per status
|
|
1053
|
+
* (currently only `diff`/`getDiffJob`'s `200`/`202` split).
|
|
1054
|
+
*/
|
|
1055
|
+
async requestJsonWithStatus(method, path, init = {}) {
|
|
1056
|
+
const response = await this.requestWithRetry(method, path, init);
|
|
1057
|
+
if (response.status === 204) return {
|
|
1058
|
+
status: response.status,
|
|
1059
|
+
body: void 0
|
|
1060
|
+
};
|
|
1061
|
+
const text = await response.text();
|
|
1062
|
+
const body = text.length > 0 ? JSON.parse(text) : void 0;
|
|
1063
|
+
return {
|
|
1064
|
+
status: response.status,
|
|
1065
|
+
body
|
|
1066
|
+
};
|
|
1067
|
+
}
|
|
1068
|
+
/**
|
|
1069
|
+
* Open a `text/event-stream` response, deliberately bypassing
|
|
1070
|
+
* {@link requestWithRetry}.
|
|
1071
|
+
*
|
|
1072
|
+
* Two of that method's behaviours are wrong for a subscription. Its retry
|
|
1073
|
+
* loop would re-open a partly-consumed stream and redeliver every event the
|
|
1074
|
+
* caller already handled — indistinguishable, from the caller's side, from
|
|
1075
|
+
* the server sending them twice. And its `AbortSignal.timeout(timeoutMs)`
|
|
1076
|
+
* bounds a request/response round trip, while this response stays open for
|
|
1077
|
+
* the length of a crawl and is idle between events by design; the caller's
|
|
1078
|
+
* own `signal` is the only deadline.
|
|
1079
|
+
*/
|
|
1080
|
+
async openEventStream(path, signal) {
|
|
1081
|
+
const url = `${this.baseUrl}${path}`;
|
|
1082
|
+
const requestInit = {
|
|
1083
|
+
method: "GET",
|
|
1084
|
+
headers: {
|
|
1085
|
+
...this.headers,
|
|
1086
|
+
Accept: EVENT_STREAM_MEDIA_TYPE
|
|
1087
|
+
}
|
|
1088
|
+
};
|
|
1089
|
+
if (signal !== void 0) requestInit.signal = signal;
|
|
1090
|
+
let response;
|
|
1091
|
+
try {
|
|
1092
|
+
response = await this.fetchImpl(url, requestInit);
|
|
1093
|
+
} catch (cause) {
|
|
1094
|
+
throw new XbergError(`Network error contacting ${url}`, {
|
|
1095
|
+
status: 0,
|
|
1096
|
+
body: null,
|
|
1097
|
+
cause
|
|
1098
|
+
});
|
|
1099
|
+
}
|
|
1100
|
+
if (!response.ok) {
|
|
1101
|
+
await raiseForStatus(response);
|
|
1102
|
+
throw new XbergError("Unreachable", {
|
|
1103
|
+
status: response.status,
|
|
1104
|
+
body: null
|
|
1105
|
+
});
|
|
1106
|
+
}
|
|
1107
|
+
return response;
|
|
1108
|
+
}
|
|
1109
|
+
/** Issue a request, raise on non-2xx, and return the response body as raw bytes. */
|
|
1110
|
+
async requestBytes(method, path, init = {}) {
|
|
1111
|
+
const response = await this.requestWithRetry(method, path, init);
|
|
1112
|
+
return new Uint8Array(await response.arrayBuffer());
|
|
1113
|
+
}
|
|
1114
|
+
/**
|
|
1115
|
+
* Issue a raw HTTP request with auth, timeout, query params, and retry
|
|
1116
|
+
* handling. Returns the raw (2xx) {@link Response}; non-2xx responses are
|
|
1117
|
+
* mapped to a thrown {@link XbergError} subclass.
|
|
1118
|
+
*/
|
|
1119
|
+
async requestWithRetry(method, path, init = {}) {
|
|
1120
|
+
const url = `${this.baseUrl}${path}${buildQueryString(init.params)}`;
|
|
1121
|
+
let attempt = 0;
|
|
1122
|
+
let interval = DEFAULT_RETRY_BACKOFF_BASE_MS;
|
|
1123
|
+
for (;;) {
|
|
1124
|
+
const headers = {
|
|
1125
|
+
...this.headers,
|
|
1126
|
+
...init.headers
|
|
1127
|
+
};
|
|
1128
|
+
let body = init.body;
|
|
1129
|
+
if (init.json !== void 0) {
|
|
1130
|
+
headers["Content-Type"] = "application/json";
|
|
1131
|
+
body = JSON.stringify(init.json);
|
|
1132
|
+
}
|
|
1133
|
+
const requestInit = {
|
|
1134
|
+
method,
|
|
1135
|
+
headers,
|
|
1136
|
+
signal: AbortSignal.timeout(this.timeoutMs)
|
|
1137
|
+
};
|
|
1138
|
+
if (body !== void 0) requestInit.body = body;
|
|
1139
|
+
let response;
|
|
1140
|
+
try {
|
|
1141
|
+
response = await this.fetchImpl(url, requestInit);
|
|
1142
|
+
} catch (cause) {
|
|
1143
|
+
if (attempt < this.retries) {
|
|
1144
|
+
attempt += 1;
|
|
1145
|
+
await this.sleep(interval);
|
|
1146
|
+
interval = nextBackoffInterval(interval, this.retryBackoff);
|
|
1147
|
+
continue;
|
|
1148
|
+
}
|
|
1149
|
+
throw new XbergError(`Network error contacting ${url}`, {
|
|
1150
|
+
status: 0,
|
|
1151
|
+
body: null,
|
|
1152
|
+
cause
|
|
1153
|
+
});
|
|
1154
|
+
}
|
|
1155
|
+
if (response.ok) return response;
|
|
1156
|
+
if (this.retryOn.includes(response.status) && attempt < this.retries) {
|
|
1157
|
+
attempt += 1;
|
|
1158
|
+
const retryAfter = parseRetryAfterHeader(response.headers.get("retry-after"));
|
|
1159
|
+
const wait = retryAfter !== void 0 ? retryAfter * 1e3 : interval;
|
|
1160
|
+
await this.sleep(wait);
|
|
1161
|
+
interval = nextBackoffInterval(interval, this.retryBackoff);
|
|
1162
|
+
continue;
|
|
1163
|
+
}
|
|
1164
|
+
try {
|
|
1165
|
+
await raiseForStatus(response);
|
|
1166
|
+
} catch (error) {
|
|
1167
|
+
if (error instanceof RateLimitError && error.retryAfter !== void 0 && attempt < this.retries) {
|
|
1168
|
+
attempt += 1;
|
|
1169
|
+
await this.sleep(error.retryAfter * 1e3);
|
|
1170
|
+
interval = nextBackoffInterval(interval, this.retryBackoff);
|
|
1171
|
+
continue;
|
|
1172
|
+
}
|
|
1173
|
+
throw error;
|
|
1174
|
+
}
|
|
1175
|
+
throw new XbergError("Unreachable", {
|
|
1176
|
+
status: response.status,
|
|
1177
|
+
body: null
|
|
1178
|
+
});
|
|
1179
|
+
}
|
|
1180
|
+
}
|
|
1181
|
+
};
|
|
1182
|
+
/**
|
|
1183
|
+
* Pair a diff response's status code with its body to build the
|
|
1184
|
+
* {@link DiffResult} union `diff`/`getDiffJob` return. `202` is the only
|
|
1185
|
+
* status carrying {@link DiffAsyncAccepted}; everything else (in practice
|
|
1186
|
+
* only `200`) carries the computed {@link DiffResponse}.
|
|
1187
|
+
*/
|
|
1188
|
+
function toDiffResult(status, body) {
|
|
1189
|
+
if (status === 202) return {
|
|
1190
|
+
status: 202,
|
|
1191
|
+
body
|
|
1192
|
+
};
|
|
1193
|
+
return {
|
|
1194
|
+
status: 200,
|
|
1195
|
+
body
|
|
1196
|
+
};
|
|
1197
|
+
}
|
|
1198
|
+
/**
|
|
1199
|
+
* Serialize a value with object keys sorted, so two configs that differ only in
|
|
1200
|
+
* key order compare equal when {@link appendPerFileConfigs} looks for a conflict.
|
|
1201
|
+
* Only ever used for that comparison — the value actually appended to the form is
|
|
1202
|
+
* a plain `JSON.stringify`, matching the `options` and `webhook` parts.
|
|
1203
|
+
*/
|
|
1204
|
+
function canonicalJson(value) {
|
|
1205
|
+
if (Array.isArray(value)) return `[${value.map((entry) => canonicalJson(entry)).join(",")}]`;
|
|
1206
|
+
if (typeof value === "object" && value !== null) return `{${Object.entries(value).filter(([, entry]) => entry !== void 0).sort(([left], [right]) => left < right ? -1 : left > right ? 1 : 0).map(([key, entry]) => `${JSON.stringify(key)}:${canonicalJson(entry)}`).join(",")}}`;
|
|
1207
|
+
return JSON.stringify(value) ?? "null";
|
|
1208
|
+
}
|
|
1209
|
+
/**
|
|
1210
|
+
* Append one `config-<filename>` part per document carrying a per-file override.
|
|
1211
|
+
*
|
|
1212
|
+
* Appended after the `file`, `options` and `webhook` parts, and skipped entirely
|
|
1213
|
+
* when `configs` is undefined, so a request without overrides is byte-identical
|
|
1214
|
+
* to one built before this existed.
|
|
1215
|
+
*
|
|
1216
|
+
* The part is keyed on the filename, mirroring the `document_id-<filename>`
|
|
1217
|
+
* convention. Two documents submitted under the same filename therefore have one
|
|
1218
|
+
* slot for two overrides: rather than let the later `append` win and lose the
|
|
1219
|
+
* other with no signal, that case throws and names the file.
|
|
1220
|
+
*/
|
|
1221
|
+
function appendPerFileConfigs(form, filenames, configs) {
|
|
1222
|
+
if (configs === void 0) return;
|
|
1223
|
+
if (configs.length !== filenames.length) throw new XbergError(`configs has ${configs.length} entries but ${filenames.length} files were supplied; pass exactly one entry per file (null for no override)`, {
|
|
1224
|
+
status: 400,
|
|
1225
|
+
body: null
|
|
1226
|
+
});
|
|
1227
|
+
const seen = /* @__PURE__ */ new Map();
|
|
1228
|
+
filenames.forEach((filename, index) => {
|
|
1229
|
+
const config = configs[index] ?? null;
|
|
1230
|
+
const canonical = canonicalJson(config);
|
|
1231
|
+
const prior = seen.get(filename);
|
|
1232
|
+
if (prior !== void 0 && prior !== canonical) throw new XbergError(`per-file config conflict for "${filename}": the same filename appears more than once in this batch with different configs, but a multipart request carries at most one config part per filename. Give the copies distinct filenames.`, {
|
|
1233
|
+
status: 400,
|
|
1234
|
+
body: null
|
|
1235
|
+
});
|
|
1236
|
+
if (prior === void 0 && config !== null) form.append(`config-${filename}`, JSON.stringify(config));
|
|
1237
|
+
seen.set(filename, canonical);
|
|
1238
|
+
});
|
|
1239
|
+
}
|
|
1240
|
+
/** Parse one SSE frame payload into the `kind`-discriminated {@link CrawlEvent} it names. */
|
|
1241
|
+
function parseCrawlEvent(payload) {
|
|
1242
|
+
let body;
|
|
1243
|
+
try {
|
|
1244
|
+
body = JSON.parse(payload);
|
|
1245
|
+
} catch (cause) {
|
|
1246
|
+
throw new XbergError(`Crawl event stream sent a non-JSON frame: ${payload}`, {
|
|
1247
|
+
status: 0,
|
|
1248
|
+
body: payload,
|
|
1249
|
+
cause
|
|
1250
|
+
});
|
|
1251
|
+
}
|
|
1252
|
+
const kind = body?.kind;
|
|
1253
|
+
if (typeof kind !== "string" || !CRAWL_EVENT_KINDS.has(kind)) throw new XbergError(`Crawl event stream sent an unrecognised kind (${JSON.stringify(kind ?? null)})`, {
|
|
1254
|
+
status: 0,
|
|
1255
|
+
body
|
|
1256
|
+
});
|
|
1257
|
+
return body;
|
|
1258
|
+
}
|
|
1259
|
+
/**
|
|
1260
|
+
* Drive one crawl-event subscription: open it, decode its frames, and cancel
|
|
1261
|
+
* the response body on every exit path.
|
|
1262
|
+
*
|
|
1263
|
+
* `open` is a thunk rather than an already-opened `Response` so that a caller
|
|
1264
|
+
* who never iterates opens nothing — the tier gate and the request both live
|
|
1265
|
+
* inside the generator. The `finally` runs when the consumer `break`s or
|
|
1266
|
+
* `return`s out of its `for await` as much as when the stream ends, which is
|
|
1267
|
+
* what makes the subscription cancellable without a separate handle.
|
|
1268
|
+
*/
|
|
1269
|
+
async function* iterateCrawlEvents(open) {
|
|
1270
|
+
const response = await open();
|
|
1271
|
+
if (response.body === null) throw new XbergError("Crawl event stream response carried no body", {
|
|
1272
|
+
status: response.status,
|
|
1273
|
+
body: null
|
|
1274
|
+
});
|
|
1275
|
+
const reader = response.body.getReader();
|
|
1276
|
+
const text = new TextDecoder();
|
|
1277
|
+
const frames = new EventStreamDecoder();
|
|
1278
|
+
try {
|
|
1279
|
+
for (;;) {
|
|
1280
|
+
const { done, value } = await reader.read();
|
|
1281
|
+
if (done) return;
|
|
1282
|
+
for (const payload of frames.push(text.decode(value, { stream: true }))) yield parseCrawlEvent(payload);
|
|
1283
|
+
}
|
|
1284
|
+
} finally {
|
|
1285
|
+
await reader.cancel().catch(() => void 0);
|
|
1286
|
+
}
|
|
1287
|
+
}
|
|
1288
|
+
function createClient(options = {}) {
|
|
1289
|
+
const headers = {
|
|
1290
|
+
"User-Agent": USER_AGENT,
|
|
1291
|
+
...options.headers
|
|
1292
|
+
};
|
|
1293
|
+
if (options.apiKey !== void 0) headers["Authorization"] = `Bearer ${options.apiKey}`;
|
|
1294
|
+
return createOpenApiClient({
|
|
1295
|
+
baseUrl: options.baseUrl ?? DEFAULT_ENTERPRISE_BASE_URL,
|
|
1296
|
+
headers,
|
|
1297
|
+
...options.fetch !== void 0 ? { fetch: options.fetch } : {}
|
|
1298
|
+
});
|
|
1299
|
+
}
|
|
1300
|
+
|
|
1301
|
+
//#endregion
|
|
1302
|
+
export { AuthError, NotFoundError, RateLimitError, SUCCESS_JOB_STATUSES, ServerError, TERMINAL_JOB_STATUSES, TimeoutError, ValidationError, XbergClient, XbergError, createClient };
|
|
1303
|
+
//# sourceMappingURL=index.js.map
|