@xberg-io/sdk 0.0.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.
package/dist/index.js ADDED
@@ -0,0 +1,1649 @@
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([blobBytes(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([blobBytes(wrapper.data)], { type: mimeType }),
209
+ filename: name
210
+ };
211
+ }
212
+ function blobBytes(bytes) {
213
+ return bytes.buffer instanceof ArrayBuffer ? new Uint8Array(bytes.buffer, bytes.byteOffset, bytes.byteLength) : new Uint8Array(bytes);
214
+ }
215
+ function guessMimeType(filename) {
216
+ const lower = filename.toLowerCase();
217
+ if (lower.endsWith(".csv")) return "text/csv";
218
+ if (lower.endsWith(".md")) return "text/markdown";
219
+ if (lower.endsWith(".pdf")) return "application/pdf";
220
+ if (lower.endsWith(".txt")) return "text/plain";
221
+ if (lower.endsWith(".docx")) return "application/vnd.openxmlformats-officedocument.wordprocessingml.document";
222
+ return "application/octet-stream";
223
+ }
224
+ /** Guess a display name for a file (used to populate `Job.filename`). */
225
+ function describeFile(file) {
226
+ if (typeof File !== "undefined" && file instanceof File) return file.name;
227
+ if (file instanceof Blob || file instanceof Uint8Array) return "upload.bin";
228
+ return file.name ?? "upload.bin";
229
+ }
230
+ /**
231
+ * Incremental decoder for a `text/event-stream` body, fed the decoded text of
232
+ * each network chunk.
233
+ *
234
+ * Implements the parts of the WHATWG event-stream parser this endpoint can
235
+ * exercise. A frame is terminated by a *blank line*, not by a newline: its
236
+ * payload is every `data:` field it carried, joined with `\n`. Lines opening
237
+ * with `:` are comments — the endpoint's 15s heartbeat is one — and
238
+ * `event:`/`id:`/`retry:` fields are accepted and ignored. A single space
239
+ * after a field's colon is framing, not value, so it is stripped.
240
+ *
241
+ * All of which is why this exists instead of `JSON.parse` per line: against a
242
+ * server that happens to emit one compact frame per line the naive version
243
+ * passes every test, then silently drops every multi-line payload and throws
244
+ * on the first heartbeat against a real one. Chunk boundaries fall wherever
245
+ * the network puts them, so lines are also reassembled here rather than
246
+ * assumed to arrive whole.
247
+ */
248
+ var EventStreamDecoder = class {
249
+ buffer = "";
250
+ data = [];
251
+ /** Running length of the frame being assembled, reset with `data` on dispatch. */
252
+ size = 0;
253
+ /** Consume one chunk of decoded text, returning the payload of every frame it completed. */
254
+ push(chunk) {
255
+ this.buffer += chunk;
256
+ const payloads = [];
257
+ for (;;) {
258
+ const boundary = this.nextLineBoundary();
259
+ if (boundary === void 0) {
260
+ 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`, {
261
+ status: 0,
262
+ body: null
263
+ });
264
+ return payloads;
265
+ }
266
+ const line = this.buffer.slice(0, boundary.index);
267
+ this.buffer = this.buffer.slice(boundary.index + boundary.width);
268
+ const payload = this.feed(line);
269
+ if (payload !== void 0) payloads.push(payload);
270
+ }
271
+ }
272
+ /**
273
+ * Locate the next `\n`, `\r\n` or `\r` in the buffer. A trailing `\r` is
274
+ * reported as "no boundary yet": it may be the first half of a `\r\n` the
275
+ * network split across two chunks, and treating it as a terminator there
276
+ * would dispatch a frame one line early.
277
+ */
278
+ nextLineBoundary() {
279
+ for (let index = 0; index < this.buffer.length; index += 1) {
280
+ const character = this.buffer[index];
281
+ if (character === "\n") return {
282
+ index,
283
+ width: 1
284
+ };
285
+ if (character === "\r") {
286
+ if (index === this.buffer.length - 1) return;
287
+ return {
288
+ index,
289
+ width: this.buffer[index + 1] === "\n" ? 2 : 1
290
+ };
291
+ }
292
+ }
293
+ }
294
+ /** Consume one terminator-stripped line, returning a payload if it completed a frame. */
295
+ feed(line) {
296
+ if (line === "") return this.dispatch();
297
+ if (line.startsWith(":")) return;
298
+ const colon = line.indexOf(":");
299
+ const field = colon === -1 ? line : line.slice(0, colon);
300
+ let value = colon === -1 ? "" : line.slice(colon + 1);
301
+ if (value.startsWith(" ")) value = value.slice(1);
302
+ if (field === "data") {
303
+ this.size += value.length + 1;
304
+ 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`, {
305
+ status: 0,
306
+ body: null
307
+ });
308
+ this.data.push(value);
309
+ }
310
+ }
311
+ /** Emit the buffered `data` payload, or nothing when the blank line closed no frame. */
312
+ dispatch() {
313
+ if (this.data.length === 0) return;
314
+ const payload = this.data.join("\n");
315
+ this.data = [];
316
+ this.size = 0;
317
+ return payload;
318
+ }
319
+ };
320
+ /** Encode a path identifier without allowing the HTTP client to change its route. */
321
+ function encodePathSegment(value) {
322
+ if (value === "." || value === "..") throw new XbergError("Path identifiers must not be '.' or '..'", {
323
+ status: 400,
324
+ body: null
325
+ });
326
+ return encodeURIComponent(value);
327
+ }
328
+
329
+ //#endregion
330
+ //#region src/types.ts
331
+ /**
332
+ * Terminal job statuses — once observed, polling stops and the job result is
333
+ * returned (or thrown, for `failed`/`cancelled`).
334
+ */
335
+ const TERMINAL_JOB_STATUSES = [
336
+ "completed",
337
+ "partial_success",
338
+ "failed",
339
+ "cancelled"
340
+ ];
341
+ /**
342
+ * Job statuses that indicate a successful extraction. Used to distinguish a
343
+ * "completed but check warnings" result from a hard failure.
344
+ */
345
+ const SUCCESS_JOB_STATUSES = ["completed", "partial_success"];
346
+
347
+ //#endregion
348
+ //#region src/version.ts
349
+ /**
350
+ * Package version, synced from the repo-root `VERSION` file by
351
+ * `scripts/sync-versions.py`. Used to build the `User-Agent` header. ~keep
352
+ */
353
+ const VERSION = "0.5.0";
354
+
355
+ //#endregion
356
+ //#region src/client.ts
357
+ /**
358
+ * High-level dual-target client for the Xberg Enterprise and Xberg Pro HTTP APIs.
359
+ *
360
+ * One {@link XbergClient} speaks to either product. The shared surface —
361
+ * extraction, jobs (including job results), audit, curated presets, and the RAG
362
+ * API — is written once and carries no tier gate. Tier-specific methods are
363
+ * capability-gated: they probe the connected instance (`GET /healthz`'s `tier`,
364
+ * or an explicit `target`) and throw a clear error instead of a raw 404 when
365
+ * invoked against the wrong tier.
366
+ *
367
+ * Both products authenticate identically: `Authorization: Bearer {apiKey}`.
368
+ * Enterprise defaults `baseUrl` to `https://api.xberg.io`; Pro has no default
369
+ * (its spec ships no servers block) and requires an explicit one.
370
+ *
371
+ * Enterprise splits into two binaries — the data plane `baseUrl` addresses and a
372
+ * control plane (projects, API keys, integrations) on its own origin — while Pro
373
+ * serves both from one. `controlPlaneBaseUrl` records the origin of the second
374
+ * and defaults to `baseUrl`. The backend methods use that origin and an optional
375
+ * separate `controlPlaneToken`; existing Pro methods retain their data-plane routing.
376
+ */
377
+ const USER_AGENT = `xberg-io-sdk-typescript/${VERSION}`;
378
+ const DEFAULT_TIMEOUT_MS = 3e4;
379
+ const DEFAULT_POLL_INTERVAL_MS = 1e3;
380
+ const DEFAULT_WAIT_TIMEOUT_MS = 5 * 6e4;
381
+ const DEFAULT_RETRY_STATUSES = [
382
+ 429,
383
+ 502,
384
+ 503,
385
+ 504
386
+ ];
387
+ const DEFAULT_RETRY_BACKOFF_BASE_MS = 200;
388
+ /**
389
+ * Saved presets are the one shared resource whose *path* differs per tier:
390
+ * Enterprise serves `/v1/saved_presets` (underscore), Pro `/v1/saved-presets`
391
+ * (hyphen). The request and response schemas are identical.
392
+ */
393
+ const SAVED_PRESETS_PATH_ENTERPRISE = "/v1/saved_presets";
394
+ const SAVED_PRESETS_PATH_PRO = "/v1/saved-presets";
395
+ const AUTO_TUNE_PATH = "/v1/auto-tune";
396
+ const TUNING_PROFILES_PATH = "/v1/tuning-profiles";
397
+ const ENRICH_PATH = "/v1/enrich";
398
+ const EXTRACTIONS_PATH = "/v1/extractions";
399
+ const DOCUMENTS_PATH = "/v1/documents";
400
+ const JOBS_PATH = "/v1/jobs";
401
+ const CRAWL_JOBS_PATH = "/v1/crawl-jobs";
402
+ /** Media type of the crawl-event stream, sent as `Accept` and served as `Content-Type`. */
403
+ const EVENT_STREAM_MEDIA_TYPE = "text/event-stream";
404
+ /** The `kind` values `CrawlEventV1` declares. A frame carrying anything else is rejected. */
405
+ const CRAWL_EVENT_KINDS = new Set([
406
+ "page",
407
+ "discovered",
408
+ "complete",
409
+ "error"
410
+ ]);
411
+ /**
412
+ * High-level dual-target client. Construct with `new XbergClient({ apiKey })`.
413
+ */
414
+ var XbergClient = class {
415
+ baseUrl;
416
+ /**
417
+ * Origin used by the Enterprise backend methods. Defaults to `baseUrl`.
418
+ */
419
+ controlPlaneBaseUrl;
420
+ controlPlaneToken;
421
+ headers;
422
+ fetchImpl;
423
+ timeoutMs;
424
+ retries;
425
+ retryOn;
426
+ retryBackoff;
427
+ sleep;
428
+ target;
429
+ probedTier;
430
+ /** In-flight `/healthz` probe, memoised so concurrent callers share one request (single-flight). */
431
+ tierProbe;
432
+ /** Underlying `openapi-fetch` client — exposed for advanced use. */
433
+ raw;
434
+ constructor(options = {}) {
435
+ if (options.target !== void 0) this.target = options.target;
436
+ this.baseUrl = resolveBaseUrl(options.baseUrl, options.target);
437
+ this.controlPlaneBaseUrl = resolveControlPlaneBaseUrl(options.controlPlaneBaseUrl, this.baseUrl);
438
+ this.controlPlaneToken = options.controlPlaneToken ?? options.apiKey;
439
+ this.fetchImpl = options.fetch ?? fetch;
440
+ this.timeoutMs = options.timeoutMs ?? DEFAULT_TIMEOUT_MS;
441
+ this.retries = options.retries ?? 0;
442
+ this.retryOn = options.retryOn ?? DEFAULT_RETRY_STATUSES;
443
+ this.retryBackoff = options.retryBackoff ?? "exponential";
444
+ this.sleep = options.sleep ?? defaultSleep;
445
+ this.headers = {
446
+ "User-Agent": USER_AGENT,
447
+ ...options.headers
448
+ };
449
+ if (options.apiKey !== void 0) this.headers["Authorization"] = `Bearer ${options.apiKey}`;
450
+ this.raw = createOpenApiClient({
451
+ baseUrl: this.baseUrl,
452
+ headers: this.headers,
453
+ fetch: this.fetchImpl
454
+ });
455
+ }
456
+ /** Enterprise backend `DELETE /auth/account`. */
457
+ async deleteAccount() {
458
+ return await this.backendRequest("DELETE", `/auth/account`);
459
+ }
460
+ /** Enterprise backend `GET /auth/config`. */
461
+ async getAuthConfig() {
462
+ return await this.backendRequest("GET", `/auth/config`, { backendPublic: true });
463
+ }
464
+ /** Enterprise backend `POST /auth/login`. */
465
+ async backendLogin(body) {
466
+ return await this.backendRequest("POST", `/auth/login`, {
467
+ json: body,
468
+ backendPublic: true
469
+ });
470
+ }
471
+ /** Enterprise backend `GET /healthz`. */
472
+ async healthz() {
473
+ return await this.backendRequest("GET", `/healthz`, { backendPublic: true });
474
+ }
475
+ /** Enterprise backend `GET /readyz`. */
476
+ async readyz() {
477
+ return await this.backendRequest("GET", `/readyz`, { backendPublic: true });
478
+ }
479
+ /** Enterprise backend `POST /v1/invitations/accept`. */
480
+ async acceptInvitation(body) {
481
+ return await this.backendRequest("POST", `/v1/invitations/accept`, { json: body });
482
+ }
483
+ /** Enterprise backend `GET /v1/oauth/callback`. */
484
+ async oauthCallback(params) {
485
+ const response = await this.requestWithRetry("GET", "/v1/oauth/callback", {
486
+ controlPlane: true,
487
+ backendPublic: true,
488
+ acceptRedirect: true,
489
+ params: {
490
+ code: params.code,
491
+ state: params.state
492
+ }
493
+ });
494
+ const location = response.headers.get("location");
495
+ await response.body?.cancel();
496
+ if (response.status !== 303 || location === null || location.length === 0) throw new XbergError("OAuth callback did not return a 303 Location", {
497
+ status: response.status,
498
+ body: null
499
+ });
500
+ return location;
501
+ }
502
+ /** Enterprise backend `GET /v1/projects`. */
503
+ async backendListProjects(params = {}) {
504
+ return await this.backendRequest("GET", `/v1/projects`, { params: {
505
+ limit: params.limit,
506
+ offset: params.offset
507
+ } });
508
+ }
509
+ /** Enterprise backend `POST /v1/projects`. */
510
+ async backendCreateProject(body) {
511
+ return await this.backendRequest("POST", `/v1/projects`, { json: body });
512
+ }
513
+ /** Enterprise backend `GET /v1/projects/{id}`. */
514
+ async getProject(projectId) {
515
+ return await this.backendRequest("GET", `/v1/projects/${encodePathSegment(projectId)}`);
516
+ }
517
+ /** Enterprise backend `DELETE /v1/projects/{id}`. */
518
+ async deleteProject(projectId, params = {}) {
519
+ return await this.backendRequest("DELETE", `/v1/projects/${encodePathSegment(projectId)}`, { params: { erase: params.erase === void 0 ? void 0 : String(params.erase) } });
520
+ }
521
+ /** Enterprise backend `PATCH /v1/projects/{id}`. */
522
+ async updateProject(projectId, body) {
523
+ return await this.backendRequest("PATCH", `/v1/projects/${encodePathSegment(projectId)}`, { json: body });
524
+ }
525
+ /** Enterprise backend `GET /v1/projects/{id}/analytics`. */
526
+ async getAnalytics(projectId, params) {
527
+ return await this.backendRequest("GET", `/v1/projects/${encodePathSegment(projectId)}/analytics`, { params: {
528
+ start_date: params.startDate,
529
+ end_date: params.endDate
530
+ } });
531
+ }
532
+ /** Enterprise backend `GET /v1/projects/{id}/api-keys`. */
533
+ async backendListApiKeys(projectId, params = {}) {
534
+ return await this.backendRequest("GET", `/v1/projects/${encodePathSegment(projectId)}/api-keys`, { params: {
535
+ limit: params.limit,
536
+ offset: params.offset
537
+ } });
538
+ }
539
+ /** Enterprise backend `POST /v1/projects/{id}/api-keys`. */
540
+ async backendCreateApiKey(projectId, body) {
541
+ return await this.backendRequest("POST", `/v1/projects/${encodePathSegment(projectId)}/api-keys`, { json: body });
542
+ }
543
+ /** Enterprise backend `DELETE /v1/projects/{id}/api-keys/{key_id}`. */
544
+ async backendRevokeApiKey(projectId, apiKeyId) {
545
+ return await this.backendRequest("DELETE", `/v1/projects/${encodePathSegment(projectId)}/api-keys/${encodePathSegment(apiKeyId)}`);
546
+ }
547
+ /** Enterprise backend `POST /v1/projects/{id}/api-keys/{key_id}/regenerate`. */
548
+ async regenerateApiKey(projectId, apiKeyId) {
549
+ return await this.backendRequest("POST", `/v1/projects/${encodePathSegment(projectId)}/api-keys/${encodePathSegment(apiKeyId)}/regenerate`);
550
+ }
551
+ /** Enterprise backend `GET /v1/projects/{id}/audit`. */
552
+ async listProjectAudit(projectId, params = {}) {
553
+ return await this.backendRequest("GET", `/v1/projects/${encodePathSegment(projectId)}/audit`, { params: {
554
+ action: params.action,
555
+ limit: params.limit,
556
+ offset: params.offset
557
+ } });
558
+ }
559
+ /** Enterprise backend `GET /v1/projects/{id}/billing`. */
560
+ async getBilling(projectId) {
561
+ return await this.backendRequest("GET", `/v1/projects/${encodePathSegment(projectId)}/billing`);
562
+ }
563
+ /** Enterprise backend `POST /v1/projects/{id}/billing/checkout`. */
564
+ async createCheckout(projectId) {
565
+ return await this.backendRequest("POST", `/v1/projects/${encodePathSegment(projectId)}/billing/checkout`);
566
+ }
567
+ /** Enterprise backend `POST /v1/projects/{id}/billing/portal`. */
568
+ async createPortal(projectId) {
569
+ return await this.backendRequest("POST", `/v1/projects/${encodePathSegment(projectId)}/billing/portal`);
570
+ }
571
+ /** Enterprise backend `GET /v1/projects/{id}/integrations`. */
572
+ async backendListIntegrations(projectId, params = {}) {
573
+ return await this.backendRequest("GET", `/v1/projects/${encodePathSegment(projectId)}/integrations`, { params: {
574
+ limit: params.limit,
575
+ offset: params.offset
576
+ } });
577
+ }
578
+ /** Enterprise backend `POST /v1/projects/{id}/integrations`. */
579
+ async backendCreateIntegration(projectId, body) {
580
+ return await this.backendRequest("POST", `/v1/projects/${encodePathSegment(projectId)}/integrations`, { json: body });
581
+ }
582
+ /** Enterprise backend `GET /v1/projects/{id}/integrations/{iid}`. */
583
+ async backendGetIntegration(projectId, integrationId) {
584
+ return await this.backendRequest("GET", `/v1/projects/${encodePathSegment(projectId)}/integrations/${encodePathSegment(integrationId)}`);
585
+ }
586
+ /** Enterprise backend `DELETE /v1/projects/{id}/integrations/{iid}`. */
587
+ async backendDeleteIntegration(projectId, integrationId) {
588
+ return await this.backendRequest("DELETE", `/v1/projects/${encodePathSegment(projectId)}/integrations/${encodePathSegment(integrationId)}`);
589
+ }
590
+ /** Enterprise backend `POST /v1/projects/{id}/integrations/{iid}/connect`. */
591
+ async oauthConnect(projectId, integrationId) {
592
+ return await this.backendRequest("POST", `/v1/projects/${encodePathSegment(projectId)}/integrations/${encodePathSegment(integrationId)}/connect`);
593
+ }
594
+ /** Enterprise backend `POST /v1/projects/{id}/integrations/{iid}/disconnect`. */
595
+ async backendDisconnectIntegration(projectId, integrationId) {
596
+ return await this.backendRequest("POST", `/v1/projects/${encodePathSegment(projectId)}/integrations/${encodePathSegment(integrationId)}/disconnect`);
597
+ }
598
+ /** Enterprise backend `GET /v1/projects/{id}/integrations/{iid}/documents`. */
599
+ async backendListIntegrationDocuments(projectId, integrationId, params = {}) {
600
+ return await this.backendRequest("GET", `/v1/projects/${encodePathSegment(projectId)}/integrations/${encodePathSegment(integrationId)}/documents`, { params: {
601
+ mime_types: params.mimeTypes,
602
+ folder_id: params.folderId,
603
+ max_results: params.maxResults
604
+ } });
605
+ }
606
+ /** Enterprise backend `GET /v1/projects/{id}/integrations/{iid}/documents/{doc_id}`. */
607
+ async backendFetchIntegrationDocument(projectId, integrationId, documentId) {
608
+ return await this.requestBytes("GET", `/v1/projects/${encodePathSegment(projectId)}/integrations/${encodePathSegment(integrationId)}/documents/${encodePathSegment(documentId)}`, { controlPlane: true });
609
+ }
610
+ /** Enterprise backend `GET /v1/projects/{id}/invitations`. */
611
+ async listInvitations(projectId, params = {}) {
612
+ return await this.backendRequest("GET", `/v1/projects/${encodePathSegment(projectId)}/invitations`, { params: {
613
+ limit: params.limit,
614
+ offset: params.offset
615
+ } });
616
+ }
617
+ /** Enterprise backend `POST /v1/projects/{id}/invitations`. */
618
+ async inviteUser(projectId, body) {
619
+ return await this.backendRequest("POST", `/v1/projects/${encodePathSegment(projectId)}/invitations`, { json: body });
620
+ }
621
+ /** Enterprise backend `DELETE /v1/projects/{id}/invitations/{inv_id}`. */
622
+ async revokeInvitation(projectId, invitationId) {
623
+ return await this.backendRequest("DELETE", `/v1/projects/${encodePathSegment(projectId)}/invitations/${encodePathSegment(invitationId)}`);
624
+ }
625
+ /** Enterprise backend `POST /v1/projects/{id}/leave`. */
626
+ async leaveProject(projectId) {
627
+ return await this.backendRequest("POST", `/v1/projects/${encodePathSegment(projectId)}/leave`);
628
+ }
629
+ /** Enterprise backend `GET /v1/projects/{id}/members`. */
630
+ async listMembers(projectId, params = {}) {
631
+ return await this.backendRequest("GET", `/v1/projects/${encodePathSegment(projectId)}/members`, { params: {
632
+ limit: params.limit,
633
+ offset: params.offset
634
+ } });
635
+ }
636
+ /** Enterprise backend `DELETE /v1/projects/{id}/members/{user_id}`. */
637
+ async removeMember(projectId, userId) {
638
+ return await this.backendRequest("DELETE", `/v1/projects/${encodePathSegment(projectId)}/members/${encodePathSegment(userId)}`);
639
+ }
640
+ /** Enterprise backend `PATCH /v1/projects/{id}/members/{user_id}`. */
641
+ async updateMemberRole(projectId, userId, body) {
642
+ return await this.backendRequest("PATCH", `/v1/projects/${encodePathSegment(projectId)}/members/${encodePathSegment(userId)}`, { json: body });
643
+ }
644
+ /** Enterprise backend `GET /v1/projects/{id}/rag-config`. */
645
+ async backendGetRagConfig(projectId) {
646
+ return await this.backendRequest("GET", `/v1/projects/${encodePathSegment(projectId)}/rag-config`);
647
+ }
648
+ /** Enterprise backend `PUT /v1/projects/{id}/rag-config`. */
649
+ async backendSetRagConfig(projectId, body) {
650
+ return await this.backendRequest("PUT", `/v1/projects/${encodePathSegment(projectId)}/rag-config`, { json: body });
651
+ }
652
+ /** Enterprise backend `POST /v1/projects/{id}/sandbox/extract`. */
653
+ async sandboxExtract(projectId, params) {
654
+ return await this.backendRequest("POST", `/v1/projects/${encodePathSegment(projectId)}/sandbox/extract`, { body: sandboxForm(params) });
655
+ }
656
+ /** Enterprise backend `GET /v1/projects/{id}/usage`. */
657
+ async getUsage(projectId, params) {
658
+ return await this.backendRequest("GET", `/v1/projects/${encodePathSegment(projectId)}/usage`, { params: {
659
+ start_date: params.startDate,
660
+ end_date: params.endDate
661
+ } });
662
+ }
663
+ /** Enterprise backend `GET /v1/projects/{id}/webhooks`. */
664
+ async listWebhooks(projectId, params = {}) {
665
+ return await this.backendRequest("GET", `/v1/projects/${encodePathSegment(projectId)}/webhooks`, { params: {
666
+ limit: params.limit,
667
+ offset: params.offset
668
+ } });
669
+ }
670
+ /** Enterprise backend `POST /v1/projects/{id}/webhooks`. */
671
+ async createWebhook(projectId, body) {
672
+ return await this.backendRequest("POST", `/v1/projects/${encodePathSegment(projectId)}/webhooks`, { json: body });
673
+ }
674
+ /** Enterprise backend `DELETE /v1/projects/{id}/webhooks/{wh_id}`. */
675
+ async deleteWebhook(projectId, webhookId) {
676
+ return await this.backendRequest("DELETE", `/v1/projects/${encodePathSegment(projectId)}/webhooks/${encodePathSegment(webhookId)}`);
677
+ }
678
+ /** Enterprise backend `PATCH /v1/projects/{id}/webhooks/{wh_id}`. */
679
+ async updateWebhook(projectId, webhookId, body) {
680
+ return await this.backendRequest("PATCH", `/v1/projects/${encodePathSegment(projectId)}/webhooks/${encodePathSegment(webhookId)}`, { json: body });
681
+ }
682
+ /** Enterprise backend `GET /v1/projects/{id}/webhooks/{wh_id}/deliveries`. */
683
+ async listWebhookDeliveries(projectId, webhookId, params = {}) {
684
+ return await this.backendRequest("GET", `/v1/projects/${encodePathSegment(projectId)}/webhooks/${encodePathSegment(webhookId)}/deliveries`, { params: {
685
+ limit: params.limit,
686
+ offset: params.offset
687
+ } });
688
+ }
689
+ /** Enterprise backend `POST /v1/projects/{id}/webhooks/{wh_id}/deliveries/{delivery_id}/retry`. */
690
+ async retryWebhookDelivery(projectId, webhookId, deliveryId) {
691
+ return await this.backendRequest("POST", `/v1/projects/${encodePathSegment(projectId)}/webhooks/${encodePathSegment(webhookId)}/deliveries/${encodePathSegment(deliveryId)}/retry`);
692
+ }
693
+ /** Enterprise backend `POST /v1/projects/{id}/webhooks/{wh_id}/test`. */
694
+ async testWebhook(projectId, webhookId) {
695
+ return await this.backendRequest("POST", `/v1/projects/${encodePathSegment(projectId)}/webhooks/${encodePathSegment(webhookId)}/test`);
696
+ }
697
+ /** Enterprise backend `POST /v1/sandbox/public/extract`. */
698
+ async publicSandboxExtract(params) {
699
+ return await this.backendRequest("POST", `/v1/sandbox/public/extract`, {
700
+ body: sandboxForm(params),
701
+ ...params.sandboxToken !== void 0 ? { sandboxToken: params.sandboxToken } : {},
702
+ backendPublic: true
703
+ });
704
+ }
705
+ /**
706
+ * Submit a single document for extraction. Returns the initial {@link Job}
707
+ * record (still pending — call `waitForJob` to await completion).
708
+ */
709
+ async extract(params) {
710
+ const jobs = await this.extractBatch({
711
+ files: [params.file],
712
+ ...params.documentId !== void 0 ? { documentIds: [params.documentId] } : {},
713
+ ...params.options !== void 0 ? { options: params.options } : {},
714
+ ...params.webhook !== void 0 ? { webhook: params.webhook } : {},
715
+ ...params.config !== void 0 ? { configs: [params.config] } : {}
716
+ });
717
+ const first = jobs[0];
718
+ if (first === void 0) throw new XbergError("Server did not return any job IDs", {
719
+ status: 500,
720
+ body: { jobs }
721
+ });
722
+ return first;
723
+ }
724
+ /**
725
+ * Submit multiple documents in a single multipart request. Returns one
726
+ * {@link Job} per file, in the same order.
727
+ */
728
+ async extractBatch(params) {
729
+ if (params.files.length === 0) throw new XbergError("extractBatch called with no files", {
730
+ status: 400,
731
+ body: null
732
+ });
733
+ const filenames = params.files.map(describeFile);
734
+ const documentIds = prepareDocumentLineage(filenames, params.documentIds);
735
+ if (documentIds.size > 0) await this.requireTier("enterprise", "extract document lineage");
736
+ const form = new FormData();
737
+ for (const [filename, documentId] of documentIds) form.append(`document_id-${filename}`, documentId);
738
+ for (const file of params.files) {
739
+ const { blob, filename } = toBlob(file);
740
+ form.append("file", blob, filename);
741
+ }
742
+ if (params.options !== void 0) form.append("options", JSON.stringify(params.options));
743
+ if (params.webhook !== void 0) form.append("webhook", JSON.stringify(params.webhook));
744
+ appendPerFileConfigs(form, filenames, params.configs);
745
+ const body = await this.requestJson("POST", "/v1/extract", { body: form });
746
+ const jobIds = body.job_ids ?? [];
747
+ const now = (/* @__PURE__ */ new Date()).toISOString();
748
+ return params.files.map((file, index) => {
749
+ const id = jobIds[index];
750
+ if (id === void 0) throw new XbergError(`Server returned ${jobIds.length} job IDs for ${params.files.length} files`, {
751
+ status: 500,
752
+ body
753
+ });
754
+ return {
755
+ id,
756
+ filename: describeFile(file),
757
+ status: "pending",
758
+ created_at: now
759
+ };
760
+ });
761
+ }
762
+ /** Fetch the current state of a job. */
763
+ async getJob(jobId) {
764
+ return await this.requestJson("GET", `${JOBS_PATH}/${encodePathSegment(jobId)}`);
765
+ }
766
+ /**
767
+ * Fetch a job's stored result document (`GET /v1/jobs/{id}/result`).
768
+ *
769
+ * Declared by both tiers with an identical `JobResult` envelope; the
770
+ * extracted documents live in `results`. Distinct from {@link getJob}, which
771
+ * returns the job's metadata record.
772
+ */
773
+ async getJobResult(jobId) {
774
+ return await this.requestJson("GET", `${JOBS_PATH}/${encodePathSegment(jobId)}/result`);
775
+ }
776
+ /** List jobs (paginated) via `GET /v1/jobs`. */
777
+ async listJobs(params = {}) {
778
+ return await this.requestJson("GET", JOBS_PATH, { params: {
779
+ limit: params.limit,
780
+ offset: params.offset
781
+ } });
782
+ }
783
+ /**
784
+ * Cancel a job (`DELETE /v1/jobs/{id}`). Idempotent: both a successful
785
+ * cancellation and a job that already reached a terminal status answer
786
+ * `204`.
787
+ */
788
+ async cancelJob(jobId) {
789
+ await this.requestJson("DELETE", `${JOBS_PATH}/${encodePathSegment(jobId)}`);
790
+ }
791
+ /**
792
+ * Poll {@link getJob} until the job reaches a terminal status. Throws
793
+ * {@link TimeoutError} if the wait exceeds `timeoutMs`. Throws
794
+ * {@link XbergError} if the terminal status is `failed` or `cancelled`.
795
+ */
796
+ async waitForJob(jobId, options = {}) {
797
+ const timeoutMs = options.timeoutMs ?? DEFAULT_WAIT_TIMEOUT_MS;
798
+ const initialInterval = options.pollIntervalMs ?? DEFAULT_POLL_INTERVAL_MS;
799
+ const backoff = options.backoff ?? "exponential";
800
+ const start = Date.now();
801
+ let interval = initialInterval;
802
+ for (;;) {
803
+ const job = await this.getJob(jobId);
804
+ if (TERMINAL_JOB_STATUSES.includes(job.status)) {
805
+ if (SUCCESS_JOB_STATUSES.includes(job.status)) return job;
806
+ throw new XbergError(`Job ${jobId} ended with status ${job.status}`, {
807
+ status: 200,
808
+ body: job
809
+ });
810
+ }
811
+ const remaining = timeoutMs - (Date.now() - start);
812
+ if (remaining <= 0) throw new TimeoutError(`Timed out waiting for job ${jobId} after ${timeoutMs}ms`, {
813
+ status: 408,
814
+ body: job
815
+ });
816
+ const delay = Math.min(interval, remaining);
817
+ await this.sleep(delay);
818
+ if (backoff === "exponential") interval = Math.min(interval * DEFAULT_BACKOFF_FACTOR, DEFAULT_RETRY_BACKOFF_CAP_MS);
819
+ }
820
+ }
821
+ /** Wait for many jobs in parallel. */
822
+ async waitForJobs(jobIds, options = {}) {
823
+ return await Promise.all(jobIds.map((id) => this.waitForJob(id, options)));
824
+ }
825
+ /** Convenience: extract one file and await its result. */
826
+ async extractAndWait(params) {
827
+ const extractParams = {
828
+ file: params.file,
829
+ ...params.documentId !== void 0 ? { documentId: params.documentId } : {},
830
+ ...params.options !== void 0 ? { options: params.options } : {},
831
+ ...params.webhook !== void 0 ? { webhook: params.webhook } : {},
832
+ ...params.config !== void 0 ? { config: params.config } : {}
833
+ };
834
+ const job = await this.extract(extractParams);
835
+ const waitOptions = {
836
+ ...params.timeoutMs !== void 0 ? { timeoutMs: params.timeoutMs } : {},
837
+ ...params.pollIntervalMs !== void 0 ? { pollIntervalMs: params.pollIntervalMs } : {},
838
+ ...params.backoff !== void 0 ? { backoff: params.backoff } : {}
839
+ };
840
+ return this.waitForJob(job.id, waitOptions);
841
+ }
842
+ /** Fetch audit-log entries via `GET /v1/audit`. */
843
+ async audit(params = {}) {
844
+ return await this.requestJson("GET", "/v1/audit", { params: {
845
+ action: params.action,
846
+ limit: params.limit,
847
+ offset: params.offset
848
+ } });
849
+ }
850
+ /** List the read-only curated presets (`GET /v1/presets`). */
851
+ async presets() {
852
+ return await this.requestJson("GET", "/v1/presets");
853
+ }
854
+ /** Fetch one curated preset in full (`GET /v1/presets/{id}`). */
855
+ async getPreset(presetId) {
856
+ return await this.requestJson("GET", `/v1/presets/${encodePathSegment(presetId)}`);
857
+ }
858
+ /**
859
+ * Download a preset's bundled sample file
860
+ * (`GET /v1/presets/{id}/sample/{name}`). The response is raw bytes, not
861
+ * JSON.
862
+ */
863
+ async getPresetSample(presetId, name) {
864
+ const path = `/v1/presets/${encodePathSegment(presetId)}/sample/${encodePathSegment(name)}`;
865
+ return await this.requestBytes("GET", path);
866
+ }
867
+ /** List RAG collections (`GET /v1/rag/collections`). */
868
+ async listRagCollections() {
869
+ return await this.requestJson("GET", "/v1/rag/collections");
870
+ }
871
+ /** Create a RAG collection (`POST /v1/rag/collections`). */
872
+ async createRagCollection(body) {
873
+ return await this.requestJson("POST", "/v1/rag/collections", { json: body });
874
+ }
875
+ /** Fetch a RAG collection (`GET /v1/rag/collections/{name}`). */
876
+ async getRagCollection(name) {
877
+ return await this.requestJson("GET", `/v1/rag/collections/${encodePathSegment(name)}`);
878
+ }
879
+ /** Delete a RAG collection (`DELETE /v1/rag/collections/{name}`). The spec documents a 204 with no content. */
880
+ async deleteRagCollection(name) {
881
+ await this.requestJson("DELETE", `/v1/rag/collections/${encodePathSegment(name)}`);
882
+ }
883
+ /** Add documents to a RAG collection (`POST /v1/rag/collections/{name}/documents`). */
884
+ async addRagDocuments(name, body) {
885
+ return await this.requestJson("POST", `/v1/rag/collections/${encodePathSegment(name)}/documents`, { json: body });
886
+ }
887
+ /**
888
+ * Delete documents from a RAG collection, by ID list or metadata filter
889
+ * (`DELETE /v1/rag/collections/{name}/documents`). Unlike
890
+ * {@link deleteRagCollection}, this answers `200` with a body reporting how
891
+ * many documents were removed.
892
+ */
893
+ async deleteRagDocuments(name, body) {
894
+ return await this.requestJson("DELETE", `/v1/rag/collections/${encodePathSegment(name)}/documents`, { json: body });
895
+ }
896
+ /** Reindex a RAG document (`POST /v1/rag/collections/{name}/documents/{id}/reindex`). */
897
+ async reindexRagDocument(name, documentId, body) {
898
+ const path = `/v1/rag/collections/${encodePathSegment(name)}/documents/${encodePathSegment(documentId)}/reindex`;
899
+ return await this.requestJson("POST", path, body !== void 0 ? { json: body } : {});
900
+ }
901
+ /** Retrieve chunks from a RAG collection (`POST /v1/rag/collections/{name}/retrieve`). */
902
+ async ragRetrieve(name, body) {
903
+ return await this.requestJson("POST", `/v1/rag/collections/${encodePathSegment(name)}/retrieve`, { json: body });
904
+ }
905
+ /** Kick off an embedding migration (`POST /v1/rag/collections/{name}/migrate-embeddings`). */
906
+ async migrateRagEmbeddings(name, body) {
907
+ return await this.requestJson("POST", `/v1/rag/collections/${encodePathSegment(name)}/migrate-embeddings`, { json: body });
908
+ }
909
+ /** Poll an embedding-migration job (`GET .../migrate-embeddings/{jobId}`). */
910
+ async getRagMigrationJob(name, jobId) {
911
+ const path = `/v1/rag/collections/${encodePathSegment(name)}/migrate-embeddings/${encodePathSegment(jobId)}`;
912
+ return await this.requestJson("GET", path);
913
+ }
914
+ /** Fetch a RAG job's status (`GET /v1/rag/jobs/{jobId}`). */
915
+ async getRagJob(jobId) {
916
+ return await this.requestJson("GET", `/v1/rag/jobs/${encodePathSegment(jobId)}`);
917
+ }
918
+ /** List the project's saved presets (`GET /v1/saved_presets`, `/v1/saved-presets` on Pro). */
919
+ async listSavedPresets(params = {}) {
920
+ const path = await this.savedPresetsPath();
921
+ return await this.requestJson("GET", path, { params: {
922
+ limit: params.limit,
923
+ offset: params.offset
924
+ } });
925
+ }
926
+ /** Create a saved preset (`POST /v1/saved_presets`, `/v1/saved-presets` on Pro). */
927
+ async createSavedPreset(body) {
928
+ const path = await this.savedPresetsPath();
929
+ return await this.requestJson("POST", path, { json: body });
930
+ }
931
+ /** Fetch one saved preset (`GET /v1/saved_presets/{presetId}`, `/v1/saved-presets/{id}` on Pro). */
932
+ async getSavedPreset(presetId) {
933
+ const path = await this.savedPresetsPath(presetId);
934
+ return await this.requestJson("GET", path);
935
+ }
936
+ /** Update a saved preset (`PATCH /v1/saved_presets/{presetId}`, `/v1/saved-presets/{id}` on Pro). */
937
+ async updateSavedPreset(presetId, body) {
938
+ const path = await this.savedPresetsPath(presetId);
939
+ return await this.requestJson("PATCH", path, { json: body });
940
+ }
941
+ /** Delete a saved preset (`DELETE /v1/saved_presets/{presetId}`, `/v1/saved-presets/{id}` on Pro). */
942
+ async deleteSavedPreset(presetId) {
943
+ const path = await this.savedPresetsPath(presetId);
944
+ await this.requestJson("DELETE", path);
945
+ }
946
+ /** List the project's auto-tune jobs (`GET /v1/auto-tune`). */
947
+ async listAutoTuneJobs(params = {}) {
948
+ return await this.requestJson("GET", AUTO_TUNE_PATH, { params: {
949
+ limit: params.limit,
950
+ offset: params.offset
951
+ } });
952
+ }
953
+ /**
954
+ * Submit an auto-tune job (`POST /v1/auto-tune`). Sent as `multipart/form-data`:
955
+ * a JSON `request` part plus one binary `file` part per document.
956
+ */
957
+ async submitAutoTune(params) {
958
+ if (params.files.length === 0) throw new XbergError("submitAutoTune called with no files", {
959
+ status: 400,
960
+ body: null
961
+ });
962
+ const form = new FormData();
963
+ form.append("request", JSON.stringify(params.request));
964
+ for (const file of params.files) {
965
+ const { blob, filename } = toBlob(file);
966
+ form.append("file", blob, filename);
967
+ }
968
+ return await this.requestJson("POST", AUTO_TUNE_PATH, { body: form });
969
+ }
970
+ /** Fetch the deployment's tunable knobs and OCR backends (`GET /v1/auto-tune/capabilities`). */
971
+ async getAutoTuneCapabilities() {
972
+ return await this.requestJson("GET", `${AUTO_TUNE_PATH}/capabilities`);
973
+ }
974
+ /** Fetch an auto-tune job's status (`GET /v1/auto-tune/{id}`). */
975
+ async getAutoTuneStatus(autoTuneJobId) {
976
+ return await this.requestJson("GET", this.autoTunePath(autoTuneJobId));
977
+ }
978
+ /** Delete an auto-tune job (`DELETE /v1/auto-tune/{id}`). */
979
+ async deleteAutoTuneJob(autoTuneJobId) {
980
+ await this.requestJson("DELETE", this.autoTunePath(autoTuneJobId));
981
+ }
982
+ /** Promote an auto-tune result to a named tuning profile (`POST /v1/auto-tune/{id}/promote`). */
983
+ async promoteAutoTuneProfile(autoTuneJobId, body) {
984
+ return await this.requestJson("POST", `${this.autoTunePath(autoTuneJobId)}/promote`, { json: body });
985
+ }
986
+ /** Fetch a completed auto-tune job's result (`GET /v1/auto-tune/{id}/result`). */
987
+ async getAutoTuneResult(autoTuneJobId) {
988
+ return await this.requestJson("GET", `${this.autoTunePath(autoTuneJobId)}/result`);
989
+ }
990
+ /** List the project's tuning profiles (`GET /v1/tuning-profiles`). */
991
+ async listTuningProfiles(params = {}) {
992
+ return await this.requestJson("GET", TUNING_PROFILES_PATH, { params: {
993
+ limit: params.limit,
994
+ offset: params.offset
995
+ } });
996
+ }
997
+ /** Fetch one tuning profile (`GET /v1/tuning-profiles/{id}`). */
998
+ async getTuningProfile(profileId) {
999
+ return await this.requestJson("GET", this.tuningProfilePath(profileId));
1000
+ }
1001
+ /** Delete a tuning profile (`DELETE /v1/tuning-profiles/{id}`). */
1002
+ async deleteTuningProfile(profileId) {
1003
+ await this.requestJson("DELETE", this.tuningProfilePath(profileId));
1004
+ }
1005
+ /** Pro only: fetch the instance's accepted auth methods (`GET /auth/config`). */
1006
+ async authConfig() {
1007
+ await this.requireTier("pro", "authConfig");
1008
+ return this.requestJson("GET", "/auth/config");
1009
+ }
1010
+ /** Pro only: exchange a verified OIDC ID token for a Pro session JWT (`POST /auth/login`). */
1011
+ async login(body) {
1012
+ await this.requireTier("pro", "login");
1013
+ return this.requestJson("POST", "/auth/login", { json: body });
1014
+ }
1015
+ /** Pro only: fetch a project's RAG config (`GET /v1/projects/{projectId}/rag-config`). */
1016
+ async getRagConfig(projectId) {
1017
+ await this.requireTier("pro", "getRagConfig");
1018
+ return this.requestJson("GET", `/v1/projects/${encodePathSegment(projectId)}/rag-config`);
1019
+ }
1020
+ /** Pro only: update a project's RAG config (`PUT /v1/projects/{projectId}/rag-config`). */
1021
+ async setRagConfig(projectId, body) {
1022
+ await this.requireTier("pro", "setRagConfig");
1023
+ return this.requestJson("PUT", `/v1/projects/${encodePathSegment(projectId)}/rag-config`, { json: body });
1024
+ }
1025
+ /** Pro only: list the caller's projects (`GET /v1/projects`). */
1026
+ async listProjects(params = {}) {
1027
+ await this.requireTier("pro", "listProjects");
1028
+ return this.requestJson("GET", "/v1/projects", { params: {
1029
+ limit: params.limit,
1030
+ offset: params.offset
1031
+ } });
1032
+ }
1033
+ /** Pro only: create a project owned by the caller (`POST /v1/projects`). */
1034
+ async createProject(body) {
1035
+ await this.requireTier("pro", "createProject");
1036
+ return this.requestJson("POST", "/v1/projects", { json: body });
1037
+ }
1038
+ /** Pro only: list a project's API keys (`GET /v1/projects/{projectId}/api-keys`). */
1039
+ async listApiKeys(projectId, params = {}) {
1040
+ await this.requireTier("pro", "listApiKeys");
1041
+ return this.requestJson("GET", `${this.projectPath(projectId)}/api-keys`, { params: {
1042
+ limit: params.limit,
1043
+ offset: params.offset
1044
+ } });
1045
+ }
1046
+ /** Pro only: mint an API key for a project (`POST /v1/projects/{projectId}/api-keys`). */
1047
+ async createApiKey(projectId, body) {
1048
+ await this.requireTier("pro", "createApiKey");
1049
+ return this.requestJson("POST", `${this.projectPath(projectId)}/api-keys`, { json: body });
1050
+ }
1051
+ /** Pro only: revoke an API key (`DELETE /v1/projects/{projectId}/api-keys/{keyId}`). */
1052
+ async revokeApiKey(projectId, keyId) {
1053
+ await this.requireTier("pro", "revokeApiKey");
1054
+ await this.requestJson("DELETE", `${this.projectPath(projectId)}/api-keys/${encodePathSegment(keyId)}`);
1055
+ }
1056
+ /** Pro only: list a project's integrations (`GET /v1/projects/{projectId}/integrations`). */
1057
+ async listIntegrations(projectId, params = {}) {
1058
+ await this.requireTier("pro", "listIntegrations");
1059
+ return this.requestJson("GET", `${this.projectPath(projectId)}/integrations`, { params: {
1060
+ limit: params.limit,
1061
+ offset: params.offset
1062
+ } });
1063
+ }
1064
+ /** Pro only: create an integration (`POST /v1/projects/{projectId}/integrations`). */
1065
+ async createIntegration(projectId, body) {
1066
+ await this.requireTier("pro", "createIntegration");
1067
+ return this.requestJson("POST", `${this.projectPath(projectId)}/integrations`, { json: body });
1068
+ }
1069
+ /** Pro only: fetch one integration (`GET .../integrations/{integrationId}`). */
1070
+ async getIntegration(projectId, integrationId) {
1071
+ await this.requireTier("pro", "getIntegration");
1072
+ return this.requestJson("GET", this.integrationPath(projectId, integrationId));
1073
+ }
1074
+ /** Pro only: delete an integration (`DELETE .../integrations/{integrationId}`). */
1075
+ async deleteIntegration(projectId, integrationId) {
1076
+ await this.requireTier("pro", "deleteIntegration");
1077
+ await this.requestJson("DELETE", this.integrationPath(projectId, integrationId));
1078
+ }
1079
+ /**
1080
+ * Pro only: begin the OAuth flow for an integration
1081
+ * (`POST .../integrations/{integrationId}/connect`). Returns the provider
1082
+ * authorize URL to redirect the user to.
1083
+ */
1084
+ async connectIntegration(projectId, integrationId) {
1085
+ await this.requireTier("pro", "connectIntegration");
1086
+ return this.requestJson("POST", `${this.integrationPath(projectId, integrationId)}/connect`);
1087
+ }
1088
+ /** Pro only: revoke an integration's OAuth connection (`POST .../disconnect`). */
1089
+ async disconnectIntegration(projectId, integrationId) {
1090
+ await this.requireTier("pro", "disconnectIntegration");
1091
+ await this.requestJson("POST", `${this.integrationPath(projectId, integrationId)}/disconnect`);
1092
+ }
1093
+ /** Pro only: list the documents an integration exposes (`GET .../documents`). */
1094
+ async listIntegrationDocuments(projectId, integrationId, params = {}) {
1095
+ await this.requireTier("pro", "listIntegrationDocuments");
1096
+ return this.requestJson("GET", `${this.integrationPath(projectId, integrationId)}/documents`, { params: {
1097
+ mime_types: params.mimeTypes,
1098
+ folder_id: params.folderId,
1099
+ max_results: params.maxResults
1100
+ } });
1101
+ }
1102
+ /**
1103
+ * Pro only: download one document from an integration
1104
+ * (`GET .../documents/{documentId}`). The response is raw bytes, not JSON.
1105
+ */
1106
+ async fetchIntegrationDocument(projectId, integrationId, documentId) {
1107
+ await this.requireTier("pro", "fetchIntegrationDocument");
1108
+ const path = `${this.integrationPath(projectId, integrationId)}/documents/${encodePathSegment(documentId)}`;
1109
+ return this.requestBytes("GET", path);
1110
+ }
1111
+ /**
1112
+ * Enterprise only: fetch a document's latest version with its extraction
1113
+ * result (`GET /v1/documents/{documentId}`). The spec declares an inline
1114
+ * schema, so the body is returned untyped.
1115
+ */
1116
+ async getDocument(documentId) {
1117
+ await this.requireTier("enterprise", "getDocument");
1118
+ return this.requestJson("GET", this.documentPath(documentId));
1119
+ }
1120
+ /** Enterprise only: list a document's versions (`GET /v1/documents/{id}/versions`). */
1121
+ async versions(documentId) {
1122
+ await this.requireTier("enterprise", "versions");
1123
+ return this.requestJson("GET", `${this.documentPath(documentId)}/versions`);
1124
+ }
1125
+ /**
1126
+ * Enterprise only: diff document versions (`GET /v1/documents/{id}/diff`).
1127
+ *
1128
+ * Computed inline when the server can afford it (`200`, {@link DiffResponse}
1129
+ * in `result.body`), or queued for async computation when it can't (`202`,
1130
+ * a {@link DiffAsyncAccepted} job envelope in `result.body`) — the same
1131
+ * fallback {@link getDiffJob} polls. Narrow on `result.status`:
1132
+ *
1133
+ * ```ts
1134
+ * const result = await client.diff(documentId);
1135
+ * if (result.status === 200) {
1136
+ * // result.body: DiffResponse
1137
+ * } else {
1138
+ * // result.body: DiffAsyncAccepted — poll getDiffJob(documentId, result.body.diff_job_id)
1139
+ * }
1140
+ * ```
1141
+ */
1142
+ async diff(documentId, params) {
1143
+ await this.requireTier("enterprise", "diff");
1144
+ const init = params !== void 0 ? { params } : {};
1145
+ const { status, body } = await this.requestJsonWithStatus("GET", `${this.documentPath(documentId)}/diff`, init);
1146
+ return toDiffResult(status, body);
1147
+ }
1148
+ /**
1149
+ * Enterprise only: poll a diff job (`GET /v1/documents/{id}/diff/{diffJobId}`).
1150
+ *
1151
+ * Returns the same {@link DiffResult} union as {@link diff}: `200` once the
1152
+ * job has finished (`result.body`: {@link DiffResponse}), `202` while it is
1153
+ * still pending (`result.body`: {@link DiffAsyncAccepted}). Narrow on
1154
+ * `result.status` as shown in {@link diff}'s TSDoc.
1155
+ */
1156
+ async getDiffJob(documentId, diffJobId) {
1157
+ await this.requireTier("enterprise", "getDiffJob");
1158
+ const path = `${this.documentPath(documentId)}/diff/${encodePathSegment(diffJobId)}`;
1159
+ const { status, body } = await this.requestJsonWithStatus("GET", path);
1160
+ return toDiffResult(status, body);
1161
+ }
1162
+ /** Enterprise only: list the project's extraction events (`GET /v1/extractions`). */
1163
+ async listExtractionEvents(params = {}) {
1164
+ await this.requireTier("enterprise", "listExtractionEvents");
1165
+ return this.requestJson("GET", EXTRACTIONS_PATH, { params: {
1166
+ days: params.days,
1167
+ limit: params.limit,
1168
+ offset: params.offset
1169
+ } });
1170
+ }
1171
+ /**
1172
+ * Enterprise only: download one rendered page of an extraction job
1173
+ * (`GET /v1/jobs/{jobId}/pages/{pageNumber}`). The response is a PNG image —
1174
+ * raw bytes, not JSON. `pageNumber` is 1-indexed.
1175
+ */
1176
+ async getJobPage(jobId, pageNumber) {
1177
+ await this.requireTier("enterprise", "getJobPage");
1178
+ const path = `${JOBS_PATH}/${encodePathSegment(jobId)}/pages/${encodePathSegment(String(pageNumber))}`;
1179
+ return this.requestBytes("GET", path);
1180
+ }
1181
+ /** Enterprise only: submit text for enrichment (`POST /v1/enrich`). */
1182
+ async submitEnrich(body) {
1183
+ await this.requireTier("enterprise", "submitEnrich");
1184
+ return this.requestJson("POST", ENRICH_PATH, { json: body });
1185
+ }
1186
+ /** Enterprise only: fetch an enrichment job's status (`GET /v1/enrich/{jobId}`). */
1187
+ async getEnrichStatus(jobId) {
1188
+ await this.requireTier("enterprise", "getEnrichStatus");
1189
+ return this.requestJson("GET", `${ENRICH_PATH}/${encodePathSegment(jobId)}`);
1190
+ }
1191
+ /**
1192
+ * Enterprise only: stream a crawl job's events
1193
+ * (`GET /v1/crawl-jobs/{crawlJobId}/events`, Server-Sent Events).
1194
+ *
1195
+ * Returns an `AsyncIterable` of the `kind`-discriminated {@link CrawlEvent}
1196
+ * union; the server closes the stream after the `complete` event.
1197
+ *
1198
+ * ```ts
1199
+ * for await (const event of client.streamCrawlEvents(crawlJobId)) {
1200
+ * if (event.kind === "page") {
1201
+ * console.log(event.url, event.status_code);
1202
+ * }
1203
+ * }
1204
+ * ```
1205
+ *
1206
+ * Nothing is requested — not even the `/healthz` tier probe — until
1207
+ * iteration begins, and the response body is cancelled when iteration ends:
1208
+ * on `complete`, on `break`/`return` out of the loop, on a thrown error, or
1209
+ * when `options.signal` aborts. A stream is idle between events by design,
1210
+ * so unlike every other method here it carries no request timeout and is not
1211
+ * routed through the retry engine — a retried subscription would redeliver
1212
+ * every event the caller had already handled.
1213
+ */
1214
+ streamCrawlEvents(crawlJobId, options = {}) {
1215
+ const path = `${CRAWL_JOBS_PATH}/${encodePathSegment(crawlJobId)}/events`;
1216
+ const open = async () => {
1217
+ await this.requireTier("enterprise", "streamCrawlEvents");
1218
+ return this.openEventStream(path, options.signal);
1219
+ };
1220
+ return { [Symbol.asyncIterator]: () => iterateCrawlEvents(open) };
1221
+ }
1222
+ /** Enterprise only: request a presigned upload URL (`POST /v1/uploads/presign`). */
1223
+ async presignUpload(body) {
1224
+ await this.requireTier("enterprise", "presignUpload");
1225
+ return this.requestJson("POST", "/v1/uploads/presign", { json: body });
1226
+ }
1227
+ /** Enterprise only: confirm a presigned upload (`POST /v1/uploads/confirm`). */
1228
+ async confirmUpload(body) {
1229
+ await this.requireTier("enterprise", "confirmUpload");
1230
+ return this.requestJson("POST", "/v1/uploads/confirm", { json: body });
1231
+ }
1232
+ /** Enterprise only: fetch usage/metering data (`GET /v1/usage`). */
1233
+ async usage(params) {
1234
+ await this.requireTier("enterprise", "usage");
1235
+ const init = params !== void 0 ? { params } : {};
1236
+ return this.requestJson("GET", "/v1/usage", init);
1237
+ }
1238
+ /** Build `/v1/projects/{projectId}` with the id percent-encoded. */
1239
+ projectPath(projectId) {
1240
+ return `/v1/projects/${encodePathSegment(projectId)}`;
1241
+ }
1242
+ /** Build `/v1/projects/{projectId}/integrations/{integrationId}`. */
1243
+ integrationPath(projectId, integrationId) {
1244
+ return `${this.projectPath(projectId)}/integrations/${encodePathSegment(integrationId)}`;
1245
+ }
1246
+ /** Build `/v1/documents/{documentId}` with the id percent-encoded. */
1247
+ documentPath(documentId) {
1248
+ return `${DOCUMENTS_PATH}/${encodePathSegment(documentId)}`;
1249
+ }
1250
+ /** Build `/v1/auto-tune/{id}` with the id percent-encoded. */
1251
+ autoTunePath(autoTuneJobId) {
1252
+ return `${AUTO_TUNE_PATH}/${encodePathSegment(autoTuneJobId)}`;
1253
+ }
1254
+ /** Build `/v1/tuning-profiles/{id}` with the id percent-encoded. */
1255
+ tuningProfilePath(profileId) {
1256
+ return `${TUNING_PROFILES_PATH}/${encodePathSegment(profileId)}`;
1257
+ }
1258
+ /**
1259
+ * Resolve the tier and render the saved-preset path in that tier's spelling:
1260
+ * `/v1/saved-presets` on Pro, `/v1/saved_presets` everywhere else. Pass a
1261
+ * `presetId` for the single-preset routes.
1262
+ */
1263
+ async savedPresetsPath(presetId) {
1264
+ const base = await this.resolveTier() === "pro" ? SAVED_PRESETS_PATH_PRO : SAVED_PRESETS_PATH_ENTERPRISE;
1265
+ return presetId === void 0 ? base : `${base}/${encodePathSegment(presetId)}`;
1266
+ }
1267
+ /**
1268
+ * Return the effective tier — an explicit `target` if set, else probed from
1269
+ * `/healthz` and cached after the first *successful* probe. A probe that
1270
+ * fails (missing, `null`, or unrecognised `tier`) is not cached, so the
1271
+ * next call retries instead of being stuck with a poisoned result for the
1272
+ * client's lifetime. Concurrent callers share a single in-flight probe.
1273
+ */
1274
+ async resolveTier() {
1275
+ if (this.target !== void 0) return this.target;
1276
+ if (this.probedTier !== void 0) return this.probedTier;
1277
+ if (this.tierProbe === void 0) this.tierProbe = this.probeTier();
1278
+ try {
1279
+ const tier = await this.tierProbe;
1280
+ this.probedTier = tier;
1281
+ return tier;
1282
+ } finally {
1283
+ this.tierProbe = void 0;
1284
+ }
1285
+ }
1286
+ /**
1287
+ * Issue the `/healthz` capability probe. Only `"enterprise"` and `"pro"` —
1288
+ * the tier values the specs actually declare — are accepted; anything else
1289
+ * (missing `tier`, `null`, or an unrecognised string) throws instead of
1290
+ * being treated as a usable result.
1291
+ */
1292
+ async probeTier() {
1293
+ const body = await this.requestJson("GET", "/healthz");
1294
+ const tier = body?.tier;
1295
+ if (tier === "enterprise" || tier === "pro") return tier;
1296
+ throw new XbergError(`/healthz returned an unrecognised tier (${JSON.stringify(tier ?? null)}); expected "enterprise" or "pro"`, {
1297
+ status: 0,
1298
+ body
1299
+ });
1300
+ }
1301
+ /** Throw a clear error when the connected tier does not match the required one. */
1302
+ async requireTier(required, methodName) {
1303
+ const tier = await this.resolveTier();
1304
+ if (tier !== required) throw new XbergError(`${methodName}() is not available on the '${tier}' tier (requires the '${required}' tier)`, {
1305
+ status: 0,
1306
+ body: null
1307
+ });
1308
+ }
1309
+ backendRequest(method, path, init = {}) {
1310
+ return this.requestJson(method, path, {
1311
+ ...init,
1312
+ controlPlane: true
1313
+ });
1314
+ }
1315
+ backendHeaders(init) {
1316
+ const headers = new Headers({
1317
+ ...this.headers,
1318
+ ...init.headers
1319
+ });
1320
+ for (const name of [
1321
+ "authorization",
1322
+ "proxy-authorization",
1323
+ "cookie",
1324
+ "x-api-key"
1325
+ ]) headers.delete(name);
1326
+ const token = init.backendPublic ? init.sandboxToken : this.controlPlaneToken;
1327
+ if (token !== void 0 && token.length > 0) headers.set("Authorization", `Bearer ${token}`);
1328
+ if (init.body instanceof FormData || init.json !== void 0) headers.delete("content-type");
1329
+ return Object.fromEntries(headers);
1330
+ }
1331
+ /** Issue a request, raise on non-2xx, and decode the JSON body (undefined for empty bodies). */
1332
+ async requestJson(method, path, init = {}) {
1333
+ const { body } = await this.requestJsonWithStatus(method, path, init);
1334
+ return body;
1335
+ }
1336
+ /**
1337
+ * Like {@link requestJson}, but also returns the response's status code.
1338
+ * Used by endpoints whose 2xx responses carry different schemas per status
1339
+ * (currently only `diff`/`getDiffJob`'s `200`/`202` split).
1340
+ */
1341
+ async requestJsonWithStatus(method, path, init = {}) {
1342
+ const response = await this.requestWithRetry(method, path, init);
1343
+ if (response.status === 204) return {
1344
+ status: response.status,
1345
+ body: void 0
1346
+ };
1347
+ const text = await response.text();
1348
+ const body = text.length > 0 ? JSON.parse(text) : void 0;
1349
+ return {
1350
+ status: response.status,
1351
+ body
1352
+ };
1353
+ }
1354
+ /**
1355
+ * Open a `text/event-stream` response, deliberately bypassing
1356
+ * {@link requestWithRetry}.
1357
+ *
1358
+ * Two of that method's behaviours are wrong for a subscription. Its retry
1359
+ * loop would re-open a partly-consumed stream and redeliver every event the
1360
+ * caller already handled — indistinguishable, from the caller's side, from
1361
+ * the server sending them twice. And its `AbortSignal.timeout(timeoutMs)`
1362
+ * bounds a request/response round trip, while this response stays open for
1363
+ * the length of a crawl and is idle between events by design; the caller's
1364
+ * own `signal` is the only deadline.
1365
+ */
1366
+ async openEventStream(path, signal) {
1367
+ const url = `${this.baseUrl}${path}`;
1368
+ const requestInit = {
1369
+ method: "GET",
1370
+ headers: {
1371
+ ...this.headers,
1372
+ Accept: EVENT_STREAM_MEDIA_TYPE
1373
+ }
1374
+ };
1375
+ if (signal !== void 0) requestInit.signal = signal;
1376
+ let response;
1377
+ try {
1378
+ response = await this.fetchImpl(url, requestInit);
1379
+ } catch (cause) {
1380
+ throw new XbergError(`Network error contacting ${url}`, {
1381
+ status: 0,
1382
+ body: null,
1383
+ cause
1384
+ });
1385
+ }
1386
+ if (!response.ok) {
1387
+ await raiseForStatus(response);
1388
+ throw new XbergError("Unreachable", {
1389
+ status: response.status,
1390
+ body: null
1391
+ });
1392
+ }
1393
+ return response;
1394
+ }
1395
+ /** Issue a request, raise on non-2xx, and return the response body as raw bytes. */
1396
+ async requestBytes(method, path, init = {}) {
1397
+ const response = await this.requestWithRetry(method, path, init);
1398
+ return new Uint8Array(await response.arrayBuffer());
1399
+ }
1400
+ /**
1401
+ * Issue a raw HTTP request with auth, timeout, query params, and retry
1402
+ * handling. Returns the raw (2xx) {@link Response}; non-2xx responses are
1403
+ * mapped to a thrown {@link XbergError} subclass.
1404
+ */
1405
+ prepareRequest(method, init) {
1406
+ const headers = init.controlPlane ? this.backendHeaders(init) : {
1407
+ ...this.headers,
1408
+ ...init.headers
1409
+ };
1410
+ let body = init.body;
1411
+ if (init.json !== void 0) {
1412
+ headers["Content-Type"] = "application/json";
1413
+ body = JSON.stringify(init.json);
1414
+ }
1415
+ const requestInit = {
1416
+ method,
1417
+ headers,
1418
+ signal: AbortSignal.timeout(this.timeoutMs),
1419
+ ...init.controlPlane ? {
1420
+ credentials: "omit",
1421
+ redirect: "manual"
1422
+ } : {}
1423
+ };
1424
+ if (body !== void 0) requestInit.body = body;
1425
+ return requestInit;
1426
+ }
1427
+ async requestWithRetry(method, path, init = {}) {
1428
+ if (init.controlPlane && (this.target ?? this.probedTier) === "pro") throw new XbergError("Enterprise backend methods are not available on the 'pro' tier", {
1429
+ status: 0,
1430
+ body: null
1431
+ });
1432
+ const url = `${init.controlPlane ? this.controlPlaneBaseUrl : this.baseUrl}${path}${buildQueryString(init.params)}`;
1433
+ let attempt = 0;
1434
+ let interval = DEFAULT_RETRY_BACKOFF_BASE_MS;
1435
+ for (;;) {
1436
+ const requestInit = this.prepareRequest(method, init);
1437
+ let response;
1438
+ try {
1439
+ response = await this.fetchImpl(url, requestInit);
1440
+ } catch (cause) {
1441
+ if (attempt < this.retries) {
1442
+ attempt += 1;
1443
+ await this.sleep(interval);
1444
+ interval = nextBackoffInterval(interval, this.retryBackoff);
1445
+ continue;
1446
+ }
1447
+ if (init.controlPlane) throw new XbergError(`Network error contacting Enterprise control plane (${method} ${path})`, {
1448
+ status: 0,
1449
+ body: null
1450
+ });
1451
+ throw new XbergError(`Network error contacting ${url}`, {
1452
+ status: 0,
1453
+ body: null,
1454
+ cause
1455
+ });
1456
+ }
1457
+ if (response.ok || init.acceptRedirect && response.status === 303) return response;
1458
+ if (this.retryOn.includes(response.status) && attempt < this.retries) {
1459
+ attempt += 1;
1460
+ const retryAfter = parseRetryAfterHeader(response.headers.get("retry-after"));
1461
+ const wait = retryAfter !== void 0 ? retryAfter * 1e3 : interval;
1462
+ await this.sleep(wait);
1463
+ interval = nextBackoffInterval(interval, this.retryBackoff);
1464
+ continue;
1465
+ }
1466
+ try {
1467
+ await raiseForStatus(response);
1468
+ } catch (error) {
1469
+ if (error instanceof RateLimitError && error.retryAfter !== void 0 && attempt < this.retries) {
1470
+ attempt += 1;
1471
+ await this.sleep(error.retryAfter * 1e3);
1472
+ interval = nextBackoffInterval(interval, this.retryBackoff);
1473
+ continue;
1474
+ }
1475
+ throw error;
1476
+ }
1477
+ throw new XbergError("Unreachable", {
1478
+ status: response.status,
1479
+ body: null
1480
+ });
1481
+ }
1482
+ }
1483
+ };
1484
+ /**
1485
+ * Pair a diff response's status code with its body to build the
1486
+ * {@link DiffResult} union `diff`/`getDiffJob` return. `202` is the only
1487
+ * status carrying {@link DiffAsyncAccepted}; everything else (in practice
1488
+ * only `200`) carries the computed {@link DiffResponse}.
1489
+ */
1490
+ function toDiffResult(status, body) {
1491
+ if (status === 202) return {
1492
+ status: 202,
1493
+ body
1494
+ };
1495
+ return {
1496
+ status: 200,
1497
+ body
1498
+ };
1499
+ }
1500
+ /**
1501
+ * Serialize a value with object keys sorted, so two configs that differ only in
1502
+ * key order compare equal when {@link appendPerFileConfigs} looks for a conflict.
1503
+ * Only ever used for that comparison — the value actually appended to the form is
1504
+ * a plain `JSON.stringify`, matching the `options` and `webhook` parts.
1505
+ */
1506
+ function canonicalJson(value) {
1507
+ if (Array.isArray(value)) return `[${value.map((entry) => canonicalJson(entry)).join(",")}]`;
1508
+ 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(",")}}`;
1509
+ return JSON.stringify(value) ?? "null";
1510
+ }
1511
+ /**
1512
+ * Append one `config-<filename>` part per document carrying a per-file override.
1513
+ *
1514
+ * Appended after the `file`, `options` and `webhook` parts, and skipped entirely
1515
+ * when `configs` is undefined, so a request without overrides is byte-identical
1516
+ * to one built before this existed.
1517
+ *
1518
+ * The part is keyed on the filename, mirroring the `document_id-<filename>`
1519
+ * convention. Two documents submitted under the same filename therefore have one
1520
+ * slot for two overrides: rather than let the later `append` win and lose the
1521
+ * other with no signal, that case throws and names the file.
1522
+ */
1523
+ function appendPerFileConfigs(form, filenames, configs) {
1524
+ if (configs === void 0) return;
1525
+ 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)`, {
1526
+ status: 400,
1527
+ body: null
1528
+ });
1529
+ const seen = /* @__PURE__ */ new Map();
1530
+ filenames.forEach((filename, index) => {
1531
+ const config = configs[index] ?? null;
1532
+ const canonical = canonicalJson(config);
1533
+ const prior = seen.get(filename);
1534
+ 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.`, {
1535
+ status: 400,
1536
+ body: null
1537
+ });
1538
+ if (prior === void 0 && config !== null) form.append(`config-${filename}`, JSON.stringify(config));
1539
+ seen.set(filename, canonical);
1540
+ });
1541
+ }
1542
+ /** Parse one SSE frame payload into the `kind`-discriminated {@link CrawlEvent} it names. */
1543
+ function parseCrawlEvent(payload) {
1544
+ let body;
1545
+ try {
1546
+ body = JSON.parse(payload);
1547
+ } catch (cause) {
1548
+ throw new XbergError(`Crawl event stream sent a non-JSON frame: ${payload}`, {
1549
+ status: 0,
1550
+ body: payload,
1551
+ cause
1552
+ });
1553
+ }
1554
+ const kind = body?.kind;
1555
+ if (typeof kind !== "string" || !CRAWL_EVENT_KINDS.has(kind)) throw new XbergError(`Crawl event stream sent an unrecognised kind (${JSON.stringify(kind ?? null)})`, {
1556
+ status: 0,
1557
+ body
1558
+ });
1559
+ return body;
1560
+ }
1561
+ /**
1562
+ * Drive one crawl-event subscription: open it, decode its frames, and cancel
1563
+ * the response body on every exit path.
1564
+ *
1565
+ * `open` is a thunk rather than an already-opened `Response` so that a caller
1566
+ * who never iterates opens nothing — the tier gate and the request both live
1567
+ * inside the generator. The `finally` runs when the consumer `break`s or
1568
+ * `return`s out of its `for await` as much as when the stream ends, which is
1569
+ * what makes the subscription cancellable without a separate handle.
1570
+ */
1571
+ async function* iterateCrawlEvents(open) {
1572
+ const response = await open();
1573
+ if (response.body === null) throw new XbergError("Crawl event stream response carried no body", {
1574
+ status: response.status,
1575
+ body: null
1576
+ });
1577
+ const reader = response.body.getReader();
1578
+ const text = new TextDecoder();
1579
+ const frames = new EventStreamDecoder();
1580
+ try {
1581
+ for (;;) {
1582
+ const { done, value } = await reader.read();
1583
+ if (done) return;
1584
+ for (const payload of frames.push(text.decode(value, { stream: true }))) yield parseCrawlEvent(payload);
1585
+ }
1586
+ } finally {
1587
+ await reader.cancel().catch(() => void 0);
1588
+ }
1589
+ }
1590
+ function createClient(options = {}) {
1591
+ const headers = {
1592
+ "User-Agent": USER_AGENT,
1593
+ ...options.headers
1594
+ };
1595
+ if (options.apiKey !== void 0) headers["Authorization"] = `Bearer ${options.apiKey}`;
1596
+ return createOpenApiClient({
1597
+ baseUrl: options.baseUrl ?? DEFAULT_ENTERPRISE_BASE_URL,
1598
+ headers,
1599
+ ...options.fetch !== void 0 ? { fetch: options.fetch } : {}
1600
+ });
1601
+ }
1602
+ function sandboxForm(params) {
1603
+ if (params.file === void 0 && !(params.mode === "web" && params.url !== void 0 && params.url.length > 0)) throw new XbergError("Sandbox extraction requires a file or web mode with a URL", {
1604
+ status: 400,
1605
+ body: null
1606
+ });
1607
+ const form = new FormData();
1608
+ if (params.file !== void 0) {
1609
+ const { blob, filename } = toBlob(params.file);
1610
+ form.append("file", blob, filename);
1611
+ }
1612
+ for (const name of [
1613
+ "mode",
1614
+ "preset",
1615
+ "url"
1616
+ ]) {
1617
+ const value = params[name];
1618
+ if (value !== void 0) form.append(name, value);
1619
+ }
1620
+ return form;
1621
+ }
1622
+ function prepareDocumentLineage(filenames, ids) {
1623
+ const fields = /* @__PURE__ */ new Map();
1624
+ if (ids === void 0) return fields;
1625
+ if (ids.length !== filenames.length) throw new XbergError("documentIds must contain one entry per file", {
1626
+ status: 400,
1627
+ body: null
1628
+ });
1629
+ const seen = /* @__PURE__ */ new Map();
1630
+ for (const [index, filename] of filenames.entries()) {
1631
+ const id = ids[index];
1632
+ if (id !== null && (typeof id !== "string" || !/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(id))) throw new XbergError("documentIds must contain UUID strings or null", {
1633
+ status: 400,
1634
+ body: null
1635
+ });
1636
+ const canonical = id === null ? null : id.toLowerCase();
1637
+ if (seen.has(filename) && seen.get(filename) !== canonical) throw new XbergError("Conflicting document IDs for the same filename", {
1638
+ status: 400,
1639
+ body: null
1640
+ });
1641
+ seen.set(filename, canonical);
1642
+ if (canonical !== null) fields.set(filename, canonical);
1643
+ }
1644
+ return fields;
1645
+ }
1646
+
1647
+ //#endregion
1648
+ export { AuthError, NotFoundError, RateLimitError, SUCCESS_JOB_STATUSES, ServerError, TERMINAL_JOB_STATUSES, TimeoutError, ValidationError, XbergClient, XbergError, createClient };
1649
+ //# sourceMappingURL=index.js.map